diff --git a/CODE-FORMATTING-STYLE.txt b/CODE-FORMATTING-STYLE.txt index ff778878..babc2a20 100644 --- a/CODE-FORMATTING-STYLE.txt +++ b/CODE-FORMATTING-STYLE.txt @@ -1,57 +1,56 @@ When writing code for Kile, it should be formatted as illustrated through the following code snippets: unsigned int Manager::findFreeID(const QMap& takenIDMap, unsigned int maxID) { - if(takenIDMap.size() == 0) { - return 0; - } - // maxID should have a real meaning now - for(unsigned int i = 0; i < maxID; ++i) { - if(takenIDMap.find(i) == takenIDMap.end()) { - return i; - } - } - return (maxID + 1); + if(takenIDMap.size() == 0) { + return 0; + } + // maxID should have a real meaning now + for(unsigned int i = 0; i < maxID; ++i) { + if(takenIDMap.find(i) == takenIDMap.end()) { + return i; + } + } + return (maxID + 1); } void Manager::writeIDs() { - KConfigGroup configGroup = m_config->group("Scripts"); - //delete old entries - QList idList = configGroup.readEntry("IDs", QList()); - for(QList::iterator i = idList.begin(); i != idList.end(); ++i) { - configGroup.deleteEntry("Script" + QString::number(*i)); - } - - //write new ones - idList.clear(); - for(QMap::iterator i = m_idScriptMap.begin(); i != m_idScriptMap.end(); ++i) { - unsigned int id = i.key(); - idList.push_back(id); - configGroup.writePathEntry("Script" + QString::number(id), (*i)->getFileName()); - } - configGroup.writeEntry("IDs", idList); + KConfigGroup configGroup = m_config->group("Scripts"); + //delete old entries + QList idList = configGroup.readEntry("IDs", QList()); + for(QList::iterator i = idList.begin(); i != idList.end(); ++i) { + configGroup.deleteEntry("Script" + QString::number(*i)); + } + //write new ones + idList.clear(); + for(QMap::iterator i = m_idScriptMap.begin(); i != m_idScriptMap.end(); ++i) { + unsigned int id = i.key(); + idList.push_back(id); + configGroup.writePathEntry("Script" + QString::number(id), (*i)->getFileName()); + } + configGroup.writeEntry("IDs", idList); } -QPair pair = m_kileInfo->editorKeySequenceManager()->checkSequence(value, oldSequence); +QPair pair = m_kileInfo->editorKeySequenceManager()->checkSequence(newSequence, oldSequence); if(pair.first == 0) { - m_kileInfo->scriptManager()->setEditorKeySequence(script, value); + m_kileInfo->scriptManager()->setEditorKeySequence(script, newType, newSequence); } KileEditorKeySequence::Action *action = m_kileInfo->editorKeySequenceManager()->getAction(pair.second); QString description = (!action) ? QString() : action->getDescription(); switch(pair.first) { - case 1: - <...> - return; - case 2: - <...> - return; - case 3: - <...> - return; +case 1: + <...> + return; +case 2: + <...> + return; +case 3: + <...> + return; } -The key points are that tabs are used for indentation, opening curly brackets follow on the same line (except +The key points are that 4 spaces are used for indentation, opening curly brackets follow on the same line (except for function declarations), and function arguments are separated by spaces. -Please feel free to ask on the kile-devel mailing list for further explanations! \ No newline at end of file +Please feel free to ask on the kile-devel mailing list for further explanations! diff --git a/src/abbreviationmanager.cpp b/src/abbreviationmanager.cpp index 853d4372..77c7a2da 100644 --- a/src/abbreviationmanager.cpp +++ b/src/abbreviationmanager.cpp @@ -1,179 +1,179 @@ /******************************************************************************** * Copyright (C) 2007 by Holger Danielsson (holger.danielsson@versanet.de) * * 2008 - 2010 by Michel Ludwig (michel.ludwig@kdemail.net) * *********************************************************************************/ /************************************************************************** * * * 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. * * * ***************************************************************************/ #include "abbreviationmanager.h" #include #include #include "codecompletion.h" #include "kileinfo.h" namespace KileAbbreviation { Manager::Manager(KileInfo* kileInfo, QObject *parent) : QObject(parent), m_kileInfo(kileInfo), m_abbreviationsDirty(false) { - setObjectName("KileAbbreviation::Manager"); - m_localAbbreviationFile = QStandardPaths::writableLocation(QStandardPaths::DataLocation) + '/' + "complete/abbreviation/" + "kile-abbrevs.cwl"; - QDir testDir(m_localAbbreviationFile); - if (!testDir.exists()) { - testDir.mkpath(m_localAbbreviationFile); - } + setObjectName("KileAbbreviation::Manager"); + m_localAbbreviationFile = QStandardPaths::writableLocation(QStandardPaths::DataLocation) + '/' + "complete/abbreviation/" + "kile-abbrevs.cwl"; + QDir testDir(m_localAbbreviationFile); + if (!testDir.exists()) { + testDir.mkpath(m_localAbbreviationFile); + } } Manager::~Manager() { } const AbbreviationMap& Manager::getAbbreviationMap() { - return m_abbreviationMap; + return m_abbreviationMap; } void Manager::updateLocalAbbreviation(const QString& text, const QString& replacement) { - if(text.isEmpty() || replacement.isEmpty()) { - return; - } - AbbreviationMap::iterator it = m_abbreviationMap.find(text); - if(it != m_abbreviationMap.end()) { - StringBooleanPair pair = it.value(); - if(pair.first == replacement) { - return; - } - m_abbreviationMap.erase(it); - } - m_abbreviationMap[text] = createLocalAbbreviationPair(replacement); - m_abbreviationsDirty = true; - emit(abbreviationsChanged()); + if(text.isEmpty() || replacement.isEmpty()) { + return; + } + AbbreviationMap::iterator it = m_abbreviationMap.find(text); + if(it != m_abbreviationMap.end()) { + StringBooleanPair pair = it.value(); + if(pair.first == replacement) { + return; + } + m_abbreviationMap.erase(it); + } + m_abbreviationMap[text] = createLocalAbbreviationPair(replacement); + m_abbreviationsDirty = true; + emit(abbreviationsChanged()); } void Manager::removeLocalAbbreviation(const QString& text) { - AbbreviationMap::iterator it = m_abbreviationMap.find(text); - if(it == m_abbreviationMap.end()) { - return; - } - StringBooleanPair pair = it.value(); - if(isLocalAbbreviation(pair)) { - m_abbreviationMap.erase(it); - m_abbreviationsDirty = true; - } - emit(abbreviationsChanged()); + AbbreviationMap::iterator it = m_abbreviationMap.find(text); + if(it == m_abbreviationMap.end()) { + return; + } + StringBooleanPair pair = it.value(); + if(isLocalAbbreviation(pair)) { + m_abbreviationMap.erase(it); + m_abbreviationsDirty = true; + } + emit(abbreviationsChanged()); } void Manager::readAbbreviationFiles() { - if(m_abbreviationsDirty) { - saveLocalAbbreviations(); - } - m_abbreviationMap.clear(); - QStringList list = m_kileInfo->codeCompletionManager()->readCWLFiles(KileConfig::completeAbbrev(), "abbreviation"); - addAbbreviationListToMap(list, true); - - // read local wordlist - list = m_kileInfo->codeCompletionManager()->readCWLFile(m_localAbbreviationFile, true); - addAbbreviationListToMap(list, false); - - emit(abbreviationsChanged()); + if(m_abbreviationsDirty) { + saveLocalAbbreviations(); + } + m_abbreviationMap.clear(); + QStringList list = m_kileInfo->codeCompletionManager()->readCWLFiles(KileConfig::completeAbbrev(), "abbreviation"); + addAbbreviationListToMap(list, true); + + // read local wordlist + list = m_kileInfo->codeCompletionManager()->readCWLFile(m_localAbbreviationFile, true); + addAbbreviationListToMap(list, false); + + emit(abbreviationsChanged()); } void Manager::saveLocalAbbreviations() { - if(!m_abbreviationsDirty) { - return; - } - - KILE_DEBUG_MAIN; - // create the file - QFile abbreviationFile(m_localAbbreviationFile); - if(!abbreviationFile.open(QIODevice::WriteOnly)) { - KMessageBox::error(m_kileInfo->mainWindow(), i18n("Could not save the local abbreviation list.\nError code %1.", QString::number(abbreviationFile.error())), - i18n("Saving Problem")); - return; - } - - QTextStream stream(&abbreviationFile); - stream << "# abbreviation mode: editable abbreviations\n"; - - //QTextCodec *codec = QTextCodec::codecForName(m_ki->activeTextDocument()->encoding().ascii()); - // stream.setCodec(codec); - - for(AbbreviationMap::iterator i = m_abbreviationMap.begin(); - i != m_abbreviationMap.end(); ++i) { - StringBooleanPair pair = i.value(); - if(!pair.second) { - stream << QString(i.key()).replace('=', "\\=") - << '=' << pair.first << '\n'; - } - } - abbreviationFile.close(); - - m_abbreviationsDirty = false; + if(!m_abbreviationsDirty) { + return; + } + + KILE_DEBUG_MAIN; + // create the file + QFile abbreviationFile(m_localAbbreviationFile); + if(!abbreviationFile.open(QIODevice::WriteOnly)) { + KMessageBox::error(m_kileInfo->mainWindow(), i18n("Could not save the local abbreviation list.\nError code %1.", QString::number(abbreviationFile.error())), + i18n("Saving Problem")); + return; + } + + QTextStream stream(&abbreviationFile); + stream << "# abbreviation mode: editable abbreviations\n"; + + //QTextCodec *codec = QTextCodec::codecForName(m_ki->activeTextDocument()->encoding().ascii()); + // stream.setCodec(codec); + + for(AbbreviationMap::iterator i = m_abbreviationMap.begin(); + i != m_abbreviationMap.end(); ++i) { + StringBooleanPair pair = i.value(); + if(!pair.second) { + stream << QString(i.key()).replace('=', "\\=") + << '=' << pair.first << '\n'; + } + } + abbreviationFile.close(); + + m_abbreviationsDirty = false; } void Manager::addAbbreviationListToMap(const QStringList& list, bool global) { - // a '=' symbol in the left-hand side is encoded by '\=' - for(QStringList::const_iterator i = list.begin(); i != list.end(); ++i) { - QString entry = *i; - int delimiter = entry.indexOf(QRegExp("[^\\\\]=")); - if(delimiter < 0) { - continue; - } - QString left = entry.left(delimiter + 1); // [^\\\\]= has length 2. - left.replace("\\=", "="); - QString right = entry.mid(delimiter + 2); // [^\\\\]= has length 2. - if(right.isEmpty()) { - continue; - } - m_abbreviationMap[left] = StringBooleanPair(right, global); - } + // a '=' symbol in the left-hand side is encoded by '\=' + for(QStringList::const_iterator i = list.begin(); i != list.end(); ++i) { + QString entry = *i; + int delimiter = entry.indexOf(QRegExp("[^\\\\]=")); + if(delimiter < 0) { + continue; + } + QString left = entry.left(delimiter + 1); // [^\\\\]= has length 2. + left.replace("\\=", "="); + QString right = entry.mid(delimiter + 2); // [^\\\\]= has length 2. + if(right.isEmpty()) { + continue; + } + m_abbreviationMap[left] = StringBooleanPair(right, global); + } } QStringList Manager::getAbbreviationTextMatches(const QString& text) const { - QStringList toReturn; - for(AbbreviationMap::const_iterator i = m_abbreviationMap.begin(); - i != m_abbreviationMap.end(); ++i) { - if(i.key().startsWith(text)) { - toReturn.append(i.value().first); - } - } - return toReturn; + QStringList toReturn; + for(AbbreviationMap::const_iterator i = m_abbreviationMap.begin(); + i != m_abbreviationMap.end(); ++i) { + if(i.key().startsWith(text)) { + toReturn.append(i.value().first); + } + } + return toReturn; } QString Manager::getAbbreviationTextMatch(const QString& text) const { - return m_abbreviationMap[text].first; + return m_abbreviationMap[text].first; } bool Manager::abbreviationStartsWith(const QString& text) const { - for(AbbreviationMap::const_iterator i = m_abbreviationMap.begin(); - i != m_abbreviationMap.end(); ++i) { - if(i.key().startsWith(text)) { - return true; - } - } - return false; + for(AbbreviationMap::const_iterator i = m_abbreviationMap.begin(); + i != m_abbreviationMap.end(); ++i) { + if(i.key().startsWith(text)) { + return true; + } + } + return false; } bool Manager::isAbbreviationDefined(const QString& text) const { - return m_abbreviationMap.find(text) != m_abbreviationMap.end(); + return m_abbreviationMap.find(text) != m_abbreviationMap.end(); } } diff --git a/src/abbreviationmanager.h b/src/abbreviationmanager.h index c9da0fb9..596bac6a 100644 --- a/src/abbreviationmanager.h +++ b/src/abbreviationmanager.h @@ -1,106 +1,106 @@ /************************************************************************** * Copyright (C) 2009-2010 by Michel Ludwig (michel.ludwig@kdemail.net) * ***************************************************************************/ /************************************************************************** * * * 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. * * * ***************************************************************************/ #ifndef ABBREVIATIONMANAGER_H #define ABBREVIATIONMANAGER_H #include #include #include #include #include class KileInfo; namespace KileAbbreviation { - typedef QPair StringBooleanPair; - typedef QMap AbbreviationMap; - - /** - * This manager class is responsible for handling abbreviations. - **/ - class Manager : public QObject { - Q_OBJECT - - public: - /** - * Constructs a new manager object. - **/ - explicit Manager(KileInfo* kileInfo, QObject *parent = Q_NULLPTR); - virtual ~Manager(); - - // the boolean value is 'true' iff the abbreviation is global - const AbbreviationMap& getAbbreviationMap(); - - void readAbbreviationFiles(); - void saveLocalAbbreviations(); - - void updateLocalAbbreviation(const QString& text, const QString& replacement); - void removeLocalAbbreviation(const QString& text); - - static inline bool isLocalAbbreviation(const StringBooleanPair& p) - { - return !p.second; - } - - static inline bool isGlobalAbbreviation(const StringBooleanPair& p) - { - return p.second; - } - - static inline StringBooleanPair createGlobalAbbreviationPair(const QString& s) - { - return StringBooleanPair(s, true); - } - - static inline StringBooleanPair createLocalAbbreviationPair(const QString& s) - { - return StringBooleanPair(s, false); - } - - /** - * Returns the replacement strings of those strings that start with 'text'. - **/ - QStringList getAbbreviationTextMatches(const QString& text) const; - - /** - * Returns the replacement string for 'text'; an empty string is returned - * is 'text' is not found - **/ - QString getAbbreviationTextMatch(const QString& text) const; - - /** - * Returns true iff there exists an abbreviation which starts with 'text'. - **/ - bool abbreviationStartsWith(const QString& text) const; - - bool isAbbreviationDefined(const QString& text) const; - - Q_SIGNALS: - void abbreviationsChanged(); - - protected: - KileInfo *m_kileInfo; - bool m_abbreviationsDirty; - QString m_localAbbreviationFile; - AbbreviationMap m_abbreviationMap; - - void addAbbreviationListToMap(const QStringList& list, bool global); - }; +typedef QPair StringBooleanPair; +typedef QMap AbbreviationMap; + +/** + * This manager class is responsible for handling abbreviations. + **/ +class Manager : public QObject { + Q_OBJECT + +public: + /** + * Constructs a new manager object. + **/ + explicit Manager(KileInfo* kileInfo, QObject *parent = Q_NULLPTR); + virtual ~Manager(); + + // the boolean value is 'true' iff the abbreviation is global + const AbbreviationMap& getAbbreviationMap(); + + void readAbbreviationFiles(); + void saveLocalAbbreviations(); + + void updateLocalAbbreviation(const QString& text, const QString& replacement); + void removeLocalAbbreviation(const QString& text); + + static inline bool isLocalAbbreviation(const StringBooleanPair& p) + { + return !p.second; + } + + static inline bool isGlobalAbbreviation(const StringBooleanPair& p) + { + return p.second; + } + + static inline StringBooleanPair createGlobalAbbreviationPair(const QString& s) + { + return StringBooleanPair(s, true); + } + + static inline StringBooleanPair createLocalAbbreviationPair(const QString& s) + { + return StringBooleanPair(s, false); + } + + /** + * Returns the replacement strings of those strings that start with 'text'. + **/ + QStringList getAbbreviationTextMatches(const QString& text) const; + + /** + * Returns the replacement string for 'text'; an empty string is returned + * is 'text' is not found + **/ + QString getAbbreviationTextMatch(const QString& text) const; + + /** + * Returns true iff there exists an abbreviation which starts with 'text'. + **/ + bool abbreviationStartsWith(const QString& text) const; + + bool isAbbreviationDefined(const QString& text) const; + +Q_SIGNALS: + void abbreviationsChanged(); + +protected: + KileInfo *m_kileInfo; + bool m_abbreviationsDirty; + QString m_localAbbreviationFile; + AbbreviationMap m_abbreviationMap; + + void addAbbreviationListToMap(const QStringList& list, bool global); +}; } #endif diff --git a/src/codecompletion.cpp b/src/codecompletion.cpp index 32f6f74d..871ec06c 100644 --- a/src/codecompletion.cpp +++ b/src/codecompletion.cpp @@ -1,1150 +1,1150 @@ /********************************************************************************************** Copyright (C) 2004-2007 by Holger Danielsson (holger.danielsson@versanet.de) 2008-2016 by Michel Ludwig (michel.ludwig@kdemail.net) ***********************************************************************************************/ /*************************************************************************** * * * 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. * * * ***************************************************************************/ #include "codecompletion.h" #include #include #include #include #include #include #include #include #include #include "kiledebug.h" #include "abbreviationmanager.h" #include "documentinfo.h" #include "editorextension.h" #include "kiledocmanager.h" #include "kileinfo.h" #include "kileviewmanager.h" #include "kileconfig.h" namespace KileCodeCompletion { LaTeXCompletionModel::LaTeXCompletionModel(QObject *parent, KileCodeCompletion::Manager *manager, - KileDocument::EditorExtension *editorExtension) -: KTextEditor::CodeCompletionModel(parent), m_codeCompletionManager(manager), m_editorExtension(editorExtension), m_currentView(Q_NULLPTR) + KileDocument::EditorExtension *editorExtension) + : KTextEditor::CodeCompletionModel(parent), m_codeCompletionManager(manager), m_editorExtension(editorExtension), m_currentView(Q_NULLPTR) { - setHasGroups(false); + setHasGroups(false); } LaTeXCompletionModel::~LaTeXCompletionModel() { } void LaTeXCompletionModel::completionInvoked(KTextEditor::View *view, const KTextEditor::Range &range, - InvocationType invocationType) + InvocationType invocationType) { - if(!range.isValid() - || (invocationType == AutomaticInvocation && !KileConfig::completeAuto())) { - beginResetModel(); - m_completionList.clear(); - endResetModel(); - return; - } - Q_UNUSED(invocationType); - m_currentView = view; - KILE_DEBUG_CODECOMPLETION << "building model..."; - buildModel(view, range); + if(!range.isValid() + || (invocationType == AutomaticInvocation && !KileConfig::completeAuto())) { + beginResetModel(); + m_completionList.clear(); + endResetModel(); + return; + } + Q_UNUSED(invocationType); + m_currentView = view; + KILE_DEBUG_CODECOMPLETION << "building model..."; + buildModel(view, range); } KTextEditor::Range LaTeXCompletionModel::updateCompletionRange(KTextEditor::View *view, - const KTextEditor::Range &range) + const KTextEditor::Range &range) { - KILE_DEBUG_CODECOMPLETION << "updating model..." << view << range; - KTextEditor::Range newRange = completionRange(view, view->cursorPosition()); - if(newRange.isValid()) { - buildModel(view, newRange); - } - return newRange; + KILE_DEBUG_CODECOMPLETION << "updating model..." << view << range; + KTextEditor::Range newRange = completionRange(view, view->cursorPosition()); + if(newRange.isValid()) { + buildModel(view, newRange); + } + return newRange; } static inline bool isSpecialLaTeXCommandCharacter(const QChar& c) { - return (c == '{' || c == '[' || c == '*' || c == ']' || c == '}'); + return (c == '{' || c == '[' || c == '*' || c == ']' || c == '}'); } static inline int specialLaTeXCommandCharacterOrdering(const QChar& c) { - switch(c.unicode()) { - case '{': - return 1; - case '[': - return 2; - case ']': - return 3; - case '}': - return 4; - case '*': - return 5; - default: // does nothing - break; - } - return 4; // must be 'isLetterOrNumber()' now + switch(c.unicode()) { + case '{': + return 1; + case '[': + return 2; + case ']': + return 3; + case '}': + return 4; + case '*': + return 5; + default: // does nothing + break; + } + return 4; // must be 'isLetterOrNumber()' now } static bool laTeXCommandLessThan(const QString& s1, const QString& s2) { - for(int i = 0; i < s1.length(); ++i) { - if(i >= s2.length()) { - return false; - } - const QChar c1 = s1.at(i); - const QChar c2 = s2.at(i); - - if(c1 == c2) { - continue; - } - if(c1.isLetterOrNumber()) { - if(isSpecialLaTeXCommandCharacter(c2)) { - return false; - } - else { - return (c1 < c2); - } - } - else if(isSpecialLaTeXCommandCharacter(c1)) { - if(isSpecialLaTeXCommandCharacter(c2)) { - return (specialLaTeXCommandCharacterOrdering(c1) - < specialLaTeXCommandCharacterOrdering(c2)); - } - else if(c2.isLetterOrNumber()) { - return true; - } - else { - return (c1 < c2); - } - } - } - return true; + for(int i = 0; i < s1.length(); ++i) { + if(i >= s2.length()) { + return false; + } + const QChar c1 = s1.at(i); + const QChar c2 = s2.at(i); + + if(c1 == c2) { + continue; + } + if(c1.isLetterOrNumber()) { + if(isSpecialLaTeXCommandCharacter(c2)) { + return false; + } + else { + return (c1 < c2); + } + } + else if(isSpecialLaTeXCommandCharacter(c1)) { + if(isSpecialLaTeXCommandCharacter(c2)) { + return (specialLaTeXCommandCharacterOrdering(c1) + < specialLaTeXCommandCharacterOrdering(c2)); + } + else if(c2.isLetterOrNumber()) { + return true; + } + else { + return (c1 < c2); + } + } + } + return true; } void LaTeXCompletionModel::buildModel(KTextEditor::View *view, const KTextEditor::Range &range) { - QString completionString = view->document()->text(range); - KILE_DEBUG_CODECOMPLETION << "Text in completion range: " << completionString; - m_completionList.clear(); - - if(completionString.startsWith('\\')) { - m_completionList = m_codeCompletionManager->getLaTeXCommands(); - m_completionList += m_codeCompletionManager->getLocallyDefinedLaTeXCommands(view); - } - else { - KTextEditor::Cursor latexCommandStart = determineLaTeXCommandStart(view->document(), - view->cursorPosition()); - if(!latexCommandStart.isValid()) { - return; - } - QString leftSubstring = view->document()->text(KTextEditor::Range(latexCommandStart, - view->cursorPosition())); - // check whether we are supposed to build a model for reference or citation completion - int citationIndex = leftSubstring.indexOf(m_codeCompletionManager->m_citeRegExp); - int referenceIndex = leftSubstring.indexOf(m_codeCompletionManager->m_referencesRegExp); - if(referenceIndex != -1) { - //FIXME: the retrieval of labels and BibTeX entries has to be revised! - m_completionList = m_codeCompletionManager->m_ki->allLabels(); - } - else if(citationIndex != -1) { - m_completionList = m_codeCompletionManager->m_ki->allBibItems(); - } - } - beginResetModel(); - filterModel(completionString); - std::sort(m_completionList.begin(), m_completionList.end(), laTeXCommandLessThan); - endResetModel(); + QString completionString = view->document()->text(range); + KILE_DEBUG_CODECOMPLETION << "Text in completion range: " << completionString; + m_completionList.clear(); + + if(completionString.startsWith('\\')) { + m_completionList = m_codeCompletionManager->getLaTeXCommands(); + m_completionList += m_codeCompletionManager->getLocallyDefinedLaTeXCommands(view); + } + else { + KTextEditor::Cursor latexCommandStart = determineLaTeXCommandStart(view->document(), + view->cursorPosition()); + if(!latexCommandStart.isValid()) { + return; + } + QString leftSubstring = view->document()->text(KTextEditor::Range(latexCommandStart, + view->cursorPosition())); + // check whether we are supposed to build a model for reference or citation completion + int citationIndex = leftSubstring.indexOf(m_codeCompletionManager->m_citeRegExp); + int referenceIndex = leftSubstring.indexOf(m_codeCompletionManager->m_referencesRegExp); + if(referenceIndex != -1) { + //FIXME: the retrieval of labels and BibTeX entries has to be revised! + m_completionList = m_codeCompletionManager->m_ki->allLabels(); + } + else if(citationIndex != -1) { + m_completionList = m_codeCompletionManager->m_ki->allBibItems(); + } + } + beginResetModel(); + filterModel(completionString); + std::sort(m_completionList.begin(), m_completionList.end(), laTeXCommandLessThan); + endResetModel(); } KTextEditor::Cursor LaTeXCompletionModel::determineLaTeXCommandStart(KTextEditor::Document *doc, - const KTextEditor::Cursor& position) const + const KTextEditor::Cursor& position) const { - QString line = doc->line(position.line()); + QString line = doc->line(position.line()); // QRegExp completionStartRegExp("((\\s|^)?)((\\\\\\w*)|(\\w+))$"); // QRegExp completionStartRegExp("((\\\\\\w*)|([^\\\\]\\b\\w+))$"); // QRegExp completionStartRegExp("(\\\\\\w*)[^\\\\]*$"); - // TeX allows '.' characters inside citation labels (bug 266670) - QRegExp completionStartRegExp("(\\\\([\\s\\{\\}\\[\\]\\w,.=\"'~:]|(\\&)|(\\$)|(\\%)(\\#)(\\_)|(\\{)|(\\})|(\\backslash)|(\\^)|(\\[)|(\\]))*)$"); - completionStartRegExp.setMinimal(true); - QString leftSubstring = line.left(position.column()); - KILE_DEBUG_CODECOMPLETION << "leftSubstring: " << leftSubstring; - int startPos = completionStartRegExp.lastIndexIn(leftSubstring); - if(startPos >= 0) { - return KTextEditor::Cursor(position.line(), startPos); - } - else { - return KTextEditor::Cursor::invalid(); - } + // TeX allows '.' characters inside citation labels (bug 266670) + QRegExp completionStartRegExp("(\\\\([\\s\\{\\}\\[\\]\\w,.=\"'~:]|(\\&)|(\\$)|(\\%)(\\#)(\\_)|(\\{)|(\\})|(\\backslash)|(\\^)|(\\[)|(\\]))*)$"); + completionStartRegExp.setMinimal(true); + QString leftSubstring = line.left(position.column()); + KILE_DEBUG_CODECOMPLETION << "leftSubstring: " << leftSubstring; + int startPos = completionStartRegExp.lastIndexIn(leftSubstring); + if(startPos >= 0) { + return KTextEditor::Cursor(position.line(), startPos); + } + else { + return KTextEditor::Cursor::invalid(); + } } bool LaTeXCompletionModel::isWithinLaTeXCommand(KTextEditor::Document *doc, const KTextEditor::Cursor& commandStart, - const KTextEditor::Cursor& cursorPosition) const + const KTextEditor::Cursor& cursorPosition) const { - QString commandText = doc->text(KTextEditor::Range(commandStart, cursorPosition)); - int numOpenSquareBrackets = commandText.count(QRegExp("[^\\\\]\\[")); - int numClosedSquareBrackets = commandText.count(QRegExp("[^\\\\]\\]")); - int numOpenCurlyBrackets = commandText.count(QRegExp("[^\\\\]\\{")); - int numClosedCurlyBrackets = commandText.count(QRegExp("[^\\\\]\\}")); - if(numOpenSquareBrackets != numClosedSquareBrackets || numOpenCurlyBrackets != numClosedCurlyBrackets) { - return true; - } - if(numOpenSquareBrackets == 0 && numOpenCurlyBrackets == 0 && commandText.count(' ') == 0) { - return true; - } - return false; + QString commandText = doc->text(KTextEditor::Range(commandStart, cursorPosition)); + int numOpenSquareBrackets = commandText.count(QRegExp("[^\\\\]\\[")); + int numClosedSquareBrackets = commandText.count(QRegExp("[^\\\\]\\]")); + int numOpenCurlyBrackets = commandText.count(QRegExp("[^\\\\]\\{")); + int numClosedCurlyBrackets = commandText.count(QRegExp("[^\\\\]\\}")); + if(numOpenSquareBrackets != numClosedSquareBrackets || numOpenCurlyBrackets != numClosedCurlyBrackets) { + return true; + } + if(numOpenSquareBrackets == 0 && numOpenCurlyBrackets == 0 && commandText.count(' ') == 0) { + return true; + } + return false; } KTextEditor::Range LaTeXCompletionModel::completionRange(KTextEditor::View *view, const KTextEditor::Cursor &position) { - bool latexCompletion = true; - QString line = view->document()->line(position.line()); - KTextEditor::Cursor startCursor = position; - KTextEditor::Cursor endCursor = position; - - QRegExp completionEndRegExp("\\W|\\b|\\\\"); - - int cursorPos = position.column(); - - KTextEditor::Cursor latexCommandStart = determineLaTeXCommandStart(view->document(), position); - KILE_DEBUG_CODECOMPLETION << "LaTeX command start " << latexCommandStart; - if(!latexCommandStart.isValid() || !isWithinLaTeXCommand(view->document(), latexCommandStart, position)) { - return KTextEditor::Range::invalid(); - } - QString completionString = view->document()->text(KTextEditor::Range(latexCommandStart, - position)); - KILE_DEBUG_CODECOMPLETION << "completionString " << completionString; - //check whether we are completing a citation of reference - if(completionString.indexOf(m_codeCompletionManager->m_citeRegExp) != -1 - || completionString.indexOf(m_codeCompletionManager->m_referencesRegExp) != -1) { - KILE_DEBUG_CODECOMPLETION << "found citation or reference!"; - int openBracketIndex = completionString.indexOf('{'); - if(openBracketIndex != -1) { - // TeX allows '.' characters inside citation labels (bug 266670) - QRegExp labelListRegExp("\\s*(([:.\\w]+)|([:.\\w]+(\\s*,\\s*[:.\\w]*)+))"); - labelListRegExp.setMinimal(false); - int column = openBracketIndex + 1; - KILE_DEBUG_CODECOMPLETION << "open bracket column + 1: " << column; - KILE_DEBUG_CODECOMPLETION << labelListRegExp.indexIn(completionString, openBracketIndex + 1); - if(labelListRegExp.indexIn(completionString, openBracketIndex + 1) == openBracketIndex + 1 - && labelListRegExp.matchedLength() + openBracketIndex + 1 == completionString.length()) { - QRegExp lastCommaRegExp(",\\s*"); - int lastCommaIndex = lastCommaRegExp.lastIndexIn(completionString); - if(lastCommaIndex >= 0) { - KILE_DEBUG_CODECOMPLETION << "last comma found at: " << lastCommaIndex; - column = lastCommaIndex + lastCommaRegExp.matchedLength(); - } - } - KILE_DEBUG_CODECOMPLETION << labelListRegExp.errorString(); - startCursor.setColumn(latexCommandStart.column() + column); - latexCompletion = false; - } - else { - startCursor = latexCommandStart; - } - } - else { - startCursor = latexCommandStart; - } - - int endPos = line.indexOf(completionEndRegExp, cursorPos); - KILE_DEBUG_CODECOMPLETION << "endPos" << endPos; - if(endPos >= 0) { - endCursor.setColumn(endPos); - } - KTextEditor::Range completionRange(startCursor, endCursor); - int rangeLength = endCursor.column() - startCursor.column(); - - if(latexCompletion && KileConfig::completeAuto() && rangeLength < KileConfig::completeAutoThreshold() + 1) { // + 1 for the command backslash - KILE_DEBUG_CODECOMPLETION << "not reached the completion threshold yet"; - return KTextEditor::Range::invalid(); - } - KILE_DEBUG_CODECOMPLETION << "returning completion range: " << completionRange; - return completionRange; + bool latexCompletion = true; + QString line = view->document()->line(position.line()); + KTextEditor::Cursor startCursor = position; + KTextEditor::Cursor endCursor = position; + + QRegExp completionEndRegExp("\\W|\\b|\\\\"); + + int cursorPos = position.column(); + + KTextEditor::Cursor latexCommandStart = determineLaTeXCommandStart(view->document(), position); + KILE_DEBUG_CODECOMPLETION << "LaTeX command start " << latexCommandStart; + if(!latexCommandStart.isValid() || !isWithinLaTeXCommand(view->document(), latexCommandStart, position)) { + return KTextEditor::Range::invalid(); + } + QString completionString = view->document()->text(KTextEditor::Range(latexCommandStart, + position)); + KILE_DEBUG_CODECOMPLETION << "completionString " << completionString; + //check whether we are completing a citation of reference + if(completionString.indexOf(m_codeCompletionManager->m_citeRegExp) != -1 + || completionString.indexOf(m_codeCompletionManager->m_referencesRegExp) != -1) { + KILE_DEBUG_CODECOMPLETION << "found citation or reference!"; + int openBracketIndex = completionString.indexOf('{'); + if(openBracketIndex != -1) { + // TeX allows '.' characters inside citation labels (bug 266670) + QRegExp labelListRegExp("\\s*(([:.\\w]+)|([:.\\w]+(\\s*,\\s*[:.\\w]*)+))"); + labelListRegExp.setMinimal(false); + int column = openBracketIndex + 1; + KILE_DEBUG_CODECOMPLETION << "open bracket column + 1: " << column; + KILE_DEBUG_CODECOMPLETION << labelListRegExp.indexIn(completionString, openBracketIndex + 1); + if(labelListRegExp.indexIn(completionString, openBracketIndex + 1) == openBracketIndex + 1 + && labelListRegExp.matchedLength() + openBracketIndex + 1 == completionString.length()) { + QRegExp lastCommaRegExp(",\\s*"); + int lastCommaIndex = lastCommaRegExp.lastIndexIn(completionString); + if(lastCommaIndex >= 0) { + KILE_DEBUG_CODECOMPLETION << "last comma found at: " << lastCommaIndex; + column = lastCommaIndex + lastCommaRegExp.matchedLength(); + } + } + KILE_DEBUG_CODECOMPLETION << labelListRegExp.errorString(); + startCursor.setColumn(latexCommandStart.column() + column); + latexCompletion = false; + } + else { + startCursor = latexCommandStart; + } + } + else { + startCursor = latexCommandStart; + } + + int endPos = line.indexOf(completionEndRegExp, cursorPos); + KILE_DEBUG_CODECOMPLETION << "endPos" << endPos; + if(endPos >= 0) { + endCursor.setColumn(endPos); + } + KTextEditor::Range completionRange(startCursor, endCursor); + int rangeLength = endCursor.column() - startCursor.column(); + + if(latexCompletion && KileConfig::completeAuto() && rangeLength < KileConfig::completeAutoThreshold() + 1) { // + 1 for the command backslash + KILE_DEBUG_CODECOMPLETION << "not reached the completion threshold yet"; + return KTextEditor::Range::invalid(); + } + KILE_DEBUG_CODECOMPLETION << "returning completion range: " << completionRange; + return completionRange; } bool LaTeXCompletionModel::shouldStartCompletion(KTextEditor::View *view, const QString &insertedText, - bool userInsertion, const KTextEditor::Cursor &position) + bool userInsertion, const KTextEditor::Cursor &position) { - Q_UNUSED(view); - Q_UNUSED(position); - if(!KileConfig::completeAuto()) { - return false; - } - - if(insertedText.isEmpty()) { - return false; - } - - if(insertedText.endsWith('{')) { - return true; - } - else { - return CodeCompletionModelControllerInterface::shouldStartCompletion(view, insertedText, userInsertion, position); - } + Q_UNUSED(view); + Q_UNUSED(position); + if(!KileConfig::completeAuto()) { + return false; + } + + if(insertedText.isEmpty()) { + return false; + } + + if(insertedText.endsWith('{')) { + return true; + } + else { + return CodeCompletionModelControllerInterface::shouldStartCompletion(view, insertedText, userInsertion, position); + } } bool LaTeXCompletionModel::shouldAbortCompletion(KTextEditor::View *view, const KTextEditor::Range &range, - const QString ¤tCompletion) + const QString ¤tCompletion) { - Q_UNUSED(currentCompletion); - if(view->cursorPosition() < range.start() || view->cursorPosition() > range.end() - || m_completionList.size() == 0) { - return true; - } - return false; + Q_UNUSED(currentCompletion); + if(view->cursorPosition() < range.start() || view->cursorPosition() > range.end() + || m_completionList.size() == 0) { + return true; + } + return false; } QString LaTeXCompletionModel::filterString(KTextEditor::View *view, const KTextEditor::Range &range, - const KTextEditor::Cursor &position) + const KTextEditor::Cursor &position) { - Q_UNUSED(position); - KILE_DEBUG_CODECOMPLETION << "range: " << range; - KILE_DEBUG_CODECOMPLETION << "text: " << (range.isValid() ? view->document()->text(range) - : "(invalid range)"); + Q_UNUSED(position); + KILE_DEBUG_CODECOMPLETION << "range: " << range; + KILE_DEBUG_CODECOMPLETION << "text: " << (range.isValid() ? view->document()->text(range) + : "(invalid range)"); - return ""; + return ""; } QVariant LaTeXCompletionModel::data(const QModelIndex& index, int role) const { - switch(role) { - case Qt::DisplayRole: - if(index.column() != KTextEditor::CodeCompletionModel::Name) { - return QVariant(); - } - return m_completionList.at(index.row()); - case InheritanceDepth: - return index.row(); - } - - return QVariant(); + switch(role) { + case Qt::DisplayRole: + if(index.column() != KTextEditor::CodeCompletionModel::Name) { + return QVariant(); + } + return m_completionList.at(index.row()); + case InheritanceDepth: + return index.row(); + } + + return QVariant(); } QModelIndex LaTeXCompletionModel::index(int row, int column, const QModelIndex &parent) const { - if (row < 0 || row >= m_completionList.count() || column < 0 || column >= ColumnCount || parent.isValid()) { - return QModelIndex(); - } + if (row < 0 || row >= m_completionList.count() || column < 0 || column >= ColumnCount || parent.isValid()) { + return QModelIndex(); + } - return createIndex(row, column); + return createIndex(row, column); } int LaTeXCompletionModel::rowCount(const QModelIndex &parent) const { - if(parent.isValid()) { - return 0; - } - return m_completionList.size(); + if(parent.isValid()) { + return 0; + } + return m_completionList.size(); } void LaTeXCompletionModel::filterModel(const QString& text) { - QMutableStringListIterator it(m_completionList); - while(it.hasNext()) { - QString string = it.next(); - if(!string.startsWith(text)) { - it.remove(); - } - } + QMutableStringListIterator it(m_completionList); + while(it.hasNext()) { + QString string = it.next(); + if(!string.startsWith(text)) { + it.remove(); + } + } } void LaTeXCompletionModel::executeCompletionItem(KTextEditor::View *view, - const KTextEditor::Range& word, const QModelIndex &index) const + const KTextEditor::Range& word, const QModelIndex &index) const { - KTextEditor::Document *document = view->document(); - KTextEditor::Cursor startCursor = word.start(); - const static QRegExp reEnv = QRegExp("^\\\\(begin|end)[^a-zA-Z]+"); - - int cursorXPos = -1, cursorYPos = -1; - QString completionText = data(index.sibling(index.row(), Name), Qt::DisplayRole).toString(); - - QString textToInsert; - int envIndex = reEnv.indexIn(completionText); - if(completionText != "\\begin{}" && envIndex != -1) { // we are completing an environment - QString prefix; - prefix = document->text(KTextEditor::Range(startCursor.line(), 0, - startCursor.line(), word.start().column())); - textToInsert = buildEnvironmentCompletedText(completionText, prefix, cursorYPos, cursorXPos); - KILE_DEBUG_CODECOMPLETION << cursorYPos << ", " << cursorXPos; - } - else { - textToInsert = buildRegularCompletedText(stripParameters(completionText), cursorYPos, cursorXPos, true); - } - // if there are brackets present immediately after 'word' (for example, due to auto-bracketing of - // the editor), we still have to remove them - QString replaceText = document->text(word); - const int numberOfOpenSimpleBrackets = replaceText.count('('); - const int numberOfOpenSquareBrackets = replaceText.count('['); - const int numberOfOpenCurlyBrackets = replaceText.count('{'); - const int numberOfClosedSimpleBrackets = replaceText.count(')'); - const int numberOfClosedSquareBrackets = replaceText.count(']'); - const int numberOfClosedCurlyBrackets = replaceText.count('}'); - const int numberOfClosedBracketsLeft = (numberOfOpenSimpleBrackets - numberOfClosedSimpleBrackets) - + (numberOfOpenSquareBrackets - numberOfClosedSquareBrackets) - + (numberOfOpenCurlyBrackets - numberOfClosedCurlyBrackets); - if(numberOfOpenSimpleBrackets >= numberOfClosedSimpleBrackets - && numberOfOpenSquareBrackets >= numberOfClosedSquareBrackets - && numberOfOpenCurlyBrackets >= numberOfClosedCurlyBrackets - && document->lineLength(word.end().line()) >= word.end().column() + numberOfClosedBracketsLeft) { - KTextEditor::Range bracketRange = KTextEditor::Range(word.end(), numberOfClosedBracketsLeft); - - QString bracketText = document->text(bracketRange); - if(bracketText.count(")") == (numberOfOpenSimpleBrackets - numberOfClosedSimpleBrackets) - && bracketText.count("]") == (numberOfOpenSquareBrackets - numberOfClosedSquareBrackets) - && bracketText.count("}") == (numberOfOpenCurlyBrackets - numberOfClosedCurlyBrackets)) { - document->removeText(bracketRange); - } - } - - // now do the real completion - document->replaceText(word, textToInsert); - //HACK, but it's impossible to do this otherwise - if(KileConfig::completeCursor() && (cursorXPos > 0 || cursorYPos > 0) - && m_currentView && document->views().contains(m_currentView)) { - m_currentView->setCursorPosition(KTextEditor::Cursor(startCursor.line() + (cursorYPos >= 0 ? cursorYPos : 0), - startCursor.column() + (cursorXPos >= 0 ? cursorXPos : 0))); - } + KTextEditor::Document *document = view->document(); + KTextEditor::Cursor startCursor = word.start(); + const static QRegExp reEnv = QRegExp("^\\\\(begin|end)[^a-zA-Z]+"); + + int cursorXPos = -1, cursorYPos = -1; + QString completionText = data(index.sibling(index.row(), Name), Qt::DisplayRole).toString(); + + QString textToInsert; + int envIndex = reEnv.indexIn(completionText); + if(completionText != "\\begin{}" && envIndex != -1) { // we are completing an environment + QString prefix; + prefix = document->text(KTextEditor::Range(startCursor.line(), 0, + startCursor.line(), word.start().column())); + textToInsert = buildEnvironmentCompletedText(completionText, prefix, cursorYPos, cursorXPos); + KILE_DEBUG_CODECOMPLETION << cursorYPos << ", " << cursorXPos; + } + else { + textToInsert = buildRegularCompletedText(stripParameters(completionText), cursorYPos, cursorXPos, true); + } + // if there are brackets present immediately after 'word' (for example, due to auto-bracketing of + // the editor), we still have to remove them + QString replaceText = document->text(word); + const int numberOfOpenSimpleBrackets = replaceText.count('('); + const int numberOfOpenSquareBrackets = replaceText.count('['); + const int numberOfOpenCurlyBrackets = replaceText.count('{'); + const int numberOfClosedSimpleBrackets = replaceText.count(')'); + const int numberOfClosedSquareBrackets = replaceText.count(']'); + const int numberOfClosedCurlyBrackets = replaceText.count('}'); + const int numberOfClosedBracketsLeft = (numberOfOpenSimpleBrackets - numberOfClosedSimpleBrackets) + + (numberOfOpenSquareBrackets - numberOfClosedSquareBrackets) + + (numberOfOpenCurlyBrackets - numberOfClosedCurlyBrackets); + if(numberOfOpenSimpleBrackets >= numberOfClosedSimpleBrackets + && numberOfOpenSquareBrackets >= numberOfClosedSquareBrackets + && numberOfOpenCurlyBrackets >= numberOfClosedCurlyBrackets + && document->lineLength(word.end().line()) >= word.end().column() + numberOfClosedBracketsLeft) { + KTextEditor::Range bracketRange = KTextEditor::Range(word.end(), numberOfClosedBracketsLeft); + + QString bracketText = document->text(bracketRange); + if(bracketText.count(")") == (numberOfOpenSimpleBrackets - numberOfClosedSimpleBrackets) + && bracketText.count("]") == (numberOfOpenSquareBrackets - numberOfClosedSquareBrackets) + && bracketText.count("}") == (numberOfOpenCurlyBrackets - numberOfClosedCurlyBrackets)) { + document->removeText(bracketRange); + } + } + + // now do the real completion + document->replaceText(word, textToInsert); + //HACK, but it's impossible to do this otherwise + if(KileConfig::completeCursor() && (cursorXPos > 0 || cursorYPos > 0) + && m_currentView && document->views().contains(m_currentView)) { + m_currentView->setCursorPosition(KTextEditor::Cursor(startCursor.line() + (cursorYPos >= 0 ? cursorYPos : 0), + startCursor.column() + (cursorXPos >= 0 ? cursorXPos : 0))); + } } QString LaTeXCompletionModel::filterLatexCommand(const QString &text, int &cursorYPos, int &cursorXPos) { - const static QRegExp reEnv = QRegExp("^\\\\(begin|end)[^a-zA-Z]+"); - - cursorXPos = -1, cursorYPos = -1; - QString textToInsert; - int envIndex = reEnv.indexIn(text); - if(text != "\\begin{}" && envIndex != -1) { - textToInsert = buildEnvironmentCompletedText(text, QString(), cursorYPos, cursorXPos); - } - else { - textToInsert = buildRegularCompletedText(stripParameters(text), cursorYPos, cursorXPos, true); - } - return textToInsert; + const static QRegExp reEnv = QRegExp("^\\\\(begin|end)[^a-zA-Z]+"); + + cursorXPos = -1, cursorYPos = -1; + QString textToInsert; + int envIndex = reEnv.indexIn(text); + if(text != "\\begin{}" && envIndex != -1) { + textToInsert = buildEnvironmentCompletedText(text, QString(), cursorYPos, cursorXPos); + } + else { + textToInsert = buildRegularCompletedText(stripParameters(text), cursorYPos, cursorXPos, true); + } + return textToInsert; } // strip all names enclosed in braces // consider also beamer like stuff [<...>] and <...> QString LaTeXCompletionModel::stripParameters(const QString &text) const { - QString s; - bool ignore = false; - - for(int i = 0; i < text.length(); ++i) { - QChar c = text[i]; - switch(c.unicode()) { - case '[': - case '{': - case '(': - case '<': - s += c; - ignore = true; - break; - case ']': - case '}': - case ')': - case '>': - s += c; - ignore = false; - break; - case ',': - s += c; - break; - default: - if(!ignore) { - s += c; - } - break; - } - } - return s; + QString s; + bool ignore = false; + + for(int i = 0; i < text.length(); ++i) { + QChar c = text[i]; + switch(c.unicode()) { + case '[': + case '{': + case '(': + case '<': + s += c; + ignore = true; + break; + case ']': + case '}': + case ')': + case '>': + s += c; + ignore = false; + break; + case ',': + s += c; + break; + default: + if(!ignore) { + s += c; + } + break; + } + } + return s; } QString LaTeXCompletionModel::buildRegularCompletedText(const QString &text, int &cursorYPos, int &cursorXPos, bool checkGroup) const { - bool setCursor = true, setBullets = true; - bool foundgroup = false; - QString s; - - cursorXPos = -1; - cursorYPos = -1; - for(int i = 0; i < text.length(); ++i) { - QChar c = text[i]; - switch(c.unicode()) { - case '<': - case '{': - case '(': - case '[': // insert character - s += c; - if(cursorXPos < 0) { - // remember position after first brace - if(c == '[' && (i + 1) < text.length() && text[i + 1] == '<') { - cursorXPos = i + 2; - s += text[i + 1]; - i++; - }// special handling for '[<' - else { - cursorXPos = i + 1; - } - // insert bullet, if this is no cursorposition - if((!setCursor) && setBullets && !(c == '[' && (i + 1) < text.length() && text[i + 1] == '<')) { - s += s_bullet; - } - } - // insert bullets after following braces - else if(setBullets && !(c == '[' && (i + 1) < text.length() && text[i + 1] == '<')) { - s += s_bullet; - } - break; - case '>': - case '}': - case ')': - case ']': // insert character - s += c; - break; - case ',': // insert character - s += c; - // insert bullet? - if(setBullets) { - s += s_bullet; - } - break; - case '.': // if the last character is a point of a range operator, - // it will be replaced by a space or a bullet surrounded by spaces - if(checkGroup && (s.right(1) == ".")) { - foundgroup = true; - s.truncate(s.length() - 1); - if(setBullets) { - s += ' ' + s_bullet + ' '; - } - else { - s += ' '; - } - } - else { - s += c; - } - break; - default: // insert all other characters - s += c; - break; - } - } - - // some more work with groups and bullets - if(s.length() >= 2 && checkGroup && foundgroup && (setBullets | setCursor)) { - int pos = 0; - - // search for braces, brackets and parens - switch(s[1].unicode()) { - case 'l': - if(s.left(6) == "\\left ") { - pos = 5; - } - break; - case 'b': - if(s.left(6) == "\\bigl ") { - pos = 5; - } - else if(s.left(7) == "\\biggl ") { - pos = 6; - } - break; - case 'B' : - if(s.left(6) == "\\Bigl ") { - pos = 5; - } - else if(s.left(7) == "\\Biggl ") { - pos = 6; - } - break; - } - - // update cursorposition and set bullet - if(pos > 0) { - if(setCursor) { - cursorXPos = pos; - } - if(setBullets) { - if(!setCursor) { - s.insert(pos, s_bullet); - } - s.append(s_bullet); - } - } - } - - return s; + bool setCursor = true, setBullets = true; + bool foundgroup = false; + QString s; + + cursorXPos = -1; + cursorYPos = -1; + for(int i = 0; i < text.length(); ++i) { + QChar c = text[i]; + switch(c.unicode()) { + case '<': + case '{': + case '(': + case '[': // insert character + s += c; + if(cursorXPos < 0) { + // remember position after first brace + if(c == '[' && (i + 1) < text.length() && text[i + 1] == '<') { + cursorXPos = i + 2; + s += text[i + 1]; + i++; + }// special handling for '[<' + else { + cursorXPos = i + 1; + } + // insert bullet, if this is no cursorposition + if((!setCursor) && setBullets && !(c == '[' && (i + 1) < text.length() && text[i + 1] == '<')) { + s += s_bullet; + } + } + // insert bullets after following braces + else if(setBullets && !(c == '[' && (i + 1) < text.length() && text[i + 1] == '<')) { + s += s_bullet; + } + break; + case '>': + case '}': + case ')': + case ']': // insert character + s += c; + break; + case ',': // insert character + s += c; + // insert bullet? + if(setBullets) { + s += s_bullet; + } + break; + case '.': // if the last character is a point of a range operator, + // it will be replaced by a space or a bullet surrounded by spaces + if(checkGroup && (s.right(1) == ".")) { + foundgroup = true; + s.truncate(s.length() - 1); + if(setBullets) { + s += ' ' + s_bullet + ' '; + } + else { + s += ' '; + } + } + else { + s += c; + } + break; + default: // insert all other characters + s += c; + break; + } + } + + // some more work with groups and bullets + if(s.length() >= 2 && checkGroup && foundgroup && (setBullets | setCursor)) { + int pos = 0; + + // search for braces, brackets and parens + switch(s[1].unicode()) { + case 'l': + if(s.left(6) == "\\left ") { + pos = 5; + } + break; + case 'b': + if(s.left(6) == "\\bigl ") { + pos = 5; + } + else if(s.left(7) == "\\biggl ") { + pos = 6; + } + break; + case 'B' : + if(s.left(6) == "\\Bigl ") { + pos = 5; + } + else if(s.left(7) == "\\Biggl ") { + pos = 6; + } + break; + } + + // update cursorposition and set bullet + if(pos > 0) { + if(setCursor) { + cursorXPos = pos; + } + if(setBullets) { + if(!setCursor) { + s.insert(pos, s_bullet); + } + s.append(s_bullet); + } + } + } + + return s; } QString LaTeXCompletionModel::buildEnvironmentCompletedText(const QString &text, const QString &prefix, - int &ypos, int &xpos) const + int &ypos, int &xpos) const { - static QRegExp reEnv = QRegExp("^\\\\(begin|end)\\{([^\\}]*)\\}([^\\\\]*)(.*)"); - - if(reEnv.indexIn(text) == -1) { - return text; - } - - QString parameter = stripParameters(reEnv.cap(3)); - QString start = reEnv.cap(1); - QString envname = reEnv.cap(2); - QString remainder = reEnv.cap(4); - QString whitespace = buildWhiteSpaceString(prefix); - QString envIndent = m_editorExtension->autoIndentEnvironment(); - - QString s = "\\" + start + "{" + envname + "}" + parameter + "\n"; - - s += whitespace; - if(start != "end") { - s += envIndent; - } - - if(!remainder.isEmpty()) { - s += remainder + ' '; - } - - if(KileConfig::completeBullets() && !parameter.isEmpty()) { - s += s_bullet; - } - - if(KileConfig::completeCloseEnv() && start != "end") { - s += '\n' + whitespace + "\\end{" + envname + "}\n"; - } - - if(parameter.isEmpty()) { - ypos = 1; - xpos = envIndent.length() + ((!remainder.isEmpty()) ? remainder.length() + 1 : 0); - } - else { - ypos = 0; - if(parameter.left(2) == "[<") { - xpos = 10 + envname.length(); - } - else { - xpos = 9 + envname.length(); - } - } - - return s; + static QRegExp reEnv = QRegExp("^\\\\(begin|end)\\{([^\\}]*)\\}([^\\\\]*)(.*)"); + + if(reEnv.indexIn(text) == -1) { + return text; + } + + QString parameter = stripParameters(reEnv.cap(3)); + QString start = reEnv.cap(1); + QString envname = reEnv.cap(2); + QString remainder = reEnv.cap(4); + QString whitespace = buildWhiteSpaceString(prefix); + QString envIndent = m_editorExtension->autoIndentEnvironment(); + + QString s = "\\" + start + "{" + envname + "}" + parameter + "\n"; + + s += whitespace; + if(start != "end") { + s += envIndent; + } + + if(!remainder.isEmpty()) { + s += remainder + ' '; + } + + if(KileConfig::completeBullets() && !parameter.isEmpty()) { + s += s_bullet; + } + + if(KileConfig::completeCloseEnv() && start != "end") { + s += '\n' + whitespace + "\\end{" + envname + "}\n"; + } + + if(parameter.isEmpty()) { + ypos = 1; + xpos = envIndent.length() + ((!remainder.isEmpty()) ? remainder.length() + 1 : 0); + } + else { + ypos = 0; + if(parameter.left(2) == "[<") { + xpos = 10 + envname.length(); + } + else { + xpos = 9 + envname.length(); + } + } + + return s; } QString LaTeXCompletionModel::buildWhiteSpaceString(const QString &s) const { - QString whitespace = s; - for(int i = 0; i < whitespace.length(); ++i) { - if(!whitespace[i].isSpace()) { - whitespace[i] = ' '; - } - } - return whitespace; + QString whitespace = s; + for(int i = 0; i < whitespace.length(); ++i) { + if(!whitespace[i].isSpace()) { + whitespace[i] = ' '; + } + } + return whitespace; } AbbreviationCompletionModel::AbbreviationCompletionModel(QObject *parent, KileAbbreviation::Manager *manager) -: KTextEditor::CodeCompletionModel(parent), m_abbreviationManager(manager) + : KTextEditor::CodeCompletionModel(parent), m_abbreviationManager(manager) { - setHasGroups(false); + setHasGroups(false); } AbbreviationCompletionModel::~AbbreviationCompletionModel() { } QModelIndex AbbreviationCompletionModel::index(int row, int column, const QModelIndex &parent) const { - if (row < 0 || row >= m_completionList.count() || column < 0 || column >= ColumnCount || parent.isValid()) { - return QModelIndex(); - } + if (row < 0 || row >= m_completionList.count() || column < 0 || column >= ColumnCount || parent.isValid()) { + return QModelIndex(); + } - return createIndex(row, column); + return createIndex(row, column); } QVariant AbbreviationCompletionModel::data(const QModelIndex& index, int role) const { - if(index.column() != KTextEditor::CodeCompletionModel::Name) { - return QVariant(); - } - switch(role) { - case Qt::DisplayRole: - return m_completionList.at(index.row()); - } - - return QVariant(); + if(index.column() != KTextEditor::CodeCompletionModel::Name) { + return QVariant(); + } + switch(role) { + case Qt::DisplayRole: + return m_completionList.at(index.row()); + } + + return QVariant(); } int AbbreviationCompletionModel::rowCount(const QModelIndex &parent) const { - if(parent.isValid()) { - return 0; - } - return m_completionList.size(); + if(parent.isValid()) { + return 0; + } + return m_completionList.size(); } bool AbbreviationCompletionModel::shouldStartCompletion(KTextEditor::View *view, const QString &insertedText, - bool userInsertion, const KTextEditor::Cursor &position) + bool userInsertion, const KTextEditor::Cursor &position) { - Q_UNUSED(view); - Q_UNUSED(userInsertion); - Q_UNUSED(position); - - int len = insertedText.length(); - QRegExp whitespace(" |\t"); - whitespace.setMinimal(true); - int pos = insertedText.lastIndexOf(whitespace, -1); - // 'pos' is less than or equal to 'len - 1' - QString searchText = (pos >= 0 && pos < len) ? insertedText.right(len - pos - 1) : insertedText; - - return (KileConfig::completeAutoAbbrev() && m_abbreviationManager->abbreviationStartsWith(searchText)); + Q_UNUSED(view); + Q_UNUSED(userInsertion); + Q_UNUSED(position); + + int len = insertedText.length(); + QRegExp whitespace(" |\t"); + whitespace.setMinimal(true); + int pos = insertedText.lastIndexOf(whitespace, -1); + // 'pos' is less than or equal to 'len - 1' + QString searchText = (pos >= 0 && pos < len) ? insertedText.right(len - pos - 1) : insertedText; + + return (KileConfig::completeAutoAbbrev() && m_abbreviationManager->abbreviationStartsWith(searchText)); } bool AbbreviationCompletionModel::shouldAbortCompletion(KTextEditor::View *view, const KTextEditor::Range &range, - const QString ¤tCompletion) + const QString ¤tCompletion) { - Q_UNUSED(currentCompletion); - if(view->cursorPosition() < range.start() || view->cursorPosition() > range.end() - || m_completionList.size() == 0) { - return true; - } - return false; + Q_UNUSED(currentCompletion); + if(view->cursorPosition() < range.start() || view->cursorPosition() > range.end() + || m_completionList.size() == 0) { + return true; + } + return false; } void AbbreviationCompletionModel::completionInvoked(KTextEditor::View *view, const KTextEditor::Range &range, - InvocationType invocationType) + InvocationType invocationType) { - if(!range.isValid() - || (invocationType == AutomaticInvocation && !KileConfig::completeAutoAbbrev())) { - beginResetModel(); - m_completionList.clear(); - endResetModel(); - return; - } - KILE_DEBUG_CODECOMPLETION << "building model..."; - buildModel(view, range, (invocationType == UserInvocation || invocationType == ManualInvocation)); + if(!range.isValid() + || (invocationType == AutomaticInvocation && !KileConfig::completeAutoAbbrev())) { + beginResetModel(); + m_completionList.clear(); + endResetModel(); + return; + } + KILE_DEBUG_CODECOMPLETION << "building model..."; + buildModel(view, range, (invocationType == UserInvocation || invocationType == ManualInvocation)); } KTextEditor::Range AbbreviationCompletionModel::updateCompletionRange(KTextEditor::View *view, - const KTextEditor::Range &range) + const KTextEditor::Range &range) { - if(!range.isValid()) { - beginResetModel(); - m_completionList.clear(); - endResetModel(); - return range; - } - - KILE_DEBUG_CODECOMPLETION << "updating model..."; - KTextEditor::Range newRange = completionRange(view, view->cursorPosition()); - if(newRange.isValid()) { - buildModel(view, newRange); - } - return newRange; + if(!range.isValid()) { + beginResetModel(); + m_completionList.clear(); + endResetModel(); + return range; + } + + KILE_DEBUG_CODECOMPLETION << "updating model..."; + KTextEditor::Range newRange = completionRange(view, view->cursorPosition()); + if(newRange.isValid()) { + buildModel(view, newRange); + } + return newRange; } KTextEditor::Range AbbreviationCompletionModel::completionRange(KTextEditor::View *view, - const KTextEditor::Cursor &position) + const KTextEditor::Cursor &position) { - QString insertedText = view->document()->line(position.line()).left(position.column()); - int len = insertedText.length(); - - QRegExp whitespace(" |\t"); - whitespace.setMinimal(true); - int pos = insertedText.lastIndexOf(whitespace,-1); - QString searchText = (pos>=0 && posdocument()->line(position.line()).left(position.column()); + int len = insertedText.length(); + + QRegExp whitespace(" |\t"); + whitespace.setMinimal(true); + int pos = insertedText.lastIndexOf(whitespace,-1); + QString searchText = (pos>=0 && posdocument(); - document->replaceText(word, completionText); - - // look if there is a %C-wish to place the cursor - if (completionText.indexOf("%C") >= 0) { - KTextEditor::Range searchrange = KTextEditor::Range(word.start(),document->lines()+1,0); - QVector rangevec = document->searchText(searchrange,"%C"); - if (rangevec.size() >= 1) { - KTextEditor::Range range = rangevec.at(0); - document->removeText(range); - if (view) { - view->setCursorPosition(range.start()); - } - } - } + // replace abbreviation and take care of newlines + QString completionText = data(index.sibling(index.row(), Name), Qt::DisplayRole).toString(); + completionText.replace("%n","\n"); + KTextEditor::Document *document = view->document(); + document->replaceText(word, completionText); + + // look if there is a %C-wish to place the cursor + if (completionText.indexOf("%C") >= 0) { + KTextEditor::Range searchrange = KTextEditor::Range(word.start(),document->lines()+1,0); + QVector rangevec = document->searchText(searchrange,"%C"); + if (rangevec.size() >= 1) { + KTextEditor::Range range = rangevec.at(0); + document->removeText(range); + if (view) { + view->setCursorPosition(range.start()); + } + } + } } void AbbreviationCompletionModel::buildModel(KTextEditor::View *view, const KTextEditor::Range &range, - bool singleMatchMode) + bool singleMatchMode) { - beginResetModel(); - m_completionList.clear(); - endResetModel(); - QString text = view->document()->text(range); - KILE_DEBUG_CODECOMPLETION << text; - if(text.isEmpty()) { - return; - } - if(singleMatchMode && m_abbreviationManager->isAbbreviationDefined(text)) { - m_completionList << m_abbreviationManager->getAbbreviationTextMatch(text); - executeCompletionItem(view, range, index(0, 0)); - } - else { - m_completionList = m_abbreviationManager->getAbbreviationTextMatches(text); - m_completionList.sort(); - if(m_completionList.size() == 1 - && m_abbreviationManager->isAbbreviationDefined(text)) { - executeCompletionItem(view, range, index(0, 0)); - } - } + beginResetModel(); + m_completionList.clear(); + endResetModel(); + QString text = view->document()->text(range); + KILE_DEBUG_CODECOMPLETION << text; + if(text.isEmpty()) { + return; + } + if(singleMatchMode && m_abbreviationManager->isAbbreviationDefined(text)) { + m_completionList << m_abbreviationManager->getAbbreviationTextMatch(text); + executeCompletionItem(view, range, index(0, 0)); + } + else { + m_completionList = m_abbreviationManager->getAbbreviationTextMatches(text); + m_completionList.sort(); + if(m_completionList.size() == 1 + && m_abbreviationManager->isAbbreviationDefined(text)) { + executeCompletionItem(view, range, index(0, 0)); + } + } } Manager::Manager(KileInfo *info, QObject *parent) -: QObject(parent), m_ki(info) + : QObject(parent), m_ki(info) { - m_firstConfig = true; + m_firstConfig = true; } Manager::~Manager() { } QStringList Manager::getLaTeXCommands() const { - return m_texWordList; + return m_texWordList; } QStringList Manager::getLocallyDefinedLaTeXCommands(KTextEditor::View *view) const { - //FIXME: the retrieval of these commands has to be revised! - KileDocument::TextInfo *textInfo = m_ki->docManager()->textInfoFor(view->document()); - if(!textInfo) { - return QStringList(); - } - return m_ki->allNewCommands(textInfo); + //FIXME: the retrieval of these commands has to be revised! + KileDocument::TextInfo *textInfo = m_ki->docManager()->textInfoFor(view->document()); + if(!textInfo) { + return QStringList(); + } + return m_ki->allNewCommands(textInfo); } void Manager::readConfig(KConfig *config) { - Q_UNUSED(config); - KILE_DEBUG_CODECOMPLETION << "======================"; - - // reading the wordlists is only necessary at the first start - // and when the list of files changes - if(m_firstConfig || KileConfig::completeChangedLists() || KileConfig::completeChangedCommands()) { - KILE_DEBUG_CODECOMPLETION << " setting regexp for references..."; - buildReferenceCitationRegularExpressions(); - - KILE_DEBUG_CODECOMPLETION << " read wordlists..."; - // wordlists for Tex/Latex mode - QStringList files = KileConfig::completeTex(); - m_texWordList = readCWLFiles(files, "tex"); - addUserDefinedLaTeXCommands(m_texWordList); - - // wordlist for dictionary mode - files = KileConfig::completeDict(); - m_dictWordList = readCWLFiles(files, "dictionary"); - m_dictWordList.sort(); - - // remember changed lists - // FIXME: remove these hacks - m_firstConfig = false; - KileConfig::setCompleteChangedLists(false); - KileConfig::setCompleteChangedCommands(false); - } + Q_UNUSED(config); + KILE_DEBUG_CODECOMPLETION << "======================"; + + // reading the wordlists is only necessary at the first start + // and when the list of files changes + if(m_firstConfig || KileConfig::completeChangedLists() || KileConfig::completeChangedCommands()) { + KILE_DEBUG_CODECOMPLETION << " setting regexp for references..."; + buildReferenceCitationRegularExpressions(); + + KILE_DEBUG_CODECOMPLETION << " read wordlists..."; + // wordlists for Tex/Latex mode + QStringList files = KileConfig::completeTex(); + m_texWordList = readCWLFiles(files, "tex"); + addUserDefinedLaTeXCommands(m_texWordList); + + // wordlist for dictionary mode + files = KileConfig::completeDict(); + m_dictWordList = readCWLFiles(files, "dictionary"); + m_dictWordList.sort(); + + // remember changed lists + // FIXME: remove these hacks + m_firstConfig = false; + KileConfig::setCompleteChangedLists(false); + KileConfig::setCompleteChangedCommands(false); + } } void Manager::startLaTeXCompletion(KTextEditor::View *view) { - if(!view) { - view = m_ki->viewManager()->currentTextView(); - if(!view) { - return; - } - } - - KileDocument::TextInfo *textInfo = m_ki->docManager()->textInfoFor(view->document()); - KileDocument::LaTeXInfo *latexInfo = dynamic_cast(textInfo); - if(!latexInfo) { - return; - } - latexInfo->startLaTeXCompletion(view); + if(!view) { + view = m_ki->viewManager()->currentTextView(); + if(!view) { + return; + } + } + + KileDocument::TextInfo *textInfo = m_ki->docManager()->textInfoFor(view->document()); + KileDocument::LaTeXInfo *latexInfo = dynamic_cast(textInfo); + if(!latexInfo) { + return; + } + latexInfo->startLaTeXCompletion(view); } void Manager::textInserted(KTextEditor::View* view, const KTextEditor::Cursor& /* position */, const QString& text) { - // auto insert '$' if the user just typed a '$' character - if (KileConfig::autoInsertDollar() && text == "$") { - // code completion seems to be never active, so there is no need to - // check KTextEditor::CodeCompletionInterface::isCompletionActive() - KTextEditor::Cursor currentCursorPos = view->cursorPosition(); - view->document()->insertText(currentCursorPos, "$"); - view->setCursorPosition(currentCursorPos); - } + // auto insert '$' if the user just typed a '$' character + if (KileConfig::autoInsertDollar() && text == "$") { + // code completion seems to be never active, so there is no need to + // check KTextEditor::CodeCompletionInterface::isCompletionActive() + KTextEditor::Cursor currentCursorPos = view->cursorPosition(); + view->document()->insertText(currentCursorPos, "$"); + view->setCursorPosition(currentCursorPos); + } } void Manager::startLaTeXEnvironment(KTextEditor::View *view) { - if(!view) { - view = m_ki->viewManager()->currentTextView(); - if(!view) { - return; - } - } - - KTextEditor::Cursor cursor = view->cursorPosition(); - QString line = view->document()->line(cursor.line()).left(cursor.column()); - - QRegExp regexp("\\\\b|\\\\be|\\\\beg|\\\\begi|\\\\begin|\\\\begin\\{|\\\\begin\\{([a-zA-z]*)"); - int pos = regexp.lastIndexIn(line); - if(pos >= 0) { - view->document()->replaceText(KTextEditor::Range(cursor.line(), pos, cursor.line(), cursor.column()), "\\begin{"+regexp.cap(1)); - } - else { - // environment completion will start with "\begin{en" when the cursor is placed - // after the following strings: - // en - // x=en - // it en - // =en - // it=en - // en - // but it will start with "\begin{" in the following situations: - // \en - // it\en - // \aen - QRegExp re("(^|[^\\\\A-Za-z])([a-zA-Z]+)$"); - pos = re.indexIn(line); - if(pos >= 0) { - view->document()->replaceText(KTextEditor::Range(cursor.line(), re.pos(2), cursor.line(), cursor.column()), "\\begin{" + re.cap(2)); - } - else { - view->document()->insertText(cursor, "\\begin{"); - } - } - - startLaTeXCompletion(view); + if(!view) { + view = m_ki->viewManager()->currentTextView(); + if(!view) { + return; + } + } + + KTextEditor::Cursor cursor = view->cursorPosition(); + QString line = view->document()->line(cursor.line()).left(cursor.column()); + + QRegExp regexp("\\\\b|\\\\be|\\\\beg|\\\\begi|\\\\begin|\\\\begin\\{|\\\\begin\\{([a-zA-z]*)"); + int pos = regexp.lastIndexIn(line); + if(pos >= 0) { + view->document()->replaceText(KTextEditor::Range(cursor.line(), pos, cursor.line(), cursor.column()), "\\begin{"+regexp.cap(1)); + } + else { + // environment completion will start with "\begin{en" when the cursor is placed + // after the following strings: + // en + // x=en + // it en + // =en + // it=en + // en + // but it will start with "\begin{" in the following situations: + // \en + // it\en + // \aen + QRegExp re("(^|[^\\\\A-Za-z])([a-zA-Z]+)$"); + pos = re.indexIn(line); + if(pos >= 0) { + view->document()->replaceText(KTextEditor::Range(cursor.line(), re.pos(2), cursor.line(), cursor.column()), "\\begin{" + re.cap(2)); + } + else { + view->document()->insertText(cursor, "\\begin{"); + } + } + + startLaTeXCompletion(view); } void Manager::startAbbreviationCompletion(KTextEditor::View *view) { - if(!view) { - view = m_ki->viewManager()->currentTextView(); - if(!view) { - return; - } - } - - KileDocument::TextInfo *textInfo = m_ki->docManager()->textInfoFor(view->document()); - if(!textInfo) { - return; - } - textInfo->startAbbreviationCompletion(view); + if(!view) { + view = m_ki->viewManager()->currentTextView(); + if(!view) { + return; + } + } + + KileDocument::TextInfo *textInfo = m_ki->docManager()->textInfoFor(view->document()); + if(!textInfo) { + return; + } + textInfo->startAbbreviationCompletion(view); } void Manager::buildReferenceCitationRegularExpressions() { - // build list of references - QString references = getCommandsString(KileDocument::CmdAttrReference); - references.replace('*', "\\*"); - m_referencesRegExp.setPattern("^\\\\(" + references + ")\\{"); - m_referencesExtRegExp.setPattern("^\\\\(" + references + ")\\{[^\\{\\}\\\\]+,$"); - - // build list of citations - QString citations = getCommandsString(KileDocument::CmdAttrCitations); - citations.replace('*',"\\*"); - m_citeRegExp.setPattern("^\\\\(((c|C|noc)(ite|itep|itet|itealt|itealp|iteauthor|iteyear|iteyearpar|itetext))" + citations + ")\\{"); - m_citeExtRegExp.setPattern("^\\\\(((c|C|noc)(ite|itep|itet|itealt|itealp|iteauthor|iteyear|iteyearpar|itetext))" + citations + ")\\{[^\\{\\}\\\\]+,$"); + // build list of references + QString references = getCommandsString(KileDocument::CmdAttrReference); + references.replace('*', "\\*"); + m_referencesRegExp.setPattern("^\\\\(" + references + ")\\{"); + m_referencesExtRegExp.setPattern("^\\\\(" + references + ")\\{[^\\{\\}\\\\]+,$"); + + // build list of citations + QString citations = getCommandsString(KileDocument::CmdAttrCitations); + citations.replace('*',"\\*"); + m_citeRegExp.setPattern("^\\\\(((c|C|noc)(ite|itep|itet|itealt|itealp|iteauthor|iteyear|iteyearpar|itetext))" + citations + ")\\{"); + m_citeExtRegExp.setPattern("^\\\\(((c|C|noc)(ite|itep|itet|itealt|itealp|iteauthor|iteyear|iteyearpar|itetext))" + citations + ")\\{[^\\{\\}\\\\]+,$"); } QString Manager::getCommandsString(KileDocument::CmdAttribute attrtype) { - QStringList cmdlist; - QStringList::ConstIterator it; - - // get info about user-defined references - KileDocument::LatexCommands *cmd = m_ki->latexCommands(); - cmd->commandList(cmdlist, attrtype, false); - - // build list of references - QString commands; - for(it = cmdlist.constBegin(); it != cmdlist.constEnd(); ++it) { - if(cmd->isStarredEnv(*it) ) { - commands += '|' + (*it).mid(1) + '*'; - } - commands += '|' + (*it).mid(1); - } - return commands; + QStringList cmdlist; + QStringList::ConstIterator it; + + // get info about user-defined references + KileDocument::LatexCommands *cmd = m_ki->latexCommands(); + cmd->commandList(cmdlist, attrtype, false); + + // build list of references + QString commands; + for(it = cmdlist.constBegin(); it != cmdlist.constEnd(); ++it) { + if(cmd->isStarredEnv(*it) ) { + commands += '|' + (*it).mid(1) + '*'; + } + commands += '|' + (*it).mid(1); + } + return commands; } void Manager::addUserDefinedLaTeXCommands(QStringList &wordlist) { - QStringList cmdlist; - QStringList::ConstIterator it; - KileDocument::LatexCmdAttributes attr; - - // get info about user-defined commands and environments - KileDocument::LatexCommands *cmd = m_ki->latexCommands(); - cmd->commandList(cmdlist, KileDocument::CmdAttrNone, true); - - // add entries to wordlist - for(it = cmdlist.constBegin(); it != cmdlist.constEnd(); ++it) { - if(cmd->commandAttributes(*it, attr)) { - QString command,eos; - QStringList entrylist; - if(attr.type < KileDocument::CmdAttrLabel) { // environment - command = "\\begin{" + (*it); - eos = '}'; - } - else { // command - command = (*it); - // eos.clear(); - } - - // get all possibilities into a stringlist - entrylist.append(command + eos); - if(!attr.option.isEmpty()) { - entrylist.append(command + eos + "[option]"); - } - if(attr.starred) { - entrylist.append(command + '*' + eos); - if (!attr.option.isEmpty()) { - entrylist.append(command + '*' + eos + "[option]"); - } - } - - // finally append entries to wordlist - QStringList::ConstIterator itentry; - for(itentry = entrylist.constBegin(); itentry != entrylist.constEnd(); ++itentry) { - QString entry = (*itentry); - if(!attr.parameter.isEmpty()) { - entry += "{param}"; - } - if(attr.type == KileDocument::CmdAttrList) { - entry += "\\item"; - } - wordlist.append(entry); - } - } - } + QStringList cmdlist; + QStringList::ConstIterator it; + KileDocument::LatexCmdAttributes attr; + + // get info about user-defined commands and environments + KileDocument::LatexCommands *cmd = m_ki->latexCommands(); + cmd->commandList(cmdlist, KileDocument::CmdAttrNone, true); + + // add entries to wordlist + for(it = cmdlist.constBegin(); it != cmdlist.constEnd(); ++it) { + if(cmd->commandAttributes(*it, attr)) { + QString command,eos; + QStringList entrylist; + if(attr.type < KileDocument::CmdAttrLabel) { // environment + command = "\\begin{" + (*it); + eos = '}'; + } + else { // command + command = (*it); + // eos.clear(); + } + + // get all possibilities into a stringlist + entrylist.append(command + eos); + if(!attr.option.isEmpty()) { + entrylist.append(command + eos + "[option]"); + } + if(attr.starred) { + entrylist.append(command + '*' + eos); + if (!attr.option.isEmpty()) { + entrylist.append(command + '*' + eos + "[option]"); + } + } + + // finally append entries to wordlist + QStringList::ConstIterator itentry; + for(itentry = entrylist.constBegin(); itentry != entrylist.constEnd(); ++itentry) { + QString entry = (*itentry); + if(!attr.parameter.isEmpty()) { + entry += "{param}"; + } + if(attr.type == KileDocument::CmdAttrList) { + entry += "\\item"; + } + wordlist.append(entry); + } + } + } } QStringList Manager::readCWLFile(const QString &filename, bool fullPathGiven) { - QStringList toReturn; - QString file = fullPathGiven ? filename : QStandardPaths::locate(QStandardPaths::DataLocation, "complete/" + filename); - if(file.isEmpty()) { - return toReturn; - } - - QFile f(file); - if(f.open(QIODevice::ReadOnly)) { // file opened successfully - QTextStream t(&f); // use a text stream - while(!t.atEnd()) { // until end of file... - QString s = t.readLine().trimmed(); // line of text excluding '\n' - if(!(s.isEmpty() || s.at(0) == '#')) { - toReturn.append(s); - } - } - f.close(); - } - return toReturn; + QStringList toReturn; + QString file = fullPathGiven ? filename : QStandardPaths::locate(QStandardPaths::DataLocation, "complete/" + filename); + if(file.isEmpty()) { + return toReturn; + } + + QFile f(file); + if(f.open(QIODevice::ReadOnly)) { // file opened successfully + QTextStream t(&f); // use a text stream + while(!t.atEnd()) { // until end of file... + QString s = t.readLine().trimmed(); // line of text excluding '\n' + if(!(s.isEmpty() || s.at(0) == '#')) { + toReturn.append(s); + } + } + f.close(); + } + return toReturn; } QStringList Manager::readCWLFiles(const QStringList &files, const QString &dir) { - // read wordlists from files - QStringList wordlist; - for(int i = 0; i < files.count(); ++i) { - QString cwlfile = validCwlFile(files[i]); - if( !cwlfile.isEmpty() ) { - wordlist += readCWLFile(dir + '/' + cwlfile + ".cwl"); - } - } - return wordlist; + // read wordlists from files + QStringList wordlist; + for(int i = 0; i < files.count(); ++i) { + QString cwlfile = validCwlFile(files[i]); + if( !cwlfile.isEmpty() ) { + wordlist += readCWLFile(dir + '/' + cwlfile + ".cwl"); + } + } + return wordlist; } QString Manager::validCwlFile(const QString &filename) { - return (filename.at(0) == '1') ? filename.right( filename.length()-2 ) : QString(); + return (filename.at(0) == '1') ? filename.right( filename.length()-2 ) : QString(); } // find local and global cwl files: global files are not added, // if there is already a local file with this name. We fill a map // with filename as key and filepath as value. static void getCwlFiles(QMap &map, const QString &dir) { - QStringList files = QDir(dir, "*.cwl").entryList(); - for (QStringList::ConstIterator it = files.constBegin(); it != files.constEnd(); ++it) { - QString filename = QFileInfo(*it).fileName(); - if(!map.contains(filename)) { - map[filename] = dir + '/' + (*it); - } - } + QStringList files = QDir(dir, "*.cwl").entryList(); + for (QStringList::ConstIterator it = files.constBegin(); it != files.constEnd(); ++it) { + QString filename = QFileInfo(*it).fileName(); + if(!map.contains(filename)) { + map[filename] = dir + '/' + (*it); + } + } } QMap Manager::getAllCwlFiles(const QString &localCwlPath, const QString &globalCwlPath) { - // get a sorted list of all cwl files from both directories - // Local files are preferred over global ones. - QMap fileMap; - getCwlFiles(fileMap, localCwlPath); - getCwlFiles(fileMap, globalCwlPath); - return fileMap; + // get a sorted list of all cwl files from both directories + // Local files are preferred over global ones. + QMap fileMap; + getCwlFiles(fileMap, localCwlPath); + getCwlFiles(fileMap, globalCwlPath); + return fileMap; } QPair Manager::getCwlBaseDirs() { - QString localDir = QStandardPaths::writableLocation(QStandardPaths::DataLocation) + QLatin1Char('/') + "complete"; - QString globalDir; - - const QStringList dirs = QStandardPaths::locateAll(QStandardPaths::DataLocation, "complete", QStandardPaths::LocateDirectory); - for(QStringList::ConstIterator it = dirs.constBegin(); it != dirs.constEnd(); ++it) { - if((*it) != localDir) { - globalDir = (*it); - break; - } - } - // we ensure that the directory strings end in '/' - if(!localDir.endsWith('/')) { - localDir += '/'; - } - if(!globalDir.endsWith('/')) { - globalDir += '/'; - } - return QPair(localDir, globalDir); + QString localDir = QStandardPaths::writableLocation(QStandardPaths::DataLocation) + QLatin1Char('/') + "complete"; + QString globalDir; + + const QStringList dirs = QStandardPaths::locateAll(QStandardPaths::DataLocation, "complete", QStandardPaths::LocateDirectory); + for(QStringList::ConstIterator it = dirs.constBegin(); it != dirs.constEnd(); ++it) { + if((*it) != localDir) { + globalDir = (*it); + break; + } + } + // we ensure that the directory strings end in '/' + if(!localDir.endsWith('/')) { + localDir += '/'; + } + if(!globalDir.endsWith('/')) { + globalDir += '/'; + } + return QPair(localDir, globalDir); } } diff --git a/src/codecompletion.h b/src/codecompletion.h index 8bd1613f..2c9791bc 100644 --- a/src/codecompletion.h +++ b/src/codecompletion.h @@ -1,189 +1,191 @@ /************************************************************************************************ Copyright (C) 2004-2007 by Holger Danielsson (holger.danielsson@versanet.de) 2008-2014 by Michel Ludwig (michel.ludwig@kdemail.net) ************************************************************************************************/ /*************************************************************************** * * * 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. * * * ***************************************************************************/ #ifndef CODECOMPLETION_H #define CODECOMPLETION_H #include #include #include #include #include #include #include #include #include "latexcmd.h" #include "widgets/abbreviationview.h" //default bullet char (a cross) static const QChar s_bullet_char = QChar(0xd7); static const QString s_bullet = QString(&s_bullet_char, 1); class QTimer; class KileInfo; -namespace KileDocument { class EditorExtension; } +namespace KileDocument { +class EditorExtension; +} namespace KileCodeCompletion { - class Manager; - - class LaTeXCompletionModel : public KTextEditor::CodeCompletionModel, - public KTextEditor::CodeCompletionModelControllerInterface { - Q_OBJECT - Q_INTERFACES(KTextEditor::CodeCompletionModelControllerInterface) - - public: - LaTeXCompletionModel(QObject *parent, KileCodeCompletion::Manager *manager, - KileDocument::EditorExtension *editorExtension); - virtual ~LaTeXCompletionModel(); - virtual QModelIndex index(int row, int column, const QModelIndex &parent=QModelIndex()) const Q_DECL_OVERRIDE; - virtual QVariant data(const QModelIndex& index, int role) const Q_DECL_OVERRIDE; - virtual int rowCount(const QModelIndex &parent = QModelIndex()) const Q_DECL_OVERRIDE; - - virtual bool shouldStartCompletion(KTextEditor::View *view, const QString &insertedText, - bool userInsertion, const KTextEditor::Cursor &position) Q_DECL_OVERRIDE; - virtual bool shouldAbortCompletion(KTextEditor::View *view, const KTextEditor::Range &range, - const QString ¤tCompletion) Q_DECL_OVERRIDE; - virtual void completionInvoked(KTextEditor::View *view, const KTextEditor::Range &range, - InvocationType invocationType) Q_DECL_OVERRIDE; - virtual KTextEditor::Range updateCompletionRange(KTextEditor::View *view, - const KTextEditor::Range& range) Q_DECL_OVERRIDE; - virtual KTextEditor::Range completionRange(KTextEditor::View *view, - const KTextEditor::Cursor &position) Q_DECL_OVERRIDE; - virtual QString filterString(KTextEditor::View *view, - const KTextEditor::Range &range, - const KTextEditor::Cursor &position) Q_DECL_OVERRIDE; - - virtual void executeCompletionItem(KTextEditor::View *view, const KTextEditor::Range& word, - const QModelIndex &index) const Q_DECL_OVERRIDE; - QString filterLatexCommand(const QString &text, int &cursorYPos, int &cursorXPos); - - - protected: - KileCodeCompletion::Manager *m_codeCompletionManager; - KileDocument::EditorExtension *m_editorExtension; - QStringList m_completionList; - KTextEditor::View *m_currentView; - - void buildModel(KTextEditor::View *view, const KTextEditor::Range &r); - void filterModel(const QString& text); - - QString stripParameters(const QString &text) const; - QString buildRegularCompletedText(const QString &text, int &cursorYPos, int &cursorXPos, - bool checkGroup) const; - QString buildEnvironmentCompletedText(const QString &text, const QString &prefix, - int &ypos, int &xpos) const; - QString buildWhiteSpaceString(const QString &s) const; - KTextEditor::Cursor determineLaTeXCommandStart(KTextEditor::Document *doc, - const KTextEditor::Cursor& position) const; - bool isWithinLaTeXCommand(KTextEditor::Document *doc, const KTextEditor::Cursor& commandStart, - const KTextEditor::Cursor& cursorPosition) const; - }; - - class AbbreviationCompletionModel : public KTextEditor::CodeCompletionModel, public KTextEditor::CodeCompletionModelControllerInterface { - Q_OBJECT - Q_INTERFACES(KTextEditor::CodeCompletionModelControllerInterface) - - public: - AbbreviationCompletionModel(QObject *parent, KileAbbreviation::Manager *manager); - virtual ~AbbreviationCompletionModel(); - - virtual QModelIndex index(int row, int column, const QModelIndex &parent=QModelIndex()) const Q_DECL_OVERRIDE; - virtual QVariant data(const QModelIndex& index, int role) const Q_DECL_OVERRIDE; - virtual int rowCount(const QModelIndex &parent = QModelIndex()) const Q_DECL_OVERRIDE; - - virtual bool shouldStartCompletion(KTextEditor::View *view, const QString &insertedText, - bool userInsertion, const KTextEditor::Cursor &position) Q_DECL_OVERRIDE; - virtual bool shouldAbortCompletion(KTextEditor::View *view, const KTextEditor::Range &range, - const QString ¤tCompletion) Q_DECL_OVERRIDE; - virtual void completionInvoked(KTextEditor::View *view, const KTextEditor::Range &range, - InvocationType invocationType) Q_DECL_OVERRIDE; - virtual KTextEditor::Range updateCompletionRange(KTextEditor::View *view, - const KTextEditor::Range& range) Q_DECL_OVERRIDE; - virtual KTextEditor::Range completionRange(KTextEditor::View *view, - const KTextEditor::Cursor &position) Q_DECL_OVERRIDE; - virtual QString filterString(KTextEditor::View *view, - const KTextEditor::Range &range, - const KTextEditor::Cursor &position) Q_DECL_OVERRIDE; - - virtual void executeCompletionItem(KTextEditor::View *view, const KTextEditor::Range& word, - const QModelIndex &index) const Q_DECL_OVERRIDE; - - protected: - KileAbbreviation::Manager *m_abbreviationManager; - QStringList m_completionList; - KTextEditor::View *m_currentView; - - /** - * 'singleMatchMode' should be set to true for manual invocations of this completion model; - * it triggers an immediate substitution of a matching abbreviation even if there is a longer - * abbreviation match, e.g. for two abbreviations 'a' -> 'x1' and 'ab' -> 'x2', 'singleMatchMode' - * will immediately replace 'a' with 'x1' if 'a' has been entered by the user. - **/ - void buildModel(KTextEditor::View *view, const KTextEditor::Range &r, bool singleMatchMode = false); - }; - - class Manager : public QObject { - Q_OBJECT - friend class LaTeXCompletionModel; - - public: - Manager(KileInfo *info, QObject *parent); - virtual ~Manager(); - - QStringList getLaTeXCommands() const; - QStringList getLocallyDefinedLaTeXCommands(KTextEditor::View *view) const; - - void readConfig(KConfig *config); - - QStringList readCWLFile(const QString &filename, bool fullPathGiven = false); - QStringList readCWLFiles(const QStringList &files, const QString &dir); - QString validCwlFile(const QString &filename); - - /** - * A map from file names to paths is returned. - */ - static QMap getAllCwlFiles(const QString &localCwlPath, const QString &globalCwlPath); - /** - * Returns a pair (local CWL base dir, global CWL base dir). - */ - static QPair getCwlBaseDirs(); - - public Q_SLOTS: - void startLaTeXCompletion(KTextEditor::View *view = Q_NULLPTR); - void startLaTeXEnvironment(KTextEditor::View *view = Q_NULLPTR); - void startAbbreviationCompletion(KTextEditor::View *view = Q_NULLPTR); - - void textInserted(KTextEditor::View* view, const KTextEditor::Cursor& position, const QString & text); - - protected: - KileInfo* m_ki; - QStringList m_texWordList, m_dictWordList, m_abbrevWordList; - bool m_firstConfig; - QRegExp m_referencesRegExp; - QRegExp m_referencesExtRegExp; - QRegExp m_citeRegExp; - QRegExp m_citeExtRegExp; - - void addUserDefinedLaTeXCommands(QStringList &wordlist); - void buildReferenceCitationRegularExpressions(); - QString getCommandsString(KileDocument::CmdAttribute attrtype); +class Manager; + +class LaTeXCompletionModel : public KTextEditor::CodeCompletionModel, + public KTextEditor::CodeCompletionModelControllerInterface { + Q_OBJECT + Q_INTERFACES(KTextEditor::CodeCompletionModelControllerInterface) + +public: + LaTeXCompletionModel(QObject *parent, KileCodeCompletion::Manager *manager, + KileDocument::EditorExtension *editorExtension); + virtual ~LaTeXCompletionModel(); + virtual QModelIndex index(int row, int column, const QModelIndex &parent=QModelIndex()) const Q_DECL_OVERRIDE; + virtual QVariant data(const QModelIndex& index, int role) const Q_DECL_OVERRIDE; + virtual int rowCount(const QModelIndex &parent = QModelIndex()) const Q_DECL_OVERRIDE; + + virtual bool shouldStartCompletion(KTextEditor::View *view, const QString &insertedText, + bool userInsertion, const KTextEditor::Cursor &position) Q_DECL_OVERRIDE; + virtual bool shouldAbortCompletion(KTextEditor::View *view, const KTextEditor::Range &range, + const QString ¤tCompletion) Q_DECL_OVERRIDE; + virtual void completionInvoked(KTextEditor::View *view, const KTextEditor::Range &range, + InvocationType invocationType) Q_DECL_OVERRIDE; + virtual KTextEditor::Range updateCompletionRange(KTextEditor::View *view, + const KTextEditor::Range& range) Q_DECL_OVERRIDE; + virtual KTextEditor::Range completionRange(KTextEditor::View *view, + const KTextEditor::Cursor &position) Q_DECL_OVERRIDE; + virtual QString filterString(KTextEditor::View *view, + const KTextEditor::Range &range, + const KTextEditor::Cursor &position) Q_DECL_OVERRIDE; + + virtual void executeCompletionItem(KTextEditor::View *view, const KTextEditor::Range& word, + const QModelIndex &index) const Q_DECL_OVERRIDE; + QString filterLatexCommand(const QString &text, int &cursorYPos, int &cursorXPos); + + +protected: + KileCodeCompletion::Manager *m_codeCompletionManager; + KileDocument::EditorExtension *m_editorExtension; + QStringList m_completionList; + KTextEditor::View *m_currentView; + + void buildModel(KTextEditor::View *view, const KTextEditor::Range &r); + void filterModel(const QString& text); + + QString stripParameters(const QString &text) const; + QString buildRegularCompletedText(const QString &text, int &cursorYPos, int &cursorXPos, + bool checkGroup) const; + QString buildEnvironmentCompletedText(const QString &text, const QString &prefix, + int &ypos, int &xpos) const; + QString buildWhiteSpaceString(const QString &s) const; + KTextEditor::Cursor determineLaTeXCommandStart(KTextEditor::Document *doc, + const KTextEditor::Cursor& position) const; + bool isWithinLaTeXCommand(KTextEditor::Document *doc, const KTextEditor::Cursor& commandStart, + const KTextEditor::Cursor& cursorPosition) const; +}; + +class AbbreviationCompletionModel : public KTextEditor::CodeCompletionModel, public KTextEditor::CodeCompletionModelControllerInterface { + Q_OBJECT + Q_INTERFACES(KTextEditor::CodeCompletionModelControllerInterface) + +public: + AbbreviationCompletionModel(QObject *parent, KileAbbreviation::Manager *manager); + virtual ~AbbreviationCompletionModel(); + + virtual QModelIndex index(int row, int column, const QModelIndex &parent=QModelIndex()) const Q_DECL_OVERRIDE; + virtual QVariant data(const QModelIndex& index, int role) const Q_DECL_OVERRIDE; + virtual int rowCount(const QModelIndex &parent = QModelIndex()) const Q_DECL_OVERRIDE; + + virtual bool shouldStartCompletion(KTextEditor::View *view, const QString &insertedText, + bool userInsertion, const KTextEditor::Cursor &position) Q_DECL_OVERRIDE; + virtual bool shouldAbortCompletion(KTextEditor::View *view, const KTextEditor::Range &range, + const QString ¤tCompletion) Q_DECL_OVERRIDE; + virtual void completionInvoked(KTextEditor::View *view, const KTextEditor::Range &range, + InvocationType invocationType) Q_DECL_OVERRIDE; + virtual KTextEditor::Range updateCompletionRange(KTextEditor::View *view, + const KTextEditor::Range& range) Q_DECL_OVERRIDE; + virtual KTextEditor::Range completionRange(KTextEditor::View *view, + const KTextEditor::Cursor &position) Q_DECL_OVERRIDE; + virtual QString filterString(KTextEditor::View *view, + const KTextEditor::Range &range, + const KTextEditor::Cursor &position) Q_DECL_OVERRIDE; + + virtual void executeCompletionItem(KTextEditor::View *view, const KTextEditor::Range& word, + const QModelIndex &index) const Q_DECL_OVERRIDE; + +protected: + KileAbbreviation::Manager *m_abbreviationManager; + QStringList m_completionList; + KTextEditor::View *m_currentView; + + /** + * 'singleMatchMode' should be set to true for manual invocations of this completion model; + * it triggers an immediate substitution of a matching abbreviation even if there is a longer + * abbreviation match, e.g. for two abbreviations 'a' -> 'x1' and 'ab' -> 'x2', 'singleMatchMode' + * will immediately replace 'a' with 'x1' if 'a' has been entered by the user. + **/ + void buildModel(KTextEditor::View *view, const KTextEditor::Range &r, bool singleMatchMode = false); +}; + +class Manager : public QObject { + Q_OBJECT + friend class LaTeXCompletionModel; + +public: + Manager(KileInfo *info, QObject *parent); + virtual ~Manager(); + + QStringList getLaTeXCommands() const; + QStringList getLocallyDefinedLaTeXCommands(KTextEditor::View *view) const; + + void readConfig(KConfig *config); + + QStringList readCWLFile(const QString &filename, bool fullPathGiven = false); + QStringList readCWLFiles(const QStringList &files, const QString &dir); + QString validCwlFile(const QString &filename); + + /** + * A map from file names to paths is returned. + */ + static QMap getAllCwlFiles(const QString &localCwlPath, const QString &globalCwlPath); + /** + * Returns a pair (local CWL base dir, global CWL base dir). + */ + static QPair getCwlBaseDirs(); + +public Q_SLOTS: + void startLaTeXCompletion(KTextEditor::View *view = Q_NULLPTR); + void startLaTeXEnvironment(KTextEditor::View *view = Q_NULLPTR); + void startAbbreviationCompletion(KTextEditor::View *view = Q_NULLPTR); + + void textInserted(KTextEditor::View* view, const KTextEditor::Cursor& position, const QString & text); + +protected: + KileInfo* m_ki; + QStringList m_texWordList, m_dictWordList, m_abbrevWordList; + bool m_firstConfig; + QRegExp m_referencesRegExp; + QRegExp m_referencesExtRegExp; + QRegExp m_citeRegExp; + QRegExp m_citeExtRegExp; + + void addUserDefinedLaTeXCommands(QStringList &wordlist); + void buildReferenceCitationRegularExpressions(); + QString getCommandsString(KileDocument::CmdAttribute attrtype); }; } #endif diff --git a/src/configtester.cpp b/src/configtester.cpp index 42ddadae..b3c2e1b6 100644 --- a/src/configtester.cpp +++ b/src/configtester.cpp @@ -1,809 +1,809 @@ /************************************************************************************* Copyright (C) 2004 by Jeroen Wijnhout (Jeroen.Wijnhout@kdemail.net) 2012 by Michel Ludwig (michel.ludwig@kdemail.net) *************************************************************************************/ /*************************************************************************** * * * 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. * * * ***************************************************************************/ #include "configtester.h" #include #include #include #include #include #include #include #include #include #include #include "documentinfo.h" #include "kiledebug.h" #include "kiledocmanager.h" #include "kiletoolmanager.h" #include "kileinfo.h" #include "kileconfig.h" #include "kiletool.h" #include "kiletool_enums.h" #include "kileversion.h" ConfigTest::ConfigTest(const QString& testGroup, const QString &name, bool isCritical) - : m_testGroup(testGroup) - , m_name(name) - , m_isCritical(isCritical) - , m_isSilent(false) - , m_status(NotRun) + : m_testGroup(testGroup) + , m_name(name) + , m_isCritical(isCritical) + , m_isSilent(false) + , m_status(NotRun) { } ConfigTest::~ConfigTest() { } int ConfigTest::status() const { - return m_status; + return m_status; } QString ConfigTest::name() const { - return m_name; + return m_name; } QString ConfigTest::testGroup() const { - return m_testGroup; + return m_testGroup; } QString ConfigTest::resultText() const { - return m_resultText; + return m_resultText; } void ConfigTest::addDependency(ConfigTest *test) { - m_dependencyTestList.push_back(test); + m_dependencyTestList.push_back(test); } bool ConfigTest::allDependenciesSucceeded() const { - Q_FOREACH(ConfigTest *test, m_dependencyTestList) { - if(test->status() != Success) { - return false; - } - } - return true; + Q_FOREACH(ConfigTest *test, m_dependencyTestList) { + if(test->status() != Success) { + return false; + } + } + return true; } bool ConfigTest::isCritical() const { - return m_isCritical; + return m_isCritical; } bool ConfigTest::isSilent() const { - return m_isSilent; + return m_isSilent; } void ConfigTest::setSilent(bool b) { - m_isSilent = b; + m_isSilent = b; } void ConfigTest::setName(const QString& name) { - m_name = name; + m_name = name; } Tester::Tester(KileInfo *kileInfo, QObject *parent) -: QObject(parent), - m_ki(kileInfo), - m_tempDir(Q_NULLPTR), - m_testsDone(0) + : QObject(parent), + m_ki(kileInfo), + m_tempDir(Q_NULLPTR), + m_testsDone(0) { - m_tempDir = new QTemporaryDir(); + m_tempDir = new QTemporaryDir(); - setupTests(); - m_nextTestIterator = m_testList.begin(); + setupTests(); + m_nextTestIterator = m_testList.begin(); } Tester::~Tester() { - if (m_tempDir) m_tempDir->remove(); - delete m_tempDir; - qDeleteAll(m_testList); + if (m_tempDir) m_tempDir->remove(); + delete m_tempDir; + qDeleteAll(m_testList); } void Tester::runTests() { - const QString& destinationDirectory = m_tempDir->path(); - const QString& testDirectory = + const QString& destinationDirectory = m_tempDir->path(); + const QString& testDirectory = #ifdef Q_OS_WIN QStandardPaths::locate(QStandardPaths::AppDataLocation, "kile/test", QStandardPaths::LocateDirectory); #else QStandardPaths::locate(QStandardPaths::AppDataLocation, "test", QStandardPaths::LocateDirectory); #endif - KIO::CopyJob *copyJob = KIO::copyAs(QUrl::fromLocalFile(testDirectory), QUrl::fromLocalFile(destinationDirectory), KIO::HideProgressInfo | KIO::Overwrite); - connect(copyJob, SIGNAL(result(KJob*)), this, SLOT(handleFileCopyResult(KJob*))); - emit(percentageDone(0)); + KIO::CopyJob *copyJob = KIO::copyAs(QUrl::fromLocalFile(testDirectory), QUrl::fromLocalFile(destinationDirectory), KIO::HideProgressInfo | KIO::Overwrite); + connect(copyJob, SIGNAL(result(KJob*)), this, SLOT(handleFileCopyResult(KJob*))); + emit(percentageDone(0)); } void Tester::handleFileCopyResult(KJob* job) { - if(job->error()) { - emit(finished(false)); - } - else { - startNextTest(); - } + if(job->error()) { + emit(finished(false)); + } + else { + startNextTest(); + } } void Tester::addResult(const QString &tool, ConfigTest* testResult) { - m_results[tool].push_back(testResult); + m_results[tool].push_back(testResult); } QStringList Tester::testGroups() { - return m_results.keys(); + return m_results.keys(); } QList Tester::resultForGroup(const QString & tool) { - return m_results[tool]; + return m_results[tool]; } // 'isCritical' is set to true iff one tool that failed was critical int Tester::statusForGroup(const QString &testGroup, bool *isCritical) { - if(isCritical) { - *isCritical = false; - } - QList tests = m_results[testGroup]; - int status = ConfigTest::Success; - for(int i = 0; i < tests.count(); ++i) { - if(tests[i]->status() == ConfigTest::Failure) { - if(isCritical && tests[i]->isCritical()) { - *isCritical = true; - } - status = ConfigTest::Failure; - } - } - return status; + if(isCritical) { + *isCritical = false; + } + QList tests = m_results[testGroup]; + int status = ConfigTest::Success; + for(int i = 0; i < tests.count(); ++i) { + if(tests[i]->status() == ConfigTest::Failure) { + if(isCritical && tests[i]->isCritical()) { + *isCritical = true; + } + status = ConfigTest::Failure; + } + } + return status; } void Tester::startNextTest() { - KILE_DEBUG_MAIN; - if(m_nextTestIterator != m_testList.end()) { - m_currentTest = *m_nextTestIterator; - ++m_nextTestIterator; - if(!m_currentTest->allDependenciesSucceeded()) { - QTimer::singleShot(0, this, SLOT(startNextTest())); - return; - } - // we want events to be handled inbetween tests -> QueuedConnection - connect(m_currentTest, SIGNAL(testComplete(ConfigTest*)), this, SLOT(handleTestComplete(ConfigTest*)), Qt::QueuedConnection); - m_currentTest->call(); - } - else { - emit(percentageDone(100)); - emit(finished(true)); - } + KILE_DEBUG_MAIN; + if(m_nextTestIterator != m_testList.end()) { + m_currentTest = *m_nextTestIterator; + ++m_nextTestIterator; + if(!m_currentTest->allDependenciesSucceeded()) { + QTimer::singleShot(0, this, SLOT(startNextTest())); + return; + } + // we want events to be handled inbetween tests -> QueuedConnection + connect(m_currentTest, SIGNAL(testComplete(ConfigTest*)), this, SLOT(handleTestComplete(ConfigTest*)), Qt::QueuedConnection); + m_currentTest->call(); + } + else { + emit(percentageDone(100)); + emit(finished(true)); + } } void Tester::handleTestComplete(ConfigTest *test) { - KILE_DEBUG_MAIN; - if(!test->isSilent()) { - addResult(test->testGroup(), test); - } - ++m_testsDone; - emit(percentageDone((m_testsDone / (float) m_testList.size()) * 100.0)); - startNextTest(); + KILE_DEBUG_MAIN; + if(!test->isSilent()) { + addResult(test->testGroup(), test); + } + ++m_testsDone; + emit(percentageDone((m_testsDone / (float) m_testList.size()) * 100.0)); + startNextTest(); } TestToolInKileTest::TestToolInKileTest(const QString& testGroup, KileInfo *kileInfo, const QString& toolName, - const QString& filePath, - bool isCritical) -: ConfigTest(testGroup, i18n("Running in Kile"), isCritical), - m_ki(kileInfo), - m_toolName(toolName), - m_filePath(filePath) + const QString& filePath, + bool isCritical) + : ConfigTest(testGroup, i18n("Running in Kile"), isCritical), + m_ki(kileInfo), + m_toolName(toolName), + m_filePath(filePath) { } TestToolInKileTest::~TestToolInKileTest() { } void TestToolInKileTest::call() { - KileDocument::TextInfo *textInfo = m_ki->docManager()->fileOpen(QUrl::fromLocalFile(m_filePath)); - if(!textInfo) { - reportFailure(); - return; - } - m_documentUrl = textInfo->url(); - - KileTool::Base *tool = m_ki->toolManager()->createTool(m_toolName, QString(), false); - if(!tool) { - m_ki->docManager()->fileClose(m_documentUrl); - m_status = Failure; - m_resultText = i18n("Tool not found.\n" - "Kile is not configured correctly. Go to Settings->Configure Kile->Tools " - "and either fix the problem or change to the default settings." - ); - emit(testComplete(this)); - return; - } - // We don't want the tool to spawn subtools (especially, for LaTeX-style tools). - // If we did, we might come into the situation that a subtool is launched before the - // parsing is complete, which could trigger a "root document not found" error message. - tool->setEntry("autoRun", "no"); - connect(tool, SIGNAL(done(KileTool::Base*,int,bool)), this, SLOT(handleToolExit(KileTool::Base*,int,bool)), Qt::UniqueConnection); - connect(tool, SIGNAL(failedToRun(KileTool::Base*, int)), this, SLOT(reportFailure())); - m_ki->toolManager()->run(tool); + KileDocument::TextInfo *textInfo = m_ki->docManager()->fileOpen(QUrl::fromLocalFile(m_filePath)); + if(!textInfo) { + reportFailure(); + return; + } + m_documentUrl = textInfo->url(); + + KileTool::Base *tool = m_ki->toolManager()->createTool(m_toolName, QString(), false); + if(!tool) { + m_ki->docManager()->fileClose(m_documentUrl); + m_status = Failure; + m_resultText = i18n("Tool not found.\n" + "Kile is not configured correctly. Go to Settings->Configure Kile->Tools " + "and either fix the problem or change to the default settings." + ); + emit(testComplete(this)); + return; + } + // We don't want the tool to spawn subtools (especially, for LaTeX-style tools). + // If we did, we might come into the situation that a subtool is launched before the + // parsing is complete, which could trigger a "root document not found" error message. + tool->setEntry("autoRun", "no"); + connect(tool, SIGNAL(done(KileTool::Base*,int,bool)), this, SLOT(handleToolExit(KileTool::Base*,int,bool)), Qt::UniqueConnection); + connect(tool, SIGNAL(failedToRun(KileTool::Base*, int)), this, SLOT(reportFailure())); + m_ki->toolManager()->run(tool); } void TestToolInKileTest::reportSuccess() { - m_ki->docManager()->fileClose(m_documentUrl); - m_documentUrl.clear(); + m_ki->docManager()->fileClose(m_documentUrl); + m_documentUrl.clear(); - m_status = Success; - m_resultText = i18n("Passed"); - emit(testComplete(this)); + m_status = Success; + m_resultText = i18n("Passed"); + emit(testComplete(this)); } void TestToolInKileTest::reportFailure() { - m_ki->docManager()->fileClose(m_documentUrl); - m_documentUrl.clear(); + m_ki->docManager()->fileClose(m_documentUrl); + m_documentUrl.clear(); - m_status = Failure; - m_resultText = i18n("Failed"); - emit(testComplete(this)); + m_status = Failure; + m_resultText = i18n("Failed"); + emit(testComplete(this)); } void TestToolInKileTest::handleToolExit(KileTool::Base *tool, int status, bool childToolSpawned) { - Q_UNUSED(tool); - Q_UNUSED(childToolSpawned); + Q_UNUSED(tool); + Q_UNUSED(childToolSpawned); - if(status == KileTool::Success) { - reportSuccess(); - } - else { - reportFailure(); - } + if(status == KileTool::Success) { + reportSuccess(); + } + else { + reportFailure(); + } } OkularVersionTest::OkularVersionTest(const QString& testGroup, bool isCritical) - : ConfigTest(testGroup, i18n("Version"), isCritical) + : ConfigTest(testGroup, i18n("Version"), isCritical) { } OkularVersionTest::~OkularVersionTest() { } void OkularVersionTest::call() { - KPluginLoader pluginLoader(OKULAR_LIBRARY_NAME); - KPluginFactory *factory = pluginLoader.factory(); - if (!factory) { - m_status = Failure; - } - else { - m_status = Success; - quint32 version = pluginLoader.pluginVersion(); - m_resultText = i18n("%1 - Forward Search is supported", version); - } + KPluginLoader pluginLoader(OKULAR_LIBRARY_NAME); + KPluginFactory *factory = pluginLoader.factory(); + if (!factory) { + m_status = Failure; + } + else { + m_status = Success; + quint32 version = pluginLoader.pluginVersion(); + m_resultText = i18n("%1 - Forward Search is supported", version); + } - emit(testComplete(this)); + emit(testComplete(this)); } FindProgramTest::FindProgramTest(const QString& testGroup, const QString& programName, bool isCritical) -: ConfigTest(testGroup, i18n("Binary"), isCritical), - m_programName(programName) + : ConfigTest(testGroup, i18n("Binary"), isCritical), + m_programName(programName) { } FindProgramTest::~FindProgramTest() { } void FindProgramTest::call() { - QString execPath = QStandardPaths::findExecutable(m_programName); + QString execPath = QStandardPaths::findExecutable(m_programName); #ifdef Q_OS_WIN - if(execPath.isEmpty()) { - execPath = QStandardPaths::findExecutable(m_programName, QStringList(QCoreApplication::applicationDirPath())); - } + if(execPath.isEmpty()) { + execPath = QStandardPaths::findExecutable(m_programName, QStringList(QCoreApplication::applicationDirPath())); + } #endif - bool thisIsWindowsConvertExe = false; + bool thisIsWindowsConvertExe = false; #ifdef Q_OS_WIN - QFileInfo execPathInfo(execPath); - thisIsWindowsConvertExe = (m_programName == "convert") && (execPathInfo.dir().dirName() == "system32"); + QFileInfo execPathInfo(execPath); + thisIsWindowsConvertExe = (m_programName == "convert") && (execPathInfo.dir().dirName() == "system32"); #endif - if(execPath.isEmpty() || thisIsWindowsConvertExe) { - m_status = Failure; - if(!m_additionalFailureMessage.isEmpty()) { - if(isCritical()) { - m_resultText = i18nc("additional failure message given as argument", - "Could not find the binary for this essential tool. %1", m_additionalFailureMessage); - } - else { - m_resultText = i18nc("additional failure message given as argument", - "No executable '%1' found. %2", m_programName, m_additionalFailureMessage); - } - } - else { - if(isCritical()) { - m_resultText = i18n("Could not find the binary for this essential tool"); - } - else { - m_resultText = i18n("No executable '%1' found", m_programName); - } - } - } - else { - m_status = Success; - m_resultText = i18nc("executable => path", "Found (%1 => %2)", m_programName, execPath); - } - emit(testComplete(this)); + if(execPath.isEmpty() || thisIsWindowsConvertExe) { + m_status = Failure; + if(!m_additionalFailureMessage.isEmpty()) { + if(isCritical()) { + m_resultText = i18nc("additional failure message given as argument", + "Could not find the binary for this essential tool. %1", m_additionalFailureMessage); + } + else { + m_resultText = i18nc("additional failure message given as argument", + "No executable '%1' found. %2", m_programName, m_additionalFailureMessage); + } + } + else { + if(isCritical()) { + m_resultText = i18n("Could not find the binary for this essential tool"); + } + else { + m_resultText = i18n("No executable '%1' found", m_programName); + } + } + } + else { + m_status = Success; + m_resultText = i18nc("executable => path", "Found (%1 => %2)", m_programName, execPath); + } + emit(testComplete(this)); } void FindProgramTest::setAdditionalFailureMessage(const QString& s) { - m_additionalFailureMessage = s; + m_additionalFailureMessage = s; } ProgramTest::ProgramTest(const QString& testGroup, const QString& programName, const QString& workingDir, - const QString& arg0, - const QString& arg1, - const QString& arg2, - bool isCritical) -: ConfigTest(testGroup, i18n("Simple Test"), isCritical), - m_testProcess(Q_NULLPTR), - m_programName(programName), - m_workingDir(workingDir), - m_arg0(arg0), - m_arg1(arg1), - m_arg2(arg2) + const QString& arg0, + const QString& arg1, + const QString& arg2, + bool isCritical) + : ConfigTest(testGroup, i18n("Simple Test"), isCritical), + m_testProcess(Q_NULLPTR), + m_programName(programName), + m_workingDir(workingDir), + m_arg0(arg0), + m_arg1(arg1), + m_arg2(arg2) { } ProgramTest::~ProgramTest() { - delete m_testProcess; + delete m_testProcess; } void ProgramTest::call() { - m_testProcess = new KProcess(); - m_testProcess->setWorkingDirectory(m_workingDir); - QStringList argList; - if(!m_arg0.isEmpty()) { - argList << m_arg0; - } - if(!m_arg1.isEmpty()) { - argList << m_arg1; - } - if(!m_arg2.isEmpty()) { - argList << m_arg2; - } - m_testProcess->setProgram(m_programName, argList); - if (!KileConfig::teXPaths().isEmpty()) { - m_testProcess->setEnv("TEXINPUTS", KileInfo::expandEnvironmentVars(KileConfig::teXPaths() + ":$TEXINPUTS")); - } - connect(m_testProcess, SIGNAL(finished(int,QProcess::ExitStatus)), - this, SLOT(handleTestProcessFinished(int,QProcess::ExitStatus))); - connect(m_testProcess, SIGNAL(error(QProcess::ProcessError)), - this, SLOT(handleTestProcessError(QProcess::ProcessError))); - m_testProcess->start(); + m_testProcess = new KProcess(); + m_testProcess->setWorkingDirectory(m_workingDir); + QStringList argList; + if(!m_arg0.isEmpty()) { + argList << m_arg0; + } + if(!m_arg1.isEmpty()) { + argList << m_arg1; + } + if(!m_arg2.isEmpty()) { + argList << m_arg2; + } + m_testProcess->setProgram(m_programName, argList); + if (!KileConfig::teXPaths().isEmpty()) { + m_testProcess->setEnv("TEXINPUTS", KileInfo::expandEnvironmentVars(KileConfig::teXPaths() + ":$TEXINPUTS")); + } + connect(m_testProcess, SIGNAL(finished(int,QProcess::ExitStatus)), + this, SLOT(handleTestProcessFinished(int,QProcess::ExitStatus))); + connect(m_testProcess, SIGNAL(error(QProcess::ProcessError)), + this, SLOT(handleTestProcessError(QProcess::ProcessError))); + m_testProcess->start(); } void ProgramTest::handleTestProcessFinished(int exitCode, QProcess::ExitStatus exitStatus) { - m_testProcess->deleteLater(); - m_testProcess = Q_NULLPTR; + m_testProcess->deleteLater(); + m_testProcess = Q_NULLPTR; - if(exitStatus == QProcess::NormalExit && exitCode == 0) { - processFinishedSuccessfully(); - } - else { - reportFailure(); - } + if(exitStatus == QProcess::NormalExit && exitCode == 0) { + processFinishedSuccessfully(); + } + else { + reportFailure(); + } } void ProgramTest::processFinishedSuccessfully() { - reportSuccess(); + reportSuccess(); } void ProgramTest::handleTestProcessError(QProcess::ProcessError error) { - Q_UNUSED(error); + Q_UNUSED(error); - m_testProcess->deleteLater(); - m_testProcess = Q_NULLPTR; - reportFailure(); + m_testProcess->deleteLater(); + m_testProcess = Q_NULLPTR; + reportFailure(); } void ProgramTest::reportSuccess() { - m_resultText = i18n("Passed"); - m_status = Success; - emit(testComplete(this)); + m_resultText = i18n("Passed"); + m_status = Success; + emit(testComplete(this)); } void ProgramTest::reportFailure() { - if(isCritical()) { - m_resultText = i18n("This essential tool does not work; please check your installation."); - } - else { - m_resultText = i18n("Failed"); - } - m_status = Failure; - emit(testComplete(this)); + if(isCritical()) { + m_resultText = i18n("This essential tool does not work; please check your installation."); + } + else { + m_resultText = i18n("Failed"); + } + m_status = Failure; + emit(testComplete(this)); } LaTeXSrcSpecialsSupportTest::LaTeXSrcSpecialsSupportTest(const QString& testGroup, const QString& workingDir, - const QString& fileBaseName) -: ProgramTest(testGroup, "latex", workingDir, "-src-specials", "--interaction=nonstopmode", fileBaseName + ".tex", false), - m_fileBaseName(fileBaseName) + const QString& fileBaseName) + : ProgramTest(testGroup, "latex", workingDir, "-src-specials", "--interaction=nonstopmode", fileBaseName + ".tex", false), + m_fileBaseName(fileBaseName) { - setName(i18n("Source Specials Switch")); + setName(i18n("Source Specials Switch")); } LaTeXSrcSpecialsSupportTest::~LaTeXSrcSpecialsSupportTest() { } void LaTeXSrcSpecialsSupportTest::processFinishedSuccessfully() { - // before we can report success, we still have to perform the - // following check: - // src-specials are supported if the created file contains source - // information (LaTeX doesn't report unknown command line flags as - // errors). Hence, we now check whether the created file contains - // the string 'src:'. - QFile file(m_workingDir + '/' + m_fileBaseName + ".dvi"); - if (!file.open(QIODevice::ReadOnly)) { - reportFailure(); - return; - } - // we read everything as it's a small file - QByteArray array = file.readAll(); - file.close(); - if(!array.contains("src:")) { - reportFailure(); - return; - } - reportSuccess(); + // before we can report success, we still have to perform the + // following check: + // src-specials are supported if the created file contains source + // information (LaTeX doesn't report unknown command line flags as + // errors). Hence, we now check whether the created file contains + // the string 'src:'. + QFile file(m_workingDir + '/' + m_fileBaseName + ".dvi"); + if (!file.open(QIODevice::ReadOnly)) { + reportFailure(); + return; + } + // we read everything as it's a small file + QByteArray array = file.readAll(); + file.close(); + if(!array.contains("src:")) { + reportFailure(); + return; + } + reportSuccess(); } void LaTeXSrcSpecialsSupportTest::reportSuccess() { - m_resultText = i18n("Supported, use the 'Modern' configuration for (La)TeX to auto-enable inverse and forward search capabilities."); - m_status = Success; - emit(testComplete(this)); + m_resultText = i18n("Supported, use the 'Modern' configuration for (La)TeX to auto-enable inverse and forward search capabilities."); + m_status = Success; + emit(testComplete(this)); } void LaTeXSrcSpecialsSupportTest::reportFailure() { - m_resultText = i18n("Not supported, use the srcltx package to enable the inverse and forward search capabilities."); - m_status = Failure; - emit(testComplete(this)); + m_resultText = i18n("Not supported, use the srcltx package to enable the inverse and forward search capabilities."); + m_status = Failure; + emit(testComplete(this)); } SyncTeXSupportTest::SyncTeXSupportTest(const QString& testGroup, const QString& toolName, const QString& workingDir, - const QString& fileBaseName) -: ProgramTest(testGroup, toolName, workingDir, "-synctex=1", "--interaction=nonstopmode", fileBaseName + ".tex", false), - m_fileBaseName(fileBaseName) + const QString& fileBaseName) + : ProgramTest(testGroup, toolName, workingDir, "-synctex=1", "--interaction=nonstopmode", fileBaseName + ".tex", false), + m_fileBaseName(fileBaseName) { - setName(i18n("SyncTeX Support")); + setName(i18n("SyncTeX Support")); } SyncTeXSupportTest::~SyncTeXSupportTest() { } void SyncTeXSupportTest::reportSuccess() { - m_resultText = i18n("Supported, use the 'Modern' configuration for PDFLaTeX and XeLaTeX to auto-enable inverse and forward search capabilities."); - m_status = Success; - emit(testComplete(this)); + m_resultText = i18n("Supported, use the 'Modern' configuration for PDFLaTeX and XeLaTeX to auto-enable inverse and forward search capabilities."); + m_status = Success; + emit(testComplete(this)); } void SyncTeXSupportTest::reportFailure() { - m_resultText = i18n("Not supported"); - m_status = Failure; - emit(testComplete(this)); + m_resultText = i18n("Not supported"); + m_status = Failure; + emit(testComplete(this)); } void SyncTeXSupportTest::processFinishedSuccessfully() { - // before we can report success, we still have to check - // whether a .synctex.gz file has been generated - QFile file(m_workingDir + '/' + m_fileBaseName + ".synctex.gz"); - if (!file.exists()) { - reportFailure(); - return; - } - reportSuccess(); + // before we can report success, we still have to check + // whether a .synctex.gz file has been generated + QFile file(m_workingDir + '/' + m_fileBaseName + ".synctex.gz"); + if (!file.exists()) { + reportFailure(); + return; + } + reportSuccess(); } void Tester::installConsecutivelyDependentTests(ConfigTest *t1, ConfigTest *t2, ConfigTest *t3, ConfigTest *t4) { - if(!t1) { - return; - } - m_testList << t1; - if(!t2) { - return; - } - t2->addDependency(t1); - m_testList << t2; - if(!t3) { - return; - } - t3->addDependency(t2); - m_testList << t3; - if(!t4) { - return; - } - t4->addDependency(t3); - m_testList << t4; + if(!t1) { + return; + } + m_testList << t1; + if(!t2) { + return; + } + t2->addDependency(t1); + m_testList << t2; + if(!t3) { + return; + } + t3->addDependency(t2); + m_testList << t3; + if(!t4) { + return; + } + t4->addDependency(t3); + m_testList << t4; } void Tester::setupTests() { -/* -testFile=test_plain.tex -echo "opening $basedir/$testFile" -$openDoc"$basedir/$testFile" - -echo "starting test: TeX" -setTool TeX -tool="tex --interaction=nonstopmode" -setKey mustpass "where,basic,kile" -setKey executable tex -setKey where `which tex` -setKey version `getTeXVersion tex` -performTest basic "$tool test_plain.tex" -performKileTest kile "run TeX" -*/ - installConsecutivelyDependentTests( - new FindProgramTest("TeX", "tex", true), - new ProgramTest("TeX", "tex", m_tempDir->path(), "--interaction=nonstopmode", "test_plain.tex", "", true), - new TestToolInKileTest("TeX", m_ki, "TeX", m_tempDir->path() + '/' + "test_plain.tex", true)); -/* -echo "starting test: PDFTeX" -setTool PDFTeX -tool="pdftex --interaction=nonstopmode" -setKey mustpass "" -setKey executable pdftex -setKey where `which pdftex` -performTest basic "$tool test_plain.tex" -performKileTest kile "run PDFTeX" -$closeDoc -*/ - installConsecutivelyDependentTests( - new FindProgramTest("PDFTeX", "pdftex", false), - new ProgramTest("PDFTeX", "pdftex", m_tempDir->path(), "--interaction=nonstopmode", "test_plain.tex", "", false), - new TestToolInKileTest("PDFTeX", m_ki, "PDFTeX", m_tempDir->path() + '/' + "test_plain.tex", false)); -/* -testFileBase="test" -testFile=$testFileBase.tex -echo "opening $basedir/$testFile" -$openDoc"$basedir/$testFile" -echo "starting test: LaTeX" -setTool LaTeX -tool="latex --interaction=nonstopmode" -setKey mustpass "where,basic,kile" -setKey executable latex -setKey where `which latex` -performTest basic "$tool $testFile" -performKileTest kile "run LaTeX" -performTest src "$tool -src $testFile" -*/ - ProgramTest *latexProgramTest = new ProgramTest("LaTeX", "latex", m_tempDir->path(), "--interaction=nonstopmode", "test.tex", "", true); - m_laTeXSrcSpecialsSupportTest = new LaTeXSrcSpecialsSupportTest("LaTeX", m_tempDir->path(), "test"); - installConsecutivelyDependentTests( - new FindProgramTest("LaTeX", "latex", true), - latexProgramTest, - new TestToolInKileTest("LaTeX", m_ki, "LaTeX", m_tempDir->path() + '/' + "test.tex", true), - m_laTeXSrcSpecialsSupportTest); -/* -echo "starting test: PDFLaTeX" -setTool PDFLaTeX -setKey mustpass "" -setKey executable pdflatex -setKey where `which pdflatex` -performTest basic "pdflatex $testFile" -performKileTest kile "run PDFLaTeX" -*/ - m_pdfLaTeXSyncTeXSupportTest = new SyncTeXSupportTest("PDFLaTeX", "pdflatex", m_tempDir->path(), "test"); - installConsecutivelyDependentTests( - new FindProgramTest("PDFLaTeX", "pdflatex", false), - new ProgramTest("PDFLaTeX", "pdflatex", m_tempDir->path(), "--interaction=nonstopmode", "test.tex", "", false), - new TestToolInKileTest("PDFLaTeX", m_ki, "PDFLaTeX", m_tempDir->path() + '/' + "test.tex", false), - m_pdfLaTeXSyncTeXSupportTest); -/* -echo "starting test: DVItoPS" -setTool DVItoPS -setKey mustpass "" -setKey executable dvips -setKey where `which dvips` -if [ -r $testFileBase.dvi ]; then performKileTest kile "run DVItoPS"; fi -*/ - TestToolInKileTest *dvipsKileTest = new TestToolInKileTest("DVItoPS", m_ki, "DVItoPS", m_tempDir->path() + '/' + "test.tex", false); - dvipsKileTest->addDependency(latexProgramTest); - installConsecutivelyDependentTests( - new FindProgramTest("DVItoPS", "dvips", false), - dvipsKileTest); -/* -echo "starting test: DVItoPDF" -setTool DVItoPDF -setKey mustpass "" -setKey executable dvipdfmx -setKey where `which dvipdfmx` -if [ -r $testFileBase.dvi ]; then performKileTest kile "run DVItoPDF"; fi -*/ - TestToolInKileTest *dvipdfmxKileTest = new TestToolInKileTest("DVItoPDF", m_ki, "DVItoPDF", m_tempDir->path() + '/' + "test.tex", false); - dvipdfmxKileTest->addDependency(latexProgramTest); - installConsecutivelyDependentTests( - new FindProgramTest("DVItoPDF", "dvipdfmx", false), - dvipdfmxKileTest); -/* -echo "starting test: PStoPDF" -setTool PStoPDF -setKey mustpass "" -setKey executable ps2pdf -setKey where `which ps2pdf` -if [ -r $testFileBase.ps ]; then performKileTest kile "run PStoPDF"; fi -$closeDoc -*/ - TestToolInKileTest *ps2pdfKileTest = new TestToolInKileTest("PStoPDF", m_ki, "PStoPDF", m_tempDir->path() + '/' + "test.tex", false); - ps2pdfKileTest->addDependency(dvipsKileTest); - installConsecutivelyDependentTests( - new FindProgramTest("PStoPDF", "ps2pdf", false), - ps2pdfKileTest); -/* -echo "starting test: BibTeX" -setTool BibTeX -setKey mustpass "" -setKey executable bibtex -setKey where `which bibtex` -if [ -r "test.dvi" ] #LaTeX is working -then - testFileBase=test_bib - testFile=$testFileBase.tex - $openDoc"$basedir/$testFile" - latex --interaction=nonstopmode $testFile - performTest basic "bibtex $testFileBase" - performKileTest kile "run BibTeX" - $closeDoc -fi -*/ - TestToolInKileTest *latexForBibTeX = new TestToolInKileTest("BibTeX", m_ki, "LaTeX", m_tempDir->path() + '/' + "test_bib.tex", false); - latexForBibTeX->addDependency(latexProgramTest); - latexForBibTeX->setSilent(true); - ProgramTest *bibtexProgramTest = new ProgramTest("BibTeX", "bibtex", m_tempDir->path(), "test_bib", "", "", false); - bibtexProgramTest->addDependency(latexForBibTeX); - TestToolInKileTest *bibtexKileTest = new TestToolInKileTest("BibTeX", m_ki, "BibTeX", m_tempDir->path() + '/' + "test_bib.tex", false); - bibtexKileTest->addDependency(latexProgramTest); - installConsecutivelyDependentTests( - new FindProgramTest("BibTeX", "bibtex", false), - latexForBibTeX, - bibtexProgramTest, - bibtexKileTest); -/* -echo "starting test: MakeIndex" -setTool MakeIndex -setKey mustpass "" -setKey executable makeindex -setKey where `which makeindex` - -if [ -r "test.dvi" ] #LaTeX is working -then - testFileBase=test_index - testFile=$testFileBase.tex - $openDoc"$basedir/$testFile" - latex --interaction=nonstopmode $testFile - performTest basic "makeindex $testFileBase" - performKileTest kile "run MakeIndex" - $closeDoc -fi -*/ - TestToolInKileTest *latexForMakeIndex = new TestToolInKileTest("MakeIndex", m_ki, "LaTeX", m_tempDir->path() + '/' + "test_index.tex", false); - latexForMakeIndex->addDependency(latexProgramTest); - latexForMakeIndex->setSilent(true); - ProgramTest *makeIndexProgramTest = new ProgramTest("MakeIndex", "makeindex", m_tempDir->path(), "test_index", "", "", false); - makeIndexProgramTest->addDependency(latexProgramTest); - TestToolInKileTest *makeindexKileTest = new TestToolInKileTest("MakeIndex", m_ki, "MakeIndex", m_tempDir->path() + '/' + "test_index.tex", false); - makeindexKileTest->addDependency(latexProgramTest); - installConsecutivelyDependentTests( - new FindProgramTest("MakeIndex", "makeindex", false), - latexForMakeIndex, - makeIndexProgramTest, - makeindexKileTest); -/* -echo "starting test: Okular" -setTool Okular -setKey mustpass "where" -setKey executable okular -setKey version `getOkularVersion okular` -performTest okular "isTheOkularVersionRecentEnough" -setKey where `which okular` -*/ - m_okularVersionTest = new OkularVersionTest("Okular", false); - installConsecutivelyDependentTests( - new FindProgramTest("Okular", "okular", false), - m_okularVersionTest); -/* -echo "starting test: Acroread" -setTool Acroread -setKey mustpass "" -setKey executable acroread -setKey where `which acroread` -*/ - -/* -echo "starting test: DVItoPNG" -setTool DVItoPNG -setKey mustpass "" -setKey executable dvipng -setKey where `which dvipng` -*/ - FindProgramTest *dvipngProgramTest = new FindProgramTest("DVItoPNG", "dvipng", false); - dvipngProgramTest->setAdditionalFailureMessage(i18n("PNG previews cannot be used for mathgroups in the bottom preview pane")); - m_testList << dvipngProgramTest; -/* -echo "starting test: Convert" -setTool Convert -setKey mustpass "" -setKey executable convert -setKey where `which convert` -*/ - FindProgramTest *convertProgramTest = new FindProgramTest("Convert", "convert", false); - convertProgramTest->setAdditionalFailureMessage(i18n("PNG previews cannot be used with conversions 'dvi->ps->png' and 'pdf->png' in the bottom preview pane")); - m_testList << convertProgramTest; + /* + testFile=test_plain.tex + echo "opening $basedir/$testFile" + $openDoc"$basedir/$testFile" + + echo "starting test: TeX" + setTool TeX + tool="tex --interaction=nonstopmode" + setKey mustpass "where,basic,kile" + setKey executable tex + setKey where `which tex` + setKey version `getTeXVersion tex` + performTest basic "$tool test_plain.tex" + performKileTest kile "run TeX" + */ + installConsecutivelyDependentTests( + new FindProgramTest("TeX", "tex", true), + new ProgramTest("TeX", "tex", m_tempDir->path(), "--interaction=nonstopmode", "test_plain.tex", "", true), + new TestToolInKileTest("TeX", m_ki, "TeX", m_tempDir->path() + '/' + "test_plain.tex", true)); + /* + echo "starting test: PDFTeX" + setTool PDFTeX + tool="pdftex --interaction=nonstopmode" + setKey mustpass "" + setKey executable pdftex + setKey where `which pdftex` + performTest basic "$tool test_plain.tex" + performKileTest kile "run PDFTeX" + $closeDoc + */ + installConsecutivelyDependentTests( + new FindProgramTest("PDFTeX", "pdftex", false), + new ProgramTest("PDFTeX", "pdftex", m_tempDir->path(), "--interaction=nonstopmode", "test_plain.tex", "", false), + new TestToolInKileTest("PDFTeX", m_ki, "PDFTeX", m_tempDir->path() + '/' + "test_plain.tex", false)); + /* + testFileBase="test" + testFile=$testFileBase.tex + echo "opening $basedir/$testFile" + $openDoc"$basedir/$testFile" + echo "starting test: LaTeX" + setTool LaTeX + tool="latex --interaction=nonstopmode" + setKey mustpass "where,basic,kile" + setKey executable latex + setKey where `which latex` + performTest basic "$tool $testFile" + performKileTest kile "run LaTeX" + performTest src "$tool -src $testFile" + */ + ProgramTest *latexProgramTest = new ProgramTest("LaTeX", "latex", m_tempDir->path(), "--interaction=nonstopmode", "test.tex", "", true); + m_laTeXSrcSpecialsSupportTest = new LaTeXSrcSpecialsSupportTest("LaTeX", m_tempDir->path(), "test"); + installConsecutivelyDependentTests( + new FindProgramTest("LaTeX", "latex", true), + latexProgramTest, + new TestToolInKileTest("LaTeX", m_ki, "LaTeX", m_tempDir->path() + '/' + "test.tex", true), + m_laTeXSrcSpecialsSupportTest); + /* + echo "starting test: PDFLaTeX" + setTool PDFLaTeX + setKey mustpass "" + setKey executable pdflatex + setKey where `which pdflatex` + performTest basic "pdflatex $testFile" + performKileTest kile "run PDFLaTeX" + */ + m_pdfLaTeXSyncTeXSupportTest = new SyncTeXSupportTest("PDFLaTeX", "pdflatex", m_tempDir->path(), "test"); + installConsecutivelyDependentTests( + new FindProgramTest("PDFLaTeX", "pdflatex", false), + new ProgramTest("PDFLaTeX", "pdflatex", m_tempDir->path(), "--interaction=nonstopmode", "test.tex", "", false), + new TestToolInKileTest("PDFLaTeX", m_ki, "PDFLaTeX", m_tempDir->path() + '/' + "test.tex", false), + m_pdfLaTeXSyncTeXSupportTest); + /* + echo "starting test: DVItoPS" + setTool DVItoPS + setKey mustpass "" + setKey executable dvips + setKey where `which dvips` + if [ -r $testFileBase.dvi ]; then performKileTest kile "run DVItoPS"; fi + */ + TestToolInKileTest *dvipsKileTest = new TestToolInKileTest("DVItoPS", m_ki, "DVItoPS", m_tempDir->path() + '/' + "test.tex", false); + dvipsKileTest->addDependency(latexProgramTest); + installConsecutivelyDependentTests( + new FindProgramTest("DVItoPS", "dvips", false), + dvipsKileTest); + /* + echo "starting test: DVItoPDF" + setTool DVItoPDF + setKey mustpass "" + setKey executable dvipdfmx + setKey where `which dvipdfmx` + if [ -r $testFileBase.dvi ]; then performKileTest kile "run DVItoPDF"; fi + */ + TestToolInKileTest *dvipdfmxKileTest = new TestToolInKileTest("DVItoPDF", m_ki, "DVItoPDF", m_tempDir->path() + '/' + "test.tex", false); + dvipdfmxKileTest->addDependency(latexProgramTest); + installConsecutivelyDependentTests( + new FindProgramTest("DVItoPDF", "dvipdfmx", false), + dvipdfmxKileTest); + /* + echo "starting test: PStoPDF" + setTool PStoPDF + setKey mustpass "" + setKey executable ps2pdf + setKey where `which ps2pdf` + if [ -r $testFileBase.ps ]; then performKileTest kile "run PStoPDF"; fi + $closeDoc + */ + TestToolInKileTest *ps2pdfKileTest = new TestToolInKileTest("PStoPDF", m_ki, "PStoPDF", m_tempDir->path() + '/' + "test.tex", false); + ps2pdfKileTest->addDependency(dvipsKileTest); + installConsecutivelyDependentTests( + new FindProgramTest("PStoPDF", "ps2pdf", false), + ps2pdfKileTest); + /* + echo "starting test: BibTeX" + setTool BibTeX + setKey mustpass "" + setKey executable bibtex + setKey where `which bibtex` + if [ -r "test.dvi" ] #LaTeX is working + then + testFileBase=test_bib + testFile=$testFileBase.tex + $openDoc"$basedir/$testFile" + latex --interaction=nonstopmode $testFile + performTest basic "bibtex $testFileBase" + performKileTest kile "run BibTeX" + $closeDoc + fi + */ + TestToolInKileTest *latexForBibTeX = new TestToolInKileTest("BibTeX", m_ki, "LaTeX", m_tempDir->path() + '/' + "test_bib.tex", false); + latexForBibTeX->addDependency(latexProgramTest); + latexForBibTeX->setSilent(true); + ProgramTest *bibtexProgramTest = new ProgramTest("BibTeX", "bibtex", m_tempDir->path(), "test_bib", "", "", false); + bibtexProgramTest->addDependency(latexForBibTeX); + TestToolInKileTest *bibtexKileTest = new TestToolInKileTest("BibTeX", m_ki, "BibTeX", m_tempDir->path() + '/' + "test_bib.tex", false); + bibtexKileTest->addDependency(latexProgramTest); + installConsecutivelyDependentTests( + new FindProgramTest("BibTeX", "bibtex", false), + latexForBibTeX, + bibtexProgramTest, + bibtexKileTest); + /* + echo "starting test: MakeIndex" + setTool MakeIndex + setKey mustpass "" + setKey executable makeindex + setKey where `which makeindex` + + if [ -r "test.dvi" ] #LaTeX is working + then + testFileBase=test_index + testFile=$testFileBase.tex + $openDoc"$basedir/$testFile" + latex --interaction=nonstopmode $testFile + performTest basic "makeindex $testFileBase" + performKileTest kile "run MakeIndex" + $closeDoc + fi + */ + TestToolInKileTest *latexForMakeIndex = new TestToolInKileTest("MakeIndex", m_ki, "LaTeX", m_tempDir->path() + '/' + "test_index.tex", false); + latexForMakeIndex->addDependency(latexProgramTest); + latexForMakeIndex->setSilent(true); + ProgramTest *makeIndexProgramTest = new ProgramTest("MakeIndex", "makeindex", m_tempDir->path(), "test_index", "", "", false); + makeIndexProgramTest->addDependency(latexProgramTest); + TestToolInKileTest *makeindexKileTest = new TestToolInKileTest("MakeIndex", m_ki, "MakeIndex", m_tempDir->path() + '/' + "test_index.tex", false); + makeindexKileTest->addDependency(latexProgramTest); + installConsecutivelyDependentTests( + new FindProgramTest("MakeIndex", "makeindex", false), + latexForMakeIndex, + makeIndexProgramTest, + makeindexKileTest); + /* + echo "starting test: Okular" + setTool Okular + setKey mustpass "where" + setKey executable okular + setKey version `getOkularVersion okular` + performTest okular "isTheOkularVersionRecentEnough" + setKey where `which okular` + */ + m_okularVersionTest = new OkularVersionTest("Okular", false); + installConsecutivelyDependentTests( + new FindProgramTest("Okular", "okular", false), + m_okularVersionTest); + /* + echo "starting test: Acroread" + setTool Acroread + setKey mustpass "" + setKey executable acroread + setKey where `which acroread` + */ + + /* + echo "starting test: DVItoPNG" + setTool DVItoPNG + setKey mustpass "" + setKey executable dvipng + setKey where `which dvipng` + */ + FindProgramTest *dvipngProgramTest = new FindProgramTest("DVItoPNG", "dvipng", false); + dvipngProgramTest->setAdditionalFailureMessage(i18n("PNG previews cannot be used for mathgroups in the bottom preview pane")); + m_testList << dvipngProgramTest; + /* + echo "starting test: Convert" + setTool Convert + setKey mustpass "" + setKey executable convert + setKey where `which convert` + */ + FindProgramTest *convertProgramTest = new FindProgramTest("Convert", "convert", false); + convertProgramTest->setAdditionalFailureMessage(i18n("PNG previews cannot be used with conversions 'dvi->ps->png' and 'pdf->png' in the bottom preview pane")); + m_testList << convertProgramTest; } bool Tester::isSyncTeXSupportedForPDFLaTeX() { - return (m_pdfLaTeXSyncTeXSupportTest->status() == ConfigTest::Success); + return (m_pdfLaTeXSyncTeXSupportTest->status() == ConfigTest::Success); } bool Tester::isViewerModeSupportedInOkular() { - return (m_okularVersionTest->status() == ConfigTest::Success); + return (m_okularVersionTest->status() == ConfigTest::Success); } bool Tester::areSrcSpecialsSupportedForLaTeX() { - return (m_laTeXSrcSpecialsSupportTest->status() == ConfigTest::Success); + return (m_laTeXSrcSpecialsSupportTest->status() == ConfigTest::Success); } diff --git a/src/configtester.h b/src/configtester.h index e3acd5e1..c3902207 100644 --- a/src/configtester.h +++ b/src/configtester.h @@ -1,249 +1,249 @@ /************************************************************************************* Copyright (C) 2004 by Jeroen Wijnhout (Jeroen.Wijnhout@kdemail.net) 2012 by Michel Ludwig (michel.ludwig@kdemail.net) *************************************************************************************/ /*************************************************************************** * * * 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. * * * ***************************************************************************/ #ifndef CONFIGTESTER_H #define CONFIGTESTER_H #include #include #include #include #include class KJob; class QTemporaryDir; class KProcess; class KileInfo; namespace KileDocument { - class TextInfo; +class TextInfo; } namespace KileTool { - class Base; +class Base; } class ConfigTest : public QObject { - Q_OBJECT + Q_OBJECT - public: - enum Status { Success = 2, Failure = 1, NotRun = 0 }; +public: + enum Status { Success = 2, Failure = 1, NotRun = 0 }; - ConfigTest(const QString& testGroup, const QString &name, bool isCritical); - virtual ~ConfigTest(); + ConfigTest(const QString& testGroup, const QString &name, bool isCritical); + virtual ~ConfigTest(); - int status() const; + int status() const; - virtual void call() = 0; + virtual void call() = 0; - QString resultText() const; - QString name() const; - QString testGroup() const; + QString resultText() const; + QString name() const; + QString testGroup() const; - void addDependency(ConfigTest *test); - bool allDependenciesSucceeded() const; + void addDependency(ConfigTest *test); + bool allDependenciesSucceeded() const; - bool isCritical() const; + bool isCritical() const; - bool isSilent() const; - void setSilent(bool b); + bool isSilent() const; + void setSilent(bool b); - Q_SIGNALS: - void testComplete(ConfigTest *test); +Q_SIGNALS: + void testComplete(ConfigTest *test); - private: - QString m_testGroup, m_name; - bool m_isCritical, m_isSilent; - QLinkedList m_dependencyTestList; +private: + QString m_testGroup, m_name; + bool m_isCritical, m_isSilent; + QLinkedList m_dependencyTestList; - protected: - Status m_status; - QString m_resultText; +protected: + Status m_status; + QString m_resultText; - void setName(const QString& name); + void setName(const QString& name); }; class OkularVersionTest : public ConfigTest { - Q_OBJECT - public: - OkularVersionTest(const QString& testGroup, bool isCritical); - ~OkularVersionTest(); + Q_OBJECT +public: + OkularVersionTest(const QString& testGroup, bool isCritical); + ~OkularVersionTest(); - virtual void call(); + virtual void call(); - bool isViewerModeSupported() const; + bool isViewerModeSupported() const; - private: - bool m_isViewerModeSupported; +private: + bool m_isViewerModeSupported; }; class FindProgramTest : public ConfigTest { - Q_OBJECT - public: - FindProgramTest(const QString& testGroup, const QString& programName, bool isCritical); - ~FindProgramTest(); + Q_OBJECT +public: + FindProgramTest(const QString& testGroup, const QString& programName, bool isCritical); + ~FindProgramTest(); - virtual void call(); + virtual void call(); - void setAdditionalFailureMessage(const QString& s); + void setAdditionalFailureMessage(const QString& s); - protected: - QString m_programName; - QString m_additionalFailureMessage; +protected: + QString m_programName; + QString m_additionalFailureMessage; }; class TestToolInKileTest : public ConfigTest { - Q_OBJECT - public: - TestToolInKileTest(const QString& testGroup, KileInfo *kileInfo, const QString& toolName, const QString& filePath, bool isCritical); - ~TestToolInKileTest(); + Q_OBJECT +public: + TestToolInKileTest(const QString& testGroup, KileInfo *kileInfo, const QString& toolName, const QString& filePath, bool isCritical); + ~TestToolInKileTest(); - virtual void call(); + virtual void call(); - protected Q_SLOTS: - void handleToolExit(KileTool::Base *tool, int status, bool childToolSpawned); +protected Q_SLOTS: + void handleToolExit(KileTool::Base *tool, int status, bool childToolSpawned); - void reportSuccess(); - void reportFailure(); + void reportSuccess(); + void reportFailure(); - protected: - KileInfo *m_ki; - QString m_toolName; - QString m_filePath; - QUrl m_documentUrl; +protected: + KileInfo *m_ki; + QString m_toolName; + QString m_filePath; + QUrl m_documentUrl; }; class ProgramTest : public ConfigTest { - Q_OBJECT - public: - ProgramTest(const QString& testGroup, const QString& programName, const QString& workingDir, - const QString& arg0, - const QString& arg1, - const QString& arg2 = "", - bool isCritical = false); - ~ProgramTest(); - - virtual void call(); - - protected Q_SLOTS: - virtual void handleTestProcessFinished(int exitCode, QProcess::ExitStatus exitStatus); - virtual void handleTestProcessError(QProcess::ProcessError error); - - virtual void reportSuccess(); - virtual void reportFailure(); - - protected: - KProcess *m_testProcess; - QString m_programName; - QString m_workingDir; - QString m_arg0, m_arg1, m_arg2; - - virtual void processFinishedSuccessfully(); + Q_OBJECT +public: + ProgramTest(const QString& testGroup, const QString& programName, const QString& workingDir, + const QString& arg0, + const QString& arg1, + const QString& arg2 = "", + bool isCritical = false); + ~ProgramTest(); + + virtual void call(); + +protected Q_SLOTS: + virtual void handleTestProcessFinished(int exitCode, QProcess::ExitStatus exitStatus); + virtual void handleTestProcessError(QProcess::ProcessError error); + + virtual void reportSuccess(); + virtual void reportFailure(); + +protected: + KProcess *m_testProcess; + QString m_programName; + QString m_workingDir; + QString m_arg0, m_arg1, m_arg2; + + virtual void processFinishedSuccessfully(); }; class LaTeXSrcSpecialsSupportTest : public ProgramTest { - Q_OBJECT - public: - LaTeXSrcSpecialsSupportTest(const QString& testGroup, const QString& workingDir, - const QString& fileBaseName); - ~LaTeXSrcSpecialsSupportTest(); - - protected: - QString m_fileBaseName; - - virtual void reportSuccess(); - virtual void reportFailure(); - virtual void processFinishedSuccessfully(); + Q_OBJECT +public: + LaTeXSrcSpecialsSupportTest(const QString& testGroup, const QString& workingDir, + const QString& fileBaseName); + ~LaTeXSrcSpecialsSupportTest(); + +protected: + QString m_fileBaseName; + + virtual void reportSuccess(); + virtual void reportFailure(); + virtual void processFinishedSuccessfully(); }; class SyncTeXSupportTest : public ProgramTest { - Q_OBJECT - public: - SyncTeXSupportTest(const QString& testGroup, const QString& toolName, const QString& workingDir, - const QString& fileBaseName); - ~SyncTeXSupportTest(); - - protected: - QString m_fileBaseName; - - virtual void reportSuccess(); - virtual void reportFailure(); - virtual void processFinishedSuccessfully(); + Q_OBJECT +public: + SyncTeXSupportTest(const QString& testGroup, const QString& toolName, const QString& workingDir, + const QString& fileBaseName); + ~SyncTeXSupportTest(); + +protected: + QString m_fileBaseName; + + virtual void reportSuccess(); + virtual void reportFailure(); + virtual void processFinishedSuccessfully(); }; class Tester : public QObject { - Q_OBJECT + Q_OBJECT public: - Tester(KileInfo *kileInfo, QObject *parent = 0); - ~Tester(); + Tester(KileInfo *kileInfo, QObject *parent = 0); + ~Tester(); - QStringList testGroups(); - QList resultForGroup(const QString &); - int statusForGroup(const QString &testGroup, bool *isCritical = Q_NULLPTR); + QStringList testGroups(); + QList resultForGroup(const QString &); + int statusForGroup(const QString &testGroup, bool *isCritical = Q_NULLPTR); - bool isSyncTeXSupportedForPDFLaTeX(); - bool isViewerModeSupportedInOkular(); - bool areSrcSpecialsSupportedForLaTeX(); + bool isSyncTeXSupportedForPDFLaTeX(); + bool isViewerModeSupportedInOkular(); + bool areSrcSpecialsSupportedForLaTeX(); public Q_SLOTS: - void runTests(); + void runTests(); Q_SIGNALS: - void started(); - void percentageDone(int); - void finished(bool); + void started(); + void percentageDone(int); + void finished(bool); private Q_SLOTS: - void addResult(const QString &tool, ConfigTest* testResult); + void addResult(const QString &tool, ConfigTest* testResult); - void startNextTest(); + void startNextTest(); - void handleFileCopyResult(KJob* job); - void handleTestComplete(ConfigTest *test); + void handleFileCopyResult(KJob* job); + void handleTestComplete(ConfigTest *test); private: - KileInfo *m_ki; - QMap > m_results; - QTemporaryDir *m_tempDir; - ConfigTest *m_currentTest; - QLinkedList m_testList; - QLinkedList::iterator m_nextTestIterator; - int m_testsDone; - ConfigTest *m_pdfLaTeXSyncTeXSupportTest, *m_laTeXSrcSpecialsSupportTest; - OkularVersionTest *m_okularVersionTest; - - QString m_runningTestGroup; - QUrl m_runningToolTestUrl; - bool m_runningTestCritical; - - void setupTests(); - void installConsecutivelyDependentTests(ConfigTest *t1, ConfigTest *t2 = Q_NULLPTR, - ConfigTest *t3 = Q_NULLPTR, - ConfigTest *t4 = Q_NULLPTR); + KileInfo *m_ki; + QMap > m_results; + QTemporaryDir *m_tempDir; + ConfigTest *m_currentTest; + QLinkedList m_testList; + QLinkedList::iterator m_nextTestIterator; + int m_testsDone; + ConfigTest *m_pdfLaTeXSyncTeXSupportTest, *m_laTeXSrcSpecialsSupportTest; + OkularVersionTest *m_okularVersionTest; + + QString m_runningTestGroup; + QUrl m_runningToolTestUrl; + bool m_runningTestCritical; + + void setupTests(); + void installConsecutivelyDependentTests(ConfigTest *t1, ConfigTest *t2 = Q_NULLPTR, + ConfigTest *t3 = Q_NULLPTR, + ConfigTest *t4 = Q_NULLPTR); }; #endif diff --git a/src/configurationmanager.cpp b/src/configurationmanager.cpp index 38b68b8f..e1d00393 100644 --- a/src/configurationmanager.cpp +++ b/src/configurationmanager.cpp @@ -1,37 +1,37 @@ /************************************************************************** * Copyright (C) 2008 by Michel Ludwig (michel.ludwig@kdemail.net) * ***************************************************************************/ /************************************************************************** * * * 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. * * * ***************************************************************************/ #include "configurationmanager.h" #include "kileconfig.h" #include "kileinfo.h" namespace KileConfiguration { - Manager::Manager(KileInfo *kileInfo, QObject *parent, const char *name) : QObject(parent), m_kileInfo(kileInfo) - { - setObjectName(name); - } +Manager::Manager(KileInfo *kileInfo, QObject *parent, const char *name) : QObject(parent), m_kileInfo(kileInfo) +{ + setObjectName(name); +} - Manager::~Manager() { +Manager::~Manager() { - } +} - void Manager::emitConfigChanged() - { - emit configChanged(); - } +void Manager::emitConfigChanged() +{ + emit configChanged(); +} } diff --git a/src/configurationmanager.h b/src/configurationmanager.h index 19364483..628c8ac4 100644 --- a/src/configurationmanager.h +++ b/src/configurationmanager.h @@ -1,57 +1,57 @@ /************************************************************************** * Copyright (C) 2008 by Michel Ludwig (michel.ludwig@kdemail.net) * ***************************************************************************/ /************************************************************************** * * * 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. * * * ***************************************************************************/ #ifndef CONFIGURATIONMANAGER_H #define CONFIGURATIONMANAGER_H #include class Kile; class KileInfo; namespace KileConfiguration { /** * This class handles the configuration management in Kile. **/ class Manager : public QObject { - friend class ::Kile; + friend class ::Kile; - Q_OBJECT + Q_OBJECT - public: - /** - * Constructs a new Manager object. - **/ - explicit Manager(KileInfo *info, QObject *parent = Q_NULLPTR, const char *name = Q_NULLPTR); - virtual ~Manager(); +public: + /** + * Constructs a new Manager object. + **/ + explicit Manager(KileInfo *info, QObject *parent = Q_NULLPTR, const char *name = Q_NULLPTR); + virtual ~Manager(); - Q_SIGNALS: - /** - * This signal is emitted when the configuration has changed. Classes that read and write to the global KConfig object - * should connect to this signal so they can update their settings. - **/ - void configChanged(); +Q_SIGNALS: + /** + * This signal is emitted when the configuration has changed. Classes that read and write to the global KConfig object + * should connect to this signal so they can update their settings. + **/ + void configChanged(); - protected: - KileInfo *m_kileInfo; +protected: + KileInfo *m_kileInfo; - void emitConfigChanged(); + void emitConfigChanged(); }; } #endif diff --git a/src/convert.cpp b/src/convert.cpp index 8ae723c8..038f2588 100644 --- a/src/convert.cpp +++ b/src/convert.cpp @@ -1,346 +1,346 @@ /************************************************************************************* begin : Sun Feb 29 2004 copyright : (C) 2004 by Jeroen Wijnhout (Jeroen.Wijnhout@kdemail.net) *************************************************************************************/ /*************************************************************************** * * * 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. * * * ***************************************************************************/ #include "convert.h" #include #include #include #include #include #include #include #include "kiledebug.h" QMap ConvertMap::g_maps; bool ConvertMap::create(const QString & encoding) { - KILE_DEBUG_MAIN << "\tlooking for map for " << encoding; - ConvertMap * map = g_maps[encoding]; - - if(!map) { - KILE_DEBUG_MAIN << "\tcreating a map for " << encoding; - map = new ConvertMap(encoding); // FIXME This will never be deleted if load() succeeds... - if(map->load()) { - g_maps[encoding] = map; - } - else { - delete map; - map = Q_NULLPTR; - } - map = g_maps[encoding]; - } - - return (map != Q_NULLPTR); + KILE_DEBUG_MAIN << "\tlooking for map for " << encoding; + ConvertMap * map = g_maps[encoding]; + + if(!map) { + KILE_DEBUG_MAIN << "\tcreating a map for " << encoding; + map = new ConvertMap(encoding); // FIXME This will never be deleted if load() succeeds... + if(map->load()) { + g_maps[encoding] = map; + } + else { + delete map; + map = Q_NULLPTR; + } + map = g_maps[encoding]; + } + + return (map != Q_NULLPTR); } QString ConvertMap::encodingNameFor(const QString & name) { - QString std; - for(int i = 0; i < name.length(); ++i) { - if(!name[i].isSpace()) { - std += name[i]; - } - } - - std = std.toLower(); - - if(std.startsWith("iso8859-")) { - return "latin" + std.right(1); - } - - if(std.startsWith("cp")) { - return "cp" + std.right(4); - } - - return name; + QString std; + for(int i = 0; i < name.length(); ++i) { + if(!name[i].isSpace()) { + std += name[i]; + } + } + + std = std.toLower(); + + if(std.startsWith("iso8859-")) { + return "latin" + std.right(1); + } + + if(std.startsWith("cp")) { + return "cp" + std.right(4); + } + + return name; } QString ConvertMap::isoNameFor(const QString & name) { - QString std; - for(int i = 0; i < name.length(); ++i) { - if(!name[i].isSpace()) { - std += name[i]; - } - } - - std = std.toLower(); - - if(std.startsWith("latin")) { - return "ISO 8859-" + std.right(1); - } - - if(std.startsWith("cp")) { - return "cp " + std.right(4); - } - - return name; + QString std; + for(int i = 0; i < name.length(); ++i) { + if(!name[i].isSpace()) { + std += name[i]; + } + } + + std = std.toLower(); + + if(std.startsWith("latin")) { + return "ISO 8859-" + std.right(1); + } + + if(std.startsWith("cp")) { + return "cp " + std.right(4); + } + + return name; } ConvertMap::ConvertMap(const QString& enc) { - m_aliases.append(encodingNameFor(enc)); - m_aliases.append(isoNameFor(enc)); + m_aliases.append(encodingNameFor(enc)); + m_aliases.append(isoNameFor(enc)); } void ConvertMap::addPair(QChar c, const QString& enc) { - m_toASCII[c] = commandIsTerminated(enc) ? enc : enc + "{}" ; - m_toEncoding[enc] = c; + m_toASCII[c] = commandIsTerminated(enc) ? enc : enc + "{}" ; + m_toEncoding[enc] = c; } bool ConvertMap::commandIsTerminated(const QString & command) { - static QRegExp reCommandSequences("\\\\([a-zA-Z]+|\\\"|\\')$"); + static QRegExp reCommandSequences("\\\\([a-zA-Z]+|\\\"|\\')$"); - return (reCommandSequences.indexIn(command) == -1); + return (reCommandSequences.indexIn(command) == -1); } bool ConvertMap::load() { - static QRegExp reMap("^(.*):(.*)"); + static QRegExp reMap("^(.*):(.*)"); - //makeMap(encoding()); + //makeMap(encoding()); - //if map already exists, replace it - QFile qf(QStandardPaths::locate(QStandardPaths::DataLocation, "encodings/" + encoding() + ".enc")); + //if map already exists, replace it + QFile qf(QStandardPaths::locate(QStandardPaths::DataLocation, "encodings/" + encoding() + ".enc")); - if(qf.open(QIODevice::ReadOnly)) { - QTextStream stream(&qf); - QTextCodec *codec = QTextCodec::codecForName(isoName().toLatin1()); - if(codec) { - stream.setCodec(codec); - } + if(qf.open(QIODevice::ReadOnly)) { + QTextStream stream(&qf); + QTextCodec *codec = QTextCodec::codecForName(isoName().toLatin1()); + if(codec) { + stream.setCodec(codec); + } - while(!stream.atEnd()) { - //parse the line - if(stream.readLine().indexOf(reMap) != -1) { - addPair(reMap.cap(1)[0], reMap.cap(2)); - } - } - qf.close(); + while(!stream.atEnd()) { + //parse the line + if(stream.readLine().indexOf(reMap) != -1) { + addPair(reMap.cap(1)[0], reMap.cap(2)); + } + } + qf.close(); - return true; - } + return true; + } - return false; + return false; } //BEGIN ConvertIO classes ConvertIO::ConvertIO(KTextEditor::Document *doc) : - m_doc(doc), - m_text(QString()), - m_line(QString()), - m_nLine(0) + m_doc(doc), + m_text(QString()), + m_line(QString()), + m_nLine(0) { } QString & ConvertIO::currentLine() { - return m_line; + return m_line; } void ConvertIO::nextLine() { - m_line = m_doc->line(m_nLine++); + m_line = m_doc->line(m_nLine++); } void ConvertIO::writeText() { - m_doc->setText(m_text); + m_doc->setText(m_text); } int ConvertIO::current() { - return m_nLine; + return m_nLine; } bool ConvertIO::done() { - return current() == m_doc->lines(); + return current() == m_doc->lines(); } ConvertIOFile::ConvertIOFile(KTextEditor::Document *doc, const QUrl &url) : ConvertIO(doc), m_url(url) { } void ConvertIOFile::writeText() { - QFile qf(m_url.toLocalFile()); - if(qf.open(QIODevice::WriteOnly)) { - //read the file - QTextStream stream(&qf); - stream << m_text; - qf.close(); - } - else { - qWarning() << "Could not open " << m_url.toLocalFile(); - } + QFile qf(m_url.toLocalFile()); + if(qf.open(QIODevice::WriteOnly)) { + //read the file + QTextStream stream(&qf); + stream << m_text; + qf.close(); + } + else { + qWarning() << "Could not open " << m_url.toLocalFile(); + } } ConvertBase::ConvertBase(const QString & encoding, ConvertIO * io) : - m_io(io), - m_encoding(encoding), - m_map(Q_NULLPTR) + m_io(io), + m_encoding(encoding), + m_map(Q_NULLPTR) { } //END ConvertIO classes //BEGIN ConvertBase QString ConvertBase::mapNext(int &i) { - return (QString)m_io->currentLine()[i++]; + return (QString)m_io->currentLine()[i++]; } bool ConvertBase::convert() { - if(!setMap()) { - return false; - } - - m_io->text().clear(); - do { - m_io->nextLine(); - int i = 0; - while(i < m_io->currentLine().length()) { - m_io->text() += mapNext(i); - } - if(!m_io->done()) { - m_io->text() += '\n'; - } - } - while(!m_io->done()); - - m_io->writeText(); - return true; + if(!setMap()) { + return false; + } + + m_io->text().clear(); + do { + m_io->nextLine(); + int i = 0; + while(i < m_io->currentLine().length()) { + m_io->text() += mapNext(i); + } + if(!m_io->done()) { + m_io->text() += '\n'; + } + } + while(!m_io->done()); + + m_io->writeText(); + return true; } bool ConvertBase::setMap() { - //create map (or use existing) - if(ConvertMap::create(m_encoding)) { - m_map = ConvertMap::mapFor(m_encoding); - } - else { - m_map = Q_NULLPTR; - } - - return (m_map != Q_NULLPTR); + //create map (or use existing) + if(ConvertMap::create(m_encoding)) { + m_map = ConvertMap::mapFor(m_encoding); + } + else { + m_map = Q_NULLPTR; + } + + return (m_map != Q_NULLPTR); } //END ConvertBase //BEGIN ConvertEncToASCII QString ConvertEncToASCII::mapNext(int &i) { - return m_map->canDecode(m_io->currentLine()[i]) ? m_map->toASCII(m_io->currentLine()[i++]) : (QString)m_io->currentLine()[i++]; + return m_map->canDecode(m_io->currentLine()[i]) ? m_map->toASCII(m_io->currentLine()[i++]) : (QString)m_io->currentLine()[i++]; } //END ConvertEncToASCII //BEGIN ConvertASCIIToEnc //i is the position of the '\' QString ConvertASCIIToEnc::nextSequence(int &i) { - //get first two characters - QString seq = (QString)m_io->currentLine()[i++]; - - if(m_io->currentLine()[i].isLetter()) { - while(m_io->currentLine()[i].isLetter()) { - seq += (QString)m_io->currentLine()[i++]; - } - } - else { - return seq + (QString)m_io->currentLine()[i++]; - } - - return seq; + //get first two characters + QString seq = (QString)m_io->currentLine()[i++]; + + if(m_io->currentLine()[i].isLetter()) { + while(m_io->currentLine()[i].isLetter()) { + seq += (QString)m_io->currentLine()[i++]; + } + } + else { + return seq + (QString)m_io->currentLine()[i++]; + } + + return seq; } bool ConvertASCIIToEnc::isModifier(const QString& seq) { - static QRegExp reModifier("\\\\([cHkruv]|\"|\'|\\^|`|~|=|\\.)"); - return reModifier.exactMatch(seq); + static QRegExp reModifier("\\\\([cHkruv]|\"|\'|\\^|`|~|=|\\.)"); + return reModifier.exactMatch(seq); } QString ConvertASCIIToEnc::getSequence(int &i) { - QString seq = nextSequence(i); - static QRegExp reBraces("\\{([a-zA-Z]?)\\}"); - - if(isModifier(seq)) { - KILE_DEBUG_MAIN << "\tisModifier true : " << seq; - if(seq[seq.length() - 1].isLetter()) { - seq += ' '; - } - - while(m_io->currentLine()[i].isSpace()) { - ++i; - } - - if(m_io->currentLine().mid(i, 2) == "{}") { - i = i + 2; - } - - if(m_io->currentLine()[i] == '\\') { - seq += nextSequence(i); - } - else { - if(reBraces.exactMatch(m_io->currentLine().mid(i, 3))) { - KILE_DEBUG_MAIN << "\tbraces detected"; - i = i + 3; - seq += reBraces.cap(1); - } - else { - QChar nextChar = m_io->currentLine()[i++]; - if(!nextChar.isSpace()) { - seq += (QString)nextChar; - } - } - } - } - else if(m_map->canEncode(seq)) { - if(m_io->currentLine().mid(i, 2) == "{}") { - i = i + 2; - } - else if(m_io->currentLine()[i].isSpace()) { - ++i; - } - } - - return seq; + QString seq = nextSequence(i); + static QRegExp reBraces("\\{([a-zA-Z]?)\\}"); + + if(isModifier(seq)) { + KILE_DEBUG_MAIN << "\tisModifier true : " << seq; + if(seq[seq.length() - 1].isLetter()) { + seq += ' '; + } + + while(m_io->currentLine()[i].isSpace()) { + ++i; + } + + if(m_io->currentLine().mid(i, 2) == "{}") { + i = i + 2; + } + + if(m_io->currentLine()[i] == '\\') { + seq += nextSequence(i); + } + else { + if(reBraces.exactMatch(m_io->currentLine().mid(i, 3))) { + KILE_DEBUG_MAIN << "\tbraces detected"; + i = i + 3; + seq += reBraces.cap(1); + } + else { + QChar nextChar = m_io->currentLine()[i++]; + if(!nextChar.isSpace()) { + seq += (QString)nextChar; + } + } + } + } + else if(m_map->canEncode(seq)) { + if(m_io->currentLine().mid(i, 2) == "{}") { + i = i + 2; + } + else if(m_io->currentLine()[i].isSpace()) { + ++i; + } + } + + return seq; } QString ConvertASCIIToEnc::mapNext(int &i) { - if(m_io->currentLine()[i] == '\\') { - QString seq = getSequence(i); - KILE_DEBUG_MAIN << "'\tsequence: " << seq; - if(m_map->canEncode(seq)) { - KILE_DEBUG_MAIN << "\tcan encode this"; - //if ( m_io->currentLine().mid(i, 2) == "{}" ) i = i + 2; - return m_map->toEncoding(seq); - } - else { - return seq; - } - } - - return ConvertBase::mapNext(i); + if(m_io->currentLine()[i] == '\\') { + QString seq = getSequence(i); + KILE_DEBUG_MAIN << "'\tsequence: " << seq; + if(m_map->canEncode(seq)) { + KILE_DEBUG_MAIN << "\tcan encode this"; + //if ( m_io->currentLine().mid(i, 2) == "{}" ) i = i + 2; + return m_map->toEncoding(seq); + } + else { + return seq; + } + } + + return ConvertBase::mapNext(i); } //END ConvertASCIIToEnc diff --git a/src/convert.h b/src/convert.h index c3bd1cb0..49d07384 100644 --- a/src/convert.h +++ b/src/convert.h @@ -1,135 +1,153 @@ /*************************************************************************** begin : Sun Feb 29 2004 copyright : (C) 2004 by Jeroen Wijnhout email : Jeroen.Wijnhout@kdemail.net ***************************************************************************/ /*************************************************************************** * * * 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. * * * ***************************************************************************/ #ifndef CONVERT_H #define CONVERT_H #include #include #include #include -namespace KTextEditor { class Document; } +namespace KTextEditor { +class Document; +} class ConvertMap { protected: - ConvertMap(const QString & encoding); + ConvertMap(const QString & encoding); public: - const QString & encoding() const { return m_aliases[0]; } - const QString & isoName() const { return m_aliases[1]; } - - QChar toEncoding(const QString & enc) { return m_toEncoding[enc]; } - QString toASCII(const QChar & c) { return m_toASCII[c]; } - - void addPair(QChar c, const QString & enc); - - bool canDecode(const QChar & c) { return ( m_toASCII.contains(c)); } - bool canEncode(const QString & enc) { return ( m_toEncoding.contains(enc)); } - - bool load(); + const QString & encoding() const { + return m_aliases[0]; + } + const QString & isoName() const { + return m_aliases[1]; + } + + QChar toEncoding(const QString & enc) { + return m_toEncoding[enc]; + } + QString toASCII(const QChar & c) { + return m_toASCII[c]; + } + + void addPair(QChar c, const QString & enc); + + bool canDecode(const QChar & c) { + return ( m_toASCII.contains(c)); + } + bool canEncode(const QString & enc) { + return ( m_toEncoding.contains(enc)); + } + + bool load(); private: - bool commandIsTerminated(const QString &); + bool commandIsTerminated(const QString &); private: - QStringList m_aliases; - QMap m_toASCII; - QMap m_toEncoding; + QStringList m_aliases; + QMap m_toASCII; + QMap m_toEncoding; //static members public: - static bool create(const QString & encoding); - static QString encodingNameFor(const QString &); - static QString isoNameFor(const QString &); - static ConvertMap * mapFor(const QString & enc) { return g_maps[enc]; } + static bool create(const QString & encoding); + static QString encodingNameFor(const QString &); + static QString isoNameFor(const QString &); + static ConvertMap * mapFor(const QString & enc) { + return g_maps[enc]; + } private: - static QMap g_maps; + static QMap g_maps; }; class ConvertIO { public: - ConvertIO(KTextEditor::Document *doc); - virtual ~ConvertIO() {} - - virtual void nextLine(); //read next line - virtual QString& currentLine(); - virtual QString& text() { return m_text; } - virtual void writeText(); - virtual int current(); //current line number - virtual bool done(); + ConvertIO(KTextEditor::Document *doc); + virtual ~ConvertIO() {} + + virtual void nextLine(); //read next line + virtual QString& currentLine(); + virtual QString& text() { + return m_text; + } + virtual void writeText(); + virtual int current(); //current line number + virtual bool done(); protected: - KTextEditor::Document *m_doc; - QString m_text, m_line; - int m_nLine; + KTextEditor::Document *m_doc; + QString m_text, m_line; + int m_nLine; }; class ConvertIOFile : public ConvertIO { public: - ConvertIOFile(KTextEditor::Document *doc, const QUrl &url); + ConvertIOFile(KTextEditor::Document *doc, const QUrl &url); - void writeText(); + void writeText(); private: - QUrl m_url; + QUrl m_url; }; class ConvertBase { public: - ConvertBase(const QString & encoding, ConvertIO * io); - virtual ~ConvertBase() {}; + ConvertBase(const QString & encoding, ConvertIO * io); + virtual ~ConvertBase() {}; public: - virtual bool convert(); + virtual bool convert(); protected: - virtual bool setMap(); + virtual bool setMap(); - virtual QString mapNext(int&); + virtual QString mapNext(int&); - ConvertIO *m_io; - QString m_encoding; - ConvertMap *m_map; + ConvertIO *m_io; + QString m_encoding; + ConvertMap *m_map; }; class ConvertEncToASCII : public ConvertBase { public: - ConvertEncToASCII(const QString & encoding, ConvertIO * io) : ConvertBase(encoding, io) {} + ConvertEncToASCII(const QString & encoding, ConvertIO * io) : ConvertBase(encoding, io) {} protected: - QString mapNext(int&); + QString mapNext(int&); }; class ConvertASCIIToEnc : public ConvertBase { public: - ConvertASCIIToEnc(const QString & encoding, ConvertIO * io) : ConvertBase(encoding, io) {} + ConvertASCIIToEnc(const QString & encoding, ConvertIO * io) : ConvertBase(encoding, io) {} protected: - QString getSequence(int&); - QString nextSequence(int&); - bool isModifier(const QString&); - QString mapNext(int&); + QString getSequence(int&); + QString nextSequence(int&); + bool isModifier(const QString&); + QString mapNext(int&); }; #endif diff --git a/src/data/symbols-ng/convertOldSymbolFormat.cpp b/src/data/symbols-ng/convertOldSymbolFormat.cpp index d652d727..47ddda92 100644 --- a/src/data/symbols-ng/convertOldSymbolFormat.cpp +++ b/src/data/symbols-ng/convertOldSymbolFormat.cpp @@ -1,211 +1,211 @@ /*************************************************************************** begin : Sat Mai 9 2009 copyright : (C) 2009 by Thomas Braun email : thomas.braun@virtuell-zuhause.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. * * * ***************************************************************************/ #include "convertOldSymbolFormat.h" using std::cout; using std::cerr; using std::endl; int main( int argc, char ** argv ) { - bool mathMode; - QList PackagesList; - QString texfile, type, greedyOptArgString, line; - QString pkgs, pkgsarg, savepkgs, savepkgsarg; - bool env=false, greedyOptArg=true; - - if (argc < 1) { - usage(); - } - - texfile=argv[1]; - greedyOptArgString=argv[2]; - - if( greedyOptArgString.isEmpty() || greedyOptArgString == QString("true") ) { - greedyOptArg = true; - } - else if( greedyOptArgString == QString("false") ) { - greedyOptArg = false; - } - else { - usage(); - } - - QFile file(texfile); - if ( !file.open( QIODevice::ReadOnly ) ) { - cerr << "File " << qPrintable(texfile) << " is not readable" << endl; - return 1; - } - - type = texfile.left(texfile.length() - 4); - cout << qPrintable("" + type + "") << endl; - - QTextStream t(&file); - - QRegExp optarg("\\\\(math)?command\\[(.*)\\]\\{(.*)\\}"); - QRegExp arg("\\\\(math)?command\\{(.*)\\}"); - QRegExp beginenvpkgs("^\\\\begin\\{neededpkgs\\}(?:\\[(.*)\\])?\\{(.*)\\}"); - QRegExp endenvpkgs("^\\\\end\\{neededpkgs\\}"); - QRegExp cmdpkgs("\\\\pkgs(?:\\[(.*)\\])?\\{(.*)\\}"); - QRegExp comment("^\\s*%"); - - beginenvpkgs.setMinimal(true); - cmdpkgs.setMinimal(true); - if(!greedyOptArg) { - optarg.setMinimal(true); - } - - while( !t.atEnd() ) { - - line = t.readLine(); + bool mathMode; + QList PackagesList; + QString texfile, type, greedyOptArgString, line; + QString pkgs, pkgsarg, savepkgs, savepkgsarg; + bool env=false, greedyOptArg=true; + + if (argc < 1) { + usage(); + } + + texfile=argv[1]; + greedyOptArgString=argv[2]; + + if( greedyOptArgString.isEmpty() || greedyOptArgString == QString("true") ) { + greedyOptArg = true; + } + else if( greedyOptArgString == QString("false") ) { + greedyOptArg = false; + } + else { + usage(); + } + + QFile file(texfile); + if ( !file.open( QIODevice::ReadOnly ) ) { + cerr << "File " << qPrintable(texfile) << " is not readable" << endl; + return 1; + } + + type = texfile.left(texfile.length() - 4); + cout << qPrintable("" + type + "") << endl; + + QTextStream t(&file); + + QRegExp optarg("\\\\(math)?command\\[(.*)\\]\\{(.*)\\}"); + QRegExp arg("\\\\(math)?command\\{(.*)\\}"); + QRegExp beginenvpkgs("^\\\\begin\\{neededpkgs\\}(?:\\[(.*)\\])?\\{(.*)\\}"); + QRegExp endenvpkgs("^\\\\end\\{neededpkgs\\}"); + QRegExp cmdpkgs("\\\\pkgs(?:\\[(.*)\\])?\\{(.*)\\}"); + QRegExp comment("^\\s*%"); + + beginenvpkgs.setMinimal(true); + cmdpkgs.setMinimal(true); + if(!greedyOptArg) { + optarg.setMinimal(true); + } + + while( !t.atEnd() ) { + + line = t.readLine(); // cout << ""; - if( line.contains(comment) ) { - continue; - } - - if(env) { - pkgs=savepkgs; - pkgsarg=savepkgsarg; - } - else { - pkgs.clear(); - pkgsarg.clear(); - } - - if ( line.indexOf(beginenvpkgs) != -1) { - env=true; - pkgs=beginenvpkgs.cap(2); - pkgsarg=beginenvpkgs.cap(1); - savepkgs=pkgs; - savepkgsarg=pkgsarg; - } - else if( line.indexOf(cmdpkgs) != -1) { - pkgs=cmdpkgs.cap(2); - pkgsarg=cmdpkgs.cap(1); - } - else if( line.indexOf(endenvpkgs) != -1) { - env=false; - savepkgs.clear(); - savepkgsarg.clear(); - pkgs.clear(); - pkgsarg.clear(); - } - - cout << "" << endl; - - - QString packageString = QString("{%1}").arg(pkgs); - mathMode = false; - - if(!pkgsarg.isEmpty()){ - packageString.prepend(QString("[%1]").arg(pkgsarg)); - } - - if(line.indexOf(optarg) != -1) { - cout << "") << endl; - if(optarg.cap(1) == QString("math") ){ - mathMode = true; - } - extractPackageString(packageString,PackagesList); - outputXML(optarg.cap(2),optarg.cap(3),PackagesList,mathMode); - } - else if(line.indexOf(arg) != -1) { - cout << "") << endl; - - if(arg.cap(1) == QString("math") ){ - mathMode = true; - } - extractPackageString(packageString,PackagesList); - outputXML(arg.cap(2),arg.cap(2),PackagesList,mathMode); - } - } - cout << "" << endl; - return 0; + if( line.contains(comment) ) { + continue; + } + + if(env) { + pkgs=savepkgs; + pkgsarg=savepkgsarg; + } + else { + pkgs.clear(); + pkgsarg.clear(); + } + + if ( line.indexOf(beginenvpkgs) != -1) { + env=true; + pkgs=beginenvpkgs.cap(2); + pkgsarg=beginenvpkgs.cap(1); + savepkgs=pkgs; + savepkgsarg=pkgsarg; + } + else if( line.indexOf(cmdpkgs) != -1) { + pkgs=cmdpkgs.cap(2); + pkgsarg=cmdpkgs.cap(1); + } + else if( line.indexOf(endenvpkgs) != -1) { + env=false; + savepkgs.clear(); + savepkgsarg.clear(); + pkgs.clear(); + pkgsarg.clear(); + } + + cout << "" << endl; + + + QString packageString = QString("{%1}").arg(pkgs); + mathMode = false; + + if(!pkgsarg.isEmpty()) { + packageString.prepend(QString("[%1]").arg(pkgsarg)); + } + + if(line.indexOf(optarg) != -1) { + cout << "") << endl; + if(optarg.cap(1) == QString("math") ) { + mathMode = true; + } + extractPackageString(packageString,PackagesList); + outputXML(optarg.cap(2),optarg.cap(3),PackagesList,mathMode); + } + else if(line.indexOf(arg) != -1) { + cout << "") << endl; + + if(arg.cap(1) == QString("math") ) { + mathMode = true; + } + extractPackageString(packageString,PackagesList); + outputXML(arg.cap(2),arg.cap(2),PackagesList,mathMode); + } + } + cout << "" << endl; + return 0; } void usage() { - cerr << "Usage:\n"; - cerr << "convertOldSymbolFormat \n"; - cerr << "latex-file, a file which can be compiled with LaTeX, has to end with .tex\n"; - cerr << "greedyOptArg, can be true or false, defaults to true\n"; - cerr << "Setting it to true will match as much of the square brackets from \\command[.*], setting it to false to as few as possible.\n"; - exit(1); + cerr << "Usage:\n"; + cerr << "convertOldSymbolFormat \n"; + cerr << "latex-file, a file which can be compiled with LaTeX, has to end with .tex\n"; + cerr << "greedyOptArg, can be true or false, defaults to true\n"; + cerr << "Setting it to true will match as much of the square brackets from \\command[.*], setting it to false to as few as possible.\n"; + exit(1); } void outputXML(const QString latexCommand, const QString imageCommand, QList< Package >& packages, bool mathMode) { - Package pkg; - QString output; - output = "\n"; - if(imageCommand == latexCommand){ - output += " " + Qt::escape(latexCommand) + "\n"; - } - else{ - output += " " + Qt::escape(latexCommand) + "\n"; - output += " " + Qt::escape(imageCommand) + "\n"; - } - - if(mathMode){ - output += " true\n"; - } - - foreach(pkg, packages){ - if(pkg.name.isEmpty()){ - continue; - } - output += " \n\ + Package pkg; + QString output; + output = "\n"; + if(imageCommand == latexCommand) { + output += " " + Qt::escape(latexCommand) + "\n"; + } + else { + output += " " + Qt::escape(latexCommand) + "\n"; + output += " " + Qt::escape(imageCommand) + "\n"; + } + + if(mathMode) { + output += " true\n"; + } + + foreach(pkg, packages) { + if(pkg.name.isEmpty()) { + continue; + } + output += " \n\ " + Qt::escape(pkg.name) + "\n"; - if(!pkg.arguments.isEmpty()){ - output += " " + Qt::escape(pkg.arguments) + "\n"; - } - output += " \n"; - } - - output += "\n"; - - cout << qPrintable(output) << endl; + if(!pkg.arguments.isEmpty()) { + output += " " + Qt::escape(pkg.arguments) + "\n"; + } + output += " \n"; + } + + output += "\n"; + + cout << qPrintable(output) << endl; } - -void extractPackageString(const QString&string, QList &packages){ - - QRegExp rePkgs("(?:\\[(.*)\\])?\\{(.*)\\}"); - QStringList args,pkgs; - Package pkg; - - if(string.isEmpty()){ - return; - } - - packages.clear(); - - if ( rePkgs.exactMatch(string) ){ - args = rePkgs.cap(1).split(','); - pkgs = rePkgs.cap(2).split(','); - } - else{ - return; - } - - for(int i = 0 ; i < pkgs.count() && i < args.count() ; i++){ - pkg.name = pkgs.at(i); - pkg.arguments = args.at(i); - packages.append(pkg); - } - + +void extractPackageString(const QString&string, QList &packages) { + + QRegExp rePkgs("(?:\\[(.*)\\])?\\{(.*)\\}"); + QStringList args,pkgs; + Package pkg; + + if(string.isEmpty()) { + return; + } + + packages.clear(); + + if ( rePkgs.exactMatch(string) ) { + args = rePkgs.cap(1).split(','); + pkgs = rePkgs.cap(2).split(','); + } + else { + return; + } + + for(int i = 0 ; i < pkgs.count() && i < args.count() ; i++) { + pkg.name = pkgs.at(i); + pkg.arguments = args.at(i); + packages.append(pkg); + } + } diff --git a/src/data/symbols-ng/convertOldSymbolFormat.h b/src/data/symbols-ng/convertOldSymbolFormat.h index 0b83a059..42fe06dc 100644 --- a/src/data/symbols-ng/convertOldSymbolFormat.h +++ b/src/data/symbols-ng/convertOldSymbolFormat.h @@ -1,35 +1,35 @@ /*************************************************************************** begin : Sat Mai 9 2009 copyright : (C) 2009 by Thomas Braun email : thomas.braun@virtuell-zuhause.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. * * * ***************************************************************************/ #ifndef GESYMB_H #define GESYMB_H #include #include #include #include #include #include #include #include #include #include "../../symbolviewclasses.h" void usage(); -void outputXML(const QString ,const QString , QList< Package >& packages, bool mathMode); +void outputXML(const QString,const QString, QList< Package >& packages, bool mathMode); void extractPackageString(const QString&string, QList &packages); #endif diff --git a/src/data/symbols-ng/gesymb-ng.cpp b/src/data/symbols-ng/gesymb-ng.cpp index b73c83eb..30992372 100644 --- a/src/data/symbols-ng/gesymb-ng.cpp +++ b/src/data/symbols-ng/gesymb-ng.cpp @@ -1,350 +1,350 @@ /* * description: converter from xml to png files for new file format * date: 8 may 2009 * * Copyright (C) 2010 Thomas Braun * * 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, see . * */ #include #include #include #include #include #include #include #include #include #include "../../symbolviewclasses.h" /* TODO - more error checking when parsing xml file */ void readImageComments(const QString &fileName) { - QImage image; - QString output; - - if(image.load(fileName)) { - qDebug() << QString("Image %1 has Command _%2_").arg(fileName).arg(image.text("Command")); - qDebug() << QString("Image %1 has Comment _%2_").arg(fileName).arg(image.text("Comment")); - qDebug() << QString("image %1 has Package _%2_").arg(fileName).arg(image.text("Packages")); - qDebug() << QString("Image %1 has CommandUnicode _%2_").arg(fileName).arg(image.text("CommandUnicode")); - qDebug() << QString("Image %1 has UnicodePackages _%2_").arg(fileName).arg(image.text("UnicodePackages")); - } - else { - qDebug() << "===readComment=== ERROR " << fileName << " could not be loaded"; - } + QImage image; + QString output; + + if(image.load(fileName)) { + qDebug() << QString("Image %1 has Command _%2_").arg(fileName).arg(image.text("Command")); + qDebug() << QString("Image %1 has Comment _%2_").arg(fileName).arg(image.text("Comment")); + qDebug() << QString("image %1 has Package _%2_").arg(fileName).arg(image.text("Packages")); + qDebug() << QString("Image %1 has CommandUnicode _%2_").arg(fileName).arg(image.text("CommandUnicode")); + qDebug() << QString("Image %1 has UnicodePackages _%2_").arg(fileName).arg(image.text("UnicodePackages")); + } + else { + qDebug() << "===readComment=== ERROR " << fileName << " could not be loaded"; + } } -QString convertUTF8toLatin1String(const QString &string){ +QString convertUTF8toLatin1String(const QString &string) { - QVector stringAsInt; - QString stringAsLatin1; + QVector stringAsInt; + QString stringAsLatin1; - Q_FOREACH(uint i, string.toUcs4()){ - stringAsLatin1 += QString("U+%1,").arg(i); - } - return stringAsLatin1; + Q_FOREACH(uint i, string.toUcs4()) { + stringAsLatin1 += QString("U+%1,").arg(i); + } + return stringAsLatin1; } -QString pkgListToString(const QList &packages){ - - QString packagesArg, packagesName; - - for(int i=0; i < packages.count() ; i++){ - packagesArg += packages[i].arguments + ','; - packagesName += packages[i].name + ','; - } - QString result = ( packagesArg.isEmpty() ? "" : '[' + packagesArg + ']' ) + ( packagesName.isEmpty() ? "" : '{' + packagesName + '}' ); - return result; +QString pkgListToString(const QList &packages) { + + QString packagesArg, packagesName; + + for(int i=0; i < packages.count() ; i++) { + packagesArg += packages[i].arguments + ','; + packagesName += packages[i].name + ','; + } + QString result = ( packagesArg.isEmpty() ? "" : '[' + packagesArg + ']' ) + ( packagesName.isEmpty() ? "" : '{' + packagesName + '}' ); + return result; } void writeImageComments(const Command &cmd, const QString &fileName) { - - QImage image; - QString unicodeCommandAsLatin1, commentAsLatin1; - QString packagesarg, packages; - - if(!cmd.unicodeCommand.isEmpty()) { - unicodeCommandAsLatin1 = convertUTF8toLatin1String(cmd.unicodeCommand); - } - if(!cmd.comment.isEmpty()) { - commentAsLatin1 = convertUTF8toLatin1String(cmd.comment); - } - - qDebug() << "fileName is " << fileName; - qDebug() << "Command is " << cmd.latexCommand; - qDebug() << "unicodeCommandAsLatin1 is " << unicodeCommandAsLatin1; - qDebug() << "commentAsLatin1 is " << commentAsLatin1; - qDebug() << "comment is " << cmd.comment; - - if(image.load(fileName)) { - - image.setText("Command",cmd.latexCommand); - if( !unicodeCommandAsLatin1.isEmpty() ) { - image.setText("CommandUnicode",unicodeCommandAsLatin1); - image.setText("UnicodePackages",pkgListToString(cmd.unicodePackages)); - } - if (!commentAsLatin1.isEmpty() ) { - image.setText("Comment",commentAsLatin1); - } - - image.setText("Packages",pkgListToString(cmd.packages)); - if(!image.save(fileName,"PNG")) { - qDebug() << "Image " << fileName << " could not be saved"; - exit(1); - } - } - else { - qDebug() << "===writeComment=== ERROR " << fileName << "could not be loaded"; - } - + + QImage image; + QString unicodeCommandAsLatin1, commentAsLatin1; + QString packagesarg, packages; + + if(!cmd.unicodeCommand.isEmpty()) { + unicodeCommandAsLatin1 = convertUTF8toLatin1String(cmd.unicodeCommand); + } + if(!cmd.comment.isEmpty()) { + commentAsLatin1 = convertUTF8toLatin1String(cmd.comment); + } + + qDebug() << "fileName is " << fileName; + qDebug() << "Command is " << cmd.latexCommand; + qDebug() << "unicodeCommandAsLatin1 is " << unicodeCommandAsLatin1; + qDebug() << "commentAsLatin1 is " << commentAsLatin1; + qDebug() << "comment is " << cmd.comment; + + if(image.load(fileName)) { + + image.setText("Command",cmd.latexCommand); + if( !unicodeCommandAsLatin1.isEmpty() ) { + image.setText("CommandUnicode",unicodeCommandAsLatin1); + image.setText("UnicodePackages",pkgListToString(cmd.unicodePackages)); + } + if (!commentAsLatin1.isEmpty() ) { + image.setText("Comment",commentAsLatin1); + } + + image.setText("Packages",pkgListToString(cmd.packages)); + if(!image.save(fileName,"PNG")) { + qDebug() << "Image " << fileName << " could not be saved"; + exit(1); + } + } + else { + qDebug() << "===writeComment=== ERROR " << fileName << "could not be loaded"; + } + } QString generatePNG(QString latexFile, int index, QString symbolGroupName) { - - QString texfile, texfileWithoutSuffix,pngfile; - int latexret, dvipngret; - - QTemporaryFile file("XXXXXX.tex"); - file.setAutoRemove(false); - if (file.open()) { - QTextStream t(&file); - t.setCodec("UTF-8"); - t << latexFile; - - texfile = file.fileName(); - texfileWithoutSuffix = texfile.left(texfile.length() - 4); - pngfile = QString("img%1%2.png").arg(index,3,10,QChar('0')).arg(symbolGroupName); - qDebug() << texfile; - qDebug() << texfileWithoutSuffix; - qDebug() << pngfile; - - file.close(); - } - - QString texcommand=QString("latex %1").arg(texfile); - QString dvipngcommand=QString("dvipng --strict --picky --freetype -x 1440 -bg Transparent -O -1.2in,-1.2in -T bbox -z 6 -o %1 %2.dvi").arg(pngfile).arg(texfileWithoutSuffix); - - qDebug() << texcommand; - qDebug() << dvipngcommand; - - latexret = system(texcommand.toLatin1()); - dvipngret= system(dvipngcommand.toLatin1()); - - if (latexret) { - qDebug() << "Error compiling the latex file"; - return QString(); - } - - if(dvipngret) { - qDebug() << "Error producing the pngs"; - return QString(); - } - - return pngfile; + + QString texfile, texfileWithoutSuffix,pngfile; + int latexret, dvipngret; + + QTemporaryFile file("XXXXXX.tex"); + file.setAutoRemove(false); + if (file.open()) { + QTextStream t(&file); + t.setCodec("UTF-8"); + t << latexFile; + + texfile = file.fileName(); + texfileWithoutSuffix = texfile.left(texfile.length() - 4); + pngfile = QString("img%1%2.png").arg(index,3,10,QChar('0')).arg(symbolGroupName); + qDebug() << texfile; + qDebug() << texfileWithoutSuffix; + qDebug() << pngfile; + + file.close(); + } + + QString texcommand=QString("latex %1").arg(texfile); + QString dvipngcommand=QString("dvipng --strict --picky --freetype -x 1440 -bg Transparent -O -1.2in,-1.2in -T bbox -z 6 -o %1 %2.dvi").arg(pngfile).arg(texfileWithoutSuffix); + + qDebug() << texcommand; + qDebug() << dvipngcommand; + + latexret = system(texcommand.toLatin1()); + dvipngret= system(dvipngcommand.toLatin1()); + + if (latexret) { + qDebug() << "Error compiling the latex file"; + return QString(); + } + + if(dvipngret) { + qDebug() << "Error producing the pngs"; + return QString(); + } + + return pngfile; } QString generateLatexFile(const Preamble &preamble, const Command &cmd) { - QString output; - Package pkg; - QString cmdString; - - output += QString("\\documentclass[%1]{%2}\n").arg(preamble.classArguments).arg(preamble.className); - output += '\n'; - output += preamble.additional; - output += '\n'; - - for(int i=0; i < cmd.packages.count(); i++){ - pkg = cmd.packages[i]; - if(pkg.arguments.isEmpty()) { - output += QString("\\usepackage{%1}\n").arg(pkg.name); - } - else{ - output += QString("\\usepackage[%1]{%2}\n").arg(pkg.arguments).arg(pkg.name); - } - } - - output += "\\begin{document}\n"; - output += '\n'; - cmdString = !cmd.ImageCommand.isEmpty() ? cmd.ImageCommand : cmd.latexCommand; - output += cmd.mathMode ? QString("\\ensuremath{%1}\n").arg(cmdString) : QString("%1\n").arg(cmdString); - output += '\n'; - output += "\\end{document}\n"; - - return output; + QString output; + Package pkg; + QString cmdString; + + output += QString("\\documentclass[%1]{%2}\n").arg(preamble.classArguments).arg(preamble.className); + output += '\n'; + output += preamble.additional; + output += '\n'; + + for(int i=0; i < cmd.packages.count(); i++) { + pkg = cmd.packages[i]; + if(pkg.arguments.isEmpty()) { + output += QString("\\usepackage{%1}\n").arg(pkg.name); + } + else { + output += QString("\\usepackage[%1]{%2}\n").arg(pkg.arguments).arg(pkg.name); + } + } + + output += "\\begin{document}\n"; + output += '\n'; + cmdString = !cmd.ImageCommand.isEmpty() ? cmd.ImageCommand : cmd.latexCommand; + output += cmd.mathMode ? QString("\\ensuremath{%1}\n").arg(cmdString) : QString("%1\n").arg(cmdString); + output += '\n'; + output += "\\end{document}\n"; + + return output; } -QList getAllPackages(const QDomElement &e){ - - QList packages; - Package pkg; - QDomElement element; - - if(e.isNull()){ - return packages; - } - - QDomNodeList cmdNodes = e.childNodes(); - - for(int i=0; i < cmdNodes.count();i++) { - element = cmdNodes.item(i).toElement(); - if( element.tagName()== "package") { - pkg.name = element.firstChildElement("name").text(); - pkg.arguments = element.firstChildElement("arguments").text(); - packages.append(pkg); - qDebug() << "pkg.name is " << pkg.name; - qDebug() << "pkg.arguments is " << pkg.arguments; - } - } - return packages; +QList getAllPackages(const QDomElement &e) { + + QList packages; + Package pkg; + QDomElement element; + + if(e.isNull()) { + return packages; + } + + QDomNodeList cmdNodes = e.childNodes(); + + for(int i=0; i < cmdNodes.count(); i++) { + element = cmdNodes.item(i).toElement(); + if( element.tagName()== "package") { + pkg.name = element.firstChildElement("name").text(); + pkg.arguments = element.firstChildElement("arguments").text(); + packages.append(pkg); + qDebug() << "pkg.name is " << pkg.name; + qDebug() << "pkg.arguments is " << pkg.arguments; + } + } + return packages; } Command getCommandDefinition(const QDomElement &e, QList unicodePackages) { - if(e.isNull()) { - return Command(); - } - - Package pkg; - Command cmd; - - cmd.unicodePackages = unicodePackages; - cmd.packages = getAllPackages(e); - cmd.mathMode = e.firstChildElement("mathMode").text() == "true" ? true : false; - cmd.comment = e.firstChildElement("comment").text(); - cmd.latexCommand = e.firstChildElement("latexCommand").text(); - cmd.unicodeCommand = e.firstChildElement("unicodeCommand").text(); - cmd.ImageCommand = e.firstChildElement("imageCommand").text(); - - qDebug() << QString("cmd: latexCommand=%1, unicodeCommand=%2, imageCommand=%3, comment=%4, mathmode=%5").arg(cmd.latexCommand).arg(cmd.unicodeCommand).arg(cmd.ImageCommand).arg(cmd.comment).arg(cmd.mathMode); - - if(cmd.packages.count() > 0 ){ - qDebug() << "packages are"; - for(int i=0; i < cmd.packages.count(); i++){ - qDebug() << QString("name=%1, arguments=%2").arg(cmd.packages[i].name).arg(cmd.packages[i].arguments); - } - } - else{ - qDebug() << "no packages to include"; - } - - return cmd; + if(e.isNull()) { + return Command(); + } + + Package pkg; + Command cmd; + + cmd.unicodePackages = unicodePackages; + cmd.packages = getAllPackages(e); + cmd.mathMode = e.firstChildElement("mathMode").text() == "true" ? true : false; + cmd.comment = e.firstChildElement("comment").text(); + cmd.latexCommand = e.firstChildElement("latexCommand").text(); + cmd.unicodeCommand = e.firstChildElement("unicodeCommand").text(); + cmd.ImageCommand = e.firstChildElement("imageCommand").text(); + + qDebug() << QString("cmd: latexCommand=%1, unicodeCommand=%2, imageCommand=%3, comment=%4, mathmode=%5").arg(cmd.latexCommand).arg(cmd.unicodeCommand).arg(cmd.ImageCommand).arg(cmd.comment).arg(cmd.mathMode); + + if(cmd.packages.count() > 0 ) { + qDebug() << "packages are"; + for(int i=0; i < cmd.packages.count(); i++) { + qDebug() << QString("name=%1, arguments=%2").arg(cmd.packages[i].name).arg(cmd.packages[i].arguments); + } + } + else { + qDebug() << "no packages to include"; + } + + return cmd; } -void usage(){ +void usage() { - qDebug() << QString("usage: gesymb-ng mySymbols.xml"); - exit(1); + qDebug() << QString("usage: gesymb-ng mySymbols.xml"); + exit(1); } int main(int argc, char** argv) { - Preamble preamble; - Version version; - QList commands; - QString symbolGroupName; - QList unicodePkgList; - - if(argc < 2){ - usage(); - } - QFile file( argv[1] ); - - if( !file.open( QIODevice::ReadOnly ) ){ - qDebug() << "could not open file"; - return -1; - } - - QString errorMsg; - int errorLine,errorColumn; - QDomDocument doc( "KileSymbolSources" ); - - if( !doc.setContent( &file,false, &errorMsg, &errorLine, &errorColumn) ) - { - qDebug() << "could not find xml content"; - qDebug() << errorMsg; - qDebug() << "line is " << errorLine; - qDebug() << "column is " << errorColumn; - file.close(); - return -2; - } - file.close(); - - // check root element - QDomElement root = doc.documentElement(); - if( root.tagName() != "symbols" ) { - qDebug() << "wrong format"; - return -3; - } - - QDomNode n = root.firstChild(); - while( !n.isNull() ) { - QDomElement e = n.toElement(); - - if( e.isNull() ) { - n = n.nextSibling(); - continue; - } - qDebug() << "element name is " << e.tagName(); - QString tagName = e.tagName(); - - if( tagName == "formatVersion" ){ - version.major = e.attribute("major"); - version.minor = e.attribute("minor"); - } - else if( tagName == "symbolGroupName" ){ - symbolGroupName = e.text(); - } - else if(tagName == "preamble"){ - preamble.className = e.firstChildElement("class").text(); - preamble.classArguments = e.firstChildElement("arguments").text(); - preamble.additional= e.firstChildElement("additional").text(); - - qDebug() << "class is " << preamble.className; - qDebug() << "arguments is " << preamble.classArguments; - qDebug() << "additional is " << preamble.additional; - + Preamble preamble; + Version version; + QList commands; + QString symbolGroupName; + QList unicodePkgList; + + if(argc < 2) { + usage(); } - else if( tagName == "unicodeCommandPackages") { - unicodePkgList = getAllPackages(e); + QFile file( argv[1] ); + + if( !file.open( QIODevice::ReadOnly ) ) { + qDebug() << "could not open file"; + return -1; } - else if( tagName == "commandDefinition" ){ - commands.append(getCommandDefinition(e,unicodePkgList)); + + QString errorMsg; + int errorLine,errorColumn; + QDomDocument doc( "KileSymbolSources" ); + + if( !doc.setContent( &file,false, &errorMsg, &errorLine, &errorColumn) ) + { + qDebug() << "could not find xml content"; + qDebug() << errorMsg; + qDebug() << "line is " << errorLine; + qDebug() << "column is " << errorColumn; + file.close(); + return -2; } - else{ - qDebug() << "unexpected node: " << tagName; + file.close(); + + // check root element + QDomElement root = doc.documentElement(); + if( root.tagName() != "symbols" ) { + qDebug() << "wrong format"; + return -3; } - n = n.nextSibling(); + + QDomNode n = root.firstChild(); + while( !n.isNull() ) { + QDomElement e = n.toElement(); + + if( e.isNull() ) { + n = n.nextSibling(); + continue; + } + qDebug() << "element name is " << e.tagName(); + QString tagName = e.tagName(); + + if( tagName == "formatVersion" ) { + version.major = e.attribute("major"); + version.minor = e.attribute("minor"); + } + else if( tagName == "symbolGroupName" ) { + symbolGroupName = e.text(); + } + else if(tagName == "preamble") { + preamble.className = e.firstChildElement("class").text(); + preamble.classArguments = e.firstChildElement("arguments").text(); + preamble.additional= e.firstChildElement("additional").text(); + + qDebug() << "class is " << preamble.className; + qDebug() << "arguments is " << preamble.classArguments; + qDebug() << "additional is " << preamble.additional; + + } + else if( tagName == "unicodeCommandPackages") { + unicodePkgList = getAllPackages(e); + } + else if( tagName == "commandDefinition" ) { + commands.append(getCommandDefinition(e,unicodePkgList)); + } + else { + qDebug() << "unexpected node: " << tagName; + } + n = n.nextSibling(); } - + QString content,pngfile; - for(int i=0; i < commands.count();i++) { - content = generateLatexFile(preamble,commands[i]); - qDebug() << content; - pngfile = generatePNG(content,i+1,symbolGroupName); - writeImageComments(commands[i],pngfile); - readImageComments(pngfile); + for(int i=0; i < commands.count(); i++) { + content = generateLatexFile(preamble,commands[i]); + qDebug() << content; + pngfile = generatePNG(content,i+1,symbolGroupName); + writeImageComments(commands[i],pngfile); + readImageComments(pngfile); } - + } diff --git a/src/dialogs/abbreviationinputdialog.cpp b/src/dialogs/abbreviationinputdialog.cpp index b8dfa2ef..e6731c66 100644 --- a/src/dialogs/abbreviationinputdialog.cpp +++ b/src/dialogs/abbreviationinputdialog.cpp @@ -1,105 +1,105 @@ /************************************************************************************** begin : Feb 24 2007 copyright : 2007 by Holger Danielsson (holger.danielsson@versanet.de) 2015 by Andreas Cord-Landwerh (cordlandwehr@kde.org) ***************************************************************************************/ /*************************************************************************** * * * 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. * * * ***************************************************************************/ #include "dialogs/abbreviationinputdialog.h" #include "kiledebug.h" #include #include #include #include #include #include #include #include namespace KileDialog { //////////////////// add/edit abbreviation //////////////////// //TODO dialog has non-standard logic // calling code is reacting on the result (i.e., if dialog accpepts or not) and then uses the // changed data accordingling; this should be changed AbbreviationInputDialog::AbbreviationInputDialog(KileWidget::AbbreviationView *listview, QTreeWidgetItem *item, int mode, const char *name) - : QDialog(listview) - , m_listview(listview) - , m_buttonBox(new QDialogButtonBox(QDialogButtonBox::Ok|QDialogButtonBox::Cancel)) - , m_abbrevItem(item) - , m_mode(mode) + : QDialog(listview) + , m_listview(listview) + , m_buttonBox(new QDialogButtonBox(QDialogButtonBox::Ok|QDialogButtonBox::Cancel)) + , m_abbrevItem(item) + , m_mode(mode) { - setWindowTitle(i18n("Add Abbreviation")); - setModal(true); - setObjectName(name); - setMinimumWidth(350); - - QFormLayout *mainLayout = new QFormLayout; - setLayout(mainLayout); - - if(m_mode == KileWidget::AbbreviationView::ALVedit) { - setWindowTitle( i18n("Edit Abbreviation") ); - m_abbrev = m_abbrevItem->text(KileWidget::AbbreviationView::ALVabbrev); - m_expansion = m_abbrevItem->text(KileWidget::AbbreviationView::ALVexpansion); - } - - m_leAbbrev = new QLineEdit(m_abbrev, this); - m_leExpansion = new QLineEdit(m_expansion, this); - QLabel *labelAbbreviation = new QLabel(i18n("&Abbreviation:"), this); - labelAbbreviation->setBuddy(m_leAbbrev); - QLabel *labelExpanded = new QLabel(i18n("&Expanded Text:"), this); - labelExpanded->setBuddy(m_leExpansion); - - mainLayout->addRow(labelAbbreviation, m_leAbbrev); - mainLayout->addRow(labelExpanded, m_leExpansion); - - QRegExp reg("[a-zA-Z0-9]+"); - QRegExpValidator *abbrevValidator = new QRegExpValidator(reg, this); - m_leAbbrev->setValidator(abbrevValidator); - - connect(m_leAbbrev, &QLineEdit::textChanged, this, &AbbreviationInputDialog::onTextChanged); - connect(m_leExpansion, &QLineEdit::textChanged, this, &AbbreviationInputDialog::onTextChanged); - - onTextChanged(QString()); - m_leAbbrev->setFocus(); - - QPushButton *okButton = m_buttonBox->button(QDialogButtonBox::Ok); - okButton->setDefault(true); - okButton->setShortcut(Qt::CTRL | Qt::Key_Return); - connect(m_buttonBox, &QDialogButtonBox::accepted, this, &QDialog::accept); - connect(m_buttonBox, &QDialogButtonBox::rejected, this, &QDialog::reject); - mainLayout->addWidget(m_buttonBox); - okButton->setDefault(true); + setWindowTitle(i18n("Add Abbreviation")); + setModal(true); + setObjectName(name); + setMinimumWidth(350); + + QFormLayout *mainLayout = new QFormLayout; + setLayout(mainLayout); + + if(m_mode == KileWidget::AbbreviationView::ALVedit) { + setWindowTitle( i18n("Edit Abbreviation") ); + m_abbrev = m_abbrevItem->text(KileWidget::AbbreviationView::ALVabbrev); + m_expansion = m_abbrevItem->text(KileWidget::AbbreviationView::ALVexpansion); + } + + m_leAbbrev = new QLineEdit(m_abbrev, this); + m_leExpansion = new QLineEdit(m_expansion, this); + QLabel *labelAbbreviation = new QLabel(i18n("&Abbreviation:"), this); + labelAbbreviation->setBuddy(m_leAbbrev); + QLabel *labelExpanded = new QLabel(i18n("&Expanded Text:"), this); + labelExpanded->setBuddy(m_leExpansion); + + mainLayout->addRow(labelAbbreviation, m_leAbbrev); + mainLayout->addRow(labelExpanded, m_leExpansion); + + QRegExp reg("[a-zA-Z0-9]+"); + QRegExpValidator *abbrevValidator = new QRegExpValidator(reg, this); + m_leAbbrev->setValidator(abbrevValidator); + + connect(m_leAbbrev, &QLineEdit::textChanged, this, &AbbreviationInputDialog::onTextChanged); + connect(m_leExpansion, &QLineEdit::textChanged, this, &AbbreviationInputDialog::onTextChanged); + + onTextChanged(QString()); + m_leAbbrev->setFocus(); + + QPushButton *okButton = m_buttonBox->button(QDialogButtonBox::Ok); + okButton->setDefault(true); + okButton->setShortcut(Qt::CTRL | Qt::Key_Return); + connect(m_buttonBox, &QDialogButtonBox::accepted, this, &QDialog::accept); + connect(m_buttonBox, &QDialogButtonBox::rejected, this, &QDialog::reject); + mainLayout->addWidget(m_buttonBox); + okButton->setDefault(true); } AbbreviationInputDialog::~AbbreviationInputDialog() { } void AbbreviationInputDialog::abbreviation(QString &abbrev, QString &expansion) { - abbrev = m_leAbbrev->text(); - expansion = m_leExpansion->text().trimmed(); + abbrev = m_leAbbrev->text(); + expansion = m_leExpansion->text().trimmed(); } void AbbreviationInputDialog::onTextChanged(const QString &) { - bool state = (m_mode == KileWidget::AbbreviationView::ALVadd) - ? !m_listview->findAbbreviation( m_leAbbrev->text()) : true; - state = state && !m_leAbbrev->text().isEmpty() && !m_leExpansion->text().isEmpty(); - m_buttonBox->button(QDialogButtonBox::Ok)->setEnabled(state); + bool state = (m_mode == KileWidget::AbbreviationView::ALVadd) + ? !m_listview->findAbbreviation( m_leAbbrev->text()) : true; + state = state && !m_leAbbrev->text().isEmpty() && !m_leExpansion->text().isEmpty(); + m_buttonBox->button(QDialogButtonBox::Ok)->setEnabled(state); } } diff --git a/src/dialogs/abbreviationinputdialog.h b/src/dialogs/abbreviationinputdialog.h index 2c31fa81..fb504f0e 100644 --- a/src/dialogs/abbreviationinputdialog.h +++ b/src/dialogs/abbreviationinputdialog.h @@ -1,56 +1,56 @@ /************************************************************************************* begin : Feb 24 2007 copyright : 2007 by Holger Danielsson (holger.danielsson@versanet.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. * * * ***************************************************************************/ #ifndef ABBREVIATIONINPUTDIALOG_H #define ABBREVIATIONINPUTDIALOG_H #include #include #include #include #include "widgets/abbreviationview.h" class QDialogButtonBox; class QLineEdit; //////////////////// add/edit dialog for abbreviations //////////////////// namespace KileDialog { class AbbreviationInputDialog : public QDialog { - Q_OBJECT + Q_OBJECT public: - AbbreviationInputDialog(KileWidget::AbbreviationView *listview, QTreeWidgetItem *item, int mode, const char *name = Q_NULLPTR); - ~AbbreviationInputDialog(); - void abbreviation(QString &abbrev, QString &expansion); + AbbreviationInputDialog(KileWidget::AbbreviationView *listview, QTreeWidgetItem *item, int mode, const char *name = Q_NULLPTR); + ~AbbreviationInputDialog(); + void abbreviation(QString &abbrev, QString &expansion); private Q_SLOTS: - void onTextChanged(const QString &text); + void onTextChanged(const QString &text); private: - KileWidget::AbbreviationView *m_listview; - QDialogButtonBox *m_buttonBox; - QTreeWidgetItem *m_abbrevItem; - QLineEdit *m_leAbbrev; - QLineEdit *m_leExpansion; - int m_mode; - QString m_abbrev, m_expansion; + KileWidget::AbbreviationView *m_listview; + QDialogButtonBox *m_buttonBox; + QTreeWidgetItem *m_abbrevItem; + QLineEdit *m_leAbbrev; + QLineEdit *m_leExpansion; + int m_mode; + QString m_abbrev, m_expansion; }; } #endif diff --git a/src/dialogs/cleandialog.cpp b/src/dialogs/cleandialog.cpp index 41f3c506..040bcb56 100644 --- a/src/dialogs/cleandialog.cpp +++ b/src/dialogs/cleandialog.cpp @@ -1,120 +1,120 @@ /*************************************************************************** date : Jan 22 2004 version : 0.10 copyright : (C) 2004 by Holger Danielsson email : holger.danielsson@t-online.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. * * * ***************************************************************************/ #include "dialogs/cleandialog.h" #include "kiledebug.h" #include #include #include #include #include #include #include #include #include #include #include #include namespace KileDialog { Clean::Clean(QWidget *parent, const QString &filename, const QStringList &extlist) - : QDialog(parent) - , m_extlist(extlist) + : QDialog(parent) + , m_extlist(extlist) { - setWindowTitle(i18n("Delete Files")); - setModal(true); - QVBoxLayout *mainLayout = new QVBoxLayout; - setLayout(mainLayout); - - QWidget *page = new QWidget(this); - mainLayout->addWidget(page); - - // Layout - QVBoxLayout *vbox = new QVBoxLayout(); - vbox->setMargin(0); - page->setLayout(vbox); - - // label widgets - QWidget *labelwidget = new QWidget(page); - mainLayout->addWidget(labelwidget); - QHBoxLayout *labellayout = new QHBoxLayout(); - labellayout->setMargin(0); - labelwidget->setLayout(labellayout); - - // line 1: picture and label - QLabel *picture = new QLabel("", labelwidget); - picture->setPixmap(KIconLoader::global()->loadIcon("dialog-warning", KIconLoader::NoGroup, KIconLoader::SizeMedium)); - QLabel *label = new QLabel(i18n("Do you really want to delete these files?"), labelwidget); - labellayout->addWidget(picture); - labellayout->addSpacing(20); - labellayout->addWidget(label); - - // line 2: m_listview - m_listview = new QTreeWidget(page); - mainLayout->addWidget(m_listview); - m_listview->setHeaderLabel(i18n("Files")); - m_listview->setSortingEnabled(false); - m_listview->setAllColumnsShowFocus(true); - m_listview->setRootIsDecorated(false); - - // insert items into m_listview - QString base = QFileInfo(filename).completeBaseName(); - for(int i = 0; i < m_extlist.count(); ++i) { - QTreeWidgetItem *item = new QTreeWidgetItem(m_listview, - QStringList(base + m_extlist[i])); - item->setFlags(item->flags() | Qt::ItemIsUserCheckable); - item->setCheckState(0, Qt::Checked); - } - - vbox->addWidget(labelwidget, 0, Qt::AlignHCenter); - vbox->addWidget(m_listview); - - // add buttons - QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok|QDialogButtonBox::Cancel); - QPushButton *okButton = buttonBox->button(QDialogButtonBox::Ok); - okButton->setDefault(true); - okButton->setShortcut(Qt::CTRL | Qt::Key_Return); - okButton->setDefault(true); - mainLayout->addWidget(buttonBox); - connect(buttonBox, &QDialogButtonBox::accepted, this, &QDialog::accept); - connect(buttonBox, &QDialogButtonBox::rejected, this, &QDialog::reject); + setWindowTitle(i18n("Delete Files")); + setModal(true); + QVBoxLayout *mainLayout = new QVBoxLayout; + setLayout(mainLayout); + + QWidget *page = new QWidget(this); + mainLayout->addWidget(page); + + // Layout + QVBoxLayout *vbox = new QVBoxLayout(); + vbox->setMargin(0); + page->setLayout(vbox); + + // label widgets + QWidget *labelwidget = new QWidget(page); + mainLayout->addWidget(labelwidget); + QHBoxLayout *labellayout = new QHBoxLayout(); + labellayout->setMargin(0); + labelwidget->setLayout(labellayout); + + // line 1: picture and label + QLabel *picture = new QLabel("", labelwidget); + picture->setPixmap(KIconLoader::global()->loadIcon("dialog-warning", KIconLoader::NoGroup, KIconLoader::SizeMedium)); + QLabel *label = new QLabel(i18n("Do you really want to delete these files?"), labelwidget); + labellayout->addWidget(picture); + labellayout->addSpacing(20); + labellayout->addWidget(label); + + // line 2: m_listview + m_listview = new QTreeWidget(page); + mainLayout->addWidget(m_listview); + m_listview->setHeaderLabel(i18n("Files")); + m_listview->setSortingEnabled(false); + m_listview->setAllColumnsShowFocus(true); + m_listview->setRootIsDecorated(false); + + // insert items into m_listview + QString base = QFileInfo(filename).completeBaseName(); + for(int i = 0; i < m_extlist.count(); ++i) { + QTreeWidgetItem *item = new QTreeWidgetItem(m_listview, + QStringList(base + m_extlist[i])); + item->setFlags(item->flags() | Qt::ItemIsUserCheckable); + item->setCheckState(0, Qt::Checked); + } + + vbox->addWidget(labelwidget, 0, Qt::AlignHCenter); + vbox->addWidget(m_listview); + + // add buttons + QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok|QDialogButtonBox::Cancel); + QPushButton *okButton = buttonBox->button(QDialogButtonBox::Ok); + okButton->setDefault(true); + okButton->setShortcut(Qt::CTRL | Qt::Key_Return); + okButton->setDefault(true); + mainLayout->addWidget(buttonBox); + connect(buttonBox, &QDialogButtonBox::accepted, this, &QDialog::accept); + connect(buttonBox, &QDialogButtonBox::rejected, this, &QDialog::reject); } Clean::~Clean() {} // get all selected items QStringList Clean::cleanList() { - QStringList templist; - - int i = 0; - QTreeWidgetItemIterator it(m_listview); - while (*it) { - if ((*it)->checkState(0) == Qt::Checked && (*it)->text(0).endsWith(m_extlist[i])) { - templist.append(m_extlist[i]); - } - ++it; - ++i; - } - - m_extlist = templist; - return m_extlist; + QStringList templist; + + int i = 0; + QTreeWidgetItemIterator it(m_listview); + while (*it) { + if ((*it)->checkState(0) == Qt::Checked && (*it)->text(0).endsWith(m_extlist[i])) { + templist.append(m_extlist[i]); + } + ++it; + ++i; + } + + m_extlist = templist; + return m_extlist; } } diff --git a/src/dialogs/cleandialog.h b/src/dialogs/cleandialog.h index bb20d5e7..b1739d87 100644 --- a/src/dialogs/cleandialog.h +++ b/src/dialogs/cleandialog.h @@ -1,47 +1,47 @@ /*************************************************************************** date : Jan 22 2004 version : 0.10 copyright : (C) 2004 by Holger Danielsson email : holger.danielsson@t-online.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. * * * ***************************************************************************/ #ifndef CLEANDIALOG_H #define CLEANDIALOG_H #include #include class QTreeWidget; /** * @author Holger Danielsson */ namespace KileDialog { class Clean : public QDialog { - Q_OBJECT + Q_OBJECT - public: - Clean(QWidget *parent, const QString &filename, const QStringList &extlist); - ~Clean(); - QStringList cleanList(); +public: + Clean(QWidget *parent, const QString &filename, const QStringList &extlist); + ~Clean(); + QStringList cleanList(); - private: - QTreeWidget *m_listview; - QStringList m_extlist; +private: + QTreeWidget *m_listview; + QStringList m_extlist; }; } #endif diff --git a/src/dialogs/configcheckerdialog.cpp b/src/dialogs/configcheckerdialog.cpp index 529b258c..dce8de7d 100644 --- a/src/dialogs/configcheckerdialog.cpp +++ b/src/dialogs/configcheckerdialog.cpp @@ -1,318 +1,318 @@ /************************************************************************************* Copyright (C) 2004 by Jeroen Wijnhout (Jeroen.Wijnhout@kdemail.net) 2012-2017 by Michel Ludwig (michel.ludwig@kdemail.net) *************************************************************************************/ /*************************************************************************** * * * 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. * * * ***************************************************************************/ #include "dialogs/configcheckerdialog.h" #include #include #include #include #include #include #include #include #include #include #include #include #include "kiledebug.h" #include "kileinfo.h" namespace KileDialog { class ResultItemDelegate : public QItemDelegate { - public: - ResultItemDelegate(QListWidget *parent) : QItemDelegate(parent) {} - - virtual void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const - { - painter->save(); - drawBackground(painter, option, index); - - QTextDocument document; - document.setHtml(index.data(Qt::UserRole).toString()); - painter->resetMatrix(); - painter->translate(option.rect.topLeft()); - document.drawContents(painter); - painter->restore(); - } - - virtual QSize sizeHint(const QStyleOptionViewItem& /* option */, const QModelIndex &index) const - { - QTextDocument document; - document.setHtml(index.data(Qt::UserRole).toString()); - return document.size().toSize(); - } +public: + ResultItemDelegate(QListWidget *parent) : QItemDelegate(parent) {} + + virtual void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const + { + painter->save(); + drawBackground(painter, option, index); + + QTextDocument document; + document.setHtml(index.data(Qt::UserRole).toString()); + painter->resetMatrix(); + painter->translate(option.rect.topLeft()); + document.drawContents(painter); + painter->restore(); + } + + virtual QSize sizeHint(const QStyleOptionViewItem& /* option */, const QModelIndex &index) const + { + QTextDocument document; + document.setHtml(index.data(Qt::UserRole).toString()); + return document.size().toSize(); + } }; ResultItem::ResultItem(QListWidget *listWidget, const QString &toolGroup, int status, bool isCritical, const QList &tests) -: QListWidgetItem(listWidget) + : QListWidgetItem(listWidget) { - QString rt = "
%2 (%3)
    "; - for (int i = 0; i < tests.count(); ++i) { - QString itemcolor = "black"; - if (tests[i]->status() == ConfigTest::Failure) { - if (tests[i]->isCritical()) { - itemcolor = "#AA0000"; - } - else { - itemcolor = "#FFA201"; - } - } - rt += QString("
  • %2:  %3
  • ").arg(itemcolor).arg(tests[i]->name()).arg(tests[i]->resultText()); - } - rt += "
"; - - QString color = "#00AA00", statustr = i18n("Passed"); - if(status == ConfigTest::Failure) { - if(isCritical) { - color = "#AA0000"; - statustr = i18n("Critical failure, Kile will not function properly"); - } - else { - color = "#FFA201"; - statustr = i18n("Failed, but not critical"); - } - } - - setData(Qt::UserRole, rt.arg(color).arg(toolGroup).arg(statustr)); - - //this is for sorting only - setText(QString::number(status) + ':' + toolGroup); + QString rt = "
%2 (%3)
    "; + for (int i = 0; i < tests.count(); ++i) { + QString itemcolor = "black"; + if (tests[i]->status() == ConfigTest::Failure) { + if (tests[i]->isCritical()) { + itemcolor = "#AA0000"; + } + else { + itemcolor = "#FFA201"; + } + } + rt += QString("
  • %2:  %3
  • ").arg(itemcolor).arg(tests[i]->name()).arg(tests[i]->resultText()); + } + rt += "
"; + + QString color = "#00AA00", statustr = i18n("Passed"); + if(status == ConfigTest::Failure) { + if(isCritical) { + color = "#AA0000"; + statustr = i18n("Critical failure, Kile will not function properly"); + } + else { + color = "#FFA201"; + statustr = i18n("Failed, but not critical"); + } + } + + setData(Qt::UserRole, rt.arg(color).arg(toolGroup).arg(statustr)); + + //this is for sorting only + setText(QString::number(status) + ':' + toolGroup); } ConfigChecker::ConfigChecker(KileInfo *kileInfo, QWidget* parent) - : KAssistantDialog(parent) - , m_ki(kileInfo) - , m_tester(Q_NULLPTR) + : KAssistantDialog(parent) + , m_ki(kileInfo) + , m_tester(Q_NULLPTR) { - // don't show the 'help' button in the title bar - setWindowFlags(this->windowFlags() & ~Qt::WindowContextHelpButtonHint); - setWindowTitle(i18n("System Check")); - setModal(true); - setSizePolicy(QSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred)); - - QWidget *introWidget = new QWidget(this); - QLabel *label = new QLabel(i18n("

This configuration assistant will check whether your system is set up " - "correctly to process LaTeX documents. It will also allow to fine-tune the configuration " - "of Kile while taking the results of the tests into account.

" - "

It is recommended to run this assistant before using Kile for the first time.

" - "

Please press 'Next' now to start the test procedure.

")); - label->setWordWrap(true); - QVBoxLayout *vboxLayout = new QVBoxLayout(this); - vboxLayout->setSizeConstraint(QLayout::SetMinimumSize); - introWidget->setLayout(vboxLayout); - vboxLayout->addWidget(label); - vboxLayout->addStretch(); - m_introPageWidgetItem = addPage(introWidget, i18n("System Check & Configuration Assistant")); - - QWidget *runningTestsWidget = new QWidget(this); - label = new QLabel(i18n("Checking whether the system is set up correctly...")); - vboxLayout = new QVBoxLayout(this); - vboxLayout->setSizeConstraint(QLayout::SetMinimumSize); - runningTestsWidget->setLayout(vboxLayout); - vboxLayout->addStretch(); - vboxLayout->addWidget(label); - m_progressBar = new QProgressBar(this); - vboxLayout->addWidget(m_progressBar); - vboxLayout->addStretch(); - m_runningTestsPageWidgetItem = addPage(runningTestsWidget, ""); - - QWidget *testResultsWidget = new QWidget(this); - vboxLayout = new QVBoxLayout(this); - vboxLayout->setSizeConstraint(QLayout::SetMinimumSize); - testResultsWidget->setLayout(vboxLayout); - m_listWidget = new QListWidget(this); - m_listWidget->setMinimumHeight(200); - vboxLayout->addWidget(m_listWidget); - m_overallResultLabel = new QLabel(this); - vboxLayout->addWidget(m_overallResultLabel); - m_useEmbeddedViewerCheckBox = new QCheckBox(i18n("Configure the viewer tools to use the document viewer")); - vboxLayout->addWidget(m_useEmbeddedViewerCheckBox); - m_useModernConfigurationForLaTeXCheckBox = new QCheckBox(i18n("Use the 'modern' configuration for the TeX, PDFTeX, and LaTeX tools")); - vboxLayout->addWidget(m_useModernConfigurationForLaTeXCheckBox); - m_useModernConfigurationForPDFLaTeX = new QCheckBox(i18n("Use the 'modern' configuration for the PDFLaTeX, LuaLaTeX and XeLaTeX tools")); - vboxLayout->addWidget(m_useModernConfigurationForPDFLaTeX); - vboxLayout->addWidget(new QLabel(i18n("
Please press 'Finish' now to accept the recommended configuration changes."))); - vboxLayout->addStretch(); - - m_testResultsPageWidgetItem = addPage(testResultsWidget, i18n("Test Results")); - - finishButton()->setVisible(false); - backButton()->setVisible(false); - buttonBox()->button(QDialogButtonBox::Help)->setVisible(false); - - m_listWidget->setAlternatingRowColors(true); - m_listWidget->setSelectionMode(QAbstractItemView::NoSelection); - m_listWidget->setItemDelegate(new ResultItemDelegate(m_listWidget)); + // don't show the 'help' button in the title bar + setWindowFlags(this->windowFlags() & ~Qt::WindowContextHelpButtonHint); + setWindowTitle(i18n("System Check")); + setModal(true); + setSizePolicy(QSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred)); + + QWidget *introWidget = new QWidget(this); + QLabel *label = new QLabel(i18n("

This configuration assistant will check whether your system is set up " + "correctly to process LaTeX documents. It will also allow to fine-tune the configuration " + "of Kile while taking the results of the tests into account.

" + "

It is recommended to run this assistant before using Kile for the first time.

" + "

Please press 'Next' now to start the test procedure.

")); + label->setWordWrap(true); + QVBoxLayout *vboxLayout = new QVBoxLayout(this); + vboxLayout->setSizeConstraint(QLayout::SetMinimumSize); + introWidget->setLayout(vboxLayout); + vboxLayout->addWidget(label); + vboxLayout->addStretch(); + m_introPageWidgetItem = addPage(introWidget, i18n("System Check & Configuration Assistant")); + + QWidget *runningTestsWidget = new QWidget(this); + label = new QLabel(i18n("Checking whether the system is set up correctly...")); + vboxLayout = new QVBoxLayout(this); + vboxLayout->setSizeConstraint(QLayout::SetMinimumSize); + runningTestsWidget->setLayout(vboxLayout); + vboxLayout->addStretch(); + vboxLayout->addWidget(label); + m_progressBar = new QProgressBar(this); + vboxLayout->addWidget(m_progressBar); + vboxLayout->addStretch(); + m_runningTestsPageWidgetItem = addPage(runningTestsWidget, ""); + + QWidget *testResultsWidget = new QWidget(this); + vboxLayout = new QVBoxLayout(this); + vboxLayout->setSizeConstraint(QLayout::SetMinimumSize); + testResultsWidget->setLayout(vboxLayout); + m_listWidget = new QListWidget(this); + m_listWidget->setMinimumHeight(200); + vboxLayout->addWidget(m_listWidget); + m_overallResultLabel = new QLabel(this); + vboxLayout->addWidget(m_overallResultLabel); + m_useEmbeddedViewerCheckBox = new QCheckBox(i18n("Configure the viewer tools to use the document viewer")); + vboxLayout->addWidget(m_useEmbeddedViewerCheckBox); + m_useModernConfigurationForLaTeXCheckBox = new QCheckBox(i18n("Use the 'modern' configuration for the TeX, PDFTeX, and LaTeX tools")); + vboxLayout->addWidget(m_useModernConfigurationForLaTeXCheckBox); + m_useModernConfigurationForPDFLaTeX = new QCheckBox(i18n("Use the 'modern' configuration for the PDFLaTeX, LuaLaTeX and XeLaTeX tools")); + vboxLayout->addWidget(m_useModernConfigurationForPDFLaTeX); + vboxLayout->addWidget(new QLabel(i18n("
Please press 'Finish' now to accept the recommended configuration changes."))); + vboxLayout->addStretch(); + + m_testResultsPageWidgetItem = addPage(testResultsWidget, i18n("Test Results")); + + finishButton()->setVisible(false); + backButton()->setVisible(false); + buttonBox()->button(QDialogButtonBox::Help)->setVisible(false); + + m_listWidget->setAlternatingRowColors(true); + m_listWidget->setSelectionMode(QAbstractItemView::NoSelection); + m_listWidget->setItemDelegate(new ResultItemDelegate(m_listWidget)); } ConfigChecker::~ConfigChecker() { } void ConfigChecker::next() { - setCurrentPage(m_runningTestsPageWidgetItem); - nextButton()->setEnabled(false); - run(); + setCurrentPage(m_runningTestsPageWidgetItem); + nextButton()->setEnabled(false); + run(); } void ConfigChecker::run() { - m_tester = new Tester(m_ki, this); + m_tester = new Tester(m_ki, this); - connect(m_tester, SIGNAL(started()), this, SLOT(started())); - connect(m_tester, SIGNAL(percentageDone(int)), this, SLOT(setPercentageDone(int))); - connect(m_tester, SIGNAL(finished(bool)), this, SLOT(finished(bool))); - connect(finishButton(), SIGNAL(clicked()), this, SLOT(assistantFinished())); + connect(m_tester, SIGNAL(started()), this, SLOT(started())); + connect(m_tester, SIGNAL(percentageDone(int)), this, SLOT(setPercentageDone(int))); + connect(m_tester, SIGNAL(finished(bool)), this, SLOT(finished(bool))); + connect(finishButton(), SIGNAL(clicked()), this, SLOT(assistantFinished())); - m_tester->runTests(); + m_tester->runTests(); } void ConfigChecker::slotCancel() { - finished(false); - reject(); + finished(false); + reject(); } void ConfigChecker::started() { - setCursor(Qt::BusyCursor); - setPercentageDone(0); + setCursor(Qt::BusyCursor); + setPercentageDone(0); } void ConfigChecker::finished(bool ok) { - setCurrentPage(m_testResultsPageWidgetItem); - setCursor(Qt::ArrowCursor); - - nextButton()->setVisible(false); - finishButton()->setVisible(true); - QString testResultText = "
"; - - QStringList tools = m_tester->testGroups(); - QStringList critical, failure; - for (int i = 0; i < tools.count(); ++i) { - bool isCritical = false; - int status = m_tester->statusForGroup(tools[i], &isCritical); - if (status == ConfigTest::Failure) { - if(isCritical) { - critical.append(tools[i]); - } - else { - failure.append(tools[i]); - } - } - new ResultItem(m_listWidget, tools[i], status, isCritical, m_tester->resultForGroup(tools[i])); - } - - m_listWidget->sortItems(); - - if(ok) { - QString cap = i18n("Test Results"); - QString overallResultText; - if (critical.count() > 0) { - testResultText += i18n("The following critical tests did not succeed:" - "

%1

Kile cannot function correctly on your system. Please consult the " - "test results
to determine which programs have to be fixed.", critical.join(", ")); - } - else { - if (failure.count() > 0) { - testResultText += i18n("The following tests did not succeed:

%1

You will still " - "be able to use Kile; however, not all features are guaranteed " - "to work.", failure.join(", ")); - } - else { - testResultText += i18n("No problems were detected. Kile will work correctly on your system."); - } - } - - testResultText += "

"; - m_useModernConfigurationForLaTeXCheckBox->setChecked(m_tester->areSrcSpecialsSupportedForLaTeX()); - m_useModernConfigurationForPDFLaTeX->setChecked(m_tester->isSyncTeXSupportedForPDFLaTeX()); + setCurrentPage(m_testResultsPageWidgetItem); + setCursor(Qt::ArrowCursor); + + nextButton()->setVisible(false); + finishButton()->setVisible(true); + QString testResultText = "
"; + + QStringList tools = m_tester->testGroups(); + QStringList critical, failure; + for (int i = 0; i < tools.count(); ++i) { + bool isCritical = false; + int status = m_tester->statusForGroup(tools[i], &isCritical); + if (status == ConfigTest::Failure) { + if(isCritical) { + critical.append(tools[i]); + } + else { + failure.append(tools[i]); + } + } + new ResultItem(m_listWidget, tools[i], status, isCritical, m_tester->resultForGroup(tools[i])); + } + + m_listWidget->sortItems(); + + if(ok) { + QString cap = i18n("Test Results"); + QString overallResultText; + if (critical.count() > 0) { + testResultText += i18n("The following critical tests did not succeed:" + "

%1

Kile cannot function correctly on your system. Please consult the " + "test results
to determine which programs have to be fixed.", critical.join(", ")); + } + else { + if (failure.count() > 0) { + testResultText += i18n("The following tests did not succeed:

%1

You will still " + "be able to use Kile; however, not all features are guaranteed " + "to work.", failure.join(", ")); + } + else { + testResultText += i18n("No problems were detected. Kile will work correctly on your system."); + } + } + + testResultText += "

"; + m_useModernConfigurationForLaTeXCheckBox->setChecked(m_tester->areSrcSpecialsSupportedForLaTeX()); + m_useModernConfigurationForPDFLaTeX->setChecked(m_tester->isSyncTeXSupportedForPDFLaTeX()); //TODO: simplify this as Okular now always supports viewer mode - if(m_tester->isViewerModeSupportedInOkular()) { - m_useEmbeddedViewerCheckBox->setVisible(true); - m_useEmbeddedViewerCheckBox->setChecked(true); - if(m_tester->isSyncTeXSupportedForPDFLaTeX()) { - testResultText += i18n("The embedded document viewer is available and live preview is supported."); - } - else { - testResultText += i18n("The embedded document viewer is available, but the installed version of PDFLaTeX is
" - "not compatible with live preview."); - } - } - else { - m_useEmbeddedViewerCheckBox->setVisible(false); - m_useEmbeddedViewerCheckBox->setChecked(false); - - testResultText += i18n("The embedded document viewer is not available (as Okular is either not available or the installed
version is too old). " - "Live preview is hence not supported."); - } - - testResultText += "

"; - - m_overallResultLabel->setText(testResultText); - - finishButton()->setEnabled(true); - finishButton()->setDefault(true); - finishButton()->setFocus(); - } - else { - // start by hiding all the labels - Q_FOREACH(QWidget *widget, m_testResultsPageWidgetItem->widget()->findChildren()) { - widget->setVisible(false); - } - // and then we show those again that we want - m_overallResultLabel->setVisible(true); - m_useEmbeddedViewerCheckBox->setVisible(false); - m_useModernConfigurationForLaTeXCheckBox->setVisible(false); - m_useModernConfigurationForPDFLaTeX->setVisible(false); - - m_overallResultLabel->setText(i18n("
The tests could not be finished correctly. " - "Please check the available disk space.")); - finishButton()->setEnabled(false); - } + if(m_tester->isViewerModeSupportedInOkular()) { + m_useEmbeddedViewerCheckBox->setVisible(true); + m_useEmbeddedViewerCheckBox->setChecked(true); + if(m_tester->isSyncTeXSupportedForPDFLaTeX()) { + testResultText += i18n("The embedded document viewer is available and live preview is supported."); + } + else { + testResultText += i18n("The embedded document viewer is available, but the installed version of PDFLaTeX is
" + "not compatible with live preview."); + } + } + else { + m_useEmbeddedViewerCheckBox->setVisible(false); + m_useEmbeddedViewerCheckBox->setChecked(false); + + testResultText += i18n("The embedded document viewer is not available (as Okular is either not available or the installed
version is too old). " + "Live preview is hence not supported."); + } + + testResultText += "

"; + + m_overallResultLabel->setText(testResultText); + + finishButton()->setEnabled(true); + finishButton()->setDefault(true); + finishButton()->setFocus(); + } + else { + // start by hiding all the labels + Q_FOREACH(QWidget *widget, m_testResultsPageWidgetItem->widget()->findChildren()) { + widget->setVisible(false); + } + // and then we show those again that we want + m_overallResultLabel->setVisible(true); + m_useEmbeddedViewerCheckBox->setVisible(false); + m_useModernConfigurationForLaTeXCheckBox->setVisible(false); + m_useModernConfigurationForPDFLaTeX->setVisible(false); + + m_overallResultLabel->setText(i18n("
The tests could not be finished correctly. " + "Please check the available disk space.")); + finishButton()->setEnabled(false); + } } void ConfigChecker::assistantFinished() { - if(m_useEmbeddedViewerCheckBox->isChecked()) { - m_ki->toolManager()->setConfigName("ViewPS", "Document Viewer"); - m_ki->toolManager()->setConfigName("ViewPDF", "Document Viewer"); - m_ki->toolManager()->setConfigName("ViewDVI", "Document Viewer"); - } - if(m_useModernConfigurationForLaTeXCheckBox->isChecked()) { - m_ki->toolManager()->setConfigName("TeX", "Modern"); - m_ki->toolManager()->setConfigName("PDFTeX", "Modern"); - m_ki->toolManager()->setConfigName("LaTeX", "Modern"); - } - if(m_useModernConfigurationForPDFLaTeX->isChecked()) { - m_ki->toolManager()->setConfigName("PDFLaTeX", "Modern"); - m_ki->toolManager()->setConfigName("XeLaTeX", "PDF Modern"); - m_ki->toolManager()->setConfigName("LuaLaTeX", "PDF Modern"); - } + if(m_useEmbeddedViewerCheckBox->isChecked()) { + m_ki->toolManager()->setConfigName("ViewPS", "Document Viewer"); + m_ki->toolManager()->setConfigName("ViewPDF", "Document Viewer"); + m_ki->toolManager()->setConfigName("ViewDVI", "Document Viewer"); + } + if(m_useModernConfigurationForLaTeXCheckBox->isChecked()) { + m_ki->toolManager()->setConfigName("TeX", "Modern"); + m_ki->toolManager()->setConfigName("PDFTeX", "Modern"); + m_ki->toolManager()->setConfigName("LaTeX", "Modern"); + } + if(m_useModernConfigurationForPDFLaTeX->isChecked()) { + m_ki->toolManager()->setConfigName("PDFLaTeX", "Modern"); + m_ki->toolManager()->setConfigName("XeLaTeX", "PDF Modern"); + m_ki->toolManager()->setConfigName("LuaLaTeX", "PDF Modern"); + } } void ConfigChecker::setPercentageDone(int p) { - m_progressBar->setValue(p); + m_progressBar->setValue(p); } } diff --git a/src/dialogs/configcheckerdialog.h b/src/dialogs/configcheckerdialog.h index 03db899f..e3654a63 100644 --- a/src/dialogs/configcheckerdialog.h +++ b/src/dialogs/configcheckerdialog.h @@ -1,68 +1,68 @@ /************************************************************************************* Copyright (C) 2004 by Jeroen Wijnhout (Jeroen.Wijnhout@kdemail.net) 2012 by Michel Ludwig (michel.ludwig@kdemail.net) *************************************************************************************/ /*************************************************************************** * * * 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. * * * ***************************************************************************/ #ifndef CONFIGCHECKERDIALOG_H #define CONFIGCHECKERDIALOG_H #include #include #include #include #include #include #include "configtester.h" class KileInfo; namespace KileDialog { class ResultItem : public QListWidgetItem { - public: - ResultItem(QListWidget *listWidget, const QString &toolGroup, int status, bool isCritical, const QList &tests); +public: + ResultItem(QListWidget *listWidget, const QString &toolGroup, int status, bool isCritical, const QList &tests); }; class ConfigChecker : public KAssistantDialog { - Q_OBJECT + Q_OBJECT - public: - ConfigChecker(KileInfo *kileInfo, QWidget* parent = Q_NULLPTR); - ~ConfigChecker(); +public: + ConfigChecker(KileInfo *kileInfo, QWidget* parent = Q_NULLPTR); + ~ConfigChecker(); - public Q_SLOTS: - void run(); - void started(); - void finished(bool); - void setPercentageDone(int); - void slotCancel(); +public Q_SLOTS: + void run(); + void started(); + void finished(bool); + void setPercentageDone(int); + void slotCancel(); - void next(); + void next(); - protected Q_SLOTS: - void assistantFinished(); +protected Q_SLOTS: + void assistantFinished(); - private: - KileInfo *m_ki; - Tester *m_tester; - QProgressBar *m_progressBar; - QListWidget *m_listWidget; - QLabel *m_overallResultLabel; - KPageWidgetItem *m_introPageWidgetItem, *m_runningTestsPageWidgetItem, *m_testResultsPageWidgetItem; - QCheckBox *m_useEmbeddedViewerCheckBox, *m_useModernConfigurationForLaTeXCheckBox, *m_useModernConfigurationForPDFLaTeX; +private: + KileInfo *m_ki; + Tester *m_tester; + QProgressBar *m_progressBar; + QListWidget *m_listWidget; + QLabel *m_overallResultLabel; + KPageWidgetItem *m_introPageWidgetItem, *m_runningTestsPageWidgetItem, *m_testResultsPageWidgetItem; + QCheckBox *m_useEmbeddedViewerCheckBox, *m_useModernConfigurationForLaTeXCheckBox, *m_useModernConfigurationForPDFLaTeX; }; } #endif diff --git a/src/dialogs/configurationdialog.cpp b/src/dialogs/configurationdialog.cpp index c8dae410..81300ddb 100644 --- a/src/dialogs/configurationdialog.cpp +++ b/src/dialogs/configurationdialog.cpp @@ -1,367 +1,367 @@ /*************************************************************************************************** begin : Wed Jun 6 2001 copyright : (C) 2003 by Jeroen Wijnhout (Jeroen.Wijnhout@kdemail.net) (C) 2005-2007 by Holger Danielsson (holger.danielsson@versanet.de) (C) 2007-2016 by Michel Ludwig (michel.ludwig@kdemail.net) ***************************************************************************************************/ /*************************************************************************** * * * 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. * * * ***************************************************************************/ #include "dialogs/configurationdialog.h" #include #include #include #include #include #include #include #include #include #include #include #include "editorextension.h" #include "errorhandler.h" #include "kileconfig.h" #include "kiledebug.h" #include "kiledocmanager.h" #include "kileinfo.h" #include "kiletoolmanager.h" #include "kileviewmanager.h" #include "widgets/appearanceconfigwidget.h" #include "widgets/generalconfigwidget.h" #include "widgets/helpconfigwidget.h" #include "widgets/latexconfigwidget.h" #include "widgets/livepreviewconfigwidget.h" #include "widgets/previewconfigwidget.h" #include "widgets/scriptingconfigwidget.h" #include "widgets/scrollwidget.h" #include "widgets/toolconfigwidget.h" #include "widgets/usermenuconfigwidget.h" namespace KileDialog { - Config::Config(KConfig *config, KileInfo *ki, QWidget* parent) - : KPageDialog(parent), - m_config(config), - m_ki(ki) - { - setWindowTitle(i18n("Configure")); - setModal(true); - setObjectName("kileconfiguration"); - setFaceType(Tree); - - m_config->sync(); - - // we need a dialog manager - m_manager = new KConfigDialogManager(this,KileConfig::self()); - - KPageWidgetItem* kilePageWidgetItem = addConfigFolder(i18n("Kile"), "kile"); - KPageWidgetItem* latexPageWidgetItem = addConfigFolder(i18n("LaTeX"), "latex-config"); - KPageWidgetItem* toolsPageWidgetItem = addConfigFolder(i18n("Tools"), "system-run"); - KPageWidgetItem* editorPageWidgetItem = addConfigFolder(i18n("Editor"), "accessories-text-editor"); - - // setup all configuration pages - setupGeneralOptions(kilePageWidgetItem); - setupAppearance(kilePageWidgetItem); - setupCodeCompletion(kilePageWidgetItem); // complete configuration (dani) - setupHelp(kilePageWidgetItem); - setupScripting(kilePageWidgetItem); - setupUsermenu(kilePageWidgetItem); - setupLivePreview(kilePageWidgetItem); - - setupLatex(latexPageWidgetItem); - setupEnvironment(latexPageWidgetItem); - setupGraphics(latexPageWidgetItem); - setupStructure(latexPageWidgetItem); - setupSymbolView(latexPageWidgetItem); - - setupTools(toolsPageWidgetItem); - setupQuickPreview(toolsPageWidgetItem); // QuickPreview (dani) - - setupEditor(editorPageWidgetItem); - - { - // every config page is added to a KileWidget::ScrollWidget, but all the scroll widgets should have - // the same size; first we find the maximal page size - QSize maximumSizeHint; - for(KPageWidgetItem *item : const_cast&>(m_pageWidgetItemList)) { // use 'qAsConst' later - QScrollArea *scrollArea = dynamic_cast(item->widget()); - if(!scrollArea) { - qWarning() << "One scroll area not a KileWidget::ScrollWidget!"; - continue; - } - maximumSizeHint = maximumSizeHint.expandedTo(scrollArea->widget()->sizeHint()); - } - // and then we set the size of all the scroll widgets to the maximal page size - for(KPageWidgetItem *item : const_cast&>(m_pageWidgetItemList)) { // use 'qAsConst' later - KileWidget::ScrollWidget *scrollWidget = dynamic_cast(item->widget()); - if(!scrollWidget) { - continue; - } - scrollWidget->setPreferredSize(maximumSizeHint); - } - } - - m_configDialogSize = m_config->group("KileConfigDialog"); - - resize(sizeHint()); - // as of October 2016, 'restoreWindowSize' has no effect when called directly from here - QTimer::singleShot(0, this, [=] () { - KWindowConfig::restoreWindowSize(windowHandle(), m_configDialogSize); - }); - // setup connections - //connect(m_manager, SIGNAL(widgetModified()), this, SLOT(slotWidgetModified())); - connect(this, &KPageDialog::accepted, this, &Config::slotAcceptChanges); - connect(this, &KPageDialog::accepted, m_manager, &KConfigDialogManager::updateSettings); - connect(this, &KPageDialog::rejected, this, [=] () { - m_config->markAsClean(); - }); - } - - Config::~Config() - { - KWindowConfig::saveWindowSize(windowHandle(), m_configDialogSize); - - delete m_manager; - } - - void Config::show() - { - m_manager->updateWidgets(); - QDialog::show(); - } - - //////////////////// add a new folder //////////////////// - - KPageWidgetItem* Config::addConfigFolder(const QString §ion, const QString &icon) - { - KPageWidgetItem *toReturn = addPage(new QWidget(this), section); - toReturn->setIcon(QIcon::fromTheme(icon)); - - return toReturn; - } - - //////////////////// add a new page //////////////////// - - KPageWidgetItem* Config::addConfigPage(KPageWidgetItem* parent, QWidget *page, const QString &itemName, - const QString &pixmapName, const QString &header) - { - return addConfigPage(parent, page, itemName, QIcon::fromTheme(pixmapName), header); - } - - KPageWidgetItem* Config::addConfigPage(KPageWidgetItem* parent, QWidget *page, - const QString &itemName, const QIcon& icon, - const QString &header) - { - KILE_DEBUG_MAIN << "slot: add config page item=" << itemName; - - // Create scroll widget for the page - KileWidget::ScrollWidget *scrollWidget = new KileWidget::ScrollWidget(this); - scrollWidget->setFrameShape(QFrame::NoFrame); - scrollWidget->setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded); - scrollWidget->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded); - scrollWidget->setWidget(page); - scrollWidget->setWidgetResizable(true); - page->setMinimumSize(page->sizeHint()); - page->resize(page->sizeHint()); - - // add page - KPageWidgetItem *pageWidgetItem = new KPageWidgetItem(scrollWidget, itemName); - pageWidgetItem->setIcon(icon); - pageWidgetItem->setHeader(header); - - addSubPage(parent, pageWidgetItem); - - // add to the dialog manager - m_manager->addWidget(page); - - m_pageWidgetItemList << pageWidgetItem; - - return pageWidgetItem; - } - - //////////////////// General Options //////////////////// - - void Config::setupGeneralOptions(KPageWidgetItem* parent) - { - generalPage = new KileWidgetGeneralConfig(this); - generalPage->setObjectName("LaTeX"); - KPageWidgetItem *item = addConfigPage(parent, generalPage, i18n("General"), "configure", i18n("General Settings")); - setCurrentPage(item); - } - - //////////////////// Tools Configuration //////////////////// - - void Config::setupTools(KPageWidgetItem* parent) - { - toolPage = new KileWidget::ToolConfig(m_ki->toolManager(), this); - addConfigPage(parent, toolPage, i18n("Build"), "application-x-executable", i18n("Build")); - } - - //////////////////// Scripting //////////////////// - - void Config::setupScripting(KPageWidgetItem* parent) - { - scriptingPage = new KileWidgetScriptingConfig(this); - scriptingPage->setObjectName("Scripting"); - // we hide this now as the feature is not implemented currently - scriptingPage->executionTimeLimitGroupBox->setHidden(true); - addConfigPage(parent, scriptingPage, i18n("Scripting"), "application-x-executable-script", i18n("Scripting Support")); - } - - //////////////////// Usermenu //////////////////// - - void Config::setupUsermenu(KPageWidgetItem *parent) - { - usermenuPage = new KileWidgetUsermenuConfig(m_ki->userMenu(), this); - usermenuPage->setObjectName("Usermenu"); - addConfigPage(parent, usermenuPage, i18n("User Menu"), "usermenu-install", i18n("User Menu")); - } - - //////////////////// LaTeX specific editing options //////////////////// - - //////////////////// Complete configuration (dani) //////////////////// - - void Config::setupCodeCompletion(KPageWidgetItem* parent) - { - completePage = new CodeCompletionConfigWidget(m_config, m_ki->errorHandler()); - completePage->readConfig(); - - addConfigPage(parent, completePage, i18n("Complete"), "text-x-tex", i18n("Code Completion")); - } - - //////////////////// QuickPreview (dani) //////////////////// - - void Config::setupQuickPreview(KPageWidgetItem* parent) - { - previewPage = new KileWidgetPreviewConfig(m_config,m_ki->quickPreview(),this); - previewPage->readConfig(); - - addConfigPage(parent, previewPage, i18n("Preview"), "preview", i18n("Quick Preview")); - } - - void Config::setupHelp(KPageWidgetItem* parent) - { - helpPage = new KileWidgetHelpConfig(this); - helpPage->setHelp(m_ki->help()); - - addConfigPage(parent, helpPage, i18n("Help"),"help-browser"); - } - - void Config::setupLivePreview(KPageWidgetItem* parent) - { - livePreviewPage = new KileWidgetLivePreviewConfig(m_config, this); - livePreviewPage->readConfig(); - - addConfigPage(parent, livePreviewPage, i18n("Live Preview"), "preview", i18n("Live Preview")); - } - - void Config::setupAppearance(KPageWidgetItem* parent) - { - appearancePage = new KileWidgetAppearanceConfig(m_config, this); - appearancePage->readConfig(); - - addConfigPage(parent, appearancePage, i18n("Appearance"), "preview", i18n("Appearance")); - } - - //////////////////// LaTeX environments //////////////////// - - void Config::setupLatex(KPageWidgetItem* parent) - { - latexPage = new KileWidgetLatexConfig(this); - latexPage->setObjectName("LaTeX"); - latexPage->kcfg_DoubleQuotes->addItems(m_ki->editorExtension()->doubleQuotesListI18N()); - latexPage->setLatexCommands(m_config,m_ki->latexCommands()); - - addConfigPage(parent, latexPage, i18n("General"), "configure"); - } - - void Config::setupEnvironment(KPageWidgetItem* parent) - { - envPage = new KileWidgetEnvironmentConfig(this); - envPage->setObjectName("LaTeX"); - addConfigPage(parent, envPage, i18n("Environments"), "environment"); - } - - void Config::setupGraphics(KPageWidgetItem* parent) - { - graphicsPage = new KileWidgetGraphicsConfig(this); - graphicsPage->setObjectName("Graphics"); - graphicsPage->m_lbImagemagick->setText( ( KileConfig::imagemagick() ) ? i18n("installed") : i18n("not installed") ); - addConfigPage(parent, graphicsPage, i18n("Graphics"), "graphicspage"); - } - - void Config::setupStructure(KPageWidgetItem* parent) - { - structurePage = new KileWidgetStructureViewConfig(this); - structurePage->setObjectName("StructureView"); - addConfigPage(parent, structurePage, i18n("Structure View"), "view-list-tree"); - } - - void Config::setupSymbolView(KPageWidgetItem* parent) - { - symbolViewPage = new KileWidgetSymbolViewConfig(this); - symbolViewPage->setObjectName("SymbolView"); - addConfigPage(parent, symbolViewPage, i18n("Symbol View"), "math0"); - } - - //////////////////// Editor //////////////////// - - void Config::setupEditor(KPageWidgetItem* parent) - { - m_editorSettingsChanged = false; - m_editorPages.clear(); - - KTextEditor::Editor* editor = m_ki->docManager()->getEditor(); - if(!editor) { - return; - } - for(int i = 0; i < editor->configPages(); ++i) { - KTextEditor::ConfigPage *configPage = editor->configPage(i, parent->widget()); - KPageWidgetItem *pageWidgetItem = addConfigPage(parent, configPage, configPage->name(), - configPage->icon(), - configPage->fullName()); - connect(configPage, &KTextEditor::ConfigPage::changed, this, [=] { - m_editorSettingsChanged = true; - }); - m_editorPages.insert(pageWidgetItem, configPage); - } - } - - //////////////////// slots //////////////////// - - void Config::slotAcceptChanges() - { - KILE_DEBUG_MAIN << " slot acceptChanges (" << m_manager->hasChanged() << "," << m_editorSettingsChanged << ")"; - - // editor settings are only available, when at least one document is opened - if(m_editorSettingsChanged) { - QMapIterator i(m_editorPages); - while (i.hasNext()) { - i.next(); - i.value()->apply(); - } - } - - // Kile settings - toolPage->writeConfig(); // config all tools - completePage->writeConfig(); // Complete configuration (dani) - previewPage->writeConfig(); // Quick Preview (dani) - usermenuPage->writeConfig(); - livePreviewPage->writeConfig(); - - m_config->sync(); - } +Config::Config(KConfig *config, KileInfo *ki, QWidget* parent) + : KPageDialog(parent), + m_config(config), + m_ki(ki) +{ + setWindowTitle(i18n("Configure")); + setModal(true); + setObjectName("kileconfiguration"); + setFaceType(Tree); + + m_config->sync(); + + // we need a dialog manager + m_manager = new KConfigDialogManager(this,KileConfig::self()); + + KPageWidgetItem* kilePageWidgetItem = addConfigFolder(i18n("Kile"), "kile"); + KPageWidgetItem* latexPageWidgetItem = addConfigFolder(i18n("LaTeX"), "latex-config"); + KPageWidgetItem* toolsPageWidgetItem = addConfigFolder(i18n("Tools"), "system-run"); + KPageWidgetItem* editorPageWidgetItem = addConfigFolder(i18n("Editor"), "accessories-text-editor"); + + // setup all configuration pages + setupGeneralOptions(kilePageWidgetItem); + setupAppearance(kilePageWidgetItem); + setupCodeCompletion(kilePageWidgetItem); // complete configuration (dani) + setupHelp(kilePageWidgetItem); + setupScripting(kilePageWidgetItem); + setupUsermenu(kilePageWidgetItem); + setupLivePreview(kilePageWidgetItem); + + setupLatex(latexPageWidgetItem); + setupEnvironment(latexPageWidgetItem); + setupGraphics(latexPageWidgetItem); + setupStructure(latexPageWidgetItem); + setupSymbolView(latexPageWidgetItem); + + setupTools(toolsPageWidgetItem); + setupQuickPreview(toolsPageWidgetItem); // QuickPreview (dani) + + setupEditor(editorPageWidgetItem); + + { + // every config page is added to a KileWidget::ScrollWidget, but all the scroll widgets should have + // the same size; first we find the maximal page size + QSize maximumSizeHint; + for(KPageWidgetItem *item : const_cast&>(m_pageWidgetItemList)) { // use 'qAsConst' later + QScrollArea *scrollArea = dynamic_cast(item->widget()); + if(!scrollArea) { + qWarning() << "One scroll area not a KileWidget::ScrollWidget!"; + continue; + } + maximumSizeHint = maximumSizeHint.expandedTo(scrollArea->widget()->sizeHint()); + } + // and then we set the size of all the scroll widgets to the maximal page size + for(KPageWidgetItem *item : const_cast&>(m_pageWidgetItemList)) { // use 'qAsConst' later + KileWidget::ScrollWidget *scrollWidget = dynamic_cast(item->widget()); + if(!scrollWidget) { + continue; + } + scrollWidget->setPreferredSize(maximumSizeHint); + } + } + + m_configDialogSize = m_config->group("KileConfigDialog"); + + resize(sizeHint()); + // as of October 2016, 'restoreWindowSize' has no effect when called directly from here + QTimer::singleShot(0, this, [=] () { + KWindowConfig::restoreWindowSize(windowHandle(), m_configDialogSize); + }); + // setup connections + //connect(m_manager, SIGNAL(widgetModified()), this, SLOT(slotWidgetModified())); + connect(this, &KPageDialog::accepted, this, &Config::slotAcceptChanges); + connect(this, &KPageDialog::accepted, m_manager, &KConfigDialogManager::updateSettings); + connect(this, &KPageDialog::rejected, this, [=] () { + m_config->markAsClean(); + }); +} + +Config::~Config() +{ + KWindowConfig::saveWindowSize(windowHandle(), m_configDialogSize); + + delete m_manager; +} + +void Config::show() +{ + m_manager->updateWidgets(); + QDialog::show(); +} + +//////////////////// add a new folder //////////////////// + +KPageWidgetItem* Config::addConfigFolder(const QString §ion, const QString &icon) +{ + KPageWidgetItem *toReturn = addPage(new QWidget(this), section); + toReturn->setIcon(QIcon::fromTheme(icon)); + + return toReturn; +} + +//////////////////// add a new page //////////////////// + +KPageWidgetItem* Config::addConfigPage(KPageWidgetItem* parent, QWidget *page, const QString &itemName, + const QString &pixmapName, const QString &header) +{ + return addConfigPage(parent, page, itemName, QIcon::fromTheme(pixmapName), header); +} + +KPageWidgetItem* Config::addConfigPage(KPageWidgetItem* parent, QWidget *page, + const QString &itemName, const QIcon& icon, + const QString &header) +{ + KILE_DEBUG_MAIN << "slot: add config page item=" << itemName; + + // Create scroll widget for the page + KileWidget::ScrollWidget *scrollWidget = new KileWidget::ScrollWidget(this); + scrollWidget->setFrameShape(QFrame::NoFrame); + scrollWidget->setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded); + scrollWidget->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded); + scrollWidget->setWidget(page); + scrollWidget->setWidgetResizable(true); + page->setMinimumSize(page->sizeHint()); + page->resize(page->sizeHint()); + + // add page + KPageWidgetItem *pageWidgetItem = new KPageWidgetItem(scrollWidget, itemName); + pageWidgetItem->setIcon(icon); + pageWidgetItem->setHeader(header); + + addSubPage(parent, pageWidgetItem); + + // add to the dialog manager + m_manager->addWidget(page); + + m_pageWidgetItemList << pageWidgetItem; + + return pageWidgetItem; +} + +//////////////////// General Options //////////////////// + +void Config::setupGeneralOptions(KPageWidgetItem* parent) +{ + generalPage = new KileWidgetGeneralConfig(this); + generalPage->setObjectName("LaTeX"); + KPageWidgetItem *item = addConfigPage(parent, generalPage, i18n("General"), "configure", i18n("General Settings")); + setCurrentPage(item); +} + +//////////////////// Tools Configuration //////////////////// + +void Config::setupTools(KPageWidgetItem* parent) +{ + toolPage = new KileWidget::ToolConfig(m_ki->toolManager(), this); + addConfigPage(parent, toolPage, i18n("Build"), "application-x-executable", i18n("Build")); +} + +//////////////////// Scripting //////////////////// + +void Config::setupScripting(KPageWidgetItem* parent) +{ + scriptingPage = new KileWidgetScriptingConfig(this); + scriptingPage->setObjectName("Scripting"); + // we hide this now as the feature is not implemented currently + scriptingPage->executionTimeLimitGroupBox->setHidden(true); + addConfigPage(parent, scriptingPage, i18n("Scripting"), "application-x-executable-script", i18n("Scripting Support")); +} + +//////////////////// Usermenu //////////////////// + +void Config::setupUsermenu(KPageWidgetItem *parent) +{ + usermenuPage = new KileWidgetUsermenuConfig(m_ki->userMenu(), this); + usermenuPage->setObjectName("Usermenu"); + addConfigPage(parent, usermenuPage, i18n("User Menu"), "usermenu-install", i18n("User Menu")); +} + +//////////////////// LaTeX specific editing options //////////////////// + +//////////////////// Complete configuration (dani) //////////////////// + +void Config::setupCodeCompletion(KPageWidgetItem* parent) +{ + completePage = new CodeCompletionConfigWidget(m_config, m_ki->errorHandler()); + completePage->readConfig(); + + addConfigPage(parent, completePage, i18n("Complete"), "text-x-tex", i18n("Code Completion")); +} + +//////////////////// QuickPreview (dani) //////////////////// + +void Config::setupQuickPreview(KPageWidgetItem* parent) +{ + previewPage = new KileWidgetPreviewConfig(m_config,m_ki->quickPreview(),this); + previewPage->readConfig(); + + addConfigPage(parent, previewPage, i18n("Preview"), "preview", i18n("Quick Preview")); +} + +void Config::setupHelp(KPageWidgetItem* parent) +{ + helpPage = new KileWidgetHelpConfig(this); + helpPage->setHelp(m_ki->help()); + + addConfigPage(parent, helpPage, i18n("Help"),"help-browser"); +} + +void Config::setupLivePreview(KPageWidgetItem* parent) +{ + livePreviewPage = new KileWidgetLivePreviewConfig(m_config, this); + livePreviewPage->readConfig(); + + addConfigPage(parent, livePreviewPage, i18n("Live Preview"), "preview", i18n("Live Preview")); +} + +void Config::setupAppearance(KPageWidgetItem* parent) +{ + appearancePage = new KileWidgetAppearanceConfig(m_config, this); + appearancePage->readConfig(); + + addConfigPage(parent, appearancePage, i18n("Appearance"), "preview", i18n("Appearance")); +} + +//////////////////// LaTeX environments //////////////////// + +void Config::setupLatex(KPageWidgetItem* parent) +{ + latexPage = new KileWidgetLatexConfig(this); + latexPage->setObjectName("LaTeX"); + latexPage->kcfg_DoubleQuotes->addItems(m_ki->editorExtension()->doubleQuotesListI18N()); + latexPage->setLatexCommands(m_config,m_ki->latexCommands()); + + addConfigPage(parent, latexPage, i18n("General"), "configure"); +} + +void Config::setupEnvironment(KPageWidgetItem* parent) +{ + envPage = new KileWidgetEnvironmentConfig(this); + envPage->setObjectName("LaTeX"); + addConfigPage(parent, envPage, i18n("Environments"), "environment"); +} + +void Config::setupGraphics(KPageWidgetItem* parent) +{ + graphicsPage = new KileWidgetGraphicsConfig(this); + graphicsPage->setObjectName("Graphics"); + graphicsPage->m_lbImagemagick->setText( ( KileConfig::imagemagick() ) ? i18n("installed") : i18n("not installed") ); + addConfigPage(parent, graphicsPage, i18n("Graphics"), "graphicspage"); +} + +void Config::setupStructure(KPageWidgetItem* parent) +{ + structurePage = new KileWidgetStructureViewConfig(this); + structurePage->setObjectName("StructureView"); + addConfigPage(parent, structurePage, i18n("Structure View"), "view-list-tree"); +} + +void Config::setupSymbolView(KPageWidgetItem* parent) +{ + symbolViewPage = new KileWidgetSymbolViewConfig(this); + symbolViewPage->setObjectName("SymbolView"); + addConfigPage(parent, symbolViewPage, i18n("Symbol View"), "math0"); +} + +//////////////////// Editor //////////////////// + +void Config::setupEditor(KPageWidgetItem* parent) +{ + m_editorSettingsChanged = false; + m_editorPages.clear(); + + KTextEditor::Editor* editor = m_ki->docManager()->getEditor(); + if(!editor) { + return; + } + for(int i = 0; i < editor->configPages(); ++i) { + KTextEditor::ConfigPage *configPage = editor->configPage(i, parent->widget()); + KPageWidgetItem *pageWidgetItem = addConfigPage(parent, configPage, configPage->name(), + configPage->icon(), + configPage->fullName()); + connect(configPage, &KTextEditor::ConfigPage::changed, this, [=] { + m_editorSettingsChanged = true; + }); + m_editorPages.insert(pageWidgetItem, configPage); + } +} + +//////////////////// slots //////////////////// + +void Config::slotAcceptChanges() +{ + KILE_DEBUG_MAIN << " slot acceptChanges (" << m_manager->hasChanged() << "," << m_editorSettingsChanged << ")"; + + // editor settings are only available, when at least one document is opened + if(m_editorSettingsChanged) { + QMapIterator i(m_editorPages); + while (i.hasNext()) { + i.next(); + i.value()->apply(); + } + } + + // Kile settings + toolPage->writeConfig(); // config all tools + completePage->writeConfig(); // Complete configuration (dani) + previewPage->writeConfig(); // Quick Preview (dani) + usermenuPage->writeConfig(); + livePreviewPage->writeConfig(); + + m_config->sync(); +} } diff --git a/src/dialogs/configurationdialog.h b/src/dialogs/configurationdialog.h index 0367bcec..9224c019 100644 --- a/src/dialogs/configurationdialog.h +++ b/src/dialogs/configurationdialog.h @@ -1,130 +1,136 @@ /************************************************************************************* begin : Wed Jun 6 2001 copyright : (C) 2003 by Jeroen Wijnout (Jeroen.Wijnhout@kdemail.net) 2007-2016 by Michel Ludwig (michel.ludwig@kdemail.net) *************************************************************************************/ /*************************************************************************** * * * 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. * * * ***************************************************************************/ #ifndef CONFIGURATIONDIALOG_H #define CONFIGURATIONDIALOG_H #include #include #include "widgets/codecompletionconfigwidget.h" // code completion (dani) #include "widgets/previewconfigwidget.h" // QuickPreview (dani) #include "widgets/environmentconfigwidget.h" // environments (dani) #include "widgets/graphicsconfigwidget.h" // graphics (dani) #include "widgets/structureviewconfigwidget.h" // structure view (dani) #include "widgets/symbolviewconfigwidget.h" class KConfig; -namespace KileWidget { class ToolConfig; } +namespace KileWidget { +class ToolConfig; +} class KileWidgetAppearanceConfig; class KileWidgetHelpConfig; class KileWidgetLatexConfig; class KileWidgetLivePreviewConfig; class KileWidgetGeneralConfig; class KileWidgetEnvironmentConfig; class KileWidgetGraphicsConfig; class KileWidgetStructureViewConfig; class KileWidgetScriptingConfig; class KileWidgetUsermenuConfig; -namespace KileTool { class Manager; } +namespace KileTool { +class Manager; +} -namespace KTextEditor { class ConfigPage; } +namespace KTextEditor { +class ConfigPage; +} namespace KileDialog { - class Config : public KPageDialog - { - Q_OBJECT - - public: - Config( KConfig *config, KileInfo *ki, QWidget* parent = 0); - ~Config(); - - virtual void show(); - - //Q_SIGNALS: - // void widgetModified(); - - private Q_SLOTS: - void slotAcceptChanges(); - - private: - // dialog manager - KConfigDialogManager *m_manager; - - KConfig *m_config; - KConfigGroup m_configDialogSize; - KileInfo *m_ki; - - QList m_pageWidgetItemList; - - bool m_editorSettingsChanged; - - KileWidget::ToolConfig *toolPage; - - // CodeCompletion (dani) - CodeCompletionConfigWidget *completePage; - KileWidgetPreviewConfig *previewPage; - - KileWidgetHelpConfig *helpPage; - KileWidgetLatexConfig *latexPage; - KileWidgetGeneralConfig *generalPage; - KileWidgetEnvironmentConfig *envPage; - KileWidgetGraphicsConfig *graphicsPage; - KileWidgetStructureViewConfig *structurePage; - KileWidgetSymbolViewConfig *symbolViewPage; - KileWidgetScriptingConfig *scriptingPage; - KileWidgetUsermenuConfig *usermenuPage; - KileWidgetLivePreviewConfig *livePreviewPage; - KileWidgetAppearanceConfig *appearancePage; - - // setup configuration - KPageWidgetItem* addConfigFolder(const QString §ion,const QString &icon); - - KPageWidgetItem* addConfigPage(KPageWidgetItem* parent, QWidget *page, - const QString &itemName, const QString &pixmapName, - const QString &header = QString()); - - KPageWidgetItem* addConfigPage(KPageWidgetItem* parent, QWidget *page, - const QString &itemName, const QIcon& icon, - const QString &header = QString()); - - void setupGeneralOptions(KPageWidgetItem* parent); - void setupTools(KPageWidgetItem* parent); - void setupLatex(KPageWidgetItem* parent); - void setupCodeCompletion(KPageWidgetItem* parent); - void setupQuickPreview(KPageWidgetItem* parent); - void setupHelp(KPageWidgetItem* parent); - void setupEditor(KPageWidgetItem* parent); - void setupEnvironment(KPageWidgetItem* parent); - void setupGraphics(KPageWidgetItem* parent); - void setupStructure(KPageWidgetItem* parent); - void setupSymbolView(KPageWidgetItem* parent); - void setupScripting(KPageWidgetItem* parent); - void setupUsermenu(KPageWidgetItem* parent); - void setupLivePreview(KPageWidgetItem* parent); - void setupAppearance(KPageWidgetItem* parent); - - // write configuration - void writeGeneralOptionsConfig(); - - // editor pages - QMap m_editorPages; - }; +class Config : public KPageDialog +{ + Q_OBJECT + +public: + Config( KConfig *config, KileInfo *ki, QWidget* parent = 0); + ~Config(); + + virtual void show(); + + //Q_SIGNALS: + // void widgetModified(); + +private Q_SLOTS: + void slotAcceptChanges(); + +private: + // dialog manager + KConfigDialogManager *m_manager; + + KConfig *m_config; + KConfigGroup m_configDialogSize; + KileInfo *m_ki; + + QList m_pageWidgetItemList; + + bool m_editorSettingsChanged; + + KileWidget::ToolConfig *toolPage; + + // CodeCompletion (dani) + CodeCompletionConfigWidget *completePage; + KileWidgetPreviewConfig *previewPage; + + KileWidgetHelpConfig *helpPage; + KileWidgetLatexConfig *latexPage; + KileWidgetGeneralConfig *generalPage; + KileWidgetEnvironmentConfig *envPage; + KileWidgetGraphicsConfig *graphicsPage; + KileWidgetStructureViewConfig *structurePage; + KileWidgetSymbolViewConfig *symbolViewPage; + KileWidgetScriptingConfig *scriptingPage; + KileWidgetUsermenuConfig *usermenuPage; + KileWidgetLivePreviewConfig *livePreviewPage; + KileWidgetAppearanceConfig *appearancePage; + + // setup configuration + KPageWidgetItem* addConfigFolder(const QString §ion,const QString &icon); + + KPageWidgetItem* addConfigPage(KPageWidgetItem* parent, QWidget *page, + const QString &itemName, const QString &pixmapName, + const QString &header = QString()); + + KPageWidgetItem* addConfigPage(KPageWidgetItem* parent, QWidget *page, + const QString &itemName, const QIcon& icon, + const QString &header = QString()); + + void setupGeneralOptions(KPageWidgetItem* parent); + void setupTools(KPageWidgetItem* parent); + void setupLatex(KPageWidgetItem* parent); + void setupCodeCompletion(KPageWidgetItem* parent); + void setupQuickPreview(KPageWidgetItem* parent); + void setupHelp(KPageWidgetItem* parent); + void setupEditor(KPageWidgetItem* parent); + void setupEnvironment(KPageWidgetItem* parent); + void setupGraphics(KPageWidgetItem* parent); + void setupStructure(KPageWidgetItem* parent); + void setupSymbolView(KPageWidgetItem* parent); + void setupScripting(KPageWidgetItem* parent); + void setupUsermenu(KPageWidgetItem* parent); + void setupLivePreview(KPageWidgetItem* parent); + void setupAppearance(KPageWidgetItem* parent); + + // write configuration + void writeGeneralOptionsConfig(); + + // editor pages + QMap m_editorPages; +}; } #endif diff --git a/src/dialogs/findfilesdialog.cpp b/src/dialogs/findfilesdialog.cpp index a06016e0..eb3ff75f 100644 --- a/src/dialogs/findfilesdialog.cpp +++ b/src/dialogs/findfilesdialog.cpp @@ -1,881 +1,882 @@ /* This file is part of the kile project Copyright (C) 2001 Christoph Cullmann Copyright (C) 2001 Joseph Wenninger Copyright (C) 2001 Anders Lund Copyright (C) 2003 Jan-Marek Glogowski Copyright (C) 2005 Holger Danielsson Copyright (C) 2008-2014 Michel Ludwig 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, see . Original from kdebase / kate changes: 2005-11-27 (dani) - add a search for all files of a Kile project (done with one grep command for each file) - dialog is now based on KDialogBase - an item of the resultbox ist opened when it's highlightened (no double click is needed anymore) - dialog is deleted after work to minimize resources - added additional search modes for environments, labels etc. - fixed some bugs (f.e. two slashes at the end of directory names, jumping to the wrong line, wrong pattern lists) - add some editable template modes to search for LaTeX commands - add some predined modes to search for environments, graphics, labels, and references, either all of them or some special ones (in other words: most parts have changed to work perfectly with Kile ...) */ // 2007-03-12 dani // - use KileDocument::Extensions #include "dialogs/findfilesdialog.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "kiledebug.h" #include "kileconfig.h" #include "kileproject.h" #include "kiledocmanager.h" #include "kileextensions.h" namespace KileDialog { FindFilesDialog::FindFilesDialog(QWidget *parent, KileInfo *ki, KileGrep::Mode mode, const char *name) - : QDialog(parent) - , m_ki(ki) - , m_mode(mode) - , m_proc(Q_NULLPTR) - , m_grepJobs(0) -{ - setObjectName(name); - setWindowTitle(QString()); - setModal(false); - QVBoxLayout *mainLayout = new QVBoxLayout; - setLayout(mainLayout); - - // project groupbox - QGroupBox *projectgroup = new QGroupBox(i18n("Project"), this); - mainLayout->addWidget(projectgroup); - QGridLayout *projectgrouplayout = new QGridLayout(); - projectgrouplayout->setAlignment(Qt::AlignTop); - projectgroup->setLayout(projectgrouplayout); - - QLabel *project_label = new QLabel(i18n("Name:"), projectgroup); - int labelwidth = project_label->sizeHint().width(); - - QLabel *projectdir_label = new QLabel(i18n("Directory:"), projectgroup); - if(projectdir_label->sizeHint().width() > labelwidth) { - labelwidth = projectdir_label->sizeHint().width(); - } - - projectname_label = new QLabel(projectgroup); - projectdirname_label = new QLabel(projectgroup); - - projectgrouplayout->addWidget(project_label, 0, 0, Qt::AlignLeft | Qt::AlignVCenter); - projectgrouplayout->addWidget(projectname_label, 0, 1, Qt::AlignLeft | Qt::AlignVCenter); - projectgrouplayout->addWidget(projectdir_label, 1, 0, Qt::AlignLeft | Qt::AlignVCenter); - projectgrouplayout->addWidget(projectdirname_label, 1, 1, Qt::AlignLeft | Qt::AlignVCenter); - projectgrouplayout->setColumnStretch(1, 1); - - // search groupbox - QGroupBox *searchgroup = new QGroupBox(i18n("Search"), this); - mainLayout->addWidget(searchgroup); - QGridLayout *searchgrouplayout = new QGridLayout(); - searchgrouplayout->setAlignment(Qt::AlignTop); - searchgroup->setLayout(searchgrouplayout); - - QLabel *pattern_label = new QLabel(i18n("Pattern:"), searchgroup); - if(pattern_label->sizeHint().width() > labelwidth) { - labelwidth = pattern_label->sizeHint().width(); - } - - pattern_combo = new KComboBox(true, searchgroup); - pattern_combo->setInsertPolicy(KComboBox::NoInsert); - pattern_combo->setFocus(); - pattern_combo->setMinimumSize(pattern_combo->sizeHint()); - pattern_label->setBuddy(pattern_combo); - - QLabel *template_label = new QLabel(i18n("Template:"), searchgroup); - if(template_label->sizeHint().width() > labelwidth) { - labelwidth = template_label->sizeHint().width(); - } - - QStringList templatemode_list; - templatemode_list << i18n("Normal") - << i18n("Command") - << i18n("Command[]") - << i18n("Environment") - << i18n("Image") - << i18n("Label") - << i18n("Reference") - << i18n("File"); - - QHBoxLayout *template_layout = new QHBoxLayout(); - template_layout->setMargin(0); - template_combo = new KComboBox(false, searchgroup); - template_combo->addItems(templatemode_list); - template_combo->adjustSize(); - template_combo->setFixedSize(template_combo->size()); - template_layout->addWidget(template_combo); - m_lastTemplateIndex = 0; - - template_edit = new QLineEdit(searchgroup); - template_edit->setText("%s"); - template_edit->setMinimumSize(template_edit->sizeHint()); - template_label->setBuddy(template_edit); - template_layout->addWidget(template_edit); - - searchgrouplayout->addWidget(pattern_label, 0, 0, Qt::AlignLeft | Qt::AlignVCenter); - searchgrouplayout->addWidget(pattern_combo, 0, 1); - searchgrouplayout->addWidget(template_label, 1, 0, Qt::AlignLeft | Qt::AlignVCenter); - searchgrouplayout->addLayout(template_layout, 1, 1); - - // filter groupbox - QGroupBox *filtergroup = new QGroupBox(i18n("Directory Options"), this); - mainLayout->addWidget(filtergroup); - QGridLayout *filtergrouplayout = new QGridLayout(); - filtergrouplayout->setAlignment(Qt::AlignTop); - filtergroup->setLayout(filtergrouplayout); - - QLabel *files_label = new QLabel(i18n("Filter:"), filtergroup); - if (files_label->sizeHint().width() > labelwidth) { - labelwidth = files_label->sizeHint().width(); - } - - filter_combo = new KComboBox(true, filtergroup); - filter_combo->setMinimumSize(filter_combo->sizeHint()); - files_label->setBuddy(filter_combo->focusProxy()); - - QLabel *dir_label = new QLabel(i18n("Directory:"), filtergroup); - if (dir_label->sizeHint().width() > labelwidth) { - labelwidth = dir_label->sizeHint().width(); - } - - dir_combo = new KUrlRequester(new KComboBox(true, filtergroup), filtergroup); - dir_combo->setObjectName("dir combo"); - dir_combo->completionObject()->setMode(KUrlCompletion::DirCompletion); - dir_combo->setMode(KFile::Directory | KFile::LocalOnly | KFile::ExistingOnly); - dir_label->setBuddy(dir_combo); - - recursive_box = new QCheckBox(i18n("Scan directories recursively"), filtergroup); - recursive_box->setMinimumWidth(recursive_box->sizeHint().width()); - - filtergrouplayout->addWidget(files_label, 0, 0); - filtergrouplayout->addWidget(filter_combo, 0, 1); - filtergrouplayout->addWidget(dir_label, 1, 0); - filtergrouplayout->addWidget(dir_combo, 1, 1); - filtergrouplayout->addWidget(recursive_box, 2, 1); - filtergrouplayout->setColumnStretch(1, 1); - - // result box - resultbox = new QListWidget(this); - mainLayout->addWidget(resultbox); - resultbox->setMinimumHeight(150); - - // button box - QDialogButtonBox *actionbox = new QDialogButtonBox(this); - mainLayout->addWidget(actionbox); - search_button = new QPushButton(i18n("&Search")); - search_button->setDefault(true); - search_button->setEnabled(false); - search_button->setIcon(QIcon::fromTheme("edit-find")); - connect(search_button, &QPushButton::clicked, this, &FindFilesDialog::slotSearch); - actionbox->addButton(search_button, QDialogButtonBox::ActionRole); - clear_button = new QPushButton(i18n("&Clear")); - clear_button->setEnabled(false); - clear_button->setIcon(QIcon::fromTheme("edit-clear-locationbar")); - connect(clear_button, &QPushButton::clicked, this, &FindFilesDialog::slotClear); - actionbox->addButton(clear_button, QDialogButtonBox::ActionRole); - close_button = actionbox->addButton(QDialogButtonBox::Close); - connect(close_button, &QPushButton::clicked, this, &FindFilesDialog::slotClose); - - // adjust labels - project_label->setFixedWidth(labelwidth); - projectdir_label->setFixedWidth(labelwidth); - pattern_label->setFixedWidth(labelwidth); - template_label->setFixedWidth(labelwidth); - files_label->setFixedWidth(labelwidth); - dir_label->setFixedWidth(labelwidth); - - if (m_mode == KileGrep::Project) { - filtergroup->hide(); - mainLayout->addWidget(projectgroup); - mainLayout->addWidget(searchgroup); - } - else { - projectgroup->hide(); - mainLayout->addWidget(searchgroup); - mainLayout->addWidget(filtergroup); - } - mainLayout->addWidget(resultbox); - mainLayout->addWidget(actionbox); - - // Produces error messages like - // QListBox::property( "text" ) failed: - // property invalid or does not exist - // Anyone an idea? - KAcceleratorManager::manage(this); - - pattern_combo->setWhatsThis( - i18n("Enter the regular expression you want to search for here.
" - "Possible meta characters are:
" - "
    " - "
  •  . - Matches any character
  • " - "
  •  ^ - Matches the beginning of a line
  • " - "
  •  $ - Matches the end of a line
  • " - "
  •  \\\\\\< - Matches the beginning of a word
  • " - "
  •  \\\\\\> - Matches the end of a word
  • " - "
" - "The following repetition operators exist:" - "
    " - "
  •  ? - The preceding item is matched at most once
  • " - "
  •  * - The preceding item is matched zero or more times
  • " - "
  •  + - The preceding item is matched one or more times
  • " - "
  •  {n} - The preceding item is matched exactly n times
  • " - "
  •  {n,} - The preceding item is matched n or more times
  • " - "
  •  {,n} - The preceding item is matched at most n times
  • " - "
  •  {n,m} - The preceding item is matched at least n, " - "but at most m times.
  • " - "
" - "Furthermore, backreferences to bracketed subexpressions are " - "available via the notation \\\\n." - )); - filter_combo->setWhatsThis( - i18n("Enter the file name pattern of the files to search here. " - "You may give several patterns separated by commas.")); - template_combo->setWhatsThis( - i18n("Choose one search mode. For the first modes, the search pattern is " - "built from the editable template, where '%s' is replaced by the given pattern.

" - "There are additional fixed predefined modes for environments, graphics, labels, references " - "and input files. If the pattern is empty, Kile will search for all commands of this mode. " - "If a pattern is given, it will be inserted as a parameter. For example, in environment mode with " - "pattern 'center', Kile will search for '\\begin{center}', and in graphics mode with " - "pattern '.*\\.png', Kile will search for all png files.")); - template_edit->setWhatsThis( - i18n("For the first three modes you can choose a template for the pattern from the combo box " - "and edit it here. The string %s in the template is replaced " - "by the pattern input field, resulting in the regular expression " - "to search for. In all other modes this template is ignored.")); - dir_combo->setWhatsThis( - i18n("Enter the directory which contains the files you want to search in.")); - recursive_box->setWhatsThis( - i18n("Check this box to search in all subdirectories.")); - resultbox->setWhatsThis( - i18n("The results of the grep run are listed here. Select a " - "filename/line number combination with a mouse click on the item " - "or with the cursor to show the respective line in the editor.")); - - // read config and setup dialog for both modes - readConfig(); - if (m_mode == KileGrep::Directory) { - setWindowTitle(i18n("Find in Files")); - setupDirectory(); - } - else { - setWindowTitle(i18n("Find in Project")); - setupProject(); - } - - pattern_combo->setEditText(QString()); - template_edit->setText(m_TemplateList[0]); - slotPatternTextChanged(QString()); - - connect(pattern_combo->lineEdit(), &QLineEdit::textChanged, - this, &FindFilesDialog::slotPatternTextChanged); - connect(template_combo, static_cast(&KComboBox::activated), - this, &FindFilesDialog::slotTemplateActivated); - connect(resultbox, &QListWidget::currentTextChanged, - this, &FindFilesDialog::slotItemSelected); - - QDialogButtonBox *buttonBox = new QDialogButtonBox(); - connect(buttonBox, &QDialogButtonBox::accepted, this, &FindFilesDialog::accept); - connect(buttonBox, &QDialogButtonBox::rejected, this, &FindFilesDialog::reject); - mainLayout->addWidget(buttonBox); - - connect(this, &FindFilesDialog::finished, this, &FindFilesDialog::slotClose); - - resize(450, sizeHint().height()); - KILE_DEBUG_MAIN << "==FindFilesDialog (create dialog)============================="; + : QDialog(parent) + , m_ki(ki) + , m_mode(mode) + , m_proc(Q_NULLPTR) + , m_grepJobs(0) +{ + setObjectName(name); + setWindowTitle(QString()); + setModal(false); + QVBoxLayout *mainLayout = new QVBoxLayout; + setLayout(mainLayout); + + // project groupbox + QGroupBox *projectgroup = new QGroupBox(i18n("Project"), this); + mainLayout->addWidget(projectgroup); + QGridLayout *projectgrouplayout = new QGridLayout(); + projectgrouplayout->setAlignment(Qt::AlignTop); + projectgroup->setLayout(projectgrouplayout); + + QLabel *project_label = new QLabel(i18n("Name:"), projectgroup); + int labelwidth = project_label->sizeHint().width(); + + QLabel *projectdir_label = new QLabel(i18n("Directory:"), projectgroup); + if(projectdir_label->sizeHint().width() > labelwidth) { + labelwidth = projectdir_label->sizeHint().width(); + } + + projectname_label = new QLabel(projectgroup); + projectdirname_label = new QLabel(projectgroup); + + projectgrouplayout->addWidget(project_label, 0, 0, Qt::AlignLeft | Qt::AlignVCenter); + projectgrouplayout->addWidget(projectname_label, 0, 1, Qt::AlignLeft | Qt::AlignVCenter); + projectgrouplayout->addWidget(projectdir_label, 1, 0, Qt::AlignLeft | Qt::AlignVCenter); + projectgrouplayout->addWidget(projectdirname_label, 1, 1, Qt::AlignLeft | Qt::AlignVCenter); + projectgrouplayout->setColumnStretch(1, 1); + + // search groupbox + QGroupBox *searchgroup = new QGroupBox(i18n("Search"), this); + mainLayout->addWidget(searchgroup); + QGridLayout *searchgrouplayout = new QGridLayout(); + searchgrouplayout->setAlignment(Qt::AlignTop); + searchgroup->setLayout(searchgrouplayout); + + QLabel *pattern_label = new QLabel(i18n("Pattern:"), searchgroup); + if(pattern_label->sizeHint().width() > labelwidth) { + labelwidth = pattern_label->sizeHint().width(); + } + + pattern_combo = new KComboBox(true, searchgroup); + pattern_combo->setInsertPolicy(KComboBox::NoInsert); + pattern_combo->setFocus(); + pattern_combo->setMinimumSize(pattern_combo->sizeHint()); + pattern_label->setBuddy(pattern_combo); + + QLabel *template_label = new QLabel(i18n("Template:"), searchgroup); + if(template_label->sizeHint().width() > labelwidth) { + labelwidth = template_label->sizeHint().width(); + } + + QStringList templatemode_list; + templatemode_list << i18n("Normal") + << i18n("Command") + << i18n("Command[]") + << i18n("Environment") + << i18n("Image") + << i18n("Label") + << i18n("Reference") + << i18n("File"); + + QHBoxLayout *template_layout = new QHBoxLayout(); + template_layout->setMargin(0); + template_combo = new KComboBox(false, searchgroup); + template_combo->addItems(templatemode_list); + template_combo->adjustSize(); + template_combo->setFixedSize(template_combo->size()); + template_layout->addWidget(template_combo); + m_lastTemplateIndex = 0; + + template_edit = new QLineEdit(searchgroup); + template_edit->setText("%s"); + template_edit->setMinimumSize(template_edit->sizeHint()); + template_label->setBuddy(template_edit); + template_layout->addWidget(template_edit); + + searchgrouplayout->addWidget(pattern_label, 0, 0, Qt::AlignLeft | Qt::AlignVCenter); + searchgrouplayout->addWidget(pattern_combo, 0, 1); + searchgrouplayout->addWidget(template_label, 1, 0, Qt::AlignLeft | Qt::AlignVCenter); + searchgrouplayout->addLayout(template_layout, 1, 1); + + // filter groupbox + QGroupBox *filtergroup = new QGroupBox(i18n("Directory Options"), this); + mainLayout->addWidget(filtergroup); + QGridLayout *filtergrouplayout = new QGridLayout(); + filtergrouplayout->setAlignment(Qt::AlignTop); + filtergroup->setLayout(filtergrouplayout); + + QLabel *files_label = new QLabel(i18n("Filter:"), filtergroup); + if (files_label->sizeHint().width() > labelwidth) { + labelwidth = files_label->sizeHint().width(); + } + + filter_combo = new KComboBox(true, filtergroup); + filter_combo->setMinimumSize(filter_combo->sizeHint()); + files_label->setBuddy(filter_combo->focusProxy()); + + QLabel *dir_label = new QLabel(i18n("Directory:"), filtergroup); + if (dir_label->sizeHint().width() > labelwidth) { + labelwidth = dir_label->sizeHint().width(); + } + + dir_combo = new KUrlRequester(new KComboBox(true, filtergroup), filtergroup); + dir_combo->setObjectName("dir combo"); + dir_combo->completionObject()->setMode(KUrlCompletion::DirCompletion); + dir_combo->setMode(KFile::Directory | KFile::LocalOnly | KFile::ExistingOnly); + dir_label->setBuddy(dir_combo); + + recursive_box = new QCheckBox(i18n("Scan directories recursively"), filtergroup); + recursive_box->setMinimumWidth(recursive_box->sizeHint().width()); + + filtergrouplayout->addWidget(files_label, 0, 0); + filtergrouplayout->addWidget(filter_combo, 0, 1); + filtergrouplayout->addWidget(dir_label, 1, 0); + filtergrouplayout->addWidget(dir_combo, 1, 1); + filtergrouplayout->addWidget(recursive_box, 2, 1); + filtergrouplayout->setColumnStretch(1, 1); + + // result box + resultbox = new QListWidget(this); + mainLayout->addWidget(resultbox); + resultbox->setMinimumHeight(150); + + // button box + QDialogButtonBox *actionbox = new QDialogButtonBox(this); + mainLayout->addWidget(actionbox); + search_button = new QPushButton(i18n("&Search")); + search_button->setDefault(true); + search_button->setEnabled(false); + search_button->setIcon(QIcon::fromTheme("edit-find")); + connect(search_button, &QPushButton::clicked, this, &FindFilesDialog::slotSearch); + actionbox->addButton(search_button, QDialogButtonBox::ActionRole); + clear_button = new QPushButton(i18n("&Clear")); + clear_button->setEnabled(false); + clear_button->setIcon(QIcon::fromTheme("edit-clear-locationbar")); + connect(clear_button, &QPushButton::clicked, this, &FindFilesDialog::slotClear); + actionbox->addButton(clear_button, QDialogButtonBox::ActionRole); + close_button = actionbox->addButton(QDialogButtonBox::Close); + connect(close_button, &QPushButton::clicked, this, &FindFilesDialog::slotClose); + + // adjust labels + project_label->setFixedWidth(labelwidth); + projectdir_label->setFixedWidth(labelwidth); + pattern_label->setFixedWidth(labelwidth); + template_label->setFixedWidth(labelwidth); + files_label->setFixedWidth(labelwidth); + dir_label->setFixedWidth(labelwidth); + + if (m_mode == KileGrep::Project) { + filtergroup->hide(); + mainLayout->addWidget(projectgroup); + mainLayout->addWidget(searchgroup); + } + else { + projectgroup->hide(); + mainLayout->addWidget(searchgroup); + mainLayout->addWidget(filtergroup); + } + mainLayout->addWidget(resultbox); + mainLayout->addWidget(actionbox); + + // Produces error messages like + // QListBox::property( "text" ) failed: + // property invalid or does not exist + // Anyone an idea? + KAcceleratorManager::manage(this); + + pattern_combo->setWhatsThis( + i18n("Enter the regular expression you want to search for here.
" + "Possible meta characters are:
" + "
    " + "
  •  . - Matches any character
  • " + "
  •  ^ - Matches the beginning of a line
  • " + "
  •  $ - Matches the end of a line
  • " + "
  •  \\\\\\< - Matches the beginning of a word
  • " + "
  •  \\\\\\> - Matches the end of a word
  • " + "
" + "The following repetition operators exist:" + "
    " + "
  •  ? - The preceding item is matched at most once
  • " + "
  •  * - The preceding item is matched zero or more times
  • " + "
  •  + - The preceding item is matched one or more times
  • " + "
  •  {n} - The preceding item is matched exactly n times
  • " + "
  •  {n,} - The preceding item is matched n or more times
  • " + "
  •  {,n} - The preceding item is matched at most n times
  • " + "
  •  {n,m} - The preceding item is matched at least n, " + "but at most m times.
  • " + "
" + "Furthermore, backreferences to bracketed subexpressions are " + "available via the notation \\\\n." + )); + filter_combo->setWhatsThis( + i18n("Enter the file name pattern of the files to search here. " + "You may give several patterns separated by commas.")); + template_combo->setWhatsThis( + i18n("Choose one search mode. For the first modes, the search pattern is " + "built from the editable template, where '%s' is replaced by the given pattern.

" + "There are additional fixed predefined modes for environments, graphics, labels, references " + "and input files. If the pattern is empty, Kile will search for all commands of this mode. " + "If a pattern is given, it will be inserted as a parameter. For example, in environment mode with " + "pattern 'center', Kile will search for '\\begin{center}', and in graphics mode with " + "pattern '.*\\.png', Kile will search for all png files.")); + template_edit->setWhatsThis( + i18n("For the first three modes you can choose a template for the pattern from the combo box " + "and edit it here. The string %s in the template is replaced " + "by the pattern input field, resulting in the regular expression " + "to search for. In all other modes this template is ignored.")); + dir_combo->setWhatsThis( + i18n("Enter the directory which contains the files you want to search in.")); + recursive_box->setWhatsThis( + i18n("Check this box to search in all subdirectories.")); + resultbox->setWhatsThis( + i18n("The results of the grep run are listed here. Select a " + "filename/line number combination with a mouse click on the item " + "or with the cursor to show the respective line in the editor.")); + + // read config and setup dialog for both modes + readConfig(); + if (m_mode == KileGrep::Directory) { + setWindowTitle(i18n("Find in Files")); + setupDirectory(); + } + else { + setWindowTitle(i18n("Find in Project")); + setupProject(); + } + + pattern_combo->setEditText(QString()); + template_edit->setText(m_TemplateList[0]); + slotPatternTextChanged(QString()); + + connect(pattern_combo->lineEdit(), &QLineEdit::textChanged, + this, &FindFilesDialog::slotPatternTextChanged); + connect(template_combo, static_cast(&KComboBox::activated), + this, &FindFilesDialog::slotTemplateActivated); + connect(resultbox, &QListWidget::currentTextChanged, + this, &FindFilesDialog::slotItemSelected); + + QDialogButtonBox *buttonBox = new QDialogButtonBox(); + connect(buttonBox, &QDialogButtonBox::accepted, this, &FindFilesDialog::accept); + connect(buttonBox, &QDialogButtonBox::rejected, this, &FindFilesDialog::reject); + mainLayout->addWidget(buttonBox); + + connect(this, &FindFilesDialog::finished, this, &FindFilesDialog::slotClose); + + resize(450, sizeHint().height()); + KILE_DEBUG_MAIN << "==FindFilesDialog (create dialog)============================="; } FindFilesDialog::~FindFilesDialog() { - KILE_DEBUG_MAIN << "==FindFilesDialog (delete dialog)============================="; - writeConfig(); + KILE_DEBUG_MAIN << "==FindFilesDialog (delete dialog)============================="; + writeConfig(); } ///////////////////// config ///////////////////// void FindFilesDialog::readConfig() { - pattern_combo->addItems(readList(KileGrep::SearchItems)); + pattern_combo->addItems(readList(KileGrep::SearchItems)); - QString labels = getCommandList(KileDocument::CmdAttrLabel); - QString references = getCommandList(KileDocument::CmdAttrReference); - m_TemplateList = readList(KileGrep::SearchTemplates) ; - if(m_TemplateList.count() != 3) { - m_TemplateList.clear(); - m_TemplateList << "%s" << "\\\\%s\\{" << "\\\\%s(\\[[^]]*\\])?\\{"; - } - m_TemplateList << "\\\\begin\\{" // to be closed with "%s\\}" - << "\\\\includegraphics(\\[[^]]*\\])?\\{" - << "\\\\(label" + labels + ")\\{" - << "\\\\(ref|pageref|vref|vpageref|fref|Fref|eqref" + references + ")(\\[[^]]*\\])?\\{" - << "\\\\(input|include)\\{" - ; + QString labels = getCommandList(KileDocument::CmdAttrLabel); + QString references = getCommandList(KileDocument::CmdAttrReference); + m_TemplateList = readList(KileGrep::SearchTemplates) ; + if(m_TemplateList.count() != 3) { + m_TemplateList.clear(); + m_TemplateList << "%s" << "\\\\%s\\{" << "\\\\%s(\\[[^]]*\\])?\\{"; + } + m_TemplateList << "\\\\begin\\{" // to be closed with "%s\\}" + << "\\\\includegraphics(\\[[^]]*\\])?\\{" + << "\\\\(label" + labels + ")\\{" + << "\\\\(ref|pageref|vref|vpageref|fref|Fref|eqref" + references + ")(\\[[^]]*\\])?\\{" + << "\\\\(input|include)\\{" + ; - if (m_mode == KileGrep::Directory) { - dir_combo->comboBox()->addItems(readList(KileGrep::SearchPaths)); - recursive_box->setChecked(KileConfig::grepRecursive()); - } + if (m_mode == KileGrep::Directory) { + dir_combo->comboBox()->addItems(readList(KileGrep::SearchPaths)); + recursive_box->setChecked(KileConfig::grepRecursive()); + } } void FindFilesDialog::writeConfig() { - KileConfig::setLastSearchItems(getListItems(pattern_combo)); + KileConfig::setLastSearchItems(getListItems(pattern_combo)); - QStringList list; - list << m_TemplateList[0] << m_TemplateList[1] << m_TemplateList[2]; - KileConfig::setLastSearchTemplates(list); + QStringList list; + list << m_TemplateList[0] << m_TemplateList[1] << m_TemplateList[2]; + KileConfig::setLastSearchTemplates(list); - if(m_mode == KileGrep::Directory) { - KileConfig::setLastSearchPaths(getListItems(dir_combo->comboBox())); - KileConfig::setGrepRecursive(recursive_box->isChecked()); - } + if(m_mode == KileGrep::Directory) { + KileConfig::setLastSearchPaths(getListItems(dir_combo->comboBox())); + KileConfig::setGrepRecursive(recursive_box->isChecked()); + } } ///////////////////// setup search modes ///////////////////// void FindFilesDialog::setupDirectory() { - setDirName(QDir::home().absolutePath()); - // use a filter for 'find in files' dialog - KileDocument::Extensions *extensions = m_ki->extensions(); - QString filter = extensions->fileFilterKDEStyle(true, {KileDocument::Extensions::TEX, - KileDocument::Extensions::PACKAGES, - KileDocument::Extensions::BIB, - KileDocument::Extensions::METAPOST}); - setFilter(filter); + setDirName(QDir::home().absolutePath()); + // use a filter for 'find in files' dialog + KileDocument::Extensions *extensions = m_ki->extensions(); + QString filter = extensions->fileFilterKDEStyle(true, {KileDocument::Extensions::TEX, + KileDocument::Extensions::PACKAGES, + KileDocument::Extensions::BIB, + KileDocument::Extensions::METAPOST + }); + setFilter(filter); } void FindFilesDialog::setupProject() { - KileProject *project = m_ki->docManager()->activeProject(); - if(project) { - m_projectOpened = true; - m_projectdir = project->baseURL().toLocalFile(); - projectname_label->setText(project->name()); - projectdirname_label->setText(m_projectdir); + KileProject *project = m_ki->docManager()->activeProject(); + if(project) { + m_projectOpened = true; + m_projectdir = project->baseURL().toLocalFile(); + projectname_label->setText(project->name()); + projectdirname_label->setText(m_projectdir); - m_projectfiles.clear(); - m_projectfiles = m_ki->docManager()->getProjectFiles(); - } - else { - m_projectOpened = false; - projectname_label->setText(i18n("no project opened")); - projectdirname_label->setText(QString()); - } + m_projectfiles.clear(); + m_projectfiles = m_ki->docManager()->getProjectFiles(); + } + else { + m_projectOpened = false; + projectname_label->setText(i18n("no project opened")); + projectdirname_label->setText(QString()); + } } ///////////////////// read entries ///////////////////// QStringList FindFilesDialog::readList(KileGrep::List listtype) { - QStringList strings, result; - - bool stripSlash = false; - switch (listtype) { - case KileGrep::SearchItems: - strings = KileConfig::lastSearchItems(); - break; - case KileGrep::SearchPaths: - strings = KileConfig::lastSearchPaths(); - stripSlash = true; - break; - case KileGrep::SearchTemplates: - strings = KileConfig::lastSearchTemplates(); - break; - } - - while (strings.count() > 0) { - if(stripSlash && strings[0].right(1) == "/") { - strings[0].truncate(strings[0].length() - 1); - } - if(!strings[0].isEmpty()) { - result.append(strings[0]); - } - strings.removeAll(strings[0]); - } - return result; + QStringList strings, result; + + bool stripSlash = false; + switch (listtype) { + case KileGrep::SearchItems: + strings = KileConfig::lastSearchItems(); + break; + case KileGrep::SearchPaths: + strings = KileConfig::lastSearchPaths(); + stripSlash = true; + break; + case KileGrep::SearchTemplates: + strings = KileConfig::lastSearchTemplates(); + break; + } + + while (strings.count() > 0) { + if(stripSlash && strings[0].right(1) == "/") { + strings[0].truncate(strings[0].length() - 1); + } + if(!strings[0].isEmpty()) { + result.append(strings[0]); + } + strings.removeAll(strings[0]); + } + return result; } ///////////////////// item selected ///////////////////// void FindFilesDialog::slotItemSelected(const QString& item) { - KILE_DEBUG_MAIN << "\tgrep: start item selected"; - int pos; - QString filename, linenumber; - - QString str = item; - if((pos = str.indexOf(':')) != -1) { - filename = str.left(pos); - str = str.right(str.length() - 1 - pos); - if((pos = str.indexOf(':')) != -1) { - linenumber = str.left(pos); - QFileInfo fileInfo(filename); - if(fileInfo.isAbsolute()) { - emit itemSelected(filename, linenumber.toInt()); - } - else if(m_mode == KileGrep::Project) { - emit itemSelected(m_projectdir + QDir::separator() + filename, linenumber.toInt()); - } - else { - emit itemSelected(dir_combo->comboBox()->itemText(0) + QDir::separator() + filename, linenumber.toInt()); - } - } - } + KILE_DEBUG_MAIN << "\tgrep: start item selected"; + int pos; + QString filename, linenumber; + + QString str = item; + if((pos = str.indexOf(':')) != -1) { + filename = str.left(pos); + str = str.right(str.length() - 1 - pos); + if((pos = str.indexOf(':')) != -1) { + linenumber = str.left(pos); + QFileInfo fileInfo(filename); + if(fileInfo.isAbsolute()) { + emit itemSelected(filename, linenumber.toInt()); + } + else if(m_mode == KileGrep::Project) { + emit itemSelected(m_projectdir + QDir::separator() + filename, linenumber.toInt()); + } + else { + emit itemSelected(dir_combo->comboBox()->itemText(0) + QDir::separator() + filename, linenumber.toInt()); + } + } + } } ///////////////////// grep ///////////////////// void FindFilesDialog::startGrep() { - m_proc = new KProcess(this); - m_proc->setOutputChannelMode(KProcess::SeparateChannels); + m_proc = new KProcess(this); + m_proc->setOutputChannelMode(KProcess::SeparateChannels); - m_buf.clear(); - m_errbuf.clear(); - QString command; - if (m_mode == KileGrep::Project) { - command = buildProjectCommand() + ' ' + KShell::quoteArg(m_projectfiles[m_grepJobs-1]); - } - else { - command = buildFilesCommand(); - } - KILE_DEBUG_MAIN << "\tgrep (project): " << command; - (*m_proc) << KShell::splitArgs(command); + m_buf.clear(); + m_errbuf.clear(); + QString command; + if (m_mode == KileGrep::Project) { + command = buildProjectCommand() + ' ' + KShell::quoteArg(m_projectfiles[m_grepJobs-1]); + } + else { + command = buildFilesCommand(); + } + KILE_DEBUG_MAIN << "\tgrep (project): " << command; + (*m_proc) << KShell::splitArgs(command); - m_grepJobs--; + m_grepJobs--; - connect(m_proc, static_cast(&KProcess::finished), - this, &FindFilesDialog::processExited); - connect(m_proc, &KProcess::readyReadStandardOutput, - this, &FindFilesDialog::processStandardOutputReady); - connect(m_proc, &KProcess::readyReadStandardError, - this, &FindFilesDialog::processErrorOutputReady); + connect(m_proc, static_cast(&KProcess::finished), + this, &FindFilesDialog::processExited); + connect(m_proc, &KProcess::readyReadStandardOutput, + this, &FindFilesDialog::processStandardOutputReady); + connect(m_proc, &KProcess::readyReadStandardError, + this, &FindFilesDialog::processErrorOutputReady); - m_proc->start(); + m_proc->start(); } void FindFilesDialog::processOutput(bool forceAll) { - // NOTE: it isn't possible to use 'kapp->processEvents()' in this method as - // this will trigger the 'readAllStandardOutput()' signal, and call this - // method again. - int pos; - int n = 0; - while((pos = m_buf.indexOf('\n')) != -1) { - QString item = m_buf.left(pos); - if(!item.isEmpty()) { - if(m_mode == KileGrep::Project) { - if (item.indexOf(m_projectdir) == 0) { - new QListWidgetItem(item.mid(m_projectdir.length()), resultbox); - } - else { - new QListWidgetItem(item, resultbox); - } - } - else { - new QListWidgetItem(item.mid(dir_combo->url().toLocalFile().length() + 1), resultbox); - } - } - m_buf = m_buf.right(m_buf.length() - pos - 1); - if(!forceAll) { - ++n; - if(n == 100) { - break; - } - } - } + // NOTE: it isn't possible to use 'kapp->processEvents()' in this method as + // this will trigger the 'readAllStandardOutput()' signal, and call this + // method again. + int pos; + int n = 0; + while((pos = m_buf.indexOf('\n')) != -1) { + QString item = m_buf.left(pos); + if(!item.isEmpty()) { + if(m_mode == KileGrep::Project) { + if (item.indexOf(m_projectdir) == 0) { + new QListWidgetItem(item.mid(m_projectdir.length()), resultbox); + } + else { + new QListWidgetItem(item, resultbox); + } + } + else { + new QListWidgetItem(item.mid(dir_combo->url().toLocalFile().length() + 1), resultbox); + } + } + m_buf = m_buf.right(m_buf.length() - pos - 1); + if(!forceAll) { + ++n; + if(n == 100) { + break; + } + } + } } void FindFilesDialog::processStandardOutputReady() { - QByteArray outputBuffer = m_proc->readAllStandardOutput(); - m_buf += QString::fromLocal8Bit(outputBuffer.data(), outputBuffer.size()); - processOutput(); + QByteArray outputBuffer = m_proc->readAllStandardOutput(); + m_buf += QString::fromLocal8Bit(outputBuffer.data(), outputBuffer.size()); + processOutput(); } void FindFilesDialog::processErrorOutputReady() { - QByteArray outputBuffer = m_proc->readAllStandardError(); - m_errbuf += QString::fromLocal8Bit(outputBuffer.data(), outputBuffer.size()); + QByteArray outputBuffer = m_proc->readAllStandardError(); + m_errbuf += QString::fromLocal8Bit(outputBuffer.data(), outputBuffer.size()); } void FindFilesDialog::processExited(int /*exitCode*/, QProcess::ExitStatus /*exitStatus*/) { - if(!m_errbuf.isEmpty()) { - KMessageBox::information(parentWidget(), i18n("Error:

") + m_errbuf, i18n("Grep Tool Error")); - m_errbuf.clear(); - } - else { - finish(); - } + if(!m_errbuf.isEmpty()) { + KMessageBox::information(parentWidget(), i18n("Error:

") + m_errbuf, i18n("Grep Tool Error")); + m_errbuf.clear(); + } + else { + finish(); + } } void FindFilesDialog::finish() { - if(m_proc) { - m_proc->kill(); - m_proc->disconnect(); - m_proc->deleteLater(); - m_proc = Q_NULLPTR; - } - m_buf += '\n'; - // we process all the remaining output - processOutput(true); - - if (shouldRestart()) { - startGrep(); - } - else { - updateLists(); - - resultbox->unsetCursor(); - clear_button->setEnabled(resultbox->count() > 0); - search_button->setText(i18n("&Search")); - slotPatternTextChanged(pattern_combo->lineEdit()->text()); - } + if(m_proc) { + m_proc->kill(); + m_proc->disconnect(); + m_proc->deleteLater(); + m_proc = Q_NULLPTR; + } + m_buf += '\n'; + // we process all the remaining output + processOutput(true); + + if (shouldRestart()) { + startGrep(); + } + else { + updateLists(); + + resultbox->unsetCursor(); + clear_button->setEnabled(resultbox->count() > 0); + search_button->setText(i18n("&Search")); + slotPatternTextChanged(pattern_combo->lineEdit()->text()); + } } void FindFilesDialog::updateLists() { - updateListItems(pattern_combo); - if(m_mode == KileGrep::Directory) { - updateListItems(dir_combo->comboBox()); - } + updateListItems(pattern_combo); + if(m_mode == KileGrep::Directory) { + updateListItems(dir_combo->comboBox()); + } } ///////////////////// build commands ///////////////////// QString FindFilesDialog::getPattern() { - QString pattern; - int template_mode = template_combo->currentIndex(); - if (template_mode < KileGrep::tmEnv) { - pattern = template_edit->text(); - if (pattern.isEmpty()) { - pattern = pattern_combo->currentText(); - } - else { - pattern.replace("%s", pattern_combo->currentText()); - } - } - else { - pattern = m_TemplateList[template_mode]; - if (!pattern_combo->currentText().isEmpty()) { - pattern += pattern_combo->currentText() + "\\}"; - } - } - - return pattern; + QString pattern; + int template_mode = template_combo->currentIndex(); + if (template_mode < KileGrep::tmEnv) { + pattern = template_edit->text(); + if (pattern.isEmpty()) { + pattern = pattern_combo->currentText(); + } + else { + pattern.replace("%s", pattern_combo->currentText()); + } + } + else { + pattern = m_TemplateList[template_mode]; + if (!pattern_combo->currentText().isEmpty()) { + pattern += pattern_combo->currentText() + "\\}"; + } + } + + return pattern; } QString FindFilesDialog::getShellPattern() { - QString pattern = getPattern(); - pattern.replace('\'', "'\\''"); - return KShell::quoteArg(pattern); + QString pattern = getPattern(); + pattern.replace('\'', "'\\''"); + return KShell::quoteArg(pattern); } QString FindFilesDialog::buildFilesCommand() { - QString files, files_temp; - - if(filter_combo->currentIndex() >= 0) { - files_temp = m_filterList[filter_combo->currentIndex()]; - } - else { - files_temp = filter_combo->currentText(); - } - - QStringList tokens = files_temp.split(' ', QString::SkipEmptyParts); - QStringList::Iterator it = tokens.begin(); - if (it != tokens.end()) { - files = " '" + (*it) + '\''; - ++it; - } - - for(; it != tokens.end(); ++it) { - files = files + " -o -name " + '\'' + (*it) + '\''; - } - - QString shell_command; - shell_command += "find "; - shell_command += KShell::quoteArg(dir_combo->url().path()); - shell_command += " \\( -name "; - shell_command += files; - shell_command += " \\)"; - if (!recursive_box->isChecked()) { - shell_command += " -maxdepth 1"; - } - shell_command += " -exec grep -n -E -I -H -e " + getShellPattern() + " {} \\;"; -KILE_DEBUG_MAIN << "shell command" << shell_command; - return shell_command; + QString files, files_temp; + + if(filter_combo->currentIndex() >= 0) { + files_temp = m_filterList[filter_combo->currentIndex()]; + } + else { + files_temp = filter_combo->currentText(); + } + + QStringList tokens = files_temp.split(' ', QString::SkipEmptyParts); + QStringList::Iterator it = tokens.begin(); + if (it != tokens.end()) { + files = " '" + (*it) + '\''; + ++it; + } + + for(; it != tokens.end(); ++it) { + files = files + " -o -name " + '\'' + (*it) + '\''; + } + + QString shell_command; + shell_command += "find "; + shell_command += KShell::quoteArg(dir_combo->url().path()); + shell_command += " \\( -name "; + shell_command += files; + shell_command += " \\)"; + if (!recursive_box->isChecked()) { + shell_command += " -maxdepth 1"; + } + shell_command += " -exec grep -n -E -I -H -e " + getShellPattern() + " {} \\;"; + KILE_DEBUG_MAIN << "shell command" << shell_command; + return shell_command; } QString FindFilesDialog::buildProjectCommand() { - return "grep -n -E -I -H -e " + getShellPattern(); + return "grep -n -E -I -H -e " + getShellPattern(); } ///////////////////// Search ///////////////////// void FindFilesDialog::slotSearch() { - KILE_DEBUG_MAIN << "\tgrep: start slot search" << m_proc; + KILE_DEBUG_MAIN << "\tgrep: start slot search" << m_proc; - if (m_proc) { - clearGrepJobs(); - finish(); - return; - } + if (m_proc) { + clearGrepJobs(); + finish(); + return; + } - if (template_combo->currentIndex() < KileGrep::tmEnv && pattern_combo->currentText().isEmpty()) { - return; - } + if (template_combo->currentIndex() < KileGrep::tmEnv && pattern_combo->currentText().isEmpty()) { + return; + } - KILE_DEBUG_MAIN << "\tgrep: start new search"; - QRegExp re(getPattern()); - if(!re.isValid()) { - KMessageBox::error(m_ki->mainWindow(), i18n("Invalid regular expression: %1", re.errorString()), i18n("Grep Tool Error")); - return; - } + KILE_DEBUG_MAIN << "\tgrep: start new search"; + QRegExp re(getPattern()); + if(!re.isValid()) { + KMessageBox::error(m_ki->mainWindow(), i18n("Invalid regular expression: %1", re.errorString()), i18n("Grep Tool Error")); + return; + } - resultbox->setCursor(QCursor(Qt::WaitCursor)); - search_button->setText(i18n("&Cancel")); - if (template_combo->currentIndex() < KileGrep::tmEnv) { - m_TemplateList[m_lastTemplateIndex] = template_edit->text(); - } + resultbox->setCursor(QCursor(Qt::WaitCursor)); + search_button->setText(i18n("&Cancel")); + if (template_combo->currentIndex() < KileGrep::tmEnv) { + m_TemplateList[m_lastTemplateIndex] = template_edit->text(); + } - // start grep command - m_grepJobs = (m_mode == KileGrep::Project) ? m_projectfiles.count() : 1; - startGrep(); + // start grep command + m_grepJobs = (m_mode == KileGrep::Project) ? m_projectfiles.count() : 1; + startGrep(); } void FindFilesDialog::slotSearchFor(const QString &pattern) { - slotClear(); - pattern_combo->setEditText(pattern); - slotSearch(); + slotClear(); + pattern_combo->setEditText(pattern); + slotSearch(); } void FindFilesDialog::slotClear() { - KILE_DEBUG_MAIN << "\tgrep: slot clear"; - clearGrepJobs(); - finish(); - resultbox->clear(); + KILE_DEBUG_MAIN << "\tgrep: slot clear"; + clearGrepJobs(); + finish(); + resultbox->clear(); } void FindFilesDialog::slotClose() { - KILE_DEBUG_MAIN << "\tgrep: slot close"; - clearGrepJobs(); - finish(); - hide(); - deleteLater(); + KILE_DEBUG_MAIN << "\tgrep: slot close"; + clearGrepJobs(); + finish(); + hide(); + deleteLater(); } ///////////////////// templates ///////////////////// void FindFilesDialog::slotPatternTextChanged(const QString &) { - updateWidgets(); + updateWidgets(); } void FindFilesDialog::slotTemplateActivated(int index) { - if (index < KileGrep::tmEnv) { - m_TemplateList[m_lastTemplateIndex] = template_edit->text(); - template_edit->setText(m_TemplateList[index]); - } - else { - template_edit->setText(QString()); - } - m_lastTemplateIndex = index; + if (index < KileGrep::tmEnv) { + m_TemplateList[m_lastTemplateIndex] = template_edit->text(); + template_edit->setText(m_TemplateList[index]); + } + else { + template_edit->setText(QString()); + } + m_lastTemplateIndex = index; - updateWidgets(); + updateWidgets(); } void FindFilesDialog::updateWidgets() { - bool search_state = (m_mode == KileGrep::Directory) || (m_mode == KileGrep::Project && m_projectOpened); + bool search_state = (m_mode == KileGrep::Directory) || (m_mode == KileGrep::Project && m_projectOpened); - if (template_combo->currentIndex() < KileGrep::tmEnv) { - template_edit->setEnabled(true); - search_button->setEnabled(search_state && !pattern_combo->currentText().isEmpty()); - } - else { - template_edit->setEnabled(false); - search_button->setEnabled(search_state); - } + if (template_combo->currentIndex() < KileGrep::tmEnv) { + template_edit->setEnabled(true); + search_button->setEnabled(search_state && !pattern_combo->currentText().isEmpty()); + } + else { + template_edit->setEnabled(false); + search_button->setEnabled(search_state); + } } ///////////////////// directory ///////////////////// void FindFilesDialog::setDirName(const QString &dir) { - KComboBox *combo = dir_combo->comboBox(); + KComboBox *combo = dir_combo->comboBox(); - if (findListItem(combo, dir) < 0) { - combo->addItem(dir); - } - if (combo->itemText(0) != dir) { - slotClear(); - } + if (findListItem(combo, dir) < 0) { + combo->addItem(dir); + } + if (combo->itemText(0) != dir) { + slotClear(); + } } ///////////////////// filter ///////////////////// void FindFilesDialog::setFilter(const QString &filter) { - m_filterList.clear(); - filter_combo->clear(); - if (!filter.isEmpty()) { - QStringList filter_lst = filter.split('\n'); - for (QStringList::Iterator it = filter_lst.begin(); it != filter_lst.end(); ++it) { - QStringList filter_split = (*it).split('|'); - m_filterList.append(filter_split[0]); - filter_combo->addItem(filter_split[1]); - } - } + m_filterList.clear(); + filter_combo->clear(); + if (!filter.isEmpty()) { + QStringList filter_lst = filter.split('\n'); + for (QStringList::Iterator it = filter_lst.begin(); it != filter_lst.end(); ++it) { + QStringList filter_split = (*it).split('|'); + m_filterList.append(filter_split[0]); + filter_combo->addItem(filter_split[1]); + } + } } void FindFilesDialog::appendFilter(const QString &name, const QString &filter) { - filter_combo->addItem(name); - m_filterList.append(filter); + filter_combo->addItem(name); + m_filterList.append(filter); } ///////////////////// template ///////////////////// void FindFilesDialog::appendTemplate(const QString &name, const QString ®exp) { - template_combo->addItem(name); - m_TemplateList.append(regexp); + template_combo->addItem(name); + m_TemplateList.append(regexp); } void FindFilesDialog::clearTemplates() { - template_combo->clear(); - m_TemplateList.clear(); + template_combo->clear(); + m_TemplateList.clear(); } ///////////////////// KComboBox ///////////////////// QStringList FindFilesDialog::getListItems(KComboBox *combo) { - QStringList list; - for (int i = 0; i < combo->count() && i < KILEGREP_MAX; ++i) { - list.append(combo->itemText(i)); - } - return list; + QStringList list; + for (int i = 0; i < combo->count() && i < KILEGREP_MAX; ++i) { + list.append(combo->itemText(i)); + } + return list; } int FindFilesDialog::findListItem(KComboBox *combo, const QString &s) { - for (int i = 0; i < combo->count(); ++i) { - if (combo->itemText(i) == s) { - return i; - } - } - return -1; + for (int i = 0; i < combo->count(); ++i) { + if (combo->itemText(i) == s) { + return i; + } + } + return -1; } void FindFilesDialog::updateListItems(KComboBox *combo) { - QString s = combo->currentText(); - if (s.isEmpty()) { - return; - } - - int index = findListItem(combo, s); - if (index > 0) { // combo already contains s - combo->removeItem(index); // remove this item - } - else { - if (index == -1) { // combo doesn't contain s - if (combo->count() >= KILEGREP_MAX) { - combo->removeItem(combo->count() - 1); // remove last item - } - } - } - - if(index != 0) { - combo->insertItem(0, s); // insert this item as first item - combo->setCurrentIndex(0); // and select it - } + QString s = combo->currentText(); + if (s.isEmpty()) { + return; + } + + int index = findListItem(combo, s); + if (index > 0) { // combo already contains s + combo->removeItem(index); // remove this item + } + else { + if (index == -1) { // combo doesn't contain s + if (combo->count() >= KILEGREP_MAX) { + combo->removeItem(combo->count() - 1); // remove last item + } + } + } + + if(index != 0) { + combo->insertItem(0, s); // insert this item as first item + combo->setCurrentIndex(0); // and select it + } } ///////////////////// template ///////////////////// QString FindFilesDialog::getCommandList(KileDocument::CmdAttribute attrtype) { - QStringList cmdlist; - QStringList::ConstIterator it; + QStringList cmdlist; + QStringList::ConstIterator it; - // get info about user-defined references - KileDocument::LatexCommands *cmd = m_ki->latexCommands(); - cmd->commandList(cmdlist, attrtype, true); + // get info about user-defined references + KileDocument::LatexCommands *cmd = m_ki->latexCommands(); + cmd->commandList(cmdlist, attrtype, true); - // build list of references - QString commands; - for (it = cmdlist.constBegin(); it != cmdlist.constEnd(); ++it) { - commands += '|' + (*it).mid(1); - } - return commands; + // build list of references + QString commands; + for (it = cmdlist.constBegin(); it != cmdlist.constEnd(); ++it) { + commands += '|' + (*it).mid(1); + } + return commands; } } diff --git a/src/dialogs/findfilesdialog.h b/src/dialogs/findfilesdialog.h index a1032f9a..e67797a6 100644 --- a/src/dialogs/findfilesdialog.h +++ b/src/dialogs/findfilesdialog.h @@ -1,143 +1,143 @@ /* This file is part of the kile project Copyright (C) 2001 Christoph Cullmann Copyright (C) 2001 Joseph Wenninger Copyright (C) 2001 Anders Lund Copyright (C) 2003 Jan-Marek Glogowski Copyright (C) 2008-2010 Michel Ludwig 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, see . Original from kdebase / kate */ #ifndef FINDFILESDIALOG_H #define FINDFILESDIALOG_H #include #include #include "kileinfo.h" #include "latexcmd.h" class QCheckBox; class QEvent; class QLabel; class QLineEdit; class QListWidget; class QPushButton; class KProcess; class KComboBox; class KUrlRequester; #define KILEGREP_MAX 12 namespace KileGrep { enum Mode { Project = 0, Directory }; enum List { SearchItems = 0, SearchPaths, SearchTemplates }; enum TemplateMode { tmNormal = 0, tmCommand, tmCommandWithOption, tmEnv, tmGraphics, tmLabel, tmRefs, tmFiles }; } namespace KileDialog { class FindFilesDialog : public QDialog { - Q_OBJECT - - public: - FindFilesDialog(QWidget *parent, KileInfo *ki, KileGrep::Mode mode, const char *name = 0); - ~FindFilesDialog(); - - void appendFilter(const QString &name, const QString &filter); - - void appendTemplate(const QString &name, const QString ®exp); - void clearTemplates(); - - public Q_SLOTS: - void slotSearchFor(const QString &pattern); - - Q_SIGNALS: - void itemSelected(const QString &abs_filename, int line); - - private: - KileInfo *m_ki; - KileGrep::Mode m_mode; - KProcess *m_proc; - int m_grepJobs; - - void readConfig(); - void writeConfig(); - - QStringList getListItems(KComboBox *combo); - int findListItem(KComboBox *combo, const QString &s); - void updateListItems(KComboBox *combo); - - void processOutput(bool forceAll = false); - void finish(); - - void startGrep(); - bool shouldRestart() { - return (m_grepJobs > 0); - } - void clearGrepJobs() { - m_grepJobs = 0; - } - QString buildFilesCommand(); - QString buildProjectCommand(); - QString getPattern(); - QString getShellPattern(); - QString getCommandList(KileDocument::CmdAttribute attrtype); - - void setupDirectory(); - void setupProject(); - void setDirName(const QString &dir); - void setFilter(const QString &filter); - QStringList readList(KileGrep::List listtype); - void updateLists(); - void updateWidgets(); - - QStringList m_projectfiles; - QString m_projectdir; - bool m_projectOpened; - - QLabel *projectname_label, *projectdirname_label; - QLineEdit *template_edit; - KComboBox *filter_combo, *pattern_combo, *template_combo; - KUrlRequester *dir_combo; - QCheckBox *recursive_box; - QListWidget *resultbox; - QPushButton *search_button, *clear_button, *close_button; - QString m_buf; - QString m_errbuf; - QStringList m_filterList; - QStringList m_TemplateList; - int m_lastTemplateIndex; - - private Q_SLOTS: - void processExited(int exitCode, QProcess::ExitStatus exitStatus); - void processStandardOutputReady(); - void processErrorOutputReady(); - void slotItemSelected(const QString&); - void slotSearch(); - void slotClear(); - void slotClose(); - void slotPatternTextChanged(const QString &); - void slotTemplateActivated(int index); + Q_OBJECT + +public: + FindFilesDialog(QWidget *parent, KileInfo *ki, KileGrep::Mode mode, const char *name = 0); + ~FindFilesDialog(); + + void appendFilter(const QString &name, const QString &filter); + + void appendTemplate(const QString &name, const QString ®exp); + void clearTemplates(); + +public Q_SLOTS: + void slotSearchFor(const QString &pattern); + +Q_SIGNALS: + void itemSelected(const QString &abs_filename, int line); + +private: + KileInfo *m_ki; + KileGrep::Mode m_mode; + KProcess *m_proc; + int m_grepJobs; + + void readConfig(); + void writeConfig(); + + QStringList getListItems(KComboBox *combo); + int findListItem(KComboBox *combo, const QString &s); + void updateListItems(KComboBox *combo); + + void processOutput(bool forceAll = false); + void finish(); + + void startGrep(); + bool shouldRestart() { + return (m_grepJobs > 0); + } + void clearGrepJobs() { + m_grepJobs = 0; + } + QString buildFilesCommand(); + QString buildProjectCommand(); + QString getPattern(); + QString getShellPattern(); + QString getCommandList(KileDocument::CmdAttribute attrtype); + + void setupDirectory(); + void setupProject(); + void setDirName(const QString &dir); + void setFilter(const QString &filter); + QStringList readList(KileGrep::List listtype); + void updateLists(); + void updateWidgets(); + + QStringList m_projectfiles; + QString m_projectdir; + bool m_projectOpened; + + QLabel *projectname_label, *projectdirname_label; + QLineEdit *template_edit; + KComboBox *filter_combo, *pattern_combo, *template_combo; + KUrlRequester *dir_combo; + QCheckBox *recursive_box; + QListWidget *resultbox; + QPushButton *search_button, *clear_button, *close_button; + QString m_buf; + QString m_errbuf; + QStringList m_filterList; + QStringList m_TemplateList; + int m_lastTemplateIndex; + +private Q_SLOTS: + void processExited(int exitCode, QProcess::ExitStatus exitStatus); + void processStandardOutputReady(); + void processErrorOutputReady(); + void slotItemSelected(const QString&); + void slotSearch(); + void slotClear(); + void slotClose(); + void slotPatternTextChanged(const QString &); + void slotTemplateActivated(int index); }; } #endif diff --git a/src/dialogs/floatdialog.cpp b/src/dialogs/floatdialog.cpp index 6f4a5bbf..95e0c3ee 100644 --- a/src/dialogs/floatdialog.cpp +++ b/src/dialogs/floatdialog.cpp @@ -1,120 +1,120 @@ /*************************************************************************** date : Dec 06 2005 version : 0.12 copyright : (C) 2005 by Holger Danielsson email : holger.danielsson@t-online.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. * * * ***************************************************************************/ #include "dialogs/floatdialog.h" #include "kiledebug.h" #include "editorextension.h" #include #include #include #include namespace KileDialog { FloatEnvironmentDialog::FloatEnvironmentDialog(KConfig *config, KileInfo *ki, - QWidget *parent) - : Wizard(config, parent), m_ki(ki) + QWidget *parent) + : Wizard(config, parent), m_ki(ki) { - QWidget *page = new QWidget(this); - QVBoxLayout *mainLayout = new QVBoxLayout; - setLayout(mainLayout); - mainLayout->addWidget(page); + QWidget *page = new QWidget(this); + QVBoxLayout *mainLayout = new QVBoxLayout; + setLayout(mainLayout); + mainLayout->addWidget(page); - m_FloatDialog.setupUi(page); + m_FloatDialog.setupUi(page); - m_prefix = "fig:"; - m_FloatDialog.m_edLabel->setText(m_prefix); + m_prefix = "fig:"; + m_FloatDialog.m_edLabel->setText(m_prefix); - slotEnvironmentClicked(); - setFocusProxy(m_FloatDialog.m_edCaption); + slotEnvironmentClicked(); + setFocusProxy(m_FloatDialog.m_edCaption); - mainLayout->addWidget(buttonBox()); - connect(buttonBox(), &QDialogButtonBox::accepted, this, &QDialog::accept); - connect(buttonBox(), &QDialogButtonBox::rejected, this, &QDialog::reject); - connect(m_FloatDialog.m_rbFigure, &QRadioButton::clicked, this, &FloatEnvironmentDialog::slotEnvironmentClicked); - connect(m_FloatDialog.m_rbTable, &QRadioButton::clicked, this, &FloatEnvironmentDialog::slotEnvironmentClicked); - connect(this, &QDialog::accepted, this, &FloatEnvironmentDialog::slotAccepted); + mainLayout->addWidget(buttonBox()); + connect(buttonBox(), &QDialogButtonBox::accepted, this, &QDialog::accept); + connect(buttonBox(), &QDialogButtonBox::rejected, this, &QDialog::reject); + connect(m_FloatDialog.m_rbFigure, &QRadioButton::clicked, this, &FloatEnvironmentDialog::slotEnvironmentClicked); + connect(m_FloatDialog.m_rbTable, &QRadioButton::clicked, this, &FloatEnvironmentDialog::slotEnvironmentClicked); + connect(this, &QDialog::accepted, this, &FloatEnvironmentDialog::slotAccepted); } ////////////////////////////// determine the whole tag ////////////////////////////// void FloatEnvironmentDialog::slotAccepted() { - QString envname = (m_FloatDialog.m_rbFigure->isChecked()) ? "figure" : "table"; - QString indent = m_ki->editorExtension()->autoIndentEnvironment(); - - QString position; - if (m_FloatDialog.m_cbHere->isChecked()) - position += 'h'; - if (m_FloatDialog.m_cbTop->isChecked()) - position += 't'; - if (m_FloatDialog.m_cbBottom->isChecked()) - position += 'b'; - if (m_FloatDialog.m_cbPage->isChecked()) - position += 'p'; - - m_td.tagBegin = "\\begin{" + envname + '}'; - if (!position.isEmpty()) { - m_td.tagBegin += '[' + position + ']'; - } - m_td.tagBegin += '\n'; - - int row = 1; - if (m_FloatDialog.m_cbCenter->isChecked()) { - m_td.tagBegin += indent + "\\centering\n"; - row = 2; - } - - m_td.tagEnd = indent + '\n'; - - QString caption = m_FloatDialog.m_edCaption->text(); - if (! caption.isEmpty()) - m_td.tagEnd += indent + "\\caption{" + caption + "}\n"; - - QString label = m_FloatDialog.m_edLabel->text(); - if (!label.isEmpty() && label != m_prefix) - m_td.tagEnd += indent + "\\label{" + label + "}\n"; - - m_td.tagEnd += "\\end{" + envname + "}\n"; - - m_td.dy = row; - m_td.dx = indent.length(); + QString envname = (m_FloatDialog.m_rbFigure->isChecked()) ? "figure" : "table"; + QString indent = m_ki->editorExtension()->autoIndentEnvironment(); + + QString position; + if (m_FloatDialog.m_cbHere->isChecked()) + position += 'h'; + if (m_FloatDialog.m_cbTop->isChecked()) + position += 't'; + if (m_FloatDialog.m_cbBottom->isChecked()) + position += 'b'; + if (m_FloatDialog.m_cbPage->isChecked()) + position += 'p'; + + m_td.tagBegin = "\\begin{" + envname + '}'; + if (!position.isEmpty()) { + m_td.tagBegin += '[' + position + ']'; + } + m_td.tagBegin += '\n'; + + int row = 1; + if (m_FloatDialog.m_cbCenter->isChecked()) { + m_td.tagBegin += indent + "\\centering\n"; + row = 2; + } + + m_td.tagEnd = indent + '\n'; + + QString caption = m_FloatDialog.m_edCaption->text(); + if (! caption.isEmpty()) + m_td.tagEnd += indent + "\\caption{" + caption + "}\n"; + + QString label = m_FloatDialog.m_edLabel->text(); + if (!label.isEmpty() && label != m_prefix) + m_td.tagEnd += indent + "\\label{" + label + "}\n"; + + m_td.tagEnd += "\\end{" + envname + "}\n"; + + m_td.dy = row; + m_td.dx = indent.length(); } void FloatEnvironmentDialog::slotEnvironmentClicked() { - KILE_DEBUG_MAIN << "entering"; - QString caption, oldprefix; - - if (m_FloatDialog.m_rbFigure->isChecked()) { - caption = i18n("Figure Environment"); - oldprefix = "^tab:"; - m_prefix = "fig:"; - } else { - caption = i18n("Table Environment"); - oldprefix = "^fig:"; - m_prefix = "tab:"; - } - - setWindowTitle(caption); - QString s = m_FloatDialog.m_edLabel->text(); - s.replace(QRegExp(oldprefix), m_prefix); - m_FloatDialog.m_edLabel->setText(s); + KILE_DEBUG_MAIN << "entering"; + QString caption, oldprefix; + + if (m_FloatDialog.m_rbFigure->isChecked()) { + caption = i18n("Figure Environment"); + oldprefix = "^tab:"; + m_prefix = "fig:"; + } else { + caption = i18n("Table Environment"); + oldprefix = "^fig:"; + m_prefix = "tab:"; + } + + setWindowTitle(caption); + QString s = m_FloatDialog.m_edLabel->text(); + s.replace(QRegExp(oldprefix), m_prefix); + m_FloatDialog.m_edLabel->setText(s); } } diff --git a/src/dialogs/floatdialog.h b/src/dialogs/floatdialog.h index 2cdb733a..a60c8894 100644 --- a/src/dialogs/floatdialog.h +++ b/src/dialogs/floatdialog.h @@ -1,52 +1,52 @@ /*************************************************************************** date : Jan 28 2005 version : 0.10 copyright : (C) 2005 by Holger Danielsson email : holger.danielsson@t-online.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. * * * ***************************************************************************/ #ifndef FLOATDIALOG_H #define FLOATDIALOG_H #include "kilewizard.h" #include "kileinfo.h" #include "ui_floatdialog_base.h" namespace KileDialog { class FloatEnvironmentDialog : public Wizard { - Q_OBJECT + Q_OBJECT - public: - FloatEnvironmentDialog(KConfig *config, KileInfo *ki, QWidget *parent); - ~FloatEnvironmentDialog() {} +public: + FloatEnvironmentDialog(KConfig *config, KileInfo *ki, QWidget *parent); + ~FloatEnvironmentDialog() {} - public Q_SLOTS: - void slotAccepted(); +public Q_SLOTS: + void slotAccepted(); - private Q_SLOTS: - void slotEnvironmentClicked(); +private Q_SLOTS: + void slotEnvironmentClicked(); - private: - Ui::FloatDialog m_FloatDialog; +private: + Ui::FloatDialog m_FloatDialog; - QString m_prefix; - KileInfo *m_ki; + QString m_prefix; + KileInfo *m_ki; }; } #endif diff --git a/src/dialogs/includegraphicsdialog.cpp b/src/dialogs/includegraphicsdialog.cpp index a2fddd7e..f5d091a2 100644 --- a/src/dialogs/includegraphicsdialog.cpp +++ b/src/dialogs/includegraphicsdialog.cpp @@ -1,627 +1,627 @@ /************************************************************************************************** Copyright (C) 2004-2005 Holger Danielsson 2004 Jeroen Wijnhout 2015 Andreas Cord-Landwehr **************************************************************************************************/ /*************************************************************************** * * * 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. * * * ***************************************************************************/ #include "dialogs/includegraphicsdialog.h" #include "editorextension.h" #include "errorhandler.h" #include "kileactions.h" #include "kileconfig.h" #include "kiledebug.h" #include "kileinfo.h" #include "kiletool_enums.h" #include #include #include #include #include #include #include #include #include #include namespace KileDialog { IncludeGraphics::IncludeGraphics(QWidget *parent, const QString &startdir, KileInfo *ki) - : QDialog(parent) - , m_buttonBox(new QDialogButtonBox(QDialogButtonBox::Ok|QDialogButtonBox::Cancel)) - , m_startdir(startdir) - , m_width(0) - , m_height(0) - , m_ki(ki) - , m_proc(Q_NULLPTR) + : QDialog(parent) + , m_buttonBox(new QDialogButtonBox(QDialogButtonBox::Ok|QDialogButtonBox::Cancel)) + , m_startdir(startdir) + , m_width(0) + , m_height(0) + , m_ki(ki) + , m_proc(Q_NULLPTR) { - setWindowTitle(i18n("Include Graphics")); - setModal(true); - QWidget *mainWidget = new QWidget(this); - QVBoxLayout *mainLayout = new QVBoxLayout; - setLayout(mainLayout); - mainLayout->addWidget(mainWidget); - - QWidget *page = new QWidget(this); - m_widget.setupUi(page); - mainLayout->addWidget(page); - - // read configuration - readConfig(); - onChooseFilter(); - - setFocusProxy(m_widget.edit_file); - m_widget.edit_file->setMode(KFile::File | KFile::LocalOnly); - m_widget.edit_file->setStartDir(QUrl::fromLocalFile(m_startdir)); - m_widget.edit_file->setFocus(); - - connect(m_widget.cb_bb, &QCheckBox::toggled, this, &IncludeGraphics::onChooseFilter); - connect(m_widget.edit_file, &KUrlRequester::urlSelected, this, &IncludeGraphics::onUrlSelected); - connect(m_widget.edit_file, &KUrlRequester::textChanged, this, &IncludeGraphics::onTextChanged); - connect(m_widget.cb_figure, &QGroupBox::toggled, this, &IncludeGraphics::onFigureSelected); - connect(m_widget.cb_wrapfigure, &QGroupBox::toggled, this, &IncludeGraphics::onWrapFigureSelected); - - QPushButton *okButton = m_buttonBox->button(QDialogButtonBox::Ok); - okButton->setDefault(true); - okButton->setShortcut(Qt::CTRL | Qt::Key_Return); - okButton->setEnabled(false); - mainLayout->addWidget(m_buttonBox); - - connect(m_buttonBox, &QDialogButtonBox::accepted, this, &QDialog::accept); - connect(m_buttonBox, &QDialogButtonBox::rejected, this, &QDialog::reject); - connect(this, &QDialog::accepted, this, &IncludeGraphics::onAccepted); + setWindowTitle(i18n("Include Graphics")); + setModal(true); + QWidget *mainWidget = new QWidget(this); + QVBoxLayout *mainLayout = new QVBoxLayout; + setLayout(mainLayout); + mainLayout->addWidget(mainWidget); + + QWidget *page = new QWidget(this); + m_widget.setupUi(page); + mainLayout->addWidget(page); + + // read configuration + readConfig(); + onChooseFilter(); + + setFocusProxy(m_widget.edit_file); + m_widget.edit_file->setMode(KFile::File | KFile::LocalOnly); + m_widget.edit_file->setStartDir(QUrl::fromLocalFile(m_startdir)); + m_widget.edit_file->setFocus(); + + connect(m_widget.cb_bb, &QCheckBox::toggled, this, &IncludeGraphics::onChooseFilter); + connect(m_widget.edit_file, &KUrlRequester::urlSelected, this, &IncludeGraphics::onUrlSelected); + connect(m_widget.edit_file, &KUrlRequester::textChanged, this, &IncludeGraphics::onTextChanged); + connect(m_widget.cb_figure, &QGroupBox::toggled, this, &IncludeGraphics::onFigureSelected); + connect(m_widget.cb_wrapfigure, &QGroupBox::toggled, this, &IncludeGraphics::onWrapFigureSelected); + + QPushButton *okButton = m_buttonBox->button(QDialogButtonBox::Ok); + okButton->setDefault(true); + okButton->setShortcut(Qt::CTRL | Qt::Key_Return); + okButton->setEnabled(false); + mainLayout->addWidget(m_buttonBox); + + connect(m_buttonBox, &QDialogButtonBox::accepted, this, &QDialog::accept); + connect(m_buttonBox, &QDialogButtonBox::rejected, this, &QDialog::reject); + connect(this, &QDialog::accepted, this, &IncludeGraphics::onAccepted); } IncludeGraphics::~IncludeGraphics() { - delete m_proc; + delete m_proc; } ////////////////////////////// configuration data ////////////////////////////// void IncludeGraphics::readConfig() { - m_widget.cb_center->setChecked(KileConfig::igCenter()); - m_widget.cb_bb->setChecked(KileConfig::igBoundingBox()); - m_widget.cb_graphicspath->setChecked(KileConfig::igGraphicspath()); - - m_widget.cb_figure->setChecked(KileConfig::igFigure()); - m_widget.cb_Bottom->setChecked(KileConfig::igBottom()); - m_widget.cb_Force->setChecked(KileConfig::igForce()); - m_widget.cb_Here->setChecked(KileConfig::igHere()); - m_widget.cb_Page->setChecked(KileConfig::igPage()); - m_widget.cb_Top->setChecked(KileConfig::igTop()); - - m_widget.cb_wrapfigure->setChecked(KileConfig::igWrapFigure()); - m_widget.cb_wrapright->setChecked(KileConfig::igWrapRight()); - m_widget.cb_wrapleft->setChecked(KileConfig::igWrapLeft()); - m_widget.cb_wrapinside->setChecked(KileConfig::igWrapInside()); - m_widget.cb_wrapoutside->setChecked(KileConfig::igWrapOutside()); - m_widget.cb_wrapfloat->setChecked(KileConfig::igWrapFloat()); - - m_imagemagick = KileConfig::imagemagick(); - m_boundingbox = KileConfig::boundingbox(); - m_defaultresolution = KileConfig::resolution(); + m_widget.cb_center->setChecked(KileConfig::igCenter()); + m_widget.cb_bb->setChecked(KileConfig::igBoundingBox()); + m_widget.cb_graphicspath->setChecked(KileConfig::igGraphicspath()); + + m_widget.cb_figure->setChecked(KileConfig::igFigure()); + m_widget.cb_Bottom->setChecked(KileConfig::igBottom()); + m_widget.cb_Force->setChecked(KileConfig::igForce()); + m_widget.cb_Here->setChecked(KileConfig::igHere()); + m_widget.cb_Page->setChecked(KileConfig::igPage()); + m_widget.cb_Top->setChecked(KileConfig::igTop()); + + m_widget.cb_wrapfigure->setChecked(KileConfig::igWrapFigure()); + m_widget.cb_wrapright->setChecked(KileConfig::igWrapRight()); + m_widget.cb_wrapleft->setChecked(KileConfig::igWrapLeft()); + m_widget.cb_wrapinside->setChecked(KileConfig::igWrapInside()); + m_widget.cb_wrapoutside->setChecked(KileConfig::igWrapOutside()); + m_widget.cb_wrapfloat->setChecked(KileConfig::igWrapFloat()); + + m_imagemagick = KileConfig::imagemagick(); + m_boundingbox = KileConfig::boundingbox(); + m_defaultresolution = KileConfig::resolution(); } void IncludeGraphics::writeConfig() { - KileConfig::setIgCenter(m_widget.cb_center->isChecked()); - KileConfig::setIgBoundingBox(m_widget.cb_bb->isChecked()); - KileConfig::setIgGraphicspath(m_widget.cb_graphicspath->isChecked()); - - KileConfig::setIgFigure(m_widget.cb_figure->isChecked()); - KileConfig::setIgBottom(m_widget.cb_Bottom->isChecked()); - KileConfig::setIgHere(m_widget.cb_Here->isChecked()); - KileConfig::setIgPage(m_widget.cb_Page->isChecked()); - KileConfig::setIgTop(m_widget.cb_Top->isChecked()); - KileConfig::setIgForce(m_widget.cb_Force->isChecked()); - - KileConfig::setIgWrapFigure(m_widget.cb_wrapfigure->isChecked()); - KileConfig::setIgWrapRight(m_widget.cb_wrapright->isChecked()); - KileConfig::setIgWrapLeft(m_widget.cb_wrapleft->isChecked()); - KileConfig::setIgWrapInside(m_widget.cb_wrapinside->isChecked()); - KileConfig::setIgWrapOutside(m_widget.cb_wrapoutside->isChecked()); - KileConfig::setIgWrapFloat(m_widget.cb_wrapfloat->isChecked()); + KileConfig::setIgCenter(m_widget.cb_center->isChecked()); + KileConfig::setIgBoundingBox(m_widget.cb_bb->isChecked()); + KileConfig::setIgGraphicspath(m_widget.cb_graphicspath->isChecked()); + + KileConfig::setIgFigure(m_widget.cb_figure->isChecked()); + KileConfig::setIgBottom(m_widget.cb_Bottom->isChecked()); + KileConfig::setIgHere(m_widget.cb_Here->isChecked()); + KileConfig::setIgPage(m_widget.cb_Page->isChecked()); + KileConfig::setIgTop(m_widget.cb_Top->isChecked()); + KileConfig::setIgForce(m_widget.cb_Force->isChecked()); + + KileConfig::setIgWrapFigure(m_widget.cb_wrapfigure->isChecked()); + KileConfig::setIgWrapRight(m_widget.cb_wrapright->isChecked()); + KileConfig::setIgWrapLeft(m_widget.cb_wrapleft->isChecked()); + KileConfig::setIgWrapInside(m_widget.cb_wrapinside->isChecked()); + KileConfig::setIgWrapOutside(m_widget.cb_wrapoutside->isChecked()); + KileConfig::setIgWrapFloat(m_widget.cb_wrapfloat->isChecked()); } ////////////////////////////// determine the whole tag ////////////////////////////// QString IncludeGraphics::getTemplate() { - QString s; - - // state of figure, wrapfigure, and center checkbox - bool figure = m_widget.cb_figure->isChecked(); - bool wrapfigure = m_widget.cb_wrapfigure->isChecked(); - bool center = m_widget.cb_center->isChecked(); - const QString indent = (figure || center) ? m_ki->editorExtension()->autoIndentEnvironment() : QString(); - - // build tags for start of figure environment - if (figure) { - // positioning for figure environment - QString p; - bool here = m_widget.cb_Here->isChecked(); - bool top = m_widget.cb_Top->isChecked(); - bool bottom = m_widget.cb_Bottom->isChecked(); - bool page = m_widget.cb_Page->isChecked(); - bool force = m_widget.cb_Force->isChecked(); - bool custom = m_widget.cb_custom->isChecked(); - - // build position string - if (here||top||bottom||page||custom) { // Don't check for force -- if it is the only selection, just skip the position tag - p += '['; - if (here) p+= 'h'; - if (top) p+= 't'; - if (bottom) p+= 'b'; - if (page) p+= 'p'; - if (force) p+= '!'; - if (custom) p+= m_widget.edit_custom->text(); - p += ']'; - } - - // add start of figure environment - s += "\\begin{figure}" + p + '\n'; - } - - // build tags for start of wrapfigure environment - if (wrapfigure) { - s += "\\begin{wrapfigure}"; - - // number of lines in length - if (!m_widget.edit_wraplines->text().isEmpty()) { - s += '[' + m_widget.edit_wraplines->text() + ']'; - } - - // positioning for wrapfigure environment - bool wrapfloat; - wrapfloat = m_widget.cb_wrapfloat->isChecked(); - if (m_widget.cb_wrapright->isChecked()) { - if (wrapfloat) s += "{R}"; - else s += "{r}"; - } - if (m_widget.cb_wrapleft->isChecked()) { - if (wrapfloat) s += "{L}"; - else s += "{l}"; - } - if (m_widget.cb_wrapinside->isChecked()) { - if (wrapfloat) s += "{I}"; - else s += "{i}"; - } - if (m_widget.cb_wrapoutside->isChecked()) { - if (wrapfloat) s += "{O}"; - else s += "{i}"; - } - - // overhang into margin - if (!m_widget.edit_wrapoverhang->text().isEmpty()) { - s += '[' + m_widget.edit_wrapoverhang->text() + ']'; - } - - // width of figure - if (!m_widget.edit_wrapwidth->text().isEmpty()) { - s += '{' + m_widget.edit_wrapwidth->text() + '}'; - } - - // end of wrapfigure options - s += '\n'; - - // Include warning in comment if wrapfig is not loaded. - // Sending a warning to the log here would be good, but - // the log seems to get cleared before user could catch - // the warning. - QStringList packagelist = m_ki->allPackages(); - if (!packagelist.contains("wrapfig")) { - s += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n"; - s += "%%% You will need to add \\usepackage{wrapfig} to your preamble to use textwrapping %%%\n"; - s += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n"; - } - } - - - // add start of center environment ? - if (center) { - if (figure || wrapfigure) { - s += indent + "\\centering\n"; - } else { - s += "\\begin{center}\n"; - } - } - - // add includegraphics command - s += indent + "\\includegraphics"; - - // add some options - QString options = getOptions(); - if (!options.isEmpty()) { - s += '[' + options + ']'; - } - - // add name of picture - // either take the filename or try to take the relative part of the name - const QString relativeUrl = QDir(QFileInfo(m_ki->getCompileName()).path()).relativeFilePath(m_widget.edit_file->lineEdit()->text()); - QString filename = (m_widget.cb_graphicspath->isChecked()) - ? QFileInfo(m_widget.edit_file->lineEdit()->text()).fileName() - : relativeUrl; - s += '{' + filename + "}\n"; - - // add some comments (depending of given resolution, this may be wrong!) - QString info = getInfo(); - if (info.length() > 0) { - s += indent + info + '\n'; - } - - // close center environment ? - if (center && !figure && !wrapfigure) { - s += "\\end{center}\n"; - } - - // close figure environment ? - if (figure) { - QString caption = m_widget.edit_caption->text().trimmed(); - if (!caption.isEmpty()) { - s += indent + "\\caption{" + caption + "}\n"; - } - QString label = m_widget.edit_label->text().trimmed(); - if (!label.isEmpty() && label != "fig:") { - s += indent + "\\label{" + label + "}\n"; - } - s += "\\end{figure}\n"; - } - - if (wrapfigure) { - QString caption = m_widget.edit_wrapcaption->text().trimmed(); - if (!caption.isEmpty()) { - s += indent + "\\caption{" + caption + "}\n"; - } - QString label = m_widget.edit_wraplabel->text().trimmed(); - if (!label.isEmpty() && label != "fig:") { - s += indent + "\\label{" + label + "}\n"; - } - s += "\\end{wrapfigure}\n"; - } - - return s; + QString s; + + // state of figure, wrapfigure, and center checkbox + bool figure = m_widget.cb_figure->isChecked(); + bool wrapfigure = m_widget.cb_wrapfigure->isChecked(); + bool center = m_widget.cb_center->isChecked(); + const QString indent = (figure || center) ? m_ki->editorExtension()->autoIndentEnvironment() : QString(); + + // build tags for start of figure environment + if (figure) { + // positioning for figure environment + QString p; + bool here = m_widget.cb_Here->isChecked(); + bool top = m_widget.cb_Top->isChecked(); + bool bottom = m_widget.cb_Bottom->isChecked(); + bool page = m_widget.cb_Page->isChecked(); + bool force = m_widget.cb_Force->isChecked(); + bool custom = m_widget.cb_custom->isChecked(); + + // build position string + if (here||top||bottom||page||custom) { // Don't check for force -- if it is the only selection, just skip the position tag + p += '['; + if (here) p+= 'h'; + if (top) p+= 't'; + if (bottom) p+= 'b'; + if (page) p+= 'p'; + if (force) p+= '!'; + if (custom) p+= m_widget.edit_custom->text(); + p += ']'; + } + + // add start of figure environment + s += "\\begin{figure}" + p + '\n'; + } + + // build tags for start of wrapfigure environment + if (wrapfigure) { + s += "\\begin{wrapfigure}"; + + // number of lines in length + if (!m_widget.edit_wraplines->text().isEmpty()) { + s += '[' + m_widget.edit_wraplines->text() + ']'; + } + + // positioning for wrapfigure environment + bool wrapfloat; + wrapfloat = m_widget.cb_wrapfloat->isChecked(); + if (m_widget.cb_wrapright->isChecked()) { + if (wrapfloat) s += "{R}"; + else s += "{r}"; + } + if (m_widget.cb_wrapleft->isChecked()) { + if (wrapfloat) s += "{L}"; + else s += "{l}"; + } + if (m_widget.cb_wrapinside->isChecked()) { + if (wrapfloat) s += "{I}"; + else s += "{i}"; + } + if (m_widget.cb_wrapoutside->isChecked()) { + if (wrapfloat) s += "{O}"; + else s += "{i}"; + } + + // overhang into margin + if (!m_widget.edit_wrapoverhang->text().isEmpty()) { + s += '[' + m_widget.edit_wrapoverhang->text() + ']'; + } + + // width of figure + if (!m_widget.edit_wrapwidth->text().isEmpty()) { + s += '{' + m_widget.edit_wrapwidth->text() + '}'; + } + + // end of wrapfigure options + s += '\n'; + + // Include warning in comment if wrapfig is not loaded. + // Sending a warning to the log here would be good, but + // the log seems to get cleared before user could catch + // the warning. + QStringList packagelist = m_ki->allPackages(); + if (!packagelist.contains("wrapfig")) { + s += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n"; + s += "%%% You will need to add \\usepackage{wrapfig} to your preamble to use textwrapping %%%\n"; + s += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n"; + } + } + + + // add start of center environment ? + if (center) { + if (figure || wrapfigure) { + s += indent + "\\centering\n"; + } else { + s += "\\begin{center}\n"; + } + } + + // add includegraphics command + s += indent + "\\includegraphics"; + + // add some options + QString options = getOptions(); + if (!options.isEmpty()) { + s += '[' + options + ']'; + } + + // add name of picture + // either take the filename or try to take the relative part of the name + const QString relativeUrl = QDir(QFileInfo(m_ki->getCompileName()).path()).relativeFilePath(m_widget.edit_file->lineEdit()->text()); + QString filename = (m_widget.cb_graphicspath->isChecked()) + ? QFileInfo(m_widget.edit_file->lineEdit()->text()).fileName() + : relativeUrl; + s += '{' + filename + "}\n"; + + // add some comments (depending of given resolution, this may be wrong!) + QString info = getInfo(); + if (info.length() > 0) { + s += indent + info + '\n'; + } + + // close center environment ? + if (center && !figure && !wrapfigure) { + s += "\\end{center}\n"; + } + + // close figure environment ? + if (figure) { + QString caption = m_widget.edit_caption->text().trimmed(); + if (!caption.isEmpty()) { + s += indent + "\\caption{" + caption + "}\n"; + } + QString label = m_widget.edit_label->text().trimmed(); + if (!label.isEmpty() && label != "fig:") { + s += indent + "\\label{" + label + "}\n"; + } + s += "\\end{figure}\n"; + } + + if (wrapfigure) { + QString caption = m_widget.edit_wrapcaption->text().trimmed(); + if (!caption.isEmpty()) { + s += indent + "\\caption{" + caption + "}\n"; + } + QString label = m_widget.edit_wraplabel->text().trimmed(); + if (!label.isEmpty() && label != "fig:") { + s += indent + "\\label{" + label + "}\n"; + } + s += "\\end{wrapfigure}\n"; + } + + return s; } QString IncludeGraphics::getFilename() { - return m_widget.edit_file->lineEdit()->text(); + return m_widget.edit_file->lineEdit()->text(); } ////////////////////////////// some calculations ////////////////////////////// QString IncludeGraphics::getOptions() { - QString s = QString(); - - if (!m_widget.edit_width->text().isEmpty()) { - s += ",width=" + m_widget.edit_width->text(); - } - - if (!m_widget.edit_height->text().isEmpty()) { - s += ",height=" + m_widget.edit_height->text(); - } - - if (!m_widget.edit_angle->text().isEmpty()) { - s += ",angle=" + m_widget.edit_angle->text(); - } - - // Only dvips needs the bounding box, not pdftex/pdflatex. - // But it will be always inserted as a comment. - if (!m_widget.edit_bb->text().isEmpty() && m_widget.cb_bb->isChecked()) { - s += ",bb=" + m_widget.edit_bb->text(); - } - - if (!m_widget.edit_scale->text().isEmpty()) { - s += ",scale=" + m_widget.edit_scale->text(); - } - - if (m_widget.cb_keepAspect->isChecked()) { - s+= ",keepaspectratio=true"; - } - - if (m_widget.cb_clip->isChecked()) { - QString l="0pt", b="0pt", r="0pt", t="0pt"; - if (!m_widget.edit_trimLeft->text().isEmpty()) { - l = m_widget.edit_trimLeft->text(); - } - if (!m_widget.edit_trimBottom->text().isEmpty()) { - b = m_widget.edit_trimBottom->text(); - } - if (!m_widget.edit_trimRight->text().isEmpty()) { - r = m_widget.edit_trimRight->text(); - } - if (!m_widget.edit_trimTop->text().isEmpty()) { - t = m_widget.edit_trimTop->text(); - } - s += ",clip=true,trim=" + l + ' ' + b + ' ' + r + ' ' + t; - } - - if (s.left(1) == ",") { - return s.right(s.length() - 1); - } else { - return s; - } + QString s = QString(); + + if (!m_widget.edit_width->text().isEmpty()) { + s += ",width=" + m_widget.edit_width->text(); + } + + if (!m_widget.edit_height->text().isEmpty()) { + s += ",height=" + m_widget.edit_height->text(); + } + + if (!m_widget.edit_angle->text().isEmpty()) { + s += ",angle=" + m_widget.edit_angle->text(); + } + + // Only dvips needs the bounding box, not pdftex/pdflatex. + // But it will be always inserted as a comment. + if (!m_widget.edit_bb->text().isEmpty() && m_widget.cb_bb->isChecked()) { + s += ",bb=" + m_widget.edit_bb->text(); + } + + if (!m_widget.edit_scale->text().isEmpty()) { + s += ",scale=" + m_widget.edit_scale->text(); + } + + if (m_widget.cb_keepAspect->isChecked()) { + s+= ",keepaspectratio=true"; + } + + if (m_widget.cb_clip->isChecked()) { + QString l="0pt", b="0pt", r="0pt", t="0pt"; + if (!m_widget.edit_trimLeft->text().isEmpty()) { + l = m_widget.edit_trimLeft->text(); + } + if (!m_widget.edit_trimBottom->text().isEmpty()) { + b = m_widget.edit_trimBottom->text(); + } + if (!m_widget.edit_trimRight->text().isEmpty()) { + r = m_widget.edit_trimRight->text(); + } + if (!m_widget.edit_trimTop->text().isEmpty()) { + t = m_widget.edit_trimTop->text(); + } + s += ",clip=true,trim=" + l + ' ' + b + ' ' + r + ' ' + t; + } + + if (s.left(1) == ",") { + return s.right(s.length() - 1); + } else { + return s; + } } ////////////////////////////// graphics info ////////////////////////////// QString IncludeGraphics::getInfo() { - QString wcm, hcm, dpi; - int wpx = 0, hpx = 0; - - bool ok = getPictureSize(wpx, hpx, dpi, wcm, hcm); - if (!ok) { - return QString(); - } else { - QFileInfo fi(m_widget.edit_file->lineEdit()->text()); - - return "% " + fi.baseName() + '.' + fi.completeSuffix() - + QString(": %1x%2 px").arg(wpx).arg(hpx) - + ", " + dpi + "dpi" - + ", " + wcm + 'x' + hcm + " cm" - + ", bb=" + m_widget.edit_bb->text(); - } + QString wcm, hcm, dpi; + int wpx = 0, hpx = 0; + + bool ok = getPictureSize(wpx, hpx, dpi, wcm, hcm); + if (!ok) { + return QString(); + } else { + QFileInfo fi(m_widget.edit_file->lineEdit()->text()); + + return "% " + fi.baseName() + '.' + fi.completeSuffix() + + QString(": %1x%2 px").arg(wpx).arg(hpx) + + ", " + dpi + "dpi" + + ", " + wcm + 'x' + hcm + " cm" + + ", bb=" + m_widget.edit_bb->text(); + } } void IncludeGraphics::setInfo() { - QString text; - QString wcm, hcm, dpi; - int wpx, hpx; - - if (!m_widget.edit_file->lineEdit()->text().isEmpty() && getPictureSize(wpx, hpx, dpi, wcm, hcm)) { - text = QString("%1x%2 px").arg(wpx).arg(hpx) - + " / " + wcm + 'x' + hcm + " cm" - + " (" + dpi + "dpi)"; - } else { - text = "---"; - } - - // insert text - m_widget.infolabel->setText(text); + QString text; + QString wcm, hcm, dpi; + int wpx, hpx; + + if (!m_widget.edit_file->lineEdit()->text().isEmpty() && getPictureSize(wpx, hpx, dpi, wcm, hcm)) { + text = QString("%1x%2 px").arg(wpx).arg(hpx) + + " / " + wcm + 'x' + hcm + " cm" + + " (" + dpi + "dpi)"; + } else { + text = "---"; + } + + // insert text + m_widget.infolabel->setText(text); } bool IncludeGraphics::getPictureSize(int &wpx, int &hpx, QString &dpi, QString &wcm, QString &hcm) { - wpx = m_width; - hpx = m_height; + wpx = m_width; + hpx = m_height; - dpi = QString::number((int)(m_resolution + 0.5)); + dpi = QString::number((int)(m_resolution + 0.5)); - // convert from inch to cm - float w = (float)m_width / m_resolution * 2.54; - wcm = wcm.setNum(w, 'f', 2); + // convert from inch to cm + float w = (float)m_width / m_resolution * 2.54; + wcm = wcm.setNum(w, 'f', 2); - float h = (float)m_height / m_resolution * 2.54; - hcm = hcm.setNum(h, 'f', 2); - return true; + float h = (float)m_height / m_resolution * 2.54; + hcm = hcm.setNum(h, 'f', 2); + return true; } void IncludeGraphics::onChooseFilter() { - QString filter = (!m_widget.cb_bb->isChecked()) - ? i18n("*.png *.jpg *.pdf *.ps *.eps|Graphics\n") - + "*.png|PNG Files\n" - + "*.jpg|JPG Files\n" - + "*.pdf|PDF Files\n" - + "*.eps *ps|Postscript Files\n" - + "*|All Files" - : i18n("*.png *.jpg *.eps.gz *.eps|Graphics\n") - + "*.png|PNG Files\n" - + "*.jpg|JPG Files\n" - + "*.eps.gz|Zipped EPS Files\n" - + "*.eps|EPS Files\n" - + "*|All Files"; - m_widget.edit_file->setFilter(filter); + QString filter = (!m_widget.cb_bb->isChecked()) + ? i18n("*.png *.jpg *.pdf *.ps *.eps|Graphics\n") + + "*.png|PNG Files\n" + + "*.jpg|JPG Files\n" + + "*.pdf|PDF Files\n" + + "*.eps *ps|Postscript Files\n" + + "*|All Files" + : i18n("*.png *.jpg *.eps.gz *.eps|Graphics\n") + + "*.png|PNG Files\n" + + "*.jpg|JPG Files\n" + + "*.eps.gz|Zipped EPS Files\n" + + "*.eps|EPS Files\n" + + "*|All Files"; + m_widget.edit_file->setFilter(filter); } void IncludeGraphics::onUrlSelected(const QUrl &url) { - QFileInfo fi(url.toLocalFile()); - - // could we accept the picture? - if (!url.toLocalFile().isEmpty() && fi.exists() && fi.isReadable()) { - // execute the command and filter the result: - // eps|eps.gz --> %%BoundingBox: 0 0 123 456 - // bitmaps --> w=123 h=456 dpi=789 - QString grep = " | grep -m1 \"^%%BoundingBox:\""; - QString ext = fi.completeSuffix(); - if (ext == "eps") { - execute("cat " + url.toLocalFile() + grep); - } - else if (ext == "eps.gz") { - execute("gunzip -c " + url.toLocalFile() + grep); - } - else { - execute("identify -format \"w=%w h=%h dpi=%x %U\" \"" + url.toLocalFile() + "\""); - } - m_buttonBox->button(QDialogButtonBox::Ok)->setEnabled(true); - } else { - KILE_DEBUG_MAIN << "=== IncludeGraphics::error ===================="; - KILE_DEBUG_MAIN << " filename: '" << url.toLocalFile() << "'"; - - m_widget.infolabel->setText("---"); - m_widget.edit_bb->setText(""); - m_buttonBox->button(QDialogButtonBox::Ok)->setEnabled(false); - } + QFileInfo fi(url.toLocalFile()); + + // could we accept the picture? + if (!url.toLocalFile().isEmpty() && fi.exists() && fi.isReadable()) { + // execute the command and filter the result: + // eps|eps.gz --> %%BoundingBox: 0 0 123 456 + // bitmaps --> w=123 h=456 dpi=789 + QString grep = " | grep -m1 \"^%%BoundingBox:\""; + QString ext = fi.completeSuffix(); + if (ext == "eps") { + execute("cat " + url.toLocalFile() + grep); + } + else if (ext == "eps.gz") { + execute("gunzip -c " + url.toLocalFile() + grep); + } + else { + execute("identify -format \"w=%w h=%h dpi=%x %U\" \"" + url.toLocalFile() + "\""); + } + m_buttonBox->button(QDialogButtonBox::Ok)->setEnabled(true); + } else { + KILE_DEBUG_MAIN << "=== IncludeGraphics::error ===================="; + KILE_DEBUG_MAIN << " filename: '" << url.toLocalFile() << "'"; + + m_widget.infolabel->setText("---"); + m_widget.edit_bb->setText(""); + m_buttonBox->button(QDialogButtonBox::Ok)->setEnabled(false); + } } void IncludeGraphics::onTextChanged(const QString &string) { - onUrlSelected(QUrl::fromLocalFile(string.trimmed())); + onUrlSelected(QUrl::fromLocalFile(string.trimmed())); } void IncludeGraphics::execute(const QString &command) { - if (!m_boundingbox || (!m_imagemagick && command.left(8) == "identify")) { - return; - } + if (!m_boundingbox || (!m_imagemagick && command.left(8) == "identify")) { + return; + } - if (m_proc) { - delete m_proc; - } + if (m_proc) { + delete m_proc; + } - m_proc = new KProcess(this); - m_proc->setShellCommand(command); - m_proc->setOutputChannelMode(KProcess::MergedChannels); - m_proc->setReadChannel(QProcess::StandardOutput); + m_proc = new KProcess(this); + m_proc->setShellCommand(command); + m_proc->setOutputChannelMode(KProcess::MergedChannels); + m_proc->setReadChannel(QProcess::StandardOutput); - connect(m_proc, &KProcess::readyReadStandardOutput, this, &IncludeGraphics::onProcessOutput); - connect(m_proc, &KProcess::readyReadStandardError, this, &IncludeGraphics::onProcessOutput); - connect(m_proc, static_cast(&KProcess::finished), this, &IncludeGraphics::onProcessExited); + connect(m_proc, &KProcess::readyReadStandardOutput, this, &IncludeGraphics::onProcessOutput); + connect(m_proc, &KProcess::readyReadStandardError, this, &IncludeGraphics::onProcessOutput); + connect(m_proc, static_cast(&KProcess::finished), this, &IncludeGraphics::onProcessExited); - m_output = QString(); - KILE_DEBUG_MAIN << "=== IncludeGraphics::execute ===================="; - KILE_DEBUG_MAIN << " execute '" << command << "'"; + m_output = QString(); + KILE_DEBUG_MAIN << "=== IncludeGraphics::execute ===================="; + KILE_DEBUG_MAIN << " execute '" << command << "'"; - m_proc->start(); + m_proc->start(); } // get all output of identify void IncludeGraphics::onProcessOutput() { - m_output += m_proc->readAll(); + m_output += m_proc->readAll(); } // identify was called void IncludeGraphics::onProcessExited(int /* exitCode */, QProcess::ExitStatus exitStatus) { - if (exitStatus == QProcess::NormalExit) { - KILE_DEBUG_MAIN << " result: " << m_output; - - // set the default resolution - m_resolution = m_defaultresolution; - - // analyze the result - if (m_output.left(14) == "%%BoundingBox:") { - m_widget.edit_bb->setText(m_output.trimmed().mid(15, m_output.length() - 15)); - - // this regexp will extract width and height from the bounding box - QRegExp reg("(\\d+) (\\d+) (\\d+) (\\d+)"); - if(reg.indexIn(m_output) == -1) { - return; - } - - // determine lower-left-x (llx), lower-left-y (lly), upper-right-x (urx) and upper-right-y (ury) - bool ok; - int llx = (int)reg.cap(1).toInt(&ok); - if (!ok) { - return; - } - - int lly = (int)reg.cap(2).toInt(&ok); - if (!ok) { - return; - } - - int urx = (int)reg.cap(3).toInt(&ok); - if (!ok) { - return; - } - - int ury = (int)reg.cap(4).toInt(&ok); - if (!ok) { - return; - } - - // calculate width and height from 72 dpi of eps graphics to the default resolution - m_width = ((urx-llx)*m_resolution) / 72; - m_height = ((ury-lly)*m_resolution) / 72; - - // show information - setInfo(); - } - else { - if (m_output.left(2) == "w=") { - // dani 31.7.2004 - // older version of imagemagick (pre 6.0): - // - doesn't care of PixelsPerCentimeter, but always works with PixelsPerInch - // - doesn't use floating numbers as resolution - // so the bounding box has to be calculated in a different way - - // this regexp will accept floating point numbers as resolution - QRegExp reg("w=(\\d+)\\s+h=(\\d+)\\s+dpi=([0-9.]+) (.*)"); - if(reg.indexIn(m_output) == -1) { - return; - } - - // get bounding box and resolution - bool ok; - m_width = (int)reg.cap(1).toInt(&ok); - if (!ok) { - return; - } - - m_height = (int)reg.cap(2).toInt(&ok); - if (!ok) { - return; - } - - float res = (float)reg.cap(3).toFloat(&ok); - if (!ok) { - return; - } - if (res > 0.0) { - m_resolution = res; - } - - // look, if resolution is in PixelsPerCentimeter - if (reg.cap(4).trimmed() == "PixelsPerCentimeter") { - m_resolution *= 2.54; - } - - // calc the bounding box - int bbw = (int)((float)m_width * 72.0 / m_resolution + 0.5); - int bbh = (int)((float)m_height * 72.0 / m_resolution + 0.5); - - // take width and height as parameters for the bounding box - m_widget.edit_bb->setText(QString("0 0 ") + QString::number(bbw) - + ' ' - + QString::number(bbh)); - - // show information - setInfo(); - - } - } - } + if (exitStatus == QProcess::NormalExit) { + KILE_DEBUG_MAIN << " result: " << m_output; + + // set the default resolution + m_resolution = m_defaultresolution; + + // analyze the result + if (m_output.left(14) == "%%BoundingBox:") { + m_widget.edit_bb->setText(m_output.trimmed().mid(15, m_output.length() - 15)); + + // this regexp will extract width and height from the bounding box + QRegExp reg("(\\d+) (\\d+) (\\d+) (\\d+)"); + if(reg.indexIn(m_output) == -1) { + return; + } + + // determine lower-left-x (llx), lower-left-y (lly), upper-right-x (urx) and upper-right-y (ury) + bool ok; + int llx = (int)reg.cap(1).toInt(&ok); + if (!ok) { + return; + } + + int lly = (int)reg.cap(2).toInt(&ok); + if (!ok) { + return; + } + + int urx = (int)reg.cap(3).toInt(&ok); + if (!ok) { + return; + } + + int ury = (int)reg.cap(4).toInt(&ok); + if (!ok) { + return; + } + + // calculate width and height from 72 dpi of eps graphics to the default resolution + m_width = ((urx-llx)*m_resolution) / 72; + m_height = ((ury-lly)*m_resolution) / 72; + + // show information + setInfo(); + } + else { + if (m_output.left(2) == "w=") { + // dani 31.7.2004 + // older version of imagemagick (pre 6.0): + // - doesn't care of PixelsPerCentimeter, but always works with PixelsPerInch + // - doesn't use floating numbers as resolution + // so the bounding box has to be calculated in a different way + + // this regexp will accept floating point numbers as resolution + QRegExp reg("w=(\\d+)\\s+h=(\\d+)\\s+dpi=([0-9.]+) (.*)"); + if(reg.indexIn(m_output) == -1) { + return; + } + + // get bounding box and resolution + bool ok; + m_width = (int)reg.cap(1).toInt(&ok); + if (!ok) { + return; + } + + m_height = (int)reg.cap(2).toInt(&ok); + if (!ok) { + return; + } + + float res = (float)reg.cap(3).toFloat(&ok); + if (!ok) { + return; + } + if (res > 0.0) { + m_resolution = res; + } + + // look, if resolution is in PixelsPerCentimeter + if (reg.cap(4).trimmed() == "PixelsPerCentimeter") { + m_resolution *= 2.54; + } + + // calc the bounding box + int bbw = (int)((float)m_width * 72.0 / m_resolution + 0.5); + int bbh = (int)((float)m_height * 72.0 / m_resolution + 0.5); + + // take width and height as parameters for the bounding box + m_widget.edit_bb->setText(QString("0 0 ") + QString::number(bbw) + + ' ' + + QString::number(bbh)); + + // show information + setInfo(); + + } + } + } } void IncludeGraphics::onAccepted() { - writeConfig(); + writeConfig(); } void IncludeGraphics::onWrapFigureSelected(bool state) { - if (m_widget.cb_figure->isChecked() && state) { - m_widget.cb_figure->setChecked(false); - } - // Adds warning to log if wrapfig isn't in the preamble - QStringList packagelist = m_ki->allPackages(); - if (!packagelist.contains("wrapfig")) { - m_ki->errorHandler()->printMessage(KileTool::Error, i18n("You must include the wrapfig package to use the text wrapping options"), i18n("Missing Package")); - } + if (m_widget.cb_figure->isChecked() && state) { + m_widget.cb_figure->setChecked(false); + } + // Adds warning to log if wrapfig isn't in the preamble + QStringList packagelist = m_ki->allPackages(); + if (!packagelist.contains("wrapfig")) { + m_ki->errorHandler()->printMessage(KileTool::Error, i18n("You must include the wrapfig package to use the text wrapping options"), i18n("Missing Package")); + } } void IncludeGraphics::onFigureSelected(bool state) { - if (m_widget.cb_wrapfigure->isChecked() && state) { - m_widget.cb_wrapfigure->setChecked(false); - } + if (m_widget.cb_wrapfigure->isChecked() && state) { + m_widget.cb_wrapfigure->setChecked(false); + } } } diff --git a/src/dialogs/includegraphicsdialog.h b/src/dialogs/includegraphicsdialog.h index be6def81..edccc17f 100644 --- a/src/dialogs/includegraphicsdialog.h +++ b/src/dialogs/includegraphicsdialog.h @@ -1,89 +1,89 @@ /*************************************************************************** date : Nov 02 2005 version : 0.23 copyright : 2004-2005 Holger Danielsson 2004 Jeroen Wijnhout 2015 Andreas Cord-Landwehr ***************************************************************************/ /*************************************************************************** * * * 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. * * * ***************************************************************************/ #ifndef INCLUDEGRAPHICSDIALOG_H #define INCLUDEGRAPHICSDIALOG_H #include #include #include "ui_includegraphicsdialog_base.h" class QDialogButtonBox; class KProcess; class KileInfo; /** *@author dani */ namespace KileDialog { class IncludeGraphics : public QDialog { - Q_OBJECT + Q_OBJECT public: - IncludeGraphics(QWidget *parent, const QString &startdir, KileInfo *ki); - virtual ~IncludeGraphics(); + IncludeGraphics(QWidget *parent, const QString &startdir, KileInfo *ki); + virtual ~IncludeGraphics(); - QString getTemplate(); - QString getFilename(); + QString getTemplate(); + QString getFilename(); private Q_SLOTS: - void onChooseFilter(); - void onUrlSelected(const QUrl &url); - void onTextChanged(const QString& string); - void onProcessOutput(); - void onProcessExited(int exitCode, QProcess::ExitStatus exitStatus); + void onChooseFilter(); + void onUrlSelected(const QUrl &url); + void onTextChanged(const QString& string); + void onProcessOutput(); + void onProcessExited(int exitCode, QProcess::ExitStatus exitStatus); - void onWrapFigureSelected(bool state); - void onFigureSelected(bool state); - void onAccepted(); + void onWrapFigureSelected(bool state); + void onFigureSelected(bool state); + void onAccepted(); private: - void readConfig(); - void writeConfig(); - QString getOptions(); - QString getInfo(); - bool getPictureSize(int &wpx, int &hpx, QString &dpi, QString &wcm, QString &hcm); - void setInfo(); + void readConfig(); + void writeConfig(); + QString getOptions(); + QString getInfo(); + bool getPictureSize(int &wpx, int &hpx, QString &dpi, QString &wcm, QString &hcm); + void setInfo(); - QDialogButtonBox *m_buttonBox; - Ui::IncludeGraphicsWidget m_widget; + QDialogButtonBox *m_buttonBox; + Ui::IncludeGraphicsWidget m_widget; - QString m_startdir; - QString m_output; + QString m_startdir; + QString m_output; - // current picture - int m_width, m_height; - float m_resolution; + // current picture + int m_width, m_height; + float m_resolution; - // default - bool m_imagemagick; - bool m_boundingbox; - float m_defaultresolution; + // default + bool m_imagemagick; + bool m_boundingbox; + float m_defaultresolution; - void execute(const QString &command); + void execute(const QString &command); - KileInfo *m_ki; - KProcess* m_proc; + KileInfo *m_ki; + KProcess* m_proc; }; } #endif diff --git a/src/dialogs/latexcommanddialog.cpp b/src/dialogs/latexcommanddialog.cpp index 68511a57..6e37c7ee 100644 --- a/src/dialogs/latexcommanddialog.cpp +++ b/src/dialogs/latexcommanddialog.cpp @@ -1,907 +1,906 @@ /*************************************************************************** Copyright (C) 2005 by Holger Danielsson (holger.danielsson@t-online.de) 2010-2014 by Michel Ludwig (michel.ludwig@kdemail.net) ***************************************************************************/ /*************************************************************************** * * * 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. * * * ***************************************************************************/ // kommandos mit weiteren Parametern #include "dialogs/latexcommanddialog.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "kileconfig.h" #include "kiledebug.h" #include "latexcmd.h" namespace KileDialog { // BEGIN NewLatexCommand NewLatexCommand::NewLatexCommand(QWidget *parent, const QString &caption, - const QString &groupname, QTreeWidgetItem *lvitem, - KileDocument::CmdAttribute cmdtype, - QMap *dict) - : QDialog(parent), m_dict(dict) + const QString &groupname, QTreeWidgetItem *lvitem, + KileDocument::CmdAttribute cmdtype, + QMap *dict) + : QDialog(parent), m_dict(dict) { - setWindowTitle(caption); - setModal(true); - QWidget *mainWidget = new QWidget(this); - QVBoxLayout *mainLayout = new QVBoxLayout; - setLayout(mainLayout); - mainLayout->addWidget(mainWidget); - - // 'add' is only allowed, if the QTreeWidgetItem is defined - m_addmode = (lvitem == 0); - m_envmode = (cmdtype < KileDocument::CmdAttrLabel); - m_cmdType = cmdtype; - - // set modes for input dialog - // AMS Math Tab List Verb Label Ref Cit Inc - // MathOrTab + + + - // Option + + + + + + + + - // Parameter + + + + + + + + - - m_useMathOrTab = false; - m_useOption = m_useParameter = true; - if (cmdtype == KileDocument::CmdAttrAmsmath || cmdtype == KileDocument::CmdAttrMath || cmdtype == KileDocument::CmdAttrTabular) { - m_useMathOrTab = true; - } - else { - if(cmdtype == KileDocument::CmdAttrVerbatim) { - m_useParameter = false; - } - } - - QWidget *page = new QWidget(this); - mainLayout->addWidget(page); - - // layout - QVBoxLayout *vbox = new QVBoxLayout(); - vbox->setMargin(0); - page->setLayout(vbox); - - QLabel *label1 = new QLabel(page); - mainLayout->addWidget(label1); - - QGroupBox* group = new QGroupBox(i18n("Attributes"), page); - mainLayout->addWidget(group); - QGridLayout *grid = new QGridLayout(); - group->setLayout(grid); - - QLabel *label2 = new QLabel(i18n("Group:"), group); - QLabel *label3 = new QLabel(i18n("&Name:"), group); - QLabel *grouplabel = new QLabel(groupname, group); - QLabel *label4 = new QLabel(i18n("Include *-&version:"), group); - m_edName = new QLineEdit(group); - m_chStarred = new QCheckBox(group); - - grid->addWidget(label2, 0, 0); - grid->addWidget(grouplabel, 0, 2); - grid->addWidget(label3, 1, 0); - grid->addWidget(m_edName, 1, 2); - grid->addWidget(label4, 2, 0); - grid->addWidget(m_chStarred, 2, 2); - - label3->setBuddy(m_edName); - label4->setBuddy(m_chStarred); - grouplabel->setWhatsThis(i18n("Name of the group, to which this environment or command belongs.")); - if (m_addmode) { - m_edName->setWhatsThis(i18n("Name of the new environment or command.")); - } - else { - m_edName->setWhatsThis(i18n("Name of the environment or command to edit.")); - } - m_chStarred->setWhatsThis(i18n("Does this environment or command also exist in a starred version?")); - - int currentRow = 3; - if (m_useMathOrTab) { - QLabel *label5 = new QLabel(i18n("\\\\ is end of &line:"), group); - QLabel *label6 = new QLabel(i18n("Needs &math mode:"), group); - QLabel *label7 = new QLabel(i18n("&Tabulator:"), group); - m_chEndofline = new QCheckBox(group); - m_chMath = new QCheckBox(group); - m_coTab = new KComboBox(group); - - grid->addWidget(label5, 3, 0); - grid->addWidget(m_chEndofline, 3, 2); - grid->addWidget(label6, 4, 0); - grid->addWidget(m_chMath, 4, 2); - grid->addWidget(label7, 5, 0); - grid->addWidget(m_coTab, 5, 2); - - label5->setBuddy(m_chEndofline); - label6->setBuddy(m_chMath); - label7->setBuddy(m_coTab); - m_chEndofline->setWhatsThis(i18n("Shall 'Smart New Line' insert \\\\?")); - m_chMath->setWhatsThis(i18n("Does this environment need math mode?")); - m_coTab->setWhatsThis(i18n("Define the standard tabulator of this environment.")); - - m_coTab->addItem(QString()); - m_coTab->addItem("&"); - m_coTab->addItem("&="); - m_coTab->addItem("&=&"); - - currentRow += 3; - } - - if (m_useOption) { - QLabel *label8 = new QLabel(i18n("Opt&ion:"), group); - m_coOption = new KComboBox(group); - grid->addWidget(label8, currentRow, 0); - grid->addWidget(m_coOption, currentRow, 2); - - label8->setBuddy(m_coOption); - - m_coOption->addItem(QString()); - if (m_envmode) { - m_coOption->addItem("[tcb]"); - m_coOption->addItem("[lcr]"); - m_coOption->setWhatsThis(i18n("Define an optional alignment parameter.")); - } - else { - m_coOption->setWhatsThis(i18n("Does this command need an optional parameter?")); - } - m_coOption->addItem("[ ]"); - - currentRow++; - } - - if(m_useParameter) { - QLabel *label9 = new QLabel(i18n("&Parameter:"), group); - m_coParameter = new KComboBox(group); - grid->addWidget(label9, currentRow, 0); - grid->addWidget(m_coParameter, currentRow, 2); - - label9->setBuddy(m_coParameter); - - if(m_envmode) { - m_coParameter->addItem(QString()); - m_coParameter->addItem("{n}"); - m_coParameter->addItem("{w}"); - m_coParameter->addItem("{ }"); - m_coParameter->setWhatsThis(i18n("Does this environment need an additional parameter like {n} for an integer number, {w} for a width or { } for any other parameter?")); - } - else - { - m_coParameter->addItem("{ }"); - // m_coParameter->addItem(QString()); - m_coParameter->setWhatsThis(i18n("Does this command need an argument?")); - } - - currentRow++; - } - - // stretch last row - //grid->setRowStretch(maxrows-1,1); - - // add or edit mode - if(m_addmode) { // add mode - QString pattern; - if(m_envmode) { - label1->setText(i18n("Define a new LaTeX environment:")); - pattern = "[A-Za-z]+"; - } - else { - label1->setText(i18n("Define a new LaTeX command:")); - pattern = "\\\\?[A-Za-z]+"; - } - QRegExp reg(pattern); - m_edName->setValidator(new QRegExpValidator(reg, m_edName)); - m_edName->setFocus(); - } - else { // edit mode - // always insert name and starred attribute - m_edName->setText(lvitem->text(0)); - m_edName->setReadOnly(true); - m_chStarred->setChecked(lvitem->text(1) == "*"); - - int index; - if (m_envmode) { // insert existing arguments for environments - label1->setText(i18n("Edit a LaTeX Environment")); - if(m_useMathOrTab) { - m_chEndofline->setChecked(lvitem->text(2) == "\\\\"); - m_chMath->setChecked(lvitem->text(3) == "$"); - if ((index = m_coTab->findText(lvitem->text(4))) > -1) - m_coTab->setCurrentIndex(index); - } - if(m_useOption) { - if ((index = m_coOption->findText(lvitem->text(5))) > -1) - m_coOption->setCurrentIndex(index); - } - if (m_useParameter) { - if ((index = m_coParameter->findText(lvitem->text(6))) > -1) - m_coParameter->setCurrentIndex(index); - } - } - else { // insert existing arguments for commands - label1->setText(i18n("Edit a LaTeX Command")); - if (m_useOption) { - if ((index = m_coOption->findText(lvitem->text(2))) > -1) { - m_coOption->setCurrentIndex(index); - } - } - if (m_useParameter) { - if ((index = m_coParameter->findText(lvitem->text(3))) > -1) { - m_coParameter->setCurrentIndex(index); - } - } - } - } - - // fill vbox - vbox->addWidget(label1, 0, Qt::AlignHCenter); - vbox->addWidget(group); - vbox->addStretch(); - - QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok|QDialogButtonBox::Cancel); - QPushButton *okButton = buttonBox->button(QDialogButtonBox::Ok); - okButton->setDefault(true); - okButton->setShortcut(Qt::CTRL | Qt::Key_Return); - mainLayout->addWidget(buttonBox); - connect(buttonBox, &QDialogButtonBox::accepted, this, &QDialog::accept); - connect(buttonBox, &QDialogButtonBox::rejected, this, &QDialog::reject); - connect(this, &QDialog::accepted, this, &NewLatexCommand::slotAccepted); + setWindowTitle(caption); + setModal(true); + QWidget *mainWidget = new QWidget(this); + QVBoxLayout *mainLayout = new QVBoxLayout; + setLayout(mainLayout); + mainLayout->addWidget(mainWidget); + + // 'add' is only allowed, if the QTreeWidgetItem is defined + m_addmode = (lvitem == 0); + m_envmode = (cmdtype < KileDocument::CmdAttrLabel); + m_cmdType = cmdtype; + + // set modes for input dialog + // AMS Math Tab List Verb Label Ref Cit Inc + // MathOrTab + + + + // Option + + + + + + + + + // Parameter + + + + + + + + + + m_useMathOrTab = false; + m_useOption = m_useParameter = true; + if (cmdtype == KileDocument::CmdAttrAmsmath || cmdtype == KileDocument::CmdAttrMath || cmdtype == KileDocument::CmdAttrTabular) { + m_useMathOrTab = true; + } + else { + if(cmdtype == KileDocument::CmdAttrVerbatim) { + m_useParameter = false; + } + } + + QWidget *page = new QWidget(this); + mainLayout->addWidget(page); + + // layout + QVBoxLayout *vbox = new QVBoxLayout(); + vbox->setMargin(0); + page->setLayout(vbox); + + QLabel *label1 = new QLabel(page); + mainLayout->addWidget(label1); + + QGroupBox* group = new QGroupBox(i18n("Attributes"), page); + mainLayout->addWidget(group); + QGridLayout *grid = new QGridLayout(); + group->setLayout(grid); + + QLabel *label2 = new QLabel(i18n("Group:"), group); + QLabel *label3 = new QLabel(i18n("&Name:"), group); + QLabel *grouplabel = new QLabel(groupname, group); + QLabel *label4 = new QLabel(i18n("Include *-&version:"), group); + m_edName = new QLineEdit(group); + m_chStarred = new QCheckBox(group); + + grid->addWidget(label2, 0, 0); + grid->addWidget(grouplabel, 0, 2); + grid->addWidget(label3, 1, 0); + grid->addWidget(m_edName, 1, 2); + grid->addWidget(label4, 2, 0); + grid->addWidget(m_chStarred, 2, 2); + + label3->setBuddy(m_edName); + label4->setBuddy(m_chStarred); + grouplabel->setWhatsThis(i18n("Name of the group, to which this environment or command belongs.")); + if (m_addmode) { + m_edName->setWhatsThis(i18n("Name of the new environment or command.")); + } + else { + m_edName->setWhatsThis(i18n("Name of the environment or command to edit.")); + } + m_chStarred->setWhatsThis(i18n("Does this environment or command also exist in a starred version?")); + + int currentRow = 3; + if (m_useMathOrTab) { + QLabel *label5 = new QLabel(i18n("\\\\ is end of &line:"), group); + QLabel *label6 = new QLabel(i18n("Needs &math mode:"), group); + QLabel *label7 = new QLabel(i18n("&Tabulator:"), group); + m_chEndofline = new QCheckBox(group); + m_chMath = new QCheckBox(group); + m_coTab = new KComboBox(group); + + grid->addWidget(label5, 3, 0); + grid->addWidget(m_chEndofline, 3, 2); + grid->addWidget(label6, 4, 0); + grid->addWidget(m_chMath, 4, 2); + grid->addWidget(label7, 5, 0); + grid->addWidget(m_coTab, 5, 2); + + label5->setBuddy(m_chEndofline); + label6->setBuddy(m_chMath); + label7->setBuddy(m_coTab); + m_chEndofline->setWhatsThis(i18n("Shall 'Smart New Line' insert \\\\?")); + m_chMath->setWhatsThis(i18n("Does this environment need math mode?")); + m_coTab->setWhatsThis(i18n("Define the standard tabulator of this environment.")); + + m_coTab->addItem(QString()); + m_coTab->addItem("&"); + m_coTab->addItem("&="); + m_coTab->addItem("&=&"); + + currentRow += 3; + } + + if (m_useOption) { + QLabel *label8 = new QLabel(i18n("Opt&ion:"), group); + m_coOption = new KComboBox(group); + grid->addWidget(label8, currentRow, 0); + grid->addWidget(m_coOption, currentRow, 2); + + label8->setBuddy(m_coOption); + + m_coOption->addItem(QString()); + if (m_envmode) { + m_coOption->addItem("[tcb]"); + m_coOption->addItem("[lcr]"); + m_coOption->setWhatsThis(i18n("Define an optional alignment parameter.")); + } + else { + m_coOption->setWhatsThis(i18n("Does this command need an optional parameter?")); + } + m_coOption->addItem("[ ]"); + + currentRow++; + } + + if(m_useParameter) { + QLabel *label9 = new QLabel(i18n("&Parameter:"), group); + m_coParameter = new KComboBox(group); + grid->addWidget(label9, currentRow, 0); + grid->addWidget(m_coParameter, currentRow, 2); + + label9->setBuddy(m_coParameter); + + if(m_envmode) { + m_coParameter->addItem(QString()); + m_coParameter->addItem("{n}"); + m_coParameter->addItem("{w}"); + m_coParameter->addItem("{ }"); + m_coParameter->setWhatsThis(i18n("Does this environment need an additional parameter like {n} for an integer number, {w} for a width or { } for any other parameter?")); + } + else + { + m_coParameter->addItem("{ }"); + // m_coParameter->addItem(QString()); + m_coParameter->setWhatsThis(i18n("Does this command need an argument?")); + } + + currentRow++; + } + + // stretch last row + //grid->setRowStretch(maxrows-1,1); + + // add or edit mode + if(m_addmode) { // add mode + QString pattern; + if(m_envmode) { + label1->setText(i18n("Define a new LaTeX environment:")); + pattern = "[A-Za-z]+"; + } + else { + label1->setText(i18n("Define a new LaTeX command:")); + pattern = "\\\\?[A-Za-z]+"; + } + QRegExp reg(pattern); + m_edName->setValidator(new QRegExpValidator(reg, m_edName)); + m_edName->setFocus(); + } + else { // edit mode + // always insert name and starred attribute + m_edName->setText(lvitem->text(0)); + m_edName->setReadOnly(true); + m_chStarred->setChecked(lvitem->text(1) == "*"); + + int index; + if (m_envmode) { // insert existing arguments for environments + label1->setText(i18n("Edit a LaTeX Environment")); + if(m_useMathOrTab) { + m_chEndofline->setChecked(lvitem->text(2) == "\\\\"); + m_chMath->setChecked(lvitem->text(3) == "$"); + if ((index = m_coTab->findText(lvitem->text(4))) > -1) + m_coTab->setCurrentIndex(index); + } + if(m_useOption) { + if ((index = m_coOption->findText(lvitem->text(5))) > -1) + m_coOption->setCurrentIndex(index); + } + if (m_useParameter) { + if ((index = m_coParameter->findText(lvitem->text(6))) > -1) + m_coParameter->setCurrentIndex(index); + } + } + else { // insert existing arguments for commands + label1->setText(i18n("Edit a LaTeX Command")); + if (m_useOption) { + if ((index = m_coOption->findText(lvitem->text(2))) > -1) { + m_coOption->setCurrentIndex(index); + } + } + if (m_useParameter) { + if ((index = m_coParameter->findText(lvitem->text(3))) > -1) { + m_coParameter->setCurrentIndex(index); + } + } + } + } + + // fill vbox + vbox->addWidget(label1, 0, Qt::AlignHCenter); + vbox->addWidget(group); + vbox->addStretch(); + + QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok|QDialogButtonBox::Cancel); + QPushButton *okButton = buttonBox->button(QDialogButtonBox::Ok); + okButton->setDefault(true); + okButton->setShortcut(Qt::CTRL | Qt::Key_Return); + mainLayout->addWidget(buttonBox); + connect(buttonBox, &QDialogButtonBox::accepted, this, &QDialog::accept); + connect(buttonBox, &QDialogButtonBox::rejected, this, &QDialog::reject); + connect(this, &QDialog::accepted, this, &NewLatexCommand::slotAccepted); } // get all attributes of this command void NewLatexCommand::getParameter(QString &name, KileDocument::LatexCmdAttributes &attr) { - name = m_edName->text(); - if(m_envmode == false && name.at(0) != '\\') { - name.prepend('\\'); - } - - // set main attributes - attr.standard = false; - attr.type = m_cmdType; - attr.starred = m_chStarred->isChecked(); - - // read all atributes attributes - if(m_useMathOrTab) { - attr.cr = m_chEndofline->isChecked(); - attr.mathmode = m_chMath->isChecked(); - attr.displaymathmode = false; - attr.tabulator = m_coTab->currentText(); - } - else { - attr.cr = false; - attr.mathmode = false; - attr.displaymathmode = false; - attr.tabulator.clear(); - } - - attr.option = (m_useOption) ? m_coOption->currentText() : QString(); - attr.parameter = (m_useParameter) ? m_coParameter->currentText() : QString(); + name = m_edName->text(); + if(m_envmode == false && name.at(0) != '\\') { + name.prepend('\\'); + } + + // set main attributes + attr.standard = false; + attr.type = m_cmdType; + attr.starred = m_chStarred->isChecked(); + + // read all atributes attributes + if(m_useMathOrTab) { + attr.cr = m_chEndofline->isChecked(); + attr.mathmode = m_chMath->isChecked(); + attr.displaymathmode = false; + attr.tabulator = m_coTab->currentText(); + } + else { + attr.cr = false; + attr.mathmode = false; + attr.displaymathmode = false; + attr.tabulator.clear(); + } + + attr.option = (m_useOption) ? m_coOption->currentText() : QString(); + attr.parameter = (m_useParameter) ? m_coParameter->currentText() : QString(); } void NewLatexCommand::slotAccepted() { - // check for an empty string - if(m_edName->text().isEmpty()) { - KMessageBox::error(this, i18n("An empty string is not allowed.")); - return; - } - - QString name = m_edName->text(); - if (m_envmode == false && name.at(0) != '\\') { - name.prepend('\\'); - } - - if (m_addmode && m_dict->contains(name)) { - QString msg = (m_envmode) ? i18n("This environment already exists.") - : i18n("This command already exists."); - KMessageBox::error(this, msg); - return; - } + // check for an empty string + if(m_edName->text().isEmpty()) { + KMessageBox::error(this, i18n("An empty string is not allowed.")); + return; + } + + QString name = m_edName->text(); + if (m_envmode == false && name.at(0) != '\\') { + name.prepend('\\'); + } + + if (m_addmode && m_dict->contains(name)) { + QString msg = (m_envmode) ? i18n("This environment already exists.") + : i18n("This command already exists."); + KMessageBox::error(this, msg); + return; + } } //END NewLatexCommand ////////////////////////////// LaTeX environments/commands dialog ////////////////////////////// //BEGIN LatexCommandsDialog LatexCommandsDialog::LatexCommandsDialog(KConfig *config, KileDocument::LatexCommands *commands, QWidget *parent) - : QDialog(parent) - , m_config(config) - , m_commands(commands) - , m_commandChanged(false) - , m_buttonBox(new QDialogButtonBox(QDialogButtonBox::Ok|QDialogButtonBox::Cancel|QDialogButtonBox::RestoreDefaults)) + : QDialog(parent) + , m_config(config) + , m_commands(commands) + , m_commandChanged(false) + , m_buttonBox(new QDialogButtonBox(QDialogButtonBox::Ok|QDialogButtonBox::Cancel|QDialogButtonBox::RestoreDefaults)) { - setWindowTitle(i18n("LaTeX Configuration")); - setLayout(new QVBoxLayout); - setModal(true); - - QWidget* widget = new QWidget(this); - m_widget.setupUi(widget); - - // read config and initialize changes (add, edit or delete an entry) - readConfig(); - // init listview - resetListviews(); - slotEnableButtons(); - - connect(m_widget.tab, SIGNAL(currentChanged(int)), this, SLOT(slotEnableButtons())); - connect(m_widget.environments, SIGNAL(itemSelectionChanged()), this, SLOT(slotEnableButtons())); - connect(m_widget.commands, SIGNAL(itemSelectionChanged()), this, SLOT(slotEnableButtons())); - connect(m_widget.addButton, SIGNAL(clicked()), this, SLOT(slotAddClicked())); - connect(m_widget.deleteButton, SIGNAL(clicked()), this, SLOT(slotDeleteClicked())); - connect(m_widget.editButton, SIGNAL(clicked()), this, SLOT(slotEditClicked())); - connect(m_widget.showOnlyUserDefined, SIGNAL(clicked()), this, SLOT(slotUserDefinedClicked())); - - for (int col = 0; col <= 6; ++col) { - m_widget.environments->resizeColumnToContents(col); - } - for (int col = 0; col <= 3; ++col) { - m_widget.commands->resizeColumnToContents(col); - } - - layout()->addWidget(widget); - layout()->addWidget(m_buttonBox); - - QPushButton* okButton = m_buttonBox->button(QDialogButtonBox::Ok); - QPushButton* defaultsButton = m_buttonBox->button(QDialogButtonBox::RestoreDefaults); - - okButton->setDefault(true); - okButton->setShortcut(Qt::CTRL | Qt::Key_Return); - - connect(m_buttonBox, &QDialogButtonBox::accepted, this, &QDialog::accept); - connect(m_buttonBox, &QDialogButtonBox::rejected, this, &QDialog::reject); - connect(defaultsButton, &QPushButton::clicked, this, &LatexCommandsDialog::slotSetDefaults); - connect(this, &QDialog::accepted, this, &LatexCommandsDialog::slotAccepted); + setWindowTitle(i18n("LaTeX Configuration")); + setLayout(new QVBoxLayout); + setModal(true); + + QWidget* widget = new QWidget(this); + m_widget.setupUi(widget); + + // read config and initialize changes (add, edit or delete an entry) + readConfig(); + // init listview + resetListviews(); + slotEnableButtons(); + + connect(m_widget.tab, SIGNAL(currentChanged(int)), this, SLOT(slotEnableButtons())); + connect(m_widget.environments, SIGNAL(itemSelectionChanged()), this, SLOT(slotEnableButtons())); + connect(m_widget.commands, SIGNAL(itemSelectionChanged()), this, SLOT(slotEnableButtons())); + connect(m_widget.addButton, SIGNAL(clicked()), this, SLOT(slotAddClicked())); + connect(m_widget.deleteButton, SIGNAL(clicked()), this, SLOT(slotDeleteClicked())); + connect(m_widget.editButton, SIGNAL(clicked()), this, SLOT(slotEditClicked())); + connect(m_widget.showOnlyUserDefined, SIGNAL(clicked()), this, SLOT(slotUserDefinedClicked())); + + for (int col = 0; col <= 6; ++col) { + m_widget.environments->resizeColumnToContents(col); + } + for (int col = 0; col <= 3; ++col) { + m_widget.commands->resizeColumnToContents(col); + } + + layout()->addWidget(widget); + layout()->addWidget(m_buttonBox); + + QPushButton* okButton = m_buttonBox->button(QDialogButtonBox::Ok); + QPushButton* defaultsButton = m_buttonBox->button(QDialogButtonBox::RestoreDefaults); + + okButton->setDefault(true); + okButton->setShortcut(Qt::CTRL | Qt::Key_Return); + + connect(m_buttonBox, &QDialogButtonBox::accepted, this, &QDialog::accept); + connect(m_buttonBox, &QDialogButtonBox::rejected, this, &QDialog::reject); + connect(defaultsButton, &QPushButton::clicked, this, &LatexCommandsDialog::slotSetDefaults); + connect(this, &QDialog::accepted, this, &LatexCommandsDialog::slotAccepted); } ////////////////////////////// listview ////////////////////////////// void LatexCommandsDialog::resetListviews() { - m_dictCommands.clear(); - m_widget.environments->clear(); - m_widget.commands->clear(); - - m_lviAmsmath = new QTreeWidgetItem(m_widget.environments, QStringList(i18n("AMS-Math"))); - m_lviMath = new QTreeWidgetItem(m_widget.environments, QStringList(i18n("Math"))); - m_lviList = new QTreeWidgetItem(m_widget.environments, QStringList(i18n("Lists"))); - m_lviTabular = new QTreeWidgetItem(m_widget.environments, QStringList(i18n("Tabular"))); - m_lviVerbatim = new QTreeWidgetItem(m_widget.environments, QStringList(i18n("Verbatim"))); - - m_lviLabels = new QTreeWidgetItem(m_widget.commands, QStringList(i18n("Labels"))); - m_lviReferences = new QTreeWidgetItem(m_widget.commands, QStringList(i18n("References"))); - m_lviBibliographies = new QTreeWidgetItem(m_widget.commands, QStringList(i18n("Bibliographies"))); - m_lviCitations = new QTreeWidgetItem(m_widget.commands, QStringList(i18n("Citations"))); - m_lviInputs = new QTreeWidgetItem(m_widget.commands, QStringList(i18n("Includes"))); - - QStringList list; - QStringList::ConstIterator it; - KileDocument::LatexCmdAttributes attr; - - m_commands->commandList(list, KileDocument::CmdAttrNone, m_widget.showOnlyUserDefined->isChecked()); - for (it = list.constBegin(); it != list.constEnd(); ++it) { - if (m_commands->commandAttributes(*it, attr)) { - QTreeWidgetItem *parent; - switch (attr.type) { - case KileDocument::CmdAttrAmsmath: - parent = m_lviAmsmath; - break; - case KileDocument::CmdAttrMath: - parent = m_lviMath; - break; - case KileDocument::CmdAttrList: - parent = m_lviList; - break; - case KileDocument::CmdAttrTabular: - parent = m_lviTabular; - break; - case KileDocument::CmdAttrVerbatim: - parent = m_lviVerbatim; - break; - case KileDocument::CmdAttrLabel: - parent = m_lviLabels; - break; - case KileDocument::CmdAttrReference: - parent = m_lviReferences; - break; - case KileDocument::CmdAttrCitations: - parent = m_lviCitations; - break; - case KileDocument::CmdAttrIncludes: - parent = m_lviInputs; - break; - case KileDocument::CmdAttrBibliographies: - parent = m_lviBibliographies; - break; - default: - continue; - } - setEntry(parent, *it, attr); - } - } + m_dictCommands.clear(); + m_widget.environments->clear(); + m_widget.commands->clear(); + + m_lviAmsmath = new QTreeWidgetItem(m_widget.environments, QStringList(i18n("AMS-Math"))); + m_lviMath = new QTreeWidgetItem(m_widget.environments, QStringList(i18n("Math"))); + m_lviList = new QTreeWidgetItem(m_widget.environments, QStringList(i18n("Lists"))); + m_lviTabular = new QTreeWidgetItem(m_widget.environments, QStringList(i18n("Tabular"))); + m_lviVerbatim = new QTreeWidgetItem(m_widget.environments, QStringList(i18n("Verbatim"))); + + m_lviLabels = new QTreeWidgetItem(m_widget.commands, QStringList(i18n("Labels"))); + m_lviReferences = new QTreeWidgetItem(m_widget.commands, QStringList(i18n("References"))); + m_lviBibliographies = new QTreeWidgetItem(m_widget.commands, QStringList(i18n("Bibliographies"))); + m_lviCitations = new QTreeWidgetItem(m_widget.commands, QStringList(i18n("Citations"))); + m_lviInputs = new QTreeWidgetItem(m_widget.commands, QStringList(i18n("Includes"))); + + QStringList list; + QStringList::ConstIterator it; + KileDocument::LatexCmdAttributes attr; + + m_commands->commandList(list, KileDocument::CmdAttrNone, m_widget.showOnlyUserDefined->isChecked()); + for (it = list.constBegin(); it != list.constEnd(); ++it) { + if (m_commands->commandAttributes(*it, attr)) { + QTreeWidgetItem *parent; + switch (attr.type) { + case KileDocument::CmdAttrAmsmath: + parent = m_lviAmsmath; + break; + case KileDocument::CmdAttrMath: + parent = m_lviMath; + break; + case KileDocument::CmdAttrList: + parent = m_lviList; + break; + case KileDocument::CmdAttrTabular: + parent = m_lviTabular; + break; + case KileDocument::CmdAttrVerbatim: + parent = m_lviVerbatim; + break; + case KileDocument::CmdAttrLabel: + parent = m_lviLabels; + break; + case KileDocument::CmdAttrReference: + parent = m_lviReferences; + break; + case KileDocument::CmdAttrCitations: + parent = m_lviCitations; + break; + case KileDocument::CmdAttrIncludes: + parent = m_lviInputs; + break; + case KileDocument::CmdAttrBibliographies: + parent = m_lviBibliographies; + break; + default: + continue; + } + setEntry(parent, *it, attr); + } + } } LatexCommandsDialog::LVmode LatexCommandsDialog::getListviewMode() { - return (m_widget.tab->currentIndex() == 0) ? lvEnvMode : lvCmdMode; + return (m_widget.tab->currentIndex() == 0) ? lvEnvMode : lvCmdMode; } KileDocument::CmdAttribute LatexCommandsDialog::getCommandMode(QTreeWidgetItem *item) { - if (item == m_lviAmsmath) { - return KileDocument::CmdAttrAmsmath; - } - if (item == m_lviMath) { - return KileDocument::CmdAttrMath; - } - if (item == m_lviList) { - return KileDocument::CmdAttrList; - } - if (item == m_lviTabular) { - return KileDocument::CmdAttrTabular; - } - if (item == m_lviVerbatim) { - return KileDocument::CmdAttrVerbatim; - } - if (item == m_lviLabels) { - return KileDocument::CmdAttrLabel; - } - if (item == m_lviReferences) { - return KileDocument::CmdAttrReference; - } - if (item == m_lviCitations) { - return KileDocument::CmdAttrCitations; - } - if (item == m_lviInputs) { - return KileDocument::CmdAttrIncludes; - } - if (item == m_lviBibliographies) { - return KileDocument::CmdAttrBibliographies; - } - - return KileDocument::CmdAttrNone; + if (item == m_lviAmsmath) { + return KileDocument::CmdAttrAmsmath; + } + if (item == m_lviMath) { + return KileDocument::CmdAttrMath; + } + if (item == m_lviList) { + return KileDocument::CmdAttrList; + } + if (item == m_lviTabular) { + return KileDocument::CmdAttrTabular; + } + if (item == m_lviVerbatim) { + return KileDocument::CmdAttrVerbatim; + } + if (item == m_lviLabels) { + return KileDocument::CmdAttrLabel; + } + if (item == m_lviReferences) { + return KileDocument::CmdAttrReference; + } + if (item == m_lviCitations) { + return KileDocument::CmdAttrCitations; + } + if (item == m_lviInputs) { + return KileDocument::CmdAttrIncludes; + } + if (item == m_lviBibliographies) { + return KileDocument::CmdAttrBibliographies; + } + + return KileDocument::CmdAttrNone; } bool LatexCommandsDialog::isParentItem(QTreeWidgetItem *item) { - return (item == m_lviMath || - item == m_lviList || - item == m_lviTabular || - item == m_lviVerbatim || - item == m_lviLabels || - item == m_lviReferences || - item == m_lviCitations || - item == m_lviInputs || - item == m_lviBibliographies - ); + return (item == m_lviMath || + item == m_lviList || + item == m_lviTabular || + item == m_lviVerbatim || + item == m_lviLabels || + item == m_lviReferences || + item == m_lviCitations || + item == m_lviInputs || + item == m_lviBibliographies + ); } ////////////////////////////// entries ////////////////////////////// void LatexCommandsDialog::setEntry(QTreeWidgetItem *parent, const QString &name, - KileDocument::LatexCmdAttributes &attr) + KileDocument::LatexCmdAttributes &attr) { - // set dictionary - m_dictCommands[name] = attr.standard; - - // create an item - QTreeWidgetItem *item = new QTreeWidgetItem(parent, QStringList(name)); - - // always set the starred entry - if (attr.starred) - item->setText(1, "*"); - - // environments have more attributes - if (attr.type < KileDocument::CmdAttrLabel) // environments - { - if (attr.cr) - item->setText(2, "\\\\"); - if (attr.mathmode) - item->setText(3, "$"); - else - if (attr.displaymathmode) - item->setText(3, "$$"); - item->setText(4, attr.tabulator); - item->setText(5, attr.option); - item->setText(6, attr.parameter); - } - else // commands - { - item->setText(2, attr.option); - item->setText(3, attr.parameter); - } - - for(int i = 1; i < parent->treeWidget()->columnCount(); ++i) { - item->setTextAlignment(i, Qt::AlignHCenter); - } + // set dictionary + m_dictCommands[name] = attr.standard; + + // create an item + QTreeWidgetItem *item = new QTreeWidgetItem(parent, QStringList(name)); + + // always set the starred entry + if (attr.starred) + item->setText(1, "*"); + + // environments have more attributes + if (attr.type < KileDocument::CmdAttrLabel) // environments + { + if (attr.cr) + item->setText(2, "\\\\"); + if (attr.mathmode) + item->setText(3, "$"); + else if (attr.displaymathmode) + item->setText(3, "$$"); + item->setText(4, attr.tabulator); + item->setText(5, attr.option); + item->setText(6, attr.parameter); + } + else // commands + { + item->setText(2, attr.option); + item->setText(3, attr.parameter); + } + + for(int i = 1; i < parent->treeWidget()->columnCount(); ++i) { + item->setTextAlignment(i, Qt::AlignHCenter); + } } void LatexCommandsDialog::getEntry(QTreeWidgetItem *item, KileDocument::LatexCmdAttributes &attr) { - // always set the starred entry - attr.starred = (item->text(1) == "*"); - - // get all attributes - if (item->text(0).at(0) != '\\') { // environment - attr.cr = (item->text(2) == "\\\\"); - attr.mathmode = (item->text(3) == "$"); - attr.displaymathmode = (item->text(3) == "$$"); - attr.tabulator = item->text(4); - attr.option = item->text(5); - attr.parameter = item->text(6); - } - else { // commands - attr.cr = false; - attr.mathmode = false; - attr.displaymathmode = false; - attr.tabulator.clear(); - attr.option = item->text(2); - attr.parameter = item->text(3); - } + // always set the starred entry + attr.starred = (item->text(1) == "*"); + + // get all attributes + if (item->text(0).at(0) != '\\') { // environment + attr.cr = (item->text(2) == "\\\\"); + attr.mathmode = (item->text(3) == "$"); + attr.displaymathmode = (item->text(3) == "$$"); + attr.tabulator = item->text(4); + attr.option = item->text(5); + attr.parameter = item->text(6); + } + else { // commands + attr.cr = false; + attr.mathmode = false; + attr.displaymathmode = false; + attr.tabulator.clear(); + attr.option = item->text(2); + attr.parameter = item->text(3); + } } ////////////////////////////// type of environment or command ////////////////////////////// bool LatexCommandsDialog::isUserDefined(const QString &name) { - return (m_dictCommands.contains(name) && m_dictCommands[name] == false); + return (m_dictCommands.contains(name) && m_dictCommands[name] == false); } // look for user-defined environment or commands in this listview bool LatexCommandsDialog::hasUserDefined(QTreeWidget *listview) { - QTreeWidgetItem *tli; - for (int i = 0; i < listview->topLevelItemCount(); ++i) { - tli = listview->topLevelItem(i); - for (int j = 0; j < tli->childCount(); ++j) { - if (isUserDefined(tli->child(j)->text(0))) { - return true; - } - } - } - return false; + QTreeWidgetItem *tli; + for (int i = 0; i < listview->topLevelItemCount(); ++i) { + tli = listview->topLevelItem(i); + for (int j = 0; j < tli->childCount(); ++j) { + if (isUserDefined(tli->child(j)->text(0))) { + return true; + } + } + } + return false; } ////////////////////////////// slots ////////////////////////////// void LatexCommandsDialog::slotEnableButtons() { - bool addState = false; - bool deleteState = false; - bool editState = false; - bool resetState = false; - - QTreeWidget *listview = (getListviewMode() == lvEnvMode) ? m_widget.environments : m_widget.commands; - resetState = (hasUserDefined(listview)); - - QTreeWidgetItem *item = (QTreeWidgetItem *)listview->currentItem(); - - if (item && item != m_lviAmsmath) - { - addState = isParentItem(item); - if (!addState && isUserDefined(item->text(0))) - { - deleteState = true; - editState = true; - } - } - - m_widget.addButton->setEnabled(addState); - m_widget.deleteButton->setEnabled(deleteState); - m_widget.editButton->setEnabled(editState); - m_buttonBox->button(QDialogButtonBox::RestoreDefaults)->setEnabled(resetState); + bool addState = false; + bool deleteState = false; + bool editState = false; + bool resetState = false; + + QTreeWidget *listview = (getListviewMode() == lvEnvMode) ? m_widget.environments : m_widget.commands; + resetState = (hasUserDefined(listview)); + + QTreeWidgetItem *item = (QTreeWidgetItem *)listview->currentItem(); + + if (item && item != m_lviAmsmath) + { + addState = isParentItem(item); + if (!addState && isUserDefined(item->text(0))) + { + deleteState = true; + editState = true; + } + } + + m_widget.addButton->setEnabled(addState); + m_widget.deleteButton->setEnabled(deleteState); + m_widget.editButton->setEnabled(editState); + m_buttonBox->button(QDialogButtonBox::RestoreDefaults)->setEnabled(resetState); } void LatexCommandsDialog::slotAddClicked() { - QTreeWidget *listview; - QString caption; - - if (getListviewMode() == lvEnvMode) { - listview = m_widget.environments; - caption = i18n("LaTeX Environments"); - } - else { - listview = m_widget.commands; - caption = i18n("LaTeX Commands"); - } - - QTreeWidgetItem *item = (QTreeWidgetItem *)listview->currentItem(); - if (item && isParentItem(item)) { - // get current command type - KileDocument::CmdAttribute type = getCommandMode(item); - if (type == KileDocument::CmdAttrNone) { - KILE_DEBUG_MAIN << "\tLatexCommandsDialog error: no item in slotAddClicked() (" << item->text(0) << ")" << endl; - return; - } - - // add a new environment or command - NewLatexCommand *dialog = new NewLatexCommand(this, caption, item->text(0), Q_NULLPTR, type, &m_dictCommands); - if (dialog->exec() == QDialog::Accepted) { - m_commandChanged = true; - - // insert new item with attributes - QString name; - KileDocument::LatexCmdAttributes attr; - dialog->getParameter(name, attr); - setEntry((QTreeWidgetItem *)item, name, attr); - // open this parent item - if (!item->isExpanded()) { - item->setExpanded(true); - } - slotEnableButtons(); - } - delete dialog; - } + QTreeWidget *listview; + QString caption; + + if (getListviewMode() == lvEnvMode) { + listview = m_widget.environments; + caption = i18n("LaTeX Environments"); + } + else { + listview = m_widget.commands; + caption = i18n("LaTeX Commands"); + } + + QTreeWidgetItem *item = (QTreeWidgetItem *)listview->currentItem(); + if (item && isParentItem(item)) { + // get current command type + KileDocument::CmdAttribute type = getCommandMode(item); + if (type == KileDocument::CmdAttrNone) { + KILE_DEBUG_MAIN << "\tLatexCommandsDialog error: no item in slotAddClicked() (" << item->text(0) << ")" << endl; + return; + } + + // add a new environment or command + NewLatexCommand *dialog = new NewLatexCommand(this, caption, item->text(0), Q_NULLPTR, type, &m_dictCommands); + if (dialog->exec() == QDialog::Accepted) { + m_commandChanged = true; + + // insert new item with attributes + QString name; + KileDocument::LatexCmdAttributes attr; + dialog->getParameter(name, attr); + setEntry((QTreeWidgetItem *)item, name, attr); + // open this parent item + if (!item->isExpanded()) { + item->setExpanded(true); + } + slotEnableButtons(); + } + delete dialog; + } } void LatexCommandsDialog::slotDeleteClicked() { - QTreeWidget *listview; - QString message; - - if (getListviewMode() == lvEnvMode) { - listview = m_widget.environments; - message = i18n("Do you want to delete this environment?"); - } - else { - listview = m_widget.commands; - message = i18n("Do you want to delete this command?"); - } - - QTreeWidgetItem *item = (QTreeWidgetItem *)listview->currentItem(); - if (item && !isParentItem(item)) { - if (KMessageBox::warningContinueCancel(this, message, i18n("Delete")) == KMessageBox::Continue) { - m_commandChanged = true; - - if (isUserDefined(item->text(0))) - m_dictCommands.remove(item->text(0)); - delete item; - slotEnableButtons(); - } - } + QTreeWidget *listview; + QString message; + + if (getListviewMode() == lvEnvMode) { + listview = m_widget.environments; + message = i18n("Do you want to delete this environment?"); + } + else { + listview = m_widget.commands; + message = i18n("Do you want to delete this command?"); + } + + QTreeWidgetItem *item = (QTreeWidgetItem *)listview->currentItem(); + if (item && !isParentItem(item)) { + if (KMessageBox::warningContinueCancel(this, message, i18n("Delete")) == KMessageBox::Continue) { + m_commandChanged = true; + + if (isUserDefined(item->text(0))) + m_dictCommands.remove(item->text(0)); + delete item; + slotEnableButtons(); + } + } } void LatexCommandsDialog::slotEditClicked() { - QTreeWidget *listview; - QString caption; - - if (getListviewMode() == lvEnvMode) - { - listview = m_widget.environments; - caption = i18n("LaTeX Environment"); - } - else - { - listview = m_widget.commands; - caption = i18n("LaTeX Commands"); - } - - QTreeWidgetItem *item = (QTreeWidgetItem *)listview->currentItem(); - if (item && !isParentItem(item)) { - QTreeWidgetItem *parentitem = (QTreeWidgetItem *)item->parent(); - if (parentitem) { - // get current command type - KileDocument::CmdAttribute type = getCommandMode(parentitem); - if (type == KileDocument::CmdAttrNone) { - KILE_DEBUG_MAIN << "\tLatexCommandsDialog error: no item in slotAddClicked() (" << item->text(0) << ")" << endl; - return; - } - - // edit a new environment or command - NewLatexCommand *dialog = new NewLatexCommand(this, caption, parentitem->text(0), item, type, &m_dictCommands); - if (dialog->exec() == QDialog::Accepted) { - m_commandChanged = true; - - // delete old item - delete item; - // insert new item with changed attributes - QString name; - KileDocument::LatexCmdAttributes attr; - dialog->getParameter(name, attr); - setEntry(parentitem, name, attr); - } - delete dialog; - } - } + QTreeWidget *listview; + QString caption; + + if (getListviewMode() == lvEnvMode) + { + listview = m_widget.environments; + caption = i18n("LaTeX Environment"); + } + else + { + listview = m_widget.commands; + caption = i18n("LaTeX Commands"); + } + + QTreeWidgetItem *item = (QTreeWidgetItem *)listview->currentItem(); + if (item && !isParentItem(item)) { + QTreeWidgetItem *parentitem = (QTreeWidgetItem *)item->parent(); + if (parentitem) { + // get current command type + KileDocument::CmdAttribute type = getCommandMode(parentitem); + if (type == KileDocument::CmdAttrNone) { + KILE_DEBUG_MAIN << "\tLatexCommandsDialog error: no item in slotAddClicked() (" << item->text(0) << ")" << endl; + return; + } + + // edit a new environment or command + NewLatexCommand *dialog = new NewLatexCommand(this, caption, parentitem->text(0), item, type, &m_dictCommands); + if (dialog->exec() == QDialog::Accepted) { + m_commandChanged = true; + + // delete old item + delete item; + // insert new item with changed attributes + QString name; + KileDocument::LatexCmdAttributes attr; + dialog->getParameter(name, attr); + setEntry(parentitem, name, attr); + } + delete dialog; + } + } } void LatexCommandsDialog::slotUserDefinedClicked() { - bool states[9]; + bool states[9]; - getListviewStates(states); - resetListviews(); - setListviewStates(states); + getListviewStates(states); + resetListviews(); + setListviewStates(states); } void LatexCommandsDialog::slotAccepted() { - // OK-Button clicked, we have to look for user-defined environments/commands - // save checkbox for user-defined commands - KileConfig::setShowUserCommands(m_widget.showOnlyUserDefined->isChecked()); + // OK-Button clicked, we have to look for user-defined environments/commands + // save checkbox for user-defined commands + KileConfig::setShowUserCommands(m_widget.showOnlyUserDefined->isChecked()); - // write config entries for environments and commands - writeConfig(m_widget.environments, m_commands->envGroupName(), true); - writeConfig(m_widget.commands, m_commands->cmdGroupName(), false); - m_config->sync(); + // write config entries for environments and commands + writeConfig(m_widget.environments, m_commands->envGroupName(), true); + writeConfig(m_widget.commands, m_commands->cmdGroupName(), false); + m_config->sync(); - // reset known LaTeX environments and commands - m_commands->resetCommands(); + // reset known LaTeX environments and commands + m_commands->resetCommands(); - // save if there is a change in user-defined commands and environments - KileConfig::setCompleteChangedCommands(m_commandChanged); + // save if there is a change in user-defined commands and environments + KileConfig::setCompleteChangedCommands(m_commandChanged); } void LatexCommandsDialog::slotSetDefaults() { - QString mode = (getListviewMode() == lvEnvMode) ? i18n("'environment'") : i18n("'command'"); - if (KMessageBox::warningContinueCancel(this, i18n("All your %1 settings will be overwritten with the default settings, are you sure you want to continue?", mode)) == KMessageBox::Continue) { - if (getListviewMode() == lvEnvMode) { - resetEnvironments(); - } - else { - resetCommands(); - } - slotEnableButtons(); - } + QString mode = (getListviewMode() == lvEnvMode) ? i18n("'environment'") : i18n("'command'"); + if (KMessageBox::warningContinueCancel(this, i18n("All your %1 settings will be overwritten with the default settings, are you sure you want to continue?", mode)) == KMessageBox::Continue) { + if (getListviewMode() == lvEnvMode) { + resetEnvironments(); + } + else { + resetCommands(); + } + slotEnableButtons(); + } } ////////////////////////////// read/write config ////////////////////////////// void LatexCommandsDialog::readConfig() { - // read checkbox for user-defined commands - m_widget.showOnlyUserDefined->setChecked(KileConfig::showUserCommands()); + // read checkbox for user-defined commands + m_widget.showOnlyUserDefined->setChecked(KileConfig::showUserCommands()); } void LatexCommandsDialog::writeConfig(QTreeWidget *listview, const QString &groupname, bool env) { - // first delete old entries - if (m_config->hasGroup(groupname)) { - m_config->deleteGroup(groupname); - } - - // prepare for new entries - KConfigGroup group = m_config->group(groupname); - - // now get all attributes - KileDocument::LatexCmdAttributes attr; - attr.standard = false; - - int nrOfdefinedCommands = 0; - - // scan the listview for non standard entries - for (int i = 0; i < listview->topLevelItemCount(); ++i) { - QTreeWidgetItem *cur = listview->topLevelItem(i); - // get the type of the parent entry - attr.type = getCommandMode(cur); - if (attr.type == KileDocument::CmdAttrNone) - { - KILE_DEBUG_MAIN << "\tLatexCommandsDialog error: no parent item (" << cur->text(0) << ")" << endl; - continue; - } - - // look for children - for (int j = 0; j < cur->childCount(); ++j) { - QTreeWidgetItem *curchild = cur->child(j); - QString key = curchild->text(0); - if (isUserDefined(key)) - { - getEntry(curchild, attr); - QString value = m_commands->configString(attr, env); - KILE_DEBUG_MAIN << "\tLatexCommandsDialog write config: " << key << " --> " << value << endl; - if (!value.isEmpty()) { - group.writeEntry("Command" + QString::number(nrOfdefinedCommands), key); - group.writeEntry("Parameters" + QString::number(nrOfdefinedCommands), value); - ++nrOfdefinedCommands; - } - } - } - } - if(nrOfdefinedCommands > 0) { - group.writeEntry("Number of Commands", nrOfdefinedCommands); - } + // first delete old entries + if (m_config->hasGroup(groupname)) { + m_config->deleteGroup(groupname); + } + + // prepare for new entries + KConfigGroup group = m_config->group(groupname); + + // now get all attributes + KileDocument::LatexCmdAttributes attr; + attr.standard = false; + + int nrOfdefinedCommands = 0; + + // scan the listview for non standard entries + for (int i = 0; i < listview->topLevelItemCount(); ++i) { + QTreeWidgetItem *cur = listview->topLevelItem(i); + // get the type of the parent entry + attr.type = getCommandMode(cur); + if (attr.type == KileDocument::CmdAttrNone) + { + KILE_DEBUG_MAIN << "\tLatexCommandsDialog error: no parent item (" << cur->text(0) << ")" << endl; + continue; + } + + // look for children + for (int j = 0; j < cur->childCount(); ++j) { + QTreeWidgetItem *curchild = cur->child(j); + QString key = curchild->text(0); + if (isUserDefined(key)) + { + getEntry(curchild, attr); + QString value = m_commands->configString(attr, env); + KILE_DEBUG_MAIN << "\tLatexCommandsDialog write config: " << key << " --> " << value << endl; + if (!value.isEmpty()) { + group.writeEntry("Command" + QString::number(nrOfdefinedCommands), key); + group.writeEntry("Parameters" + QString::number(nrOfdefinedCommands), value); + ++nrOfdefinedCommands; + } + } + } + } + if(nrOfdefinedCommands > 0) { + group.writeEntry("Number of Commands", nrOfdefinedCommands); + } } ////////////////////////////// reset environments and commands ////////////////////////////// // delete all user-defined environments void LatexCommandsDialog::resetEnvironments() { - // remember current states - bool states[9]; - getListviewStates(states); - - // delete user-defined commands and re-read the list - if (m_config->hasGroup(m_commands->envGroupName())) - m_config->deleteGroup(m_commands->envGroupName()); - m_commands->resetCommands(); - - // reset Listview and set old states again (if possible) - resetListviews(); - setListviewStates(states); + // remember current states + bool states[9]; + getListviewStates(states); + + // delete user-defined commands and re-read the list + if (m_config->hasGroup(m_commands->envGroupName())) + m_config->deleteGroup(m_commands->envGroupName()); + m_commands->resetCommands(); + + // reset Listview and set old states again (if possible) + resetListviews(); + setListviewStates(states); } // delete all user-defined commands void LatexCommandsDialog::resetCommands() { - // remember current states - bool states[9]; - getListviewStates(states); - - // delete user-defined commands and re-read the list - if (m_config->hasGroup(m_commands->cmdGroupName())) - m_config->deleteGroup(m_commands->cmdGroupName()); - m_commands->resetCommands(); - - // reset Listview and set old states again (if possible) - resetListviews(); - setListviewStates(states); + // remember current states + bool states[9]; + getListviewStates(states); + + // delete user-defined commands and re-read the list + if (m_config->hasGroup(m_commands->cmdGroupName())) + m_config->deleteGroup(m_commands->cmdGroupName()); + m_commands->resetCommands(); + + // reset Listview and set old states again (if possible) + resetListviews(); + setListviewStates(states); } // states of all parent items void LatexCommandsDialog::getListviewStates(bool states[]) { - states[0] = m_lviAmsmath->isExpanded(); - states[1] = m_lviMath->isExpanded(); - states[2] = m_lviList->isExpanded(); - states[3] = m_lviTabular->isExpanded(); - states[4] = m_lviVerbatim->isExpanded(); - - states[5] = m_lviLabels->isExpanded(); - states[6] = m_lviReferences->isExpanded(); - states[7] = m_lviCitations->isExpanded(); - states[8] = m_lviInputs->isExpanded(); + states[0] = m_lviAmsmath->isExpanded(); + states[1] = m_lviMath->isExpanded(); + states[2] = m_lviList->isExpanded(); + states[3] = m_lviTabular->isExpanded(); + states[4] = m_lviVerbatim->isExpanded(); + + states[5] = m_lviLabels->isExpanded(); + states[6] = m_lviReferences->isExpanded(); + states[7] = m_lviCitations->isExpanded(); + states[8] = m_lviInputs->isExpanded(); } void LatexCommandsDialog::setListviewStates(bool states[]) { - m_lviAmsmath->setExpanded(states[0]); - m_lviMath->setExpanded(states[1]); - m_lviList->setExpanded(states[2]); - m_lviTabular->setExpanded(states[3]); - m_lviVerbatim->setExpanded(states[4]); - - m_lviLabels->setExpanded(states[5]); - m_lviReferences->setExpanded(states[6]); - m_lviCitations->setExpanded(states[7]); - m_lviInputs->setExpanded(states[8]); + m_lviAmsmath->setExpanded(states[0]); + m_lviMath->setExpanded(states[1]); + m_lviList->setExpanded(states[2]); + m_lviTabular->setExpanded(states[3]); + m_lviVerbatim->setExpanded(states[4]); + + m_lviLabels->setExpanded(states[5]); + m_lviReferences->setExpanded(states[6]); + m_lviCitations->setExpanded(states[7]); + m_lviInputs->setExpanded(states[8]); } //END LatexCommandsDialog } diff --git a/src/dialogs/latexcommanddialog.h b/src/dialogs/latexcommanddialog.h index 30ec8a20..5eac51a3 100644 --- a/src/dialogs/latexcommanddialog.h +++ b/src/dialogs/latexcommanddialog.h @@ -1,128 +1,128 @@ /*************************************************************************** latexcmddialog.h -------------- date : Jul 25 2005 version : 0.20 copyright : (C) 2005 by Holger Danielsson email : holger.danielsson@t-online.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. * * * ***************************************************************************/ #ifndef LATEXCOMMANDDIALOG_H #define LATEXCOMMANDDIALOG_H #include #include #include "latexcmd.h" #include "ui_latexcommanddialog_base.h" class KComboBox; class KConfig; class QCheckBox; class QDialogButtonBox; class QLabel; class QLineEdit; class QTabWidget; class QTreeWidget; class QTreeWidgetItem; namespace KileDialog { class NewLatexCommand : public QDialog { - Q_OBJECT - - public: - NewLatexCommand(QWidget *parent, const QString &caption, - const QString &groupname, QTreeWidgetItem *lvitem, - KileDocument::CmdAttribute cmdtype, QMap *dict); - ~NewLatexCommand() {} - void getParameter(QString &name, KileDocument::LatexCmdAttributes &attr); - - private: - QLineEdit *m_edName; - QCheckBox *m_chStarred, *m_chEndofline, *m_chMath; - KComboBox *m_coTab, *m_coOption, *m_coParameter; - - bool m_addmode, m_envmode; - bool m_useMathOrTab, m_useOption, m_useParameter; - KileDocument::CmdAttribute m_cmdType; - QMap *m_dict; - - private Q_SLOTS: - virtual void slotAccepted(); + Q_OBJECT + +public: + NewLatexCommand(QWidget *parent, const QString &caption, + const QString &groupname, QTreeWidgetItem *lvitem, + KileDocument::CmdAttribute cmdtype, QMap *dict); + ~NewLatexCommand() {} + void getParameter(QString &name, KileDocument::LatexCmdAttributes &attr); + +private: + QLineEdit *m_edName; + QCheckBox *m_chStarred, *m_chEndofline, *m_chMath; + KComboBox *m_coTab, *m_coOption, *m_coParameter; + + bool m_addmode, m_envmode; + bool m_useMathOrTab, m_useOption, m_useParameter; + KileDocument::CmdAttribute m_cmdType; + QMap *m_dict; + +private Q_SLOTS: + virtual void slotAccepted(); }; class LatexCommandsDialog : public QDialog { - Q_OBJECT - - public: - LatexCommandsDialog(KConfig *config, KileDocument::LatexCommands *commands, QWidget *parent = 0); - ~LatexCommandsDialog() {} - - //enum EnvParameter { envName,envStarred,envEOL,envMath,envTab,envOption }; - - private: - enum LVmode { lvEnvMode = 1, lvCmdMode = 2 }; - - KConfig *m_config; - KileDocument::LatexCommands *m_commands; - QMap m_dictCommands; - bool m_commandChanged; - - //QTreeWidget *m_lvEnvironments, *m_lvCommands; - QTreeWidgetItem *m_lviList, *m_lviTabular, *m_lviMath, *m_lviAmsmath, *m_lviVerbatim; - QTreeWidgetItem *m_lviLabels, *m_lviReferences, *m_lviBibliographies, *m_lviCitations; - QTreeWidgetItem *m_lviInputs; - /*QTabWidget *m_tab; - QPushButton *m_btnAdd, *m_btnDelete, *m_btnEdit; - QCheckBox *m_cbUserDefined;*/ - QDialogButtonBox *m_buttonBox; - Ui::LatexCommandWidget m_widget; - - void resetListviews(); - LVmode getListviewMode(); - KileDocument::CmdAttribute getCommandMode(QTreeWidgetItem *item); - bool isParentItem(QTreeWidgetItem *item); - - void setEntry(QTreeWidgetItem *parent, const QString &name, KileDocument::LatexCmdAttributes &attr); - void getEntry(QTreeWidgetItem *item, KileDocument::LatexCmdAttributes &attr); - - bool isUserDefined(const QString &name); - bool hasUserDefined(QTreeWidget *listview); - - void resetEnvironments(); - void resetCommands(); - void getListviewStates(bool states[]); - void setListviewStates(bool states[]); - - void readConfig(); - void writeConfig(QTreeWidget *listview, const QString &groupname, bool env); - - private Q_SLOTS: - void slotEnableButtons(); - void slotAddClicked(); - void slotDeleteClicked(); - void slotEditClicked(); - void slotUserDefinedClicked(); - void slotAccepted(); - void slotSetDefaults(); + Q_OBJECT + +public: + LatexCommandsDialog(KConfig *config, KileDocument::LatexCommands *commands, QWidget *parent = 0); + ~LatexCommandsDialog() {} + + //enum EnvParameter { envName,envStarred,envEOL,envMath,envTab,envOption }; + +private: + enum LVmode { lvEnvMode = 1, lvCmdMode = 2 }; + + KConfig *m_config; + KileDocument::LatexCommands *m_commands; + QMap m_dictCommands; + bool m_commandChanged; + + //QTreeWidget *m_lvEnvironments, *m_lvCommands; + QTreeWidgetItem *m_lviList, *m_lviTabular, *m_lviMath, *m_lviAmsmath, *m_lviVerbatim; + QTreeWidgetItem *m_lviLabels, *m_lviReferences, *m_lviBibliographies, *m_lviCitations; + QTreeWidgetItem *m_lviInputs; + /*QTabWidget *m_tab; + QPushButton *m_btnAdd, *m_btnDelete, *m_btnEdit; + QCheckBox *m_cbUserDefined;*/ + QDialogButtonBox *m_buttonBox; + Ui::LatexCommandWidget m_widget; + + void resetListviews(); + LVmode getListviewMode(); + KileDocument::CmdAttribute getCommandMode(QTreeWidgetItem *item); + bool isParentItem(QTreeWidgetItem *item); + + void setEntry(QTreeWidgetItem *parent, const QString &name, KileDocument::LatexCmdAttributes &attr); + void getEntry(QTreeWidgetItem *item, KileDocument::LatexCmdAttributes &attr); + + bool isUserDefined(const QString &name); + bool hasUserDefined(QTreeWidget *listview); + + void resetEnvironments(); + void resetCommands(); + void getListviewStates(bool states[]); + void setListviewStates(bool states[]); + + void readConfig(); + void writeConfig(QTreeWidget *listview, const QString &groupname, bool env); + +private Q_SLOTS: + void slotEnableButtons(); + void slotAddClicked(); + void slotDeleteClicked(); + void slotEditClicked(); + void slotUserDefinedClicked(); + void slotAccepted(); + void slotSetDefaults(); }; } #endif diff --git a/src/dialogs/listselector.cpp b/src/dialogs/listselector.cpp index fcf07e47..0be85afc 100644 --- a/src/dialogs/listselector.cpp +++ b/src/dialogs/listselector.cpp @@ -1,302 +1,302 @@ /****************************************************************************************** begin : Fri Aug 15 2003 copyright : (C) 2003 by Jeroen Wijnhout (Jeroen.Wijnhout@kdemail.net) (C) 2007 by Holger Danielsson (holger.danielsson@versanet.de) (C) 2011 by Libor Bukata (lbukata@gmail.com) (C) 2013 by Michel Ludwig (michel.ludwig@kdemail.net) ******************************************************************************************/ /*************************************************************************** * * * 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. * * * ***************************************************************************/ #include "listselector.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "kiledebug.h" #include "codecompletion.h" //////////////////// KileListSelector //////////////////// KileListSelector::KileListSelector(const QStringList &list, const QString &caption, const QString &select, bool sort, - QWidget *parent, const char *name) - : QDialog(parent) - , m_listView(new QTreeWidget(this)) - , m_buttonBox(new QDialogButtonBox(QDialogButtonBox::Ok|QDialogButtonBox::Cancel)) + QWidget *parent, const char *name) + : QDialog(parent) + , m_listView(new QTreeWidget(this)) + , m_buttonBox(new QDialogButtonBox(QDialogButtonBox::Ok|QDialogButtonBox::Cancel)) { - setObjectName(name); - setWindowTitle(caption); - setModal(true); - QVBoxLayout *mainLayout = new QVBoxLayout; - setLayout(mainLayout); - mainLayout->addWidget(new QLabel(select, this)); - - m_listView->setHeaderLabel(i18n("Files")); - m_listView->setSortingEnabled(false); - m_listView->setAllColumnsShowFocus(true); - m_listView->setRootIsDecorated(false); - mainLayout->addWidget(m_listView); - mainLayout->addWidget(new QLabel(i18np("1 item found.", "%1 items found.", list.size()))); - - m_listView->setSortingEnabled(sort); - m_listView->setSelectionMode(QAbstractItemView::SingleSelection); - if (sort) { - m_listView->sortByColumn(0, Qt::AscendingOrder); - } - - insertStringList(list); - - m_listView->clearSelection(); - connect(m_listView, &QTreeWidget::itemDoubleClicked, this, &QDialog::accept); - QItemSelectionModel *selectionModel = m_listView->selectionModel(); - if (selectionModel) { // checking just to be safe - connect(selectionModel, &QItemSelectionModel::selectionChanged, - this, &KileListSelector::handleSelectionChanged); - } - - QPushButton *okButton = m_buttonBox->button(QDialogButtonBox::Ok); - okButton->setDefault(true); - okButton->setShortcut(Qt::CTRL | Qt::Key_Return); - okButton->setEnabled(false); - connect(m_buttonBox, &QDialogButtonBox::accepted, this, &QDialog::accept); - connect(m_buttonBox, &QDialogButtonBox::rejected, this, &QDialog::reject); - mainLayout->addWidget(m_buttonBox); + setObjectName(name); + setWindowTitle(caption); + setModal(true); + QVBoxLayout *mainLayout = new QVBoxLayout; + setLayout(mainLayout); + mainLayout->addWidget(new QLabel(select, this)); + + m_listView->setHeaderLabel(i18n("Files")); + m_listView->setSortingEnabled(false); + m_listView->setAllColumnsShowFocus(true); + m_listView->setRootIsDecorated(false); + mainLayout->addWidget(m_listView); + mainLayout->addWidget(new QLabel(i18np("1 item found.", "%1 items found.", list.size()))); + + m_listView->setSortingEnabled(sort); + m_listView->setSelectionMode(QAbstractItemView::SingleSelection); + if (sort) { + m_listView->sortByColumn(0, Qt::AscendingOrder); + } + + insertStringList(list); + + m_listView->clearSelection(); + connect(m_listView, &QTreeWidget::itemDoubleClicked, this, &QDialog::accept); + QItemSelectionModel *selectionModel = m_listView->selectionModel(); + if (selectionModel) { // checking just to be safe + connect(selectionModel, &QItemSelectionModel::selectionChanged, + this, &KileListSelector::handleSelectionChanged); + } + + QPushButton *okButton = m_buttonBox->button(QDialogButtonBox::Ok); + okButton->setDefault(true); + okButton->setShortcut(Qt::CTRL | Qt::Key_Return); + okButton->setEnabled(false); + connect(m_buttonBox, &QDialogButtonBox::accepted, this, &QDialog::accept); + connect(m_buttonBox, &QDialogButtonBox::rejected, this, &QDialog::reject); + mainLayout->addWidget(m_buttonBox); } void KileListSelector::handleSelectionChanged(const QItemSelection& selected, const QItemSelection& deselected) { - Q_UNUSED(selected); - Q_UNUSED(deselected); - m_buttonBox->button(QDialogButtonBox::Ok)->setEnabled(hasSelection()); + Q_UNUSED(selected); + Q_UNUSED(deselected); + m_buttonBox->button(QDialogButtonBox::Ok)->setEnabled(hasSelection()); } bool KileListSelector::hasSelection() const { - if (!m_listView->selectionModel()) { - return false; - } - return m_listView->selectionModel()->hasSelection(); + if (!m_listView->selectionModel()) { + return false; + } + return m_listView->selectionModel()->hasSelection(); } void KileListSelector::setSelectionMode(QAbstractItemView::SelectionMode mode) { - m_listView->setSelectionMode(mode); + m_listView->setSelectionMode(mode); } void KileListSelector::insertStringList(const QStringList &list) { - QStringList::ConstIterator it; - for (it = list.begin(); it != list.end(); ++it) { - QTreeWidgetItem *item = new QTreeWidgetItem(m_listView, QStringList(*it)); - - if (it == list.begin()) { - m_listView->setCurrentItem(item); - } - } + QStringList::ConstIterator it; + for (it = list.begin(); it != list.end(); ++it) { + QTreeWidgetItem *item = new QTreeWidgetItem(m_listView, QStringList(*it)); + + if (it == list.begin()) { + m_listView->setCurrentItem(item); + } + } } QStringList KileListSelector::selectedItems() const { - QStringList items; - QTreeWidgetItemIterator it(m_listView, QTreeWidgetItemIterator::Selected); - while (*it) { - items.append((*it)->text(0)); - ++it; - } - return items; + QStringList items; + QTreeWidgetItemIterator it(m_listView, QTreeWidgetItemIterator::Selected); + while (*it) { + items.append((*it)->text(0)); + ++it; + } + return items; } //////////////////// ManageCompletionFilesDialog //////////////////// ManageCompletionFilesDialog::ManageCompletionFilesDialog(const QString& caption, - const QString &localCompletionDir, const QString &globalCompletionDir, QWidget* parent, const char* name) - : QDialog(parent) - , m_localCompletionDirectory(localCompletionDir) - , m_globalCompletionDirectory(globalCompletionDir) + const QString &localCompletionDir, const QString &globalCompletionDir, QWidget* parent, const char* name) + : QDialog(parent) + , m_localCompletionDirectory(localCompletionDir) + , m_globalCompletionDirectory(globalCompletionDir) { - setObjectName(name); - setWindowTitle(caption); - setModal(true); - QVBoxLayout *mainLayout = new QVBoxLayout; - setLayout(mainLayout); - - m_listView = new QTreeWidget(this); - m_listView->setHeaderLabels(QStringList() << i18n("File Name") << i18n("Local File") << i18n("Add File?")); - m_listView->setSortingEnabled(false); - m_listView->setSelectionMode(QAbstractItemView::NoSelection); - m_listView->setRootIsDecorated(false); - mainLayout->addWidget(m_listView); - - m_dirWatcher = new KDirWatch(this); - if (m_dirWatcher) { - m_dirWatcher->addDir(localCompletionDir, KDirWatch::WatchFiles); - connect(m_dirWatcher, &KDirWatch::created, this, &ManageCompletionFilesDialog::fillTreeView); - connect(m_dirWatcher, &KDirWatch::deleted, this, &ManageCompletionFilesDialog::fillTreeView); - } - fillTreeView(); - - QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok|QDialogButtonBox::Cancel); - QPushButton *okButton = buttonBox->button(QDialogButtonBox::Ok); - QPushButton *installCustomButton = new QPushButton; - QPushButton *manageCustomButton = new QPushButton; - okButton->setDefault(true); - okButton->setShortcut(Qt::CTRL | Qt::Key_Return); - okButton->setText(i18n("Add selected files")); - okButton->setToolTip(i18n("Add all the selected files")); - installCustomButton->setText(i18n("Install custom files")); - installCustomButton->setToolTip(i18n("Install your own completion files")); - manageCustomButton->setText(i18n("Manage custom files")); - manageCustomButton->setToolTip(i18n("Manage the local completion files in the file manager")); - buttonBox->addButton(installCustomButton, QDialogButtonBox::ActionRole); - buttonBox->addButton(manageCustomButton, QDialogButtonBox::ActionRole); - mainLayout->addWidget(buttonBox); - connect(buttonBox, &QDialogButtonBox::accepted, - this, &QDialog::accept); - connect(buttonBox, &QDialogButtonBox::rejected, - this, &QDialog::reject); - connect(installCustomButton, &QPushButton::clicked, - this, &ManageCompletionFilesDialog::addCustomCompletionFiles); - connect(manageCustomButton, &QPushButton::clicked, - this, &ManageCompletionFilesDialog::openLocalCompletionDirectoryInFileManager); - - // Create the local path if it doesn't exist - QDir localPath(m_localCompletionDirectory); - if(!localPath.exists()) { - localPath.mkpath(m_localCompletionDirectory); - } + setObjectName(name); + setWindowTitle(caption); + setModal(true); + QVBoxLayout *mainLayout = new QVBoxLayout; + setLayout(mainLayout); + + m_listView = new QTreeWidget(this); + m_listView->setHeaderLabels(QStringList() << i18n("File Name") << i18n("Local File") << i18n("Add File?")); + m_listView->setSortingEnabled(false); + m_listView->setSelectionMode(QAbstractItemView::NoSelection); + m_listView->setRootIsDecorated(false); + mainLayout->addWidget(m_listView); + + m_dirWatcher = new KDirWatch(this); + if (m_dirWatcher) { + m_dirWatcher->addDir(localCompletionDir, KDirWatch::WatchFiles); + connect(m_dirWatcher, &KDirWatch::created, this, &ManageCompletionFilesDialog::fillTreeView); + connect(m_dirWatcher, &KDirWatch::deleted, this, &ManageCompletionFilesDialog::fillTreeView); + } + fillTreeView(); + + QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok|QDialogButtonBox::Cancel); + QPushButton *okButton = buttonBox->button(QDialogButtonBox::Ok); + QPushButton *installCustomButton = new QPushButton; + QPushButton *manageCustomButton = new QPushButton; + okButton->setDefault(true); + okButton->setShortcut(Qt::CTRL | Qt::Key_Return); + okButton->setText(i18n("Add selected files")); + okButton->setToolTip(i18n("Add all the selected files")); + installCustomButton->setText(i18n("Install custom files")); + installCustomButton->setToolTip(i18n("Install your own completion files")); + manageCustomButton->setText(i18n("Manage custom files")); + manageCustomButton->setToolTip(i18n("Manage the local completion files in the file manager")); + buttonBox->addButton(installCustomButton, QDialogButtonBox::ActionRole); + buttonBox->addButton(manageCustomButton, QDialogButtonBox::ActionRole); + mainLayout->addWidget(buttonBox); + connect(buttonBox, &QDialogButtonBox::accepted, + this, &QDialog::accept); + connect(buttonBox, &QDialogButtonBox::rejected, + this, &QDialog::reject); + connect(installCustomButton, &QPushButton::clicked, + this, &ManageCompletionFilesDialog::addCustomCompletionFiles); + connect(manageCustomButton, &QPushButton::clicked, + this, &ManageCompletionFilesDialog::openLocalCompletionDirectoryInFileManager); + + // Create the local path if it doesn't exist + QDir localPath(m_localCompletionDirectory); + if(!localPath.exists()) { + localPath.mkpath(m_localCompletionDirectory); + } } ManageCompletionFilesDialog::~ManageCompletionFilesDialog() { } void ManageCompletionFilesDialog::fillTreeView() { - // we want to keep selected items still selected after refreshing - QSet previouslySelectedItems = selected(); - QStringList list = KileCodeCompletion::Manager::getAllCwlFiles(m_localCompletionDirectory, m_globalCompletionDirectory).uniqueKeys(); - std::sort(list.begin(), list.end()); - m_listView->clear(); - foreach(QString filename, list) { - QString expectedLocalPath = m_localCompletionDirectory + "/" + filename; - QString expectedGlobalPath = m_globalCompletionDirectory + "/" + filename; - if (QFileInfo(expectedLocalPath).exists() && QFileInfo(expectedLocalPath).isReadable()) { - QTreeWidgetItem* item = new QTreeWidgetItem(m_listView, QStringList() << filename << i18n("yes")); - item->setCheckState(2, previouslySelectedItems.contains(filename) ? Qt::Checked : Qt::Unchecked); - } - else if (QFileInfo(expectedGlobalPath).exists() && QFileInfo(expectedGlobalPath).isReadable()) { - QTreeWidgetItem* item = new QTreeWidgetItem(m_listView, QStringList() << filename << i18n("no")); - item->setCheckState(2, previouslySelectedItems.contains(filename) ? Qt::Checked : Qt::Unchecked); - } - else { - KILE_DEBUG_MAIN << "Cannot load file" << filename << "!"; - } - } - m_listView->resizeColumnToContents(0); - m_listView->resizeColumnToContents(1); - m_listView->resizeColumnToContents(2); + // we want to keep selected items still selected after refreshing + QSet previouslySelectedItems = selected(); + QStringList list = KileCodeCompletion::Manager::getAllCwlFiles(m_localCompletionDirectory, m_globalCompletionDirectory).uniqueKeys(); + std::sort(list.begin(), list.end()); + m_listView->clear(); + foreach(QString filename, list) { + QString expectedLocalPath = m_localCompletionDirectory + "/" + filename; + QString expectedGlobalPath = m_globalCompletionDirectory + "/" + filename; + if (QFileInfo(expectedLocalPath).exists() && QFileInfo(expectedLocalPath).isReadable()) { + QTreeWidgetItem* item = new QTreeWidgetItem(m_listView, QStringList() << filename << i18n("yes")); + item->setCheckState(2, previouslySelectedItems.contains(filename) ? Qt::Checked : Qt::Unchecked); + } + else if (QFileInfo(expectedGlobalPath).exists() && QFileInfo(expectedGlobalPath).isReadable()) { + QTreeWidgetItem* item = new QTreeWidgetItem(m_listView, QStringList() << filename << i18n("no")); + item->setCheckState(2, previouslySelectedItems.contains(filename) ? Qt::Checked : Qt::Unchecked); + } + else { + KILE_DEBUG_MAIN << "Cannot load file" << filename << "!"; + } + } + m_listView->resizeColumnToContents(0); + m_listView->resizeColumnToContents(1); + m_listView->resizeColumnToContents(2); } void ManageCompletionFilesDialog::addCustomCompletionFiles() { - bool someFileAdded = false; - QStringList files = QFileDialog::getOpenFileNames( - this, i18n("Select Completion Files to Install Locally"), QString(), i18n("Completion files (*.cwl)")); - - if (files.isEmpty()) { - return; - } - QDir workPath(m_localCompletionDirectory); - - foreach (QString file, files) { - QFileInfo fileInf(file); - QFileInfo localFile(m_localCompletionDirectory + "/" + fileInf.fileName()); - if (localFile.exists()) { - const QString dialog_text = i18n("A local completion file with the name \"%1\" already exists.\nDo you want to replace this file?").arg(localFile.fileName()); - const QString dialog_caption = i18n("Replace Local File?"); - if (KMessageBox::questionYesNo(this, dialog_text, dialog_caption) == KMessageBox::Yes) { - if (!QFile::remove(localFile.absoluteFilePath())) { - KMessageBox::error(this, i18n("An error occurred while removing the file \"%1\".\nPlease check the file permissions.") - .arg(localFile.fileName()), i18n("Remove Error")); - continue; - } - } - else { - // Skip selected file. - continue; - } - } - // Copy selected file to local directory. - if (!QFile::copy(fileInf.absoluteFilePath(),localFile.absoluteFilePath())) { - KMessageBox::error(this, i18n("Cannot copy the file to the local directory!\nPlease check the access permissions of the directory \"%1\".") - .arg(localFile.absolutePath()), i18n("Copy Error")); - } - else { - // Add file to QTreeWidget or change status to local if a global file with the same name exists. - QList foundItems = m_listView->findItems(fileInf.fileName(), Qt::MatchExactly, 0); - if (foundItems.empty()) { - QTreeWidgetItem *item = new QTreeWidgetItem(m_listView, QStringList() << localFile.fileName() << i18n("yes")); - item->setCheckState(2, Qt::Checked); - } - else { - foundItems.first()->setCheckState(2, Qt::Checked); - foundItems.first()->setText(1, i18n("yes")); - } - someFileAdded = true; - } - } - - // Resort QTreeWidget list. - m_listView->sortItems(0, Qt::AscendingOrder); - - // Info about preselected files. - if (someFileAdded == true) { - KMessageBox::information(this, - i18n("The custom files have been installed and preselected for adding."), - i18n("Installation Successful")); - } + bool someFileAdded = false; + QStringList files = QFileDialog::getOpenFileNames( + this, i18n("Select Completion Files to Install Locally"), QString(), i18n("Completion files (*.cwl)")); + + if (files.isEmpty()) { + return; + } + QDir workPath(m_localCompletionDirectory); + + foreach (QString file, files) { + QFileInfo fileInf(file); + QFileInfo localFile(m_localCompletionDirectory + "/" + fileInf.fileName()); + if (localFile.exists()) { + const QString dialog_text = i18n("A local completion file with the name \"%1\" already exists.\nDo you want to replace this file?").arg(localFile.fileName()); + const QString dialog_caption = i18n("Replace Local File?"); + if (KMessageBox::questionYesNo(this, dialog_text, dialog_caption) == KMessageBox::Yes) { + if (!QFile::remove(localFile.absoluteFilePath())) { + KMessageBox::error(this, i18n("An error occurred while removing the file \"%1\".\nPlease check the file permissions.") + .arg(localFile.fileName()), i18n("Remove Error")); + continue; + } + } + else { + // Skip selected file. + continue; + } + } + // Copy selected file to local directory. + if (!QFile::copy(fileInf.absoluteFilePath(),localFile.absoluteFilePath())) { + KMessageBox::error(this, i18n("Cannot copy the file to the local directory!\nPlease check the access permissions of the directory \"%1\".") + .arg(localFile.absolutePath()), i18n("Copy Error")); + } + else { + // Add file to QTreeWidget or change status to local if a global file with the same name exists. + QList foundItems = m_listView->findItems(fileInf.fileName(), Qt::MatchExactly, 0); + if (foundItems.empty()) { + QTreeWidgetItem *item = new QTreeWidgetItem(m_listView, QStringList() << localFile.fileName() << i18n("yes")); + item->setCheckState(2, Qt::Checked); + } + else { + foundItems.first()->setCheckState(2, Qt::Checked); + foundItems.first()->setText(1, i18n("yes")); + } + someFileAdded = true; + } + } + + // Resort QTreeWidget list. + m_listView->sortItems(0, Qt::AscendingOrder); + + // Info about preselected files. + if (someFileAdded == true) { + KMessageBox::information(this, + i18n("The custom files have been installed and preselected for adding."), + i18n("Installation Successful")); + } } void ManageCompletionFilesDialog::openLocalCompletionDirectoryInFileManager() { - new KRun(QUrl::fromLocalFile(m_localCompletionDirectory), QApplication::activeWindow()); + new KRun(QUrl::fromLocalFile(m_localCompletionDirectory), QApplication::activeWindow()); } const QSet ManageCompletionFilesDialog::selected() const { - QSet checked_files; - for (int i = 0; i < m_listView->topLevelItemCount(); ++i) { - QTreeWidgetItem* item = m_listView->topLevelItem(i); - if (item->checkState(2) == Qt::Checked) { - checked_files.insert(item->text(0)); - } - } - - return checked_files; + QSet checked_files; + for (int i = 0; i < m_listView->topLevelItemCount(); ++i) { + QTreeWidgetItem* item = m_listView->topLevelItem(i); + if (item->checkState(2) == Qt::Checked) { + checked_files.insert(item->text(0)); + } + } + + return checked_files; } diff --git a/src/dialogs/listselector.h b/src/dialogs/listselector.h index 3af33a2b..c643bdaa 100644 --- a/src/dialogs/listselector.h +++ b/src/dialogs/listselector.h @@ -1,75 +1,75 @@ /***************************************************************************************** begin : Fri Aug 15 2003 copyright : (C) 2003 by Jeroen Wijnhout (Jeroen.Wijnhout@kdemail.net) (C) 2007 by Holger Danielsson (holger.danielsson@versanet.de) (C) 2011 by Libor Bukata (lbukata@gmail.com) (C) 2013 by Michel Ludwig (michel.ludwig@kdemail.net) *****************************************************************************************/ /*************************************************************************** * * * 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. * * * ***************************************************************************/ #ifndef LISTSELECTOR_H #define LISTSELECTOR_H #include #include #include #include class QDialogButtonBox; class QTreeWidget; class QStringList; class KDirWatch; class KileListSelector : public QDialog { - Q_OBJECT + Q_OBJECT public: - KileListSelector(const QStringList &list, const QString &caption, const QString &select, bool sort = true, - QWidget *parent = Q_NULLPTR, const char *name = Q_NULLPTR); + KileListSelector(const QStringList &list, const QString &caption, const QString &select, bool sort = true, + QWidget *parent = Q_NULLPTR, const char *name = Q_NULLPTR); - bool hasSelection() const; - void setSelectionMode(QAbstractItemView::SelectionMode mode); - QStringList selectedItems() const; + bool hasSelection() const; + void setSelectionMode(QAbstractItemView::SelectionMode mode); + QStringList selectedItems() const; protected Q_SLOTS: - void handleSelectionChanged(const QItemSelection& selected, const QItemSelection& deselected); + void handleSelectionChanged(const QItemSelection& selected, const QItemSelection& deselected); protected: - QTreeWidget *m_listView; - QDialogButtonBox *m_buttonBox; - void insertStringList(const QStringList &list); + QTreeWidget *m_listView; + QDialogButtonBox *m_buttonBox; + void insertStringList(const QStringList &list); }; class ManageCompletionFilesDialog : public QDialog { - Q_OBJECT; + Q_OBJECT; public: - ManageCompletionFilesDialog(const QString &caption, - const QString &localCompletionDir, const QString &globalCompletionDir, - QWidget* parent = Q_NULLPTR, const char *name = Q_NULLPTR); - ~ManageCompletionFilesDialog(); + ManageCompletionFilesDialog(const QString &caption, + const QString &localCompletionDir, const QString &globalCompletionDir, + QWidget* parent = Q_NULLPTR, const char *name = Q_NULLPTR); + ~ManageCompletionFilesDialog(); - const QSet selected() const; + const QSet selected() const; protected Q_SLOTS: - void addCustomCompletionFiles(); - void openLocalCompletionDirectoryInFileManager(); - void fillTreeView(); + void addCustomCompletionFiles(); + void openLocalCompletionDirectoryInFileManager(); + void fillTreeView(); private: - KDirWatch *m_dirWatcher; - QTreeWidget *m_listView; - QString m_localCompletionDirectory, m_globalCompletionDirectory; + KDirWatch *m_dirWatcher; + QTreeWidget *m_listView; + QString m_localCompletionDirectory, m_globalCompletionDirectory; }; #endif diff --git a/src/dialogs/managetemplatesdialog.cpp b/src/dialogs/managetemplatesdialog.cpp index 8959148c..42cd8f0d 100644 --- a/src/dialogs/managetemplatesdialog.cpp +++ b/src/dialogs/managetemplatesdialog.cpp @@ -1,341 +1,341 @@ /***************************************************************************************** begin : Sun Apr 27 2003 copyright : (C) 2003 by Jeroen Wijnhout (wijnhout@science.uva.nl) 2007 by Michel Ludwig (michel.ludwig@kdemail.net) *****************************************************************************************/ /*************************************************************************** * * * 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. * * * ***************************************************************************/ #include "dialogs/managetemplatesdialog.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "kiledebug.h" #include "kileextensions.h" #include "kileinfo.h" #include "templates.h" class TemplateListViewItem : public QTreeWidgetItem { - public: - TemplateListViewItem(QTreeWidget* parent, QTreeWidgetItem* preceding, const QString& mode, const KileTemplate::Info& info) : QTreeWidgetItem(parent, preceding), m_info(info) { - setText(0, mode); - setText(1, info.name); - setText(2, KileInfo::documentTypeToString(info.type)); - } - - virtual ~TemplateListViewItem() { - } - - KileTemplate::Info getTemplateInfo() { - return m_info; - } - - protected: - KileTemplate::Info m_info; +public: + TemplateListViewItem(QTreeWidget* parent, QTreeWidgetItem* preceding, const QString& mode, const KileTemplate::Info& info) : QTreeWidgetItem(parent, preceding), m_info(info) { + setText(0, mode); + setText(1, info.name); + setText(2, KileInfo::documentTypeToString(info.type)); + } + + virtual ~TemplateListViewItem() { + } + + KileTemplate::Info getTemplateInfo() { + return m_info; + } + +protected: + KileTemplate::Info m_info; }; // dialog to create a template ManageTemplatesDialog::ManageTemplatesDialog(KileTemplate::Manager *templateManager, const QUrl &sourceURL, const QString &caption, QWidget *parent, const char *name) - : QDialog(parent) - , m_templateManager(templateManager) - , m_sourceURL(sourceURL) + : QDialog(parent) + , m_templateManager(templateManager) + , m_sourceURL(sourceURL) { - setObjectName(name); - setWindowTitle(caption); - setModal(true); - QVBoxLayout *mainLayout = new QVBoxLayout; - setLayout(mainLayout); - - m_templateType = KileDocument::Extensions().determineDocumentType(sourceURL); - - QWidget *page = new QWidget(this); - page->setObjectName("managetemplates_mainwidget"); - mainLayout->addWidget(page); - QGridLayout *topLayout = new QGridLayout(); - topLayout->setMargin(0); - page->setLayout(topLayout); - - topLayout->addWidget(new QLabel(i18n("Name:"), page), 0, 0); - - QString fileName = m_sourceURL.fileName(); - //remove the extension - int dotPos = fileName.lastIndexOf('.'); - if (dotPos >= 0) { - fileName = fileName.mid(0, dotPos); - } - m_nameEdit = new QLineEdit(fileName, page); - mainLayout->addWidget(m_nameEdit); - topLayout->addWidget(m_nameEdit, 0, 1); - - topLayout->addWidget(new QLabel(i18n("Type: %1", KileInfo::documentTypeToString(m_templateType)), page), 0, 2); - topLayout->addWidget(new QLabel(i18n("Icon:"), page), 1, 0); - - m_iconEdit = new QLineEdit(QStandardPaths::locate(QStandardPaths::DataLocation, "pics/type_Default.png"), page); - mainLayout->addWidget(m_iconEdit); - topLayout->addWidget(m_iconEdit, 1, 1); - - QPushButton *iconbut = new QPushButton(i18n("Select..."), page); - mainLayout->addWidget(iconbut); - topLayout->addWidget(iconbut, 1, 2); - - m_templateList = new QTreeWidget(page); - mainLayout->addWidget(m_templateList); - m_templateList->setSortingEnabled(false); - m_templateList->setHeaderLabels(QStringList() << i18nc("marked", "M") - << i18n("Existing Templates") - << i18n("Document Type")); - m_templateList->setAllColumnsShowFocus(true); - m_templateList->setRootIsDecorated(false); - - populateTemplateListView(m_templateType); - - topLayout->addWidget(m_templateList, 2, 0, 1, 3); - - m_showAllTypesCheckBox = new QCheckBox(i18n("Show all the templates"), page); - mainLayout->addWidget(m_showAllTypesCheckBox); - m_showAllTypesCheckBox->setChecked(false); - connect(m_showAllTypesCheckBox, &QCheckBox::toggled, this, &ManageTemplatesDialog::updateTemplateListView); - topLayout->addWidget(m_showAllTypesCheckBox, 3, 0, 1, 2); - - QPushButton *clearSelectionButton = new QPushButton(page); - mainLayout->addWidget(clearSelectionButton); - clearSelectionButton->setIcon(QIcon::fromTheme("edit-clear-locationbar")); - int buttonSize = clearSelectionButton->sizeHint().height(); - clearSelectionButton->setFixedSize(buttonSize, buttonSize); - clearSelectionButton->setToolTip(i18n("Clear Selection")); - connect(clearSelectionButton, &QPushButton::clicked, this, &ManageTemplatesDialog::clearSelection); - topLayout->addWidget(clearSelectionButton, 3, 2, Qt::AlignRight); - - topLayout->addWidget(new QLabel(i18n("Select an existing template if you want to overwrite it with your new template.\nNote that you cannot overwrite templates marked with an asterisk:\nif you do select such a template, a new template with the same name\nwill be created in a location you have write access to."), page), 4, 0, 1, 3); - - QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok|QDialogButtonBox::Cancel); - QPushButton *okButton = buttonBox->button(QDialogButtonBox::Ok); - okButton->setDefault(true); - okButton->setShortcut(Qt::CTRL | Qt::Key_Return); - mainLayout->addWidget(buttonBox); - connect(buttonBox, &QDialogButtonBox::accepted, this, &QDialog::accept); - connect(buttonBox, &QDialogButtonBox::rejected, this, &QDialog::reject); - - connect(m_templateList, &QTreeWidget::itemClicked, this, &ManageTemplatesDialog::slotSelectedTemplate); - connect(iconbut, &QPushButton::clicked, this, &ManageTemplatesDialog::slotSelectIcon); - connect(this, &QDialog::accepted, this, &ManageTemplatesDialog::addTemplate); + setObjectName(name); + setWindowTitle(caption); + setModal(true); + QVBoxLayout *mainLayout = new QVBoxLayout; + setLayout(mainLayout); + + m_templateType = KileDocument::Extensions().determineDocumentType(sourceURL); + + QWidget *page = new QWidget(this); + page->setObjectName("managetemplates_mainwidget"); + mainLayout->addWidget(page); + QGridLayout *topLayout = new QGridLayout(); + topLayout->setMargin(0); + page->setLayout(topLayout); + + topLayout->addWidget(new QLabel(i18n("Name:"), page), 0, 0); + + QString fileName = m_sourceURL.fileName(); + //remove the extension + int dotPos = fileName.lastIndexOf('.'); + if (dotPos >= 0) { + fileName = fileName.mid(0, dotPos); + } + m_nameEdit = new QLineEdit(fileName, page); + mainLayout->addWidget(m_nameEdit); + topLayout->addWidget(m_nameEdit, 0, 1); + + topLayout->addWidget(new QLabel(i18n("Type: %1", KileInfo::documentTypeToString(m_templateType)), page), 0, 2); + topLayout->addWidget(new QLabel(i18n("Icon:"), page), 1, 0); + + m_iconEdit = new QLineEdit(QStandardPaths::locate(QStandardPaths::DataLocation, "pics/type_Default.png"), page); + mainLayout->addWidget(m_iconEdit); + topLayout->addWidget(m_iconEdit, 1, 1); + + QPushButton *iconbut = new QPushButton(i18n("Select..."), page); + mainLayout->addWidget(iconbut); + topLayout->addWidget(iconbut, 1, 2); + + m_templateList = new QTreeWidget(page); + mainLayout->addWidget(m_templateList); + m_templateList->setSortingEnabled(false); + m_templateList->setHeaderLabels(QStringList() << i18nc("marked", "M") + << i18n("Existing Templates") + << i18n("Document Type")); + m_templateList->setAllColumnsShowFocus(true); + m_templateList->setRootIsDecorated(false); + + populateTemplateListView(m_templateType); + + topLayout->addWidget(m_templateList, 2, 0, 1, 3); + + m_showAllTypesCheckBox = new QCheckBox(i18n("Show all the templates"), page); + mainLayout->addWidget(m_showAllTypesCheckBox); + m_showAllTypesCheckBox->setChecked(false); + connect(m_showAllTypesCheckBox, &QCheckBox::toggled, this, &ManageTemplatesDialog::updateTemplateListView); + topLayout->addWidget(m_showAllTypesCheckBox, 3, 0, 1, 2); + + QPushButton *clearSelectionButton = new QPushButton(page); + mainLayout->addWidget(clearSelectionButton); + clearSelectionButton->setIcon(QIcon::fromTheme("edit-clear-locationbar")); + int buttonSize = clearSelectionButton->sizeHint().height(); + clearSelectionButton->setFixedSize(buttonSize, buttonSize); + clearSelectionButton->setToolTip(i18n("Clear Selection")); + connect(clearSelectionButton, &QPushButton::clicked, this, &ManageTemplatesDialog::clearSelection); + topLayout->addWidget(clearSelectionButton, 3, 2, Qt::AlignRight); + + topLayout->addWidget(new QLabel(i18n("Select an existing template if you want to overwrite it with your new template.\nNote that you cannot overwrite templates marked with an asterisk:\nif you do select such a template, a new template with the same name\nwill be created in a location you have write access to."), page), 4, 0, 1, 3); + + QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok|QDialogButtonBox::Cancel); + QPushButton *okButton = buttonBox->button(QDialogButtonBox::Ok); + okButton->setDefault(true); + okButton->setShortcut(Qt::CTRL | Qt::Key_Return); + mainLayout->addWidget(buttonBox); + connect(buttonBox, &QDialogButtonBox::accepted, this, &QDialog::accept); + connect(buttonBox, &QDialogButtonBox::rejected, this, &QDialog::reject); + + connect(m_templateList, &QTreeWidget::itemClicked, this, &ManageTemplatesDialog::slotSelectedTemplate); + connect(iconbut, &QPushButton::clicked, this, &ManageTemplatesDialog::slotSelectIcon); + connect(this, &QDialog::accepted, this, &ManageTemplatesDialog::addTemplate); } // dialog to remove a template ManageTemplatesDialog::ManageTemplatesDialog(KileTemplate::Manager *templateManager, const QString &caption, QWidget *parent, const char *name) - : QDialog(parent) - , m_templateManager(templateManager) - , m_templateType(KileDocument::Undefined) - , m_showAllTypesCheckBox(Q_NULLPTR) + : QDialog(parent) + , m_templateManager(templateManager) + , m_templateType(KileDocument::Undefined) + , m_showAllTypesCheckBox(Q_NULLPTR) { - setObjectName(name); - setWindowTitle(caption); - setModal(true); - - QVBoxLayout *mainLayout = new QVBoxLayout(); - mainLayout->setMargin(0); - setLayout(mainLayout); - - m_templateList = new QTreeWidget(this); - m_templateList->setSortingEnabled(false); - m_templateList->setHeaderLabels(QStringList() << i18nc("marked", "M") - << i18n("Existing Templates") - << i18n("Document Type")); - m_templateList->setAllColumnsShowFocus(true); - m_templateList->setRootIsDecorated(false); - - populateTemplateListView(KileDocument::Undefined); - - mainLayout->addWidget(m_templateList); - mainLayout->addWidget(new QLabel(i18n("Please select the template that you want to remove.\nNote that you cannot delete templates marked with an asterisk (for which you lack the necessary deletion permissions)."), this)); - - QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok|QDialogButtonBox::Cancel); - QPushButton *okButton = buttonBox->button(QDialogButtonBox::Ok); - okButton->setDefault(true); - okButton->setShortcut(Qt::CTRL | Qt::Key_Return); - mainLayout->addWidget(buttonBox); - connect(buttonBox, &QDialogButtonBox::accepted, this, &QDialog::accept); - connect(buttonBox, &QDialogButtonBox::rejected, this, &QDialog::reject); - - connect(this, &QDialog::accepted, this, &ManageTemplatesDialog::removeTemplate); + setObjectName(name); + setWindowTitle(caption); + setModal(true); + + QVBoxLayout *mainLayout = new QVBoxLayout(); + mainLayout->setMargin(0); + setLayout(mainLayout); + + m_templateList = new QTreeWidget(this); + m_templateList->setSortingEnabled(false); + m_templateList->setHeaderLabels(QStringList() << i18nc("marked", "M") + << i18n("Existing Templates") + << i18n("Document Type")); + m_templateList->setAllColumnsShowFocus(true); + m_templateList->setRootIsDecorated(false); + + populateTemplateListView(KileDocument::Undefined); + + mainLayout->addWidget(m_templateList); + mainLayout->addWidget(new QLabel(i18n("Please select the template that you want to remove.\nNote that you cannot delete templates marked with an asterisk (for which you lack the necessary deletion permissions)."), this)); + + QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok|QDialogButtonBox::Cancel); + QPushButton *okButton = buttonBox->button(QDialogButtonBox::Ok); + okButton->setDefault(true); + okButton->setShortcut(Qt::CTRL | Qt::Key_Return); + mainLayout->addWidget(buttonBox); + connect(buttonBox, &QDialogButtonBox::accepted, this, &QDialog::accept); + connect(buttonBox, &QDialogButtonBox::rejected, this, &QDialog::reject); + + connect(this, &QDialog::accepted, this, &ManageTemplatesDialog::removeTemplate); } ManageTemplatesDialog::~ManageTemplatesDialog() { } void ManageTemplatesDialog::updateTemplateListView(bool showAllTypes) { - populateTemplateListView((showAllTypes ? KileDocument::Undefined : m_templateType)); + populateTemplateListView((showAllTypes ? KileDocument::Undefined : m_templateType)); } void ManageTemplatesDialog::clearSelection() { - m_templateList->clearSelection(); + m_templateList->clearSelection(); } void ManageTemplatesDialog::populateTemplateListView(KileDocument::Type type) { - m_templateManager->scanForTemplates(); - KileTemplate::TemplateList templateList = m_templateManager->getTemplates(type); - QString mode; - QTreeWidgetItem* previousItem = Q_NULLPTR; - - m_templateList->clear(); - for (KileTemplate::TemplateListIterator i = templateList.begin(); i != templateList.end(); ++i) - { - KileTemplate::Info info = *i; - QFileInfo iconFileInfo(info.icon); - mode = (QFileInfo(info.path).isWritable() && (!iconFileInfo.exists() || iconFileInfo.isWritable())) ? " " : "*"; - if ((type == KileDocument::Undefined) || (info.type == type)) { - previousItem = new TemplateListViewItem(m_templateList, previousItem, mode, info); - } - } - - m_templateList->resizeColumnToContents(0); - m_templateList->resizeColumnToContents(1); + m_templateManager->scanForTemplates(); + KileTemplate::TemplateList templateList = m_templateManager->getTemplates(type); + QString mode; + QTreeWidgetItem* previousItem = Q_NULLPTR; + + m_templateList->clear(); + for (KileTemplate::TemplateListIterator i = templateList.begin(); i != templateList.end(); ++i) + { + KileTemplate::Info info = *i; + QFileInfo iconFileInfo(info.icon); + mode = (QFileInfo(info.path).isWritable() && (!iconFileInfo.exists() || iconFileInfo.isWritable())) ? " " : "*"; + if ((type == KileDocument::Undefined) || (info.type == type)) { + previousItem = new TemplateListViewItem(m_templateList, previousItem, mode, info); + } + } + + m_templateList->resizeColumnToContents(0); + m_templateList->resizeColumnToContents(1); } void ManageTemplatesDialog::slotSelectedTemplate(QTreeWidgetItem *item) { - TemplateListViewItem *templateItem = dynamic_cast(item); - if (templateItem) { - KileTemplate::Info info = templateItem->getTemplateInfo(); - m_nameEdit->setText(info.name); - m_iconEdit->setText(info.icon); - } + TemplateListViewItem *templateItem = dynamic_cast(item); + if (templateItem) { + KileTemplate::Info info = templateItem->getTemplateInfo(); + m_nameEdit->setText(info.name); + m_iconEdit->setText(info.icon); + } } void ManageTemplatesDialog::slotSelectIcon() { - KIconDialog *dlg = new KIconDialog(); - QString res = dlg->openDialog(); - KIconLoader kil; + KIconDialog *dlg = new KIconDialog(); + QString res = dlg->openDialog(); + KIconLoader kil; - if (!res.isNull()) { - m_iconEdit->setText(kil.iconPath(res, -KIconLoader::SizeLarge, false)); - } + if (!res.isNull()) { + m_iconEdit->setText(kil.iconPath(res, -KIconLoader::SizeLarge, false)); + } } void ManageTemplatesDialog::addTemplate() { - QString templateName = (m_nameEdit->text()).trimmed(); - - if (templateName.isEmpty()) { - KMessageBox::error(this, i18n("The template name that you have entered is invalid.\nPlease enter a new name.")); - return; - } - - QString icon = (m_iconEdit->text()).trimmed(); - QUrl iconURL = QUrl::fromUserInput(icon); - - if (icon.isEmpty()) { - KMessageBox::error(this, i18n("Please choose an icon first.")); - return; - } - - KIO::StatJob* statJob = KIO::stat(iconURL, KIO::StatJob::SourceSide, 0); - KJobWidgets::setWindow(statJob, this); - statJob->exec(); - if (statJob->error()) { - KMessageBox::error(this, i18n("The icon file: %1\ndoes not seem to exist. Please choose a new icon.", icon)); - return; - } - - statJob = KIO::stat(m_sourceURL, KIO::StatJob::SourceSide, 0); - KJobWidgets::setWindow(statJob, this); - statJob->exec(); - if (statJob->error()) { - KMessageBox::error(this, i18n("The file: %1\ndoes not seem to exist. Maybe you forgot to save the file?", m_sourceURL.toString())); - return; - } - - QTreeWidgetItem* item = m_templateList->currentItem(); - - if (!item && m_templateManager->searchForTemplate(templateName, m_templateType)) { - KMessageBox::error(this, i18n("A template named \"%1\" already exists.\nPlease remove it first.", templateName)); - return; - } - - bool returnValue; - if (item) { - TemplateListViewItem *templateItem = dynamic_cast(item); - Q_ASSERT(templateItem); - KileTemplate::Info templateInfo = templateItem->getTemplateInfo(); - if (KMessageBox::warningYesNo(this, i18n("You are about to replace the template \"%1\"; are you sure?", templateInfo.name)) == KMessageBox::No) { - reject(); - return; - } - returnValue = m_templateManager->replace(templateInfo, m_sourceURL, templateName, iconURL); - } - else { - returnValue = m_templateManager->add(m_sourceURL, templateName, iconURL); - } - if (!returnValue) { - KMessageBox::error(this, i18n("Failed to create the template.")); - reject(); - return; - } + QString templateName = (m_nameEdit->text()).trimmed(); + + if (templateName.isEmpty()) { + KMessageBox::error(this, i18n("The template name that you have entered is invalid.\nPlease enter a new name.")); + return; + } + + QString icon = (m_iconEdit->text()).trimmed(); + QUrl iconURL = QUrl::fromUserInput(icon); + + if (icon.isEmpty()) { + KMessageBox::error(this, i18n("Please choose an icon first.")); + return; + } + + KIO::StatJob* statJob = KIO::stat(iconURL, KIO::StatJob::SourceSide, 0); + KJobWidgets::setWindow(statJob, this); + statJob->exec(); + if (statJob->error()) { + KMessageBox::error(this, i18n("The icon file: %1\ndoes not seem to exist. Please choose a new icon.", icon)); + return; + } + + statJob = KIO::stat(m_sourceURL, KIO::StatJob::SourceSide, 0); + KJobWidgets::setWindow(statJob, this); + statJob->exec(); + if (statJob->error()) { + KMessageBox::error(this, i18n("The file: %1\ndoes not seem to exist. Maybe you forgot to save the file?", m_sourceURL.toString())); + return; + } + + QTreeWidgetItem* item = m_templateList->currentItem(); + + if (!item && m_templateManager->searchForTemplate(templateName, m_templateType)) { + KMessageBox::error(this, i18n("A template named \"%1\" already exists.\nPlease remove it first.", templateName)); + return; + } + + bool returnValue; + if (item) { + TemplateListViewItem *templateItem = dynamic_cast(item); + Q_ASSERT(templateItem); + KileTemplate::Info templateInfo = templateItem->getTemplateInfo(); + if (KMessageBox::warningYesNo(this, i18n("You are about to replace the template \"%1\"; are you sure?", templateInfo.name)) == KMessageBox::No) { + reject(); + return; + } + returnValue = m_templateManager->replace(templateInfo, m_sourceURL, templateName, iconURL); + } + else { + returnValue = m_templateManager->add(m_sourceURL, templateName, iconURL); + } + if (!returnValue) { + KMessageBox::error(this, i18n("Failed to create the template.")); + reject(); + return; + } } bool ManageTemplatesDialog::removeTemplate() { - QTreeWidgetItem* item = m_templateList->currentItem(); - if (!item) { - KMessageBox::information(this, i18n("Please select a template that should be removed.")); - return true; - } - - TemplateListViewItem *templateItem = dynamic_cast(item); - Q_ASSERT(templateItem); - - KileTemplate::Info templateInfo = templateItem->getTemplateInfo(); - - KIO::StatJob* statJob = KIO::stat(QUrl::fromUserInput(templateInfo.path), KIO::StatJob::DestinationSide, 0); - KIO::StatJob* statJob2 = KIO::stat(QUrl::fromUserInput(templateInfo.icon), KIO::StatJob::DestinationSide, 0); - KJobWidgets::setWindow(statJob, this); - KJobWidgets::setWindow(statJob2, this); - statJob->exec(); - statJob2->exec(); - if ((statJob->error() && statJob2->error()) || !QFileInfo(templateInfo.icon).exists()) { - KMessageBox::error(this, i18n("Sorry, but you do not have the necessary permissions to remove the selected template.")); - return false; - } - - if (KMessageBox::warningYesNo(this, i18n("You are about to remove the template \"%1\"; are you sure?", templateInfo.name)) == KMessageBox::No) { - return false; - } - - if (!m_templateManager->remove(templateInfo)) { - KMessageBox::error(this, i18n("The template could not be removed.")); - reject(); - return false; - } - return true; + QTreeWidgetItem* item = m_templateList->currentItem(); + if (!item) { + KMessageBox::information(this, i18n("Please select a template that should be removed.")); + return true; + } + + TemplateListViewItem *templateItem = dynamic_cast(item); + Q_ASSERT(templateItem); + + KileTemplate::Info templateInfo = templateItem->getTemplateInfo(); + + KIO::StatJob* statJob = KIO::stat(QUrl::fromUserInput(templateInfo.path), KIO::StatJob::DestinationSide, 0); + KIO::StatJob* statJob2 = KIO::stat(QUrl::fromUserInput(templateInfo.icon), KIO::StatJob::DestinationSide, 0); + KJobWidgets::setWindow(statJob, this); + KJobWidgets::setWindow(statJob2, this); + statJob->exec(); + statJob2->exec(); + if ((statJob->error() && statJob2->error()) || !QFileInfo(templateInfo.icon).exists()) { + KMessageBox::error(this, i18n("Sorry, but you do not have the necessary permissions to remove the selected template.")); + return false; + } + + if (KMessageBox::warningYesNo(this, i18n("You are about to remove the template \"%1\"; are you sure?", templateInfo.name)) == KMessageBox::No) { + return false; + } + + if (!m_templateManager->remove(templateInfo)) { + KMessageBox::error(this, i18n("The template could not be removed.")); + reject(); + return false; + } + return true; } diff --git a/src/dialogs/managetemplatesdialog.h b/src/dialogs/managetemplatesdialog.h index e5a63366..b99d0810 100644 --- a/src/dialogs/managetemplatesdialog.h +++ b/src/dialogs/managetemplatesdialog.h @@ -1,74 +1,74 @@ /**************************************************************************************** begin : Sun Apr 27 2003 copyright : (C) 2003 by Jeroen Wijnhout (wijnhout@science.uva.nl) 2007 by Michel Ludwig (michel.ludwig@kdemail.net) ****************************************************************************************/ /*************************************************************************** * * * 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. * * * ***************************************************************************/ #ifndef MANAGETEMPLATESDIALOG_H #define MANAGETEMPLATESDIALOG_H #include #include class QCheckBox; class QLineEdit; class QTreeWidget; class QTreeWidgetItem; #include "kileconstants.h" namespace KileTemplate { class Manager; struct Info; } /** *@author Jeroen Wijnhout */ class ManageTemplatesDialog : public QDialog { - Q_OBJECT + Q_OBJECT public: - ManageTemplatesDialog(KileTemplate::Manager *templateManager, const QUrl &sourceURL, const QString &caption, QWidget *parent = 0, const char *name = 0); - ManageTemplatesDialog(KileTemplate::Manager *templateManager, const QString &caption, QWidget *parent = 0, const char *name = 0); - virtual ~ManageTemplatesDialog(); + ManageTemplatesDialog(KileTemplate::Manager *templateManager, const QUrl &sourceURL, const QString &caption, QWidget *parent = 0, const char *name = 0); + ManageTemplatesDialog(KileTemplate::Manager *templateManager, const QString &caption, QWidget *parent = 0, const char *name = 0); + virtual ~ManageTemplatesDialog(); public Q_SLOTS: - void slotSelectedTemplate(QTreeWidgetItem *item); - void slotSelectIcon(); - void addTemplate(); - bool removeTemplate(); + void slotSelectedTemplate(QTreeWidgetItem *item); + void slotSelectIcon(); + void addTemplate(); + bool removeTemplate(); Q_SIGNALS: - void aboutToClose(); + void aboutToClose(); protected Q_SLOTS: - void updateTemplateListView(bool showAllTypes); - void clearSelection(); + void updateTemplateListView(bool showAllTypes); + void clearSelection(); protected: - KileTemplate::Manager* m_templateManager; - QLineEdit *m_nameEdit, *m_iconEdit; - QTreeWidget *m_templateList; - KileDocument::Type m_templateType; - QCheckBox *m_showAllTypesCheckBox; - QUrl m_sourceURL; + KileTemplate::Manager* m_templateManager; + QLineEdit *m_nameEdit, *m_iconEdit; + QTreeWidget *m_templateList; + KileDocument::Type m_templateType; + QCheckBox *m_showAllTypesCheckBox; + QUrl m_sourceURL; - /** - * Fills the template list view with template entries. - * - * @param type The type of the templates that should be displayed. You can pass "KileDocument::Undefined" to - * display every template. - **/ - void populateTemplateListView(KileDocument::Type type); + /** + * Fills the template list view with template entries. + * + * @param type The type of the templates that should be displayed. You can pass "KileDocument::Undefined" to + * display every template. + **/ + void populateTemplateListView(KileDocument::Type type); }; #endif diff --git a/src/dialogs/mathenvironmentdialog.cpp b/src/dialogs/mathenvironmentdialog.cpp index d181f4da..7b8bb3ec 100644 --- a/src/dialogs/mathenvironmentdialog.cpp +++ b/src/dialogs/mathenvironmentdialog.cpp @@ -1,398 +1,398 @@ /***************************************************************************************** mathenvdialog.cpp ---------------------------------------------------------------------------- date : Dec 06 2005 version : 0.21 copyright : (C) 2005 by Holger Danielsson (holger.danielsson@t-online.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. * * * ***************************************************************************/ #include "mathenvironmentdialog.h" #include "codecompletion.h" #include "kiledebug.h" #include "editorextension.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include namespace KileDialog { MathEnvironmentDialog::MathEnvironmentDialog(QWidget *parent, KConfig *config, KileInfo *ki, KileDocument::LatexCommands *commands) - : Wizard(config, parent), m_ki(ki), m_latexCommands(commands) + : Wizard(config, parent), m_ki(ki), m_latexCommands(commands) { - QWidget *page = new QWidget(this); - QVBoxLayout *mainLayout = new QVBoxLayout; - setLayout(mainLayout); - mainLayout->addWidget(page); - setWindowTitle(i18n("Math Environments")); - - QVBoxLayout *vbox = new QVBoxLayout(); - vbox->setMargin(0); - page->setLayout(vbox); - - // environment groupbox - QGroupBox *envgroup = new QGroupBox(i18n("Environment"), page); - mainLayout->addWidget(envgroup); - - m_lbEnvironment = new QLabel(i18n("&Name:"), envgroup); - m_lbStarred = new QLabel(i18n("Without n&umbering:"), envgroup); - m_lbRows = new QLabel(i18n("Number of &rows:"), envgroup); - m_lbCols = new QLabel(i18n("Number of c&ols:"), envgroup); - m_lbSpace = new QLabel(i18n("Space command\nto &separate groups:"), envgroup); - m_lbTabulator = new QLabel(i18n("Standard &tabulator:"), envgroup); - m_lbDisplaymath = new QLabel(i18n("Display&math mode:"), envgroup); - m_lbBullets = new QLabel(i18n("Use &bullets:"), envgroup); - - QFrame *frame = new QFrame(envgroup); - frame->setFrameStyle(QFrame::HLine); - frame->setFrameShadow(QFrame::Sunken); - frame->setLineWidth(1); - - m_coEnvironment = new KComboBox(envgroup); - m_cbStarred = new QCheckBox(envgroup); - m_spRows = new QSpinBox(envgroup); - m_spRows->setMinimum(1); - m_spRows->setMaximum(99); - m_spRows->setSingleStep(1); - m_spRows->setValue(3); - m_spCols = new QSpinBox(envgroup); - m_spCols->setMinimum(1); - m_spCols->setMaximum(49); - m_spCols->setSingleStep(1); - m_spCols->setValue(3); - m_edSpace = new QLineEdit(envgroup); - m_coTabulator = new KComboBox(envgroup); - m_coDisplaymath = new KComboBox(envgroup); - m_cbBullets = new QCheckBox(envgroup); - - QGridLayout *envlayout = new QGridLayout(); - envgroup->setLayout(envlayout); - envlayout->setAlignment(Qt::AlignTop); - envlayout->addWidget(m_lbEnvironment, 0, 0); - envlayout->addWidget(m_lbStarred, 1, 0); - envlayout->addWidget(m_lbRows, 2, 0); - envlayout->addWidget(m_lbCols, 3, 0); - envlayout->addWidget(m_lbTabulator, 5, 0); - envlayout->addWidget(m_lbDisplaymath, 6, 0); - envlayout->addWidget(m_coEnvironment, 0, 1); - envlayout->addWidget(m_cbStarred, 1, 1); - envlayout->addWidget(m_spRows, 2, 1); - envlayout->addWidget(m_spCols, 3, 1); - envlayout->addWidget(m_coTabulator, 5, 1); - envlayout->addWidget(m_coDisplaymath, 6, 1); - envlayout->addWidget(m_lbSpace, 3, 3); - envlayout->addWidget(m_lbBullets, 5, 3); - envlayout->addWidget(m_edSpace, 3, 4); - envlayout->addWidget(m_cbBullets, 5, 4); - envlayout->addWidget(frame, 4, 0, 1, 5); - envlayout->setRowMinimumHeight(4, 30); - envlayout->setColumnMinimumWidth(2, 20); - envlayout->setColumnStretch(4, 1); - - // add widgets - vbox->addWidget(envgroup); - vbox->addStretch(1); - - m_lbEnvironment->setBuddy(m_coEnvironment); - m_lbStarred->setBuddy(m_cbStarred); - m_lbRows->setBuddy(m_spRows); - m_lbCols->setBuddy(m_spCols); - m_lbSpace->setBuddy(m_edSpace); - m_lbTabulator->setBuddy(m_coTabulator); - m_lbDisplaymath->setBuddy(m_coDisplaymath); - m_lbBullets->setBuddy(m_cbBullets); - - // initialize dialog - m_coDisplaymath->addItem(QString()); - m_coDisplaymath->addItem("displaymath"); - m_coDisplaymath->addItem("\\["); - m_coDisplaymath->addItem("equation"); - m_coDisplaymath->addItem("equation*"); - - // install environments - initEnvironments(); - int alignIndex = m_coEnvironment->findText("align"); - if(alignIndex >= 0) { - m_coEnvironment->setCurrentIndex(alignIndex); - } - slotEnvironmentChanged(m_coEnvironment->currentIndex()); - - // signals and slots - connect(m_coEnvironment, SIGNAL(activated(int)), this, SLOT(slotEnvironmentChanged(int))); - connect(m_spCols, SIGNAL(valueChanged(int)), this, SLOT(slotSpinboxValueChanged(int))); - - m_coEnvironment->setWhatsThis(i18n("Choose an environment.")); - m_cbStarred->setWhatsThis(i18n("Use the starred version of this environment.")); - m_spRows->setWhatsThis(i18n("Choose the number of table rows.")); - m_spCols->setWhatsThis(i18n("Choose the number of table columns or alignment groups.")); - m_edSpace->setWhatsThis(i18n("Define an extra LaTeX command to separate alignment groups.")); - m_coTabulator->setWhatsThis(i18n("Choose one of some predefined tabulators.")); - m_coDisplaymath->setWhatsThis(i18n("Some environments are only valid in math mode. You can surround them with one of these display math modes.")); - m_cbBullets->setWhatsThis(i18n("Insert bullets in each cell. Alt+Ctrl+Right and Alt+Ctrl+Left will move very quick from one cell to another.")); - - mainLayout->addWidget(buttonBox()); - connect(buttonBox(), &QDialogButtonBox::accepted, this, &QDialog::accept); - connect(buttonBox(), &QDialogButtonBox::rejected, this, &QDialog::reject); - connect(this, &QDialog::accepted, this, &MathEnvironmentDialog::slotAccepted); + QWidget *page = new QWidget(this); + QVBoxLayout *mainLayout = new QVBoxLayout; + setLayout(mainLayout); + mainLayout->addWidget(page); + setWindowTitle(i18n("Math Environments")); + + QVBoxLayout *vbox = new QVBoxLayout(); + vbox->setMargin(0); + page->setLayout(vbox); + + // environment groupbox + QGroupBox *envgroup = new QGroupBox(i18n("Environment"), page); + mainLayout->addWidget(envgroup); + + m_lbEnvironment = new QLabel(i18n("&Name:"), envgroup); + m_lbStarred = new QLabel(i18n("Without n&umbering:"), envgroup); + m_lbRows = new QLabel(i18n("Number of &rows:"), envgroup); + m_lbCols = new QLabel(i18n("Number of c&ols:"), envgroup); + m_lbSpace = new QLabel(i18n("Space command\nto &separate groups:"), envgroup); + m_lbTabulator = new QLabel(i18n("Standard &tabulator:"), envgroup); + m_lbDisplaymath = new QLabel(i18n("Display&math mode:"), envgroup); + m_lbBullets = new QLabel(i18n("Use &bullets:"), envgroup); + + QFrame *frame = new QFrame(envgroup); + frame->setFrameStyle(QFrame::HLine); + frame->setFrameShadow(QFrame::Sunken); + frame->setLineWidth(1); + + m_coEnvironment = new KComboBox(envgroup); + m_cbStarred = new QCheckBox(envgroup); + m_spRows = new QSpinBox(envgroup); + m_spRows->setMinimum(1); + m_spRows->setMaximum(99); + m_spRows->setSingleStep(1); + m_spRows->setValue(3); + m_spCols = new QSpinBox(envgroup); + m_spCols->setMinimum(1); + m_spCols->setMaximum(49); + m_spCols->setSingleStep(1); + m_spCols->setValue(3); + m_edSpace = new QLineEdit(envgroup); + m_coTabulator = new KComboBox(envgroup); + m_coDisplaymath = new KComboBox(envgroup); + m_cbBullets = new QCheckBox(envgroup); + + QGridLayout *envlayout = new QGridLayout(); + envgroup->setLayout(envlayout); + envlayout->setAlignment(Qt::AlignTop); + envlayout->addWidget(m_lbEnvironment, 0, 0); + envlayout->addWidget(m_lbStarred, 1, 0); + envlayout->addWidget(m_lbRows, 2, 0); + envlayout->addWidget(m_lbCols, 3, 0); + envlayout->addWidget(m_lbTabulator, 5, 0); + envlayout->addWidget(m_lbDisplaymath, 6, 0); + envlayout->addWidget(m_coEnvironment, 0, 1); + envlayout->addWidget(m_cbStarred, 1, 1); + envlayout->addWidget(m_spRows, 2, 1); + envlayout->addWidget(m_spCols, 3, 1); + envlayout->addWidget(m_coTabulator, 5, 1); + envlayout->addWidget(m_coDisplaymath, 6, 1); + envlayout->addWidget(m_lbSpace, 3, 3); + envlayout->addWidget(m_lbBullets, 5, 3); + envlayout->addWidget(m_edSpace, 3, 4); + envlayout->addWidget(m_cbBullets, 5, 4); + envlayout->addWidget(frame, 4, 0, 1, 5); + envlayout->setRowMinimumHeight(4, 30); + envlayout->setColumnMinimumWidth(2, 20); + envlayout->setColumnStretch(4, 1); + + // add widgets + vbox->addWidget(envgroup); + vbox->addStretch(1); + + m_lbEnvironment->setBuddy(m_coEnvironment); + m_lbStarred->setBuddy(m_cbStarred); + m_lbRows->setBuddy(m_spRows); + m_lbCols->setBuddy(m_spCols); + m_lbSpace->setBuddy(m_edSpace); + m_lbTabulator->setBuddy(m_coTabulator); + m_lbDisplaymath->setBuddy(m_coDisplaymath); + m_lbBullets->setBuddy(m_cbBullets); + + // initialize dialog + m_coDisplaymath->addItem(QString()); + m_coDisplaymath->addItem("displaymath"); + m_coDisplaymath->addItem("\\["); + m_coDisplaymath->addItem("equation"); + m_coDisplaymath->addItem("equation*"); + + // install environments + initEnvironments(); + int alignIndex = m_coEnvironment->findText("align"); + if(alignIndex >= 0) { + m_coEnvironment->setCurrentIndex(alignIndex); + } + slotEnvironmentChanged(m_coEnvironment->currentIndex()); + + // signals and slots + connect(m_coEnvironment, SIGNAL(activated(int)), this, SLOT(slotEnvironmentChanged(int))); + connect(m_spCols, SIGNAL(valueChanged(int)), this, SLOT(slotSpinboxValueChanged(int))); + + m_coEnvironment->setWhatsThis(i18n("Choose an environment.")); + m_cbStarred->setWhatsThis(i18n("Use the starred version of this environment.")); + m_spRows->setWhatsThis(i18n("Choose the number of table rows.")); + m_spCols->setWhatsThis(i18n("Choose the number of table columns or alignment groups.")); + m_edSpace->setWhatsThis(i18n("Define an extra LaTeX command to separate alignment groups.")); + m_coTabulator->setWhatsThis(i18n("Choose one of some predefined tabulators.")); + m_coDisplaymath->setWhatsThis(i18n("Some environments are only valid in math mode. You can surround them with one of these display math modes.")); + m_cbBullets->setWhatsThis(i18n("Insert bullets in each cell. Alt+Ctrl+Right and Alt+Ctrl+Left will move very quick from one cell to another.")); + + mainLayout->addWidget(buttonBox()); + connect(buttonBox(), &QDialogButtonBox::accepted, this, &QDialog::accept); + connect(buttonBox(), &QDialogButtonBox::rejected, this, &QDialog::reject); + connect(this, &QDialog::accepted, this, &MathEnvironmentDialog::slotAccepted); } void MathEnvironmentDialog::initEnvironments() { - // read all math environments and insert them into the combobox - QStringList list; - QStringList::ConstIterator it; - m_latexCommands->commandList(list, (uint)(KileDocument::CmdAttrAmsmath | KileDocument::CmdAttrMath), false); - for (it = list.constBegin(); it != list.constEnd(); ++it) { - m_coEnvironment->addItem(*it); - } + // read all math environments and insert them into the combobox + QStringList list; + QStringList::ConstIterator it; + m_latexCommands->commandList(list, (uint)(KileDocument::CmdAttrAmsmath | KileDocument::CmdAttrMath), false); + for (it = list.constBegin(); it != list.constEnd(); ++it) { + m_coEnvironment->addItem(*it); + } } bool MathEnvironmentDialog::isGroupsParameterEnv() { - return (m_parameter == "{n}"); + return (m_parameter == "{n}"); } bool MathEnvironmentDialog::isParameterEnv() { - return (m_parameter.indexOf("{") >= 0); + return (m_parameter.indexOf("{") >= 0); } ////////////////////////////// determine the whole tag ////////////////////////////// void MathEnvironmentDialog::slotEnvironmentChanged(int index) { - KILE_DEBUG_MAIN << "environment changed: " << m_coEnvironment->itemText(index) << endl; - m_envname = m_coEnvironment->itemText(index); - - // look for environment parameter in dictionary - KileDocument::LatexCmdAttributes attr; - if (m_latexCommands->commandAttributes(m_envname, attr)) { - m_starred = attr.starred; - m_mathmode = attr.mathmode; - m_columns = (attr.tabulator == "&"); - m_groups = (attr.tabulator == "&="); - m_fixedcolumns = (attr.tabulator == "&=&"); - m_tabulator = attr.tabulator; - m_parameter = attr.parameter; - } - - // set starred version - m_cbStarred->setChecked(false); - m_lbStarred->setEnabled(m_starred); - m_cbStarred->setEnabled(m_starred); - - // determine column/group entries - QString labeltext = i18n("Number of cols:"); - bool spinstate = false; - int minvalue = 1; - int maxvalue = 1; - int value = 1; - - if (m_columns) { - spinstate = true; - if (m_envname != "cases") { // 1,49,3 - maxvalue = 49; - value = 3; - } - else { - minvalue = 2; // 2,2,2 - maxvalue = 2; - value = 2; - } - } - else { - if (m_groups) { - spinstate = true; - labeltext = i18n("Number of groups:"); - maxvalue = 19; // 1,19,1 - } - else { - if (m_fixedcolumns) { - spinstate = true; - minvalue = 3; // 3,3,3 - maxvalue = 3; - value = 3; - } - else { - if (m_envname == "split") { - spinstate = true; - maxvalue = 2; // 1,2,1 - } - } - } - } - - // set column/group entries - m_lbCols->setText(labeltext); - m_spCols->setMinimum(minvalue); - m_spCols->setMaximum(maxvalue); - m_spCols->setValue(value); - - m_lbCols->setEnabled(spinstate); - m_spCols->setEnabled(spinstate); - slotSpinboxValueChanged(m_spCols->value()); - - // set tabulator entries - m_coTabulator->clear(); - QStringList tablist; - if(m_tabulator == "&=&") { - tablist << "&=&" << "& &" << "&<&" << "&<=&" << "&>&" << "&>=&" - << "&\\ne&" << "&\\approx&" << "&\\equiv&" << "&\\conq&"; - } - else { - if(m_tabulator == "&=") { - tablist << "&=" << "& " << "&<" << "&<=" << "&>" << "&>=" - << "&\\ne" << "&\\approx" << "&\\equiv" << "&\\conq"; - } - else { - if(!m_tabulator.isEmpty()) { - tablist << "&"; - } - } - } - bool tabstate = (tablist.count() > 0); - m_lbTabulator->setEnabled(tabstate); - m_coTabulator->setEnabled(tabstate); - if(tabstate) { - m_coTabulator->addItems(tablist); - } - - // set displaymathmode entries - m_lbDisplaymath->setEnabled(m_mathmode); - m_coDisplaymath->setEnabled(m_mathmode); + KILE_DEBUG_MAIN << "environment changed: " << m_coEnvironment->itemText(index) << endl; + m_envname = m_coEnvironment->itemText(index); + + // look for environment parameter in dictionary + KileDocument::LatexCmdAttributes attr; + if (m_latexCommands->commandAttributes(m_envname, attr)) { + m_starred = attr.starred; + m_mathmode = attr.mathmode; + m_columns = (attr.tabulator == "&"); + m_groups = (attr.tabulator == "&="); + m_fixedcolumns = (attr.tabulator == "&=&"); + m_tabulator = attr.tabulator; + m_parameter = attr.parameter; + } + + // set starred version + m_cbStarred->setChecked(false); + m_lbStarred->setEnabled(m_starred); + m_cbStarred->setEnabled(m_starred); + + // determine column/group entries + QString labeltext = i18n("Number of cols:"); + bool spinstate = false; + int minvalue = 1; + int maxvalue = 1; + int value = 1; + + if (m_columns) { + spinstate = true; + if (m_envname != "cases") { // 1,49,3 + maxvalue = 49; + value = 3; + } + else { + minvalue = 2; // 2,2,2 + maxvalue = 2; + value = 2; + } + } + else { + if (m_groups) { + spinstate = true; + labeltext = i18n("Number of groups:"); + maxvalue = 19; // 1,19,1 + } + else { + if (m_fixedcolumns) { + spinstate = true; + minvalue = 3; // 3,3,3 + maxvalue = 3; + value = 3; + } + else { + if (m_envname == "split") { + spinstate = true; + maxvalue = 2; // 1,2,1 + } + } + } + } + + // set column/group entries + m_lbCols->setText(labeltext); + m_spCols->setMinimum(minvalue); + m_spCols->setMaximum(maxvalue); + m_spCols->setValue(value); + + m_lbCols->setEnabled(spinstate); + m_spCols->setEnabled(spinstate); + slotSpinboxValueChanged(m_spCols->value()); + + // set tabulator entries + m_coTabulator->clear(); + QStringList tablist; + if(m_tabulator == "&=&") { + tablist << "&=&" << "& &" << "&<&" << "&<=&" << "&>&" << "&>=&" + << "&\\ne&" << "&\\approx&" << "&\\equiv&" << "&\\conq&"; + } + else { + if(m_tabulator == "&=") { + tablist << "&=" << "& " << "&<" << "&<=" << "&>" << "&>=" + << "&\\ne" << "&\\approx" << "&\\equiv" << "&\\conq"; + } + else { + if(!m_tabulator.isEmpty()) { + tablist << "&"; + } + } + } + bool tabstate = (tablist.count() > 0); + m_lbTabulator->setEnabled(tabstate); + m_coTabulator->setEnabled(tabstate); + if(tabstate) { + m_coTabulator->addItems(tablist); + } + + // set displaymathmode entries + m_lbDisplaymath->setEnabled(m_mathmode); + m_coDisplaymath->setEnabled(m_mathmode); } void MathEnvironmentDialog::slotSpinboxValueChanged(int index) { - bool state = (index > 1 && m_groups && isGroupsParameterEnv()); - m_lbSpace->setEnabled(state); - m_edSpace->setEnabled(state); + bool state = (index > 1 && m_groups && isGroupsParameterEnv()); + m_lbSpace->setEnabled(state); + m_edSpace->setEnabled(state); } void MathEnvironmentDialog::slotAccepted() { - // environment - QString envname = (m_cbStarred->isChecked()) ? m_envname + '*' : m_envname; - QString indent = m_ki->editorExtension()->autoIndentEnvironment(); - - // use bullets? - QString bullet = (m_cbBullets->isChecked()) ? s_bullet : QString(); - - // normal tabulator - QString tab = m_coTabulator->currentText(); - tab.replace("<=", "\\le"); - tab.replace(">=", "\\ge"); - QString tabulator = bullet + ' ' + tab + ' '; - - // number of rows - int numrows = m_spRows->value(); - - // get number of groups/columns and tabulator to separate these - QString grouptabulator; - int numgroups; - bool aligngroups; - if (m_groups) { - aligngroups = true; - numgroups = (m_tabulator != "&") ? m_spCols->value() : 1; - if (m_edSpace->isEnabled()) { - QString spaces; - grouptabulator = " &" + m_edSpace->text() + " "; - } - else { - grouptabulator = " & "; - } - } - else { - aligngroups = false; - if(!m_fixedcolumns) { - numgroups = (m_columns) ? m_spCols->value() - 1 : 0; - } - else { - numgroups = 1; - } - } - - // get displaymath mode - QString displaymathbegin; - QString displaymathend; - if(m_coDisplaymath->isEnabled()) { - QString mathmode = m_coDisplaymath->currentText(); - if(!mathmode.isEmpty()) { - if(mathmode == "\\[") { - displaymathbegin = "\\[\n"; - displaymathend = "\\]\n"; - } - else { - displaymathbegin = QString("\\begin{%1}\n").arg(mathmode); - displaymathend = QString("\\end{%1}\n").arg(mathmode); - } - } - } - - // build tag - m_td.tagBegin = displaymathbegin; - - QString parameter; - if (isGroupsParameterEnv()) { - parameter = QString("{%2}").arg(numgroups); - } - else { - if(isParameterEnv()) { - parameter = '{' + bullet + '}'; - } - } - - // open environment - m_td.tagBegin += QString("\\begin{%1}").arg(envname) + parameter + '\n'; - - for(int row = 0; row < numrows; ++row) { - m_td.tagBegin += indent; - for(int col = 0; col < numgroups; ++col) { - m_td.tagBegin += tabulator; - // is there more than one group or column? - if(aligngroups && col < numgroups - 1) { - m_td.tagBegin += bullet + grouptabulator; - } - } - // last row without CR - if(row < numrows - 1) { - m_td.tagBegin += bullet + " \\\\\n"; - } - else { - m_td.tagBegin += bullet; - } - } - - // close environment - m_td.tagEnd = QString("\n\\end{%1}\n").arg(envname); - m_td.tagEnd += displaymathend; - - m_td.dy = (displaymathbegin.isEmpty()) ? 1 : 2; - m_td.dx = indent.length(); + // environment + QString envname = (m_cbStarred->isChecked()) ? m_envname + '*' : m_envname; + QString indent = m_ki->editorExtension()->autoIndentEnvironment(); + + // use bullets? + QString bullet = (m_cbBullets->isChecked()) ? s_bullet : QString(); + + // normal tabulator + QString tab = m_coTabulator->currentText(); + tab.replace("<=", "\\le"); + tab.replace(">=", "\\ge"); + QString tabulator = bullet + ' ' + tab + ' '; + + // number of rows + int numrows = m_spRows->value(); + + // get number of groups/columns and tabulator to separate these + QString grouptabulator; + int numgroups; + bool aligngroups; + if (m_groups) { + aligngroups = true; + numgroups = (m_tabulator != "&") ? m_spCols->value() : 1; + if (m_edSpace->isEnabled()) { + QString spaces; + grouptabulator = " &" + m_edSpace->text() + " "; + } + else { + grouptabulator = " & "; + } + } + else { + aligngroups = false; + if(!m_fixedcolumns) { + numgroups = (m_columns) ? m_spCols->value() - 1 : 0; + } + else { + numgroups = 1; + } + } + + // get displaymath mode + QString displaymathbegin; + QString displaymathend; + if(m_coDisplaymath->isEnabled()) { + QString mathmode = m_coDisplaymath->currentText(); + if(!mathmode.isEmpty()) { + if(mathmode == "\\[") { + displaymathbegin = "\\[\n"; + displaymathend = "\\]\n"; + } + else { + displaymathbegin = QString("\\begin{%1}\n").arg(mathmode); + displaymathend = QString("\\end{%1}\n").arg(mathmode); + } + } + } + + // build tag + m_td.tagBegin = displaymathbegin; + + QString parameter; + if (isGroupsParameterEnv()) { + parameter = QString("{%2}").arg(numgroups); + } + else { + if(isParameterEnv()) { + parameter = '{' + bullet + '}'; + } + } + + // open environment + m_td.tagBegin += QString("\\begin{%1}").arg(envname) + parameter + '\n'; + + for(int row = 0; row < numrows; ++row) { + m_td.tagBegin += indent; + for(int col = 0; col < numgroups; ++col) { + m_td.tagBegin += tabulator; + // is there more than one group or column? + if(aligngroups && col < numgroups - 1) { + m_td.tagBegin += bullet + grouptabulator; + } + } + // last row without CR + if(row < numrows - 1) { + m_td.tagBegin += bullet + " \\\\\n"; + } + else { + m_td.tagBegin += bullet; + } + } + + // close environment + m_td.tagEnd = QString("\n\\end{%1}\n").arg(envname); + m_td.tagEnd += displaymathend; + + m_td.dy = (displaymathbegin.isEmpty()) ? 1 : 2; + m_td.dx = indent.length(); } } diff --git a/src/dialogs/mathenvironmentdialog.h b/src/dialogs/mathenvironmentdialog.h index e38c6e38..383cfb56 100644 --- a/src/dialogs/mathenvironmentdialog.h +++ b/src/dialogs/mathenvironmentdialog.h @@ -1,79 +1,79 @@ /****************************************************************************************** mathenvdialog.h ------------------------------------------------------------------------------------------- date : Dec 06 2005 version : 0.21 copyright : (C) 2005 by Holger Danielsson (holger.danielsson@t-online.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. * * * ***************************************************************************/ #ifndef MATHENVIRONMENTDIALOG_H #define MATHENVIRONMENTDIALOG_H #include "kileinfo.h" #include "kilewizard.h" #include "latexcmd.h" class QLabel; class QCheckBox; class QSpinBox; class QLineEdit; class KComboBox; namespace KileDialog { class MathEnvironmentDialog : public Wizard { - Q_OBJECT - - public: - MathEnvironmentDialog(QWidget *parent, KConfig *config, KileInfo *ki, - KileDocument::LatexCommands *commands); - ~MathEnvironmentDialog() {} - - public Q_SLOTS: - void slotAccepted(); - - private Q_SLOTS: - void slotEnvironmentChanged(int index); - void slotSpinboxValueChanged(int index); - - private: - KileInfo *m_ki; - KileDocument::LatexCommands *m_latexCommands; - - KComboBox *m_coEnvironment, *m_coTabulator, *m_coDisplaymath; - QCheckBox *m_cbStarred, *m_cbBullets; - QSpinBox *m_spRows, *m_spCols; - QLabel *m_lbRows, *m_lbCols, *m_lbSpace ; - QLabel *m_lbTabulator, *m_lbDisplaymath, *m_lbStarred; - QLabel *m_lbEnvironment, *m_lbBullets; - QLineEdit *m_edSpace; - - QString m_envname; - bool m_starred; - bool m_groups; - bool m_columns; - bool m_fixedcolumns; - bool m_mathmode; - QString m_tabulator; - QString m_parameter; - - void initEnvironments(); - bool isParameterEnv(); - bool isGroupsParameterEnv(); + Q_OBJECT + +public: + MathEnvironmentDialog(QWidget *parent, KConfig *config, KileInfo *ki, + KileDocument::LatexCommands *commands); + ~MathEnvironmentDialog() {} + +public Q_SLOTS: + void slotAccepted(); + +private Q_SLOTS: + void slotEnvironmentChanged(int index); + void slotSpinboxValueChanged(int index); + +private: + KileInfo *m_ki; + KileDocument::LatexCommands *m_latexCommands; + + KComboBox *m_coEnvironment, *m_coTabulator, *m_coDisplaymath; + QCheckBox *m_cbStarred, *m_cbBullets; + QSpinBox *m_spRows, *m_spCols; + QLabel *m_lbRows, *m_lbCols, *m_lbSpace ; + QLabel *m_lbTabulator, *m_lbDisplaymath, *m_lbStarred; + QLabel *m_lbEnvironment, *m_lbBullets; + QLineEdit *m_edSpace; + + QString m_envname; + bool m_starred; + bool m_groups; + bool m_columns; + bool m_fixedcolumns; + bool m_mathmode; + QString m_tabulator; + QString m_parameter; + + void initEnvironments(); + bool isParameterEnv(); + bool isGroupsParameterEnv(); }; } #endif diff --git a/src/dialogs/newfilewizard.cpp b/src/dialogs/newfilewizard.cpp index 3514a5b0..cece8f1a 100644 --- a/src/dialogs/newfilewizard.cpp +++ b/src/dialogs/newfilewizard.cpp @@ -1,216 +1,216 @@ /***************************************************************************************** begin : Sat Apr 26 2003 copyright : (C) 2003 by Jeroen Wijnhout (wijnhout@science.uva.nl) 2005 by Holger Danielsson (holger.danielsson@t-online.de) 2006-2014 by Michel Ludwig (michel.ludwig@kdemail.net) ******************************************************************************************/ /*************************************************************************** * * * 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. * * * ***************************************************************************/ #include "dialogs/newfilewizard.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "kiledebug.h" #include "widgets/newdocumentwidget.h" #define LATEX_TYPE 0 #define BIBTEX_TYPE 1 #define SCRIPT_TYPE 2 NewFileWizard::NewFileWizard(KileTemplate::Manager *templateManager, KileDocument::Type startType, QWidget *parent, const char *name) - : QDialog(parent), m_templateManager(templateManager), m_currentlyDisplayedType(-1) + : QDialog(parent), m_templateManager(templateManager), m_currentlyDisplayedType(-1) { - setObjectName(name); - setWindowTitle(i18n("New File")); - setModal(true); - - QVBoxLayout *mainLayout = new QVBoxLayout; - setLayout(mainLayout); - - // first read config - KConfigGroup newFileWizardGroup = KSharedConfig::openConfig()->group("NewFileWizard"); - bool wizard = newFileWizardGroup.readEntry("UseWizardWhenCreatingEmptyFile", false); - int w = newFileWizardGroup.readEntry("width", -1); - if(w == -1) { - w = width(); - } - int h = newFileWizardGroup.readEntry("height", -1); - if(h == -1) { - h = height(); - } - - m_newDocumentWidget = new NewDocumentWidget(this); - connect(m_newDocumentWidget->templateIconView, SIGNAL(itemDoubleClicked(QListWidgetItem*)), SLOT(okButtonClicked())); - m_templateManager->scanForTemplates(); - m_newDocumentWidget->templateIconView->setTemplateManager(m_templateManager); - - connect(m_newDocumentWidget->documentTypeComboBox, SIGNAL(activated(int)), this, SLOT(slotActivated(int))); - connect(m_newDocumentWidget->templateIconView, SIGNAL(classFileSearchFinished()), this, SLOT(restoreSelectedIcon())); - - mainLayout->addWidget(m_newDocumentWidget); - - m_newDocumentWidget->documentTypeComboBox->insertItem(LATEX_TYPE, i18n("LaTeX Document")); - m_newDocumentWidget->documentTypeComboBox->insertItem(BIBTEX_TYPE, i18n("BibTeX Document")); - m_newDocumentWidget->documentTypeComboBox->insertItem(SCRIPT_TYPE, i18n("Kile Script")); - - QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel); - QPushButton *okButton = buttonBox->button(QDialogButtonBox::Ok); - okButton->setDefault(true); - okButton->setShortcut(Qt::CTRL | Qt::Key_Return); - connect(buttonBox, SIGNAL(accepted()), this, SLOT(accept())); - connect(buttonBox, SIGNAL(accepted()), this, SLOT(okButtonClicked())); - connect(buttonBox, SIGNAL(rejected()), this, SLOT(reject())); - mainLayout->addWidget(buttonBox); - - // set config entries - m_newDocumentWidget->quickStartWizardCheckBox->setChecked(wizard); - resize(w,h); - - int index = 0; - switch(startType) { - default: // fall through - case KileDocument::LaTeX: - index = LATEX_TYPE; - break; - case KileDocument::BibTeX: - index = BIBTEX_TYPE; - break; - case KileDocument::Script: - index = SCRIPT_TYPE; - break; - } - - // select the document type - m_newDocumentWidget->documentTypeComboBox->setCurrentIndex(index); - m_currentlyDisplayedType = index; - displayType(index); + setObjectName(name); + setWindowTitle(i18n("New File")); + setModal(true); + + QVBoxLayout *mainLayout = new QVBoxLayout; + setLayout(mainLayout); + + // first read config + KConfigGroup newFileWizardGroup = KSharedConfig::openConfig()->group("NewFileWizard"); + bool wizard = newFileWizardGroup.readEntry("UseWizardWhenCreatingEmptyFile", false); + int w = newFileWizardGroup.readEntry("width", -1); + if(w == -1) { + w = width(); + } + int h = newFileWizardGroup.readEntry("height", -1); + if(h == -1) { + h = height(); + } + + m_newDocumentWidget = new NewDocumentWidget(this); + connect(m_newDocumentWidget->templateIconView, SIGNAL(itemDoubleClicked(QListWidgetItem*)), SLOT(okButtonClicked())); + m_templateManager->scanForTemplates(); + m_newDocumentWidget->templateIconView->setTemplateManager(m_templateManager); + + connect(m_newDocumentWidget->documentTypeComboBox, SIGNAL(activated(int)), this, SLOT(slotActivated(int))); + connect(m_newDocumentWidget->templateIconView, SIGNAL(classFileSearchFinished()), this, SLOT(restoreSelectedIcon())); + + mainLayout->addWidget(m_newDocumentWidget); + + m_newDocumentWidget->documentTypeComboBox->insertItem(LATEX_TYPE, i18n("LaTeX Document")); + m_newDocumentWidget->documentTypeComboBox->insertItem(BIBTEX_TYPE, i18n("BibTeX Document")); + m_newDocumentWidget->documentTypeComboBox->insertItem(SCRIPT_TYPE, i18n("Kile Script")); + + QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel); + QPushButton *okButton = buttonBox->button(QDialogButtonBox::Ok); + okButton->setDefault(true); + okButton->setShortcut(Qt::CTRL | Qt::Key_Return); + connect(buttonBox, SIGNAL(accepted()), this, SLOT(accept())); + connect(buttonBox, SIGNAL(accepted()), this, SLOT(okButtonClicked())); + connect(buttonBox, SIGNAL(rejected()), this, SLOT(reject())); + mainLayout->addWidget(buttonBox); + + // set config entries + m_newDocumentWidget->quickStartWizardCheckBox->setChecked(wizard); + resize(w,h); + + int index = 0; + switch(startType) { + default: // fall through + case KileDocument::LaTeX: + index = LATEX_TYPE; + break; + case KileDocument::BibTeX: + index = BIBTEX_TYPE; + break; + case KileDocument::Script: + index = SCRIPT_TYPE; + break; + } + + // select the document type + m_newDocumentWidget->documentTypeComboBox->setCurrentIndex(index); + m_currentlyDisplayedType = index; + displayType(index); } NewFileWizard::~NewFileWizard() { } TemplateItem* NewFileWizard::getSelection() const { - QList selectedItems = m_newDocumentWidget->templateIconView->selectedItems(); - if(selectedItems.isEmpty()) { - return Q_NULLPTR; - } - return static_cast(selectedItems.first()); + QList selectedItems = m_newDocumentWidget->templateIconView->selectedItems(); + if(selectedItems.isEmpty()) { + return Q_NULLPTR; + } + return static_cast(selectedItems.first()); } bool NewFileWizard::useWizard() { - // check (among other things) whether we want to create a LaTeX document - return ((m_newDocumentWidget->documentTypeComboBox->currentIndex() == 0) - && getSelection() - && (getSelection()->name() == KileTemplate::Manager::defaultEmptyTemplateCaption() - || getSelection()->name() == KileTemplate::Manager::defaultEmptyLaTeXTemplateCaption()) - && m_newDocumentWidget->quickStartWizardCheckBox->isChecked()); + // check (among other things) whether we want to create a LaTeX document + return ((m_newDocumentWidget->documentTypeComboBox->currentIndex() == 0) + && getSelection() + && (getSelection()->name() == KileTemplate::Manager::defaultEmptyTemplateCaption() + || getSelection()->name() == KileTemplate::Manager::defaultEmptyLaTeXTemplateCaption()) + && m_newDocumentWidget->quickStartWizardCheckBox->isChecked()); } QString NewFileWizard::getConfigKey(int index) { - QString configKey = "NewFileWizardSelectedIcon"; - switch(index) { - case LATEX_TYPE: - configKey += "LaTeX"; - break; - - case BIBTEX_TYPE: - configKey += "BibTeX"; - break; - - case SCRIPT_TYPE: - configKey += "Script"; - break; - } - return configKey; + QString configKey = "NewFileWizardSelectedIcon"; + switch(index) { + case LATEX_TYPE: + configKey += "LaTeX"; + break; + + case BIBTEX_TYPE: + configKey += "BibTeX"; + break; + + case SCRIPT_TYPE: + configKey += "Script"; + break; + } + return configKey; } void NewFileWizard::storeSelectedIcon() { - if(m_currentlyDisplayedType < 0) { - return; - } - TemplateItem *selectedItem = getSelection(); - if (selectedItem) { - KSharedConfig::openConfig()->group("default").writeEntry(getConfigKey(m_currentlyDisplayedType), selectedItem->name()); - } + if(m_currentlyDisplayedType < 0) { + return; + } + TemplateItem *selectedItem = getSelection(); + if (selectedItem) { + KSharedConfig::openConfig()->group("default").writeEntry(getConfigKey(m_currentlyDisplayedType), selectedItem->name()); + } } void NewFileWizard::restoreSelectedIcon() { - KConfigGroup defaultGroup = KSharedConfig::openConfig()->group("default"); - QString selectedIconName = defaultGroup.readEntry(getConfigKey(m_currentlyDisplayedType), - KileTemplate::Manager::defaultEmptyTemplateCaption()); - QList items = m_newDocumentWidget->templateIconView->findItems(selectedIconName, Qt::MatchExactly); - if(items.count() > 0) { - items[0]->setSelected(true); - } + KConfigGroup defaultGroup = KSharedConfig::openConfig()->group("default"); + QString selectedIconName = defaultGroup.readEntry(getConfigKey(m_currentlyDisplayedType), + KileTemplate::Manager::defaultEmptyTemplateCaption()); + QList items = m_newDocumentWidget->templateIconView->findItems(selectedIconName, Qt::MatchExactly); + if(items.count() > 0) { + items[0]->setSelected(true); + } } void NewFileWizard::okButtonClicked() { - KConfigGroup newFileWizardGroup = KSharedConfig::openConfig()->group("NewFileWizard"); + KConfigGroup newFileWizardGroup = KSharedConfig::openConfig()->group("NewFileWizard"); - newFileWizardGroup.writeEntry("UseWizardWhenCreatingEmptyFile", m_newDocumentWidget->quickStartWizardCheckBox->isChecked()); - newFileWizardGroup.writeEntry("width", width()); - newFileWizardGroup.writeEntry("height", height()); + newFileWizardGroup.writeEntry("UseWizardWhenCreatingEmptyFile", m_newDocumentWidget->quickStartWizardCheckBox->isChecked()); + newFileWizardGroup.writeEntry("width", width()); + newFileWizardGroup.writeEntry("height", height()); - storeSelectedIcon(); - accept(); + storeSelectedIcon(); + accept(); } void NewFileWizard::slotActivated(int index) { - storeSelectedIcon(); - m_currentlyDisplayedType = index; - displayType(index); + storeSelectedIcon(); + m_currentlyDisplayedType = index; + displayType(index); } void NewFileWizard::displayType(int index) { - switch(index) { - case LATEX_TYPE: - m_newDocumentWidget->templateIconView->fillWithTemplates(KileDocument::LaTeX); - break; - - case BIBTEX_TYPE: - m_newDocumentWidget->templateIconView->fillWithTemplates(KileDocument::BibTeX); - break; - - case SCRIPT_TYPE: - m_newDocumentWidget->templateIconView->fillWithTemplates(KileDocument::Script); - break; - } - m_newDocumentWidget->quickStartWizardCheckBox->setEnabled((index == 0)); - - // and select an icon - restoreSelectedIcon(); + switch(index) { + case LATEX_TYPE: + m_newDocumentWidget->templateIconView->fillWithTemplates(KileDocument::LaTeX); + break; + + case BIBTEX_TYPE: + m_newDocumentWidget->templateIconView->fillWithTemplates(KileDocument::BibTeX); + break; + + case SCRIPT_TYPE: + m_newDocumentWidget->templateIconView->fillWithTemplates(KileDocument::Script); + break; + } + m_newDocumentWidget->quickStartWizardCheckBox->setEnabled((index == 0)); + + // and select an icon + restoreSelectedIcon(); } diff --git a/src/dialogs/newfilewizard.h b/src/dialogs/newfilewizard.h index 4f4e1741..bb7ed3e1 100644 --- a/src/dialogs/newfilewizard.h +++ b/src/dialogs/newfilewizard.h @@ -1,61 +1,61 @@ /***************************************************************************************** begin : Sat Apr 26 2003 copyright : (C) 2003 by Jeroen Wijnhout (Jeroen.Wijnhout@kdemail.net) 2007-2008 by Michel Ludwig (michel.ludwig@kdemail.net) *****************************************************************************************/ /*************************************************************************** * * * 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. * * * ***************************************************************************/ #ifndef NEWFILEWIZARD_H #define NEWFILEWIZARD_H #include #include #include #include #include "kileconstants.h" #include "templates.h" class NewDocumentWidget; class NewFileWizard : public QDialog { - Q_OBJECT + Q_OBJECT public: - explicit NewFileWizard(KileTemplate::Manager *manager, KileDocument::Type startType = KileDocument::LaTeX, - QWidget *parent = Q_NULLPTR, const char *name = Q_NULLPTR); - ~NewFileWizard(); + explicit NewFileWizard(KileTemplate::Manager *manager, KileDocument::Type startType = KileDocument::LaTeX, + QWidget *parent = Q_NULLPTR, const char *name = Q_NULLPTR); + ~NewFileWizard(); public: - TemplateItem* getSelection() const; - bool useWizard(); + TemplateItem* getSelection() const; + bool useWizard(); protected Q_SLOTS: - void okButtonClicked(); + void okButtonClicked(); - void slotActivated(int index); + void slotActivated(int index); - void restoreSelectedIcon(); + void restoreSelectedIcon(); protected: - KileTemplate::Manager *m_templateManager; - NewDocumentWidget* m_newDocumentWidget; - int m_currentlyDisplayedType; // not a document type, only a local type! + KileTemplate::Manager *m_templateManager; + NewDocumentWidget* m_newDocumentWidget; + int m_currentlyDisplayedType; // not a document type, only a local type! - QString getConfigKey(int index); + QString getConfigKey(int index); - void storeSelectedIcon(); - void displayType(int index); + void storeSelectedIcon(); + void displayType(int index); }; #endif diff --git a/src/dialogs/newtoolwizard.cpp b/src/dialogs/newtoolwizard.cpp index 9b741940..28d55017 100644 --- a/src/dialogs/newtoolwizard.cpp +++ b/src/dialogs/newtoolwizard.cpp @@ -1,92 +1,92 @@ /************************************************************************** * Copyright (C) 2007 by Michel Ludwig (michel.ludwig@kdemail.net) * ***************************************************************************/ /************************************************************************** * * * 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. * * * ***************************************************************************/ #include "dialogs/newtoolwizard.h" #include "kiletoolmanager.h" #include #include NewToolWizard::NewToolWizard(QWidget *parent, Qt::WindowFlags fl) : KAssistantDialog(parent, fl) { - QWidget *toolNameWidget = new QWidget(this); - Ui::NewToolWizardToolNamePage::setupUi(toolNameWidget); - toolNamePage = new KPageWidgetItem(toolNameWidget, i18n("Tool Name")); + QWidget *toolNameWidget = new QWidget(this); + Ui::NewToolWizardToolNamePage::setupUi(toolNameWidget); + toolNamePage = new KPageWidgetItem(toolNameWidget, i18n("Tool Name")); - QWidget *classWidget = new QWidget(this); - Ui::NewToolWizardClassPage::setupUi(classWidget); - classPage = new KPageWidgetItem(classWidget, i18n("Class")); + QWidget *classWidget = new QWidget(this); + Ui::NewToolWizardClassPage::setupUi(classWidget); + classPage = new KPageWidgetItem(classWidget, i18n("Class")); - addPage(toolNamePage); - addPage(classPage); + addPage(toolNamePage); + addPage(classPage); - m_toolList = KileTool::toolList(KSharedConfig::openConfig().data(), false); + m_toolList = KileTool::toolList(KSharedConfig::openConfig().data(), false); - buttonBox()->button(QDialogButtonBox::Help)->setVisible(false); + buttonBox()->button(QDialogButtonBox::Help)->setVisible(false); - connect(this, SIGNAL(currentPageChanged(KPageWidgetItem*, KPageWidgetItem*)), this, SLOT(slotCurrentPageChanged(KPageWidgetItem*, KPageWidgetItem*))); - connect(m_leName, SIGNAL(textChanged(const QString &)), this, SLOT(nameChanged(const QString &))); - setValid(toolNamePage, false); + connect(this, SIGNAL(currentPageChanged(KPageWidgetItem*, KPageWidgetItem*)), this, SLOT(slotCurrentPageChanged(KPageWidgetItem*, KPageWidgetItem*))); + connect(m_leName, SIGNAL(textChanged(const QString &)), this, SLOT(nameChanged(const QString &))); + setValid(toolNamePage, false); - //setup the Behavior page (page 1) - m_cbTools->addItem(customTool()); - m_cbTools->addItems(m_toolList); + //setup the Behavior page (page 1) + m_cbTools->addItem(customTool()); + m_cbTools->addItems(m_toolList); } QString NewToolWizard::customTool() { - return i18n(""); + return i18n(""); } QString NewToolWizard::toolName() { - return m_leName->text(); + return m_leName->text(); } QString NewToolWizard::parentTool() { - return m_cbTools->currentText(); + return m_cbTools->currentText(); } void NewToolWizard::nameChanged(const QString &name) { - static QRegExp reBracket = QRegExp("\\(|\\)|\\[|\\]"); - bool ok = true; - - if(m_toolList.contains(name)) { - m_lbWarning->setText(i18n( "Error: A tool by this name exists already." )); - ok = false; - } - else if(name.indexOf("/") != -1) { - m_lbWarning->setText(i18n( "Error: The name may not contain a slash '/'." )); - ok = false; - } - else if(name.indexOf(reBracket) != -1) { - m_lbWarning->setText(i18n("Error: The name may not contain a (, ), [, or ].")); - ok = false; - } - else { - m_lbWarning->setText(""); - } - setValid(toolNamePage, ok); + static QRegExp reBracket = QRegExp("\\(|\\)|\\[|\\]"); + bool ok = true; + + if(m_toolList.contains(name)) { + m_lbWarning->setText(i18n( "Error: A tool by this name exists already." )); + ok = false; + } + else if(name.indexOf("/") != -1) { + m_lbWarning->setText(i18n( "Error: The name may not contain a slash '/'." )); + ok = false; + } + else if(name.indexOf(reBracket) != -1) { + m_lbWarning->setText(i18n("Error: The name may not contain a (, ), [, or ].")); + ok = false; + } + else { + m_lbWarning->setText(""); + } + setValid(toolNamePage, ok); } void NewToolWizard::slotCurrentPageChanged(KPageWidgetItem* current, KPageWidgetItem* /* before */) { - if (current == toolNamePage) { - m_leName->setFocus(); - } - else if (current == classPage) { - m_cbTools->setFocus(); - } + if (current == toolNamePage) { + m_leName->setFocus(); + } + else if (current == classPage) { + m_cbTools->setFocus(); + } } diff --git a/src/dialogs/newtoolwizard.h b/src/dialogs/newtoolwizard.h index 52e76275..2bbc9b08 100644 --- a/src/dialogs/newtoolwizard.h +++ b/src/dialogs/newtoolwizard.h @@ -1,42 +1,42 @@ /************************************************************************** * Copyright (C) 2007 by Michel Ludwig (michel.ludwig@kdemail.net) * ***************************************************************************/ /************************************************************************** * * * 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. * * * ***************************************************************************/ #ifndef NEWTOOLWIZARD_H #define NEWTOOLWIZARD_H #include "kassistantdialog.h" #include "ui_newtoolwizard_class_page.h" #include "ui_newtoolwizard_toolname_page.h" class NewToolWizard : public KAssistantDialog, public Ui::NewToolWizardToolNamePage, public Ui::NewToolWizardClassPage { - Q_OBJECT - - public: - explicit NewToolWizard(QWidget *parent = 0, Qt::WindowFlags fl = 0); - - virtual QString customTool(); - virtual QString toolName(); - virtual QString parentTool(); - - protected Q_SLOTS: - void nameChanged(const QString & name); - void slotCurrentPageChanged(KPageWidgetItem* current, KPageWidgetItem* before); - - private: - QStringList m_toolList; - KPageWidgetItem *toolNamePage, *classPage; + Q_OBJECT + +public: + explicit NewToolWizard(QWidget *parent = 0, Qt::WindowFlags fl = 0); + + virtual QString customTool(); + virtual QString toolName(); + virtual QString parentTool(); + +protected Q_SLOTS: + void nameChanged(const QString & name); + void slotCurrentPageChanged(KPageWidgetItem* current, KPageWidgetItem* before); + +private: + QStringList m_toolList; + KPageWidgetItem *toolNamePage, *classPage; }; #endif diff --git a/src/dialogs/pdf-wizard/pdfdialog.cpp b/src/dialogs/pdf-wizard/pdfdialog.cpp old mode 100755 new mode 100644 index 7a4504ea..836b7836 --- a/src/dialogs/pdf-wizard/pdfdialog.cpp +++ b/src/dialogs/pdf-wizard/pdfdialog.cpp @@ -1,1790 +1,1791 @@ /****************************************************************************** Copyright (C) 2009-2011 by Holger Danielsson (holger.danielsson@versanet.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. * * * ***************************************************************************/ #include "pdfdialog.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "errorhandler.h" #include "kileconfig.h" #include "kiledebug.h" namespace KileDialog { PdfDialog::PdfDialog(QWidget *parent, const QString &texfilename,const QString &startdir, const QString &latexextensions, KileTool::Manager *manager, KileErrorHandler *errorHandler, KileWidget::OutputView *output) - : QDialog(parent) - , m_startdir(startdir) - , m_manager(manager) - , m_errorHandler(errorHandler) - , m_output(output) - , m_proc(Q_NULLPTR) - , m_rearrangeButton(new QPushButton) - , m_buttonBox(new QDialogButtonBox(QDialogButtonBox::Help|QDialogButtonBox::Close)) + : QDialog(parent) + , m_startdir(startdir) + , m_manager(manager) + , m_errorHandler(errorHandler) + , m_output(output) + , m_proc(Q_NULLPTR) + , m_rearrangeButton(new QPushButton) + , m_buttonBox(new QDialogButtonBox(QDialogButtonBox::Help|QDialogButtonBox::Close)) { - setWindowTitle(i18n("PDF Wizard")); - setModal(true); - QVBoxLayout *mainLayout = new QVBoxLayout; - setLayout(mainLayout); - m_rearrangeButton->setDefault(true); - - // determine if a pdffile already exists - QString pdffilename; - if(!texfilename.isEmpty()) { - // working with a pdf document, so we try to determine the LaTeX source file - QStringList extlist = latexextensions.split(' '); - for (QStringList::Iterator it = extlist.begin(); it != extlist.end(); ++it) { - if (texfilename.indexOf((*it), -(*it).length()) >= 0) { - pdffilename = texfilename.left(texfilename.length() - (*it).length()) + ".pdf"; - if (!QFileInfo(pdffilename).exists()) - pdffilename.clear(); - break; - } - } - } - - // prepare dialog - QWidget *page = new QWidget(this); - mainLayout->addWidget(page); - m_PdfDialog.setupUi(page); - page->setMinimumWidth(500); - m_PdfDialog.m_pbPrinting->setIcon(QIcon::fromTheme("printer")); - m_PdfDialog.m_pbAll->setIcon(QIcon::fromTheme("list-add")); - m_PdfDialog.m_pbBackgroundColor->setColor(QColor(255, 255, 224)); - - // insert KileWidget::CategoryComboBox - m_cbTask = new KileWidget::CategoryComboBox(m_PdfDialog.m_gbParameter); - QGridLayout *paramLayout = (QGridLayout *)m_PdfDialog.m_gbParameter->layout(); - paramLayout->addWidget(m_cbTask, 4, 1); - - // setup filenames - m_PdfDialog.m_edInfile->setFilter(i18n("*.pdf|PDF Files")); - m_PdfDialog.m_edInfile->lineEdit()->setText(pdffilename); - m_PdfDialog.m_edOutfile->setFilter(i18n("*.pdf|PDF Files")); - m_PdfDialog.m_edOutfile->setMode(KFile::File | KFile::LocalOnly ); - m_PdfDialog.m_edOutfile->lineEdit()->setText( getOutfileName(pdffilename) ); - - //max password length for pdf files - m_PdfDialog.m_edPassword->setMaxLength(32); - - // set an user button to execute the task and icon for help button - m_rearrangeButton->setText(i18n("Re&arrange")); - m_rearrangeButton->setIcon(QIcon::fromTheme("system-run")); - m_PdfDialog.m_lbParameterIcon->setPixmap(KIconLoader::global()->loadIcon("help-about", KIconLoader::NoGroup, KIconLoader::SizeSmallMedium)); - - // init important variables - m_numpages = 0; - m_encrypted = false; - m_pdftk = false; - m_pdfpages = false; - m_scriptrunning = false; - m_pagesize = QSize(0,0); - - // setup tasks - m_tasklist << i18n("1 Page + Empty Page --> 2up") // 0 PDF_PAGE_EMPTY - << i18n("1 Page + Duplicate --> 2up") // 1 PDF_PAGE_DUPLICATE - << i18n("2 Pages --> 2up") // 2 PDF_2UP - << i18n("2 Pages (landscape) --> 2up") // 3 PDF_2UP_LANDSCAPE - << i18n("4 Pages --> 4up") // 4 PDF_4UP - << i18n("4 Pages (landscape) --> 4up") // 5 PDF_4UP_LANDSCAPE - << i18n("Select Even Pages") // 6 PDF_EVEN - << i18n("Select Odd Pages") // 7 PDF_ODD - << i18n("Select Even Pages (reverse order)") // 8 PDF_EVEN_REV - << i18n("Select Odd Pages (reverse order)") // 9 PDF_ODD_REV - << i18n("Reverse All Pages") // 10 PDF_REVERSE - << i18n("Decrypt") // 11 PDF_DECRYPT - << i18n("Select Pages") // 12 PDF_SELECT - << i18n("Delete Pages") // 13 PDF_DELETE - << i18n("Apply a background watermark") // 14 PDF_PDFTK_BACKGROUND - << i18n("Apply a background color") // 15 PDF_PDFTK_BGCOLOR - << i18n("Apply a foreground stamp") // 16 PDF_PDFTK_STAMP - << i18n("pdftk: Choose Parameter") // 17 PDF_PDFTK_FREE - << i18n("pdfpages: Choose Parameter") // 18 PDF_PDFPAGES_FREE - ; - - // set data for properties: key/widget - m_pdfInfoKeys << "Title" << "Subject" << "Author" << "Creator" << "Producer" << "Keywords"; - - m_pdfInfoWidget["Title"] = m_PdfDialog.m_leTitle; - m_pdfInfoWidget["Subject"] = m_PdfDialog.m_leSubject; - m_pdfInfoWidget["Keywords"] = m_PdfDialog.m_leKeywords; - m_pdfInfoWidget["Author"] = m_PdfDialog.m_leAuthor; - m_pdfInfoWidget["Creator"] = m_PdfDialog.m_leCreator; - m_pdfInfoWidget["Producer"] = m_PdfDialog.m_leProducer; - - // set data for permissions: key/widget - m_pdfPermissionKeys << AllowModify << AllowCopy << AllowPrint - << AllowNotes << AllowFillForms; - - m_pdfPermissionWidgets << m_PdfDialog.m_cbModify << m_PdfDialog.m_cbCopy << m_PdfDialog.m_cbPrinting - << m_PdfDialog.m_cbAnnotations << m_PdfDialog.m_cbFormFeeds; - - m_pdfPermissionPdftk << "ModifyContents" << "CopyContents" << "Printing" - << "ModifyAnnotations" << "FillIn"; - - // default permissions - m_pdfPermissionState << false << false << false << false << false; - - // check for libpoppler pdf library + setWindowTitle(i18n("PDF Wizard")); + setModal(true); + QVBoxLayout *mainLayout = new QVBoxLayout; + setLayout(mainLayout); + m_rearrangeButton->setDefault(true); + + // determine if a pdffile already exists + QString pdffilename; + if(!texfilename.isEmpty()) { + // working with a pdf document, so we try to determine the LaTeX source file + QStringList extlist = latexextensions.split(' '); + for (QStringList::Iterator it = extlist.begin(); it != extlist.end(); ++it) { + if (texfilename.indexOf((*it), -(*it).length()) >= 0) { + pdffilename = texfilename.left(texfilename.length() - (*it).length()) + ".pdf"; + if (!QFileInfo(pdffilename).exists()) + pdffilename.clear(); + break; + } + } + } + + // prepare dialog + QWidget *page = new QWidget(this); + mainLayout->addWidget(page); + m_PdfDialog.setupUi(page); + page->setMinimumWidth(500); + m_PdfDialog.m_pbPrinting->setIcon(QIcon::fromTheme("printer")); + m_PdfDialog.m_pbAll->setIcon(QIcon::fromTheme("list-add")); + m_PdfDialog.m_pbBackgroundColor->setColor(QColor(255, 255, 224)); + + // insert KileWidget::CategoryComboBox + m_cbTask = new KileWidget::CategoryComboBox(m_PdfDialog.m_gbParameter); + QGridLayout *paramLayout = (QGridLayout *)m_PdfDialog.m_gbParameter->layout(); + paramLayout->addWidget(m_cbTask, 4, 1); + + // setup filenames + m_PdfDialog.m_edInfile->setFilter(i18n("*.pdf|PDF Files")); + m_PdfDialog.m_edInfile->lineEdit()->setText(pdffilename); + m_PdfDialog.m_edOutfile->setFilter(i18n("*.pdf|PDF Files")); + m_PdfDialog.m_edOutfile->setMode(KFile::File | KFile::LocalOnly ); + m_PdfDialog.m_edOutfile->lineEdit()->setText( getOutfileName(pdffilename) ); + + //max password length for pdf files + m_PdfDialog.m_edPassword->setMaxLength(32); + + // set an user button to execute the task and icon for help button + m_rearrangeButton->setText(i18n("Re&arrange")); + m_rearrangeButton->setIcon(QIcon::fromTheme("system-run")); + m_PdfDialog.m_lbParameterIcon->setPixmap(KIconLoader::global()->loadIcon("help-about", KIconLoader::NoGroup, KIconLoader::SizeSmallMedium)); + + // init important variables + m_numpages = 0; + m_encrypted = false; + m_pdftk = false; + m_pdfpages = false; + m_scriptrunning = false; + m_pagesize = QSize(0,0); + + // setup tasks + m_tasklist << i18n("1 Page + Empty Page --> 2up") // 0 PDF_PAGE_EMPTY + << i18n("1 Page + Duplicate --> 2up") // 1 PDF_PAGE_DUPLICATE + << i18n("2 Pages --> 2up") // 2 PDF_2UP + << i18n("2 Pages (landscape) --> 2up") // 3 PDF_2UP_LANDSCAPE + << i18n("4 Pages --> 4up") // 4 PDF_4UP + << i18n("4 Pages (landscape) --> 4up") // 5 PDF_4UP_LANDSCAPE + << i18n("Select Even Pages") // 6 PDF_EVEN + << i18n("Select Odd Pages") // 7 PDF_ODD + << i18n("Select Even Pages (reverse order)") // 8 PDF_EVEN_REV + << i18n("Select Odd Pages (reverse order)") // 9 PDF_ODD_REV + << i18n("Reverse All Pages") // 10 PDF_REVERSE + << i18n("Decrypt") // 11 PDF_DECRYPT + << i18n("Select Pages") // 12 PDF_SELECT + << i18n("Delete Pages") // 13 PDF_DELETE + << i18n("Apply a background watermark") // 14 PDF_PDFTK_BACKGROUND + << i18n("Apply a background color") // 15 PDF_PDFTK_BGCOLOR + << i18n("Apply a foreground stamp") // 16 PDF_PDFTK_STAMP + << i18n("pdftk: Choose Parameter") // 17 PDF_PDFTK_FREE + << i18n("pdfpages: Choose Parameter") // 18 PDF_PDFPAGES_FREE + ; + + // set data for properties: key/widget + m_pdfInfoKeys << "Title" << "Subject" << "Author" << "Creator" << "Producer" << "Keywords"; + + m_pdfInfoWidget["Title"] = m_PdfDialog.m_leTitle; + m_pdfInfoWidget["Subject"] = m_PdfDialog.m_leSubject; + m_pdfInfoWidget["Keywords"] = m_PdfDialog.m_leKeywords; + m_pdfInfoWidget["Author"] = m_PdfDialog.m_leAuthor; + m_pdfInfoWidget["Creator"] = m_PdfDialog.m_leCreator; + m_pdfInfoWidget["Producer"] = m_PdfDialog.m_leProducer; + + // set data for permissions: key/widget + m_pdfPermissionKeys << AllowModify << AllowCopy << AllowPrint + << AllowNotes << AllowFillForms; + + m_pdfPermissionWidgets << m_PdfDialog.m_cbModify << m_PdfDialog.m_cbCopy << m_PdfDialog.m_cbPrinting + << m_PdfDialog.m_cbAnnotations << m_PdfDialog.m_cbFormFeeds; + + m_pdfPermissionPdftk << "ModifyContents" << "CopyContents" << "Printing" + << "ModifyAnnotations" << "FillIn"; + + // default permissions + m_pdfPermissionState << false << false << false << false << false; + + // check for libpoppler pdf library #if LIBPOPPLER_AVAILABLE m_poppler = true; KILE_DEBUG_MAIN << "working with libpoppler pdf library"; #else - m_poppler = false; - KILE_DEBUG_MAIN << "working without libpoppler pdf library"; - m_PdfDialog.tabWidget->removeTab(2); - m_PdfDialog.tabWidget->removeTab(1); + m_poppler = false; + KILE_DEBUG_MAIN << "working without libpoppler pdf library"; + m_PdfDialog.tabWidget->removeTab(2); + m_PdfDialog.tabWidget->removeTab(1); #endif - // init Dialog - m_PdfDialog.m_lbParameterInfo->setTextFormat(Qt::RichText); - m_PdfDialog.m_cbOverwrite->setChecked(true); - updateDialog(); + // init Dialog + m_PdfDialog.m_lbParameterInfo->setTextFormat(Qt::RichText); + m_PdfDialog.m_cbOverwrite->setChecked(true); + updateDialog(); - // create tempdir - m_tempdir = new QTemporaryDir(QDir::tempPath() + QLatin1Char('/') + "pdfwizard/pdf-"); - KILE_DEBUG_MAIN << "tempdir: " << m_tempdir->path() ; + // create tempdir + m_tempdir = new QTemporaryDir(QDir::tempPath() + QLatin1Char('/') + "pdfwizard/pdf-"); + KILE_DEBUG_MAIN << "tempdir: " << m_tempdir->path() ; - connect(this, &PdfDialog::output, m_output, &KileWidget::OutputView::receive); - connect(m_PdfDialog.m_edInfile->lineEdit(), &QLineEdit::textChanged, this, &PdfDialog::slotInputfileChanged); + connect(this, &PdfDialog::output, m_output, &KileWidget::OutputView::receive); + connect(m_PdfDialog.m_edInfile->lineEdit(), &QLineEdit::textChanged, this, &PdfDialog::slotInputfileChanged); #if LIBPOPPLER_AVAILABLE - connect(m_PdfDialog.tabWidget, SIGNAL(currentChanged(int)), this, SLOT(slotTabwidgetChanged(int))); - connect(m_PdfDialog.m_pbPrinting, SIGNAL(clicked()), this, SLOT(slotPrintingClicked())); - connect(m_PdfDialog.m_pbAll, SIGNAL(clicked()), this, SLOT(slotAllClicked())); + connect(m_PdfDialog.tabWidget, SIGNAL(currentChanged(int)), this, SLOT(slotTabwidgetChanged(int))); + connect(m_PdfDialog.m_pbPrinting, SIGNAL(clicked()), this, SLOT(slotPrintingClicked())); + connect(m_PdfDialog.m_pbAll, SIGNAL(clicked()), this, SLOT(slotAllClicked())); #endif - m_buttonBox->addButton(m_rearrangeButton, QDialogButtonBox::ActionRole); - connect(m_buttonBox, &QDialogButtonBox::accepted, this, &QDialog::accept); - connect(m_buttonBox, &QDialogButtonBox::rejected, this, &QDialog::reject); - connect(m_buttonBox, &QDialogButtonBox::helpRequested, this, &PdfDialog::slotShowHelp); - connect(m_rearrangeButton, &QPushButton::clicked, this, &PdfDialog::slotExecute); - mainLayout->addWidget(m_buttonBox); + m_buttonBox->addButton(m_rearrangeButton, QDialogButtonBox::ActionRole); + connect(m_buttonBox, &QDialogButtonBox::accepted, this, &QDialog::accept); + connect(m_buttonBox, &QDialogButtonBox::rejected, this, &QDialog::reject); + connect(m_buttonBox, &QDialogButtonBox::helpRequested, this, &PdfDialog::slotShowHelp); + connect(m_rearrangeButton, &QPushButton::clicked, this, &PdfDialog::slotExecute); + mainLayout->addWidget(m_buttonBox); - // find available utilities for this dialog - executeScript("kpsewhich pdfpages.sty", QString(), PDF_SCRIPTMODE_TOOLS); + // find available utilities for this dialog + executeScript("kpsewhich pdfpages.sty", QString(), PDF_SCRIPTMODE_TOOLS); } PdfDialog::~PdfDialog() { - if (m_cbTask->currentIndex() != -1) { - KileConfig::setPdfWizardLastTask(m_cbTask->currentIndex()); - } - delete m_tempdir; - delete m_proc; + if (m_cbTask->currentIndex() != -1) { + KileConfig::setPdfWizardLastTask(m_cbTask->currentIndex()); + } + delete m_tempdir; + delete m_proc; } void PdfDialog::initUtilities() { - // find pdfpages.sty? - m_pdfpages = m_outputtext.contains("pdfpages.sty"); + // find pdfpages.sty? + m_pdfpages = m_outputtext.contains("pdfpages.sty"); - // additionally look for pdftk - m_pdftk = !QStandardPaths::findExecutable("pdftk").isEmpty(); + // additionally look for pdftk + m_pdftk = !QStandardPaths::findExecutable("pdftk").isEmpty(); //m_pdfpages = false; // <----------- only for testing HACK //m_pdftk = false; // <----------- only for testing HACK - KILE_DEBUG_MAIN << "Looking for pdf tools: pdftk=" << m_pdftk << " pdfpages.sty=" << m_pdfpages; + KILE_DEBUG_MAIN << "Looking for pdf tools: pdftk=" << m_pdftk << " pdfpages.sty=" << m_pdfpages; #if !LIBPOPPLER_AVAILABLE - m_imagemagick = KileConfig::imagemagick(); - - // we can't use libpoppler pdf library and need to find another method to determine the number of pdf pages - // Kile will use three options before giving up - if ( m_pdftk ) - m_numpagesMode = PDF_SCRIPTMODE_NUMPAGES_PDFTK; - else if ( m_imagemagick ) - m_numpagesMode = PDF_SCRIPTMODE_NUMPAGES_IMAGEMAGICK; - else - m_numpagesMode = PDF_SCRIPTMODE_NUMPAGES_GHOSTSCRIPT; + m_imagemagick = KileConfig::imagemagick(); + + // we can't use libpoppler pdf library and need to find another method to determine the number of pdf pages + // Kile will use three options before giving up + if ( m_pdftk ) + m_numpagesMode = PDF_SCRIPTMODE_NUMPAGES_PDFTK; + else if ( m_imagemagick ) + m_numpagesMode = PDF_SCRIPTMODE_NUMPAGES_IMAGEMAGICK; + else + m_numpagesMode = PDF_SCRIPTMODE_NUMPAGES_GHOSTSCRIPT; #endif - // no pdftk, so properties and permissions are readonly - if ( !m_pdftk ) { - // set readonly properties - for (QStringList::const_iterator it = m_pdfInfoKeys.constBegin(); it != m_pdfInfoKeys.constEnd(); ++it) { - m_pdfInfoWidget[*it]->setReadOnly(true); - } + // no pdftk, so properties and permissions are readonly + if ( !m_pdftk ) { + // set readonly properties + for (QStringList::const_iterator it = m_pdfInfoKeys.constBegin(); it != m_pdfInfoKeys.constEnd(); ++it) { + m_pdfInfoWidget[*it]->setReadOnly(true); + } #if LIBPOPPLER_AVAILABLE - // connect permission widgets - for (int i=0; ilineEdit(), SIGNAL(textChanged(const QString &)), this, SLOT(slotOutputfileChanged(const QString &))); - connect(m_PdfDialog.m_cbOverwrite, SIGNAL(stateChanged(int)), this, SLOT(slotOverwriteChanged(int))); - connect(m_cbTask, SIGNAL(activated(int)), this, SLOT(slotTaskChanged(int))); - } + // if we found at least one utility, we can enable some connections + if ( m_pdftk || m_pdfpages) { + connect(m_PdfDialog.m_edOutfile->lineEdit(), SIGNAL(textChanged(const QString &)), this, SLOT(slotOutputfileChanged(const QString &))); + connect(m_PdfDialog.m_cbOverwrite, SIGNAL(stateChanged(int)), this, SLOT(slotOverwriteChanged(int))); + connect(m_cbTask, SIGNAL(activated(int)), this, SLOT(slotTaskChanged(int))); + } - // setup dialog - slotInputfileChanged(m_PdfDialog.m_edInfile->lineEdit()->text()); + // setup dialog + slotInputfileChanged(m_PdfDialog.m_edInfile->lineEdit()->text()); } // read properties and permissions from the PDF document void PdfDialog::pdfParser(const QString &filename) { #if LIBPOPPLER_AVAILABLE - Poppler::Document *doc = Poppler::Document::load(filename); - if ( !doc || doc->isLocked() ) { - KILE_DEBUG_MAIN << "Error: could not open pdf document '" << filename << "'"; - return; - } - KILE_DEBUG_MAIN << "Parse pdf document: " << filename; - - // read encryption - m_encrypted = doc->isEncrypted(); - m_PdfDialog.m_lbEncryption->setText( (m_encrypted) ? i18n("yes") : i18n("no") ); - - // read properties - for (QStringList::const_iterator it = m_pdfInfoKeys.constBegin(); it != m_pdfInfoKeys.constEnd(); ++it) { - QString value = doc->info(*it); - m_pdfInfo[*it] = value; - m_pdfInfoWidget[*it]->setText(value); - } - - // read creation date and modification date - m_PdfDialog.m_lbCreationDate->setText(QLocale().toString(doc->date("CreationDate"))); - m_PdfDialog.m_lbModDate->setText(QLocale().toString(doc->date("ModDate"))); - - // read PDF version - int major,minor; - doc->getPdfVersion(&major,&minor); - m_PdfDialog.m_lbFormat->setText( QString("PDF version %1.%2").arg(major).arg(minor) ); - - // read permissions - for (int i=0; isetChecked(value); - - if ( !m_pdftk ) { - m_pdfPermissionState[i] = value; - } - } - - // determine and set number of pages - setNumberOfPages( doc->numPages() ); - - // look if all pages have the same size - m_pagesize = allPagesSize(doc); - - delete doc; + Poppler::Document *doc = Poppler::Document::load(filename); + if ( !doc || doc->isLocked() ) { + KILE_DEBUG_MAIN << "Error: could not open pdf document '" << filename << "'"; + return; + } + KILE_DEBUG_MAIN << "Parse pdf document: " << filename; + + // read encryption + m_encrypted = doc->isEncrypted(); + m_PdfDialog.m_lbEncryption->setText( (m_encrypted) ? i18n("yes") : i18n("no") ); + + // read properties + for (QStringList::const_iterator it = m_pdfInfoKeys.constBegin(); it != m_pdfInfoKeys.constEnd(); ++it) { + QString value = doc->info(*it); + m_pdfInfo[*it] = value; + m_pdfInfoWidget[*it]->setText(value); + } + + // read creation date and modification date + m_PdfDialog.m_lbCreationDate->setText(QLocale().toString(doc->date("CreationDate"))); + m_PdfDialog.m_lbModDate->setText(QLocale().toString(doc->date("ModDate"))); + + // read PDF version + int major,minor; + doc->getPdfVersion(&major,&minor); + m_PdfDialog.m_lbFormat->setText( QString("PDF version %1.%2").arg(major).arg(minor) ); + + // read permissions + for (int i=0; isetChecked(value); + + if ( !m_pdftk ) { + m_pdfPermissionState[i] = value; + } + } + + // determine and set number of pages + setNumberOfPages( doc->numPages() ); + + // look if all pages have the same size + m_pagesize = allPagesSize(doc); + + delete doc; #else - /* libpoppler pdf library is not available: - * - we use a brute force method to determine, if this file is encrypted - * - then we try to determine the number of pages with - * - pdftk (always first choice, if installed) - * - imagemagick (second choice) - * - gs (third and last choice) - * - if the pdf file is encrypted, pdftk will ask for a password - */ - - // look if the pdf file is encrypted (brute force) - m_encrypted = readEncryption(filename); - KILE_DEBUG_MAIN << "PDF encryption: " << m_encrypted; - - // determine the number of pages of the pdf file - determineNumberOfPages(filename,m_encrypted); - KILE_DEBUG_MAIN << "PDF number of pages: " << m_numpages; - - // clear pagesize - m_pagesize = QSize(0,0); + /* libpoppler pdf library is not available: + * - we use a brute force method to determine, if this file is encrypted + * - then we try to determine the number of pages with + * - pdftk (always first choice, if installed) + * - imagemagick (second choice) + * - gs (third and last choice) + * - if the pdf file is encrypted, pdftk will ask for a password + */ + + // look if the pdf file is encrypted (brute force) + m_encrypted = readEncryption(filename); + KILE_DEBUG_MAIN << "PDF encryption: " << m_encrypted; + + // determine the number of pages of the pdf file + determineNumberOfPages(filename,m_encrypted); + KILE_DEBUG_MAIN << "PDF number of pages: " << m_numpages; + + // clear pagesize + m_pagesize = QSize(0,0); #endif } #if LIBPOPPLER_AVAILABLE bool PdfDialog::isAllowed(Poppler::Document *doc, PDF_Permission permission) const { bool b = true; switch ( permission ) { - case AllowModify: - b = doc->okToChange(); - break; - case AllowCopy: - b = doc->okToCopy(); - break; - case AllowPrint: - b = doc->okToPrint(); - break; - case AllowNotes: - b = doc->okToAddNotes(); - break; - case AllowFillForms: - b = doc->okToFillForm(); - break; - default: ; + case AllowModify: + b = doc->okToChange(); + break; + case AllowCopy: + b = doc->okToCopy(); + break; + case AllowPrint: + b = doc->okToPrint(); + break; + case AllowNotes: + b = doc->okToAddNotes(); + break; + case AllowFillForms: + b = doc->okToFillForm(); + break; + default: + ; } return b; } QSize PdfDialog::allPagesSize(Poppler::Document *doc) { - QSize commonsize = QSize(0,0); - - // Access all pages of the PDF file (m_numpages is known) - for ( int i=0; ipage(i); - if ( pdfpage == 0 ) { - KILE_DEBUG_MAIN << "Cannot parse all pages of the PDF file"; - delete pdfpage; - return QSize(0,0); - } - - if ( i == 0 ) { - commonsize = pdfpage->pageSize(); - } else if ( commonsize != pdfpage->pageSize() ) { - delete pdfpage; - return QSize(0,0); - } - // documentation says: after the usage, the page must be deleted - delete pdfpage; - } - - return commonsize; + QSize commonsize = QSize(0,0); + + // Access all pages of the PDF file (m_numpages is known) + for ( int i=0; ipage(i); + if ( pdfpage == 0 ) { + KILE_DEBUG_MAIN << "Cannot parse all pages of the PDF file"; + delete pdfpage; + return QSize(0,0); + } + + if ( i == 0 ) { + commonsize = pdfpage->pageSize(); + } else if ( commonsize != pdfpage->pageSize() ) { + delete pdfpage; + return QSize(0,0); + } + // documentation says: after the usage, the page must be deleted + delete pdfpage; + } + + return commonsize; } #endif void PdfDialog::setNumberOfPages(int numpages) { - m_numpages = numpages; - if (m_numpages > 0) { - // show all, if the number of pages is known - m_PdfDialog.tabWidget->widget(0)->setEnabled(true); - - QString pages; - if ( m_encrypted ) - m_PdfDialog.m_lbPages->setText(pages.setNum(m_numpages)+" "+i18n("(encrypted)")); - else - m_PdfDialog.m_lbPages->setText(pages.setNum(m_numpages)); - } - else { - // hide all, if the number of pages can't be determined - m_PdfDialog.tabWidget->widget(0)->setEnabled(false); - m_PdfDialog.m_lbPages->setText(i18n("Error: unknown number of pages")); - } + m_numpages = numpages; + if (m_numpages > 0) { + // show all, if the number of pages is known + m_PdfDialog.tabWidget->widget(0)->setEnabled(true); + + QString pages; + if ( m_encrypted ) + m_PdfDialog.m_lbPages->setText(pages.setNum(m_numpages)+" "+i18n("(encrypted)")); + else + m_PdfDialog.m_lbPages->setText(pages.setNum(m_numpages)); + } + else { + // hide all, if the number of pages can't be determined + m_PdfDialog.tabWidget->widget(0)->setEnabled(false); + m_PdfDialog.m_lbPages->setText(i18n("Error: unknown number of pages")); + } } #if !LIBPOPPLER_AVAILABLE void PdfDialog::determineNumberOfPages(const QString &filename, bool askForPassword) { - // determine the number of pages of the pdf file (delegate this task) - QString command; - QString passwordparam; - int scriptmode = m_numpagesMode; - - if ( scriptmode==PDF_SCRIPTMODE_NUMPAGES_PDFTK && askForPassword ) { - QString password = QInputDialog::getText(this, i18n("PDFTK-Password"), - i18n("This PDF file is encrypted and 'pdftk' cannot open it.\n" - "Please enter the password for this PDF file\n or leave it blank to try another method: "), - QLineEdit::Normal, QString()).trimmed(); - if(!password.isEmpty()) { - passwordparam = " input_pw " + password; - } - else { - scriptmode = ( m_imagemagick ) ? PDF_SCRIPTMODE_NUMPAGES_IMAGEMAGICK : PDF_SCRIPTMODE_NUMPAGES_GHOSTSCRIPT; - } - } - - // now take the original or changed mode - if ( scriptmode == PDF_SCRIPTMODE_NUMPAGES_PDFTK ) { - command = "pdftk \"" + filename + "\"" + passwordparam + " dump_data | grep NumberOfPages"; - } - else if ( scriptmode == PDF_SCRIPTMODE_NUMPAGES_IMAGEMAGICK ) { - command = "identify -format \"%n\" \"" + filename + "\""; - } - else { - command = "gs -q -c \"(" + filename + ") (r) file runpdfbegin pdfpagecount = quit\""; - } - - // run Process - KILE_DEBUG_MAIN << "execute for NumberOfPages: " << command; - executeScript(command, m_tempdir->path(), scriptmode); + // determine the number of pages of the pdf file (delegate this task) + QString command; + QString passwordparam; + int scriptmode = m_numpagesMode; + + if ( scriptmode==PDF_SCRIPTMODE_NUMPAGES_PDFTK && askForPassword ) { + QString password = QInputDialog::getText(this, i18n("PDFTK-Password"), + i18n("This PDF file is encrypted and 'pdftk' cannot open it.\n" + "Please enter the password for this PDF file\n or leave it blank to try another method: "), + QLineEdit::Normal, QString()).trimmed(); + if(!password.isEmpty()) { + passwordparam = " input_pw " + password; + } + else { + scriptmode = ( m_imagemagick ) ? PDF_SCRIPTMODE_NUMPAGES_IMAGEMAGICK : PDF_SCRIPTMODE_NUMPAGES_GHOSTSCRIPT; + } + } + + // now take the original or changed mode + if ( scriptmode == PDF_SCRIPTMODE_NUMPAGES_PDFTK ) { + command = "pdftk \"" + filename + "\"" + passwordparam + " dump_data | grep NumberOfPages"; + } + else if ( scriptmode == PDF_SCRIPTMODE_NUMPAGES_IMAGEMAGICK ) { + command = "identify -format \"%n\" \"" + filename + "\""; + } + else { + command = "gs -q -c \"(" + filename + ") (r) file runpdfbegin pdfpagecount = quit\""; + } + + // run Process + KILE_DEBUG_MAIN << "execute for NumberOfPages: " << command; + executeScript(command, m_tempdir->path(), scriptmode); } void PdfDialog::readNumberOfPages(int scriptmode, const QString &output) { - int numpages = 0; - - bool ok; - if ( scriptmode == PDF_SCRIPTMODE_NUMPAGES_PDFTK ) { - KILE_DEBUG_MAIN << "pdftk output for NumberOfPages: " << output; - if ( output.contains("OWNER PASSWORD REQUIRED") ) { - QString filename = m_PdfDialog.m_edInfile->lineEdit()->text().trimmed(); - determineNumberOfPages(m_PdfDialog.m_edInfile->lineEdit()->text().trimmed(),true); - return; - } else { - QRegExp re("\\d+"); - if ( re.indexIn(output) >= 0) { - numpages = re.cap(0).toInt(&ok); - } - } - - } - else { - QString s = output; - numpages = s.remove("\n").toInt(&ok); - } - - setNumberOfPages(numpages); + int numpages = 0; + + bool ok; + if ( scriptmode == PDF_SCRIPTMODE_NUMPAGES_PDFTK ) { + KILE_DEBUG_MAIN << "pdftk output for NumberOfPages: " << output; + if ( output.contains("OWNER PASSWORD REQUIRED") ) { + QString filename = m_PdfDialog.m_edInfile->lineEdit()->text().trimmed(); + determineNumberOfPages(m_PdfDialog.m_edInfile->lineEdit()->text().trimmed(),true); + return; + } else { + QRegExp re("\\d+"); + if ( re.indexIn(output) >= 0) { + numpages = re.cap(0).toInt(&ok); + } + } + + } + else { + QString s = output; + numpages = s.remove("\n").toInt(&ok); + } + + setNumberOfPages(numpages); } bool PdfDialog::readEncryption(const QString &filename) { - QFile file(filename); - if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) { - return false; - } - - KILE_DEBUG_MAIN << "search for encryption "; - QRegExp re("/Encrypt(\\W|\\s|$)"); - QTextStream in(&file); - QString line = in.readLine(); - while ( !line.isNull() ) { - if ( re.indexIn(line) >= 0 ) { - KILE_DEBUG_MAIN << "pdf file is encrypted !!!"; - return true; - } - line = in.readLine(); - } - return false; + QFile file(filename); + if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) { + return false; + } + + KILE_DEBUG_MAIN << "search for encryption "; + QRegExp re("/Encrypt(\\W|\\s|$)"); + QTextStream in(&file); + QString line = in.readLine(); + while ( !line.isNull() ) { + if ( re.indexIn(line) >= 0 ) { + KILE_DEBUG_MAIN << "pdf file is encrypted !!!"; + return true; + } + line = in.readLine(); + } + return false; } #endif void PdfDialog::clearDocumentInfo() { - m_numpages = 0; - m_encrypted = false; - m_PdfDialog.m_lbPassword->setEnabled(false); - m_PdfDialog.m_edPassword->setEnabled(false); - m_PdfDialog.m_edPassword->clear(); - - for (QStringList::const_iterator it = m_pdfInfoKeys.constBegin(); it != m_pdfInfoKeys.constEnd(); ++it) { - m_pdfInfoWidget[*it]->clear(); - } - - m_PdfDialog.m_lbCreationDate->clear(); - m_PdfDialog.m_lbModDate->clear(); - - for (int i=0; isetChecked(false); - } - - m_PdfDialog.m_lbPages->clear(); - m_PdfDialog.m_lbFormat->clear(); - m_PdfDialog.m_lbEncryption->clear(); + m_numpages = 0; + m_encrypted = false; + m_PdfDialog.m_lbPassword->setEnabled(false); + m_PdfDialog.m_edPassword->setEnabled(false); + m_PdfDialog.m_edPassword->clear(); + + for (QStringList::const_iterator it = m_pdfInfoKeys.constBegin(); it != m_pdfInfoKeys.constEnd(); ++it) { + m_pdfInfoWidget[*it]->clear(); + } + + m_PdfDialog.m_lbCreationDate->clear(); + m_PdfDialog.m_lbModDate->clear(); + + for (int i=0; isetChecked(false); + } + + m_PdfDialog.m_lbPages->clear(); + m_PdfDialog.m_lbFormat->clear(); + m_PdfDialog.m_lbEncryption->clear(); } void PdfDialog::updateOwnerPassword(bool infile_exists) { - int tabindex = m_PdfDialog.tabWidget->currentIndex(); - bool state = ( infile_exists && (m_encrypted || (!m_encrypted && tabindex==2)) ) ? m_pdftk : false; - m_PdfDialog.m_lbPassword->setEnabled(state); - m_PdfDialog.m_edPassword->setEnabled(state); + int tabindex = m_PdfDialog.tabWidget->currentIndex(); + bool state = ( infile_exists && (m_encrypted || (!m_encrypted && tabindex==2)) ) ? m_pdftk : false; + m_PdfDialog.m_lbPassword->setEnabled(state); + m_PdfDialog.m_edPassword->setEnabled(state); } // update dialog widgets void PdfDialog::updateDialog() { - QString infile = m_PdfDialog.m_edInfile->lineEdit()->text().trimmed(); - bool infile_exists = QFile(infile).exists(); - - updateOwnerPassword(infile_exists); - updateTasks(); - updateToolsInfo(); - - bool pstate = ( m_encrypted ) ? infile_exists && m_pdftk : infile_exists && (m_pdftk || m_pdfpages); - m_PdfDialog.m_gbParameter->setEnabled(pstate); - - m_PdfDialog.m_gbProperties->setEnabled(infile_exists); - m_PdfDialog.m_gbPermissions->setEnabled(infile_exists); - m_PdfDialog.m_lbPrinting->setEnabled(infile_exists); - m_PdfDialog.m_pbPrinting->setEnabled(infile_exists); - m_PdfDialog.m_lbAll->setEnabled(infile_exists); - m_PdfDialog.m_pbAll->setEnabled(infile_exists); - - // and exec button - QString outfile = m_PdfDialog.m_edOutfile->lineEdit()->text().trimmed(); - bool destination = m_PdfDialog.m_cbOverwrite->isChecked() || m_PdfDialog.m_cbView->isChecked(); - - bool state = ( infile_exists && (destination || (!destination && !outfile.isEmpty())) ); - if ( m_PdfDialog.tabWidget->currentIndex() == 0 ) { - state = state && (m_pdfpages || m_pdftk); - } - else { - state = state && m_pdftk; - } - m_rearrangeButton->setEnabled(state&&!m_scriptrunning); + QString infile = m_PdfDialog.m_edInfile->lineEdit()->text().trimmed(); + bool infile_exists = QFile(infile).exists(); + + updateOwnerPassword(infile_exists); + updateTasks(); + updateToolsInfo(); + + bool pstate = ( m_encrypted ) ? infile_exists && m_pdftk : infile_exists && (m_pdftk || m_pdfpages); + m_PdfDialog.m_gbParameter->setEnabled(pstate); + + m_PdfDialog.m_gbProperties->setEnabled(infile_exists); + m_PdfDialog.m_gbPermissions->setEnabled(infile_exists); + m_PdfDialog.m_lbPrinting->setEnabled(infile_exists); + m_PdfDialog.m_pbPrinting->setEnabled(infile_exists); + m_PdfDialog.m_lbAll->setEnabled(infile_exists); + m_PdfDialog.m_pbAll->setEnabled(infile_exists); + + // and exec button + QString outfile = m_PdfDialog.m_edOutfile->lineEdit()->text().trimmed(); + bool destination = m_PdfDialog.m_cbOverwrite->isChecked() || m_PdfDialog.m_cbView->isChecked(); + + bool state = ( infile_exists && (destination || (!destination && !outfile.isEmpty())) ); + if ( m_PdfDialog.tabWidget->currentIndex() == 0 ) { + state = state && (m_pdfpages || m_pdftk); + } + else { + state = state && m_pdftk; + } + m_rearrangeButton->setEnabled(state&&!m_scriptrunning); } // update tools information void PdfDialog::updateToolsInfo() { - QString info; - QString newline = "
"; - QString password = i18n("A password is necessary to set or change the current settings."); - - int tabindex = m_PdfDialog.tabWidget->currentIndex(); - if (tabindex == 2 ) { - info = ( m_pdftk ) ? i18n("The permissions of this document can be changed with pdftk.") + newline + password - : i18n("pdftk is not available, so no permission can be changed."); - } - else if ( tabindex == 1 ) { - if ( ! m_pdftk ) { - info = i18n("pdftk is not available, so no property can be changed."); - } - else { - info = i18n("The properties of this document can be changed with pdftk."); - if ( m_encrypted ) { - info += newline + password; - } - } - } - else { // if ( tabindex == 0 ) - if ( m_encrypted ) { - info = ( m_pdftk ) ? i18n("This input file is encrypted, so only pdftk works.") + newline - + i18n("A password is necessary to rearrange pages.") - : i18n("This input file is encrypted, but pdftk is not installed."); - } - else { - if ( m_pdftk ) { // not encrypted and pdftk - info = ( m_pdfpages ) ? i18n("This wizard will use pdftk and the LaTeX package pdfpages.") - : i18n("This wizard will only use pdftk (pdfpages.sty is not installed)."); - } - else { // not encrypted and not pdftk - info = ( m_pdfpages ) ? i18n("This wizard will only use the LaTeX package pdfpages (pdftk was not found).") - : i18n("This wizard can't work, because no tool was found (see help section)."); - } - } - } - - QString popplerinfo = (m_poppler ) ? QString() : newline + i18n("(Compiled without libpoppler pdf library. Not all tasks are available.)"); - info += popplerinfo; - - // set info text - m_PdfDialog.m_lbParameterInfo->setText(info); + QString info; + QString newline = "
"; + QString password = i18n("A password is necessary to set or change the current settings."); + + int tabindex = m_PdfDialog.tabWidget->currentIndex(); + if (tabindex == 2 ) { + info = ( m_pdftk ) ? i18n("The permissions of this document can be changed with pdftk.") + newline + password + : i18n("pdftk is not available, so no permission can be changed."); + } + else if ( tabindex == 1 ) { + if ( ! m_pdftk ) { + info = i18n("pdftk is not available, so no property can be changed."); + } + else { + info = i18n("The properties of this document can be changed with pdftk."); + if ( m_encrypted ) { + info += newline + password; + } + } + } + else { // if ( tabindex == 0 ) + if ( m_encrypted ) { + info = ( m_pdftk ) ? i18n("This input file is encrypted, so only pdftk works.") + newline + + i18n("A password is necessary to rearrange pages.") + : i18n("This input file is encrypted, but pdftk is not installed."); + } + else { + if ( m_pdftk ) { // not encrypted and pdftk + info = ( m_pdfpages ) ? i18n("This wizard will use pdftk and the LaTeX package pdfpages.") + : i18n("This wizard will only use pdftk (pdfpages.sty is not installed)."); + } + else { // not encrypted and not pdftk + info = ( m_pdfpages ) ? i18n("This wizard will only use the LaTeX package pdfpages (pdftk was not found).") + : i18n("This wizard can't work, because no tool was found (see help section)."); + } + } + } + + QString popplerinfo = (m_poppler ) ? QString() : newline + i18n("(Compiled without libpoppler pdf library. Not all tasks are available.)"); + info += popplerinfo; + + // set info text + m_PdfDialog.m_lbParameterInfo->setText(info); } // it is important to calculate the task index from the combobox index, // as not all tasks are available, when an utility was not found void PdfDialog::updateTasks() { - // according to QT 4.4 docu the index of QComboBox might change if adding or removing items - // but because we populate the QComboBox before we start the dialog, we can use the index here - int lastindex = m_cbTask->currentIndex(); - QString lasttext = m_cbTask->currentText(); - - int group = 0; - m_cbTask->clear(); - if (m_pdfpages && !m_encrypted) { // task index - m_cbTask->addItem( m_tasklist[PDF_PAGE_EMPTY] ); // 0 PDF_PAGE_EMPTY - m_cbTask->addItem( m_tasklist[PDF_PAGE_DUPLICATE] ); // 1 PDF_PAGE_DUPLICATE - m_cbTask->addItem( m_tasklist[PDF_2UP] ); // 2 PDF_2UP - m_cbTask->addItem( m_tasklist[PDF_2UP_LANDSCAPE] ); // 3 PDF_2UP_LANDSCAPE - m_cbTask->addItem( m_tasklist[PDF_4UP] ); // 4 PDF_4UP - m_cbTask->addItem( m_tasklist[PDF_4UP_LANDSCAPE] ); // 5 PDF_4UP_LANDSCAPE - group = 1; - } - - if ( (m_pdfpages && !m_encrypted) || m_pdftk ){ - if ( group > 0 ) { - m_cbTask->addCategoryItem(""); - } - m_cbTask->addItem( m_tasklist[PDF_EVEN] ); // 6 PDF_EVEN - m_cbTask->addItem( m_tasklist[PDF_ODD] ); // 7 PDF_ODD - m_cbTask->addItem( m_tasklist[PDF_EVEN_REV] ); // 8 PDF_EVEN_REV - m_cbTask->addItem( m_tasklist[PDF_ODD_REV] ); // 9 PDF_ODD_REV - m_cbTask->addItem( m_tasklist[PDF_REVERSE] ); // 10 PDF_REVERSE - if (m_encrypted) { - m_cbTask->addItem( m_tasklist[PDF_DECRYPT] ); // 11 PDF_DECRYPT - } - m_cbTask->addCategoryItem(""); - m_cbTask->addItem( m_tasklist[PDF_SELECT] ); // 12 PDF_SELECT - m_cbTask->addItem( m_tasklist[PDF_DELETE] ); // 13 PDF_DELETE - group = 2; - } - - if (m_pdftk) { - m_cbTask->addCategoryItem(""); - m_cbTask->addItem( m_tasklist[PDF_PDFTK_BACKGROUND] ); // 14 PDF_PDFTK_BACKGROUND - if ( ! m_pagesize.isNull() ) { - m_cbTask->addItem( m_tasklist[PDF_PDFTK_BGCOLOR] ); // 15 PDF_PDFTK_BGCOLOR - } - m_cbTask->addItem( m_tasklist[PDF_PDFTK_STAMP] ); // 16 PDF_PDFTK_STAMP - m_cbTask->addCategoryItem(""); - m_cbTask->addItem( m_tasklist[PDF_PDFTK_FREE] ); // 17 PDF_PDFTK_FREE - group = 3; - } - - if (m_pdfpages && !m_encrypted) { - if ( group < 3 ) { - m_cbTask->addCategoryItem(""); - } - m_cbTask->addItem( m_tasklist[PDF_PDFPAGES_FREE] ); // 17 PDF_PDFPAGES_FREE - } - - // choose one common task (need to calculate the combobox index) - int index = m_cbTask->findText(lasttext); - if ( lastindex==-1 || index==-1 ) { - int lastTask = KileConfig::pdfWizardLastTask(); - int task = ( lastTask < m_cbTask->count() ) ? lastTask : PDF_SELECT; - index = m_cbTask->findText(m_tasklist[task]); - if ( index == -1 ) { - index = 0; - } - } - - m_cbTask->setCurrentIndex(index); - slotTaskChanged(index); - - setFocusProxy(m_PdfDialog.m_edInfile); - m_PdfDialog.m_edInfile->setFocus(); + // according to QT 4.4 docu the index of QComboBox might change if adding or removing items + // but because we populate the QComboBox before we start the dialog, we can use the index here + int lastindex = m_cbTask->currentIndex(); + QString lasttext = m_cbTask->currentText(); + + int group = 0; + m_cbTask->clear(); + if (m_pdfpages && !m_encrypted) { // task index + m_cbTask->addItem( m_tasklist[PDF_PAGE_EMPTY] ); // 0 PDF_PAGE_EMPTY + m_cbTask->addItem( m_tasklist[PDF_PAGE_DUPLICATE] ); // 1 PDF_PAGE_DUPLICATE + m_cbTask->addItem( m_tasklist[PDF_2UP] ); // 2 PDF_2UP + m_cbTask->addItem( m_tasklist[PDF_2UP_LANDSCAPE] ); // 3 PDF_2UP_LANDSCAPE + m_cbTask->addItem( m_tasklist[PDF_4UP] ); // 4 PDF_4UP + m_cbTask->addItem( m_tasklist[PDF_4UP_LANDSCAPE] ); // 5 PDF_4UP_LANDSCAPE + group = 1; + } + + if ( (m_pdfpages && !m_encrypted) || m_pdftk ) { + if ( group > 0 ) { + m_cbTask->addCategoryItem(""); + } + m_cbTask->addItem( m_tasklist[PDF_EVEN] ); // 6 PDF_EVEN + m_cbTask->addItem( m_tasklist[PDF_ODD] ); // 7 PDF_ODD + m_cbTask->addItem( m_tasklist[PDF_EVEN_REV] ); // 8 PDF_EVEN_REV + m_cbTask->addItem( m_tasklist[PDF_ODD_REV] ); // 9 PDF_ODD_REV + m_cbTask->addItem( m_tasklist[PDF_REVERSE] ); // 10 PDF_REVERSE + if (m_encrypted) { + m_cbTask->addItem( m_tasklist[PDF_DECRYPT] ); // 11 PDF_DECRYPT + } + m_cbTask->addCategoryItem(""); + m_cbTask->addItem( m_tasklist[PDF_SELECT] ); // 12 PDF_SELECT + m_cbTask->addItem( m_tasklist[PDF_DELETE] ); // 13 PDF_DELETE + group = 2; + } + + if (m_pdftk) { + m_cbTask->addCategoryItem(""); + m_cbTask->addItem( m_tasklist[PDF_PDFTK_BACKGROUND] ); // 14 PDF_PDFTK_BACKGROUND + if ( ! m_pagesize.isNull() ) { + m_cbTask->addItem( m_tasklist[PDF_PDFTK_BGCOLOR] ); // 15 PDF_PDFTK_BGCOLOR + } + m_cbTask->addItem( m_tasklist[PDF_PDFTK_STAMP] ); // 16 PDF_PDFTK_STAMP + m_cbTask->addCategoryItem(""); + m_cbTask->addItem( m_tasklist[PDF_PDFTK_FREE] ); // 17 PDF_PDFTK_FREE + group = 3; + } + + if (m_pdfpages && !m_encrypted) { + if ( group < 3 ) { + m_cbTask->addCategoryItem(""); + } + m_cbTask->addItem( m_tasklist[PDF_PDFPAGES_FREE] ); // 17 PDF_PDFPAGES_FREE + } + + // choose one common task (need to calculate the combobox index) + int index = m_cbTask->findText(lasttext); + if ( lastindex==-1 || index==-1 ) { + int lastTask = KileConfig::pdfWizardLastTask(); + int task = ( lastTask < m_cbTask->count() ) ? lastTask : PDF_SELECT; + index = m_cbTask->findText(m_tasklist[task]); + if ( index == -1 ) { + index = 0; + } + } + + m_cbTask->setCurrentIndex(index); + slotTaskChanged(index); + + setFocusProxy(m_PdfDialog.m_edInfile); + m_PdfDialog.m_edInfile->setFocus(); } QString PdfDialog::getOutfileName(const QString &infile) { - return ( infile.isEmpty() ) ? QString() : infile.left(infile.length()-4) + "-out" + ".pdf"; + return ( infile.isEmpty() ) ? QString() : infile.left(infile.length()-4) + "-out" + ".pdf"; } // calculate task index from comboxbox index int PdfDialog::taskIndex() { - return m_tasklist.indexOf( m_cbTask->currentText() ); + return m_tasklist.indexOf( m_cbTask->currentText() ); } void PdfDialog::setPermissions(bool print, bool other) { - for (int i = 0; isetChecked(state); - } + for (int i = 0; isetChecked(state); + } } // read permissions QString PdfDialog::readPermissions() { - QString permissions; - for (int i = 0; i < m_pdfPermissionKeys.size(); ++i) { - if ( m_pdfPermissionWidgets.at(i)->isChecked() ) { - permissions += m_pdfPermissionPdftk.at(i) + " "; - } - } - return permissions; + QString permissions; + for (int i = 0; i < m_pdfPermissionKeys.size(); ++i) { + if ( m_pdfPermissionWidgets.at(i)->isChecked() ) { + permissions += m_pdfPermissionPdftk.at(i) + " "; + } + } + return permissions; } //-------------------- slots -------------------- void PdfDialog::slotTabwidgetChanged(int index) { - m_rearrangeButton->setText(index == 0 ? i18n("Re&arrange") : i18n("&Update")); - updateDialog(); + m_rearrangeButton->setText(index == 0 ? i18n("Re&arrange") : i18n("&Update")); + updateDialog(); } void PdfDialog::slotPrintingClicked() { - if ( m_pdftk ) { - setPermissions(true, false); - } + if ( m_pdftk ) { + setPermissions(true, false); + } } void PdfDialog::slotAllClicked() { - if ( m_pdftk ) { - setPermissions(true, true); - } + if ( m_pdftk ) { + setPermissions(true, true); + } } void PdfDialog::slotPermissionClicked(bool) { - for (int i = 0; i < m_pdfPermissionKeys.size(); ++i) { - QCheckBox *box = m_pdfPermissionWidgets.at(i); - if ( box->isChecked() != m_pdfPermissionState[i] ) { - box->setChecked( m_pdfPermissionState[i] ); - } - } + for (int i = 0; i < m_pdfPermissionKeys.size(); ++i) { + QCheckBox *box = m_pdfPermissionWidgets.at(i); + if ( box->isChecked() != m_pdfPermissionState[i] ) { + box->setChecked( m_pdfPermissionState[i] ); + } + } } void PdfDialog::slotInputfileChanged(const QString &text) { - clearDocumentInfo(); - if ( QFile(text).exists() ) { - m_PdfDialog.m_edOutfile->lineEdit()->setText( getOutfileName(text) ); - pdfParser(text); - } + clearDocumentInfo(); + if ( QFile(text).exists() ) { + m_PdfDialog.m_edOutfile->lineEdit()->setText( getOutfileName(text) ); + pdfParser(text); + } - updateDialog(); + updateDialog(); } void PdfDialog::slotOverwriteChanged(int state) { - bool checked = (state!=Qt::Checked); - m_PdfDialog.m_lbOutfile->setEnabled(checked); - m_PdfDialog.m_edOutfile->setEnabled(checked); + bool checked = (state!=Qt::Checked); + m_PdfDialog.m_lbOutfile->setEnabled(checked); + m_PdfDialog.m_edOutfile->setEnabled(checked); - updateDialog(); + updateDialog(); } void PdfDialog::slotOutputfileChanged(const QString &) { - updateDialog(); + updateDialog(); } void PdfDialog::slotTaskChanged(int) { - if ( m_PdfDialog.tabWidget->currentIndex() > 0 ) { - return; - } - - int taskindex = taskIndex(); - if ( isParameterTask(taskindex) ) { - QString s,labeltext; - if ( taskindex==PDF_SELECT || taskindex==PDF_DELETE ) { - labeltext = i18n("Pages:"); - s = i18n("Comma separated page list: 1,4-7,9"); - QRegExp re("((\\d+(-\\d+)?),)*\\d+(-\\d+)?"); - m_PdfDialog.m_edParameter->setValidator(new QRegExpValidator(re, m_PdfDialog.m_edParameter)); - } - else if (taskindex==PDF_PDFTK_FREE) { - labeltext = i18n("Parameter:"); - s = i18n("All options for 'pdftk'"); - m_PdfDialog.m_edParameter->setValidator(0); - } - else { //if (taskindex==PDF_PDFPAGES_FREE) { - labeltext = i18n("Parameter:"); - s = i18n("All options for 'pdfpages'"); - m_PdfDialog.m_edParameter->setValidator(0); - } - m_PdfDialog.m_lbParamInfo->setText(" (" + s + ")"); - - m_PdfDialog.m_lbParameter->setText(labeltext); - m_PdfDialog.m_lbParameter->show(); - m_PdfDialog.m_edParameter->clear(); - m_PdfDialog.m_edParameter->show(); - m_PdfDialog.m_lbParamInfo->show(); - } - else { - m_PdfDialog.m_lbParameter->hide(); - m_PdfDialog.m_edParameter->hide(); - m_PdfDialog.m_lbParamInfo->hide(); - } - - if ( isOverlayTask(taskindex) ) { - m_PdfDialog.m_lbStamp->show(); - m_PdfDialog.m_edStamp->show(); - - if ( taskindex == PDF_PDFTK_BACKGROUND ) { - m_PdfDialog.m_edStamp->setWhatsThis(i18n("Applies a PDF watermark to the background of a single input PDF. " - "Pdftk uses only the first page from the background PDF and applies it to every page of the input PDF. " - "This page is scaled and rotated as needed to fit the input page.") ); - } - else if ( taskindex == PDF_PDFTK_STAMP ) { - m_PdfDialog.m_edStamp->setWhatsThis( i18n("Applies a foreground stamp on top of the input PDF document's pages. " - "Pdftk uses only the first page from the stamp PDF and applies it to every page of the input PDF. " - "This page is scaled and rotated as needed to fit the input page. " - "This works best if the stamp PDF page has a transparent background.") ); - } - } - else { - m_PdfDialog.m_lbStamp->hide(); - m_PdfDialog.m_edStamp->hide(); - } - - if (isBackgroundColor(taskindex)) { - m_PdfDialog.m_lbBackgroundColor->show(); - m_PdfDialog.m_pbBackgroundColor->show(); - } - else { - m_PdfDialog.m_lbBackgroundColor->hide(); - m_PdfDialog.m_pbBackgroundColor->hide(); - } - if (isOverlayTask(taskindex) || isBackgroundColor(taskindex) || isFreeTask(taskindex)) { - m_rearrangeButton->setText(i18n("&Apply")); - } - else { - m_rearrangeButton->setText(i18n("Re&arrange")); - } + if ( m_PdfDialog.tabWidget->currentIndex() > 0 ) { + return; + } + + int taskindex = taskIndex(); + if ( isParameterTask(taskindex) ) { + QString s,labeltext; + if ( taskindex==PDF_SELECT || taskindex==PDF_DELETE ) { + labeltext = i18n("Pages:"); + s = i18n("Comma separated page list: 1,4-7,9"); + QRegExp re("((\\d+(-\\d+)?),)*\\d+(-\\d+)?"); + m_PdfDialog.m_edParameter->setValidator(new QRegExpValidator(re, m_PdfDialog.m_edParameter)); + } + else if (taskindex==PDF_PDFTK_FREE) { + labeltext = i18n("Parameter:"); + s = i18n("All options for 'pdftk'"); + m_PdfDialog.m_edParameter->setValidator(0); + } + else { //if (taskindex==PDF_PDFPAGES_FREE) { + labeltext = i18n("Parameter:"); + s = i18n("All options for 'pdfpages'"); + m_PdfDialog.m_edParameter->setValidator(0); + } + m_PdfDialog.m_lbParamInfo->setText(" (" + s + ")"); + + m_PdfDialog.m_lbParameter->setText(labeltext); + m_PdfDialog.m_lbParameter->show(); + m_PdfDialog.m_edParameter->clear(); + m_PdfDialog.m_edParameter->show(); + m_PdfDialog.m_lbParamInfo->show(); + } + else { + m_PdfDialog.m_lbParameter->hide(); + m_PdfDialog.m_edParameter->hide(); + m_PdfDialog.m_lbParamInfo->hide(); + } + + if ( isOverlayTask(taskindex) ) { + m_PdfDialog.m_lbStamp->show(); + m_PdfDialog.m_edStamp->show(); + + if ( taskindex == PDF_PDFTK_BACKGROUND ) { + m_PdfDialog.m_edStamp->setWhatsThis(i18n("Applies a PDF watermark to the background of a single input PDF. " + "Pdftk uses only the first page from the background PDF and applies it to every page of the input PDF. " + "This page is scaled and rotated as needed to fit the input page.") ); + } + else if ( taskindex == PDF_PDFTK_STAMP ) { + m_PdfDialog.m_edStamp->setWhatsThis( i18n("Applies a foreground stamp on top of the input PDF document's pages. " + "Pdftk uses only the first page from the stamp PDF and applies it to every page of the input PDF. " + "This page is scaled and rotated as needed to fit the input page. " + "This works best if the stamp PDF page has a transparent background.") ); + } + } + else { + m_PdfDialog.m_lbStamp->hide(); + m_PdfDialog.m_edStamp->hide(); + } + + if (isBackgroundColor(taskindex)) { + m_PdfDialog.m_lbBackgroundColor->show(); + m_PdfDialog.m_pbBackgroundColor->show(); + } + else { + m_PdfDialog.m_lbBackgroundColor->hide(); + m_PdfDialog.m_pbBackgroundColor->hide(); + } + if (isOverlayTask(taskindex) || isBackgroundColor(taskindex) || isFreeTask(taskindex)) { + m_rearrangeButton->setText(i18n("&Apply")); + } + else { + m_rearrangeButton->setText(i18n("Re&arrange")); + } } // execute commands void PdfDialog::slotExecute() { - int tabindex = m_PdfDialog.tabWidget->currentIndex(); - - switch (tabindex) { - case 0: - if (checkParameter()) { - executeAction(); - } - break; - case 1: - if (checkProperties()) { - executeProperties(); - } - break; - case 2: - if (checkPermissions()) { - executePermissions(); - } - break; - } + int tabindex = m_PdfDialog.tabWidget->currentIndex(); + + switch (tabindex) { + case 0: + if (checkParameter()) { + executeAction(); + } + break; + case 1: + if (checkProperties()) { + executeProperties(); + } + break; + case 2: + if (checkPermissions()) { + executePermissions(); + } + break; + } } void PdfDialog::slotShowHelp() { - QString message = i18n("

PDF-Wizard

" - "This wizard uses 'pdftk' and the LaTeX package 'pdfpages' to" - "
    " - "
  • rearrange pages of an existing PDF document
  • " - "
  • read and update documentinfo of a PDF document (only pdftk)
  • " - "
  • read, set or change some permissions of a PDF document (only pdftk). " - "A password is necessary to set or change this document settings. " - "Additionally PDF encryption is done to lock the file's content behind this password.
  • " - "
" - "

The package 'pdfpages' will only work with non-encrypted documents. " - "'pdftk' can handle both kind of documents, but a password is needed for encrypted files. " - "If one of 'pdftk' or 'pdfpages' is not available, the possible rearrangements are reduced.

" - "

Warning: Encryption and a password does not provide any real PDF security. The content " - "is encrypted, but the key is known. You should see it more as a polite but firm request " - "to respect the author's wishes.

"); + QString message = i18n("
PDF-Wizard

" + "This wizard uses 'pdftk' and the LaTeX package 'pdfpages' to" + "
    " + "
  • rearrange pages of an existing PDF document
  • " + "
  • read and update documentinfo of a PDF document (only pdftk)
  • " + "
  • read, set or change some permissions of a PDF document (only pdftk). " + "A password is necessary to set or change this document settings. " + "Additionally PDF encryption is done to lock the file's content behind this password.
  • " + "
" + "

The package 'pdfpages' will only work with non-encrypted documents. " + "'pdftk' can handle both kind of documents, but a password is needed for encrypted files. " + "If one of 'pdftk' or 'pdfpages' is not available, the possible rearrangements are reduced.

" + "

Warning: Encryption and a password does not provide any real PDF security. The content " + "is encrypted, but the key is known. You should see it more as a polite but firm request " + "to respect the author's wishes.

"); #if !LIBPOPPLER_AVAILABLE - message += i18n("

Information: This version of Kile was compiled without libpoppler library. " - "Setting, changing and removing of properties and permissions is not possible.

"); + message += i18n("

Information: This version of Kile was compiled without libpoppler library. " + "Setting, changing and removing of properties and permissions is not possible.

"); #endif - KMessageBox::information(this, message, i18n("PDF Tools")); + KMessageBox::information(this, message, i18n("PDF Tools")); } void PdfDialog::executeAction() { - QString command = buildActionCommand(); - if ( command.isEmpty() ) { - return; - } - - m_errorHandler->clearMessages(); - QFileInfo from(m_inputfile); - QFileInfo to(m_outputfile); - - // output for log window - QString program = (m_execLatex) ? i18n("LaTeX with 'pdfpages' package") : i18n("pdftk"); - QString msg = i18n("Rearranging PDF file: ") + from.fileName(); - if (!to.fileName().isEmpty()) - msg += " ---> " + to.fileName(); - m_errorHandler->printMessage(KileTool::Info, msg, program); - - // some output logs - m_output->clear(); - QString s = QString("*****\n") - + i18n("***** tool: ") + program + '\n' - + i18n("***** input file: ") + from.fileName()+ '\n' - + i18n("***** output file: ") + to.fileName()+ '\n' - + i18n("***** param: ") + m_param + '\n' - + i18n("***** command: ") + command + '\n' - + i18n("***** viewer: ") + ((m_PdfDialog.m_cbView->isChecked()) ? i18n("yes") : i18n("no")) + '\n' - + "*****\n"; - emit( output(s) ); - - // run Process - executeScript(command, m_tempdir->path(), PDF_SCRIPTMODE_ACTION); + QString command = buildActionCommand(); + if ( command.isEmpty() ) { + return; + } + + m_errorHandler->clearMessages(); + QFileInfo from(m_inputfile); + QFileInfo to(m_outputfile); + + // output for log window + QString program = (m_execLatex) ? i18n("LaTeX with 'pdfpages' package") : i18n("pdftk"); + QString msg = i18n("Rearranging PDF file: ") + from.fileName(); + if (!to.fileName().isEmpty()) + msg += " ---> " + to.fileName(); + m_errorHandler->printMessage(KileTool::Info, msg, program); + + // some output logs + m_output->clear(); + QString s = QString("*****\n") + + i18n("***** tool: ") + program + '\n' + + i18n("***** input file: ") + from.fileName()+ '\n' + + i18n("***** output file: ") + to.fileName()+ '\n' + + i18n("***** param: ") + m_param + '\n' + + i18n("***** command: ") + command + '\n' + + i18n("***** viewer: ") + ((m_PdfDialog.m_cbView->isChecked()) ? i18n("yes") : i18n("no")) + '\n' + + "*****\n"; + emit( output(s) ); + + // run Process + executeScript(command, m_tempdir->path(), PDF_SCRIPTMODE_ACTION); } void PdfDialog::executeProperties() { - // create temporary file - QTemporaryFile infotemp; + // create temporary file + QTemporaryFile infotemp; //code was infotemp.setSuffix(".txt"); -//Add to constructor and adapt if necessay: QDir::tempPath() + QLatin1String("/myapp_XXXXXX") + QLatin1String(".txt") - infotemp.setAutoRemove(false); - - if(!infotemp.open()) { - KILE_DEBUG_MAIN << "Could not create tempfile for key/value pairs in QString PdfDialog::executeProperties()" ; - return; - } - QString infofile = infotemp.fileName(); - - // create a text file with key/value pairs for pdftk - QTextStream infostream(&infotemp); - for (QStringList::const_iterator it = m_pdfInfoKeys.constBegin(); it != m_pdfInfoKeys.constEnd(); ++it) { - infostream << "InfoKey: " << (*it) << "\n"; - infostream << "InfoValue: " << m_pdfInfoWidget[*it]->text().trimmed() << "\n"; - } - // add modification Date - QString datetime = QDateTime::currentDateTimeUtc().toString("%Y%m%d%H%M%S%:z"); - datetime = datetime.replace(":","'"); - infostream << "InfoKey: " << "ModDate" << "\n"; - infostream << "InfoValue: " << "D:" << datetime << "'\n"; - infotemp.close(); - - // build command - QString inputfile = m_PdfDialog.m_edInfile->lineEdit()->text().trimmed(); - QString password = m_PdfDialog.m_edPassword->text().trimmed(); - QString pdffile = m_tempdir->path() + QFileInfo(m_inputfile).baseName() + "-props.pdf"; - - // read permissions - QString permissions = readPermissions(); - - // build param - QString param = "\"" + inputfile + "\""; - if ( m_encrypted ) { - param += " input_pw " + password; - } - - param += " update_info " + infofile + " output \"" + pdffile+ "\""; - if ( m_encrypted ) { - param += " encrypt_128bit"; - if ( !permissions.isEmpty() ) - param += " allow " + permissions; - param += " owner_pw " + password; - } - QString command = "pdftk " + param; - - // move destination file - m_move_filelist.clear(); - m_move_filelist << pdffile << inputfile; - - // execute script - showLogs("Updating properties", inputfile, param); - executeScript(command, QString(), PDF_SCRIPTMODE_PROPERTIES); +//Add to constructor and adapt if necessay: QDir::tempPath() + QLatin1String("/myapp_XXXXXX") + QLatin1String(".txt") + infotemp.setAutoRemove(false); + + if(!infotemp.open()) { + KILE_DEBUG_MAIN << "Could not create tempfile for key/value pairs in QString PdfDialog::executeProperties()" ; + return; + } + QString infofile = infotemp.fileName(); + + // create a text file with key/value pairs for pdftk + QTextStream infostream(&infotemp); + for (QStringList::const_iterator it = m_pdfInfoKeys.constBegin(); it != m_pdfInfoKeys.constEnd(); ++it) { + infostream << "InfoKey: " << (*it) << "\n"; + infostream << "InfoValue: " << m_pdfInfoWidget[*it]->text().trimmed() << "\n"; + } + // add modification Date + QString datetime = QDateTime::currentDateTimeUtc().toString("%Y%m%d%H%M%S%:z"); + datetime = datetime.replace(":","'"); + infostream << "InfoKey: " << "ModDate" << "\n"; + infostream << "InfoValue: " << "D:" << datetime << "'\n"; + infotemp.close(); + + // build command + QString inputfile = m_PdfDialog.m_edInfile->lineEdit()->text().trimmed(); + QString password = m_PdfDialog.m_edPassword->text().trimmed(); + QString pdffile = m_tempdir->path() + QFileInfo(m_inputfile).baseName() + "-props.pdf"; + + // read permissions + QString permissions = readPermissions(); + + // build param + QString param = "\"" + inputfile + "\""; + if ( m_encrypted ) { + param += " input_pw " + password; + } + + param += " update_info " + infofile + " output \"" + pdffile+ "\""; + if ( m_encrypted ) { + param += " encrypt_128bit"; + if ( !permissions.isEmpty() ) + param += " allow " + permissions; + param += " owner_pw " + password; + } + QString command = "pdftk " + param; + + // move destination file + m_move_filelist.clear(); + m_move_filelist << pdffile << inputfile; + + // execute script + showLogs("Updating properties", inputfile, param); + executeScript(command, QString(), PDF_SCRIPTMODE_PROPERTIES); } void PdfDialog::executePermissions() { - // read permissions - QString permissions = readPermissions(); - - // build command - QString inputfile = m_PdfDialog.m_edInfile->lineEdit()->text().trimmed(); - QString password = m_PdfDialog.m_edPassword->text().trimmed(); - QString pdffile = m_tempdir->path() + QFileInfo(m_inputfile).baseName() + "-perms.pdf"; - - QString param = "\"" + inputfile + "\""; - if ( m_encrypted ) { - param += " input_pw " + password; - } - param += " output \"" + pdffile + "\" encrypt_128bit"; - if ( !permissions.isEmpty() ) { - param += " allow " + permissions; - } - param += " owner_pw " + password; - QString command = "pdftk " + param; - - // move destination file - m_move_filelist.clear(); - m_move_filelist << pdffile << inputfile; - - // execute script - showLogs("Updating permissions", inputfile, param); - executeScript(command, QString(), PDF_SCRIPTMODE_PERMISSIONS); + // read permissions + QString permissions = readPermissions(); + + // build command + QString inputfile = m_PdfDialog.m_edInfile->lineEdit()->text().trimmed(); + QString password = m_PdfDialog.m_edPassword->text().trimmed(); + QString pdffile = m_tempdir->path() + QFileInfo(m_inputfile).baseName() + "-perms.pdf"; + + QString param = "\"" + inputfile + "\""; + if ( m_encrypted ) { + param += " input_pw " + password; + } + param += " output \"" + pdffile + "\" encrypt_128bit"; + if ( !permissions.isEmpty() ) { + param += " allow " + permissions; + } + param += " owner_pw " + password; + QString command = "pdftk " + param; + + // move destination file + m_move_filelist.clear(); + m_move_filelist << pdffile << inputfile; + + // execute script + showLogs("Updating permissions", inputfile, param); + executeScript(command, QString(), PDF_SCRIPTMODE_PERMISSIONS); } void PdfDialog::showLogs(const QString &title, const QString &inputfile, const QString ¶m) { - // some info for log widget - m_errorHandler->clearMessages(); - m_errorHandler->printMessage(KileTool::Info, title, "pdftk" ); - - // some info for output widget - QFileInfo input(inputfile); - m_output->clear(); - QString s = QString("*****\n") - + i18n("***** tool: ") + "pdftk" + '\n' - + i18n("***** input file: ") + input.fileName()+ '\n' - + i18n("***** param: ") + param + '\n' - + "*****\n"; - emit( output(s) ); + // some info for log widget + m_errorHandler->clearMessages(); + m_errorHandler->printMessage(KileTool::Info, title, "pdftk" ); + + // some info for output widget + QFileInfo input(inputfile); + m_output->clear(); + QString s = QString("*****\n") + + i18n("***** tool: ") + "pdftk" + '\n' + + i18n("***** input file: ") + input.fileName()+ '\n' + + i18n("***** param: ") + param + '\n' + + "*****\n"; + emit( output(s) ); } void PdfDialog::executeScript(const QString &command, const QString &dir, int scriptmode) { - // delete old KProcess - if (m_proc) { - delete m_proc; - } - - m_scriptmode = scriptmode; - m_outputtext = ""; - - m_proc = new KProcess(); - if (!dir.isEmpty()) { - m_proc->setWorkingDirectory(dir); - } - m_proc->setShellCommand(command); - m_proc->setOutputChannelMode(KProcess::MergedChannels); - m_proc->setReadChannel(QProcess::StandardOutput); - - connect(m_proc, SIGNAL(readyReadStandardOutput()), - this, SLOT(slotProcessOutput())); - connect(m_proc, SIGNAL(readyReadStandardError()), - this, SLOT(slotProcessOutput())); - connect(m_proc, SIGNAL(finished(int, QProcess::ExitStatus)), - this, SLOT(slotProcessExited(int, QProcess::ExitStatus))); - - KILE_DEBUG_MAIN << "=== PdfDialog::runPdfutils() ===================="; - KILE_DEBUG_MAIN << "execute '" << command << "'"; - m_scriptrunning = true; - m_rearrangeButton->setEnabled(false); - m_buttonBox->button(QDialogButtonBox::Close)->setEnabled(false); - m_proc->start(); + // delete old KProcess + if (m_proc) { + delete m_proc; + } + + m_scriptmode = scriptmode; + m_outputtext = ""; + + m_proc = new KProcess(); + if (!dir.isEmpty()) { + m_proc->setWorkingDirectory(dir); + } + m_proc->setShellCommand(command); + m_proc->setOutputChannelMode(KProcess::MergedChannels); + m_proc->setReadChannel(QProcess::StandardOutput); + + connect(m_proc, SIGNAL(readyReadStandardOutput()), + this, SLOT(slotProcessOutput())); + connect(m_proc, SIGNAL(readyReadStandardError()), + this, SLOT(slotProcessOutput())); + connect(m_proc, SIGNAL(finished(int, QProcess::ExitStatus)), + this, SLOT(slotProcessExited(int, QProcess::ExitStatus))); + + KILE_DEBUG_MAIN << "=== PdfDialog::runPdfutils() ===================="; + KILE_DEBUG_MAIN << "execute '" << command << "'"; + m_scriptrunning = true; + m_rearrangeButton->setEnabled(false); + m_buttonBox->button(QDialogButtonBox::Close)->setEnabled(false); + m_proc->start(); } void PdfDialog::slotProcessOutput() { - m_outputtext += m_proc->readAll(); + m_outputtext += m_proc->readAll(); } void PdfDialog::slotProcessExited(int exitCode, QProcess::ExitStatus exitStatus) { - if ( exitStatus != QProcess::NormalExit) { - if (m_scriptmode != PDF_SCRIPTMODE_TOOLS) - showError(i18n("An error occurred while executing the task.")); - } - else { - bool state = ( exitCode == 0 ); - if ( m_scriptmode == PDF_SCRIPTMODE_TOOLS ) { - initUtilities(); - } + if ( exitStatus != QProcess::NormalExit) { + if (m_scriptmode != PDF_SCRIPTMODE_TOOLS) + showError(i18n("An error occurred while executing the task.")); + } + else { + bool state = ( exitCode == 0 ); + if ( m_scriptmode == PDF_SCRIPTMODE_TOOLS ) { + initUtilities(); + } #if !LIBPOPPLER_AVAILABLE - else if ( m_scriptmode==PDF_SCRIPTMODE_NUMPAGES_PDFTK - || m_scriptmode==PDF_SCRIPTMODE_NUMPAGES_IMAGEMAGICK - || m_scriptmode==PDF_SCRIPTMODE_NUMPAGES_GHOSTSCRIPT ) { - readNumberOfPages(m_scriptmode,m_outputtext); - } + else if ( m_scriptmode==PDF_SCRIPTMODE_NUMPAGES_PDFTK + || m_scriptmode==PDF_SCRIPTMODE_NUMPAGES_IMAGEMAGICK + || m_scriptmode==PDF_SCRIPTMODE_NUMPAGES_GHOSTSCRIPT ) { + readNumberOfPages(m_scriptmode,m_outputtext); + } #endif - else { - finishPdfAction(state); - } - } - - m_scriptrunning = false; - m_buttonBox->button(QDialogButtonBox::Close)->setEnabled(true); - updateDialog(); + else { + finishPdfAction(state); + } + } + + m_scriptrunning = false; + m_buttonBox->button(QDialogButtonBox::Close)->setEnabled(true); + updateDialog(); } void PdfDialog::finishPdfAction(bool state) { - // output window - emit( output(m_outputtext) ); - - // log window - QString program = (m_scriptmode==PDF_SCRIPTMODE_ACTION && m_execLatex) ? "LaTeX with 'pdfpages' package" : "pdftk"; - - if ( state ) { - m_errorHandler->printMessage(KileTool::Info, "finished", program); - - // should we move the temporary pdf file - if ( ! m_move_filelist.isEmpty() ) { - QFile::remove( m_move_filelist[1] ); - QFile::rename( m_move_filelist[0], m_move_filelist[1] ); - KILE_DEBUG_MAIN << "move file: " << m_move_filelist[0] << " ---> " << m_move_filelist[1]; - } - - // run viewer - if ( m_PdfDialog.m_cbView->isChecked() && m_scriptmode==PDF_SCRIPTMODE_ACTION ) { - runViewer(); - } - - // file properties/permissions could be changed - if ( (m_scriptmode==PDF_SCRIPTMODE_ACTION && m_PdfDialog.m_cbOverwrite->isChecked()) - || m_scriptmode==PDF_SCRIPTMODE_PROPERTIES || m_scriptmode==PDF_SCRIPTMODE_PERMISSIONS ) { - slotInputfileChanged( m_PdfDialog.m_edInfile->lineEdit()->text().trimmed() ); - } - } - else { - QString msg; - if (m_outputtext.indexOf("OWNER PASSWORD") >= 0 ) { - msg = i18n("Finished with an error (wrong password)"); - } - else { - msg = i18n("Finished with an error"); - } - m_errorHandler->printMessage(KileTool::Error, msg, program); - } + // output window + emit( output(m_outputtext) ); + + // log window + QString program = (m_scriptmode==PDF_SCRIPTMODE_ACTION && m_execLatex) ? "LaTeX with 'pdfpages' package" : "pdftk"; + + if ( state ) { + m_errorHandler->printMessage(KileTool::Info, "finished", program); + + // should we move the temporary pdf file + if ( ! m_move_filelist.isEmpty() ) { + QFile::remove( m_move_filelist[1] ); + QFile::rename( m_move_filelist[0], m_move_filelist[1] ); + KILE_DEBUG_MAIN << "move file: " << m_move_filelist[0] << " ---> " << m_move_filelist[1]; + } + + // run viewer + if ( m_PdfDialog.m_cbView->isChecked() && m_scriptmode==PDF_SCRIPTMODE_ACTION ) { + runViewer(); + } + + // file properties/permissions could be changed + if ( (m_scriptmode==PDF_SCRIPTMODE_ACTION && m_PdfDialog.m_cbOverwrite->isChecked()) + || m_scriptmode==PDF_SCRIPTMODE_PROPERTIES || m_scriptmode==PDF_SCRIPTMODE_PERMISSIONS ) { + slotInputfileChanged( m_PdfDialog.m_edInfile->lineEdit()->text().trimmed() ); + } + } + else { + QString msg; + if (m_outputtext.indexOf("OWNER PASSWORD") >= 0 ) { + msg = i18n("Finished with an error (wrong password)"); + } + else { + msg = i18n("Finished with an error"); + } + m_errorHandler->printMessage(KileTool::Error, msg, program); + } } void PdfDialog::runViewer() { - m_errorHandler->printMessage(KileTool::Info, "Running viewer", "ViewPDF"); - - // call ViewPDF - QString cfg = KileTool::configName("ViewPDF", m_manager->config()); - KileTool::View *tool = dynamic_cast(m_manager->createTool("ViewPDF", cfg, false)); - if(!tool) { - m_errorHandler->printMessage(KileTool::Error, i18n("Could not create the ViewPDF tool"), i18n("ViewPDF")); - return; - } - tool->setFlags(0); - tool->setSource(m_outputfile); - m_manager->run(tool); + m_errorHandler->printMessage(KileTool::Info, "Running viewer", "ViewPDF"); + + // call ViewPDF + QString cfg = KileTool::configName("ViewPDF", m_manager->config()); + KileTool::View *tool = dynamic_cast(m_manager->createTool("ViewPDF", cfg, false)); + if(!tool) { + m_errorHandler->printMessage(KileTool::Error, i18n("Could not create the ViewPDF tool"), i18n("ViewPDF")); + return; + } + tool->setFlags(0); + tool->setSource(m_outputfile); + m_manager->run(tool); } QString PdfDialog::buildActionCommand() { - // build action: parameter - m_execLatex = true; // default - m_inputfile = m_PdfDialog.m_edInfile->lineEdit()->text().trimmed(); - m_outputfile = m_PdfDialog.m_edOutfile->lineEdit()->text().trimmed(); - - QColor bgcolor; - QString bgfile; - int taskindex = taskIndex(); - switch (taskindex) { - case PDF_PAGE_EMPTY: - m_param = "nup=1x2,landscape,pages=" + buildPageRange(PDF_PAGE_EMPTY); - break; - - case PDF_PAGE_DUPLICATE: - m_param = "nup=1x2,landscape,pages=" + buildPageRange(PDF_PAGE_DUPLICATE); - break; - - case PDF_2UP: - m_param = "nup=1x2,landscape,pages=1-"; - break; - - case PDF_2UP_LANDSCAPE: - m_param = "nup=1x2,pages=1-"; - break; - - case PDF_4UP: - m_param = "nup=2x2,pages=1-"; - break; - - case PDF_4UP_LANDSCAPE: - m_param = "nup=2x2,landscape,pages=1-"; - break; - - case PDF_EVEN: - if ( m_pdftk ) { - m_param = "cat 1-endeven"; - m_execLatex = false; - } - else { - m_param = buildPageList(true); - } - break; - - case PDF_ODD: - if ( m_pdftk ) { - m_param = "cat 1-endodd"; - m_execLatex = false; - } - else { - m_param = buildPageList(false); - } - break; - - case PDF_EVEN_REV: - if ( m_pdftk ) { - m_param = "cat end-1even"; - m_execLatex = false; - } - else { - m_param = buildReversPageList(true); - } - break; - - case PDF_ODD_REV: - if ( m_pdftk ) { - m_param = "cat end-1odd"; - m_execLatex = false; - } - else { - m_param = buildReversPageList(false); - } - break; - - case PDF_REVERSE: - if ( m_pdftk ) { - m_param = "cat end-1"; - m_execLatex = false; - } - else { - m_param = "last-1"; - } - break; - - case PDF_DECRYPT: - m_param.clear(); - m_execLatex = false; - break; - - case PDF_SELECT: - case PDF_DELETE: - m_param = ( taskindex == PDF_SELECT ) ? buildSelectPageList() : buildDeletePageList(); - if ( m_pdftk ) { - m_param = "cat " + m_param.replace(","," "); - m_execLatex = false; - } - else { - m_param = "pages={" + m_param + "}"; - } - break; - - case PDF_PDFTK_BACKGROUND: - m_param = "background \"" + m_PdfDialog.m_edStamp->text().trimmed() + "\""; - m_execLatex = false; - break; - - case PDF_PDFTK_BGCOLOR: - bgcolor = m_PdfDialog.m_pbBackgroundColor->color(); - bgfile = buildPdfBackgroundFile(&bgcolor); - m_param = "background " + bgfile; - m_execLatex = false; - break; - - case PDF_PDFTK_STAMP: - m_param = "stamp \"" + m_PdfDialog.m_edStamp->text().trimmed() + "\""; - m_execLatex = false; - break; - - case PDF_PDFTK_FREE: - m_param = m_PdfDialog.m_edParameter->text().trimmed(); - m_execLatex = false; - break; - - case PDF_PDFPAGES_FREE: - m_param = m_PdfDialog.m_edParameter->text().trimmed(); - break; - } - - // build action: command - QString command,latexfile,pdffile; - if ( m_execLatex ) { - latexfile = buildLatexFile(m_param); - pdffile = latexfile + ".pdf"; - command = "pdflatex " + latexfile + ".tex"; - } - else { - pdffile = m_tempdir->path() + QFileInfo(m_inputfile).baseName() + "-temp.pdf"; - command = "pdftk \"" + m_inputfile + "\""; - if ( m_encrypted ) { - QString password = m_PdfDialog.m_edPassword->text().trimmed(); - command += " input_pw " + password; - } - command += " " + m_param + " output \"" + pdffile+ "\""; - } - - // additional actions - bool viewer = m_PdfDialog.m_cbView->isChecked(); - - bool equalfiles = (m_PdfDialog.m_cbOverwrite->isChecked() || m_inputfile==m_outputfile); - if (equalfiles) { - m_outputfile = m_inputfile; - } - - // move destination file - m_move_filelist.clear(); - if ( equalfiles ) { - m_move_filelist << pdffile << m_inputfile; - } - else if ( !m_outputfile.isEmpty() ) { - m_move_filelist << pdffile << m_outputfile; - } - - // viewer - if ( viewer && m_outputfile.isEmpty() ) { - m_outputfile = pdffile; - } - - return command; + // build action: parameter + m_execLatex = true; // default + m_inputfile = m_PdfDialog.m_edInfile->lineEdit()->text().trimmed(); + m_outputfile = m_PdfDialog.m_edOutfile->lineEdit()->text().trimmed(); + + QColor bgcolor; + QString bgfile; + int taskindex = taskIndex(); + switch (taskindex) { + case PDF_PAGE_EMPTY: + m_param = "nup=1x2,landscape,pages=" + buildPageRange(PDF_PAGE_EMPTY); + break; + + case PDF_PAGE_DUPLICATE: + m_param = "nup=1x2,landscape,pages=" + buildPageRange(PDF_PAGE_DUPLICATE); + break; + + case PDF_2UP: + m_param = "nup=1x2,landscape,pages=1-"; + break; + + case PDF_2UP_LANDSCAPE: + m_param = "nup=1x2,pages=1-"; + break; + + case PDF_4UP: + m_param = "nup=2x2,pages=1-"; + break; + + case PDF_4UP_LANDSCAPE: + m_param = "nup=2x2,landscape,pages=1-"; + break; + + case PDF_EVEN: + if ( m_pdftk ) { + m_param = "cat 1-endeven"; + m_execLatex = false; + } + else { + m_param = buildPageList(true); + } + break; + + case PDF_ODD: + if ( m_pdftk ) { + m_param = "cat 1-endodd"; + m_execLatex = false; + } + else { + m_param = buildPageList(false); + } + break; + + case PDF_EVEN_REV: + if ( m_pdftk ) { + m_param = "cat end-1even"; + m_execLatex = false; + } + else { + m_param = buildReversPageList(true); + } + break; + + case PDF_ODD_REV: + if ( m_pdftk ) { + m_param = "cat end-1odd"; + m_execLatex = false; + } + else { + m_param = buildReversPageList(false); + } + break; + + case PDF_REVERSE: + if ( m_pdftk ) { + m_param = "cat end-1"; + m_execLatex = false; + } + else { + m_param = "last-1"; + } + break; + + case PDF_DECRYPT: + m_param.clear(); + m_execLatex = false; + break; + + case PDF_SELECT: + case PDF_DELETE: + m_param = ( taskindex == PDF_SELECT ) ? buildSelectPageList() : buildDeletePageList(); + if ( m_pdftk ) { + m_param = "cat " + m_param.replace(","," "); + m_execLatex = false; + } + else { + m_param = "pages={" + m_param + "}"; + } + break; + + case PDF_PDFTK_BACKGROUND: + m_param = "background \"" + m_PdfDialog.m_edStamp->text().trimmed() + "\""; + m_execLatex = false; + break; + + case PDF_PDFTK_BGCOLOR: + bgcolor = m_PdfDialog.m_pbBackgroundColor->color(); + bgfile = buildPdfBackgroundFile(&bgcolor); + m_param = "background " + bgfile; + m_execLatex = false; + break; + + case PDF_PDFTK_STAMP: + m_param = "stamp \"" + m_PdfDialog.m_edStamp->text().trimmed() + "\""; + m_execLatex = false; + break; + + case PDF_PDFTK_FREE: + m_param = m_PdfDialog.m_edParameter->text().trimmed(); + m_execLatex = false; + break; + + case PDF_PDFPAGES_FREE: + m_param = m_PdfDialog.m_edParameter->text().trimmed(); + break; + } + + // build action: command + QString command,latexfile,pdffile; + if ( m_execLatex ) { + latexfile = buildLatexFile(m_param); + pdffile = latexfile + ".pdf"; + command = "pdflatex " + latexfile + ".tex"; + } + else { + pdffile = m_tempdir->path() + QFileInfo(m_inputfile).baseName() + "-temp.pdf"; + command = "pdftk \"" + m_inputfile + "\""; + if ( m_encrypted ) { + QString password = m_PdfDialog.m_edPassword->text().trimmed(); + command += " input_pw " + password; + } + command += " " + m_param + " output \"" + pdffile+ "\""; + } + + // additional actions + bool viewer = m_PdfDialog.m_cbView->isChecked(); + + bool equalfiles = (m_PdfDialog.m_cbOverwrite->isChecked() || m_inputfile==m_outputfile); + if (equalfiles) { + m_outputfile = m_inputfile; + } + + // move destination file + m_move_filelist.clear(); + if ( equalfiles ) { + m_move_filelist << pdffile << m_inputfile; + } + else if ( !m_outputfile.isEmpty() ) { + m_move_filelist << pdffile << m_outputfile; + } + + // viewer + if ( viewer && m_outputfile.isEmpty() ) { + m_outputfile = pdffile; + } + + return command; } // create a temporary file to run latex with package pdfpages.sty QString PdfDialog::buildLatexFile(const QString ¶m) { - QTemporaryFile temp; + QTemporaryFile temp; //code was temp.setPrefix(m_tempdir->path()); -//Add to constructor and adapt if necessay: m_tempdir->path()QLatin1String("/myapp_XXXXXX.txt") +//Add to constructor and adapt if necessay: m_tempdir->path()QLatin1String("/myapp_XXXXXX.txt") //code was temp.setSuffix(".tex"); -//Add to constructor and adapt if necessay: QDir::tempPath() + QLatin1String("/myapp_XXXXXX") + QLatin1String(".tex") - temp.setAutoRemove(false); - - if(!temp.open()) { - KILE_DEBUG_MAIN << "Could not create tempfile in PdfDialog::buildLatexFile()" ; - return QString(); - } - QString tempname = temp.fileName(); - - QTextStream stream(&temp); - stream << "\\documentclass[a4paper,12pt]{article}"; - stream << "\\usepackage[final]{pdfpages}"; - stream << "\\begin{document}"; - stream << "\\includepdf[" << param << "]{" << m_inputfile << "}"; - stream << "\\end{document}"; - - // everything is prepared to do the job - temp.close(); - return(tempname.left(tempname.length() - 4)); +//Add to constructor and adapt if necessay: QDir::tempPath() + QLatin1String("/myapp_XXXXXX") + QLatin1String(".tex") + temp.setAutoRemove(false); + + if(!temp.open()) { + KILE_DEBUG_MAIN << "Could not create tempfile in PdfDialog::buildLatexFile()" ; + return QString(); + } + QString tempname = temp.fileName(); + + QTextStream stream(&temp); + stream << "\\documentclass[a4paper,12pt]{article}"; + stream << "\\usepackage[final]{pdfpages}"; + stream << "\\begin{document}"; + stream << "\\includepdf[" << param << "]{" << m_inputfile << "}"; + stream << "\\end{document}"; + + // everything is prepared to do the job + temp.close(); + return(tempname.left(tempname.length() - 4)); } // create a temporary pdf file to set a background color QString PdfDialog::buildPdfBackgroundFile(QColor *color) { - QTemporaryFile temp; + QTemporaryFile temp; //code was temp.setPrefix(m_tempdir->path()); -//Add to constructor and adapt if necessay: m_tempdir->path()QLatin1String("/myapp_XXXXXX.txt") +//Add to constructor and adapt if necessay: m_tempdir->path()QLatin1String("/myapp_XXXXXX.txt") //code was temp.setSuffix(".pdf"); -//Add to constructor and adapt if necessay: QDir::tempPath() + QLatin1String("/myapp_XXXXXX") + QLatin1String(".pdf") - temp.setAutoRemove(false); - - if(!temp.open()) { - KILE_DEBUG_MAIN << "Could not create tempfile in PdfDialog::buildPdfBackgroundFile()" ; - return QString(); - } - QString tempname = temp.fileName(); - - QTextStream stream(&temp); - stream << "%PDF-1.4\n"; - stream << '%' << '\0' << '\0' << '\0' << '\0' << '\r'; - stream << "5 0 obj \n" - "<<\n" - "/Type /ExtGState\n" - "/OPM 1\n" - ">>\n" - "endobj \n" - "4 0 obj \n" - "<<\n" - "/R7 5 0 R\n" - ">>\n" - "endobj \n" - "6 0 obj \n" - "<<\n" - "/Length 83\n" - ">>\n" - "stream\n" - "q 0.1 0 0 0.1 0 0 cm\n" - "/R7 gs\n"; - stream << color->redF() << " " << color->greenF() << " " << color->blueF() << " rg\n"; - stream << "0 0 " << 10*m_pagesize.width() << " " << 10*m_pagesize.height() << " re\n"; - stream << "f\n" - "0 g\n" - "Q\n" - "\n" - "endstream \n" - "endobj \n" - "3 0 obj \n" - "<<\n" - "/Parent 1 0 R\n"; - stream << "/MediaBox [0 0 " << m_pagesize.width() << " " << m_pagesize.height() << "]\n"; - stream << "/Resources \n" - "<<\n" - "/ExtGState 4 0 R\n" - "/ProcSet [/PDF]\n" - ">>\n" - "/pdftk_PageNum 1\n" - "/Type /Page\n" - "/Contents 6 0 R\n" - ">>\n" - "endobj \n" - "1 0 obj \n" - "<<\n" - "/Kids [3 0 R]\n" - "/Count 1\n" - "/Type /Pages\n" - ">>\n" - "endobj \n" - "7 0 obj \n" - "<<\n" - "/Pages 1 0 R\n" - "/Type /Catalog\n" - ">>\n" - "endobj \n" - "8 0 obj \n" - "<<\n" - "/Creator ()\n" - "/Producer ())\n" - "/ModDate ()\n" - "/CreationDate ()\n" - ">>\n" - "endobj xref\n" - "0 9\n" - "0000000000 65535 f \n" - "0000000388 00000 n \n" - "0000000000 65536 n \n" - "0000000231 00000 n \n" - "0000000062 00000 n \n" - "0000000015 00000 n \n" - "0000000095 00000 n \n" - "0000000447 00000 n \n" - "0000000498 00000 n \n" - "trailer\n" - "\n" - "<<\n" - "/Info 8 0 R\n" - "/Root 7 0 R\n" - "/Size 9\n" - "/ID [<4a7c31ef3aeb884b18f59c2037a752f5><54079f85d95a11f3400fe5fc3cfc832b>]\n" - ">>\n" - "startxref\n" - "721\n" - "%%EOF\n"; - - // everything is prepared to do the job - temp.close(); - return tempname; +//Add to constructor and adapt if necessay: QDir::tempPath() + QLatin1String("/myapp_XXXXXX") + QLatin1String(".pdf") + temp.setAutoRemove(false); + + if(!temp.open()) { + KILE_DEBUG_MAIN << "Could not create tempfile in PdfDialog::buildPdfBackgroundFile()" ; + return QString(); + } + QString tempname = temp.fileName(); + + QTextStream stream(&temp); + stream << "%PDF-1.4\n"; + stream << '%' << '\0' << '\0' << '\0' << '\0' << '\r'; + stream << "5 0 obj \n" + "<<\n" + "/Type /ExtGState\n" + "/OPM 1\n" + ">>\n" + "endobj \n" + "4 0 obj \n" + "<<\n" + "/R7 5 0 R\n" + ">>\n" + "endobj \n" + "6 0 obj \n" + "<<\n" + "/Length 83\n" + ">>\n" + "stream\n" + "q 0.1 0 0 0.1 0 0 cm\n" + "/R7 gs\n"; + stream << color->redF() << " " << color->greenF() << " " << color->blueF() << " rg\n"; + stream << "0 0 " << 10*m_pagesize.width() << " " << 10*m_pagesize.height() << " re\n"; + stream << "f\n" + "0 g\n" + "Q\n" + "\n" + "endstream \n" + "endobj \n" + "3 0 obj \n" + "<<\n" + "/Parent 1 0 R\n"; + stream << "/MediaBox [0 0 " << m_pagesize.width() << " " << m_pagesize.height() << "]\n"; + stream << "/Resources \n" + "<<\n" + "/ExtGState 4 0 R\n" + "/ProcSet [/PDF]\n" + ">>\n" + "/pdftk_PageNum 1\n" + "/Type /Page\n" + "/Contents 6 0 R\n" + ">>\n" + "endobj \n" + "1 0 obj \n" + "<<\n" + "/Kids [3 0 R]\n" + "/Count 1\n" + "/Type /Pages\n" + ">>\n" + "endobj \n" + "7 0 obj \n" + "<<\n" + "/Pages 1 0 R\n" + "/Type /Catalog\n" + ">>\n" + "endobj \n" + "8 0 obj \n" + "<<\n" + "/Creator ()\n" + "/Producer ())\n" + "/ModDate ()\n" + "/CreationDate ()\n" + ">>\n" + "endobj xref\n" + "0 9\n" + "0000000000 65535 f \n" + "0000000388 00000 n \n" + "0000000000 65536 n \n" + "0000000231 00000 n \n" + "0000000062 00000 n \n" + "0000000015 00000 n \n" + "0000000095 00000 n \n" + "0000000447 00000 n \n" + "0000000498 00000 n \n" + "trailer\n" + "\n" + "<<\n" + "/Info 8 0 R\n" + "/Root 7 0 R\n" + "/Size 9\n" + "/ID [<4a7c31ef3aeb884b18f59c2037a752f5><54079f85d95a11f3400fe5fc3cfc832b>]\n" + ">>\n" + "startxref\n" + "721\n" + "%%EOF\n"; + + // everything is prepared to do the job + temp.close(); + return tempname; } QString PdfDialog::buildPageRange(int type) { - QString s; - for (int i = 1; i <= m_numpages; ++i) { - if (type == PDF_PAGE_EMPTY) { - s += QString("%1,{},").arg(i); - } - else { - s += QString("%1,%2,").arg(i).arg(i); - } - } - - return "{" + s.left(s.length()-1) + "}"; + QString s; + for (int i = 1; i <= m_numpages; ++i) { + if (type == PDF_PAGE_EMPTY) { + s += QString("%1,{},").arg(i); + } + else { + s += QString("%1,%2,").arg(i).arg(i); + } + } + + return "{" + s.left(s.length()-1) + "}"; } QString PdfDialog::buildPageList(bool even) { - QString s, number; + QString s, number; - int start = ( even ) ? 2 : 1; - for (int i=start; i<=m_numpages; i+=2 ) { - s += number.setNum(i) + ","; - } + int start = ( even ) ? 2 : 1; + for (int i=start; i<=m_numpages; i+=2 ) { + s += number.setNum(i) + ","; + } - if ( !s.isEmpty() ) { - s.truncate(s.length()-1); - } - return "{" + s + "}"; + if ( !s.isEmpty() ) { + s.truncate(s.length()-1); + } + return "{" + s + "}"; } QString PdfDialog::buildReversPageList(bool even) { - QString s,number; - - int last = m_numpages; - if ( even ) { - if ( (last & 1) == 1 ) { - last--; - } - } - else { - if ( (last & 1) == 0 ) { - last--; - } - } - - for (int i=last; i>=1; i-=2 ) { - s += number.setNum(i) + ","; - } - - if ( !s.isEmpty() ) { - s.truncate(s.length()-1); - } - return "{" + s + "}"; + QString s,number; + + int last = m_numpages; + if ( even ) { + if ( (last & 1) == 1 ) { + last--; + } + } + else { + if ( (last & 1) == 0 ) { + last--; + } + } + + for (int i=last; i>=1; i-=2 ) { + s += number.setNum(i) + ","; + } + + if ( !s.isEmpty() ) { + s.truncate(s.length()-1); + } + return "{" + s + "}"; } QString PdfDialog::buildSelectPageList() { - return m_PdfDialog.m_edParameter->text().trimmed(); + return m_PdfDialog.m_edParameter->text().trimmed(); } QString PdfDialog::buildDeletePageList() { - // m_numpages is known - QString param = m_PdfDialog.m_edParameter->text().trimmed(); - QRegExp re("(\\d+)-(\\d+)"); - - // analyze delete list - bool ok; - QBitArray arr(m_numpages + 1,false); - QStringList pagelist = param.split(','); - foreach (const QString &s, pagelist) { - if ( s.contains('-') && re.indexIn(s) >= 0 ) { - int from = re.cap(1).toInt(&ok); - int to = re.cap(2).toInt(&ok); - for (int i=from; i<=to; ++i) { - arr.setBit(i); - } - } - else { - arr.setBit(s.toInt(&ok)); - } - } - - // build select list - QString result; - int page = 1; - while ( page <= m_numpages ) { - int from = searchPages(&arr,page,m_numpages,true); - if ( from > m_numpages ) { - break; - } - int to = searchPages(&arr,from+1,m_numpages,false) - 1; - if ( !result.isEmpty() ) { - result += ","; - } - if ( from < to ) { - result += QString::number(from) + "-" + QString::number(to); - } - else { - result += QString::number(from); - } - page = to + 1; - } - - return result; + // m_numpages is known + QString param = m_PdfDialog.m_edParameter->text().trimmed(); + QRegExp re("(\\d+)-(\\d+)"); + + // analyze delete list + bool ok; + QBitArray arr(m_numpages + 1,false); + QStringList pagelist = param.split(','); + foreach (const QString &s, pagelist) { + if ( s.contains('-') && re.indexIn(s) >= 0 ) { + int from = re.cap(1).toInt(&ok); + int to = re.cap(2).toInt(&ok); + for (int i=from; i<=to; ++i) { + arr.setBit(i); + } + } + else { + arr.setBit(s.toInt(&ok)); + } + } + + // build select list + QString result; + int page = 1; + while ( page <= m_numpages ) { + int from = searchPages(&arr,page,m_numpages,true); + if ( from > m_numpages ) { + break; + } + int to = searchPages(&arr,from+1,m_numpages,false) - 1; + if ( !result.isEmpty() ) { + result += ","; + } + if ( from < to ) { + result += QString::number(from) + "-" + QString::number(to); + } + else { + result += QString::number(from); + } + page = to + 1; + } + + return result; } int PdfDialog::searchPages(QBitArray *arr, int page, int lastpage, bool value) { - while ( page <= lastpage ) { - if ( arr->at(page) != value ) { - return page; - } - page++; - } - return lastpage + 1; + while ( page <= lastpage ) { + if ( arr->at(page) != value ) { + return page; + } + page++; + } + return lastpage + 1; } bool PdfDialog::checkParameter() { - if ( !checkInputFile() ) { - return false; - } - - if ( m_encrypted ) { - if ( !checkPassword() ) { - return false; - } - } - - // check parameter - int taskindex = taskIndex(); - if ( isParameterTask(taskindex) && m_PdfDialog.m_edParameter->text().trimmed().isEmpty() ) { - showError( i18n("The utility needs some parameters in this mode.") ); - return false; - } - - // check select/delete page list (m_numpages is known) - if ( taskindex==PDF_SELECT || taskindex==PDF_DELETE ) { - // m_numpages is known - QString param = m_PdfDialog.m_edParameter->text().trimmed(); - QRegExp re("(\\d+)-(\\d+)"); - - // analyze page list - bool ok; - QStringList pagelist = param.split(','); - foreach (const QString &s, pagelist) { - if ( s.contains('-') && re.indexIn(s)>=0 ) { - int from = re.cap(1).toInt(&ok); - int to = re.cap(2).toInt(&ok); - if ( from > to ) { - showError(i18n("Illegal page list 'from-to': %1 is bigger than %2.",from,to)); - return false; - } - if ( to > m_numpages ) { - showError(i18n("Illegal pagenumber: %1.",to)); - return false; - } - } - else { - int page = s.toInt(&ok); - if ( page > m_numpages ) { - showError(i18n("Illegal pagenumber: %1.",page)); - return false; - } - } - } - } - - // check background/stamp parameter - if ( isOverlayTask(taskindex) ) { - QString filename = m_PdfDialog.m_edStamp->text().trimmed(); - - if ( filename.isEmpty() ) { - QString message = ( taskindex == PDF_PDFTK_STAMP ) - ? i18n("You need to define a PDF file as foreground stamp.") - : i18n("You need to define a PDF file as background watermark."); - showError(message); - return false; - } - - QFileInfo fs(filename); - if (fs.completeSuffix() != "pdf") { - showError(i18n("Unknown file format: only '.pdf' is accepted as image file in this mode.")); - return false; - } - - if ( !QFile::exists(filename) ) { - showError(i18n("The given file doesn't exist.")); - return false; - } - } - - // overwrite mode: no output file is needed - if ( m_PdfDialog.m_cbOverwrite->isChecked() ) { - return true; - } - - // create a different output file - QString outfile = m_PdfDialog.m_edOutfile->lineEdit()->text().trimmed(); - if ( outfile.isEmpty() ) { - showError(i18n("You need to define an output file.")); - return false; - } - - // outfile file must have extension pdf - QFileInfo fo(outfile); - if (fo.completeSuffix() != "pdf") { - showError(i18n("Unknown file format: only '.pdf' is accepted as output file.")); - return false; - } - - // check, if this output file already exists - if ( fo.exists() ) { - QString s = i18n("A file named \"%1\" already exists. Are you sure you want to overwrite it?", fo.fileName()); - if (KMessageBox::questionYesNo(this, - "
" + s + "
", - i18n("PDF Tools")) == KMessageBox::No) { - return false; - } - } - - return true; + if ( !checkInputFile() ) { + return false; + } + + if ( m_encrypted ) { + if ( !checkPassword() ) { + return false; + } + } + + // check parameter + int taskindex = taskIndex(); + if ( isParameterTask(taskindex) && m_PdfDialog.m_edParameter->text().trimmed().isEmpty() ) { + showError( i18n("The utility needs some parameters in this mode.") ); + return false; + } + + // check select/delete page list (m_numpages is known) + if ( taskindex==PDF_SELECT || taskindex==PDF_DELETE ) { + // m_numpages is known + QString param = m_PdfDialog.m_edParameter->text().trimmed(); + QRegExp re("(\\d+)-(\\d+)"); + + // analyze page list + bool ok; + QStringList pagelist = param.split(','); + foreach (const QString &s, pagelist) { + if ( s.contains('-') && re.indexIn(s)>=0 ) { + int from = re.cap(1).toInt(&ok); + int to = re.cap(2).toInt(&ok); + if ( from > to ) { + showError(i18n("Illegal page list 'from-to': %1 is bigger than %2.",from,to)); + return false; + } + if ( to > m_numpages ) { + showError(i18n("Illegal pagenumber: %1.",to)); + return false; + } + } + else { + int page = s.toInt(&ok); + if ( page > m_numpages ) { + showError(i18n("Illegal pagenumber: %1.",page)); + return false; + } + } + } + } + + // check background/stamp parameter + if ( isOverlayTask(taskindex) ) { + QString filename = m_PdfDialog.m_edStamp->text().trimmed(); + + if ( filename.isEmpty() ) { + QString message = ( taskindex == PDF_PDFTK_STAMP ) + ? i18n("You need to define a PDF file as foreground stamp.") + : i18n("You need to define a PDF file as background watermark."); + showError(message); + return false; + } + + QFileInfo fs(filename); + if (fs.completeSuffix() != "pdf") { + showError(i18n("Unknown file format: only '.pdf' is accepted as image file in this mode.")); + return false; + } + + if ( !QFile::exists(filename) ) { + showError(i18n("The given file doesn't exist.")); + return false; + } + } + + // overwrite mode: no output file is needed + if ( m_PdfDialog.m_cbOverwrite->isChecked() ) { + return true; + } + + // create a different output file + QString outfile = m_PdfDialog.m_edOutfile->lineEdit()->text().trimmed(); + if ( outfile.isEmpty() ) { + showError(i18n("You need to define an output file.")); + return false; + } + + // outfile file must have extension pdf + QFileInfo fo(outfile); + if (fo.completeSuffix() != "pdf") { + showError(i18n("Unknown file format: only '.pdf' is accepted as output file.")); + return false; + } + + // check, if this output file already exists + if ( fo.exists() ) { + QString s = i18n("A file named \"%1\" already exists. Are you sure you want to overwrite it?", fo.fileName()); + if (KMessageBox::questionYesNo(this, + "
" + s + "
", + i18n("PDF Tools")) == KMessageBox::No) { + return false; + } + } + + return true; } bool PdfDialog::checkProperties() { - if ( !checkInputFile() ) { - return false; - } + if ( !checkInputFile() ) { + return false; + } - return ( m_encrypted ) ? checkPassword() : true; + return ( m_encrypted ) ? checkPassword() : true; } bool PdfDialog::checkPermissions() { - if ( !checkInputFile() ) { - return false; - } + if ( !checkInputFile() ) { + return false; + } - return checkPassword(); + return checkPassword(); } bool PdfDialog::checkInputFile() { - QString infile = m_PdfDialog.m_edInfile->lineEdit()->text().trimmed(); - if (infile.isEmpty()) { - showError(i18n("No input file is given.")); - return false; - } - - QFileInfo fi(infile); - QString suffix = fi.completeSuffix(); - if (suffix != "pdf") { - showError(i18n("Unknown file format: only '.pdf' are accepted for input files.")); - return false; - } - - if (!fi.exists()) { - showError(i18n("This input file does not exist.")); - return false; - } - - return true; + QString infile = m_PdfDialog.m_edInfile->lineEdit()->text().trimmed(); + if (infile.isEmpty()) { + showError(i18n("No input file is given.")); + return false; + } + + QFileInfo fi(infile); + QString suffix = fi.completeSuffix(); + if (suffix != "pdf") { + showError(i18n("Unknown file format: only '.pdf' are accepted for input files.")); + return false; + } + + if (!fi.exists()) { + showError(i18n("This input file does not exist.")); + return false; + } + + return true; } bool PdfDialog::checkPassword() { - // check password - QString password = m_PdfDialog.m_edPassword->text().trimmed(); - if (password.isEmpty()) { - showError(i18n("No password is given.")); - return false; - } - - if (password.length() < 6) { - showError(i18n("The password should be at least 6 characters long.")); - return false; - } - - return true; + // check password + QString password = m_PdfDialog.m_edPassword->text().trimmed(); + if (password.isEmpty()) { + showError(i18n("No password is given.")); + return false; + } + + if (password.length() < 6) { + showError(i18n("The password should be at least 6 characters long.")); + return false; + } + + return true; } void PdfDialog::showError(const QString &text) { - KMessageBox::error(this, i18n("
") + text + i18n("
"), i18n("PDF Tools")); + KMessageBox::error(this, i18n("
") + text + i18n("
"), i18n("PDF Tools")); } // check tasks bool PdfDialog::isParameterTask(int task) { - return ( task==PDF_SELECT || task==PDF_DELETE || task==PDF_PDFPAGES_FREE || task==PDF_PDFTK_FREE ); + return ( task==PDF_SELECT || task==PDF_DELETE || task==PDF_PDFPAGES_FREE || task==PDF_PDFTK_FREE ); } bool PdfDialog::isOverlayTask(int task) { - return ( task==PDF_PDFTK_BACKGROUND || task==PDF_PDFTK_STAMP ); + return ( task==PDF_PDFTK_BACKGROUND || task==PDF_PDFTK_STAMP ); } bool PdfDialog::isBackgroundColor(int task) { - return ( task == PDF_PDFTK_BGCOLOR ) ? true : false; + return ( task == PDF_PDFTK_BGCOLOR ) ? true : false; } bool PdfDialog::isFreeTask(int task) { - return ( task==PDF_PDFPAGES_FREE || task==PDF_PDFTK_FREE ); + return ( task==PDF_PDFPAGES_FREE || task==PDF_PDFTK_FREE ); } } diff --git a/src/dialogs/pdf-wizard/pdfdialog.h b/src/dialogs/pdf-wizard/pdfdialog.h index b2149900..fd751c38 100644 --- a/src/dialogs/pdf-wizard/pdfdialog.h +++ b/src/dialogs/pdf-wizard/pdfdialog.h @@ -1,207 +1,207 @@ /****************************************************************************** Copyright (C) 2009-2011 by Holger Danielsson (holger.danielsson@versanet.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. * * * ***************************************************************************/ #ifndef PDFDIALOG_H #define PDFDIALOG_H #include #if LIBPOPPLER_AVAILABLE #include #endif #include #include #include #include #include #include #include #include "widgets/outputview.h" #include "widgets/categorycombobox.h" #include "kiletool_enums.h" #include "kiletoolmanager.h" #include "ui_pdfdialog_base.h" class QDialogButtonBox; class QLineEdit; class KProcess; class KileErrorHandler; namespace KileDialog { class PdfDialog : public QDialog { - Q_OBJECT - - public: - PdfDialog(QWidget *parent, - const QString &texfilename, const QString &startdir, - const QString &latexextensions, - KileTool::Manager *manager, - KileErrorHandler *errorHandler, KileWidget::OutputView *output); - ~PdfDialog(); - - Q_SIGNALS: - void output(const QString &); - - private Q_SLOTS: - void slotInputfileChanged(const QString &text); - void slotOutputfileChanged(const QString &text); - void slotTaskChanged(int index); - void slotOverwriteChanged(int state); - void slotExecute(); - void slotShowHelp(); - void slotTabwidgetChanged(int index); - void slotPrintingClicked(); - void slotAllClicked(); - void slotPermissionClicked(bool); - - void slotProcessOutput(); - void slotProcessExited(int exitCode, QProcess::ExitStatus exitStatus); - - private: - enum PDF_Permission { AllowModify = 1, // Allows to modify the document - AllowCopy = 2, // Allows to copy the document - AllowPrint = 4, // Allows to print the document - AllowNotes = 8, // Allows to add annotations to the document - AllowFillForms = 16 // Allows to fill the forms in the document - }; - - enum PDF_Action { PDF_PAGE_EMPTY=0, PDF_PAGE_DUPLICATE=1, PDF_2UP=2, PDF_2UP_LANDSCAPE=3, - PDF_4UP=4, PDF_4UP_LANDSCAPE=5, PDF_EVEN=6, PDF_ODD=7, - PDF_EVEN_REV=8, PDF_ODD_REV=9, PDF_REVERSE=10, PDF_DECRYPT=11, - PDF_SELECT=12, PDF_DELETE=13, - PDF_PDFTK_BACKGROUND=14, PDF_PDFTK_BGCOLOR=15, PDF_PDFTK_STAMP=16, - PDF_PDFTK_FREE=17, PDF_PDFPAGES_FREE=18 - }; - - enum PDF_ScriptMode { PDF_SCRIPTMODE_TOOLS=0, PDF_SCRIPTMODE_ACTION=1, - PDF_SCRIPTMODE_PROPERTIES=2, PDF_SCRIPTMODE_PERMISSIONS=3, + Q_OBJECT + +public: + PdfDialog(QWidget *parent, + const QString &texfilename, const QString &startdir, + const QString &latexextensions, + KileTool::Manager *manager, + KileErrorHandler *errorHandler, KileWidget::OutputView *output); + ~PdfDialog(); + +Q_SIGNALS: + void output(const QString &); + +private Q_SLOTS: + void slotInputfileChanged(const QString &text); + void slotOutputfileChanged(const QString &text); + void slotTaskChanged(int index); + void slotOverwriteChanged(int state); + void slotExecute(); + void slotShowHelp(); + void slotTabwidgetChanged(int index); + void slotPrintingClicked(); + void slotAllClicked(); + void slotPermissionClicked(bool); + + void slotProcessOutput(); + void slotProcessExited(int exitCode, QProcess::ExitStatus exitStatus); + +private: + enum PDF_Permission { AllowModify = 1, // Allows to modify the document + AllowCopy = 2, // Allows to copy the document + AllowPrint = 4, // Allows to print the document + AllowNotes = 8, // Allows to add annotations to the document + AllowFillForms = 16 // Allows to fill the forms in the document + }; + + enum PDF_Action { PDF_PAGE_EMPTY=0, PDF_PAGE_DUPLICATE=1, PDF_2UP=2, PDF_2UP_LANDSCAPE=3, + PDF_4UP=4, PDF_4UP_LANDSCAPE=5, PDF_EVEN=6, PDF_ODD=7, + PDF_EVEN_REV=8, PDF_ODD_REV=9, PDF_REVERSE=10, PDF_DECRYPT=11, + PDF_SELECT=12, PDF_DELETE=13, + PDF_PDFTK_BACKGROUND=14, PDF_PDFTK_BGCOLOR=15, PDF_PDFTK_STAMP=16, + PDF_PDFTK_FREE=17, PDF_PDFPAGES_FREE=18 + }; + + enum PDF_ScriptMode { PDF_SCRIPTMODE_TOOLS=0, PDF_SCRIPTMODE_ACTION=1, + PDF_SCRIPTMODE_PROPERTIES=2, PDF_SCRIPTMODE_PERMISSIONS=3, #if !LIBPOPPLER_AVAILABLE - PDF_SCRIPTMODE_NUMPAGES_PDFTK=4, - PDF_SCRIPTMODE_NUMPAGES_IMAGEMAGICK=5, - PDF_SCRIPTMODE_NUMPAGES_GHOSTSCRIPT=6 + PDF_SCRIPTMODE_NUMPAGES_PDFTK=4, + PDF_SCRIPTMODE_NUMPAGES_IMAGEMAGICK=5, + PDF_SCRIPTMODE_NUMPAGES_GHOSTSCRIPT=6 #endif - }; - - QString m_inputfile; - QString m_outputfile; - QStringList m_tasklist; - - void executeAction(); - void executeProperties(); - void executePermissions(); - - bool checkParameter(); - bool checkProperties(); - bool checkPermissions(); - bool checkInputFile(); - bool checkPassword(); - - bool isParameterTask(int task); - bool isOverlayTask(int task); - bool isBackgroundColor(int task); - bool isFreeTask(int task); - - QString buildActionCommand(); - QString buildLatexFile(const QString ¶m); - QString buildPdfBackgroundFile(QColor *color); - QString buildPageRange(int type); - QString buildPageList(bool even); - QString buildReversPageList(bool even); - QString buildSelectPageList(); - QString buildDeletePageList(); - - int searchPages(QBitArray *arr, int page, int lastpage, bool value); - QString getOutfileName(const QString &infile); - void showError(const QString &text); - - void executeScript(const QString &command, const QString &dir, int scriptmode); - void showLogs(const QString &title, const QString &inputfile, const QString ¶m); - - void initUtilities(); - void finishPdfAction(bool state); - void runViewer(); - void updateDialog(); - void updateOwnerPassword(bool infile_exists); - void updateToolsInfo(); - void updateTasks(); - int taskIndex(); - void clearDocumentInfo(); - void setPermissions(bool print,bool other); - QString readPermissions(); - void setNumberOfPages(int numpages); + }; + + QString m_inputfile; + QString m_outputfile; + QStringList m_tasklist; + + void executeAction(); + void executeProperties(); + void executePermissions(); + + bool checkParameter(); + bool checkProperties(); + bool checkPermissions(); + bool checkInputFile(); + bool checkPassword(); + + bool isParameterTask(int task); + bool isOverlayTask(int task); + bool isBackgroundColor(int task); + bool isFreeTask(int task); + + QString buildActionCommand(); + QString buildLatexFile(const QString ¶m); + QString buildPdfBackgroundFile(QColor *color); + QString buildPageRange(int type); + QString buildPageList(bool even); + QString buildReversPageList(bool even); + QString buildSelectPageList(); + QString buildDeletePageList(); + + int searchPages(QBitArray *arr, int page, int lastpage, bool value); + QString getOutfileName(const QString &infile); + void showError(const QString &text); + + void executeScript(const QString &command, const QString &dir, int scriptmode); + void showLogs(const QString &title, const QString &inputfile, const QString ¶m); + + void initUtilities(); + void finishPdfAction(bool state); + void runViewer(); + void updateDialog(); + void updateOwnerPassword(bool infile_exists); + void updateToolsInfo(); + void updateTasks(); + int taskIndex(); + void clearDocumentInfo(); + void setPermissions(bool print,bool other); + QString readPermissions(); + void setNumberOfPages(int numpages); #if LIBPOPPLER_AVAILABLE - QSize allPagesSize(Poppler::Document *doc); - bool isAllowed(Poppler::Document *doc, PDF_Permission permission) const; + QSize allPagesSize(Poppler::Document *doc); + bool isAllowed(Poppler::Document *doc, PDF_Permission permission) const; #endif - void pdfParser(const QString &filename); + void pdfParser(const QString &filename); - QString m_startdir; - KileTool::Manager *m_manager; - KileErrorHandler *m_errorHandler; - KileWidget::OutputView *m_output; - KileWidget::CategoryComboBox *m_cbTask; + QString m_startdir; + KileTool::Manager *m_manager; + KileErrorHandler *m_errorHandler; + KileWidget::OutputView *m_output; + KileWidget::CategoryComboBox *m_cbTask; - int m_scriptmode; - QString m_outputtext; - bool m_execLatex; - QString m_param; - bool m_scriptrunning; + int m_scriptmode; + QString m_outputtext; + bool m_execLatex; + QString m_param; + bool m_scriptrunning; - QTemporaryDir *m_tempdir; - QStringList m_move_filelist; + QTemporaryDir *m_tempdir; + QStringList m_move_filelist; - bool m_poppler; - bool m_pdftk; - bool m_pdfpages; + bool m_poppler; + bool m_pdftk; + bool m_pdfpages; - int m_numpages; - bool m_encrypted; - QSize m_pagesize; + int m_numpages; + bool m_encrypted; + QSize m_pagesize; - QStringList m_pdfInfoKeys; - QMap m_pdfInfo; - QMap m_pdfInfoWidget; - QMap m_pdfInfoPdftk; + QStringList m_pdfInfoKeys; + QMap m_pdfInfo; + QMap m_pdfInfoWidget; + QMap m_pdfInfoPdftk; - QVector m_pdfPermissionKeys; - QVector m_pdfPermissionWidgets; - QVector m_pdfPermissionPdftk; - QVector m_pdfPermissionState; + QVector m_pdfPermissionKeys; + QVector m_pdfPermissionWidgets; + QVector m_pdfPermissionPdftk; + QVector m_pdfPermissionState; - KProcess* m_proc; + KProcess* m_proc; - QPushButton *m_rearrangeButton; - QDialogButtonBox *m_buttonBox; - Ui::PdfDialog m_PdfDialog; + QPushButton *m_rearrangeButton; + QDialogButtonBox *m_buttonBox; + Ui::PdfDialog m_PdfDialog; #if !LIBPOPPLER_AVAILABLE - int m_imagemagick; - int m_numpagesMode; - void determineNumberOfPages(const QString &filename, bool askForPasswor); - void readNumberOfPages(int scriptmode, const QString &output); - bool readEncryption(const QString &filename); + int m_imagemagick; + int m_numpagesMode; + void determineNumberOfPages(const QString &filename, bool askForPasswor); + void readNumberOfPages(int scriptmode, const QString &output); + bool readEncryption(const QString &filename); #endif }; } #endif diff --git a/src/dialogs/postscriptdialog.cpp b/src/dialogs/postscriptdialog.cpp index bc05af49..4ee27f3b 100644 --- a/src/dialogs/postscriptdialog.cpp +++ b/src/dialogs/postscriptdialog.cpp @@ -1,498 +1,516 @@ /********************************************************************************** Ccopyright (C) 2005-2007 by Holger Danielsson (holger.danielsson@versanet.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. * * * ***************************************************************************/ // 2007-03-12 dani // - use KileDocument::Extensions #include "dialogs/postscriptdialog.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "errorhandler.h" #include "kiledebug.h" #include "kiletool_enums.h" namespace KileDialog { PostscriptDialog::PostscriptDialog(QWidget *parent, const QString &texfilename,const QString &startdir, const QString &latexextensions, KileErrorHandler *errorHandler, KileWidget::OutputView *output) : - QDialog(parent), - m_startdir(startdir), - m_errorHandler(errorHandler), - m_output(output), - m_proc(Q_NULLPTR) -{ - setWindowTitle(i18n("Rearrange Postscript File")); - setModal(true); - - QWidget *mainWidget = new QWidget(this); - QVBoxLayout *mainLayout = new QVBoxLayout; - setLayout(mainLayout); - mainLayout->addWidget(mainWidget); - - - // determine if a psfile already exists - QString psfilename,psoutfilename; - if(!texfilename.isEmpty()) { - // working with a postscript document, so we try to determine the LaTeX source file - QStringList extlist = latexextensions.split(' '); - for (QStringList::Iterator it = extlist.begin(); it != extlist.end(); ++it) { - if (texfilename.indexOf((*it), -(*it).length()) >= 0) { - QString basename = psfilename = texfilename.left(texfilename.length() - (*it).length()); - psfilename = basename + ".ps"; - psoutfilename = basename + "-out.ps"; - if (!QFileInfo(psfilename).exists()) - psfilename.clear(); - break; - } - } - } - - // prepare dialog - QWidget *page = new QWidget(this); - mainLayout->addWidget(page); - m_PostscriptDialog.setupUi(page); - - // line 0: QLabel - bool pstops = !QStandardPaths::findExecutable("pstops").isEmpty(); - bool psselect = !QStandardPaths::findExecutable("psselect").isEmpty(); - - if (!pstops || !psselect) { - QString msg; - if (!pstops) { - msg = "'pstops'"; - if (!psselect) - msg += " and "; - } - if (!psselect) { - msg += "'psselect'"; - } - m_PostscriptDialog.m_lbInfo->setText(m_PostscriptDialog.m_lbInfo->text() + "\n(Error: " + msg + " not found.)"); - } - - m_PostscriptDialog.m_edInfile->lineEdit()->setText(psfilename); - m_PostscriptDialog.m_edOutfile->lineEdit()->setText(psoutfilename); - - // according to QT 4.4 docu the index of QComboBox might change if adding or removing items - // but because we populate the QComboBox before we start the dialog, we can use the index here - if (pstops) { - m_PostscriptDialog.m_cbTask->addItem(i18n("1 DIN A5 Page + Empty Page --> DIN A4")); // 0 PS_A5_EMPTY - m_PostscriptDialog.m_cbTask->addItem(i18n("1 DIN A5 Page + Duplicate --> DIN A4")); // 1 PS_A5_DUPLICATE - m_PostscriptDialog.m_cbTask->addItem(i18n("2 DIN A5 Pages --> DIN A4")); // 2 PS_2xA5 - m_PostscriptDialog.m_cbTask->addItem(i18n("2 DIN A5L Pages --> DIN A4")); // 3 PS_2xA5L - m_PostscriptDialog.m_cbTask->addItem(i18n("4 DIN A5 Pages --> DIN A4")); // 4 PS_4xA5 - m_PostscriptDialog.m_cbTask->addItem(i18n("1 DIN A4 Page + Empty Page --> DIN A4")); // 5 m_PostscriptDialog.PS_A4_EMPTY - m_PostscriptDialog.m_cbTask->addItem(i18n("1 DIN A4 Page + Duplicate --> DIN A4")); // 6 PS_A4_DUPLICATE - m_PostscriptDialog.m_cbTask->addItem(i18n("2 DIN A4 Pages --> DIN A4")); // 7 PS_2xA4 - m_PostscriptDialog.m_cbTask->addItem(i18n("2 DIN A4L Pages --> DIN A4")); // 8 PS_2xA4L - } - if (psselect) { - m_PostscriptDialog.m_cbTask->addItem(i18n("Select Even Pages")); // 9 PS_EVEN - m_PostscriptDialog.m_cbTask->addItem(i18n("Select Odd Pages")); // 10 PS_ODD - m_PostscriptDialog.m_cbTask->addItem(i18n("Select Even Pages (reverse order)")); // 11 m_PostscriptDialog.PS_EVEN_REV - m_PostscriptDialog.m_cbTask->addItem(i18n("Select Odd Pages (reverse order)")); // 12 PS_ODD_REV - m_PostscriptDialog.m_cbTask->addItem(i18n("Reverse All Pages")); // 13 PS_REVERSE - m_PostscriptDialog.m_cbTask->addItem(i18n("Copy All Pages (sorted)")); // 14 PS_COPY_SORTED - } - if (pstops) { - m_PostscriptDialog.m_cbTask->addItem(i18n("Copy All Pages (unsorted)")); // 15 PS_COPY_UNSORTED - m_PostscriptDialog.m_cbTask->addItem(i18n("pstops: Choose Parameter")); // 16 PS_PSTOPS_FREE - } - if (psselect) { - m_PostscriptDialog.m_cbTask->addItem(i18n("psselect: Choose Parameter")); // 17 PS_PSSELECT_FREE - } - - m_PostscriptDialog.m_edInfile->setFilter("*.ps|PS Files\n*.ps.gz|Zipped PS Files"); - m_PostscriptDialog.m_edOutfile->setFilter("*.ps|PS Files\n*.ps.gz|Zipped PS Files"); - m_PostscriptDialog.m_edOutfile->setMode(KFile::File | KFile::LocalOnly); - - // choose one common task - m_PostscriptDialog.m_cbTask->setCurrentIndex(PS_2xA4); - comboboxChanged(PS_2xA4); - - QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Close); - QPushButton *executeButton = new QPushButton; - buttonBox->addButton(executeButton, QDialogButtonBox::ActionRole); - - // set an user button to execute the task - buttonBox->button(QDialogButtonBox::Close)->setText(i18n("Done")); - executeButton->setText(i18n("Execute")); - executeButton->setIcon(QIcon::fromTheme("system-run")); - if (!pstops && !psselect) - executeButton->setEnabled(false); - - setFocusProxy(m_PostscriptDialog.m_edInfile); - m_PostscriptDialog.m_edInfile->setFocus(); - - mainLayout->addWidget(buttonBox); - executeButton->setDefault(true); - mainLayout->addWidget(buttonBox); - connect(buttonBox, &QDialogButtonBox::accepted, - this, &QDialog::accept); - connect(buttonBox, &QDialogButtonBox::rejected, - this, &QDialog::reject); - connect(executeButton, &QPushButton::clicked, - this, &PostscriptDialog::slotExecuteClicked); - connect(m_PostscriptDialog.m_cbTask, static_cast(&KComboBox::activated), - this, &PostscriptDialog::comboboxChanged); - connect(this, &PostscriptDialog::output, m_output, - &KileWidget::OutputView::receive); + QDialog(parent), + m_startdir(startdir), + m_errorHandler(errorHandler), + m_output(output), + m_proc(Q_NULLPTR) +{ + setWindowTitle(i18n("Rearrange Postscript File")); + setModal(true); + + QWidget *mainWidget = new QWidget(this); + QVBoxLayout *mainLayout = new QVBoxLayout; + setLayout(mainLayout); + mainLayout->addWidget(mainWidget); + + + // determine if a psfile already exists + QString psfilename,psoutfilename; + if(!texfilename.isEmpty()) { + // working with a postscript document, so we try to determine the LaTeX source file + QStringList extlist = latexextensions.split(' '); + for (QStringList::Iterator it = extlist.begin(); it != extlist.end(); ++it) { + if (texfilename.indexOf((*it), -(*it).length()) >= 0) { + QString basename = psfilename = texfilename.left(texfilename.length() - (*it).length()); + psfilename = basename + ".ps"; + psoutfilename = basename + "-out.ps"; + if (!QFileInfo(psfilename).exists()) + psfilename.clear(); + break; + } + } + } + + // prepare dialog + QWidget *page = new QWidget(this); + mainLayout->addWidget(page); + m_PostscriptDialog.setupUi(page); + + // line 0: QLabel + bool pstops = !QStandardPaths::findExecutable("pstops").isEmpty(); + bool psselect = !QStandardPaths::findExecutable("psselect").isEmpty(); + + if (!pstops || !psselect) { + QString msg; + if (!pstops) { + msg = "'pstops'"; + if (!psselect) + msg += " and "; + } + if (!psselect) { + msg += "'psselect'"; + } + m_PostscriptDialog.m_lbInfo->setText(m_PostscriptDialog.m_lbInfo->text() + "\n(Error: " + msg + " not found.)"); + } + + m_PostscriptDialog.m_edInfile->lineEdit()->setText(psfilename); + m_PostscriptDialog.m_edOutfile->lineEdit()->setText(psoutfilename); + + // according to QT 4.4 docu the index of QComboBox might change if adding or removing items + // but because we populate the QComboBox before we start the dialog, we can use the index here + if (pstops) { + m_PostscriptDialog.m_cbTask->addItem(i18n("1 DIN A5 Page + Empty Page --> DIN A4")); // 0 PS_A5_EMPTY + m_PostscriptDialog.m_cbTask->addItem(i18n("1 DIN A5 Page + Duplicate --> DIN A4")); // 1 PS_A5_DUPLICATE + m_PostscriptDialog.m_cbTask->addItem(i18n("2 DIN A5 Pages --> DIN A4")); // 2 PS_2xA5 + m_PostscriptDialog.m_cbTask->addItem(i18n("2 DIN A5L Pages --> DIN A4")); // 3 PS_2xA5L + m_PostscriptDialog.m_cbTask->addItem(i18n("4 DIN A5 Pages --> DIN A4")); // 4 PS_4xA5 + m_PostscriptDialog.m_cbTask->addItem(i18n("1 DIN A4 Page + Empty Page --> DIN A4")); // 5 m_PostscriptDialog.PS_A4_EMPTY + m_PostscriptDialog.m_cbTask->addItem(i18n("1 DIN A4 Page + Duplicate --> DIN A4")); // 6 PS_A4_DUPLICATE + m_PostscriptDialog.m_cbTask->addItem(i18n("2 DIN A4 Pages --> DIN A4")); // 7 PS_2xA4 + m_PostscriptDialog.m_cbTask->addItem(i18n("2 DIN A4L Pages --> DIN A4")); // 8 PS_2xA4L + } + if (psselect) { + m_PostscriptDialog.m_cbTask->addItem(i18n("Select Even Pages")); // 9 PS_EVEN + m_PostscriptDialog.m_cbTask->addItem(i18n("Select Odd Pages")); // 10 PS_ODD + m_PostscriptDialog.m_cbTask->addItem(i18n("Select Even Pages (reverse order)")); // 11 m_PostscriptDialog.PS_EVEN_REV + m_PostscriptDialog.m_cbTask->addItem(i18n("Select Odd Pages (reverse order)")); // 12 PS_ODD_REV + m_PostscriptDialog.m_cbTask->addItem(i18n("Reverse All Pages")); // 13 PS_REVERSE + m_PostscriptDialog.m_cbTask->addItem(i18n("Copy All Pages (sorted)")); // 14 PS_COPY_SORTED + } + if (pstops) { + m_PostscriptDialog.m_cbTask->addItem(i18n("Copy All Pages (unsorted)")); // 15 PS_COPY_UNSORTED + m_PostscriptDialog.m_cbTask->addItem(i18n("pstops: Choose Parameter")); // 16 PS_PSTOPS_FREE + } + if (psselect) { + m_PostscriptDialog.m_cbTask->addItem(i18n("psselect: Choose Parameter")); // 17 PS_PSSELECT_FREE + } + + m_PostscriptDialog.m_edInfile->setFilter("*.ps|PS Files\n*.ps.gz|Zipped PS Files"); + m_PostscriptDialog.m_edOutfile->setFilter("*.ps|PS Files\n*.ps.gz|Zipped PS Files"); + m_PostscriptDialog.m_edOutfile->setMode(KFile::File | KFile::LocalOnly); + + // choose one common task + m_PostscriptDialog.m_cbTask->setCurrentIndex(PS_2xA4); + comboboxChanged(PS_2xA4); + + QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Close); + QPushButton *executeButton = new QPushButton; + buttonBox->addButton(executeButton, QDialogButtonBox::ActionRole); + + // set an user button to execute the task + buttonBox->button(QDialogButtonBox::Close)->setText(i18n("Done")); + executeButton->setText(i18n("Execute")); + executeButton->setIcon(QIcon::fromTheme("system-run")); + if (!pstops && !psselect) + executeButton->setEnabled(false); + + setFocusProxy(m_PostscriptDialog.m_edInfile); + m_PostscriptDialog.m_edInfile->setFocus(); + + mainLayout->addWidget(buttonBox); + executeButton->setDefault(true); + mainLayout->addWidget(buttonBox); + connect(buttonBox, &QDialogButtonBox::accepted, + this, &QDialog::accept); + connect(buttonBox, &QDialogButtonBox::rejected, + this, &QDialog::reject); + connect(executeButton, &QPushButton::clicked, + this, &PostscriptDialog::slotExecuteClicked); + connect(m_PostscriptDialog.m_cbTask, static_cast(&KComboBox::activated), + this, &PostscriptDialog::comboboxChanged); + connect(this, &PostscriptDialog::output, m_output, + &KileWidget::OutputView::receive); } PostscriptDialog::~PostscriptDialog() { - if (m_proc) { - delete m_proc; - } + if (m_proc) { + delete m_proc; + } } void PostscriptDialog::slotExecuteClicked() { - if (checkParameter()) { - execute(); - } + if (checkParameter()) { + execute(); + } } void PostscriptDialog::execute() { - m_tempfile = buildTempfile(); - - if(m_tempfile.isEmpty()) { - m_errorHandler->printMessage(KileTool::Error, i18n("Could not create a temporary file.")); - return; - } - else { - m_errorHandler->clearMessages(); - QFileInfo from(m_PostscriptDialog.m_edInfile->lineEdit()->text()); - QFileInfo to(m_PostscriptDialog.m_edOutfile->lineEdit()->text()); - - // output for log window - QString msg = i18n("rearrange ps file: ") + from.fileName(); - if (!to.fileName().isEmpty()) - msg += " ---> " + to.fileName(); - m_errorHandler->printMessage(KileTool::Info, msg, m_program); - - // some output logs - m_output->clear(); - QString s = QString("*****\n") - + i18n("***** tool: ") + m_program + ' ' + m_param + '\n' - + i18n("***** input file: ") + from.fileName()+ '\n' - + i18n("***** output file: ") + to.fileName()+ '\n' - + i18n("***** viewer: ") + ((m_PostscriptDialog.m_cbView->isChecked()) ? i18n("yes") : i18n("no")) + '\n' - + "*****\n"; - emit( output(s) ); - - // delete old KProcess - if (m_proc) - delete m_proc; - - m_proc = new KProcess(); - m_proc->setShellCommand("sh " + m_tempfile); - m_proc->setOutputChannelMode(KProcess::MergedChannels); - m_proc->setReadChannel(QProcess::StandardOutput); - - connect(m_proc, SIGNAL(readyReadStandardOutput()), - this, SLOT(slotProcessOutput())); - connect(m_proc, SIGNAL(readyReadStandardError()), - this, SLOT(slotProcessOutput())); - connect(m_proc, SIGNAL(finished(int, QProcess::ExitStatus)), - this, SLOT(slotProcessExited(int, QProcess::ExitStatus))); - - KILE_DEBUG_MAIN << "=== PostscriptDialog::runPsutils() ===================="; - KILE_DEBUG_MAIN << " execute '" << m_tempfile << "'"; - m_proc->start(); - } + m_tempfile = buildTempfile(); + + if(m_tempfile.isEmpty()) { + m_errorHandler->printMessage(KileTool::Error, i18n("Could not create a temporary file.")); + return; + } + else { + m_errorHandler->clearMessages(); + QFileInfo from(m_PostscriptDialog.m_edInfile->lineEdit()->text()); + QFileInfo to(m_PostscriptDialog.m_edOutfile->lineEdit()->text()); + + // output for log window + QString msg = i18n("rearrange ps file: ") + from.fileName(); + if (!to.fileName().isEmpty()) + msg += " ---> " + to.fileName(); + m_errorHandler->printMessage(KileTool::Info, msg, m_program); + + // some output logs + m_output->clear(); + QString s = QString("*****\n") + + i18n("***** tool: ") + m_program + ' ' + m_param + '\n' + + i18n("***** input file: ") + from.fileName()+ '\n' + + i18n("***** output file: ") + to.fileName()+ '\n' + + i18n("***** viewer: ") + ((m_PostscriptDialog.m_cbView->isChecked()) ? i18n("yes") : i18n("no")) + '\n' + + "*****\n"; + emit( output(s) ); + + // delete old KProcess + if (m_proc) + delete m_proc; + + m_proc = new KProcess(); + m_proc->setShellCommand("sh " + m_tempfile); + m_proc->setOutputChannelMode(KProcess::MergedChannels); + m_proc->setReadChannel(QProcess::StandardOutput); + + connect(m_proc, SIGNAL(readyReadStandardOutput()), + this, SLOT(slotProcessOutput())); + connect(m_proc, SIGNAL(readyReadStandardError()), + this, SLOT(slotProcessOutput())); + connect(m_proc, SIGNAL(finished(int, QProcess::ExitStatus)), + this, SLOT(slotProcessExited(int, QProcess::ExitStatus))); + + KILE_DEBUG_MAIN << "=== PostscriptDialog::runPsutils() ===================="; + KILE_DEBUG_MAIN << " execute '" << m_tempfile << "'"; + m_proc->start(); + } } void PostscriptDialog::slotProcessOutput() { - emit(output(m_proc->readAllStandardOutput())); - emit(output(m_proc->readAllStandardError())); + emit(output(m_proc->readAllStandardOutput())); + emit(output(m_proc->readAllStandardError())); } void PostscriptDialog::slotProcessExited(int /* exitCode */, QProcess::ExitStatus exitStatus) { - if (exitStatus != QProcess::NormalExit) { - showError(i18n("An error occurred while rearranging the file.")); - } + if (exitStatus != QProcess::NormalExit) { + showError(i18n("An error occurred while rearranging the file.")); + } - QFile::remove(m_tempfile); + QFile::remove(m_tempfile); } QString PostscriptDialog::buildTempfile() { - // build command - m_program = "pstops"; // default - m_param = ""; - - switch (m_PostscriptDialog.m_cbTask->currentIndex()) { - case PS_A5_EMPTY: m_param = "1:0L(29.7cm,0cm)"; - break; - case PS_A5_DUPLICATE: m_param = "1:0L(29.7cm,0cm)+0L(29.7cm,14.85cm)"; - break; - case PS_2xA5: m_param = "2:0L(29.7cm,0cm)+1L(29.7cm,14.85cm)"; - break; - case PS_2xA5L: break; - case PS_4xA5: m_param = "4:0@0.7(0cm,8.7cm)" - "+1@0.7(10.5cm,8.7cm)" - "+2@0.7(0cm,-6.15cm)" - "+3@0.7(10.5cm,-6.15cm)"; - break; - case PS_A4_EMPTY: m_param = "1:0L@0.7(21cm,0cm)"; - break; - case PS_A4_DUPLICATE: m_param = "1:0L@0.7(21cm,0cm)+0L@0.7(21cm,14.85cm)"; - break; - case PS_2xA4: m_param = "2:0L@0.7(21cm,0cm)+1L@0.7(21cm,14.85cm)"; - break; - case PS_2xA4L: m_param = "2:0R@0.7(0cm,29.7cm)+1R@0.7(0cm,14.85cm)"; - break; - case PS_EVEN: m_program = "psselect"; - m_param = "-e"; - break; - case PS_ODD: m_program = "psselect"; - m_param = "-o"; - break; - case PS_EVEN_REV: m_program = "psselect"; - m_param = "-e -r"; - break; - case PS_ODD_REV: m_program = "psselect"; - m_param = "-o -r"; - break; - case PS_REVERSE: m_program = "psselect"; - m_param = "-r"; - break; - case PS_COPY_SORTED: m_program = "psselect"; - m_param = "-p" + duplicateParameter("1-"); - break; - case PS_COPY_UNSORTED: m_param = "1:" + duplicateParameter("0"); - break; - case PS_PSTOPS_FREE: m_param = m_PostscriptDialog.m_edParameter->text(); - break; - case PS_PSSELECT_FREE: m_program = "psselect"; - m_param = m_PostscriptDialog.m_edParameter->text(); - break; - } - - // create a temporary file - QTemporaryFile temp; + // build command + m_program = "pstops"; // default + m_param = ""; + + switch (m_PostscriptDialog.m_cbTask->currentIndex()) { + case PS_A5_EMPTY: + m_param = "1:0L(29.7cm,0cm)"; + break; + case PS_A5_DUPLICATE: + m_param = "1:0L(29.7cm,0cm)+0L(29.7cm,14.85cm)"; + break; + case PS_2xA5: + m_param = "2:0L(29.7cm,0cm)+1L(29.7cm,14.85cm)"; + break; + case PS_2xA5L: + break; + case PS_4xA5: + m_param = "4:0@0.7(0cm,8.7cm)" + "+1@0.7(10.5cm,8.7cm)" + "+2@0.7(0cm,-6.15cm)" + "+3@0.7(10.5cm,-6.15cm)"; + break; + case PS_A4_EMPTY: + m_param = "1:0L@0.7(21cm,0cm)"; + break; + case PS_A4_DUPLICATE: + m_param = "1:0L@0.7(21cm,0cm)+0L@0.7(21cm,14.85cm)"; + break; + case PS_2xA4: + m_param = "2:0L@0.7(21cm,0cm)+1L@0.7(21cm,14.85cm)"; + break; + case PS_2xA4L: + m_param = "2:0R@0.7(0cm,29.7cm)+1R@0.7(0cm,14.85cm)"; + break; + case PS_EVEN: + m_program = "psselect"; + m_param = "-e"; + break; + case PS_ODD: + m_program = "psselect"; + m_param = "-o"; + break; + case PS_EVEN_REV: + m_program = "psselect"; + m_param = "-e -r"; + break; + case PS_ODD_REV: + m_program = "psselect"; + m_param = "-o -r"; + break; + case PS_REVERSE: + m_program = "psselect"; + m_param = "-r"; + break; + case PS_COPY_SORTED: + m_program = "psselect"; + m_param = "-p" + duplicateParameter("1-"); + break; + case PS_COPY_UNSORTED: + m_param = "1:" + duplicateParameter("0"); + break; + case PS_PSTOPS_FREE: + m_param = m_PostscriptDialog.m_edParameter->text(); + break; + case PS_PSSELECT_FREE: + m_program = "psselect"; + m_param = m_PostscriptDialog.m_edParameter->text(); + break; + } + + // create a temporary file + QTemporaryFile temp; //code was temp.setSuffix(".sh"); -//Add to constructor and adapt if necessay: QDir::tempPath() + QLatin1String("/myapp_XXXXXX") + QLatin1String(".sh") - temp.setAutoRemove(false); - if(!temp.open()) { - KILE_DEBUG_MAIN << "Could not create tempfile in QString PostscriptDialog::buildTempfile()" ; - return QString(); - } - QString tempname = temp.fileName(); - - QTextStream stream(&temp); - stream << "#! /bin/sh" << endl; - - // accept only ".ps" or ".ps.gz" as an input file - QFileInfo fi(m_PostscriptDialog.m_edInfile->lineEdit()->text()); - bool zipped_psfile = (fi.completeSuffix() == "ps.gz") ? true : false; - - // there are four possible cases - // outfile view - // 1) + + pstops/psselect + okular - // 2) + - pstops/psselect - // 3) - + pstops/psselect | okular (nur Shell) - // 4) - - error (already detected by checkParameter()) - - // some files, which are used - QString command = m_program + " \"" + m_param + "\""; - QString inputfile = "\"" + m_PostscriptDialog.m_edInfile->lineEdit()->text() + "\""; - QString outputfile = "\"" + m_PostscriptDialog.m_edOutfile->lineEdit()->text() + "\""; - bool viewer = m_PostscriptDialog.m_cbView->isChecked(); - - bool equalfiles = false; - if (inputfile == outputfile) { - outputfile = tempname + ".tmp"; - equalfiles = true; - } - - if (!zipped_psfile) { // unzipped ps files - if (m_PostscriptDialog.m_edOutfile->lineEdit()->text().isEmpty()) { // pstops/psselect | okular - stream << command << " " << inputfile << " | okular -" << endl; - viewer = false; - } else { // pstops/psselect - stream << command << " " << inputfile << " " << outputfile << endl; - } - } else { // zipped ps files - if (m_PostscriptDialog.m_edOutfile->lineEdit()->text().isEmpty()) { // pstops/psselect | okular - stream << "gunzip -c " << inputfile - << " | " << command - << " | okular -" - << endl; - viewer = false; - } else { - stream << "gunzip -c " << inputfile // pstops/psselect - << " | " << command - << " > " << outputfile - << endl; - } - } - - // check, if we should stop - if ( equalfiles || viewer ) { - stream << "if [ $? != 0 ]; then" << endl; - stream << " exit 1" << endl; - stream << "fi" << endl; - } - - // replace the original file - if ( equalfiles ) { - stream << "rm " << inputfile << endl; - stream << "mv " << outputfile << " " << inputfile << endl; - } - - // viewer - if ( viewer ) { // viewer: okular - stream << "okular" << " " - << ((equalfiles) ? inputfile : outputfile) << endl; - } - - // everything is prepared to do the job - temp.close(); - - return(tempname); +//Add to constructor and adapt if necessay: QDir::tempPath() + QLatin1String("/myapp_XXXXXX") + QLatin1String(".sh") + temp.setAutoRemove(false); + if(!temp.open()) { + KILE_DEBUG_MAIN << "Could not create tempfile in QString PostscriptDialog::buildTempfile()" ; + return QString(); + } + QString tempname = temp.fileName(); + + QTextStream stream(&temp); + stream << "#! /bin/sh" << endl; + + // accept only ".ps" or ".ps.gz" as an input file + QFileInfo fi(m_PostscriptDialog.m_edInfile->lineEdit()->text()); + bool zipped_psfile = (fi.completeSuffix() == "ps.gz") ? true : false; + + // there are four possible cases + // outfile view + // 1) + + pstops/psselect + okular + // 2) + - pstops/psselect + // 3) - + pstops/psselect | okular (nur Shell) + // 4) - - error (already detected by checkParameter()) + + // some files, which are used + QString command = m_program + " \"" + m_param + "\""; + QString inputfile = "\"" + m_PostscriptDialog.m_edInfile->lineEdit()->text() + "\""; + QString outputfile = "\"" + m_PostscriptDialog.m_edOutfile->lineEdit()->text() + "\""; + bool viewer = m_PostscriptDialog.m_cbView->isChecked(); + + bool equalfiles = false; + if (inputfile == outputfile) { + outputfile = tempname + ".tmp"; + equalfiles = true; + } + + if (!zipped_psfile) { // unzipped ps files + if (m_PostscriptDialog.m_edOutfile->lineEdit()->text().isEmpty()) { // pstops/psselect | okular + stream << command << " " << inputfile << " | okular -" << endl; + viewer = false; + } else { // pstops/psselect + stream << command << " " << inputfile << " " << outputfile << endl; + } + } else { // zipped ps files + if (m_PostscriptDialog.m_edOutfile->lineEdit()->text().isEmpty()) { // pstops/psselect | okular + stream << "gunzip -c " << inputfile + << " | " << command + << " | okular -" + << endl; + viewer = false; + } else { + stream << "gunzip -c " << inputfile // pstops/psselect + << " | " << command + << " > " << outputfile + << endl; + } + } + + // check, if we should stop + if ( equalfiles || viewer ) { + stream << "if [ $? != 0 ]; then" << endl; + stream << " exit 1" << endl; + stream << "fi" << endl; + } + + // replace the original file + if ( equalfiles ) { + stream << "rm " << inputfile << endl; + stream << "mv " << outputfile << " " << inputfile << endl; + } + + // viewer + if ( viewer ) { // viewer: okular + stream << "okular" << " " + << ((equalfiles) ? inputfile : outputfile) << endl; + } + + // everything is prepared to do the job + temp.close(); + + return(tempname); } QString PostscriptDialog::duplicateParameter(const QString ¶m) { - QString s; - for (int i = 0; i < m_PostscriptDialog.m_spCopies->value(); ++i) { - if (i == 0) - s += param; - else - s += ',' + param; - } - - return s; + QString s; + for (int i = 0; i < m_PostscriptDialog.m_spCopies->value(); ++i) { + if (i == 0) + s += param; + else + s += ',' + param; + } + + return s; } bool PostscriptDialog::checkParameter() { - QString infile = m_PostscriptDialog.m_edInfile->lineEdit()->text(); - if (infile.isEmpty()) { - showError(i18n("No input file is given.")); - return false; - } - - QFileInfo fi(infile); - QString suffix = fi.completeSuffix(); - if (suffix != "ps" && suffix != "ps.gz") { - showError(i18n("Unknown file format: only '.ps' and '.ps.gz' are accepted for input files.")); - return false; - } - - if (!fi.exists()) { - showError(i18n("This input file does not exist.")); - return false; - } - - // check parameter - int index = m_PostscriptDialog.m_cbTask->currentIndex(); - if (m_PostscriptDialog.m_edParameter->text().isEmpty()) { - if (index == PS_PSSELECT_FREE) { - showError( i18n("psselect needs some parameters in this mode.") ); - return false; - } else if (index == PS_PSTOPS_FREE) { - showError( i18n("pstops needs some parameters in this mode.") ); - return false; - } - } - - QString outfile = m_PostscriptDialog.m_edOutfile->lineEdit()->text(); - if (outfile.isEmpty() && !m_PostscriptDialog.m_cbView->isChecked()) { - showError(i18n("You need to define an output file or select the viewer.")); - return false; - } - - if (! outfile.isEmpty()) { - QFileInfo fo(outfile); - if (fo.completeSuffix() != "ps") { - showError(i18n("Unknown file format: only '.ps' is accepted as output file.")); - return false; - } - - if (infile != outfile && fo.exists()) { - QString s = i18n("A file named \"%1\" already exists. Are you sure you want to overwrite it?", fo.fileName()); - if (KMessageBox::questionYesNo(this, - "
" + s + "
", - "Postscript tools") == KMessageBox::No) { - return false; - } - } - } - - return true; + QString infile = m_PostscriptDialog.m_edInfile->lineEdit()->text(); + if (infile.isEmpty()) { + showError(i18n("No input file is given.")); + return false; + } + + QFileInfo fi(infile); + QString suffix = fi.completeSuffix(); + if (suffix != "ps" && suffix != "ps.gz") { + showError(i18n("Unknown file format: only '.ps' and '.ps.gz' are accepted for input files.")); + return false; + } + + if (!fi.exists()) { + showError(i18n("This input file does not exist.")); + return false; + } + + // check parameter + int index = m_PostscriptDialog.m_cbTask->currentIndex(); + if (m_PostscriptDialog.m_edParameter->text().isEmpty()) { + if (index == PS_PSSELECT_FREE) { + showError( i18n("psselect needs some parameters in this mode.") ); + return false; + } else if (index == PS_PSTOPS_FREE) { + showError( i18n("pstops needs some parameters in this mode.") ); + return false; + } + } + + QString outfile = m_PostscriptDialog.m_edOutfile->lineEdit()->text(); + if (outfile.isEmpty() && !m_PostscriptDialog.m_cbView->isChecked()) { + showError(i18n("You need to define an output file or select the viewer.")); + return false; + } + + if (! outfile.isEmpty()) { + QFileInfo fo(outfile); + if (fo.completeSuffix() != "ps") { + showError(i18n("Unknown file format: only '.ps' is accepted as output file.")); + return false; + } + + if (infile != outfile && fo.exists()) { + QString s = i18n("A file named \"%1\" already exists. Are you sure you want to overwrite it?", fo.fileName()); + if (KMessageBox::questionYesNo(this, + "
" + s + "
", + "Postscript tools") == KMessageBox::No) { + return false; + } + } + } + + return true; } void PostscriptDialog::comboboxChanged(int index) { - KILE_DEBUG_MAIN << index << endl; - if (index == PS_COPY_SORTED || index == PS_COPY_UNSORTED) { - m_PostscriptDialog.m_lbParameter->setEnabled(true); - m_PostscriptDialog.m_lbParameter->setText(i18n("Copies:")); - m_PostscriptDialog.m_edParameter->hide(); - m_PostscriptDialog.m_spCopies->show(); - m_PostscriptDialog.m_spCopies->setEnabled(true); - } else { - if (index == PS_PSSELECT_FREE || index == PS_PSTOPS_FREE) { - m_PostscriptDialog.m_lbParameter->setEnabled(true); - m_PostscriptDialog.m_lbParameter->setText(i18n("Parameter:")); - m_PostscriptDialog.m_spCopies->hide(); - m_PostscriptDialog.m_edParameter->show(); - m_PostscriptDialog.m_edParameter->setEnabled(true); - } else { - m_PostscriptDialog.m_lbParameter->setEnabled(false); - m_PostscriptDialog.m_edParameter->setEnabled(false); - m_PostscriptDialog.m_spCopies->setEnabled(false); - } - } + KILE_DEBUG_MAIN << index << endl; + if (index == PS_COPY_SORTED || index == PS_COPY_UNSORTED) { + m_PostscriptDialog.m_lbParameter->setEnabled(true); + m_PostscriptDialog.m_lbParameter->setText(i18n("Copies:")); + m_PostscriptDialog.m_edParameter->hide(); + m_PostscriptDialog.m_spCopies->show(); + m_PostscriptDialog.m_spCopies->setEnabled(true); + } else { + if (index == PS_PSSELECT_FREE || index == PS_PSTOPS_FREE) { + m_PostscriptDialog.m_lbParameter->setEnabled(true); + m_PostscriptDialog.m_lbParameter->setText(i18n("Parameter:")); + m_PostscriptDialog.m_spCopies->hide(); + m_PostscriptDialog.m_edParameter->show(); + m_PostscriptDialog.m_edParameter->setEnabled(true); + } else { + m_PostscriptDialog.m_lbParameter->setEnabled(false); + m_PostscriptDialog.m_edParameter->setEnabled(false); + m_PostscriptDialog.m_spCopies->setEnabled(false); + } + } } void PostscriptDialog::showError(const QString &text) { - KMessageBox::error(this, i18n("
") + text + i18n("
"), i18n("Postscript Tools")); + KMessageBox::error(this, i18n("
") + text + i18n("
"), i18n("Postscript Tools")); } } diff --git a/src/dialogs/postscriptdialog.h b/src/dialogs/postscriptdialog.h index 024aaea2..86f9dc22 100644 --- a/src/dialogs/postscriptdialog.h +++ b/src/dialogs/postscriptdialog.h @@ -1,93 +1,93 @@ /********************************************************************************** Copyright (C) 2005-2007 by Holger Danielsson (holger.danielsson@versanet.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. * * * ***************************************************************************/ #ifndef POSTSCRIPTDIALOG_H #define POSTSCRIPTDIALOG_H #include #include #include "widgets/outputview.h" #include "ui_postscriptdialog_base.h" #define PS_A5_EMPTY 0 #define PS_A5_DUPLICATE 1 #define PS_2xA5 2 #define PS_2xA5L 3 #define PS_4xA5 4 #define PS_A4_EMPTY 5 #define PS_A4_DUPLICATE 6 #define PS_2xA4 7 #define PS_2xA4L 8 #define PS_EVEN 9 #define PS_ODD 10 #define PS_EVEN_REV 11 #define PS_ODD_REV 12 #define PS_REVERSE 13 #define PS_COPY_SORTED 14 #define PS_COPY_UNSORTED 15 #define PS_PSTOPS_FREE 16 #define PS_PSSELECT_FREE 17 class KProcess; class KileErrorHandler; namespace KileDialog { class PostscriptDialog : public QDialog { - Q_OBJECT - - public: - PostscriptDialog(QWidget *parent, - const QString &texfilename, const QString &startdir, - const QString &latexextensions, - KileErrorHandler *errorHandler, KileWidget::OutputView *output); - ~PostscriptDialog(); - - Q_SIGNALS: - void output(const QString &); - - private Q_SLOTS: - void comboboxChanged(int index); - void slotExecuteClicked(); - void slotProcessOutput(); - void slotProcessExited(int exitCode, QProcess::ExitStatus exitStatus); - - private: - bool checkParameter(); - QString buildTempfile(); - QString duplicateParameter(const QString ¶m); - void showError(const QString &text); - void execute(); - - QString m_startdir; - KileErrorHandler *m_errorHandler; - KileWidget::OutputView *m_output; - - QString m_tempfile; - QString m_program; - QString m_param; - - KProcess* m_proc; - - Ui::PostscriptDialog m_PostscriptDialog; + Q_OBJECT + +public: + PostscriptDialog(QWidget *parent, + const QString &texfilename, const QString &startdir, + const QString &latexextensions, + KileErrorHandler *errorHandler, KileWidget::OutputView *output); + ~PostscriptDialog(); + +Q_SIGNALS: + void output(const QString &); + +private Q_SLOTS: + void comboboxChanged(int index); + void slotExecuteClicked(); + void slotProcessOutput(); + void slotProcessExited(int exitCode, QProcess::ExitStatus exitStatus); + +private: + bool checkParameter(); + QString buildTempfile(); + QString duplicateParameter(const QString ¶m); + void showError(const QString &text); + void execute(); + + QString m_startdir; + KileErrorHandler *m_errorHandler; + KileWidget::OutputView *m_output; + + QString m_tempfile; + QString m_program; + QString m_param; + + KProcess* m_proc; + + Ui::PostscriptDialog m_PostscriptDialog; }; } #endif diff --git a/src/dialogs/projectdialogs.cpp b/src/dialogs/projectdialogs.cpp index 157e877a..8eafd539 100644 --- a/src/dialogs/projectdialogs.cpp +++ b/src/dialogs/projectdialogs.cpp @@ -1,609 +1,609 @@ /******************************************************************************************* Copyright (C) 2003 by Jeroen Wijnhout (Jeroen.Wijnhout@kdemail.net) (C) 2007 by Holger Danielsson (holger.danielsson@versanet.de) (C) 2013-2016 by Michel Ludwig (michel.ludwig@kdemail.net) (C) 2015 by Andreas Cord-Landwehr (cordlandwehr@kde.org) ********************************************************************************************/ /*************************************************************************** * * * 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. * * * ***************************************************************************/ // 2007-02-15 (dani) // - cosmetic changes // - use of groupboxes to prepare further extensions // 2007-03-12 (dani) // - use KileDocument::Extensions // - allowed extensions are always defined as list, f.e.: .tex .ltx .latex #include "dialogs/projectdialogs.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "kiledebug.h" #include "kileproject.h" #include "kiletoolmanager.h" #include "documentinfo.h" #include "kileconfig.h" #include "kileextensions.h" #include "templates.h" KileProjectDialogBase::KileProjectDialogBase(const QString &caption, KileDocument::Extensions *extensions, QWidget *parent, const char *name) - : QDialog(parent) - , m_extmanager(extensions) - , m_project(Q_NULLPTR) - , m_projectGroup(new QGroupBox(i18n("Project"), this)) - , m_extensionGroup(new QGroupBox(i18n("Extensions"), this)) + : QDialog(parent) + , m_extmanager(extensions) + , m_project(Q_NULLPTR) + , m_projectGroup(new QGroupBox(i18n("Project"), this)) + , m_extensionGroup(new QGroupBox(i18n("Extensions"), this)) { - setWindowTitle(caption); - setModal(true); - setObjectName(name); - - const QString whatsthisName = i18n("Insert a short descriptive name of your project here."); - const QString whatsthisExt = i18n("Insert a list (separated by spaces) of file extensions which should be treated also as files of the corresponding type in this project."); - - m_title = new QLineEdit(m_projectGroup); - m_title->setWhatsThis(whatsthisName); - QLabel *projectTitleLabel = new QLabel(i18n("Project &title:"), m_projectGroup); - projectTitleLabel->setBuddy(m_title); - projectTitleLabel->setWhatsThis(whatsthisName); - - // project settings groupbox - QFormLayout *projectGoupLayout= new QFormLayout(m_projectGroup); - projectGoupLayout->setAlignment(Qt::AlignTop); - m_projectGroup->setLayout(projectGoupLayout); - projectGoupLayout->addRow(projectTitleLabel, m_title); - - m_projectFolder = new KUrlRequester(m_projectGroup); - m_projectFolder->setMode(KFile::Directory | KFile::LocalOnly); - - QLabel *projectFolderLabel = new QLabel(i18n("Project &folder:"), m_projectGroup); - projectFolderLabel->setBuddy(m_projectFolder); - const QString whatsthisPath = i18n("Insert the path to your project here."); - m_projectFolder->setWhatsThis(whatsthisPath); - projectGoupLayout->addRow(projectFolderLabel, m_projectFolder); - - // combo box for default graphics extension - m_defaultGraphicsExtensionCombo = new QComboBox(this); - KileDocument::Extensions extManager; - QStringList imageExtensions = extManager.images().split(" "); - foreach (const QString &extension, imageExtensions) { - const QString extName = extension.mid(1); // all characters right of "." - m_defaultGraphicsExtensionCombo->addItem(extension, extName); - } - m_defaultGraphicsExtensionCombo->addItem(i18n("(use global settings)"),""); - const QString whatsThisTextDefaultGraphicsExtension = i18n("Default graphic extension to open when none specified by file name."); - m_defaultGraphicsExtensionCombo->setWhatsThis(whatsThisTextDefaultGraphicsExtension); - - // extension settings groupbox - m_userFileExtensions = new QLineEdit(this); - m_userFileExtensions->setWhatsThis(whatsthisExt); - QRegExp reg("[\\. a-zA-Z0-9]+"); - QRegExpValidator *extValidator = new QRegExpValidator(reg, m_extensionGroup); - m_userFileExtensions->setValidator(extValidator); - - m_defaultLatexFileExtensionsCombo = new KComboBox(false, this); - m_defaultLatexFileExtensionsCombo->addItem(i18n("Source Files")); - m_defaultLatexFileExtensionsCombo->addItem(i18n("Package Files")); - m_defaultLatexFileExtensionsCombo->addItem(i18n("Image Files")); - m_defaultLatexFileExtensionsCombo->addItem(i18n("Bibliography Files")); - m_defaultLatexFileExtensions = new QLabel(QString(), this); - m_defaultLatexFileExtensionsCombo->setWhatsThis(whatsthisExt); - - QFormLayout *extensionGroupLayout = new QFormLayout(m_extensionGroup); - m_extensionGroup->setLayout(extensionGroupLayout); - extensionGroupLayout->setAlignment(Qt::AlignTop); - extensionGroupLayout->addRow(new QLabel(i18n("Default Graphics Extension:"), this), m_defaultGraphicsExtensionCombo); - extensionGroupLayout->addRow(m_defaultLatexFileExtensionsCombo, m_userFileExtensions); - extensionGroupLayout->addRow(new QLabel(i18n("Predefined:"), this), m_defaultLatexFileExtensions); - - fillProjectDefaults(); - - QWidget::setTabOrder(m_title, m_projectFolder); - QWidget::setTabOrder(m_defaultGraphicsExtensionCombo, m_defaultLatexFileExtensionsCombo); - QWidget::setTabOrder(m_defaultLatexFileExtensionsCombo, m_defaultLatexFileExtensions); + setWindowTitle(caption); + setModal(true); + setObjectName(name); + + const QString whatsthisName = i18n("Insert a short descriptive name of your project here."); + const QString whatsthisExt = i18n("Insert a list (separated by spaces) of file extensions which should be treated also as files of the corresponding type in this project."); + + m_title = new QLineEdit(m_projectGroup); + m_title->setWhatsThis(whatsthisName); + QLabel *projectTitleLabel = new QLabel(i18n("Project &title:"), m_projectGroup); + projectTitleLabel->setBuddy(m_title); + projectTitleLabel->setWhatsThis(whatsthisName); + + // project settings groupbox + QFormLayout *projectGoupLayout= new QFormLayout(m_projectGroup); + projectGoupLayout->setAlignment(Qt::AlignTop); + m_projectGroup->setLayout(projectGoupLayout); + projectGoupLayout->addRow(projectTitleLabel, m_title); + + m_projectFolder = new KUrlRequester(m_projectGroup); + m_projectFolder->setMode(KFile::Directory | KFile::LocalOnly); + + QLabel *projectFolderLabel = new QLabel(i18n("Project &folder:"), m_projectGroup); + projectFolderLabel->setBuddy(m_projectFolder); + const QString whatsthisPath = i18n("Insert the path to your project here."); + m_projectFolder->setWhatsThis(whatsthisPath); + projectGoupLayout->addRow(projectFolderLabel, m_projectFolder); + + // combo box for default graphics extension + m_defaultGraphicsExtensionCombo = new QComboBox(this); + KileDocument::Extensions extManager; + QStringList imageExtensions = extManager.images().split(" "); + foreach (const QString &extension, imageExtensions) { + const QString extName = extension.mid(1); // all characters right of "." + m_defaultGraphicsExtensionCombo->addItem(extension, extName); + } + m_defaultGraphicsExtensionCombo->addItem(i18n("(use global settings)"),""); + const QString whatsThisTextDefaultGraphicsExtension = i18n("Default graphic extension to open when none specified by file name."); + m_defaultGraphicsExtensionCombo->setWhatsThis(whatsThisTextDefaultGraphicsExtension); + + // extension settings groupbox + m_userFileExtensions = new QLineEdit(this); + m_userFileExtensions->setWhatsThis(whatsthisExt); + QRegExp reg("[\\. a-zA-Z0-9]+"); + QRegExpValidator *extValidator = new QRegExpValidator(reg, m_extensionGroup); + m_userFileExtensions->setValidator(extValidator); + + m_defaultLatexFileExtensionsCombo = new KComboBox(false, this); + m_defaultLatexFileExtensionsCombo->addItem(i18n("Source Files")); + m_defaultLatexFileExtensionsCombo->addItem(i18n("Package Files")); + m_defaultLatexFileExtensionsCombo->addItem(i18n("Image Files")); + m_defaultLatexFileExtensionsCombo->addItem(i18n("Bibliography Files")); + m_defaultLatexFileExtensions = new QLabel(QString(), this); + m_defaultLatexFileExtensionsCombo->setWhatsThis(whatsthisExt); + + QFormLayout *extensionGroupLayout = new QFormLayout(m_extensionGroup); + m_extensionGroup->setLayout(extensionGroupLayout); + extensionGroupLayout->setAlignment(Qt::AlignTop); + extensionGroupLayout->addRow(new QLabel(i18n("Default Graphics Extension:"), this), m_defaultGraphicsExtensionCombo); + extensionGroupLayout->addRow(m_defaultLatexFileExtensionsCombo, m_userFileExtensions); + extensionGroupLayout->addRow(new QLabel(i18n("Predefined:"), this), m_defaultLatexFileExtensions); + + fillProjectDefaults(); + + QWidget::setTabOrder(m_title, m_projectFolder); + QWidget::setTabOrder(m_defaultGraphicsExtensionCombo, m_defaultLatexFileExtensionsCombo); + QWidget::setTabOrder(m_defaultLatexFileExtensionsCombo, m_defaultLatexFileExtensions); } KileProjectDialogBase::~KileProjectDialogBase() { } void KileProjectDialogBase::onExtensionsIndexChanged(int index) { - m_userFileExtensions->setText(m_val_extensions[index]); - m_defaultLatexFileExtensions->setText(m_val_standardExtensions[index]); + m_userFileExtensions->setText(m_val_extensions[index]); + m_defaultLatexFileExtensions->setText(m_val_standardExtensions[index]); } void KileProjectDialogBase::onExtensionsTextEdited(const QString &text) { - m_val_extensions[m_defaultLatexFileExtensionsCombo->currentIndex()] = text; + m_val_extensions[m_defaultLatexFileExtensionsCombo->currentIndex()] = text; } bool KileProjectDialogBase::acceptUserExtensions() { - QRegExp reg("\\.\\w+"); - - for (int i = KileProjectItem::Source; i < KileProjectItem::Other; ++i) { - m_val_extensions[i-1] = m_val_extensions[i-1].trimmed(); - if (! m_val_extensions[i-1].isEmpty()) { - // some tiny extension checks - QStringList::ConstIterator it; - QStringList list = m_val_extensions[i-1].split(' '); - for (it = list.constBegin(); it != list.constEnd(); ++it) { - if (! reg.exactMatch(*it)) { - KMessageBox::error(this, i18n("Error in extension") + " '" + (*it) + "':\n" + i18n("All user-defined extensions should look like '.xyz'"), i18n("Invalid extension")); - return false; - } - } - } - } - - return true; + QRegExp reg("\\.\\w+"); + + for (int i = KileProjectItem::Source; i < KileProjectItem::Other; ++i) { + m_val_extensions[i-1] = m_val_extensions[i-1].trimmed(); + if (! m_val_extensions[i-1].isEmpty()) { + // some tiny extension checks + QStringList::ConstIterator it; + QStringList list = m_val_extensions[i-1].split(' '); + for (it = list.constBegin(); it != list.constEnd(); ++it) { + if (! reg.exactMatch(*it)) { + KMessageBox::error(this, i18n("Error in extension") + " '" + (*it) + "':\n" + i18n("All user-defined extensions should look like '.xyz'"), i18n("Invalid extension")); + return false; + } + } + } + } + + return true; } void KileProjectDialogBase::setExtensions(KileProjectItem::Type type, const QString & ext) { - if (m_defaultLatexFileExtensionsCombo->currentIndex() == type - 1) { - m_userFileExtensions->setText(ext); - } - else { - m_val_extensions[type-1] = ext; - } + if (m_defaultLatexFileExtensionsCombo->currentIndex() == type - 1) { + m_userFileExtensions->setText(ext); + } + else { + m_val_extensions[type-1] = ext; + } } void KileProjectDialogBase::setProject(KileProject *project, bool override) { - m_project = project; + m_project = project; - if ((!override) || (project == 0)) { - return; - } + if ((!override) || (project == 0)) { + return; + } - for (int i = KileProjectItem::Source; i < KileProjectItem::Other; ++i) { - m_val_extensions[i - 1] = project->extensions((KileProjectItem::Type) i); - } + for (int i = KileProjectItem::Source; i < KileProjectItem::Other; ++i) { + m_val_extensions[i - 1] = project->extensions((KileProjectItem::Type) i); + } - m_title->setText(m_project->name()); - m_userFileExtensions->setText(m_val_extensions[0]); - m_defaultLatexFileExtensions->setText(m_val_standardExtensions[0]); + m_title->setText(m_project->name()); + m_userFileExtensions->setText(m_val_extensions[0]); + m_defaultLatexFileExtensions->setText(m_val_standardExtensions[0]); - m_defaultGraphicsExtensionCombo->setCurrentIndex(m_defaultGraphicsExtensionCombo->findData(project->defaultGraphicExt())); + m_defaultGraphicsExtensionCombo->setCurrentIndex(m_defaultGraphicsExtensionCombo->findData(project->defaultGraphicExt())); } KileProject* KileProjectDialogBase::project() { - return m_project; + return m_project; } void KileProjectDialogBase::fillProjectDefaults() { - m_val_extensions[0].clear(); - m_val_extensions[1].clear(); - m_val_extensions[2].clear(); - m_val_extensions[3].clear(); - //m_val_extensions[4] = OTHER_EXTENSIONS; + m_val_extensions[0].clear(); + m_val_extensions[1].clear(); + m_val_extensions[2].clear(); + m_val_extensions[3].clear(); + //m_val_extensions[4] = OTHER_EXTENSIONS; - m_val_standardExtensions[0] = m_extmanager->latexDocuments(); - m_val_standardExtensions[1] = m_extmanager->latexPackages(); - m_val_standardExtensions[2] = m_extmanager->images(); - m_val_standardExtensions[3] = m_extmanager->bibtex(); + m_val_standardExtensions[0] = m_extmanager->latexDocuments(); + m_val_standardExtensions[1] = m_extmanager->latexPackages(); + m_val_standardExtensions[2] = m_extmanager->images(); + m_val_standardExtensions[3] = m_extmanager->bibtex(); - m_userFileExtensions->setText(m_val_extensions[0]); - m_defaultLatexFileExtensions->setText(m_val_standardExtensions[0]); + m_userFileExtensions->setText(m_val_extensions[0]); + m_defaultLatexFileExtensions->setText(m_val_standardExtensions[0]); - m_defaultGraphicsExtensionCombo->setCurrentIndex(0); + m_defaultGraphicsExtensionCombo->setCurrentIndex(0); } /* * KileNewProjectDialog */ KileNewProjectDialog::KileNewProjectDialog(KileTemplate::Manager *templateManager, KileDocument::Extensions *extensions, QWidget* parent, const char* name) - : KileProjectDialogBase(i18n("Create New Project"), extensions, parent, name) - , m_templateManager(templateManager) + : KileProjectDialogBase(i18n("Create New Project"), extensions, parent, name) + , m_templateManager(templateManager) { - QVBoxLayout *mainLayout = new QVBoxLayout; - setLayout(mainLayout); - - // properties groupbox - mainLayout->addWidget(m_projectGroup); - - // second groupbox - QGroupBox *fileGroup = new QGroupBox(i18n("File"), this); - mainLayout->addWidget(fileGroup); - QGridLayout *fileGrid = new QGridLayout(); - fileGroup->setLayout(fileGrid); - m_createNewFileCheckbox = new QCheckBox(i18n("Create a new file and add it to this project"), fileGroup); - m_createNewFileCheckbox->setChecked(true); - m_filenameLabel = new QLabel(i18n("File&name (relative to where the project file is):"), fileGroup); - m_file = new QLineEdit(fileGroup); - m_filenameLabel->setBuddy(m_file); - m_templateIconView = new TemplateIconView(fileGroup); - m_templateIconView->setTemplateManager(m_templateManager); - m_templateManager->scanForTemplates(); - m_templateIconView->fillWithTemplates(KileDocument::LaTeX); - m_createNewFileCheckbox->setWhatsThis(i18n("If you want Kile to create a new file and add it to the project, then check this option and select a template from the list that will appear below.")); - - fileGrid->addWidget(m_createNewFileCheckbox, 0, 0, 1, 2); - fileGrid->addWidget(m_filenameLabel, 1, 0); - fileGrid->addWidget(m_file, 1, 1); - fileGrid->addWidget(m_templateIconView, 2, 0, 1, 2); - fileGrid->setColumnStretch(1, 1); - connect(m_createNewFileCheckbox, SIGNAL(clicked()), this, SLOT(clickedCreateNewFileCb())); - - // add to layout - mainLayout->addWidget(m_projectGroup); - mainLayout->addWidget(fileGroup); - mainLayout->addWidget(m_extensionGroup); - mainLayout->addStretch(); - - fillProjectDefaults(); - - // add buttons - QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok|QDialogButtonBox::Cancel); - QPushButton *okButton = buttonBox->button(QDialogButtonBox::Ok); - okButton->setDefault(true); - okButton->setShortcut(Qt::CTRL | Qt::Key_Return); - okButton->setDefault(true); - connect(okButton, &QPushButton::clicked, this, &KileNewProjectDialog::handleOKButtonClicked); - connect(buttonBox, &QDialogButtonBox::rejected, this, &QDialog::reject); - - connect(m_defaultLatexFileExtensionsCombo, static_cast(&QComboBox::currentIndexChanged), - this, &KileNewProjectDialog::onExtensionsIndexChanged); - connect(m_userFileExtensions, &QLineEdit::textEdited, this, &KileNewProjectDialog::onExtensionsTextEdited); - - mainLayout->addWidget(buttonBox); - - QWidget::setTabOrder(m_projectFolder, m_createNewFileCheckbox); - - QWidget::setTabOrder(m_createNewFileCheckbox, m_file); - QWidget::setTabOrder(m_file, m_templateIconView); - QWidget::setTabOrder(m_templateIconView, m_defaultGraphicsExtensionCombo); - - QWidget::setTabOrder(m_defaultGraphicsExtensionCombo, buttonBox); + QVBoxLayout *mainLayout = new QVBoxLayout; + setLayout(mainLayout); + + // properties groupbox + mainLayout->addWidget(m_projectGroup); + + // second groupbox + QGroupBox *fileGroup = new QGroupBox(i18n("File"), this); + mainLayout->addWidget(fileGroup); + QGridLayout *fileGrid = new QGridLayout(); + fileGroup->setLayout(fileGrid); + m_createNewFileCheckbox = new QCheckBox(i18n("Create a new file and add it to this project"), fileGroup); + m_createNewFileCheckbox->setChecked(true); + m_filenameLabel = new QLabel(i18n("File&name (relative to where the project file is):"), fileGroup); + m_file = new QLineEdit(fileGroup); + m_filenameLabel->setBuddy(m_file); + m_templateIconView = new TemplateIconView(fileGroup); + m_templateIconView->setTemplateManager(m_templateManager); + m_templateManager->scanForTemplates(); + m_templateIconView->fillWithTemplates(KileDocument::LaTeX); + m_createNewFileCheckbox->setWhatsThis(i18n("If you want Kile to create a new file and add it to the project, then check this option and select a template from the list that will appear below.")); + + fileGrid->addWidget(m_createNewFileCheckbox, 0, 0, 1, 2); + fileGrid->addWidget(m_filenameLabel, 1, 0); + fileGrid->addWidget(m_file, 1, 1); + fileGrid->addWidget(m_templateIconView, 2, 0, 1, 2); + fileGrid->setColumnStretch(1, 1); + connect(m_createNewFileCheckbox, SIGNAL(clicked()), this, SLOT(clickedCreateNewFileCb())); + + // add to layout + mainLayout->addWidget(m_projectGroup); + mainLayout->addWidget(fileGroup); + mainLayout->addWidget(m_extensionGroup); + mainLayout->addStretch(); + + fillProjectDefaults(); + + // add buttons + QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok|QDialogButtonBox::Cancel); + QPushButton *okButton = buttonBox->button(QDialogButtonBox::Ok); + okButton->setDefault(true); + okButton->setShortcut(Qt::CTRL | Qt::Key_Return); + okButton->setDefault(true); + connect(okButton, &QPushButton::clicked, this, &KileNewProjectDialog::handleOKButtonClicked); + connect(buttonBox, &QDialogButtonBox::rejected, this, &QDialog::reject); + + connect(m_defaultLatexFileExtensionsCombo, static_cast(&QComboBox::currentIndexChanged), + this, &KileNewProjectDialog::onExtensionsIndexChanged); + connect(m_userFileExtensions, &QLineEdit::textEdited, this, &KileNewProjectDialog::onExtensionsTextEdited); + + mainLayout->addWidget(buttonBox); + + QWidget::setTabOrder(m_projectFolder, m_createNewFileCheckbox); + + QWidget::setTabOrder(m_createNewFileCheckbox, m_file); + QWidget::setTabOrder(m_file, m_templateIconView); + QWidget::setTabOrder(m_templateIconView, m_defaultGraphicsExtensionCombo); + + QWidget::setTabOrder(m_defaultGraphicsExtensionCombo, buttonBox); } KileNewProjectDialog::~KileNewProjectDialog() {} KileProject * KileNewProjectDialog::project() { - if (!m_project) { - m_project = new KileProject(projectTitle(), m_projectFileWithPath, m_extmanager); + if (!m_project) { + m_project = new KileProject(projectTitle(), m_projectFileWithPath, m_extmanager); - KileProjectItem::Type type; - for (int i = KileProjectItem::Source; i < KileProjectItem::Other; ++i) { - type = (KileProjectItem::Type) i; - m_project->setExtensions(type, extensions(type)); - } + KileProjectItem::Type type; + for (int i = KileProjectItem::Source; i < KileProjectItem::Other; ++i) { + type = (KileProjectItem::Type) i; + m_project->setExtensions(type, extensions(type)); + } - m_project->setDefaultGraphicExt( - m_defaultGraphicsExtensionCombo->itemData(m_defaultGraphicsExtensionCombo->currentIndex()).toString()); + m_project->setDefaultGraphicExt( + m_defaultGraphicsExtensionCombo->itemData(m_defaultGraphicsExtensionCombo->currentIndex()).toString()); - m_project->buildProjectTree(); - } + m_project->buildProjectTree(); + } - return m_project; + return m_project; } void KileNewProjectDialog::clickedCreateNewFileCb() { - if (m_createNewFileCheckbox->isChecked()) { - m_file->show(); - m_filenameLabel->show(); - m_templateIconView->show(); - } - else { - m_file->hide(); - m_filenameLabel->hide(); - m_templateIconView->hide(); - } + if (m_createNewFileCheckbox->isChecked()) { + m_file->show(); + m_filenameLabel->show(); + m_templateIconView->show(); + } + else { + m_file->hide(); + m_filenameLabel->hide(); + m_templateIconView->hide(); + } } QString KileNewProjectDialog::cleanProjectFile() { - return projectTitle().toLower().trimmed().remove(QRegExp("\\s*")) + ".kilepr"; + return projectTitle().toLower().trimmed().remove(QRegExp("\\s*")) + ".kilepr"; } void KileNewProjectDialog::handleOKButtonClicked() { - if (!acceptUserExtensions()) { - return; - } - - if (projectTitle().trimmed().isEmpty()) { - if (KMessageBox::warningYesNo(this, i18n("You have not entered a project name. If you decide to proceed, the project name will be set to \"Untitled\".\n" - "Do you want to create the project nevertheless?"), i18n("No Project Name Given")) == KMessageBox::Yes) { - m_title->setText(i18n("Untitled")); - } - else { - return; - } - } - - const QString dirString = folder().trimmed(); - const QString fileString = file().trimmed(); - - if (dirString.isEmpty()) { - KMessageBox::error(this, i18n("Please enter the folder where the project file should be saved to."), i18n("Empty Location")); - return; - } - - if (!QDir::isAbsolutePath(dirString)) { - KMessageBox::error(this, i18n("Please enter an absolute path to the project folder."), i18n("Invalid Location")); - return; - } - - if (createNewFile() && fileString.isEmpty()){ - KMessageBox::error(this, i18n("Please enter a filename for the file that should be added to this project."), i18n("No File Name Given")); - return; - } - - const QString cleanProjectFileName = cleanProjectFile(); - const QDir projectDir(dirString); - const QString projectFilePath = projectDir.filePath(cleanProjectFileName); - const QDir guiFileDir = KileProject::getPathForPrivateKileDirectory(projectFilePath); - - testDirectoryIsUsable(projectDir); - testDirectoryIsUsable(guiFileDir); - - if (QFileInfo(projectFilePath).exists()) { // this can only happen when the project dir existed already - KMessageBox::error(this, i18n("The project file exists already. Please choose another name."), i18n("Project File Already Exists")); - return; - } - - const QString guiProjectFilePath = KileProject::getPathForGUISettingsProjectFile(projectFilePath); - if (QFileInfo(guiProjectFilePath).exists()) { // this can only happen when the project dir existed already - KMessageBox::error(this, i18n("The GUI settings file exists already. Please choose another project name."), i18n("Project File Already Exists")); - return; - } - - if (createNewFile()) { - //check for validity of name first, then check for existence (fixed by tbraun) - QUrl fileURL; - fileURL = fileURL.adjusted(QUrl::RemoveFilename); - fileURL.setPath(fileURL.path() + file()); - QUrl validURL = KileDocument::Info::makeValidTeXURL(fileURL, this, m_extmanager->isTexFile(fileURL), true); - if(validURL != fileURL) { - m_file->setText(validURL.fileName()); - } - - if(QFileInfo(projectDir.filePath(fileString)).exists()){ - if (KMessageBox::warningYesNo(this, i18n("The file \"%1\" already exists, overwrite it?", fileString), i18n("File Already Exists")) == KMessageBox::No) { - return; - } - } - } - - m_projectFileWithPath = QUrl::fromLocalFile(projectFilePath); - accept(); + if (!acceptUserExtensions()) { + return; + } + + if (projectTitle().trimmed().isEmpty()) { + if (KMessageBox::warningYesNo(this, i18n("You have not entered a project name. If you decide to proceed, the project name will be set to \"Untitled\".\n" + "Do you want to create the project nevertheless?"), i18n("No Project Name Given")) == KMessageBox::Yes) { + m_title->setText(i18n("Untitled")); + } + else { + return; + } + } + + const QString dirString = folder().trimmed(); + const QString fileString = file().trimmed(); + + if (dirString.isEmpty()) { + KMessageBox::error(this, i18n("Please enter the folder where the project file should be saved to."), i18n("Empty Location")); + return; + } + + if (!QDir::isAbsolutePath(dirString)) { + KMessageBox::error(this, i18n("Please enter an absolute path to the project folder."), i18n("Invalid Location")); + return; + } + + if (createNewFile() && fileString.isEmpty()) { + KMessageBox::error(this, i18n("Please enter a filename for the file that should be added to this project."), i18n("No File Name Given")); + return; + } + + const QString cleanProjectFileName = cleanProjectFile(); + const QDir projectDir(dirString); + const QString projectFilePath = projectDir.filePath(cleanProjectFileName); + const QDir guiFileDir = KileProject::getPathForPrivateKileDirectory(projectFilePath); + + testDirectoryIsUsable(projectDir); + testDirectoryIsUsable(guiFileDir); + + if (QFileInfo(projectFilePath).exists()) { // this can only happen when the project dir existed already + KMessageBox::error(this, i18n("The project file exists already. Please choose another name."), i18n("Project File Already Exists")); + return; + } + + const QString guiProjectFilePath = KileProject::getPathForGUISettingsProjectFile(projectFilePath); + if (QFileInfo(guiProjectFilePath).exists()) { // this can only happen when the project dir existed already + KMessageBox::error(this, i18n("The GUI settings file exists already. Please choose another project name."), i18n("Project File Already Exists")); + return; + } + + if (createNewFile()) { + //check for validity of name first, then check for existence (fixed by tbraun) + QUrl fileURL; + fileURL = fileURL.adjusted(QUrl::RemoveFilename); + fileURL.setPath(fileURL.path() + file()); + QUrl validURL = KileDocument::Info::makeValidTeXURL(fileURL, this, m_extmanager->isTexFile(fileURL), true); + if(validURL != fileURL) { + m_file->setText(validURL.fileName()); + } + + if(QFileInfo(projectDir.filePath(fileString)).exists()) { + if (KMessageBox::warningYesNo(this, i18n("The file \"%1\" already exists, overwrite it?", fileString), i18n("File Already Exists")) == KMessageBox::No) { + return; + } + } + } + + m_projectFileWithPath = QUrl::fromLocalFile(projectFilePath); + accept(); } void KileNewProjectDialog::fillProjectDefaults() { - m_projectFolder->lineEdit()->setText(QDir::cleanPath(KileConfig::defaultProjectLocation())); - m_createNewFileCheckbox->setChecked(true); - KileProjectDialogBase::fillProjectDefaults(); + m_projectFolder->lineEdit()->setText(QDir::cleanPath(KileConfig::defaultProjectLocation())); + m_createNewFileCheckbox->setChecked(true); + KileProjectDialogBase::fillProjectDefaults(); } TemplateItem* KileNewProjectDialog::getSelection() const { - return static_cast(m_templateIconView->currentItem()); + return static_cast(m_templateIconView->currentItem()); } /* * KileProjectOptionsDialog */ KileProjectOptionsDialog::KileProjectOptionsDialog(KileProject *project, KileDocument::Extensions *extensions, QWidget *parent, const char * name) - : KileProjectDialogBase(i18n("Project Options"), extensions, parent, name) - , m_toolDefaultString(i18n("(use global setting)")) + : KileProjectDialogBase(i18n("Project Options"), extensions, parent, name) + , m_toolDefaultString(i18n("(use global setting)")) { - QVBoxLayout *mainLayout = new QVBoxLayout; - setLayout(mainLayout); - - // properties groupbox - mainLayout->addWidget(m_projectGroup); - - // third groupbox - QGroupBox *group3 = new QGroupBox(i18n("Properties"), this); - mainLayout->addWidget(group3); - QGridLayout *grid3 = new QGridLayout(); - grid3->setAlignment(Qt::AlignTop); - group3->setLayout(grid3); - - const QString whatsthisMaster = i18n("Select the default master document. Leave empty for auto detection."); - - m_selectMasterDocumentCombo = new KComboBox(false, group3); - m_selectMasterDocumentCombo->setObjectName("master"); - //m_selectMasterDocumentCombo->setDisabled(true); - QLabel *lb1 = new QLabel(i18n("&Master document:"), group3); - lb1->setBuddy(m_selectMasterDocumentCombo); - lb1->setMinimumWidth(m_defaultLatexFileExtensionsCombo->sizeHint().width()); - m_selectMasterDocumentCombo->setWhatsThis(whatsthisMaster); - lb1->setWhatsThis(whatsthisMaster); - - m_selectMasterDocumentCombo->addItem(i18n("(auto-detect)")); - QList rootItemList = project->rootItems(); - int index = 0; - for (QList::iterator it = rootItemList.begin(); it != rootItemList.end(); ++it) { - if ((*it)->type() == KileProjectItem::Source) { - m_selectMasterDocumentCombo->addItem((*it)->url().fileName()); - ++index; - if ((*it)->url().path() == project->masterDocument()) { - m_selectMasterDocumentCombo->setCurrentIndex(index); - } - } - } - - if (project->masterDocument().isEmpty()) { - m_selectMasterDocumentCombo->setCurrentIndex(0); - } - - QLabel *quickbuildLabel = new QLabel(i18n("&QuickBuild configuration:"), group3); - m_QuickBuildCheckbox = new KComboBox(group3); - quickbuildLabel->setBuddy(m_QuickBuildCheckbox); - m_QuickBuildCheckbox->addItem(m_toolDefaultString); - m_QuickBuildCheckbox->addItems(KileTool::configNames("QuickBuild", KSharedConfig::openConfig().data())); - QString itemToSelect = project->quickBuildConfig().length() > 0 ? project->quickBuildConfig() : m_toolDefaultString; - int selectIndex = m_QuickBuildCheckbox->findText(itemToSelect); - if(selectIndex >= 0) { - m_QuickBuildCheckbox->setCurrentIndex(selectIndex); - } - else { - m_QuickBuildCheckbox->addItem(itemToSelect); - } - - //don't put this after the call to toggleMakeIndex - setProject(project, true); - m_projectFolder->setUrl(project->baseURL()); - m_projectFolder->setEnabled(false); - - m_ckMakeIndex = new QCheckBox(i18n("&MakeIndex options"), group3); - connect(m_ckMakeIndex, SIGNAL(toggled(bool)), this, SLOT(toggleMakeIndex(bool))); - m_leMakeIndex = new QLineEdit(group3); - m_ckMakeIndex->setChecked(project->useMakeIndexOptions()); - toggleMakeIndex(m_ckMakeIndex->isChecked()); - - grid3->addWidget(lb1, 0, 0); - grid3->addWidget(m_selectMasterDocumentCombo, 0, 1); - grid3->addWidget(quickbuildLabel, 1, 0); - grid3->addWidget(m_QuickBuildCheckbox, 1, 1); - grid3->addWidget(m_ckMakeIndex, 2, 0); - grid3->addWidget(m_leMakeIndex, 2, 1, 1, 2); - grid3->setColumnStretch(2, 1); - - // add to layout - mainLayout->addWidget(m_projectGroup); - mainLayout->addWidget(m_extensionGroup); - mainLayout->addWidget(group3); - mainLayout->addStretch(); - - // add buttons - QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok|QDialogButtonBox::Cancel); - QPushButton *okButton = buttonBox->button(QDialogButtonBox::Ok); - okButton->setDefault(true); - okButton->setShortcut(Qt::CTRL | Qt::Key_Return); - okButton->setDefault(true); - connect(buttonBox, &QDialogButtonBox::accepted, this, &QDialog::accept); - connect(buttonBox, &QDialogButtonBox::rejected, this, &QDialog::reject); - connect(this, &QDialog::accepted, this, &KileProjectOptionsDialog::onAccepted); - - connect(m_defaultLatexFileExtensionsCombo, static_cast(&QComboBox::currentIndexChanged), - this, &KileProjectOptionsDialog::onExtensionsIndexChanged); - connect(m_userFileExtensions, &QLineEdit::textChanged, this, &KileProjectOptionsDialog::onExtensionsTextEdited); - - mainLayout->addWidget(buttonBox); - - QWidget::setTabOrder(m_projectFolder, m_defaultGraphicsExtensionCombo); - QWidget::setTabOrder(m_defaultLatexFileExtensions, m_selectMasterDocumentCombo); - - QWidget::setTabOrder(m_selectMasterDocumentCombo, m_QuickBuildCheckbox); - QWidget::setTabOrder(m_QuickBuildCheckbox, m_ckMakeIndex); - QWidget::setTabOrder(m_ckMakeIndex, m_leMakeIndex); - - QWidget::setTabOrder(m_leMakeIndex, buttonBox); + QVBoxLayout *mainLayout = new QVBoxLayout; + setLayout(mainLayout); + + // properties groupbox + mainLayout->addWidget(m_projectGroup); + + // third groupbox + QGroupBox *group3 = new QGroupBox(i18n("Properties"), this); + mainLayout->addWidget(group3); + QGridLayout *grid3 = new QGridLayout(); + grid3->setAlignment(Qt::AlignTop); + group3->setLayout(grid3); + + const QString whatsthisMaster = i18n("Select the default master document. Leave empty for auto detection."); + + m_selectMasterDocumentCombo = new KComboBox(false, group3); + m_selectMasterDocumentCombo->setObjectName("master"); + //m_selectMasterDocumentCombo->setDisabled(true); + QLabel *lb1 = new QLabel(i18n("&Master document:"), group3); + lb1->setBuddy(m_selectMasterDocumentCombo); + lb1->setMinimumWidth(m_defaultLatexFileExtensionsCombo->sizeHint().width()); + m_selectMasterDocumentCombo->setWhatsThis(whatsthisMaster); + lb1->setWhatsThis(whatsthisMaster); + + m_selectMasterDocumentCombo->addItem(i18n("(auto-detect)")); + QList rootItemList = project->rootItems(); + int index = 0; + for (QList::iterator it = rootItemList.begin(); it != rootItemList.end(); ++it) { + if ((*it)->type() == KileProjectItem::Source) { + m_selectMasterDocumentCombo->addItem((*it)->url().fileName()); + ++index; + if ((*it)->url().path() == project->masterDocument()) { + m_selectMasterDocumentCombo->setCurrentIndex(index); + } + } + } + + if (project->masterDocument().isEmpty()) { + m_selectMasterDocumentCombo->setCurrentIndex(0); + } + + QLabel *quickbuildLabel = new QLabel(i18n("&QuickBuild configuration:"), group3); + m_QuickBuildCheckbox = new KComboBox(group3); + quickbuildLabel->setBuddy(m_QuickBuildCheckbox); + m_QuickBuildCheckbox->addItem(m_toolDefaultString); + m_QuickBuildCheckbox->addItems(KileTool::configNames("QuickBuild", KSharedConfig::openConfig().data())); + QString itemToSelect = project->quickBuildConfig().length() > 0 ? project->quickBuildConfig() : m_toolDefaultString; + int selectIndex = m_QuickBuildCheckbox->findText(itemToSelect); + if(selectIndex >= 0) { + m_QuickBuildCheckbox->setCurrentIndex(selectIndex); + } + else { + m_QuickBuildCheckbox->addItem(itemToSelect); + } + + //don't put this after the call to toggleMakeIndex + setProject(project, true); + m_projectFolder->setUrl(project->baseURL()); + m_projectFolder->setEnabled(false); + + m_ckMakeIndex = new QCheckBox(i18n("&MakeIndex options"), group3); + connect(m_ckMakeIndex, SIGNAL(toggled(bool)), this, SLOT(toggleMakeIndex(bool))); + m_leMakeIndex = new QLineEdit(group3); + m_ckMakeIndex->setChecked(project->useMakeIndexOptions()); + toggleMakeIndex(m_ckMakeIndex->isChecked()); + + grid3->addWidget(lb1, 0, 0); + grid3->addWidget(m_selectMasterDocumentCombo, 0, 1); + grid3->addWidget(quickbuildLabel, 1, 0); + grid3->addWidget(m_QuickBuildCheckbox, 1, 1); + grid3->addWidget(m_ckMakeIndex, 2, 0); + grid3->addWidget(m_leMakeIndex, 2, 1, 1, 2); + grid3->setColumnStretch(2, 1); + + // add to layout + mainLayout->addWidget(m_projectGroup); + mainLayout->addWidget(m_extensionGroup); + mainLayout->addWidget(group3); + mainLayout->addStretch(); + + // add buttons + QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok|QDialogButtonBox::Cancel); + QPushButton *okButton = buttonBox->button(QDialogButtonBox::Ok); + okButton->setDefault(true); + okButton->setShortcut(Qt::CTRL | Qt::Key_Return); + okButton->setDefault(true); + connect(buttonBox, &QDialogButtonBox::accepted, this, &QDialog::accept); + connect(buttonBox, &QDialogButtonBox::rejected, this, &QDialog::reject); + connect(this, &QDialog::accepted, this, &KileProjectOptionsDialog::onAccepted); + + connect(m_defaultLatexFileExtensionsCombo, static_cast(&QComboBox::currentIndexChanged), + this, &KileProjectOptionsDialog::onExtensionsIndexChanged); + connect(m_userFileExtensions, &QLineEdit::textChanged, this, &KileProjectOptionsDialog::onExtensionsTextEdited); + + mainLayout->addWidget(buttonBox); + + QWidget::setTabOrder(m_projectFolder, m_defaultGraphicsExtensionCombo); + QWidget::setTabOrder(m_defaultLatexFileExtensions, m_selectMasterDocumentCombo); + + QWidget::setTabOrder(m_selectMasterDocumentCombo, m_QuickBuildCheckbox); + QWidget::setTabOrder(m_QuickBuildCheckbox, m_ckMakeIndex); + QWidget::setTabOrder(m_ckMakeIndex, m_leMakeIndex); + + QWidget::setTabOrder(m_leMakeIndex, buttonBox); } KileProjectOptionsDialog::~KileProjectOptionsDialog() { } void KileProjectOptionsDialog::toggleMakeIndex(bool on) { - KILE_DEBUG_MAIN << "TOGGLED!" << endl; - m_leMakeIndex->setEnabled(on); - m_project->setUseMakeIndexOptions(on); - m_project->writeUseMakeIndexOptions(); - m_project->readMakeIndexOptions(); - m_leMakeIndex->setText(m_project->makeIndexOptions()); + KILE_DEBUG_MAIN << "TOGGLED!" << endl; + m_leMakeIndex->setEnabled(on); + m_project->setUseMakeIndexOptions(on); + m_project->writeUseMakeIndexOptions(); + m_project->readMakeIndexOptions(); + m_leMakeIndex->setText(m_project->makeIndexOptions()); } void KileProjectOptionsDialog::onAccepted() { - if(!acceptUserExtensions()) { - return; - } - - this->m_project->setName(m_title->text()); - - QList rootItemList = m_project->rootItems(); - for (QList::iterator it = rootItemList.begin(); it != rootItemList.end(); ++it) { - if ((*it)->url().fileName() == m_selectMasterDocumentCombo->currentText()) { - m_project->setMasterDocument((*it)->url().toLocalFile()); - } - } - if (m_selectMasterDocumentCombo->currentIndex() == 0) { - m_project->setMasterDocument(QString()); - } - - m_val_extensions[m_defaultLatexFileExtensionsCombo->currentIndex()] = m_userFileExtensions->text(); - - for (int i = KileProjectItem::Source; i < KileProjectItem::Other; ++i) { - m_project->setExtensions((KileProjectItem::Type) i, m_val_extensions[i-1]); - } - - if (m_QuickBuildCheckbox->currentText() == m_toolDefaultString) { - m_project->setQuickBuildConfig(""); - } - else { - m_project->setQuickBuildConfig(m_QuickBuildCheckbox->currentText()); - } - - m_project->setUseMakeIndexOptions(m_ckMakeIndex->isChecked()); - if (m_project->useMakeIndexOptions()) { - m_project->setMakeIndexOptions(m_leMakeIndex->text()); - } - - m_project->setDefaultGraphicExt( - m_defaultGraphicsExtensionCombo->itemData(m_defaultGraphicsExtensionCombo->currentIndex()).toString()); - - m_project->save(); + if(!acceptUserExtensions()) { + return; + } + + this->m_project->setName(m_title->text()); + + QList rootItemList = m_project->rootItems(); + for (QList::iterator it = rootItemList.begin(); it != rootItemList.end(); ++it) { + if ((*it)->url().fileName() == m_selectMasterDocumentCombo->currentText()) { + m_project->setMasterDocument((*it)->url().toLocalFile()); + } + } + if (m_selectMasterDocumentCombo->currentIndex() == 0) { + m_project->setMasterDocument(QString()); + } + + m_val_extensions[m_defaultLatexFileExtensionsCombo->currentIndex()] = m_userFileExtensions->text(); + + for (int i = KileProjectItem::Source; i < KileProjectItem::Other; ++i) { + m_project->setExtensions((KileProjectItem::Type) i, m_val_extensions[i-1]); + } + + if (m_QuickBuildCheckbox->currentText() == m_toolDefaultString) { + m_project->setQuickBuildConfig(""); + } + else { + m_project->setQuickBuildConfig(m_QuickBuildCheckbox->currentText()); + } + + m_project->setUseMakeIndexOptions(m_ckMakeIndex->isChecked()); + if (m_project->useMakeIndexOptions()) { + m_project->setMakeIndexOptions(m_leMakeIndex->text()); + } + + m_project->setDefaultGraphicExt( + m_defaultGraphicsExtensionCombo->itemData(m_defaultGraphicsExtensionCombo->currentIndex()).toString()); + + m_project->save(); } bool KileNewProjectDialog::testDirectoryIsUsable(const QString& path) { - return testDirectoryIsUsable(QDir(path)); + return testDirectoryIsUsable(QDir(path)); } bool KileNewProjectDialog::testDirectoryIsUsable(const QDir& dir) { - if (!dir.exists()) { - dir.mkpath(dir.absolutePath()); - } - - if (!dir.exists()) { - KMessageBox::error(this, i18n("

Could not create the project folder \"\n%1\"

." - "

Please check whether you have write permissions.

").arg(dir.path())); - return false; - } - - QFileInfo fi(dir.absolutePath()); - if (!fi.isDir() || !fi.isWritable()){ - KMessageBox::error(this, i18n("

The project folder \"(%1)\" is not writable.

" - "

Please check the permissions of the project folder.

").arg(dir.path())); - return false; - } - return true; + if (!dir.exists()) { + dir.mkpath(dir.absolutePath()); + } + + if (!dir.exists()) { + KMessageBox::error(this, i18n("

Could not create the project folder \"\n%1\"

." + "

Please check whether you have write permissions.

").arg(dir.path())); + return false; + } + + QFileInfo fi(dir.absolutePath()); + if (!fi.isDir() || !fi.isWritable()) { + KMessageBox::error(this, i18n("

The project folder \"(%1)\" is not writable.

" + "

Please check the permissions of the project folder.

").arg(dir.path())); + return false; + } + return true; } diff --git a/src/dialogs/projectdialogs.h b/src/dialogs/projectdialogs.h index 2c3da06d..4b92b61a 100644 --- a/src/dialogs/projectdialogs.h +++ b/src/dialogs/projectdialogs.h @@ -1,154 +1,154 @@ /*************************************************************************** Copyright (C) 2003 by Jeroen Wijnhout (Jeroen.Wijnhout@kdemail.net) (C) 2015 by Andreas Cord-Landwehr (cordlandwehr@kde.org) ***************************************************************************/ /*************************************************************************** * * * 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. * * * ***************************************************************************/ #ifndef PROJECTDIALOGS_H #define PROJECTDIALOGS_H #include #include #include #include #include #include "kileextensions.h" #include "kileproject.h" #include "templates.h" class QComboBox; class QGridLayout; class QGroupBox; class QLabel; class KileProject; class TemplateItem; class TemplateIconView; namespace KileDocument { class Extensions; } namespace KileTemplate { class Manager; } class KileProjectDialogBase : public QDialog { - Q_OBJECT + Q_OBJECT public: - KileProjectDialogBase(const QString &caption, KileDocument::Extensions *extensions, QWidget *parent = Q_NULLPTR, const char * name = Q_NULLPTR); - virtual ~KileProjectDialogBase(); - - void setProject(KileProject *project, bool override); - virtual KileProject * project(); - - void setProjectTitle(const QString &title) - { - m_title->setText(title); - } - QString projectTitle() const - { - return m_title->text(); - } - - void setExtensions(KileProjectItem::Type type, const QString &ext); - QString extensions(KileProjectItem::Type type) const - { - return m_val_extensions[type-1]; - } + KileProjectDialogBase(const QString &caption, KileDocument::Extensions *extensions, QWidget *parent = Q_NULLPTR, const char * name = Q_NULLPTR); + virtual ~KileProjectDialogBase(); + + void setProject(KileProject *project, bool override); + virtual KileProject * project(); + + void setProjectTitle(const QString &title) + { + m_title->setText(title); + } + QString projectTitle() const + { + return m_title->text(); + } + + void setExtensions(KileProjectItem::Type type, const QString &ext); + QString extensions(KileProjectItem::Type type) const + { + return m_val_extensions[type-1]; + } protected Q_SLOTS: - virtual void fillProjectDefaults(); - virtual void onExtensionsIndexChanged(int index); - virtual void onExtensionsTextEdited(const QString &text); + virtual void fillProjectDefaults(); + virtual void onExtensionsIndexChanged(int index); + virtual void onExtensionsTextEdited(const QString &text); protected: - KileDocument::Extensions *m_extmanager; - KileProject *m_project; + KileDocument::Extensions *m_extmanager; + KileProject *m_project; - QGroupBox *m_projectGroup; - QGroupBox *m_extensionGroup; - KUrlRequester *m_projectFolder; + QGroupBox *m_projectGroup; + QGroupBox *m_extensionGroup; + KUrlRequester *m_projectFolder; - QLineEdit *m_title, *m_userFileExtensions; - QLabel *m_defaultLatexFileExtensions; + QLineEdit *m_title, *m_userFileExtensions; + QLabel *m_defaultLatexFileExtensions; - QComboBox *m_defaultLatexFileExtensionsCombo; - QComboBox *m_defaultGraphicsExtensionCombo; + QComboBox *m_defaultLatexFileExtensionsCombo; + QComboBox *m_defaultGraphicsExtensionCombo; - QString m_val_extensions[KileProjectItem::Other - 1]; - QString m_val_standardExtensions[KileProjectItem::Other - 1]; + QString m_val_extensions[KileProjectItem::Other - 1]; + QString m_val_standardExtensions[KileProjectItem::Other - 1]; - bool acceptUserExtensions(); + bool acceptUserExtensions(); }; class KileNewProjectDialog : public KileProjectDialogBase { - Q_OBJECT + Q_OBJECT public: - KileNewProjectDialog(KileTemplate::Manager *templateManager, KileDocument::Extensions *extensions, QWidget* parent = Q_NULLPTR, const char* name = Q_NULLPTR); - ~KileNewProjectDialog(); + KileNewProjectDialog(KileTemplate::Manager *templateManager, KileDocument::Extensions *extensions, QWidget* parent = Q_NULLPTR, const char* name = Q_NULLPTR); + ~KileNewProjectDialog(); - KileProject *project() Q_DECL_OVERRIDE; + KileProject *project() Q_DECL_OVERRIDE; - QString cleanProjectFile(); - QString folder() const { - return m_projectFolder->lineEdit()->text(); - } + QString cleanProjectFile(); + QString folder() const { + return m_projectFolder->lineEdit()->text(); + } - TemplateItem* getSelection() const; - QString file() const { - return m_file->text(); - } - bool createNewFile() const { - return m_createNewFileCheckbox->isChecked(); - } + TemplateItem* getSelection() const; + QString file() const { + return m_file->text(); + } + bool createNewFile() const { + return m_createNewFileCheckbox->isChecked(); + } private Q_SLOTS: - void clickedCreateNewFileCb(); - void fillProjectDefaults() Q_DECL_OVERRIDE; - void handleOKButtonClicked(); + void clickedCreateNewFileCb(); + void fillProjectDefaults() Q_DECL_OVERRIDE; + void handleOKButtonClicked(); private: - bool testDirectoryIsUsable(const QString& path); - bool testDirectoryIsUsable(const QDir& dir); - - KileTemplate::Manager *m_templateManager; - QLineEdit *m_file, *m_name; - TemplateIconView *m_templateIconView; - QCheckBox *m_createNewFileCheckbox; - QLabel *m_filenameLabel; - QUrl m_projectFileWithPath; + bool testDirectoryIsUsable(const QString& path); + bool testDirectoryIsUsable(const QDir& dir); + + KileTemplate::Manager *m_templateManager; + QLineEdit *m_file, *m_name; + TemplateIconView *m_templateIconView; + QCheckBox *m_createNewFileCheckbox; + QLabel *m_filenameLabel; + QUrl m_projectFileWithPath; }; class KileProjectOptionsDialog : public KileProjectDialogBase { - Q_OBJECT + Q_OBJECT public: - KileProjectOptionsDialog(KileProject *project, KileDocument::Extensions *extensions, QWidget *parent = Q_NULLPTR, const char * name = Q_NULLPTR); - ~KileProjectOptionsDialog(); + KileProjectOptionsDialog(KileProject *project, KileDocument::Extensions *extensions, QWidget *parent = Q_NULLPTR, const char * name = Q_NULLPTR); + ~KileProjectOptionsDialog(); private Q_SLOTS: - void toggleMakeIndex(bool); - void onAccepted(); + void toggleMakeIndex(bool); + void onAccepted(); private: - KComboBox *m_selectMasterDocumentCombo, *m_QuickBuildCheckbox; - QLineEdit *m_leMakeIndex; - QCheckBox *m_ckMakeIndex; - QString m_toolDefaultString; + KComboBox *m_selectMasterDocumentCombo, *m_QuickBuildCheckbox; + QLineEdit *m_leMakeIndex; + QCheckBox *m_ckMakeIndex; + QString m_toolDefaultString; }; #endif diff --git a/src/dialogs/quickdocumentdialog.cpp b/src/dialogs/quickdocumentdialog.cpp index 46e34964..3fee343e 100644 --- a/src/dialogs/quickdocumentdialog.cpp +++ b/src/dialogs/quickdocumentdialog.cpp @@ -1,2384 +1,2367 @@ /*************************************************************************************** date : Sep 15 2004 version : 0.23 copyright : Thomas Fischer restructured, improved and completed by Holger Danielsson (C) 2004 by Holger Danielsson (holger.danielsson@t-online.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. * * * ***************************************************************************/ #include "dialogs/quickdocumentdialog.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "widgets/categorycombobox.h" #include "kiledebug.h" #include "kileconfig.h" namespace KileDialog { enum { - qd_Base = 1, - qd_Article = 2, - qd_BookReport = 4, - qd_KomaArticle = 8, - qd_KomaBookReport = 16, - qd_KomaAbstract = 32, - qd_Prosper = 64, - qd_Beamer = 128 + qd_Base = 1, + qd_Article = 2, + qd_BookReport = 4, + qd_KomaArticle = 8, + qd_KomaBookReport = 16, + qd_KomaAbstract = 32, + qd_Prosper = 64, + qd_Beamer = 128 }; // list with index numbers for the stringlist with all information of a document class enum { - qd_Fontsizes, - qd_Papersizes, - qd_DefaultOptions, - qd_SelectedOptions, - qd_OptionsStart + qd_Fontsizes, + qd_Papersizes, + qd_DefaultOptions, + qd_SelectedOptions, + qd_OptionsStart }; //////////////////// EditableItemDelegate //////////////////// class EditableItemDelegate : public QItemDelegate { - public: - EditableItemDelegate(QObject *parent = 0) : QItemDelegate(parent) {} - - virtual void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex& index) const - { - drawBackground(painter, option, index); - - QColor textColor = option.palette.color(QPalette::Text); - QString text = index.data(Qt::DisplayRole).toString(); - if (text == "" || text == "") { - textColor = Qt::gray; - } else - if (option.state & QStyle::State_Selected) { - textColor = option.palette.color(QPalette::HighlightedText); - } - painter->setPen(textColor); - painter->drawText(option.rect, Qt::AlignCenter | Qt::AlignVCenter, text); - //drawDisplay(painter, option, option.rect, index.data(Qt::DisplayRole).toString()); - drawFocus(painter, option, option.rect); - } +public: + EditableItemDelegate(QObject *parent = 0) : QItemDelegate(parent) {} + + virtual void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex& index) const + { + drawBackground(painter, option, index); + + QColor textColor = option.palette.color(QPalette::Text); + QString text = index.data(Qt::DisplayRole).toString(); + if (text == "" || text == "") { + textColor = Qt::gray; + } else if (option.state & QStyle::State_Selected) { + textColor = option.palette.color(QPalette::HighlightedText); + } + painter->setPen(textColor); + painter->drawText(option.rect, Qt::AlignCenter | Qt::AlignVCenter, text); + //drawDisplay(painter, option, option.rect, index.data(Qt::DisplayRole).toString()); + drawFocus(painter, option, option.rect); + } }; //////////////////// QuickDocument class //////////////////// QuickDocument::QuickDocument(KConfig *config, QWidget *parent, const char *name, const QString &caption) : Wizard(config, parent, name, caption) { - KILE_DEBUG_MAIN << "==QuickDocument::setupGUI()============"; - QTabWidget *tabWidget = new QTabWidget(this); - QVBoxLayout *mainLayout = new QVBoxLayout; - setLayout(mainLayout); - mainLayout->addWidget(tabWidget); + KILE_DEBUG_MAIN << "==QuickDocument::setupGUI()============"; + QTabWidget *tabWidget = new QTabWidget(this); + QVBoxLayout *mainLayout = new QVBoxLayout; + setLayout(mainLayout); + mainLayout->addWidget(tabWidget); - tabWidget->addTab(setupClassOptions(tabWidget), i18n("Cla&ss Options")); - tabWidget->addTab(setupPackages(tabWidget), i18n("&Packages")); - tabWidget->addTab(setupProperties(tabWidget), i18n("&Document Properties")); + tabWidget->addTab(setupClassOptions(tabWidget), i18n("Cla&ss Options")); + tabWidget->addTab(setupPackages(tabWidget), i18n("&Packages")); + tabWidget->addTab(setupProperties(tabWidget), i18n("&Document Properties")); - QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok|QDialogButtonBox::Cancel); - QPushButton *okButton = buttonBox->button(QDialogButtonBox::Ok); - okButton->setDefault(true); - okButton->setShortcut(Qt::CTRL | Qt::Key_Return); - connect(buttonBox, &QDialogButtonBox::accepted, this, &QDialog::accept); - connect(buttonBox, &QDialogButtonBox::rejected, this, &QDialog::reject); - connect(this, &QDialog::accepted, this, &QuickDocument::slotAccepted); - mainLayout->addWidget(buttonBox); + QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok|QDialogButtonBox::Cancel); + QPushButton *okButton = buttonBox->button(QDialogButtonBox::Ok); + okButton->setDefault(true); + okButton->setShortcut(Qt::CTRL | Qt::Key_Return); + connect(buttonBox, &QDialogButtonBox::accepted, this, &QDialog::accept); + connect(buttonBox, &QDialogButtonBox::rejected, this, &QDialog::reject); + connect(this, &QDialog::accepted, this, &QuickDocument::slotAccepted); + mainLayout->addWidget(buttonBox); - // read config file - readConfig(); - m_lvClassOptions->resizeColumnToContents(0); - m_lvPackages->resizeColumnToContents(0); + // read config file + readConfig(); + m_lvClassOptions->resizeColumnToContents(0); + m_lvPackages->resizeColumnToContents(0); } QuickDocument::~QuickDocument() {} //////////////////// GUI //////////////////// QWidget *QuickDocument::setupClassOptions(QTabWidget *tab) { - KILE_DEBUG_MAIN << "\tsetupClassOptions"; - QLabel *label; - - QWidget *classOptions = new QWidget(tab); - QGridLayout *gl = new QGridLayout(); - classOptions->setLayout(gl); - - // Document classes - m_cbDocumentClass = new KileWidget::CategoryComboBox(classOptions); - m_cbDocumentClass->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Minimum); - m_cbDocumentClass->setDuplicatesEnabled(false); - gl->addWidget(m_cbDocumentClass, 0, 1); - connect(m_cbDocumentClass, SIGNAL(activated(int)), this, SLOT(slotDocumentClassChanged(int))); - - label = new QLabel(i18n("Doc&ument class:"), classOptions); - gl->addWidget(label, 0, 0); - label->setBuddy(m_cbDocumentClass); - label->setSizePolicy(QSizePolicy::Maximum, QSizePolicy::Maximum); - - m_btnDocumentClassAdd = new QPushButton(classOptions); - m_btnDocumentClassAdd->setIcon(QIcon::fromTheme("list-add")); - m_btnDocumentClassAdd->setWhatsThis(i18n("Add an entry to this combo box")); - gl->addWidget(m_btnDocumentClassAdd, 0, 2); - connect(m_btnDocumentClassAdd, SIGNAL(clicked()), this, SLOT(slotDocumentClassAdd())); - - m_btnDocumentClassDelete = new QPushButton(classOptions); - m_btnDocumentClassDelete->setIcon(QIcon::fromTheme("list-remove")); - m_btnDocumentClassDelete->setWhatsThis(i18n("Remove current entry from this combo box")); - gl->addWidget(m_btnDocumentClassDelete, 0, 3); - connect(m_btnDocumentClassDelete, SIGNAL(clicked()), this, SLOT(slotDocumentClassDelete())); - - // Fontsize - m_cbTypefaceSize = new KileWidget::CategoryComboBox(classOptions); - m_cbTypefaceSize->setDuplicatesEnabled(false); - gl->addWidget(m_cbTypefaceSize, 1, 1); - - label = new QLabel(i18n("&Typeface size:"), classOptions); - label->setBuddy(m_cbTypefaceSize); - label->setSizePolicy(QSizePolicy::Maximum, QSizePolicy::Maximum); - gl->addWidget(label, 1, 0); - - m_btnTypefaceSizeAdd = new QPushButton(classOptions); - m_btnTypefaceSizeAdd->setIcon(QIcon::fromTheme("list-add")); - m_btnTypefaceSizeAdd->setWhatsThis(i18n("Add an entry to this combo box")); - gl->addWidget(m_btnTypefaceSizeAdd, 1, 2); - connect(m_btnTypefaceSizeAdd, SIGNAL(clicked()), this, SLOT(slotTypefaceSizeAdd())); - - m_btnTypefaceSizeDelete = new QPushButton(classOptions); - m_btnTypefaceSizeDelete->setIcon(QIcon::fromTheme("list-remove")); - m_btnTypefaceSizeDelete->setWhatsThis(i18n("Remove current entry from this combo box")); - gl->addWidget(m_btnTypefaceSizeDelete, 1, 3); - connect(m_btnTypefaceSizeDelete, SIGNAL(clicked()), this, SLOT(slotTypefaceSizeDelete())); - - // Papersize - m_cbPaperSize = new KileWidget::CategoryComboBox(classOptions); - m_cbPaperSize->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Minimum); - m_cbPaperSize->setDuplicatesEnabled(false); - gl->addWidget(m_cbPaperSize, 2, 1); - - m_lbPaperSize = new QLabel(i18n("Paper si&ze:"), classOptions); - m_lbPaperSize->setBuddy(m_cbPaperSize); - m_lbPaperSize->setSizePolicy(QSizePolicy::Maximum, QSizePolicy::Maximum); - gl->addWidget(m_lbPaperSize, 2, 0); - - m_btnPaperSizeAdd = new QPushButton(classOptions); - m_btnPaperSizeAdd->setIcon(QIcon::fromTheme("list-add")); - m_btnPaperSizeAdd->setWhatsThis(i18n("Add an entry to this combo box")); - gl->addWidget(m_btnPaperSizeAdd, 2, 2); - connect(m_btnPaperSizeAdd, SIGNAL(clicked()), this, SLOT(slotPaperSizeAdd())); - - m_btnPaperSizeDelete = new QPushButton(classOptions); - m_btnPaperSizeDelete->setIcon(QIcon::fromTheme("list-remove")); - m_btnPaperSizeDelete->setWhatsThis(i18n("Remove current entry from this combo box")); - gl->addWidget(m_btnPaperSizeDelete, 2, 3); - connect(m_btnPaperSizeDelete, SIGNAL(clicked()), this, SLOT(slotPaperSizeDelete())); - - // Encoding - m_cbEncoding = new KileWidget::CategoryComboBox(classOptions); - m_cbEncoding->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Minimum); - m_cbEncoding->setDuplicatesEnabled(false); - gl->addWidget(m_cbEncoding, 3, 1); - - label = new QLabel(i18n("E&ncoding:"), classOptions); - label->setBuddy(m_cbEncoding); - label->setSizePolicy(QSizePolicy::Maximum, QSizePolicy::Maximum); - gl->addWidget(label, 3, 0); - - // Class Options - m_lvClassOptions = new QTreeWidget(classOptions); - m_lvClassOptions->setHeaderLabels(QStringList() << i18n("Option") - << i18n("Description")); - m_lvClassOptions->setAllColumnsShowFocus(true); - m_lvClassOptions->setRootIsDecorated(false); - gl->addWidget(m_lvClassOptions, 4, 1, 1, 3); - connect(m_lvClassOptions, SIGNAL(itemSelectionChanged()), - this, SLOT(slotEnableButtons())); - connect(m_lvClassOptions, SIGNAL(itemDoubleClicked(QTreeWidgetItem*, int)), - this, SLOT(slotOptionDoubleClicked(QTreeWidgetItem*, int))); - - label = new QLabel(i18n("Cl&ass options:"), classOptions); - label->setBuddy(m_lvClassOptions); - label->setSizePolicy(QSizePolicy::Maximum, QSizePolicy::MinimumExpanding); - label->setAlignment(Qt::AlignTop); - gl->addWidget(label, 4, 0); - - // button - QWidget *frame = new QWidget(classOptions); - QHBoxLayout *hl = new QHBoxLayout(); - hl->setMargin(0); - frame->setLayout(hl); - gl->addWidget(frame, 5, 1, 1, 3, Qt::AlignCenter); - - m_btnClassOptionsAdd = new QPushButton(i18n("&Add..."), frame); - m_btnClassOptionsAdd->setIcon(QIcon::fromTheme("list-add")); - m_btnClassOptionsAdd->setWhatsThis(i18n("Add a new class option")); - hl->addWidget(m_btnClassOptionsAdd); - connect(m_btnClassOptionsAdd, SIGNAL(clicked()), this, SLOT(slotClassOptionAdd())); - - m_btnClassOptionsEdit = new QPushButton(i18n("Ed&it..."), frame); - m_btnClassOptionsEdit->setIcon(QIcon::fromTheme("document-properties")); - m_btnClassOptionsEdit->setWhatsThis(i18n("Edit the current class option")); - hl->addWidget(m_btnClassOptionsEdit); - connect(m_btnClassOptionsEdit, SIGNAL(clicked()), this, SLOT(slotClassOptionEdit())); - - m_btnClassOptionsDelete = new QPushButton(i18n("De&lete"), frame); - m_btnClassOptionsDelete->setIcon(QIcon::fromTheme("list-remove")); - m_btnClassOptionsDelete->setWhatsThis(i18n("Remove the current class option")); - hl->addWidget(m_btnClassOptionsDelete); - connect(m_btnClassOptionsDelete, SIGNAL(clicked()), this, SLOT(slotClassOptionDelete())); - - return classOptions; + KILE_DEBUG_MAIN << "\tsetupClassOptions"; + QLabel *label; + + QWidget *classOptions = new QWidget(tab); + QGridLayout *gl = new QGridLayout(); + classOptions->setLayout(gl); + + // Document classes + m_cbDocumentClass = new KileWidget::CategoryComboBox(classOptions); + m_cbDocumentClass->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Minimum); + m_cbDocumentClass->setDuplicatesEnabled(false); + gl->addWidget(m_cbDocumentClass, 0, 1); + connect(m_cbDocumentClass, SIGNAL(activated(int)), this, SLOT(slotDocumentClassChanged(int))); + + label = new QLabel(i18n("Doc&ument class:"), classOptions); + gl->addWidget(label, 0, 0); + label->setBuddy(m_cbDocumentClass); + label->setSizePolicy(QSizePolicy::Maximum, QSizePolicy::Maximum); + + m_btnDocumentClassAdd = new QPushButton(classOptions); + m_btnDocumentClassAdd->setIcon(QIcon::fromTheme("list-add")); + m_btnDocumentClassAdd->setWhatsThis(i18n("Add an entry to this combo box")); + gl->addWidget(m_btnDocumentClassAdd, 0, 2); + connect(m_btnDocumentClassAdd, SIGNAL(clicked()), this, SLOT(slotDocumentClassAdd())); + + m_btnDocumentClassDelete = new QPushButton(classOptions); + m_btnDocumentClassDelete->setIcon(QIcon::fromTheme("list-remove")); + m_btnDocumentClassDelete->setWhatsThis(i18n("Remove current entry from this combo box")); + gl->addWidget(m_btnDocumentClassDelete, 0, 3); + connect(m_btnDocumentClassDelete, SIGNAL(clicked()), this, SLOT(slotDocumentClassDelete())); + + // Fontsize + m_cbTypefaceSize = new KileWidget::CategoryComboBox(classOptions); + m_cbTypefaceSize->setDuplicatesEnabled(false); + gl->addWidget(m_cbTypefaceSize, 1, 1); + + label = new QLabel(i18n("&Typeface size:"), classOptions); + label->setBuddy(m_cbTypefaceSize); + label->setSizePolicy(QSizePolicy::Maximum, QSizePolicy::Maximum); + gl->addWidget(label, 1, 0); + + m_btnTypefaceSizeAdd = new QPushButton(classOptions); + m_btnTypefaceSizeAdd->setIcon(QIcon::fromTheme("list-add")); + m_btnTypefaceSizeAdd->setWhatsThis(i18n("Add an entry to this combo box")); + gl->addWidget(m_btnTypefaceSizeAdd, 1, 2); + connect(m_btnTypefaceSizeAdd, SIGNAL(clicked()), this, SLOT(slotTypefaceSizeAdd())); + + m_btnTypefaceSizeDelete = new QPushButton(classOptions); + m_btnTypefaceSizeDelete->setIcon(QIcon::fromTheme("list-remove")); + m_btnTypefaceSizeDelete->setWhatsThis(i18n("Remove current entry from this combo box")); + gl->addWidget(m_btnTypefaceSizeDelete, 1, 3); + connect(m_btnTypefaceSizeDelete, SIGNAL(clicked()), this, SLOT(slotTypefaceSizeDelete())); + + // Papersize + m_cbPaperSize = new KileWidget::CategoryComboBox(classOptions); + m_cbPaperSize->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Minimum); + m_cbPaperSize->setDuplicatesEnabled(false); + gl->addWidget(m_cbPaperSize, 2, 1); + + m_lbPaperSize = new QLabel(i18n("Paper si&ze:"), classOptions); + m_lbPaperSize->setBuddy(m_cbPaperSize); + m_lbPaperSize->setSizePolicy(QSizePolicy::Maximum, QSizePolicy::Maximum); + gl->addWidget(m_lbPaperSize, 2, 0); + + m_btnPaperSizeAdd = new QPushButton(classOptions); + m_btnPaperSizeAdd->setIcon(QIcon::fromTheme("list-add")); + m_btnPaperSizeAdd->setWhatsThis(i18n("Add an entry to this combo box")); + gl->addWidget(m_btnPaperSizeAdd, 2, 2); + connect(m_btnPaperSizeAdd, SIGNAL(clicked()), this, SLOT(slotPaperSizeAdd())); + + m_btnPaperSizeDelete = new QPushButton(classOptions); + m_btnPaperSizeDelete->setIcon(QIcon::fromTheme("list-remove")); + m_btnPaperSizeDelete->setWhatsThis(i18n("Remove current entry from this combo box")); + gl->addWidget(m_btnPaperSizeDelete, 2, 3); + connect(m_btnPaperSizeDelete, SIGNAL(clicked()), this, SLOT(slotPaperSizeDelete())); + + // Encoding + m_cbEncoding = new KileWidget::CategoryComboBox(classOptions); + m_cbEncoding->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Minimum); + m_cbEncoding->setDuplicatesEnabled(false); + gl->addWidget(m_cbEncoding, 3, 1); + + label = new QLabel(i18n("E&ncoding:"), classOptions); + label->setBuddy(m_cbEncoding); + label->setSizePolicy(QSizePolicy::Maximum, QSizePolicy::Maximum); + gl->addWidget(label, 3, 0); + + // Class Options + m_lvClassOptions = new QTreeWidget(classOptions); + m_lvClassOptions->setHeaderLabels(QStringList() << i18n("Option") + << i18n("Description")); + m_lvClassOptions->setAllColumnsShowFocus(true); + m_lvClassOptions->setRootIsDecorated(false); + gl->addWidget(m_lvClassOptions, 4, 1, 1, 3); + connect(m_lvClassOptions, SIGNAL(itemSelectionChanged()), + this, SLOT(slotEnableButtons())); + connect(m_lvClassOptions, SIGNAL(itemDoubleClicked(QTreeWidgetItem*, int)), + this, SLOT(slotOptionDoubleClicked(QTreeWidgetItem*, int))); + + label = new QLabel(i18n("Cl&ass options:"), classOptions); + label->setBuddy(m_lvClassOptions); + label->setSizePolicy(QSizePolicy::Maximum, QSizePolicy::MinimumExpanding); + label->setAlignment(Qt::AlignTop); + gl->addWidget(label, 4, 0); + + // button + QWidget *frame = new QWidget(classOptions); + QHBoxLayout *hl = new QHBoxLayout(); + hl->setMargin(0); + frame->setLayout(hl); + gl->addWidget(frame, 5, 1, 1, 3, Qt::AlignCenter); + + m_btnClassOptionsAdd = new QPushButton(i18n("&Add..."), frame); + m_btnClassOptionsAdd->setIcon(QIcon::fromTheme("list-add")); + m_btnClassOptionsAdd->setWhatsThis(i18n("Add a new class option")); + hl->addWidget(m_btnClassOptionsAdd); + connect(m_btnClassOptionsAdd, SIGNAL(clicked()), this, SLOT(slotClassOptionAdd())); + + m_btnClassOptionsEdit = new QPushButton(i18n("Ed&it..."), frame); + m_btnClassOptionsEdit->setIcon(QIcon::fromTheme("document-properties")); + m_btnClassOptionsEdit->setWhatsThis(i18n("Edit the current class option")); + hl->addWidget(m_btnClassOptionsEdit); + connect(m_btnClassOptionsEdit, SIGNAL(clicked()), this, SLOT(slotClassOptionEdit())); + + m_btnClassOptionsDelete = new QPushButton(i18n("De&lete"), frame); + m_btnClassOptionsDelete->setIcon(QIcon::fromTheme("list-remove")); + m_btnClassOptionsDelete->setWhatsThis(i18n("Remove the current class option")); + hl->addWidget(m_btnClassOptionsDelete); + connect(m_btnClassOptionsDelete, SIGNAL(clicked()), this, SLOT(slotClassOptionDelete())); + + return classOptions; } QWidget *QuickDocument::setupPackages(QTabWidget *tab) { - KILE_DEBUG_MAIN << "\tsetupPackages"; - - QWidget *packages = new QWidget(tab); - QVBoxLayout *vl = new QVBoxLayout(); - packages->setLayout(vl); - - QLabel *label = new QLabel(i18n("LaTe&X packages:"), packages); - vl->addWidget(label); - m_lvPackages = new QTreeWidget(packages); - vl->addWidget(m_lvPackages); - m_lvPackages->setRootIsDecorated(true); - m_lvPackages->setHeaderLabels(QStringList() << i18n("Package") << i18n("Value") << i18n("Description")); - m_lvPackages->setAllColumnsShowFocus(true); - m_lvPackages->setItemDelegateForColumn(1, new EditableItemDelegate()); - label->setBuddy(m_lvPackages); - connect(m_lvPackages, SIGNAL(itemClicked(QTreeWidgetItem*, int)), - this, SLOT(slotCheckParent(QTreeWidgetItem*))); - connect(m_lvPackages, SIGNAL(itemChanged(QTreeWidgetItem*, int)), - this, SLOT(slotCheckParent(QTreeWidgetItem*))); - connect(m_lvPackages, SIGNAL(itemSelectionChanged()), - this, SLOT(slotEnableButtons())); - connect(m_lvPackages, SIGNAL(itemDoubleClicked(QTreeWidgetItem*, int)), - this, SLOT(slotPackageDoubleClicked(QTreeWidgetItem*))); - - QWidget *frame = new QWidget(packages); - vl->addWidget(frame); - QHBoxLayout *hl = new QHBoxLayout(); - hl->setMargin(0); - frame->setLayout(hl); - hl->addStretch(); - - m_btnPackagesAdd = new QPushButton(i18n("&Add Package..."), frame); - m_btnPackagesAdd->setIcon(QIcon::fromTheme("list-add")); - m_btnPackagesAdd->setWhatsThis(i18n("Add a new package")); - connect(m_btnPackagesAdd, SIGNAL(clicked()), this, SLOT(slotPackageAdd())); - hl->addWidget(m_btnPackagesAdd); - m_btnPackagesAddOption = new QPushButton(i18n("Add Op&tion..."), frame); - m_btnPackagesAddOption->setIcon(QIcon::fromTheme("list-add")); - m_btnPackagesAddOption->setWhatsThis(i18n("Add a new package option")); - connect(m_btnPackagesAddOption, SIGNAL(clicked()), this, SLOT(slotPackageAddOption())); - hl->addWidget(m_btnPackagesAddOption); - m_btnPackagesEdit = new QPushButton(i18n("Ed&it..."), frame); - m_btnPackagesEdit->setIcon(QIcon::fromTheme("document-properties")); - m_btnPackagesEdit->setWhatsThis(i18n("Edit the current package option")); - connect(m_btnPackagesEdit, SIGNAL(clicked()), this, SLOT(slotPackageEdit())); - hl->addWidget(m_btnPackagesEdit); - m_btnPackagesDelete = new QPushButton(i18n("De&lete"), frame); - m_btnPackagesDelete->setIcon(QIcon::fromTheme("list-remove")); - m_btnPackagesDelete->setWhatsThis(i18n("Remove the current package option")); - connect(m_btnPackagesDelete, SIGNAL(clicked()), this, SLOT(slotPackageDelete())); - hl->addWidget(m_btnPackagesDelete); - m_btnPackagesReset = new QPushButton(i18n("&Reset to Defaults"), frame); - m_btnPackagesReset->setIcon(QIcon::fromTheme("document-revert")); - m_btnPackagesReset->setWhatsThis(i18n("Reset to the default list of packages")); - connect(m_btnPackagesReset, SIGNAL(clicked()), this, SLOT(slotPackageReset())); - hl->addWidget(m_btnPackagesReset); - hl->addStretch(); - - return packages; + KILE_DEBUG_MAIN << "\tsetupPackages"; + + QWidget *packages = new QWidget(tab); + QVBoxLayout *vl = new QVBoxLayout(); + packages->setLayout(vl); + + QLabel *label = new QLabel(i18n("LaTe&X packages:"), packages); + vl->addWidget(label); + m_lvPackages = new QTreeWidget(packages); + vl->addWidget(m_lvPackages); + m_lvPackages->setRootIsDecorated(true); + m_lvPackages->setHeaderLabels(QStringList() << i18n("Package") << i18n("Value") << i18n("Description")); + m_lvPackages->setAllColumnsShowFocus(true); + m_lvPackages->setItemDelegateForColumn(1, new EditableItemDelegate()); + label->setBuddy(m_lvPackages); + connect(m_lvPackages, SIGNAL(itemClicked(QTreeWidgetItem*, int)), + this, SLOT(slotCheckParent(QTreeWidgetItem*))); + connect(m_lvPackages, SIGNAL(itemChanged(QTreeWidgetItem*, int)), + this, SLOT(slotCheckParent(QTreeWidgetItem*))); + connect(m_lvPackages, SIGNAL(itemSelectionChanged()), + this, SLOT(slotEnableButtons())); + connect(m_lvPackages, SIGNAL(itemDoubleClicked(QTreeWidgetItem*, int)), + this, SLOT(slotPackageDoubleClicked(QTreeWidgetItem*))); + + QWidget *frame = new QWidget(packages); + vl->addWidget(frame); + QHBoxLayout *hl = new QHBoxLayout(); + hl->setMargin(0); + frame->setLayout(hl); + hl->addStretch(); + + m_btnPackagesAdd = new QPushButton(i18n("&Add Package..."), frame); + m_btnPackagesAdd->setIcon(QIcon::fromTheme("list-add")); + m_btnPackagesAdd->setWhatsThis(i18n("Add a new package")); + connect(m_btnPackagesAdd, SIGNAL(clicked()), this, SLOT(slotPackageAdd())); + hl->addWidget(m_btnPackagesAdd); + m_btnPackagesAddOption = new QPushButton(i18n("Add Op&tion..."), frame); + m_btnPackagesAddOption->setIcon(QIcon::fromTheme("list-add")); + m_btnPackagesAddOption->setWhatsThis(i18n("Add a new package option")); + connect(m_btnPackagesAddOption, SIGNAL(clicked()), this, SLOT(slotPackageAddOption())); + hl->addWidget(m_btnPackagesAddOption); + m_btnPackagesEdit = new QPushButton(i18n("Ed&it..."), frame); + m_btnPackagesEdit->setIcon(QIcon::fromTheme("document-properties")); + m_btnPackagesEdit->setWhatsThis(i18n("Edit the current package option")); + connect(m_btnPackagesEdit, SIGNAL(clicked()), this, SLOT(slotPackageEdit())); + hl->addWidget(m_btnPackagesEdit); + m_btnPackagesDelete = new QPushButton(i18n("De&lete"), frame); + m_btnPackagesDelete->setIcon(QIcon::fromTheme("list-remove")); + m_btnPackagesDelete->setWhatsThis(i18n("Remove the current package option")); + connect(m_btnPackagesDelete, SIGNAL(clicked()), this, SLOT(slotPackageDelete())); + hl->addWidget(m_btnPackagesDelete); + m_btnPackagesReset = new QPushButton(i18n("&Reset to Defaults"), frame); + m_btnPackagesReset->setIcon(QIcon::fromTheme("document-revert")); + m_btnPackagesReset->setWhatsThis(i18n("Reset to the default list of packages")); + connect(m_btnPackagesReset, SIGNAL(clicked()), this, SLOT(slotPackageReset())); + hl->addWidget(m_btnPackagesReset); + hl->addStretch(); + + return packages; } QWidget *QuickDocument::setupProperties(QTabWidget *tab) { - KILE_DEBUG_MAIN << "\tsetupProperties"; - QLabel *label; + KILE_DEBUG_MAIN << "\tsetupProperties"; + QLabel *label; - QWidget *personalInfoPage = new QWidget(tab); - QVBoxLayout *vl = new QVBoxLayout(); - vl->setMargin(0); - personalInfoPage->setLayout(vl); + QWidget *personalInfoPage = new QWidget(tab); + QVBoxLayout *vl = new QVBoxLayout(); + vl->setMargin(0); + personalInfoPage->setLayout(vl); - QWidget *personalInfo = new QWidget(personalInfoPage); - QGridLayout *gl = new QGridLayout(); - personalInfo->setLayout(gl); + QWidget *personalInfo = new QWidget(personalInfoPage); + QGridLayout *gl = new QGridLayout(); + personalInfo->setLayout(gl); - m_leAuthor = new QLineEdit(personalInfo); - gl->addWidget(m_leAuthor, 0, 1); - label = new QLabel(i18n("&Author:"), personalInfo); - gl->addWidget(label, 0, 0); - label->setBuddy(m_leAuthor); + m_leAuthor = new QLineEdit(personalInfo); + gl->addWidget(m_leAuthor, 0, 1); + label = new QLabel(i18n("&Author:"), personalInfo); + gl->addWidget(label, 0, 0); + label->setBuddy(m_leAuthor); - m_leTitle = new QLineEdit(personalInfo); - gl->addWidget(m_leTitle, 1, 1); - label = new QLabel(i18n("&Title:"), personalInfo); - gl->addWidget(label, 1, 0); - label->setBuddy(m_leTitle); + m_leTitle = new QLineEdit(personalInfo); + gl->addWidget(m_leTitle, 1, 1); + label = new QLabel(i18n("&Title:"), personalInfo); + gl->addWidget(label, 1, 0); + label->setBuddy(m_leTitle); - m_leDate = new QLineEdit(personalInfo); - gl->addWidget(m_leDate, 2, 1); - label = new QLabel(i18n("Dat&e:"), personalInfo); - gl->addWidget(label, 2, 0); - label->setBuddy(m_leDate); + m_leDate = new QLineEdit(personalInfo); + gl->addWidget(m_leDate, 2, 1); + label = new QLabel(i18n("Dat&e:"), personalInfo); + gl->addWidget(label, 2, 0); + label->setBuddy(m_leDate); - // set current date - m_leDate->setText(QLocale().toString(QDate::currentDate(), QLocale::ShortFormat)); + // set current date + m_leDate->setText(QLocale().toString(QDate::currentDate(), QLocale::ShortFormat)); - vl->addWidget(personalInfo); - vl->addStretch(); + vl->addWidget(personalInfo); + vl->addStretch(); - return personalInfoPage; + return personalInfoPage; } //////////////////// read configuration //////////////////// void QuickDocument::readConfig() { - KILE_DEBUG_MAIN << "==QuickDocument::readConfig()============"; + KILE_DEBUG_MAIN << "==QuickDocument::readConfig()============"; - // read config for document class - readDocumentClassConfig(); - // init the current document class - initDocumentClass(); + // read config for document class + readDocumentClassConfig(); + // init the current document class + initDocumentClass(); - // read config for packages - readPackagesConfig(); - initHyperref(); + // read config for packages + readPackagesConfig(); + initHyperref(); - // read author - m_leAuthor->setText(KileConfig::author()); + // read author + m_leAuthor->setText(KileConfig::author()); } //////////////////// write configuration //////////////////// void QuickDocument::writeConfig() { - KILE_DEBUG_MAIN << "==QuickDocument::writeConfig()============"; + KILE_DEBUG_MAIN << "==QuickDocument::writeConfig()============"; - // write document class to config file - writeDocumentClassConfig(); + // write document class to config file + writeDocumentClassConfig(); - // write packages to config file - writePackagesConfig(); + // write packages to config file + writePackagesConfig(); - // set author - KileConfig::setAuthor(m_leAuthor->text()); + // set author + KileConfig::setAuthor(m_leAuthor->text()); } ////////////////////////////// document class tab ////////////////////////////// void QuickDocument::readDocumentClassConfig() { - KILE_DEBUG_MAIN << "\tread config: document class"; - - // read standard options - m_userClasslist = KileConfig::userClasses(); - m_currentClass = KileConfig::documentClass(); - m_currentEncoding = KileConfig::encoding(); - - // init standard classes - QString stdFontsize = "10pt,11pt,12pt"; - QString stdPapersize = "a4paper,a5paper,b5paper,executivepaper,legalpaper,letterpaper"; - QString beamerThemes = "bars;boxes;classic;lined;plain;sidebar;sidebar (dark);sidebar (tab);" - "sidebar (dark,tab);shadow;split;tree;tree (bar)"; - - initStandardClass("article", stdFontsize, stdPapersize, - "10pt,letterpaper,oneside,onecolumn,final", - KileConfig::optionsArticle()); - initStandardClass("book", stdFontsize, stdPapersize, - "10pt,letterpaper,twoside,onecolumn,final,openright", - KileConfig::optionsBook()); - initStandardClass("letter", stdFontsize, stdPapersize, - "10pt,letterpaper,oneside,onecolumn,final", - KileConfig::optionsLetter()); - initStandardClass("report", stdFontsize, stdPapersize, - "10pt,letterpaper,oneside,onecolumn,final,openany", - KileConfig::optionsReport()); - initStandardClass("scrartcl", stdFontsize, stdPapersize, - "11pt,a4paper,abstractoff,bigheadings,final,headnosepline," - "footnosepline,listsindent,onelinecaption,notitlepage,onecolumn," - "oneside,openany,parindent,tablecaptionbelow,tocindent", - KileConfig::optionsScrartcl()); - initStandardClass("scrbook", stdFontsize, stdPapersize, - "11pt,a4paper,bigheadings,final,headnosepline,footnosepline," - "listsindent,nochapterprefix,onelinecaption,onecolumn," - "openright,parindent,tablecaptionbelow,titlepage,tocindent,twoside", - KileConfig::optionsScrbook()); - initStandardClass("scrreprt", stdFontsize, stdPapersize, - "11pt,a4paper,abstractoff,bigheadings,final,headnosepline," - "footnosepline,listsindent,nochapterprefix,onelinecaption,onecolumn," - "oneside,openany,parindent,tablecaptionbelow,titlepage,tocindent", - KileConfig::optionsScrreprt()); - initStandardClass("prosper", QString(), QString(), - "final,slideBW,total,nocolorBG,ps,noaccumulate,ps2pdf", - KileConfig::optionsProsper()); - initStandardClass("beamer", "8pt,9pt,10pt,11pt,12pt,14pt,17pt,20pt", beamerThemes, - "11pt,blue,notes=show,sans,slidescentered", - KileConfig::optionsBeamer()); - - // init all user classes - for (int i = 0; i < m_userClasslist.count(); ++i) { - KILE_DEBUG_MAIN << "\tinit user class: " << m_userClasslist[i]; - QStringList list; - // read dour default entries for this user class - KConfigGroup configGroup = config()->group(QString("QuickDocument/") + m_userClasslist[i]); - list.append(configGroup.readEntry("fontsizesList")); - list.append(configGroup.readEntry("pagesizesList")); - list.append(configGroup.readEntry("defaultOptions")); - list.append(configGroup.readEntry("selectedOptions")); - // now read all user-defined options - QStringList options = (configGroup.readEntry("options")).split(','); - for (int j = 0; j < options.count(); ++j) { - list.append(options[j] + " => " + configGroup.readEntry(options[j])); - } - - // save all information of this class into the documentClass-dictionary - m_dictDocumentClasses[ m_userClasslist[i] ] = list; - } - - // set classes combobox (standard and user-defined classes) - fillDocumentClassCombobox(); - - // set encoding combobox - fillCombobox(m_cbEncoding, - "ansinew,applemac,ascii,cp1252,cp1250,cp1251,cp1257,cp437,cp437de,cp850,cp858," - "cp852,cp865,decmulti,koi8-r,latin1,latin2,latin3,latin4,latin5,latin9,latin10,next,utf8,utf8x,utfcyr", - m_currentEncoding); + KILE_DEBUG_MAIN << "\tread config: document class"; + + // read standard options + m_userClasslist = KileConfig::userClasses(); + m_currentClass = KileConfig::documentClass(); + m_currentEncoding = KileConfig::encoding(); + + // init standard classes + QString stdFontsize = "10pt,11pt,12pt"; + QString stdPapersize = "a4paper,a5paper,b5paper,executivepaper,legalpaper,letterpaper"; + QString beamerThemes = "bars;boxes;classic;lined;plain;sidebar;sidebar (dark);sidebar (tab);" + "sidebar (dark,tab);shadow;split;tree;tree (bar)"; + + initStandardClass("article", stdFontsize, stdPapersize, + "10pt,letterpaper,oneside,onecolumn,final", + KileConfig::optionsArticle()); + initStandardClass("book", stdFontsize, stdPapersize, + "10pt,letterpaper,twoside,onecolumn,final,openright", + KileConfig::optionsBook()); + initStandardClass("letter", stdFontsize, stdPapersize, + "10pt,letterpaper,oneside,onecolumn,final", + KileConfig::optionsLetter()); + initStandardClass("report", stdFontsize, stdPapersize, + "10pt,letterpaper,oneside,onecolumn,final,openany", + KileConfig::optionsReport()); + initStandardClass("scrartcl", stdFontsize, stdPapersize, + "11pt,a4paper,abstractoff,bigheadings,final,headnosepline," + "footnosepline,listsindent,onelinecaption,notitlepage,onecolumn," + "oneside,openany,parindent,tablecaptionbelow,tocindent", + KileConfig::optionsScrartcl()); + initStandardClass("scrbook", stdFontsize, stdPapersize, + "11pt,a4paper,bigheadings,final,headnosepline,footnosepline," + "listsindent,nochapterprefix,onelinecaption,onecolumn," + "openright,parindent,tablecaptionbelow,titlepage,tocindent,twoside", + KileConfig::optionsScrbook()); + initStandardClass("scrreprt", stdFontsize, stdPapersize, + "11pt,a4paper,abstractoff,bigheadings,final,headnosepline," + "footnosepline,listsindent,nochapterprefix,onelinecaption,onecolumn," + "oneside,openany,parindent,tablecaptionbelow,titlepage,tocindent", + KileConfig::optionsScrreprt()); + initStandardClass("prosper", QString(), QString(), + "final,slideBW,total,nocolorBG,ps,noaccumulate,ps2pdf", + KileConfig::optionsProsper()); + initStandardClass("beamer", "8pt,9pt,10pt,11pt,12pt,14pt,17pt,20pt", beamerThemes, + "11pt,blue,notes=show,sans,slidescentered", + KileConfig::optionsBeamer()); + + // init all user classes + for (int i = 0; i < m_userClasslist.count(); ++i) { + KILE_DEBUG_MAIN << "\tinit user class: " << m_userClasslist[i]; + QStringList list; + // read dour default entries for this user class + KConfigGroup configGroup = config()->group(QString("QuickDocument/") + m_userClasslist[i]); + list.append(configGroup.readEntry("fontsizesList")); + list.append(configGroup.readEntry("pagesizesList")); + list.append(configGroup.readEntry("defaultOptions")); + list.append(configGroup.readEntry("selectedOptions")); + // now read all user-defined options + QStringList options = (configGroup.readEntry("options")).split(','); + for (int j = 0; j < options.count(); ++j) { + list.append(options[j] + " => " + configGroup.readEntry(options[j])); + } + + // save all information of this class into the documentClass-dictionary + m_dictDocumentClasses[ m_userClasslist[i] ] = list; + } + + // set classes combobox (standard and user-defined classes) + fillDocumentClassCombobox(); + + // set encoding combobox + fillCombobox(m_cbEncoding, + "ansinew,applemac,ascii,cp1252,cp1250,cp1251,cp1257,cp437,cp437de,cp850,cp858," + "cp852,cp865,decmulti,koi8-r,latin1,latin2,latin3,latin4,latin5,latin9,latin10,next,utf8,utf8x,utfcyr", + m_currentEncoding); } void QuickDocument::fillDocumentClassCombobox() { - QString stdClasses = "article,book,letter,report,-,scrartcl,scrbook,scrreprt,-"; - QString stdUserClasses = "beamer,prosper"; + QString stdClasses = "article,book,letter,report,-,scrartcl,scrbook,scrreprt,-"; + QString stdUserClasses = "beamer,prosper"; - // set classes combobox (standard and user-defined classes) - QStringList classlist = stdUserClasses.split(','); - for (int i = 0; i < m_userClasslist.count(); ++i) { - classlist.append(m_userClasslist[i]); - } - classlist.sort(); - fillCombobox(m_cbDocumentClass, stdClasses + ',' + classlist.join(","), m_currentClass); + // set classes combobox (standard and user-defined classes) + QStringList classlist = stdUserClasses.split(','); + for (int i = 0; i < m_userClasslist.count(); ++i) { + classlist.append(m_userClasslist[i]); + } + classlist.sort(); + fillCombobox(m_cbDocumentClass, stdClasses + ',' + classlist.join(","), m_currentClass); } void QuickDocument::writeDocumentClassConfig() { - KILE_DEBUG_MAIN << "\twrite config: document class"; - - // first delete all marked document classes - for (int i = 0; i < m_deleteDocumentClasses.count(); ++i) { - KILE_DEBUG_MAIN << "\tdelete class: " << m_deleteDocumentClasses[i]; - config()->deleteGroup(QString("QuickDocument/") + m_deleteDocumentClasses[i]); - } - - // write document classes and encoding - QStringList userclasses; - for (int i = 0; i < m_cbDocumentClass->count(); ++i) { - if (!m_cbDocumentClass->itemText(i).isEmpty() && !isStandardClass(m_cbDocumentClass->itemText(i))) { - userclasses.append(m_cbDocumentClass->itemText(i)); - } - } - KileConfig::setUserClasses(userclasses); - KileConfig::setDocumentClass(m_cbDocumentClass->currentText()); - KileConfig::setEncoding(m_cbEncoding->currentText()); - - // write checked options of standard classes - KILE_DEBUG_MAIN << "\twrite standard classes"; - KileConfig::setOptionsArticle(m_dictDocumentClasses["article"][qd_SelectedOptions]); - KileConfig::setOptionsBook(m_dictDocumentClasses["book"][qd_SelectedOptions]); - KileConfig::setOptionsLetter(m_dictDocumentClasses["letter"][qd_SelectedOptions]); - KileConfig::setOptionsReport(m_dictDocumentClasses["report"][qd_SelectedOptions]); - KileConfig::setOptionsScrartcl(m_dictDocumentClasses["scrartcl"][qd_SelectedOptions]); - KileConfig::setOptionsScrbook(m_dictDocumentClasses["scrbook"][qd_SelectedOptions]); - KileConfig::setOptionsScrreprt(m_dictDocumentClasses["scrreprt"][qd_SelectedOptions]); - KileConfig::setOptionsProsper(m_dictDocumentClasses["prosper"][qd_SelectedOptions]); - KileConfig::setOptionsBeamer(m_dictDocumentClasses["beamer"][qd_SelectedOptions]); - - // write config of user packages - QRegExp reg("(\\S+)\\s+=>\\s+(.*)"); - for (int i = 0; i < userclasses.count(); ++i) { - // get the stringlist with all information - KILE_DEBUG_MAIN << "\twrite user class: " << userclasses[i]; - QStringList list = m_dictDocumentClasses[userclasses[i]]; - - // write the config group and the default entries - KConfigGroup configGroup = config()->group(QString("QuickDocument/") + userclasses[i]); - configGroup.writeEntry("fontsizesList", list[qd_Fontsizes]); - configGroup.writeEntry("pagesizesList", list[qd_Papersizes]); - configGroup.writeEntry("defaultOptions", list[qd_DefaultOptions]); - configGroup.writeEntry("selectedOptions", list[qd_SelectedOptions]); - - // write user-defined options - QString options; - for (int j = qd_OptionsStart; j < list.count(); ++j) { - int pos = reg.indexIn(list[j]); - if (pos != -1) { - configGroup.writeEntry(reg.cap(1), reg.cap(2)); - if (!options.isEmpty()) { - options += ','; - } - options += reg.cap(1); - } - } - configGroup.writeEntry("options", options); - } + KILE_DEBUG_MAIN << "\twrite config: document class"; + + // first delete all marked document classes + for (int i = 0; i < m_deleteDocumentClasses.count(); ++i) { + KILE_DEBUG_MAIN << "\tdelete class: " << m_deleteDocumentClasses[i]; + config()->deleteGroup(QString("QuickDocument/") + m_deleteDocumentClasses[i]); + } + + // write document classes and encoding + QStringList userclasses; + for (int i = 0; i < m_cbDocumentClass->count(); ++i) { + if (!m_cbDocumentClass->itemText(i).isEmpty() && !isStandardClass(m_cbDocumentClass->itemText(i))) { + userclasses.append(m_cbDocumentClass->itemText(i)); + } + } + KileConfig::setUserClasses(userclasses); + KileConfig::setDocumentClass(m_cbDocumentClass->currentText()); + KileConfig::setEncoding(m_cbEncoding->currentText()); + + // write checked options of standard classes + KILE_DEBUG_MAIN << "\twrite standard classes"; + KileConfig::setOptionsArticle(m_dictDocumentClasses["article"][qd_SelectedOptions]); + KileConfig::setOptionsBook(m_dictDocumentClasses["book"][qd_SelectedOptions]); + KileConfig::setOptionsLetter(m_dictDocumentClasses["letter"][qd_SelectedOptions]); + KileConfig::setOptionsReport(m_dictDocumentClasses["report"][qd_SelectedOptions]); + KileConfig::setOptionsScrartcl(m_dictDocumentClasses["scrartcl"][qd_SelectedOptions]); + KileConfig::setOptionsScrbook(m_dictDocumentClasses["scrbook"][qd_SelectedOptions]); + KileConfig::setOptionsScrreprt(m_dictDocumentClasses["scrreprt"][qd_SelectedOptions]); + KileConfig::setOptionsProsper(m_dictDocumentClasses["prosper"][qd_SelectedOptions]); + KileConfig::setOptionsBeamer(m_dictDocumentClasses["beamer"][qd_SelectedOptions]); + + // write config of user packages + QRegExp reg("(\\S+)\\s+=>\\s+(.*)"); + for (int i = 0; i < userclasses.count(); ++i) { + // get the stringlist with all information + KILE_DEBUG_MAIN << "\twrite user class: " << userclasses[i]; + QStringList list = m_dictDocumentClasses[userclasses[i]]; + + // write the config group and the default entries + KConfigGroup configGroup = config()->group(QString("QuickDocument/") + userclasses[i]); + configGroup.writeEntry("fontsizesList", list[qd_Fontsizes]); + configGroup.writeEntry("pagesizesList", list[qd_Papersizes]); + configGroup.writeEntry("defaultOptions", list[qd_DefaultOptions]); + configGroup.writeEntry("selectedOptions", list[qd_SelectedOptions]); + + // write user-defined options + QString options; + for (int j = qd_OptionsStart; j < list.count(); ++j) { + int pos = reg.indexIn(list[j]); + if (pos != -1) { + configGroup.writeEntry(reg.cap(1), reg.cap(2)); + if (!options.isEmpty()) { + options += ','; + } + options += reg.cap(1); + } + } + configGroup.writeEntry("options", options); + } } void QuickDocument::initDocumentClass() { - KILE_DEBUG_MAIN << "==QuickDocument::initDocumentClass()============"; - KILE_DEBUG_MAIN << "\tset class: " << m_currentClass; + KILE_DEBUG_MAIN << "==QuickDocument::initDocumentClass()============"; + KILE_DEBUG_MAIN << "\tset class: " << m_currentClass; - // get the stringlist of this class with all information - QStringList classlist = m_dictDocumentClasses[m_currentClass]; + // get the stringlist of this class with all information + QStringList classlist = m_dictDocumentClasses[m_currentClass]; - // First of all, we have to set the defaultOptions-dictionary and the - // selectedOptions-dictionary for this class, before inserting options - // into the listview. The function setClassOptions() will look - // into both dictionaries to do some extra work. - setDefaultClassOptions(classlist[qd_DefaultOptions]); - setSelectedClassOptions(classlist[qd_SelectedOptions]); + // First of all, we have to set the defaultOptions-dictionary and the + // selectedOptions-dictionary for this class, before inserting options + // into the listview. The function setClassOptions() will look + // into both dictionaries to do some extra work. + setDefaultClassOptions(classlist[qd_DefaultOptions]); + setSelectedClassOptions(classlist[qd_SelectedOptions]); - // set comboboxes for fontsizes and papersizes - fillCombobox(m_cbTypefaceSize, classlist[qd_Fontsizes], m_currentFontsize); - fillCombobox(m_cbPaperSize, classlist[qd_Papersizes], m_currentPapersize); + // set comboboxes for fontsizes and papersizes + fillCombobox(m_cbTypefaceSize, classlist[qd_Fontsizes], m_currentFontsize); + fillCombobox(m_cbPaperSize, classlist[qd_Papersizes], m_currentPapersize); - // now we are ready to set the class options - if (isStandardClass(m_currentClass)) { - QStringList optionlist; - initStandardOptions(m_currentClass, optionlist); - setClassOptions(optionlist, 0); - } else { - setClassOptions(classlist, qd_OptionsStart); - } + // now we are ready to set the class options + if (isStandardClass(m_currentClass)) { + QStringList optionlist; + initStandardOptions(m_currentClass, optionlist); + setClassOptions(optionlist, 0); + } else { + setClassOptions(classlist, qd_OptionsStart); + } - // there is no papersize with class beamer, but a theme - if (m_currentClass == "beamer") - m_lbPaperSize->setText(i18n("&Theme:")); - else - m_lbPaperSize->setText(i18n("Paper si&ze:")); + // there is no papersize with class beamer, but a theme + if (m_currentClass == "beamer") + m_lbPaperSize->setText(i18n("&Theme:")); + else + m_lbPaperSize->setText(i18n("Paper si&ze:")); - // enable/disable buttons to add or delete entries - slotEnableButtons(); + // enable/disable buttons to add or delete entries + slotEnableButtons(); } void QuickDocument::initStandardClass(const QString &classname, const QString &fontsize, const QString &papersize, const QString &defaultoptions, const QString &selectedoptions) { - KILE_DEBUG_MAIN << "\tinit standard class: " << classname; + KILE_DEBUG_MAIN << "\tinit standard class: " << classname; - // remember that this is a standard class - m_dictStandardClasses[ classname ] = true; + // remember that this is a standard class + m_dictStandardClasses[ classname ] = true; - // save all entries - QStringList list; - list << fontsize << papersize << defaultoptions << selectedoptions; + // save all entries + QStringList list; + list << fontsize << papersize << defaultoptions << selectedoptions; - // save in documentClass-dictionary - m_dictDocumentClasses[ classname ] = list; + // save in documentClass-dictionary + m_dictDocumentClasses[ classname ] = list; } // build all option for the current standard class void QuickDocument::initStandardOptions(const QString &classname, QStringList &optionlist) { - // build the bitcode for all options of this class - int options; - if (classname == "article") - options = qd_Base + qd_Article; - else - if (classname == "book") - options = qd_Base + qd_Article + qd_BookReport; - else - if (classname == "letter") - options = qd_Base; - else - if (classname == "report") - options = qd_Base + qd_Article + qd_BookReport; - else - if (classname == "scrartcl") - options = qd_Base + qd_Article + qd_KomaArticle + qd_KomaAbstract; - else - if (classname == "scrbook") - options = qd_Base + qd_Article + qd_BookReport + qd_KomaArticle + qd_KomaBookReport; - else - if (classname == "scrreprt") - options = qd_Base + qd_Article + qd_BookReport + qd_KomaArticle + qd_KomaAbstract + qd_KomaBookReport; - else - if (classname == "prosper") - options = qd_Prosper; - else - if (classname == "beamer") - options = qd_Beamer; - else - return; - - // insert all options into the list - if (options & qd_Base) { - optionlist - << QString("landscape => ") + i18n("Sets the document's orientation to landscape") - << QString("oneside => ") + i18n("Margins are set for single side output") - << QString("twoside => ") + i18n("Left and right pages differ in page margins") - << QString("draft => ") + i18n("Marks \"overfull hboxes\" on the output with black boxes") - << QString("final => ") + i18n("No special marks for \"overfull hboxes\" on the output") - << QString("leqno => ") + i18n("Puts formula numbers on the left side") - << QString("fleqn => ") + i18n("Aligns formulas on the left side") - ; - } - - if (options & qd_Article) { - optionlist - << QString("titlepage => ") + i18n("Puts title and abstract on an extra page") - << QString("notitlepage => ") + i18n("Puts title and abstract on the same page as the text") - << QString("onecolumn => ") + i18n("Puts the text in one column") - << QString("twocolumn => ") + i18n("Puts the text in two columns") - << QString("openbib => ") + i18n("Formats the bibliography in open style") - ; - } - - if (options & qd_BookReport) { - optionlist - << QString("openany => ") + i18n("Chapters may start on top of every page") - << QString("openright => ") + i18n("Chapters may only start on top of right pages") - ; - } - - if (options & qd_KomaArticle) { - optionlist - << QString("headinclude => ") + i18n("Cause the header to be counted as text") - << QString("headexclude => ") + i18n("Cause the header to be counted as border") - << QString("footinclude => ") + i18n("Cause the footer to be counted as text") - << QString("footexclude => ") + i18n("Cause the footer to be counted as border") - << QString("mpinclude => ") + i18n("Cause the margin-note to be counted to the text body") - << QString("mpexclude => ") + i18n("The normal margin is used for the margin-note area") - << QString("dvips => ") + i18n("Writes the paper size as a special into the DVI-file") - << QString("pdftex => ") + i18n("Writes the paper size into the pdftex page register") - << QString("pagesize => ") + i18n("Uses the correct mechanism with PDF- or DVI-file") - << QString("cleardoubleempty => ") + i18n("Enables the default for an empty left page") - << QString("cleardoubleplain => ") + i18n("An empty left page will set with the plain-pagestyle") - << QString("cleardoublestandard => ") + i18n("An empty left page will set with the empty-pagestyle") - << QString("headsepline => ") + i18n("Use a line to separate the header from the text body") - << QString("headnosepline => ") + i18n("Use no line to separate the header from the text body") - << QString("footsepline => ") + i18n("Use a line to separate the footer from the text body") - << QString("footnosepline => ") + i18n("Use no line to separate the footer from the text body") - << QString("parskip => ") + i18n("Normal paragraph spacing of one line") - << QString("parskip- => ") + i18n("Normal spacing, at least 1/3 of the last line is free") - << QString("parskip+ => ") + i18n("Normal spacing, at least 1/4 of the last line is free") - << QString("parskip* => ") + i18n("Normal spacing, no special provision for the last line") - << QString("halfparskip => ") + i18n("Paragraph spacing of half a line") - << QString("halfparskip- => ") + i18n("Spacing 1/2 line, at least 1/3 of the last line is free") - << QString("halfparskip+ => ") + i18n("Spacing 1/2 line, at least 1/4 of the last line is free") - << QString("halfparskip* => ") + i18n("Spacing 1/2 line, no special provision for the last line") - << QString("parindent => ") + i18n("No spacing between paragraphs, indent the first line by 1 em") - << QString("onelinecaption => ") + i18n("One-line captions are centered, multi-line left-justified") - << QString("noonelinecaption => ") + i18n("No special handling of one-line captions") - << QString("bigheading => ") + i18n("Normal great title font sizes") - << QString("normalheadings => ") + i18n("Small font sizes for titles") - << QString("smallheadings => ") + i18n("Even smaller font sizes for titles") - << QString("liststotoc => ") + i18n("Include lists of figures and tables in the TOC") - << QString("bibtotoc => ") + i18n("Include the bibliography in the TOC") - << QString("idxtotoc => ") + i18n("Include the index in the TOC") - << QString("liststotocnumbered => ") + i18n("Number the lists of figures and tables in the TOC") - << QString("bibtotocnumbered => ") + i18n("Number the bibliography in the TOC") - << QString("tocleft => ") + i18n("All numbers and titles are set in a left-justified column") - << QString("tocindent => ") + i18n("Different sectional units have different indentations") - << QString("listsleft => ") + i18n("All numbers and captions are set in a left-justified column") - << QString("listsindent => ") + i18n("All Numbers uses a fixed space") - << QString("pointednumbers => ") + i18n("Numbering of sectional units have a point at the end") - << QString("pointlessnumbers => ") + i18n("Numbering of sectional units have no point at the end") - << QString("tablecaptionabove => ") + i18n("Caption command acts like \\captionabove") - << QString("tablecaptionbelow => ") + i18n("Caption command acts like \\captionbelow") - << QString("origlongtable => ") + i18n("Captions of the longtable package should not be redefined") - ; - } - - if (options & qd_KomaBookReport) { - optionlist - << QString("chapterprefix => ") + i18n("Use a separate line for the chapter number") - << QString("nochapterprefix => ") + i18n("Use the same line for the chapter number and title") - << QString("appendixprefix => ") + i18n("Use a separate line for the appendix name") - << QString("noappendixprefix => ") + i18n("No separate line for the appendix name") - ; - } - - if (options & qd_KomaAbstract) { - optionlist - << QString("abstracton => ") + i18n("Include the abstract's title") - << QString("abstractoff => ") + i18n("Exclude the abstract's title") - ; - } - - if (options & qd_Prosper) { - optionlist - << QString("draft => ") + i18n("The file is compiled in draft mode") - << QString("final => ") + i18n("The file is compiled in final mode") - << QString("slideColor => ") + i18n("Slides will use many colors") - << QString("slideBW => ") + i18n("Slides will use a restricted set of colors") - << QString("total => ") + i18n("Display the number of the current slide and the total number") - << QString("nototal => ") + i18n("Display only the number of the current slide") - << QString("nocolorBG => ") + i18n("The background of the slide is always white") - << QString("colorBG => ") + i18n("The color of the background depends on the current style") - << QString("ps => ") + i18n("The LaTeX file is compiled to produce a PostScript file") - << QString("pdf => ") + i18n("The LaTeX file is compiled to produce a PDF file") - << QString("accumulate => ") + i18n("Some macros interpret their argument in ps mode") - << QString("noaccumulate => ") + i18n("Some macros do not interpret their argument in ps mode") - << QString("distiller => ") + i18n("The PS file is to be translated into a PDF file using Adobe Distiller") - << QString("YandY => ") + i18n("The LaTeX file is to be processed with YandY LaTeX") - << QString("ps2pdf => ") + i18n("The PS file is to be translated into a PDF file using ps2pdf") - << QString("vtex => ") + i18n("The LaTeX file is to be processed with MicroPress VTeX") - << QString("noFooter => ") + i18n("Do not add any caption at the bottom of the slides") - ; - } - - if (options & qd_Beamer) { - optionlist - << QString("slidestop => ") + i18n("Place text of slides at the (vertical) top of the slides") - << QString("slidescentered => ") + i18n("Place text of slides at the (vertical) center of the slides") - << QString("draft => ") + i18n("Headlines, footlines, and sidebars are replaced by gray rectangles") - << QString("compress => ") + i18n("Make all navigation bars as small as possible") - << QString("usepdftitle=false => ") + i18n("Suppresses generation of some entries in the pdf information") - << QString("notheorems => ") + i18n("Switches off the definition of default blocks like theorem") - << QString("noamsthm => ") + i18n("Does not load amsthm and amsmath") - << QString("CJK => ") + i18n("Needed when using the CJK package for Asian fonts") - << QString("sans => ") + i18n("Use a sans-serif font during the presentation") - << QString("serif => ") + i18n("Use a serif font during the presentation") - << QString("mathsans => ") + i18n("Override the math font to be a sans-serif font") - << QString("mathserif => ") + i18n("Override the math font to be a serif font") - << QString("professionalfont => ") + i18n("Deactivate internal font replacements for math text") - << QString("handout => ") + i18n("Create a PDF handout") - << QString("trans => ") + i18n("For PDF transparency") - << QString("blue => ") + i18n("All structure elements are typeset in blue") - << QString("red => ") + i18n("All structure elements are typeset in red") - << QString("blackandwhite => ") + i18n("All structure elements are typeset in black and white") - << QString("brown => ") + i18n("All structure elements are typeset in brown") - << QString("notes=hide => ") + i18n(" Notes are not shown") - << QString("notes=show => ") + i18n(" Include notes in the output file") - << QString("notes=only => ") + i18n(" Include only notes and suppress frames") - ; - } + // build the bitcode for all options of this class + int options; + if (classname == "article") + options = qd_Base + qd_Article; + else if (classname == "book") + options = qd_Base + qd_Article + qd_BookReport; + else if (classname == "letter") + options = qd_Base; + else if (classname == "report") + options = qd_Base + qd_Article + qd_BookReport; + else if (classname == "scrartcl") + options = qd_Base + qd_Article + qd_KomaArticle + qd_KomaAbstract; + else if (classname == "scrbook") + options = qd_Base + qd_Article + qd_BookReport + qd_KomaArticle + qd_KomaBookReport; + else if (classname == "scrreprt") + options = qd_Base + qd_Article + qd_BookReport + qd_KomaArticle + qd_KomaAbstract + qd_KomaBookReport; + else if (classname == "prosper") + options = qd_Prosper; + else if (classname == "beamer") + options = qd_Beamer; + else + return; + + // insert all options into the list + if (options & qd_Base) { + optionlist + << QString("landscape => ") + i18n("Sets the document's orientation to landscape") + << QString("oneside => ") + i18n("Margins are set for single side output") + << QString("twoside => ") + i18n("Left and right pages differ in page margins") + << QString("draft => ") + i18n("Marks \"overfull hboxes\" on the output with black boxes") + << QString("final => ") + i18n("No special marks for \"overfull hboxes\" on the output") + << QString("leqno => ") + i18n("Puts formula numbers on the left side") + << QString("fleqn => ") + i18n("Aligns formulas on the left side") + ; + } + + if (options & qd_Article) { + optionlist + << QString("titlepage => ") + i18n("Puts title and abstract on an extra page") + << QString("notitlepage => ") + i18n("Puts title and abstract on the same page as the text") + << QString("onecolumn => ") + i18n("Puts the text in one column") + << QString("twocolumn => ") + i18n("Puts the text in two columns") + << QString("openbib => ") + i18n("Formats the bibliography in open style") + ; + } + + if (options & qd_BookReport) { + optionlist + << QString("openany => ") + i18n("Chapters may start on top of every page") + << QString("openright => ") + i18n("Chapters may only start on top of right pages") + ; + } + + if (options & qd_KomaArticle) { + optionlist + << QString("headinclude => ") + i18n("Cause the header to be counted as text") + << QString("headexclude => ") + i18n("Cause the header to be counted as border") + << QString("footinclude => ") + i18n("Cause the footer to be counted as text") + << QString("footexclude => ") + i18n("Cause the footer to be counted as border") + << QString("mpinclude => ") + i18n("Cause the margin-note to be counted to the text body") + << QString("mpexclude => ") + i18n("The normal margin is used for the margin-note area") + << QString("dvips => ") + i18n("Writes the paper size as a special into the DVI-file") + << QString("pdftex => ") + i18n("Writes the paper size into the pdftex page register") + << QString("pagesize => ") + i18n("Uses the correct mechanism with PDF- or DVI-file") + << QString("cleardoubleempty => ") + i18n("Enables the default for an empty left page") + << QString("cleardoubleplain => ") + i18n("An empty left page will set with the plain-pagestyle") + << QString("cleardoublestandard => ") + i18n("An empty left page will set with the empty-pagestyle") + << QString("headsepline => ") + i18n("Use a line to separate the header from the text body") + << QString("headnosepline => ") + i18n("Use no line to separate the header from the text body") + << QString("footsepline => ") + i18n("Use a line to separate the footer from the text body") + << QString("footnosepline => ") + i18n("Use no line to separate the footer from the text body") + << QString("parskip => ") + i18n("Normal paragraph spacing of one line") + << QString("parskip- => ") + i18n("Normal spacing, at least 1/3 of the last line is free") + << QString("parskip+ => ") + i18n("Normal spacing, at least 1/4 of the last line is free") + << QString("parskip* => ") + i18n("Normal spacing, no special provision for the last line") + << QString("halfparskip => ") + i18n("Paragraph spacing of half a line") + << QString("halfparskip- => ") + i18n("Spacing 1/2 line, at least 1/3 of the last line is free") + << QString("halfparskip+ => ") + i18n("Spacing 1/2 line, at least 1/4 of the last line is free") + << QString("halfparskip* => ") + i18n("Spacing 1/2 line, no special provision for the last line") + << QString("parindent => ") + i18n("No spacing between paragraphs, indent the first line by 1 em") + << QString("onelinecaption => ") + i18n("One-line captions are centered, multi-line left-justified") + << QString("noonelinecaption => ") + i18n("No special handling of one-line captions") + << QString("bigheading => ") + i18n("Normal great title font sizes") + << QString("normalheadings => ") + i18n("Small font sizes for titles") + << QString("smallheadings => ") + i18n("Even smaller font sizes for titles") + << QString("liststotoc => ") + i18n("Include lists of figures and tables in the TOC") + << QString("bibtotoc => ") + i18n("Include the bibliography in the TOC") + << QString("idxtotoc => ") + i18n("Include the index in the TOC") + << QString("liststotocnumbered => ") + i18n("Number the lists of figures and tables in the TOC") + << QString("bibtotocnumbered => ") + i18n("Number the bibliography in the TOC") + << QString("tocleft => ") + i18n("All numbers and titles are set in a left-justified column") + << QString("tocindent => ") + i18n("Different sectional units have different indentations") + << QString("listsleft => ") + i18n("All numbers and captions are set in a left-justified column") + << QString("listsindent => ") + i18n("All Numbers uses a fixed space") + << QString("pointednumbers => ") + i18n("Numbering of sectional units have a point at the end") + << QString("pointlessnumbers => ") + i18n("Numbering of sectional units have no point at the end") + << QString("tablecaptionabove => ") + i18n("Caption command acts like \\captionabove") + << QString("tablecaptionbelow => ") + i18n("Caption command acts like \\captionbelow") + << QString("origlongtable => ") + i18n("Captions of the longtable package should not be redefined") + ; + } + + if (options & qd_KomaBookReport) { + optionlist + << QString("chapterprefix => ") + i18n("Use a separate line for the chapter number") + << QString("nochapterprefix => ") + i18n("Use the same line for the chapter number and title") + << QString("appendixprefix => ") + i18n("Use a separate line for the appendix name") + << QString("noappendixprefix => ") + i18n("No separate line for the appendix name") + ; + } + + if (options & qd_KomaAbstract) { + optionlist + << QString("abstracton => ") + i18n("Include the abstract's title") + << QString("abstractoff => ") + i18n("Exclude the abstract's title") + ; + } + + if (options & qd_Prosper) { + optionlist + << QString("draft => ") + i18n("The file is compiled in draft mode") + << QString("final => ") + i18n("The file is compiled in final mode") + << QString("slideColor => ") + i18n("Slides will use many colors") + << QString("slideBW => ") + i18n("Slides will use a restricted set of colors") + << QString("total => ") + i18n("Display the number of the current slide and the total number") + << QString("nototal => ") + i18n("Display only the number of the current slide") + << QString("nocolorBG => ") + i18n("The background of the slide is always white") + << QString("colorBG => ") + i18n("The color of the background depends on the current style") + << QString("ps => ") + i18n("The LaTeX file is compiled to produce a PostScript file") + << QString("pdf => ") + i18n("The LaTeX file is compiled to produce a PDF file") + << QString("accumulate => ") + i18n("Some macros interpret their argument in ps mode") + << QString("noaccumulate => ") + i18n("Some macros do not interpret their argument in ps mode") + << QString("distiller => ") + i18n("The PS file is to be translated into a PDF file using Adobe Distiller") + << QString("YandY => ") + i18n("The LaTeX file is to be processed with YandY LaTeX") + << QString("ps2pdf => ") + i18n("The PS file is to be translated into a PDF file using ps2pdf") + << QString("vtex => ") + i18n("The LaTeX file is to be processed with MicroPress VTeX") + << QString("noFooter => ") + i18n("Do not add any caption at the bottom of the slides") + ; + } + + if (options & qd_Beamer) { + optionlist + << QString("slidestop => ") + i18n("Place text of slides at the (vertical) top of the slides") + << QString("slidescentered => ") + i18n("Place text of slides at the (vertical) center of the slides") + << QString("draft => ") + i18n("Headlines, footlines, and sidebars are replaced by gray rectangles") + << QString("compress => ") + i18n("Make all navigation bars as small as possible") + << QString("usepdftitle=false => ") + i18n("Suppresses generation of some entries in the pdf information") + << QString("notheorems => ") + i18n("Switches off the definition of default blocks like theorem") + << QString("noamsthm => ") + i18n("Does not load amsthm and amsmath") + << QString("CJK => ") + i18n("Needed when using the CJK package for Asian fonts") + << QString("sans => ") + i18n("Use a sans-serif font during the presentation") + << QString("serif => ") + i18n("Use a serif font during the presentation") + << QString("mathsans => ") + i18n("Override the math font to be a sans-serif font") + << QString("mathserif => ") + i18n("Override the math font to be a serif font") + << QString("professionalfont => ") + i18n("Deactivate internal font replacements for math text") + << QString("handout => ") + i18n("Create a PDF handout") + << QString("trans => ") + i18n("For PDF transparency") + << QString("blue => ") + i18n("All structure elements are typeset in blue") + << QString("red => ") + i18n("All structure elements are typeset in red") + << QString("blackandwhite => ") + i18n("All structure elements are typeset in black and white") + << QString("brown => ") + i18n("All structure elements are typeset in brown") + << QString("notes=hide => ") + i18n(" Notes are not shown") + << QString("notes=show => ") + i18n(" Include notes in the output file") + << QString("notes=only => ") + i18n(" Include only notes and suppress frames") + ; + } } // check for a standard class bool QuickDocument::isStandardClass(const QString &classname) { - return m_dictStandardClasses.contains(classname); + return m_dictStandardClasses.contains(classname); } // check for a default option bool QuickDocument::isDefaultClassOption(const QString &option) { - return m_currentDefaultOptions.contains(option); + return m_currentDefaultOptions.contains(option); } // check for an user option bool QuickDocument::isSelectedClassOption(const QString &option) { - return m_currentSelectedOptions.contains(option); + return m_currentSelectedOptions.contains(option); } // insert all default options of the current class into the defaultOptions-dictionary void QuickDocument::setDefaultClassOptions(const QString &defaultoptions) { - QStringList list = defaultoptions.split(','); - m_currentDefaultOptions.clear(); - for (int i = 0; i < list.count(); ++i) { - if (!list[i].isEmpty()) { - m_currentDefaultOptions[list[i]] = true; - } - } + QStringList list = defaultoptions.split(','); + m_currentDefaultOptions.clear(); + for (int i = 0; i < list.count(); ++i) { + if (!list[i].isEmpty()) { + m_currentDefaultOptions[list[i]] = true; + } + } } // insert all checked options of the current class into the selectedOptions-dictionary void QuickDocument::setSelectedClassOptions(const QString &selectedoptions) { - KILE_DEBUG_MAIN << "\tset options: " << selectedoptions; + KILE_DEBUG_MAIN << "\tset options: " << selectedoptions; - QStringList list = selectedoptions.split(','); - uint nlist = list.count(); + QStringList list = selectedoptions.split(','); + uint nlist = list.count(); - m_currentFontsize = (nlist >= 1) ? list[0] : ""; - m_currentPapersize = (nlist >= 2) ? list[1] : ""; + m_currentFontsize = (nlist >= 1) ? list[0] : ""; + m_currentPapersize = (nlist >= 2) ? list[1] : ""; - m_currentSelectedOptions.clear(); - for (uint i = 0; i < nlist; ++i) { - if (! list[i].isEmpty()) - m_currentSelectedOptions[ list[i] ] = true; - } + m_currentSelectedOptions.clear(); + for (uint i = 0; i < nlist; ++i) { + if (! list[i].isEmpty()) + m_currentSelectedOptions[ list[i] ] = true; + } } // show all options of the current class // - split this string into option and description (option => description) // - if the option is in the defaultOptions-dictionary, add 'default' // - if the option is in the selectedOptions-dictionary, set the 'checked' symbol void QuickDocument::setClassOptions(const QStringList &list, uint start) { - QRegExp reg("(\\S+)\\s+=>\\s+(.*)"); + QRegExp reg("(\\S+)\\s+=>\\s+(.*)"); - m_lvClassOptions->clear(); - for (int i = start; i < list.count(); ++i) { - int pos = reg.indexIn(list[i]); - if (pos != -1) { - QTreeWidgetItem *twi = new QTreeWidgetItem(m_lvClassOptions, QStringList(reg.cap(1))); - twi->setFlags(twi->flags() | Qt::ItemIsUserCheckable); + m_lvClassOptions->clear(); + for (int i = start; i < list.count(); ++i) { + int pos = reg.indexIn(list[i]); + if (pos != -1) { + QTreeWidgetItem *twi = new QTreeWidgetItem(m_lvClassOptions, QStringList(reg.cap(1))); + twi->setFlags(twi->flags() | Qt::ItemIsUserCheckable); - // see if it is a default option - if (isDefaultClassOption(reg.cap(1))) { - twi->setText(1, reg.cap(2) + " [default]"); - } - else { - twi->setText(1, reg.cap(2)); - } + // see if it is a default option + if (isDefaultClassOption(reg.cap(1))) { + twi->setText(1, reg.cap(2) + " [default]"); + } + else { + twi->setText(1, reg.cap(2)); + } - // check it if this option is set by th user - twi->setCheckState(0, isSelectedClassOption(reg.cap(1)) ? Qt::Checked : Qt::Unchecked); - } - } + // check it if this option is set by th user + twi->setCheckState(0, isSelectedClassOption(reg.cap(1)) ? Qt::Checked : Qt::Unchecked); + } + } } // get all options of the current class as a comma separated list // - first entry: always the current fontsize // - second entry: always the current papersize // - followed by all other checked options QString QuickDocument::getClassOptions() { - QString fontsize = stripDefault(m_cbTypefaceSize->currentText()); - QString papersize = stripDefault(m_cbPaperSize->currentText()); + QString fontsize = stripDefault(m_cbTypefaceSize->currentText()); + QString papersize = stripDefault(m_cbPaperSize->currentText()); - QString options = fontsize + ',' + papersize; + QString options = fontsize + ',' + papersize; - QTreeWidgetItemIterator it(m_lvClassOptions); - while (*it) { - if ((*it)->checkState(0) == Qt::Checked) { - options += ',' + (*it)->text(0); - } - ++it; - } + QTreeWidgetItemIterator it(m_lvClassOptions); + while (*it) { + if ((*it)->checkState(0) == Qt::Checked) { + options += ',' + (*it)->text(0); + } + ++it; + } - return options; + return options; } // Some changes were made in the listview: add, edit oder delete entries. // This means that the defaultOptions-dictionary, the selectedOptions-dictionary // and the list of all options may be . So the documentClass-dictionary, // the defaultOptions-dictionary and the selectedOptions-dictionary must be updated. void QuickDocument::updateClassOptions() { - KILE_DEBUG_MAIN << "==QuickDocument::updateClassOptions()============"; - KILE_DEBUG_MAIN << "\tclass: " << m_currentClass; + KILE_DEBUG_MAIN << "==QuickDocument::updateClassOptions()============"; + KILE_DEBUG_MAIN << "\tclass: " << m_currentClass; - QString defaultoptions; - QStringList newlist; - QStringList oldlist = m_dictDocumentClasses[m_currentClass]; + QString defaultoptions; + QStringList newlist; + QStringList oldlist = m_dictDocumentClasses[m_currentClass]; - // read the first four static entries - newlist << oldlist[qd_Fontsizes]; - newlist << oldlist[qd_Papersizes]; - newlist << QString(); // dummy entry: will be changed - newlist << getClassOptions(); + // read the first four static entries + newlist << oldlist[qd_Fontsizes]; + newlist << oldlist[qd_Papersizes]; + newlist << QString(); // dummy entry: will be changed + newlist << getClassOptions(); - // read all options - QTreeWidgetItemIterator it(m_lvClassOptions); - while (*it) { - QString description = (*it)->text(1); - if (description.right(10) == " [default]") { - description = stripDefault(description); - if (!defaultoptions.isEmpty()) { - defaultoptions += ','; - } - defaultoptions += (*it)->text(0); - } - newlist += (*it)->text(0) + " => " + description; - ++it; - } + // read all options + QTreeWidgetItemIterator it(m_lvClassOptions); + while (*it) { + QString description = (*it)->text(1); + if (description.right(10) == " [default]") { + description = stripDefault(description); + if (!defaultoptions.isEmpty()) { + defaultoptions += ','; + } + defaultoptions += (*it)->text(0); + } + newlist += (*it)->text(0) + " => " + description; + ++it; + } - // update list entry with defaultoptions - newlist[qd_DefaultOptions] = defaultoptions; + // update list entry with defaultoptions + newlist[qd_DefaultOptions] = defaultoptions; - // insert this changed list into the documentClass-dictionary - m_dictDocumentClasses[m_currentClass] = newlist; + // insert this changed list into the documentClass-dictionary + m_dictDocumentClasses[m_currentClass] = newlist; - // update other dictionaries - setDefaultClassOptions(newlist[qd_DefaultOptions]); - setSelectedClassOptions(newlist[qd_SelectedOptions]); + // update other dictionaries + setDefaultClassOptions(newlist[qd_DefaultOptions]); + setSelectedClassOptions(newlist[qd_SelectedOptions]); } // Insert all entries from a comma separated list into a combobox. // If this entry matches a given text, this entry will be activated. void QuickDocument::fillCombobox(KileWidget::CategoryComboBox *combo, const QString &cslist, const QString &seltext) { - bool documentclasscombo = (combo == m_cbDocumentClass); - - QString sep = (m_currentClass == "beamer" && combo == m_cbPaperSize) ? ";" : ","; - QStringList list = cslist.split(sep, QString::SkipEmptyParts); - if (!documentclasscombo) { - list.sort(); - } - - combo->clear(); - for (int i = 0; i < list.count(); ++i) { - if (!documentclasscombo && isDefaultClassOption(list[i])) { - combo->addItem(QString(list[i]) + " [default]"); - } - else - if (list[i] != "-") { - combo->addItem(list[i]); - } - else { - combo->addCategoryItem(""); - } - - // should this entry be selected? - if (!seltext.isEmpty() && list[i] == seltext) { - combo->setCurrentIndex(i); - } - } + bool documentclasscombo = (combo == m_cbDocumentClass); + + QString sep = (m_currentClass == "beamer" && combo == m_cbPaperSize) ? ";" : ","; + QStringList list = cslist.split(sep, QString::SkipEmptyParts); + if (!documentclasscombo) { + list.sort(); + } + + combo->clear(); + for (int i = 0; i < list.count(); ++i) { + if (!documentclasscombo && isDefaultClassOption(list[i])) { + combo->addItem(QString(list[i]) + " [default]"); + } + else if (list[i] != "-") { + combo->addItem(list[i]); + } + else { + combo->addCategoryItem(""); + } + + // should this entry be selected? + if (!seltext.isEmpty() && list[i] == seltext) { + combo->setCurrentIndex(i); + } + } } // Add some entries from a comma separated list to a sorted combobox. // The new entries must match a regular expression or will be denied. bool QuickDocument::addComboboxEntries(KileWidget::CategoryComboBox *combo, const QString &title, const QString &entry) { - // read current comboxbox entries - QStringList combolist; - for (int i = 0; i < combo->count(); ++i) { - combolist += combo->itemText(i); - } - - // add new entries (one or a comma separated list) - QStringList list = entry.split(','); - for (int i = 0; i < list.count(); ++i) { - QString s = list[i].trimmed(); - // entries must match a regular expression - if (combolist.indexOf(s) != -1) { - KMessageBox::error(this, i18n("%1 '%2' already exists.", title, s)); - } - else { - combolist += s; - KILE_DEBUG_MAIN << "\tinsert new " << title << ": " << s; - } - } - - // insert list, if there are more entries than before - if (combolist.count() > combo->count()) { - fillCombobox(combo, combolist.join(","), list[0]); - return true; - } - else { - return false; - } + // read current comboxbox entries + QStringList combolist; + for (int i = 0; i < combo->count(); ++i) { + combolist += combo->itemText(i); + } + + // add new entries (one or a comma separated list) + QStringList list = entry.split(','); + for (int i = 0; i < list.count(); ++i) { + QString s = list[i].trimmed(); + // entries must match a regular expression + if (combolist.indexOf(s) != -1) { + KMessageBox::error(this, i18n("%1 '%2' already exists.", title, s)); + } + else { + combolist += s; + KILE_DEBUG_MAIN << "\tinsert new " << title << ": " << s; + } + } + + // insert list, if there are more entries than before + if (combolist.count() > combo->count()) { + fillCombobox(combo, combolist.join(","), list[0]); + return true; + } + else { + return false; + } } QString QuickDocument::getComboxboxList(KComboBox *combo) { - QStringList list; - for (int i = 0; i < combo->count(); ++i) { - list += combo->itemText(i); - } + QStringList list; + for (int i = 0; i < combo->count(); ++i) { + list += combo->itemText(i); + } - return (list.count() > 0) ? list.join(",") : QString(); + return (list.count() > 0) ? list.join(",") : QString(); } // strip an optional default-tag from the string QString QuickDocument::stripDefault(const QString &s) { - return (s.right(10) == " [default]") ? s.left(s.length() - 10) : s; + return (s.right(10) == " [default]") ? s.left(s.length() - 10) : s; } ////////////////////////////// packages tab ////////////////////////////// void QuickDocument::readPackagesConfig() { - KILE_DEBUG_MAIN << "\tread config: packages"; + KILE_DEBUG_MAIN << "\tread config: packages"; - if (! readPackagesListview()) - initPackages(); + if (! readPackagesListview()) + initPackages(); } // init default values for packages tab void QuickDocument::initPackages() { - KILE_DEBUG_MAIN << "read config: init standard packages"; - QTreeWidgetItem *cli; - QTreeWidgetItem *clichild; - - m_lvPackages->clear(); - cli = insertTreeWidget(m_lvPackages, "amsmath", i18n("Special math environments and commands (AMS)")); - cli = insertTreeWidget(m_lvPackages, "amsfonts", i18n("Collection of fonts and symbols for math mode (AMS)")); - cli = insertTreeWidget(m_lvPackages, "amssymb", i18n("Defines symbol names for all math symbols in MSAM and MSBM (AMS)")); - cli = insertTreeWidget(m_lvPackages, "amsthm", i18n("Improved theorem setup (AMS)")); - cli = insertTreeWidget(m_lvPackages, "caption", i18n("Extends caption capabilities for figures and tables")); - - cli = insertTreeWidget(m_lvPackages, "hyperref", i18n("Hypertext marks in LaTeX")); - cli->setExpanded(true); - clichild = insertTreeWidget(cli, "dvips", i18n("Use dvips as hyperref driver")); - clichild->setCheckState(0, Qt::Checked); - clichild = insertTreeWidget(cli, "pdftex", i18n("Use pdftex as hyperref driver")); - clichild = insertEditableTreeWidget(cli, "bookmarks", i18n("Make bookmarks"), "true", "true"); - clichild = insertEditableTreeWidget(cli, "bookmarksnumbered", i18n("Put section numbers in bookmarks"), "false", "false"); - clichild = insertEditableTreeWidget(cli, "bookmarksopen", i18n("Open up bookmark tree"), QString(), QString()); - clichild = insertEditableTreeWidget(cli, "pdfauthor", i18n("Text for PDF Author field"), QString(), QString()); - clichild = insertEditableTreeWidget(cli, "pdfcreator", i18n("Text for PDF Creator field"), i18n("LaTeX with hyperref package"), i18n("LaTeX with hyperref package")); - clichild = insertEditableTreeWidget(cli, "pdffitwindow", i18n("Resize document window to fit document size"), "false", "false"); - clichild = insertEditableTreeWidget(cli, "pdfkeywords", i18n("Text for PDF Keywords field"), QString(), QString()); - clichild = insertEditableTreeWidget(cli, "pdfproducer", i18n("Text for PDF Producer field"), QString(), QString()); - clichild = insertEditableTreeWidget(cli, "pdfstartview", i18n("Starting view of PDF document"), "/Fit", "/Fit"); - clichild = insertEditableTreeWidget(cli, "pdfsubject", i18n("Text for PDF Subject field"), QString(), QString()); - clichild = insertEditableTreeWidget(cli, "pdftitle", i18n("Text for PDF Title field"), QString(), QString()); - - cli = insertTreeWidget(m_lvPackages, "mathpazo", i18n("Use Palatino font as roman font (both text and math mode)")); - cli = insertTreeWidget(m_lvPackages, "mathptmx", i18n("Use Times font as roman font (both text and math mode)")); - cli = insertTreeWidget(m_lvPackages, "makeidx", i18n("Enable index generation")); - cli = insertTreeWidget(m_lvPackages, "multicol", i18n("Enables multicolumn environments")); - cli = insertTreeWidget(m_lvPackages, "pst-all", i18n("Load all pstricks packages")); - cli = insertTreeWidget(m_lvPackages, "rotating", i18n("Rotates text")); - cli = insertTreeWidget(m_lvPackages, "subfigure", i18n("Enables subfigures inside figures")); - cli = insertTreeWidget(m_lvPackages, "upgreek", i18n("Typesetting capital Greek letters")); - cli = insertTreeWidget(m_lvPackages, "xcolor", i18n("Extending LaTeX's color facilities")); - - cli = insertTreeWidget(m_lvPackages, "babel", i18n("Adds language specific support")); - cli->setExpanded(true); - cli->setCheckState(0, Qt::Checked); - clichild = insertTreeWidget(cli, "acadian", ""); - clichild = insertTreeWidget(cli, "afrikaans", ""); - clichild = insertTreeWidget(cli, "american", ""); - clichild = insertTreeWidget(cli, "australian", ""); - clichild = insertTreeWidget(cli, "austrian", ""); - clichild = insertTreeWidget(cli, "bahasa", ""); - clichild = insertTreeWidget(cli, "basque", ""); - clichild = insertTreeWidget(cli, "brazil", ""); - clichild = insertTreeWidget(cli, "brazilian", ""); - clichild = insertTreeWidget(cli, "breton", ""); - clichild = insertTreeWidget(cli, "british", ""); - clichild = insertTreeWidget(cli, "bulgarian", ""); - clichild = insertTreeWidget(cli, "canadian", ""); - clichild = insertTreeWidget(cli, "canadien", ""); - clichild = insertTreeWidget(cli, "catalan", ""); - clichild = insertTreeWidget(cli, "croatian", ""); - clichild = insertTreeWidget(cli, "czech", ""); - clichild = insertTreeWidget(cli, "danish", ""); - clichild = insertTreeWidget(cli, "dutch", ""); - clichild = insertTreeWidget(cli, "english", ""); - clichild = insertTreeWidget(cli, "esperanto", ""); - clichild = insertTreeWidget(cli, "estonian", ""); - clichild = insertTreeWidget(cli, "finnish", ""); - clichild = insertTreeWidget(cli, "francais", ""); - clichild = insertTreeWidget(cli, "frenchb", ""); - clichild = insertTreeWidget(cli, "french", ""); - clichild = insertTreeWidget(cli, "galician", ""); - clichild = insertTreeWidget(cli, "german", ""); - clichild = insertTreeWidget(cli, "germanb", ""); - clichild = insertTreeWidget(cli, "greek", ""); - clichild = insertTreeWidget(cli, "polutonikogreek", ""); - clichild = insertTreeWidget(cli, "hebrew", ""); - clichild = insertTreeWidget(cli, "hungarian", ""); - clichild = insertTreeWidget(cli, "icelandic", ""); - clichild = insertTreeWidget(cli, "interlingua", ""); - clichild = insertTreeWidget(cli, "irish", ""); - clichild = insertTreeWidget(cli, "italian", ""); - clichild = insertTreeWidget(cli, "latin", ""); - clichild = insertTreeWidget(cli, "lowersorbian", ""); - clichild = insertTreeWidget(cli, "magyar", ""); - clichild = insertTreeWidget(cli, "naustrian", ""); - clichild = insertTreeWidget(cli, "newzealand", ""); - clichild = insertTreeWidget(cli, "ngerman", ""); - clichild = insertTreeWidget(cli, "norsk", ""); - clichild = insertTreeWidget(cli, "samin", ""); - clichild = insertTreeWidget(cli, "nynorsk", ""); - clichild = insertTreeWidget(cli, "polish", ""); - clichild = insertTreeWidget(cli, "portuges", ""); - clichild = insertTreeWidget(cli, "portuguese", ""); - clichild = insertTreeWidget(cli, "romanian", ""); - clichild = insertTreeWidget(cli, "russian", ""); - clichild = insertTreeWidget(cli, "scottish", ""); - clichild = insertTreeWidget(cli, "serbian", ""); - clichild = insertTreeWidget(cli, "slovak", ""); - clichild = insertTreeWidget(cli, "slovene", ""); - clichild = insertTreeWidget(cli, "spanish", ""); - clichild = insertTreeWidget(cli, "swedish", ""); - clichild = insertTreeWidget(cli, "turkish", ""); - clichild = insertTreeWidget(cli, "ukrainian", ""); - clichild = insertTreeWidget(cli, "uppersorbian", ""); - clichild = insertTreeWidget(cli, "welsh", ""); - clichild = insertTreeWidget(cli, "UKenglish", ""); - clichild = insertTreeWidget(cli, "USenglish", ""); - - cli = insertTreeWidget(m_lvPackages, "fontenc", i18n("Use a font encoding scheme")); - cli->setExpanded(true); - cli->setCheckState(0, Qt::Checked); - clichild = insertTreeWidget(cli, "HE8", ""); - clichild = insertTreeWidget(cli, "IL2", ""); - clichild = insertTreeWidget(cli, "LCH", ""); - clichild = insertTreeWidget(cli, "LCY", ""); - clichild = insertTreeWidget(cli, "LGR", ""); - clichild = insertTreeWidget(cli, "LHE", ""); - clichild = insertTreeWidget(cli, "LIT", ""); - clichild = insertTreeWidget(cli, "LO1", ""); - clichild = insertTreeWidget(cli, "LY1", ""); - clichild = insertTreeWidget(cli, "MTT", ""); - clichild = insertTreeWidget(cli, "OML", ""); - clichild = insertTreeWidget(cli, "OMS", ""); - clichild = insertTreeWidget(cli, "OT1", ""); - clichild = insertTreeWidget(cli, "OT2", ""); - clichild = insertTreeWidget(cli, "OT4", ""); - clichild = insertTreeWidget(cli, "PD1", ""); - clichild = insertTreeWidget(cli, "PU", ""); - clichild = insertTreeWidget(cli, "QX", ""); - clichild = insertTreeWidget(cli, "T1", ""); - clichild = insertTreeWidget(cli, "T2A", ""); - clichild = insertTreeWidget(cli, "T2B", ""); - clichild = insertTreeWidget(cli, "T2C", ""); - clichild = insertTreeWidget(cli, "T5", ""); - clichild = insertTreeWidget(cli, "TS1", ""); - clichild = insertTreeWidget(cli, "UT1", ""); - clichild = insertTreeWidget(cli, "X2", ""); - - cli = insertTreeWidget(m_lvPackages, "graphicx", i18n("Support for including graphics")); - cli->setExpanded(true); - cli->setCheckState(0, Qt::Checked); - clichild = insertTreeWidget(cli, "dvips", i18n("Specialize on graphic inclusion for dvips")); - clichild = insertTreeWidget(cli, "pdftex", i18n("Specialize on graphic inclusion for pdftex")); - clichild = insertTreeWidget(cli, "draft", i18n("Show only frames of graphics")); + KILE_DEBUG_MAIN << "read config: init standard packages"; + QTreeWidgetItem *cli; + QTreeWidgetItem *clichild; + + m_lvPackages->clear(); + cli = insertTreeWidget(m_lvPackages, "amsmath", i18n("Special math environments and commands (AMS)")); + cli = insertTreeWidget(m_lvPackages, "amsfonts", i18n("Collection of fonts and symbols for math mode (AMS)")); + cli = insertTreeWidget(m_lvPackages, "amssymb", i18n("Defines symbol names for all math symbols in MSAM and MSBM (AMS)")); + cli = insertTreeWidget(m_lvPackages, "amsthm", i18n("Improved theorem setup (AMS)")); + cli = insertTreeWidget(m_lvPackages, "caption", i18n("Extends caption capabilities for figures and tables")); + + cli = insertTreeWidget(m_lvPackages, "hyperref", i18n("Hypertext marks in LaTeX")); + cli->setExpanded(true); + clichild = insertTreeWidget(cli, "dvips", i18n("Use dvips as hyperref driver")); + clichild->setCheckState(0, Qt::Checked); + clichild = insertTreeWidget(cli, "pdftex", i18n("Use pdftex as hyperref driver")); + clichild = insertEditableTreeWidget(cli, "bookmarks", i18n("Make bookmarks"), "true", "true"); + clichild = insertEditableTreeWidget(cli, "bookmarksnumbered", i18n("Put section numbers in bookmarks"), "false", "false"); + clichild = insertEditableTreeWidget(cli, "bookmarksopen", i18n("Open up bookmark tree"), QString(), QString()); + clichild = insertEditableTreeWidget(cli, "pdfauthor", i18n("Text for PDF Author field"), QString(), QString()); + clichild = insertEditableTreeWidget(cli, "pdfcreator", i18n("Text for PDF Creator field"), i18n("LaTeX with hyperref package"), i18n("LaTeX with hyperref package")); + clichild = insertEditableTreeWidget(cli, "pdffitwindow", i18n("Resize document window to fit document size"), "false", "false"); + clichild = insertEditableTreeWidget(cli, "pdfkeywords", i18n("Text for PDF Keywords field"), QString(), QString()); + clichild = insertEditableTreeWidget(cli, "pdfproducer", i18n("Text for PDF Producer field"), QString(), QString()); + clichild = insertEditableTreeWidget(cli, "pdfstartview", i18n("Starting view of PDF document"), "/Fit", "/Fit"); + clichild = insertEditableTreeWidget(cli, "pdfsubject", i18n("Text for PDF Subject field"), QString(), QString()); + clichild = insertEditableTreeWidget(cli, "pdftitle", i18n("Text for PDF Title field"), QString(), QString()); + + cli = insertTreeWidget(m_lvPackages, "mathpazo", i18n("Use Palatino font as roman font (both text and math mode)")); + cli = insertTreeWidget(m_lvPackages, "mathptmx", i18n("Use Times font as roman font (both text and math mode)")); + cli = insertTreeWidget(m_lvPackages, "makeidx", i18n("Enable index generation")); + cli = insertTreeWidget(m_lvPackages, "multicol", i18n("Enables multicolumn environments")); + cli = insertTreeWidget(m_lvPackages, "pst-all", i18n("Load all pstricks packages")); + cli = insertTreeWidget(m_lvPackages, "rotating", i18n("Rotates text")); + cli = insertTreeWidget(m_lvPackages, "subfigure", i18n("Enables subfigures inside figures")); + cli = insertTreeWidget(m_lvPackages, "upgreek", i18n("Typesetting capital Greek letters")); + cli = insertTreeWidget(m_lvPackages, "xcolor", i18n("Extending LaTeX's color facilities")); + + cli = insertTreeWidget(m_lvPackages, "babel", i18n("Adds language specific support")); + cli->setExpanded(true); + cli->setCheckState(0, Qt::Checked); + clichild = insertTreeWidget(cli, "acadian", ""); + clichild = insertTreeWidget(cli, "afrikaans", ""); + clichild = insertTreeWidget(cli, "american", ""); + clichild = insertTreeWidget(cli, "australian", ""); + clichild = insertTreeWidget(cli, "austrian", ""); + clichild = insertTreeWidget(cli, "bahasa", ""); + clichild = insertTreeWidget(cli, "basque", ""); + clichild = insertTreeWidget(cli, "brazil", ""); + clichild = insertTreeWidget(cli, "brazilian", ""); + clichild = insertTreeWidget(cli, "breton", ""); + clichild = insertTreeWidget(cli, "british", ""); + clichild = insertTreeWidget(cli, "bulgarian", ""); + clichild = insertTreeWidget(cli, "canadian", ""); + clichild = insertTreeWidget(cli, "canadien", ""); + clichild = insertTreeWidget(cli, "catalan", ""); + clichild = insertTreeWidget(cli, "croatian", ""); + clichild = insertTreeWidget(cli, "czech", ""); + clichild = insertTreeWidget(cli, "danish", ""); + clichild = insertTreeWidget(cli, "dutch", ""); + clichild = insertTreeWidget(cli, "english", ""); + clichild = insertTreeWidget(cli, "esperanto", ""); + clichild = insertTreeWidget(cli, "estonian", ""); + clichild = insertTreeWidget(cli, "finnish", ""); + clichild = insertTreeWidget(cli, "francais", ""); + clichild = insertTreeWidget(cli, "frenchb", ""); + clichild = insertTreeWidget(cli, "french", ""); + clichild = insertTreeWidget(cli, "galician", ""); + clichild = insertTreeWidget(cli, "german", ""); + clichild = insertTreeWidget(cli, "germanb", ""); + clichild = insertTreeWidget(cli, "greek", ""); + clichild = insertTreeWidget(cli, "polutonikogreek", ""); + clichild = insertTreeWidget(cli, "hebrew", ""); + clichild = insertTreeWidget(cli, "hungarian", ""); + clichild = insertTreeWidget(cli, "icelandic", ""); + clichild = insertTreeWidget(cli, "interlingua", ""); + clichild = insertTreeWidget(cli, "irish", ""); + clichild = insertTreeWidget(cli, "italian", ""); + clichild = insertTreeWidget(cli, "latin", ""); + clichild = insertTreeWidget(cli, "lowersorbian", ""); + clichild = insertTreeWidget(cli, "magyar", ""); + clichild = insertTreeWidget(cli, "naustrian", ""); + clichild = insertTreeWidget(cli, "newzealand", ""); + clichild = insertTreeWidget(cli, "ngerman", ""); + clichild = insertTreeWidget(cli, "norsk", ""); + clichild = insertTreeWidget(cli, "samin", ""); + clichild = insertTreeWidget(cli, "nynorsk", ""); + clichild = insertTreeWidget(cli, "polish", ""); + clichild = insertTreeWidget(cli, "portuges", ""); + clichild = insertTreeWidget(cli, "portuguese", ""); + clichild = insertTreeWidget(cli, "romanian", ""); + clichild = insertTreeWidget(cli, "russian", ""); + clichild = insertTreeWidget(cli, "scottish", ""); + clichild = insertTreeWidget(cli, "serbian", ""); + clichild = insertTreeWidget(cli, "slovak", ""); + clichild = insertTreeWidget(cli, "slovene", ""); + clichild = insertTreeWidget(cli, "spanish", ""); + clichild = insertTreeWidget(cli, "swedish", ""); + clichild = insertTreeWidget(cli, "turkish", ""); + clichild = insertTreeWidget(cli, "ukrainian", ""); + clichild = insertTreeWidget(cli, "uppersorbian", ""); + clichild = insertTreeWidget(cli, "welsh", ""); + clichild = insertTreeWidget(cli, "UKenglish", ""); + clichild = insertTreeWidget(cli, "USenglish", ""); + + cli = insertTreeWidget(m_lvPackages, "fontenc", i18n("Use a font encoding scheme")); + cli->setExpanded(true); + cli->setCheckState(0, Qt::Checked); + clichild = insertTreeWidget(cli, "HE8", ""); + clichild = insertTreeWidget(cli, "IL2", ""); + clichild = insertTreeWidget(cli, "LCH", ""); + clichild = insertTreeWidget(cli, "LCY", ""); + clichild = insertTreeWidget(cli, "LGR", ""); + clichild = insertTreeWidget(cli, "LHE", ""); + clichild = insertTreeWidget(cli, "LIT", ""); + clichild = insertTreeWidget(cli, "LO1", ""); + clichild = insertTreeWidget(cli, "LY1", ""); + clichild = insertTreeWidget(cli, "MTT", ""); + clichild = insertTreeWidget(cli, "OML", ""); + clichild = insertTreeWidget(cli, "OMS", ""); + clichild = insertTreeWidget(cli, "OT1", ""); + clichild = insertTreeWidget(cli, "OT2", ""); + clichild = insertTreeWidget(cli, "OT4", ""); + clichild = insertTreeWidget(cli, "PD1", ""); + clichild = insertTreeWidget(cli, "PU", ""); + clichild = insertTreeWidget(cli, "QX", ""); + clichild = insertTreeWidget(cli, "T1", ""); + clichild = insertTreeWidget(cli, "T2A", ""); + clichild = insertTreeWidget(cli, "T2B", ""); + clichild = insertTreeWidget(cli, "T2C", ""); + clichild = insertTreeWidget(cli, "T5", ""); + clichild = insertTreeWidget(cli, "TS1", ""); + clichild = insertTreeWidget(cli, "UT1", ""); + clichild = insertTreeWidget(cli, "X2", ""); + + cli = insertTreeWidget(m_lvPackages, "graphicx", i18n("Support for including graphics")); + cli->setExpanded(true); + cli->setCheckState(0, Qt::Checked); + clichild = insertTreeWidget(cli, "dvips", i18n("Specialize on graphic inclusion for dvips")); + clichild = insertTreeWidget(cli, "pdftex", i18n("Specialize on graphic inclusion for pdftex")); + clichild = insertTreeWidget(cli, "draft", i18n("Show only frames of graphics")); } // Try to read values from the config file: // - main entry: selected,open,empty,empty,description // - child entry: selected,editable,defaultvalue,value,description bool QuickDocument::readPackagesListview() { - KILE_DEBUG_MAIN << "\tread config: packages from config file"; - - QStringList elements = KileConfig::packagesList(); - - // clear packages dictionaries and listview - m_dictPackagesEditable.clear(); - m_dictPackagesDefaultvalues.clear(); - m_lvPackages->clear(); - - if (elements.empty()) - return false; - - // regular expression to split the string from the config file - QRegExp reg("([^,]*),([^,]*),([^,]*),([^,]*),(.*)"); - - KConfigGroup configGroup = config()->group("QuickDocument/Packages"); - for (QStringList::Iterator it = elements.begin(); it != elements.end(); ++it) { - QTreeWidgetItem *item; - - // look, if this is a main or a child entry - KILE_DEBUG_MAIN << "\tread config entry: " << *it; - int pos = (*it).indexOf('!'); - if (pos == -1) { // main entry - item = new QTreeWidgetItem(m_lvPackages, QStringList(*it)); - item->setFlags(item->flags() | Qt::ItemIsUserCheckable); - item->setCheckState(0, Qt::Unchecked); - if (reg.exactMatch(configGroup.readEntry(*it))) { - if (reg.cap(1) == "1") // selected state (entry 1) - item->setCheckState(0, Qt::Checked); - if (reg.cap(2) == "1") // open state (entry 2) - item->setExpanded(true); - item->setText(2, reg.cap(5)); // description (entry 5) - } else { - KILE_DEBUG_MAIN << "\twrong config entry for package " << item->text(0); - } - } else { // child entry - QList items = m_lvPackages->findItems((*it).left(pos), Qt::MatchExactly); - if (items.count() > 0) { - item = items[0]; - QTreeWidgetItem *clichild; - if (reg.exactMatch(configGroup.readEntry(*it))) { - if (reg.cap(2) == "1") { // editable state - clichild = insertEditableTreeWidget(item, (*it).mid(pos + 1), reg.cap(5), reg.cap(4), reg.cap(3)); - } else { - clichild = new QTreeWidgetItem(item, QStringList((*it).mid(pos + 1))); - clichild->setFlags(clichild->flags() | Qt::ItemIsUserCheckable); - clichild->setCheckState(0, Qt::Unchecked); - clichild->setText(2, reg.cap(5)); // description - } - if (reg.cap(1) == "1") // selected state - clichild->setCheckState(0, Qt::Checked); - } else { - KILE_DEBUG_MAIN << "\twrong config entry for package option " << item->text(0); - } - } else { - KILE_DEBUG_MAIN << "\tlistview entry for package " << (*it).left(pos) << " not found"; - } - } - } - - return true; + KILE_DEBUG_MAIN << "\tread config: packages from config file"; + + QStringList elements = KileConfig::packagesList(); + + // clear packages dictionaries and listview + m_dictPackagesEditable.clear(); + m_dictPackagesDefaultvalues.clear(); + m_lvPackages->clear(); + + if (elements.empty()) + return false; + + // regular expression to split the string from the config file + QRegExp reg("([^,]*),([^,]*),([^,]*),([^,]*),(.*)"); + + KConfigGroup configGroup = config()->group("QuickDocument/Packages"); + for (QStringList::Iterator it = elements.begin(); it != elements.end(); ++it) { + QTreeWidgetItem *item; + + // look, if this is a main or a child entry + KILE_DEBUG_MAIN << "\tread config entry: " << *it; + int pos = (*it).indexOf('!'); + if (pos == -1) { // main entry + item = new QTreeWidgetItem(m_lvPackages, QStringList(*it)); + item->setFlags(item->flags() | Qt::ItemIsUserCheckable); + item->setCheckState(0, Qt::Unchecked); + if (reg.exactMatch(configGroup.readEntry(*it))) { + if (reg.cap(1) == "1") // selected state (entry 1) + item->setCheckState(0, Qt::Checked); + if (reg.cap(2) == "1") // open state (entry 2) + item->setExpanded(true); + item->setText(2, reg.cap(5)); // description (entry 5) + } else { + KILE_DEBUG_MAIN << "\twrong config entry for package " << item->text(0); + } + } else { // child entry + QList items = m_lvPackages->findItems((*it).left(pos), Qt::MatchExactly); + if (items.count() > 0) { + item = items[0]; + QTreeWidgetItem *clichild; + if (reg.exactMatch(configGroup.readEntry(*it))) { + if (reg.cap(2) == "1") { // editable state + clichild = insertEditableTreeWidget(item, (*it).mid(pos + 1), reg.cap(5), reg.cap(4), reg.cap(3)); + } else { + clichild = new QTreeWidgetItem(item, QStringList((*it).mid(pos + 1))); + clichild->setFlags(clichild->flags() | Qt::ItemIsUserCheckable); + clichild->setCheckState(0, Qt::Unchecked); + clichild->setText(2, reg.cap(5)); // description + } + if (reg.cap(1) == "1") // selected state + clichild->setCheckState(0, Qt::Checked); + } else { + KILE_DEBUG_MAIN << "\twrong config entry for package option " << item->text(0); + } + } else { + KILE_DEBUG_MAIN << "\tlistview entry for package " << (*it).left(pos) << " not found"; + } + } + } + + return true; } void QuickDocument::writePackagesConfig() { - KILE_DEBUG_MAIN << "\twrite config: packages"; - - QStringList packagesList; - - KConfigGroup configGroup = config()->group("QuickDocument/Packages"); - for (int i = 0; i < m_lvPackages->topLevelItemCount(); ++i) { - QTreeWidgetItem *currentItem = m_lvPackages->topLevelItem(i); - KILE_DEBUG_MAIN << "\twrite config: " << currentItem->text(0); - // add to packages list - packagesList += currentItem->text(0); - - // determine config entry - QString packageentry; - - // look for selected entries - if (currentItem->checkState(0) == Qt::Checked) - packageentry = "1,"; - else - packageentry = "0,"; - - // look if this listitem is opened - if (currentItem->isExpanded()) - packageentry += "1,"; - else - packageentry += "0,"; - - // two dummy entries and finally the description - packageentry += ",," + currentItem->text(2); - - // write listview entry - configGroup.writeEntry(currentItem->text(0), packageentry); - - // look for children - for (int j = 0; j < currentItem->childCount(); ++j) { - QTreeWidgetItem *curchild = currentItem->child(j); - // add child to packages list - QString option = currentItem->text(0) + '!' + curchild->text(0); - packagesList += option; - KILE_DEBUG_MAIN << "\twrite config: " << option; - - // determine config entry - QString optionentry; - - // look for selected options - if (curchild->checkState(0) == Qt::Checked) - optionentry = "1,"; - else - optionentry = "0,"; - - // look, if this child is editable - if (m_dictPackagesEditable.contains(option)) { - optionentry += "1,"; - if (m_dictPackagesDefaultvalues.contains(option)) - optionentry += m_dictPackagesDefaultvalues[option] + ','; - else - optionentry += ','; - } else - optionentry += "0,,"; - - // add a value and a description - optionentry += getPackagesValue(curchild->text(1)) - + ',' + stripPackageDefault(option, curchild->text(2)); - - // write listview entry - configGroup.writeEntry(option, optionentry); - } - } - - // write the list of all packages - KileConfig::setPackagesList(packagesList); + KILE_DEBUG_MAIN << "\twrite config: packages"; + + QStringList packagesList; + + KConfigGroup configGroup = config()->group("QuickDocument/Packages"); + for (int i = 0; i < m_lvPackages->topLevelItemCount(); ++i) { + QTreeWidgetItem *currentItem = m_lvPackages->topLevelItem(i); + KILE_DEBUG_MAIN << "\twrite config: " << currentItem->text(0); + // add to packages list + packagesList += currentItem->text(0); + + // determine config entry + QString packageentry; + + // look for selected entries + if (currentItem->checkState(0) == Qt::Checked) + packageentry = "1,"; + else + packageentry = "0,"; + + // look if this listitem is opened + if (currentItem->isExpanded()) + packageentry += "1,"; + else + packageentry += "0,"; + + // two dummy entries and finally the description + packageentry += ",," + currentItem->text(2); + + // write listview entry + configGroup.writeEntry(currentItem->text(0), packageentry); + + // look for children + for (int j = 0; j < currentItem->childCount(); ++j) { + QTreeWidgetItem *curchild = currentItem->child(j); + // add child to packages list + QString option = currentItem->text(0) + '!' + curchild->text(0); + packagesList += option; + KILE_DEBUG_MAIN << "\twrite config: " << option; + + // determine config entry + QString optionentry; + + // look for selected options + if (curchild->checkState(0) == Qt::Checked) + optionentry = "1,"; + else + optionentry = "0,"; + + // look, if this child is editable + if (m_dictPackagesEditable.contains(option)) { + optionentry += "1,"; + if (m_dictPackagesDefaultvalues.contains(option)) + optionentry += m_dictPackagesDefaultvalues[option] + ','; + else + optionentry += ','; + } else + optionentry += "0,,"; + + // add a value and a description + optionentry += getPackagesValue(curchild->text(1)) + + ',' + stripPackageDefault(option, curchild->text(2)); + + // write listview entry + configGroup.writeEntry(option, optionentry); + } + } + + // write the list of all packages + KileConfig::setPackagesList(packagesList); } QTreeWidgetItem* QuickDocument::insertTreeWidget(QTreeWidget *treeWidget, - const QString &entry, - const QString &description) + const QString &entry, + const QString &description) { - QTreeWidgetItem *item = new QTreeWidgetItem(treeWidget, QStringList() << entry << "" << description); - item->setFlags(item->flags() | Qt::ItemIsUserCheckable); - item->setCheckState(0, Qt::Unchecked); + QTreeWidgetItem *item = new QTreeWidgetItem(treeWidget, QStringList() << entry << "" << description); + item->setFlags(item->flags() | Qt::ItemIsUserCheckable); + item->setCheckState(0, Qt::Unchecked); - return item; + return item; } QTreeWidgetItem* QuickDocument::insertTreeWidget(QTreeWidgetItem *parent, - const QString &entry, - const QString &description) + const QString &entry, + const QString &description) { - QTreeWidgetItem *item = new QTreeWidgetItem(parent, QStringList() << entry << "" << description); - item->setFlags(item->flags() | Qt::ItemIsUserCheckable); - item->setCheckState(0, Qt::Unchecked); + QTreeWidgetItem *item = new QTreeWidgetItem(parent, QStringList() << entry << "" << description); + item->setFlags(item->flags() | Qt::ItemIsUserCheckable); + item->setCheckState(0, Qt::Unchecked); - return item; + return item; } QTreeWidgetItem* QuickDocument::insertEditableTreeWidget(QTreeWidgetItem *parent, - const QString &entry, - const QString &description, - const QString &value, - const QString &defaultvalue) + const QString &entry, + const QString &description, + const QString &value, + const QString &defaultvalue) { - QTreeWidgetItem *item = new QTreeWidgetItem(parent, QStringList() << entry << "" << description); - item->setFlags(item->flags() | Qt::ItemIsUserCheckable); - item->setCheckState(0, Qt::Unchecked); + QTreeWidgetItem *item = new QTreeWidgetItem(parent, QStringList() << entry << "" << description); + item->setFlags(item->flags() | Qt::ItemIsUserCheckable); + item->setCheckState(0, Qt::Unchecked); - QString option = parent->text(0) + '!' + entry; - m_dictPackagesEditable[option] = true; - if (!defaultvalue.isEmpty()) - m_dictPackagesDefaultvalues[option] = defaultvalue; - setPackagesValue(item, option, value); - if (!description.isEmpty()) - item->setText(2, addPackageDefault(option, description)); + QString option = parent->text(0) + '!' + entry; + m_dictPackagesEditable[option] = true; + if (!defaultvalue.isEmpty()) + m_dictPackagesDefaultvalues[option] = defaultvalue; + setPackagesValue(item, option, value); + if (!description.isEmpty()) + item->setText(2, addPackageDefault(option, description)); - return item; + return item; } void QuickDocument::setPackagesValue(QTreeWidgetItem *item, const QString &option, const QString &val) { - QString defaultvalue = (m_dictPackagesDefaultvalues.contains(option)) - ? m_dictPackagesDefaultvalues[option] : QString(); - QString value = (! val.isEmpty()) ? val : QString(); + QString defaultvalue = (m_dictPackagesDefaultvalues.contains(option)) + ? m_dictPackagesDefaultvalues[option] : QString(); + QString value = (! val.isEmpty()) ? val : QString(); - if (value == defaultvalue) - item->setText(1, i18n("")); - else - if (value.isEmpty()) - item->setText(1, i18n("")); - else - item->setText(1, value); + if (value == defaultvalue) + item->setText(1, i18n("")); + else if (value.isEmpty()) + item->setText(1, i18n("")); + else + item->setText(1, value); } QString QuickDocument::getPackagesValue(const QString &value) { - return (value == i18n("") || value == i18n("")) ? QString() : value; + return (value == i18n("") || value == i18n("")) ? QString() : value; } bool QuickDocument::isTreeWidgetEntry(QTreeWidget *treeWidget, const QString &entry) { - return treeWidget->findItems(entry, Qt::MatchExactly).count() != 0; + return treeWidget->findItems(entry, Qt::MatchExactly).count() != 0; } bool QuickDocument::isTreeWidgetChild(QTreeWidget *treeWidget, const QString &entry, const QString &option) { - for (int i = 0; i < treeWidget->topLevelItemCount(); ++i) { - QTreeWidgetItem *currentItem = treeWidget->topLevelItem(i); - if (currentItem->text(0) == entry) { - for (int j = 0; j < currentItem->childCount(); ++j) { - QTreeWidgetItem *currentChild = currentItem->child(j); - if (currentChild->text(0) == option) { - return true; - } - } - return false; - } - } - return false; + for (int i = 0; i < treeWidget->topLevelItemCount(); ++i) { + QTreeWidgetItem *currentItem = treeWidget->topLevelItem(i); + if (currentItem->text(0) == entry) { + for (int j = 0; j < currentItem->childCount(); ++j) { + QTreeWidgetItem *currentChild = currentItem->child(j); + if (currentChild->text(0) == option) { + return true; + } + } + return false; + } + } + return false; } QString QuickDocument::addPackageDefault(const QString &option, const QString &description) { - return (m_dictPackagesDefaultvalues.contains(option)) - ? description + " [" + m_dictPackagesDefaultvalues[option] + ']' - : description + " [ ]"; + return (m_dictPackagesDefaultvalues.contains(option)) + ? description + " [" + m_dictPackagesDefaultvalues[option] + ']' + : description + " [ ]"; } QString QuickDocument::stripPackageDefault(const QString &option, const QString &description) { - QRegExp reg("(.*) \\[([^\\[]*)\\]"); + QRegExp reg("(.*) \\[([^\\[]*)\\]"); - if (description.right(4) == " [ ]") - return description.left(description.length() - 4); + if (description.right(4) == " [ ]") + return description.left(description.length() - 4); - if (! reg.exactMatch(description)) - return description; + if (! reg.exactMatch(description)) + return description; - return (reg.cap(2).isEmpty() || - (m_dictPackagesDefaultvalues.contains(option) && m_dictPackagesDefaultvalues[option] == reg.cap(2)) - ) ? reg.cap(1) : description; + return (reg.cap(2).isEmpty() || + (m_dictPackagesDefaultvalues.contains(option) && m_dictPackagesDefaultvalues[option] == reg.cap(2)) + ) ? reg.cap(1) : description; } ////////////////////////////// hyperref tab ////////////////////////////// void QuickDocument::initHyperref() { - KILE_DEBUG_MAIN << "\tread config: init hyperref"; + KILE_DEBUG_MAIN << "\tread config: init hyperref"; - QString driver = "dvipdf,dvipdfm,dvips,dvipsone," - "dviwindo,hypertex,latex2html,pdftex," - "ps2pdf,tex4ht,textures,vtex"; - QStringList list = driver.split(','); + QString driver = "dvipdf,dvipdfm,dvips,dvipsone," + "dviwindo,hypertex,latex2html,pdftex," + "ps2pdf,tex4ht,textures,vtex"; + QStringList list = driver.split(','); - m_dictHyperrefDriver.clear(); - for (int i = 0; i < list.count(); ++i) { - m_dictHyperrefDriver[list[i]] = true; - } + m_dictHyperrefDriver.clear(); + for (int i = 0; i < list.count(); ++i) { + m_dictHyperrefDriver[list[i]] = true; + } } bool QuickDocument::isHyperrefDriver(const QString &name) { - return m_dictHyperrefDriver.contains(name); + return m_dictHyperrefDriver.contains(name); } ////////////////////////////// check for existing exntries ////////////////////////////// bool QuickDocument::isDocumentClass(const QString &name) { - for (int i = 0; i < m_cbDocumentClass->count(); ++i) { - if (m_cbDocumentClass->itemText(i) == name) - return true; - } - return false; + for (int i = 0; i < m_cbDocumentClass->count(); ++i) { + if (m_cbDocumentClass->itemText(i) == name) + return true; + } + return false; } bool QuickDocument::isDocumentClassOption(const QString &option) { - return isTreeWidgetEntry(m_lvClassOptions, option); + return isTreeWidgetEntry(m_lvClassOptions, option); } bool QuickDocument::isPackage(const QString &package) { - return isTreeWidgetEntry(m_lvPackages, package); + return isTreeWidgetEntry(m_lvPackages, package); } bool QuickDocument::isPackageOption(const QString &package, const QString &option) { - return isTreeWidgetChild(m_lvPackages, package, option); + return isTreeWidgetChild(m_lvPackages, package, option); } ////////////////////////////// print document template ////////////////////////////// void QuickDocument::printTemplate() { - KILE_DEBUG_MAIN << "==QuickDocument::printTemplate()============"; - - // get current document class - QString documentclass = m_cbDocumentClass->currentText(); - KILE_DEBUG_MAIN << "\tdocument class: " << documentclass; - - // build template - m_td.tagBegin = "\\documentclass"; - - // build options - QString options; - if (documentclass != "beamer") { - if (!m_cbPaperSize->currentText().isEmpty()) - options += stripDefault(m_cbPaperSize->currentText()) + ','; - } - - if (!m_cbTypefaceSize->currentText().isEmpty()) - options += stripDefault(m_cbTypefaceSize->currentText()) + ','; - - QTreeWidgetItemIterator it(m_lvClassOptions); - while (*it) { - if ((*it)->checkState(0) == Qt::Checked) { - options += (*it)->text(0) + ','; - } - ++it; - } - - if (! options.isEmpty()) - m_td.tagBegin += '[' + options.left(options.length() - 1) + ']'; - m_td.tagBegin += '{' + documentclass + "}\n\n"; - - - QString enc = m_cbEncoding->currentText(); - if (!enc.isEmpty()) - { - if (enc.indexOf("utf") != -1) - m_td.tagBegin += "\\usepackage{ucs}\n"; - m_td.tagBegin += "\\usepackage[" + enc + "]{inputenc}\n"; - } - if (documentclass != "beamer") { - printPackages(); - printHyperref(); - } else { - printBeamerTheme(); - printPackages(); - } - - if (!m_leAuthor->text().isEmpty()) - m_td.tagBegin += "\\author{" + m_leAuthor->text() + "}\n"; - if (!m_leTitle->text().isEmpty()) - m_td.tagBegin += "\\title{" + m_leTitle->text() + "}\n"; - if (!m_leDate->text().isEmpty()) - m_td.tagBegin += "\\date{" + m_leDate->text() + "}\n"; - m_td.tagBegin += '\n'; - - m_td.tagBegin += "\\begin{document}\n%E%C"; - - m_td.tagEnd = "\n\\end{document}\n"; - - KILE_DEBUG_MAIN << "m_td.tagBegin " << m_td.tagBegin; - KILE_DEBUG_MAIN << "m_td.tagEnd " << m_td.tagEnd; + KILE_DEBUG_MAIN << "==QuickDocument::printTemplate()============"; + + // get current document class + QString documentclass = m_cbDocumentClass->currentText(); + KILE_DEBUG_MAIN << "\tdocument class: " << documentclass; + + // build template + m_td.tagBegin = "\\documentclass"; + + // build options + QString options; + if (documentclass != "beamer") { + if (!m_cbPaperSize->currentText().isEmpty()) + options += stripDefault(m_cbPaperSize->currentText()) + ','; + } + + if (!m_cbTypefaceSize->currentText().isEmpty()) + options += stripDefault(m_cbTypefaceSize->currentText()) + ','; + + QTreeWidgetItemIterator it(m_lvClassOptions); + while (*it) { + if ((*it)->checkState(0) == Qt::Checked) { + options += (*it)->text(0) + ','; + } + ++it; + } + + if (! options.isEmpty()) + m_td.tagBegin += '[' + options.left(options.length() - 1) + ']'; + m_td.tagBegin += '{' + documentclass + "}\n\n"; + + + QString enc = m_cbEncoding->currentText(); + if (!enc.isEmpty()) + { + if (enc.indexOf("utf") != -1) + m_td.tagBegin += "\\usepackage{ucs}\n"; + m_td.tagBegin += "\\usepackage[" + enc + "]{inputenc}\n"; + } + if (documentclass != "beamer") { + printPackages(); + printHyperref(); + } else { + printBeamerTheme(); + printPackages(); + } + + if (!m_leAuthor->text().isEmpty()) + m_td.tagBegin += "\\author{" + m_leAuthor->text() + "}\n"; + if (!m_leTitle->text().isEmpty()) + m_td.tagBegin += "\\title{" + m_leTitle->text() + "}\n"; + if (!m_leDate->text().isEmpty()) + m_td.tagBegin += "\\date{" + m_leDate->text() + "}\n"; + m_td.tagBegin += '\n'; + + m_td.tagBegin += "\\begin{document}\n%E%C"; + + m_td.tagEnd = "\n\\end{document}\n"; + + KILE_DEBUG_MAIN << "m_td.tagBegin " << m_td.tagBegin; + KILE_DEBUG_MAIN << "m_td.tagEnd " << m_td.tagEnd; } void QuickDocument::printPackages() { - KILE_DEBUG_MAIN << "\tpackages"; - - m_currentHyperref = false; - m_hyperrefdriver.clear(); - m_hyperrefsetup.clear(); - - for (int i = 0; i < m_lvPackages->topLevelItemCount(); ++i) { - QTreeWidgetItem *cur = m_lvPackages->topLevelItem(i); - - if (cur->text(0) == "hyperref") { // manage hyperref package - m_currentHyperref = cur->checkState(0) == Qt::Checked; - for (int j = 0; j < cur->childCount(); ++j) { - QTreeWidgetItem *curchild = cur->child(j); - if (curchild->checkState(0) == Qt::Checked) { // manage hyperref option - if (isHyperrefDriver(curchild->text(0))) { // either hyperref driver - if (! m_hyperrefdriver.isEmpty()) - m_hyperrefdriver += ','; - m_hyperrefdriver += curchild->text(0); - } else { - QString value = curchild->text(1); // or another option - if (value != i18n("")) { - if (! m_hyperrefsetup.isEmpty()) - m_hyperrefsetup += ','; - m_hyperrefsetup += "%\n " + curchild->text(0) + '=' + getPackagesValue(curchild->text(1)); - } - } - } - } - } else - if (cur->checkState(0) == Qt::Checked) { // manage other package options - QString packageOptions; - for (int j = 0; j < cur->childCount(); ++j) { - QTreeWidgetItem *curchild = cur->child(j); - if (curchild->checkState(0) == Qt::Checked) { - QString optiontext; - if (m_dictPackagesEditable.contains(cur->text(0) + '!' + curchild->text(0))) { - QString value = curchild->text(1); - if (value != i18n("")) - optiontext = curchild->text(0) + '=' + getPackagesValue(curchild->text(1)); - } else - optiontext = curchild->text(0); - - if (! optiontext.isEmpty()) { - if (!packageOptions.isEmpty()) - packageOptions += ','; - packageOptions += optiontext; - } - } - } - - m_td.tagBegin += "\\usepackage"; - if (!packageOptions.isEmpty()) - m_td.tagBegin += '[' + packageOptions + ']'; - m_td.tagBegin += '{' + cur->text(0) + "}\n"; - } - } - m_td.tagBegin += '\n'; + KILE_DEBUG_MAIN << "\tpackages"; + + m_currentHyperref = false; + m_hyperrefdriver.clear(); + m_hyperrefsetup.clear(); + + for (int i = 0; i < m_lvPackages->topLevelItemCount(); ++i) { + QTreeWidgetItem *cur = m_lvPackages->topLevelItem(i); + + if (cur->text(0) == "hyperref") { // manage hyperref package + m_currentHyperref = cur->checkState(0) == Qt::Checked; + for (int j = 0; j < cur->childCount(); ++j) { + QTreeWidgetItem *curchild = cur->child(j); + if (curchild->checkState(0) == Qt::Checked) { // manage hyperref option + if (isHyperrefDriver(curchild->text(0))) { // either hyperref driver + if (! m_hyperrefdriver.isEmpty()) + m_hyperrefdriver += ','; + m_hyperrefdriver += curchild->text(0); + } else { + QString value = curchild->text(1); // or another option + if (value != i18n("")) { + if (! m_hyperrefsetup.isEmpty()) + m_hyperrefsetup += ','; + m_hyperrefsetup += "%\n " + curchild->text(0) + '=' + getPackagesValue(curchild->text(1)); + } + } + } + } + } else if (cur->checkState(0) == Qt::Checked) { // manage other package options + QString packageOptions; + for (int j = 0; j < cur->childCount(); ++j) { + QTreeWidgetItem *curchild = cur->child(j); + if (curchild->checkState(0) == Qt::Checked) { + QString optiontext; + if (m_dictPackagesEditable.contains(cur->text(0) + '!' + curchild->text(0))) { + QString value = curchild->text(1); + if (value != i18n("")) + optiontext = curchild->text(0) + '=' + getPackagesValue(curchild->text(1)); + } else + optiontext = curchild->text(0); + + if (! optiontext.isEmpty()) { + if (!packageOptions.isEmpty()) + packageOptions += ','; + packageOptions += optiontext; + } + } + } + + m_td.tagBegin += "\\usepackage"; + if (!packageOptions.isEmpty()) + m_td.tagBegin += '[' + packageOptions + ']'; + m_td.tagBegin += '{' + cur->text(0) + "}\n"; + } + } + m_td.tagBegin += '\n'; } void QuickDocument::printHyperref() { - if (! m_currentHyperref) - return; + if (! m_currentHyperref) + return; - KILE_DEBUG_MAIN << "\thyperref"; + KILE_DEBUG_MAIN << "\thyperref"; - // output hyperref package - m_td.tagBegin += "\\usepackage"; - if (! m_hyperrefdriver.isEmpty()) - m_td.tagBegin += '[' + m_hyperrefdriver + ']'; - m_td.tagBegin += "{hyperref}\n"; + // output hyperref package + m_td.tagBegin += "\\usepackage"; + if (! m_hyperrefdriver.isEmpty()) + m_td.tagBegin += '[' + m_hyperrefdriver + ']'; + m_td.tagBegin += "{hyperref}\n"; - // output hyperref options - if (! m_hyperrefsetup.isEmpty()) { - m_td.tagBegin += "\\hypersetup{" + m_hyperrefsetup + "%\n}\n"; - } + // output hyperref options + if (! m_hyperrefsetup.isEmpty()) { + m_td.tagBegin += "\\hypersetup{" + m_hyperrefsetup + "%\n}\n"; + } - m_td.tagBegin += '\n'; + m_td.tagBegin += '\n'; } void QuickDocument::printBeamerTheme() { - KILE_DEBUG_MAIN << "\tbeamer theme"; + KILE_DEBUG_MAIN << "\tbeamer theme"; - QString theme = m_cbPaperSize->currentText(); - QRegExp reg("(\\w+)\\s+\\((.*)\\)$"); + QString theme = m_cbPaperSize->currentText(); + QRegExp reg("(\\w+)\\s+\\((.*)\\)$"); - if (reg.indexIn(theme) >= 0) { - QStringList optionlist = reg.cap(2).split(','); - m_td.tagBegin += "\\usepackage[" + optionlist.join(",") + "]{beamertheme" + reg.cap(1) + "}\n\n"; - } - else { - m_td.tagBegin += "\\usepackage{beamertheme" + theme + "}\n\n"; - } + if (reg.indexIn(theme) >= 0) { + QStringList optionlist = reg.cap(2).split(','); + m_td.tagBegin += "\\usepackage[" + optionlist.join(",") + "]{beamertheme" + reg.cap(1) + "}\n\n"; + } + else { + m_td.tagBegin += "\\usepackage{beamertheme" + theme + "}\n\n"; + } } ////////////////////////////// Slots ////////////////////////////// void QuickDocument::slotAccepted() { - // get current class options - m_currentClass = m_cbDocumentClass->currentText(); - KILE_DEBUG_MAIN << "current class: " << m_currentClass; + // get current class options + m_currentClass = m_cbDocumentClass->currentText(); + KILE_DEBUG_MAIN << "current class: " << m_currentClass; - // save the checked options - m_dictDocumentClasses[m_currentClass][qd_SelectedOptions] = getClassOptions(); - KILE_DEBUG_MAIN << "save options: " << m_dictDocumentClasses[m_currentClass][qd_SelectedOptions]; + // save the checked options + m_dictDocumentClasses[m_currentClass][qd_SelectedOptions] = getClassOptions(); + KILE_DEBUG_MAIN << "save options: " << m_dictDocumentClasses[m_currentClass][qd_SelectedOptions]; - // build template - printTemplate(); + // build template + printTemplate(); - // update config file - writeConfig(); + // update config file + writeConfig(); } ////////////////////////////// slots: document class void QuickDocument::slotDocumentClassAdd() { - KILE_DEBUG_MAIN << "==QuickDocument::slotDocumentClassAdd()============"; - QStringList list; - list << i18n("Document Class") - << "label,edit,label,combobox,checkbox,checkbox" - << i18n("Please enter the new document &class:") - << QString() // 3 - << i18n("&Set all options from this standard class (optional):") - << ",article,book,letter,report,scrartcl,scrbook,scrreprt" // 5 - << i18n("Use standard &fontsizes") // 6 - << i18n("Use standard &papersizes") // 7 - ; - - if (inputDialog(list, qd_CheckNotEmpty | qd_CheckDocumentClass)) { - QString classname = list[3]; - - QStringList classlist; - if (list[5].isEmpty()) { // no base class - QString useFontsizes = (list[6] == "true") - ? "10pt,11pt,12pt" : ""; - QString usePapersizes = (list[7] == "true") - ? "a4paper,a5paper,b5paper,executivepaper,legalpaper,letterpaper" : ""; - KILE_DEBUG_MAIN << "\tadd document class: " << classname - << " fontsize=" << list[6] << " papersize=" << list[7]; - - // set default entries for the documentClass-dictionary - classlist << useFontsizes << usePapersizes << "" << ""; - } - else { // based on a standard class - // first get the first four parameters - classlist = m_dictDocumentClasses[list[5]]; - // then add all baseclass options - QStringList optionlist; - initStandardOptions(list[5], optionlist); - for (int i = 0; i < optionlist.count(); ++i) { - classlist.append(optionlist[i]); - } - } - - // insert the stringlist for this new document class - m_dictDocumentClasses[classname] = classlist; - - fillDocumentClassCombobox(); - - // add the new document class into the userClasslist and the documentClass-combobox - m_userClasslist.append(classname); - - // activate the new document class - m_cbDocumentClass->addItem(classname); - m_cbDocumentClass->setCurrentIndex(m_cbDocumentClass->count() - 1); - slotDocumentClassChanged(m_cbDocumentClass->count() - 1); - } + KILE_DEBUG_MAIN << "==QuickDocument::slotDocumentClassAdd()============"; + QStringList list; + list << i18n("Document Class") + << "label,edit,label,combobox,checkbox,checkbox" + << i18n("Please enter the new document &class:") + << QString() // 3 + << i18n("&Set all options from this standard class (optional):") + << ",article,book,letter,report,scrartcl,scrbook,scrreprt" // 5 + << i18n("Use standard &fontsizes") // 6 + << i18n("Use standard &papersizes") // 7 + ; + + if (inputDialog(list, qd_CheckNotEmpty | qd_CheckDocumentClass)) { + QString classname = list[3]; + + QStringList classlist; + if (list[5].isEmpty()) { // no base class + QString useFontsizes = (list[6] == "true") + ? "10pt,11pt,12pt" : ""; + QString usePapersizes = (list[7] == "true") + ? "a4paper,a5paper,b5paper,executivepaper,legalpaper,letterpaper" : ""; + KILE_DEBUG_MAIN << "\tadd document class: " << classname + << " fontsize=" << list[6] << " papersize=" << list[7]; + + // set default entries for the documentClass-dictionary + classlist << useFontsizes << usePapersizes << "" << ""; + } + else { // based on a standard class + // first get the first four parameters + classlist = m_dictDocumentClasses[list[5]]; + // then add all baseclass options + QStringList optionlist; + initStandardOptions(list[5], optionlist); + for (int i = 0; i < optionlist.count(); ++i) { + classlist.append(optionlist[i]); + } + } + + // insert the stringlist for this new document class + m_dictDocumentClasses[classname] = classlist; + + fillDocumentClassCombobox(); + + // add the new document class into the userClasslist and the documentClass-combobox + m_userClasslist.append(classname); + + // activate the new document class + m_cbDocumentClass->addItem(classname); + m_cbDocumentClass->setCurrentIndex(m_cbDocumentClass->count() - 1); + slotDocumentClassChanged(m_cbDocumentClass->count() - 1); + } } void QuickDocument::slotDocumentClassDelete() { - // get the name of the current class - QString documentclass = m_cbDocumentClass->currentText(); + // get the name of the current class + QString documentclass = m_cbDocumentClass->currentText(); - KILE_DEBUG_MAIN << "==QuickDocument::slotDocumentClassDelete()============"; - if (KMessageBox::warningContinueCancel(this, i18n("Do you want to remove \"%1\" from the document class list?", documentclass), - i18n("Remove Document Class")) == KMessageBox::Continue) { - KILE_DEBUG_MAIN << "\tlazy delete class: " << documentclass; + KILE_DEBUG_MAIN << "==QuickDocument::slotDocumentClassDelete()============"; + if (KMessageBox::warningContinueCancel(this, i18n("Do you want to remove \"%1\" from the document class list?", documentclass), + i18n("Remove Document Class")) == KMessageBox::Continue) { + KILE_DEBUG_MAIN << "\tlazy delete class: " << documentclass; - // remove this document class from the documentClass-dictionary - m_dictDocumentClasses.remove(documentclass); + // remove this document class from the documentClass-dictionary + m_dictDocumentClasses.remove(documentclass); - // mark this document class for deleting from config file (only with OK-Button) - if (m_deleteDocumentClasses.indexOf(documentclass) == -1) { - m_deleteDocumentClasses.append(documentclass); - } + // mark this document class for deleting from config file (only with OK-Button) + if (m_deleteDocumentClasses.indexOf(documentclass) == -1) { + m_deleteDocumentClasses.append(documentclass); + } - // remove it from the list of userclasses - m_userClasslist.removeAll(documentclass); + // remove it from the list of userclasses + m_userClasslist.removeAll(documentclass); - // and finally remove it from the combobox - int i = m_cbDocumentClass->currentIndex(); - m_cbDocumentClass->removeItem(i); + // and finally remove it from the combobox + int i = m_cbDocumentClass->currentIndex(); + m_cbDocumentClass->removeItem(i); - // init a new document class - m_currentClass = m_cbDocumentClass->currentText(); - KILE_DEBUG_MAIN << "\tchange class: --> " << m_currentClass; - initDocumentClass(); - } + // init a new document class + m_currentClass = m_cbDocumentClass->currentText(); + KILE_DEBUG_MAIN << "\tchange class: --> " << m_currentClass; + initDocumentClass(); + } } void QuickDocument::slotDocumentClassChanged(int index) { - KILE_DEBUG_MAIN << "==QuickDocument::slotDocumentClassChanged()============"; - if (m_cbDocumentClass->itemText(index).isEmpty()) { - KILE_DEBUG_MAIN << "\tempty"; - return; - } + KILE_DEBUG_MAIN << "==QuickDocument::slotDocumentClassChanged()============"; + if (m_cbDocumentClass->itemText(index).isEmpty()) { + KILE_DEBUG_MAIN << "\tempty"; + return; + } - // get old and new document class - QString oldclass = m_currentClass; - m_currentClass = m_cbDocumentClass->itemText(index); - KILE_DEBUG_MAIN << "\tchange class: " << oldclass << " --> " << m_currentClass; + // get old and new document class + QString oldclass = m_currentClass; + m_currentClass = m_cbDocumentClass->itemText(index); + KILE_DEBUG_MAIN << "\tchange class: " << oldclass << " --> " << m_currentClass; - // save the checked options - m_dictDocumentClasses[oldclass][qd_SelectedOptions] = getClassOptions(); - KILE_DEBUG_MAIN << "\tsave options: " << m_dictDocumentClasses[oldclass][qd_SelectedOptions]; + // save the checked options + m_dictDocumentClasses[oldclass][qd_SelectedOptions] = getClassOptions(); + KILE_DEBUG_MAIN << "\tsave options: " << m_dictDocumentClasses[oldclass][qd_SelectedOptions]; - // init the new document class - initDocumentClass(); + // init the new document class + initDocumentClass(); } void QuickDocument::slotTypefaceSizeAdd() { - KILE_DEBUG_MAIN << "==QuickDocument::slotTypefaceSizeAdd()============"; - QStringList list; - list << i18n("Add Fontsize") - << "label,edit" - << i18n("Please enter the &fontsizes (comma-separated list):") - << QString() // 3 - ; + KILE_DEBUG_MAIN << "==QuickDocument::slotTypefaceSizeAdd()============"; + QStringList list; + list << i18n("Add Fontsize") + << "label,edit" + << i18n("Please enter the &fontsizes (comma-separated list):") + << QString() // 3 + ; - if (inputDialog(list, qd_CheckNotEmpty | qd_CheckFontsize)) { - KILE_DEBUG_MAIN << "\tadd fontsize: " << list[3]; - addComboboxEntries(m_cbTypefaceSize, "fontsize", list[3]); + if (inputDialog(list, qd_CheckNotEmpty | qd_CheckFontsize)) { + KILE_DEBUG_MAIN << "\tadd fontsize: " << list[3]; + addComboboxEntries(m_cbTypefaceSize, "fontsize", list[3]); - // save the new list of fontsizes - m_dictDocumentClasses[m_currentClass][qd_Fontsizes] = getComboxboxList(m_cbTypefaceSize); + // save the new list of fontsizes + m_dictDocumentClasses[m_currentClass][qd_Fontsizes] = getComboxboxList(m_cbTypefaceSize); - // enable/disable buttons to add or delete entries - slotEnableButtons(); - } + // enable/disable buttons to add or delete entries + slotEnableButtons(); + } } void QuickDocument::slotTypefaceSizeDelete() { - if (KMessageBox::warningContinueCancel(this, i18n("Do you want to remove \"%1\" from the fontsize list?", m_cbTypefaceSize->currentText()), i18n("Remove Fontsize")) == KMessageBox::Continue) - { - int i = m_cbTypefaceSize->currentIndex(); - m_cbTypefaceSize->removeItem(i); + if (KMessageBox::warningContinueCancel(this, i18n("Do you want to remove \"%1\" from the fontsize list?", m_cbTypefaceSize->currentText()), i18n("Remove Fontsize")) == KMessageBox::Continue) + { + int i = m_cbTypefaceSize->currentIndex(); + m_cbTypefaceSize->removeItem(i); - // save the new list of fontsizes - m_dictDocumentClasses[m_currentClass][qd_Fontsizes] = getComboxboxList(m_cbTypefaceSize); + // save the new list of fontsizes + m_dictDocumentClasses[m_currentClass][qd_Fontsizes] = getComboxboxList(m_cbTypefaceSize); - // enable/disable buttons to add or delete entries - slotEnableButtons(); - } + // enable/disable buttons to add or delete entries + slotEnableButtons(); + } } void QuickDocument::slotPaperSizeAdd() { - KILE_DEBUG_MAIN << "==QuickDocument::slotPaperSizeAdd()============"; - QStringList list; - list << i18n("Add Papersize") - << "label,edit" - << i18n("Please enter the &papersizes (comma-separated list):") - << QString() // 3 - ; + KILE_DEBUG_MAIN << "==QuickDocument::slotPaperSizeAdd()============"; + QStringList list; + list << i18n("Add Papersize") + << "label,edit" + << i18n("Please enter the &papersizes (comma-separated list):") + << QString() // 3 + ; - if (inputDialog(list, qd_CheckNotEmpty | qd_CheckPapersize)) { - KILE_DEBUG_MAIN << "\tadd papersize: " << list[3]; - addComboboxEntries(m_cbPaperSize, "papersize", list[3]); + if (inputDialog(list, qd_CheckNotEmpty | qd_CheckPapersize)) { + KILE_DEBUG_MAIN << "\tadd papersize: " << list[3]; + addComboboxEntries(m_cbPaperSize, "papersize", list[3]); - // save the new list of papersizes - m_dictDocumentClasses[m_currentClass][qd_Papersizes] = getComboxboxList(m_cbPaperSize); + // save the new list of papersizes + m_dictDocumentClasses[m_currentClass][qd_Papersizes] = getComboxboxList(m_cbPaperSize); - // enable/disable buttons to add or delete entries - slotEnableButtons(); - } + // enable/disable buttons to add or delete entries + slotEnableButtons(); + } } void QuickDocument::slotPaperSizeDelete() { - if (KMessageBox::warningContinueCancel(this, i18n("Do you want to remove \"%1\" from the papersize list?", m_cbPaperSize->currentText()), i18n("Remove Papersize")) == KMessageBox::Continue) - { - int i = m_cbPaperSize->currentIndex(); - m_cbPaperSize->removeItem(i); + if (KMessageBox::warningContinueCancel(this, i18n("Do you want to remove \"%1\" from the papersize list?", m_cbPaperSize->currentText()), i18n("Remove Papersize")) == KMessageBox::Continue) + { + int i = m_cbPaperSize->currentIndex(); + m_cbPaperSize->removeItem(i); - // save the new list of papersizes - m_dictDocumentClasses[m_currentClass][qd_Papersizes] = getComboxboxList(m_cbPaperSize); + // save the new list of papersizes + m_dictDocumentClasses[m_currentClass][qd_Papersizes] = getComboxboxList(m_cbPaperSize); - // enable/disable buttons to add or delete entries - slotEnableButtons(); - } + // enable/disable buttons to add or delete entries + slotEnableButtons(); + } } ////////////////////////////// slots: document class button ////////////////////////////// void QuickDocument::slotClassOptionAdd() { - KILE_DEBUG_MAIN << "==QuickDocument::slotClassOptionAdd()============"; - QStringList list; - list << i18n("Add Option") - << "label,edit,label,edit,checkbox" - << i18n("Name of &option:") - << QString() // 3 - << i18n("&Description:") - << QString() // 5 - << i18n("&Select this option") // 6 - ; - - if (inputDialog(list, qd_CheckNotEmpty | qd_CheckClassOption)) { - // get results - QString option = list[3]; - QString description = list[5]; - bool check = (list[6] == "true"); - - // add class option - KILE_DEBUG_MAIN << "\tadd option: " << option << " (" << description << ") checked=" << list[6]; - QTreeWidgetItem *twi = new QTreeWidgetItem(m_lvClassOptions, QStringList() << option << description); - twi->setFlags(twi->flags() | Qt::ItemIsUserCheckable); - twi->setCheckState(0, check ? Qt::Checked : Qt::Unchecked); - - // update dictionary - updateClassOptions(); - } + KILE_DEBUG_MAIN << "==QuickDocument::slotClassOptionAdd()============"; + QStringList list; + list << i18n("Add Option") + << "label,edit,label,edit,checkbox" + << i18n("Name of &option:") + << QString() // 3 + << i18n("&Description:") + << QString() // 5 + << i18n("&Select this option") // 6 + ; + + if (inputDialog(list, qd_CheckNotEmpty | qd_CheckClassOption)) { + // get results + QString option = list[3]; + QString description = list[5]; + bool check = (list[6] == "true"); + + // add class option + KILE_DEBUG_MAIN << "\tadd option: " << option << " (" << description << ") checked=" << list[6]; + QTreeWidgetItem *twi = new QTreeWidgetItem(m_lvClassOptions, QStringList() << option << description); + twi->setFlags(twi->flags() | Qt::ItemIsUserCheckable); + twi->setCheckState(0, check ? Qt::Checked : Qt::Unchecked); + + // update dictionary + updateClassOptions(); + } } void QuickDocument::slotClassOptionEdit() { - if (m_lvClassOptions->selectedItems().count() == 0) - return; + if (m_lvClassOptions->selectedItems().count() == 0) + return; - QTreeWidgetItem *cur = m_lvClassOptions->selectedItems()[0]; + QTreeWidgetItem *cur = m_lvClassOptions->selectedItems()[0]; - KILE_DEBUG_MAIN << "==QuickDocument::slotClassOptionEdit()============"; - QStringList list; - list << i18n("Edit Option") - << "label,edit-r,label,edit" - << i18n("Name of &option:") - << cur->text(0) - << i18n("&Description:") - << stripDefault(cur->text(1)) // 5 - ; + KILE_DEBUG_MAIN << "==QuickDocument::slotClassOptionEdit()============"; + QStringList list; + list << i18n("Edit Option") + << "label,edit-r,label,edit" + << i18n("Name of &option:") + << cur->text(0) + << i18n("&Description:") + << stripDefault(cur->text(1)) // 5 + ; - //if ( inputDialog(list,qd_CheckNotEmpty | qd_CheckClassOption) ) { - if (inputDialog(list)) { - // get results - //QString option = list[3]; - QString description = list[5]; + //if ( inputDialog(list,qd_CheckNotEmpty | qd_CheckClassOption) ) { + if (inputDialog(list)) { + // get results + //QString option = list[3]; + QString description = list[5]; - // set changed class option - KILE_DEBUG_MAIN << "\tedit option: " << cur->text(0) << " (" << description << ")"; - //cur->setText(0, option); - cur->setText(1, description); + // set changed class option + KILE_DEBUG_MAIN << "\tedit option: " << cur->text(0) << " (" << description << ")"; + //cur->setText(0, option); + cur->setText(1, description); - // update dictionary - updateClassOptions(); - } + // update dictionary + updateClassOptions(); + } } void QuickDocument::slotClassOptionDelete() { - KILE_DEBUG_MAIN << "==QuickDocument::slotClassOptionDelete()============"; - if (m_lvClassOptions->selectedItems().count() > 0 && (KMessageBox::warningContinueCancel(this, i18n("Do you want to delete this class option?"), i18n("Delete")) == KMessageBox::Continue)) { - QTreeWidgetItem *cur = m_lvClassOptions->selectedItems()[0]; + KILE_DEBUG_MAIN << "==QuickDocument::slotClassOptionDelete()============"; + if (m_lvClassOptions->selectedItems().count() > 0 && (KMessageBox::warningContinueCancel(this, i18n("Do you want to delete this class option?"), i18n("Delete")) == KMessageBox::Continue)) { + QTreeWidgetItem *cur = m_lvClassOptions->selectedItems()[0]; - KILE_DEBUG_MAIN << "\tdelete option: " << cur->text(0) << " (" << cur->text(1) << ")"; - m_lvClassOptions->takeTopLevelItem(m_lvClassOptions->indexOfTopLevelItem(cur)); + KILE_DEBUG_MAIN << "\tdelete option: " << cur->text(0) << " (" << cur->text(1) << ")"; + m_lvClassOptions->takeTopLevelItem(m_lvClassOptions->indexOfTopLevelItem(cur)); - // update dictionary - updateClassOptions(); - } + // update dictionary + updateClassOptions(); + } } void QuickDocument::slotOptionDoubleClicked(QTreeWidgetItem *item, int column) { - Q_UNUSED(column); + Q_UNUSED(column); - item->setCheckState(0, item->checkState(0) == Qt::Checked ? Qt::Unchecked : Qt::Checked); + item->setCheckState(0, item->checkState(0) == Qt::Checked ? Qt::Unchecked : Qt::Checked); } ////////////////////////////// slots: packages ////////////////////////////// void QuickDocument::slotPackageAdd() { - KILE_DEBUG_MAIN << "==QuickDocument::slotPackageAdd()============"; - QStringList list; - list << i18n("Add Package") - << "label,edit,label,edit,checkbox" - << i18n("&Package:") - << QString() // 3 - << i18n("&Description:") - << QString() // 5 - << i18n("&Select this package") // 6 - ; - - if (inputDialog(list, qd_CheckNotEmpty | qd_CheckPackage)) { - KILE_DEBUG_MAIN << "\tadd package: " << list[3] << " (" << list[5] << ") checked=" << list[6]; - QTreeWidgetItem *cli = new QTreeWidgetItem(m_lvPackages, QStringList() << list[3] << "" << list[5]); - cli->setFlags(cli->flags() | Qt::ItemIsUserCheckable); - cli->setCheckState(0, list[6] == "true" ? Qt::Checked : Qt::Unchecked); - } + KILE_DEBUG_MAIN << "==QuickDocument::slotPackageAdd()============"; + QStringList list; + list << i18n("Add Package") + << "label,edit,label,edit,checkbox" + << i18n("&Package:") + << QString() // 3 + << i18n("&Description:") + << QString() // 5 + << i18n("&Select this package") // 6 + ; + + if (inputDialog(list, qd_CheckNotEmpty | qd_CheckPackage)) { + KILE_DEBUG_MAIN << "\tadd package: " << list[3] << " (" << list[5] << ") checked=" << list[6]; + QTreeWidgetItem *cli = new QTreeWidgetItem(m_lvPackages, QStringList() << list[3] << "" << list[5]); + cli->setFlags(cli->flags() | Qt::ItemIsUserCheckable); + cli->setCheckState(0, list[6] == "true" ? Qt::Checked : Qt::Unchecked); + } } void QuickDocument::slotPackageAddOption() { - if (m_lvPackages->selectedItems().count() == 0) - return; - - QTreeWidgetItem *cur = m_lvPackages->selectedItems()[0]; - - KILE_DEBUG_MAIN << "==QuickDocument::packageAddOption()============"; - QStringList list; - list << i18n("Add Option") - << "label,edit,checkbox,label,edit,label,edit,label,edit,checkbox" - << i18n("&Option:") + " (" + i18n("package:") + ' ' + cur->text(0) + ')' - << QString() // 3 - << i18n("&Editable") // 4 - << i18n("De&fault value:") - << QString() // 6 - << i18n("&Value:") - << QString() // 8 - << i18n("&Description:") - << QString() // 10 - << i18n("&Select this option") // 11 - ; - - if (!cur->parent() && inputDialog(list, qd_CheckNotEmpty | qd_CheckPackageOption)) { - KILE_DEBUG_MAIN << "\tadd option: " << list[3] << " (" << list[10] << ") checked=" << list[11]; - - QTreeWidgetItem *cli; - if (list[4] == "true") { - cli = insertEditableTreeWidget(cur, list[3], list[10], list[8], list[6]); - } else { - cli = new QTreeWidgetItem(cur, QStringList() << list[3] << "" << list[10]); - cli->setFlags(cli->flags() | Qt::ItemIsUserCheckable); - cli->setCheckState(0, Qt::Unchecked); - } - if (list[11] == "true") - cli->setCheckState(0, Qt::Checked); - cur->setExpanded(true); - } + if (m_lvPackages->selectedItems().count() == 0) + return; + + QTreeWidgetItem *cur = m_lvPackages->selectedItems()[0]; + + KILE_DEBUG_MAIN << "==QuickDocument::packageAddOption()============"; + QStringList list; + list << i18n("Add Option") + << "label,edit,checkbox,label,edit,label,edit,label,edit,checkbox" + << i18n("&Option:") + " (" + i18n("package:") + ' ' + cur->text(0) + ')' + << QString() // 3 + << i18n("&Editable") // 4 + << i18n("De&fault value:") + << QString() // 6 + << i18n("&Value:") + << QString() // 8 + << i18n("&Description:") + << QString() // 10 + << i18n("&Select this option") // 11 + ; + + if (!cur->parent() && inputDialog(list, qd_CheckNotEmpty | qd_CheckPackageOption)) { + KILE_DEBUG_MAIN << "\tadd option: " << list[3] << " (" << list[10] << ") checked=" << list[11]; + + QTreeWidgetItem *cli; + if (list[4] == "true") { + cli = insertEditableTreeWidget(cur, list[3], list[10], list[8], list[6]); + } else { + cli = new QTreeWidgetItem(cur, QStringList() << list[3] << "" << list[10]); + cli->setFlags(cli->flags() | Qt::ItemIsUserCheckable); + cli->setCheckState(0, Qt::Unchecked); + } + if (list[11] == "true") + cli->setCheckState(0, Qt::Checked); + cur->setExpanded(true); + } } void QuickDocument::slotPackageEdit() { - if (m_lvPackages->selectedItems().count() == 0) - return; + if (m_lvPackages->selectedItems().count() == 0) + return; - QTreeWidgetItem *cur = m_lvPackages->selectedItems()[0]; + QTreeWidgetItem *cur = m_lvPackages->selectedItems()[0]; - KILE_DEBUG_MAIN << "==QuickDocument::slotPackageEdit()============"; - bool editableOption; - QString caption, labelText, optionname; + KILE_DEBUG_MAIN << "==QuickDocument::slotPackageEdit()============"; + bool editableOption; + QString caption, labelText, optionname; - if (cur->parent()) { + if (cur->parent()) { // checkmode = qd_CheckPackageOption; - caption = i18n("Edit Option"); - labelText = i18n("Op&tion:") + " (" + i18n("package:") + ' ' + cur->parent()->text(0) + ')'; - optionname = cur->parent()->text(0) + '!' + cur->text(0); - editableOption = m_dictPackagesEditable.contains(optionname); - } else { + caption = i18n("Edit Option"); + labelText = i18n("Op&tion:") + " (" + i18n("package:") + ' ' + cur->parent()->text(0) + ')'; + optionname = cur->parent()->text(0) + '!' + cur->text(0); + editableOption = m_dictPackagesEditable.contains(optionname); + } else { // checkmode = qd_CheckPackage; - caption = i18n("Edit Package"); - labelText = i18n("&Package:"); - optionname.clear(); - editableOption = false; - } - - // create one of three different dialogs; edit package, edit editable option, edit option - QStringList list; - list << caption; - if (editableOption) { - QString defaultvalue = (m_dictPackagesDefaultvalues.contains(optionname)) - ? m_dictPackagesDefaultvalues[optionname] - : QString(); - QString value = (cur->text(1) == i18n("")) - ? defaultvalue : getPackagesValue(cur->text(1)); - - list << "label,edit-r,label,edit-r,label,edit,label,edit" - << labelText - << cur->text(0) // 3 - << i18n("De&fault value:") - << defaultvalue // 5 - << i18n("&Value:") - << value // 7 - << i18n("&Description:") - << stripPackageDefault(optionname, cur->text(2)) // 9 - ; - } else { - list << "label,edit-r,label,edit" - << labelText - << cur->text(0) // 3 - << i18n("&Description:") - << cur->text(2) // 5 - ; - } - - if (inputDialog(list)) { - if (editableOption) { - KILE_DEBUG_MAIN << "\tedit package: " - << list[3] - << " (" << list[7] << ") " - << " (" << list[9] << ")"; - cur->setText(0, list[3]); - setPackagesValue(cur, optionname, list[7]); - cur->setText(2, addPackageDefault(optionname, list[9])); - } else { - KILE_DEBUG_MAIN << "\tedit package: " << list[3] << " (" << list[5] << ")"; - cur->setText(0, list[3]); - cur->setText(2, list[5]); - } - } + caption = i18n("Edit Package"); + labelText = i18n("&Package:"); + optionname.clear(); + editableOption = false; + } + + // create one of three different dialogs; edit package, edit editable option, edit option + QStringList list; + list << caption; + if (editableOption) { + QString defaultvalue = (m_dictPackagesDefaultvalues.contains(optionname)) + ? m_dictPackagesDefaultvalues[optionname] + : QString(); + QString value = (cur->text(1) == i18n("")) + ? defaultvalue : getPackagesValue(cur->text(1)); + + list << "label,edit-r,label,edit-r,label,edit,label,edit" + << labelText + << cur->text(0) // 3 + << i18n("De&fault value:") + << defaultvalue // 5 + << i18n("&Value:") + << value // 7 + << i18n("&Description:") + << stripPackageDefault(optionname, cur->text(2)) // 9 + ; + } else { + list << "label,edit-r,label,edit" + << labelText + << cur->text(0) // 3 + << i18n("&Description:") + << cur->text(2) // 5 + ; + } + + if (inputDialog(list)) { + if (editableOption) { + KILE_DEBUG_MAIN << "\tedit package: " + << list[3] + << " (" << list[7] << ") " + << " (" << list[9] << ")"; + cur->setText(0, list[3]); + setPackagesValue(cur, optionname, list[7]); + cur->setText(2, addPackageDefault(optionname, list[9])); + } else { + KILE_DEBUG_MAIN << "\tedit package: " << list[3] << " (" << list[5] << ")"; + cur->setText(0, list[3]); + cur->setText(2, list[5]); + } + } } void QuickDocument::slotPackageDelete() { - if (m_lvPackages->selectedItems().count() == 0) - return; + if (m_lvPackages->selectedItems().count() == 0) + return; - QTreeWidgetItem *cur = m_lvPackages->selectedItems()[0]; + QTreeWidgetItem *cur = m_lvPackages->selectedItems()[0]; - bool packageoption; - QString message, optionname; - if (cur->parent()) { - packageoption = true; - message = i18n("Do you want to delete this package option?"); - optionname = cur->parent()->text(0) + '!' + cur->text(0); - } else { - packageoption = false; - message = i18n("Do you want to delete this package?"); - optionname = cur->text(0); - } + bool packageoption; + QString message, optionname; + if (cur->parent()) { + packageoption = true; + message = i18n("Do you want to delete this package option?"); + optionname = cur->parent()->text(0) + '!' + cur->text(0); + } else { + packageoption = false; + message = i18n("Do you want to delete this package?"); + optionname = cur->text(0); + } - if (KMessageBox::warningContinueCancel(this, message, i18n("Delete")) == KMessageBox::Continue) { - while (cur->childCount() > 0) { - cur->takeChild(0); - } - m_lvPackages->takeTopLevelItem(m_lvPackages->indexOfTopLevelItem(cur)); + if (KMessageBox::warningContinueCancel(this, message, i18n("Delete")) == KMessageBox::Continue) { + while (cur->childCount() > 0) { + cur->takeChild(0); + } + m_lvPackages->takeTopLevelItem(m_lvPackages->indexOfTopLevelItem(cur)); - // also delete entries for editable package option - if (packageoption && m_dictPackagesEditable.contains(optionname)) { - m_dictPackagesEditable.remove(optionname); - if (m_dictPackagesDefaultvalues.contains(optionname)) - m_dictPackagesDefaultvalues.remove(optionname); - } - } + // also delete entries for editable package option + if (packageoption && m_dictPackagesEditable.contains(optionname)) { + m_dictPackagesEditable.remove(optionname); + if (m_dictPackagesDefaultvalues.contains(optionname)) + m_dictPackagesDefaultvalues.remove(optionname); + } + } } void QuickDocument::slotPackageReset() { - if (KMessageBox::warningContinueCancel(this, i18n("Do you want to reset this package list?"), i18n("Reset Package List")) == KMessageBox::Continue) - { - KILE_DEBUG_MAIN << "\treset packages"; + if (KMessageBox::warningContinueCancel(this, i18n("Do you want to reset this package list?"), i18n("Reset Package List")) == KMessageBox::Continue) + { + KILE_DEBUG_MAIN << "\treset packages"; - initPackages(); - slotEnableButtons(); - } + initPackages(); + slotEnableButtons(); + } } void QuickDocument::slotCheckParent(QTreeWidgetItem *item) { - if (item && item->checkState(0) == Qt::Checked && item->parent()) { - item->parent()->setCheckState(0, Qt::Checked); - } + if (item && item->checkState(0) == Qt::Checked && item->parent()) { + item->parent()->setCheckState(0, Qt::Checked); + } } void QuickDocument::slotPackageDoubleClicked(QTreeWidgetItem *item) { - if (item && item->parent()) { - QString option = item->parent()->text(0) + '!' + item->text(0); - if (m_dictPackagesEditable.contains(option)) - slotPackageEdit(); - } + if (item && item->parent()) { + QString option = item->parent()->text(0) + '!' + item->text(0); + if (m_dictPackagesEditable.contains(option)) + slotPackageEdit(); + } } ////////////////////////////// button states ////////////////////////////// void QuickDocument::slotEnableButtons() { - bool enable; + bool enable; - enable = (! isStandardClass(m_currentClass)); + enable = (! isStandardClass(m_currentClass)); - // add/delete button - m_btnDocumentClassDelete->setEnabled(enable); - m_btnTypefaceSizeAdd->setEnabled(enable); - m_btnTypefaceSizeDelete->setEnabled(enable && m_cbTypefaceSize->count() > 0); - m_btnPaperSizeAdd->setEnabled(enable); - m_btnPaperSizeDelete->setEnabled(enable && m_cbPaperSize->count() > 0); + // add/delete button + m_btnDocumentClassDelete->setEnabled(enable); + m_btnTypefaceSizeAdd->setEnabled(enable); + m_btnTypefaceSizeDelete->setEnabled(enable && m_cbTypefaceSize->count() > 0); + m_btnPaperSizeAdd->setEnabled(enable); + m_btnPaperSizeDelete->setEnabled(enable && m_cbPaperSize->count() > 0); - // class options - m_btnClassOptionsAdd->setEnabled(enable); - enable = (enable && (m_lvClassOptions->selectedItems().count() != 0)); - m_btnClassOptionsEdit->setEnabled(enable); - m_btnClassOptionsDelete->setEnabled(enable); + // class options + m_btnClassOptionsAdd->setEnabled(enable); + enable = (enable && (m_lvClassOptions->selectedItems().count() != 0)); + m_btnClassOptionsEdit->setEnabled(enable); + m_btnClassOptionsDelete->setEnabled(enable); - // packeges - if (m_lvPackages->selectedItems().count() > 0 && m_lvPackages->selectedItems()[0]->text(0) != "hyperref") { - m_btnPackagesEdit->setEnabled(true); - m_btnPackagesDelete->setEnabled(true); - if (m_lvPackages->selectedItems()[0]->parent()) - m_btnPackagesAddOption->setEnabled(false); - else - m_btnPackagesAddOption->setEnabled(true); - } else { - m_btnPackagesEdit->setEnabled(false); - m_btnPackagesDelete->setEnabled(false); - m_btnPackagesAddOption->setEnabled(false); - } + // packeges + if (m_lvPackages->selectedItems().count() > 0 && m_lvPackages->selectedItems()[0]->text(0) != "hyperref") { + m_btnPackagesEdit->setEnabled(true); + m_btnPackagesDelete->setEnabled(true); + if (m_lvPackages->selectedItems()[0]->parent()) + m_btnPackagesAddOption->setEnabled(false); + else + m_btnPackagesAddOption->setEnabled(true); + } else { + m_btnPackagesEdit->setEnabled(false); + m_btnPackagesDelete->setEnabled(false); + m_btnPackagesAddOption->setEnabled(false); + } } ////////////////////////////// input dialog ////////////////////////////// // A variable input dialog, whose widgets are determind by the entries of a stringlist. // Entry 1 is always the label for the main lineedit, entry 2 the main lineedit. All // other objects are optionale and their return values are not checked. // 0 : caption (input: always) // 1 : comma separated list of Qt widgets (label,checkbox,edit,edit-r) // 2ff : strings for Qt widgets bool QuickDocument::inputDialog(QStringList &list, int check) { - QuickDocumentInputDialog *dialog = new QuickDocumentInputDialog(list, check, this, "inputDialog"); + QuickDocumentInputDialog *dialog = new QuickDocumentInputDialog(list, check, this, "inputDialog"); - bool result = false; - if (dialog->exec()) { - dialog->getResults(list); - result = true; - } + bool result = false; + if (dialog->exec()) { + dialog->getResults(list); + result = true; + } - delete dialog; - return result; + delete dialog; + return result; } QuickDocumentInputDialog::QuickDocumentInputDialog(const QStringList &list, int check, - QuickDocument *parent, const char *name) - : QDialog(parent) - , m_parent(parent) - , m_check(check) -{ - setObjectName(name); - setWindowTitle(list[0]); - setModal(true); - QVBoxLayout *mainLayout = new QVBoxLayout; - setLayout(mainLayout); - - QWidget *page = new QWidget(this); - mainLayout->addWidget(page); - QVBoxLayout *vl = new QVBoxLayout(); - page->setLayout(vl); - - int firstlinedit = -1; - m_description = list[1].split(','); - for (int i = 0; i < m_description.count(); ++i) { - // create the object - if (m_description[i] == "label") { - m_objectlist.append(new QLabel(list[i+2], page)); - } - else - if (m_description[i] == "checkbox") { - m_objectlist.append(new QCheckBox(list[i+2], page)); - } - else - if (m_description[i] == "combobox") { - KComboBox *combobox = new KComboBox(page); - mainLayout->addWidget(combobox); - combobox->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Minimum); - combobox->setDuplicatesEnabled(false); - combobox->addItems(list[i+2].split(',', QString::KeepEmptyParts)); - if (i > 0 && m_description[i-1] == "label") { - ((QLabel *)m_objectlist[i-1])->setBuddy(combobox); - } - m_objectlist.append(combobox); - } - else { - m_objectlist.append(new QLineEdit(list[i+2], page)); - if (m_description[i] == "edit-r") { - ((QLineEdit *)m_objectlist[i])->setReadOnly(true); - } - else - if (firstlinedit == -1) { - firstlinedit = i; - } - if (i > 0 && m_description[i-1] == "label") { - ((QLabel *)m_objectlist[i-1])->setBuddy(m_objectlist[i]); - } - } - - // insert the new object into the layout - vl->addWidget(m_objectlist[i]); - } - - if (firstlinedit != -1) { - m_objectlist[firstlinedit]->setFocus(); - } - vl->addStretch(1); - - QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok|QDialogButtonBox::Cancel); - QPushButton *okButton = buttonBox->button(QDialogButtonBox::Ok); - okButton->setDefault(true); - okButton->setShortcut(Qt::CTRL | Qt::Key_Return); - connect(buttonBox, &QDialogButtonBox::accepted, this, &QDialog::accept); - connect(buttonBox, &QDialogButtonBox::rejected, this, &QDialog::reject); - connect(this, &QDialog::accepted, this, &QuickDocumentInputDialog::slotAccepted); - mainLayout->addWidget(buttonBox); - - page->setMinimumWidth(350); + QuickDocument *parent, const char *name) + : QDialog(parent) + , m_parent(parent) + , m_check(check) +{ + setObjectName(name); + setWindowTitle(list[0]); + setModal(true); + QVBoxLayout *mainLayout = new QVBoxLayout; + setLayout(mainLayout); + + QWidget *page = new QWidget(this); + mainLayout->addWidget(page); + QVBoxLayout *vl = new QVBoxLayout(); + page->setLayout(vl); + + int firstlinedit = -1; + m_description = list[1].split(','); + for (int i = 0; i < m_description.count(); ++i) { + // create the object + if (m_description[i] == "label") { + m_objectlist.append(new QLabel(list[i+2], page)); + } + else if (m_description[i] == "checkbox") { + m_objectlist.append(new QCheckBox(list[i+2], page)); + } + else if (m_description[i] == "combobox") { + KComboBox *combobox = new KComboBox(page); + mainLayout->addWidget(combobox); + combobox->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Minimum); + combobox->setDuplicatesEnabled(false); + combobox->addItems(list[i+2].split(',', QString::KeepEmptyParts)); + if (i > 0 && m_description[i-1] == "label") { + ((QLabel *)m_objectlist[i-1])->setBuddy(combobox); + } + m_objectlist.append(combobox); + } + else { + m_objectlist.append(new QLineEdit(list[i+2], page)); + if (m_description[i] == "edit-r") { + ((QLineEdit *)m_objectlist[i])->setReadOnly(true); + } + else if (firstlinedit == -1) { + firstlinedit = i; + } + if (i > 0 && m_description[i-1] == "label") { + ((QLabel *)m_objectlist[i-1])->setBuddy(m_objectlist[i]); + } + } + + // insert the new object into the layout + vl->addWidget(m_objectlist[i]); + } + + if (firstlinedit != -1) { + m_objectlist[firstlinedit]->setFocus(); + } + vl->addStretch(1); + + QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok|QDialogButtonBox::Cancel); + QPushButton *okButton = buttonBox->button(QDialogButtonBox::Ok); + okButton->setDefault(true); + okButton->setShortcut(Qt::CTRL | Qt::Key_Return); + connect(buttonBox, &QDialogButtonBox::accepted, this, &QDialog::accept); + connect(buttonBox, &QDialogButtonBox::rejected, this, &QDialog::reject); + connect(this, &QDialog::accepted, this, &QuickDocumentInputDialog::slotAccepted); + mainLayout->addWidget(buttonBox); + + page->setMinimumWidth(350); } QuickDocumentInputDialog::~QuickDocumentInputDialog() {} void QuickDocumentInputDialog::getResults(QStringList &list) { - for (int i = 0; i < m_description.count(); ++i) { - if (m_description[i] == "label") { - list[i+2] = ((QLabel *)m_objectlist[i])->text(); - } - else - if (m_description[i] == "checkbox") { - list[i+2] = (((QCheckBox *)m_objectlist[i])->isChecked()) ? "true" : "false"; - } - else - if (m_description[i] == "combobox") { - list[i+2] = ((KComboBox *)m_objectlist[i])->currentText(); - } - else { - list[i+2] = ((QLineEdit *)m_objectlist[i])->text().simplified(); - } - } + for (int i = 0; i < m_description.count(); ++i) { + if (m_description[i] == "label") { + list[i+2] = ((QLabel *)m_objectlist[i])->text(); + } + else if (m_description[i] == "checkbox") { + list[i+2] = (((QCheckBox *)m_objectlist[i])->isChecked()) ? "true" : "false"; + } + else if (m_description[i] == "combobox") { + list[i+2] = ((KComboBox *)m_objectlist[i])->currentText(); + } + else { + list[i+2] = ((QLineEdit *)m_objectlist[i])->text().simplified(); + } + } } // get the package name from string 'Option: (package: name)' QString QuickDocumentInputDialog::getPackageName(const QString &text) { - QRegExp reg(i18n("package:") + " ([^\\)]+)"); - return (reg.indexIn(text) >= 0) ? reg.cap(1) : QString(); + QRegExp reg(i18n("package:") + " ([^\\)]+)"); + return (reg.indexIn(text) >= 0) ? reg.cap(1) : QString(); } bool QuickDocumentInputDialog::checkListEntries(const QString &title, const QString &textlist, - const QString &pattern) + const QString &pattern) { - // split entries (one or a comma separated list) - QStringList list = textlist.split(','); + // split entries (one or a comma separated list) + QStringList list = textlist.split(','); - for (int i = 0; i < list.count(); ++i) { - QString s = list[i].trimmed(); - // entries must match a regular expression - QRegExp reg(pattern); - if (!reg.exactMatch(s)) { - KMessageBox::error(this, i18n("%1 '%2' is not allowed.", title, s)); - return false; - } - } - return true; + for (int i = 0; i < list.count(); ++i) { + QString s = list[i].trimmed(); + // entries must match a regular expression + QRegExp reg(pattern); + if (!reg.exactMatch(s)) { + KMessageBox::error(this, i18n("%1 '%2' is not allowed.", title, s)); + return false; + } + } + return true; } // check the main result of the input dialog void QuickDocumentInputDialog::slotAccepted() { - if (m_check) { - // get the label and main input string from the first label/linedit - QString inputlabel = ((QLabel *)m_objectlist[0])->text(); - QString input = ((QLineEdit *)m_objectlist[1])->text().simplified(); - - // should we check for an empty string - if ((m_check & qd_CheckNotEmpty) && input.isEmpty()) { - KMessageBox::error(this, i18n("An empty string is not allowed.")); - return; - } - - // should we check for an existing document class - if (m_check & qd_CheckDocumentClass) { - if (m_parent->isDocumentClass(input)) { - KMessageBox::error(this, i18n("This document class already exists.")); - return; - } - - QRegExp reg("\\w+"); - if (!reg.exactMatch(input)) { - KMessageBox::error(this, i18n("This name is not allowed for a document class.")); - return; - } - } - - // should we check for an existing document class option - if ((m_check & qd_CheckClassOption) && m_parent->isDocumentClassOption(input)) { - KMessageBox::error(this, i18n("This document class option already exists.")); - return; - } - - // should we check for an existing package - if ((m_check & qd_CheckPackage) && m_parent->isPackage(input)) { - KMessageBox::error(this, i18n("This package already exists.")); - return; - } - - // should we check for an existing package option - if (m_check & qd_CheckPackageOption) { - QString package = getPackageName(inputlabel); - if (package.isEmpty()) { - KMessageBox::error(this, i18n("Could not identify the package name.")); - return; - } - if (m_parent->isPackageOption(package, input)) { - KMessageBox::error(this, i18n("This package option already exists.")); - return; - } - } - - // should we check for a (list of) fontsizes - if ((m_check & qd_CheckFontsize) && !checkListEntries("Fontsize", input, "\\d+pt")) { - return; - } - - // should we check for a (list of) papersizes - if ((m_check & qd_CheckPapersize) && !checkListEntries("Papersize", input, "\\w+")) { - return; - } - } + if (m_check) { + // get the label and main input string from the first label/linedit + QString inputlabel = ((QLabel *)m_objectlist[0])->text(); + QString input = ((QLineEdit *)m_objectlist[1])->text().simplified(); + + // should we check for an empty string + if ((m_check & qd_CheckNotEmpty) && input.isEmpty()) { + KMessageBox::error(this, i18n("An empty string is not allowed.")); + return; + } + + // should we check for an existing document class + if (m_check & qd_CheckDocumentClass) { + if (m_parent->isDocumentClass(input)) { + KMessageBox::error(this, i18n("This document class already exists.")); + return; + } + + QRegExp reg("\\w+"); + if (!reg.exactMatch(input)) { + KMessageBox::error(this, i18n("This name is not allowed for a document class.")); + return; + } + } + + // should we check for an existing document class option + if ((m_check & qd_CheckClassOption) && m_parent->isDocumentClassOption(input)) { + KMessageBox::error(this, i18n("This document class option already exists.")); + return; + } + + // should we check for an existing package + if ((m_check & qd_CheckPackage) && m_parent->isPackage(input)) { + KMessageBox::error(this, i18n("This package already exists.")); + return; + } + + // should we check for an existing package option + if (m_check & qd_CheckPackageOption) { + QString package = getPackageName(inputlabel); + if (package.isEmpty()) { + KMessageBox::error(this, i18n("Could not identify the package name.")); + return; + } + if (m_parent->isPackageOption(package, input)) { + KMessageBox::error(this, i18n("This package option already exists.")); + return; + } + } + + // should we check for a (list of) fontsizes + if ((m_check & qd_CheckFontsize) && !checkListEntries("Fontsize", input, "\\d+pt")) { + return; + } + + // should we check for a (list of) papersizes + if ((m_check & qd_CheckPapersize) && !checkListEntries("Papersize", input, "\\w+")) { + return; + } + } } } // namespace diff --git a/src/dialogs/quickdocumentdialog.h b/src/dialogs/quickdocumentdialog.h index f92c2f2e..389180b9 100644 --- a/src/dialogs/quickdocumentdialog.h +++ b/src/dialogs/quickdocumentdialog.h @@ -1,231 +1,231 @@ /****************************************************************************************** date : Sep 12 2004 version : 0.22 copyright : Thomas Fischer (t-fisch@users.sourceforge.net) restructured, improved and completed by Holger Danielsson (C) 2004 by Holger Danielsson (holger.danielsson@t-online.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. * * * ***************************************************************************/ #ifndef QUICKDOCUMENTDIALOG_H #define QUICKDOCUMENTDIALOG_H #include "kilewizard.h" #include #include class QLabel; class QLineEdit; class QPushButton; class QTabWidget; class QTreeWidget; class QTreeWidgetItem; namespace KileWidget { class CategoryComboBox; } class KComboBox; namespace KileDialog { // some flags to check the results of the input dialog enum { - qd_CheckNotEmpty = 1, - qd_CheckDocumentClass = 2, - qd_CheckClassOption = 4, - qd_CheckPackage = 8, - qd_CheckPackageOption = 16, - qd_CheckFontsize = 32, - qd_CheckPapersize = 64 + qd_CheckNotEmpty = 1, + qd_CheckDocumentClass = 2, + qd_CheckClassOption = 4, + qd_CheckPackage = 8, + qd_CheckPackageOption = 16, + qd_CheckFontsize = 32, + qd_CheckPapersize = 64 }; class QuickDocument : public Wizard { - Q_OBJECT - - public: - explicit QuickDocument(KConfig *, QWidget *parent = 0, const char *name = 0, const QString &caption = QString()); - ~QuickDocument(); - - bool isStandardClass(const QString &classname); - bool isDocumentClass(const QString &name); - bool isDocumentClassOption(const QString &option); - bool isPackage(const QString &package); - bool isPackageOption(const QString &package, const QString &option); - - private: - KileWidget::CategoryComboBox *m_cbDocumentClass; - KileWidget::CategoryComboBox *m_cbTypefaceSize; - KileWidget::CategoryComboBox *m_cbPaperSize; - KileWidget::CategoryComboBox *m_cbEncoding; - QTreeWidget *m_lvClassOptions; - QTreeWidget *m_lvPackages; - QLineEdit *m_leAuthor; - QLineEdit *m_leTitle; - QLineEdit *m_leDate; - QLabel *m_lbPaperSize; - - QString m_currentClass; - QString m_currentFontsize; - QString m_currentPapersize; - QString m_currentEncoding; - bool m_currentHyperref; - QString m_hyperrefdriver; - QString m_hyperrefsetup; - QStringList m_userClasslist; - QStringList m_deleteDocumentClasses; - - QMap m_dictDocumentClasses; - QMap m_dictStandardClasses; - QMap m_currentDefaultOptions; - QMap m_currentSelectedOptions; - QMap m_dictPackagesEditable; - QMap m_dictPackagesDefaultvalues; - QMap m_dictHyperrefDriver; - - QPushButton *m_btnDocumentClassAdd; - QPushButton *m_btnDocumentClassDelete; - QPushButton *m_btnTypefaceSizeAdd; - QPushButton *m_btnTypefaceSizeDelete; - QPushButton *m_btnPaperSizeAdd; - QPushButton *m_btnPaperSizeDelete; - QPushButton *m_btnEncodingAdd; - QPushButton *m_btnEncodingDelete; - - QPushButton *m_btnClassOptionsAdd; - QPushButton *m_btnClassOptionsEdit; - QPushButton *m_btnClassOptionsDelete; - QPushButton *m_btnPackagesAdd; - QPushButton *m_btnPackagesAddOption; - QPushButton *m_btnPackagesEdit; - QPushButton *m_btnPackagesDelete; - QPushButton *m_btnPackagesReset; - - // GUI - QWidget *setupClassOptions(QTabWidget *tab); - QWidget *setupPackages(QTabWidget *tab); - QWidget *setupProperties(QTabWidget *tab); - - // read/write config files and init data - void readConfig(); - void readDocumentClassConfig(); - void readPackagesConfig(); - void initHyperref(); - void writeConfig(); - void writeDocumentClassConfig(); - void writePackagesConfig(); - - // document class tab - void initDocumentClass(); - void initStandardClass(const QString &classname, const QString &fontsize, - const QString &papersize, const QString &defaultoptions, - const QString &selectedoptions); - void initStandardOptions(const QString &classname, QStringList &optionlist); - void setDefaultClassOptions(const QString &defaultoptions); - void setSelectedClassOptions(const QString &selectedoptions); - void setClassOptions(const QStringList &list, uint start); - void updateClassOptions(); - QString getClassOptions(); - void fillDocumentClassCombobox(); - void fillCombobox(KileWidget::CategoryComboBox *combo, const QString &cslist, const QString &seltext); - bool addComboboxEntries(KileWidget::CategoryComboBox *combo, const QString &title, const QString &entry); - QString getComboxboxList(KComboBox *combo); - - bool isDefaultClassOption(const QString &option); - bool isSelectedClassOption(const QString &option); - QString stripDefault(const QString &s); - - // packages tab - void initPackages(); - bool readPackagesListview(); - QTreeWidgetItem *insertTreeWidget(QTreeWidget *treeWidget, - const QString &entry, - const QString &description); - QTreeWidgetItem *insertTreeWidget(QTreeWidgetItem *parent, - const QString &entry, - const QString &description); - QTreeWidgetItem *insertEditableTreeWidget(QTreeWidgetItem *parent, - const QString &entry, - const QString &description, - const QString &value, - const QString &defaultvalue); - bool isTreeWidgetEntry(QTreeWidget *treeWidget, const QString &entry); - void setPackagesValue(QTreeWidgetItem *item, const QString &option, const QString &val); - QString getPackagesValue(const QString &value); - - bool isTreeWidgetChild(QTreeWidget *treeWidget, const QString &entry, const QString &option); - QString addPackageDefault(const QString &option, const QString &description); - QString stripPackageDefault(const QString &option, const QString &description); - bool isHyperrefDriver(const QString &name); - - // document template - void printTemplate(); - void printPackages(); - void printHyperref(); - void printBeamerTheme(); - - // input dialog - bool inputDialog(QStringList &list, int check = qd_CheckNotEmpty); - - private Q_SLOTS: - void slotDocumentClassAdd(); - void slotDocumentClassDelete(); - void slotDocumentClassChanged(int index); - void slotTypefaceSizeAdd(); - void slotTypefaceSizeDelete(); - void slotPaperSizeAdd(); - void slotPaperSizeDelete(); - void slotOptionDoubleClicked(QTreeWidgetItem *item, int column); - void slotClassOptionAdd(); - void slotClassOptionEdit(); - void slotClassOptionDelete(); - - void slotCheckParent(QTreeWidgetItem *item); - void slotPackageDoubleClicked(QTreeWidgetItem *item); - void slotPackageAdd(); - void slotPackageAddOption(); - void slotPackageEdit(); - void slotPackageDelete(); - void slotPackageReset(); - - void slotEnableButtons(); - void slotAccepted(); + Q_OBJECT + +public: + explicit QuickDocument(KConfig *, QWidget *parent = 0, const char *name = 0, const QString &caption = QString()); + ~QuickDocument(); + + bool isStandardClass(const QString &classname); + bool isDocumentClass(const QString &name); + bool isDocumentClassOption(const QString &option); + bool isPackage(const QString &package); + bool isPackageOption(const QString &package, const QString &option); + +private: + KileWidget::CategoryComboBox *m_cbDocumentClass; + KileWidget::CategoryComboBox *m_cbTypefaceSize; + KileWidget::CategoryComboBox *m_cbPaperSize; + KileWidget::CategoryComboBox *m_cbEncoding; + QTreeWidget *m_lvClassOptions; + QTreeWidget *m_lvPackages; + QLineEdit *m_leAuthor; + QLineEdit *m_leTitle; + QLineEdit *m_leDate; + QLabel *m_lbPaperSize; + + QString m_currentClass; + QString m_currentFontsize; + QString m_currentPapersize; + QString m_currentEncoding; + bool m_currentHyperref; + QString m_hyperrefdriver; + QString m_hyperrefsetup; + QStringList m_userClasslist; + QStringList m_deleteDocumentClasses; + + QMap m_dictDocumentClasses; + QMap m_dictStandardClasses; + QMap m_currentDefaultOptions; + QMap m_currentSelectedOptions; + QMap m_dictPackagesEditable; + QMap m_dictPackagesDefaultvalues; + QMap m_dictHyperrefDriver; + + QPushButton *m_btnDocumentClassAdd; + QPushButton *m_btnDocumentClassDelete; + QPushButton *m_btnTypefaceSizeAdd; + QPushButton *m_btnTypefaceSizeDelete; + QPushButton *m_btnPaperSizeAdd; + QPushButton *m_btnPaperSizeDelete; + QPushButton *m_btnEncodingAdd; + QPushButton *m_btnEncodingDelete; + + QPushButton *m_btnClassOptionsAdd; + QPushButton *m_btnClassOptionsEdit; + QPushButton *m_btnClassOptionsDelete; + QPushButton *m_btnPackagesAdd; + QPushButton *m_btnPackagesAddOption; + QPushButton *m_btnPackagesEdit; + QPushButton *m_btnPackagesDelete; + QPushButton *m_btnPackagesReset; + + // GUI + QWidget *setupClassOptions(QTabWidget *tab); + QWidget *setupPackages(QTabWidget *tab); + QWidget *setupProperties(QTabWidget *tab); + + // read/write config files and init data + void readConfig(); + void readDocumentClassConfig(); + void readPackagesConfig(); + void initHyperref(); + void writeConfig(); + void writeDocumentClassConfig(); + void writePackagesConfig(); + + // document class tab + void initDocumentClass(); + void initStandardClass(const QString &classname, const QString &fontsize, + const QString &papersize, const QString &defaultoptions, + const QString &selectedoptions); + void initStandardOptions(const QString &classname, QStringList &optionlist); + void setDefaultClassOptions(const QString &defaultoptions); + void setSelectedClassOptions(const QString &selectedoptions); + void setClassOptions(const QStringList &list, uint start); + void updateClassOptions(); + QString getClassOptions(); + void fillDocumentClassCombobox(); + void fillCombobox(KileWidget::CategoryComboBox *combo, const QString &cslist, const QString &seltext); + bool addComboboxEntries(KileWidget::CategoryComboBox *combo, const QString &title, const QString &entry); + QString getComboxboxList(KComboBox *combo); + + bool isDefaultClassOption(const QString &option); + bool isSelectedClassOption(const QString &option); + QString stripDefault(const QString &s); + + // packages tab + void initPackages(); + bool readPackagesListview(); + QTreeWidgetItem *insertTreeWidget(QTreeWidget *treeWidget, + const QString &entry, + const QString &description); + QTreeWidgetItem *insertTreeWidget(QTreeWidgetItem *parent, + const QString &entry, + const QString &description); + QTreeWidgetItem *insertEditableTreeWidget(QTreeWidgetItem *parent, + const QString &entry, + const QString &description, + const QString &value, + const QString &defaultvalue); + bool isTreeWidgetEntry(QTreeWidget *treeWidget, const QString &entry); + void setPackagesValue(QTreeWidgetItem *item, const QString &option, const QString &val); + QString getPackagesValue(const QString &value); + + bool isTreeWidgetChild(QTreeWidget *treeWidget, const QString &entry, const QString &option); + QString addPackageDefault(const QString &option, const QString &description); + QString stripPackageDefault(const QString &option, const QString &description); + bool isHyperrefDriver(const QString &name); + + // document template + void printTemplate(); + void printPackages(); + void printHyperref(); + void printBeamerTheme(); + + // input dialog + bool inputDialog(QStringList &list, int check = qd_CheckNotEmpty); + +private Q_SLOTS: + void slotDocumentClassAdd(); + void slotDocumentClassDelete(); + void slotDocumentClassChanged(int index); + void slotTypefaceSizeAdd(); + void slotTypefaceSizeDelete(); + void slotPaperSizeAdd(); + void slotPaperSizeDelete(); + void slotOptionDoubleClicked(QTreeWidgetItem *item, int column); + void slotClassOptionAdd(); + void slotClassOptionEdit(); + void slotClassOptionDelete(); + + void slotCheckParent(QTreeWidgetItem *item); + void slotPackageDoubleClicked(QTreeWidgetItem *item); + void slotPackageAdd(); + void slotPackageAddOption(); + void slotPackageEdit(); + void slotPackageDelete(); + void slotPackageReset(); + + void slotEnableButtons(); + void slotAccepted(); }; class QuickDocumentInputDialog : public QDialog { - Q_OBJECT - public: - QuickDocumentInputDialog(const QStringList &list, int check = 0, - QuickDocument *parent = 0, const char *name = 0); - ~QuickDocumentInputDialog(); + Q_OBJECT +public: + QuickDocumentInputDialog(const QStringList &list, int check = 0, + QuickDocument *parent = 0, const char *name = 0); + ~QuickDocumentInputDialog(); - void getResults(QStringList &list); + void getResults(QStringList &list); - private: - QuickDocument *m_parent; - int m_check; +private: + QuickDocument *m_parent; + int m_check; - QStringList m_description; - QList m_objectlist; + QStringList m_description; + QList m_objectlist; - QString getPackageName(const QString &text); - bool checkListEntries(const QString &title, const QString &textlist, const QString &pattern); + QString getPackageName(const QString &text); + bool checkListEntries(const QString &title, const QString &textlist, const QString &pattern); - protected Q_SLOTS: - void slotAccepted(); +protected Q_SLOTS: + void slotAccepted(); }; } // namespace #endif diff --git a/src/dialogs/scriptshortcutdialog.cpp b/src/dialogs/scriptshortcutdialog.cpp index d0613b80..e1306f7f 100644 --- a/src/dialogs/scriptshortcutdialog.cpp +++ b/src/dialogs/scriptshortcutdialog.cpp @@ -1,105 +1,105 @@ /****************************************************************************** Copyright (C) 2011-2012 by Holger Danielsson (holger.danielsson@versanet.de) ******************************************************************************/ #include "dialogs/scriptshortcutdialog.h" #include #include #include #include #include #include #include #include #include "kiledebug.h" namespace KileDialog { ScriptShortcutDialog::ScriptShortcutDialog(QWidget *parent, KileInfo *ki, int type, const QString &sequence) - : QDialog(parent) + : QDialog(parent) { - setWindowTitle(i18n("New Key Sequence")); - setModal(true); - QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok|QDialogButtonBox::Cancel); - QWidget *mainWidget = new QWidget(this); - QVBoxLayout *mainLayout = new QVBoxLayout; - setLayout(mainLayout); - mainLayout->addWidget(mainWidget); - QPushButton *okButton = buttonBox->button(QDialogButtonBox::Ok); - okButton->setDefault(true); - okButton->setShortcut(Qt::CTRL | Qt::Key_Return); - connect(buttonBox, SIGNAL(accepted()), this, SLOT(accept())); - connect(buttonBox, SIGNAL(rejected()), this, SLOT(reject())); - //PORTING SCRIPT: WARNING mainLayout->addWidget(buttonBox) must be last item in layout. Please move it. - mainLayout->addWidget(buttonBox); - okButton->setDefault(true); - - QWidget *page = new QWidget(this); - mainLayout->addWidget(page); - m_scriptShortcutDialog.setupUi(page); - - m_scriptShortcutDialog.m_rbKeySequence->setWhatsThis(i18n("Use a key sequence written in the editor to execute a script.")); - m_scriptShortcutDialog.m_rbShortcut->setWhatsThis(i18n("Use a shortcut to execute a script.")); - - if ( type == KileScript::Script::KEY_SHORTCUT ) { - m_scriptShortcutDialog.m_rbShortcut->setChecked(true); - if ( sequence.isEmpty() ) { - m_scriptShortcutDialog.m_keyChooser->clearKeySequence(); - } - else { - m_scriptShortcutDialog.m_keyChooser->setKeySequence( QKeySequence(sequence) ); - } - } - else { - m_scriptShortcutDialog.m_rbKeySequence->setChecked(true); - m_scriptShortcutDialog.m_leKeySequence->setText(sequence); - } - slotUpdate(); - - // search for all action collections (needed for shortcut conflicts) - QList allCollections; - foreach ( KXMLGUIClient *client, ki->mainWindow()->guiFactory()->clients() ) { - allCollections += client->actionCollection(); - } - m_scriptShortcutDialog.m_keyChooser->setCheckActionCollections(allCollections); - - connect(m_scriptShortcutDialog.m_rbKeySequence, SIGNAL(clicked()), this, SLOT(slotUpdate())); - connect(m_scriptShortcutDialog.m_rbShortcut, SIGNAL(clicked()), this, SLOT(slotUpdate())); + setWindowTitle(i18n("New Key Sequence")); + setModal(true); + QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok|QDialogButtonBox::Cancel); + QWidget *mainWidget = new QWidget(this); + QVBoxLayout *mainLayout = new QVBoxLayout; + setLayout(mainLayout); + mainLayout->addWidget(mainWidget); + QPushButton *okButton = buttonBox->button(QDialogButtonBox::Ok); + okButton->setDefault(true); + okButton->setShortcut(Qt::CTRL | Qt::Key_Return); + connect(buttonBox, SIGNAL(accepted()), this, SLOT(accept())); + connect(buttonBox, SIGNAL(rejected()), this, SLOT(reject())); + //PORTING SCRIPT: WARNING mainLayout->addWidget(buttonBox) must be last item in layout. Please move it. + mainLayout->addWidget(buttonBox); + okButton->setDefault(true); + + QWidget *page = new QWidget(this); + mainLayout->addWidget(page); + m_scriptShortcutDialog.setupUi(page); + + m_scriptShortcutDialog.m_rbKeySequence->setWhatsThis(i18n("Use a key sequence written in the editor to execute a script.")); + m_scriptShortcutDialog.m_rbShortcut->setWhatsThis(i18n("Use a shortcut to execute a script.")); + + if ( type == KileScript::Script::KEY_SHORTCUT ) { + m_scriptShortcutDialog.m_rbShortcut->setChecked(true); + if ( sequence.isEmpty() ) { + m_scriptShortcutDialog.m_keyChooser->clearKeySequence(); + } + else { + m_scriptShortcutDialog.m_keyChooser->setKeySequence( QKeySequence(sequence) ); + } + } + else { + m_scriptShortcutDialog.m_rbKeySequence->setChecked(true); + m_scriptShortcutDialog.m_leKeySequence->setText(sequence); + } + slotUpdate(); + + // search for all action collections (needed for shortcut conflicts) + QList allCollections; + foreach ( KXMLGUIClient *client, ki->mainWindow()->guiFactory()->clients() ) { + allCollections += client->actionCollection(); + } + m_scriptShortcutDialog.m_keyChooser->setCheckActionCollections(allCollections); + + connect(m_scriptShortcutDialog.m_rbKeySequence, SIGNAL(clicked()), this, SLOT(slotUpdate())); + connect(m_scriptShortcutDialog.m_rbShortcut, SIGNAL(clicked()), this, SLOT(slotUpdate())); } int ScriptShortcutDialog::sequenceType() { - return ( m_scriptShortcutDialog.m_rbShortcut->isChecked() ) ? KileScript::Script::KEY_SHORTCUT : KileScript::Script::KEY_SEQUENCE; + return ( m_scriptShortcutDialog.m_rbShortcut->isChecked() ) ? KileScript::Script::KEY_SHORTCUT : KileScript::Script::KEY_SEQUENCE; } QString ScriptShortcutDialog::sequenceValue() { - return ( m_scriptShortcutDialog.m_rbShortcut->isChecked() ) - ? m_scriptShortcutDialog.m_keyChooser->keySequence().toString(QKeySequence::PortableText) - : m_scriptShortcutDialog.m_leKeySequence->text(); + return ( m_scriptShortcutDialog.m_rbShortcut->isChecked() ) + ? m_scriptShortcutDialog.m_keyChooser->keySequence().toString(QKeySequence::PortableText) + : m_scriptShortcutDialog.m_leKeySequence->text(); } void ScriptShortcutDialog::slotUpdate() { - bool state = ( m_scriptShortcutDialog.m_rbKeySequence->isChecked() ) ? true : false; - m_scriptShortcutDialog.m_lbKeySequence->setEnabled(state); - m_scriptShortcutDialog.m_leKeySequence->setEnabled(state); - m_scriptShortcutDialog.m_lbShortcut->setEnabled(!state); - m_scriptShortcutDialog.m_keyChooser->setEnabled(!state); - - if ( state ) { - m_scriptShortcutDialog.m_leKeySequence->setFocus(); - } - else { - m_scriptShortcutDialog.m_keyChooser->setFocus(); - } + bool state = ( m_scriptShortcutDialog.m_rbKeySequence->isChecked() ) ? true : false; + m_scriptShortcutDialog.m_lbKeySequence->setEnabled(state); + m_scriptShortcutDialog.m_leKeySequence->setEnabled(state); + m_scriptShortcutDialog.m_lbShortcut->setEnabled(!state); + m_scriptShortcutDialog.m_keyChooser->setEnabled(!state); + + if ( state ) { + m_scriptShortcutDialog.m_leKeySequence->setFocus(); + } + else { + m_scriptShortcutDialog.m_keyChooser->setFocus(); + } } } diff --git a/src/dialogs/scriptshortcutdialog.h b/src/dialogs/scriptshortcutdialog.h index aab1a61f..b6ce0907 100644 --- a/src/dialogs/scriptshortcutdialog.h +++ b/src/dialogs/scriptshortcutdialog.h @@ -1,41 +1,41 @@ /****************************************************************************** Copyright (C) 2011-2012 by Holger Danielsson (holger.danielsson@versanet.de) ******************************************************************************/ #ifndef SCRIPTSHORTCUTDIALOG_H #define SCRIPTSHORTCUTDIALOG_H #include #include "kileinfo.h" #include "scripting/script.h" #include "ui_scriptshortcutdialog_base.h" namespace KileDialog { class ScriptShortcutDialog : public QDialog { - Q_OBJECT + Q_OBJECT - public: - ScriptShortcutDialog(QWidget *parent, KileInfo *ki, int type, const QString &sequence); - ~ScriptShortcutDialog() {} +public: + ScriptShortcutDialog(QWidget *parent, KileInfo *ki, int type, const QString &sequence); + ~ScriptShortcutDialog() {} - int sequenceType(); - QString sequenceValue(); + int sequenceType(); + QString sequenceValue(); - private Q_SLOTS: - void slotUpdate(); +private Q_SLOTS: + void slotUpdate(); - private: - Ui::ScriptShortcutDialog m_scriptShortcutDialog; +private: + Ui::ScriptShortcutDialog m_scriptShortcutDialog; }; } #endif diff --git a/src/dialogs/statisticsdialog.cpp b/src/dialogs/statisticsdialog.cpp index 3b0c75c3..2c7d16eb 100644 --- a/src/dialogs/statisticsdialog.cpp +++ b/src/dialogs/statisticsdialog.cpp @@ -1,239 +1,239 @@ /********************************************************************************** begin : Tuesday Nov 1 2005 copyright : (C) 2005 by Thomas Braun (thomas.braun@virtuell-zuhause.de) 2015 by Andreas Cord-Landwehr (cordlandwehr@kde.org) **********************************************************************************/ /*************************************************************************** * * * 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. * * * ***************************************************************************/ #include "dialogs/statisticsdialog.h" #include "kileproject.h" #include "widgets/statisticswidget.h" #include #include #include #include #include #include #include #include #include #include #include #include // A dialog that displays statistical information about the active project/file namespace KileDialog { StatisticsDialog::StatisticsDialog(KileProject *project, KileDocument::TextInfo* docinfo, QWidget* parent, KTextEditor::View *view, const QString &caption) - : KPageDialog(parent), m_project(project), m_docinfo(docinfo), m_view(view) + : KPageDialog(parent), m_project(project), m_docinfo(docinfo), m_view(view) { - setFaceType(Tabbed); - setWindowTitle(caption); - setModal(true); - setStandardButtons(QDialogButtonBox::Help | QDialogButtonBox::Close); - QWidget *mainWidget = new QWidget(this); - QVBoxLayout *mainLayout = new QVBoxLayout; - setLayout(mainLayout); - mainLayout->addWidget(mainWidget); - QPushButton *copyButton = new QPushButton; - copyButton->setText(i18n("Copy")); - buttonBox()->addButton(copyButton, QDialogButtonBox::ActionRole); - QPushButton *copyLatexButton = new QPushButton; - copyLatexButton->setText(i18n("Copy as LaTeX")); - buttonBox()->addButton(copyLatexButton, QDialogButtonBox::ActionRole); - buttonBox()->button(QDialogButtonBox::Close)->setDefault(true); - - connect(copyButton, &QPushButton::clicked, this, [=]() { - KILE_DEBUG_MAIN << "Open tab is" << currentPage()->name() << ' ' + (m_pagetoname.contains(currentPage()) ? m_pagetoname[currentPage()] : "No such entry"); - QClipboard *clip = QApplication::clipboard(); - QString text; - convertText(&text, false); - clip->setText(text, QClipboard::Selection); // the text will be available with the middle mouse button - }); - connect(copyLatexButton, &QPushButton::clicked, this, [=]() { - KILE_DEBUG_MAIN << "Open tab is" << currentPage()->name() << ' ' + (m_pagetoname.contains(currentPage()) ? m_pagetoname[currentPage()] : "No such entry"); - QClipboard *clip = QApplication::clipboard(); - QString text; - convertText(&text, true); - clip->setText(text, QClipboard::Selection); // the text will be available with the middle mouse button - }); - connect(buttonBox(), &QDialogButtonBox::helpRequested, this, [=] () { - KHelpClient::invokeHelp("statistics", "kile"); - }); - - m_summarystats = new long[SIZE_STAT_ARRAY]; - m_summarystats[0] = m_summarystats[1] = m_summarystats[2] = m_summarystats[3] = m_summarystats[4] = m_summarystats[5] = 0; - - const long* stats; - QString tempName; - KileWidget::StatisticsWidget* tempWidget; - KileWidget::StatisticsWidget* summary; - KileDocument::TextInfo* tempDocinfo; - - m_hasSelection = view->selection(); // class variable, if the user has selected text, - summary = new KileWidget::StatisticsWidget(mainWidget); - KPageWidgetItem *itemSummary = new KPageWidgetItem(summary, i18n("Summary")); - addPage(itemSummary); - summary->m_commentAboutHelp->setText(i18n("For information about the accuracy see the Help.")); - - // we have in every case a summary tab - m_pagetowidget[itemSummary] = summary; - m_pagetoname[itemSummary] = i18n("Summary"); - - if (!m_project) { // the active doc doesn't belong to a project - setWindowTitle(i18n("Statistics for %1", m_docinfo->getDoc()->url().fileName())); - stats = m_docinfo->getStatistics(m_view); - fillWidget(stats, summary); - } - else { // active doc belongs to a project - setWindowTitle(i18n("Statistics for the Project %1", m_project->name())); - KILE_DEBUG_MAIN << "Project file is " << project->baseURL() << endl; - - QList items = project->items(); - - if (m_hasSelection) { // if the active doc has a selection - stats = m_docinfo->getStatistics(m_view); - fillWidget(stats, summary); // if yes we fill the summary widget and are finished - } - else { - for(QList::iterator i = items.begin(); i != items.end(); ++i) { - KileProjectItem *item = *i; - - if (item->type() == KileProjectItem::ProjectFile) { // ignore project files - continue; - } - - tempDocinfo = item->getInfo(); - if(tempDocinfo && tempDocinfo->getDoc()) { // closed items don't have a doc - tempName = tempDocinfo->getDoc()->url().fileName(); - stats = tempDocinfo->getStatistics(m_view); - - for (uint j = 0; j < SIZE_STAT_ARRAY; j++) { - m_summarystats[j] += stats[j]; - } - - tempWidget = new KileWidget::StatisticsWidget(); - KPageWidgetItem *itemTemp = new KPageWidgetItem(tempWidget, tempName); - addPage(itemTemp); - KILE_DEBUG_MAIN << "TempName is " << tempName << endl; - m_pagetowidget[itemTemp] = tempWidget; - m_pagetoname[itemTemp] = tempName; - fillWidget(stats, tempWidget); - } - else { - m_notAllFilesOpenWarning = true; // print warning - } - } - - fillWidget(m_summarystats, summary); - if (m_notAllFilesOpenWarning) { - summary->m_warning->setText(i18n("To get statistics for all project files, you have to open them all.")); - } - - KILE_DEBUG_MAIN << "All keys in name " << m_pagetoname.keys() << " Nr. of keys " << m_pagetowidget.count() << endl; - KILE_DEBUG_MAIN << "All keys in widget " << m_pagetowidget.keys() << " Nr. of keys " << m_pagetowidget.count() << endl; - } - } + setFaceType(Tabbed); + setWindowTitle(caption); + setModal(true); + setStandardButtons(QDialogButtonBox::Help | QDialogButtonBox::Close); + QWidget *mainWidget = new QWidget(this); + QVBoxLayout *mainLayout = new QVBoxLayout; + setLayout(mainLayout); + mainLayout->addWidget(mainWidget); + QPushButton *copyButton = new QPushButton; + copyButton->setText(i18n("Copy")); + buttonBox()->addButton(copyButton, QDialogButtonBox::ActionRole); + QPushButton *copyLatexButton = new QPushButton; + copyLatexButton->setText(i18n("Copy as LaTeX")); + buttonBox()->addButton(copyLatexButton, QDialogButtonBox::ActionRole); + buttonBox()->button(QDialogButtonBox::Close)->setDefault(true); + + connect(copyButton, &QPushButton::clicked, this, [=]() { + KILE_DEBUG_MAIN << "Open tab is" << currentPage()->name() << ' ' + (m_pagetoname.contains(currentPage()) ? m_pagetoname[currentPage()] : "No such entry"); + QClipboard *clip = QApplication::clipboard(); + QString text; + convertText(&text, false); + clip->setText(text, QClipboard::Selection); // the text will be available with the middle mouse button + }); + connect(copyLatexButton, &QPushButton::clicked, this, [=]() { + KILE_DEBUG_MAIN << "Open tab is" << currentPage()->name() << ' ' + (m_pagetoname.contains(currentPage()) ? m_pagetoname[currentPage()] : "No such entry"); + QClipboard *clip = QApplication::clipboard(); + QString text; + convertText(&text, true); + clip->setText(text, QClipboard::Selection); // the text will be available with the middle mouse button + }); + connect(buttonBox(), &QDialogButtonBox::helpRequested, this, [=] () { + KHelpClient::invokeHelp("statistics", "kile"); + }); + + m_summarystats = new long[SIZE_STAT_ARRAY]; + m_summarystats[0] = m_summarystats[1] = m_summarystats[2] = m_summarystats[3] = m_summarystats[4] = m_summarystats[5] = 0; + + const long* stats; + QString tempName; + KileWidget::StatisticsWidget* tempWidget; + KileWidget::StatisticsWidget* summary; + KileDocument::TextInfo* tempDocinfo; + + m_hasSelection = view->selection(); // class variable, if the user has selected text, + summary = new KileWidget::StatisticsWidget(mainWidget); + KPageWidgetItem *itemSummary = new KPageWidgetItem(summary, i18n("Summary")); + addPage(itemSummary); + summary->m_commentAboutHelp->setText(i18n("For information about the accuracy see the Help.")); + + // we have in every case a summary tab + m_pagetowidget[itemSummary] = summary; + m_pagetoname[itemSummary] = i18n("Summary"); + + if (!m_project) { // the active doc doesn't belong to a project + setWindowTitle(i18n("Statistics for %1", m_docinfo->getDoc()->url().fileName())); + stats = m_docinfo->getStatistics(m_view); + fillWidget(stats, summary); + } + else { // active doc belongs to a project + setWindowTitle(i18n("Statistics for the Project %1", m_project->name())); + KILE_DEBUG_MAIN << "Project file is " << project->baseURL() << endl; + + QList items = project->items(); + + if (m_hasSelection) { // if the active doc has a selection + stats = m_docinfo->getStatistics(m_view); + fillWidget(stats, summary); // if yes we fill the summary widget and are finished + } + else { + for(QList::iterator i = items.begin(); i != items.end(); ++i) { + KileProjectItem *item = *i; + + if (item->type() == KileProjectItem::ProjectFile) { // ignore project files + continue; + } + + tempDocinfo = item->getInfo(); + if(tempDocinfo && tempDocinfo->getDoc()) { // closed items don't have a doc + tempName = tempDocinfo->getDoc()->url().fileName(); + stats = tempDocinfo->getStatistics(m_view); + + for (uint j = 0; j < SIZE_STAT_ARRAY; j++) { + m_summarystats[j] += stats[j]; + } + + tempWidget = new KileWidget::StatisticsWidget(); + KPageWidgetItem *itemTemp = new KPageWidgetItem(tempWidget, tempName); + addPage(itemTemp); + KILE_DEBUG_MAIN << "TempName is " << tempName << endl; + m_pagetowidget[itemTemp] = tempWidget; + m_pagetoname[itemTemp] = tempName; + fillWidget(stats, tempWidget); + } + else { + m_notAllFilesOpenWarning = true; // print warning + } + } + + fillWidget(m_summarystats, summary); + if (m_notAllFilesOpenWarning) { + summary->m_warning->setText(i18n("To get statistics for all project files, you have to open them all.")); + } + + KILE_DEBUG_MAIN << "All keys in name " << m_pagetoname.keys() << " Nr. of keys " << m_pagetowidget.count() << endl; + KILE_DEBUG_MAIN << "All keys in widget " << m_pagetowidget.keys() << " Nr. of keys " << m_pagetowidget.count() << endl; + } + } } StatisticsDialog::~StatisticsDialog() { - delete [] m_summarystats; + delete [] m_summarystats; } void StatisticsDialog::fillWidget(const long* stats, KileWidget::StatisticsWidget* widget) { // we don't have to write 0's in the number labels because this is the default value - if (!stats || !widget) { - return; - } + if (!stats || !widget) { + return; + } - if (m_hasSelection) { - widget->m_warning->setText(i18n("WARNING: These are the statistics for the selected text only.")); - } + if (m_hasSelection) { + widget->m_warning->setText(i18n("WARNING: These are the statistics for the selected text only.")); + } - widget->m_wordChar->setText(QString::number(stats[0])); - widget->m_commandChar->setText(QString::number(stats[1])); - widget->m_whitespaceChar->setText(QString::number(stats[2])); - widget->m_totalChar->setText(QString::number(stats[0] + stats[1] + stats[2])); + widget->m_wordChar->setText(QString::number(stats[0])); + widget->m_commandChar->setText(QString::number(stats[1])); + widget->m_whitespaceChar->setText(QString::number(stats[2])); + widget->m_totalChar->setText(QString::number(stats[0] + stats[1] + stats[2])); - widget->m_wordString->setText(QString::number(stats[3])); - widget->m_commandString->setText(QString::number(stats[4])); - widget->m_environmentString->setText(QString::number(stats[5])); - widget->m_totalString->setText(QString::number(stats[3] + stats[4] + stats[5])); + widget->m_wordString->setText(QString::number(stats[3])); + widget->m_commandString->setText(QString::number(stats[4])); + widget->m_environmentString->setText(QString::number(stats[5])); + widget->m_totalString->setText(QString::number(stats[3] + stats[4] + stats[5])); - widget->updateColumns(); + widget->updateColumns(); } void StatisticsDialog::convertText(QString* text, bool forLaTeX) // the bool determines if we want plainText or LaTeXCode { - KileWidget::StatisticsWidget* widget = m_pagetowidget[currentPage()]; - QString name = m_pagetoname[currentPage()]; - QString charGroupName = widget->m_charactersGroup->title(); - QString stringGroupName = widget->m_stringsGroup->title(); - - if (forLaTeX) { - text->append("\\begin{tabular}{ll}\n"); - } - - if (m_project && currentPage()) { - text->append(i18n("Statistics for project %1, file %2", m_project->name(), name)); - } - else { - if (m_project) { - text->append(i18n("Statistics for project %1", m_project->name())); - } - else { - if (m_docinfo->getDoc()->url().isValid()) { - text->append(i18n("Statistics for %1", m_docinfo->getDoc()->url().fileName())); - } - else { - text->append(i18n("Statistics for Untitled")); - } - } - } - if(forLaTeX) { - text->append(" & \\\\\\hline\n"); - } - else { - text->append("\n\n"); - } - text->append(charGroupName + (forLaTeX ? " & \\\\\n" : "\n")); - text->append(widget->m_wordCharText->text() + (forLaTeX ? " & " : "\t") + widget->m_wordChar->text() + (forLaTeX ? " \\\\\n" : "\n")); - text->append(widget->m_commandCharText->text() + (forLaTeX ? " & " : "\t") + widget->m_commandChar->text() + (forLaTeX ? " \\\\\n" : "\n")); - text->append(widget->m_whitespaceCharText->text() + (forLaTeX ? " & " : "\t") + widget->m_whitespaceChar->text() + (forLaTeX ? " \\\\\n" : "\n")); - text->append(widget->m_totalCharText->text() + (forLaTeX ? " & " : "\t") + widget->m_totalChar->text() + (forLaTeX ? " \\\\\n" : "\n")); - - text->append((forLaTeX ? " & \\\\\n" : "\n")); - text->append(stringGroupName + (forLaTeX ? " & \\\\\n" : "\n")); - text->append(widget->m_wordStringText->text() + (forLaTeX ? " & " : "\t") + widget->m_wordString->text() + (forLaTeX ? " \\\\\n" : "\n")); - text->append(widget->m_commandStringText->text() + (forLaTeX ? " & " : "\t") + widget->m_commandString->text() + (forLaTeX ? " \\\\\n" : "\n")); - text->append(widget->m_environmentStringText->text() + (forLaTeX ? " & " : "\t") + widget->m_environmentString->text() + (forLaTeX ? " \\\\\n" : "\n")); - text->append(widget->m_totalStringText->text() + (forLaTeX ? " & " : "\t") + widget->m_totalString->text() + (forLaTeX ? " \\\\\\hline\n" : "\n")); - - if (forLaTeX) { - text->append("\\end{tabular}\n"); - } - - if (m_hasSelection) { // we can't have both cases - text->append((forLaTeX ? "\\par\\bigskip\n" : "\n") + widget->m_warning->text() + '\n'); - } - else { - if(m_notAllFilesOpenWarning) { - text->append((forLaTeX ? "\\par\\bigskip\n" : "\n") + widget->m_warning->text() + '\n'); - } - } + KileWidget::StatisticsWidget* widget = m_pagetowidget[currentPage()]; + QString name = m_pagetoname[currentPage()]; + QString charGroupName = widget->m_charactersGroup->title(); + QString stringGroupName = widget->m_stringsGroup->title(); + + if (forLaTeX) { + text->append("\\begin{tabular}{ll}\n"); + } + + if (m_project && currentPage()) { + text->append(i18n("Statistics for project %1, file %2", m_project->name(), name)); + } + else { + if (m_project) { + text->append(i18n("Statistics for project %1", m_project->name())); + } + else { + if (m_docinfo->getDoc()->url().isValid()) { + text->append(i18n("Statistics for %1", m_docinfo->getDoc()->url().fileName())); + } + else { + text->append(i18n("Statistics for Untitled")); + } + } + } + if(forLaTeX) { + text->append(" & \\\\\\hline\n"); + } + else { + text->append("\n\n"); + } + text->append(charGroupName + (forLaTeX ? " & \\\\\n" : "\n")); + text->append(widget->m_wordCharText->text() + (forLaTeX ? " & " : "\t") + widget->m_wordChar->text() + (forLaTeX ? " \\\\\n" : "\n")); + text->append(widget->m_commandCharText->text() + (forLaTeX ? " & " : "\t") + widget->m_commandChar->text() + (forLaTeX ? " \\\\\n" : "\n")); + text->append(widget->m_whitespaceCharText->text() + (forLaTeX ? " & " : "\t") + widget->m_whitespaceChar->text() + (forLaTeX ? " \\\\\n" : "\n")); + text->append(widget->m_totalCharText->text() + (forLaTeX ? " & " : "\t") + widget->m_totalChar->text() + (forLaTeX ? " \\\\\n" : "\n")); + + text->append((forLaTeX ? " & \\\\\n" : "\n")); + text->append(stringGroupName + (forLaTeX ? " & \\\\\n" : "\n")); + text->append(widget->m_wordStringText->text() + (forLaTeX ? " & " : "\t") + widget->m_wordString->text() + (forLaTeX ? " \\\\\n" : "\n")); + text->append(widget->m_commandStringText->text() + (forLaTeX ? " & " : "\t") + widget->m_commandString->text() + (forLaTeX ? " \\\\\n" : "\n")); + text->append(widget->m_environmentStringText->text() + (forLaTeX ? " & " : "\t") + widget->m_environmentString->text() + (forLaTeX ? " \\\\\n" : "\n")); + text->append(widget->m_totalStringText->text() + (forLaTeX ? " & " : "\t") + widget->m_totalString->text() + (forLaTeX ? " \\\\\\hline\n" : "\n")); + + if (forLaTeX) { + text->append("\\end{tabular}\n"); + } + + if (m_hasSelection) { // we can't have both cases + text->append((forLaTeX ? "\\par\\bigskip\n" : "\n") + widget->m_warning->text() + '\n'); + } + else { + if(m_notAllFilesOpenWarning) { + text->append((forLaTeX ? "\\par\\bigskip\n" : "\n") + widget->m_warning->text() + '\n'); + } + } } } diff --git a/src/dialogs/statisticsdialog.h b/src/dialogs/statisticsdialog.h index 86f4839d..c37dae6f 100644 --- a/src/dialogs/statisticsdialog.h +++ b/src/dialogs/statisticsdialog.h @@ -1,56 +1,56 @@ /*************************************************************************** begin : Tuesday Nov 1 2005 copyright : (C) 2005 by Thomas Braun email : thomas.braun@virtuell-zuhause.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. * * * ***************************************************************************/ #ifndef STATISTICSDIALOG_H #define STATISTICSDIALOG_H #include "kiledocmanager.h" #include "documentinfo.h" #include #include class KileProject; namespace KileWidget { - class StatisticsWidget; +class StatisticsWidget; } namespace KileDialog { class StatisticsDialog : public KPageDialog { - public: - StatisticsDialog(KileProject *project, KileDocument::TextInfo* docinfo, - QWidget* parent = Q_NULLPTR, KTextEditor::View *view = Q_NULLPTR, - const QString &caption = QString()); - ~StatisticsDialog(); - - private: - void fillWidget(const long* stats, KileWidget::StatisticsWidget* widget); - void convertText(QString* text, bool forLaTeX); - - KileProject *m_project; - KileDocument::TextInfo *m_docinfo; - KTextEditor::View *m_view; - long *m_summarystats; - bool m_hasSelection; - bool m_notAllFilesOpenWarning; - QMap m_pagetowidget; - QMap m_pagetoname; +public: + StatisticsDialog(KileProject *project, KileDocument::TextInfo* docinfo, + QWidget* parent = Q_NULLPTR, KTextEditor::View *view = Q_NULLPTR, + const QString &caption = QString()); + ~StatisticsDialog(); + +private: + void fillWidget(const long* stats, KileWidget::StatisticsWidget* widget); + void convertText(QString* text, bool forLaTeX); + + KileProject *m_project; + KileDocument::TextInfo *m_docinfo; + KTextEditor::View *m_view; + long *m_summarystats; + bool m_hasSelection; + bool m_notAllFilesOpenWarning; + QMap m_pagetowidget; + QMap m_pagetoname; }; } #endif diff --git a/src/dialogs/tabbingdialog.cpp b/src/dialogs/tabbingdialog.cpp index b7c63362..70eda028 100644 --- a/src/dialogs/tabbingdialog.cpp +++ b/src/dialogs/tabbingdialog.cpp @@ -1,78 +1,78 @@ /*************************************************************************** begin : dim jui 14 2002 copyright : (C) 2002 - 2003 by Pascal Brachet, 2003 Jeroen Wijnhout email : Jeroen.Wijnhout@kdemail.net ***************************************************************************/ /*************************************************************************** * * * 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. * * * ***************************************************************************/ #include "dialogs/tabbingdialog.h" #include "editorextension.h" #include #include #include namespace KileDialog { QuickTabbing::QuickTabbing(KConfig *config, KileInfo *info, QWidget *parent, const char *name, const QString &caption) - : Wizard(config, parent, name, caption) - , m_info(info) + : Wizard(config, parent, name, caption) + , m_info(info) { - QWidget *page = new QWidget(this); - m_tabbingDialog.setupUi(page); - QVBoxLayout *mainLayout = new QVBoxLayout; - setLayout(mainLayout); - mainLayout->addWidget(page); - mainLayout->addWidget(buttonBox()); + QWidget *page = new QWidget(this); + m_tabbingDialog.setupUi(page); + QVBoxLayout *mainLayout = new QVBoxLayout; + setLayout(mainLayout); + mainLayout->addWidget(page); + mainLayout->addWidget(buttonBox()); - connect(this, &Wizard::accepted, this, &QuickTabbing::onAccepted); + connect(this, &Wizard::accepted, this, &QuickTabbing::onAccepted); } QuickTabbing::~QuickTabbing() { } void QuickTabbing::onAccepted() { - int x = m_tabbingDialog.m_spCols->value(); - int y = m_tabbingDialog.m_spRows->value(); - QString s = m_tabbingDialog.m_leSpacing->text(); - QString indent = m_info->editorExtension()->autoIndentEnvironment(); + int x = m_tabbingDialog.m_spCols->value(); + int y = m_tabbingDialog.m_spRows->value(); + QString s = m_tabbingDialog.m_leSpacing->text(); + QString indent = m_info->editorExtension()->autoIndentEnvironment(); - m_td.tagBegin = "\\begin{tabbing}\n"; - m_td.tagBegin += indent; + m_td.tagBegin = "\\begin{tabbing}\n"; + m_td.tagBegin += indent; - for (int j = 1; j < x ; ++j) { - m_td.tagBegin += "\\hspace{" + s + "}\\="; - } + for (int j = 1; j < x ; ++j) { + m_td.tagBegin += "\\hspace{" + s + "}\\="; + } - m_td.tagBegin += "\\kill\n"; + m_td.tagBegin += "\\kill\n"; - for (int i = 0; i < y - 1; ++i) { - m_td.tagBegin += indent; - for (int j = 1; j < x; ++j) - m_td.tagBegin += " \\> "; - m_td.tagBegin += "\\\\ \n"; - } + for (int i = 0; i < y - 1; ++i) { + m_td.tagBegin += indent; + for (int j = 1; j < x; ++j) + m_td.tagBegin += " \\> "; + m_td.tagBegin += "\\\\ \n"; + } - m_td.tagBegin += indent; - for (int j = 1; j < x; ++j) { - m_td.tagBegin += " \\> "; - } + m_td.tagBegin += indent; + for (int j = 1; j < x; ++j) { + m_td.tagBegin += " \\> "; + } - m_td.tagEnd = "\n\\end{tabbing}"; - m_td.dy = 1; - m_td.dx = indent.length(); + m_td.tagEnd = "\n\\end{tabbing}"; + m_td.dy = 1; + m_td.dx = indent.length(); } } diff --git a/src/dialogs/tabbingdialog.h b/src/dialogs/tabbingdialog.h index f4547169..98b70489 100644 --- a/src/dialogs/tabbingdialog.h +++ b/src/dialogs/tabbingdialog.h @@ -1,50 +1,50 @@ /*************************************************************************** begin : dim jui 14 2002 copyright : (C) 2002 - 2003 by Pascal Brachet, (C) 2003 Jeroen Wijnhout email : Jeroen.Wijnhout@kdemail.net ***************************************************************************/ /*************************************************************************** * * * 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. * * * ***************************************************************************/ #ifndef TABBINGDIALOG_H #define TABBINGDIALOG_H #include "kilewizard.h" #include "kileinfo.h" #include "ui_tabbingdialog_base.h" /** * @author Pascal Brachet * @author Jeroen Wijnhout */ namespace KileDialog { class QuickTabbing : public Wizard { - Q_OBJECT + Q_OBJECT public: - QuickTabbing(KConfig *config, KileInfo *info, QWidget *parent = Q_NULLPTR, - const char *name = Q_NULLPTR, const QString &caption = QString()); - ~QuickTabbing(); + QuickTabbing(KConfig *config, KileInfo *info, QWidget *parent = Q_NULLPTR, + const char *name = Q_NULLPTR, const QString &caption = QString()); + ~QuickTabbing(); public Q_SLOTS: - void onAccepted(); + void onAccepted(); private: - KileInfo *m_info; - Ui::TabbingDialog m_tabbingDialog; + KileInfo *m_info; + Ui::TabbingDialog m_tabbingDialog; }; } #endif diff --git a/src/dialogs/tabular/multicolumnborderhelper.cpp b/src/dialogs/tabular/multicolumnborderhelper.cpp index 55835d9f..ec74f272 100644 --- a/src/dialogs/tabular/multicolumnborderhelper.cpp +++ b/src/dialogs/tabular/multicolumnborderhelper.cpp @@ -1,55 +1,55 @@ /******************************************************************************************** begin : Sunday Jun 27 2008 copyright : (C) 2008 by Mathias Soeken (msoeken@informatik.uni-bremen.de) copyright : (C) 2005-2006 by Holger Danielsson (holger.danielsson@t-online.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. * * * ***************************************************************************/ #include "multicolumnborderhelper.h" namespace KileDialog { MultiColumnBorderHelper::MultiColumnBorderHelper() - : m_FirstNumber(-2), m_LastNumber(-2) + : m_FirstNumber(-2), m_LastNumber(-2) { } void MultiColumnBorderHelper::addColumn(int column) { - if(column == m_LastNumber + 1) { // enlarge range - m_LastNumber = column; - } else { - if(m_LastNumber != -2) { - m_SpanColumns.append(std::make_pair(m_FirstNumber, m_LastNumber)); - } - m_FirstNumber = m_LastNumber = column; - } + if(column == m_LastNumber + 1) { // enlarge range + m_LastNumber = column; + } else { + if(m_LastNumber != -2) { + m_SpanColumns.append(std::make_pair(m_FirstNumber, m_LastNumber)); + } + m_FirstNumber = m_LastNumber = column; + } } void MultiColumnBorderHelper::finish() { - if(m_LastNumber != -2) { - m_SpanColumns.append(std::make_pair(m_FirstNumber, m_LastNumber)); - } + if(m_LastNumber != -2) { + m_SpanColumns.append(std::make_pair(m_FirstNumber, m_LastNumber)); + } } QString MultiColumnBorderHelper::toLaTeX() const { - QString result; - QVector >::const_iterator it; - for(it = m_SpanColumns.constBegin(); it != m_SpanColumns.constEnd(); ++it) { - result += "\\cline{" + QString::number(it->first + 1) + '-' + - QString::number(it->second + 1) + '}'; - } - return result; + QString result; + QVector >::const_iterator it; + for(it = m_SpanColumns.constBegin(); it != m_SpanColumns.constEnd(); ++it) { + result += "\\cline{" + QString::number(it->first + 1) + '-' + + QString::number(it->second + 1) + '}'; + } + return result; } } diff --git a/src/dialogs/tabular/multicolumnborderhelper.h b/src/dialogs/tabular/multicolumnborderhelper.h index 85e457fc..ef2e18f4 100644 --- a/src/dialogs/tabular/multicolumnborderhelper.h +++ b/src/dialogs/tabular/multicolumnborderhelper.h @@ -1,44 +1,44 @@ /*************************************************************************** begin : Sunday Jun 27 2008 copyright : (C) 2008 by Mathias Soeken email : msoeken@informatik.uni-bremen.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. * * * ***************************************************************************/ #ifndef MULTICOLUMNBORDERHELPER_H #define MULTICOLUMNBORDERHELPER_H #include #include #include namespace KileDialog { /** * @brief A helper class for managing multi column borders */ class MultiColumnBorderHelper { - public: - MultiColumnBorderHelper(); - void addColumn(int column); - void finish(); - QString toLaTeX() const; - - private: - QVector > m_SpanColumns; - int m_FirstNumber; - int m_LastNumber; +public: + MultiColumnBorderHelper(); + void addColumn(int column); + void finish(); + QString toLaTeX() const; + +private: + QVector > m_SpanColumns; + int m_FirstNumber; + int m_LastNumber; }; } #endif diff --git a/src/dialogs/tabular/newtabulardialog.cpp b/src/dialogs/tabular/newtabulardialog.cpp index 19d364bf..344d103f 100644 --- a/src/dialogs/tabular/newtabulardialog.cpp +++ b/src/dialogs/tabular/newtabulardialog.cpp @@ -1,1026 +1,1026 @@ /******************************************************************************************** Copyright (C) 2008 by Mathias Soeken (msoeken@informatik.uni-bremen.de) (C) 2005-2006 by Holger Danielsson (holger.danielsson@t-online.de) (C) 2012 by Michel Ludwig (michel.ludwig@kdemail.net) ********************************************************************************************/ /*************************************************************************** * * * 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. * * * ***************************************************************************/ #include "newtabulardialog.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "codecompletion.h" #include "kiledebug.h" #include "latexcmd.h" #include "multicolumnborderhelper.h" #include "selectcoloraction.h" #include "selectframeaction.h" #include "tabularcell.h" #include "tabularcelldelegate.h" #include "tabularheaderitem.h" #include "tabularproperties.h" #include "tabulartable.h" namespace KileDialog { NewTabularDialog::NewTabularDialog(const QString &environment, KileDocument::LatexCommands *commands, KConfig *config, QWidget *parent) - : Wizard(config, parent), - m_latexCommands(commands), - m_clCurrentBackground(Qt::white), - m_clCurrentForeground(Qt::black), - m_defaultEnvironment(environment) + : Wizard(config, parent), + m_latexCommands(commands), + m_clCurrentBackground(Qt::white), + m_clCurrentForeground(Qt::black), + m_defaultEnvironment(environment) { - setWindowTitle(i18n("Tabular Environments")); - - QWidget *page = new QWidget(this); - QVBoxLayout *pageLayout = new QVBoxLayout(); - pageLayout->setMargin(0); - page->setLayout(pageLayout); - - m_Table = new TabularTable(page); - - m_tbFormat = new QToolBar(page); - m_tbFormat->setMovable(false); - m_tbFormat->setFloatable(false); - m_tbFormat->setOrientation(Qt::Horizontal); - - m_acLeft = addAction(QIcon::fromTheme("format-justify-left"), i18n("Align Left"), SLOT(slotAlignLeft()), page); - m_acCenter = addAction(QIcon::fromTheme("format-justify-center"), i18n("Align Center"), SLOT(slotAlignCenter()), page); - m_acRight = addAction(QIcon::fromTheme("format-justify-right"), i18n("Align Right"), SLOT(slotAlignRight()), page); - m_tbFormat->addSeparator(); - m_acBold = addAction(QIcon::fromTheme("format-text-bold"), i18n("Bold"), SLOT(slotBold()), page); - m_acItalic = addAction(QIcon::fromTheme("format-text-italic"), i18n("Italic"), SLOT(slotItalic()), page); - m_acUnderline = addAction(QIcon::fromTheme("format-text-underline"), i18n("Underline"), SLOT(slotUnderline()), page); - m_tbFormat->addSeparator(); - m_acJoin = addAction(QIcon::fromTheme("joincells"), i18n("Join Cells"), SLOT(slotJoinCells()), page); - m_acSplit = addAction(QIcon::fromTheme("splitcells"), i18n("Split Cells"), SLOT(slotSplitCells()), page); - m_acSplit->setEnabled(false); - m_acFrame = new SelectFrameAction(i18n("Edit Frame"), m_tbFormat); - connect(m_acFrame, SIGNAL(borderSelected(int)), this, SLOT(slotFrame(int))); - m_tbFormat->addAction(m_acFrame); - m_tbFormat->addSeparator(); - - m_acBackground = new SelectColorAction(QIcon::fromTheme("format-fill-color"), i18n("Background Color"), page); - m_acBackground->setIcon(generateColorIcon(true)); - connect(m_acBackground, SIGNAL(triggered(bool)), this, SLOT(slotCurrentBackground())); - connect(m_acBackground, SIGNAL(colorSelected(const QColor&)), this, SLOT(slotBackground(const QColor&))); - m_tbFormat->addAction(m_acBackground); - m_acForeground = new SelectColorAction(QIcon::fromTheme("format-stroke-color"), i18n("Text Color"), page); - m_acForeground->setIcon(generateColorIcon(false)); - connect(m_acForeground, SIGNAL(colorSelected(const QColor&)), this, SLOT(slotForeground(const QColor&))); - connect(m_acForeground, SIGNAL(triggered(bool)), this, SLOT(slotCurrentForeground())); - m_tbFormat->addAction(m_acForeground); - - m_tbFormat->addSeparator(); - m_acClearText = addAction(QIcon::fromTheme("edit-clear"), i18n("Clear Text"), SLOT(slotClearText()), page); // FIXME icon - m_acClearAttributes = addAction(QIcon::fromTheme("edit-clear"), i18n("Clear Attributes"), SLOT(slotClearAttributes()), page); // FIXME icon - m_acClearAll = addAction(QIcon::fromTheme("edit-clear"), i18n("Clear All"), SLOT(slotClearAll()), page); - m_tbFormat->addSeparator(); - m_acPaste = addAction(QIcon::fromTheme("edit-paste"), i18n("Paste content from clipboard"), m_Table, SLOT(paste()), page); - - /* checkable items */ - m_acLeft->setCheckable(true); - m_acCenter->setCheckable(true); - m_acRight->setCheckable(true); - m_acBold->setCheckable(true); - m_acItalic->setCheckable(true); - m_acUnderline->setCheckable(true); - - QGroupBox *configPage = new QGroupBox(i18n("Environment"), page); - QGridLayout *configPageLayout = new QGridLayout(); - configPage->setLayout(configPageLayout); - - QLabel *label = new QLabel(i18n("Name:"), configPage); - m_cmbName = new QComboBox(configPage); - label->setBuddy(m_cmbName); - configPageLayout->addWidget(label, 0, 0); - configPageLayout->addWidget(m_cmbName, 0, 1); - label = new QLabel(i18n("Parameter:"), configPage); - m_cmbParameter = new QComboBox(configPage); - label->setBuddy(m_cmbParameter); - configPageLayout->addWidget(label, 1, 0); - configPageLayout->addWidget(m_cmbParameter, 1, 1); - - label = new QLabel(i18n("Number of rows:"), configPage); - m_sbRows = new QSpinBox(configPage); - m_sbRows->setMinimum(1); - m_sbRows->setValue(3); - label->setBuddy(m_sbRows); - configPageLayout->addWidget(label, 0, 2); - configPageLayout->addWidget(m_sbRows, 0, 3); - label = new QLabel(i18n("Number of cols:"), configPage); - m_sbCols = new QSpinBox(configPage); - m_sbCols->setMinimum(1); - m_sbCols->setValue(3); - label->setBuddy(m_sbCols); - configPageLayout->addWidget(label, 1, 2); - configPageLayout->addWidget(m_sbCols, 1, 3); - - m_cbStarred = new QCheckBox(i18n("Use starred version"), configPage); - label = new QLabel(i18n("Table width:"), configPage); - m_leTableWidth = new QLineEdit(configPage); - m_leTableWidth->setEnabled(false); - connect(m_cbStarred, SIGNAL(stateChanged(int)), this, SLOT(slotStarredChanged())); - label->setBuddy(m_leTableWidth); - m_cbCenter = new QCheckBox(i18n("Center"), configPage); - m_cbCenter->setChecked(true); - m_cbBooktabs = new QCheckBox(i18n("Use booktabs package"), configPage); - m_cbBullets = new QCheckBox(i18n("Insert bullets"), configPage); - m_cbBullets->setChecked(true); - configPageLayout->addWidget(m_cbStarred, 2, 0, 1, 2); - configPageLayout->addWidget(label, 2, 2, 1, 1); - configPageLayout->addWidget(m_leTableWidth, 2, 3, 1, 1); - configPageLayout->addWidget(m_cbCenter, 3, 0, 1, 2); - configPageLayout->addWidget(m_cbBooktabs, 3, 2, 1, 2); - configPageLayout->addWidget(m_cbBullets, 4, 0, 1, 2); - - // whats this texts - m_Table->setWhatsThis(i18n("Input data. Enter text when a cell is selected. When return is pressed, the adjacent cell will become selected.")); - m_cmbName->setWhatsThis(i18n("Choose an environment.")); - m_cmbParameter->setWhatsThis(i18n("Optional parameter for the chosen environment.")); - m_sbRows->setWhatsThis(i18n("Choose the number of table rows.")); - m_sbCols->setWhatsThis(i18n("Choose the number of table columns.")); - m_cbCenter->setWhatsThis(i18n("The tabular will be centered.")); - m_cbBooktabs->setWhatsThis(i18n("Use line commands of the booktabs package.")); - m_cbStarred->setWhatsThis(i18n("Use the starred version of this environment.")); - m_leTableWidth->setWhatsThis(i18n("Set the width of the table.")); - m_cbBullets->setWhatsThis(i18n("Insert bullets in each cell. Alt+Ctrl+Right and Alt+Ctrl+Left will move very quickly from one cell to another.")); - m_acBold->setWhatsThis(i18n("Set bold font series.")); - m_acItalic->setWhatsThis(i18n("Set italic font shape.")); - m_acUnderline->setWhatsThis(i18n("Set underlined font shape.")); - m_acLeft->setWhatsThis(i18n("The text will be aligned at the left border of the cell.")); - m_acCenter->setWhatsThis(i18n("The text will be centered.")); - m_acRight->setWhatsThis(i18n("The text will be aligned at the right border of the cell.")); - m_acJoin->setWhatsThis(i18n("Joins adjacent cells when they are in the same row.")); - m_acSplit->setWhatsThis(i18n("Splits joined cells.")); - m_acFrame->setWhatsThis(i18n("Choose the border for the selected cells. When clicking on the button, the current border will be applied to the selected cells.")); - m_acBackground->setWhatsThis(i18n("Choose a background color (needs color package).")); - m_acForeground->setWhatsThis(i18n("Choose a text color (needs color package).")); - m_acClearText->setWhatsThis(i18n("Clears the text of the selected cells but keeps attributes such as alignment and font shape.")); - m_acClearAttributes->setWhatsThis(i18n("Resets the attributes of the selected cells to the default values but keeps the text.")); - m_acClearAll->setWhatsThis(i18n("Clears the text of the selected cells and resets the attributes.")); - m_acPaste->setWhatsThis(i18n("Pastes a table stored in the clipboard into this wizard.")); - - pageLayout->addWidget(m_tbFormat); - pageLayout->addWidget(m_Table); - pageLayout->addWidget(configPage); - pageLayout->addWidget(buttonBox()); - setLayout(pageLayout); - - initEnvironments(); - updateColsAndRows(); - m_Table->item(0, 0)->setSelected(true); - - connect(m_Table, &KileDialog::TabularTable::itemSelectionChanged, this, &NewTabularDialog::slotItemSelectionChanged); - connect(m_Table, &KileDialog::TabularTable::rowAppended, this, &NewTabularDialog::slotRowAppended); - connect(m_Table, &KileDialog::TabularTable::colAppended, this, &NewTabularDialog::slotColAppended); - connect(m_cmbName, static_cast(&QComboBox::activated), this, &NewTabularDialog::slotEnvironmentChanged); - connect(m_sbCols, static_cast(&QSpinBox::valueChanged), this, &NewTabularDialog::updateColsAndRows); - connect(m_sbRows, static_cast(&QSpinBox::valueChanged), this, &NewTabularDialog::updateColsAndRows); - connect(m_Table->horizontalHeader(), &QHeaderView::customContextMenuRequested, this, &NewTabularDialog::slotHeaderCustomContextMenuRequested); - connect(this, &QDialog::accepted, this, &NewTabularDialog::slotAccepted); + setWindowTitle(i18n("Tabular Environments")); + + QWidget *page = new QWidget(this); + QVBoxLayout *pageLayout = new QVBoxLayout(); + pageLayout->setMargin(0); + page->setLayout(pageLayout); + + m_Table = new TabularTable(page); + + m_tbFormat = new QToolBar(page); + m_tbFormat->setMovable(false); + m_tbFormat->setFloatable(false); + m_tbFormat->setOrientation(Qt::Horizontal); + + m_acLeft = addAction(QIcon::fromTheme("format-justify-left"), i18n("Align Left"), SLOT(slotAlignLeft()), page); + m_acCenter = addAction(QIcon::fromTheme("format-justify-center"), i18n("Align Center"), SLOT(slotAlignCenter()), page); + m_acRight = addAction(QIcon::fromTheme("format-justify-right"), i18n("Align Right"), SLOT(slotAlignRight()), page); + m_tbFormat->addSeparator(); + m_acBold = addAction(QIcon::fromTheme("format-text-bold"), i18n("Bold"), SLOT(slotBold()), page); + m_acItalic = addAction(QIcon::fromTheme("format-text-italic"), i18n("Italic"), SLOT(slotItalic()), page); + m_acUnderline = addAction(QIcon::fromTheme("format-text-underline"), i18n("Underline"), SLOT(slotUnderline()), page); + m_tbFormat->addSeparator(); + m_acJoin = addAction(QIcon::fromTheme("joincells"), i18n("Join Cells"), SLOT(slotJoinCells()), page); + m_acSplit = addAction(QIcon::fromTheme("splitcells"), i18n("Split Cells"), SLOT(slotSplitCells()), page); + m_acSplit->setEnabled(false); + m_acFrame = new SelectFrameAction(i18n("Edit Frame"), m_tbFormat); + connect(m_acFrame, SIGNAL(borderSelected(int)), this, SLOT(slotFrame(int))); + m_tbFormat->addAction(m_acFrame); + m_tbFormat->addSeparator(); + + m_acBackground = new SelectColorAction(QIcon::fromTheme("format-fill-color"), i18n("Background Color"), page); + m_acBackground->setIcon(generateColorIcon(true)); + connect(m_acBackground, SIGNAL(triggered(bool)), this, SLOT(slotCurrentBackground())); + connect(m_acBackground, SIGNAL(colorSelected(const QColor&)), this, SLOT(slotBackground(const QColor&))); + m_tbFormat->addAction(m_acBackground); + m_acForeground = new SelectColorAction(QIcon::fromTheme("format-stroke-color"), i18n("Text Color"), page); + m_acForeground->setIcon(generateColorIcon(false)); + connect(m_acForeground, SIGNAL(colorSelected(const QColor&)), this, SLOT(slotForeground(const QColor&))); + connect(m_acForeground, SIGNAL(triggered(bool)), this, SLOT(slotCurrentForeground())); + m_tbFormat->addAction(m_acForeground); + + m_tbFormat->addSeparator(); + m_acClearText = addAction(QIcon::fromTheme("edit-clear"), i18n("Clear Text"), SLOT(slotClearText()), page); // FIXME icon + m_acClearAttributes = addAction(QIcon::fromTheme("edit-clear"), i18n("Clear Attributes"), SLOT(slotClearAttributes()), page); // FIXME icon + m_acClearAll = addAction(QIcon::fromTheme("edit-clear"), i18n("Clear All"), SLOT(slotClearAll()), page); + m_tbFormat->addSeparator(); + m_acPaste = addAction(QIcon::fromTheme("edit-paste"), i18n("Paste content from clipboard"), m_Table, SLOT(paste()), page); + + /* checkable items */ + m_acLeft->setCheckable(true); + m_acCenter->setCheckable(true); + m_acRight->setCheckable(true); + m_acBold->setCheckable(true); + m_acItalic->setCheckable(true); + m_acUnderline->setCheckable(true); + + QGroupBox *configPage = new QGroupBox(i18n("Environment"), page); + QGridLayout *configPageLayout = new QGridLayout(); + configPage->setLayout(configPageLayout); + + QLabel *label = new QLabel(i18n("Name:"), configPage); + m_cmbName = new QComboBox(configPage); + label->setBuddy(m_cmbName); + configPageLayout->addWidget(label, 0, 0); + configPageLayout->addWidget(m_cmbName, 0, 1); + label = new QLabel(i18n("Parameter:"), configPage); + m_cmbParameter = new QComboBox(configPage); + label->setBuddy(m_cmbParameter); + configPageLayout->addWidget(label, 1, 0); + configPageLayout->addWidget(m_cmbParameter, 1, 1); + + label = new QLabel(i18n("Number of rows:"), configPage); + m_sbRows = new QSpinBox(configPage); + m_sbRows->setMinimum(1); + m_sbRows->setValue(3); + label->setBuddy(m_sbRows); + configPageLayout->addWidget(label, 0, 2); + configPageLayout->addWidget(m_sbRows, 0, 3); + label = new QLabel(i18n("Number of cols:"), configPage); + m_sbCols = new QSpinBox(configPage); + m_sbCols->setMinimum(1); + m_sbCols->setValue(3); + label->setBuddy(m_sbCols); + configPageLayout->addWidget(label, 1, 2); + configPageLayout->addWidget(m_sbCols, 1, 3); + + m_cbStarred = new QCheckBox(i18n("Use starred version"), configPage); + label = new QLabel(i18n("Table width:"), configPage); + m_leTableWidth = new QLineEdit(configPage); + m_leTableWidth->setEnabled(false); + connect(m_cbStarred, SIGNAL(stateChanged(int)), this, SLOT(slotStarredChanged())); + label->setBuddy(m_leTableWidth); + m_cbCenter = new QCheckBox(i18n("Center"), configPage); + m_cbCenter->setChecked(true); + m_cbBooktabs = new QCheckBox(i18n("Use booktabs package"), configPage); + m_cbBullets = new QCheckBox(i18n("Insert bullets"), configPage); + m_cbBullets->setChecked(true); + configPageLayout->addWidget(m_cbStarred, 2, 0, 1, 2); + configPageLayout->addWidget(label, 2, 2, 1, 1); + configPageLayout->addWidget(m_leTableWidth, 2, 3, 1, 1); + configPageLayout->addWidget(m_cbCenter, 3, 0, 1, 2); + configPageLayout->addWidget(m_cbBooktabs, 3, 2, 1, 2); + configPageLayout->addWidget(m_cbBullets, 4, 0, 1, 2); + + // whats this texts + m_Table->setWhatsThis(i18n("Input data. Enter text when a cell is selected. When return is pressed, the adjacent cell will become selected.")); + m_cmbName->setWhatsThis(i18n("Choose an environment.")); + m_cmbParameter->setWhatsThis(i18n("Optional parameter for the chosen environment.")); + m_sbRows->setWhatsThis(i18n("Choose the number of table rows.")); + m_sbCols->setWhatsThis(i18n("Choose the number of table columns.")); + m_cbCenter->setWhatsThis(i18n("The tabular will be centered.")); + m_cbBooktabs->setWhatsThis(i18n("Use line commands of the booktabs package.")); + m_cbStarred->setWhatsThis(i18n("Use the starred version of this environment.")); + m_leTableWidth->setWhatsThis(i18n("Set the width of the table.")); + m_cbBullets->setWhatsThis(i18n("Insert bullets in each cell. Alt+Ctrl+Right and Alt+Ctrl+Left will move very quickly from one cell to another.")); + m_acBold->setWhatsThis(i18n("Set bold font series.")); + m_acItalic->setWhatsThis(i18n("Set italic font shape.")); + m_acUnderline->setWhatsThis(i18n("Set underlined font shape.")); + m_acLeft->setWhatsThis(i18n("The text will be aligned at the left border of the cell.")); + m_acCenter->setWhatsThis(i18n("The text will be centered.")); + m_acRight->setWhatsThis(i18n("The text will be aligned at the right border of the cell.")); + m_acJoin->setWhatsThis(i18n("Joins adjacent cells when they are in the same row.")); + m_acSplit->setWhatsThis(i18n("Splits joined cells.")); + m_acFrame->setWhatsThis(i18n("Choose the border for the selected cells. When clicking on the button, the current border will be applied to the selected cells.")); + m_acBackground->setWhatsThis(i18n("Choose a background color (needs color package).")); + m_acForeground->setWhatsThis(i18n("Choose a text color (needs color package).")); + m_acClearText->setWhatsThis(i18n("Clears the text of the selected cells but keeps attributes such as alignment and font shape.")); + m_acClearAttributes->setWhatsThis(i18n("Resets the attributes of the selected cells to the default values but keeps the text.")); + m_acClearAll->setWhatsThis(i18n("Clears the text of the selected cells and resets the attributes.")); + m_acPaste->setWhatsThis(i18n("Pastes a table stored in the clipboard into this wizard.")); + + pageLayout->addWidget(m_tbFormat); + pageLayout->addWidget(m_Table); + pageLayout->addWidget(configPage); + pageLayout->addWidget(buttonBox()); + setLayout(pageLayout); + + initEnvironments(); + updateColsAndRows(); + m_Table->item(0, 0)->setSelected(true); + + connect(m_Table, &KileDialog::TabularTable::itemSelectionChanged, this, &NewTabularDialog::slotItemSelectionChanged); + connect(m_Table, &KileDialog::TabularTable::rowAppended, this, &NewTabularDialog::slotRowAppended); + connect(m_Table, &KileDialog::TabularTable::colAppended, this, &NewTabularDialog::slotColAppended); + connect(m_cmbName, static_cast(&QComboBox::activated), this, &NewTabularDialog::slotEnvironmentChanged); + connect(m_sbCols, static_cast(&QSpinBox::valueChanged), this, &NewTabularDialog::updateColsAndRows); + connect(m_sbRows, static_cast(&QSpinBox::valueChanged), this, &NewTabularDialog::updateColsAndRows); + connect(m_Table->horizontalHeader(), &QHeaderView::customContextMenuRequested, this, &NewTabularDialog::slotHeaderCustomContextMenuRequested); + connect(this, &QDialog::accepted, this, &NewTabularDialog::slotAccepted); } NewTabularDialog::~NewTabularDialog() { } const QStringList& NewTabularDialog::requiredPackages() const { - return m_requiredPackages; + return m_requiredPackages; } QString NewTabularDialog::environment() const { - return m_cmbName->currentText(); + return m_cmbName->currentText(); } void NewTabularDialog::initEnvironments() { - /* read all tabular environments and insert them into the combobox */ - QStringList list; - QStringList::ConstIterator it; - m_latexCommands->commandList(list, KileDocument::CmdAttrTabular, false); - m_cmbName->addItems(list); - - // set default environment - int index = m_cmbName->findText(m_defaultEnvironment); - if(index != -1) { - m_cmbName->setCurrentIndex(index); - } else { - if(m_defaultEnvironment == "array") { - m_cmbName->insertItem(0, "array"); - m_cmbName->setCurrentIndex(0); - } - } - - // refresh other gui elements regarding environment combo box - slotEnvironmentChanged(m_cmbName->currentText()); + /* read all tabular environments and insert them into the combobox */ + QStringList list; + QStringList::ConstIterator it; + m_latexCommands->commandList(list, KileDocument::CmdAttrTabular, false); + m_cmbName->addItems(list); + + // set default environment + int index = m_cmbName->findText(m_defaultEnvironment); + if(index != -1) { + m_cmbName->setCurrentIndex(index); + } else { + if(m_defaultEnvironment == "array") { + m_cmbName->insertItem(0, "array"); + m_cmbName->setCurrentIndex(0); + } + } + + // refresh other gui elements regarding environment combo box + slotEnvironmentChanged(m_cmbName->currentText()); } QAction * NewTabularDialog::addAction(const QIcon &icon, const QString &text, const char *method, QObject *parent) { - return addAction(icon, text, this, method, parent); + return addAction(icon, text, this, method, parent); } QAction * NewTabularDialog::addAction(const QIcon &icon, const QString &text, QObject *receiver, const char *method, QObject *parent) { - QAction *action = new QAction(icon, text, parent); - connect(action, SIGNAL(triggered(bool)), receiver, method); - m_tbFormat->addAction(action); + QAction *action = new QAction(icon, text, parent); + connect(action, SIGNAL(triggered(bool)), receiver, method); + m_tbFormat->addAction(action); - return action; + return action; } void NewTabularDialog::alignItems(int alignment) { - QList checkColumns; + QList checkColumns; - foreach(QTableWidgetItem *item, m_Table->selectedItems()) { - item->setTextAlignment(alignment | Qt::AlignVCenter); + foreach(QTableWidgetItem *item, m_Table->selectedItems()) { + item->setTextAlignment(alignment | Qt::AlignVCenter); - int column = item->column(); - if(!checkColumns.contains(column)) { - checkColumns.append(column); - } - } + int column = item->column(); + if(!checkColumns.contains(column)) { + checkColumns.append(column); + } + } - foreach(int column, checkColumns) { - if(checkForColumnAlignment(column)) { - static_cast(m_Table->horizontalHeaderItem(column))->setAlignment(alignment); - } - } + foreach(int column, checkColumns) { + if(checkForColumnAlignment(column)) { + static_cast(m_Table->horizontalHeaderItem(column))->setAlignment(alignment); + } + } - slotItemSelectionChanged(); + slotItemSelectionChanged(); } bool NewTabularDialog::checkForColumnAlignment(int column) { - int alignment = m_Table->item(0, column)->textAlignment(); + int alignment = m_Table->item(0, column)->textAlignment(); - for(int row = 1; row < m_Table->rowCount(); ++row) { - if(m_Table->item(row, column)->textAlignment() != alignment) { - return false; - } - } + for(int row = 1; row < m_Table->rowCount(); ++row) { + if(m_Table->item(row, column)->textAlignment() != alignment) { + return false; + } + } - return true; + return true; } QIcon NewTabularDialog::generateColorIcon(bool background) const { - QString iconName = background ? "format-fill-color" : "format-stroke-color"; - QPixmap pixmap = KIconLoader().loadIcon(iconName, KIconLoader::Toolbar); + QString iconName = background ? "format-fill-color" : "format-stroke-color"; + QPixmap pixmap = KIconLoader().loadIcon(iconName, KIconLoader::Toolbar); - QPainter painter(&pixmap); - QColor color = background ? m_clCurrentBackground : m_clCurrentForeground; - painter.fillRect(1, pixmap.height() - 7, pixmap.width() - 2, 6, color); - painter.end(); + QPainter painter(&pixmap); + QColor color = background ? m_clCurrentBackground : m_clCurrentForeground; + painter.fillRect(1, pixmap.height() - 7, pixmap.width() - 2, 6, color); + painter.end(); - return QIcon(pixmap); + return QIcon(pixmap); } bool NewTabularDialog::canJoin() const { - const QList selectedItems = m_Table->selectedItems(); - if(selectedItems.count() < 2) { - KILE_DEBUG_MAIN << "cannot join cells, because selectedItems.count() < 2"; - return false; - } - - /* check whether all selected items are in the same row */ - int row = selectedItems[0]->row(); - for(int i = 1; i < selectedItems.count(); ++i) { - if(selectedItems[i]->row() != row) { - KILE_DEBUG_MAIN << "cannot join cells, because of different rows"; - return false; - } - } - - /* check whether all selected items are adjacent */ - QList columns; - for(QTableWidgetItem* item : selectedItems) { - columns.append(item->column()); - } - std::sort(columns.begin(), columns.end()); - if((columns.last() - columns.first()) != (columns.size() - 1)) { - KILE_DEBUG_MAIN << "cannot join cells, because not all cells are adjacent"; - return false; - } - - return true; + const QList selectedItems = m_Table->selectedItems(); + if(selectedItems.count() < 2) { + KILE_DEBUG_MAIN << "cannot join cells, because selectedItems.count() < 2"; + return false; + } + + /* check whether all selected items are in the same row */ + int row = selectedItems[0]->row(); + for(int i = 1; i < selectedItems.count(); ++i) { + if(selectedItems[i]->row() != row) { + KILE_DEBUG_MAIN << "cannot join cells, because of different rows"; + return false; + } + } + + /* check whether all selected items are adjacent */ + QList columns; + for(QTableWidgetItem* item : selectedItems) { + columns.append(item->column()); + } + std::sort(columns.begin(), columns.end()); + if((columns.last() - columns.first()) != (columns.size() - 1)) { + KILE_DEBUG_MAIN << "cannot join cells, because not all cells are adjacent"; + return false; + } + + return true; } int NewTabularDialog::exec() { - show(); - return Wizard::exec(); + show(); + return Wizard::exec(); } void NewTabularDialog::slotAccepted() { - int rows = m_Table->rowCount(); - int columns = m_Table->columnCount(); - TabularProperties properties; - - //BEGIN preprocessing colors and border - QColor firstColor; - bool topBorder = true; - for(int row = 0; row < rows; ++row) { - bool sameColor = true; - bool borderUnderRow = true; - { - const QBrush backgroundBrush = m_Table->item(row, 0)->background(); - if(backgroundBrush.style() != Qt::NoBrush) { - firstColor = backgroundBrush.color(); - } - } - for(int column = 0; column < columns; ++column) { - TabularCell *cell = static_cast(m_Table->item(row, column)); - - // Adjust right and bottom border for current item - if(column < columns - 1) { - TabularCell *next = static_cast(m_Table->item(row, column + 1)); - if(next->border() & TabularCell::Left) { - cell->setBorder(cell->border() | TabularCell::Right); - } - } - if(row < rows - 1) { - TabularCell *next = static_cast(m_Table->item(row + 1, column)); - if(next->border() & TabularCell::Top) { - cell->setBorder(cell->border() | TabularCell::Bottom); - } - } - - const QBrush backgroundBrush = m_Table->item(row, column)->background(); - if(backgroundBrush.style() != Qt::NoBrush) { - QColor currentColor = backgroundBrush.color(); - properties.addColor(currentColor); - if(currentColor != firstColor) { - sameColor = false; - } - } - - const QBrush foregroundBrush = m_Table->item(row, column)->foreground(); - if(foregroundBrush.style() != Qt::NoBrush) { - properties.addColor(foregroundBrush.color()); - } - - if(!(cell->border() & TabularCell::Bottom)) { - borderUnderRow = false; - } - if (row == 0 && !(cell->border() & TabularCell::Top)) { - topBorder = false; - } - } - if(sameColor) { - properties.addRowColor(row, firstColor); - } - if(borderUnderRow) { - properties.addBorderUnderRow(row); - } - } - - if(topBorder) { - properties.setHasTopBorder(); - } - - bool leftBorder = true; - for(int column = 0; column < columns; ++column) { - bool borderBesideColumn = true; - for(int row = 0; row < rows; ++row) { - TabularCell *cell = static_cast(m_Table->item(row, column)); - - if(!(cell->border() & TabularCell::Right)) { - borderBesideColumn = false; - } - if (column == 0 && !(cell->border() & TabularCell::Left)) { - leftBorder = false; - } - } - if(borderBesideColumn) { - properties.addBorderBesideColumn(column); - } - } - - if(leftBorder) { - properties.setHasLeftBorder(); - } - //END - - /* bullet */ - if(m_cbBullets->isChecked()) { - properties.setBullet(s_bullet); - } - - /* environment */ - QString environment = m_cmbName->currentText(); - QString environmentFormatted = environment; - QString tableWidth; - if(m_cbStarred->isEnabled() && m_cbStarred->isChecked()) { - environmentFormatted += '*'; - } - - // Environment needs a width - if(m_leTableWidth->isEnabled()) { - tableWidth = '{' + m_leTableWidth->text() + '}'; - } - - /* build table parameter */ - QString tableParameter; - if(m_cmbParameter->currentIndex() != 0) { - tableParameter = '[' + m_cmbParameter->currentText() + ']'; - } - - /* build table alignment */ - QString tableAlignment = QString('{'); - if(properties.hasLeftBorder()) { - tableAlignment += '|'; - } - for(int column = 0; column < columns; ++column) { - TabularHeaderItem *headerItem = static_cast(m_Table->horizontalHeaderItem(column)); - if(headerItem->suppressSpace()) { - tableAlignment += QString("@{%1}").arg(properties.bullet()); - } else if(headerItem->dontSuppressSpace()) { - tableAlignment += QString("!{%1}").arg(properties.bullet()); - } - if(headerItem->insertBefore()) { - tableAlignment += QString(">{%1}").arg(properties.bullet()); - } - - switch(headerItem->alignment()) { - case Qt::AlignLeft: - tableAlignment += 'l'; - break; - case Qt::AlignHCenter: - tableAlignment += 'c'; - break; - case Qt::AlignRight: - tableAlignment += 'r'; - break; - case TabularHeaderItem::AlignP: - tableAlignment += QString("p{%1}").arg(properties.bullet()); - break; - case TabularHeaderItem::AlignB: - tableAlignment += QString("b{%1}").arg(properties.bullet()); - break; - case TabularHeaderItem::AlignM: - tableAlignment += QString("m{%1}").arg(properties.bullet()); - break; - case TabularHeaderItem::AlignX: - tableAlignment += 'X'; - break; - } - - if(headerItem->insertAfter()) { - tableAlignment += QString("<{%1}").arg(properties.bullet()); - } - - if(properties.hasBorderBesideColumn(column)) { - tableAlignment += '|'; - } - } - tableAlignment += '}'; - - /* build top border */ - QString topBorderStr; - if(properties.hasTopBorder()) { - if(m_cbBooktabs->isChecked()) { // we need a toprule with booktabs here - topBorderStr = "\\toprule"; - } - else { - topBorderStr = "\\hline"; - } - } - else { - MultiColumnBorderHelper topBorderHelper; - for(int column = 0; column < columns; ++column) { - TabularCell *cell = static_cast(m_Table->item(0, column)); - if(cell->border() & TabularCell::Top) { - topBorderHelper.addColumn(column); - } - } - topBorderHelper.finish(); - topBorderStr = topBorderHelper.toLaTeX(); - } - - if(m_cbCenter->isChecked()) { - m_td.tagBegin += "\\begin{center}\n"; - } - - m_td.tagBegin += QString("\\begin{%1}%2%3%4%5\n") - .arg(environmentFormatted) - .arg(tableWidth) - .arg(tableParameter) - .arg(tableAlignment) - .arg(topBorderStr); - - /* required packages */ - m_requiredPackages.clear(); - if(properties.requiredPackages().count()) { - m_td.tagBegin += "% use packages: " + properties.requiredPackages().join(",") + '\n'; - m_requiredPackages << properties.requiredPackages(); - } - - QColor rowColor; - for(int row = 0; row < rows; ++row) { - rowColor = properties.rowColor(row); - if(rowColor.isValid()) { - m_td.tagBegin += "\\rowcolor{" + properties.colorName(rowColor) + "}\n"; - } - MultiColumnBorderHelper columnBorderHelper; - for(int column = 0; column < columns;) { - TabularCell *cell = static_cast(m_Table->item(row, column)); - QString content = cell->toLaTeX(properties); - int columnSpan = m_Table->columnSpan(row, column); - - if(!properties.hasBorderUnderRow(row) && (cell->border() & TabularCell::Bottom)) { - for(int c2 = 0; c2 < columnSpan; ++c2) { - columnBorderHelper.addColumn(column + c2); - } - } - - QString sep = " & "; - if(column + columnSpan >= columns) { - QString end; - sep.clear(); - if(properties.hasBorderUnderRow(row)) { - if(m_cbBooktabs->isChecked()){ // we need a midrule with booktabs. - if(row < rows-1) { - end = "\\midrule"; - } - else { // last line gets a bottomrule - end = "\\bottomrule"; - } - } - else { - end = "\\hline"; - } - } - else { - columnBorderHelper.finish(); - end = columnBorderHelper.toLaTeX(); - } - if(row < rows - 1 || !end.isEmpty()) { - sep = "\\\\"; - } - sep += end + '\n'; - } - m_td.tagBegin += content + sep; - - column += columnSpan; - } - } - - m_td.tagEnd += QString("\\end{%1}\n").arg(environmentFormatted); - - if(m_cbCenter->isChecked()) { - m_td.tagEnd += "\\end{center}\n"; - } - - QHashIterator itColorName(properties.colorNames()); - QString colorNames = ""; - while(itColorName.hasNext()) { - itColorName.next(); - colorNames += "\\definecolor{" + itColorName.value() + "}{rgb}{"; - QColor color(itColorName.key()); - colorNames += QString::number(color.redF()) + ',' - + QString::number(color.greenF()) + ',' - + QString::number(color.blueF()) + "}\n"; - } - m_td.tagBegin = colorNames + m_td.tagBegin; - - if(properties.useMultiColumn()) { - m_td.tagBegin = "\\newcommand{\\mc}[3]{\\multicolumn{#1}{#2}{#3}}\n" - + m_td.tagBegin; - } - - /* use {} if mc was defined */ - if(properties.useMultiColumn()) { - m_td.tagBegin = "{%\n" + m_td.tagBegin; - m_td.tagEnd += "}%\n"; - } + int rows = m_Table->rowCount(); + int columns = m_Table->columnCount(); + TabularProperties properties; + + //BEGIN preprocessing colors and border + QColor firstColor; + bool topBorder = true; + for(int row = 0; row < rows; ++row) { + bool sameColor = true; + bool borderUnderRow = true; + { + const QBrush backgroundBrush = m_Table->item(row, 0)->background(); + if(backgroundBrush.style() != Qt::NoBrush) { + firstColor = backgroundBrush.color(); + } + } + for(int column = 0; column < columns; ++column) { + TabularCell *cell = static_cast(m_Table->item(row, column)); + + // Adjust right and bottom border for current item + if(column < columns - 1) { + TabularCell *next = static_cast(m_Table->item(row, column + 1)); + if(next->border() & TabularCell::Left) { + cell->setBorder(cell->border() | TabularCell::Right); + } + } + if(row < rows - 1) { + TabularCell *next = static_cast(m_Table->item(row + 1, column)); + if(next->border() & TabularCell::Top) { + cell->setBorder(cell->border() | TabularCell::Bottom); + } + } + + const QBrush backgroundBrush = m_Table->item(row, column)->background(); + if(backgroundBrush.style() != Qt::NoBrush) { + QColor currentColor = backgroundBrush.color(); + properties.addColor(currentColor); + if(currentColor != firstColor) { + sameColor = false; + } + } + + const QBrush foregroundBrush = m_Table->item(row, column)->foreground(); + if(foregroundBrush.style() != Qt::NoBrush) { + properties.addColor(foregroundBrush.color()); + } + + if(!(cell->border() & TabularCell::Bottom)) { + borderUnderRow = false; + } + if (row == 0 && !(cell->border() & TabularCell::Top)) { + topBorder = false; + } + } + if(sameColor) { + properties.addRowColor(row, firstColor); + } + if(borderUnderRow) { + properties.addBorderUnderRow(row); + } + } + + if(topBorder) { + properties.setHasTopBorder(); + } + + bool leftBorder = true; + for(int column = 0; column < columns; ++column) { + bool borderBesideColumn = true; + for(int row = 0; row < rows; ++row) { + TabularCell *cell = static_cast(m_Table->item(row, column)); + + if(!(cell->border() & TabularCell::Right)) { + borderBesideColumn = false; + } + if (column == 0 && !(cell->border() & TabularCell::Left)) { + leftBorder = false; + } + } + if(borderBesideColumn) { + properties.addBorderBesideColumn(column); + } + } + + if(leftBorder) { + properties.setHasLeftBorder(); + } + //END + + /* bullet */ + if(m_cbBullets->isChecked()) { + properties.setBullet(s_bullet); + } + + /* environment */ + QString environment = m_cmbName->currentText(); + QString environmentFormatted = environment; + QString tableWidth; + if(m_cbStarred->isEnabled() && m_cbStarred->isChecked()) { + environmentFormatted += '*'; + } + + // Environment needs a width + if(m_leTableWidth->isEnabled()) { + tableWidth = '{' + m_leTableWidth->text() + '}'; + } + + /* build table parameter */ + QString tableParameter; + if(m_cmbParameter->currentIndex() != 0) { + tableParameter = '[' + m_cmbParameter->currentText() + ']'; + } + + /* build table alignment */ + QString tableAlignment = QString('{'); + if(properties.hasLeftBorder()) { + tableAlignment += '|'; + } + for(int column = 0; column < columns; ++column) { + TabularHeaderItem *headerItem = static_cast(m_Table->horizontalHeaderItem(column)); + if(headerItem->suppressSpace()) { + tableAlignment += QString("@{%1}").arg(properties.bullet()); + } else if(headerItem->dontSuppressSpace()) { + tableAlignment += QString("!{%1}").arg(properties.bullet()); + } + if(headerItem->insertBefore()) { + tableAlignment += QString(">{%1}").arg(properties.bullet()); + } + + switch(headerItem->alignment()) { + case Qt::AlignLeft: + tableAlignment += 'l'; + break; + case Qt::AlignHCenter: + tableAlignment += 'c'; + break; + case Qt::AlignRight: + tableAlignment += 'r'; + break; + case TabularHeaderItem::AlignP: + tableAlignment += QString("p{%1}").arg(properties.bullet()); + break; + case TabularHeaderItem::AlignB: + tableAlignment += QString("b{%1}").arg(properties.bullet()); + break; + case TabularHeaderItem::AlignM: + tableAlignment += QString("m{%1}").arg(properties.bullet()); + break; + case TabularHeaderItem::AlignX: + tableAlignment += 'X'; + break; + } + + if(headerItem->insertAfter()) { + tableAlignment += QString("<{%1}").arg(properties.bullet()); + } + + if(properties.hasBorderBesideColumn(column)) { + tableAlignment += '|'; + } + } + tableAlignment += '}'; + + /* build top border */ + QString topBorderStr; + if(properties.hasTopBorder()) { + if(m_cbBooktabs->isChecked()) { // we need a toprule with booktabs here + topBorderStr = "\\toprule"; + } + else { + topBorderStr = "\\hline"; + } + } + else { + MultiColumnBorderHelper topBorderHelper; + for(int column = 0; column < columns; ++column) { + TabularCell *cell = static_cast(m_Table->item(0, column)); + if(cell->border() & TabularCell::Top) { + topBorderHelper.addColumn(column); + } + } + topBorderHelper.finish(); + topBorderStr = topBorderHelper.toLaTeX(); + } + + if(m_cbCenter->isChecked()) { + m_td.tagBegin += "\\begin{center}\n"; + } + + m_td.tagBegin += QString("\\begin{%1}%2%3%4%5\n") + .arg(environmentFormatted) + .arg(tableWidth) + .arg(tableParameter) + .arg(tableAlignment) + .arg(topBorderStr); + + /* required packages */ + m_requiredPackages.clear(); + if(properties.requiredPackages().count()) { + m_td.tagBegin += "% use packages: " + properties.requiredPackages().join(",") + '\n'; + m_requiredPackages << properties.requiredPackages(); + } + + QColor rowColor; + for(int row = 0; row < rows; ++row) { + rowColor = properties.rowColor(row); + if(rowColor.isValid()) { + m_td.tagBegin += "\\rowcolor{" + properties.colorName(rowColor) + "}\n"; + } + MultiColumnBorderHelper columnBorderHelper; + for(int column = 0; column < columns;) { + TabularCell *cell = static_cast(m_Table->item(row, column)); + QString content = cell->toLaTeX(properties); + int columnSpan = m_Table->columnSpan(row, column); + + if(!properties.hasBorderUnderRow(row) && (cell->border() & TabularCell::Bottom)) { + for(int c2 = 0; c2 < columnSpan; ++c2) { + columnBorderHelper.addColumn(column + c2); + } + } + + QString sep = " & "; + if(column + columnSpan >= columns) { + QString end; + sep.clear(); + if(properties.hasBorderUnderRow(row)) { + if(m_cbBooktabs->isChecked()) { // we need a midrule with booktabs. + if(row < rows-1) { + end = "\\midrule"; + } + else { // last line gets a bottomrule + end = "\\bottomrule"; + } + } + else { + end = "\\hline"; + } + } + else { + columnBorderHelper.finish(); + end = columnBorderHelper.toLaTeX(); + } + if(row < rows - 1 || !end.isEmpty()) { + sep = "\\\\"; + } + sep += end + '\n'; + } + m_td.tagBegin += content + sep; + + column += columnSpan; + } + } + + m_td.tagEnd += QString("\\end{%1}\n").arg(environmentFormatted); + + if(m_cbCenter->isChecked()) { + m_td.tagEnd += "\\end{center}\n"; + } + + QHashIterator itColorName(properties.colorNames()); + QString colorNames = ""; + while(itColorName.hasNext()) { + itColorName.next(); + colorNames += "\\definecolor{" + itColorName.value() + "}{rgb}{"; + QColor color(itColorName.key()); + colorNames += QString::number(color.redF()) + ',' + + QString::number(color.greenF()) + ',' + + QString::number(color.blueF()) + "}\n"; + } + m_td.tagBegin = colorNames + m_td.tagBegin; + + if(properties.useMultiColumn()) { + m_td.tagBegin = "\\newcommand{\\mc}[3]{\\multicolumn{#1}{#2}{#3}}\n" + + m_td.tagBegin; + } + + /* use {} if mc was defined */ + if(properties.useMultiColumn()) { + m_td.tagBegin = "{%\n" + m_td.tagBegin; + m_td.tagEnd += "}%\n"; + } } void NewTabularDialog::updateColsAndRows() { - int addedCols = m_sbCols->value() - m_Table->columnCount(); - int addedRows = m_sbRows->value() - m_Table->rowCount(); - - // check whether content could be deleted when shrinking the table - if(addedCols < 0) { - bool hasContent = false; - for(int column = m_Table->columnCount() + addedCols; column < m_Table->columnCount(); ++column) { - for(int row = 0; row < m_Table->rowCount(); ++row) { - if(m_Table->item(row, column) && !(m_Table->item(row, column)->text().isEmpty())) { - hasContent = true; - break; - } - } - if(hasContent) break; - } - - if(hasContent) { - if(KMessageBox::questionYesNo(m_Table, i18n("Setting the new size for the table will delete content. Are you sure to set the new size?"), i18n("Resizing table")) == KMessageBox::No) { - m_sbCols->setValue(m_Table->columnCount()); - return; - } - } - } - - // check whether content could be deleted when shrinking the table - if(addedRows < 0) { - bool hasContent = false; - for(int row = m_Table->rowCount() + addedRows; row < m_Table->rowCount(); ++row) { - for(int column = 0; column < m_Table->columnCount(); ++column) { - if(m_Table->item(row, column) && !(m_Table->item(row, column)->text().isEmpty())) { - hasContent = true; - break; - } - } - if(hasContent) break; - } - - if(hasContent) { - if(KMessageBox::questionYesNo(m_Table, i18n("Setting the new size for the table will delete content. Are you sure to set the new size?"), i18n("Resizing table")) == KMessageBox::No) { - m_sbRows->setValue(m_Table->rowCount()); - return; - } - } - } - - m_Table->setColumnCount(m_sbCols->value()); - m_Table->setRowCount(m_sbRows->value()); - - if(addedCols > 0) { - for(int i = m_Table->columnCount() - addedCols; i < m_Table->columnCount(); ++i) { - TabularHeaderItem *headerItem = new TabularHeaderItem(m_Table->horizontalHeader()); - connect(headerItem, SIGNAL(alignColumn(int)), this, SLOT(slotAlignColumn(int))); - m_Table->setHorizontalHeaderItem(i, headerItem); - - // each cell should be an item. This is necessary for selection checking - for(int row = 0; row < m_Table->rowCount(); ++row) { - QTableWidgetItem *item = new TabularCell(QString()); - item->setTextAlignment(Qt::AlignLeft | Qt::AlignVCenter); - m_Table->setItem(row, i, item); - } - } - } - - if(addedRows > 0) { - for(int i = m_Table->rowCount() - addedRows; i < m_Table->rowCount(); ++i) { - m_Table->resizeRowToContents(i); - - // each cell should be an item. This is necessary for selection checking - for(int column = 0; column < m_Table->columnCount(); ++column) { - QTableWidgetItem *item = new TabularCell(QString()); - item->setTextAlignment(Qt::AlignLeft | Qt::AlignVCenter); - m_Table->setItem(i, column, item); - } - } - } + int addedCols = m_sbCols->value() - m_Table->columnCount(); + int addedRows = m_sbRows->value() - m_Table->rowCount(); + + // check whether content could be deleted when shrinking the table + if(addedCols < 0) { + bool hasContent = false; + for(int column = m_Table->columnCount() + addedCols; column < m_Table->columnCount(); ++column) { + for(int row = 0; row < m_Table->rowCount(); ++row) { + if(m_Table->item(row, column) && !(m_Table->item(row, column)->text().isEmpty())) { + hasContent = true; + break; + } + } + if(hasContent) break; + } + + if(hasContent) { + if(KMessageBox::questionYesNo(m_Table, i18n("Setting the new size for the table will delete content. Are you sure to set the new size?"), i18n("Resizing table")) == KMessageBox::No) { + m_sbCols->setValue(m_Table->columnCount()); + return; + } + } + } + + // check whether content could be deleted when shrinking the table + if(addedRows < 0) { + bool hasContent = false; + for(int row = m_Table->rowCount() + addedRows; row < m_Table->rowCount(); ++row) { + for(int column = 0; column < m_Table->columnCount(); ++column) { + if(m_Table->item(row, column) && !(m_Table->item(row, column)->text().isEmpty())) { + hasContent = true; + break; + } + } + if(hasContent) break; + } + + if(hasContent) { + if(KMessageBox::questionYesNo(m_Table, i18n("Setting the new size for the table will delete content. Are you sure to set the new size?"), i18n("Resizing table")) == KMessageBox::No) { + m_sbRows->setValue(m_Table->rowCount()); + return; + } + } + } + + m_Table->setColumnCount(m_sbCols->value()); + m_Table->setRowCount(m_sbRows->value()); + + if(addedCols > 0) { + for(int i = m_Table->columnCount() - addedCols; i < m_Table->columnCount(); ++i) { + TabularHeaderItem *headerItem = new TabularHeaderItem(m_Table->horizontalHeader()); + connect(headerItem, SIGNAL(alignColumn(int)), this, SLOT(slotAlignColumn(int))); + m_Table->setHorizontalHeaderItem(i, headerItem); + + // each cell should be an item. This is necessary for selection checking + for(int row = 0; row < m_Table->rowCount(); ++row) { + QTableWidgetItem *item = new TabularCell(QString()); + item->setTextAlignment(Qt::AlignLeft | Qt::AlignVCenter); + m_Table->setItem(row, i, item); + } + } + } + + if(addedRows > 0) { + for(int i = m_Table->rowCount() - addedRows; i < m_Table->rowCount(); ++i) { + m_Table->resizeRowToContents(i); + + // each cell should be an item. This is necessary for selection checking + for(int column = 0; column < m_Table->columnCount(); ++column) { + QTableWidgetItem *item = new TabularCell(QString()); + item->setTextAlignment(Qt::AlignLeft | Qt::AlignVCenter); + m_Table->setItem(i, column, item); + } + } + } } void NewTabularDialog::slotEnvironmentChanged(const QString &environment) { - // clear parameter combobox - m_cmbParameter->clear(); - m_cmbParameter->setEnabled(false); - // disable table width line edit - m_leTableWidth->setEnabled(false); - - // look for environment parameter in dictionary - KileDocument::LatexCmdAttributes attr; - if(m_latexCommands->commandAttributes(environment, attr)) { - // starred version - m_cbStarred->setEnabled(attr.starred); - slotStarredChanged(); - - // option - if(attr.option.indexOf('[') == 0) { - QStringList optionlist = attr.option.split(""); - optionlist.removeAll(""); - if(optionlist.count() > 2) { - // ok, let's enable it - m_cmbParameter->setEnabled(true); - m_cmbParameter->addItem(QString()); - // insert some options - for(int i = 1; i < optionlist.count() - 1; ++i) { - m_cmbParameter->addItem(optionlist[i]); - } - } - } - - // enable table width line edit if needed - if( attr.parameter.indexOf('{') == 0 ) { - m_leTableWidth->setEnabled(true); - } - } - - // has X alignment - bool hasXAlignment = (environment == "tabularx" || environment == "xtabular"); - for(int column = 0; column < m_Table->columnCount(); ++column) { - static_cast(m_Table->horizontalHeaderItem(column))->setHasXAlignment(hasXAlignment); - } + // clear parameter combobox + m_cmbParameter->clear(); + m_cmbParameter->setEnabled(false); + // disable table width line edit + m_leTableWidth->setEnabled(false); + + // look for environment parameter in dictionary + KileDocument::LatexCmdAttributes attr; + if(m_latexCommands->commandAttributes(environment, attr)) { + // starred version + m_cbStarred->setEnabled(attr.starred); + slotStarredChanged(); + + // option + if(attr.option.indexOf('[') == 0) { + QStringList optionlist = attr.option.split(""); + optionlist.removeAll(""); + if(optionlist.count() > 2) { + // ok, let's enable it + m_cmbParameter->setEnabled(true); + m_cmbParameter->addItem(QString()); + // insert some options + for(int i = 1; i < optionlist.count() - 1; ++i) { + m_cmbParameter->addItem(optionlist[i]); + } + } + } + + // enable table width line edit if needed + if( attr.parameter.indexOf('{') == 0 ) { + m_leTableWidth->setEnabled(true); + } + } + + // has X alignment + bool hasXAlignment = (environment == "tabularx" || environment == "xtabular"); + for(int column = 0; column < m_Table->columnCount(); ++column) { + static_cast(m_Table->horizontalHeaderItem(column))->setHasXAlignment(hasXAlignment); + } } void NewTabularDialog::slotItemSelectionChanged() { - /* unset some items */ - m_acLeft->setChecked(false); - m_acCenter->setChecked(false); - m_acRight->setChecked(false); - - /* set all font format items and eventually unset them later */ - m_acBold->setChecked(true); - m_acItalic->setChecked(true); - m_acUnderline->setChecked(true); - - /* nothing selected, nothing to do! */ - QList selectedItems = m_Table->selectedItems(); - if(selectedItems.count() == 0) return; - - /* check for alignment */ - int alignment = selectedItems[0]->textAlignment(); - bool sameAlignment = true; - for(int i = 1; i < selectedItems.count(); ++i) { - if(selectedItems[i]->textAlignment() != alignment) { - sameAlignment = false; - break; - } - } - if(sameAlignment) { - m_acLeft->setChecked(alignment & Qt::AlignLeft); - m_acCenter->setChecked(alignment & Qt::AlignHCenter); - m_acRight->setChecked(alignment & Qt::AlignRight); - } - - /* check for font format */ - bool unsetBold = false; - bool unsetItalic = false; - bool unsetUnderline = false; - foreach(QTableWidgetItem *item, selectedItems) { - if(!unsetBold && !item->font().bold()) { - m_acBold->setChecked(false); - unsetBold = true; - } - if(!unsetItalic && !item->font().italic()) { - m_acItalic->setChecked(false); - unsetItalic = true; - } - if(!unsetUnderline && !item->font().underline()) { - m_acUnderline->setChecked(false); - unsetUnderline = true; - } - if(unsetBold && unsetItalic && unsetUnderline) { - break; - } - } - - m_acJoin->setEnabled(canJoin()); - - /* split action */ - m_acSplit->setEnabled(selectedItems.count() == 1 && - m_Table->columnSpan(selectedItems[0]->row(), selectedItems[0]->column()) > 1); + /* unset some items */ + m_acLeft->setChecked(false); + m_acCenter->setChecked(false); + m_acRight->setChecked(false); + + /* set all font format items and eventually unset them later */ + m_acBold->setChecked(true); + m_acItalic->setChecked(true); + m_acUnderline->setChecked(true); + + /* nothing selected, nothing to do! */ + QList selectedItems = m_Table->selectedItems(); + if(selectedItems.count() == 0) return; + + /* check for alignment */ + int alignment = selectedItems[0]->textAlignment(); + bool sameAlignment = true; + for(int i = 1; i < selectedItems.count(); ++i) { + if(selectedItems[i]->textAlignment() != alignment) { + sameAlignment = false; + break; + } + } + if(sameAlignment) { + m_acLeft->setChecked(alignment & Qt::AlignLeft); + m_acCenter->setChecked(alignment & Qt::AlignHCenter); + m_acRight->setChecked(alignment & Qt::AlignRight); + } + + /* check for font format */ + bool unsetBold = false; + bool unsetItalic = false; + bool unsetUnderline = false; + foreach(QTableWidgetItem *item, selectedItems) { + if(!unsetBold && !item->font().bold()) { + m_acBold->setChecked(false); + unsetBold = true; + } + if(!unsetItalic && !item->font().italic()) { + m_acItalic->setChecked(false); + unsetItalic = true; + } + if(!unsetUnderline && !item->font().underline()) { + m_acUnderline->setChecked(false); + unsetUnderline = true; + } + if(unsetBold && unsetItalic && unsetUnderline) { + break; + } + } + + m_acJoin->setEnabled(canJoin()); + + /* split action */ + m_acSplit->setEnabled(selectedItems.count() == 1 && + m_Table->columnSpan(selectedItems[0]->row(), selectedItems[0]->column()) > 1); } void NewTabularDialog::slotHeaderCustomContextMenuRequested(const QPoint &pos) { - int logicalIndex = m_Table->horizontalHeader()->logicalIndexAt(pos); - if(logicalIndex == -1) return; + int logicalIndex = m_Table->horizontalHeader()->logicalIndexAt(pos); + if(logicalIndex == -1) return; - QMenu *popup = static_cast(m_Table->horizontalHeaderItem(logicalIndex))->popupMenu(); - popup->exec(m_Table->horizontalHeader()->mapToGlobal(pos)); + QMenu *popup = static_cast(m_Table->horizontalHeaderItem(logicalIndex))->popupMenu(); + popup->exec(m_Table->horizontalHeader()->mapToGlobal(pos)); } void NewTabularDialog::slotAlignColumn(int alignment) { - TabularHeaderItem *headerItem = static_cast(sender()); - - // find column - for(int column = 0; column < m_Table->columnCount(); ++column) { - if(m_Table->horizontalHeaderItem(column) == headerItem) { - for(int row = 0; row < m_Table->rowCount(); ++row) { - m_Table->item(row, column)->setTextAlignment(Qt::AlignVCenter | alignment); - } - - break; - } - } + TabularHeaderItem *headerItem = static_cast(sender()); + + // find column + for(int column = 0; column < m_Table->columnCount(); ++column) { + if(m_Table->horizontalHeaderItem(column) == headerItem) { + for(int row = 0; row < m_Table->rowCount(); ++row) { + m_Table->item(row, column)->setTextAlignment(Qt::AlignVCenter | alignment); + } + + break; + } + } } void NewTabularDialog::slotAlignLeft() { - alignItems(Qt::AlignLeft); + alignItems(Qt::AlignLeft); } void NewTabularDialog::slotAlignCenter() { - alignItems(Qt::AlignHCenter); + alignItems(Qt::AlignHCenter); } void NewTabularDialog::slotAlignRight() { - alignItems(Qt::AlignRight); + alignItems(Qt::AlignRight); } void NewTabularDialog::slotBold() { - foreach(QTableWidgetItem *item, m_Table->selectedItems()) { - QFont font = item->font(); - font.setBold(!font.bold()); - item->setFont(font); - } - slotItemSelectionChanged(); + foreach(QTableWidgetItem *item, m_Table->selectedItems()) { + QFont font = item->font(); + font.setBold(!font.bold()); + item->setFont(font); + } + slotItemSelectionChanged(); } void NewTabularDialog::slotItalic() { - foreach(QTableWidgetItem *item, m_Table->selectedItems()) { - QFont font = item->font(); - font.setItalic(!font.italic()); - item->setFont(font); - } - slotItemSelectionChanged(); + foreach(QTableWidgetItem *item, m_Table->selectedItems()) { + QFont font = item->font(); + font.setItalic(!font.italic()); + item->setFont(font); + } + slotItemSelectionChanged(); } void NewTabularDialog::slotUnderline() { - foreach(QTableWidgetItem *item, m_Table->selectedItems()) { - QFont font = item->font(); - font.setUnderline(!font.underline()); - item->setFont(font); - } - slotItemSelectionChanged(); + foreach(QTableWidgetItem *item, m_Table->selectedItems()) { + QFont font = item->font(); + font.setUnderline(!font.underline()); + item->setFont(font); + } + slotItemSelectionChanged(); } void NewTabularDialog::slotJoinCells() { - if(!canJoin()) return; + if(!canJoin()) return; - const QList selectedItems = m_Table->selectedItems(); - int row = selectedItems[0]->row(); + const QList selectedItems = m_Table->selectedItems(); + int row = selectedItems[0]->row(); - QList columns; - for(QTableWidgetItem* item : selectedItems) { - columns.append(item->column()); - } - std::sort(columns.begin(), columns.end()); + QList columns; + for(QTableWidgetItem* item : selectedItems) { + columns.append(item->column()); + } + std::sort(columns.begin(), columns.end()); - int newColumnSpan = columns.size(); + int newColumnSpan = columns.size(); - /* check for already joined cells in range */ - foreach(int column, columns) { - int thisColumnSpan = m_Table->columnSpan(row, column); - if(thisColumnSpan > 1) { - newColumnSpan = qMax(newColumnSpan, thisColumnSpan + column - columns.first()); - m_Table->setSpan(row, column, 1, 1); - } - } + /* check for already joined cells in range */ + foreach(int column, columns) { + int thisColumnSpan = m_Table->columnSpan(row, column); + if(thisColumnSpan > 1) { + newColumnSpan = qMax(newColumnSpan, thisColumnSpan + column - columns.first()); + m_Table->setSpan(row, column, 1, 1); + } + } - /* everything's fine -> join the cells */ - m_Table->setSpan(row, columns.first(), 1, newColumnSpan); + /* everything's fine -> join the cells */ + m_Table->setSpan(row, columns.first(), 1, newColumnSpan); - slotItemSelectionChanged(); + slotItemSelectionChanged(); } void NewTabularDialog::slotSplitCells() { - /* one item has to be selected */ - if(m_Table->selectedItems().count() != 1) return; + /* one item has to be selected */ + if(m_Table->selectedItems().count() != 1) return; - QTableWidgetItem *selectedItem = m_Table->selectedItems()[0]; + QTableWidgetItem *selectedItem = m_Table->selectedItems()[0]; - if(m_Table->columnSpan(selectedItem->row(), selectedItem->column()) > 1) { - m_Table->setSpan(selectedItem->row(), selectedItem->column(), 1, 1); - } + if(m_Table->columnSpan(selectedItem->row(), selectedItem->column()) > 1) { + m_Table->setSpan(selectedItem->row(), selectedItem->column(), 1, 1); + } - slotItemSelectionChanged(); + slotItemSelectionChanged(); } void NewTabularDialog::slotFrame(int border) { - foreach(QTableWidgetItem *item, m_Table->selectedItems()) { - static_cast(item)->setBorder(border); - } + foreach(QTableWidgetItem *item, m_Table->selectedItems()) { + static_cast(item)->setBorder(border); + } } void NewTabularDialog::slotBackground(const QColor &color) { - m_clCurrentBackground = color; - foreach(QTableWidgetItem *item, m_Table->selectedItems()) { - item->setBackground(color); - } - m_acBackground->setIcon(generateColorIcon(true)); - m_acForeground->setIcon(generateColorIcon(false)); + m_clCurrentBackground = color; + foreach(QTableWidgetItem *item, m_Table->selectedItems()) { + item->setBackground(color); + } + m_acBackground->setIcon(generateColorIcon(true)); + m_acForeground->setIcon(generateColorIcon(false)); } void NewTabularDialog::slotForeground(const QColor &color) { - m_clCurrentForeground = color; - foreach(QTableWidgetItem *item, m_Table->selectedItems()) { - item->setForeground(color); - } - m_acBackground->setIcon(generateColorIcon(true)); - m_acForeground->setIcon(generateColorIcon(false)); + m_clCurrentForeground = color; + foreach(QTableWidgetItem *item, m_Table->selectedItems()) { + item->setForeground(color); + } + m_acBackground->setIcon(generateColorIcon(true)); + m_acForeground->setIcon(generateColorIcon(false)); } void NewTabularDialog::slotCurrentBackground() { - slotBackground(m_clCurrentBackground); + slotBackground(m_clCurrentBackground); } void NewTabularDialog::slotCurrentForeground() { - slotForeground(m_clCurrentForeground); + slotForeground(m_clCurrentForeground); } void NewTabularDialog::slotClearText() { - foreach(QTableWidgetItem *item, m_Table->selectedItems()) { - item->setText(QString()); - } + foreach(QTableWidgetItem *item, m_Table->selectedItems()) { + item->setText(QString()); + } } void NewTabularDialog::slotClearAttributes() { - foreach(QTableWidgetItem *item, m_Table->selectedItems()) { - item->setTextAlignment(Qt::AlignLeft | Qt::AlignVCenter); - QFont font = item->font(); - font.setBold(false); - font.setItalic(false); - font.setUnderline(false); - item->setFont(font); - item->setBackground(QBrush()); - item->setForeground(QBrush()); - } + foreach(QTableWidgetItem *item, m_Table->selectedItems()) { + item->setTextAlignment(Qt::AlignLeft | Qt::AlignVCenter); + QFont font = item->font(); + font.setBold(false); + font.setItalic(false); + font.setUnderline(false); + item->setFont(font); + item->setBackground(QBrush()); + item->setForeground(QBrush()); + } } void NewTabularDialog::slotClearAll() { - slotClearText(); - slotClearAttributes(); + slotClearText(); + slotClearAttributes(); } void NewTabularDialog::slotRowAppended() { - const int newValue = m_sbRows->value() + 1; + const int newValue = m_sbRows->value() + 1; - m_sbRows->setMaximum(qMax(m_sbRows->maximum(), newValue)); - m_sbRows->setValue(newValue); + m_sbRows->setMaximum(qMax(m_sbRows->maximum(), newValue)); + m_sbRows->setValue(newValue); - updateColsAndRows(); + updateColsAndRows(); } void NewTabularDialog::slotColAppended() { - const int newValue = m_sbCols->value() + 1; + const int newValue = m_sbCols->value() + 1; - m_sbCols->setMaximum(qMax(m_sbCols->maximum(), newValue)); - m_sbCols->setValue(newValue); + m_sbCols->setMaximum(qMax(m_sbCols->maximum(), newValue)); + m_sbCols->setValue(newValue); - updateColsAndRows(); + updateColsAndRows(); } } void KileDialog::NewTabularDialog::slotStarredChanged() { - m_leTableWidth->setEnabled(m_cbStarred->isChecked() && m_cbStarred->isEnabled()); + m_leTableWidth->setEnabled(m_cbStarred->isChecked() && m_cbStarred->isEnabled()); } diff --git a/src/dialogs/tabular/newtabulardialog.h b/src/dialogs/tabular/newtabulardialog.h index d313a2bb..f843f106 100644 --- a/src/dialogs/tabular/newtabulardialog.h +++ b/src/dialogs/tabular/newtabulardialog.h @@ -1,120 +1,120 @@ /*************************************************************************** begin : Sunday Jun 27 2008 copyright : (C) 2008 by Mathias Soeken email : msoeken@informatik.uni-bremen.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. * * * ***************************************************************************/ #ifndef NEW_TABULARDIALOG_H #define NEW_TABULARDIALOG_H #include #include "kilewizard.h" class QAction; class QCheckBox; class QComboBox; class QIcon; class QLineEdit; class QMenu; class QPushButton; class QSpinBox; class QTableWidget; class QToolBar; class KComboBox; namespace KileDocument { - class LatexCommands; +class LatexCommands; } namespace KileDialog { class SelectColorAction; class SelectFrameAction; class TabularProperties; class TabularCell; class TabularTable; class NewTabularDialog : public Wizard { - Q_OBJECT - - public: - NewTabularDialog(const QString &environment, KileDocument::LatexCommands *commands, KConfig *config, QWidget *parent = 0); - ~NewTabularDialog(); - - const QStringList& requiredPackages() const; - QString environment() const; - - private: - void initEnvironments(); - QAction * addAction(const QIcon &icon, const QString &text, const char *method, QObject *parent = Q_NULLPTR); - QAction * addAction(const QIcon &icon, const QString &text, QObject *receiver, const char *method, QObject *parent = Q_NULLPTR); - void alignItems(int alignment); - bool checkForColumnAlignment(int column); - QIcon generateColorIcon(bool background) const; - bool canJoin() const; - - public Q_SLOTS: - int exec(); - void slotAccepted(); - - private Q_SLOTS: - void updateColsAndRows(); - void slotEnvironmentChanged(const QString &environment); - void slotItemSelectionChanged(); - void slotHeaderCustomContextMenuRequested(const QPoint &pos); - void slotAlignColumn(int alignment); - void slotAlignLeft(); - void slotAlignCenter(); - void slotAlignRight(); - void slotBold(); - void slotItalic(); - void slotUnderline(); - void slotJoinCells(); - void slotSplitCells(); - void slotFrame(int border); - void slotBackground(const QColor &color); - void slotForeground(const QColor &color); - void slotCurrentBackground(); - void slotCurrentForeground(); - void slotClearText(); - void slotClearAttributes(); - void slotClearAll(); - void slotRowAppended(); - void slotColAppended(); - void slotStarredChanged(); - - private: - KileDocument::LatexCommands *m_latexCommands; - - QAction *m_acLeft, *m_acCenter, *m_acRight, - *m_acBold, *m_acItalic, *m_acUnderline, - *m_acJoin, *m_acSplit, - *m_acClearText, *m_acClearAttributes, *m_acClearAll, - *m_acPaste; - SelectFrameAction *m_acFrame; - SelectColorAction *m_acBackground, *m_acForeground; - QToolBar *m_tbFormat; - TabularTable *m_Table; - QComboBox *m_cmbName, *m_cmbParameter; - QSpinBox *m_sbRows, *m_sbCols; - QCheckBox *m_cbStarred, *m_cbCenter, *m_cbBooktabs, *m_cbBullets; - QLineEdit *m_leTableWidth; - QColor m_clCurrentBackground, m_clCurrentForeground; - QString m_defaultEnvironment; - QStringList m_requiredPackages; + Q_OBJECT + +public: + NewTabularDialog(const QString &environment, KileDocument::LatexCommands *commands, KConfig *config, QWidget *parent = 0); + ~NewTabularDialog(); + + const QStringList& requiredPackages() const; + QString environment() const; + +private: + void initEnvironments(); + QAction * addAction(const QIcon &icon, const QString &text, const char *method, QObject *parent = Q_NULLPTR); + QAction * addAction(const QIcon &icon, const QString &text, QObject *receiver, const char *method, QObject *parent = Q_NULLPTR); + void alignItems(int alignment); + bool checkForColumnAlignment(int column); + QIcon generateColorIcon(bool background) const; + bool canJoin() const; + +public Q_SLOTS: + int exec(); + void slotAccepted(); + +private Q_SLOTS: + void updateColsAndRows(); + void slotEnvironmentChanged(const QString &environment); + void slotItemSelectionChanged(); + void slotHeaderCustomContextMenuRequested(const QPoint &pos); + void slotAlignColumn(int alignment); + void slotAlignLeft(); + void slotAlignCenter(); + void slotAlignRight(); + void slotBold(); + void slotItalic(); + void slotUnderline(); + void slotJoinCells(); + void slotSplitCells(); + void slotFrame(int border); + void slotBackground(const QColor &color); + void slotForeground(const QColor &color); + void slotCurrentBackground(); + void slotCurrentForeground(); + void slotClearText(); + void slotClearAttributes(); + void slotClearAll(); + void slotRowAppended(); + void slotColAppended(); + void slotStarredChanged(); + +private: + KileDocument::LatexCommands *m_latexCommands; + + QAction *m_acLeft, *m_acCenter, *m_acRight, + *m_acBold, *m_acItalic, *m_acUnderline, + *m_acJoin, *m_acSplit, + *m_acClearText, *m_acClearAttributes, *m_acClearAll, + *m_acPaste; + SelectFrameAction *m_acFrame; + SelectColorAction *m_acBackground, *m_acForeground; + QToolBar *m_tbFormat; + TabularTable *m_Table; + QComboBox *m_cmbName, *m_cmbParameter; + QSpinBox *m_sbRows, *m_sbCols; + QCheckBox *m_cbStarred, *m_cbCenter, *m_cbBooktabs, *m_cbBullets; + QLineEdit *m_leTableWidth; + QColor m_clCurrentBackground, m_clCurrentForeground; + QString m_defaultEnvironment; + QStringList m_requiredPackages; }; } #endif diff --git a/src/dialogs/tabular/selectcoloraction.cpp b/src/dialogs/tabular/selectcoloraction.cpp index ba2ab7d8..e7bd3342 100644 --- a/src/dialogs/tabular/selectcoloraction.cpp +++ b/src/dialogs/tabular/selectcoloraction.cpp @@ -1,43 +1,43 @@ /******************************************************************************************** begin : Sunday Jun 27 2008 copyright : (C) 2008 by Mathias Soeken (msoeken@informatik.uni-bremen.de) copyright : (C) 2005-2006 by Holger Danielsson (holger.danielsson@t-online.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. * * * ***************************************************************************/ #include "selectcoloraction.h" #include #include #include #include #include #include #include namespace KileDialog { SelectColorAction::SelectColorAction(const QIcon &icon, const QString &text, QWidget *parent) - : QAction(icon, text, parent) + : QAction(icon, text, parent) { - connect(this, &QAction::triggered, this, &SelectColorAction::showDialog); + connect(this, &QAction::triggered, this, &SelectColorAction::showDialog); } void SelectColorAction::showDialog() { - QColor color = QColorDialog::getColor(); - if (color.isValid()) { - emit colorSelected(color); - } + QColor color = QColorDialog::getColor(); + if (color.isValid()) { + emit colorSelected(color); + } } } diff --git a/src/dialogs/tabular/selectcoloraction.h b/src/dialogs/tabular/selectcoloraction.h index 2fa51fa1..0479b406 100644 --- a/src/dialogs/tabular/selectcoloraction.h +++ b/src/dialogs/tabular/selectcoloraction.h @@ -1,38 +1,38 @@ /*************************************************************************** begin : Sunday Jun 27 2008 copyright : (C) 2008 by Mathias Soeken email : msoeken@informatik.uni-bremen.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. * * * ***************************************************************************/ #ifndef SELECTCOLORACTION_H #define SELECTCOLORACTION_H #include namespace KileDialog { class SelectColorAction : public QAction { - Q_OBJECT + Q_OBJECT public: - SelectColorAction(const QIcon &icon, const QString &text, QWidget *parent); + SelectColorAction(const QIcon &icon, const QString &text, QWidget *parent); private Q_SLOTS: - void showDialog(); + void showDialog(); Q_SIGNALS: - void colorSelected(const QColor &color); + void colorSelected(const QColor &color); }; } #endif diff --git a/src/dialogs/tabular/selectframeaction.cpp b/src/dialogs/tabular/selectframeaction.cpp index 523b1699..96514ce5 100644 --- a/src/dialogs/tabular/selectframeaction.cpp +++ b/src/dialogs/tabular/selectframeaction.cpp @@ -1,376 +1,378 @@ /******************************************************************************************** begin : Sunday Jun 27 2008 copyright : (C) 2008 by Mathias Soeken (msoeken@informatik.uni-bremen.de) copyright : (C) 2005-2006 by Holger Danielsson (holger.danielsson@t-online.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. * * * ***************************************************************************/ #include "selectframeaction.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "tabularcell.h" namespace KileDialog { //BEGIN Icons for standard frames static const char* const all_border_xpm[] = { -"14 14 2 1", -"# c #000000", -". c #ffffff", -"##############", -"#............#", -"#............#", -"#............#", -"#............#", -"#............#", -"#............#", -"#............#", -"#............#", -"#............#", -"#............#", -"#............#", -"#............#", -"##############" + "14 14 2 1", + "# c #000000", + ". c #ffffff", + "##############", + "#............#", + "#............#", + "#............#", + "#............#", + "#............#", + "#............#", + "#............#", + "#............#", + "#............#", + "#............#", + "#............#", + "#............#", + "##############" }; static const char* const lr_border_xpm[] = { -"14 14 2 1", -"# c #000000", -". c #ffffff", -"#............#", -"#............#", -"#............#", -"#............#", -"#............#", -"#............#", -"#............#", -"#............#", -"#............#", -"#............#", -"#............#", -"#............#", -"#............#", -"#............#" + "14 14 2 1", + "# c #000000", + ". c #ffffff", + "#............#", + "#............#", + "#............#", + "#............#", + "#............#", + "#............#", + "#............#", + "#............#", + "#............#", + "#............#", + "#............#", + "#............#", + "#............#", + "#............#" }; static const char* const tb_border_xpm[] = { -"14 14 2 1", -"# c #000000", -". c #ffffff", -"##############", -"..............", -"..............", -"..............", -"..............", -"..............", -"..............", -"..............", -"..............", -"..............", -"..............", -"..............", -"..............", -"##############" + "14 14 2 1", + "# c #000000", + ". c #ffffff", + "##############", + "..............", + "..............", + "..............", + "..............", + "..............", + "..............", + "..............", + "..............", + "..............", + "..............", + "..............", + "..............", + "##############" }; static const char* const no_border_xpm[] = { -"14 14 2 1", -"# c #000000", -". c #ffffff", -"..............", -"..............", -"..............", -"..............", -"..............", -"..............", -"..............", -"..............", -"..............", -"..............", -"..............", -"..............", -"..............", -".............." + "14 14 2 1", + "# c #000000", + ". c #ffffff", + "..............", + "..............", + "..............", + "..............", + "..............", + "..............", + "..............", + "..............", + "..............", + "..............", + "..............", + "..............", + "..............", + ".............." }; //END //BEGIN TabularFrameWidget class TabularFrameWidget : public QFrame { - public: - TabularFrameWidget(QWidget* parent = Q_NULLPTR); - void setBorder(int value); - int border() const { return m_border; } - - protected: - void paintEvent(QPaintEvent *event); - void mousePressEvent(QMouseEvent *event); - - private: - int m_border; - QRect m_left, m_top, m_right, m_bottom; +public: + TabularFrameWidget(QWidget* parent = Q_NULLPTR); + void setBorder(int value); + int border() const { + return m_border; + } + +protected: + void paintEvent(QPaintEvent *event); + void mousePressEvent(QMouseEvent *event); + +private: + int m_border; + QRect m_left, m_top, m_right, m_bottom; }; TabularFrameWidget::TabularFrameWidget(QWidget* parent) - : QFrame(parent) + : QFrame(parent) { - m_border = TabularCell::None; - - QPalette p = palette(); - p.setColor(backgroundRole(), QColor(Qt::white)); - setPalette(p); - setFixedWidth(120); - setFixedHeight(120); - setLineWidth(2); - setFrameStyle(QFrame::Box | QFrame::Raised); - - QRect r = contentsRect(); - int x1 = r.left(); - int y1 = r.top(); - int x2 = r.right(); - int y2 = r.bottom(); - - m_left.setRect(x1, y1 + 20, 20, y2 - 43); - m_top.setRect(x1 + 20, y1, x2 - 43, 20); - m_right.setRect(x2 - 20, y1 + 20, 20, y2 - 43); - m_bottom.setRect(x1 + 20, y2 - 20, x2 - 43, 20); + m_border = TabularCell::None; + + QPalette p = palette(); + p.setColor(backgroundRole(), QColor(Qt::white)); + setPalette(p); + setFixedWidth(120); + setFixedHeight(120); + setLineWidth(2); + setFrameStyle(QFrame::Box | QFrame::Raised); + + QRect r = contentsRect(); + int x1 = r.left(); + int y1 = r.top(); + int x2 = r.right(); + int y2 = r.bottom(); + + m_left.setRect(x1, y1 + 20, 20, y2 - 43); + m_top.setRect(x1 + 20, y1, x2 - 43, 20); + m_right.setRect(x2 - 20, y1 + 20, 20, y2 - 43); + m_bottom.setRect(x1 + 20, y2 - 20, x2 - 43, 20); } void TabularFrameWidget::setBorder(int value) { - m_border = value; - update(); + m_border = value; + update(); } void TabularFrameWidget::paintEvent(QPaintEvent *event) { - Q_UNUSED(event); - QPainter painter(this); - - QRect r = contentsRect(); - int x1 = r.left(); - int y1 = r.top(); - int x2 = r.right(); - int y2 = r.bottom(); - - // left/top - painter.setPen(Qt::black); - painter.drawLine(x1 + 6, y1 + 14, x1 + 14, y1 + 14); - painter.drawLine(x1 + 14, y1 + 14, x1 + 14, y1 + 6); - - // left/bottom - painter.drawLine(x1 + 6, y2 - 14, x1 + 14, y2 - 14); - painter.drawLine(x1 + 14, y2 - 14, x1 + 14, y2 - 6); - - // right/top - painter.drawLine(x2 - 6, y1 + 14, x2 - 14, y1 + 14); - painter.drawLine(x2 - 14, y1 + 14, x2 - 14, y1 + 6); - - // right/bottom - painter.drawLine(x2 - 6, y2 - 14, x2 - 14, y2 - 14); - painter.drawLine(x2 - 14, y2 - 14, x2 - 14, y2 - 6); - - // centered rectangle - painter.setPen(Qt::gray); - painter.setBrush(Qt::gray); - painter.drawRect(x1 + 20, y1 + 20, x2 - 43, y2 - 43); - - //QPen pen = QPen(Qt::red,4); - QPen pen = QPen(Qt::black, 4); - painter.setPen(pen); - if(m_border & TabularCell::Left) { - painter.drawLine(x1 + 10, y1 + 20, x1 + 10, y2 - 20); - } - if(m_border & TabularCell::Top) { - painter.drawLine(x1 + 20, y1 + 10, x2 - 20, y1 + 10); - } - if(m_border & TabularCell::Right) { - painter.drawLine(x2 - 10, y1 + 20, x2 - 10, y2 - 20); - } - if(m_border & TabularCell::Bottom) { - painter.drawLine(x1 + 20, y2 - 10, x2 - 20, y2 - 10); - } + Q_UNUSED(event); + QPainter painter(this); + + QRect r = contentsRect(); + int x1 = r.left(); + int y1 = r.top(); + int x2 = r.right(); + int y2 = r.bottom(); + + // left/top + painter.setPen(Qt::black); + painter.drawLine(x1 + 6, y1 + 14, x1 + 14, y1 + 14); + painter.drawLine(x1 + 14, y1 + 14, x1 + 14, y1 + 6); + + // left/bottom + painter.drawLine(x1 + 6, y2 - 14, x1 + 14, y2 - 14); + painter.drawLine(x1 + 14, y2 - 14, x1 + 14, y2 - 6); + + // right/top + painter.drawLine(x2 - 6, y1 + 14, x2 - 14, y1 + 14); + painter.drawLine(x2 - 14, y1 + 14, x2 - 14, y1 + 6); + + // right/bottom + painter.drawLine(x2 - 6, y2 - 14, x2 - 14, y2 - 14); + painter.drawLine(x2 - 14, y2 - 14, x2 - 14, y2 - 6); + + // centered rectangle + painter.setPen(Qt::gray); + painter.setBrush(Qt::gray); + painter.drawRect(x1 + 20, y1 + 20, x2 - 43, y2 - 43); + + //QPen pen = QPen(Qt::red,4); + QPen pen = QPen(Qt::black, 4); + painter.setPen(pen); + if(m_border & TabularCell::Left) { + painter.drawLine(x1 + 10, y1 + 20, x1 + 10, y2 - 20); + } + if(m_border & TabularCell::Top) { + painter.drawLine(x1 + 20, y1 + 10, x2 - 20, y1 + 10); + } + if(m_border & TabularCell::Right) { + painter.drawLine(x2 - 10, y1 + 20, x2 - 10, y2 - 20); + } + if(m_border & TabularCell::Bottom) { + painter.drawLine(x1 + 20, y2 - 10, x2 - 20, y2 - 10); + } } void TabularFrameWidget::mousePressEvent(QMouseEvent *event) { - if (event->button() != Qt::LeftButton) - return; - - int x = event->x(); - int y = event->y(); - - int state = 0; - if(m_left.contains(x, y)) - state = TabularCell::Left; - else if(m_top.contains(x, y)) - state = TabularCell::Top; - else if(m_right.contains(x, y)) - state = TabularCell::Right; - else if(m_bottom.contains(x, y)) - state = TabularCell::Bottom; - - if(state > 0) { - if(m_border & state) { - m_border &= ~state; - } - else { - m_border |= state; - } - update(); - } + if (event->button() != Qt::LeftButton) + return; + + int x = event->x(); + int y = event->y(); + + int state = 0; + if(m_left.contains(x, y)) + state = TabularCell::Left; + else if(m_top.contains(x, y)) + state = TabularCell::Top; + else if(m_right.contains(x, y)) + state = TabularCell::Right; + else if(m_bottom.contains(x, y)) + state = TabularCell::Bottom; + + if(state > 0) { + if(m_border & state) { + m_border &= ~state; + } + else { + m_border |= state; + } + update(); + } } //END SelectFrameAction::SelectFrameAction(const QString &text, QToolBar *parent) - : KToolBarPopupAction(QIcon(), text, parent), - m_Parent(parent), - m_CurrentBorder(TabularCell::None) + : KToolBarPopupAction(QIcon(), text, parent), + m_Parent(parent), + m_CurrentBorder(TabularCell::None) { - setIcon(generateIcon()); - - QWidget *page = new QWidget(parent); - QVBoxLayout *layout = new QVBoxLayout(); - layout->setMargin(0); - layout->setSpacing(0); - page->setLayout(layout); - - QWidget *buttonBox = new QWidget(page); - QHBoxLayout *buttonBoxLayout = new QHBoxLayout(); - buttonBoxLayout->setMargin(0); - buttonBox->setLayout(buttonBoxLayout); - - m_pbNone = new QToolButton(buttonBox); - m_pbLeftRight = new QToolButton(buttonBox); - m_pbTopBottom = new QToolButton(buttonBox); - m_pbAll = new QToolButton(buttonBox); - - m_pbNone->setIcon(QIcon(QPixmap(const_cast(no_border_xpm)))); - m_pbLeftRight->setIcon(QIcon(QPixmap(const_cast(lr_border_xpm)))); - m_pbTopBottom->setIcon(QIcon(QPixmap(const_cast(tb_border_xpm)))); - m_pbAll->setIcon(QIcon(QPixmap(const_cast(all_border_xpm)))); - - buttonBoxLayout->addStretch(); - buttonBoxLayout->addWidget(m_pbNone); - buttonBoxLayout->addWidget(m_pbLeftRight); - buttonBoxLayout->addWidget(m_pbTopBottom); - buttonBoxLayout->addWidget(m_pbAll); - buttonBoxLayout->addStretch(); - - QWidget *frameWidget = new QWidget(page); - QHBoxLayout *frameWidgetLayout = new QHBoxLayout(); - frameWidgetLayout->setMargin(0); - frameWidget->setLayout(frameWidgetLayout); - - m_FrameWidget = new TabularFrameWidget(frameWidget); - - frameWidgetLayout->addStretch(); - frameWidgetLayout->addWidget(m_FrameWidget); - frameWidgetLayout->addStretch(); - - m_pbDone = new QPushButton(QIcon::fromTheme("dialog-ok-apply"), i18n("Apply"), page); - - layout->addWidget(buttonBox); - layout->addWidget(frameWidget); - layout->addWidget(m_pbDone); - - QWidgetAction *widgetAction = new QWidgetAction(this); - widgetAction->setDefaultWidget(page); - menu()->addAction(widgetAction); - - connect(this, SIGNAL(triggered(bool)), - this, SLOT(slotTriggered())); - connect(m_pbNone, SIGNAL(clicked()), - this, SLOT(slotNoneClicked())); - connect(m_pbLeftRight, SIGNAL(clicked()), - this, SLOT(slotLeftRightClicked())); - connect(m_pbTopBottom, SIGNAL(clicked()), - this, SLOT(slotTopBottomClicked())); - connect(m_pbAll, SIGNAL(clicked()), - this, SLOT(slotAllClicked())); - connect(m_pbDone, SIGNAL(clicked()), - this, SLOT(slotDoneClicked())); + setIcon(generateIcon()); + + QWidget *page = new QWidget(parent); + QVBoxLayout *layout = new QVBoxLayout(); + layout->setMargin(0); + layout->setSpacing(0); + page->setLayout(layout); + + QWidget *buttonBox = new QWidget(page); + QHBoxLayout *buttonBoxLayout = new QHBoxLayout(); + buttonBoxLayout->setMargin(0); + buttonBox->setLayout(buttonBoxLayout); + + m_pbNone = new QToolButton(buttonBox); + m_pbLeftRight = new QToolButton(buttonBox); + m_pbTopBottom = new QToolButton(buttonBox); + m_pbAll = new QToolButton(buttonBox); + + m_pbNone->setIcon(QIcon(QPixmap(const_cast(no_border_xpm)))); + m_pbLeftRight->setIcon(QIcon(QPixmap(const_cast(lr_border_xpm)))); + m_pbTopBottom->setIcon(QIcon(QPixmap(const_cast(tb_border_xpm)))); + m_pbAll->setIcon(QIcon(QPixmap(const_cast(all_border_xpm)))); + + buttonBoxLayout->addStretch(); + buttonBoxLayout->addWidget(m_pbNone); + buttonBoxLayout->addWidget(m_pbLeftRight); + buttonBoxLayout->addWidget(m_pbTopBottom); + buttonBoxLayout->addWidget(m_pbAll); + buttonBoxLayout->addStretch(); + + QWidget *frameWidget = new QWidget(page); + QHBoxLayout *frameWidgetLayout = new QHBoxLayout(); + frameWidgetLayout->setMargin(0); + frameWidget->setLayout(frameWidgetLayout); + + m_FrameWidget = new TabularFrameWidget(frameWidget); + + frameWidgetLayout->addStretch(); + frameWidgetLayout->addWidget(m_FrameWidget); + frameWidgetLayout->addStretch(); + + m_pbDone = new QPushButton(QIcon::fromTheme("dialog-ok-apply"), i18n("Apply"), page); + + layout->addWidget(buttonBox); + layout->addWidget(frameWidget); + layout->addWidget(m_pbDone); + + QWidgetAction *widgetAction = new QWidgetAction(this); + widgetAction->setDefaultWidget(page); + menu()->addAction(widgetAction); + + connect(this, SIGNAL(triggered(bool)), + this, SLOT(slotTriggered())); + connect(m_pbNone, SIGNAL(clicked()), + this, SLOT(slotNoneClicked())); + connect(m_pbLeftRight, SIGNAL(clicked()), + this, SLOT(slotLeftRightClicked())); + connect(m_pbTopBottom, SIGNAL(clicked()), + this, SLOT(slotTopBottomClicked())); + connect(m_pbAll, SIGNAL(clicked()), + this, SLOT(slotAllClicked())); + connect(m_pbDone, SIGNAL(clicked()), + this, SLOT(slotDoneClicked())); } QIcon SelectFrameAction::generateIcon() { - QPixmap pixmap(m_Parent->iconSize()); + QPixmap pixmap(m_Parent->iconSize()); - QPainter painter(&pixmap); - painter.fillRect(pixmap.rect(), Qt::gray); + QPainter painter(&pixmap); + painter.fillRect(pixmap.rect(), Qt::gray); - painter.setPen(Qt::black); - if(m_CurrentBorder & TabularCell::Left) - painter.drawLine(0, 0, 0, pixmap.height() - 1); - if(m_CurrentBorder & TabularCell::Top) - painter.drawLine(0, 0, pixmap.width() - 1, 0); - if(m_CurrentBorder & TabularCell::Right) - painter.drawLine(pixmap.width() - 1, 0, pixmap.width() - 1, pixmap.height() - 1); - if(m_CurrentBorder & TabularCell::Bottom) - painter.drawLine(0, pixmap.height() - 1, pixmap.width() - 1, pixmap.height() - 1); + painter.setPen(Qt::black); + if(m_CurrentBorder & TabularCell::Left) + painter.drawLine(0, 0, 0, pixmap.height() - 1); + if(m_CurrentBorder & TabularCell::Top) + painter.drawLine(0, 0, pixmap.width() - 1, 0); + if(m_CurrentBorder & TabularCell::Right) + painter.drawLine(pixmap.width() - 1, 0, pixmap.width() - 1, pixmap.height() - 1); + if(m_CurrentBorder & TabularCell::Bottom) + painter.drawLine(0, pixmap.height() - 1, pixmap.width() - 1, pixmap.height() - 1); - painter.end(); + painter.end(); - return QIcon(pixmap); + return QIcon(pixmap); } void SelectFrameAction::slotTriggered() { - emit borderSelected(m_CurrentBorder); + emit borderSelected(m_CurrentBorder); } void SelectFrameAction::slotNoneClicked() { - m_FrameWidget->setBorder(TabularCell::None); + m_FrameWidget->setBorder(TabularCell::None); } void SelectFrameAction::slotLeftRightClicked() { - m_FrameWidget->setBorder(TabularCell::Left | TabularCell::Right); + m_FrameWidget->setBorder(TabularCell::Left | TabularCell::Right); } void SelectFrameAction::slotTopBottomClicked() { - m_FrameWidget->setBorder(TabularCell::Top | TabularCell::Bottom); + m_FrameWidget->setBorder(TabularCell::Top | TabularCell::Bottom); } void SelectFrameAction::slotAllClicked() { - m_FrameWidget->setBorder(TabularCell::Left | TabularCell::Right | TabularCell::Top | TabularCell::Bottom); + m_FrameWidget->setBorder(TabularCell::Left | TabularCell::Right | TabularCell::Top | TabularCell::Bottom); } void SelectFrameAction::slotDoneClicked() { - int newBorder = m_FrameWidget->border(); - if(m_CurrentBorder != newBorder) { - m_CurrentBorder = newBorder; - setIcon(generateIcon()); - } - emit borderSelected(newBorder); - menu()->hide(); + int newBorder = m_FrameWidget->border(); + if(m_CurrentBorder != newBorder) { + m_CurrentBorder = newBorder; + setIcon(generateIcon()); + } + emit borderSelected(newBorder); + menu()->hide(); } } diff --git a/src/dialogs/tabular/selectframeaction.h b/src/dialogs/tabular/selectframeaction.h index 5e7be08e..fcc05f75 100644 --- a/src/dialogs/tabular/selectframeaction.h +++ b/src/dialogs/tabular/selectframeaction.h @@ -1,60 +1,60 @@ /*************************************************************************** begin : Sunday Jun 27 2008 copyright : (C) 2008 by Mathias Soeken email : msoeken@informatik.uni-bremen.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. * * * ***************************************************************************/ #ifndef SELECTFRAMEACTION_H #define SELECTFRAMEACTION_H #include class QToolBar; class QToolButton; class QPushButton; namespace KileDialog { class TabularFrameWidget; class SelectFrameAction : public KToolBarPopupAction { - Q_OBJECT - - public: - SelectFrameAction(const QString &text, QToolBar *parent); - - private: - QIcon generateIcon(); - - private: - QToolButton *m_pbNone, *m_pbLeftRight, *m_pbTopBottom, *m_pbAll; - TabularFrameWidget *m_FrameWidget; - QPushButton *m_pbDone; - QToolBar *m_Parent; - int m_CurrentBorder; - - private Q_SLOTS: - void slotTriggered(); - void slotNoneClicked(); - void slotLeftRightClicked(); - void slotTopBottomClicked(); - void slotAllClicked(); - void slotDoneClicked(); - - Q_SIGNALS: - void borderSelected(int border); + Q_OBJECT + +public: + SelectFrameAction(const QString &text, QToolBar *parent); + +private: + QIcon generateIcon(); + +private: + QToolButton *m_pbNone, *m_pbLeftRight, *m_pbTopBottom, *m_pbAll; + TabularFrameWidget *m_FrameWidget; + QPushButton *m_pbDone; + QToolBar *m_Parent; + int m_CurrentBorder; + +private Q_SLOTS: + void slotTriggered(); + void slotNoneClicked(); + void slotLeftRightClicked(); + void slotTopBottomClicked(); + void slotAllClicked(); + void slotDoneClicked(); + +Q_SIGNALS: + void borderSelected(int border); }; } #endif diff --git a/src/dialogs/tabular/tabularcell.cpp b/src/dialogs/tabular/tabularcell.cpp index dc740212..e069e3ca 100644 --- a/src/dialogs/tabular/tabularcell.cpp +++ b/src/dialogs/tabular/tabularcell.cpp @@ -1,147 +1,147 @@ /******************************************************************************************** Copyright (C) 2008 by Mathias Soeken (msoeken@informatik.uni-bremen.de) (C) 2005-2006 by Holger Danielsson (holger.danielsson@t-online.de) (C) 2012 by Michel Ludwig (michel.ludwig@kdemail.net) ********************************************************************************************/ /*************************************************************************** * * * 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. * * * ***************************************************************************/ #include "tabularcell.h" #include "tabularheaderitem.h" #include "tabularproperties.h" namespace KileDialog { //BEGIN TabularCell TabularCell::TabularCell() - : QTableWidgetItem(), - m_Border(None) + : QTableWidgetItem(), + m_Border(None) { } TabularCell::TabularCell(const QString &text) - : QTableWidgetItem(text), - m_Border(None) + : QTableWidgetItem(text), + m_Border(None) { } void TabularCell::setBorder(int border) { - m_Border = border; - tableWidget()->update(); + m_Border = border; + tableWidget()->update(); } int TabularCell::border() const { - return m_Border; + return m_Border; } QString TabularCell::toLaTeX( TabularProperties &properties ) const { - QString prefix; - QString suffix; - - int alignment = textAlignment() & ~Qt::AlignVCenter; - TabularHeaderItem *headerItem = static_cast(tableWidget()->horizontalHeaderItem(column())); - - QString colorCommand; - if(background().style() != Qt::NoBrush - && !properties.rowColor(row()).isValid()) { - colorCommand = ">{\\columncolor{" + properties.colorName(background().color()) + "}}"; - } - - QString leftBorder, rightBorder; - // First col border always needs to be set - if(column() == 0) { - if(border() & TabularCell::Left) { - leftBorder = '|'; - } - } - // Does the cell have a right border? - if(border() & TabularCell::Right) { - rightBorder = '|'; - } - - bool adjustBorder = false; - // If 1st col has no left border, but the cell should have one, set it manually - if(column() == 0 && !properties.hasLeftBorder() && - (border() & TabularCell::Left)) { - adjustBorder = true; - } - // Do we have to set the right border manually? - if(!properties.hasBorderBesideColumn(column()) && - (border() & TabularCell::Right)) { - adjustBorder = true; - } - - int columnSpan = tableWidget()->columnSpan(row(), column()); - - if(headerItem->alignment() != alignment || !colorCommand.isEmpty() || - adjustBorder || columnSpan > 1 ) { - - switch(alignment) { - case Qt::AlignHCenter: - properties.setUseMultiColumn(); - prefix += "\\mc{" + QString::number(columnSpan) + "}{" + - leftBorder + colorCommand + 'c' + rightBorder + "}{"; - suffix = '}' + suffix; - break; - - case Qt::AlignRight: - properties.setUseMultiColumn(); - prefix += "\\mc{" + QString::number(columnSpan) + "}{" + - leftBorder + colorCommand + 'r' + rightBorder + "}{"; - suffix = '}' + suffix; - break; - default: // This handles Qt::AlignLeft, - // alignP, alignM, alignB and alignX (they get thrown away here) - properties.setUseMultiColumn(); - prefix += "\\mc{" + QString::number(columnSpan) + "}{" + - leftBorder + colorCommand + 'l' + rightBorder + "}{"; - suffix = '}' + suffix; - break; - }; - } - - /* format */ - if (font().bold()) { - prefix += "\\textbf{"; - suffix = '}' + suffix; - } - if (font().italic()) { - prefix += "\\textit{"; - suffix = '}' + suffix; - } - - /* prefix */ - if (font().underline()) { - prefix += "\\underline{"; - suffix = '}' + suffix; - } - - /* foreground color */ - if(foreground().style() != Qt::NoBrush) { - prefix += "\\textcolor{" + properties.colorName(foreground().color()) + "}{"; - suffix = '}' + suffix; - } - - /* content */ - QString content = ""; - QString incontent = text().trimmed(); - if(incontent.isEmpty()) { - incontent = properties.bullet(); - } - content += prefix + incontent + suffix; - return content; + QString prefix; + QString suffix; + + int alignment = textAlignment() & ~Qt::AlignVCenter; + TabularHeaderItem *headerItem = static_cast(tableWidget()->horizontalHeaderItem(column())); + + QString colorCommand; + if(background().style() != Qt::NoBrush + && !properties.rowColor(row()).isValid()) { + colorCommand = ">{\\columncolor{" + properties.colorName(background().color()) + "}}"; + } + + QString leftBorder, rightBorder; + // First col border always needs to be set + if(column() == 0) { + if(border() & TabularCell::Left) { + leftBorder = '|'; + } + } + // Does the cell have a right border? + if(border() & TabularCell::Right) { + rightBorder = '|'; + } + + bool adjustBorder = false; + // If 1st col has no left border, but the cell should have one, set it manually + if(column() == 0 && !properties.hasLeftBorder() && + (border() & TabularCell::Left)) { + adjustBorder = true; + } + // Do we have to set the right border manually? + if(!properties.hasBorderBesideColumn(column()) && + (border() & TabularCell::Right)) { + adjustBorder = true; + } + + int columnSpan = tableWidget()->columnSpan(row(), column()); + + if(headerItem->alignment() != alignment || !colorCommand.isEmpty() || + adjustBorder || columnSpan > 1 ) { + + switch(alignment) { + case Qt::AlignHCenter: + properties.setUseMultiColumn(); + prefix += "\\mc{" + QString::number(columnSpan) + "}{" + + leftBorder + colorCommand + 'c' + rightBorder + "}{"; + suffix = '}' + suffix; + break; + + case Qt::AlignRight: + properties.setUseMultiColumn(); + prefix += "\\mc{" + QString::number(columnSpan) + "}{" + + leftBorder + colorCommand + 'r' + rightBorder + "}{"; + suffix = '}' + suffix; + break; + default: // This handles Qt::AlignLeft, + // alignP, alignM, alignB and alignX (they get thrown away here) + properties.setUseMultiColumn(); + prefix += "\\mc{" + QString::number(columnSpan) + "}{" + + leftBorder + colorCommand + 'l' + rightBorder + "}{"; + suffix = '}' + suffix; + break; + }; + } + + /* format */ + if (font().bold()) { + prefix += "\\textbf{"; + suffix = '}' + suffix; + } + if (font().italic()) { + prefix += "\\textit{"; + suffix = '}' + suffix; + } + + /* prefix */ + if (font().underline()) { + prefix += "\\underline{"; + suffix = '}' + suffix; + } + + /* foreground color */ + if(foreground().style() != Qt::NoBrush) { + prefix += "\\textcolor{" + properties.colorName(foreground().color()) + "}{"; + suffix = '}' + suffix; + } + + /* content */ + QString content = ""; + QString incontent = text().trimmed(); + if(incontent.isEmpty()) { + incontent = properties.bullet(); + } + content += prefix + incontent + suffix; + return content; } //END } diff --git a/src/dialogs/tabular/tabularcell.h b/src/dialogs/tabular/tabularcell.h index 8f6c52dc..cd6cea04 100644 --- a/src/dialogs/tabular/tabularcell.h +++ b/src/dialogs/tabular/tabularcell.h @@ -1,47 +1,47 @@ /*************************************************************************** begin : Sunday Jun 27 2008 copyright : (C) 2008 by Mathias Soeken email : msoeken@informatik.uni-bremen.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. * * * ***************************************************************************/ #ifndef TABULARCELL_H #define TABULARCELL_H #include namespace KileDocument { - class LatexCommands; +class LatexCommands; } namespace KileDialog { class TabularProperties; class TabularCell : public QTableWidgetItem { - public: - enum { None = 0, Left = 1, Top = 2, Right = 4, Bottom = 8 }; +public: + enum { None = 0, Left = 1, Top = 2, Right = 4, Bottom = 8 }; - TabularCell(); - TabularCell(const QString &text); + TabularCell(); + TabularCell(const QString &text); - void setBorder(int border); - int border() const; - - QString toLaTeX( TabularProperties &properties ) const; + void setBorder(int border); + int border() const; - private: - int m_Border; + QString toLaTeX( TabularProperties &properties ) const; + +private: + int m_Border; }; } #endif diff --git a/src/dialogs/tabular/tabularcelldelegate.cpp b/src/dialogs/tabular/tabularcelldelegate.cpp index 1577c58b..86535a34 100644 --- a/src/dialogs/tabular/tabularcelldelegate.cpp +++ b/src/dialogs/tabular/tabularcelldelegate.cpp @@ -1,132 +1,132 @@ /******************************************************************************************** begin : Sunday Jun 27 2008 copyright : (C) 2008 by Mathias Soeken (msoeken@informatik.uni-bremen.de) copyright : (C) 2005-2006 by Holger Danielsson (holger.danielsson@t-online.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. * * * ***************************************************************************/ #include "tabularcelldelegate.h" #include #include #include #include #include "tabularcell.h" namespace KileDialog { TabularCellDelegate::TabularCellDelegate(QTableWidget *parent) - : QStyledItemDelegate(parent), - m_Table(parent) + : QStyledItemDelegate(parent), + m_Table(parent) { } void TabularCellDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const { - if(option.state & QStyle::State_Selected || option.state & QStyle::State_MouseOver) { - QStyledItemDelegate::paint(painter, option, index); - } else { - painter->fillRect(option.rect, qvariant_cast(index.model()->data(index, Qt::BackgroundRole))); - QFont oldFont = painter->font(); - painter->setFont(qvariant_cast(index.model()->data(index, Qt::FontRole))); - QRect textRect(option.rect.x() + 3, option.rect.y(), option.rect.width() - 6, option.rect.height()); - QApplication::style()->drawItemText(painter, textRect, - index.model()->data(index, Qt::TextAlignmentRole).toInt(), - QPalette(qvariant_cast(index.model()->data(index, Qt::ForegroundRole)).color()), - true, index.model()->data(index, Qt::DisplayRole).toString(), QPalette::Window ); - painter->setFont(oldFont); - } - - int rowCount = m_Table->rowCount(); - int columnCount = m_Table->columnCount(); - - int row = index.row(); - int column = index.column(); - - TabularCell *cell = static_cast(m_Table->item(row, column)); - - if(column == 0) { - painter->setPen(cell->border() & TabularCell::Left ? Qt::black : Qt::lightGray); - painter->drawLine(option.rect.topLeft(), option.rect.bottomLeft()); - } - - if(row == 0) { - painter->setPen(cell->border() & TabularCell::Top ? Qt::black : Qt::lightGray); - painter->drawLine(option.rect.topLeft(), option.rect.topRight()); - } - - bool right = (cell->border() & TabularCell::Right) - || (column < (columnCount - 1) && static_cast(m_Table->item(row, column + 1))->border() & TabularCell::Left); - painter->setPen(right ? Qt::black : Qt::lightGray); - painter->drawLine(option.rect.topRight(), option.rect.bottomRight()); - - bool bottom = (cell->border() & TabularCell::Bottom) - || (row < (rowCount - 1) && static_cast(m_Table->item(row + 1, column))->border() & TabularCell::Top); - painter->setPen(bottom ? Qt::black : Qt::lightGray); - painter->drawLine(option.rect.bottomLeft(), option.rect.bottomRight()); + if(option.state & QStyle::State_Selected || option.state & QStyle::State_MouseOver) { + QStyledItemDelegate::paint(painter, option, index); + } else { + painter->fillRect(option.rect, qvariant_cast(index.model()->data(index, Qt::BackgroundRole))); + QFont oldFont = painter->font(); + painter->setFont(qvariant_cast(index.model()->data(index, Qt::FontRole))); + QRect textRect(option.rect.x() + 3, option.rect.y(), option.rect.width() - 6, option.rect.height()); + QApplication::style()->drawItemText(painter, textRect, + index.model()->data(index, Qt::TextAlignmentRole).toInt(), + QPalette(qvariant_cast(index.model()->data(index, Qt::ForegroundRole)).color()), + true, index.model()->data(index, Qt::DisplayRole).toString(), QPalette::Window ); + painter->setFont(oldFont); + } + + int rowCount = m_Table->rowCount(); + int columnCount = m_Table->columnCount(); + + int row = index.row(); + int column = index.column(); + + TabularCell *cell = static_cast(m_Table->item(row, column)); + + if(column == 0) { + painter->setPen(cell->border() & TabularCell::Left ? Qt::black : Qt::lightGray); + painter->drawLine(option.rect.topLeft(), option.rect.bottomLeft()); + } + + if(row == 0) { + painter->setPen(cell->border() & TabularCell::Top ? Qt::black : Qt::lightGray); + painter->drawLine(option.rect.topLeft(), option.rect.topRight()); + } + + bool right = (cell->border() & TabularCell::Right) + || (column < (columnCount - 1) && static_cast(m_Table->item(row, column + 1))->border() & TabularCell::Left); + painter->setPen(right ? Qt::black : Qt::lightGray); + painter->drawLine(option.rect.topRight(), option.rect.bottomRight()); + + bool bottom = (cell->border() & TabularCell::Bottom) + || (row < (rowCount - 1) && static_cast(m_Table->item(row + 1, column))->border() & TabularCell::Top); + painter->setPen(bottom ? Qt::black : Qt::lightGray); + painter->drawLine(option.rect.bottomLeft(), option.rect.bottomRight()); } QWidget* TabularCellDelegate::createEditor(QWidget *parent, - const QStyleOptionViewItem &option, - const QModelIndex &index) const + const QStyleOptionViewItem &option, + const QModelIndex &index) const { - Q_UNUSED(option); - Q_UNUSED(index); + Q_UNUSED(option); + Q_UNUSED(index); - QLineEdit *editor = new QLineEdit(parent); - editor->setFrame(false); - return editor; + QLineEdit *editor = new QLineEdit(parent); + editor->setFrame(false); + return editor; } void TabularCellDelegate::setEditorData(QWidget *editor, - const QModelIndex &index) const + const QModelIndex &index) const { - QString value = index.model()->data(index, Qt::EditRole).toString(); - QBrush bgBrush = qvariant_cast(index.model()->data(index, Qt::BackgroundRole)); - QBrush fgBrush = qvariant_cast(index.model()->data(index, Qt::ForegroundRole)); - QFont font = qvariant_cast(index.model()->data(index, Qt::FontRole)); - int alignment = index.model()->data(index, Qt::TextAlignmentRole).toInt(); - QLineEdit *edit = static_cast(editor); - QString styleSheet; - if(bgBrush.style() != Qt::NoBrush) { - styleSheet += "background-color:" + bgBrush.color().name() + ';'; - } - if(fgBrush.style() != Qt::NoBrush) { - styleSheet += "color:" + fgBrush.color().name() + ';'; - } - edit->setStyleSheet(styleSheet); - edit->setAlignment((Qt::Alignment)alignment); - edit->setFont(font); - edit->setText(value); + QString value = index.model()->data(index, Qt::EditRole).toString(); + QBrush bgBrush = qvariant_cast(index.model()->data(index, Qt::BackgroundRole)); + QBrush fgBrush = qvariant_cast(index.model()->data(index, Qt::ForegroundRole)); + QFont font = qvariant_cast(index.model()->data(index, Qt::FontRole)); + int alignment = index.model()->data(index, Qt::TextAlignmentRole).toInt(); + QLineEdit *edit = static_cast(editor); + QString styleSheet; + if(bgBrush.style() != Qt::NoBrush) { + styleSheet += "background-color:" + bgBrush.color().name() + ';'; + } + if(fgBrush.style() != Qt::NoBrush) { + styleSheet += "color:" + fgBrush.color().name() + ';'; + } + edit->setStyleSheet(styleSheet); + edit->setAlignment((Qt::Alignment)alignment); + edit->setFont(font); + edit->setText(value); } void TabularCellDelegate::setModelData(QWidget *editor, - QAbstractItemModel *model, - const QModelIndex &index) const + QAbstractItemModel *model, + const QModelIndex &index) const { - QLineEdit *edit = static_cast(editor); - QString value = edit->text(); - model->setData(index, value, Qt::EditRole); + QLineEdit *edit = static_cast(editor); + QString value = edit->text(); + model->setData(index, value, Qt::EditRole); } void TabularCellDelegate::updateEditorGeometry(QWidget *editor, - const QStyleOptionViewItem &option, - const QModelIndex &index) const + const QStyleOptionViewItem &option, + const QModelIndex &index) const { - Q_UNUSED(index); + Q_UNUSED(index); - editor->setGeometry(option.rect); + editor->setGeometry(option.rect); } } diff --git a/src/dialogs/tabular/tabularcelldelegate.h b/src/dialogs/tabular/tabularcelldelegate.h index 9f10e2de..ebd445a0 100644 --- a/src/dialogs/tabular/tabularcelldelegate.h +++ b/src/dialogs/tabular/tabularcelldelegate.h @@ -1,49 +1,49 @@ /*************************************************************************** begin : Sunday Jun 27 2008 copyright : (C) 2008 by Mathias Soeken email : msoeken@informatik.uni-bremen.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. * * * ***************************************************************************/ #ifndef TABULARCELLDELEGATE_H #define TABULARCELLDELEGATE_H #include class QAbstractItemModel; class QModelIndex; class QPainter; class QStyleOptionViewItem; class QTableWidget; namespace KileDialog { class TabularCellDelegate : public QStyledItemDelegate { - public: - TabularCellDelegate(QTableWidget *parent = 0); +public: + TabularCellDelegate(QTableWidget *parent = 0); - virtual void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const; + virtual void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const; - virtual QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &option, - const QModelIndex &index) const; - virtual void setEditorData(QWidget *editor, const QModelIndex &index) const; - virtual void setModelData(QWidget *editor, QAbstractItemModel *model, - const QModelIndex &index) const; - virtual void updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, - const QModelIndex &index) const; + virtual QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &option, + const QModelIndex &index) const; + virtual void setEditorData(QWidget *editor, const QModelIndex &index) const; + virtual void setModelData(QWidget *editor, QAbstractItemModel *model, + const QModelIndex &index) const; + virtual void updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, + const QModelIndex &index) const; - private: - QTableWidget *m_Table; +private: + QTableWidget *m_Table; }; } #endif diff --git a/src/dialogs/tabular/tabularheaderitem.cpp b/src/dialogs/tabular/tabularheaderitem.cpp index 805b679f..5e80c6a8 100644 --- a/src/dialogs/tabular/tabularheaderitem.cpp +++ b/src/dialogs/tabular/tabularheaderitem.cpp @@ -1,241 +1,241 @@ /******************************************************************************************** begin : Sunday Jun 27 2008 copyright : (C) 2008 by Mathias Soeken (msoeken@informatik.uni-bremen.de) copyright : (C) 2005-2006 by Holger Danielsson (holger.danielsson@t-online.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. * * * ***************************************************************************/ #include "tabularheaderitem.h" #include #include #include #include namespace KileDialog { TabularHeaderItem::TabularHeaderItem(QWidget *parent) - : QObject(parent), - QTableWidgetItem(QIcon::fromTheme("format-justify-left"), "l"), - m_Alignment(Qt::AlignLeft), - m_InsertBefore(false), - m_InsertAfter(false), - m_SuppressSpace(false), - m_DontSuppressSpace(false), - m_hasXAlignment(false) -{ - m_Popup = new QMenu(parent); - m_Popup->addAction(QIcon::fromTheme("format-justify-left"), i18n("Align Left"), this, SLOT(slotAlignLeft())); - m_Popup->addAction(QIcon::fromTheme("format-justify-center"), i18n("Align Center"), this, SLOT(slotAlignCenter())); - m_Popup->addAction(QIcon::fromTheme("format-justify-right"), i18n("Align Right"), this, SLOT(slotAlignRight())); - m_Popup->addAction(i18n("p{w} Alignment"), this, SLOT(slotAlignP())); - m_Popup->addAction(i18n("b{w} Alignment"), this, SLOT(slotAlignB())); - m_Popup->addAction(i18n("m{w} Alignment"), this, SLOT(slotAlignM())); - m_acXAlignment = m_Popup->addAction(i18n("X Alignment"), this, SLOT(slotAlignX())); - m_Popup->addSeparator(); - m_acDeclPre = m_Popup->addAction(i18n("Insert Before Declaration"), this, SLOT(slotDeclPre())); - m_acDeclPost = m_Popup->addAction(i18n("Insert After Declaration"), this, SLOT(slotDeclPost())); - m_acDeclAt = m_Popup->addAction(i18n("Suppress Space"), this, SLOT(slotDeclAt())); - m_acDeclBang = m_Popup->addAction(i18n("Do not Suppress Space"), this, SLOT(slotDeclBang())); - - m_acDeclPre->setCheckable(true); - m_acDeclPost->setCheckable(true); - m_acDeclAt->setCheckable(true); - m_acDeclBang->setCheckable(true); + : QObject(parent), + QTableWidgetItem(QIcon::fromTheme("format-justify-left"), "l"), + m_Alignment(Qt::AlignLeft), + m_InsertBefore(false), + m_InsertAfter(false), + m_SuppressSpace(false), + m_DontSuppressSpace(false), + m_hasXAlignment(false) +{ + m_Popup = new QMenu(parent); + m_Popup->addAction(QIcon::fromTheme("format-justify-left"), i18n("Align Left"), this, SLOT(slotAlignLeft())); + m_Popup->addAction(QIcon::fromTheme("format-justify-center"), i18n("Align Center"), this, SLOT(slotAlignCenter())); + m_Popup->addAction(QIcon::fromTheme("format-justify-right"), i18n("Align Right"), this, SLOT(slotAlignRight())); + m_Popup->addAction(i18n("p{w} Alignment"), this, SLOT(slotAlignP())); + m_Popup->addAction(i18n("b{w} Alignment"), this, SLOT(slotAlignB())); + m_Popup->addAction(i18n("m{w} Alignment"), this, SLOT(slotAlignM())); + m_acXAlignment = m_Popup->addAction(i18n("X Alignment"), this, SLOT(slotAlignX())); + m_Popup->addSeparator(); + m_acDeclPre = m_Popup->addAction(i18n("Insert Before Declaration"), this, SLOT(slotDeclPre())); + m_acDeclPost = m_Popup->addAction(i18n("Insert After Declaration"), this, SLOT(slotDeclPost())); + m_acDeclAt = m_Popup->addAction(i18n("Suppress Space"), this, SLOT(slotDeclAt())); + m_acDeclBang = m_Popup->addAction(i18n("Do not Suppress Space"), this, SLOT(slotDeclBang())); + + m_acDeclPre->setCheckable(true); + m_acDeclPost->setCheckable(true); + m_acDeclAt->setCheckable(true); + m_acDeclBang->setCheckable(true); } void TabularHeaderItem::setAlignment(int alignment) { - m_Alignment = alignment; - format(); + m_Alignment = alignment; + format(); } int TabularHeaderItem::alignment() const { - return m_Alignment; + return m_Alignment; } bool TabularHeaderItem::insertBefore() const { - return m_InsertBefore; + return m_InsertBefore; } bool TabularHeaderItem::insertAfter() const { - return m_InsertAfter; + return m_InsertAfter; } bool TabularHeaderItem::suppressSpace() const { - return m_SuppressSpace; + return m_SuppressSpace; } bool TabularHeaderItem::dontSuppressSpace() const { - return m_DontSuppressSpace; + return m_DontSuppressSpace; } void TabularHeaderItem::setHasXAlignment(bool hasXAlignment) { - m_hasXAlignment = hasXAlignment; - if(!hasXAlignment && m_Alignment == AlignX) { - slotAlignLeft(); - } + m_hasXAlignment = hasXAlignment; + if(!hasXAlignment && m_Alignment == AlignX) { + slotAlignLeft(); + } } bool TabularHeaderItem::hasXAlignment() const { - return m_hasXAlignment; + return m_hasXAlignment; } QMenu* TabularHeaderItem::popupMenu() const { - m_acXAlignment->setVisible(m_hasXAlignment); - return m_Popup; + m_acXAlignment->setVisible(m_hasXAlignment); + return m_Popup; } void TabularHeaderItem::format() { - setIcon(iconForAlignment(m_Alignment)); - - QString text; - - if(m_SuppressSpace) { - text += '@'; - } else if(m_DontSuppressSpace) { - text += '!'; - } - if(m_InsertBefore) { - text += '>'; - } - - switch(m_Alignment) { - case Qt::AlignLeft: - text += 'l'; - break; - case Qt::AlignHCenter: - text += 'c'; - break; - case Qt::AlignRight: - text += 'r'; - break; - case AlignP: - text += 'p'; - break; - case AlignB: - text += 'b'; - break; - case AlignM: - text += 'm'; - break; - case AlignX: - text += 'X'; - break; - } - - if(m_InsertAfter) { - text += '<'; - } - - setText(text); + setIcon(iconForAlignment(m_Alignment)); + + QString text; + + if(m_SuppressSpace) { + text += '@'; + } else if(m_DontSuppressSpace) { + text += '!'; + } + if(m_InsertBefore) { + text += '>'; + } + + switch(m_Alignment) { + case Qt::AlignLeft: + text += 'l'; + break; + case Qt::AlignHCenter: + text += 'c'; + break; + case Qt::AlignRight: + text += 'r'; + break; + case AlignP: + text += 'p'; + break; + case AlignB: + text += 'b'; + break; + case AlignM: + text += 'm'; + break; + case AlignX: + text += 'X'; + break; + } + + if(m_InsertAfter) { + text += '<'; + } + + setText(text); } inline QIcon TabularHeaderItem::iconForAlignment(int alignment) const { - switch(alignment) { - case Qt::AlignLeft: - return QIcon::fromTheme("format-justify-left"); - case Qt::AlignHCenter: - return QIcon::fromTheme("format-justify-center"); - case Qt::AlignRight: - return QIcon::fromTheme("format-justify-right"); - default: - return QIcon(); - } + switch(alignment) { + case Qt::AlignLeft: + return QIcon::fromTheme("format-justify-left"); + case Qt::AlignHCenter: + return QIcon::fromTheme("format-justify-center"); + case Qt::AlignRight: + return QIcon::fromTheme("format-justify-right"); + default: + return QIcon(); + } } void TabularHeaderItem::slotAlignLeft() { - setAlignment(Qt::AlignLeft); - emit alignColumn(Qt::AlignLeft); + setAlignment(Qt::AlignLeft); + emit alignColumn(Qt::AlignLeft); } void TabularHeaderItem::slotAlignCenter() { - setAlignment(Qt::AlignHCenter); - emit alignColumn(Qt::AlignHCenter); + setAlignment(Qt::AlignHCenter); + emit alignColumn(Qt::AlignHCenter); } void TabularHeaderItem::slotAlignRight() { - setAlignment(Qt::AlignRight); - emit alignColumn(Qt::AlignRight); + setAlignment(Qt::AlignRight); + emit alignColumn(Qt::AlignRight); } void TabularHeaderItem::slotAlignP() { - setAlignment(AlignP); - emit alignColumn(AlignP); + setAlignment(AlignP); + emit alignColumn(AlignP); } void TabularHeaderItem::slotAlignB() { - setAlignment(AlignB); - emit alignColumn(AlignB); + setAlignment(AlignB); + emit alignColumn(AlignB); } void TabularHeaderItem::slotAlignM() { - setAlignment(AlignM); - emit alignColumn(AlignM); + setAlignment(AlignM); + emit alignColumn(AlignM); } void TabularHeaderItem::slotAlignX() { - setAlignment(AlignX); - emit alignColumn(AlignX); + setAlignment(AlignX); + emit alignColumn(AlignX); } void TabularHeaderItem::slotDeclPre() { - m_InsertBefore = m_acDeclPre->isChecked(); - format(); + m_InsertBefore = m_acDeclPre->isChecked(); + format(); } void TabularHeaderItem::slotDeclPost() { - m_InsertAfter = m_acDeclPost->isChecked(); - format(); + m_InsertAfter = m_acDeclPost->isChecked(); + format(); } void TabularHeaderItem::slotDeclAt() { - m_SuppressSpace = m_acDeclAt->isChecked(); - if(m_SuppressSpace) { - m_DontSuppressSpace = false; - m_acDeclBang->setChecked(false); - } - format(); + m_SuppressSpace = m_acDeclAt->isChecked(); + if(m_SuppressSpace) { + m_DontSuppressSpace = false; + m_acDeclBang->setChecked(false); + } + format(); } void TabularHeaderItem::slotDeclBang() { - m_DontSuppressSpace = m_acDeclBang->isChecked(); - if(m_DontSuppressSpace) { - m_SuppressSpace = false; - m_acDeclAt->setChecked(false); - } - format(); + m_DontSuppressSpace = m_acDeclBang->isChecked(); + if(m_DontSuppressSpace) { + m_SuppressSpace = false; + m_acDeclAt->setChecked(false); + } + format(); } } diff --git a/src/dialogs/tabular/tabularheaderitem.h b/src/dialogs/tabular/tabularheaderitem.h index 4dbb7604..83f52684 100644 --- a/src/dialogs/tabular/tabularheaderitem.h +++ b/src/dialogs/tabular/tabularheaderitem.h @@ -1,79 +1,79 @@ /*************************************************************************** begin : Sunday Jun 27 2008 copyright : (C) 2008 by Mathias Soeken email : msoeken@informatik.uni-bremen.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. * * * ***************************************************************************/ #ifndef TABULARHEADERITEM_H #define TABULARHEADERITEM_H #include class QAction; class QIcon; class QMenu; namespace KileDialog { class TabularHeaderItem : public QObject, public QTableWidgetItem { - Q_OBJECT - - public: - enum { AlignP = 0x0200, AlignB = 0x0400, AlignM = 0x0800, AlignX = 0x1000 }; - - TabularHeaderItem(QWidget *parent); - - void setAlignment(int alignment); - int alignment() const; - - bool insertBefore() const; - bool insertAfter() const; - bool suppressSpace() const; - bool dontSuppressSpace() const; - - void setHasXAlignment(bool hasXAlignment); - bool hasXAlignment() const; - - QMenu* popupMenu() const; - - private: - void format(); - QIcon iconForAlignment(int alignment) const; - - private Q_SLOTS: - void slotAlignLeft(); - void slotAlignCenter(); - void slotAlignRight(); - void slotAlignP(); - void slotAlignB(); - void slotAlignM(); - void slotAlignX(); - void slotDeclPre(); - void slotDeclPost(); - void slotDeclAt(); - void slotDeclBang(); - - Q_SIGNALS: - void alignColumn(int alignment); - - private: - int m_Alignment; - bool m_InsertBefore, m_InsertAfter, m_SuppressSpace, m_DontSuppressSpace; - QMenu *m_Popup; - QAction *m_acXAlignment, - *m_acDeclPre, *m_acDeclPost, *m_acDeclAt, *m_acDeclBang; - bool m_hasXAlignment; + Q_OBJECT + +public: + enum { AlignP = 0x0200, AlignB = 0x0400, AlignM = 0x0800, AlignX = 0x1000 }; + + TabularHeaderItem(QWidget *parent); + + void setAlignment(int alignment); + int alignment() const; + + bool insertBefore() const; + bool insertAfter() const; + bool suppressSpace() const; + bool dontSuppressSpace() const; + + void setHasXAlignment(bool hasXAlignment); + bool hasXAlignment() const; + + QMenu* popupMenu() const; + +private: + void format(); + QIcon iconForAlignment(int alignment) const; + +private Q_SLOTS: + void slotAlignLeft(); + void slotAlignCenter(); + void slotAlignRight(); + void slotAlignP(); + void slotAlignB(); + void slotAlignM(); + void slotAlignX(); + void slotDeclPre(); + void slotDeclPost(); + void slotDeclAt(); + void slotDeclBang(); + +Q_SIGNALS: + void alignColumn(int alignment); + +private: + int m_Alignment; + bool m_InsertBefore, m_InsertAfter, m_SuppressSpace, m_DontSuppressSpace; + QMenu *m_Popup; + QAction *m_acXAlignment, + *m_acDeclPre, *m_acDeclPost, *m_acDeclAt, *m_acDeclBang; + bool m_hasXAlignment; }; } #endif diff --git a/src/dialogs/tabular/tabularproperties.cpp b/src/dialogs/tabular/tabularproperties.cpp index a2fdb7c0..de6da347 100644 --- a/src/dialogs/tabular/tabularproperties.cpp +++ b/src/dialogs/tabular/tabularproperties.cpp @@ -1,149 +1,149 @@ /******************************************************************************************** Copyright (C) 2008 by Mathias Soeken (msoeken@informatik.uni-bremen.de) (C) 2005-2006 by Holger Danielsson (holger.danielsson@t-online.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. * * * ***************************************************************************/ #include "tabularproperties.h" namespace KileDialog { TabularProperties::TabularProperties() - : m_UseMultiColumn(false), m_ColorIndex(0), - m_TopBorder(false), m_LeftBorder(false) {} + : m_UseMultiColumn(false), m_ColorIndex(0), + m_TopBorder(false), m_LeftBorder(false) {} void TabularProperties::setUseMultiColumn(bool useMultiColumn) { - m_UseMultiColumn = useMultiColumn; + m_UseMultiColumn = useMultiColumn; } bool TabularProperties::useMultiColumn() const { - return m_UseMultiColumn; + return m_UseMultiColumn; } void TabularProperties::addRowColor(int row, const QColor &color) { - if(!color.isValid()) { - return; - } + if(!color.isValid()) { + return; + } - m_RowColors.insert(row, color); + m_RowColors.insert(row, color); } void TabularProperties::addColor(const QColor &color) { - if(!color.isValid()) { - return; - } + if(!color.isValid()) { + return; + } - if(!m_ColorNames.contains(color.name())) { - int index = m_ColorIndex; - int value; - QString colorName = "tc"; + if(!m_ColorNames.contains(color.name())) { + int index = m_ColorIndex; + int value; + QString colorName = "tc"; - do { - value = index % 26; - colorName += ('A' + value); - index -= value; - } while(index > 0); + do { + value = index % 26; + colorName += ('A' + value); + index -= value; + } while(index > 0); - if(m_ColorNames.count() == 0) { - m_RequiredPackages << "color" << "colortbl"; - } + if(m_ColorNames.count() == 0) { + m_RequiredPackages << "color" << "colortbl"; + } - m_ColorNames.insert(color.name(), colorName); - ++m_ColorIndex; - } + m_ColorNames.insert(color.name(), colorName); + ++m_ColorIndex; + } } QColor TabularProperties::rowColor(int row) const { - if(m_RowColors.contains(row)) { - return m_RowColors[row]; - } - else { - return QColor(); - } + if(m_RowColors.contains(row)) { + return m_RowColors[row]; + } + else { + return QColor(); + } } QString TabularProperties::colorName(const QColor &color) const { - if(color.isValid() && m_ColorNames.contains(color.name())) { - return m_ColorNames[color.name()]; - } - else { - return QString(); - } + if(color.isValid() && m_ColorNames.contains(color.name())) { + return m_ColorNames[color.name()]; + } + else { + return QString(); + } } const QHash& TabularProperties::colorNames() const { - return m_ColorNames; + return m_ColorNames; } const QStringList& TabularProperties::requiredPackages() const { - return m_RequiredPackages; + return m_RequiredPackages; } void TabularProperties::setBullet(const QString &bullet) { - m_Bullet = bullet; + m_Bullet = bullet; } QString TabularProperties::bullet() const { - return m_Bullet; + return m_Bullet; } void TabularProperties::addBorderUnderRow(int row) { - m_BorderUnderRow.append(row); + m_BorderUnderRow.append(row); } bool TabularProperties::hasBorderUnderRow(int row) const { - return m_BorderUnderRow.contains(row); + return m_BorderUnderRow.contains(row); } void TabularProperties::setHasTopBorder() { - m_TopBorder = true; + m_TopBorder = true; } bool TabularProperties::hasTopBorder() const { - return m_TopBorder; + return m_TopBorder; } void TabularProperties::addBorderBesideColumn(int column) { - m_BorderBesideColumn.append(column); + m_BorderBesideColumn.append(column); } bool TabularProperties::hasBorderBesideColumn(int column) const { - return m_BorderBesideColumn.contains(column); + return m_BorderBesideColumn.contains(column); } void TabularProperties::setHasLeftBorder() { - m_LeftBorder = true; + m_LeftBorder = true; } bool TabularProperties::hasLeftBorder() const { - return m_LeftBorder; + return m_LeftBorder; } } diff --git a/src/dialogs/tabular/tabularproperties.h b/src/dialogs/tabular/tabularproperties.h index 6d692ada..c9928f24 100644 --- a/src/dialogs/tabular/tabularproperties.h +++ b/src/dialogs/tabular/tabularproperties.h @@ -1,78 +1,78 @@ /*************************************************************************** Copyright (C) 2008 by Mathias Soeken (msoeken@informatik.uni-bremen.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. * * * ***************************************************************************/ #ifndef TABULARPROPERTIES_H #define TABULARPROPERTIES_H #include #include #include #include #include namespace KileDocument { - class LatexCommands; +class LatexCommands; } namespace KileDialog { /** * @brief This class stores data while generating LaTeX output. * * This class saves information like whether the \multicolumn command * and/or other commands have been used. */ class TabularProperties { - public: - TabularProperties(); +public: + TabularProperties(); - void setUseMultiColumn(bool useMultiColumn = true); - bool useMultiColumn() const; + void setUseMultiColumn(bool useMultiColumn = true); + bool useMultiColumn() const; - void addRowColor(int row, const QColor &color); - void addColor(const QColor &color); - QColor rowColor(int row) const; - QString colorName(const QColor &color) const; - const QHash& colorNames() const; + void addRowColor(int row, const QColor &color); + void addColor(const QColor &color); + QColor rowColor(int row) const; + QString colorName(const QColor &color) const; + const QHash& colorNames() const; - const QStringList& requiredPackages() const; + const QStringList& requiredPackages() const; - void setBullet(const QString &bullet); - QString bullet() const; + void setBullet(const QString &bullet); + QString bullet() const; - void addBorderUnderRow(int row); - bool hasBorderUnderRow(int row) const; - void setHasTopBorder(); - bool hasTopBorder() const; + void addBorderUnderRow(int row); + bool hasBorderUnderRow(int row) const; + void setHasTopBorder(); + bool hasTopBorder() const; - void addBorderBesideColumn(int column); - bool hasBorderBesideColumn(int column) const; - void setHasLeftBorder(); - bool hasLeftBorder() const; + void addBorderBesideColumn(int column); + bool hasBorderBesideColumn(int column) const; + void setHasLeftBorder(); + bool hasLeftBorder() const; - private: - bool m_UseMultiColumn; - QHash m_RowColors; - QHash m_ColorNames; - int m_ColorIndex; - QStringList m_RequiredPackages; - QString m_Bullet; - QList m_BorderUnderRow; - bool m_TopBorder; - QList m_BorderBesideColumn; - bool m_LeftBorder; +private: + bool m_UseMultiColumn; + QHash m_RowColors; + QHash m_ColorNames; + int m_ColorIndex; + QStringList m_RequiredPackages; + QString m_Bullet; + QList m_BorderUnderRow; + bool m_TopBorder; + QList m_BorderBesideColumn; + bool m_LeftBorder; }; } #endif diff --git a/src/dialogs/tabular/tabulartable.cpp b/src/dialogs/tabular/tabulartable.cpp index 14238f95..087f7cae 100644 --- a/src/dialogs/tabular/tabulartable.cpp +++ b/src/dialogs/tabular/tabulartable.cpp @@ -1,249 +1,249 @@ /******************************************************************************************** begin : Sunday Jun 27 2008 Copyright (C) 2008 by Mathias Soeken (msoeken@informatik.uni-bremen.de) (C) 2005-2006 by Holger Danielsson (holger.danielsson@t-online.de) (C) 2011 by Felix Mauch (felix_mauch@web.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. * * * ***************************************************************************/ #include "tabulartable.h" #include #include #include #include #include #include #include #include #include #include #include "tabularcell.h" #include "tabularcelldelegate.h" namespace KileDialog { TabularTable::TabularTable(QWidget *parent) - : QTableWidget(parent), m_ManualBorderPosition(QPoint(-1, -1)), - m_ManualBorderStart(QPoint(-1, -1)),m_LastItem(Q_NULLPTR) { - setItemDelegate(new TabularCellDelegate(this)); - setShowGrid(false); - setAttribute(Qt::WA_Hover, true); - horizontalHeader()->setContextMenuPolicy(Qt::CustomContextMenu); - installEventFilter(this); - m_DefaultMode = selectionMode(); + : QTableWidget(parent), m_ManualBorderPosition(QPoint(-1, -1)), + m_ManualBorderStart(QPoint(-1, -1)),m_LastItem(Q_NULLPTR) { + setItemDelegate(new TabularCellDelegate(this)); + setShowGrid(false); + setAttribute(Qt::WA_Hover, true); + horizontalHeader()->setContextMenuPolicy(Qt::CustomContextMenu); + installEventFilter(this); + m_DefaultMode = selectionMode(); } bool TabularTable::eventFilter(QObject *obj, QEvent *event) { - if(obj == this) { - if(event->type() == QEvent::KeyPress) { - QKeyEvent *keyEvent = static_cast(event); - - if(keyEvent->key() == Qt::Key_Return && selectedItems().count() == 1) { - QTableWidgetItem *selectedItem = selectedItems()[0]; - int row = selectedItem->row(); - int column = selectedItem->column(); - if(column < (columnCount() - 1)) { - selectedItem->setSelected(false); - item(row, column + 1)->setSelected(true); - setCurrentItem(item(row, column + 1)); - } else { - if(row == (rowCount() - 1)) { - emit rowAppended(); - } - selectedItem->setSelected(false); - item(row + 1, 0)->setSelected(true); - setCurrentItem(item(row + 1, 0)); - } - return true; - } - else if(keyEvent->matches(QKeySequence::Paste)) { - paste(); - } - } - else if(event->type() == QEvent::HoverMove) { - QHoverEvent *hoverEvent = static_cast(event); - QPoint pos = viewport()->mapFromGlobal(mapToGlobal(hoverEvent->pos())); - QTableWidgetItem *itemAtPos = itemAt(pos); - - if(itemAtPos) { - if(itemAtPos->row() == 0 && itemAtPos->column() == columnCount() - 1 && - (visualItemRect(itemAtPos).topRight() - pos).manhattanLength() <= 8) { - setCursor(Qt::CrossCursor); - m_ManualBorderPosition.setX(columnCount()); - m_ManualBorderPosition.setY(0); - } - else if(itemAtPos->row() == 0 && - (visualItemRect(itemAtPos).topLeft() - pos).manhattanLength() <= 8) { - setCursor(Qt::CrossCursor); - m_ManualBorderPosition.setX(itemAtPos->column()); - m_ManualBorderPosition.setY(0); - } - else if(itemAtPos->column() == columnCount() - 1 && - (visualItemRect(itemAtPos).bottomRight() - pos).manhattanLength() <= 8) { - setCursor(Qt::CrossCursor); - m_ManualBorderPosition.setX(columnCount()); - m_ManualBorderPosition.setY(itemAtPos->row() + 1); - } - else if((visualItemRect(itemAtPos).bottomLeft() - pos).manhattanLength() <= 8) { - setCursor(Qt::CrossCursor); - m_ManualBorderPosition.setX(itemAtPos->column()); - m_ManualBorderPosition.setY(itemAtPos->row() + 1); - } - else { - unsetCursor(); - m_ManualBorderPosition.setX(-1); - m_ManualBorderPosition.setY(-1); - } - } - else { - unsetCursor(); - m_ManualBorderPosition.setX(-1); - m_ManualBorderPosition.setY(-1); - } - - m_HoverPosition = pos; - viewport()->update(); - - return true; - } - } - - return QTableWidget::eventFilter(obj, event); + if(obj == this) { + if(event->type() == QEvent::KeyPress) { + QKeyEvent *keyEvent = static_cast(event); + + if(keyEvent->key() == Qt::Key_Return && selectedItems().count() == 1) { + QTableWidgetItem *selectedItem = selectedItems()[0]; + int row = selectedItem->row(); + int column = selectedItem->column(); + if(column < (columnCount() - 1)) { + selectedItem->setSelected(false); + item(row, column + 1)->setSelected(true); + setCurrentItem(item(row, column + 1)); + } else { + if(row == (rowCount() - 1)) { + emit rowAppended(); + } + selectedItem->setSelected(false); + item(row + 1, 0)->setSelected(true); + setCurrentItem(item(row + 1, 0)); + } + return true; + } + else if(keyEvent->matches(QKeySequence::Paste)) { + paste(); + } + } + else if(event->type() == QEvent::HoverMove) { + QHoverEvent *hoverEvent = static_cast(event); + QPoint pos = viewport()->mapFromGlobal(mapToGlobal(hoverEvent->pos())); + QTableWidgetItem *itemAtPos = itemAt(pos); + + if(itemAtPos) { + if(itemAtPos->row() == 0 && itemAtPos->column() == columnCount() - 1 && + (visualItemRect(itemAtPos).topRight() - pos).manhattanLength() <= 8) { + setCursor(Qt::CrossCursor); + m_ManualBorderPosition.setX(columnCount()); + m_ManualBorderPosition.setY(0); + } + else if(itemAtPos->row() == 0 && + (visualItemRect(itemAtPos).topLeft() - pos).manhattanLength() <= 8) { + setCursor(Qt::CrossCursor); + m_ManualBorderPosition.setX(itemAtPos->column()); + m_ManualBorderPosition.setY(0); + } + else if(itemAtPos->column() == columnCount() - 1 && + (visualItemRect(itemAtPos).bottomRight() - pos).manhattanLength() <= 8) { + setCursor(Qt::CrossCursor); + m_ManualBorderPosition.setX(columnCount()); + m_ManualBorderPosition.setY(itemAtPos->row() + 1); + } + else if((visualItemRect(itemAtPos).bottomLeft() - pos).manhattanLength() <= 8) { + setCursor(Qt::CrossCursor); + m_ManualBorderPosition.setX(itemAtPos->column()); + m_ManualBorderPosition.setY(itemAtPos->row() + 1); + } + else { + unsetCursor(); + m_ManualBorderPosition.setX(-1); + m_ManualBorderPosition.setY(-1); + } + } + else { + unsetCursor(); + m_ManualBorderPosition.setX(-1); + m_ManualBorderPosition.setY(-1); + } + + m_HoverPosition = pos; + viewport()->update(); + + return true; + } + } + + return QTableWidget::eventFilter(obj, event); } void TabularTable::mousePressEvent(QMouseEvent *event) { - m_ManualBorderStart = m_ManualBorderPosition; - if(m_ManualBorderStart.x() > -1) { - setSelectionMode(QAbstractItemView::NoSelection); - if(currentItem()) { - m_LastItem = currentItem(); - currentItem()->setSelected(false); - } - } - - QTableWidget::mousePressEvent(event); + m_ManualBorderStart = m_ManualBorderPosition; + if(m_ManualBorderStart.x() > -1) { + setSelectionMode(QAbstractItemView::NoSelection); + if(currentItem()) { + m_LastItem = currentItem(); + currentItem()->setSelected(false); + } + } + + QTableWidget::mousePressEvent(event); } void TabularTable::mouseReleaseEvent(QMouseEvent *event) { - if(m_ManualBorderStart.x() > -1) { - if(m_ManualBorderPosition.x() > -1) { - if(m_ManualBorderStart != m_ManualBorderPosition) { - if(m_ManualBorderStart.x() == m_ManualBorderPosition.x()) { - int column = (m_ManualBorderStart.x() == columnCount()) ? m_ManualBorderStart.x() - 1 : m_ManualBorderStart.x(); - for(int row = qMin(m_ManualBorderStart.y(), m_ManualBorderPosition.y()); - row < qMax(m_ManualBorderStart.y(), m_ManualBorderPosition.y()); ++row) { - TabularCell *cell = static_cast(item(row, column)); - int border = cell->border() | ((m_ManualBorderStart.x() == columnCount()) ? TabularCell::Right : TabularCell::Left); - cell->setBorder(border); - } - } else if(m_ManualBorderStart.y() == m_ManualBorderPosition.y()) { - int row = (m_ManualBorderStart.y() == rowCount()) ? m_ManualBorderStart.y() - 1 : m_ManualBorderStart.y(); - for(int column = qMin(m_ManualBorderStart.x(), m_ManualBorderPosition.x()); - column < qMax(m_ManualBorderStart.x(), m_ManualBorderPosition.x()); ++column) { - TabularCell *cell = static_cast(item(row, column)); - int border = cell->border() | ((m_ManualBorderStart.y() == rowCount()) ? TabularCell::Bottom : TabularCell::Top); - cell->setBorder(border); - } - } - viewport()->update(); - } - - m_ManualBorderPosition.setX(-1); - m_ManualBorderPosition.setY(-1); - } - - m_ManualBorderStart.setX(-1); - m_ManualBorderStart.setY(-1); - } - - setSelectionMode(m_DefaultMode); - if(m_LastItem) { - setCurrentItem(m_LastItem); - currentItem()->setSelected(true); - m_LastItem = 0; - } - QTableWidget::mouseReleaseEvent(event); + if(m_ManualBorderStart.x() > -1) { + if(m_ManualBorderPosition.x() > -1) { + if(m_ManualBorderStart != m_ManualBorderPosition) { + if(m_ManualBorderStart.x() == m_ManualBorderPosition.x()) { + int column = (m_ManualBorderStart.x() == columnCount()) ? m_ManualBorderStart.x() - 1 : m_ManualBorderStart.x(); + for(int row = qMin(m_ManualBorderStart.y(), m_ManualBorderPosition.y()); + row < qMax(m_ManualBorderStart.y(), m_ManualBorderPosition.y()); ++row) { + TabularCell *cell = static_cast(item(row, column)); + int border = cell->border() | ((m_ManualBorderStart.x() == columnCount()) ? TabularCell::Right : TabularCell::Left); + cell->setBorder(border); + } + } else if(m_ManualBorderStart.y() == m_ManualBorderPosition.y()) { + int row = (m_ManualBorderStart.y() == rowCount()) ? m_ManualBorderStart.y() - 1 : m_ManualBorderStart.y(); + for(int column = qMin(m_ManualBorderStart.x(), m_ManualBorderPosition.x()); + column < qMax(m_ManualBorderStart.x(), m_ManualBorderPosition.x()); ++column) { + TabularCell *cell = static_cast(item(row, column)); + int border = cell->border() | ((m_ManualBorderStart.y() == rowCount()) ? TabularCell::Bottom : TabularCell::Top); + cell->setBorder(border); + } + } + viewport()->update(); + } + + m_ManualBorderPosition.setX(-1); + m_ManualBorderPosition.setY(-1); + } + + m_ManualBorderStart.setX(-1); + m_ManualBorderStart.setY(-1); + } + + setSelectionMode(m_DefaultMode); + if(m_LastItem) { + setCurrentItem(m_LastItem); + currentItem()->setSelected(true); + m_LastItem = 0; + } + QTableWidget::mouseReleaseEvent(event); } void TabularTable::paintEvent(QPaintEvent *event) { - QPainter painter(viewport()); - if(m_ManualBorderStart.x() > -1) { - QTableWidgetItem *startItem = item( - (m_ManualBorderStart.y() == rowCount() ? m_ManualBorderStart.y() - 1 : m_ManualBorderStart.y()), - (m_ManualBorderStart.x() == columnCount() ? m_ManualBorderStart.x() - 1 : m_ManualBorderStart.x())); - - int xStart = (m_ManualBorderStart.x() == columnCount() ? visualItemRect(startItem).right() : visualItemRect(startItem).left()); - int yStart = (m_ManualBorderStart.y() == rowCount() ? visualItemRect(startItem).bottom() : visualItemRect(startItem).top()); - - QColor color = - ((m_ManualBorderStart != m_ManualBorderPosition) && - ((m_ManualBorderStart.x() == m_ManualBorderPosition.x()) || - (m_ManualBorderStart.y() == m_ManualBorderPosition.y())) ? Qt::darkGreen : Qt::darkRed); - painter.setPen(QPen(color, 2)); - painter.drawLine(xStart, yStart, m_HoverPosition.x(), m_HoverPosition.y()); - } - - QTableWidget::paintEvent(event); + QPainter painter(viewport()); + if(m_ManualBorderStart.x() > -1) { + QTableWidgetItem *startItem = item( + (m_ManualBorderStart.y() == rowCount() ? m_ManualBorderStart.y() - 1 : m_ManualBorderStart.y()), + (m_ManualBorderStart.x() == columnCount() ? m_ManualBorderStart.x() - 1 : m_ManualBorderStart.x())); + + int xStart = (m_ManualBorderStart.x() == columnCount() ? visualItemRect(startItem).right() : visualItemRect(startItem).left()); + int yStart = (m_ManualBorderStart.y() == rowCount() ? visualItemRect(startItem).bottom() : visualItemRect(startItem).top()); + + QColor color = + ((m_ManualBorderStart != m_ManualBorderPosition) && + ((m_ManualBorderStart.x() == m_ManualBorderPosition.x()) || + (m_ManualBorderStart.y() == m_ManualBorderPosition.y())) ? Qt::darkGreen : Qt::darkRed); + painter.setPen(QPen(color, 2)); + painter.drawLine(xStart, yStart, m_HoverPosition.x(), m_HoverPosition.y()); + } + + QTableWidget::paintEvent(event); } } void KileDialog::TabularTable::paste() { - // Maybe we want to insert content at a certain point in the table - int selectedRow = 0; - int selectedCol = 0; - if(!selectedItems().isEmpty()) { - selectedRow = selectedItems().first()->row(); - selectedCol = selectedItems().first()->column(); - } - - //Clipboard->QStringlist - QString selectedText = qApp->clipboard()->text(); - selectedText = selectedText.remove('\r'); - if(selectedText.isEmpty()) { - KMessageBox::information(this, i18n("There is no content to insert into the table as the clipboard is empty."), i18n("Empty Clipboard")); - return; - } - if(!selectedText.endsWith('\n')) { - selectedText += '\n'; - } - QStringList cells = selectedText.split(QRegExp(QLatin1String("\\n|\\t"))); - while(!cells.empty() && cells.back().size() == 0) { - cells.pop_back(); // strip empty trailing tokens - } - int rows = selectedText.count(QLatin1Char('\n')); - int cols = cells.size() / rows; - - // Fill everything in the tableWidget - // If needed, new rows and cols get generated on the fly - int cell = 0; - for(int row = 0; row < rows; ++row) { - if(selectedRow + row > (rowCount() - 1)) { - emit rowAppended(); - } - for(int col = 0; col < cols; ++col, ++cell) { - if(selectedCol + col > (columnCount() - 1)) { - emit colAppended(); - } - item(selectedRow + row, selectedCol + col)->setText(cells[cell]); - } - } + // Maybe we want to insert content at a certain point in the table + int selectedRow = 0; + int selectedCol = 0; + if(!selectedItems().isEmpty()) { + selectedRow = selectedItems().first()->row(); + selectedCol = selectedItems().first()->column(); + } + + //Clipboard->QStringlist + QString selectedText = qApp->clipboard()->text(); + selectedText = selectedText.remove('\r'); + if(selectedText.isEmpty()) { + KMessageBox::information(this, i18n("There is no content to insert into the table as the clipboard is empty."), i18n("Empty Clipboard")); + return; + } + if(!selectedText.endsWith('\n')) { + selectedText += '\n'; + } + QStringList cells = selectedText.split(QRegExp(QLatin1String("\\n|\\t"))); + while(!cells.empty() && cells.back().size() == 0) { + cells.pop_back(); // strip empty trailing tokens + } + int rows = selectedText.count(QLatin1Char('\n')); + int cols = cells.size() / rows; + + // Fill everything in the tableWidget + // If needed, new rows and cols get generated on the fly + int cell = 0; + for(int row = 0; row < rows; ++row) { + if(selectedRow + row > (rowCount() - 1)) { + emit rowAppended(); + } + for(int col = 0; col < cols; ++col, ++cell) { + if(selectedCol + col > (columnCount() - 1)) { + emit colAppended(); + } + item(selectedRow + row, selectedCol + col)->setText(cells[cell]); + } + } } diff --git a/src/dialogs/tabular/tabulartable.h b/src/dialogs/tabular/tabulartable.h index 91f9bf56..dc4799b6 100644 --- a/src/dialogs/tabular/tabulartable.h +++ b/src/dialogs/tabular/tabulartable.h @@ -1,56 +1,56 @@ /*************************************************************************** begin : Sunday Jun 27 2008 copyright : (C) 2008 by Mathias Soeken email : msoeken@informatik.uni-bremen.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. * * * ***************************************************************************/ #ifndef TABULARTABLE_H #define TABULARTABLE_H #include class QEvent; class QMouseEvent; class QPaintEvent; namespace KileDialog { class TabularTable : public QTableWidget { - Q_OBJECT - - public: - TabularTable(QWidget *parent = 0); - - public Q_SLOTS: - void paste(); - - protected: - bool eventFilter(QObject *obj, QEvent *event); - void mousePressEvent(QMouseEvent *event); - void mouseReleaseEvent(QMouseEvent *event); - void paintEvent(QPaintEvent *event); - - Q_SIGNALS: - void rowAppended(); - void colAppended(); - - private: - SelectionMode m_DefaultMode; - QPoint m_ManualBorderPosition; - QPoint m_ManualBorderStart; - QPoint m_HoverPosition; - QTableWidgetItem *m_LastItem; + Q_OBJECT + +public: + TabularTable(QWidget *parent = 0); + +public Q_SLOTS: + void paste(); + +protected: + bool eventFilter(QObject *obj, QEvent *event); + void mousePressEvent(QMouseEvent *event); + void mouseReleaseEvent(QMouseEvent *event); + void paintEvent(QPaintEvent *event); + +Q_SIGNALS: + void rowAppended(); + void colAppended(); + +private: + SelectionMode m_DefaultMode; + QPoint m_ManualBorderPosition; + QPoint m_ManualBorderStart; + QPoint m_HoverPosition; + QTableWidgetItem *m_LastItem; }; } #endif diff --git a/src/dialogs/texdocumentationdialog.cpp b/src/dialogs/texdocumentationdialog.cpp index 864f6d5f..9d598c0f 100644 --- a/src/dialogs/texdocumentationdialog.cpp +++ b/src/dialogs/texdocumentationdialog.cpp @@ -1,653 +1,653 @@ /*************************************************************************** Copyright (C) 2005-2007 by Holger Danielsson (holger.danielsson@t-online.de) 2014 by Michel Ludwig (michel.ludwig@kdemail.net) ***************************************************************************/ /*************************************************************************** * * * 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. * * * ***************************************************************************/ #include "dialogs/texdocumentationdialog.h" #include "kileconstants.h" #include "kiledebug.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include namespace KileDialog { TexDocDialog::TexDocDialog(QWidget *parent) - : QDialog(parent) - , m_buttonBox(new QDialogButtonBox(QDialogButtonBox::RestoreDefaults|QDialogButtonBox::Close)) - , m_tempfile(Q_NULLPTR) - , m_proc(Q_NULLPTR) + : QDialog(parent) + , m_buttonBox(new QDialogButtonBox(QDialogButtonBox::RestoreDefaults|QDialogButtonBox::Close)) + , m_tempfile(Q_NULLPTR) + , m_proc(Q_NULLPTR) { - setWindowTitle(i18n("Documentation Browser")); - setModal(true); - QVBoxLayout *mainLayout = new QVBoxLayout; - setLayout(mainLayout); - - // listview - m_texdocs = new QTreeWidget(this); - mainLayout->addWidget(m_texdocs); - m_texdocs->setRootIsDecorated(true); - m_texdocs->setHeaderLabel(i18n("Table of Contents")); - - // groupbox - QGroupBox *groupbox = new QGroupBox(i18n("Search"), this); - mainLayout->addWidget(groupbox); - QHBoxLayout *groupboxLayout = new QHBoxLayout(); - groupboxLayout->setAlignment(Qt::AlignTop); - groupbox->setLayout(groupboxLayout); - - m_leKeywords = new QLineEdit(groupbox); - m_leKeywords->setPlaceholderText("Keyword"); - m_leKeywords->setClearButtonEnabled(true); - m_pbSearch = new QPushButton(i18n("&Search"), groupbox); - - groupboxLayout->addWidget(m_leKeywords); - groupboxLayout->addWidget(m_pbSearch); - - m_texdocs->setWhatsThis(i18n("A list of available documents, which are listed in 'texdoctk.dat', that come with TexLive/teTeX. Double clicking with the mouse or pressing the space key will open a viewer to show this file.")); - m_leKeywords->setWhatsThis(i18n("You can choose a keyword to show only document files that are related to this keyword.")); - m_pbSearch->setWhatsThis(i18n("Start the search for the chosen keyword.")); - m_pbSearch->setEnabled(false); - m_buttonBox->button(QDialogButtonBox::RestoreDefaults)->setWhatsThis(i18n("Reset list to all available documentation files.")); - m_buttonBox->button(QDialogButtonBox::RestoreDefaults)->setText(i18n("Cancel &Search")); - m_buttonBox->button(QDialogButtonBox::RestoreDefaults)->setEnabled(false); - connect(m_buttonBox->button(QDialogButtonBox::RestoreDefaults), &QPushButton::clicked, - this, &TexDocDialog::slotResetSearch); - - // catch some Return/Enter events - m_texdocs->installEventFilter(this); - m_leKeywords->installEventFilter(this); - - connect(m_texdocs, &QTreeWidget::itemDoubleClicked, this, &TexDocDialog::slotListViewDoubleClicked); - connect(m_pbSearch, &QPushButton::clicked, this, &TexDocDialog::slotSearchClicked); - connect(m_leKeywords, &QLineEdit::textChanged, this, &TexDocDialog::slotTextChanged); - - m_texmfPath.clear(); - m_texmfdocPath.clear(); - m_texdoctkPath.clear(); - - connect(this, &TexDocDialog::processFinished, this, &TexDocDialog::slotInitToc); - executeScript( - "kpsewhich --progname=texdoctk --format='other text files' texdoctk.dat && " - "kpsewhich --expand-path='$TEXMF/doc' && " - "kpsewhich --expand-path='$TEXMF'" - ); - - mainLayout->addWidget(m_texdocs); - mainLayout->addWidget(groupbox); - mainLayout->addWidget(m_buttonBox); - - connect(m_buttonBox, &QDialogButtonBox::accepted, this, &QDialog::accept); - connect(m_buttonBox, &QDialogButtonBox::rejected, this, &QDialog::reject); - - resize(sizeHint() + m_texdocs->sizeHint()); + setWindowTitle(i18n("Documentation Browser")); + setModal(true); + QVBoxLayout *mainLayout = new QVBoxLayout; + setLayout(mainLayout); + + // listview + m_texdocs = new QTreeWidget(this); + mainLayout->addWidget(m_texdocs); + m_texdocs->setRootIsDecorated(true); + m_texdocs->setHeaderLabel(i18n("Table of Contents")); + + // groupbox + QGroupBox *groupbox = new QGroupBox(i18n("Search"), this); + mainLayout->addWidget(groupbox); + QHBoxLayout *groupboxLayout = new QHBoxLayout(); + groupboxLayout->setAlignment(Qt::AlignTop); + groupbox->setLayout(groupboxLayout); + + m_leKeywords = new QLineEdit(groupbox); + m_leKeywords->setPlaceholderText("Keyword"); + m_leKeywords->setClearButtonEnabled(true); + m_pbSearch = new QPushButton(i18n("&Search"), groupbox); + + groupboxLayout->addWidget(m_leKeywords); + groupboxLayout->addWidget(m_pbSearch); + + m_texdocs->setWhatsThis(i18n("A list of available documents, which are listed in 'texdoctk.dat', that come with TexLive/teTeX. Double clicking with the mouse or pressing the space key will open a viewer to show this file.")); + m_leKeywords->setWhatsThis(i18n("You can choose a keyword to show only document files that are related to this keyword.")); + m_pbSearch->setWhatsThis(i18n("Start the search for the chosen keyword.")); + m_pbSearch->setEnabled(false); + m_buttonBox->button(QDialogButtonBox::RestoreDefaults)->setWhatsThis(i18n("Reset list to all available documentation files.")); + m_buttonBox->button(QDialogButtonBox::RestoreDefaults)->setText(i18n("Cancel &Search")); + m_buttonBox->button(QDialogButtonBox::RestoreDefaults)->setEnabled(false); + connect(m_buttonBox->button(QDialogButtonBox::RestoreDefaults), &QPushButton::clicked, + this, &TexDocDialog::slotResetSearch); + + // catch some Return/Enter events + m_texdocs->installEventFilter(this); + m_leKeywords->installEventFilter(this); + + connect(m_texdocs, &QTreeWidget::itemDoubleClicked, this, &TexDocDialog::slotListViewDoubleClicked); + connect(m_pbSearch, &QPushButton::clicked, this, &TexDocDialog::slotSearchClicked); + connect(m_leKeywords, &QLineEdit::textChanged, this, &TexDocDialog::slotTextChanged); + + m_texmfPath.clear(); + m_texmfdocPath.clear(); + m_texdoctkPath.clear(); + + connect(this, &TexDocDialog::processFinished, this, &TexDocDialog::slotInitToc); + executeScript( + "kpsewhich --progname=texdoctk --format='other text files' texdoctk.dat && " + "kpsewhich --expand-path='$TEXMF/doc' && " + "kpsewhich --expand-path='$TEXMF'" + ); + + mainLayout->addWidget(m_texdocs); + mainLayout->addWidget(groupbox); + mainLayout->addWidget(m_buttonBox); + + connect(m_buttonBox, &QDialogButtonBox::accepted, this, &QDialog::accept); + connect(m_buttonBox, &QDialogButtonBox::rejected, this, &QDialog::reject); + + resize(sizeHint() + m_texdocs->sizeHint()); } TexDocDialog::~TexDocDialog() { - delete m_proc; - delete m_tempfile; + delete m_proc; + delete m_tempfile; } ////////////////////// TOC ////////////////////// void TexDocDialog::readToc() { - // open to read - QFile fin(m_texdoctkPath); - if (!fin.exists() || !fin.open(QIODevice::ReadOnly)) { - KMessageBox::error(this, i18n("Could not read 'texdoctk.dat'.")); - return; - } - - // use a textstream to read all data - QString textline; - QTextStream data(&fin); - while (!data.atEnd()) { - textline = data.readLine(); - if (!(textline.isEmpty() || textline[0] == '#')) { - // save the whole entry - m_tocList.append(textline); - - // list entries 0,1,basename(2),3 are needed for keyword search - // (key,title,filepath,keywords) - QStringList list = textline.split(';', QString::KeepEmptyParts); - - // get basename of help file - QString basename; - if (list.count() > 2) { - QFileInfo fi(list[2]); - basename = fi.baseName().toLower(); - } - else { - if (list.count() < 2) { - continue; - } - } - QString entry = list[0] + ';' + list[1]; - if (!basename.isEmpty()) { - entry += ';' + basename; - } - if (list.count() > 3) { - entry += ';' + list[3]; - } - m_tocSearchList.append(entry); - } - } + // open to read + QFile fin(m_texdoctkPath); + if (!fin.exists() || !fin.open(QIODevice::ReadOnly)) { + KMessageBox::error(this, i18n("Could not read 'texdoctk.dat'.")); + return; + } + + // use a textstream to read all data + QString textline; + QTextStream data(&fin); + while (!data.atEnd()) { + textline = data.readLine(); + if (!(textline.isEmpty() || textline[0] == '#')) { + // save the whole entry + m_tocList.append(textline); + + // list entries 0,1,basename(2),3 are needed for keyword search + // (key,title,filepath,keywords) + QStringList list = textline.split(';', QString::KeepEmptyParts); + + // get basename of help file + QString basename; + if (list.count() > 2) { + QFileInfo fi(list[2]); + basename = fi.baseName().toLower(); + } + else { + if (list.count() < 2) { + continue; + } + } + QString entry = list[0] + ';' + list[1]; + if (!basename.isEmpty()) { + entry += ';' + basename; + } + if (list.count() > 3) { + entry += ';' + list[3]; + } + m_tocSearchList.append(entry); + } + } } void TexDocDialog::showToc(const QString &caption, const QStringList &doclist, bool toc) { - QString section, textline; - QStringList keylist; - QTreeWidgetItem *itemsection = Q_NULLPTR; - - setUpdatesEnabled(false); - m_texdocs->setHeaderLabel(caption); - - for (int i = 0; i < doclist.count(); ++i) { - if (doclist[i][0] == '@') { - section = doclist[i]; - itemsection = new QTreeWidgetItem(m_texdocs, QStringList(section.remove(0, 1))); - } - else { - keylist = doclist[i].split(';', QString::KeepEmptyParts); - if (keylist.size() < 4) { - continue; - } - if (itemsection) { - QTreeWidgetItem *item = new QTreeWidgetItem(itemsection, QStringList() << keylist[1] << keylist[0]); - item->setIcon(0, QIcon::fromTheme(getIconName(keylist[2]))); - - // save filename in dictionary - m_dictDocuments[keylist[0]] = keylist[2]; - - // search for special keywords - QRegExp reg("^\\s*(-\\d-)"); - if (keylist[3].indexOf(reg, 0) == 0) { - m_dictStyleCodes[keylist[0]] = reg.cap(1); - } - } - } - } - setUpdatesEnabled(true); - - if (toc) { - m_pbSearch->setEnabled(false); - } - m_buttonBox->button(QDialogButtonBox::RestoreDefaults)->setEnabled(!toc); - m_texdocs->setFocus(); - - if (m_texdocs->topLevelItemCount() == 1) { - m_texdocs->expandAll(); - } + QString section, textline; + QStringList keylist; + QTreeWidgetItem *itemsection = Q_NULLPTR; + + setUpdatesEnabled(false); + m_texdocs->setHeaderLabel(caption); + + for (int i = 0; i < doclist.count(); ++i) { + if (doclist[i][0] == '@') { + section = doclist[i]; + itemsection = new QTreeWidgetItem(m_texdocs, QStringList(section.remove(0, 1))); + } + else { + keylist = doclist[i].split(';', QString::KeepEmptyParts); + if (keylist.size() < 4) { + continue; + } + if (itemsection) { + QTreeWidgetItem *item = new QTreeWidgetItem(itemsection, QStringList() << keylist[1] << keylist[0]); + item->setIcon(0, QIcon::fromTheme(getIconName(keylist[2]))); + + // save filename in dictionary + m_dictDocuments[keylist[0]] = keylist[2]; + + // search for special keywords + QRegExp reg("^\\s*(-\\d-)"); + if (keylist[3].indexOf(reg, 0) == 0) { + m_dictStyleCodes[keylist[0]] = reg.cap(1); + } + } + } + } + setUpdatesEnabled(true); + + if (toc) { + m_pbSearch->setEnabled(false); + } + m_buttonBox->button(QDialogButtonBox::RestoreDefaults)->setEnabled(!toc); + m_texdocs->setFocus(); + + if (m_texdocs->topLevelItemCount() == 1) { + m_texdocs->expandAll(); + } } bool TexDocDialog::eventFilter(QObject *o, QEvent *e) { - // catch KeyPress events - if (e->type() == QEvent::KeyPress) { - QKeyEvent *kev = (QKeyEvent*) e; - - // ListView: - // - space: enable start of viewer - // - return: ignore - if(o == m_texdocs) { - if(kev->key() == Qt::Key_Space) { - slotListViewDoubleClicked(m_texdocs->currentItem()); - return true; - } - if(kev->key() == Qt::Key_Return || kev->key() == Qt::Key_Enter) { - return true; - } - } - - // LineEdit - // - return: start search, if button is enabled - if (o == m_leKeywords) { - if(kev->key() == Qt::Key_Return || kev->key() == Qt::Key_Enter) { - callSearch(); - return true; - } - } - } - - return false; + // catch KeyPress events + if (e->type() == QEvent::KeyPress) { + QKeyEvent *kev = (QKeyEvent*) e; + + // ListView: + // - space: enable start of viewer + // - return: ignore + if(o == m_texdocs) { + if(kev->key() == Qt::Key_Space) { + slotListViewDoubleClicked(m_texdocs->currentItem()); + return true; + } + if(kev->key() == Qt::Key_Return || kev->key() == Qt::Key_Enter) { + return true; + } + } + + // LineEdit + // - return: start search, if button is enabled + if (o == m_leKeywords) { + if(kev->key() == Qt::Key_Return || kev->key() == Qt::Key_Enter) { + callSearch(); + return true; + } + } + } + + return false; } ////////////////////// prepare document file ////////////////////// QString TexDocDialog::searchFile(const QString &docfilename, const QString &listofpaths, const QString &subdir) { - QStringList pathlist = listofpaths.split(PATH_SEPARATOR); - QStringList extlist = QString(",.gz,.bz2").split(',', QString::KeepEmptyParts); - - QString filename; - for (QStringList::Iterator itp = pathlist.begin(); itp != pathlist.end(); ++itp) { - for (QStringList::Iterator ite = extlist.begin(); ite != extlist.end(); ++ite) { - filename = (subdir.isEmpty()) ? (*itp) + '/' + docfilename + (*ite) - : (*itp) + '/' + subdir + '/' + docfilename + (*ite); - KILE_DEBUG_MAIN << "search file: " << filename << endl; - if(QFile::exists(filename)) { - return filename; - } - } - } - - return QString(); + QStringList pathlist = listofpaths.split(PATH_SEPARATOR); + QStringList extlist = QString(",.gz,.bz2").split(',', QString::KeepEmptyParts); + + QString filename; + for (QStringList::Iterator itp = pathlist.begin(); itp != pathlist.end(); ++itp) { + for (QStringList::Iterator ite = extlist.begin(); ite != extlist.end(); ++ite) { + filename = (subdir.isEmpty()) ? (*itp) + '/' + docfilename + (*ite) + : (*itp) + '/' + subdir + '/' + docfilename + (*ite); + KILE_DEBUG_MAIN << "search file: " << filename << endl; + if(QFile::exists(filename)) { + return filename; + } + } + } + + return QString(); } void TexDocDialog::decompressFile(const QString &docfile, const QString &command) { - QString ext = QFileInfo(docfile).suffix().toLower(); - if(!(ext == "dvi" || ext == "pdf" || ext == "ps" || ext == "html")) { - ext = "txt"; - } - - if(m_tempfile) { - delete m_tempfile; - } - m_tempfile = new QTemporaryFile(QDir::tempPath() + QLatin1String("/kile_XXXXXX.") + ext); - m_tempfile->setAutoRemove(true); - - if (!m_tempfile->open()) { - KMessageBox::error(this, i18n("Could not create a temporary file.")); - m_filename.clear(); - return; - } - m_filename = m_tempfile->fileName(); // the unique file name of the temporary file should be kept - m_tempfile->close(); - - KILE_DEBUG_MAIN << "\tdecompress file: " << command + " > " + m_filename << endl; - connect(this, &TexDocDialog::processFinished, this, &TexDocDialog::slotShowFile); - executeScript(command + " > " + m_filename); + QString ext = QFileInfo(docfile).suffix().toLower(); + if(!(ext == "dvi" || ext == "pdf" || ext == "ps" || ext == "html")) { + ext = "txt"; + } + + if(m_tempfile) { + delete m_tempfile; + } + m_tempfile = new QTemporaryFile(QDir::tempPath() + QLatin1String("/kile_XXXXXX.") + ext); + m_tempfile->setAutoRemove(true); + + if (!m_tempfile->open()) { + KMessageBox::error(this, i18n("Could not create a temporary file.")); + m_filename.clear(); + return; + } + m_filename = m_tempfile->fileName(); // the unique file name of the temporary file should be kept + m_tempfile->close(); + + KILE_DEBUG_MAIN << "\tdecompress file: " << command + " > " + m_filename << endl; + connect(this, &TexDocDialog::processFinished, this, &TexDocDialog::slotShowFile); + executeScript(command + " > " + m_filename); } void TexDocDialog::showStyleFile(const QString &filename, const QString &stylecode) { - KILE_DEBUG_MAIN << "\tshow style file: " << filename << endl; - if (!QFile::exists(filename)) { - return; - } - - // open to read - QFile fin(filename); - if (!fin.exists() || !fin.open(QIODevice::ReadOnly)) { - KMessageBox::error(this, i18n("Could not read the style file.")); - return; - } - - if (m_tempfile) { - delete m_tempfile; - } - m_tempfile = new QTemporaryFile(); - m_tempfile->setAutoRemove(true); - - // use a textstream to write to the temporary file - if (!m_tempfile->open()) { - KMessageBox::error(this, i18n("Could not create a temporary file.")); - return ; - } - QTextStream stream(m_tempfile); - - // use another textstream to read from the style file - QTextStream sty(&fin); - - // there are four mode to read from the style file - QString textline; - if (stylecode == "-3-") { - // mode 3: read everything up to the first empty line - while (!sty.atEnd()) { - textline = sty.readLine().trimmed(); - if(textline.isEmpty()) { - break; - } - stream << textline << "\n"; - } - } - else { - if (stylecode == "-2-") { - // mode 2: read everything up to a line starting with at least 4 '%' characters - for (int i = 0; i < 9; ++i) { - stream << sty.readLine() << "\n"; - } - while (!sty.atEnd()) { - textline = sty.readLine(); - if (textline.indexOf("%%%%") == 0) - break; - stream << textline << "\n"; - } - } - else { - if(stylecode == "-1-") { - // mode 1: read all lines at the end behind \endinput - while (!sty.atEnd()) { - textline = sty.readLine().trimmed(); - if(textline.indexOf("\\endinput") == 0) - break; - } - while (!sty.atEnd()) { - stream << sty.readLine() << "\n"; - } - } - else { - // mode 0: read everything except empty lines and comments - while (!sty.atEnd()) { - textline = sty.readLine(); - if (!textline.isEmpty() && textline[0] != '%') { - stream << textline << "\n"; - } - } - } - } - } - // start the viewer - showFile(m_tempfile->fileName()); + KILE_DEBUG_MAIN << "\tshow style file: " << filename << endl; + if (!QFile::exists(filename)) { + return; + } + + // open to read + QFile fin(filename); + if (!fin.exists() || !fin.open(QIODevice::ReadOnly)) { + KMessageBox::error(this, i18n("Could not read the style file.")); + return; + } + + if (m_tempfile) { + delete m_tempfile; + } + m_tempfile = new QTemporaryFile(); + m_tempfile->setAutoRemove(true); + + // use a textstream to write to the temporary file + if (!m_tempfile->open()) { + KMessageBox::error(this, i18n("Could not create a temporary file.")); + return ; + } + QTextStream stream(m_tempfile); + + // use another textstream to read from the style file + QTextStream sty(&fin); + + // there are four mode to read from the style file + QString textline; + if (stylecode == "-3-") { + // mode 3: read everything up to the first empty line + while (!sty.atEnd()) { + textline = sty.readLine().trimmed(); + if(textline.isEmpty()) { + break; + } + stream << textline << "\n"; + } + } + else { + if (stylecode == "-2-") { + // mode 2: read everything up to a line starting with at least 4 '%' characters + for (int i = 0; i < 9; ++i) { + stream << sty.readLine() << "\n"; + } + while (!sty.atEnd()) { + textline = sty.readLine(); + if (textline.indexOf("%%%%") == 0) + break; + stream << textline << "\n"; + } + } + else { + if(stylecode == "-1-") { + // mode 1: read all lines at the end behind \endinput + while (!sty.atEnd()) { + textline = sty.readLine().trimmed(); + if(textline.indexOf("\\endinput") == 0) + break; + } + while (!sty.atEnd()) { + stream << sty.readLine() << "\n"; + } + } + else { + // mode 0: read everything except empty lines and comments + while (!sty.atEnd()) { + textline = sty.readLine(); + if (!textline.isEmpty() && textline[0] != '%') { + stream << textline << "\n"; + } + } + } + } + } + // start the viewer + showFile(m_tempfile->fileName()); } void TexDocDialog::showFile(const QString &filename) { - KILE_DEBUG_MAIN << "\tshow file: " << filename << endl; - if (QFile::exists(filename)) { - QUrl url; - url.setPath(filename); - - KService::List offers = KMimeTypeTrader::self()->query(getMimeType(filename), "Application"); - if(offers.isEmpty()) { - KMessageBox::error(this, i18n("No KDE service found for this file.")); - return; - } - QList lst; - lst.append(url); - KRun::runService(*(offers.first()), lst, this, true); - } + KILE_DEBUG_MAIN << "\tshow file: " << filename << endl; + if (QFile::exists(filename)) { + QUrl url; + url.setPath(filename); + + KService::List offers = KMimeTypeTrader::self()->query(getMimeType(filename), "Application"); + if(offers.isEmpty()) { + KMessageBox::error(this, i18n("No KDE service found for this file.")); + return; + } + QList lst; + lst.append(url); + KRun::runService(*(offers.first()), lst, this, true); + } } ////////////////////// Slots ////////////////////// void TexDocDialog::slotListViewDoubleClicked(QTreeWidgetItem *item) { - if (!item->parent()) { - return; - } - - QString package = item->text(1); - KILE_DEBUG_MAIN << "\tselect child: " << item->text(0) << endl - << "\tis package: " << package << endl; - if (!m_dictDocuments.contains(package)) { - return; - } - - QString texdocfile = m_dictDocuments[package]; - KILE_DEBUG_MAIN << "\tis texdocfile: " << texdocfile << endl; - - // search for the file in the documentation directories - QString filename = searchFile(texdocfile, m_texmfdocPath); - if (filename.isEmpty()) { - // not found: search it elsewhere - filename = searchFile(texdocfile, m_texmfPath, "tex"); - if (filename.isEmpty()) { - KMessageBox::error(this, i18n("Could not find '%1'", filename)); - return; - } - } - KILE_DEBUG_MAIN << "\tfound file: " << filename << endl; - - QString ext = QFileInfo(filename).suffix().toLower(); - m_filename.clear(); - if (ext == "gz") { - decompressFile(m_dictDocuments[package], "gzip -cd " + filename); - } - else { - if (ext == "bz2") { - decompressFile(m_dictDocuments[package], "bzip2 -cd " + filename); - } - else { - if (ext == "sty" && m_dictStyleCodes.contains(package)) { - showStyleFile(filename, m_dictStyleCodes[package]); - } - else { - showFile(filename); - } - } - } + if (!item->parent()) { + return; + } + + QString package = item->text(1); + KILE_DEBUG_MAIN << "\tselect child: " << item->text(0) << endl + << "\tis package: " << package << endl; + if (!m_dictDocuments.contains(package)) { + return; + } + + QString texdocfile = m_dictDocuments[package]; + KILE_DEBUG_MAIN << "\tis texdocfile: " << texdocfile << endl; + + // search for the file in the documentation directories + QString filename = searchFile(texdocfile, m_texmfdocPath); + if (filename.isEmpty()) { + // not found: search it elsewhere + filename = searchFile(texdocfile, m_texmfPath, "tex"); + if (filename.isEmpty()) { + KMessageBox::error(this, i18n("Could not find '%1'", filename)); + return; + } + } + KILE_DEBUG_MAIN << "\tfound file: " << filename << endl; + + QString ext = QFileInfo(filename).suffix().toLower(); + m_filename.clear(); + if (ext == "gz") { + decompressFile(m_dictDocuments[package], "gzip -cd " + filename); + } + else { + if (ext == "bz2") { + decompressFile(m_dictDocuments[package], "bzip2 -cd " + filename); + } + else { + if (ext == "sty" && m_dictStyleCodes.contains(package)) { + showStyleFile(filename, m_dictStyleCodes[package]); + } + else { + showFile(filename); + } + } + } } void TexDocDialog::slotTextChanged(const QString &text) { - m_pbSearch->setEnabled(! text.trimmed().isEmpty()); + m_pbSearch->setEnabled(! text.trimmed().isEmpty()); } void TexDocDialog::slotSearchClicked() { - QString keyword = m_leKeywords->text().trimmed(); - if (keyword.isEmpty()) { - KMessageBox::error(this, i18n("No keyword given.")); - return; - } - - QString section; - bool writesection = true; - QStringList searchlist; - - for (int i = 0; i < m_tocList.count(); i++) { - if (m_tocList[i][0] == '@') { - section = m_tocList[i]; - writesection = true; - } - else { - if (i < m_tocSearchList.count() && m_tocSearchList[i].indexOf(keyword, 0, Qt::CaseInsensitive) > -1) { - if (writesection) { - searchlist.append(section); - } - searchlist.append(m_tocList[i]); - writesection = false; - } - } - } - - if (searchlist.count() > 0) { - m_texdocs->clear(); - showToc(i18n("Search results for keyword '%1'", keyword), searchlist, false); - } - else { - KMessageBox::error(this, i18n("No documents found for keyword '%1'.", keyword)); - } + QString keyword = m_leKeywords->text().trimmed(); + if (keyword.isEmpty()) { + KMessageBox::error(this, i18n("No keyword given.")); + return; + } + + QString section; + bool writesection = true; + QStringList searchlist; + + for (int i = 0; i < m_tocList.count(); i++) { + if (m_tocList[i][0] == '@') { + section = m_tocList[i]; + writesection = true; + } + else { + if (i < m_tocSearchList.count() && m_tocSearchList[i].indexOf(keyword, 0, Qt::CaseInsensitive) > -1) { + if (writesection) { + searchlist.append(section); + } + searchlist.append(m_tocList[i]); + writesection = false; + } + } + } + + if (searchlist.count() > 0) { + m_texdocs->clear(); + showToc(i18n("Search results for keyword '%1'", keyword), searchlist, false); + } + else { + KMessageBox::error(this, i18n("No documents found for keyword '%1'.", keyword)); + } } void TexDocDialog::slotResetSearch() { - m_leKeywords->setText(QString()); - m_texdocs->clear(); - showToc(i18n("Table of Contents"), m_tocList, true); + m_leKeywords->setText(QString()); + m_texdocs->clear(); + showToc(i18n("Table of Contents"), m_tocList, true); } void TexDocDialog::callSearch() { - if(m_pbSearch->isEnabled()) { - slotSearchClicked(); - } + if(m_pbSearch->isEnabled()) { + slotSearchClicked(); + } } ////////////////////// execute shell script ////////////////////// void TexDocDialog::executeScript(const QString &command) { - if (m_proc) { - delete m_proc; - } - - m_proc = new KProcess(); - m_proc->setShellCommand(command); - m_proc->setOutputChannelMode(KProcess::MergedChannels); - m_proc->setReadChannel(QProcess::StandardOutput); - m_output.clear(); - - connect(m_proc, &KProcess::readyReadStandardOutput, - this, &TexDocDialog::slotProcessOutput); - connect(m_proc, &KProcess::readyReadStandardError, - this, &TexDocDialog::slotProcessOutput); - connect(m_proc, static_cast(&QProcess::finished), - this, &TexDocDialog::slotProcessExited); - - KILE_DEBUG_MAIN << "=== TexDocDialog::runShellSkript() ====================" << endl; - KILE_DEBUG_MAIN << " execute: " << command << endl; - m_proc->start(); + if (m_proc) { + delete m_proc; + } + + m_proc = new KProcess(); + m_proc->setShellCommand(command); + m_proc->setOutputChannelMode(KProcess::MergedChannels); + m_proc->setReadChannel(QProcess::StandardOutput); + m_output.clear(); + + connect(m_proc, &KProcess::readyReadStandardOutput, + this, &TexDocDialog::slotProcessOutput); + connect(m_proc, &KProcess::readyReadStandardError, + this, &TexDocDialog::slotProcessOutput); + connect(m_proc, static_cast(&QProcess::finished), + this, &TexDocDialog::slotProcessExited); + + KILE_DEBUG_MAIN << "=== TexDocDialog::runShellSkript() ====================" << endl; + KILE_DEBUG_MAIN << " execute: " << command << endl; + m_proc->start(); } void TexDocDialog::slotProcessOutput() { - m_output += m_proc->readAll(); + m_output += m_proc->readAll(); } void TexDocDialog::slotProcessExited(int exitCode, QProcess::ExitStatus exitStatus) { - Q_UNUSED(exitCode); - - if (exitStatus == QProcess::NormalExit) { - //showFile(m_filename); - emit(processFinished()); - } - else { - KMessageBox::error(this, i18n("
") + i18n("Could not determine the search paths of TexLive/teTeX or file 'texdoctk.dat'.
Hence, this dialog is unable to provide any useful information.") + i18n("
"), i18n("TexDoc Dialog")); - } + Q_UNUSED(exitCode); + + if (exitStatus == QProcess::NormalExit) { + //showFile(m_filename); + emit(processFinished()); + } + else { + KMessageBox::error(this, i18n("
") + i18n("Could not determine the search paths of TexLive/teTeX or file 'texdoctk.dat'.
Hence, this dialog is unable to provide any useful information.") + i18n("
"), i18n("TexDoc Dialog")); + } } ////////////////////// process slots, when finished ////////////////////// void TexDocDialog::slotInitToc() { - disconnect(this, &TexDocDialog::processFinished, this, &TexDocDialog::slotInitToc); + disconnect(this, &TexDocDialog::processFinished, this, &TexDocDialog::slotInitToc); - QStringList results = m_output.split('\n', QString::KeepEmptyParts); - if (results.count() < 3) { - KMessageBox::error(this, i18n("Could not determine the search paths of TexLive or file 'texdoctk.dat'.
Hence, this dialog is unable to provide any useful information.")); - return; - } + QStringList results = m_output.split('\n', QString::KeepEmptyParts); + if (results.count() < 3) { + KMessageBox::error(this, i18n("Could not determine the search paths of TexLive or file 'texdoctk.dat'.
Hence, this dialog is unable to provide any useful information.")); + return; + } - m_texdoctkPath = results[0]; - m_texmfdocPath = results[1]; - m_texmfPath = results[2]; + m_texdoctkPath = results[0]; + m_texmfdocPath = results[1]; + m_texmfPath = results[2]; - KILE_DEBUG_MAIN << "\ttexdoctk path: " << m_texdoctkPath << endl; - KILE_DEBUG_MAIN << "\ttexmfdoc path: " << m_texmfdocPath << endl; - KILE_DEBUG_MAIN << "\ttexmf path: " << m_texmfPath << endl; + KILE_DEBUG_MAIN << "\ttexdoctk path: " << m_texdoctkPath << endl; + KILE_DEBUG_MAIN << "\ttexmfdoc path: " << m_texmfdocPath << endl; + KILE_DEBUG_MAIN << "\ttexmf path: " << m_texmfPath << endl; - if(m_texdoctkPath.indexOf('\n', -1) > -1) { - m_texdoctkPath.truncate(m_texdoctkPath.length() - 1); - } + if(m_texdoctkPath.indexOf('\n', -1) > -1) { + m_texdoctkPath.truncate(m_texdoctkPath.length() - 1); + } - // read data and initialize listview - readToc(); - slotResetSearch(); + // read data and initialize listview + readToc(); + slotResetSearch(); } void TexDocDialog::slotShowFile() { - disconnect(this, &TexDocDialog::processFinished, this, &TexDocDialog::slotShowFile); - showFile(m_filename); + disconnect(this, &TexDocDialog::processFinished, this, &TexDocDialog::slotShowFile); + showFile(m_filename); } ////////////////////// Icon/Mime ////////////////////// QString TexDocDialog::getMimeType(const QString &filename) { - QFileInfo fi(filename); - QString basename = fi.baseName().toLower(); - QString ext = fi.suffix().toLower(); - - QString mimetype; - if (ext == "txt" || ext == "faq" || ext == "sty" || basename == "readme" || basename == "00readme") { - mimetype = "text/plain"; - } - else { - QUrl mimeurl; - mimeurl.setPath(filename); - QMimeDatabase db; - QMimeType pMime = db.mimeTypeForUrl(mimeurl); - mimetype = pMime.name(); - } - - KILE_DEBUG_MAIN << "\tmime = " << mimetype << " " << endl; - return mimetype; + QFileInfo fi(filename); + QString basename = fi.baseName().toLower(); + QString ext = fi.suffix().toLower(); + + QString mimetype; + if (ext == "txt" || ext == "faq" || ext == "sty" || basename == "readme" || basename == "00readme") { + mimetype = "text/plain"; + } + else { + QUrl mimeurl; + mimeurl.setPath(filename); + QMimeDatabase db; + QMimeType pMime = db.mimeTypeForUrl(mimeurl); + mimetype = pMime.name(); + } + + KILE_DEBUG_MAIN << "\tmime = " << mimetype << " " << endl; + return mimetype; } QString TexDocDialog::getIconName(const QString &filename) { - QFileInfo fi(filename); - QString basename = fi.baseName().toLower(); - QString ext = fi.suffix().toLower(); - - QString icon; - if (ext == "application-x-bzdvi" ) { // FIXME exchange as soon as a real dvi icon is available - icon = ext; - } - else if( ext == "htm" || ext == "html" ){ - icon = "text-html"; - } - else if(ext == "pdf" ){ - icon = "application-pdf"; - } - else if( ext == "txt"){ - ext = "text-plain"; - } - else { - if(ext == "ps") { - icon = "application-postscript"; - } - else { - if(ext == "sty") { - icon = "text-x-tex"; - } - else { - if(ext == "faq" || basename == "readme" || basename == "00readme") { - icon = "text-x-readme"; - } - else { - icon = "text-plain"; - } - } - } - } - return icon; + QFileInfo fi(filename); + QString basename = fi.baseName().toLower(); + QString ext = fi.suffix().toLower(); + + QString icon; + if (ext == "application-x-bzdvi" ) { // FIXME exchange as soon as a real dvi icon is available + icon = ext; + } + else if( ext == "htm" || ext == "html" ) { + icon = "text-html"; + } + else if(ext == "pdf" ) { + icon = "application-pdf"; + } + else if( ext == "txt") { + ext = "text-plain"; + } + else { + if(ext == "ps") { + icon = "application-postscript"; + } + else { + if(ext == "sty") { + icon = "text-x-tex"; + } + else { + if(ext == "faq" || basename == "readme" || basename == "00readme") { + icon = "text-x-readme"; + } + else { + icon = "text-plain"; + } + } + } + } + return icon; } } diff --git a/src/dialogs/texdocumentationdialog.h b/src/dialogs/texdocumentationdialog.h index b95e2a0b..7a850e7b 100644 --- a/src/dialogs/texdocumentationdialog.h +++ b/src/dialogs/texdocumentationdialog.h @@ -1,101 +1,101 @@ /*************************************************************************** texdocdialog.h -------------- date : Feb 15 2007 version : 0.14 copyright : (C) 2005-2007 by Holger Danielsson email : holger.danielsson@versanet.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. * * * ***************************************************************************/ #ifndef TEXDOCUMENTATIONDIALOG_H #define TEXDOCUMENTATIONDIALOG_H #include #include #include class QTreeWidget; class QTreeWidgetItem; class KProcess; class QDialogButtonBox; class QLineEdit; class QPushButton; class QTemporaryFile; namespace KileDialog { class TexDocDialog : public QDialog { - Q_OBJECT + Q_OBJECT public: - TexDocDialog(QWidget *parent = 0); - ~TexDocDialog(); + TexDocDialog(QWidget *parent = 0); + ~TexDocDialog(); private: - QTreeWidget *m_texdocs; - QLineEdit *m_leKeywords; - QPushButton *m_pbSearch; - QDialogButtonBox *m_buttonBox; + QTreeWidget *m_texdocs; + QLineEdit *m_leKeywords; + QPushButton *m_pbSearch; + QDialogButtonBox *m_buttonBox; - QString m_texmfPath, m_texmfdocPath, m_texdoctkPath; + QString m_texmfPath, m_texmfdocPath, m_texdoctkPath; - QStringList m_tocList, m_tocSearchList; - QMap m_dictDocuments; - QMap m_dictStyleCodes; + QStringList m_tocList, m_tocSearchList; + QMap m_dictDocuments; + QMap m_dictStyleCodes; - void readToc(); - void showToc(const QString &caption, const QStringList &doclist, bool toc = true); + void readToc(); + void showToc(const QString &caption, const QStringList &doclist, bool toc = true); - QString m_filename; - QString m_output; + QString m_filename; + QString m_output; - QTemporaryFile *m_tempfile; - KProcess *m_proc; + QTemporaryFile *m_tempfile; + KProcess *m_proc; - void callSearch(); - void executeScript(const QString &command); - void showFile(const QString &filename); + void callSearch(); + void executeScript(const QString &command); + void showFile(const QString &filename); - QString searchFile(const QString &docfilename, const QString &listofpathes, - const QString &subdir = QString()); - void decompressFile(const QString &docfile, const QString &command); - void showStyleFile(const QString &filename, const QString &stylecode); + QString searchFile(const QString &docfilename, const QString &listofpathes, + const QString &subdir = QString()); + void decompressFile(const QString &docfile, const QString &command); + void showStyleFile(const QString &filename, const QString &stylecode); - QString getMimeType(const QString &filename); - QString getIconName(const QString &filename); + QString getMimeType(const QString &filename); + QString getIconName(const QString &filename); protected: - bool eventFilter(QObject *o, QEvent *e); + bool eventFilter(QObject *o, QEvent *e); Q_SIGNALS: - void processFinished(); + void processFinished(); private Q_SLOTS: - void slotListViewDoubleClicked(QTreeWidgetItem *item); - void slotTextChanged(const QString &text); - void slotSearchClicked(); - void slotResetSearch(); + void slotListViewDoubleClicked(QTreeWidgetItem *item); + void slotTextChanged(const QString &text); + void slotSearchClicked(); + void slotResetSearch(); - void slotProcessOutput(); - void slotProcessExited(int, QProcess::ExitStatus); + void slotProcessOutput(); + void slotProcessExited(int, QProcess::ExitStatus); - void slotInitToc(); - void slotShowFile(); + void slotInitToc(); + void slotShowFile(); }; } #endif diff --git a/src/dialogs/userhelpdialog.cpp b/src/dialogs/userhelpdialog.cpp index f98a9b33..1cdb2bac 100644 --- a/src/dialogs/userhelpdialog.cpp +++ b/src/dialogs/userhelpdialog.cpp @@ -1,457 +1,457 @@ /***************************************************************************************** userhelpdialog.cpp ---------------------------------------------------------------------------- date : Jul 22 2005 version : 0.20 copyright : (C) 2005 by Holger Danielsson (holger.danielsson@t-online.de) 2008 by Michel Ludwig (michel.ludwig@kdemail.net) *****************************************************************************************/ /*************************************************************************** * * * 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. * * * ***************************************************************************/ #include "userhelpdialog.h" #include "kiledebug.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include namespace KileDialog { //////////////////// UserHelpDialog //////////////////// //BEGIN UserHelpDialog UserHelpDialog::UserHelpDialog(QWidget *parent, const char *name) - : QDialog(parent) + : QDialog(parent) { - KILE_DEBUG_MAIN << "==UserHelpDialog::UserHelpDialog()==================="; - - setObjectName(name); - setWindowTitle(i18n("Configure User Help")); - setModal(true); - - QVBoxLayout *mainLayout = new QVBoxLayout; - setLayout(mainLayout); - - QGroupBox* group = new QGroupBox(i18n("User Help"), this); - QGridLayout *grid = new QGridLayout(); - group->setLayout(grid); - mainLayout->addWidget(group); - - // listbox - QLabel *label1 = new QLabel(i18n("&Menu item:"), group); - grid->addWidget(label1, 0, 0); - m_menulistbox = new QListWidget(group); - m_menulistbox->setSelectionMode(QAbstractItemView::SingleSelection); - grid->addWidget(m_menulistbox, 1, 0); - label1->setBuddy(m_menulistbox); - - // action widget - QWidget *actionwidget = new QWidget(group); - QVBoxLayout *actions = new QVBoxLayout(actionwidget); - actions->setMargin(0); - - m_add = new QPushButton(i18n("&Add..."), actionwidget); - m_remove = new QPushButton(i18n("&Remove"), actionwidget); - m_addsep = new QPushButton(i18n("&Separator"), actionwidget); - m_up = new QPushButton(i18n("Move &Up"), actionwidget); - m_down = new QPushButton(i18n("Move &Down"), actionwidget); - - int wmax = m_add->sizeHint().width(); - int w = m_remove->sizeHint().width(); - if(w > wmax) { - wmax = w; - } - w = m_addsep->sizeHint().width(); - if(w > wmax) { - wmax = w; - } - w = m_up->sizeHint().width(); - if(w > wmax) { - wmax = w; - } - w = m_down->sizeHint().width(); - if(w > wmax) { - wmax = w; - } - - m_add->setFixedWidth(wmax); - m_remove->setFixedWidth(wmax); - m_addsep->setFixedWidth(wmax); - m_up->setFixedWidth(wmax); - m_down->setFixedWidth(wmax); - - actions->addWidget(m_add); - actions->addWidget(m_remove); - actions->addSpacing(20); - actions->addWidget(m_addsep); - actions->addSpacing(20); - actions->addWidget(m_up); - actions->addWidget(m_down); - actions->addStretch(1); - - // insert action widget - grid->addWidget(actionwidget, 1, 1, Qt::AlignTop); - - // file - grid->addWidget(new QLabel(i18n("File:"), group), 2, 0); - m_fileedit = new QLineEdit(group); - m_fileedit->setReadOnly(true); - grid->addWidget(m_fileedit, 3, 0, 1, 2); - - // fill vbox - mainLayout->addWidget(group); - - connect(m_menulistbox, &QListWidget::itemSelectionChanged, this, &UserHelpDialog::slotChange); - connect(m_add, &QPushButton::clicked, this, &UserHelpDialog::slotAdd); - connect(m_remove, &QPushButton::clicked, this, &UserHelpDialog::slotRemove); - connect(m_addsep, &QPushButton::clicked, this, &UserHelpDialog::slotAddSep); - connect(m_up, &QPushButton::clicked, this, &UserHelpDialog::slotUp); - connect(m_down, &QPushButton::clicked, this, &UserHelpDialog::slotDown); - - // dialog buttons - QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok|QDialogButtonBox::Cancel); - QPushButton *okButton = buttonBox->button(QDialogButtonBox::Ok); - okButton->setDefault(true); - okButton->setShortcut(Qt::CTRL | Qt::Key_Return); - connect(buttonBox, &QDialogButtonBox::accepted, this, &QDialog::accept); - connect(buttonBox, &QDialogButtonBox::rejected, this, &QDialog::reject); - mainLayout->addWidget(buttonBox); - - resize(400, sizeHint().height()); - updateButton(); + KILE_DEBUG_MAIN << "==UserHelpDialog::UserHelpDialog()==================="; + + setObjectName(name); + setWindowTitle(i18n("Configure User Help")); + setModal(true); + + QVBoxLayout *mainLayout = new QVBoxLayout; + setLayout(mainLayout); + + QGroupBox* group = new QGroupBox(i18n("User Help"), this); + QGridLayout *grid = new QGridLayout(); + group->setLayout(grid); + mainLayout->addWidget(group); + + // listbox + QLabel *label1 = new QLabel(i18n("&Menu item:"), group); + grid->addWidget(label1, 0, 0); + m_menulistbox = new QListWidget(group); + m_menulistbox->setSelectionMode(QAbstractItemView::SingleSelection); + grid->addWidget(m_menulistbox, 1, 0); + label1->setBuddy(m_menulistbox); + + // action widget + QWidget *actionwidget = new QWidget(group); + QVBoxLayout *actions = new QVBoxLayout(actionwidget); + actions->setMargin(0); + + m_add = new QPushButton(i18n("&Add..."), actionwidget); + m_remove = new QPushButton(i18n("&Remove"), actionwidget); + m_addsep = new QPushButton(i18n("&Separator"), actionwidget); + m_up = new QPushButton(i18n("Move &Up"), actionwidget); + m_down = new QPushButton(i18n("Move &Down"), actionwidget); + + int wmax = m_add->sizeHint().width(); + int w = m_remove->sizeHint().width(); + if(w > wmax) { + wmax = w; + } + w = m_addsep->sizeHint().width(); + if(w > wmax) { + wmax = w; + } + w = m_up->sizeHint().width(); + if(w > wmax) { + wmax = w; + } + w = m_down->sizeHint().width(); + if(w > wmax) { + wmax = w; + } + + m_add->setFixedWidth(wmax); + m_remove->setFixedWidth(wmax); + m_addsep->setFixedWidth(wmax); + m_up->setFixedWidth(wmax); + m_down->setFixedWidth(wmax); + + actions->addWidget(m_add); + actions->addWidget(m_remove); + actions->addSpacing(20); + actions->addWidget(m_addsep); + actions->addSpacing(20); + actions->addWidget(m_up); + actions->addWidget(m_down); + actions->addStretch(1); + + // insert action widget + grid->addWidget(actionwidget, 1, 1, Qt::AlignTop); + + // file + grid->addWidget(new QLabel(i18n("File:"), group), 2, 0); + m_fileedit = new QLineEdit(group); + m_fileedit->setReadOnly(true); + grid->addWidget(m_fileedit, 3, 0, 1, 2); + + // fill vbox + mainLayout->addWidget(group); + + connect(m_menulistbox, &QListWidget::itemSelectionChanged, this, &UserHelpDialog::slotChange); + connect(m_add, &QPushButton::clicked, this, &UserHelpDialog::slotAdd); + connect(m_remove, &QPushButton::clicked, this, &UserHelpDialog::slotRemove); + connect(m_addsep, &QPushButton::clicked, this, &UserHelpDialog::slotAddSep); + connect(m_up, &QPushButton::clicked, this, &UserHelpDialog::slotUp); + connect(m_down, &QPushButton::clicked, this, &UserHelpDialog::slotDown); + + // dialog buttons + QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok|QDialogButtonBox::Cancel); + QPushButton *okButton = buttonBox->button(QDialogButtonBox::Ok); + okButton->setDefault(true); + okButton->setShortcut(Qt::CTRL | Qt::Key_Return); + connect(buttonBox, &QDialogButtonBox::accepted, this, &QDialog::accept); + connect(buttonBox, &QDialogButtonBox::rejected, this, &QDialog::reject); + mainLayout->addWidget(buttonBox); + + resize(400, sizeHint().height()); + updateButton(); } void UserHelpDialog::setParameter(const QStringList &menuentries, const QList &helpfiles) { - for (int i = 0; i < menuentries.count(); ++i) { - m_menulistbox->addItem(menuentries[i]); - - if(m_menulistbox->item(i)->text() != "-") { - m_filelist << helpfiles[i]; - } - else { - m_filelist << QUrl(); - } - } - updateButton(); + for (int i = 0; i < menuentries.count(); ++i) { + m_menulistbox->addItem(menuentries[i]); + + if(m_menulistbox->item(i)->text() != "-") { + m_filelist << helpfiles[i]; + } + else { + m_filelist << QUrl(); + } + } + updateButton(); } void UserHelpDialog::getParameter(QStringList &userhelpmenulist, QList &userhelpfilelist) { - // clear result - userhelpmenulist.clear(); - userhelpfilelist.clear(); - bool separator = false; - - // now get all entries - for (int i = 0; i < m_menulistbox->count(); ++i) { - if(m_menulistbox->item(i)->text() != "-") { - userhelpmenulist << m_menulistbox->item(i)->text(); - userhelpfilelist << m_filelist[i]; - separator = false; - } - else { - if(!separator) { - userhelpmenulist << m_menulistbox->item(i)->text(); - userhelpfilelist << QUrl(); - separator = true; - } - } - } + // clear result + userhelpmenulist.clear(); + userhelpfilelist.clear(); + bool separator = false; + + // now get all entries + for (int i = 0; i < m_menulistbox->count(); ++i) { + if(m_menulistbox->item(i)->text() != "-") { + userhelpmenulist << m_menulistbox->item(i)->text(); + userhelpfilelist << m_filelist[i]; + separator = false; + } + else { + if(!separator) { + userhelpmenulist << m_menulistbox->item(i)->text(); + userhelpfilelist << QUrl(); + separator = true; + } + } + } } void UserHelpDialog::slotChange() { - int index = m_menulistbox->currentRow(); - if (index >= 0) { - m_fileedit->setText(m_filelist[index].url()); - } - else { - m_fileedit->clear(); - } - updateButton(); + int index = m_menulistbox->currentRow(); + if (index >= 0) { + m_fileedit->setText(m_filelist[index].url()); + } + else { + m_fileedit->clear(); + } + updateButton(); } void UserHelpDialog::slotAdd() { - KileDialog::UserHelpAddDialog *dialog = new KileDialog::UserHelpAddDialog(m_menulistbox, this); - if (dialog->exec()) { - // with corresponding filename - QString helpfile = dialog->getHelpfile(); - - if (helpfile.isEmpty() - || m_menulistbox->findItems(helpfile, Qt::MatchExactly).count() > 0 - ) { - return; - } - - m_filelist.append(QUrl::fromLocalFile(helpfile)); - m_fileedit->setText(helpfile); - - // insert into listbox - m_menulistbox->addItem(dialog->getMenuitem()); - m_menulistbox->setCurrentRow(m_menulistbox->count() - 1); - - updateButton(); - } + KileDialog::UserHelpAddDialog *dialog = new KileDialog::UserHelpAddDialog(m_menulistbox, this); + if (dialog->exec()) { + // with corresponding filename + QString helpfile = dialog->getHelpfile(); + + if (helpfile.isEmpty() + || m_menulistbox->findItems(helpfile, Qt::MatchExactly).count() > 0 + ) { + return; + } + + m_filelist.append(QUrl::fromLocalFile(helpfile)); + m_fileedit->setText(helpfile); + + // insert into listbox + m_menulistbox->addItem(dialog->getMenuitem()); + m_menulistbox->setCurrentRow(m_menulistbox->count() - 1); + + updateButton(); + } } void UserHelpDialog::slotRemove() { - // get current index - int index = m_menulistbox->currentRow(); - if(index >= 0) { - // remove item - m_menulistbox->takeItem(index); - m_filelist.removeAt(index); - - // select a new index: first we try to take the old index. When - // this index is too big now, index is decremented. - // If the list is empty now, index is set to -1. - int entries = m_menulistbox->count(); - if (entries > 0) { - if (index >= entries) { - index--; - } - m_menulistbox->setCurrentRow(index); - } - else { - m_menulistbox->setCurrentItem(0); - } - } - - updateButton(); + // get current index + int index = m_menulistbox->currentRow(); + if(index >= 0) { + // remove item + m_menulistbox->takeItem(index); + m_filelist.removeAt(index); + + // select a new index: first we try to take the old index. When + // this index is too big now, index is decremented. + // If the list is empty now, index is set to -1. + int entries = m_menulistbox->count(); + if (entries > 0) { + if (index >= entries) { + index--; + } + m_menulistbox->setCurrentRow(index); + } + else { + m_menulistbox->setCurrentItem(0); + } + } + + updateButton(); } void UserHelpDialog::slotAddSep() { - // get current index - int index = m_menulistbox->currentRow(); - if (index == -1) { - return; - } + // get current index + int index = m_menulistbox->currentRow(); + if (index == -1) { + return; + } - // insert separator - m_menulistbox->insertItem(index, "-"); - m_filelist.insert(index, QUrl()); + // insert separator + m_menulistbox->insertItem(index, "-"); + m_filelist.insert(index, QUrl()); - updateButton(); + updateButton(); } void UserHelpDialog::slotUp() { - // get current index - int index = m_menulistbox->currentRow(); - if (index <= 0) { - return; - } + // get current index + int index = m_menulistbox->currentRow(); + if (index <= 0) { + return; + } - // insert current entry before current - m_menulistbox->insertItem(index - 1, m_menulistbox->currentItem()->text()); - m_filelist.insert(index - 1, m_filelist[index]); + // insert current entry before current + m_menulistbox->insertItem(index - 1, m_menulistbox->currentItem()->text()); + m_filelist.insert(index - 1, m_filelist[index]); - // then remove the old entry - m_menulistbox->takeItem(index + 1); - m_filelist.removeAt(index + 1); + // then remove the old entry + m_menulistbox->takeItem(index + 1); + m_filelist.removeAt(index + 1); - // select current entry - m_menulistbox->setCurrentRow(index - 1); + // select current entry + m_menulistbox->setCurrentRow(index - 1); - updateButton(); + updateButton(); } void UserHelpDialog::slotDown() { - int entries = m_menulistbox->count(); - - // get current index - int index = m_menulistbox->currentRow(); - if (index < 0 || index == entries - 1) { - return; - } - - // insert current entry after current - if (index < entries - 2) { - m_menulistbox->insertItem(index + 2, m_menulistbox->currentItem()->text()); // index + 2 - m_filelist.insert(index + 2, m_filelist[index]); - } - else { - m_menulistbox->addItem(m_menulistbox->currentItem()->text()); - m_filelist.append(m_filelist[index]); - } - - // then remove the old entry - m_menulistbox->takeItem(index); - m_filelist.removeAt(index); - - // select current entry - m_menulistbox->setCurrentRow(index + 1); - - updateButton(); + int entries = m_menulistbox->count(); + + // get current index + int index = m_menulistbox->currentRow(); + if (index < 0 || index == entries - 1) { + return; + } + + // insert current entry after current + if (index < entries - 2) { + m_menulistbox->insertItem(index + 2, m_menulistbox->currentItem()->text()); // index + 2 + m_filelist.insert(index + 2, m_filelist[index]); + } + else { + m_menulistbox->addItem(m_menulistbox->currentItem()->text()); + m_filelist.append(m_filelist[index]); + } + + // then remove the old entry + m_menulistbox->takeItem(index); + m_filelist.removeAt(index); + + // select current entry + m_menulistbox->setCurrentRow(index + 1); + + updateButton(); } void UserHelpDialog::updateButton() { - // default states - bool rem_state = false; - bool sep_state = false; - bool up_state = false; - bool down_state = false; - - // change button states, if there are entries - int index = m_menulistbox->currentRow(); - int entries = m_menulistbox->count(); - if (entries == 1) { - rem_state = true; - } - else { - if(entries >= 2) { - rem_state = true; - if(index == 0) { - down_state = true; // index = 0 - } - else { - if(index == entries - 1) { - sep_state = true; // index = entries-1 - up_state = true; - } - else { // 0 < index < entries-1 - sep_state = true; - up_state = true; - down_state = true; - } - } - } - } - // don't allow two continuous spearators - if(m_menulistbox->currentItem() && m_menulistbox->currentItem()->text() == "-") { - sep_state = false; - } - - // set button states - m_remove->setEnabled(rem_state); - m_addsep->setEnabled(sep_state); - m_up->setEnabled(up_state); - m_down->setEnabled(down_state); + // default states + bool rem_state = false; + bool sep_state = false; + bool up_state = false; + bool down_state = false; + + // change button states, if there are entries + int index = m_menulistbox->currentRow(); + int entries = m_menulistbox->count(); + if (entries == 1) { + rem_state = true; + } + else { + if(entries >= 2) { + rem_state = true; + if(index == 0) { + down_state = true; // index = 0 + } + else { + if(index == entries - 1) { + sep_state = true; // index = entries-1 + up_state = true; + } + else { // 0 < index < entries-1 + sep_state = true; + up_state = true; + down_state = true; + } + } + } + } + // don't allow two continuous spearators + if(m_menulistbox->currentItem() && m_menulistbox->currentItem()->text() == "-") { + sep_state = false; + } + + // set button states + m_remove->setEnabled(rem_state); + m_addsep->setEnabled(sep_state); + m_up->setEnabled(up_state); + m_down->setEnabled(down_state); } //END UserHelpDialog //////////////////// UserHelpAddDialog //////////////////// //BEGIN UserHelpAddDialog UserHelpAddDialog::UserHelpAddDialog(QListWidget *menulistbox, QWidget *parent) - : QDialog(parent) - , m_menulistbox(menulistbox) + : QDialog(parent) + , m_menulistbox(menulistbox) { - setWindowTitle(i18n("Add User Helpfile")); - setModal(true); - - KILE_DEBUG_MAIN << "==UserHelpAddDialog::UserHelpAddDialog()==================="; - - QVBoxLayout *mainLayout = new QVBoxLayout; - setLayout(mainLayout); - - // layout - QGroupBox *group = new QGroupBox(i18n("User Help"), this); - QGridLayout *grid = new QGridLayout(); - group->setLayout(grid); - mainLayout->addWidget(group); - - // menu entry - QLabel *label1 = new QLabel(i18n("&Menu entry:"), group); - grid->addWidget(label1, 0, 0); - m_leMenuEntry = new QLineEdit(group); - m_leMenuEntry->setClearButtonEnabled(true); - grid->addWidget(m_leMenuEntry, 0, 1, 1, 3); - label1->setBuddy(m_leMenuEntry); - - // help file - QLabel *label2 = new QLabel(i18n("&Help file:"), group); - grid->addWidget(label2, 1, 0); - m_leHelpFile = new QLineEdit(group); - m_leHelpFile->setReadOnly(false); - m_leHelpFile->setClearButtonEnabled(true); - grid->addWidget(m_leHelpFile, 1, 1); - m_pbChooseFile = new QPushButton("", group); - m_pbChooseFile->setObjectName("filechooser_button"); - m_pbChooseFile->setIcon(QIcon::fromTheme("document-open")); - int buttonSize = m_leHelpFile->sizeHint().height(); - m_pbChooseFile->setFixedSize(buttonSize, buttonSize); - m_pbChooseFile->setToolTip(i18n("Open file dialog")); - grid->addWidget(m_pbChooseFile, 1, 2); - label2->setBuddy(m_pbChooseFile); - - // fill mainLayout - mainLayout->addWidget(group); - mainLayout->addStretch(); - - m_leMenuEntry->setWhatsThis(i18n("The menu entry for this help file.")); - m_leHelpFile->setWhatsThis(i18n("The name of the local help file or a valid WEB url.")); - m_pbChooseFile->setWhatsThis(i18n("Start a file dialog to choose a local help file.")); - - connect(m_pbChooseFile, &QPushButton::clicked, this, &UserHelpAddDialog::onShowLocalFileSelection); - - QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok|QDialogButtonBox::Cancel); - QPushButton *okButton = buttonBox->button(QDialogButtonBox::Ok); - okButton->setDefault(true); - okButton->setShortcut(Qt::CTRL | Qt::Key_Return); - mainLayout->addWidget(buttonBox); - connect(buttonBox, &QDialogButtonBox::accepted, this, &QDialog::accept); - connect(buttonBox, &QDialogButtonBox::rejected, this, &QDialog::reject); - - setFocusProxy(m_leMenuEntry); - resize(500, sizeHint().height()); + setWindowTitle(i18n("Add User Helpfile")); + setModal(true); + + KILE_DEBUG_MAIN << "==UserHelpAddDialog::UserHelpAddDialog()==================="; + + QVBoxLayout *mainLayout = new QVBoxLayout; + setLayout(mainLayout); + + // layout + QGroupBox *group = new QGroupBox(i18n("User Help"), this); + QGridLayout *grid = new QGridLayout(); + group->setLayout(grid); + mainLayout->addWidget(group); + + // menu entry + QLabel *label1 = new QLabel(i18n("&Menu entry:"), group); + grid->addWidget(label1, 0, 0); + m_leMenuEntry = new QLineEdit(group); + m_leMenuEntry->setClearButtonEnabled(true); + grid->addWidget(m_leMenuEntry, 0, 1, 1, 3); + label1->setBuddy(m_leMenuEntry); + + // help file + QLabel *label2 = new QLabel(i18n("&Help file:"), group); + grid->addWidget(label2, 1, 0); + m_leHelpFile = new QLineEdit(group); + m_leHelpFile->setReadOnly(false); + m_leHelpFile->setClearButtonEnabled(true); + grid->addWidget(m_leHelpFile, 1, 1); + m_pbChooseFile = new QPushButton("", group); + m_pbChooseFile->setObjectName("filechooser_button"); + m_pbChooseFile->setIcon(QIcon::fromTheme("document-open")); + int buttonSize = m_leHelpFile->sizeHint().height(); + m_pbChooseFile->setFixedSize(buttonSize, buttonSize); + m_pbChooseFile->setToolTip(i18n("Open file dialog")); + grid->addWidget(m_pbChooseFile, 1, 2); + label2->setBuddy(m_pbChooseFile); + + // fill mainLayout + mainLayout->addWidget(group); + mainLayout->addStretch(); + + m_leMenuEntry->setWhatsThis(i18n("The menu entry for this help file.")); + m_leHelpFile->setWhatsThis(i18n("The name of the local help file or a valid WEB url.")); + m_pbChooseFile->setWhatsThis(i18n("Start a file dialog to choose a local help file.")); + + connect(m_pbChooseFile, &QPushButton::clicked, this, &UserHelpAddDialog::onShowLocalFileSelection); + + QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok|QDialogButtonBox::Cancel); + QPushButton *okButton = buttonBox->button(QDialogButtonBox::Ok); + okButton->setDefault(true); + okButton->setShortcut(Qt::CTRL | Qt::Key_Return); + mainLayout->addWidget(buttonBox); + connect(buttonBox, &QDialogButtonBox::accepted, this, &QDialog::accept); + connect(buttonBox, &QDialogButtonBox::rejected, this, &QDialog::reject); + + setFocusProxy(m_leMenuEntry); + resize(500, sizeHint().height()); } void UserHelpAddDialog::onShowLocalFileSelection() { - QString directory = QDir::currentPath(); - QString filter = i18n("Websites (HTML) (*.html *.htm);;Documents (PDF, PS, DVI, EPUB) (*.ps *.pdf *.dvi *.epub);;All Files (*)"); - - QString filename = QFileDialog::getOpenFileName(this, i18n("Select File"), directory, filter); - if (filename.isEmpty()) { - return; - } - - QFileInfo fi(filename); - if (!fi.exists()) { - KMessageBox::error(Q_NULLPTR, i18n("File '%1' does not exist.", filename)); - return; - } - m_leHelpFile->setText(filename); + QString directory = QDir::currentPath(); + QString filter = i18n("Websites (HTML) (*.html *.htm);;Documents (PDF, PS, DVI, EPUB) (*.ps *.pdf *.dvi *.epub);;All Files (*)"); + + QString filename = QFileDialog::getOpenFileName(this, i18n("Select File"), directory, filter); + if (filename.isEmpty()) { + return; + } + + QFileInfo fi(filename); + if (!fi.exists()) { + KMessageBox::error(Q_NULLPTR, i18n("File '%1' does not exist.", filename)); + return; + } + m_leHelpFile->setText(filename); } void UserHelpAddDialog::onAccepted() { - m_leMenuEntry->setText(m_leMenuEntry->text().trimmed()); - QString urlString = m_leHelpFile->text().trimmed(); - m_leHelpFile->setText(urlString); + m_leMenuEntry->setText(m_leMenuEntry->text().trimmed()); + QString urlString = m_leHelpFile->text().trimmed(); + m_leHelpFile->setText(urlString); } //END UserHelpAddDialog } diff --git a/src/dialogs/userhelpdialog.h b/src/dialogs/userhelpdialog.h index 299a94de..46a5df3b 100644 --- a/src/dialogs/userhelpdialog.h +++ b/src/dialogs/userhelpdialog.h @@ -1,90 +1,90 @@ /***************************************************************************************** userhelpdialog.h ---------------------------------------------------------------------------- date : Jul 22 2005 version : 0.20 copyright : (C) 2005 by Holger Danielsson (holger.danielsson@t-online.de) 2008 by Michel Ludwig (michel.ludwig@kdemail.net) ****************************************************************************************/ /*************************************************************************** * * * 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. * * * ***************************************************************************/ #ifndef USERHELPDIALOG_H #define USERHELPDIALOG_H #include #include #include #include class QListWidget; class QPushButton; namespace KileDialog { class UserHelpDialog : public QDialog { - Q_OBJECT - - public: - explicit UserHelpDialog(QWidget *parent = Q_NULLPTR, const char *name = Q_NULLPTR); - ~UserHelpDialog() {} - - void setParameter(const QStringList &menuentries, const QList &helpfiles); - void getParameter(QStringList &userhelpmenulist, QList &userhelpfilelist); - private: - QListWidget *m_menulistbox; - QLineEdit *m_fileedit; - QPushButton *m_add, *m_remove, *m_addsep, *m_up, *m_down; - - QList m_filelist; - - void updateButton(); - - private Q_SLOTS: - void slotChange(); - void slotAdd(); - void slotRemove(); - void slotAddSep(); - void slotUp(); - void slotDown(); + Q_OBJECT + +public: + explicit UserHelpDialog(QWidget *parent = Q_NULLPTR, const char *name = Q_NULLPTR); + ~UserHelpDialog() {} + + void setParameter(const QStringList &menuentries, const QList &helpfiles); + void getParameter(QStringList &userhelpmenulist, QList &userhelpfilelist); +private: + QListWidget *m_menulistbox; + QLineEdit *m_fileedit; + QPushButton *m_add, *m_remove, *m_addsep, *m_up, *m_down; + + QList m_filelist; + + void updateButton(); + +private Q_SLOTS: + void slotChange(); + void slotAdd(); + void slotRemove(); + void slotAddSep(); + void slotUp(); + void slotDown(); }; class UserHelpAddDialog : public QDialog { - Q_OBJECT - - public: - explicit UserHelpAddDialog(QListWidget *menulistbox, QWidget *parent = Q_NULLPTR); - ~UserHelpAddDialog() {} - - private: - QLineEdit *m_leMenuEntry, *m_leHelpFile; - QPushButton *m_pbChooseFile; - QListWidget *m_menulistbox; - - public: - QString getMenuitem() { - return m_leMenuEntry->text(); - } - QString getHelpfile() { - return m_leHelpFile->text(); - } - - private Q_SLOTS: - void onShowLocalFileSelection(); - void onAccepted(); + Q_OBJECT + +public: + explicit UserHelpAddDialog(QListWidget *menulistbox, QWidget *parent = Q_NULLPTR); + ~UserHelpAddDialog() {} + +private: + QLineEdit *m_leMenuEntry, *m_leHelpFile; + QPushButton *m_pbChooseFile; + QListWidget *m_menulistbox; + +public: + QString getMenuitem() { + return m_leMenuEntry->text(); + } + QString getHelpfile() { + return m_leHelpFile->text(); + } + +private Q_SLOTS: + void onShowLocalFileSelection(); + void onAccepted(); }; } #endif diff --git a/src/dialogs/usermenu/usermenudialog.cpp b/src/dialogs/usermenu/usermenudialog.cpp index 641a7895..3aafd031 100644 --- a/src/dialogs/usermenu/usermenudialog.cpp +++ b/src/dialogs/usermenu/usermenudialog.cpp @@ -1,981 +1,998 @@ /*********************************************************************************** Copyright (C) 2011-2012 by Holger Danielsson (holger.danielsson@versanet.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. * * * ***************************************************************************/ #include #include #include #include #include #include #include #include #include #include #include #include #include #include "dialogs/usermenu/usermenudialog.h" #include "dialogs/usermenu/usermenutree.h" #include "dialogs/usermenu/usermenuitem.h" #include "usermenu/usermenu.h" #include "kiledebug.h" #include "utilities.h" namespace KileMenu { #define CHOOSABLE_MENUTYPES 3 UserMenuDialog::UserMenuDialog(KConfig *config, KileInfo *ki, KileMenu::UserMenu *userMenu, const QString &xmlfile, QWidget *parent) - : KileDialog::Wizard(config, parent, Q_NULLPTR, i18n("Edit User Menu")) - , m_ki(ki) - , m_userMenu(userMenu) -{ - QWidget *page = new QWidget(); - QVBoxLayout *mainLayout = new QVBoxLayout; - setLayout(mainLayout); - - m_UserMenuDialog.setupUi(page); - - m_menutree = m_UserMenuDialog.m_twUserMenu; - m_menutree->setHeaderLabels(QStringList() << i18n("Menu Entry") << i18n("Shortcut")); - - // Indexes must be identical to MenuType. Only the first three of them are choosable (see CHOOSABLE_MENUTYPES) - m_listMenutypes << i18n("Text") << i18n("Insert file contents") << i18n("Execute program") << i18n("Separator") << i18n("Submenu"); - - // some text - m_UserMenuDialog.m_teText->setWhatsThis(i18n("Text, which will be inserted, if the action is executed. Some placeholders are available:
  • %M - selected (marked) text
  • %C - cursor position
  • %B - bullet
  • %E - indentation in environments
  • %R - select label from list
  • %T - select citation key from list
")); - m_UserMenuDialog.m_teText->setToolTip(i18n("Available placeholders:\n%M: Selected (marked) text\n%C: Cursor position\n%B: Bullet\n%E: Indentation in environments\n%R: Select label from list\n%T: Select citation key from list\n%S: Source file name without extension")); - - // search for all action collections (needed for shortcut conflicts) - QList allCollections; - foreach (KXMLGUIClient *client, m_ki->mainWindow()->guiFactory()->clients()) { - KILE_DEBUG_MAIN << "collection count: " << client->actionCollection()->count() ; - allCollections += client->actionCollection(); - } - m_UserMenuDialog.m_keyChooser->setCheckActionCollections(allCollections); - KILE_DEBUG_MAIN << "total collections: " << allCollections.count(); - - m_UserMenuDialog.m_pbInsertBelow->setIcon(QIcon::fromTheme("usermenu-insert-below.png")); - m_UserMenuDialog.m_pbInsertSubmenu->setIcon(QIcon::fromTheme("usermenu-submenu-below.png")); - m_UserMenuDialog.m_pbInsertSeparator->setIcon(QIcon::fromTheme("usermenu-separator-below.png")); - m_UserMenuDialog.m_pbDelete->setIcon(QIcon::fromTheme("usermenu-delete.png")); - m_UserMenuDialog.m_pbUp->setIcon(QIcon::fromTheme("usermenu-up.png")); - m_UserMenuDialog.m_pbDown->setIcon(QIcon::fromTheme("usermenu-down.png")); - m_UserMenuDialog.m_pbIconDelete->setIcon(QIcon::fromTheme("edit-clear-locationbar-rtl.png")); - - connect(m_UserMenuDialog.m_pbInsertBelow, &QPushButton::clicked, this, &UserMenuDialog::slotInsertMenuItem); - connect(m_UserMenuDialog.m_pbInsertSubmenu, &QPushButton::clicked, this, &UserMenuDialog::slotInsertSubmenu); - connect(m_UserMenuDialog.m_pbInsertSeparator, &QPushButton::clicked, this, &UserMenuDialog::slotInsertSeparator); - connect(m_UserMenuDialog.m_pbUp, &QPushButton::clicked, this, &UserMenuDialog::slotUp); - connect(m_UserMenuDialog.m_pbDown, &QPushButton::clicked, this, &UserMenuDialog::slotDown); - connect(m_UserMenuDialog.m_pbDelete, &QPushButton::clicked, this, &UserMenuDialog::slotDelete); - - connect(m_menutree, &QTreeWidget::currentItemChanged, this, &UserMenuDialog::slotCurrentItemChanged); - - connect(m_UserMenuDialog.m_pbMenuentryType, &QPushButton::clicked, this, &UserMenuDialog::slotMenuentryTypeClicked); - connect(m_UserMenuDialog.m_leMenuEntry, &KLineEdit::textEdited, this, &UserMenuDialog::slotMenuentryTextChanged); - connect(m_UserMenuDialog.m_urlRequester, &KUrlRequester::textChanged, this, &UserMenuDialog::slotUrlTextChanged); - connect(m_UserMenuDialog.m_urlRequester, &KUrlRequester::urlSelected, this, [=](){ setModified(); }); - connect(m_UserMenuDialog.m_leParameter, &KLineEdit::textEdited, this, [=](){ setModified(); }); - connect(m_UserMenuDialog.m_teText, &QPlainTextEdit::textChanged, this, [=](){ setModified(); }); - connect(m_UserMenuDialog.m_pbIcon, &QPushButton::clicked, this, &UserMenuDialog::slotIconClicked); - connect(m_UserMenuDialog.m_pbIconDelete, &QPushButton::clicked, this, &UserMenuDialog::slotIconDeleteClicked); - connect(m_UserMenuDialog.m_keyChooser, &KKeySequenceWidget::keySequenceChanged, this, &UserMenuDialog::slotKeySequenceChanged); - - connect(m_UserMenuDialog.m_cbNeedsSelection, &QCheckBox::stateChanged, this, &UserMenuDialog::slotSelectionStateChanged); - connect(m_UserMenuDialog.m_cbContextMenu, &QCheckBox::stateChanged, this, &UserMenuDialog::slotCheckboxStateChanged); - connect(m_UserMenuDialog.m_cbReplaceSelection, &QCheckBox::stateChanged, this, &UserMenuDialog::slotCheckboxStateChanged); - connect(m_UserMenuDialog.m_cbSelectInsertion, &QCheckBox::stateChanged, this, &UserMenuDialog::slotCheckboxStateChanged); - connect(m_UserMenuDialog.m_cbInsertOutput, &QCheckBox::stateChanged, this, &UserMenuDialog::slotCheckboxStateChanged); - - connect(m_UserMenuDialog.m_pbInstall, &QPushButton::clicked, this, &UserMenuDialog::slotInstallClicked); - connect(m_UserMenuDialog.m_pbNew, &QPushButton::clicked, this, &UserMenuDialog::slotNewClicked); - - connect(m_UserMenuDialog.m_pbLoad, &QPushButton::clicked, this, &UserMenuDialog::slotLoadClicked); - connect(m_UserMenuDialog.m_pbSave, &QPushButton::clicked, this, &UserMenuDialog::slotSaveClicked); - connect(m_UserMenuDialog.m_pbSaveAs, &QPushButton::clicked, this, &UserMenuDialog::slotSaveAsClicked); - - // set context menu handler for the menutree - m_menutree->setContextMenuPolicy(Qt::CustomContextMenu); - connect(m_menutree, &QWidget::customContextMenuRequested, this, &UserMenuDialog::slotCustomContextMenuRequested); - - // adjust some widths - const int w = m_UserMenuDialog.m_pbInsertBelow->sizeHint().width(); - m_UserMenuDialog.m_pbUp->setMinimumWidth(w); - m_UserMenuDialog.m_pbDown->setMinimumWidth(w); - m_UserMenuDialog.m_lbIconChosen->setMinimumWidth(m_UserMenuDialog.m_pbIcon->sizeHint().width()); - - setFocusProxy(m_menutree); - setModal(false); - - // TODO: currently all dialog actions are in an extra widget - // for usability some of those actions should be connect to the main dialog controls, - // e.g. automatic install when pressing OK - buttonBox()->clear(); - buttonBox()->addButton(QDialogButtonBox::Close); - buttonBox()->addButton(QDialogButtonBox::Help); - - mainLayout->addWidget(page); - mainLayout->addWidget(buttonBox()); - connect(buttonBox(), &QDialogButtonBox::helpRequested, this, &UserMenuDialog::slotShowHelp); - - KILE_DEBUG_MAIN << "start dialog with xmfile " << xmlfile; - - if (!xmlfile.isEmpty() && QFile::exists(xmlfile)) { - m_modified = false; - loadXmlFile(xmlfile,true); - } - else { - startDialog(); - } - - resize(minimumSize()); + : KileDialog::Wizard(config, parent, Q_NULLPTR, i18n("Edit User Menu")) + , m_ki(ki) + , m_userMenu(userMenu) +{ + QWidget *page = new QWidget(); + QVBoxLayout *mainLayout = new QVBoxLayout; + setLayout(mainLayout); + + m_UserMenuDialog.setupUi(page); + + m_menutree = m_UserMenuDialog.m_twUserMenu; + m_menutree->setHeaderLabels(QStringList() << i18n("Menu Entry") << i18n("Shortcut")); + + // Indexes must be identical to MenuType. Only the first three of them are choosable (see CHOOSABLE_MENUTYPES) + m_listMenutypes << i18n("Text") << i18n("Insert file contents") << i18n("Execute program") << i18n("Separator") << i18n("Submenu"); + + // some text + m_UserMenuDialog.m_teText->setWhatsThis(i18n("Text, which will be inserted, if the action is executed. Some placeholders are available:
  • %M - selected (marked) text
  • %C - cursor position
  • %B - bullet
  • %E - indentation in environments
  • %R - select label from list
  • %T - select citation key from list
")); + m_UserMenuDialog.m_teText->setToolTip(i18n("Available placeholders:\n%M: Selected (marked) text\n%C: Cursor position\n%B: Bullet\n%E: Indentation in environments\n%R: Select label from list\n%T: Select citation key from list\n%S: Source file name without extension")); + + // search for all action collections (needed for shortcut conflicts) + QList allCollections; + foreach (KXMLGUIClient *client, m_ki->mainWindow()->guiFactory()->clients()) { + KILE_DEBUG_MAIN << "collection count: " << client->actionCollection()->count() ; + allCollections += client->actionCollection(); + } + m_UserMenuDialog.m_keyChooser->setCheckActionCollections(allCollections); + KILE_DEBUG_MAIN << "total collections: " << allCollections.count(); + + m_UserMenuDialog.m_pbInsertBelow->setIcon(QIcon::fromTheme("usermenu-insert-below.png")); + m_UserMenuDialog.m_pbInsertSubmenu->setIcon(QIcon::fromTheme("usermenu-submenu-below.png")); + m_UserMenuDialog.m_pbInsertSeparator->setIcon(QIcon::fromTheme("usermenu-separator-below.png")); + m_UserMenuDialog.m_pbDelete->setIcon(QIcon::fromTheme("usermenu-delete.png")); + m_UserMenuDialog.m_pbUp->setIcon(QIcon::fromTheme("usermenu-up.png")); + m_UserMenuDialog.m_pbDown->setIcon(QIcon::fromTheme("usermenu-down.png")); + m_UserMenuDialog.m_pbIconDelete->setIcon(QIcon::fromTheme("edit-clear-locationbar-rtl.png")); + + connect(m_UserMenuDialog.m_pbInsertBelow, &QPushButton::clicked, this, &UserMenuDialog::slotInsertMenuItem); + connect(m_UserMenuDialog.m_pbInsertSubmenu, &QPushButton::clicked, this, &UserMenuDialog::slotInsertSubmenu); + connect(m_UserMenuDialog.m_pbInsertSeparator, &QPushButton::clicked, this, &UserMenuDialog::slotInsertSeparator); + connect(m_UserMenuDialog.m_pbUp, &QPushButton::clicked, this, &UserMenuDialog::slotUp); + connect(m_UserMenuDialog.m_pbDown, &QPushButton::clicked, this, &UserMenuDialog::slotDown); + connect(m_UserMenuDialog.m_pbDelete, &QPushButton::clicked, this, &UserMenuDialog::slotDelete); + + connect(m_menutree, &QTreeWidget::currentItemChanged, this, &UserMenuDialog::slotCurrentItemChanged); + + connect(m_UserMenuDialog.m_pbMenuentryType, &QPushButton::clicked, this, &UserMenuDialog::slotMenuentryTypeClicked); + connect(m_UserMenuDialog.m_leMenuEntry, &KLineEdit::textEdited, this, &UserMenuDialog::slotMenuentryTextChanged); + connect(m_UserMenuDialog.m_urlRequester, &KUrlRequester::textChanged, this, &UserMenuDialog::slotUrlTextChanged); + connect(m_UserMenuDialog.m_urlRequester, &KUrlRequester::urlSelected, this, [=]() { + setModified(); + }); + connect(m_UserMenuDialog.m_leParameter, &KLineEdit::textEdited, this, [=]() { + setModified(); + }); + connect(m_UserMenuDialog.m_teText, &QPlainTextEdit::textChanged, this, [=]() { + setModified(); + }); + connect(m_UserMenuDialog.m_pbIcon, &QPushButton::clicked, this, &UserMenuDialog::slotIconClicked); + connect(m_UserMenuDialog.m_pbIconDelete, &QPushButton::clicked, this, &UserMenuDialog::slotIconDeleteClicked); + connect(m_UserMenuDialog.m_keyChooser, &KKeySequenceWidget::keySequenceChanged, this, &UserMenuDialog::slotKeySequenceChanged); + + connect(m_UserMenuDialog.m_cbNeedsSelection, &QCheckBox::stateChanged, this, &UserMenuDialog::slotSelectionStateChanged); + connect(m_UserMenuDialog.m_cbContextMenu, &QCheckBox::stateChanged, this, &UserMenuDialog::slotCheckboxStateChanged); + connect(m_UserMenuDialog.m_cbReplaceSelection, &QCheckBox::stateChanged, this, &UserMenuDialog::slotCheckboxStateChanged); + connect(m_UserMenuDialog.m_cbSelectInsertion, &QCheckBox::stateChanged, this, &UserMenuDialog::slotCheckboxStateChanged); + connect(m_UserMenuDialog.m_cbInsertOutput, &QCheckBox::stateChanged, this, &UserMenuDialog::slotCheckboxStateChanged); + + connect(m_UserMenuDialog.m_pbInstall, &QPushButton::clicked, this, &UserMenuDialog::slotInstallClicked); + connect(m_UserMenuDialog.m_pbNew, &QPushButton::clicked, this, &UserMenuDialog::slotNewClicked); + + connect(m_UserMenuDialog.m_pbLoad, &QPushButton::clicked, this, &UserMenuDialog::slotLoadClicked); + connect(m_UserMenuDialog.m_pbSave, &QPushButton::clicked, this, &UserMenuDialog::slotSaveClicked); + connect(m_UserMenuDialog.m_pbSaveAs, &QPushButton::clicked, this, &UserMenuDialog::slotSaveAsClicked); + + // set context menu handler for the menutree + m_menutree->setContextMenuPolicy(Qt::CustomContextMenu); + connect(m_menutree, &QWidget::customContextMenuRequested, this, &UserMenuDialog::slotCustomContextMenuRequested); + + // adjust some widths + const int w = m_UserMenuDialog.m_pbInsertBelow->sizeHint().width(); + m_UserMenuDialog.m_pbUp->setMinimumWidth(w); + m_UserMenuDialog.m_pbDown->setMinimumWidth(w); + m_UserMenuDialog.m_lbIconChosen->setMinimumWidth(m_UserMenuDialog.m_pbIcon->sizeHint().width()); + + setFocusProxy(m_menutree); + setModal(false); + + // TODO: currently all dialog actions are in an extra widget + // for usability some of those actions should be connect to the main dialog controls, + // e.g. automatic install when pressing OK + buttonBox()->clear(); + buttonBox()->addButton(QDialogButtonBox::Close); + buttonBox()->addButton(QDialogButtonBox::Help); + + mainLayout->addWidget(page); + mainLayout->addWidget(buttonBox()); + connect(buttonBox(), &QDialogButtonBox::helpRequested, this, &UserMenuDialog::slotShowHelp); + + KILE_DEBUG_MAIN << "start dialog with xmfile " << xmlfile; + + if (!xmlfile.isEmpty() && QFile::exists(xmlfile)) { + m_modified = false; + loadXmlFile(xmlfile,true); + } + else { + startDialog(); + } + + resize(minimumSize()); } void UserMenuDialog::startDialog() { - initDialog(); + initDialog(); - m_modified = false; - setXmlFile(QString(), false); - updateDialogButtons(); - m_UserMenuDialog.m_pbNew->setEnabled(false); + m_modified = false; + setXmlFile(QString(), false); + updateDialogButtons(); + m_UserMenuDialog.m_pbNew->setEnabled(false); } void UserMenuDialog::initDialog() { - updateTreeButtons(); + updateTreeButtons(); - QTreeWidgetItem *current = m_menutree->currentItem(); - if (current) { - m_menutree->setCurrentItem(current); - } + QTreeWidgetItem *current = m_menutree->currentItem(); + if (current) { + m_menutree->setCurrentItem(current); + } - // init first entry - m_currentIcon.clear(); - showMenuentryData(dynamic_cast(current)); + // init first entry + m_currentIcon.clear(); + showMenuentryData(dynamic_cast(current)); } void UserMenuDialog::setXmlFile(const QString &filename, bool installed) { - m_currentXmlInstalled = installed; - m_currentXmlFile = filename; - m_UserMenuDialog.m_lbXmlFile->setText(i18n("File:") + QLatin1String(" ") + QFileInfo(m_currentXmlFile).fileName()); - if (m_currentXmlInstalled) { - m_UserMenuDialog.m_lbXmlInstalled->show(); - } else { - m_UserMenuDialog.m_lbXmlInstalled->hide(); - } + m_currentXmlInstalled = installed; + m_currentXmlFile = filename; + m_UserMenuDialog.m_lbXmlFile->setText(i18n("File:") + QLatin1String(" ") + QFileInfo(m_currentXmlFile).fileName()); + if (m_currentXmlInstalled) { + m_UserMenuDialog.m_lbXmlInstalled->show(); + } else { + m_UserMenuDialog.m_lbXmlInstalled->hide(); + } } void UserMenuDialog::setModified() { - if (!m_modified) { - m_modified = true; - } + if (!m_modified) { + m_modified = true; + } - updateDialogButtons(); + updateDialogButtons(); } void UserMenuDialog::updateDialogButtons() { - bool installedFile = (!m_currentXmlFile.isEmpty()); - bool menutreeState = !m_menutree->isEmpty(); + bool installedFile = (!m_currentXmlFile.isEmpty()); + bool menutreeState = !m_menutree->isEmpty(); - bool installState = !m_modified && installedFile && !m_currentXmlInstalled; - bool saveState = m_modified && installedFile; - bool saveAsState = m_modified || (!m_modified && installedFile && m_currentXmlInstalled); + bool installState = !m_modified && installedFile && !m_currentXmlInstalled; + bool saveState = m_modified && installedFile; + bool saveAsState = m_modified || (!m_modified && installedFile && m_currentXmlInstalled); - m_UserMenuDialog.m_pbInstall->setEnabled(installState && menutreeState); - m_UserMenuDialog.m_pbSave->setEnabled(saveState && menutreeState); - m_UserMenuDialog.m_pbSaveAs->setEnabled(saveAsState && menutreeState); - m_UserMenuDialog.m_pbNew->setEnabled(true); + m_UserMenuDialog.m_pbInstall->setEnabled(installState && menutreeState); + m_UserMenuDialog.m_pbSave->setEnabled(saveState && menutreeState); + m_UserMenuDialog.m_pbSaveAs->setEnabled(saveAsState && menutreeState); + m_UserMenuDialog.m_pbNew->setEnabled(true); } void UserMenuDialog::slotShowHelp() { - const QString message = i18n("

You can create, change and install a user-defined menu, which will appear as a part of Kile's menu. " - "To create or change this menu, use the six buttons on the left side. " - "Even more possible actions are available in the context menu of already existing menu items.

" - "

Like a standard menu, three different kinds of menu items are available:

" - "
    " - "
  • standard entries, which are assigned to an action
  • " - "
  • submenus, which contain more menu items
  • " - "
  • separators, to get a visible structure of all entries
  • " - "
" - "

Each standard menu item is assigned to one of three action types:

" - "
    " - "
  • insert text: this action will insert your text at the current cursor position. " - "Some metachars are available: %M, %C, %B, %E, %R, %T, %S: " - "see the What's This or Tool Tip feature of this widget to get more information.
  • " - "
  • file content: inserts the complete contents of a given file (metachars are also available)
  • " - "
  • run an external program: The output of this program can be inserted into the opened document. " - "Metachar %M is also possible in the commandline of this program, as the selected text will be saved in a temporary file. " - "Use %M for the filename of this temporary file.
  • " - "
" - "

If some important information for an action is missing, menu items are colored red. " - "More information is available using the What's this feature of most widgets.

"); - - KMessageBox::information(this, message, i18n("UserMenu Dialog")); + const QString message = i18n("

You can create, change and install a user-defined menu, which will appear as a part of Kile's menu. " + "To create or change this menu, use the six buttons on the left side. " + "Even more possible actions are available in the context menu of already existing menu items.

" + "

Like a standard menu, three different kinds of menu items are available:

" + "
    " + "
  • standard entries, which are assigned to an action
  • " + "
  • submenus, which contain more menu items
  • " + "
  • separators, to get a visible structure of all entries
  • " + "
" + "

Each standard menu item is assigned to one of three action types:

" + "
    " + "
  • insert text: this action will insert your text at the current cursor position. " + "Some metachars are available: %M, %C, %B, %E, %R, %T, %S: " + "see the What's This or Tool Tip feature of this widget to get more information.
  • " + "
  • file content: inserts the complete contents of a given file (metachars are also available)
  • " + "
  • run an external program: The output of this program can be inserted into the opened document. " + "Metachar %M is also possible in the commandline of this program, as the selected text will be saved in a temporary file. " + "Use %M for the filename of this temporary file.
  • " + "
" + "

If some important information for an action is missing, menu items are colored red. " + "More information is available using the What's this feature of most widgets.

"); + + KMessageBox::information(this, message, i18n("UserMenu Dialog")); } ///////////////////////////// Button slots (Install/New) ////////////////////////////// void UserMenuDialog::slotInstallClicked() { - KILE_DEBUG_MAIN << "install " << m_currentXmlFile << "..."; + KILE_DEBUG_MAIN << "install " << m_currentXmlFile << "..."; - if (!m_modified && !m_currentXmlFile.isEmpty()) { - m_userMenu->installXmlFile(m_currentXmlFile); - setXmlFile(m_currentXmlFile,true); - updateDialogButtons(); - } + if (!m_modified && !m_currentXmlFile.isEmpty()) { + m_userMenu->installXmlFile(m_currentXmlFile); + setXmlFile(m_currentXmlFile,true); + updateDialogButtons(); + } } void UserMenuDialog::slotNewClicked() { - KILE_DEBUG_MAIN << "start new menutree ... "; + KILE_DEBUG_MAIN << "start new menutree ... "; - if (!m_menutree->isEmpty() && m_modified) { - if (KMessageBox::questionYesNo(this, i18n("Current menu tree was modified, but not saved.\nDiscard this tree?")) == KMessageBox::No) { - return; - } - } + if (!m_menutree->isEmpty() && m_modified) { + if (KMessageBox::questionYesNo(this, i18n("Current menu tree was modified, but not saved.\nDiscard this tree?")) == KMessageBox::No) { + return; + } + } - m_menutree->clear(); - m_modified = false; - startDialog(); // includes updating of buttons + m_menutree->clear(); + m_modified = false; + startDialog(); // includes updating of buttons } ///////////////////////////// Button slots (Load) ////////////////////////////// void UserMenuDialog::slotLoadClicked() { - KILE_DEBUG_MAIN << "load xml file "; + KILE_DEBUG_MAIN << "load xml file "; - if (!m_menutree->isEmpty() && m_modified) { - if (KMessageBox::questionYesNo(this, i18n("Current menu tree was modified, but not saved.\nDiscard this tree?")) == KMessageBox::No) { - return; - } - } + if (!m_menutree->isEmpty() && m_modified) { + if (KMessageBox::questionYesNo(this, i18n("Current menu tree was modified, but not saved.\nDiscard this tree?")) == KMessageBox::No) { + return; + } + } - QString directory = UserMenu::selectUserMenuDir(); - QString filter = i18n("User Menu Files (*.xml)"); + QString directory = UserMenu::selectUserMenuDir(); + QString filter = i18n("User Menu Files (*.xml)"); - QString filename = QFileDialog::getOpenFileName(this, i18n("Select Menu File"), directory, filter); - if (filename.isEmpty()) { - return; - } + QString filename = QFileDialog::getOpenFileName(this, i18n("Select Menu File"), directory, filter); + if (filename.isEmpty()) { + return; + } - if (QFile::exists(filename)) { - loadXmlFile(filename,false); // includes updating of buttons - } - else { - KMessageBox::error(this, i18n("File '%1' does not exist.", filename)); - } + if (QFile::exists(filename)) { + loadXmlFile(filename,false); // includes updating of buttons + } + else { + KMessageBox::error(this, i18n("File '%1' does not exist.", filename)); + } } void UserMenuDialog::loadXmlFile(const QString &filename, bool installed) { - KILE_DEBUG_MAIN << "load xml started ..."; - m_menutree->readXml(filename); - initDialog(); - m_modified = false; - setXmlFile(filename,installed); - updateDialogButtons(); - KILE_DEBUG_MAIN << "load xml finished ..."; + KILE_DEBUG_MAIN << "load xml started ..."; + m_menutree->readXml(filename); + initDialog(); + m_modified = false; + setXmlFile(filename,installed); + updateDialogButtons(); + KILE_DEBUG_MAIN << "load xml finished ..."; } ///////////////////////////// Button slots (Save) ////////////////////////////// void UserMenuDialog::slotSaveClicked() { - if (saveClicked()) { - m_modified = false; - if (m_currentXmlInstalled) { - slotInstallClicked(); // includes all updates - } - else { - setXmlFile(m_currentXmlFile,false); - } - updateDialogButtons(); - } + if (saveClicked()) { + m_modified = false; + if (m_currentXmlInstalled) { + slotInstallClicked(); // includes all updates + } + else { + setXmlFile(m_currentXmlFile,false); + } + updateDialogButtons(); + } } bool UserMenuDialog::saveClicked() { - if (m_currentXmlFile.isEmpty()) { - return false; - } - KILE_DEBUG_MAIN << "save menutree: " << m_currentXmlFile; + if (m_currentXmlFile.isEmpty()) { + return false; + } + KILE_DEBUG_MAIN << "save menutree: " << m_currentXmlFile; - // read current entry - QTreeWidgetItem *current = m_menutree->currentItem(); - if (current) { - KILE_DEBUG_MAIN << "read current item ..."; - readMenuentryData( dynamic_cast(current) ); - } + // read current entry + QTreeWidgetItem *current = m_menutree->currentItem(); + if (current) { + KILE_DEBUG_MAIN << "read current item ..."; + readMenuentryData( dynamic_cast(current) ); + } - if (saveCheck() == false) { - return false; - } + if (saveCheck() == false) { + return false; + } - // force to save file in local directory - QStringList dirs = QStandardPaths::locateAll(QStandardPaths::DataLocation, "usermenu", QStandardPaths::LocateDirectory); - if (dirs.size() > 1) { - if (m_currentXmlFile.startsWith(dirs[1])) { - m_currentXmlFile.replace(dirs[1],dirs[0]); - KILE_DEBUG_MAIN << "change filename to local directory:" << m_currentXmlFile; - } - } + // force to save file in local directory + QStringList dirs = QStandardPaths::locateAll(QStandardPaths::DataLocation, "usermenu", QStandardPaths::LocateDirectory); + if (dirs.size() > 1) { + if (m_currentXmlFile.startsWith(dirs[1])) { + m_currentXmlFile.replace(dirs[1],dirs[0]); + KILE_DEBUG_MAIN << "change filename to local directory:" << m_currentXmlFile; + } + } - // save file - m_menutree->writeXml(m_currentXmlFile); - return true; + // save file + m_menutree->writeXml(m_currentXmlFile); + return true; } void UserMenuDialog::slotSaveAsClicked() { - const QString filename = saveAsClicked(); - if (!filename.isEmpty()) { - // set new state: current file is not installed anymore - m_modified = false; - setXmlFile(filename,false); - updateDialogButtons(); - } + const QString filename = saveAsClicked(); + if (!filename.isEmpty()) { + // set new state: current file is not installed anymore + m_modified = false; + setXmlFile(filename,false); + updateDialogButtons(); + } } QString UserMenuDialog::saveAsClicked() { - KILE_DEBUG_MAIN << "menutree should be saved as ..."; + KILE_DEBUG_MAIN << "menutree should be saved as ..."; - // read current entry - QTreeWidgetItem *current = m_menutree->currentItem(); - if (current) { - KILE_DEBUG_MAIN << "read current item ..."; - readMenuentryData(dynamic_cast(current)); - } + // read current entry + QTreeWidgetItem *current = m_menutree->currentItem(); + if (current) { + KILE_DEBUG_MAIN << "read current item ..."; + readMenuentryData(dynamic_cast(current)); + } - if (saveCheck() == false) { - return QString(); - } + if (saveCheck() == false) { + return QString(); + } - const QString directory = QStandardPaths::writableLocation(QStandardPaths::DataLocation) + QLatin1Char('/') + "usermenu/"; - const QString filter = i18n("User Menu Files (*.xml)"); + const QString directory = QStandardPaths::writableLocation(QStandardPaths::DataLocation) + QLatin1Char('/') + "usermenu/"; + const QString filter = i18n("User Menu Files (*.xml)"); - QString filename = QFileDialog::getSaveFileName(this, i18n("Save Menu File"), directory, filter); - if (filename.isEmpty()) { - return QString(); - } + QString filename = QFileDialog::getSaveFileName(this, i18n("Save Menu File"), directory, filter); + if (filename.isEmpty()) { + return QString(); + } - if (QFile::exists(filename)) { - if (KMessageBox::questionYesNo(this, i18n("File '%1' does already exist.\nOverwrite this file?", filename)) == KMessageBox::No) { - return QString(); - } - } + if (QFile::exists(filename)) { + if (KMessageBox::questionYesNo(this, i18n("File '%1' does already exist.\nOverwrite this file?", filename)) == KMessageBox::No) { + return QString(); + } + } - // save file - m_menutree->writeXml(filename); - return filename; + // save file + m_menutree->writeXml(filename); + return filename; } bool UserMenuDialog::saveCheck() { - if (m_menutree->errorCheck() == false) { - if (KMessageBox::questionYesNo(this, i18n("The menu tree contains some errors and installing this file may lead to unpredictable results.\nDo you really want to save this file?")) == KMessageBox::No) { - return false; - } - } + if (m_menutree->errorCheck() == false) { + if (KMessageBox::questionYesNo(this, i18n("The menu tree contains some errors and installing this file may lead to unpredictable results.\nDo you really want to save this file?")) == KMessageBox::No) { + return false; + } + } - return true; + return true; } ///////////////////////////// Button slots (left widget) ////////////////////////////// void UserMenuDialog::slotCustomContextMenuRequested(const QPoint &pos) { - m_menutree->contextMenuRequested(pos); - updateAfterDelete(); + m_menutree->contextMenuRequested(pos); + updateAfterDelete(); } void UserMenuDialog::slotInsertMenuItem() { - if (m_menutree->insertMenuItem(m_menutree->currentItem())) { - updateTreeButtons(); - setModified(); - } + if (m_menutree->insertMenuItem(m_menutree->currentItem())) { + updateTreeButtons(); + setModified(); + } } void UserMenuDialog::slotInsertSubmenu() { - QTreeWidgetItem *current = m_menutree->currentItem(); - if (current && m_menutree->insertSubmenu(current)) { - updateTreeButtons(); - setModified(); - } + QTreeWidgetItem *current = m_menutree->currentItem(); + if (current && m_menutree->insertSubmenu(current)) { + updateTreeButtons(); + setModified(); + } } void UserMenuDialog::slotInsertSeparator() { - QTreeWidgetItem *current = m_menutree->currentItem(); - if (current && m_menutree->insertSeparator(current)) { - updateTreeButtons(); - setModified(); - } + QTreeWidgetItem *current = m_menutree->currentItem(); + if (current && m_menutree->insertSeparator(current)) { + updateTreeButtons(); + setModified(); + } } void UserMenuDialog::slotDelete() { - QTreeWidgetItem *current = m_menutree->currentItem(); - if (current) { - m_menutree->itemDelete(current); - updateAfterDelete(); - } + QTreeWidgetItem *current = m_menutree->currentItem(); + if (current) { + m_menutree->itemDelete(current); + updateAfterDelete(); + } } void UserMenuDialog::slotUp() { - QTreeWidgetItem *current = m_menutree->currentItem(); - if (current) { - m_menutree->itemUp(); - updateTreeButtons(); - setModified(); - } + QTreeWidgetItem *current = m_menutree->currentItem(); + if (current) { + m_menutree->itemUp(); + updateTreeButtons(); + setModified(); + } } void UserMenuDialog::slotDown() { - QTreeWidgetItem *current = m_menutree->currentItem(); - if (current) { - m_menutree->itemDown(); - updateTreeButtons(); - setModified(); - } + QTreeWidgetItem *current = m_menutree->currentItem(); + if (current) { + m_menutree->itemDown(); + updateTreeButtons(); + setModified(); + } } void UserMenuDialog::updateTreeButtons() { - UserMenuItem *current = dynamic_cast(m_menutree->currentItem()); - if (current) { - bool state = (current->menutype() == UserMenuData::Separator) ? false : true; - m_UserMenuDialog.m_pbInsertSeparator->setEnabled(state); - m_UserMenuDialog.m_pbDelete->setEnabled(true); - - bool upstate = (m_menutree->indexOfTopLevelItem(current) == 0) ? false : true; - m_UserMenuDialog.m_pbUp->setEnabled(upstate); - - bool downstate = (m_menutree->itemBelow(current)) ? true : false; - if (!downstate && current->parent()) { - downstate = true; - } - m_UserMenuDialog.m_pbDown->setEnabled(downstate); - } - else { - m_UserMenuDialog.m_pbInsertSeparator->setEnabled(false); - m_UserMenuDialog.m_pbDelete->setEnabled(false); - m_UserMenuDialog.m_pbUp->setEnabled(false); - m_UserMenuDialog.m_pbDown->setEnabled(false); - } + UserMenuItem *current = dynamic_cast(m_menutree->currentItem()); + if (current) { + bool state = (current->menutype() == UserMenuData::Separator) ? false : true; + m_UserMenuDialog.m_pbInsertSeparator->setEnabled(state); + m_UserMenuDialog.m_pbDelete->setEnabled(true); + + bool upstate = (m_menutree->indexOfTopLevelItem(current) == 0) ? false : true; + m_UserMenuDialog.m_pbUp->setEnabled(upstate); + + bool downstate = (m_menutree->itemBelow(current)) ? true : false; + if (!downstate && current->parent()) { + downstate = true; + } + m_UserMenuDialog.m_pbDown->setEnabled(downstate); + } + else { + m_UserMenuDialog.m_pbInsertSeparator->setEnabled(false); + m_UserMenuDialog.m_pbDelete->setEnabled(false); + m_UserMenuDialog.m_pbUp->setEnabled(false); + m_UserMenuDialog.m_pbDown->setEnabled(false); + } } void UserMenuDialog::updateAfterDelete() { - if (m_menutree->isEmpty()) { - initDialog(); - } + if (m_menutree->isEmpty()) { + initDialog(); + } - updateTreeButtons(); - setModified(); + updateTreeButtons(); + setModified(); } ////////////////////////////// TreeWidget slots (left widget) ////////////////////////////// void UserMenuDialog::slotCurrentItemChanged(QTreeWidgetItem *current,QTreeWidgetItem *previous) { - QString from = (previous) ? previous->text(0) : "---"; - QString to = (current) ? current->text(0) : "---"; + QString from = (previous) ? previous->text(0) : "---"; + QString to = (current) ? current->text(0) : "---"; - KILE_DEBUG_MAIN << "currentItemChanged: from=" << from << " to=" << to; - bool modifiedState = m_modified; - bool installState = m_UserMenuDialog.m_pbInstall->isEnabled(); - bool saveState = m_UserMenuDialog.m_pbSave->isEnabled(); - bool saveAsState = m_UserMenuDialog.m_pbSaveAs->isEnabled(); + KILE_DEBUG_MAIN << "currentItemChanged: from=" << from << " to=" << to; + bool modifiedState = m_modified; + bool installState = m_UserMenuDialog.m_pbInstall->isEnabled(); + bool saveState = m_UserMenuDialog.m_pbSave->isEnabled(); + bool saveAsState = m_UserMenuDialog.m_pbSaveAs->isEnabled(); - // read old data - readMenuentryData(dynamic_cast(previous)); + // read old data + readMenuentryData(dynamic_cast(previous)); - // set new data - showMenuentryData(dynamic_cast(current)); + // set new data + showMenuentryData(dynamic_cast(current)); - // update buttons for treewidget - updateTreeButtons(); + // update buttons for treewidget + updateTreeButtons(); - // restore saved states - m_modified = modifiedState; - m_UserMenuDialog.m_pbInstall->setEnabled(installState); - m_UserMenuDialog.m_pbSave->setEnabled(saveState); - m_UserMenuDialog.m_pbSaveAs->setEnabled(saveAsState); + // restore saved states + m_modified = modifiedState; + m_UserMenuDialog.m_pbInstall->setEnabled(installState); + m_UserMenuDialog.m_pbSave->setEnabled(saveState); + m_UserMenuDialog.m_pbSaveAs->setEnabled(saveAsState); } ////////////////////////////// MenuentryType slots (right widget) ////////////////////////////// void UserMenuDialog::slotMenuentryTypeClicked() { - UserMenuItem *current = dynamic_cast(m_menutree->currentItem()); - if (!current) { - return; - } - - KILE_DEBUG_MAIN << "change menu item type of current item: " << current->text(0); - QStringList typelist; - for (int i = 0; i < CHOOSABLE_MENUTYPES; ++i) { - typelist << m_listMenutypes[i]; - } - - int oldtype = current->menutype(); - bool ok = false; - - QString item = QInputDialog::getItem(this, i18n("Menutype"), i18n("Please choose a menutype"), - typelist, oldtype, false, &ok); - if (!ok) { - return; - } - - int newtype = m_listMenutypes.indexOf(item); - if (newtype == -1 || newtype == oldtype) { - return; - } - - // set new values - current->setMenutype( UserMenuData::MenuType(newtype) ); - m_UserMenuDialog.m_lbMenuentryType->setText(item); - if (newtype == UserMenuData::Text) { - setMenuentryFileChooser(current,false); - setMenuentryFileParameter(current,false); - setMenuentryTextEdit(current,true); - setMenuentryCheckboxes(current,false); - } - else if (newtype == UserMenuData::FileContent) { - setMenuentryFileChooser(current,true); - setMenuentryFileParameter(current,false); - setMenuentryTextEdit(current,false); - setMenuentryCheckboxes(current,false); - } - else /* if (newtype == UserMenuData::Program) */ { - setMenuentryFileChooser(current,true); - setMenuentryFileParameter(current,true); - setMenuentryTextEdit(current,false); - setMenuentryCheckboxes(current,true); - } - - setModified(); + UserMenuItem *current = dynamic_cast(m_menutree->currentItem()); + if (!current) { + return; + } + + KILE_DEBUG_MAIN << "change menu item type of current item: " << current->text(0); + QStringList typelist; + for (int i = 0; i < CHOOSABLE_MENUTYPES; ++i) { + typelist << m_listMenutypes[i]; + } + + int oldtype = current->menutype(); + bool ok = false; + + QString item = QInputDialog::getItem(this, i18n("Menutype"), i18n("Please choose a menutype"), + typelist, oldtype, false, &ok); + if (!ok) { + return; + } + + int newtype = m_listMenutypes.indexOf(item); + if (newtype == -1 || newtype == oldtype) { + return; + } + + // set new values + current->setMenutype( UserMenuData::MenuType(newtype) ); + m_UserMenuDialog.m_lbMenuentryType->setText(item); + if (newtype == UserMenuData::Text) { + setMenuentryFileChooser(current,false); + setMenuentryFileParameter(current,false); + setMenuentryTextEdit(current,true); + setMenuentryCheckboxes(current,false); + } + else if (newtype == UserMenuData::FileContent) { + setMenuentryFileChooser(current,true); + setMenuentryFileParameter(current,false); + setMenuentryTextEdit(current,false); + setMenuentryCheckboxes(current,false); + } + else { /* if (newtype == UserMenuData::Program) */ + setMenuentryFileChooser(current,true); + setMenuentryFileParameter(current,true); + setMenuentryTextEdit(current,false); + setMenuentryCheckboxes(current,true); + } + + setModified(); } ////////////////////////////// Menuentry slot (right widget) ////////////////////////////// void UserMenuDialog::slotMenuentryTextChanged(const QString &text) { - UserMenuItem *current = dynamic_cast( m_menutree->currentItem() ); - if (current) { - current->setText(0,text); - } - setModified(); + UserMenuItem *current = dynamic_cast( m_menutree->currentItem() ); + if (current) { + current->setText(0,text); + } + setModified(); } ////////////////////////////// KUrlRequester slots (right widget) ////////////////////////////// void UserMenuDialog::slotUrlTextChanged(const QString &) { - UserMenuItem *current = dynamic_cast(m_menutree->currentItem()); - if (!current) { - return; - } + UserMenuItem *current = dynamic_cast(m_menutree->currentItem()); + if (!current) { + return; + } - QString file = m_UserMenuDialog.m_urlRequester->text().trimmed(); + QString file = m_UserMenuDialog.m_urlRequester->text().trimmed(); - QString color = "black"; - int type = current->menutype(); - if (type == UserMenuData::FileContent) { - if (file.isEmpty() || !QFile::exists(file)) { - color = "red"; - } - } - else if (type == UserMenuData::Program) { - if (file.isEmpty() || !m_menutree->isItemExecutable(file)) { - color= "red"; - } - } + QString color = "black"; + int type = current->menutype(); + if (type == UserMenuData::FileContent) { + if (file.isEmpty() || !QFile::exists(file)) { + color = "red"; + } + } + else if (type == UserMenuData::Program) { + if (file.isEmpty() || !m_menutree->isItemExecutable(file)) { + color= "red"; + } + } - m_UserMenuDialog.m_urlRequester->setStyleSheet( "QLineEdit { color: " + color + "; }" ); - setModified(); + m_UserMenuDialog.m_urlRequester->setStyleSheet( "QLineEdit { color: " + color + "; }" ); + setModified(); } ////////////////////////////// Icon slots (right widget) ////////////////////////////// void UserMenuDialog::slotIconClicked() { - QString iconname = KIconDialog::getIcon(KIconLoader::Small, KIconLoader::Any,true); - if (iconname!=m_currentIcon && !iconname.isEmpty()) { - QString iconpath = KIconLoader::global()->iconPath(iconname,KIconLoader::Small); - KILE_DEBUG_MAIN << "icon changed: " << iconname << " path=" << iconpath; - m_currentIcon = iconpath; - setMenuentryIcon(m_currentIcon); - setModified(); - } + QString iconname = KIconDialog::getIcon(KIconLoader::Small, KIconLoader::Any,true); + if (iconname!=m_currentIcon && !iconname.isEmpty()) { + QString iconpath = KIconLoader::global()->iconPath(iconname,KIconLoader::Small); + KILE_DEBUG_MAIN << "icon changed: " << iconname << " path=" << iconpath; + m_currentIcon = iconpath; + setMenuentryIcon(m_currentIcon); + setModified(); + } } void UserMenuDialog::slotIconDeleteClicked() { - m_currentIcon.clear(); - setMenuentryIcon(m_currentIcon); - setModified(); + m_currentIcon.clear(); + setMenuentryIcon(m_currentIcon); + setModified(); } void UserMenuDialog::setMenuentryIcon(const QString &icon) { - UserMenuItem *current = dynamic_cast(m_menutree->currentItem()); - if (current) { - if (icon.isEmpty()) { - current->setIcon(0, QIcon::fromTheme(QString())); - } else { - current->setIcon(0, QIcon::fromTheme(icon)); - } - current->setMenuicon(icon); + UserMenuItem *current = dynamic_cast(m_menutree->currentItem()); + if (current) { + if (icon.isEmpty()) { + current->setIcon(0, QIcon::fromTheme(QString())); + } else { + current->setIcon(0, QIcon::fromTheme(icon)); + } + current->setMenuicon(icon); - // update icon widgets - setMenuentryIcon(current,true,icon); - setModified(); - } + // update icon widgets + setMenuentryIcon(current,true,icon); + setModified(); + } } ////////////////////////////// Shortcut slots (right widget) ////////////////////////////// void UserMenuDialog::slotKeySequenceChanged(const QKeySequence &seq) { - QString shortcut = seq.toString(QKeySequence::NativeText); - KILE_DEBUG_MAIN << "key sequence changed: " << shortcut; + QString shortcut = seq.toString(QKeySequence::NativeText); + KILE_DEBUG_MAIN << "key sequence changed: " << shortcut; - UserMenuItem *current = dynamic_cast( m_menutree->currentItem() ); - if (current) { - current->setText(1, shortcut); - current->setShortcut(shortcut); + UserMenuItem *current = dynamic_cast( m_menutree->currentItem() ); + if (current) { + current->setText(1, shortcut); + current->setShortcut(shortcut); - m_UserMenuDialog.m_keyChooser->applyStealShortcut(); - setModified(); - } + m_UserMenuDialog.m_keyChooser->applyStealShortcut(); + setModified(); + } } ////////////////////////////// Selection checkbox slots (right widget) ////////////////////////////// void UserMenuDialog::slotSelectionStateChanged(int state) { - m_UserMenuDialog.m_cbReplaceSelection->setEnabled(state); - m_UserMenuDialog.m_cbContextMenu->setEnabled(state); - if (!state) { - m_UserMenuDialog.m_cbReplaceSelection->setChecked(state); - m_UserMenuDialog.m_cbContextMenu->setChecked(state); - } - setModified(); + m_UserMenuDialog.m_cbReplaceSelection->setEnabled(state); + m_UserMenuDialog.m_cbContextMenu->setEnabled(state); + if (!state) { + m_UserMenuDialog.m_cbReplaceSelection->setChecked(state); + m_UserMenuDialog.m_cbContextMenu->setChecked(state); + } + setModified(); } void UserMenuDialog::slotCheckboxStateChanged(int) { - setModified(); + setModified(); } ////////////////////////////// read menu item data ////////////////////////////// void UserMenuDialog::readMenuentryData(UserMenuItem *item) { - KILE_DEBUG_MAIN << "read current menu item ..."; - if (!item) { - return; - } + KILE_DEBUG_MAIN << "read current menu item ..."; + if (!item) { + return; + } - UserMenuData::MenuType type = UserMenuData::MenuType( m_listMenutypes.indexOf(m_UserMenuDialog.m_lbMenuentryType->text()) ); - item->setMenutype(type); - if (type == UserMenuData::Separator) { - return; - } + UserMenuData::MenuType type = UserMenuData::MenuType( m_listMenutypes.indexOf(m_UserMenuDialog.m_lbMenuentryType->text()) ); + item->setMenutype(type); + if (type == UserMenuData::Separator) { + return; + } - item->setMenutitle(m_UserMenuDialog.m_leMenuEntry->text().trimmed()); - item->setFilename(m_UserMenuDialog.m_urlRequester->text().trimmed()); - item->setParameter(m_UserMenuDialog.m_leParameter->text().trimmed()); - item->setPlaintext(m_UserMenuDialog.m_teText->toPlainText()); + item->setMenutitle(m_UserMenuDialog.m_leMenuEntry->text().trimmed()); + item->setFilename(m_UserMenuDialog.m_urlRequester->text().trimmed()); + item->setParameter(m_UserMenuDialog.m_leParameter->text().trimmed()); + item->setPlaintext(m_UserMenuDialog.m_teText->toPlainText()); - item->setMenuicon(m_currentIcon); - item->setShortcut(m_UserMenuDialog.m_keyChooser->keySequence().toString(QKeySequence::NativeText)); + item->setMenuicon(m_currentIcon); + item->setShortcut(m_UserMenuDialog.m_keyChooser->keySequence().toString(QKeySequence::NativeText)); - item->setNeedsSelection(m_UserMenuDialog.m_cbNeedsSelection->checkState()); - item->setUseContextMenu(m_UserMenuDialog.m_cbContextMenu->checkState()); - item->setReplaceSelection(m_UserMenuDialog.m_cbReplaceSelection->checkState()); - item->setSelectInsertion(m_UserMenuDialog.m_cbSelectInsertion->checkState()); - item->setInsertOutput(m_UserMenuDialog.m_cbInsertOutput->checkState()); + item->setNeedsSelection(m_UserMenuDialog.m_cbNeedsSelection->checkState()); + item->setUseContextMenu(m_UserMenuDialog.m_cbContextMenu->checkState()); + item->setReplaceSelection(m_UserMenuDialog.m_cbReplaceSelection->checkState()); + item->setSelectInsertion(m_UserMenuDialog.m_cbSelectInsertion->checkState()); + item->setInsertOutput(m_UserMenuDialog.m_cbInsertOutput->checkState()); - bool executable = (type==UserMenuData::Program && m_menutree->isItemExecutable(item->filename())); - item->setModelData(executable); + bool executable = (type==UserMenuData::Program && m_menutree->isItemExecutable(item->filename())); + item->setModelData(executable); - item->setText(0, item->updateMenutitle()); + item->setText(0, item->updateMenutitle()); } ////////////////////////////// show menu item data ////////////////////////////// void UserMenuDialog::showMenuentryData(UserMenuItem *item) { - KILE_DEBUG_MAIN << "show new menu item ..."; - if (!item) { - disableMenuEntryData(); - return; - } - - UserMenuData::MenuType type = item->menutype(); - - blockSignals(true); - switch (type) { - case UserMenuData::Text: setTextEntry(item); break; - case UserMenuData::FileContent: setFileContentEntry(item); break; - case UserMenuData::Program: setProgramEntry(item); break; - case UserMenuData::Separator: setSeparatorEntry(item); break; - case UserMenuData::Submenu: setSubmenuEntry(item); break; - default: disableMenuEntryData(); // should not happen - } - blockSignals(false); + KILE_DEBUG_MAIN << "show new menu item ..."; + if (!item) { + disableMenuEntryData(); + return; + } + + UserMenuData::MenuType type = item->menutype(); + + blockSignals(true); + switch (type) { + case UserMenuData::Text: + setTextEntry(item); + break; + case UserMenuData::FileContent: + setFileContentEntry(item); + break; + case UserMenuData::Program: + setProgramEntry(item); + break; + case UserMenuData::Separator: + setSeparatorEntry(item); + break; + case UserMenuData::Submenu: + setSubmenuEntry(item); + break; + default: + disableMenuEntryData(); // should not happen + } + blockSignals(false); } void UserMenuDialog::setTextEntry(UserMenuItem *item) { - setMenuentryText(item, true); - setMenuentryType(item, true, true); - setMenuentryFileChooser(item, false); - setMenuentryFileParameter(item, false); - setMenuentryTextEdit(item, true); - setMenuentryIcon(item, true); - setMenuentryShortcut(item, true); - setParameterGroupbox(true); - setMenuentryCheckboxes(item, false); + setMenuentryText(item, true); + setMenuentryType(item, true, true); + setMenuentryFileChooser(item, false); + setMenuentryFileParameter(item, false); + setMenuentryTextEdit(item, true); + setMenuentryIcon(item, true); + setMenuentryShortcut(item, true); + setParameterGroupbox(true); + setMenuentryCheckboxes(item, false); } void UserMenuDialog::setFileContentEntry(UserMenuItem *item) { - setMenuentryText(item, true); - setMenuentryType(item, true, true); - setMenuentryFileChooser(item, true); - setMenuentryFileParameter(item, false); - setMenuentryTextEdit(item, false); - setMenuentryIcon(item, true); - setMenuentryShortcut(item, true); - setParameterGroupbox(true); - setMenuentryCheckboxes(item, false); + setMenuentryText(item, true); + setMenuentryType(item, true, true); + setMenuentryFileChooser(item, true); + setMenuentryFileParameter(item, false); + setMenuentryTextEdit(item, false); + setMenuentryIcon(item, true); + setMenuentryShortcut(item, true); + setParameterGroupbox(true); + setMenuentryCheckboxes(item, false); } void UserMenuDialog::setProgramEntry(UserMenuItem *item) { - setMenuentryText(item, true); - setMenuentryType(item, true, true); - setMenuentryFileChooser(item, true); - setMenuentryFileParameter(item, true); - setMenuentryTextEdit(item, false); - setMenuentryIcon(item, true); - setMenuentryShortcut(item, true); - setParameterGroupbox(true); - setMenuentryCheckboxes(item, true); + setMenuentryText(item, true); + setMenuentryType(item, true, true); + setMenuentryFileChooser(item, true); + setMenuentryFileParameter(item, true); + setMenuentryTextEdit(item, false); + setMenuentryIcon(item, true); + setMenuentryShortcut(item, true); + setParameterGroupbox(true); + setMenuentryCheckboxes(item, true); } void UserMenuDialog::setSeparatorEntry(UserMenuItem *item) { - disableMenuEntryData(); - setMenuentryType(item, true, false); + disableMenuEntryData(); + setMenuentryType(item, true, false); } void UserMenuDialog::setSubmenuEntry(UserMenuItem *item) { - setMenuentryText(item, true); - setMenuentryType(item, true, false); - setMenuentryFileChooser(Q_NULLPTR, false); - setMenuentryFileParameter(Q_NULLPTR, false); - setMenuentryTextEdit(Q_NULLPTR, false); - setMenuentryIcon(Q_NULLPTR, false); - setMenuentryShortcut(Q_NULLPTR, false); - setParameterGroupbox(false); - setMenuentryCheckboxes(Q_NULLPTR, false); + setMenuentryText(item, true); + setMenuentryType(item, true, false); + setMenuentryFileChooser(Q_NULLPTR, false); + setMenuentryFileParameter(Q_NULLPTR, false); + setMenuentryTextEdit(Q_NULLPTR, false); + setMenuentryIcon(Q_NULLPTR, false); + setMenuentryShortcut(Q_NULLPTR, false); + setParameterGroupbox(false); + setMenuentryCheckboxes(Q_NULLPTR, false); } ////////////////////////////// update data widgets////////////////////////////// void UserMenuDialog::setMenuentryType(UserMenuItem *item, bool state1, bool state2) { - const QString s = (item && state1) ? m_listMenutypes[item->menutype()] : QString(); - m_UserMenuDialog.m_lbMenuentryType->setText(s); - m_UserMenuDialog.m_lbMenuentryType->setEnabled(state1); - m_UserMenuDialog.m_pbMenuentryType->setEnabled(state2); + const QString s = (item && state1) ? m_listMenutypes[item->menutype()] : QString(); + m_UserMenuDialog.m_lbMenuentryType->setText(s); + m_UserMenuDialog.m_lbMenuentryType->setEnabled(state1); + m_UserMenuDialog.m_pbMenuentryType->setEnabled(state2); } void UserMenuDialog::setMenuentryText(UserMenuItem *item, bool state) { - const QString s = (item && state) ? item->menutitle() : QString(); - m_UserMenuDialog.m_leMenuEntry->setText(s); + const QString s = (item && state) ? item->menutitle() : QString(); + m_UserMenuDialog.m_leMenuEntry->setText(s); - m_UserMenuDialog.m_lbMenuEntry->setEnabled(state); - m_UserMenuDialog.m_leMenuEntry->setEnabled(state); + m_UserMenuDialog.m_lbMenuEntry->setEnabled(state); + m_UserMenuDialog.m_leMenuEntry->setEnabled(state); } void UserMenuDialog::setMenuentryFileChooser(UserMenuItem *item, bool state) { - const QString s = (item && state) ? item->filename() : QString(); - m_UserMenuDialog.m_urlRequester->setText(s); + const QString s = (item && state) ? item->filename() : QString(); + m_UserMenuDialog.m_urlRequester->setText(s); - m_UserMenuDialog.m_lbFile->setEnabled(state); - m_UserMenuDialog.m_urlRequester->setEnabled(state); + m_UserMenuDialog.m_lbFile->setEnabled(state); + m_UserMenuDialog.m_urlRequester->setEnabled(state); } void UserMenuDialog::setMenuentryFileParameter(UserMenuItem *item, bool state) { - const QString s = (item && state) ? item->parameter() : QString(); - m_UserMenuDialog.m_leParameter->setText(s); + const QString s = (item && state) ? item->parameter() : QString(); + m_UserMenuDialog.m_leParameter->setText(s); - m_UserMenuDialog.m_lbParameter->setEnabled(state); - m_UserMenuDialog.m_leParameter->setEnabled(state); + m_UserMenuDialog.m_lbParameter->setEnabled(state); + m_UserMenuDialog.m_leParameter->setEnabled(state); } void UserMenuDialog::setMenuentryTextEdit(UserMenuItem *item, bool state) { - const QString s = (item && state) ? item->plaintext() : QString(); - m_UserMenuDialog.m_teText->setPlainText(s); + const QString s = (item && state) ? item->plaintext() : QString(); + m_UserMenuDialog.m_teText->setPlainText(s); - m_UserMenuDialog.m_lbText->setEnabled(state); - m_UserMenuDialog.m_teText->setEnabled(state); + m_UserMenuDialog.m_lbText->setEnabled(state); + m_UserMenuDialog.m_teText->setEnabled(state); } void UserMenuDialog::setMenuentryIcon(UserMenuItem *item, bool state, const QString &icon) { - if (item && state) { - m_currentIcon = (icon.isEmpty()) ? item->menuicon() : icon; - } - else { - m_currentIcon.clear(); - } - - // update widgets - if (m_currentIcon.isEmpty()) { - m_UserMenuDialog.m_lbIconChosen->setText(m_currentIcon); - m_UserMenuDialog.m_lbIconChosen->hide(); - m_UserMenuDialog.m_pbIcon->show(); - } - else { - QString iconpath = KIconLoader::global()->iconPath(m_currentIcon,KIconLoader::Small); - m_UserMenuDialog.m_lbIconChosen->setText(""); - m_UserMenuDialog.m_lbIconChosen->show(); - m_UserMenuDialog.m_pbIcon->hide(); - } - - m_UserMenuDialog.m_lbIcon->setEnabled(state); - m_UserMenuDialog.m_pbIcon->setEnabled(state); - m_UserMenuDialog.m_lbIconChosen->setEnabled(state); - bool deleteIconState = ( state && !m_currentIcon.isEmpty() ); - m_UserMenuDialog.m_pbIconDelete->setEnabled(deleteIconState); + if (item && state) { + m_currentIcon = (icon.isEmpty()) ? item->menuicon() : icon; + } + else { + m_currentIcon.clear(); + } + + // update widgets + if (m_currentIcon.isEmpty()) { + m_UserMenuDialog.m_lbIconChosen->setText(m_currentIcon); + m_UserMenuDialog.m_lbIconChosen->hide(); + m_UserMenuDialog.m_pbIcon->show(); + } + else { + QString iconpath = KIconLoader::global()->iconPath(m_currentIcon,KIconLoader::Small); + m_UserMenuDialog.m_lbIconChosen->setText(""); + m_UserMenuDialog.m_lbIconChosen->show(); + m_UserMenuDialog.m_pbIcon->hide(); + } + + m_UserMenuDialog.m_lbIcon->setEnabled(state); + m_UserMenuDialog.m_pbIcon->setEnabled(state); + m_UserMenuDialog.m_lbIconChosen->setEnabled(state); + bool deleteIconState = ( state && !m_currentIcon.isEmpty() ); + m_UserMenuDialog.m_pbIconDelete->setEnabled(deleteIconState); } void UserMenuDialog::setMenuentryShortcut(UserMenuItem *item, bool state) { - if (item && state) { - QString shortcut = item->shortcut(); - if (shortcut.isEmpty()) { - m_UserMenuDialog.m_keyChooser->clearKeySequence(); - } - else { - m_UserMenuDialog.m_keyChooser->setKeySequence(QKeySequence(shortcut)); - } - item->setText(1, shortcut); - } - else { - m_UserMenuDialog.m_keyChooser->clearKeySequence(); - } + if (item && state) { + QString shortcut = item->shortcut(); + if (shortcut.isEmpty()) { + m_UserMenuDialog.m_keyChooser->clearKeySequence(); + } + else { + m_UserMenuDialog.m_keyChooser->setKeySequence(QKeySequence(shortcut)); + } + item->setText(1, shortcut); + } + else { + m_UserMenuDialog.m_keyChooser->clearKeySequence(); + } - m_UserMenuDialog.m_lbShortcut->setEnabled(state); - m_UserMenuDialog.m_keyChooser->setEnabled(state); + m_UserMenuDialog.m_lbShortcut->setEnabled(state); + m_UserMenuDialog.m_keyChooser->setEnabled(state); } void UserMenuDialog::setParameterGroupbox(bool state) { - m_UserMenuDialog.m_gbParameter->setEnabled(state); + m_UserMenuDialog.m_gbParameter->setEnabled(state); } void UserMenuDialog::setMenuentryCheckboxes(UserMenuItem *item, bool useInsertOutput) { - bool selectionState, insertionState, outputState, replaceState, contextState; - if (item) { - selectionState = item->needsSelection(); - replaceState = (selectionState) ? item->replaceSelection() : false; - insertionState = item->selectInsertion(); - outputState = (useInsertOutput) ? item->insertOutput() : false; - contextState = (selectionState) ? item->useContextMenu() : false; - } - else { - selectionState = false; - replaceState = false; - insertionState = false; - outputState = false; - contextState = false; - } - - // m_cbNeedsSelection and m_cbSelectInsertion are always enabled - m_UserMenuDialog.m_cbNeedsSelection->setChecked(selectionState); - - // m_cbContextMenu and m_cbReplaceSelection need a selection to be enabled - m_UserMenuDialog.m_cbContextMenu->setEnabled(selectionState); - m_UserMenuDialog.m_cbReplaceSelection->setEnabled(selectionState); - - m_UserMenuDialog.m_cbContextMenu->setChecked(contextState); - m_UserMenuDialog.m_cbReplaceSelection->setChecked(replaceState); - m_UserMenuDialog.m_cbSelectInsertion->setChecked(insertionState); - m_UserMenuDialog.m_cbInsertOutput->setChecked(outputState); - m_UserMenuDialog.m_cbInsertOutput->setEnabled(useInsertOutput); + bool selectionState, insertionState, outputState, replaceState, contextState; + if (item) { + selectionState = item->needsSelection(); + replaceState = (selectionState) ? item->replaceSelection() : false; + insertionState = item->selectInsertion(); + outputState = (useInsertOutput) ? item->insertOutput() : false; + contextState = (selectionState) ? item->useContextMenu() : false; + } + else { + selectionState = false; + replaceState = false; + insertionState = false; + outputState = false; + contextState = false; + } + + // m_cbNeedsSelection and m_cbSelectInsertion are always enabled + m_UserMenuDialog.m_cbNeedsSelection->setChecked(selectionState); + + // m_cbContextMenu and m_cbReplaceSelection need a selection to be enabled + m_UserMenuDialog.m_cbContextMenu->setEnabled(selectionState); + m_UserMenuDialog.m_cbReplaceSelection->setEnabled(selectionState); + + m_UserMenuDialog.m_cbContextMenu->setChecked(contextState); + m_UserMenuDialog.m_cbReplaceSelection->setChecked(replaceState); + m_UserMenuDialog.m_cbSelectInsertion->setChecked(insertionState); + m_UserMenuDialog.m_cbInsertOutput->setChecked(outputState); + m_UserMenuDialog.m_cbInsertOutput->setEnabled(useInsertOutput); } void UserMenuDialog::clearMenuEntryData() { - m_UserMenuDialog.m_leMenuEntry->clear(); - m_UserMenuDialog.m_lbMenuentryType->clear(); - m_UserMenuDialog.m_urlRequester->clear(); - m_UserMenuDialog.m_teText->clear(); - m_UserMenuDialog.m_pbIcon->setIcon(QIcon::fromTheme(i18n("Choose"))); - m_UserMenuDialog.m_keyChooser->clearKeySequence(); + m_UserMenuDialog.m_leMenuEntry->clear(); + m_UserMenuDialog.m_lbMenuentryType->clear(); + m_UserMenuDialog.m_urlRequester->clear(); + m_UserMenuDialog.m_teText->clear(); + m_UserMenuDialog.m_pbIcon->setIcon(QIcon::fromTheme(i18n("Choose"))); + m_UserMenuDialog.m_keyChooser->clearKeySequence(); - m_UserMenuDialog.m_cbNeedsSelection->setChecked(false); - m_UserMenuDialog.m_cbReplaceSelection->setChecked(false); - m_UserMenuDialog.m_cbContextMenu->setChecked(false); - m_UserMenuDialog.m_cbSelectInsertion->setChecked(false); - m_UserMenuDialog.m_cbInsertOutput->setChecked(false); + m_UserMenuDialog.m_cbNeedsSelection->setChecked(false); + m_UserMenuDialog.m_cbReplaceSelection->setChecked(false); + m_UserMenuDialog.m_cbContextMenu->setChecked(false); + m_UserMenuDialog.m_cbSelectInsertion->setChecked(false); + m_UserMenuDialog.m_cbInsertOutput->setChecked(false); } void UserMenuDialog::disableMenuEntryData() { - setMenuentryText(Q_NULLPTR, false); - setMenuentryType(Q_NULLPTR, false, false); - setMenuentryFileChooser(Q_NULLPTR, false); - setMenuentryFileParameter(Q_NULLPTR, false); - setMenuentryTextEdit(Q_NULLPTR, false); - setMenuentryIcon(Q_NULLPTR, false); - setMenuentryShortcut(Q_NULLPTR, false); - setParameterGroupbox(false); - setMenuentryCheckboxes(Q_NULLPTR, false); + setMenuentryText(Q_NULLPTR, false); + setMenuentryType(Q_NULLPTR, false, false); + setMenuentryFileChooser(Q_NULLPTR, false); + setMenuentryFileParameter(Q_NULLPTR, false); + setMenuentryTextEdit(Q_NULLPTR, false); + setMenuentryIcon(Q_NULLPTR, false); + setMenuentryShortcut(Q_NULLPTR, false); + setParameterGroupbox(false); + setMenuentryCheckboxes(Q_NULLPTR, false); } } diff --git a/src/dialogs/usermenu/usermenudialog.h b/src/dialogs/usermenu/usermenudialog.h index ee6ed04c..ab9e9817 100644 --- a/src/dialogs/usermenu/usermenudialog.h +++ b/src/dialogs/usermenu/usermenudialog.h @@ -1,123 +1,123 @@ /*********************************************************************************** Copyright (C) 2011-2012 by Holger Danielsson (holger.danielsson@versanet.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. * * * ***************************************************************************/ #ifndef LATEXMENUDIALOG_H #define LATEXMENUDIALOG_H #include #include #include "kilewizard.h" #include "kileinfo.h" #include "dialogs/usermenu/usermenuitem.h" #include "ui_usermenudialog_base.h" namespace KileMenu { class UserMenu; class UserMenuDialog : public KileDialog::Wizard { - Q_OBJECT - - public: - UserMenuDialog(KConfig *config, KileInfo *ki, KileMenu::UserMenu *userMenu, const QString &xmlfile, QWidget *parent); - ~UserMenuDialog() {} - - private Q_SLOTS: - void slotCurrentItemChanged(QTreeWidgetItem *current,QTreeWidgetItem *previous); - void slotInsertMenuItem(); - void slotInsertSubmenu(); - void slotInsertSeparator(); - void slotDelete(); - void slotUp(); - void slotDown(); - - void slotMenuentryTypeClicked(); - void slotMenuentryTextChanged(const QString &text); - void slotUrlTextChanged(const QString &text); - void slotIconClicked(); - void slotIconDeleteClicked(); - void slotKeySequenceChanged(const QKeySequence &seq); - - void slotSelectionStateChanged(int state); - void slotCheckboxStateChanged(int); - - void slotNewClicked(); - void slotInstallClicked(); - void slotLoadClicked(); - void slotSaveClicked(); - void slotSaveAsClicked(); - void slotShowHelp(); - - void slotCustomContextMenuRequested(const QPoint &pos); - - private: - Ui::UserMenuDialog m_UserMenuDialog; - UserMenuTree *m_menutree; - - KileInfo *m_ki; - KileMenu::UserMenu *m_userMenu; - - bool m_modified; - bool m_currentXmlInstalled; - QString m_currentXmlFile; - void setXmlFile(const QString &filename, bool installed); - - QString m_currentIcon; - QStringList m_listMenutypes; - - void startDialog(); - void initDialog(); - void setModified(); - - bool saveClicked(); - QString saveAsClicked(); - - void readMenuentryData(UserMenuItem *tem); - void showMenuentryData(UserMenuItem *item); - void clearMenuEntryData(); - void disableMenuEntryData(); - - void setTextEntry(UserMenuItem *item); - void setFileContentEntry(UserMenuItem *item); - void setProgramEntry(UserMenuItem *item); - void setSeparatorEntry(UserMenuItem *item); - void setSubmenuEntry(UserMenuItem *item); - - void setMenuentryText(UserMenuItem *item, bool state); - void setMenuentryType(UserMenuItem *item, bool state1, bool state2); - void setMenuentryFileChooser(UserMenuItem *item, bool state); - void setMenuentryFileParameter(UserMenuItem *item, bool state); - void setMenuentryTextEdit(UserMenuItem *item, bool state); - void setMenuentryIcon(UserMenuItem *item, bool state, const QString &icon = QString()); - void setMenuentryShortcut(UserMenuItem *item, bool state); - - void setParameterGroupbox(bool state); - void setMenuentryCheckboxes(UserMenuItem *item, bool useInsertOutput); - - void setMenuentryIcon(const QString &icon); - void updateTreeButtons(); - void updateDialogButtons(); - void updateAfterDelete(); - - void loadXmlFile(const QString &filename, bool installed); - bool saveCheck(); + Q_OBJECT + +public: + UserMenuDialog(KConfig *config, KileInfo *ki, KileMenu::UserMenu *userMenu, const QString &xmlfile, QWidget *parent); + ~UserMenuDialog() {} + +private Q_SLOTS: + void slotCurrentItemChanged(QTreeWidgetItem *current,QTreeWidgetItem *previous); + void slotInsertMenuItem(); + void slotInsertSubmenu(); + void slotInsertSeparator(); + void slotDelete(); + void slotUp(); + void slotDown(); + + void slotMenuentryTypeClicked(); + void slotMenuentryTextChanged(const QString &text); + void slotUrlTextChanged(const QString &text); + void slotIconClicked(); + void slotIconDeleteClicked(); + void slotKeySequenceChanged(const QKeySequence &seq); + + void slotSelectionStateChanged(int state); + void slotCheckboxStateChanged(int); + + void slotNewClicked(); + void slotInstallClicked(); + void slotLoadClicked(); + void slotSaveClicked(); + void slotSaveAsClicked(); + void slotShowHelp(); + + void slotCustomContextMenuRequested(const QPoint &pos); + +private: + Ui::UserMenuDialog m_UserMenuDialog; + UserMenuTree *m_menutree; + + KileInfo *m_ki; + KileMenu::UserMenu *m_userMenu; + + bool m_modified; + bool m_currentXmlInstalled; + QString m_currentXmlFile; + void setXmlFile(const QString &filename, bool installed); + + QString m_currentIcon; + QStringList m_listMenutypes; + + void startDialog(); + void initDialog(); + void setModified(); + + bool saveClicked(); + QString saveAsClicked(); + + void readMenuentryData(UserMenuItem *tem); + void showMenuentryData(UserMenuItem *item); + void clearMenuEntryData(); + void disableMenuEntryData(); + + void setTextEntry(UserMenuItem *item); + void setFileContentEntry(UserMenuItem *item); + void setProgramEntry(UserMenuItem *item); + void setSeparatorEntry(UserMenuItem *item); + void setSubmenuEntry(UserMenuItem *item); + + void setMenuentryText(UserMenuItem *item, bool state); + void setMenuentryType(UserMenuItem *item, bool state1, bool state2); + void setMenuentryFileChooser(UserMenuItem *item, bool state); + void setMenuentryFileParameter(UserMenuItem *item, bool state); + void setMenuentryTextEdit(UserMenuItem *item, bool state); + void setMenuentryIcon(UserMenuItem *item, bool state, const QString &icon = QString()); + void setMenuentryShortcut(UserMenuItem *item, bool state); + + void setParameterGroupbox(bool state); + void setMenuentryCheckboxes(UserMenuItem *item, bool useInsertOutput); + + void setMenuentryIcon(const QString &icon); + void updateTreeButtons(); + void updateDialogButtons(); + void updateAfterDelete(); + + void loadXmlFile(const QString &filename, bool installed); + bool saveCheck(); }; } #endif diff --git a/src/dialogs/usermenu/usermenuitem.cpp b/src/dialogs/usermenu/usermenuitem.cpp index aeebdc7c..76e17245 100644 --- a/src/dialogs/usermenu/usermenuitem.cpp +++ b/src/dialogs/usermenu/usermenuitem.cpp @@ -1,105 +1,105 @@ /*********************************************************************************** Copyright (C) 2011-2012 by Holger Danielsson (holger.danielsson@versanet.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. * * * ***************************************************************************/ #include #include #include "dialogs/usermenu/usermenuitem.h" namespace KileMenu { UserMenuItem::UserMenuItem(UserMenuData::MenuType type, const QString &menutitle) - : QTreeWidgetItem() + : QTreeWidgetItem() { - initItem(type,menutitle); + initItem(type,menutitle); } UserMenuItem::UserMenuItem( QTreeWidget *parent, QTreeWidgetItem *preceding, UserMenuData::MenuType type, const QString &menutitle) - : QTreeWidgetItem(parent,preceding) + : QTreeWidgetItem(parent,preceding) { - initItem(type,menutitle); + initItem(type,menutitle); } UserMenuItem::UserMenuItem( QTreeWidgetItem *parent, QTreeWidgetItem *preceding, UserMenuData::MenuType type, const QString &menutitle) - : QTreeWidgetItem(parent,preceding) + : QTreeWidgetItem(parent,preceding) { - initItem(type,menutitle); + initItem(type,menutitle); } void UserMenuItem::initItem(UserMenuData::MenuType type, const QString &menutitle) { - clear(); - setText(0,menutitle); + clear(); + setText(0,menutitle); - m_data.menutitle = menutitle; - m_data.menutype = type; + m_data.menutitle = menutitle; + m_data.menutype = type; - setData(0, Qt::UserRole+1, UserMenuData::xmlMenuTypeName(type)); - setData(0, Qt::UserRole+2, MODEL_ERROR_NONE); + setData(0, Qt::UserRole+1, UserMenuData::xmlMenuTypeName(type)); + setData(0, Qt::UserRole+2, MODEL_ERROR_NONE); } // check for possible errors and save for use with model data void UserMenuItem::setModelData(bool executable) { - int modelerror = MODEL_ERROR_NONE; - - if ( m_data.menutitle.isEmpty() && m_data.menutype!=UserMenuData::Separator ) { - modelerror |= UserMenuItem::MODEL_ERROR_EMPTY; - } - - if ( m_data.menutype==UserMenuData::Submenu && childCount()==0 ) { - modelerror |= UserMenuItem::MODEL_ERROR_SUBMENU; - } - else if ( m_data.menutype==UserMenuData::Text && m_data.text.isEmpty() ) { - modelerror |= UserMenuItem::MODEL_ERROR_TEXT; - } - else if ( m_data.menutype == UserMenuData::FileContent ) { - if ( m_data.filename.isEmpty() ) { - modelerror |= UserMenuItem::MODEL_ERROR_FILE_EMPTY; - } - else if ( !QFile::exists(m_data.filename) ) { - modelerror |= UserMenuItem::MODEL_ERROR_FILE_EXIST; - } - } - else if ( m_data.menutype == UserMenuData::Program && !executable ) { - modelerror |= UserMenuItem::MODEL_ERROR_FILE_EXECUTABLE; - } - - setData(0,Qt::UserRole+2,modelerror); + int modelerror = MODEL_ERROR_NONE; + + if ( m_data.menutitle.isEmpty() && m_data.menutype!=UserMenuData::Separator ) { + modelerror |= UserMenuItem::MODEL_ERROR_EMPTY; + } + + if ( m_data.menutype==UserMenuData::Submenu && childCount()==0 ) { + modelerror |= UserMenuItem::MODEL_ERROR_SUBMENU; + } + else if ( m_data.menutype==UserMenuData::Text && m_data.text.isEmpty() ) { + modelerror |= UserMenuItem::MODEL_ERROR_TEXT; + } + else if ( m_data.menutype == UserMenuData::FileContent ) { + if ( m_data.filename.isEmpty() ) { + modelerror |= UserMenuItem::MODEL_ERROR_FILE_EMPTY; + } + else if ( !QFile::exists(m_data.filename) ) { + modelerror |= UserMenuItem::MODEL_ERROR_FILE_EXIST; + } + } + else if ( m_data.menutype == UserMenuData::Program && !executable ) { + modelerror |= UserMenuItem::MODEL_ERROR_FILE_EXECUTABLE; + } + + setData(0,Qt::UserRole+2,modelerror); } // two possible errors in the menutree are made visible for the user // - if no menutitle is given, it is changed to '???' // - if a (useless) submenu with no children is given, the menutitle 'title' is changed to 'title >' QString UserMenuItem::updateMenutitle() { - QString menutitle = m_data.menutitle; - if ( menutitle.isEmpty() ) { - menutitle = EMPTY_MENUENTRY; - } - else if ( m_data.menutype==UserMenuData::Submenu && childCount()==0 ) { - menutitle += EMPTY_SUBMENU; - } - return menutitle; + QString menutitle = m_data.menutitle; + if ( menutitle.isEmpty() ) { + menutitle = EMPTY_MENUENTRY; + } + else if ( m_data.menutype==UserMenuData::Submenu && childCount()==0 ) { + menutitle += EMPTY_SUBMENU; + } + return menutitle; } void UserMenuItem::clear() { - m_data.clear(); + m_data.clear(); } } diff --git a/src/dialogs/usermenu/usermenuitem.h b/src/dialogs/usermenu/usermenuitem.h index 3c6cccce..89f1427c 100644 --- a/src/dialogs/usermenu/usermenuitem.h +++ b/src/dialogs/usermenu/usermenuitem.h @@ -1,106 +1,154 @@ /*********************************************************************************** Copyright (C) 2011-2012 by Holger Danielsson (holger.danielsson@versanet.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. * * * ***************************************************************************/ #ifndef LATEXMENUITEM_H #define LATEXMENUITEM_H #include #include #include #include #include #include "usermenu/usermenudata.h" #define EMPTY_MENUENTRY i18n("???") #define EMPTY_SUBMENU i18n(" >") #define LENGTH_SUBSTITUTE 3 namespace KileMenu { ////////////////////////////// UserMenuItem ////////////////////////////// class UserMenuItem : public QTreeWidgetItem { - public: - - UserMenuItem(UserMenuData::MenuType type, const QString &menutitle = QString()); - UserMenuItem(QTreeWidget *parent, QTreeWidgetItem *preceding, - UserMenuData::MenuType type, const QString &menutitle = QString()); - UserMenuItem(QTreeWidgetItem *parent, QTreeWidgetItem *preceding, - UserMenuData::MenuType type, const QString &menutitle = QString()); - - virtual ~UserMenuItem() {} - - enum ModelUserError { MODEL_ERROR_NONE=0x00, - MODEL_ERROR_EMPTY=0x01, - MODEL_ERROR_SUBMENU=0x02, - MODEL_ERROR_TEXT=0x04, - MODEL_ERROR_FILE_EMPTY=0x08, - MODEL_ERROR_FILE_EXIST=0x10, - MODEL_ERROR_FILE_EXECUTABLE=0x20, - }; - - void setModelData(bool executable=false); - QString updateMenutitle(); - - void setMenutype(UserMenuData::MenuType type) { m_data.menutype = type; } - UserMenuData::MenuType menutype() { return m_data.menutype; } - - void setMenutitle(const QString &s) { m_data.menutitle = s; } - const QString &menutitle() { return m_data.menutitle; } - - void setMenuicon(const QString &icon) { m_data.icon = icon; } - QString menuicon() { return m_data.icon; } - - void setFilename(const QString &filename) { m_data.filename = filename; } - const QString &filename() { return m_data.filename; } - - void setParameter(const QString ¶meter) { m_data.parameter = parameter; } - const QString ¶meter() { return m_data.parameter; } - - void setPlaintext(const QString &text) { m_data.text = text; } - const QString &plaintext() { return m_data.text; } - - void setShortcut(const QString &shortcut) { m_data.shortcut = shortcut; } - QString shortcut() { return m_data.shortcut; } - - // checkboxes - void setNeedsSelection(bool state) { m_data.needsSelection = state; } - bool needsSelection() { return m_data.needsSelection; } - - void setUseContextMenu(bool state) { m_data.useContextMenu = state; } - bool useContextMenu() { return m_data.useContextMenu; } - - void setReplaceSelection(bool state) { m_data.replaceSelection = state; } - bool replaceSelection() { return m_data.replaceSelection; } - - void setSelectInsertion(bool state) { m_data.selectInsertion = state; } - bool selectInsertion() { return m_data.selectInsertion; } - - void setInsertOutput(bool state) { m_data.insertOutput = state; } - bool insertOutput() { return m_data.insertOutput; } - - private: - UserMenuData m_data; - - void clear(); - void initItem(UserMenuData::MenuType type, const QString &menutitle); +public: + + UserMenuItem(UserMenuData::MenuType type, const QString &menutitle = QString()); + UserMenuItem(QTreeWidget *parent, QTreeWidgetItem *preceding, + UserMenuData::MenuType type, const QString &menutitle = QString()); + UserMenuItem(QTreeWidgetItem *parent, QTreeWidgetItem *preceding, + UserMenuData::MenuType type, const QString &menutitle = QString()); + + virtual ~UserMenuItem() {} + + enum ModelUserError { MODEL_ERROR_NONE=0x00, + MODEL_ERROR_EMPTY=0x01, + MODEL_ERROR_SUBMENU=0x02, + MODEL_ERROR_TEXT=0x04, + MODEL_ERROR_FILE_EMPTY=0x08, + MODEL_ERROR_FILE_EXIST=0x10, + MODEL_ERROR_FILE_EXECUTABLE=0x20, + }; + + void setModelData(bool executable=false); + QString updateMenutitle(); + + void setMenutype(UserMenuData::MenuType type) { + m_data.menutype = type; + } + UserMenuData::MenuType menutype() { + return m_data.menutype; + } + + void setMenutitle(const QString &s) { + m_data.menutitle = s; + } + const QString &menutitle() { + return m_data.menutitle; + } + + void setMenuicon(const QString &icon) { + m_data.icon = icon; + } + QString menuicon() { + return m_data.icon; + } + + void setFilename(const QString &filename) { + m_data.filename = filename; + } + const QString &filename() { + return m_data.filename; + } + + void setParameter(const QString ¶meter) { + m_data.parameter = parameter; + } + const QString ¶meter() { + return m_data.parameter; + } + + void setPlaintext(const QString &text) { + m_data.text = text; + } + const QString &plaintext() { + return m_data.text; + } + + void setShortcut(const QString &shortcut) { + m_data.shortcut = shortcut; + } + QString shortcut() { + return m_data.shortcut; + } + + // checkboxes + void setNeedsSelection(bool state) { + m_data.needsSelection = state; + } + bool needsSelection() { + return m_data.needsSelection; + } + + void setUseContextMenu(bool state) { + m_data.useContextMenu = state; + } + bool useContextMenu() { + return m_data.useContextMenu; + } + + void setReplaceSelection(bool state) { + m_data.replaceSelection = state; + } + bool replaceSelection() { + return m_data.replaceSelection; + } + + void setSelectInsertion(bool state) { + m_data.selectInsertion = state; + } + bool selectInsertion() { + return m_data.selectInsertion; + } + + void setInsertOutput(bool state) { + m_data.insertOutput = state; + } + bool insertOutput() { + return m_data.insertOutput; + } + +private: + UserMenuData m_data; + + void clear(); + void initItem(UserMenuData::MenuType type, const QString &menutitle); }; } #endif diff --git a/src/dialogs/usermenu/usermenutree.cpp b/src/dialogs/usermenu/usermenutree.cpp index baa271aa..59619a82 100644 --- a/src/dialogs/usermenu/usermenutree.cpp +++ b/src/dialogs/usermenu/usermenutree.cpp @@ -1,1050 +1,1110 @@ /*********************************************************************************** Copyright (C) 2011-2012 by Holger Danielsson (holger.danielsson@versanet.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. * * * ***************************************************************************/ #include #include #include #include #include #include #include #include #include #include #include #include #include "dialogs/usermenu/usermenuitem.h" #include "dialogs/usermenu/usermenutree.h" #include "kiledebug.h" // Qt::UserRole+1: menutype // Qt::UserRole+2: errorcode for menu item namespace KileMenu { // - Separators are shown as a horizontal line (Qt:UserRole+1) // - Menu items with errors are displayed in red (Qt:UserRole+2) void MenuentryDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex& index) const { - QString menutitle = index.data(Qt::DisplayRole).toString(); - int error = index.data(Qt::UserRole+2).toInt(); - - // any errors? - if (index.column()==0 && error!=UserMenuItem::MODEL_ERROR_NONE ) { - QStyleOptionViewItem optionCustom = option; - optionCustom.palette.setColor(QPalette::Text, Qt::red); - QStyledItemDelegate::paint( painter, optionCustom, index ); - } - else { - QStyledItemDelegate::paint( painter, option, index ); - } - - // display separators - QString itemtype = index.data(Qt::UserRole+1).toString(); - if ( itemtype == "separator" ) { - QRect r = option.rect; - int y = ( r.bottom() + r.top() ) / 2; - - painter->save(); - QPen pen = QPen(Qt::gray); - painter->setPen(pen); - painter->drawLine(r.left()+3,y, r.right()-20,y); - painter->restore(); - } + QString menutitle = index.data(Qt::DisplayRole).toString(); + int error = index.data(Qt::UserRole+2).toInt(); + + // any errors? + if (index.column()==0 && error!=UserMenuItem::MODEL_ERROR_NONE ) { + QStyleOptionViewItem optionCustom = option; + optionCustom.palette.setColor(QPalette::Text, Qt::red); + QStyledItemDelegate::paint( painter, optionCustom, index ); + } + else { + QStyledItemDelegate::paint( painter, option, index ); + } + + // display separators + QString itemtype = index.data(Qt::UserRole+1).toString(); + if ( itemtype == "separator" ) { + QRect r = option.rect; + int y = ( r.bottom() + r.top() ) / 2; + + painter->save(); + QPen pen = QPen(Qt::gray); + painter->setPen(pen); + painter->drawLine(r.left()+3,y, r.right()-20,y); + painter->restore(); + } } ///////////////////////////// UserMenuTree ////////////////////////////// UserMenuTree::UserMenuTree(QWidget *parent) - : QTreeWidget(parent) + : QTreeWidget(parent) { - setColumnCount(2); - - header()->setSectionResizeMode(0, QHeaderView::Stretch); - header()->setSectionResizeMode(1, QHeaderView::Fixed); - header()->setSectionsMovable(false); - header()->setStretchLastSection(false); - setColumnWidth(1,140); - setItemDelegateForColumn(0, new MenuentryDelegate(parent)); - - // drag and drop - setDragEnabled(true); - setDropIndicatorShown(true); - //setAcceptDrops(true); - setDragDropMode(QAbstractItemView::InternalMove); - setDragDropOverwriteMode(false); - - initEnvPathlist(); + setColumnCount(2); + + header()->setSectionResizeMode(0, QHeaderView::Stretch); + header()->setSectionResizeMode(1, QHeaderView::Fixed); + header()->setSectionsMovable(false); + header()->setStretchLastSection(false); + setColumnWidth(1,140); + setItemDelegateForColumn(0, new MenuentryDelegate(parent)); + + // drag and drop + setDragEnabled(true); + setDropIndicatorShown(true); + //setAcceptDrops(true); + setDragDropMode(QAbstractItemView::InternalMove); + setDragDropOverwriteMode(false); + + initEnvPathlist(); } bool UserMenuTree::isEmpty() { - return ( topLevelItemCount() == 0 ); + return ( topLevelItemCount() == 0 ); } ///////////////////////////// PATH environment variable ////////////////////////////// // save PATH to search for executable files void UserMenuTree::initEnvPathlist() { - QString envpath; + QString envpath; #if QT_VERSION >= 0x040600 - QProcessEnvironment env = QProcessEnvironment::systemEnvironment(); - if ( env.contains("PATH") ) { - envpath = env.value("PATH"); - } + QProcessEnvironment env = QProcessEnvironment::systemEnvironment(); + if ( env.contains("PATH") ) { + envpath = env.value("PATH"); + } #else - // Returns the environment of the calling process as a list of key=value pairs. - QStringList environment = QProcess::systemEnvironment(); - foreach ( const QString &s, environment ) { - if ( s.startsWith("PATH=") ) { - envpath = s.mid(5); - break; - } - } + // Returns the environment of the calling process as a list of key=value pairs. + QStringList environment = QProcess::systemEnvironment(); + foreach ( const QString &s, environment ) { + if ( s.startsWith("PATH=") ) { + envpath = s.mid(5); + break; + } + } #endif #ifdef Q_WS_WIN - m_envPathlist = envpath.split(';'); + m_envPathlist = envpath.split(';'); #else - m_envPathlist = envpath.split(':'); + m_envPathlist = envpath.split(':'); #endif - m_envPathlist.append("."); + m_envPathlist.append("."); } bool UserMenuTree::isItemExecutable(const QString &filename) { - if ( filename.isEmpty() ) { - return false; - } - - // absolute paths can be checked immediately - QFileInfo fi(filename); - if ( fi.isAbsolute() ) { - return fi.isExecutable(); - } - - // search in all paths - for (int i=0; i 0 ) { - QString temp = m_envPathlist[0]; - m_envPathlist[0] = m_envPathlist[i]; - m_envPathlist[i] = temp; - } - return true; - } - } - - return false; + if ( filename.isEmpty() ) { + return false; + } + + // absolute paths can be checked immediately + QFileInfo fi(filename); + if ( fi.isAbsolute() ) { + return fi.isExecutable(); + } + + // search in all paths + for (int i=0; i 0 ) { + QString temp = m_envPathlist[0]; + m_envPathlist[0] = m_envPathlist[i]; + m_envPathlist[i] = temp; + } + return true; + } + } + + return false; } ///////////////////////////// context menu event ////////////////////////////// // build a context menu void UserMenuTree::contextMenuRequested(const QPoint &pos) { - KILE_DEBUG_MAIN << "context menu requested ..." ; - - m_popupItem = dynamic_cast(itemAt(pos)); - if ( !m_popupItem ) { - KILE_DEBUG_MAIN << "... no item found"; - return; - } - - KILE_DEBUG_MAIN << "... popup item found: " << m_popupItem->text(0); - bool submenu = ( m_popupItem->menutype() == UserMenuData::Submenu ); - bool separator = ( m_popupItem->menutype() == UserMenuData::Separator ); - - QMenu popup; - QAction *action = Q_NULLPTR; - QSignalMapper signalMapper; - connect(&signalMapper, SIGNAL(mapped(int)), this, SLOT(slotPopupActivated(int))); - - // insert standard menu items - action = popup.addAction(QIcon::fromTheme("usermenu-insert-above.png"),i18n("Insert above"), &signalMapper, SLOT(map())); - signalMapper.setMapping(action, POPUP_INSERT_ABOVE); - action = popup.addAction(QIcon::fromTheme("usermenu-insert-below.png"),i18n("Insert below"), &signalMapper, SLOT(map())); - signalMapper.setMapping(action, POPUP_INSERT_BELOW); - popup.addSeparator(); - - // insert separators - if ( !separator ) { - action = popup.addAction(QIcon::fromTheme("usermenu-separator-above.png"),i18n("Insert a separator above"), &signalMapper, SLOT(map())); - signalMapper.setMapping(action, POPUP_SEPARATOR_ABOVE); - action = popup.addAction(QIcon::fromTheme("usermenu-separator-below.png"),i18n("Insert a separator below"), &signalMapper, SLOT(map())); - signalMapper.setMapping(action, POPUP_SEPARATOR_BELOW); - popup.addSeparator(); - } - - // insert submenus - action = popup.addAction(QIcon::fromTheme("usermenu-submenu-above.png"),i18n("Insert a submenu above"), &signalMapper, SLOT(map())); - signalMapper.setMapping(action, POPUP_SUBMENU_ABOVE); - action = popup.addAction(QIcon::fromTheme("usermenu-submenu-below.png"),i18n("Insert a submenu below"), &signalMapper, SLOT(map())); - signalMapper.setMapping(action, POPUP_SUBMENU_BELOW); - popup.addSeparator(); - - // insert into submenus - if ( submenu ) { - action = popup.addAction(QIcon::fromTheme("usermenu-into-submenu.png"),i18n("Insert into this submenu"), &signalMapper, SLOT(map())); - signalMapper.setMapping(action, POPUP_INTO_SUBMENU); - action = popup.addAction(i18n("Insert a separator into this submenu"), &signalMapper, SLOT(map())); - signalMapper.setMapping(action, POPUP_SEPARATOR_INTO_SUBMENU); - action = popup.addAction(i18n("Insert a submenu into this submenu"), &signalMapper, SLOT(map())); - signalMapper.setMapping(action, POPUP_SUBMENU_INTO_SUBMENU); - popup.addSeparator(); - } - - // delete actions - action = popup.addAction(QIcon::fromTheme("usermenu-delete.png"),i18n("Delete this item"), &signalMapper, SLOT(map())); - signalMapper.setMapping(action,POPUP_DELETE_ITEM); - popup.addSeparator(); - action = popup.addAction(QIcon::fromTheme("usermenu-clear.png"),i18n("Delete the complete tree"), &signalMapper, SLOT(map())); - signalMapper.setMapping(action, POPUP_DELETE_TREE); - - // expand/collapse tree - if ( submenu ) { - popup.addSeparator(); - if ( m_popupItem->isExpanded() ) { - action = popup.addAction(i18n("Collapse submenu"), &signalMapper, SLOT(map())); - signalMapper.setMapping(action,POPUP_COLLAPSE_ITEM); - } - else { - action = popup.addAction(i18n("Expand submenu"), &signalMapper, SLOT(map())); - signalMapper.setMapping(action,POPUP_EXPAND_ITEM); - } - popup.addSeparator(); - action = popup.addAction(i18n("Collapse complete tree"), &signalMapper, SLOT(map())); - signalMapper.setMapping(action,POPUP_COLLAPSE_TREE); - action = popup.addAction(i18n("Expand complete tree"), &signalMapper, SLOT(map())); - signalMapper.setMapping(action,POPUP_EXPAND_TREE); - } - - // if there are any errors with this item, some info is available - int error = m_popupItem->data(0,Qt::UserRole+2).toInt(); - if ( error != UserMenuItem::MODEL_ERROR_NONE ) { - popup.addSeparator(); - action = popup.addAction(QIcon::fromTheme("help-about.png"),i18n("Info"), &signalMapper, SLOT(map())); - signalMapper.setMapping(action, POPUP_ITEM_INFO); - } - - // const QPoint& pos parameter in the customContextMenuRequested() signal is normally in widget coordinates. - // But classes like QTreeWidget, which inherit from QAbstractScrollArea1 instead use the coordinates of their viewport() - if ( !popup.isEmpty() ) { - popup.exec( viewport()->mapToGlobal(pos) ); - } + KILE_DEBUG_MAIN << "context menu requested ..." ; + + m_popupItem = dynamic_cast(itemAt(pos)); + if ( !m_popupItem ) { + KILE_DEBUG_MAIN << "... no item found"; + return; + } + + KILE_DEBUG_MAIN << "... popup item found: " << m_popupItem->text(0); + bool submenu = ( m_popupItem->menutype() == UserMenuData::Submenu ); + bool separator = ( m_popupItem->menutype() == UserMenuData::Separator ); + + QMenu popup; + QAction *action = Q_NULLPTR; + QSignalMapper signalMapper; + connect(&signalMapper, SIGNAL(mapped(int)), this, SLOT(slotPopupActivated(int))); + + // insert standard menu items + action = popup.addAction(QIcon::fromTheme("usermenu-insert-above.png"),i18n("Insert above"), &signalMapper, SLOT(map())); + signalMapper.setMapping(action, POPUP_INSERT_ABOVE); + action = popup.addAction(QIcon::fromTheme("usermenu-insert-below.png"),i18n("Insert below"), &signalMapper, SLOT(map())); + signalMapper.setMapping(action, POPUP_INSERT_BELOW); + popup.addSeparator(); + + // insert separators + if ( !separator ) { + action = popup.addAction(QIcon::fromTheme("usermenu-separator-above.png"),i18n("Insert a separator above"), &signalMapper, SLOT(map())); + signalMapper.setMapping(action, POPUP_SEPARATOR_ABOVE); + action = popup.addAction(QIcon::fromTheme("usermenu-separator-below.png"),i18n("Insert a separator below"), &signalMapper, SLOT(map())); + signalMapper.setMapping(action, POPUP_SEPARATOR_BELOW); + popup.addSeparator(); + } + + // insert submenus + action = popup.addAction(QIcon::fromTheme("usermenu-submenu-above.png"),i18n("Insert a submenu above"), &signalMapper, SLOT(map())); + signalMapper.setMapping(action, POPUP_SUBMENU_ABOVE); + action = popup.addAction(QIcon::fromTheme("usermenu-submenu-below.png"),i18n("Insert a submenu below"), &signalMapper, SLOT(map())); + signalMapper.setMapping(action, POPUP_SUBMENU_BELOW); + popup.addSeparator(); + + // insert into submenus + if ( submenu ) { + action = popup.addAction(QIcon::fromTheme("usermenu-into-submenu.png"),i18n("Insert into this submenu"), &signalMapper, SLOT(map())); + signalMapper.setMapping(action, POPUP_INTO_SUBMENU); + action = popup.addAction(i18n("Insert a separator into this submenu"), &signalMapper, SLOT(map())); + signalMapper.setMapping(action, POPUP_SEPARATOR_INTO_SUBMENU); + action = popup.addAction(i18n("Insert a submenu into this submenu"), &signalMapper, SLOT(map())); + signalMapper.setMapping(action, POPUP_SUBMENU_INTO_SUBMENU); + popup.addSeparator(); + } + + // delete actions + action = popup.addAction(QIcon::fromTheme("usermenu-delete.png"),i18n("Delete this item"), &signalMapper, SLOT(map())); + signalMapper.setMapping(action,POPUP_DELETE_ITEM); + popup.addSeparator(); + action = popup.addAction(QIcon::fromTheme("usermenu-clear.png"),i18n("Delete the complete tree"), &signalMapper, SLOT(map())); + signalMapper.setMapping(action, POPUP_DELETE_TREE); + + // expand/collapse tree + if ( submenu ) { + popup.addSeparator(); + if ( m_popupItem->isExpanded() ) { + action = popup.addAction(i18n("Collapse submenu"), &signalMapper, SLOT(map())); + signalMapper.setMapping(action,POPUP_COLLAPSE_ITEM); + } + else { + action = popup.addAction(i18n("Expand submenu"), &signalMapper, SLOT(map())); + signalMapper.setMapping(action,POPUP_EXPAND_ITEM); + } + popup.addSeparator(); + action = popup.addAction(i18n("Collapse complete tree"), &signalMapper, SLOT(map())); + signalMapper.setMapping(action,POPUP_COLLAPSE_TREE); + action = popup.addAction(i18n("Expand complete tree"), &signalMapper, SLOT(map())); + signalMapper.setMapping(action,POPUP_EXPAND_TREE); + } + + // if there are any errors with this item, some info is available + int error = m_popupItem->data(0,Qt::UserRole+2).toInt(); + if ( error != UserMenuItem::MODEL_ERROR_NONE ) { + popup.addSeparator(); + action = popup.addAction(QIcon::fromTheme("help-about.png"),i18n("Info"), &signalMapper, SLOT(map())); + signalMapper.setMapping(action, POPUP_ITEM_INFO); + } + + // const QPoint& pos parameter in the customContextMenuRequested() signal is normally in widget coordinates. + // But classes like QTreeWidget, which inherit from QAbstractScrollArea1 instead use the coordinates of their viewport() + if ( !popup.isEmpty() ) { + popup.exec( viewport()->mapToGlobal(pos) ); + } } // a context menu action was selected void UserMenuTree::slotPopupActivated(int id) { - KILE_DEBUG_MAIN << "popup activated with id: " << id; - switch (id ) { - case POPUP_INSERT_ABOVE: insertMenuItem (m_popupItem, false); break; - case POPUP_INSERT_BELOW: insertMenuItem (m_popupItem, true); break; - case POPUP_SEPARATOR_ABOVE: insertSeparator(m_popupItem, false); break; - case POPUP_SEPARATOR_BELOW: insertSeparator(m_popupItem, true); break; - case POPUP_SUBMENU_ABOVE: insertSubmenu (m_popupItem, false); break; - case POPUP_SUBMENU_BELOW: insertSubmenu (m_popupItem, true); break; - case POPUP_INTO_SUBMENU: insertIntoSubmenu(m_popupItem, UserMenuData::Text); break; - case POPUP_SEPARATOR_INTO_SUBMENU: insertIntoSubmenu(m_popupItem, UserMenuData::Separator); break; - case POPUP_SUBMENU_INTO_SUBMENU: insertIntoSubmenu(m_popupItem, UserMenuData::Submenu); break; - case POPUP_DELETE_ITEM: itemDelete(m_popupItem); break; - case POPUP_DELETE_TREE: deleteMenuTree(); break; - case POPUP_COLLAPSE_ITEM: m_popupItem->setExpanded(false); break; - case POPUP_EXPAND_ITEM: m_popupItem->setExpanded(true); break; - case POPUP_COLLAPSE_TREE: collapseAll(); break; - case POPUP_EXPAND_TREE: expandAll(); break; - case POPUP_ITEM_INFO: itemInfo(m_popupItem); break; - } + KILE_DEBUG_MAIN << "popup activated with id: " << id; + switch (id ) { + case POPUP_INSERT_ABOVE: + insertMenuItem (m_popupItem, false); + break; + case POPUP_INSERT_BELOW: + insertMenuItem (m_popupItem, true); + break; + case POPUP_SEPARATOR_ABOVE: + insertSeparator(m_popupItem, false); + break; + case POPUP_SEPARATOR_BELOW: + insertSeparator(m_popupItem, true); + break; + case POPUP_SUBMENU_ABOVE: + insertSubmenu (m_popupItem, false); + break; + case POPUP_SUBMENU_BELOW: + insertSubmenu (m_popupItem, true); + break; + case POPUP_INTO_SUBMENU: + insertIntoSubmenu(m_popupItem, UserMenuData::Text); + break; + case POPUP_SEPARATOR_INTO_SUBMENU: + insertIntoSubmenu(m_popupItem, UserMenuData::Separator); + break; + case POPUP_SUBMENU_INTO_SUBMENU: + insertIntoSubmenu(m_popupItem, UserMenuData::Submenu); + break; + case POPUP_DELETE_ITEM: + itemDelete(m_popupItem); + break; + case POPUP_DELETE_TREE: + deleteMenuTree(); + break; + case POPUP_COLLAPSE_ITEM: + m_popupItem->setExpanded(false); + break; + case POPUP_EXPAND_ITEM: + m_popupItem->setExpanded(true); + break; + case POPUP_COLLAPSE_TREE: + collapseAll(); + break; + case POPUP_EXPAND_TREE: + expandAll(); + break; + case POPUP_ITEM_INFO: + itemInfo(m_popupItem); + break; + } } ///////////////////////////// read XML ////////////////////////////// // read an xml file and check for errors bool UserMenuTree::readXml(const QString &filename) { - KILE_DEBUG_MAIN << "read xml file " << filename; - - QDomDocument doc("UserMenu"); - QFile file(filename); - if ( !file.open(QFile::ReadOnly | QFile::Text) ) { - KMessageBox::error(this, i18n("File '%1' does not exist.", filename)); - return false; - } - if ( !doc.setContent( &file ) ) { - file.close(); - return false; - } - file.close(); - - KILE_DEBUG_MAIN << "parse xml ..."; - blockSignals(true); - - // clear menutree - clear(); - - // read toplevelitems - QDomElement root = doc.documentElement(); - QDomElement e = root.firstChildElement(); - while ( !e.isNull()) { - QString tag = e.tagName(); - - UserMenuItem *item = Q_NULLPTR; - if ( tag == "submenu" ) { - item = readXmlSubmenu(e); - } - else if ( tag == "separator" ) { - item = readXmlSeparator(); - } - else /* if ( tag == "menu" ) */ { - item = readXmlMenuentry(e); - } - - if ( item ) { - addTopLevelItem(item); - } - e = e.nextSiblingElement(); - } - - // the xml menu is built, now check for errors - setErrorCodes(); - - // polish menutree - expandAll(); - if ( topLevelItemCount() > 0 ) { - setCurrentItem( topLevelItem(0) ); - } - blockSignals(false); - - return true; + KILE_DEBUG_MAIN << "read xml file " << filename; + + QDomDocument doc("UserMenu"); + QFile file(filename); + if ( !file.open(QFile::ReadOnly | QFile::Text) ) { + KMessageBox::error(this, i18n("File '%1' does not exist.", filename)); + return false; + } + if ( !doc.setContent( &file ) ) { + file.close(); + return false; + } + file.close(); + + KILE_DEBUG_MAIN << "parse xml ..."; + blockSignals(true); + + // clear menutree + clear(); + + // read toplevelitems + QDomElement root = doc.documentElement(); + QDomElement e = root.firstChildElement(); + while ( !e.isNull()) { + QString tag = e.tagName(); + + UserMenuItem *item = Q_NULLPTR; + if ( tag == "submenu" ) { + item = readXmlSubmenu(e); + } + else if ( tag == "separator" ) { + item = readXmlSeparator(); + } + else { /* if ( tag == "menu" ) */ + item = readXmlMenuentry(e); + } + + if ( item ) { + addTopLevelItem(item); + } + e = e.nextSiblingElement(); + } + + // the xml menu is built, now check for errors + setErrorCodes(); + + // polish menutree + expandAll(); + if ( topLevelItemCount() > 0 ) { + setCurrentItem( topLevelItem(0) ); + } + blockSignals(false); + + return true; } // a separator tag was found UserMenuItem *UserMenuTree::readXmlSeparator() { - return new UserMenuItem(UserMenuData::Separator, QString()); + return new UserMenuItem(UserMenuData::Separator, QString()); } // read tags for a submenu UserMenuItem *UserMenuTree::readXmlSubmenu(const QDomElement &element) { - UserMenuItem *submenuitem = new UserMenuItem(UserMenuData::Submenu, QString()) ; - - QString title; - if ( element.hasChildNodes() ) { - QDomElement e = element.firstChildElement(); - while ( !e.isNull()) { - UserMenuItem *item = Q_NULLPTR; - - QString tag = e.tagName(); - if ( tag == "title" ) { - title = e.text(); - } - else if ( tag == "submenu" ) { - item = readXmlSubmenu(e); - } - else if ( tag == "separator" ) { - item = readXmlSeparator(); - } - else /* if ( tag == "menu" ) */ { - item = readXmlMenuentry(e); - } - - submenuitem->setMenutitle(title); - submenuitem->setText(0,title); - - if ( item ) { - submenuitem->addChild(item); - } - e = e.nextSiblingElement(); - } - } - - return submenuitem; + UserMenuItem *submenuitem = new UserMenuItem(UserMenuData::Submenu, QString()) ; + + QString title; + if ( element.hasChildNodes() ) { + QDomElement e = element.firstChildElement(); + while ( !e.isNull()) { + UserMenuItem *item = Q_NULLPTR; + + QString tag = e.tagName(); + if ( tag == "title" ) { + title = e.text(); + } + else if ( tag == "submenu" ) { + item = readXmlSubmenu(e); + } + else if ( tag == "separator" ) { + item = readXmlSeparator(); + } + else { /* if ( tag == "menu" ) */ + item = readXmlMenuentry(e); + } + + submenuitem->setMenutitle(title); + submenuitem->setText(0,title); + + if ( item ) { + submenuitem->addChild(item); + } + e = e.nextSiblingElement(); + } + } + + return submenuitem; } // read tags for a standard menu item UserMenuItem *UserMenuTree::readXmlMenuentry(const QDomElement &element) { - QString menutypename = element.attribute("type"); - UserMenuData::MenuType menutype = UserMenuData::xmlMenuType(menutypename); - - UserMenuItem *menuentryitem = new UserMenuItem(menutype, QString()) ; - - // default values - QString title; - QString plaintext; - QString filename; - QString parameter; - QString icon; - QString shortcut; - bool needsSelection = false; - bool useContextMenu = false; - bool replaceSelection = false; - bool selectInsertion = false; - bool insertOutput = false; - - // read values - if ( element.hasChildNodes() ) { - QDomElement e = element.firstChildElement(); - while ( !e.isNull()) { - QString tag = e.tagName(); - QString text = e.text(); - - int index = UserMenuData::xmlMenuTag(tag); - switch (index) { - case UserMenuData::XML_TITLE: title = text; break; - case UserMenuData::XML_PLAINTEXT: plaintext = text; break; - case UserMenuData::XML_FILENAME: filename = text; break; - case UserMenuData::XML_PARAMETER: parameter = text; break; - case UserMenuData::XML_ICON: icon = text; break; - case UserMenuData::XML_SHORTCUT: shortcut = text; break; - case UserMenuData::XML_NEEDSSELECTION: needsSelection = str2bool(text); break; - case UserMenuData::XML_USECONTEXTMENU: useContextMenu = str2bool(text); break; - case UserMenuData::XML_REPLACESELECTION: replaceSelection = str2bool(text); break; - case UserMenuData::XML_SELECTINSERTION: selectInsertion = str2bool(text); break; - case UserMenuData::XML_INSERTOUTPUT: insertOutput = str2bool(text); break; - } - - e = e.nextSiblingElement(); - } - - // save values - menuentryitem->setMenutitle(title); - - // add code newline - plaintext = UserMenuData::decodeLineFeed(plaintext); - menuentryitem->setPlaintext(plaintext); - - menuentryitem->setFilename(filename); - menuentryitem->setParameter(parameter); - if ( !icon.isEmpty() ) { - menuentryitem->setMenuicon(icon); - menuentryitem->setIcon(0,QIcon::fromTheme(icon)); - } - if ( !shortcut.isEmpty() ) { - QKeySequence seq = QKeySequence::fromString(shortcut,QKeySequence::PortableText); - shortcut = seq.toString(QKeySequence::NativeText); - - menuentryitem->setShortcut(shortcut); - menuentryitem->setText(1,shortcut); - } - menuentryitem->setNeedsSelection(needsSelection); - menuentryitem->setUseContextMenu(useContextMenu); - menuentryitem->setReplaceSelection(replaceSelection); - menuentryitem->setSelectInsertion(selectInsertion); - menuentryitem->setInsertOutput(insertOutput); - - menuentryitem->setText(0,title); - } - - return menuentryitem; + QString menutypename = element.attribute("type"); + UserMenuData::MenuType menutype = UserMenuData::xmlMenuType(menutypename); + + UserMenuItem *menuentryitem = new UserMenuItem(menutype, QString()) ; + + // default values + QString title; + QString plaintext; + QString filename; + QString parameter; + QString icon; + QString shortcut; + bool needsSelection = false; + bool useContextMenu = false; + bool replaceSelection = false; + bool selectInsertion = false; + bool insertOutput = false; + + // read values + if ( element.hasChildNodes() ) { + QDomElement e = element.firstChildElement(); + while ( !e.isNull()) { + QString tag = e.tagName(); + QString text = e.text(); + + int index = UserMenuData::xmlMenuTag(tag); + switch (index) { + case UserMenuData::XML_TITLE: + title = text; + break; + case UserMenuData::XML_PLAINTEXT: + plaintext = text; + break; + case UserMenuData::XML_FILENAME: + filename = text; + break; + case UserMenuData::XML_PARAMETER: + parameter = text; + break; + case UserMenuData::XML_ICON: + icon = text; + break; + case UserMenuData::XML_SHORTCUT: + shortcut = text; + break; + case UserMenuData::XML_NEEDSSELECTION: + needsSelection = str2bool(text); + break; + case UserMenuData::XML_USECONTEXTMENU: + useContextMenu = str2bool(text); + break; + case UserMenuData::XML_REPLACESELECTION: + replaceSelection = str2bool(text); + break; + case UserMenuData::XML_SELECTINSERTION: + selectInsertion = str2bool(text); + break; + case UserMenuData::XML_INSERTOUTPUT: + insertOutput = str2bool(text); + break; + } + + e = e.nextSiblingElement(); + } + + // save values + menuentryitem->setMenutitle(title); + + // add code newline + plaintext = UserMenuData::decodeLineFeed(plaintext); + menuentryitem->setPlaintext(plaintext); + + menuentryitem->setFilename(filename); + menuentryitem->setParameter(parameter); + if ( !icon.isEmpty() ) { + menuentryitem->setMenuicon(icon); + menuentryitem->setIcon(0,QIcon::fromTheme(icon)); + } + if ( !shortcut.isEmpty() ) { + QKeySequence seq = QKeySequence::fromString(shortcut,QKeySequence::PortableText); + shortcut = seq.toString(QKeySequence::NativeText); + + menuentryitem->setShortcut(shortcut); + menuentryitem->setText(1,shortcut); + } + menuentryitem->setNeedsSelection(needsSelection); + menuentryitem->setUseContextMenu(useContextMenu); + menuentryitem->setReplaceSelection(replaceSelection); + menuentryitem->setSelectInsertion(selectInsertion); + menuentryitem->setInsertOutput(insertOutput); + + menuentryitem->setText(0,title); + } + + return menuentryitem; } ///////////////////////////// write XML ////////////////////////////// bool UserMenuTree::writeXml(const QString &filename) { - KILE_DEBUG_MAIN << "write xml file " << filename; + KILE_DEBUG_MAIN << "write xml file " << filename; - QFile file(filename); - if ( !file.open(QFile::WriteOnly | QFile::Text) ) { - KMessageBox::error(this, i18n("File '%1' could not be opened to save the usermenu file.", filename)); - return false; - } + QFile file(filename); + if ( !file.open(QFile::WriteOnly | QFile::Text) ) { + KMessageBox::error(this, i18n("File '%1' could not be opened to save the usermenu file.", filename)); + return false; + } - QXmlStreamWriter xmlWriter(&file); - xmlWriter.setAutoFormatting(true); - xmlWriter.setAutoFormattingIndent(2) ; + QXmlStreamWriter xmlWriter(&file); + xmlWriter.setAutoFormatting(true); + xmlWriter.setAutoFormattingIndent(2) ; - xmlWriter.writeStartDocument(); - xmlWriter.writeStartElement("UserMenu"); + xmlWriter.writeStartDocument(); + xmlWriter.writeStartElement("UserMenu"); - for (int i = 0; i < topLevelItemCount(); ++i) { - writeXmlItem(&xmlWriter, dynamic_cast(topLevelItem(i)) ); - } - xmlWriter.writeEndDocument(); + for (int i = 0; i < topLevelItemCount(); ++i) { + writeXmlItem(&xmlWriter, dynamic_cast(topLevelItem(i)) ); + } + xmlWriter.writeEndDocument(); - file.close(); - return true; + file.close(); + return true; } void UserMenuTree::writeXmlItem(QXmlStreamWriter *xml, UserMenuItem *item) { - switch (item->menutype()) { - case UserMenuData::Separator: writeXmlSeparator(xml); break; - case UserMenuData::Submenu: writeXmlSubmenu(xml,item); break; - default: writeXmlMenuentry(xml,item); break; - } + switch (item->menutype()) { + case UserMenuData::Separator: + writeXmlSeparator(xml); + break; + case UserMenuData::Submenu: + writeXmlSubmenu(xml,item); + break; + default: + writeXmlMenuentry(xml,item); + break; + } } // write xml tags for a standard menu item void UserMenuTree::writeXmlMenuentry(QXmlStreamWriter *xml, UserMenuItem *item) { - int menutype = item->menutype(); - QString menutypename = UserMenuData::xmlMenuTypeName(menutype); - - xml->writeStartElement("menu"); - xml->writeAttribute("type", menutypename); - - QString menutitle = ( item->text(0) == EMPTY_MENUENTRY ) ? QString() : item->text(0); - xml->writeTextElement(UserMenuData::xmlMenuTagName(UserMenuData::XML_TITLE),menutitle); - - if ( menutype == UserMenuData::Text ) { - QString plaintext = item->plaintext(); - if ( !plaintext.isEmpty() ) { - // encode newline characters - plaintext = UserMenuData::encodeLineFeed(plaintext); - xml->writeTextElement(UserMenuData::xmlMenuTagName(UserMenuData::XML_PLAINTEXT), plaintext); - } - } - else /* if ( menutype!=UserMenuData::FileContent || menutype==UserMenuData:Program) */ { - // both types use a filename - QString filename = item->filename(); - if ( !filename.isEmpty() ) { - xml->writeTextElement(UserMenuData::xmlMenuTagName(UserMenuData::XML_FILENAME), filename); - - // but UserMenuItem::Program may have an additional parameter - if ( menutype == UserMenuData::Program) { - QString parameter = item->parameter(); - if ( !parameter.isEmpty() ) { - xml->writeTextElement(UserMenuData::xmlMenuTagName(UserMenuData::XML_PARAMETER), parameter); - } - } - } - } - - QString icon = item->menuicon(); - if ( !icon.isEmpty() ) { - xml->writeTextElement(UserMenuData::xmlMenuTagName(UserMenuData::XML_ICON),icon); - } - - QKeySequence seq = QKeySequence::fromString( item->shortcut(), QKeySequence::NativeText ); - if ( !seq.isEmpty() ) { - xml->writeTextElement(UserMenuData::xmlMenuTagName(UserMenuData::XML_SHORTCUT), seq.toString(QKeySequence::PortableText)); - } - - if ( item->needsSelection() ) { - xml->writeTextElement(UserMenuData::xmlMenuTagName(UserMenuData::XML_NEEDSSELECTION), "true"); - } - if ( item->useContextMenu() ) { - xml->writeTextElement(UserMenuData::xmlMenuTagName(UserMenuData::XML_USECONTEXTMENU), "true"); - } - if ( item->replaceSelection() ) { - xml->writeTextElement(UserMenuData::xmlMenuTagName(UserMenuData::XML_REPLACESELECTION), "true"); - } - if ( item->selectInsertion() ) { - xml->writeTextElement(UserMenuData::xmlMenuTagName(UserMenuData::XML_SELECTINSERTION), "true"); - } - if ( item->insertOutput() ) { - xml->writeTextElement(UserMenuData::xmlMenuTagName(UserMenuData::XML_INSERTOUTPUT), "true"); - } - - xml->writeEndElement(); + int menutype = item->menutype(); + QString menutypename = UserMenuData::xmlMenuTypeName(menutype); + + xml->writeStartElement("menu"); + xml->writeAttribute("type", menutypename); + + QString menutitle = ( item->text(0) == EMPTY_MENUENTRY ) ? QString() : item->text(0); + xml->writeTextElement(UserMenuData::xmlMenuTagName(UserMenuData::XML_TITLE),menutitle); + + if ( menutype == UserMenuData::Text ) { + QString plaintext = item->plaintext(); + if ( !plaintext.isEmpty() ) { + // encode newline characters + plaintext = UserMenuData::encodeLineFeed(plaintext); + xml->writeTextElement(UserMenuData::xmlMenuTagName(UserMenuData::XML_PLAINTEXT), plaintext); + } + } + else { /* if ( menutype!=UserMenuData::FileContent || menutype==UserMenuData:Program) */ + // both types use a filename + QString filename = item->filename(); + if ( !filename.isEmpty() ) { + xml->writeTextElement(UserMenuData::xmlMenuTagName(UserMenuData::XML_FILENAME), filename); + + // but UserMenuItem::Program may have an additional parameter + if ( menutype == UserMenuData::Program) { + QString parameter = item->parameter(); + if ( !parameter.isEmpty() ) { + xml->writeTextElement(UserMenuData::xmlMenuTagName(UserMenuData::XML_PARAMETER), parameter); + } + } + } + } + + QString icon = item->menuicon(); + if ( !icon.isEmpty() ) { + xml->writeTextElement(UserMenuData::xmlMenuTagName(UserMenuData::XML_ICON),icon); + } + + QKeySequence seq = QKeySequence::fromString( item->shortcut(), QKeySequence::NativeText ); + if ( !seq.isEmpty() ) { + xml->writeTextElement(UserMenuData::xmlMenuTagName(UserMenuData::XML_SHORTCUT), seq.toString(QKeySequence::PortableText)); + } + + if ( item->needsSelection() ) { + xml->writeTextElement(UserMenuData::xmlMenuTagName(UserMenuData::XML_NEEDSSELECTION), "true"); + } + if ( item->useContextMenu() ) { + xml->writeTextElement(UserMenuData::xmlMenuTagName(UserMenuData::XML_USECONTEXTMENU), "true"); + } + if ( item->replaceSelection() ) { + xml->writeTextElement(UserMenuData::xmlMenuTagName(UserMenuData::XML_REPLACESELECTION), "true"); + } + if ( item->selectInsertion() ) { + xml->writeTextElement(UserMenuData::xmlMenuTagName(UserMenuData::XML_SELECTINSERTION), "true"); + } + if ( item->insertOutput() ) { + xml->writeTextElement(UserMenuData::xmlMenuTagName(UserMenuData::XML_INSERTOUTPUT), "true"); + } + + xml->writeEndElement(); } // write xml tags for a submenu void UserMenuTree::writeXmlSubmenu(QXmlStreamWriter *xml, UserMenuItem *item) { - xml->writeStartElement("submenu"); - - QString menutitle = item->text(0); - if ( menutitle == EMPTY_MENUENTRY ) { - menutitle.clear(); - } - else if ( menutitle.right(LENGTH_SUBSTITUTE) == EMPTY_SUBMENU ) { - menutitle = menutitle.left(menutitle.length()-LENGTH_SUBSTITUTE); - } - xml->writeTextElement(UserMenuData::xmlMenuTagName(UserMenuData::XML_TITLE),menutitle); - - for ( int i=0; ichildCount(); ++i ) { - writeXmlItem(xml, dynamic_cast(item->child(i)) ); - } - - xml->writeEndElement(); + xml->writeStartElement("submenu"); + + QString menutitle = item->text(0); + if ( menutitle == EMPTY_MENUENTRY ) { + menutitle.clear(); + } + else if ( menutitle.right(LENGTH_SUBSTITUTE) == EMPTY_SUBMENU ) { + menutitle = menutitle.left(menutitle.length()-LENGTH_SUBSTITUTE); + } + xml->writeTextElement(UserMenuData::xmlMenuTagName(UserMenuData::XML_TITLE),menutitle); + + for ( int i=0; ichildCount(); ++i ) { + writeXmlItem(xml, dynamic_cast(item->child(i)) ); + } + + xml->writeEndElement(); } // write xml tag for a separator void UserMenuTree::writeXmlSeparator(QXmlStreamWriter *xml) { - xml->writeStartElement("separator"); - xml->writeEndElement(); + xml->writeStartElement("separator"); + xml->writeEndElement(); } ///////////////////////////// check menutree and set error codes ////////////////////////////// // the complete menutree was build, now check for errors // - empty menutitles // - useless submenus without children // - empty filenames, not existing or not executable files void UserMenuTree::setErrorCodes() { - KILE_DEBUG_MAIN << "check menutree for errors and set error codes ..."; - - for (int i = 0; i < topLevelItemCount(); ++i) { - UserMenuItem *item = dynamic_cast(topLevelItem(i)); - UserMenuData::MenuType type = item->menutype(); - - bool executable = ( type==UserMenuData::Program && isItemExecutable(item->filename()) ); - item->setModelData(executable); - - if ( type != UserMenuData::Separator ) { - checkMenuTitle(item); - } - if ( type == UserMenuData::Submenu ) { - checkSubmenu(item); - } - } + KILE_DEBUG_MAIN << "check menutree for errors and set error codes ..."; + + for (int i = 0; i < topLevelItemCount(); ++i) { + UserMenuItem *item = dynamic_cast(topLevelItem(i)); + UserMenuData::MenuType type = item->menutype(); + + bool executable = ( type==UserMenuData::Program && isItemExecutable(item->filename()) ); + item->setModelData(executable); + + if ( type != UserMenuData::Separator ) { + checkMenuTitle(item); + } + if ( type == UserMenuData::Submenu ) { + checkSubmenu(item); + } + } } void UserMenuTree::checkMenuTitle(UserMenuItem *item) { - if ( item->menutitle().isEmpty() ) { - item->setText(0,EMPTY_MENUENTRY); - KILE_DEBUG_MAIN << "empty menutitle changed to " << EMPTY_MENUENTRY; - } + if ( item->menutitle().isEmpty() ) { + item->setText(0,EMPTY_MENUENTRY); + KILE_DEBUG_MAIN << "empty menutitle changed to " << EMPTY_MENUENTRY; + } } void UserMenuTree::checkSubmenu(UserMenuItem *item) { - QString menutitle = item->menutitle(); - int children = item->childCount(); - - if ( menutitle.isEmpty() ) { - menutitle = EMPTY_MENUENTRY; - } - else if ( children == 0 ) { - menutitle += EMPTY_SUBMENU; - } - item->setText(0,menutitle); - - for ( int i=0; i(item->child(i)); - child->setModelData(); - UserMenuData::MenuType type = child->menutype(); - - if ( type != UserMenuData::Separator ) { - checkMenuTitle(child); - } - if ( type == UserMenuData::Submenu ) { - checkSubmenu(child); - } - } + QString menutitle = item->menutitle(); + int children = item->childCount(); + + if ( menutitle.isEmpty() ) { + menutitle = EMPTY_MENUENTRY; + } + else if ( children == 0 ) { + menutitle += EMPTY_SUBMENU; + } + item->setText(0,menutitle); + + for ( int i=0; i(item->child(i)); + child->setModelData(); + UserMenuData::MenuType type = child->menutype(); + + if ( type != UserMenuData::Separator ) { + checkMenuTitle(child); + } + if ( type == UserMenuData::Submenu ) { + checkSubmenu(child); + } + } } ///////////////////////////// check menutree ////////////////////////////// // check for errors (true=no errors) bool UserMenuTree::errorCheck() { - KILE_DEBUG_MAIN << "check menutree for errors ..."; - - for (int i = 0; i < topLevelItemCount(); ++i) { - UserMenuItem *item = dynamic_cast(topLevelItem(i)); - UserMenuData::MenuType type = item->menutype(); - - if ( type != UserMenuData::Separator ) { - if ( item->data(0,Qt::UserRole+2).toInt() != UserMenuItem::MODEL_ERROR_NONE ) { - return false; - } - } - - if ( type == UserMenuData::Submenu ) { - if ( checkSubmenuError(item) == false ) { - return false; - } - } - } - - return true; + KILE_DEBUG_MAIN << "check menutree for errors ..."; + + for (int i = 0; i < topLevelItemCount(); ++i) { + UserMenuItem *item = dynamic_cast(topLevelItem(i)); + UserMenuData::MenuType type = item->menutype(); + + if ( type != UserMenuData::Separator ) { + if ( item->data(0,Qt::UserRole+2).toInt() != UserMenuItem::MODEL_ERROR_NONE ) { + return false; + } + } + + if ( type == UserMenuData::Submenu ) { + if ( checkSubmenuError(item) == false ) { + return false; + } + } + } + + return true; } bool UserMenuTree::checkSubmenuError(UserMenuItem *item) { - int children = item->childCount(); - for ( int i=0; i(item->child(i)); - UserMenuData::MenuType type = child->menutype(); - - if ( type != UserMenuData::Separator ) { - if ( child->data(0,Qt::UserRole+2).toInt() != UserMenuItem::MODEL_ERROR_NONE ) { - return false; - } - } - - if ( type == UserMenuData::Submenu ) { - if ( checkSubmenuError(child) == false ) { - return false; - } - } - } - - return true; + int children = item->childCount(); + for ( int i=0; i(item->child(i)); + UserMenuData::MenuType type = child->menutype(); + + if ( type != UserMenuData::Separator ) { + if ( child->data(0,Qt::UserRole+2).toInt() != UserMenuItem::MODEL_ERROR_NONE ) { + return false; + } + } + + if ( type == UserMenuData::Submenu ) { + if ( checkSubmenuError(child) == false ) { + return false; + } + } + } + + return true; } ///////////////////////////// tree ops ////////////////////////////// // insert a standard menu item bool UserMenuTree::insertMenuItem(QTreeWidgetItem *current, bool below) { - QString menulabel = getMenuTitle(i18n("Please enter a label for this menu item:")); - if ( menulabel.isEmpty() ) { - return false; - } - - if ( below ) { - insertMenuItemBelow(current,UserMenuData::Text,menulabel); - } - else { - insertMenuItemAbove(current,UserMenuData::Text,menulabel); - } - return true; + QString menulabel = getMenuTitle(i18n("Please enter a label for this menu item:")); + if ( menulabel.isEmpty() ) { + return false; + } + + if ( below ) { + insertMenuItemBelow(current,UserMenuData::Text,menulabel); + } + else { + insertMenuItemAbove(current,UserMenuData::Text,menulabel); + } + return true; } // insert a submenu item bool UserMenuTree::insertSubmenu(QTreeWidgetItem *current, bool below) { - QString menulabel = getMenuTitle(i18n("Please enter a label for this submenu:")); - if ( menulabel.isEmpty() ) { - return false; - } - - if ( below ) { - insertMenuItemBelow(current,UserMenuData::Submenu,menulabel); - } - else { - insertMenuItemAbove(current,UserMenuData::Submenu,menulabel); - } - return true; + QString menulabel = getMenuTitle(i18n("Please enter a label for this submenu:")); + if ( menulabel.isEmpty() ) { + return false; + } + + if ( below ) { + insertMenuItemBelow(current,UserMenuData::Submenu,menulabel); + } + else { + insertMenuItemAbove(current,UserMenuData::Submenu,menulabel); + } + return true; } // insert a separator item bool UserMenuTree::insertSeparator(QTreeWidgetItem *current, bool below) { - if(below) { - insertMenuItemBelow(current,UserMenuData::Separator, QString()); - } - else { - insertMenuItemAbove(current,UserMenuData::Separator, QString()); - } - return true; + if(below) { + insertMenuItemBelow(current,UserMenuData::Separator, QString()); + } + else { + insertMenuItemAbove(current,UserMenuData::Separator, QString()); + } + return true; } void UserMenuTree::insertMenuItemAbove(QTreeWidgetItem *current, UserMenuData::MenuType type, const QString &menulabel) { - QTreeWidgetItem *parent = ( current ) ? current->parent() : Q_NULLPTR; - int index = itemIndex(parent,current); + QTreeWidgetItem *parent = ( current ) ? current->parent() : Q_NULLPTR; + int index = itemIndex(parent,current); - UserMenuItem *item = new UserMenuItem(type,menulabel); - insertItem(parent,index,item); + UserMenuItem *item = new UserMenuItem(type,menulabel); + insertItem(parent,index,item); - item->setText(0,menulabel); - setCurrentItem(item); + item->setText(0,menulabel); + setCurrentItem(item); } void UserMenuTree::insertMenuItemBelow(QTreeWidgetItem *current, UserMenuData::MenuType type, const QString &menulabel) { - UserMenuItem *item; - QTreeWidgetItem *parent = ( current ) ? current->parent() : Q_NULLPTR; - - if(!parent) { - item = new UserMenuItem(this,current,type,menulabel); - } - else { - item = new UserMenuItem(parent,current,type,menulabel); - } - - item->setText(0,menulabel); - setCurrentItem(item); + UserMenuItem *item; + QTreeWidgetItem *parent = ( current ) ? current->parent() : Q_NULLPTR; + + if(!parent) { + item = new UserMenuItem(this,current,type,menulabel); + } + else { + item = new UserMenuItem(parent,current,type,menulabel); + } + + item->setText(0,menulabel); + setCurrentItem(item); } void UserMenuTree::insertIntoSubmenu(QTreeWidgetItem *current, UserMenuData::MenuType type) { - QString menulabel; - if ( type == UserMenuData::Text || type == UserMenuData::Submenu ) { - menulabel = getMenuTitle(i18n("Please enter a label for this entry:")); - if ( menulabel.isEmpty() ) { - return; - } - } - - UserMenuItem *item = new UserMenuItem(type,menulabel); - insertItem(current,0,item); - setCurrentItem(item); + QString menulabel; + if ( type == UserMenuData::Text || type == UserMenuData::Submenu ) { + menulabel = getMenuTitle(i18n("Please enter a label for this entry:")); + if ( menulabel.isEmpty() ) { + return; + } + } + + UserMenuItem *item = new UserMenuItem(type,menulabel); + insertItem(current,0,item); + setCurrentItem(item); } // delete an item void UserMenuTree::itemDelete(QTreeWidgetItem *current) { - int children,index; - QTreeWidgetItem *item, *selectitem; - QTreeWidgetItem *parent = current->parent(); - if(!parent) { - children = topLevelItemCount(); - index = indexOfTopLevelItem(current); - if ( index < children-1 ) { - selectitem = topLevelItem(index+1); - } - else if ( index > 0 ) { - selectitem = topLevelItem(index-1); - } - else { - selectitem = Q_NULLPTR; - } - - item = takeTopLevelItem(index); - } - else { - children = parent->childCount(); - index = parent->indexOfChild(current); - if ( index < children-1 ) { - selectitem = parent->child(index+1); - } - else if ( index > 0 ) { - selectitem = parent->child(index-1); - } - else { - selectitem = parent; - } - - item = parent->takeChild(index); - } - - delete item; - - if(selectitem) { - setCurrentItem(selectitem); - } + int children,index; + QTreeWidgetItem *item, *selectitem; + QTreeWidgetItem *parent = current->parent(); + if(!parent) { + children = topLevelItemCount(); + index = indexOfTopLevelItem(current); + if ( index < children-1 ) { + selectitem = topLevelItem(index+1); + } + else if ( index > 0 ) { + selectitem = topLevelItem(index-1); + } + else { + selectitem = Q_NULLPTR; + } + + item = takeTopLevelItem(index); + } + else { + children = parent->childCount(); + index = parent->indexOfChild(current); + if ( index < children-1 ) { + selectitem = parent->child(index+1); + } + else if ( index > 0 ) { + selectitem = parent->child(index-1); + } + else { + selectitem = parent; + } + + item = parent->takeChild(index); + } + + delete item; + + if(selectitem) { + setCurrentItem(selectitem); + } } // move an item one position up void UserMenuTree::itemUp() { - QTreeWidgetItem *current = currentItem(); - UserMenuItem *aboveitem = dynamic_cast(itemAbove(current)); - if (!aboveitem) { - return; - } - - bool expanded = current->isExpanded(); - blockSignals(true); - - QTreeWidgetItem *aboveparent = aboveitem->parent(); - int aboveindex = itemIndex(aboveparent,aboveitem); - - UserMenuItem *parent = dynamic_cast(current->parent()); - int index = itemIndex(parent,current); - takeItem(parent,current); - - if ( parent!=aboveparent && index!=0 ) { - aboveindex++; - } - - if ( parent==aboveparent && aboveitem->menutype()==UserMenuData::Submenu ) { - insertItem(aboveitem,0,current); - } - else { - insertItem(aboveparent,aboveindex,current); - } - - // update model data of old and new parent, if it has changed - UserMenuItem *newparent = dynamic_cast(current->parent()); - if ( parent != newparent ) { - if ( parent ) { - parent->setModelData(); - parent->setText(0, parent->updateMenutitle()); - } - if ( newparent ) { - newparent->setModelData(); - newparent->setText(0, newparent->updateMenutitle()); - } - } - - current->setExpanded(expanded); - setCurrentItem(current); - blockSignals(false); + QTreeWidgetItem *current = currentItem(); + UserMenuItem *aboveitem = dynamic_cast(itemAbove(current)); + if (!aboveitem) { + return; + } + + bool expanded = current->isExpanded(); + blockSignals(true); + + QTreeWidgetItem *aboveparent = aboveitem->parent(); + int aboveindex = itemIndex(aboveparent,aboveitem); + + UserMenuItem *parent = dynamic_cast(current->parent()); + int index = itemIndex(parent,current); + takeItem(parent,current); + + if ( parent!=aboveparent && index!=0 ) { + aboveindex++; + } + + if ( parent==aboveparent && aboveitem->menutype()==UserMenuData::Submenu ) { + insertItem(aboveitem,0,current); + } + else { + insertItem(aboveparent,aboveindex,current); + } + + // update model data of old and new parent, if it has changed + UserMenuItem *newparent = dynamic_cast(current->parent()); + if ( parent != newparent ) { + if ( parent ) { + parent->setModelData(); + parent->setText(0, parent->updateMenutitle()); + } + if ( newparent ) { + newparent->setModelData(); + newparent->setText(0, newparent->updateMenutitle()); + } + } + + current->setExpanded(expanded); + setCurrentItem(current); + blockSignals(false); } // move an item one position down void UserMenuTree::itemDown() { - QTreeWidgetItem *current = currentItem(); - bool expanded = current->isExpanded(); - blockSignals(true); - - // get all necessary parameter - UserMenuItem *parent = dynamic_cast(current->parent()); - int index = itemIndex(parent,current); - int children = numChildren(parent); - - // successor exists? - if ( index < children-1 ) { - UserMenuItem *successor = dynamic_cast( itemAtIndex(parent,index+1) ); - takeItem(parent,current); - if ( successor->menutype() == UserMenuData::Submenu ) { - successor->insertChild(0,current); - } - else { - insertItem(parent,index+1,current); - } - } - else if ( parent ) { - QTreeWidgetItem *grandparent = parent->parent(); - int parentindex = itemIndex(grandparent,parent); - takeItem(parent,current); - insertItem(grandparent,parentindex+1,current); - } - - // update model data of old and new parent, if it has changed - UserMenuItem *newparent = dynamic_cast(current->parent()); - if ( parent != newparent ) { - if ( parent ) { - parent->setModelData(); - parent->setText(0, parent->updateMenutitle()); - } - if ( newparent ) { - newparent->setModelData(); - newparent->setText(0, newparent->updateMenutitle()); - } - } - - current->setExpanded(expanded); - setCurrentItem(current); - blockSignals(false); + QTreeWidgetItem *current = currentItem(); + bool expanded = current->isExpanded(); + blockSignals(true); + + // get all necessary parameter + UserMenuItem *parent = dynamic_cast(current->parent()); + int index = itemIndex(parent,current); + int children = numChildren(parent); + + // successor exists? + if ( index < children-1 ) { + UserMenuItem *successor = dynamic_cast( itemAtIndex(parent,index+1) ); + takeItem(parent,current); + if ( successor->menutype() == UserMenuData::Submenu ) { + successor->insertChild(0,current); + } + else { + insertItem(parent,index+1,current); + } + } + else if ( parent ) { + QTreeWidgetItem *grandparent = parent->parent(); + int parentindex = itemIndex(grandparent,parent); + takeItem(parent,current); + insertItem(grandparent,parentindex+1,current); + } + + // update model data of old and new parent, if it has changed + UserMenuItem *newparent = dynamic_cast(current->parent()); + if ( parent != newparent ) { + if ( parent ) { + parent->setModelData(); + parent->setText(0, parent->updateMenutitle()); + } + if ( newparent ) { + newparent->setModelData(); + newparent->setText(0, newparent->updateMenutitle()); + } + } + + current->setExpanded(expanded); + setCurrentItem(current); + blockSignals(false); } ////////////////////////////// delete tree ////////////////////////////// // delete the whole menutree void UserMenuTree::deleteMenuTree() { - if ( KMessageBox::questionYesNo(this, i18n("Do you really want to clear the complete menutree?") ) == KMessageBox::Yes ) { - blockSignals(true); - clear(); - blockSignals(false); - } + if ( KMessageBox::questionYesNo(this, i18n("Do you really want to clear the complete menutree?") ) == KMessageBox::Yes ) { + blockSignals(true); + clear(); + blockSignals(false); + } } ////////////////////////////// info ////////////////////////////// // prepare info for en item with errors void UserMenuTree::itemInfo(UserMenuItem *item) { - int error = item->data(0,Qt::UserRole+2).toInt(); - - QStringList list; - if ( error & UserMenuItem::MODEL_ERROR_EMPTY ) { - list << i18n("This menuitem has no title."); - } - - if ( error & UserMenuItem::MODEL_ERROR_SUBMENU ) { - list << i18n("This submenu item is useless without children."); - } - - if ( error & UserMenuItem::MODEL_ERROR_TEXT ) { - list << i18n("This item offers no text to insert."); - } - - if ( error & UserMenuItem::MODEL_ERROR_FILE_EMPTY ) { - list << i18n("No file is given for this task."); - } - - if ( error & UserMenuItem::MODEL_ERROR_FILE_EXIST ) { - list << i18n("The file for this item does not exist."); - } - - if ( error & UserMenuItem::MODEL_ERROR_FILE_EXECUTABLE ) { - list << i18n("The file for this item is not executable."); - } - - QString msg = i18n("

Error:"); - if ( list.size() == 1 ) { - msg += "

" + list[0] + "

"; - } - else { - msg += "
    "; - foreach ( const QString &s, list ) { - msg += "
  •  " + s + "
  • "; - } - msg += "

"; - } - - KMessageBox::information(this, msg, i18n("Menutree Error")); + int error = item->data(0,Qt::UserRole+2).toInt(); + + QStringList list; + if ( error & UserMenuItem::MODEL_ERROR_EMPTY ) { + list << i18n("This menuitem has no title."); + } + + if ( error & UserMenuItem::MODEL_ERROR_SUBMENU ) { + list << i18n("This submenu item is useless without children."); + } + + if ( error & UserMenuItem::MODEL_ERROR_TEXT ) { + list << i18n("This item offers no text to insert."); + } + + if ( error & UserMenuItem::MODEL_ERROR_FILE_EMPTY ) { + list << i18n("No file is given for this task."); + } + + if ( error & UserMenuItem::MODEL_ERROR_FILE_EXIST ) { + list << i18n("The file for this item does not exist."); + } + + if ( error & UserMenuItem::MODEL_ERROR_FILE_EXECUTABLE ) { + list << i18n("The file for this item is not executable."); + } + + QString msg = i18n("

Error:"); + if ( list.size() == 1 ) { + msg += "

" + list[0] + "

"; + } + else { + msg += "
    "; + foreach ( const QString &s, list ) { + msg += "
  •  " + s + "
  • "; + } + msg += "

"; + } + + KMessageBox::information(this, msg, i18n("Menutree Error")); } ////////////////////////////// auxiliary ////////////////////////////// int UserMenuTree::itemIndex(QTreeWidgetItem *parent, QTreeWidgetItem *item) { - return ( parent ) ? parent->indexOfChild(item) : indexOfTopLevelItem(item); + return ( parent ) ? parent->indexOfChild(item) : indexOfTopLevelItem(item); } QTreeWidgetItem *UserMenuTree::itemAtIndex(QTreeWidgetItem *parent, int index) { - return ( parent ) ? parent->child(index) : topLevelItem(index); + return ( parent ) ? parent->child(index) : topLevelItem(index); } int UserMenuTree::numChildren(QTreeWidgetItem *parent) { - return ( parent ) ? parent->childCount() : topLevelItemCount(); + return ( parent ) ? parent->childCount() : topLevelItemCount(); } void UserMenuTree::insertItem(QTreeWidgetItem *parent, int index, QTreeWidgetItem *item) { - if ( parent ) { - parent->insertChild(index,item); - } - else { - insertTopLevelItem(index,item); - } + if ( parent ) { + parent->insertChild(index,item); + } + else { + insertTopLevelItem(index,item); + } } void UserMenuTree::takeItem(QTreeWidgetItem *parent, QTreeWidgetItem *item) { - if ( parent ) { - int index = parent->indexOfChild(item); - parent->takeChild(index); - } - else { - int index = indexOfTopLevelItem(item); - takeTopLevelItem(index); - } + if ( parent ) { + int index = parent->indexOfChild(item); + parent->takeChild(index); + } + else { + int index = indexOfTopLevelItem(item); + takeTopLevelItem(index); + } } bool UserMenuTree::str2bool(const QString &value) { - return ( value == "true" ); + return ( value == "true" ); } QString UserMenuTree::getMenuTitle(const QString &title) { - bool ok; - QString value = QInputDialog::getText(this, i18n("Name"), title, QLineEdit::Normal, QString(), &ok); - return ( ok ) ? value : QString(); + bool ok; + QString value = QInputDialog::getText(this, i18n("Name"), title, QLineEdit::Normal, QString(), &ok); + return ( ok ) ? value : QString(); } } diff --git a/src/dialogs/usermenu/usermenutree.h b/src/dialogs/usermenu/usermenutree.h index 712d6e79..35171a66 100644 --- a/src/dialogs/usermenu/usermenutree.h +++ b/src/dialogs/usermenu/usermenutree.h @@ -1,113 +1,113 @@ /*********************************************************************************** Copyright (C) 2011-2012 by Holger Danielsson (holger.danielsson@versanet.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. * * * ***************************************************************************/ #ifndef LATEXMENUTREE_H #define LATEXMENUTREE_H #include #include #include #include #include #include namespace KileMenu { class MenuentryDelegate : public QStyledItemDelegate { - public: - MenuentryDelegate(QObject *parent=0) : QStyledItemDelegate(parent) {} +public: + MenuentryDelegate(QObject *parent=0) : QStyledItemDelegate(parent) {} - virtual void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex& index) const; + virtual void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex& index) const; }; class UserMenuTree : public QTreeWidget { - Q_OBJECT + Q_OBJECT - public: - UserMenuTree(QWidget *parent); - ~UserMenuTree() {} +public: + UserMenuTree(QWidget *parent); + ~UserMenuTree() {} - bool insertMenuItem(QTreeWidgetItem *current, bool below=true); - bool insertSubmenu(QTreeWidgetItem *current, bool below=true); - bool insertSeparator(QTreeWidgetItem *current, bool below=true); + bool insertMenuItem(QTreeWidgetItem *current, bool below=true); + bool insertSubmenu(QTreeWidgetItem *current, bool below=true); + bool insertSeparator(QTreeWidgetItem *current, bool below=true); - void itemDelete(QTreeWidgetItem *current); - void itemUp(); - void itemDown(); - void contextMenuRequested(const QPoint &pos); + void itemDelete(QTreeWidgetItem *current); + void itemUp(); + void itemDown(); + void contextMenuRequested(const QPoint &pos); - bool readXml(const QString &filename); - bool writeXml(const QString &filename); - bool errorCheck(); - bool isItemExecutable(const QString &filename); + bool readXml(const QString &filename); + bool writeXml(const QString &filename); + bool errorCheck(); + bool isItemExecutable(const QString &filename); - bool isEmpty(); + bool isEmpty(); - private Q_SLOTS: - void slotPopupActivated(int id); +private Q_SLOTS: + void slotPopupActivated(int id); - private: - enum PopupType { POPUP_INSERT_ABOVE=0x00, POPUP_INSERT_BELOW=0x01, - POPUP_SEPARATOR_ABOVE=0x02, POPUP_SEPARATOR_BELOW=0x03, - POPUP_SUBMENU_ABOVE=0x04, POPUP_SUBMENU_BELOW=0x05, - POPUP_INTO_SUBMENU=0x06, POPUP_SEPARATOR_INTO_SUBMENU=0x07, POPUP_SUBMENU_INTO_SUBMENU=0x08, - POPUP_DELETE_ITEM=0x09, POPUP_DELETE_TREE=0x0A, - POPUP_COLLAPSE_ITEM=0x0B, POPUP_EXPAND_ITEM=0x0C, - POPUP_COLLAPSE_TREE=0x0D, POPUP_EXPAND_TREE=0x0E, - POPUP_ITEM_INFO=0x0F - }; +private: + enum PopupType { POPUP_INSERT_ABOVE=0x00, POPUP_INSERT_BELOW=0x01, + POPUP_SEPARATOR_ABOVE=0x02, POPUP_SEPARATOR_BELOW=0x03, + POPUP_SUBMENU_ABOVE=0x04, POPUP_SUBMENU_BELOW=0x05, + POPUP_INTO_SUBMENU=0x06, POPUP_SEPARATOR_INTO_SUBMENU=0x07, POPUP_SUBMENU_INTO_SUBMENU=0x08, + POPUP_DELETE_ITEM=0x09, POPUP_DELETE_TREE=0x0A, + POPUP_COLLAPSE_ITEM=0x0B, POPUP_EXPAND_ITEM=0x0C, + POPUP_COLLAPSE_TREE=0x0D, POPUP_EXPAND_TREE=0x0E, + POPUP_ITEM_INFO=0x0F + }; - UserMenuItem *m_popupItem; + UserMenuItem *m_popupItem; - void setErrorCodes(); - bool checkSubmenuError(UserMenuItem *item); + void setErrorCodes(); + bool checkSubmenuError(UserMenuItem *item); - QStringList m_envPathlist; - void initEnvPathlist(); + QStringList m_envPathlist; + void initEnvPathlist(); - void insertMenuItemAbove(QTreeWidgetItem *current, UserMenuData::MenuType type, const QString &menulabel); - void insertMenuItemBelow(QTreeWidgetItem *current, UserMenuData::MenuType type, const QString &menulabel); - void insertIntoSubmenu(QTreeWidgetItem *current, UserMenuData::MenuType type); + void insertMenuItemAbove(QTreeWidgetItem *current, UserMenuData::MenuType type, const QString &menulabel); + void insertMenuItemBelow(QTreeWidgetItem *current, UserMenuData::MenuType type, const QString &menulabel); + void insertIntoSubmenu(QTreeWidgetItem *current, UserMenuData::MenuType type); - void deleteMenuTree(); + void deleteMenuTree(); - int itemIndex(QTreeWidgetItem *parent, QTreeWidgetItem *item); - QTreeWidgetItem *itemAtIndex(QTreeWidgetItem *parent, int index); - int numChildren(QTreeWidgetItem *parent); + int itemIndex(QTreeWidgetItem *parent, QTreeWidgetItem *item); + QTreeWidgetItem *itemAtIndex(QTreeWidgetItem *parent, int index); + int numChildren(QTreeWidgetItem *parent); - void insertItem(QTreeWidgetItem *parent, int index, QTreeWidgetItem *item); - void takeItem(QTreeWidgetItem *parent, QTreeWidgetItem *item); + void insertItem(QTreeWidgetItem *parent, int index, QTreeWidgetItem *item); + void takeItem(QTreeWidgetItem *parent, QTreeWidgetItem *item); - UserMenuItem *readXmlSeparator(); - UserMenuItem *readXmlSubmenu(const QDomElement &element); - UserMenuItem *readXmlMenuentry(const QDomElement &element); + UserMenuItem *readXmlSeparator(); + UserMenuItem *readXmlSubmenu(const QDomElement &element); + UserMenuItem *readXmlMenuentry(const QDomElement &element); - void writeXmlItem(QXmlStreamWriter *xml, UserMenuItem *item); - void writeXmlMenuentry(QXmlStreamWriter *xml, UserMenuItem *item); - void writeXmlSubmenu(QXmlStreamWriter *xml, UserMenuItem *item); - void writeXmlSeparator(QXmlStreamWriter *xml); + void writeXmlItem(QXmlStreamWriter *xml, UserMenuItem *item); + void writeXmlMenuentry(QXmlStreamWriter *xml, UserMenuItem *item); + void writeXmlSubmenu(QXmlStreamWriter *xml, UserMenuItem *item); + void writeXmlSeparator(QXmlStreamWriter *xml); - void checkMenuTitle(UserMenuItem *item); - void checkSubmenu(UserMenuItem *item); + void checkMenuTitle(UserMenuItem *item); + void checkSubmenu(UserMenuItem *item); - bool str2bool(const QString &value); - QString getMenuTitle(const QString &title); - void itemInfo(UserMenuItem *item); + bool str2bool(const QString &value); + QString getMenuTitle(const QString &title); + void itemInfo(UserMenuItem *item); }; } #endif diff --git a/src/dialogs/validatorinputdialog.cpp b/src/dialogs/validatorinputdialog.cpp index 20c03ae6..514c0d67 100644 --- a/src/dialogs/validatorinputdialog.cpp +++ b/src/dialogs/validatorinputdialog.cpp @@ -1,119 +1,119 @@ /* * Copyright 2003 Nadeem Hasan * Copyright 2015 Andreas Cord-Landwehr * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Library 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 Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #include "validatorinputdialog.h" #include "validatorinputdialog_p.h" #include #include #include #include #include #include using namespace KileDialog; ValidatorInputDialogHelper::ValidatorInputDialogHelper(const QString &caption, const QString &label, - const QString &value, QWidget *parent, - QValidator *validator, const QString &mask) - : QDialog(parent) - , m_lineEdit(new QLineEdit(this)) - , m_buttonBox(new QDialogButtonBox(this)) + const QString &value, QWidget *parent, + QValidator *validator, const QString &mask) + : QDialog(parent) + , m_lineEdit(new QLineEdit(this)) + , m_buttonBox(new QDialogButtonBox(this)) { - setWindowTitle(caption); - setModal(true); + setWindowTitle(caption); + setModal(true); - QVBoxLayout *layout = new QVBoxLayout; - setLayout(layout); + QVBoxLayout *layout = new QVBoxLayout; + setLayout(layout); - QLabel *m_label = new QLabel(label, this); - m_label->setWordWrap(true); - layout->addWidget(m_label); + QLabel *m_label = new QLabel(label, this); + m_label->setWordWrap(true); + layout->addWidget(m_label); - m_lineEdit->setText(value); - m_lineEdit->setClearButtonEnabled(true); - layout->addWidget(m_lineEdit); + m_lineEdit->setText(value); + m_lineEdit->setClearButtonEnabled(true); + layout->addWidget(m_lineEdit); - m_lineEdit->setFocus(); - m_label->setBuddy(m_lineEdit); + m_lineEdit->setFocus(); + m_label->setBuddy(m_lineEdit); - layout->addStretch(); + layout->addStretch(); - m_buttonBox->setStandardButtons(QDialogButtonBox::Ok | QDialogButtonBox::Cancel); - connect(m_buttonBox, &QDialogButtonBox::accepted, this, &QDialog::accept); - connect(m_buttonBox, &QDialogButtonBox::rejected, this, &QDialog::reject); - layout->addWidget(m_buttonBox); + m_buttonBox->setStandardButtons(QDialogButtonBox::Ok | QDialogButtonBox::Cancel); + connect(m_buttonBox, &QDialogButtonBox::accepted, this, &QDialog::accept); + connect(m_buttonBox, &QDialogButtonBox::rejected, this, &QDialog::reject); + layout->addWidget(m_buttonBox); - if (validator) { - m_lineEdit->setValidator(validator); - } + if (validator) { + m_lineEdit->setValidator(validator); + } - if (!mask.isEmpty()) { - m_lineEdit->setInputMask(mask); - } + if (!mask.isEmpty()) { + m_lineEdit->setInputMask(mask); + } - connect(m_lineEdit, &QLineEdit::textChanged, this, &ValidatorInputDialogHelper::slotEditTextChanged); + connect(m_lineEdit, &QLineEdit::textChanged, this, &ValidatorInputDialogHelper::slotEditTextChanged); - slotEditTextChanged(value); - setMinimumWidth(350); + slotEditTextChanged(value); + setMinimumWidth(350); } QLineEdit * ValidatorInputDialogHelper::lineEdit() const { - return m_lineEdit; + return m_lineEdit; } void ValidatorInputDialogHelper::slotEditTextChanged(const QString &text) { bool enabled; if (m_lineEdit->validator()) { QString str = m_lineEdit->text(); int index = m_lineEdit->cursorPosition(); enabled = (m_lineEdit->validator()->validate(str, index) == QValidator::Acceptable); } else { enabled = !text.trimmed().isEmpty(); } m_buttonBox->button(QDialogButtonBox::Ok)->setEnabled(enabled); } QString KileDialog::getText(const QString &caption, - const QString &label, const QString &value, QWidget *parent, - QValidator *validator, const QString &mask) + const QString &label, const QString &value, QWidget *parent, + QValidator *validator, const QString &mask) { ValidatorInputDialogHelper dlg(caption, label, value, parent, validator, mask); bool ok = (dlg.exec() == QDialog::Accepted); QString result; if (ok) { result = dlg.lineEdit()->text(); } // validator may explicitly allow leading and trailing whitespace if (!validator) { result = result.trimmed(); } return result; } #include "moc_validatorinputdialog_p.cpp" diff --git a/src/dialogs/validatorinputdialog.h b/src/dialogs/validatorinputdialog.h index f5ddf45d..2ae09616 100644 --- a/src/dialogs/validatorinputdialog.h +++ b/src/dialogs/validatorinputdialog.h @@ -1,63 +1,63 @@ /* * Copyright 2003 Nadeem Hasan * Copyright 2015 Andreas Cord-Landwehr * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Library 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 Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #ifndef KILEVALIDATORINPUTDIALOG_H #define KILEVALIDATORINPUTDIALOG_H #include class QDialogButtonBox; class QLineEdit; class QString; class QWidget; class QValidator; namespace KileDialog { /** * Static convenience function to get a validated string from the user. * * @p caption is the text that is displayed in the title bar. @p label is the * text that appears as a label for the line edit. @p value is the initial * value of the line edit. * * If you provide a validator, the Ok button is disabled as long as * the validator doesn't return Acceptable. If there is no validator, * the Ok button is enabled whenever the line edit isn't empty. If you * want to accept empty input, create a trivial QValidator that * always returns acceptable, e.g. QRegExpValidator with a regexp * of ".*". * * @param caption Caption of the dialog * @param label Text of the label for the line edit * @param value Initial value of the line edit * @param parent Parent of the dialog widget * @param validator A @ref QValidator to be associated with the line edit * @param mask Mask associated with the line edit. See the * documentation for @ref QLineEdit about masks * @return String user entered if Ok was pressed, else a null string */ QString getText(const QString &caption, const QString &label, - const QString &value = QString(), QWidget *parent = Q_NULLPTR, - QValidator *validator = 0, - const QString &mask = QString()); + const QString &value = QString(), QWidget *parent = Q_NULLPTR, + QValidator *validator = 0, + const QString &mask = QString()); } #endif diff --git a/src/dialogs/validatorinputdialog_p.h b/src/dialogs/validatorinputdialog_p.h index 84899631..56ed0a22 100644 --- a/src/dialogs/validatorinputdialog_p.h +++ b/src/dialogs/validatorinputdialog_p.h @@ -1,54 +1,54 @@ /* * Copyright 2003 Nadeem Hasan * Copyright 2015 Andreas Cord-Landwehr * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Library 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 Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #ifndef KILEVALIDATORINPUTDIALOG_P_H #define KILEVALIDATORINPUTDIALOG_P_H #include class QDialogButtonBox; class QLineEdit; class QString; class QWidget; class QValidator; namespace KileDialog { class ValidatorInputDialogHelper : public QDialog { - Q_OBJECT + Q_OBJECT public: - ValidatorInputDialogHelper(const QString &caption, const QString &label, - const QString &value, QWidget *parent, - QValidator *validator, const QString &mask); + ValidatorInputDialogHelper(const QString &caption, const QString &label, + const QString &value, QWidget *parent, + QValidator *validator, const QString &mask); - QLineEdit * lineEdit() const; + QLineEdit * lineEdit() const; public Q_SLOTS: - void slotEditTextChanged(const QString &value); + void slotEditTextChanged(const QString &value); private: - QLineEdit *m_lineEdit; - QDialogButtonBox *m_buttonBox; + QLineEdit *m_lineEdit; + QDialogButtonBox *m_buttonBox; }; } #endif diff --git a/src/docpart.cpp b/src/docpart.cpp index 99973aff..c1e0639c 100644 --- a/src/docpart.cpp +++ b/src/docpart.cpp @@ -1,129 +1,129 @@ /************************************************************************************************* begin : Sun Jul 29 2001 copyright : (C) 2001 - 2003 by Brachet Pascal 2004 by Jeroen Wijnhout (Jeroen.Wijnhout@kdemail.net) 2008 by Michel Ludwig (michel.ludwig@kdemail.net) *************************************************************************************************/ /*************************************************************************** * * * 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. * * * ***************************************************************************/ #include "docpart.h" #include #include #include #include #include #include #include #include #include #include "kiledebug.h" DocumentationViewer::DocumentationViewer(QWidget *parent) : KHTMLPart(parent, parent, BrowserViewGUI) { - m_hpos = 0; - QString rc = QStandardPaths::locate(QStandardPaths::DataLocation, "docpartui.rc"); - setXMLFile(rc); - KStandardAction::back(this, SLOT(back()), (QObject*)actionCollection()); - KStandardAction::forward(this, SLOT(forward()), (QObject*)actionCollection()); - KStandardAction::home(this, SLOT(home()), (QObject*)actionCollection()); + m_hpos = 0; + QString rc = QStandardPaths::locate(QStandardPaths::DataLocation, "docpartui.rc"); + setXMLFile(rc); + KStandardAction::back(this, SLOT(back()), (QObject*)actionCollection()); + KStandardAction::forward(this, SLOT(forward()), (QObject*)actionCollection()); + KStandardAction::home(this, SLOT(home()), (QObject*)actionCollection()); } DocumentationViewer::~DocumentationViewer() { } bool DocumentationViewer::urlSelected(const QString &url, int button, int state, const QString &_target, const KParts::OpenUrlArguments &args, const KParts::BrowserArguments & /* browserArgs */) { - QUrl cURL = completeURL(url); - QMimeDatabase db; - QString mime = db.mimeTypeForUrl(cURL).name(); - - //load this URL in the embedded viewer if KHTML can handle it, or when mimetype detection failed - KService::Ptr service = KService::serviceByDesktopName("khtml"); - if (db.mimeTypeForUrl(cURL).isDefault() || (service && service->hasServiceType(mime))) { - KHTMLPart::urlSelected(url, button, state, _target, args); - openUrl(cURL); - addToHistory(cURL.url()); - } - //KHTML can't handle it, look for an appropriate application - else { - KService::List offers = KMimeTypeTrader::self()->query(mime, "Type == 'Application'"); - if(offers.isEmpty()) { - KMessageBox::error(view(), i18n("No KDE service found for the MIME type \"%1\".", mime)); - return false; - } - QList lst; - lst.append(cURL); - KRun::runService(*(offers.first()), lst, view()); - } - return true; + QUrl cURL = completeURL(url); + QMimeDatabase db; + QString mime = db.mimeTypeForUrl(cURL).name(); + + //load this URL in the embedded viewer if KHTML can handle it, or when mimetype detection failed + KService::Ptr service = KService::serviceByDesktopName("khtml"); + if (db.mimeTypeForUrl(cURL).isDefault() || (service && service->hasServiceType(mime))) { + KHTMLPart::urlSelected(url, button, state, _target, args); + openUrl(cURL); + addToHistory(cURL.url()); + } + //KHTML can't handle it, look for an appropriate application + else { + KService::List offers = KMimeTypeTrader::self()->query(mime, "Type == 'Application'"); + if(offers.isEmpty()) { + KMessageBox::error(view(), i18n("No KDE service found for the MIME type \"%1\".", mime)); + return false; + } + QList lst; + lst.append(cURL); + KRun::runService(*(offers.first()), lst, view()); + } + return true; } void DocumentationViewer::home() { - if(!m_history.isEmpty()) { - openUrl(QUrl::fromLocalFile(m_history.first())); - } + if(!m_history.isEmpty()) { + openUrl(QUrl::fromLocalFile(m_history.first())); + } } void DocumentationViewer::forward() { - if(forwardEnable()) { - ++m_hpos; - openUrl(QUrl::fromLocalFile(m_history[m_hpos])); - emit updateStatus(backEnable(), forwardEnable()); - } + if(forwardEnable()) { + ++m_hpos; + openUrl(QUrl::fromLocalFile(m_history[m_hpos])); + emit updateStatus(backEnable(), forwardEnable()); + } } void DocumentationViewer::back() { - if(backEnable()) { - --m_hpos; - openUrl(QUrl::fromLocalFile(m_history[m_hpos])); - emit updateStatus(backEnable() , forwardEnable()); - } + if(backEnable()) { + --m_hpos; + openUrl(QUrl::fromLocalFile(m_history[m_hpos])); + emit updateStatus(backEnable(), forwardEnable()); + } } void DocumentationViewer::addToHistory(const QString& url) { - if(m_history.count() > 0) { - while(m_hpos < m_history.count() - 1) { - m_history.pop_back(); - } - } - - if(!m_history.isEmpty()) { - ++m_hpos; - } - - m_history.append(url); - - m_hpos = m_history.count() - 1; - emit updateStatus(backEnable(), forwardEnable()); + if(m_history.count() > 0) { + while(m_hpos < m_history.count() - 1) { + m_history.pop_back(); + } + } + + if(!m_history.isEmpty()) { + ++m_hpos; + } + + m_history.append(url); + + m_hpos = m_history.count() - 1; + emit updateStatus(backEnable(), forwardEnable()); } bool DocumentationViewer::backEnable() { - return (m_hpos > 0); + return (m_hpos > 0); } bool DocumentationViewer::forwardEnable() { - return (m_hpos < m_history.count() - 1); + return (m_hpos < m_history.count() - 1); } diff --git a/src/docpart.h b/src/docpart.h index b1afe0c8..ec509e62 100644 --- a/src/docpart.h +++ b/src/docpart.h @@ -1,55 +1,55 @@ /*********************************************************************************************** begin : Sun Jul 29 2001 copyright : (C) 2001 - 2003 by Brachet Pascal 2003 by Jeroen Wijnhout (Jeroen.Wijnhout@kdemail.net) ***********************************************************************************************/ /*************************************************************************** * * * 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. * * * ***************************************************************************/ #ifndef DOCPART_H #define DOCPART_H #include #include class DocumentationViewer : public KHTMLPart { - Q_OBJECT - - public: - DocumentationViewer(QWidget *parent = Q_NULLPTR); - ~DocumentationViewer(); - - bool backEnable(); - bool forwardEnable(); - - public Q_SLOTS: - void home(); - void forward(); - void back(); - void addToHistory(const QString& url); - - Q_SIGNALS: - void updateStatus(bool back, bool forward); - - protected: - virtual bool urlSelected(const QString &url, - int button, - int state, - const QString &_target, - const KParts::OpenUrlArguments &args = KParts::OpenUrlArguments(), - const KParts::BrowserArguments &browserArgs = KParts::BrowserArguments()); - - private: - QStringList m_history; - int m_hpos; + Q_OBJECT + +public: + DocumentationViewer(QWidget *parent = Q_NULLPTR); + ~DocumentationViewer(); + + bool backEnable(); + bool forwardEnable(); + +public Q_SLOTS: + void home(); + void forward(); + void back(); + void addToHistory(const QString& url); + +Q_SIGNALS: + void updateStatus(bool back, bool forward); + +protected: + virtual bool urlSelected(const QString &url, + int button, + int state, + const QString &_target, + const KParts::OpenUrlArguments &args = KParts::OpenUrlArguments(), + const KParts::BrowserArguments &browserArgs = KParts::BrowserArguments()); + +private: + QStringList m_history; + int m_hpos; }; #endif diff --git a/src/documentinfo.cpp b/src/documentinfo.cpp index bcc4a489..cbf46750 100644 --- a/src/documentinfo.cpp +++ b/src/documentinfo.cpp @@ -1,1189 +1,1189 @@ /********************************************************************************************* Copyright (C) 2003 by Jeroen Wijnhout (Jeroen.Wijnhout@kdemail.net) (C) 2005-2007 by Holger Danielsson (holger.danielsson@versanet.de) (C) 2006-2017 by Michel Ludwig (michel.ludwig@kdemail.net) *********************************************************************************************/ /*************************************************************************** * * * 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. * * * ***************************************************************************/ // 2005-11-02: dani // - cleaning up source of central function updateStruct() // - always use 'else if', because all conditions are exclusive or // - most often used commands are at the top // - add some new types of elements (and levels) for the structure view // - new commands, which are passed to the structure listview: // \includegraphics, \caption // - all user-defined commands for labels are recognized // - changed folder name of KileStruct::BibItem to "bibs", so that "refs" // is still unused and can be used for references (if wanted) // - \begin, \end to gather all environments. But only figure and table // environments are passed to the structure view // 2005-11-26: dani // - add support for \fref, \Fref and \eqref references commands // 2005-12-07: dani // - add support to enable and disable some structure view items // 2006-01-16 tbraun // - fix #59945 Now we call (through a signal ) project->buildProjectTree so the bib files are correct, // and therefore the keys in \cite completion // 2006-02-09 tbraun/dani // - fix #106261#4 improved parsing of (optional) command parameters // - all comments are removed //2006-09-09 mludwig // - generalising the different document types //2007-02-15 // - signal foundItem() not only sends the cursor position of the parameter, // but also the real cursor position of the command // 2007-03-12 dani // - use KileDocument::Extensions // 2007-03-24 dani // - preliminary minimal support for Beamer class // 2007-03-25 dani // - merge labels and sections in document structure view as user configurable option // 2007-04-06 dani // - add TODO/FIXME section to structure view #include "documentinfo.h" #include #include #include #include #include #include #include #include #include #include #include #include "abbreviationmanager.h" #include "codecompletion.h" #include "configurationmanager.h" #include "editorextension.h" #include "eventfilter.h" #include "kileconfig.h" #include "kiledebug.h" #include "kileviewmanager.h" #include "parser/bibtexparser.h" #include "parser/latexparser.h" #include "parser/parsermanager.h" #include "livepreview.h" #include "utilities.h" namespace KileDocument { bool Info::containsInvalidCharacters(const QUrl &url) { - QString filename = url.fileName(); - return filename.contains(" ") || filename.contains("~") || filename.contains("$") || filename.contains("#"); + QString filename = url.fileName(); + return filename.contains(" ") || filename.contains("~") || filename.contains("$") || filename.contains("#"); } QUrl Info::repairInvalidCharacters(const QUrl &url, QWidget* mainWidget, bool checkForFileExistence /* = true */) { - QUrl ret(url); - do { - bool isOK; - QString newURL = QInputDialog::getText( - mainWidget, - i18n("Invalid Characters"), - i18n("The filename contains invalid characters ($~ #).
Please provide " - "another one, or click \"Cancel\" to save anyway."), - QLineEdit::Normal, - ret.fileName(), - &isOK); - if(!isOK) { - break; - } - ret = ret.adjusted(QUrl::RemoveFilename); - ret.setPath(ret.path() + newURL); - } while(containsInvalidCharacters(ret)); - - return (checkForFileExistence ? renameIfExist(ret, mainWidget) : ret); + QUrl ret(url); + do { + bool isOK; + QString newURL = QInputDialog::getText( + mainWidget, + i18n("Invalid Characters"), + i18n("The filename contains invalid characters ($~ #).
Please provide " + "another one, or click \"Cancel\" to save anyway."), + QLineEdit::Normal, + ret.fileName(), + &isOK); + if(!isOK) { + break; + } + ret = ret.adjusted(QUrl::RemoveFilename); + ret.setPath(ret.path() + newURL); + } while(containsInvalidCharacters(ret)); + + return (checkForFileExistence ? renameIfExist(ret, mainWidget) : ret); } QUrl Info::renameIfExist(const QUrl &url, QWidget* mainWidget) { - QUrl ret(url); - - auto statJob = KIO::stat(url, KIO::StatJob::SourceSide, 0); - KJobWidgets::setWindow(statJob, mainWidget); - while (statJob->exec()) { // check for writing possibility - bool isOK; - QString newURL = QInputDialog::getText( - mainWidget, - i18n("File Already Exists"), - i18n("A file with filename '%1' already exists.
Please provide " - "another one, or click \"Cancel\" to overwrite it.", ret.fileName()), - QLineEdit::Normal, - ret.fileName(), - &isOK); - if (!isOK) { - break; - } - ret = ret.adjusted(QUrl::RemoveFilename); - ret.setPath(ret.path() + newURL); - } - return ret; + QUrl ret(url); + + auto statJob = KIO::stat(url, KIO::StatJob::SourceSide, 0); + KJobWidgets::setWindow(statJob, mainWidget); + while (statJob->exec()) { // check for writing possibility + bool isOK; + QString newURL = QInputDialog::getText( + mainWidget, + i18n("File Already Exists"), + i18n("A file with filename '%1' already exists.
Please provide " + "another one, or click \"Cancel\" to overwrite it.", ret.fileName()), + QLineEdit::Normal, + ret.fileName(), + &isOK); + if (!isOK) { + break; + } + ret = ret.adjusted(QUrl::RemoveFilename); + ret.setPath(ret.path() + newURL); + } + return ret; } QUrl Info::repairExtension(const QUrl &url, QWidget *mainWidget, bool checkForFileExistence /* = true */) { - QUrl ret(url); + QUrl ret(url); - QString filename = url.fileName(); - if(filename.contains(".") && filename[0] != '.') // There already is an extension - return ret; + QString filename = url.fileName(); + if(filename.contains(".") && filename[0] != '.') // There already is an extension + return ret; - if(KMessageBox::Yes == KMessageBox::questionYesNo(Q_NULLPTR, - i18n("The given filename has no extension; do you want one to be automatically added?"), - i18n("Missing Extension"), - KStandardGuiItem::yes(), - KStandardGuiItem::no(), - "AutomaticallyAddExtension")) - { - ret = ret.adjusted(QUrl::RemoveFilename); - ret.setPath(ret.path() + filename + ".tex"); - } - return (checkForFileExistence ? renameIfExist(ret, mainWidget) : ret); + if(KMessageBox::Yes == KMessageBox::questionYesNo(Q_NULLPTR, + i18n("The given filename has no extension; do you want one to be automatically added?"), + i18n("Missing Extension"), + KStandardGuiItem::yes(), + KStandardGuiItem::no(), + "AutomaticallyAddExtension")) + { + ret = ret.adjusted(QUrl::RemoveFilename); + ret.setPath(ret.path() + filename + ".tex"); + } + return (checkForFileExistence ? renameIfExist(ret, mainWidget) : ret); } QUrl Info::makeValidTeXURL(const QUrl &url, QWidget *mainWidget, bool istexfile, bool checkForFileExistence) { - QUrl newURL(url); + QUrl newURL(url); - //add a .tex extension - if(!istexfile) { - newURL = repairExtension(newURL, mainWidget, checkForFileExistence); - } + //add a .tex extension + if(!istexfile) { + newURL = repairExtension(newURL, mainWidget, checkForFileExistence); + } - //remove characters TeX does not accept, make sure the newURL does not exists yet - if(containsInvalidCharacters(newURL)) { - newURL = repairInvalidCharacters(newURL, mainWidget, checkForFileExistence); - } + //remove characters TeX does not accept, make sure the newURL does not exists yet + if(containsInvalidCharacters(newURL)) { + newURL = repairInvalidCharacters(newURL, mainWidget, checkForFileExistence); + } - return newURL; + return newURL; } Info::Info() : - m_bIsRoot(false), - m_dirty(false), - m_config(KSharedConfig::openConfig().data()), - documentTypePromotionAllowed(true) + m_bIsRoot(false), + m_dirty(false), + m_config(KSharedConfig::openConfig().data()), + documentTypePromotionAllowed(true) { - updateStructLevelInfo(); + updateStructLevelInfo(); } Info::~Info(void) { - KILE_DEBUG_MAIN << "DELETING DOCINFO" << this; + KILE_DEBUG_MAIN << "DELETING DOCINFO" << this; } void Info::updateStructLevelInfo() { - KILE_DEBUG_MAIN << "===void Info::updateStructLevelInfo()==="; - // read config for structureview items - m_showStructureLabels = KileConfig::svShowLabels(); - m_showStructureReferences = KileConfig::svShowReferences(); - m_showStructureBibitems = KileConfig::svShowBibitems(); - m_showStructureGraphics = KileConfig::svShowGraphics(); - m_showStructureFloats = KileConfig::svShowFloats(); - m_showStructureInputFiles = KileConfig::svShowInputFiles(); - m_showStructureTodo = KileConfig::svShowTodo(); - m_showSectioningLabels = KileConfig::svShowSectioningLabels(); - m_openStructureLabels = KileConfig::svOpenLabels(); - m_openStructureReferences = KileConfig::svOpenReferences(); - m_openStructureBibitems = KileConfig::svOpenBibitems(); - m_openStructureTodo = KileConfig::svOpenTodo(); + KILE_DEBUG_MAIN << "===void Info::updateStructLevelInfo()==="; + // read config for structureview items + m_showStructureLabels = KileConfig::svShowLabels(); + m_showStructureReferences = KileConfig::svShowReferences(); + m_showStructureBibitems = KileConfig::svShowBibitems(); + m_showStructureGraphics = KileConfig::svShowGraphics(); + m_showStructureFloats = KileConfig::svShowFloats(); + m_showStructureInputFiles = KileConfig::svShowInputFiles(); + m_showStructureTodo = KileConfig::svShowTodo(); + m_showSectioningLabels = KileConfig::svShowSectioningLabels(); + m_openStructureLabels = KileConfig::svOpenLabels(); + m_openStructureReferences = KileConfig::svOpenReferences(); + m_openStructureBibitems = KileConfig::svOpenBibitems(); + m_openStructureTodo = KileConfig::svOpenTodo(); } void Info::setBaseDirectory(const QUrl &url) { - KILE_DEBUG_MAIN << "===void Info::setBaseDirectory(const QUrl&" << url << ")==="; - m_baseDirectory = url; + KILE_DEBUG_MAIN << "===void Info::setBaseDirectory(const QUrl&" << url << ")==="; + m_baseDirectory = url; } const QUrl &Info::getBaseDirectory() const { - return m_baseDirectory; + return m_baseDirectory; } bool Info::isTextDocument() { - return false; + return false; } Type Info::getType() { - return Undefined; + return Undefined; } QLinkedList Info::getFileFilter() const { - return {}; + return {}; } bool Info::isDocumentTypePromotionAllowed() { - return documentTypePromotionAllowed; + return documentTypePromotionAllowed; } void Info::setDocumentTypePromotionAllowed(bool b) { - documentTypePromotionAllowed = b; + documentTypePromotionAllowed = b; } bool Info::isDirty() const { - return m_dirty; + return m_dirty; } void Info::setDirty(bool b) { - m_dirty = b; + m_dirty = b; } void Info::installParserOutput(KileParser::ParserOutput *parserOutput) { - Q_UNUSED(parserOutput); + Q_UNUSED(parserOutput); } QUrl Info::url() { - return QUrl(); + return QUrl(); } void Info::count(const QString& line, long *stat) { - QChar c; - int state = stStandard; - bool word = false; // we are in a word - - int lineLength = line.length(); - for(int p = 0; p < lineLength; ++p) { - c = line[p]; - - switch(state) { - case stStandard: - if(c == TEX_CAT0) { - state = stControlSequence; - ++stat[1]; - - //look ahead to avoid counting words like K\"ahler as two words - if( (p+1) < lineLength && ( !line[p+1].isPunct() || line[p+1] == '~' || line[p+1] == '^' )) { - word = false; - } - } - else if(c == TEX_CAT14) { - state = stComment; - } - else { - if (c.isLetterOrNumber()) { - //only start new word if first character is a letter (42test is still counted as a word, but 42.2 not) - if (c.isLetter() && !word) { - word = true; - ++stat[3]; - } - ++stat[0]; - } - else { - ++stat[2]; - word = false; - } - } - break; - - case stControlSequence : - if(c.isLetter()) { - // "\begin{[a-zA-z]+}" is an environment, and you can't define a command like \begin - if(line.mid(p, 5) == "begin") { - ++stat[5]; - state = stEnvironment; - stat[1] +=5; - p+=4; // after break p++ is executed - } - else if(line.mid(p, 3) == "end") { - stat[1] +=3; - state = stEnvironment; - p+=2; - } // we don't count \end as new environment, this can give wrong results in selections - else { - ++stat[4]; - ++stat[1]; - state = stCommand; - } - } - else { - ++stat[4]; - ++stat[1]; - state = stStandard; - } - break; - - case stCommand : - if(c.isLetter()) { - ++stat[1]; - } - else if(c == TEX_CAT0) { - ++stat[1]; - state = stControlSequence; - } - else if(c == TEX_CAT14) { - state = stComment; - } - else { - ++stat[2]; - state = stStandard; - } - break; - - case stEnvironment : - if(c == TEX_CAT2) { // until we find a closing } we have an environment - ++stat[1]; - state = stStandard; - } - else if(c == TEX_CAT14) { - state = stComment; - } - else { - ++stat[1]; - } - break; - - case stComment : // if we get a selection the line possibly contains \n and so the comment is only valid till \n and not necessarily till line.length() - if(c == '\n') { - ++stat[2]; // \n was counted as punctuation in the old implementation - state = stStandard; - word = false; - } - break; - - default : - qWarning() << "Unhandled state in getStatistics " << state; - break; - } - } + QChar c; + int state = stStandard; + bool word = false; // we are in a word + + int lineLength = line.length(); + for(int p = 0; p < lineLength; ++p) { + c = line[p]; + + switch(state) { + case stStandard: + if(c == TEX_CAT0) { + state = stControlSequence; + ++stat[1]; + + //look ahead to avoid counting words like K\"ahler as two words + if( (p+1) < lineLength && ( !line[p+1].isPunct() || line[p+1] == '~' || line[p+1] == '^' )) { + word = false; + } + } + else if(c == TEX_CAT14) { + state = stComment; + } + else { + if (c.isLetterOrNumber()) { + //only start new word if first character is a letter (42test is still counted as a word, but 42.2 not) + if (c.isLetter() && !word) { + word = true; + ++stat[3]; + } + ++stat[0]; + } + else { + ++stat[2]; + word = false; + } + } + break; + + case stControlSequence : + if(c.isLetter()) { + // "\begin{[a-zA-z]+}" is an environment, and you can't define a command like \begin + if(line.mid(p, 5) == "begin") { + ++stat[5]; + state = stEnvironment; + stat[1] +=5; + p+=4; // after break p++ is executed + } + else if(line.mid(p, 3) == "end") { + stat[1] +=3; + state = stEnvironment; + p+=2; + } // we don't count \end as new environment, this can give wrong results in selections + else { + ++stat[4]; + ++stat[1]; + state = stCommand; + } + } + else { + ++stat[4]; + ++stat[1]; + state = stStandard; + } + break; + + case stCommand : + if(c.isLetter()) { + ++stat[1]; + } + else if(c == TEX_CAT0) { + ++stat[1]; + state = stControlSequence; + } + else if(c == TEX_CAT14) { + state = stComment; + } + else { + ++stat[2]; + state = stStandard; + } + break; + + case stEnvironment : + if(c == TEX_CAT2) { // until we find a closing } we have an environment + ++stat[1]; + state = stStandard; + } + else if(c == TEX_CAT14) { + state = stComment; + } + else { + ++stat[1]; + } + break; + + case stComment : // if we get a selection the line possibly contains \n and so the comment is only valid till \n and not necessarily till line.length() + if(c == '\n') { + ++stat[2]; // \n was counted as punctuation in the old implementation + state = stStandard; + word = false; + } + break; + + default : + qWarning() << "Unhandled state in getStatistics " << state; + break; + } + } } void Info::updateStruct() { } void Info::updateBibItems() { } void Info::slotCompleted() { - setDirty(true); - emit completed(this); + setDirty(true); + emit completed(this); } TextInfo::TextInfo(Extensions* extensions, KileAbbreviation::Manager* abbreviationManager, KileParser::Manager* parserManager, const QString& defaultMode) -: m_doc(Q_NULLPTR), - m_defaultMode(defaultMode), - m_abbreviationManager(abbreviationManager), - m_parserManager(parserManager) + : m_doc(Q_NULLPTR), + m_defaultMode(defaultMode), + m_abbreviationManager(abbreviationManager), + m_parserManager(parserManager) { - m_arStatistics = new long[SIZE_STAT_ARRAY]; + m_arStatistics = new long[SIZE_STAT_ARRAY]; - m_extensions = extensions; - m_abbreviationCodeCompletionModel = new KileCodeCompletion::AbbreviationCompletionModel(this, m_abbreviationManager); + m_extensions = extensions; + m_abbreviationCodeCompletionModel = new KileCodeCompletion::AbbreviationCompletionModel(this, m_abbreviationManager); } TextInfo::~TextInfo() { - emit(aboutToBeDestroyed(this)); - detach(); - delete [] m_arStatistics; + emit(aboutToBeDestroyed(this)); + detach(); + delete [] m_arStatistics; } const KTextEditor::Document* TextInfo::getDoc() const { - return m_doc; + return m_doc; } KTextEditor::Document* TextInfo::getDoc() { - return m_doc; + return m_doc; } const KTextEditor::Document* TextInfo::getDocument() const { - return m_doc; + return m_doc; } KTextEditor::Document* TextInfo::getDocument() { - return m_doc; + return m_doc; } void TextInfo::setDoc(KTextEditor::Document *doc) { - setDocument(doc); + setDocument(doc); } void TextInfo::setDocument(KTextEditor::Document *doc) { - KILE_DEBUG_MAIN << "===void TextInfo::setDoc(KTextEditor::Document *doc)==="; + KILE_DEBUG_MAIN << "===void TextInfo::setDoc(KTextEditor::Document *doc)==="; - if(m_doc == doc) { - return; - } + if(m_doc == doc) { + return; + } - detach(); - if(doc) { - m_doc = doc; - m_documentContents.clear(); - connect(m_doc, SIGNAL(documentNameChanged(KTextEditor::Document*)), this, SLOT(slotFileNameChanged())); - connect(m_doc, SIGNAL(documentUrlChanged(KTextEditor::Document*)), this, SLOT(slotFileNameChanged())); - connect(m_doc, SIGNAL(completed()), this, SLOT(slotCompleted())); - connect(m_doc, SIGNAL(modifiedChanged(KTextEditor::Document*)), this, SLOT(makeDirtyIfModified())); - // this could be a KatePart bug, and as "work-around" we manually set the highlighting mode again - connect(m_doc, SIGNAL(completed()), this, SLOT(activateDefaultMode())); - setMode(m_defaultMode); - installEventFilters(); - registerCodeCompletionModels(); - } + detach(); + if(doc) { + m_doc = doc; + m_documentContents.clear(); + connect(m_doc, SIGNAL(documentNameChanged(KTextEditor::Document*)), this, SLOT(slotFileNameChanged())); + connect(m_doc, SIGNAL(documentUrlChanged(KTextEditor::Document*)), this, SLOT(slotFileNameChanged())); + connect(m_doc, SIGNAL(completed()), this, SLOT(slotCompleted())); + connect(m_doc, SIGNAL(modifiedChanged(KTextEditor::Document*)), this, SLOT(makeDirtyIfModified())); + // this could be a KatePart bug, and as "work-around" we manually set the highlighting mode again + connect(m_doc, SIGNAL(completed()), this, SLOT(activateDefaultMode())); + setMode(m_defaultMode); + installEventFilters(); + registerCodeCompletionModels(); + } } void TextInfo::detach() { - if(m_doc) { - m_doc->disconnect(this); - removeInstalledEventFilters(); - removeSignalConnections(); - unregisterCodeCompletionModels(); - emit(documentDetached(m_doc)); - } - m_doc = Q_NULLPTR; + if(m_doc) { + m_doc->disconnect(this); + removeInstalledEventFilters(); + removeSignalConnections(); + unregisterCodeCompletionModels(); + emit(documentDetached(m_doc)); + } + m_doc = Q_NULLPTR; } void TextInfo::makeDirtyIfModified() { - if(m_doc && m_doc->isModified()) { - setDirty(true); - } + if(m_doc && m_doc->isModified()) { + setDirty(true); + } } const long* TextInfo::getStatistics(KTextEditor::View *view) { - /* [0] = #c in words, [1] = #c in latex commands and environments, - [2] = #c whitespace, [3] = #words, [4] = # latex_commands, [5] = latex_environments */ - m_arStatistics[0] = m_arStatistics[1] = m_arStatistics[2] = m_arStatistics[3] = m_arStatistics[4] = m_arStatistics[5] = 0; + /* [0] = #c in words, [1] = #c in latex commands and environments, + [2] = #c whitespace, [3] = #words, [4] = # latex_commands, [5] = latex_environments */ + m_arStatistics[0] = m_arStatistics[1] = m_arStatistics[2] = m_arStatistics[3] = m_arStatistics[4] = m_arStatistics[5] = 0; - QString line; + QString line; - if(view && view->selection()) { - line = view->selectionText(); - KILE_DEBUG_MAIN << "line: " << line; - count(line, m_arStatistics); - } - else if(m_doc) { - for(int l = 0; l < m_doc->lines(); ++l) { - line = m_doc->line(l); - KILE_DEBUG_MAIN << "line : " << line; - count(line, m_arStatistics); - } - } + if(view && view->selection()) { + line = view->selectionText(); + KILE_DEBUG_MAIN << "line: " << line; + count(line, m_arStatistics); + } + else if(m_doc) { + for(int l = 0; l < m_doc->lines(); ++l) { + line = m_doc->line(l); + KILE_DEBUG_MAIN << "line : " << line; + count(line, m_arStatistics); + } + } - return m_arStatistics; + return m_arStatistics; } QUrl TextInfo::url() { - if(m_doc) { - return m_doc->url(); - } - else { - return QUrl(); - } + if(m_doc) { + return m_doc->url(); + } + else { + return QUrl(); + } } Type TextInfo::getType() { - return Text; + return Text; } bool TextInfo::isTextDocument() { - return true; + return true; } void TextInfo::setMode(const QString &mode) { - KILE_DEBUG_MAIN << "==Kile::setMode(" << m_doc->url() << "," << mode << " )=================="; + KILE_DEBUG_MAIN << "==Kile::setMode(" << m_doc->url() << "," << mode << " )=================="; - if (m_doc && !mode.isEmpty()) { - m_doc->setMode(mode); - } + if (m_doc && !mode.isEmpty()) { + m_doc->setMode(mode); + } } void TextInfo::setHighlightingMode(const QString& highlight) { - KILE_DEBUG_MAIN << "==Kile::setHighlightingMode(" << m_doc->url() << "," << highlight << " )=================="; + KILE_DEBUG_MAIN << "==Kile::setHighlightingMode(" << m_doc->url() << "," << highlight << " )=================="; - if (m_doc && !highlight.isEmpty()) { - m_doc->setHighlightingMode(highlight); - } + if (m_doc && !highlight.isEmpty()) { + m_doc->setHighlightingMode(highlight); + } } void TextInfo::setDefaultMode(const QString& string) { - m_defaultMode = string; + m_defaultMode = string; } // match a { with the corresponding } // pos is the position of the { QString TextInfo::matchBracket(QChar obracket, int &l, int &pos) { - QChar cbracket; - if(obracket == '{') { - cbracket = '}'; - } - if(obracket == '[') { - cbracket = ']'; - } - if(obracket == '(') { - cbracket = ')'; - } - - QString line, grab = ""; - int count=0, len; - ++pos; - - TodoResult todo; - while(l <= m_doc->lines()) { - line = getTextline(l,todo); - len = line.length(); - for (int i=pos; i < len; ++i) { - if(line[i] == '\\' && (line[i+1] == obracket || line[i+1] == cbracket)) { - ++i; - } - else if(line[i] == obracket) { - ++count; - } - else if(line[i] == cbracket) { - --count; - if (count < 0) { - pos = i; - return grab; - } - } - - grab += line[i]; - } - ++l; - pos = 0; - } - - return QString(); + QChar cbracket; + if(obracket == '{') { + cbracket = '}'; + } + if(obracket == '[') { + cbracket = ']'; + } + if(obracket == '(') { + cbracket = ')'; + } + + QString line, grab = ""; + int count=0, len; + ++pos; + + TodoResult todo; + while(l <= m_doc->lines()) { + line = getTextline(l,todo); + len = line.length(); + for (int i=pos; i < len; ++i) { + if(line[i] == '\\' && (line[i+1] == obracket || line[i+1] == cbracket)) { + ++i; + } + else if(line[i] == obracket) { + ++count; + } + else if(line[i] == cbracket) { + --count; + if (count < 0) { + pos = i; + return grab; + } + } + + grab += line[i]; + } + ++l; + pos = 0; + } + + return QString(); } QString TextInfo::getTextline(uint line, TodoResult &todo) { - static QRegExp reComments("[^\\\\](%.*$)"); - - todo.type = -1; - QString s = m_doc->line(line); - if(!s.isEmpty()) { - // remove comment lines - if(s[0] == '%') { - searchTodoComment(s,0,todo); - s.clear(); - } - else { - //remove escaped \ characters - s.replace("\\\\", " "); - - //remove comments - int pos = s.indexOf(reComments); - if(pos != -1) { - searchTodoComment(s, pos,todo); - s = s.left(reComments.pos(1)); - } - } - } - return s; + static QRegExp reComments("[^\\\\](%.*$)"); + + todo.type = -1; + QString s = m_doc->line(line); + if(!s.isEmpty()) { + // remove comment lines + if(s[0] == '%') { + searchTodoComment(s,0,todo); + s.clear(); + } + else { + //remove escaped \ characters + s.replace("\\\\", " "); + + //remove comments + int pos = s.indexOf(reComments); + if(pos != -1) { + searchTodoComment(s, pos,todo); + s = s.left(reComments.pos(1)); + } + } + } + return s; } void TextInfo::searchTodoComment(const QString &s, uint startpos, TodoResult &todo) { - static QRegExp reTodoComment("\\b(TODO|FIXME)\\b(:|\\s)?\\s*(.*)"); + static QRegExp reTodoComment("\\b(TODO|FIXME)\\b(:|\\s)?\\s*(.*)"); - if(s.indexOf(reTodoComment, startpos) != -1) { - todo.type = (reTodoComment.cap(1) == "TODO") ? KileStruct::ToDo : KileStruct::FixMe; - todo.colTag = reTodoComment.pos(1); - todo.colComment = reTodoComment.pos(3); - todo.comment = reTodoComment.cap(3).trimmed(); - } + if(s.indexOf(reTodoComment, startpos) != -1) { + todo.type = (reTodoComment.cap(1) == "TODO") ? KileStruct::ToDo : KileStruct::FixMe; + todo.colTag = reTodoComment.pos(1); + todo.colComment = reTodoComment.pos(3); + todo.comment = reTodoComment.cap(3).trimmed(); + } } KTextEditor::View* TextInfo::createView(QWidget *parent, const char* /* name */) { - if(!m_doc) { - return Q_NULLPTR; - } - KTextEditor::View *view = m_doc->createView(parent); - installEventFilters(view); - installSignalConnections(view); - registerCodeCompletionModels(view); - view->setStatusBarEnabled(false); - connect(view, SIGNAL(destroyed(QObject*)), this, SLOT(slotViewDestroyed(QObject*))); - return view; + if(!m_doc) { + return Q_NULLPTR; + } + KTextEditor::View *view = m_doc->createView(parent); + installEventFilters(view); + installSignalConnections(view); + registerCodeCompletionModels(view); + view->setStatusBarEnabled(false); + connect(view, SIGNAL(destroyed(QObject*)), this, SLOT(slotViewDestroyed(QObject*))); + return view; } void TextInfo::startAbbreviationCompletion(KTextEditor::View *view) { - KTextEditor::CodeCompletionInterface* completionInterface = qobject_cast(view); - if(!completionInterface) { - return; - } - KTextEditor::Range range = m_abbreviationCodeCompletionModel->completionRange(view, view->cursorPosition()); - if(!range.isValid()) { - range = KTextEditor::Range(view->cursorPosition(), view->cursorPosition()); - } - completionInterface->startCompletion(range, m_abbreviationCodeCompletionModel); + KTextEditor::CodeCompletionInterface* completionInterface = qobject_cast(view); + if(!completionInterface) { + return; + } + KTextEditor::Range range = m_abbreviationCodeCompletionModel->completionRange(view, view->cursorPosition()); + if(!range.isValid()) { + range = KTextEditor::Range(view->cursorPosition(), view->cursorPosition()); + } + completionInterface->startCompletion(range, m_abbreviationCodeCompletionModel); } void TextInfo::slotFileNameChanged() { - emit urlChanged(this, url()); + emit urlChanged(this, url()); } void TextInfo::installEventFilters(KTextEditor::View *view) { - if(m_eventFilterHash.find(view) != m_eventFilterHash.end()) { - return; - } + if(m_eventFilterHash.find(view) != m_eventFilterHash.end()) { + return; + } - QList eventFilterList = createEventFilters(view); - if(!eventFilterList.isEmpty()) { - for(QList::iterator i = eventFilterList.begin(); i != eventFilterList.end(); ++i) { - QObject* eventFilter = *i; - KileView::Manager::installEventFilter(view, eventFilter); - } - m_eventFilterHash[view] = eventFilterList; - } + QList eventFilterList = createEventFilters(view); + if(!eventFilterList.isEmpty()) { + for(QList::iterator i = eventFilterList.begin(); i != eventFilterList.end(); ++i) { + QObject* eventFilter = *i; + KileView::Manager::installEventFilter(view, eventFilter); + } + m_eventFilterHash[view] = eventFilterList; + } } void TextInfo::removeInstalledEventFilters(KTextEditor::View *view) { - QHash >::iterator i = m_eventFilterHash.find(view); - if(i != m_eventFilterHash.end()) { - QList eventFilterList = *i; - for(QList::iterator i2 = eventFilterList.begin(); i2 != eventFilterList.end(); ++i2) { - QObject *eventFilter = *i2; - KileView::Manager::removeEventFilter(view, eventFilter); - delete(*i2); - } - m_eventFilterHash.erase(i); - } + QHash >::iterator i = m_eventFilterHash.find(view); + if(i != m_eventFilterHash.end()) { + QList eventFilterList = *i; + for(QList::iterator i2 = eventFilterList.begin(); i2 != eventFilterList.end(); ++i2) { + QObject *eventFilter = *i2; + KileView::Manager::removeEventFilter(view, eventFilter); + delete(*i2); + } + m_eventFilterHash.erase(i); + } } QList TextInfo::createEventFilters(KTextEditor::View* /* view */) { - return QList(); + return QList(); } void TextInfo::installEventFilters() { - if(!m_doc) { - return; - } - QList views = m_doc->views(); - for(QList::iterator i = views.begin(); i != views.end(); ++i) { - installEventFilters(*i); - } + if(!m_doc) { + return; + } + QList views = m_doc->views(); + for(QList::iterator i = views.begin(); i != views.end(); ++i) { + installEventFilters(*i); + } } void TextInfo::removeInstalledEventFilters() { - if(!m_doc) { - return; - } - QList views = m_doc->views(); - for(QList::iterator i = views.begin(); i != views.end(); ++i) { - removeInstalledEventFilters(*i); - } + if(!m_doc) { + return; + } + QList views = m_doc->views(); + for(QList::iterator i = views.begin(); i != views.end(); ++i) { + removeInstalledEventFilters(*i); + } } void TextInfo::installSignalConnections(KTextEditor::View *) { - /* does nothing */ + /* does nothing */ } void TextInfo::removeSignalConnections(KTextEditor::View *) { - /* does nothing */ + /* does nothing */ } void TextInfo::installSignalConnections() { - if(!m_doc) { - return; - } - QList views = m_doc->views(); - for(QList::iterator i = views.begin(); i != views.end(); ++i) { - installSignalConnections(*i); - } + if(!m_doc) { + return; + } + QList views = m_doc->views(); + for(QList::iterator i = views.begin(); i != views.end(); ++i) { + installSignalConnections(*i); + } } void TextInfo::removeSignalConnections() { - if(!m_doc) { - return; - } - QList views = m_doc->views(); - for(QList::iterator i = views.begin(); i != views.end(); ++i) { - removeSignalConnections(*i); - } + if(!m_doc) { + return; + } + QList views = m_doc->views(); + for(QList::iterator i = views.begin(); i != views.end(); ++i) { + removeSignalConnections(*i); + } } void TextInfo::registerCodeCompletionModels(KTextEditor::View *view) { - KTextEditor::CodeCompletionInterface* completionInterface = qobject_cast(view); - if(!completionInterface) { - return; - } - completionInterface->registerCompletionModel(m_abbreviationCodeCompletionModel); - completionInterface->setAutomaticInvocationEnabled(true); + KTextEditor::CodeCompletionInterface* completionInterface = qobject_cast(view); + if(!completionInterface) { + return; + } + completionInterface->registerCompletionModel(m_abbreviationCodeCompletionModel); + completionInterface->setAutomaticInvocationEnabled(true); } void TextInfo::unregisterCodeCompletionModels(KTextEditor::View *view) { - KTextEditor::CodeCompletionInterface* completionInterface = qobject_cast(view); - if(!completionInterface) { - return; - } - completionInterface->unregisterCompletionModel(m_abbreviationCodeCompletionModel); + KTextEditor::CodeCompletionInterface* completionInterface = qobject_cast(view); + if(!completionInterface) { + return; + } + completionInterface->unregisterCompletionModel(m_abbreviationCodeCompletionModel); } void TextInfo::registerCodeCompletionModels() { - if(!m_doc) { - return; - } - QList views = m_doc->views(); - for(QList::iterator i = views.begin(); i != views.end(); ++i) { - registerCodeCompletionModels(*i); - } + if(!m_doc) { + return; + } + QList views = m_doc->views(); + for(QList::iterator i = views.begin(); i != views.end(); ++i) { + registerCodeCompletionModels(*i); + } } void TextInfo::unregisterCodeCompletionModels() { - if(!m_doc) { - return; - } - QList views = m_doc->views(); - for(QList::iterator i = views.begin(); i != views.end(); ++i) { - unregisterCodeCompletionModels(*i); - } + if(!m_doc) { + return; + } + QList views = m_doc->views(); + for(QList::iterator i = views.begin(); i != views.end(); ++i) { + unregisterCodeCompletionModels(*i); + } } void TextInfo::slotViewDestroyed(QObject *object) { - KTextEditor::View* view = dynamic_cast(object); - if(view) { - removeInstalledEventFilters(view); - removeSignalConnections(view); - unregisterCodeCompletionModels(view); - QHash >::iterator i = m_eventFilterHash.find(view); - if(i != m_eventFilterHash.end()) { - m_eventFilterHash.erase(i); - } - } + KTextEditor::View* view = dynamic_cast(object); + if(view) { + removeInstalledEventFilters(view); + removeSignalConnections(view); + unregisterCodeCompletionModels(view); + QHash >::iterator i = m_eventFilterHash.find(view); + if(i != m_eventFilterHash.end()) { + m_eventFilterHash.erase(i); + } + } } void TextInfo::activateDefaultMode() { - KILE_DEBUG_MAIN << "m_defaultMode = " << m_defaultMode << endl; + KILE_DEBUG_MAIN << "m_defaultMode = " << m_defaultMode << endl; - if(m_doc && !m_defaultMode.isEmpty()) { - m_doc->setMode(m_defaultMode); - } + if(m_doc && !m_defaultMode.isEmpty()) { + m_doc->setMode(m_defaultMode); + } } const QStringList TextInfo::documentContents() const { - if (m_doc) { - return m_doc->textLines(m_doc->documentRange()); - } - else { - return m_documentContents; - } + if (m_doc) { + return m_doc->textLines(m_doc->documentRange()); + } + else { + return m_documentContents; + } } void TextInfo::setDocumentContents(const QStringList& contents) { - m_documentContents = contents; + m_documentContents = contents; } LaTeXInfo::LaTeXInfo(Extensions* extensions, KileAbbreviation::Manager* abbreviationManager, LatexCommands* commands, EditorExtension* editorExtension, KileConfiguration::Manager* manager, KileCodeCompletion::Manager* codeCompletionManager, KileTool::LivePreviewManager* livePreviewManager, KileView::Manager *viewManager, KileParser::Manager* parserManager) -: TextInfo(extensions, abbreviationManager, parserManager, "LaTeX"), - m_commands(commands), - m_editorExtension(editorExtension), - m_configurationManager(manager), - m_eventFilter(Q_NULLPTR), - m_livePreviewManager(livePreviewManager), - m_viewManager(viewManager) + : TextInfo(extensions, abbreviationManager, parserManager, "LaTeX"), + m_commands(commands), + m_editorExtension(editorExtension), + m_configurationManager(manager), + m_eventFilter(Q_NULLPTR), + m_livePreviewManager(livePreviewManager), + m_viewManager(viewManager) { - documentTypePromotionAllowed = false; - updateStructLevelInfo(); - m_latexCompletionModel = new KileCodeCompletion::LaTeXCompletionModel(this, - codeCompletionManager, - editorExtension); + documentTypePromotionAllowed = false; + updateStructLevelInfo(); + m_latexCompletionModel = new KileCodeCompletion::LaTeXCompletionModel(this, + codeCompletionManager, + editorExtension); } LaTeXInfo::~LaTeXInfo() { } Type LaTeXInfo::getType() { - return LaTeX; + return LaTeX; } QLinkedList LaTeXInfo::getFileFilter() const { - return {Extensions::TEX, Extensions::PACKAGES}; + return {Extensions::TEX, Extensions::PACKAGES}; } void LaTeXInfo::startLaTeXCompletion(KTextEditor::View *view) { - KTextEditor::CodeCompletionInterface* completionInterface = qobject_cast(view); - if(!completionInterface) { - return; - } - KTextEditor::Range range = m_latexCompletionModel->completionRange(view, view->cursorPosition()); - if(!range.isValid()) { - range = KTextEditor::Range(view->cursorPosition(), view->cursorPosition()); - } - completionInterface->startCompletion(range, m_latexCompletionModel); + KTextEditor::CodeCompletionInterface* completionInterface = qobject_cast(view); + if(!completionInterface) { + return; + } + KTextEditor::Range range = m_latexCompletionModel->completionRange(view, view->cursorPosition()); + if(!range.isValid()) { + range = KTextEditor::Range(view->cursorPosition(), view->cursorPosition()); + } + completionInterface->startCompletion(range, m_latexCompletionModel); } void LaTeXInfo::updateStructLevelInfo() { - KILE_DEBUG_MAIN << "===void LaTeXInfo::updateStructLevelInfo()==="; - - // read config stuff - Info::updateStructLevelInfo(); - - // clear all entries - m_dictStructLevel.clear(); - - //TODO: make sectioning and bibliography configurable - - // sectioning - m_dictStructLevel["\\part"] = KileStructData(1, KileStruct::Sect, "part"); - m_dictStructLevel["\\chapter"] = KileStructData(2, KileStruct::Sect, "chapter"); - m_dictStructLevel["\\section"] = KileStructData(3, KileStruct::Sect, "section"); - m_dictStructLevel["\\subsection"] = KileStructData(4, KileStruct::Sect, "subsection"); - m_dictStructLevel["\\subsubsection"] = KileStructData(5, KileStruct::Sect, "subsubsection"); - m_dictStructLevel["\\paragraph"] = KileStructData(6, KileStruct::Sect, "subsubsection"); - m_dictStructLevel["\\subparagraph"] = KileStructData(7, KileStruct::Sect, "subsubsection"); - - // hidden commands - m_dictStructLevel["\\usepackage"] = KileStructData(KileStruct::Hidden, KileStruct::Package); - m_dictStructLevel["\\newcommand"] = KileStructData(KileStruct::Hidden, KileStruct::NewCommand); - m_dictStructLevel["\\newlength"] = KileStructData(KileStruct::Hidden, KileStruct::NewCommand); - m_dictStructLevel["\\newenvironment"] = KileStructData(KileStruct::Hidden, KileStruct::NewEnvironment); - m_dictStructLevel["\\addunit"] = KileStructData(KileStruct::Hidden, KileStruct::NewCommand); // hack to get support for the fancyunits package until we can configure the commands in the gui (tbraun) - m_dictStructLevel["\\DeclareMathOperator"] = KileStructData(KileStruct::Hidden, KileStruct::NewCommand); // amsmath package - m_dictStructLevel["\\caption"] = KileStructData(KileStruct::Hidden,KileStruct::Caption); - - // bibitems - if(m_showStructureBibitems) { - m_dictStructLevel["\\bibitem"] = KileStructData(KileStruct::NotSpecified, KileStruct::BibItem, QString(), "bibs"); - } - - // graphics - if(m_showStructureGraphics) { - m_dictStructLevel["\\includegraphics"] = KileStructData(KileStruct::Object,KileStruct::Graphics, "graphics"); - } - - // float environments - if(m_showStructureFloats) { - m_dictStructLevel["\\begin"] = KileStructData(KileStruct::Object,KileStruct::BeginEnv); - m_dictStructLevel["\\end"] = KileStructData(KileStruct::Hidden,KileStruct::EndEnv); - - // some entries, which could never be found (but they are set manually) - m_dictStructLevel["\\begin{figure}"]=KileStructData(KileStruct::Object,KileStruct::BeginFloat, "figure-env"); - m_dictStructLevel["\\begin{figure*}"]=KileStructData(KileStruct::Object,KileStruct::BeginFloat, "figure-env"); - m_dictStructLevel["\\begin{table}"]=KileStructData(KileStruct::Object,KileStruct::BeginFloat, "table-env"); - m_dictStructLevel["\\begin{table*}"]=KileStructData(KileStruct::Object,KileStruct::BeginFloat, "table-env"); - m_dictStructLevel["\\begin{asy}"]=KileStructData(KileStruct::Object,KileStruct::BeginFloat, "image-x-generic"); - m_dictStructLevel["\\end{float}"]=KileStructData(KileStruct::Hidden,KileStruct::EndFloat); - } - - // preliminary minimal beamer support - m_dictStructLevel["\\frame"] = KileStructData(KileStruct::Object, KileStruct::BeamerFrame, "beamerframe"); - m_dictStructLevel["\\frametitle"] = KileStructData(KileStruct::Hidden, KileStruct::BeamerFrametitle); - m_dictStructLevel["\\begin{frame}"] = KileStructData(KileStruct::Object, KileStruct::BeamerBeginFrame, "beamerframe"); - m_dictStructLevel["\\end{frame}"] = KileStructData(KileStruct::Hidden, KileStruct::BeamerEndFrame); - m_dictStructLevel["\\begin{block}"] = KileStructData(KileStruct::Object, KileStruct::BeamerBeginBlock, "beamerblock"); - - // add user-defined commands - - QStringList list; - QStringList::ConstIterator it; - - // labels, we also gather them - m_commands->commandList(list,KileDocument::CmdAttrLabel, false); - for(it=list.constBegin(); it != list.constEnd(); ++it) { - m_dictStructLevel[*it] = KileStructData(KileStruct::NotSpecified, KileStruct::Label, QString(), "labels"); - } - - // input files - if(m_showStructureInputFiles) { - m_commands->commandList(list, KileDocument::CmdAttrIncludes, false); - for(it = list.constBegin(); it != list.constEnd(); ++it) { - m_dictStructLevel[*it] = KileStructData(KileStruct::File, KileStruct::Input, "input-file"); - } - } - - // references - if(m_showStructureReferences) { - m_commands->commandList(list, KileDocument::CmdAttrReference, false); - for(it=list.constBegin(); it != list.constEnd(); ++it ) { - m_dictStructLevel[*it] = KileStructData(KileStruct::Hidden, KileStruct::Reference); - } - } - - //bibliography commands - m_commands->commandList(list,KileDocument::CmdAttrBibliographies, false); - for(it=list.constBegin(); it != list.constEnd(); ++it) { - m_dictStructLevel[*it] = KileStructData(0, KileStruct::Bibliography, "viewbib"); - } + KILE_DEBUG_MAIN << "===void LaTeXInfo::updateStructLevelInfo()==="; + + // read config stuff + Info::updateStructLevelInfo(); + + // clear all entries + m_dictStructLevel.clear(); + + //TODO: make sectioning and bibliography configurable + + // sectioning + m_dictStructLevel["\\part"] = KileStructData(1, KileStruct::Sect, "part"); + m_dictStructLevel["\\chapter"] = KileStructData(2, KileStruct::Sect, "chapter"); + m_dictStructLevel["\\section"] = KileStructData(3, KileStruct::Sect, "section"); + m_dictStructLevel["\\subsection"] = KileStructData(4, KileStruct::Sect, "subsection"); + m_dictStructLevel["\\subsubsection"] = KileStructData(5, KileStruct::Sect, "subsubsection"); + m_dictStructLevel["\\paragraph"] = KileStructData(6, KileStruct::Sect, "subsubsection"); + m_dictStructLevel["\\subparagraph"] = KileStructData(7, KileStruct::Sect, "subsubsection"); + + // hidden commands + m_dictStructLevel["\\usepackage"] = KileStructData(KileStruct::Hidden, KileStruct::Package); + m_dictStructLevel["\\newcommand"] = KileStructData(KileStruct::Hidden, KileStruct::NewCommand); + m_dictStructLevel["\\newlength"] = KileStructData(KileStruct::Hidden, KileStruct::NewCommand); + m_dictStructLevel["\\newenvironment"] = KileStructData(KileStruct::Hidden, KileStruct::NewEnvironment); + m_dictStructLevel["\\addunit"] = KileStructData(KileStruct::Hidden, KileStruct::NewCommand); // hack to get support for the fancyunits package until we can configure the commands in the gui (tbraun) + m_dictStructLevel["\\DeclareMathOperator"] = KileStructData(KileStruct::Hidden, KileStruct::NewCommand); // amsmath package + m_dictStructLevel["\\caption"] = KileStructData(KileStruct::Hidden,KileStruct::Caption); + + // bibitems + if(m_showStructureBibitems) { + m_dictStructLevel["\\bibitem"] = KileStructData(KileStruct::NotSpecified, KileStruct::BibItem, QString(), "bibs"); + } + + // graphics + if(m_showStructureGraphics) { + m_dictStructLevel["\\includegraphics"] = KileStructData(KileStruct::Object,KileStruct::Graphics, "graphics"); + } + + // float environments + if(m_showStructureFloats) { + m_dictStructLevel["\\begin"] = KileStructData(KileStruct::Object,KileStruct::BeginEnv); + m_dictStructLevel["\\end"] = KileStructData(KileStruct::Hidden,KileStruct::EndEnv); + + // some entries, which could never be found (but they are set manually) + m_dictStructLevel["\\begin{figure}"]=KileStructData(KileStruct::Object,KileStruct::BeginFloat, "figure-env"); + m_dictStructLevel["\\begin{figure*}"]=KileStructData(KileStruct::Object,KileStruct::BeginFloat, "figure-env"); + m_dictStructLevel["\\begin{table}"]=KileStructData(KileStruct::Object,KileStruct::BeginFloat, "table-env"); + m_dictStructLevel["\\begin{table*}"]=KileStructData(KileStruct::Object,KileStruct::BeginFloat, "table-env"); + m_dictStructLevel["\\begin{asy}"]=KileStructData(KileStruct::Object,KileStruct::BeginFloat, "image-x-generic"); + m_dictStructLevel["\\end{float}"]=KileStructData(KileStruct::Hidden,KileStruct::EndFloat); + } + + // preliminary minimal beamer support + m_dictStructLevel["\\frame"] = KileStructData(KileStruct::Object, KileStruct::BeamerFrame, "beamerframe"); + m_dictStructLevel["\\frametitle"] = KileStructData(KileStruct::Hidden, KileStruct::BeamerFrametitle); + m_dictStructLevel["\\begin{frame}"] = KileStructData(KileStruct::Object, KileStruct::BeamerBeginFrame, "beamerframe"); + m_dictStructLevel["\\end{frame}"] = KileStructData(KileStruct::Hidden, KileStruct::BeamerEndFrame); + m_dictStructLevel["\\begin{block}"] = KileStructData(KileStruct::Object, KileStruct::BeamerBeginBlock, "beamerblock"); + + // add user-defined commands + + QStringList list; + QStringList::ConstIterator it; + + // labels, we also gather them + m_commands->commandList(list,KileDocument::CmdAttrLabel, false); + for(it=list.constBegin(); it != list.constEnd(); ++it) { + m_dictStructLevel[*it] = KileStructData(KileStruct::NotSpecified, KileStruct::Label, QString(), "labels"); + } + + // input files + if(m_showStructureInputFiles) { + m_commands->commandList(list, KileDocument::CmdAttrIncludes, false); + for(it = list.constBegin(); it != list.constEnd(); ++it) { + m_dictStructLevel[*it] = KileStructData(KileStruct::File, KileStruct::Input, "input-file"); + } + } + + // references + if(m_showStructureReferences) { + m_commands->commandList(list, KileDocument::CmdAttrReference, false); + for(it=list.constBegin(); it != list.constEnd(); ++it ) { + m_dictStructLevel[*it] = KileStructData(KileStruct::Hidden, KileStruct::Reference); + } + } + + //bibliography commands + m_commands->commandList(list,KileDocument::CmdAttrBibliographies, false); + for(it=list.constBegin(); it != list.constEnd(); ++it) { + m_dictStructLevel[*it] = KileStructData(0, KileStruct::Bibliography, "viewbib"); + } } QList LaTeXInfo::createEventFilters(KTextEditor::View *view) { - QList toReturn; - QObject *eventFilter = new LaTeXEventFilter(view, m_editorExtension); - connect(m_configurationManager, SIGNAL(configChanged()), eventFilter, SLOT(readConfig())); - toReturn << eventFilter; - return toReturn; + QList toReturn; + QObject *eventFilter = new LaTeXEventFilter(view, m_editorExtension); + connect(m_configurationManager, SIGNAL(configChanged()), eventFilter, SLOT(readConfig())); + toReturn << eventFilter; + return toReturn; } void LaTeXInfo::installSignalConnections(KTextEditor::View *view) { - connect(view, &KTextEditor::View::cursorPositionChanged, - m_viewManager, &KileView::Manager::handleCursorPositionChanged); - connect(view->document(), &KTextEditor::Document::textChanged, - m_livePreviewManager, &KileTool::LivePreviewManager::handleTextChanged, Qt::UniqueConnection); - connect(view->document(), &KTextEditor::Document::documentSavedOrUploaded, - m_livePreviewManager, &KileTool::LivePreviewManager::handleDocumentSavedOrUploaded, Qt::UniqueConnection); + connect(view, &KTextEditor::View::cursorPositionChanged, + m_viewManager, &KileView::Manager::handleCursorPositionChanged); + connect(view->document(), &KTextEditor::Document::textChanged, + m_livePreviewManager, &KileTool::LivePreviewManager::handleTextChanged, Qt::UniqueConnection); + connect(view->document(), &KTextEditor::Document::documentSavedOrUploaded, + m_livePreviewManager, &KileTool::LivePreviewManager::handleDocumentSavedOrUploaded, Qt::UniqueConnection); } void LaTeXInfo::removeSignalConnections(KTextEditor::View *view) { - disconnect(view, &KTextEditor::View::cursorPositionChanged, - m_viewManager, &KileView::Manager::handleCursorPositionChanged); - disconnect(view->document(), &KTextEditor::Document::textChanged, - m_livePreviewManager, &KileTool::LivePreviewManager::handleTextChanged); - disconnect(view->document(), &KTextEditor::Document::documentSavedOrUploaded, - m_livePreviewManager, &KileTool::LivePreviewManager::handleDocumentSavedOrUploaded); + disconnect(view, &KTextEditor::View::cursorPositionChanged, + m_viewManager, &KileView::Manager::handleCursorPositionChanged); + disconnect(view->document(), &KTextEditor::Document::textChanged, + m_livePreviewManager, &KileTool::LivePreviewManager::handleTextChanged); + disconnect(view->document(), &KTextEditor::Document::documentSavedOrUploaded, + m_livePreviewManager, &KileTool::LivePreviewManager::handleDocumentSavedOrUploaded); } void LaTeXInfo::registerCodeCompletionModels(KTextEditor::View *view) { - KTextEditor::CodeCompletionInterface* completionInterface = qobject_cast(view); - if(!completionInterface) { - return; - } - completionInterface->registerCompletionModel(m_latexCompletionModel); - completionInterface->setAutomaticInvocationEnabled(true); - TextInfo::registerCodeCompletionModels(view); + KTextEditor::CodeCompletionInterface* completionInterface = qobject_cast(view); + if(!completionInterface) { + return; + } + completionInterface->registerCompletionModel(m_latexCompletionModel); + completionInterface->setAutomaticInvocationEnabled(true); + TextInfo::registerCodeCompletionModels(view); } void LaTeXInfo::unregisterCodeCompletionModels(KTextEditor::View *view) { - KTextEditor::CodeCompletionInterface* completionInterface = qobject_cast(view); - if(!completionInterface) { - return; - } - completionInterface->unregisterCompletionModel(m_latexCompletionModel); - TextInfo::unregisterCodeCompletionModels(view); + KTextEditor::CodeCompletionInterface* completionInterface = qobject_cast(view); + if(!completionInterface) { + return; + } + completionInterface->unregisterCompletionModel(m_latexCompletionModel); + TextInfo::unregisterCodeCompletionModels(view); } BracketResult LaTeXInfo::matchBracket(int &l, int &pos) { - BracketResult result; - TodoResult todo; - - if(m_doc->line(l)[pos] == '[') { - result.option = TextInfo::matchBracket('[', l, pos); - int p = 0; - while(l < m_doc->lines()) { - if((p = getTextline(l, todo).indexOf('{', pos)) != -1) { - pos = p; - break; - } - else { - pos = 0; - ++l; - } - } - } - - if(m_doc->line(l)[pos] == '{') { - result.line = l; - result.col = pos; - result.value = TextInfo::matchBracket('{', l, pos); - } - - return result; + BracketResult result; + TodoResult todo; + + if(m_doc->line(l)[pos] == '[') { + result.option = TextInfo::matchBracket('[', l, pos); + int p = 0; + while(l < m_doc->lines()) { + if((p = getTextline(l, todo).indexOf('{', pos)) != -1) { + pos = p; + break; + } + else { + pos = 0; + ++l; + } + } + } + + if(m_doc->line(l)[pos] == '{') { + result.line = l; + result.col = pos; + result.value = TextInfo::matchBracket('{', l, pos); + } + + return result; } void LaTeXInfo::updateStruct() { - KILE_DEBUG_MAIN << "==void TeXInfo::updateStruct: (" << url() << ")========="; + KILE_DEBUG_MAIN << "==void TeXInfo::updateStruct: (" << url() << ")========="; - m_parserManager->parseDocument(this); + m_parserManager->parseDocument(this); } void LaTeXInfo::checkChangedDeps() { - if(m_depsPrev != m_deps) { - KILE_DEBUG_MAIN << "===void LaTeXInfo::checkChangedDeps()===, deps have changed"<< endl; - emit(depChanged()); - m_depsPrev = m_deps; - } + if(m_depsPrev != m_deps) { + KILE_DEBUG_MAIN << "===void LaTeXInfo::checkChangedDeps()===, deps have changed"<< endl; + emit(depChanged()); + m_depsPrev = m_deps; + } } void LaTeXInfo::installParserOutput(KileParser::ParserOutput *parserOutput) { - KILE_DEBUG_MAIN; - KileParser::LaTeXParserOutput *latexParserOutput = dynamic_cast(parserOutput); - Q_ASSERT(latexParserOutput); - if(!latexParserOutput) { - KILE_DEBUG_MAIN << "wrong type given"; - return; - } - - m_labels = latexParserOutput->labels; - m_bibItems = latexParserOutput->bibItems; - m_deps = latexParserOutput->deps; - m_bibliography = latexParserOutput->bibliography; - m_packages = latexParserOutput->packages; - m_newCommands = latexParserOutput->newCommands; - m_asyFigures = latexParserOutput->asyFigures; - m_preamble = latexParserOutput->preamble; - m_bIsRoot = latexParserOutput->bIsRoot; - - checkChangedDeps(); - emit(isrootChanged(isLaTeXRoot())); - setDirty(false); - emit(parsingComplete()); + KILE_DEBUG_MAIN; + KileParser::LaTeXParserOutput *latexParserOutput = dynamic_cast(parserOutput); + Q_ASSERT(latexParserOutput); + if(!latexParserOutput) { + KILE_DEBUG_MAIN << "wrong type given"; + return; + } + + m_labels = latexParserOutput->labels; + m_bibItems = latexParserOutput->bibItems; + m_deps = latexParserOutput->deps; + m_bibliography = latexParserOutput->bibliography; + m_packages = latexParserOutput->packages; + m_newCommands = latexParserOutput->newCommands; + m_asyFigures = latexParserOutput->asyFigures; + m_preamble = latexParserOutput->preamble; + m_bIsRoot = latexParserOutput->bIsRoot; + + checkChangedDeps(); + emit(isrootChanged(isLaTeXRoot())); + setDirty(false); + emit(parsingComplete()); } BibInfo::BibInfo(Extensions* extensions, KileAbbreviation::Manager* abbreviationManager, KileParser::Manager* parserManager, LatexCommands* /* commands */) -: TextInfo(extensions, abbreviationManager, parserManager, "BibTeX") + : TextInfo(extensions, abbreviationManager, parserManager, "BibTeX") { - documentTypePromotionAllowed = false; + documentTypePromotionAllowed = false; } BibInfo::~BibInfo() { } bool BibInfo::isLaTeXRoot() { - return false; + return false; } void BibInfo::updateStruct() { - m_parserManager->parseDocument(this); + m_parserManager->parseDocument(this); } void BibInfo::installParserOutput(KileParser::ParserOutput *parserOutput) { - KILE_DEBUG_MAIN; - KileParser::BibTeXParserOutput *bibtexParserOutput = dynamic_cast(parserOutput); - Q_ASSERT(bibtexParserOutput); - if(!bibtexParserOutput) { - KILE_DEBUG_MAIN << "wrong type given"; - return; - } + KILE_DEBUG_MAIN; + KileParser::BibTeXParserOutput *bibtexParserOutput = dynamic_cast(parserOutput); + Q_ASSERT(bibtexParserOutput); + if(!bibtexParserOutput) { + KILE_DEBUG_MAIN << "wrong type given"; + return; + } - m_bibItems = bibtexParserOutput->bibItems; + m_bibItems = bibtexParserOutput->bibItems; - setDirty(false); - emit(parsingComplete()); + setDirty(false); + emit(parsingComplete()); } Type BibInfo::getType() { - return BibTeX; + return BibTeX; } QLinkedList BibInfo::getFileFilter() const { - return {Extensions::BIB}; + return {Extensions::BIB}; } ScriptInfo::ScriptInfo(Extensions* extensions, KileAbbreviation::Manager* abbreviationManager, KileParser::Manager* parserManager) -: TextInfo(extensions, abbreviationManager, parserManager, "JavaScript") + : TextInfo(extensions, abbreviationManager, parserManager, "JavaScript") { - documentTypePromotionAllowed = false; + documentTypePromotionAllowed = false; } ScriptInfo::~ScriptInfo() { } bool ScriptInfo::isLaTeXRoot() { - return false; + return false; } Type ScriptInfo::getType() { - return Script; + return Script; } QLinkedList ScriptInfo::getFileFilter() const { - return {Extensions::JS}; + return {Extensions::JS}; } } diff --git a/src/documentinfo.h b/src/documentinfo.h index c64ee1a9..04b3b5e6 100644 --- a/src/documentinfo.h +++ b/src/documentinfo.h @@ -1,522 +1,569 @@ /************************************************************************************* Copyright (C) 2003 by Jeroen Wijnhout (Jeroen.Wijnhout@kdemail.net) (C) 2006-2017 by Michel Ludwig (michel.ludwig@kdemail.net) *************************************************************************************/ /*************************************************************************** * * * 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. * * * ***************************************************************************/ #ifndef DOCUMENTINFO_H #define DOCUMENTINFO_H #include #include #include #include "kiledebug.h" #include #include "kileconstants.h" #include "kileextensions.h" #include "livepreview_utils.h" #include "outputinfo.h" #define TEX_CAT0 '\\' #define TEX_CAT1 '{' #define TEX_CAT2 '}' #define TEX_CAT3 '$' #define TEX_CAT4 '&' #define TEX_CAT6 '#' #define TEX_CAT7 '^' #define TEX_CAT8 '_' #define TEX_CAT13 '~' #define TEX_CAT14 '%' #define SIZE_STAT_ARRAY 6 -namespace KileDocument { class EditorExtension; } -namespace KileConfiguration { class Manager; } -namespace KileCodeCompletion { class LaTeXCompletionModel; class AbbreviationCompletionModel; class Manager; } -namespace KileAbbreviation { class Manager; } -namespace KileTool { class LivePreviewManager; } -namespace KileParser { class ParserOutput; class Manager; } -namespace KileView { class Manager; } +namespace KileDocument { +class EditorExtension; +} +namespace KileConfiguration { +class Manager; +} +namespace KileCodeCompletion { +class LaTeXCompletionModel; +class AbbreviationCompletionModel; +class Manager; +} +namespace KileAbbreviation { +class Manager; +} +namespace KileTool { +class LivePreviewManager; +} +namespace KileParser { +class ParserOutput; +class Manager; +} +namespace KileView { +class Manager; +} namespace KileStruct { - //Different types of elements in the structure view - enum - { - None = 0x1, Label = 0x2, Sect = 0x4, Input = 0x8, - BibItem = 0x10, Bibliography = 0x20, Package = 0x40, NewCommand = 0x80, - Graphics = 0x100, Reference = 0x200, BeginEnv = 0x400, EndEnv = 0x800, - BeginFloat = 0x1000, EndFloat = 0x2000, Caption = 0x4000, BeamerFrame = 0x8000, - BeamerBeginFrame = 0x10000, BeamerEndFrame = 0x20000, BeamerFrametitle = 0x40000, BeamerBeginBlock = 0x80000, - ToDo = 0x100000, FixMe = 0x200000, NewEnvironment = 0x400000 - }; - - //Different levels (in the parent-child hierarchy) in the structure view - enum - { - Hidden = -4, NotSpecified = -3, Object = -2, File = -1 - }; +//Different types of elements in the structure view +enum +{ + None = 0x1, Label = 0x2, Sect = 0x4, Input = 0x8, + BibItem = 0x10, Bibliography = 0x20, Package = 0x40, NewCommand = 0x80, + Graphics = 0x100, Reference = 0x200, BeginEnv = 0x400, EndEnv = 0x800, + BeginFloat = 0x1000, EndFloat = 0x2000, Caption = 0x4000, BeamerFrame = 0x8000, + BeamerBeginFrame = 0x10000, BeamerEndFrame = 0x20000, BeamerFrametitle = 0x40000, BeamerBeginBlock = 0x80000, + ToDo = 0x100000, FixMe = 0x200000, NewEnvironment = 0x400000 +}; + +//Different levels (in the parent-child hierarchy) in the structure view +enum +{ + Hidden = -4, NotSpecified = -3, Object = -2, File = -1 +}; } /** * A convenience class to store info about how LaTeX elements should appear in the * structure view. A QMap should be created, so that the * actual LaTeX elements can be mapped to this class. **/ class KileStructData { public: - explicit KileStructData(int lvl = 0, int tp = KileStruct::None, QString px = QString(), QString fldr = "root" ) : level(lvl), type(tp), pix(px), folder(fldr) {} - /** At which level the element should be visible **/ - int level; - /** The type of element (see @ref KileStruct) **/ - int type; - /** The name of the icon that goes with this element. The icon is located using SmallIcon(pix). **/ - QString pix, folder; + explicit KileStructData(int lvl = 0, int tp = KileStruct::None, QString px = QString(), QString fldr = "root" ) : level(lvl), type(tp), pix(px), folder(fldr) {} + /** At which level the element should be visible **/ + int level; + /** The type of element (see @ref KileStruct) **/ + int type; + /** The name of the icon that goes with this element. The icon is located using SmallIcon(pix). **/ + QString pix, folder; }; /** * KileDocument::Info is a decorator class for the Document class. We can't derive a class from an interface * without implementing the interface, a decorator class is a way to add some functionality to the Document class. **/ namespace KileDocument { struct BracketResult { - BracketResult() : line(0), col(0) {} - QString option, value; - int line, col; + BracketResult() : line(0), col(0) {} + QString option, value; + int line, col; }; struct TodoResult { - int type; - uint colTag; - uint colComment; - QString comment; + int type; + uint colTag; + uint colComment; + QString comment; }; class Info : public QObject { - Q_OBJECT + Q_OBJECT public: - static bool containsInvalidCharacters(const QUrl&); - static QUrl repairInvalidCharacters(const QUrl&, QWidget *mainWidget, bool checkForFileExistence = true); - static QUrl repairExtension(const QUrl &url, QWidget *mainWidget, bool checkForFileExistence = true); - static QUrl makeValidTeXURL(const QUrl &url, QWidget *mainWidget, bool istexfile, bool checkForFileExistence = true); - static QUrl renameIfExist(const QUrl &url, QWidget *mainWidget); + static bool containsInvalidCharacters(const QUrl&); + static QUrl repairInvalidCharacters(const QUrl&, QWidget *mainWidget, bool checkForFileExistence = true); + static QUrl repairExtension(const QUrl &url, QWidget *mainWidget, bool checkForFileExistence = true); + static QUrl makeValidTeXURL(const QUrl &url, QWidget *mainWidget, bool istexfile, bool checkForFileExistence = true); + static QUrl renameIfExist(const QUrl &url, QWidget *mainWidget); public: - Info(); - ~Info(); - - QStringList labels() const{ return m_labels; } - QStringList bibItems() const { return m_bibItems; } - QStringList dependencies() const {return m_deps; } - QStringList bibliographies() const { return m_bibliography; } - QStringList packages() const { return m_packages; } - QStringList newCommands() const { return m_newCommands; } - QStringList asyFigures() const {return m_asyFigures; } - - bool openStructureLabels() { return m_openStructureLabels; } - bool openStructureReferences() { return m_openStructureReferences; } - bool openStructureBibitems() { return m_openStructureBibitems; } - bool openStructureTodo() { return m_openStructureTodo; } - - bool showStructureLabels() { return m_showStructureLabels; } - - const QMap& dictStructLevel() { return m_dictStructLevel; } - - const QString & preamble() const { return m_preamble; } - - virtual bool isLaTeXRoot() { return m_bIsRoot; } - - virtual QUrl url(); - - virtual void updateStructLevelInfo(); - - void setBaseDirectory(const QUrl &url); - const QUrl &getBaseDirectory() const; - - virtual bool isTextDocument(); - virtual Type getType(); - - /** - * Returns a file filter suitable for loading and saving files of this class' type. - **/ - virtual QLinkedList getFileFilter() const; - - virtual bool isDocumentTypePromotionAllowed(); - void setDocumentTypePromotionAllowed(bool b); - - /** - * Returns true iff new parsing is required. - **/ - bool isDirty() const; - void setDirty(bool b); - - virtual void installParserOutput(KileParser::ParserOutput *parserOutput); + Info(); + ~Info(); + + QStringList labels() const { + return m_labels; + } + QStringList bibItems() const { + return m_bibItems; + } + QStringList dependencies() const { + return m_deps; + } + QStringList bibliographies() const { + return m_bibliography; + } + QStringList packages() const { + return m_packages; + } + QStringList newCommands() const { + return m_newCommands; + } + QStringList asyFigures() const { + return m_asyFigures; + } + + bool openStructureLabels() { + return m_openStructureLabels; + } + bool openStructureReferences() { + return m_openStructureReferences; + } + bool openStructureBibitems() { + return m_openStructureBibitems; + } + bool openStructureTodo() { + return m_openStructureTodo; + } + + bool showStructureLabels() { + return m_showStructureLabels; + } + + const QMap& dictStructLevel() { + return m_dictStructLevel; + } + + const QString & preamble() const { + return m_preamble; + } + + virtual bool isLaTeXRoot() { + return m_bIsRoot; + } + + virtual QUrl url(); + + virtual void updateStructLevelInfo(); + + void setBaseDirectory(const QUrl &url); + const QUrl &getBaseDirectory() const; + + virtual bool isTextDocument(); + virtual Type getType(); + + /** + * Returns a file filter suitable for loading and saving files of this class' type. + **/ + virtual QLinkedList getFileFilter() const; + + virtual bool isDocumentTypePromotionAllowed(); + void setDocumentTypePromotionAllowed(bool b); + + /** + * Returns true iff new parsing is required. + **/ + bool isDirty() const; + void setDirty(bool b); + + virtual void installParserOutput(KileParser::ParserOutput *parserOutput); public Q_SLOTS: - /** - * Never call this function directly, use KileWidget::Structure::update(KileDocument::Info *, bool) instead - **/ - virtual void updateStruct(); - virtual void updateBibItems(); + /** + * Never call this function directly, use KileWidget::Structure::update(KileDocument::Info *, bool) instead + **/ + virtual void updateStruct(); + virtual void updateBibItems(); Q_SIGNALS: - void urlChanged(KileDocument::Info* info, const QUrl &url); - void isrootChanged(bool); + void urlChanged(KileDocument::Info* info, const QUrl &url); + void isrootChanged(bool); - void foundItem(const QString &title, uint line, uint column, int type, int level, uint startline, uint startcol, - const QString & pix, const QString & folder); - void depChanged(); - void completed(KileDocument::Info* info); - void parsingStarted(int maxValue); - void parsingComplete(); - void parsingUpdate(int value); + void foundItem(const QString &title, uint line, uint column, int type, int level, uint startline, uint startcol, + const QString & pix, const QString & folder); + void depChanged(); + void completed(KileDocument::Info* info); + void parsingStarted(int maxValue); + void parsingComplete(); + void parsingUpdate(int value); protected Q_SLOTS: - void slotCompleted(); + void slotCompleted(); protected: - void count(const QString& line, long *stat); - - enum State { - stStandard = 0, stComment = 1, stControlSequence = 3, stControlSymbol = 4, - stCommand = 5, stEnvironment = 6 - }; - - bool m_bIsRoot; - bool m_dirty; - QStringList m_labels; - QStringList m_bibItems; - QStringList m_deps, m_depsPrev; - QStringList m_bibliography; - QStringList m_packages; - QStringList m_newCommands; - QStringList m_asyFigures; - QString m_preamble; - QMap m_dictStructLevel; - KConfig *m_config; - bool m_showStructureLabels; - bool m_showStructureBibitems; - bool m_showStructureGraphics; - bool m_showStructureFloats; - bool m_showStructureReferences; - bool m_showStructureInputFiles; - bool m_showStructureTodo; - bool m_showSectioningLabels; - bool m_openStructureLabels; - bool m_openStructureReferences; - bool m_openStructureBibitems; - bool m_openStructureTodo; - QUrl m_baseDirectory; - bool documentTypePromotionAllowed; - Extensions *m_extensions; + void count(const QString& line, long *stat); + + enum State { + stStandard = 0, stComment = 1, stControlSequence = 3, stControlSymbol = 4, + stCommand = 5, stEnvironment = 6 + }; + + bool m_bIsRoot; + bool m_dirty; + QStringList m_labels; + QStringList m_bibItems; + QStringList m_deps, m_depsPrev; + QStringList m_bibliography; + QStringList m_packages; + QStringList m_newCommands; + QStringList m_asyFigures; + QString m_preamble; + QMap m_dictStructLevel; + KConfig *m_config; + bool m_showStructureLabels; + bool m_showStructureBibitems; + bool m_showStructureGraphics; + bool m_showStructureFloats; + bool m_showStructureReferences; + bool m_showStructureInputFiles; + bool m_showStructureTodo; + bool m_showSectioningLabels; + bool m_openStructureLabels; + bool m_openStructureReferences; + bool m_openStructureBibitems; + bool m_openStructureTodo; + QUrl m_baseDirectory; + bool documentTypePromotionAllowed; + Extensions *m_extensions; }; /** * The URL of a text document is managed directly by the corresponding KTextEditor::Document. **/ class TextInfo : public Info { - Q_OBJECT + Q_OBJECT public: - /** - * @param defaultMode the mode that will be set automatically - * once a new document is installed - **/ - TextInfo(Extensions *extensions, - KileAbbreviation::Manager *abbreviationManager, - KileParser::Manager *parserManager, - const QString& defaultMode = QString()); - virtual ~TextInfo(); - - /** - * @returns the document for which this class is a decorator - **/ - const KTextEditor::Document* getDoc() const; - KTextEditor::Document* getDoc(); - const KTextEditor::Document* getDocument() const; - KTextEditor::Document* getDocument(); - void setDoc(KTextEditor::Document *doc); - void setDocument(KTextEditor::Document *doc); - void detach(); - - /** - * Used by @ref KileDocInfoDlg to display statistics of the Document. - * @returns an array with some statistical data of the document. - * The array is filled as follows: [0] = #c in words, [1] = #c in latex commands and environments, - [2] = #c whitespace, [3] = #words, [4] = # latex_commands, [5] = latex_environments **/ - - virtual const long* getStatistics(KTextEditor::View *view = Q_NULLPTR); - - /** - * @returns the URL of the KTextEditor::Document if not null, an empty QUrl otherwise - **/ - virtual QUrl url(); - - virtual Type getType(); - - bool isTextDocument(); - - void setHighlightingMode(const QString& highlight = QString()); - - void setMode(const QString& mode = QString()); - - void setDefaultMode(const QString& string); - - /** - * "Overridden" method that installs custom event filters by using the "installEventFilters" - * method. It also installs signal connections by using the "installSignalConnections" - * method. - * @warning Only this method should be used to create new views for text documents ! - * @return Q_NULLPTR if no document is set (m_doc == NULL) - **/ - KTextEditor::View* createView(QWidget *parent, const char *name = Q_NULLPTR); - - void startAbbreviationCompletion(KTextEditor::View *view); - - /** - * Returns the contents of the document if a KTextEditor::Document is present. Otherwise, - * the contents supplied via @ref setDocumentContents is returned. - **/ - const QStringList documentContents() const; - void setDocumentContents(const QStringList& contents); + /** + * @param defaultMode the mode that will be set automatically + * once a new document is installed + **/ + TextInfo(Extensions *extensions, + KileAbbreviation::Manager *abbreviationManager, + KileParser::Manager *parserManager, + const QString& defaultMode = QString()); + virtual ~TextInfo(); + + /** + * @returns the document for which this class is a decorator + **/ + const KTextEditor::Document* getDoc() const; + KTextEditor::Document* getDoc(); + const KTextEditor::Document* getDocument() const; + KTextEditor::Document* getDocument(); + void setDoc(KTextEditor::Document *doc); + void setDocument(KTextEditor::Document *doc); + void detach(); + + /** + * Used by @ref KileDocInfoDlg to display statistics of the Document. + * @returns an array with some statistical data of the document. + * The array is filled as follows: [0] = #c in words, [1] = #c in latex commands and environments, + [2] = #c whitespace, [3] = #words, [4] = # latex_commands, [5] = latex_environments **/ + + virtual const long* getStatistics(KTextEditor::View *view = Q_NULLPTR); + + /** + * @returns the URL of the KTextEditor::Document if not null, an empty QUrl otherwise + **/ + virtual QUrl url(); + + virtual Type getType(); + + bool isTextDocument(); + + void setHighlightingMode(const QString& highlight = QString()); + + void setMode(const QString& mode = QString()); + + void setDefaultMode(const QString& string); + + /** + * "Overridden" method that installs custom event filters by using the "installEventFilters" + * method. It also installs signal connections by using the "installSignalConnections" + * method. + * @warning Only this method should be used to create new views for text documents ! + * @return Q_NULLPTR if no document is set (m_doc == NULL) + **/ + KTextEditor::View* createView(QWidget *parent, const char *name = Q_NULLPTR); + + void startAbbreviationCompletion(KTextEditor::View *view); + + /** + * Returns the contents of the document if a KTextEditor::Document is present. Otherwise, + * the contents supplied via @ref setDocumentContents is returned. + **/ + const QStringList documentContents() const; + void setDocumentContents(const QStringList& contents); Q_SIGNALS: - void documentDetached(KTextEditor::Document*); - void aboutToBeDestroyed(KileDocument::TextInfo*); + void documentDetached(KTextEditor::Document*); + void aboutToBeDestroyed(KileDocument::TextInfo*); protected Q_SLOTS: - void slotFileNameChanged(); - void slotViewDestroyed(QObject *object); - void activateDefaultMode(); + void slotFileNameChanged(); + void slotViewDestroyed(QObject *object); + void activateDefaultMode(); - void makeDirtyIfModified(); + void makeDirtyIfModified(); protected: - KTextEditor::Document *m_doc; - bool m_dirty; - long *m_arStatistics; - QString m_defaultMode; - QHash > m_eventFilterHash; - KileAbbreviation::Manager *m_abbreviationManager; - KileCodeCompletion::AbbreviationCompletionModel *m_abbreviationCodeCompletionModel; - KileParser::Manager *m_parserManager; - - QString matchBracket(QChar c, int &, int &); - QString getTextline(uint line, TodoResult &todo); - void searchTodoComment(const QString &s, uint startpos, TodoResult &todo); - - /** - * Creates the event filters that should be used on a view. Subclasses can override - * this method to provide custom event filters. The default implementation does nothing and - * returns an empty list. The event filters that are returned by this method are managed by - * the "installEventFilters", "removeInstalledEventFilters" methods. - * @warning The event filters that are created must be children of the view! - * @param view the view that is considered - **/ - virtual QList createEventFilters(KTextEditor::View *view); - - /** - * Installs event filters on a view. The function "createEventFilters(KTextEditor::View *view) - * function is used for a specific view. - * @param view the view that is considered - **/ - virtual void installEventFilters(KTextEditor::View *view); - - /** - * Removes the event filters that were previously installed by the "installEventFilters" - * function. - * @param view the view that is considered - **/ - virtual void removeInstalledEventFilters(KTextEditor::View *view); - - /** - * Installs the event filters on all the views that are currently open for the - * managed document object. The function "installEventFilters(KTextEditor::View *view) - * function is used for a specific view. - **/ - void installEventFilters(); - - /** - * Removes the event filters from all the views that are currently open for the - * managed document object. - **/ - void removeInstalledEventFilters(); - - /** - * Installs signal connections on a view. - */ - virtual void installSignalConnections(KTextEditor::View *view); - - /** - * Disconnects the signals that were previously connected with the - * "installSignalConnections" function. - */ - virtual void removeSignalConnections(KTextEditor::View *view); - - /** - * Installs signal connections on all the views that are currently open for the - * managed document object. The function "installSignalConnections(KTextEditor::View *view) - * function is used for a specific view. - **/ - void installSignalConnections(); - - /** - * Removes signal connections from all the views that are currently open for the - * managed document object. - **/ - void removeSignalConnections(); - - /** - * Register code completion models on a view. - */ - virtual void registerCodeCompletionModels(KTextEditor::View *view); - - /** - * Unregisters the code completion models that were previously registered by the - * "registerCodeCompletionModels" method. - */ - virtual void unregisterCodeCompletionModels(KTextEditor::View *view); - - /** - * Register code completion models on all the views that are currently open for the - * managed document object. The function "registerCodeCompletionModels(KTextEditor::View *view) - * function is used for a specific view. - **/ - void registerCodeCompletionModels(); - - /** - * Unregister the code completion models from all the views that are currently open for the - * managed document object. - **/ - void unregisterCodeCompletionModels(); + KTextEditor::Document *m_doc; + bool m_dirty; + long *m_arStatistics; + QString m_defaultMode; + QHash > m_eventFilterHash; + KileAbbreviation::Manager *m_abbreviationManager; + KileCodeCompletion::AbbreviationCompletionModel *m_abbreviationCodeCompletionModel; + KileParser::Manager *m_parserManager; + + QString matchBracket(QChar c, int &, int &); + QString getTextline(uint line, TodoResult &todo); + void searchTodoComment(const QString &s, uint startpos, TodoResult &todo); + + /** + * Creates the event filters that should be used on a view. Subclasses can override + * this method to provide custom event filters. The default implementation does nothing and + * returns an empty list. The event filters that are returned by this method are managed by + * the "installEventFilters", "removeInstalledEventFilters" methods. + * @warning The event filters that are created must be children of the view! + * @param view the view that is considered + **/ + virtual QList createEventFilters(KTextEditor::View *view); + + /** + * Installs event filters on a view. The function "createEventFilters(KTextEditor::View *view) + * function is used for a specific view. + * @param view the view that is considered + **/ + virtual void installEventFilters(KTextEditor::View *view); + + /** + * Removes the event filters that were previously installed by the "installEventFilters" + * function. + * @param view the view that is considered + **/ + virtual void removeInstalledEventFilters(KTextEditor::View *view); + + /** + * Installs the event filters on all the views that are currently open for the + * managed document object. The function "installEventFilters(KTextEditor::View *view) + * function is used for a specific view. + **/ + void installEventFilters(); + + /** + * Removes the event filters from all the views that are currently open for the + * managed document object. + **/ + void removeInstalledEventFilters(); + + /** + * Installs signal connections on a view. + */ + virtual void installSignalConnections(KTextEditor::View *view); + + /** + * Disconnects the signals that were previously connected with the + * "installSignalConnections" function. + */ + virtual void removeSignalConnections(KTextEditor::View *view); + + /** + * Installs signal connections on all the views that are currently open for the + * managed document object. The function "installSignalConnections(KTextEditor::View *view) + * function is used for a specific view. + **/ + void installSignalConnections(); + + /** + * Removes signal connections from all the views that are currently open for the + * managed document object. + **/ + void removeSignalConnections(); + + /** + * Register code completion models on a view. + */ + virtual void registerCodeCompletionModels(KTextEditor::View *view); + + /** + * Unregisters the code completion models that were previously registered by the + * "registerCodeCompletionModels" method. + */ + virtual void unregisterCodeCompletionModels(KTextEditor::View *view); + + /** + * Register code completion models on all the views that are currently open for the + * managed document object. The function "registerCodeCompletionModels(KTextEditor::View *view) + * function is used for a specific view. + **/ + void registerCodeCompletionModels(); + + /** + * Unregister the code completion models from all the views that are currently open for the + * managed document object. + **/ + void unregisterCodeCompletionModels(); private: - QStringList m_documentContents; + QStringList m_documentContents; }; class LaTeXInfo : public TextInfo, public KileTool::LivePreviewUserStatusHandler, public LaTeXOutputHandler { - Q_OBJECT + Q_OBJECT public: - /** - * @param eventFilter the event filter that will be installed on managed documents - **/ - LaTeXInfo(Extensions *extensions, - KileAbbreviation::Manager *abbreviationManager, - LatexCommands *commands, - KileDocument::EditorExtension *editorExtension, - KileConfiguration::Manager *manager, - KileCodeCompletion::Manager *codeCompletionManager, - KileTool::LivePreviewManager *livePreviewManager, - KileView::Manager *viewManager, - KileParser::Manager *parserManager); + /** + * @param eventFilter the event filter that will be installed on managed documents + **/ + LaTeXInfo(Extensions *extensions, + KileAbbreviation::Manager *abbreviationManager, + LatexCommands *commands, + KileDocument::EditorExtension *editorExtension, + KileConfiguration::Manager *manager, + KileCodeCompletion::Manager *codeCompletionManager, + KileTool::LivePreviewManager *livePreviewManager, + KileView::Manager *viewManager, + KileParser::Manager *parserManager); - virtual ~LaTeXInfo(); + virtual ~LaTeXInfo(); - virtual Type getType(); + virtual Type getType(); - virtual QLinkedList getFileFilter() const; + virtual QLinkedList getFileFilter() const; - void startLaTeXCompletion(KTextEditor::View *view); + void startLaTeXCompletion(KTextEditor::View *view); - void installParserOutput(KileParser::ParserOutput *parserOutput); + void installParserOutput(KileParser::ParserOutput *parserOutput); public Q_SLOTS: - virtual void updateStruct(); + virtual void updateStruct(); protected: - LatexCommands *m_commands; - EditorExtension *m_editorExtension; - KileConfiguration::Manager *m_configurationManager; - QObject *m_eventFilter; - KileCodeCompletion::LaTeXCompletionModel *m_latexCompletionModel; - KileTool::LivePreviewManager *m_livePreviewManager; - KileView::Manager *m_viewManager; + LatexCommands *m_commands; + EditorExtension *m_editorExtension; + KileConfiguration::Manager *m_configurationManager; + QObject *m_eventFilter; + KileCodeCompletion::LaTeXCompletionModel *m_latexCompletionModel; + KileTool::LivePreviewManager *m_livePreviewManager; + KileView::Manager *m_viewManager; - virtual void updateStructLevelInfo(); - virtual void checkChangedDeps(); + virtual void updateStructLevelInfo(); + virtual void checkChangedDeps(); - /** - * Creates a custom event filter. - */ - virtual QList createEventFilters(KTextEditor::View *view); + /** + * Creates a custom event filter. + */ + virtual QList createEventFilters(KTextEditor::View *view); - virtual void installSignalConnections(KTextEditor::View *view); - virtual void removeSignalConnections(KTextEditor::View *view); + virtual void installSignalConnections(KTextEditor::View *view); + virtual void removeSignalConnections(KTextEditor::View *view); - virtual void registerCodeCompletionModels(KTextEditor::View *view); - virtual void unregisterCodeCompletionModels(KTextEditor::View *view); + virtual void registerCodeCompletionModels(KTextEditor::View *view); + virtual void unregisterCodeCompletionModels(KTextEditor::View *view); private: - BracketResult matchBracket(int &, int &); + BracketResult matchBracket(int &, int &); }; class BibInfo : public TextInfo { - Q_OBJECT + Q_OBJECT public: - BibInfo (Extensions *extensions, - KileAbbreviation::Manager *abbreviationManager, - KileParser::Manager *parserManager, - LatexCommands* commands); - virtual ~BibInfo(); + BibInfo (Extensions *extensions, + KileAbbreviation::Manager *abbreviationManager, + KileParser::Manager *parserManager, + LatexCommands* commands); + virtual ~BibInfo(); - virtual bool isLaTeXRoot(); + virtual bool isLaTeXRoot(); - virtual Type getType(); + virtual Type getType(); - virtual QLinkedList getFileFilter() const; + virtual QLinkedList getFileFilter() const; - void installParserOutput(KileParser::ParserOutput *parserOutput); + void installParserOutput(KileParser::ParserOutput *parserOutput); public Q_SLOTS: - virtual void updateStruct(); + virtual void updateStruct(); }; class ScriptInfo : public TextInfo { - Q_OBJECT + Q_OBJECT public: - ScriptInfo(Extensions *extensions, - KileAbbreviation::Manager *abbreviationManager, - KileParser::Manager *parserManager); + ScriptInfo(Extensions *extensions, + KileAbbreviation::Manager *abbreviationManager, + KileParser::Manager *parserManager); - virtual ~ScriptInfo(); + virtual ~ScriptInfo(); - virtual bool isLaTeXRoot(); + virtual bool isLaTeXRoot(); - virtual Type getType(); + virtual Type getType(); - virtual QLinkedList getFileFilter() const; + virtual QLinkedList getFileFilter() const; }; } #endif diff --git a/src/editorcommands.cpp b/src/editorcommands.cpp index 638fd13e..026a60bb 100644 --- a/src/editorcommands.cpp +++ b/src/editorcommands.cpp @@ -1,90 +1,90 @@ /************************************************************************** * Copyright (C) 2010 by Michel Ludwig (michel.ludwig@kdemail.net) * ***************************************************************************/ /************************************************************************** * * * 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. * * * ***************************************************************************/ #include "editorcommands.h" #include #include "kiledocmanager.h" #include "kileinfo.h" EditorCommands::EditorCommands(KileInfo *info) - : KTextEditor::Command(QStringList() << "w" << "wa" << "wq" << "q" << "wqa") - , m_ki(info) + : KTextEditor::Command(QStringList() << "w" << "wa" << "wq" << "q" << "wqa") + , m_ki(info) { } EditorCommands::~EditorCommands() { } bool EditorCommands::exec(KTextEditor::View *view, const QString &cmd, QString &msg, const KTextEditor::Range &range) { - Q_UNUSED(range) + Q_UNUSED(range) - if(cmd == "w" || cmd == "wa") { - if(cmd == "wa") { - bool result = m_ki->docManager()->fileSaveAll(); - msg = result ? i18n("All documents saved to disk.") - : i18n("Saving of all documents failed."); - return result; - } - else { - bool result = m_ki->docManager()->fileSave(view); - msg = result ? i18n("Document saved to disk.") - : i18n("Saving document failed."); - return result; - } - } - else if(cmd == "q" || cmd == "wq" || cmd == "wqa") { - if(cmd == "wq" || cmd == "wqa") { - bool result = true; - if(cmd == "wq") { - result = m_ki->docManager()->fileSave(view); - } - else { - result = m_ki->docManager()->fileSaveAll(); - } - if(!result) { - msg = i18n("Saving failed and quitting canceled."); - return false; - } - } - QTimer::singleShot(0, m_ki->mainWindow(), SLOT(close())); - return true; - } + if(cmd == "w" || cmd == "wa") { + if(cmd == "wa") { + bool result = m_ki->docManager()->fileSaveAll(); + msg = result ? i18n("All documents saved to disk.") + : i18n("Saving of all documents failed."); + return result; + } + else { + bool result = m_ki->docManager()->fileSave(view); + msg = result ? i18n("Document saved to disk.") + : i18n("Saving document failed."); + return result; + } + } + else if(cmd == "q" || cmd == "wq" || cmd == "wqa") { + if(cmd == "wq" || cmd == "wqa") { + bool result = true; + if(cmd == "wq") { + result = m_ki->docManager()->fileSave(view); + } + else { + result = m_ki->docManager()->fileSaveAll(); + } + if(!result) { + msg = i18n("Saving failed and quitting canceled."); + return false; + } + } + QTimer::singleShot(0, m_ki->mainWindow(), SLOT(close())); + return true; + } - return false; + return false; } bool EditorCommands::help(KTextEditor::View *view, const QString &cmd, QString &msg) { - Q_UNUSED(view); + Q_UNUSED(view); - if(cmd == "w" || cmd == "wa") { - msg = "

w/wa: Save document(s) to disk.

" - "

w only saves the current document, whereas " - "wa saves all the documents.

"; - return true; - } - else if(cmd == "q" || cmd == "wq" || cmd == "wqa") { - msg = "

q/wq/wqa: Quit Kile

" - "

wq additionally saves the current document to disk " - "before quitting, whereas wqa saves all the documents " - "before exiting.

"; - return true; - } + if(cmd == "w" || cmd == "wa") { + msg = "

w/wa: Save document(s) to disk.

" + "

w only saves the current document, whereas " + "wa saves all the documents.

"; + return true; + } + else if(cmd == "q" || cmd == "wq" || cmd == "wqa") { + msg = "

q/wq/wqa: Quit Kile

" + "

wq additionally saves the current document to disk " + "before quitting, whereas wqa saves all the documents " + "before exiting.

"; + return true; + } - return false; + return false; } diff --git a/src/editorcommands.h b/src/editorcommands.h index 6fd27157..ee89594c 100644 --- a/src/editorcommands.h +++ b/src/editorcommands.h @@ -1,42 +1,42 @@ /************************************************************************** * Copyright (C) 2010 by Michel Ludwig (michel.ludwig@kdemail.net) * ***************************************************************************/ /************************************************************************** * * * 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. * * * ***************************************************************************/ #ifndef EDITORCOMMANDS_H #define EDITORCOMMANDS_H #include #include #include #include class KileInfo; /** * Implements bindings for commands like 'w', 'q', etc. for the VI input mode of KatePart. **/ class EditorCommands : public KTextEditor::Command { - public: - EditorCommands(KileInfo *info); - virtual ~EditorCommands(); +public: + EditorCommands(KileInfo *info); + virtual ~EditorCommands(); - virtual bool exec(KTextEditor::View *view, const QString &cmd, QString &msg, - const KTextEditor::Range &range = KTextEditor::Range::invalid()) Q_DECL_OVERRIDE; - virtual bool help(KTextEditor::View *view, const QString &cmd, QString &msg) Q_DECL_OVERRIDE; + virtual bool exec(KTextEditor::View *view, const QString &cmd, QString &msg, + const KTextEditor::Range &range = KTextEditor::Range::invalid()) Q_DECL_OVERRIDE; + virtual bool help(KTextEditor::View *view, const QString &cmd, QString &msg) Q_DECL_OVERRIDE; - private: - KileInfo *m_ki; - QStringList m_commandList; +private: + KileInfo *m_ki; + QStringList m_commandList; }; #endif diff --git a/src/editorextension.cpp b/src/editorextension.cpp index 27130aba..07449585 100644 --- a/src/editorextension.cpp +++ b/src/editorextension.cpp @@ -1,3389 +1,3594 @@ /*********************************************************************************************** Copyright (C) 2004-2012 by Holger Danielsson (holger.danielsson@versanet.de) 2008-2013 by Michel Ludwig (michel.ludwig@kdemail.net) ***********************************************************************************************/ /*************************************************************************** * * * 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. * * * ***************************************************************************/ #include "editorextension.h" #include #include #include #include #include #include #include #include #include #include "errorhandler.h" #include "codecompletion.h" #include "kile.h" #include "kileactions.h" #include "kileconfig.h" #include "kileextensions.h" #include "kileinfo.h" #include "kiletool_enums.h" #include "kileviewmanager.h" #include "quickpreview.h" #include "widgets/konsolewidget.h" /* * FIXME: The code in this file should be reworked completely. Once we've got a better parser * most of the code in here should also be superfluous. */ namespace KileDocument { EditorExtension::EditorExtension(KileInfo *info) : m_ki(info) { - m_latexCommands = m_ki->latexCommands(); - - // init regexp - m_reg.setPattern("(\\\\(begin|end)\\s*\\{([A-Za-z]+\\*?)\\})|(\\\\\\[|\\\\\\])"); - // 1 2 3 4 - m_regexpEnter.setPattern("^(.*)((\\\\begin\\s*\\{([^\\{\\}]*)\\})|(\\\\\\[))"); - // 1 23 4 5 - - // init double quotes - m_quoteListI18N // this is shown in the configuration dialog - << i18n("English quotes: `` ''") - << i18n("French quotes: "< ">") - << i18n("German quotes: "` "'") - << i18n("French quotes (long): \\flqq \\frqq") - << i18n("German quotes (long): \\glqq \\grqq") - << i18n("Icelandic quotes (v1): \\ilqq \\irqq") - << i18n("Icelandic quotes (v2): \\iflqq \\ifrqq") - << i18n("Czech quotes: \\uv{}") - << i18n("csquotes package: \\enquote{}"); - - - m_quoteList - << QPair("``", "''") - << QPair("\"<", "\">") - << QPair("\"`", "\"'") - << QPair("\\flqq", "\\frqq") - << QPair("\\glqq", "\\grqq") - << QPair("\\ilqq", "\\irqq") - << QPair("\\iflqq", "\\ifrqq") - << QPair("\\uv{", "}") - << QPair("\\enquote{", "}"); - - readConfig(); + m_latexCommands = m_ki->latexCommands(); + + // init regexp + m_reg.setPattern("(\\\\(begin|end)\\s*\\{([A-Za-z]+\\*?)\\})|(\\\\\\[|\\\\\\])"); + // 1 2 3 4 + m_regexpEnter.setPattern("^(.*)((\\\\begin\\s*\\{([^\\{\\}]*)\\})|(\\\\\\[))"); + // 1 23 4 5 + + // init double quotes + m_quoteListI18N // this is shown in the configuration dialog + << i18n("English quotes: `` ''") + << i18n("French quotes: "< ">") + << i18n("German quotes: "` "'") + << i18n("French quotes (long): \\flqq \\frqq") + << i18n("German quotes (long): \\glqq \\grqq") + << i18n("Icelandic quotes (v1): \\ilqq \\irqq") + << i18n("Icelandic quotes (v2): \\iflqq \\ifrqq") + << i18n("Czech quotes: \\uv{}") + << i18n("csquotes package: \\enquote{}"); + + + m_quoteList + << QPair("``", "''") + << QPair("\"<", "\">") + << QPair("\"`", "\"'") + << QPair("\\flqq", "\\frqq") + << QPair("\\glqq", "\\grqq") + << QPair("\\ilqq", "\\irqq") + << QPair("\\iflqq", "\\ifrqq") + << QPair("\\uv{", "}") + << QPair("\\enquote{", "}"); + + readConfig(); } EditorExtension::~EditorExtension() { } //////////////////// read configuration //////////////////// void EditorExtension::readConfig(void) { - // init insertion of double quotes - initDoubleQuotes(); - - // allow special chars? - m_specialCharacters = KileConfig::insertSpecialCharacters(); - - // calculate indent for autoindent of environments - m_envAutoIndent.clear(); - if(KileConfig::envIndentation()) { - if(KileConfig::envIndentSpaces()) { - int num = KileConfig::envIndentNumSpaces(); - if(num < 1 || num > 9) { - num = 1; - } - m_envAutoIndent.fill(' ', num); - } - else { - m_envAutoIndent = "\t"; - } - } + // init insertion of double quotes + initDoubleQuotes(); + + // allow special chars? + m_specialCharacters = KileConfig::insertSpecialCharacters(); + + // calculate indent for autoindent of environments + m_envAutoIndent.clear(); + if(KileConfig::envIndentation()) { + if(KileConfig::envIndentSpaces()) { + int num = KileConfig::envIndentNumSpaces(); + if(num < 1 || num > 9) { + num = 1; + } + m_envAutoIndent.fill(' ', num); + } + else { + m_envAutoIndent = "\t"; + } + } } void EditorExtension::insertTag(const KileAction::TagData& data, KTextEditor::View *view) { - KTextEditor::Document *doc = view->document(); - if(!doc) { - return; - } - - //whether or not to wrap tag around selection - bool wrap = !data.tagEnd.isNull() && view->selection(); - - //%C before or after the selection - bool before = data.tagBegin.count("%C"); - bool after = data.tagEnd.count("%C"); - - //save current cursor position - KTextEditor::Cursor cursor = view->cursorPosition(); - int para = cursor.line(); - int para_begin = para; - int index = cursor.column(); - int index_begin = index; - int para_end = 0; - int index_cursor = index; - int para_cursor = index; - // offset for autoindentation of environments - int dxIndentEnv = 0; - - // environment tag - bool envtag = data.tagBegin.count("%E") || data.tagEnd.count("%E"); - QString whitespace = getWhiteSpace( doc->line(para).left(index) ); - - //if there is a selection act as if cursor is at the beginning of selection - if (wrap) { - KTextEditor::Range selectionRange = view->selectionRange(); - index = selectionRange.start().column(); - para = selectionRange.start().line(); - para_end = selectionRange.end().line(); - } - - QString ins = data.tagBegin; - QString tagEnd = data.tagEnd; - - //start an atomic editing sequence - KTextEditor::Document::EditingTransaction transaction(doc); - - //cut the selected text - QString trailing; - if(wrap) { - QString sel = view->selectionText(); - view->removeSelectionText(); - - // no autoindentation of environments, when text is selected - if(envtag) { - ins.remove("%E"); - tagEnd.remove("%E\n"); - } - - // strip one of two consecutive line ends - int len = sel.length(); - if(tagEnd.at(0)=='\n' && len > 0 && sel.indexOf('\n',-1) == len - 1) { - sel.truncate( len-1 ); - } - - // now add the selection - ins += sel; - - // place the cursor behind this tag, if there is no other wish - if(!before && !after) { - trailing = "%C"; - after = true; - } - } - else if(envtag) { - ins.replace("%E",whitespace+m_envAutoIndent); - tagEnd.replace("%E",whitespace+m_envAutoIndent); - if(data.dy > 0) { - dxIndentEnv = whitespace.length() + m_envAutoIndent.length(); - } - } - - tagEnd.replace("\\end{",whitespace+"\\end{"); - ins += tagEnd + trailing; - - //do some replacements - QFileInfo fi( doc->url().toLocalFile()); - ins.replace("%S", fi.completeBaseName()); - ins.replace("%B", s_bullet); - - //insert first part of tag at cursor position - doc->insertText(KTextEditor::Cursor(para, index), ins); - - //move cursor to the new position - if(before || after) { - int n = data.tagBegin.count("\n")+ data.tagEnd.count("\n"); - if(wrap) { - n += para_end > para ? para_end-para : para-para_end; - } - for (int line = para_begin; line <= para_begin+n; ++line) { - if(doc->line(line).count("%C")) { - int i=doc->line(line).indexOf("%C"); - para_cursor = line; index_cursor = i; - doc->removeText(KTextEditor::Range(line, i, line, i+2)); - break; - } - index_cursor=index; - para_cursor=line; - } - } - else { - int py = para_begin, px = index_begin; - if(wrap) { //act as if cursor was at beginning of selected text (which is the point where the tagBegin is inserted) - py = para; - px = index; - } - para_cursor = py+data.dy; index_cursor = px+data.dx+dxIndentEnv; - } - - //end the atomic editing sequence - transaction.finish(); - - //set the cursor position (it is important that this is done outside of the atomic editing sequence) - view->setCursorPosition(KTextEditor::Cursor(para_cursor, index_cursor)); - - view->removeSelection(); + KTextEditor::Document *doc = view->document(); + if(!doc) { + return; + } + + //whether or not to wrap tag around selection + bool wrap = !data.tagEnd.isNull() && view->selection(); + + //%C before or after the selection + bool before = data.tagBegin.count("%C"); + bool after = data.tagEnd.count("%C"); + + //save current cursor position + KTextEditor::Cursor cursor = view->cursorPosition(); + int para = cursor.line(); + int para_begin = para; + int index = cursor.column(); + int index_begin = index; + int para_end = 0; + int index_cursor = index; + int para_cursor = index; + // offset for autoindentation of environments + int dxIndentEnv = 0; + + // environment tag + bool envtag = data.tagBegin.count("%E") || data.tagEnd.count("%E"); + QString whitespace = getWhiteSpace( doc->line(para).left(index) ); + + //if there is a selection act as if cursor is at the beginning of selection + if (wrap) { + KTextEditor::Range selectionRange = view->selectionRange(); + index = selectionRange.start().column(); + para = selectionRange.start().line(); + para_end = selectionRange.end().line(); + } + + QString ins = data.tagBegin; + QString tagEnd = data.tagEnd; + + //start an atomic editing sequence + KTextEditor::Document::EditingTransaction transaction(doc); + + //cut the selected text + QString trailing; + if(wrap) { + QString sel = view->selectionText(); + view->removeSelectionText(); + + // no autoindentation of environments, when text is selected + if(envtag) { + ins.remove("%E"); + tagEnd.remove("%E\n"); + } + + // strip one of two consecutive line ends + int len = sel.length(); + if(tagEnd.at(0)=='\n' && len > 0 && sel.indexOf('\n',-1) == len - 1) { + sel.truncate( len-1 ); + } + + // now add the selection + ins += sel; + + // place the cursor behind this tag, if there is no other wish + if(!before && !after) { + trailing = "%C"; + after = true; + } + } + else if(envtag) { + ins.replace("%E",whitespace+m_envAutoIndent); + tagEnd.replace("%E",whitespace+m_envAutoIndent); + if(data.dy > 0) { + dxIndentEnv = whitespace.length() + m_envAutoIndent.length(); + } + } + + tagEnd.replace("\\end{",whitespace+"\\end{"); + ins += tagEnd + trailing; + + //do some replacements + QFileInfo fi( doc->url().toLocalFile()); + ins.replace("%S", fi.completeBaseName()); + ins.replace("%B", s_bullet); + + //insert first part of tag at cursor position + doc->insertText(KTextEditor::Cursor(para, index), ins); + + //move cursor to the new position + if(before || after) { + int n = data.tagBegin.count("\n")+ data.tagEnd.count("\n"); + if(wrap) { + n += para_end > para ? para_end-para : para-para_end; + } + for (int line = para_begin; line <= para_begin+n; ++line) { + if(doc->line(line).count("%C")) { + int i=doc->line(line).indexOf("%C"); + para_cursor = line; + index_cursor = i; + doc->removeText(KTextEditor::Range(line, i, line, i+2)); + break; + } + index_cursor=index; + para_cursor=line; + } + } + else { + int py = para_begin, px = index_begin; + if(wrap) { //act as if cursor was at beginning of selected text (which is the point where the tagBegin is inserted) + py = para; + px = index; + } + para_cursor = py+data.dy; + index_cursor = px+data.dx+dxIndentEnv; + } + + //end the atomic editing sequence + transaction.finish(); + + //set the cursor position (it is important that this is done outside of the atomic editing sequence) + view->setCursorPosition(KTextEditor::Cursor(para_cursor, index_cursor)); + + view->removeSelection(); } //////////////////// goto environment tag (begin or end) //////////////////// // goto the next non-nested environment tag KTextEditor::View* EditorExtension::determineView(KTextEditor::View *view) { - if (!view) { - view = m_ki->viewManager()->currentTextView(); - } + if (!view) { + view = m_ki->viewManager()->currentTextView(); + } - m_overwritemode = (!view) ? false : (view->viewMode() == KTextEditor::View::NormalModeOverwrite); + m_overwritemode = (!view) ? false : (view->viewMode() == KTextEditor::View::NormalModeOverwrite); - return view; + return view; } void EditorExtension::gotoEnvironment(bool backwards, KTextEditor::View *view) { - view = determineView(view); - if(!view) { - return; - } + view = determineView(view); + if(!view) { + return; + } - uint row,col; - EnvData env; - bool found; + uint row,col; + EnvData env; + bool found; - // get current position - KTextEditor::Document *doc = view->document(); - KTextEditor::Cursor cursor = view->cursorPosition(); - row = cursor.line(); - col = cursor.column(); + // get current position + KTextEditor::Document *doc = view->document(); + KTextEditor::Cursor cursor = view->cursorPosition(); + row = cursor.line(); + col = cursor.column(); - // start searching - if(backwards) { - found = findBeginEnvironment(doc,row,col,env); - //KILE_DEBUG_MAIN << " goto begin env: " << env.row << "/" << env.col; + // start searching + if(backwards) { + found = findBeginEnvironment(doc,row,col,env); + //KILE_DEBUG_MAIN << " goto begin env: " << env.row << "/" << env.col; - } - else { - found = findEndEnvironment(doc,row,col,env); - env.col += env.len; - } + } + else { + found = findEndEnvironment(doc,row,col,env); + env.col += env.len; + } - if(found) { - view->setCursorPosition(KTextEditor::Cursor(env.row, env.col)); - } + if(found) { + view->setCursorPosition(KTextEditor::Cursor(env.row, env.col)); + } } // match the opposite environment tag void EditorExtension::matchEnvironment(KTextEditor::View *view) { - view = determineView(view); - if(!view) { - return; - } + view = determineView(view); + if(!view) { + return; + } - uint row,col; - EnvData env; + uint row,col; + EnvData env; - // get current position - KTextEditor::Document *doc = view->document(); - KTextEditor::Cursor cursor = view->cursorPosition(); - row = cursor.line(); - col = cursor.column(); + // get current position + KTextEditor::Document *doc = view->document(); + KTextEditor::Cursor cursor = view->cursorPosition(); + row = cursor.line(); + col = cursor.column(); - // we only start, when we are at an environment tag - if(!isEnvironmentPosition(doc, row, col, env)) { - return; - } + // we only start, when we are at an environment tag + if(!isEnvironmentPosition(doc, row, col, env)) { + return; + } - gotoEnvironment(env.tag != EnvBegin, view); + gotoEnvironment(env.tag != EnvBegin, view); } //////////////////// close opened environments //////////////////// // search for the last opened environment and close it void EditorExtension::closeEnvironment(KTextEditor::View *view) { - view = determineView(view); - if(!view) { - return; - } - - int row, col, currentRow, currentCol; - QString name; - - KTextEditor::Cursor cursor = view->cursorPosition(); - currentRow = cursor.line(); - currentCol = cursor.column(); - - if(findOpenedEnvironment(row, col, name, view)) { - if(name == "\\[") { - view->document()->insertText(KTextEditor::Cursor(currentRow, currentCol), "\\]"); - } - else { - view->document()->insertText(KTextEditor::Cursor(currentRow, currentCol), "\\end{" + name + '}'); - } + view = determineView(view); + if(!view) { + return; + } + + int row, col, currentRow, currentCol; + QString name; + + KTextEditor::Cursor cursor = view->cursorPosition(); + currentRow = cursor.line(); + currentCol = cursor.column(); + + if(findOpenedEnvironment(row, col, name, view)) { + if(name == "\\[") { + view->document()->insertText(KTextEditor::Cursor(currentRow, currentCol), "\\]"); + } + else { + view->document()->insertText(KTextEditor::Cursor(currentRow, currentCol), "\\end{" + name + '}'); + } // view->setCursorPosition(KTextEditor::Cursor(row + 1, 0)); - } + } } // close all opened environments void EditorExtension::closeAllEnvironments(KTextEditor::View *view) { - view = determineView(view); - if(!view) { - return; - } - - QStringList envlist = findOpenedEnvironmentList(view, true); - if(envlist.count() == 0) { - return; - } - - int currentRow, currentCol, outputCol; - KTextEditor::Document *doc = view->document(); - KTextEditor::Cursor cursor = view->cursorPosition(); - currentRow = cursor.line(); - currentCol = cursor.column(); - - bool indent = !m_envAutoIndent.isEmpty(); - if(indent && currentCol > 0) { - doc->insertText(KTextEditor::Cursor(currentRow, currentCol),"\n"); - currentRow++; - currentCol = 0; - } - - bool ok1,ok2; - for(QStringList::Iterator it = envlist.begin(); it != envlist.end(); ++it) { - QStringList entry = (*it).split(','); - if(entry[0] == "document") { - break; - } - - int row = entry[1].toInt(&ok1); - int col = entry[2].toInt(&ok2); - if(!ok1 || !ok2) { - continue; - } - - outputCol = currentCol; - if(indent) { - QString whitespace = getWhiteSpace( doc->line(row).left(col) ); - doc->insertText(KTextEditor::Cursor(currentRow, outputCol), whitespace); - outputCol += whitespace.length(); - } - QString endtag = ( entry[0] == "\\[" ) ? "\\]\n" : "\\end{"+entry[0]+"}\n"; - doc->insertText(KTextEditor::Cursor(currentRow, outputCol), endtag); - ++currentRow; - } + view = determineView(view); + if(!view) { + return; + } + + QStringList envlist = findOpenedEnvironmentList(view, true); + if(envlist.count() == 0) { + return; + } + + int currentRow, currentCol, outputCol; + KTextEditor::Document *doc = view->document(); + KTextEditor::Cursor cursor = view->cursorPosition(); + currentRow = cursor.line(); + currentCol = cursor.column(); + + bool indent = !m_envAutoIndent.isEmpty(); + if(indent && currentCol > 0) { + doc->insertText(KTextEditor::Cursor(currentRow, currentCol),"\n"); + currentRow++; + currentCol = 0; + } + + bool ok1,ok2; + for(QStringList::Iterator it = envlist.begin(); it != envlist.end(); ++it) { + QStringList entry = (*it).split(','); + if(entry[0] == "document") { + break; + } + + int row = entry[1].toInt(&ok1); + int col = entry[2].toInt(&ok2); + if(!ok1 || !ok2) { + continue; + } + + outputCol = currentCol; + if(indent) { + QString whitespace = getWhiteSpace( doc->line(row).left(col) ); + doc->insertText(KTextEditor::Cursor(currentRow, outputCol), whitespace); + outputCol += whitespace.length(); + } + QString endtag = ( entry[0] == "\\[" ) ? "\\]\n" : "\\end{"+entry[0]+"}\n"; + doc->insertText(KTextEditor::Cursor(currentRow, outputCol), endtag); + ++currentRow; + } } //////////////////// mathgroup //////////////////// void EditorExtension::selectMathgroup(KTextEditor::View *view) { - view = determineView(view); - if(!view) { - return; - } + view = determineView(view); + if(!view) { + return; + } - KTextEditor::Range range = mathgroupRange(view); - if(range.isValid()) { - view->setSelection(range); - } + KTextEditor::Range range = mathgroupRange(view); + if(range.isValid()) { + view->setSelection(range); + } } void EditorExtension::deleteMathgroup(KTextEditor::View *view) { - view = determineView(view); - if(!view) { - return; - } + view = determineView(view); + if(!view) { + return; + } - KTextEditor::Range range = mathgroupRange(view); - if(range.isValid()) { - deleteRange(range,view); - } + KTextEditor::Range range = mathgroupRange(view); + if(range.isValid()) { + deleteRange(range,view); + } } bool EditorExtension::hasMathgroup(KTextEditor::View *view) { - // view will be checked in mathgroupRange() - KTextEditor::Range range = mathgroupRange(view); - return (range.isValid()) ? true : false; + // view will be checked in mathgroupRange() + KTextEditor::Range range = mathgroupRange(view); + return (range.isValid()) ? true : false; } QString EditorExtension::getMathgroupText(KTextEditor::View *view) { - view = determineView(view); - if(!view) { - return QString(); - } + view = determineView(view); + if(!view) { + return QString(); + } - KTextEditor::Range range = mathgroupRange(view); - return (range.isValid()) ? view->document()->text(range) : QString(); + KTextEditor::Range range = mathgroupRange(view); + return (range.isValid()) ? view->document()->text(range) : QString(); } QString EditorExtension::getMathgroupText(uint &row, uint &col, KTextEditor::View *view) { - int row1, col1, row2, col2; + int row1, col1, row2, col2; - view = determineView(view); - if(view && getMathgroup(view, row1, col1, row2, col2)) { - row = row1; - col = col1; - return view->document()->text(KTextEditor::Range(row1, col1, row2, col2)); - } - else { - return QString(); - } + view = determineView(view); + if(view && getMathgroup(view, row1, col1, row2, col2)) { + row = row1; + col = col1; + return view->document()->text(KTextEditor::Range(row1, col1, row2, col2)); + } + else { + return QString(); + } } KTextEditor::Range EditorExtension::mathgroupRange(KTextEditor::View *view) { - view = determineView(view); - if(!view) { - return KTextEditor::Range::invalid(); - } + view = determineView(view); + if(!view) { + return KTextEditor::Range::invalid(); + } - int row1, col1, row2, col2; - if(getMathgroup(view, row1, col1, row2, col2)) { - return KTextEditor::Range(row1, col1, row2, col2); - } - else { - return KTextEditor::Range::invalid(); - } + int row1, col1, row2, col2; + if(getMathgroup(view, row1, col1, row2, col2)) { + return KTextEditor::Range(row1, col1, row2, col2); + } + else { + return KTextEditor::Range::invalid(); + } } bool EditorExtension::getMathgroup(KTextEditor::View *view, int &row1, int &col1, int &row2, int &col2) { - int row, col, r, c; - MathData begin, end; - - KTextEditor::Document *doc = view->document(); - KTextEditor::Cursor cursor = view->cursorPosition(); - row = cursor.line(); - col = cursor.column(); - - QString textline = getTextLineReal(doc,row); - - // check for '\ensuremath{...}' - QString word; - int x1, x2; - if(getCurrentWord(doc, row, col, smTex, word, x1, x2) && word == "\\ensuremath") { - view->setCursorPosition(KTextEditor::Cursor(row, x2)); - } - - BracketData open,close; - if(getTexgroup(false, open, close, view)) { - QString s = getTextLineReal(doc,open.row); - if(open.col >= 11 && s.mid(open.col - 11, 11) == "\\ensuremath") { - view->setCursorPosition(KTextEditor::Cursor(row, col)); - row1 = open.row; - col1 = open.col-11; - row2 = close.row; - col2 = close.col; - return true; - } - } - - // do we need to restore the cursor position - view->setCursorPosition(KTextEditor::Cursor(row, col)); - - // '$' is difficult, because it is used as opening and closing tag - int mode = 0; - if(textline[col] == '$') { - mode = 1; - } - else if(col > 0 && textline[col - 1] == '$') { - mode = 2; - } - - if(mode > 0) { - // first look, if this is a closing '$' - r = row; - c = (mode == 1) ? col : col - 1; - if(decreaseCursorPosition(doc, r, c) && findOpenMathTag(doc, r, c, begin)) { - if(begin.tag == mmMathDollar && (begin.numdollar & 1)) { - row1 = begin.row; - col1 = begin.col; - row2 = row; - col2 = (mode == 1) ? col + 1 : col; - return true; - } - } - - // perhaps an opening '$' - r = row; - c = (mode == 1) ? col+1 : col; - if(findCloseMathTag(doc, r, c, end)) { - if(end.tag == mmMathDollar) { - row1 = row; - col1 = ( mode == 1 ) ? col : col-1; - row2 = end.row; - col2 = end.col + end.len; - return true; - } - } - - // found no mathgroup with '$' - return false; - } - - // now let's search for all other math tags: - // if a mathgroup tag starts in the current column, we save this - // position and move the cursor one column to the right - bool openingtag = isOpeningMathTagPosition(doc, row, col, begin); - if(openingtag) { - // try to find the corresponding closing tag at the right - bool closetag = findCloseMathTag(doc, row, col + 1, end); - if(closetag && checkMathtags(begin, end)) { - row1 = begin.row; - col1 = begin.col; - row2 = end.row; - col2 = end.col + end.len; - return true; - } - } - - r = row; - c = col; - bool closingtag = isClosingMathTagPosition(doc, row, col, end); - if(closingtag) { - c = end.col; - if(!decreaseCursorPosition(doc, r, c)) { - return false; - } - } - - // now try to search to opening tag of the math group - if(!findOpenMathTag(doc, r, c, begin)) { - return false; - } - - if(begin.tag == mmMathDollar && !(begin.numdollar & 1)) { - //KILE_DEBUG_MAIN << "error: even number of '$' --> no math mode" ; - return false; - } - - // and now the closing tag - if(!findCloseMathTag(doc, r, c, end)) { - return false; - } - - // both tags were found, but they must be of the same type - if(checkMathtags(begin, end)) { - row1 = begin.row; - col1 = begin.col; - row2 = end.row; - col2 = end.col + end.len; - return true; - } - else { - return false; - } + int row, col, r, c; + MathData begin, end; + + KTextEditor::Document *doc = view->document(); + KTextEditor::Cursor cursor = view->cursorPosition(); + row = cursor.line(); + col = cursor.column(); + + QString textline = getTextLineReal(doc,row); + + // check for '\ensuremath{...}' + QString word; + int x1, x2; + if(getCurrentWord(doc, row, col, smTex, word, x1, x2) && word == "\\ensuremath") { + view->setCursorPosition(KTextEditor::Cursor(row, x2)); + } + + BracketData open,close; + if(getTexgroup(false, open, close, view)) { + QString s = getTextLineReal(doc,open.row); + if(open.col >= 11 && s.mid(open.col - 11, 11) == "\\ensuremath") { + view->setCursorPosition(KTextEditor::Cursor(row, col)); + row1 = open.row; + col1 = open.col-11; + row2 = close.row; + col2 = close.col; + return true; + } + } + + // do we need to restore the cursor position + view->setCursorPosition(KTextEditor::Cursor(row, col)); + + // '$' is difficult, because it is used as opening and closing tag + int mode = 0; + if(textline[col] == '$') { + mode = 1; + } + else if(col > 0 && textline[col - 1] == '$') { + mode = 2; + } + + if(mode > 0) { + // first look, if this is a closing '$' + r = row; + c = (mode == 1) ? col : col - 1; + if(decreaseCursorPosition(doc, r, c) && findOpenMathTag(doc, r, c, begin)) { + if(begin.tag == mmMathDollar && (begin.numdollar & 1)) { + row1 = begin.row; + col1 = begin.col; + row2 = row; + col2 = (mode == 1) ? col + 1 : col; + return true; + } + } + + // perhaps an opening '$' + r = row; + c = (mode == 1) ? col+1 : col; + if(findCloseMathTag(doc, r, c, end)) { + if(end.tag == mmMathDollar) { + row1 = row; + col1 = ( mode == 1 ) ? col : col-1; + row2 = end.row; + col2 = end.col + end.len; + return true; + } + } + + // found no mathgroup with '$' + return false; + } + + // now let's search for all other math tags: + // if a mathgroup tag starts in the current column, we save this + // position and move the cursor one column to the right + bool openingtag = isOpeningMathTagPosition(doc, row, col, begin); + if(openingtag) { + // try to find the corresponding closing tag at the right + bool closetag = findCloseMathTag(doc, row, col + 1, end); + if(closetag && checkMathtags(begin, end)) { + row1 = begin.row; + col1 = begin.col; + row2 = end.row; + col2 = end.col + end.len; + return true; + } + } + + r = row; + c = col; + bool closingtag = isClosingMathTagPosition(doc, row, col, end); + if(closingtag) { + c = end.col; + if(!decreaseCursorPosition(doc, r, c)) { + return false; + } + } + + // now try to search to opening tag of the math group + if(!findOpenMathTag(doc, r, c, begin)) { + return false; + } + + if(begin.tag == mmMathDollar && !(begin.numdollar & 1)) { + //KILE_DEBUG_MAIN << "error: even number of '$' --> no math mode" ; + return false; + } + + // and now the closing tag + if(!findCloseMathTag(doc, r, c, end)) { + return false; + } + + // both tags were found, but they must be of the same type + if(checkMathtags(begin, end)) { + row1 = begin.row; + col1 = begin.col; + row2 = end.row; + col2 = end.col + end.len; + return true; + } + else { + return false; + } } //////////////////// mathgroup tags //////////////////// bool EditorExtension::checkMathtags(const MathData &begin,const MathData &end) { - // both tags were found, but they must be of the same type - if(begin.tag != end.tag) { - //KILE_DEBUG_MAIN << "error: opening and closing tag of mathmode don't match: " << begin.tag << " - " << end.tag; - return false; - } + // both tags were found, but they must be of the same type + if(begin.tag != end.tag) { + //KILE_DEBUG_MAIN << "error: opening and closing tag of mathmode don't match: " << begin.tag << " - " << end.tag; + return false; + } - // and additionally: if it is a math env, both tags must have the same name - if(begin.tag == mmDisplaymathEnv && begin.envname != end.envname) { - //KILE_DEBUG_MAIN << "error: opening and closing env tags have different names: " << begin.envname << " - " << end.envname; - return false; - } + // and additionally: if it is a math env, both tags must have the same name + if(begin.tag == mmDisplaymathEnv && begin.envname != end.envname) { + //KILE_DEBUG_MAIN << "error: opening and closing env tags have different names: " << begin.envname << " - " << end.envname; + return false; + } - return true; + return true; } bool EditorExtension::isOpeningMathTagPosition(KTextEditor::Document *doc, uint row, uint col, MathData &mathdata) { - QString textline = getTextLineReal(doc,row); + QString textline = getTextLineReal(doc,row); - QRegExp reg("\\\\begin\\s*\\{([A-Za-z]+\\*?)\\}|\\\\\\[|\\\\\\("); - if((int)col != reg.indexIn(textline, col)) { - return false; - } + QRegExp reg("\\\\begin\\s*\\{([A-Za-z]+\\*?)\\}|\\\\\\[|\\\\\\("); + if((int)col != reg.indexIn(textline, col)) { + return false; + } - QChar id = reg.cap(0)[1]; - QString envname = reg.cap(1); - - mathdata.row = row; - mathdata.col = col; - mathdata.len = reg.cap(0).length(); - - switch(id.unicode()) { - case 'b': - if(!(m_latexCommands->isMathEnv(envname) || envname=="math") || m_latexCommands->needsMathMode(envname)) { - return false; - } - mathdata.tag = ( envname=="math" ) ? mmMathEnv : mmDisplaymathEnv; - mathdata.envname = envname; - break; - case '[': - mathdata.tag = mmDisplaymathParen; - break; - case '(': - mathdata.tag = mmMathParen; - break; - } + QChar id = reg.cap(0)[1]; + QString envname = reg.cap(1); + + mathdata.row = row; + mathdata.col = col; + mathdata.len = reg.cap(0).length(); + + switch(id.unicode()) { + case 'b': + if(!(m_latexCommands->isMathEnv(envname) || envname=="math") || m_latexCommands->needsMathMode(envname)) { + return false; + } + mathdata.tag = ( envname=="math" ) ? mmMathEnv : mmDisplaymathEnv; + mathdata.envname = envname; + break; + case '[': + mathdata.tag = mmDisplaymathParen; + break; + case '(': + mathdata.tag = mmMathParen; + break; + } - return true; + return true; } bool EditorExtension::isClosingMathTagPosition(KTextEditor::Document *doc, uint row, uint col,MathData &mathdata) { - QString textline = doc->line(row); + QString textline = doc->line(row); - QRegExp reg("\\\\end\\s*\\{([A-Za-z]+\\*?)\\}|\\\\\\]|\\\\\\)"); - int pos = reg.lastIndexIn(textline, col); - if(pos < 0 || (int)col > pos + reg.matchedLength()) { - return false; - } + QRegExp reg("\\\\end\\s*\\{([A-Za-z]+\\*?)\\}|\\\\\\]|\\\\\\)"); + int pos = reg.lastIndexIn(textline, col); + if(pos < 0 || (int)col > pos + reg.matchedLength()) { + return false; + } - QChar id = reg.cap(0)[1]; - QString envname = reg.cap(1); - - mathdata.row = row; - mathdata.col = pos; - mathdata.len = reg.cap(0).length(); - - switch(id.unicode()) { - case 'e': - if(!(m_latexCommands->isMathEnv(envname) || envname=="math") || m_latexCommands->needsMathMode(envname)) { - return false; - } - mathdata.tag = ( envname=="math" ) ? mmMathEnv : mmDisplaymathEnv; - mathdata.envname = envname; - break; - case ']': - mathdata.tag = mmDisplaymathParen; - break; - case ')': - mathdata.tag = mmMathParen; - break; - } + QChar id = reg.cap(0)[1]; + QString envname = reg.cap(1); + + mathdata.row = row; + mathdata.col = pos; + mathdata.len = reg.cap(0).length(); + + switch(id.unicode()) { + case 'e': + if(!(m_latexCommands->isMathEnv(envname) || envname=="math") || m_latexCommands->needsMathMode(envname)) { + return false; + } + mathdata.tag = ( envname=="math" ) ? mmMathEnv : mmDisplaymathEnv; + mathdata.envname = envname; + break; + case ']': + mathdata.tag = mmDisplaymathParen; + break; + case ')': + mathdata.tag = mmMathParen; + break; + } - return true; + return true; } bool EditorExtension::findOpenMathTag(KTextEditor::Document *doc, int row, int col, MathData &mathdata) { - const QString regExpString = "\\$" - "|\\\\begin\\s*\\{([A-Za-z]+\\*?)\\}" - "|\\\\end\\s*\\{([A-Za-z]+\\*?)\\}" - "|\\\\\\[|\\\\\\]" - "|\\\\\\(|\\\\\\)"; - - QRegExp reg(regExpString); - int lastrow = -1, lastcol = -1; - QString mathname; - - bool foundDollar = false; - uint numDollar = 0; - - QString textline = getTextLineReal(doc, row); - int column = col; - - bool continueSearch = true; - while(continueSearch) { - while((column = reg.lastIndexIn(textline, col)) != -1) { - col = column; - - mathdata.row = row; - mathdata.col = col; - mathdata.len = reg.cap(0).length(); - mathname = reg.cap(0).left(2); - - // should be better called 'isValidChar()', because it checks for comments - // and escaped chars like backslash and dollar in '\\' and '\$' - if(mathname == "$") { - // count and continue search - ++numDollar; - - // but remember the first dollar found backwards - if(!foundDollar) { - lastrow = row; - lastcol = col; - foundDollar = true; - } - } - else if(mathname=="\\[" || mathname=="\\(") { - // found start of mathmode - if(numDollar == 0) { - mathdata.tag = ( mathname == "\\[" ) ? mmDisplaymathParen : mmMathParen; - mathdata.numdollar = 0; - return true; - } - else { - //KILE_DEBUG_MAIN << "error: dollar not allowed in \\[ or \\( mode"; - return false; - } - } - else if(mathname=="\\]" || mathname=="\\)") { - continueSearch = false; - break; - } - else if(mathname=="\\b") { - // save name of environment - QString envname = reg.cap(1); - - // if we found the opening tag of a math env - if(m_latexCommands->isMathEnv(envname) || envname=="math") { - if(numDollar > 0) { - //KILE_DEBUG_MAIN << "error: dollar not allowed in math env numdollar=" << numDollar; - return false; - } - - // if this is a math env with its own mathmode, we have found the starting position - if(envname == "math") { - mathdata.tag = mmMathEnv; - mathdata.envname = envname; - return true; - } - - if(!m_latexCommands->needsMathMode(envname)) { - mathdata.tag = mmDisplaymathEnv; - mathdata.envname = envname; - return true; - } - } - // no math env, we found the opening tag of a normal env - else { - continueSearch = false; - break; - } - } - else if(mathname == "\\e") { - QString envname = reg.cap(2); - - // if we found the closing tag of a math env - if(m_latexCommands->isMathEnv(envname) || envname == "math") { - // if this is a math env with its own mathmode - if(!m_latexCommands->needsMathMode(envname) || envname == "math") { - continueSearch = false; - break; - } - - // if this is a math env which needs $..$ - if(m_latexCommands->isMathModeEnv(envname)) { - if(numDollar >= 1) { - --numDollar; - continueSearch = false; - break; - } - // else continue search - } - } - // if we found the closing tag of a normal env - else { - continueSearch = false; - break; - } - } - else { - //KILE_DEBUG_MAIN << "error: unknown match"; - return false; - } - - // continue search one column left of the last match (if this is possible) - if(col == 0) { - break; - } - - --col; - } - - if(row > 0) { - textline = getTextLineReal(doc,--row); - col = textline.length(); - } - else if(column == -1) { - continueSearch = false; - break; - } - } - - // nothing else found, so math mode starts a the last dollar (the first one found backwards) - mathdata.row = lastrow; - mathdata.col = lastcol; - mathdata.len = 1; - mathdata.numdollar = numDollar; - - mathdata.tag = (numDollar > 0) ? mmMathDollar : mmNoMathMode; - - return true; + const QString regExpString = "\\$" + "|\\\\begin\\s*\\{([A-Za-z]+\\*?)\\}" + "|\\\\end\\s*\\{([A-Za-z]+\\*?)\\}" + "|\\\\\\[|\\\\\\]" + "|\\\\\\(|\\\\\\)"; + + QRegExp reg(regExpString); + int lastrow = -1, lastcol = -1; + QString mathname; + + bool foundDollar = false; + uint numDollar = 0; + + QString textline = getTextLineReal(doc, row); + int column = col; + + bool continueSearch = true; + while(continueSearch) { + while((column = reg.lastIndexIn(textline, col)) != -1) { + col = column; + + mathdata.row = row; + mathdata.col = col; + mathdata.len = reg.cap(0).length(); + mathname = reg.cap(0).left(2); + + // should be better called 'isValidChar()', because it checks for comments + // and escaped chars like backslash and dollar in '\\' and '\$' + if(mathname == "$") { + // count and continue search + ++numDollar; + + // but remember the first dollar found backwards + if(!foundDollar) { + lastrow = row; + lastcol = col; + foundDollar = true; + } + } + else if(mathname=="\\[" || mathname=="\\(") { + // found start of mathmode + if(numDollar == 0) { + mathdata.tag = ( mathname == "\\[" ) ? mmDisplaymathParen : mmMathParen; + mathdata.numdollar = 0; + return true; + } + else { + //KILE_DEBUG_MAIN << "error: dollar not allowed in \\[ or \\( mode"; + return false; + } + } + else if(mathname=="\\]" || mathname=="\\)") { + continueSearch = false; + break; + } + else if(mathname=="\\b") { + // save name of environment + QString envname = reg.cap(1); + + // if we found the opening tag of a math env + if(m_latexCommands->isMathEnv(envname) || envname=="math") { + if(numDollar > 0) { + //KILE_DEBUG_MAIN << "error: dollar not allowed in math env numdollar=" << numDollar; + return false; + } + + // if this is a math env with its own mathmode, we have found the starting position + if(envname == "math") { + mathdata.tag = mmMathEnv; + mathdata.envname = envname; + return true; + } + + if(!m_latexCommands->needsMathMode(envname)) { + mathdata.tag = mmDisplaymathEnv; + mathdata.envname = envname; + return true; + } + } + // no math env, we found the opening tag of a normal env + else { + continueSearch = false; + break; + } + } + else if(mathname == "\\e") { + QString envname = reg.cap(2); + + // if we found the closing tag of a math env + if(m_latexCommands->isMathEnv(envname) || envname == "math") { + // if this is a math env with its own mathmode + if(!m_latexCommands->needsMathMode(envname) || envname == "math") { + continueSearch = false; + break; + } + + // if this is a math env which needs $..$ + if(m_latexCommands->isMathModeEnv(envname)) { + if(numDollar >= 1) { + --numDollar; + continueSearch = false; + break; + } + // else continue search + } + } + // if we found the closing tag of a normal env + else { + continueSearch = false; + break; + } + } + else { + //KILE_DEBUG_MAIN << "error: unknown match"; + return false; + } + + // continue search one column left of the last match (if this is possible) + if(col == 0) { + break; + } + + --col; + } + + if(row > 0) { + textline = getTextLineReal(doc,--row); + col = textline.length(); + } + else if(column == -1) { + continueSearch = false; + break; + } + } + + // nothing else found, so math mode starts a the last dollar (the first one found backwards) + mathdata.row = lastrow; + mathdata.col = lastcol; + mathdata.len = 1; + mathdata.numdollar = numDollar; + + mathdata.tag = (numDollar > 0) ? mmMathDollar : mmNoMathMode; + + return true; } bool EditorExtension::findCloseMathTag(KTextEditor::Document *doc, int row, int col, MathData &mathdata) { - const QString regExpString = "\\$" - "|\\\\begin\\s*\\{([A-Za-z]+\\*?)\\}" - "|\\\\end\\s*\\{([A-Za-z]+\\*?)\\}" - "|\\\\\\[|\\\\\\]" - "|\\\\\\(|\\\\\\)"; + const QString regExpString = "\\$" + "|\\\\begin\\s*\\{([A-Za-z]+\\*?)\\}" + "|\\\\end\\s*\\{([A-Za-z]+\\*?)\\}" + "|\\\\\\[|\\\\\\]" + "|\\\\\\(|\\\\\\)"; // + int rowFound, colFound; // + QRegExp reg(regExpString); // + reg.setCaseSensitivity(Qt::CaseInsensitive); // + int lastMatch = 0; - int rowFound, colFound; - QRegExp reg(regExpString); - - KTextEditor::Range searchRange = KTextEditor::Range(KTextEditor::Cursor(row, col), doc->documentEnd()); - - while(true) { - QVector foundRanges = doc->searchText(searchRange, regExpString, KTextEditor::Regex | KTextEditor::CaseInsensitive); - if(foundRanges.isEmpty() || (foundRanges.size() == 1 && !foundRanges.first().isValid())) { - break; - } - - //KILE_DEBUG_MAIN << "number of ranges " << foundRanges.count(); - if(foundRanges.size() < 3) { - break; - } - - KTextEditor::Range range = foundRanges.first(); - //KILE_DEBUG_MAIN << "found math tag: " << doc->text(range); - if(!range.isValid()) { - break; - } - - rowFound = range.start().line(); - colFound = range.start().column(); - QString textFound = doc->text(range); - - // should be better called 'isValidChar()', because it checks for comments - // and escaped chars like backslash and dollar in '\\' and '\$' - if(isValidBackslash(doc, rowFound, colFound)) { - QString mathname = textFound.left(2); - - // always remember behind the last match - mathdata.row = rowFound; - mathdata.col = colFound; - mathdata.len = textFound.length(); - - if(mathname=="$") { - mathdata.tag = mmMathDollar; - return true; - } - else if(mathname=="\\]") { - mathdata.tag = mmDisplaymathParen; - return true; - } - else if(mathname=="\\)") { - mathdata.tag = mmMathParen; - return true; - } - else if(mathname=="\\[" || mathname=="\\(") { - //KILE_DEBUG_MAIN << "error: current mathgroup was not closed"; - return false; - } - else if(mathname=="\\b") { - QString envname = doc->text(foundRanges[1]); - if(!(m_latexCommands->isMathEnv(envname) || envname=="math")) { - //KILE_DEBUG_MAIN << "error: only math env are allowed in mathmode (found begin tag)"; - return false; - } - - if(!m_latexCommands->needsMathMode(envname) || envname=="math") { - //KILE_DEBUG_MAIN << "error: mathenv with its own mathmode are not allowed in mathmode "; - return false; - } - - // else continue search - } - else if(mathname == "\\e") { - QString envname = doc->text(foundRanges[2]); - if(!(m_latexCommands->isMathEnv(envname) || envname=="math")) { - //KILE_DEBUG_MAIN << "error: only math env are allowed in mathmode (found end tag)"; - return false; - } - - if(envname == "math") { - mathdata.tag = mmMathEnv; - mathdata.envname = envname; - return true; - } - - if(!m_latexCommands->needsMathMode(envname)) { - mathdata.tag = mmDisplaymathEnv; - mathdata.envname = envname; - return true; - } - - // else continue search - } - } - - // go ahead - searchRange = KTextEditor::Range(foundRanges.first().end(), doc->documentEnd()); - } - - //KILE_DEBUG_MAIN << "not found anything"; - return false; + int rowFound, colFound; + QRegExp reg(regExpString); + + KTextEditor::Range searchRange = KTextEditor::Range(KTextEditor::Cursor(row, col), doc->documentEnd()); + + while(true) { + QVector foundRanges = doc->searchText(searchRange, regExpString, KTextEditor::Regex | KTextEditor::CaseInsensitive); + if(foundRanges.isEmpty() || (foundRanges.size() == 1 && !foundRanges.first().isValid())) { + break; + } + + //KILE_DEBUG_MAIN << "number of ranges " << foundRanges.count(); + if(foundRanges.size() < 3) { + break; + } + + KTextEditor::Range range = foundRanges.first(); + //KILE_DEBUG_MAIN << "found math tag: " << doc->text(range); + if(!range.isValid()) { + break; + } + + rowFound = range.start().line(); + colFound = range.start().column(); + QString textFound = doc->text(range); + + // should be better called 'isValidChar()', because it checks for comments + // and escaped chars like backslash and dollar in '\\' and '\$' + if(isValidBackslash(doc, rowFound, colFound)) { + QString mathname = textFound.left(2); + + // always remember behind the last match + mathdata.row = rowFound; + mathdata.col = colFound; + mathdata.len = textFound.length(); + + if(mathname=="$") { + mathdata.tag = mmMathDollar; + return true; + } + else if(mathname=="\\]") { + mathdata.tag = mmDisplaymathParen; + return true; + } + else if(mathname=="\\)") { + mathdata.tag = mmMathParen; + return true; + } + else if(mathname=="\\[" || mathname=="\\(") { + //KILE_DEBUG_MAIN << "error: current mathgroup was not closed"; + return false; + } + else if(mathname=="\\b") { + QString envname = doc->text(foundRanges[1]); + if(!(m_latexCommands->isMathEnv(envname) || envname=="math")) { + //KILE_DEBUG_MAIN << "error: only math env are allowed in mathmode (found begin tag)"; + return false; + } + + if(!m_latexCommands->needsMathMode(envname) || envname=="math") { + //KILE_DEBUG_MAIN << "error: mathenv with its own mathmode are not allowed in mathmode "; + return false; + } + + // else continue search + } + else if(mathname == "\\e") { + QString envname = doc->text(foundRanges[2]); + if(!(m_latexCommands->isMathEnv(envname) || envname=="math")) { + //KILE_DEBUG_MAIN << "error: only math env are allowed in mathmode (found end tag)"; + return false; + } + + if(envname == "math") { + mathdata.tag = mmMathEnv; + mathdata.envname = envname; + return true; + } + + if(!m_latexCommands->needsMathMode(envname)) { + mathdata.tag = mmDisplaymathEnv; + mathdata.envname = envname; + return true; + } + + // else continue search + } + } + + // go ahead + searchRange = KTextEditor::Range(foundRanges.first().end(), doc->documentEnd()); + } + + //KILE_DEBUG_MAIN << "not found anything"; + return false; } //////////////////// insert newlines inside an environment //////////////////// // intelligent newlines: look for the last opened environment // and decide what to insert // or continue the comment void EditorExtension::insertIntelligentNewline(KTextEditor::View *view) { - KILE_DEBUG_MAIN << view; - - view = determineView(view); - - if(!view) { - return; - } - - KTextEditor::Document* doc = view->document(); - - if(!doc) { - return; - } - - QString name; - KTextEditor::Cursor cursor = view->cursorPosition(); - int row = cursor.line(); - int col = cursor.column(); - - QString newLineAndIndentationString = '\n' + extractIndentationString(view, row); - - if(isCommentPosition(doc, row, col)) { - KILE_DEBUG_MAIN << "found comment"; - view->insertText(newLineAndIndentationString + "% "); - moveCursorToLastPositionInCurrentLine(view); - return; - } - else if(findOpenedEnvironment(row, col, name, view)) { - if(m_latexCommands->isListEnv(name)) { - if ( name == "description" ) { - view->insertText(newLineAndIndentationString + "\\item[]"); - } - else { - view->insertText(newLineAndIndentationString + "\\item "); - } - moveCursorToLastPositionInCurrentLine(view); - return; - } - else if(m_latexCommands->isTabularEnv(name) || m_latexCommands->isMathEnv(name)) { - view->insertText(newLineAndIndentationString + "\\\\"); - moveCursorToLastPositionInCurrentLine(view); - return; - } - } - // - no comment position - // - found no opened environment - // - unknown environment - // - finish tabular or math environment - view->insertText(newLineAndIndentationString); - moveCursorToLastPositionInCurrentLine(view); + KILE_DEBUG_MAIN << view; + + view = determineView(view); + + if(!view) { + return; + } + + KTextEditor::Document* doc = view->document(); + + if(!doc) { + return; + } + + QString name; + KTextEditor::Cursor cursor = view->cursorPosition(); + int row = cursor.line(); + int col = cursor.column(); + + QString newLineAndIndentationString = '\n' + extractIndentationString(view, row); + + if(isCommentPosition(doc, row, col)) { + KILE_DEBUG_MAIN << "found comment"; + view->insertText(newLineAndIndentationString + "% "); + moveCursorToLastPositionInCurrentLine(view); + return; + } + else if(findOpenedEnvironment(row, col, name, view)) { + if(m_latexCommands->isListEnv(name)) { + if ( name == "description" ) { + view->insertText(newLineAndIndentationString + "\\item[]"); + } + else { + view->insertText(newLineAndIndentationString + "\\item "); + } + moveCursorToLastPositionInCurrentLine(view); + return; + } + else if(m_latexCommands->isTabularEnv(name) || m_latexCommands->isMathEnv(name)) { + view->insertText(newLineAndIndentationString + "\\\\"); + moveCursorToLastPositionInCurrentLine(view); + return; + } + } + // - no comment position + // - found no opened environment + // - unknown environment + // - finish tabular or math environment + view->insertText(newLineAndIndentationString); + moveCursorToLastPositionInCurrentLine(view); } bool EditorExtension::findOpenedEnvironment(int &row, int &col, QString &envname, KTextEditor::View *view) { - view = determineView(view); - if(!view) { - return false; - } - - // get current cursor position - KTextEditor::Document *doc = view->document(); - KTextEditor::Cursor cursor = view->cursorPosition(); - row = cursor.line(); - col = cursor.column(); - - EnvData env; - int startrow = row; - int startcol = col; - - //KILE_DEBUG_MAIN << " close - start "; - // accept a starting place outside an environment - bool env_position = isEnvironmentPosition(doc, row, col, env); - - // We can also accept a column, if we are on the left side of an environment. - // But we should decrease the current cursor position for the search. - if(env_position && env.cpos != EnvInside) { - if(env.cpos == EnvLeft && !decreaseCursorPosition(doc, startrow, startcol)) { - return false; - } - env_position = false; - } - - if(!env_position && findEnvironmentTag(doc, startrow, startcol, env, true)) { - //KILE_DEBUG_MAIN << " close - found begin env at: " << env.row << "/" << env.col << " " << env.name; - row = env.row; - col = env.col; - envname = env.name; - return true; - } - else { - return false; - } + view = determineView(view); + if(!view) { + return false; + } + + // get current cursor position + KTextEditor::Document *doc = view->document(); + KTextEditor::Cursor cursor = view->cursorPosition(); + row = cursor.line(); + col = cursor.column(); + + EnvData env; + int startrow = row; + int startcol = col; + + //KILE_DEBUG_MAIN << " close - start "; + // accept a starting place outside an environment + bool env_position = isEnvironmentPosition(doc, row, col, env); + + // We can also accept a column, if we are on the left side of an environment. + // But we should decrease the current cursor position for the search. + if(env_position && env.cpos != EnvInside) { + if(env.cpos == EnvLeft && !decreaseCursorPosition(doc, startrow, startcol)) { + return false; + } + env_position = false; + } + + if(!env_position && findEnvironmentTag(doc, startrow, startcol, env, true)) { + //KILE_DEBUG_MAIN << " close - found begin env at: " << env.row << "/" << env.col << " " << env.name; + row = env.row; + col = env.col; + envname = env.name; + return true; + } + else { + return false; + } } QStringList EditorExtension::findOpenedEnvironmentList(KTextEditor::View *view, bool position) { - QStringList envlist; - - view = determineView(view); - if(view) { - int currentRow, currentCol; - KTextEditor::Document *doc = view->document(); - KTextEditor::Cursor cursor = view->cursorPosition(); - currentRow = cursor.line(); - currentCol = cursor.column(); - - - int row = currentRow; - int col = currentCol; - EnvData env; - - // check the starting position - bool env_position = isEnvironmentPosition(doc, row, col, env); - if(env_position) { - // we are inside an environment tag: bad to complete - if(env.cpos == EnvInside) { - return envlist; - } - // we are left of an environment tag: go one position to the left - if(env.cpos == EnvLeft) { - if (!decreaseCursorPosition(doc, row, col)) { - return envlist; - } - } - } - - while (findEnvironmentTag(doc, row, col, env, true)) { - row = env.row; - col = env.col; - - if(position) { - envlist << env.name + QString(",%1,%2").arg(row).arg(col); - } - else { - envlist << env.name; - } - - if(col == 0) { - if (!decreaseCursorPosition(doc, row, col)) { - break; - } - } - view->setCursorPosition(KTextEditor::Cursor(row, col)); - } - - // reset cursor original position - view->setCursorPosition(KTextEditor::Cursor(currentRow, currentCol)); - } - - return envlist; + QStringList envlist; + + view = determineView(view); + if(view) { + int currentRow, currentCol; + KTextEditor::Document *doc = view->document(); + KTextEditor::Cursor cursor = view->cursorPosition(); + currentRow = cursor.line(); + currentCol = cursor.column(); + + + int row = currentRow; + int col = currentCol; + EnvData env; + + // check the starting position + bool env_position = isEnvironmentPosition(doc, row, col, env); + if(env_position) { + // we are inside an environment tag: bad to complete + if(env.cpos == EnvInside) { + return envlist; + } + // we are left of an environment tag: go one position to the left + if(env.cpos == EnvLeft) { + if (!decreaseCursorPosition(doc, row, col)) { + return envlist; + } + } + } + + while (findEnvironmentTag(doc, row, col, env, true)) { + row = env.row; + col = env.col; + + if(position) { + envlist << env.name + QString(",%1,%2").arg(row).arg(col); + } + else { + envlist << env.name; + } + + if(col == 0) { + if (!decreaseCursorPosition(doc, row, col)) { + break; + } + } + view->setCursorPosition(KTextEditor::Cursor(row, col)); + } + + // reset cursor original position + view->setCursorPosition(KTextEditor::Cursor(currentRow, currentCol)); + } + + return envlist; } //////////////////// select an environment //////////////////// void EditorExtension::selectEnvironment(bool inside, KTextEditor::View *view) { - view = determineView(view); - if(!view) { - return; - } + view = determineView(view); + if(!view) { + return; + } - if (!view->selection() || !expandSelectionEnvironment(inside,view)) { - KTextEditor::Range range = environmentRange(inside,view); - if(range.isValid()) { - view->setSelection(range); - } - } + if (!view->selection() || !expandSelectionEnvironment(inside,view)) { + KTextEditor::Range range = environmentRange(inside,view); + if(range.isValid()) { + view->setSelection(range); + } + } } void EditorExtension::deleteEnvironment(bool inside, KTextEditor::View *view) { - view = determineView(view); - if(!view) { - return; - } + view = determineView(view); + if(!view) { + return; + } - KTextEditor::Range range = environmentRange(inside,view); - if(range.isValid()) { - deleteRange(range,view); - } + KTextEditor::Range range = environmentRange(inside,view); + if(range.isValid()) { + deleteRange(range,view); + } } void EditorExtension::deleteRange(KTextEditor::Range &range, KTextEditor::View *view) { - view->removeSelection(); - view->document()->removeText(range); - view->setCursorPosition(range.start()); + view->removeSelection(); + view->document()->removeText(range); + view->setCursorPosition(range.start()); } // calculate start and end of an environment bool EditorExtension::getEnvironment(bool inside, EnvData &envbegin, EnvData &envend, KTextEditor::View *view) { - view = determineView(view); - if(!view) { - return false; - } + view = determineView(view); + if(!view) { + return false; + } - int row, col; + int row, col; - KTextEditor::Document *doc = view->document(); - KTextEditor::Cursor cursor = view->cursorPosition(); - row = cursor.line(); - col = cursor.column(); - if(!findBeginEnvironment(doc, row, col, envbegin)) { - return false; - } - if(!findEndEnvironment(doc, row, col, envend)) { - return false; - } + KTextEditor::Document *doc = view->document(); + KTextEditor::Cursor cursor = view->cursorPosition(); + row = cursor.line(); + col = cursor.column(); + if(!findBeginEnvironment(doc, row, col, envbegin)) { + return false; + } + if(!findEndEnvironment(doc, row, col, envend)) { + return false; + } - if(inside) { - envbegin.col += envbegin.len; - } - else { - envend.col += envend.len; - } + if(inside) { + envbegin.col += envbegin.len; + } + else { + envend.col += envend.len; + } - return true; + return true; } KTextEditor::Range EditorExtension::environmentRange(bool inside, KTextEditor::View *view) { - // view will be checked in getEnvironment() - EnvData envbegin, envend; - return (getEnvironment(inside, envbegin, envend, view)) - ? KTextEditor::Range(envbegin.row, envbegin.col, envend.row, envend.col) - : KTextEditor::Range::invalid(); + // view will be checked in getEnvironment() + EnvData envbegin, envend; + return (getEnvironment(inside, envbegin, envend, view)) + ? KTextEditor::Range(envbegin.row, envbegin.col, envend.row, envend.col) + : KTextEditor::Range::invalid(); } QString EditorExtension::environmentText(bool inside, KTextEditor::View *view) { - view = determineView(view); - if(!view) { - return QString(); - } + view = determineView(view); + if(!view) { + return QString(); + } - KTextEditor::Range range = environmentRange(inside,view); - return (range.isValid()) ? view->document()->text(range) : QString(); + KTextEditor::Range range = environmentRange(inside,view); + return (range.isValid()) ? view->document()->text(range) : QString(); } QString EditorExtension::environmentName(KTextEditor::View *view) { - // view will be checked in getEnvironment() - EnvData envbegin, envend; - return (getEnvironment(false, envbegin, envend, view)) ? envbegin.name : QString(); + // view will be checked in getEnvironment() + EnvData envbegin, envend; + return (getEnvironment(false, envbegin, envend, view)) ? envbegin.name : QString(); } // determine text, startrow and startcol of current environment QString EditorExtension::getEnvironmentText(int &row, int &col, QString &name, KTextEditor::View *view) { - view = determineView(view); - if(!view) { - return QString(); - } + view = determineView(view); + if(!view) { + return QString(); + } - EnvData envbegin, envend; + EnvData envbegin, envend; - if(getEnvironment(false, envbegin, envend, view) && envbegin.name != "document") { - row = envbegin.row; - col = envbegin.col; - name = envbegin.name; - return view->document()->text(KTextEditor::Range(envbegin.row, envbegin.col, envend.row, envend.col)); - } - else { - return QString(); - } + if(getEnvironment(false, envbegin, envend, view) && envbegin.name != "document") { + row = envbegin.row; + col = envbegin.col; + name = envbegin.name; + return view->document()->text(KTextEditor::Range(envbegin.row, envbegin.col, envend.row, envend.col)); + } + else { + return QString(); + } } bool EditorExtension::hasEnvironment(KTextEditor::View *view) { - view = determineView(view); - if(!view) { - return false; - } + view = determineView(view); + if(!view) { + return false; + } - EnvData envbegin,envend; - return (getEnvironment(false, envbegin, envend, view) && envbegin.name != "document"); + EnvData envbegin,envend; + return (getEnvironment(false, envbegin, envend, view) && envbegin.name != "document"); } // when an environment is selected (inside or outside), // the selection is expanded to the surrounding environment bool EditorExtension::expandSelectionEnvironment(bool inside, KTextEditor::View *view) { - KTextEditor::Document *doc = view->document(); - if (!view->selection()) { - return false; - } - - // get current position - int row, col; - KTextEditor::Cursor cursor = view->cursorPosition(); - row = cursor.line(); - col = cursor.column(); - - // get current selection - KTextEditor::Range selectionRange = view->selectionRange(); - int row1 = selectionRange.start().line(); - int col1 = selectionRange.start().column(); - int row2 = selectionRange.end().line(); - int col2 = selectionRange.end().column(); - - // determine current environment outside - EnvData oenvbegin,oenvend; - if(!getEnvironment(false, oenvbegin, oenvend, view)) { - return false; - } - - bool newselection = false; - // first look, if this environment is selected outside - if(row1 == oenvbegin.row && col1 == oenvbegin.col && row2 == oenvend.row && col2 == oenvend.col) { - - if(!decreaseCursorPosition(doc, oenvbegin.row, oenvbegin.col) ) { - return newselection; - } - view->setCursorPosition(KTextEditor::Cursor(oenvbegin.row, oenvbegin.col)); - // search the surrounding environment and select it - if(getEnvironment(inside, oenvbegin, oenvend, view)) { - view->setSelection(KTextEditor::Range(oenvbegin.row, oenvbegin.col, oenvend.row, oenvend.col)); - newselection = true; - - } - } - else { - // then determine current environment inside - EnvData ienvbegin, ienvend; - getEnvironment(true, ienvbegin, ienvend, view); - // and look, if this environment is selected inside - if(row1 == ienvbegin.row && col1 == ienvbegin.col && row2 == ienvend.row && col2 == ienvend.col) { - if(!decreaseCursorPosition(doc, oenvbegin.row, oenvbegin.col) ) { - return newselection; - } - view->setCursorPosition(KTextEditor::Cursor(oenvbegin.row, oenvbegin.col)); - // search the surrounding environment and select it - if(getEnvironment(inside, ienvbegin, ienvend, view)) { - view->setSelection(KTextEditor::Range(ienvbegin.row, ienvbegin.col, ienvend.row, ienvend.col)); - newselection = true; - } - - } - } - - // restore old cursor position - view->setCursorPosition(KTextEditor::Cursor(row, col)); - return newselection; + KTextEditor::Document *doc = view->document(); + if (!view->selection()) { + return false; + } + + // get current position + int row, col; + KTextEditor::Cursor cursor = view->cursorPosition(); + row = cursor.line(); + col = cursor.column(); + + // get current selection + KTextEditor::Range selectionRange = view->selectionRange(); + int row1 = selectionRange.start().line(); + int col1 = selectionRange.start().column(); + int row2 = selectionRange.end().line(); + int col2 = selectionRange.end().column(); + + // determine current environment outside + EnvData oenvbegin,oenvend; + if(!getEnvironment(false, oenvbegin, oenvend, view)) { + return false; + } + + bool newselection = false; + // first look, if this environment is selected outside + if(row1 == oenvbegin.row && col1 == oenvbegin.col && row2 == oenvend.row && col2 == oenvend.col) { + + if(!decreaseCursorPosition(doc, oenvbegin.row, oenvbegin.col) ) { + return newselection; + } + view->setCursorPosition(KTextEditor::Cursor(oenvbegin.row, oenvbegin.col)); + // search the surrounding environment and select it + if(getEnvironment(inside, oenvbegin, oenvend, view)) { + view->setSelection(KTextEditor::Range(oenvbegin.row, oenvbegin.col, oenvend.row, oenvend.col)); + newselection = true; + + } + } + else { + // then determine current environment inside + EnvData ienvbegin, ienvend; + getEnvironment(true, ienvbegin, ienvend, view); + // and look, if this environment is selected inside + if(row1 == ienvbegin.row && col1 == ienvbegin.col && row2 == ienvend.row && col2 == ienvend.col) { + if(!decreaseCursorPosition(doc, oenvbegin.row, oenvbegin.col) ) { + return newselection; + } + view->setCursorPosition(KTextEditor::Cursor(oenvbegin.row, oenvbegin.col)); + // search the surrounding environment and select it + if(getEnvironment(inside, ienvbegin, ienvend, view)) { + view->setSelection(KTextEditor::Range(ienvbegin.row, ienvbegin.col, ienvend.row, ienvend.col)); + newselection = true; + } + + } + } + + // restore old cursor position + view->setCursorPosition(KTextEditor::Cursor(row, col)); + return newselection; } //////////////////// search for \begin{env} //////////////////// // Find the last \begin{env} tag. If the current cursor is over // - \begin{env} tag: we will stop immediately // - \end{env} tag: we will start before this tag bool EditorExtension::findBeginEnvironment(KTextEditor::Document *doc, int row, int col, EnvData &env) { - // KILE_DEBUG_MAIN << " find begin: "; - if(isEnvironmentPosition(doc, row, col, env)) { - // already found position? - //KILE_DEBUG_MAIN << " found env at: " << env.row << "/" << env.col << " " << env.name; - if(env.tag == EnvBegin) { - //KILE_DEBUG_MAIN << " is begin env at: " << env.row << "/" << env.col << " " << env.name; - return true; - } - - // go one position back - //KILE_DEBUG_MAIN << " is end env at: " << env.row << "/" << env.col << " " << env.name; - row = env.row; - col = env.col; - if(!decreaseCursorPosition(doc, row, col)) { - return false; - } - } - - // looking back for last environment - //KILE_DEBUG_MAIN << " looking back from pos: " << row << "/" << col << " " << env.name; - return findEnvironmentTag(doc, row, col, env, true); + // KILE_DEBUG_MAIN << " find begin: "; + if(isEnvironmentPosition(doc, row, col, env)) { + // already found position? + //KILE_DEBUG_MAIN << " found env at: " << env.row << "/" << env.col << " " << env.name; + if(env.tag == EnvBegin) { + //KILE_DEBUG_MAIN << " is begin env at: " << env.row << "/" << env.col << " " << env.name; + return true; + } + + // go one position back + //KILE_DEBUG_MAIN << " is end env at: " << env.row << "/" << env.col << " " << env.name; + row = env.row; + col = env.col; + if(!decreaseCursorPosition(doc, row, col)) { + return false; + } + } + + // looking back for last environment + //KILE_DEBUG_MAIN << " looking back from pos: " << row << "/" << col << " " << env.name; + return findEnvironmentTag(doc, row, col, env, true); } //////////////////// search for \end{env} //////////////////// // Find the last \end{env} tag. If the current cursor is over // - \end{env} tag: we will stop immediately // - \begin{env} tag: we will start behind this tag bool EditorExtension::findEndEnvironment(KTextEditor::Document *doc, int row, int col, EnvData &env) { - if(isEnvironmentPosition(doc, row, col, env)) { - // already found position? - if(env.tag == EnvEnd ) { - return true; - } + if(isEnvironmentPosition(doc, row, col, env)) { + // already found position? + if(env.tag == EnvEnd ) { + return true; + } - // go one position forward - row = env.row; - col = env.col + 1; - } + // go one position forward + row = env.row; + col = env.col + 1; + } - // looking forward for the next environment - return findEnvironmentTag(doc, row, col, env, false); + // looking forward for the next environment + return findEnvironmentTag(doc, row, col, env, false); } //////////////////// search for an environment tag //////////////////// // find the last/next non-nested environment tag bool EditorExtension::findEnvironmentTag(KTextEditor::Document *doc, int row, int col, EnvData &env, bool backwards) { - unsigned int envcount = 0; - - KTextEditor::Range searchRange; - if(backwards) { - searchRange = KTextEditor::Range(KTextEditor::Cursor(0, 0), KTextEditor::Cursor(row, col)); - } - else { - searchRange = KTextEditor::Range(KTextEditor::Cursor(row, col), doc->documentEnd()); - } - - KTextEditor::SearchOptions searchOptions = (backwards) ? KTextEditor::Regex | KTextEditor::Backwards : KTextEditor::Regex; - - while(true) { - QVector foundRanges = doc->searchText(searchRange, m_reg.pattern(), searchOptions); - if(foundRanges.isEmpty() || (foundRanges.size() == 1 && !foundRanges.first().isValid())) { - break; - } - - //KILE_DEBUG_MAIN << "number of ranges " << foundRanges.count(); - - EnvTag wrong_env = (backwards) ? EnvEnd : EnvBegin; - - if(foundRanges.size() < 5) { - break; - } - - KTextEditor::Range range = foundRanges.first(); - - if(!range.isValid()) { - //KILE_DEBUG_MAIN << "invalid range found"; - break; - } - env.row = range.start().line(); - env.col = range.start().column(); - env.len = doc->text(range).length(); - - if(isValidBackslash(doc, env.row, env.col)) { - // index 0 is the fullmatch, 1 first cap and so on - QString cap2 = (foundRanges[2].isValid() ? doc->text(foundRanges[2]) : ""); - QString cap3 = (foundRanges[3].isValid() ? doc->text(foundRanges[3]) : ""); - QString cap4 = (foundRanges[4].isValid() ? doc->text(foundRanges[4]) : ""); - EnvTag found_env = (cap2 == "begin" || cap4 == "\\[") ? EnvBegin : EnvEnd; - if(found_env == wrong_env) { - ++envcount; - } - else { - if(envcount > 0) { - --envcount; - } - else { - if(found_env == EnvBegin) { - env.name = (cap2 == "begin") ? cap3 : "\\["; - } - else { - env.name = (cap2 == "end") ? cap3 : "\\]"; - } - env.tag = found_env; - //KILE_DEBUG_MAIN << "found " << env.name; - return true; - } - } - } - - // finally, prepare the range for the next search - if(backwards) { - searchRange = KTextEditor::Range(KTextEditor::Cursor(0, 0), foundRanges.first().start()); - } - else { - searchRange = KTextEditor::Range(foundRanges.first().end(), doc->documentEnd()); - } - } - - //KILE_DEBUG_MAIN << "not found anything"; - return false; + unsigned int envcount = 0; + + KTextEditor::Range searchRange; + if(backwards) { + searchRange = KTextEditor::Range(KTextEditor::Cursor(0, 0), KTextEditor::Cursor(row, col)); + } + else { + searchRange = KTextEditor::Range(KTextEditor::Cursor(row, col), doc->documentEnd()); + } + + KTextEditor::SearchOptions searchOptions = (backwards) ? KTextEditor::Regex | KTextEditor::Backwards : KTextEditor::Regex; + + while(true) { + QVector foundRanges = doc->searchText(searchRange, m_reg.pattern(), searchOptions); + if(foundRanges.isEmpty() || (foundRanges.size() == 1 && !foundRanges.first().isValid())) { + break; + } + + //KILE_DEBUG_MAIN << "number of ranges " << foundRanges.count(); + + EnvTag wrong_env = (backwards) ? EnvEnd : EnvBegin; + + if(foundRanges.size() < 5) { + break; + } + + KTextEditor::Range range = foundRanges.first(); + + if(!range.isValid()) { + //KILE_DEBUG_MAIN << "invalid range found"; + break; + } + env.row = range.start().line(); + env.col = range.start().column(); + env.len = doc->text(range).length(); + + if(isValidBackslash(doc, env.row, env.col)) { + // index 0 is the fullmatch, 1 first cap and so on + QString cap2 = (foundRanges[2].isValid() ? doc->text(foundRanges[2]) : ""); + QString cap3 = (foundRanges[3].isValid() ? doc->text(foundRanges[3]) : ""); + QString cap4 = (foundRanges[4].isValid() ? doc->text(foundRanges[4]) : ""); + EnvTag found_env = (cap2 == "begin" || cap4 == "\\[") ? EnvBegin : EnvEnd; + if(found_env == wrong_env) { + ++envcount; + } + else { + if(envcount > 0) { + --envcount; + } + else { + if(found_env == EnvBegin) { + env.name = (cap2 == "begin") ? cap3 : "\\["; + } + else { + env.name = (cap2 == "end") ? cap3 : "\\]"; + } + env.tag = found_env; + //KILE_DEBUG_MAIN << "found " << env.name; + return true; + } + } + } + + // finally, prepare the range for the next search + if(backwards) { + searchRange = KTextEditor::Range(KTextEditor::Cursor(0, 0), foundRanges.first().start()); + } + else { + searchRange = KTextEditor::Range(foundRanges.first().end(), doc->documentEnd()); + } + } + + //KILE_DEBUG_MAIN << "not found anything"; + return false; } //////////////////// check for an environment position //////////////////// // Check if the current position belongs to an environment. The result is set // to the beginning backslash of the environment tag. The same algorithms as // matching brackets is used. // // insert mode: if there is a full tag on the left, always take it // if not, look to the right // overwrite mode: always take the tag, which begins at the cursor position // // test it with {a}{{b}}{c} bool EditorExtension::isEnvironmentPosition(KTextEditor::Document *doc, int row, int col, EnvData &env) { - // get real textline without comments, quoted characters and pairs of backslashes - QString textline = getTextLineReal(doc, row); - - if(col > textline.length()) { - return false; - } - - bool left = false; - - //KILE_DEBUG_MAIN << "col=" << col; - - // check if there is a match in this line from the current position to the left - int startcol = (textline[col] == '\\') ? col - 1 : col; - if(startcol >= 1) { - //KILE_DEBUG_MAIN << "search to the left "; - int pos = textline.lastIndexOf(m_reg, startcol); - env.len = m_reg.matchedLength(); - if(pos != -1 && pos < col && col <= pos + env.len) { - //KILE_DEBUG_MAIN << "search to the left: found"; - env.row = row; - env.col = pos; - QChar ch = textline.at(pos + 1); - if(ch=='b' || ch=='e') { - env.tag = (ch == 'b') ? EnvBegin : EnvEnd; - env.name = m_reg.cap(3); - } - else { - env.tag = (ch == '[') ? EnvBegin : EnvEnd; - env.name = m_reg.cap(4); - } - - if ( !m_overwritemode || (m_overwritemode && col textline.length()) { + return false; + } + + bool left = false; + + //KILE_DEBUG_MAIN << "col=" << col; + + // check if there is a match in this line from the current position to the left + int startcol = (textline[col] == '\\') ? col - 1 : col; + if(startcol >= 1) { + //KILE_DEBUG_MAIN << "search to the left "; + int pos = textline.lastIndexOf(m_reg, startcol); + env.len = m_reg.matchedLength(); + if(pos != -1 && pos < col && col <= pos + env.len) { + //KILE_DEBUG_MAIN << "search to the left: found"; + env.row = row; + env.col = pos; + QChar ch = textline.at(pos + 1); + if(ch=='b' || ch=='e') { + env.tag = (ch == 'b') ? EnvBegin : EnvEnd; + env.name = m_reg.cap(3); + } + else { + env.tag = (ch == '[') ? EnvBegin : EnvEnd; + env.name = m_reg.cap(4); + } + + if ( !m_overwritemode || (m_overwritemode && colline(row); - - bool backslash = false; - for(int i = 0; i < col; ++i) { - if(textline[i] == '%') { - if(!backslash) { // found a comment sign - return true; - } - else { - backslash = false; - } - } - else if(textline[i] == '\\') { // count number of backslashes - backslash = !backslash; - } - else { - backslash = false; // no backslash - } - } - - return false; + QString textline = doc->line(row); + + bool backslash = false; + for(int i = 0; i < col; ++i) { + if(textline[i] == '%') { + if(!backslash) { // found a comment sign + return true; + } + else { + backslash = false; + } + } + else if(textline[i] == '\\') { // count number of backslashes + backslash = !backslash; + } + else { + backslash = false; // no backslash + } + } + + return false; } // check if the character at text[col] is a valid backslash: // - there is no comment sign in this line before // - there is not a odd number of backslashes directly before bool EditorExtension::isValidBackslash(KTextEditor::Document *doc, int row, int col) { - QString textline = doc->line(row); - - bool backslash = false; - for(int i = 0; i < col; ++i) { - if(textline[i] == '%') { - if(!backslash) { - return false; // found a comment sign - } - else { - backslash = false; - } - } - else if(textline[i] == '\\') { // count number of backslashes - backslash = !backslash; - } - else { - backslash = false; // no backslash - } - } - - return !backslash; + QString textline = doc->line(row); + + bool backslash = false; + for(int i = 0; i < col; ++i) { + if(textline[i] == '%') { + if(!backslash) { + return false; // found a comment sign + } + else { + backslash = false; + } + } + else if(textline[i] == '\\') { // count number of backslashes + backslash = !backslash; + } + else { + backslash = false; // no backslash + } + } + + return !backslash; } //////////////////// goto next bullet //////////////////// void EditorExtension::gotoBullet(bool backwards, KTextEditor::View *view) { - view = determineView(view); - if(!view) { - return; - } - - // get current position - KTextEditor::Document *doc = view->document(); - - KTextEditor::Cursor cursor = view->cursorPosition(); - - KTextEditor::SearchOptions searchOptions = (backwards) ? KTextEditor::Backwards : KTextEditor::Default; - - KTextEditor::Range searchRange; - if(backwards) { - searchRange = KTextEditor::Range(KTextEditor::Cursor(0, 0), cursor); - } - else { - const KTextEditor::Cursor nextCursorPosition(cursor.line(), cursor.column() + 1); - if((doc->characterAt(cursor) == s_bullet_char) // we are already at a bullet - && view->selection() - && view->selectionRange() == KTextEditor::Range(cursor, nextCursorPosition)) { // which has been 'highlighted' - cursor = nextCursorPosition; // search for the next bullet - } - searchRange = KTextEditor::Range(cursor, doc->documentEnd()); - } - - QVector foundRanges = doc->searchText(searchRange, s_bullet, searchOptions); - if(foundRanges.size() >= 1) { - KTextEditor::Range range = foundRanges.first(); - if(range.isValid()) { - int line = range.start().line(); - int column = range.start().column(); - view->setCursorPosition(KTextEditor::Cursor(line, column)); - view->setSelection(KTextEditor::Range(line, column, line, column + 1)); - } - } + view = determineView(view); + if(!view) { + return; + } + + // get current position + KTextEditor::Document *doc = view->document(); + + KTextEditor::Cursor cursor = view->cursorPosition(); + + KTextEditor::SearchOptions searchOptions = (backwards) ? KTextEditor::Backwards : KTextEditor::Default; + + KTextEditor::Range searchRange; + if(backwards) { + searchRange = KTextEditor::Range(KTextEditor::Cursor(0, 0), cursor); + } + else { + const KTextEditor::Cursor nextCursorPosition(cursor.line(), cursor.column() + 1); + if((doc->characterAt(cursor) == s_bullet_char) // we are already at a bullet + && view->selection() + && view->selectionRange() == KTextEditor::Range(cursor, nextCursorPosition)) { // which has been 'highlighted' + cursor = nextCursorPosition; // search for the next bullet + } + searchRange = KTextEditor::Range(cursor, doc->documentEnd()); + } + + QVector foundRanges = doc->searchText(searchRange, s_bullet, searchOptions); + if(foundRanges.size() >= 1) { + KTextEditor::Range range = foundRanges.first(); + if(range.isValid()) { + int line = range.start().line(); + int column = range.start().column(); + view->setCursorPosition(KTextEditor::Cursor(line, column)); + view->setSelection(KTextEditor::Range(line, column, line, column + 1)); + } + } } //////////////////// increase/decrease cursor position //////////////////// bool EditorExtension::moveCursorRight(KTextEditor::View *view) { - return moveCursor(view, MoveCursorRight); + return moveCursor(view, MoveCursorRight); } bool EditorExtension::moveCursorLeft(KTextEditor::View *view) { - return moveCursor(view, MoveCursorLeft); + return moveCursor(view, MoveCursorLeft); } bool EditorExtension::moveCursorUp(KTextEditor::View *view) { - return moveCursor(view, MoveCursorUp); + return moveCursor(view, MoveCursorUp); } bool EditorExtension::moveCursorDown(KTextEditor::View *view) { - return moveCursor(view, MoveCursorDown); + return moveCursor(view, MoveCursorDown); } bool EditorExtension::moveCursor(KTextEditor::View *view, CursorMove direction) { - view = determineView(view); - if(!view) { - return false; - } - - KTextEditor::Document *doc = view->document(); - - KTextEditor::Cursor cursor = view->cursorPosition(); - int row = cursor.line(); - int col = cursor.column(); - - bool ok = false; - switch (direction) { - case MoveCursorLeft: ok = decreaseCursorPosition(doc,row,col); - break; - case MoveCursorRight: ok = increaseCursorPosition(doc,row,col); - break; - case MoveCursorUp: if(row > 0) { - row--; - ok = true; - } - break; - case MoveCursorDown: if(row < doc->lines() - 1) { - row++; - ok = true; - } - break; - } - - if(ok) { - return view->setCursorPosition(KTextEditor::Cursor(row,col)); - } - else { - return false; - } + view = determineView(view); + if(!view) { + return false; + } + + KTextEditor::Document *doc = view->document(); + + KTextEditor::Cursor cursor = view->cursorPosition(); + int row = cursor.line(); + int col = cursor.column(); + + bool ok = false; + switch (direction) { + case MoveCursorLeft: + ok = decreaseCursorPosition(doc,row,col); + break; + case MoveCursorRight: + ok = increaseCursorPosition(doc,row,col); + break; + case MoveCursorUp: + if(row > 0) { + row--; + ok = true; + } + break; + case MoveCursorDown: + if(row < doc->lines() - 1) { + row++; + ok = true; + } + break; + } + + if(ok) { + return view->setCursorPosition(KTextEditor::Cursor(row,col)); + } + else { + return false; + } } bool EditorExtension::increaseCursorPosition(KTextEditor::Document *doc, int &row, int &col) { - bool ok = true; + bool ok = true; - if(col < doc->lineLength(row) - 1) { - ++col; - } - else if(row < doc->lines() - 1) { - ++row; - col = 0; - } - else { - ok = false; - } + if(col < doc->lineLength(row) - 1) { + ++col; + } + else if(row < doc->lines() - 1) { + ++row; + col = 0; + } + else { + ok = false; + } - return ok; + return ok; } bool EditorExtension::decreaseCursorPosition(KTextEditor::Document *doc, int &row, int &col) { - bool ok = true; + bool ok = true; - if(col > 0) { - --col; - } - else if(row > 0) { - --row; - col = doc->lineLength(row); - } - else { - ok = false; - } + if(col > 0) { + --col; + } + else if(row > 0) { + --row; + col = doc->lineLength(row); + } + else { + ok = false; + } - return ok; + return ok; } //////////////////// texgroups //////////////////// // goto the next non-nested bracket void EditorExtension::gotoTexgroup(bool backwards, KTextEditor::View *view) { - view = determineView(view); - if(!view) return; - - uint row,col; - bool found; - BracketData bracket; - - // get current position - KTextEditor::Document *doc = view->document(); - KTextEditor::Cursor cursor = view->cursorPosition(); - row = cursor.line(); - col = cursor.column(); - m_overwritemode = (view->viewMode() == KTextEditor::View::NormalModeOverwrite); - - // start searching - if(backwards) { - found = findOpenBracket(doc, row, col, bracket); - } - else { - found = findCloseBracket(doc, row, col, bracket); - // go behind the bracket - if(!m_overwritemode) { - ++bracket.col; - } - } - - if(found) { - view->setCursorPosition(KTextEditor::Cursor(bracket.row, bracket.col)); - } + view = determineView(view); + if(!view) return; + + uint row,col; + bool found; + BracketData bracket; + + // get current position + KTextEditor::Document *doc = view->document(); + KTextEditor::Cursor cursor = view->cursorPosition(); + row = cursor.line(); + col = cursor.column(); + m_overwritemode = (view->viewMode() == KTextEditor::View::NormalModeOverwrite); + + // start searching + if(backwards) { + found = findOpenBracket(doc, row, col, bracket); + } + else { + found = findCloseBracket(doc, row, col, bracket); + // go behind the bracket + if(!m_overwritemode) { + ++bracket.col; + } + } + + if(found) { + view->setCursorPosition(KTextEditor::Cursor(bracket.row, bracket.col)); + } } // match the opposite bracket void EditorExtension::matchTexgroup(KTextEditor::View *view) { - view = determineView(view); - if(!view) { - return; - } - - int row, col; - BracketData bracket; - - // get current position - KTextEditor::Document *doc = view->document(); - KTextEditor::Cursor cursor = view->cursorPosition(); - row = cursor.line(); - col = cursor.column(); - m_overwritemode = (view->viewMode() == KTextEditor::View::NormalModeOverwrite); - - // this operation is only allowed at a bracket position - if(!isBracketPosition(doc, row, col, bracket)) { - return; - } - - // start searching - bool found = false; - if(bracket.open) { - found = findCloseBracketTag(doc, bracket.row, bracket.col + 1, bracket); - // go behind the bracket - if(!m_overwritemode) { - ++bracket.col; - } - } - else { - if(!decreaseCursorPosition(doc, bracket.row, bracket.col)) { - return; - } - found = findOpenBracketTag(doc, bracket.row, bracket.col, bracket); - } - - if(found) { - view->setCursorPosition(KTextEditor::Cursor(bracket.row, bracket.col)); - } + view = determineView(view); + if(!view) { + return; + } + + int row, col; + BracketData bracket; + + // get current position + KTextEditor::Document *doc = view->document(); + KTextEditor::Cursor cursor = view->cursorPosition(); + row = cursor.line(); + col = cursor.column(); + m_overwritemode = (view->viewMode() == KTextEditor::View::NormalModeOverwrite); + + // this operation is only allowed at a bracket position + if(!isBracketPosition(doc, row, col, bracket)) { + return; + } + + // start searching + bool found = false; + if(bracket.open) { + found = findCloseBracketTag(doc, bracket.row, bracket.col + 1, bracket); + // go behind the bracket + if(!m_overwritemode) { + ++bracket.col; + } + } + else { + if(!decreaseCursorPosition(doc, bracket.row, bracket.col)) { + return; + } + found = findOpenBracketTag(doc, bracket.row, bracket.col, bracket); + } + + if(found) { + view->setCursorPosition(KTextEditor::Cursor(bracket.row, bracket.col)); + } } //////////////////// close an open texgroup //////////////////// // search for the last opened texgroup and close it void EditorExtension::closeTexgroup(KTextEditor::View *view) { - view = determineView(view); - if(!view) { - return; - } + view = determineView(view); + if(!view) { + return; + } - int row, col; - BracketData bracket; + int row, col; + BracketData bracket; - KTextEditor::Document *doc = view->document(); - KTextEditor::Cursor cursor = view->cursorPosition(); - row = cursor.line(); - col = cursor.column(); + KTextEditor::Document *doc = view->document(); + KTextEditor::Cursor cursor = view->cursorPosition(); + row = cursor.line(); + col = cursor.column(); - int rowtemp = row; - int coltemp = col; - if(!decreaseCursorPosition(doc, rowtemp, coltemp)) { - return; - } + int rowtemp = row; + int coltemp = col; + if(!decreaseCursorPosition(doc, rowtemp, coltemp)) { + return; + } - if(findOpenBracketTag(doc, rowtemp, coltemp, bracket)) { - doc->insertText(KTextEditor::Cursor(row, col), "}"); - view->setCursorPosition(KTextEditor::Cursor(row, col + 1)); - } + if(findOpenBracketTag(doc, rowtemp, coltemp, bracket)) { + doc->insertText(KTextEditor::Cursor(row, col), "}"); + view->setCursorPosition(KTextEditor::Cursor(row, col + 1)); + } } //////////////////// select a texgroup //////////////////// void EditorExtension::selectTexgroup(bool inside, KTextEditor::View *view) { - view = determineView(view); - if(!view) { - return; - } + view = determineView(view); + if(!view) { + return; + } - KTextEditor::Range range = texgroupRange(inside,view); - if(range.isValid()) { - view->setSelection(range); - } + KTextEditor::Range range = texgroupRange(inside,view); + if(range.isValid()) { + view->setSelection(range); + } } void EditorExtension::deleteTexgroup(bool inside, KTextEditor::View *view) { - view = determineView(view); - if(!view) { - return; - } + view = determineView(view); + if(!view) { + return; + } - KTextEditor::Range range =texgroupRange(inside,view); - if(range.isValid()) { - deleteRange(range, view); - } + KTextEditor::Range range =texgroupRange(inside,view); + if(range.isValid()) { + deleteRange(range, view); + } } // calculate start and end of a Texgroup KTextEditor::Range EditorExtension::texgroupRange(bool inside, KTextEditor::View *view) { - view = determineView(view); - if(!view) { - return KTextEditor::Range::invalid(); - } + view = determineView(view); + if(!view) { + return KTextEditor::Range::invalid(); + } - BracketData open, close; - if(getTexgroup(inside, open, close, view)) { - return KTextEditor::Range(open.row, open.col, close.row, close.col); - } - else { - return KTextEditor::Range::invalid(); - } + BracketData open, close; + if(getTexgroup(inside, open, close, view)) { + return KTextEditor::Range(open.row, open.col, close.row, close.col); + } + else { + return KTextEditor::Range::invalid(); + } } bool EditorExtension::hasTexgroup(KTextEditor::View *view) { - // view will be checked in texgroupRange() - KTextEditor::Range range = texgroupRange(true, view); - return (range.isValid()) ? true : false; + // view will be checked in texgroupRange() + KTextEditor::Range range = texgroupRange(true, view); + return (range.isValid()) ? true : false; } QString EditorExtension::getTexgroupText(bool inside, KTextEditor::View *view) { - view = determineView(view); - if(!view) { - return QString(); - } + view = determineView(view); + if(!view) { + return QString(); + } - KTextEditor::Range range = texgroupRange(inside,view); - return (range.isValid()) ? view->document()->text(range) : QString(); + KTextEditor::Range range = texgroupRange(inside,view); + return (range.isValid()) ? view->document()->text(range) : QString(); } bool EditorExtension::getTexgroup(bool inside, BracketData &open, BracketData &close, KTextEditor::View *view) { - view = determineView(view); - if(!view) { - return false; - } + view = determineView(view); + if(!view) { + return false; + } - int row, col; + int row, col; - KTextEditor::Document *doc = view->document(); - KTextEditor::Cursor cursor = view->cursorPosition(); - row = cursor.line(); - col = cursor.column(); + KTextEditor::Document *doc = view->document(); + KTextEditor::Cursor cursor = view->cursorPosition(); + row = cursor.line(); + col = cursor.column(); - if(!findOpenBracket(doc, row, col, open)) { - //KILE_DEBUG_MAIN << "no open bracket"; - return false; - } - if(!findCloseBracket(doc, row, col, close)) { - //KILE_DEBUG_MAIN << "no close bracket"; - return false; - } + if(!findOpenBracket(doc, row, col, open)) { + //KILE_DEBUG_MAIN << "no open bracket"; + return false; + } + if(!findCloseBracket(doc, row, col, close)) { + //KILE_DEBUG_MAIN << "no close bracket"; + return false; + } - if(inside) { - ++open.col; - } - else { - ++close.col; - } + if(inside) { + ++open.col; + } + else { + ++close.col; + } - return true; + return true; } //////////////////// search for a bracket position //////////////////// // Find the last opening bracket. If the current cursor is over // - '{': we will stop immediately // - '}': we will start before this character bool EditorExtension::findOpenBracket(KTextEditor::Document *doc, int row, int col, BracketData &bracket) { - if(isBracketPosition(doc, row, col, bracket)) { - // already found position? - if(bracket.open) { - return true; - } - - // go one position back - row = bracket.row; - col = bracket.col; - if(!decreaseCursorPosition(doc, row, col)) { - return false; - } - } + if(isBracketPosition(doc, row, col, bracket)) { + // already found position? + if(bracket.open) { + return true; + } - // looking back for last bracket - return findOpenBracketTag(doc, row, col, bracket); + // go one position back + row = bracket.row; + col = bracket.col; + if(!decreaseCursorPosition(doc, row, col)) { + return false; + } + } + + // looking back for last bracket + return findOpenBracketTag(doc, row, col, bracket); } // Find the last closing bracket. If the current cursor is over // - '}': we will stop immediately // - '{': we will start behind this character bool EditorExtension::findCloseBracket(KTextEditor::Document *doc, int row, int col, BracketData &bracket) { - if (isBracketPosition(doc, row, col, bracket)) { - // already found position? - if(!bracket.open) { - return true; - } + if (isBracketPosition(doc, row, col, bracket)) { + // already found position? + if(!bracket.open) { + return true; + } - // go one position forward - row = bracket.row; - col = bracket.col + 1; - } + // go one position forward + row = bracket.row; + col = bracket.col + 1; + } - // looking forward for next bracket - return findCloseBracketTag(doc, row, col, bracket); + // looking forward for next bracket + return findCloseBracketTag(doc, row, col, bracket); } /* Bracket matching uses the following algorithm (taken from Kate): 1) If in overwrite mode, match the bracket currently underneath the cursor. 2) Otherwise, if the character to the left of the cursor is an ending bracket, match it. 3) Otherwise if the character to the right of the cursor is a starting bracket, match it. 4) Otherwise, if the character to the left of the cursor is a starting bracket, match it. 5) Otherwise, if the character to the right of the cursor is an ending bracket, match it. 6) Otherwise, don't match anything. */ bool EditorExtension::isBracketPosition(KTextEditor::Document *doc, int row, int col, BracketData &bracket) { - // default results - bracket.row = row; - bracket.col = col; - - QString textline = getTextLineReal(doc, row); - QChar right = textline[col]; - QChar left = (col > 0) ? textline[col-1] : QChar(' '); - - if (m_overwritemode) { - if(right == '{') { - bracket.open = true; - } - else if(left == '}') { - bracket.open = false; - } - else { - return false; - } - } - else if(left == '}') { - bracket.open = false; - --bracket.col; - } - else if(right == '{') { - bracket.open = true; - } - else if(left == '{') { - bracket.open = true; - --bracket.col; - } - else if(right == '}') { - bracket.open = false; - } - else { - return false; - } - - return true; + // default results + bracket.row = row; + bracket.col = col; + + QString textline = getTextLineReal(doc, row); + QChar right = textline[col]; + QChar left = (col > 0) ? textline[col-1] : QChar(' '); + + if (m_overwritemode) { + if(right == '{') { + bracket.open = true; + } + else if(left == '}') { + bracket.open = false; + } + else { + return false; + } + } + else if(left == '}') { + bracket.open = false; + --bracket.col; + } + else if(right == '{') { + bracket.open = true; + } + else if(left == '{') { + bracket.open = true; + --bracket.col; + } + else if(right == '}') { + bracket.open = false; + } + else { + return false; + } + + return true; } // find next non-nested closing bracket bool EditorExtension::findCloseBracketTag(KTextEditor::Document *doc, int row, int col, BracketData &bracket) { - uint brackets = 0; - for(int line = row; line < doc->lines(); ++line) { - uint start = (line == row) ? col : 0; - QString textline = getTextLineReal(doc,line); - for(int i = start; i < textline.length(); ++i) { - if(textline[i] == '{') { - ++brackets; - } - else if(textline[i] == '}') { - if(brackets > 0) { - --brackets; - } - else { - bracket.row = line; - bracket.col = i; - bracket.open = false; - return true; - } - } - } - } - - return false; + uint brackets = 0; + for(int line = row; line < doc->lines(); ++line) { + uint start = (line == row) ? col : 0; + QString textline = getTextLineReal(doc,line); + for(int i = start; i < textline.length(); ++i) { + if(textline[i] == '{') { + ++brackets; + } + else if(textline[i] == '}') { + if(brackets > 0) { + --brackets; + } + else { + bracket.row = line; + bracket.col = i; + bracket.open = false; + return true; + } + } + } + } + + return false; } // find next non-nested opening bracket bool EditorExtension::findOpenBracketTag(KTextEditor::Document *doc, int row, int col, BracketData &bracket) { - uint brackets = 0; - for(int line = row; line >= 0; --line) { - QString textline = getTextLineReal(doc, line); - int start = (line == row) ? col : textline.length() - 1; - for (int i = start; i >= 0; --i) { - //KILE_DEBUG_MAIN << "findOpenBracketTag: (" << line << "," << i << ") = " << textline[i].toLatin1(); - if(textline[i] == '{') { - if(brackets > 0) { - --brackets; - } - else { - bracket.row = line; - bracket.col = i; - bracket.open = true; - return true; - } - } - else if(textline[i] == '}') { - ++brackets; - } - } - } - - //KILE_DEBUG_MAIN << "nothting found"; - return false; + uint brackets = 0; + for(int line = row; line >= 0; --line) { + QString textline = getTextLineReal(doc, line); + int start = (line == row) ? col : textline.length() - 1; + for (int i = start; i >= 0; --i) { + //KILE_DEBUG_MAIN << "findOpenBracketTag: (" << line << "," << i << ") = " << textline[i].toLatin1(); + if(textline[i] == '{') { + if(brackets > 0) { + --brackets; + } + else { + bracket.row = line; + bracket.col = i; + bracket.open = true; + return true; + } + } + else if(textline[i] == '}') { + ++brackets; + } + } + } + + //KILE_DEBUG_MAIN << "nothting found"; + return false; } //////////////////// get real text //////////////////// // get current textline and remove // - all pairs of backslashes: '\\' // - all quoted comment signs: '\%' // - all quoted brackets: '\{' and '\}' // - all comments // replace these characters with one, which never will be looked for QString EditorExtension::getTextLineReal(KTextEditor::Document *doc, int row) { - QString textline = doc->line(row); - int len = textline.length(); - if(len == 0) { - return QString(); - } - - bool backslash = false; - for(int i = 0; i < len; ++i) { - if (textline[i]=='{' || textline[i]=='}' || textline[i]=='$') { - if(backslash) { - textline[i-1] = '&'; - textline[i] = '&'; - } - backslash = false; - } - else if(textline[i] == '\\') { - if(backslash) { - textline[i-1] = '&'; - textline[i] = '&'; - backslash = false; - } - else { - backslash = true; - } - } - else if(textline[i]=='%') { - if (backslash) { - textline[i-1] = '&'; - textline[i] = '&'; - } - else { - len = i; - break; - } - backslash = false; - } - else { - backslash = false; - } - } - - // return real text - return textline.left(len); + QString textline = doc->line(row); + int len = textline.length(); + if(len == 0) { + return QString(); + } + + bool backslash = false; + for(int i = 0; i < len; ++i) { + if (textline[i]=='{' || textline[i]=='}' || textline[i]=='$') { + if(backslash) { + textline[i-1] = '&'; + textline[i] = '&'; + } + backslash = false; + } + else if(textline[i] == '\\') { + if(backslash) { + textline[i-1] = '&'; + textline[i] = '&'; + backslash = false; + } + else { + backslash = true; + } + } + else if(textline[i]=='%') { + if (backslash) { + textline[i-1] = '&'; + textline[i] = '&'; + } + else { + len = i; + break; + } + backslash = false; + } + else { + backslash = false; + } + } + + // return real text + return textline.left(len); } //////////////////// capture the current word //////////////////// // Capture the current word from the cursor position to the left and right. // The result depens on the given search mode; // - smTex only letters, except backslash as first and star as last character // - smLetter: only letters // - smWord: letters and digits // - smNospace: everything except white space bool EditorExtension::getCurrentWord(KTextEditor::Document *doc, int row, int col, EditorExtension::SelectMode mode, QString &word, int &x1, int &x2) { - // get real textline without comments, quoted characters and pairs of backslashes - QString textline = getTextLineReal(doc, row); - if (col > textline.length()) { - return false; - } - - QRegExp reg; - QString pattern1, pattern2; - switch(mode) { - case smLetter: - pattern1 = "[^a-zA-Z]+"; - pattern2 = "[a-zA-Z]+"; - break; - case smWord: - pattern1 = "[^a-zA-Z0-9]"; - pattern2 = "[a-zA-Z0-9]+"; - break; - case smNospace: - pattern1 = "\\s"; - pattern2 = "\\S+"; - break; - default: - pattern1 = "[^a-zA-Z]"; - pattern2 = "\\\\?[a-zA-Z]+\\*?"; - break; - } - x1 = x2 = col; - - int pos; - // search to the left side - if(col > 0) { - reg.setPattern(pattern1); - pos = textline.lastIndexOf(reg, col - 1); - if(pos != -1) { // found an illegal character - x1 = pos + 1; - if(mode == smTex) { - if(textline[pos] == '\\') { - x1 = pos; - } - col = x1; - } - } - else { - x1 = 0; // pattern matches from beginning of line - } - } - - // search at the current position - reg.setPattern(pattern2); - pos = textline.indexOf(reg, col); - if(pos != -1 && pos == col) { - x2 = pos + reg.matchedLength(); - } - - // get all characters - if(x1 != x2) { - word = textline.mid(x1, x2 - x1); - return true; - } - else { - return false; - } + // get real textline without comments, quoted characters and pairs of backslashes + QString textline = getTextLineReal(doc, row); + if (col > textline.length()) { + return false; + } + + QRegExp reg; + QString pattern1, pattern2; + switch(mode) { + case smLetter: + pattern1 = "[^a-zA-Z]+"; + pattern2 = "[a-zA-Z]+"; + break; + case smWord: + pattern1 = "[^a-zA-Z0-9]"; + pattern2 = "[a-zA-Z0-9]+"; + break; + case smNospace: + pattern1 = "\\s"; + pattern2 = "\\S+"; + break; + default: + pattern1 = "[^a-zA-Z]"; + pattern2 = "\\\\?[a-zA-Z]+\\*?"; + break; + } + x1 = x2 = col; + + int pos; + // search to the left side + if(col > 0) { + reg.setPattern(pattern1); + pos = textline.lastIndexOf(reg, col - 1); + if(pos != -1) { // found an illegal character + x1 = pos + 1; + if(mode == smTex) { + if(textline[pos] == '\\') { + x1 = pos; + } + col = x1; + } + } + else { + x1 = 0; // pattern matches from beginning of line + } + } + + // search at the current position + reg.setPattern(pattern2); + pos = textline.indexOf(reg, col); + if(pos != -1 && pos == col) { + x2 = pos + reg.matchedLength(); + } + + // get all characters + if(x1 != x2) { + word = textline.mid(x1, x2 - x1); + return true; + } + else { + return false; + } } KTextEditor::Range EditorExtension::wordRange(const KTextEditor::Cursor &cursor, bool latexCommand, KTextEditor::View *view) { - view = determineView(view); - if(!view) { - return KTextEditor::Range::invalid(); - } + view = determineView(view); + if(!view) { + return KTextEditor::Range::invalid(); + } - int col1, col2; - QString word; - EditorExtension::SelectMode mode = ( latexCommand ) ? EditorExtension::smTex : EditorExtension::smLetter; - int line = cursor.line(); + int col1, col2; + QString word; + EditorExtension::SelectMode mode = ( latexCommand ) ? EditorExtension::smTex : EditorExtension::smLetter; + int line = cursor.line(); - return (getCurrentWord(view->document(), line, cursor.column(), mode, word, col1, col2)) - ? KTextEditor::Range(line,col1,line,col2) - : KTextEditor::Range::invalid(); + return (getCurrentWord(view->document(), line, cursor.column(), mode, word, col1, col2)) + ? KTextEditor::Range(line,col1,line,col2) + : KTextEditor::Range::invalid(); } QString EditorExtension::word(const KTextEditor::Cursor &cursor, bool latexCommand, KTextEditor::View *view) { - KTextEditor::Range range = EditorExtension::wordRange(cursor,latexCommand,view); - return ( range.isValid() ) ? view->document()->text(range) : QString(); + KTextEditor::Range range = EditorExtension::wordRange(cursor,latexCommand,view); + return ( range.isValid() ) ? view->document()->text(range) : QString(); } //////////////////// paragraph //////////////////// void EditorExtension::selectParagraph(KTextEditor::View* view, bool wholeLines) { - view = determineView(view); - if(!view) { - return; - } + view = determineView(view); + if(!view) { + return; + } - KTextEditor::Range range = findCurrentParagraphRange(view, wholeLines); - if ( range.isValid() ) { - view->setSelection(range); - } + KTextEditor::Range range = findCurrentParagraphRange(view, wholeLines); + if ( range.isValid() ) { + view->setSelection(range); + } } void EditorExtension::deleteParagraph(KTextEditor::View *view) { - view = determineView(view); - if(!view) { - return; - } - int startline, endline; - - if(findCurrentTexParagraph(startline, endline, view)) { - KTextEditor::Document *doc = view->document(); - view->removeSelection(); - if(startline > 0) { - --startline; - } - else if(endline < doc->lines() - 1) { - ++endline; - } - doc->removeText(KTextEditor::Range(startline, 0, endline+1, 0)); - view->setCursorPosition(KTextEditor::Cursor(startline, 0)); - } + view = determineView(view); + if(!view) { + return; + } + int startline, endline; + + if(findCurrentTexParagraph(startline, endline, view)) { + KTextEditor::Document *doc = view->document(); + view->removeSelection(); + if(startline > 0) { + --startline; + } + else if(endline < doc->lines() - 1) { + ++endline; + } + doc->removeText(KTextEditor::Range(startline, 0, endline+1, 0)); + view->setCursorPosition(KTextEditor::Cursor(startline, 0)); + } } // get the range of the current paragraph KTextEditor::Range EditorExtension::findCurrentParagraphRange(KTextEditor::View* view, bool wholeLines) { - view = determineView(view); - if(!view) { - return KTextEditor::Range::invalid(); - } + view = determineView(view); + if(!view) { + return KTextEditor::Range::invalid(); + } - int startline, endline, startcolumn, endcolumn; + int startline, endline, startcolumn, endcolumn; - if (findCurrentTexParagraph(startline, startcolumn, endline, endcolumn, view)) { - return wholeLines ? - KTextEditor::Range(startline, 0, endline + 1, 0) : - KTextEditor::Range(startline, startcolumn, endline, endcolumn); - } - else { - return KTextEditor::Range::invalid(); - } + if (findCurrentTexParagraph(startline, startcolumn, endline, endcolumn, view)) { + return wholeLines ? + KTextEditor::Range(startline, 0, endline + 1, 0) : + KTextEditor::Range(startline, startcolumn, endline, endcolumn); + } + else { + return KTextEditor::Range::invalid(); + } } QString EditorExtension::getParagraphText(KTextEditor::View *view) { - view = determineView(view); - if(!view) { - return QString(); - } + view = determineView(view); + if(!view) { + return QString(); + } - KTextEditor::Range range = findCurrentParagraphRange(view); - return (range.isValid()) ? view->document()->text(range) : QString(); + KTextEditor::Range range = findCurrentParagraphRange(view); + return (range.isValid()) ? view->document()->text(range) : QString(); } bool EditorExtension::findCurrentTexParagraph(int& startline, int& endline, KTextEditor::View* view) { - int dummy; - return findCurrentTexParagraph(startline, dummy, endline, dummy, view); + int dummy; + return findCurrentTexParagraph(startline, dummy, endline, dummy, view); } bool EditorExtension::findCurrentTexParagraph(int& startline, int& startcolumn, int& endline, int& endcolumn, KTextEditor::View* view) { - view = determineView(view); - if(!view) { - return false; - } - - int row; - - // get current position - KTextEditor::Document *doc = view->document(); - KTextEditor::Cursor cursor = view->cursorPosition(); - row = cursor.line(); - - // don't accept an empty line as part of a paragraph - if(doc->line(row).trimmed().isEmpty()) { - return false; - } - - // settings default results - startline = row; - endline = row; - - // find the previous empty line - for(int line = row - 1; line >= 0; --line) { - if(doc->line(line).trimmed().isEmpty()) { - break; - } - startline = line; - } - - // it is guaranteed that 'startline.trimmed()' won't be empty - startcolumn = 0; - QString line = doc->line(startline); - for(int i = 0; i < line.size(); ++i) { - if(!line[i].isSpace()) { - startcolumn = i; - break; - } - } - - // find the next empty line - for(int line = row + 1; line < doc->lines(); ++line) { - if(doc->line(line).trimmed().isEmpty()) { - break; - } - endline = line; - } - - // it is guaranteed that 'endline.trimmed()' won't be empty - line = doc->line(endline); - endcolumn = line.size(); - for(int i = line.size() - 1; i >= 0; --i) { - if(!line[i].isSpace()) { - endcolumn = i+1; - break; - } - } - - // settings result - return true; + view = determineView(view); + if(!view) { + return false; + } + + int row; + + // get current position + KTextEditor::Document *doc = view->document(); + KTextEditor::Cursor cursor = view->cursorPosition(); + row = cursor.line(); + + // don't accept an empty line as part of a paragraph + if(doc->line(row).trimmed().isEmpty()) { + return false; + } + + // settings default results + startline = row; + endline = row; + + // find the previous empty line + for(int line = row - 1; line >= 0; --line) { + if(doc->line(line).trimmed().isEmpty()) { + break; + } + startline = line; + } + + // it is guaranteed that 'startline.trimmed()' won't be empty + startcolumn = 0; + QString line = doc->line(startline); + for(int i = 0; i < line.size(); ++i) { + if(!line[i].isSpace()) { + startcolumn = i; + break; + } + } + + // find the next empty line + for(int line = row + 1; line < doc->lines(); ++line) { + if(doc->line(line).trimmed().isEmpty()) { + break; + } + endline = line; + } + + // it is guaranteed that 'endline.trimmed()' won't be empty + line = doc->line(endline); + endcolumn = line.size(); + for(int i = line.size() - 1; i >= 0; --i) { + if(!line[i].isSpace()) { + endcolumn = i+1; + break; + } + } + + // settings result + return true; } void EditorExtension::gotoNextParagraph(KTextEditor::View *view) { - view = determineView(view); - if(!view) { - return; - } - - bool found; - int startline, endline; - KTextEditor::Document *doc = view->document(); - - endline = view->cursorPosition().line(); - if(doc->line(endline).trimmed().isEmpty()) { - found = true; - } - else { - found = findCurrentTexParagraph(startline, endline, view); - } - - // we are in an empty line or in the last line of a paragraph - if (found) { - // find the next non empty line - for(int line = endline + 1; line < doc->lines(); ++line) { - if(!doc->line(line).trimmed().isEmpty()) { - view->setCursorPosition(KTextEditor::Cursor(line, 0)); - return; - } - } - } + view = determineView(view); + if(!view) { + return; + } + + bool found; + int startline, endline; + KTextEditor::Document *doc = view->document(); + + endline = view->cursorPosition().line(); + if(doc->line(endline).trimmed().isEmpty()) { + found = true; + } + else { + found = findCurrentTexParagraph(startline, endline, view); + } + + // we are in an empty line or in the last line of a paragraph + if (found) { + // find the next non empty line + for(int line = endline + 1; line < doc->lines(); ++line) { + if(!doc->line(line).trimmed().isEmpty()) { + view->setCursorPosition(KTextEditor::Cursor(line, 0)); + return; + } + } + } } void EditorExtension::gotoPrevParagraph(KTextEditor::View *view) { - view = determineView(view); - if(!view) { - return; - } - - bool found; - int startline,endline; - KTextEditor::Document *doc = view->document(); - - startline = view->cursorPosition().line(); - if(doc->line(startline).trimmed().isEmpty()) { - startline++; - found = true; - } - else { - found = findCurrentTexParagraph(startline,endline,view); - } - // we are in an empty line or in the first line of a paragraph - if(found) { - // find the last line of the previous paragraph - int foundline = -1; - for (int line = startline - 1; line >= 0; --line) { - if(!doc->line(line).trimmed().isEmpty()) { - break; - } - foundline = line; - } - if(foundline < 0) { - return; - } - - // and finally the first line of this paragraph - int prevstartline = -1; - for(int line = foundline - 1; line >= 0; --line) { - if(doc->line(line).trimmed().isEmpty()) { - break; - } - prevstartline = line; - } - - if(prevstartline >= 0) { - view->setCursorPosition(KTextEditor::Cursor(prevstartline, 0)); - } - } + view = determineView(view); + if(!view) { + return; + } + + bool found; + int startline,endline; + KTextEditor::Document *doc = view->document(); + + startline = view->cursorPosition().line(); + if(doc->line(startline).trimmed().isEmpty()) { + startline++; + found = true; + } + else { + found = findCurrentTexParagraph(startline,endline,view); + } + // we are in an empty line or in the first line of a paragraph + if(found) { + // find the last line of the previous paragraph + int foundline = -1; + for (int line = startline - 1; line >= 0; --line) { + if(!doc->line(line).trimmed().isEmpty()) { + break; + } + foundline = line; + } + if(foundline < 0) { + return; + } + + // and finally the first line of this paragraph + int prevstartline = -1; + for(int line = foundline - 1; line >= 0; --line) { + if(doc->line(line).trimmed().isEmpty()) { + break; + } + prevstartline = line; + } + + if(prevstartline >= 0) { + view->setCursorPosition(KTextEditor::Cursor(prevstartline, 0)); + } + } } int EditorExtension::prevNonEmptyLine(int line, KTextEditor::View *view) { - view = determineView(view); - if(!view) { - return -1; - } + view = determineView(view); + if(!view) { + return -1; + } - KTextEditor::Document *doc = view->document(); - for(int i = line - 1; i >= 0; --i) { - if(!doc->line(i).trimmed().isEmpty()) { - return i; - } - } - return -1; + KTextEditor::Document *doc = view->document(); + for(int i = line - 1; i >= 0; --i) { + if(!doc->line(i).trimmed().isEmpty()) { + return i; + } + } + return -1; } int EditorExtension::nextNonEmptyLine(int line, KTextEditor::View *view) { - view = determineView(view); - if(!view) { - return -1; - } + view = determineView(view); + if(!view) { + return -1; + } - KTextEditor::Document *doc = view->document(); - int lines = doc->lines(); - for(int i = line + 1; i < lines; ++i) { - if(!doc->line(i).trimmed().isEmpty()) { - return i; - } - } - return -1; + KTextEditor::Document *doc = view->document(); + int lines = doc->lines(); + for(int i = line + 1; i < lines; ++i) { + if(!doc->line(i).trimmed().isEmpty()) { + return i; + } + } + return -1; } //////////////////// one line of text//////////////////// void EditorExtension::selectLine(KTextEditor::View *view) { - view = determineView(view); - if(!view) { - return; - } + view = determineView(view); + if(!view) { + return; + } - // get current position - int row; - QString word; - KTextEditor::Document *doc = view->document(); - KTextEditor::Cursor cursor = view->cursorPosition(); - row = cursor.line(); + // get current position + int row; + QString word; + KTextEditor::Document *doc = view->document(); + KTextEditor::Cursor cursor = view->cursorPosition(); + row = cursor.line(); - if(doc->lineLength(row) > 0) { - view->setSelection(KTextEditor::Range(row, 0, row + 1, 0)); - } + if(doc->lineLength(row) > 0) { + view->setSelection(KTextEditor::Range(row, 0, row + 1, 0)); + } } void EditorExtension::selectLine(int line, KTextEditor::View *view) { - view = determineView(view); - if(!view) { - return; - } + view = determineView(view); + if(!view) { + return; + } - if(view->document()->lineLength(line) > 0) { - view->setSelection(KTextEditor::Range(line, 0, line + 1, 0)); - } + if(view->document()->lineLength(line) > 0) { + view->setSelection(KTextEditor::Range(line, 0, line + 1, 0)); + } } void EditorExtension::selectLines(int from, int to, KTextEditor::View *view) { - view = determineView(view); - if(view && from <= to) { - view->setSelection(KTextEditor::Range(from, 0, to + 1, 0)); - } + view = determineView(view); + if(view && from <= to) { + view->setSelection(KTextEditor::Range(from, 0, to + 1, 0)); + } } bool EditorExtension::replaceLine(int line, const QString &s, KTextEditor::View *view) { - view = determineView(view); - if(!view) { - return false; - } + view = determineView(view); + if(!view) { + return false; + } - KTextEditor::Document *doc = view->document(); - KTextEditor::Document::EditingTransaction transaction(doc); - doc->removeLine(line); - bool result = doc->insertLine(line, s); - return result; + KTextEditor::Document *doc = view->document(); + KTextEditor::Document::EditingTransaction transaction(doc); + doc->removeLine(line); + bool result = doc->insertLine(line, s); + return result; } void EditorExtension::deleteEndOfLine(KTextEditor::View *view) { - view = determineView(view); - if(!view) { - return; - } + view = determineView(view); + if(!view) { + return; + } - int row, col; - KTextEditor::Cursor cursor = view->cursorPosition(); - row = cursor.line(); - col = cursor.column(); + int row, col; + KTextEditor::Cursor cursor = view->cursorPosition(); + row = cursor.line(); + col = cursor.column(); - KTextEditor::Document *doc = view->document(); - view->removeSelection(); - doc->removeText(KTextEditor::Range(row, col, row, doc->lineLength(row))); + KTextEditor::Document *doc = view->document(); + view->removeSelection(); + doc->removeText(KTextEditor::Range(row, col, row, doc->lineLength(row))); } //////////////////// LaTeX command //////////////////// void EditorExtension::selectWord(EditorExtension::SelectMode mode, KTextEditor::View *view) { - view = determineView(view); - if(!view) { - return; - } + view = determineView(view); + if(!view) { + return; + } - KTextEditor::Range range = wordRange(view->cursorPosition(),mode,view); - if ( range.isValid() ) { - view->setSelection(range); - } + KTextEditor::Range range = wordRange(view->cursorPosition(),mode,view); + if ( range.isValid() ) { + view->setSelection(range); + } } void EditorExtension::deleteWord(EditorExtension::SelectMode mode, KTextEditor::View *view) { - view = determineView(view); - if(!view) { - return; - } + view = determineView(view); + if(!view) { + return; + } - KTextEditor::Range range = wordRange(view->cursorPosition(),mode,view); - if(range.isValid()) { - deleteRange(range,view); - } + KTextEditor::Range range = wordRange(view->cursorPosition(),mode,view); + if(range.isValid()) { + deleteRange(range,view); + } } void EditorExtension::nextBullet(KTextEditor::View* view) { - gotoBullet(false, view); + gotoBullet(false, view); } void EditorExtension::prevBullet(KTextEditor::View* view) { - gotoBullet(true, view); + gotoBullet(true, view); } void EditorExtension::insertBullet(KTextEditor::View* view) { - view = determineView(view); - if(!view) { - return; - } + view = determineView(view); + if(!view) { + return; + } - view->document()->insertText(view->cursorPosition(), s_bullet); + view->document()->insertText(view->cursorPosition(), s_bullet); } ///////////////////// Special Functions /////////////// /* void EditorExtension::insertNewLine(KTextEditor::View *view) { view = determineView(view); if(!view) { return; } int newLineNumber = view->cursorPosition().line() + 1; view->document()->insertLine(newLineNumber, QString()); } */ void EditorExtension::moveCursorToLastPositionInCurrentLine(KTextEditor::View *view) { - view = determineView(view); - if(!view) { - return; - } + view = determineView(view); + if(!view) { + return; + } - const KTextEditor::Cursor currentPosition = view->cursorPosition(); - view->setCursorPosition(KTextEditor::Cursor(currentPosition.line(), - view->document()->lineLength(currentPosition.line()))); + const KTextEditor::Cursor currentPosition = view->cursorPosition(); + view->setCursorPosition(KTextEditor::Cursor(currentPosition.line(), + view->document()->lineLength(currentPosition.line()))); } void EditorExtension::keyReturn(KTextEditor::View *view) { - view = determineView(view); - if(!view) { - return; - } + view = determineView(view); + if(!view) { + return; + } - int newLineNumber = view->cursorPosition().line() + 1; - view->document()->insertLine(newLineNumber, QString()); - view->setCursorPosition(KTextEditor::Cursor(newLineNumber, 0)); + int newLineNumber = view->cursorPosition().line() + 1; + view->document()->insertLine(newLineNumber, QString()); + view->setCursorPosition(KTextEditor::Cursor(newLineNumber, 0)); } void EditorExtension::commentLaTeX(KTextEditor::Document* document, const KTextEditor::Range& range) { - int startLine = range.start().line(), endLine = range.end().line(); - for(int i = startLine; i <= endLine; ++i) { - document->insertText(KTextEditor::Cursor(i, 0), "% "); - } + int startLine = range.start().line(), endLine = range.end().line(); + for(int i = startLine; i <= endLine; ++i) { + document->insertText(KTextEditor::Cursor(i, 0), "% "); + } } void EditorExtension::goToLine(int line, KTextEditor::View *view) { - view = determineView(view); - if(!view) { - return; - } + view = determineView(view); + if(!view) { + return; + } - KTextEditor::Cursor cursor(line, 0); - view->setCursorPosition(cursor); + KTextEditor::Cursor cursor(line, 0); + view->setCursorPosition(cursor); } //////////////////// double quotes //////////////////// void EditorExtension::initDoubleQuotes() { - m_dblQuotes = KileConfig::insertDoubleQuotes(); + m_dblQuotes = KileConfig::insertDoubleQuotes(); - int index = KileConfig::doubleQuotes(); - if(index < 0 || index >= m_quoteList.count()) { - index = 0; - } + int index = KileConfig::doubleQuotes(); + if(index < 0 || index >= m_quoteList.count()) { + index = 0; + } - m_leftDblQuote = m_quoteList[index].first; - m_rightDblQuote = m_quoteList[index].second; - KILE_DEBUG_MAIN << "new quotes: " << m_dblQuotes << " left=" << m_leftDblQuote << " right=" << m_rightDblQuote<< endl; + m_leftDblQuote = m_quoteList[index].first; + m_rightDblQuote = m_quoteList[index].second; + KILE_DEBUG_MAIN << "new quotes: " << m_dblQuotes << " left=" << m_leftDblQuote << " right=" << m_rightDblQuote<< endl; } bool EditorExtension::insertDoubleQuotes(KTextEditor::View *view) { - // don't insert double quotes, if konsole has focus - // return false, because if this is called from an event - // handler, because this event has to be passed on - if(m_ki->texKonsole()->hasFocus()) { - return false; - } - - // insert double quotes, normal mode or autocompletion mode - // always return true for event handler - view = determineView(view); - if(!view) { - return true; - } - - KTextEditor::Document *doc = view->document(); - - if(!doc) { - return false; - } - - view->removeSelectionText(); - - int row, col; - KTextEditor::Cursor cursor = view->cursorPosition(); - row = cursor.line(); - col = cursor.column(); - - // simply insert, if we are inside a verb command - if(insideVerb(view) || insideVerbatim(view)) { - return false; - } - - // simply insert, if autoinsert mode is not active or the char bevor is \ (typically for \"a useful) - if (!m_dblQuotes || (col > 0 && doc->text(KTextEditor::Range(row, col - 1, row, col)) == "\\")) { - return false; - } - - // insert with auto mode - QString pattern1 = QRegExp::escape(m_leftDblQuote); - if(m_leftDblQuote.at(m_leftDblQuote.length()-1).isLetter()) { - pattern1 += "(\\b|(\\{\\}))"; - } - QString pattern2 = QRegExp::escape(m_rightDblQuote); - if(m_rightDblQuote.at(m_rightDblQuote.length()-1).isLetter()) { - pattern2 += "(\\b|(\\{\\}))"; - } - - bool openFound = false; - KTextEditor::Range searchRange = KTextEditor::Range(KTextEditor::Cursor(0, 0), KTextEditor::Cursor(row, col)); - QVector foundRanges = doc->searchText(searchRange, '(' + pattern1 + ")|(" + pattern2 + ')', - KTextEditor::Regex | KTextEditor::Backwards); - // KTextEditor::Document#searchText always returns at least one range, even - // if no occurrences have been found. Thus, we have to check if the range is valid. - KTextEditor::Range range = foundRanges.first(); - if(range.isValid()) { - int lineFound = range.start().line(); - int columnFound = range.start().column(); - openFound = (doc->line(lineFound).indexOf(m_leftDblQuote, columnFound) == columnFound); - } - - QString textline = doc->line(row); - //KILE_DEBUG_MAIN << "text=" << textline << " open=" << openfound; - if(openFound) { - // If we last inserted a language specific doublequote open, - // we have to change it to a normal doublequote. If not we - // insert a language specific doublequote close - int startcol = col - m_leftDblQuote.length(); - //KILE_DEBUG_MAIN << "startcol=" << startcol << " col=" << col ; - if (startcol>=0 && textline.indexOf(m_leftDblQuote, startcol) == startcol) { - doc->removeText(KTextEditor::Range(row, startcol, row, startcol + m_leftDblQuote.length())); - doc->insertText(KTextEditor::Cursor(row, startcol), "\""); - } - else { - doc->insertText(KTextEditor::Cursor(row, col), m_rightDblQuote); - } - } - else { - // If we last inserted a language specific doublequote close, - // we have to change it to a normal doublequote. If not we - // insert a language specific doublequote open - int startcol = col - m_rightDblQuote.length(); - //KILE_DEBUG_MAIN << "startcol=" << startcol << " col=" << col ; - if (startcol >= 0 && textline.indexOf(m_rightDblQuote, startcol) == startcol) { - doc->removeText(KTextEditor::Range(row, startcol, row, startcol + m_rightDblQuote.length())); - doc->insertText(KTextEditor::Cursor(row,startcol), "\""); - } - else { - doc->insertText(KTextEditor::Cursor(row, col), m_leftDblQuote); - } - } - return true; + // don't insert double quotes, if konsole has focus + // return false, because if this is called from an event + // handler, because this event has to be passed on + if(m_ki->texKonsole()->hasFocus()) { + return false; + } + + // insert double quotes, normal mode or autocompletion mode + // always return true for event handler + view = determineView(view); + if(!view) { + return true; + } + + KTextEditor::Document *doc = view->document(); + + if(!doc) { + return false; + } + + view->removeSelectionText(); + + int row, col; + KTextEditor::Cursor cursor = view->cursorPosition(); + row = cursor.line(); + col = cursor.column(); + + // simply insert, if we are inside a verb command + if(insideVerb(view) || insideVerbatim(view)) { + return false; + } + + // simply insert, if autoinsert mode is not active or the char bevor is \ (typically for \"a useful) + if (!m_dblQuotes || (col > 0 && doc->text(KTextEditor::Range(row, col - 1, row, col)) == "\\")) { + return false; + } + + // insert with auto mode + QString pattern1 = QRegExp::escape(m_leftDblQuote); + if(m_leftDblQuote.at(m_leftDblQuote.length()-1).isLetter()) { + pattern1 += "(\\b|(\\{\\}))"; + } + QString pattern2 = QRegExp::escape(m_rightDblQuote); + if(m_rightDblQuote.at(m_rightDblQuote.length()-1).isLetter()) { + pattern2 += "(\\b|(\\{\\}))"; + } + + bool openFound = false; + KTextEditor::Range searchRange = KTextEditor::Range(KTextEditor::Cursor(0, 0), KTextEditor::Cursor(row, col)); + QVector foundRanges = doc->searchText(searchRange, '(' + pattern1 + ")|(" + pattern2 + ')', + KTextEditor::Regex | KTextEditor::Backwards); + // KTextEditor::Document#searchText always returns at least one range, even + // if no occurrences have been found. Thus, we have to check if the range is valid. + KTextEditor::Range range = foundRanges.first(); + if(range.isValid()) { + int lineFound = range.start().line(); + int columnFound = range.start().column(); + openFound = (doc->line(lineFound).indexOf(m_leftDblQuote, columnFound) == columnFound); + } + + QString textline = doc->line(row); + //KILE_DEBUG_MAIN << "text=" << textline << " open=" << openfound; + if(openFound) { + // If we last inserted a language specific doublequote open, + // we have to change it to a normal doublequote. If not we + // insert a language specific doublequote close + int startcol = col - m_leftDblQuote.length(); + //KILE_DEBUG_MAIN << "startcol=" << startcol << " col=" << col ; + if (startcol>=0 && textline.indexOf(m_leftDblQuote, startcol) == startcol) { + doc->removeText(KTextEditor::Range(row, startcol, row, startcol + m_leftDblQuote.length())); + doc->insertText(KTextEditor::Cursor(row, startcol), "\""); + } + else { + doc->insertText(KTextEditor::Cursor(row, col), m_rightDblQuote); + } + } + else { + // If we last inserted a language specific doublequote close, + // we have to change it to a normal doublequote. If not we + // insert a language specific doublequote open + int startcol = col - m_rightDblQuote.length(); + //KILE_DEBUG_MAIN << "startcol=" << startcol << " col=" << col ; + if (startcol >= 0 && textline.indexOf(m_rightDblQuote, startcol) == startcol) { + doc->removeText(KTextEditor::Range(row, startcol, row, startcol + m_rightDblQuote.length())); + doc->insertText(KTextEditor::Cursor(row,startcol), "\""); + } + else { + doc->insertText(KTextEditor::Cursor(row, col), m_leftDblQuote); + } + } + return true; } // Takes an unicode unsigned short and calls insertSpecialCharacter to // insert the proper LaTeX sequence and warn user of any dependencies. //FIXME: there should be one central place to convert unicode chars to LaTeX; // also see 'LaTeXEventFilter::eventFilter'. bool EditorExtension::insertLatexFromUnicode(unsigned short rep, KTextEditor::View *view) { - switch(rep) - { // Find the unicode decimal representation - case 160: return insertSpecialCharacter("~", view); - case 161: return insertSpecialCharacter("!`", view); - case 162: return insertSpecialCharacter("\\textcent", view, "textcomp"); - case 163: return insertSpecialCharacter("\\pounds", view); - case 164: return insertSpecialCharacter("\\textcurrency", view, "textcomp"); - case 165: return insertSpecialCharacter("\\textyen", view, "textcomp"); - case 166: return insertSpecialCharacter("\\textbrokenbar", view, "textcomp"); - case 167: return insertSpecialCharacter("\\S", view); - case 168: return insertSpecialCharacter("\"", view); - case 169: return insertSpecialCharacter("\\copyright", view); - case 170: return insertSpecialCharacter("\\textordfeminine", view, "textcomp"); - case 171: return insertSpecialCharacter("\\guillemotleft", view); - case 172: return insertSpecialCharacter("\\neg", view); // TODO: Check for math - case 173: return insertSpecialCharacter("-", view); // TODO: Check for math - case 174: return insertSpecialCharacter("\\textregistered", view, "textcomp"); - case 176: return insertSpecialCharacter("^\\circ", view); // TODO: Check for math - case 177: return insertSpecialCharacter("\\pm", view); // TODO: Check for math - case 178: return insertSpecialCharacter("^2", view); // TODO: Check for math - case 179: return insertSpecialCharacter("^3", view); // TODO: Check for math - case 180: return insertSpecialCharacter("'", view); - case 181: return insertSpecialCharacter("\\mu", view); // TODO: Check for math - case 182: return insertSpecialCharacter("\\P", view); - case 185: return insertSpecialCharacter("^1", view); // TODO: Check for math - case 186: return insertSpecialCharacter("\\textordmasculine", view, "textcomp"); - case 187: return insertSpecialCharacter("\\guillemotright", view); - case 191: return insertSpecialCharacter("?`", view); - case 192: return insertSpecialCharacter("\\`A", view); - case 193: return insertSpecialCharacter("\\'A", view); - case 194: return insertSpecialCharacter("\\^A", view); - case 195: return insertSpecialCharacter("\\~A", view); - case 196: return insertSpecialCharacter("\\\"A", view); - case 197: return insertSpecialCharacter("\\AA", view); - case 198: return insertSpecialCharacter("\\AE", view); - case 199: return insertSpecialCharacter("\\c{C}", view); - case 200: return insertSpecialCharacter("\\`E", view); - case 201: return insertSpecialCharacter("\\'E", view); - case 202: return insertSpecialCharacter("\\^E", view); - case 203: return insertSpecialCharacter("\\\"E", view); - case 204: return insertSpecialCharacter("\\`I", view); - case 205: return insertSpecialCharacter("\\'I", view); - case 206: return insertSpecialCharacter("\\^I", view); - case 207: return insertSpecialCharacter("\\\"I", view); - case 209: return insertSpecialCharacter("\\~N", view); - case 210: return insertSpecialCharacter("\\`O", view); - case 211: return insertSpecialCharacter("\\'O", view); - case 212: return insertSpecialCharacter("\\^O", view); - case 213: return insertSpecialCharacter("\\~O", view); - case 214: return insertSpecialCharacter("\\\"O", view); - case 215: return insertSpecialCharacter("\\times", view); //TODO: Check for math - case 216: return insertSpecialCharacter("\\Oslash", view); - case 217: return insertSpecialCharacter("\\`U", view); - case 218: return insertSpecialCharacter("\\'U", view); - case 219: return insertSpecialCharacter("\\^U", view); - case 220: return insertSpecialCharacter("\\\"U", view); - case 221: return insertSpecialCharacter("\\'Y", view); - case 223: return insertSpecialCharacter("\\ss{}", view); - case 224: return insertSpecialCharacter("\\`a", view); - case 225: return insertSpecialCharacter("\\'a", view); - case 226: return insertSpecialCharacter("\\^a", view); - case 227: return insertSpecialCharacter("\\~a", view); - case 228: return insertSpecialCharacter("\\\"a", view); - case 229: return insertSpecialCharacter("\\aa", view); - case 230: return insertSpecialCharacter("\\ae", view); - case 231: return insertSpecialCharacter("\\c{c}", view); - case 232: return insertSpecialCharacter("\\`e", view); - case 233: return insertSpecialCharacter("\\'e", view); - case 234: return insertSpecialCharacter("\\^e", view); - case 235: return insertSpecialCharacter("\\\"e", view); - case 236: return insertSpecialCharacter("\\`i", view); - case 237: return insertSpecialCharacter("\\'i", view); - case 238: return insertSpecialCharacter("\\^i", view); - case 239: return insertSpecialCharacter("\\\"i", view); - case 240: return insertSpecialCharacter("\\~o", view); - case 241: return insertSpecialCharacter("\\~n", view); - case 242: return insertSpecialCharacter("\\`o", view); - case 243: return insertSpecialCharacter("\\'o", view); - case 244: return insertSpecialCharacter("\\^o", view); - case 245: return insertSpecialCharacter("\\~o", view); - case 246: return insertSpecialCharacter("\\\"o", view); - case 247: return insertSpecialCharacter("\\div", view); - case 248: return insertSpecialCharacter("\\oslash", view); - case 249: return insertSpecialCharacter("\\`u", view); - case 250: return insertSpecialCharacter("\\'u", view); - case 251: return insertSpecialCharacter("\\^u", view); - case 252: return insertSpecialCharacter("\\\"u", view); - case 253: return insertSpecialCharacter("\\'y", view); - case 255: return insertSpecialCharacter("\\\"y", view); - case 256: return insertSpecialCharacter("\\=A", view); - case 257: return insertSpecialCharacter("\\=a", view); - case 258: return insertSpecialCharacter("\\uA", view); - case 259: return insertSpecialCharacter("\\ua", view); - case 262: return insertSpecialCharacter("\\'C", view); - case 263: return insertSpecialCharacter("\\'c", view); - case 264: return insertSpecialCharacter("\\^C", view); - case 265: return insertSpecialCharacter("\\^c", view); - case 266: return insertSpecialCharacter("\\.C", view); - case 267: return insertSpecialCharacter("\\.c", view); - case 268: return insertSpecialCharacter("\\vC", view); - case 269: return insertSpecialCharacter("\\vc", view); - case 270: return insertSpecialCharacter("\\vD", view); - case 271: return insertSpecialCharacter("\\vd", view); - case 272: return insertSpecialCharacter("\\=D", view); - case 273: return insertSpecialCharacter("\\=d", view); - case 274: return insertSpecialCharacter("\\=E", view); - case 275: return insertSpecialCharacter("\\=e", view); - case 276: return insertSpecialCharacter("\\uE", view); - case 277: return insertSpecialCharacter("\\ue", view); - case 278: return insertSpecialCharacter("\\.E", view); - case 279: return insertSpecialCharacter("\\.e", view); - case 282: return insertSpecialCharacter("\\vE", view); - case 283: return insertSpecialCharacter("\\ve", view); - case 284: return insertSpecialCharacter("\\^G", view); - case 285: return insertSpecialCharacter("\\^g", view); - case 286: return insertSpecialCharacter("\\uG", view); - case 287: return insertSpecialCharacter("\\ug", view); - case 288: return insertSpecialCharacter("\\.G", view); - case 289: return insertSpecialCharacter("\\.g", view); - case 290: return insertSpecialCharacter("\\cG", view); - case 291: return insertSpecialCharacter("\\'g", view); - case 292: return insertSpecialCharacter("\\^H", view); - case 293: return insertSpecialCharacter("\\^h", view); - case 294: return insertSpecialCharacter("\\=H", view); - case 295: return insertSpecialCharacter("\\=h", view); - case 296: return insertSpecialCharacter("\\~I", view); - case 297: return insertSpecialCharacter("\\~i", view); - case 298: return insertSpecialCharacter("\\=I", view); - case 299: return insertSpecialCharacter("\\=i", view); - case 300: return insertSpecialCharacter("\\uI", view); - case 301: return insertSpecialCharacter("\\ui", view); - case 304: return insertSpecialCharacter("\\.I", view); - case 305: return insertSpecialCharacter("\\i", view); - case 308: return insertSpecialCharacter("\\^J", view); - case 309: return insertSpecialCharacter("\\^j", view); - case 310: return insertSpecialCharacter("\\cK", view); - case 311: return insertSpecialCharacter("\\ck", view); - case 313: return insertSpecialCharacter("\\'L", view); - case 314: return insertSpecialCharacter("\\'l", view); - case 315: return insertSpecialCharacter("\\cL", view); - case 316: return insertSpecialCharacter("\\cl", view); - case 317: return insertSpecialCharacter("\\vL", view); - case 318: return insertSpecialCharacter("\\vl", view); - case 323: return insertSpecialCharacter("\\'N", view); - case 324: return insertSpecialCharacter("\\'n", view); - case 325: return insertSpecialCharacter("\\cN", view); - case 326: return insertSpecialCharacter("\\cn", view); - case 327: return insertSpecialCharacter("\\vN", view); - case 328: return insertSpecialCharacter("\\vn", view); - case 332: return insertSpecialCharacter("\\=O", view); - case 333: return insertSpecialCharacter("\\=o", view); - case 334: return insertSpecialCharacter("\\uO", view); - case 335: return insertSpecialCharacter("\\uo", view); - case 336: return insertSpecialCharacter("\\HO", view); - case 337: return insertSpecialCharacter("\\Ho", view); - case 338: return insertSpecialCharacter("\\OE", view); - case 339: return insertSpecialCharacter("\\oe", view); - case 340: return insertSpecialCharacter("\\'R", view); - case 341: return insertSpecialCharacter("\\'r", view); - case 342: return insertSpecialCharacter("\\cR", view); - case 343: return insertSpecialCharacter("\\cr", view); - case 344: return insertSpecialCharacter("\\vR", view); - case 345: return insertSpecialCharacter("\\vr", view); - case 346: return insertSpecialCharacter("\\'S", view); - case 347: return insertSpecialCharacter("\\'s", view); - case 348: return insertSpecialCharacter("\\^S", view); - case 349: return insertSpecialCharacter("\\^s", view); - case 350: return insertSpecialCharacter("\\cS", view); - case 351: return insertSpecialCharacter("\\cs", view); - case 352: return insertSpecialCharacter("\\vS", view); - case 353: return insertSpecialCharacter("\\vs", view); - case 354: return insertSpecialCharacter("\\cT", view); - case 355: return insertSpecialCharacter("\\ct", view); - case 356: return insertSpecialCharacter("\\vT", view); - case 357: return insertSpecialCharacter("\\vt", view); - case 358: return insertSpecialCharacter("\\=T", view); - case 359: return insertSpecialCharacter("\\=t", view); - case 360: return insertSpecialCharacter("\\~U", view); - case 361: return insertSpecialCharacter("\\~u", view); - case 362: return insertSpecialCharacter("\\=U", view); - case 363: return insertSpecialCharacter("\\=u", view); - case 364: return insertSpecialCharacter("\\uU", view); - case 365: return insertSpecialCharacter("\\uu", view); - case 366: return insertSpecialCharacter("\\AU", view); - case 367: return insertSpecialCharacter("\\Au", view); - case 368: return insertSpecialCharacter("\\HU", view); - case 369: return insertSpecialCharacter("\\Hu", view); - case 370: return insertSpecialCharacter("\\cU", view); - case 371: return insertSpecialCharacter("\\cu", view); - case 372: return insertSpecialCharacter("\\^W", view); - case 373: return insertSpecialCharacter("\\^w", view); - case 374: return insertSpecialCharacter("\\^Y", view); - case 375: return insertSpecialCharacter("\\^y", view); - case 376: return insertSpecialCharacter("\\\"Y", view); - case 377: return insertSpecialCharacter("\\'Z", view); - case 378: return insertSpecialCharacter("\\'z", view); - case 379: return insertSpecialCharacter("\\.Z", view); - case 380: return insertSpecialCharacter("\\.z", view); - case 381: return insertSpecialCharacter("\\vZ", view); - case 382: return insertSpecialCharacter("\\vz", view); - default: return false; - } + switch(rep) + { // Find the unicode decimal representation + case 160: + return insertSpecialCharacter("~", view); + case 161: + return insertSpecialCharacter("!`", view); + case 162: + return insertSpecialCharacter("\\textcent", view, "textcomp"); + case 163: + return insertSpecialCharacter("\\pounds", view); + case 164: + return insertSpecialCharacter("\\textcurrency", view, "textcomp"); + case 165: + return insertSpecialCharacter("\\textyen", view, "textcomp"); + case 166: + return insertSpecialCharacter("\\textbrokenbar", view, "textcomp"); + case 167: + return insertSpecialCharacter("\\S", view); + case 168: + return insertSpecialCharacter("\"", view); + case 169: + return insertSpecialCharacter("\\copyright", view); + case 170: + return insertSpecialCharacter("\\textordfeminine", view, "textcomp"); + case 171: + return insertSpecialCharacter("\\guillemotleft", view); + case 172: + return insertSpecialCharacter("\\neg", view); // TODO: Check for math + case 173: + return insertSpecialCharacter("-", view); // TODO: Check for math + case 174: + return insertSpecialCharacter("\\textregistered", view, "textcomp"); + case 176: + return insertSpecialCharacter("^\\circ", view); // TODO: Check for math + case 177: + return insertSpecialCharacter("\\pm", view); // TODO: Check for math + case 178: + return insertSpecialCharacter("^2", view); // TODO: Check for math + case 179: + return insertSpecialCharacter("^3", view); // TODO: Check for math + case 180: + return insertSpecialCharacter("'", view); + case 181: + return insertSpecialCharacter("\\mu", view); // TODO: Check for math + case 182: + return insertSpecialCharacter("\\P", view); + case 185: + return insertSpecialCharacter("^1", view); // TODO: Check for math + case 186: + return insertSpecialCharacter("\\textordmasculine", view, "textcomp"); + case 187: + return insertSpecialCharacter("\\guillemotright", view); + case 191: + return insertSpecialCharacter("?`", view); + case 192: + return insertSpecialCharacter("\\`A", view); + case 193: + return insertSpecialCharacter("\\'A", view); + case 194: + return insertSpecialCharacter("\\^A", view); + case 195: + return insertSpecialCharacter("\\~A", view); + case 196: + return insertSpecialCharacter("\\\"A", view); + case 197: + return insertSpecialCharacter("\\AA", view); + case 198: + return insertSpecialCharacter("\\AE", view); + case 199: + return insertSpecialCharacter("\\c{C}", view); + case 200: + return insertSpecialCharacter("\\`E", view); + case 201: + return insertSpecialCharacter("\\'E", view); + case 202: + return insertSpecialCharacter("\\^E", view); + case 203: + return insertSpecialCharacter("\\\"E", view); + case 204: + return insertSpecialCharacter("\\`I", view); + case 205: + return insertSpecialCharacter("\\'I", view); + case 206: + return insertSpecialCharacter("\\^I", view); + case 207: + return insertSpecialCharacter("\\\"I", view); + case 209: + return insertSpecialCharacter("\\~N", view); + case 210: + return insertSpecialCharacter("\\`O", view); + case 211: + return insertSpecialCharacter("\\'O", view); + case 212: + return insertSpecialCharacter("\\^O", view); + case 213: + return insertSpecialCharacter("\\~O", view); + case 214: + return insertSpecialCharacter("\\\"O", view); + case 215: + return insertSpecialCharacter("\\times", view); //TODO: Check for math + case 216: + return insertSpecialCharacter("\\Oslash", view); + case 217: + return insertSpecialCharacter("\\`U", view); + case 218: + return insertSpecialCharacter("\\'U", view); + case 219: + return insertSpecialCharacter("\\^U", view); + case 220: + return insertSpecialCharacter("\\\"U", view); + case 221: + return insertSpecialCharacter("\\'Y", view); + case 223: + return insertSpecialCharacter("\\ss{}", view); + case 224: + return insertSpecialCharacter("\\`a", view); + case 225: + return insertSpecialCharacter("\\'a", view); + case 226: + return insertSpecialCharacter("\\^a", view); + case 227: + return insertSpecialCharacter("\\~a", view); + case 228: + return insertSpecialCharacter("\\\"a", view); + case 229: + return insertSpecialCharacter("\\aa", view); + case 230: + return insertSpecialCharacter("\\ae", view); + case 231: + return insertSpecialCharacter("\\c{c}", view); + case 232: + return insertSpecialCharacter("\\`e", view); + case 233: + return insertSpecialCharacter("\\'e", view); + case 234: + return insertSpecialCharacter("\\^e", view); + case 235: + return insertSpecialCharacter("\\\"e", view); + case 236: + return insertSpecialCharacter("\\`i", view); + case 237: + return insertSpecialCharacter("\\'i", view); + case 238: + return insertSpecialCharacter("\\^i", view); + case 239: + return insertSpecialCharacter("\\\"i", view); + case 240: + return insertSpecialCharacter("\\~o", view); + case 241: + return insertSpecialCharacter("\\~n", view); + case 242: + return insertSpecialCharacter("\\`o", view); + case 243: + return insertSpecialCharacter("\\'o", view); + case 244: + return insertSpecialCharacter("\\^o", view); + case 245: + return insertSpecialCharacter("\\~o", view); + case 246: + return insertSpecialCharacter("\\\"o", view); + case 247: + return insertSpecialCharacter("\\div", view); + case 248: + return insertSpecialCharacter("\\oslash", view); + case 249: + return insertSpecialCharacter("\\`u", view); + case 250: + return insertSpecialCharacter("\\'u", view); + case 251: + return insertSpecialCharacter("\\^u", view); + case 252: + return insertSpecialCharacter("\\\"u", view); + case 253: + return insertSpecialCharacter("\\'y", view); + case 255: + return insertSpecialCharacter("\\\"y", view); + case 256: + return insertSpecialCharacter("\\=A", view); + case 257: + return insertSpecialCharacter("\\=a", view); + case 258: + return insertSpecialCharacter("\\uA", view); + case 259: + return insertSpecialCharacter("\\ua", view); + case 262: + return insertSpecialCharacter("\\'C", view); + case 263: + return insertSpecialCharacter("\\'c", view); + case 264: + return insertSpecialCharacter("\\^C", view); + case 265: + return insertSpecialCharacter("\\^c", view); + case 266: + return insertSpecialCharacter("\\.C", view); + case 267: + return insertSpecialCharacter("\\.c", view); + case 268: + return insertSpecialCharacter("\\vC", view); + case 269: + return insertSpecialCharacter("\\vc", view); + case 270: + return insertSpecialCharacter("\\vD", view); + case 271: + return insertSpecialCharacter("\\vd", view); + case 272: + return insertSpecialCharacter("\\=D", view); + case 273: + return insertSpecialCharacter("\\=d", view); + case 274: + return insertSpecialCharacter("\\=E", view); + case 275: + return insertSpecialCharacter("\\=e", view); + case 276: + return insertSpecialCharacter("\\uE", view); + case 277: + return insertSpecialCharacter("\\ue", view); + case 278: + return insertSpecialCharacter("\\.E", view); + case 279: + return insertSpecialCharacter("\\.e", view); + case 282: + return insertSpecialCharacter("\\vE", view); + case 283: + return insertSpecialCharacter("\\ve", view); + case 284: + return insertSpecialCharacter("\\^G", view); + case 285: + return insertSpecialCharacter("\\^g", view); + case 286: + return insertSpecialCharacter("\\uG", view); + case 287: + return insertSpecialCharacter("\\ug", view); + case 288: + return insertSpecialCharacter("\\.G", view); + case 289: + return insertSpecialCharacter("\\.g", view); + case 290: + return insertSpecialCharacter("\\cG", view); + case 291: + return insertSpecialCharacter("\\'g", view); + case 292: + return insertSpecialCharacter("\\^H", view); + case 293: + return insertSpecialCharacter("\\^h", view); + case 294: + return insertSpecialCharacter("\\=H", view); + case 295: + return insertSpecialCharacter("\\=h", view); + case 296: + return insertSpecialCharacter("\\~I", view); + case 297: + return insertSpecialCharacter("\\~i", view); + case 298: + return insertSpecialCharacter("\\=I", view); + case 299: + return insertSpecialCharacter("\\=i", view); + case 300: + return insertSpecialCharacter("\\uI", view); + case 301: + return insertSpecialCharacter("\\ui", view); + case 304: + return insertSpecialCharacter("\\.I", view); + case 305: + return insertSpecialCharacter("\\i", view); + case 308: + return insertSpecialCharacter("\\^J", view); + case 309: + return insertSpecialCharacter("\\^j", view); + case 310: + return insertSpecialCharacter("\\cK", view); + case 311: + return insertSpecialCharacter("\\ck", view); + case 313: + return insertSpecialCharacter("\\'L", view); + case 314: + return insertSpecialCharacter("\\'l", view); + case 315: + return insertSpecialCharacter("\\cL", view); + case 316: + return insertSpecialCharacter("\\cl", view); + case 317: + return insertSpecialCharacter("\\vL", view); + case 318: + return insertSpecialCharacter("\\vl", view); + case 323: + return insertSpecialCharacter("\\'N", view); + case 324: + return insertSpecialCharacter("\\'n", view); + case 325: + return insertSpecialCharacter("\\cN", view); + case 326: + return insertSpecialCharacter("\\cn", view); + case 327: + return insertSpecialCharacter("\\vN", view); + case 328: + return insertSpecialCharacter("\\vn", view); + case 332: + return insertSpecialCharacter("\\=O", view); + case 333: + return insertSpecialCharacter("\\=o", view); + case 334: + return insertSpecialCharacter("\\uO", view); + case 335: + return insertSpecialCharacter("\\uo", view); + case 336: + return insertSpecialCharacter("\\HO", view); + case 337: + return insertSpecialCharacter("\\Ho", view); + case 338: + return insertSpecialCharacter("\\OE", view); + case 339: + return insertSpecialCharacter("\\oe", view); + case 340: + return insertSpecialCharacter("\\'R", view); + case 341: + return insertSpecialCharacter("\\'r", view); + case 342: + return insertSpecialCharacter("\\cR", view); + case 343: + return insertSpecialCharacter("\\cr", view); + case 344: + return insertSpecialCharacter("\\vR", view); + case 345: + return insertSpecialCharacter("\\vr", view); + case 346: + return insertSpecialCharacter("\\'S", view); + case 347: + return insertSpecialCharacter("\\'s", view); + case 348: + return insertSpecialCharacter("\\^S", view); + case 349: + return insertSpecialCharacter("\\^s", view); + case 350: + return insertSpecialCharacter("\\cS", view); + case 351: + return insertSpecialCharacter("\\cs", view); + case 352: + return insertSpecialCharacter("\\vS", view); + case 353: + return insertSpecialCharacter("\\vs", view); + case 354: + return insertSpecialCharacter("\\cT", view); + case 355: + return insertSpecialCharacter("\\ct", view); + case 356: + return insertSpecialCharacter("\\vT", view); + case 357: + return insertSpecialCharacter("\\vt", view); + case 358: + return insertSpecialCharacter("\\=T", view); + case 359: + return insertSpecialCharacter("\\=t", view); + case 360: + return insertSpecialCharacter("\\~U", view); + case 361: + return insertSpecialCharacter("\\~u", view); + case 362: + return insertSpecialCharacter("\\=U", view); + case 363: + return insertSpecialCharacter("\\=u", view); + case 364: + return insertSpecialCharacter("\\uU", view); + case 365: + return insertSpecialCharacter("\\uu", view); + case 366: + return insertSpecialCharacter("\\AU", view); + case 367: + return insertSpecialCharacter("\\Au", view); + case 368: + return insertSpecialCharacter("\\HU", view); + case 369: + return insertSpecialCharacter("\\Hu", view); + case 370: + return insertSpecialCharacter("\\cU", view); + case 371: + return insertSpecialCharacter("\\cu", view); + case 372: + return insertSpecialCharacter("\\^W", view); + case 373: + return insertSpecialCharacter("\\^w", view); + case 374: + return insertSpecialCharacter("\\^Y", view); + case 375: + return insertSpecialCharacter("\\^y", view); + case 376: + return insertSpecialCharacter("\\\"Y", view); + case 377: + return insertSpecialCharacter("\\'Z", view); + case 378: + return insertSpecialCharacter("\\'z", view); + case 379: + return insertSpecialCharacter("\\.Z", view); + case 380: + return insertSpecialCharacter("\\.z", view); + case 381: + return insertSpecialCharacter("\\vZ", view); + case 382: + return insertSpecialCharacter("\\vz", view); + default: + return false; + } } // If allowed, inserts texString at current cursor postition. Startlingly similar to insertDoubleQuotes. bool EditorExtension::insertSpecialCharacter(const QString& texString, KTextEditor::View *view, const QString& dep) { - // stop if special character replacement is disabled - if (!m_specialCharacters) { - return false; - } + // stop if special character replacement is disabled + if (!m_specialCharacters) { + return false; + } - // return false if konsole has focus - if(m_ki->texKonsole()->hasFocus()) { - return false; - } + // return false if konsole has focus + if(m_ki->texKonsole()->hasFocus()) { + return false; + } - // always return true for event handler - view = determineView(view); - if(!view) { - return true; - } + // always return true for event handler + view = determineView(view); + if(!view) { + return true; + } - KTextEditor::Document *doc = view->document(); + KTextEditor::Document *doc = view->document(); - // Only change if we have a tex document - if(!doc || !m_ki->extensions()->isTexFile(doc->url())) { - return false; - } + // Only change if we have a tex document + if(!doc || !m_ki->extensions()->isTexFile(doc->url())) { + return false; + } - // In case of replace - view->removeSelectionText(); + // In case of replace + view->removeSelectionText(); - int row, col; - KTextEditor::Cursor cursor = view->cursorPosition(); - row = cursor.line(); - col = cursor.column(); + int row, col; + KTextEditor::Cursor cursor = view->cursorPosition(); + row = cursor.line(); + col = cursor.column(); - // insert texString - doc->insertText(KTextEditor::Cursor(row, col), texString); + // insert texString + doc->insertText(KTextEditor::Cursor(row, col), texString); - KILE_DEBUG_MAIN << "Replacing with "<allPackages(); - if(!packagelist.contains(dep)) { - m_ki->errorHandler()->printMessage(KileTool::Error, i18n("You have to include the package %1 to use %2.", dep, texString), i18n("Missing Package")); - KILE_DEBUG_MAIN << "Need package "<< dep; - } - } + // Check dependency + if (!dep.isEmpty()) { + QStringList packagelist = m_ki->allPackages(); + if(!packagelist.contains(dep)) { + m_ki->errorHandler()->printMessage(KileTool::Error, i18n("You have to include the package %1 to use %2.", dep, texString), i18n("Missing Package")); + KILE_DEBUG_MAIN << "Need package "<< dep; + } + } - return true; + return true; } //////////////////// insert tabulator //////////////////// void EditorExtension::insertIntelligentTabulator(KTextEditor::View *view) { - view = determineView(view); - if(!view) { - return; - } - - int row, col, currentRow, currentCol; - QString envname,tab; - QString prefix = " "; - - KTextEditor::Cursor cursor = view->cursorPosition(); - currentRow = cursor.line(); - currentCol = cursor.column(); - if(findOpenedEnvironment(row, col, envname, view)) { - // look if this is an environment with tabs - tab = m_latexCommands->getTabulator(envname); - - // try to align tabulator with textline above - if(currentRow >= 1) { - int tabpos = view->document()->line(currentRow - 1).indexOf('&', currentCol); - if(tabpos >= 0) { - currentCol = tabpos; - prefix.clear(); - } - } - } - - if(tab.isEmpty()) { - tab = '&'; - } - tab = prefix + tab + ' '; - - view->document()->insertText(KTextEditor::Cursor(currentRow, currentCol), tab); - view->setCursorPosition(KTextEditor::Cursor(currentRow, currentCol + tab.length())); + view = determineView(view); + if(!view) { + return; + } + + int row, col, currentRow, currentCol; + QString envname,tab; + QString prefix = " "; + + KTextEditor::Cursor cursor = view->cursorPosition(); + currentRow = cursor.line(); + currentCol = cursor.column(); + if(findOpenedEnvironment(row, col, envname, view)) { + // look if this is an environment with tabs + tab = m_latexCommands->getTabulator(envname); + + // try to align tabulator with textline above + if(currentRow >= 1) { + int tabpos = view->document()->line(currentRow - 1).indexOf('&', currentCol); + if(tabpos >= 0) { + currentCol = tabpos; + prefix.clear(); + } + } + } + + if(tab.isEmpty()) { + tab = '&'; + } + tab = prefix + tab + ' '; + + view->document()->insertText(KTextEditor::Cursor(currentRow, currentCol), tab); + view->setCursorPosition(KTextEditor::Cursor(currentRow, currentCol + tab.length())); } //////////////////// autocomplete environment //////////////////// // should we complete the current environment (call from LaTeXEventFilter) bool EditorExtension::eventInsertEnvironment(KTextEditor::View *view) { - if(!view) { - return false; - } - - // don't complete environment, if we are - // still working inside the completion box - KTextEditor::CodeCompletionInterface *codeCompletionInterface - = qobject_cast(view); - if(codeCompletionInterface && codeCompletionInterface->isCompletionActive()) { - return false; - } - - int row = view->cursorPosition().line(); - int col = view->cursorPositionVirtual().column(); - QString line = view->document()->line(row).left(col); - - int pos = m_regexpEnter.indexIn(line); - if (pos != -1) { - line = m_regexpEnter.cap(1); - for(int i = 0; i < line.length(); ++i) { - if(!line[i].isSpace()) { - line[i] = ' '; - } - } - - QString envname, endenv; - if(m_regexpEnter.cap(2) == "\\[") { - envname = m_regexpEnter.cap(2); - endenv = "\\]\n"; - } - else { - envname = m_regexpEnter.cap(4); - endenv = m_regexpEnter.cap(2).replace("\\begin","\\end") + '\n'; - } - - if(shouldCompleteEnv(envname, view)) { - QString item = m_latexCommands->isListEnv(envname) ? "\\item " : QString(); - view->document()->insertText(KTextEditor::Cursor(row, col), '\n' + line + m_envAutoIndent + item + '\n' + line + endenv); - view->setCursorPosition(KTextEditor::Cursor(row + 1, line.length() + m_envAutoIndent.length() + item.length())); - return true; - } - } - return false; + if(!view) { + return false; + } + + // don't complete environment, if we are + // still working inside the completion box + KTextEditor::CodeCompletionInterface *codeCompletionInterface + = qobject_cast(view); + if(codeCompletionInterface && codeCompletionInterface->isCompletionActive()) { + return false; + } + + int row = view->cursorPosition().line(); + int col = view->cursorPositionVirtual().column(); + QString line = view->document()->line(row).left(col); + + int pos = m_regexpEnter.indexIn(line); + if (pos != -1) { + line = m_regexpEnter.cap(1); + for(int i = 0; i < line.length(); ++i) { + if(!line[i].isSpace()) { + line[i] = ' '; + } + } + + QString envname, endenv; + if(m_regexpEnter.cap(2) == "\\[") { + envname = m_regexpEnter.cap(2); + endenv = "\\]\n"; + } + else { + envname = m_regexpEnter.cap(4); + endenv = m_regexpEnter.cap(2).replace("\\begin","\\end") + '\n'; + } + + if(shouldCompleteEnv(envname, view)) { + QString item = m_latexCommands->isListEnv(envname) ? "\\item " : QString(); + view->document()->insertText(KTextEditor::Cursor(row, col), '\n' + line + m_envAutoIndent + item + '\n' + line + endenv); + view->setCursorPosition(KTextEditor::Cursor(row + 1, line.length() + m_envAutoIndent.length() + item.length())); + return true; + } + } + return false; } bool EditorExtension::shouldCompleteEnv(const QString &env, KTextEditor::View *view) { - KILE_DEBUG_MAIN << "===EditorExtension::shouldCompleteEnv( " << env << " )==="; - QRegExp reTestBegin,reTestEnd; - if(env == "\\[") { - KILE_DEBUG_MAIN << "display style"; - reTestBegin.setPattern("(?:[^\\\\]|^)\\\\\\["); - // the first part is a non-capturing bracket (?:...) and we check if we don't have a backslash in front, - // or that we are at the begin of the line - reTestEnd.setPattern("(?:[^\\\\]|^)\\\\\\]"); - } - else { - reTestBegin.setPattern("(?:[^\\\\]|^)\\\\begin\\s*\\{" + QRegExp::escape(env) + "\\}"); - reTestEnd.setPattern("(?:[^\\\\]|^)\\\\end\\s*\\{" + QRegExp::escape(env) + "\\}"); - } - - int num = view->document()->lines(); - int numBeginsFound = 0; - int numEndsFound = 0; - KTextEditor::Cursor cursor = view->cursorPosition(); - int realLine = cursor.line(); - - for(int i = realLine; i < num; ++i) { - numBeginsFound += view->document()->line(i).count(reTestBegin); - numEndsFound += view->document()->line(i).count(reTestEnd); - KILE_DEBUG_MAIN << "line is " << i << " numBeginsFound = " << numBeginsFound << " , " << "numEndsFound = " << numEndsFound; - if(numEndsFound >= numBeginsFound) { - return false; - } - else if(numEndsFound == 0 && numBeginsFound > 1) { - return true; - } - else if(numBeginsFound > 2 || numEndsFound > 1) { - return true; // terminate the search - } - } - - return true; + KILE_DEBUG_MAIN << "===EditorExtension::shouldCompleteEnv( " << env << " )==="; + QRegExp reTestBegin,reTestEnd; + if(env == "\\[") { + KILE_DEBUG_MAIN << "display style"; + reTestBegin.setPattern("(?:[^\\\\]|^)\\\\\\["); + // the first part is a non-capturing bracket (?:...) and we check if we don't have a backslash in front, + // or that we are at the begin of the line + reTestEnd.setPattern("(?:[^\\\\]|^)\\\\\\]"); + } + else { + reTestBegin.setPattern("(?:[^\\\\]|^)\\\\begin\\s*\\{" + QRegExp::escape(env) + "\\}"); + reTestEnd.setPattern("(?:[^\\\\]|^)\\\\end\\s*\\{" + QRegExp::escape(env) + "\\}"); + } + + int num = view->document()->lines(); + int numBeginsFound = 0; + int numEndsFound = 0; + KTextEditor::Cursor cursor = view->cursorPosition(); + int realLine = cursor.line(); + + for(int i = realLine; i < num; ++i) { + numBeginsFound += view->document()->line(i).count(reTestBegin); + numEndsFound += view->document()->line(i).count(reTestEnd); + KILE_DEBUG_MAIN << "line is " << i << " numBeginsFound = " << numBeginsFound << " , " << "numEndsFound = " << numEndsFound; + if(numEndsFound >= numBeginsFound) { + return false; + } + else if(numEndsFound == 0 && numBeginsFound > 1) { + return true; + } + else if(numBeginsFound > 2 || numEndsFound > 1) { + return true; // terminate the search + } + } + + return true; } QString EditorExtension::getWhiteSpace(const QString &s) { - QString whitespace = s; + QString whitespace = s; - for(int i = 0; i < whitespace.length(); ++i) { - if(!whitespace[i].isSpace()) { - whitespace[i] = ' '; - } - } - return whitespace; + for(int i = 0; i < whitespace.length(); ++i) { + if(!whitespace[i].isSpace()) { + whitespace[i] = ' '; + } + } + return whitespace; } //////////////////// inside verbatim commands //////////////////// bool EditorExtension::insideVerbatim(KTextEditor::View *view) { - int rowEnv, colEnv; - QString nameEnv; + int rowEnv, colEnv; + QString nameEnv; - if(findOpenedEnvironment(rowEnv, colEnv, nameEnv, view)) { - if(m_latexCommands->isVerbatimEnv(nameEnv)) { - return true; - } - } + if(findOpenedEnvironment(rowEnv, colEnv, nameEnv, view)) { + if(m_latexCommands->isVerbatimEnv(nameEnv)) { + return true; + } + } - return false; + return false; } bool EditorExtension::insideVerb(KTextEditor::View *view) { - view = determineView(view); - if(!view) { - return false; - } - - // get current position - int row, col; - KTextEditor::Cursor cursor = view->cursorPosition(); - row = cursor.line(); - col = cursor.column(); - - int startpos = 0; - QString textline = getTextLineReal(view->document(),row); - QRegExp reg("\\\\verb(\\*?)(.)"); - while(true) { - int pos = textline.indexOf(reg,startpos); - if(pos < 0 || col < pos + 6 + reg.cap(1).length()) { - return false; - } - pos = textline.indexOf(reg.cap(2), pos + 6 + reg.cap(1).length()); - if(pos < 0 || col <= pos) { - return true; - } - - startpos = pos + 1; - } + view = determineView(view); + if(!view) { + return false; + } + + // get current position + int row, col; + KTextEditor::Cursor cursor = view->cursorPosition(); + row = cursor.line(); + col = cursor.column(); + + int startpos = 0; + QString textline = getTextLineReal(view->document(),row); + QRegExp reg("\\\\verb(\\*?)(.)"); + while(true) { + int pos = textline.indexOf(reg,startpos); + if(pos < 0 || col < pos + 6 + reg.cap(1).length()) { + return false; + } + pos = textline.indexOf(reg.cap(2), pos + 6 + reg.cap(1).length()); + if(pos < 0 || col <= pos) { + return true; + } + + startpos = pos + 1; + } } //////////////////// goto sectioning command //////////////////// void EditorExtension::gotoNextSectioning() { - gotoSectioning(false); + gotoSectioning(false); } void EditorExtension::gotoPrevSectioning() { - gotoSectioning(true); + gotoSectioning(true); } void EditorExtension::gotoSectioning(bool backwards, KTextEditor::View *view) { - view = determineView(view); - if(!view) { - return; - } + view = determineView(view); + if(!view) { + return; + } - int rowFound, colFound; - if( view && view->document()->isModified() ){ // after saving, the document structure is the current one, so in this case we don't need to update it - m_ki->viewManager()->updateStructure(true); - } - if(m_ki->structureWidget()->findSectioning(Q_NULLPTR,view->document(), view->cursorPosition().line(), view->cursorPosition().column(), backwards, false, rowFound, colFound)) { - view->setCursorPosition(KTextEditor::Cursor(rowFound, colFound)); - } + int rowFound, colFound; + if( view && view->document()->isModified() ) { // after saving, the document structure is the current one, so in this case we don't need to update it + m_ki->viewManager()->updateStructure(true); + } + if(m_ki->structureWidget()->findSectioning(Q_NULLPTR,view->document(), view->cursorPosition().line(), view->cursorPosition().column(), backwards, false, rowFound, colFound)) { + view->setCursorPosition(KTextEditor::Cursor(rowFound, colFound)); + } } //////////////////// sectioning popup //////////////////// void EditorExtension::sectioningCommand(KileWidget::StructureViewItem *item, int id) { - KTextEditor::View *view = determineView(Q_NULLPTR); - if(!view) { - return; - } - - if(!item) { - return; - } - KTextEditor::Document *doc = view->document(); - - // try to determine the whole secting - // get the start auf the selected sectioning - int row, col, row1, col1, row2, col2; - row = row1 = item->startline() - 1; - col = col1 = item->startcol() - 1; - - // FIXME tbraun make this more clever, introdoce in kiledocinfo a flag which can be easily queried for that, so that we don' - // check, if the document was changed in the meantime - QRegExp reg( "\\\\(part|chapter|section|subsection|subsubsection|paragraph|subparagraph)\\*?\\s*(\\{|\\[)" ); - QString textline = getTextLineReal(doc,row1); - if(reg.indexIn(textline, col1) != col1) { - m_ki->errorHandler()->clearMessages(); - m_ki->errorHandler()->printMessage(KileTool::Error, - i18n("The document was modified and the structure view should be updated, before starting such an operation."), - i18n("Structure View Error") ); - return; - } - - // increase cursor position and find the following sectioning command - if(!increaseCursorPosition(doc, row, col)) { - return; - } - if (!m_ki->structureWidget()->findSectioning(item, doc, row, col, false, true, row2, col2)){ - // or the end of the document - // if there is a '\end{document} command, we have to exclude it - if (!findEndOfDocument(doc, row, col, row2, col2)) { - row2 = doc->lines() - 1; - col2 = 0; - } - } - - // clear selection and make cursor position visible - view->removeSelection(); - view->setCursorPosition(KTextEditor::Cursor(row1, col1)); - - QString text; - KTextEditor::Document::EditingTransaction transaction(doc); - switch (id) { - case KileWidget::StructureWidget::SectioningCut: - QApplication::clipboard()->setText(doc->text(KTextEditor::Range(row1, col1, row2, col2))); // copy -> clipboard - doc->removeText(KTextEditor::Range(row1, col1, row2, col2)); // delete - break; - case KileWidget::StructureWidget::SectioningCopy: - QApplication::clipboard()->setText(doc->text(KTextEditor::Range(row1, col1, row2, col2))); // copy -> clipboard - break; - case KileWidget::StructureWidget::SectioningPaste: - text = QApplication::clipboard()->text(); // clipboard -> text - if(!text.isEmpty()) { - view->setCursorPosition(KTextEditor::Cursor(row2, col2)); // insert - view->insertText(text + '\n'); - } - break; - case KileWidget::StructureWidget::SectioningSelect: - view->setSelection(KTextEditor::Range(row1, col1, row2, col2)); // select - break; - case KileWidget::StructureWidget::SectioningDelete: - doc->removeText(KTextEditor::Range(row1, col1, row2, col2)); // delete - break; - case KileWidget::StructureWidget::SectioningComment: - commentLaTeX(doc, KTextEditor::Range(row1, col1, row2, col2)); - break; - case KileWidget::StructureWidget::SectioningPreview: - view->setSelection(KTextEditor::Range(row1, col1, row2, col2)); // quick preview - m_ki->quickPreview()->previewSelection(view, false); - view->removeSelection(); - break; - } - transaction.finish(); - - // update structure view, because it has changed - if(id == KileWidget::StructureWidget::SectioningDelete || id == KileWidget::StructureWidget::SectioningComment) { - m_ki->viewManager()->updateStructure(true); - } + KTextEditor::View *view = determineView(Q_NULLPTR); + if(!view) { + return; + } + + if(!item) { + return; + } + KTextEditor::Document *doc = view->document(); + + // try to determine the whole secting + // get the start auf the selected sectioning + int row, col, row1, col1, row2, col2; + row = row1 = item->startline() - 1; + col = col1 = item->startcol() - 1; + + // FIXME tbraun make this more clever, introdoce in kiledocinfo a flag which can be easily queried for that, so that we don' + // check, if the document was changed in the meantime + QRegExp reg( "\\\\(part|chapter|section|subsection|subsubsection|paragraph|subparagraph)\\*?\\s*(\\{|\\[)" ); + QString textline = getTextLineReal(doc,row1); + if(reg.indexIn(textline, col1) != col1) { + m_ki->errorHandler()->clearMessages(); + m_ki->errorHandler()->printMessage(KileTool::Error, + i18n("The document was modified and the structure view should be updated, before starting such an operation."), + i18n("Structure View Error") ); + return; + } + + // increase cursor position and find the following sectioning command + if(!increaseCursorPosition(doc, row, col)) { + return; + } + if (!m_ki->structureWidget()->findSectioning(item, doc, row, col, false, true, row2, col2)) { + // or the end of the document + // if there is a '\end{document} command, we have to exclude it + if (!findEndOfDocument(doc, row, col, row2, col2)) { + row2 = doc->lines() - 1; + col2 = 0; + } + } + + // clear selection and make cursor position visible + view->removeSelection(); + view->setCursorPosition(KTextEditor::Cursor(row1, col1)); + + QString text; + KTextEditor::Document::EditingTransaction transaction(doc); + switch (id) { + case KileWidget::StructureWidget::SectioningCut: + QApplication::clipboard()->setText(doc->text(KTextEditor::Range(row1, col1, row2, col2))); // copy -> clipboard + doc->removeText(KTextEditor::Range(row1, col1, row2, col2)); // delete + break; + case KileWidget::StructureWidget::SectioningCopy: + QApplication::clipboard()->setText(doc->text(KTextEditor::Range(row1, col1, row2, col2))); // copy -> clipboard + break; + case KileWidget::StructureWidget::SectioningPaste: + text = QApplication::clipboard()->text(); // clipboard -> text + if(!text.isEmpty()) { + view->setCursorPosition(KTextEditor::Cursor(row2, col2)); // insert + view->insertText(text + '\n'); + } + break; + case KileWidget::StructureWidget::SectioningSelect: + view->setSelection(KTextEditor::Range(row1, col1, row2, col2)); // select + break; + case KileWidget::StructureWidget::SectioningDelete: + doc->removeText(KTextEditor::Range(row1, col1, row2, col2)); // delete + break; + case KileWidget::StructureWidget::SectioningComment: + commentLaTeX(doc, KTextEditor::Range(row1, col1, row2, col2)); + break; + case KileWidget::StructureWidget::SectioningPreview: + view->setSelection(KTextEditor::Range(row1, col1, row2, col2)); // quick preview + m_ki->quickPreview()->previewSelection(view, false); + view->removeSelection(); + break; + } + transaction.finish(); + + // update structure view, because it has changed + if(id == KileWidget::StructureWidget::SectioningDelete || id == KileWidget::StructureWidget::SectioningComment) { + m_ki->viewManager()->updateStructure(true); + } } bool EditorExtension::findEndOfDocument(KTextEditor::Document *doc, int row, int col, int &rowFound, int &colFound) { - KTextEditor::Range documentRange(KTextEditor::Cursor(row, col), doc->documentEnd()); - QVector foundRanges = doc->searchText(documentRange, "\\end{document}"); + KTextEditor::Range documentRange(KTextEditor::Cursor(row, col), doc->documentEnd()); + QVector foundRanges = doc->searchText(documentRange, "\\end{document}"); - if(foundRanges.size() >= 1) { - KTextEditor::Range range = foundRanges.first(); - if(range.isValid()) { - rowFound = range.start().line(); - colFound = range.start().column(); - return true; - } - } + if(foundRanges.size() >= 1) { + KTextEditor::Range range = foundRanges.first(); + if(range.isValid()) { + rowFound = range.start().line(); + colFound = range.start().column(); + return true; + } + } - return false; + return false; } QString EditorExtension::extractIndentationString(KTextEditor::View *view, int line) { - KTextEditor::Document* doc = view->document(); + KTextEditor::Document* doc = view->document(); - if(!doc) { - return QString(); - } + if(!doc) { + return QString(); + } - const QString lineString = doc->line(line); - int lastWhiteSpaceCharIndex = -1; + const QString lineString = doc->line(line); + int lastWhiteSpaceCharIndex = -1; - for(int i = 0; i < lineString.length(); ++i) { - if(!lineString[i].isSpace()) { - break; - } - ++lastWhiteSpaceCharIndex; - } - return lineString.left(lastWhiteSpaceCharIndex + 1); + for(int i = 0; i < lineString.length(); ++i) { + if(!lineString[i].isSpace()) { + break; + } + ++lastWhiteSpaceCharIndex; + } + return lineString.left(lastWhiteSpaceCharIndex + 1); } } diff --git a/src/editorextension.h b/src/editorextension.h index cfa375e5..d8f8ae9b 100644 --- a/src/editorextension.h +++ b/src/editorextension.h @@ -1,287 +1,323 @@ /********************************************************************************************* copyright : (C) 2004-2007 by Holger Danielsson (holger.danielsson@versanet.de) 2008-2011 by Michel Ludwig (michel.ludwig@kdemail.net) 2012 by Holger Danielsson (holger.danielsson@versanet.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. * * * ***************************************************************************/ #ifndef EDITOREXTENSION_H #define EDITOREXTENSION_H #include #include #include #include #include #include "widgets/structurewidget.h" #include "latexcmd.h" class KileInfo; -namespace KileAction { class TagData; } +namespace KileAction { +class TagData; +} namespace KileDocument { class EditorExtension : public QObject { - Q_OBJECT + Q_OBJECT public: - EditorExtension(KileInfo *); - ~EditorExtension(); - - enum EnvType {EnvNone, EnvList, EnvTab, EnvCrTab}; - - enum SelectMode {smTex, smLetter, smWord, smNospace}; - - void readConfig(); - - void insertTag(const KileAction::TagData& data, KTextEditor::View *view); - - QString getTextLineReal(KTextEditor::Document *doc, int row); - void gotoBullet(bool backwards, KTextEditor::View *view = Q_NULLPTR); - void selectLine(int line,KTextEditor::View *view = Q_NULLPTR); - bool replaceLine(int line, const QString &s, KTextEditor::View *view = Q_NULLPTR); - - void gotoEnvironment(bool backwards, KTextEditor::View *view = Q_NULLPTR); - void matchEnvironment(KTextEditor::View *view = Q_NULLPTR); - void closeEnvironment(KTextEditor::View *view = Q_NULLPTR); - void closeAllEnvironments(KTextEditor::View *view = Q_NULLPTR); - void selectEnvironment(bool inside, KTextEditor::View *view = Q_NULLPTR); - void deleteEnvironment(bool inside, KTextEditor::View *view = Q_NULLPTR); - QString autoIndentEnvironment() { return m_envAutoIndent; } - - bool hasTexgroup(KTextEditor::View *view = Q_NULLPTR); - void gotoTexgroup(bool backwards, KTextEditor::View *view = Q_NULLPTR); - void selectTexgroup(bool inside, KTextEditor::View *view = Q_NULLPTR); - void deleteTexgroup(bool inside, KTextEditor::View *view = Q_NULLPTR); - KTextEditor::Range texgroupRange(bool inside=true, KTextEditor::View *view = Q_NULLPTR); - QString getTexgroupText(bool inside=true, KTextEditor::View *view = Q_NULLPTR); - - /** - * Returns a (potentially) translated list of options for inserting double quotes - */ - const QStringList doubleQuotesListI18N() { return m_quoteListI18N; } - - // get current word - bool getCurrentWord(KTextEditor::Document *doc, int row, int col, SelectMode mode, QString &word, int &x1, int &x2); - QString getEnvironmentText(int &row, int &col, QString &name, KTextEditor::View *view = Q_NULLPTR); - bool hasEnvironment(KTextEditor::View *view = Q_NULLPTR); - - KTextEditor::Range environmentRange(bool inside=false, KTextEditor::View *view = Q_NULLPTR); - QString environmentName(KTextEditor::View *view = Q_NULLPTR); - QString environmentText(bool inside=false, KTextEditor::View *view = Q_NULLPTR); - - KTextEditor::Range wordRange(const KTextEditor::Cursor &cursor, bool latexCommand=false, KTextEditor::View *view = Q_NULLPTR); - QString word(const KTextEditor::Cursor &cursor, bool latexCommand=false, KTextEditor::View *view = Q_NULLPTR); - - KTextEditor::Range findCurrentParagraphRange(KTextEditor::View *view, bool wholeLines = true); - QString getParagraphText(KTextEditor::View *view); - int prevNonEmptyLine(int line, KTextEditor::View *view = Q_NULLPTR); - int nextNonEmptyLine(int line, KTextEditor::View *view = Q_NULLPTR); - - // complete environment - bool eventInsertEnvironment(KTextEditor::View *view); - - // mathgroup - QString getMathgroupText(uint &row, uint &col, KTextEditor::View *view = Q_NULLPTR); - QString getMathgroupText(KTextEditor::View *view = Q_NULLPTR); - bool hasMathgroup(KTextEditor::View *view = Q_NULLPTR); - KTextEditor::Range mathgroupRange(KTextEditor::View *view = Q_NULLPTR); - - bool moveCursorRight(KTextEditor::View *view = Q_NULLPTR); - bool moveCursorLeft(KTextEditor::View *view = Q_NULLPTR); - bool moveCursorUp(KTextEditor::View *view = Q_NULLPTR); - bool moveCursorDown(KTextEditor::View *view = Q_NULLPTR); + EditorExtension(KileInfo *); + ~EditorExtension(); + + enum EnvType {EnvNone, EnvList, EnvTab, EnvCrTab}; + + enum SelectMode {smTex, smLetter, smWord, smNospace}; + + void readConfig(); + + void insertTag(const KileAction::TagData& data, KTextEditor::View *view); + + QString getTextLineReal(KTextEditor::Document *doc, int row); + void gotoBullet(bool backwards, KTextEditor::View *view = Q_NULLPTR); + void selectLine(int line,KTextEditor::View *view = Q_NULLPTR); + bool replaceLine(int line, const QString &s, KTextEditor::View *view = Q_NULLPTR); + + void gotoEnvironment(bool backwards, KTextEditor::View *view = Q_NULLPTR); + void matchEnvironment(KTextEditor::View *view = Q_NULLPTR); + void closeEnvironment(KTextEditor::View *view = Q_NULLPTR); + void closeAllEnvironments(KTextEditor::View *view = Q_NULLPTR); + void selectEnvironment(bool inside, KTextEditor::View *view = Q_NULLPTR); + void deleteEnvironment(bool inside, KTextEditor::View *view = Q_NULLPTR); + QString autoIndentEnvironment() { + return m_envAutoIndent; + } + + bool hasTexgroup(KTextEditor::View *view = Q_NULLPTR); + void gotoTexgroup(bool backwards, KTextEditor::View *view = Q_NULLPTR); + void selectTexgroup(bool inside, KTextEditor::View *view = Q_NULLPTR); + void deleteTexgroup(bool inside, KTextEditor::View *view = Q_NULLPTR); + KTextEditor::Range texgroupRange(bool inside=true, KTextEditor::View *view = Q_NULLPTR); + QString getTexgroupText(bool inside=true, KTextEditor::View *view = Q_NULLPTR); + + /** + * Returns a (potentially) translated list of options for inserting double quotes + */ + const QStringList doubleQuotesListI18N() { + return m_quoteListI18N; + } + + // get current word + bool getCurrentWord(KTextEditor::Document *doc, int row, int col, SelectMode mode, QString &word, int &x1, int &x2); + QString getEnvironmentText(int &row, int &col, QString &name, KTextEditor::View *view = Q_NULLPTR); + bool hasEnvironment(KTextEditor::View *view = Q_NULLPTR); + + KTextEditor::Range environmentRange(bool inside=false, KTextEditor::View *view = Q_NULLPTR); + QString environmentName(KTextEditor::View *view = Q_NULLPTR); + QString environmentText(bool inside=false, KTextEditor::View *view = Q_NULLPTR); + + KTextEditor::Range wordRange(const KTextEditor::Cursor &cursor, bool latexCommand=false, KTextEditor::View *view = Q_NULLPTR); + QString word(const KTextEditor::Cursor &cursor, bool latexCommand=false, KTextEditor::View *view = Q_NULLPTR); + + KTextEditor::Range findCurrentParagraphRange(KTextEditor::View *view, bool wholeLines = true); + QString getParagraphText(KTextEditor::View *view); + int prevNonEmptyLine(int line, KTextEditor::View *view = Q_NULLPTR); + int nextNonEmptyLine(int line, KTextEditor::View *view = Q_NULLPTR); + + // complete environment + bool eventInsertEnvironment(KTextEditor::View *view); + + // mathgroup + QString getMathgroupText(uint &row, uint &col, KTextEditor::View *view = Q_NULLPTR); + QString getMathgroupText(KTextEditor::View *view = Q_NULLPTR); + bool hasMathgroup(KTextEditor::View *view = Q_NULLPTR); + KTextEditor::Range mathgroupRange(KTextEditor::View *view = Q_NULLPTR); + + bool moveCursorRight(KTextEditor::View *view = Q_NULLPTR); + bool moveCursorLeft(KTextEditor::View *view = Q_NULLPTR); + bool moveCursorUp(KTextEditor::View *view = Q_NULLPTR); + bool moveCursorDown(KTextEditor::View *view = Q_NULLPTR); public Q_SLOTS: - void insertIntelligentNewline(KTextEditor::View *view = Q_NULLPTR); - - void selectEnvInside() { selectEnvironment(true); } - void selectEnvOutside() { selectEnvironment(false); } - void deleteEnvInside() { deleteEnvironment(true); } - void deleteEnvOutside() {deleteEnvironment(false); } - void gotoBeginEnv() { gotoEnvironment(true); } - void gotoEndEnv() { gotoEnvironment(false); } - void matchEnv() { matchEnvironment(); } - void closeEnv() {closeEnvironment(); } - void closeAllEnv() {closeAllEnvironments(); } - - void selectTexgroupInside() { selectTexgroup(true); } - void selectTexgroupOutside() { selectTexgroup(false); } - void deleteTexgroupInside() { deleteTexgroup(true); } - void deleteTexgroupOutside() { deleteTexgroup(false); } - void gotoBeginTexgroup() { gotoTexgroup(true); } - void gotoEndTexgroup() { gotoTexgroup(false); } - void matchTexgroup(KTextEditor::View *view = Q_NULLPTR); - void closeTexgroup(KTextEditor::View *view = Q_NULLPTR); - - void selectParagraph(KTextEditor::View *view = Q_NULLPTR, bool wholeLines = true); - void selectLine(KTextEditor::View *view = Q_NULLPTR); - void selectLines(int from, int to, KTextEditor::View *view = Q_NULLPTR); - void selectWord(SelectMode mode = smTex, KTextEditor::View *view = Q_NULLPTR); - void deleteParagraph(KTextEditor::View *view = Q_NULLPTR); - void deleteEndOfLine(KTextEditor::View *view = Q_NULLPTR); - void deleteWord(SelectMode mode = smTex, KTextEditor::View *view = Q_NULLPTR); - - void selectMathgroup(KTextEditor::View *view = Q_NULLPTR); - void deleteMathgroup(KTextEditor::View *view = Q_NULLPTR); - - void nextBullet(KTextEditor::View* view = Q_NULLPTR); - void prevBullet(KTextEditor::View* view = Q_NULLPTR); - void insertBullet(KTextEditor::View* view = Q_NULLPTR); - - void gotoNextParagraph(KTextEditor::View *view = Q_NULLPTR); - void gotoPrevParagraph(KTextEditor::View *view = Q_NULLPTR); - - void gotoNextSectioning(); - void gotoPrevSectioning(); - void gotoSectioning(bool backwards, KTextEditor::View *view = Q_NULLPTR); - void sectioningCommand(KileWidget::StructureViewItem *item, int id); - - bool insertDoubleQuotes(KTextEditor::View *view = Q_NULLPTR); - void initDoubleQuotes(); - - bool insertLatexFromUnicode(unsigned short rep, KTextEditor::View *view); - bool insertSpecialCharacter(const QString& texString, KTextEditor::View *view = Q_NULLPTR, const QString& dep = ""); - - void insertIntelligentTabulator(KTextEditor::View *view = Q_NULLPTR); - - void moveCursorToLastPositionInCurrentLine(KTextEditor::View *view = Q_NULLPTR); - void keyReturn(KTextEditor::View *view = Q_NULLPTR); - void commentLaTeX(KTextEditor::Document* document, const KTextEditor::Range &range); - - void goToLine(int line, KTextEditor::View *view = Q_NULLPTR); + void insertIntelligentNewline(KTextEditor::View *view = Q_NULLPTR); + + void selectEnvInside() { + selectEnvironment(true); + } + void selectEnvOutside() { + selectEnvironment(false); + } + void deleteEnvInside() { + deleteEnvironment(true); + } + void deleteEnvOutside() { + deleteEnvironment(false); + } + void gotoBeginEnv() { + gotoEnvironment(true); + } + void gotoEndEnv() { + gotoEnvironment(false); + } + void matchEnv() { + matchEnvironment(); + } + void closeEnv() { + closeEnvironment(); + } + void closeAllEnv() { + closeAllEnvironments(); + } + + void selectTexgroupInside() { + selectTexgroup(true); + } + void selectTexgroupOutside() { + selectTexgroup(false); + } + void deleteTexgroupInside() { + deleteTexgroup(true); + } + void deleteTexgroupOutside() { + deleteTexgroup(false); + } + void gotoBeginTexgroup() { + gotoTexgroup(true); + } + void gotoEndTexgroup() { + gotoTexgroup(false); + } + void matchTexgroup(KTextEditor::View *view = Q_NULLPTR); + void closeTexgroup(KTextEditor::View *view = Q_NULLPTR); + + void selectParagraph(KTextEditor::View *view = Q_NULLPTR, bool wholeLines = true); + void selectLine(KTextEditor::View *view = Q_NULLPTR); + void selectLines(int from, int to, KTextEditor::View *view = Q_NULLPTR); + void selectWord(SelectMode mode = smTex, KTextEditor::View *view = Q_NULLPTR); + void deleteParagraph(KTextEditor::View *view = Q_NULLPTR); + void deleteEndOfLine(KTextEditor::View *view = Q_NULLPTR); + void deleteWord(SelectMode mode = smTex, KTextEditor::View *view = Q_NULLPTR); + + void selectMathgroup(KTextEditor::View *view = Q_NULLPTR); + void deleteMathgroup(KTextEditor::View *view = Q_NULLPTR); + + void nextBullet(KTextEditor::View* view = Q_NULLPTR); + void prevBullet(KTextEditor::View* view = Q_NULLPTR); + void insertBullet(KTextEditor::View* view = Q_NULLPTR); + + void gotoNextParagraph(KTextEditor::View *view = Q_NULLPTR); + void gotoPrevParagraph(KTextEditor::View *view = Q_NULLPTR); + + void gotoNextSectioning(); + void gotoPrevSectioning(); + void gotoSectioning(bool backwards, KTextEditor::View *view = Q_NULLPTR); + void sectioningCommand(KileWidget::StructureViewItem *item, int id); + + bool insertDoubleQuotes(KTextEditor::View *view = Q_NULLPTR); + void initDoubleQuotes(); + + bool insertLatexFromUnicode(unsigned short rep, KTextEditor::View *view); + bool insertSpecialCharacter(const QString& texString, KTextEditor::View *view = Q_NULLPTR, const QString& dep = ""); + + void insertIntelligentTabulator(KTextEditor::View *view = Q_NULLPTR); + + void moveCursorToLastPositionInCurrentLine(KTextEditor::View *view = Q_NULLPTR); + void keyReturn(KTextEditor::View *view = Q_NULLPTR); + void commentLaTeX(KTextEditor::Document* document, const KTextEditor::Range &range); + + void goToLine(int line, KTextEditor::View *view = Q_NULLPTR); private: - enum EnvTag {EnvBegin, EnvEnd}; - - enum EnvPos {EnvLeft, EnvInside, EnvRight}; - - enum MathTag {mmNoMathMode, mmMathDollar, mmMathParen, mmDisplaymathParen, mmMathEnv, mmDisplaymathEnv}; - - enum CursorMove {MoveCursorLeft, MoveCursorRight, MoveCursorUp, MoveCursorDown}; - - struct EnvData { - int row; - int col; - QString name; - int len; - EnvPos cpos; - EnvTag tag; - EnvType type; - }; - - struct MathData { - int row; - int col; - int len; - unsigned int numdollar; - MathTag tag; - QString envname; - }; - - struct BracketData { - int row; - int col; - bool open; - }; - - QRegExp m_reg; - bool m_overwritemode; - QString m_envAutoIndent; - - KileInfo *m_ki; - - // complete environments - QRegExp m_regexpEnter; - - // double Quotes - bool m_dblQuotes; - QStringList m_quoteListI18N; - QList > m_quoteList; - QString m_leftDblQuote, m_rightDblQuote; - - // special chars - bool m_specialCharacters; - - // change cursor position - bool increaseCursorPosition(KTextEditor::Document *doc, int &row, int &col); - bool decreaseCursorPosition(KTextEditor::Document *doc, int &row, int &col); - bool moveCursor(KTextEditor::View *view, CursorMove direction); - - // check position - bool isValidBackslash(KTextEditor::Document *doc, int row, int col); - bool isCommentPosition(KTextEditor::Document *doc, int row, int col); - bool isEnvironmentPosition(KTextEditor::Document *doc, int row, int col,EnvData &env); - - // find environment tags - bool findBeginEnvironment(KTextEditor::Document *doc, int row, int col, EnvData &env); - bool findEndEnvironment(KTextEditor::Document *doc, int row, int col, EnvData &env); - bool findEnvironmentTag(KTextEditor::Document *doc, int row, int col, EnvData &env, bool backwards = false); - bool findOpenedEnvironment(int &row, int &col, QString &envname, KTextEditor::View *view); - QStringList findOpenedEnvironmentList(KTextEditor::View *view, bool position = false); - - // get current environment - bool getEnvironment(bool inside, EnvData &envbegin, EnvData &envend,KTextEditor::View *view); - bool expandSelectionEnvironment(bool inside, KTextEditor::View *view); - - // find brackets - bool isBracketPosition(KTextEditor::Document *doc, int row, int col, BracketData &bracket); - bool findOpenBracket(KTextEditor::Document *doc, int row, int col, BracketData &bracket); - bool findCloseBracket(KTextEditor::Document *doc, int row, int col, BracketData &bracket); - bool findCloseBracketTag(KTextEditor::Document *doc, int row, int col,BracketData &bracket); - bool findOpenBracketTag(KTextEditor::Document *doc, int row, int col, BracketData &bracket); - - // find math tags - bool isOpeningMathTagPosition(KTextEditor::Document *doc, uint row, uint col, MathData &mathdata); - bool isClosingMathTagPosition(KTextEditor::Document *doc, uint row, uint col, MathData &mathdata); - bool findOpenMathTag(KTextEditor::Document *doc, int row, int col, MathData &mathdata); - bool findCloseMathTag(KTextEditor::Document *doc, int row, int col, MathData &mathdata); - bool checkMathtags(const MathData &begin,const MathData &end); - - // mathgroup - bool getMathgroup(KTextEditor::View *view, int &row1, int &col1, int &row2, int &col2); - - // get current Texgroup - bool getTexgroup(bool inside, BracketData &open, BracketData &close, KTextEditor::View *view); - - // find current paragraph - bool findCurrentTexParagraph(int &startline, int &endline, KTextEditor::View *view); - bool findCurrentTexParagraph(int &startline, int& startcolumn, int &endline, int& endcolumn, KTextEditor::View *view); - - // sectioning commands - bool findEndOfDocument(KTextEditor::Document *doc, int row, int col, int &rowFound, int &colFound); - - // check environment type - KileDocument::LatexCommands *m_latexCommands; - bool shouldCompleteEnv(const QString &envname, KTextEditor::View *view); - QString getWhiteSpace(const QString &s); - - // verbatim text - bool insideVerb(KTextEditor::View *view); - bool insideVerbatim(KTextEditor::View *view); - - // help - void readHelpList(QString const &filename); - - KTextEditor::View *determineView(KTextEditor::View *view); - void deleteRange(KTextEditor::Range &range, KTextEditor::View *view); - - QString extractIndentationString(KTextEditor::View *view, int line); + enum EnvTag {EnvBegin, EnvEnd}; + + enum EnvPos {EnvLeft, EnvInside, EnvRight}; + + enum MathTag {mmNoMathMode, mmMathDollar, mmMathParen, mmDisplaymathParen, mmMathEnv, mmDisplaymathEnv}; + + enum CursorMove {MoveCursorLeft, MoveCursorRight, MoveCursorUp, MoveCursorDown}; + + struct EnvData { + int row; + int col; + QString name; + int len; + EnvPos cpos; + EnvTag tag; + EnvType type; + }; + + struct MathData { + int row; + int col; + int len; + unsigned int numdollar; + MathTag tag; + QString envname; + }; + + struct BracketData { + int row; + int col; + bool open; + }; + + QRegExp m_reg; + bool m_overwritemode; + QString m_envAutoIndent; + + KileInfo *m_ki; + + // complete environments + QRegExp m_regexpEnter; + + // double Quotes + bool m_dblQuotes; + QStringList m_quoteListI18N; + QList > m_quoteList; + QString m_leftDblQuote, m_rightDblQuote; + + // special chars + bool m_specialCharacters; + + // change cursor position + bool increaseCursorPosition(KTextEditor::Document *doc, int &row, int &col); + bool decreaseCursorPosition(KTextEditor::Document *doc, int &row, int &col); + bool moveCursor(KTextEditor::View *view, CursorMove direction); + + // check position + bool isValidBackslash(KTextEditor::Document *doc, int row, int col); + bool isCommentPosition(KTextEditor::Document *doc, int row, int col); + bool isEnvironmentPosition(KTextEditor::Document *doc, int row, int col,EnvData &env); + + // find environment tags + bool findBeginEnvironment(KTextEditor::Document *doc, int row, int col, EnvData &env); + bool findEndEnvironment(KTextEditor::Document *doc, int row, int col, EnvData &env); + bool findEnvironmentTag(KTextEditor::Document *doc, int row, int col, EnvData &env, bool backwards = false); + bool findOpenedEnvironment(int &row, int &col, QString &envname, KTextEditor::View *view); + QStringList findOpenedEnvironmentList(KTextEditor::View *view, bool position = false); + + // get current environment + bool getEnvironment(bool inside, EnvData &envbegin, EnvData &envend,KTextEditor::View *view); + bool expandSelectionEnvironment(bool inside, KTextEditor::View *view); + + // find brackets + bool isBracketPosition(KTextEditor::Document *doc, int row, int col, BracketData &bracket); + bool findOpenBracket(KTextEditor::Document *doc, int row, int col, BracketData &bracket); + bool findCloseBracket(KTextEditor::Document *doc, int row, int col, BracketData &bracket); + bool findCloseBracketTag(KTextEditor::Document *doc, int row, int col,BracketData &bracket); + bool findOpenBracketTag(KTextEditor::Document *doc, int row, int col, BracketData &bracket); + + // find math tags + bool isOpeningMathTagPosition(KTextEditor::Document *doc, uint row, uint col, MathData &mathdata); + bool isClosingMathTagPosition(KTextEditor::Document *doc, uint row, uint col, MathData &mathdata); + bool findOpenMathTag(KTextEditor::Document *doc, int row, int col, MathData &mathdata); + bool findCloseMathTag(KTextEditor::Document *doc, int row, int col, MathData &mathdata); + bool checkMathtags(const MathData &begin,const MathData &end); + + // mathgroup + bool getMathgroup(KTextEditor::View *view, int &row1, int &col1, int &row2, int &col2); + + // get current Texgroup + bool getTexgroup(bool inside, BracketData &open, BracketData &close, KTextEditor::View *view); + + // find current paragraph + bool findCurrentTexParagraph(int &startline, int &endline, KTextEditor::View *view); + bool findCurrentTexParagraph(int &startline, int& startcolumn, int &endline, int& endcolumn, KTextEditor::View *view); + + // sectioning commands + bool findEndOfDocument(KTextEditor::Document *doc, int row, int col, int &rowFound, int &colFound); + + // check environment type + KileDocument::LatexCommands *m_latexCommands; + bool shouldCompleteEnv(const QString &envname, KTextEditor::View *view); + QString getWhiteSpace(const QString &s); + + // verbatim text + bool insideVerb(KTextEditor::View *view); + bool insideVerbatim(KTextEditor::View *view); + + // help + void readHelpList(QString const &filename); + + KTextEditor::View *determineView(KTextEditor::View *view); + void deleteRange(KTextEditor::Range &range, KTextEditor::View *view); + + QString extractIndentationString(KTextEditor::View *view, int line); }; } #endif diff --git a/src/editorkeysequencemanager.cpp b/src/editorkeysequencemanager.cpp index 81c6932d..986a0893 100644 --- a/src/editorkeysequencemanager.cpp +++ b/src/editorkeysequencemanager.cpp @@ -1,259 +1,259 @@ /************************************************************************** * Copyright (C) 2006 by Michel Ludwig (michel.ludwig@kdemail.net) * ***************************************************************************/ /************************************************************************** * * * 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. * * * ***************************************************************************/ #include "editorkeysequencemanager.h" #include "kileinfo.h" #include "scriptmanager.h" #include "scripting/script.h" #include #include #include #include namespace KileEditorKeySequence { - Manager::Manager(KileInfo* kileInfo, QObject *parent, const char *name) : QObject(parent), m_kileInfo(kileInfo) - { - setObjectName(name); - } - - Manager::~Manager() - { - } - - void Manager::addAction(const QString& seq, Action *action) - { - if(seq.isEmpty()) { - return; - } - if(m_actionMap.find(seq) == m_actionMap.end()) { - m_actionMap[seq] = action; - m_watchedKeySequencesList.push_back(seq); - emit watchedKeySequencesChanged(); - } - } - - void Manager::removeKeySequence(const QString& seq) - { - if(seq.isEmpty()) { - return; - } - QMap::iterator it = m_actionMap.find(seq); - if(it != m_actionMap.end()) { - delete (it.value()); - m_actionMap.erase(it); - m_watchedKeySequencesList.removeAll(seq); - emit watchedKeySequencesChanged(); - } - } - - void Manager::removeKeySequence(const QStringList& l) - { - bool changed = false; - for(QStringList::const_iterator i = l.begin(); i != l.end(); ++i) { - if((*i).isEmpty()) { - continue; - } - QMap::iterator it = m_actionMap.find(*i); - if(it != m_actionMap.end()) { - delete (it.value()); - m_actionMap.erase(it); - m_watchedKeySequencesList.removeAll(*i); - changed = true; - } - } - if(changed) { - emit watchedKeySequencesChanged(); - } - } - - void Manager::addActionMap(const QMap& map) - { - bool changed = false; - for(QMap::const_iterator i = map.begin(); i != map.end(); ++i) { - if(i.key().isEmpty()) { - continue; - } - if(m_actionMap[i.key()] != i.value()) { - m_actionMap[i.key()] = i.value(); - changed = true; - } - } - if(changed) { - emit watchedKeySequencesChanged(); - } - } - - QString Manager::getKeySequence(const Action* a) - { - for(QMap::const_iterator i = m_actionMap.constBegin(); i != m_actionMap.constEnd(); ++i) { - if(i.value() == a) { - return i.key(); - } - } - return QString(); - } - - Action* Manager::getAction(const QString& seq) - { - QMap::iterator i = m_actionMap.find(seq); - return (i == m_actionMap.end()) ? Q_NULLPTR : (*i); - } - - void Manager::setEditorKeySequence(const QString& /* seq */, Action* /* action */) - { - } - - void Manager::keySequenceTyped(const QString& seq) - { - m_actionMap[seq]->execute(); - } - - void Manager::clear() - { - m_watchedKeySequencesList.clear(); - m_actionMap.clear(); - emit watchedKeySequencesChanged(); - } - - - const QStringList& Manager::getWatchedKeySequences() - { - return m_watchedKeySequencesList; - } - - bool Manager::isSequenceAssigned(const QString& seq) const { - for(QList::const_iterator i = m_watchedKeySequencesList.begin(); i != m_watchedKeySequencesList.end(); ++i) { - if((*i).startsWith(seq)) { - return true; - } - } - return false; - } - - QPair Manager::checkSequence(const QString& seq, const QString& skip) - { - for(QList::iterator i = m_watchedKeySequencesList.begin(); i != m_watchedKeySequencesList.end(); ++i) { - if((*i) == skip) { - continue; - } - if((*i).startsWith(seq)) { - return (*i == seq) ? qMakePair(1, seq) : qMakePair(2, *i); - } - if(!(*i).isEmpty() && seq.startsWith(*i)) { - return qMakePair(3, *i); - } - } - return qMakePair(0, QString()); - } +Manager::Manager(KileInfo* kileInfo, QObject *parent, const char *name) : QObject(parent), m_kileInfo(kileInfo) +{ + setObjectName(name); +} + +Manager::~Manager() +{ +} + +void Manager::addAction(const QString& seq, Action *action) +{ + if(seq.isEmpty()) { + return; + } + if(m_actionMap.find(seq) == m_actionMap.end()) { + m_actionMap[seq] = action; + m_watchedKeySequencesList.push_back(seq); + emit watchedKeySequencesChanged(); + } +} + +void Manager::removeKeySequence(const QString& seq) +{ + if(seq.isEmpty()) { + return; + } + QMap::iterator it = m_actionMap.find(seq); + if(it != m_actionMap.end()) { + delete (it.value()); + m_actionMap.erase(it); + m_watchedKeySequencesList.removeAll(seq); + emit watchedKeySequencesChanged(); + } +} + +void Manager::removeKeySequence(const QStringList& l) +{ + bool changed = false; + for(QStringList::const_iterator i = l.begin(); i != l.end(); ++i) { + if((*i).isEmpty()) { + continue; + } + QMap::iterator it = m_actionMap.find(*i); + if(it != m_actionMap.end()) { + delete (it.value()); + m_actionMap.erase(it); + m_watchedKeySequencesList.removeAll(*i); + changed = true; + } + } + if(changed) { + emit watchedKeySequencesChanged(); + } +} + +void Manager::addActionMap(const QMap& map) +{ + bool changed = false; + for(QMap::const_iterator i = map.begin(); i != map.end(); ++i) { + if(i.key().isEmpty()) { + continue; + } + if(m_actionMap[i.key()] != i.value()) { + m_actionMap[i.key()] = i.value(); + changed = true; + } + } + if(changed) { + emit watchedKeySequencesChanged(); + } +} + +QString Manager::getKeySequence(const Action* a) +{ + for(QMap::const_iterator i = m_actionMap.constBegin(); i != m_actionMap.constEnd(); ++i) { + if(i.value() == a) { + return i.key(); + } + } + return QString(); +} + +Action* Manager::getAction(const QString& seq) +{ + QMap::iterator i = m_actionMap.find(seq); + return (i == m_actionMap.end()) ? Q_NULLPTR : (*i); +} + +void Manager::setEditorKeySequence(const QString& /* seq */, Action* /* action */) +{ +} + +void Manager::keySequenceTyped(const QString& seq) +{ + m_actionMap[seq]->execute(); +} + +void Manager::clear() +{ + m_watchedKeySequencesList.clear(); + m_actionMap.clear(); + emit watchedKeySequencesChanged(); +} + + +const QStringList& Manager::getWatchedKeySequences() +{ + return m_watchedKeySequencesList; +} + +bool Manager::isSequenceAssigned(const QString& seq) const { + for(QList::const_iterator i = m_watchedKeySequencesList.begin(); i != m_watchedKeySequencesList.end(); ++i) { + if((*i).startsWith(seq)) { + return true; + } + } + return false; +} + +QPair Manager::checkSequence(const QString& seq, const QString& skip) +{ + for(QList::iterator i = m_watchedKeySequencesList.begin(); i != m_watchedKeySequencesList.end(); ++i) { + if((*i) == skip) { + continue; + } + if((*i).startsWith(seq)) { + return (*i == seq) ? qMakePair(1, seq) : qMakePair(2, *i); + } + if(!(*i).isEmpty() && seq.startsWith(*i)) { + return qMakePair(3, *i); + } + } + return qMakePair(0, QString()); +} Recorder::Recorder(KTextEditor::View *view, Manager *manager) : QObject(view), m_manager(manager), m_view(view) { - connect(m_manager, SIGNAL(watchedKeySequencesChanged()), this, SLOT(reloadWatchedKeySequences())); - connect(this, SIGNAL(detectedTypedKeySequence(const QString&)), m_manager, SLOT(keySequenceTyped(const QString&))); - KTextEditor::Cursor cursor = m_view->cursorPosition(); - m_oldLine = cursor.line(); - m_oldCol = cursor.column(); + connect(m_manager, SIGNAL(watchedKeySequencesChanged()), this, SLOT(reloadWatchedKeySequences())); + connect(this, SIGNAL(detectedTypedKeySequence(const QString&)), m_manager, SLOT(keySequenceTyped(const QString&))); + KTextEditor::Cursor cursor = m_view->cursorPosition(); + m_oldLine = cursor.line(); + m_oldCol = cursor.column(); - reloadWatchedKeySequences(); + reloadWatchedKeySequences(); } Recorder::~Recorder() { } bool Recorder::eventFilter(QObject* /* o */, QEvent *e) { - if (e->type() == QEvent::KeyPress) { - QKeyEvent *keyEvent = (QKeyEvent*)(e); - int curLine, curCol; - KTextEditor::Cursor cursor = m_view->cursorPosition(); - curLine = cursor.line(); - curCol = cursor.column(); - if(curLine != m_oldLine || m_oldCol+1 != curCol) { - m_typedSequence.clear(); - m_oldLine = curLine; - m_oldCol = curCol; - } - else { - ++m_oldCol; - } - m_typedSequence += keyEvent->text(); - if(m_typedSequence.length() == m_maxSequenceLength + 1) { - m_typedSequence = m_typedSequence.mid(1, m_typedSequence.length() - 1); - } - return seekForKeySequence(m_typedSequence); - } - return false; + if (e->type() == QEvent::KeyPress) { + QKeyEvent *keyEvent = (QKeyEvent*)(e); + int curLine, curCol; + KTextEditor::Cursor cursor = m_view->cursorPosition(); + curLine = cursor.line(); + curCol = cursor.column(); + if(curLine != m_oldLine || m_oldCol+1 != curCol) { + m_typedSequence.clear(); + m_oldLine = curLine; + m_oldCol = curCol; + } + else { + ++m_oldCol; + } + m_typedSequence += keyEvent->text(); + if(m_typedSequence.length() == m_maxSequenceLength + 1) { + m_typedSequence = m_typedSequence.mid(1, m_typedSequence.length() - 1); + } + return seekForKeySequence(m_typedSequence); + } + return false; +} + +bool Recorder::seekForKeySequence(const QString& s) +{ + for(int i = 0; i < s.length(); ++i) { + QString toCheck = s.right(s.length() - i); + if(m_watchedKeySequencesList.contains(toCheck) > 0) { + m_view->document()->removeText(KTextEditor::Range(m_oldLine, m_oldCol - (s.length() - i - 1), m_oldLine, m_oldCol)); + m_typedSequence.clear(); // clean m_typedSequence to avoid wrong action triggering if one presses keys without printable character + emit detectedTypedKeySequence(toCheck); + return true; + } + } + return false; +} + +void Recorder::reloadWatchedKeySequences() +{ + m_watchedKeySequencesList = m_manager->getWatchedKeySequences(); + m_maxSequenceLength = 0; + for(QStringList::iterator i = m_watchedKeySequencesList.begin(); i != m_watchedKeySequencesList.end(); ++i) { + m_maxSequenceLength = qMax(m_maxSequenceLength, (*i).length()); + } + if(m_maxSequenceLength < m_typedSequence.length()) { + m_typedSequence = m_typedSequence.right(m_maxSequenceLength); + } +} + +Action::Action() { +} + +Action::~Action() { +} + +QString Action::getDescription() const { + return QString(); +} + +ExecuteScriptAction::ExecuteScriptAction(KileScript::Script *script, KileScript::Manager *scriptManager) : m_script(script), m_scriptManager(scriptManager) +{ } - bool Recorder::seekForKeySequence(const QString& s) - { - for(int i = 0; i < s.length(); ++i) { - QString toCheck = s.right(s.length() - i); - if(m_watchedKeySequencesList.contains(toCheck) > 0) { - m_view->document()->removeText(KTextEditor::Range(m_oldLine, m_oldCol - (s.length() - i - 1), m_oldLine, m_oldCol)); - m_typedSequence.clear(); // clean m_typedSequence to avoid wrong action triggering if one presses keys without printable character - emit detectedTypedKeySequence(toCheck); - return true; - } - } - return false; - } - - void Recorder::reloadWatchedKeySequences() - { - m_watchedKeySequencesList = m_manager->getWatchedKeySequences(); - m_maxSequenceLength = 0; - for(QStringList::iterator i = m_watchedKeySequencesList.begin(); i != m_watchedKeySequencesList.end(); ++i) { - m_maxSequenceLength = qMax(m_maxSequenceLength, (*i).length()); - } - if(m_maxSequenceLength < m_typedSequence.length()) { - m_typedSequence = m_typedSequence.right(m_maxSequenceLength); - } - } - - Action::Action() { - } - - Action::~Action() { - } - - QString Action::getDescription() const { - return QString(); - } - - ExecuteScriptAction::ExecuteScriptAction(KileScript::Script *script, KileScript::Manager *scriptManager) : m_script(script), m_scriptManager(scriptManager) - { - } - - ExecuteScriptAction::~ExecuteScriptAction() - { - } - - void ExecuteScriptAction::execute() - { - m_scriptManager->executeScript(m_script); - } - - QString ExecuteScriptAction::getDescription() const - { - return i18n("Script execution of %1", m_script->getFileName()); - } +ExecuteScriptAction::~ExecuteScriptAction() +{ +} + +void ExecuteScriptAction::execute() +{ + m_scriptManager->executeScript(m_script); +} + +QString ExecuteScriptAction::getDescription() const +{ + return i18n("Script execution of %1", m_script->getFileName()); +} } diff --git a/src/editorkeysequencemanager.h b/src/editorkeysequencemanager.h index 95fd656a..a48fb209 100644 --- a/src/editorkeysequencemanager.h +++ b/src/editorkeysequencemanager.h @@ -1,229 +1,229 @@ /************************************************************************** * Copyright (C) 2006 by Michel Ludwig (michel.ludwig@kdemail.net) * ***************************************************************************/ /************************************************************************** * * * 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. * * * ***************************************************************************/ #ifndef EDITORKEYSEQUENCEMANAGER_H #define EDITORKEYSEQUENCEMANAGER_H #include #include #include #include #include #include namespace KileScript { - class Script; - class Manager; +class Script; +class Manager; } class KileInfo; namespace KileEditorKeySequence { - /** - * This class represents an action that can be assigned to an editor key sequence. - **/ - class Action { - public: - Action(); - virtual ~Action(); - - /** - * The main method, which implements the "action" itself. - **/ - virtual void execute() = 0; - - /** - * Returns a textual representation of the action. - **/ - virtual QString getDescription() const; - }; - - /** - * This class represents the execution of a script in Kile. - **/ - class ExecuteScriptAction : public Action { - public: - ExecuteScriptAction(KileScript::Script *script, KileScript::Manager *scriptManager); - virtual ~ExecuteScriptAction(); - - virtual void execute(); - virtual QString getDescription() const; - - protected: - KileScript::Script *m_script; - KileScript::Manager *m_scriptManager; - }; - - // forward declaration - class Recorder; - - /** - * This manager class is responsible for handling the key sequences that get assigned - * to actions. Currently, every key sequence can only trigger one single action. - * - * Whenever a watched key sequence is typed, the manager triggers the corresponding - * action. The only characters that are allowed in key sequences are those that make - * the cursor advance by one position, i.e. for example tabs are not allowed in key - * sequences. - **/ - class Manager : public QObject { - Q_OBJECT - - friend class Recorder; - - public: - /** - * Constructs a new manager object. - **/ - explicit Manager(KileInfo* kileInfo, QObject *parent = 0, const char *name = 0); - virtual ~Manager(); - - /** - * Adds a new consequence and the corresponding action. - * @param seq the key sequence - * @param action the action for the sequence - **/ - void addAction(const QString& seq, Action *action); - - /** - * Convenience method. Adds a key sequence-to-action map to this - * manager, removing any existing mappings. - * @warning This method overrides any exising mappings ! - **/ - void addActionMap(const QMap& map); - - /** - * Removes all the mappings. - **/ - void clear(); - - /** - * Returns a list of all the key sequences that are currently being - * watched. - **/ - const QStringList& getWatchedKeySequences(); - - /** - * Returns the key sequence that corresponds to an action. - * @param a the action that is considered - **/ - QString getKeySequence(const Action* a); - - /** - * Returns the action that corresponds to a key sequence. - **/ - Action* getAction(const QString& seq); - - /** - * Remove a key sequence, i.e. the key sequence is no longer watched. - * @param seq the key sequence that should be removed - **/ - void removeKeySequence(const QString& seq); - - /** - * Convenience method. Removes every key sequence contained in the list. - * @see removeKeySequence(const QString& seq) - **/ - void removeKeySequence(const QStringList& l); - - /** - * @warning not implemented yet ! - **/ - void setEditorKeySequence(const QString& seq, Action *action); - - /** - * Checks whether the sequence "seq" is already assigned to an action. - * This method also checks whether a longer sequence that starts with - * "seq" is assigned to an action. - * @param seq the sequence that should be checked - * @return "true" if and only the sequence "seq" or another sequence - * that starts with "seq" is assigned to an action - **/ - bool isSequenceAssigned(const QString& seq) const; - - /** - * Performs a few checks on a key sequence. - * @returns in the first component: 0 if the sequence is free; 1 - * if the sequence is assigned; 2 if there is a longer, - * currently stored sequence that starts with "seq"; 3 - * if "seq" starts with a shorter sequence that is currently - * stored - * - * in the second component: a string that corresponds to one - * of the previous cases (in the case 0: QString()) - **/ - QPair checkSequence(const QString& seq, const QString& skip = QString()); - - Q_SIGNALS: - /** - * Emitted whenever the set of watched key sequences changes. - **/ - void watchedKeySequencesChanged(); - - protected Q_SLOTS: - /** - * Signalises to the manager that a (watched) sequence has been typed. - * @param seq the sequence that has been typed - **/ - void keySequenceTyped(const QString& seq); - - protected: - KileInfo *m_kileInfo; - QMap m_actionMap; - QStringList m_watchedKeySequencesList; - }; - - /** - * This class keeps track of the characters that are typed. It is used in - * conjunction with a KTextEditor view and a KileEditorKeySequence::Manager. - **/ - class Recorder : public QObject { - Q_OBJECT - public: - Recorder(KTextEditor::View *view, Manager *manager); - virtual ~Recorder(); - - Q_SIGNALS: - /** - * Emitted whenever a key sequence that is currently watched has - * been typed. - **/ - void detectedTypedKeySequence(const QString& seq); - - - public Q_SLOTS: - /** - * Reloads the key sequences that this recorders watches. - **/ - void reloadWatchedKeySequences(); - - protected: - Manager *m_manager; - QString m_typedSequence; - int m_maxSequenceLength; - int m_oldCol, m_oldLine; - KTextEditor::View* m_view; - QStringList m_watchedKeySequencesList; - - virtual bool eventFilter(QObject *o, QEvent *e); - - /** - * Checks whether a key sequence is currently watched. - * @param s the key sequence that should be checked - **/ - bool seekForKeySequence(const QString& s); - }; +/** + * This class represents an action that can be assigned to an editor key sequence. + **/ +class Action { +public: + Action(); + virtual ~Action(); + + /** + * The main method, which implements the "action" itself. + **/ + virtual void execute() = 0; + + /** + * Returns a textual representation of the action. + **/ + virtual QString getDescription() const; +}; + +/** + * This class represents the execution of a script in Kile. + **/ +class ExecuteScriptAction : public Action { +public: + ExecuteScriptAction(KileScript::Script *script, KileScript::Manager *scriptManager); + virtual ~ExecuteScriptAction(); + + virtual void execute(); + virtual QString getDescription() const; + +protected: + KileScript::Script *m_script; + KileScript::Manager *m_scriptManager; +}; + +// forward declaration +class Recorder; + +/** + * This manager class is responsible for handling the key sequences that get assigned + * to actions. Currently, every key sequence can only trigger one single action. + * + * Whenever a watched key sequence is typed, the manager triggers the corresponding + * action. The only characters that are allowed in key sequences are those that make + * the cursor advance by one position, i.e. for example tabs are not allowed in key + * sequences. + **/ +class Manager : public QObject { + Q_OBJECT + + friend class Recorder; + +public: + /** + * Constructs a new manager object. + **/ + explicit Manager(KileInfo* kileInfo, QObject *parent = 0, const char *name = 0); + virtual ~Manager(); + + /** + * Adds a new consequence and the corresponding action. + * @param seq the key sequence + * @param action the action for the sequence + **/ + void addAction(const QString& seq, Action *action); + + /** + * Convenience method. Adds a key sequence-to-action map to this + * manager, removing any existing mappings. + * @warning This method overrides any exising mappings ! + **/ + void addActionMap(const QMap& map); + + /** + * Removes all the mappings. + **/ + void clear(); + + /** + * Returns a list of all the key sequences that are currently being + * watched. + **/ + const QStringList& getWatchedKeySequences(); + + /** + * Returns the key sequence that corresponds to an action. + * @param a the action that is considered + **/ + QString getKeySequence(const Action* a); + + /** + * Returns the action that corresponds to a key sequence. + **/ + Action* getAction(const QString& seq); + + /** + * Remove a key sequence, i.e. the key sequence is no longer watched. + * @param seq the key sequence that should be removed + **/ + void removeKeySequence(const QString& seq); + + /** + * Convenience method. Removes every key sequence contained in the list. + * @see removeKeySequence(const QString& seq) + **/ + void removeKeySequence(const QStringList& l); + + /** + * @warning not implemented yet ! + **/ + void setEditorKeySequence(const QString& seq, Action *action); + + /** + * Checks whether the sequence "seq" is already assigned to an action. + * This method also checks whether a longer sequence that starts with + * "seq" is assigned to an action. + * @param seq the sequence that should be checked + * @return "true" if and only the sequence "seq" or another sequence + * that starts with "seq" is assigned to an action + **/ + bool isSequenceAssigned(const QString& seq) const; + + /** + * Performs a few checks on a key sequence. + * @returns in the first component: 0 if the sequence is free; 1 + * if the sequence is assigned; 2 if there is a longer, + * currently stored sequence that starts with "seq"; 3 + * if "seq" starts with a shorter sequence that is currently + * stored + * + * in the second component: a string that corresponds to one + * of the previous cases (in the case 0: QString()) + **/ + QPair checkSequence(const QString& seq, const QString& skip = QString()); + +Q_SIGNALS: + /** + * Emitted whenever the set of watched key sequences changes. + **/ + void watchedKeySequencesChanged(); + +protected Q_SLOTS: + /** + * Signalises to the manager that a (watched) sequence has been typed. + * @param seq the sequence that has been typed + **/ + void keySequenceTyped(const QString& seq); + +protected: + KileInfo *m_kileInfo; + QMap m_actionMap; + QStringList m_watchedKeySequencesList; +}; + +/** + * This class keeps track of the characters that are typed. It is used in + * conjunction with a KTextEditor view and a KileEditorKeySequence::Manager. + **/ +class Recorder : public QObject { + Q_OBJECT +public: + Recorder(KTextEditor::View *view, Manager *manager); + virtual ~Recorder(); + +Q_SIGNALS: + /** + * Emitted whenever a key sequence that is currently watched has + * been typed. + **/ + void detectedTypedKeySequence(const QString& seq); + + +public Q_SLOTS: + /** + * Reloads the key sequences that this recorders watches. + **/ + void reloadWatchedKeySequences(); + +protected: + Manager *m_manager; + QString m_typedSequence; + int m_maxSequenceLength; + int m_oldCol, m_oldLine; + KTextEditor::View* m_view; + QStringList m_watchedKeySequencesList; + + virtual bool eventFilter(QObject *o, QEvent *e); + + /** + * Checks whether a key sequence is currently watched. + * @param s the key sequence that should be checked + **/ + bool seekForKeySequence(const QString& s); +}; } #endif diff --git a/src/errorhandler.cpp b/src/errorhandler.cpp index ce7dbddd..f650a1bf 100644 --- a/src/errorhandler.cpp +++ b/src/errorhandler.cpp @@ -1,575 +1,575 @@ /************************************************************************* Copyright (C) 2003 by Jeroen Wijnhout (Jeroen.Wijnhout@kdemail.net) 2008-2016 by Michel Ludwig (michel.ludwig@kdemail.net) *************************************************************************/ /*************************************************************************** * * * 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. * * * ***************************************************************************/ #include "errorhandler.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "kiledocmanager.h" #include "kileinfo.h" #include "kileproject.h" #include "kiletool_enums.h" #include "kileviewmanager.h" #include "outputinfo.h" #include "utilities.h" #include "widgets/logwidget.h" #include "widgets/outputview.h" #include "widgets/sidebar.h" KileErrorHandler::KileErrorHandler(QObject *parent, KileInfo *info, KActionCollection *ac) - : QObject(parent), m_ki(info), m_errorHanderToolBar(Q_NULLPTR), m_currentLaTeXOutputHandler(Q_NULLPTR) -{ - setObjectName("ErrorHandler"); - - createActions(ac); - setOutputActionsEnabled(false); - - m_compilationResultLabel = new QLabel(); - - m_mainLogWidget = new KileWidget::LogWidget(); - m_mainLogWidget->setFocusPolicy(Qt::ClickFocus); - m_mainLogWidget->setMinimumHeight(40); - - connect(m_mainLogWidget, SIGNAL(outputInfoSelected(const OutputInfo&)), - this, SLOT(jumpToProblem(const OutputInfo&))); - connect(m_mainLogWidget, SIGNAL(showingErrorMessage(QWidget*)), - this, SIGNAL(showingErrorMessage(QWidget*))); - connect(m_mainLogWidget, SIGNAL(showingErrorMessage(QWidget*)), - this, SLOT(showMessagesOutput())); - m_errorLogWidget = new KileWidget::LogWidget(KileWidget::LogWidget::NoHideActions); - connect(m_errorLogWidget, SIGNAL(outputInfoSelected(const OutputInfo&)), - this, SLOT(jumpToProblem(const OutputInfo&))); - m_warningLogWidget = new KileWidget::LogWidget(KileWidget::LogWidget::NoHideActions); - connect(m_warningLogWidget, SIGNAL(outputInfoSelected(const OutputInfo&)), - this, SLOT(jumpToProblem(const OutputInfo&))); - m_badBoxLogWidget = new KileWidget::LogWidget(KileWidget::LogWidget::NoHideActions); - connect(m_badBoxLogWidget, SIGNAL(outputInfoSelected(const OutputInfo&)), - this, SLOT(jumpToProblem(const OutputInfo&))); - - // FIXME: suggestions for icons: utilities-log-viewer, script-error, dialog-warning - m_outputTabWidget = new QTabWidget(); - m_outputTabWidget->setTabPosition(QTabWidget::South); - m_outputTabWidget->setTabsClosable(false); - m_outputTabWidget->addTab(m_mainLogWidget, i18n("Messages")); - m_outputTabWidget->addTab(m_errorLogWidget, i18n("Errors")); - m_outputTabWidget->addTab(m_warningLogWidget, i18n("Warnings")); - m_outputTabWidget->addTab(m_badBoxLogWidget, i18n("BadBoxes")); - - connect(m_ki->viewManager(), SIGNAL(textViewActivated(KTextEditor::View*)), - this, SLOT(updateCurrentLaTeXOutputHandler())); - connect(m_ki->viewManager(), SIGNAL(textViewClosed(KTextEditor::View*,bool)), - this, SLOT(updateCurrentLaTeXOutputHandler())); - connect(m_ki->docManager(), SIGNAL(documentOpened(KileDocument::TextInfo*)), - this, SLOT(updateCurrentLaTeXOutputHandler())); - connect(m_ki->docManager(), SIGNAL(projectOpened(KileProject*)), - this, SLOT(handleProjectOpened(KileProject*))); - - showMessagesOutput(); + : QObject(parent), m_ki(info), m_errorHanderToolBar(Q_NULLPTR), m_currentLaTeXOutputHandler(Q_NULLPTR) +{ + setObjectName("ErrorHandler"); + + createActions(ac); + setOutputActionsEnabled(false); + + m_compilationResultLabel = new QLabel(); + + m_mainLogWidget = new KileWidget::LogWidget(); + m_mainLogWidget->setFocusPolicy(Qt::ClickFocus); + m_mainLogWidget->setMinimumHeight(40); + + connect(m_mainLogWidget, SIGNAL(outputInfoSelected(const OutputInfo&)), + this, SLOT(jumpToProblem(const OutputInfo&))); + connect(m_mainLogWidget, SIGNAL(showingErrorMessage(QWidget*)), + this, SIGNAL(showingErrorMessage(QWidget*))); + connect(m_mainLogWidget, SIGNAL(showingErrorMessage(QWidget*)), + this, SLOT(showMessagesOutput())); + m_errorLogWidget = new KileWidget::LogWidget(KileWidget::LogWidget::NoHideActions); + connect(m_errorLogWidget, SIGNAL(outputInfoSelected(const OutputInfo&)), + this, SLOT(jumpToProblem(const OutputInfo&))); + m_warningLogWidget = new KileWidget::LogWidget(KileWidget::LogWidget::NoHideActions); + connect(m_warningLogWidget, SIGNAL(outputInfoSelected(const OutputInfo&)), + this, SLOT(jumpToProblem(const OutputInfo&))); + m_badBoxLogWidget = new KileWidget::LogWidget(KileWidget::LogWidget::NoHideActions); + connect(m_badBoxLogWidget, SIGNAL(outputInfoSelected(const OutputInfo&)), + this, SLOT(jumpToProblem(const OutputInfo&))); + + // FIXME: suggestions for icons: utilities-log-viewer, script-error, dialog-warning + m_outputTabWidget = new QTabWidget(); + m_outputTabWidget->setTabPosition(QTabWidget::South); + m_outputTabWidget->setTabsClosable(false); + m_outputTabWidget->addTab(m_mainLogWidget, i18n("Messages")); + m_outputTabWidget->addTab(m_errorLogWidget, i18n("Errors")); + m_outputTabWidget->addTab(m_warningLogWidget, i18n("Warnings")); + m_outputTabWidget->addTab(m_badBoxLogWidget, i18n("BadBoxes")); + + connect(m_ki->viewManager(), SIGNAL(textViewActivated(KTextEditor::View*)), + this, SLOT(updateCurrentLaTeXOutputHandler())); + connect(m_ki->viewManager(), SIGNAL(textViewClosed(KTextEditor::View*,bool)), + this, SLOT(updateCurrentLaTeXOutputHandler())); + connect(m_ki->docManager(), SIGNAL(documentOpened(KileDocument::TextInfo*)), + this, SLOT(updateCurrentLaTeXOutputHandler())); + connect(m_ki->docManager(), SIGNAL(projectOpened(KileProject*)), + this, SLOT(handleProjectOpened(KileProject*))); + + showMessagesOutput(); } KileErrorHandler::~KileErrorHandler() { } void KileErrorHandler::createActions(KActionCollection *ac) { - m_viewLogAction = ac->addAction("ViewLog", this, SLOT(ViewLog())); - m_viewLogAction->setText(i18n("View Log File")); - ac->setDefaultShortcut(m_viewLogAction, QKeySequence(Qt::ALT + Qt::Key_0)); - m_viewLogAction->setIcon(QIcon::fromTheme("viewlog")); + m_viewLogAction = ac->addAction("ViewLog", this, SLOT(ViewLog())); + m_viewLogAction->setText(i18n("View Log File")); + ac->setDefaultShortcut(m_viewLogAction, QKeySequence(Qt::ALT + Qt::Key_0)); + m_viewLogAction->setIcon(QIcon::fromTheme("viewlog")); - m_previousErrorAction = ac->addAction("PreviousError", this, SLOT(PreviousError())); - m_previousErrorAction->setText(i18n("Previous LaTeX Error")); - m_previousErrorAction->setIcon(QIcon::fromTheme("errorprev")); + m_previousErrorAction = ac->addAction("PreviousError", this, SLOT(PreviousError())); + m_previousErrorAction->setText(i18n("Previous LaTeX Error")); + m_previousErrorAction->setIcon(QIcon::fromTheme("errorprev")); - m_nextErrorAction = ac->addAction("NextError", this, SLOT(NextError())); - m_nextErrorAction->setText(i18n("Next LaTeX Error")); - m_nextErrorAction->setIcon(QIcon::fromTheme("errornext")); + m_nextErrorAction = ac->addAction("NextError", this, SLOT(NextError())); + m_nextErrorAction->setText(i18n("Next LaTeX Error")); + m_nextErrorAction->setIcon(QIcon::fromTheme("errornext")); - m_previousWarningAction = ac->addAction("PreviousWarning", this, SLOT(PreviousWarning())); - m_previousWarningAction->setText(i18n("Previous LaTeX Warning")); - m_previousWarningAction->setIcon(QIcon::fromTheme("warnprev")); + m_previousWarningAction = ac->addAction("PreviousWarning", this, SLOT(PreviousWarning())); + m_previousWarningAction->setText(i18n("Previous LaTeX Warning")); + m_previousWarningAction->setIcon(QIcon::fromTheme("warnprev")); - m_nextWarningAction = ac->addAction("NextWarning", this, SLOT(NextWarning())); - m_nextWarningAction->setText(i18n("Next LaTeX Warnings")); - m_nextWarningAction->setIcon(QIcon::fromTheme("warnnext")); + m_nextWarningAction = ac->addAction("NextWarning", this, SLOT(NextWarning())); + m_nextWarningAction->setText(i18n("Next LaTeX Warnings")); + m_nextWarningAction->setIcon(QIcon::fromTheme("warnnext")); - m_previousBadBoxAction = ac->addAction("PreviousBadBox", this, SLOT(PreviousBadBox())); - m_previousBadBoxAction->setText(i18n("Previous LaTeX BadBox")); - m_previousBadBoxAction->setIcon(QIcon::fromTheme("bboxprev")); + m_previousBadBoxAction = ac->addAction("PreviousBadBox", this, SLOT(PreviousBadBox())); + m_previousBadBoxAction->setText(i18n("Previous LaTeX BadBox")); + m_previousBadBoxAction->setIcon(QIcon::fromTheme("bboxprev")); - m_nextBadBoxAction = ac->addAction("NextBadBox", this, SLOT(NextBadBox())); - m_nextBadBoxAction->setText(i18n("Next LaTeX BadBox")); - m_nextBadBoxAction->setIcon(QIcon::fromTheme("bboxnext")); + m_nextBadBoxAction = ac->addAction("NextBadBox", this, SLOT(NextBadBox())); + m_nextBadBoxAction->setText(i18n("Next LaTeX BadBox")); + m_nextBadBoxAction->setIcon(QIcon::fromTheme("bboxnext")); } void KileErrorHandler::setErrorHandlerToolBar(QToolBar *toolBar) { - m_errorHanderToolBar = toolBar; - toolBar->addAction(m_viewLogAction); - toolBar->addAction(m_previousErrorAction); - toolBar->addAction(m_nextErrorAction); - toolBar->addAction(m_previousWarningAction); - toolBar->addAction(m_nextWarningAction); - toolBar->addAction(m_previousBadBoxAction); - toolBar->addAction(m_nextBadBoxAction); + m_errorHanderToolBar = toolBar; + toolBar->addAction(m_viewLogAction); + toolBar->addAction(m_previousErrorAction); + toolBar->addAction(m_nextErrorAction); + toolBar->addAction(m_previousWarningAction); + toolBar->addAction(m_nextWarningAction); + toolBar->addAction(m_previousBadBoxAction); + toolBar->addAction(m_nextBadBoxAction); } void KileErrorHandler::setOutputActionsEnabled(bool b) { - m_viewLogAction->setEnabled(b); - m_previousErrorAction->setEnabled(b); - m_nextErrorAction->setEnabled(b); - m_previousWarningAction->setEnabled(b); - m_nextWarningAction->setEnabled(b); - m_previousBadBoxAction->setEnabled(b); - m_nextBadBoxAction->setEnabled(b); + m_viewLogAction->setEnabled(b); + m_previousErrorAction->setEnabled(b); + m_nextErrorAction->setEnabled(b); + m_previousWarningAction->setEnabled(b); + m_nextWarningAction->setEnabled(b); + m_previousBadBoxAction->setEnabled(b); + m_nextBadBoxAction->setEnabled(b); } QLabel* KileErrorHandler::compilationResultLabel() { - return m_compilationResultLabel; + return m_compilationResultLabel; } QWidget* KileErrorHandler::outputWidget() { - return m_outputTabWidget; + return m_outputTabWidget; } bool KileErrorHandler::areMessagesShown() const { - return m_mainLogWidget->isShowingOutput(); + return m_mainLogWidget->isShowingOutput(); } void KileErrorHandler::addEmptyLineToMessages() { - m_mainLogWidget->addEmptyLine(); + m_mainLogWidget->addEmptyLine(); } void KileErrorHandler::startToolLogOutput() { - m_mainLogWidget->startToolLogOutput(); + m_mainLogWidget->startToolLogOutput(); } void KileErrorHandler::endToolLogOutput() { - m_mainLogWidget->endToolLogOutput(); + m_mainLogWidget->endToolLogOutput(); } void KileErrorHandler::printMessage(const QString& message) { - m_mainLogWidget->printMessage(message); + m_mainLogWidget->printMessage(message); } void KileErrorHandler::printMessage(int type, const QString& message, const QString &tool, const OutputInfo& outputInfo, bool allowSelection, bool scroll) { - m_mainLogWidget->printMessage(type, message, tool, outputInfo, allowSelection, scroll); + m_mainLogWidget->printMessage(type, message, tool, outputInfo, allowSelection, scroll); } void KileErrorHandler::printProblem(int type, const QString& problem, const OutputInfo& outputInfo) { - m_mainLogWidget->printProblem(type, problem, outputInfo); + m_mainLogWidget->printProblem(type, problem, outputInfo); } void KileErrorHandler::clearMessages() { - m_mainLogWidget->clear(); + m_mainLogWidget->clear(); } int KileErrorHandler::currentOutputTabIndex() { - return m_outputTabWidget->currentIndex(); + return m_outputTabWidget->currentIndex(); } void KileErrorHandler::setCurrentOutputTab(int i) { - if(i < 0 || i >= m_outputTabWidget->count()) { - return; - } - m_outputTabWidget->setCurrentIndex(i); + if(i < 0 || i >= m_outputTabWidget->count()) { + return; + } + m_outputTabWidget->setCurrentIndex(i); } void KileErrorHandler::showMessagesOutput() { - m_outputTabWidget->setCurrentWidget(m_mainLogWidget); + m_outputTabWidget->setCurrentWidget(m_mainLogWidget); } void KileErrorHandler::showErrorsOutput() { - m_outputTabWidget->setCurrentWidget(m_errorLogWidget); + m_outputTabWidget->setCurrentWidget(m_errorLogWidget); } void KileErrorHandler::showWarningsOutput() { - m_outputTabWidget->setCurrentWidget(m_warningLogWidget); + m_outputTabWidget->setCurrentWidget(m_warningLogWidget); } void KileErrorHandler::showBadBoxesOutput() { - m_outputTabWidget->setCurrentWidget(m_badBoxLogWidget); + m_outputTabWidget->setCurrentWidget(m_badBoxLogWidget); } void KileErrorHandler::handleProjectOpened(KileProject *project) { - connect(project, SIGNAL(aboutToBeDestroyed(KileProject*)), - this, SLOT(updateCurrentLaTeXOutputHandler()), - Qt::UniqueConnection); - connect(project, SIGNAL(projectItemAdded(KileProject*,KileProjectItem*)), - this, SLOT(updateCurrentLaTeXOutputHandler()), - Qt::UniqueConnection); - connect(project, SIGNAL(projectItemRemoved(KileProject*,KileProjectItem*)), - this, SLOT(updateCurrentLaTeXOutputHandler()), - Qt::UniqueConnection); + connect(project, SIGNAL(aboutToBeDestroyed(KileProject*)), + this, SLOT(updateCurrentLaTeXOutputHandler()), + Qt::UniqueConnection); + connect(project, SIGNAL(projectItemAdded(KileProject*,KileProjectItem*)), + this, SLOT(updateCurrentLaTeXOutputHandler()), + Qt::UniqueConnection); + connect(project, SIGNAL(projectItemRemoved(KileProject*,KileProjectItem*)), + this, SLOT(updateCurrentLaTeXOutputHandler()), + Qt::UniqueConnection); } void KileErrorHandler::handleLaTeXToolDone(KileTool::Base *tool, int i, bool childToolSpawned) { - Q_UNUSED(i); + Q_UNUSED(i); - KileTool::LaTeX *latex = dynamic_cast(tool); - if(!latex) { - return; - } - if(childToolSpawned) { - return; - } - if(latex->latexOutputHandler() == m_currentLaTeXOutputHandler) { - updateForCompilationResult(); - } + KileTool::LaTeX *latex = dynamic_cast(tool); + if(!latex) { + return; + } + if(childToolSpawned) { + return; + } + if(latex->latexOutputHandler() == m_currentLaTeXOutputHandler) { + updateForCompilationResult(); + } } void KileErrorHandler::handleSpawnedChildTool(KileTool::Base *parent, KileTool::Base *child) { - if(!dynamic_cast(parent) || !dynamic_cast(child)) { - return; - } + if(!dynamic_cast(parent) || !dynamic_cast(child)) { + return; + } - connect(child, SIGNAL(done(KileTool::Base*, int, bool)), - this, SLOT(handleLaTeXToolDone(KileTool::Base*, int, bool))); + connect(child, SIGNAL(done(KileTool::Base*, int, bool)), + this, SLOT(handleLaTeXToolDone(KileTool::Base*, int, bool))); } void KileErrorHandler::updateCurrentLaTeXOutputHandler() { - LaTeXOutputHandler *h = Q_NULLPTR; - m_ki->getCompileName(false, &h); - if(h == m_currentLaTeXOutputHandler) { - return; - } - m_currentLaTeXOutputHandler = h; + LaTeXOutputHandler *h = Q_NULLPTR; + m_ki->getCompileName(false, &h); + if(h == m_currentLaTeXOutputHandler) { + return; + } + m_currentLaTeXOutputHandler = h; - if(!m_currentLaTeXOutputHandler) { - setOutputActionsEnabled(false); - clearErrorOutput(); - } - else { - setOutputActionsEnabled(true); - updateForCompilationResult(); - } - emit(currentLaTeXOutputHandlerChanged(m_currentLaTeXOutputHandler)); + if(!m_currentLaTeXOutputHandler) { + setOutputActionsEnabled(false); + clearErrorOutput(); + } + else { + setOutputActionsEnabled(true); + updateForCompilationResult(); + } + emit(currentLaTeXOutputHandlerChanged(m_currentLaTeXOutputHandler)); } void KileErrorHandler::updateForCompilationResult() { - if(!m_currentLaTeXOutputHandler) { - return; - } - m_errorLogWidget->clear(); - displayProblemsInLogWidget(m_errorLogWidget, m_currentLaTeXOutputHandler->outputList(), KileErrorHandler::OnlyErrors); - m_warningLogWidget->clear(); - displayProblemsInLogWidget(m_warningLogWidget, m_currentLaTeXOutputHandler->outputList(), KileErrorHandler::OnlyWarnings); - m_badBoxLogWidget->clear(); - displayProblemsInLogWidget(m_badBoxLogWidget, m_currentLaTeXOutputHandler->outputList(), KileErrorHandler::OnlyBadBoxes); - - const int nErrors = m_currentLaTeXOutputHandler->numberOfErrors(); - const int nWarnings = m_currentLaTeXOutputHandler->numberOfWarnings(); - const int nBadBoxes = m_currentLaTeXOutputHandler->numberOfBadBoxes(); - QString errorString, warningString, badBoxString; - - if(nErrors >= 0) { - errorString = i18n("Errors: %1", nErrors); - } - if(nWarnings >= 0) { - warningString = i18n("Warnings: %1", nWarnings); - } - if(nBadBoxes >= 0) { - badBoxString = i18n("BadBoxes: %1", nBadBoxes); - } - - m_compilationResultLabel->setText(i18nc("Result of the compilation w.r.t. number of errors/warnings/badboxes", - "%1 %2 %3", errorString, warningString, badBoxString)); + if(!m_currentLaTeXOutputHandler) { + return; + } + m_errorLogWidget->clear(); + displayProblemsInLogWidget(m_errorLogWidget, m_currentLaTeXOutputHandler->outputList(), KileErrorHandler::OnlyErrors); + m_warningLogWidget->clear(); + displayProblemsInLogWidget(m_warningLogWidget, m_currentLaTeXOutputHandler->outputList(), KileErrorHandler::OnlyWarnings); + m_badBoxLogWidget->clear(); + displayProblemsInLogWidget(m_badBoxLogWidget, m_currentLaTeXOutputHandler->outputList(), KileErrorHandler::OnlyBadBoxes); + + const int nErrors = m_currentLaTeXOutputHandler->numberOfErrors(); + const int nWarnings = m_currentLaTeXOutputHandler->numberOfWarnings(); + const int nBadBoxes = m_currentLaTeXOutputHandler->numberOfBadBoxes(); + QString errorString, warningString, badBoxString; + + if(nErrors >= 0) { + errorString = i18n("Errors: %1", nErrors); + } + if(nWarnings >= 0) { + warningString = i18n("Warnings: %1", nWarnings); + } + if(nBadBoxes >= 0) { + badBoxString = i18n("BadBoxes: %1", nBadBoxes); + } + + m_compilationResultLabel->setText(i18nc("Result of the compilation w.r.t. number of errors/warnings/badboxes", + "%1 %2 %3", errorString, warningString, badBoxString)); } void KileErrorHandler::clearErrorOutput() { - m_compilationResultLabel->clear(); - m_errorLogWidget->clear(); - m_warningLogWidget->clear(); - m_badBoxLogWidget->clear(); + m_compilationResultLabel->clear(); + m_errorLogWidget->clear(); + m_warningLogWidget->clear(); + m_badBoxLogWidget->clear(); } void KileErrorHandler::setMostRecentLogInformation(const QString& logFile, const LatexOutputInfoArray& outputInfoList) { - Q_UNUSED(logFile); + Q_UNUSED(logFile); - // add them to the log widget - displayProblemsInMainLogWidget(outputInfoList); + // add them to the log widget + displayProblemsInMainLogWidget(outputInfoList); } void KileErrorHandler::displayProblemsInMainLogWidget(const LatexOutputInfoArray& infoList) { - displayProblemsInLogWidget(m_mainLogWidget, infoList); + displayProblemsInLogWidget(m_mainLogWidget, infoList); } void KileErrorHandler::displayProblemsInLogWidget(KileWidget::LogWidget *logWidget, const LatexOutputInfoArray& infoList, ProblemType problemType) { - QString message; - int type = KileTool::Info; - - //print detailed error info - logWidget->setUpdatesEnabled(false); - - for(QList::const_iterator i = infoList.begin(); - i != infoList.end(); ++i) { - - const LatexOutputInfo& info = *i; - message = info.source() + ':' + QString::number(info.sourceLine()) + ':' + info.message(); - switch(info.type()) { - case LatexOutputInfo::itmBadBox: - if(problemType == AllProblems || problemType == OnlyBadBoxes) { - type = KileTool::ProblemBadBox; - } - else { - continue; - } - break; - case LatexOutputInfo::itmError: - if(problemType == AllProblems || problemType == OnlyErrors) { - type = KileTool::ProblemError; - } - else { - continue; - } - break; - case LatexOutputInfo::itmWarning: - if(problemType == AllProblems || problemType == OnlyWarnings) { - type = KileTool::ProblemWarning; - } - else { - continue; - } - break; - default: - type = KileTool::Info; - break; - } - KileWidget::LogWidget::ProblemInformation problem; - problem.type = type; - problem.message = message; - problem.outputInfo = info; - logWidget->printMessage(type, message, QString(), info, false, false); - } - - logWidget->setUpdatesEnabled(true); - logWidget->scrollToBottom(); + QString message; + int type = KileTool::Info; + + //print detailed error info + logWidget->setUpdatesEnabled(false); + + for(QList::const_iterator i = infoList.begin(); + i != infoList.end(); ++i) { + + const LatexOutputInfo& info = *i; + message = info.source() + ':' + QString::number(info.sourceLine()) + ':' + info.message(); + switch(info.type()) { + case LatexOutputInfo::itmBadBox: + if(problemType == AllProblems || problemType == OnlyBadBoxes) { + type = KileTool::ProblemBadBox; + } + else { + continue; + } + break; + case LatexOutputInfo::itmError: + if(problemType == AllProblems || problemType == OnlyErrors) { + type = KileTool::ProblemError; + } + else { + continue; + } + break; + case LatexOutputInfo::itmWarning: + if(problemType == AllProblems || problemType == OnlyWarnings) { + type = KileTool::ProblemWarning; + } + else { + continue; + } + break; + default: + type = KileTool::Info; + break; + } + KileWidget::LogWidget::ProblemInformation problem; + problem.type = type; + problem.message = message; + problem.outputInfo = info; + logWidget->printMessage(type, message, QString(), info, false, false); + } + + logWidget->setUpdatesEnabled(true); + logWidget->scrollToBottom(); } void KileErrorHandler::printNoInformationAvailable() { - m_mainLogWidget->printMessage(i18n("No information about warnings or errors is available.")); + m_mainLogWidget->printMessage(i18n("No information about warnings or errors is available.")); } void KileErrorHandler::ViewLog() { - if(!m_currentLaTeXOutputHandler) { - printNoInformationAvailable(); - return; - } - - const LatexOutputInfoArray& outputInfoList = m_currentLaTeXOutputHandler->outputList(); - - KileWidget::LogWidget *logWidget = m_mainLogWidget; - m_ki->focusLog(); - - QFile logFile(m_currentLaTeXOutputHandler->logFile()); - if(!m_currentLaTeXOutputHandler->logFile().isEmpty() && logFile.open(QIODevice::ReadOnly | QIODevice::Text)) { - QHash hash; - - for(QList::const_iterator i = outputInfoList.begin(); - i != outputInfoList.end(); ++i) { - LatexOutputInfo info = *i; - hash[info.outputLine()] = info; - } - - QTextStream textStream(&logFile); - - for(int lineNumber = 0; !textStream.atEnd(); ++lineNumber) { - int type = -1; - const QString line = textStream.readLine(); - if(hash.find(lineNumber) != hash.end()) { - switch(hash[lineNumber].type()) { - case LatexOutputInfo::itmError: - type = KileTool::Error; - break; - case LatexOutputInfo::itmWarning: - type = KileTool::Warning; - break; - case LatexOutputInfo::itmBadBox: - type = KileTool::ProblemBadBox; - break; - } - } - // don't scroll to the item as this will lead to severely degraded performance - logWidget->printMessage(type, line, QString(), hash[lineNumber], true, false); - } - - logWidget->scrollToBottom(); - } - else { - logWidget->printProblem(KileTool::Error, i18n("Cannot open log file; did you run LaTeX?")); - } + if(!m_currentLaTeXOutputHandler) { + printNoInformationAvailable(); + return; + } + + const LatexOutputInfoArray& outputInfoList = m_currentLaTeXOutputHandler->outputList(); + + KileWidget::LogWidget *logWidget = m_mainLogWidget; + m_ki->focusLog(); + + QFile logFile(m_currentLaTeXOutputHandler->logFile()); + if(!m_currentLaTeXOutputHandler->logFile().isEmpty() && logFile.open(QIODevice::ReadOnly | QIODevice::Text)) { + QHash hash; + + for(QList::const_iterator i = outputInfoList.begin(); + i != outputInfoList.end(); ++i) { + LatexOutputInfo info = *i; + hash[info.outputLine()] = info; + } + + QTextStream textStream(&logFile); + + for(int lineNumber = 0; !textStream.atEnd(); ++lineNumber) { + int type = -1; + const QString line = textStream.readLine(); + if(hash.find(lineNumber) != hash.end()) { + switch(hash[lineNumber].type()) { + case LatexOutputInfo::itmError: + type = KileTool::Error; + break; + case LatexOutputInfo::itmWarning: + type = KileTool::Warning; + break; + case LatexOutputInfo::itmBadBox: + type = KileTool::ProblemBadBox; + break; + } + } + // don't scroll to the item as this will lead to severely degraded performance + logWidget->printMessage(type, line, QString(), hash[lineNumber], true, false); + } + + logWidget->scrollToBottom(); + } + else { + logWidget->printProblem(KileTool::Error, i18n("Cannot open log file; did you run LaTeX?")); + } } void KileErrorHandler::jumpToFirstError() { - if(!m_currentLaTeXOutputHandler) { - printNoInformationAvailable(); - return; - } + if(!m_currentLaTeXOutputHandler) { + printNoInformationAvailable(); + return; + } - const LatexOutputInfoArray& outputInfoList = m_currentLaTeXOutputHandler->outputList(); + const LatexOutputInfoArray& outputInfoList = m_currentLaTeXOutputHandler->outputList(); - int sz = outputInfoList.size(); - for(int i = 0; i < sz; ++i) { - if(outputInfoList[i].type() == LatexOutputInfo::itmError) { - // this has to be before calling 'jumpToProblem' as this might change 'm_currentLaTeXOutputHandler' - m_currentLaTeXOutputHandler->setCurrentError(i); - jumpToProblem(outputInfoList[i]); - break; - } - } + int sz = outputInfoList.size(); + for(int i = 0; i < sz; ++i) { + if(outputInfoList[i].type() == LatexOutputInfo::itmError) { + // this has to be before calling 'jumpToProblem' as this might change 'm_currentLaTeXOutputHandler' + m_currentLaTeXOutputHandler->setCurrentError(i); + jumpToProblem(outputInfoList[i]); + break; + } + } } void KileErrorHandler::jumpToProblem(const OutputInfo& info) { - QString file = m_ki->getFullFromPrettyName(info, info.source()); + QString file = m_ki->getFullFromPrettyName(info, info.source()); - if(!file.isEmpty()) { - m_ki->docManager()->fileOpen(QUrl::fromLocalFile(file)); - int line = (info.sourceLine() > 0) ? (info.sourceLine() - 1) : 0; + if(!file.isEmpty()) { + m_ki->docManager()->fileOpen(QUrl::fromLocalFile(file)); + int line = (info.sourceLine() > 0) ? (info.sourceLine() - 1) : 0; - KTextEditor::Document *doc = m_ki->docManager()->docFor(QUrl::fromLocalFile(file)); - if(doc) { - KTextEditor::View* view = doc->views().first(); - if(view) { - view->setCursorPosition(KTextEditor::Cursor(line, 0)); - } - } - } + KTextEditor::Document *doc = m_ki->docManager()->docFor(QUrl::fromLocalFile(file)); + if(doc) { + KTextEditor::View* view = doc->views().first(); + if(view) { + view->setCursorPosition(KTextEditor::Cursor(line, 0)); + } + } + } } void KileErrorHandler::jumpToProblem(int type, bool forward) { - if(!m_currentLaTeXOutputHandler) { - printNoInformationAvailable(); - return; - } + if(!m_currentLaTeXOutputHandler) { + printNoInformationAvailable(); + return; + } - const LatexOutputInfoArray& outputInfoList = m_currentLaTeXOutputHandler->outputList(); + const LatexOutputInfoArray& outputInfoList = m_currentLaTeXOutputHandler->outputList(); - if (!outputInfoList.isEmpty()) { - int sz = outputInfoList.size(); - int pl = forward ? 1 : -1; - bool found = false; + if (!outputInfoList.isEmpty()) { + int sz = outputInfoList.size(); + int pl = forward ? 1 : -1; + bool found = false; - //look for next problem of requested type - for(int i = 0; i < sz; ++i) { - //always look at the whole outputInfo array, but start - //at the problem adjacent to the current error - //if we go beyond the bounds of the array we use - //a simple "modulo" calculation to get within bounds again - int index = (m_currentLaTeXOutputHandler->currentError() + (i + 1) *pl) % sz; - while(index < 0) { - index += sz; - } + //look for next problem of requested type + for(int i = 0; i < sz; ++i) { + //always look at the whole outputInfo array, but start + //at the problem adjacent to the current error + //if we go beyond the bounds of the array we use + //a simple "modulo" calculation to get within bounds again + int index = (m_currentLaTeXOutputHandler->currentError() + (i + 1) *pl) % sz; + while(index < 0) { + index += sz; + } - if(outputInfoList[index].type() == type) { - m_currentLaTeXOutputHandler->setCurrentError(index); - found = true; - break; - } - } + if(outputInfoList[index].type() == type) { + m_currentLaTeXOutputHandler->setCurrentError(index); + found = true; + break; + } + } - if(!found) { - return; - } + if(!found) { + return; + } - //If the log file is being viewed, use this to jump to the errors, - //otherwise, use the error summary display - m_mainLogWidget->highlight(outputInfoList[m_currentLaTeXOutputHandler->currentError()]); + //If the log file is being viewed, use this to jump to the errors, + //otherwise, use the error summary display + m_mainLogWidget->highlight(outputInfoList[m_currentLaTeXOutputHandler->currentError()]); - jumpToProblem(outputInfoList[m_currentLaTeXOutputHandler->currentError()]); - } + jumpToProblem(outputInfoList[m_currentLaTeXOutputHandler->currentError()]); + } - if(outputInfoList.isEmpty()) { - m_mainLogWidget->printMessage(i18n("No LaTeX warnings/errors detected.")); - } + if(outputInfoList.isEmpty()) { + m_mainLogWidget->printMessage(i18n("No LaTeX warnings/errors detected.")); + } } void KileErrorHandler::NextError() { - jumpToProblem(LatexOutputInfo::itmError, true); + jumpToProblem(LatexOutputInfo::itmError, true); } void KileErrorHandler::PreviousError() { - jumpToProblem(LatexOutputInfo::itmError, false); + jumpToProblem(LatexOutputInfo::itmError, false); } void KileErrorHandler::NextWarning() { - jumpToProblem(LatexOutputInfo::itmWarning, true); + jumpToProblem(LatexOutputInfo::itmWarning, true); } void KileErrorHandler::PreviousWarning() { - jumpToProblem(LatexOutputInfo::itmWarning, false); + jumpToProblem(LatexOutputInfo::itmWarning, false); } void KileErrorHandler::NextBadBox() { - jumpToProblem(LatexOutputInfo::itmBadBox, true); + jumpToProblem(LatexOutputInfo::itmBadBox, true); } void KileErrorHandler::PreviousBadBox() { - jumpToProblem(LatexOutputInfo::itmBadBox, false); + jumpToProblem(LatexOutputInfo::itmBadBox, false); } diff --git a/src/errorhandler.h b/src/errorhandler.h index 84618b66..0d123934 100644 --- a/src/errorhandler.h +++ b/src/errorhandler.h @@ -1,131 +1,135 @@ /*************************************************************************** Copyright (C) 2003 by Jeroen Wijnhout (Jeroen.Wijnhout@kdemail.net) 2011-2016 by Michel Ludwig (michel.ludwig@kdemail.net) ***************************************************************************/ /*************************************************************************** * * * 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. * * * ***************************************************************************/ #ifndef ERRORHANDLER_H #define ERRORHANDLER_H #include #include #include "outputinfo.h" class QLabel; class QTabWidget; class QToolBar; class QToolButton; class QAction; class KActionCollection; class KileInfo; class KileProject; class LaTeXOutputHandler; class OutputInfo; -namespace KileTool { class Base; } -namespace KileWidget { class LogWidget; } +namespace KileTool { +class Base; +} +namespace KileWidget { +class LogWidget; +} class KileErrorHandler : public QObject { - Q_OBJECT + Q_OBJECT public: - KileErrorHandler(QObject *parent, KileInfo *info, KActionCollection *ac); + KileErrorHandler(QObject *parent, KileInfo *info, KActionCollection *ac); - ~KileErrorHandler(); + ~KileErrorHandler(); - QLabel* compilationResultLabel(); + QLabel* compilationResultLabel(); - QWidget* outputWidget(); + QWidget* outputWidget(); - void setErrorHandlerToolBar(QToolBar *toolBar); + void setErrorHandlerToolBar(QToolBar *toolBar); - void setMostRecentLogInformation(const QString& logFile, const LatexOutputInfoArray& outputInfoList); + void setMostRecentLogInformation(const QString& logFile, const LatexOutputInfoArray& outputInfoList); - enum ProblemType { AllProblems = 0, OnlyErrors, OnlyWarnings, OnlyBadBoxes }; + enum ProblemType { AllProblems = 0, OnlyErrors, OnlyWarnings, OnlyBadBoxes }; - void displayProblemsInLogWidget(KileWidget::LogWidget *logWidget, const LatexOutputInfoArray& infoList, ProblemType problemType = AllProblems); + void displayProblemsInLogWidget(KileWidget::LogWidget *logWidget, const LatexOutputInfoArray& infoList, ProblemType problemType = AllProblems); - bool areMessagesShown() const; - void addEmptyLineToMessages(); + bool areMessagesShown() const; + void addEmptyLineToMessages(); - void startToolLogOutput(); - void endToolLogOutput(); + void startToolLogOutput(); + void endToolLogOutput(); Q_SIGNALS: - void showingErrorMessage(QWidget *w); - void currentLaTeXOutputHandlerChanged(LaTeXOutputHandler *outputHandler); + void showingErrorMessage(QWidget *w); + void currentLaTeXOutputHandlerChanged(LaTeXOutputHandler *outputHandler); public Q_SLOTS: - void handleSpawnedChildTool(KileTool::Base *parent, KileTool::Base *child); - void handleLaTeXToolDone(KileTool::Base*, int, bool childToolSpawned); + void handleSpawnedChildTool(KileTool::Base *parent, KileTool::Base *child); + void handleLaTeXToolDone(KileTool::Base*, int, bool childToolSpawned); - void printMessage(const QString& message); - void printMessage(int type, const QString& message, const QString &tool = "Kile", - const OutputInfo& outputInfo = OutputInfo(), bool allowSelection = false, - bool scroll = true); - void printProblem(int type, const QString& problem, const OutputInfo& outputInfo = OutputInfo()); - void clearMessages(); + void printMessage(const QString& message); + void printMessage(int type, const QString& message, const QString &tool = "Kile", + const OutputInfo& outputInfo = OutputInfo(), bool allowSelection = false, + bool scroll = true); + void printProblem(int type, const QString& problem, const OutputInfo& outputInfo = OutputInfo()); + void clearMessages(); - void jumpToFirstError(); - void jumpToProblem(const OutputInfo& info); + void jumpToFirstError(); + void jumpToProblem(const OutputInfo& info); - int currentOutputTabIndex(); - void setCurrentOutputTab(int i); + int currentOutputTabIndex(); + void setCurrentOutputTab(int i); - void showMessagesOutput(); - void showErrorsOutput(); - void showWarningsOutput(); - void showBadBoxesOutput(); + void showMessagesOutput(); + void showErrorsOutput(); + void showWarningsOutput(); + void showBadBoxesOutput(); - void clearErrorOutput(); + void clearErrorOutput(); -/* log view, error handling */ + /* log view, error handling */ private Q_SLOTS: - void ViewLog(); - void NextError(); - void PreviousError(); - void NextWarning(); - void PreviousWarning(); - void NextBadBox(); - void PreviousBadBox(); + void ViewLog(); + void NextError(); + void PreviousError(); + void NextWarning(); + void PreviousWarning(); + void NextBadBox(); + void PreviousBadBox(); - void setOutputActionsEnabled(bool b); + void setOutputActionsEnabled(bool b); - void handleProjectOpened(KileProject *project); - void updateCurrentLaTeXOutputHandler(); - void updateForCompilationResult(); + void handleProjectOpened(KileProject *project); + void updateCurrentLaTeXOutputHandler(); + void updateForCompilationResult(); private: - KileInfo *m_ki; - QToolBar *m_errorHanderToolBar; - int m_currentOutputType; - LaTeXOutputHandler *m_currentLaTeXOutputHandler; - QPointer m_outputTabWidget; - QPointer m_compilationResultLabel; - QPointer m_mainLogWidget; - QPointer m_errorLogWidget, m_warningLogWidget, m_badBoxLogWidget; - QPointer m_viewLogAction; - QPointer m_previousErrorAction, m_nextErrorAction; - QPointer m_previousWarningAction, m_nextWarningAction; - QPointer m_previousBadBoxAction, m_nextBadBoxAction; - - void createActions(KActionCollection *ac); - void jumpToProblem(int type, bool); - void displayProblemsInMainLogWidget(const LatexOutputInfoArray& infoList); - void printNoInformationAvailable(); + KileInfo *m_ki; + QToolBar *m_errorHanderToolBar; + int m_currentOutputType; + LaTeXOutputHandler *m_currentLaTeXOutputHandler; + QPointer m_outputTabWidget; + QPointer m_compilationResultLabel; + QPointer m_mainLogWidget; + QPointer m_errorLogWidget, m_warningLogWidget, m_badBoxLogWidget; + QPointer m_viewLogAction; + QPointer m_previousErrorAction, m_nextErrorAction; + QPointer m_previousWarningAction, m_nextWarningAction; + QPointer m_previousBadBoxAction, m_nextBadBoxAction; + + void createActions(KActionCollection *ac); + void jumpToProblem(int type, bool); + void displayProblemsInMainLogWidget(const LatexOutputInfoArray& infoList); + void printNoInformationAvailable(); }; #endif diff --git a/src/eventfilter.cpp b/src/eventfilter.cpp index ed4645a9..62dc724e 100644 --- a/src/eventfilter.cpp +++ b/src/eventfilter.cpp @@ -1,255 +1,278 @@ /*********************************************************************************************** Copyright (C) 2004 by Jeroen Wijnhout 2008-2012 by Michel Ludwig (michel.ludwig@kdemail.net) ***********************************************************************************************/ /*************************************************************************** * * * 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. * * * ***************************************************************************/ // 2007-03-17 dani // - select a single LaTeX command with CTRL+MouseDblClick-left // (such a double click on the middle part '\def' of '\abd\def\ghi' // will select only '\def\', not the whole text, as it does now) #include "eventfilter.h" #include #include #include #include #include #include "kiledebug.h" #include "editorextension.h" #include "kileconfig.h" LaTeXEventFilter::LaTeXEventFilter(KTextEditor::View *view, KileDocument::EditorExtension *edit) : QObject(view), m_view(view), m_edit(edit) { - m_modifierKeyInfo = new KModifierKeyInfo(this); - readConfig(); + m_modifierKeyInfo = new KModifierKeyInfo(this); + readConfig(); } void LaTeXEventFilter::readConfig() { - m_bCompleteEnvironment = KileConfig::completeEnvironment(); + m_bCompleteEnvironment = KileConfig::completeEnvironment(); } // querying the caps lock state directly is currrently not supported by Qt bool LaTeXEventFilter::isCapsLockEnabled() { - return m_modifierKeyInfo->isKeyLatched(Qt::Key_CapsLock) - || m_modifierKeyInfo->isKeyLocked(Qt::Key_CapsLock); + return m_modifierKeyInfo->isKeyLatched(Qt::Key_CapsLock) + || m_modifierKeyInfo->isKeyLocked(Qt::Key_CapsLock); } //FIXME: there should be one central place to convert unicode chars to LaTeX; // also see 'EditorExtension::insertLatexFromUnicode'. // KateViewInternal as a child of KTextEditor::View has the focus // This was set with KTextEditor::View::setFocusProxy(viewInternal) bool LaTeXEventFilter::eventFilter(QObject* /* o */, QEvent *e) { - // Handles input method events, i.e. multi-key combinations with international keyboard layouts - if (e->type() == QEvent::InputMethod) { - QInputMethodEvent *ime = static_cast(e); - // Only single chars, please. ime->commitString() holds the non-latex unicode character string - if (ime->commitString().size() == 1) { - // Extract unicode representation: - unsigned short rep = ime->commitString().at(0).unicode(); - KILE_DEBUG_MAIN << "string= "<< ime->commitString().at(0) << " dec= "<< rep; - return m_edit->insertLatexFromUnicode(rep, m_view); - } - } - - if (e->type() == QEvent::KeyPress) { - QKeyEvent *ke = static_cast(e); - switch(ke->key()) - { - case Qt::Key_QuoteDbl: return m_edit->insertDoubleQuotes(m_view); - case Qt::Key_exclamdown: return m_edit->insertSpecialCharacter("!`", m_view); - case Qt::Key_cent: return m_edit->insertSpecialCharacter("\\textcent", m_view, "textcomp"); - case Qt::Key_sterling: return m_edit->insertSpecialCharacter("\\pounds", m_view); - case Qt::Key_currency: return m_edit->insertSpecialCharacter("\\textcurrency", m_view, "textcomp"); - case Qt::Key_yen: return m_edit->insertSpecialCharacter("\\textyen", m_view, "textcomp"); - case Qt::Key_copyright: return m_edit->insertSpecialCharacter("\\copyright", m_view); - case Qt::Key_ordfeminine: return m_edit->insertSpecialCharacter("\\textordfeminine", m_view, "textcomp"); - case Qt::Key_guillemotleft: return m_edit->insertSpecialCharacter("\\guillemotleft", m_view); - case Qt::Key_notsign: return m_edit->insertSpecialCharacter("\\neg", m_view); - case Qt::Key_registered: return m_edit->insertSpecialCharacter("\\textregistered", m_view, "textcomp"); - case Qt::Key_degree: return m_edit->insertSpecialCharacter("^\\circ", m_view); - case Qt::Key_plusminus: return m_edit->insertSpecialCharacter("\\pm", m_view); - case Qt::Key_mu: return m_edit->insertSpecialCharacter("\\mu", m_view); - case Qt::Key_paragraph: return m_edit->insertSpecialCharacter("\\P", m_view); - case Qt::Key_guillemotright: return m_edit->insertSpecialCharacter("\\guillemotright", m_view); - case Qt::Key_onequarter: return m_edit->insertSpecialCharacter("\\textonequarter", m_view, "textcomp"); - case Qt::Key_onehalf: return m_edit->insertSpecialCharacter("\\textonehalf", m_view, "textcomp"); - case Qt::Key_threequarters: return m_edit->insertSpecialCharacter("\\textthreequarter", m_view, "textcomp"); - case Qt::Key_questiondown: return m_edit->insertSpecialCharacter("?`", m_view); - case Qt::Key_multiply: return m_edit->insertSpecialCharacter("\\times", m_view); - case Qt::Key_ssharp: return m_edit->insertSpecialCharacter("\\ss{}", m_view); - case Qt::Key_Agrave: - if (ke->modifiers() == Qt::ShiftModifier || isCapsLockEnabled()) { - return m_edit->insertSpecialCharacter("\\`A", m_view); - } - else return m_edit->insertSpecialCharacter("\\`a", m_view); - case Qt::Key_Aacute: - if (ke->modifiers() == Qt::ShiftModifier || isCapsLockEnabled()) { - return m_edit->insertSpecialCharacter("\\'A", m_view); - } - else return m_edit->insertSpecialCharacter("\\'a", m_view); - case Qt::Key_Acircumflex: - if (ke->modifiers() == Qt::ShiftModifier || isCapsLockEnabled()) { - return m_edit->insertSpecialCharacter("\\^A", m_view); - } - else return m_edit->insertSpecialCharacter("\\^a", m_view); - case Qt::Key_Atilde: - if (ke->modifiers() == Qt::ShiftModifier || isCapsLockEnabled()) { - return m_edit->insertSpecialCharacter("\\~A", m_view); - } - else return m_edit->insertSpecialCharacter("\\~a", m_view); - case Qt::Key_Adiaeresis: - if (ke->modifiers() == Qt::ShiftModifier || isCapsLockEnabled()) { - return m_edit->insertSpecialCharacter("\\\"A", m_view); - } - else return m_edit->insertSpecialCharacter("\\\"a", m_view); - case Qt::Key_Aring: - if (ke->modifiers() == Qt::ShiftModifier || isCapsLockEnabled()) { - return m_edit->insertSpecialCharacter("\\AA", m_view); - } - else return m_edit->insertSpecialCharacter("\\aa", m_view); - case Qt::Key_AE: - if (ke->modifiers() == Qt::ShiftModifier || isCapsLockEnabled()) { - return m_edit->insertSpecialCharacter("\\AE", m_view); - } - else return m_edit->insertSpecialCharacter("\\ae", m_view); - case Qt::Key_Ccedilla: - if (ke->modifiers() == Qt::ShiftModifier || isCapsLockEnabled()) { - return m_edit->insertSpecialCharacter("\\c{C}", m_view); - } - else return m_edit->insertSpecialCharacter("\\c{c}", m_view); - case Qt::Key_Egrave: - if (ke->modifiers() == Qt::ShiftModifier || isCapsLockEnabled()) { - return m_edit->insertSpecialCharacter("\\`E", m_view); - } - else return m_edit->insertSpecialCharacter("\\`e", m_view); - case Qt::Key_Eacute: - if (ke->modifiers() == Qt::ShiftModifier || isCapsLockEnabled()) { - return m_edit->insertSpecialCharacter("\\'E", m_view); - } - else return m_edit->insertSpecialCharacter("\\'e", m_view); - case Qt::Key_Ecircumflex: - if (ke->modifiers() == Qt::ShiftModifier || isCapsLockEnabled()) { - return m_edit->insertSpecialCharacter("\\^E", m_view); - } - else return m_edit->insertSpecialCharacter("\\^e", m_view); - case Qt::Key_Ediaeresis: - if (ke->modifiers() == Qt::ShiftModifier || isCapsLockEnabled()) { - return m_edit->insertSpecialCharacter("\\\"E", m_view); - } - else return m_edit->insertSpecialCharacter("\\\"e", m_view); - case Qt::Key_Igrave: - if (ke->modifiers() == Qt::ShiftModifier || isCapsLockEnabled()) { - return m_edit->insertSpecialCharacter("\\`I", m_view); - } - else return m_edit->insertSpecialCharacter("\\`i", m_view); - case Qt::Key_Iacute: - if (ke->modifiers() == Qt::ShiftModifier || isCapsLockEnabled()) { - return m_edit->insertSpecialCharacter("\\'I", m_view); - } - else return m_edit->insertSpecialCharacter("\\'i", m_view); - case Qt::Key_Icircumflex: - if (ke->modifiers() == Qt::ShiftModifier || isCapsLockEnabled()) { - return m_edit->insertSpecialCharacter("\\^I", m_view); - } - else return m_edit->insertSpecialCharacter("\\^i", m_view); - case Qt::Key_Idiaeresis: - if (ke->modifiers() == Qt::ShiftModifier || isCapsLockEnabled()) { - return m_edit->insertSpecialCharacter("\\\"I", m_view); - } - else return m_edit->insertSpecialCharacter("\\\"i", m_view); - case Qt::Key_Ntilde: - if (ke->modifiers() == Qt::ShiftModifier || isCapsLockEnabled()) { - return m_edit->insertSpecialCharacter("\\~N", m_view); - } - else return m_edit->insertSpecialCharacter("\\~n", m_view); - case Qt::Key_Ograve: - if (ke->modifiers() == Qt::ShiftModifier || isCapsLockEnabled()) { - return m_edit->insertSpecialCharacter("\\`O", m_view); - } - else return m_edit->insertSpecialCharacter("\\`o", m_view); - case Qt::Key_Oacute: - if (ke->modifiers() == Qt::ShiftModifier || isCapsLockEnabled()) { - return m_edit->insertSpecialCharacter("\\'O", m_view); - } - else return m_edit->insertSpecialCharacter("\\'o", m_view); - case Qt::Key_Ocircumflex: - if (ke->modifiers() == Qt::ShiftModifier || isCapsLockEnabled()) { - return m_edit->insertSpecialCharacter("\\^O", m_view); - } - else return m_edit->insertSpecialCharacter("\\^o", m_view); - case Qt::Key_Otilde: - if (ke->modifiers() == Qt::ShiftModifier || isCapsLockEnabled()) { - return m_edit->insertSpecialCharacter("\\~O", m_view); - } - else return m_edit->insertSpecialCharacter("\\~o", m_view); - case Qt::Key_Odiaeresis: - if (ke->modifiers() == Qt::ShiftModifier || isCapsLockEnabled()) { - return m_edit->insertSpecialCharacter("\\\"O", m_view); - } - else return m_edit->insertSpecialCharacter("\\\"o", m_view); - case Qt::Key_Ugrave: - if (ke->modifiers() == Qt::ShiftModifier || isCapsLockEnabled()) { - return m_edit->insertSpecialCharacter("\\`U", m_view); - } - else return m_edit->insertSpecialCharacter("\\`u", m_view); - case Qt::Key_Uacute: - if (ke->modifiers() == Qt::ShiftModifier || isCapsLockEnabled()) { - return m_edit->insertSpecialCharacter("\\'U", m_view); - } - else return m_edit->insertSpecialCharacter("\\'u", m_view); - case Qt::Key_Ucircumflex: - if (ke->modifiers() == Qt::ShiftModifier || isCapsLockEnabled()) { - return m_edit->insertSpecialCharacter("\\^U", m_view); - } - else return m_edit->insertSpecialCharacter("\\^u", m_view); - case Qt::Key_Udiaeresis: - if (ke->modifiers() == Qt::ShiftModifier || isCapsLockEnabled()) { - return m_edit->insertSpecialCharacter("\\\"U", m_view); - } - else return m_edit->insertSpecialCharacter("\\\"u", m_view); - case Qt::Key_Yacute: - if (ke->modifiers() == Qt::ShiftModifier || isCapsLockEnabled()) { - return m_edit->insertSpecialCharacter("\\'Y", m_view); - } - else return m_edit->insertSpecialCharacter("\\'y", m_view); - case Qt::Key_ydiaeresis: - if (ke->modifiers() == Qt::ShiftModifier || isCapsLockEnabled()) { - return m_edit->insertSpecialCharacter("\\\"Y", m_view); - } - else return m_edit->insertSpecialCharacter("\\\"y", m_view); - default: break; - } - - if(m_bCompleteEnvironment && ke->key() == Qt::Key_Return && ke->modifiers() == 0) { - return m_edit->eventInsertEnvironment(m_view); - } - } - - else if(e->type() == QEvent::MouseButtonDblClick) { - QMouseEvent *me = static_cast(e); - if(me->button() == Qt::LeftButton && me->modifiers() & Qt::ControlModifier) { - m_edit->selectWord(KileDocument::EditorExtension::smTex, m_view); - return true; - } - } - - //pass this event on - return false; + // Handles input method events, i.e. multi-key combinations with international keyboard layouts + if (e->type() == QEvent::InputMethod) { + QInputMethodEvent *ime = static_cast(e); + // Only single chars, please. ime->commitString() holds the non-latex unicode character string + if (ime->commitString().size() == 1) { + // Extract unicode representation: + unsigned short rep = ime->commitString().at(0).unicode(); + KILE_DEBUG_MAIN << "string= "<< ime->commitString().at(0) << " dec= "<< rep; + return m_edit->insertLatexFromUnicode(rep, m_view); + } + } + + if (e->type() == QEvent::KeyPress) { + QKeyEvent *ke = static_cast(e); + switch(ke->key()) + { + case Qt::Key_QuoteDbl: + return m_edit->insertDoubleQuotes(m_view); + case Qt::Key_exclamdown: + return m_edit->insertSpecialCharacter("!`", m_view); + case Qt::Key_cent: + return m_edit->insertSpecialCharacter("\\textcent", m_view, "textcomp"); + case Qt::Key_sterling: + return m_edit->insertSpecialCharacter("\\pounds", m_view); + case Qt::Key_currency: + return m_edit->insertSpecialCharacter("\\textcurrency", m_view, "textcomp"); + case Qt::Key_yen: + return m_edit->insertSpecialCharacter("\\textyen", m_view, "textcomp"); + case Qt::Key_copyright: + return m_edit->insertSpecialCharacter("\\copyright", m_view); + case Qt::Key_ordfeminine: + return m_edit->insertSpecialCharacter("\\textordfeminine", m_view, "textcomp"); + case Qt::Key_guillemotleft: + return m_edit->insertSpecialCharacter("\\guillemotleft", m_view); + case Qt::Key_notsign: + return m_edit->insertSpecialCharacter("\\neg", m_view); + case Qt::Key_registered: + return m_edit->insertSpecialCharacter("\\textregistered", m_view, "textcomp"); + case Qt::Key_degree: + return m_edit->insertSpecialCharacter("^\\circ", m_view); + case Qt::Key_plusminus: + return m_edit->insertSpecialCharacter("\\pm", m_view); + case Qt::Key_mu: + return m_edit->insertSpecialCharacter("\\mu", m_view); + case Qt::Key_paragraph: + return m_edit->insertSpecialCharacter("\\P", m_view); + case Qt::Key_guillemotright: + return m_edit->insertSpecialCharacter("\\guillemotright", m_view); + case Qt::Key_onequarter: + return m_edit->insertSpecialCharacter("\\textonequarter", m_view, "textcomp"); + case Qt::Key_onehalf: + return m_edit->insertSpecialCharacter("\\textonehalf", m_view, "textcomp"); + case Qt::Key_threequarters: + return m_edit->insertSpecialCharacter("\\textthreequarter", m_view, "textcomp"); + case Qt::Key_questiondown: + return m_edit->insertSpecialCharacter("?`", m_view); + case Qt::Key_multiply: + return m_edit->insertSpecialCharacter("\\times", m_view); + case Qt::Key_ssharp: + return m_edit->insertSpecialCharacter("\\ss{}", m_view); + case Qt::Key_Agrave: + if (ke->modifiers() == Qt::ShiftModifier || isCapsLockEnabled()) { + return m_edit->insertSpecialCharacter("\\`A", m_view); + } + else return m_edit->insertSpecialCharacter("\\`a", m_view); + case Qt::Key_Aacute: + if (ke->modifiers() == Qt::ShiftModifier || isCapsLockEnabled()) { + return m_edit->insertSpecialCharacter("\\'A", m_view); + } + else return m_edit->insertSpecialCharacter("\\'a", m_view); + case Qt::Key_Acircumflex: + if (ke->modifiers() == Qt::ShiftModifier || isCapsLockEnabled()) { + return m_edit->insertSpecialCharacter("\\^A", m_view); + } + else return m_edit->insertSpecialCharacter("\\^a", m_view); + case Qt::Key_Atilde: + if (ke->modifiers() == Qt::ShiftModifier || isCapsLockEnabled()) { + return m_edit->insertSpecialCharacter("\\~A", m_view); + } + else return m_edit->insertSpecialCharacter("\\~a", m_view); + case Qt::Key_Adiaeresis: + if (ke->modifiers() == Qt::ShiftModifier || isCapsLockEnabled()) { + return m_edit->insertSpecialCharacter("\\\"A", m_view); + } + else return m_edit->insertSpecialCharacter("\\\"a", m_view); + case Qt::Key_Aring: + if (ke->modifiers() == Qt::ShiftModifier || isCapsLockEnabled()) { + return m_edit->insertSpecialCharacter("\\AA", m_view); + } + else return m_edit->insertSpecialCharacter("\\aa", m_view); + case Qt::Key_AE: + if (ke->modifiers() == Qt::ShiftModifier || isCapsLockEnabled()) { + return m_edit->insertSpecialCharacter("\\AE", m_view); + } + else return m_edit->insertSpecialCharacter("\\ae", m_view); + case Qt::Key_Ccedilla: + if (ke->modifiers() == Qt::ShiftModifier || isCapsLockEnabled()) { + return m_edit->insertSpecialCharacter("\\c{C}", m_view); + } + else return m_edit->insertSpecialCharacter("\\c{c}", m_view); + case Qt::Key_Egrave: + if (ke->modifiers() == Qt::ShiftModifier || isCapsLockEnabled()) { + return m_edit->insertSpecialCharacter("\\`E", m_view); + } + else return m_edit->insertSpecialCharacter("\\`e", m_view); + case Qt::Key_Eacute: + if (ke->modifiers() == Qt::ShiftModifier || isCapsLockEnabled()) { + return m_edit->insertSpecialCharacter("\\'E", m_view); + } + else return m_edit->insertSpecialCharacter("\\'e", m_view); + case Qt::Key_Ecircumflex: + if (ke->modifiers() == Qt::ShiftModifier || isCapsLockEnabled()) { + return m_edit->insertSpecialCharacter("\\^E", m_view); + } + else return m_edit->insertSpecialCharacter("\\^e", m_view); + case Qt::Key_Ediaeresis: + if (ke->modifiers() == Qt::ShiftModifier || isCapsLockEnabled()) { + return m_edit->insertSpecialCharacter("\\\"E", m_view); + } + else return m_edit->insertSpecialCharacter("\\\"e", m_view); + case Qt::Key_Igrave: + if (ke->modifiers() == Qt::ShiftModifier || isCapsLockEnabled()) { + return m_edit->insertSpecialCharacter("\\`I", m_view); + } + else return m_edit->insertSpecialCharacter("\\`i", m_view); + case Qt::Key_Iacute: + if (ke->modifiers() == Qt::ShiftModifier || isCapsLockEnabled()) { + return m_edit->insertSpecialCharacter("\\'I", m_view); + } + else return m_edit->insertSpecialCharacter("\\'i", m_view); + case Qt::Key_Icircumflex: + if (ke->modifiers() == Qt::ShiftModifier || isCapsLockEnabled()) { + return m_edit->insertSpecialCharacter("\\^I", m_view); + } + else return m_edit->insertSpecialCharacter("\\^i", m_view); + case Qt::Key_Idiaeresis: + if (ke->modifiers() == Qt::ShiftModifier || isCapsLockEnabled()) { + return m_edit->insertSpecialCharacter("\\\"I", m_view); + } + else return m_edit->insertSpecialCharacter("\\\"i", m_view); + case Qt::Key_Ntilde: + if (ke->modifiers() == Qt::ShiftModifier || isCapsLockEnabled()) { + return m_edit->insertSpecialCharacter("\\~N", m_view); + } + else return m_edit->insertSpecialCharacter("\\~n", m_view); + case Qt::Key_Ograve: + if (ke->modifiers() == Qt::ShiftModifier || isCapsLockEnabled()) { + return m_edit->insertSpecialCharacter("\\`O", m_view); + } + else return m_edit->insertSpecialCharacter("\\`o", m_view); + case Qt::Key_Oacute: + if (ke->modifiers() == Qt::ShiftModifier || isCapsLockEnabled()) { + return m_edit->insertSpecialCharacter("\\'O", m_view); + } + else return m_edit->insertSpecialCharacter("\\'o", m_view); + case Qt::Key_Ocircumflex: + if (ke->modifiers() == Qt::ShiftModifier || isCapsLockEnabled()) { + return m_edit->insertSpecialCharacter("\\^O", m_view); + } + else return m_edit->insertSpecialCharacter("\\^o", m_view); + case Qt::Key_Otilde: + if (ke->modifiers() == Qt::ShiftModifier || isCapsLockEnabled()) { + return m_edit->insertSpecialCharacter("\\~O", m_view); + } + else return m_edit->insertSpecialCharacter("\\~o", m_view); + case Qt::Key_Odiaeresis: + if (ke->modifiers() == Qt::ShiftModifier || isCapsLockEnabled()) { + return m_edit->insertSpecialCharacter("\\\"O", m_view); + } + else return m_edit->insertSpecialCharacter("\\\"o", m_view); + case Qt::Key_Ugrave: + if (ke->modifiers() == Qt::ShiftModifier || isCapsLockEnabled()) { + return m_edit->insertSpecialCharacter("\\`U", m_view); + } + else return m_edit->insertSpecialCharacter("\\`u", m_view); + case Qt::Key_Uacute: + if (ke->modifiers() == Qt::ShiftModifier || isCapsLockEnabled()) { + return m_edit->insertSpecialCharacter("\\'U", m_view); + } + else return m_edit->insertSpecialCharacter("\\'u", m_view); + case Qt::Key_Ucircumflex: + if (ke->modifiers() == Qt::ShiftModifier || isCapsLockEnabled()) { + return m_edit->insertSpecialCharacter("\\^U", m_view); + } + else return m_edit->insertSpecialCharacter("\\^u", m_view); + case Qt::Key_Udiaeresis: + if (ke->modifiers() == Qt::ShiftModifier || isCapsLockEnabled()) { + return m_edit->insertSpecialCharacter("\\\"U", m_view); + } + else return m_edit->insertSpecialCharacter("\\\"u", m_view); + case Qt::Key_Yacute: + if (ke->modifiers() == Qt::ShiftModifier || isCapsLockEnabled()) { + return m_edit->insertSpecialCharacter("\\'Y", m_view); + } + else return m_edit->insertSpecialCharacter("\\'y", m_view); + case Qt::Key_ydiaeresis: + if (ke->modifiers() == Qt::ShiftModifier || isCapsLockEnabled()) { + return m_edit->insertSpecialCharacter("\\\"Y", m_view); + } + else return m_edit->insertSpecialCharacter("\\\"y", m_view); + default: + break; + } + + if(m_bCompleteEnvironment && ke->key() == Qt::Key_Return && ke->modifiers() == 0) { + return m_edit->eventInsertEnvironment(m_view); + } + } + + else if(e->type() == QEvent::MouseButtonDblClick) { + QMouseEvent *me = static_cast(e); + if(me->button() == Qt::LeftButton && me->modifiers() & Qt::ControlModifier) { + m_edit->selectWord(KileDocument::EditorExtension::smTex, m_view); + return true; + } + } + + //pass this event on + return false; } diff --git a/src/eventfilter.h b/src/eventfilter.h index ce936f2c..3e9814f4 100644 --- a/src/eventfilter.h +++ b/src/eventfilter.h @@ -1,53 +1,57 @@ /*********************************************************************************************** Copyright (C) 2004 by Jeroen Wijnhout 2008-2012 by Michel Ludwig (michel.ludwig@kdemail.net) ***********************************************************************************************/ /*************************************************************************** * * * 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. * * * ***************************************************************************/ #ifndef EVENTFILTER_H #define EVENTFILTER_H #include #include #include class KModifierKeyInfo; -namespace KTextEditor {class View; } -namespace KileDocument { class EditorExtension; } +namespace KTextEditor { +class View; +} +namespace KileDocument { +class EditorExtension; +} /** * This class is capable of intercepting key-strokes from the editor. It can complete a \begin{env} * with a \end{env} when enter is pressed. **/ class LaTeXEventFilter : public QObject { - Q_OBJECT + Q_OBJECT public: - LaTeXEventFilter(KTextEditor::View *view, KileDocument::EditorExtension *edit); + LaTeXEventFilter(KTextEditor::View *view, KileDocument::EditorExtension *edit); public Q_SLOTS: - void readConfig(); + void readConfig(); protected: - bool eventFilter(QObject *o, QEvent *e); - bool isCapsLockEnabled(); + bool eventFilter(QObject *o, QEvent *e); + bool isCapsLockEnabled(); private: - bool m_bCompleteEnvironment; - KTextEditor::View *m_view; - KileDocument::EditorExtension *m_edit; - KModifierKeyInfo *m_modifierKeyInfo; + bool m_bCompleteEnvironment; + KTextEditor::View *m_view; + KileDocument::EditorExtension *m_edit; + KModifierKeyInfo *m_modifierKeyInfo; }; #endif diff --git a/src/kile.cpp b/src/kile.cpp index da992cd5..af886e60 100644 --- a/src/kile.cpp +++ b/src/kile.cpp @@ -1,2946 +1,2954 @@ /**************************************************************************************** Copyright (C) 2003 by Jeroen Wijnhout (Jeroen.Wijnhout@kdemail.net) (C) 2007-2017 by Michel Ludwig (michel.ludwig@kdemail.net) (C) 2007 Holger Danielsson (holger.danielsson@versanet.de) (C) 2009 Thomas Braun (thomas.braun@virtuell-zuhause.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. * * * ***************************************************************************/ // 2007-03-12 dani // - use KileDocument::Extensions #include "kile.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "abbreviationmanager.h" #include "configurationmanager.h" #include "documentinfo.h" #include "errorhandler.h" #include "kileactions.h" #include "kiledebug.h" #include "kilestdactions.h" #include "widgets/statusbar.h" #include "dialogs/configurationdialog.h" #include "kileproject.h" #include "widgets/projectview.h" #include "dialogs/projectdialogs.h" #include "kilelyxserver.h" #include "dialogs/findfilesdialog.h" #include "kiletool_enums.h" #include "kiletool.h" #include "kiletoolmanager.h" #include "kilestdtools.h" #include "widgets/outputview.h" #include "widgets/konsolewidget.h" #include "dialogs/quickdocumentdialog.h" #include "dialogs/tabbingdialog.h" #include "widgets/structurewidget.h" #include "convert.h" #include "dialogs/includegraphicsdialog.h" #include "kiledocmanager.h" #include "kileversion.h" #include "kileviewmanager.h" #include "kileconfig.h" #include "dialogs/configcheckerdialog.h" #include "widgets/sidebar.h" #include "dialogs/floatdialog.h" #include "dialogs/mathenvironmentdialog.h" #include "dialogs/tabular/newtabulardialog.h" #include "dialogs/postscriptdialog.h" #include "dialogs/pdf-wizard/pdfdialog.h" #include "latexcmd.h" #include "mainadaptor.h" #include "dialogs/statisticsdialog.h" #include "widgets/scriptsmanagementwidget.h" #include "scriptmanager.h" #include "widgets/previewwidget.h" #include "symbolviewclasses.h" #include "livepreview.h" #include "parser/parsermanager.h" #include "dialogs/usermenu/usermenudialog.h" #include "usermenu/usermenudata.h" #include "usermenu/usermenu.h" #include "utilities.h" #define LOG_TAB 0 #define OUTPUT_TAB 1 #define KONSOLE_TAB 2 #define PREVIEW_TAB 3 /* * Class Kile. */ Kile::Kile(bool allowRestore, QWidget *parent) - : KParts::MainWindow() - , KileInfo(this) - , m_paPrint(Q_NULLPTR) + : KParts::MainWindow() + , KileInfo(this) + , m_paPrint(Q_NULLPTR) { - setObjectName("Kile"); + setObjectName("Kile"); - // Under some circumstances (Qt or KDE issues like a KIO process still running (?)), Kile doesn't terminate - // when the main window is closed (bugs 220343 and 299569). So, we force this here. - // This still seems to happen with Qt 4.8.1 and KDE 4.8.2. - connect(m_mainWindow, SIGNAL(destroyed(QObject*)), qApp, SLOT(quit())); //FIXME: KF5 is this still necessary? + // Under some circumstances (Qt or KDE issues like a KIO process still running (?)), Kile doesn't terminate + // when the main window is closed (bugs 220343 and 299569). So, we force this here. + // This still seems to happen with Qt 4.8.1 and KDE 4.8.2. + connect(m_mainWindow, SIGNAL(destroyed(QObject*)), qApp, SLOT(quit())); //FIXME: KF5 is this still necessary? - QSplashScreen splashScreen(QPixmap(QStandardPaths::locate(QStandardPaths::DataLocation, "pics/kile_splash.png")), Qt::WindowStaysOnTopHint); - if(KileConfig::showSplashScreen()) { - splashScreen.show(); - qApp->processEvents(); - } - - m_config = KSharedConfig::openConfig(); - - m_codeCompletionManager = new KileCodeCompletion::Manager(this, parent); - - setStandardToolBarMenuEnabled(true); - - m_singlemode = true; - - m_viewManager= new KileView::Manager(this, actionCollection(), parent, "KileView::Manager"); - viewManager()->setClient(this); - - // process events for correctly displaying the splash screen - qApp->processEvents(); - - m_latexCommands = new KileDocument::LatexCommands(m_config.data(), this); // at first (dani) - m_edit = new KileDocument::EditorExtension(this); - m_help = new KileHelp::Help(m_edit, this); - m_errorHandler = new KileErrorHandler(this, this, actionCollection()); - m_quickPreview = new KileTool::QuickPreview(this); - m_extensions = new KileDocument::Extensions(); - m_jScriptManager = new KileScript::Manager(this, m_config.data(), actionCollection(), parent, "KileScript::Manager"); - m_userMenu = Q_NULLPTR; - - // do initializations first - m_bWatchFile = false; - - setStatusBar(new KileWidget::StatusBar(m_errorHandler, parent)); - - // process events for correctly displaying the splash screen - qApp->processEvents(); - - connect(viewManager(), SIGNAL(currentViewChanged(QWidget*)), this, SLOT(newCaption())); - connect(viewManager(), SIGNAL(currentViewChanged(QWidget*)), this, SLOT(activateView(QWidget*))); - connect(viewManager(), SIGNAL(currentViewChanged(QWidget*)), this, SLOT(updateModeStatus())); - connect(viewManager(), SIGNAL(updateCaption()), this, SLOT(newCaption())); - connect(viewManager(), SIGNAL(updateModeStatus()), this, SLOT(updateModeStatus())); - connect(viewManager(), &KileView::Manager::cursorPositionChanged, this, &Kile::updateStatusBarCursorPosition); - connect(viewManager(), SIGNAL(viewModeChanged(KTextEditor::View*, KTextEditor::View::ViewMode)), - this, SLOT(updateStatusBarViewMode(KTextEditor::View*))); - connect(viewManager(), SIGNAL(informationMessage(KTextEditor::View*,const QString&)), - this, SLOT(updateStatusBarInformationMessage(KTextEditor::View*,const QString&))); - connect(viewManager(), SIGNAL(selectionChanged(KTextEditor::View*)), - this, SLOT(updateStatusBarSelection(KTextEditor::View*))); - - connect(docManager(), SIGNAL(documentNameChanged(KTextEditor::Document*)), this, SLOT(newCaption())); - connect(docManager(), SIGNAL(documentUrlChanged(KTextEditor::Document*)), this, SLOT(newCaption())); - connect(docManager(), SIGNAL(documentReadWriteStateChanged(KTextEditor::Document*)), this, SLOT(newCaption())); - - m_topWidgetStack = new QStackedWidget(); - m_topWidgetStack->setFocusPolicy(Qt::NoFocus); + QSplashScreen splashScreen(QPixmap(QStandardPaths::locate(QStandardPaths::DataLocation, "pics/kile_splash.png")), Qt::WindowStaysOnTopHint); + if(KileConfig::showSplashScreen()) { + splashScreen.show(); + qApp->processEvents(); + } - m_horizontalSplitter = new QSplitter(Qt::Horizontal); + m_config = KSharedConfig::openConfig(); - setupSideBar(); - m_horizontalSplitter->addWidget(m_sideBar); + m_codeCompletionManager = new KileCodeCompletion::Manager(this, parent); - m_verticalSplitter = new QSplitter(Qt::Vertical); - m_horizontalSplitter->addWidget(m_verticalSplitter); - viewManager()->createTabs(m_verticalSplitter); + setStandardToolBarMenuEnabled(true); - connect(viewManager(), SIGNAL(activateView(QWidget*, bool)), this, SLOT(activateView(QWidget*, bool))); - connect(viewManager(), SIGNAL(startQuickPreview(int)), this, SLOT(slotQuickPreview(int)) ); + m_singlemode = true; - connect(parserManager(), SIGNAL(documentParsingStarted()), this, SLOT(handleDocumentParsingStarted())); - connect(parserManager(), SIGNAL(documentParsingComplete()), this, SLOT(handleDocumentParsingComplete())); + m_viewManager= new KileView::Manager(this, actionCollection(), parent, "KileView::Manager"); + viewManager()->setClient(this); - m_signalMapper = new QSignalMapper(this); - connect(m_signalMapper, SIGNAL(mapped(const QString &)), - this, SLOT(runTool(const QString &))); + // process events for correctly displaying the splash screen + qApp->processEvents(); - // process events for correctly displaying the splash screen - qApp->processEvents(); + m_latexCommands = new KileDocument::LatexCommands(m_config.data(), this); // at first (dani) + m_edit = new KileDocument::EditorExtension(this); + m_help = new KileHelp::Help(m_edit, this); + m_errorHandler = new KileErrorHandler(this, this, actionCollection()); + m_quickPreview = new KileTool::QuickPreview(this); + m_extensions = new KileDocument::Extensions(); + m_jScriptManager = new KileScript::Manager(this, m_config.data(), actionCollection(), parent, "KileScript::Manager"); + m_userMenu = Q_NULLPTR; - setupBottomBar(); - m_verticalSplitter->addWidget(m_bottomBar); - m_topWidgetStack->addWidget(m_horizontalSplitter); - setCentralWidget(m_topWidgetStack); + // do initializations first + m_bWatchFile = false; - setupGraphicTools(); - setupPreviewTools(); - setupActions(); // sets up m_paStop + setStatusBar(new KileWidget::StatusBar(m_errorHandler, parent)); - // Parser manager and view manager must be created before the tool manager! - m_manager = new KileTool::Manager(this, m_config.data(), m_outputWidget, m_topWidgetStack, m_paStop, 10000, actionCollection()); //FIXME make timeout configurable - connect(m_manager, SIGNAL(jumpToFirstError()), m_errorHandler, SLOT(jumpToFirstError())); - connect(m_manager, SIGNAL(previewDone()), this, SLOT(focusPreview())); + // process events for correctly displaying the splash screen + qApp->processEvents(); - if(viewManager()->viewerPart()) { - m_bottomBar->addExtraWidget(viewManager()->getViewerControlToolBar()); - } + connect(viewManager(), SIGNAL(currentViewChanged(QWidget*)), this, SLOT(newCaption())); + connect(viewManager(), SIGNAL(currentViewChanged(QWidget*)), this, SLOT(activateView(QWidget*))); + connect(viewManager(), SIGNAL(currentViewChanged(QWidget*)), this, SLOT(updateModeStatus())); + connect(viewManager(), SIGNAL(updateCaption()), this, SLOT(newCaption())); + connect(viewManager(), SIGNAL(updateModeStatus()), this, SLOT(updateModeStatus())); + connect(viewManager(), &KileView::Manager::cursorPositionChanged, this, &Kile::updateStatusBarCursorPosition); + connect(viewManager(), SIGNAL(viewModeChanged(KTextEditor::View*, KTextEditor::View::ViewMode)), + this, SLOT(updateStatusBarViewMode(KTextEditor::View*))); + connect(viewManager(), SIGNAL(informationMessage(KTextEditor::View*,const QString&)), + this, SLOT(updateStatusBarInformationMessage(KTextEditor::View*,const QString&))); + connect(viewManager(), SIGNAL(selectionChanged(KTextEditor::View*)), + this, SLOT(updateStatusBarSelection(KTextEditor::View*))); - m_livePreviewManager = new KileTool::LivePreviewManager(this, actionCollection()); - connect(this, &Kile::masterDocumentChanged, m_livePreviewManager, &KileTool::LivePreviewManager::handleMasterDocumentChanged); + connect(docManager(), SIGNAL(documentNameChanged(KTextEditor::Document*)), this, SLOT(newCaption())); + connect(docManager(), SIGNAL(documentUrlChanged(KTextEditor::Document*)), this, SLOT(newCaption())); + connect(docManager(), SIGNAL(documentReadWriteStateChanged(KTextEditor::Document*)), this, SLOT(newCaption())); - if(!viewManager()->viewerPart()) { // live preview part couldn't be created - delete m_livePreviewManager; - m_livePreviewManager = Q_NULLPTR; - } + m_topWidgetStack = new QStackedWidget(); + m_topWidgetStack->setFocusPolicy(Qt::NoFocus); - m_toolFactory = new KileTool::Factory(m_manager, m_config.data(), actionCollection()); - m_manager->setFactory(m_toolFactory); + m_horizontalSplitter = new QSplitter(Qt::Horizontal); - initSelectActions(); + setupSideBar(); + m_horizontalSplitter->addWidget(m_sideBar); - newCaption(); + m_verticalSplitter = new QSplitter(Qt::Vertical); + m_horizontalSplitter->addWidget(m_verticalSplitter); + viewManager()->createTabs(m_verticalSplitter); - m_help->setUserhelp(m_manager, m_userHelpActionMenu); // kile user help (dani) + connect(viewManager(), SIGNAL(activateView(QWidget*, bool)), this, SLOT(activateView(QWidget*, bool))); + connect(viewManager(), SIGNAL(startQuickPreview(int)), this, SLOT(slotQuickPreview(int)) ); - // process events for correctly displaying the splash screen - qApp->processEvents(); + connect(parserManager(), SIGNAL(documentParsingStarted()), this, SLOT(handleDocumentParsingStarted())); + connect(parserManager(), SIGNAL(documentParsingComplete()), this, SLOT(handleDocumentParsingComplete())); - connect(docManager(), SIGNAL(updateModeStatus()), this, SLOT(updateModeStatus())); - connect(docManager(), SIGNAL(updateStructure(bool, KileDocument::Info*)), viewManager(), SLOT(updateStructure(bool, KileDocument::Info*))); - connect(docManager(), SIGNAL(closingDocument(KileDocument::Info* )), m_kwStructure, SLOT(closeDocumentInfo(KileDocument::Info *))); - connect(docManager(), SIGNAL(documentInfoCreated(KileDocument::Info* )), m_kwStructure, SLOT(addDocumentInfo(KileDocument::Info* ))); - connect(docManager(), SIGNAL(updateReferences(KileDocument::Info *)), m_kwStructure, SLOT(updateReferences(KileDocument::Info *))); - connect(docManager(), SIGNAL(documentModificationStatusChanged(KTextEditor::Document*, bool, KTextEditor::ModificationInterface::ModifiedOnDiskReason)), - viewManager(), SLOT(reflectDocumentModificationStatus(KTextEditor::Document*, bool, KTextEditor::ModificationInterface::ModifiedOnDiskReason))); + m_signalMapper = new QSignalMapper(this); + connect(m_signalMapper, SIGNAL(mapped(const QString &)), + this, SLOT(runTool(const QString &))); - if(KileConfig::rCVersion() < 8) { - transformOldUserSettings(); - transformOldUserTags(); + // process events for correctly displaying the splash screen + qApp->processEvents(); - // before Kile 2.1 shortcuts were stored in a "Shortcuts" group inside - // Kile's configuration file, but this led to problems with the way of how shortcuts - // are generally stored in kdelibs; we now delete the "Shortcuts" group if it - // still present in Kile's configuration file. - if(m_config->hasGroup("Shortcuts")) { - KConfigGroup shortcutGroup = m_config->group("Shortcuts"); - actionCollection()->readSettings(&shortcutGroup); - m_config->deleteGroup("Shortcuts"); - } - - if(m_config->hasGroup("Complete")) { - KConfigGroup completionGroup = m_config->group("Complete"); - completionGroup.deleteEntry("maxCwlFiles"); // in Kile 3.0 the UI has been changed so that this setting is no longer - // needed - } - } - readGUISettings(); - readRecentFileSettings(); - readConfig(); + setupBottomBar(); + m_verticalSplitter->addWidget(m_bottomBar); + m_topWidgetStack->addWidget(m_horizontalSplitter); + setCentralWidget(m_topWidgetStack); - createToolActions(); // this creates the actions for the tools and user tags, which is required before 'activePartGUI' is called + setupGraphicTools(); + setupPreviewTools(); + setupActions(); // sets up m_paStop - setupGUI(KXmlGuiWindow::StatusBar | KXmlGuiWindow::Save, "kileui.rc"); - createShellGUI(true); // do not call guiFactory()->refreshActionProperties() after this! (bug 314580) + // Parser manager and view manager must be created before the tool manager! + m_manager = new KileTool::Manager(this, m_config.data(), m_outputWidget, m_topWidgetStack, m_paStop, 10000, actionCollection()); //FIXME make timeout configurable + connect(m_manager, SIGNAL(jumpToFirstError()), m_errorHandler, SLOT(jumpToFirstError())); + connect(m_manager, SIGNAL(previewDone()), this, SLOT(focusPreview())); - m_userMenu = new KileMenu::UserMenu(this, this); - connect(m_userMenu, &KileMenu::UserMenu::sendText, this, static_cast(&Kile::insertText)); - connect(m_userMenu, &KileMenu::UserMenu::updateStatus, this, &Kile::slotUpdateUserMenuStatus); + if(viewManager()->viewerPart()) { + m_bottomBar->addExtraWidget(viewManager()->getViewerControlToolBar()); + } - updateUserDefinedMenus(); + m_livePreviewManager = new KileTool::LivePreviewManager(this, actionCollection()); + connect(this, &Kile::masterDocumentChanged, m_livePreviewManager, &KileTool::LivePreviewManager::handleMasterDocumentChanged); - // we can only do this here after the main GUI has been set up - if(m_livePreviewManager && viewManager()->viewerPart()) { - guiFactory()->addClient(viewManager()->viewerPart()); + if(!viewManager()->viewerPart()) { // live preview part couldn't be created + delete m_livePreviewManager; + m_livePreviewManager = Q_NULLPTR; + } - QMenu *documentViewerMenu = static_cast(guiFactory()->container("menu_document_viewer", this)); - QMenu *popup = static_cast(guiFactory()->container("menu_okular_part_viewer", viewManager()->viewerPart())); - if(documentViewerMenu && popup) { - // we populate our menu with the actions from the part's menu - documentViewerMenu->addActions(popup->actions()); - documentViewerMenu->setEnabled(false); - connect(viewManager()->viewerPart(), SIGNAL(viewerMenuStateChange(bool)), documentViewerMenu, SLOT(setEnabled(bool))); - } - else { - if(documentViewerMenu) { - documentViewerMenu->setVisible(false); - } - delete popup; - } - } - else { // we hide the special document viewer menu - QMenu *documentViewerMenu = static_cast(guiFactory()->container("menu_document_viewer", this)); - if(documentViewerMenu) { - documentViewerMenu->setVisible(false); - } - } + m_toolFactory = new KileTool::Factory(m_manager, m_config.data(), actionCollection()); + m_manager->setFactory(m_toolFactory); + + initSelectActions(); + + newCaption(); + + m_help->setUserhelp(m_manager, m_userHelpActionMenu); // kile user help (dani) + + // process events for correctly displaying the splash screen + qApp->processEvents(); + + connect(docManager(), SIGNAL(updateModeStatus()), this, SLOT(updateModeStatus())); + connect(docManager(), SIGNAL(updateStructure(bool, KileDocument::Info*)), viewManager(), SLOT(updateStructure(bool, KileDocument::Info*))); + connect(docManager(), SIGNAL(closingDocument(KileDocument::Info* )), m_kwStructure, SLOT(closeDocumentInfo(KileDocument::Info *))); + connect(docManager(), SIGNAL(documentInfoCreated(KileDocument::Info* )), m_kwStructure, SLOT(addDocumentInfo(KileDocument::Info* ))); + connect(docManager(), SIGNAL(updateReferences(KileDocument::Info *)), m_kwStructure, SLOT(updateReferences(KileDocument::Info *))); + connect(docManager(), SIGNAL(documentModificationStatusChanged(KTextEditor::Document*, bool, KTextEditor::ModificationInterface::ModifiedOnDiskReason)), + viewManager(), SLOT(reflectDocumentModificationStatus(KTextEditor::Document*, bool, KTextEditor::ModificationInterface::ModifiedOnDiskReason))); + + if(KileConfig::rCVersion() < 8) { + transformOldUserSettings(); + transformOldUserTags(); + + // before Kile 2.1 shortcuts were stored in a "Shortcuts" group inside + // Kile's configuration file, but this led to problems with the way of how shortcuts + // are generally stored in kdelibs; we now delete the "Shortcuts" group if it + // still present in Kile's configuration file. + if(m_config->hasGroup("Shortcuts")) { + KConfigGroup shortcutGroup = m_config->group("Shortcuts"); + actionCollection()->readSettings(&shortcutGroup); + m_config->deleteGroup("Shortcuts"); + } + + if(m_config->hasGroup("Complete")) { + KConfigGroup completionGroup = m_config->group("Complete"); + completionGroup.deleteEntry("maxCwlFiles"); // in Kile 3.0 the UI has been changed so that this setting is no longer + // needed + } + } + readGUISettings(); + readRecentFileSettings(); + readConfig(); + + createToolActions(); // this creates the actions for the tools and user tags, which is required before 'activePartGUI' is called + + setupGUI(KXmlGuiWindow::StatusBar | KXmlGuiWindow::Save, "kileui.rc"); + createShellGUI(true); // do not call guiFactory()->refreshActionProperties() after this! (bug 314580) + + m_userMenu = new KileMenu::UserMenu(this, this); + connect(m_userMenu, &KileMenu::UserMenu::sendText, this, static_cast(&Kile::insertText)); + connect(m_userMenu, &KileMenu::UserMenu::updateStatus, this, &Kile::slotUpdateUserMenuStatus); + + updateUserDefinedMenus(); + + // we can only do this here after the main GUI has been set up + if(m_livePreviewManager && viewManager()->viewerPart()) { + guiFactory()->addClient(viewManager()->viewerPart()); + + QMenu *documentViewerMenu = static_cast(guiFactory()->container("menu_document_viewer", this)); + QMenu *popup = static_cast(guiFactory()->container("menu_okular_part_viewer", viewManager()->viewerPart())); + if(documentViewerMenu && popup) { + // we populate our menu with the actions from the part's menu + documentViewerMenu->addActions(popup->actions()); + documentViewerMenu->setEnabled(false); + connect(viewManager()->viewerPart(), SIGNAL(viewerMenuStateChange(bool)), documentViewerMenu, SLOT(setEnabled(bool))); + } + else { + if(documentViewerMenu) { + documentViewerMenu->setVisible(false); + } + delete popup; + } + } + else { // we hide the special document viewer menu + QMenu *documentViewerMenu = static_cast(guiFactory()->container("menu_document_viewer", this)); + if(documentViewerMenu) { + documentViewerMenu->setVisible(false); + } + } - resize(KileConfig::mainwindowWidth(), KileConfig::mainwindowHeight()); - applyMainWindowSettings(m_config->group("KileMainWindow")); - - restoreLastSelectedAction(); // don't call this inside 'setupTools' as it is not compatible with KParts switching! - QList sizes; - int verSplitTop = KileConfig::verticalSplitterTop(); - int verSplitBottom = KileConfig::verticalSplitterBottom(); - sizes << verSplitTop << verSplitBottom; - m_verticalSplitter->setSizes(sizes); - sizes.clear(); - int horSplitLeft = KileConfig::horizontalSplitterLeft(); - int horSplitRight = KileConfig::horizontalSplitterRight(); - if(horSplitLeft <= 0 && horSplitRight <= 0) { // compute default values - horSplitLeft = m_sideBar->width(); - horSplitRight = width() / 2; // leave some room for the viewer part - } - // the size of the third widget is computed from the sizes of the two other widgets - sizes << horSplitLeft << horSplitRight << width() - (horSplitLeft + horSplitRight); - m_horizontalSplitter->setSizes(sizes); + resize(KileConfig::mainwindowWidth(), KileConfig::mainwindowHeight()); + applyMainWindowSettings(m_config->group("KileMainWindow")); + + restoreLastSelectedAction(); // don't call this inside 'setupTools' as it is not compatible with KParts switching! + QList sizes; + int verSplitTop = KileConfig::verticalSplitterTop(); + int verSplitBottom = KileConfig::verticalSplitterBottom(); + sizes << verSplitTop << verSplitBottom; + m_verticalSplitter->setSizes(sizes); + sizes.clear(); + int horSplitLeft = KileConfig::horizontalSplitterLeft(); + int horSplitRight = KileConfig::horizontalSplitterRight(); + if(horSplitLeft <= 0 && horSplitRight <= 0) { // compute default values + horSplitLeft = m_sideBar->width(); + horSplitRight = width() / 2; // leave some room for the viewer part + } + // the size of the third widget is computed from the sizes of the two other widgets + sizes << horSplitLeft << horSplitRight << width() - (horSplitLeft + horSplitRight); + m_horizontalSplitter->setSizes(sizes); - show(); - if(KileConfig::showSplashScreen()) { - splashScreen.finish(this); - } + show(); + if(KileConfig::showSplashScreen()) { + splashScreen.finish(this); + } - // Due to 'processEvents' being called earlier we only create the DBUS adaptor and - // the LyX server when all of Kile's structures have been set up. - // publish the D-Bus interfaces - new MainAdaptor(this); - QDBusConnection dbus = QDBusConnection::sessionBus(); - dbus.registerObject("/main", this); - dbus.registerService("net.sourceforge.kile"); // register under a constant name + // Due to 'processEvents' being called earlier we only create the DBUS adaptor and + // the LyX server when all of Kile's structures have been set up. + // publish the D-Bus interfaces + new MainAdaptor(this); + QDBusConnection dbus = QDBusConnection::sessionBus(); + dbus.registerObject("/main", this); + dbus.registerService("net.sourceforge.kile"); // register under a constant name - m_lyxserver = new KileLyxServer(KileConfig::runLyxServer()); - connect(m_lyxserver, SIGNAL(insert(const KileAction::TagData &)), this, SLOT(insertTag(const KileAction::TagData &))); + m_lyxserver = new KileLyxServer(KileConfig::runLyxServer()); + connect(m_lyxserver, SIGNAL(insert(const KileAction::TagData &)), this, SLOT(insertTag(const KileAction::TagData &))); - if(m_listUserTools.count() > 0) { - KMessageBox::information(0, i18n("You have defined some tools in the User menu. From now on these tools will be available from the Build->Other menu and can be configured in the configuration dialog (go to the Settings menu and choose Configure Kile). This has some advantages; your own tools can now be used in a QuickBuild command if you wish."), i18n("User Tools Detected")); - m_listUserTools.clear(); - } + if(m_listUserTools.count() > 0) { + KMessageBox::information(0, i18n("You have defined some tools in the User menu. From now on these tools will be available from the Build->Other menu and can be configured in the configuration dialog (go to the Settings menu and choose Configure Kile). This has some advantages; your own tools can now be used in a QuickBuild command if you wish."), i18n("User Tools Detected")); + m_listUserTools.clear(); + } - if(KileConfig::rCVersion() < 8) { - // if KileConfig::rCVersion() <= 0, then 'kilerc' is (most likely) fresh or empty, - // otherwise, we have to ask the user if she wants to reset the tools - if ((KileConfig::rCVersion() <= 0) || (KMessageBox::questionYesNo(mainWindow(), - i18n("

The tool settings need to be reset for this version of Kile to function properly.
" - "This will overwrite any changes you have made.

" - "

Do you want to reset the tools now?

"), - i18n("Tools need to be reset")) == KMessageBox::Yes)){ - m_toolFactory->resetToolConfigurations(); - } - } + if(KileConfig::rCVersion() < 8) { + // if KileConfig::rCVersion() <= 0, then 'kilerc' is (most likely) fresh or empty, + // otherwise, we have to ask the user if she wants to reset the tools + if ((KileConfig::rCVersion() <= 0) || (KMessageBox::questionYesNo(mainWindow(), + i18n("

The tool settings need to be reset for this version of Kile to function properly.
" + "This will overwrite any changes you have made.

" + "

Do you want to reset the tools now?

"), + i18n("Tools need to be reset")) == KMessageBox::Yes)) { + m_toolFactory->resetToolConfigurations(); + } + } - restoreFilesAndProjects(allowRestore); - initMenu(); - updateModeStatus(); + restoreFilesAndProjects(allowRestore); + initMenu(); + updateModeStatus(); - // finally init all actions for the ScriptManager - m_jScriptManager->initScriptActions(); + // finally init all actions for the ScriptManager + m_jScriptManager->initScriptActions(); - setUpdatesEnabled(false); - setAutoSaveSettings(QLatin1String("KileMainWindow"),true); + setUpdatesEnabled(false); + setAutoSaveSettings(QLatin1String("KileMainWindow"),true); - m_userMenu->refreshActionProperties(); - setUpdatesEnabled(true); + m_userMenu->refreshActionProperties(); + setUpdatesEnabled(true); - // finally, we check whether the system check assistant should be run, which is important for - // version 3.0 regarding the newly introduced live preview feature - const QString& lastVersionRunFor = KileConfig::systemCheckLastVersionRunForAtStartUp(); - if(lastVersionRunFor.isEmpty() || compareVersionStrings(lastVersionRunFor, "2.9.91") < 0) { - slotPerformCheck(); - KileConfig::setSystemCheckLastVersionRunForAtStartUp(kileFullVersion); - } + // finally, we check whether the system check assistant should be run, which is important for + // version 3.0 regarding the newly introduced live preview feature + const QString& lastVersionRunFor = KileConfig::systemCheckLastVersionRunForAtStartUp(); + if(lastVersionRunFor.isEmpty() || compareVersionStrings(lastVersionRunFor, "2.9.91") < 0) { + slotPerformCheck(); + KileConfig::setSystemCheckLastVersionRunForAtStartUp(kileFullVersion); + } - if(m_livePreviewManager) { - m_livePreviewManager->buildLivePreviewMenu(m_config.data()); - m_livePreviewManager->disableBootUpMode(); - } + if(m_livePreviewManager) { + m_livePreviewManager->buildLivePreviewMenu(m_config.data()); + m_livePreviewManager->disableBootUpMode(); + } } Kile::~Kile() { - KILE_DEBUG_MAIN << "cleaning up..." << endl; + KILE_DEBUG_MAIN << "cleaning up..." << endl; - if(m_livePreviewManager && viewManager()->viewerPart()) { - guiFactory()->removeClient(viewManager()->viewerPart()); - } - delete m_userMenu; - delete m_livePreviewManager; - delete m_toolFactory; - delete m_manager; - delete m_quickPreview; - delete m_edit; - delete m_help; - delete m_lyxserver; //QObject without parent, have to delete it ourselves - delete m_latexCommands; - delete m_extensions; - delete m_viewManager; + if(m_livePreviewManager && viewManager()->viewerPart()) { + guiFactory()->removeClient(viewManager()->viewerPart()); + } + delete m_userMenu; + delete m_livePreviewManager; + delete m_toolFactory; + delete m_manager; + delete m_quickPreview; + delete m_edit; + delete m_help; + delete m_lyxserver; //QObject without parent, have to delete it ourselves + delete m_latexCommands; + delete m_extensions; + delete m_viewManager; } // currently not usable due to https://bugs.kde.org/show_bug.cgi?id=194732 // void Kile::plugActionList(const QString& name, const QList& actionList) // { // plugActionList(name, actionList); // } // // void Kile::unplugActionList(const QString& name) // { // unplugActionList(name); // } void Kile::setupSideBar() { - m_sideBar = new KileWidget::SideBar(m_horizontalSplitter); + m_sideBar = new KileWidget::SideBar(m_horizontalSplitter); - m_fileBrowserWidget = new KileWidget::FileBrowserWidget(m_extensions, m_sideBar); - m_sideBar->addPage(m_fileBrowserWidget, QIcon::fromTheme("document-open"), i18n("Open File")); - connect(m_fileBrowserWidget,SIGNAL(fileSelected(const KFileItem&)), docManager(), SLOT(fileSelected(const KFileItem&))); + m_fileBrowserWidget = new KileWidget::FileBrowserWidget(m_extensions, m_sideBar); + m_sideBar->addPage(m_fileBrowserWidget, QIcon::fromTheme("document-open"), i18n("Open File")); + connect(m_fileBrowserWidget,SIGNAL(fileSelected(const KFileItem&)), docManager(), SLOT(fileSelected(const KFileItem&))); - setupProjectView(); - setupStructureView(); - setupSymbolViews(); - setupScriptsManagementView(); - setupCommandViewToolbox(); - setupAbbreviationView(); + setupProjectView(); + setupStructureView(); + setupSymbolViews(); + setupScriptsManagementView(); + setupCommandViewToolbox(); + setupAbbreviationView(); - m_sideBar->switchToTab(KileConfig::selectedLeftView()); - m_sideBar->setVisible(KileConfig::sideBar()); - m_sideBar->setDirectionalSize(KileConfig::sideBarSize()); + m_sideBar->switchToTab(KileConfig::selectedLeftView()); + m_sideBar->setVisible(KileConfig::sideBar()); + m_sideBar->setDirectionalSize(KileConfig::sideBarSize()); } void Kile::setupProjectView() { - KileWidget::ProjectView *projectview = new KileWidget::ProjectView(m_sideBar, this); + KileWidget::ProjectView *projectview = new KileWidget::ProjectView(m_sideBar, this); // viewManager()->setProjectView(projectview); - m_sideBar->addPage(projectview, QIcon::fromTheme("relation"), i18n("Files and Projects")); - connect(projectview, SIGNAL(fileSelected(const KileProjectItem *)), docManager(), SLOT(fileSelected(const KileProjectItem *))); - connect(projectview, SIGNAL(fileSelected(const QUrl &)), docManager(), SLOT(fileSelected(const QUrl &))); - connect(projectview, SIGNAL(closeURL(const QUrl&)), docManager(), SLOT(fileClose(const QUrl&))); - connect(projectview, SIGNAL(closeProject(const QUrl&)), docManager(), SLOT(projectClose(const QUrl&))); - connect(projectview, SIGNAL(projectOptions(const QUrl&)), docManager(), SLOT(projectOptions(const QUrl&))); - connect(projectview, SIGNAL(projectArchive(const QUrl&)), this, SLOT(runArchiveTool(const QUrl&))); - connect(projectview, SIGNAL(removeFromProject(KileProjectItem *)), docManager(), SLOT(removeFromProject(KileProjectItem*))); - connect(projectview, SIGNAL(addFiles(const QUrl &)), docManager(), SLOT(projectAddFiles(const QUrl &))); - connect(projectview, SIGNAL(openAllFiles(const QUrl &)), docManager(), SLOT(projectOpenAllFiles(const QUrl &))); - connect(projectview, SIGNAL(toggleArchive(KileProjectItem *)), docManager(), SLOT(toggleArchive(KileProjectItem *))); - connect(projectview, SIGNAL(addToProject(const QUrl &)), docManager(), SLOT(addToProject(const QUrl &))); - connect(projectview, SIGNAL(saveURL(const QUrl &)), docManager(), SLOT(saveURL(const QUrl &))); - connect(projectview, SIGNAL(buildProjectTree(const QUrl &)), docManager(), SLOT(buildProjectTree(const QUrl &))); - connect(docManager(), SIGNAL(projectTreeChanged(const KileProject *)), projectview, SLOT(refreshProjectTree(const KileProject *))); - connect(docManager(), SIGNAL(removeFromProjectView(const QUrl &)),projectview,SLOT(remove(const QUrl &))); - connect(docManager(), SIGNAL(removeFromProjectView(const KileProject *)),projectview,SLOT(remove(const KileProject *))); - connect(docManager(), SIGNAL(addToProjectView(const QUrl &)),projectview,SLOT(add(const QUrl &))); - connect(docManager(), SIGNAL(addToProjectView(const KileProject *)),projectview,SLOT(add(const KileProject *))); - connect(docManager(),SIGNAL(removeItemFromProjectView(const KileProjectItem *, bool)),projectview,SLOT(removeItem(const KileProjectItem *, bool))); - connect(docManager(),SIGNAL(addToProjectView(KileProjectItem *)),projectview,SLOT(add(KileProjectItem *))); + m_sideBar->addPage(projectview, QIcon::fromTheme("relation"), i18n("Files and Projects")); + connect(projectview, SIGNAL(fileSelected(const KileProjectItem *)), docManager(), SLOT(fileSelected(const KileProjectItem *))); + connect(projectview, SIGNAL(fileSelected(const QUrl &)), docManager(), SLOT(fileSelected(const QUrl &))); + connect(projectview, SIGNAL(closeURL(const QUrl&)), docManager(), SLOT(fileClose(const QUrl&))); + connect(projectview, SIGNAL(closeProject(const QUrl&)), docManager(), SLOT(projectClose(const QUrl&))); + connect(projectview, SIGNAL(projectOptions(const QUrl&)), docManager(), SLOT(projectOptions(const QUrl&))); + connect(projectview, SIGNAL(projectArchive(const QUrl&)), this, SLOT(runArchiveTool(const QUrl&))); + connect(projectview, SIGNAL(removeFromProject(KileProjectItem *)), docManager(), SLOT(removeFromProject(KileProjectItem*))); + connect(projectview, SIGNAL(addFiles(const QUrl &)), docManager(), SLOT(projectAddFiles(const QUrl &))); + connect(projectview, SIGNAL(openAllFiles(const QUrl &)), docManager(), SLOT(projectOpenAllFiles(const QUrl &))); + connect(projectview, SIGNAL(toggleArchive(KileProjectItem *)), docManager(), SLOT(toggleArchive(KileProjectItem *))); + connect(projectview, SIGNAL(addToProject(const QUrl &)), docManager(), SLOT(addToProject(const QUrl &))); + connect(projectview, SIGNAL(saveURL(const QUrl &)), docManager(), SLOT(saveURL(const QUrl &))); + connect(projectview, SIGNAL(buildProjectTree(const QUrl &)), docManager(), SLOT(buildProjectTree(const QUrl &))); + connect(docManager(), SIGNAL(projectTreeChanged(const KileProject *)), projectview, SLOT(refreshProjectTree(const KileProject *))); + connect(docManager(), SIGNAL(removeFromProjectView(const QUrl &)),projectview,SLOT(remove(const QUrl &))); + connect(docManager(), SIGNAL(removeFromProjectView(const KileProject *)),projectview,SLOT(remove(const KileProject *))); + connect(docManager(), SIGNAL(addToProjectView(const QUrl &)),projectview,SLOT(add(const QUrl &))); + connect(docManager(), SIGNAL(addToProjectView(const KileProject *)),projectview,SLOT(add(const KileProject *))); + connect(docManager(),SIGNAL(removeItemFromProjectView(const KileProjectItem *, bool)),projectview,SLOT(removeItem(const KileProjectItem *, bool))); + connect(docManager(),SIGNAL(addToProjectView(KileProjectItem *)),projectview,SLOT(add(KileProjectItem *))); } void Kile::setupStructureView() { - m_kwStructure = new KileWidget::StructureWidget(this, m_sideBar); - m_sideBar->addPage(m_kwStructure, QIcon::fromTheme("view-list-tree"), i18n("Structure")); - m_kwStructure->setFocusPolicy(Qt::ClickFocus); - connect(configurationManager(), SIGNAL(configChanged()), m_kwStructure, SIGNAL(configChanged())); - connect(m_kwStructure, SIGNAL(setCursor(const QUrl &,int,int)), this, SLOT(setCursor(const QUrl &,int,int))); - connect(m_kwStructure, SIGNAL(fileOpen(const QUrl&, const QString & )), docManager(), SLOT(fileOpen(const QUrl&, const QString& ))); - connect(m_kwStructure, SIGNAL(fileNew(const QUrl&)), docManager(), SLOT(fileNew(const QUrl&))); - connect(m_kwStructure, SIGNAL(sendText(const QString &)), this, SLOT(insertText(const QString &))); - connect(m_kwStructure, SIGNAL(sectioningPopup(KileWidget::StructureViewItem*,int)), m_edit, SLOT(sectioningCommand(KileWidget::StructureViewItem*,int))); + m_kwStructure = new KileWidget::StructureWidget(this, m_sideBar); + m_sideBar->addPage(m_kwStructure, QIcon::fromTheme("view-list-tree"), i18n("Structure")); + m_kwStructure->setFocusPolicy(Qt::ClickFocus); + connect(configurationManager(), SIGNAL(configChanged()), m_kwStructure, SIGNAL(configChanged())); + connect(m_kwStructure, SIGNAL(setCursor(const QUrl &,int,int)), this, SLOT(setCursor(const QUrl &,int,int))); + connect(m_kwStructure, SIGNAL(fileOpen(const QUrl&, const QString & )), docManager(), SLOT(fileOpen(const QUrl&, const QString& ))); + connect(m_kwStructure, SIGNAL(fileNew(const QUrl&)), docManager(), SLOT(fileNew(const QUrl&))); + connect(m_kwStructure, SIGNAL(sendText(const QString &)), this, SLOT(insertText(const QString &))); + connect(m_kwStructure, SIGNAL(sectioningPopup(KileWidget::StructureViewItem*,int)), m_edit, SLOT(sectioningCommand(KileWidget::StructureViewItem*,int))); } void Kile::setupScriptsManagementView() { - m_scriptsManagementWidget = new KileWidget::ScriptsManagement(this, m_sideBar); - m_sideBar->addPage(m_scriptsManagementWidget, QIcon::fromTheme("preferences-plugin-script"), i18n("Scripts")); + m_scriptsManagementWidget = new KileWidget::ScriptsManagement(this, m_sideBar); + m_sideBar->addPage(m_scriptsManagementWidget, QIcon::fromTheme("preferences-plugin-script"), i18n("Scripts")); } void Kile::enableSymbolViewMFUS() { - m_toolBox->setItemEnabled(m_toolBox->indexOf(m_symbolViewMFUS),true); + m_toolBox->setItemEnabled(m_toolBox->indexOf(m_symbolViewMFUS),true); - connect(m_symbolViewRelation, &KileWidget::SymbolView::addToList ,m_symbolViewMFUS, &KileWidget::SymbolView::slotAddToList); - connect(m_symbolViewOperators, &KileWidget::SymbolView::addToList ,m_symbolViewMFUS, &KileWidget::SymbolView::slotAddToList); - connect(m_symbolViewArrows, &KileWidget::SymbolView::addToList ,m_symbolViewMFUS, &KileWidget::SymbolView::slotAddToList); - connect(m_symbolViewMiscMath, &KileWidget::SymbolView::addToList ,m_symbolViewMFUS, &KileWidget::SymbolView::slotAddToList); - connect(m_symbolViewMiscText, &KileWidget::SymbolView::addToList ,m_symbolViewMFUS, &KileWidget::SymbolView::slotAddToList); - connect(m_symbolViewDelimiters, &KileWidget::SymbolView::addToList ,m_symbolViewMFUS, &KileWidget::SymbolView::slotAddToList); - connect(m_symbolViewGreek, &KileWidget::SymbolView::addToList ,m_symbolViewMFUS, &KileWidget::SymbolView::slotAddToList); - connect(m_symbolViewSpecial, &KileWidget::SymbolView::addToList ,m_symbolViewMFUS, &KileWidget::SymbolView::slotAddToList); - connect(m_symbolViewCyrillic, &KileWidget::SymbolView::addToList ,m_symbolViewMFUS, &KileWidget::SymbolView::slotAddToList); - connect(m_symbolViewUser, &KileWidget::SymbolView::addToList ,m_symbolViewMFUS, &KileWidget::SymbolView::slotAddToList); + connect(m_symbolViewRelation, &KileWidget::SymbolView::addToList,m_symbolViewMFUS, &KileWidget::SymbolView::slotAddToList); + connect(m_symbolViewOperators, &KileWidget::SymbolView::addToList,m_symbolViewMFUS, &KileWidget::SymbolView::slotAddToList); + connect(m_symbolViewArrows, &KileWidget::SymbolView::addToList,m_symbolViewMFUS, &KileWidget::SymbolView::slotAddToList); + connect(m_symbolViewMiscMath, &KileWidget::SymbolView::addToList,m_symbolViewMFUS, &KileWidget::SymbolView::slotAddToList); + connect(m_symbolViewMiscText, &KileWidget::SymbolView::addToList,m_symbolViewMFUS, &KileWidget::SymbolView::slotAddToList); + connect(m_symbolViewDelimiters, &KileWidget::SymbolView::addToList,m_symbolViewMFUS, &KileWidget::SymbolView::slotAddToList); + connect(m_symbolViewGreek, &KileWidget::SymbolView::addToList,m_symbolViewMFUS, &KileWidget::SymbolView::slotAddToList); + connect(m_symbolViewSpecial, &KileWidget::SymbolView::addToList,m_symbolViewMFUS, &KileWidget::SymbolView::slotAddToList); + connect(m_symbolViewCyrillic, &KileWidget::SymbolView::addToList,m_symbolViewMFUS, &KileWidget::SymbolView::slotAddToList); + connect(m_symbolViewUser, &KileWidget::SymbolView::addToList,m_symbolViewMFUS, &KileWidget::SymbolView::slotAddToList); } void Kile::disableSymbolViewMFUS() { - m_toolBox->setItemEnabled(m_toolBox->indexOf(m_symbolViewMFUS),false); - m_toolBox->setItemToolTip(m_toolBox->indexOf(m_symbolViewMFUS),QString()); + m_toolBox->setItemEnabled(m_toolBox->indexOf(m_symbolViewMFUS),false); + m_toolBox->setItemToolTip(m_toolBox->indexOf(m_symbolViewMFUS),QString()); - disconnect(m_symbolViewRelation, &KileWidget::SymbolView::addToList ,m_symbolViewMFUS, &KileWidget::SymbolView::slotAddToList); - disconnect(m_symbolViewOperators, &KileWidget::SymbolView::addToList ,m_symbolViewMFUS, &KileWidget::SymbolView::slotAddToList); - disconnect(m_symbolViewArrows, &KileWidget::SymbolView::addToList ,m_symbolViewMFUS, &KileWidget::SymbolView::slotAddToList); - disconnect(m_symbolViewMiscMath, &KileWidget::SymbolView::addToList ,m_symbolViewMFUS, &KileWidget::SymbolView::slotAddToList); - disconnect(m_symbolViewMiscText, &KileWidget::SymbolView::addToList ,m_symbolViewMFUS, &KileWidget::SymbolView::slotAddToList); - disconnect(m_symbolViewDelimiters, &KileWidget::SymbolView::addToList ,m_symbolViewMFUS, &KileWidget::SymbolView::slotAddToList); - disconnect(m_symbolViewGreek, &KileWidget::SymbolView::addToList ,m_symbolViewMFUS, &KileWidget::SymbolView::slotAddToList); - disconnect(m_symbolViewSpecial, &KileWidget::SymbolView::addToList ,m_symbolViewMFUS, &KileWidget::SymbolView::slotAddToList); - disconnect(m_symbolViewCyrillic, &KileWidget::SymbolView::addToList ,m_symbolViewMFUS, &KileWidget::SymbolView::slotAddToList); - disconnect(m_symbolViewUser, &KileWidget::SymbolView::addToList ,m_symbolViewMFUS, &KileWidget::SymbolView::slotAddToList); + disconnect(m_symbolViewRelation, &KileWidget::SymbolView::addToList,m_symbolViewMFUS, &KileWidget::SymbolView::slotAddToList); + disconnect(m_symbolViewOperators, &KileWidget::SymbolView::addToList,m_symbolViewMFUS, &KileWidget::SymbolView::slotAddToList); + disconnect(m_symbolViewArrows, &KileWidget::SymbolView::addToList,m_symbolViewMFUS, &KileWidget::SymbolView::slotAddToList); + disconnect(m_symbolViewMiscMath, &KileWidget::SymbolView::addToList,m_symbolViewMFUS, &KileWidget::SymbolView::slotAddToList); + disconnect(m_symbolViewMiscText, &KileWidget::SymbolView::addToList,m_symbolViewMFUS, &KileWidget::SymbolView::slotAddToList); + disconnect(m_symbolViewDelimiters, &KileWidget::SymbolView::addToList,m_symbolViewMFUS, &KileWidget::SymbolView::slotAddToList); + disconnect(m_symbolViewGreek, &KileWidget::SymbolView::addToList,m_symbolViewMFUS, &KileWidget::SymbolView::slotAddToList); + disconnect(m_symbolViewSpecial, &KileWidget::SymbolView::addToList,m_symbolViewMFUS, &KileWidget::SymbolView::slotAddToList); + disconnect(m_symbolViewCyrillic, &KileWidget::SymbolView::addToList,m_symbolViewMFUS, &KileWidget::SymbolView::slotAddToList); + disconnect(m_symbolViewUser, &KileWidget::SymbolView::addToList,m_symbolViewMFUS, &KileWidget::SymbolView::slotAddToList); } void Kile::setupSymbolViews() { - m_toolBox = new QToolBox(m_sideBar); - m_sideBar->addPage(m_toolBox,QIcon::fromTheme("math0"),i18n("Symbols")); - - m_symbolViewMFUS = new KileWidget::SymbolView(this, m_toolBox, KileWidget::SymbolView::MFUS); - m_toolBox->addItem(m_symbolViewMFUS,i18n("Most Frequently Used")); - m_toolBox->setItemEnabled(m_toolBox->indexOf(m_symbolViewMFUS),false); - connect(m_symbolViewMFUS, &KileWidget::SymbolView::insertText, - this, static_cast&)>(&Kile::insertText)); - - m_symbolViewRelation = new KileWidget::SymbolView(this, m_toolBox, KileWidget::SymbolView::Relation); - m_toolBox->addItem(m_symbolViewRelation,QIcon::fromTheme("math1"),i18n("Relation")); - connect(m_symbolViewRelation, &KileWidget::SymbolView::insertText, - this, static_cast&)>(&Kile::insertText)); - - m_symbolViewOperators = new KileWidget::SymbolView(this, m_toolBox, KileWidget::SymbolView::Operator); - m_toolBox->addItem(m_symbolViewOperators,QIcon::fromTheme("math2"),i18n("Operators")); - connect(m_symbolViewOperators, &KileWidget::SymbolView::insertText, - this, static_cast&)>(&Kile::insertText)); - - m_symbolViewArrows = new KileWidget::SymbolView(this, m_toolBox, KileWidget::SymbolView::Arrow); - m_toolBox->addItem(m_symbolViewArrows,QIcon::fromTheme("math3"),i18n("Arrows")); - connect(m_symbolViewArrows, &KileWidget::SymbolView::insertText, - this, static_cast&)>(&Kile::insertText)); - - m_symbolViewMiscMath = new KileWidget::SymbolView(this, m_toolBox, KileWidget::SymbolView::MiscMath); - m_toolBox->addItem(m_symbolViewMiscMath,QIcon::fromTheme("math4"),i18n("Miscellaneous Math")); - connect(m_symbolViewMiscMath, &KileWidget::SymbolView::insertText, - this, static_cast&)>(&Kile::insertText)); - - m_symbolViewMiscText = new KileWidget::SymbolView(this, m_toolBox, KileWidget::SymbolView::MiscText); - m_toolBox->addItem(m_symbolViewMiscText,QIcon::fromTheme("math5"),i18n("Miscellaneous Text")); - connect(m_symbolViewMiscText, &KileWidget::SymbolView::insertText, - this, static_cast&)>(&Kile::insertText)); - - m_symbolViewDelimiters= new KileWidget::SymbolView(this, m_toolBox, KileWidget::SymbolView::Delimiters); - m_toolBox->addItem(m_symbolViewDelimiters,QIcon::fromTheme("math6"),i18n("Delimiters")); - connect(m_symbolViewDelimiters, &KileWidget::SymbolView::insertText, - this, static_cast&)>(&Kile::insertText)); - - m_symbolViewGreek = new KileWidget::SymbolView(this, m_toolBox, KileWidget::SymbolView::Greek); - m_toolBox->addItem(m_symbolViewGreek,QIcon::fromTheme("math7"),i18n("Greek")); - connect(m_symbolViewGreek, SIGNAL(insertText(const QString& ,const QList&)), - this, SLOT(insertText(const QString& ,const QList&))); - - m_symbolViewSpecial = new KileWidget::SymbolView(this, m_toolBox, KileWidget::SymbolView::Special); - m_toolBox->addItem(m_symbolViewSpecial,QIcon::fromTheme("math8"),i18n("Special Characters")); - connect(m_symbolViewSpecial, &KileWidget::SymbolView::insertText, - this, static_cast&)>(&Kile::insertText)); - - m_symbolViewCyrillic = new KileWidget::SymbolView(this, m_toolBox, KileWidget::SymbolView::Cyrillic); - m_toolBox->addItem(m_symbolViewCyrillic,QIcon::fromTheme("math10"),i18n("Cyrillic Characters")); - connect(m_symbolViewCyrillic, &KileWidget::SymbolView::insertText, - this, static_cast&)>(&Kile::insertText)); - - m_symbolViewUser = new KileWidget::SymbolView(this, m_toolBox, KileWidget::SymbolView::User); - m_toolBox->addItem(m_symbolViewUser,QIcon::fromTheme("math9"),i18n("User Defined")); - connect(m_symbolViewUser, &KileWidget::SymbolView::insertText, - this, static_cast&)>(&Kile::insertText)); - - for(int i = 0; i < m_toolBox->count(); ++i) { - m_toolBox->setItemToolTip(i, i18n("

Move the mouse over the icons to see the corresponding LaTeX commands.
" - "Click on an image to insert the corresponding command, additionally pressing \"Shift\" inserts " - "it in math mode, pressing \"Ctrl\" in curly brackets.

")); - } + m_toolBox = new QToolBox(m_sideBar); + m_sideBar->addPage(m_toolBox,QIcon::fromTheme("math0"),i18n("Symbols")); + + m_symbolViewMFUS = new KileWidget::SymbolView(this, m_toolBox, KileWidget::SymbolView::MFUS); + m_toolBox->addItem(m_symbolViewMFUS,i18n("Most Frequently Used")); + m_toolBox->setItemEnabled(m_toolBox->indexOf(m_symbolViewMFUS),false); + connect(m_symbolViewMFUS, &KileWidget::SymbolView::insertText, + this, static_cast&)>(&Kile::insertText)); + + m_symbolViewRelation = new KileWidget::SymbolView(this, m_toolBox, KileWidget::SymbolView::Relation); + m_toolBox->addItem(m_symbolViewRelation,QIcon::fromTheme("math1"),i18n("Relation")); + connect(m_symbolViewRelation, &KileWidget::SymbolView::insertText, + this, static_cast&)>(&Kile::insertText)); + + m_symbolViewOperators = new KileWidget::SymbolView(this, m_toolBox, KileWidget::SymbolView::Operator); + m_toolBox->addItem(m_symbolViewOperators,QIcon::fromTheme("math2"),i18n("Operators")); + connect(m_symbolViewOperators, &KileWidget::SymbolView::insertText, + this, static_cast&)>(&Kile::insertText)); + + m_symbolViewArrows = new KileWidget::SymbolView(this, m_toolBox, KileWidget::SymbolView::Arrow); + m_toolBox->addItem(m_symbolViewArrows,QIcon::fromTheme("math3"),i18n("Arrows")); + connect(m_symbolViewArrows, &KileWidget::SymbolView::insertText, + this, static_cast&)>(&Kile::insertText)); + + m_symbolViewMiscMath = new KileWidget::SymbolView(this, m_toolBox, KileWidget::SymbolView::MiscMath); + m_toolBox->addItem(m_symbolViewMiscMath,QIcon::fromTheme("math4"),i18n("Miscellaneous Math")); + connect(m_symbolViewMiscMath, &KileWidget::SymbolView::insertText, + this, static_cast&)>(&Kile::insertText)); + + m_symbolViewMiscText = new KileWidget::SymbolView(this, m_toolBox, KileWidget::SymbolView::MiscText); + m_toolBox->addItem(m_symbolViewMiscText,QIcon::fromTheme("math5"),i18n("Miscellaneous Text")); + connect(m_symbolViewMiscText, &KileWidget::SymbolView::insertText, + this, static_cast&)>(&Kile::insertText)); + + m_symbolViewDelimiters= new KileWidget::SymbolView(this, m_toolBox, KileWidget::SymbolView::Delimiters); + m_toolBox->addItem(m_symbolViewDelimiters,QIcon::fromTheme("math6"),i18n("Delimiters")); + connect(m_symbolViewDelimiters, &KileWidget::SymbolView::insertText, + this, static_cast&)>(&Kile::insertText)); + + m_symbolViewGreek = new KileWidget::SymbolView(this, m_toolBox, KileWidget::SymbolView::Greek); + m_toolBox->addItem(m_symbolViewGreek,QIcon::fromTheme("math7"),i18n("Greek")); + connect(m_symbolViewGreek, SIGNAL(insertText(const QString&,const QList&)), + this, SLOT(insertText(const QString&,const QList&))); + + m_symbolViewSpecial = new KileWidget::SymbolView(this, m_toolBox, KileWidget::SymbolView::Special); + m_toolBox->addItem(m_symbolViewSpecial,QIcon::fromTheme("math8"),i18n("Special Characters")); + connect(m_symbolViewSpecial, &KileWidget::SymbolView::insertText, + this, static_cast&)>(&Kile::insertText)); + + m_symbolViewCyrillic = new KileWidget::SymbolView(this, m_toolBox, KileWidget::SymbolView::Cyrillic); + m_toolBox->addItem(m_symbolViewCyrillic,QIcon::fromTheme("math10"),i18n("Cyrillic Characters")); + connect(m_symbolViewCyrillic, &KileWidget::SymbolView::insertText, + this, static_cast&)>(&Kile::insertText)); + + m_symbolViewUser = new KileWidget::SymbolView(this, m_toolBox, KileWidget::SymbolView::User); + m_toolBox->addItem(m_symbolViewUser,QIcon::fromTheme("math9"),i18n("User Defined")); + connect(m_symbolViewUser, &KileWidget::SymbolView::insertText, + this, static_cast&)>(&Kile::insertText)); + + for(int i = 0; i < m_toolBox->count(); ++i) { + m_toolBox->setItemToolTip(i, i18n("

Move the mouse over the icons to see the corresponding LaTeX commands.
" + "Click on an image to insert the corresponding command, additionally pressing \"Shift\" inserts " + "it in math mode, pressing \"Ctrl\" in curly brackets.

")); + } } void Kile::setupCommandViewToolbox() { - m_commandViewToolBox = new KileWidget::CommandViewToolBox(this, m_sideBar); - m_sideBar->addPage(m_commandViewToolBox, QIcon::fromTheme("texlion"), i18n("LaTeX")); + m_commandViewToolBox = new KileWidget::CommandViewToolBox(this, m_sideBar); + m_sideBar->addPage(m_commandViewToolBox, QIcon::fromTheme("texlion"), i18n("LaTeX")); - connect(m_commandViewToolBox, SIGNAL(sendText(const QString &)), this, SLOT(insertText(const QString &))); + connect(m_commandViewToolBox, SIGNAL(sendText(const QString &)), this, SLOT(insertText(const QString &))); } void Kile::setupAbbreviationView() { - m_kileAbbrevView = new KileWidget::AbbreviationView(abbreviationManager(), m_sideBar); - connect(abbreviationManager(), SIGNAL(abbreviationsChanged()), m_kileAbbrevView, SLOT(updateAbbreviations()));; - m_sideBar->addPage(m_kileAbbrevView, QIcon::fromTheme("complete3"), i18n("Abbreviation")); + m_kileAbbrevView = new KileWidget::AbbreviationView(abbreviationManager(), m_sideBar); + connect(abbreviationManager(), SIGNAL(abbreviationsChanged()), m_kileAbbrevView, SLOT(updateAbbreviations()));; + m_sideBar->addPage(m_kileAbbrevView, QIcon::fromTheme("complete3"), i18n("Abbreviation")); - connect(m_kileAbbrevView, SIGNAL(sendText(const QString&)), this, SLOT(insertText(const QString&))); + connect(m_kileAbbrevView, SIGNAL(sendText(const QString&)), this, SLOT(insertText(const QString&))); } void Kile::setupBottomBar() { - m_bottomBar = new KileWidget::BottomBar(this); - m_bottomBar->setFocusPolicy(Qt::ClickFocus); + m_bottomBar = new KileWidget::BottomBar(this); + m_bottomBar->setFocusPolicy(Qt::ClickFocus); - connect(errorHandler(), SIGNAL(showingErrorMessage(QWidget* )), this, SLOT(focusLog())); + connect(errorHandler(), SIGNAL(showingErrorMessage(QWidget* )), this, SLOT(focusLog())); - QWidget *widget = new QWidget(this); - QHBoxLayout *layout = new QHBoxLayout(widget); - layout->setMargin(0); - widget->setLayout(layout); + QWidget *widget = new QWidget(this); + QHBoxLayout *layout = new QHBoxLayout(widget); + layout->setMargin(0); + widget->setLayout(layout); - m_latexOutputErrorToolBar = new KToolBar(widget); - m_latexOutputErrorToolBar->setToolButtonStyle(Qt::ToolButtonIconOnly); - m_latexOutputErrorToolBar->setIconDimensions(KIconLoader::SizeSmall); - m_latexOutputErrorToolBar->setOrientation(Qt::Vertical); + m_latexOutputErrorToolBar = new KToolBar(widget); + m_latexOutputErrorToolBar->setToolButtonStyle(Qt::ToolButtonIconOnly); + m_latexOutputErrorToolBar->setIconDimensions(KIconLoader::SizeSmall); + m_latexOutputErrorToolBar->setOrientation(Qt::Vertical); - layout->addWidget(errorHandler()->outputWidget()); - layout->addWidget(m_latexOutputErrorToolBar); - m_bottomBar->addPage(widget, QIcon::fromTheme("utilities-log-viewer"), i18n("Log and Messages")); + layout->addWidget(errorHandler()->outputWidget()); + layout->addWidget(m_latexOutputErrorToolBar); + m_bottomBar->addPage(widget, QIcon::fromTheme("utilities-log-viewer"), i18n("Log and Messages")); - m_outputWidget = new KileWidget::OutputView(this); - m_outputWidget->setFocusPolicy(Qt::ClickFocus); - m_outputWidget->setMinimumHeight(40); - m_outputWidget->setReadOnly(true); - m_bottomBar->addPage(m_outputWidget, QIcon::fromTheme("output_win"), i18n("Output")); + m_outputWidget = new KileWidget::OutputView(this); + m_outputWidget->setFocusPolicy(Qt::ClickFocus); + m_outputWidget->setMinimumHeight(40); + m_outputWidget->setReadOnly(true); + m_bottomBar->addPage(m_outputWidget, QIcon::fromTheme("output_win"), i18n("Output")); - m_texKonsole = new KileWidget::Konsole(this, this); - m_bottomBar->addPage(m_texKonsole, QIcon::fromTheme("utilities-terminal"),i18n("Konsole")); - connect(viewManager(), static_cast(&KileView::Manager::currentViewChanged), - m_texKonsole, static_cast(&KileWidget::Konsole::sync)); + m_texKonsole = new KileWidget::Konsole(this, this); + m_bottomBar->addPage(m_texKonsole, QIcon::fromTheme("utilities-terminal"),i18n("Konsole")); + connect(viewManager(), static_cast(&KileView::Manager::currentViewChanged), + m_texKonsole, static_cast(&KileWidget::Konsole::sync)); - m_previewWidget = new KileWidget::PreviewWidget(this, m_bottomBar); - m_bottomBar->addPage(m_previewWidget, QIcon::fromTheme ("document-preview"), i18n ("Preview")); + m_previewWidget = new KileWidget::PreviewWidget(this, m_bottomBar); + m_bottomBar->addPage(m_previewWidget, QIcon::fromTheme ("document-preview"), i18n ("Preview")); - m_bottomBar->setVisible(true); - m_bottomBar->switchToTab(KileConfig::bottomBarIndex()); - m_bottomBar->setDirectionalSize(KileConfig::bottomBarSize()); + m_bottomBar->setVisible(true); + m_bottomBar->switchToTab(KileConfig::bottomBarIndex()); + m_bottomBar->setDirectionalSize(KileConfig::bottomBarSize()); } void Kile::setupGraphicTools() { - KileConfig::setImagemagick(!(QStandardPaths::findExecutable("identify").isNull())); + KileConfig::setImagemagick(!(QStandardPaths::findExecutable("identify").isNull())); } void Kile::setupPreviewTools() { - // search for tools - bool dvipng = !(QStandardPaths::findExecutable("dvipng").isNull()); - bool convert = !(QStandardPaths::findExecutable("convert").isNull()); + // search for tools + bool dvipng = !(QStandardPaths::findExecutable("dvipng").isNull()); + bool convert = !(QStandardPaths::findExecutable("convert").isNull()); - KileConfig::setDvipng(dvipng); - KileConfig::setConvert(convert); + KileConfig::setDvipng(dvipng); + KileConfig::setConvert(convert); - // disable some previews, if tools are missing - if ( ! dvipng ) - { - KileConfig::setMathgroupPreviewInWidget(false); // no mathgroup preview in bottom bar - if ( ! convert ) - { - KileConfig::setEnvPreviewInWidget(false); // no preview in bottom bar at all - KileConfig::setSelPreviewInWidget(false); - } - } + // disable some previews, if tools are missing + if ( ! dvipng ) + { + KileConfig::setMathgroupPreviewInWidget(false); // no mathgroup preview in bottom bar + if ( ! convert ) + { + KileConfig::setEnvPreviewInWidget(false); // no preview in bottom bar at all + KileConfig::setSelPreviewInWidget(false); + } + } } QAction * Kile::createAction(const QString &text, const QString &name, const QObject *receiver, const char *member) { - return createAction(text, name, QString(), QKeySequence(), receiver, member); + return createAction(text, name, QString(), QKeySequence(), receiver, member); } QAction * Kile::createAction(const QString &text, const QString &name, const QKeySequence& shortcut, const QObject *receiver, const char *member) { - return createAction(text, name, QString(), shortcut, receiver, member); + return createAction(text, name, QString(), shortcut, receiver, member); } QAction * Kile::createAction(const QString &text, const QString &name, const QString& iconName, const QObject *receiver, const char *member) { - return createAction(text, name, iconName, QKeySequence(), receiver, member); + return createAction(text, name, iconName, QKeySequence(), receiver, member); } QAction * Kile::createAction(const QString &text, const QString &name, const QString& iconName, const QKeySequence& shortcut, const QObject *receiver, const char *member) { - QAction *action = actionCollection()->addAction(name, receiver, member); - action->setText(text); - if(!shortcut.isEmpty()) { - actionCollection()->setDefaultShortcut(action, shortcut); - } - if(!iconName.isEmpty()) { - action->setIcon(QIcon::fromTheme(iconName)); - } - return action; + QAction *action = actionCollection()->addAction(name, receiver, member); + action->setText(text); + if(!shortcut.isEmpty()) { + actionCollection()->setDefaultShortcut(action, shortcut); + } + if(!iconName.isEmpty()) { + action->setIcon(QIcon::fromTheme(iconName)); + } + return action; } QAction * Kile::createAction(KStandardAction::StandardAction actionType, const QString &name, const QObject *receiver, const char *member) { - return actionCollection()->addAction(actionType, name, receiver, member); + return actionCollection()->addAction(actionType, name, receiver, member); } void Kile::setupActions() { - QAction *act; - - m_paPrint = createAction(KStandardAction::Print, "file_print", Q_NULLPTR, Q_NULLPTR); - createAction(KStandardAction::New, "file_new", docManager(), SLOT(fileNew())); - createAction(KStandardAction::Open, "file_open", docManager(), SLOT(fileOpen())); - - m_actRecentFiles = static_cast(actionCollection()->addAction(KStandardAction::OpenRecent, "file_open_recent", docManager(), SLOT(fileOpen(const QUrl&)))); - connect(docManager(), SIGNAL(addToRecentFiles(const QUrl&)), this, SLOT(addRecentFile(const QUrl&))); - m_actRecentFiles->loadEntries(m_config->group("Recent Files")); - - createAction(i18n("Save All"), "file_save_all", "document-save-all", docManager(), SLOT(fileSaveAll())); - createAction(i18n("Save Copy As..."), "file_save_copy_as", docManager(), SLOT(fileSaveCopyAs())); - createAction(i18n("Create Template From Document..."), "template_create", docManager(), SLOT(createTemplate())); - createAction(i18n("&Remove Template..."), "template_remove", docManager(), SLOT(removeTemplate())); - createAction(KStandardAction::Close, "file_close", docManager(), SLOT(fileClose())); - createAction(i18n("Close All"), "file_close_all", docManager(), SLOT(fileCloseAll())); - createAction(i18n("Close All Ot&hers"), "file_close_all_others", docManager(), SLOT(fileCloseAllOthers())); - createAction(i18n("S&tatistics"), "Statistics", this, SLOT(showDocInfo())); - createAction(i18n("&ASCII"), "file_export_ascii", this, SLOT(convertToASCII())); - createAction(i18n("Latin-&1 (iso 8859-1)"), "file_export_latin1", this, SLOT(convertToEnc())); - createAction(i18n("Latin-&2 (iso 8859-2)"), "file_export_latin2", this, SLOT(convertToEnc())); - createAction(i18n("Latin-&3 (iso 8859-3)"), "file_export_latin3", this, SLOT(convertToEnc())); - createAction(i18n("Latin-&4 (iso 8859-4)"), "file_export_latin4", this, SLOT(convertToEnc())); - createAction(i18n("Latin-&5 (iso 8859-5)"), "file_export_latin5", this, SLOT(convertToEnc())); - createAction(i18n("Latin-&9 (iso 8859-9)"), "file_export_latin9", this, SLOT(convertToEnc())); - createAction(i18n("&Central European (cp-1250)"), "file_export_cp1250", this, SLOT(convertToEnc())); - createAction(i18n("&Western European (cp-1252)"), "file_export_cp1252", this, SLOT(convertToEnc())); - createAction(KStandardAction::Quit, "file_quit", this, SLOT(close())); - - createAction(i18n("Move Tab Left"), "move_view_tab_left", "arrow-left", viewManager(), SLOT(moveTabLeft())); - createAction(i18n("Move Tab Right"), "move_view_tab_right", "arrow-right", viewManager(), SLOT(moveTabRight())); - - createAction(i18n("Next section"), "edit_next_section", "nextsection", QKeySequence(Qt::ALT + Qt::Key_Down), m_edit, SLOT(gotoNextSectioning())); - createAction(i18n("Prev section"), "edit_prev_section", "prevsection", QKeySequence(Qt::ALT + Qt::Key_Up), m_edit, SLOT(gotoPrevSectioning())); - createAction(i18n("Next paragraph"), "edit_next_paragraph", "nextparagraph", QKeySequence(Qt::ALT + Qt::SHIFT + Qt::Key_Down), m_edit, SLOT(gotoNextParagraph())); - createAction(i18n("Prev paragraph"), "edit_prev_paragraph", "prevparagraph", QKeySequence(Qt::ALT + Qt::SHIFT + Qt::Key_Up), m_edit, SLOT(gotoPrevParagraph())); - - createAction(i18n("Find &in Files..."), "FindInFiles", "filegrep", this, SLOT(findInFiles())); - - createAction(i18n("Refresh Str&ucture"), "RefreshStructure", "refreshstructure", QKeySequence(Qt::Key_F12), this, SLOT(refreshStructure())); - - //project actions - createAction(i18n("&New Project..."), "project_new", "window-new", docManager(), SLOT(projectNew())); - createAction(i18n("&Open Project..."), "project_open", "project-open", docManager(), SLOT(projectOpen())); - - m_actRecentProjects = new KRecentFilesAction(i18n("Open &Recent Project"), actionCollection()); - actionCollection()->addAction("project_openrecent", m_actRecentProjects); - connect(m_actRecentProjects, SIGNAL(urlSelected(const QUrl&)), docManager(), SLOT(projectOpen(const QUrl&))); - connect(docManager(), SIGNAL(removeFromRecentProjects(const QUrl&)), this, SLOT(removeRecentProject(const QUrl&))); - connect(docManager(), SIGNAL(addToRecentProjects(const QUrl& )), this, SLOT(addRecentProject(const QUrl&))); - m_actRecentProjects->loadEntries(m_config->group("Projects")); - - createAction(i18n("A&dd Files to Project..."), "project_add", "project_add", docManager(), SLOT(projectAddFiles())); - createAction(i18n("Refresh Project &Tree"), "project_buildtree", "project_rebuild", docManager(), SLOT(buildProjectTree())); - createAction(i18n("&Archive"), "project_archive", "project_archive", this, SLOT(runArchiveTool())); - createAction(i18n("Project &Options"), "project_options", "configure_project", docManager(), SLOT(projectOptions())); - createAction(i18n("&Close Project"), "project_close", "project-development-close", docManager(), SLOT(projectClose())); - - // new project actions (dani) - createAction(i18n("&Show Projects..."), "project_show", docManager(), SLOT(projectShow())); - createAction(i18n("Re&move Files From Project..."), "project_remove", "project_remove", docManager(), SLOT(projectRemoveFiles())); - createAction(i18n("Show Project &Files..."), "project_showfiles", "project_show", docManager(), SLOT(projectShowFiles())); - // tbraun - createAction(i18n("Open All &Project Files"), "project_openallfiles", docManager(), SLOT(projectOpenAllFiles())); - createAction(i18n("Find in &Project..."), "project_findfiles", "projectgrep", this, SLOT(findInProjects())); - - //build actions - act = createAction(i18n("Clean"),"CleanAll", "user-trash", this, SLOT(cleanAll())); - m_paStop = createAction(i18n("&Stop"),"Stop", "process-stop", QKeySequence(Qt::Key_Escape)); - m_paStop->setEnabled(false); - m_latexOutputErrorToolBar->addAction(m_paStop); - - errorHandler()->setErrorHandlerToolBar(m_latexOutputErrorToolBar); - - createAction(i18n("Next Document"), "gotoNextDocument", "go-next-view-page", QKeySequence(Qt::ALT + Qt::Key_Right), viewManager(), SLOT(gotoNextView())); - createAction(i18n("Previous Document"), "gotoPrevDocument", "go-previous-view-page", QKeySequence(Qt::ALT + Qt::Key_Left), viewManager(), SLOT(gotoPrevView())); - createAction(i18n("Focus Log/Messages View"), "focus_log", QKeySequence("CTRL+Alt+M"), this, SLOT(focusLog())); - createAction(i18n("Focus Output View"), "focus_output", QKeySequence("CTRL+Alt+O"), this, SLOT(focusOutput())); - createAction(i18n("Focus Konsole View"), "focus_konsole", QKeySequence("CTRL+Alt+K"), this, SLOT(focusKonsole())); - createAction(i18n("Focus Editor View"), "focus_editor", QKeySequence("CTRL+Alt+F"), this, SLOT(focusEditor())); - - createAction(i18nc("@action: Starts the completion of the current LaTeX command", "Complete (La)TeX Command"), "edit_complete_word", "complete1", QKeySequence(Qt::SHIFT + Qt::CTRL + Qt::Key_Space), codeCompletionManager(), SLOT(startLaTeXCompletion())); - createAction(i18nc("@action: Starts the input (and completion) of a LaTeX environment", "Complete LaTeX Environment"), "edit_complete_env", "complete2", QKeySequence(Qt::SHIFT + Qt::ALT + Qt::Key_Space), codeCompletionManager(), SLOT(startLaTeXEnvironment())); - createAction(i18nc("@action: Starts the completion of the current abbreviation", "Complete Abbreviation"), "edit_complete_abbrev", "complete3", QKeySequence(Qt::CTRL + Qt::ALT + Qt::Key_Space), codeCompletionManager(), SLOT(startAbbreviationCompletion())); - - createAction(i18n("Next Bullet"), "edit_next_bullet", "nextbullet", QKeySequence(Qt::CTRL + Qt::ALT + Qt::Key_Right), m_edit, SLOT(nextBullet())); - createAction(i18n("Prev Bullet"), "edit_prev_bullet", "prevbullet", QKeySequence(Qt::CTRL + Qt::ALT + Qt::Key_Left), m_edit, SLOT(prevBullet())); - - // advanced editor (dani) - createAction(i18n("Environment (inside)"), "edit_select_inside_env", "selenv_i", QKeySequence("CTRL+Alt+S, E"), m_edit, SLOT(selectEnvInside())); - createAction(i18n("Environment (outside)"), "edit_select_outside_env", "selenv_o", QKeySequence("CTRL+Alt+S, F"), m_edit, SLOT(selectEnvOutside())); - createAction(i18n("TeX Group (inside)"), "edit_select_inside_group", "selgroup_i", QKeySequence("CTRL+Alt+S, T"), m_edit, SLOT(selectTexgroupInside())); - createAction(i18n("TeX Group (outside)"), "edit_select_outside_group", "selgroup_o", QKeySequence("CTRL+Alt+S, U"),m_edit, SLOT(selectTexgroupOutside())); - createAction(i18n("Math Group"), "edit_select_mathgroup", "selmath", QKeySequence("CTRL+Alt+S, M"), m_edit, SLOT(selectMathgroup())); - createAction(i18n("Paragraph"), "edit_select_paragraph", "selpar", QKeySequence("CTRL+Alt+S, P"), m_edit, SLOT(selectParagraph())); - createAction(i18n("Line"), "edit_select_line", "selline", QKeySequence("CTRL+Alt+S, L"), m_edit, SLOT(selectLine())); - createAction(i18n("TeX Word"), "edit_select_word", "selword", QKeySequence("CTRL+Alt+S, W"), m_edit, SLOT(selectWord())); - - createAction(i18n("Environment (inside)"), "edit_delete_inside_env", "delenv_i", QKeySequence("CTRL+Alt+T, E"), m_edit, SLOT(deleteEnvInside())); - createAction(i18n("Environment (outside)"), "edit_delete_outside_env", "delenv_o", QKeySequence("CTRL+Alt+T, F"), m_edit, SLOT(deleteEnvOutside())); - createAction(i18n("TeX Group (inside)"), "edit_delete_inside_group", "delgroup_i", QKeySequence("CTRL+Alt+T, T"), m_edit, SLOT(deleteTexgroupInside())); - createAction(i18n("TeX Group (outside)"), "edit_delete_outside_group", "delgroup_o",QKeySequence("CTRL+Alt+T, U"),m_edit, SLOT(deleteTexgroupInside())); - createAction(i18n("Math Group"), "edit_delete_mathgroup", "delmath", QKeySequence("CTRL+Alt+T, M"), m_edit, SLOT(deleteMathgroup())); - createAction(i18n("Paragraph"), "edit_delete_paragraph", "delpar", QKeySequence("CTRL+Alt+T, P"), m_edit, SLOT(deleteParagraph())); - createAction(i18n("To End of Line"), "edit_delete_eol", "deleol", QKeySequence("CTRL+Alt+T, L"), m_edit, SLOT(deleteEndOfLine())); - createAction(i18n("TeX Word"), "edit_delete_word", "delword", QKeySequence("CTRL+Alt+T, W"), m_edit, SLOT(deleteWord())); - - createAction(i18n("Go to Begin"), "edit_begin_env", "gotobeginenv", QKeySequence("CTRL+Alt+E, B"), m_edit, SLOT(gotoBeginEnv())); - createAction(i18n("Go to End"), "edit_end_env", "gotoendenv", QKeySequence("CTRL+Alt+E, E"), m_edit, SLOT(gotoEndEnv())); - createAction(i18n("Match"), "edit_match_env", "matchenv", QKeySequence("CTRL+Alt+E, M"), m_edit, SLOT(matchEnv())); - createAction(i18n("Close"), "edit_close_env", "closeenv", QKeySequence("CTRL+Alt+E, C"), m_edit, SLOT(closeEnv())); - createAction(i18n("Close All"), "edit_closeall_env", "closeallenv", QKeySequence("CTRL+Alt+E, A"), m_edit, SLOT(closeAllEnv())); - - createAction(i18n("Go to Begin"), "edit_begin_group", "gotobegingroup", QKeySequence("CTRL+Alt+G, B"), m_edit, SLOT(gotoBeginTexgroup())); - createAction(i18n("Go to End"), "edit_end_group", "gotoendgroup", QKeySequence("CTRL+Alt+G, E"), m_edit, SLOT(gotoEndTexgroup())); - createAction(i18n("Match"), "edit_match_group", "matchgroup", QKeySequence("CTRL+Alt+G, M"), m_edit, SLOT(matchTexgroup())); - createAction(i18n("Close"), "edit_close_group", "closegroup", QKeySequence("CTRL+Alt+G, C"), m_edit, SLOT(closeTexgroup())); - - createAction(i18n("Selection"), "quickpreview_selection", "preview_sel", QKeySequence("CTRL+Alt+P, S"), this, SLOT(quickPreviewSelection())); - createAction(i18n("Environment"), "quickpreview_environment", "preview_env",QKeySequence("CTRL+Alt+P, E"), this, SLOT(quickPreviewEnvironment())); - createAction(i18n("Subdocument"), "quickpreview_subdocument", "preview_subdoc",QKeySequence("CTRL+Alt+P, D"), this, SLOT(quickPreviewSubdocument())); - createAction(i18n("Mathgroup"), "quickpreview_math", "preview_math", QKeySequence("CTRL+Alt+P, M"), this, SLOT(quickPreviewMathgroup())); - - KileStdActions::setupStdTags(this, this, actionCollection(), this); - KileStdActions::setupMathTags(this, actionCollection()); - - m_bibTagActionMenu = new KActionMenu(i18n("&Bibliography"), actionCollection()); - m_bibTagActionMenu->setDelayed(false); - actionCollection()->addAction("menu_bibliography", m_bibTagActionMenu); - - createAction(i18n("Clean"), "CleanBib", this, SLOT(cleanBib())); - - m_bibTagSettings = new KSelectAction(i18n("&Settings"),actionCollection()); - actionCollection()->addAction("settings_menu_bibliography", m_bibTagSettings); - - act = createAction(i18n("Settings for BibTeX"), "setting_bibtex", this, SLOT(rebuildBibliographyMenu())); - act->setCheckable(true); - m_bibTagSettings->addAction(act); - - act = createAction(i18n("Settings for Biblatex"), "setting_biblatex", this, SLOT(rebuildBibliographyMenu())); - act->setCheckable(true); - m_bibTagSettings->addAction(act); - m_bibTagSettings->setCurrentAction(action((QString("setting_") + KileConfig::bibliographyType()).toLatin1())); - - rebuildBibliographyMenu(); - - createAction(i18n("Quick Start"), "wizard_document", "quickwizard", this, SLOT(quickDocument())); - connect(docManager(), SIGNAL(startWizard()), this, SLOT(quickDocument())); - createAction(i18n("Tabular"), "wizard_tabular", "wizard_tabular", this, SLOT(quickTabular())); - createAction(i18n("Array"), "wizard_array", "wizard_array", this, SLOT(quickArray())); - createAction(i18n("Tabbing"), "wizard_tabbing", "wizard_tabbing", this, SLOT(quickTabbing())); - createAction(i18n("Floats"), "wizard_float", "wizard_float", this, SLOT(quickFloat())); - createAction(i18n("Math"), "wizard_mathenv", "wizard_math", this, SLOT(quickMathenv())); - createAction(i18n("Postscript Tools"), "wizard_postscript", "wizard_pstools", this, SLOT(quickPostscript())); - createAction(i18n("PDF Tools"), "wizard_pdf", "wizard_pdftools", this, SLOT(quickPdf())); - - ModeAction = new KToggleAction(i18n("Define Current Document as '&Master Document'"), actionCollection()); - actionCollection()->addAction("Mode", ModeAction); - ModeAction->setIcon(QIcon::fromTheme("master")); - connect(ModeAction, SIGNAL(triggered()), this, SLOT(toggleMasterDocumentMode())); - - if(viewManager()->viewerPart()) { - KToggleAction *showDocumentViewer = new KToggleAction(i18n("Show Document Viewer"), actionCollection()); - actionCollection()->addAction("ShowDocumentViewer", showDocumentViewer); - showDocumentViewer->setChecked(KileConfig::showDocumentViewer()); - connect(showDocumentViewer, SIGNAL(toggled(bool)), viewManager(), SLOT(setDocumentViewerVisible(bool))); - connect(viewManager(), SIGNAL(documentViewerWindowVisibilityChanged(bool)), - showDocumentViewer, SLOT(setChecked(bool))); - } + QAction *act; + + m_paPrint = createAction(KStandardAction::Print, "file_print", Q_NULLPTR, Q_NULLPTR); + createAction(KStandardAction::New, "file_new", docManager(), SLOT(fileNew())); + createAction(KStandardAction::Open, "file_open", docManager(), SLOT(fileOpen())); + + m_actRecentFiles = static_cast(actionCollection()->addAction(KStandardAction::OpenRecent, "file_open_recent", docManager(), SLOT(fileOpen(const QUrl&)))); + connect(docManager(), SIGNAL(addToRecentFiles(const QUrl&)), this, SLOT(addRecentFile(const QUrl&))); + m_actRecentFiles->loadEntries(m_config->group("Recent Files")); + + createAction(i18n("Save All"), "file_save_all", "document-save-all", docManager(), SLOT(fileSaveAll())); + createAction(i18n("Save Copy As..."), "file_save_copy_as", docManager(), SLOT(fileSaveCopyAs())); + createAction(i18n("Create Template From Document..."), "template_create", docManager(), SLOT(createTemplate())); + createAction(i18n("&Remove Template..."), "template_remove", docManager(), SLOT(removeTemplate())); + createAction(KStandardAction::Close, "file_close", docManager(), SLOT(fileClose())); + createAction(i18n("Close All"), "file_close_all", docManager(), SLOT(fileCloseAll())); + createAction(i18n("Close All Ot&hers"), "file_close_all_others", docManager(), SLOT(fileCloseAllOthers())); + createAction(i18n("S&tatistics"), "Statistics", this, SLOT(showDocInfo())); + createAction(i18n("&ASCII"), "file_export_ascii", this, SLOT(convertToASCII())); + createAction(i18n("Latin-&1 (iso 8859-1)"), "file_export_latin1", this, SLOT(convertToEnc())); + createAction(i18n("Latin-&2 (iso 8859-2)"), "file_export_latin2", this, SLOT(convertToEnc())); + createAction(i18n("Latin-&3 (iso 8859-3)"), "file_export_latin3", this, SLOT(convertToEnc())); + createAction(i18n("Latin-&4 (iso 8859-4)"), "file_export_latin4", this, SLOT(convertToEnc())); + createAction(i18n("Latin-&5 (iso 8859-5)"), "file_export_latin5", this, SLOT(convertToEnc())); + createAction(i18n("Latin-&9 (iso 8859-9)"), "file_export_latin9", this, SLOT(convertToEnc())); + createAction(i18n("&Central European (cp-1250)"), "file_export_cp1250", this, SLOT(convertToEnc())); + createAction(i18n("&Western European (cp-1252)"), "file_export_cp1252", this, SLOT(convertToEnc())); + createAction(KStandardAction::Quit, "file_quit", this, SLOT(close())); + + createAction(i18n("Move Tab Left"), "move_view_tab_left", "arrow-left", viewManager(), SLOT(moveTabLeft())); + createAction(i18n("Move Tab Right"), "move_view_tab_right", "arrow-right", viewManager(), SLOT(moveTabRight())); + + createAction(i18n("Next section"), "edit_next_section", "nextsection", QKeySequence(Qt::ALT + Qt::Key_Down), m_edit, SLOT(gotoNextSectioning())); + createAction(i18n("Prev section"), "edit_prev_section", "prevsection", QKeySequence(Qt::ALT + Qt::Key_Up), m_edit, SLOT(gotoPrevSectioning())); + createAction(i18n("Next paragraph"), "edit_next_paragraph", "nextparagraph", QKeySequence(Qt::ALT + Qt::SHIFT + Qt::Key_Down), m_edit, SLOT(gotoNextParagraph())); + createAction(i18n("Prev paragraph"), "edit_prev_paragraph", "prevparagraph", QKeySequence(Qt::ALT + Qt::SHIFT + Qt::Key_Up), m_edit, SLOT(gotoPrevParagraph())); + + createAction(i18n("Find &in Files..."), "FindInFiles", "filegrep", this, SLOT(findInFiles())); + + createAction(i18n("Refresh Str&ucture"), "RefreshStructure", "refreshstructure", QKeySequence(Qt::Key_F12), this, SLOT(refreshStructure())); + + //project actions + createAction(i18n("&New Project..."), "project_new", "window-new", docManager(), SLOT(projectNew())); + createAction(i18n("&Open Project..."), "project_open", "project-open", docManager(), SLOT(projectOpen())); + + m_actRecentProjects = new KRecentFilesAction(i18n("Open &Recent Project"), actionCollection()); + actionCollection()->addAction("project_openrecent", m_actRecentProjects); + connect(m_actRecentProjects, SIGNAL(urlSelected(const QUrl&)), docManager(), SLOT(projectOpen(const QUrl&))); + connect(docManager(), SIGNAL(removeFromRecentProjects(const QUrl&)), this, SLOT(removeRecentProject(const QUrl&))); + connect(docManager(), SIGNAL(addToRecentProjects(const QUrl& )), this, SLOT(addRecentProject(const QUrl&))); + m_actRecentProjects->loadEntries(m_config->group("Projects")); + + createAction(i18n("A&dd Files to Project..."), "project_add", "project_add", docManager(), SLOT(projectAddFiles())); + createAction(i18n("Refresh Project &Tree"), "project_buildtree", "project_rebuild", docManager(), SLOT(buildProjectTree())); + createAction(i18n("&Archive"), "project_archive", "project_archive", this, SLOT(runArchiveTool())); + createAction(i18n("Project &Options"), "project_options", "configure_project", docManager(), SLOT(projectOptions())); + createAction(i18n("&Close Project"), "project_close", "project-development-close", docManager(), SLOT(projectClose())); + + // new project actions (dani) + createAction(i18n("&Show Projects..."), "project_show", docManager(), SLOT(projectShow())); + createAction(i18n("Re&move Files From Project..."), "project_remove", "project_remove", docManager(), SLOT(projectRemoveFiles())); + createAction(i18n("Show Project &Files..."), "project_showfiles", "project_show", docManager(), SLOT(projectShowFiles())); + // tbraun + createAction(i18n("Open All &Project Files"), "project_openallfiles", docManager(), SLOT(projectOpenAllFiles())); + createAction(i18n("Find in &Project..."), "project_findfiles", "projectgrep", this, SLOT(findInProjects())); + + //build actions + act = createAction(i18n("Clean"),"CleanAll", "user-trash", this, SLOT(cleanAll())); + m_paStop = createAction(i18n("&Stop"),"Stop", "process-stop", QKeySequence(Qt::Key_Escape)); + m_paStop->setEnabled(false); + m_latexOutputErrorToolBar->addAction(m_paStop); + + errorHandler()->setErrorHandlerToolBar(m_latexOutputErrorToolBar); + + createAction(i18n("Next Document"), "gotoNextDocument", "go-next-view-page", QKeySequence(Qt::ALT + Qt::Key_Right), viewManager(), SLOT(gotoNextView())); + createAction(i18n("Previous Document"), "gotoPrevDocument", "go-previous-view-page", QKeySequence(Qt::ALT + Qt::Key_Left), viewManager(), SLOT(gotoPrevView())); + createAction(i18n("Focus Log/Messages View"), "focus_log", QKeySequence("CTRL+Alt+M"), this, SLOT(focusLog())); + createAction(i18n("Focus Output View"), "focus_output", QKeySequence("CTRL+Alt+O"), this, SLOT(focusOutput())); + createAction(i18n("Focus Konsole View"), "focus_konsole", QKeySequence("CTRL+Alt+K"), this, SLOT(focusKonsole())); + createAction(i18n("Focus Editor View"), "focus_editor", QKeySequence("CTRL+Alt+F"), this, SLOT(focusEditor())); + + createAction(i18nc("@action: Starts the completion of the current LaTeX command", "Complete (La)TeX Command"), "edit_complete_word", "complete1", QKeySequence(Qt::SHIFT + Qt::CTRL + Qt::Key_Space), codeCompletionManager(), SLOT(startLaTeXCompletion())); + createAction(i18nc("@action: Starts the input (and completion) of a LaTeX environment", "Complete LaTeX Environment"), "edit_complete_env", "complete2", QKeySequence(Qt::SHIFT + Qt::ALT + Qt::Key_Space), codeCompletionManager(), SLOT(startLaTeXEnvironment())); + createAction(i18nc("@action: Starts the completion of the current abbreviation", "Complete Abbreviation"), "edit_complete_abbrev", "complete3", QKeySequence(Qt::CTRL + Qt::ALT + Qt::Key_Space), codeCompletionManager(), SLOT(startAbbreviationCompletion())); + + createAction(i18n("Next Bullet"), "edit_next_bullet", "nextbullet", QKeySequence(Qt::CTRL + Qt::ALT + Qt::Key_Right), m_edit, SLOT(nextBullet())); + createAction(i18n("Prev Bullet"), "edit_prev_bullet", "prevbullet", QKeySequence(Qt::CTRL + Qt::ALT + Qt::Key_Left), m_edit, SLOT(prevBullet())); + +// advanced editor (dani) + createAction(i18n("Environment (inside)"), "edit_select_inside_env", "selenv_i", QKeySequence("CTRL+Alt+S, E"), m_edit, SLOT(selectEnvInside())); + createAction(i18n("Environment (outside)"), "edit_select_outside_env", "selenv_o", QKeySequence("CTRL+Alt+S, F"), m_edit, SLOT(selectEnvOutside())); + createAction(i18n("TeX Group (inside)"), "edit_select_inside_group", "selgroup_i", QKeySequence("CTRL+Alt+S, T"), m_edit, SLOT(selectTexgroupInside())); + createAction(i18n("TeX Group (outside)"), "edit_select_outside_group", "selgroup_o", QKeySequence("CTRL+Alt+S, U"),m_edit, SLOT(selectTexgroupOutside())); + createAction(i18n("Math Group"), "edit_select_mathgroup", "selmath", QKeySequence("CTRL+Alt+S, M"), m_edit, SLOT(selectMathgroup())); + createAction(i18n("Paragraph"), "edit_select_paragraph", "selpar", QKeySequence("CTRL+Alt+S, P"), m_edit, SLOT(selectParagraph())); + createAction(i18n("Line"), "edit_select_line", "selline", QKeySequence("CTRL+Alt+S, L"), m_edit, SLOT(selectLine())); + createAction(i18n("TeX Word"), "edit_select_word", "selword", QKeySequence("CTRL+Alt+S, W"), m_edit, SLOT(selectWord())); + + createAction(i18n("Environment (inside)"), "edit_delete_inside_env", "delenv_i", QKeySequence("CTRL+Alt+T, E"), m_edit, SLOT(deleteEnvInside())); + createAction(i18n("Environment (outside)"), "edit_delete_outside_env", "delenv_o", QKeySequence("CTRL+Alt+T, F"), m_edit, SLOT(deleteEnvOutside())); + createAction(i18n("TeX Group (inside)"), "edit_delete_inside_group", "delgroup_i", QKeySequence("CTRL+Alt+T, T"), m_edit, SLOT(deleteTexgroupInside())); + createAction(i18n("TeX Group (outside)"), "edit_delete_outside_group", "delgroup_o",QKeySequence("CTRL+Alt+T, U"),m_edit, SLOT(deleteTexgroupInside())); + createAction(i18n("Math Group"), "edit_delete_mathgroup", "delmath", QKeySequence("CTRL+Alt+T, M"), m_edit, SLOT(deleteMathgroup())); + createAction(i18n("Paragraph"), "edit_delete_paragraph", "delpar", QKeySequence("CTRL+Alt+T, P"), m_edit, SLOT(deleteParagraph())); + createAction(i18n("To End of Line"), "edit_delete_eol", "deleol", QKeySequence("CTRL+Alt+T, L"), m_edit, SLOT(deleteEndOfLine())); + createAction(i18n("TeX Word"), "edit_delete_word", "delword", QKeySequence("CTRL+Alt+T, W"), m_edit, SLOT(deleteWord())); + + createAction(i18n("Go to Begin"), "edit_begin_env", "gotobeginenv", QKeySequence("CTRL+Alt+E, B"), m_edit, SLOT(gotoBeginEnv())); + createAction(i18n("Go to End"), "edit_end_env", "gotoendenv", QKeySequence("CTRL+Alt+E, E"), m_edit, SLOT(gotoEndEnv())); + createAction(i18n("Match"), "edit_match_env", "matchenv", QKeySequence("CTRL+Alt+E, M"), m_edit, SLOT(matchEnv())); + createAction(i18n("Close"), "edit_close_env", "closeenv", QKeySequence("CTRL+Alt+E, C"), m_edit, SLOT(closeEnv())); + createAction(i18n("Close All"), "edit_closeall_env", "closeallenv", QKeySequence("CTRL+Alt+E, A"), m_edit, SLOT(closeAllEnv())); + + createAction(i18n("Go to Begin"), "edit_begin_group", "gotobegingroup", QKeySequence("CTRL+Alt+G, B"), m_edit, SLOT(gotoBeginTexgroup())); + createAction(i18n("Go to End"), "edit_end_group", "gotoendgroup", QKeySequence("CTRL+Alt+G, E"), m_edit, SLOT(gotoEndTexgroup())); + createAction(i18n("Match"), "edit_match_group", "matchgroup", QKeySequence("CTRL+Alt+G, M"), m_edit, SLOT(matchTexgroup())); + createAction(i18n("Close"), "edit_close_group", "closegroup", QKeySequence("CTRL+Alt+G, C"), m_edit, SLOT(closeTexgroup())); + + createAction(i18n("Selection"), "quickpreview_selection", "preview_sel", QKeySequence("CTRL+Alt+P, S"), this, SLOT(quickPreviewSelection())); + createAction(i18n("Environment"), "quickpreview_environment", "preview_env",QKeySequence("CTRL+Alt+P, E"), this, SLOT(quickPreviewEnvironment())); + createAction(i18n("Subdocument"), "quickpreview_subdocument", "preview_subdoc",QKeySequence("CTRL+Alt+P, D"), this, SLOT(quickPreviewSubdocument())); + createAction(i18n("Mathgroup"), "quickpreview_math", "preview_math", QKeySequence("CTRL+Alt+P, M"), this, SLOT(quickPreviewMathgroup())); + + KileStdActions::setupStdTags(this, this, actionCollection(), this); + KileStdActions::setupMathTags(this, actionCollection()); + + m_bibTagActionMenu = new KActionMenu(i18n("&Bibliography"), actionCollection()); + m_bibTagActionMenu->setDelayed(false); + actionCollection()->addAction("menu_bibliography", m_bibTagActionMenu); + + createAction(i18n("Clean"), "CleanBib", this, SLOT(cleanBib())); + + m_bibTagSettings = new KSelectAction(i18n("&Settings"),actionCollection()); + actionCollection()->addAction("settings_menu_bibliography", m_bibTagSettings); + + act = createAction(i18n("Settings for BibTeX"), "setting_bibtex", this, SLOT(rebuildBibliographyMenu())); + act->setCheckable(true); + m_bibTagSettings->addAction(act); + + act = createAction(i18n("Settings for Biblatex"), "setting_biblatex", this, SLOT(rebuildBibliographyMenu())); + act->setCheckable(true); + m_bibTagSettings->addAction(act); + m_bibTagSettings->setCurrentAction(action((QString("setting_") + KileConfig::bibliographyType()).toLatin1())); + + rebuildBibliographyMenu(); + + createAction(i18n("Quick Start"), "wizard_document", "quickwizard", this, SLOT(quickDocument())); + connect(docManager(), SIGNAL(startWizard()), this, SLOT(quickDocument())); + createAction(i18n("Tabular"), "wizard_tabular", "wizard_tabular", this, SLOT(quickTabular())); + createAction(i18n("Array"), "wizard_array", "wizard_array", this, SLOT(quickArray())); + createAction(i18n("Tabbing"), "wizard_tabbing", "wizard_tabbing", this, SLOT(quickTabbing())); + createAction(i18n("Floats"), "wizard_float", "wizard_float", this, SLOT(quickFloat())); + createAction(i18n("Math"), "wizard_mathenv", "wizard_math", this, SLOT(quickMathenv())); + createAction(i18n("Postscript Tools"), "wizard_postscript", "wizard_pstools", this, SLOT(quickPostscript())); + createAction(i18n("PDF Tools"), "wizard_pdf", "wizard_pdftools", this, SLOT(quickPdf())); + + ModeAction = new KToggleAction(i18n("Define Current Document as '&Master Document'"), actionCollection()); + actionCollection()->addAction("Mode", ModeAction); + ModeAction->setIcon(QIcon::fromTheme("master")); + connect(ModeAction, SIGNAL(triggered()), this, SLOT(toggleMasterDocumentMode())); + + if(viewManager()->viewerPart()) { + KToggleAction *showDocumentViewer = new KToggleAction(i18n("Show Document Viewer"), actionCollection()); + actionCollection()->addAction("ShowDocumentViewer", showDocumentViewer); + showDocumentViewer->setChecked(KileConfig::showDocumentViewer()); + connect(showDocumentViewer, SIGNAL(toggled(bool)), viewManager(), SLOT(setDocumentViewerVisible(bool))); + connect(viewManager(), SIGNAL(documentViewerWindowVisibilityChanged(bool)), + showDocumentViewer, SLOT(setChecked(bool))); + } - KToggleAction *tact = new KToggleAction(i18n("Show S&ide Bar"), actionCollection()); - actionCollection()->addAction("StructureView", tact); - tact->setChecked(KileConfig::sideBar()); - connect(tact, SIGNAL(toggled(bool)), m_sideBar, SLOT(setVisible(bool))); - connect(m_sideBar, SIGNAL(visibilityChanged(bool)), this, SLOT(sideOrBottomBarChanged(bool))); - - m_actionMessageView = new KToggleAction(i18n("Show Mess&ages Bar"), actionCollection()); - actionCollection()->addAction("MessageView", m_actionMessageView); - m_actionMessageView->setChecked(true); - connect(m_actionMessageView, SIGNAL(toggled(bool)), m_bottomBar, SLOT(setVisible(bool))); - connect(m_bottomBar, SIGNAL(visibilityChanged(bool)), this, SLOT(sideOrBottomBarChanged(bool))); - if(m_singlemode) { - ModeAction->setChecked(false); - } - else { - ModeAction->setChecked(true); - } + KToggleAction *tact = new KToggleAction(i18n("Show S&ide Bar"), actionCollection()); + actionCollection()->addAction("StructureView", tact); + tact->setChecked(KileConfig::sideBar()); + connect(tact, SIGNAL(toggled(bool)), m_sideBar, SLOT(setVisible(bool))); + connect(m_sideBar, SIGNAL(visibilityChanged(bool)), this, SLOT(sideOrBottomBarChanged(bool))); + + m_actionMessageView = new KToggleAction(i18n("Show Mess&ages Bar"), actionCollection()); + actionCollection()->addAction("MessageView", m_actionMessageView); + m_actionMessageView->setChecked(true); + connect(m_actionMessageView, SIGNAL(toggled(bool)), m_bottomBar, SLOT(setVisible(bool))); + connect(m_bottomBar, SIGNAL(visibilityChanged(bool)), this, SLOT(sideOrBottomBarChanged(bool))); + if(m_singlemode) { + ModeAction->setChecked(false); + } + else { + ModeAction->setChecked(true); + } - WatchFileAction = new KToggleAction(i18n("Watch File Mode"), actionCollection()); - actionCollection()->addAction("WatchFile", WatchFileAction); - WatchFileAction->setIcon(QIcon::fromTheme("watchfile")); - connect(WatchFileAction, SIGNAL(triggered()), this, SLOT(toggleWatchFile())); - if(m_bWatchFile) { - WatchFileAction->setChecked(true); - } - else { - WatchFileAction->setChecked(false); - } + WatchFileAction = new KToggleAction(i18n("Watch File Mode"), actionCollection()); + actionCollection()->addAction("WatchFile", WatchFileAction); + WatchFileAction->setIcon(QIcon::fromTheme("watchfile")); + connect(WatchFileAction, SIGNAL(triggered()), this, SLOT(toggleWatchFile())); + if(m_bWatchFile) { + WatchFileAction->setChecked(true); + } + else { + WatchFileAction->setChecked(false); + } - setHelpMenuEnabled(false); + setHelpMenuEnabled(false); - KHelpMenu *help_menu = new KHelpMenu(this, KAboutData::applicationData()); + KHelpMenu *help_menu = new KHelpMenu(this, KAboutData::applicationData()); - createAction(i18n("TeX Guide"), "help_tex_guide", QKeySequence("CTRL+Alt+H, G"), m_help, SLOT(helpTexGuide())); - createAction(i18n("LaTeX"), "help_latex_index", QKeySequence("CTRL+Alt+H, L"), m_help, SLOT(helpLatexIndex())); - createAction(i18n("LaTeX Command"), "help_latex_command", QKeySequence("CTRL+Alt+H, C"), m_help, SLOT(helpLatexCommand())); - createAction(i18n("LaTeX Subject"), "help_latex_subject", QKeySequence("CTRL+Alt+H, S"), m_help, SLOT(helpLatexSubject())); - createAction(i18n("LaTeX Env"), "help_latex_env", QKeySequence("CTRL+Alt+H, E"), m_help, SLOT(helpLatexEnvironment())); - createAction(i18n("Context Help"), "help_context", QKeySequence("CTRL+Alt+H, K"), m_help, SLOT(helpKeyword())); - createAction(i18n("Documentation Browser"), "help_docbrowser", QKeySequence("CTRL+Alt+H, B"), m_help, SLOT(helpDocBrowser())); + createAction(i18n("TeX Guide"), "help_tex_guide", QKeySequence("CTRL+Alt+H, G"), m_help, SLOT(helpTexGuide())); + createAction(i18n("LaTeX"), "help_latex_index", QKeySequence("CTRL+Alt+H, L"), m_help, SLOT(helpLatexIndex())); + createAction(i18n("LaTeX Command"), "help_latex_command", QKeySequence("CTRL+Alt+H, C"), m_help, SLOT(helpLatexCommand())); + createAction(i18n("LaTeX Subject"), "help_latex_subject", QKeySequence("CTRL+Alt+H, S"), m_help, SLOT(helpLatexSubject())); + createAction(i18n("LaTeX Env"), "help_latex_env", QKeySequence("CTRL+Alt+H, E"), m_help, SLOT(helpLatexEnvironment())); + createAction(i18n("Context Help"), "help_context", QKeySequence("CTRL+Alt+H, K"), m_help, SLOT(helpKeyword())); + createAction(i18n("Documentation Browser"), "help_docbrowser", QKeySequence("CTRL+Alt+H, B"), m_help, SLOT(helpDocBrowser())); - createAction(i18n("LaTeX Reference"), "help_latex_reference", "help-latex", this, SLOT(helpLaTex())); + createAction(i18n("LaTeX Reference"), "help_latex_reference", "help-latex", this, SLOT(helpLaTex())); - actionCollection()->addAction(KStandardAction::HelpContents, help_menu, SLOT(appHelpActivated())); - actionCollection()->addAction(KStandardAction::ReportBug, help_menu, SLOT(reportBug())); - act = actionCollection()->addAction(KStandardAction::AboutApp, help_menu, SLOT(aboutApplication())); - act->setMenuRole(QAction::AboutRole); // for Mac OS X, to get the right about menu in the application menu + actionCollection()->addAction(KStandardAction::HelpContents, help_menu, SLOT(appHelpActivated())); + actionCollection()->addAction(KStandardAction::ReportBug, help_menu, SLOT(reportBug())); + act = actionCollection()->addAction(KStandardAction::AboutApp, help_menu, SLOT(aboutApplication())); + act->setMenuRole(QAction::AboutRole); // for Mac OS X, to get the right about menu in the application menu - act = actionCollection()->addAction(KStandardAction::AboutKDE, help_menu, SLOT(aboutKDE())); - act->setMenuRole(QAction::NoRole); - act = createAction(i18n("&About Editor Component"), "help_about_editor", this, SLOT(aboutEditorComponent())); - act->setMenuRole(QAction::NoRole); + act = actionCollection()->addAction(KStandardAction::AboutKDE, help_menu, SLOT(aboutKDE())); + act->setMenuRole(QAction::NoRole); + act = createAction(i18n("&About Editor Component"), "help_about_editor", this, SLOT(aboutEditorComponent())); + act->setMenuRole(QAction::NoRole); - QAction *kileconfig = KStandardAction::preferences(this, SLOT(generalOptions()), actionCollection()); - kileconfig->setIcon(QIcon::fromTheme("configure-kile")); + QAction *kileconfig = KStandardAction::preferences(this, SLOT(generalOptions()), actionCollection()); + kileconfig->setIcon(QIcon::fromTheme("configure-kile")); - actionCollection()->addAction(KStandardAction::KeyBindings, this, SLOT(configureKeys())); - actionCollection()->addAction(KStandardAction::ConfigureToolbars, this, SLOT(configureToolbars())); + actionCollection()->addAction(KStandardAction::KeyBindings, this, SLOT(configureKeys())); + actionCollection()->addAction(KStandardAction::ConfigureToolbars, this, SLOT(configureToolbars())); - createAction(i18n("&System Check..."), "settings_perform_check", this, SLOT(slotPerformCheck())); + createAction(i18n("&System Check..."), "settings_perform_check", this, SLOT(slotPerformCheck())); - m_userHelpActionMenu = new KActionMenu(i18n("User Help"), actionCollection()); - actionCollection()->addAction("help_userhelp", m_userHelpActionMenu); + m_userHelpActionMenu = new KActionMenu(i18n("User Help"), actionCollection()); + actionCollection()->addAction("help_userhelp", m_userHelpActionMenu); - m_pFullScreen = KStandardAction::fullScreen(this, SLOT(slotToggleFullScreen()), this, actionCollection()); + m_pFullScreen = KStandardAction::fullScreen(this, SLOT(slotToggleFullScreen()), this, actionCollection()); } -void Kile::rebuildBibliographyMenu(){ +void Kile::rebuildBibliographyMenu() { - KILE_DEBUG_MAIN << " current is " << m_bibTagSettings->currentText(); + KILE_DEBUG_MAIN << " current is " << m_bibTagSettings->currentText(); - QString currentItem = m_bibTagSettings->currentText(); - QString name; + QString currentItem = m_bibTagSettings->currentText(); + QString name; - if( currentItem == i18n("BibTeX") ){ // avoid writing i18n'ed strings to config file - name = QString("bibtex"); - } - else if ( currentItem == i18n("Biblatex") ){ - name = QString("biblatex"); - } - else { - KILE_DEBUG_MAIN << "wrong currentItem in bibliography settings menu"; - name = QString("bibtex"); - } + if( currentItem == i18n("BibTeX") ) { // avoid writing i18n'ed strings to config file + name = QString("bibtex"); + } + else if ( currentItem == i18n("Biblatex") ) { + name = QString("biblatex"); + } + else { + KILE_DEBUG_MAIN << "wrong currentItem in bibliography settings menu"; + name = QString("bibtex"); + } - KileConfig::setBibliographyType(name); - m_bibTagActionMenu->menu()->clear(); + KileConfig::setBibliographyType(name); + m_bibTagActionMenu->menu()->clear(); - KileStdActions::setupBibTags(this, actionCollection(),m_bibTagActionMenu); - m_bibTagActionMenu->addSeparator(); - m_bibTagActionMenu->addAction(action("CleanBib")); - m_bibTagActionMenu->addSeparator(); - m_bibTagActionMenu->addAction(action("settings_menu_bibliography")); + KileStdActions::setupBibTags(this, actionCollection(),m_bibTagActionMenu); + m_bibTagActionMenu->addSeparator(); + m_bibTagActionMenu->addAction(action("CleanBib")); + m_bibTagActionMenu->addSeparator(); + m_bibTagActionMenu->addAction(action("settings_menu_bibliography")); } QAction* Kile::createToolAction(QString toolName) { - return createAction(toolName, "tool_" + toolName, - KileTool::iconFor(toolName, m_config.data()), m_signalMapper, SLOT(map())); + return createAction(toolName, "tool_" + toolName, + KileTool::iconFor(toolName, m_config.data()), m_signalMapper, SLOT(map())); } void Kile::createToolActions() { - QStringList tools = KileTool::toolList(m_config.data()); - for (QStringList::iterator i = tools.begin(); i != tools.end(); ++i) { - QString toolName = *i; - if(!actionCollection()->action("tool_" + toolName)) { - KILE_DEBUG_MAIN << "Creating action for tool" << toolName; - QAction *act = createToolAction(toolName); - m_signalMapper->removeMappings(act); - m_signalMapper->setMapping(act, toolName); - } - } + QStringList tools = KileTool::toolList(m_config.data()); + for (QStringList::iterator i = tools.begin(); i != tools.end(); ++i) { + QString toolName = *i; + if(!actionCollection()->action("tool_" + toolName)) { + KILE_DEBUG_MAIN << "Creating action for tool" << toolName; + QAction *act = createToolAction(toolName); + m_signalMapper->removeMappings(act); + m_signalMapper->setMapping(act, toolName); + } + } } void Kile::setupTools() { - KILE_DEBUG_MAIN << "==Kile::setupTools()===================" << endl; - - if(!m_buildMenuCompile || !m_buildMenuConvert || !m_buildMenuTopLevel || !m_buildMenuQuickPreview || !m_buildMenuViewer || !m_buildMenuOther){ - KILE_DEBUG_MAIN << "BUG, menu pointers are Q_NULLPTR" - << (m_buildMenuCompile == Q_NULLPTR) - << (m_buildMenuConvert == Q_NULLPTR) - << (m_buildMenuTopLevel == Q_NULLPTR) - << (m_buildMenuQuickPreview == Q_NULLPTR) - << (m_buildMenuViewer == Q_NULLPTR) - << (m_buildMenuOther == Q_NULLPTR); - return; - } - - QStringList tools = KileTool::toolList(m_config.data()); - QString toolMenu, grp; - QList *pl; - QAction *act; - ToolbarSelectAction *pSelectAction = Q_NULLPTR; - - m_compilerActions->saveCurrentAction(); - m_viewActions->saveCurrentAction(); - m_convertActions->saveCurrentAction(); - m_quickActions->saveCurrentAction(); - - // do plugActionList by hand ... - foreach(act, m_listQuickActions){ - m_buildMenuTopLevel->removeAction(act); - } - - m_buildMenuCompile->clear(); - m_buildMenuConvert->clear(); - m_buildMenuViewer->clear(); - m_buildMenuOther->clear(); - - m_compilerActions->removeAllActions(); - m_viewActions->removeAllActions(); - m_convertActions->removeAllActions(); - m_quickActions->removeAllActions(); - - for (int i = 0; i < tools.count(); ++i) { - grp = KileTool::groupFor(tools[i], m_config.data()); - toolMenu = KileTool::menuFor(tools[i], m_config.data()); - - KILE_DEBUG_MAIN << tools[i] << " is using group: " << grp << " and menu: "<< toolMenu; - if(toolMenu == "none") { - continue; - } + KILE_DEBUG_MAIN << "==Kile::setupTools()===================" << endl; + + if(!m_buildMenuCompile || !m_buildMenuConvert || !m_buildMenuTopLevel || !m_buildMenuQuickPreview || !m_buildMenuViewer || !m_buildMenuOther) { + KILE_DEBUG_MAIN << "BUG, menu pointers are Q_NULLPTR" + << (m_buildMenuCompile == Q_NULLPTR) + << (m_buildMenuConvert == Q_NULLPTR) + << (m_buildMenuTopLevel == Q_NULLPTR) + << (m_buildMenuQuickPreview == Q_NULLPTR) + << (m_buildMenuViewer == Q_NULLPTR) + << (m_buildMenuOther == Q_NULLPTR); + return; + } - if ( toolMenu == "Compile" ){ - pl = &m_listCompilerActions; - pSelectAction = m_compilerActions; - } - else if ( toolMenu == "View" ){ - pl = &m_listViewerActions; - pSelectAction = m_viewActions; - } - else if ( toolMenu == "Convert" ){ - pl = &m_listConverterActions; - pSelectAction = m_convertActions; - } - else if ( toolMenu == "Quick" ){ - pl = &m_listQuickActions; - pSelectAction = m_quickActions; - } - else{ - pl = &m_listOtherActions; - pSelectAction = Q_NULLPTR; - } + QStringList tools = KileTool::toolList(m_config.data()); + QString toolMenu, grp; + QList *pl; + QAction *act; + ToolbarSelectAction *pSelectAction = Q_NULLPTR; - KILE_DEBUG_MAIN << "\tadding " << tools[i] << " " << toolMenu << " #" << pl->count() << endl; + m_compilerActions->saveCurrentAction(); + m_viewActions->saveCurrentAction(); + m_convertActions->saveCurrentAction(); + m_quickActions->saveCurrentAction(); - act = actionCollection()->action("tool_" + tools[i]); - if(!act) { - KILE_DEBUG_MAIN << "no tool for " << tools[i]; - act = createToolAction(tools[i]); - m_signalMapper->removeMappings(act); - m_signalMapper->setMapping(act, tools[i]); - } - pl->append(act); + // do plugActionList by hand ... + foreach(act, m_listQuickActions) { + m_buildMenuTopLevel->removeAction(act); + } - if(pSelectAction){ - pSelectAction->addAction(actionCollection()->action("tool_" + tools[i])); - } - } + m_buildMenuCompile->clear(); + m_buildMenuConvert->clear(); + m_buildMenuViewer->clear(); + m_buildMenuOther->clear(); + + m_compilerActions->removeAllActions(); + m_viewActions->removeAllActions(); + m_convertActions->removeAllActions(); + m_quickActions->removeAllActions(); + + for (int i = 0; i < tools.count(); ++i) { + grp = KileTool::groupFor(tools[i], m_config.data()); + toolMenu = KileTool::menuFor(tools[i], m_config.data()); + + KILE_DEBUG_MAIN << tools[i] << " is using group: " << grp << " and menu: "<< toolMenu; + if(toolMenu == "none") { + continue; + } + + if ( toolMenu == "Compile" ) { + pl = &m_listCompilerActions; + pSelectAction = m_compilerActions; + } + else if ( toolMenu == "View" ) { + pl = &m_listViewerActions; + pSelectAction = m_viewActions; + } + else if ( toolMenu == "Convert" ) { + pl = &m_listConverterActions; + pSelectAction = m_convertActions; + } + else if ( toolMenu == "Quick" ) { + pl = &m_listQuickActions; + pSelectAction = m_quickActions; + } + else { + pl = &m_listOtherActions; + pSelectAction = Q_NULLPTR; + } + + KILE_DEBUG_MAIN << "\tadding " << tools[i] << " " << toolMenu << " #" << pl->count() << endl; + + act = actionCollection()->action("tool_" + tools[i]); + if(!act) { + KILE_DEBUG_MAIN << "no tool for " << tools[i]; + act = createToolAction(tools[i]); + m_signalMapper->removeMappings(act); + m_signalMapper->setMapping(act, tools[i]); + } + pl->append(act); + + if(pSelectAction) { + pSelectAction->addAction(actionCollection()->action("tool_" + tools[i])); + } + } - m_quickActions->addSeparator(); - m_quickActions->addAction(action("quickpreview_selection")); - m_quickActions->addAction(action("quickpreview_environment")); - m_quickActions->addAction(action("quickpreview_subdocument")); - m_quickActions->addSeparator(); - m_quickActions->addAction(action("quickpreview_math")); + m_quickActions->addSeparator(); + m_quickActions->addAction(action("quickpreview_selection")); + m_quickActions->addAction(action("quickpreview_environment")); + m_quickActions->addAction(action("quickpreview_subdocument")); + m_quickActions->addSeparator(); + m_quickActions->addAction(action("quickpreview_math")); - cleanUpActionList(m_listCompilerActions, tools); - cleanUpActionList(m_listViewerActions, tools); - cleanUpActionList(m_listConverterActions, tools); - cleanUpActionList(m_listQuickActions, tools); - cleanUpActionList(m_listOtherActions, tools); + cleanUpActionList(m_listCompilerActions, tools); + cleanUpActionList(m_listViewerActions, tools); + cleanUpActionList(m_listConverterActions, tools); + cleanUpActionList(m_listQuickActions, tools); + cleanUpActionList(m_listOtherActions, tools); - m_buildMenuTopLevel->insertActions(m_buildMenuQuickPreview->menuAction(),m_listQuickActions); - m_buildMenuCompile->addActions(m_listCompilerActions); - m_buildMenuConvert->addActions(m_listConverterActions); - m_buildMenuViewer->addActions(m_listViewerActions); - m_buildMenuOther->addActions(m_listOtherActions); + m_buildMenuTopLevel->insertActions(m_buildMenuQuickPreview->menuAction(),m_listQuickActions); + m_buildMenuCompile->addActions(m_listCompilerActions); + m_buildMenuConvert->addActions(m_listConverterActions); + m_buildMenuViewer->addActions(m_listViewerActions); + m_buildMenuOther->addActions(m_listOtherActions); - m_compilerActions->restoreCurrentAction(); - m_viewActions->restoreCurrentAction(); - m_convertActions->restoreCurrentAction(); - m_quickActions->restoreCurrentAction(); + m_compilerActions->restoreCurrentAction(); + m_viewActions->restoreCurrentAction(); + m_convertActions->restoreCurrentAction(); + m_quickActions->restoreCurrentAction(); } -void Kile::initSelectActions(){ +void Kile::initSelectActions() { - m_compilerActions = new ToolbarSelectAction(i18n("Compile"), this); - m_viewActions = new ToolbarSelectAction(i18n("View"), this); - m_convertActions = new ToolbarSelectAction(i18n("Convert"), this); - m_quickActions = new ToolbarSelectAction(i18n("Quick"), this); + m_compilerActions = new ToolbarSelectAction(i18n("Compile"), this); + m_viewActions = new ToolbarSelectAction(i18n("View"), this); + m_convertActions = new ToolbarSelectAction(i18n("Convert"), this); + m_quickActions = new ToolbarSelectAction(i18n("Quick"), this); - actionCollection()->setShortcutsConfigurable(m_compilerActions, false); - actionCollection()->setShortcutsConfigurable(m_viewActions, false); - actionCollection()->setShortcutsConfigurable(m_convertActions, false); - actionCollection()->setShortcutsConfigurable(m_quickActions, false); + actionCollection()->setShortcutsConfigurable(m_compilerActions, false); + actionCollection()->setShortcutsConfigurable(m_viewActions, false); + actionCollection()->setShortcutsConfigurable(m_convertActions, false); + actionCollection()->setShortcutsConfigurable(m_quickActions, false); - actionCollection()->addAction("list_compiler_select", m_compilerActions); - actionCollection()->addAction("list_convert_select", m_convertActions); - actionCollection()->addAction("list_view_select", m_viewActions); - actionCollection()->addAction("list_quick_select", m_quickActions); + actionCollection()->addAction("list_compiler_select", m_compilerActions); + actionCollection()->addAction("list_convert_select", m_convertActions); + actionCollection()->addAction("list_view_select", m_viewActions); + actionCollection()->addAction("list_quick_select", m_quickActions); } -void Kile::saveLastSelectedAction(){ +void Kile::saveLastSelectedAction() { - KILE_DEBUG_MAIN << "Kile::saveLastSelectedAction()" << endl; - QStringList list; - list << "Compile" << "Convert" << "View" << "Quick"; + KILE_DEBUG_MAIN << "Kile::saveLastSelectedAction()" << endl; + QStringList list; + list << "Compile" << "Convert" << "View" << "Quick"; - ToolbarSelectAction *pSelectAction = Q_NULLPTR ; + ToolbarSelectAction *pSelectAction = Q_NULLPTR ; - KConfigGroup grp = m_config->group("ToolSelectAction"); + KConfigGroup grp = m_config->group("ToolSelectAction"); - for(QStringList::Iterator it = list.begin(); it != list.end() ; ++it) { - if ( *it == "Compile" ){ - pSelectAction = m_compilerActions; - } - else if ( *it == "View" ){ - pSelectAction = m_viewActions; - } - else if ( *it == "Convert" ){ - pSelectAction = m_convertActions; - } - else if ( *it == "Quick" ){ - pSelectAction = m_quickActions; - } + for(QStringList::Iterator it = list.begin(); it != list.end() ; ++it) { + if ( *it == "Compile" ) { + pSelectAction = m_compilerActions; + } + else if ( *it == "View" ) { + pSelectAction = m_viewActions; + } + else if ( *it == "Convert" ) { + pSelectAction = m_convertActions; + } + else if ( *it == "Quick" ) { + pSelectAction = m_quickActions; + } - KILE_DEBUG_MAIN << "current item is " << pSelectAction->currentItem(); + KILE_DEBUG_MAIN << "current item is " << pSelectAction->currentItem(); - grp.writeEntry(*it, pSelectAction->currentItem()); - } + grp.writeEntry(*it, pSelectAction->currentItem()); + } } -void Kile::restoreLastSelectedAction(){ - - QStringList list; - list << "Compile" << "Convert" << "View" << "Quick"; - - ToolbarSelectAction *pSelectAction = Q_NULLPTR; - int defaultAction = 0; - - KConfigGroup grp = m_config->group("ToolSelectAction"); - - for(QStringList::Iterator it = list.begin(); it != list.end(); ++it) { - if ( *it == "Compile" ) { - pSelectAction = m_compilerActions; - defaultAction = 9; // PDFLatex - } - else if ( *it == "View" ) { - pSelectAction = m_viewActions; - defaultAction = 4; // ViewPDF - } - else if ( *it == "Convert" ) { - pSelectAction = m_convertActions; - defaultAction = 0; - } - else if ( *it == "Quick" ) { - pSelectAction = m_quickActions; - defaultAction = 0; - } - - int actIndex = grp.readEntry(*it, defaultAction); - KILE_DEBUG_MAIN << "selecting" << actIndex << "for" << *it; - pSelectAction->setCurrentItem(actIndex); - } +void Kile::restoreLastSelectedAction() { + + QStringList list; + list << "Compile" << "Convert" << "View" << "Quick"; + + ToolbarSelectAction *pSelectAction = Q_NULLPTR; + int defaultAction = 0; + + KConfigGroup grp = m_config->group("ToolSelectAction"); + + for(QStringList::Iterator it = list.begin(); it != list.end(); ++it) { + if ( *it == "Compile" ) { + pSelectAction = m_compilerActions; + defaultAction = 9; // PDFLatex + } + else if ( *it == "View" ) { + pSelectAction = m_viewActions; + defaultAction = 4; // ViewPDF + } + else if ( *it == "Convert" ) { + pSelectAction = m_convertActions; + defaultAction = 0; + } + else if ( *it == "Quick" ) { + pSelectAction = m_quickActions; + defaultAction = 0; + } + + int actIndex = grp.readEntry(*it, defaultAction); + KILE_DEBUG_MAIN << "selecting" << actIndex << "for" << *it; + pSelectAction->setCurrentItem(actIndex); + } } void Kile::cleanUpActionList(QList &list, const QStringList &tools) { // KILE_DEBUG_MAIN << "cleanUpActionList tools are" << tools.join("; "); - QList::iterator it, testIt; - for ( it= list.begin(); it != list.end(); ++it){ - QAction *act = *it; - if ( act != Q_NULLPTR && !act->objectName().isEmpty() && !tools.contains(act->objectName().mid(5)) ) { - if (act->associatedWidgets().contains(toolBar("toolsToolBar"))) { - toolBar("toolsToolBar")->removeAction(act); - } + QList::iterator it, testIt; + for ( it= list.begin(); it != list.end(); ++it) { + QAction *act = *it; + if ( act != Q_NULLPTR && !act->objectName().isEmpty() && !tools.contains(act->objectName().mid(5)) ) { + if (act->associatedWidgets().contains(toolBar("toolsToolBar"))) { + toolBar("toolsToolBar")->removeAction(act); + } // KILE_DEBUG_MAIN << "about to delete action: " << act->objectName(); - testIt = list.erase(it); - if( testIt == list.end()){ - break; - } - } - } + testIt = list.erase(it); + if( testIt == list.end()) { + break; + } + } + } } void Kile::restoreFilesAndProjects(bool allowRestore) { - if (!(allowRestore && KileConfig::restore())) { - return; - } + if (!(allowRestore && KileConfig::restore())) { + return; + } - QUrl url; - for (int i=0; i < m_listProjectsOpenOnStart.count(); ++i) { - // don't open project files as they will be opened later in this method - docManager()->projectOpen(QUrl::fromUserInput(m_listProjectsOpenOnStart[i]), i, m_listProjectsOpenOnStart.count(), false); - } + QUrl url; + for (int i=0; i < m_listProjectsOpenOnStart.count(); ++i) { + // don't open project files as they will be opened later in this method + docManager()->projectOpen(QUrl::fromUserInput(m_listProjectsOpenOnStart[i]), i, m_listProjectsOpenOnStart.count(), false); + } - for (int i = 0; i < m_listDocsOpenOnStart.count(); ++i) { - docManager()->fileOpen(QUrl::fromUserInput(m_listDocsOpenOnStart[i]), m_listEncodingsOfDocsOpenOnStart[i]); - } + for (int i = 0; i < m_listDocsOpenOnStart.count(); ++i) { + docManager()->fileOpen(QUrl::fromUserInput(m_listDocsOpenOnStart[i]), m_listEncodingsOfDocsOpenOnStart[i]); + } - if (ModeAction) { - ModeAction->setChecked(!m_singlemode); - } - updateModeStatus(); + if (ModeAction) { + ModeAction->setChecked(!m_singlemode); + } + updateModeStatus(); - m_listProjectsOpenOnStart.clear(); - m_listDocsOpenOnStart.clear(); - m_listEncodingsOfDocsOpenOnStart.clear(); + m_listProjectsOpenOnStart.clear(); + m_listDocsOpenOnStart.clear(); + m_listEncodingsOfDocsOpenOnStart.clear(); - KILE_DEBUG_MAIN << "lastDocument=" << KileConfig::lastDocument() << endl; - KTextEditor::Document *doc = docManager()->docFor(QUrl::fromUserInput(KileConfig::lastDocument())); - if (doc) { - viewManager()->switchToTextView(doc->url(), true); // request the focus on the view - } - setMasterDocumentFileName(KileConfig::singleFileMasterDocument()); + KILE_DEBUG_MAIN << "lastDocument=" << KileConfig::lastDocument() << endl; + KTextEditor::Document *doc = docManager()->docFor(QUrl::fromUserInput(KileConfig::lastDocument())); + if (doc) { + viewManager()->switchToTextView(doc->url(), true); // request the focus on the view + } + setMasterDocumentFileName(KileConfig::singleFileMasterDocument()); } void Kile::setActive() { - KILE_DEBUG_MAIN << "Activating" << endl; - raise(); - activateWindow(); - show(); + KILE_DEBUG_MAIN << "Activating" << endl; + raise(); + activateWindow(); + show(); } void Kile::setLine(const QString &line) { - bool ok; - uint l = line.toUInt(&ok, 10); - KTextEditor::View *view = viewManager()->currentTextView(); - if (view && ok) { - show(); - raise(); - activateWindow(); - // be very aggressive when it comes to raising the main window to the top - KWindowSystem::forceActiveWindow(winId()); - focusTextView(view); - editorExtension()->goToLine(l - 1, view); - } + bool ok; + uint l = line.toUInt(&ok, 10); + KTextEditor::View *view = viewManager()->currentTextView(); + if (view && ok) { + show(); + raise(); + activateWindow(); + // be very aggressive when it comes to raising the main window to the top + KWindowSystem::forceActiveWindow(winId()); + focusTextView(view); + editorExtension()->goToLine(l - 1, view); + } } void Kile::setCursor(const QUrl &url, int parag, int index) { - KTextEditor::Document *doc = docManager()->docFor(url); - if(doc) { - KTextEditor::View *view = (KTextEditor::View*)doc->views().first(); - if(view) { - view->setCursorPosition(KTextEditor::Cursor(parag, index)); - focusTextView(view); - } - } + KTextEditor::Document *doc = docManager()->docFor(url); + if(doc) { + KTextEditor::View *view = (KTextEditor::View*)doc->views().first(); + if(view) { + view->setCursorPosition(KTextEditor::Cursor(parag, index)); + focusTextView(view); + } + } } void Kile::runArchiveTool() { - runArchiveTool(QUrl()); + runArchiveTool(QUrl()); } void Kile::runArchiveTool(const QUrl &url) { - KileTool::Archive *tool = dynamic_cast(m_manager->createTool("Archive", QString(), false)); - if(!tool) { - KMessageBox::error(mainWindow(), i18n("It was impossible to create the \"Archive\" tool.\n\n" - "Please check and repair your installation of Kile."), - i18n("Unable to Create Archive Tool")); - return; - } - if(url.isValid()) { - tool->setSource(url.toLocalFile()); - } - tool->prepareToRun(); - m_manager->run(tool); + KileTool::Archive *tool = dynamic_cast(m_manager->createTool("Archive", QString(), false)); + if(!tool) { + KMessageBox::error(mainWindow(), i18n("It was impossible to create the \"Archive\" tool.\n\n" + "Please check and repair your installation of Kile."), + i18n("Unable to Create Archive Tool")); + return; + } + if(url.isValid()) { + tool->setSource(url.toLocalFile()); + } + tool->prepareToRun(); + m_manager->run(tool); } //TODO: move to KileView::Manager void Kile::activateView(QWidget* w, bool updateStruct /* = true */ ) //Needs to be QWidget because of QTabWidget::currentChanged { - //KILE_DEBUG_MAIN << "==Kile::activateView==========================" << endl; - if (!w || !w->inherits("KTextEditor::View")) { - return; - } + //KILE_DEBUG_MAIN << "==Kile::activateView==========================" << endl; + if (!w || !w->inherits("KTextEditor::View")) { + return; + } - //disable gui updates to avoid flickering of toolbars - setUpdatesEnabled(false); + //disable gui updates to avoid flickering of toolbars + setUpdatesEnabled(false); - QList toolBarsList = toolBars(); - QHash toolBarVisibilityHash; + QList toolBarsList = toolBars(); + QHash toolBarVisibilityHash; - for(QList::iterator i = toolBarsList.begin(); - i != toolBarsList.end(); ++i) { - KToolBar *toolBar = *i; - toolBarVisibilityHash[toolBar] = toolBar->isVisible(); - } + for(QList::iterator i = toolBarsList.begin(); + i != toolBarsList.end(); ++i) { + KToolBar *toolBar = *i; + toolBarVisibilityHash[toolBar] = toolBar->isVisible(); + } - KTextEditor::View* view = dynamic_cast(w); - Q_ASSERT(view); + KTextEditor::View* view = dynamic_cast(w); + Q_ASSERT(view); - for(int i = 0; i < viewManager()->textViewCount(); ++i) { - KTextEditor::View *view2 = viewManager()->textView(i); - if(view == view2) { - continue; - } - guiFactory()->removeClient(view2); - view2->clearFocus(); - } + for(int i = 0; i < viewManager()->textViewCount(); ++i) { + KTextEditor::View *view2 = viewManager()->textView(i); + if(view == view2) { + continue; + } + guiFactory()->removeClient(view2); + view2->clearFocus(); + } - guiFactory()->addClient(view); + guiFactory()->addClient(view); - for(QList::iterator i = toolBarsList.begin(); - i != toolBarsList.end(); ++i) { - KToolBar *toolBar = *i; - toolBar->setVisible(toolBarVisibilityHash[*i]); - } + for(QList::iterator i = toolBarsList.begin(); + i != toolBarsList.end(); ++i) { + KToolBar *toolBar = *i; + toolBar->setVisible(toolBarVisibilityHash[*i]); + } - setUpdatesEnabled(true); + setUpdatesEnabled(true); - if(updateStruct) { - viewManager()->updateStructure(); - } + if(updateStruct) { + viewManager()->updateStructure(); + } - focusTextView(view); + focusTextView(view); } void Kile::updateModeStatus() { - KILE_DEBUG_MAIN << "==Kile::updateModeStatus()=========="; - KileProject *project = docManager()->activeProject(); - QString shortName = m_masterDocumentFileName; - int pos = shortName.lastIndexOf('/'); - shortName.remove(0, pos + 1); - - if(project) { - if (m_singlemode) { - statusBar()->setHintText(i18n("Project: %1", project->name())); - } - else { - statusBar()->setHintText(i18n("Project: %1 (Master document: %2)", project->name(), shortName)); - } - } - else { - if (m_singlemode) { - statusBar()->setHintText(i18n("Normal mode")); - } - else { - statusBar()->setHintText(i18n("Master document: %1", shortName)); - } - } + KILE_DEBUG_MAIN << "==Kile::updateModeStatus()=========="; + KileProject *project = docManager()->activeProject(); + QString shortName = m_masterDocumentFileName; + int pos = shortName.lastIndexOf('/'); + shortName.remove(0, pos + 1); + + if(project) { + if (m_singlemode) { + statusBar()->setHintText(i18n("Project: %1", project->name())); + } + else { + statusBar()->setHintText(i18n("Project: %1 (Master document: %2)", project->name(), shortName)); + } + } + else { + if (m_singlemode) { + statusBar()->setHintText(i18n("Normal mode")); + } + else { + statusBar()->setHintText(i18n("Master document: %1", shortName)); + } + } - if(m_singlemode) { - ModeAction->setText(i18n("Define Current Document as 'Master Document'")); - ModeAction->setChecked(false); - } - else { - ModeAction->setText(i18n("Normal mode (current master document: %1)", shortName)); - ModeAction->setChecked(true); - } + if(m_singlemode) { + ModeAction->setText(i18n("Define Current Document as 'Master Document'")); + ModeAction->setChecked(false); + } + else { + ModeAction->setText(i18n("Normal mode (current master document: %1)", shortName)); + ModeAction->setChecked(true); + } - // enable or disable entries in Kile'S menu - updateMenu(); + // enable or disable entries in Kile'S menu + updateMenu(); - KTextEditor::View *view = viewManager()->currentTextView(); - // Passing Q_NULLPTR is ok - updateStatusBarCursorPosition(view, (view ? view->cursorPosition() : KTextEditor::Cursor())); - updateStatusBarViewMode(view); - updateStatusBarSelection(view); + KTextEditor::View *view = viewManager()->currentTextView(); + // Passing Q_NULLPTR is ok + updateStatusBarCursorPosition(view, (view ? view->cursorPosition() : KTextEditor::Cursor())); + updateStatusBarViewMode(view); + updateStatusBarSelection(view); } void Kile::openDocument(const QUrl &url) { - docManager()->fileSelected(url); + docManager()->fileSelected(url); } void Kile::openDocument(const QString& s) { - openDocument(QUrl::fromUserInput(s)); + openDocument(QUrl::fromUserInput(s)); } void Kile::closeDocument() { - docManager()->fileClose(); + docManager()->fileClose(); } void Kile::openProject(const QUrl &url) { - docManager()->projectOpen(url); + docManager()->projectOpen(url); } void Kile::openProject(const QString& proj) { - openProject(QUrl::fromUserInput(proj)); + openProject(QUrl::fromUserInput(proj)); } void Kile::focusPreview() { - m_bottomBar->switchToTab(PREVIEW_TAB); + m_bottomBar->switchToTab(PREVIEW_TAB); } void Kile::focusLog() { - m_bottomBar->switchToTab(LOG_TAB); + m_bottomBar->switchToTab(LOG_TAB); } void Kile::focusOutput() { - m_bottomBar->switchToTab(OUTPUT_TAB); + m_bottomBar->switchToTab(OUTPUT_TAB); } void Kile::focusKonsole() { - m_bottomBar->switchToTab(KONSOLE_TAB); + m_bottomBar->switchToTab(KONSOLE_TAB); } void Kile::focusEditor() { - KTextEditor::View *view = viewManager()->currentTextView(); - if(view) { - focusTextView(view); - } + KTextEditor::View *view = viewManager()->currentTextView(); + if(view) { + focusTextView(view); + } } void Kile::sideOrBottomBarChanged(bool visible) { if ( ! visible ) { focusEditor(); } } //FIXME: documents probably shouldn't be closed in this method yet (also see API doc of 'queryClose') bool Kile::queryClose() { - KTextEditor::View *view = viewManager()->currentTextView(); - if(view) { - KileConfig::setLastDocument(view->document()->url().toLocalFile()); - } - else { - KileConfig::setLastDocument(""); - } - - //don't close Kile if embedded viewers are present - KILE_DEBUG_MAIN << "==bool Kile::queryClose==========" << endl; - - m_listProjectsOpenOnStart.clear(); - m_listDocsOpenOnStart.clear(); - m_listEncodingsOfDocsOpenOnStart.clear(); + KTextEditor::View *view = viewManager()->currentTextView(); + if(view) { + KileConfig::setLastDocument(view->document()->url().toLocalFile()); + } + else { + KileConfig::setLastDocument(""); + } - for(int i = 0; i < viewManager()->textViewCount(); ++i) { - KTextEditor::Document *doc = viewManager()->textView(i)->document(); - const QUrl url = doc->url(); - if(url.isEmpty()) { - continue; - } - m_listDocsOpenOnStart.append(url.toLocalFile()); - m_listEncodingsOfDocsOpenOnStart.append(doc->encoding()); - } + //don't close Kile if embedded viewers are present + KILE_DEBUG_MAIN << "==bool Kile::queryClose==========" << endl; + + m_listProjectsOpenOnStart.clear(); + m_listDocsOpenOnStart.clear(); + m_listEncodingsOfDocsOpenOnStart.clear(); + + for(int i = 0; i < viewManager()->textViewCount(); ++i) { + KTextEditor::Document *doc = viewManager()->textView(i)->document(); + const QUrl url = doc->url(); + if(url.isEmpty()) { + continue; + } + m_listDocsOpenOnStart.append(url.toLocalFile()); + m_listEncodingsOfDocsOpenOnStart.append(doc->encoding()); + } - KILE_DEBUG_MAIN << "#projects = " << docManager()->projects().count() << endl; - QList projectList = docManager()->projects(); - for(QList::iterator i = projectList.begin(); i != projectList.end(); ++i) { - const QUrl url = (*i)->url(); - if(url.isEmpty()) { // shouldn't happen, but just in case... - continue; - } - m_listProjectsOpenOnStart.append(url.toLocalFile()); - } + KILE_DEBUG_MAIN << "#projects = " << docManager()->projects().count() << endl; + QList projectList = docManager()->projects(); + for(QList::iterator i = projectList.begin(); i != projectList.end(); ++i) { + const QUrl url = (*i)->url(); + if(url.isEmpty()) { // shouldn't happen, but just in case... + continue; + } + m_listProjectsOpenOnStart.append(url.toLocalFile()); + } - bool stage1 = docManager()->projectCloseAll(); - bool stage2 = true; + bool stage1 = docManager()->projectCloseAll(); + bool stage2 = true; - if(stage1) { - stage2 = docManager()->fileCloseAll(); - } + if(stage1) { + stage2 = docManager()->fileCloseAll(); + } - bool close = stage1 && stage2; - if(close) { - saveSettings(); - } + bool close = stage1 && stage2; + if(close) { + saveSettings(); + } - return close; + return close; } void Kile::showDocInfo(KTextEditor::View *view) { - if(!view) { - view = viewManager()->currentTextView(); - } + if(!view) { + view = viewManager()->currentTextView(); + } - if(!view) { - return; - } + if(!view) { + return; + } - KileDocument::TextInfo *docinfo = docManager()->textInfoFor(view->document()); - KileProject *project = KileInfo::docManager()->activeProject(); - if(docinfo) { // we have to ensure that we always get a _valid_ docinfo object - KileDialog::StatisticsDialog *dlg = new KileDialog::StatisticsDialog(project, - docinfo, - this, - view); - dlg->exec(); - delete dlg; - } - else { - qWarning() << "There is no KileDocument::Info object belonging to this document!"; - } + KileDocument::TextInfo *docinfo = docManager()->textInfoFor(view->document()); + KileProject *project = KileInfo::docManager()->activeProject(); + if(docinfo) { // we have to ensure that we always get a _valid_ docinfo object + KileDialog::StatisticsDialog *dlg = new KileDialog::StatisticsDialog(project, + docinfo, + this, + view); + dlg->exec(); + delete dlg; + } + else { + qWarning() << "There is no KileDocument::Info object belonging to this document!"; + } } void Kile::convertToASCII(KTextEditor::Document *doc) { - if(!doc) { - KTextEditor::View *view = viewManager()->currentTextView(); + if(!doc) { + KTextEditor::View *view = viewManager()->currentTextView(); - if(view) { - doc = view->document(); - } - else { - return; - } - } + if(view) { + doc = view->document(); + } + else { + return; + } + } - ConvertIO io(doc); - ConvertEncToASCII conv = ConvertEncToASCII(doc->encoding(), &io); - doc->setEncoding("ISO 8859-1"); - conv.convert(); + ConvertIO io(doc); + ConvertEncToASCII conv = ConvertEncToASCII(doc->encoding(), &io); + doc->setEncoding("ISO 8859-1"); + conv.convert(); } void Kile::convertToEnc(KTextEditor::Document *doc) { - if(!doc) { - KTextEditor::View *view = viewManager()->currentTextView(); + if(!doc) { + KTextEditor::View *view = viewManager()->currentTextView(); - if (view) doc = view->document(); - else return; - } + if (view) doc = view->document(); + else return; + } - if(sender()) { - ConvertIO io(doc); - QString name = QString(sender()->objectName()).section('_', -1); - ConvertASCIIToEnc conv = ConvertASCIIToEnc(name, &io); - conv.convert(); - doc->setEncoding(ConvertMap::encodingNameFor(name)); - } + if(sender()) { + ConvertIO io(doc); + QString name = QString(sender()->objectName()).section('_', -1); + ConvertASCIIToEnc conv = ConvertASCIIToEnc(name, &io); + conv.convert(); + doc->setEncoding(ConvertMap::encodingNameFor(name)); + } } KileWidget::StatusBar * Kile::statusBar() { - return static_cast(KXmlGuiWindow::statusBar()); + return static_cast(KXmlGuiWindow::statusBar()); } ////////////////// GENERAL SLOTS ////////////// int Kile::lineNumber() { - KTextEditor::View *view = viewManager()->currentTextView(); + KTextEditor::View *view = viewManager()->currentTextView(); - int para = 0; + int para = 0; - if (view) { - para = view->cursorPosition().line(); - } + if (view) { + para = view->cursorPosition().line(); + } - return para; + return para; } void Kile::newCaption() { - KTextEditor::View *view = viewManager()->currentTextView(); - if(view) { - const bool showFullPath = KileConfig::showFullPathInWindowTitle(); - - KTextEditor::Document *doc = view->document(); - const QString caption = (doc->isReadWrite() ? getName(doc, !showFullPath) - : i18nc("Window caption in read-only mode: [Read-Only]", - "%1 [Read-Only]", getName(doc, !showFullPath))); - setWindowTitle(caption); - if (m_bottomBar->currentPage() && m_bottomBar->currentPage()->inherits("KileWidget::Konsole")) { - m_texKonsole->sync(); - } - } - else { - setWindowTitle(""); - } + KTextEditor::View *view = viewManager()->currentTextView(); + if(view) { + const bool showFullPath = KileConfig::showFullPathInWindowTitle(); + + KTextEditor::Document *doc = view->document(); + const QString caption = (doc->isReadWrite() ? getName(doc, !showFullPath) + : i18nc("Window caption in read-only mode: [Read-Only]", + "%1 [Read-Only]", getName(doc, !showFullPath))); + setWindowTitle(caption); + if (m_bottomBar->currentPage() && m_bottomBar->currentPage()->inherits("KileWidget::Konsole")) { + m_texKonsole->sync(); + } + } + else { + setWindowTitle(""); + } } void Kile::grepItemSelected(const QString &abs_filename, int line) { - KILE_DEBUG_MAIN << "Open file: " - << abs_filename << " (" << line << ")" << endl; - docManager()->fileOpen(QUrl::fromUserInput(abs_filename)); - setLine(QString::number(line)); + KILE_DEBUG_MAIN << "Open file: " + << abs_filename << " (" << line << ")" << endl; + docManager()->fileOpen(QUrl::fromUserInput(abs_filename)); + setLine(QString::number(line)); } void Kile::findInFiles() { - static QPointer dlg = 0; + static QPointer dlg = 0; - if (!dlg) { - KILE_DEBUG_MAIN << "grep guard: create findInFiles dlg" << endl; - dlg = new KileDialog::FindFilesDialog(mainWindow(), this, KileGrep::Directory); - dlg->show(); - connect(dlg, SIGNAL(itemSelected(const QString &, int)), - this, SLOT(grepItemSelected(const QString &, int))); - } - else { - KILE_DEBUG_MAIN << "grep guard: show findInFiles dlg" << endl; - dlg->activateWindow(); - dlg->raise(); - } + if (!dlg) { + KILE_DEBUG_MAIN << "grep guard: create findInFiles dlg" << endl; + dlg = new KileDialog::FindFilesDialog(mainWindow(), this, KileGrep::Directory); + dlg->show(); + connect(dlg, SIGNAL(itemSelected(const QString &, int)), + this, SLOT(grepItemSelected(const QString &, int))); + } + else { + KILE_DEBUG_MAIN << "grep guard: show findInFiles dlg" << endl; + dlg->activateWindow(); + dlg->raise(); + } } void Kile::findInProjects() { - static QPointer project_dlg = Q_NULLPTR; + static QPointer project_dlg = Q_NULLPTR; - if(!project_dlg) { - KILE_DEBUG_MAIN << "grep guard: create findInProjects dlg" << endl; - project_dlg = new KileDialog::FindFilesDialog(mainWindow(), this, KileGrep::Project); - project_dlg->show(); - connect(project_dlg, SIGNAL(itemSelected(const QString &, int)), - this, SLOT(grepItemSelected(const QString &, int))); - } - else { - KILE_DEBUG_MAIN << "grep guard: show findInProjects dlg" << endl; - project_dlg->activateWindow(); - project_dlg->raise(); - } + if(!project_dlg) { + KILE_DEBUG_MAIN << "grep guard: create findInProjects dlg" << endl; + project_dlg = new KileDialog::FindFilesDialog(mainWindow(), this, KileGrep::Project); + project_dlg->show(); + connect(project_dlg, SIGNAL(itemSelected(const QString &, int)), + this, SLOT(grepItemSelected(const QString &, int))); + } + else { + KILE_DEBUG_MAIN << "grep guard: show findInProjects dlg" << endl; + project_dlg->activateWindow(); + project_dlg->raise(); + } } /////////////////// PART & EDITOR WIDGET ////////// bool Kile::resetPart() { - KILE_DEBUG_MAIN << "==Kile::resetPart()=============================" << endl; + KILE_DEBUG_MAIN << "==Kile::resetPart()=============================" << endl; - statusBar()->reset(); - updateModeStatus(); - newCaption(); + statusBar()->reset(); + updateModeStatus(); + newCaption(); - KTextEditor::View *view = viewManager()->currentTextView(); - if (view){ - activateView(view); - } + KTextEditor::View *view = viewManager()->currentTextView(); + if (view) { + activateView(view); + } - return true; + return true; } void Kile::updateUserDefinedMenus() { - m_buildMenuTopLevel = dynamic_cast(m_mainWindow->guiFactory()->container("menu_build", m_mainWindow)); - m_buildMenuCompile = dynamic_cast(m_mainWindow->guiFactory()->container("menu_compile", m_mainWindow)); - m_buildMenuConvert = dynamic_cast(m_mainWindow->guiFactory()->container("menu_convert", m_mainWindow)); - m_buildMenuViewer = dynamic_cast(m_mainWindow->guiFactory()->container("menu_viewer", m_mainWindow)); - m_buildMenuOther = dynamic_cast(m_mainWindow->guiFactory()->container("menu_other", m_mainWindow)); - m_buildMenuQuickPreview = dynamic_cast(m_mainWindow->guiFactory()->container("quickpreview", m_mainWindow)); + m_buildMenuTopLevel = dynamic_cast(m_mainWindow->guiFactory()->container("menu_build", m_mainWindow)); + m_buildMenuCompile = dynamic_cast(m_mainWindow->guiFactory()->container("menu_compile", m_mainWindow)); + m_buildMenuConvert = dynamic_cast(m_mainWindow->guiFactory()->container("menu_convert", m_mainWindow)); + m_buildMenuViewer = dynamic_cast(m_mainWindow->guiFactory()->container("menu_viewer", m_mainWindow)); + m_buildMenuOther = dynamic_cast(m_mainWindow->guiFactory()->container("menu_other", m_mainWindow)); + m_buildMenuQuickPreview = dynamic_cast(m_mainWindow->guiFactory()->container("quickpreview", m_mainWindow)); - m_userMenu->updateGUI(); + m_userMenu->updateGUI(); - setupTools(); + setupTools(); } void Kile::enableGUI(bool enable) { - // update action lists - QList actions = actionCollection()->actions(); - for(QList::iterator itact = actions.begin(); itact != actions.end(); ++itact) { - if (m_dictMenuAction.contains((*itact)->objectName()) - || m_dictMenuFile.contains((*itact)->objectName())) { - (*itact)->setEnabled(enable); - } - } + // update action lists + QList actions = actionCollection()->actions(); + for(QList::iterator itact = actions.begin(); itact != actions.end(); ++itact) { + if (m_dictMenuAction.contains((*itact)->objectName()) + || m_dictMenuFile.contains((*itact)->objectName())) { + (*itact)->setEnabled(enable); + } + } - // update latex usermenu actions - if ( m_userMenu ) { - QList useractions = m_userMenu->menuActions(); - foreach ( QAction *action, useractions ) { - action->setEnabled(enable); - } - } + // update latex usermenu actions + if ( m_userMenu ) { + QList useractions = m_userMenu->menuActions(); + foreach ( QAction *action, useractions ) { + action->setEnabled(enable); + } + } - // enable or disable userhelp entries - m_help->enableUserhelpEntries(enable); - - QList actionList; - actionList << m_listQuickActions - << m_listCompilerActions - << m_listConverterActions - << m_listViewerActions - << m_listOtherActions; - // enable or disable list actions - for(QList::iterator i = actionList.begin(); i != actionList.end(); ++i) { - (*i)->setEnabled(enable); - } + // enable or disable userhelp entries + m_help->enableUserhelpEntries(enable); + + QList actionList; + actionList << m_listQuickActions + << m_listCompilerActions + << m_listConverterActions + << m_listViewerActions + << m_listOtherActions; + // enable or disable list actions + for(QList::iterator i = actionList.begin(); i != actionList.end(); ++i) { + (*i)->setEnabled(enable); + } - // enable or disable bibliography menu entries - actionList = m_bibTagActionMenu->menu()->actions(); - for(QList::iterator it = actionList.begin(); it != actionList.end(); ++it) { - (*it)->setEnabled(enable); - } + // enable or disable bibliography menu entries + actionList = m_bibTagActionMenu->menu()->actions(); + for(QList::iterator it = actionList.begin(); it != actionList.end(); ++it) { + (*it)->setEnabled(enable); + } - QStringList menuList; - menuList << "file" << "edit" << "view" << "menu_build" << "menu_project" << "menu_latex" << "wizard" << "tools"; - for(QStringList::iterator it = menuList.begin(); it != menuList.end(); ++it) { - QMenu *menu = dynamic_cast(guiFactory()->container(*it, this)); - if(menu) { - updateMenuActivationStatus(menu); - } - } + QStringList menuList; + menuList << "file" << "edit" << "view" << "menu_build" << "menu_project" << "menu_latex" << "wizard" << "tools"; + for(QStringList::iterator it = menuList.begin(); it != menuList.end(); ++it) { + QMenu *menu = dynamic_cast(guiFactory()->container(*it, this)); + if(menu) { + updateMenuActivationStatus(menu); + } + } - updateUserMenuStatus(enable); + updateUserMenuStatus(enable); } // adds action names to their lists void Kile::initMenu() { - QStringList projectlist,filelist,actionlist; - - projectlist - << "project_add" << "project_remove" - << "project_showfiles" - << "project_buildtree" << "project_options" << "project_findfiles" - << "project_archive" << "project_close" << "project_openallfiles" - ; - - filelist - // file - << "convert" - // edit - << "goto_menu" << "complete" << "bullet" << "select" - << "delete" << "environment" << "texgroup" - // build - << "quickpreview" << "menu_compile" << "menu_convert" - << "menu_viewers" << "menu_other" - // latex - << "menu_preamble" << "menu_lists" << "menu_sectioning" << "references" - << "menu_environment" << "menu_listenv" << "menu_tabularenv" << "menu_floatenv" - << "menu_code" << "menu_math" << "menu_mathenv" << "menu_mathamsenv" - << "menu_bibliography" << "menu_fontstyles" << "menu_spacing" - ; - - actionlist - // file - << "file_save_copy_as" << "file_save_all" << "template_create" << "Statistics" - << "file_close" << "file_close_all" << "file_close_all_others" - // edit - << "RefreshStructure" - // view - << "gotoPrevDocument" << "gotoNextDocument" - // build - << "quickpreview_selection" << "quickpreview_environment" - << "quickpreview_subdocument" << "quickpreview_math" - << "WatchFile" << "CleanAll" - // latex - << "tag_documentclass" << "tag_usepackage" << "tag_amspackages" << "tag_env_document" - << "tag_author" << "tag_title" << "tag_maketitle" << "tag_titlepage" << "tag_env_abstract" - << "tag_tableofcontents" << "tag_listoffigures" << "tag_listoftables" - << "tag_makeindex" << "tag_printindex" << "tag_makeglossary" << "tag_env_thebibliography" - << "tag_part" << "tag_chapter" << "tag_section" << "tag_subsection" << "tag_subsubsection" - << "tag_paragraph" << "tag_subparagraph" << "tag_label" - << "tag_ref" << "tag_pageref" << "tag_index" << "tag_footnote" << "tag_cite" // << "citeViewBib" - << "tag_center" << "tag_flushleft" << "tag_flushright" - << "tag_env_minipage" << "tag_quote" << "tag_quotation" << "tag_verse" - << "tag_env_itemize" << "tag_env_enumerate" << "tag_env_description" << "tag_item" - << "tag_env_tabular" << "tag_env_tabular*" << "tag_env_tabbing" - << "tag_multicolumn" << "tag_hline" << "tag_vline" << "tag_cline" - << "tag_figure" << "tag_table" - << "tag_verbatim" << "tag_env_verbatim*" << "tag_verb" << "tag_verb*" - << "tag_mathmode" << "tag_equation" << "tag_subscript" << "tag_superscript" - << "tag_sqrt" << "tag_nroot" << "tag_left" << "tag_right" << "tag_leftright" - << "tag_bigl" << "tag_bigr" << "tag_Bigl" << "tag_Bigr" - << "tag_biggl" << "tag_biggr" << "tag_Biggl" << "tag_Biggr" - << "tag_text" << "tag_intertext" << "tag_boxed" - << "tag_frac" << "tag_dfrac" << "tag_tfrac" - << "tag_binom" << "tag_dbinom" << "tag_tbinom" - << "tag_xleftarrow" << "tag_xrightarrow" - << "tag_mathrm" << "tag_mathit" << "tag_mathbf" << "tag_mathsf" - << "tag_mathtt" << "tag_mathcal" << "tag_mathbb" << "tag_mathfrak" - << "tag_acute" << "tag_grave" << "tag_tilde" << "tag_bar" << "tag_vec" - << "tag_hat" << "tag_check" << "tag_breve" << "tag_dot" << "tag_ddot" - << "tag_space_small" << "tag_space_medium" << "tag_space_large" - << "tag_quad" << "tag_qquad" << "tag_enskip" - << "tag_env_displaymath" << "tag_env_equation" << "tag_env_equation*" - << "tag_env_array" - << "tag_env_multline" << "tag_env_multline*" << "tag_env_split" - << "tag_env_gather" << "tag_env_gather*" << "tag_env_align" << "tag_env_align*" - << "tag_env_flalign" << "tag_env_flalign*" << "tag_env_alignat" << "tag_env_alignat*" - << "tag_env_aligned" << "tag_env_gathered" << "tag_env_alignedat" << "tag_env_cases" - << "tag_env_matrix" << "tag_env_pmatrix" << "tag_env_vmatrix" - << "tag_env_VVmatrix" << "tag_env_bmatrix" << "tag_env_BBmatrix" - // bibliography stuff - << "menu_bibliography" - << "setting_bibtex" << "setting_biblatex" - << "tag_textit" << "tag_textsl" << "tag_textbf" << "tag_underline" - << "tag_texttt" << "tag_textsc" << "tag_emph" << "tag_strong" - << "tag_rmfamily" << "tag_sffamily" << "tag_ttfamily" - << "tag_mdseries" << "tag_bfseries" << "tag_upshape" - << "tag_itshape" << "tag_slshape" << "tag_scshape" - << "tag_newline" << "tag_newpage" << "tag_linebreak" << "tag_pagebreak" - << "tag_bigskip" << "tag_medskip" << "tag_smallskip" - << "tag_hspace" << "tag_hspace*" << "tag_vspace" << "tag_vspace*" - << "tag_hfill" << "tag_hrulefill" << "tag_dotfill" << "tag_vfill" - << "tag_includegraphics" << "tag_include" << "tag_input" - // wizard - << "wizard_tabular" << "wizard_array" << "wizard_tabbing" - << "wizard_float" << "wizard_mathenv" - << "wizard_usermenu" << "wizard_usermenu2" - // settings - << "Mode" - // help - << "help_context" - // action lists - << "structure_list" << "size_list" << "other_list" - << "left_list" << "right_list" - // tool lists - << "list_compiler_select" << "list_convert_select" << "list_view_select" << "list_quick_select" - // user help - << "help_userhelp" - << "edit_next_bullet" << "edit_prev_bullet" - << "edit_next_section" << "edit_prev_section" << "edit_next_paragraph" << "edit_prev_paragraph" - - << "edit_select_inside_env" << "edit_select_outside_env" << "edit_select_inside_group" - << "edit_select_outside_group" << "edit_select_mathgroup" << "edit_select_paragraph" - << "edit_select_line" << "edit_select_word" - - << "edit_delete_inside_env" << "edit_delete_outside_env" << "edit_delete_inside_group" - << "edit_delete_outside_group" << "edit_delete_mathgroup" << "edit_delete_paragraph" - << "edit_delete_eol" << "edit_delete_word" - - << "edit_complete_word" << "edit_complete_env" << "edit_complete_abbrev" - - << "edit_begin_env" << "edit_end_env" << "edit_match_env" << "edit_close_env" << "edit_closeall_env" - - << "edit_begin_group" << "edit_end_group" << "edit_match_group" << "edit_close_group" - - << "file_export_ascii" << "file_export_latin1" << "file_export_latin2" << "file_export_latin3" - << "file_export_latin4" << "file_export_latin5" << "file_export_latin9" << "file_export_cp1250" - << "file_export_cp1252" - ; - - setMenuItems(projectlist,m_dictMenuProject); - setMenuItems(filelist,m_dictMenuFile); - setMenuItems(actionlist,m_dictMenuAction); + QStringList projectlist,filelist,actionlist; + + projectlist + << "project_add" << "project_remove" + << "project_showfiles" + << "project_buildtree" << "project_options" << "project_findfiles" + << "project_archive" << "project_close" << "project_openallfiles" + ; + + filelist + // file + << "convert" + // edit + << "goto_menu" << "complete" << "bullet" << "select" + << "delete" << "environment" << "texgroup" + // build + << "quickpreview" << "menu_compile" << "menu_convert" + << "menu_viewers" << "menu_other" + // latex + << "menu_preamble" << "menu_lists" << "menu_sectioning" << "references" + << "menu_environment" << "menu_listenv" << "menu_tabularenv" << "menu_floatenv" + << "menu_code" << "menu_math" << "menu_mathenv" << "menu_mathamsenv" + << "menu_bibliography" << "menu_fontstyles" << "menu_spacing" + ; + + actionlist + // file + << "file_save_copy_as" << "file_save_all" << "template_create" << "Statistics" + << "file_close" << "file_close_all" << "file_close_all_others" + // edit + << "RefreshStructure" + // view + << "gotoPrevDocument" << "gotoNextDocument" + // build + << "quickpreview_selection" << "quickpreview_environment" + << "quickpreview_subdocument" << "quickpreview_math" + << "WatchFile" << "CleanAll" + // latex + << "tag_documentclass" << "tag_usepackage" << "tag_amspackages" << "tag_env_document" + << "tag_author" << "tag_title" << "tag_maketitle" << "tag_titlepage" << "tag_env_abstract" + << "tag_tableofcontents" << "tag_listoffigures" << "tag_listoftables" + << "tag_makeindex" << "tag_printindex" << "tag_makeglossary" << "tag_env_thebibliography" + << "tag_part" << "tag_chapter" << "tag_section" << "tag_subsection" << "tag_subsubsection" + << "tag_paragraph" << "tag_subparagraph" << "tag_label" + << "tag_ref" << "tag_pageref" << "tag_index" << "tag_footnote" << "tag_cite" // << "citeViewBib" + << "tag_center" << "tag_flushleft" << "tag_flushright" + << "tag_env_minipage" << "tag_quote" << "tag_quotation" << "tag_verse" + << "tag_env_itemize" << "tag_env_enumerate" << "tag_env_description" << "tag_item" + << "tag_env_tabular" << "tag_env_tabular*" << "tag_env_tabbing" + << "tag_multicolumn" << "tag_hline" << "tag_vline" << "tag_cline" + << "tag_figure" << "tag_table" + << "tag_verbatim" << "tag_env_verbatim*" << "tag_verb" << "tag_verb*" + << "tag_mathmode" << "tag_equation" << "tag_subscript" << "tag_superscript" + << "tag_sqrt" << "tag_nroot" << "tag_left" << "tag_right" << "tag_leftright" + << "tag_bigl" << "tag_bigr" << "tag_Bigl" << "tag_Bigr" + << "tag_biggl" << "tag_biggr" << "tag_Biggl" << "tag_Biggr" + << "tag_text" << "tag_intertext" << "tag_boxed" + << "tag_frac" << "tag_dfrac" << "tag_tfrac" + << "tag_binom" << "tag_dbinom" << "tag_tbinom" + << "tag_xleftarrow" << "tag_xrightarrow" + << "tag_mathrm" << "tag_mathit" << "tag_mathbf" << "tag_mathsf" + << "tag_mathtt" << "tag_mathcal" << "tag_mathbb" << "tag_mathfrak" + << "tag_acute" << "tag_grave" << "tag_tilde" << "tag_bar" << "tag_vec" + << "tag_hat" << "tag_check" << "tag_breve" << "tag_dot" << "tag_ddot" + << "tag_space_small" << "tag_space_medium" << "tag_space_large" + << "tag_quad" << "tag_qquad" << "tag_enskip" + << "tag_env_displaymath" << "tag_env_equation" << "tag_env_equation*" + << "tag_env_array" + << "tag_env_multline" << "tag_env_multline*" << "tag_env_split" + << "tag_env_gather" << "tag_env_gather*" << "tag_env_align" << "tag_env_align*" + << "tag_env_flalign" << "tag_env_flalign*" << "tag_env_alignat" << "tag_env_alignat*" + << "tag_env_aligned" << "tag_env_gathered" << "tag_env_alignedat" << "tag_env_cases" + << "tag_env_matrix" << "tag_env_pmatrix" << "tag_env_vmatrix" + << "tag_env_VVmatrix" << "tag_env_bmatrix" << "tag_env_BBmatrix" + // bibliography stuff + << "menu_bibliography" + << "setting_bibtex" << "setting_biblatex" + << "tag_textit" << "tag_textsl" << "tag_textbf" << "tag_underline" + << "tag_texttt" << "tag_textsc" << "tag_emph" << "tag_strong" + << "tag_rmfamily" << "tag_sffamily" << "tag_ttfamily" + << "tag_mdseries" << "tag_bfseries" << "tag_upshape" + << "tag_itshape" << "tag_slshape" << "tag_scshape" + << "tag_newline" << "tag_newpage" << "tag_linebreak" << "tag_pagebreak" + << "tag_bigskip" << "tag_medskip" << "tag_smallskip" + << "tag_hspace" << "tag_hspace*" << "tag_vspace" << "tag_vspace*" + << "tag_hfill" << "tag_hrulefill" << "tag_dotfill" << "tag_vfill" + << "tag_includegraphics" << "tag_include" << "tag_input" + // wizard + << "wizard_tabular" << "wizard_array" << "wizard_tabbing" + << "wizard_float" << "wizard_mathenv" + << "wizard_usermenu" << "wizard_usermenu2" + // settings + << "Mode" + // help + << "help_context" + // action lists + << "structure_list" << "size_list" << "other_list" + << "left_list" << "right_list" + // tool lists + << "list_compiler_select" << "list_convert_select" << "list_view_select" << "list_quick_select" + // user help + << "help_userhelp" + << "edit_next_bullet" << "edit_prev_bullet" + << "edit_next_section" << "edit_prev_section" << "edit_next_paragraph" << "edit_prev_paragraph" + + << "edit_select_inside_env" << "edit_select_outside_env" << "edit_select_inside_group" + << "edit_select_outside_group" << "edit_select_mathgroup" << "edit_select_paragraph" + << "edit_select_line" << "edit_select_word" + + << "edit_delete_inside_env" << "edit_delete_outside_env" << "edit_delete_inside_group" + << "edit_delete_outside_group" << "edit_delete_mathgroup" << "edit_delete_paragraph" + << "edit_delete_eol" << "edit_delete_word" + + << "edit_complete_word" << "edit_complete_env" << "edit_complete_abbrev" + + << "edit_begin_env" << "edit_end_env" << "edit_match_env" << "edit_close_env" << "edit_closeall_env" + + << "edit_begin_group" << "edit_end_group" << "edit_match_group" << "edit_close_group" + + << "file_export_ascii" << "file_export_latin1" << "file_export_latin2" << "file_export_latin3" + << "file_export_latin4" << "file_export_latin5" << "file_export_latin9" << "file_export_cp1250" + << "file_export_cp1252" + ; + + setMenuItems(projectlist,m_dictMenuProject); + setMenuItems(filelist,m_dictMenuFile); + setMenuItems(actionlist,m_dictMenuAction); } void Kile::setMenuItems(QStringList &list, QMap &dict) { - for ( QStringList::Iterator it=list.begin(); it!=list.end(); ++it ) { - dict[(*it)] = true; - } + for ( QStringList::Iterator it=list.begin(); it!=list.end(); ++it ) { + dict[(*it)] = true; + } } void Kile::updateMenu() { - KILE_DEBUG_MAIN << "==Kile::updateMenu()====================" << endl; - QAction *a; - QMap::Iterator it; + KILE_DEBUG_MAIN << "==Kile::updateMenu()====================" << endl; + QAction *a; + QMap::Iterator it; - // update project menus - m_actRecentProjects->setEnabled( m_actRecentProjects->items().count() > 0 ); - bool project_open = ( docManager()->isProjectOpen() ) ; + // update project menus + m_actRecentProjects->setEnabled( m_actRecentProjects->items().count() > 0 ); + bool project_open = ( docManager()->isProjectOpen() ) ; - for ( it=m_dictMenuProject.begin(); it!=m_dictMenuProject.end(); ++it ) { - a = actionCollection()->action(it.key()); - if(a) { - a->setEnabled(project_open); - } - } + for ( it=m_dictMenuProject.begin(); it!=m_dictMenuProject.end(); ++it ) { + a = actionCollection()->action(it.key()); + if(a) { + a->setEnabled(project_open); + } + } - // project_show is only enabled, when more than 1 project is opened - a = actionCollection()->action("project_show"); - if(a) { - a->setEnabled(project_open && docManager()->projects().count() > 1); - } + // project_show is only enabled, when more than 1 project is opened + a = actionCollection()->action("project_show"); + if(a) { + a->setEnabled(project_open && docManager()->projects().count() > 1); + } - // update file menus - m_actRecentFiles->setEnabled( m_actRecentFiles->items().count() > 0 ); - bool file_open = ( viewManager()->currentTextView() ); - KILE_DEBUG_MAIN << "\tprojectopen=" << project_open << " fileopen=" << file_open << endl; + // update file menus + m_actRecentFiles->setEnabled( m_actRecentFiles->items().count() > 0 ); + bool file_open = ( viewManager()->currentTextView() ); + KILE_DEBUG_MAIN << "\tprojectopen=" << project_open << " fileopen=" << file_open << endl; - enableGUI(file_open); + enableGUI(file_open); } bool Kile::updateMenuActivationStatus(QMenu *menu) { - return updateMenuActivationStatus(menu, QSet()); + return updateMenuActivationStatus(menu, QSet()); } bool Kile::updateMenuActivationStatus(QMenu *menu, const QSet& visited) { - if(visited.contains(menu)) { - qWarning() << "Recursive menu structure detected - aborting!"; - return true; - } - if(menu->objectName() == "usermenu-submenu") { - menu->setEnabled(true); - return true; - } + if(visited.contains(menu)) { + qWarning() << "Recursive menu structure detected - aborting!"; + return true; + } + if(menu->objectName() == "usermenu-submenu") { + menu->setEnabled(true); + return true; + } - bool enabled = false; - QList actionList = menu->actions(); - - for(QList::iterator it = actionList.begin(); it != actionList.end(); ++it) { - QAction *action = *it; - QMenu *subMenu = action->menu(); - if(subMenu) { - QSet newVisited(visited); - newVisited.insert(menu); - if(updateMenuActivationStatus(subMenu, newVisited)) { - enabled = true; - } - } - else if(!action->isSeparator() && action->isEnabled()) { - enabled = true; - } - } - menu->setEnabled(enabled); - return enabled; + bool enabled = false; + QList actionList = menu->actions(); + + for(QList::iterator it = actionList.begin(); it != actionList.end(); ++it) { + QAction *action = *it; + QMenu *subMenu = action->menu(); + if(subMenu) { + QSet newVisited(visited); + newVisited.insert(menu); + if(updateMenuActivationStatus(subMenu, newVisited)) { + enabled = true; + } + } + else if(!action->isSeparator() && action->isEnabled()) { + enabled = true; + } + } + menu->setEnabled(enabled); + return enabled; } void Kile::updateLatexenuActivationStatus(QMenu *menu, bool state) { - if ( menu->isEmpty() || !viewManager()->currentTextView() ) { - state = false; - } - menu->menuAction()->setVisible(state); + if ( menu->isEmpty() || !viewManager()->currentTextView() ) { + state = false; + } + menu->menuAction()->setVisible(state); } void Kile::runTool(const QString& tool) { - runToolWithConfig(tool, QString()); + runToolWithConfig(tool, QString()); } void Kile::runToolWithConfig(const QString &toolName, const QString &config) { - KILE_DEBUG_MAIN << toolName << config; + KILE_DEBUG_MAIN << toolName << config; - focusLog(); - KileTool::Base *tool = m_manager->createTool(toolName, config); + focusLog(); + KileTool::Base *tool = m_manager->createTool(toolName, config); - if(!tool || (tool->requestSaveAll() && !m_docManager->fileSaveAll())) { - delete tool; - return; - } + if(!tool || (tool->requestSaveAll() && !m_docManager->fileSaveAll())) { + delete tool; + return; + } - return m_manager->run(tool); + return m_manager->run(tool); } void Kile::cleanAll(KileDocument::TextInfo *docinfo) { - const QString noactivedoc = i18n("There is no active document or it is not saved."); - if(!docinfo) { - KTextEditor::Document *doc = activeTextDocument(); - if (doc) { - docinfo = docManager()->textInfoFor(doc); - } - else { - errorHandler()->printMessage(KileTool::Error, noactivedoc, i18n("Clean")); - return; - } - } + const QString noactivedoc = i18n("There is no active document or it is not saved."); + if(!docinfo) { + KTextEditor::Document *doc = activeTextDocument(); + if (doc) { + docinfo = docManager()->textInfoFor(doc); + } + else { + errorHandler()->printMessage(KileTool::Error, noactivedoc, i18n("Clean")); + return; + } + } - if (docinfo) { - docManager()->cleanUpTempFiles(docinfo->url(), false); - } + if (docinfo) { + docManager()->cleanUpTempFiles(docinfo->url(), false); + } } void Kile::refreshStructure() { - viewManager()->updateStructure(true); + viewManager()->updateStructure(true); } void Kile::insertTag(const KileAction::TagData& data) { - errorHandler()->clearMessages(); + errorHandler()->clearMessages(); - if(data.description.length() > 0) { - focusLog(); - errorHandler()->printMessage(data.description); - } + if(data.description.length() > 0) { + focusLog(); + errorHandler()->printMessage(data.description); + } - KTextEditor::View *view = viewManager()->currentTextView(); + KTextEditor::View *view = viewManager()->currentTextView(); - if(!view) { - return; - } + if(!view) { + return; + } - focusTextView(view); + focusTextView(view); - editorExtension()->insertTag(data, view); + editorExtension()->insertTag(data, view); } void Kile::insertTag(const QString& tagB, const QString& tagE, int dx, int dy) { - insertTag(KileAction::TagData(QString(), tagB, tagE, dx, dy)); + insertTag(KileAction::TagData(QString(), tagB, tagE, dx, dy)); } void Kile::insertAmsTag(const KileAction::TagData& data) { - insertTag(data, QStringList("amsmath")); + insertTag(data, QStringList("amsmath")); } -void Kile::insertTag(const KileAction::TagData& data,const QList &pkgs){ +void Kile::insertTag(const KileAction::TagData& data,const QList &pkgs) { - QStringList packages; - QString pkgName; + QStringList packages; + QString pkgName; - QList::const_iterator it; - for(it = pkgs.begin(); it != pkgs.end() ; it++){ - pkgName = (*it).name; - if(!pkgName.isEmpty()){ - packages.append(pkgName); - } - } + QList::const_iterator it; + for(it = pkgs.begin(); it != pkgs.end() ; it++) { + pkgName = (*it).name; + if(!pkgName.isEmpty()) { + packages.append(pkgName); + } + } - insertTag(data,packages); + insertTag(data,packages); } void Kile::insertTag(const KileAction::TagData& data,const QStringList &pkgs) { - KILE_DEBUG_MAIN << "void Kile::insertTag(const KileAction::TagData& data,const QStringList " << pkgs.join(",") << ")" << endl; - insertTag(data); - - KileDocument::TextInfo *docinfo = docManager()->textInfoFor(getCompileName()); - if(docinfo) { - QStringList packagelist = allPackages(docinfo); - QStringList::const_iterator it; - QStringList warnPkgs; - - for ( it = pkgs.begin(); it != pkgs.end(); ++it) { - if(!packagelist.contains(*it)) { - warnPkgs.append(*it); - } - } - - if(warnPkgs.count() > 0) { - if(warnPkgs.count() == 1) { - errorHandler()->printMessage(KileTool::Error, i18n("You have to include the package %1.", warnPkgs.join(",")), i18n("Insert text")); - } - else { - errorHandler()->printMessage(KileTool::Error, i18n("You have to include the packages %1.", warnPkgs.join(",")), i18n("Insert text")); - } - } - } + KILE_DEBUG_MAIN << "void Kile::insertTag(const KileAction::TagData& data,const QStringList " << pkgs.join(",") << ")" << endl; + insertTag(data); + + KileDocument::TextInfo *docinfo = docManager()->textInfoFor(getCompileName()); + if(docinfo) { + QStringList packagelist = allPackages(docinfo); + QStringList::const_iterator it; + QStringList warnPkgs; + + for ( it = pkgs.begin(); it != pkgs.end(); ++it) { + if(!packagelist.contains(*it)) { + warnPkgs.append(*it); + } + } + + if(warnPkgs.count() > 0) { + if(warnPkgs.count() == 1) { + errorHandler()->printMessage(KileTool::Error, i18n("You have to include the package %1.", warnPkgs.join(",")), i18n("Insert text")); + } + else { + errorHandler()->printMessage(KileTool::Error, i18n("You have to include the packages %1.", warnPkgs.join(",")), i18n("Insert text")); + } + } + } } void Kile::insertText(const QString &text) { - if(text.indexOf("%C")>=0) - insertTag(KileAction::TagData(QString(), text, QString(), 0, 0)); - else - insertTag(KileAction::TagData(QString(), text, "%C", 0, 0)); + if(text.indexOf("%C")>=0) + insertTag(KileAction::TagData(QString(), text, QString(), 0, 0)); + else + insertTag(KileAction::TagData(QString(), text, "%C", 0, 0)); } void Kile::insertText(const QString &text, const QStringList &pkgs) { - insertTag(KileAction::TagData(QString(), text, "%C", 0, 0), pkgs); + insertTag(KileAction::TagData(QString(), text, "%C", 0, 0), pkgs); } void Kile::insertText(const QString &text, const QList &pkgs) { - insertTag(KileAction::TagData(QString(), text, "%C", 0, 0), pkgs); + insertTag(KileAction::TagData(QString(), text, "%C", 0, 0), pkgs); } void Kile::quickDocument() { - KileDialog::QuickDocument *dlg = new KileDialog::QuickDocument(m_config.data(), this, "Quick Start", i18n("Quick Start")); + KileDialog::QuickDocument *dlg = new KileDialog::QuickDocument(m_config.data(), this, "Quick Start", i18n("Quick Start")); - if(dlg->exec()) { - if(!viewManager()->currentTextView()) { - docManager()->createNewLaTeXDocument(); - } - insertTag( dlg->tagData() ); - viewManager()->updateStructure(true); - } - delete dlg; + if(dlg->exec()) { + if(!viewManager()->currentTextView()) { + docManager()->createNewLaTeXDocument(); + } + insertTag( dlg->tagData() ); + viewManager()->updateStructure(true); + } + delete dlg; } void Kile::quickArray() { - quickTabulardialog(false); + quickTabulardialog(false); } void Kile::quickTabular() { - quickTabulardialog(true); + quickTabulardialog(true); } void Kile::quickTabulardialog(bool tabularenv) { - if(!viewManager()->currentTextView()) { - return; - } + if(!viewManager()->currentTextView()) { + return; + } - QString env; - if(tabularenv) { - KConfigGroup group = m_config->group("Wizard"); - env = group.readEntry("TabularEnvironment", "tabular"); - } else { - env = "array"; - } + QString env; + if(tabularenv) { + KConfigGroup group = m_config->group("Wizard"); + env = group.readEntry("TabularEnvironment", "tabular"); + } else { + env = "array"; + } - KileDialog::NewTabularDialog dlg(env, m_latexCommands, m_config.data(), this); - if(dlg.exec()) { - insertTag(dlg.tagData(), dlg.requiredPackages()); - if(tabularenv) { - KConfigGroup group = m_config->group("Wizard"); - group.writeEntry("TabularEnvironment", dlg.environment()); - m_config->sync(); - } - } + KileDialog::NewTabularDialog dlg(env, m_latexCommands, m_config.data(), this); + if(dlg.exec()) { + insertTag(dlg.tagData(), dlg.requiredPackages()); + if(tabularenv) { + KConfigGroup group = m_config->group("Wizard"); + group.writeEntry("TabularEnvironment", dlg.environment()); + m_config->sync(); + } + } } void Kile::quickTabbing() { - if(!viewManager()->currentTextView()) { - return; - } - KileDialog::QuickTabbing *dlg = new KileDialog::QuickTabbing(m_config.data(), this, this, "Tabbing", i18n("Tabbing")); - if(dlg->exec()) { - insertTag(dlg->tagData()); - } - delete dlg; + if(!viewManager()->currentTextView()) { + return; + } + KileDialog::QuickTabbing *dlg = new KileDialog::QuickTabbing(m_config.data(), this, this, "Tabbing", i18n("Tabbing")); + if(dlg->exec()) { + insertTag(dlg->tagData()); + } + delete dlg; } void Kile::quickFloat() { - if(!viewManager()->currentTextView()) { - return; - } + if(!viewManager()->currentTextView()) { + return; + } - KileDialog::FloatEnvironmentDialog *dlg = new KileDialog::FloatEnvironmentDialog(m_config.data(), this, this); - if(dlg->exec()) { - insertTag(dlg->tagData()); - } - delete dlg; + KileDialog::FloatEnvironmentDialog *dlg = new KileDialog::FloatEnvironmentDialog(m_config.data(), this, this); + if(dlg->exec()) { + insertTag(dlg->tagData()); + } + delete dlg; } void Kile::quickMathenv() { - if(!viewManager()->currentTextView()) { - return; - } + if(!viewManager()->currentTextView()) { + return; + } - KileDialog::MathEnvironmentDialog *dlg = new KileDialog::MathEnvironmentDialog(this, m_config.data(), this, m_latexCommands); - if(dlg->exec()) { - insertTag(dlg->tagData()); - } - delete dlg; + KileDialog::MathEnvironmentDialog *dlg = new KileDialog::MathEnvironmentDialog(this, m_config.data(), this, m_latexCommands); + if(dlg->exec()) { + insertTag(dlg->tagData()); + } + delete dlg; } void Kile::quickPostscript() { - QString startdir = QDir::homePath(); - QString texfilename; + QString startdir = QDir::homePath(); + QString texfilename; - KTextEditor::View *view = viewManager()->currentTextView(); - if(view) { - startdir = QFileInfo(view->document()->url().toLocalFile()).path(); - texfilename = getCompileName(); - } + KTextEditor::View *view = viewManager()->currentTextView(); + if(view) { + startdir = QFileInfo(view->document()->url().toLocalFile()).path(); + texfilename = getCompileName(); + } - KileDialog::PostscriptDialog *dlg = new KileDialog::PostscriptDialog(this, texfilename, startdir, m_extensions->latexDocuments(), errorHandler(), m_outputWidget); - dlg->exec(); - delete dlg; + KileDialog::PostscriptDialog *dlg = new KileDialog::PostscriptDialog(this, texfilename, startdir, m_extensions->latexDocuments(), errorHandler(), m_outputWidget); + dlg->exec(); + delete dlg; } void Kile::quickPdf() { - QString startDir = QDir::homePath(); - QString texFileName; + QString startDir = QDir::homePath(); + QString texFileName; - KTextEditor::View *view = viewManager()->currentTextView(); - if(view) { - startDir = QFileInfo(view->document()->url().toLocalFile()).path(); - texFileName = getCompileName(); - } + KTextEditor::View *view = viewManager()->currentTextView(); + if(view) { + startDir = QFileInfo(view->document()->url().toLocalFile()).path(); + texFileName = getCompileName(); + } - KileDialog::PdfDialog *dlg = new KileDialog::PdfDialog(m_mainWindow, texFileName, startDir, m_extensions->latexDocuments(), m_manager, errorHandler(), m_outputWidget); - dlg->exec(); - delete dlg; + KileDialog::PdfDialog *dlg = new KileDialog::PdfDialog(m_mainWindow, texFileName, startDir, m_extensions->latexDocuments(), m_manager, errorHandler(), m_outputWidget); + dlg->exec(); + delete dlg; } void Kile::quickUserMenuDialog() { - m_userMenu->removeShortcuts(); - QPointer dlg = new KileMenu::UserMenuDialog(m_config.data(), this, m_userMenu, m_userMenu->xmlFile(), m_mainWindow); + m_userMenu->removeShortcuts(); + QPointer dlg = new KileMenu::UserMenuDialog(m_config.data(), this, m_userMenu, m_userMenu->xmlFile(), m_mainWindow); - dlg->exec(); + dlg->exec(); - connect(dlg, &QDialog::finished, this, [=] (int result) { - Q_UNUSED(result); + connect(dlg, &QDialog::finished, this, [=] (int result) { + Q_UNUSED(result); - // tell all the documents and views to update their action shortcuts (bug 247646) - docManager()->reloadXMLOnAllDocumentsAndViews(); + // tell all the documents and views to update their action shortcuts (bug 247646) + docManager()->reloadXMLOnAllDocumentsAndViews(); - // a new usermenu could have been installed, even if the return value is QDialog::Rejected - m_userMenu->refreshActionProperties(); - }); + // a new usermenu could have been installed, even if the return value is QDialog::Rejected + m_userMenu->refreshActionProperties(); + }); - delete dlg; + delete dlg; } void Kile::slotUpdateUserMenuStatus() { - KILE_DEBUG_MAIN << "slot update usermenu status"; - updateUserMenuStatus(true); + KILE_DEBUG_MAIN << "slot update usermenu status"; + updateUserMenuStatus(true); } void Kile::updateUserMenuStatus(bool state) { - KILE_DEBUG_MAIN << "update usermenu status"; + KILE_DEBUG_MAIN << "update usermenu status"; - if(m_userMenu) { - QMenu *menu = m_userMenu->getMenuItem(); - if(menu) { - updateLatexenuActivationStatus(menu,state); - } - } + if(m_userMenu) { + QMenu *menu = m_userMenu->getMenuItem(); + if(menu) { + updateLatexenuActivationStatus(menu,state); + } + } } void Kile::helpLaTex() { - QString loc = QStandardPaths::locate(QStandardPaths::DataLocation, "help/latexhelp.html"); - KileTool::Base *tool = toolManager()->createTool("ViewHTML", QString(), false); - if(!tool) { - errorHandler()->printMessage(KileTool::Error, i18n("Could not create the \"ViewHTML\" tool. Please reset the tools.")); - return; - } - tool->setFlags(KileTool::NeedSourceExists | KileTool::NeedSourceRead); - tool->setSource(loc); - tool->setTargetPath(loc); - tool->prepareToRun(); - m_manager->run(tool); + QString loc = QStandardPaths::locate(QStandardPaths::DataLocation, "help/latexhelp.html"); + KileTool::Base *tool = toolManager()->createTool("ViewHTML", QString(), false); + if(!tool) { + errorHandler()->printMessage(KileTool::Error, i18n("Could not create the \"ViewHTML\" tool. Please reset the tools.")); + return; + } + tool->setFlags(KileTool::NeedSourceExists | KileTool::NeedSourceRead); + tool->setSource(loc); + tool->setTargetPath(loc); + tool->prepareToRun(); + m_manager->run(tool); } void Kile::readGUISettings() { } // transform old user tags to xml file void Kile::transformOldUserTags() { - KILE_DEBUG_MAIN << "Convert old user tags"; - QString xmldir = QStandardPaths::writableLocation(QStandardPaths::DataLocation) + "/usermenu/"; - // create dir if not existing - QDir testDir(xmldir); - if (!testDir.exists()) { - testDir.mkpath(xmldir); - } - - KConfigGroup userGroup = m_config->group("User"); - int len = userGroup.readEntry("nUserTags", 0); - - if ( len > 0) { - QString usertagfile = "usertags.xml"; - QString filename = xmldir + usertagfile; - KILE_DEBUG_MAIN << "-convert user tags " << filename; - - QFile file(filename); - if ( !file.open(QFile::WriteOnly | QFile::Text) ) { - KILE_DEBUG_MAIN << "-Error - could not open file to write: " << filename; - return; - } - - KILE_DEBUG_MAIN << "Write xml: " << filename; - QXmlStreamWriter xml(&file); - xml.setAutoFormatting(true); - xml.setAutoFormattingIndent(2) ; - - xml.writeStartDocument(); - xml.writeStartElement("UserMenu"); - - for (int i = 0; i < len; ++i) { - const QString tagNameConfigKey = "userTagName" + QString::number(i); - const QString tagname = userGroup.readEntry(tagNameConfigKey, i18n("No Name")); - const QString tagConfigKey = "userTag" + QString::number(i); - QString tag = userGroup.readEntry(tagConfigKey, ""); - tag = tag.replace('\n',"\\n"); - - xml.writeStartElement("menu"); - xml.writeAttribute("type", "text"); - xml.writeTextElement(KileMenu::UserMenuData::xmlMenuTagName(KileMenu::UserMenuData::XML_TITLE), tagname); - xml.writeTextElement(KileMenu::UserMenuData::xmlMenuTagName(KileMenu::UserMenuData::XML_PLAINTEXT), tag); - xml.writeTextElement(KileMenu::UserMenuData::xmlMenuTagName(KileMenu::UserMenuData::XML_SHORTCUT), QString("Ctrl+Shift+%1").arg(i+1)); - xml.writeEndElement(); - - userGroup.deleteEntry(tagNameConfigKey); - userGroup.deleteEntry(tagConfigKey); - } - xml.writeEndDocument(); - file.close(); + KILE_DEBUG_MAIN << "Convert old user tags"; + QString xmldir = QStandardPaths::writableLocation(QStandardPaths::DataLocation) + "/usermenu/"; + // create dir if not existing + QDir testDir(xmldir); + if (!testDir.exists()) { + testDir.mkpath(xmldir); + } - // save current xml file - KileConfig::setUserMenuFile(usertagfile); - } - userGroup.deleteEntry("nUserTags"); + KConfigGroup userGroup = m_config->group("User"); + int len = userGroup.readEntry("nUserTags", 0); + + if ( len > 0) { + QString usertagfile = "usertags.xml"; + QString filename = xmldir + usertagfile; + KILE_DEBUG_MAIN << "-convert user tags " << filename; + + QFile file(filename); + if ( !file.open(QFile::WriteOnly | QFile::Text) ) { + KILE_DEBUG_MAIN << "-Error - could not open file to write: " << filename; + return; + } + + KILE_DEBUG_MAIN << "Write xml: " << filename; + QXmlStreamWriter xml(&file); + xml.setAutoFormatting(true); + xml.setAutoFormattingIndent(2) ; + + xml.writeStartDocument(); + xml.writeStartElement("UserMenu"); + + for (int i = 0; i < len; ++i) { + const QString tagNameConfigKey = "userTagName" + QString::number(i); + const QString tagname = userGroup.readEntry(tagNameConfigKey, i18n("No Name")); + const QString tagConfigKey = "userTag" + QString::number(i); + QString tag = userGroup.readEntry(tagConfigKey, ""); + tag = tag.replace('\n',"\\n"); + + xml.writeStartElement("menu"); + xml.writeAttribute("type", "text"); + xml.writeTextElement(KileMenu::UserMenuData::xmlMenuTagName(KileMenu::UserMenuData::XML_TITLE), tagname); + xml.writeTextElement(KileMenu::UserMenuData::xmlMenuTagName(KileMenu::UserMenuData::XML_PLAINTEXT), tag); + xml.writeTextElement(KileMenu::UserMenuData::xmlMenuTagName(KileMenu::UserMenuData::XML_SHORTCUT), QString("Ctrl+Shift+%1").arg(i+1)); + xml.writeEndElement(); + + userGroup.deleteEntry(tagNameConfigKey); + userGroup.deleteEntry(tagConfigKey); + } + xml.writeEndDocument(); + file.close(); + + // save current xml file + KileConfig::setUserMenuFile(usertagfile); + } + userGroup.deleteEntry("nUserTags"); } void Kile::transformOldUserSettings() { - //delete old editor key - if(m_config->hasGroup("Editor")) { - m_config->deleteGroup("Editor"); - } + //delete old editor key + if(m_config->hasGroup("Editor")) { + m_config->deleteGroup("Editor"); + } - //convert user tools to new KileTool classes - KConfigGroup userGroup = m_config->group("User"); - userItem tempItem; - int len = userGroup.readEntry("nUserTools", 0); - for (int i=0; i< len; ++i) { - tempItem.name = userGroup.readEntry("userToolName" + QString::number(i), i18n("no name")); - tempItem.tag = userGroup.readEntry("userTool" + QString::number(i), ""); - m_listUserTools.append(tempItem); - } - if(len > 0) { - //move the tools - userGroup.writeEntry("nUserTools", 0); - for(int i = 0; i < len; ++i) { - tempItem = m_listUserTools[i]; - KConfigGroup toolsGroup = m_config->group("Tools"); - toolsGroup.writeEntry(tempItem.name, "Default"); - - KileTool::setGUIOptions(tempItem.name, "Other", "preferences-other", m_config.data()); - - KConfigGroup group = m_config->group(KileTool::groupFor(tempItem.name, "Default")); - QString bin = KRun::binaryName(tempItem.tag, false); - group.writeEntry("command", bin); - group.writeEntry("options", tempItem.tag.mid(bin.length())); - group.writeEntry("class", "Base"); - group.writeEntry("type", "Process"); - group.writeEntry("from", ""); - group.writeEntry("to", ""); - - if(i < 10) { - QAction *toolAction = static_cast(actionCollection()->action("tool_" + tempItem.name)); - actionCollection()->setDefaultShortcut(toolAction, "Alt+Shift+" + QString::number(i + 1)); //should be alt+shift+ - } - } - } + //convert user tools to new KileTool classes + KConfigGroup userGroup = m_config->group("User"); + userItem tempItem; + int len = userGroup.readEntry("nUserTools", 0); + for (int i=0; i< len; ++i) { + tempItem.name = userGroup.readEntry("userToolName" + QString::number(i), i18n("no name")); + tempItem.tag = userGroup.readEntry("userTool" + QString::number(i), ""); + m_listUserTools.append(tempItem); + } + if(len > 0) { + //move the tools + userGroup.writeEntry("nUserTools", 0); + for(int i = 0; i < len; ++i) { + tempItem = m_listUserTools[i]; + KConfigGroup toolsGroup = m_config->group("Tools"); + toolsGroup.writeEntry(tempItem.name, "Default"); + + KileTool::setGUIOptions(tempItem.name, "Other", "preferences-other", m_config.data()); + + KConfigGroup group = m_config->group(KileTool::groupFor(tempItem.name, "Default")); + QString bin = KRun::binaryName(tempItem.tag, false); + group.writeEntry("command", bin); + group.writeEntry("options", tempItem.tag.mid(bin.length())); + group.writeEntry("class", "Base"); + group.writeEntry("type", "Process"); + group.writeEntry("from", ""); + group.writeEntry("to", ""); + + if(i < 10) { + QAction *toolAction = static_cast(actionCollection()->action("tool_" + tempItem.name)); + actionCollection()->setDefaultShortcut(toolAction, "Alt+Shift+" + QString::number(i + 1)); //should be alt+shift+ + } + } + } } void Kile::readRecentFileSettings() { - KConfigGroup group = m_config->group("FilesOpenOnStart"); - int n = group.readEntry("NoDOOS", 0); - for (int i = 0; i < n; ++i) { - const QString urlString = group.readPathEntry("DocsOpenOnStart" + QString::number(i), ""); - if(urlString.isEmpty()) { - continue; - } - m_listDocsOpenOnStart.append(urlString); - m_listEncodingsOfDocsOpenOnStart.append(group.readPathEntry("EncodingsOfDocsOpenOnStart" + QString::number(i), "")); - } + KConfigGroup group = m_config->group("FilesOpenOnStart"); + int n = group.readEntry("NoDOOS", 0); + for (int i = 0; i < n; ++i) { + const QString urlString = group.readPathEntry("DocsOpenOnStart" + QString::number(i), ""); + if(urlString.isEmpty()) { + continue; + } + m_listDocsOpenOnStart.append(urlString); + m_listEncodingsOfDocsOpenOnStart.append(group.readPathEntry("EncodingsOfDocsOpenOnStart" + QString::number(i), "")); + } - n = group.readEntry("NoPOOS", 0); - for(int i = 0; i < n; ++i) { - const QString urlString = group.readPathEntry("ProjectsOpenOnStart" + QString::number(i), ""); - if(urlString.isEmpty()) { - continue; - } - m_listProjectsOpenOnStart.append(urlString); - } + n = group.readEntry("NoPOOS", 0); + for(int i = 0; i < n; ++i) { + const QString urlString = group.readPathEntry("ProjectsOpenOnStart" + QString::number(i), ""); + if(urlString.isEmpty()) { + continue; + } + m_listProjectsOpenOnStart.append(urlString); + } } void Kile::readConfig() { - m_codeCompletionManager->readConfig(m_config.data()); + m_codeCompletionManager->readConfig(m_config.data()); - m_livePreviewManager->readConfig(m_config.data()); + m_livePreviewManager->readConfig(m_config.data()); - //m_edit->initDoubleQuotes(); - m_edit->readConfig(); - docManager()->updateInfos(); - m_jScriptManager->readConfig(); - docManager()->readConfig(); - viewManager()->readConfig(m_horizontalSplitter); + //m_edit->initDoubleQuotes(); + m_edit->readConfig(); + docManager()->updateInfos(); + m_jScriptManager->readConfig(); + docManager()->readConfig(); + viewManager()->readConfig(m_horizontalSplitter); - // set visible views in sidebar - m_sideBar->setPageVisible(m_scriptsManagementWidget, KileConfig::scriptingEnabled()); - m_sideBar->setPageVisible(m_commandViewToolBox, KileConfig::showCwlCommands()); - m_sideBar->setPageVisible(m_kileAbbrevView, KileConfig::completeShowAbbrev()); + // set visible views in sidebar + m_sideBar->setPageVisible(m_scriptsManagementWidget, KileConfig::scriptingEnabled()); + m_sideBar->setPageVisible(m_commandViewToolBox, KileConfig::showCwlCommands()); + m_sideBar->setPageVisible(m_kileAbbrevView, KileConfig::completeShowAbbrev()); - m_scriptsManagementWidget->setScriptNameColumnWidth(KileConfig::scriptNameColumnWidth()); + m_scriptsManagementWidget->setScriptNameColumnWidth(KileConfig::scriptNameColumnWidth()); - if(KileConfig::displayMFUS()) { - enableSymbolViewMFUS(); - } - else { - disableSymbolViewMFUS(); - } - m_commandViewToolBox->readCommandViewFiles(); - abbreviationManager()->readAbbreviationFiles(); + if(KileConfig::displayMFUS()) { + enableSymbolViewMFUS(); + } + else { + disableSymbolViewMFUS(); + } + m_commandViewToolBox->readCommandViewFiles(); + abbreviationManager()->readAbbreviationFiles(); } void Kile::saveSettings() { - m_fileBrowserWidget->writeConfig(); + m_fileBrowserWidget->writeConfig(); - m_livePreviewManager->writeConfig(); + m_livePreviewManager->writeConfig(); - m_symbolViewMFUS->writeConfig(); - saveLastSelectedAction(); - // Store recent files - m_actRecentFiles->saveEntries(m_config->group("Recent Files")); - m_actRecentProjects->saveEntries(m_config->group("Projects")); + m_symbolViewMFUS->writeConfig(); + saveLastSelectedAction(); + // Store recent files + m_actRecentFiles->saveEntries(m_config->group("Recent Files")); + m_actRecentProjects->saveEntries(m_config->group("Projects")); - m_config->deleteGroup("FilesOpenOnStart"); - if (KileConfig::restore()) - { - KConfigGroup configGroup = m_config->group("FilesOpenOnStart"); - KileConfig::setSingleFileMasterDocument(getMasterDocumentFileName()); - configGroup.writeEntry("NoDOOS", m_listDocsOpenOnStart.count()); - for (int i = 0; i < m_listDocsOpenOnStart.count(); ++i) { - configGroup.writePathEntry("DocsOpenOnStart" + QString::number(i), m_listDocsOpenOnStart[i]); - configGroup.writePathEntry("EncodingsOfDocsOpenOnStart" + QString::number(i), m_listEncodingsOfDocsOpenOnStart[i]); - } - - configGroup.writeEntry("NoPOOS", m_listProjectsOpenOnStart.count()); - for (int i = 0; i < m_listProjectsOpenOnStart.count(); ++i) { - configGroup.writePathEntry("ProjectsOpenOnStart"+QString::number(i), m_listProjectsOpenOnStart[i]); - } - } + m_config->deleteGroup("FilesOpenOnStart"); + if (KileConfig::restore()) + { + KConfigGroup configGroup = m_config->group("FilesOpenOnStart"); + KileConfig::setSingleFileMasterDocument(getMasterDocumentFileName()); + configGroup.writeEntry("NoDOOS", m_listDocsOpenOnStart.count()); + for (int i = 0; i < m_listDocsOpenOnStart.count(); ++i) { + configGroup.writePathEntry("DocsOpenOnStart" + QString::number(i), m_listDocsOpenOnStart[i]); + configGroup.writePathEntry("EncodingsOfDocsOpenOnStart" + QString::number(i), m_listEncodingsOfDocsOpenOnStart[i]); + } + + configGroup.writeEntry("NoPOOS", m_listProjectsOpenOnStart.count()); + for (int i = 0; i < m_listProjectsOpenOnStart.count(); ++i) { + configGroup.writePathEntry("ProjectsOpenOnStart"+QString::number(i), m_listProjectsOpenOnStart[i]); + } + } - KConfigGroup configGroup = KSharedConfig::openConfig()->group("KileMainWindow"); - saveMainWindowSettings(configGroup); - - docManager()->writeConfig(); - viewManager()->writeConfig(); - - scriptManager()->writeConfig(); - KileConfig::setScriptNameColumnWidth(m_scriptsManagementWidget->scriptNameColumnWidth()); - - KileConfig::setRCVersion(KILERC_VERSION); - KileConfig::setMainwindowWidth(width()); - KileConfig::setMainwindowHeight(height()); - - QList sizes; - QList::Iterator it; - sizes = m_horizontalSplitter->sizes(); - it = sizes.begin(); - KileConfig::setHorizontalSplitterLeft(*it); - ++it; - KileConfig::setHorizontalSplitterRight(*it); - sizes.clear(); - sizes = m_verticalSplitter->sizes(); - it = sizes.begin(); - KileConfig::setVerticalSplitterTop(*it); - ++it; - KileConfig::setVerticalSplitterBottom(*it); + KConfigGroup configGroup = KSharedConfig::openConfig()->group("KileMainWindow"); + saveMainWindowSettings(configGroup); + + docManager()->writeConfig(); + viewManager()->writeConfig(); + + scriptManager()->writeConfig(); + KileConfig::setScriptNameColumnWidth(m_scriptsManagementWidget->scriptNameColumnWidth()); + + KileConfig::setRCVersion(KILERC_VERSION); + KileConfig::setMainwindowWidth(width()); + KileConfig::setMainwindowHeight(height()); + + QList sizes; + QList::Iterator it; + sizes = m_horizontalSplitter->sizes(); + it = sizes.begin(); + KileConfig::setHorizontalSplitterLeft(*it); + ++it; + KileConfig::setHorizontalSplitterRight(*it); + sizes.clear(); + sizes = m_verticalSplitter->sizes(); + it = sizes.begin(); + KileConfig::setVerticalSplitterTop(*it); + ++it; + KileConfig::setVerticalSplitterBottom(*it); #ifdef __GNUC__ #warning Restoring the side bar sizes from minimized after start up does not work perfectly yet! #endif // // sync vertical splitter and size of bottom bar // int sizeBottomBar = m_bottomBar->directionalSize(); // if(m_bottomBar->isVisible()) { // sizeBottomBar = m_verSplitBottom; // } // else { // m_verSplitBottom = sizeBottomBar; // } - KileConfig::setSideBar(!m_sideBar->isHidden()); // do not use 'isVisible()'! - KileConfig::setSideBarSize(m_sideBar->directionalSize()); - KileConfig::setBottomBar(!m_bottomBar->isHidden()); // do not use 'isVisible()'! - KileConfig::setBottomBarSize(m_bottomBar->directionalSize()); - KileConfig::setBottomBarIndex(m_bottomBar->currentTab()); + KileConfig::setSideBar(!m_sideBar->isHidden()); // do not use 'isVisible()'! + KileConfig::setSideBarSize(m_sideBar->directionalSize()); + KileConfig::setBottomBar(!m_bottomBar->isHidden()); // do not use 'isVisible()'! + KileConfig::setBottomBarSize(m_bottomBar->directionalSize()); + KileConfig::setBottomBarIndex(m_bottomBar->currentTab()); - KileConfig::setSelectedLeftView(m_sideBar->currentTab()); + KileConfig::setSelectedLeftView(m_sideBar->currentTab()); - abbreviationManager()->saveLocalAbbreviations(); + abbreviationManager()->saveLocalAbbreviations(); - KileConfig::self()->save(); - m_config->sync(); + KileConfig::self()->save(); + m_config->sync(); } ///////////////// OPTIONS //////////////////// void Kile::setMasterDocumentFileName(const QString& fileName) { - if(fileName.isEmpty() || !viewManager()->viewForLocalFilePresent(fileName)) { - return; - } + if(fileName.isEmpty() || !viewManager()->viewForLocalFilePresent(fileName)) { + return; + } - m_masterDocumentFileName = fileName; + m_masterDocumentFileName = fileName; - QString shortName = QFileInfo(m_masterDocumentFileName).fileName(); + QString shortName = QFileInfo(m_masterDocumentFileName).fileName(); - ModeAction->setText(i18n("Normal mode (current master document: %1)", shortName)); - ModeAction->setChecked(true); - m_singlemode = false; - updateModeStatus(); - emit masterDocumentChanged(); - KILE_DEBUG_MAIN << "SETTING master to " << m_masterDocumentFileName << " singlemode = " << m_singlemode << endl; + ModeAction->setText(i18n("Normal mode (current master document: %1)", shortName)); + ModeAction->setChecked(true); + m_singlemode = false; + updateModeStatus(); + emit masterDocumentChanged(); + KILE_DEBUG_MAIN << "SETTING master to " << m_masterDocumentFileName << " singlemode = " << m_singlemode << endl; } void Kile::clearMasterDocument() { - ModeAction->setText(i18n("Define Current Document as 'Master Document'")); - ModeAction->setChecked(false); - m_singlemode = true; - m_masterDocumentFileName.clear(); - updateModeStatus(); - emit masterDocumentChanged(); - KILE_DEBUG_MAIN << "CLEARING master document"; + ModeAction->setText(i18n("Define Current Document as 'Master Document'")); + ModeAction->setChecked(false); + m_singlemode = true; + m_masterDocumentFileName.clear(); + updateModeStatus(); + emit masterDocumentChanged(); + KILE_DEBUG_MAIN << "CLEARING master document"; } void Kile::toggleMasterDocumentMode() { - if (!m_singlemode) { - clearMasterDocument(); - } - else if (m_singlemode && viewManager()->currentTextView()) { - QString name = getName(); - if(name.isEmpty()) { - ModeAction->setChecked(false); - KMessageBox::error(this, i18n("In order to define the current document as a master document, it has to be saved first.")); - return; - } - setMasterDocumentFileName(name); - } - else { - ModeAction->setChecked(false); - updateModeStatus(); - } + if (!m_singlemode) { + clearMasterDocument(); + } + else if (m_singlemode && viewManager()->currentTextView()) { + QString name = getName(); + if(name.isEmpty()) { + ModeAction->setChecked(false); + KMessageBox::error(this, i18n("In order to define the current document as a master document, it has to be saved first.")); + return; + } + setMasterDocumentFileName(name); + } + else { + ModeAction->setChecked(false); + updateModeStatus(); + } } void Kile::toggleWatchFile() { - m_bWatchFile=!m_bWatchFile; + m_bWatchFile=!m_bWatchFile; - if (m_bWatchFile) { - WatchFileAction->setChecked(true); - } - else { - WatchFileAction->setChecked(false); - } + if (m_bWatchFile) { + WatchFileAction->setChecked(true); + } + else { + WatchFileAction->setChecked(false); + } } // execute configuration dialog void Kile::generalOptions() { - KileDialog::Config *dlg = new KileDialog::Config(m_config.data(), this, this); - KileUtilities::scheduleCenteringOfWidget(dlg); + KileDialog::Config *dlg = new KileDialog::Config(m_config.data(), this, this); + KileUtilities::scheduleCenteringOfWidget(dlg); - if (dlg->exec()) { - // update new settings - readConfig(); - saveLastSelectedAction(); // save the old current tools before calling setupTools() which calls restoreLastSelectedActions() - setupTools(); - m_help->update(); - newCaption(); // for the 'showFullPathInWindowTitle' setting + if (dlg->exec()) { + // update new settings + readConfig(); + saveLastSelectedAction(); // save the old current tools before calling setupTools() which calls restoreLastSelectedActions() + setupTools(); + m_help->update(); + newCaption(); // for the 'showFullPathInWindowTitle' setting - configurationManager()->emitConfigChanged(); + configurationManager()->emitConfigChanged(); - //stop/restart LyX server if necessary - if(KileConfig::runLyxServer() && !m_lyxserver->isRunning()) { - m_lyxserver->start(); - } + //stop/restart LyX server if necessary + if(KileConfig::runLyxServer() && !m_lyxserver->isRunning()) { + m_lyxserver->start(); + } - if(!KileConfig::runLyxServer() && m_lyxserver->isRunning()) { - m_lyxserver->stop(); - } - } + if(!KileConfig::runLyxServer() && m_lyxserver->isRunning()) { + m_lyxserver->stop(); + } + } - delete dlg; + delete dlg; } void Kile::slotPerformCheck() { - // first we have to disable the live preview that may be running, and clear the master document - const bool livePreviewEnabledForFreshlyOpenedDocuments = KileConfig::previewEnabledForFreshlyOpenedDocuments(); - const bool livePreviewEnabledForCurrentDocument = livePreviewManager() && livePreviewManager()->isLivePreviewEnabledForCurrentDocument(); - if (livePreviewManager()) { - KileConfig::setPreviewEnabledForFreshlyOpenedDocuments(false); - livePreviewManager()->setLivePreviewEnabledForCurrentDocument(false); - } + // first we have to disable the live preview that may be running, and clear the master document + const bool livePreviewEnabledForFreshlyOpenedDocuments = KileConfig::previewEnabledForFreshlyOpenedDocuments(); + const bool livePreviewEnabledForCurrentDocument = livePreviewManager() && livePreviewManager()->isLivePreviewEnabledForCurrentDocument(); + if (livePreviewManager()) { + KileConfig::setPreviewEnabledForFreshlyOpenedDocuments(false); + livePreviewManager()->setLivePreviewEnabledForCurrentDocument(false); + } - // we show the message output widget in the bottom bar and shrink the side bar - int sideBarTab = m_sideBar->currentTab(); - int bottomBarTab = m_bottomBar->currentTab(); + // we show the message output widget in the bottom bar and shrink the side bar + int sideBarTab = m_sideBar->currentTab(); + int bottomBarTab = m_bottomBar->currentTab(); - m_sideBar->shrink(); - m_bottomBar->switchToTab(0); // show the log widget + m_sideBar->shrink(); + m_bottomBar->switchToTab(0); // show the log widget - int outputTab = m_errorHandler->currentOutputTabIndex(); - m_errorHandler->showMessagesOutput(); + int outputTab = m_errorHandler->currentOutputTabIndex(); + m_errorHandler->showMessagesOutput(); - QString currentMasterDocument = m_masterDocumentFileName; - if(!m_singlemode) { - clearMasterDocument(); - } - // we hide the editor pane and tabs - m_viewManager->setTabsAndEditorVisible(false); + QString currentMasterDocument = m_masterDocumentFileName; + if(!m_singlemode) { + clearMasterDocument(); + } + // we hide the editor pane and tabs + m_viewManager->setTabsAndEditorVisible(false); - // now, we can run the tests - KileDialog::ConfigChecker *dlg = new KileDialog::ConfigChecker(this); - dlg->exec(); - delete dlg; + // now, we can run the tests + KileDialog::ConfigChecker *dlg = new KileDialog::ConfigChecker(this); + dlg->exec(); + delete dlg; - m_errorHandler->clearMessages(); - m_errorHandler->clearErrorOutput(); + m_errorHandler->clearMessages(); + m_errorHandler->clearErrorOutput(); - // finally, we restore the rest to what it was before launching the tests - m_viewManager->setTabsAndEditorVisible(true); - if(!currentMasterDocument.isEmpty()) { - setMasterDocumentFileName(currentMasterDocument); - } + // finally, we restore the rest to what it was before launching the tests + m_viewManager->setTabsAndEditorVisible(true); + if(!currentMasterDocument.isEmpty()) { + setMasterDocumentFileName(currentMasterDocument); + } - m_errorHandler->setCurrentOutputTab(outputTab); + m_errorHandler->setCurrentOutputTab(outputTab); - if(sideBarTab >= 0) { - m_sideBar->switchToTab(sideBarTab); - } - if(bottomBarTab < 0) { - m_bottomBar->shrink(); - } - else { - m_bottomBar->switchToTab(bottomBarTab); - } + if(sideBarTab >= 0) { + m_sideBar->switchToTab(sideBarTab); + } + if(bottomBarTab < 0) { + m_bottomBar->shrink(); + } + else { + m_bottomBar->switchToTab(bottomBarTab); + } - if (livePreviewManager()) { - KileConfig::setPreviewEnabledForFreshlyOpenedDocuments(livePreviewEnabledForFreshlyOpenedDocuments); - if(livePreviewEnabledForCurrentDocument) { - livePreviewManager()->setLivePreviewEnabledForCurrentDocument(true); - } - } + if (livePreviewManager()) { + KileConfig::setPreviewEnabledForFreshlyOpenedDocuments(livePreviewEnabledForFreshlyOpenedDocuments); + if(livePreviewEnabledForCurrentDocument) { + livePreviewManager()->setLivePreviewEnabledForCurrentDocument(true); + } + } } void Kile::aboutEditorComponent() { - KTextEditor::Editor *editor = m_docManager->getEditor(); - if(!editor) { - return; - } - KAboutApplicationDialog dialog(editor->aboutData(), this); - dialog.exec(); + KTextEditor::Editor *editor = m_docManager->getEditor(); + if(!editor) { + return; + } + KAboutApplicationDialog dialog(editor->aboutData(), this); + dialog.exec(); } /////////////// KEYS - TOOLBARS CONFIGURATION //////////////// void Kile::configureKeys() { - KShortcutsDialog dlg(KShortcutsEditor::AllActions, KShortcutsEditor::LetterShortcutsAllowed, this); + KShortcutsDialog dlg(KShortcutsEditor::AllActions, KShortcutsEditor::LetterShortcutsAllowed, this); // due to bug 280988, we can't add all the clients... // QList clients = guiFactory()->clients(); // for(QList::iterator it = clients.begin(); it != clients.end(); ++it) { // dlg.addCollection((*it)->actionCollection()); // } - dlg.addCollection(mainWindow()->actionCollection()); - KTextEditor::View *view = m_viewManager->currentTextView(); - if(view) { - dlg.addCollection(view->actionCollection()); - } - KParts::ReadOnlyPart *part = viewManager()->viewerPart(); - if(part) { - dlg.addCollection(part->actionCollection()); - } - dlg.configure(); + dlg.addCollection(mainWindow()->actionCollection()); + KTextEditor::View *view = m_viewManager->currentTextView(); + if(view) { + dlg.addCollection(view->actionCollection()); + } + KParts::ReadOnlyPart *part = viewManager()->viewerPart(); + if(part) { + dlg.addCollection(part->actionCollection()); + } + dlg.configure(); - // tell all the documents and views to update their action shortcuts (bug 247646) - docManager()->reloadXMLOnAllDocumentsAndViews(); + // tell all the documents and views to update their action shortcuts (bug 247646) + docManager()->reloadXMLOnAllDocumentsAndViews(); - // tell m_userMenu that key bindings may have been changed - m_userMenu->updateKeyBindings(); + // tell m_userMenu that key bindings may have been changed + m_userMenu->updateKeyBindings(); } void Kile::configureToolbars() { - { - KConfigGroup configGroup = KSharedConfig::openConfig()->group("KileMainWindow"); - saveMainWindowSettings(configGroup); - } + { + KConfigGroup configGroup = KSharedConfig::openConfig()->group("KileMainWindow"); + saveMainWindowSettings(configGroup); + } - KEditToolBar dlg(factory()); - connect(&dlg, &KEditToolBar::newToolBarConfig, this, [=] () { - setUpdatesEnabled(false); - applyMainWindowSettings(m_config->group("KileMainWindow")); + KEditToolBar dlg(factory()); + connect(&dlg, &KEditToolBar::newToolBarConfig, this, [=] () { + setUpdatesEnabled(false); + applyMainWindowSettings(m_config->group("KileMainWindow")); - updateUserDefinedMenus(); - setUpdatesEnabled(true); - }); - dlg.exec(); + updateUserDefinedMenus(); + setUpdatesEnabled(true); + }); + dlg.exec(); } //////////////////// CLEAN BIB ///////////////////// void Kile::cleanBib() { - KTextEditor::View *view = viewManager()->currentTextView(); - if ( ! view ) - return; - - QRegExp reOptional( "(ALT|OPT)(\\w+)\\s*=\\s*(\\S.*)" ); - QRegExp reNonEmptyEntry( ".*\\w.*" ); - - QString s; - int i = 0; - while(i < view->document()->lines()) { - s = view->document()->line(i); - - // do we have a line that starts with ALT or OPT? - if(reOptional.indexIn(s) >= 0) { - // yes! capture type and entry - QString type = reOptional.cap( 2 ); - QString entry = reOptional.cap( 3 ); - view->document()->removeLine( i ); - view->document()->setModified(true); - if(reNonEmptyEntry.indexIn(entry) >= 0) { - type.append(" = "); - type.append(entry); - view->document()->insertLine(i, type); - ++i; - } - } - else { - ++i; - } - } - int j = 0; - for (i = 0; i < view->document()->lines(); ++i) { - j = i+1; - if(j < view->document()->lines() && view->document()->line(j).contains(QRegExp("^\\s*\\}\\s*$"))) { - s = view->document()->line(i); - view->document()->removeLine(i); - s.remove(QRegExp(",\\s*$")); - view->document()->setModified(true); - view->document()->insertLine(i, s); - } - } + KTextEditor::View *view = viewManager()->currentTextView(); + if ( ! view ) + return; + + QRegExp reOptional( "(ALT|OPT)(\\w+)\\s*=\\s*(\\S.*)" ); + QRegExp reNonEmptyEntry( ".*\\w.*" ); + + QString s; + int i = 0; + while(i < view->document()->lines()) { + s = view->document()->line(i); + + // do we have a line that starts with ALT or OPT? + if(reOptional.indexIn(s) >= 0) { + // yes! capture type and entry + QString type = reOptional.cap( 2 ); + QString entry = reOptional.cap( 3 ); + view->document()->removeLine( i ); + view->document()->setModified(true); + if(reNonEmptyEntry.indexIn(entry) >= 0) { + type.append(" = "); + type.append(entry); + view->document()->insertLine(i, type); + ++i; + } + } + else { + ++i; + } + } + int j = 0; + for (i = 0; i < view->document()->lines(); ++i) { + j = i+1; + if(j < view->document()->lines() && view->document()->line(j).contains(QRegExp("^\\s*\\}\\s*$"))) { + s = view->document()->line(i); + view->document()->removeLine(i); + s.remove(QRegExp(",\\s*$")); + view->document()->setModified(true); + view->document()->insertLine(i, s); + } + } } void Kile::includeGraphics() { - KTextEditor::View *view = viewManager()->currentTextView(); - if ( !view ) return; + KTextEditor::View *view = viewManager()->currentTextView(); + if ( !view ) return; - QFileInfo fi( view->document()->url().toLocalFile() ); - KileDialog::IncludeGraphics *dialog = new KileDialog::IncludeGraphics(this, fi.path(), this); + QFileInfo fi( view->document()->url().toLocalFile() ); + KileDialog::IncludeGraphics *dialog = new KileDialog::IncludeGraphics(this, fi.path(), this); - if ( dialog->exec() == QDialog::Accepted ) - { - insertTag(dialog->getTemplate(), "%C", 0,0); - docManager()->projectAddFile( dialog->getFilename(),true ); - } + if ( dialog->exec() == QDialog::Accepted ) + { + insertTag(dialog->getTemplate(), "%C", 0,0); + docManager()->projectAddFile( dialog->getFilename(),true ); + } - delete dialog; + delete dialog; } void Kile::slotToggleFullScreen() { - if (!m_pFullScreen->isChecked()) { - setWindowState( windowState() & ~Qt::WindowFullScreen ); - } - else { - setWindowState( windowState() | Qt::WindowFullScreen ); - } + if (!m_pFullScreen->isChecked()) { + setWindowState( windowState() & ~Qt::WindowFullScreen ); + } + else { + setWindowState( windowState() | Qt::WindowFullScreen ); + } } /////////////// QuickPreview (dani) //////////////// // all calls of QuickPreview will get here, so we can decide what to do // rewritten Sep 05 2006 to work together with preview in the bottom bar void Kile::slotQuickPreview(int type) { - KILE_DEBUG_MAIN << "==Kile::slotQuickPreview()==========================" << endl; + KILE_DEBUG_MAIN << "==Kile::slotQuickPreview()==========================" << endl; - KTextEditor::View *view = viewManager()->currentTextView(); - if ( ! view) return; + KTextEditor::View *view = viewManager()->currentTextView(); + if ( ! view) return; - KTextEditor::Document *doc = view->document(); - if ( ! doc ) - return; + KTextEditor::Document *doc = view->document(); + if ( ! doc ) + return; - switch ( type ) - { - case KileTool::qpSelection: m_quickPreview->previewSelection(view); break; - case KileTool::qpEnvironment: m_quickPreview->previewEnvironment(doc); break; - case KileTool::qpSubdocument: m_quickPreview->previewSubdocument(doc); break; - case KileTool::qpMathgroup: m_quickPreview->previewMathgroup(doc); break; - } + switch ( type ) + { + case KileTool::qpSelection: + m_quickPreview->previewSelection(view); + break; + case KileTool::qpEnvironment: + m_quickPreview->previewEnvironment(doc); + break; + case KileTool::qpSubdocument: + m_quickPreview->previewSubdocument(doc); + break; + case KileTool::qpMathgroup: + m_quickPreview->previewMathgroup(doc); + break; + } } /* FIXME Port the citeViewBib function as soon as we got a kbib version for KDE4. void Kile::citeViewBib() { KILE_DEBUG_MAIN << "===void Kile::citeViewBib()===" << endl; DCOPClient *client = kapp->dcopClient(); QByteArray params, replyData; Q3CString replyType; QDataStream stream(params, QIODevice::WriteOnly); QCStringList functions,remoteApps,remoteObjs; const Q3CString viewBibApp = "kbib"; // currently these things are hardcoded because only kbib supports it const Q3CString viewBibObj = "kbibapp"; const Q3CString viewBibFncDef = "QString cite()"; const Q3CString viewBibFnc = "cite()"; remoteApps = client->registeredApplications(); if( !remoteApps.contains(viewBibApp) ) { errorHandler()->printMessage(KileTool::Warning, i18n("No ViewBib tool running, trying to start it now"), i18n("ViewBib Citation")); uint ret = runWith("ViewBib","KBib"); if( ret == 0 ) errorHandler()->printMessage(KileTool::Info, i18n("Please select the desired bibliographies and re-execute this command"), i18n("ViewBib Citation")); return; } remoteObjs = client->remoteObjects(viewBibApp); if( !remoteObjs.contains(viewBibObj) ) { errorHandler()->printMessage(KileTool::Warning, i18n("The ViewBib tool does not have the correct interface"), i18n("ViewBib Citation")); return; } functions = client->remoteFunctions(viewBibApp,viewBibObj); if( !functions.contains(viewBibFncDef) ) { errorHandler()->printMessage(KileTool::Warning, i18n("The ViewBib tool does not have the correct definition of the cite function"), i18n("ViewBib Citation")); return; } if ( !client->call(viewBibApp, viewBibObj, viewBibFnc, params, replyType, replyData) ) { // we should never get here qWarning() << "internal error in viewbib citation" << endl; return; } else{ QDataStream reply(replyData, QIODevice::ReadOnly); if (replyType == "QString") { QString result; reply >> result; if (result.isEmpty()) { errorHandler()->printMessage(KileTool::Warning, i18n("No reference selected.\nPlease select a reference first!"), i18n("ViewBib Citation")); } else { insertTag(KileAction::TagData(i18n("ViewBib Citation"), result, QString(), result.length())); } } } } */ void Kile::addRecentFile(const QUrl &url) { - m_actRecentFiles->addUrl(url); + m_actRecentFiles->addUrl(url); } void Kile::removeRecentFile(const QUrl &url) { - m_actRecentFiles->removeUrl(url); + m_actRecentFiles->removeUrl(url); } void Kile::addRecentProject(const QUrl &url) { - m_actRecentProjects->addUrl(url); + m_actRecentProjects->addUrl(url); } void Kile::removeRecentProject(const QUrl &url) { - m_actRecentProjects->removeUrl(url); + m_actRecentProjects->removeUrl(url); } void Kile::updateStatusBarCursorPosition(KTextEditor::View *view, - const KTextEditor::Cursor &newPosition) + const KTextEditor::Cursor &newPosition) { - if(!view) { - statusBar()->clearLineColumn(); - } - else { - statusBar()->setLineColumn(newPosition.line() + 1, newPosition.column() + 1); - } + if(!view) { + statusBar()->clearLineColumn(); + } + else { + statusBar()->setLineColumn(newPosition.line() + 1, newPosition.column() + 1); + } } void Kile::updateStatusBarViewMode(KTextEditor::View *view) { - if(!view) { - statusBar()->clearViewMode(); - } - else { - statusBar()->setViewMode(view->viewModeHuman()); - } + if(!view) { + statusBar()->clearViewMode(); + } + else { + statusBar()->setViewMode(view->viewModeHuman()); + } } void Kile::updateStatusBarInformationMessage(KTextEditor::View * /* view */, const QString &message) { - statusBar()->showMessage(message, 5000); + statusBar()->showMessage(message, 5000); } void Kile::updateStatusBarSelection(KTextEditor::View *view) { - if(!view) { - statusBar()->clearSelectionMode(); - } - else { - const QString text = view->blockSelection() ? - i18nc("@info:status status bar label for block selection mode", "BLOCK") + ' ' : - i18nc("@info:status status bar label for line selection mode", "LINE") + ' '; - statusBar()->setSelectionMode(text); - } + if(!view) { + statusBar()->clearSelectionMode(); + } + else { + const QString text = view->blockSelection() ? + i18nc("@info:status status bar label for block selection mode", "BLOCK") + ' ' : + i18nc("@info:status status bar label for line selection mode", "LINE") + ' '; + statusBar()->setSelectionMode(text); + } } void Kile::handleDocumentParsingStarted() { - statusBar()->setParserStatus(i18n("Refreshing structure...")); + statusBar()->setParserStatus(i18n("Refreshing structure...")); } void Kile::handleDocumentParsingComplete() { - statusBar()->clearParserStatus(); + statusBar()->clearParserStatus(); } diff --git a/src/kile.h b/src/kile.h index dc198fe6..70bcdae3 100644 --- a/src/kile.h +++ b/src/kile.h @@ -1,326 +1,345 @@ /*************************************************************************************** begin : sam jui 13 09:50:06 CEST 2002 copyright : (C) 2003 by Jeroen Wijnhout (wijnhout@science.uva.nl) 2007-2012 by Michel Ludwig (michel.ludwig@kdemail.net) (C) 2009 Thomas Braun (thomas.braun@virtuell-zuhause.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. * * * ***************************************************************************/ #ifndef KILE_H #define KILE_H #include #include #include #include #include #include #include #include #include #include #include #include #include "widgets/filebrowserwidget.h" #include "kileinfo.h" #include "kileactions.h" #include "kileversion.h" #include "widgets/symbolview.h" #include "widgets/commandview.h" #include "outputinfo.h" #include "codecompletion.h" // code completion (dani) #include "editorextension.h" // advanced editor (dani) #include "kilehelp.h" // kile help (dani) #include "quickpreview.h" #include "widgets/abbreviationview.h" class QFileInfo; class QTimer; class QSignalMapper; class KToolBar; class QAction; class KActionMenu; class KRecentFilesAction; class KToggleFullScreenAction; class KToggleToolBarAction; class KMultiTabBar; -namespace KParts { class MainWindow; } +namespace KParts { +class MainWindow; +} class KileLyxServer; class KileProject; class KileProjectItem; class TemplateItem; class KileAutoSaveJob; -namespace KileAction { class TagData; } -namespace KileDocument { class Info; class TextInfo; class Extensions; } -namespace KileTool { class Manager; class Factory; } +namespace KileAction { +class TagData; +} +namespace KileDocument { +class Info; +class TextInfo; +class Extensions; +} +namespace KileTool { +class Manager; +class Factory; +} namespace KileWidget { - class LogWidget; - class Output; - class Konsole; - class StructureWidget; - class SideBar; - class BottomBar; - class StatusBar; +class LogWidget; +class Output; +class Konsole; +class StructureWidget; +class SideBar; +class BottomBar; +class StatusBar; } //TODO remove once we stop supporting pre 1.7 user tools struct userItem { - QString name, tag; + QString name, tag; }; /** * The Kile main class. It acts as information manager and DBUS interface. **/ class Kile : public KParts::MainWindow, public KileInfo { - Q_OBJECT + Q_OBJECT public: - explicit Kile(bool allowRestore = true, QWidget *parent = Q_NULLPTR); - ~Kile(); + explicit Kile(bool allowRestore = true, QWidget *parent = Q_NULLPTR); + ~Kile(); - int lineNumber(); - KileWidget::StatusBar * statusBar(); + int lineNumber(); + KileWidget::StatusBar * statusBar(); public Q_SLOTS: - void setCursor(const QUrl &, int, int); + void setCursor(const QUrl &, int, int); - void runArchiveTool(); - void runArchiveTool(const QUrl&); + void runArchiveTool(); + void runArchiveTool(const QUrl&); - void updateModeStatus(); - void newCaption(); + void updateModeStatus(); + void newCaption(); // void citeViewBib(); - void rebuildBibliographyMenu(); - - void openDocument(const QUrl &url); - void openProject(const QUrl &url); - - // D-Bus Interface - void openDocument(const QString & url); - void closeDocument(); - void setActive(); - /** - * @param line : Jump to give line in current editor (can be called via DBUS interface). - **/ - void setLine(const QString &line); - void openProject(const QString& proj); - void runTool(const QString& tool); - void runToolWithConfig(const QString &tool, const QString &config); - void insertText(const QString &text); - void insertTag(const KileAction::TagData& td); + void rebuildBibliographyMenu(); + + void openDocument(const QUrl &url); + void openProject(const QUrl &url); + + // D-Bus Interface + void openDocument(const QString & url); + void closeDocument(); + void setActive(); + /** + * @param line : Jump to give line in current editor (can be called via DBUS interface). + **/ + void setLine(const QString &line); + void openProject(const QString& proj); + void runTool(const QString& tool); + void runToolWithConfig(const QString &tool, const QString &config); + void insertText(const QString &text); + void insertTag(const KileAction::TagData& td); Q_SIGNALS: - void masterDocumentChanged(); + void masterDocumentChanged(); protected: - virtual bool queryClose(); + virtual bool queryClose(); private: - QMap m_dictMenuAction, m_dictMenuFile, m_dictMenuProject; - - KToolBar *m_toolsToolBar; - KActionMenu *m_userHelpActionMenu; - KSelectAction *m_bibTagSettings; - ToolbarSelectAction *m_compilerActions, *m_viewActions, *m_convertActions, *m_quickActions; - QList m_listUserTags; - QList m_listUserTools; - QList m_listQuickActions, m_listCompilerActions, m_listConverterActions, m_listViewerActions, m_listOtherActions; - KActionMenu *m_bibTagActionMenu; - QAction *m_paStop, *m_paPrint; - KToggleAction *ModeAction, *WatchFileAction; - KToggleAction *m_actionMessageView; - KRecentFilesAction *m_actRecentFiles; - KToggleFullScreenAction *m_pFullScreen; - - /* GUI */ - //widgets - KileWidget::SideBar *m_sideBar; - KileWidget::AbbreviationView *m_kileAbbrevView; - QStackedWidget *m_topWidgetStack; - QSplitter *m_horizontalSplitter, *m_verticalSplitter; - QToolBox *m_toolBox; - KileWidget::CommandViewToolBox *m_commandViewToolBox; - KileWidget::SymbolView *m_symbolViewMFUS, *m_symbolViewRelation, *m_symbolViewArrows, *m_symbolViewMiscMath, *m_symbolViewMiscText, *m_symbolViewOperators, *m_symbolViewUser, *m_symbolViewDelimiters, *m_symbolViewGreek, *m_symbolViewSpecial, *m_symbolViewCyrillic; - KileWidget::CommandView *m_commandView; - KToolBar *m_latexOutputErrorToolBar; - QMenu *m_buildMenuTopLevel, *m_buildMenuCompile, *m_buildMenuConvert, *m_buildMenuViewer, *m_buildMenuOther, *m_buildMenuQuickPreview; - - QSignalMapper *m_signalMapper; - - /* config */ - KSharedConfigPtr m_config; - QStringList m_recentFilesList, m_listDocsOpenOnStart, m_listEncodingsOfDocsOpenOnStart, m_listProjectsOpenOnStart; - - KRecentFilesAction *m_actRecentProjects; - - KileLyxServer *m_lyxserver; - - /* actions */ - void initSelectActions(); - void setupSideBar(); - void setupProjectView(); - void setupStructureView(); - void setupScriptsManagementView(); - void setupCommandViewToolbox(); - void setupSymbolViews(); - void enableSymbolViewMFUS(); - void disableSymbolViewMFUS(); - void setupAbbreviationView(); - void setupBottomBar(); - void setupGraphicTools(); - void setupPreviewTools(); - void setupActions(); - QAction* createToolAction(QString toolName); - void createToolActions(); - void setupTools(); - void updateUserDefinedMenus(); - void cleanUpActionList(QList &list, const QStringList &tools); - void restoreLastSelectedAction(); - void saveLastSelectedAction(); - - void transformOldUserTags(); - - void initMenu(); - void setMenuItems(QStringList &list, QMap &dict); - void updateMenu(); - bool updateMenuActivationStatus(QMenu *menu); - bool updateMenuActivationStatus(QMenu *menu, const QSet& visited); - void updateLatexenuActivationStatus(QMenu *menu, bool state); - void updateUserMenuStatus(bool state); - - QAction * createAction(const QString &text, const QString &name, const QObject *receiver = Q_NULLPTR, const char *member = Q_NULLPTR); - QAction * createAction(const QString &text, const QString &name, const QString& iconName, const QObject *receiver = Q_NULLPTR, const char *member = Q_NULLPTR); - QAction * createAction(const QString &text, const QString &name, const QKeySequence& shortcut, const QObject *receiver = Q_NULLPTR, const char *member = Q_NULLPTR); - QAction * createAction(const QString &text, const QString &name, const QString& iconName, const QKeySequence& shortcut = QKeySequence(), const QObject *receiver = Q_NULLPTR, const char *member = Q_NULLPTR); - QAction * createAction(KStandardAction::StandardAction actionType, const QString &name, const QObject *receiver = Q_NULLPTR, const char *member = Q_NULLPTR); - - void setMasterDocumentFileName(const QString& fileName); - void clearMasterDocument(); + QMap m_dictMenuAction, m_dictMenuFile, m_dictMenuProject; + + KToolBar *m_toolsToolBar; + KActionMenu *m_userHelpActionMenu; + KSelectAction *m_bibTagSettings; + ToolbarSelectAction *m_compilerActions, *m_viewActions, *m_convertActions, *m_quickActions; + QList m_listUserTags; + QList m_listUserTools; + QList m_listQuickActions, m_listCompilerActions, m_listConverterActions, m_listViewerActions, m_listOtherActions; + KActionMenu *m_bibTagActionMenu; + QAction *m_paStop, *m_paPrint; + KToggleAction *ModeAction, *WatchFileAction; + KToggleAction *m_actionMessageView; + KRecentFilesAction *m_actRecentFiles; + KToggleFullScreenAction *m_pFullScreen; + + /* GUI */ + //widgets + KileWidget::SideBar *m_sideBar; + KileWidget::AbbreviationView *m_kileAbbrevView; + QStackedWidget *m_topWidgetStack; + QSplitter *m_horizontalSplitter, *m_verticalSplitter; + QToolBox *m_toolBox; + KileWidget::CommandViewToolBox *m_commandViewToolBox; + KileWidget::SymbolView *m_symbolViewMFUS, *m_symbolViewRelation, *m_symbolViewArrows, *m_symbolViewMiscMath, *m_symbolViewMiscText, *m_symbolViewOperators, *m_symbolViewUser, *m_symbolViewDelimiters, *m_symbolViewGreek, *m_symbolViewSpecial, *m_symbolViewCyrillic; + KileWidget::CommandView *m_commandView; + KToolBar *m_latexOutputErrorToolBar; + QMenu *m_buildMenuTopLevel, *m_buildMenuCompile, *m_buildMenuConvert, *m_buildMenuViewer, *m_buildMenuOther, *m_buildMenuQuickPreview; + + QSignalMapper *m_signalMapper; + + /* config */ + KSharedConfigPtr m_config; + QStringList m_recentFilesList, m_listDocsOpenOnStart, m_listEncodingsOfDocsOpenOnStart, m_listProjectsOpenOnStart; + + KRecentFilesAction *m_actRecentProjects; + + KileLyxServer *m_lyxserver; + + /* actions */ + void initSelectActions(); + void setupSideBar(); + void setupProjectView(); + void setupStructureView(); + void setupScriptsManagementView(); + void setupCommandViewToolbox(); + void setupSymbolViews(); + void enableSymbolViewMFUS(); + void disableSymbolViewMFUS(); + void setupAbbreviationView(); + void setupBottomBar(); + void setupGraphicTools(); + void setupPreviewTools(); + void setupActions(); + QAction* createToolAction(QString toolName); + void createToolActions(); + void setupTools(); + void updateUserDefinedMenus(); + void cleanUpActionList(QList &list, const QStringList &tools); + void restoreLastSelectedAction(); + void saveLastSelectedAction(); + + void transformOldUserTags(); + + void initMenu(); + void setMenuItems(QStringList &list, QMap &dict); + void updateMenu(); + bool updateMenuActivationStatus(QMenu *menu); + bool updateMenuActivationStatus(QMenu *menu, const QSet& visited); + void updateLatexenuActivationStatus(QMenu *menu, bool state); + void updateUserMenuStatus(bool state); + + QAction * createAction(const QString &text, const QString &name, const QObject *receiver = Q_NULLPTR, const char *member = Q_NULLPTR); + QAction * createAction(const QString &text, const QString &name, const QString& iconName, const QObject *receiver = Q_NULLPTR, const char *member = Q_NULLPTR); + QAction * createAction(const QString &text, const QString &name, const QKeySequence& shortcut, const QObject *receiver = Q_NULLPTR, const char *member = Q_NULLPTR); + QAction * createAction(const QString &text, const QString &name, const QString& iconName, const QKeySequence& shortcut = QKeySequence(), const QObject *receiver = Q_NULLPTR, const char *member = Q_NULLPTR); + QAction * createAction(KStandardAction::StandardAction actionType, const QString &name, const QObject *receiver = Q_NULLPTR, const char *member = Q_NULLPTR); + + void setMasterDocumentFileName(const QString& fileName); + void clearMasterDocument(); private Q_SLOTS: - void toggleMasterDocumentMode(); - void toggleWatchFile(); - void refreshStructure(); - - void helpLaTex(); - - bool resetPart(); - void enableGUI(bool); - void slotToggleFullScreen(); - - void restoreFilesAndProjects(bool allowRestore); - void readGUISettings(); - void transformOldUserSettings(); - void readRecentFileSettings(); - void saveSettings(); - - void readConfig(); - - void generalOptions(); - void configureKeys(); - void configureToolbars(); - void slotPerformCheck(); - - void aboutEditorComponent(); - - /** - * Activates (sets up the GUI for the editor part) the view. - * @param updateStruct If true, force an update of the structure view. - **/ - void activateView(QWidget* view , bool updateStruct = true); - - void focusLog(); - void focusOutput(); - void focusKonsole(); - void focusEditor(); - void focusPreview(); - - void sideOrBottomBarChanged(bool visible); - - void showDocInfo(KTextEditor::View *view = Q_NULLPTR); - void convertToASCII(KTextEditor::Document *doc = Q_NULLPTR); - void convertToEnc(KTextEditor::Document *doc = Q_NULLPTR); - - void cleanAll(KileDocument::TextInfo *docinfo = Q_NULLPTR); - void cleanBib(); - - void findInFiles(); - void findInProjects(); - void grepItemSelected(const QString &abs_filename, int line); - - /** - * @param td Inserts the TagData td into the current editor - * @param pkgs list of packages needed for this command - * - * warns if latex packages in pkgs are not included in the document - **/ - void insertTag(const KileAction::TagData& td, const QStringList& pkgs); - - /** - * An overloaded member function, behaves essentially as above. - **/ - - void insertTag(const KileAction::TagData& td, const QList& pkgs); - void insertTag(const QString& tagB, const QString& tagE, int dx, int dy); - void insertAmsTag(const KileAction::TagData& td); - void insertText(const QString &text, const QStringList &pkgs); - void insertText(const QString &text, const QList &pkgs); - - void quickTabular(); - void quickArray(); - void quickTabbing(); - void quickDocument(); - void quickFloat(); - void quickMathenv(); - void quickPostscript(); - void quickPdf(); - void quickTabulardialog(bool tabularenv); - - void quickUserMenuDialog(); - void slotUpdateUserMenuStatus(); - - void includeGraphics(); - - // QuickPreview - void slotQuickPreview(int type); - - void quickPreviewEnvironment() { slotQuickPreview(KileTool::qpEnvironment); } - void quickPreviewSelection() { slotQuickPreview(KileTool::qpSelection); } - void quickPreviewSubdocument() { slotQuickPreview(KileTool::qpSubdocument); } - void quickPreviewMathgroup() { slotQuickPreview(KileTool::qpMathgroup); } - - void addRecentFile(const QUrl &url); - void removeRecentFile(const QUrl &url); - void addRecentProject(const QUrl &url); - void removeRecentProject(const QUrl &url); - - void updateStatusBarCursorPosition(KTextEditor::View *view, const KTextEditor::Cursor &newPosition); - void updateStatusBarViewMode(KTextEditor::View *view); - void updateStatusBarInformationMessage(KTextEditor::View *view, const QString &message); - void updateStatusBarSelection(KTextEditor::View *view); - - void handleDocumentParsingStarted(); - void handleDocumentParsingComplete(); + void toggleMasterDocumentMode(); + void toggleWatchFile(); + void refreshStructure(); + + void helpLaTex(); + + bool resetPart(); + void enableGUI(bool); + void slotToggleFullScreen(); + + void restoreFilesAndProjects(bool allowRestore); + void readGUISettings(); + void transformOldUserSettings(); + void readRecentFileSettings(); + void saveSettings(); + + void readConfig(); + + void generalOptions(); + void configureKeys(); + void configureToolbars(); + void slotPerformCheck(); + + void aboutEditorComponent(); + + /** + * Activates (sets up the GUI for the editor part) the view. + * @param updateStruct If true, force an update of the structure view. + **/ + void activateView(QWidget* view, bool updateStruct = true); + + void focusLog(); + void focusOutput(); + void focusKonsole(); + void focusEditor(); + void focusPreview(); + + void sideOrBottomBarChanged(bool visible); + + void showDocInfo(KTextEditor::View *view = Q_NULLPTR); + void convertToASCII(KTextEditor::Document *doc = Q_NULLPTR); + void convertToEnc(KTextEditor::Document *doc = Q_NULLPTR); + + void cleanAll(KileDocument::TextInfo *docinfo = Q_NULLPTR); + void cleanBib(); + + void findInFiles(); + void findInProjects(); + void grepItemSelected(const QString &abs_filename, int line); + + /** + * @param td Inserts the TagData td into the current editor + * @param pkgs list of packages needed for this command + * + * warns if latex packages in pkgs are not included in the document + **/ + void insertTag(const KileAction::TagData& td, const QStringList& pkgs); + + /** + * An overloaded member function, behaves essentially as above. + **/ + + void insertTag(const KileAction::TagData& td, const QList& pkgs); + void insertTag(const QString& tagB, const QString& tagE, int dx, int dy); + void insertAmsTag(const KileAction::TagData& td); + void insertText(const QString &text, const QStringList &pkgs); + void insertText(const QString &text, const QList &pkgs); + + void quickTabular(); + void quickArray(); + void quickTabbing(); + void quickDocument(); + void quickFloat(); + void quickMathenv(); + void quickPostscript(); + void quickPdf(); + void quickTabulardialog(bool tabularenv); + + void quickUserMenuDialog(); + void slotUpdateUserMenuStatus(); + + void includeGraphics(); + + // QuickPreview + void slotQuickPreview(int type); + + void quickPreviewEnvironment() { + slotQuickPreview(KileTool::qpEnvironment); + } + void quickPreviewSelection() { + slotQuickPreview(KileTool::qpSelection); + } + void quickPreviewSubdocument() { + slotQuickPreview(KileTool::qpSubdocument); + } + void quickPreviewMathgroup() { + slotQuickPreview(KileTool::qpMathgroup); + } + + void addRecentFile(const QUrl &url); + void removeRecentFile(const QUrl &url); + void addRecentProject(const QUrl &url); + void removeRecentProject(const QUrl &url); + + void updateStatusBarCursorPosition(KTextEditor::View *view, const KTextEditor::Cursor &newPosition); + void updateStatusBarViewMode(KTextEditor::View *view); + void updateStatusBarInformationMessage(KTextEditor::View *view, const QString &message); + void updateStatusBarSelection(KTextEditor::View *view); + + void handleDocumentParsingStarted(); + void handleDocumentParsingComplete(); }; #endif diff --git a/src/kileactions.cpp b/src/kileactions.cpp index eea28629..3be5e810 100644 --- a/src/kileactions.cpp +++ b/src/kileactions.cpp @@ -1,631 +1,631 @@ /************************************************************************************** begin : 2003-07-01 17:33:00 CEST 2003 copyright : (C) 2003 by Jeroen Wijnhout (Jeroen.Wijnhout@kdemail.net) 2008-2016 by Michel Ludwig (michel.ludwig@kdemail.net) **************************************************************************************/ /*************************************************************************** * * * 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. * * * ***************************************************************************/ // 2005-07-26 dani // - cleanup dialog // - added new action 'ShowLabel' // 2007-03-12 dani // - use KileDocument::Extensions #include "kileactions.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "kiledebug.h" #include "kileextensions.h" #include "kileinfo.h" #include "kiledocmanager.h" namespace KileAction { //////////////// // Tag // //////////////// Tag::Tag(const QString &text, const QString& iconText, const QKeySequence &shortcut, const QObject *receiver, const char *slot, KActionCollection *parent, const QString& name, const QString &tagBegin, const QString &tagEnd, int dx, int dy, const QString &description) - : QAction(text, parent), - m_data(text,tagBegin, tagEnd, dx, dy, description) + : QAction(text, parent), + m_data(text,tagBegin, tagEnd, dx, dy, description) { - parent->addAction(name, this); - setIconText(iconText); - if(!shortcut.isEmpty()) { - parent->setDefaultShortcut(this, shortcut); - } - init(receiver, slot); + parent->addAction(name, this); + setIconText(iconText); + if(!shortcut.isEmpty()) { + parent->setDefaultShortcut(this, shortcut); + } + init(receiver, slot); } Tag::Tag(const QString &text, const QString& iconText, const QString& pix, const QKeySequence &shortcut, const QObject *receiver, const char *slot, KActionCollection *parent, const QString& name, const QString &tagBegin, const QString &tagEnd, int dx, int dy, const QString &description) - : QAction(QIcon::fromTheme(pix), text, parent), - m_data(text,tagBegin, tagEnd, dx, dy, description) + : QAction(QIcon::fromTheme(pix), text, parent), + m_data(text,tagBegin, tagEnd, dx, dy, description) { - parent->addAction(name, this); - setIconText(iconText); - if(!shortcut.isEmpty()) { - parent->setDefaultShortcut(this, shortcut); - } - init(receiver,slot); + parent->addAction(name, this); + setIconText(iconText); + if(!shortcut.isEmpty()) { + parent->setDefaultShortcut(this, shortcut); + } + init(receiver,slot); } Tag::Tag(const QString &text, const QString& iconText, const QKeySequence &shortcut, const QObject *receiver, const char *slot, KActionCollection *parent, const QString& name, const TagData& data) - : QAction(text, parent), - m_data(data) + : QAction(text, parent), + m_data(data) { - parent->addAction(name, this); - setIconText(iconText); - if(!shortcut.isEmpty()) { - parent->setDefaultShortcut(this, shortcut); - } - init(receiver,slot); + parent->addAction(name, this); + setIconText(iconText); + if(!shortcut.isEmpty()) { + parent->setDefaultShortcut(this, shortcut); + } + init(receiver,slot); } Tag::Tag(const QString &text, const QString& iconText, const QString& pix, const QKeySequence &shortcut, const QObject *receiver, const char *slot, KActionCollection *parent, - const QString& name, const TagData& data) - : QAction(QIcon::fromTheme(pix), text, parent), - m_data(data) + const QString& name, const TagData& data) + : QAction(QIcon::fromTheme(pix), text, parent), + m_data(data) { - parent->addAction(name, this); - if(!shortcut.isEmpty()) { - parent->setDefaultShortcut(this, shortcut); - } - setIconText(iconText); - init(receiver,slot); + parent->addAction(name, this); + if(!shortcut.isEmpty()) { + parent->setDefaultShortcut(this, shortcut); + } + setIconText(iconText); + init(receiver,slot); } Tag::~Tag() { } void Tag::init(const QObject *receiver, const char *slot) { - connect(this, SIGNAL(triggered()), SLOT(emitData())); - connect(this, SIGNAL(triggered(const KileAction::TagData&)), receiver, slot); + connect(this, SIGNAL(triggered()), SLOT(emitData())); + connect(this, SIGNAL(triggered(const KileAction::TagData&)), receiver, slot); } void Tag::emitData() { - emit(triggered(m_data)); + emit(triggered(m_data)); } //////////////// // InputTag // //////////////// InputTag::InputTag(KileInfo* ki, const QString &text, const QString &iconText, const QKeySequence &cut, const QObject *receiver, const char *slot, KActionCollection *parent, const QString& name, QWidget *wparent, uint options, const QString &tagBegin, const QString &tagEnd, int dx, int dy, const QString &description, const QString &hint, const QString &alter) - : Tag(text, iconText, cut, receiver, slot, parent, name, tagBegin, tagEnd, dx, dy, description), m_ki(ki), - m_parent(wparent), m_options(options), m_hint(hint), m_alter(alter) + : Tag(text, iconText, cut, receiver, slot, parent, name, tagBegin, tagEnd, dx, dy, description), m_ki(ki), + m_parent(wparent), m_options(options), m_hint(hint), m_alter(alter) { - init(); + init(); } InputTag::InputTag(KileInfo* ki, const QString &text, const QString &iconText, const QString& pix, const QKeySequence &cut, const QObject *receiver, const char *slot, KActionCollection *parent, const QString& name, QWidget *wparent, uint options, const QString &tagBegin, const QString &tagEnd, int dx, int dy, const QString &description, const QString &hint, const QString &alter) - : Tag(text, iconText, pix, cut, receiver, slot, parent, name, tagBegin, tagEnd, dx, dy, description), m_ki(ki), - m_parent(wparent), m_options(options), m_hint(hint), m_alter(alter) + : Tag(text, iconText, pix, cut, receiver, slot, parent, name, tagBegin, tagEnd, dx, dy, description), m_ki(ki), + m_parent(wparent), m_options(options), m_hint(hint), m_alter(alter) { - init(); + init(); } InputTag::InputTag(KileInfo* ki, const QString &text, const QString &iconText, const QKeySequence &cut, const QObject *receiver, const char *slot, KActionCollection *parent, const QString& name, QWidget *wparent, uint options, const TagData& data, const QString &hint, const QString &alter) - : Tag(text, iconText, cut, receiver, slot, parent, name,data), m_ki(ki), - m_parent(wparent), m_options(options), m_hint(hint), m_alter(alter) + : Tag(text, iconText, cut, receiver, slot, parent, name,data), m_ki(ki), + m_parent(wparent), m_options(options), m_hint(hint), m_alter(alter) { - init(); + init(); } InputTag::InputTag(KileInfo* ki, const QString &text, const QString &iconText, const QString& pix, const QKeySequence &cut, const QObject *receiver, const char *slot, KActionCollection *parent, const QString& name, QWidget *wparent, uint options, const TagData& data, const QString &hint, const QString &alter) - : Tag(text, iconText, pix, cut,receiver, slot, parent, name,data), m_ki(ki), - m_parent(wparent), m_options(options), m_hint(hint), m_alter(alter) + : Tag(text, iconText, pix, cut,receiver, slot, parent, name,data), m_ki(ki), + m_parent(wparent), m_options(options), m_hint(hint), m_alter(alter) { - init(); + init(); } InputTag::~InputTag() { } void InputTag::init() { - m_history.clear(); + m_history.clear(); } void InputTag::addToHistory(const QString& str) { - if(!m_history.contains(str)) { - m_history.prepend(str); - } + if(!m_history.contains(str)) { + m_history.prepend(str); + } } void InputTag::emitData() { - KILE_DEBUG_MAIN << "InputTag::emitData() " << m_ki->getName(); + KILE_DEBUG_MAIN << "InputTag::emitData() " << m_ki->getName(); - InputDialog *dlg = new InputDialog(m_data.text, m_options, m_history, m_hint, m_alter, m_ki, m_parent, "input_dialog"); - if (dlg->exec()) { - if((!dlg->tag().isEmpty()) && hasHistory()) { - addToHistory(dlg->tag()); - } + InputDialog *dlg = new InputDialog(m_data.text, m_options, m_history, m_hint, m_alter, m_ki, m_parent, "input_dialog"); + if (dlg->exec()) { + if((!dlg->tag().isEmpty()) && hasHistory()) { + addToHistory(dlg->tag()); + } - TagData td(m_data); + TagData td(m_data); - td.tagBegin.replace("%R",dlg->tag()); - td.tagEnd.replace("%R",dlg->tag()); + td.tagBegin.replace("%R",dlg->tag()); + td.tagEnd.replace("%R",dlg->tag()); - QString alt = dlg->useAlternative() ? "*" : ""; - td.tagBegin.replace("%A", alt); - td.tagEnd.replace("%A", alt); + QString alt = dlg->useAlternative() ? "*" : ""; + td.tagBegin.replace("%A", alt); + td.tagEnd.replace("%A", alt); - if(dlg->useLabel()) { - td.tagEnd += dlg->label(); - td.dy++; - } + if(dlg->useLabel()) { + td.tagEnd += dlg->label(); + td.dy++; + } - if(dlg->usedSelection()) { - m_ki->clearSelection(); - } + if(dlg->usedSelection()) { + m_ki->clearSelection(); + } - // if a filename was given for a \input- or \include-command, - // the cursor is moved out of the braces - if ( (m_options & (KileAction::ShowBrowseButton | KileAction::FromLabelList | KileAction::FromBibItemList)) && !dlg->tag().isEmpty() ) { - td.dx += dlg->tag().length() + 1; - } + // if a filename was given for a \input- or \include-command, + // the cursor is moved out of the braces + if ( (m_options & (KileAction::ShowBrowseButton | KileAction::FromLabelList | KileAction::FromBibItemList)) && !dlg->tag().isEmpty() ) { + td.dx += dlg->tag().length() + 1; + } - // insert tag - emit(triggered(td)); - // refresh document structure and project tree when a file was inserted - if(dlg->useAddProjectFile()) { - m_ki->docManager()->projectAddFile(QFileInfo(m_ki->getCompileName()).absolutePath() + '/' + dlg->tag()); - } - } - delete dlg; + // insert tag + emit(triggered(td)); + // refresh document structure and project tree when a file was inserted + if(dlg->useAddProjectFile()) { + m_ki->docManager()->projectAddFile(QFileInfo(m_ki->getCompileName()).absolutePath() + '/' + dlg->tag()); + } + } + delete dlg; } /* InputDialog */ InputDialog::InputDialog(const QString &caption, uint options, const QStringList& history, const QString& hint, const QString& alter, KileInfo *ki, QWidget *parent, const char *name) - : QDialog (parent), m_ki(ki) -{ - setModal(true); - - QVBoxLayout *mainLayout = new QVBoxLayout; - setLayout(mainLayout); - setObjectName(name); - - QString newcaption = caption; - setWindowTitle(newcaption.remove('&')); - - m_labelprefix = (newcaption == "chapter") ? "chap:" : "sec:"; - m_usedSelection = false; - - QGridLayout *gbox = new QGridLayout(this); - QWidget *page = new QWidget(this); - page->setLayout(gbox); - mainLayout->addWidget(page); - - QLabel *lb = new QLabel(hint, this); - gbox->addWidget(lb, 0, 0, 1, 3); - - m_tag.clear(); - QWidget *focus; - if((options & KileAction::KeepHistory) || (options & KileAction::FromLabelList) || (options & KileAction::FromBibItemList)) { - KComboBox *input = new KComboBox(true, this); - input->setObjectName("input_dialog_input"); - input->setCompletionMode(KCompletion::CompletionAuto); - input->setMinimumWidth(300); - focus = input; - - connect(input, SIGNAL(textChanged(const QString&)), this, SLOT(setTag(const QString&))); - connect(this, SIGNAL(setInput(const QString&)), input, SLOT(setEditText(const QString&))); - if(options & KileAction::ShowBrowseButton) { - gbox->addWidget(input, 1, 0); - } - else { - gbox->addWidget(input, 1, 0, 1, 3); - } - - QStringList list; - - if(options & KileAction::FromLabelList) { - list = ki->allLabels(); - if(list.size() > 0) { - input->addItems(list); - m_tag = list.first(); - } - } - else if(options & KileAction::FromBibItemList) { - list = ki->allBibItems(); - if(list.size() > 0) { - input->addItems(list); - m_tag = list.first(); - } - } - else { - if(history.size() > 0){ - input->addItems(history); - m_tag = history.first(); - } - } - } - else { - QLineEdit *input = new QLineEdit(this); - gbox->addWidget(input); - input->setMinimumWidth(300); - focus = input; - - connect(input, SIGNAL(textChanged(const QString&)), this, SLOT(setTag(const QString&))); - connect(this, SIGNAL(setInput(const QString&)), input, SLOT(setText(const QString&))); - if(options & KileAction::ShowBrowseButton) { - gbox->addWidget(input, 1, 0); - } - else { - gbox->addWidget(input, 1, 0, 1, 3); - } - - input->setText(ki->getSelection()); - m_usedSelection=true; - } - - if(focus) { - lb->setBuddy(focus); - } - - if(options & KileAction::ShowBrowseButton) { - QPushButton *pbutton = new QPushButton(QString(), this); - mainLayout->addWidget(pbutton); - pbutton->setIcon(QIcon::fromTheme("document-open")); - gbox->addWidget(pbutton, 1, 2); - gbox->setColumnMinimumWidth(1, 8); - gbox->setColumnMinimumWidth(2, pbutton->sizeHint().width() + 5); - connect(pbutton, SIGNAL(clicked()), this, SLOT(slotBrowse())); - } - - if(options & KileAction::ShowAlternative) { - QCheckBox *m_checkbox = new QCheckBox(alter, this); - mainLayout->addWidget(m_checkbox); - m_checkbox->setObjectName("input_dialog_checkbox"); - connect(m_checkbox, SIGNAL(clicked()), this, SLOT(slotAltClicked())); - m_useAlternative=false; - gbox->addWidget(m_checkbox, 2, 0, 1, 3); - } - - m_edLabel = Q_NULLPTR; - m_useLabel = (options & KileAction::ShowLabel); - if(m_useLabel) { - // Label - QLabel *label = new QLabel(i18n("&Label:"),this); - mainLayout->addWidget(label); - m_edLabel = new QLineEdit(this); - mainLayout->addWidget(m_edLabel); - m_edLabel->setMinimumWidth(300); - m_edLabel->setText(m_labelprefix); - label->setBuddy(m_edLabel); - gbox->addWidget(label, 3, 0, 1, 3); - gbox->addWidget(m_edLabel, 4, 0, 1, 3); - } - - m_useAddProjectFile = (options & KileAction::AddProjectFile); - - gbox->setRowStretch(5, 1); - gbox->setColumnStretch(0, 1); - - // add buttons - QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok|QDialogButtonBox::Cancel); - mainLayout->addWidget(buttonBox); - QPushButton *okButton = buttonBox->button(QDialogButtonBox::Ok); - okButton->setDefault(true); - okButton->setShortcut(Qt::CTRL | Qt::Key_Return); - connect(buttonBox, SIGNAL(accepted()), this, SLOT(accept())); - connect(buttonBox, SIGNAL(rejected()), this, SLOT(reject())); - - focus->setFocus(); + : QDialog (parent), m_ki(ki) +{ + setModal(true); + + QVBoxLayout *mainLayout = new QVBoxLayout; + setLayout(mainLayout); + setObjectName(name); + + QString newcaption = caption; + setWindowTitle(newcaption.remove('&')); + + m_labelprefix = (newcaption == "chapter") ? "chap:" : "sec:"; + m_usedSelection = false; + + QGridLayout *gbox = new QGridLayout(this); + QWidget *page = new QWidget(this); + page->setLayout(gbox); + mainLayout->addWidget(page); + + QLabel *lb = new QLabel(hint, this); + gbox->addWidget(lb, 0, 0, 1, 3); + + m_tag.clear(); + QWidget *focus; + if((options & KileAction::KeepHistory) || (options & KileAction::FromLabelList) || (options & KileAction::FromBibItemList)) { + KComboBox *input = new KComboBox(true, this); + input->setObjectName("input_dialog_input"); + input->setCompletionMode(KCompletion::CompletionAuto); + input->setMinimumWidth(300); + focus = input; + + connect(input, SIGNAL(textChanged(const QString&)), this, SLOT(setTag(const QString&))); + connect(this, SIGNAL(setInput(const QString&)), input, SLOT(setEditText(const QString&))); + if(options & KileAction::ShowBrowseButton) { + gbox->addWidget(input, 1, 0); + } + else { + gbox->addWidget(input, 1, 0, 1, 3); + } + + QStringList list; + + if(options & KileAction::FromLabelList) { + list = ki->allLabels(); + if(list.size() > 0) { + input->addItems(list); + m_tag = list.first(); + } + } + else if(options & KileAction::FromBibItemList) { + list = ki->allBibItems(); + if(list.size() > 0) { + input->addItems(list); + m_tag = list.first(); + } + } + else { + if(history.size() > 0) { + input->addItems(history); + m_tag = history.first(); + } + } + } + else { + QLineEdit *input = new QLineEdit(this); + gbox->addWidget(input); + input->setMinimumWidth(300); + focus = input; + + connect(input, SIGNAL(textChanged(const QString&)), this, SLOT(setTag(const QString&))); + connect(this, SIGNAL(setInput(const QString&)), input, SLOT(setText(const QString&))); + if(options & KileAction::ShowBrowseButton) { + gbox->addWidget(input, 1, 0); + } + else { + gbox->addWidget(input, 1, 0, 1, 3); + } + + input->setText(ki->getSelection()); + m_usedSelection=true; + } + + if(focus) { + lb->setBuddy(focus); + } + + if(options & KileAction::ShowBrowseButton) { + QPushButton *pbutton = new QPushButton(QString(), this); + mainLayout->addWidget(pbutton); + pbutton->setIcon(QIcon::fromTheme("document-open")); + gbox->addWidget(pbutton, 1, 2); + gbox->setColumnMinimumWidth(1, 8); + gbox->setColumnMinimumWidth(2, pbutton->sizeHint().width() + 5); + connect(pbutton, SIGNAL(clicked()), this, SLOT(slotBrowse())); + } + + if(options & KileAction::ShowAlternative) { + QCheckBox *m_checkbox = new QCheckBox(alter, this); + mainLayout->addWidget(m_checkbox); + m_checkbox->setObjectName("input_dialog_checkbox"); + connect(m_checkbox, SIGNAL(clicked()), this, SLOT(slotAltClicked())); + m_useAlternative=false; + gbox->addWidget(m_checkbox, 2, 0, 1, 3); + } + + m_edLabel = Q_NULLPTR; + m_useLabel = (options & KileAction::ShowLabel); + if(m_useLabel) { + // Label + QLabel *label = new QLabel(i18n("&Label:"),this); + mainLayout->addWidget(label); + m_edLabel = new QLineEdit(this); + mainLayout->addWidget(m_edLabel); + m_edLabel->setMinimumWidth(300); + m_edLabel->setText(m_labelprefix); + label->setBuddy(m_edLabel); + gbox->addWidget(label, 3, 0, 1, 3); + gbox->addWidget(m_edLabel, 4, 0, 1, 3); + } + + m_useAddProjectFile = (options & KileAction::AddProjectFile); + + gbox->setRowStretch(5, 1); + gbox->setColumnStretch(0, 1); + + // add buttons + QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok|QDialogButtonBox::Cancel); + mainLayout->addWidget(buttonBox); + QPushButton *okButton = buttonBox->button(QDialogButtonBox::Ok); + okButton->setDefault(true); + okButton->setShortcut(Qt::CTRL | Qt::Key_Return); + connect(buttonBox, SIGNAL(accepted()), this, SLOT(accept())); + connect(buttonBox, SIGNAL(rejected()), this, SLOT(reject())); + + focus->setFocus(); } InputDialog::~InputDialog() { } void InputDialog::slotBrowse() { - QString fn; - QFileInfo fi(m_ki->getCompileName()); + QString fn; + QFileInfo fi(m_ki->getCompileName()); - // Called from InputDialog after a \input- or \include command: - // so we are only looking for a LaTeX source document - QString filter = m_ki->extensions()->fileFilterQtStyle(true, {KileDocument::Extensions::TEX}); + // Called from InputDialog after a \input- or \include command: + // so we are only looking for a LaTeX source document + QString filter = m_ki->extensions()->fileFilterQtStyle(true, {KileDocument::Extensions::TEX}); - fn = QFileDialog::getOpenFileName(this, i18n("Select File") , fi.absoluteFilePath(), filter); - if(!fn.isEmpty()) { - QString path = QDir(fi.path()).relativeFilePath(fn); + fn = QFileDialog::getOpenFileName(this, i18n("Select File"), fi.absoluteFilePath(), filter); + if(!fn.isEmpty()) { + QString path = QDir(fi.path()).relativeFilePath(fn); - // if the file has no extension, we add the default TeX extension - if(QFileInfo(path).completeSuffix().isEmpty()) { - path += m_ki->extensions()->latexDocumentDefault(); - } + // if the file has no extension, we add the default TeX extension + if(QFileInfo(path).completeSuffix().isEmpty()) { + path += m_ki->extensions()->latexDocumentDefault(); + } - setTag(path); - emit(setInput(path)); - } + setTag(path); + emit(setInput(path)); + } } void InputDialog::slotAltClicked() { - m_useAlternative = !m_useAlternative; + m_useAlternative = !m_useAlternative; } void InputDialog::setTag(const QString &tag) { - m_tag = tag; + m_tag = tag; } QString InputDialog::label() { - if(m_edLabel) { - QString label = m_edLabel->text().trimmed(); - if(!label.isEmpty() && label != m_labelprefix) { - return "\\label{" + label + "}\n"; - } - } + if(m_edLabel) { + QString label = m_edLabel->text().trimmed(); + if(!label.isEmpty() && label != m_labelprefix) { + return "\\label{" + label + "}\n"; + } + } - return QString(); + return QString(); } ///////////////// // SelectTag // ///////////////// Select::Select(const QString &text, const QKeySequence &shortcut, KActionCollection *parent, const char *name) - : KSelectAction(text, parent) + : KSelectAction(text, parent) { - parent->addAction(name, this); - parent->setDefaultShortcut(this, shortcut); + parent->addAction(name, this); + parent->setDefaultShortcut(this, shortcut); } void Select::setItems(const QList& list) { - removeAllActions(); + removeAllActions(); - for(QList::const_iterator i = list.begin(); i != list.end(); ++i) { - addAction(*i); - } + for(QList::const_iterator i = list.begin(); i != list.end(); ++i) { + addAction(*i); + } } ///////////////////////// // VariantSelection // ///////////////////////// VariantSelection::VariantSelection(const QString &text, const QVariant& value, QObject *parent) -: QAction(text, parent), m_variant(value) + : QAction(text, parent), m_variant(value) { - connect(this, SIGNAL(triggered(bool)), this, SLOT(slotTriggered())); + connect(this, SIGNAL(triggered(bool)), this, SLOT(slotTriggered())); } void VariantSelection::slotTriggered() { - emit(triggered(m_variant)); + emit(triggered(m_variant)); - if(m_variant.canConvert()) { - emit(triggered(m_variant.value())); - } + if(m_variant.canConvert()) { + emit(triggered(m_variant.value())); + } - if(m_variant.canConvert()) { - emit(triggered(m_variant.value())); - } + if(m_variant.canConvert()) { + emit(triggered(m_variant.value())); + } } } // ToolbarSelectAction // based on 'KActionMenu', therefore our thanks go to // Copyright (C) 1999 Reginald Stadlbauer // (C) 1999 Simon Hausmann // (C) 2000 Nicolas Hadacek // (C) 2000 Kurt Granroth // (C) 2000 Michael Koch // (C) 2001 Holger Freyther // (C) 2002 Ellis Whitehead // (C) 2002 Joseph Wenninger // (C) 2003 Andras Mantia // (C) 2005-2006 Hamish Rodda ToolbarSelectAction::ToolbarSelectAction(const QString& text, QObject* parent, - bool changeMainActionOnTriggering /*= true */) - : QWidgetAction(parent), m_currentItem(-1), m_mainText(text), m_savedCurrentAction(Q_NULLPTR) + bool changeMainActionOnTriggering /*= true */) + : QWidgetAction(parent), m_currentItem(-1), m_mainText(text), m_savedCurrentAction(Q_NULLPTR) { - setText(text); - if(changeMainActionOnTriggering) { - connect(menu(), SIGNAL(triggered(QAction*)), this, SLOT(slotTriggered(QAction*))); - } + setText(text); + if(changeMainActionOnTriggering) { + connect(menu(), SIGNAL(triggered(QAction*)), this, SLOT(slotTriggered(QAction*))); + } } int ToolbarSelectAction::actionIndex(QAction *action) { - int counter = -1; - QList actionList = menu()->actions(); - for(QList::iterator i = actionList.begin(); i != actionList.end(); ++i) { - if(*i == action) { - return counter + 1; - } - ++counter; - } - return counter; + int counter = -1; + QList actionList = menu()->actions(); + for(QList::iterator i = actionList.begin(); i != actionList.end(); ++i) { + if(*i == action) { + return counter + 1; + } + ++counter; + } + return counter; } void ToolbarSelectAction::addAction(QAction *action) { - menu()->addAction(action); + menu()->addAction(action); } void ToolbarSelectAction::addSeparator() { - menu()->addSeparator(); + menu()->addSeparator(); } QAction* ToolbarSelectAction::action(int i) { - QList actionList = menu()->actions(); - if(i < 0 || i >= actionList.size()) { - return Q_NULLPTR; - } - return actionList.at(i); + QList actionList = menu()->actions(); + if(i < 0 || i >= actionList.size()) { + return Q_NULLPTR; + } + return actionList.at(i); } int ToolbarSelectAction::currentItem() const { - return m_currentItem; + return m_currentItem; } QAction* ToolbarSelectAction::currentAction() { - return action(m_currentItem); + return action(m_currentItem); } bool ToolbarSelectAction::containsAction(QAction *action) { - return actionIndex(action) >= 0; + return actionIndex(action) >= 0; } void ToolbarSelectAction::setCurrentItem(int i) { - setCurrentAction(action(i)); + setCurrentAction(action(i)); } void ToolbarSelectAction::setCurrentAction(QAction *action) { - if(!action) { - return; - } - int index = actionIndex(action); - if(index < 0) { - return; - } - setIcon(action->icon()); - setText(action->text()); - m_currentItem = index; + if(!action) { + return; + } + int index = actionIndex(action); + if(index < 0) { + return; + } + setIcon(action->icon()); + setText(action->text()); + m_currentItem = index; } void ToolbarSelectAction::removeAllActions() { - menu()->clear(); - m_currentItem = -1; - setText(m_mainText); - setIcon(QIcon()); + menu()->clear(); + m_currentItem = -1; + setText(m_mainText); + setIcon(QIcon()); } -void ToolbarSelectAction::slotTriggered(QAction* action){ +void ToolbarSelectAction::slotTriggered(QAction* action) { - KILE_DEBUG_MAIN << "triggered with " << action->text(); + KILE_DEBUG_MAIN << "triggered with " << action->text(); - if( currentAction() != action ) { - setIcon(action->icon()); - setText(action->text()); - setCurrentAction(action); - } + if( currentAction() != action ) { + setIcon(action->icon()); + setText(action->text()); + setCurrentAction(action); + } } void ToolbarSelectAction::slotMainActionTriggered() { - QAction *action = currentAction(); - if(action) { - action->trigger(); - } + QAction *action = currentAction(); + if(action) { + action->trigger(); + } } void ToolbarSelectAction::slotMainButtonPressed() { - QAction *action = currentAction(); - if(!action) { - emit(mainButtonWithNoActionPressed()); - } + QAction *action = currentAction(); + if(!action) { + emit(mainButtonWithNoActionPressed()); + } } QMenu* ToolbarSelectAction::menu() { - if(!QAction::menu()) { - QMenu *menu = new QMenu(); - setMenu(menu); - } + if(!QAction::menu()) { + QMenu *menu = new QMenu(); + setMenu(menu); + } - return qobject_cast(QAction::menu()); + return qobject_cast(QAction::menu()); } QWidget* ToolbarSelectAction::createWidget(QWidget *parent) { - QToolBar *parentToolBar = qobject_cast(parent); - if (!parentToolBar) { - return QWidgetAction::createWidget(parent); - } - QToolButton* button = new QToolButton(parent); - button->setAutoRaise(true); - button->setFocusPolicy(Qt::NoFocus); - button->setPopupMode(QToolButton::MenuButtonPopup); - button->setIconSize(parentToolBar->iconSize()); - button->setToolButtonStyle(parentToolBar->toolButtonStyle()); - connect(parent, SIGNAL(iconSizeChanged(const QSize&)), - button, SLOT(setIconSize(const QSize&))); - connect(parent, SIGNAL(toolButtonStyleChanged(Qt::ToolButtonStyle)), - button, SLOT(setToolButtonStyle(Qt::ToolButtonStyle))); - button->setDefaultAction(this); - connect(button, SIGNAL(clicked(bool)), this, SLOT(slotMainActionTriggered())); - connect(button, SIGNAL(pressed()), this, SLOT(slotMainButtonPressed())); - connect(this, SIGNAL(mainButtonWithNoActionPressed()), button, SLOT(showMenu())); - return button; + QToolBar *parentToolBar = qobject_cast(parent); + if (!parentToolBar) { + return QWidgetAction::createWidget(parent); + } + QToolButton* button = new QToolButton(parent); + button->setAutoRaise(true); + button->setFocusPolicy(Qt::NoFocus); + button->setPopupMode(QToolButton::MenuButtonPopup); + button->setIconSize(parentToolBar->iconSize()); + button->setToolButtonStyle(parentToolBar->toolButtonStyle()); + connect(parent, SIGNAL(iconSizeChanged(const QSize&)), + button, SLOT(setIconSize(const QSize&))); + connect(parent, SIGNAL(toolButtonStyleChanged(Qt::ToolButtonStyle)), + button, SLOT(setToolButtonStyle(Qt::ToolButtonStyle))); + button->setDefaultAction(this); + connect(button, SIGNAL(clicked(bool)), this, SLOT(slotMainActionTriggered())); + connect(button, SIGNAL(pressed()), this, SLOT(slotMainButtonPressed())); + connect(this, SIGNAL(mainButtonWithNoActionPressed()), button, SLOT(showMenu())); + return button; } void ToolbarSelectAction::saveCurrentAction() { - m_savedCurrentAction = currentAction(); + m_savedCurrentAction = currentAction(); } void ToolbarSelectAction::restoreCurrentAction() { - if(!m_savedCurrentAction) { - return; - } - setCurrentAction(m_savedCurrentAction); - m_savedCurrentAction = Q_NULLPTR; + if(!m_savedCurrentAction) { + return; + } + setCurrentAction(m_savedCurrentAction); + m_savedCurrentAction = Q_NULLPTR; } diff --git a/src/kileactions.h b/src/kileactions.h index 1bf0b9f1..8f0b90d9 100644 --- a/src/kileactions.h +++ b/src/kileactions.h @@ -1,246 +1,262 @@ /************************************************************************************* begin : 2003-07-01 17:33:00 CEST 2003 copyright : (C) 2003 by Jeroen Wijnhout (Jeroen.Wijnhout@kdemail.net) (C) 2008-2014 by Michel Ludwig (michel.ludwig@kdemail.net) (C) 2009 Thomas Braun (thomas.braun@virtuell-zuhause.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. * * * ***************************************************************************/ #ifndef KILEACTIONS_H #define KILEACTIONS_H #include #include #include #include #include #include class QCheckBox; class KileInfo; namespace KileAction { enum { KeepHistory=1, ShowAlternative=2, ShowBrowseButton=4, FromLabelList=8, FromBibItemList=16, ShowLabel=32, AddProjectFile=64}; /* TagData */ class TagData { public: - explicit TagData(const QString &t, const QString &tB = QString(), const QString &tE = QString(), int x = 0, int y = 0, const QString &desc = QString()) - : text(t), tagBegin(tB), tagEnd(tE), dx(x), dy(y), description(desc) {} + explicit TagData(const QString &t, const QString &tB = QString(), const QString &tE = QString(), int x = 0, int y = 0, const QString &desc = QString()) + : text(t), tagBegin(tB), tagEnd(tE), dx(x), dy(y), description(desc) {} - TagData() : text(QString()), tagBegin(QString()), tagEnd(QString()), dx(0), dy(0), description(QString()) {} + TagData() : text(QString()), tagBegin(QString()), tagEnd(QString()), dx(0), dy(0), description(QString()) {} - QString text; - QString tagBegin, tagEnd; - int dx,dy; - QString description; + QString text; + QString tagBegin, tagEnd; + int dx,dy; + QString description; }; class Tag : public QAction { - Q_OBJECT + Q_OBJECT public: - //constructors - Tag(const QString &text, const QString& iconText, const QKeySequence &cut, const QObject *receiver, const char *slot, KActionCollection *parent, const QString& name, - const QString &tagBegin, const QString &tagEnd = QString(), int dx = 0, int dy = 0, const QString &description = QString()); + //constructors + Tag(const QString &text, const QString& iconText, const QKeySequence &cut, const QObject *receiver, const char *slot, KActionCollection *parent, const QString& name, + const QString &tagBegin, const QString &tagEnd = QString(), int dx = 0, int dy = 0, const QString &description = QString()); - Tag(const QString &text, const QString& iconText, const QString& pix, const QKeySequence &cut, const QObject *receiver, const char *slot, KActionCollection *parent, const QString& name, - const QString &tagBegin, const QString &tagEnd = QString(), int dx = 0, int dy = 0, const QString &description = QString()); + Tag(const QString &text, const QString& iconText, const QString& pix, const QKeySequence &cut, const QObject *receiver, const char *slot, KActionCollection *parent, const QString& name, + const QString &tagBegin, const QString &tagEnd = QString(), int dx = 0, int dy = 0, const QString &description = QString()); - Tag(const QString &text, const QString& iconText, const QKeySequence &cut, const QObject *receiver, const char *slot, KActionCollection *parent, const QString& name, - const TagData& data); + Tag(const QString &text, const QString& iconText, const QKeySequence &cut, const QObject *receiver, const char *slot, KActionCollection *parent, const QString& name, + const TagData& data); - Tag(const QString &text, const QString& iconText, const QString& pix, const QKeySequence &cut, const QObject *receiver, const char *slot, KActionCollection *parent, const QString& name, - const TagData& data); + Tag(const QString &text, const QString& iconText, const QString& pix, const QKeySequence &cut, const QObject *receiver, const char *slot, KActionCollection *parent, const QString& name, + const TagData& data); - ~Tag(); + ~Tag(); private: - void init(const QObject *receiver = Q_NULLPTR, const char *slot = Q_NULLPTR); + void init(const QObject *receiver = Q_NULLPTR, const char *slot = Q_NULLPTR); Q_SIGNALS: - //sends along tagdata so that receiver knows what to insert - void triggered(const KileAction::TagData&); + //sends along tagdata so that receiver knows what to insert + void triggered(const KileAction::TagData&); private Q_SLOTS: - //emits the triggered(TagData) signal - virtual void emitData(); + //emits the triggered(TagData) signal + virtual void emitData(); protected: - TagData m_data; + TagData m_data; }; /* InputTag: adds a history list and options for a input dialog to TagData */ class InputTag : public Tag { - Q_OBJECT + Q_OBJECT public: - //constructors - InputTag(KileInfo* ki, const QString &text, const QString &iconText, const QKeySequence &cut, const QObject *receiver, const char *slot, KActionCollection *parent, const QString& name, QWidget *wparent, uint options, - const QString &tagBegin, const QString &tagEnd = QString(), int dx = 0, int dy = 0, const QString &description = QString(), const QString &hint = QString(), const QString &alter = QString()); + //constructors + InputTag(KileInfo* ki, const QString &text, const QString &iconText, const QKeySequence &cut, const QObject *receiver, const char *slot, KActionCollection *parent, const QString& name, QWidget *wparent, uint options, + const QString &tagBegin, const QString &tagEnd = QString(), int dx = 0, int dy = 0, const QString &description = QString(), const QString &hint = QString(), const QString &alter = QString()); - InputTag(KileInfo* ki, const QString &text, const QString &iconText, const QString& pix, const QKeySequence &cut, const QObject *receiver, const char *slot, KActionCollection *parent, const QString& name, QWidget *wparent, uint options, - const QString &tagBegin, const QString &tagEnd = QString(), int dx = 0, int dy = 0, const QString &description = QString(), const QString &hint = QString(), const QString &alter = QString()); + InputTag(KileInfo* ki, const QString &text, const QString &iconText, const QString& pix, const QKeySequence &cut, const QObject *receiver, const char *slot, KActionCollection *parent, const QString& name, QWidget *wparent, uint options, + const QString &tagBegin, const QString &tagEnd = QString(), int dx = 0, int dy = 0, const QString &description = QString(), const QString &hint = QString(), const QString &alter = QString()); - InputTag(KileInfo* ki, const QString &text, const QString &iconText, const QKeySequence &cut, const QObject *receiver, const char *slot, KActionCollection *parent, const QString& name, QWidget *wparent, uint options, - const TagData& data, const QString &hint = QString(), const QString &alter = QString()); + InputTag(KileInfo* ki, const QString &text, const QString &iconText, const QKeySequence &cut, const QObject *receiver, const char *slot, KActionCollection *parent, const QString& name, QWidget *wparent, uint options, + const TagData& data, const QString &hint = QString(), const QString &alter = QString()); - InputTag(KileInfo* ki, const QString &text, const QString &iconText, const QString& pix, const QKeySequence &cut, const QObject *receiver, const char *slot, KActionCollection *parent, const QString& name, QWidget *wparent, uint options, - const TagData& data, const QString &hint = QString(), const QString &alter = QString()); + InputTag(KileInfo* ki, const QString &text, const QString &iconText, const QString& pix, const QKeySequence &cut, const QObject *receiver, const char *slot, KActionCollection *parent, const QString& name, QWidget *wparent, uint options, + const TagData& data, const QString &hint = QString(), const QString &alter = QString()); - ~InputTag(); + ~InputTag(); - bool hasHistory() {return (m_options & KeepHistory); } - bool hasAlternative() { return (m_options & ShowAlternative); } - bool hasBrowseButton() { return (m_options & ShowBrowseButton); } + bool hasHistory() { + return (m_options & KeepHistory); + } + bool hasAlternative() { + return (m_options & ShowAlternative); + } + bool hasBrowseButton() { + return (m_options & ShowBrowseButton); + } - void addToHistory(const QString& str); + void addToHistory(const QString& str); private: - void init(); + void init(); private Q_SLOTS: - //emits the triggered(TagData) signal - virtual void emitData(); + //emits the triggered(TagData) signal + virtual void emitData(); private: - KileInfo *m_ki; - QStringList m_history; - QWidget *m_parent; - uint m_options; - QString m_hint; - QString m_alter; + KileInfo *m_ki; + QStringList m_history; + QWidget *m_parent; + uint m_options; + QString m_hint; + QString m_alter; }; /* InputDialog */ class InputDialog : public QDialog { - Q_OBJECT + Q_OBJECT public: - InputDialog(const QString &caption, uint options, const QStringList& history, const QString &hint, const QString &alter, KileInfo *ki, QWidget *parent=0, const char *name=0); - ~InputDialog(); - - bool useAlternative() {return m_useAlternative;} - bool useLabel() {return m_useLabel;} - bool useAddProjectFile() {return m_useAddProjectFile;} + InputDialog(const QString &caption, uint options, const QStringList& history, const QString &hint, const QString &alter, KileInfo *ki, QWidget *parent=0, const char *name=0); + ~InputDialog(); + + bool useAlternative() { + return m_useAlternative; + } + bool useLabel() { + return m_useLabel; + } + bool useAddProjectFile() { + return m_useAddProjectFile; + } public Q_SLOTS: - void slotBrowse(); - void slotAltClicked(); + void slotBrowse(); + void slotAltClicked(); - void setTag(const QString&); + void setTag(const QString&); Q_SIGNALS: - void setInput(const QString&); + void setInput(const QString&); public: - QString tag() { return m_tag; } - QString label(); - bool usedSelection() { return m_usedSelection; } - - QLineEdit *m_edLabel; + QString tag() { + return m_tag; + } + QString label(); + bool usedSelection() { + return m_usedSelection; + } + + QLineEdit *m_edLabel; private: - QString m_tag; - QString m_labelprefix; - bool m_useAlternative,m_useLabel,m_usedSelection,m_useAddProjectFile; - KileInfo *m_ki; + QString m_tag; + QString m_labelprefix; + bool m_useAlternative,m_useLabel,m_usedSelection,m_useAddProjectFile; + KileInfo *m_ki; }; class Select : public KSelectAction { - Q_OBJECT + Q_OBJECT public: - //constructors - Select(const QString &text, const QKeySequence &cut, KActionCollection *parent, const char *name); + //constructors + Select(const QString &text, const QKeySequence &cut, KActionCollection *parent, const char *name); public Q_SLOTS: - void setItems(const QList &); + void setItems(const QList &); }; class VariantSelection : public QAction { - Q_OBJECT + Q_OBJECT - public: - VariantSelection(const QString &text, const QVariant& value, QObject *parent = Q_NULLPTR); +public: + VariantSelection(const QString &text, const QVariant& value, QObject *parent = Q_NULLPTR); - Q_SIGNALS: - void triggered(const QVariant& value); - void triggered(const QUrl &url); - void triggered(const QString& string); +Q_SIGNALS: + void triggered(const QVariant& value); + void triggered(const QUrl &url); + void triggered(const QString& string); - private Q_SLOTS: - void slotTriggered(); +private Q_SLOTS: + void slotTriggered(); - private: - QVariant m_variant; +private: + QVariant m_variant; }; } class ToolbarSelectAction : public QWidgetAction { - Q_OBJECT + Q_OBJECT public: - ToolbarSelectAction(const QString& text, QObject* parent, bool changeMainActionOnTriggering = true); - - void addAction(QAction *action); - void addSeparator(); - int actionIndex(QAction *action); - QAction* action(int i); - QAction* currentAction(); - bool containsAction(QAction *action); - int currentItem() const; - void setCurrentItem(int i); - void setCurrentAction(QAction *action); - void removeAllActions(); - - void saveCurrentAction(); - void restoreCurrentAction(); + ToolbarSelectAction(const QString& text, QObject* parent, bool changeMainActionOnTriggering = true); + + void addAction(QAction *action); + void addSeparator(); + int actionIndex(QAction *action); + QAction* action(int i); + QAction* currentAction(); + bool containsAction(QAction *action); + int currentItem() const; + void setCurrentItem(int i); + void setCurrentAction(QAction *action); + void removeAllActions(); + + void saveCurrentAction(); + void restoreCurrentAction(); protected Q_SLOTS: - void slotTriggered(QAction*); - void slotMainActionTriggered(); - void slotMainButtonPressed(); + void slotTriggered(QAction*); + void slotMainActionTriggered(); + void slotMainButtonPressed(); Q_SIGNALS: - void mainButtonWithNoActionPressed(); + void mainButtonWithNoActionPressed(); protected: - QMenu* menu(); - QWidget* createWidget(QWidget *parent); + QMenu* menu(); + QWidget* createWidget(QWidget *parent); private: - QList m_actionList; - int m_currentItem; - QString m_mainText; - QAction *m_savedCurrentAction; + QList m_actionList; + int m_currentItem; + QString m_mainText; + QAction *m_savedCurrentAction; }; #endif diff --git a/src/kileappIface.h b/src/kileappIface.h index 76669579..46a13e41 100644 --- a/src/kileappIface.h +++ b/src/kileappIface.h @@ -1,52 +1,52 @@ /******************************************************************************************** begin : sam sep 28 2002 edit : 12/10/2007 copyright : (C) 2002 - 2003 by Pascal Brachet (Jeroen.Wijnhout@kdemail.net) 2003 by Jeroen Wijnhout 2007-2008 by Thomas Braun 2008 by Michel Ludwig (michel.ludwig@kdemail.net) ********************************************************************************************/ /*************************************************************************** * * * 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. * * * ***************************************************************************/ #ifndef KILEAPPIFACE_H #define KILEAPPIFACE_H #include #include /* * This files servers as our source for the xml file net.sourceforge.kile.main.xml - * After changing this file execute + * After changing this file execute * qdbuscpp2xml -a kileappIface.h -o net.sourceforge.kile.main.xml - * + * * This API is subject to change at anytime, however it will be finalized before the next major release * */ class MainAdaptor : public QDBusAbstractAdaptor { - Q_OBJECT - Q_CLASSINFO("D-Bus Interface", "net.sourceforge.kile.main") + Q_OBJECT + Q_CLASSINFO("D-Bus Interface", "net.sourceforge.kile.main") - public Q_SLOTS: - Q_SCRIPTABLE void openDocument(const QString &path); - Q_SCRIPTABLE void closeDocument(); +public Q_SLOTS: + Q_SCRIPTABLE void openDocument(const QString &path); + Q_SCRIPTABLE void closeDocument(); - Q_SCRIPTABLE void openProject(const QString &path); + Q_SCRIPTABLE void openProject(const QString &path); - Q_SCRIPTABLE void insertText(const QString &path); - Q_SCRIPTABLE void setLine(const QString& line); - Q_SCRIPTABLE void setActive(); + Q_SCRIPTABLE void insertText(const QString &path); + Q_SCRIPTABLE void setLine(const QString& line); + Q_SCRIPTABLE void setActive(); - Q_SCRIPTABLE int runTool(const QString &tool); - Q_SCRIPTABLE int runToolWithConfig(const QString &tool, const QString & config); + Q_SCRIPTABLE int runTool(const QString &tool); + Q_SCRIPTABLE int runToolWithConfig(const QString &tool, const QString & config); }; #endif diff --git a/src/kileconstants.h b/src/kileconstants.h index 3d58d0c4..5af4da9e 100644 --- a/src/kileconstants.h +++ b/src/kileconstants.h @@ -1,28 +1,28 @@ /************************************************************************** * Copyright (C) 2006 by Michel Ludwig (michel.ludwig@kdemail.net) * ***************************************************************************/ /************************************************************************** * * * 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. * * * ***************************************************************************/ #ifndef KILECONSTANTS_H #define KILECONSTANTS_H namespace KileDocument { - enum Type {Undefined, Text, LaTeX, BibTeX, Script}; +enum Type {Undefined, Text, LaTeX, BibTeX, Script}; } #ifdef Q_WS_WIN - #define PATH_SEPARATOR ';' +#define PATH_SEPARATOR ';' #else - #define PATH_SEPARATOR ':' +#define PATH_SEPARATOR ':' #endif #endif diff --git a/src/kiledocmanager.cpp b/src/kiledocmanager.cpp index fa773153..e43aee3e 100644 --- a/src/kiledocmanager.cpp +++ b/src/kiledocmanager.cpp @@ -1,2585 +1,2588 @@ /***************************************************************************** * Copyright (C) 2004 by Jeroen Wijnhout (Jeroen.Wijnhout@kdemail.net) * * (C) 2006-2017 by Michel Ludwig (michel.ludwig@kdemail.net) * * (C) 2007 by Holger Danielsson (holger.danielsson@versanet.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. * * * ***************************************************************************/ // 2007-03-12 dani // - use KileDocument::Extensions #include "kiledocmanager.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "dialogs/cleandialog.h" #include "dialogs/listselector.h" #include "dialogs/managetemplatesdialog.h" #include "dialogs/newfilewizard.h" #include "dialogs/projectdialogs.h" #include "documentinfo.h" #include "errorhandler.h" #include "kileconfig.h" #include "kiledebug.h" #include "kileinfo.h" #include "kileproject.h" #include "kilestdtools.h" #include "kiletool_enums.h" #include "kiletool.h" #include "kiletoolmanager.h" #include "kileviewmanager.h" #include "livepreview.h" #include "parser/parsermanager.h" #include "scriptmanager.h" #include "templates.h" #include "widgets/filebrowserwidget.h" #include "widgets/konsolewidget.h" #include "widgets/projectview.h" #include "widgets/structurewidget.h" /* * Newly created text documents have an empty URL and a non-empty document name. */ #define MAX_NUMBER_OF_STORED_SETTINGS 50 namespace KileDocument { Manager::Manager(KileInfo *info, QObject *parent, const char *name) : - QObject(parent), - m_ki(info), - m_progressDialog(Q_NULLPTR), - m_currentlySavingAll(false), - m_currentlyOpeningFile(false) + QObject(parent), + m_ki(info), + m_progressDialog(Q_NULLPTR), + m_currentlySavingAll(false), + m_currentlyOpeningFile(false) { - setObjectName(name); - m_editor = KTextEditor::Editor::instance(); - if(!m_editor) { - KMessageBox::error(m_ki->mainWindow(), i18n("No editor component found. Please check your KDE installation."), - i18n("No editor component found.")); - } + setObjectName(name); + m_editor = KTextEditor::Editor::instance(); + if(!m_editor) { + KMessageBox::error(m_ki->mainWindow(), i18n("No editor component found. Please check your KDE installation."), + i18n("No editor component found.")); + } } Manager::~Manager() { - KILE_DEBUG_MAIN << "==KileDocument::Manager::~Manager()========="; - if(m_progressDialog.isNull()) { - delete m_progressDialog.data(); - } + KILE_DEBUG_MAIN << "==KileDocument::Manager::~Manager()========="; + if(m_progressDialog.isNull()) { + delete m_progressDialog.data(); + } } void Manager::readConfig() { } void Manager::writeConfig() { } void Manager::trashDoc(TextInfo *docinfo, KTextEditor::Document *doc /*= Q_NULLPTR */ ) { - KILE_DEBUG_MAIN << "==void Manager::trashDoc(" << docinfo->url().toLocalFile() << ")====="; + KILE_DEBUG_MAIN << "==void Manager::trashDoc(" << docinfo->url().toLocalFile() << ")====="; - if(m_ki->isOpen(docinfo->url())) { - return; - } + if(m_ki->isOpen(docinfo->url())) { + return; + } - if(doc) { - doc = docinfo->getDoc(); - } + if(doc) { + doc = docinfo->getDoc(); + } - //look for doc before we detach the docinfo - //if we do it the other way around, docFor will always return nil - if(!doc) { - doc = docFor(docinfo->url()); - } + //look for doc before we detach the docinfo + //if we do it the other way around, docFor will always return nil + if(!doc) { + doc = docFor(docinfo->url()); + } - KILE_DEBUG_MAIN << "DETACHING " << docinfo; - docinfo->detach(); + KILE_DEBUG_MAIN << "DETACHING " << docinfo; + docinfo->detach(); - KILE_DEBUG_MAIN << "\tTRASHING " << doc; - if(!doc) { - return; - } + KILE_DEBUG_MAIN << "\tTRASHING " << doc; + if(!doc) { + return; + } - KILE_DEBUG_MAIN << "just checking: docinfo->getDoc() = " << docinfo->getDoc(); - KILE_DEBUG_MAIN << "just checking: docFor(docinfo->url()) = " << docFor(docinfo->url()); + KILE_DEBUG_MAIN << "just checking: docinfo->getDoc() = " << docinfo->getDoc(); + KILE_DEBUG_MAIN << "just checking: docFor(docinfo->url()) = " << docFor(docinfo->url()); - for (int i = 0; i < m_textInfoList.count(); ++i) { - if((m_textInfoList.at(i) != docinfo) && (m_textInfoList.at(i)->getDoc() == doc)) { - KMessageBox::information(0, i18n("The internal structure of Kile is corrupted (probably due to a bug in Kile). Please select Save All from the File menu and close Kile.\nThe Kile team apologizes for any inconvenience and would appreciate a bug report.")); - qWarning() << "docinfo " << m_textInfoList.at(i) << " url " << m_textInfoList.at(i)->url().fileName() << " has a wild pointer!!!"; - } - } + for (int i = 0; i < m_textInfoList.count(); ++i) { + if((m_textInfoList.at(i) != docinfo) && (m_textInfoList.at(i)->getDoc() == doc)) { + KMessageBox::information(0, i18n("The internal structure of Kile is corrupted (probably due to a bug in Kile). Please select Save All from the File menu and close Kile.\nThe Kile team apologizes for any inconvenience and would appreciate a bug report.")); + qWarning() << "docinfo " << m_textInfoList.at(i) << " url " << m_textInfoList.at(i)->url().fileName() << " has a wild pointer!!!"; + } + } - KILE_DEBUG_MAIN << "DELETING doc"; - delete doc; + KILE_DEBUG_MAIN << "DELETING doc"; + delete doc; } // update all Info's with changed user commands void Manager::updateInfos() { - for(QList::iterator it = m_textInfoList.begin(); it != m_textInfoList.end(); ++it) { - (*it)->updateStructLevelInfo(); - } + for(QList::iterator it = m_textInfoList.begin(); it != m_textInfoList.end(); ++it) { + (*it)->updateStructLevelInfo(); + } } bool Manager::isOpeningFile() { - return m_currentlyOpeningFile; + return m_currentlyOpeningFile; } KTextEditor::Editor* Manager::getEditor() { - return m_editor; + return m_editor; } KTextEditor::Document* Manager::docFor(const QUrl &url) { - for(QList::iterator it = m_textInfoList.begin(); it != m_textInfoList.end(); ++it) { - TextInfo *info = *it; + for(QList::iterator it = m_textInfoList.begin(); it != m_textInfoList.end(); ++it) { + TextInfo *info = *it; - if(m_ki->similarOrEqualURL(info->url(), url)) { - return info->getDoc(); - } - } + if(m_ki->similarOrEqualURL(info->url(), url)) { + return info->getDoc(); + } + } - return Q_NULLPTR; + return Q_NULLPTR; } TextInfo* Manager::getInfo() const { - KTextEditor::Document *doc = m_ki->activeTextDocument(); - if(doc) { - return textInfoFor(doc); - } - else { - return Q_NULLPTR; - } + KTextEditor::Document *doc = m_ki->activeTextDocument(); + if(doc) { + return textInfoFor(doc); + } + else { + return Q_NULLPTR; + } } TextInfo* Manager::textInfoFor(const QUrl &url) { - if(url.isEmpty()) { - return Q_NULLPTR; - } + if(url.isEmpty()) { + return Q_NULLPTR; + } - KILE_DEBUG_MAIN << "==KileInfo::textInfoFor(" << url << ")=========================="; + KILE_DEBUG_MAIN << "==KileInfo::textInfoFor(" << url << ")=========================="; - for(QList::iterator it = m_textInfoList.begin(); it != m_textInfoList.end(); ++it) { - TextInfo *info = *it; + for(QList::iterator it = m_textInfoList.begin(); it != m_textInfoList.end(); ++it) { + TextInfo *info = *it; - if (info->url() == url) { - return info; - } - } + if (info->url() == url) { + return info; + } + } - // the URL might belong to a TextInfo* which currently doesn't have a KTextEditor::Document* - // associated with it, i.e. a project item which isn't open in the editor - for(QList::iterator it = m_projects.begin(); it != m_projects.end(); ++it) { - KileProjectItem *item = (*it)->item(url); + // the URL might belong to a TextInfo* which currently doesn't have a KTextEditor::Document* + // associated with it, i.e. a project item which isn't open in the editor + for(QList::iterator it = m_projects.begin(); it != m_projects.end(); ++it) { + KileProjectItem *item = (*it)->item(url); - // all project items (across different projects) that share a URL have the same TextInfo*; - // so, the first one we find is good enough - if(item) { - KileDocument::TextInfo *info = item->getInfo(); - if(info) { - return info; - } - } - } + // all project items (across different projects) that share a URL have the same TextInfo*; + // so, the first one we find is good enough + if(item) { + KileDocument::TextInfo *info = item->getInfo(); + if(info) { + return info; + } + } + } - KILE_DEBUG_MAIN << "\tCOULD NOT find info for " << url; - return Q_NULLPTR; + KILE_DEBUG_MAIN << "\tCOULD NOT find info for " << url; + return Q_NULLPTR; } TextInfo* Manager::textInfoFor(KTextEditor::Document* doc) const { - if(!doc) { - return Q_NULLPTR; - } + if(!doc) { + return Q_NULLPTR; + } - // TextInfo* objects that contain KTextEditor::Document* pointers must be open in the editor, i.e. - // we don't have to look through the project items - for(QList::const_iterator it = m_textInfoList.begin(); it != m_textInfoList.end(); ++it) { - if((*it)->getDoc() == doc) { - return (*it); - } - } + // TextInfo* objects that contain KTextEditor::Document* pointers must be open in the editor, i.e. + // we don't have to look through the project items + for(QList::const_iterator it = m_textInfoList.begin(); it != m_textInfoList.end(); ++it) { + if((*it)->getDoc() == doc) { + return (*it); + } + } - KILE_DEBUG_MAIN << "\tCOULD NOT find info for" << doc->url() << "by searching via a KTextEditor::Document*"; - return Q_NULLPTR; + KILE_DEBUG_MAIN << "\tCOULD NOT find info for" << doc->url() << "by searching via a KTextEditor::Document*"; + return Q_NULLPTR; } QUrl Manager::urlFor(TextInfo* textInfo) { - KileProjectItem *item = itemFor(textInfo); + KileProjectItem *item = itemFor(textInfo); - QUrl url; - if(item) { - url = item->url(); // all items with 'textInfo' share the same URL - } - else { - KTextEditor::Document *document = textInfo->getDoc(); - if(document) { - url = document->url(); - } - } - return url; + QUrl url; + if(item) { + url = item->url(); // all items with 'textInfo' share the same URL + } + else { + KTextEditor::Document *document = textInfo->getDoc(); + if(document) { + url = document->url(); + } + } + return url; } KileProject* Manager::projectForMember(const QUrl &memberUrl) { - for(QList::iterator it = m_projects.begin(); it != m_projects.end(); ++it) { - KileProject *project = *it; + for(QList::iterator it = m_projects.begin(); it != m_projects.end(); ++it) { + KileProject *project = *it; - if(project->contains(memberUrl)) { - return project; - } - } - return Q_NULLPTR; + if(project->contains(memberUrl)) { + return project; + } + } + return Q_NULLPTR; } KileProject* Manager::projectFor(const QUrl &projecturl) { - //find project with url = projecturl - for(QList::iterator it = m_projects.begin(); it != m_projects.end(); ++it) { - KileProject *project = *it; - if(project->url() == projecturl) { - return project; - } - } + //find project with url = projecturl + for(QList::iterator it = m_projects.begin(); it != m_projects.end(); ++it) { + KileProject *project = *it; + if(project->url() == projecturl) { + return project; + } + } - return Q_NULLPTR; + return Q_NULLPTR; } KileProject* Manager::projectFor(const QString &name) { - //find project with url = projecturl - for(QList::iterator it = m_projects.begin(); it != m_projects.end(); ++it) { - KileProject *project = *it; + //find project with url = projecturl + for(QList::iterator it = m_projects.begin(); it != m_projects.end(); ++it) { + KileProject *project = *it; - if (project->name() == name) { - return project; - } - } + if (project->name() == name) { + return project; + } + } - return Q_NULLPTR; + return Q_NULLPTR; } KileProjectItem* Manager::itemFor(const QUrl &url, KileProject *project /*=0L*/) const { - if (!project) { - for(QList::const_iterator it = m_projects.begin(); it != m_projects.end(); ++it) { - KileProject *project = *it; + if (!project) { + for(QList::const_iterator it = m_projects.begin(); it != m_projects.end(); ++it) { + KileProject *project = *it; - KileProjectItem *item = project->item(url); - if(item) { - return item; - } - } - return Q_NULLPTR; - } - else { - return project->item(url); - } + KileProjectItem *item = project->item(url); + if(item) { + return item; + } + } + return Q_NULLPTR; + } + else { + return project->item(url); + } } KileProjectItem* Manager::itemFor(TextInfo *docinfo, KileProject *project /*=0*/) const { - if (!project) { - for(QList::const_iterator it = m_projects.begin(); it != m_projects.end(); ++it) { - KileProject *project = *it; + if (!project) { + for(QList::const_iterator it = m_projects.begin(); it != m_projects.end(); ++it) { + KileProject *project = *it; - KileProjectItem *item = project->item(docinfo); - if(item) { - return item; - } - } - return Q_NULLPTR; - } - else { - return project->item(docinfo); - } + KileProjectItem *item = project->item(docinfo); + if(item) { + return item; + } + } + return Q_NULLPTR; + } + else { + return project->item(docinfo); + } } QList Manager::itemsFor(Info *docinfo) const { - if(!docinfo) { - return QList(); - } + if(!docinfo) { + return QList(); + } - KILE_DEBUG_MAIN << "==KileInfo::itemsFor(" << docinfo->url().fileName() << ")============"; - QList list; - for(QList::const_iterator it = m_projects.begin(); it != m_projects.end(); ++it) { - KileProject *project = *it; + KILE_DEBUG_MAIN << "==KileInfo::itemsFor(" << docinfo->url().fileName() << ")============"; + QList list; + for(QList::const_iterator it = m_projects.begin(); it != m_projects.end(); ++it) { + KileProject *project = *it; - KILE_DEBUG_MAIN << "\tproject: " << (*it)->name(); - if(project->contains(docinfo)) { - KILE_DEBUG_MAIN << "\t\tcontains"; - list.append(project->item(docinfo)); - } - } + KILE_DEBUG_MAIN << "\tproject: " << (*it)->name(); + if(project->contains(docinfo)) { + KILE_DEBUG_MAIN << "\t\tcontains"; + list.append(project->item(docinfo)); + } + } - return list; + return list; } QList Manager::itemsFor(const QUrl &url) const { - QList list; - for(QList::const_iterator it = m_projects.begin(); it != m_projects.end(); ++it) { - KileProject *project = *it; + QList list; + for(QList::const_iterator it = m_projects.begin(); it != m_projects.end(); ++it) { + KileProject *project = *it; - if(project->contains(url)) { - list.append(project->item(url)); - } - } + if(project->contains(url)) { + list.append(project->item(url)); + } + } - return list; + return list; } bool Manager::isProjectOpen() { - return ( m_projects.count() > 0 ); + return ( m_projects.count() > 0 ); } KileProject* Manager::activeProject() { - KTextEditor::Document *doc = m_ki->activeTextDocument(); + KTextEditor::Document *doc = m_ki->activeTextDocument(); - if (doc) { - return projectForMember(doc->url()); - } - else { - return Q_NULLPTR; - } + if (doc) { + return projectForMember(doc->url()); + } + else { + return Q_NULLPTR; + } } KileProjectItem* Manager::activeProjectItem() { - KileProject *curpr = activeProject(); - KTextEditor::Document *doc = m_ki->activeTextDocument(); + KileProject *curpr = activeProject(); + KTextEditor::Document *doc = m_ki->activeTextDocument(); - if (curpr && doc) { - QList list = curpr->items(); + if (curpr && doc) { + QList list = curpr->items(); - for(QList::iterator it = list.begin(); it != list.end(); ++it) { - KileProjectItem *item = *it; + for(QList::iterator it = list.begin(); it != list.end(); ++it) { + KileProjectItem *item = *it; - if (item->url() == doc->url()) { - return item; - } - } - } + if (item->url() == doc->url()) { + return item; + } + } + } - return Q_NULLPTR; + return Q_NULLPTR; } TextInfo* Manager::createTextDocumentInfo(KileDocument::Type type, const QUrl &url, const QUrl& baseDirectory) { - TextInfo *docinfo = Q_NULLPTR; - - // check whether this URL belongs to an opened project and a TextInfo* object has already - // been created for that URL - docinfo = textInfoFor(url); - - if(!docinfo) { - switch(type) { - case Undefined: // fall through - case Text: - KILE_DEBUG_MAIN << "CREATING TextInfo for " << url.url(); - docinfo = new TextInfo(m_ki->extensions(), - m_ki->abbreviationManager(), - m_ki->parserManager()); - break; - case LaTeX: - KILE_DEBUG_MAIN << "CREATING LaTeXInfo for " << url.url(); - docinfo = new LaTeXInfo(m_ki->extensions(), - m_ki->abbreviationManager(), - m_ki->latexCommands(), - m_ki->editorExtension(), - m_ki->configurationManager(), - m_ki->codeCompletionManager(), - m_ki->livePreviewManager(), - m_ki->viewManager(), - m_ki->parserManager()); - break; - case BibTeX: - KILE_DEBUG_MAIN << "CREATING BibInfo for " << url.url(); - docinfo = new BibInfo(m_ki->extensions(), - m_ki->abbreviationManager(), - m_ki->parserManager(), - m_ki->latexCommands()); - break; - case Script: - KILE_DEBUG_MAIN << "CREATING ScriptInfo for " << url.url(); - docinfo = new ScriptInfo(m_ki->extensions(), - m_ki->abbreviationManager(), - m_ki->parserManager()); - break; - } - docinfo->setBaseDirectory(baseDirectory); - emit(documentInfoCreated(docinfo)); - m_textInfoList.append(docinfo); - } - - KILE_DEBUG_MAIN << "DOCINFO: returning " << docinfo << " " << docinfo->url().fileName(); - return docinfo; + TextInfo *docinfo = Q_NULLPTR; + + // check whether this URL belongs to an opened project and a TextInfo* object has already + // been created for that URL + docinfo = textInfoFor(url); + + if(!docinfo) { + switch(type) { + case Undefined: // fall through + case Text: + KILE_DEBUG_MAIN << "CREATING TextInfo for " << url.url(); + docinfo = new TextInfo(m_ki->extensions(), + m_ki->abbreviationManager(), + m_ki->parserManager()); + break; + case LaTeX: + KILE_DEBUG_MAIN << "CREATING LaTeXInfo for " << url.url(); + docinfo = new LaTeXInfo(m_ki->extensions(), + m_ki->abbreviationManager(), + m_ki->latexCommands(), + m_ki->editorExtension(), + m_ki->configurationManager(), + m_ki->codeCompletionManager(), + m_ki->livePreviewManager(), + m_ki->viewManager(), + m_ki->parserManager()); + break; + case BibTeX: + KILE_DEBUG_MAIN << "CREATING BibInfo for " << url.url(); + docinfo = new BibInfo(m_ki->extensions(), + m_ki->abbreviationManager(), + m_ki->parserManager(), + m_ki->latexCommands()); + break; + case Script: + KILE_DEBUG_MAIN << "CREATING ScriptInfo for " << url.url(); + docinfo = new ScriptInfo(m_ki->extensions(), + m_ki->abbreviationManager(), + m_ki->parserManager()); + break; + } + docinfo->setBaseDirectory(baseDirectory); + emit(documentInfoCreated(docinfo)); + m_textInfoList.append(docinfo); + } + + KILE_DEBUG_MAIN << "DOCINFO: returning " << docinfo << " " << docinfo->url().fileName(); + return docinfo; } void Manager::recreateTextDocumentInfo(TextInfo *oldinfo) { - QList list = itemsFor(oldinfo); - QUrl url = oldinfo->url(); - TextInfo *newinfo = createTextDocumentInfo(m_ki->extensions()->determineDocumentType(url), url, oldinfo->getBaseDirectory()); + QList list = itemsFor(oldinfo); + QUrl url = oldinfo->url(); + TextInfo *newinfo = createTextDocumentInfo(m_ki->extensions()->determineDocumentType(url), url, oldinfo->getBaseDirectory()); - newinfo->setDoc(oldinfo->getDoc()); + newinfo->setDoc(oldinfo->getDoc()); - for(QList::iterator it = list.begin(); it != list.end(); ++it) { - (*it)->setInfo(newinfo); - } + for(QList::iterator it = list.begin(); it != list.end(); ++it) { + (*it)->setInfo(newinfo); + } - removeTextDocumentInfo(oldinfo); + removeTextDocumentInfo(oldinfo); - emit(updateStructure(false, newinfo)); + emit(updateStructure(false, newinfo)); } bool Manager::removeTextDocumentInfo(TextInfo *docinfo, bool closingproject /* = false */) { - KILE_DEBUG_MAIN << "==Manager::removeTextDocumentInfo(Info *docinfo)====="; - QList itms = itemsFor(docinfo); - bool oneItem = false; - if(itms.count() == 1) { - oneItem = true; - } + KILE_DEBUG_MAIN << "==Manager::removeTextDocumentInfo(Info *docinfo)====="; + QList itms = itemsFor(docinfo); + bool oneItem = false; + if(itms.count() == 1) { + oneItem = true; + } - if(itms.count() == 0 || ( closingproject && oneItem )) { - KILE_DEBUG_MAIN << "\tremoving " << docinfo << " count = " << m_textInfoList.count(); + if(itms.count() == 0 || ( closingproject && oneItem )) { + KILE_DEBUG_MAIN << "\tremoving " << docinfo << " count = " << m_textInfoList.count(); - // we still have to stop parsing for 'docinfo' - QUrl url = urlFor(docinfo); - if(url.isValid()) { - m_ki->parserManager()->stopDocumentParsing(url); - } + // we still have to stop parsing for 'docinfo' + QUrl url = urlFor(docinfo); + if(url.isValid()) { + m_ki->parserManager()->stopDocumentParsing(url); + } - m_textInfoList.removeAll(docinfo); + m_textInfoList.removeAll(docinfo); - emit(closingDocument(docinfo)); + emit(closingDocument(docinfo)); - cleanupDocumentInfoForProjectItems(docinfo); - delete docinfo; + cleanupDocumentInfoForProjectItems(docinfo); + delete docinfo; - return true; - } + return true; + } - KILE_DEBUG_MAIN << "\tnot removing " << docinfo; - return false; + KILE_DEBUG_MAIN << "\tnot removing " << docinfo; + return false; } KTextEditor::Document* Manager::createDocument(const QUrl &url, TextInfo *docinfo, const QString& encoding, - const QString& mode, - const QString& highlight) -{ - KILE_DEBUG_MAIN << "==KTextEditor::Document* Manager::createDocument()==========="; - - KTextEditor::Document *doc = Q_NULLPTR; - - if(!m_editor) { - return Q_NULLPTR; - } - - doc = docFor(url); - if (doc) { - qWarning() << url << " already has a document!"; - return doc; - } - doc = m_editor->createDocument(Q_NULLPTR); - KILE_DEBUG_MAIN << "appending document " << doc; - - connect(doc, &KTextEditor::Document::canceled, [=] (const QString &errMsg) { - if(!errMsg.isEmpty()) { - KMessageBox::error(m_ki->mainWindow(), i18n("The URL \"%1\" couldn't be opened.\n\n%2", url.toDisplayString(), errMsg), - i18n("Cannot open URL")); - } - else { - KMessageBox::error(m_ki->mainWindow(), i18n("The URL \"%1\" couldn't be opened.", url.toDisplayString()), i18n("Cannot open URL")); - } - }); - - docinfo->setDoc(doc); // do this here to set up all the signals correctly in 'TextInfo' - doc->setEncoding(encoding); - - KILE_DEBUG_MAIN << "url is = " << docinfo->url(); - - if(!url.isEmpty()) { - bool r = doc->openUrl(url); - if(!r) { - KILE_WARNING_MAIN << "couldn't open the url" << url; - docinfo->detach(); - delete doc; - return Q_NULLPTR; - } - // don't add scripts to the recent files - if(r && docinfo->getType() != Script) { - emit(addToRecentFiles(url)); - } - } - - //handle changes of the document - connect(doc, SIGNAL(documentNameChanged(KTextEditor::Document*)), this, SIGNAL(documentNameChanged(KTextEditor::Document*))); - connect(doc, SIGNAL(documentUrlChanged(KTextEditor::Document*)), this, SIGNAL(documentUrlChanged(KTextEditor::Document*))); - if(doc->metaObject()->indexOfSignal(QMetaObject::normalizedSignature("readWriteChanged(KTextEditor::Document*)")) >= 0) { - // signal available in KDE 4.10 - connect(doc, SIGNAL(readWriteChanged(KTextEditor::Document*)), - this, SIGNAL(documentReadWriteStateChanged(KTextEditor::Document*))); - } - - connect(doc, SIGNAL(modifiedChanged(KTextEditor::Document*)), this, SLOT(newDocumentStatus(KTextEditor::Document*))); - KTextEditor::ModificationInterface *modificationInterface = qobject_cast(doc); - if(modificationInterface) { - modificationInterface->setModifiedOnDiskWarning(true); - connect(doc, SIGNAL(modifiedOnDisk(KTextEditor::Document*,bool,KTextEditor::ModificationInterface::ModifiedOnDiskReason)), - this, SIGNAL(documentModificationStatusChanged(KTextEditor::Document*,bool,KTextEditor::ModificationInterface::ModifiedOnDiskReason))); - } - - if(!mode.isEmpty()){ - docinfo->setMode(mode); // this ensures that mode passed with the mode parameter is actually used - } - if(!highlight.isEmpty()){ - docinfo->setHighlightingMode(highlight); - } - // FIXME: the whole structure updating stuff needs to be rewritten; updates should originate from - // the docinfo only, i.e. the structure view should just react to changes! - connect(docinfo, SIGNAL(completed(KileDocument::Info*)), m_ki->structureWidget(), SLOT(update(KileDocument::Info*))); - - KILE_DEBUG_MAIN << "createDocument: url " << doc->url(); - KILE_DEBUG_MAIN << "createDocument: SANITY check: " << (docinfo->getDoc() == docFor(docinfo->url())); - return doc; + const QString& mode, + const QString& highlight) +{ + KILE_DEBUG_MAIN << "==KTextEditor::Document* Manager::createDocument()==========="; + + KTextEditor::Document *doc = Q_NULLPTR; + + if(!m_editor) { + return Q_NULLPTR; + } + + doc = docFor(url); + if (doc) { + qWarning() << url << " already has a document!"; + return doc; + } + doc = m_editor->createDocument(Q_NULLPTR); + KILE_DEBUG_MAIN << "appending document " << doc; + + connect(doc, &KTextEditor::Document::canceled, [=] (const QString &errMsg) { + if(!errMsg.isEmpty()) { + KMessageBox::error(m_ki->mainWindow(), i18n("The URL \"%1\" couldn't be opened.\n\n%2", url.toDisplayString(), errMsg), + i18n("Cannot open URL")); + } + else { + KMessageBox::error(m_ki->mainWindow(), i18n("The URL \"%1\" couldn't be opened.", url.toDisplayString()), i18n("Cannot open URL")); + } + }); + + docinfo->setDoc(doc); // do this here to set up all the signals correctly in 'TextInfo' + doc->setEncoding(encoding); + + KILE_DEBUG_MAIN << "url is = " << docinfo->url(); + + if(!url.isEmpty()) { + bool r = doc->openUrl(url); + if(!r) { + KILE_WARNING_MAIN << "couldn't open the url" << url; + docinfo->detach(); + delete doc; + return Q_NULLPTR; + } + // don't add scripts to the recent files + if(r && docinfo->getType() != Script) { + emit(addToRecentFiles(url)); + } + } + + //handle changes of the document + connect(doc, SIGNAL(documentNameChanged(KTextEditor::Document*)), this, SIGNAL(documentNameChanged(KTextEditor::Document*))); + connect(doc, SIGNAL(documentUrlChanged(KTextEditor::Document*)), this, SIGNAL(documentUrlChanged(KTextEditor::Document*))); + if(doc->metaObject()->indexOfSignal(QMetaObject::normalizedSignature("readWriteChanged(KTextEditor::Document*)")) >= 0) { + // signal available in KDE 4.10 + connect(doc, SIGNAL(readWriteChanged(KTextEditor::Document*)), + this, SIGNAL(documentReadWriteStateChanged(KTextEditor::Document*))); + } + + connect(doc, SIGNAL(modifiedChanged(KTextEditor::Document*)), this, SLOT(newDocumentStatus(KTextEditor::Document*))); + KTextEditor::ModificationInterface *modificationInterface = qobject_cast(doc); + if(modificationInterface) { + modificationInterface->setModifiedOnDiskWarning(true); + connect(doc, SIGNAL(modifiedOnDisk(KTextEditor::Document*,bool,KTextEditor::ModificationInterface::ModifiedOnDiskReason)), + this, SIGNAL(documentModificationStatusChanged(KTextEditor::Document*,bool,KTextEditor::ModificationInterface::ModifiedOnDiskReason))); + } + + if(!mode.isEmpty()) { + docinfo->setMode(mode); // this ensures that mode passed with the mode parameter is actually used + } + if(!highlight.isEmpty()) { + docinfo->setHighlightingMode(highlight); + } + // FIXME: the whole structure updating stuff needs to be rewritten; updates should originate from + // the docinfo only, i.e. the structure view should just react to changes! + connect(docinfo, SIGNAL(completed(KileDocument::Info*)), m_ki->structureWidget(), SLOT(update(KileDocument::Info*))); + + KILE_DEBUG_MAIN << "createDocument: url " << doc->url(); + KILE_DEBUG_MAIN << "createDocument: SANITY check: " << (docinfo->getDoc() == docFor(docinfo->url())); + return doc; } // WARNING: 'item' must have been set up with a TextInfo* object already KTextEditor::View* Manager::loadItem(KileDocument::Type type, KileProjectItem *item, const QString & text, bool openProjectItemViews) { - KTextEditor::View *view = Q_NULLPTR; + KTextEditor::View *view = Q_NULLPTR; - KILE_DEBUG_MAIN << "==loadItem(" << item->url() << ")======"; + KILE_DEBUG_MAIN << "==loadItem(" << item->url() << ")======"; - if(item->type() != KileProjectItem::Image) { - view = loadText(type, item->url(), item->encoding(), openProjectItemViews && item->isOpen(), item->mode(), item->highlight(), text); - KILE_DEBUG_MAIN << "\tloadItem: docfor = " << docFor(item->url()); + if(item->type() != KileProjectItem::Image) { + view = loadText(type, item->url(), item->encoding(), openProjectItemViews && item->isOpen(), item->mode(), item->highlight(), text); + KILE_DEBUG_MAIN << "\tloadItem: docfor = " << docFor(item->url()); - TextInfo *docinfo = item->getInfo(); + TextInfo *docinfo = item->getInfo(); - KILE_DEBUG_MAIN << "\tloadItem: docinfo = " << docinfo << " doc = " << docinfo->getDoc() << " docfor = " << docFor(docinfo->url()); - if ( docinfo->getDoc() != docFor(docinfo->url()) ) qWarning() << "docinfo->getDoc() != docFor()"; - } - else { - KILE_DEBUG_MAIN << "\tloadItem: no document generated"; - TextInfo *docinfo = item->getInfo(); + KILE_DEBUG_MAIN << "\tloadItem: docinfo = " << docinfo << " doc = " << docinfo->getDoc() << " docfor = " << docFor(docinfo->url()); + if ( docinfo->getDoc() != docFor(docinfo->url()) ) qWarning() << "docinfo->getDoc() != docFor()"; + } + else { + KILE_DEBUG_MAIN << "\tloadItem: no document generated"; + TextInfo *docinfo = item->getInfo(); - if(!docFor(item->url())) { - docinfo->detach(); - KILE_DEBUG_MAIN << "\t\t\tdetached"; - } - } + if(!docFor(item->url())) { + docinfo->detach(); + KILE_DEBUG_MAIN << "\t\t\tdetached"; + } + } - return view; + return view; } KTextEditor::View* Manager::loadText(KileDocument::Type type, const QUrl &url, const QString& encoding, - bool create, - const QString& mode, - const QString& highlight, - const QString& text, - int index, - const QUrl &baseDirectory) + bool create, + const QString& mode, + const QString& highlight, + const QString& text, + int index, + const QUrl &baseDirectory) { - KILE_DEBUG_MAIN << "==loadText(" << url.url() << ")================="; - //if doc already opened, update the structure view and return the view - if(!url.isEmpty() && m_ki->isOpen(url)) { - return m_ki->viewManager()->switchToTextView(url); - } + KILE_DEBUG_MAIN << "==loadText(" << url.url() << ")================="; + //if doc already opened, update the structure view and return the view + if(!url.isEmpty() && m_ki->isOpen(url)) { + return m_ki->viewManager()->switchToTextView(url); + } - TextInfo *docinfo = createTextDocumentInfo(type, url, baseDirectory); - KTextEditor::Document *doc = createDocument(url, docinfo, encoding, mode, highlight); - if(!doc) { - removeTextDocumentInfo(docinfo); - return Q_NULLPTR; - } + TextInfo *docinfo = createTextDocumentInfo(type, url, baseDirectory); + KTextEditor::Document *doc = createDocument(url, docinfo, encoding, mode, highlight); + if(!doc) { + removeTextDocumentInfo(docinfo); + return Q_NULLPTR; + } - m_ki->structureWidget()->clean(docinfo); + m_ki->structureWidget()->clean(docinfo); - if(!text.isEmpty()) { - doc->setText(text); - } + if(!text.isEmpty()) { + doc->setText(text); + } - if (doc && create) { - return m_ki->viewManager()->createTextView(docinfo, index); - } + if (doc && create) { + return m_ki->viewManager()->createTextView(docinfo, index); + } - KILE_DEBUG_MAIN << "just after createView()"; - KILE_DEBUG_MAIN << "\tdocinfo = " << docinfo << " doc = " << docinfo->getDoc() << " docfor = " << docFor(docinfo->url()); + KILE_DEBUG_MAIN << "just after createView()"; + KILE_DEBUG_MAIN << "\tdocinfo = " << docinfo << " doc = " << docinfo->getDoc() << " docfor = " << docFor(docinfo->url()); - return Q_NULLPTR; + return Q_NULLPTR; } //FIXME: template stuff should be in own class KTextEditor::View* Manager::loadTemplate(TemplateItem *sel) { - KILE_DEBUG_MAIN << "templateitem *sel = " << sel; - QString text; - - if(!sel) { - return Q_NULLPTR; - } - - if (sel->name() != KileTemplate::Manager::defaultEmptyTemplateCaption() - && sel->name() != KileTemplate::Manager::defaultEmptyLaTeXTemplateCaption() - && sel->name() != KileTemplate::Manager::defaultEmptyBibTeXTemplateCaption()) { - if(!m_editor) { - return Q_NULLPTR; - } - //create a new document to open the template in - KTextEditor::Document *tempdoc = m_editor->createDocument(Q_NULLPTR); - - if (!tempdoc->openUrl(QUrl::fromLocalFile(sel->path()))) { - KMessageBox::error(m_ki->mainWindow(), i18n("Could not find template: %1", sel->name()), i18n("File Not Found")); - } - else { - //substitute templates variables - text = tempdoc->text(); - delete tempdoc; - replaceTemplateVariables(text); - } - } - - KileDocument::Type type = sel->type(); - //always set the base directory for scripts - return createDocumentWithText(text, type, QString(), (type == KileDocument::Script ? QUrl::fromLocalFile(m_ki->scriptManager()->getLocalScriptDirectory()) : QUrl())); + KILE_DEBUG_MAIN << "templateitem *sel = " << sel; + QString text; + + if(!sel) { + return Q_NULLPTR; + } + + if (sel->name() != KileTemplate::Manager::defaultEmptyTemplateCaption() + && sel->name() != KileTemplate::Manager::defaultEmptyLaTeXTemplateCaption() + && sel->name() != KileTemplate::Manager::defaultEmptyBibTeXTemplateCaption()) { + if(!m_editor) { + return Q_NULLPTR; + } + //create a new document to open the template in + KTextEditor::Document *tempdoc = m_editor->createDocument(Q_NULLPTR); + + if (!tempdoc->openUrl(QUrl::fromLocalFile(sel->path()))) { + KMessageBox::error(m_ki->mainWindow(), i18n("Could not find template: %1", sel->name()), i18n("File Not Found")); + } + else { + //substitute templates variables + text = tempdoc->text(); + delete tempdoc; + replaceTemplateVariables(text); + } + } + + KileDocument::Type type = sel->type(); + //always set the base directory for scripts + return createDocumentWithText(text, type, QString(), (type == KileDocument::Script ? QUrl::fromLocalFile(m_ki->scriptManager()->getLocalScriptDirectory()) : QUrl())); } KTextEditor::View* Manager::createDocumentWithText(const QString& text, KileDocument::Type type /* = KileDocument::Undefined */, const QString& /* extension */, const QUrl &baseDirectory) { - KTextEditor::View *view = loadText(type, QUrl(), QString(), true, QString(), QString(), text, -1, baseDirectory); - if(view) { - //FIXME this shouldn't be necessary!!! - view->document()->setModified(true); - newDocumentStatus(view->document()); - } + KTextEditor::View *view = loadText(type, QUrl(), QString(), true, QString(), QString(), text, -1, baseDirectory); + if(view) { + //FIXME this shouldn't be necessary!!! + view->document()->setModified(true); + newDocumentStatus(view->document()); + } - return view; + return view; } KTextEditor::View* Manager::createNewJScript() { - KTextEditor::View *view = createDocumentWithText(QString(), Script, "js", QUrl::fromLocalFile(m_ki->scriptManager()->getLocalScriptDirectory())); - emit(updateStructure(false, Q_NULLPTR)); - emit(updateModeStatus()); - return view; + KTextEditor::View *view = createDocumentWithText(QString(), Script, "js", QUrl::fromLocalFile(m_ki->scriptManager()->getLocalScriptDirectory())); + emit(updateStructure(false, Q_NULLPTR)); + emit(updateModeStatus()); + return view; } KTextEditor::View* Manager::createNewLaTeXDocument() { - KTextEditor::View *view = createDocumentWithText(QString(), LaTeX); - emit(updateStructure(false, Q_NULLPTR)); - emit(updateModeStatus()); - return view; + KTextEditor::View *view = createDocumentWithText(QString(), LaTeX); + emit(updateStructure(false, Q_NULLPTR)); + emit(updateModeStatus()); + return view; } void Manager::replaceTemplateVariables(QString &line) { - line=line.replace("$$AUTHOR$$", KileConfig::author()); - line=line.replace("$$DOCUMENTCLASSOPTIONS$$", KileConfig::documentClassOptions()); - if (!KileConfig::templateEncoding().isEmpty()) { line=line.replace("$$INPUTENCODING$$", "\\usepackage["+ KileConfig::templateEncoding() +"]{inputenc}");} - else { - line = line.remove("$$INPUTENCODING$$"); - } + line=line.replace("$$AUTHOR$$", KileConfig::author()); + line=line.replace("$$DOCUMENTCLASSOPTIONS$$", KileConfig::documentClassOptions()); + if (!KileConfig::templateEncoding().isEmpty()) { + line=line.replace("$$INPUTENCODING$$", "\\usepackage["+ KileConfig::templateEncoding() +"]{inputenc}"); + } + else { + line = line.remove("$$INPUTENCODING$$"); + } } void Manager::createTemplate() { - KTextEditor::View *view = m_ki->viewManager()->currentTextView(); - if (view) { - if (view->document()->isModified()) { - KMessageBox::information(m_ki->mainWindow(),i18n("Please save the file first.")); - return; - } - } - else { - KMessageBox::information(m_ki->mainWindow(),i18n("Open/create a document first.")); - return; - } + KTextEditor::View *view = m_ki->viewManager()->currentTextView(); + if (view) { + if (view->document()->isModified()) { + KMessageBox::information(m_ki->mainWindow(),i18n("Please save the file first.")); + return; + } + } + else { + KMessageBox::information(m_ki->mainWindow(),i18n("Open/create a document first.")); + return; + } - QUrl url = view->document()->url(); - KileDocument::Type type = m_ki->extensions()->determineDocumentType(url); + QUrl url = view->document()->url(); + KileDocument::Type type = m_ki->extensions()->determineDocumentType(url); - if(type == KileDocument::Undefined || type == KileDocument::Text) { - KMessageBox::information(m_ki->mainWindow(),i18n("A template for this type of document cannot be created.")); - return; - } + if(type == KileDocument::Undefined || type == KileDocument::Text) { + KMessageBox::information(m_ki->mainWindow(),i18n("A template for this type of document cannot be created.")); + return; + } - ManageTemplatesDialog mtd(m_ki->templateManager(), url, i18n("Create Template From Document")); - mtd.exec(); + ManageTemplatesDialog mtd(m_ki->templateManager(), url, i18n("Create Template From Document")); + mtd.exec(); } void Manager::removeTemplate() { - ManageTemplatesDialog mtd(m_ki->templateManager(), i18n("Remove Template")); - mtd.exec(); + ManageTemplatesDialog mtd(m_ki->templateManager(), i18n("Remove Template")); + mtd.exec(); } void Manager::fileNew(KileDocument::Type type) { - NewFileWizard *nfw = new NewFileWizard(m_ki->templateManager(), type, m_ki->mainWindow()); - if(nfw->exec()) { - KTextEditor::View *view = loadTemplate(nfw->getSelection()); - if(view) { - if(nfw->useWizard()) { - emit(startWizard()); - } - emit(updateStructure(false, Q_NULLPTR)); - emit(updateModeStatus()); - } - } - delete nfw; + NewFileWizard *nfw = new NewFileWizard(m_ki->templateManager(), type, m_ki->mainWindow()); + if(nfw->exec()) { + KTextEditor::View *view = loadTemplate(nfw->getSelection()); + if(view) { + if(nfw->useWizard()) { + emit(startWizard()); + } + emit(updateStructure(false, Q_NULLPTR)); + emit(updateModeStatus()); + } + } + delete nfw; } void Manager::fileNewScript() { - fileNew(KileDocument::Script); + fileNew(KileDocument::Script); } void Manager::fileNew(const QUrl &url) { - //create an empty file - QFile file(url.toLocalFile()); - file.open(QIODevice::ReadWrite); - file.close(); + //create an empty file + QFile file(url.toLocalFile()); + file.open(QIODevice::ReadWrite); + file.close(); - fileOpen(url, QString()); + fileOpen(url, QString()); } void Manager::fileOpen() { - //determine the starting dir for the file dialog - QString compileName = m_ki->getCompileName(); - QString currentDir; - if(QFileInfo(compileName).exists()) { - currentDir = QFileInfo(compileName).absolutePath(); - } - else { - currentDir = m_ki->fileSelector()->currentUrl().toLocalFile(); - } - - // use a filter for fileOpen dialog - Extensions *extensions = m_ki->extensions(); - QString filter = extensions->fileFilterKDEStyle(true, {KileDocument::Extensions::TEX, - KileDocument::Extensions::PACKAGES, - KileDocument::Extensions::BIB, - KileDocument::Extensions::METAPOST}); - - // try to get the current encoding, this is kind of ugly ... - QString encoding = m_ki->toolManager()->config()->group("Kate Document Defaults").readEntry("Encoding",""); - - //get the URLs - KEncodingFileDialog::Result result = KEncodingFileDialog::getOpenUrlsAndEncoding(encoding, QUrl::fromLocalFile(currentDir), filter, m_ki->mainWindow(), i18n("Open Files")); - - //open them - const QList& urls = result.URLs; - for (QList::ConstIterator i = urls.begin(); i != urls.end(); ++i) { - const QUrl& url = *i; - if(m_ki->extensions()->isProjectFile(url)) { // this can happen... (bug 317432) - KILE_DEBUG_MAIN << "file is a project file:" << url; - projectOpen(url); - continue; - } - - fileOpen(url, result.encoding); - } + //determine the starting dir for the file dialog + QString compileName = m_ki->getCompileName(); + QString currentDir; + if(QFileInfo(compileName).exists()) { + currentDir = QFileInfo(compileName).absolutePath(); + } + else { + currentDir = m_ki->fileSelector()->currentUrl().toLocalFile(); + } + + // use a filter for fileOpen dialog + Extensions *extensions = m_ki->extensions(); + QString filter = extensions->fileFilterKDEStyle(true, {KileDocument::Extensions::TEX, + KileDocument::Extensions::PACKAGES, + KileDocument::Extensions::BIB, + KileDocument::Extensions::METAPOST + }); + + // try to get the current encoding, this is kind of ugly ... + QString encoding = m_ki->toolManager()->config()->group("Kate Document Defaults").readEntry("Encoding",""); + + //get the URLs + KEncodingFileDialog::Result result = KEncodingFileDialog::getOpenUrlsAndEncoding(encoding, QUrl::fromLocalFile(currentDir), filter, m_ki->mainWindow(), i18n("Open Files")); + + //open them + const QList& urls = result.URLs; + for (QList::ConstIterator i = urls.begin(); i != urls.end(); ++i) { + const QUrl& url = *i; + if(m_ki->extensions()->isProjectFile(url)) { // this can happen... (bug 317432) + KILE_DEBUG_MAIN << "file is a project file:" << url; + projectOpen(url); + continue; + } + + fileOpen(url, result.encoding); + } } void Manager::fileSelected(const KFileItem& file) { - fileSelected(file.url()); + fileSelected(file.url()); } void Manager::fileSelected(const KileProjectItem * item) { - fileOpen(item->url(), item->encoding()); + fileOpen(item->url(), item->encoding()); } void Manager::fileSelected(const QUrl &url) { - fileOpen(url, QString()); + fileOpen(url, QString()); } void Manager::saveURL(const QUrl &url) { - KTextEditor::Document *doc = docFor(url); - if(doc) { - doc->save(); - } + KTextEditor::Document *doc = docFor(url); + if(doc) { + doc->save(); + } } void Manager::newDocumentStatus(KTextEditor::Document *doc) { - KILE_DEBUG_MAIN << "void Manager::newDocumentStatus(Kate::Document)" << endl; - if(!doc) { - return; - } + KILE_DEBUG_MAIN << "void Manager::newDocumentStatus(Kate::Document)" << endl; + if(!doc) { + return; + } - // sync terminal - m_ki->texKonsole()->sync(); + // sync terminal + m_ki->texKonsole()->sync(); - emit(documentModificationStatusChanged(doc, doc->isModified(), KTextEditor::ModificationInterface::OnDiskUnmodified)); + emit(documentModificationStatusChanged(doc, doc->isModified(), KTextEditor::ModificationInterface::OnDiskUnmodified)); } bool Manager::fileSaveAll(bool disUntitled) { - // this can occur when autosaving should take place when we - // are still busy with it (KIO::NetAccess keeps the event loop running) - if(m_currentlySavingAll) { - return true; - } - m_currentlySavingAll = true; - KTextEditor::View *view = Q_NULLPTR; - QFileInfo fi; - bool oneSaveFailed = false; - QUrl url, backupUrl; - - KILE_DEBUG_MAIN << "===Kile::fileSaveAll(disUntitled = " << disUntitled <<")"; - - for(int i = 0; i < m_ki->viewManager()->textViewCount(); ++i) { - view = m_ki->viewManager()->textView(i); - - if(view && view->document()->isModified()) { - url = view->document()->url(); - fi.setFile(url.toLocalFile()); - - if(!disUntitled || !(disUntitled && url.isEmpty())) { // either we don't disregard untitled docs, or the doc has a title - KILE_DEBUG_MAIN << "trying to save: " << url.toLocalFile(); - bool saveResult = view->document()->documentSave(); - fi.refresh(); - - if(!saveResult) { - oneSaveFailed = true; - m_ki->errorHandler()->printMessage(KileTool::Error, - i18n("Kile encountered problems while saving the file %1. Do you have enough free disk space left?", url.toDisplayString()), - i18n("Saving")); - } - } - } - } - - /* - This may look superfluos but actually it is not, in the case of multiple modified docs it ensures that the structure view keeps synchronized with the currentTextView - And if we only have one masterdoc or none nothing goes wrong. - */ - emit(updateStructure(false, Q_NULLPTR)); - m_currentlySavingAll = false; - return !oneSaveFailed; + // this can occur when autosaving should take place when we + // are still busy with it (KIO::NetAccess keeps the event loop running) + if(m_currentlySavingAll) { + return true; + } + m_currentlySavingAll = true; + KTextEditor::View *view = Q_NULLPTR; + QFileInfo fi; + bool oneSaveFailed = false; + QUrl url, backupUrl; + + KILE_DEBUG_MAIN << "===Kile::fileSaveAll(disUntitled = " << disUntitled <<")"; + + for(int i = 0; i < m_ki->viewManager()->textViewCount(); ++i) { + view = m_ki->viewManager()->textView(i); + + if(view && view->document()->isModified()) { + url = view->document()->url(); + fi.setFile(url.toLocalFile()); + + if(!disUntitled || !(disUntitled && url.isEmpty())) { // either we don't disregard untitled docs, or the doc has a title + KILE_DEBUG_MAIN << "trying to save: " << url.toLocalFile(); + bool saveResult = view->document()->documentSave(); + fi.refresh(); + + if(!saveResult) { + oneSaveFailed = true; + m_ki->errorHandler()->printMessage(KileTool::Error, + i18n("Kile encountered problems while saving the file %1. Do you have enough free disk space left?", url.toDisplayString()), + i18n("Saving")); + } + } + } + } + + /* + This may look superfluos but actually it is not, in the case of multiple modified docs it ensures that the structure view keeps synchronized with the currentTextView + And if we only have one masterdoc or none nothing goes wrong. + */ + emit(updateStructure(false, Q_NULLPTR)); + m_currentlySavingAll = false; + return !oneSaveFailed; } TextInfo* Manager::fileOpen(const QUrl &url, const QString& encoding, int index) { - m_currentlyOpeningFile = true; - KILE_DEBUG_MAIN << "==Kile::fileOpen=========================="; - - if(url.isLocalFile() && QFileInfo(url.toLocalFile()).isDir()) { - KILE_DEBUG_MAIN << "tried to open directory" << url; - KMessageBox::error(m_ki->mainWindow(), i18n("The URL \"%1\" cannot be opened\nas it is a directory.", url.toDisplayString()), - i18n("Cannot open directory")); - m_currentlyOpeningFile = false; // has to be before the 'switchToTextView' call as - // it emits signals that are handled by the live preview manager - return Q_NULLPTR; - } - - KILE_DEBUG_MAIN << "url is " << url.url(); - const QUrl realurl = symlinkFreeURL(url); - KILE_DEBUG_MAIN << "symlink free url is " << realurl.url(); - - if(m_ki->isOpen(realurl)) { - m_currentlyOpeningFile = false; // has to be before the 'switchToTextView' call as - // it emits signals that are handled by the live preview manager - m_ki->viewManager()->switchToTextView(realurl); - return textInfoFor(realurl); - } - - KTextEditor::View *view = loadText(m_ki->extensions()->determineDocumentType(realurl), realurl, encoding, true, QString(), QString(), QString(), index); - if(!view) { - m_currentlyOpeningFile = false; // has to be before the 'switchToTextView' call as - // it emits signals that are handled by the live preview manager - return Q_NULLPTR; - } - QList itemList = itemsFor(realurl); - TextInfo *textInfo = textInfoFor(realurl); - - for(QList::iterator it = itemList.begin(); it != itemList.end(); ++it) { - (*it)->setInfo(textInfo); - } - - if(itemList.isEmpty()) { - emit addToProjectView(realurl); - loadDocumentAndViewSettings(textInfo); - } - else if(view) { - KileProjectItem *item = itemList.first(); - item->loadDocumentAndViewSettings(); - } - - emit(updateStructure(false, Q_NULLPTR)); - emit(updateModeStatus()); - // update undefined references in this file - emit(updateReferences(textInfoFor(realurl))); - m_currentlyOpeningFile = false; - emit documentOpened(textInfo); - return textInfo; + m_currentlyOpeningFile = true; + KILE_DEBUG_MAIN << "==Kile::fileOpen=========================="; + + if(url.isLocalFile() && QFileInfo(url.toLocalFile()).isDir()) { + KILE_DEBUG_MAIN << "tried to open directory" << url; + KMessageBox::error(m_ki->mainWindow(), i18n("The URL \"%1\" cannot be opened\nas it is a directory.", url.toDisplayString()), + i18n("Cannot open directory")); + m_currentlyOpeningFile = false; // has to be before the 'switchToTextView' call as + // it emits signals that are handled by the live preview manager + return Q_NULLPTR; + } + + KILE_DEBUG_MAIN << "url is " << url.url(); + const QUrl realurl = symlinkFreeURL(url); + KILE_DEBUG_MAIN << "symlink free url is " << realurl.url(); + + if(m_ki->isOpen(realurl)) { + m_currentlyOpeningFile = false; // has to be before the 'switchToTextView' call as + // it emits signals that are handled by the live preview manager + m_ki->viewManager()->switchToTextView(realurl); + return textInfoFor(realurl); + } + + KTextEditor::View *view = loadText(m_ki->extensions()->determineDocumentType(realurl), realurl, encoding, true, QString(), QString(), QString(), index); + if(!view) { + m_currentlyOpeningFile = false; // has to be before the 'switchToTextView' call as + // it emits signals that are handled by the live preview manager + return Q_NULLPTR; + } + QList itemList = itemsFor(realurl); + TextInfo *textInfo = textInfoFor(realurl); + + for(QList::iterator it = itemList.begin(); it != itemList.end(); ++it) { + (*it)->setInfo(textInfo); + } + + if(itemList.isEmpty()) { + emit addToProjectView(realurl); + loadDocumentAndViewSettings(textInfo); + } + else if(view) { + KileProjectItem *item = itemList.first(); + item->loadDocumentAndViewSettings(); + } + + emit(updateStructure(false, Q_NULLPTR)); + emit(updateModeStatus()); + // update undefined references in this file + emit(updateReferences(textInfoFor(realurl))); + m_currentlyOpeningFile = false; + emit documentOpened(textInfo); + return textInfo; } bool Manager::fileSave(KTextEditor::View *view) { - // the 'data' property can be set by the view manager - QAction *action = dynamic_cast(QObject::sender()); - if(action) { - QVariant var = action->data(); - if(!view && var.isValid()) { - view = var.value(); - // the 'data' property for the relevant actions is cleared - // inside the view manager - } - } - if(!view) { - view = m_ki->viewManager()->currentTextView(); - } - if(!view) { - return false; - } - QUrl url = view->document()->url(); - if(url.isEmpty()) { // newly created document - return fileSaveAs(view); - } - else { - bool ret = view->document()->documentSave(); - emit(updateStructure(false, textInfoFor(view->document()))); - return ret; - } + // the 'data' property can be set by the view manager + QAction *action = dynamic_cast(QObject::sender()); + if(action) { + QVariant var = action->data(); + if(!view && var.isValid()) { + view = var.value(); + // the 'data' property for the relevant actions is cleared + // inside the view manager + } + } + if(!view) { + view = m_ki->viewManager()->currentTextView(); + } + if(!view) { + return false; + } + QUrl url = view->document()->url(); + if(url.isEmpty()) { // newly created document + return fileSaveAs(view); + } + else { + bool ret = view->document()->documentSave(); + emit(updateStructure(false, textInfoFor(view->document()))); + return ret; + } } bool Manager::fileSaveAs(KTextEditor::View* view) { - // the 'data' property can be set by the view manager - QAction *action = dynamic_cast(QObject::sender()); - if(action) { - QVariant var = action->data(); - if(!view && var.isValid()) { - view = var.value(); - // the 'data' property for the relevant actions is cleared - // inside the view manager - } - } - if(!view) { - view = m_ki->viewManager()->currentTextView(); - } - if(!view) { - return false; - } - - KTextEditor::Document* doc = view->document(); - Q_ASSERT(doc); - KileDocument::TextInfo* info = textInfoFor(doc); - Q_ASSERT(info); - QUrl startUrl = info->url(); - QUrl oldURL = info->url(); - if(startUrl.isEmpty()) { - QUrl baseDirectory = info->getBaseDirectory(); - if(baseDirectory.isEmpty()) { - startUrl = QUrl("kfiledialog:///KILE_LATEX_SAVE_DIR"); - } - else { - startUrl = baseDirectory; - } - } - - KILE_DEBUG_MAIN << "startUrl is " << startUrl; - KEncodingFileDialog::Result result; - QUrl saveURL; - while(true) { - QString filter = m_ki->extensions()->fileFilterKDEStyle(true, info->getFileFilter()); - - result = KEncodingFileDialog::getSaveUrlAndEncoding(doc->encoding(), startUrl, filter, m_ki->mainWindow(), i18n("Save File")); - if(result.URLs.isEmpty() || result.URLs.first().isEmpty()) { - return false; - } - saveURL = result.URLs.first(); - if(info->getType() == KileDocument::LaTeX) { - saveURL = Info::makeValidTeXURL(saveURL, m_ki->mainWindow(), - m_ki->extensions()->isTexFile(saveURL), false); // don't check for file existence - } - - auto statJob = KIO::stat(saveURL, KIO::StatJob::SourceSide, 0); - KJobWidgets::setWindow(statJob, m_ki->mainWindow()); - if (statJob->exec()) { // check for writing possibility - int r = KMessageBox::warningContinueCancel(m_ki->mainWindow(), i18n("A file with the name \"%1\" exists already. Do you want to overwrite it?", saveURL.fileName()), i18n("Overwrite File?"), KStandardGuiItem::overwrite()); - if(r != KMessageBox::Continue) { - continue; - } - } - break; - } - doc->setEncoding(result.encoding); - if(!doc->saveAs(saveURL)) { - return false; - } - if(oldURL != saveURL) { - if(info->isDocumentTypePromotionAllowed()) { - recreateTextDocumentInfo(info); - info = textInfoFor(doc); - } - m_ki->structureWidget()->updateUrl(info); - emit addToRecentFiles(saveURL); - emit addToProjectView(doc->url()); - } - emit(documentSavedAs(view, info)); - return true; + // the 'data' property can be set by the view manager + QAction *action = dynamic_cast(QObject::sender()); + if(action) { + QVariant var = action->data(); + if(!view && var.isValid()) { + view = var.value(); + // the 'data' property for the relevant actions is cleared + // inside the view manager + } + } + if(!view) { + view = m_ki->viewManager()->currentTextView(); + } + if(!view) { + return false; + } + + KTextEditor::Document* doc = view->document(); + Q_ASSERT(doc); + KileDocument::TextInfo* info = textInfoFor(doc); + Q_ASSERT(info); + QUrl startUrl = info->url(); + QUrl oldURL = info->url(); + if(startUrl.isEmpty()) { + QUrl baseDirectory = info->getBaseDirectory(); + if(baseDirectory.isEmpty()) { + startUrl = QUrl("kfiledialog:///KILE_LATEX_SAVE_DIR"); + } + else { + startUrl = baseDirectory; + } + } + + KILE_DEBUG_MAIN << "startUrl is " << startUrl; + KEncodingFileDialog::Result result; + QUrl saveURL; + while(true) { + QString filter = m_ki->extensions()->fileFilterKDEStyle(true, info->getFileFilter()); + + result = KEncodingFileDialog::getSaveUrlAndEncoding(doc->encoding(), startUrl, filter, m_ki->mainWindow(), i18n("Save File")); + if(result.URLs.isEmpty() || result.URLs.first().isEmpty()) { + return false; + } + saveURL = result.URLs.first(); + if(info->getType() == KileDocument::LaTeX) { + saveURL = Info::makeValidTeXURL(saveURL, m_ki->mainWindow(), + m_ki->extensions()->isTexFile(saveURL), false); // don't check for file existence + } + + auto statJob = KIO::stat(saveURL, KIO::StatJob::SourceSide, 0); + KJobWidgets::setWindow(statJob, m_ki->mainWindow()); + if (statJob->exec()) { // check for writing possibility + int r = KMessageBox::warningContinueCancel(m_ki->mainWindow(), i18n("A file with the name \"%1\" exists already. Do you want to overwrite it?", saveURL.fileName()), i18n("Overwrite File?"), KStandardGuiItem::overwrite()); + if(r != KMessageBox::Continue) { + continue; + } + } + break; + } + doc->setEncoding(result.encoding); + if(!doc->saveAs(saveURL)) { + return false; + } + if(oldURL != saveURL) { + if(info->isDocumentTypePromotionAllowed()) { + recreateTextDocumentInfo(info); + info = textInfoFor(doc); + } + m_ki->structureWidget()->updateUrl(info); + emit addToRecentFiles(saveURL); + emit addToProjectView(doc->url()); + } + emit(documentSavedAs(view, info)); + return true; } void Manager::fileSaveCopyAs() { - KTextEditor::View *view = Q_NULLPTR; - // the 'data' property can be set by the view manager - QAction *action = dynamic_cast(QObject::sender()); - if(action) { - QVariant var = action->data(); - if(var.isValid()) { - view = var.value(); - // the 'data' property for the relevant actions is cleared - // inside the view manager - } - } - if(!view) { - view = m_ki->viewManager()->currentTextView(); - } - if(!view) { - return; - } + KTextEditor::View *view = Q_NULLPTR; + // the 'data' property can be set by the view manager + QAction *action = dynamic_cast(QObject::sender()); + if(action) { + QVariant var = action->data(); + if(var.isValid()) { + view = var.value(); + // the 'data' property for the relevant actions is cleared + // inside the view manager + } + } + if(!view) { + view = m_ki->viewManager()->currentTextView(); + } + if(!view) { + return; + } - KTextEditor::Document *doc = view->document(); + KTextEditor::Document *doc = view->document(); - if(!doc) { - return; - } + if(!doc) { + return; + } - KileDocument::TextInfo *originalInfo = textInfoFor(doc); + KileDocument::TextInfo *originalInfo = textInfoFor(doc); - if(!originalInfo) { - return; - } + if(!originalInfo) { + return; + } - view = createDocumentWithText(doc->text(),originalInfo->getType()); + view = createDocumentWithText(doc->text(),originalInfo->getType()); - KileDocument::TextInfo *newInfo = textInfoFor(view->document()); + KileDocument::TextInfo *newInfo = textInfoFor(view->document()); - if(originalInfo->url().isEmpty()) { // untitled doc - newInfo->setBaseDirectory(m_ki->fileSelector()->currentUrl()); - } - else { - newInfo->setBaseDirectory(originalInfo->url()); - } + if(originalInfo->url().isEmpty()) { // untitled doc + newInfo->setBaseDirectory(m_ki->fileSelector()->currentUrl()); + } + else { + newInfo->setBaseDirectory(originalInfo->url()); + } - fileSaveAs(view); + fileSaveAs(view); - doc = view->document(); - if(doc && !doc->isModified()) { // fileSaveAs was successful - fileClose(doc); - } + doc = view->document(); + if(doc && !doc->isModified()) { // fileSaveAs was successful + fileClose(doc); + } } bool Manager::fileCloseAllOthers(KTextEditor::View *currentView) { - // the 'data' property can be set by the view manager - QAction *action = dynamic_cast(QObject::sender()); - if(action) { - QVariant var = action->data(); - if(!currentView && var.isValid()) { - // the 'data' property for the relevant actions is cleared - // inside the view manager - currentView = var.value(); - } - } - if(!currentView) { - currentView = m_ki->viewManager()->currentTextView(); - } - if(!currentView) { - return false; - } - - QList viewList; - for(int i = 0; i < m_ki->viewManager()->textViewCount(); ++i) { - KTextEditor::View *view = m_ki->viewManager()->textView(i); - if(currentView == view) { - continue; - } - viewList.push_back(view); - - } - for(QList::iterator it = viewList.begin(); - it != viewList.end(); ++it) { - if (!fileClose(*it)) { - return false; - } - } - return true; + // the 'data' property can be set by the view manager + QAction *action = dynamic_cast(QObject::sender()); + if(action) { + QVariant var = action->data(); + if(!currentView && var.isValid()) { + // the 'data' property for the relevant actions is cleared + // inside the view manager + currentView = var.value(); + } + } + if(!currentView) { + currentView = m_ki->viewManager()->currentTextView(); + } + if(!currentView) { + return false; + } + + QList viewList; + for(int i = 0; i < m_ki->viewManager()->textViewCount(); ++i) { + KTextEditor::View *view = m_ki->viewManager()->textView(i); + if(currentView == view) { + continue; + } + viewList.push_back(view); + + } + for(QList::iterator it = viewList.begin(); + it != viewList.end(); ++it) { + if (!fileClose(*it)) { + return false; + } + } + return true; } bool Manager::fileCloseAll() { - KTextEditor::View * view = m_ki->viewManager()->currentTextView(); + KTextEditor::View * view = m_ki->viewManager()->currentTextView(); - //assumes one view per doc here - while(m_ki->viewManager()->textViewCount() > 0) { - view = m_ki->viewManager()->textView(0); - if (!fileClose(view->document())) { - return false; - } - } - return true; + //assumes one view per doc here + while(m_ki->viewManager()->textViewCount() > 0) { + view = m_ki->viewManager()->textView(0); + if (!fileClose(view->document())) { + return false; + } + } + return true; } bool Manager::fileClose(const QUrl &url) { - KTextEditor::Document *doc = docFor(url); - if(!doc) { - return true; - } - else { - return fileClose(doc); - } + KTextEditor::Document *doc = docFor(url); + if(!doc) { + return true; + } + else { + return fileClose(doc); + } } bool Manager::fileClose(KTextEditor::View *view) { - // the 'data' property can be set by the view manager - QAction *action = dynamic_cast(QObject::sender()); - if(action) { - QVariant var = action->data(); - if(!view && var.isValid()) { - view = var.value(); - // the 'data' property for the relevant actions is cleared - // inside the view manager - } - } - if(!view) { - view = m_ki->viewManager()->currentTextView(); - } - if(!view) { - return false; - } - return fileClose(view->document()); + // the 'data' property can be set by the view manager + QAction *action = dynamic_cast(QObject::sender()); + if(action) { + QVariant var = action->data(); + if(!view && var.isValid()) { + view = var.value(); + // the 'data' property for the relevant actions is cleared + // inside the view manager + } + } + if(!view) { + view = m_ki->viewManager()->currentTextView(); + } + if(!view) { + return false; + } + return fileClose(view->document()); } bool Manager::fileClose(KTextEditor::Document *doc /* = 0L*/, bool closingproject /*= false*/) { - KILE_DEBUG_MAIN << "==Kile::fileClose=========================="; - - if(!doc) { - doc = m_ki->activeTextDocument(); - } - - if(!doc) { - return true; - } - - //FIXME: remove from docinfo map, remove from dirwatch - KILE_DEBUG_MAIN << "doc->url().toLocalFile()=" << doc->url().toLocalFile(); - - const QUrl url = doc->url(); - - TextInfo *docinfo= textInfoFor(doc); - if(!docinfo) { - qWarning() << "no DOCINFO for " << url.url(); - return true; - } - bool inProject = false; - QList items = itemsFor(docinfo); - for(QList::iterator it = items.begin(); it != items.end(); ++it) { - KileProjectItem *item = *it; - - //FIXME: refactor here - if(item && doc) { - storeProjectItem(item, doc); - inProject = true; - } - } - - if(!inProject) { - KILE_DEBUG_MAIN << "not in project"; - saveDocumentAndViewSettings(docinfo); - } - - if(doc->closeUrl()) { - // docinfo may have been recreated from 'Untitled' doc to a named doc - if(url.isEmpty()) { - docinfo= textInfoFor(doc); - } - - if(KileConfig::cleanUpAfterClose()) { - cleanUpTempFiles(url, true); // yes we pass here url and not docinfo->url() - } - - //FIXME: use signal/slot - if( doc->views().count() > 0){ - m_ki->viewManager()->removeView(doc->views().first()); - } - //remove the decorations - - trashDoc(docinfo, doc); - m_ki->structureWidget()->clean(docinfo); - removeTextDocumentInfo(docinfo, closingproject); - - emit removeFromProjectView(url); - emit updateModeStatus(); - } - else { - return false; - } - - return true; + KILE_DEBUG_MAIN << "==Kile::fileClose=========================="; + + if(!doc) { + doc = m_ki->activeTextDocument(); + } + + if(!doc) { + return true; + } + + //FIXME: remove from docinfo map, remove from dirwatch + KILE_DEBUG_MAIN << "doc->url().toLocalFile()=" << doc->url().toLocalFile(); + + const QUrl url = doc->url(); + + TextInfo *docinfo= textInfoFor(doc); + if(!docinfo) { + qWarning() << "no DOCINFO for " << url.url(); + return true; + } + bool inProject = false; + QList items = itemsFor(docinfo); + for(QList::iterator it = items.begin(); it != items.end(); ++it) { + KileProjectItem *item = *it; + + //FIXME: refactor here + if(item && doc) { + storeProjectItem(item, doc); + inProject = true; + } + } + + if(!inProject) { + KILE_DEBUG_MAIN << "not in project"; + saveDocumentAndViewSettings(docinfo); + } + + if(doc->closeUrl()) { + // docinfo may have been recreated from 'Untitled' doc to a named doc + if(url.isEmpty()) { + docinfo= textInfoFor(doc); + } + + if(KileConfig::cleanUpAfterClose()) { + cleanUpTempFiles(url, true); // yes we pass here url and not docinfo->url() + } + + //FIXME: use signal/slot + if( doc->views().count() > 0) { + m_ki->viewManager()->removeView(doc->views().first()); + } + //remove the decorations + + trashDoc(docinfo, doc); + m_ki->structureWidget()->clean(docinfo); + removeTextDocumentInfo(docinfo, closingproject); + + emit removeFromProjectView(url); + emit updateModeStatus(); + } + else { + return false; + } + + return true; } void Manager::buildProjectTree(const QUrl &url) { - KileProject * project = projectFor(url); + KileProject * project = projectFor(url); - if (project) { - buildProjectTree(project); - } + if (project) { + buildProjectTree(project); + } } void Manager::buildProjectTree(KileProject *project) { - if(!project) { - project = activeProject(); - } + if(!project) { + project = activeProject(); + } - if(!project) { - project = selectProject(i18n("Refresh Project Tree")); - } + if(!project) { + project = selectProject(i18n("Refresh Project Tree")); + } - if (project) { - //TODO: update structure for all docs - project->buildProjectTree(); - } - else if (m_projects.count() == 0) { - KMessageBox::error(m_ki->mainWindow(), i18n("The current document is not associated to a project. Please activate a document that is associated to the project you want to build the tree for, then choose Refresh Project Tree again."),i18n( "Could Not Refresh Project Tree")); - } + if (project) { + //TODO: update structure for all docs + project->buildProjectTree(); + } + else if (m_projects.count() == 0) { + KMessageBox::error(m_ki->mainWindow(), i18n("The current document is not associated to a project. Please activate a document that is associated to the project you want to build the tree for, then choose Refresh Project Tree again."),i18n( "Could Not Refresh Project Tree")); + } } void Manager::projectNew() { - KileNewProjectDialog *dlg = new KileNewProjectDialog(m_ki->templateManager(), m_ki->extensions(), m_ki->mainWindow()); + KileNewProjectDialog *dlg = new KileNewProjectDialog(m_ki->templateManager(), m_ki->extensions(), m_ki->mainWindow()); - if (dlg->exec()) - { - TextInfo *newTextInfo = Q_NULLPTR; + if (dlg->exec()) + { + TextInfo *newTextInfo = Q_NULLPTR; - KileProject *project = dlg->project(); + KileProject *project = dlg->project(); - //add the project file to the project - KileProjectItem *item = new KileProjectItem(project, project->url()); - createTextInfoForProjectItem(item); - item->setOpenState(false); - projectOpenItem(item); + //add the project file to the project + KileProjectItem *item = new KileProjectItem(project, project->url()); + createTextInfoForProjectItem(item); + item->setOpenState(false); + projectOpenItem(item); - if(dlg->createNewFile()) { - m_currentlyOpeningFile = true; // don't let live preview interfere + if(dlg->createNewFile()) { + m_currentlyOpeningFile = true; // don't let live preview interfere - QString filename = dlg->file(); + QString filename = dlg->file(); - //create the new document and fill it with the template - KTextEditor::View *view = loadTemplate(dlg->getSelection()); + //create the new document and fill it with the template + KTextEditor::View *view = loadTemplate(dlg->getSelection()); - if(view) { - //derive the URL from the base url of the project - QUrl url = project->baseURL(); - url = url.adjusted(QUrl::StripTrailingSlash); - url.setPath(url.path() + '/' + filename); + if(view) { + //derive the URL from the base url of the project + QUrl url = project->baseURL(); + url = url.adjusted(QUrl::StripTrailingSlash); + url.setPath(url.path() + '/' + filename); - newTextInfo = textInfoFor(view->document()); + newTextInfo = textInfoFor(view->document()); - //save the new file - //FIXME: this needs proper error handling - view->document()->saveAs(url); - emit(documentModificationStatusChanged(view->document(), - false, KTextEditor::ModificationInterface::OnDiskUnmodified)); + //save the new file + //FIXME: this needs proper error handling + view->document()->saveAs(url); + emit(documentModificationStatusChanged(view->document(), + false, KTextEditor::ModificationInterface::OnDiskUnmodified)); - //add this file to the project - item = new KileProjectItem(project, url); - item->setInfo(newTextInfo); + //add this file to the project + item = new KileProjectItem(project, url); + item->setInfo(newTextInfo); - //docinfo->updateStruct(m_kwStructure->level()); - emit(updateStructure(false, newTextInfo)); - } + //docinfo->updateStruct(m_kwStructure->level()); + emit(updateStructure(false, newTextInfo)); + } - m_currentlyOpeningFile = false; - } + m_currentlyOpeningFile = false; + } - project->buildProjectTree(); - project->save(); - addProject(project); + project->buildProjectTree(); + project->save(); + addProject(project); - emit(updateModeStatus()); - emit(addToRecentProjects(project->url())); + emit(updateModeStatus()); + emit(addToRecentProjects(project->url())); - if(newTextInfo) { - emit documentOpened(newTextInfo); - } - } + if(newTextInfo) { + emit documentOpened(newTextInfo); + } + } } void Manager::addProject(KileProject *project) { - KILE_DEBUG_MAIN << "==void Manager::addProject(const KileProject *project)=========="; - m_projects.append(project); - KILE_DEBUG_MAIN << "\tnow " << m_projects.count() << " projects"; - emit addToProjectView(project); - connect(project, SIGNAL(projectTreeChanged(const KileProject *)), this, SIGNAL(projectTreeChanged(const KileProject *))); + KILE_DEBUG_MAIN << "==void Manager::addProject(const KileProject *project)=========="; + m_projects.append(project); + KILE_DEBUG_MAIN << "\tnow " << m_projects.count() << " projects"; + emit addToProjectView(project); + connect(project, SIGNAL(projectTreeChanged(const KileProject *)), this, SIGNAL(projectTreeChanged(const KileProject *))); } KileProject* Manager::selectProject(const QString& caption) { - QStringList list; - for(QList::iterator it = m_projects.begin(); it != m_projects.end(); ++it) { - list.append((*it)->name()); - } - - KileProject *project = Q_NULLPTR; - QString name; - if (list.count() > 1) { - KileListSelector *dlg = new KileListSelector(list, caption, i18n("Select Project"), true, m_ki->mainWindow()); - if (dlg->exec()) { - if(!dlg->hasSelection()) { - return Q_NULLPTR; - } - name = dlg->selectedItems().first(); - } - delete dlg; - } - else if (list.count() == 0) { - return Q_NULLPTR; - } - else { - name = m_projects.first()->name(); - } - - project = projectFor(name); - - return project; + QStringList list; + for(QList::iterator it = m_projects.begin(); it != m_projects.end(); ++it) { + list.append((*it)->name()); + } + + KileProject *project = Q_NULLPTR; + QString name; + if (list.count() > 1) { + KileListSelector *dlg = new KileListSelector(list, caption, i18n("Select Project"), true, m_ki->mainWindow()); + if (dlg->exec()) { + if(!dlg->hasSelection()) { + return Q_NULLPTR; + } + name = dlg->selectedItems().first(); + } + delete dlg; + } + else if (list.count() == 0) { + return Q_NULLPTR; + } + else { + name = m_projects.first()->name(); + } + + project = projectFor(name); + + return project; } void Manager::addToProject(const QUrl &url) { - KILE_DEBUG_MAIN << "===Kile::addToProject(const QUrl &url =" << url.url() << ")"; + KILE_DEBUG_MAIN << "===Kile::addToProject(const QUrl &url =" << url.url() << ")"; - KileProject *project = selectProject(i18n("Add to Project")); + KileProject *project = selectProject(i18n("Add to Project")); - if (project) { - addToProject(project, url); - } + if (project) { + addToProject(project, url); + } } void Manager::addToProject(KileProject* project, const QUrl &url) { - const QUrl realurl = symlinkFreeURL(url); - QFileInfo fi(realurl.toLocalFile()); - - if (project->contains(realurl)) { - m_ki->errorHandler()->printMessage(KileTool::Info, - i18n("The file %1 is already member of the project %2", realurl.fileName(), project->name()), - i18n("Add to Project")); - return; - } - else if(!fi.exists() || !fi.isReadable()) - { - m_ki->errorHandler()->printMessage(KileTool::Info, - i18n("The file %1 can not be added because it does not exist or is not readable", realurl.fileName()), - i18n("Add to Project")); - return; - } - - KileProjectItem *item = new KileProjectItem(project, realurl); - createTextInfoForProjectItem(item); - item->setOpenState(m_ki->isOpen(realurl)); - projectOpenItem(item); - emit addToProjectView(item); - buildProjectTree(project); + const QUrl realurl = symlinkFreeURL(url); + QFileInfo fi(realurl.toLocalFile()); + + if (project->contains(realurl)) { + m_ki->errorHandler()->printMessage(KileTool::Info, + i18n("The file %1 is already member of the project %2", realurl.fileName(), project->name()), + i18n("Add to Project")); + return; + } + else if(!fi.exists() || !fi.isReadable()) + { + m_ki->errorHandler()->printMessage(KileTool::Info, + i18n("The file %1 can not be added because it does not exist or is not readable", realurl.fileName()), + i18n("Add to Project")); + return; + } + + KileProjectItem *item = new KileProjectItem(project, realurl); + createTextInfoForProjectItem(item); + item->setOpenState(m_ki->isOpen(realurl)); + projectOpenItem(item); + emit addToProjectView(item); + buildProjectTree(project); } void Manager::removeFromProject(KileProjectItem *item) { - if (item && item->project()) { - KILE_DEBUG_MAIN << "\tprojecturl = " << item->project()->url().toLocalFile() << ", url = " << item->url().toLocalFile(); + if (item && item->project()) { + KILE_DEBUG_MAIN << "\tprojecturl = " << item->project()->url().toLocalFile() << ", url = " << item->url().toLocalFile(); - if (item->project()->url() == item->url()) { - KMessageBox::error(m_ki->mainWindow(), i18n("This file is the project file, which holds all the information about your project. As such, it cannot be removed from the project."), i18n("Cannot Remove File From Project")); - return; - } + if (item->project()->url() == item->url()) { + KMessageBox::error(m_ki->mainWindow(), i18n("This file is the project file, which holds all the information about your project. As such, it cannot be removed from the project."), i18n("Cannot Remove File From Project")); + return; + } - emit removeItemFromProjectView(item, m_ki->isOpen(item->url())); + emit removeItemFromProjectView(item, m_ki->isOpen(item->url())); - KileProject *project = item->project(); - project->remove(item); + KileProject *project = item->project(); + project->remove(item); - // update undefined references in all project files - updateProjectReferences(project); - project->buildProjectTree(); - } + // update undefined references in all project files + updateProjectReferences(project); + project->buildProjectTree(); + } } // WARNING: 'item' must have been set up with a TextInfo* object already void Manager::projectOpenItem(KileProjectItem *item, bool openProjectItemViews) { - KILE_DEBUG_MAIN << "==Kile::projectOpenItem=========================="; - KILE_DEBUG_MAIN << "\titem:" << item->url().toLocalFile(); - - if (m_ki->isOpen(item->url())) { //remove item from projectview (this file was opened before as a normal file) - emit removeFromProjectView(item->url()); - } - - KileDocument::TextInfo* itemInfo = item->getInfo(); - Q_ASSERT(itemInfo); - - if(item->isOpen()) { - KTextEditor::View *view = loadItem(m_ki->extensions()->determineDocumentType(item->url()), item, QString(), openProjectItemViews); - if (view) { - item->loadDocumentAndViewSettings(); - } - // make sure that the item has been parsed, even if it isn't shown; - // this is necessary to identify the correct LaTeX root document (bug 233667); - m_ki->structureWidget()->update(itemInfo, true); - } - else if(item->type() == KileProjectItem::Source || item->type() == KileProjectItem::Package || item->type() == KileProjectItem::Bibliography) { - // 'item' is not shown (and it is either a LaTeX source file or package), i.e. its - // contents won't be loaded into a KTextEditor::Document; so, we have to do it: - // we are loading the contents of the project item into the docinfo - // for a moment - itemInfo->setDocumentContents(loadTextURLContents(item->url(), item->encoding())); - // in order to pass the contents to the parser - m_ki->structureWidget()->update(itemInfo, true); - // now we don't need the contents anymore - itemInfo->setDocumentContents(QStringList()); - } + KILE_DEBUG_MAIN << "==Kile::projectOpenItem=========================="; + KILE_DEBUG_MAIN << "\titem:" << item->url().toLocalFile(); + + if (m_ki->isOpen(item->url())) { //remove item from projectview (this file was opened before as a normal file) + emit removeFromProjectView(item->url()); + } + + KileDocument::TextInfo* itemInfo = item->getInfo(); + Q_ASSERT(itemInfo); + + if(item->isOpen()) { + KTextEditor::View *view = loadItem(m_ki->extensions()->determineDocumentType(item->url()), item, QString(), openProjectItemViews); + if (view) { + item->loadDocumentAndViewSettings(); + } + // make sure that the item has been parsed, even if it isn't shown; + // this is necessary to identify the correct LaTeX root document (bug 233667); + m_ki->structureWidget()->update(itemInfo, true); + } + else if(item->type() == KileProjectItem::Source || item->type() == KileProjectItem::Package || item->type() == KileProjectItem::Bibliography) { + // 'item' is not shown (and it is either a LaTeX source file or package), i.e. its + // contents won't be loaded into a KTextEditor::Document; so, we have to do it: + // we are loading the contents of the project item into the docinfo + // for a moment + itemInfo->setDocumentContents(loadTextURLContents(item->url(), item->encoding())); + // in order to pass the contents to the parser + m_ki->structureWidget()->update(itemInfo, true); + // now we don't need the contents anymore + itemInfo->setDocumentContents(QStringList()); + } } void Manager::createTextInfoForProjectItem(KileProjectItem *item) { - item->setInfo(createTextDocumentInfo(m_ki->extensions()->determineDocumentType(item->url()), - item->url(), item->project()->baseURL())); + item->setInfo(createTextDocumentInfo(m_ki->extensions()->determineDocumentType(item->url()), + item->url(), item->project()->baseURL())); } void Manager::projectOpen(const QUrl &url, int step, int max, bool openProjectItemViews) { - KILE_DEBUG_MAIN << "==Kile::projectOpen=========================="; - KILE_DEBUG_MAIN << "\tfilename: " << url.fileName(); - - const QUrl realurl = symlinkFreeURL(url); - - if(m_ki->projectIsOpen(realurl)) { - if(m_progressDialog) { - m_progressDialog->hide(); - } - - KMessageBox::information(m_ki->mainWindow(), i18n("

The project \"%1\" is already open.

" - "

If you wanted to reload the project, close the project before you re-open it.

", url.fileName()), - i18n("Project Already Open")); - return; - } - - QFileInfo fi(realurl.toLocalFile()); - if(!fi.isReadable()) { - if(m_progressDialog) { - m_progressDialog->hide(); - } - - if (KMessageBox::warningYesNo(m_ki->mainWindow(), i18n("

The project file for the project \"%1\" does not exist or it is not readable.

" - "

Do you want to remove this project from the recent projects list?

", - url.fileName()), - i18n("Could Not Open Project")) == KMessageBox::Yes) { - emit(removeFromRecentProjects(realurl)); - } - return; - } - - if(!m_progressDialog) { - createProgressDialog(); - } - - KileProject *kp = new KileProject(realurl, m_ki->extensions()); - - if(!kp->appearsToBeValidProjectFile()) { - if(m_progressDialog) { - m_progressDialog->hide(); - } - - KMessageBox::sorry(m_ki->mainWindow(), i18n("

The file \"%1\" cannot be opened as it does not appear to be a project file.

", - url.fileName()), - i18n("Impossible to Open Project File")); - delete kp; - return; - } - - if(kp->getProjectFileVersion() > KILE_PROJECTFILE_VERSION) { - if(m_progressDialog) { - m_progressDialog->hide(); - } - - KMessageBox::sorry(m_ki->mainWindow(), i18n("

The project \"%1\" cannot be opened as it was created
by a newer version of Kile.

", - url.fileName()), - i18n("Impossible to Open Project")); - delete kp; - return; - } - - if(!kp->isOfCurrentVersion()) { - if(m_progressDialog) { - m_progressDialog->hide(); - } - - if(KMessageBox::questionYesNo(m_ki->mainWindow(), i18n("

The project file \"%1\" was created by a previous version of Kile.
" - "It needs to be updated before it can be opened.

" - "

Do you want to update it?

", url.fileName()), - i18n("Project File Needs to be Updated")) == KMessageBox::No) { - delete kp; - return; - } - - if(!kp->migrateProjectFileToCurrentVersion()) { - if (KMessageBox::warningYesNo(m_ki->mainWindow(), i18n("

The project file \"%1\" could be not updated.

" - "

Do you want to remove this project from the recent projects list?

", url.fileName()), - i18n("Could Not Update Project File")) == KMessageBox::Yes) { - emit(removeFromRecentProjects(realurl)); - } - delete kp; - return; - } - } - - m_progressDialog->show(); - - kp->load(); - - if(kp->isInvalid()) { - if(m_progressDialog) { - m_progressDialog->hide(); - } - delete kp; - return; - } - - emit(addToRecentProjects(realurl)); - - QList list = kp->items(); - int project_steps = list.count(); - m_progressDialog->setMaximum(project_steps * max); - project_steps *= step; - m_progressDialog->setValue(project_steps); - - // open the project files in the correct order - QVector givenPositionVector(list.count(), Q_NULLPTR); - QList notCorrectlyOrderedList; - for(QList::iterator it = list.begin(); it != list.end(); ++it) { - KileProjectItem *item = *it; - int order = item->order(); - - if(order >= 0 && order >= list.count()) { - order = -1; - } - if(!item->isOpen() || order < 0 || givenPositionVector[order] != Q_NULLPTR) { - notCorrectlyOrderedList.push_back(item); - } - else { - givenPositionVector[order] = item; - } - } - - QList orderedList; - for(int i = 0; i < givenPositionVector.size(); ++i) { - KileProjectItem *item = givenPositionVector[i]; - if(item) { - orderedList.push_back(item); - } - } - for(QList::iterator i = notCorrectlyOrderedList.begin(); i != notCorrectlyOrderedList.end(); ++i) { - orderedList.push_back(*i); - } - - addProject(kp); - - // for the parsing to work correctly, all ProjectItems need to have TextInfo* objects, but - // the URL of 'item' might already be associated with a TextInfo* object; for example, through - // a stand-alone document currently being open already, or through a project item that belongs to - // a different project - // => 'createTextDocumentInfo' will take care of that situation as well - for (QList::iterator i = orderedList.begin(); i != orderedList.end(); ++i) { - createTextInfoForProjectItem(*i); - } - - unsigned int counter = 1; - for (QList::iterator i = orderedList.begin(); i != orderedList.end(); ++i) { - projectOpenItem(*i, openProjectItemViews); - m_progressDialog->setValue(counter + project_steps); - qApp->processEvents(); - ++counter; - } - - kp->buildProjectTree(); - - emit(updateStructure(false, Q_NULLPTR)); - emit(updateModeStatus()); - - // update undefined references in all project files - updateProjectReferences(kp); - - m_ki->viewManager()->switchToTextView(kp->lastDocument()); - - emit(projectOpened(kp)); + KILE_DEBUG_MAIN << "==Kile::projectOpen=========================="; + KILE_DEBUG_MAIN << "\tfilename: " << url.fileName(); + + const QUrl realurl = symlinkFreeURL(url); + + if(m_ki->projectIsOpen(realurl)) { + if(m_progressDialog) { + m_progressDialog->hide(); + } + + KMessageBox::information(m_ki->mainWindow(), i18n("

The project \"%1\" is already open.

" + "

If you wanted to reload the project, close the project before you re-open it.

", url.fileName()), + i18n("Project Already Open")); + return; + } + + QFileInfo fi(realurl.toLocalFile()); + if(!fi.isReadable()) { + if(m_progressDialog) { + m_progressDialog->hide(); + } + + if (KMessageBox::warningYesNo(m_ki->mainWindow(), i18n("

The project file for the project \"%1\" does not exist or it is not readable.

" + "

Do you want to remove this project from the recent projects list?

", + url.fileName()), + i18n("Could Not Open Project")) == KMessageBox::Yes) { + emit(removeFromRecentProjects(realurl)); + } + return; + } + + if(!m_progressDialog) { + createProgressDialog(); + } + + KileProject *kp = new KileProject(realurl, m_ki->extensions()); + + if(!kp->appearsToBeValidProjectFile()) { + if(m_progressDialog) { + m_progressDialog->hide(); + } + + KMessageBox::sorry(m_ki->mainWindow(), i18n("

The file \"%1\" cannot be opened as it does not appear to be a project file.

", + url.fileName()), + i18n("Impossible to Open Project File")); + delete kp; + return; + } + + if(kp->getProjectFileVersion() > KILE_PROJECTFILE_VERSION) { + if(m_progressDialog) { + m_progressDialog->hide(); + } + + KMessageBox::sorry(m_ki->mainWindow(), i18n("

The project \"%1\" cannot be opened as it was created
by a newer version of Kile.

", + url.fileName()), + i18n("Impossible to Open Project")); + delete kp; + return; + } + + if(!kp->isOfCurrentVersion()) { + if(m_progressDialog) { + m_progressDialog->hide(); + } + + if(KMessageBox::questionYesNo(m_ki->mainWindow(), i18n("

The project file \"%1\" was created by a previous version of Kile.
" + "It needs to be updated before it can be opened.

" + "

Do you want to update it?

", url.fileName()), + i18n("Project File Needs to be Updated")) == KMessageBox::No) { + delete kp; + return; + } + + if(!kp->migrateProjectFileToCurrentVersion()) { + if (KMessageBox::warningYesNo(m_ki->mainWindow(), i18n("

The project file \"%1\" could be not updated.

" + "

Do you want to remove this project from the recent projects list?

", url.fileName()), + i18n("Could Not Update Project File")) == KMessageBox::Yes) { + emit(removeFromRecentProjects(realurl)); + } + delete kp; + return; + } + } + + m_progressDialog->show(); + + kp->load(); + + if(kp->isInvalid()) { + if(m_progressDialog) { + m_progressDialog->hide(); + } + delete kp; + return; + } + + emit(addToRecentProjects(realurl)); + + QList list = kp->items(); + int project_steps = list.count(); + m_progressDialog->setMaximum(project_steps * max); + project_steps *= step; + m_progressDialog->setValue(project_steps); + + // open the project files in the correct order + QVector givenPositionVector(list.count(), Q_NULLPTR); + QList notCorrectlyOrderedList; + for(QList::iterator it = list.begin(); it != list.end(); ++it) { + KileProjectItem *item = *it; + int order = item->order(); + + if(order >= 0 && order >= list.count()) { + order = -1; + } + if(!item->isOpen() || order < 0 || givenPositionVector[order] != Q_NULLPTR) { + notCorrectlyOrderedList.push_back(item); + } + else { + givenPositionVector[order] = item; + } + } + + QList orderedList; + for(int i = 0; i < givenPositionVector.size(); ++i) { + KileProjectItem *item = givenPositionVector[i]; + if(item) { + orderedList.push_back(item); + } + } + for(QList::iterator i = notCorrectlyOrderedList.begin(); i != notCorrectlyOrderedList.end(); ++i) { + orderedList.push_back(*i); + } + + addProject(kp); + + // for the parsing to work correctly, all ProjectItems need to have TextInfo* objects, but + // the URL of 'item' might already be associated with a TextInfo* object; for example, through + // a stand-alone document currently being open already, or through a project item that belongs to + // a different project + // => 'createTextDocumentInfo' will take care of that situation as well + for (QList::iterator i = orderedList.begin(); i != orderedList.end(); ++i) { + createTextInfoForProjectItem(*i); + } + + unsigned int counter = 1; + for (QList::iterator i = orderedList.begin(); i != orderedList.end(); ++i) { + projectOpenItem(*i, openProjectItemViews); + m_progressDialog->setValue(counter + project_steps); + qApp->processEvents(); + ++counter; + } + + kp->buildProjectTree(); + + emit(updateStructure(false, Q_NULLPTR)); + emit(updateModeStatus()); + + // update undefined references in all project files + updateProjectReferences(kp); + + m_ki->viewManager()->switchToTextView(kp->lastDocument()); + + emit(projectOpened(kp)); } // as all labels are gathered in the project, we can check for unsolved references void Manager::updateProjectReferences(KileProject *project) { - QList list = project->items(); - for(QList::iterator it = list.begin(); it != list.end(); ++it) { - emit(updateReferences((*it)->getInfo())); - } + QList list = project->items(); + for(QList::iterator it = list.begin(); it != list.end(); ++it) { + emit(updateReferences((*it)->getInfo())); + } } void Manager::projectOpen() { - KILE_DEBUG_MAIN << "==Kile::projectOpen=========================="; - QUrl url = QFileDialog::getOpenFileUrl(m_ki->mainWindow(), i18n("Open Project"), - QUrl::fromLocalFile(KileConfig::defaultProjectLocation()), - m_ki->extensions()->fileFilterQtStyle(false, {KileDocument::Extensions::KILE_PROJECT})); + KILE_DEBUG_MAIN << "==Kile::projectOpen=========================="; + QUrl url = QFileDialog::getOpenFileUrl(m_ki->mainWindow(), i18n("Open Project"), + QUrl::fromLocalFile(KileConfig::defaultProjectLocation()), + m_ki->extensions()->fileFilterQtStyle(false, {KileDocument::Extensions::KILE_PROJECT})); - if(!url.isEmpty()) { - projectOpen(url); - } + if(!url.isEmpty()) { + projectOpen(url); + } } void Manager::projectSave(KileProject *project /* = 0 */) { - KILE_DEBUG_MAIN << "==Kile::projectSave=========================="; - if (!project) { - //find the project that corresponds to the active doc - project= activeProject(); - } - - if(!project) { - project = selectProject(i18n("Save Project")); - } - - if(project) { - QList list = project->items(); - KTextEditor::Document *doc = Q_NULLPTR; - KileProjectItem *item = Q_NULLPTR; - TextInfo *docinfo = Q_NULLPTR; - - // determine the order in which the project items are opened - QVector viewPositionVector(m_ki->viewManager()->getTabCount(), Q_NULLPTR); - for(QList::iterator i = list.begin(); i != list.end(); ++i) { - docinfo = (*i)->getInfo(); - if(docinfo) { - KTextEditor::View *view = m_ki->viewManager()->textView(docinfo); - if(view) { - int position = m_ki->viewManager()->tabIndexOf(view); - if(position >= 0 && position < viewPositionVector.size()) { - viewPositionVector[position] = *i; - } - } - } - } - int position = 0; - for(int i = 0; i < viewPositionVector.size(); ++i) { - if(viewPositionVector[i] != Q_NULLPTR) { - viewPositionVector[i]->setOrder(position); - ++position; - } - } - - //update the open-state of the items - for (QList::iterator i = list.begin(); i != list.end(); ++i) { - item = *i; - KILE_DEBUG_MAIN << "\tsetOpenState(" << (*i)->url().toLocalFile() << ") to " << m_ki->isOpen(item->url()); - item->setOpenState(m_ki->isOpen(item->url())); - docinfo = item->getInfo(); - - if(docinfo) { - doc = docinfo->getDoc(); - } - if(doc) { - storeProjectItem(item, doc); - } - - doc = Q_NULLPTR; - docinfo = Q_NULLPTR; - } - - project->save(); - } - else { - KMessageBox::error(m_ki->mainWindow(), i18n("The current document is not associated to a project. Please activate a document that is associated to the project you want to save, then choose Save Project again."),i18n( "Could Determine Active Project")); - } + KILE_DEBUG_MAIN << "==Kile::projectSave=========================="; + if (!project) { + //find the project that corresponds to the active doc + project= activeProject(); + } + + if(!project) { + project = selectProject(i18n("Save Project")); + } + + if(project) { + QList list = project->items(); + KTextEditor::Document *doc = Q_NULLPTR; + KileProjectItem *item = Q_NULLPTR; + TextInfo *docinfo = Q_NULLPTR; + + // determine the order in which the project items are opened + QVector viewPositionVector(m_ki->viewManager()->getTabCount(), Q_NULLPTR); + for(QList::iterator i = list.begin(); i != list.end(); ++i) { + docinfo = (*i)->getInfo(); + if(docinfo) { + KTextEditor::View *view = m_ki->viewManager()->textView(docinfo); + if(view) { + int position = m_ki->viewManager()->tabIndexOf(view); + if(position >= 0 && position < viewPositionVector.size()) { + viewPositionVector[position] = *i; + } + } + } + } + int position = 0; + for(int i = 0; i < viewPositionVector.size(); ++i) { + if(viewPositionVector[i] != Q_NULLPTR) { + viewPositionVector[i]->setOrder(position); + ++position; + } + } + + //update the open-state of the items + for (QList::iterator i = list.begin(); i != list.end(); ++i) { + item = *i; + KILE_DEBUG_MAIN << "\tsetOpenState(" << (*i)->url().toLocalFile() << ") to " << m_ki->isOpen(item->url()); + item->setOpenState(m_ki->isOpen(item->url())); + docinfo = item->getInfo(); + + if(docinfo) { + doc = docinfo->getDoc(); + } + if(doc) { + storeProjectItem(item, doc); + } + + doc = Q_NULLPTR; + docinfo = Q_NULLPTR; + } + + project->save(); + } + else { + KMessageBox::error(m_ki->mainWindow(), i18n("The current document is not associated to a project. Please activate a document that is associated to the project you want to save, then choose Save Project again."),i18n( "Could Determine Active Project")); + } } void Manager::projectAddFiles(const QUrl &url) { - KileProject *project = projectFor(url); + KileProject *project = projectFor(url); - if (project) { - projectAddFiles(project,url); - } + if (project) { + projectAddFiles(project,url); + } } void Manager::projectAddFiles(KileProject *project,const QUrl &fileUrl) { - KILE_DEBUG_MAIN << "==Kile::projectAddFiles()=========================="; - if(project == 0) { - project = activeProject(); - } - - if(project == 0) { - project = selectProject(i18n("Add Files to Project")); - } - - if (project) { - QString currentDir; - if(fileUrl.isEmpty()) { - currentDir = QFileInfo(project->url().path()).dir().dirName(); - } - else { - currentDir = fileUrl.adjusted(QUrl::RemoveFilename | QUrl::StripTrailingSlash).path(); - } - - KILE_DEBUG_MAIN << "currentDir is " << currentDir; - QFileDialog *dlg = new QFileDialog(m_ki->mainWindow(), i18n("Add Files"), currentDir, m_ki->extensions()->fileFilterQtStyle(true, {})); - dlg->setModal(true); - dlg->setFileMode(QFileDialog::ExistingFiles); - dlg->setLabelText(QFileDialog::Accept, i18n("Add")); - - if(dlg->exec()) { - QList urls = dlg->selectedUrls(); - for(int i=0; i < urls.count(); ++i) { - addToProject(project, urls[i]); - } - // update undefined references in all project files - updateProjectReferences(project); - } - delete dlg; - - //open them - } - else if (m_projects.count() == 0) { - KMessageBox::error(m_ki->mainWindow(), i18n("There are no projects opened. Please open the project you want to add files to, then choose Add Files again."),i18n( "Could Not Determine Active Project")); - } + KILE_DEBUG_MAIN << "==Kile::projectAddFiles()=========================="; + if(project == 0) { + project = activeProject(); + } + + if(project == 0) { + project = selectProject(i18n("Add Files to Project")); + } + + if (project) { + QString currentDir; + if(fileUrl.isEmpty()) { + currentDir = QFileInfo(project->url().path()).dir().dirName(); + } + else { + currentDir = fileUrl.adjusted(QUrl::RemoveFilename | QUrl::StripTrailingSlash).path(); + } + + KILE_DEBUG_MAIN << "currentDir is " << currentDir; + QFileDialog *dlg = new QFileDialog(m_ki->mainWindow(), i18n("Add Files"), currentDir, m_ki->extensions()->fileFilterQtStyle(true, {})); + dlg->setModal(true); + dlg->setFileMode(QFileDialog::ExistingFiles); + dlg->setLabelText(QFileDialog::Accept, i18n("Add")); + + if(dlg->exec()) { + QList urls = dlg->selectedUrls(); + for(int i=0; i < urls.count(); ++i) { + addToProject(project, urls[i]); + } + // update undefined references in all project files + updateProjectReferences(project); + } + delete dlg; + + //open them + } + else if (m_projects.count() == 0) { + KMessageBox::error(m_ki->mainWindow(), i18n("There are no projects opened. Please open the project you want to add files to, then choose Add Files again."),i18n( "Could Not Determine Active Project")); + } } void Manager::toggleArchive(KileProjectItem *item) { - item->setArchive(!item->archive()); + item->setArchive(!item->archive()); } void Manager::projectOptions(const QUrl &url) { - KileProject *project = projectFor(url); + KileProject *project = projectFor(url); - if (project) { - projectOptions(project); - } + if (project) { + projectOptions(project); + } } void Manager::projectOptions(KileProject *project /* = 0*/) { - KILE_DEBUG_MAIN << "==Kile::projectOptions=========================="; - if(!project) { - project = activeProject(); - } + KILE_DEBUG_MAIN << "==Kile::projectOptions=========================="; + if(!project) { + project = activeProject(); + } - if(!project) { - project = selectProject(i18n("Project Options For")); - } + if(!project) { + project = selectProject(i18n("Project Options For")); + } - if (project) { - KILE_DEBUG_MAIN << "\t" << project->name(); - KileProjectOptionsDialog *dlg = new KileProjectOptionsDialog(project, m_ki->extensions(), m_ki->mainWindow()); - dlg->exec(); - } - else if (m_projects.count() == 0) { - KMessageBox::error(m_ki->mainWindow(), i18n("The current document is not associated to a project. Please activate a document that is associated to the project you want to modify, then choose Project Options again."),i18n( "Could Not Determine Active Project")); - } + if (project) { + KILE_DEBUG_MAIN << "\t" << project->name(); + KileProjectOptionsDialog *dlg = new KileProjectOptionsDialog(project, m_ki->extensions(), m_ki->mainWindow()); + dlg->exec(); + } + else if (m_projects.count() == 0) { + KMessageBox::error(m_ki->mainWindow(), i18n("The current document is not associated to a project. Please activate a document that is associated to the project you want to modify, then choose Project Options again."),i18n( "Could Not Determine Active Project")); + } } bool Manager::projectCloseAll() { - KILE_DEBUG_MAIN << "==Kile::projectCloseAll=========================="; + KILE_DEBUG_MAIN << "==Kile::projectCloseAll=========================="; - while(m_projects.size() > 0) { - if(!projectClose(m_projects.first()->url())) { - return false; - } - } + while(m_projects.size() > 0) { + if(!projectClose(m_projects.first()->url())) { + return false; + } + } - return true; + return true; } bool Manager::projectClose(const QUrl &url) { - KILE_DEBUG_MAIN << "==Kile::projectClose=========================="; - KileProject *project = 0; - - if (url.isEmpty()) { - project = activeProject(); - - if (!project) { - project = selectProject(i18n("Close Project")); - } - } - else { - project = projectFor(url); - } - - if(project) { - KILE_DEBUG_MAIN << "\tclosing:" << project->name(); - project->setLastDocument(QUrl::fromLocalFile(m_ki->getName())); - - projectSave(project); - - QList list = project->items(); - - bool close = true; - KTextEditor::Document *doc = Q_NULLPTR; - TextInfo *docinfo = Q_NULLPTR; - for(QList::iterator it = list.begin(); it != list.end(); ++it) { - KileProjectItem *item = *it; - - doc = Q_NULLPTR; - docinfo = item->getInfo(); - if (docinfo) { - doc = docinfo->getDoc(); - } - else { - continue; - } - if (doc) { - KILE_DEBUG_MAIN << "\t\tclosing item " << doc->url().toLocalFile(); - bool r = fileClose(doc, true); - close = close && r; - if (!close) { - break; - } - } - else { - // we still need to delete the TextInfo object - removeTextDocumentInfo(docinfo, true); - } - } - - if (close) { - m_projects.removeAll(project); - emit removeFromProjectView(project); - delete project; - emit(updateModeStatus()); - return true; - } - else - return false; - } - else if (m_projects.count() == 0) - KMessageBox::error(m_ki->mainWindow(), i18n("The current document is not associated to a project. Please activate a document that is associated to the project you want to close, then choose Close Project again."),i18n( "Could Not Close Project")); - - return true; + KILE_DEBUG_MAIN << "==Kile::projectClose=========================="; + KileProject *project = 0; + + if (url.isEmpty()) { + project = activeProject(); + + if (!project) { + project = selectProject(i18n("Close Project")); + } + } + else { + project = projectFor(url); + } + + if(project) { + KILE_DEBUG_MAIN << "\tclosing:" << project->name(); + project->setLastDocument(QUrl::fromLocalFile(m_ki->getName())); + + projectSave(project); + + QList list = project->items(); + + bool close = true; + KTextEditor::Document *doc = Q_NULLPTR; + TextInfo *docinfo = Q_NULLPTR; + for(QList::iterator it = list.begin(); it != list.end(); ++it) { + KileProjectItem *item = *it; + + doc = Q_NULLPTR; + docinfo = item->getInfo(); + if (docinfo) { + doc = docinfo->getDoc(); + } + else { + continue; + } + if (doc) { + KILE_DEBUG_MAIN << "\t\tclosing item " << doc->url().toLocalFile(); + bool r = fileClose(doc, true); + close = close && r; + if (!close) { + break; + } + } + else { + // we still need to delete the TextInfo object + removeTextDocumentInfo(docinfo, true); + } + } + + if (close) { + m_projects.removeAll(project); + emit removeFromProjectView(project); + delete project; + emit(updateModeStatus()); + return true; + } + else + return false; + } + else if (m_projects.count() == 0) + KMessageBox::error(m_ki->mainWindow(), i18n("The current document is not associated to a project. Please activate a document that is associated to the project you want to close, then choose Close Project again."),i18n( "Could Not Close Project")); + + return true; } void Manager::storeProjectItem(KileProjectItem *item, KTextEditor::Document *doc) { - KILE_DEBUG_MAIN << "===Kile::storeProjectItem=============="; - KILE_DEBUG_MAIN << "\titem = " << item << ", doc = " << doc; - item->setEncoding(doc->encoding()); - item->setMode(doc->mode()); - item->setHighlight(doc->highlightingMode()); - item->saveDocumentAndViewSettings(); + KILE_DEBUG_MAIN << "===Kile::storeProjectItem=============="; + KILE_DEBUG_MAIN << "\titem = " << item << ", doc = " << doc; + item->setEncoding(doc->encoding()); + item->setMode(doc->mode()); + item->setHighlight(doc->highlightingMode()); + item->saveDocumentAndViewSettings(); } void Manager::cleanUpTempFiles(const QUrl &url, bool silent) { - KILE_DEBUG_MAIN << "===void Manager::cleanUpTempFiles(const QUrl " << url.toLocalFile() << ", bool " << silent << ")==="; - - if( url.isEmpty() ) - return; - - QStringList extlist; - QFileInfo fi(url.toLocalFile()); - const QStringList templist = KileConfig::cleanUpFileExtensions().split(' '); - const QString fileName = fi.fileName(); - const QString dirPath = fi.absolutePath(); - const QString baseName = fi.completeBaseName(); - - for (int i = 0; i < templist.count(); ++i) { - fi.setFile( dirPath + '/' + baseName + templist[i] ); - if(fi.exists()) { - extlist.append(templist[i]); - } - } - - if(!silent && fileName.isEmpty()) { - return; - } - - if (!silent && extlist.count() > 0) { - KILE_DEBUG_MAIN << "not silent"; - KileDialog::Clean *dialog = new KileDialog::Clean(m_ki->mainWindow(), fileName, extlist); - if (dialog->exec() == QDialog::Accepted) { - extlist = dialog->cleanList(); - } - else { - delete dialog; - return; - } - - delete dialog; - } - - if(extlist.count() == 0) { - m_ki->errorHandler()->printMessage(KileTool::Warning, i18n("Nothing to clean for %1", fileName), - i18n("Clean")); - } - else { - for(int i = 0; i < extlist.count(); ++i) { - QFile file(dirPath + '/' + baseName + extlist[i]); - KILE_DEBUG_MAIN << "About to remove file = " << file.fileName(); - file.remove(); - } - m_ki->errorHandler()->printMessage(KileTool::Info, - i18n("Cleaning %1: %2", fileName, extlist.join(" ")), - i18n("Clean")); - } + KILE_DEBUG_MAIN << "===void Manager::cleanUpTempFiles(const QUrl " << url.toLocalFile() << ", bool " << silent << ")==="; + + if( url.isEmpty() ) + return; + + QStringList extlist; + QFileInfo fi(url.toLocalFile()); + const QStringList templist = KileConfig::cleanUpFileExtensions().split(' '); + const QString fileName = fi.fileName(); + const QString dirPath = fi.absolutePath(); + const QString baseName = fi.completeBaseName(); + + for (int i = 0; i < templist.count(); ++i) { + fi.setFile( dirPath + '/' + baseName + templist[i] ); + if(fi.exists()) { + extlist.append(templist[i]); + } + } + + if(!silent && fileName.isEmpty()) { + return; + } + + if (!silent && extlist.count() > 0) { + KILE_DEBUG_MAIN << "not silent"; + KileDialog::Clean *dialog = new KileDialog::Clean(m_ki->mainWindow(), fileName, extlist); + if (dialog->exec() == QDialog::Accepted) { + extlist = dialog->cleanList(); + } + else { + delete dialog; + return; + } + + delete dialog; + } + + if(extlist.count() == 0) { + m_ki->errorHandler()->printMessage(KileTool::Warning, i18n("Nothing to clean for %1", fileName), + i18n("Clean")); + } + else { + for(int i = 0; i < extlist.count(); ++i) { + QFile file(dirPath + '/' + baseName + extlist[i]); + KILE_DEBUG_MAIN << "About to remove file = " << file.fileName(); + file.remove(); + } + m_ki->errorHandler()->printMessage(KileTool::Info, + i18n("Cleaning %1: %2", fileName, extlist.join(" ")), + i18n("Clean")); + } } void Manager::openDroppedURLs(QDropEvent *e) { - QList urls = e->mimeData()->urls(); - Extensions *extensions = m_ki->extensions(); + QList urls = e->mimeData()->urls(); + Extensions *extensions = m_ki->extensions(); - for(QList::iterator i = urls.begin(); i != urls.end(); ++i) { - QUrl url = *i; - if(extensions->isProjectFile(url)) { - projectOpen(url); - } - else { - fileOpen(url); - } - } + for(QList::iterator i = urls.begin(); i != urls.end(); ++i) { + QUrl url = *i; + if(extensions->isProjectFile(url)) { + projectOpen(url); + } + else { + fileOpen(url); + } + } } void Manager::reloadXMLOnAllDocumentsAndViews() { - for(QList::iterator it = m_textInfoList.begin(); it != m_textInfoList.end(); ++it) { - KTextEditor::Document *doc = (*it)->getDoc(); - // FIXME: 'doc' can be null, for example if it belongs to a project item - // which has been closed, but this should be improved in the sense - // that 'm_textInfoList' should only contain 'TextInfo' objects which - // contain valid pointers to 'KTextEditor::Document' objects. - if(!doc) { - continue; - } - doc->reloadXML(); - QList views = doc->views(); - for(QList::iterator viewIt = views.begin(); viewIt != views.end(); ++viewIt) { - (*viewIt)->reloadXML(); - } - } + for(QList::iterator it = m_textInfoList.begin(); it != m_textInfoList.end(); ++it) { + KTextEditor::Document *doc = (*it)->getDoc(); + // FIXME: 'doc' can be null, for example if it belongs to a project item + // which has been closed, but this should be improved in the sense + // that 'm_textInfoList' should only contain 'TextInfo' objects which + // contain valid pointers to 'KTextEditor::Document' objects. + if(!doc) { + continue; + } + doc->reloadXML(); + QList views = doc->views(); + for(QList::iterator viewIt = views.begin(); viewIt != views.end(); ++viewIt) { + (*viewIt)->reloadXML(); + } + } } void Manager::handleParsingComplete(const QUrl &url, KileParser::ParserOutput* output) { - KILE_DEBUG_MAIN << url << output; - if(!output) { - KILE_DEBUG_MAIN << "NULL output given"; - return; - } - KileDocument::TextInfo *textInfo = textInfoFor(url); - if(!textInfo) { - KileProjectItem* item = itemFor(url); - if(item) { - textInfo = item->getInfo(); - } - if(!textInfo) { - // this can happen for instance when the document is closed - // while the parser is still running - KILE_DEBUG_MAIN << "no TextInfo object found for" << url << "found"; - return; - } - } - textInfo->installParserOutput(output); - m_ki->structureWidget()->updateAfterParsing(textInfo, output->structureViewItems); - delete(output); + KILE_DEBUG_MAIN << url << output; + if(!output) { + KILE_DEBUG_MAIN << "NULL output given"; + return; + } + KileDocument::TextInfo *textInfo = textInfoFor(url); + if(!textInfo) { + KileProjectItem* item = itemFor(url); + if(item) { + textInfo = item->getInfo(); + } + if(!textInfo) { + // this can happen for instance when the document is closed + // while the parser is still running + KILE_DEBUG_MAIN << "no TextInfo object found for" << url << "found"; + return; + } + } + textInfo->installParserOutput(output); + m_ki->structureWidget()->updateAfterParsing(textInfo, output->structureViewItems); + delete(output); } // Show all opened projects and switch to another one, if you want void Manager::projectShow() { - if(m_projects.count() <= 1) { - return; - } - - // select the new project - KileProject *project = selectProject(i18n("Switch Project")); - if(!project || project==activeProject()) { - return; - } - - // get last opened document - const QUrl lastdoc = project->lastDocument(); - KileProjectItem *docitem = (!lastdoc.isEmpty()) ? itemFor(lastdoc, project) : Q_NULLPTR; - - // if not, we search for the first opened tex file of this project - // if no file is opened, we take the first tex file mentioned in the list - KileProjectItem *first_texitem = Q_NULLPTR; - if(!docitem) { - QList list = project->items(); - for(QList::iterator it = list.begin(); it != list.end(); ++it) { - KileProjectItem *item = *it; - - QString itempath = item->path(); - - // called from QAction 'Show projects...': find the first opened - // LaTeX document or, if that fails, any other opened file - QStringList extlist = (m_ki->extensions()->latexDocuments() + ' ' + m_ki->extensions()->latexPackages()).split(' '); - for(QStringList::Iterator it=extlist.begin(); it!=extlist.end(); ++it) { - if(itempath.indexOf( (*it), -(*it).length() ) >= 0) { - if (m_ki->isOpen(item->url())) { - docitem = item; - break; - } - else if(!first_texitem) { - first_texitem = item; - } - } - } - if(docitem) { - break; - } - } - } - - // did we find one opened file or must we take the first entry - if(!docitem) { - if(!first_texitem) { - return; - } - docitem = first_texitem; - } - - // ok, we can switch to another project now - if (m_ki->isOpen(docitem->url())) { - m_ki->viewManager()->switchToTextView(docitem->url()); - } - else { - fileOpen(docitem->url(), docitem->encoding()); - } + if(m_projects.count() <= 1) { + return; + } + + // select the new project + KileProject *project = selectProject(i18n("Switch Project")); + if(!project || project==activeProject()) { + return; + } + + // get last opened document + const QUrl lastdoc = project->lastDocument(); + KileProjectItem *docitem = (!lastdoc.isEmpty()) ? itemFor(lastdoc, project) : Q_NULLPTR; + + // if not, we search for the first opened tex file of this project + // if no file is opened, we take the first tex file mentioned in the list + KileProjectItem *first_texitem = Q_NULLPTR; + if(!docitem) { + QList list = project->items(); + for(QList::iterator it = list.begin(); it != list.end(); ++it) { + KileProjectItem *item = *it; + + QString itempath = item->path(); + + // called from QAction 'Show projects...': find the first opened + // LaTeX document or, if that fails, any other opened file + QStringList extlist = (m_ki->extensions()->latexDocuments() + ' ' + m_ki->extensions()->latexPackages()).split(' '); + for(QStringList::Iterator it=extlist.begin(); it!=extlist.end(); ++it) { + if(itempath.indexOf( (*it), -(*it).length() ) >= 0) { + if (m_ki->isOpen(item->url())) { + docitem = item; + break; + } + else if(!first_texitem) { + first_texitem = item; + } + } + } + if(docitem) { + break; + } + } + } + + // did we find one opened file or must we take the first entry + if(!docitem) { + if(!first_texitem) { + return; + } + docitem = first_texitem; + } + + // ok, we can switch to another project now + if (m_ki->isOpen(docitem->url())) { + m_ki->viewManager()->switchToTextView(docitem->url()); + } + else { + fileOpen(docitem->url(), docitem->encoding()); + } } void Manager::projectRemoveFiles() { - QList itemsList = selectProjectFileItems(i18n("Select Files to Remove")); - if(itemsList.count() > 0) { - for(QList::iterator it = itemsList.begin(); it != itemsList.end(); ++it) { - removeFromProject(*it); - } - } + QList itemsList = selectProjectFileItems(i18n("Select Files to Remove")); + if(itemsList.count() > 0) { + for(QList::iterator it = itemsList.begin(); it != itemsList.end(); ++it) { + removeFromProject(*it); + } + } } void Manager::projectShowFiles() { - KileProjectItem *item = selectProjectFileItem( i18n("Select File") ); - if(item) { - if (item->type() == KileProjectItem::ProjectFile) { - dontOpenWarning(item, i18n("Show Project Files"), i18n("project configuration file")); - } - else if(item->type() == KileProjectItem::Image) { - dontOpenWarning(item, i18n("Show Project Files"), i18n("graphics file")); - } - else { // ok, we can switch to another file - if (m_ki->isOpen(item->url())) { - m_ki->viewManager()->switchToTextView(item->url()); - } - else { - fileOpen(item->url(), item->encoding() ); - } - } - } + KileProjectItem *item = selectProjectFileItem( i18n("Select File") ); + if(item) { + if (item->type() == KileProjectItem::ProjectFile) { + dontOpenWarning(item, i18n("Show Project Files"), i18n("project configuration file")); + } + else if(item->type() == KileProjectItem::Image) { + dontOpenWarning(item, i18n("Show Project Files"), i18n("graphics file")); + } + else { // ok, we can switch to another file + if (m_ki->isOpen(item->url())) { + m_ki->viewManager()->switchToTextView(item->url()); + } + else { + fileOpen(item->url(), item->encoding() ); + } + } + } } void Manager::projectOpenAllFiles() { - KileProject *project = selectProject(i18n("Select Project")); - if(project) { - projectOpenAllFiles(project->url()); - } + KileProject *project = selectProject(i18n("Select Project")); + if(project) { + projectOpenAllFiles(project->url()); + } } void Manager::projectOpenAllFiles(const QUrl &url) { - KileProject* project; - KTextEditor::Document* doc = Q_NULLPTR; + KileProject* project; + KTextEditor::Document* doc = Q_NULLPTR; - if(!url.isValid()) { - return; - } - project = projectFor(url); + if(!url.isValid()) { + return; + } + project = projectFor(url); - if(!project) - return; + if(!project) + return; - if(m_ki->viewManager()->currentTextView()) { - doc = m_ki->viewManager()->currentTextView()->document(); - } - // we remember the actual view, so the user gets the same view back after opening + if(m_ki->viewManager()->currentTextView()) { + doc = m_ki->viewManager()->currentTextView()->document(); + } + // we remember the actual view, so the user gets the same view back after opening - QList list = project->items(); - for(QList::iterator it = list.begin(); it != list.end(); ++it) { - KileProjectItem *item = *it; + QList list = project->items(); + for(QList::iterator it = list.begin(); it != list.end(); ++it) { + KileProjectItem *item = *it; - if (item->type()==KileProjectItem::ProjectFile) { - dontOpenWarning( item, i18n("Open All Project Files"), i18n("project configuration file") ); - } - else if(item->type()==KileProjectItem::Image) { - dontOpenWarning( item, i18n("Open All Project Files"), i18n("graphics file") ); - } - else if(!m_ki->isOpen(item->url())) { - fileOpen(item->url(), item->encoding()); - } - } + if (item->type()==KileProjectItem::ProjectFile) { + dontOpenWarning( item, i18n("Open All Project Files"), i18n("project configuration file") ); + } + else if(item->type()==KileProjectItem::Image) { + dontOpenWarning( item, i18n("Open All Project Files"), i18n("graphics file") ); + } + else if(!m_ki->isOpen(item->url())) { + fileOpen(item->url(), item->encoding()); + } + } - if(doc) { // we have a doc so switch back to original view - m_ki->viewManager()->switchToTextView(doc->url()); - } + if(doc) { // we have a doc so switch back to original view + m_ki->viewManager()->switchToTextView(doc->url()); + } } QStringList Manager::getProjectFiles() { - QStringList filelist; + QStringList filelist; - KileProject *project = activeProject(); - if ( project ) - { - QList list = project->items(); - for(QList::iterator it = list.begin(); it != list.end(); ++it) { - KileProjectItem *item = *it; + KileProject *project = activeProject(); + if ( project ) + { + QList list = project->items(); + for(QList::iterator it = list.begin(); it != list.end(); ++it) { + KileProjectItem *item = *it; - if(item->type() != KileProjectItem::ProjectFile && item->type() != KileProjectItem::Image) { - filelist << item->url().toLocalFile(); - } - } - } - return filelist; + if(item->type() != KileProjectItem::ProjectFile && item->type() != KileProjectItem::Image) { + filelist << item->url().toLocalFile(); + } + } + } + return filelist; } void Manager::dontOpenWarning(KileProjectItem *item, const QString &action, const QString &filetype) { - m_ki->errorHandler()->printMessage(KileTool::Info, - i18n("not opened: %1 (%2)", item->url().toLocalFile(), filetype), - action); + m_ki->errorHandler()->printMessage(KileTool::Info, + i18n("not opened: %1 (%2)", item->url().toLocalFile(), filetype), + action); } KileProjectItem* Manager::selectProjectFileItem(const QString &label) { - // select a project - KileProject *project = selectProject(i18n("Select Project")); - if(!project) { - return Q_NULLPTR; - } - - // get a list of files - QStringList filelist; - QMap map; - QList list = project->items(); - for(QList::iterator it = list.begin(); it != list.end(); ++it) { - KileProjectItem *item = *it; - - filelist << item->path(); - map[item->path()] = item; - } - - // select one of these files - KileProjectItem *item = Q_NULLPTR; - KileListSelector *dlg = new KileListSelector(filelist, i18n("Project Files"), label, true, m_ki->mainWindow()); - if(dlg->exec()) { - if(dlg->hasSelection()) { - QString name = dlg->selectedItems().first(); - if(map.contains(name)) { - item = map[name]; - } - else { - KMessageBox::error(m_ki->mainWindow(), i18n("Could not determine the selected file."),i18n( "Project Error")); - } - } - } - delete dlg; - - return item; + // select a project + KileProject *project = selectProject(i18n("Select Project")); + if(!project) { + return Q_NULLPTR; + } + + // get a list of files + QStringList filelist; + QMap map; + QList list = project->items(); + for(QList::iterator it = list.begin(); it != list.end(); ++it) { + KileProjectItem *item = *it; + + filelist << item->path(); + map[item->path()] = item; + } + + // select one of these files + KileProjectItem *item = Q_NULLPTR; + KileListSelector *dlg = new KileListSelector(filelist, i18n("Project Files"), label, true, m_ki->mainWindow()); + if(dlg->exec()) { + if(dlg->hasSelection()) { + QString name = dlg->selectedItems().first(); + if(map.contains(name)) { + item = map[name]; + } + else { + KMessageBox::error(m_ki->mainWindow(), i18n("Could not determine the selected file."),i18n( "Project Error")); + } + } + } + delete dlg; + + return item; } QList Manager::selectProjectFileItems(const QString &label) { - KileProject *project = selectProject(i18n("Select Project")); - if(!project) { - return QList(); - } + KileProject *project = selectProject(i18n("Select Project")); + if(!project) { + return QList(); + } - QStringList filelist; - QMap map; + QStringList filelist; + QMap map; - QList list = project->items(); - for(QList::iterator it = list.begin(); it != list.end(); ++it) { - KileProjectItem *item = *it; + QList list = project->items(); + for(QList::iterator it = list.begin(); it != list.end(); ++it) { + KileProjectItem *item = *it; - filelist << item->path(); - map[item->path()] = item; - } + filelist << item->path(); + map[item->path()] = item; + } - QList itemsList; + QList itemsList; - KileListSelector *dlg = new KileListSelector(filelist, i18n("Project Files"), label, true, m_ki->mainWindow()); - dlg->setSelectionMode(QAbstractItemView::ExtendedSelection); - if(dlg->exec()) { - if(dlg->hasSelection()) { - QStringList selectedfiles = dlg->selectedItems(); - for(QStringList::Iterator it = selectedfiles.begin(); it != selectedfiles.end(); ++it ){ - if(map.contains(*it)) { - itemsList.append(map[(*it)]); - } - else { - KMessageBox::error(m_ki->mainWindow(), i18n("Could not determine the selected file."), i18n( "Project Error")); - } - } - } - } - delete dlg; + KileListSelector *dlg = new KileListSelector(filelist, i18n("Project Files"), label, true, m_ki->mainWindow()); + dlg->setSelectionMode(QAbstractItemView::ExtendedSelection); + if(dlg->exec()) { + if(dlg->hasSelection()) { + QStringList selectedfiles = dlg->selectedItems(); + for(QStringList::Iterator it = selectedfiles.begin(); it != selectedfiles.end(); ++it ) { + if(map.contains(*it)) { + itemsList.append(map[(*it)]); + } + else { + KMessageBox::error(m_ki->mainWindow(), i18n("Could not determine the selected file."), i18n( "Project Error")); + } + } + } + } + delete dlg; - return itemsList; + return itemsList; } // add a new file to the project // - only when there is an active project // - if the file doesn't already belong to it (checked by addToProject) void Manager::projectAddFile(QString filename, bool graphics) { - KILE_DEBUG_MAIN << "===Kile::projectAddFile=============="; - KileProject *project = activeProject(); - if(!project) { - return; - } - - QFileInfo fi(filename); - if(!fi.exists()) { - if(graphics) { - return; - } - - // called from InputDialog after a \input- or \include command: - // - if the chosen file has an extension: accept - // - if not we add the default TeX extension: accept if it exists else reject - QString ext = fi.completeSuffix(); - if ( ! ext.isEmpty() ) { - return; - } - - filename += m_ki->extensions()->latexDocumentDefault(); - if ( QFileInfo(filename).exists() ) { - return; - } - } - - //ok, we have a project and an existing file - KILE_DEBUG_MAIN << "\tadd file: " << filename; - m_ki->viewManager()->updateStructure(false); - - QUrl url; - url.setPath(filename); - addToProject(project, url); + KILE_DEBUG_MAIN << "===Kile::projectAddFile=============="; + KileProject *project = activeProject(); + if(!project) { + return; + } + + QFileInfo fi(filename); + if(!fi.exists()) { + if(graphics) { + return; + } + + // called from InputDialog after a \input- or \include command: + // - if the chosen file has an extension: accept + // - if not we add the default TeX extension: accept if it exists else reject + QString ext = fi.completeSuffix(); + if ( ! ext.isEmpty() ) { + return; + } + + filename += m_ki->extensions()->latexDocumentDefault(); + if ( QFileInfo(filename).exists() ) { + return; + } + } + + //ok, we have a project and an existing file + KILE_DEBUG_MAIN << "\tadd file: " << filename; + m_ki->viewManager()->updateStructure(false); + + QUrl url; + url.setPath(filename); + addToProject(project, url); } const QUrl Manager::symlinkFreeURL(const QUrl &url) { #ifdef Q_OS_WIN - //TODO: maybe actually do something here? Seems unncecessary given Windows' lack of symlinks though... - //Also: the else'd code below fails badly on Windows - return url; + //TODO: maybe actually do something here? Seems unncecessary given Windows' lack of symlinks though... + //Also: the else'd code below fails badly on Windows + return url; #else - KILE_DEBUG_MAIN << "===symlinkFreeURL=="; + KILE_DEBUG_MAIN << "===symlinkFreeURL=="; - if(!url.isLocalFile()) { - return url; - } + if(!url.isLocalFile()) { + return url; + } - QDir dir(url.adjusted(QUrl::RemoveFilename | QUrl::StripTrailingSlash).path()); - QString filename = url.toLocalFile(); // if the directory does not exist we return the old url (just to be sure) + QDir dir(url.adjusted(QUrl::RemoveFilename | QUrl::StripTrailingSlash).path()); + QString filename = url.toLocalFile(); // if the directory does not exist we return the old url (just to be sure) - if(dir.exists()) { - filename= dir.canonicalPath() + '/' + url.fileName(); - } - else { - KILE_DEBUG_MAIN << "directory " << url.adjusted(QUrl::RemoveFilename|QUrl::StripTrailingSlash).path() << "does not exist"; - } + if(dir.exists()) { + filename= dir.canonicalPath() + '/' + url.fileName(); + } + else { + KILE_DEBUG_MAIN << "directory " << url.adjusted(QUrl::RemoveFilename|QUrl::StripTrailingSlash).path() << "does not exist"; + } - QFileInfo fi(filename); - if (fi.isSymLink()) { - filename = fi.symLinkTarget(); - } + QFileInfo fi(filename); + if (fi.isSymLink()) { + filename = fi.symLinkTarget(); + } - return QUrl::fromLocalFile(filename); + return QUrl::fromLocalFile(filename); #endif //def Q_OS_WIN } void Manager::cleanupDocumentInfoForProjectItems(KileDocument::Info *info) { - QList itemsList = itemsFor(info); - for(QList::iterator it = itemsList.begin(); it != itemsList.end(); ++it) { - (*it)->setInfo(Q_NULLPTR); - } + QList itemsList = itemsFor(info); + for(QList::iterator it = itemsList.begin(); it != itemsList.end(); ++it) { + (*it)->setInfo(Q_NULLPTR); + } } void Manager::createProgressDialog() { - //TODO this is a dangerous dialog and should be removed in the long-term: - // the dialog disables all close events unless all files are loaded, - // thus if there is a loading error, the only way to abort loading gracefully is to - // terminate the application - m_progressDialog = new KileWidget::ProgressDialog(m_ki->mainWindow()); - QLabel *label = new QLabel(m_progressDialog); - label->setText(i18n("Opening Project...")); - m_progressDialog->setLabel(label); - m_progressDialog->setModal(true); - m_progressDialog->setLabelText(i18n("Scanning project files...")); - m_progressDialog->setAutoClose(true); - m_progressDialog->setMinimumDuration(2000); - m_progressDialog->hide(); + //TODO this is a dangerous dialog and should be removed in the long-term: + // the dialog disables all close events unless all files are loaded, + // thus if there is a loading error, the only way to abort loading gracefully is to + // terminate the application + m_progressDialog = new KileWidget::ProgressDialog(m_ki->mainWindow()); + QLabel *label = new QLabel(m_progressDialog); + label->setText(i18n("Opening Project...")); + m_progressDialog->setLabel(label); + m_progressDialog->setModal(true); + m_progressDialog->setLabelText(i18n("Scanning project files...")); + m_progressDialog->setAutoClose(true); + m_progressDialog->setMinimumDuration(2000); + m_progressDialog->hide(); } void Manager::loadDocumentAndViewSettings(KileDocument::TextInfo *textInfo) { - KTextEditor::Document *document = textInfo->getDoc(); - if(!document) { - return; - } - - KConfigGroup configGroup = configGroupForDocumentSettings(document); - if(!configGroup.exists()) { - return; - } - - document->readSessionConfig(configGroup, QSet() << "SkipEncoding" << "SkipUrl"); - { - LaTeXInfo *latexInfo = dynamic_cast(textInfo); - if(latexInfo) { - KileTool::LivePreviewManager::readLivePreviewStatusSettings(configGroup, latexInfo); - } - } - - { - LaTeXOutputHandler *h = dynamic_cast(textInfo); - if(h) { - h->readBibliographyBackendSettings(configGroup); - } - } - - QList viewList = document->views(); - int i = 0; - for(QList::iterator it = viewList.begin(); it != viewList.end(); ++it) { - KTextEditor::View *view = *it; - configGroup = configGroupForViewSettings(document, i); - view->readSessionConfig(configGroup); - ++i; - } + KTextEditor::Document *document = textInfo->getDoc(); + if(!document) { + return; + } + + KConfigGroup configGroup = configGroupForDocumentSettings(document); + if(!configGroup.exists()) { + return; + } + + document->readSessionConfig(configGroup, QSet() << "SkipEncoding" << "SkipUrl"); + { + LaTeXInfo *latexInfo = dynamic_cast(textInfo); + if(latexInfo) { + KileTool::LivePreviewManager::readLivePreviewStatusSettings(configGroup, latexInfo); + } + } + + { + LaTeXOutputHandler *h = dynamic_cast(textInfo); + if(h) { + h->readBibliographyBackendSettings(configGroup); + } + } + + QList viewList = document->views(); + int i = 0; + for(QList::iterator it = viewList.begin(); it != viewList.end(); ++it) { + KTextEditor::View *view = *it; + configGroup = configGroupForViewSettings(document, i); + view->readSessionConfig(configGroup); + ++i; + } } void Manager::saveDocumentAndViewSettings(KileDocument::TextInfo *textInfo) { - KTextEditor::Document *document = textInfo->getDoc(); - if(!document) { - return; - } - - KConfigGroup configGroup = configGroupForDocumentSettings(document); - - QUrl url = document->url(); - url.setPassword(""); // we don't want the password to appear in the configuration file - deleteDocumentAndViewSettingsGroups(url); - - document->writeSessionConfig(configGroup, QSet() << "SkipEncoding" << "SkipUrl"); - { - LaTeXInfo *latexInfo = dynamic_cast(textInfo); - if(latexInfo) { - KileTool::LivePreviewManager::writeLivePreviewStatusSettings(configGroup, latexInfo); - } - } - - { - LaTeXOutputHandler *h = dynamic_cast(textInfo); - if(h) { - h->writeBibliographyBackendSettings(configGroup); - } - } - - QList viewList = document->views(); - int i = 0; - for(QList::iterator it = viewList.begin(); it != viewList.end(); ++it) { - configGroup = configGroupForViewSettings(document, i); - (*it)->writeSessionConfig(configGroup); - ++i; - } - // finally remove the config groups for the oldest documents that exceed MAX_NUMBER_OF_STORED_SETTINGS - configGroup = KSharedConfig::openConfig()->group("Session Settings"); - QList urlList = QUrl::fromStringList(configGroup.readEntry("Saved Documents", QStringList())); - urlList.removeAll(url); - urlList.push_front(url); - // remove excess elements - if(urlList.length() > MAX_NUMBER_OF_STORED_SETTINGS) { - int excessNumber = urlList.length() - MAX_NUMBER_OF_STORED_SETTINGS; - for(; excessNumber > 0; --excessNumber) { - QUrl url = urlList.takeLast(); - deleteDocumentAndViewSettingsGroups(url); - } - } - configGroup.writeEntry("Documents", url); - configGroup.writeEntry("Saved Documents", QUrl::toStringList(urlList)); + KTextEditor::Document *document = textInfo->getDoc(); + if(!document) { + return; + } + + KConfigGroup configGroup = configGroupForDocumentSettings(document); + + QUrl url = document->url(); + url.setPassword(""); // we don't want the password to appear in the configuration file + deleteDocumentAndViewSettingsGroups(url); + + document->writeSessionConfig(configGroup, QSet() << "SkipEncoding" << "SkipUrl"); + { + LaTeXInfo *latexInfo = dynamic_cast(textInfo); + if(latexInfo) { + KileTool::LivePreviewManager::writeLivePreviewStatusSettings(configGroup, latexInfo); + } + } + + { + LaTeXOutputHandler *h = dynamic_cast(textInfo); + if(h) { + h->writeBibliographyBackendSettings(configGroup); + } + } + + QList viewList = document->views(); + int i = 0; + for(QList::iterator it = viewList.begin(); it != viewList.end(); ++it) { + configGroup = configGroupForViewSettings(document, i); + (*it)->writeSessionConfig(configGroup); + ++i; + } + // finally remove the config groups for the oldest documents that exceed MAX_NUMBER_OF_STORED_SETTINGS + configGroup = KSharedConfig::openConfig()->group("Session Settings"); + QList urlList = QUrl::fromStringList(configGroup.readEntry("Saved Documents", QStringList())); + urlList.removeAll(url); + urlList.push_front(url); + // remove excess elements + if(urlList.length() > MAX_NUMBER_OF_STORED_SETTINGS) { + int excessNumber = urlList.length() - MAX_NUMBER_OF_STORED_SETTINGS; + for(; excessNumber > 0; --excessNumber) { + QUrl url = urlList.takeLast(); + deleteDocumentAndViewSettingsGroups(url); + } + } + configGroup.writeEntry("Documents", url); + configGroup.writeEntry("Saved Documents", QUrl::toStringList(urlList)); } KConfigGroup Manager::configGroupForDocumentSettings(KTextEditor::Document *doc) const { - return KSharedConfig::openConfig()->group(configGroupNameForDocumentSettings(doc->url())); + return KSharedConfig::openConfig()->group(configGroupNameForDocumentSettings(doc->url())); } QString Manager::configGroupNameForDocumentSettings(const QUrl &url) const { - QUrl url2 = url; - url2.setPassword(""); - return "Document-Settings,URL=" + url2.url(); + QUrl url2 = url; + url2.setPassword(""); + return "Document-Settings,URL=" + url2.url(); } KConfigGroup Manager::configGroupForViewSettings(KTextEditor::Document *doc, int viewIndex) const { - return KSharedConfig::openConfig()->group(configGroupNameForViewSettings(doc->url(), viewIndex)); + return KSharedConfig::openConfig()->group(configGroupNameForViewSettings(doc->url(), viewIndex)); } QString Manager::configGroupNameForViewSettings(const QUrl &url, int viewIndex) const { - QUrl url2 = url; - url2.setPassword(""); - return "View-Settings,View=" + QString::number(viewIndex) + ",URL=" + url2.url(); + QUrl url2 = url; + url2.setPassword(""); + return "View-Settings,View=" + QString::number(viewIndex) + ",URL=" + url2.url(); } void Manager::deleteDocumentAndViewSettingsGroups(const QUrl &url) { - QString urlString = url.url(); - const QStringList groupList = KSharedConfig::openConfig()->groupList(); - for(auto groupName : groupList) { - if(!KSharedConfig::openConfig()->hasGroup(groupName)) { // 'groupName' might have been deleted - continue; // work around bug 384039 - } - if(groupName.startsWith("Document-Settings") - || groupName.startsWith("View-Settings")) { - int urlIndex = groupName.indexOf("URL="); - if(urlIndex >= 0 && groupName.mid(urlIndex + 4) == urlString) { - KSharedConfig::openConfig()->deleteGroup(groupName); - } - } - } + QString urlString = url.url(); + const QStringList groupList = KSharedConfig::openConfig()->groupList(); + for(auto groupName : groupList) { + if(!KSharedConfig::openConfig()->hasGroup(groupName)) { // 'groupName' might have been deleted + continue; // work around bug 384039 + } + if(groupName.startsWith("Document-Settings") + || groupName.startsWith("View-Settings")) { + int urlIndex = groupName.indexOf("URL="); + if(urlIndex >= 0 && groupName.mid(urlIndex + 4) == urlString) { + KSharedConfig::openConfig()->deleteGroup(groupName); + } + } + } } QStringList Manager::loadTextURLContents(const QUrl &url, const QString& encoding) { - QTemporaryFile *temporaryFile = Q_NULLPTR; - QString localFileName; - if(url.isLocalFile()) { - localFileName = url.path(); - } - else { // only use KIO when we have to - temporaryFile = new QTemporaryFile(); - if(!temporaryFile->open()) { - KILE_DEBUG_MAIN << "Cannot create temporary file for" << url; - delete temporaryFile; - return QStringList(); - } - localFileName = temporaryFile->fileName(); - auto downloadJob = KIO::file_copy(url, QUrl::fromLocalFile(localFileName), 0600, KIO::Overwrite); - KJobWidgets::setWindow(downloadJob, m_ki->mainWindow()); - // FIXME: 'exec' should not be used! - if (!downloadJob->exec()) { - KILE_DEBUG_MAIN << "Cannot download resource: " << url; - KILE_DEBUG_MAIN << downloadJob->errorString(); - delete temporaryFile; - return QStringList(); - } - } - - QFile localFile(localFileName); - - if (!localFile.open(QIODevice::ReadOnly | QIODevice::Text)) { - KILE_DEBUG_MAIN << "Cannot open source file: " << localFileName; - delete temporaryFile; - return QStringList(); - } - - QStringList res; - QTextStream stream(&localFile); - if(!encoding.isEmpty()) { - stream.setCodec(encoding.toLatin1()); - } - while(!stream.atEnd()) { - res.append(stream.readLine()); - } - delete temporaryFile; - return res; + QTemporaryFile *temporaryFile = Q_NULLPTR; + QString localFileName; + if(url.isLocalFile()) { + localFileName = url.path(); + } + else { // only use KIO when we have to + temporaryFile = new QTemporaryFile(); + if(!temporaryFile->open()) { + KILE_DEBUG_MAIN << "Cannot create temporary file for" << url; + delete temporaryFile; + return QStringList(); + } + localFileName = temporaryFile->fileName(); + auto downloadJob = KIO::file_copy(url, QUrl::fromLocalFile(localFileName), 0600, KIO::Overwrite); + KJobWidgets::setWindow(downloadJob, m_ki->mainWindow()); + // FIXME: 'exec' should not be used! + if (!downloadJob->exec()) { + KILE_DEBUG_MAIN << "Cannot download resource: " << url; + KILE_DEBUG_MAIN << downloadJob->errorString(); + delete temporaryFile; + return QStringList(); + } + } + + QFile localFile(localFileName); + + if (!localFile.open(QIODevice::ReadOnly | QIODevice::Text)) { + KILE_DEBUG_MAIN << "Cannot open source file: " << localFileName; + delete temporaryFile; + return QStringList(); + } + + QStringList res; + QTextStream stream(&localFile); + if(!encoding.isEmpty()) { + stream.setCodec(encoding.toLatin1()); + } + while(!stream.atEnd()) { + res.append(stream.readLine()); + } + delete temporaryFile; + return res; } } diff --git a/src/kiledocmanager.h b/src/kiledocmanager.h index c731eae8..54a73c2f 100644 --- a/src/kiledocmanager.h +++ b/src/kiledocmanager.h @@ -1,298 +1,307 @@ /************************************************************************** * Copyright (C) 2004 by Jeroen Wijnhout (Jeroen.Wijnhout@kdemail.net) * * (C) 2006-2013 by Michel Ludwig (michel.ludwig@kdemail.net) * ***************************************************************************/ /*************************************************************************** * * * 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. * * * ***************************************************************************/ #ifndef KILEDOCUMENTKILEDOCMANAGER_H #define KILEDOCUMENTKILEDOCMANAGER_H #include #include #include #include #include #include #include "kileconstants.h" #include "kileproject.h" #include "widgets/progressdialog.h" class QUrl; class KFileItem; class QProgressDialog; -namespace KTextEditor {class Document; class View;} +namespace KTextEditor { +class Document; +class View; +} class TemplateItem; class KileInfo; class KileProjectItem; -namespace KileParser { class ParserOutput; } +namespace KileParser { +class ParserOutput; +} namespace KileDocument { class Info; class TextInfo; /** * The design of the document manager is based on the following invariants: * - Several projects can be open simultaneously * - For every URL there can only be at most one associated KileDocument::Info* object, but * there can be several KileProject* items (each one belonging to a different project) * - It is guaranteed that every project item that represents textual data contains a TextInfo* object **/ class Manager : public QObject { - Q_OBJECT + Q_OBJECT public: - explicit Manager(KileInfo *info, QObject *parent = Q_NULLPTR, const char *name = Q_NULLPTR); - ~Manager(); + explicit Manager(KileInfo *info, QObject *parent = Q_NULLPTR, const char *name = Q_NULLPTR); + ~Manager(); - void readConfig(); - void writeConfig(); + void readConfig(); + void writeConfig(); public Q_SLOTS: - KTextEditor::View* createNewJScript(); - KTextEditor::View* createNewLaTeXDocument(); + KTextEditor::View* createNewJScript(); + KTextEditor::View* createNewLaTeXDocument(); //files - void newDocumentStatus(KTextEditor::Document *doc); - - /** - * Creates a new file on disk. - **/ - void fileNew(const QUrl&); - void fileNewScript(); - void fileNew(KileDocument::Type type = LaTeX); - - void fileSelected(const QUrl&); - void fileSelected(const KileProjectItem *item); - void fileSelected(const KFileItem& file); - - void fileOpen(); - inline TextInfo* fileOpen(const QString& localFile, const QString& encoding = QString(), int index = -1) - { - return fileOpen(QUrl::fromLocalFile(localFile), encoding, index); - } - TextInfo* fileOpen(const QUrl &url, const QString& encoding = QString(), int index = -1); - - bool fileSave(KTextEditor::View* = Q_NULLPTR); - bool fileSaveAs(KTextEditor::View* = Q_NULLPTR); - void fileSaveCopyAs(); - - void saveURL(const QUrl&); - bool fileSaveAll(bool disUntitled = false); - - bool fileCloseAllOthers(KTextEditor::View *view = Q_NULLPTR); - bool fileCloseAll(); - bool fileClose(const QUrl &url); - bool fileClose(KTextEditor::View *view = Q_NULLPTR); - bool fileClose(KTextEditor::Document *doc, bool closingproject = false); + void newDocumentStatus(KTextEditor::Document *doc); + + /** + * Creates a new file on disk. + **/ + void fileNew(const QUrl&); + void fileNewScript(); + void fileNew(KileDocument::Type type = LaTeX); + + void fileSelected(const QUrl&); + void fileSelected(const KileProjectItem *item); + void fileSelected(const KFileItem& file); + + void fileOpen(); + inline TextInfo* fileOpen(const QString& localFile, const QString& encoding = QString(), int index = -1) + { + return fileOpen(QUrl::fromLocalFile(localFile), encoding, index); + } + TextInfo* fileOpen(const QUrl &url, const QString& encoding = QString(), int index = -1); + + bool fileSave(KTextEditor::View* = Q_NULLPTR); + bool fileSaveAs(KTextEditor::View* = Q_NULLPTR); + void fileSaveCopyAs(); + + void saveURL(const QUrl&); + bool fileSaveAll(bool disUntitled = false); + + bool fileCloseAllOthers(KTextEditor::View *view = Q_NULLPTR); + bool fileCloseAll(); + bool fileClose(const QUrl &url); + bool fileClose(KTextEditor::View *view = Q_NULLPTR); + bool fileClose(KTextEditor::Document *doc, bool closingproject = false); //templates - KTextEditor::View* loadTemplate(TemplateItem*); - void createTemplate(); - void removeTemplate(); - void replaceTemplateVariables(QString &line); + KTextEditor::View* loadTemplate(TemplateItem*); + void createTemplate(); + void removeTemplate(); + void replaceTemplateVariables(QString &line); //projects - void projectNew(); - void projectOpen(); - - /** - * @param openProjectItemViews Opens project files in the editor iff openProjectItemViews is set to 'true'. - **/ - void projectOpen(const QUrl&, int step = 0, int max = 1, bool openProjectItemViews = true); - - /** - * Saves the state of the project, if @param project is zero, the active project is saved. - **/ - void projectSave(KileProject* project = Q_NULLPTR); - void projectAddFiles(const QUrl&); - void projectAddFiles(KileProject* project = Q_NULLPTR,const QUrl &url = QUrl()); - void toggleArchive(KileProjectItem *); - void buildProjectTree(KileProject *project = Q_NULLPTR); - void buildProjectTree(const QUrl&); - void projectOptions(const QUrl&); - void projectOptions(KileProject *project = Q_NULLPTR); - bool projectClose(const QUrl &url = QUrl()); - bool projectCloseAll(); - - void projectShow(); - void projectRemoveFiles(); - void projectShowFiles(); - void projectAddFile(QString filename, bool graphics=false); - void projectOpenAllFiles(); - void projectOpenAllFiles(const QUrl&); - - KileProject* selectProject(const QString&); - - void addProject(KileProject *project); - void addToProject(const QUrl&); - void addToProject(KileProject*, const QUrl&); - void removeFromProject(KileProjectItem *item); - void storeProjectItem(KileProjectItem *item, KTextEditor::Document *doc); - - void cleanUpTempFiles(const QUrl &url, bool silent = false); - - void openDroppedURLs(QDropEvent *e); - - void reloadXMLOnAllDocumentsAndViews(); - - void handleParsingComplete(const QUrl &url, KileParser::ParserOutput* output); + void projectNew(); + void projectOpen(); + + /** + * @param openProjectItemViews Opens project files in the editor iff openProjectItemViews is set to 'true'. + **/ + void projectOpen(const QUrl&, int step = 0, int max = 1, bool openProjectItemViews = true); + + /** + * Saves the state of the project, if @param project is zero, the active project is saved. + **/ + void projectSave(KileProject* project = Q_NULLPTR); + void projectAddFiles(const QUrl&); + void projectAddFiles(KileProject* project = Q_NULLPTR,const QUrl &url = QUrl()); + void toggleArchive(KileProjectItem *); + void buildProjectTree(KileProject *project = Q_NULLPTR); + void buildProjectTree(const QUrl&); + void projectOptions(const QUrl&); + void projectOptions(KileProject *project = Q_NULLPTR); + bool projectClose(const QUrl &url = QUrl()); + bool projectCloseAll(); + + void projectShow(); + void projectRemoveFiles(); + void projectShowFiles(); + void projectAddFile(QString filename, bool graphics=false); + void projectOpenAllFiles(); + void projectOpenAllFiles(const QUrl&); + + KileProject* selectProject(const QString&); + + void addProject(KileProject *project); + void addToProject(const QUrl&); + void addToProject(KileProject*, const QUrl&); + void removeFromProject(KileProjectItem *item); + void storeProjectItem(KileProjectItem *item, KTextEditor::Document *doc); + + void cleanUpTempFiles(const QUrl &url, bool silent = false); + + void openDroppedURLs(QDropEvent *e); + + void reloadXMLOnAllDocumentsAndViews(); + + void handleParsingComplete(const QUrl &url, KileParser::ParserOutput* output); Q_SIGNALS: - void projectTreeChanged(const KileProject*); - void closingDocument(KileDocument::Info*); - void documentInfoCreated(KileDocument::Info*); + void projectTreeChanged(const KileProject*); + void closingDocument(KileDocument::Info*); + void documentInfoCreated(KileDocument::Info*); - void updateStructure(bool needToParse, KileDocument::Info*); - void updateModeStatus(); - void updateReferences(KileDocument::Info*); + void updateStructure(bool needToParse, KileDocument::Info*); + void updateModeStatus(); + void updateReferences(KileDocument::Info*); - void documentModificationStatusChanged(KTextEditor::Document*, bool, KTextEditor::ModificationInterface::ModifiedOnDiskReason); - void documentUrlChanged(KTextEditor::Document*); - void documentNameChanged(KTextEditor::Document*); - void documentReadWriteStateChanged(KTextEditor::Document*); + void documentModificationStatusChanged(KTextEditor::Document*, bool, KTextEditor::ModificationInterface::ModifiedOnDiskReason); + void documentUrlChanged(KTextEditor::Document*); + void documentNameChanged(KTextEditor::Document*); + void documentReadWriteStateChanged(KTextEditor::Document*); - void addToRecentFiles(const QUrl&); - void addToRecentProjects(const QUrl&); - void removeFromRecentProjects(const QUrl&); + void addToRecentFiles(const QUrl&); + void addToRecentProjects(const QUrl&); + void removeFromRecentProjects(const QUrl&); - void startWizard(); + void startWizard(); - void removeFromProjectView(const QUrl&); - void removeFromProjectView(const KileProject*); - void removeItemFromProjectView(const KileProjectItem*, bool); - void addToProjectView(const QUrl&); - void addToProjectView(KileProjectItem *item); - void addToProjectView(const KileProject*); + void removeFromProjectView(const QUrl&); + void removeFromProjectView(const KileProject*); + void removeItemFromProjectView(const KileProjectItem*, bool); + void addToProjectView(const QUrl&); + void addToProjectView(KileProjectItem *item); + void addToProjectView(const KileProject*); - void documentSavedAs(KTextEditor::View*, KileDocument::TextInfo*); + void documentSavedAs(KTextEditor::View*, KileDocument::TextInfo*); - void projectOpened(KileProject *project); - void documentOpened(KileDocument::TextInfo *textInfo); + void projectOpened(KileProject *project); + void documentOpened(KileDocument::TextInfo *textInfo); public: - bool isOpeningFile(); + bool isOpeningFile(); - KTextEditor::Editor* getEditor(); + KTextEditor::Editor* getEditor(); - QList projects() { return m_projects; } - QList textDocumentInfos() { return m_textInfoList; } + QList projects() { + return m_projects; + } + QList textDocumentInfos() { + return m_textInfoList; + } - KTextEditor::Document* docFor(const QUrl &url); + KTextEditor::Document* docFor(const QUrl &url); - TextInfo* getInfo() const; + TextInfo* getInfo() const; - inline TextInfo* textInfoFor(const QString& localFile) - { - return textInfoFor(QUrl::fromLocalFile(localFile)); - } + inline TextInfo* textInfoFor(const QString& localFile) + { + return textInfoFor(QUrl::fromLocalFile(localFile)); + } - TextInfo* textInfoFor(const QUrl &url); - TextInfo* textInfoFor(KTextEditor::Document* doc) const; + TextInfo* textInfoFor(const QUrl &url); + TextInfo* textInfoFor(KTextEditor::Document* doc) const; - QUrl urlFor(TextInfo* textInfo); + QUrl urlFor(TextInfo* textInfo); - void updateInfos(); + void updateInfos(); - KileProject* projectForMember(const QUrl &memberUrl); - KileProject* projectFor(const QUrl &projecturl); - KileProject* projectFor(const QString & name); - KileProject* activeProject(); - bool isProjectOpen(); - void updateProjectReferences(KileProject *project); - QStringList getProjectFiles(); + KileProject* projectForMember(const QUrl &memberUrl); + KileProject* projectFor(const QUrl &projecturl); + KileProject* projectFor(const QString & name); + KileProject* activeProject(); + bool isProjectOpen(); + void updateProjectReferences(KileProject *project); + QStringList getProjectFiles(); - KileProjectItem* activeProjectItem(); - /** - * Finds the project item for the file with URL @param url. - * @returns a pointer to the project item, 0 if this file does not belong to a project - **/ - KileProjectItem* itemFor(const QUrl &url, KileProject *project = Q_NULLPTR) const; - KileProjectItem* itemFor(TextInfo *docinfo, KileProject *project = Q_NULLPTR) const; - KileProjectItem* selectProjectFileItem(const QString &label); - QList selectProjectFileItems(const QString &label); + KileProjectItem* activeProjectItem(); + /** + * Finds the project item for the file with URL @param url. + * @returns a pointer to the project item, 0 if this file does not belong to a project + **/ + KileProjectItem* itemFor(const QUrl &url, KileProject *project = Q_NULLPTR) const; + KileProjectItem* itemFor(TextInfo *docinfo, KileProject *project = Q_NULLPTR) const; + KileProjectItem* selectProjectFileItem(const QString &label); + QList selectProjectFileItems(const QString &label); - /** - * The next method returns a list as several projects can be open simultaneously, i.e. - * one URL can be associated with several project item belonging to different projects. - **/ - QList itemsFor(Info *docinfo) const; - QList itemsFor(const QUrl &url) const; + /** + * The next method returns a list as several projects can be open simultaneously, i.e. + * one URL can be associated with several project item belonging to different projects. + **/ + QList itemsFor(Info *docinfo) const; + QList itemsFor(const QUrl &url) const; - static const QUrl symlinkFreeURL(const QUrl &url); + static const QUrl symlinkFreeURL(const QUrl &url); protected: - /** - * @param openProjectItemViews Opens project files in the editor iff openProjectItemViews is set to 'true'. - **/ - void projectOpenItem(KileProjectItem *item, bool openProjectItemViews = true); - void createTextInfoForProjectItem(KileProjectItem *item); - - void trashDoc(TextInfo *docinfo, KTextEditor::Document *doc = Q_NULLPTR); - - TextInfo* createTextDocumentInfo(KileDocument::Type type, const QUrl &url, const QUrl& baseDirectory = QUrl()); - void recreateTextDocumentInfo(TextInfo *oldinfo); - - /** - * Tries to remove and delete a TextInfo object. The TextInfo object will only be deleted if it isn't referenced - * by any project item or if it is only referenced by a project that should be closed. - * @param closingproject Indicates whether the TextInfo object should be removed as part of a project close - * operation. - * @warning This method does not close or delete any Kate documents that are associated with the TextInfo object ! - **/ - bool removeTextDocumentInfo(TextInfo *docinfo, bool closingproject = false); - KTextEditor::Document* createDocument(const QUrl &url, TextInfo *docinfo, const QString& encoding, const QString& mode, const QString& highlight); - - /** - * Creates a document with the specified text. - * - * @param extension The extension of the file that should be created without leading "." - **/ - KTextEditor::View* createDocumentWithText(const QString& text, KileDocument::Type type = KileDocument::Text, const QString& extension = QString(), const QUrl &baseDirectory = QUrl()); - - KTextEditor::View* loadText(KileDocument::Type type, const QUrl &url, const QString& encoding = QString(), bool create = true, const QString& mode = QString(), const QString& highlight = QString(), const QString &text = QString(), int index = -1, const QUrl& baseDirectory = QUrl()); - KTextEditor::View* loadItem(KileDocument::Type type, KileProjectItem *item, const QString& text = QString(), bool openProjectItemViews = true); - - QStringList loadTextURLContents(const QUrl &url, const QString& encoding); + /** + * @param openProjectItemViews Opens project files in the editor iff openProjectItemViews is set to 'true'. + **/ + void projectOpenItem(KileProjectItem *item, bool openProjectItemViews = true); + void createTextInfoForProjectItem(KileProjectItem *item); + + void trashDoc(TextInfo *docinfo, KTextEditor::Document *doc = Q_NULLPTR); + + TextInfo* createTextDocumentInfo(KileDocument::Type type, const QUrl &url, const QUrl& baseDirectory = QUrl()); + void recreateTextDocumentInfo(TextInfo *oldinfo); + + /** + * Tries to remove and delete a TextInfo object. The TextInfo object will only be deleted if it isn't referenced + * by any project item or if it is only referenced by a project that should be closed. + * @param closingproject Indicates whether the TextInfo object should be removed as part of a project close + * operation. + * @warning This method does not close or delete any Kate documents that are associated with the TextInfo object ! + **/ + bool removeTextDocumentInfo(TextInfo *docinfo, bool closingproject = false); + KTextEditor::Document* createDocument(const QUrl &url, TextInfo *docinfo, const QString& encoding, const QString& mode, const QString& highlight); + + /** + * Creates a document with the specified text. + * + * @param extension The extension of the file that should be created without leading "." + **/ + KTextEditor::View* createDocumentWithText(const QString& text, KileDocument::Type type = KileDocument::Text, const QString& extension = QString(), const QUrl &baseDirectory = QUrl()); + + KTextEditor::View* loadText(KileDocument::Type type, const QUrl &url, const QString& encoding = QString(), bool create = true, const QString& mode = QString(), const QString& highlight = QString(), const QString &text = QString(), int index = -1, const QUrl& baseDirectory = QUrl()); + KTextEditor::View* loadItem(KileDocument::Type type, KileProjectItem *item, const QString& text = QString(), bool openProjectItemViews = true); + + QStringList loadTextURLContents(const QUrl &url, const QString& encoding); private: - KTextEditor::Editor *m_editor; - QList m_textInfoList; - KileInfo *m_ki; - QList m_projects; - QPointer m_progressDialog; - unsigned int m_autoSaveLock; - bool m_currentlySavingAll, m_currentlyOpeningFile; - - void dontOpenWarning(KileProjectItem *item, const QString &action, const QString &filetype); - void cleanupDocumentInfoForProjectItems(KileDocument::Info *info); - - void createProgressDialog(); - - QStringList autosaveWarnings; - - void loadDocumentAndViewSettings(KileDocument::TextInfo *textInfo); - void saveDocumentAndViewSettings(KileDocument::TextInfo *textInfo); - KConfigGroup configGroupForDocumentSettings(KTextEditor::Document *doc) const; - QString configGroupNameForDocumentSettings(const QUrl &url) const; - KConfigGroup configGroupForViewSettings(KTextEditor::Document *doc, int viewIndex) const; - QString configGroupNameForViewSettings(const QUrl &url, int viewIndex) const; - void deleteDocumentAndViewSettingsGroups(const QUrl &url); + KTextEditor::Editor *m_editor; + QList m_textInfoList; + KileInfo *m_ki; + QList m_projects; + QPointer m_progressDialog; + unsigned int m_autoSaveLock; + bool m_currentlySavingAll, m_currentlyOpeningFile; + + void dontOpenWarning(KileProjectItem *item, const QString &action, const QString &filetype); + void cleanupDocumentInfoForProjectItems(KileDocument::Info *info); + + void createProgressDialog(); + + QStringList autosaveWarnings; + + void loadDocumentAndViewSettings(KileDocument::TextInfo *textInfo); + void saveDocumentAndViewSettings(KileDocument::TextInfo *textInfo); + KConfigGroup configGroupForDocumentSettings(KTextEditor::Document *doc) const; + QString configGroupNameForDocumentSettings(const QUrl &url) const; + KConfigGroup configGroupForViewSettings(KTextEditor::Document *doc, int viewIndex) const; + QString configGroupNameForViewSettings(const QUrl &url, int viewIndex) const; + void deleteDocumentAndViewSettingsGroups(const QUrl &url); }; } #endif diff --git a/src/kileextensions.cpp b/src/kileextensions.cpp index fd660ba1..7edbf17f 100644 --- a/src/kileextensions.cpp +++ b/src/kileextensions.cpp @@ -1,209 +1,209 @@ /***************************************************************************** * Copyright (C) 2007 by Holger Danielsson (holger.danielsson@versanet.de) * * (C) 2016 by Michel Ludwig (michel.ludwig@kdemail.net) * ******************************************************************************/ /*************************************************************************** * * * 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. * * * ***************************************************************************/ #include "kileextensions.h" #include #include #include "kiledebug.h" -namespace KileDocument +namespace KileDocument { //////////////////// Extensions //////////////////// Extensions::Extensions() { - m_documents = ".tex .ltx .latex .dtx .ins"; - m_packages = ".cls .sty .bbx .cbx .lbx"; - m_bibtex = ".bib"; - m_metapost = ".mp"; - m_script = ".js"; - m_project = ".kilepr"; - //m_images = ".eps .pdf .dvi .ps .fig .gif .jpg .jpeg .png"; - m_images = ".eps .jpg .jpeg .png .pdf .ps .fig .gif"; - - m_latexDefault = ".tex"; - m_bibtexDefault = ".bib"; - m_metapostDefault = ".mp"; - m_scriptDefault = ".js"; - m_projectDefault = ".kilepr"; + m_documents = ".tex .ltx .latex .dtx .ins"; + m_packages = ".cls .sty .bbx .cbx .lbx"; + m_bibtex = ".bib"; + m_metapost = ".mp"; + m_script = ".js"; + m_project = ".kilepr"; + //m_images = ".eps .pdf .dvi .ps .fig .gif .jpg .jpeg .png"; + m_images = ".eps .jpg .jpeg .png .pdf .ps .fig .gif"; + + m_latexDefault = ".tex"; + m_bibtexDefault = ".bib"; + m_metapostDefault = ".mp"; + m_scriptDefault = ".js"; + m_projectDefault = ".kilepr"; } //////////////////// file filter //////////////////// QString Extensions::fileFilterKDEStyle(ExtensionType type) const { - QString ext, text; - fileFilterRaw(type, ext, text); + QString ext, text; + fileFilterRaw(type, ext, text); - ext.replace('.', "*."); - return ext + '|' + text; + ext.replace('.', "*."); + return ext + '|' + text; } QString Extensions::fileFilterQtStyle(ExtensionType type) const { - QString ext, text; - fileFilterRaw(type, ext, text); + QString ext, text; + fileFilterRaw(type, ext, text); - ext.replace('.', "*."); - return text + QStringLiteral(" (") + ext + ')'; + ext.replace('.', "*."); + return text + QStringLiteral(" (") + ext + ')'; } void Extensions::fileFilterRaw(ExtensionType type, QString& ext, QString& text) const { - switch(type) { - case TEX: - ext = m_documents; - text = i18n("(La)TeX Source Files"); - return; - case PACKAGES: - ext = m_packages; - text = i18n("(La)TeX Packages"); - return; - case BIB: - ext = m_bibtex; - text = i18n("BibTeX Files"); - return; - case IMG: - ext = m_images; - text = i18n("Image Files"); - return; - case METAPOST: - ext = m_metapost; - text = i18n("Metapost Files"); - return; - case JS: - ext = m_script; - text = i18n("Kile Script Files"); - return; - case KILE_PROJECT: - ext = m_project; - text = i18n("Kile Project Files"); - return; - } + switch(type) { + case TEX: + ext = m_documents; + text = i18n("(La)TeX Source Files"); + return; + case PACKAGES: + ext = m_packages; + text = i18n("(La)TeX Packages"); + return; + case BIB: + ext = m_bibtex; + text = i18n("BibTeX Files"); + return; + case IMG: + ext = m_images; + text = i18n("Image Files"); + return; + case METAPOST: + ext = m_metapost; + text = i18n("Metapost Files"); + return; + case JS: + ext = m_script; + text = i18n("Kile Script Files"); + return; + case KILE_PROJECT: + ext = m_project; + text = i18n("Kile Project Files"); + return; + } } QString Extensions::fileFilterKDEStyle(bool includeAllFiles, const QLinkedList& extensions) const { - QString toReturn; + QString toReturn; - for(ExtensionType extension : extensions) { - toReturn += fileFilterKDEStyle(extension) + '\n'; - } + for(ExtensionType extension : extensions) { + toReturn += fileFilterKDEStyle(extension) + '\n'; + } - if(includeAllFiles) { - toReturn += i18n("* |All Files"); - } + if(includeAllFiles) { + toReturn += i18n("* |All Files"); + } - return toReturn; + return toReturn; } QString Extensions::fileFilterQtStyle(bool includeAllFiles, const QLinkedList& extensions) const { - QString toReturn; + QString toReturn; - for(ExtensionType extension : extensions) { - toReturn += fileFilterQtStyle(extension) + QStringLiteral(";;"); - } + for(ExtensionType extension : extensions) { + toReturn += fileFilterQtStyle(extension) + QStringLiteral(";;"); + } - if(includeAllFiles) { - toReturn += i18n("All Files (*)"); - } + if(includeAllFiles) { + toReturn += i18n("All Files (*)"); + } - return toReturn; + return toReturn; } //////////////////// document type //////////////////// bool Extensions::isTexFile(const QString &fileName) const { - //TODO use mimetype - QString ext = '.' + QFileInfo(fileName).suffix(); - return isLatexDocument(ext) || isLatexPackage(ext); + //TODO use mimetype + QString ext = '.' + QFileInfo(fileName).suffix(); + return isLatexDocument(ext) || isLatexPackage(ext); } bool Extensions::isBibFile(const QString &fileName) const { - QString ext = '.' + QFileInfo(fileName).suffix(); - return isBibtex(ext); + QString ext = '.' + QFileInfo(fileName).suffix(); + return isBibtex(ext); } bool Extensions::isScriptFile(const QString &fileName) const { - QString ext = '.' + QFileInfo(fileName).suffix(); - return isScript(ext); + QString ext = '.' + QFileInfo(fileName).suffix(); + return isScript(ext); } bool Extensions::isProjectFile(const QString &fileName) const { - QString ext = '.' + QFileInfo(fileName).suffix(); - return isProject(ext); + QString ext = '.' + QFileInfo(fileName).suffix(); + return isProject(ext); } bool Extensions::validExtension(const QString &ext, const QString &extensions) const { - const QStringList extlist = extensions.split(' '); - for(QStringList::ConstIterator it = extlist.constBegin(); it != extlist.constEnd(); ++it) { - if((*it) == ext) { - return true; - } - } - - return false; + const QStringList extlist = extensions.split(' '); + for(QStringList::ConstIterator it = extlist.constBegin(); it != extlist.constEnd(); ++it) { + if((*it) == ext) { + return true; + } + } + + return false; } Type Extensions::determineDocumentType(const QUrl &url) const { - if ( isTexFile(url) ) - { - return KileDocument::LaTeX; - } - else if ( isBibFile(url) ) - { - return KileDocument::BibTeX; - } - else if ( isScriptFile(url) ) - { - return KileDocument::Script; - } - else - { - return KileDocument::Text; - } + if ( isTexFile(url) ) + { + return KileDocument::LaTeX; + } + else if ( isBibFile(url) ) + { + return KileDocument::BibTeX; + } + else if ( isScriptFile(url) ) + { + return KileDocument::Script; + } + else + { + return KileDocument::Text; + } } QString Extensions::defaultExtensionForDocumentType(KileDocument::Type type) const { - switch(type) { - case KileDocument::LaTeX: - return m_latexDefault; - - case KileDocument::BibTeX: - return m_bibtexDefault; - - case KileDocument::Script: - return m_scriptDefault; - - case KileDocument::Text: - /* fall through */ - case KileDocument::Undefined: - /* do nothing */ - break; - } - return QString(); + switch(type) { + case KileDocument::LaTeX: + return m_latexDefault; + + case KileDocument::BibTeX: + return m_bibtexDefault; + + case KileDocument::Script: + return m_scriptDefault; + + case KileDocument::Text: + /* fall through */ + case KileDocument::Undefined: + /* do nothing */ + break; + } + return QString(); } } diff --git a/src/kileextensions.h b/src/kileextensions.h index 804df96a..2f308392 100644 --- a/src/kileextensions.h +++ b/src/kileextensions.h @@ -1,89 +1,127 @@ /***************************************************************************** * Copyright (C) 2007 by Holger Danielsson (holger.danielsson@versanet.de) * * (C) 2016 by Michel Ludwig (michel.ludwig@kdemail.net) * ******************************************************************************/ /*************************************************************************** * * * 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. * * * ***************************************************************************/ #ifndef KILEEXTENSIONS_H #define KILEEXTENSIONS_H #include "kileconstants.h" #include #include #include -namespace KileDocument +namespace KileDocument { class Extensions { public: - Extensions(); - ~Extensions() {} - - enum ExtensionType { TEX=1, PACKAGES=2, BIB=4, IMG=8, METAPOST=16, JS=32, KILE_PROJECT=64 }; - - QString latexDocuments() const { return m_documents; } - QString latexPackages() const { return m_packages; } - QString bibtex() const { return m_bibtex; } - QString images() const { return m_images; } - QString metapost() const { return m_metapost; } - - QString latexDocumentDefault() const { return m_latexDefault; } - QString bibtexDefault() const { return m_bibtexDefault; } - QString metapostDefault() const { return m_metapostDefault; } - - // we need two methods as KEncodingFileDialog has no Qt-equivalent yet - QString fileFilterKDEStyle(bool includeAllFiles, const QLinkedList& extensions) const; - QString fileFilterQtStyle(bool includeAllFiles, const QLinkedList& extensions) const; - - bool isTexFile(const QString &fileName) const; - bool isTexFile(const QUrl &url) const { return isTexFile(url.fileName()); } - bool isBibFile(const QString &fileName) const; - bool isBibFile(const QUrl &url) const { return isBibFile(url.fileName()); } - bool isScriptFile(const QString &fileName) const; - bool isScriptFile(const QUrl &url) const { return isScriptFile(url.fileName()); } - bool isProjectFile(const QString &fileName) const; - bool isProjectFile(const QUrl &url) const { return isProjectFile(url.fileName()); } - - bool isLatexDocument(const QString &ext) const { return validExtension(ext,m_documents); } - bool isLatexPackage(const QString &ext) const { return validExtension(ext,m_packages); } - bool isImage(const QString &ext) const { return validExtension(ext,m_images); } - - KileDocument::Type determineDocumentType(const QUrl &url) const; - QString defaultExtensionForDocumentType(KileDocument::Type type) const; + Extensions(); + ~Extensions() {} + + enum ExtensionType { TEX=1, PACKAGES=2, BIB=4, IMG=8, METAPOST=16, JS=32, KILE_PROJECT=64 }; + + QString latexDocuments() const { + return m_documents; + } + QString latexPackages() const { + return m_packages; + } + QString bibtex() const { + return m_bibtex; + } + QString images() const { + return m_images; + } + QString metapost() const { + return m_metapost; + } + + QString latexDocumentDefault() const { + return m_latexDefault; + } + QString bibtexDefault() const { + return m_bibtexDefault; + } + QString metapostDefault() const { + return m_metapostDefault; + } + + // we need two methods as KEncodingFileDialog has no Qt-equivalent yet + QString fileFilterKDEStyle(bool includeAllFiles, const QLinkedList& extensions) const; + QString fileFilterQtStyle(bool includeAllFiles, const QLinkedList& extensions) const; + + bool isTexFile(const QString &fileName) const; + bool isTexFile(const QUrl &url) const { + return isTexFile(url.fileName()); + } + bool isBibFile(const QString &fileName) const; + bool isBibFile(const QUrl &url) const { + return isBibFile(url.fileName()); + } + bool isScriptFile(const QString &fileName) const; + bool isScriptFile(const QUrl &url) const { + return isScriptFile(url.fileName()); + } + bool isProjectFile(const QString &fileName) const; + bool isProjectFile(const QUrl &url) const { + return isProjectFile(url.fileName()); + } + + bool isLatexDocument(const QString &ext) const { + return validExtension(ext,m_documents); + } + bool isLatexPackage(const QString &ext) const { + return validExtension(ext,m_packages); + } + bool isImage(const QString &ext) const { + return validExtension(ext,m_images); + } + + KileDocument::Type determineDocumentType(const QUrl &url) const; + QString defaultExtensionForDocumentType(KileDocument::Type type) const; private: - QString m_documents, m_packages; - QString m_bibtex, m_metapost; - QString m_images, m_script; - QString m_project; - - QString m_latexDefault, m_bibtexDefault; - QString m_metapostDefault, m_scriptDefault; - QString m_projectDefault; - - bool isBibtex(const QString &ext) const { return validExtension(ext,m_bibtex); } - bool isMetapost(const QString &ext) const { return validExtension(ext,m_metapost); } - bool isScript(const QString &ext) const { return validExtension(ext,m_script); } - bool isProject(const QString &ext) const { return validExtension(ext,m_project); } - bool validExtension(const QString &ext, const QString &extensions) const; - - void fileFilterRaw(ExtensionType type, QString& ext, QString& text) const; - QString fileFilterKDEStyle(ExtensionType type) const; - QString fileFilterQtStyle(ExtensionType type) const; + QString m_documents, m_packages; + QString m_bibtex, m_metapost; + QString m_images, m_script; + QString m_project; + + QString m_latexDefault, m_bibtexDefault; + QString m_metapostDefault, m_scriptDefault; + QString m_projectDefault; + + bool isBibtex(const QString &ext) const { + return validExtension(ext,m_bibtex); + } + bool isMetapost(const QString &ext) const { + return validExtension(ext,m_metapost); + } + bool isScript(const QString &ext) const { + return validExtension(ext,m_script); + } + bool isProject(const QString &ext) const { + return validExtension(ext,m_project); + } + bool validExtension(const QString &ext, const QString &extensions) const; + + void fileFilterRaw(ExtensionType type, QString& ext, QString& text) const; + QString fileFilterKDEStyle(ExtensionType type) const; + QString fileFilterQtStyle(ExtensionType type) const; }; } #endif diff --git a/src/kilehelp.cpp b/src/kilehelp.cpp index cbfabb28..4496de23 100644 --- a/src/kilehelp.cpp +++ b/src/kilehelp.cpp @@ -1,402 +1,402 @@ /********************************************************************************************** Copyright (C) 2004-2012 by Holger Danielsson (holger.danielsson@versanet.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. * * * ***************************************************************************/ #include #include #include #include #include "editorextension.h" #include "errorhandler.h" #include "kilehelp.h" #include "kiledebug.h" #include "kiletool_enums.h" #include "kiletoolmanager.h" #include "kileviewmanager.h" #include "kileinfo.h" #include "dialogs/texdocumentationdialog.h" #include "kileconfig.h" // tbraun 27.06.2007 // it _looks_ like texlive 2007 has the same layout than texlive 2005 so don't get confused about the variable names :) namespace KileHelp { - Help::Help(KileDocument::EditorExtension *edit, QWidget *mainWindow) : m_mainWindow(mainWindow), m_edit(edit), m_userhelp(Q_NULLPTR) - { - m_helpDir = QStandardPaths::locate(QStandardPaths::DataLocation, "help/", QStandardPaths::LocateDirectory); // this must end in '/' - KILE_DEBUG_MAIN << "help dir: " << m_helpDir; - - m_kileReference = m_helpDir + "latexhelp.html"; - m_latex2eReference = m_helpDir + "latex2e-texlive.html"; - - m_contextHelpType = contextHelpType(); - initTexDocumentation(); - initContextHelp(); - } - - Help::~Help() - { - delete m_userhelp; - } - - void Help::initTexDocumentation() - { - // use documentation for teTeX v3.x, TexLive 2005-2007, TexLive 2009, TexLive2 010-2011 (TUG) - m_texdocPath = KileConfig::location(); - - // first check for TexLive 2010-2011 (TUG) - m_texlivePath = locateTexLive201x(); - if ( !m_texlivePath.isEmpty() ) { - KILE_DEBUG_MAIN << "found TexLive 2010-2011 (TUG): " << m_texlivePath; - m_texVersion = TEXLIVE_201x_TUG; - m_texVersionText = "TexLive " + m_texlivePath.right(4) + " (TUG)"; - m_texrefsReference = "/generic/tex-refs/"; - return; - } - - // then check for TexLive 2009 (as found with Debian, Ubuntu, ...) - QDir dir(m_texdocPath + "/generic/tex-refs/"); - if ( dir.exists() ) { - KILE_DEBUG_MAIN << "found TexLive 2009: " << m_texdocPath; - m_texVersion = TEXLIVE2009; - m_texVersionText = "TexLive 2009"; - m_texrefsReference = "/generic/tex-refs/"; - return; - } - - // then check for older versions of TexLive 2005-2007 - dir.setPath(m_texdocPath + "/english/tex-refs"); - if ( dir.exists() ) { - KILE_DEBUG_MAIN << "found TexLive 2005-2007: " << m_texdocPath; - m_texVersion = TEXLIVE2005; - m_texVersionText = "TexLive 2005-2007"; - m_texrefsReference = "/english/tex-refs/"; - return; - } - - // finally we check for tetex3 - dir.setPath(m_texdocPath + "/latex/tex-refs"); - if ( dir.exists() ) { - m_texVersion = TETEX3; - m_texVersionText = "teTeX v3.x"; - // check if this is buggy tetex3.0 or an updated version with subdirectory 'html' - dir.setPath(m_texdocPath + "/latex/tex-refs/html"); - m_texrefsReference = ( dir.exists() ) ? "/latex/tex-refs/html/" : "/latex/tex-refs/"; - return; - } - - // found no tex documents for LaTeX help - m_texVersion = TEX_UNKNOWN; - } - - void Help::initContextHelp() - { - // read a list with keywords for context help - if ( m_contextHelpType == HelpKileRefs ) { - readHelpList("latex-kile.lst"); - } - else if ( m_contextHelpType == HelpLatex2eRefs ) { - readHelpList("latex2e-texlive.lst"); - } - else if ( m_contextHelpType == HelpTexRefs ) { - QString keyfile = ( m_texVersion != TETEX3 ) ? "latex-texlive-3.9.lst" : "latex-tetex3.lst"; - readHelpList(keyfile); - } - } - - QString Help::locateTexLivePath(const QStringList &paths) - { - QString sep = QDir::separator(); - QRegExp re( sep + "texlive" + sep + "(201\\d)" + sep ); - - for (QStringList::ConstIterator it = paths.begin(); it != paths.end(); ++it) { - // Remove any leading or trailing ", this is commonly used in the environment variables - QString path = (*it); - if (path.startsWith("\"")) - path = path.right(path.length() - 1); - if (path.endsWith("\"")) - path = path.left(path.length() - 1); - - if ( re.indexIn(path) > 0 ) { - return path.left(re.pos(1)+4); - } - } - return QString(); - } - - QString Help::locateTexLive201x() - { +Help::Help(KileDocument::EditorExtension *edit, QWidget *mainWindow) : m_mainWindow(mainWindow), m_edit(edit), m_userhelp(Q_NULLPTR) +{ + m_helpDir = QStandardPaths::locate(QStandardPaths::DataLocation, "help/", QStandardPaths::LocateDirectory); // this must end in '/' + KILE_DEBUG_MAIN << "help dir: " << m_helpDir; + + m_kileReference = m_helpDir + "latexhelp.html"; + m_latex2eReference = m_helpDir + "latex2e-texlive.html"; + + m_contextHelpType = contextHelpType(); + initTexDocumentation(); + initContextHelp(); +} + +Help::~Help() +{ + delete m_userhelp; +} + +void Help::initTexDocumentation() +{ + // use documentation for teTeX v3.x, TexLive 2005-2007, TexLive 2009, TexLive2 010-2011 (TUG) + m_texdocPath = KileConfig::location(); + + // first check for TexLive 2010-2011 (TUG) + m_texlivePath = locateTexLive201x(); + if ( !m_texlivePath.isEmpty() ) { + KILE_DEBUG_MAIN << "found TexLive 2010-2011 (TUG): " << m_texlivePath; + m_texVersion = TEXLIVE_201x_TUG; + m_texVersionText = "TexLive " + m_texlivePath.right(4) + " (TUG)"; + m_texrefsReference = "/generic/tex-refs/"; + return; + } + + // then check for TexLive 2009 (as found with Debian, Ubuntu, ...) + QDir dir(m_texdocPath + "/generic/tex-refs/"); + if ( dir.exists() ) { + KILE_DEBUG_MAIN << "found TexLive 2009: " << m_texdocPath; + m_texVersion = TEXLIVE2009; + m_texVersionText = "TexLive 2009"; + m_texrefsReference = "/generic/tex-refs/"; + return; + } + + // then check for older versions of TexLive 2005-2007 + dir.setPath(m_texdocPath + "/english/tex-refs"); + if ( dir.exists() ) { + KILE_DEBUG_MAIN << "found TexLive 2005-2007: " << m_texdocPath; + m_texVersion = TEXLIVE2005; + m_texVersionText = "TexLive 2005-2007"; + m_texrefsReference = "/english/tex-refs/"; + return; + } + + // finally we check for tetex3 + dir.setPath(m_texdocPath + "/latex/tex-refs"); + if ( dir.exists() ) { + m_texVersion = TETEX3; + m_texVersionText = "teTeX v3.x"; + // check if this is buggy tetex3.0 or an updated version with subdirectory 'html' + dir.setPath(m_texdocPath + "/latex/tex-refs/html"); + m_texrefsReference = ( dir.exists() ) ? "/latex/tex-refs/html/" : "/latex/tex-refs/"; + return; + } + + // found no tex documents for LaTeX help + m_texVersion = TEX_UNKNOWN; +} + +void Help::initContextHelp() +{ + // read a list with keywords for context help + if ( m_contextHelpType == HelpKileRefs ) { + readHelpList("latex-kile.lst"); + } + else if ( m_contextHelpType == HelpLatex2eRefs ) { + readHelpList("latex2e-texlive.lst"); + } + else if ( m_contextHelpType == HelpTexRefs ) { + QString keyfile = ( m_texVersion != TETEX3 ) ? "latex-texlive-3.9.lst" : "latex-tetex3.lst"; + readHelpList(keyfile); + } +} + +QString Help::locateTexLivePath(const QStringList &paths) +{ + QString sep = QDir::separator(); + QRegExp re( sep + "texlive" + sep + "(201\\d)" + sep ); + + for (QStringList::ConstIterator it = paths.begin(); it != paths.end(); ++it) { + // Remove any leading or trailing ", this is commonly used in the environment variables + QString path = (*it); + if (path.startsWith("\"")) + path = path.right(path.length() - 1); + if (path.endsWith("\"")) + path = path.left(path.length() - 1); + + if ( re.indexIn(path) > 0 ) { + return path.left(re.pos(1)+4); + } + } + return QString(); +} + +QString Help::locateTexLive201x() +{ #if defined(Q_OS_WIN32) - QRegExp splitReg("[;,]"); + QRegExp splitReg("[;,]"); #else - QRegExp splitReg("[:]"); + QRegExp splitReg("[:]"); #endif - QStringList paths = QString::fromLocal8Bit(getenv("PATH")).split(splitReg, QString::SkipEmptyParts); - return locateTexLivePath(paths); + QStringList paths = QString::fromLocal8Bit(getenv("PATH")).split(splitReg, QString::SkipEmptyParts); + return locateTexLivePath(paths); +} + +////////////////////// update paths and context help of TeX documentation ////////////////////// + +void Help::update() +{ + if ( m_texdocPath != KileConfig::location() ) { + initTexDocumentation(); + } + + HelpType contextHelp = contextHelpType(); + if ( m_contextHelpType != contextHelp ) { + m_contextHelpType = contextHelp; + initContextHelp(); + } } - ////////////////////// update paths and context help of TeX documentation ////////////////////// - - void Help::update() - { - if ( m_texdocPath != KileConfig::location() ) { - initTexDocumentation(); - } - - HelpType contextHelp = contextHelpType(); - if ( m_contextHelpType != contextHelp ) { - m_contextHelpType = contextHelp; - initContextHelp(); - } - } - - ////////////////////// set parameter/initialize user help ////////////////////// - - void Help::setUserhelp(KileTool::Manager *manager, KActionMenu *userHelpActionMenu) - { - m_manager = manager; - m_userhelp = new UserHelp(manager, userHelpActionMenu, m_mainWindow); - } - - void Help::enableUserhelpEntries(bool state) - { - if(m_userhelp) { - m_userhelp->enableUserHelpEntries(state); - } - } - ////////////////////// show help ////////////////////// - - void Help::showHelpFile(const QString ¶meter) - { - KILE_DEBUG_MAIN << "--------------------------------------------> help file: " << parameter; - KileTool::Base *tool = m_manager->createTool("ViewHTML", QString(), false); - if(!tool) { - return; - } - tool->setFlags(KileTool::NeedSourceExists | KileTool::NeedSourceRead); - //FIXME strip the #label part of the source (not the target), - //somehow this is already done somewhere (by accident), - //bad to rely on it - tool->setMsg(KileTool::NeedSourceExists, ki18n("Could not find the LaTeX documentation at %1; please set the correct path in Settings->Configure Kile->Help.")); - tool->setSource(parameter); - tool->setTargetPath(parameter); - tool->prepareToRun(); - m_manager->run(tool); - } - - void Help::helpKeyword() - { - //FIXME: we should have a better way to access the current view - helpKeyword(m_manager->info()->viewManager()->currentTextView()); - } +////////////////////// set parameter/initialize user help ////////////////////// + +void Help::setUserhelp(KileTool::Manager *manager, KActionMenu *userHelpActionMenu) +{ + m_manager = manager; + m_userhelp = new UserHelp(manager, userHelpActionMenu, m_mainWindow); +} + +void Help::enableUserhelpEntries(bool state) +{ + if(m_userhelp) { + m_userhelp->enableUserHelpEntries(state); + } +} +////////////////////// show help ////////////////////// + +void Help::showHelpFile(const QString ¶meter) +{ + KILE_DEBUG_MAIN << "--------------------------------------------> help file: " << parameter; + KileTool::Base *tool = m_manager->createTool("ViewHTML", QString(), false); + if(!tool) { + return; + } + tool->setFlags(KileTool::NeedSourceExists | KileTool::NeedSourceRead); + //FIXME strip the #label part of the source (not the target), + //somehow this is already done somewhere (by accident), + //bad to rely on it + tool->setMsg(KileTool::NeedSourceExists, ki18n("Could not find the LaTeX documentation at %1; please set the correct path in Settings->Configure Kile->Help.")); + tool->setSource(parameter); + tool->setTargetPath(parameter); + tool->prepareToRun(); + m_manager->run(tool); +} + +void Help::helpKeyword() +{ + //FIXME: we should have a better way to access the current view + helpKeyword(m_manager->info()->viewManager()->currentTextView()); +} ////////////////////// Help: TexDoc ////////////////////// - void Help::helpDocBrowser() - { - KileDialog::TexDocDialog *dlg = new KileDialog::TexDocDialog(); - dlg->exec(); - delete dlg; - } +void Help::helpDocBrowser() +{ + KileDialog::TexDocDialog *dlg = new KileDialog::TexDocDialog(); + dlg->exec(); + delete dlg; +} ////////////////////// Help: TeTeX ////////////////////// - void Help::helpTexGuide() - { - QString filename = m_texdocPath; - - switch(m_texVersion) { - case TEXLIVE_201x_TUG: - filename = filename.replace("texmf-dist","texmf"); - filename += "/texlive/texlive-en/texlive-en.html"; - break; - case TEXLIVE2009: - filename += "/texlive/texlive-en/texlive-en.html"; - break; - case TEXLIVE2005: - filename += "/english/texlive-en/live.html"; - break; - case TETEX3: - filename += "/index.html"; - break; - default: - return; - } - - KILE_DEBUG_MAIN << "show TeX Guide: " << m_texVersionText << " file=" << filename; - showHelpFile( filename ); - } +void Help::helpTexGuide() +{ + QString filename = m_texdocPath; + + switch(m_texVersion) { + case TEXLIVE_201x_TUG: + filename = filename.replace("texmf-dist","texmf"); + filename += "/texlive/texlive-en/texlive-en.html"; + break; + case TEXLIVE2009: + filename += "/texlive/texlive-en/texlive-en.html"; + break; + case TEXLIVE2005: + filename += "/english/texlive-en/live.html"; + break; + case TETEX3: + filename += "/index.html"; + break; + default: + return; + } + + KILE_DEBUG_MAIN << "show TeX Guide: " << m_texVersionText << " file=" << filename; + showHelpFile( filename ); +} ////////////////////// Help: LaTeX ////////////////////// - void Help::helpLatex(HelpType type) - { - QString filename; - // use older 'tex-refs' documentation, if this document is present and explicitly wanted - // in all other cases use current TexLive documentation (latex2e-texlive.html) - if ( m_contextHelpType==HelpTexRefs && m_texVersion!=TETEX3 ) { - QString link; - switch(type) { - case HelpLatexIndex: - link = "tex-refs.html#latex"; - break; - case HelpLatexCommand: - link = "tex-refs.html#tex-refs-idx"; - break; - case HelpLatexSubject: - link = "tex-refs.html#commands"; - break; - case HelpLatexEnvironment: - link = "tex-refs.html#env-latex"; - break; - default: - return; - } - filename = m_texdocPath + m_texrefsReference + link; - } - else { - QString link; - switch(type) { - case HelpLatexIndex: - link = "LaTeX2e"; - break; - case HelpLatexCommand: - link = "Command-Index"; - break; - case HelpLatexSubject: - link = "SEC_Overview"; - break; - case HelpLatexEnvironment: - link = "Environments"; - break; - default: - return; - } - filename = m_latex2eReference + "#" + link; - } - - // show help file - KILE_DEBUG_MAIN << "show LaTeX help: " << m_texVersionText << " file=" << filename; - showHelpFile( filename ); - } - - ////////////////////// Help: Keyword ////////////////////// - - // Context help: user either current TexLive's Latex2e help, TexLive's older tex-refs help or Kile LaTeX help - void Help::helpKeyword(KTextEditor::View *view) - { - QString word = getKeyword(view); - KILE_DEBUG_MAIN << "keyword: " << word; - - if ( !m_helpDir.isEmpty() && !word.isEmpty() && m_dictHelpTex.contains(word) ) { - KILE_DEBUG_MAIN << "about to show help for '" << word << "' (section " << m_dictHelpTex[word] << " )"; - - if ( m_contextHelpType == HelpLatex2eRefs ) { - showHelpFile( m_latex2eReference + "#" + m_dictHelpTex[word] ); - } - else if ( m_contextHelpType == HelpTexRefs ) { - showHelpFile( m_texdocPath + m_texrefsReference + m_dictHelpTex[word] ); - } - else if ( m_contextHelpType == HelpKileRefs ) { - showHelpFile(m_kileReference + '#' + m_dictHelpTex[word]); - } - } - else { - noHelpAvailableFor(word); - } - } - - void Help::noHelpAvailableFor(const QString &word) - { - m_manager->info()->errorHandler()->printMessage(KileTool::Error, i18n("No help available for %1.", word), i18n("Help")); - } - - QString Help::getKeyword(KTextEditor::View *view) - { - if(!view) { - return QString(); - } - - // get current position - int row, col, col1, col2; - QString word; - KTextEditor::Document *doc = view->document(); - KTextEditor::Cursor cursor = view->cursorPosition(); - row = cursor.line(); - col = cursor.column(); - - if (m_edit->getCurrentWord(doc, row, col, KileDocument::EditorExtension::smTex, word, col1, col2)) { - // There is no starred keyword in the references. So if // dani 04.08.2004 - // we find one, we better try the unstarred keyword. - if(word.right(1) == "*") { - return word.left(word.length() - 1); - } - else { - return word; - } - } - else { - return QString(); - } - } - - HelpType Help::contextHelpType() - { - if ( KileConfig::latex2erefs() ) { - return HelpLatex2eRefs; - } - else if ( KileConfig::texrefs() ) { - return HelpTexRefs; - } - else { - return HelpKileRefs; - } - } +void Help::helpLatex(HelpType type) +{ + QString filename; + // use older 'tex-refs' documentation, if this document is present and explicitly wanted + // in all other cases use current TexLive documentation (latex2e-texlive.html) + if ( m_contextHelpType==HelpTexRefs && m_texVersion!=TETEX3 ) { + QString link; + switch(type) { + case HelpLatexIndex: + link = "tex-refs.html#latex"; + break; + case HelpLatexCommand: + link = "tex-refs.html#tex-refs-idx"; + break; + case HelpLatexSubject: + link = "tex-refs.html#commands"; + break; + case HelpLatexEnvironment: + link = "tex-refs.html#env-latex"; + break; + default: + return; + } + filename = m_texdocPath + m_texrefsReference + link; + } + else { + QString link; + switch(type) { + case HelpLatexIndex: + link = "LaTeX2e"; + break; + case HelpLatexCommand: + link = "Command-Index"; + break; + case HelpLatexSubject: + link = "SEC_Overview"; + break; + case HelpLatexEnvironment: + link = "Environments"; + break; + default: + return; + } + filename = m_latex2eReference + "#" + link; + } + + // show help file + KILE_DEBUG_MAIN << "show LaTeX help: " << m_texVersionText << " file=" << filename; + showHelpFile( filename ); +} + +////////////////////// Help: Keyword ////////////////////// + +// Context help: user either current TexLive's Latex2e help, TexLive's older tex-refs help or Kile LaTeX help +void Help::helpKeyword(KTextEditor::View *view) +{ + QString word = getKeyword(view); + KILE_DEBUG_MAIN << "keyword: " << word; + + if ( !m_helpDir.isEmpty() && !word.isEmpty() && m_dictHelpTex.contains(word) ) { + KILE_DEBUG_MAIN << "about to show help for '" << word << "' (section " << m_dictHelpTex[word] << " )"; + + if ( m_contextHelpType == HelpLatex2eRefs ) { + showHelpFile( m_latex2eReference + "#" + m_dictHelpTex[word] ); + } + else if ( m_contextHelpType == HelpTexRefs ) { + showHelpFile( m_texdocPath + m_texrefsReference + m_dictHelpTex[word] ); + } + else if ( m_contextHelpType == HelpKileRefs ) { + showHelpFile(m_kileReference + '#' + m_dictHelpTex[word]); + } + } + else { + noHelpAvailableFor(word); + } +} + +void Help::noHelpAvailableFor(const QString &word) +{ + m_manager->info()->errorHandler()->printMessage(KileTool::Error, i18n("No help available for %1.", word), i18n("Help")); +} + +QString Help::getKeyword(KTextEditor::View *view) +{ + if(!view) { + return QString(); + } + + // get current position + int row, col, col1, col2; + QString word; + KTextEditor::Document *doc = view->document(); + KTextEditor::Cursor cursor = view->cursorPosition(); + row = cursor.line(); + col = cursor.column(); + + if (m_edit->getCurrentWord(doc, row, col, KileDocument::EditorExtension::smTex, word, col1, col2)) { + // There is no starred keyword in the references. So if // dani 04.08.2004 + // we find one, we better try the unstarred keyword. + if(word.right(1) == "*") { + return word.left(word.length() - 1); + } + else { + return word; + } + } + else { + return QString(); + } +} + +HelpType Help::contextHelpType() +{ + if ( KileConfig::latex2erefs() ) { + return HelpLatex2eRefs; + } + else if ( KileConfig::texrefs() ) { + return HelpTexRefs; + } + else { + return HelpKileRefs; + } +} //////////////////// read help lists //////////////////// - void Help::readHelpList(const QString &filename) - { - // clear old map - m_dictHelpTex.clear(); +void Help::readHelpList(const QString &filename) +{ + // clear old map + m_dictHelpTex.clear(); - QString file = m_helpDir + filename; - if(file.isEmpty()) { - KILE_DEBUG_MAIN << " file not found: " << filename << endl; - return; - } + QString file = m_helpDir + filename; + if(file.isEmpty()) { + KILE_DEBUG_MAIN << " file not found: " << filename << endl; + return; + } // KILE_DEBUG_MAIN << " read file: " << filename << endl; - KILE_DEBUG_MAIN << "read keyword file: " << file; - QRegExp reg("\\s*(\\S+)\\s*=>\\s*(\\S+)"); - - QFile f(file); - if(f.open(QIODevice::ReadOnly)) { // file opened successfully - QTextStream t(&f); // use a text stream - while(!t.atEnd()) { // until end of file... - QString s = t.readLine().trimmed(); // line of text excluding '\n' - if(!(s.isEmpty() || s.at(0)=='#')) { - int pos = reg.indexIn(s); - if ( pos != -1 ) { - m_dictHelpTex[reg.cap(1)] = reg.cap(2); - } - } - } - f.close(); - } - } + KILE_DEBUG_MAIN << "read keyword file: " << file; + QRegExp reg("\\s*(\\S+)\\s*=>\\s*(\\S+)"); + + QFile f(file); + if(f.open(QIODevice::ReadOnly)) { // file opened successfully + QTextStream t(&f); // use a text stream + while(!t.atEnd()) { // until end of file... + QString s = t.readLine().trimmed(); // line of text excluding '\n' + if(!(s.isEmpty() || s.at(0)=='#')) { + int pos = reg.indexIn(s); + if ( pos != -1 ) { + m_dictHelpTex[reg.cap(1)] = reg.cap(2); + } + } + } + f.close(); + } +} } diff --git a/src/kilehelp.h b/src/kilehelp.h index af122509..5374a4fe 100644 --- a/src/kilehelp.h +++ b/src/kilehelp.h @@ -1,111 +1,123 @@ /*************************************************************************** begin : 2004 copyright : (C) 2004-2012 by Holger Danielsson (holger.danielsson@versanet.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. * * * ***************************************************************************/ #ifndef KILEHELP_H #define KILEHELP_H #include #include #include #include "editorextension.h" #include "userhelp.h" -namespace KileDocument { class EditorExtension; } +namespace KileDocument { +class EditorExtension; +} namespace KileHelp { - enum HelpType - { - HelpKileRefs, - HelpTexRefs, - HelpLatex2eRefs, - HelpLatexIndex, - HelpLatexCommand, - HelpLatexSubject, - HelpLatexEnvironment - }; - - enum TexVersion - { - TEXLIVE_201x_TUG, - TEXLIVE2009, - TEXLIVE2005, - TETEX3, - TEX_UNKNOWN - }; - - class Help : public QObject - { - Q_OBJECT - - public: - Help(KileDocument::EditorExtension *edit, QWidget *mainWindow); - ~Help(); - - void setUserhelp(KileTool::Manager *manager, KActionMenu *userHelpActionMenu); - void update(); - - // calls for help - void helpKeyword(KTextEditor::View *view); - void noHelpAvailableFor(const QString &word); - void userHelpDialog() { m_userhelp->userHelpDialog(); } - void enableUserhelpEntries(bool state); - - public Q_SLOTS: - void helpTexGuide(); - void helpLatexIndex() { helpLatex(KileHelp::HelpLatexIndex); } - void helpLatexCommand() { helpLatex(KileHelp::HelpLatexCommand); } - void helpLatexSubject() { helpLatex(KileHelp::HelpLatexSubject); } - void helpLatexEnvironment() { helpLatex(KileHelp::HelpLatexEnvironment); } - void helpKeyword(); - void helpDocBrowser(); - - private: - QWidget *m_mainWindow; - KileTool::Manager *m_manager; - KileDocument::EditorExtension *m_edit; - UserHelp *m_userhelp; - QString m_helpDir; - - TexVersion m_texVersion; - QString m_texVersionText; - QString m_texlivePath; - QString m_texdocPath; - - QString m_latex2eReference; - QString m_texrefsReference; - QString m_kileReference; - - HelpType m_contextHelpType; - QMap m_dictHelpTex; - - void initTexDocumentation(); - void initContextHelp(); - QString locateTexLivePath(const QStringList &paths); - QString locateTexLive201x(); - - void readHelpList(const QString &filename); - void showHelpFile(const QString ¶meter); - - void helpLatex(HelpType type); - QString getKeyword(KTextEditor::View *view); - HelpType contextHelpType(); - - }; +enum HelpType +{ + HelpKileRefs, + HelpTexRefs, + HelpLatex2eRefs, + HelpLatexIndex, + HelpLatexCommand, + HelpLatexSubject, + HelpLatexEnvironment +}; + +enum TexVersion +{ + TEXLIVE_201x_TUG, + TEXLIVE2009, + TEXLIVE2005, + TETEX3, + TEX_UNKNOWN +}; + +class Help : public QObject +{ + Q_OBJECT + +public: + Help(KileDocument::EditorExtension *edit, QWidget *mainWindow); + ~Help(); + + void setUserhelp(KileTool::Manager *manager, KActionMenu *userHelpActionMenu); + void update(); + + // calls for help + void helpKeyword(KTextEditor::View *view); + void noHelpAvailableFor(const QString &word); + void userHelpDialog() { + m_userhelp->userHelpDialog(); + } + void enableUserhelpEntries(bool state); + +public Q_SLOTS: + void helpTexGuide(); + void helpLatexIndex() { + helpLatex(KileHelp::HelpLatexIndex); + } + void helpLatexCommand() { + helpLatex(KileHelp::HelpLatexCommand); + } + void helpLatexSubject() { + helpLatex(KileHelp::HelpLatexSubject); + } + void helpLatexEnvironment() { + helpLatex(KileHelp::HelpLatexEnvironment); + } + void helpKeyword(); + void helpDocBrowser(); + +private: + QWidget *m_mainWindow; + KileTool::Manager *m_manager; + KileDocument::EditorExtension *m_edit; + UserHelp *m_userhelp; + QString m_helpDir; + + TexVersion m_texVersion; + QString m_texVersionText; + QString m_texlivePath; + QString m_texdocPath; + + QString m_latex2eReference; + QString m_texrefsReference; + QString m_kileReference; + + HelpType m_contextHelpType; + QMap m_dictHelpTex; + + void initTexDocumentation(); + void initContextHelp(); + QString locateTexLivePath(const QStringList &paths); + QString locateTexLive201x(); + + void readHelpList(const QString &filename); + void showHelpFile(const QString ¶meter); + + void helpLatex(HelpType type); + QString getKeyword(KTextEditor::View *view); + HelpType contextHelpType(); + +}; } #endif diff --git a/src/kileinfo.cpp b/src/kileinfo.cpp index 7d79d3db..cf13575a 100644 --- a/src/kileinfo.cpp +++ b/src/kileinfo.cpp @@ -1,446 +1,447 @@ /************************************************************************************* begin : Thu Jul 17 2003 copyright : (C) 2003 by Jeroen Wijnhout (Jeroen.Wijnhout@kdemail.net) 2007-2011 by Michel Ludwig (michel.ludwig@kdemail.net) *************************************************************************************/ /*************************************************************************** * * * 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. * * * ***************************************************************************/ // 2007-03-12 dani // - use KileDocument::Extensions #include "kileinfo.h" #include #include #include #include #include #include #include #include "parser/parsermanager.h" #include "widgets/structurewidget.h" #include "configurationmanager.h" #include "editorcommands.h" #include "kiledocmanager.h" #include "kileviewmanager.h" #include "documentinfo.h" #include "kileproject.h" #include "scriptmanager.h" #include "abbreviationmanager.h" #include "editorkeysequencemanager.h" #include "templates.h" #include "utilities.h" #include "usermenu/usermenu.h" #include #include /* * Class KileInfo. */ KileInfo::KileInfo(KParts::MainWindow *parent) - : m_mainWindow(parent) - , m_viewManager(Q_NULLPTR) - , m_manager(Q_NULLPTR) - , m_jScriptManager(Q_NULLPTR) - , m_toolFactory(Q_NULLPTR) - , m_texKonsole(Q_NULLPTR) - , m_errorHandler(Q_NULLPTR) - , m_edit(Q_NULLPTR) - , m_userMenu(Q_NULLPTR) + : m_mainWindow(parent) + , m_viewManager(Q_NULLPTR) + , m_manager(Q_NULLPTR) + , m_jScriptManager(Q_NULLPTR) + , m_toolFactory(Q_NULLPTR) + , m_texKonsole(Q_NULLPTR) + , m_errorHandler(Q_NULLPTR) + , m_edit(Q_NULLPTR) + , m_userMenu(Q_NULLPTR) { - m_configurationManager = new KileConfiguration::Manager(this, parent, "KileConfiguration::Manager"); - m_docManager = new KileDocument::Manager(this, parent, "KileDocument::Manager"); - m_templateManager = new KileTemplate::Manager(this, parent, "KileTemplate::Manager"); - m_editorKeySequenceManager = new KileEditorKeySequence::Manager(this, parent, "KileEditorKeySequence::Manager"); - m_abbreviationManager = new KileAbbreviation::Manager(this, parent); - m_parserManager = new KileParser::Manager(this, parent); - m_editorCommands = new EditorCommands(this); + m_configurationManager = new KileConfiguration::Manager(this, parent, "KileConfiguration::Manager"); + m_docManager = new KileDocument::Manager(this, parent, "KileDocument::Manager"); + m_templateManager = new KileTemplate::Manager(this, parent, "KileTemplate::Manager"); + m_editorKeySequenceManager = new KileEditorKeySequence::Manager(this, parent, "KileEditorKeySequence::Manager"); + m_abbreviationManager = new KileAbbreviation::Manager(this, parent); + m_parserManager = new KileParser::Manager(this, parent); + m_editorCommands = new EditorCommands(this); } KileInfo::~KileInfo() { - // this has to be deleted before the editor component is destroyed - delete m_editorCommands; + // this has to be deleted before the editor component is destroyed + delete m_editorCommands; } KTextEditor::Document * KileInfo::activeTextDocument() const { - KTextEditor::View *view = viewManager()->currentTextView(); - if (view) return view->document(); else return Q_NULLPTR; + KTextEditor::View *view = viewManager()->currentTextView(); + if (view) return view->document(); + else return Q_NULLPTR; } QString KileInfo::getName(KTextEditor::Document *doc, bool shrt) const { - KILE_DEBUG_MAIN << "===KileInfo::getName(KTextEditor::Document *doc, bool " << shrt << ")===" << endl; - QString title; - - if (!doc) { - doc = activeTextDocument(); - } - if (doc) { - QUrl url = doc->url(); - KILE_DEBUG_MAIN << "url " << url << endl; - if(url.isLocalFile()) { - title = shrt ? doc->url().fileName() : doc->url().toLocalFile(); - } - else { - title = url.toDisplayString(); - } - } - - return title; + KILE_DEBUG_MAIN << "===KileInfo::getName(KTextEditor::Document *doc, bool " << shrt << ")===" << endl; + QString title; + + if (!doc) { + doc = activeTextDocument(); + } + if (doc) { + QUrl url = doc->url(); + KILE_DEBUG_MAIN << "url " << url << endl; + if(url.isLocalFile()) { + title = shrt ? doc->url().fileName() : doc->url().toLocalFile(); + } + else { + title = url.toDisplayString(); + } + } + + return title; } LaTeXOutputHandler* KileInfo::findCurrentLaTeXOutputHandler() const { - LaTeXOutputHandler *h = Q_NULLPTR; + LaTeXOutputHandler *h = Q_NULLPTR; - getCompileName(false, &h); - return h; + getCompileName(false, &h); + return h; } QString KileInfo::getCompileName(bool shrt /* = false */, LaTeXOutputHandler** h /* = Q_NULLPTR */) const { - KileProject *project = docManager()->activeProject(); - - if (m_singlemode) { - if (project) { - if(h) { - *h = project; - } - return getCompileNameForProject(project, shrt); - } - else { - KTextEditor::Document *doc = activeTextDocument(); - if(h) { - *h = dynamic_cast(m_docManager->textInfoFor(doc)); - } - return getName(doc, shrt); - } - } - else { - QFileInfo fi(m_masterDocumentFileName); - if(h) { - *h = dynamic_cast(m_docManager->textInfoFor(m_masterDocumentFileName)); - } - if(shrt) { - return fi.fileName(); - } - else { - return m_masterDocumentFileName; - } - } + KileProject *project = docManager()->activeProject(); + + if (m_singlemode) { + if (project) { + if(h) { + *h = project; + } + return getCompileNameForProject(project, shrt); + } + else { + KTextEditor::Document *doc = activeTextDocument(); + if(h) { + *h = dynamic_cast(m_docManager->textInfoFor(doc)); + } + return getName(doc, shrt); + } + } + else { + QFileInfo fi(m_masterDocumentFileName); + if(h) { + *h = dynamic_cast(m_docManager->textInfoFor(m_masterDocumentFileName)); + } + if(shrt) { + return fi.fileName(); + } + else { + return m_masterDocumentFileName; + } + } } QString KileInfo::getCompileNameForProject(KileProject *project, bool shrt) const { - if (!project->masterDocument().isEmpty()) { - QUrl master(project->masterDocument()); - if(shrt) { - return master.fileName(); - } - else { - return master.toLocalFile(); - } - } - else { - KileProjectItem *item = project->rootItem(docManager()->activeProjectItem()); - if (item) { - QUrl url = item->url(); - if(shrt) { - return url.fileName(); - } - else { - return url.toLocalFile(); - } - } - else { - return QString(); - } - } + if (!project->masterDocument().isEmpty()) { + QUrl master(project->masterDocument()); + if(shrt) { + return master.fileName(); + } + else { + return master.toLocalFile(); + } + } + else { + KileProjectItem *item = project->rootItem(docManager()->activeProjectItem()); + if (item) { + QUrl url = item->url(); + if(shrt) { + return url.fileName(); + } + else { + return url.toLocalFile(); + } + } + else { + return QString(); + } + } } QString KileInfo::getFullFromPrettyName(const OutputInfo& info, const QString& name) const { - if(name.isEmpty()) { - return name; - } - - QString file = name; - - if(file.left(2) == "./") { - file = QFileInfo(info.mainSourceFile()).absolutePath() + '/' + file.mid(2); - } - - if(QDir::isRelativePath(file)) { - file = QFileInfo(info.mainSourceFile()).absolutePath() + '/' + file; - } - - QFileInfo fi(file); - if(file.isEmpty() || fi.isDir() || (! fi.exists()) || (! fi.isReadable())) { - // - call from logwidget or error handling, which - // tries to determine the LaTeX source file - bool found = false; - QStringList extlist = (m_extensions->latexDocuments()).split(' '); - for(QStringList::Iterator it=extlist.begin(); it!=extlist.end(); ++it) { - QString name = file + (*it); - if(QFileInfo(name).exists()) { - file = name; - fi.setFile(name); - found = true; - break; - } - } - if(!found) { - file.clear(); - } - } - - if(!fi.isReadable()) { - return QString(); - } - - return file; + if(name.isEmpty()) { + return name; + } + + QString file = name; + + if(file.left(2) == "./") { + file = QFileInfo(info.mainSourceFile()).absolutePath() + '/' + file.mid(2); + } + + if(QDir::isRelativePath(file)) { + file = QFileInfo(info.mainSourceFile()).absolutePath() + '/' + file; + } + + QFileInfo fi(file); + if(file.isEmpty() || fi.isDir() || (! fi.exists()) || (! fi.isReadable())) { + // - call from logwidget or error handling, which + // tries to determine the LaTeX source file + bool found = false; + QStringList extlist = (m_extensions->latexDocuments()).split(' '); + for(QStringList::Iterator it=extlist.begin(); it!=extlist.end(); ++it) { + QString name = file + (*it); + if(QFileInfo(name).exists()) { + file = name; + fi.setFile(name); + found = true; + break; + } + } + if(!found) { + file.clear(); + } + } + + if(!fi.isReadable()) { + return QString(); + } + + return file; } QList KileInfo::getParentsFor(KileDocument::Info *info) { - QList items = docManager()->itemsFor(info); - QList list; - for(QList::iterator it = items.begin(); it != items.end(); ++it) { - if((*it)->parent()) { - list.append((*it)->parent()->url()); - } - } - return list; + QList items = docManager()->itemsFor(info); + QList list; + for(QList::iterator it = items.begin(); it != items.end(); ++it) { + if((*it)->parent()) { + list.append((*it)->parent()->url()); + } + } + return list; } QStringList KileInfo::retrieveList(QStringList (KileDocument::Info::*getit)() const, KileDocument::TextInfo *docinfo) { - if(!docinfo) { - docinfo = docManager()->getInfo(); - } - KileProjectItem *item = docManager()->itemFor(docinfo, docManager()->activeProject()); - - KILE_DEBUG_MAIN << "Kile::retrieveList()"; - if (item) { - KileProject *project = item->project(); - KileProjectItem *root = project->rootItem(item); - if (root) { - KILE_DEBUG_MAIN << "\tusing root item " << root->url().fileName(); - - QList children; - children.append(root); - root->allChildren(&children); - - QStringList toReturn; - for(QList::iterator it = children.begin(); it != children.end(); ++it) { - const KileProjectItem *item = *it; - KileDocument::TextInfo *textInfo = item->getInfo(); - KILE_DEBUG_MAIN << "\t" << item->url(); - - if(textInfo) { - toReturn << (textInfo->*getit)(); - } - } - return toReturn; - } - else { - return QStringList(); - } - } - else if (docinfo) { - return (docinfo->*getit)(); - } - else { - return QStringList(); - } + if(!docinfo) { + docinfo = docManager()->getInfo(); + } + KileProjectItem *item = docManager()->itemFor(docinfo, docManager()->activeProject()); + + KILE_DEBUG_MAIN << "Kile::retrieveList()"; + if (item) { + KileProject *project = item->project(); + KileProjectItem *root = project->rootItem(item); + if (root) { + KILE_DEBUG_MAIN << "\tusing root item " << root->url().fileName(); + + QList children; + children.append(root); + root->allChildren(&children); + + QStringList toReturn; + for(QList::iterator it = children.begin(); it != children.end(); ++it) { + const KileProjectItem *item = *it; + KileDocument::TextInfo *textInfo = item->getInfo(); + KILE_DEBUG_MAIN << "\t" << item->url(); + + if(textInfo) { + toReturn << (textInfo->*getit)(); + } + } + return toReturn; + } + else { + return QStringList(); + } + } + else if (docinfo) { + return (docinfo->*getit)(); + } + else { + return QStringList(); + } } QStringList KileInfo::allLabels(KileDocument::TextInfo *info) { - KILE_DEBUG_MAIN << "Kile::allLabels()" << endl; - return retrieveList(&KileDocument::Info::labels, info); + KILE_DEBUG_MAIN << "Kile::allLabels()" << endl; + return retrieveList(&KileDocument::Info::labels, info); } QStringList KileInfo::allBibItems(KileDocument::TextInfo *info) { - KILE_DEBUG_MAIN << "Kile::allBibItems()" << endl; - return retrieveList(&KileDocument::Info::bibItems, info); + KILE_DEBUG_MAIN << "Kile::allBibItems()" << endl; + return retrieveList(&KileDocument::Info::bibItems, info); } QStringList KileInfo::allBibliographies(KileDocument::TextInfo *info) { - KILE_DEBUG_MAIN << "Kile::bibliographies()" << endl; - return retrieveList(&KileDocument::Info::bibliographies, info); + KILE_DEBUG_MAIN << "Kile::bibliographies()" << endl; + return retrieveList(&KileDocument::Info::bibliographies, info); } QStringList KileInfo::allDependencies(KileDocument::TextInfo *info) { - KILE_DEBUG_MAIN << "Kile::dependencies()" << endl; - return retrieveList(&KileDocument::Info::dependencies, info); + KILE_DEBUG_MAIN << "Kile::dependencies()" << endl; + return retrieveList(&KileDocument::Info::dependencies, info); } QStringList KileInfo::allNewCommands(KileDocument::TextInfo *info) { - KILE_DEBUG_MAIN << "Kile::newCommands()" << endl; - return retrieveList(&KileDocument::Info::newCommands, info); + KILE_DEBUG_MAIN << "Kile::newCommands()" << endl; + return retrieveList(&KileDocument::Info::newCommands, info); } QStringList KileInfo::allAsyFigures(KileDocument::TextInfo *info) { - KILE_DEBUG_MAIN << "Kile::asyFigures()" << endl; - return retrieveList(&KileDocument::Info::asyFigures, info); + KILE_DEBUG_MAIN << "Kile::asyFigures()" << endl; + return retrieveList(&KileDocument::Info::asyFigures, info); } QStringList KileInfo::allPackages(KileDocument::TextInfo *info) { - KILE_DEBUG_MAIN << "Kile::allPackages()" << endl; - return retrieveList(&KileDocument::Info::packages, info); + KILE_DEBUG_MAIN << "Kile::allPackages()" << endl; + return retrieveList(&KileDocument::Info::packages, info); } QString KileInfo::lastModifiedFile(KileDocument::TextInfo* info) { - if(!info) { - info = docManager()->getInfo(); - } - QStringList list = allDependencies(info); - QFileInfo fileinfo(info->url().toLocalFile()); - list.append(fileinfo.fileName()); - - return KileUtilities::lastModifiedFile(list, fileinfo.absolutePath()); + if(!info) { + info = docManager()->getInfo(); + } + QStringList list = allDependencies(info); + QFileInfo fileinfo(info->url().toLocalFile()); + list.append(fileinfo.fileName()); + + return KileUtilities::lastModifiedFile(list, fileinfo.absolutePath()); } QString KileInfo::documentTypeToString(KileDocument::Type type) { - switch(type) { - case KileDocument::Undefined: - return i18n("Undefined"); - case KileDocument::Text: - return i18n("Text"); - case KileDocument::LaTeX: - return i18n("LaTeX"); - case KileDocument::BibTeX: - return i18n("BibTeX"); - case KileDocument::Script: - return i18n("Script"); - } - return QString(); + switch(type) { + case KileDocument::Undefined: + return i18n("Undefined"); + case KileDocument::Text: + return i18n("Text"); + case KileDocument::LaTeX: + return i18n("LaTeX"); + case KileDocument::BibTeX: + return i18n("BibTeX"); + case KileDocument::Script: + return i18n("Script"); + } + return QString(); } bool KileInfo::similarOrEqualURL(const QUrl &validurl, const QUrl &testurl) { - if ( testurl.isEmpty() || testurl.path().isEmpty() ) return false; + if ( testurl.isEmpty() || testurl.path().isEmpty() ) return false; - bool absolute = QDir::isAbsolutePath(testurl.toLocalFile()); - return ( - (validurl == testurl) || - (!absolute && validurl.path().endsWith(testurl.path())) - ); + bool absolute = QDir::isAbsolutePath(testurl.toLocalFile()); + return ( + (validurl == testurl) || + (!absolute && validurl.path().endsWith(testurl.path())) + ); } bool KileInfo::isOpen(const QUrl &url) { - KILE_DEBUG_MAIN << "==bool KileInfo::isOpen(const QUrl &url)=============" << endl; + KILE_DEBUG_MAIN << "==bool KileInfo::isOpen(const QUrl &url)=============" << endl; - for (int i = 0; i < viewManager()->textViewCount(); ++i) { - KTextEditor::View *view = viewManager()->textView(i); - if (view->document() && similarOrEqualURL(view->document()->url(), url)) { - return true; - } - } + for (int i = 0; i < viewManager()->textViewCount(); ++i) { + KTextEditor::View *view = viewManager()->textView(i); + if (view->document() && similarOrEqualURL(view->document()->url(), url)) { + return true; + } + } - return false; + return false; } bool KileInfo::projectIsOpen(const QUrl &url) { - KileProject *project = docManager()->projectFor(url); + KileProject *project = docManager()->projectFor(url); - return project != 0 ; + return project != 0 ; } QString KileInfo::getSelection() const { - KTextEditor::View *view = viewManager()->currentTextView(); + KTextEditor::View *view = viewManager()->currentTextView(); - if (view && view->selection()) { - return view->selectionText(); - } + if (view && view->selection()) { + return view->selectionText(); + } - return QString(); + return QString(); } void KileInfo::clearSelection() const { - KTextEditor::View *view = viewManager()->currentTextView(); + KTextEditor::View *view = viewManager()->currentTextView(); - if(view && view->selection()) { - view->removeSelectionText(); - } + if(view && view->selection()) { + view->removeSelectionText(); + } } QString KileInfo::expandEnvironmentVars(const QString &str) { - static QRegExp reEnvVars("\\$(\\w+)"); - QString result = str; - int index = -1; - while ( (index = str.indexOf(reEnvVars, index + 1)) != -1 ) - result.replace(reEnvVars.cap(0),qgetenv(reEnvVars.cap(1).toLocal8Bit())); + static QRegExp reEnvVars("\\$(\\w+)"); + QString result = str; + int index = -1; + while ( (index = str.indexOf(reEnvVars, index + 1)) != -1 ) + result.replace(reEnvVars.cap(0),qgetenv(reEnvVars.cap(1).toLocal8Bit())); - return result; + return result; } QString KileInfo::checkOtherPaths(const QString &path,const QString &file, int type) { - KILE_DEBUG_MAIN << "QString KileInfo::checkOtherPaths(const QString &path,const QString &file, int type)" << endl; - QStringList inputpaths; - QString configpaths; - QFileInfo info; - - switch(type) - { - case bibinputs: - configpaths = KileConfig::bibInputPaths() + PATH_SEPARATOR + "$BIBINPUTS"; - break; - case texinputs: - configpaths = KileConfig::teXPaths() + PATH_SEPARATOR + "$TEXINPUTS"; - break; - case bstinputs: - configpaths = KileConfig::bstInputPaths() + PATH_SEPARATOR + "$BSTINPUTS"; - break; - default: - KILE_DEBUG_MAIN << "Unknown type in checkOtherPaths" << endl; - return QString(); - break; - } - - inputpaths = expandEnvironmentVars(configpaths).split(PATH_SEPARATOR); - inputpaths.prepend(path); - - // the first match is supposed to be the correct one - foreach(const QString &string, inputpaths){ - KILE_DEBUG_MAIN << "path is " << string << "and file is " << file << endl; - info.setFile(string + '/' + file); - if(info.exists()) { - KILE_DEBUG_MAIN << "filepath after correction is: " << info.path() << endl; - return info.absoluteFilePath(); - } - } - return QString(); + KILE_DEBUG_MAIN << "QString KileInfo::checkOtherPaths(const QString &path,const QString &file, int type)" << endl; + QStringList inputpaths; + QString configpaths; + QFileInfo info; + + switch(type) + { + case bibinputs: + configpaths = KileConfig::bibInputPaths() + PATH_SEPARATOR + "$BIBINPUTS"; + break; + case texinputs: + configpaths = KileConfig::teXPaths() + PATH_SEPARATOR + "$TEXINPUTS"; + break; + case bstinputs: + configpaths = KileConfig::bstInputPaths() + PATH_SEPARATOR + "$BSTINPUTS"; + break; + default: + KILE_DEBUG_MAIN << "Unknown type in checkOtherPaths" << endl; + return QString(); + break; + } + + inputpaths = expandEnvironmentVars(configpaths).split(PATH_SEPARATOR); + inputpaths.prepend(path); + + // the first match is supposed to be the correct one + foreach(const QString &string, inputpaths) { + KILE_DEBUG_MAIN << "path is " << string << "and file is " << file << endl; + info.setFile(string + '/' + file); + if(info.exists()) { + KILE_DEBUG_MAIN << "filepath after correction is: " << info.path() << endl; + return info.absoluteFilePath(); + } + } + return QString(); } diff --git a/src/kileinfo.h b/src/kileinfo.h index 015c118e..23623d68 100644 --- a/src/kileinfo.h +++ b/src/kileinfo.h @@ -1,205 +1,312 @@ /************************************************************************************** begin : Thu Jul 17 2003 copyright : (C) 2003 by Jeroen Wijnhout (Jeroen.Wijnhout@kdemail.net) 2007-2011 by Michel Ludwig (michel.ludwig@kdemail.net) **************************************************************************************/ /*************************************************************************** * * * 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. * * * ***************************************************************************/ #ifndef KILEINFO_H #define KILEINFO_H #include #include #include "kiledebug.h" #include #include #include "kileconstants.h" #include "kileextensions.h" #include "kiletoolmanager.h" #include "kilestdtools.h" #include "outputinfo.h" #include "latexcmd.h" #include "kileconfig.h" class QWidget; -namespace KileDocument { class Info; class TextInfo; } +namespace KileDocument { +class Info; +class TextInfo; +} class KileErrorHandler; class KileProject; class KileProjectItem; class KileProjectItemList; -namespace KTextEditor { class Document;} - -namespace KileConfiguration{ class Manager; } -namespace KileDocument { class Extensions; class Manager; class EditorExtension; } -namespace KileView { class Manager; } -namespace KileWidget { class StructureWidget; class Konsole; class ScriptsManagement; class PreviewWidget; class ExtendedScrollArea; class FileBrowserWidget; class OutputView; class BottomBar; } -namespace KileTool { class QuickPreview; class LivePreviewManager; } -namespace KileHelp { class Help; } -namespace KileScript { class Manager; } -namespace KileEditorKeySequence { class Manager; } -namespace KileTemplate { class Manager; } -namespace KileCodeCompletion { class Manager; } -namespace KileAbbreviation { class Manager; } -namespace KileParser { class Manager; } - -namespace KileMenu { class UserMenu; } +namespace KTextEditor { +class Document; +} + +namespace KileConfiguration { +class Manager; +} +namespace KileDocument { +class Extensions; +class Manager; +class EditorExtension; +} +namespace KileView { +class Manager; +} +namespace KileWidget { +class StructureWidget; +class Konsole; +class ScriptsManagement; +class PreviewWidget; +class ExtendedScrollArea; +class FileBrowserWidget; +class OutputView; +class BottomBar; +} +namespace KileTool { +class QuickPreview; +class LivePreviewManager; +} +namespace KileHelp { +class Help; +} +namespace KileScript { +class Manager; +} +namespace KileEditorKeySequence { +class Manager; +} +namespace KileTemplate { +class Manager; +} +namespace KileCodeCompletion { +class Manager; +} +namespace KileAbbreviation { +class Manager; +} +namespace KileParser { +class Manager; +} + +namespace KileMenu { +class UserMenu; +} class EditorCommands; class KileInfo { - friend class KileMainWindow; + friend class KileMainWindow; public: - KileInfo(KParts::MainWindow *mainWindow); - virtual ~KileInfo(); + KileInfo(KParts::MainWindow *mainWindow); + virtual ~KileInfo(); public: - enum {bibinputs = 0,bstinputs, texinputs}; - QString getName(KTextEditor::Document *doc = Q_NULLPTR, bool shrt = false) const; - QString getShortName(KTextEditor::Document *doc = Q_NULLPTR) const { return getName(doc, true); } - LaTeXOutputHandler* findCurrentLaTeXOutputHandler() const; - QString getCompileNameForProject(KileProject *project, bool shrt = false) const; - QString getCompileName(bool shrt = false, LaTeXOutputHandler** h = Q_NULLPTR) const; - QString getFullFromPrettyName(const OutputInfo& info, const QString& name) const; - QList getParentsFor(KileDocument::Info *); - bool getSinglemode() { return m_singlemode; } - - QString getCurrentTarget() const { return m_currentTarget; } - void setTarget(const QString &target) { m_currentTarget=target; } - - virtual KTextEditor::Document* activeTextDocument() const; - - QString getSelection() const; - void clearSelection() const; - - virtual QStringList allLabels(KileDocument::TextInfo *info = Q_NULLPTR); - virtual QStringList allBibItems(KileDocument::TextInfo *info = Q_NULLPTR); - virtual QStringList allBibliographies(KileDocument::TextInfo *info = Q_NULLPTR); - virtual QStringList allDependencies(KileDocument::TextInfo *info = Q_NULLPTR); - virtual QStringList allNewCommands(KileDocument::TextInfo *info = Q_NULLPTR); - virtual QStringList allAsyFigures(KileDocument::TextInfo *info = Q_NULLPTR); - virtual QStringList allPackages(KileDocument::TextInfo *info = Q_NULLPTR); - - QString lastModifiedFile(KileDocument::TextInfo *info = Q_NULLPTR); - - static QString documentTypeToString(KileDocument::Type type); - - virtual void focusLog() = 0; - virtual void focusOutput() = 0; - virtual void focusKonsole() = 0; - virtual void focusEditor() = 0; - virtual void focusPreview() = 0; + enum {bibinputs = 0,bstinputs, texinputs}; + QString getName(KTextEditor::Document *doc = Q_NULLPTR, bool shrt = false) const; + QString getShortName(KTextEditor::Document *doc = Q_NULLPTR) const { + return getName(doc, true); + } + LaTeXOutputHandler* findCurrentLaTeXOutputHandler() const; + QString getCompileNameForProject(KileProject *project, bool shrt = false) const; + QString getCompileName(bool shrt = false, LaTeXOutputHandler** h = Q_NULLPTR) const; + QString getFullFromPrettyName(const OutputInfo& info, const QString& name) const; + QList getParentsFor(KileDocument::Info *); + bool getSinglemode() { + return m_singlemode; + } + + QString getCurrentTarget() const { + return m_currentTarget; + } + void setTarget(const QString &target) { + m_currentTarget=target; + } + + virtual KTextEditor::Document* activeTextDocument() const; + + QString getSelection() const; + void clearSelection() const; + + virtual QStringList allLabels(KileDocument::TextInfo *info = Q_NULLPTR); + virtual QStringList allBibItems(KileDocument::TextInfo *info = Q_NULLPTR); + virtual QStringList allBibliographies(KileDocument::TextInfo *info = Q_NULLPTR); + virtual QStringList allDependencies(KileDocument::TextInfo *info = Q_NULLPTR); + virtual QStringList allNewCommands(KileDocument::TextInfo *info = Q_NULLPTR); + virtual QStringList allAsyFigures(KileDocument::TextInfo *info = Q_NULLPTR); + virtual QStringList allPackages(KileDocument::TextInfo *info = Q_NULLPTR); + + QString lastModifiedFile(KileDocument::TextInfo *info = Q_NULLPTR); + + static QString documentTypeToString(KileDocument::Type type); + + virtual void focusLog() = 0; + virtual void focusOutput() = 0; + virtual void focusKonsole() = 0; + virtual void focusEditor() = 0; + virtual void focusPreview() = 0; private: - QStringList retrieveList(QStringList (KileDocument::Info::*getit)() const, KileDocument::TextInfo *docinfo = Q_NULLPTR); + QStringList retrieveList(QStringList (KileDocument::Info::*getit)() const, KileDocument::TextInfo *docinfo = Q_NULLPTR); public: - bool similarOrEqualURL(const QUrl &validurl, const QUrl &testurl); - bool isOpen(const QUrl &url); - inline bool isOpen(const QString& localFile) - { - return isOpen(QUrl::fromLocalFile(localFile)); - } - bool projectIsOpen(const QUrl & ); - - bool watchFile() { return m_bWatchFile; } - - virtual int lineNumber() = 0; - - KileWidget::StructureWidget *structureWidget() { return m_kwStructure; } - KileWidget::Konsole *texKonsole() { return m_texKonsole; } - KileWidget::OutputView *outputWidget() { return m_outputWidget; } - KileWidget::BottomBar *outputView() { return m_bottomBar; } - KileWidget::PreviewWidget *previewWidget () { return m_previewWidget; } - - KileConfiguration::Manager* configurationManager() const { return m_configurationManager; } - KileDocument::Manager* docManager() const { return m_docManager; } - KileView::Manager* viewManager() const { return m_viewManager; } - KileTool::Manager* toolManager() const { return m_manager; } - KileScript::Manager* scriptManager() const { return m_jScriptManager; } - KileEditorKeySequence::Manager* editorKeySequenceManager() const { return m_editorKeySequenceManager; } - KileTool::Factory* toolFactory() const { return m_toolFactory; } - KileDocument::EditorExtension *editorExtension() const { return m_edit; } - KileDocument::LatexCommands *latexCommands() const { return m_latexCommands; } - KileHelp::Help *help() const { return m_help; } - KileTool::QuickPreview *quickPreview() const { return m_quickPreview; } - KileTool::LivePreviewManager *livePreviewManager() const { return m_livePreviewManager; } - KileDocument::Extensions *extensions() const { return m_extensions; } - KileTemplate::Manager *templateManager() const { return m_templateManager; } - KileCodeCompletion::Manager *codeCompletionManager() const { return m_codeCompletionManager; } - KileAbbreviation::Manager* abbreviationManager() const { return m_abbreviationManager; } - KileParser::Manager* parserManager() const { return m_parserManager; } - KileErrorHandler* errorHandler() const { return m_errorHandler; } - KileMenu::UserMenu *userMenu() const { return m_userMenu; } - - //FIXME:refactor - KileWidget::FileBrowserWidget* fileSelector() const { return m_fileBrowserWidget; } - - KParts::MainWindow* mainWindow() const { return m_mainWindow; } - - static QString expandEnvironmentVars(const QString &variable); - static QString checkOtherPaths(const QString &path,const QString &file, int type); - static QString checkOtherPaths(const QUrl &url,const QString &file, int type){ return checkOtherPaths(url.toLocalFile(),file, type); } - - virtual void setLine(const QString &line) = 0; - - QString getMasterDocumentFileName() const { return m_masterDocumentFileName; } + bool similarOrEqualURL(const QUrl &validurl, const QUrl &testurl); + bool isOpen(const QUrl &url); + inline bool isOpen(const QString& localFile) + { + return isOpen(QUrl::fromLocalFile(localFile)); + } + bool projectIsOpen(const QUrl & ); + + bool watchFile() { + return m_bWatchFile; + } + + virtual int lineNumber() = 0; + + KileWidget::StructureWidget *structureWidget() { + return m_kwStructure; + } + KileWidget::Konsole *texKonsole() { + return m_texKonsole; + } + KileWidget::OutputView *outputWidget() { + return m_outputWidget; + } + KileWidget::BottomBar *outputView() { + return m_bottomBar; + } + KileWidget::PreviewWidget *previewWidget () { + return m_previewWidget; + } + + KileConfiguration::Manager* configurationManager() const { + return m_configurationManager; + } + KileDocument::Manager* docManager() const { + return m_docManager; + } + KileView::Manager* viewManager() const { + return m_viewManager; + } + KileTool::Manager* toolManager() const { + return m_manager; + } + KileScript::Manager* scriptManager() const { + return m_jScriptManager; + } + KileEditorKeySequence::Manager* editorKeySequenceManager() const { + return m_editorKeySequenceManager; + } + KileTool::Factory* toolFactory() const { + return m_toolFactory; + } + KileDocument::EditorExtension *editorExtension() const { + return m_edit; + } + KileDocument::LatexCommands *latexCommands() const { + return m_latexCommands; + } + KileHelp::Help *help() const { + return m_help; + } + KileTool::QuickPreview *quickPreview() const { + return m_quickPreview; + } + KileTool::LivePreviewManager *livePreviewManager() const { + return m_livePreviewManager; + } + KileDocument::Extensions *extensions() const { + return m_extensions; + } + KileTemplate::Manager *templateManager() const { + return m_templateManager; + } + KileCodeCompletion::Manager *codeCompletionManager() const { + return m_codeCompletionManager; + } + KileAbbreviation::Manager* abbreviationManager() const { + return m_abbreviationManager; + } + KileParser::Manager* parserManager() const { + return m_parserManager; + } + KileErrorHandler* errorHandler() const { + return m_errorHandler; + } + KileMenu::UserMenu *userMenu() const { + return m_userMenu; + } + + //FIXME:refactor + KileWidget::FileBrowserWidget* fileSelector() const { + return m_fileBrowserWidget; + } + + KParts::MainWindow* mainWindow() const { + return m_mainWindow; + } + + static QString expandEnvironmentVars(const QString &variable); + static QString checkOtherPaths(const QString &path,const QString &file, int type); + static QString checkOtherPaths(const QUrl &url,const QString &file, int type) { + return checkOtherPaths(url.toLocalFile(),file, type); + } + + virtual void setLine(const QString &line) = 0; + + QString getMasterDocumentFileName() const { + return m_masterDocumentFileName; + } protected: - KileConfiguration::Manager *m_configurationManager; - KParts::MainWindow *m_mainWindow; - KileDocument::Manager *m_docManager; - KileView::Manager *m_viewManager; - KileTool::Manager *m_manager; - KileTemplate::Manager *m_templateManager; - KileScript::Manager *m_jScriptManager; - KileEditorKeySequence::Manager *m_editorKeySequenceManager; - KileTool::Factory *m_toolFactory; - KileWidget::Konsole *m_texKonsole; - KileWidget::OutputView *m_outputWidget; - KileWidget::ScriptsManagement *m_scriptsManagementWidget; - KileWidget::BottomBar *m_bottomBar; - KileWidget::PreviewWidget *m_previewWidget; - KileWidget::ExtendedScrollArea *m_previewScrollArea; - KileCodeCompletion::Manager *m_codeCompletionManager; - KileAbbreviation::Manager *m_abbreviationManager; - KileParser::Manager *m_parserManager; - KileErrorHandler *m_errorHandler; - - EditorCommands *m_editorCommands; - - KileHelp::Help *m_help; - KileDocument::EditorExtension *m_edit; - KileDocument::LatexCommands *m_latexCommands; - KileDocument::Extensions *m_extensions; - KileTool::QuickPreview *m_quickPreview; - KileMenu::UserMenu *m_userMenu; - KileTool::LivePreviewManager *m_livePreviewManager; - - bool m_singlemode; - QString m_masterDocumentFileName; - - QString m_currentTarget; - - bool m_bWatchFile; - - KileWidget::StructureWidget *m_kwStructure; - KileWidget::FileBrowserWidget *m_fileBrowserWidget; + KileConfiguration::Manager *m_configurationManager; + KParts::MainWindow *m_mainWindow; + KileDocument::Manager *m_docManager; + KileView::Manager *m_viewManager; + KileTool::Manager *m_manager; + KileTemplate::Manager *m_templateManager; + KileScript::Manager *m_jScriptManager; + KileEditorKeySequence::Manager *m_editorKeySequenceManager; + KileTool::Factory *m_toolFactory; + KileWidget::Konsole *m_texKonsole; + KileWidget::OutputView *m_outputWidget; + KileWidget::ScriptsManagement *m_scriptsManagementWidget; + KileWidget::BottomBar *m_bottomBar; + KileWidget::PreviewWidget *m_previewWidget; + KileWidget::ExtendedScrollArea *m_previewScrollArea; + KileCodeCompletion::Manager *m_codeCompletionManager; + KileAbbreviation::Manager *m_abbreviationManager; + KileParser::Manager *m_parserManager; + KileErrorHandler *m_errorHandler; + + EditorCommands *m_editorCommands; + + KileHelp::Help *m_help; + KileDocument::EditorExtension *m_edit; + KileDocument::LatexCommands *m_latexCommands; + KileDocument::Extensions *m_extensions; + KileTool::QuickPreview *m_quickPreview; + KileMenu::UserMenu *m_userMenu; + KileTool::LivePreviewManager *m_livePreviewManager; + + bool m_singlemode; + QString m_masterDocumentFileName; + + QString m_currentTarget; + + bool m_bWatchFile; + + KileWidget::StructureWidget *m_kwStructure; + KileWidget::FileBrowserWidget *m_fileBrowserWidget; }; #endif diff --git a/src/kilelauncher.cpp b/src/kilelauncher.cpp index af987219..84781619 100644 --- a/src/kilelauncher.cpp +++ b/src/kilelauncher.cpp @@ -1,384 +1,384 @@ /**************************************************************************************** Copyright (C) 2003 by Jeroen Wijnhout (Jeroen.Wijnhout@kdemail.net) 2008-2017 by Michel Ludwig (michel.ludwig@kdemail.net) ****************************************************************************************/ /*************************************************************************** * * * 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. * * * ***************************************************************************/ #include "kilelauncher.h" #include #include "docpart.h" #include "kileconfig.h" #include "kileinfo.h" #include "kiletool.h" #include "kiletoolmanager.h" #include "kiletool_enums.h" #include "kileviewmanager.h" #include "livepreview.h" #include #include #include "kiledebug.h" #include #include #include #include #include #include #include #include namespace KileTool { - Launcher::Launcher() : - m_tool(Q_NULLPTR) - { - } - - Launcher::~ Launcher() - { - KILE_DEBUG_MAIN << "DELETING launcher"; - } - - ProcessLauncher::ProcessLauncher() : - m_changeTo(true) - { - KILE_DEBUG_MAIN << "==KileTool::ProcessLauncher::ProcessLauncher()=============="; - - m_proc = new KProcess(this); - - m_proc->setOutputChannelMode(KProcess::MergedChannels); - m_proc->setReadChannel(QProcess::StandardOutput); - - connect(m_proc, SIGNAL(readyReadStandardOutput()), this, SLOT(slotProcessOutput())); - connect(m_proc, SIGNAL(finished(int, QProcess::ExitStatus)), this, SLOT(slotProcessExited(int, QProcess::ExitStatus))); - connect(m_proc, SIGNAL(error(QProcess::ProcessError)), this, SLOT(slotProcessError(QProcess::ProcessError))); - } - - ProcessLauncher::~ProcessLauncher() - { - KILE_DEBUG_MAIN << "DELETING ProcessLauncher"; - - if(m_proc) { - // we don't want it to emit any signals as we are being deleted - m_proc->disconnect(); - kill(false); - delete m_proc; - } - } - - void ProcessLauncher::setWorkingDirectory(const QString &wd) - { - m_wd = wd; - } - - void ProcessLauncher::changeToWorkingDirectory(bool change) - { - m_changeTo = change; - } - - void ProcessLauncher::setCommand(const QString& cmd) - { - m_cmd = cmd; - } - - void ProcessLauncher::setOptions(const QString& opt) - { - m_options = opt; - } - - bool ProcessLauncher::launch() - { - if(tool() == Q_NULLPTR){ - qWarning() << "tool() is Q_NULLPTR which is a BUG"; - return false; - } - if(m_proc == Q_NULLPTR){ - qWarning() << "m_proc is Q_NULLPTR which is a BUG"; - return false; - } - - QString msg; - QString out = "*****\n***** " + tool()->name() + i18n(" output: \n"); - - if(m_cmd.isEmpty()) { - m_cmd = tool()->readEntry("command"); - KILE_DEBUG_MAIN << "readEntry('command'): " << m_cmd; - } - - if(m_options.isEmpty()) { - m_options = tool()->readEntry("options"); - KILE_DEBUG_MAIN << "readEntry('option'):" << m_options; - } - - if(m_changeTo && (!m_wd.isEmpty())) { - m_proc->setWorkingDirectory(m_wd); - KILE_DEBUG_MAIN << "changed to " << m_wd; - out += QString("***** cd \"") + m_wd + QString("\"\n"); - } - - QString str; - tool()->translate(m_cmd); - tool()->translate(m_options, true); // quote the substituted strings using 'KShell::quoteArg' - // (see bug 314109) - KILE_DEBUG_MAIN << "after translate: m_cmd=" << m_cmd << ", m_options=" << m_options; - - if(m_cmd.isEmpty()) { - return false; - } - - KShell::Errors err; - QStringList arguments = KShell::splitArgs(m_options, KShell::AbortOnMeta | KShell::TildeExpand, &err); - if(err == KShell::BadQuoting || err == KShell::FoundMeta) { - return false; - } - - // we cannot use 'KProcess::setShellCommand' here as that method uses 'KStandardDirs::findExe' - // which doesn't respect the path preferences given by the user, i.e. 'KStandardDirs::findExe' is happy - // to return the first executable it finds (for example, in '/usr/bin' although the user maybe didn't - // want to use that directory) - // BUG: 204397 - m_proc->setProgram(m_cmd, arguments); - - KILE_DEBUG_MAIN << "sent " << m_cmd << ' ' << arguments; - - out += QString("***** ") + m_cmd + ' ' + arguments.join(" ") + '\n'; - - QString src = tool()->source(false); - QString trgt = tool()->target(); - if(src == trgt) { - msg = src; - } - else { - msg = src + " => " + trgt; - } - - msg += " (" + m_cmd + ')'; - - emit(message(Info, msg)); - - QString teXInputPaths = tool()->teXInputPaths(); - QString bibInputPaths = tool()->bibInputPaths(); - QString bstInputPaths = tool()->bstInputPaths(); - - // QuickView tools need a special TEXINPUTS environment variable - if(tool()->isQuickie()) { - teXInputPaths = KileConfig::previewTeXPaths(); - bibInputPaths = KileConfig::previewBibInputPaths(); - } - - KILE_DEBUG_MAIN << "$PATH=" << tool()->manager()->info()->expandEnvironmentVars("$PATH"); - KILE_DEBUG_MAIN << "$TEXINPUTS=" << tool()->manager()->info()->expandEnvironmentVars(teXInputPaths + PATH_SEPARATOR + "$TEXINPUTS"); - KILE_DEBUG_MAIN << "$BIBINPUTS=" << tool()->manager()->info()->expandEnvironmentVars(bibInputPaths + PATH_SEPARATOR + "$BIBINPUTS"); - KILE_DEBUG_MAIN << "$BSTINPUTS=" << tool()->manager()->info()->expandEnvironmentVars(bstInputPaths + PATH_SEPARATOR + "$BSTINPUTS"); - KILE_DEBUG_MAIN << "Tool name is "<< tool()->name(); - - m_proc->setEnv("PATH", tool()->manager()->info()->expandEnvironmentVars("$PATH")); - - if(!teXInputPaths.isEmpty()) { - m_proc->setEnv("TEXINPUTS", tool()->manager()->info()->expandEnvironmentVars(teXInputPaths + PATH_SEPARATOR + "$TEXINPUTS")); - } - if(!bibInputPaths.isEmpty()) { - m_proc->setEnv("BIBINPUTS", tool()->manager()->info()->expandEnvironmentVars(bibInputPaths + PATH_SEPARATOR + "$BIBINPUTS")); - } - if(!bstInputPaths.isEmpty()) { - m_proc->setEnv("BSTINPUTS", tool()->manager()->info()->expandEnvironmentVars(bstInputPaths + PATH_SEPARATOR + "$BSTINPUTS")); - } - - out += "*****\n"; - emit(output(out)); - - if(tool()->manager()->shouldBlock()) { - KILE_DEBUG_MAIN << "About to execute: " << m_proc->program(); - m_proc->execute(); - } - else { - KILE_DEBUG_MAIN << "About to start: " << m_proc->program(); - m_proc->start(); - } - return true; - } - - void ProcessLauncher::kill(bool emitSignals) - { - KILE_DEBUG_MAIN << "==KileTool::ProcessLauncher::kill()=============="; - if(m_proc && m_proc->state() == QProcess::Running) { - KILE_DEBUG_MAIN << "\tkilling"; - m_proc->kill(); - m_proc->waitForFinished(-1); - } - else { - KILE_DEBUG_MAIN << "\tno process or process not running"; - if(emitSignals) { - emit(message(Error, i18n("terminated"))); - emit(done(AbnormalExit)); - } - } - } - - // FIXME: this should be done in the 'launch()' method itself - bool ProcessLauncher::selfCheck() - { - emit(message(Error, i18n("Launching failed, diagnostics:"))); - - KShell::Errors err; - QStringList arguments = KShell::splitArgs(m_options, KShell::AbortOnMeta | KShell::TildeExpand, &err); - if(err == KShell::BadQuoting) { - emit(message(Error, i18n("An error occurred while parsing the options given to the tool."))); - return false; - } - else if(err == KShell::FoundMeta) { - emit(message(Error, i18n("Shell meta characters that cannot be handled are present in the options given to the tool."))); - return false; - } - - - QString exe = KRun::binaryName(tool()->readEntry("command"), false); - QString path = QStandardPaths::findExecutable(exe); - - if(path.isEmpty()) { - emit(message(Error, i18n("There is no executable named \"%1\" in your path.", exe))); - return false; - } - else { - QFileInfo fi(path); - if(!fi.isExecutable()) { - emit(message(Error, i18n("You do not have permission to run %1.", path))); - return false; - } - } - - emit(message(Info, i18n("Diagnostics could not find any obvious problems."))); - return true; - } - - void ProcessLauncher::slotProcessOutput() - { - QByteArray buf = m_proc->readAllStandardOutput(); - emit output(QString::fromLocal8Bit(buf, buf.size())); - } - - void ProcessLauncher::slotProcessExited(int exitCode, QProcess::ExitStatus exitStatus) - { - KILE_DEBUG_MAIN << "==KileTool::ProcessLauncher::slotProcessExited============="; - KILE_DEBUG_MAIN << "\t" << tool()->name(); - - if(m_proc) { - if(exitStatus == QProcess::NormalExit) { - KILE_DEBUG_MAIN << "\tnormal exit"; - int type = Info; - if(exitCode != 0) { - type = Error; - emit(message(type, i18n("finished with exit code %1", exitCode))); - } - - if (type == Info) { - emit(done(Success)); - } - else { - emit(done(Failed)); - } - } - else { - KILE_DEBUG_MAIN << "\tabnormal exit"; - emit(message(Error, i18n("finished abruptly"))); - emit(done(AbnormalExit)); - } - } - else { - qWarning() << "\tNO PROCESS, emitting done"; - emit(done(Success)); - } - } - - void ProcessLauncher::slotProcessError(QProcess::ProcessError error) - { - KILE_DEBUG_MAIN << "error =" << error << "tool = " << tool()->name(); - QString errorString; - switch(error) { - case QProcess::FailedToStart: - errorString = i18n("failed to start"); - break; - case QProcess::Crashed: - errorString = i18n("crashed"); - break; - default: - errorString = i18n("failed (error code %i)", error); - break; - } - emit(message(Error, errorString)); - emit(done(AbnormalExit)); - } - - KonsoleLauncher::KonsoleLauncher() : ProcessLauncher() - { - } - - bool KonsoleLauncher::launch() - { - QString cmd = tool()->readEntry("command"); - QString noclose = (tool()->readEntry("close") == "no") ? "--noclose" : ""; - setCommand("konsole"); - setOptions(noclose + " -e " + cmd + ' ' + tool()->readEntry("options")); - if(QStandardPaths::findExecutable(KRun::binaryName(cmd, false)).isEmpty()) { - return false; - } - - return ProcessLauncher::launch(); - } - - DocumentViewerLauncher::DocumentViewerLauncher() - { - } - - DocumentViewerLauncher::~DocumentViewerLauncher() - { - KILE_DEBUG_MAIN << "DELETING DocumentViewerLauncher"; - } - - bool DocumentViewerLauncher::selfCheck() - { - return true; //no additional self-checks, all of them are done in launch() - } - - bool DocumentViewerLauncher::launch() - { - if(!tool()->manager()->viewManager()->viewerPart()) { - emit(message(Error, i18n("The document viewer is not available"))); - return false; - } - if(tool()->manager()->livePreviewManager() && tool()->manager()->livePreviewManager()->isLivePreviewActive()) { - emit(message(Error, i18n("Please disable the live preview before launching this tool"))); - return false; - } - const QString fileName = tool()->paramDict()["%dir_target"] + '/' + tool()->paramDict()["%target"]; - tool()->manager()->viewManager()->openInDocumentViewer(QUrl::fromLocalFile(fileName)); - if(tool()->paramDict().contains("%sourceFileName") - && tool()->paramDict().contains("%sourceLine")) { - const QString sourceFileName = tool()->paramDict()["%sourceFileName"]; - const QString lineString = tool()->paramDict()["%sourceLine"]; - tool()->manager()->viewManager()->showSourceLocationInDocumentViewer(sourceFileName, lineString.toInt(), 0); - } - emit(done(Success)); - - return true; - } - - void DocumentViewerLauncher::kill(bool emitSignals) - { - Q_UNUSED(emitSignals); - } +Launcher::Launcher() : + m_tool(Q_NULLPTR) +{ +} + +Launcher::~ Launcher() +{ + KILE_DEBUG_MAIN << "DELETING launcher"; +} + +ProcessLauncher::ProcessLauncher() : + m_changeTo(true) +{ + KILE_DEBUG_MAIN << "==KileTool::ProcessLauncher::ProcessLauncher()=============="; + + m_proc = new KProcess(this); + + m_proc->setOutputChannelMode(KProcess::MergedChannels); + m_proc->setReadChannel(QProcess::StandardOutput); + + connect(m_proc, SIGNAL(readyReadStandardOutput()), this, SLOT(slotProcessOutput())); + connect(m_proc, SIGNAL(finished(int, QProcess::ExitStatus)), this, SLOT(slotProcessExited(int, QProcess::ExitStatus))); + connect(m_proc, SIGNAL(error(QProcess::ProcessError)), this, SLOT(slotProcessError(QProcess::ProcessError))); +} + +ProcessLauncher::~ProcessLauncher() +{ + KILE_DEBUG_MAIN << "DELETING ProcessLauncher"; + + if(m_proc) { + // we don't want it to emit any signals as we are being deleted + m_proc->disconnect(); + kill(false); + delete m_proc; + } +} + +void ProcessLauncher::setWorkingDirectory(const QString &wd) +{ + m_wd = wd; +} + +void ProcessLauncher::changeToWorkingDirectory(bool change) +{ + m_changeTo = change; +} + +void ProcessLauncher::setCommand(const QString& cmd) +{ + m_cmd = cmd; +} + +void ProcessLauncher::setOptions(const QString& opt) +{ + m_options = opt; +} + +bool ProcessLauncher::launch() +{ + if(tool() == Q_NULLPTR) { + qWarning() << "tool() is Q_NULLPTR which is a BUG"; + return false; + } + if(m_proc == Q_NULLPTR) { + qWarning() << "m_proc is Q_NULLPTR which is a BUG"; + return false; + } + + QString msg; + QString out = "*****\n***** " + tool()->name() + i18n(" output: \n"); + + if(m_cmd.isEmpty()) { + m_cmd = tool()->readEntry("command"); + KILE_DEBUG_MAIN << "readEntry('command'): " << m_cmd; + } + + if(m_options.isEmpty()) { + m_options = tool()->readEntry("options"); + KILE_DEBUG_MAIN << "readEntry('option'):" << m_options; + } + + if(m_changeTo && (!m_wd.isEmpty())) { + m_proc->setWorkingDirectory(m_wd); + KILE_DEBUG_MAIN << "changed to " << m_wd; + out += QString("***** cd \"") + m_wd + QString("\"\n"); + } + + QString str; + tool()->translate(m_cmd); + tool()->translate(m_options, true); // quote the substituted strings using 'KShell::quoteArg' + // (see bug 314109) + KILE_DEBUG_MAIN << "after translate: m_cmd=" << m_cmd << ", m_options=" << m_options; + + if(m_cmd.isEmpty()) { + return false; + } + + KShell::Errors err; + QStringList arguments = KShell::splitArgs(m_options, KShell::AbortOnMeta | KShell::TildeExpand, &err); + if(err == KShell::BadQuoting || err == KShell::FoundMeta) { + return false; + } + + // we cannot use 'KProcess::setShellCommand' here as that method uses 'KStandardDirs::findExe' + // which doesn't respect the path preferences given by the user, i.e. 'KStandardDirs::findExe' is happy + // to return the first executable it finds (for example, in '/usr/bin' although the user maybe didn't + // want to use that directory) + // BUG: 204397 + m_proc->setProgram(m_cmd, arguments); + + KILE_DEBUG_MAIN << "sent " << m_cmd << ' ' << arguments; + + out += QString("***** ") + m_cmd + ' ' + arguments.join(" ") + '\n'; + + QString src = tool()->source(false); + QString trgt = tool()->target(); + if(src == trgt) { + msg = src; + } + else { + msg = src + " => " + trgt; + } + + msg += " (" + m_cmd + ')'; + + emit(message(Info, msg)); + + QString teXInputPaths = tool()->teXInputPaths(); + QString bibInputPaths = tool()->bibInputPaths(); + QString bstInputPaths = tool()->bstInputPaths(); + + // QuickView tools need a special TEXINPUTS environment variable + if(tool()->isQuickie()) { + teXInputPaths = KileConfig::previewTeXPaths(); + bibInputPaths = KileConfig::previewBibInputPaths(); + } + + KILE_DEBUG_MAIN << "$PATH=" << tool()->manager()->info()->expandEnvironmentVars("$PATH"); + KILE_DEBUG_MAIN << "$TEXINPUTS=" << tool()->manager()->info()->expandEnvironmentVars(teXInputPaths + PATH_SEPARATOR + "$TEXINPUTS"); + KILE_DEBUG_MAIN << "$BIBINPUTS=" << tool()->manager()->info()->expandEnvironmentVars(bibInputPaths + PATH_SEPARATOR + "$BIBINPUTS"); + KILE_DEBUG_MAIN << "$BSTINPUTS=" << tool()->manager()->info()->expandEnvironmentVars(bstInputPaths + PATH_SEPARATOR + "$BSTINPUTS"); + KILE_DEBUG_MAIN << "Tool name is "<< tool()->name(); + + m_proc->setEnv("PATH", tool()->manager()->info()->expandEnvironmentVars("$PATH")); + + if(!teXInputPaths.isEmpty()) { + m_proc->setEnv("TEXINPUTS", tool()->manager()->info()->expandEnvironmentVars(teXInputPaths + PATH_SEPARATOR + "$TEXINPUTS")); + } + if(!bibInputPaths.isEmpty()) { + m_proc->setEnv("BIBINPUTS", tool()->manager()->info()->expandEnvironmentVars(bibInputPaths + PATH_SEPARATOR + "$BIBINPUTS")); + } + if(!bstInputPaths.isEmpty()) { + m_proc->setEnv("BSTINPUTS", tool()->manager()->info()->expandEnvironmentVars(bstInputPaths + PATH_SEPARATOR + "$BSTINPUTS")); + } + + out += "*****\n"; + emit(output(out)); + + if(tool()->manager()->shouldBlock()) { + KILE_DEBUG_MAIN << "About to execute: " << m_proc->program(); + m_proc->execute(); + } + else { + KILE_DEBUG_MAIN << "About to start: " << m_proc->program(); + m_proc->start(); + } + return true; +} + +void ProcessLauncher::kill(bool emitSignals) +{ + KILE_DEBUG_MAIN << "==KileTool::ProcessLauncher::kill()=============="; + if(m_proc && m_proc->state() == QProcess::Running) { + KILE_DEBUG_MAIN << "\tkilling"; + m_proc->kill(); + m_proc->waitForFinished(-1); + } + else { + KILE_DEBUG_MAIN << "\tno process or process not running"; + if(emitSignals) { + emit(message(Error, i18n("terminated"))); + emit(done(AbnormalExit)); + } + } +} + +// FIXME: this should be done in the 'launch()' method itself +bool ProcessLauncher::selfCheck() +{ + emit(message(Error, i18n("Launching failed, diagnostics:"))); + + KShell::Errors err; + QStringList arguments = KShell::splitArgs(m_options, KShell::AbortOnMeta | KShell::TildeExpand, &err); + if(err == KShell::BadQuoting) { + emit(message(Error, i18n("An error occurred while parsing the options given to the tool."))); + return false; + } + else if(err == KShell::FoundMeta) { + emit(message(Error, i18n("Shell meta characters that cannot be handled are present in the options given to the tool."))); + return false; + } + + + QString exe = KRun::binaryName(tool()->readEntry("command"), false); + QString path = QStandardPaths::findExecutable(exe); + + if(path.isEmpty()) { + emit(message(Error, i18n("There is no executable named \"%1\" in your path.", exe))); + return false; + } + else { + QFileInfo fi(path); + if(!fi.isExecutable()) { + emit(message(Error, i18n("You do not have permission to run %1.", path))); + return false; + } + } + + emit(message(Info, i18n("Diagnostics could not find any obvious problems."))); + return true; +} + +void ProcessLauncher::slotProcessOutput() +{ + QByteArray buf = m_proc->readAllStandardOutput(); + emit output(QString::fromLocal8Bit(buf, buf.size())); +} + +void ProcessLauncher::slotProcessExited(int exitCode, QProcess::ExitStatus exitStatus) +{ + KILE_DEBUG_MAIN << "==KileTool::ProcessLauncher::slotProcessExited============="; + KILE_DEBUG_MAIN << "\t" << tool()->name(); + + if(m_proc) { + if(exitStatus == QProcess::NormalExit) { + KILE_DEBUG_MAIN << "\tnormal exit"; + int type = Info; + if(exitCode != 0) { + type = Error; + emit(message(type, i18n("finished with exit code %1", exitCode))); + } + + if (type == Info) { + emit(done(Success)); + } + else { + emit(done(Failed)); + } + } + else { + KILE_DEBUG_MAIN << "\tabnormal exit"; + emit(message(Error, i18n("finished abruptly"))); + emit(done(AbnormalExit)); + } + } + else { + qWarning() << "\tNO PROCESS, emitting done"; + emit(done(Success)); + } +} + +void ProcessLauncher::slotProcessError(QProcess::ProcessError error) +{ + KILE_DEBUG_MAIN << "error =" << error << "tool = " << tool()->name(); + QString errorString; + switch(error) { + case QProcess::FailedToStart: + errorString = i18n("failed to start"); + break; + case QProcess::Crashed: + errorString = i18n("crashed"); + break; + default: + errorString = i18n("failed (error code %i)", error); + break; + } + emit(message(Error, errorString)); + emit(done(AbnormalExit)); +} + +KonsoleLauncher::KonsoleLauncher() : ProcessLauncher() +{ +} + +bool KonsoleLauncher::launch() +{ + QString cmd = tool()->readEntry("command"); + QString noclose = (tool()->readEntry("close") == "no") ? "--noclose" : ""; + setCommand("konsole"); + setOptions(noclose + " -e " + cmd + ' ' + tool()->readEntry("options")); + if(QStandardPaths::findExecutable(KRun::binaryName(cmd, false)).isEmpty()) { + return false; + } + + return ProcessLauncher::launch(); +} + +DocumentViewerLauncher::DocumentViewerLauncher() +{ +} + +DocumentViewerLauncher::~DocumentViewerLauncher() +{ + KILE_DEBUG_MAIN << "DELETING DocumentViewerLauncher"; +} + +bool DocumentViewerLauncher::selfCheck() +{ + return true; //no additional self-checks, all of them are done in launch() +} + +bool DocumentViewerLauncher::launch() +{ + if(!tool()->manager()->viewManager()->viewerPart()) { + emit(message(Error, i18n("The document viewer is not available"))); + return false; + } + if(tool()->manager()->livePreviewManager() && tool()->manager()->livePreviewManager()->isLivePreviewActive()) { + emit(message(Error, i18n("Please disable the live preview before launching this tool"))); + return false; + } + const QString fileName = tool()->paramDict()["%dir_target"] + '/' + tool()->paramDict()["%target"]; + tool()->manager()->viewManager()->openInDocumentViewer(QUrl::fromLocalFile(fileName)); + if(tool()->paramDict().contains("%sourceFileName") + && tool()->paramDict().contains("%sourceLine")) { + const QString sourceFileName = tool()->paramDict()["%sourceFileName"]; + const QString lineString = tool()->paramDict()["%sourceLine"]; + tool()->manager()->viewManager()->showSourceLocationInDocumentViewer(sourceFileName, lineString.toInt(), 0); + } + emit(done(Success)); + + return true; +} + +void DocumentViewerLauncher::kill(bool emitSignals) +{ + Q_UNUSED(emitSignals); +} } diff --git a/src/kilelauncher.h b/src/kilelauncher.h index b08f5fc2..db8b7dd2 100644 --- a/src/kilelauncher.h +++ b/src/kilelauncher.h @@ -1,130 +1,137 @@ /*************************************************************************************** begin : mon 3-11 20:40:00 CEST 2003 copyright : (C) 2003 by Jeroen Wijnhout (Jeroen.Wijnhout@kdemail.net) 2008 by Michel Ludwig (michel.ludwig@kdemail.net) ***************************************************************************************/ /*************************************************************************** * * * 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. * * * ***************************************************************************/ #ifndef KILE_LAUNCHER #define KILE_LAUNCHER #include #include class KProcess; class KileInfo; -namespace KParts { class ReadOnlyPart; class PartManager; } +namespace KParts { +class ReadOnlyPart; +class PartManager; +} namespace KileTool { - class Base; - - /** - * This class represents a way to launch a tool. This could be a commandline tool - * running in a Konsole, running as a separate process, it could even be responsible - * for starting a KPart. - * - * @author Jeroen Wijnhout - **/ - class Launcher : public QObject - { - Q_OBJECT - - public: - Launcher(); - ~Launcher(); - - public Q_SLOTS: - virtual bool launch() = 0; - virtual void kill(bool emitSignals = true) = 0; - virtual bool selfCheck() = 0; - - public: - virtual void setWorkingDirectory(const QString &) {} - - void setTool(Base *tool) { m_tool = tool; } - Base* tool() { return m_tool; } - - Q_SIGNALS: - void message(int, const QString&); - void output(const QString&); - - void exitedWith(int); - void abnormalExit(); - - void done(int); - - private: - //QDict *m_pdictParams; - Base *m_tool; - }; - - class ProcessLauncher : public Launcher - { - Q_OBJECT - - public: - ProcessLauncher(); - ~ProcessLauncher(); - - public: - void setWorkingDirectory(const QString &wd); - void changeToWorkingDirectory(bool change); - void setCommand(const QString& cmd); - void setOptions(const QString& opt); - - public Q_SLOTS: - bool launch(); - void kill(bool emitSignals = true); - bool selfCheck(); - - private Q_SLOTS: - void slotProcessOutput(); - void slotProcessExited(int exitCode, QProcess::ExitStatus exitStatus); - void slotProcessError(QProcess::ProcessError error); - - private: - QString m_wd, m_cmd; - QString m_options; - KProcess *m_proc; - bool m_changeTo; - }; - - class KonsoleLauncher : public ProcessLauncher - { - Q_OBJECT - - public: - KonsoleLauncher(); - - public Q_SLOTS: - bool launch(); - }; - - class DocumentViewerLauncher : public Launcher - { - Q_OBJECT - - public: - DocumentViewerLauncher(); - ~DocumentViewerLauncher(); - - public Q_SLOTS: - bool launch(); - void kill(bool emitSignals = true); - bool selfCheck(); - - }; +class Base; + +/** + * This class represents a way to launch a tool. This could be a commandline tool + * running in a Konsole, running as a separate process, it could even be responsible + * for starting a KPart. + * + * @author Jeroen Wijnhout + **/ +class Launcher : public QObject +{ + Q_OBJECT + +public: + Launcher(); + ~Launcher(); + +public Q_SLOTS: + virtual bool launch() = 0; + virtual void kill(bool emitSignals = true) = 0; + virtual bool selfCheck() = 0; + +public: + virtual void setWorkingDirectory(const QString &) {} + + void setTool(Base *tool) { + m_tool = tool; + } + Base* tool() { + return m_tool; + } + +Q_SIGNALS: + void message(int, const QString&); + void output(const QString&); + + void exitedWith(int); + void abnormalExit(); + + void done(int); + +private: + //QDict *m_pdictParams; + Base *m_tool; +}; + +class ProcessLauncher : public Launcher +{ + Q_OBJECT + +public: + ProcessLauncher(); + ~ProcessLauncher(); + +public: + void setWorkingDirectory(const QString &wd); + void changeToWorkingDirectory(bool change); + void setCommand(const QString& cmd); + void setOptions(const QString& opt); + +public Q_SLOTS: + bool launch(); + void kill(bool emitSignals = true); + bool selfCheck(); + +private Q_SLOTS: + void slotProcessOutput(); + void slotProcessExited(int exitCode, QProcess::ExitStatus exitStatus); + void slotProcessError(QProcess::ProcessError error); + +private: + QString m_wd, m_cmd; + QString m_options; + KProcess *m_proc; + bool m_changeTo; +}; + +class KonsoleLauncher : public ProcessLauncher +{ + Q_OBJECT + +public: + KonsoleLauncher(); + +public Q_SLOTS: + bool launch(); +}; + +class DocumentViewerLauncher : public Launcher +{ + Q_OBJECT + +public: + DocumentViewerLauncher(); + ~DocumentViewerLauncher(); + +public Q_SLOTS: + bool launch(); + void kill(bool emitSignals = true); + bool selfCheck(); + +}; } #endif diff --git a/src/kilelyxserver.cpp b/src/kilelyxserver.cpp index 936fdc3f..c52e2f5f 100644 --- a/src/kilelyxserver.cpp +++ b/src/kilelyxserver.cpp @@ -1,265 +1,265 @@ /*************************************************************************** begin : Sat Sept 9 2003 edit : Wed Jan 14 2009 copyright : (C) 2003 by Jeroen Wijnhout, 2007-2009 by Thomas Braun email : Jeroen.Wijnhout@kdemail.net ***************************************************************************/ /*************************************************************************** * * * 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. * * * ***************************************************************************/ #include "kilelyxserver.h" #include #include //getenv #ifndef _MSC_VER #include //read #else #include #endif #include #include "kileactions.h" #include "kiledebug.h" #include #include #include #include #include #include KileLyxServer::KileLyxServer(bool startMe) : - m_running(false) + m_running(false) { #ifndef _MSC_VER m_perms = S_IRUSR | S_IWUSR; #else m_perms = 0; #endif - KILE_DEBUG_MAIN << "===KileLyxServer::KileLyxServer(bool" << startMe << ")=== "; - - m_tempDir = new QTemporaryDir(); - if(!m_tempDir->isValid()) { - KILE_DEBUG_MAIN << "an error ocurred while creating a tempfile" ; - return; - } - - m_links << ".lyxpipe.in" << ".lyx/lyxpipe.in"; - m_links << ".lyxpipe.out" << ".lyx/lyxpipe.out"; - - for(int i = 0; i < m_links.count() ; ++i) { - m_pipes.append( m_tempDir->path() + m_links[i] ); - m_links[i].prepend(QDir::homePath() + QDir::separator() ); - KILE_DEBUG_MAIN << "m_pipes[" << i << "]=" << m_pipes[i]; - KILE_DEBUG_MAIN << "m_links[" << i << "]=" << m_links[i]; - } - - if(startMe) { - start(); - } + KILE_DEBUG_MAIN << "===KileLyxServer::KileLyxServer(bool" << startMe << ")=== "; + + m_tempDir = new QTemporaryDir(); + if(!m_tempDir->isValid()) { + KILE_DEBUG_MAIN << "an error ocurred while creating a tempfile" ; + return; + } + + m_links << ".lyxpipe.in" << ".lyx/lyxpipe.in"; + m_links << ".lyxpipe.out" << ".lyx/lyxpipe.out"; + + for(int i = 0; i < m_links.count() ; ++i) { + m_pipes.append( m_tempDir->path() + m_links[i] ); + m_links[i].prepend(QDir::homePath() + QDir::separator() ); + KILE_DEBUG_MAIN << "m_pipes[" << i << "]=" << m_pipes[i]; + KILE_DEBUG_MAIN << "m_links[" << i << "]=" << m_links[i]; + } + + if(startMe) { + start(); + } } KileLyxServer::~KileLyxServer() { - stop(); - removePipes(); + stop(); + removePipes(); - delete m_tempDir; + delete m_tempDir; - for(QList::iterator i = m_pipeIn.begin(); i != m_pipeIn.end(); ++i) { - delete *i; - } + for(QList::iterator i = m_pipeIn.begin(); i != m_pipeIn.end(); ++i) { + delete *i; + } - for(QList::iterator i = m_notifier.begin(); i != m_notifier.end(); ++i) { - delete *i; - } + for(QList::iterator i = m_notifier.begin(); i != m_notifier.end(); ++i) { + delete *i; + } } bool KileLyxServer::start() { - if (m_running) { - stop(); - } - - KILE_DEBUG_MAIN << "Starting the LyX server..."; - - if (openPipes()) { - QSocketNotifier *notifier; - for(QList::iterator it = m_pipeIn.begin(); it != m_pipeIn.end(); ++it) { - if ((*it)->fileName().right(3) == ".in" ) { - notifier = new QSocketNotifier((*it)->handle(), QSocketNotifier::Read, this); - connect(notifier, SIGNAL(activated(int)), this, SLOT(receive(int))); - m_notifier.append(notifier); - KILE_DEBUG_MAIN << "Created notifier for " << (*it)->fileName(); - } - else { - KILE_DEBUG_MAIN << "No notifier created for " << (*it)->fileName(); - } - } - m_running=true; - } - - return m_running; + if (m_running) { + stop(); + } + + KILE_DEBUG_MAIN << "Starting the LyX server..."; + + if (openPipes()) { + QSocketNotifier *notifier; + for(QList::iterator it = m_pipeIn.begin(); it != m_pipeIn.end(); ++it) { + if ((*it)->fileName().right(3) == ".in" ) { + notifier = new QSocketNotifier((*it)->handle(), QSocketNotifier::Read, this); + connect(notifier, SIGNAL(activated(int)), this, SLOT(receive(int))); + m_notifier.append(notifier); + KILE_DEBUG_MAIN << "Created notifier for " << (*it)->fileName(); + } + else { + KILE_DEBUG_MAIN << "No notifier created for " << (*it)->fileName(); + } + } + m_running=true; + } + + return m_running; } bool KileLyxServer::openPipes() { - KILE_DEBUG_MAIN << "===bool KileLyxServer::openPipes()==="; - - #ifdef Q_OS_WIN - qCritical() << "kile's lyx server can not work on windows since we don't have pipes"; - qCritical() << "And also lyx itself does not support it, see http://wiki.lyx.org/LyX/LyXServer"; - return false; - #else - bool opened = false; - QFileInfo pipeInfo,linkInfo; - QFile *file; - struct stat buf; - struct stat *stats = &buf; - - QDir lyxDir(QDir::homePath() + QDir::separator() + ".lyx"); - if(!lyxDir.exists()){ - KILE_DEBUG_MAIN << "Directory " << lyxDir.absolutePath() << " does not exist"; - if(mkdir(QFile::encodeName( lyxDir.path() ), m_perms | S_IXUSR) == -1){ - qCritical() << "Could not create directory"; - } - else{ - KILE_DEBUG_MAIN << "Directory created successfully"; - } - } - - for(int i = 0; i < m_pipes.count(); ++i) { - pipeInfo.setFile(m_pipes[i]); - linkInfo.setFile(m_links[i]); - - QFile::remove(linkInfo.absoluteFilePath()); - linkInfo.refresh(); - - KILE_DEBUG_MAIN << "pipe=" << m_pipes[i] << endl; - KILE_DEBUG_MAIN << "link=" << m_links[i] << endl; - - if(!pipeInfo.exists()) { - //create the dir first - if(!QFileInfo(pipeInfo.absolutePath()).exists()) { - if(mkdir(QFile::encodeName( pipeInfo.path() ), m_perms | S_IXUSR) == -1) { - qCritical() << "Could not create directory for pipe"; - continue; - } - else { - KILE_DEBUG_MAIN << "Created directory " << pipeInfo.path(); - } - } - if (mkfifo(QFile::encodeName( pipeInfo.absoluteFilePath() ), m_perms) != 0) { - qCritical() << "Could not create pipe: " << pipeInfo.absoluteFilePath(); - continue; - } - else { - KILE_DEBUG_MAIN << "Created pipe: " << pipeInfo.absoluteFilePath(); - } - } - - if(symlink(QFile::encodeName(pipeInfo.absoluteFilePath()),QFile::encodeName(linkInfo.absoluteFilePath())) != 0) { - qCritical() << "Could not create symlink: " << linkInfo.absoluteFilePath() << " --> " << pipeInfo.absoluteFilePath(); - continue; - } - - // the file object will be deleted at the shutdown of the server in KileLyxServer::stop() - file = new QFile(pipeInfo.absoluteFilePath()); - pipeInfo.refresh(); - - if(pipeInfo.exists() && file->open(QIODevice::ReadWrite)) { // in that order we don't create the file if it does not exist - KILE_DEBUG_MAIN << "Opened file: " << pipeInfo.absoluteFilePath(); - fstat(file->handle(),stats); - if(!S_ISFIFO(stats->st_mode)) { - qCritical() << "The file " << pipeInfo.absoluteFilePath() << "we just created is not a pipe!"; - file->close(); - delete file; - continue; - } - else { - m_pipeIn.append(file); - m_file.insert(file->handle(), file); - opened = true; - KILE_DEBUG_MAIN << "everything is correct :)" << endl; - } - } - else { - qCritical() << "Could not open " << pipeInfo.absoluteFilePath(); - } - } - return opened; - #endif + KILE_DEBUG_MAIN << "===bool KileLyxServer::openPipes()==="; + +#ifdef Q_OS_WIN + qCritical() << "kile's lyx server can not work on windows since we don't have pipes"; + qCritical() << "And also lyx itself does not support it, see http://wiki.lyx.org/LyX/LyXServer"; + return false; +#else + bool opened = false; + QFileInfo pipeInfo,linkInfo; + QFile *file; + struct stat buf; + struct stat *stats = &buf; + + QDir lyxDir(QDir::homePath() + QDir::separator() + ".lyx"); + if(!lyxDir.exists()) { + KILE_DEBUG_MAIN << "Directory " << lyxDir.absolutePath() << " does not exist"; + if(mkdir(QFile::encodeName( lyxDir.path() ), m_perms | S_IXUSR) == -1) { + qCritical() << "Could not create directory"; + } + else { + KILE_DEBUG_MAIN << "Directory created successfully"; + } + } + + for(int i = 0; i < m_pipes.count(); ++i) { + pipeInfo.setFile(m_pipes[i]); + linkInfo.setFile(m_links[i]); + + QFile::remove(linkInfo.absoluteFilePath()); + linkInfo.refresh(); + + KILE_DEBUG_MAIN << "pipe=" << m_pipes[i] << endl; + KILE_DEBUG_MAIN << "link=" << m_links[i] << endl; + + if(!pipeInfo.exists()) { + //create the dir first + if(!QFileInfo(pipeInfo.absolutePath()).exists()) { + if(mkdir(QFile::encodeName( pipeInfo.path() ), m_perms | S_IXUSR) == -1) { + qCritical() << "Could not create directory for pipe"; + continue; + } + else { + KILE_DEBUG_MAIN << "Created directory " << pipeInfo.path(); + } + } + if (mkfifo(QFile::encodeName( pipeInfo.absoluteFilePath() ), m_perms) != 0) { + qCritical() << "Could not create pipe: " << pipeInfo.absoluteFilePath(); + continue; + } + else { + KILE_DEBUG_MAIN << "Created pipe: " << pipeInfo.absoluteFilePath(); + } + } + + if(symlink(QFile::encodeName(pipeInfo.absoluteFilePath()),QFile::encodeName(linkInfo.absoluteFilePath())) != 0) { + qCritical() << "Could not create symlink: " << linkInfo.absoluteFilePath() << " --> " << pipeInfo.absoluteFilePath(); + continue; + } + + // the file object will be deleted at the shutdown of the server in KileLyxServer::stop() + file = new QFile(pipeInfo.absoluteFilePath()); + pipeInfo.refresh(); + + if(pipeInfo.exists() && file->open(QIODevice::ReadWrite)) { // in that order we don't create the file if it does not exist + KILE_DEBUG_MAIN << "Opened file: " << pipeInfo.absoluteFilePath(); + fstat(file->handle(),stats); + if(!S_ISFIFO(stats->st_mode)) { + qCritical() << "The file " << pipeInfo.absoluteFilePath() << "we just created is not a pipe!"; + file->close(); + delete file; + continue; + } + else { + m_pipeIn.append(file); + m_file.insert(file->handle(), file); + opened = true; + KILE_DEBUG_MAIN << "everything is correct :)" << endl; + } + } + else { + qCritical() << "Could not open " << pipeInfo.absoluteFilePath(); + } + } + return opened; +#endif } void KileLyxServer::stop() { - KILE_DEBUG_MAIN << "Stopping the LyX server..."; + KILE_DEBUG_MAIN << "Stopping the LyX server..."; - for(QList::iterator it = m_pipeIn.begin(); it != m_pipeIn.end(); ++it) { - (*it)->close(); - delete *it; - } + for(QList::iterator it = m_pipeIn.begin(); it != m_pipeIn.end(); ++it) { + (*it)->close(); + delete *it; + } - for(QList::iterator i = m_notifier.begin(); i != m_notifier.end(); ++i) { - delete *i; - } + for(QList::iterator i = m_notifier.begin(); i != m_notifier.end(); ++i) { + delete *i; + } - m_pipeIn.clear(); - m_notifier.clear(); + m_pipeIn.clear(); + m_notifier.clear(); - m_running=false; + m_running=false; } void KileLyxServer::removePipes() { - for (int i = 0; i < m_links.count(); ++i) { - QFile::remove(m_links[i]); - } - for (int i = 0; i < m_pipes.count(); ++i) { - QFile::remove(m_pipes[i]); - } + for (int i = 0; i < m_links.count(); ++i) { + QFile::remove(m_links[i]); + } + for (int i = 0; i < m_pipes.count(); ++i) { + QFile::remove(m_pipes[i]); + } } void KileLyxServer::processLine(const QString &line) { - KILE_DEBUG_MAIN << "===void KileLyxServer::processLine(const QString " << line << ")==="; - - QRegExp reCite(":citation-insert:(.*)$"); - QRegExp reBibtexdbadd(":bibtex-database-add:(.*)$"); - QRegExp rePaste(":paste:(.*)$"); - - if(line.indexOf(reCite) != -1) { - emit(insert(KileAction::TagData(i18n("Cite"), "\\cite{"+reCite.cap(1)+'}'))); - } - else if(line.indexOf(reBibtexdbadd) != -1) { - emit(insert(KileAction::TagData(i18n("Add BibTeX database"), "\\bibliography{"+ reBibtexdbadd.cap(1) + '}'))); - } - else if(line.indexOf(rePaste) != -1) { - emit(insert(KileAction::TagData(i18n("Paste"), rePaste.cap(1)))); - } + KILE_DEBUG_MAIN << "===void KileLyxServer::processLine(const QString " << line << ")==="; + + QRegExp reCite(":citation-insert:(.*)$"); + QRegExp reBibtexdbadd(":bibtex-database-add:(.*)$"); + QRegExp rePaste(":paste:(.*)$"); + + if(line.indexOf(reCite) != -1) { + emit(insert(KileAction::TagData(i18n("Cite"), "\\cite{"+reCite.cap(1)+'}'))); + } + else if(line.indexOf(reBibtexdbadd) != -1) { + emit(insert(KileAction::TagData(i18n("Add BibTeX database"), "\\bibliography{"+ reBibtexdbadd.cap(1) + '}'))); + } + else if(line.indexOf(rePaste) != -1) { + emit(insert(KileAction::TagData(i18n("Paste"), rePaste.cap(1)))); + } } void KileLyxServer::receive(int fd) { - if(m_file[fd]) { - int bytesRead; - int const size = 256; - char buffer[size]; - if((bytesRead = read(fd, buffer, size - 1)) > 0) { - buffer[bytesRead] = '\0'; // turn it into a c string - QStringList cmds = QString(buffer).trimmed().split('\n'); - for(int i = 0; i < cmds.count(); ++i) { - processLine(cmds[i]); - } - } - } + if(m_file[fd]) { + int bytesRead; + int const size = 256; + char buffer[size]; + if((bytesRead = read(fd, buffer, size - 1)) > 0) { + buffer[bytesRead] = '\0'; // turn it into a c string + QStringList cmds = QString(buffer).trimmed().split('\n'); + for(int i = 0; i < cmds.count(); ++i) { + processLine(cmds[i]); + } + } + } } diff --git a/src/kilelyxserver.h b/src/kilelyxserver.h index 20eb59f0..ebe1796b 100644 --- a/src/kilelyxserver.h +++ b/src/kilelyxserver.h @@ -1,83 +1,87 @@ /*************************************************************************** begin : Sat Sept 9 2003 copyright : (C) 2003 by Jeroen Wijnhout email : Jeroen.Wijnhout@kdemail.net ***************************************************************************/ /*************************************************************************** * * * 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. * * * ***************************************************************************/ #ifndef _LYXSERVER_H_ #define _LYXSERVER_H_ #ifdef HAVE_CONFIG_H #include #endif #include #include #include #include #include #include #ifdef _MSC_VER typedef int mode_t; #endif /** * @short Simple server that impersonates as LyX to work with gBib, pyBibliographer etc. * @author Jeroen Wijnhout * @author Thomas Braun * @version 0.2 */ class QFile; class QSocketNotifier; -namespace KileAction { class TagData; } +namespace KileAction { +class TagData; +} class KileLyxServer : public QObject { - Q_OBJECT + Q_OBJECT public: - KileLyxServer(bool start = true); - ~KileLyxServer(); + KileLyxServer(bool start = true); + ~KileLyxServer(); - bool isRunning() { return m_running; } + bool isRunning() { + return m_running; + } public Q_SLOTS: - bool start(); - void stop(); + bool start(); + void stop(); private Q_SLOTS: - void receive(int); - + void receive(int); + private: - bool openPipes(); - void removePipes(); - void processLine(const QString &); + bool openPipes(); + void removePipes(); + void processLine(const QString &); Q_SIGNALS: - void insert(const KileAction::TagData &); + void insert(const KileAction::TagData &); private: - mode_t m_perms; - QTemporaryDir *m_tempDir; - QList m_pipeIn; - QList m_notifier; - QHash m_file; - bool m_running; - QStringList m_links,m_pipes; + mode_t m_perms; + QTemporaryDir *m_tempDir; + QList m_pipeIn; + QList m_notifier; + QHash m_file; + bool m_running; + QStringList m_links,m_pipes; }; #endif // _LYXSERVER_H_ diff --git a/src/kileproject.cpp b/src/kileproject.cpp index 39978152..f4f94bab 100644 --- a/src/kileproject.cpp +++ b/src/kileproject.cpp @@ -1,1009 +1,1009 @@ /******************************************************************************************** begin : Fri Aug 1 2003 copyright : (C) 2003 by Jeroen Wijnhout (Jeroen.Wijnhout@kdemail.net) (C) 2007 by Holger Danielsson (holger.danielsson@versanet.de) (C) 2009-2016 by Michel Ludwig (michel.ludwig@kdemail.net) *********************************************************************************************/ /*************************************************************************** * * * 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. * * * ***************************************************************************/ // 2007-03-12 dani // - use KileDocument::Extensions // - allowed extensions are always defined as list, f.e.: .tex .ltx .latex #include "kileproject.h" #include #include #include #include #include #include #include #include "documentinfo.h" #include "kiledebug.h" #include "kiledocmanager.h" #include "kiletoolmanager.h" #include "kileinfo.h" #include "kileextensions.h" #include "livepreview.h" /** * Since project file version 3, project files 'consist' of two files: one file named '.kilepr' and * one file named '.kilepr.gui' located in the '.kile' subdirectory of the project directory. * The former files contains the static structure of the project, and the later contains the current gui display settings * (like which file is open or on which line and column the cursors are). */ /* * KileProjectItem */ KileProjectItem::KileProjectItem(KileProject *project, const QUrl &url, int type) : - m_project(project), - m_url(url), - m_type(type), - m_docinfo(Q_NULLPTR), - m_parent(Q_NULLPTR), - m_child(Q_NULLPTR), - m_sibling(Q_NULLPTR), - m_order(-1) -{ - m_bOpen = m_archive = true; - - if (project) { - project->add(this); - } + m_project(project), + m_url(url), + m_type(type), + m_docinfo(Q_NULLPTR), + m_parent(Q_NULLPTR), + m_child(Q_NULLPTR), + m_sibling(Q_NULLPTR), + m_order(-1) +{ + m_bOpen = m_archive = true; + + if (project) { + project->add(this); + } } void KileProjectItem::setOrder(int i) { - m_order = i; + m_order = i; } void KileProjectItem::setParent(KileProjectItem * item) { - m_parent = item; - - //update parent info - if (m_parent) { - if (m_parent->firstChild()) { - //get last child - KileProjectItem *sib = m_parent->firstChild(); - while (sib->sibling()) { - sib = sib->sibling(); - } - - sib->setSibling(this); - } - else { - m_parent->setChild(this); - } - } - else { - setChild(0); - setSibling(0); - } + m_parent = item; + + //update parent info + if (m_parent) { + if (m_parent->firstChild()) { + //get last child + KileProjectItem *sib = m_parent->firstChild(); + while (sib->sibling()) { + sib = sib->sibling(); + } + + sib->setSibling(this); + } + else { + m_parent->setChild(this); + } + } + else { + setChild(0); + setSibling(0); + } } void KileProjectItem::load() { - KConfigGroup projectConfigGroup = m_project->configGroupForItem(this, KileProject::ProjectFile); - KConfigGroup guiConfigGroup = m_project->configGroupForItem(this, KileProject::GUIFile); - // project: archive, highlight, mode - // gui: column, encoding, line, open, order - setEncoding(projectConfigGroup.readEntry("encoding", QString())); - setMode(projectConfigGroup.readEntry("mode", QString())); - setHighlight(projectConfigGroup.readEntry("highlight", QString())); - setArchive(projectConfigGroup.readEntry("archive", true)); - setOpenState(guiConfigGroup.readEntry("open", true)); - setOrder(guiConfigGroup.readEntry("order", -1)); + KConfigGroup projectConfigGroup = m_project->configGroupForItem(this, KileProject::ProjectFile); + KConfigGroup guiConfigGroup = m_project->configGroupForItem(this, KileProject::GUIFile); + // project: archive, highlight, mode + // gui: column, encoding, line, open, order + setEncoding(projectConfigGroup.readEntry("encoding", QString())); + setMode(projectConfigGroup.readEntry("mode", QString())); + setHighlight(projectConfigGroup.readEntry("highlight", QString())); + setArchive(projectConfigGroup.readEntry("archive", true)); + setOpenState(guiConfigGroup.readEntry("open", true)); + setOrder(guiConfigGroup.readEntry("order", -1)); } void KileProjectItem::save() { - KConfigGroup projectConfigGroup = m_project->configGroupForItem(this, KileProject::ProjectFile); - KConfigGroup guiConfigGroup = m_project->configGroupForItem(this, KileProject::GUIFile); - // project: archive, highlight, mode - // gui: encoding, open, order - projectConfigGroup.writeEntry("encoding", encoding()); - projectConfigGroup.writeEntry("mode", mode()); - projectConfigGroup.writeEntry("highlight", highlight()); - projectConfigGroup.writeEntry("archive", archive()); - guiConfigGroup.writeEntry("open", isOpen()); - guiConfigGroup.writeEntry("order", order()); + KConfigGroup projectConfigGroup = m_project->configGroupForItem(this, KileProject::ProjectFile); + KConfigGroup guiConfigGroup = m_project->configGroupForItem(this, KileProject::GUIFile); + // project: archive, highlight, mode + // gui: encoding, open, order + projectConfigGroup.writeEntry("encoding", encoding()); + projectConfigGroup.writeEntry("mode", mode()); + projectConfigGroup.writeEntry("highlight", highlight()); + projectConfigGroup.writeEntry("archive", archive()); + guiConfigGroup.writeEntry("open", isOpen()); + guiConfigGroup.writeEntry("order", order()); } void KileProjectItem::loadDocumentAndViewSettings() { - if(!m_docinfo) { - return; - } - KTextEditor::Document *document = m_docinfo->getDocument(); - if(!document) { - return; - } - QList viewList = document->views(); - loadDocumentSettings(document); - int i = 0; - for(QList::iterator it = viewList.begin(); it != viewList.end(); ++it) { - loadViewSettings(*it, i); - ++i; - } + if(!m_docinfo) { + return; + } + KTextEditor::Document *document = m_docinfo->getDocument(); + if(!document) { + return; + } + QList viewList = document->views(); + loadDocumentSettings(document); + int i = 0; + for(QList::iterator it = viewList.begin(); it != viewList.end(); ++it) { + loadViewSettings(*it, i); + ++i; + } } void KileProjectItem::saveDocumentAndViewSettings() { - if(!m_docinfo) { - return; - } - KTextEditor::Document *document = m_docinfo->getDocument(); - if(!document) { - return; - } - QList viewList = document->views(); - saveDocumentSettings(document); - int i = 0; - for(QList::iterator it = viewList.begin(); it != viewList.end(); ++it) { - saveViewSettings(*it, i); - ++i; - } + if(!m_docinfo) { + return; + } + KTextEditor::Document *document = m_docinfo->getDocument(); + if(!document) { + return; + } + QList viewList = document->views(); + saveDocumentSettings(document); + int i = 0; + for(QList::iterator it = viewList.begin(); it != viewList.end(); ++it) { + saveViewSettings(*it, i); + ++i; + } } void KileProjectItem::loadViewSettings(KTextEditor::View *view, int viewIndex) { - KConfigGroup configGroup = m_project->configGroupForItemViewSettings(this, viewIndex); - view->readSessionConfig(configGroup); + KConfigGroup configGroup = m_project->configGroupForItemViewSettings(this, viewIndex); + view->readSessionConfig(configGroup); } void KileProjectItem::saveViewSettings(KTextEditor::View *view, int viewIndex) { - KConfigGroup configGroup = m_project->configGroupForItemViewSettings(this, viewIndex); - view->writeSessionConfig(configGroup); + KConfigGroup configGroup = m_project->configGroupForItemViewSettings(this, viewIndex); + view->writeSessionConfig(configGroup); } void KileProjectItem::loadDocumentSettings(KTextEditor::Document *document) { - KConfigGroup configGroup = m_project->configGroupForItemDocumentSettings(this); - if(!configGroup.exists()) { - return; - } - document->readSessionConfig(configGroup, QSet() << "SkipUrl"); + KConfigGroup configGroup = m_project->configGroupForItemDocumentSettings(this); + if(!configGroup.exists()) { + return; + } + document->readSessionConfig(configGroup, QSet() << "SkipUrl"); } void KileProjectItem::saveDocumentSettings(KTextEditor::Document *document) { - KConfigGroup configGroup = m_project->configGroupForItemDocumentSettings(this); - document->writeSessionConfig(configGroup, QSet() << "SkipUrl"); + KConfigGroup configGroup = m_project->configGroupForItemDocumentSettings(this); + document->writeSessionConfig(configGroup, QSet() << "SkipUrl"); } void KileProjectItem::print(int level) { - QString str; - str.fill('\t', level); - KILE_DEBUG_MAIN << str << "+" << url().fileName(); + QString str; + str.fill('\t', level); + KILE_DEBUG_MAIN << str << "+" << url().fileName(); - if (firstChild()) { - firstChild()->print(++level); - } + if (firstChild()) { + firstChild()->print(++level); + } - if (sibling()) { - sibling()->print(level); - } + if (sibling()) { + sibling()->print(level); + } } void KileProjectItem::allChildren(QList *list) const { - KileProjectItem *item = firstChild(); + KileProjectItem *item = firstChild(); // KILE_DEBUG_MAIN << "\tKileProjectItem::allChildren(" << list->count() << ")"; - while(item != Q_NULLPTR) { - list->append(item); + while(item != Q_NULLPTR) { + list->append(item); // KILE_DEBUG_MAIN << "\t\tappending " << item->url().fileName(); - item->allChildren(list); - item = item->sibling(); - } + item->allChildren(list); + item = item->sibling(); + } } void KileProjectItem::setInfo(KileDocument::TextInfo *docinfo) { - m_docinfo = docinfo; - if(docinfo) - { - connect(docinfo,SIGNAL(urlChanged(KileDocument::Info*, const QUrl &)), this, SLOT(slotChangeURL(KileDocument::Info*, const QUrl &))); - connect(docinfo,SIGNAL(depChanged()), m_project, SLOT(buildProjectTree())); - } + m_docinfo = docinfo; + if(docinfo) + { + connect(docinfo,SIGNAL(urlChanged(KileDocument::Info*, const QUrl &)), this, SLOT(slotChangeURL(KileDocument::Info*, const QUrl &))); + connect(docinfo,SIGNAL(depChanged()), m_project, SLOT(buildProjectTree())); + } } void KileProjectItem::changeURL(const QUrl &url) { - // don't allow empty URLs - if(!url.isEmpty() && m_url != url) - { - m_url = url; - emit(urlChanged(this)); - } + // don't allow empty URLs + if(!url.isEmpty() && m_url != url) + { + m_url = url; + emit(urlChanged(this)); + } } void KileProjectItem::slotChangeURL(KileDocument::Info*, const QUrl &url) { - changeURL(url); + changeURL(url); } /* * KileProject */ // for creating an empty project KileProject::KileProject(const QString& name, const QUrl &url, KileDocument::Extensions *extensions) -: QObject(Q_NULLPTR), m_invalid(false), m_masterDocument(QString()), m_useMakeIndexOptions(false), - m_config(Q_NULLPTR), m_guiConfig(Q_NULLPTR), m_extmanager(extensions) + : QObject(Q_NULLPTR), m_invalid(false), m_masterDocument(QString()), m_useMakeIndexOptions(false), + m_config(Q_NULLPTR), m_guiConfig(Q_NULLPTR), m_extmanager(extensions) { - m_name = name; - init(url); + m_name = name; + init(url); - //create the project file - KConfigGroup configGroup = m_config->group("General"); - configGroup.writeEntry("name", m_name); - configGroup.writeEntry("kileprversion", KILE_PROJECTFILE_VERSION); - configGroup.writeEntry("kileversion", kileFullVersion); + //create the project file + KConfigGroup configGroup = m_config->group("General"); + configGroup.writeEntry("name", m_name); + configGroup.writeEntry("kileprversion", KILE_PROJECTFILE_VERSION); + configGroup.writeEntry("kileversion", kileFullVersion); - load(); + load(); } // for opening an existing project, 'load()' still has to be called separately! KileProject::KileProject(const QUrl &url, KileDocument::Extensions *extensions) -: QObject(Q_NULLPTR), m_invalid(false), m_masterDocument(QString()), m_useMakeIndexOptions(false), - m_config(Q_NULLPTR), m_guiConfig(Q_NULLPTR), m_extmanager(extensions) + : QObject(Q_NULLPTR), m_invalid(false), m_masterDocument(QString()), m_useMakeIndexOptions(false), + m_config(Q_NULLPTR), m_guiConfig(Q_NULLPTR), m_extmanager(extensions) { - init(url); + init(url); } KileProject::~KileProject() { - KILE_DEBUG_MAIN << "DELETING KILEPROJECT " << m_projecturl.url(); - emit(aboutToBeDestroyed(this)); - delete m_guiConfig; - delete m_config; + KILE_DEBUG_MAIN << "DELETING KILEPROJECT " << m_projecturl.url(); + emit(aboutToBeDestroyed(this)); + delete m_guiConfig; + delete m_config; - for(QList::iterator it = m_projectItems.begin(); it != m_projectItems.end(); ++it) { - delete *it; - } + for(QList::iterator it = m_projectItems.begin(); it != m_projectItems.end(); ++it) { + delete *it; + } } void KileProject::init(const QUrl &url) { - m_projecturl = KileDocument::Manager::symlinkFreeURL(url); + m_projecturl = KileDocument::Manager::symlinkFreeURL(url); - m_baseurl = m_projecturl.adjusted(QUrl::RemoveFilename); + m_baseurl = m_projecturl.adjusted(QUrl::RemoveFilename); - KILE_DEBUG_MAIN << "KileProject m_baseurl = " << m_baseurl.toLocalFile(); + KILE_DEBUG_MAIN << "KileProject m_baseurl = " << m_baseurl.toLocalFile(); - m_config = new KConfig(m_projecturl.toLocalFile(), KConfig::SimpleConfig); + m_config = new KConfig(m_projecturl.toLocalFile(), KConfig::SimpleConfig); } void KileProject::setLastDocument(const QUrl &url) { if (item(url) != 0) { m_lastDocument = KileDocument::Manager::symlinkFreeURL(url); } } void KileProject::setExtensions(KileProjectItem::Type type, const QString & ext) { - if (type == KileProjectItem::ProjectFile || type >= KileProjectItem::Other) - { - qWarning() << "ERROR: invalid project item type:" << type; - return; - } - - // first we take all standard extensions - QStringList standardExtList; - if(type == KileProjectItem::Source) { - standardExtList = (m_extmanager->latexDocuments()).split(' '); - } - else if(type == KileProjectItem::Package) { - standardExtList = (m_extmanager->latexPackages()).split(' '); - } - else if(type == KileProjectItem::Image) { - standardExtList = (m_extmanager->images()).split(' '); - } - else if(type == KileProjectItem::Bibliography) { - standardExtList = (m_extmanager->bibtex()).split(' '); - } - - // now we scan user-defined list and accept all extension, - // except standard extensions of course - QString userExt; - if(!ext.isEmpty()) { - QStringList userExtList; - - QStringList::ConstIterator it; - QStringList list = ext.split(' '); - for(it = list.constBegin(); it != list.constEnd(); ++it) { - // some tiny extension checks - if((*it).length() < 2 || (*it)[0] != '.') { - continue; - } - - // some of the old definitions are wrong, so we test them all - if(type == KileProjectItem::Source || type == KileProjectItem::Package) { - if(!(m_extmanager->isLatexDocument(*it) || m_extmanager->isLatexPackage(*it))) { - standardExtList << (*it); - userExtList << (*it); - } - } - else if(type == KileProjectItem::Image) { - if(!m_extmanager->isImage(*it)) { - standardExtList << (*it); - userExtList << (*it); - } - } - else if(type == KileProjectItem::Bibliography) { - if(!m_extmanager->isBibFile(*it)) { - standardExtList << (*it); - userExtList << (*it); - } - } - } - if(userExtList.count() > 0) { - userExt = userExtList.join(" "); - } - } - - // now we build a regular expression for all extensions - // (used to search for a filename with a valid extension) - QString pattern = standardExtList.join("|"); - pattern.replace('.', "\\."); - pattern = '('+ pattern +")$"; - - // and save it - m_reExtensions[type-1].setPattern(pattern); - - // if the list of user-defined extensions has changed - // we save the new value and (re)build the project tree - if (m_extensions[type-1] != userExt) { - m_extensions[type-1] = userExt; - buildProjectTree(); - } -} - -void KileProject::setDefaultGraphicExt(const QString & ext){ - m_defGraphicExt = ext; -} - -const QString & KileProject::defaultGraphicExt(){ - return m_defGraphicExt; + if (type == KileProjectItem::ProjectFile || type >= KileProjectItem::Other) + { + qWarning() << "ERROR: invalid project item type:" << type; + return; + } + + // first we take all standard extensions + QStringList standardExtList; + if(type == KileProjectItem::Source) { + standardExtList = (m_extmanager->latexDocuments()).split(' '); + } + else if(type == KileProjectItem::Package) { + standardExtList = (m_extmanager->latexPackages()).split(' '); + } + else if(type == KileProjectItem::Image) { + standardExtList = (m_extmanager->images()).split(' '); + } + else if(type == KileProjectItem::Bibliography) { + standardExtList = (m_extmanager->bibtex()).split(' '); + } + + // now we scan user-defined list and accept all extension, + // except standard extensions of course + QString userExt; + if(!ext.isEmpty()) { + QStringList userExtList; + + QStringList::ConstIterator it; + QStringList list = ext.split(' '); + for(it = list.constBegin(); it != list.constEnd(); ++it) { + // some tiny extension checks + if((*it).length() < 2 || (*it)[0] != '.') { + continue; + } + + // some of the old definitions are wrong, so we test them all + if(type == KileProjectItem::Source || type == KileProjectItem::Package) { + if(!(m_extmanager->isLatexDocument(*it) || m_extmanager->isLatexPackage(*it))) { + standardExtList << (*it); + userExtList << (*it); + } + } + else if(type == KileProjectItem::Image) { + if(!m_extmanager->isImage(*it)) { + standardExtList << (*it); + userExtList << (*it); + } + } + else if(type == KileProjectItem::Bibliography) { + if(!m_extmanager->isBibFile(*it)) { + standardExtList << (*it); + userExtList << (*it); + } + } + } + if(userExtList.count() > 0) { + userExt = userExtList.join(" "); + } + } + + // now we build a regular expression for all extensions + // (used to search for a filename with a valid extension) + QString pattern = standardExtList.join("|"); + pattern.replace('.', "\\."); + pattern = '('+ pattern +")$"; + + // and save it + m_reExtensions[type-1].setPattern(pattern); + + // if the list of user-defined extensions has changed + // we save the new value and (re)build the project tree + if (m_extensions[type-1] != userExt) { + m_extensions[type-1] = userExt; + buildProjectTree(); + } +} + +void KileProject::setDefaultGraphicExt(const QString & ext) { + m_defGraphicExt = ext; +} + +const QString & KileProject::defaultGraphicExt() { + return m_defGraphicExt; } void KileProject::setType(KileProjectItem *item) { - if(item->path().right(7) == ".kilepr") { - item->setType(KileProjectItem::ProjectFile); - return; - } + if(item->path().right(7) == ".kilepr") { + item->setType(KileProjectItem::ProjectFile); + return; + } - bool unknown = true; - for(int i = KileProjectItem::Source; i < KileProjectItem::Other; ++i) { - if(m_reExtensions[i-1].indexIn(item->url().fileName()) != -1) { - item->setType(i); - unknown = false; - break; - } - } + bool unknown = true; + for(int i = KileProjectItem::Source; i < KileProjectItem::Other; ++i) { + if(m_reExtensions[i-1].indexIn(item->url().fileName()) != -1) { + item->setType(i); + unknown = false; + break; + } + } - if(unknown) { - item->setType(KileProjectItem::Other); - } + if(unknown) { + item->setType(KileProjectItem::Other); + } } void KileProject::readMakeIndexOptions() { - QString grp = KileTool::groupFor("MakeIndex", m_config); + QString grp = KileTool::groupFor("MakeIndex", m_config); - //get the default value - KSharedConfig::Ptr cfg = KSharedConfig::openConfig(); - KConfigGroup configGroup = cfg->group(KileTool::groupFor("MakeIndex", KileTool::configName("MakeIndex", cfg.data()))); - QString deflt = configGroup.readEntry("options", "'%S'.idx"); + //get the default value + KSharedConfig::Ptr cfg = KSharedConfig::openConfig(); + KConfigGroup configGroup = cfg->group(KileTool::groupFor("MakeIndex", KileTool::configName("MakeIndex", cfg.data()))); + QString deflt = configGroup.readEntry("options", "'%S'.idx"); - if (useMakeIndexOptions() && !grp.isEmpty()) { - KConfigGroup makeIndexGroup = m_config->group(grp); - QString val = makeIndexGroup.readEntry("options", deflt); - if ( val.isEmpty() ) val = deflt; - setMakeIndexOptions(val); - } - else { //use default value - setMakeIndexOptions(deflt); - } + if (useMakeIndexOptions() && !grp.isEmpty()) { + KConfigGroup makeIndexGroup = m_config->group(grp); + QString val = makeIndexGroup.readEntry("options", deflt); + if ( val.isEmpty() ) val = deflt; + setMakeIndexOptions(val); + } + else { //use default value + setMakeIndexOptions(deflt); + } } void KileProject::writeUseMakeIndexOptions() { - if ( useMakeIndexOptions() ) - KileTool::setConfigName("MakeIndex", "Default", m_config); - else - KileTool::setConfigName("MakeIndex", "", m_config); + if ( useMakeIndexOptions() ) + KileTool::setConfigName("MakeIndex", "Default", m_config); + else + KileTool::setConfigName("MakeIndex", "", m_config); } QString KileProject::addBaseURL(const QString &path) { - KILE_DEBUG_MAIN << "===addBaseURL(const QString & " << path << " )"; - if(path.isEmpty()) { - return path; - } + KILE_DEBUG_MAIN << "===addBaseURL(const QString & " << path << " )"; + if(path.isEmpty()) { + return path; + } - else if(QDir::isAbsolutePath(path)) { - return KileDocument::Manager::symlinkFreeURL(QUrl::fromLocalFile(path)).toLocalFile(); - } - else { - return KileDocument::Manager::symlinkFreeURL(QUrl::fromLocalFile(m_baseurl.adjusted(QUrl::StripTrailingSlash).toLocalFile() + '/' + path)).toLocalFile(); - } + else if(QDir::isAbsolutePath(path)) { + return KileDocument::Manager::symlinkFreeURL(QUrl::fromLocalFile(path)).toLocalFile(); + } + else { + return KileDocument::Manager::symlinkFreeURL(QUrl::fromLocalFile(m_baseurl.adjusted(QUrl::StripTrailingSlash).toLocalFile() + '/' + path)).toLocalFile(); + } } QString KileProject::removeBaseURL(const QString &path) { - if(QDir::isAbsolutePath(path)) { - QFileInfo info(path); - QString relPath = findRelativePath(path); - KILE_DEBUG_MAIN << "removeBaseURL path is" << path << " , relPath is " << relPath; - return relPath; - } - else { - return path; - } + if(QDir::isAbsolutePath(path)) { + QFileInfo info(path); + QString relPath = findRelativePath(path); + KILE_DEBUG_MAIN << "removeBaseURL path is" << path << " , relPath is " << relPath; + return relPath; + } + else { + return path; + } } bool KileProject::appearsToBeValidProjectFile() { - if(!m_config->hasGroup("General")) { - return false; - } + if(!m_config->hasGroup("General")) { + return false; + } - KConfigGroup generalGroup = m_config->group("General"); - return generalGroup.hasKey("name") && generalGroup.hasKey("kileprversion") && generalGroup.hasKey("kileversion"); + KConfigGroup generalGroup = m_config->group("General"); + return generalGroup.hasKey("name") && generalGroup.hasKey("kileprversion") && generalGroup.hasKey("kileversion"); } int KileProject::getProjectFileVersion() { - KConfigGroup generalGroup = m_config->group("General"); + KConfigGroup generalGroup = m_config->group("General"); - return generalGroup.readEntry("kileprversion", 0); + return generalGroup.readEntry("kileprversion", 0); } // WARNING: before calling this method, the project file must be of the current 'kileprversion'! // also assumes that 'm_name' has been set correctly already if this is a fresh (empty) project! bool KileProject::load() { - KILE_DEBUG_MAIN << "KileProject: loading..." << endl; - - if(!ensurePrivateKileDirectoryExists(m_projecturl)) { - return false; - } + KILE_DEBUG_MAIN << "KileProject: loading..." << endl; - delete m_guiConfig; - m_guiConfig = new KConfig(getPathForGUISettingsProjectFile(m_projecturl), KConfig::SimpleConfig); - - //load general settings/options - KConfigGroup generalGroup = m_config->group("General"); - m_name = generalGroup.readEntry("name", m_name); - - m_defGraphicExt = generalGroup.readEntry("def_graphic_ext", QString()); + if(!ensurePrivateKileDirectoryExists(m_projecturl)) { + return false; + } - QString master = addBaseURL(generalGroup.readEntry("masterDocument", QString())); - KILE_DEBUG_MAIN << "masterDoc == " << master; - setMasterDocument(master); + delete m_guiConfig; + m_guiConfig = new KConfig(getPathForGUISettingsProjectFile(m_projecturl), KConfig::SimpleConfig); - setExtensions(KileProjectItem::Source, generalGroup.readEntry("src_extensions",m_extmanager->latexDocuments())); - setExtensions(KileProjectItem::Package, generalGroup.readEntry("pkg_extensions",m_extmanager->latexPackages())); - setExtensions(KileProjectItem::Image, generalGroup.readEntry("img_extensions",m_extmanager->images())); - setExtensions(KileProjectItem::Bibliography, generalGroup.readEntry("bib_extensions", m_extmanager->bibtex())); + //load general settings/options + KConfigGroup generalGroup = m_config->group("General"); + m_name = generalGroup.readEntry("name", m_name); - setQuickBuildConfig(KileTool::configName("QuickBuild", m_config)); + m_defGraphicExt = generalGroup.readEntry("def_graphic_ext", QString()); - if( KileTool::configName("MakeIndex",m_config).compare("Default") == 0) { - setUseMakeIndexOptions(true); - } - else { - setUseMakeIndexOptions(false); - } + QString master = addBaseURL(generalGroup.readEntry("masterDocument", QString())); + KILE_DEBUG_MAIN << "masterDoc == " << master; + setMasterDocument(master); - readMakeIndexOptions(); + setExtensions(KileProjectItem::Source, generalGroup.readEntry("src_extensions",m_extmanager->latexDocuments())); + setExtensions(KileProjectItem::Package, generalGroup.readEntry("pkg_extensions",m_extmanager->latexPackages())); + setExtensions(KileProjectItem::Image, generalGroup.readEntry("img_extensions",m_extmanager->images())); + setExtensions(KileProjectItem::Bibliography, generalGroup.readEntry("bib_extensions", m_extmanager->bibtex())); - QUrl url; - KileProjectItem *item; - const QStringList groups = m_config->groupList(); + setQuickBuildConfig(KileTool::configName("QuickBuild", m_config)); - //retrieve all the project files and create and initialize project items for them - for (auto group : groups) { - if(!m_config->hasGroup(group)) { // 'group' might have been deleted - continue; // work around bug 384039 - } - if (group.left(5) == "item:") { - QString path = group.mid(5); - if (QDir::isAbsolutePath(path)) { - url = QUrl::fromLocalFile(path); - } - else { - url = m_baseurl.adjusted(QUrl::StripTrailingSlash); - url.setPath(url.path() + '/' + path); - } - item = new KileProjectItem(this, KileDocument::Manager::symlinkFreeURL(url)); - setType(item); + if( KileTool::configName("MakeIndex",m_config).compare("Default") == 0) { + setUseMakeIndexOptions(true); + } + else { + setUseMakeIndexOptions(false); + } - KConfigGroup configGroup = m_config->group(group); - // path has to be set before we can load it - item->changePath(group.mid(5)); - item->load(); - connect(item, SIGNAL(urlChanged(KileProjectItem*)), this, SLOT(itemRenamed(KileProjectItem*)) ); - } - } + readMakeIndexOptions(); + + QUrl url; + KileProjectItem *item; + const QStringList groups = m_config->groupList(); + + //retrieve all the project files and create and initialize project items for them + for (auto group : groups) { + if(!m_config->hasGroup(group)) { // 'group' might have been deleted + continue; // work around bug 384039 + } + if (group.left(5) == "item:") { + QString path = group.mid(5); + if (QDir::isAbsolutePath(path)) { + url = QUrl::fromLocalFile(path); + } + else { + url = m_baseurl.adjusted(QUrl::StripTrailingSlash); + url.setPath(url.path() + '/' + path); + } + item = new KileProjectItem(this, KileDocument::Manager::symlinkFreeURL(url)); + setType(item); + + KConfigGroup configGroup = m_config->group(group); + // path has to be set before we can load it + item->changePath(group.mid(5)); + item->load(); + connect(item, SIGNAL(urlChanged(KileProjectItem*)), this, SLOT(itemRenamed(KileProjectItem*)) ); + } + } - // only call this after all items are created, otherwise setLastDocument doesn't accept the url - KConfigGroup guiGeneralGroup = m_guiConfig->group("General"); - setLastDocument(QUrl::fromLocalFile(addBaseURL(guiGeneralGroup.readEntry("lastDocument", QString())))); + // only call this after all items are created, otherwise setLastDocument doesn't accept the url + KConfigGroup guiGeneralGroup = m_guiConfig->group("General"); + setLastDocument(QUrl::fromLocalFile(addBaseURL(guiGeneralGroup.readEntry("lastDocument", QString())))); - generalGroup = m_config->group("General"); + generalGroup = m_config->group("General"); - readBibliographyBackendSettings(generalGroup); + readBibliographyBackendSettings(generalGroup); - KileTool::LivePreviewManager::readLivePreviewStatusSettings(guiGeneralGroup, this); + KileTool::LivePreviewManager::readLivePreviewStatusSettings(guiGeneralGroup, this); // dump(); - return true; + return true; } bool KileProject::save() { - KILE_DEBUG_MAIN << "KileProject: saving..." <group("General"); - KConfigGroup guiGeneralGroup = m_guiConfig->group("General"); + KConfigGroup generalGroup = m_config->group("General"); + KConfigGroup guiGeneralGroup = m_guiConfig->group("General"); - generalGroup.writeEntry("name", m_name); - generalGroup.writeEntry("kileprversion", KILE_PROJECTFILE_VERSION); - generalGroup.writeEntry("kileversion", kileFullVersion); - generalGroup.writeEntry("def_graphic_ext", m_defGraphicExt); + generalGroup.writeEntry("name", m_name); + generalGroup.writeEntry("kileprversion", KILE_PROJECTFILE_VERSION); + generalGroup.writeEntry("kileversion", kileFullVersion); + generalGroup.writeEntry("def_graphic_ext", m_defGraphicExt); - KILE_DEBUG_MAIN << "KileProject::save() masterDoc = " << removeBaseURL(m_masterDocument); - generalGroup.writeEntry("masterDocument", removeBaseURL(m_masterDocument)); - guiGeneralGroup.writeEntry("lastDocument", removeBaseURL(m_lastDocument.toLocalFile())); + KILE_DEBUG_MAIN << "KileProject::save() masterDoc = " << removeBaseURL(m_masterDocument); + generalGroup.writeEntry("masterDocument", removeBaseURL(m_masterDocument)); + guiGeneralGroup.writeEntry("lastDocument", removeBaseURL(m_lastDocument.toLocalFile())); - writeBibliographyBackendSettings(generalGroup); + writeBibliographyBackendSettings(generalGroup); - KileTool::LivePreviewManager::writeLivePreviewStatusSettings(guiGeneralGroup, this); + KileTool::LivePreviewManager::writeLivePreviewStatusSettings(guiGeneralGroup, this); - writeConfigEntry("src_extensions",m_extmanager->latexDocuments(),KileProjectItem::Source); - writeConfigEntry("pkg_extensions",m_extmanager->latexPackages(),KileProjectItem::Package); - writeConfigEntry("img_extensions",m_extmanager->images(),KileProjectItem::Image); - writeConfigEntry("bib_extensions", m_extmanager->bibtex(), KileProjectItem::Bibliography); - // only to avoid problems with older versions - generalGroup.writeEntry("src_extIsRegExp", false); - generalGroup.writeEntry("pkg_extIsRegExp", false); - generalGroup.writeEntry("img_extIsRegExp", false); + writeConfigEntry("src_extensions",m_extmanager->latexDocuments(),KileProjectItem::Source); + writeConfigEntry("pkg_extensions",m_extmanager->latexPackages(),KileProjectItem::Package); + writeConfigEntry("img_extensions",m_extmanager->images(),KileProjectItem::Image); + writeConfigEntry("bib_extensions", m_extmanager->bibtex(), KileProjectItem::Bibliography); + // only to avoid problems with older versions + generalGroup.writeEntry("src_extIsRegExp", false); + generalGroup.writeEntry("pkg_extIsRegExp", false); + generalGroup.writeEntry("img_extIsRegExp", false); - for(QList::iterator it = m_projectItems.begin(); it != m_projectItems.end(); ++it) { - (*it)->save(); - } + for(QList::iterator it = m_projectItems.begin(); it != m_projectItems.end(); ++it) { + (*it)->save(); + } - KileTool::setConfigName("QuickBuild", quickBuildConfig(), m_config); + KileTool::setConfigName("QuickBuild", quickBuildConfig(), m_config); - writeUseMakeIndexOptions(); - if(useMakeIndexOptions()) { - QString grp = KileTool::groupFor("MakeIndex", m_config); - if(grp.isEmpty()) { - grp = "Default"; - } - KConfigGroup configGroup = m_config->group(grp); - configGroup.writeEntry("options", makeIndexOptions()); - } + writeUseMakeIndexOptions(); + if(useMakeIndexOptions()) { + QString grp = KileTool::groupFor("MakeIndex", m_config); + if(grp.isEmpty()) { + grp = "Default"; + } + KConfigGroup configGroup = m_config->group(grp); + configGroup.writeEntry("options", makeIndexOptions()); + } - m_config->sync(); - m_guiConfig->sync(); + m_config->sync(); + m_guiConfig->sync(); - // dump(); + // dump(); - return true; + return true; } void KileProject::writeConfigEntry(const QString &key, const QString &standardExt, KileProjectItem::Type type) { - KConfigGroup generalGroup = m_config->group("General"); - QString userExt = extensions(type); - if(userExt.isEmpty()) { - generalGroup.writeEntry(key, standardExt); - } - else { - generalGroup.writeEntry(key, standardExt + ' ' + extensions(type)); - } + KConfigGroup generalGroup = m_config->group("General"); + QString userExt = extensions(type); + if(userExt.isEmpty()) { + generalGroup.writeEntry(key, standardExt); + } + else { + generalGroup.writeEntry(key, standardExt + ' ' + extensions(type)); + } } KConfigGroup KileProject::configGroupForItem(KileProjectItem *item, ConfigScope scope) const { - KConfig* cfgObject = (scope == GUIFile ? m_guiConfig : m_config); - return cfgObject->group("item:" + item->path()); + KConfig* cfgObject = (scope == GUIFile ? m_guiConfig : m_config); + return cfgObject->group("item:" + item->path()); } KConfigGroup KileProject::configGroupForItemDocumentSettings(KileProjectItem *item) const { - return m_guiConfig->group("document-settings,item:" + item->path()); + return m_guiConfig->group("document-settings,item:" + item->path()); } KConfigGroup KileProject::configGroupForItemViewSettings(KileProjectItem *item, int viewIndex) const { - return m_guiConfig->group("view-settings,view=" + QString::number(viewIndex) + ",item:" + item->path()); + return m_guiConfig->group("view-settings,view=" + QString::number(viewIndex) + ",item:" + item->path()); } void KileProject::removeConfigGroupsForItem(KileProjectItem *item) { - QString itemString = "item:" + item->path(); - const QStringList groupList = m_config->groupList(); - for(auto groupName : groupList) { - if(!m_config->hasGroup(groupName)) { // 'groupName' might have been deleted - continue; // work around bug 384039 - } - if(groupName.indexOf(itemString) >= 0) { - m_config->deleteGroup(groupName); - } - } + QString itemString = "item:" + item->path(); + const QStringList groupList = m_config->groupList(); + for(auto groupName : groupList) { + if(!m_config->hasGroup(groupName)) { // 'groupName' might have been deleted + continue; // work around bug 384039 + } + if(groupName.indexOf(itemString) >= 0) { + m_config->deleteGroup(groupName); + } + } } static bool isAncestorOf(KileProjectItem *toBeChecked, KileProjectItem *parent) { - KileProjectItem *item = parent; - while(item != Q_NULLPTR) { - if(item == toBeChecked) { - return true; - } - item = item->parent(); - } - return false; + KileProjectItem *item = parent; + while(item != Q_NULLPTR) { + if(item == toBeChecked) { + return true; + } + item = item->parent(); + } + return false; } void KileProject::buildProjectTree() { - KILE_DEBUG_MAIN << "==KileProject::buildProjectTree=========================="; - - //determine the parent doc for each item (TODO:an item can only have one parent, not necessarily true for LaTeX docs) - - QStringList deps; - QString dep; - KileProjectItem *itm; - QUrl url; - - //clean first - for(QList::iterator it = m_projectItems.begin(); it != m_projectItems.end(); ++it) { - (*it)->setParent(0); - } - - //use the dependencies list of the documentinfo object to determine the parent - for(QList::iterator it = m_projectItems.begin(); it != m_projectItems.end(); ++it) { - //set the type correctly (changing m_extensions causes a call to buildProjectTree) - setType(*it); - KileDocument::Info *docinfo = (*it)->getInfo(); - - if(docinfo) { - QUrl parentUrl = docinfo->url(); - if(parentUrl.isLocalFile()) { - // strip the file name from 'parentUrl' - parentUrl = QUrl::fromUserInput(QFileInfo(parentUrl.path()).path()); - } - else { - parentUrl = m_baseurl; - } - deps = docinfo->dependencies(); - for(int i = 0; i < deps.count(); ++i) { - dep = deps[i]; - - if(m_extmanager->isTexFile(dep)) { - url = QUrl::fromLocalFile(KileInfo::checkOtherPaths(parentUrl, dep, KileInfo::texinputs)); - } - else if(m_extmanager->isBibFile(dep)) { - url = QUrl::fromLocalFile(KileInfo::checkOtherPaths(parentUrl, dep, KileInfo::bibinputs)); - } - itm = item(url); - if(itm && (itm->parent() == 0) - && !isAncestorOf(itm, *it)) { // avoid circular references if a file should - // include itself in a circular way - itm->setParent(*it); - } - } - } - } - - //make a list of all the root items (items with parent == 0) - m_rootItems.clear(); - for(QList::iterator it = m_projectItems.begin(); it != m_projectItems.end(); ++it) { - if((*it)->parent() == Q_NULLPTR) { - m_rootItems.append(*it); - } - } - - emit(projectTreeChanged(this)); + KILE_DEBUG_MAIN << "==KileProject::buildProjectTree=========================="; + + //determine the parent doc for each item (TODO:an item can only have one parent, not necessarily true for LaTeX docs) + + QStringList deps; + QString dep; + KileProjectItem *itm; + QUrl url; + + //clean first + for(QList::iterator it = m_projectItems.begin(); it != m_projectItems.end(); ++it) { + (*it)->setParent(0); + } + + //use the dependencies list of the documentinfo object to determine the parent + for(QList::iterator it = m_projectItems.begin(); it != m_projectItems.end(); ++it) { + //set the type correctly (changing m_extensions causes a call to buildProjectTree) + setType(*it); + KileDocument::Info *docinfo = (*it)->getInfo(); + + if(docinfo) { + QUrl parentUrl = docinfo->url(); + if(parentUrl.isLocalFile()) { + // strip the file name from 'parentUrl' + parentUrl = QUrl::fromUserInput(QFileInfo(parentUrl.path()).path()); + } + else { + parentUrl = m_baseurl; + } + deps = docinfo->dependencies(); + for(int i = 0; i < deps.count(); ++i) { + dep = deps[i]; + + if(m_extmanager->isTexFile(dep)) { + url = QUrl::fromLocalFile(KileInfo::checkOtherPaths(parentUrl, dep, KileInfo::texinputs)); + } + else if(m_extmanager->isBibFile(dep)) { + url = QUrl::fromLocalFile(KileInfo::checkOtherPaths(parentUrl, dep, KileInfo::bibinputs)); + } + itm = item(url); + if(itm && (itm->parent() == 0) + && !isAncestorOf(itm, *it)) { // avoid circular references if a file should + // include itself in a circular way + itm->setParent(*it); + } + } + } + } + + //make a list of all the root items (items with parent == 0) + m_rootItems.clear(); + for(QList::iterator it = m_projectItems.begin(); it != m_projectItems.end(); ++it) { + if((*it)->parent() == Q_NULLPTR) { + m_rootItems.append(*it); + } + } + + emit(projectTreeChanged(this)); } KileProjectItem* KileProject::item(const QUrl &url) { - for(QList::iterator it = m_projectItems.begin(); it != m_projectItems.end(); ++it) { - if((*it)->url() == url) { - return *it; - } - } + for(QList::iterator it = m_projectItems.begin(); it != m_projectItems.end(); ++it) { + if((*it)->url() == url) { + return *it; + } + } - return Q_NULLPTR; + return Q_NULLPTR; } KileProjectItem* KileProject::item(const KileDocument::Info *info) { - for(QList::iterator it = m_projectItems.begin(); it != m_projectItems.end(); ++it) { - KileProjectItem *current = *it; + for(QList::iterator it = m_projectItems.begin(); it != m_projectItems.end(); ++it) { + KileProjectItem *current = *it; - if (current->getInfo() == info) { - return current; - } - } + if (current->getInfo() == info) { + return current; + } + } - return Q_NULLPTR; + return Q_NULLPTR; } void KileProject::add(KileProjectItem* item) { - KILE_DEBUG_MAIN << "KileProject::add projectitem" << item->url().toLocalFile(); + KILE_DEBUG_MAIN << "KileProject::add projectitem" << item->url().toLocalFile(); - setType(item); + setType(item); - item->changePath(findRelativePath(item->url())); - connect(item, SIGNAL(urlChanged(KileProjectItem*)), this, SLOT(itemRenamed(KileProjectItem*)) ); + item->changePath(findRelativePath(item->url())); + connect(item, SIGNAL(urlChanged(KileProjectItem*)), this, SLOT(itemRenamed(KileProjectItem*)) ); - m_projectItems.append(item); + m_projectItems.append(item); - emit projectItemAdded(this, item); + emit projectItemAdded(this, item); - // dump(); + // dump(); } void KileProject::remove(KileProjectItem* item) { - KILE_DEBUG_MAIN << item->path(); - removeConfigGroupsForItem(item); - m_projectItems.removeAll(item); + KILE_DEBUG_MAIN << item->path(); + removeConfigGroupsForItem(item); + m_projectItems.removeAll(item); - emit projectItemRemoved(this, item); + emit projectItemRemoved(this, item); - // dump(); + // dump(); } void KileProject::itemRenamed(KileProjectItem *item) { - KILE_DEBUG_MAIN << "==KileProject::itemRenamed=========================="; - KILE_DEBUG_MAIN << "\t" << item->url().fileName(); - removeConfigGroupsForItem(item); + KILE_DEBUG_MAIN << "==KileProject::itemRenamed=========================="; + KILE_DEBUG_MAIN << "\t" << item->url().fileName(); + removeConfigGroupsForItem(item); - item->changePath(findRelativePath(item->url())); + item->changePath(findRelativePath(item->url())); } QString KileProject::findRelativePath(const QString &path) { - return this->findRelativePath(QUrl::fromLocalFile(path)); + return this->findRelativePath(QUrl::fromLocalFile(path)); } QString KileProject::findRelativePath(const QUrl &url) { - KILE_DEBUG_MAIN << "QString KileProject::findRelativePath(const QUrl " << url.path() << ")"; + KILE_DEBUG_MAIN << "QString KileProject::findRelativePath(const QUrl " << url.path() << ")"; - if ( m_baseurl.toLocalFile() == url.toLocalFile() ) { - return "./"; - } - const QString path = QDir(m_baseurl.path()).relativeFilePath(url.path()); - KILE_DEBUG_MAIN << "relPath is " << path; - return path; + if ( m_baseurl.toLocalFile() == url.toLocalFile() ) { + return "./"; + } + const QString path = QDir(m_baseurl.path()).relativeFilePath(url.path()); + KILE_DEBUG_MAIN << "relPath is " << path; + return path; } bool KileProject::contains(const QUrl &url) { - for(QList::iterator it = m_projectItems.begin(); it != m_projectItems.end(); ++it) { - if((*it)->url() == url) { - return true; - } - } + for(QList::iterator it = m_projectItems.begin(); it != m_projectItems.end(); ++it) { + if((*it)->url() == url) { + return true; + } + } - return false; + return false; } bool KileProject::contains(const KileDocument::Info *info) { - for(QList::iterator it = m_projectItems.begin(); it != m_projectItems.end(); ++it) { - if((*it)->getInfo() == info) { - return true; - } - } - return false; + for(QList::iterator it = m_projectItems.begin(); it != m_projectItems.end(); ++it) { + if((*it)->getInfo() == info) { + return true; + } + } + return false; } KileProjectItem *KileProject::rootItem(KileProjectItem *item) const { - //find the root item (i.e. the eldest parent) - KileProjectItem *root = item; - while(root->parent() != Q_NULLPTR) { - root = root->parent(); - } - - //check if this root item is a LaTeX root - if(root->getInfo()) { - if (root->getInfo()->isLaTeXRoot()) { - return root; - } - else { - //if not, see if we can find another root item that is a LaTeX root - for(QList::const_iterator it = m_rootItems.begin(); it != m_rootItems.end(); ++it) { - KileProjectItem *current = *it; - if(current->getInfo() && current->getInfo()->isLaTeXRoot()) { - return current; - } - } - } - - //no LaTeX root found, return previously found root - return root; - } - - //root is not a valid item (getInfo() return 0L), return original item - return item; + //find the root item (i.e. the eldest parent) + KileProjectItem *root = item; + while(root->parent() != Q_NULLPTR) { + root = root->parent(); + } + + //check if this root item is a LaTeX root + if(root->getInfo()) { + if (root->getInfo()->isLaTeXRoot()) { + return root; + } + else { + //if not, see if we can find another root item that is a LaTeX root + for(QList::const_iterator it = m_rootItems.begin(); it != m_rootItems.end(); ++it) { + KileProjectItem *current = *it; + if(current->getInfo() && current->getInfo()->isLaTeXRoot()) { + return current; + } + } + } + + //no LaTeX root found, return previously found root + return root; + } + + //root is not a valid item (getInfo() return 0L), return original item + return item; } void KileProject::dump() { - KILE_DEBUG_MAIN << "KileProject::dump() " << m_name; - for(QList::iterator it = m_projectItems.begin(); it != m_projectItems.end(); ++it) { - KileProjectItem *item = *it; - KILE_DEBUG_MAIN << "item " << item << " has path: " << item->path(); - KILE_DEBUG_MAIN << "item->type() " << item->type(); - KILE_DEBUG_MAIN << "OpenState: " << item->isOpen(); - } + KILE_DEBUG_MAIN << "KileProject::dump() " << m_name; + for(QList::iterator it = m_projectItems.begin(); it != m_projectItems.end(); ++it) { + KileProjectItem *item = *it; + KILE_DEBUG_MAIN << "item " << item << " has path: " << item->path(); + KILE_DEBUG_MAIN << "item->type() " << item->type(); + KILE_DEBUG_MAIN << "OpenState: " << item->isOpen(); + } } QString KileProject::archiveFileList() const { - KILE_DEBUG_MAIN << "KileProject::archiveFileList()"; + KILE_DEBUG_MAIN << "KileProject::archiveFileList()"; - QString path, list; - for(QList::const_iterator it = m_projectItems.begin(); it != m_projectItems.end(); ++it) { - if ((*it)->archive()) { - list.append(KShell::quoteArg((*it)->path()) + ' '); - } - } - return list; + QString path, list; + for(QList::const_iterator it = m_projectItems.begin(); it != m_projectItems.end(); ++it) { + if ((*it)->archive()) { + list.append(KShell::quoteArg((*it)->path()) + ' '); + } + } + return list; } -void KileProject::setMasterDocument(const QString & master){ +void KileProject::setMasterDocument(const QString & master) { - if(!master.isEmpty()){ + if(!master.isEmpty()) { - QFileInfo fi(master); - if(fi.exists()) - m_masterDocument = master; - else { - m_masterDocument.clear(); - KILE_DEBUG_MAIN << "setMasterDocument: masterDoc=Q_NULLPTR"; - } + QFileInfo fi(master); + if(fi.exists()) + m_masterDocument = master; + else { + m_masterDocument.clear(); + KILE_DEBUG_MAIN << "setMasterDocument: masterDoc=Q_NULLPTR"; + } - } - else { - m_masterDocument.clear(); - } + } + else { + m_masterDocument.clear(); + } - emit (masterDocumentChanged(m_masterDocument)); + emit (masterDocumentChanged(m_masterDocument)); } namespace { - void moveConfigGroupKeysAsStrings(KConfig *src, KConfig *dst, const QString& groupName, const QStringList &keysToMove) - { - KConfigGroup srcGroup(src, groupName); - KConfigGroup dstGroup(dst, groupName); +void moveConfigGroupKeysAsStrings(KConfig *src, KConfig *dst, const QString& groupName, const QStringList &keysToMove) +{ + KConfigGroup srcGroup(src, groupName); + KConfigGroup dstGroup(dst, groupName); - for(const QString& key : keysToMove) { - if(srcGroup.hasKey(key)) { - QString value = srcGroup.readEntry(key, QStringLiteral("")); - dstGroup.writeEntry(key, value); - srcGroup.deleteEntry(key); - } - } - } + for(const QString& key : keysToMove) { + if(srcGroup.hasKey(key)) { + QString value = srcGroup.readEntry(key, QStringLiteral("")); + dstGroup.writeEntry(key, value); + srcGroup.deleteEntry(key); + } + } +} - void deleteConfigGroupKeys(KConfig *src, const QString& groupName, const QStringList &keysToDelete) - { - KConfigGroup srcGroup(src, groupName); +void deleteConfigGroupKeys(KConfig *src, const QString& groupName, const QStringList &keysToDelete) +{ + KConfigGroup srcGroup(src, groupName); - for(const QString& key : keysToDelete) { - srcGroup.deleteEntry(key); - } - } + for(const QString& key : keysToDelete) { + srcGroup.deleteEntry(key); + } +} } bool KileProject::migrateProjectFileToCurrentVersion() { if(getProjectFileVersion() < KILE_PROJECTFILE_VERSION) { - return migrateProjectFileToVersion3(); + return migrateProjectFileToVersion3(); } return true; } bool KileProject::migrateProjectFileToVersion3() { - KILE_DEBUG_MAIN << "Migrating project file" << m_projecturl << "to version 3"; - - // (1) Every config group starting with "document-settings," or "view-settings," will be moved to the GUI config file - // (2) In every group named "item:..." the keys "column" and "line" are deleted - // (3) In every group named "item:..." the keys "open" and "order" are moved to a new group of the same name - // in the GUI project file - // (4) In the "General" group the keys "lastDocument", "kile_livePreviewEnabled", "kile_livePreviewStatusUserSpecified", - // "kile_livePreviewTool" are moved to the "General" group in the GUI project file - - if(!ensurePrivateKileDirectoryExists(m_projecturl)) { - return false; - } - - KConfig projectGUIFile(getPathForGUISettingsProjectFile(m_projecturl), KConfig::SimpleConfig); - - QStringList keysToMoveInItemGroups, keysToDeleteInItemGroups, keysToMoveInGeneralGroup; - - keysToMoveInItemGroups - << QStringLiteral("column") - << QStringLiteral("line") - << QStringLiteral("open") - << QStringLiteral("order"); - - keysToDeleteInItemGroups - << QStringLiteral("column") - << QStringLiteral("line"); - - keysToMoveInGeneralGroup - << QStringLiteral("lastDocument") - << QStringLiteral("kile_livePreviewEnabled") - << QStringLiteral("kile_livePreviewStatusUserSpecified") - << QStringLiteral("kile_livePreviewTool"); - - const QStringList groups = m_config->groupList(); - for(auto groupName : groups) { - if(!m_config->hasGroup(groupName)) { // 'groupName' might have been deleted - continue; // work around bug 384039 - } - - // these ones we move completely - if(groupName.startsWith(QLatin1String("document-settings,")) || groupName.startsWith(QLatin1String("view-settings,"))) { - KConfigGroup oldGroup(m_config, groupName); - KConfigGroup guiGroup(&projectGUIFile, groupName); - oldGroup.copyTo(&guiGroup); - m_config->deleteGroup(groupName); - continue; - } - - if(groupName.startsWith(QLatin1String("item:"))) { - deleteConfigGroupKeys(m_config, groupName, keysToDeleteInItemGroups); - moveConfigGroupKeysAsStrings(m_config, &projectGUIFile, groupName, keysToMoveInItemGroups); - } - else if(groupName == QLatin1String("General")) { - moveConfigGroupKeysAsStrings(m_config, &projectGUIFile, groupName, keysToMoveInGeneralGroup); - } - } - - if(!projectGUIFile.sync()) { - return false; - } - - KConfigGroup configGroup = m_config->group("General"); - configGroup.writeEntry("kileprversion", KILE_PROJECTFILE_VERSION); - configGroup.writeEntry("kileversion", kileFullVersion); - - return m_config->sync(); + KILE_DEBUG_MAIN << "Migrating project file" << m_projecturl << "to version 3"; + + // (1) Every config group starting with "document-settings," or "view-settings," will be moved to the GUI config file + // (2) In every group named "item:..." the keys "column" and "line" are deleted + // (3) In every group named "item:..." the keys "open" and "order" are moved to a new group of the same name + // in the GUI project file + // (4) In the "General" group the keys "lastDocument", "kile_livePreviewEnabled", "kile_livePreviewStatusUserSpecified", + // "kile_livePreviewTool" are moved to the "General" group in the GUI project file + + if(!ensurePrivateKileDirectoryExists(m_projecturl)) { + return false; + } + + KConfig projectGUIFile(getPathForGUISettingsProjectFile(m_projecturl), KConfig::SimpleConfig); + + QStringList keysToMoveInItemGroups, keysToDeleteInItemGroups, keysToMoveInGeneralGroup; + + keysToMoveInItemGroups + << QStringLiteral("column") + << QStringLiteral("line") + << QStringLiteral("open") + << QStringLiteral("order"); + + keysToDeleteInItemGroups + << QStringLiteral("column") + << QStringLiteral("line"); + + keysToMoveInGeneralGroup + << QStringLiteral("lastDocument") + << QStringLiteral("kile_livePreviewEnabled") + << QStringLiteral("kile_livePreviewStatusUserSpecified") + << QStringLiteral("kile_livePreviewTool"); + + const QStringList groups = m_config->groupList(); + for(auto groupName : groups) { + if(!m_config->hasGroup(groupName)) { // 'groupName' might have been deleted + continue; // work around bug 384039 + } + + // these ones we move completely + if(groupName.startsWith(QLatin1String("document-settings,")) || groupName.startsWith(QLatin1String("view-settings,"))) { + KConfigGroup oldGroup(m_config, groupName); + KConfigGroup guiGroup(&projectGUIFile, groupName); + oldGroup.copyTo(&guiGroup); + m_config->deleteGroup(groupName); + continue; + } + + if(groupName.startsWith(QLatin1String("item:"))) { + deleteConfigGroupKeys(m_config, groupName, keysToDeleteInItemGroups); + moveConfigGroupKeysAsStrings(m_config, &projectGUIFile, groupName, keysToMoveInItemGroups); + } + else if(groupName == QLatin1String("General")) { + moveConfigGroupKeysAsStrings(m_config, &projectGUIFile, groupName, keysToMoveInGeneralGroup); + } + } + + if(!projectGUIFile.sync()) { + return false; + } + + KConfigGroup configGroup = m_config->group("General"); + configGroup.writeEntry("kileprversion", KILE_PROJECTFILE_VERSION); + configGroup.writeEntry("kileversion", kileFullVersion); + + return m_config->sync(); } diff --git a/src/kileproject.h b/src/kileproject.h index 76d11ba9..6c1b57fc 100644 --- a/src/kileproject.h +++ b/src/kileproject.h @@ -1,311 +1,404 @@ /*************************************************************************************** begin : Fri Aug 1 2003 copyright : (C) 2003 by Jeroen Wijnhout (Jeroen.Wijnhout@kdemail.net) (C) 2009-2016 by Michel Ludwig (michel.ludwig@kdemail.net) ***************************************************************************************/ /*************************************************************************** * * * 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. * * * ***************************************************************************/ #ifndef KILEPROJECT_H #define KILEPROJECT_H #include #include #include #include #include #include #include #include #include "kiledebug.h" #include "kileversion.h" #include "livepreview_utils.h" #include "outputinfo.h" class QString; class QStringList; -namespace KileDocument { class Info; class TextInfo; class Extensions; } +namespace KileDocument { +class Info; +class TextInfo; +class Extensions; +} /** * KileProjectItem **/ class KileProject; class KileProjectItem : public QObject { - Q_OBJECT + Q_OBJECT public: - explicit KileProjectItem(KileProject *project = 0, const QUrl &url = QUrl(), int type = Source); - ~KileProjectItem() { KILE_DEBUG_MAIN << "DELETING PROJITEM " << m_path << endl;} - - bool operator==(const KileProjectItem& item) { return m_url == item.url();} - - enum Type { ProjectFile = 0, Source, Package, Image, Bibliography, Other /* should be the last item*/ }; - - int type() const { return m_type; } - void setType(int type) { m_type = type; } - - bool archive() const { return m_archive; } - void setArchive(bool ar) { m_archive = ar; } - - void setInfo(KileDocument::TextInfo * docinfo); - KileDocument::TextInfo* getInfo() const { return m_docinfo; } - - KileProject* project() const { return m_project;} - - /** - * @returns absolute URL of this item - **/ - const QUrl &url() const { return m_url; } - - /** - * @returns path of this item relative to the project file - **/ - const QString& path() const { return m_path; } - - bool isOpen() const { return m_bOpen; } - void setOpenState(bool state) { m_bOpen = state; } - - const QString& encoding() const { return m_encoding;} - void setEncoding(const QString& encoding) {m_encoding = encoding;} - - const QString& highlight() { return m_highlight;} - void setHighlight(const QString& highlight) {m_highlight = highlight;} - - const QString& mode() { return m_mode;} - void setMode(const QString& mode) {m_mode = mode;} - - int order() const { return m_order; } - void setOrder(int i); - - //project tree functions - void setParent(KileProjectItem * item); - - void load(); - void save(); - - void loadDocumentAndViewSettings(); - void saveDocumentAndViewSettings(); + explicit KileProjectItem(KileProject *project = 0, const QUrl &url = QUrl(), int type = Source); + ~KileProjectItem() { + KILE_DEBUG_MAIN << "DELETING PROJITEM " << m_path << endl; + } + + bool operator==(const KileProjectItem& item) { + return m_url == item.url(); + } + + enum Type { ProjectFile = 0, Source, Package, Image, Bibliography, Other /* should be the last item*/ }; + + int type() const { + return m_type; + } + void setType(int type) { + m_type = type; + } + + bool archive() const { + return m_archive; + } + void setArchive(bool ar) { + m_archive = ar; + } + + void setInfo(KileDocument::TextInfo * docinfo); + KileDocument::TextInfo* getInfo() const { + return m_docinfo; + } + + KileProject* project() const { + return m_project; + } + + /** + * @returns absolute URL of this item + **/ + const QUrl &url() const { + return m_url; + } + + /** + * @returns path of this item relative to the project file + **/ + const QString& path() const { + return m_path; + } + + bool isOpen() const { + return m_bOpen; + } + void setOpenState(bool state) { + m_bOpen = state; + } + + const QString& encoding() const { + return m_encoding; + } + void setEncoding(const QString& encoding) { + m_encoding = encoding; + } + + const QString& highlight() { + return m_highlight; + } + void setHighlight(const QString& highlight) { + m_highlight = highlight; + } + + const QString& mode() { + return m_mode; + } + void setMode(const QString& mode) { + m_mode = mode; + } + + int order() const { + return m_order; + } + void setOrder(int i); + + //project tree functions + void setParent(KileProjectItem * item); + + void load(); + void save(); + + void loadDocumentAndViewSettings(); + void saveDocumentAndViewSettings(); protected: - void setChild(KileProjectItem *item) { m_child = item; } - void setSibling(KileProjectItem *item) { m_sibling = item; } + void setChild(KileProjectItem *item) { + m_child = item; + } + void setSibling(KileProjectItem *item) { + m_sibling = item; + } - void loadViewSettings(KTextEditor::View *view, int viewIndex); - void saveViewSettings(KTextEditor::View *view, int viewIndex); + void loadViewSettings(KTextEditor::View *view, int viewIndex); + void saveViewSettings(KTextEditor::View *view, int viewIndex); - void loadDocumentSettings(KTextEditor::Document *document); - void saveDocumentSettings(KTextEditor::Document *document); + void loadDocumentSettings(KTextEditor::Document *document); + void saveDocumentSettings(KTextEditor::Document *document); public: - KileProjectItem* parent() const { return m_parent; } - KileProjectItem* firstChild() const { return m_child;} - KileProjectItem* sibling() const { return m_sibling; } + KileProjectItem* parent() const { + return m_parent; + } + KileProjectItem* firstChild() const { + return m_child; + } + KileProjectItem* sibling() const { + return m_sibling; + } - void allChildren(QList* list) const; + void allChildren(QList* list) const; - void print(int level); + void print(int level); public Q_SLOTS: - /** - * @warning Does nothing if "url" is empty ! - **/ - void changeURL(const QUrl &url); - void changePath(const QString& path) { m_path = path;} + /** + * @warning Does nothing if "url" is empty ! + **/ + void changeURL(const QUrl &url); + void changePath(const QString& path) { + m_path = path; + } private Q_SLOTS: - void slotChangeURL(KileDocument::Info* info, const QUrl &url); + void slotChangeURL(KileDocument::Info* info, const QUrl &url); Q_SIGNALS: - void urlChanged(KileProjectItem*); + void urlChanged(KileProjectItem*); private: - KileProject *m_project; - QUrl m_url; - QString m_path; - QString m_encoding; - QString m_mode; - QString m_highlight; - bool m_bOpen, m_archive; - int m_type; - KileDocument::TextInfo *m_docinfo; - KileProjectItem *m_parent, *m_child, *m_sibling; - int m_order; + KileProject *m_project; + QUrl m_url; + QString m_path; + QString m_encoding; + QString m_mode; + QString m_highlight; + bool m_bOpen, m_archive; + int m_type; + KileDocument::TextInfo *m_docinfo; + KileProjectItem *m_parent, *m_child, *m_sibling; + int m_order; }; /** * KileProject **/ class KileProject : public QObject, public KileTool::LivePreviewUserStatusHandler, public LaTeXOutputHandler { - Q_OBJECT - friend class KileProjectItem; + Q_OBJECT + friend class KileProjectItem; public: - KileProject(const QString& name, const QUrl &url, KileDocument::Extensions *extensions); - KileProject(const QUrl &url, KileDocument::Extensions *extensions); - - ~KileProject(); - - void setName(const QString & name) { m_name = name; emit (nameChanged(name));} - const QString& name() const { return m_name; } - - void setMasterDocument(const QString & master); - const QString& masterDocument() const { return m_masterDocument; } - - void setExtensions(KileProjectItem::Type type, const QString & ext); - const QString & extensions(KileProjectItem::Type type) { return m_extensions[type-1]; } - - void setDefaultGraphicExt(const QString & ext); - const QString & defaultGraphicExt(); - - void setQuickBuildConfig(const QString & cfg) { m_quickBuildConfig = cfg; } - const QString & quickBuildConfig() { return m_quickBuildConfig; } - - void setLastDocument(const QUrl &url); - const QUrl &lastDocument() const { return m_lastDocument; } - - void setMakeIndexOptions(const QString & opt) { m_makeIndexOptions = opt; } - const QString & makeIndexOptions() { return m_makeIndexOptions; } - void readMakeIndexOptions(); - void setUseMakeIndexOptions(bool use) { m_useMakeIndexOptions = use; } - void writeUseMakeIndexOptions(); - bool useMakeIndexOptions() { return m_useMakeIndexOptions; } - - QUrl url() const { return m_projecturl; } - void setURL(const QUrl &url ) { m_projecturl = url; } - QUrl baseURL() const { return m_baseurl; } - - KileProjectItem* item(const QUrl &); - KileProjectItem* item(const KileDocument::Info *info); - QList items() { return m_projectItems; } - - KConfig *config() { return m_config; } - KConfig *guiConfig() { return m_guiConfig; } - - bool contains(const QUrl&); - bool contains(const KileDocument::Info *info); - KileProjectItem *rootItem(KileProjectItem *) const; - const QList& rootItems() const {return m_rootItems;} - bool isInvalid(){ return m_invalid;} - QString archiveFileList() const; - - bool appearsToBeValidProjectFile(); - - inline bool isOfCurrentVersion() - { - return (getProjectFileVersion() == KILE_PROJECTFILE_VERSION); - } - - int getProjectFileVersion(); - - bool migrateProjectFileToCurrentVersion(); - - static inline QString getPathForGUISettingsProjectFile(const QString& projectFilePath) - { - QFileInfo fi(projectFilePath); - - return getPathForPrivateKileDirectory(fi) + QStringLiteral("/") + fi.fileName() + QStringLiteral(".gui"); - } - - static inline QString getPathForGUISettingsProjectFile(const QUrl& projectUrl) - { - return getPathForGUISettingsProjectFile(projectUrl.toLocalFile()); - } - - static inline QString getPathForPrivateKileDirectory(const QUrl& projectUrl) - { - return getPathForPrivateKileDirectory(projectUrl.toLocalFile()); - } - - static inline QString getPathForPrivateKileDirectory(const QFileInfo& projectFilePath) - { - return projectFilePath.dir().absoluteFilePath(".kile"); - } - - static inline QString getPathForPrivateKileDirectory(const QString& projectFilePath) - { - return getPathForPrivateKileDirectory(QFileInfo(projectFilePath)); - } - - static inline bool ensurePrivateKileDirectoryExists(const QUrl& projectUrl) - { - return QFileInfo(projectUrl.toLocalFile()).dir().mkpath(".kile"); - } + KileProject(const QString& name, const QUrl &url, KileDocument::Extensions *extensions); + KileProject(const QUrl &url, KileDocument::Extensions *extensions); + + ~KileProject(); + + void setName(const QString & name) { + m_name = name; + emit (nameChanged(name)); + } + const QString& name() const { + return m_name; + } + + void setMasterDocument(const QString & master); + const QString& masterDocument() const { + return m_masterDocument; + } + + void setExtensions(KileProjectItem::Type type, const QString & ext); + const QString & extensions(KileProjectItem::Type type) { + return m_extensions[type-1]; + } + + void setDefaultGraphicExt(const QString & ext); + const QString & defaultGraphicExt(); + + void setQuickBuildConfig(const QString & cfg) { + m_quickBuildConfig = cfg; + } + const QString & quickBuildConfig() { + return m_quickBuildConfig; + } + + void setLastDocument(const QUrl &url); + const QUrl &lastDocument() const { + return m_lastDocument; + } + + void setMakeIndexOptions(const QString & opt) { + m_makeIndexOptions = opt; + } + const QString & makeIndexOptions() { + return m_makeIndexOptions; + } + void readMakeIndexOptions(); + void setUseMakeIndexOptions(bool use) { + m_useMakeIndexOptions = use; + } + void writeUseMakeIndexOptions(); + bool useMakeIndexOptions() { + return m_useMakeIndexOptions; + } + + QUrl url() const { + return m_projecturl; + } + void setURL(const QUrl &url ) { + m_projecturl = url; + } + QUrl baseURL() const { + return m_baseurl; + } + + KileProjectItem* item(const QUrl &); + KileProjectItem* item(const KileDocument::Info *info); + QList items() { + return m_projectItems; + } + + KConfig *config() { + return m_config; + } + KConfig *guiConfig() { + return m_guiConfig; + } + + bool contains(const QUrl&); + bool contains(const KileDocument::Info *info); + KileProjectItem *rootItem(KileProjectItem *) const; + const QList& rootItems() const { + return m_rootItems; + } + bool isInvalid() { + return m_invalid; + } + QString archiveFileList() const; + + bool appearsToBeValidProjectFile(); + + inline bool isOfCurrentVersion() + { + return (getProjectFileVersion() == KILE_PROJECTFILE_VERSION); + } + + int getProjectFileVersion(); + + bool migrateProjectFileToCurrentVersion(); + + static inline QString getPathForGUISettingsProjectFile(const QString& projectFilePath) + { + QFileInfo fi(projectFilePath); + + return getPathForPrivateKileDirectory(fi) + QStringLiteral("/") + fi.fileName() + QStringLiteral(".gui"); + } + + static inline QString getPathForGUISettingsProjectFile(const QUrl& projectUrl) + { + return getPathForGUISettingsProjectFile(projectUrl.toLocalFile()); + } + + static inline QString getPathForPrivateKileDirectory(const QUrl& projectUrl) + { + return getPathForPrivateKileDirectory(projectUrl.toLocalFile()); + } + + static inline QString getPathForPrivateKileDirectory(const QFileInfo& projectFilePath) + { + return projectFilePath.dir().absoluteFilePath(".kile"); + } + + static inline QString getPathForPrivateKileDirectory(const QString& projectFilePath) + { + return getPathForPrivateKileDirectory(QFileInfo(projectFilePath)); + } + + static inline bool ensurePrivateKileDirectoryExists(const QUrl& projectUrl) + { + return QFileInfo(projectUrl.toLocalFile()).dir().mkpath(".kile"); + } Q_SIGNALS: - void nameChanged(const QString &); - void masterDocumentChanged(const QString &); - void projectTreeChanged(const KileProject *); - void projectItemAdded(KileProject *project, KileProjectItem *item); - void projectItemRemoved(KileProject *project, KileProjectItem *item); - void aboutToBeDestroyed(KileProject*); + void nameChanged(const QString &); + void masterDocumentChanged(const QString &); + void projectTreeChanged(const KileProject *); + void projectItemAdded(KileProject *project, KileProjectItem *item); + void projectItemRemoved(KileProject *project, KileProjectItem *item); + void aboutToBeDestroyed(KileProject*); public Q_SLOTS: - bool load(); - bool save(); + bool load(); + bool save(); - void add(KileProjectItem*); - void remove(KileProjectItem*); + void add(KileProjectItem*); + void remove(KileProjectItem*); - void itemRenamed(KileProjectItem*); + void itemRenamed(KileProjectItem*); - void buildProjectTree(); // moved to slots by tbraun + void buildProjectTree(); // moved to slots by tbraun - //debugging - void dump(); + //debugging + void dump(); Q_SIGNALS: - void loadFile(const QUrl &url , const QString & encoding); + void loadFile(const QUrl &url, const QString & encoding); private: - bool migrateProjectFileToVersion3(); + bool migrateProjectFileToVersion3(); - void init(const QUrl &url); - QString findRelativePath(const QUrl&); - QString findRelativePath(const QString&); + void init(const QUrl &url); + QString findRelativePath(const QUrl&); + QString findRelativePath(const QString&); - void setType(KileProjectItem *item); - QString addBaseURL(const QString &path); - QString removeBaseURL(const QString &path); - void writeConfigEntry(const QString &key,const QString &standardExt,KileProjectItem::Type type); + void setType(KileProjectItem *item); + QString addBaseURL(const QString &path); + QString removeBaseURL(const QString &path); + void writeConfigEntry(const QString &key,const QString &standardExt,KileProjectItem::Type type); - enum ConfigScope { - ProjectFile, - GUIFile - }; + enum ConfigScope { + ProjectFile, + GUIFile + }; - KConfigGroup configGroupForItem(KileProjectItem *item, ConfigScope scope) const; - KConfigGroup configGroupForItemDocumentSettings(KileProjectItem *item) const; - KConfigGroup configGroupForItemViewSettings(KileProjectItem *item, int viewIndex) const; + KConfigGroup configGroupForItem(KileProjectItem *item, ConfigScope scope) const; + KConfigGroup configGroupForItemDocumentSettings(KileProjectItem *item) const; + KConfigGroup configGroupForItemViewSettings(KileProjectItem *item, int viewIndex) const; - void removeConfigGroupsForItem(KileProjectItem *item); + void removeConfigGroupsForItem(KileProjectItem *item); private: - QString m_name, m_quickBuildConfig, m_defGraphicExt; - QUrl m_projecturl, m_baseurl, m_lastDocument; - bool m_invalid; - QList m_rootItems; - QList m_projectItems; + QString m_name, m_quickBuildConfig, m_defGraphicExt; + QUrl m_projecturl, m_baseurl, m_lastDocument; + bool m_invalid; + QList m_rootItems; + QList m_projectItems; - QString m_extensions[4]; - QRegExp m_reExtensions[4]; + QString m_extensions[4]; + QRegExp m_reExtensions[4]; - QString m_masterDocument, m_makeIndexOptions; - bool m_useMakeIndexOptions; + QString m_masterDocument, m_makeIndexOptions; + bool m_useMakeIndexOptions; - KConfig *m_config; // stores project structure - KConfig *m_guiConfig; // stores project GUI settings: last document, items view settings, etc. - KileDocument::Extensions *m_extmanager; + KConfig *m_config; // stores project structure + KConfig *m_guiConfig; // stores project GUI settings: last document, items view settings, etc. + KileDocument::Extensions *m_extmanager; }; #endif diff --git a/src/kilestdactions.cpp b/src/kilestdactions.cpp index f5ea6bd2..e6da6aa4 100644 --- a/src/kilestdactions.cpp +++ b/src/kilestdactions.cpp @@ -1,496 +1,496 @@ /************************************************************************** * Copyright (C) 2003 by Jeroen Wijnhout (Jeroen.Wijnhout@kdemail.net) * ***************************************************************************/ /*************************************************************************** * * * 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. * * * ***************************************************************************/ #include "kilestdactions.h" #include #include #include #include #include #include "kileactions.h" #include "editorextension.h" namespace KileStdActions { void setupStdTags(KileInfo *ki, const QObject* receiver, KActionCollection *actionCollection, QWidget *parentWidget) { - (void) new KileAction::Tag(i18n("Document Class Selection - \\documentclass{}"), i18n("Document Class"), QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection, "tag_documentclass", - "\\documentclass[10pt]{","}", 21, 0, i18n("\\documentclass[options]{class}\nclass : article,report,book,letter\nsize options : 10pt, 11pt, 12pt\npaper size options: a4paper, a5paper, b5paper, letterpaper, legalpaper, executivepaper\n" - "other options: \nlandscape -- selects landscape format; default is portrait. \ntitlepage, notitlepage -- selects if there should be a separate title page.\nleqno -- display equation number on left side of equations; default is right side.\n" - "fleqn -- display formulae flush left; default is centered.\nonecolumn, twocolumn -- one or two columns; defaults to one column\noneside, twoside -- selects one- or two-sided layout.\n" )); - - (void) new KileAction::Tag(i18n("Package Import - \\usepackage{}"), i18n("Package Import"), QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_usepackage", - "\\usepackage{","}", 12, 0, i18n("Any options given in the \\documentclass command that are unknown by the selected document class\n" - "are passed on to the packages loaded with \\usepackage.")); - - (void) new KileAction::Tag(i18n("AMS Packages"), QString(), QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_amspackages","\\usepackage{amsmath}\n\\usepackage{amsfonts}\n\\usepackage{amssymb}\n",QString(),0,3,i18n("The principal American Mathematical Society packages")); - (void) new KileAction::Tag(i18n("Start Document Body - \\begin{document}"), i18n("Start Document Body"), QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_env_document","\\begin{document}\n", "\n\\end{document}", 0,1,i18n("Text is allowed only between \\begin{document} and \\end{document}.\nThe 'preamble' (before \\begin{document} ) may contain declarations only.")); - (void) new KileAction::Tag(i18n("Generate Title - \\maketitle"), i18n("Generate Title"), QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_maketitle","\\maketitle",QString(),10,0,i18n("This command generates a title on a separate title page\n- except in the article class, where the title normally goes at the top of the first page.")); - (void) new KileAction::Tag(i18n("Table of Contents - \\tableofcontents"), i18n("Table of Contents"), "view-table-of-contents-ltr", QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_tableofcontents","\\tableofcontents",QString(),16,0,i18n("Put this command where you want the table of contents to go")); - (void) new KileAction::Tag(i18n("Title Definition - \\title{}"), i18n("Title Definition"), QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_title","\\title{","}",7,0,i18n( "\\title{text}\nThe \\title command declares text to be the title.\nUse \\\\ to tell LaTeX where to start a new line in a long title.")); - (void) new KileAction::Tag(i18n("Author Definition - \\author{}"), i18n("Author Definition"), QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_author","\\author{","}",8,0,i18n( "\\author{names}\nThe \\author command declares the author(s), where names is a list of authors separated by \\and commands.")); - - (void) new KileAction::Tag(i18n("Center - \\begin{center}"), i18n("Center"), "format-justify-center", QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_center", "\\begin{center}\n","%E\n\\end{center}", 0,1, i18n("Each line must be terminated with the string \\\\.")); - (void) new KileAction::Tag(i18n("Align Left - \\begin{flushleft}"), i18n("Align Left"), "format-justify-left", QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_flushleft", "\\begin{flushleft}\n","%E\n\\end{flushleft}", 0,1, i18n("Each line must be terminated with the string \\\\.") ); - (void) new KileAction::Tag(i18n("Align Right - \\begin{flushright}"), i18n("Align Right"), "format-justify-right", QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_flushright", "\\begin{flushright}\n","%E\n\\end{flushright}", 0,1, i18n("Each line must be terminated with the string \\\\.") ); - (void) new KileAction::Tag(i18n("Quote - \\begin{quote}"), i18n("Quote"), QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_quote","\\begin{quote}\n","%E\n\\end{quote} ",0,1,i18n("The text is justified at both margins.\nLeaving a blank line between text produces a new paragraph.") ); - (void) new KileAction::Tag(i18n("Quotation - \\begin{quotation}"), i18n("Quotation"), QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_quotation","\\begin{quotation}\n","%E\n\\end{quotation} ",0,1, i18n("The text is justified at both margins and there is paragraph indentation.\nLeaving a blank line between text produces a new paragraph.") ); - (void) new KileAction::Tag(i18n("Verse - \\begin{verse}"), i18n("Verse"), QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_verse", "\\begin{verse}\n","%E\n\\end{verse} ",0,1,i18n("The verse environment is designed for poetry.\nSeparate the lines of each stanza with \\\\, and use one or more blank lines to separate the stanzas.") ); - - (void) new KileAction::Tag(i18n("Verbatim - \\begin{verbatim}"), i18n("Verbatim"), "verbatim", QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_verbatim","\\begin{verbatim}\n","%E\n\\end{verbatim} ",0,1,i18n("Environment that gets LaTeX to print exactly what you type in.")); - (void) new KileAction::Tag(i18n("Bulleted List - \\begin{itemize}"), i18n("Bulleted List"), "itemize", QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_env_itemize","\\begin{itemize}\n%E\\item \n", "\\end{itemize}\n", 6,1,i18n("The itemize environment produces a 'bulleted' list.\nEach item of an itemized list begins with an \\item command.")); - (void) new KileAction::Tag(i18n("Enumeration - \\begin{enumerate}"), i18n("Enumeration"), "enumerate", QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_env_enumerate","\\begin{enumerate}\n%E\\item \n","\\end{enumerate}\n", 6,1,i18n("The enumerate environment produces a numbered list.\nEach item of an enumerated list begins with an \\item command.")); - (void) new KileAction::Tag(i18n("Description - \\begin{description}"), i18n("Description"), "description", QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_env_description","\\begin{description}\n%E\\item[] \n", "\\end{description}",6,1,i18n("The description environment is used to make labeled lists.\nEach item of the list begins with an \\item[label] command.\nThe 'label' is bold face and flushed right.")); - - (void) new KileAction::Tag(i18n("Table - \\begin{table}"), i18n("Table"), "table-env", QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_table","\\begin{table}\n","%E\n\\caption{}\n\\end{table} ",0,1, - i18n("\\begin{table}[placement]\nbody of the table\n\\caption{table title}\n\\end{table}\nTables are objects that are not part of the normal text, and are usually floated to a convenient place.\n" - "The optional argument [placement] determines where LaTeX will try to place your table\nh : Here - at the position in the text where the table environment appears\nt : Top - at the top of a text page\nb : Bottom - at the bottom of a text page\n" - "p : Page of floats - on a separate float page, which is a page containing no text, only floats.\nThe body of the table is made up of whatever text or LaTeX commands, etc., you wish.\nThe \\caption command allows you to title your table.")); - - (void) new KileAction::Tag(i18n("Figure - \\begin{figure}"), i18n("Figure"), "figure-env", QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_figure" ,"\\begin{figure}\n","%E\n\\caption{}\n\\end{figure} ",0,1, - i18n("\\begin{figure}[placement]\nbody of the figure\n\\caption{figure title}\n\\end{figure}\nFigures are objects that are not part of the normal text, and are usually floated to a convenient place.\n" - "The optional argument [placement] determines where LaTeX will try to place your figure\nh : Here - at the position in the text where the figure environment appears\nt : Top - at the top of a text page\n" - "b : Bottom - at the bottom of a text page\np : Page of floats - on a separate float page, which is a page containing no text, only floats.\nThe body of the figure is made up of whatever text or LaTeX commands, etc., you wish.\nThe \\caption command allows you to title your figure.")); - - (void) new KileAction::Tag(i18n("Title Page - \\begin{titlepage}"), i18n("Title Page"), QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_titlepage" ,"\\begin{titlepage}\n","%E\n\\end{titlepage} ",0,1, - i18n("\\begin{titlepage}\ntext\n\\end{titlepage}\nThe titlepage environment creates a title page, i.e. a page with no printed page number or heading.")); - - new KileAction::Tag(i18n("Italics - \\textit{}"), i18n("Italics"), "format-text-italic", QKeySequence(Qt::ALT+Qt::SHIFT+Qt::Key_I), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_textit","\\textit{","}",8,0,i18n("\\textit{italic text}")); - new KileAction::Tag(i18n("Slanted - \\textsl{}"), i18n("Slanted"), "slanted", QKeySequence(Qt::ALT+Qt::SHIFT+Qt::Key_A), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_textsl","\\textsl{","}",8,0,i18n("\\textsl{slanted text}")); - new KileAction::Tag(i18n("Boldface - \\textbf{}"), i18n("Boldface"), "format-text-bold", QKeySequence(Qt::ALT+Qt::SHIFT+Qt::Key_B), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_textbf","\\textbf{","}",8,0,i18n("\\textbf{boldface text}")); - new KileAction::Tag(i18n("Typewriter - \\texttt{}"), i18n("Typewriter"), "typewriter", QKeySequence(Qt::ALT+Qt::SHIFT+Qt::Key_T), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_texttt","\\texttt{","}",8,0,i18n("\\texttt{typewriter text}")); - new KileAction::Tag(i18n("Small Caps - \\textsc{}"), i18n("Small Caps"), QKeySequence(Qt::ALT+Qt::SHIFT+Qt::Key_C), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_textsc","\\textsc{","}",8,0,i18n("\\textsc{small caps text}")); - new KileAction::Tag("\\item", QString(), "item", QKeySequence(Qt::ALT+Qt::SHIFT+Qt::Key_H), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_item","\\item ",QString(),6,0, i18n("\\item[label] Hello!")); - - (void) new KileAction::Tag(i18n("Tabbing - \\begin{tabbing}"), i18n("Tabbing"), "tabbing", QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_env_tabbing" ,"\\begin{tabbing}\n","%E\n\\end{tabbing} ",0,1,i18n("The tabbing environment provides a way to align text in columns.\n\\begin{tabbing}\ntext \\= more text \\= still more text \\= last text \\\\\nsecond row \\> \\> more \\\\\n\\end{tabbing}\nCommands :\n\\= Sets a tab stop at the current position.\n\\> Advances to the next tab stop.\n\\< Allows you to put something to the left of the local margin without changing the margin. Can only be used at the start of the line.\n\\+ Moves the left margin of the next and all the following commands one tab stop to the right\n\\- Moves the left margin of the next and all the following commands one tab stop to the left\n\\' Moves everything that you have typed so far in the current column to the right of the previous column, flush against the current column's tab stop. \n\\` Allows you to put text flush right against any tab stop, including tab stop 0\n\\kill Sets tab stops without producing text.\n\\a In a tabbing environment, the commands \\=, \\' and \\` do not produce accents as normal. Instead, the commands \\a=, \\a' and \\a` are used.")); - (void) new KileAction::Tag(i18n("Tabular - \\begin{tabular}"), i18n("Tabular"), "tabular", QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_env_tabular" ,"\\begin{tabular}{","}\n%E\n\\end{tabular} ",16,0,i18n("\\begin{tabular}[pos]{cols}\ncolumn 1 entry & column 2 entry ... & column n entry \\\\\n...\n\\end{tabular}\npos : Specifies the vertical position; default is alignment on the center of the environment.\n t - align on top row\n b - align on bottom row\ncols : Specifies the column formatting.\n l - A column of left-aligned items.\n r - A column of right-aligned items.\n c - A column of centered items.\n | - A vertical line the full height and depth of the environment.\n @{text} - this inserts text in every row.\nThe \\hline command draws a horizontal line the width of the table.\nThe \\cline{i-j} command draws horizontal lines across the columns specified, beginning in column i and ending in column j.\nThe \\vline command draws a vertical line extending the full height and depth of its row.")); - (void) new KileAction::Tag(i18n("Multicolumn Cells - \\multicolumn"), i18n("Multicolumn Cells"), "multicolumn", QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)),actionCollection,"tag_multicolumn","\\multicolumn{","}{}{} ",13,0,i18n("\\multicolumn{cols}{pos}{text}\ncol, specifies the number of columns to span.\npos specifies the formatting of the entry: c for centered, l for flushleft, r for flushright.\ntext specifies what text is to make up the entry.")); - (void) new KileAction::Tag(i18n("Horizontal Line - \\hline"), i18n("Horizontal Line"), "hline", QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_hline" ,"\\hline ",QString(),7,0,i18n("The \\hline command draws a horizontal line the width of the table.")); - (void) new KileAction::Tag(i18n("Vertical Line - \\vline"), i18n("Vertical Line"), "vline", QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_vline" ,"\\vline ",QString(),7,0,i18n("The \\vline command draws a vertical line extending the full height and depth of its row.")); - (void) new KileAction::Tag(i18n("Horizontal Line Across Columns - \\cline{m-n}"), i18n("Horizontal Line Across Columns"), "cline", QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_cline" ,"\\cline{-} ",QString(),7,0,i18n("The \\cline{i-j} command draws horizontal lines across the columns specified, beginning in column i and ending in column j,")); - - (void) new KileAction::Tag(i18n("New Page - \\newpage"), i18n("New Page"), QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_newpage","\\newpage ",QString(),9,0,i18n("The \\newpage command ends the current page")); - (void) new KileAction::Tag(i18n("Line Break - \\linebreak"), i18n("Line Break"), QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_linebreak","\\linebreak ",QString(),11,0,i18n("The \\linebreak command tells LaTeX to break the current line at the point of the command.")); - (void) new KileAction::Tag(i18n("Page Break - \\pagebreak"), i18n("Page Break"), QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_pagebreak","\\pagebreak ",QString(),11,0,i18n("The \\pagebreak command tells LaTeX to break the current page at the point of the command.")); - (void) new KileAction::Tag(i18n("\"Big\" Vertical Space - \\bigskip"), i18n("\"Big\" Vertical Space"), "bigskip", QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_bigskip","\\bigskip ",QString(),9,0,i18n("The \\bigskip command adds a 'big' vertical space.")); - (void) new KileAction::Tag(i18n("\"Medium\" Vertical Space - \\medskip"), i18n("\"Medium\" Vertical Space"), "medskip", QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_medskip","\\medskip ",QString(),9,0,i18n("The \\medskip command adds a 'medium' vertical space.")); - - // includegraphics (dani) - (void) new KileAction::Tag(i18n("Image Insertion - \\includegraphics{file}"), i18n("Image Insertion"), "insert-image", QKeySequence("Alt+I, G"),receiver,SLOT(includeGraphics()), actionCollection,"tag_includegraphics",0L); - // two new shortcuts (dani) - (void) new KileAction::InputTag(ki, i18n("Customizable File Inclusion - \\include{file}"), i18n("Customizable File Inclusion"), "include-file", QKeySequence("Alt+I, F"), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_include", parentWidget, KileAction::KeepHistory | KileAction::ShowBrowseButton | KileAction::AddProjectFile, "\\include{%R","}",9,0, i18n("\\include{file}\nThe \\include command is used in conjunction with the \\includeonly command for selective inclusion of files."),i18n("Type or select a filename: ")); - (void) new KileAction::InputTag(ki, i18n("File Inclusion - \\input{file}"), i18n("File Inclusion"), "input-file", QKeySequence("Alt+I, P"), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_input", parentWidget, KileAction::KeepHistory | KileAction::ShowBrowseButton | KileAction::AddProjectFile, "\\input{%R","}",7,0,i18n("\\input{file}\nThe \\input command causes the indicated file to be read and processed, exactly as if its contents had been inserted in the current file at that point."),i18n("Type or select a filename: ")); - - ToolbarSelectAction *actionstructure_list = new ToolbarSelectAction(i18n("Sectioning"), actionCollection,false); - actionCollection->addAction("structure_list", actionstructure_list); - actionstructure_list->addAction(new KileAction::InputTag(ki,"&part", QString(), "part", QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_part", parentWidget, KileAction::ShowAlternative|KileAction::ShowLabel , "\\part%A{%R}","\n", 0,1,i18n("\\part{title}\n\\part*{title} : do not include a number and do not make an entry in the table of contents\n"), i18n("&Part"),i18n("No &numbering"))); - actionstructure_list->addSeparator(); - actionstructure_list->addAction(new KileAction::InputTag(ki,"&chapter", QString(), "chapter", QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_chapter", parentWidget, KileAction::ShowAlternative|KileAction::ShowLabel , "\\chapter%A{%R}","\n", 0,1,i18n("\\chapter{title}\n\\chapter*{title} : do not include a number and do not make an entry in the table of contents\nOnly for 'report' and 'book' class document."), i18n("C&hapter"),i18n("No &numbering"))); - actionstructure_list->addAction(new KileAction::InputTag(ki,"§ion", QString(), "section", QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_section", parentWidget, KileAction::ShowAlternative|KileAction::ShowLabel , "\\section%A{%R}","\n", 0,1,i18n("\\section{title}\n\\section*{title} : do not include a number and do not make an entry in the table of contents"), i18n("&Section"),i18n("No &numbering"))); - actionstructure_list->addAction(new KileAction::InputTag(ki,"s&ubsection", QString(), "subsection", QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_subsection", parentWidget, KileAction::ShowAlternative|KileAction::ShowLabel , "\\subsection%A{%R}","\n", 0,1,i18n("\\subsection{title}\n\\subsection*{title} : do not include a number and do not make an entry in the table of contents"), i18n("&Subsection"),i18n("No &numbering"))); - actionstructure_list->addAction(new KileAction::InputTag(ki,"su&bsubsection", QString(), "subsubsection", QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_subsubsection", parentWidget, KileAction::ShowAlternative|KileAction::ShowLabel , "\\subsubsection%A{%R}","\n", 0,1,i18n("\\subsubsection{title}\n\\subsubsection*{title} : do not include a number and do not make an entry in the table of contents"), i18n("&Subsubsection"),i18n("No &numbering"))); - actionstructure_list->addSeparator(); - actionstructure_list->addAction(new KileAction::InputTag(ki,"p&aragraph", QString(), QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_paragraph", parentWidget, KileAction::ShowAlternative|KileAction::ShowLabel , "\\paragraph%A{%R}","\n", 0,1,i18n("\\paragraph{title}\n\\paragraph*{title} : do not include a number and do not make an entry in the table of contents"), i18n("&Paragraph"),i18n("No &numbering"))); - actionstructure_list->addAction(new KileAction::InputTag(ki,"subpa&ragraph", QString(), QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_subparagraph", parentWidget, KileAction::ShowAlternative|KileAction::ShowLabel , "\\subparagraph%A{%R}","\n", 0,1,i18n("\\subparagraph{title}\n\\subparagraph*{title} : do not include a number and do not make an entry in the table of contents"), i18n("&Subparagraph"),i18n("No &numbering"))); - - ToolbarSelectAction *actionsize_list = new ToolbarSelectAction(i18n("Size"), actionCollection,false); - actionCollection->addAction("size_list", actionsize_list); - actionsize_list->addAction(new KileAction::Tag(i18n("tiny"), QString(), QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection, "tag_tiny", "\\begin{tiny}", "\\end{tiny}", 12, 0)); - actionsize_list->addAction(new KileAction::Tag(i18n("scriptsize"), QString(), QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection, "tag_scriptsize", "\\begin{scriptsize}", "\\end{scriptsize}", 18, 0)); - actionsize_list->addAction(new KileAction::Tag(i18n("footnotesize"), QString(), QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection, "tag_footnotesize", "\\begin{footnotesize}", "\\end{footnotesize}", 20, 0)); - actionsize_list->addAction(new KileAction::Tag(i18n("small"), QString(), QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection, "tag_small", "\\begin{small}", "\\end{small}", 13, 0)); - actionsize_list->addSeparator(); - actionsize_list->addAction(new KileAction::Tag(i18n("normalsize"), QString(), QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection, "tag_normalsize", "\\begin{normalsize}", "\\end{normalsize}", 18, 0)); - actionsize_list->addSeparator(); - actionsize_list->addAction(new KileAction::Tag(i18n("large"), QString(), QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_large", "\\begin{large}", "\\end{large}", 13, 0)); - actionsize_list->addAction(new KileAction::Tag(i18n("Large"), QString(), QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_Large", "\\begin{Large}", "\\end{Large}", 13, 0)); - actionsize_list->addAction(new KileAction::Tag(i18n("LARGE"), QString(), QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_LARGE", "\\begin{LARGE}", "\\end{LARGE}", 13, 0)); - actionsize_list->addAction(new KileAction::Tag(i18n("huge"), QString(), QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection, "tag_huge", "\\begin{huge}", "\\end{huge}", 12, 0)); - actionsize_list->addAction(new KileAction::Tag(i18n("Huge"), QString(), QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection, "tag_Huge", "\\begin{Huge}", "\\end{Huge}", 12, 0)); - - ToolbarSelectAction *actionother_list = new ToolbarSelectAction(i18n("Other"), actionCollection,false); - actionCollection->addAction("other_list", actionother_list); - actionother_list->addAction(new KileAction::Tag("label", QString(), QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_label", "\\label{","} ",7,0,i18n("\\label{key}"))); - actionother_list->addAction(new KileAction::InputTag(ki,"ref", QString(), QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_ref", parentWidget, KileAction::FromLabelList, "\\ref{%R", "}", 5,0, QString(), i18n("Label") )); - actionother_list->addAction(new KileAction::InputTag(ki,"pageref", QString(), QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_pageref", parentWidget, KileAction::FromLabelList, "\\pageref{%R", "}", 9,0, QString(), i18n("Label") )); - actionother_list->addSeparator(); - actionother_list->addAction(new KileAction::Tag("index", QString(), QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_index","\\index{","}",7,0,i18n( "\\index{word}"))); - actionother_list->addAction(new KileAction::Tag("footnote", QString(), QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_footnote", "\\footnote{","}",10,0,i18n( "\\footnote{text}"))); - actionother_list->addSeparator(); - actionother_list->addAction(new KileAction::InputTag(ki,"cite", QString(), QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_cite", parentWidget, KileAction::FromBibItemList, "\\cite{%R", "}", 6,0, i18n("This command generates an in-text citation to the reference associated with the ref entry in the bib file\nYou can open the bib file with Kile to see all the available references"), i18n("Reference"))); + (void) new KileAction::Tag(i18n("Document Class Selection - \\documentclass{}"), i18n("Document Class"), QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection, "tag_documentclass", + "\\documentclass[10pt]{","}", 21, 0, i18n("\\documentclass[options]{class}\nclass : article,report,book,letter\nsize options : 10pt, 11pt, 12pt\npaper size options: a4paper, a5paper, b5paper, letterpaper, legalpaper, executivepaper\n" + "other options: \nlandscape -- selects landscape format; default is portrait. \ntitlepage, notitlepage -- selects if there should be a separate title page.\nleqno -- display equation number on left side of equations; default is right side.\n" + "fleqn -- display formulae flush left; default is centered.\nonecolumn, twocolumn -- one or two columns; defaults to one column\noneside, twoside -- selects one- or two-sided layout.\n" )); + + (void) new KileAction::Tag(i18n("Package Import - \\usepackage{}"), i18n("Package Import"), QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_usepackage", + "\\usepackage{","}", 12, 0, i18n("Any options given in the \\documentclass command that are unknown by the selected document class\n" + "are passed on to the packages loaded with \\usepackage.")); + + (void) new KileAction::Tag(i18n("AMS Packages"), QString(), QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_amspackages","\\usepackage{amsmath}\n\\usepackage{amsfonts}\n\\usepackage{amssymb}\n",QString(),0,3,i18n("The principal American Mathematical Society packages")); + (void) new KileAction::Tag(i18n("Start Document Body - \\begin{document}"), i18n("Start Document Body"), QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_env_document","\\begin{document}\n", "\n\\end{document}", 0,1,i18n("Text is allowed only between \\begin{document} and \\end{document}.\nThe 'preamble' (before \\begin{document} ) may contain declarations only.")); + (void) new KileAction::Tag(i18n("Generate Title - \\maketitle"), i18n("Generate Title"), QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_maketitle","\\maketitle",QString(),10,0,i18n("This command generates a title on a separate title page\n- except in the article class, where the title normally goes at the top of the first page.")); + (void) new KileAction::Tag(i18n("Table of Contents - \\tableofcontents"), i18n("Table of Contents"), "view-table-of-contents-ltr", QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_tableofcontents","\\tableofcontents",QString(),16,0,i18n("Put this command where you want the table of contents to go")); + (void) new KileAction::Tag(i18n("Title Definition - \\title{}"), i18n("Title Definition"), QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_title","\\title{","}",7,0,i18n( "\\title{text}\nThe \\title command declares text to be the title.\nUse \\\\ to tell LaTeX where to start a new line in a long title.")); + (void) new KileAction::Tag(i18n("Author Definition - \\author{}"), i18n("Author Definition"), QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_author","\\author{","}",8,0,i18n( "\\author{names}\nThe \\author command declares the author(s), where names is a list of authors separated by \\and commands.")); + + (void) new KileAction::Tag(i18n("Center - \\begin{center}"), i18n("Center"), "format-justify-center", QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_center", "\\begin{center}\n","%E\n\\end{center}", 0,1, i18n("Each line must be terminated with the string \\\\.")); + (void) new KileAction::Tag(i18n("Align Left - \\begin{flushleft}"), i18n("Align Left"), "format-justify-left", QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_flushleft", "\\begin{flushleft}\n","%E\n\\end{flushleft}", 0,1, i18n("Each line must be terminated with the string \\\\.") ); + (void) new KileAction::Tag(i18n("Align Right - \\begin{flushright}"), i18n("Align Right"), "format-justify-right", QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_flushright", "\\begin{flushright}\n","%E\n\\end{flushright}", 0,1, i18n("Each line must be terminated with the string \\\\.") ); + (void) new KileAction::Tag(i18n("Quote - \\begin{quote}"), i18n("Quote"), QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_quote","\\begin{quote}\n","%E\n\\end{quote} ",0,1,i18n("The text is justified at both margins.\nLeaving a blank line between text produces a new paragraph.") ); + (void) new KileAction::Tag(i18n("Quotation - \\begin{quotation}"), i18n("Quotation"), QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_quotation","\\begin{quotation}\n","%E\n\\end{quotation} ",0,1, i18n("The text is justified at both margins and there is paragraph indentation.\nLeaving a blank line between text produces a new paragraph.") ); + (void) new KileAction::Tag(i18n("Verse - \\begin{verse}"), i18n("Verse"), QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_verse", "\\begin{verse}\n","%E\n\\end{verse} ",0,1,i18n("The verse environment is designed for poetry.\nSeparate the lines of each stanza with \\\\, and use one or more blank lines to separate the stanzas.") ); + + (void) new KileAction::Tag(i18n("Verbatim - \\begin{verbatim}"), i18n("Verbatim"), "verbatim", QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_verbatim","\\begin{verbatim}\n","%E\n\\end{verbatim} ",0,1,i18n("Environment that gets LaTeX to print exactly what you type in.")); + (void) new KileAction::Tag(i18n("Bulleted List - \\begin{itemize}"), i18n("Bulleted List"), "itemize", QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_env_itemize","\\begin{itemize}\n%E\\item \n", "\\end{itemize}\n", 6,1,i18n("The itemize environment produces a 'bulleted' list.\nEach item of an itemized list begins with an \\item command.")); + (void) new KileAction::Tag(i18n("Enumeration - \\begin{enumerate}"), i18n("Enumeration"), "enumerate", QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_env_enumerate","\\begin{enumerate}\n%E\\item \n","\\end{enumerate}\n", 6,1,i18n("The enumerate environment produces a numbered list.\nEach item of an enumerated list begins with an \\item command.")); + (void) new KileAction::Tag(i18n("Description - \\begin{description}"), i18n("Description"), "description", QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_env_description","\\begin{description}\n%E\\item[] \n", "\\end{description}",6,1,i18n("The description environment is used to make labeled lists.\nEach item of the list begins with an \\item[label] command.\nThe 'label' is bold face and flushed right.")); + + (void) new KileAction::Tag(i18n("Table - \\begin{table}"), i18n("Table"), "table-env", QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_table","\\begin{table}\n","%E\n\\caption{}\n\\end{table} ",0,1, + i18n("\\begin{table}[placement]\nbody of the table\n\\caption{table title}\n\\end{table}\nTables are objects that are not part of the normal text, and are usually floated to a convenient place.\n" + "The optional argument [placement] determines where LaTeX will try to place your table\nh : Here - at the position in the text where the table environment appears\nt : Top - at the top of a text page\nb : Bottom - at the bottom of a text page\n" + "p : Page of floats - on a separate float page, which is a page containing no text, only floats.\nThe body of the table is made up of whatever text or LaTeX commands, etc., you wish.\nThe \\caption command allows you to title your table.")); + + (void) new KileAction::Tag(i18n("Figure - \\begin{figure}"), i18n("Figure"), "figure-env", QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_figure","\\begin{figure}\n","%E\n\\caption{}\n\\end{figure} ",0,1, + i18n("\\begin{figure}[placement]\nbody of the figure\n\\caption{figure title}\n\\end{figure}\nFigures are objects that are not part of the normal text, and are usually floated to a convenient place.\n" + "The optional argument [placement] determines where LaTeX will try to place your figure\nh : Here - at the position in the text where the figure environment appears\nt : Top - at the top of a text page\n" + "b : Bottom - at the bottom of a text page\np : Page of floats - on a separate float page, which is a page containing no text, only floats.\nThe body of the figure is made up of whatever text or LaTeX commands, etc., you wish.\nThe \\caption command allows you to title your figure.")); + + (void) new KileAction::Tag(i18n("Title Page - \\begin{titlepage}"), i18n("Title Page"), QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_titlepage","\\begin{titlepage}\n","%E\n\\end{titlepage} ",0,1, + i18n("\\begin{titlepage}\ntext\n\\end{titlepage}\nThe titlepage environment creates a title page, i.e. a page with no printed page number or heading.")); + + new KileAction::Tag(i18n("Italics - \\textit{}"), i18n("Italics"), "format-text-italic", QKeySequence(Qt::ALT+Qt::SHIFT+Qt::Key_I), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_textit","\\textit{","}",8,0,i18n("\\textit{italic text}")); + new KileAction::Tag(i18n("Slanted - \\textsl{}"), i18n("Slanted"), "slanted", QKeySequence(Qt::ALT+Qt::SHIFT+Qt::Key_A), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_textsl","\\textsl{","}",8,0,i18n("\\textsl{slanted text}")); + new KileAction::Tag(i18n("Boldface - \\textbf{}"), i18n("Boldface"), "format-text-bold", QKeySequence(Qt::ALT+Qt::SHIFT+Qt::Key_B), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_textbf","\\textbf{","}",8,0,i18n("\\textbf{boldface text}")); + new KileAction::Tag(i18n("Typewriter - \\texttt{}"), i18n("Typewriter"), "typewriter", QKeySequence(Qt::ALT+Qt::SHIFT+Qt::Key_T), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_texttt","\\texttt{","}",8,0,i18n("\\texttt{typewriter text}")); + new KileAction::Tag(i18n("Small Caps - \\textsc{}"), i18n("Small Caps"), QKeySequence(Qt::ALT+Qt::SHIFT+Qt::Key_C), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_textsc","\\textsc{","}",8,0,i18n("\\textsc{small caps text}")); + new KileAction::Tag("\\item", QString(), "item", QKeySequence(Qt::ALT+Qt::SHIFT+Qt::Key_H), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_item","\\item ",QString(),6,0, i18n("\\item[label] Hello!")); + + (void) new KileAction::Tag(i18n("Tabbing - \\begin{tabbing}"), i18n("Tabbing"), "tabbing", QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_env_tabbing","\\begin{tabbing}\n","%E\n\\end{tabbing} ",0,1,i18n("The tabbing environment provides a way to align text in columns.\n\\begin{tabbing}\ntext \\= more text \\= still more text \\= last text \\\\\nsecond row \\> \\> more \\\\\n\\end{tabbing}\nCommands :\n\\= Sets a tab stop at the current position.\n\\> Advances to the next tab stop.\n\\< Allows you to put something to the left of the local margin without changing the margin. Can only be used at the start of the line.\n\\+ Moves the left margin of the next and all the following commands one tab stop to the right\n\\- Moves the left margin of the next and all the following commands one tab stop to the left\n\\' Moves everything that you have typed so far in the current column to the right of the previous column, flush against the current column's tab stop. \n\\` Allows you to put text flush right against any tab stop, including tab stop 0\n\\kill Sets tab stops without producing text.\n\\a In a tabbing environment, the commands \\=, \\' and \\` do not produce accents as normal. Instead, the commands \\a=, \\a' and \\a` are used.")); + (void) new KileAction::Tag(i18n("Tabular - \\begin{tabular}"), i18n("Tabular"), "tabular", QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_env_tabular","\\begin{tabular}{","}\n%E\n\\end{tabular} ",16,0,i18n("\\begin{tabular}[pos]{cols}\ncolumn 1 entry & column 2 entry ... & column n entry \\\\\n...\n\\end{tabular}\npos : Specifies the vertical position; default is alignment on the center of the environment.\n t - align on top row\n b - align on bottom row\ncols : Specifies the column formatting.\n l - A column of left-aligned items.\n r - A column of right-aligned items.\n c - A column of centered items.\n | - A vertical line the full height and depth of the environment.\n @{text} - this inserts text in every row.\nThe \\hline command draws a horizontal line the width of the table.\nThe \\cline{i-j} command draws horizontal lines across the columns specified, beginning in column i and ending in column j.\nThe \\vline command draws a vertical line extending the full height and depth of its row.")); + (void) new KileAction::Tag(i18n("Multicolumn Cells - \\multicolumn"), i18n("Multicolumn Cells"), "multicolumn", QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)),actionCollection,"tag_multicolumn","\\multicolumn{","}{}{} ",13,0,i18n("\\multicolumn{cols}{pos}{text}\ncol, specifies the number of columns to span.\npos specifies the formatting of the entry: c for centered, l for flushleft, r for flushright.\ntext specifies what text is to make up the entry.")); + (void) new KileAction::Tag(i18n("Horizontal Line - \\hline"), i18n("Horizontal Line"), "hline", QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_hline","\\hline ",QString(),7,0,i18n("The \\hline command draws a horizontal line the width of the table.")); + (void) new KileAction::Tag(i18n("Vertical Line - \\vline"), i18n("Vertical Line"), "vline", QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_vline","\\vline ",QString(),7,0,i18n("The \\vline command draws a vertical line extending the full height and depth of its row.")); + (void) new KileAction::Tag(i18n("Horizontal Line Across Columns - \\cline{m-n}"), i18n("Horizontal Line Across Columns"), "cline", QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_cline","\\cline{-} ",QString(),7,0,i18n("The \\cline{i-j} command draws horizontal lines across the columns specified, beginning in column i and ending in column j,")); + + (void) new KileAction::Tag(i18n("New Page - \\newpage"), i18n("New Page"), QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_newpage","\\newpage ",QString(),9,0,i18n("The \\newpage command ends the current page")); + (void) new KileAction::Tag(i18n("Line Break - \\linebreak"), i18n("Line Break"), QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_linebreak","\\linebreak ",QString(),11,0,i18n("The \\linebreak command tells LaTeX to break the current line at the point of the command.")); + (void) new KileAction::Tag(i18n("Page Break - \\pagebreak"), i18n("Page Break"), QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_pagebreak","\\pagebreak ",QString(),11,0,i18n("The \\pagebreak command tells LaTeX to break the current page at the point of the command.")); + (void) new KileAction::Tag(i18n("\"Big\" Vertical Space - \\bigskip"), i18n("\"Big\" Vertical Space"), "bigskip", QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_bigskip","\\bigskip ",QString(),9,0,i18n("The \\bigskip command adds a 'big' vertical space.")); + (void) new KileAction::Tag(i18n("\"Medium\" Vertical Space - \\medskip"), i18n("\"Medium\" Vertical Space"), "medskip", QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_medskip","\\medskip ",QString(),9,0,i18n("The \\medskip command adds a 'medium' vertical space.")); + + // includegraphics (dani) + (void) new KileAction::Tag(i18n("Image Insertion - \\includegraphics{file}"), i18n("Image Insertion"), "insert-image", QKeySequence("Alt+I, G"),receiver,SLOT(includeGraphics()), actionCollection,"tag_includegraphics",0L); + // two new shortcuts (dani) + (void) new KileAction::InputTag(ki, i18n("Customizable File Inclusion - \\include{file}"), i18n("Customizable File Inclusion"), "include-file", QKeySequence("Alt+I, F"), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_include", parentWidget, KileAction::KeepHistory | KileAction::ShowBrowseButton | KileAction::AddProjectFile, "\\include{%R","}",9,0, i18n("\\include{file}\nThe \\include command is used in conjunction with the \\includeonly command for selective inclusion of files."),i18n("Type or select a filename: ")); + (void) new KileAction::InputTag(ki, i18n("File Inclusion - \\input{file}"), i18n("File Inclusion"), "input-file", QKeySequence("Alt+I, P"), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_input", parentWidget, KileAction::KeepHistory | KileAction::ShowBrowseButton | KileAction::AddProjectFile, "\\input{%R","}",7,0,i18n("\\input{file}\nThe \\input command causes the indicated file to be read and processed, exactly as if its contents had been inserted in the current file at that point."),i18n("Type or select a filename: ")); + + ToolbarSelectAction *actionstructure_list = new ToolbarSelectAction(i18n("Sectioning"), actionCollection,false); + actionCollection->addAction("structure_list", actionstructure_list); + actionstructure_list->addAction(new KileAction::InputTag(ki,"&part", QString(), "part", QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_part", parentWidget, KileAction::ShowAlternative|KileAction::ShowLabel, "\\part%A{%R}","\n", 0,1,i18n("\\part{title}\n\\part*{title} : do not include a number and do not make an entry in the table of contents\n"), i18n("&Part"),i18n("No &numbering"))); + actionstructure_list->addSeparator(); + actionstructure_list->addAction(new KileAction::InputTag(ki,"&chapter", QString(), "chapter", QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_chapter", parentWidget, KileAction::ShowAlternative|KileAction::ShowLabel, "\\chapter%A{%R}","\n", 0,1,i18n("\\chapter{title}\n\\chapter*{title} : do not include a number and do not make an entry in the table of contents\nOnly for 'report' and 'book' class document."), i18n("C&hapter"),i18n("No &numbering"))); + actionstructure_list->addAction(new KileAction::InputTag(ki,"§ion", QString(), "section", QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_section", parentWidget, KileAction::ShowAlternative|KileAction::ShowLabel, "\\section%A{%R}","\n", 0,1,i18n("\\section{title}\n\\section*{title} : do not include a number and do not make an entry in the table of contents"), i18n("&Section"),i18n("No &numbering"))); + actionstructure_list->addAction(new KileAction::InputTag(ki,"s&ubsection", QString(), "subsection", QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_subsection", parentWidget, KileAction::ShowAlternative|KileAction::ShowLabel, "\\subsection%A{%R}","\n", 0,1,i18n("\\subsection{title}\n\\subsection*{title} : do not include a number and do not make an entry in the table of contents"), i18n("&Subsection"),i18n("No &numbering"))); + actionstructure_list->addAction(new KileAction::InputTag(ki,"su&bsubsection", QString(), "subsubsection", QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_subsubsection", parentWidget, KileAction::ShowAlternative|KileAction::ShowLabel, "\\subsubsection%A{%R}","\n", 0,1,i18n("\\subsubsection{title}\n\\subsubsection*{title} : do not include a number and do not make an entry in the table of contents"), i18n("&Subsubsection"),i18n("No &numbering"))); + actionstructure_list->addSeparator(); + actionstructure_list->addAction(new KileAction::InputTag(ki,"p&aragraph", QString(), QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_paragraph", parentWidget, KileAction::ShowAlternative|KileAction::ShowLabel, "\\paragraph%A{%R}","\n", 0,1,i18n("\\paragraph{title}\n\\paragraph*{title} : do not include a number and do not make an entry in the table of contents"), i18n("&Paragraph"),i18n("No &numbering"))); + actionstructure_list->addAction(new KileAction::InputTag(ki,"subpa&ragraph", QString(), QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_subparagraph", parentWidget, KileAction::ShowAlternative|KileAction::ShowLabel, "\\subparagraph%A{%R}","\n", 0,1,i18n("\\subparagraph{title}\n\\subparagraph*{title} : do not include a number and do not make an entry in the table of contents"), i18n("&Subparagraph"),i18n("No &numbering"))); + + ToolbarSelectAction *actionsize_list = new ToolbarSelectAction(i18n("Size"), actionCollection,false); + actionCollection->addAction("size_list", actionsize_list); + actionsize_list->addAction(new KileAction::Tag(i18n("tiny"), QString(), QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection, "tag_tiny", "\\begin{tiny}", "\\end{tiny}", 12, 0)); + actionsize_list->addAction(new KileAction::Tag(i18n("scriptsize"), QString(), QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection, "tag_scriptsize", "\\begin{scriptsize}", "\\end{scriptsize}", 18, 0)); + actionsize_list->addAction(new KileAction::Tag(i18n("footnotesize"), QString(), QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection, "tag_footnotesize", "\\begin{footnotesize}", "\\end{footnotesize}", 20, 0)); + actionsize_list->addAction(new KileAction::Tag(i18n("small"), QString(), QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection, "tag_small", "\\begin{small}", "\\end{small}", 13, 0)); + actionsize_list->addSeparator(); + actionsize_list->addAction(new KileAction::Tag(i18n("normalsize"), QString(), QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection, "tag_normalsize", "\\begin{normalsize}", "\\end{normalsize}", 18, 0)); + actionsize_list->addSeparator(); + actionsize_list->addAction(new KileAction::Tag(i18n("large"), QString(), QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_large", "\\begin{large}", "\\end{large}", 13, 0)); + actionsize_list->addAction(new KileAction::Tag(i18n("Large"), QString(), QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_Large", "\\begin{Large}", "\\end{Large}", 13, 0)); + actionsize_list->addAction(new KileAction::Tag(i18n("LARGE"), QString(), QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_LARGE", "\\begin{LARGE}", "\\end{LARGE}", 13, 0)); + actionsize_list->addAction(new KileAction::Tag(i18n("huge"), QString(), QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection, "tag_huge", "\\begin{huge}", "\\end{huge}", 12, 0)); + actionsize_list->addAction(new KileAction::Tag(i18n("Huge"), QString(), QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection, "tag_Huge", "\\begin{Huge}", "\\end{Huge}", 12, 0)); + + ToolbarSelectAction *actionother_list = new ToolbarSelectAction(i18n("Other"), actionCollection,false); + actionCollection->addAction("other_list", actionother_list); + actionother_list->addAction(new KileAction::Tag("label", QString(), QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_label", "\\label{","} ",7,0,i18n("\\label{key}"))); + actionother_list->addAction(new KileAction::InputTag(ki,"ref", QString(), QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_ref", parentWidget, KileAction::FromLabelList, "\\ref{%R", "}", 5,0, QString(), i18n("Label") )); + actionother_list->addAction(new KileAction::InputTag(ki,"pageref", QString(), QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_pageref", parentWidget, KileAction::FromLabelList, "\\pageref{%R", "}", 9,0, QString(), i18n("Label") )); + actionother_list->addSeparator(); + actionother_list->addAction(new KileAction::Tag("index", QString(), QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_index","\\index{","}",7,0,i18n( "\\index{word}"))); + actionother_list->addAction(new KileAction::Tag("footnote", QString(), QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_footnote", "\\footnote{","}",10,0,i18n( "\\footnote{text}"))); + actionother_list->addSeparator(); + actionother_list->addAction(new KileAction::InputTag(ki,"cite", QString(), QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_cite", parentWidget, KileAction::FromBibItemList, "\\cite{%R", "}", 6,0, i18n("This command generates an in-text citation to the reference associated with the ref entry in the bib file\nYou can open the bib file with Kile to see all the available references"), i18n("Reference"))); // QAction *action = actionCollection->addAction("citeViewBib", receiver, SLOT(citeViewBib())); // action->setText(i18n("cite from ViewBib")); // actionother_list->addAction(action); - (void) new KileAction::Tag(i18n("Underline - \\underline{}"), i18n("Underline"), "format-text-underline", QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_underline", "\\underline{","}",11); + (void) new KileAction::Tag(i18n("Underline - \\underline{}"), i18n("Underline"), "format-text-underline", QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_underline", "\\underline{","}",11); - QAction *action = actionCollection->addAction("tag_newline", ki->editorExtension(), SLOT(insertIntelligentNewline())); - action->setText(i18n("Smart New Line")); - actionCollection->setDefaultShortcut(action, QKeySequence(Qt::CTRL + Qt::Key_Return)); - action->setIcon(QIcon::fromTheme("smartnewline")); + QAction *action = actionCollection->addAction("tag_newline", ki->editorExtension(), SLOT(insertIntelligentNewline())); + action->setText(i18n("Smart New Line")); + actionCollection->setDefaultShortcut(action, QKeySequence(Qt::CTRL + Qt::Key_Return)); + action->setIcon(QIcon::fromTheme("smartnewline")); - action = actionCollection->addAction("tag_tabulator", ki->editorExtension(), SLOT(insertIntelligentTabulator())); - action->setText(i18n("Smart Tabulator")); - actionCollection->setDefaultShortcut(action, QKeySequence(Qt::ALT + Qt::Key_Ampersand)); + action = actionCollection->addAction("tag_tabulator", ki->editorExtension(), SLOT(insertIntelligentTabulator())); + action->setText(i18n("Smart Tabulator")); + actionCollection->setDefaultShortcut(action, QKeySequence(Qt::ALT + Qt::Key_Ampersand)); - // new tags (dani 29.01.2005) - KActionCollection* ac = actionCollection; + // new tags (dani 29.01.2005) + KActionCollection* ac = actionCollection; - // environments - (void) new KileAction::Tag(i18n("Abstract - \\begin{abstract}"), i18n("Abstract"), QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), ac,"tag_env_abstract","\\begin{abstract}\n","%E\n\\end{abstract} ",0,1, i18n("\\begin{abstract}\ntext\n\\end{abstract}\nThe abstract environment creates a title page, i.e. a page with no printed page number or heading.")); + // environments + (void) new KileAction::Tag(i18n("Abstract - \\begin{abstract}"), i18n("Abstract"), QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), ac,"tag_env_abstract","\\begin{abstract}\n","%E\n\\end{abstract} ",0,1, i18n("\\begin{abstract}\ntext\n\\end{abstract}\nThe abstract environment creates a title page, i.e. a page with no printed page number or heading.")); - (void) new KileAction::Tag(i18n("Tabular* - \\begin{tabular*}"), i18n("Tabular*"), "tabular-star", QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), ac,"tag_env_tabular*","\\begin{tabular*}{}{","}\n%E\n\\end{tabular*}\n",17,0, i18n("\\begin{tabular*}{width}[pos]{cols}\ncolumn 1 entry & column 2 entry ... & column n entry \\\\\n...\n\\end{tabular*}\nThis is an extended version of the tabular environment with an extra parameter for the width. There must be rubber space between columns that can stretch to fill out the specified width.")); + (void) new KileAction::Tag(i18n("Tabular* - \\begin{tabular*}"), i18n("Tabular*"), "tabular-star", QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), ac,"tag_env_tabular*","\\begin{tabular*}{}{","}\n%E\n\\end{tabular*}\n",17,0, i18n("\\begin{tabular*}{width}[pos]{cols}\ncolumn 1 entry & column 2 entry ... & column n entry \\\\\n...\n\\end{tabular*}\nThis is an extended version of the tabular environment with an extra parameter for the width. There must be rubber space between columns that can stretch to fill out the specified width.")); - (void) new KileAction::Tag(i18n("Minipage - \\begin{minipage}"), i18n("Minipage"), "minipage", QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)),ac,"tag_env_minipage","\\begin{minipage}[","]{}\n%E\n\\end{minipage} ",17,0, i18n("The minipage environment is similar to a \\parbox command. It takes the same optional position argument and mandatory width argument. You may use other paragraph-making environments inside a minipage.")); + (void) new KileAction::Tag(i18n("Minipage - \\begin{minipage}"), i18n("Minipage"), "minipage", QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)),ac,"tag_env_minipage","\\begin{minipage}[","]{}\n%E\n\\end{minipage} ",17,0, i18n("The minipage environment is similar to a \\parbox command. It takes the same optional position argument and mandatory width argument. You may use other paragraph-making environments inside a minipage.")); - // lists - (void) new KileAction::Tag(i18n("Table of Figures - \\listoffigures"), i18n("Table of Figures"), QKeySequence(), receiver,SLOT(insertTag(const KileAction::TagData&)), ac,"tag_listoffigures","\\listoffigures",QString(),14,0, i18n("Put this command where you want the list of figures to go.")); + // lists + (void) new KileAction::Tag(i18n("Table of Figures - \\listoffigures"), i18n("Table of Figures"), QKeySequence(), receiver,SLOT(insertTag(const KileAction::TagData&)), ac,"tag_listoffigures","\\listoffigures",QString(),14,0, i18n("Put this command where you want the list of figures to go.")); - (void) new KileAction::Tag(i18n("Table of Tables - \\listoftables"), i18n("Table of Tables"), QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), ac,"tag_listoftables","\\listoftables",QString(),14,0, i18n("Put this command where you want the list of tables to go.")); + (void) new KileAction::Tag(i18n("Table of Tables - \\listoftables"), i18n("Table of Tables"), QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), ac,"tag_listoftables","\\listoftables",QString(),14,0, i18n("Put this command where you want the list of tables to go.")); - (void) new KileAction::Tag(i18n("Generate Index - \\makeindex"), i18n("Generate Index"), QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), ac,"tag_makeindex","\\makeindex",QString(),10,0, i18n("Put this command when you want to generate the raw index.")); + (void) new KileAction::Tag(i18n("Generate Index - \\makeindex"), i18n("Generate Index"), QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), ac,"tag_makeindex","\\makeindex",QString(),10,0, i18n("Put this command when you want to generate the raw index.")); - (void) new KileAction::Tag(i18n("Print Index - \\printindex"), i18n("Print Index"), QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), ac,"tag_printindex","\\printindex",QString(),11,0, i18n("Put this command when you want to print the formatted index.")); + (void) new KileAction::Tag(i18n("Print Index - \\printindex"), i18n("Print Index"), QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), ac,"tag_printindex","\\printindex",QString(),11,0, i18n("Put this command when you want to print the formatted index.")); - (void) new KileAction::Tag(i18n("Glossary - \\makeglossary"), i18n("Glossary"), QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), ac,"tag_makeglossary","\\makeglossary",QString(),13,0, i18n("Put this command when you want to print a glossary.")); + (void) new KileAction::Tag(i18n("Glossary - \\makeglossary"), i18n("Glossary"), QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), ac,"tag_makeglossary","\\makeglossary",QString(),13,0, i18n("Put this command when you want to print a glossary.")); - (void) new KileAction::Tag(i18n("Bibliography - \\begin{thebibliography}"), i18n("Bibliography"), QKeySequence(), receiver,SLOT(insertTag(const KileAction::TagData&)), ac,"tag_env_thebibliography" ,"\\begin{thebibliography}{","}\n\n\\end{thebibliography} ",24,0, i18n("\\begin{thebibliography}{widest-label}\n\\bibitem[label]{cite_key}\n...\n\\end{thebibliography}\n\nwidest-label : Text that, when printed, is approximately as wide as the widest item label produces by the \\bibitem commands\n\\bibitem : Specify a bibliography item")); + (void) new KileAction::Tag(i18n("Bibliography - \\begin{thebibliography}"), i18n("Bibliography"), QKeySequence(), receiver,SLOT(insertTag(const KileAction::TagData&)), ac,"tag_env_thebibliography","\\begin{thebibliography}{","}\n\n\\end{thebibliography} ",24,0, i18n("\\begin{thebibliography}{widest-label}\n\\bibitem[label]{cite_key}\n...\n\\end{thebibliography}\n\nwidest-label : Text that, when printed, is approximately as wide as the widest item label produces by the \\bibitem commands\n\\bibitem : Specify a bibliography item")); - // verbatim code - (void) new KileAction::Tag(i18n("Verbatim (show spaces) - \\begin{verbatim*}"), i18n("Verbatim (show spaces)"), QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)),ac,"tag_env_verbatim*","\\begin{verbatim*}\n","%E\n\\end{verbatim*}\n",0,1, i18n("Environment that gets LaTeX to print exactly what you type in. In this variant, spaces are printed in a special manner.")); + // verbatim code + (void) new KileAction::Tag(i18n("Verbatim (show spaces) - \\begin{verbatim*}"), i18n("Verbatim (show spaces)"), QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)),ac,"tag_env_verbatim*","\\begin{verbatim*}\n","%E\n\\end{verbatim*}\n",0,1, i18n("Environment that gets LaTeX to print exactly what you type in. In this variant, spaces are printed in a special manner.")); - (void) new KileAction::Tag(i18n("Embedded Code - \\verb||"), i18n("Embedded Code"), "verb", QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)),ac,"tag_verb","\\verb|","|",6,0, i18n("Macro form of the verbatim environment.")); + (void) new KileAction::Tag(i18n("Embedded Code - \\verb||"), i18n("Embedded Code"), "verb", QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)),ac,"tag_verb","\\verb|","|",6,0, i18n("Macro form of the verbatim environment.")); - (void) new KileAction::Tag(i18n("Embedded Code (show spaces) - \\verb*||"), i18n("Embedded Code (show spaces)"), QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)),ac,"tag_verb*","\\verb*|","|",7,0, i18n("Macro form of the verbatim* environment.")); + (void) new KileAction::Tag(i18n("Embedded Code (show spaces) - \\verb*||"), i18n("Embedded Code (show spaces)"), QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)),ac,"tag_verb*","\\verb*|","|",7,0, i18n("Macro form of the verbatim* environment.")); - // horizontal/vertical space - (void) new KileAction::Tag(i18n("\"Small\" Vertical Space - \\smallskip"), i18n("\"Small\" Vertical Space"), "smallskip", QKeySequence(), receiver,SLOT(insertTag(const KileAction::TagData&)), ac,"tag_smallskip","\\smallskip ",QString(),10,0, i18n("The \\smallskip command adds a 'small' vertical space.")); + // horizontal/vertical space + (void) new KileAction::Tag(i18n("\"Small\" Vertical Space - \\smallskip"), i18n("\"Small\" Vertical Space"), "smallskip", QKeySequence(), receiver,SLOT(insertTag(const KileAction::TagData&)), ac,"tag_smallskip","\\smallskip ",QString(),10,0, i18n("The \\smallskip command adds a 'small' vertical space.")); - (void) new KileAction::Tag(i18n("\\enskip"), QString(), "enskip", QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), ac,"tag_enskip", "\\enskip ", QString(), 8); + (void) new KileAction::Tag(i18n("\\enskip"), QString(), "enskip", QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), ac,"tag_enskip", "\\enskip ", QString(), 8); - (void) new KileAction::Tag(i18n("Horizontal Variable Space - \\hfill"), i18n("Horizontal Variable Space"), QKeySequence(), receiver,SLOT(insertTag(const KileAction::TagData&)),ac,"tag_hfill","\\hfill",QString(),6,0, i18n("The \\hfill fill command produces a \"rubber length\" which can stretch or shrink horizontally. It will be filled with spaces.")); + (void) new KileAction::Tag(i18n("Horizontal Variable Space - \\hfill"), i18n("Horizontal Variable Space"), QKeySequence(), receiver,SLOT(insertTag(const KileAction::TagData&)),ac,"tag_hfill","\\hfill",QString(),6,0, i18n("The \\hfill fill command produces a \"rubber length\" which can stretch or shrink horizontally. It will be filled with spaces.")); - (void) new KileAction::Tag(i18n("Horizontal Dots - \\dotfill"), i18n("Horizontal Dots"), QKeySequence(), receiver,SLOT(insertTag(const KileAction::TagData&)),ac,"tag_dotfill","\\dotfill",QString(),8,0, i18n("The \\dotfill command produces a \"rubber length\" that produces dots instead of just spaces.")); + (void) new KileAction::Tag(i18n("Horizontal Dots - \\dotfill"), i18n("Horizontal Dots"), QKeySequence(), receiver,SLOT(insertTag(const KileAction::TagData&)),ac,"tag_dotfill","\\dotfill",QString(),8,0, i18n("The \\dotfill command produces a \"rubber length\" that produces dots instead of just spaces.")); - (void) new KileAction::Tag(i18n("Horizontal Rule - \\hrulefill"), i18n("Horizontal Rule"), QKeySequence(), receiver,SLOT(insertTag(const KileAction::TagData&)),ac,"tag_hrulefill","\\hrulefill",QString(),10,0, i18n("The \\hrulefill fill command produces a \"rubber length\" which can stretch or shrink horizontally. It will be filled with a horizontal rule.")); + (void) new KileAction::Tag(i18n("Horizontal Rule - \\hrulefill"), i18n("Horizontal Rule"), QKeySequence(), receiver,SLOT(insertTag(const KileAction::TagData&)),ac,"tag_hrulefill","\\hrulefill",QString(),10,0, i18n("The \\hrulefill fill command produces a \"rubber length\" which can stretch or shrink horizontally. It will be filled with a horizontal rule.")); - (void) new KileAction::Tag(i18n("Vertical Variable Space - \\vfill"), i18n("Vertical Variable Space"), QKeySequence(), receiver,SLOT(insertTag(const KileAction::TagData&)),ac,"tag_vfill","\\vfill",QString(),6,0, i18n("The \\vfill fill command produces a \"rubber length\" which can stretch or shrink vertically.")); + (void) new KileAction::Tag(i18n("Vertical Variable Space - \\vfill"), i18n("Vertical Variable Space"), QKeySequence(), receiver,SLOT(insertTag(const KileAction::TagData&)),ac,"tag_vfill","\\vfill",QString(),6,0, i18n("The \\vfill fill command produces a \"rubber length\" which can stretch or shrink vertically.")); - (void) new KileAction::Tag(i18n("Horizontal Space - \\hspace{}"), i18n("Horizontal Space"), "hspace", QKeySequence(), receiver,SLOT(insertTag(const KileAction::TagData&)),ac,"tag_hspace","\\hspace{","}",8,0, i18n("The \\hspace command adds horizontal space. The length of the space can be expressed in any terms that LaTeX understands, i.e., points, inches, etc. You can add negative as well as positive space with an \\hspace command. Adding negative space is like backspacing.")); + (void) new KileAction::Tag(i18n("Horizontal Space - \\hspace{}"), i18n("Horizontal Space"), "hspace", QKeySequence(), receiver,SLOT(insertTag(const KileAction::TagData&)),ac,"tag_hspace","\\hspace{","}",8,0, i18n("The \\hspace command adds horizontal space. The length of the space can be expressed in any terms that LaTeX understands, i.e., points, inches, etc. You can add negative as well as positive space with an \\hspace command. Adding negative space is like backspacing.")); - (void) new KileAction::Tag(i18n("Horizontal Space (forced) - \\hspace*{}"), i18n("Horizontal Space (forced)"), "hspace-star", QKeySequence(), receiver,SLOT(insertTag(const KileAction::TagData&)),ac,"tag_hspace*","\\hspace*{","}",9,0, i18n("The \\hspace* command adds horizontal space like the \\hspace command. LaTeX removes horizontal space that comes at the end of a line. If you do not want LaTeX to remove this space, include the optional * argument. Then the space is never removed.")); + (void) new KileAction::Tag(i18n("Horizontal Space (forced) - \\hspace*{}"), i18n("Horizontal Space (forced)"), "hspace-star", QKeySequence(), receiver,SLOT(insertTag(const KileAction::TagData&)),ac,"tag_hspace*","\\hspace*{","}",9,0, i18n("The \\hspace* command adds horizontal space like the \\hspace command. LaTeX removes horizontal space that comes at the end of a line. If you do not want LaTeX to remove this space, include the optional * argument. Then the space is never removed.")); - (void) new KileAction::Tag(i18n("Vertical Space - \\vspace{}"), i18n("Vertical Space"), "vspace", QKeySequence(), receiver,SLOT(insertTag(const KileAction::TagData&)),ac,"tag_vspace","\\vspace{","}",8,0, i18n("The \\vspace command adds vertical space. The length of the space can be expressed in any terms that LaTeX understands, i.e., points, inches, etc. You can add negative as well as positive space with an \\vspace command.")); + (void) new KileAction::Tag(i18n("Vertical Space - \\vspace{}"), i18n("Vertical Space"), "vspace", QKeySequence(), receiver,SLOT(insertTag(const KileAction::TagData&)),ac,"tag_vspace","\\vspace{","}",8,0, i18n("The \\vspace command adds vertical space. The length of the space can be expressed in any terms that LaTeX understands, i.e., points, inches, etc. You can add negative as well as positive space with an \\vspace command.")); - (void) new KileAction::Tag(i18n("Vertical Space (forced) - \\vspace*{}"), i18n("Vertical Space (forced)"), "vspace-star", QKeySequence(), receiver,SLOT(insertTag(const KileAction::TagData&)),ac,"tag_vspace*","\\vspace*{","}",9,0, i18n("The \\vspace* command adds vertical space like the \\vspace command. LaTeX removes vertical space that comes at the end of a page. If you do not want LaTeX to remove this space, include the optional * argument. Then the space is never removed.")); + (void) new KileAction::Tag(i18n("Vertical Space (forced) - \\vspace*{}"), i18n("Vertical Space (forced)"), "vspace-star", QKeySequence(), receiver,SLOT(insertTag(const KileAction::TagData&)),ac,"tag_vspace*","\\vspace*{","}",9,0, i18n("The \\vspace* command adds vertical space like the \\vspace command. LaTeX removes vertical space that comes at the end of a page. If you do not want LaTeX to remove this space, include the optional * argument. Then the space is never removed.")); - // fonts - new KileAction::Tag(i18n("Emphasized - \\emph{}"), i18n("Emphasized"), "emph", QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), ac,"tag_emph","\\emph{","}",6,0,i18n("\\emph{emphasized text}")); - new KileAction::Tag(i18n("Strong - \\strong{}"), i18n("Strong"), "strong", QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), ac,"tag_strong","\\strong{","}",8,0,i18n("\\strong{text}")); + // fonts + new KileAction::Tag(i18n("Emphasized - \\emph{}"), i18n("Emphasized"), "emph", QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), ac,"tag_emph","\\emph{","}",6,0,i18n("\\emph{emphasized text}")); + new KileAction::Tag(i18n("Strong - \\strong{}"), i18n("Strong"), "strong", QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), ac,"tag_strong","\\strong{","}",8,0,i18n("\\strong{text}")); - (void) new KileAction::Tag(i18n("Roman - \\rmfamily"), i18n("Roman"), QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), ac,"tag_rmfamily", "\\rmfamily", QString(), 9); - (void) new KileAction::Tag(i18n("Sans Serif - \\sffamily"), i18n("Sans Serif"), QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), ac,"tag_sffamily", "\\sffamily", QString(), 9); - (void) new KileAction::Tag(i18n("Monospace - \\ttfamily"), i18n("Monospace"), QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), ac,"tag_ttfamily", "\\ttfamily", QString(), 9); + (void) new KileAction::Tag(i18n("Roman - \\rmfamily"), i18n("Roman"), QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), ac,"tag_rmfamily", "\\rmfamily", QString(), 9); + (void) new KileAction::Tag(i18n("Sans Serif - \\sffamily"), i18n("Sans Serif"), QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), ac,"tag_sffamily", "\\sffamily", QString(), 9); + (void) new KileAction::Tag(i18n("Monospace - \\ttfamily"), i18n("Monospace"), QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), ac,"tag_ttfamily", "\\ttfamily", QString(), 9); - (void) new KileAction::Tag(i18n("Medium - \\mdseries"), i18n("Medium"), QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), ac,"tag_mdseries", "\\mdseries", QString(), 9); - (void) new KileAction::Tag(i18n("Bold - \\bfseries"), i18n("Bold"), QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), ac,"tag_bfseries", "\\bfseries", QString(), 9); + (void) new KileAction::Tag(i18n("Medium - \\mdseries"), i18n("Medium"), QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), ac,"tag_mdseries", "\\mdseries", QString(), 9); + (void) new KileAction::Tag(i18n("Bold - \\bfseries"), i18n("Bold"), QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), ac,"tag_bfseries", "\\bfseries", QString(), 9); - (void) new KileAction::Tag(i18n("Upright - \\upshape"), i18n("Upright"), QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), ac,"tag_upshape", "\\upshape", QString(), 8); - (void) new KileAction::Tag(i18n("Italic - \\itshape"), i18n("Italic"), QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), ac,"tag_itshape", "\\itshape", QString(), 8); - (void) new KileAction::Tag(i18n("Slanted - \\slshape"), i18n("Slanted"), QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), ac,"tag_slshape", "\\slshape", QString(), 8); - (void) new KileAction::Tag(i18n("Smallcaps - \\scshape"), i18n("Smallcaps"), QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), ac,"tag_scshape", "\\scshape", QString(), 8); + (void) new KileAction::Tag(i18n("Upright - \\upshape"), i18n("Upright"), QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), ac,"tag_upshape", "\\upshape", QString(), 8); + (void) new KileAction::Tag(i18n("Italic - \\itshape"), i18n("Italic"), QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), ac,"tag_itshape", "\\itshape", QString(), 8); + (void) new KileAction::Tag(i18n("Slanted - \\slshape"), i18n("Slanted"), QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), ac,"tag_slshape", "\\slshape", QString(), 8); + (void) new KileAction::Tag(i18n("Smallcaps - \\scshape"), i18n("Smallcaps"), QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), ac,"tag_scshape", "\\scshape", QString(), 8); } void setupBibTags(const QObject *receiver, KActionCollection *actionCollection, KActionMenu * menu) { - KILE_DEBUG_MAIN << "void setupBibTags(const QObject *receiver, KActionCollection *actionCollection)"; - - QString filename; - - if(KileConfig::bibliographyType().isEmpty() || KileConfig::bibliographyType() == QString("bibtex") ) { - - menu->addAction(new KileAction::Tag(i18n("Bibliography Style Selection - \\bibliographystyle{}"), i18n("Bibliography Style Selection"), QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_bibliographystyle", "\\bibliographystyle{","} ",19,0,i18n("The argument to \\bibliographystyle refers to a file style.bst, which defines how your citations will look\nThe standard styles distributed with BibTeX are:\nalpha : sorted alphabetically. Labels are formed from name of author and year of publication.\nplain : sorted alphabetically. Labels are numeric.\nunsrt : like plain, but entries are in order of citation.\nabbrv : like plain, but more compact labels."))); - menu->addAction(new KileAction::Tag(i18n("Bibliography Generation - \\bibliography{}"), i18n("Bibliography Generation"), QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_bibliography","\\bibliography{%S", "}\n",14, 0,i18n("The argument to \\bibliography refers to the bib file (without extension)\nwhich should contain your database in BibTeX format.\nKile inserts automatically the base name of the TeX file"))); - menu->addSeparator(); - - filename = QStandardPaths::locate(QStandardPaths::DataLocation, "bibtexentries.rc"); - } - else if(KileConfig::bibliographyType() == QString("biblatex")){ - - menu->addAction(new KileAction::Tag(i18n("Load Biblatex Package - \\usepackage{biblatex}"), i18n("Load Biblatex Package"), QKeySequence(), receiver,SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_bibliographyPackage", "\\usepackage{biblatex}\n",QString(),21,0,i18n("This includes the package biblatex"))); - menu->addAction(new KileAction::Tag(i18n("Bibliography Generation - \\bibliography{}"), i18n("Bibliography Generation"), QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_bibliography","\\bibliography{%S", "}\n",14, 0,i18n("The argument to \\bibliography refers to the bib file (without extension)\nwhich should contain your database in BibTeX format.\nKile inserts automatically the base name of the TeX file"))); - menu->addAction(new KileAction::Tag(i18n("Print Bibliography"), QString(), QKeySequence(), receiver,SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_printbibliography", "\\printbibliography",QString(),18,0,i18n("Prints the complete bibliography"))); - menu->addAction(new KileAction::Tag(i18n("Print Bibliography by Section"), QString(), QKeySequence(), receiver,SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_bibliographyBySection", "\\bibbysection[","]",14,0,i18n("Print the bibliography for each section"))); - menu->addAction(new KileAction::Tag(i18n("Print List of Shorthands"), QString(), QKeySequence(), receiver,SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_bibliographyShortHands", "\\printshorthands",QString(),16,0,QString())); - menu->addSeparator(); -/* use this to insert more - menu->addAction(new KileAction::Tag(i18n(""), QKeySequence(), receiver,SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_", "\\",QString(),,0,i18n(""))); -Load Biblatex-Package - \usepackage{biblatex} -Bibliography File - \bibliography{} -Print Bibliography - \printbibliography -Print Bibliography by Section - \bibbysection[] -Print List of Shorthands - \printshorthands -*/ - filename = QStandardPaths::locate(QStandardPaths::DataLocation, "biblatexentries.rc"); - } - else { - filename.clear(); - } - - if(filename.isEmpty()){ - KILE_DEBUG_MAIN << "found no filename" << endl; - return; - } - - KConfig *bibCfg = new KConfig(filename, KConfig::SimpleConfig); - - if(bibCfg == Q_NULLPTR ) - return; - - const QStringList groupList = bibCfg->groupList(); - - // check if a non-deleted group exists - // groupList.count() == 0 is not enough due to bug 384039 - { - bool allDeleted = false; - for(auto group : groupList) { - if(bibCfg->hasGroup(group)) { - allDeleted = false; - break; - } - } - if(allDeleted) { - return; - } - } - - QString name, tag, internalName, keys, key; - QStringList keyList, optKeyList, altKeyList; - QString altText, optText, compText; - - for(auto group : groupList) { - if(!bibCfg->hasGroup(group)) { // 'group' might have been deleted - continue; // work around bug 384039 - } - altKeyList.clear(); - keyList.clear(); - optKeyList.clear(); - - KConfigGroup grp = bibCfg->group(group); + KILE_DEBUG_MAIN << "void setupBibTags(const QObject *receiver, KActionCollection *actionCollection)"; + + QString filename; + + if(KileConfig::bibliographyType().isEmpty() || KileConfig::bibliographyType() == QString("bibtex") ) { + + menu->addAction(new KileAction::Tag(i18n("Bibliography Style Selection - \\bibliographystyle{}"), i18n("Bibliography Style Selection"), QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_bibliographystyle", "\\bibliographystyle{","} ",19,0,i18n("The argument to \\bibliographystyle refers to a file style.bst, which defines how your citations will look\nThe standard styles distributed with BibTeX are:\nalpha : sorted alphabetically. Labels are formed from name of author and year of publication.\nplain : sorted alphabetically. Labels are numeric.\nunsrt : like plain, but entries are in order of citation.\nabbrv : like plain, but more compact labels."))); + menu->addAction(new KileAction::Tag(i18n("Bibliography Generation - \\bibliography{}"), i18n("Bibliography Generation"), QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_bibliography","\\bibliography{%S", "}\n",14, 0,i18n("The argument to \\bibliography refers to the bib file (without extension)\nwhich should contain your database in BibTeX format.\nKile inserts automatically the base name of the TeX file"))); + menu->addSeparator(); + + filename = QStandardPaths::locate(QStandardPaths::DataLocation, "bibtexentries.rc"); + } + else if(KileConfig::bibliographyType() == QString("biblatex")) { + + menu->addAction(new KileAction::Tag(i18n("Load Biblatex Package - \\usepackage{biblatex}"), i18n("Load Biblatex Package"), QKeySequence(), receiver,SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_bibliographyPackage", "\\usepackage{biblatex}\n",QString(),21,0,i18n("This includes the package biblatex"))); + menu->addAction(new KileAction::Tag(i18n("Bibliography Generation - \\bibliography{}"), i18n("Bibliography Generation"), QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_bibliography","\\bibliography{%S", "}\n",14, 0,i18n("The argument to \\bibliography refers to the bib file (without extension)\nwhich should contain your database in BibTeX format.\nKile inserts automatically the base name of the TeX file"))); + menu->addAction(new KileAction::Tag(i18n("Print Bibliography"), QString(), QKeySequence(), receiver,SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_printbibliography", "\\printbibliography",QString(),18,0,i18n("Prints the complete bibliography"))); + menu->addAction(new KileAction::Tag(i18n("Print Bibliography by Section"), QString(), QKeySequence(), receiver,SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_bibliographyBySection", "\\bibbysection[","]",14,0,i18n("Print the bibliography for each section"))); + menu->addAction(new KileAction::Tag(i18n("Print List of Shorthands"), QString(), QKeySequence(), receiver,SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_bibliographyShortHands", "\\printshorthands",QString(),16,0,QString())); + menu->addSeparator(); + /* use this to insert more + menu->addAction(new KileAction::Tag(i18n(""), QKeySequence(), receiver,SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_", "\\",QString(),,0,i18n(""))); + Load Biblatex-Package - \usepackage{biblatex} + Bibliography File - \bibliography{} + Print Bibliography - \printbibliography + Print Bibliography by Section - \bibbysection[] + Print List of Shorthands - \printshorthands + */ + filename = QStandardPaths::locate(QStandardPaths::DataLocation, "biblatexentries.rc"); + } + else { + filename.clear(); + } + + if(filename.isEmpty()) { + KILE_DEBUG_MAIN << "found no filename" << endl; + return; + } + + KConfig *bibCfg = new KConfig(filename, KConfig::SimpleConfig); + + if(bibCfg == Q_NULLPTR ) + return; + + const QStringList groupList = bibCfg->groupList(); + + // check if a non-deleted group exists + // groupList.count() == 0 is not enough due to bug 384039 + { + bool allDeleted = false; + for(auto group : groupList) { + if(bibCfg->hasGroup(group)) { + allDeleted = false; + break; + } + } + if(allDeleted) { + return; + } + } + + QString name, tag, internalName, keys, key; + QStringList keyList, optKeyList, altKeyList; + QString altText, optText, compText; + + for(auto group : groupList) { + if(!bibCfg->hasGroup(group)) { // 'group' might have been deleted + continue; // work around bug 384039 + } + altKeyList.clear(); + keyList.clear(); + optKeyList.clear(); + + KConfigGroup grp = bibCfg->group(group); // KILE_DEBUG_MAIN << "group " << grp.name(); - tag = grp.name(); - name = grp.readEntry(QString("name")); - internalName = grp.readEntry(QString("internalName")); - keyList = grp.readEntry(QString("key")).split(',', QString::SkipEmptyParts); - altKeyList = grp.readEntry(QString("altkey")).split(',', QString::SkipEmptyParts); - optKeyList = grp.readEntry(QString("optkey")).split(',', QString::SkipEmptyParts); - + tag = grp.name(); + name = grp.readEntry(QString("name")); + internalName = grp.readEntry(QString("internalName")); + keyList = grp.readEntry(QString("key")).split(',', QString::SkipEmptyParts); + altKeyList = grp.readEntry(QString("altkey")).split(',', QString::SkipEmptyParts); + optKeyList = grp.readEntry(QString("optkey")).split(',', QString::SkipEmptyParts); + // KILE_DEBUG_MAIN << "length(keys)=" << keyList.count() << ", length(altkeys)=" << altKeyList.count() << ", length(optkeys)=" << optKeyList.count(); // KILE_DEBUG_MAIN << "tag=" << tag << ", name=" << name << ", internalName=" << internalName; - - keys = QString("@%1{,\n").arg(tag); - int length = keys.length() - 2; - - // do some trimming - name = name.trimmed(); - internalName = "tag_bib_" + internalName.trimmed(); - tag = tag.trimmed(); - - for(QList::iterator it = keyList.begin(); it != keyList.end(); ++it) { - key = (*it).trimmed(); - key = QString(" %1 = {},\n").arg(key); - keys.append(key); + + keys = QString("@%1{,\n").arg(tag); + int length = keys.length() - 2; + + // do some trimming + name = name.trimmed(); + internalName = "tag_bib_" + internalName.trimmed(); + tag = tag.trimmed(); + + for(QList::iterator it = keyList.begin(); it != keyList.end(); ++it) { + key = (*it).trimmed(); + key = QString(" %1 = {},\n").arg(key); + keys.append(key); // KILE_DEBUG_MAIN << "key" << key ; - } + } - for(QList::iterator it = altKeyList.begin(); it != altKeyList.end(); ++it) { - key = (*it).trimmed(); - key = QString(" ALT%1 = {},\n").arg(key); - keys.append(key); + for(QList::iterator it = altKeyList.begin(); it != altKeyList.end(); ++it) { + key = (*it).trimmed(); + key = QString(" ALT%1 = {},\n").arg(key); + keys.append(key); // KILE_DEBUG_MAIN << "altkey" << key ; - } - - for(QList::iterator it = optKeyList.begin(); it != optKeyList.end(); ++it) { - key = (*it).trimmed(); - key = QString(" OPT%1 = {},\n").arg(key); - keys.append(key); + } + + for(QList::iterator it = optKeyList.begin(); it != optKeyList.end(); ++it) { + key = (*it).trimmed(); + key = QString(" OPT%1 = {},\n").arg(key); + keys.append(key); // KILE_DEBUG_MAIN << "optKey" << key; - } - keys.append("}\n"); - - altText = i18n("ALT.... : you have the choice between these two fields\n"); - optText = i18n("OPT.... : optional fields (use the 'Clean' command to remove them)"); - compText = i18n("Bib fields - %1\n",name); - - if( altKeyList.count() > 1 ) { - compText.append(altText); - } - if( optKeyList.count() > 1 ) { - compText.append(optText); - } - - menu->addAction(new KileAction::Tag(name, QString(), QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,internalName,keys,QString(),length,0,compText)); - } + } + keys.append("}\n"); + + altText = i18n("ALT.... : you have the choice between these two fields\n"); + optText = i18n("OPT.... : optional fields (use the 'Clean' command to remove them)"); + compText = i18n("Bib fields - %1\n",name); + + if( altKeyList.count() > 1 ) { + compText.append(altText); + } + if( optKeyList.count() > 1 ) { + compText.append(optText); + } + + menu->addAction(new KileAction::Tag(name, QString(), QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,internalName,keys,QString(),length,0,compText)); + } } - + void setupMathTags(const QObject *receiver, KActionCollection *actionCollection) { - (void) new KileAction::Tag(i18n("\\mathrm{}"), QString(), QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_mathrm","\\mathrm{","}",8); - (void) new KileAction::Tag(i18n("\\mathit{}"), QString(), QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_mathit" ,"\\mathit{","}",8); - (void) new KileAction::Tag(i18n("\\mathbf{}"), QString(), QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_mathbf" ,"\\mathbf{","}",8); - (void) new KileAction::Tag(i18n("\\mathsf{}"), QString(), QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_mathsf" ,"\\mathsf{","}",8); - (void) new KileAction::Tag(i18n("\\mathtt{}"), QString(), QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_mathtt" ,"\\mathtt{","}",8); - (void) new KileAction::Tag(i18n("\\mathcal{}"), QString(), QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_mathcal" ,"\\mathcal{","}",9); - (void) new KileAction::Tag(i18n("\\mathbb{}"), QString(), QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_mathbb" ,"\\mathbb{","}",8); - (void) new KileAction::Tag(i18n("\\mathfrak{}"), QString(), QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_mathfrak" ,"\\mathfrak{","}",10); - - (void) new KileAction::Tag(i18n("\\acute{}"), QString(), "acute", QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_acute", "\\acute{","}",7); - (void) new KileAction::Tag(i18n("\\grave{}"), QString(), "grave", QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_grave", "\\grave{","}", 7); - (void) new KileAction::Tag(i18n("\\tilde{}"), QString(), "tilde", QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_tilde", "\\tilde{","}", 7); - (void) new KileAction::Tag(i18n("\\bar{}"), QString(), "bar", QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_bar", "\\bar{","}", 5); - (void) new KileAction::Tag(i18n("\\vec{}"), QString(), "vec", QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_vec", "\\vec{","}", 5); - (void) new KileAction::Tag(i18n("\\hat{}"), QString(), "hat", QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_hat", "\\hat{","}", 5); - (void) new KileAction::Tag(i18n("\\check{}"), QString(), "check", QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_check", "\\check{","}", 7); - (void) new KileAction::Tag(i18n("\\breve{}"), QString(), "breve", QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_breve", "\\breve{","}", 7); - (void) new KileAction::Tag(i18n("\\dot{}"), QString(), "dot", QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_dot", "\\dot{","}", 5); - (void) new KileAction::Tag(i18n("\\ddot{}"), QString(), "ddot", QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_ddot", "\\ddot{","}", 6); - - (void) new KileAction::Tag(i18n("Small Space"), QString(), "thinspace", QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_space_small", "\\,", QString(), 2); - (void) new KileAction::Tag(i18n("Medium Space"), QString(), "medspace", QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_space_medium", "\\:", QString(),2); - (void) new KileAction::Tag(i18n("Large Space"), QString(), "bigspace", QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_space_large", "\\;", QString(),2); - (void) new KileAction::Tag(i18n("\\quad"), QString(), "quad", QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_quad", "\\quad ", QString(), 6); - (void) new KileAction::Tag(i18n("\\qquad"), QString(), "qquad", QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_qquad", "\\qquad ", QString(), 7); - - (void) new KileAction::Tag(i18n("Math Mode - $...$"), i18n("Math Mode"), "mathmode", QKeySequence(Qt::ALT+Qt::SHIFT+Qt::Key_M), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_mathmode","$","$",1); - (void) new KileAction::Tag(i18n("Displaymath Mode - \\[...\\]"), i18n("Displaymath Mode"), "displaymathmode", QKeySequence(Qt::ALT+Qt::SHIFT+Qt::Key_E), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_equation", "\\[","\\]", 2); - (void) new KileAction::Tag(i18n("Equation - \\begin{equation}"), i18n("Equation"), "equation", QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_env_equation","\\begin{equation}\n","%E\n\\end{equation} ",0,1); - (void) new KileAction::Tag(i18n("Subscript - _{}"), i18n("Subscript"), "format-text-subscript", QKeySequence(Qt::ALT+Qt::SHIFT+Qt::Key_D), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_subscript","_{","}",2); - (void) new KileAction::Tag(i18n("Superscript - ^{}"), i18n("Superscript"), "format-text-superscript", QKeySequence(Qt::ALT+Qt::SHIFT+Qt::Key_U), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_superscript","^{","}",2); - (void) new KileAction::Tag(i18n("Normal Fraction - \\frac{}{}"), i18n("Normal Fraction"), "smallfrac", QKeySequence(Qt::ALT+Qt::SHIFT+Qt::Key_F), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_frac", "\\frac{","}{}",6); - (void) new KileAction::Tag(i18n("Displaystyle Fraction - \\dfrac{}{}"), i18n("Displaystyle Fraction"), "dfrac", QKeySequence(Qt::ALT+Qt::SHIFT+Qt::Key_Q), receiver, SLOT(insertAmsTag(const KileAction::TagData&)), actionCollection,"tag_dfrac", "\\dfrac{","}{}", 7); - (void) new KileAction::Tag(i18n("Textstyle Fraction - \\tfrac{}{}"), i18n("Textstyle Fraction"), QKeySequence(), receiver, SLOT(insertAmsTag(const KileAction::TagData&)), actionCollection, "tag_tfrac", "\\tfrac{", "}{}", 7); - (void) new KileAction::Tag(i18n("Square Root - \\sqrt{}"), i18n("Square Root"), "sqrt", QKeySequence(Qt::ALT+Qt::SHIFT+Qt::Key_S), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_sqrt", "\\sqrt{","}", 6); - (void) new KileAction::Tag(i18n("\\left"), QString(), QKeySequence(Qt::ALT+Qt::SHIFT+Qt::Key_L), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_left", "\\left", QString(), 5); - (void) new KileAction::Tag(i18n("\\right"), QString(), QKeySequence(Qt::ALT+Qt::SHIFT+Qt::Key_R), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_right", "\\right", QString(), 6); - (void) new KileAction::Tag(i18n("Array - \\begin{array}"), i18n("Array"), "array", QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_env_array", "\\begin{array}{}\n", "%E\n\\end{array}", 14, 0, - i18n("\\begin{array}{col1col2...coln}\ncolumn 1 entry & column 2 entry ... & column n entry \\\\ \n...\n\\end{array}\nEach column, coln, is specified by a single letter that tells how items in that column should be formatted.\n" - " c -- for centered \n l -- for flush left \n r -- for flush right\n")); - - ToolbarSelectAction *actionleft_list = new ToolbarSelectAction(i18n("Left Delimiter"), actionCollection,false); - actionCollection->addAction("left_list", actionleft_list); - actionleft_list->addAction(new KileAction::Tag(i18n("left ("), QString(), QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection, "tag_left_(", "\\left( ", QString(), 7, 0)); - actionleft_list->addAction(new KileAction::Tag(i18n("left ["), QString(), QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection, "tag_left_[", "\\left[ ", QString(), 7, 0)); - actionleft_list->addAction(new KileAction::Tag(i18n("left {"), QString(), QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection, "tag_left_{", "\\left\\lbrace ", QString(), 14, 0)); - actionleft_list->addAction(new KileAction::Tag(i18n("left <"), QString(), QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection, "tag_left_<", "\\left\\langle ", QString(), 14, 0)); - actionleft_list->addSeparator(); - actionleft_list->addAction(new KileAction::Tag(i18n("left )"), QString(), QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection, "tag_left_)", "\\left) ", QString(), 7, 0)); - actionleft_list->addAction(new KileAction::Tag(i18n("left ]"), QString(), QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection, "tag_left_]", "\\left] ", QString(), 7, 0)); - actionleft_list->addAction(new KileAction::Tag(i18n("left }"), QString(), QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection, "tag_left_}", "\\left\\rbrace ", QString(), 14, 0)); - actionleft_list->addAction(new KileAction::Tag(i18n("left >"), QString(), QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection, "tag_left_>", "\\left\\rangle ", QString(), 14, 0)); - actionleft_list->addSeparator(); - actionleft_list->addAction(new KileAction::Tag(i18n("left ."), QString(), QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection, "tag_left_.", "\\left. ", QString(), 7, 0)); - - ToolbarSelectAction *actionright_list = new ToolbarSelectAction(i18n("Right Delimiter"), actionCollection,false); - actionCollection->addAction("right_list", actionright_list); - actionright_list->addAction(new KileAction::Tag(i18n("right )"), QString(), QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection, "tag_right_)", "\\right) ", QString(), 8, 0)); - actionright_list->addAction(new KileAction::Tag(i18n("right ]"), QString(), QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection, "tag_right_]", "\\right] ", QString(), 8, 0)); - actionright_list->addAction(new KileAction::Tag(i18n("right }"), QString(), QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection, "tag_right_}", "\\right\\rbrace ", QString(), 14, 0)); - actionright_list->addAction(new KileAction::Tag(i18n("right >"), QString(), QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection, "tag_right_>", "\\right\\rangle ", QString(), 14, 0)); - actionright_list->addSeparator(); - actionright_list->addAction(new KileAction::Tag(i18n("right ("), QString(), QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection, "tag_right_(", "\\right( ", QString(), 8, 0)); - actionright_list->addAction(new KileAction::Tag(i18n("right ["), QString(), QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection, "tag_right_[", "\\right[ ", QString(), 8, 0)); - actionright_list->addAction(new KileAction::Tag(i18n("right {"), QString(), QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection, "tag_right_{", "\\right\\lbrace ", QString(), 14, 0)); - actionright_list->addAction(new KileAction::Tag(i18n("right <"), QString(), QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection, "tag_right_<", "\\right\\langle ", QString(), 14, 0)); - actionright_list->addSeparator(); - actionright_list->addAction(new KileAction::Tag(i18n("right ."), QString(), QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection, "tag_right_.", "\\right. ", QString(), 8, 0)); - - // new math tags (dani 29.01.2005) - KActionCollection* ac = actionCollection; - - (void) new KileAction::Tag(i18n("Normal Binomial - \\binom{}{}"), i18n("Normal Binomial"), "binom", QKeySequence(), receiver, SLOT(insertAmsTag(const KileAction::TagData&)), ac,"tag_binom", "\\binom{","}{}", 7); - - (void) new KileAction::Tag(i18n("Displaystyle Binomial - \\dbinom{}{}"), i18n("Displaystyle Binomial"), QKeySequence(), receiver,SLOT(insertAmsTag(const KileAction::TagData&)), ac,"tag_dbinom", "\\dbinom{","}{}", 8); - - (void) new KileAction::Tag(i18n("Textstyle Binomial - \\tbinom{}{}"), i18n("Textstyle Binomial"), QKeySequence(), receiver, SLOT(insertAmsTag(const KileAction::TagData&)), ac,"tag_tbinom", "\\tbinom{","}{}", 8); - - (void) new KileAction::Tag(i18n("N-th Root - \\sqrt[]{}"), i18n("N-th Root"), "nroot", QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), ac,"tag_nroot", "\\sqrt[]{","}", 6); - - (void) new KileAction::Tag(i18n("Left-Right () - \\left(..\\right)"), i18n("Left-Right ()"), "lr", QKeySequence(Qt::ALT+Qt::Key_ParenLeft), receiver, SLOT(insertTag(const KileAction::TagData&)), ac,"tag_leftright", "\\left( \\right)", QString(), 7); - - (void) new KileAction::Tag(i18n("Extendable Left Arrow - \\xleftarrow{}"), i18n("Extendable Left Arrow"), QKeySequence(), receiver, SLOT(insertAmsTag(const KileAction::TagData&)), ac,"tag_xleftarrow", "\\xleftarrow{","}", 12); - - (void) new KileAction::Tag(i18n("Extendable Right Arrow - \\xrightarrow{}"), i18n("Extendable Right Arrow"), QKeySequence(), receiver, SLOT(insertAmsTag(const KileAction::TagData&)), ac,"tag_xrightarrow", "\\xrightarrow{","}", 13); - - (void) new KileAction::Tag(i18n("Boxed Formula - \\boxed{}"), i18n("Boxed Formula"), QKeySequence(), receiver, SLOT(insertAmsTag(const KileAction::TagData&)), ac,"tag_boxed", "\\boxed{","}", 7); - - (void) new KileAction::Tag(i18n("bigl - \\bigl"), i18n("bigl"), QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), ac,"tag_bigl", "\\bigl",QString(), 5); - (void) new KileAction::Tag(i18n("Bigl - \\Bigl"), i18n("Bigl"), QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), ac,"tag_Bigl", "\\Bigl",QString(), 5); - (void) new KileAction::Tag(i18n("biggl - \\biggl"), i18n("biggl"), QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), ac,"tag_biggl", "\\biggl",QString(), 6); - (void) new KileAction::Tag(i18n("Biggl - \\Biggl"), i18n("Biggl"), QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), ac,"tag_Biggl", "\\Biggl",QString(), 6); - - (void) new KileAction::Tag(i18n("bigr - \\bigr"), i18n("bigr"), QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), ac,"tag_bigr", "\\bigr",QString(), 5); - (void) new KileAction::Tag(i18n("Bigr - \\Bigr"), i18n("Bigr"), QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), ac,"tag_Bigr", "\\Bigr",QString(), 5); - (void) new KileAction::Tag(i18n("biggr - \\biggr"), i18n("biggr"), QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), ac,"tag_biggr", "\\biggr",QString(), 6); - (void) new KileAction::Tag(i18n("Biggr - \\Biggr"), i18n("Biggr"), QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), ac,"tag_Biggr", "\\Biggr",QString(), 6); - - // text in mathmode - (void) new KileAction::Tag(i18n("Text in Mathmode - \\text{}"), i18n("Text in Mathmode"), QKeySequence(), receiver, SLOT(insertAmsTag(const KileAction::TagData&)), ac,"tag_text", "\\text{","}", 6); - - (void) new KileAction::Tag(i18n("Intertext - \\intertext{}"), i18n("Intertext"), QKeySequence(), receiver, SLOT(insertAmsTag(const KileAction::TagData&)), ac,"tag_intertext", "\\intertext{","}\n", 11); - - // math environments - (void) new KileAction::Tag(i18n("Displaymath - \\begin{displaymath}"), i18n("Displaymath"), QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), ac,"tag_env_displaymath","\\begin{displaymath}\n","%E\n\\end{displaymath}\n",0,1); - - (void) new KileAction::Tag(i18n("Equation (not numbered) - \\begin{equation*}"), i18n("Equation (not numbered)"), QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), ac,"tag_env_equation*","\\begin{equation*}\n","%E\n\\end{equation*}\n",0,1); - - // AMS environments - (void) new KileAction::Tag(i18n("Multline - \\begin{multline}"), i18n("Multline"), "multline", QKeySequence(), receiver, SLOT(insertAmsTag(const KileAction::TagData&)),ac,"tag_env_multline","\\begin{multline}\n","%E\n\\end{multline}\n", 0,1); - (void) new KileAction::Tag(i18n("Multline* - \\begin{multline*}"), i18n("Multline*"), QKeySequence(), receiver, SLOT(insertAmsTag(const KileAction::TagData&)),ac,"tag_env_multline*","\\begin{multline*}\n","%E\n\\end{multline*}\n", 0,1); - - (void) new KileAction::Tag(i18n("Split - \\begin{split}"), i18n("Split"), QKeySequence(), receiver, SLOT(insertAmsTag(const KileAction::TagData&)),ac,"tag_env_split","\\begin{split}\n","%E\n\\end{split}\n", 0,1); - - (void) new KileAction::Tag(i18n("Gather - \\begin{gather}"), i18n("Gather"), "gather", QKeySequence(), receiver, SLOT(insertAmsTag(const KileAction::TagData&)),ac,"tag_env_gather","\\begin{gather}\n","%E\n\\end{gather}\n", 0,1); - (void) new KileAction::Tag(i18n("Gather* - \\begin{gather*}"), i18n("Gather*"), QKeySequence(), receiver, SLOT(insertAmsTag(const KileAction::TagData&)),ac,"tag_env_gather*","\\begin{gather*}\n","%E\n\\end{gather*}\n", 0,1); - - (void) new KileAction::Tag(i18n("Align - \\begin{align}"), i18n("Align"), "align", QKeySequence(), receiver, SLOT(insertAmsTag(const KileAction::TagData&)),ac,"tag_env_align","\\begin{align}\n","%E\n\\end{align}\n", 0,1); - (void) new KileAction::Tag(i18n("Align* - \\begin{align*}"), i18n("Align*"), QKeySequence(), receiver, SLOT(insertAmsTag(const KileAction::TagData&)),ac,"tag_env_align*","\\begin{align*}\n","%E\n\\end{align*}\n", 0,1); - - (void) new KileAction::Tag(i18n("Flalign - \\begin{flalign}"), i18n("Flalign"), "flalign", QKeySequence(), receiver, SLOT(insertAmsTag(const KileAction::TagData&)),ac,"tag_env_flalign","\\begin{flalign}\n","%E\n\\end{flalign}\n", 0,1); - (void) new KileAction::Tag(i18n("Flalign* - \\begin{flalign*}"), i18n("Flalign*"), QKeySequence(), receiver, SLOT(insertAmsTag(const KileAction::TagData&)),ac,"tag_env_flalign*","\\begin{flalign*}\n","%E\n\\end{flalign*}\n", 0,1); - - (void) new KileAction::Tag(i18n("Alignat - \\begin{alignat}"), i18n("Alignat"), QKeySequence(), receiver, SLOT(insertAmsTag(const KileAction::TagData&)),ac,"tag_env_alignat","\\begin{alignat}{","}\n%E\n\\end{alignat}\n", 16,0); - (void) new KileAction::Tag(i18n("Alignat* - \\begin{alignat*}"), i18n("Alignat*"), QKeySequence(), receiver, SLOT(insertAmsTag(const KileAction::TagData&)),ac,"tag_env_alignat*","\\begin{alignat*}{","}\n%E\n\\end{alignat*}\n", 17,0); - - (void) new KileAction::Tag(i18n("Aligned - \\begin{aligned}"), i18n("Aligned"), QKeySequence(), receiver, SLOT(insertAmsTag(const KileAction::TagData&)),ac,"tag_env_aligned","\\begin{aligned}\n","%E\n\\end{aligned}\n", 0,1); - (void) new KileAction::Tag(i18n("Gathered - \\begin{gathered}"), i18n("Gathered"), QKeySequence(), receiver, SLOT(insertAmsTag(const KileAction::TagData&)),ac,"tag_env_gathered","\\begin{gathered}\n","%E\n\\end{gathered}\n", 0,1); - (void) new KileAction::Tag(i18n("Alignedat - \\begin{alignedat}"), i18n("Alignedat"), QKeySequence(), receiver, SLOT(insertAmsTag(const KileAction::TagData&)),ac,"tag_env_alignedat","\\begin{alignedat}\n","%E\n\\end{alignedat}\n", 0,1); - - (void) new KileAction::Tag(i18n("Cases - \\begin{cases}"), i18n("Cases"), "cases", QKeySequence(), receiver, SLOT(insertAmsTag(const KileAction::TagData&)),ac,"tag_env_cases","\\begin{cases}\n","%E\n\\end{cases}\n", 0,1); + (void) new KileAction::Tag(i18n("\\mathrm{}"), QString(), QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_mathrm","\\mathrm{","}",8); + (void) new KileAction::Tag(i18n("\\mathit{}"), QString(), QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_mathit","\\mathit{","}",8); + (void) new KileAction::Tag(i18n("\\mathbf{}"), QString(), QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_mathbf","\\mathbf{","}",8); + (void) new KileAction::Tag(i18n("\\mathsf{}"), QString(), QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_mathsf","\\mathsf{","}",8); + (void) new KileAction::Tag(i18n("\\mathtt{}"), QString(), QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_mathtt","\\mathtt{","}",8); + (void) new KileAction::Tag(i18n("\\mathcal{}"), QString(), QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_mathcal","\\mathcal{","}",9); + (void) new KileAction::Tag(i18n("\\mathbb{}"), QString(), QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_mathbb","\\mathbb{","}",8); + (void) new KileAction::Tag(i18n("\\mathfrak{}"), QString(), QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_mathfrak","\\mathfrak{","}",10); + + (void) new KileAction::Tag(i18n("\\acute{}"), QString(), "acute", QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_acute", "\\acute{","}",7); + (void) new KileAction::Tag(i18n("\\grave{}"), QString(), "grave", QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_grave", "\\grave{","}", 7); + (void) new KileAction::Tag(i18n("\\tilde{}"), QString(), "tilde", QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_tilde", "\\tilde{","}", 7); + (void) new KileAction::Tag(i18n("\\bar{}"), QString(), "bar", QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_bar", "\\bar{","}", 5); + (void) new KileAction::Tag(i18n("\\vec{}"), QString(), "vec", QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_vec", "\\vec{","}", 5); + (void) new KileAction::Tag(i18n("\\hat{}"), QString(), "hat", QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_hat", "\\hat{","}", 5); + (void) new KileAction::Tag(i18n("\\check{}"), QString(), "check", QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_check", "\\check{","}", 7); + (void) new KileAction::Tag(i18n("\\breve{}"), QString(), "breve", QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_breve", "\\breve{","}", 7); + (void) new KileAction::Tag(i18n("\\dot{}"), QString(), "dot", QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_dot", "\\dot{","}", 5); + (void) new KileAction::Tag(i18n("\\ddot{}"), QString(), "ddot", QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_ddot", "\\ddot{","}", 6); + + (void) new KileAction::Tag(i18n("Small Space"), QString(), "thinspace", QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_space_small", "\\,", QString(), 2); + (void) new KileAction::Tag(i18n("Medium Space"), QString(), "medspace", QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_space_medium", "\\:", QString(),2); + (void) new KileAction::Tag(i18n("Large Space"), QString(), "bigspace", QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_space_large", "\\;", QString(),2); + (void) new KileAction::Tag(i18n("\\quad"), QString(), "quad", QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_quad", "\\quad ", QString(), 6); + (void) new KileAction::Tag(i18n("\\qquad"), QString(), "qquad", QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_qquad", "\\qquad ", QString(), 7); + + (void) new KileAction::Tag(i18n("Math Mode - $...$"), i18n("Math Mode"), "mathmode", QKeySequence(Qt::ALT+Qt::SHIFT+Qt::Key_M), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_mathmode","$","$",1); + (void) new KileAction::Tag(i18n("Displaymath Mode - \\[...\\]"), i18n("Displaymath Mode"), "displaymathmode", QKeySequence(Qt::ALT+Qt::SHIFT+Qt::Key_E), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_equation", "\\[","\\]", 2); + (void) new KileAction::Tag(i18n("Equation - \\begin{equation}"), i18n("Equation"), "equation", QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_env_equation","\\begin{equation}\n","%E\n\\end{equation} ",0,1); + (void) new KileAction::Tag(i18n("Subscript - _{}"), i18n("Subscript"), "format-text-subscript", QKeySequence(Qt::ALT+Qt::SHIFT+Qt::Key_D), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_subscript","_{","}",2); + (void) new KileAction::Tag(i18n("Superscript - ^{}"), i18n("Superscript"), "format-text-superscript", QKeySequence(Qt::ALT+Qt::SHIFT+Qt::Key_U), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_superscript","^{","}",2); + (void) new KileAction::Tag(i18n("Normal Fraction - \\frac{}{}"), i18n("Normal Fraction"), "smallfrac", QKeySequence(Qt::ALT+Qt::SHIFT+Qt::Key_F), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_frac", "\\frac{","}{}",6); + (void) new KileAction::Tag(i18n("Displaystyle Fraction - \\dfrac{}{}"), i18n("Displaystyle Fraction"), "dfrac", QKeySequence(Qt::ALT+Qt::SHIFT+Qt::Key_Q), receiver, SLOT(insertAmsTag(const KileAction::TagData&)), actionCollection,"tag_dfrac", "\\dfrac{","}{}", 7); + (void) new KileAction::Tag(i18n("Textstyle Fraction - \\tfrac{}{}"), i18n("Textstyle Fraction"), QKeySequence(), receiver, SLOT(insertAmsTag(const KileAction::TagData&)), actionCollection, "tag_tfrac", "\\tfrac{", "}{}", 7); + (void) new KileAction::Tag(i18n("Square Root - \\sqrt{}"), i18n("Square Root"), "sqrt", QKeySequence(Qt::ALT+Qt::SHIFT+Qt::Key_S), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_sqrt", "\\sqrt{","}", 6); + (void) new KileAction::Tag(i18n("\\left"), QString(), QKeySequence(Qt::ALT+Qt::SHIFT+Qt::Key_L), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_left", "\\left", QString(), 5); + (void) new KileAction::Tag(i18n("\\right"), QString(), QKeySequence(Qt::ALT+Qt::SHIFT+Qt::Key_R), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_right", "\\right", QString(), 6); + (void) new KileAction::Tag(i18n("Array - \\begin{array}"), i18n("Array"), "array", QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection,"tag_env_array", "\\begin{array}{}\n", "%E\n\\end{array}", 14, 0, + i18n("\\begin{array}{col1col2...coln}\ncolumn 1 entry & column 2 entry ... & column n entry \\\\ \n...\n\\end{array}\nEach column, coln, is specified by a single letter that tells how items in that column should be formatted.\n" + " c -- for centered \n l -- for flush left \n r -- for flush right\n")); + + ToolbarSelectAction *actionleft_list = new ToolbarSelectAction(i18n("Left Delimiter"), actionCollection,false); + actionCollection->addAction("left_list", actionleft_list); + actionleft_list->addAction(new KileAction::Tag(i18n("left ("), QString(), QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection, "tag_left_(", "\\left( ", QString(), 7, 0)); + actionleft_list->addAction(new KileAction::Tag(i18n("left ["), QString(), QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection, "tag_left_[", "\\left[ ", QString(), 7, 0)); + actionleft_list->addAction(new KileAction::Tag(i18n("left {"), QString(), QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection, "tag_left_{", "\\left\\lbrace ", QString(), 14, 0)); + actionleft_list->addAction(new KileAction::Tag(i18n("left <"), QString(), QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection, "tag_left_<", "\\left\\langle ", QString(), 14, 0)); + actionleft_list->addSeparator(); + actionleft_list->addAction(new KileAction::Tag(i18n("left )"), QString(), QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection, "tag_left_)", "\\left) ", QString(), 7, 0)); + actionleft_list->addAction(new KileAction::Tag(i18n("left ]"), QString(), QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection, "tag_left_]", "\\left] ", QString(), 7, 0)); + actionleft_list->addAction(new KileAction::Tag(i18n("left }"), QString(), QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection, "tag_left_}", "\\left\\rbrace ", QString(), 14, 0)); + actionleft_list->addAction(new KileAction::Tag(i18n("left >"), QString(), QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection, "tag_left_>", "\\left\\rangle ", QString(), 14, 0)); + actionleft_list->addSeparator(); + actionleft_list->addAction(new KileAction::Tag(i18n("left ."), QString(), QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection, "tag_left_.", "\\left. ", QString(), 7, 0)); + + ToolbarSelectAction *actionright_list = new ToolbarSelectAction(i18n("Right Delimiter"), actionCollection,false); + actionCollection->addAction("right_list", actionright_list); + actionright_list->addAction(new KileAction::Tag(i18n("right )"), QString(), QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection, "tag_right_)", "\\right) ", QString(), 8, 0)); + actionright_list->addAction(new KileAction::Tag(i18n("right ]"), QString(), QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection, "tag_right_]", "\\right] ", QString(), 8, 0)); + actionright_list->addAction(new KileAction::Tag(i18n("right }"), QString(), QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection, "tag_right_}", "\\right\\rbrace ", QString(), 14, 0)); + actionright_list->addAction(new KileAction::Tag(i18n("right >"), QString(), QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection, "tag_right_>", "\\right\\rangle ", QString(), 14, 0)); + actionright_list->addSeparator(); + actionright_list->addAction(new KileAction::Tag(i18n("right ("), QString(), QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection, "tag_right_(", "\\right( ", QString(), 8, 0)); + actionright_list->addAction(new KileAction::Tag(i18n("right ["), QString(), QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection, "tag_right_[", "\\right[ ", QString(), 8, 0)); + actionright_list->addAction(new KileAction::Tag(i18n("right {"), QString(), QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection, "tag_right_{", "\\right\\lbrace ", QString(), 14, 0)); + actionright_list->addAction(new KileAction::Tag(i18n("right <"), QString(), QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection, "tag_right_<", "\\right\\langle ", QString(), 14, 0)); + actionright_list->addSeparator(); + actionright_list->addAction(new KileAction::Tag(i18n("right ."), QString(), QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), actionCollection, "tag_right_.", "\\right. ", QString(), 8, 0)); + + // new math tags (dani 29.01.2005) + KActionCollection* ac = actionCollection; + + (void) new KileAction::Tag(i18n("Normal Binomial - \\binom{}{}"), i18n("Normal Binomial"), "binom", QKeySequence(), receiver, SLOT(insertAmsTag(const KileAction::TagData&)), ac,"tag_binom", "\\binom{","}{}", 7); + + (void) new KileAction::Tag(i18n("Displaystyle Binomial - \\dbinom{}{}"), i18n("Displaystyle Binomial"), QKeySequence(), receiver,SLOT(insertAmsTag(const KileAction::TagData&)), ac,"tag_dbinom", "\\dbinom{","}{}", 8); + + (void) new KileAction::Tag(i18n("Textstyle Binomial - \\tbinom{}{}"), i18n("Textstyle Binomial"), QKeySequence(), receiver, SLOT(insertAmsTag(const KileAction::TagData&)), ac,"tag_tbinom", "\\tbinom{","}{}", 8); + + (void) new KileAction::Tag(i18n("N-th Root - \\sqrt[]{}"), i18n("N-th Root"), "nroot", QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), ac,"tag_nroot", "\\sqrt[]{","}", 6); + + (void) new KileAction::Tag(i18n("Left-Right () - \\left(..\\right)"), i18n("Left-Right ()"), "lr", QKeySequence(Qt::ALT+Qt::Key_ParenLeft), receiver, SLOT(insertTag(const KileAction::TagData&)), ac,"tag_leftright", "\\left( \\right)", QString(), 7); + + (void) new KileAction::Tag(i18n("Extendable Left Arrow - \\xleftarrow{}"), i18n("Extendable Left Arrow"), QKeySequence(), receiver, SLOT(insertAmsTag(const KileAction::TagData&)), ac,"tag_xleftarrow", "\\xleftarrow{","}", 12); + + (void) new KileAction::Tag(i18n("Extendable Right Arrow - \\xrightarrow{}"), i18n("Extendable Right Arrow"), QKeySequence(), receiver, SLOT(insertAmsTag(const KileAction::TagData&)), ac,"tag_xrightarrow", "\\xrightarrow{","}", 13); + + (void) new KileAction::Tag(i18n("Boxed Formula - \\boxed{}"), i18n("Boxed Formula"), QKeySequence(), receiver, SLOT(insertAmsTag(const KileAction::TagData&)), ac,"tag_boxed", "\\boxed{","}", 7); + + (void) new KileAction::Tag(i18n("bigl - \\bigl"), i18n("bigl"), QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), ac,"tag_bigl", "\\bigl",QString(), 5); + (void) new KileAction::Tag(i18n("Bigl - \\Bigl"), i18n("Bigl"), QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), ac,"tag_Bigl", "\\Bigl",QString(), 5); + (void) new KileAction::Tag(i18n("biggl - \\biggl"), i18n("biggl"), QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), ac,"tag_biggl", "\\biggl",QString(), 6); + (void) new KileAction::Tag(i18n("Biggl - \\Biggl"), i18n("Biggl"), QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), ac,"tag_Biggl", "\\Biggl",QString(), 6); + + (void) new KileAction::Tag(i18n("bigr - \\bigr"), i18n("bigr"), QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), ac,"tag_bigr", "\\bigr",QString(), 5); + (void) new KileAction::Tag(i18n("Bigr - \\Bigr"), i18n("Bigr"), QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), ac,"tag_Bigr", "\\Bigr",QString(), 5); + (void) new KileAction::Tag(i18n("biggr - \\biggr"), i18n("biggr"), QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), ac,"tag_biggr", "\\biggr",QString(), 6); + (void) new KileAction::Tag(i18n("Biggr - \\Biggr"), i18n("Biggr"), QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), ac,"tag_Biggr", "\\Biggr",QString(), 6); + + // text in mathmode + (void) new KileAction::Tag(i18n("Text in Mathmode - \\text{}"), i18n("Text in Mathmode"), QKeySequence(), receiver, SLOT(insertAmsTag(const KileAction::TagData&)), ac,"tag_text", "\\text{","}", 6); + + (void) new KileAction::Tag(i18n("Intertext - \\intertext{}"), i18n("Intertext"), QKeySequence(), receiver, SLOT(insertAmsTag(const KileAction::TagData&)), ac,"tag_intertext", "\\intertext{","}\n", 11); + + // math environments + (void) new KileAction::Tag(i18n("Displaymath - \\begin{displaymath}"), i18n("Displaymath"), QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), ac,"tag_env_displaymath","\\begin{displaymath}\n","%E\n\\end{displaymath}\n",0,1); + + (void) new KileAction::Tag(i18n("Equation (not numbered) - \\begin{equation*}"), i18n("Equation (not numbered)"), QKeySequence(), receiver, SLOT(insertTag(const KileAction::TagData&)), ac,"tag_env_equation*","\\begin{equation*}\n","%E\n\\end{equation*}\n",0,1); + + // AMS environments + (void) new KileAction::Tag(i18n("Multline - \\begin{multline}"), i18n("Multline"), "multline", QKeySequence(), receiver, SLOT(insertAmsTag(const KileAction::TagData&)),ac,"tag_env_multline","\\begin{multline}\n","%E\n\\end{multline}\n", 0,1); + (void) new KileAction::Tag(i18n("Multline* - \\begin{multline*}"), i18n("Multline*"), QKeySequence(), receiver, SLOT(insertAmsTag(const KileAction::TagData&)),ac,"tag_env_multline*","\\begin{multline*}\n","%E\n\\end{multline*}\n", 0,1); + + (void) new KileAction::Tag(i18n("Split - \\begin{split}"), i18n("Split"), QKeySequence(), receiver, SLOT(insertAmsTag(const KileAction::TagData&)),ac,"tag_env_split","\\begin{split}\n","%E\n\\end{split}\n", 0,1); + + (void) new KileAction::Tag(i18n("Gather - \\begin{gather}"), i18n("Gather"), "gather", QKeySequence(), receiver, SLOT(insertAmsTag(const KileAction::TagData&)),ac,"tag_env_gather","\\begin{gather}\n","%E\n\\end{gather}\n", 0,1); + (void) new KileAction::Tag(i18n("Gather* - \\begin{gather*}"), i18n("Gather*"), QKeySequence(), receiver, SLOT(insertAmsTag(const KileAction::TagData&)),ac,"tag_env_gather*","\\begin{gather*}\n","%E\n\\end{gather*}\n", 0,1); + + (void) new KileAction::Tag(i18n("Align - \\begin{align}"), i18n("Align"), "align", QKeySequence(), receiver, SLOT(insertAmsTag(const KileAction::TagData&)),ac,"tag_env_align","\\begin{align}\n","%E\n\\end{align}\n", 0,1); + (void) new KileAction::Tag(i18n("Align* - \\begin{align*}"), i18n("Align*"), QKeySequence(), receiver, SLOT(insertAmsTag(const KileAction::TagData&)),ac,"tag_env_align*","\\begin{align*}\n","%E\n\\end{align*}\n", 0,1); + + (void) new KileAction::Tag(i18n("Flalign - \\begin{flalign}"), i18n("Flalign"), "flalign", QKeySequence(), receiver, SLOT(insertAmsTag(const KileAction::TagData&)),ac,"tag_env_flalign","\\begin{flalign}\n","%E\n\\end{flalign}\n", 0,1); + (void) new KileAction::Tag(i18n("Flalign* - \\begin{flalign*}"), i18n("Flalign*"), QKeySequence(), receiver, SLOT(insertAmsTag(const KileAction::TagData&)),ac,"tag_env_flalign*","\\begin{flalign*}\n","%E\n\\end{flalign*}\n", 0,1); + + (void) new KileAction::Tag(i18n("Alignat - \\begin{alignat}"), i18n("Alignat"), QKeySequence(), receiver, SLOT(insertAmsTag(const KileAction::TagData&)),ac,"tag_env_alignat","\\begin{alignat}{","}\n%E\n\\end{alignat}\n", 16,0); + (void) new KileAction::Tag(i18n("Alignat* - \\begin{alignat*}"), i18n("Alignat*"), QKeySequence(), receiver, SLOT(insertAmsTag(const KileAction::TagData&)),ac,"tag_env_alignat*","\\begin{alignat*}{","}\n%E\n\\end{alignat*}\n", 17,0); + + (void) new KileAction::Tag(i18n("Aligned - \\begin{aligned}"), i18n("Aligned"), QKeySequence(), receiver, SLOT(insertAmsTag(const KileAction::TagData&)),ac,"tag_env_aligned","\\begin{aligned}\n","%E\n\\end{aligned}\n", 0,1); + (void) new KileAction::Tag(i18n("Gathered - \\begin{gathered}"), i18n("Gathered"), QKeySequence(), receiver, SLOT(insertAmsTag(const KileAction::TagData&)),ac,"tag_env_gathered","\\begin{gathered}\n","%E\n\\end{gathered}\n", 0,1); + (void) new KileAction::Tag(i18n("Alignedat - \\begin{alignedat}"), i18n("Alignedat"), QKeySequence(), receiver, SLOT(insertAmsTag(const KileAction::TagData&)),ac,"tag_env_alignedat","\\begin{alignedat}\n","%E\n\\end{alignedat}\n", 0,1); + + (void) new KileAction::Tag(i18n("Cases - \\begin{cases}"), i18n("Cases"), "cases", QKeySequence(), receiver, SLOT(insertAmsTag(const KileAction::TagData&)),ac,"tag_env_cases","\\begin{cases}\n","%E\n\\end{cases}\n", 0,1); - (void) new KileAction::Tag(i18n("matrix - \\begin{matrix}"), i18n("matrix"), "matrix", QKeySequence(), receiver, SLOT(insertAmsTag(const KileAction::TagData&)),ac,"tag_env_matrix","\\begin{matrix}\n","%E\n\\end{matrix}\n", 0,1); - (void) new KileAction::Tag(i18n("pmatrix - \\begin{pmatrix}"), i18n("pmatrix"), "pmatrix", QKeySequence(), receiver, SLOT(insertAmsTag(const KileAction::TagData&)),ac,"tag_env_pmatrix","\\begin{pmatrix}\n","%E\n\\end{pmatrix}\n", 0,1); - (void) new KileAction::Tag(i18n("vmatrix - \\begin{vmatrix}"), i18n("vmatrix"), "vmatrix", QKeySequence(), receiver, SLOT(insertAmsTag(const KileAction::TagData&)),ac,"tag_env_vmatrix","\\begin{vmatrix}\n","%E\n\\end{vmatrix}\n", 0,1); - (void) new KileAction::Tag(i18n("Vmatrix - \\begin{Vmatrix}"), i18n("Vmatrix"), "VVmatrix", QKeySequence(), receiver, SLOT(insertAmsTag(const KileAction::TagData&)),ac,"tag_env_VVmatrix","\\begin{Vmatrix}\n","%E\n\\end{Vmatrix}\n", 0,1); - (void) new KileAction::Tag(i18n("bmatrix - \\begin{bmatrix}"), i18n("bmatrix"), "bmatrix", QKeySequence(), receiver, SLOT(insertAmsTag(const KileAction::TagData&)),ac,"tag_env_bmatrix","\\begin{bmatrix}\n","%E\n\\end{bmatrix}\n", 0,1); - (void) new KileAction::Tag(i18n("Bmatrix - \\begin{Bmatrix}"), i18n("Bmatrix"), "BBmatrix", QKeySequence(), receiver, SLOT(insertAmsTag(const KileAction::TagData&)),ac,"tag_env_BBmatrix","\\begin{Bmatrix}\n","%E\n\\end{Bmatrix}\n", 0,1); + (void) new KileAction::Tag(i18n("matrix - \\begin{matrix}"), i18n("matrix"), "matrix", QKeySequence(), receiver, SLOT(insertAmsTag(const KileAction::TagData&)),ac,"tag_env_matrix","\\begin{matrix}\n","%E\n\\end{matrix}\n", 0,1); + (void) new KileAction::Tag(i18n("pmatrix - \\begin{pmatrix}"), i18n("pmatrix"), "pmatrix", QKeySequence(), receiver, SLOT(insertAmsTag(const KileAction::TagData&)),ac,"tag_env_pmatrix","\\begin{pmatrix}\n","%E\n\\end{pmatrix}\n", 0,1); + (void) new KileAction::Tag(i18n("vmatrix - \\begin{vmatrix}"), i18n("vmatrix"), "vmatrix", QKeySequence(), receiver, SLOT(insertAmsTag(const KileAction::TagData&)),ac,"tag_env_vmatrix","\\begin{vmatrix}\n","%E\n\\end{vmatrix}\n", 0,1); + (void) new KileAction::Tag(i18n("Vmatrix - \\begin{Vmatrix}"), i18n("Vmatrix"), "VVmatrix", QKeySequence(), receiver, SLOT(insertAmsTag(const KileAction::TagData&)),ac,"tag_env_VVmatrix","\\begin{Vmatrix}\n","%E\n\\end{Vmatrix}\n", 0,1); + (void) new KileAction::Tag(i18n("bmatrix - \\begin{bmatrix}"), i18n("bmatrix"), "bmatrix", QKeySequence(), receiver, SLOT(insertAmsTag(const KileAction::TagData&)),ac,"tag_env_bmatrix","\\begin{bmatrix}\n","%E\n\\end{bmatrix}\n", 0,1); + (void) new KileAction::Tag(i18n("Bmatrix - \\begin{Bmatrix}"), i18n("Bmatrix"), "BBmatrix", QKeySequence(), receiver, SLOT(insertAmsTag(const KileAction::TagData&)),ac,"tag_env_BBmatrix","\\begin{Bmatrix}\n","%E\n\\end{Bmatrix}\n", 0,1); } } diff --git a/src/kilestdactions.h b/src/kilestdactions.h index 13c15ea4..598c86e4 100644 --- a/src/kilestdactions.h +++ b/src/kilestdactions.h @@ -1,37 +1,37 @@ // // // C++ Interface: kilestdactions // -// Description: +// Description: // // // Author: Jeroen Wijnhout , (C) 2003 /*************************************************************************** * * * 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. * * * ***************************************************************************/ #ifndef KILESTDACTIONS_H #define KILESTDACTIONS_H #include #include #include #include "kileinfo.h" namespace KileStdActions { - void setupStdTags(KileInfo *ki, const QObject *receiver, KActionCollection *actionCollection, QWidget *parentWidget); - void setupBibTags(const QObject *receiver, KActionCollection *actionCollection,KActionMenu* menu); - void setupMathTags(const QObject *receiver, KActionCollection *actionCollection); +void setupStdTags(KileInfo *ki, const QObject *receiver, KActionCollection *actionCollection, QWidget *parentWidget); +void setupBibTags(const QObject *receiver, KActionCollection *actionCollection,KActionMenu* menu); +void setupMathTags(const QObject *receiver, KActionCollection *actionCollection); } #endif diff --git a/src/kilestdtools.cpp b/src/kilestdtools.cpp index a031223c..883b0378 100644 --- a/src/kilestdtools.cpp +++ b/src/kilestdtools.cpp @@ -1,823 +1,823 @@ /************************************************************************************** begin : Thu Nov 27 2003 copyright : (C) 2003 by Jeroen Wijnhout (Jeroen.Wijnhout@kdemail.net) (C) 2011-2017 by Michel Ludwig (michel.ludwig@kdemail.net) **************************************************************************************/ /*************************************************************************** * * * 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. * * * ***************************************************************************/ #include "kilestdtools.h" #include #include #include #include #include #include #include #include #include "dialogs/listselector.h" #include "kileconfig.h" #include "kiletool.h" #include "kiletoolmanager.h" #include "kiletool_enums.h" #include "kileinfo.h" #include "kiledocmanager.h" #include "documentinfo.h" #include "outputinfo.h" #include "parser/parsermanager.h" #include "utilities.h" #define SHORTCUTS_GROUP_NAME "Shortcuts" namespace KileTool { - Factory::Factory(Manager *mngr, KConfig *config, KActionCollection *actionCollection) - : m_manager(mngr), m_config(config), m_actionCollection(actionCollection) - { - m_standardToolConfigurationFileName = QStandardPaths::locate(QStandardPaths::DataLocation, "kilestdtools.rc"); - } - - Factory::~Factory() - { - } - - Base* Factory::create(const QString& toolName, const QString& config, bool prepare /* = true */) - { - KILE_DEBUG_MAIN << toolName << config << prepare; - KileTool::Base *tool = Q_NULLPTR; - //perhaps we can find the tool in the config file - if (m_config->hasGroup(groupFor(toolName, m_config))) { - KConfigGroup configGroup = m_config->group(groupFor(toolName, m_config)); - QString toolClass = configGroup.readEntry("class", QString()); - - if(toolClass == "LaTeX") { - tool = new LaTeX(toolName, m_manager, prepare); - } - else if(toolClass == "LaTeXpreview") { - tool = new PreviewLaTeX(toolName, m_manager, prepare); - } - else if(toolClass == "LaTeXLivePreview") { - tool = new LivePreviewLaTeX(toolName, m_manager, prepare); - } - else if(toolClass == "ForwardDVI") { - tool = new ForwardDVI(toolName, m_manager, prepare); - } - else if(toolClass == "ViewHTML") { - tool = new ViewHTML(toolName, m_manager, prepare); - } - else if(toolClass == "ViewBib") { - tool = new ViewBib(toolName, m_manager, prepare); - } - else if(toolClass == "Base") { - tool = new Base(toolName, m_manager, prepare); - } - else if(toolClass == "Compile") { - tool = new Compile(toolName, m_manager, prepare); - } - else if (BibliographyCompile::ToolClass == toolClass) { - tool = new BibliographyCompile(toolName, m_manager, prepare); - } - else if(toolClass == "Convert") { - tool = new Convert(toolName, m_manager, prepare); - } - else if(toolClass == "Archive") { - tool = new Archive(toolName, m_manager, prepare); - } - else if(toolClass == "View") { - tool = new View(toolName, m_manager, prepare); - } - else if(toolClass == "Sequence") { - tool = new Sequence(toolName, m_manager, prepare); - } - } - if(!tool) { - return Q_NULLPTR; - } - - if(!m_manager->configure(tool, config)) { - delete tool; - return Q_NULLPTR; - } - tool->setToolConfig(config); - - // this has to be done after the configuration step only! - if(dynamic_cast(tool)) { - dynamic_cast(tool)->setupSequenceTools(); - } - - return tool; - } - - void Factory::resetToolConfigurations() - { - KConfig stdToolConfig(m_standardToolConfigurationFileName, KConfig::NoGlobals); - - m_config->deleteGroup(QLatin1String("Tools")); - m_config->deleteGroup(QLatin1String("ToolsGUI")); - - // we delete all the groups whose names start with "Tool/"; - for(QString groupName : m_config->groupList()) { - if(groupName.startsWith(QLatin1String("Tool/"))) { - m_config->deleteGroup(groupName); - } - } - - // now we copy all the "Tool/" groups, the "Tools", and "ToolsGUI" groups over - for(QString groupName : stdToolConfig.groupList()) { - if(groupName != SHORTCUTS_GROUP_NAME) { - KConfigGroup configGroup = stdToolConfig.group(groupName); - m_config->deleteGroup(groupName); - KConfigGroup newGroup = m_config->group(groupName); - configGroup.copyTo(&newGroup, KConfigGroup::Persistent); - } - } - } - - static void transferKeyStringPairsStartingWith(KConfigGroup& src, KConfigGroup& target, const QString& startsWith) - { - const QStringList keyList = src.keyList(); - for(QString key : keyList) { - if(key.startsWith(startsWith)) { - QString value = src.readEntry(key, QString()); - target.writeEntry(key, value); - } - } - } - - void Factory::installStandardLivePreviewTools() - { - KConfig stdToolConfig(m_standardToolConfigurationFileName, KConfig::NoGlobals); - - const QStringList groupList = stdToolConfig.groupList(); - for(QString groupName : groupList) { - if(groupName.startsWith(QStringLiteral("Tool/LivePreview"))) { - KConfigGroup configGroup = stdToolConfig.group(groupName); - m_config->deleteGroup(groupName); - KConfigGroup newGroup = m_config->group(groupName); - configGroup.copyTo(&newGroup, KConfigGroup::Persistent); - } - } - - { // transfer the standard settings inside the "Tools" group - const QString groupName(QStringLiteral("Tools")); - KConfigGroup stdConfigGroup = stdToolConfig.group(groupName); - KConfigGroup newGroup = m_config->group(groupName); - transferKeyStringPairsStartingWith(stdConfigGroup, newGroup, QStringLiteral("LivePreview")); - } - - { // transfer the standard settings inside the "ToolsGUI" group - const QString groupName(QStringLiteral("ToolsGUI")); - KConfigGroup stdConfigGroup = stdToolConfig.group(groupName); - KConfigGroup newGroup = m_config->group(groupName); - transferKeyStringPairsStartingWith(stdConfigGroup, newGroup, QStringLiteral("LivePreview")); - } - } - - /////////////// LaTeX //////////////// - - LaTeX::LaTeX(const QString& tool, Manager *mngr, bool prepare) - : Compile(tool, mngr, prepare), m_latexOutputHandler(Q_NULLPTR) - { - } - - LaTeX::~LaTeX() - { - } - - void LaTeX::setupAsChildTool(KileTool::Base *child) - { - KileTool::LaTeX *latexChild = dynamic_cast(child); - if(latexChild) { - latexChild->setLaTeXOutputHandler(latexOutputHandler()); - } - } - - LaTeXOutputHandler* LaTeX::latexOutputHandler() - { - return m_latexOutputHandler; - } - - void LaTeX::setLaTeXOutputHandler(LaTeXOutputHandler *h) - { - m_latexOutputHandler = h; - } - - bool LaTeX::determineSource() - { - QString src = source(); - - // check whether the source has been set already - if(!src.isEmpty()) { - return true; - } - - //the basedir is determined from the current compile target - //determined by getCompileName() - LaTeXOutputHandler *h = Q_NULLPTR; - src = m_ki->getCompileName(false, &h); - - setSource(src); - setLaTeXOutputHandler(h); - - return true; - } - - int LaTeX::m_reRun = 0; - - // FIXME don't hardcode bbl and ind suffix here. - bool LaTeX::updateBibs(bool checkOnlyBibDependencies) - { - KileDocument::TextInfo *docinfo = manager()->info()->docManager()->textInfoFor(source()); - if(docinfo) { - QFileInfo fileinfo(docinfo->url().toLocalFile()); - QStringList dependencies; - - if (checkOnlyBibDependencies) { - dependencies = manager()->info()->allBibliographies(docinfo); - } - else { - dependencies = manager()->info()->allDependencies(docinfo); - dependencies.append(fileinfo.fileName()); - } - if (!dependencies.empty()) { - return needsUpdate(targetDir() + '/' + S() + ".bbl", - KileUtilities::lastModifiedFile(dependencies, fileinfo.absolutePath())); - } - } - - return false; - } - - bool LaTeX::updateIndex() - { - KileDocument::TextInfo *docinfo = manager()->info()->docManager()->textInfoFor(source()); - if(docinfo) { - QStringList pckgs = manager()->info()->allPackages(docinfo); - if(pckgs.contains("makeidx") || pckgs.contains("imakeidx") || pckgs.contains("splitidx")) { - return needsUpdate(targetDir() + '/' + S() + ".ind", manager()->info()->lastModifiedFile(docinfo)); - } - } - - return false; - } - - bool LaTeX::updateAsy() - { - KileDocument::TextInfo *docinfo = manager()->info()->docManager()->textInfoFor(source()); - if(docinfo) { - QStringList pckgs = manager()->info()->allPackages(docinfo); - // As asymptote doesn't properly notify the user when it needs to be rerun, we run - // it every time LaTeX is run (but only for m_reRun == 0 if LaTeX has to be rerun). - if(pckgs.contains("asymptote")) { - return true; - } - } - return false; - } - - bool LaTeX::finish(int r) - { - KILE_DEBUG_MAIN << "==bool LaTeX::finish(" << r << ")====="; - - m_toolResult = r; - - if(m_toolResult == AbnormalExit || m_toolResult == Aborted) { - return false; - } - - // in case the compilation failed, we try to parse the log file in order to detect - // errors reported by LaTeX - QString log = targetDir() + '/' + S() + ".log"; - manager()->parserManager()->parseOutput(this, log, source()); - - return true; - } - - void LaTeX::latexOutputParserResultInstalled() - { - KILE_DEBUG_MAIN; - - if(m_latexOutputHandler) { - m_latexOutputHandler->storeLaTeXOutputParserResult(m_nErrors, m_nWarnings, m_nBadBoxes, m_latexOutputInfoList, - m_logFile); - } - - checqCriticals(); - - if(readEntry("autoRun") == "yes") { - checkAutoRun(); - } - - Compile::finish(m_toolResult); - } - - void LaTeX::checqCriticals() - { - // work around the 0 cases as the i18np call can cause some confusion when 0 is passed to it (#275700) - QString es = (m_nErrors == 0 ? i18n("0 errors") : i18np("1 error", "%1 errors", m_nErrors)); - QString ws = (m_nWarnings == 0 ? i18n("0 warnings") : i18np("1 warning", "%1 warnings", m_nWarnings)); - QString bs = (m_nBadBoxes == 0 ? i18n("0 badboxes") : i18np("1 badbox", "%1 badboxes", m_nBadBoxes)); - - sendMessage(Info, i18nc("String displayed in the log panel showing the number of errors/warnings/badboxes", - "%1, %2, %3", es, ws, bs)); - - // jump to first error - if(!isPartOfLivePreview() && m_nErrors > 0 && (readEntry("jumpToFirstError") == "yes")) { - connect(this, SIGNAL(jumpToFirstError()), manager(), SIGNAL(jumpToFirstError())); - emit(jumpToFirstError()); - } - } - - void LaTeX::configureLaTeX(KileTool::Base *tool, const QString& source) - { - tool->setSource(source, workingDir()); - } - - void LaTeX::configureBibTeX(KileTool::Base *tool, const QString& source) - { - tool->setSource(source, workingDir()); - } - - void LaTeX::configureMakeIndex(KileTool::Base *tool, const QString& source) - { - tool->setSource(source, workingDir()); - } - - void LaTeX::configureAsymptote(KileTool::Base *tool, const QString& source) - { - tool->setSource(source, workingDir()); - } - - // if 'Biblatex' is not used in the document, 'hint' will be empty - ToolConfigPair LaTeX::determineBibliographyBackend(const QString& hint) - { - if(m_latexOutputHandler) { - ToolConfigPair userBibTool = m_latexOutputHandler->bibliographyBackendToolUserOverride(); - - if(userBibTool.isValid()) { - // now we still check whether such a tool really exists - if (manager()->containsBibliographyTool(userBibTool)) { - return userBibTool; - } - else { - KILE_DEBUG_MAIN << "Cannot find the following bibtool set by the user:" << userBibTool; - KILE_DEBUG_MAIN << "trying to auto-detect it now!"; - sendMessage(Warning, i18n("Manually selected bibliography tool does not exist: trying to " - "auto-detect it now.")); - } - } - } - - // we will now try to detect the bib tool by using the given command hint - ToolConfigPair bibTool = manager()->findFirstBibliographyToolForCommand(hint); - - if(m_latexOutputHandler) { - // if we managed to detect a backend, store (or update) it for future runs - if(bibTool.isValid()) { - m_latexOutputHandler->setBibliographyBackendToolAutoDetected(bibTool); - } - else { - // perhaps we have it stored from a previous run? - bibTool = m_latexOutputHandler->bibliographyBackendToolAutoDetected(); - // perhaps the bib tools have changed from the previous run? - if (!manager()->containsBibliographyTool(bibTool)) { - bibTool = ToolConfigPair(); - } - } - } - - // this tool must always be available - const ToolConfigPair defaultBibTool = ToolConfigPair(QString("BibTeX"), DEFAULT_TOOL_CONFIGURATION); - - // if no tool has been detected, the default is BibTeX - return bibTool.isValid() ? bibTool : defaultBibTool; - } - - void LaTeX::checkAutoRun() - { - KILE_DEBUG_MAIN << "check for autorun, m_reRun is " << m_reRun; - if(m_reRun >= 2) { - KILE_DEBUG_MAIN << "Already rerun twice, doing nothing."; - m_reRun = 0; - return; - } - if(m_nErrors > 0) { - KILE_DEBUG_MAIN << "Errors found, not running again."; - m_reRun = 0; - return; - } - bool reRunWarningFound = false; - QString bibToolInLaTexOutput; - bool haveUndefinedCitations = false; - // check for "rerun" LaTeX and other tools warnings - if(m_nWarnings > 0) { - int sz = m_latexOutputInfoList.size(); - // the messages we are looking for are the last ones (most likely the very last one), so go from end to beginning - for(int i = sz-1; i >= 0; --i) { - if (m_latexOutputInfoList[i].type() == LatexOutputInfo::itmWarning - && m_latexOutputInfoList[i].message().contains("Rerun", Qt::CaseInsensitive)) { - // the message could be a message from Biblatex like this: - // Package biblatex Warning: The following entry could not be found - // (biblatex) in the database: - // (biblatex) - // (biblatex) Please verify the spelling and rerun - // (biblatex) LaTeX afterwards. - // - // our strategy: if the warning message contains "(biblatex)", Biblatex only - // suggests to check the source files first, but not to recompile yet - if (!m_latexOutputInfoList[i].message().contains("(biblatex)", Qt::CaseInsensitive)) { - reRunWarningFound = true; - break; - } - } - } - // Now look for messages from Biblatex like the following: - // Please (re)run Biber on the file: - // or - // Please (re)run Bibtex on the file: - QRegExp biblatexBackendMessage = QRegExp(".*Please \\(re\\)run ([A-Za-z]+) on the file", Qt::CaseInsensitive); - for(int i = sz-1; i >= 0; --i) { // same here, start from the end - if (m_latexOutputInfoList[i].type() == LatexOutputInfo::itmWarning - && biblatexBackendMessage.indexIn(m_latexOutputInfoList[i].message()) != -1) { - bibToolInLaTexOutput = biblatexBackendMessage.cap(1); - KILE_DEBUG_MAIN << "Captured Bib tool: " << bibToolInLaTexOutput; - break; - } - } - // If we did not get a message from Biblatex about bibtool (re)run, then - // we look for messages like "LaTeX Warning: Citation `A' on page 234 undefined on input line 12345." - // In that case we probably need to (re)run the bibtool. - if (bibToolInLaTexOutput.isEmpty()) { - QRegExp citationUndefinedMessage = QRegExp("Citation `(.+)' on page (\\d+) undefined on input line (\\d+)", - Qt::CaseInsensitive); - for(int i = 0; i < sz; ++i) { - if (m_latexOutputInfoList[i].type() == LatexOutputInfo::itmWarning - && citationUndefinedMessage.indexIn(m_latexOutputInfoList[i].message()) != -1) { - haveUndefinedCitations = true; - KILE_DEBUG_MAIN << "Detected undefined citations"; - break; - } - } - } - } - - bool asy = (m_reRun == 0) && updateAsy(); - // We run bibtool in the following cases: - // 1. Biblatex said that we have to (in this case bibToolInLaTexOutput is not empty), OR - // 2. There are no undefined citations and at least one of the .bib files has a younger modification - // date than the .bbl file, OR - // 3. We have undefined citations and at least one of the source files (including .bib and .tex) is - // younger than .bbl. - // (If the .bbl file is younger than all of them, the next rerun will not change anything) - bool bibs = !bibToolInLaTexOutput.isEmpty() || updateBibs(!haveUndefinedCitations); - bool index = updateIndex(); - KILE_DEBUG_MAIN << "asy:" << asy << "bibs:" << bibs << "index:" << index << "reRunWarningFound:" << reRunWarningFound; - // Currently, we don't properly detect yet whether asymptote has to be run. - // So, if asymtote figures are present, we run it each time after the first LaTeX run. - bool reRun = (asy || bibs || index || reRunWarningFound); - KILE_DEBUG_MAIN << "reRun:" << reRun; - - if(reRun) { - KILE_DEBUG_MAIN << "rerunning LaTeX, m_reRun is now " << m_reRun; - Base *tool = manager()->createTool(name(), toolConfig()); - if(tool) { - configureLaTeX(tool, source()); - // e.g. for LivePreview, it is necessary that the paths are copied to child processes - tool->copyPaths(this); - runChildNext(tool); - m_reRun++; - } - } - else { - m_reRun = 0; - } - - if(bibs) { - KILE_DEBUG_MAIN << "need to run the bibliography tool " << bibToolInLaTexOutput; - ToolConfigPair bibTool = determineBibliographyBackend(bibToolInLaTexOutput); - Base *tool = manager()->createTool(bibTool.first, bibTool.second); - if(tool) { - configureBibTeX(tool, targetDir() + '/' + S() + '.' + tool->from()); - // e.g. for LivePreview, it is necessary that the paths are copied to child processes - tool->copyPaths(this); - runChildNext(tool); - } - } - - if(index) { - KILE_DEBUG_MAIN << "need to run MakeIndex"; - Base *tool = manager()->createTool("MakeIndex", QString()); - KILE_DEBUG_MAIN << targetDir() << S() << tool->from(); - if(tool) { - configureMakeIndex(tool, targetDir() + '/' + S() + '.' + tool->from()); - // e.g. for LivePreview, it is necessary that the paths are copied to child processes - tool->copyPaths(this); - runChildNext(tool); - } - } - - if(asy) { - KILE_DEBUG_MAIN << "need to run asymptote"; - int sz = manager()->info()->allAsyFigures().size(); - for(int i = sz -1; i >= 0; --i) { - Base *tool = manager()->createTool("Asymptote", QString()); - - if(tool) { - configureAsymptote(tool, targetDir() + '/' + S() + "-" + QString::number(i + 1) + '.' + tool->from()); - // e.g. for LivePreview, it is necessary that the paths are copied to child processes - tool->copyPaths(this); - runChildNext(tool); - } - } - } - } - - - /////////////// PreviewLaTeX (dani) //////////////// - - PreviewLaTeX::PreviewLaTeX(const QString& tool, Manager *mngr, bool prepare) : LaTeX(tool, mngr, prepare) - { - } - - // PreviewLatex makes three steps: - // - filterLogfile() : parse logfile and read info into InfoLists - // - updateInfoLists(): change entries of temporary file into normal tex file - // - checqCriticals() : count errors and warnings and emit signals - bool PreviewLaTeX::finish(int r) - { - KILE_DEBUG_MAIN << r; - - m_toolResult = r; - - if(r != Success) { - return Compile::finish(r); - } - - QString log = targetDir() + '/' + S() + ".log"; - manager()->parserManager()->parseOutput(this, log, source(), m_filename, m_selrow, m_docrow); - - return true; - } - - void PreviewLaTeX::setPreviewInfo(const QString &filename, int selrow,int docrow) - { - m_filename = filename; - m_selrow = selrow; - m_docrow = docrow; - } - - /////////////// LivePreviewLaTeX //////////////// - - LivePreviewLaTeX::LivePreviewLaTeX(const QString& tool, Manager *mngr, bool prepare) - : LaTeX(tool, mngr, prepare) - { - } - - void LivePreviewLaTeX::configureLaTeX(KileTool::Base *tool, const QString& source) - { - LaTeX::configureLaTeX(tool, source); - tool->setTargetDir(targetDir()); - } - - void LivePreviewLaTeX::configureBibTeX(KileTool::Base *tool, const QString& source) - { - tool->setSource(source, targetDir()); - } - - void LivePreviewLaTeX::configureMakeIndex(KileTool::Base *tool, const QString& source) - { - tool->setSource(source, targetDir()); - } - - void LivePreviewLaTeX::configureAsymptote(KileTool::Base *tool, const QString& source) - { - tool->setSource(source, targetDir()); - } - // PreviewLatex makes three steps: - // - filterLogfile() : parse logfile and read info into InfoLists - // - updateInfoLists(): change entries of temporary file into normal tex file - // - checqCriticals() : count errors and warnings and emit signals +Factory::Factory(Manager *mngr, KConfig *config, KActionCollection *actionCollection) + : m_manager(mngr), m_config(config), m_actionCollection(actionCollection) +{ + m_standardToolConfigurationFileName = QStandardPaths::locate(QStandardPaths::DataLocation, "kilestdtools.rc"); +} + +Factory::~Factory() +{ +} + +Base* Factory::create(const QString& toolName, const QString& config, bool prepare /* = true */) +{ + KILE_DEBUG_MAIN << toolName << config << prepare; + KileTool::Base *tool = Q_NULLPTR; + //perhaps we can find the tool in the config file + if (m_config->hasGroup(groupFor(toolName, m_config))) { + KConfigGroup configGroup = m_config->group(groupFor(toolName, m_config)); + QString toolClass = configGroup.readEntry("class", QString()); + + if(toolClass == "LaTeX") { + tool = new LaTeX(toolName, m_manager, prepare); + } + else if(toolClass == "LaTeXpreview") { + tool = new PreviewLaTeX(toolName, m_manager, prepare); + } + else if(toolClass == "LaTeXLivePreview") { + tool = new LivePreviewLaTeX(toolName, m_manager, prepare); + } + else if(toolClass == "ForwardDVI") { + tool = new ForwardDVI(toolName, m_manager, prepare); + } + else if(toolClass == "ViewHTML") { + tool = new ViewHTML(toolName, m_manager, prepare); + } + else if(toolClass == "ViewBib") { + tool = new ViewBib(toolName, m_manager, prepare); + } + else if(toolClass == "Base") { + tool = new Base(toolName, m_manager, prepare); + } + else if(toolClass == "Compile") { + tool = new Compile(toolName, m_manager, prepare); + } + else if (BibliographyCompile::ToolClass == toolClass) { + tool = new BibliographyCompile(toolName, m_manager, prepare); + } + else if(toolClass == "Convert") { + tool = new Convert(toolName, m_manager, prepare); + } + else if(toolClass == "Archive") { + tool = new Archive(toolName, m_manager, prepare); + } + else if(toolClass == "View") { + tool = new View(toolName, m_manager, prepare); + } + else if(toolClass == "Sequence") { + tool = new Sequence(toolName, m_manager, prepare); + } + } + if(!tool) { + return Q_NULLPTR; + } + + if(!m_manager->configure(tool, config)) { + delete tool; + return Q_NULLPTR; + } + tool->setToolConfig(config); + + // this has to be done after the configuration step only! + if(dynamic_cast(tool)) { + dynamic_cast(tool)->setupSequenceTools(); + } + + return tool; +} + +void Factory::resetToolConfigurations() +{ + KConfig stdToolConfig(m_standardToolConfigurationFileName, KConfig::NoGlobals); + + m_config->deleteGroup(QLatin1String("Tools")); + m_config->deleteGroup(QLatin1String("ToolsGUI")); + + // we delete all the groups whose names start with "Tool/"; + for(QString groupName : m_config->groupList()) { + if(groupName.startsWith(QLatin1String("Tool/"))) { + m_config->deleteGroup(groupName); + } + } + + // now we copy all the "Tool/" groups, the "Tools", and "ToolsGUI" groups over + for(QString groupName : stdToolConfig.groupList()) { + if(groupName != SHORTCUTS_GROUP_NAME) { + KConfigGroup configGroup = stdToolConfig.group(groupName); + m_config->deleteGroup(groupName); + KConfigGroup newGroup = m_config->group(groupName); + configGroup.copyTo(&newGroup, KConfigGroup::Persistent); + } + } +} + +static void transferKeyStringPairsStartingWith(KConfigGroup& src, KConfigGroup& target, const QString& startsWith) +{ + const QStringList keyList = src.keyList(); + for(QString key : keyList) { + if(key.startsWith(startsWith)) { + QString value = src.readEntry(key, QString()); + target.writeEntry(key, value); + } + } +} + +void Factory::installStandardLivePreviewTools() +{ + KConfig stdToolConfig(m_standardToolConfigurationFileName, KConfig::NoGlobals); + + const QStringList groupList = stdToolConfig.groupList(); + for(QString groupName : groupList) { + if(groupName.startsWith(QStringLiteral("Tool/LivePreview"))) { + KConfigGroup configGroup = stdToolConfig.group(groupName); + m_config->deleteGroup(groupName); + KConfigGroup newGroup = m_config->group(groupName); + configGroup.copyTo(&newGroup, KConfigGroup::Persistent); + } + } + + { // transfer the standard settings inside the "Tools" group + const QString groupName(QStringLiteral("Tools")); + KConfigGroup stdConfigGroup = stdToolConfig.group(groupName); + KConfigGroup newGroup = m_config->group(groupName); + transferKeyStringPairsStartingWith(stdConfigGroup, newGroup, QStringLiteral("LivePreview")); + } + + { // transfer the standard settings inside the "ToolsGUI" group + const QString groupName(QStringLiteral("ToolsGUI")); + KConfigGroup stdConfigGroup = stdToolConfig.group(groupName); + KConfigGroup newGroup = m_config->group(groupName); + transferKeyStringPairsStartingWith(stdConfigGroup, newGroup, QStringLiteral("LivePreview")); + } +} + +/////////////// LaTeX //////////////// + +LaTeX::LaTeX(const QString& tool, Manager *mngr, bool prepare) + : Compile(tool, mngr, prepare), m_latexOutputHandler(Q_NULLPTR) +{ +} + +LaTeX::~LaTeX() +{ +} + +void LaTeX::setupAsChildTool(KileTool::Base *child) +{ + KileTool::LaTeX *latexChild = dynamic_cast(child); + if(latexChild) { + latexChild->setLaTeXOutputHandler(latexOutputHandler()); + } +} + +LaTeXOutputHandler* LaTeX::latexOutputHandler() +{ + return m_latexOutputHandler; +} + +void LaTeX::setLaTeXOutputHandler(LaTeXOutputHandler *h) +{ + m_latexOutputHandler = h; +} + +bool LaTeX::determineSource() +{ + QString src = source(); + + // check whether the source has been set already + if(!src.isEmpty()) { + return true; + } + + //the basedir is determined from the current compile target + //determined by getCompileName() + LaTeXOutputHandler *h = Q_NULLPTR; + src = m_ki->getCompileName(false, &h); + + setSource(src); + setLaTeXOutputHandler(h); + + return true; +} + +int LaTeX::m_reRun = 0; + +// FIXME don't hardcode bbl and ind suffix here. +bool LaTeX::updateBibs(bool checkOnlyBibDependencies) +{ + KileDocument::TextInfo *docinfo = manager()->info()->docManager()->textInfoFor(source()); + if(docinfo) { + QFileInfo fileinfo(docinfo->url().toLocalFile()); + QStringList dependencies; + + if (checkOnlyBibDependencies) { + dependencies = manager()->info()->allBibliographies(docinfo); + } + else { + dependencies = manager()->info()->allDependencies(docinfo); + dependencies.append(fileinfo.fileName()); + } + if (!dependencies.empty()) { + return needsUpdate(targetDir() + '/' + S() + ".bbl", + KileUtilities::lastModifiedFile(dependencies, fileinfo.absolutePath())); + } + } + + return false; +} + +bool LaTeX::updateIndex() +{ + KileDocument::TextInfo *docinfo = manager()->info()->docManager()->textInfoFor(source()); + if(docinfo) { + QStringList pckgs = manager()->info()->allPackages(docinfo); + if(pckgs.contains("makeidx") || pckgs.contains("imakeidx") || pckgs.contains("splitidx")) { + return needsUpdate(targetDir() + '/' + S() + ".ind", manager()->info()->lastModifiedFile(docinfo)); + } + } + + return false; +} + +bool LaTeX::updateAsy() +{ + KileDocument::TextInfo *docinfo = manager()->info()->docManager()->textInfoFor(source()); + if(docinfo) { + QStringList pckgs = manager()->info()->allPackages(docinfo); + // As asymptote doesn't properly notify the user when it needs to be rerun, we run + // it every time LaTeX is run (but only for m_reRun == 0 if LaTeX has to be rerun). + if(pckgs.contains("asymptote")) { + return true; + } + } + return false; +} + +bool LaTeX::finish(int r) +{ + KILE_DEBUG_MAIN << "==bool LaTeX::finish(" << r << ")====="; + + m_toolResult = r; + + if(m_toolResult == AbnormalExit || m_toolResult == Aborted) { + return false; + } + + // in case the compilation failed, we try to parse the log file in order to detect + // errors reported by LaTeX + QString log = targetDir() + '/' + S() + ".log"; + manager()->parserManager()->parseOutput(this, log, source()); + + return true; +} + +void LaTeX::latexOutputParserResultInstalled() +{ + KILE_DEBUG_MAIN; + + if(m_latexOutputHandler) { + m_latexOutputHandler->storeLaTeXOutputParserResult(m_nErrors, m_nWarnings, m_nBadBoxes, m_latexOutputInfoList, + m_logFile); + } + + checqCriticals(); + + if(readEntry("autoRun") == "yes") { + checkAutoRun(); + } + + Compile::finish(m_toolResult); +} + +void LaTeX::checqCriticals() +{ + // work around the 0 cases as the i18np call can cause some confusion when 0 is passed to it (#275700) + QString es = (m_nErrors == 0 ? i18n("0 errors") : i18np("1 error", "%1 errors", m_nErrors)); + QString ws = (m_nWarnings == 0 ? i18n("0 warnings") : i18np("1 warning", "%1 warnings", m_nWarnings)); + QString bs = (m_nBadBoxes == 0 ? i18n("0 badboxes") : i18np("1 badbox", "%1 badboxes", m_nBadBoxes)); + + sendMessage(Info, i18nc("String displayed in the log panel showing the number of errors/warnings/badboxes", + "%1, %2, %3", es, ws, bs)); + + // jump to first error + if(!isPartOfLivePreview() && m_nErrors > 0 && (readEntry("jumpToFirstError") == "yes")) { + connect(this, SIGNAL(jumpToFirstError()), manager(), SIGNAL(jumpToFirstError())); + emit(jumpToFirstError()); + } +} + +void LaTeX::configureLaTeX(KileTool::Base *tool, const QString& source) +{ + tool->setSource(source, workingDir()); +} + +void LaTeX::configureBibTeX(KileTool::Base *tool, const QString& source) +{ + tool->setSource(source, workingDir()); +} + +void LaTeX::configureMakeIndex(KileTool::Base *tool, const QString& source) +{ + tool->setSource(source, workingDir()); +} + +void LaTeX::configureAsymptote(KileTool::Base *tool, const QString& source) +{ + tool->setSource(source, workingDir()); +} + +// if 'Biblatex' is not used in the document, 'hint' will be empty +ToolConfigPair LaTeX::determineBibliographyBackend(const QString& hint) +{ + if(m_latexOutputHandler) { + ToolConfigPair userBibTool = m_latexOutputHandler->bibliographyBackendToolUserOverride(); + + if(userBibTool.isValid()) { + // now we still check whether such a tool really exists + if (manager()->containsBibliographyTool(userBibTool)) { + return userBibTool; + } + else { + KILE_DEBUG_MAIN << "Cannot find the following bibtool set by the user:" << userBibTool; + KILE_DEBUG_MAIN << "trying to auto-detect it now!"; + sendMessage(Warning, i18n("Manually selected bibliography tool does not exist: trying to " + "auto-detect it now.")); + } + } + } + + // we will now try to detect the bib tool by using the given command hint + ToolConfigPair bibTool = manager()->findFirstBibliographyToolForCommand(hint); + + if(m_latexOutputHandler) { + // if we managed to detect a backend, store (or update) it for future runs + if(bibTool.isValid()) { + m_latexOutputHandler->setBibliographyBackendToolAutoDetected(bibTool); + } + else { + // perhaps we have it stored from a previous run? + bibTool = m_latexOutputHandler->bibliographyBackendToolAutoDetected(); + // perhaps the bib tools have changed from the previous run? + if (!manager()->containsBibliographyTool(bibTool)) { + bibTool = ToolConfigPair(); + } + } + } + + // this tool must always be available + const ToolConfigPair defaultBibTool = ToolConfigPair(QString("BibTeX"), DEFAULT_TOOL_CONFIGURATION); + + // if no tool has been detected, the default is BibTeX + return bibTool.isValid() ? bibTool : defaultBibTool; +} + +void LaTeX::checkAutoRun() +{ + KILE_DEBUG_MAIN << "check for autorun, m_reRun is " << m_reRun; + if(m_reRun >= 2) { + KILE_DEBUG_MAIN << "Already rerun twice, doing nothing."; + m_reRun = 0; + return; + } + if(m_nErrors > 0) { + KILE_DEBUG_MAIN << "Errors found, not running again."; + m_reRun = 0; + return; + } + bool reRunWarningFound = false; + QString bibToolInLaTexOutput; + bool haveUndefinedCitations = false; + // check for "rerun" LaTeX and other tools warnings + if(m_nWarnings > 0) { + int sz = m_latexOutputInfoList.size(); + // the messages we are looking for are the last ones (most likely the very last one), so go from end to beginning + for(int i = sz-1; i >= 0; --i) { + if (m_latexOutputInfoList[i].type() == LatexOutputInfo::itmWarning + && m_latexOutputInfoList[i].message().contains("Rerun", Qt::CaseInsensitive)) { + // the message could be a message from Biblatex like this: + // Package biblatex Warning: The following entry could not be found + // (biblatex) in the database: + // (biblatex) + // (biblatex) Please verify the spelling and rerun + // (biblatex) LaTeX afterwards. + // + // our strategy: if the warning message contains "(biblatex)", Biblatex only + // suggests to check the source files first, but not to recompile yet + if (!m_latexOutputInfoList[i].message().contains("(biblatex)", Qt::CaseInsensitive)) { + reRunWarningFound = true; + break; + } + } + } + // Now look for messages from Biblatex like the following: + // Please (re)run Biber on the file: + // or + // Please (re)run Bibtex on the file: + QRegExp biblatexBackendMessage = QRegExp(".*Please \\(re\\)run ([A-Za-z]+) on the file", Qt::CaseInsensitive); + for(int i = sz-1; i >= 0; --i) { // same here, start from the end + if (m_latexOutputInfoList[i].type() == LatexOutputInfo::itmWarning + && biblatexBackendMessage.indexIn(m_latexOutputInfoList[i].message()) != -1) { + bibToolInLaTexOutput = biblatexBackendMessage.cap(1); + KILE_DEBUG_MAIN << "Captured Bib tool: " << bibToolInLaTexOutput; + break; + } + } + // If we did not get a message from Biblatex about bibtool (re)run, then + // we look for messages like "LaTeX Warning: Citation `A' on page 234 undefined on input line 12345." + // In that case we probably need to (re)run the bibtool. + if (bibToolInLaTexOutput.isEmpty()) { + QRegExp citationUndefinedMessage = QRegExp("Citation `(.+)' on page (\\d+) undefined on input line (\\d+)", + Qt::CaseInsensitive); + for(int i = 0; i < sz; ++i) { + if (m_latexOutputInfoList[i].type() == LatexOutputInfo::itmWarning + && citationUndefinedMessage.indexIn(m_latexOutputInfoList[i].message()) != -1) { + haveUndefinedCitations = true; + KILE_DEBUG_MAIN << "Detected undefined citations"; + break; + } + } + } + } + + bool asy = (m_reRun == 0) && updateAsy(); + // We run bibtool in the following cases: + // 1. Biblatex said that we have to (in this case bibToolInLaTexOutput is not empty), OR + // 2. There are no undefined citations and at least one of the .bib files has a younger modification + // date than the .bbl file, OR + // 3. We have undefined citations and at least one of the source files (including .bib and .tex) is + // younger than .bbl. + // (If the .bbl file is younger than all of them, the next rerun will not change anything) + bool bibs = !bibToolInLaTexOutput.isEmpty() || updateBibs(!haveUndefinedCitations); + bool index = updateIndex(); + KILE_DEBUG_MAIN << "asy:" << asy << "bibs:" << bibs << "index:" << index << "reRunWarningFound:" << reRunWarningFound; + // Currently, we don't properly detect yet whether asymptote has to be run. + // So, if asymtote figures are present, we run it each time after the first LaTeX run. + bool reRun = (asy || bibs || index || reRunWarningFound); + KILE_DEBUG_MAIN << "reRun:" << reRun; + + if(reRun) { + KILE_DEBUG_MAIN << "rerunning LaTeX, m_reRun is now " << m_reRun; + Base *tool = manager()->createTool(name(), toolConfig()); + if(tool) { + configureLaTeX(tool, source()); + // e.g. for LivePreview, it is necessary that the paths are copied to child processes + tool->copyPaths(this); + runChildNext(tool); + m_reRun++; + } + } + else { + m_reRun = 0; + } + + if(bibs) { + KILE_DEBUG_MAIN << "need to run the bibliography tool " << bibToolInLaTexOutput; + ToolConfigPair bibTool = determineBibliographyBackend(bibToolInLaTexOutput); + Base *tool = manager()->createTool(bibTool.first, bibTool.second); + if(tool) { + configureBibTeX(tool, targetDir() + '/' + S() + '.' + tool->from()); + // e.g. for LivePreview, it is necessary that the paths are copied to child processes + tool->copyPaths(this); + runChildNext(tool); + } + } + + if(index) { + KILE_DEBUG_MAIN << "need to run MakeIndex"; + Base *tool = manager()->createTool("MakeIndex", QString()); + KILE_DEBUG_MAIN << targetDir() << S() << tool->from(); + if(tool) { + configureMakeIndex(tool, targetDir() + '/' + S() + '.' + tool->from()); + // e.g. for LivePreview, it is necessary that the paths are copied to child processes + tool->copyPaths(this); + runChildNext(tool); + } + } + + if(asy) { + KILE_DEBUG_MAIN << "need to run asymptote"; + int sz = manager()->info()->allAsyFigures().size(); + for(int i = sz -1; i >= 0; --i) { + Base *tool = manager()->createTool("Asymptote", QString()); + + if(tool) { + configureAsymptote(tool, targetDir() + '/' + S() + "-" + QString::number(i + 1) + '.' + tool->from()); + // e.g. for LivePreview, it is necessary that the paths are copied to child processes + tool->copyPaths(this); + runChildNext(tool); + } + } + } +} + + +/////////////// PreviewLaTeX (dani) //////////////// + +PreviewLaTeX::PreviewLaTeX(const QString& tool, Manager *mngr, bool prepare) : LaTeX(tool, mngr, prepare) +{ +} + +// PreviewLatex makes three steps: +// - filterLogfile() : parse logfile and read info into InfoLists +// - updateInfoLists(): change entries of temporary file into normal tex file +// - checqCriticals() : count errors and warnings and emit signals +bool PreviewLaTeX::finish(int r) +{ + KILE_DEBUG_MAIN << r; + + m_toolResult = r; + + if(r != Success) { + return Compile::finish(r); + } + + QString log = targetDir() + '/' + S() + ".log"; + manager()->parserManager()->parseOutput(this, log, source(), m_filename, m_selrow, m_docrow); + + return true; +} + +void PreviewLaTeX::setPreviewInfo(const QString &filename, int selrow,int docrow) +{ + m_filename = filename; + m_selrow = selrow; + m_docrow = docrow; +} + +/////////////// LivePreviewLaTeX //////////////// + +LivePreviewLaTeX::LivePreviewLaTeX(const QString& tool, Manager *mngr, bool prepare) + : LaTeX(tool, mngr, prepare) +{ +} + +void LivePreviewLaTeX::configureLaTeX(KileTool::Base *tool, const QString& source) +{ + LaTeX::configureLaTeX(tool, source); + tool->setTargetDir(targetDir()); +} + +void LivePreviewLaTeX::configureBibTeX(KileTool::Base *tool, const QString& source) +{ + tool->setSource(source, targetDir()); +} + +void LivePreviewLaTeX::configureMakeIndex(KileTool::Base *tool, const QString& source) +{ + tool->setSource(source, targetDir()); +} + +void LivePreviewLaTeX::configureAsymptote(KileTool::Base *tool, const QString& source) +{ + tool->setSource(source, targetDir()); +} +// PreviewLatex makes three steps: +// - filterLogfile() : parse logfile and read info into InfoLists +// - updateInfoLists(): change entries of temporary file into normal tex file +// - checqCriticals() : count errors and warnings and emit signals // bool LivePreviewLaTeX::finish(int r) // { // KILE_DEBUG_MAIN << "==bool PreviewLaTeX::finish(" << r << ")====="; // // int nErrors = 0, nWarnings = 0; // if(filterLogfile()) { // manager()->info()->outputFilter()->updateInfoLists(m_filename,m_selrow,m_docrow); // checqCriticals(nErrors,nWarnings); // } // // return Compile::finish(r); // } // // void LivePreviewLaTeX::setPreviewInfo(const QString &filename, int selrow,int docrow) // { // m_filename = filename; // m_selrow = selrow; // m_docrow = docrow; // } - ForwardDVI::ForwardDVI(const QString& tool, Manager *mngr, bool prepare) : View(tool, mngr, prepare) - { - } - - bool ForwardDVI::checkPrereqs () - { - KProcess okularVersionTester; - okularVersionTester.setOutputChannelMode(KProcess::MergedChannels); - okularVersionTester.setProgram("okular", QStringList("--version")); - okularVersionTester.start(); - - if (okularVersionTester.waitForFinished()){ - QString output = okularVersionTester.readAll(); - QRegExp regExp = QRegExp("Okular: (\\d+).(\\d+).(\\d+)"); - - if(output.contains(regExp)){ - int majorVersion = regExp.cap(1).toInt(); - int minorVersion = regExp.cap(2).toInt(); - int veryMinorVersion = regExp.cap(3).toInt(); - - // see http://mail.kde.org/pipermail/okular-devel/2009-May/003741.html - // the required okular version is > 0.8.5 - if( majorVersion > 0 || - ( majorVersion == 0 && minorVersion > 8 ) || - ( majorVersion == 0 && minorVersion == 8 && veryMinorVersion > 5 ) ){ - ; // everything okay - } - else{ - sendMessage(Error,i18n("The version %1.%2.%3 of okular is too old for ForwardDVI. Please update okular to version 0.8.6 or higher",majorVersion,minorVersion,veryMinorVersion)); - } - } - } - // don't return false here because we don't know for sure if okular is used - return true; - } - - bool ForwardDVI::determineTarget() - { - if (!View::determineTarget()) { - return false; - } - - int para = manager()->info()->lineNumber(); - KTextEditor::Document *doc = manager()->info()->activeTextDocument(); - - if (!doc) { - return false; - } - - QString filepath = doc->url().toLocalFile(); - QString texfile = QDir(baseDir()).relativeFilePath(filepath); - QString relativeTarget = "file:" + targetDir() + '/' + target() + "#src:" + QString::number(para + 1) + ' ' + texfile; // space added, for files starting with numbers - QString absoluteTarget = "file:" + targetDir() + '/' + target() + "#src:" + QString::number(para + 1) + filepath; - - if(readEntry("type") == "DocumentViewer") { - addDict("%dir_target", targetDir()); - addDict("%target", target()); - addDict("%sourceFileName", filepath); - addDict("%sourceLine", QString::number(para + 1)); - } - else { - addDict("%dir_target", QString()); - addDict("%target", relativeTarget); - } - - addDict("%absolute_target", absoluteTarget); - KILE_DEBUG_MAIN << "==KileTool::ForwardDVI::determineTarget()=============\n"; - KILE_DEBUG_MAIN << "\tusing (absolute)" << absoluteTarget; - KILE_DEBUG_MAIN << "\tusing (relative)" << relativeTarget; - - return true; - } - - ViewBib::ViewBib(const QString& tool, Manager *mngr, bool prepare) : View(tool, mngr, prepare) - { - } - - bool ViewBib::determineSource() - { - KILE_DEBUG_MAIN << "==ViewBib::determineSource()======="; - if (!View::determineSource()) { - return false; - } - - QString path = source(true); - QFileInfo info(path); - - //get the bibliographies for this source - QStringList bibs = manager()->info()->allBibliographies(manager()->info()->docManager()->textInfoFor(path)); - KILE_DEBUG_MAIN << "\tfound " << bibs.count() << " bibs"; - if(bibs.count() > 0) { - QString bib = bibs.front(); - if (bibs.count() > 1) { - //show dialog - bool bib_selected = false; - KileListSelector *dlg = new KileListSelector(bibs, i18n("Select Bibliography"),i18n("Select a bibliography")); - if (dlg->exec() && dlg->hasSelection()) { - bib = dlg->selectedItems().first(); - bib_selected = true; - KILE_DEBUG_MAIN << "Bibliography selected : " << bib; - } - delete dlg; - - if(!bib_selected) { - sendMessage(Warning, i18n("No bibliography selected.")); - return false; - } - } - KILE_DEBUG_MAIN << "filename before: " << info.path(); - setSource(manager()->info()->checkOtherPaths(info.path(),bib + ".bib",KileInfo::bibinputs)); - } - else if(info.exists()) { //active doc is a bib file - KILE_DEBUG_MAIN << "filename before: " << info.path(); - setSource(manager()->info()->checkOtherPaths(info.path(),info.fileName(),KileInfo::bibinputs)); - } - else { - sendMessage(Error, i18n("No bibliographies found.")); - return false; - } - return true; - } - - ViewHTML::ViewHTML(const QString& tool, Manager *mngr, bool prepare) : View(tool, mngr, prepare) - { - } - - bool ViewHTML::determineTarget() - { - if (target().isNull()) { - //setRelativeBaseDir(S()); - QString dir = readEntry("relDir"); - QString trg = readEntry("target"); - - if(!dir.isEmpty()) { - translate(dir); - setRelativeBaseDir(dir); - } - - if(!trg.isEmpty()) { - translate(trg); - setTarget(trg); - } - - //auto-detect the file to view - if(dir.isEmpty() && trg.isEmpty()) { - QFileInfo file1 = QFileInfo(baseDir() + '/' + S() + "/index.html"); - QFileInfo file2 = QFileInfo(baseDir() + '/' + S() + ".html"); - - bool read1 = file1.isReadable(); - bool read2 = file2.isReadable(); - - if(!read1 && !read2) { - sendMessage(Error, i18n("Unable to find %1 or %2; if you are trying to view some other HTML file, go to Settings->Configure Kile->Tools->ViewHTML->Advanced.", file1.absoluteFilePath(), file2.absoluteFilePath())); - return false; - } - - //both exist, take most recent - if(read1 && read2) { - read1 = file1.lastModified() > file2.lastModified(); - read2 = !read1; - } - - if(read1) { - dir = S(); - trg = "index.html"; - - translate(dir); - setRelativeBaseDir(dir); - translate(trg); - setTarget(trg); - } - } - } - - return View::determineTarget(); - } +ForwardDVI::ForwardDVI(const QString& tool, Manager *mngr, bool prepare) : View(tool, mngr, prepare) +{ +} + +bool ForwardDVI::checkPrereqs () +{ + KProcess okularVersionTester; + okularVersionTester.setOutputChannelMode(KProcess::MergedChannels); + okularVersionTester.setProgram("okular", QStringList("--version")); + okularVersionTester.start(); + + if (okularVersionTester.waitForFinished()) { + QString output = okularVersionTester.readAll(); + QRegExp regExp = QRegExp("Okular: (\\d+).(\\d+).(\\d+)"); + + if(output.contains(regExp)) { + int majorVersion = regExp.cap(1).toInt(); + int minorVersion = regExp.cap(2).toInt(); + int veryMinorVersion = regExp.cap(3).toInt(); + + // see http://mail.kde.org/pipermail/okular-devel/2009-May/003741.html + // the required okular version is > 0.8.5 + if( majorVersion > 0 || + ( majorVersion == 0 && minorVersion > 8 ) || + ( majorVersion == 0 && minorVersion == 8 && veryMinorVersion > 5 ) ) { + ; // everything okay + } + else { + sendMessage(Error,i18n("The version %1.%2.%3 of okular is too old for ForwardDVI. Please update okular to version 0.8.6 or higher",majorVersion,minorVersion,veryMinorVersion)); + } + } + } + // don't return false here because we don't know for sure if okular is used + return true; +} + +bool ForwardDVI::determineTarget() +{ + if (!View::determineTarget()) { + return false; + } + + int para = manager()->info()->lineNumber(); + KTextEditor::Document *doc = manager()->info()->activeTextDocument(); + + if (!doc) { + return false; + } + + QString filepath = doc->url().toLocalFile(); + QString texfile = QDir(baseDir()).relativeFilePath(filepath); + QString relativeTarget = "file:" + targetDir() + '/' + target() + "#src:" + QString::number(para + 1) + ' ' + texfile; // space added, for files starting with numbers + QString absoluteTarget = "file:" + targetDir() + '/' + target() + "#src:" + QString::number(para + 1) + filepath; + + if(readEntry("type") == "DocumentViewer") { + addDict("%dir_target", targetDir()); + addDict("%target", target()); + addDict("%sourceFileName", filepath); + addDict("%sourceLine", QString::number(para + 1)); + } + else { + addDict("%dir_target", QString()); + addDict("%target", relativeTarget); + } + + addDict("%absolute_target", absoluteTarget); + KILE_DEBUG_MAIN << "==KileTool::ForwardDVI::determineTarget()=============\n"; + KILE_DEBUG_MAIN << "\tusing (absolute)" << absoluteTarget; + KILE_DEBUG_MAIN << "\tusing (relative)" << relativeTarget; + + return true; +} + +ViewBib::ViewBib(const QString& tool, Manager *mngr, bool prepare) : View(tool, mngr, prepare) +{ +} + +bool ViewBib::determineSource() +{ + KILE_DEBUG_MAIN << "==ViewBib::determineSource()======="; + if (!View::determineSource()) { + return false; + } + + QString path = source(true); + QFileInfo info(path); + + //get the bibliographies for this source + QStringList bibs = manager()->info()->allBibliographies(manager()->info()->docManager()->textInfoFor(path)); + KILE_DEBUG_MAIN << "\tfound " << bibs.count() << " bibs"; + if(bibs.count() > 0) { + QString bib = bibs.front(); + if (bibs.count() > 1) { + //show dialog + bool bib_selected = false; + KileListSelector *dlg = new KileListSelector(bibs, i18n("Select Bibliography"),i18n("Select a bibliography")); + if (dlg->exec() && dlg->hasSelection()) { + bib = dlg->selectedItems().first(); + bib_selected = true; + KILE_DEBUG_MAIN << "Bibliography selected : " << bib; + } + delete dlg; + + if(!bib_selected) { + sendMessage(Warning, i18n("No bibliography selected.")); + return false; + } + } + KILE_DEBUG_MAIN << "filename before: " << info.path(); + setSource(manager()->info()->checkOtherPaths(info.path(),bib + ".bib",KileInfo::bibinputs)); + } + else if(info.exists()) { //active doc is a bib file + KILE_DEBUG_MAIN << "filename before: " << info.path(); + setSource(manager()->info()->checkOtherPaths(info.path(),info.fileName(),KileInfo::bibinputs)); + } + else { + sendMessage(Error, i18n("No bibliographies found.")); + return false; + } + return true; +} + +ViewHTML::ViewHTML(const QString& tool, Manager *mngr, bool prepare) : View(tool, mngr, prepare) +{ +} + +bool ViewHTML::determineTarget() +{ + if (target().isNull()) { + //setRelativeBaseDir(S()); + QString dir = readEntry("relDir"); + QString trg = readEntry("target"); + + if(!dir.isEmpty()) { + translate(dir); + setRelativeBaseDir(dir); + } + + if(!trg.isEmpty()) { + translate(trg); + setTarget(trg); + } + + //auto-detect the file to view + if(dir.isEmpty() && trg.isEmpty()) { + QFileInfo file1 = QFileInfo(baseDir() + '/' + S() + "/index.html"); + QFileInfo file2 = QFileInfo(baseDir() + '/' + S() + ".html"); + + bool read1 = file1.isReadable(); + bool read2 = file2.isReadable(); + + if(!read1 && !read2) { + sendMessage(Error, i18n("Unable to find %1 or %2; if you are trying to view some other HTML file, go to Settings->Configure Kile->Tools->ViewHTML->Advanced.", file1.absoluteFilePath(), file2.absoluteFilePath())); + return false; + } + + //both exist, take most recent + if(read1 && read2) { + read1 = file1.lastModified() > file2.lastModified(); + read2 = !read1; + } + + if(read1) { + dir = S(); + trg = "index.html"; + + translate(dir); + setRelativeBaseDir(dir); + translate(trg); + setTarget(trg); + } + } + } + + return View::determineTarget(); +} } /* * BibliographyCompile */ const QString KileTool::BibliographyCompile::ToolClass = "Bibliography"; KileTool::BibliographyCompile::BibliographyCompile(const QString& name, KileTool::Manager* manager, bool prepare) -: Compile(name, manager, prepare) + : Compile(name, manager, prepare) { } diff --git a/src/kilestdtools.h b/src/kilestdtools.h index 2a00f3d7..d1f09a5f 100644 --- a/src/kilestdtools.h +++ b/src/kilestdtools.h @@ -1,199 +1,199 @@ /************************************************************************************* Copyright (C) 2003 by Jeroen Wijnhout (Jeroen.Wijnhout@kdemail.net) *************************************************************************************/ /*************************************************************************** * * * 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. * * * ***************************************************************************/ #ifndef KILESTDTOOLS_H #define KILESTDTOOLS_H #include #include "kiledebug.h" #include "kiletool.h" #include "tool_utils.h" class KConfig; class KActionCollection; namespace KileTool { - class View; - class Compile; - class Manager; - - class Factory - { - friend class Manager; - - public: - Factory(Manager *mngr, KConfig *config, KActionCollection *actionCollection); - ~Factory(); - - void resetToolConfigurations(); - void installStandardLivePreviewTools(); - - private: - Manager *m_manager; - KConfig *m_config; - KActionCollection *m_actionCollection; - QString m_standardToolConfigurationFileName; - - // only the 'Manager' is allowed to call this - Base* create(const QString& tool, const QString& config, bool prepare = true); - }; - - class LaTeX : public Compile - { - Q_OBJECT - friend class KileTool::Factory; - - protected: - LaTeX(const QString& tool, Manager *mngr, bool prepare); - public: - virtual ~LaTeX(); - - void setupAsChildTool(KileTool::Base *child); - - LaTeXOutputHandler* latexOutputHandler(); - void setLaTeXOutputHandler(LaTeXOutputHandler *h); - - Q_SIGNALS: - void jumpToFirstError(); - - public Q_SLOTS: - bool finish(int); - - protected: - LaTeXOutputHandler *m_latexOutputHandler; - - virtual bool determineSource(); - - void checqCriticals(); - void checkAutoRun(); - void latexOutputParserResultInstalled(); - - virtual bool updateBibs(bool checkOnlyBibDependencies); - virtual bool updateIndex(); - virtual bool updateAsy(); - - virtual void configureLaTeX(KileTool::Base *tool, const QString& source); - virtual void configureBibTeX(KileTool::Base *tool, const QString& source); - virtual void configureMakeIndex(KileTool::Base *tool, const QString& source); - virtual void configureAsymptote(KileTool::Base *tool, const QString& source); - - /** - * @brief Determine the tool name and configuration for the bibliography backend - * - * If a backend has been set by the user, that one is returned. Otherwise, - * an automatic detection of the backend is attempted. If an automatic detection - * is not possible and no backend has been previously auto-detected, the - * default tool (BibTex) is returned. - * @returns Tool name that can be provided to @ref KileTool::Manager::create - **/ - ToolConfigPair determineBibliographyBackend(const QString& hint); - - //FIXME: this is a little 'hackish' - static int m_reRun; - }; - - class PreviewLaTeX : public LaTeX - { - Q_OBJECT - friend class KileTool::Factory; - - protected: - PreviewLaTeX(const QString& tool, Manager *mngr, bool prepare); - - public: - void setPreviewInfo(const QString &filename, int selrow, int docrow); - - public Q_SLOTS: - bool finish(int); - - private: - QString m_filename; - int m_selrow; - int m_docrow; - }; - - class LivePreviewLaTeX : public LaTeX - { - Q_OBJECT - friend class KileTool::Factory; +class View; +class Compile; +class Manager; - protected: - LivePreviewLaTeX(const QString& tool, Manager *mngr, bool prepare); +class Factory +{ + friend class Manager; + +public: + Factory(Manager *mngr, KConfig *config, KActionCollection *actionCollection); + ~Factory(); + + void resetToolConfigurations(); + void installStandardLivePreviewTools(); + +private: + Manager *m_manager; + KConfig *m_config; + KActionCollection *m_actionCollection; + QString m_standardToolConfigurationFileName; + + // only the 'Manager' is allowed to call this + Base* create(const QString& tool, const QString& config, bool prepare = true); +}; + +class LaTeX : public Compile +{ + Q_OBJECT + friend class KileTool::Factory; + +protected: + LaTeX(const QString& tool, Manager *mngr, bool prepare); +public: + virtual ~LaTeX(); + + void setupAsChildTool(KileTool::Base *child); + + LaTeXOutputHandler* latexOutputHandler(); + void setLaTeXOutputHandler(LaTeXOutputHandler *h); + +Q_SIGNALS: + void jumpToFirstError(); + +public Q_SLOTS: + bool finish(int); + +protected: + LaTeXOutputHandler *m_latexOutputHandler; + + virtual bool determineSource(); + + void checqCriticals(); + void checkAutoRun(); + void latexOutputParserResultInstalled(); + + virtual bool updateBibs(bool checkOnlyBibDependencies); + virtual bool updateIndex(); + virtual bool updateAsy(); - public: + virtual void configureLaTeX(KileTool::Base *tool, const QString& source); + virtual void configureBibTeX(KileTool::Base *tool, const QString& source); + virtual void configureMakeIndex(KileTool::Base *tool, const QString& source); + virtual void configureAsymptote(KileTool::Base *tool, const QString& source); + + /** + * @brief Determine the tool name and configuration for the bibliography backend + * + * If a backend has been set by the user, that one is returned. Otherwise, + * an automatic detection of the backend is attempted. If an automatic detection + * is not possible and no backend has been previously auto-detected, the + * default tool (BibTex) is returned. + * @returns Tool name that can be provided to @ref KileTool::Manager::create + **/ + ToolConfigPair determineBibliographyBackend(const QString& hint); + + //FIXME: this is a little 'hackish' + static int m_reRun; +}; + +class PreviewLaTeX : public LaTeX +{ + Q_OBJECT + friend class KileTool::Factory; + +protected: + PreviewLaTeX(const QString& tool, Manager *mngr, bool prepare); + +public: + void setPreviewInfo(const QString &filename, int selrow, int docrow); + +public Q_SLOTS: + bool finish(int); + +private: + QString m_filename; + int m_selrow; + int m_docrow; +}; + +class LivePreviewLaTeX : public LaTeX +{ + Q_OBJECT + friend class KileTool::Factory; + +protected: + LivePreviewLaTeX(const QString& tool, Manager *mngr, bool prepare); + +public: // void setPreviewInfo(const QString &filename, int selrow, int docrow); - public Q_SLOTS: +public Q_SLOTS: // bool finish(int); - protected: - virtual void configureLaTeX(KileTool::Base *tool, const QString& source); - virtual void configureBibTeX(KileTool::Base *tool, const QString& source); - virtual void configureMakeIndex(KileTool::Base *tool, const QString& source); - virtual void configureAsymptote(KileTool::Base *tool, const QString& source); +protected: + virtual void configureLaTeX(KileTool::Base *tool, const QString& source); + virtual void configureBibTeX(KileTool::Base *tool, const QString& source); + virtual void configureMakeIndex(KileTool::Base *tool, const QString& source); + virtual void configureAsymptote(KileTool::Base *tool, const QString& source); - private: - QString m_filename; - int m_selrow; - int m_docrow; - }; +private: + QString m_filename; + int m_selrow; + int m_docrow; +}; - class ForwardDVI : public View - { - friend class KileTool::Factory; +class ForwardDVI : public View +{ + friend class KileTool::Factory; - protected: - ForwardDVI(const QString & tool, Manager *mngr, bool prepare = true); +protected: + ForwardDVI(const QString & tool, Manager *mngr, bool prepare = true); - bool determineTarget(); - bool checkPrereqs(); - }; + bool determineTarget(); + bool checkPrereqs(); +}; - class ViewBib : public View - { - friend class KileTool::Factory; +class ViewBib : public View +{ + friend class KileTool::Factory; - protected: - ViewBib(const QString& tool, Manager *mngr, bool prepare = true); +protected: + ViewBib(const QString& tool, Manager *mngr, bool prepare = true); - bool determineSource(); - }; + bool determineSource(); +}; - class ViewHTML : public View - { - Q_OBJECT - friend class KileTool::Factory; +class ViewHTML : public View +{ + Q_OBJECT + friend class KileTool::Factory; - protected: - ViewHTML(const QString& tool, Manager *mngr, bool prepare = true); +protected: + ViewHTML(const QString& tool, Manager *mngr, bool prepare = true); - bool determineTarget(); + bool determineTarget(); - Q_SIGNALS: - void updateStatus(bool, bool); - }; +Q_SIGNALS: + void updateStatus(bool, bool); +}; - class BibliographyCompile : public Compile - { - friend class KileTool::Factory; +class BibliographyCompile : public Compile +{ + friend class KileTool::Factory; - protected: - BibliographyCompile(const QString& name, Manager* manager, bool prepare = true); - public: - static const QString ToolClass; - }; +protected: + BibliographyCompile(const QString& name, Manager* manager, bool prepare = true); +public: + static const QString ToolClass; +}; } #endif diff --git a/src/kiletool.cpp b/src/kiletool.cpp index 1bc99a12..4d626d26 100644 --- a/src/kiletool.cpp +++ b/src/kiletool.cpp @@ -1,848 +1,848 @@ /*************************************************************************** Copyright (C) 2003 by Jeroen Wijnhout (jeroen.wijnhout@kdemail.net) 2010-2014 by Michel Ludwig (michel.ludwig@kdemail.net) ***************************************************************************/ /*************************************************************************** * * * 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. * * * ***************************************************************************/ #include "kiletool.h" #include #include #include #include #include #include #include #include #include #include "kileconfig.h" #include "kiletool_enums.h" #include "kilestdtools.h" //for the factory #include "kiletoolmanager.h" #include "kiledocmanager.h" #include "kileinfo.h" #include "documentinfo.h" #include "kileproject.h" namespace KileTool { - Base::Base(const QString &name, Manager *manager, bool prepare /* = true */) : - QObject(manager), // ensure that they are deleted whenever the tool manager gets deleted - m_launcher(Q_NULLPTR), - m_quickie(false), - m_isPartOfLivePreview(false), - m_manager(manager), - m_name(name), - m_bPrepareToRun(prepare), - m_texInputs(KileConfig::teXPaths()), - m_bibInputs(KileConfig::bibInputPaths()), - m_bstInputs(KileConfig::bstInputPaths()), - m_childToolSpawned(false), - m_toolResult(-1) - { - // WARNING: 'NeedSaveAll' is currently needed to indicate to the tool manager that parsing has to be finished - // before it launches this tool! This is important to ensure that the right master document is used - // in the case of projects, for example. - m_flags = NeedTargetDirExec | NeedTargetDirWrite | NeedActiveDoc | NeedMasterDoc | NoUntitledDoc | NeedSourceExists | NeedSourceRead | NeedSaveAll; - - setMsg(NeedTargetDirExec, ki18n("Could not change to the folder %1.")); - setMsg(NeedTargetDirWrite, ki18n("The folder %1 is not writable, therefore %2 will not be able to save its results.")); - setMsg(NeedTargetExists, ki18n("The file %1/%2 does not exist. If this is unexpected, check the file permissions.")); - setMsg(NeedTargetRead, ki18n("The file %1/%2 is not readable. If this is unexpected, check the file permissions.")); - setMsg(NeedActiveDoc, ki18n("Could not determine on which file to run %1, because there is no active document.")); - setMsg(NeedMasterDoc, ki18n("Could not determine the master file for this document.")); - setMsg(NoUntitledDoc, ki18n("Please save the untitled document first.")); - setMsg(NeedSourceExists, ki18n("The file %1 does not exist.")); - setMsg(NeedSourceRead, ki18n("The file %1 is not readable.")); - - m_bPrepared = false; - } - - Base::~Base() - { - KILE_DEBUG_MAIN << "DELETING TOOL: " << name() << this; - emit(aboutToBeDestroyed(this)); - delete m_launcher; - } - - QString Base::source(bool absolute /* = true */) const - { - if (m_source.isEmpty()) { - return QString(); - } - - QString src = m_source; - if (absolute) { - src = m_basedir + '/' + src; - } - - return src; - } - - void Base::setMsg(long n, const KLocalizedString& msg) - { - m_messages[n] = msg; - } - - void Base::translate(QString &str, bool quoteForShell) - { - QHashIterator it(paramDict()); - while(it.hasNext()) { - it.next(); - QString value; - // the file names in %AFL are quoted already - if(quoteForShell && it.key() != "%AFL") { - value = KShell::quoteArg(it.value()); - } - else { - value = it.value(); - } - str.replace(it.key(), value); - } - } - - void Base::removeFlag(uint flag) - { - m_flags &= ~flag; - } - - - bool Base::requestSaveAll() - { - return (flags() & NeedSaveAll); - } - - void Base::setEntry(const QString& key, const QString& value) - { - m_entryMap[key] = value; - } - - void Base::prepareToRun() - { - KILE_DEBUG_MAIN << "==Base::prepareToRun()======="; - - //install a launcher - if (!installLauncher()) - { - m_nPreparationResult = NoLauncherInstalled; - m_bPrepared = false; - return; - } - - if (!determineSource()) - { - m_nPreparationResult = NoValidSource; - m_bPrepared = false; - return; - } - - if (!determineTarget()) - { - m_nPreparationResult = NoValidTarget; - m_bPrepared = false; - return; - } - - if ( m_launcher == 0 ) - { - m_nPreparationResult = NoLauncherInstalled; - m_bPrepared = false; - return; - } - - if(!workingDir().isEmpty()) { - m_launcher->setWorkingDirectory(workingDir()); - } - else { - m_launcher->setWorkingDirectory(baseDir()); - } - - //fill in the dictionary - addDict("%options", m_options); - - m_resolution = KileConfig::dvipngResolution() ; - addDict("%res",m_resolution); - - m_bPrepared = true; - m_nPreparationResult = Running; - } - - int Base::run() - { - KILE_DEBUG_MAIN << "==KileTool::Base::run()================="; - - if(m_nPreparationResult != 0) { - emit(failedToRun(this, m_nPreparationResult)); - return m_nPreparationResult; - } - - if(!checkSource()) { - emit(failedToRun(this, NoValidSource)); - return NoValidSource; - } - - if(!checkTarget()) { - emit(failedToRun(this, TargetHasWrongPermissions)); - return TargetHasWrongPermissions; - } - - if (!checkPrereqs()) { - emit(failedToRun(this, NoValidPrereqs)); - return NoValidPrereqs; - } - - emit(start(this)); - - if (!m_launcher || !m_launcher->launch()) { - KILE_DEBUG_MAIN << "\tlaunching failed"; - if(!m_launcher) { - emit(failedToRun(this, CouldNotLaunch)); - return CouldNotLaunch; - } - if(!m_launcher->selfCheck()) { - emit(failedToRun(this, SelfCheckFailed)); - return SelfCheckFailed; - } - else { - emit(failedToRun(this, CouldNotLaunch)); - return CouldNotLaunch; - } - } - - KILE_DEBUG_MAIN << "\trunning..."; - - return Running; - - } - - bool Base::determineSource() - { - QString src = source(); - - // check whether the source has been set already - if(!src.isEmpty()) { - return true; - } - - //the basedir is determined from the current compile target - //determined by getCompileName() - if(src.isEmpty()) { - src = m_ki->getCompileName(); - } - setSource(src); - - return true; - } - - bool Base::checkSource() - { - //FIXME deal with tools that do not need a source or target (yes they exist) - //Is there an active document? Only check if the source file is not explicitly set. - if((m_source.isEmpty()) && (m_manager->info()->activeTextDocument() == Q_NULLPTR)) { - sendMessage(Error, msg(NeedActiveDoc).subs(name()).toString()); - return false; - } - - if(m_source.isEmpty() && m_manager->info()->activeTextDocument() != Q_NULLPTR) { - if(m_manager->info()->activeTextDocument()->url().isEmpty() - && (flags() & NoUntitledDoc)) { - sendMessage(Error, msg(NoUntitledDoc).toString()); - return false; - } - else { - //couldn't find a source file, huh? - //we know there is an active document, the only reason is could have failed is because - //we couldn't find a LaTeX root document - sendMessage(Error, msg(NeedMasterDoc).toString()); - return false; - } - } - - QFileInfo fi(source()); - if((flags() & NeedSourceExists) && !fi.exists()) { - sendMessage(Error, msg(NeedSourceExists).subs(fi.absoluteFilePath()).toString()); - return false; - } - - if((flags() & NeedSourceRead) && !fi.isReadable()) { - sendMessage(Error, msg(NeedSourceRead).subs(fi.absoluteFilePath()).toString()); - return false; - } - - return true; - } - - void Base::runChildNext(Base *tool, bool block /*= false*/) - { - m_childToolSpawned = true; - if(isPartOfLivePreview()) { - tool->setPartOfLivePreview(); - } - manager()->runChildNext(this, tool, block); - } - - void Base::setSource(const QString &source, const QString& workingDir) - { - QFileInfo info(source); - - if(!from().isEmpty()) { - QString src = source; - if(info.suffix().length() > 0) { - src.replace(QRegExp(info.suffix() + '$'), from()); - } - info.setFile(src); - } - - if(!workingDir.isEmpty()) { - setWorkingDir(workingDir); - } - - m_basedir = info.absolutePath(); - m_source = info.fileName(); - m_S = info.completeBaseName(); - - addDict("%dir_base", m_basedir); - addDict("%source", m_source); - addDict("%S",m_S); - - KILE_DEBUG_MAIN << "===KileTool::Base::setSource()=============="; - KILE_DEBUG_MAIN << "using " << source; - KILE_DEBUG_MAIN << "source="< 0) { - m_target = S() + '.' + to(); - } - else { - m_target = source(false); - } - } - - if(m_relativedir.isEmpty() && (!readEntry("relDir").isEmpty())) { - m_relativedir = readEntry("relDir"); - } - - QUrl url; - if(!m_targetdir.isEmpty()) { - url = QUrl::fromLocalFile(m_targetdir); - } - else if(!m_workingDir.isEmpty()) { - url = QUrl::fromLocalFile(m_workingDir); - } - else { - url = QUrl::fromLocalFile(m_basedir); - } - url = url.adjusted(QUrl::StripTrailingSlash); - url.setPath(QDir::cleanPath(url.path() + '/' + m_relativedir)); - m_targetdir = url.toLocalFile(); - - setTarget(m_target); - setTargetDir(m_targetdir); - - KILE_DEBUG_MAIN << "==KileTool::Base::determineTarget()========="; - KILE_DEBUG_MAIN << "\tm_targetdir=" << m_targetdir; - KILE_DEBUG_MAIN << "\tm_target=" << m_target; - - return true; - } - - bool Base::checkTarget() - { - //check if the target directory is accessible - QFileInfo info(m_targetdir); - - if((flags() & NeedTargetDirExec ) && (!info.isExecutable())) { - sendMessage(Error, msg(NeedTargetDirExec).subs(m_targetdir).toString()); - return false; - } - - if((flags() & NeedTargetDirWrite) && (!info.isWritable())) { - sendMessage(Error, msg(NeedTargetDirWrite).subs(m_targetdir).subs(m_name).toString()); - return false; - } - - info.setFile(m_targetdir + '/' + m_target); - - if((flags() & NeedTargetExists) && (!info.exists())) { - sendMessage(Error, msg(NeedTargetExists).subs(m_targetdir).subs(m_target).toString()); - return false; - } - - if((flags() & NeedTargetRead) && (!info.isReadable())) { - sendMessage(Error, msg(NeedTargetRead).subs(m_targetdir).subs(m_target).toString()); - return false; - } - - return true; - } - - void Base::setTarget(const QString &target) - { - m_target = target; - addDict("%target", m_target); - } - - void Base::setTargetDir(const QString &target) - { - m_targetdir = target; - addDict("%dir_target", m_targetdir); - } - - void Base::setTargetPath(const QString &target) - { - QFileInfo fi(target); - setTarget(fi.fileName()); - setTargetDir(fi.absolutePath()); - } - - bool Base::checkPrereqs() - { - return true; - } - - void Base::stop() - { - if (m_launcher) { - m_launcher->kill(); - } - - emit(done(this, Aborted, m_childToolSpawned)); - } - - bool Base::finish(int result) - { - KILE_DEBUG_MAIN << "==KileTool::Base::finish()=============="; - if (sender()) - { - KILE_DEBUG_MAIN << "\tcalled by " << sender()->objectName() << " " << sender()->metaObject()->className(); - } - - if ( result == Aborted ) - sendMessage(Error, "Aborted"); - - if ( result == Success ) - sendMessage(Info,"Done!"); - - KILE_DEBUG_MAIN << "\temitting done(KileTool::Base*, int) " << name(); - emit(done(this, result, m_childToolSpawned)); - - //we will only get here if the done() signal is not connected to the manager (who will destroy this object) - if (result == Success) { - return true; - } - else { - return false; - } - } - - void Base::installLaTeXOutputParserResult(int nErrors, int nWarnings, int nBadBoxes, const LatexOutputInfoArray& outputList, - const QString& logFile) - { - m_nErrors = nErrors; - m_nWarnings = nWarnings; - m_nBadBoxes = nBadBoxes; - m_latexOutputInfoList = outputList; - m_logFile = logFile; - - latexOutputParserResultInstalled(); - } - - void Base::latexOutputParserResultInstalled() - { - finish(Success); - } - - void Base::installLauncher(Launcher *lr) - { - if(m_launcher != lr) - delete m_launcher; - - m_launcher = lr; - //lr->setParamDict(paramDict()); - lr->setTool(this); - - connect(lr, SIGNAL(message(int, const QString &)), this, SLOT(sendMessage(int, const QString &))); - connect(lr, SIGNAL(output(const QString &)), this, SLOT(filterOutput(const QString &))); - connect(lr, SIGNAL(done(int)), this, SLOT(finish(int))); - } - - bool Base::installLauncher() - { - if (m_launcher) { - return true; - } - - QString type = readEntry("type"); - KILE_DEBUG_MAIN << "installing launcher of type " << type; - Launcher *lr = Q_NULLPTR; - - if ( type == "Process" ) { - lr = new ProcessLauncher(); - } - else if ( type == "Konsole" ) { - lr = new KonsoleLauncher(); - } - else if ( type == "DocumentViewer" ) { - lr = new DocumentViewerLauncher(); - } - - if (lr) { - installLauncher(lr); - return true; - } - else { - m_launcher = Q_NULLPTR; - return false; - } - } - - void Base::setupAsChildTool(KileTool::Base *child) - { - Q_UNUSED(child); - } - - void Base::sendMessage(int type, const QString &msg) - { - emit(message(type, msg, name())); - } - - void Base::filterOutput(const QString & str) - { - //here you have the change to filter the output and do some error extraction for example - //this should be done by a OutputFilter class - - //idea: store the buffer until a complete line (or more) has been received then parse these lines - //just send the buf immediately to the output widget, the results of the parsing are displayed in - //the log widget anyway. - emit(output(str)); - } - - bool Base::addDict(const QString & key, const QString & value) - { - bool e = !(paramDict().contains(key)); - paramDict()[key] = value; - return e; - } - - bool Base::needsUpdate(const QString &target, const QString &source) - { - KILE_DEBUG_MAIN << "==Base::needsUpdate(" << target << "," << source; - QFileInfo targetinfo(target); - QFileInfo sourceinfo(source); - QDateTime currDateTime = QDateTime::currentDateTime(); - - if(!(sourceinfo.exists() && sourceinfo.isReadable())) { - KILE_DEBUG_MAIN << "\treturning false: source does not exist"; - return false; - } - - if(!targetinfo.exists()) { - KILE_DEBUG_MAIN << "\treturning true: target does not exist"; - return true; - } - - KILE_DEBUG_MAIN << "\ttarget: " << targetinfo.lastModified().toString(); - KILE_DEBUG_MAIN << "\tsource: " << sourceinfo.lastModified().toString(); - - if(targetinfo.lastModified() > currDateTime) { - KILE_DEBUG_MAIN << "targetinfo.lastModifiedTime() is in the future"; - return false; - } - else if(sourceinfo.lastModified() > currDateTime) { - KILE_DEBUG_MAIN << "sourceinfo.lastModifiedTime() is in the future"; - return false; - } - - KILE_DEBUG_MAIN << "\treturning " << (targetinfo.lastModified() < sourceinfo.lastModified()); - return targetinfo.lastModified() < sourceinfo.lastModified(); - } - - Compile::Compile(const QString &name, Manager * manager, bool prepare /*= true*/) - : Base(name, manager, prepare) - { - setFlags( flags() | NeedTargetDirExec | NeedTargetDirWrite); - } - - Compile::~Compile() - {} - - bool Compile::checkSource() - { - if ( !Base::checkSource() ) return false; - - bool isRoot = true; - KileDocument::TextInfo *docinfo = manager()->info()->docManager()->textInfoFor(source()); - if (docinfo) { - isRoot = (readEntry("checkForRoot") == "yes") ? docinfo->isLaTeXRoot() : true; - } - - if (!isRoot) - { - return manager()->queryContinue(i18n("The document %1 is not a LaTeX root document; continue anyway?", source()), i18n("Continue?")); - } - - return true; - } - - View::View(const QString &name, Manager * manager, bool prepare /*= true*/) - : Base(name, manager, prepare) - { - setFlags(NeedTargetDirExec | NeedTargetExists | NeedTargetRead); - - KILE_DEBUG_MAIN << "View: flag " << (flags() & NeedTargetExists); - setMsg(NeedTargetExists, ki18n("The file %1/%2 does not exist; did you compile the source file?")); - } - - View::~View() - { - } - - - Archive::Archive(const QString &name, Manager * manager, bool prepare /* = true*/) - : Base(name, manager,prepare) - { - setFlags( NeedTargetDirExec | NeedTargetDirWrite ); - } - - Archive::~Archive() - {} - - bool Archive::checkPrereqs() - { - if(!m_project) { - sendMessage(Error,i18n("The current document is not associated to a project. Please activate a document that is associated to the project you want to archive, then choose Archive again.")); - return false; - } - else if(m_fileList.isEmpty()) { - sendMessage(Error, i18n("No files have been chosen for archiving.")); - return false; - } - else { - return true; - } - } - - void Archive::setSource(const QString &source, const QString& workingDir) - { - Q_UNUSED(workingDir); - QUrl url = QUrl::fromLocalFile(source); - m_project = manager()->info()->docManager()->projectFor(url); - if ( !m_project ) - m_project = manager()->info()->docManager()->activeProject(); - if ( !m_project ) - m_project = manager()->info()->docManager()->selectProject(i18n("Archive Project")); - if ( !m_project ) - { - Base::setSource(source); - return; - } - - manager()->info()->docManager()->projectSave(m_project); - Base::setSource(m_project->url().toLocalFile()); - m_fileList = m_project->archiveFileList(); - - addDict("%AFL", m_fileList); - - KILE_DEBUG_MAIN << "===KileTool::Archive::setSource("<< source << ")=============="; - KILE_DEBUG_MAIN << "m_fileList="<getCompileName(false, &h); - - setSource(src); - setLaTeXOutputHandler(h); - - return true; - } - - bool Sequence::requestSaveAll() - { - // if one of the tools in the sequence requests save-all, then we also - // request it - for(QLinkedList::iterator i = m_tools.begin(); i != m_tools.end(); ++i) { - if((*i)->requestSaveAll()) { - return true; - } - } - - return false; - } - - void Sequence::setupSequenceTools() - { - QStringList toolNameList = readEntry("sequence").split(','); - QString tl, cfg; - Base *tool; - for(QStringList::iterator i = toolNameList.begin(); i != toolNameList.end(); ++i) { - QString fullToolSpec = (*i).trimmed(); - extract(fullToolSpec, tl, cfg); - - tool = manager()->createTool(tl, cfg, false); // create tool with delayed preparation - if (tool) { - KILE_DEBUG_MAIN << "===tool created with name " << tool->name(); - if(!(manager()->info()->watchFile() && tool->isViewer())) { // FIXME: why this? - KILE_DEBUG_MAIN << "\tqueueing " << tl << "(" << cfg << ") with " << source(); - m_tools << tool; - } - else { - delete tool; - } - } - else { - m_unknownToolSpec = fullToolSpec; - qDeleteAll(m_tools); - m_tools.clear(); - return; - } - } - } - - int Sequence::run() - { - KILE_DEBUG_MAIN << "==KileTool::Sequence::run()=================="; - - determineSource(); - if (!checkSource()) { - // tools in 'm_tools' will be deleted in the destructor - return NoValidSource; - } - - if(!m_unknownToolSpec.isEmpty()) { - // 'm_tools' is empty - sendMessage(Error, i18n("Unknown tool %1.", m_unknownToolSpec)); - emit(done(this, Failed, m_childToolSpawned)); - return ConfigureFailed; - } - - for(QLinkedList::iterator i = m_tools.begin(); i != m_tools.end(); ++i) { - Base *tool = *i; - tool->setSource(source()); - - // if we are running a 'LaTeX' tool here, we still have to set the - // appropriate LaTeXOutputHandler - { - LaTeX *latex = dynamic_cast(tool); - if(latex && m_latexOutputHandler) { - latex->setLaTeXOutputHandler(m_latexOutputHandler); - } - } - - manager()->run(tool); - } - - m_tools.clear(); // the tools will be deleted by the tool manager from now on - emit(done(this, Silent, m_childToolSpawned)); - - return Success; - } +Base::Base(const QString &name, Manager *manager, bool prepare /* = true */) : + QObject(manager), // ensure that they are deleted whenever the tool manager gets deleted + m_launcher(Q_NULLPTR), + m_quickie(false), + m_isPartOfLivePreview(false), + m_manager(manager), + m_name(name), + m_bPrepareToRun(prepare), + m_texInputs(KileConfig::teXPaths()), + m_bibInputs(KileConfig::bibInputPaths()), + m_bstInputs(KileConfig::bstInputPaths()), + m_childToolSpawned(false), + m_toolResult(-1) +{ + // WARNING: 'NeedSaveAll' is currently needed to indicate to the tool manager that parsing has to be finished + // before it launches this tool! This is important to ensure that the right master document is used + // in the case of projects, for example. + m_flags = NeedTargetDirExec | NeedTargetDirWrite | NeedActiveDoc | NeedMasterDoc | NoUntitledDoc | NeedSourceExists | NeedSourceRead | NeedSaveAll; + + setMsg(NeedTargetDirExec, ki18n("Could not change to the folder %1.")); + setMsg(NeedTargetDirWrite, ki18n("The folder %1 is not writable, therefore %2 will not be able to save its results.")); + setMsg(NeedTargetExists, ki18n("The file %1/%2 does not exist. If this is unexpected, check the file permissions.")); + setMsg(NeedTargetRead, ki18n("The file %1/%2 is not readable. If this is unexpected, check the file permissions.")); + setMsg(NeedActiveDoc, ki18n("Could not determine on which file to run %1, because there is no active document.")); + setMsg(NeedMasterDoc, ki18n("Could not determine the master file for this document.")); + setMsg(NoUntitledDoc, ki18n("Please save the untitled document first.")); + setMsg(NeedSourceExists, ki18n("The file %1 does not exist.")); + setMsg(NeedSourceRead, ki18n("The file %1 is not readable.")); + + m_bPrepared = false; +} + +Base::~Base() +{ + KILE_DEBUG_MAIN << "DELETING TOOL: " << name() << this; + emit(aboutToBeDestroyed(this)); + delete m_launcher; +} + +QString Base::source(bool absolute /* = true */) const +{ + if (m_source.isEmpty()) { + return QString(); + } + + QString src = m_source; + if (absolute) { + src = m_basedir + '/' + src; + } + + return src; +} + +void Base::setMsg(long n, const KLocalizedString& msg) +{ + m_messages[n] = msg; +} + +void Base::translate(QString &str, bool quoteForShell) +{ + QHashIterator it(paramDict()); + while(it.hasNext()) { + it.next(); + QString value; + // the file names in %AFL are quoted already + if(quoteForShell && it.key() != "%AFL") { + value = KShell::quoteArg(it.value()); + } + else { + value = it.value(); + } + str.replace(it.key(), value); + } +} + +void Base::removeFlag(uint flag) +{ + m_flags &= ~flag; +} + + +bool Base::requestSaveAll() +{ + return (flags() & NeedSaveAll); +} + +void Base::setEntry(const QString& key, const QString& value) +{ + m_entryMap[key] = value; +} + +void Base::prepareToRun() +{ + KILE_DEBUG_MAIN << "==Base::prepareToRun()======="; + + //install a launcher + if (!installLauncher()) + { + m_nPreparationResult = NoLauncherInstalled; + m_bPrepared = false; + return; + } + + if (!determineSource()) + { + m_nPreparationResult = NoValidSource; + m_bPrepared = false; + return; + } + + if (!determineTarget()) + { + m_nPreparationResult = NoValidTarget; + m_bPrepared = false; + return; + } + + if ( m_launcher == 0 ) + { + m_nPreparationResult = NoLauncherInstalled; + m_bPrepared = false; + return; + } + + if(!workingDir().isEmpty()) { + m_launcher->setWorkingDirectory(workingDir()); + } + else { + m_launcher->setWorkingDirectory(baseDir()); + } + + //fill in the dictionary + addDict("%options", m_options); + + m_resolution = KileConfig::dvipngResolution() ; + addDict("%res",m_resolution); + + m_bPrepared = true; + m_nPreparationResult = Running; +} + +int Base::run() +{ + KILE_DEBUG_MAIN << "==KileTool::Base::run()================="; + + if(m_nPreparationResult != 0) { + emit(failedToRun(this, m_nPreparationResult)); + return m_nPreparationResult; + } + + if(!checkSource()) { + emit(failedToRun(this, NoValidSource)); + return NoValidSource; + } + + if(!checkTarget()) { + emit(failedToRun(this, TargetHasWrongPermissions)); + return TargetHasWrongPermissions; + } + + if (!checkPrereqs()) { + emit(failedToRun(this, NoValidPrereqs)); + return NoValidPrereqs; + } + + emit(start(this)); + + if (!m_launcher || !m_launcher->launch()) { + KILE_DEBUG_MAIN << "\tlaunching failed"; + if(!m_launcher) { + emit(failedToRun(this, CouldNotLaunch)); + return CouldNotLaunch; + } + if(!m_launcher->selfCheck()) { + emit(failedToRun(this, SelfCheckFailed)); + return SelfCheckFailed; + } + else { + emit(failedToRun(this, CouldNotLaunch)); + return CouldNotLaunch; + } + } + + KILE_DEBUG_MAIN << "\trunning..."; + + return Running; + +} + +bool Base::determineSource() +{ + QString src = source(); + + // check whether the source has been set already + if(!src.isEmpty()) { + return true; + } + + //the basedir is determined from the current compile target + //determined by getCompileName() + if(src.isEmpty()) { + src = m_ki->getCompileName(); + } + setSource(src); + + return true; +} + +bool Base::checkSource() +{ + //FIXME deal with tools that do not need a source or target (yes they exist) + //Is there an active document? Only check if the source file is not explicitly set. + if((m_source.isEmpty()) && (m_manager->info()->activeTextDocument() == Q_NULLPTR)) { + sendMessage(Error, msg(NeedActiveDoc).subs(name()).toString()); + return false; + } + + if(m_source.isEmpty() && m_manager->info()->activeTextDocument() != Q_NULLPTR) { + if(m_manager->info()->activeTextDocument()->url().isEmpty() + && (flags() & NoUntitledDoc)) { + sendMessage(Error, msg(NoUntitledDoc).toString()); + return false; + } + else { + //couldn't find a source file, huh? + //we know there is an active document, the only reason is could have failed is because + //we couldn't find a LaTeX root document + sendMessage(Error, msg(NeedMasterDoc).toString()); + return false; + } + } + + QFileInfo fi(source()); + if((flags() & NeedSourceExists) && !fi.exists()) { + sendMessage(Error, msg(NeedSourceExists).subs(fi.absoluteFilePath()).toString()); + return false; + } + + if((flags() & NeedSourceRead) && !fi.isReadable()) { + sendMessage(Error, msg(NeedSourceRead).subs(fi.absoluteFilePath()).toString()); + return false; + } + + return true; +} + +void Base::runChildNext(Base *tool, bool block /*= false*/) +{ + m_childToolSpawned = true; + if(isPartOfLivePreview()) { + tool->setPartOfLivePreview(); + } + manager()->runChildNext(this, tool, block); +} + +void Base::setSource(const QString &source, const QString& workingDir) +{ + QFileInfo info(source); + + if(!from().isEmpty()) { + QString src = source; + if(info.suffix().length() > 0) { + src.replace(QRegExp(info.suffix() + '$'), from()); + } + info.setFile(src); + } + + if(!workingDir.isEmpty()) { + setWorkingDir(workingDir); + } + + m_basedir = info.absolutePath(); + m_source = info.fileName(); + m_S = info.completeBaseName(); + + addDict("%dir_base", m_basedir); + addDict("%source", m_source); + addDict("%S",m_S); + + KILE_DEBUG_MAIN << "===KileTool::Base::setSource()=============="; + KILE_DEBUG_MAIN << "using " << source; + KILE_DEBUG_MAIN << "source="< 0) { + m_target = S() + '.' + to(); + } + else { + m_target = source(false); + } + } + + if(m_relativedir.isEmpty() && (!readEntry("relDir").isEmpty())) { + m_relativedir = readEntry("relDir"); + } + + QUrl url; + if(!m_targetdir.isEmpty()) { + url = QUrl::fromLocalFile(m_targetdir); + } + else if(!m_workingDir.isEmpty()) { + url = QUrl::fromLocalFile(m_workingDir); + } + else { + url = QUrl::fromLocalFile(m_basedir); + } + url = url.adjusted(QUrl::StripTrailingSlash); + url.setPath(QDir::cleanPath(url.path() + '/' + m_relativedir)); + m_targetdir = url.toLocalFile(); + + setTarget(m_target); + setTargetDir(m_targetdir); + + KILE_DEBUG_MAIN << "==KileTool::Base::determineTarget()========="; + KILE_DEBUG_MAIN << "\tm_targetdir=" << m_targetdir; + KILE_DEBUG_MAIN << "\tm_target=" << m_target; + + return true; +} + +bool Base::checkTarget() +{ + //check if the target directory is accessible + QFileInfo info(m_targetdir); + + if((flags() & NeedTargetDirExec ) && (!info.isExecutable())) { + sendMessage(Error, msg(NeedTargetDirExec).subs(m_targetdir).toString()); + return false; + } + + if((flags() & NeedTargetDirWrite) && (!info.isWritable())) { + sendMessage(Error, msg(NeedTargetDirWrite).subs(m_targetdir).subs(m_name).toString()); + return false; + } + + info.setFile(m_targetdir + '/' + m_target); + + if((flags() & NeedTargetExists) && (!info.exists())) { + sendMessage(Error, msg(NeedTargetExists).subs(m_targetdir).subs(m_target).toString()); + return false; + } + + if((flags() & NeedTargetRead) && (!info.isReadable())) { + sendMessage(Error, msg(NeedTargetRead).subs(m_targetdir).subs(m_target).toString()); + return false; + } + + return true; +} + +void Base::setTarget(const QString &target) +{ + m_target = target; + addDict("%target", m_target); +} + +void Base::setTargetDir(const QString &target) +{ + m_targetdir = target; + addDict("%dir_target", m_targetdir); +} + +void Base::setTargetPath(const QString &target) +{ + QFileInfo fi(target); + setTarget(fi.fileName()); + setTargetDir(fi.absolutePath()); +} + +bool Base::checkPrereqs() +{ + return true; +} + +void Base::stop() +{ + if (m_launcher) { + m_launcher->kill(); + } + + emit(done(this, Aborted, m_childToolSpawned)); +} + +bool Base::finish(int result) +{ + KILE_DEBUG_MAIN << "==KileTool::Base::finish()=============="; + if (sender()) + { + KILE_DEBUG_MAIN << "\tcalled by " << sender()->objectName() << " " << sender()->metaObject()->className(); + } + + if ( result == Aborted ) + sendMessage(Error, "Aborted"); + + if ( result == Success ) + sendMessage(Info,"Done!"); + + KILE_DEBUG_MAIN << "\temitting done(KileTool::Base*, int) " << name(); + emit(done(this, result, m_childToolSpawned)); + + //we will only get here if the done() signal is not connected to the manager (who will destroy this object) + if (result == Success) { + return true; + } + else { + return false; + } +} + +void Base::installLaTeXOutputParserResult(int nErrors, int nWarnings, int nBadBoxes, const LatexOutputInfoArray& outputList, + const QString& logFile) +{ + m_nErrors = nErrors; + m_nWarnings = nWarnings; + m_nBadBoxes = nBadBoxes; + m_latexOutputInfoList = outputList; + m_logFile = logFile; + + latexOutputParserResultInstalled(); +} + +void Base::latexOutputParserResultInstalled() +{ + finish(Success); +} + +void Base::installLauncher(Launcher *lr) +{ + if(m_launcher != lr) + delete m_launcher; + + m_launcher = lr; + //lr->setParamDict(paramDict()); + lr->setTool(this); + + connect(lr, SIGNAL(message(int, const QString &)), this, SLOT(sendMessage(int, const QString &))); + connect(lr, SIGNAL(output(const QString &)), this, SLOT(filterOutput(const QString &))); + connect(lr, SIGNAL(done(int)), this, SLOT(finish(int))); +} + +bool Base::installLauncher() +{ + if (m_launcher) { + return true; + } + + QString type = readEntry("type"); + KILE_DEBUG_MAIN << "installing launcher of type " << type; + Launcher *lr = Q_NULLPTR; + + if ( type == "Process" ) { + lr = new ProcessLauncher(); + } + else if ( type == "Konsole" ) { + lr = new KonsoleLauncher(); + } + else if ( type == "DocumentViewer" ) { + lr = new DocumentViewerLauncher(); + } + + if (lr) { + installLauncher(lr); + return true; + } + else { + m_launcher = Q_NULLPTR; + return false; + } +} + +void Base::setupAsChildTool(KileTool::Base *child) +{ + Q_UNUSED(child); +} + +void Base::sendMessage(int type, const QString &msg) +{ + emit(message(type, msg, name())); +} + +void Base::filterOutput(const QString & str) +{ + //here you have the change to filter the output and do some error extraction for example + //this should be done by a OutputFilter class + + //idea: store the buffer until a complete line (or more) has been received then parse these lines + //just send the buf immediately to the output widget, the results of the parsing are displayed in + //the log widget anyway. + emit(output(str)); +} + +bool Base::addDict(const QString & key, const QString & value) +{ + bool e = !(paramDict().contains(key)); + paramDict()[key] = value; + return e; +} + +bool Base::needsUpdate(const QString &target, const QString &source) +{ + KILE_DEBUG_MAIN << "==Base::needsUpdate(" << target << "," << source; + QFileInfo targetinfo(target); + QFileInfo sourceinfo(source); + QDateTime currDateTime = QDateTime::currentDateTime(); + + if(!(sourceinfo.exists() && sourceinfo.isReadable())) { + KILE_DEBUG_MAIN << "\treturning false: source does not exist"; + return false; + } + + if(!targetinfo.exists()) { + KILE_DEBUG_MAIN << "\treturning true: target does not exist"; + return true; + } + + KILE_DEBUG_MAIN << "\ttarget: " << targetinfo.lastModified().toString(); + KILE_DEBUG_MAIN << "\tsource: " << sourceinfo.lastModified().toString(); + + if(targetinfo.lastModified() > currDateTime) { + KILE_DEBUG_MAIN << "targetinfo.lastModifiedTime() is in the future"; + return false; + } + else if(sourceinfo.lastModified() > currDateTime) { + KILE_DEBUG_MAIN << "sourceinfo.lastModifiedTime() is in the future"; + return false; + } + + KILE_DEBUG_MAIN << "\treturning " << (targetinfo.lastModified() < sourceinfo.lastModified()); + return targetinfo.lastModified() < sourceinfo.lastModified(); +} + +Compile::Compile(const QString &name, Manager * manager, bool prepare /*= true*/) + : Base(name, manager, prepare) +{ + setFlags( flags() | NeedTargetDirExec | NeedTargetDirWrite); +} + +Compile::~Compile() +{} + +bool Compile::checkSource() +{ + if ( !Base::checkSource() ) return false; + + bool isRoot = true; + KileDocument::TextInfo *docinfo = manager()->info()->docManager()->textInfoFor(source()); + if (docinfo) { + isRoot = (readEntry("checkForRoot") == "yes") ? docinfo->isLaTeXRoot() : true; + } + + if (!isRoot) + { + return manager()->queryContinue(i18n("The document %1 is not a LaTeX root document; continue anyway?", source()), i18n("Continue?")); + } + + return true; +} + +View::View(const QString &name, Manager * manager, bool prepare /*= true*/) + : Base(name, manager, prepare) +{ + setFlags(NeedTargetDirExec | NeedTargetExists | NeedTargetRead); + + KILE_DEBUG_MAIN << "View: flag " << (flags() & NeedTargetExists); + setMsg(NeedTargetExists, ki18n("The file %1/%2 does not exist; did you compile the source file?")); +} + +View::~View() +{ +} + + +Archive::Archive(const QString &name, Manager * manager, bool prepare /* = true*/) + : Base(name, manager,prepare) +{ + setFlags( NeedTargetDirExec | NeedTargetDirWrite ); +} + +Archive::~Archive() +{} + +bool Archive::checkPrereqs() +{ + if(!m_project) { + sendMessage(Error,i18n("The current document is not associated to a project. Please activate a document that is associated to the project you want to archive, then choose Archive again.")); + return false; + } + else if(m_fileList.isEmpty()) { + sendMessage(Error, i18n("No files have been chosen for archiving.")); + return false; + } + else { + return true; + } +} + +void Archive::setSource(const QString &source, const QString& workingDir) +{ + Q_UNUSED(workingDir); + QUrl url = QUrl::fromLocalFile(source); + m_project = manager()->info()->docManager()->projectFor(url); + if ( !m_project ) + m_project = manager()->info()->docManager()->activeProject(); + if ( !m_project ) + m_project = manager()->info()->docManager()->selectProject(i18n("Archive Project")); + if ( !m_project ) + { + Base::setSource(source); + return; + } + + manager()->info()->docManager()->projectSave(m_project); + Base::setSource(m_project->url().toLocalFile()); + m_fileList = m_project->archiveFileList(); + + addDict("%AFL", m_fileList); + + KILE_DEBUG_MAIN << "===KileTool::Archive::setSource("<< source << ")=============="; + KILE_DEBUG_MAIN << "m_fileList="<getCompileName(false, &h); + + setSource(src); + setLaTeXOutputHandler(h); + + return true; +} + +bool Sequence::requestSaveAll() +{ + // if one of the tools in the sequence requests save-all, then we also + // request it + for(QLinkedList::iterator i = m_tools.begin(); i != m_tools.end(); ++i) { + if((*i)->requestSaveAll()) { + return true; + } + } + + return false; +} + +void Sequence::setupSequenceTools() +{ + QStringList toolNameList = readEntry("sequence").split(','); + QString tl, cfg; + Base *tool; + for(QStringList::iterator i = toolNameList.begin(); i != toolNameList.end(); ++i) { + QString fullToolSpec = (*i).trimmed(); + extract(fullToolSpec, tl, cfg); + + tool = manager()->createTool(tl, cfg, false); // create tool with delayed preparation + if (tool) { + KILE_DEBUG_MAIN << "===tool created with name " << tool->name(); + if(!(manager()->info()->watchFile() && tool->isViewer())) { // FIXME: why this? + KILE_DEBUG_MAIN << "\tqueueing " << tl << "(" << cfg << ") with " << source(); + m_tools << tool; + } + else { + delete tool; + } + } + else { + m_unknownToolSpec = fullToolSpec; + qDeleteAll(m_tools); + m_tools.clear(); + return; + } + } +} + +int Sequence::run() +{ + KILE_DEBUG_MAIN << "==KileTool::Sequence::run()=================="; + + determineSource(); + if (!checkSource()) { + // tools in 'm_tools' will be deleted in the destructor + return NoValidSource; + } + + if(!m_unknownToolSpec.isEmpty()) { + // 'm_tools' is empty + sendMessage(Error, i18n("Unknown tool %1.", m_unknownToolSpec)); + emit(done(this, Failed, m_childToolSpawned)); + return ConfigureFailed; + } + + for(QLinkedList::iterator i = m_tools.begin(); i != m_tools.end(); ++i) { + Base *tool = *i; + tool->setSource(source()); + + // if we are running a 'LaTeX' tool here, we still have to set the + // appropriate LaTeXOutputHandler + { + LaTeX *latex = dynamic_cast(tool); + if(latex && m_latexOutputHandler) { + latex->setLaTeXOutputHandler(m_latexOutputHandler); + } + } + + manager()->run(tool); + } + + m_tools.clear(); // the tools will be deleted by the tool manager from now on + emit(done(this, Silent, m_childToolSpawned)); + + return Success; +} } diff --git a/src/kiletool.h b/src/kiletool.h index 6d587d45..4b1176a0 100644 --- a/src/kiletool.h +++ b/src/kiletool.h @@ -1,405 +1,471 @@ /**************************************************************************************** Copyright (C) 2003 by Jeroen Wijnhout (Jeroen.Wijnhout@kdemail.net) (C) 2011-2013 by Michel Ludwig (michel.ludwig@kdemail.net) ****************************************************************************************/ /*************************************************************************** * * * 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. * * * ***************************************************************************/ #ifndef KILETOOL_H #define KILETOOL_H #include #include #include #include #include #include #include #include "kilelauncher.h" #include "outputinfo.h" class KConfig; class KileInfo; class KileProject; namespace KileTool { - typedef QMap Config; - - class Factory; - class Manager; - - /** - * A class that defines a general tool (latex, dvips etc.) to be launched from - * within Kile. - * - * @author Jeroen Wijnhout - **/ - - class Base : public QObject - { - Q_OBJECT - friend class KileTool::Factory; - - // only the factory can create tools - protected: - Base(const QString &name, Manager *manager, bool prepare = true); - public: - ~Base(); - - /** - * Sets the KileInfo object, this is already taken care of by the Manager. - **/ - void setInfo(KileInfo *ki) { m_ki = ki; } - - /** - * Sets the KConfig object, this is already taken care of by the Manager. - **/ - void setConfig(KConfig *config) { m_config = config; } - - /** - * @returns the Manager object for this tool. - **/ - Manager* manager() const { return m_manager; } - - /** - * @returns a short descriptive name for this tool. - **/ - const QString& name() const { return m_name; } - - /** - * Allows you to set the source file and working directory explicitly (absolute path). - **/ - virtual void setSource(const QString& source, const QString& workingDir = ""); - - /** - * @returns the source file that is used to run the tool on. - **/ - QString source(bool absolute = true) const; - - QString S() const { return m_S; } - QString baseDir() const { return m_basedir; } - QString relativeDir() const { return m_relativedir; } - QString targetDir() const { return m_targetdir; } - inline QString from() const { return readEntry("from"); } - inline QString to() const { return readEntry("to"); } - QString target() const { return m_target; } - QString options() const { return m_options; } - - QString toolConfig() const { return m_toolConfig; } - - void setOptions(const QString& opt) { m_options = opt; } - - virtual bool isViewer() { return false; } - - void setQuickie() { m_quickie = true; } - bool isQuickie() { return m_quickie; } - - /** - * Returns true iff all documents must be saved before the tool can be launched - **/ - virtual bool requestSaveAll(); - - void setPartOfLivePreview() { m_isPartOfLivePreview = true; } - bool isPartOfLivePreview() const { return m_isPartOfLivePreview; } - - void setTeXInputPaths(const QString& s); - QString teXInputPaths() const; - void setBibInputPaths(const QString& s); - QString bibInputPaths() const; - void setBstInputPaths(const QString& s); - QString bstInputPaths() const; - void copyPaths(Base* tool); - - /** - * Allows you to set the target file explicitly (filename only). - **/ - virtual void setTarget(const QString & target); - virtual void setTargetDir(const QString & target); - virtual void setTargetPath(const QString & target); - - /** - * Sets the target directory relative to the source directory. - **/ - void setRelativeBaseDir(const QString & dir) { m_relativedir = dir; } - - /** - * Installs a launcher object that will be responsible for actually starting the tool. The - * tool can be a command-line tool or a kpart, the KileTool class doesn't need to know - * about the specifics of the launcher. - **/ - void installLauncher(Launcher *lr ); - - /** - * Installs a launcher as indicated by the tool type. This creates a launcher object. - **/ - bool installLauncher(); - - /** - * @returns a pointer to the launcher object, returns 0 if no launcher is installed. - **/ - Launcher *launcher() { return m_launcher; } - - /** - * @returns the working dir for this tool. - **/ - const QString &workingDir() const { return m_workingDir; } - - void setWorkingDir(const QString& s) { m_workingDir = s; } - - /** - * @returns the dictionary that translates the following keys - Example docu: - Consider a file which is called myBestBook.tex which resides in /home/thomas/latex and you compile it with pdflatex to myBestBook.pdf. - - The variables have the following meanings: - %source -> filename with suffix but without path <-> myBestBook.tex - %S -> filename without suffix but without path <-> myBestBook - %dir_base -> path of the source file without filename <-> /home/thomas/latex - %dir_target -> path of the target file without filename, same as %dir_base if no relative path has been set <-> /home/thomas/latex - %target -> target filename without path <-> without filename - - And these are special variables: - %res <-> resolution of the quickpreview action set in configure kile->tools->preview - - %AFL <-> List of all files in a project marked for archiving. You can set the archive flag in the "Files and projects" sidebar using the context menu. - - %absolute_target -> Used in conjunction with Okular to inform it about the cursor position for - the ForwardDVI/PDF feature - - %sourceFileName <-> Source file name (for synchronizing the cursor location with the viewer) - %sourceLine <-> Line in the source file on which the cursor is located (for synchronizing the cursor location with the viewer) - */ - QHash& paramDict() { return m_dictParams; } - - bool addDict(const QString& key, const QString& value); - - void translate(QString &str, bool quoteForShell = false); - - void setFlags(uint flags) { m_flags = flags; } - uint flags() { return m_flags; } - void removeFlag(uint flag); - - void setMsg(long n, const KLocalizedString& msg); - KLocalizedString msg(long n) const { return m_messages[n]; } +typedef QMap Config; - virtual void setupAsChildTool(KileTool::Base *child); +class Factory; +class Manager; - public Q_SLOTS: - void sendMessage(int, const QString &); - virtual void filterOutput(const QString &); - - /** - * Starts the tool. First it performs basic checks (checkPrereqs()), - * if all is well it launches the tool (launch()). After the process has - * exited it calls finish(). - * @return the exit code of the tool (if available) - **/ - virtual int run(); - - /** - * Terminates the running process. - **/ - virtual void stop(); - - /** - * Clean up after the process/lib has finished. - **/ - virtual bool finish(int); - - void installLaTeXOutputParserResult(int nErrors, int nWarnings, int nBadBoxes, const LatexOutputInfoArray& outputList, - const QString& logFile); - - Q_SIGNALS: - void message(int, const QString &, const QString &); - void output(const QString &); - - void start(KileTool::Base*); - void done(KileTool::Base*, int, bool childToolSpawned); - void failedToRun(KileTool::Base*, int); - - void aboutToBeDestroyed(KileTool::Base*); - - public: - void setEntryMap(Config map) { m_entryMap = map; } - void setEntry(const QString& key, const QString& value); - const QString readEntry(const QString& key) const { return m_entryMap[key]; } - - virtual void prepareToRun(); - bool isPrepared() { return m_bPrepared; } - bool needsToBePrepared() { return m_bPrepareToRun; } - - protected: - Launcher *m_launcher; - bool m_quickie; - bool m_isPartOfLivePreview; - - bool needsUpdate(const QString &target, const QString &source); - - /** - * Checks if the prerequisites are in order. - * @returns true if everything is ok, false otherwise. - **/ - virtual bool checkPrereqs(); - - /** - * Determines on which file to run the tool. - **/ - virtual bool determineSource(); - - /** - * Determines the target of the tool (i.e. a DVI for latex, PS for dvips) and - * checks if the target file can be written to the specified location. - **/ - virtual bool determineTarget(); - - /** - * Check if the target dir and file have the correct permissions (according to the flags set). - **/ - virtual bool checkTarget(); - - virtual bool checkSource(); - - void runChildNext(Base *tool, bool block = false); - - void setToolConfig(const QString& config) { m_toolConfig = config; } - - virtual void latexOutputParserResultInstalled(); - - protected: - Manager *m_manager; - KileInfo *m_ki; - KConfig *m_config; - - private: - QString m_name; - QString m_target, m_basedir, m_relativedir, m_targetdir, m_source, m_S, m_workingDir; - QString m_options; - QString m_resolution; - - QString m_message; - - bool m_buildPrereqs; - - QHash m_dictParams; - Config m_entryMap; - - uint m_flags; - int m_nPreparationResult; - bool m_bPrepared; - bool m_bPrepareToRun; - QString m_toolConfig; - - QString m_texInputs, m_bibInputs, m_bstInputs; - - //messages - QMap m_messages; - - protected: - int m_nErrors, m_nWarnings, m_nBadBoxes; - LatexOutputInfoArray m_latexOutputInfoList; - QString m_logFile; - bool m_childToolSpawned; - int m_toolResult; - }; - - /** - * A class that represents a compile tool (such as latex, pdflatex). - **/ - class Compile : public Base - { - friend class KileTool::Factory; - protected: - Compile(const QString &name, Manager * manager, bool prepare = true); - public: - ~Compile(); - - protected: - bool checkSource(); - }; - - /** - * A class that represents a view tool (such as KDVI, gv, etc.). - **/ - class View : public Base - { - friend class KileTool::Factory; - protected: - View(const QString &name, Manager * manager, bool prepare = true); - public: - ~View(); - - bool isViewer() { return true; } - }; - - /** - * A class that represents a conversion tool (such as dvips). - **/ - class Convert : public Base - { - friend class KileTool::Factory; - protected: - Convert(const QString &name, Manager * manager, bool prepare = true); - public: - ~Convert(); - - bool determineSource(); - }; - - /** - * A class that represents a tool like tar, from multiple files to one file - **/ - class Archive: public Base - { - Q_OBJECT - friend class KileTool::Factory; - - protected: - Archive(const QString &name, Manager * manager, bool prepare = true); - public: - ~Archive(); - bool checkPrereqs(); - void setSource(const QString & source, const QString& workingDir = ""); - private: - KileProject *m_project; - QString m_fileList; - }; - - class Sequence : public Base - { - Q_OBJECT - friend class KileTool::Factory; - - bool requestSaveAll(); - - void setupSequenceTools(); - - LaTeXOutputHandler* latexOutputHandler(); - void setLaTeXOutputHandler(LaTeXOutputHandler *h); - - public Q_SLOTS: - int run(); - - protected: - Sequence(const QString &name, Manager *manager, bool prepare = true); - ~Sequence(); - - // will also determine the current LaTeXOutputHandler - bool determineSource(); - - QLinkedList m_tools; - QString m_unknownToolSpec; - LaTeXOutputHandler *m_latexOutputHandler; - }; +/** +* A class that defines a general tool (latex, dvips etc.) to be launched from +* within Kile. +* +* @author Jeroen Wijnhout +**/ + +class Base : public QObject +{ + Q_OBJECT + friend class KileTool::Factory; + + // only the factory can create tools +protected: + Base(const QString &name, Manager *manager, bool prepare = true); +public: + ~Base(); + + /** + * Sets the KileInfo object, this is already taken care of by the Manager. + **/ + void setInfo(KileInfo *ki) { + m_ki = ki; + } + + /** + * Sets the KConfig object, this is already taken care of by the Manager. + **/ + void setConfig(KConfig *config) { + m_config = config; + } + + /** + * @returns the Manager object for this tool. + **/ + Manager* manager() const { + return m_manager; + } + + /** + * @returns a short descriptive name for this tool. + **/ + const QString& name() const { + return m_name; + } + + /** + * Allows you to set the source file and working directory explicitly (absolute path). + **/ + virtual void setSource(const QString& source, const QString& workingDir = ""); + + /** + * @returns the source file that is used to run the tool on. + **/ + QString source(bool absolute = true) const; + + QString S() const { + return m_S; + } + QString baseDir() const { + return m_basedir; + } + QString relativeDir() const { + return m_relativedir; + } + QString targetDir() const { + return m_targetdir; + } + inline QString from() const { + return readEntry("from"); + } + inline QString to() const { + return readEntry("to"); + } + QString target() const { + return m_target; + } + QString options() const { + return m_options; + } + + QString toolConfig() const { + return m_toolConfig; + } + + void setOptions(const QString& opt) { + m_options = opt; + } + + virtual bool isViewer() { + return false; + } + + void setQuickie() { + m_quickie = true; + } + bool isQuickie() { + return m_quickie; + } + + /** + * Returns true iff all documents must be saved before the tool can be launched + **/ + virtual bool requestSaveAll(); + + void setPartOfLivePreview() { + m_isPartOfLivePreview = true; + } + bool isPartOfLivePreview() const { + return m_isPartOfLivePreview; + } + + void setTeXInputPaths(const QString& s); + QString teXInputPaths() const; + void setBibInputPaths(const QString& s); + QString bibInputPaths() const; + void setBstInputPaths(const QString& s); + QString bstInputPaths() const; + void copyPaths(Base* tool); + + /** + * Allows you to set the target file explicitly (filename only). + **/ + virtual void setTarget(const QString & target); + virtual void setTargetDir(const QString & target); + virtual void setTargetPath(const QString & target); + + /** + * Sets the target directory relative to the source directory. + **/ + void setRelativeBaseDir(const QString & dir) { + m_relativedir = dir; + } + + /** + * Installs a launcher object that will be responsible for actually starting the tool. The + * tool can be a command-line tool or a kpart, the KileTool class doesn't need to know + * about the specifics of the launcher. + **/ + void installLauncher(Launcher *lr ); + + /** + * Installs a launcher as indicated by the tool type. This creates a launcher object. + **/ + bool installLauncher(); + + /** + * @returns a pointer to the launcher object, returns 0 if no launcher is installed. + **/ + Launcher *launcher() { + return m_launcher; + } + + /** + * @returns the working dir for this tool. + **/ + const QString &workingDir() const { + return m_workingDir; + } + + void setWorkingDir(const QString& s) { + m_workingDir = s; + } + + /** + * @returns the dictionary that translates the following keys + Example docu: + Consider a file which is called myBestBook.tex which resides in /home/thomas/latex and you compile it with pdflatex to myBestBook.pdf. + + The variables have the following meanings: + %source -> filename with suffix but without path <-> myBestBook.tex + %S -> filename without suffix but without path <-> myBestBook + %dir_base -> path of the source file without filename <-> /home/thomas/latex + %dir_target -> path of the target file without filename, same as %dir_base if no relative path has been set <-> /home/thomas/latex + %target -> target filename without path <-> without filename + + And these are special variables: + %res <-> resolution of the quickpreview action set in configure kile->tools->preview + + %AFL <-> List of all files in a project marked for archiving. You can set the archive flag in the "Files and projects" sidebar using the context menu. + + %absolute_target -> Used in conjunction with Okular to inform it about the cursor position for + the ForwardDVI/PDF feature + + %sourceFileName <-> Source file name (for synchronizing the cursor location with the viewer) + %sourceLine <-> Line in the source file on which the cursor is located (for synchronizing the cursor location with the viewer) + */ + QHash& paramDict() { + return m_dictParams; + } + + bool addDict(const QString& key, const QString& value); + + void translate(QString &str, bool quoteForShell = false); + + void setFlags(uint flags) { + m_flags = flags; + } + uint flags() { + return m_flags; + } + void removeFlag(uint flag); + + void setMsg(long n, const KLocalizedString& msg); + KLocalizedString msg(long n) const { + return m_messages[n]; + } + + virtual void setupAsChildTool(KileTool::Base *child); + +public Q_SLOTS: + void sendMessage(int, const QString &); + virtual void filterOutput(const QString &); + + /** + * Starts the tool. First it performs basic checks (checkPrereqs()), + * if all is well it launches the tool (launch()). After the process has + * exited it calls finish(). + * @return the exit code of the tool (if available) + **/ + virtual int run(); + + /** + * Terminates the running process. + **/ + virtual void stop(); + + /** + * Clean up after the process/lib has finished. + **/ + virtual bool finish(int); + + void installLaTeXOutputParserResult(int nErrors, int nWarnings, int nBadBoxes, const LatexOutputInfoArray& outputList, + const QString& logFile); + +Q_SIGNALS: + void message(int, const QString &, const QString &); + void output(const QString &); + + void start(KileTool::Base*); + void done(KileTool::Base*, int, bool childToolSpawned); + void failedToRun(KileTool::Base*, int); + + void aboutToBeDestroyed(KileTool::Base*); + +public: + void setEntryMap(Config map) { + m_entryMap = map; + } + void setEntry(const QString& key, const QString& value); + const QString readEntry(const QString& key) const { + return m_entryMap[key]; + } + + virtual void prepareToRun(); + bool isPrepared() { + return m_bPrepared; + } + bool needsToBePrepared() { + return m_bPrepareToRun; + } + +protected: + Launcher *m_launcher; + bool m_quickie; + bool m_isPartOfLivePreview; + + bool needsUpdate(const QString &target, const QString &source); + + /** + * Checks if the prerequisites are in order. + * @returns true if everything is ok, false otherwise. + **/ + virtual bool checkPrereqs(); + + /** + * Determines on which file to run the tool. + **/ + virtual bool determineSource(); + + /** + * Determines the target of the tool (i.e. a DVI for latex, PS for dvips) and + * checks if the target file can be written to the specified location. + **/ + virtual bool determineTarget(); + + /** + * Check if the target dir and file have the correct permissions (according to the flags set). + **/ + virtual bool checkTarget(); + + virtual bool checkSource(); + + void runChildNext(Base *tool, bool block = false); + + void setToolConfig(const QString& config) { + m_toolConfig = config; + } + + virtual void latexOutputParserResultInstalled(); + +protected: + Manager *m_manager; + KileInfo *m_ki; + KConfig *m_config; + +private: + QString m_name; + QString m_target, m_basedir, m_relativedir, m_targetdir, m_source, m_S, m_workingDir; + QString m_options; + QString m_resolution; + + QString m_message; + + bool m_buildPrereqs; + + QHash m_dictParams; + Config m_entryMap; + + uint m_flags; + int m_nPreparationResult; + bool m_bPrepared; + bool m_bPrepareToRun; + QString m_toolConfig; + + QString m_texInputs, m_bibInputs, m_bstInputs; + + //messages + QMap m_messages; + +protected: + int m_nErrors, m_nWarnings, m_nBadBoxes; + LatexOutputInfoArray m_latexOutputInfoList; + QString m_logFile; + bool m_childToolSpawned; + int m_toolResult; +}; + +/** + * A class that represents a compile tool (such as latex, pdflatex). + **/ +class Compile : public Base +{ + friend class KileTool::Factory; +protected: + Compile(const QString &name, Manager * manager, bool prepare = true); +public: + ~Compile(); + +protected: + bool checkSource(); +}; + +/** + * A class that represents a view tool (such as KDVI, gv, etc.). + **/ +class View : public Base +{ + friend class KileTool::Factory; +protected: + View(const QString &name, Manager * manager, bool prepare = true); +public: + ~View(); + + bool isViewer() { + return true; + } +}; + +/** + * A class that represents a conversion tool (such as dvips). + **/ +class Convert : public Base +{ + friend class KileTool::Factory; +protected: + Convert(const QString &name, Manager * manager, bool prepare = true); +public: + ~Convert(); + + bool determineSource(); +}; + +/** + * A class that represents a tool like tar, from multiple files to one file + **/ +class Archive: public Base +{ + Q_OBJECT + friend class KileTool::Factory; + +protected: + Archive(const QString &name, Manager * manager, bool prepare = true); +public: + ~Archive(); + bool checkPrereqs(); + void setSource(const QString & source, const QString& workingDir = ""); +private: + KileProject *m_project; + QString m_fileList; +}; + +class Sequence : public Base +{ + Q_OBJECT + friend class KileTool::Factory; + + bool requestSaveAll(); + + void setupSequenceTools(); + + LaTeXOutputHandler* latexOutputHandler(); + void setLaTeXOutputHandler(LaTeXOutputHandler *h); + +public Q_SLOTS: + int run(); + +protected: + Sequence(const QString &name, Manager *manager, bool prepare = true); + ~Sequence(); + + // will also determine the current LaTeXOutputHandler + bool determineSource(); + + QLinkedList m_tools; + QString m_unknownToolSpec; + LaTeXOutputHandler *m_latexOutputHandler; +}; } #endif diff --git a/src/kiletool_enums.h b/src/kiletool_enums.h index 734fad22..ab166abd 100644 --- a/src/kiletool_enums.h +++ b/src/kiletool_enums.h @@ -1,37 +1,38 @@ /************************************************************************************ begin : mon 3-11 20:40:00 CEST 2003 copyright : (C) 2003 by Jeroen Wijnhout (Jeroen.Wijnhout@kdemail.net) ************************************************************************************/ /*************************************************************************** * * * 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. * * * ***************************************************************************/ #ifndef KILETOOL_ENUMS_H #define KILETOOL_ENUMS_H #define OKULAR_LIBRARY_NAME "okularpart" namespace KileTool { - /** - * KileTool can send several types of messages - * Error - * Warning - * Info - **/ - enum { Error = 0, Warning, Info, ProblemError, ProblemWarning, ProblemBadBox }; +/** + * KileTool can send several types of messages + * Error + * Warning + * Info + **/ +enum { Error = 0, Warning, Info, ProblemError, ProblemWarning, ProblemBadBox }; - enum { NeedTargetDirExec = 0x01, NeedTargetDirWrite = 0x02, NeedTargetExists = 0x04, NeedTargetRead = 0x08, - NeedActiveDoc = 0x10, NeedMasterDoc = 0x20, NoUntitledDoc = 0x40, NeedSourceExists = 0x80, NeedSourceRead = 0x100, NeedSaveAll = 0x200 }; +enum { NeedTargetDirExec = 0x01, NeedTargetDirWrite = 0x02, NeedTargetExists = 0x04, NeedTargetRead = 0x08, + NeedActiveDoc = 0x10, NeedMasterDoc = 0x20, NoUntitledDoc = 0x40, NeedSourceExists = 0x80, NeedSourceRead = 0x100, NeedSaveAll = 0x200 + }; - enum { Running = 0, ConfigureFailed, NoLauncherInstalled, NoValidTarget, NoValidSource, TargetHasWrongPermissions, NoValidPrereqs, CouldNotLaunch, SelfCheckFailed}; - - enum { Success = 0, Failed = 1, AbnormalExit = 2, Aborted = 3, Silent = 4 }; +enum { Running = 0, ConfigureFailed, NoLauncherInstalled, NoValidTarget, NoValidSource, TargetHasWrongPermissions, NoValidPrereqs, CouldNotLaunch, SelfCheckFailed}; + +enum { Success = 0, Failed = 1, AbnormalExit = 2, Aborted = 3, Silent = 4 }; } #endif diff --git a/src/kiletoolmanager.cpp b/src/kiletoolmanager.cpp index 041d1e87..385f3383 100644 --- a/src/kiletoolmanager.cpp +++ b/src/kiletoolmanager.cpp @@ -1,817 +1,817 @@ /************************************************************************************** Copyright (C) 2003 by Jeroen Wijnhout (Jeroen.Wijnhout@kdemail.net) 2011-2017 by Michel Ludwig (michel.ludwig@kdemail.net) **************************************************************************************/ /*************************************************************************** * * * 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. * * * ***************************************************************************/ #include "kiletoolmanager.h" #include #include #include #include #include #include #include #include #include #include #include #include "configurationmanager.h" #include "errorhandler.h" #include "kileconfig.h" #include "kiledebug.h" #include "kiledocmanager.h" #include "kileinfo.h" #include "kileproject.h" #include "kilestdtools.h" #include "kiletool_enums.h" #include "parser/parsermanager.h" #include "widgets/logwidget.h" #include "widgets/outputview.h" #include "widgets/sidebar.h" namespace KileTool { - QueueItem::QueueItem(Base *tool, bool block) : m_tool(tool), m_bBlock(block) - { - } - - QueueItem::~QueueItem() - { - } - - Base* Queue::tool() const - { - if(count() > 0 && head()) { - return head()->tool(); - } - else { - return 0; - } - } - - bool Queue::shouldBlock() const - { - if(count() > 0 && head()) { - return head()->shouldBlock(); - } - else { - return false; - } - } - - void Queue::enqueueNext(QueueItem *item) - { - if(count() < 2) { - enqueue(item); - } - else { - QueueItem *headitem = dequeue(); - Queue *oldqueue = new Queue(*this); - - clear(); - KILE_DEBUG_MAIN << "\tenqueueing: " << headitem->tool()->name() << endl; - enqueue(headitem); - KILE_DEBUG_MAIN << "\tenqueueing: " << item->tool()->name() << endl; - enqueue(item); - while(!oldqueue->isEmpty()) { - KILE_DEBUG_MAIN << "\tenqueueing: " << oldqueue->head()->tool()->name() << endl; - enqueue(oldqueue->dequeue()); - } - } - } - - Manager::Manager(KileInfo *ki, KConfig *config, KileWidget::OutputView *output, QStackedWidget *stack, QAction *stop, uint to, KActionCollection *ac) : - m_ki(ki), - m_config(config), - m_output(output), - m_stack(stack), - m_stop(stop), - m_bClear(true), - m_nLastResult(Success), - m_nTimeout(to), - m_bibliographyBackendSelectAction(Q_NULLPTR) - { - connect(m_ki->parserManager(), SIGNAL(documentParsingComplete()), this, SLOT(handleDocumentParsingComplete())); - - connect(this, SIGNAL(childToolSpawned(KileTool::Base*,KileTool::Base*)), - m_ki->errorHandler(), SLOT(handleSpawnedChildTool(KileTool::Base*, KileTool::Base*))); - - m_timer = new QTimer(this); - connect(m_timer, SIGNAL(timeout()), this, SLOT(enableClear())); - connect(stop, SIGNAL(triggered()), this, SLOT(stop())); - connect(stop, SIGNAL(destroyed(QObject*)), this, SLOT(stopActionDestroyed())); - - connect(m_ki->errorHandler(), SIGNAL(currentLaTeXOutputHandlerChanged(LaTeXOutputHandler*)), SLOT(currentLaTeXOutputHandlerChanged(LaTeXOutputHandler*))); - - //create actions must be invoked before buildBibliographyBackendSelection()! - createActions(ac); - buildBibliographyBackendSelection(); - - connect(m_ki->configurationManager(), SIGNAL(configChanged()), SLOT(buildBibliographyBackendSelection())); - } - - Manager::~Manager() - { - KILE_DEBUG_MAIN; - - for(QQueue::iterator i = m_queue.begin(); i != m_queue.end(); ++i) { - // this will also stop any running processes - delete (*i)->tool(); - delete (*i); - } - // tools have the tool manager as parent; so, all remaining tools will be deleted - // after this, i.e. those that were scheduled for deletion via 'deleteLater' but - // are no longer member of the queue - } - - bool Manager::shouldBlock() - { - return m_queue.shouldBlock(); - } - - // in some cases the pointer m_stop might not be valid, therefore this helper function comes in handy - void Manager::setEnabledStopButton(bool state){ - - if(m_stop){ - m_stop->setEnabled(state); - } - } - - void Manager::enableClear() - { - m_bClear = true; - } - - bool Manager::queryContinue(const QString & question, const QString & caption /*= QString()*/) - { - return (KMessageBox::warningContinueCancel(m_stack, question, caption, KStandardGuiItem::cont(), KStandardGuiItem::no(), "showNotALaTeXRootDocumentWarning") == KMessageBox::Continue); - } - - void Manager::run(Base *tool) - { - // if the tool requests a save-all operation, we wait for the parsing to - // be finished before launching it - if(!tool->requestSaveAll() || m_ki->parserManager()->isDocumentParsingComplete()) { - // parsing done, we can start the tool immediately - runImmediately(tool); - return; - } - connect(tool, SIGNAL(aboutToBeDestroyed(KileTool::Base*)), - this, SLOT(toolScheduledAfterParsingDestroyed(KileTool::Base*)), Qt::UniqueConnection); - if(!m_toolsScheduledAfterParsingList.contains(tool)) { - m_toolsScheduledAfterParsingList.push_back(tool); - } - } - - void Manager::toolScheduledAfterParsingDestroyed(KileTool::Base *tool) - { - m_toolsScheduledAfterParsingList.removeAll(tool); - } - - void Manager::handleDocumentParsingComplete() - { - Q_FOREACH(Base *tool, m_toolsScheduledAfterParsingList) { - disconnect(tool, SIGNAL(aboutToBeDestroyed(KileTool::Base*)), - this, SLOT(toolScheduledAfterParsingDestroyed(KileTool::Base*))); - runImmediately(tool); - } - m_toolsScheduledAfterParsingList.clear(); - } - - int Manager::runImmediately(Base *tool, bool insertNext /*= false*/, bool block /*= false*/, Base *parent /*= Q_NULLPTR*/) - { - KILE_DEBUG_MAIN << "==KileTool::Manager::runImmediately(Base *)============" << endl; - if(m_bClear && (m_queue.count() == 0)) { - m_ki->errorHandler()->clearMessages(); - m_output->clear(); - } - - if(dynamic_cast(tool)) { - connect(tool, SIGNAL(done(KileTool::Base*, int, bool)), - m_ki->errorHandler(), SLOT(handleLaTeXToolDone(KileTool::Base*, int, bool))); - } - - if(tool->needsToBePrepared()) { - tool->prepareToRun(); - } - - //FIXME: shouldn't restart timer if a Sequence command takes longer than the 10 secs - //restart timer, so we only clear the logs if a tool is started after 10 sec. - m_bClear = false; - m_timer->start(m_nTimeout); - - if(insertNext) { - m_queue.enqueueNext(new QueueItem(tool, block)); - } - else { - m_queue.enqueue(new QueueItem(tool, block)); - } - - if(parent) { - emit(childToolSpawned(parent,tool)); - } - - KILE_DEBUG_MAIN << "\tin queue: " << m_queue.count() << endl; - if(m_queue.count() == 1) { - return runNextInQueue(); - } - else if(m_queue.count() > 1) { - return Running; - } - else { - return ConfigureFailed; - } - } - - int Manager::runChildNext(Base *parent, Base *tool, bool block /*= false*/) - { - parent->setupAsChildTool(tool); - - return runImmediately(tool, true, block, parent); - } - - int Manager::runNextInQueue() - { - Base *head = m_queue.tool(); - if(head) { - if (m_ki->errorHandler()->areMessagesShown()) { - m_ki->errorHandler()->addEmptyLineToMessages(); - } - - if(!head->isPrepared()) { - head->prepareToRun(); - } - - int status; - if((status=head->run()) != Running) { //tool did not even start, clear queue - stop(); - for(QQueue::iterator i = m_queue.begin(); i != m_queue.end(); ++i) { - (*i)->tool()->deleteLater(); - delete (*i); - } - m_queue.clear(); - return status; - } - - m_ki->errorHandler()->startToolLogOutput(); - emit(toolStarted()); - - return Running; - } - - return ConfigureFailed; - } - - Base* Manager::createTool(const QString& name, const QString &cfg, bool prepare) - { - if(!m_factory) { - m_ki->errorHandler()->printMessage(Error, i18n("No factory installed, contact the author of Kile.")); - return Q_NULLPTR; - } - - Base* pTool = m_factory->create(name, cfg, prepare); - if(!pTool) { - m_ki->errorHandler()->printMessage(Error, i18n("Unknown tool %1.", name)); - return Q_NULLPTR; - } - initTool(pTool); - return pTool; - } - - void Manager::initTool(Base *tool) - { - tool->setInfo(m_ki); - tool->setConfig(m_config); - - connect(tool, SIGNAL(message(int, const QString &, const QString &)), m_ki->errorHandler(), SLOT(printMessage(int, const QString &, const QString &))); - connect(tool, SIGNAL(output(const QString &)), m_output, SLOT(receive(const QString &))); - connect(tool, SIGNAL(done(KileTool::Base*,int,bool)), this, SLOT(done(KileTool::Base*, int))); - connect(tool, SIGNAL(start(KileTool::Base*)), this, SLOT(started(KileTool::Base*))); - } - - void Manager::started(Base *tool) - { - KILE_DEBUG_MAIN << "STARTING tool: " << tool->name() << endl; - setEnabledStopButton(true); - - if (tool->isViewer()) { - if(tool == m_queue.tool()) { - m_queue.dequeue(); - } - setEnabledStopButton(false); - QTimer::singleShot(100, this, SLOT(runNextInQueue())); - } - } - - void Manager::stop() - { - setEnabledStopButton(false); - if(m_queue.tool()) { - m_queue.tool()->stop(); - } - } - - void Manager::stopLivePreview() - { - KILE_DEBUG_MAIN; - - Base *tool = m_queue.tool(); - - if(tool && tool->isPartOfLivePreview()) { - setEnabledStopButton(false); - tool->stop(); - } - - deleteLivePreviewToolsFromQueue(); - deleteLivePreviewToolsFromRunningAfterParsingQueue(); - } - - void Manager::stopActionDestroyed() - { - m_stop = Q_NULLPTR; - } - - void Manager::done(KileTool::Base *tool, int result) - { - setEnabledStopButton(false); - m_nLastResult = result; - - m_ki->errorHandler()->endToolLogOutput(); - - if(tool != m_queue.tool()) { //oops, tool finished async, could happen with view tools - tool->deleteLater(); - return; - } - - QueueItem *item = m_queue.dequeue(); - item->tool()->deleteLater(); - delete item; - - if(result == Aborted) { - tool->sendMessage(Error, i18n("Aborted")); - } - - if(result != Success && result != Silent) { //abort execution, delete all remaining tools - if(tool->isPartOfLivePreview()) { // live preview was stopped / aborted - deleteLivePreviewToolsFromQueue(); - // don't forget to run non-live preview tools that are pending - runNextInQueue(); - } - else { - for(QQueue::iterator i = m_queue.begin(); i != m_queue.end(); ++i) { - (*i)->tool()->deleteLater(); - delete (*i); - } - m_queue.clear(); - m_ki->focusLog(); - } - } - else { //continue - runNextInQueue(); - } - } - - void Manager::deleteLivePreviewToolsFromQueue() - { - for(QQueue::iterator i = m_queue.begin(); i != m_queue.end();) { - QueueItem *item = *i; - if(item->tool()->isPartOfLivePreview()) { - i = m_queue.erase(i); - item->tool()->deleteLater(); - delete item; - } - else { - ++i; - } - } - } - - void Manager::deleteLivePreviewToolsFromRunningAfterParsingQueue() - { - for(QQueue::iterator i = m_toolsScheduledAfterParsingList.begin(); i != m_toolsScheduledAfterParsingList.end();) { - Base *tool = *i; - if(tool->isPartOfLivePreview()) { - i = m_toolsScheduledAfterParsingList.erase(i); - delete tool; - } - else { - ++i; - } - } - } - - QString Manager::currentGroup(const QString &name, bool usequeue, bool useproject) - { - if (useproject) { - KileProject *project = m_ki->docManager()->activeProject(); - if(project) { - QString cfg = configName(name, dynamic_cast(project->config())); - if(cfg.length() > 0) { - return groupFor(name, cfg); - } - } - } - if(usequeue && !m_queue.isEmpty() && m_queue.tool() && (m_queue.tool()->name() == name) && (!m_queue.tool()->toolConfig().isEmpty())) { - return groupFor(name, m_queue.tool()->toolConfig()); - } - else { - return groupFor(name, m_config); - } - } - - bool Manager::retrieveEntryMap(const QString & name, Config & map, bool usequeue, bool useproject, const QString & cfg /*= QString()*/) - { - QString group = (cfg.isEmpty()) ? currentGroup(name, usequeue, useproject) : groupFor(name, cfg); - - KILE_DEBUG_MAIN << "==KileTool::Manager::retrieveEntryMap=============" << endl; - KILE_DEBUG_MAIN << "\t" << name << " => " << group << endl; - if(m_config->hasGroup(group)) { - map = m_config->entryMap(group); - - //use project overrides - KileProject *project = m_ki->docManager()->activeProject(); - if(useproject && project) { - KConfig *prjcfg = dynamic_cast(project->config()); - if(prjcfg) { - QString grp = groupFor(name, prjcfg); - Config prjmap = prjcfg->entryMap(grp); - for (Config::Iterator it = prjmap.begin(); it != prjmap.end(); ++it) { - map[it.key()] = it.value(); - } - } - } - } - else { - return false; - } - - return true; - } - - void Manager::saveEntryMap(const QString & name, Config & map, bool usequeue, bool useproject) - { - KILE_DEBUG_MAIN << "==KileTool::Manager::saveEntryMap=============" << endl; - QString group = currentGroup(name, usequeue, useproject); - KILE_DEBUG_MAIN << "\t" << name << " => " << group << endl; - KConfigGroup configGroup = m_config->group(group); - - Config::Iterator it; - for(it = map.begin() ; it != map.end(); ++it) { - if(!it.value().isEmpty()) { - configGroup.writeEntry(it.key(), it.value()); - } - } - } - - bool Manager::configure(Base *tool, const QString& cfg /* = QString() */) - { - KILE_DEBUG_MAIN << "==KileTool::Manager::configure()===============" << endl; - //configure the tool - - Config map; - - if(!retrieveEntryMap(tool->name(), map, true, true, cfg)) { - QString group = (cfg.isEmpty()) ? currentGroup(tool->name(), true, true) : groupFor(tool->name(), cfg); - m_ki->errorHandler()->printMessage(Error, i18n("Cannot find the tool \"%1\" in the configuration database.", group)); - return false; - } - - tool->setEntryMap(map); - - return true; - } - - void Manager::wantGUIState(const QString & state) - { - KILE_DEBUG_MAIN << "REQUESTED state: " << state << endl; - emit(requestGUIState(state)); - } - - KileView::Manager* Manager::viewManager() - { - return m_ki->viewManager(); - } - - KileTool::LivePreviewManager* Manager::livePreviewManager() - { - return m_ki->livePreviewManager(); - } - - KileParser::Manager* Manager::parserManager() - { - return m_ki->parserManager(); - } - - QStringList toolList(KConfig *config, bool menuOnly) - { - KILE_DEBUG_MAIN << "==KileTool::toolList()==================" << endl; - - const QStringList groups = config->groupList(); - QStringList tools; - - QRegExp re = QRegExp("Tool/(.+)/.+"); - QString name; - - for(auto group : groups) { - if(!config->hasGroup(group)) { // 'group' might have been deleted - continue; // work around bug 384039 - } - if(re.exactMatch(group)) { - name = configName(re.cap(1), config); - - if(name.isEmpty() || !group.endsWith(name)) { - continue; - } - - if((!menuOnly) || (menuFor(re.cap(1), config) != "none")) { - tools.append(re.cap(1)); - } - } - } - - tools.sort(); +QueueItem::QueueItem(Base *tool, bool block) : m_tool(tool), m_bBlock(block) +{ +} + +QueueItem::~QueueItem() +{ +} + +Base* Queue::tool() const +{ + if(count() > 0 && head()) { + return head()->tool(); + } + else { + return 0; + } +} + +bool Queue::shouldBlock() const +{ + if(count() > 0 && head()) { + return head()->shouldBlock(); + } + else { + return false; + } +} + +void Queue::enqueueNext(QueueItem *item) +{ + if(count() < 2) { + enqueue(item); + } + else { + QueueItem *headitem = dequeue(); + Queue *oldqueue = new Queue(*this); + + clear(); + KILE_DEBUG_MAIN << "\tenqueueing: " << headitem->tool()->name() << endl; + enqueue(headitem); + KILE_DEBUG_MAIN << "\tenqueueing: " << item->tool()->name() << endl; + enqueue(item); + while(!oldqueue->isEmpty()) { + KILE_DEBUG_MAIN << "\tenqueueing: " << oldqueue->head()->tool()->name() << endl; + enqueue(oldqueue->dequeue()); + } + } +} + +Manager::Manager(KileInfo *ki, KConfig *config, KileWidget::OutputView *output, QStackedWidget *stack, QAction *stop, uint to, KActionCollection *ac) : + m_ki(ki), + m_config(config), + m_output(output), + m_stack(stack), + m_stop(stop), + m_bClear(true), + m_nLastResult(Success), + m_nTimeout(to), + m_bibliographyBackendSelectAction(Q_NULLPTR) +{ + connect(m_ki->parserManager(), SIGNAL(documentParsingComplete()), this, SLOT(handleDocumentParsingComplete())); + + connect(this, SIGNAL(childToolSpawned(KileTool::Base*,KileTool::Base*)), + m_ki->errorHandler(), SLOT(handleSpawnedChildTool(KileTool::Base*, KileTool::Base*))); + + m_timer = new QTimer(this); + connect(m_timer, SIGNAL(timeout()), this, SLOT(enableClear())); + connect(stop, SIGNAL(triggered()), this, SLOT(stop())); + connect(stop, SIGNAL(destroyed(QObject*)), this, SLOT(stopActionDestroyed())); + + connect(m_ki->errorHandler(), SIGNAL(currentLaTeXOutputHandlerChanged(LaTeXOutputHandler*)), SLOT(currentLaTeXOutputHandlerChanged(LaTeXOutputHandler*))); + + //create actions must be invoked before buildBibliographyBackendSelection()! + createActions(ac); + buildBibliographyBackendSelection(); + + connect(m_ki->configurationManager(), SIGNAL(configChanged()), SLOT(buildBibliographyBackendSelection())); +} + +Manager::~Manager() +{ + KILE_DEBUG_MAIN; + + for(QQueue::iterator i = m_queue.begin(); i != m_queue.end(); ++i) { + // this will also stop any running processes + delete (*i)->tool(); + delete (*i); + } + // tools have the tool manager as parent; so, all remaining tools will be deleted + // after this, i.e. those that were scheduled for deletion via 'deleteLater' but + // are no longer member of the queue +} + +bool Manager::shouldBlock() +{ + return m_queue.shouldBlock(); +} + +// in some cases the pointer m_stop might not be valid, therefore this helper function comes in handy +void Manager::setEnabledStopButton(bool state) { + + if(m_stop) { + m_stop->setEnabled(state); + } +} + +void Manager::enableClear() +{ + m_bClear = true; +} + +bool Manager::queryContinue(const QString & question, const QString & caption /*= QString()*/) +{ + return (KMessageBox::warningContinueCancel(m_stack, question, caption, KStandardGuiItem::cont(), KStandardGuiItem::no(), "showNotALaTeXRootDocumentWarning") == KMessageBox::Continue); +} + +void Manager::run(Base *tool) +{ + // if the tool requests a save-all operation, we wait for the parsing to + // be finished before launching it + if(!tool->requestSaveAll() || m_ki->parserManager()->isDocumentParsingComplete()) { + // parsing done, we can start the tool immediately + runImmediately(tool); + return; + } + connect(tool, SIGNAL(aboutToBeDestroyed(KileTool::Base*)), + this, SLOT(toolScheduledAfterParsingDestroyed(KileTool::Base*)), Qt::UniqueConnection); + if(!m_toolsScheduledAfterParsingList.contains(tool)) { + m_toolsScheduledAfterParsingList.push_back(tool); + } +} + +void Manager::toolScheduledAfterParsingDestroyed(KileTool::Base *tool) +{ + m_toolsScheduledAfterParsingList.removeAll(tool); +} + +void Manager::handleDocumentParsingComplete() +{ + Q_FOREACH(Base *tool, m_toolsScheduledAfterParsingList) { + disconnect(tool, SIGNAL(aboutToBeDestroyed(KileTool::Base*)), + this, SLOT(toolScheduledAfterParsingDestroyed(KileTool::Base*))); + runImmediately(tool); + } + m_toolsScheduledAfterParsingList.clear(); +} + +int Manager::runImmediately(Base *tool, bool insertNext /*= false*/, bool block /*= false*/, Base *parent /*= Q_NULLPTR*/) +{ + KILE_DEBUG_MAIN << "==KileTool::Manager::runImmediately(Base *)============" << endl; + if(m_bClear && (m_queue.count() == 0)) { + m_ki->errorHandler()->clearMessages(); + m_output->clear(); + } + + if(dynamic_cast(tool)) { + connect(tool, SIGNAL(done(KileTool::Base*, int, bool)), + m_ki->errorHandler(), SLOT(handleLaTeXToolDone(KileTool::Base*, int, bool))); + } + + if(tool->needsToBePrepared()) { + tool->prepareToRun(); + } + + //FIXME: shouldn't restart timer if a Sequence command takes longer than the 10 secs + //restart timer, so we only clear the logs if a tool is started after 10 sec. + m_bClear = false; + m_timer->start(m_nTimeout); + + if(insertNext) { + m_queue.enqueueNext(new QueueItem(tool, block)); + } + else { + m_queue.enqueue(new QueueItem(tool, block)); + } + + if(parent) { + emit(childToolSpawned(parent,tool)); + } + + KILE_DEBUG_MAIN << "\tin queue: " << m_queue.count() << endl; + if(m_queue.count() == 1) { + return runNextInQueue(); + } + else if(m_queue.count() > 1) { + return Running; + } + else { + return ConfigureFailed; + } +} + +int Manager::runChildNext(Base *parent, Base *tool, bool block /*= false*/) +{ + parent->setupAsChildTool(tool); + + return runImmediately(tool, true, block, parent); +} + +int Manager::runNextInQueue() +{ + Base *head = m_queue.tool(); + if(head) { + if (m_ki->errorHandler()->areMessagesShown()) { + m_ki->errorHandler()->addEmptyLineToMessages(); + } + + if(!head->isPrepared()) { + head->prepareToRun(); + } + + int status; + if((status=head->run()) != Running) { //tool did not even start, clear queue + stop(); + for(QQueue::iterator i = m_queue.begin(); i != m_queue.end(); ++i) { + (*i)->tool()->deleteLater(); + delete (*i); + } + m_queue.clear(); + return status; + } + + m_ki->errorHandler()->startToolLogOutput(); + emit(toolStarted()); + + return Running; + } + + return ConfigureFailed; +} + +Base* Manager::createTool(const QString& name, const QString &cfg, bool prepare) +{ + if(!m_factory) { + m_ki->errorHandler()->printMessage(Error, i18n("No factory installed, contact the author of Kile.")); + return Q_NULLPTR; + } + + Base* pTool = m_factory->create(name, cfg, prepare); + if(!pTool) { + m_ki->errorHandler()->printMessage(Error, i18n("Unknown tool %1.", name)); + return Q_NULLPTR; + } + initTool(pTool); + return pTool; +} + +void Manager::initTool(Base *tool) +{ + tool->setInfo(m_ki); + tool->setConfig(m_config); + + connect(tool, SIGNAL(message(int, const QString &, const QString &)), m_ki->errorHandler(), SLOT(printMessage(int, const QString &, const QString &))); + connect(tool, SIGNAL(output(const QString &)), m_output, SLOT(receive(const QString &))); + connect(tool, SIGNAL(done(KileTool::Base*,int,bool)), this, SLOT(done(KileTool::Base*, int))); + connect(tool, SIGNAL(start(KileTool::Base*)), this, SLOT(started(KileTool::Base*))); +} + +void Manager::started(Base *tool) +{ + KILE_DEBUG_MAIN << "STARTING tool: " << tool->name() << endl; + setEnabledStopButton(true); + + if (tool->isViewer()) { + if(tool == m_queue.tool()) { + m_queue.dequeue(); + } + setEnabledStopButton(false); + QTimer::singleShot(100, this, SLOT(runNextInQueue())); + } +} + +void Manager::stop() +{ + setEnabledStopButton(false); + if(m_queue.tool()) { + m_queue.tool()->stop(); + } +} + +void Manager::stopLivePreview() +{ + KILE_DEBUG_MAIN; + + Base *tool = m_queue.tool(); + + if(tool && tool->isPartOfLivePreview()) { + setEnabledStopButton(false); + tool->stop(); + } + + deleteLivePreviewToolsFromQueue(); + deleteLivePreviewToolsFromRunningAfterParsingQueue(); +} + +void Manager::stopActionDestroyed() +{ + m_stop = Q_NULLPTR; +} + +void Manager::done(KileTool::Base *tool, int result) +{ + setEnabledStopButton(false); + m_nLastResult = result; + + m_ki->errorHandler()->endToolLogOutput(); + + if(tool != m_queue.tool()) { //oops, tool finished async, could happen with view tools + tool->deleteLater(); + return; + } + + QueueItem *item = m_queue.dequeue(); + item->tool()->deleteLater(); + delete item; + + if(result == Aborted) { + tool->sendMessage(Error, i18n("Aborted")); + } + + if(result != Success && result != Silent) { //abort execution, delete all remaining tools + if(tool->isPartOfLivePreview()) { // live preview was stopped / aborted + deleteLivePreviewToolsFromQueue(); + // don't forget to run non-live preview tools that are pending + runNextInQueue(); + } + else { + for(QQueue::iterator i = m_queue.begin(); i != m_queue.end(); ++i) { + (*i)->tool()->deleteLater(); + delete (*i); + } + m_queue.clear(); + m_ki->focusLog(); + } + } + else { //continue + runNextInQueue(); + } +} + +void Manager::deleteLivePreviewToolsFromQueue() +{ + for(QQueue::iterator i = m_queue.begin(); i != m_queue.end();) { + QueueItem *item = *i; + if(item->tool()->isPartOfLivePreview()) { + i = m_queue.erase(i); + item->tool()->deleteLater(); + delete item; + } + else { + ++i; + } + } +} + +void Manager::deleteLivePreviewToolsFromRunningAfterParsingQueue() +{ + for(QQueue::iterator i = m_toolsScheduledAfterParsingList.begin(); i != m_toolsScheduledAfterParsingList.end();) { + Base *tool = *i; + if(tool->isPartOfLivePreview()) { + i = m_toolsScheduledAfterParsingList.erase(i); + delete tool; + } + else { + ++i; + } + } +} + +QString Manager::currentGroup(const QString &name, bool usequeue, bool useproject) +{ + if (useproject) { + KileProject *project = m_ki->docManager()->activeProject(); + if(project) { + QString cfg = configName(name, dynamic_cast(project->config())); + if(cfg.length() > 0) { + return groupFor(name, cfg); + } + } + } + if(usequeue && !m_queue.isEmpty() && m_queue.tool() && (m_queue.tool()->name() == name) && (!m_queue.tool()->toolConfig().isEmpty())) { + return groupFor(name, m_queue.tool()->toolConfig()); + } + else { + return groupFor(name, m_config); + } +} + +bool Manager::retrieveEntryMap(const QString & name, Config & map, bool usequeue, bool useproject, const QString & cfg /*= QString()*/) +{ + QString group = (cfg.isEmpty()) ? currentGroup(name, usequeue, useproject) : groupFor(name, cfg); + + KILE_DEBUG_MAIN << "==KileTool::Manager::retrieveEntryMap=============" << endl; + KILE_DEBUG_MAIN << "\t" << name << " => " << group << endl; + if(m_config->hasGroup(group)) { + map = m_config->entryMap(group); + + //use project overrides + KileProject *project = m_ki->docManager()->activeProject(); + if(useproject && project) { + KConfig *prjcfg = dynamic_cast(project->config()); + if(prjcfg) { + QString grp = groupFor(name, prjcfg); + Config prjmap = prjcfg->entryMap(grp); + for (Config::Iterator it = prjmap.begin(); it != prjmap.end(); ++it) { + map[it.key()] = it.value(); + } + } + } + } + else { + return false; + } + + return true; +} + +void Manager::saveEntryMap(const QString & name, Config & map, bool usequeue, bool useproject) +{ + KILE_DEBUG_MAIN << "==KileTool::Manager::saveEntryMap=============" << endl; + QString group = currentGroup(name, usequeue, useproject); + KILE_DEBUG_MAIN << "\t" << name << " => " << group << endl; + KConfigGroup configGroup = m_config->group(group); + + Config::Iterator it; + for(it = map.begin() ; it != map.end(); ++it) { + if(!it.value().isEmpty()) { + configGroup.writeEntry(it.key(), it.value()); + } + } +} + +bool Manager::configure(Base *tool, const QString& cfg /* = QString() */) +{ + KILE_DEBUG_MAIN << "==KileTool::Manager::configure()===============" << endl; + //configure the tool + + Config map; + + if(!retrieveEntryMap(tool->name(), map, true, true, cfg)) { + QString group = (cfg.isEmpty()) ? currentGroup(tool->name(), true, true) : groupFor(tool->name(), cfg); + m_ki->errorHandler()->printMessage(Error, i18n("Cannot find the tool \"%1\" in the configuration database.", group)); + return false; + } + + tool->setEntryMap(map); + + return true; +} + +void Manager::wantGUIState(const QString & state) +{ + KILE_DEBUG_MAIN << "REQUESTED state: " << state << endl; + emit(requestGUIState(state)); +} + +KileView::Manager* Manager::viewManager() +{ + return m_ki->viewManager(); +} + +KileTool::LivePreviewManager* Manager::livePreviewManager() +{ + return m_ki->livePreviewManager(); +} + +KileParser::Manager* Manager::parserManager() +{ + return m_ki->parserManager(); +} + +QStringList toolList(KConfig *config, bool menuOnly) +{ + KILE_DEBUG_MAIN << "==KileTool::toolList()==================" << endl; + + const QStringList groups = config->groupList(); + QStringList tools; + + QRegExp re = QRegExp("Tool/(.+)/.+"); + QString name; + + for(auto group : groups) { + if(!config->hasGroup(group)) { // 'group' might have been deleted + continue; // work around bug 384039 + } + if(re.exactMatch(group)) { + name = configName(re.cap(1), config); + + if(name.isEmpty() || !group.endsWith(name)) { + continue; + } + + if((!menuOnly) || (menuFor(re.cap(1), config) != "none")) { + tools.append(re.cap(1)); + } + } + } + + tools.sort(); // KILE_DEBUG_MAIN << "tools " << tools.join(", "); - return tools; - } - - QList toolsWithConfigurationsBasedOnClass(KConfig *config, const QString& className) - { - const QStringList groups = config->groupList(); - QStringList tools; - - QRegExp re = QRegExp("Tool/(.+)/(.+)"); - QList toReturn; - - for(auto group : groups) { - if(!config->hasGroup(group)) { // 'group' might have been deleted - continue; // work around bug 384039 - } - if(re.exactMatch(group)) { - const QString toolName = re.cap(1); - const QString configName = re.cap(2); - - if(toolName.isEmpty()) { - continue; - } - - if(config->group(group).readEntry("class", "") == className) { - toReturn.push_back(ToolConfigPair(toolName, configName)); - } - } - } - - return toReturn; - } - - QString configName(const QString & tool, KConfig *config) - { - return config->group("Tools").readEntry(tool, QString()); - } - - void Manager::setConfigName(const QString &tool, const QString &name) - { - KileTool::setConfigName(tool, name, m_config); - } - - void setConfigName(const QString &tool, const QString &name, KConfig *config) - { - KILE_DEBUG_MAIN << "==KileTool::Manager::setConfigName(" << tool << "," << name << ")===============" << endl; - config->group("Tools").writeEntry(tool, name); - } - - QString groupFor(const QString &tool, KConfig *config) - { - return groupFor(tool, configName(tool, config)); - } - - QString groupFor(const QString& tool, const QString& cfg /* = Default */ ) - { - QString group = "Tool/" + tool + '/' + cfg; - KILE_DEBUG_MAIN << "groupFor(const QString &" << tool << ", const QString & " << cfg << " ) = " << group; - return group; - } - - void extract(const QString &str, QString &tool, QString &cfg) - { - static QRegExp re("([^\\(]*)\\((.*)\\)"); - QString lcl = str.trimmed(); - cfg.clear(); - if(re.exactMatch(lcl)) { - tool = re.cap(1).trimmed(); - cfg = re.cap(2).trimmed(); - } - else { - tool = lcl; - } - KILE_DEBUG_MAIN << "===void extract(const QString &str = " << str << " , QString &tool = " << tool << ", QString &cfg = " << cfg << " )===" << endl; - } - - QString format(const QString & tool, const QString &cfg) - { - if (!cfg.isEmpty()) { - return tool + '(' + cfg + ')'; - } - else { - return tool; - } - } - - QStringList configNames(const QString &tool, KConfig *config) - { - const QStringList groups = config->groupList(); - QStringList configs; - - QRegExp re = QRegExp("Tool/"+ tool +"/(.+)"); - - for(auto group : groups) { - if(!config->hasGroup(group)) { // 'group' might have been deleted - continue; // work around bug 384039 - } - if(re.exactMatch(group)) { - configs.append(re.cap(1)); - } - } - - return configs; - } - - QString commandFor(const QString& toolName, const QString& configName, KConfig *config) - { - return config->group(groupFor(toolName, configName)).readEntry("command", ""); - } - - QString menuFor(const QString &tool, KConfig *config) - { - return config->group("ToolsGUI").readEntry(tool, "Other,application-x-executable").section(',', 0, 0); - } - - QString iconFor(const QString &tool, KConfig *config) - { - return config->group("ToolsGUI").readEntry(tool, "Other,application-x-executable").section(',', 1, 1); - } - - void setGUIOptions(const QString &tool, const QString &menu, const QString &icon, KConfig *config) - { - QString entry = menu + ',' + icon; - - config->group("ToolsGUI").writeEntry(tool, entry); - } - - QString categoryFor(const QString &clss) - { - if(clss == "Compile" || clss == "LaTeX") { - return "Compile"; - } - if(clss == "Convert") { - return "Convert"; - } - if(clss == "View" || clss == "ViewBib" || clss == "ViewHTML" || clss == "ForwardDVI") { - return "View"; - } - if(clss == "Sequence") { - return "Sequence"; - } - if(clss == "Archive") { - return "Archive"; - } - - return "Base"; - } + return tools; } -bool KileTool::Manager::containsBibliographyTool(const ToolConfigPair& p) const +QList toolsWithConfigurationsBasedOnClass(KConfig *config, const QString& className) { - return m_bibliographyToolsList.contains(p); + const QStringList groups = config->groupList(); + QStringList tools; + + QRegExp re = QRegExp("Tool/(.+)/(.+)"); + QList toReturn; + + for(auto group : groups) { + if(!config->hasGroup(group)) { // 'group' might have been deleted + continue; // work around bug 384039 + } + if(re.exactMatch(group)) { + const QString toolName = re.cap(1); + const QString configName = re.cap(2); + + if(toolName.isEmpty()) { + continue; + } + + if(config->group(group).readEntry("class", "") == className) { + toReturn.push_back(ToolConfigPair(toolName, configName)); + } + } + } + + return toReturn; } -KileTool::ToolConfigPair KileTool::Manager::findFirstBibliographyToolForCommand(const QString& command) const +QString configName(const QString & tool, KConfig *config) { - // for now we will just select the first suitable tool - Q_FOREACH(const KileTool::ToolConfigPair& tool, m_bibliographyToolsList) { - const QString toolCommand = commandFor(tool, m_config); - if (QString::compare(command, toolCommand, Qt::CaseInsensitive) == 0) { - return tool; - } - } + return config->group("Tools").readEntry(tool, QString()); +} - return KileTool::ToolConfigPair(); +void Manager::setConfigName(const QString &tool, const QString &name) +{ + KileTool::setConfigName(tool, name, m_config); } -void KileTool::Manager::buildBibliographyBackendSelection() +void setConfigName(const QString &tool, const QString &name, KConfig *config) { - m_bibliographyBackendSelectAction->removeAllActions(); - m_bibliographyBackendSelectAction->menu()->clear(); - for(QMap::iterator i = m_bibliographyBackendActionMap.begin(); i != m_bibliographyBackendActionMap.end(); ++i) { - delete i.value(); - } - m_bibliographyBackendActionMap.clear(); - m_bibliographyToolsList.clear(); + KILE_DEBUG_MAIN << "==KileTool::Manager::setConfigName(" << tool << "," << name << ")===============" << endl; + config->group("Tools").writeEntry(tool, name); +} - m_bibliographyBackendSelectAction->addAction(m_bibliographyBackendAutodetectAction); +QString groupFor(const QString &tool, KConfig *config) +{ + return groupFor(tool, configName(tool, config)); +} + +QString groupFor(const QString& tool, const QString& cfg /* = Default */ ) +{ + QString group = "Tool/" + tool + '/' + cfg; + KILE_DEBUG_MAIN << "groupFor(const QString &" << tool << ", const QString & " << cfg << " ) = " << group; + return group; +} + +void extract(const QString &str, QString &tool, QString &cfg) +{ + static QRegExp re("([^\\(]*)\\((.*)\\)"); + QString lcl = str.trimmed(); + cfg.clear(); + if(re.exactMatch(lcl)) { + tool = re.cap(1).trimmed(); + cfg = re.cap(2).trimmed(); + } + else { + tool = lcl; + } + KILE_DEBUG_MAIN << "===void extract(const QString &str = " << str << " , QString &tool = " << tool << ", QString &cfg = " << cfg << " )===" << endl; +} + +QString format(const QString & tool, const QString &cfg) +{ + if (!cfg.isEmpty()) { + return tool + '(' + cfg + ')'; + } + else { + return tool; + } +} + +QStringList configNames(const QString &tool, KConfig *config) +{ + const QStringList groups = config->groupList(); + QStringList configs; + + QRegExp re = QRegExp("Tool/"+ tool +"/(.+)"); + + for(auto group : groups) { + if(!config->hasGroup(group)) { // 'group' might have been deleted + continue; // work around bug 384039 + } + if(re.exactMatch(group)) { + configs.append(re.cap(1)); + } + } + + return configs; +} + +QString commandFor(const QString& toolName, const QString& configName, KConfig *config) +{ + return config->group(groupFor(toolName, configName)).readEntry("command", ""); +} + +QString menuFor(const QString &tool, KConfig *config) +{ + return config->group("ToolsGUI").readEntry(tool, "Other,application-x-executable").section(',', 0, 0); +} - m_bibliographyToolsList = toolsWithConfigurationsBasedOnClass(m_config, BibliographyCompile::ToolClass); - std::sort(m_bibliographyToolsList.begin(), m_bibliographyToolsList.end()); // necessary for the user-visible actions in the menu bar +QString iconFor(const QString &tool, KConfig *config) +{ + return config->group("ToolsGUI").readEntry(tool, "Other,application-x-executable").section(',', 1, 1); +} - Q_FOREACH(const ToolConfigPair& tool, m_bibliographyToolsList) { - // create an action for backend selection - QAction * action = m_bibliographyBackendSelectAction->addAction(tool.userStringRepresentation()); - action->setData(qVariantFromValue(tool)); - m_bibliographyBackendActionMap[tool] = action; - } +void setGUIOptions(const QString &tool, const QString &menu, const QString &icon, KConfig *config) +{ + QString entry = menu + ',' + icon; - m_bibliographyBackendSelectAction->menu()->addSeparator(); - m_bibliographyBackendSelectAction->menu()->addAction(m_bibliographyBackendResetAutodetectedAction); + config->group("ToolsGUI").writeEntry(tool, entry); +} - currentLaTeXOutputHandlerChanged(m_ki->findCurrentLaTeXOutputHandler()); +QString categoryFor(const QString &clss) +{ + if(clss == "Compile" || clss == "LaTeX") { + return "Compile"; + } + if(clss == "Convert") { + return "Convert"; + } + if(clss == "View" || clss == "ViewBib" || clss == "ViewHTML" || clss == "ForwardDVI") { + return "View"; + } + if(clss == "Sequence") { + return "Sequence"; + } + if(clss == "Archive") { + return "Archive"; + } + + return "Base"; +} +} + +bool KileTool::Manager::containsBibliographyTool(const ToolConfigPair& p) const +{ + return m_bibliographyToolsList.contains(p); +} + +KileTool::ToolConfigPair KileTool::Manager::findFirstBibliographyToolForCommand(const QString& command) const +{ + // for now we will just select the first suitable tool + Q_FOREACH(const KileTool::ToolConfigPair& tool, m_bibliographyToolsList) { + const QString toolCommand = commandFor(tool, m_config); + if (QString::compare(command, toolCommand, Qt::CaseInsensitive) == 0) { + return tool; + } + } + + return KileTool::ToolConfigPair(); +} + +void KileTool::Manager::buildBibliographyBackendSelection() +{ + m_bibliographyBackendSelectAction->removeAllActions(); + m_bibliographyBackendSelectAction->menu()->clear(); + for(QMap::iterator i = m_bibliographyBackendActionMap.begin(); i != m_bibliographyBackendActionMap.end(); ++i) { + delete i.value(); + } + m_bibliographyBackendActionMap.clear(); + m_bibliographyToolsList.clear(); + + m_bibliographyBackendSelectAction->addAction(m_bibliographyBackendAutodetectAction); + + m_bibliographyToolsList = toolsWithConfigurationsBasedOnClass(m_config, BibliographyCompile::ToolClass); + std::sort(m_bibliographyToolsList.begin(), m_bibliographyToolsList.end()); // necessary for the user-visible actions in the menu bar + + Q_FOREACH(const ToolConfigPair& tool, m_bibliographyToolsList) { + // create an action for backend selection + QAction * action = m_bibliographyBackendSelectAction->addAction(tool.userStringRepresentation()); + action->setData(qVariantFromValue(tool)); + m_bibliographyBackendActionMap[tool] = action; + } + + m_bibliographyBackendSelectAction->menu()->addSeparator(); + m_bibliographyBackendSelectAction->menu()->addAction(m_bibliographyBackendResetAutodetectedAction); + + currentLaTeXOutputHandlerChanged(m_ki->findCurrentLaTeXOutputHandler()); } void KileTool::Manager::createActions(KActionCollection *ac) { - delete m_bibliographyBackendSelectAction; + delete m_bibliographyBackendSelectAction; - m_bibliographyBackendSelectAction = new KSelectAction(i18n("Bibliography Back End"), this); - m_bibliographyBackendAutodetectAction = m_bibliographyBackendSelectAction->addAction(i18n("Auto-Detect")); - m_bibliographyBackendAutodetectAction->setStatusTip(i18n("Auto-detect the bibliography back end from LaTeX output")); - m_bibliographyBackendSelectAction->setChecked(false); + m_bibliographyBackendSelectAction = new KSelectAction(i18n("Bibliography Back End"), this); + m_bibliographyBackendAutodetectAction = m_bibliographyBackendSelectAction->addAction(i18n("Auto-Detect")); + m_bibliographyBackendAutodetectAction->setStatusTip(i18n("Auto-detect the bibliography back end from LaTeX output")); + m_bibliographyBackendSelectAction->setChecked(false); - ac->addAction("bibbackend_select", m_bibliographyBackendSelectAction); + ac->addAction("bibbackend_select", m_bibliographyBackendSelectAction); - m_bibliographyBackendResetAutodetectedAction = new QAction(i18n("Reset Auto-Detected Back End"), this); - m_bibliographyBackendResetAutodetectedAction->setEnabled(false); + m_bibliographyBackendResetAutodetectedAction = new QAction(i18n("Reset Auto-Detected Back End"), this); + m_bibliographyBackendResetAutodetectedAction->setEnabled(false); - connect(m_bibliographyBackendSelectAction, SIGNAL(triggered(QAction*)), SLOT(bibliographyBackendSelectedByUser())); - connect(m_bibliographyBackendResetAutodetectedAction, SIGNAL(triggered(bool)), SLOT(resetAutodetectedBibliographyBackend())); - connect(m_bibliographyBackendAutodetectAction, SIGNAL(toggled(bool)), - m_bibliographyBackendResetAutodetectedAction, SLOT(setEnabled(bool))); + connect(m_bibliographyBackendSelectAction, SIGNAL(triggered(QAction*)), SLOT(bibliographyBackendSelectedByUser())); + connect(m_bibliographyBackendResetAutodetectedAction, SIGNAL(triggered(bool)), SLOT(resetAutodetectedBibliographyBackend())); + connect(m_bibliographyBackendAutodetectAction, SIGNAL(toggled(bool)), + m_bibliographyBackendResetAutodetectedAction, SLOT(setEnabled(bool))); } void KileTool::Manager::bibliographyBackendSelectedByUser() { - LaTeXOutputHandler* h = m_ki->findCurrentLaTeXOutputHandler(); - QAction* currentBackendAction = m_bibliographyBackendSelectAction->currentAction(); - - if (currentBackendAction == m_bibliographyBackendAutodetectAction) { - h->setBibliographyBackendToolUserOverride(ToolConfigPair()); - } - else { - //here we do not need to check existence of tool - h->setBibliographyBackendToolUserOverride(currentBackendAction->data().value()); - h->setBibliographyBackendToolAutoDetected(ToolConfigPair()); - } + LaTeXOutputHandler* h = m_ki->findCurrentLaTeXOutputHandler(); + QAction* currentBackendAction = m_bibliographyBackendSelectAction->currentAction(); + + if (currentBackendAction == m_bibliographyBackendAutodetectAction) { + h->setBibliographyBackendToolUserOverride(ToolConfigPair()); + } + else { + //here we do not need to check existence of tool + h->setBibliographyBackendToolUserOverride(currentBackendAction->data().value()); + h->setBibliographyBackendToolAutoDetected(ToolConfigPair()); + } } void KileTool::Manager::currentLaTeXOutputHandlerChanged(LaTeXOutputHandler* handler) { - if(!handler) { - m_bibliographyBackendSelectAction->setEnabled(false); - return; - } - - m_bibliographyBackendSelectAction->setEnabled(true); - - if (!m_bibliographyBackendActionMap.empty()) { - ToolConfigPair userOverrideBibBackend = handler->bibliographyBackendToolUserOverride(); - if(!userOverrideBibBackend.isValid()) { - m_bibliographyBackendAutodetectAction->setChecked(true); - } - else { - // here we have to check whether the action exists - QMap::const_iterator i = m_bibliographyBackendActionMap.constFind(userOverrideBibBackend); - if (i != m_bibliographyBackendActionMap.constEnd()) { - i.value()->setChecked(true); - } - else { - // the user previously selected a bibtool backend which is (no longer) present - let's use autodetection; - // this is done analogously in 'LaTeX::determineBibliographyBackend' - m_bibliographyBackendAutodetectAction->setChecked(true); - } - } - } - else { - m_bibliographyBackendAutodetectAction->setChecked(true); - } + if(!handler) { + m_bibliographyBackendSelectAction->setEnabled(false); + return; + } + + m_bibliographyBackendSelectAction->setEnabled(true); + + if (!m_bibliographyBackendActionMap.empty()) { + ToolConfigPair userOverrideBibBackend = handler->bibliographyBackendToolUserOverride(); + if(!userOverrideBibBackend.isValid()) { + m_bibliographyBackendAutodetectAction->setChecked(true); + } + else { + // here we have to check whether the action exists + QMap::const_iterator i = m_bibliographyBackendActionMap.constFind(userOverrideBibBackend); + if (i != m_bibliographyBackendActionMap.constEnd()) { + i.value()->setChecked(true); + } + else { + // the user previously selected a bibtool backend which is (no longer) present - let's use autodetection; + // this is done analogously in 'LaTeX::determineBibliographyBackend' + m_bibliographyBackendAutodetectAction->setChecked(true); + } + } + } + else { + m_bibliographyBackendAutodetectAction->setChecked(true); + } } void KileTool::Manager::resetAutodetectedBibliographyBackend() { - LaTeXOutputHandler* h = m_ki->findCurrentLaTeXOutputHandler(); - if (h) { - h->setBibliographyBackendToolAutoDetected(ToolConfigPair()); - } + LaTeXOutputHandler* h = m_ki->findCurrentLaTeXOutputHandler(); + if (h) { + h->setBibliographyBackendToolAutoDetected(ToolConfigPair()); + } } diff --git a/src/kiletoolmanager.h b/src/kiletoolmanager.h index 2d5567a5..fad09b04 100644 --- a/src/kiletoolmanager.h +++ b/src/kiletoolmanager.h @@ -1,223 +1,245 @@ /************************************************************************************** Copyright (C) 2003 by Jeroen Wijnhout (Jeroen.Wijnhout@kdemail.net) 2011-2017 by Michel Ludwig (michel.ludwig@kdemail.net) **************************************************************************************/ /*************************************************************************** * * * 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. * * * ****************************************************************************/ #ifndef KILETOOLMANAGER_H #define KILETOOLMANAGER_H #include #include #include #include #include #include "kiletool.h" #include "tool_utils.h" /*********************************************************************************************************** * CAUTION!! * It must be ensured that no event loop is started whenever some tool operation * is running. This includes running code inside the tool classes! * * The reason for that is that an event loop might trigger the deletion a tool object for which code * is currently executed, for instance with the 'stopLivePreview' method. * An event loop is executed, for example, within the 'documentSave' method of KatePart. Although the event * loop doesn't process user events, the document modification timer might still be triggered in such * an event loop and 'stopLivePreview' will be called. Now, no document saving is performed inside tool * classes anymore (including the tool manager). *********************************************************************************************************** * Also, it is important that parsing has to be finished before any tool is processed; for example, when * a project is being opened and the right master document still has to be determined through parsing. ***********************************************************************************************************/ class QTimer; class QAction; class KActionCollection; class KConfig; class KSelectAction; class KTextEdit; class KileInfo; -namespace KileParser { class Manager; } -namespace KileView { class Manager; } -namespace KileWidget { class OutputView; } +namespace KileParser { +class Manager; +} +namespace KileView { +class Manager; +} +namespace KileWidget { +class OutputView; +} namespace KileTool { - class Factory; - class LivePreviewManager; - - class QueueItem - { - public: - explicit QueueItem(Base *tool, bool block = false); - ~QueueItem(); - - Base* tool() const { return m_tool; } - bool shouldBlock() { return m_bBlock; } - - private: - Base *m_tool; - bool m_bBlock; - }; - - class Queue : public QQueue - { - public: - Base* tool() const; - bool shouldBlock() const; - - void enqueueNext(QueueItem *); - }; - - class Manager : public QObject - { - friend class Base; - Q_OBJECT - - public: - Manager(KileInfo *ki, KConfig *config, KileWidget::OutputView *output, QStackedWidget* stack, QAction *, uint to, KActionCollection *); - ~Manager(); - public: - Base* createTool(const QString& name, const QString &cfg = QString(), bool prepare = false); - inline Base* createTool(const ToolConfigPair& p, bool prepare = false) - { - return createTool(p.first, p.second, prepare); - } - bool configure(Base*, const QString &cfg = QString()); - bool retrieveEntryMap(const QString & name, Config & map, bool usequeue = true, bool useproject = true, const QString & cfg = QString()); - void saveEntryMap(const QString & name, Config & map, bool usequeue = true, bool useproject = true); - QString currentGroup(const QString &name, bool usequeue = true, bool useproject = true); - - void wantGUIState(const QString &); - - QStackedWidget* widgetStack() { return m_stack; } - KileView::Manager* viewManager(); - KileTool::LivePreviewManager* livePreviewManager(); - KileParser::Manager* parserManager(); - - KileInfo * info() { return m_ki; } - KConfig * config() { return m_config; } - - void setFactory(Factory* fac) { m_factory = fac; } - Factory* factory() { return m_factory; } - - bool queryContinue(const QString & question, const QString & caption = QString()); - - bool shouldBlock(); - int lastResult() { return m_nLastResult; } - - // convenience method; also see the static method of the same name below - void setConfigName(const QString &tool, const QString &name); - - bool containsBibliographyTool(const ToolConfigPair& p) const; - ToolConfigPair findFirstBibliographyToolForCommand(const QString& command) const; - - public Q_SLOTS: - void run(KileTool::Base *tool); - - void stopLivePreview(); - - private: - void setEnabledStopButton(bool state); - void initTool(Base*); - - private Q_SLOTS: - int runImmediately(Base *tool, bool insertAtTop = false, bool block = false, Base *parent = Q_NULLPTR); - int runNextInQueue(); - void enableClear(); - - void started(KileTool::Base *tool); - void done(KileTool::Base *tool, int result); - - void stop(); //should be a slot that stops the active tool and clears the queue - void stopActionDestroyed(); - - // must be used when a child tool is launched from within another tool! - int runChildNext(Base *parent, Base *tool, bool block = false); +class Factory; +class LivePreviewManager; - void toolScheduledAfterParsingDestroyed(KileTool::Base *tool); - void handleDocumentParsingComplete(); - - void currentLaTeXOutputHandlerChanged(LaTeXOutputHandler* handler); - - void bibliographyBackendSelectedByUser(); - void buildBibliographyBackendSelection(); - void resetAutodetectedBibliographyBackend(); - - Q_SIGNALS: - void requestGUIState(const QString &); - void jumpToFirstError(); - void toolStarted(); - void previewDone(); - // emitted when a tool spawns another tool (parent, child). - void childToolSpawned(KileTool::Base*,KileTool::Base*); - - private: - KileInfo *m_ki; - KConfig *m_config; - KileWidget::OutputView *m_output; - QStackedWidget *m_stack; - QAction *m_stop; - Factory *m_factory; - Queue m_queue; - QTimer *m_timer; - bool m_bClear; - int m_nLastResult; - uint m_nTimeout; - QQueue m_toolsScheduledAfterParsingList; - KSelectAction *m_bibliographyBackendSelectAction; - QAction *m_bibliographyBackendAutodetectAction; - QAction *m_bibliographyBackendResetAutodetectedAction; - QMap m_bibliographyBackendActionMap; - QList m_bibliographyToolsList; - - void createActions(KActionCollection *ac); - - void deleteLivePreviewToolsFromQueue(); - void deleteLivePreviewToolsFromRunningAfterParsingQueue(); - }; - - QStringList toolList(KConfig *config, bool menuOnly = false); - QStringList configNames(const QString &tool, KConfig *config); - - QList toolsWithConfigurationsBasedOnClass(KConfig *config, const QString& className); - - // configuration names must be in English, i.e. not translated! - QString configName(const QString &tool, KConfig *config); - void setConfigName(const QString &tool, const QString &name, KConfig *config); +class QueueItem +{ +public: + explicit QueueItem(Base *tool, bool block = false); + ~QueueItem(); + + Base* tool() const { + return m_tool; + } + bool shouldBlock() { + return m_bBlock; + } + +private: + Base *m_tool; + bool m_bBlock; +}; + +class Queue : public QQueue +{ +public: + Base* tool() const; + bool shouldBlock() const; - QString groupFor(const QString& tool, KConfig *config); - QString groupFor(const QString& tool, const QString& cfg = "Default"); + void enqueueNext(QueueItem *); +}; - void extract(const QString& str, QString &tool, QString &cfg); - QString format(const QString& tool, const QString &cfg); +class Manager : public QObject +{ + friend class Base; + Q_OBJECT + +public: + Manager(KileInfo *ki, KConfig *config, KileWidget::OutputView *output, QStackedWidget* stack, QAction *, uint to, KActionCollection *); + ~Manager(); +public: + Base* createTool(const QString& name, const QString &cfg = QString(), bool prepare = false); + inline Base* createTool(const ToolConfigPair& p, bool prepare = false) + { + return createTool(p.first, p.second, prepare); + } + bool configure(Base*, const QString &cfg = QString()); + bool retrieveEntryMap(const QString & name, Config & map, bool usequeue = true, bool useproject = true, const QString & cfg = QString()); + void saveEntryMap(const QString & name, Config & map, bool usequeue = true, bool useproject = true); + QString currentGroup(const QString &name, bool usequeue = true, bool useproject = true); + + void wantGUIState(const QString &); + + QStackedWidget* widgetStack() { + return m_stack; + } + KileView::Manager* viewManager(); + KileTool::LivePreviewManager* livePreviewManager(); + KileParser::Manager* parserManager(); + + KileInfo * info() { + return m_ki; + } + KConfig * config() { + return m_config; + } + + void setFactory(Factory* fac) { + m_factory = fac; + } + Factory* factory() { + return m_factory; + } + + bool queryContinue(const QString & question, const QString & caption = QString()); + + bool shouldBlock(); + int lastResult() { + return m_nLastResult; + } + + // convenience method; also see the static method of the same name below + void setConfigName(const QString &tool, const QString &name); + + bool containsBibliographyTool(const ToolConfigPair& p) const; + ToolConfigPair findFirstBibliographyToolForCommand(const QString& command) const; + +public Q_SLOTS: + void run(KileTool::Base *tool); + + void stopLivePreview(); + +private: + void setEnabledStopButton(bool state); + void initTool(Base*); + +private Q_SLOTS: + int runImmediately(Base *tool, bool insertAtTop = false, bool block = false, Base *parent = Q_NULLPTR); + int runNextInQueue(); + void enableClear(); + + void started(KileTool::Base *tool); + void done(KileTool::Base *tool, int result); + + void stop(); //should be a slot that stops the active tool and clears the queue + void stopActionDestroyed(); + + // must be used when a child tool is launched from within another tool! + int runChildNext(Base *parent, Base *tool, bool block = false); + + void toolScheduledAfterParsingDestroyed(KileTool::Base *tool); + void handleDocumentParsingComplete(); + + void currentLaTeXOutputHandlerChanged(LaTeXOutputHandler* handler); + + void bibliographyBackendSelectedByUser(); + void buildBibliographyBackendSelection(); + void resetAutodetectedBibliographyBackend(); + +Q_SIGNALS: + void requestGUIState(const QString &); + void jumpToFirstError(); + void toolStarted(); + void previewDone(); + // emitted when a tool spawns another tool (parent, child). + void childToolSpawned(KileTool::Base*,KileTool::Base*); + +private: + KileInfo *m_ki; + KConfig *m_config; + KileWidget::OutputView *m_output; + QStackedWidget *m_stack; + QAction *m_stop; + Factory *m_factory; + Queue m_queue; + QTimer *m_timer; + bool m_bClear; + int m_nLastResult; + uint m_nTimeout; + QQueue m_toolsScheduledAfterParsingList; + KSelectAction *m_bibliographyBackendSelectAction; + QAction *m_bibliographyBackendAutodetectAction; + QAction *m_bibliographyBackendResetAutodetectedAction; + QMap m_bibliographyBackendActionMap; + QList m_bibliographyToolsList; + + void createActions(KActionCollection *ac); + + void deleteLivePreviewToolsFromQueue(); + void deleteLivePreviewToolsFromRunningAfterParsingQueue(); +}; + +QStringList toolList(KConfig *config, bool menuOnly = false); +QStringList configNames(const QString &tool, KConfig *config); + +QList toolsWithConfigurationsBasedOnClass(KConfig *config, const QString& className); + +// configuration names must be in English, i.e. not translated! +QString configName(const QString &tool, KConfig *config); +void setConfigName(const QString &tool, const QString &name, KConfig *config); + +QString groupFor(const QString& tool, KConfig *config); +QString groupFor(const QString& tool, const QString& cfg = "Default"); + +void extract(const QString& str, QString &tool, QString &cfg); +QString format(const QString& tool, const QString &cfg); - QString commandFor(const QString& toolName, const QString& configName, KConfig *config); - inline QString commandFor(const ToolConfigPair& p, KConfig *config) - { - return commandFor(p.first, p.second, config); - } +QString commandFor(const QString& toolName, const QString& configName, KConfig *config); +inline QString commandFor(const ToolConfigPair& p, KConfig *config) +{ + return commandFor(p.first, p.second, config); +} - QString menuFor(const QString &tool, KConfig *config); - QString iconFor(const QString &tool, KConfig *config); +QString menuFor(const QString &tool, KConfig *config); +QString iconFor(const QString &tool, KConfig *config); - QString categoryFor(const QString &clss); +QString categoryFor(const QString &clss); - void setGUIOptions(const QString &tool, const QString &menu, const QString &icon, KConfig *config); +void setGUIOptions(const QString &tool, const QString &menu, const QString &icon, KConfig *config); } #endif diff --git a/src/kileviewmanager.cpp b/src/kileviewmanager.cpp index fa40b050..4d593215 100644 --- a/src/kileviewmanager.cpp +++ b/src/kileviewmanager.cpp @@ -1,1313 +1,1315 @@ /************************************************************************** * Copyright (C) 2004 by Jeroen Wijnhout (Jeroen.Wijnhout@kdemail.net) * * (C) 2006-2017 by Michel Ludwig (michel.ludwig@kdemail.net) * ***************************************************************************/ /*************************************************************************** * * * 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. * * * ***************************************************************************/ #include "kileviewmanager.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include //for QTimer::singleShot trick #include #include "editorkeysequencemanager.h" #include "kileinfo.h" #include "kileconstants.h" #include "kileproject.h" #include "kiledocmanager.h" #include "kileextensions.h" #include "kiletool_enums.h" #include "usermenu/usermenu.h" #include "livepreview.h" #include "widgets/projectview.h" #include "widgets/structurewidget.h" #include "editorextension.h" #include "plaintolatexconverter.h" #include "widgets/previewwidget.h" #include "quickpreview.h" #include "codecompletion.h" namespace KileView { bool sortDocuments(const KTextEditor::View * const lhs, const KTextEditor::View * const rhs) { - return lhs->document()->documentName().compare(rhs->document()->documentName(), Qt::CaseInsensitive) < 0; + return lhs->document()->documentName().compare(rhs->document()->documentName(), Qt::CaseInsensitive) < 0; } //BEGIN DocumentViewerWindow DocumentViewerWindow::DocumentViewerWindow(QWidget *parent, Qt::WindowFlags f) -: KMainWindow(parent, f) + : KMainWindow(parent, f) { } DocumentViewerWindow::~DocumentViewerWindow() { } void DocumentViewerWindow::showEvent(QShowEvent *event) { - KMainWindow::showEvent(event); - emit visibilityChanged(true); + KMainWindow::showEvent(event); + emit visibilityChanged(true); } void DocumentViewerWindow::closeEvent(QCloseEvent *event) { - KMainWindow::closeEvent(event); - emit visibilityChanged(false); + KMainWindow::closeEvent(event); + emit visibilityChanged(false); } //END DocumentViewerWindow Manager::Manager(KileInfo *info, KActionCollection *actionCollection, QObject *parent, const char *name) : - QObject(parent), - m_ki(info), + QObject(parent), + m_ki(info), // m_projectview(Q_NULLPTR), - m_tabsAndEditorWidget(Q_NULLPTR), - m_tabBar(Q_NULLPTR), - m_documentListButton(Q_NULLPTR), - m_viewerPartWindow(Q_NULLPTR), - m_widgetStack(Q_NULLPTR), - m_pasteAsLaTeXAction(Q_NULLPTR), - m_convertToLaTeXAction(Q_NULLPTR), - m_quickPreviewAction(Q_NULLPTR), - m_showCursorPositionInViewerAction(Q_NULLPTR), - m_viewerControlToolBar(Q_NULLPTR), - m_cursorPositionChangedTimer(Q_NULLPTR), - m_clearLastShownSourceLocationTimer(Q_NULLPTR), - m_synchronizeViewWithCursorAction(Q_NULLPTR) -{ - setObjectName(name); - createViewerPart(actionCollection); - - m_showCursorPositionInViewerAction = new QAction(QIcon::fromTheme("go-jump-symbolic"), i18n("Show Cursor Position in Viewer"), this); - connect(m_showCursorPositionInViewerAction, &QAction::triggered, this, &KileView::Manager::showCursorPositionInDocumentViewer); - actionCollection->addAction("show_cursor_position_in_document_viewer", m_showCursorPositionInViewerAction); - - m_synchronizeViewWithCursorAction = new KToggleAction(i18n("Synchronize Cursor Position with Viewer"), this); - connect(m_synchronizeViewWithCursorAction, &KToggleAction::toggled, this, &KileView::Manager::synchronizeViewWithCursorActionToggled); - connect(m_synchronizeViewWithCursorAction, &KToggleAction::changed, - this, [=] () { m_showCursorPositionInViewerAction->setEnabled(!m_synchronizeViewWithCursorAction->isChecked()); }); - actionCollection->addAction("synchronize_cursor_with_document_viewer", m_synchronizeViewWithCursorAction); - - m_cursorPositionChangedTimer = new QTimer(this); - m_cursorPositionChangedTimer->setSingleShot(true); - connect(m_cursorPositionChangedTimer, &QTimer::timeout, this, &KileView::Manager::handleCursorPositionChangedTimeout); - - m_clearLastShownSourceLocationTimer = new QTimer(this); - m_clearLastShownSourceLocationTimer->setInterval(3000); - m_clearLastShownSourceLocationTimer->setSingleShot(true); - connect(m_clearLastShownSourceLocationTimer, &QTimer::timeout, this, &KileView::Manager::clearLastShownSourceLocationInDocumentViewer); - - createViewerControlToolBar(); + m_tabsAndEditorWidget(Q_NULLPTR), + m_tabBar(Q_NULLPTR), + m_documentListButton(Q_NULLPTR), + m_viewerPartWindow(Q_NULLPTR), + m_widgetStack(Q_NULLPTR), + m_pasteAsLaTeXAction(Q_NULLPTR), + m_convertToLaTeXAction(Q_NULLPTR), + m_quickPreviewAction(Q_NULLPTR), + m_showCursorPositionInViewerAction(Q_NULLPTR), + m_viewerControlToolBar(Q_NULLPTR), + m_cursorPositionChangedTimer(Q_NULLPTR), + m_clearLastShownSourceLocationTimer(Q_NULLPTR), + m_synchronizeViewWithCursorAction(Q_NULLPTR) +{ + setObjectName(name); + createViewerPart(actionCollection); + + m_showCursorPositionInViewerAction = new QAction(QIcon::fromTheme("go-jump-symbolic"), i18n("Show Cursor Position in Viewer"), this); + connect(m_showCursorPositionInViewerAction, &QAction::triggered, this, &KileView::Manager::showCursorPositionInDocumentViewer); + actionCollection->addAction("show_cursor_position_in_document_viewer", m_showCursorPositionInViewerAction); + + m_synchronizeViewWithCursorAction = new KToggleAction(i18n("Synchronize Cursor Position with Viewer"), this); + connect(m_synchronizeViewWithCursorAction, &KToggleAction::toggled, this, &KileView::Manager::synchronizeViewWithCursorActionToggled); + connect(m_synchronizeViewWithCursorAction, &KToggleAction::changed, + this, [=] () { + m_showCursorPositionInViewerAction->setEnabled(!m_synchronizeViewWithCursorAction->isChecked()); + }); + actionCollection->addAction("synchronize_cursor_with_document_viewer", m_synchronizeViewWithCursorAction); + + m_cursorPositionChangedTimer = new QTimer(this); + m_cursorPositionChangedTimer->setSingleShot(true); + connect(m_cursorPositionChangedTimer, &QTimer::timeout, this, &KileView::Manager::handleCursorPositionChangedTimeout); + + m_clearLastShownSourceLocationTimer = new QTimer(this); + m_clearLastShownSourceLocationTimer->setInterval(3000); + m_clearLastShownSourceLocationTimer->setSingleShot(true); + connect(m_clearLastShownSourceLocationTimer, &QTimer::timeout, this, &KileView::Manager::clearLastShownSourceLocationInDocumentViewer); + + createViewerControlToolBar(); } Manager::~Manager() { - KILE_DEBUG_MAIN; + KILE_DEBUG_MAIN; - // the parent of the widget might be Q_NULLPTR; see 'destroyDocumentViewerWindow()' - if(m_viewerPart) { - delete m_viewerPart->widget(); - delete m_viewerPart; - } + // the parent of the widget might be Q_NULLPTR; see 'destroyDocumentViewerWindow()' + if(m_viewerPart) { + delete m_viewerPart->widget(); + delete m_viewerPart; + } - destroyDocumentViewerWindow(); + destroyDocumentViewerWindow(); } KTextEditor::View * Manager::textViewAtTab(int index) const { - return m_tabBar->tabData(index).value(); + return m_tabBar->tabData(index).value(); } void Manager::createViewerControlToolBar() { - m_viewerControlToolBar = new KToolBar(Q_NULLPTR, false, false); - m_viewerControlToolBar->setToolButtonStyle(Qt::ToolButtonIconOnly); - m_viewerControlToolBar->setFloatable(false); - m_viewerControlToolBar->setMovable(false); - m_viewerControlToolBar->setIconDimensions(KIconLoader::SizeSmall); + m_viewerControlToolBar = new KToolBar(Q_NULLPTR, false, false); + m_viewerControlToolBar->setToolButtonStyle(Qt::ToolButtonIconOnly); + m_viewerControlToolBar->setFloatable(false); + m_viewerControlToolBar->setMovable(false); + m_viewerControlToolBar->setIconDimensions(KIconLoader::SizeSmall); - m_viewerControlToolBar->addAction(m_showCursorPositionInViewerAction); + m_viewerControlToolBar->addAction(m_showCursorPositionInViewerAction); } void Manager::setClient(KXMLGUIClient *client) { - m_client = client; - if(Q_NULLPTR == m_client->actionCollection()->action("popup_pasteaslatex")) { - m_pasteAsLaTeXAction = new QAction(i18n("Paste as LaTe&X"), this); - connect(m_pasteAsLaTeXAction, &QAction::triggered, this, &Manager::pasteAsLaTeX); - } - if(Q_NULLPTR == m_client->actionCollection()->action("popup_converttolatex")) { - m_convertToLaTeXAction = new QAction(i18n("Convert Selection to &LaTeX"), this); - connect(m_convertToLaTeXAction, &QAction::triggered, this, &Manager::convertSelectionToLaTeX); - } - if(Q_NULLPTR == m_client->actionCollection()->action("popup_quickpreview")) { - m_quickPreviewAction = new QAction(this); - connect(m_quickPreviewAction, &QAction::triggered, this, &Manager::quickPreviewPopup); - } + m_client = client; + if(Q_NULLPTR == m_client->actionCollection()->action("popup_pasteaslatex")) { + m_pasteAsLaTeXAction = new QAction(i18n("Paste as LaTe&X"), this); + connect(m_pasteAsLaTeXAction, &QAction::triggered, this, &Manager::pasteAsLaTeX); + } + if(Q_NULLPTR == m_client->actionCollection()->action("popup_converttolatex")) { + m_convertToLaTeXAction = new QAction(i18n("Convert Selection to &LaTeX"), this); + connect(m_convertToLaTeXAction, &QAction::triggered, this, &Manager::convertSelectionToLaTeX); + } + if(Q_NULLPTR == m_client->actionCollection()->action("popup_quickpreview")) { + m_quickPreviewAction = new QAction(this); + connect(m_quickPreviewAction, &QAction::triggered, this, &Manager::quickPreviewPopup); + } } void Manager::readConfig(QSplitter *splitter) { - // we might have to change the location of the viewer part - setupViewerPart(splitter); + // we might have to change the location of the viewer part + setupViewerPart(splitter); - setDocumentViewerVisible(KileConfig::showDocumentViewer()); + setDocumentViewerVisible(KileConfig::showDocumentViewer()); - m_synchronizeViewWithCursorAction->setChecked(KileConfig::synchronizeCursorWithView()); + m_synchronizeViewWithCursorAction->setChecked(KileConfig::synchronizeCursorWithView()); - Okular::ViewerInterface *viewerInterface = dynamic_cast(m_viewerPart.data()); - if(viewerInterface && !m_ki->livePreviewManager()->isLivePreviewActive()) { - viewerInterface->setWatchFileModeEnabled(KileConfig::watchFileForDocumentViewer()); - // also reload the document; this is necessary for switching back on watch-file mode as otherwise - // it would only enabled after the document has been reloaded anyway - if(m_viewerPart->url().isValid()) { - m_viewerPart->openUrl(m_viewerPart->url()); - } - } + Okular::ViewerInterface *viewerInterface = dynamic_cast(m_viewerPart.data()); + if(viewerInterface && !m_ki->livePreviewManager()->isLivePreviewActive()) { + viewerInterface->setWatchFileModeEnabled(KileConfig::watchFileForDocumentViewer()); + // also reload the document; this is necessary for switching back on watch-file mode as otherwise + // it would only enabled after the document has been reloaded anyway + if(m_viewerPart->url().isValid()) { + m_viewerPart->openUrl(m_viewerPart->url()); + } + } } void Manager::writeConfig() { - if(m_viewerPart) { - KileConfig::setShowDocumentViewer(isViewerPartShown()); - } - if(m_viewerPartWindow) { - KConfigGroup group(KSharedConfig::openConfig(), "KileDocumentViewerWindow"); - m_viewerPartWindow->saveMainWindowSettings(group); - } + if(m_viewerPart) { + KileConfig::setShowDocumentViewer(isViewerPartShown()); + } + if(m_viewerPartWindow) { + KConfigGroup group(KSharedConfig::openConfig(), "KileDocumentViewerWindow"); + m_viewerPartWindow->saveMainWindowSettings(group); + } - KileConfig::setSynchronizeCursorWithView(m_synchronizeViewWithCursorAction->isChecked()); + KileConfig::setSynchronizeCursorWithView(m_synchronizeViewWithCursorAction->isChecked()); } void Manager::setTabsAndEditorVisible(bool b) { - m_tabsAndEditorWidget->setVisible(b); + m_tabsAndEditorWidget->setVisible(b); } QWidget * Manager::createTabs(QWidget *parent) { - m_widgetStack = new QStackedWidget(parent); - DropWidget *emptyDropWidget = new DropWidget(m_widgetStack); - m_widgetStack->insertWidget(0, emptyDropWidget); - connect(emptyDropWidget, &KileView::DropWidget::testCanDecode, this, static_cast(&Manager::testCanDecodeURLs)); - connect(emptyDropWidget, &KileView::DropWidget::receivedDropEvent, m_ki->docManager(), &KileDocument::Manager::openDroppedURLs); - connect(emptyDropWidget, &KileView::DropWidget::mouseDoubleClick, [=]() { - m_ki->docManager()->fileNew(); - }); - m_tabBar = new QTabBar(parent); - QWidget *tabBarWidget = new QWidget(); - tabBarWidget->setLayout(new QHBoxLayout); - tabBarWidget->layout()->setSpacing(0); - tabBarWidget->layout()->setContentsMargins(0, 0, 0, 0); - KAcceleratorManager::setNoAccel(m_tabBar); - - // quick menu for all open documents - m_documentListButton = new QToolButton(parent); - m_documentListButton->setIcon(QIcon::fromTheme("format-list-unordered")); - m_documentListButton->setMenu(new QMenu(parent)); - m_documentListButton->setPopupMode(QToolButton::InstantPopup); - m_documentListButton->setAutoRaise(true); - m_documentListButton->setToolTip(i18n("Show sorted list of opened documents")); - m_documentListButton->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Preferred); - // lambda: update context menu - connect(m_documentListButton->menu(), &QMenu::aboutToShow, [=]() { - qDeleteAll(m_documentListButton->menu()->actions()); - m_documentListButton->menu()->clear(); - - // create a lexicographically sorted list - QVector views; - views.reserve(m_tabBar->count()); - for(int i = 0; i < m_tabBar->count(); ++i) { - views << textViewAtTab(i); - } - std::sort(views.begin(), views.end(), sortDocuments); - - foreach(KTextEditor::View* view, views) { - QAction *action = m_documentListButton->menu()->addAction(view->document()->documentName()); - action->setData(QVariant::fromValue(view)); - } - }); - // lambda: handle context menu action triggers - connect(m_documentListButton->menu(), &QMenu::triggered, [=](QAction *action) { - KTextEditor::View *view = action->data().value(); - Q_ASSERT(view); - m_tabBar->setCurrentIndex(tabIndexOf(view)); - }); - // lambda: menu button is enabled if and only if at least two documents are open - connect(this, &KileView::Manager::textViewCreated, [=]() { - m_documentListButton->setEnabled(m_tabBar->count() > 1); - }); - connect(this, &KileView::Manager::textViewClosed, [=]() { - m_documentListButton->setEnabled(m_tabBar->count() > 1); - m_cursorPositionChangedTimer->stop(); - }); - connect(this, &KileView::Manager::textViewClosed, [=]() { - m_documentListButton->setEnabled(m_tabBar->count() > 1); - }); - tabBarWidget->layout()->addWidget(m_documentListButton); - - // tabbar - m_tabBar->setFocusPolicy(Qt::ClickFocus); - m_tabBar->setMovable(true); - m_tabBar->setTabsClosable(true); - m_tabBar->setUsesScrollButtons(true); - m_tabBar->setFocus(); - m_tabBar->setContextMenuPolicy(Qt::CustomContextMenu); - tabBarWidget->layout()->addWidget(m_tabBar); - - // connect tabbar with document views - connect(m_tabBar, &QTabBar::currentChanged, this, &Manager::currentTabChanged); - connect(m_tabBar, &QTabBar::tabCloseRequested, this, &Manager::closeTab); - connect(m_tabBar, &QTabBar::customContextMenuRequested, this, &Manager::tabContext); - - // main widget in which we put everything - m_tabsAndEditorWidget = new QWidget(parent); - m_tabsAndEditorWidget->setLayout(new QVBoxLayout); - m_tabsAndEditorWidget->layout()->setSpacing(0); - m_tabsAndEditorWidget->layout()->setContentsMargins(0, 0, 0, 0); - m_tabsAndEditorWidget->layout()->addWidget(tabBarWidget); - m_tabsAndEditorWidget->layout()->addWidget(m_widgetStack); - - return m_tabsAndEditorWidget; + m_widgetStack = new QStackedWidget(parent); + DropWidget *emptyDropWidget = new DropWidget(m_widgetStack); + m_widgetStack->insertWidget(0, emptyDropWidget); + connect(emptyDropWidget, &KileView::DropWidget::testCanDecode, this, static_cast(&Manager::testCanDecodeURLs)); + connect(emptyDropWidget, &KileView::DropWidget::receivedDropEvent, m_ki->docManager(), &KileDocument::Manager::openDroppedURLs); + connect(emptyDropWidget, &KileView::DropWidget::mouseDoubleClick, [=]() { + m_ki->docManager()->fileNew(); + }); + m_tabBar = new QTabBar(parent); + QWidget *tabBarWidget = new QWidget(); + tabBarWidget->setLayout(new QHBoxLayout); + tabBarWidget->layout()->setSpacing(0); + tabBarWidget->layout()->setContentsMargins(0, 0, 0, 0); + KAcceleratorManager::setNoAccel(m_tabBar); + + // quick menu for all open documents + m_documentListButton = new QToolButton(parent); + m_documentListButton->setIcon(QIcon::fromTheme("format-list-unordered")); + m_documentListButton->setMenu(new QMenu(parent)); + m_documentListButton->setPopupMode(QToolButton::InstantPopup); + m_documentListButton->setAutoRaise(true); + m_documentListButton->setToolTip(i18n("Show sorted list of opened documents")); + m_documentListButton->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Preferred); + // lambda: update context menu + connect(m_documentListButton->menu(), &QMenu::aboutToShow, [=]() { + qDeleteAll(m_documentListButton->menu()->actions()); + m_documentListButton->menu()->clear(); + + // create a lexicographically sorted list + QVector views; + views.reserve(m_tabBar->count()); + for(int i = 0; i < m_tabBar->count(); ++i) { + views << textViewAtTab(i); + } + std::sort(views.begin(), views.end(), sortDocuments); + + foreach(KTextEditor::View* view, views) { + QAction *action = m_documentListButton->menu()->addAction(view->document()->documentName()); + action->setData(QVariant::fromValue(view)); + } + }); + // lambda: handle context menu action triggers + connect(m_documentListButton->menu(), &QMenu::triggered, [=](QAction *action) { + KTextEditor::View *view = action->data().value(); + Q_ASSERT(view); + m_tabBar->setCurrentIndex(tabIndexOf(view)); + }); + // lambda: menu button is enabled if and only if at least two documents are open + connect(this, &KileView::Manager::textViewCreated, [=]() { + m_documentListButton->setEnabled(m_tabBar->count() > 1); + }); + connect(this, &KileView::Manager::textViewClosed, [=]() { + m_documentListButton->setEnabled(m_tabBar->count() > 1); + m_cursorPositionChangedTimer->stop(); + }); + connect(this, &KileView::Manager::textViewClosed, [=]() { + m_documentListButton->setEnabled(m_tabBar->count() > 1); + }); + tabBarWidget->layout()->addWidget(m_documentListButton); + + // tabbar + m_tabBar->setFocusPolicy(Qt::ClickFocus); + m_tabBar->setMovable(true); + m_tabBar->setTabsClosable(true); + m_tabBar->setUsesScrollButtons(true); + m_tabBar->setFocus(); + m_tabBar->setContextMenuPolicy(Qt::CustomContextMenu); + tabBarWidget->layout()->addWidget(m_tabBar); + + // connect tabbar with document views + connect(m_tabBar, &QTabBar::currentChanged, this, &Manager::currentTabChanged); + connect(m_tabBar, &QTabBar::tabCloseRequested, this, &Manager::closeTab); + connect(m_tabBar, &QTabBar::customContextMenuRequested, this, &Manager::tabContext); + + // main widget in which we put everything + m_tabsAndEditorWidget = new QWidget(parent); + m_tabsAndEditorWidget->setLayout(new QVBoxLayout); + m_tabsAndEditorWidget->layout()->setSpacing(0); + m_tabsAndEditorWidget->layout()->setContentsMargins(0, 0, 0, 0); + m_tabsAndEditorWidget->layout()->addWidget(tabBarWidget); + m_tabsAndEditorWidget->layout()->addWidget(m_widgetStack); + + return m_tabsAndEditorWidget; } void Manager::closeTab(int index) { - QWidget *widget = textViewAtTab(index); - if(widget->inherits("KTextEditor::View")) { - KTextEditor::View *view = static_cast(widget); - m_ki->docManager()->fileClose(view->document()); - } + QWidget *widget = textViewAtTab(index); + if(widget->inherits("KTextEditor::View")) { + KTextEditor::View *view = static_cast(widget); + m_ki->docManager()->fileClose(view->document()); + } } void Manager::currentTabChanged(int index) { - QWidget *newlyActivatedWidget = textViewAtTab(index); - if(!newlyActivatedWidget) { - return; - } - QWidget *oldViewWidget = m_widgetStack->widget(1); - if(oldViewWidget == newlyActivatedWidget) { - return; - } - if(oldViewWidget) { - m_widgetStack->removeWidget(oldViewWidget); - } - m_widgetStack->insertWidget(1, newlyActivatedWidget); - m_widgetStack->setCurrentIndex(1); - emit currentViewChanged(newlyActivatedWidget); - KTextEditor::View *view = dynamic_cast(newlyActivatedWidget); - if(view) { - emit textViewActivated(view); - } + QWidget *newlyActivatedWidget = textViewAtTab(index); + if(!newlyActivatedWidget) { + return; + } + QWidget *oldViewWidget = m_widgetStack->widget(1); + if(oldViewWidget == newlyActivatedWidget) { + return; + } + if(oldViewWidget) { + m_widgetStack->removeWidget(oldViewWidget); + } + m_widgetStack->insertWidget(1, newlyActivatedWidget); + m_widgetStack->setCurrentIndex(1); + emit currentViewChanged(newlyActivatedWidget); + KTextEditor::View *view = dynamic_cast(newlyActivatedWidget); + if(view) { + emit textViewActivated(view); + } } void Manager::handleCursorPositionChangedTimeout() { - if(m_ki->livePreviewManager()->isLivePreviewEnabledForCurrentDocument()) { - m_ki->livePreviewManager()->showCursorPositionInDocumentViewer(); - } + if(m_ki->livePreviewManager()->isLivePreviewEnabledForCurrentDocument()) { + m_ki->livePreviewManager()->showCursorPositionInDocumentViewer(); + } } void Manager::handleCursorPositionChanged(KTextEditor::View *view, const KTextEditor::Cursor &pos) { - Q_UNUSED(view); - Q_UNUSED(pos); + Q_UNUSED(view); + Q_UNUSED(pos); - if(!m_synchronizeViewWithCursorAction->isChecked()) { - return; - } - m_cursorPositionChangedTimer->start(100); + if(!m_synchronizeViewWithCursorAction->isChecked()) { + return; + } + m_cursorPositionChangedTimer->start(100); } KTextEditor::View * Manager::createTextView(KileDocument::TextInfo *info, int index) { - KTextEditor::Document *doc = info->getDoc(); - KTextEditor::View *view = info->createView(m_tabBar, Q_NULLPTR); - Q_ASSERT(view); + KTextEditor::Document *doc = info->getDoc(); + KTextEditor::View *view = info->createView(m_tabBar, Q_NULLPTR); + Q_ASSERT(view); - if(!view) { - KMessageBox::error(m_ki->mainWindow(), i18n("Could not create an editor view."), i18n("Fatal Error")); - } + if(!view) { + KMessageBox::error(m_ki->mainWindow(), i18n("Could not create an editor view."), i18n("Fatal Error")); + } - //install a key sequence recorder on the view - view->focusProxy()->installEventFilter(new KileEditorKeySequence::Recorder(view, m_ki->editorKeySequenceManager())); + //install a key sequence recorder on the view + view->focusProxy()->installEventFilter(new KileEditorKeySequence::Recorder(view, m_ki->editorKeySequenceManager())); - // in the case of simple text documents, we mimic the behaviour of LaTeX documents - if(info->getType() == KileDocument::Text) { + // in the case of simple text documents, we mimic the behaviour of LaTeX documents + if(info->getType() == KileDocument::Text) { // view->focusProxy()->installEventFilter(m_ki->eventFilter()); - } + } - index = m_tabBar->insertTab(index, QString()); // if index=-1 for appending tab, it gets assigned a new index - m_tabBar->setTabData(index, QVariant::fromValue(view)); + index = m_tabBar->insertTab(index, QString()); // if index=-1 for appending tab, it gets assigned a new index + m_tabBar->setTabData(index, QVariant::fromValue(view)); - connect(view, &KTextEditor::View::cursorPositionChanged, this, &Manager::cursorPositionChanged); - connect(view, &KTextEditor::View::viewModeChanged, this, &Manager::viewModeChanged); - connect(view, &KTextEditor::View::selectionChanged, this, &Manager::selectionChanged); - connect(view, &KTextEditor::View::viewModeChanged, this, &Manager::updateCaption); - connect(view, &KTextEditor::View::viewInputModeChanged, this, &Manager::updateModeStatus); + connect(view, &KTextEditor::View::cursorPositionChanged, this, &Manager::cursorPositionChanged); + connect(view, &KTextEditor::View::viewModeChanged, this, &Manager::viewModeChanged); + connect(view, &KTextEditor::View::selectionChanged, this, &Manager::selectionChanged); + connect(view, &KTextEditor::View::viewModeChanged, this, &Manager::updateCaption); + connect(view, &KTextEditor::View::viewInputModeChanged, this, &Manager::updateModeStatus); //TODO KF5: signals not available anymore // connect(view, SIGNAL(informationMessage(KTextEditor::View*,const QString&)), this, SIGNAL(informationMessage(KTextEditor::View*,const QString&))); // connect(view, SIGNAL(dropEventPass(QDropEvent *)), m_ki->docManager(), SLOT(openDroppedURLs(QDropEvent *))); - connect(view, &KTextEditor::View::textInserted, m_ki->codeCompletionManager(), &KileCodeCompletion::Manager::textInserted); - connect(doc, &KTextEditor::Document::documentNameChanged, this, &Manager::updateTabTexts); - connect(doc, &KTextEditor::Document::documentUrlChanged, this, &Manager::updateTabTexts); - - connect(this, &KileView::Manager::textViewClosed, m_cursorPositionChangedTimer, &QTimer::stop); - - // code completion - KTextEditor::CodeCompletionInterface *completionInterface = qobject_cast(view); - if(completionInterface) { - completionInterface->setAutomaticInvocationEnabled(true); - } - - // install a working text editor part popup dialog thingy - installContextMenu(view); - - // delete the 'Configure Editor...' action - delete view->actionCollection()->action("set_confdlg"); - // delete the "save copy as" action as we have our own - delete view->actionCollection()->action("file_save_copy_as"); - - // use Kile's save and save-as functions instead of the text editor's - QAction *action = view->actionCollection()->action(KStandardAction::name(KStandardAction::Save)); - if(action) { - KILE_DEBUG_MAIN << " reconnect action 'file_save'..."; - disconnect(action, &QAction::triggered, 0, 0); - connect(action, &QAction::triggered, [=]() { - m_ki->docManager()->fileSave(); - }); - } - action = view->actionCollection()->action(KStandardAction::name(KStandardAction::SaveAs)); - if(action) { - KILE_DEBUG_MAIN << " reconnect action 'file_save_as'..."; - disconnect(action, &QAction::triggered, 0, 0); - connect(action, &QAction::triggered, [=]() { - m_ki->docManager()->fileSaveAs(); - }); - } - updateTabTexts(doc); - // we do this twice as otherwise the tool tip for the first view did not appear (Qt issue ?) - // (BUG 205245) - updateTabTexts(doc); - - m_tabBar->setCurrentIndex(index); - if(m_tabBar->count() == 1) { // when the tab bar is empty initially, 'setCurrentIndex' won't have any effect - currentTabChanged(0); // at this point; so we do it manually - } - - //activate the newly created view - emit(textViewCreated(view)); - emit(activateView(view, false)); - emit(updateCaption()); //make sure the caption gets updated - - reflectDocumentModificationStatus(view->document(), false, KTextEditor::ModificationInterface::OnDiskUnmodified); - - return view; + connect(view, &KTextEditor::View::textInserted, m_ki->codeCompletionManager(), &KileCodeCompletion::Manager::textInserted); + connect(doc, &KTextEditor::Document::documentNameChanged, this, &Manager::updateTabTexts); + connect(doc, &KTextEditor::Document::documentUrlChanged, this, &Manager::updateTabTexts); + + connect(this, &KileView::Manager::textViewClosed, m_cursorPositionChangedTimer, &QTimer::stop); + + // code completion + KTextEditor::CodeCompletionInterface *completionInterface = qobject_cast(view); + if(completionInterface) { + completionInterface->setAutomaticInvocationEnabled(true); + } + + // install a working text editor part popup dialog thingy + installContextMenu(view); + + // delete the 'Configure Editor...' action + delete view->actionCollection()->action("set_confdlg"); + // delete the "save copy as" action as we have our own + delete view->actionCollection()->action("file_save_copy_as"); + + // use Kile's save and save-as functions instead of the text editor's + QAction *action = view->actionCollection()->action(KStandardAction::name(KStandardAction::Save)); + if(action) { + KILE_DEBUG_MAIN << " reconnect action 'file_save'..."; + disconnect(action, &QAction::triggered, 0, 0); + connect(action, &QAction::triggered, [=]() { + m_ki->docManager()->fileSave(); + }); + } + action = view->actionCollection()->action(KStandardAction::name(KStandardAction::SaveAs)); + if(action) { + KILE_DEBUG_MAIN << " reconnect action 'file_save_as'..."; + disconnect(action, &QAction::triggered, 0, 0); + connect(action, &QAction::triggered, [=]() { + m_ki->docManager()->fileSaveAs(); + }); + } + updateTabTexts(doc); + // we do this twice as otherwise the tool tip for the first view did not appear (Qt issue ?) + // (BUG 205245) + updateTabTexts(doc); + + m_tabBar->setCurrentIndex(index); + if(m_tabBar->count() == 1) { // when the tab bar is empty initially, 'setCurrentIndex' won't have any effect + currentTabChanged(0); // at this point; so we do it manually + } + + //activate the newly created view + emit(textViewCreated(view)); + emit(activateView(view, false)); + emit(updateCaption()); //make sure the caption gets updated + + reflectDocumentModificationStatus(view->document(), false, KTextEditor::ModificationInterface::OnDiskUnmodified); + + return view; } void Manager::installContextMenu(KTextEditor::View *view) { - QMenu *popupMenu = view->defaultContextMenu(); - - if(popupMenu) { - connect(popupMenu, &QMenu::aboutToShow, this, &Manager::onTextEditorPopupMenuRequest); - - // install some more actions on it - popupMenu->addSeparator(); - popupMenu->addAction(m_pasteAsLaTeXAction); - popupMenu->addAction(m_convertToLaTeXAction); - popupMenu->addSeparator(); - popupMenu->addAction(m_quickPreviewAction); - - // insert actions from user-defined latex menu - KileMenu::UserMenu *usermenu = m_ki->userMenu(); - if(usermenu) { - KILE_DEBUG_MAIN << "Insert actions from user-defined latex menu"; - popupMenu->addSeparator(); - foreach(QAction *action, usermenu->contextMenuActions()) { - if(action) { - popupMenu->addAction(action); - } - else { - popupMenu->addSeparator(); - } - } - } - - view->setContextMenu(popupMenu); - } + QMenu *popupMenu = view->defaultContextMenu(); + + if(popupMenu) { + connect(popupMenu, &QMenu::aboutToShow, this, &Manager::onTextEditorPopupMenuRequest); + + // install some more actions on it + popupMenu->addSeparator(); + popupMenu->addAction(m_pasteAsLaTeXAction); + popupMenu->addAction(m_convertToLaTeXAction); + popupMenu->addSeparator(); + popupMenu->addAction(m_quickPreviewAction); + + // insert actions from user-defined latex menu + KileMenu::UserMenu *usermenu = m_ki->userMenu(); + if(usermenu) { + KILE_DEBUG_MAIN << "Insert actions from user-defined latex menu"; + popupMenu->addSeparator(); + foreach(QAction *action, usermenu->contextMenuActions()) { + if(action) { + popupMenu->addAction(action); + } + else { + popupMenu->addSeparator(); + } + } + } + + view->setContextMenu(popupMenu); + } } void Manager::tabContext(const QPoint &pos) { - KILE_DEBUG_MAIN << pos; - const int tabUnderPos = m_tabBar->tabAt(pos); - if(tabUnderPos < 0) { - KILE_DEBUG_MAIN << tabUnderPos; - return; - } - - KTextEditor::View *view = textViewAtTab(tabUnderPos); - - if(!view || !view->document()) { - return; - } - - QMenu tabMenu; - - tabMenu.addSection(m_ki->getShortName(view->document())); - - // 'action1' can become null if it belongs to a view that has been closed, for example - QPointer action1 = m_ki->mainWindow()->action("move_view_tab_left"); - action1->setData(qVariantFromValue(view)); - tabMenu.addAction(action1); - - QPointer action2 = m_ki->mainWindow()->action("move_view_tab_right"); - action2->setData(qVariantFromValue(view)); - tabMenu.addAction(action2); - - tabMenu.addSeparator(); - - QPointer action3; - if(view->document()->isModified()) { - action3 = view->actionCollection()->action(KStandardAction::name(KStandardAction::Save)); - action3->setData(qVariantFromValue(view)); - tabMenu.addAction(action3); - } - - QPointer action4 = view->actionCollection()->action(KStandardAction::name(KStandardAction::SaveAs)); - action4->setData(qVariantFromValue(view)); - tabMenu.addAction(action4); - - QPointer action5 = m_ki->mainWindow()->action("file_save_copy_as"); - action5->setData(qVariantFromValue(view)); - tabMenu.addAction(action5); - - tabMenu.addSeparator(); - - QPointer action6 = m_ki->mainWindow()->action("file_close"); - action6->setData(qVariantFromValue(view)); - tabMenu.addAction(action6); - - QPointer action7 = m_ki->mainWindow()->action("file_close_all_others"); - action7->setData(qVariantFromValue(view)); - tabMenu.addAction(action7); -/* - FIXME create proper actions which delete/add the current file without asking stupidly - QAction* removeAction = m_ki->mainWindow()->action("project_remove"); - QAction* addAction = m_ki->mainWindow()->action("project_add"); - - tabMenu.insertSeparator(addAction); - tabMenu.addAction(addAction); - tabMenu.addAction(removeAction);*/ - - tabMenu.exec(m_tabBar->mapToGlobal(pos)); - - if(action1) { - action1->setData(QVariant()); - } - if(action2) { - action2->setData(QVariant()); - } - if(action3) { - action3->setData(QVariant()); - } - if(action4) { - action4->setData(QVariant()); - } - if(action5) { - action5->setData(QVariant()); - } - if(action6) { - action6->setData(QVariant()); - } - if(action7) { - action7->setData(QVariant()); - } + KILE_DEBUG_MAIN << pos; + const int tabUnderPos = m_tabBar->tabAt(pos); + if(tabUnderPos < 0) { + KILE_DEBUG_MAIN << tabUnderPos; + return; + } + + KTextEditor::View *view = textViewAtTab(tabUnderPos); + + if(!view || !view->document()) { + return; + } + + QMenu tabMenu; + + tabMenu.addSection(m_ki->getShortName(view->document())); + + // 'action1' can become null if it belongs to a view that has been closed, for example + QPointer action1 = m_ki->mainWindow()->action("move_view_tab_left"); + action1->setData(qVariantFromValue(view)); + tabMenu.addAction(action1); + + QPointer action2 = m_ki->mainWindow()->action("move_view_tab_right"); + action2->setData(qVariantFromValue(view)); + tabMenu.addAction(action2); + + tabMenu.addSeparator(); + + QPointer action3; + if(view->document()->isModified()) { + action3 = view->actionCollection()->action(KStandardAction::name(KStandardAction::Save)); + action3->setData(qVariantFromValue(view)); + tabMenu.addAction(action3); + } + + QPointer action4 = view->actionCollection()->action(KStandardAction::name(KStandardAction::SaveAs)); + action4->setData(qVariantFromValue(view)); + tabMenu.addAction(action4); + + QPointer action5 = m_ki->mainWindow()->action("file_save_copy_as"); + action5->setData(qVariantFromValue(view)); + tabMenu.addAction(action5); + + tabMenu.addSeparator(); + + QPointer action6 = m_ki->mainWindow()->action("file_close"); + action6->setData(qVariantFromValue(view)); + tabMenu.addAction(action6); + + QPointer action7 = m_ki->mainWindow()->action("file_close_all_others"); + action7->setData(qVariantFromValue(view)); + tabMenu.addAction(action7); + /* + FIXME create proper actions which delete/add the current file without asking stupidly + QAction* removeAction = m_ki->mainWindow()->action("project_remove"); + QAction* addAction = m_ki->mainWindow()->action("project_add"); + + tabMenu.insertSeparator(addAction); + tabMenu.addAction(addAction); + tabMenu.addAction(removeAction);*/ + + tabMenu.exec(m_tabBar->mapToGlobal(pos)); + + if(action1) { + action1->setData(QVariant()); + } + if(action2) { + action2->setData(QVariant()); + } + if(action3) { + action3->setData(QVariant()); + } + if(action4) { + action4->setData(QVariant()); + } + if(action5) { + action5->setData(QVariant()); + } + if(action6) { + action6->setData(QVariant()); + } + if(action7) { + action7->setData(QVariant()); + } } void Manager::removeView(KTextEditor::View *view) { - if(view) { - m_client->factory()->removeClient(view); + if(view) { + m_client->factory()->removeClient(view); - const bool isActiveView = (KTextEditor::Editor::instance()->application()->activeMainWindow()->activeView() == view); - m_tabBar->removeTab(tabIndexOf(view)); + const bool isActiveView = (KTextEditor::Editor::instance()->application()->activeMainWindow()->activeView() == view); + m_tabBar->removeTab(tabIndexOf(view)); - emit(updateCaption()); //make sure the caption gets updated - if(m_tabBar->count() == 0) { - m_ki->structureWidget()->clear(); - m_widgetStack->setCurrentIndex(0); // if there are no open views, then show the DropWidget - } + emit(updateCaption()); //make sure the caption gets updated + if(m_tabBar->count() == 0) { + m_ki->structureWidget()->clear(); + m_widgetStack->setCurrentIndex(0); // if there are no open views, then show the DropWidget + } - emit(textViewClosed(view, isActiveView)); - delete view; - } - else { - KILE_DEBUG_MAIN << "View should be removed but is Q_NULLPTR"; - } + emit(textViewClosed(view, isActiveView)); + delete view; + } + else { + KILE_DEBUG_MAIN << "View should be removed but is Q_NULLPTR"; + } } KTextEditor::View * Manager::currentTextView() const { - return textViewAtTab(m_tabBar->currentIndex()); + return textViewAtTab(m_tabBar->currentIndex()); } KTextEditor::View * Manager::textView(int index) const { - Q_ASSERT(textViewAtTab(index)); - return textViewAtTab(index); + Q_ASSERT(textViewAtTab(index)); + return textViewAtTab(index); } KTextEditor::View * Manager::textView(KileDocument::TextInfo *info) const { - KTextEditor::Document *doc = info->getDoc(); - if(!doc) { - return Q_NULLPTR; - } - for(int i = 0; i < m_tabBar->count(); ++i) { - KTextEditor::View *view = textViewAtTab(i); - if(!view) { - continue; - } + KTextEditor::Document *doc = info->getDoc(); + if(!doc) { + return Q_NULLPTR; + } + for(int i = 0; i < m_tabBar->count(); ++i) { + KTextEditor::View *view = textViewAtTab(i); + if(!view) { + continue; + } - if(view->document() == doc) { - return view; - } - } + if(view->document() == doc) { + return view; + } + } - return Q_NULLPTR; + return Q_NULLPTR; } int Manager::textViewCount() const { - return m_tabBar->count(); + return m_tabBar->count(); } int Manager::tabIndexOf(KTextEditor::View* view) const { - for(int i = 0; i < m_tabBar->count(); ++i) { - if(textViewAtTab(i) == view) { - return i; - } - } - return -1; + for(int i = 0; i < m_tabBar->count(); ++i) { + if(textViewAtTab(i) == view) { + return i; + } + } + return -1; } unsigned int Manager::getTabCount() const { - return m_tabBar->count(); + return m_tabBar->count(); } KTextEditor::View * Manager::switchToTextView(const QUrl &url, bool requestFocus) { - return switchToTextView(m_ki->docManager()->docFor(url), requestFocus); + return switchToTextView(m_ki->docManager()->docFor(url), requestFocus); } KTextEditor::View * Manager::switchToTextView(KTextEditor::Document *doc, bool requestFocus) { - KTextEditor::View *view = Q_NULLPTR; - if(doc) { - if(doc->views().count() > 0) { - view = doc->views().first(); - if(view) { - switchToTextView(view, requestFocus); - } - } - } - return view; + KTextEditor::View *view = Q_NULLPTR; + if(doc) { + if(doc->views().count() > 0) { + view = doc->views().first(); + if(view) { + switchToTextView(view, requestFocus); + } + } + } + return view; } void Manager::switchToTextView(KTextEditor::View *view, bool requestFocus) { - int index = tabIndexOf(view); - if(index < 0) { - return; - } - m_tabBar->setCurrentIndex(index); - if(requestFocus) { - focusTextView(view); - } + int index = tabIndexOf(view); + if(index < 0) { + return; + } + m_tabBar->setCurrentIndex(index); + if(requestFocus) { + focusTextView(view); + } } void Manager::setTabIcon(QWidget *view, const QIcon& icon) { - m_tabBar->setTabIcon(tabIndexOf(qobject_cast(view)), icon); + m_tabBar->setTabIcon(tabIndexOf(qobject_cast(view)), icon); } void Manager::updateStructure(bool parse /* = false */, KileDocument::Info *docinfo /* = Q_NULLPTR */) { - if(!docinfo) { - docinfo = m_ki->docManager()->getInfo(); - } + if(!docinfo) { + docinfo = m_ki->docManager()->getInfo(); + } - if(docinfo) { - m_ki->structureWidget()->update(docinfo, parse); - } + if(docinfo) { + m_ki->structureWidget()->update(docinfo, parse); + } - if(m_tabBar->count() == 0) { - m_ki->structureWidget()->clear(); - } + if(m_tabBar->count() == 0) { + m_ki->structureWidget()->clear(); + } } void Manager::gotoNextView() { - if(m_tabBar->count() < 2) { - return; - } + if(m_tabBar->count() < 2) { + return; + } - int cPage = m_tabBar->currentIndex() + 1; - if(cPage >= m_tabBar->count()) { - m_tabBar->setCurrentIndex(0); - } - else { - m_tabBar->setCurrentIndex(cPage); - } + int cPage = m_tabBar->currentIndex() + 1; + if(cPage >= m_tabBar->count()) { + m_tabBar->setCurrentIndex(0); + } + else { + m_tabBar->setCurrentIndex(cPage); + } } void Manager::gotoPrevView() { - if(m_tabBar->count() < 2) { - return; - } + if(m_tabBar->count() < 2) { + return; + } - int cPage = m_tabBar->currentIndex() - 1; - if(cPage < 0) { - m_tabBar->setCurrentIndex(m_tabBar->count() - 1); - } - else { - m_tabBar->setCurrentIndex(cPage); - } + int cPage = m_tabBar->currentIndex() - 1; + if(cPage < 0) { + m_tabBar->setCurrentIndex(m_tabBar->count() - 1); + } + else { + m_tabBar->setCurrentIndex(cPage); + } } void Manager::moveTabLeft(QWidget *widget) { - if(m_tabBar->count() < 2) { - return; - } - - // the 'data' property can be set by 'tabContext' - QAction *action = dynamic_cast(QObject::sender()); - if(action) { - QVariant var = action->data(); - if(!widget && var.isValid()) { - // the action's 'data' property is cleared - // when the context menu is destroyed - widget = var.value(); - } - } - if(!widget) { - widget = currentTextView(); - } - if(!widget) { - return; - } - int currentIndex = tabIndexOf(qobject_cast(widget)); - int newIndex = (currentIndex == 0 ? m_tabBar->count() - 1 : currentIndex - 1); - m_tabBar->moveTab(currentIndex, newIndex); + if(m_tabBar->count() < 2) { + return; + } + + // the 'data' property can be set by 'tabContext' + QAction *action = dynamic_cast(QObject::sender()); + if(action) { + QVariant var = action->data(); + if(!widget && var.isValid()) { + // the action's 'data' property is cleared + // when the context menu is destroyed + widget = var.value(); + } + } + if(!widget) { + widget = currentTextView(); + } + if(!widget) { + return; + } + int currentIndex = tabIndexOf(qobject_cast(widget)); + int newIndex = (currentIndex == 0 ? m_tabBar->count() - 1 : currentIndex - 1); + m_tabBar->moveTab(currentIndex, newIndex); } void Manager::moveTabRight(QWidget *widget) { - if(m_tabBar->count() < 2) { - return; - } - - // the 'data' property can be set by 'tabContext' - QAction *action = dynamic_cast(QObject::sender()); - if(action) { - QVariant var = action->data(); - if(!widget && var.isValid()) { - // the action's 'data' property is cleared - // when the context menu is destroyed - widget = var.value(); - } - } - if(!widget) { - widget = currentTextView(); - } - if(!widget) { - return; - } - int currentIndex = tabIndexOf(qobject_cast(widget)); - int newIndex = (currentIndex == m_tabBar->count() - 1 ? 0 : currentIndex + 1); - m_tabBar->moveTab(currentIndex, newIndex); + if(m_tabBar->count() < 2) { + return; + } + + // the 'data' property can be set by 'tabContext' + QAction *action = dynamic_cast(QObject::sender()); + if(action) { + QVariant var = action->data(); + if(!widget && var.isValid()) { + // the action's 'data' property is cleared + // when the context menu is destroyed + widget = var.value(); + } + } + if(!widget) { + widget = currentTextView(); + } + if(!widget) { + return; + } + int currentIndex = tabIndexOf(qobject_cast(widget)); + int newIndex = (currentIndex == m_tabBar->count() - 1 ? 0 : currentIndex + 1); + m_tabBar->moveTab(currentIndex, newIndex); } void Manager::reflectDocumentModificationStatus(KTextEditor::Document *doc, - bool isModified, - KTextEditor::ModificationInterface::ModifiedOnDiskReason reason) -{ - QIcon icon; - if(reason == KTextEditor::ModificationInterface::OnDiskUnmodified && isModified) { //nothing - icon = QIcon::fromTheme("modified"); // This icon is taken from Kate. Therefore - // our thanks go to the authors of Kate. - } - else if(reason == KTextEditor::ModificationInterface::OnDiskModified - || reason == KTextEditor::ModificationInterface::OnDiskCreated) { //dirty file - icon = QIcon::fromTheme("modonhd"); // This icon is taken from Kate. Therefore - // our thanks go to the authors of Kate. - } - else if(reason == KTextEditor::ModificationInterface::OnDiskDeleted) { //file deleted - icon = QIcon::fromTheme("process-stop"); - } - else if(m_ki->extensions()->isScriptFile(doc->url())) { - icon = QIcon::fromTheme("js"); - } - else { - icon = QIcon::fromTheme(KIO::iconNameForUrl(doc->url())); - } - - const QList &viewsList = doc->views(); - for(QList::const_iterator i = viewsList.begin(); i != viewsList.end(); ++i) { - setTabIcon(*i, icon); - } + bool isModified, + KTextEditor::ModificationInterface::ModifiedOnDiskReason reason) +{ + QIcon icon; + if(reason == KTextEditor::ModificationInterface::OnDiskUnmodified && isModified) { //nothing + icon = QIcon::fromTheme("modified"); // This icon is taken from Kate. Therefore + // our thanks go to the authors of Kate. + } + else if(reason == KTextEditor::ModificationInterface::OnDiskModified + || reason == KTextEditor::ModificationInterface::OnDiskCreated) { //dirty file + icon = QIcon::fromTheme("modonhd"); // This icon is taken from Kate. Therefore + // our thanks go to the authors of Kate. + } + else if(reason == KTextEditor::ModificationInterface::OnDiskDeleted) { //file deleted + icon = QIcon::fromTheme("process-stop"); + } + else if(m_ki->extensions()->isScriptFile(doc->url())) { + icon = QIcon::fromTheme("js"); + } + else { + icon = QIcon::fromTheme(KIO::iconNameForUrl(doc->url())); + } + + const QList &viewsList = doc->views(); + for(QList::const_iterator i = viewsList.begin(); i != viewsList.end(); ++i) { + setTabIcon(*i, icon); + } } /** * Adds/removes the "Convert to LaTeX" entry in Kate's popup menu according to the selection. */ void Manager::onTextEditorPopupMenuRequest() { - KTextEditor::View *view = currentTextView(); - if(!view) { - return; - } - - const QString quickPreviewSelection = i18n("&QuickPreview Selection"); - const QString quickPreviewEnvironment = i18n("&QuickPreview Environment"); - const QString quickPreviewMath = i18n("&QuickPreview Math"); - - // Setting up the "QuickPreview selection" entry - if(view->selection()) { - m_quickPreviewAction->setText(quickPreviewSelection); - m_quickPreviewAction->setEnabled(true); - - } - else if(m_ki->editorExtension()->hasMathgroup(view)) { - m_quickPreviewAction->setText(quickPreviewMath); - m_quickPreviewAction->setEnabled(true); - } - else if(m_ki->editorExtension()->hasEnvironment(view)) { - m_quickPreviewAction->setText(quickPreviewEnvironment); - m_quickPreviewAction->setEnabled(true); - } - else { - m_quickPreviewAction->setText(quickPreviewSelection); - m_quickPreviewAction->setEnabled(false); - } - - - // Setting up the "Convert to LaTeX" entry - m_convertToLaTeXAction->setEnabled(view->selection()); - - // Setting up the "Paste as LaTeX" entry - QClipboard *clipboard = QApplication::clipboard(); - if(clipboard) { - m_pasteAsLaTeXAction->setEnabled(!clipboard->text().isEmpty()); - } + KTextEditor::View *view = currentTextView(); + if(!view) { + return; + } + + const QString quickPreviewSelection = i18n("&QuickPreview Selection"); + const QString quickPreviewEnvironment = i18n("&QuickPreview Environment"); + const QString quickPreviewMath = i18n("&QuickPreview Math"); + + // Setting up the "QuickPreview selection" entry + if(view->selection()) { + m_quickPreviewAction->setText(quickPreviewSelection); + m_quickPreviewAction->setEnabled(true); + + } + else if(m_ki->editorExtension()->hasMathgroup(view)) { + m_quickPreviewAction->setText(quickPreviewMath); + m_quickPreviewAction->setEnabled(true); + } + else if(m_ki->editorExtension()->hasEnvironment(view)) { + m_quickPreviewAction->setText(quickPreviewEnvironment); + m_quickPreviewAction->setEnabled(true); + } + else { + m_quickPreviewAction->setText(quickPreviewSelection); + m_quickPreviewAction->setEnabled(false); + } + + + // Setting up the "Convert to LaTeX" entry + m_convertToLaTeXAction->setEnabled(view->selection()); + + // Setting up the "Paste as LaTeX" entry + QClipboard *clipboard = QApplication::clipboard(); + if(clipboard) { + m_pasteAsLaTeXAction->setEnabled(!clipboard->text().isEmpty()); + } } void Manager::convertSelectionToLaTeX(void) { - KTextEditor::View *view = currentTextView(); + KTextEditor::View *view = currentTextView(); - if(view == Q_NULLPTR) { - return; - } + if(view == Q_NULLPTR) { + return; + } - KTextEditor::Document *doc = view->document(); + KTextEditor::Document *doc = view->document(); - if(doc == Q_NULLPTR) { - return; - } + if(doc == Q_NULLPTR) { + return; + } - // Getting the selection - KTextEditor::Range range = view->selectionRange(); - uint selStartLine = range.start().line(), selStartCol = range.start().column(); - uint selEndLine = range.end().line(), selEndCol = range.start().column(); + // Getting the selection + KTextEditor::Range range = view->selectionRange(); + uint selStartLine = range.start().line(), selStartCol = range.start().column(); + uint selEndLine = range.end().line(), selEndCol = range.start().column(); - /* Variable to "restore" the selection after replacement: if {} was selected, - we increase the selection of two characters */ - uint newSelEndCol; + /* Variable to "restore" the selection after replacement: if {} was selected, + we increase the selection of two characters */ + uint newSelEndCol; - PlainToLaTeXConverter cvt; + PlainToLaTeXConverter cvt; - // "Notifying" the editor that what we're about to do must be seen as ONE operation - KTextEditor::Document::EditingTransaction transaction(doc); + // "Notifying" the editor that what we're about to do must be seen as ONE operation + KTextEditor::Document::EditingTransaction transaction(doc); - // Processing the first line - int firstLineLength; - if(selStartLine != selEndLine) { - firstLineLength = doc->lineLength(selStartLine); - } else { - firstLineLength = selEndCol; - } - QString firstLine = doc->text(KTextEditor::Range(selStartLine, selStartCol, selStartLine, firstLineLength)); - QString firstLineCvt = cvt.ConvertToLaTeX(firstLine); - doc->removeText(KTextEditor::Range(selStartLine, selStartCol, selStartLine, firstLineLength)); - doc->insertText(KTextEditor::Cursor(selStartLine, selStartCol), firstLineCvt); - newSelEndCol = selStartCol + firstLineCvt.length(); + // Processing the first line + int firstLineLength; + if(selStartLine != selEndLine) { + firstLineLength = doc->lineLength(selStartLine); + } else { + firstLineLength = selEndCol; + } + QString firstLine = doc->text(KTextEditor::Range(selStartLine, selStartCol, selStartLine, firstLineLength)); + QString firstLineCvt = cvt.ConvertToLaTeX(firstLine); + doc->removeText(KTextEditor::Range(selStartLine, selStartCol, selStartLine, firstLineLength)); + doc->insertText(KTextEditor::Cursor(selStartLine, selStartCol), firstLineCvt); + newSelEndCol = selStartCol + firstLineCvt.length(); - // Processing the intermediate lines - for(uint nLine = selStartLine + 1; nLine < selEndLine; ++nLine) { - QString line = doc->line(nLine); - QString newLine = cvt.ConvertToLaTeX(line); - doc->removeLine(nLine); - doc->insertLine(nLine, newLine); - } + // Processing the intermediate lines + for(uint nLine = selStartLine + 1; nLine < selEndLine; ++nLine) { + QString line = doc->line(nLine); + QString newLine = cvt.ConvertToLaTeX(line); + doc->removeLine(nLine); + doc->insertLine(nLine, newLine); + } - // Processing the final line - if(selStartLine != selEndLine) { - QString lastLine = doc->text(KTextEditor::Range(selEndLine, 0, selEndLine, selEndCol)); - QString lastLineCvt = cvt.ConvertToLaTeX(lastLine); - doc->removeText(KTextEditor::Range(selEndLine, 0, selEndLine, selEndCol)); - doc->insertText(KTextEditor::Cursor(selEndLine, 0), lastLineCvt); - newSelEndCol = lastLineCvt.length(); - } + // Processing the final line + if(selStartLine != selEndLine) { + QString lastLine = doc->text(KTextEditor::Range(selEndLine, 0, selEndLine, selEndCol)); + QString lastLineCvt = cvt.ConvertToLaTeX(lastLine); + doc->removeText(KTextEditor::Range(selEndLine, 0, selEndLine, selEndCol)); + doc->insertText(KTextEditor::Cursor(selEndLine, 0), lastLineCvt); + newSelEndCol = lastLineCvt.length(); + } - // End of the "atomic edit operation" - transaction.finish(); + // End of the "atomic edit operation" + transaction.finish(); - view->setSelection(KTextEditor::Range(selStartLine, selStartCol, selEndLine, newSelEndCol)); + view->setSelection(KTextEditor::Range(selStartLine, selStartCol, selEndLine, newSelEndCol)); } /** * Pastes the clipboard's contents as LaTeX (ie. % -> \%, etc.). */ void Manager::pasteAsLaTeX(void) { - KTextEditor::View *view = currentTextView(); + KTextEditor::View *view = currentTextView(); - if(!view) { - return; - } + if(!view) { + return; + } - KTextEditor::Document *doc = view->document(); + KTextEditor::Document *doc = view->document(); - if(!doc) { - return; - } + if(!doc) { + return; + } - // Getting a proper text insertion point BEFORE the atomic editing operation - uint cursorLine, cursorCol; - if(view->selection()) { - KTextEditor::Range range = view->selectionRange(); - cursorLine = range.start().line(); - cursorCol = range.start().column(); - } else { - KTextEditor::Cursor cursor = view->cursorPosition(); - cursorLine = cursor.line(); - cursorCol = cursor.column(); - } + // Getting a proper text insertion point BEFORE the atomic editing operation + uint cursorLine, cursorCol; + if(view->selection()) { + KTextEditor::Range range = view->selectionRange(); + cursorLine = range.start().line(); + cursorCol = range.start().column(); + } else { + KTextEditor::Cursor cursor = view->cursorPosition(); + cursorLine = cursor.line(); + cursorCol = cursor.column(); + } - // "Notifying" the editor that what we're about to do must be seen as ONE operation - KTextEditor::Document::EditingTransaction transaction(doc); + // "Notifying" the editor that what we're about to do must be seen as ONE operation + KTextEditor::Document::EditingTransaction transaction(doc); - // If there is a selection, one must remove it - if(view->selection()) { - doc->removeText(view->selectionRange()); - } + // If there is a selection, one must remove it + if(view->selection()) { + doc->removeText(view->selectionRange()); + } - PlainToLaTeXConverter cvt; - QString toPaste = cvt.ConvertToLaTeX(QApplication::clipboard()->text()); - doc->insertText(KTextEditor::Cursor(cursorLine, cursorCol), toPaste); + PlainToLaTeXConverter cvt; + QString toPaste = cvt.ConvertToLaTeX(QApplication::clipboard()->text()); + doc->insertText(KTextEditor::Cursor(cursorLine, cursorCol), toPaste); - // End of the "atomic edit operation" - transaction.finish(); + // End of the "atomic edit operation" + transaction.finish(); } void Manager::quickPreviewPopup() { - KTextEditor::View *view = currentTextView(); - if(!view) { - return; - } + KTextEditor::View *view = currentTextView(); + if(!view) { + return; + } - if(view->selection()) { - emit(startQuickPreview(KileTool::qpSelection)); - } - else if(m_ki->editorExtension()->hasMathgroup(view)) { - emit(startQuickPreview(KileTool::qpMathgroup)); - } - else if(m_ki->editorExtension()->hasEnvironment(view)) { - emit(startQuickPreview(KileTool::qpEnvironment)); - } + if(view->selection()) { + emit(startQuickPreview(KileTool::qpSelection)); + } + else if(m_ki->editorExtension()->hasMathgroup(view)) { + emit(startQuickPreview(KileTool::qpMathgroup)); + } + else if(m_ki->editorExtension()->hasEnvironment(view)) { + emit(startQuickPreview(KileTool::qpEnvironment)); + } } void Manager::testCanDecodeURLs(const QDragEnterEvent *e, bool &accept) { - accept = e->mimeData()->hasUrls(); // only accept URL drops + accept = e->mimeData()->hasUrls(); // only accept URL drops } void Manager::testCanDecodeURLs(const QDragMoveEvent *e, bool &accept) { - accept = e->mimeData()->hasUrls(); // only accept URL drops + accept = e->mimeData()->hasUrls(); // only accept URL drops } void Manager::replaceLoadedURL(QWidget *w, QDropEvent *e) { - QList urls = e->mimeData()->urls(); - if(urls.isEmpty()) { - return; - } - int index = tabIndexOf(qobject_cast(w)); - KileDocument::Extensions *extensions = m_ki->extensions(); - bool hasReplacedTab = false; - for(QList::iterator i = urls.begin(); i != urls.end(); ++i) { - QUrl url = *i; - if(extensions->isProjectFile(url)) { - m_ki->docManager()->projectOpen(url); - } - else if(!hasReplacedTab) { - closeTab(index); - m_ki->docManager()->fileOpen(url, QString(), index); - hasReplacedTab = true; - } - else { - m_ki->docManager()->fileOpen(url); - } - } + QList urls = e->mimeData()->urls(); + if(urls.isEmpty()) { + return; + } + int index = tabIndexOf(qobject_cast(w)); + KileDocument::Extensions *extensions = m_ki->extensions(); + bool hasReplacedTab = false; + for(QList::iterator i = urls.begin(); i != urls.end(); ++i) { + QUrl url = *i; + if(extensions->isProjectFile(url)) { + m_ki->docManager()->projectOpen(url); + } + else if(!hasReplacedTab) { + closeTab(index); + m_ki->docManager()->fileOpen(url, QString(), index); + hasReplacedTab = true; + } + else { + m_ki->docManager()->fileOpen(url); + } + } } void Manager::updateTabTexts(KTextEditor::Document *changedDoc) { - const QList &viewsList = changedDoc->views(); - for(QList::const_iterator i = viewsList.begin(); i != viewsList.end(); ++i) { - QString documentName = changedDoc->documentName(); - if(documentName.isEmpty()) { - documentName = i18n("Untitled"); - } - const int viewIndex = tabIndexOf(*i); - m_tabBar->setTabText(viewIndex, documentName); - m_tabBar->setTabToolTip(viewIndex, changedDoc->url().toString()); - } + const QList &viewsList = changedDoc->views(); + for(QList::const_iterator i = viewsList.begin(); i != viewsList.end(); ++i) { + QString documentName = changedDoc->documentName(); + if(documentName.isEmpty()) { + documentName = i18n("Untitled"); + } + const int viewIndex = tabIndexOf(*i); + m_tabBar->setTabText(viewIndex, documentName); + m_tabBar->setTabToolTip(viewIndex, changedDoc->url().toString()); + } } DropWidget::DropWidget(QWidget *parent, const char *name, Qt::WindowFlags f) : QWidget(parent, f) { - setObjectName(name); - setAcceptDrops(true); + setObjectName(name); + setAcceptDrops(true); } DropWidget::~DropWidget() { } void DropWidget::dragEnterEvent(QDragEnterEvent *e) { - bool b; - emit testCanDecode(e, b); - if(b) { - e->acceptProposedAction(); - } + bool b; + emit testCanDecode(e, b); + if(b) { + e->acceptProposedAction(); + } } void DropWidget::dropEvent(QDropEvent *e) { - emit receivedDropEvent(e); + emit receivedDropEvent(e); } void DropWidget::mouseDoubleClickEvent(QMouseEvent *e) { - Q_UNUSED(e); - emit mouseDoubleClick(); + Q_UNUSED(e); + emit mouseDoubleClick(); } void Manager::installEventFilter(KTextEditor::View *view, QObject *eventFilter) { - QWidget *focusProxy = view->focusProxy(); - if(focusProxy) { - focusProxy->installEventFilter(eventFilter); - } - else { - view->installEventFilter(eventFilter); - } + QWidget *focusProxy = view->focusProxy(); + if(focusProxy) { + focusProxy->installEventFilter(eventFilter); + } + else { + view->installEventFilter(eventFilter); + } } void Manager::removeEventFilter(KTextEditor::View *view, QObject *eventFilter) { - QWidget *focusProxy = view->focusProxy(); - if(focusProxy) { - focusProxy->removeEventFilter(eventFilter); - } - else { - view->removeEventFilter(eventFilter); - } + QWidget *focusProxy = view->focusProxy(); + if(focusProxy) { + focusProxy->removeEventFilter(eventFilter); + } + else { + view->removeEventFilter(eventFilter); + } } //BEGIN ViewerPart methods void Manager::createViewerPart(KActionCollection *actionCollection) { - m_viewerPart = Q_NULLPTR; - - KPluginLoader pluginLoader(OKULAR_LIBRARY_NAME); - KPluginFactory *factory = pluginLoader.factory(); - if(!factory) { - KILE_DEBUG_MAIN << "Could not find the Okular library."; - m_viewerPart = Q_NULLPTR; - return; - } - else { - QVariantList argList; - argList << "ViewerWidget" << "ConfigFileName=kile-livepreview-okularpartrc"; - m_viewerPart = factory->create(this, argList); - Okular::ViewerInterface *viewerInterface = dynamic_cast(m_viewerPart.data()); - if(!viewerInterface) { - // OkularPart doesn't provide the ViewerInterface - delete m_viewerPart; - m_viewerPart = Q_NULLPTR; - return; - } - viewerInterface->setWatchFileModeEnabled(false); - viewerInterface->setShowSourceLocationsGraphically(true); - connect(m_viewerPart, SIGNAL(openSourceReference(const QString&, int, int)), this, SLOT(handleActivatedSourceReference(const QString&, int, int))); - - QAction *paPrintCompiledDocument = actionCollection->addAction(KStandardAction::Print, "print_compiled_document", m_viewerPart, SLOT(slotPrint())); - paPrintCompiledDocument->setText(i18n("Print Compiled Document...")); - paPrintCompiledDocument->setShortcut(QKeySequence()); - paPrintCompiledDocument->setEnabled(false); - connect(m_viewerPart, SIGNAL(enablePrintAction(bool)), paPrintCompiledDocument, SLOT(setEnabled(bool))); - QAction *printPreviewAction = m_viewerPart->actionCollection()->action("file_print_preview"); - if(printPreviewAction) { - printPreviewAction->setText(i18n("Print Preview For Compiled Document...")); - } - } + m_viewerPart = Q_NULLPTR; + + KPluginLoader pluginLoader(OKULAR_LIBRARY_NAME); + KPluginFactory *factory = pluginLoader.factory(); + if(!factory) { + KILE_DEBUG_MAIN << "Could not find the Okular library."; + m_viewerPart = Q_NULLPTR; + return; + } + else { + QVariantList argList; + argList << "ViewerWidget" << "ConfigFileName=kile-livepreview-okularpartrc"; + m_viewerPart = factory->create(this, argList); + Okular::ViewerInterface *viewerInterface = dynamic_cast(m_viewerPart.data()); + if(!viewerInterface) { + // OkularPart doesn't provide the ViewerInterface + delete m_viewerPart; + m_viewerPart = Q_NULLPTR; + return; + } + viewerInterface->setWatchFileModeEnabled(false); + viewerInterface->setShowSourceLocationsGraphically(true); + connect(m_viewerPart, SIGNAL(openSourceReference(const QString&, int, int)), this, SLOT(handleActivatedSourceReference(const QString&, int, int))); + + QAction *paPrintCompiledDocument = actionCollection->addAction(KStandardAction::Print, "print_compiled_document", m_viewerPart, SLOT(slotPrint())); + paPrintCompiledDocument->setText(i18n("Print Compiled Document...")); + paPrintCompiledDocument->setShortcut(QKeySequence()); + paPrintCompiledDocument->setEnabled(false); + connect(m_viewerPart, SIGNAL(enablePrintAction(bool)), paPrintCompiledDocument, SLOT(setEnabled(bool))); + QAction *printPreviewAction = m_viewerPart->actionCollection()->action("file_print_preview"); + if(printPreviewAction) { + printPreviewAction->setText(i18n("Print Preview For Compiled Document...")); + } + } } void Manager::setupViewerPart(QSplitter *splitter) { - if(!m_viewerPart) { - return; - } - if(KileConfig::showDocumentViewerInExternalWindow()) { - if(m_viewerPartWindow && m_viewerPart->widget()->window() == m_viewerPartWindow) { // nothing to be done - return; - } - m_viewerPartWindow = new DocumentViewerWindow(); - m_viewerPartWindow->setObjectName("KileDocumentViewerWindow"); - m_viewerPartWindow->setCentralWidget(m_viewerPart->widget()); - m_viewerPartWindow->setAttribute(Qt::WA_DeleteOnClose, false); - m_viewerPartWindow->setAttribute(Qt::WA_QuitOnClose, false); - connect(m_viewerPartWindow, &KileView::DocumentViewerWindow::visibilityChanged, this, &Manager::documentViewerWindowVisibilityChanged); - - m_viewerPartWindow->setWindowTitle(i18n("Document Viewer")); - m_viewerPartWindow->applyMainWindowSettings(KSharedConfig::openConfig()->group("KileDocumentViewerWindow")); - } - else { - if(m_viewerPart->widget()->parent() && m_viewerPart->widget()->parent() != m_viewerPartWindow) { // nothing to be done - return; - } - splitter->addWidget(m_viewerPart->widget()); // remove it from the window first! - destroyDocumentViewerWindow(); - } + if(!m_viewerPart) { + return; + } + if(KileConfig::showDocumentViewerInExternalWindow()) { + if(m_viewerPartWindow && m_viewerPart->widget()->window() == m_viewerPartWindow) { // nothing to be done + return; + } + m_viewerPartWindow = new DocumentViewerWindow(); + m_viewerPartWindow->setObjectName("KileDocumentViewerWindow"); + m_viewerPartWindow->setCentralWidget(m_viewerPart->widget()); + m_viewerPartWindow->setAttribute(Qt::WA_DeleteOnClose, false); + m_viewerPartWindow->setAttribute(Qt::WA_QuitOnClose, false); + connect(m_viewerPartWindow, &KileView::DocumentViewerWindow::visibilityChanged, this, &Manager::documentViewerWindowVisibilityChanged); + + m_viewerPartWindow->setWindowTitle(i18n("Document Viewer")); + m_viewerPartWindow->applyMainWindowSettings(KSharedConfig::openConfig()->group("KileDocumentViewerWindow")); + } + else { + if(m_viewerPart->widget()->parent() && m_viewerPart->widget()->parent() != m_viewerPartWindow) { // nothing to be done + return; + } + splitter->addWidget(m_viewerPart->widget()); // remove it from the window first! + destroyDocumentViewerWindow(); + } } void Manager::destroyDocumentViewerWindow() { - if(!m_viewerPartWindow) { - return; - } + if(!m_viewerPartWindow) { + return; + } - KConfigGroup group(KSharedConfig::openConfig(), "KileDocumentViewerWindow"); - m_viewerPartWindow->saveMainWindowSettings(group); - // we don't want it to influence the document viewer visibility setting as - // this is a forced close - disconnect(m_viewerPartWindow, &KileView::DocumentViewerWindow::visibilityChanged, this, &Manager::documentViewerWindowVisibilityChanged); - m_viewerPartWindow->hide(); - delete m_viewerPartWindow; - m_viewerPartWindow = Q_NULLPTR; + KConfigGroup group(KSharedConfig::openConfig(), "KileDocumentViewerWindow"); + m_viewerPartWindow->saveMainWindowSettings(group); + // we don't want it to influence the document viewer visibility setting as + // this is a forced close + disconnect(m_viewerPartWindow, &KileView::DocumentViewerWindow::visibilityChanged, this, &Manager::documentViewerWindowVisibilityChanged); + m_viewerPartWindow->hide(); + delete m_viewerPartWindow; + m_viewerPartWindow = Q_NULLPTR; } void Manager::handleActivatedSourceReference(const QString& absFileName, int line, int col) { - KILE_DEBUG_MAIN << "absFileName:" << absFileName << "line:" << line << "column:" << col; - - QFileInfo fileInfo(absFileName); - if(!fileInfo.isFile() || !fileInfo.isReadable()) { - qWarning() << "Got passed an unreadable file:" << absFileName; - return; - } - - KileDocument::TextInfo *textInfo = m_ki->docManager()->textInfoFor(absFileName); - // check whether the file or the project item associated with 'absFileName' is already open - if(!textInfo || !m_ki->isOpen(absFileName)) { - m_ki->docManager()->fileOpen(absFileName); - textInfo = m_ki->docManager()->textInfoFor(absFileName); - } - if(!textInfo) { - KILE_DEBUG_MAIN << "no document found!"; - return; - } - KTextEditor::View *view = textView(textInfo); - if(!view) { - KILE_DEBUG_MAIN << "no view found!"; - return; - } - view->setCursorPosition(KTextEditor::Cursor(line, col)); - switchToTextView(view, true); + KILE_DEBUG_MAIN << "absFileName:" << absFileName << "line:" << line << "column:" << col; + + QFileInfo fileInfo(absFileName); + if(!fileInfo.isFile() || !fileInfo.isReadable()) { + qWarning() << "Got passed an unreadable file:" << absFileName; + return; + } + + KileDocument::TextInfo *textInfo = m_ki->docManager()->textInfoFor(absFileName); + // check whether the file or the project item associated with 'absFileName' is already open + if(!textInfo || !m_ki->isOpen(absFileName)) { + m_ki->docManager()->fileOpen(absFileName); + textInfo = m_ki->docManager()->textInfoFor(absFileName); + } + if(!textInfo) { + KILE_DEBUG_MAIN << "no document found!"; + return; + } + KTextEditor::View *view = textView(textInfo); + if(!view) { + KILE_DEBUG_MAIN << "no view found!"; + return; + } + view->setCursorPosition(KTextEditor::Cursor(line, col)); + switchToTextView(view, true); } void Manager::showCursorPositionInDocumentViewer() { - if(m_ki->livePreviewManager()->isLivePreviewEnabledForCurrentDocument()) { - m_ki->livePreviewManager()->showCursorPositionInDocumentViewer(); - } + if(m_ki->livePreviewManager()->isLivePreviewEnabledForCurrentDocument()) { + m_ki->livePreviewManager()->showCursorPositionInDocumentViewer(); + } } void Manager::synchronizeViewWithCursorActionToggled(bool checked) { - m_showCursorPositionInViewerAction->setEnabled(!checked); - if(checked) { - showCursorPositionInDocumentViewer(); - } + m_showCursorPositionInViewerAction->setEnabled(!checked); + if(checked) { + showCursorPositionInDocumentViewer(); + } } void Manager::setDocumentViewerVisible(bool b) { - if(!m_viewerPart) { - return; - } - KileConfig::setShowDocumentViewer(b); - if(m_viewerPartWindow) { - m_viewerPartWindow->setVisible(b); - } - m_viewerPart->widget()->setVisible(b); + if(!m_viewerPart) { + return; + } + KileConfig::setShowDocumentViewer(b); + if(m_viewerPartWindow) { + m_viewerPartWindow->setVisible(b); + } + m_viewerPart->widget()->setVisible(b); } bool Manager::isViewerPartShown() const { - if(!m_viewerPart) { - return false; - } + if(!m_viewerPart) { + return false; + } - if(m_viewerPartWindow) { - return !m_viewerPartWindow->isHidden(); - } - else { - return !m_viewerPart->widget()->isHidden(); - } + if(m_viewerPartWindow) { + return !m_viewerPartWindow->isHidden(); + } + else { + return !m_viewerPart->widget()->isHidden(); + } } bool Manager::openInDocumentViewer(const QUrl &url) { - Okular::ViewerInterface *v = dynamic_cast(m_viewerPart.data()); - if(!v) { - return false; - } - bool r = m_viewerPart->openUrl(url); - v->clearLastShownSourceLocation(); - return r; + Okular::ViewerInterface *v = dynamic_cast(m_viewerPart.data()); + if(!v) { + return false; + } + bool r = m_viewerPart->openUrl(url); + v->clearLastShownSourceLocation(); + return r; } void Manager::clearLastShownSourceLocationInDocumentViewer() { - Okular::ViewerInterface *v = dynamic_cast(m_viewerPart.data()); - if(v) { - v->clearLastShownSourceLocation(); - } + Okular::ViewerInterface *v = dynamic_cast(m_viewerPart.data()); + if(v) { + v->clearLastShownSourceLocation(); + } } void Manager::showSourceLocationInDocumentViewer(const QString& fileName, int line, int column) { - Okular::ViewerInterface *v = dynamic_cast(m_viewerPart.data()); - if(v) { - m_clearLastShownSourceLocationTimer->stop(); - v->showSourceLocation(fileName, line, column, true); - m_clearLastShownSourceLocationTimer->start(); - } + Okular::ViewerInterface *v = dynamic_cast(m_viewerPart.data()); + if(v) { + m_clearLastShownSourceLocationTimer->stop(); + v->showSourceLocation(fileName, line, column, true); + m_clearLastShownSourceLocationTimer->start(); + } } void Manager::setLivePreviewModeForDocumentViewer(bool b) { - Okular::ViewerInterface *viewerInterface = dynamic_cast(m_viewerPart.data()); - if(viewerInterface) { - if(b) { - viewerInterface->setWatchFileModeEnabled(false); - } - else { - viewerInterface->setWatchFileModeEnabled(KileConfig::watchFileForDocumentViewer()); + Okular::ViewerInterface *viewerInterface = dynamic_cast(m_viewerPart.data()); + if(viewerInterface) { + if(b) { + viewerInterface->setWatchFileModeEnabled(false); + } + else { + viewerInterface->setWatchFileModeEnabled(KileConfig::watchFileForDocumentViewer()); - } - } + } + } } KToolBar* Manager::getViewerControlToolBar() { - return m_viewerControlToolBar; + return m_viewerControlToolBar; } bool Manager::isSynchronisingCursorWithDocumentViewer() const { - return m_synchronizeViewWithCursorAction->isChecked(); + return m_synchronizeViewWithCursorAction->isChecked(); } //END ViewerPart methods bool Manager::viewForLocalFilePresent(const QString& localFileName) { - for(int i = 0; i < m_tabBar->count(); ++i) { - KTextEditor::View *view = textViewAtTab(i); - if(!view) { - continue; - } - if(view->document()->url().toLocalFile() == localFileName) { - return true; - } - } - return false; + for(int i = 0; i < m_tabBar->count(); ++i) { + KTextEditor::View *view = textViewAtTab(i); + if(!view) { + continue; + } + if(view->document()->url().toLocalFile() == localFileName) { + return true; + } + } + return false; } } void focusTextView(KTextEditor::View *view) { - // we work around a potential Qt bug here which can result in dead keys - // being treated as 'alive' keys in some circumstances, probably when 'setFocus' - // is called when the widget hasn't been shown yet (see bug 269590) - QTimer::singleShot(0, view, SLOT(setFocus())); + // we work around a potential Qt bug here which can result in dead keys + // being treated as 'alive' keys in some circumstances, probably when 'setFocus' + // is called when the widget hasn't been shown yet (see bug 269590) + QTimer::singleShot(0, view, SLOT(setFocus())); } diff --git a/src/kileviewmanager.h b/src/kileviewmanager.h index 4e2833c8..6804aff2 100644 --- a/src/kileviewmanager.h +++ b/src/kileviewmanager.h @@ -1,256 +1,258 @@ /************************************************************************** * Copyright (C) 2004 by Jeroen Wijnhout (Jeroen.Wijnhout@kdemail.net) * * (C) 2006-2017 by Michel Ludwig (michel.ludwig@kdemail.net) * ***************************************************************************/ /*************************************************************************** * * * 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. * * * ***************************************************************************/ #ifndef KILEVIEWKILEVIEWMANAGER_H #define KILEVIEWKILEVIEWMANAGER_H #include #include #include #include #include #include #include #include #include #include #include #include class QSplitter; class QStackedWidget; class QTabBar; class QToolButton; class QUrl; class KActionCollection; class KToggleAction; class KXMLGUIClient; class KileInfo; namespace KParts { - class ReadOnlyPart; +class ReadOnlyPart; } namespace KileWidget { - class ProjectView; +class ProjectView; } namespace KTextEditor { - class Document; - class View; +class Document; +class View; } namespace KileDocument { - class Info; - class TextInfo; +class Info; +class TextInfo; } namespace KileView { class DocumentViewerWindow : public KMainWindow { - Q_OBJECT + Q_OBJECT public: - DocumentViewerWindow(QWidget *parent = Q_NULLPTR, Qt::WindowFlags f = KDE_DEFAULT_WINDOWFLAGS); - virtual ~DocumentViewerWindow(); + DocumentViewerWindow(QWidget *parent = Q_NULLPTR, Qt::WindowFlags f = KDE_DEFAULT_WINDOWFLAGS); + virtual ~DocumentViewerWindow(); Q_SIGNALS: - void visibilityChanged(bool shown); + void visibilityChanged(bool shown); protected: - virtual void showEvent(QShowEvent *event); - virtual void closeEvent(QCloseEvent *event); + virtual void showEvent(QShowEvent *event); + virtual void closeEvent(QCloseEvent *event); }; //TODO inherit from KParts::Manager class Manager - : public QObject + : public QObject { - Q_OBJECT + Q_OBJECT public: - explicit Manager(KileInfo *ki, KActionCollection *actionCollection, QObject *parent = Q_NULLPTR, const char *name = Q_NULLPTR); + explicit Manager(KileInfo *ki, KActionCollection *actionCollection, QObject *parent = Q_NULLPTR, const char *name = Q_NULLPTR); - ~Manager(); + ~Manager(); public: - void setClient(KXMLGUIClient *client); + void setClient(KXMLGUIClient *client); - KTextEditor::View* currentTextView() const; - KTextEditor::View* textView(int index) const; - KTextEditor::View* textView(KileDocument::TextInfo *info) const; - int textViewCount() const; - int tabIndexOf(KTextEditor::View* view) const; - unsigned int getTabCount() const; + KTextEditor::View* currentTextView() const; + KTextEditor::View* textView(int index) const; + KTextEditor::View* textView(KileDocument::TextInfo *info) const; + int textViewCount() const; + int tabIndexOf(KTextEditor::View* view) const; + unsigned int getTabCount() const; - QWidget* createTabs(QWidget *parent); - void setTabsAndEditorVisible(bool b); - KTextEditor::View* createTextView(KileDocument::TextInfo *info, int index = -1); + QWidget* createTabs(QWidget *parent); + void setTabsAndEditorVisible(bool b); + KTextEditor::View* createTextView(KileDocument::TextInfo *info, int index = -1); // void setProjectView(KileWidget::ProjectView *view) { m_projectview = view; } // KileWidget::ProjectView *projectView() { return m_projectview; } commented out by tbraun, better use signal/slot stuff - static void installEventFilter(KTextEditor::View *view, QObject *eventFilter); - static void removeEventFilter(KTextEditor::View *view, QObject *eventFilter); + static void installEventFilter(KTextEditor::View *view, QObject *eventFilter); + static void removeEventFilter(KTextEditor::View *view, QObject *eventFilter); - void installContextMenu(KTextEditor::View *view); + void installContextMenu(KTextEditor::View *view); - KParts::ReadOnlyPart* viewerPart() const { return m_viewerPart; } + KParts::ReadOnlyPart* viewerPart() const { + return m_viewerPart; + } - void readConfig(QSplitter *splitter); - void writeConfig(); + void readConfig(QSplitter *splitter); + void writeConfig(); - bool isViewerPartShown() const; - void setupViewerPart(QSplitter *splitter); - bool openInDocumentViewer(const QUrl &url); - void clearLastShownSourceLocationInDocumentViewer(); - void showSourceLocationInDocumentViewer(const QString& fileName, int line, int column); - void setLivePreviewModeForDocumentViewer(bool b); + bool isViewerPartShown() const; + void setupViewerPart(QSplitter *splitter); + bool openInDocumentViewer(const QUrl &url); + void clearLastShownSourceLocationInDocumentViewer(); + void showSourceLocationInDocumentViewer(const QString& fileName, int line, int column); + void setLivePreviewModeForDocumentViewer(bool b); - KToolBar* getViewerControlToolBar(); + KToolBar* getViewerControlToolBar(); - bool isSynchronisingCursorWithDocumentViewer() const; + bool isSynchronisingCursorWithDocumentViewer() const; Q_SIGNALS: - void activateView(QWidget*, bool); - void startQuickPreview(int); - void currentViewChanged(QWidget*); - void textViewActivated(KTextEditor::View *view); - void textViewCreated(KTextEditor::View *view); - void textViewClosed(KTextEditor::View *view, bool wasActiveView); - void updateModeStatus(); - void updateCaption(); - - void informationMessage(KTextEditor::View*, const QString&); - void cursorPositionChanged(KTextEditor::View *view, const KTextEditor::Cursor &newPosition); - void viewModeChanged(KTextEditor::View*, KTextEditor::View::ViewMode); - void selectionChanged(KTextEditor::View *view); - - void documentViewerWindowVisibilityChanged(bool shown); + void activateView(QWidget*, bool); + void startQuickPreview(int); + void currentViewChanged(QWidget*); + void textViewActivated(KTextEditor::View *view); + void textViewCreated(KTextEditor::View *view); + void textViewClosed(KTextEditor::View *view, bool wasActiveView); + void updateModeStatus(); + void updateCaption(); + + void informationMessage(KTextEditor::View*, const QString&); + void cursorPositionChanged(KTextEditor::View *view, const KTextEditor::Cursor &newPosition); + void viewModeChanged(KTextEditor::View*, KTextEditor::View::ViewMode); + void selectionChanged(KTextEditor::View *view); + + void documentViewerWindowVisibilityChanged(bool shown); public Q_SLOTS: - KTextEditor::View* switchToTextView(const QUrl &url, bool requestFocus = false); - KTextEditor::View* switchToTextView(KTextEditor::Document *doc, bool requestFocus = false); - void switchToTextView(KTextEditor::View *view, bool requestFocus = false); + KTextEditor::View* switchToTextView(const QUrl &url, bool requestFocus = false); + KTextEditor::View* switchToTextView(KTextEditor::Document *doc, bool requestFocus = false); + void switchToTextView(KTextEditor::View *view, bool requestFocus = false); - void removeView(KTextEditor::View *view); + void removeView(KTextEditor::View *view); - void updateStructure(bool parse = false, KileDocument::Info *docinfo = Q_NULLPTR); + void updateStructure(bool parse = false, KileDocument::Info *docinfo = Q_NULLPTR); - void gotoNextView(); - void gotoPrevView(); + void gotoNextView(); + void gotoPrevView(); - void reflectDocumentModificationStatus(KTextEditor::Document*, - bool, - KTextEditor::ModificationInterface::ModifiedOnDiskReason reason); + void reflectDocumentModificationStatus(KTextEditor::Document*, + bool, + KTextEditor::ModificationInterface::ModifiedOnDiskReason reason); - void convertSelectionToLaTeX(void); - void pasteAsLaTeX(void); - void quickPreviewPopup(); + void convertSelectionToLaTeX(void); + void pasteAsLaTeX(void); + void quickPreviewPopup(); - void moveTabLeft(QWidget *widget = Q_NULLPTR); - void moveTabRight(QWidget *widget = Q_NULLPTR); + void moveTabLeft(QWidget *widget = Q_NULLPTR); + void moveTabRight(QWidget *widget = Q_NULLPTR); - void setDocumentViewerVisible(bool b); + void setDocumentViewerVisible(bool b); - void handleCursorPositionChanged(KTextEditor::View *view, const KTextEditor::Cursor &pos); + void handleCursorPositionChanged(KTextEditor::View *view, const KTextEditor::Cursor &pos); private Q_SLOTS: - void tabContext(const QPoint& pos); - void closeTab(int index); - void currentTabChanged(int index); - void handleCursorPositionChangedTimeout(); + void tabContext(const QPoint& pos); + void closeTab(int index); + void currentTabChanged(int index); + void handleCursorPositionChangedTimeout(); private: - KTextEditor::View * textViewAtTab(int index) const; + KTextEditor::View * textViewAtTab(int index) const; - void createViewerControlToolBar(); + void createViewerControlToolBar(); public: - bool viewForLocalFilePresent(const QString& localFileName); + bool viewForLocalFilePresent(const QString& localFileName); protected: - void setTabIcon(QWidget *view, const QIcon& icon); + void setTabIcon(QWidget *view, const QIcon& icon); - void createViewerPart(KActionCollection *actionCollection); - void destroyDocumentViewerWindow(); + void createViewerPart(KActionCollection *actionCollection); + void destroyDocumentViewerWindow(); protected Q_SLOTS: - void testCanDecodeURLs(const QDragEnterEvent *e, bool &accept); - void testCanDecodeURLs(const QDragMoveEvent *e, bool &accept); - void replaceLoadedURL(QWidget *w, QDropEvent *e); - void onTextEditorPopupMenuRequest(void); + void testCanDecodeURLs(const QDragEnterEvent *e, bool &accept); + void testCanDecodeURLs(const QDragMoveEvent *e, bool &accept); + void replaceLoadedURL(QWidget *w, QDropEvent *e); + void onTextEditorPopupMenuRequest(void); - /** - * Updates the labels of every tab that contains a view for 'changedDoc' to reflect there - * the name of 'changedDoc'. - **/ - void updateTabTexts(KTextEditor::Document* changedDoc); + /** + * Updates the labels of every tab that contains a view for 'changedDoc' to reflect there + * the name of 'changedDoc'. + **/ + void updateTabTexts(KTextEditor::Document* changedDoc); - void handleActivatedSourceReference(const QString& absFileName, int line, int col); + void handleActivatedSourceReference(const QString& absFileName, int line, int col); - void showCursorPositionInDocumentViewer(); - void synchronizeViewWithCursorActionToggled(bool b); + void showCursorPositionInDocumentViewer(); + void synchronizeViewWithCursorActionToggled(bool b); private: - KileInfo *m_ki; - QWidget *m_tabsAndEditorWidget; - QTabBar *m_tabBar; - QToolButton *m_documentListButton; - QObject *m_receiver; - KXMLGUIClient *m_client; - DocumentViewerWindow *m_viewerPartWindow; - QStackedWidget *m_widgetStack; - QAction *m_pasteAsLaTeXAction; - QAction *m_convertToLaTeXAction; - QAction *m_quickPreviewAction; - QAction *m_showCursorPositionInViewerAction; - QPointer m_viewerPart; - QPointer m_viewerControlToolBar; - QTimer *m_cursorPositionChangedTimer, *m_clearLastShownSourceLocationTimer; - KToggleAction *m_synchronizeViewWithCursorAction; + KileInfo *m_ki; + QWidget *m_tabsAndEditorWidget; + QTabBar *m_tabBar; + QToolButton *m_documentListButton; + QObject *m_receiver; + KXMLGUIClient *m_client; + DocumentViewerWindow *m_viewerPartWindow; + QStackedWidget *m_widgetStack; + QAction *m_pasteAsLaTeXAction; + QAction *m_convertToLaTeXAction; + QAction *m_quickPreviewAction; + QAction *m_showCursorPositionInViewerAction; + QPointer m_viewerPart; + QPointer m_viewerControlToolBar; + QTimer *m_cursorPositionChangedTimer, *m_clearLastShownSourceLocationTimer; + KToggleAction *m_synchronizeViewWithCursorAction; }; /** * Little helper widget to overcome the limitation that QTabWidget doesn't honour drop events when * there are no tabs: the DropWidget is shown instead of QTabWidget when there are no tabs. */ class DropWidget : public QWidget { -Q_OBJECT + Q_OBJECT public: - explicit DropWidget(QWidget * parent = 0, const char * name = 0, Qt::WindowFlags f = 0); - virtual ~DropWidget(); + explicit DropWidget(QWidget * parent = 0, const char * name = 0, Qt::WindowFlags f = 0); + virtual ~DropWidget(); - virtual void dragEnterEvent(QDragEnterEvent *e); - virtual void dropEvent(QDropEvent *e); + virtual void dragEnterEvent(QDragEnterEvent *e); + virtual void dropEvent(QDropEvent *e); - virtual void mouseDoubleClickEvent(QMouseEvent *e); + virtual void mouseDoubleClickEvent(QMouseEvent *e); Q_SIGNALS: - void testCanDecode(const QDragEnterEvent *, bool &); - void receivedDropEvent(QDropEvent *); - void mouseDoubleClick(); + void testCanDecode(const QDragEnterEvent *, bool &); + void receivedDropEvent(QDropEvent *); + void mouseDoubleClick(); }; } void focusTextView(KTextEditor::View *view); #endif diff --git a/src/kilewizard.cpp b/src/kilewizard.cpp index e8235757..76529866 100644 --- a/src/kilewizard.cpp +++ b/src/kilewizard.cpp @@ -1,65 +1,65 @@ /****************************************************************************** Copyright (C) 2003 by Jeroen Wijnhout (Jeroen.Wijnhout@kdemail.net) 2017 by Michel Ludwig (michel.ludwig@kdemail.net) ******************************************************************************/ /*************************************************************************** * * * 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. * * * ***************************************************************************/ #include "kilewizard.h" #include #include #include #include "utilities.h" namespace KileDialog { Wizard::Wizard(KConfig *config, QWidget *parent, const char *name, const QString &caption) - : QDialog(parent) - , m_td(QString(), QString(), QString(), 0, 0, QString()) - , m_config(config) - , m_buttonBox(new QDialogButtonBox(QDialogButtonBox::Ok|QDialogButtonBox::Cancel)) + : QDialog(parent) + , m_td(QString(), QString(), QString(), 0, 0, QString()) + , m_config(config) + , m_buttonBox(new QDialogButtonBox(QDialogButtonBox::Ok|QDialogButtonBox::Cancel)) { - setObjectName(name); - setWindowTitle(caption); - setModal(true); + setObjectName(name); + setWindowTitle(caption); + setModal(true); - // add buttons - QPushButton *okButton = m_buttonBox->button(QDialogButtonBox::Ok); - okButton->setDefault(true); - okButton->setShortcut(Qt::CTRL | Qt::Key_Return); - okButton->setDefault(true); - connect(m_buttonBox, &QDialogButtonBox::accepted, this, &QDialog::accept); - connect(m_buttonBox, &QDialogButtonBox::rejected, this, &QDialog::reject); + // add buttons + QPushButton *okButton = m_buttonBox->button(QDialogButtonBox::Ok); + okButton->setDefault(true); + okButton->setShortcut(Qt::CTRL | Qt::Key_Return); + okButton->setDefault(true); + connect(m_buttonBox, &QDialogButtonBox::accepted, this, &QDialog::accept); + connect(m_buttonBox, &QDialogButtonBox::rejected, this, &QDialog::reject); } Wizard::~Wizard() {} KConfig* Wizard::config() const { - return m_config; + return m_config; } QDialogButtonBox * Wizard::buttonBox() const { - return m_buttonBox; + return m_buttonBox; } void Wizard::showEvent(QShowEvent *event) { - // even with 'showEvent' the dialog might not be shown yet, only about to be shown - // so we have to 'schedule' a centering (still does not work all the time) - KileUtilities::scheduleCenteringOfWidget(this); - QDialog::showEvent(event); + // even with 'showEvent' the dialog might not be shown yet, only about to be shown + // so we have to 'schedule' a centering (still does not work all the time) + KileUtilities::scheduleCenteringOfWidget(this); + QDialog::showEvent(event); } } diff --git a/src/kilewizard.h b/src/kilewizard.h index 56888a01..66f6edde 100644 --- a/src/kilewizard.h +++ b/src/kilewizard.h @@ -1,50 +1,52 @@ /****************************************************************************** Copyright (C) 2003 by Jeroen Wijnhout (Jeroen.Wijnhout@kdemail.net) 2017 by Michel Ludwig (michel.ludwig@kdemail.net) ******************************************************************************/ /*************************************************************************** * * * 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. * * * ***************************************************************************/ #ifndef KILEWIZARD_H #define KILEWIZARD_H #include #include "kileactions.h" class KConfig; class QDialogButtonBox; class QShowEvent; namespace KileDialog { class Wizard : public QDialog { public: - explicit Wizard(KConfig *, QWidget *parent = Q_NULLPTR, const char *name = Q_NULLPTR, const QString &caption = QString()); - virtual ~Wizard(); + explicit Wizard(KConfig *, QWidget *parent = Q_NULLPTR, const char *name = Q_NULLPTR, const QString &caption = QString()); + virtual ~Wizard(); public: - const KileAction::TagData & tagData() const { return m_td; } + const KileAction::TagData & tagData() const { + return m_td; + } protected: - KConfig * config() const; - QDialogButtonBox * buttonBox() const; - KileAction::TagData m_td; + KConfig * config() const; + QDialogButtonBox * buttonBox() const; + KileAction::TagData m_td; - virtual void showEvent(QShowEvent *event); + virtual void showEvent(QShowEvent *event); private: - KConfig *m_config; - QDialogButtonBox *m_buttonBox; + KConfig *m_config; + QDialogButtonBox *m_buttonBox; }; } #endif diff --git a/src/latexcmd.cpp b/src/latexcmd.cpp index 488d5880..c643f51f 100644 --- a/src/latexcmd.cpp +++ b/src/latexcmd.cpp @@ -1,489 +1,509 @@ /***************************************************************************************** Copyright (C) 2005 by Holger Danielsson (holger.danielsson@t-online.de) 2010 by Michel Ludwig (michel.ludwig@kdemail.net) ******************************************************************************************/ /*************************************************************************** * * * 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. * * * ***************************************************************************/ #include "latexcmd.h" #include // #include #include "kiledebug.h" namespace KileDocument { // BEGIN LatexCommands LatexCommands::LatexCommands(KConfig *config, KileInfo *info) : m_config(config), m_ki(info) { - m_envGroupName = "Latex Environments"; - m_cmdGroupName = "Latex Commands"; + m_envGroupName = "Latex Environments"; + m_cmdGroupName = "Latex Commands"; - LatexCommands::resetCommands(); + LatexCommands::resetCommands(); } void LatexCommands::resetCommands() { - // description of the fields for environments - // 0: standard entry (+,-) - // 1: environmenty type (a,m,l,t,v) - // 2: including starred version (*) - // 3: eol character (\\\\) - // 4: need mathmode ($) or displaymathmode ($$) - // 5: standard tabulator (tabulator string, f.e. &=& or &=) - // 6: optional parameter - // 7: parameter group(s) - - QStringList envlist; - envlist - // list environments - << "itemize,+,l,*,,,,," - << "enumerate,+,l,*,,,,," - << "description,+,l,*,,,,," - << "Bitemize,+,l,,,,,," - << "Benumerate,+,l,,,,,," - << "Bdescription,+,l,,,,,," - << "labeling,+,l,,,,,[ ],{ }" - // tabular environments - << "tabular,+,t,*,\\\\,,&,[tcb]," - << "tabularx,+,t,,\\\\,,&,,{w}" - << "tabbing,+,t,,\\\\,,\\>,," - << "longtable,+,t,,\\\\,,&,[tcb]," - << "ltxtable,+,t,,\\\\,,&,[tcb],{w}" - << "supertabular,+,t,*,\\\\,,&,," - << "mpsupertabular,+,t,*,\\\\,,&,," - << "xtabular,+,t,*,\\\\,,&,," - << "mpxtabular,+,t,*,\\\\,,&,," - // math environments - << "displaymath,+,m,,,,,," - << "equation,+,m,*,,,,," - << "eqnarray,+,m,*,\\\\,,&=&,," - << "array,+,m,,\\\\,$,&,[tcb]," - << "matrix,+,m,,\\\\,$,&,," - << "pmatrix,+,m,,\\\\,$,&,," - << "bmatrix,+,m,,\\\\,$,&,," - << "Bmatrix,+,m,,\\\\,$,&,," - << "vmatrix,+,m,,\\\\,$,&,," - << "Vmatrix,+,m,,\\\\,$,&,," - // amsmath environments - << "multline,+,a,*,\\\\,,,," - << "gather,+,a,*,\\\\,,,," - << "split,+,a,,\\\\,$$,,," // needs surrounding environment - << "align,+,a,*,\\\\,,&=,," - << "flalign,+,a,*,\\\\,,&=,," - << "alignat,+,a,*,\\\\,,&=,,{n}" - << "aligned,+,a,,\\\\,$,&=,[tcb]," - << "gathered,+,a,,\\\\,$,,[tcb]," - << "alignedat,+,a,,\\\\,$,&=,[tcb],{n}" - //<< "xalignat,+,a,*,\\\\,,&=,,{n}" // obsolet - //<< "xxalignat,+,a,*,\\\\,,&=,,{n}" // obsolet - << "cases,+,a,,\\\\,$,&,," - // verbatim environments - << "verbatim,+,v,*,,,,," - << "boxedverbatim,+,v,,,,,," - << "Bverbatim,+,v,,,,,[ ]," - << "Lverbatim,+,v,,,,,[ ]," - << "lstlisting,+,v,,,,,[ ]," - ; - - // description of the fields for commands - // 0: standard entry (+,-) - // 1: command type (L,R,C,I) - // 2: including starred version (*) - // 3: optional parameter - // 4: parameter - - QStringList cmdlist; - cmdlist - // Labels - << "\\label,+,L,,,{ }" - // References - << "\\ref,+,R,,,{ }" - << "\\pageref,+,R,,,{ }" - << "\\vref,+,R,,,{ }" - << "\\vpageref,+,R,,[ ],{ }" - << "\\fref,+,R,,,{ }" - << "\\Fref,+,R,,,{ }" - << "\\eqref,+,R,,,{ }" - << "\\autoref,+,R,,,{ }" - // Bibliographies - << "\\bibliography,+,B,,,{ }" - << "\\addbibresource,+,B,*,[ ],{ }" - << "\\addglobalbib,+,B,*,[ ],{ }" - << "\\addsectionbib,+,B,*,[ ],{ }" - // Citations - << "\\cite,+,C,,,{ }" - // Includes - << "\\include,+,I,,,{ }" - << "\\input,+,I,,,{ }" - << "\\Input,+,I,,,{ }" - ; - - // first clear the dictionary - m_latexCommands.clear(); - - // insert environments - addUserCommands(m_envGroupName,envlist); - insert(envlist); - - // insert commands - addUserCommands(m_cmdGroupName,cmdlist); - insert(cmdlist); + // description of the fields for environments + // 0: standard entry (+,-) + // 1: environmenty type (a,m,l,t,v) + // 2: including starred version (*) + // 3: eol character (\\\\) + // 4: need mathmode ($) or displaymathmode ($$) + // 5: standard tabulator (tabulator string, f.e. &=& or &=) + // 6: optional parameter + // 7: parameter group(s) + + QStringList envlist; + envlist + // list environments + << "itemize,+,l,*,,,,," + << "enumerate,+,l,*,,,,," + << "description,+,l,*,,,,," + << "Bitemize,+,l,,,,,," + << "Benumerate,+,l,,,,,," + << "Bdescription,+,l,,,,,," + << "labeling,+,l,,,,,[ ],{ }" + // tabular environments + << "tabular,+,t,*,\\\\,,&,[tcb]," + << "tabularx,+,t,,\\\\,,&,,{w}" + << "tabbing,+,t,,\\\\,,\\>,," + << "longtable,+,t,,\\\\,,&,[tcb]," + << "ltxtable,+,t,,\\\\,,&,[tcb],{w}" + << "supertabular,+,t,*,\\\\,,&,," + << "mpsupertabular,+,t,*,\\\\,,&,," + << "xtabular,+,t,*,\\\\,,&,," + << "mpxtabular,+,t,*,\\\\,,&,," + // math environments + << "displaymath,+,m,,,,,," + << "equation,+,m,*,,,,," + << "eqnarray,+,m,*,\\\\,,&=&,," + << "array,+,m,,\\\\,$,&,[tcb]," + << "matrix,+,m,,\\\\,$,&,," + << "pmatrix,+,m,,\\\\,$,&,," + << "bmatrix,+,m,,\\\\,$,&,," + << "Bmatrix,+,m,,\\\\,$,&,," + << "vmatrix,+,m,,\\\\,$,&,," + << "Vmatrix,+,m,,\\\\,$,&,," + // amsmath environments + << "multline,+,a,*,\\\\,,,," + << "gather,+,a,*,\\\\,,,," + << "split,+,a,,\\\\,$$,,," // needs surrounding environment + << "align,+,a,*,\\\\,,&=,," + << "flalign,+,a,*,\\\\,,&=,," + << "alignat,+,a,*,\\\\,,&=,,{n}" + << "aligned,+,a,,\\\\,$,&=,[tcb]," + << "gathered,+,a,,\\\\,$,,[tcb]," + << "alignedat,+,a,,\\\\,$,&=,[tcb],{n}" + //<< "xalignat,+,a,*,\\\\,,&=,,{n}" // obsolet + //<< "xxalignat,+,a,*,\\\\,,&=,,{n}" // obsolet + << "cases,+,a,,\\\\,$,&,," + // verbatim environments + << "verbatim,+,v,*,,,,," + << "boxedverbatim,+,v,,,,,," + << "Bverbatim,+,v,,,,,[ ]," + << "Lverbatim,+,v,,,,,[ ]," + << "lstlisting,+,v,,,,,[ ]," + ; + + // description of the fields for commands + // 0: standard entry (+,-) + // 1: command type (L,R,C,I) + // 2: including starred version (*) + // 3: optional parameter + // 4: parameter + + QStringList cmdlist; + cmdlist + // Labels + << "\\label,+,L,,,{ }" + // References + << "\\ref,+,R,,,{ }" + << "\\pageref,+,R,,,{ }" + << "\\vref,+,R,,,{ }" + << "\\vpageref,+,R,,[ ],{ }" + << "\\fref,+,R,,,{ }" + << "\\Fref,+,R,,,{ }" + << "\\eqref,+,R,,,{ }" + << "\\autoref,+,R,,,{ }" + // Bibliographies + << "\\bibliography,+,B,,,{ }" + << "\\addbibresource,+,B,*,[ ],{ }" + << "\\addglobalbib,+,B,*,[ ],{ }" + << "\\addsectionbib,+,B,*,[ ],{ }" + // Citations + << "\\cite,+,C,,,{ }" + // Includes + << "\\include,+,I,,,{ }" + << "\\input,+,I,,,{ }" + << "\\Input,+,I,,,{ }" + ; + + // first clear the dictionary + m_latexCommands.clear(); + + // insert environments + addUserCommands(m_envGroupName,envlist); + insert(envlist); + + // insert commands + addUserCommands(m_cmdGroupName,cmdlist); + insert(cmdlist); } // add user-defined environments/commands //FIXME: the code for reading and writing these configuration entries should be regrouped // within a single class (currently, the code for writing the values can be found // in 'latexcommanddialog.cpp'). void LatexCommands::addUserCommands(const QString &name, QStringList &list) { - KILE_DEBUG_MAIN << name; - if(!m_config->hasGroup(name)) { - KILE_DEBUG_MAIN << "\tGroup does not exist."; - return; - } - - KConfigGroup group = m_config->group(name); - int nrOfDefinedCommands = group.readEntry("Number of Commands", 0); - - for(int i = 0; i < nrOfDefinedCommands; ++i) { - const QString commandKey = "Command" + QString::number(i); - const QString parametersKey = "Parameters" + QString::number(i); - - if(!group.hasKey(commandKey) || !group.hasKey(parametersKey)) { - KILE_DEBUG_MAIN << "\tEntry" << i << "is invalid!"; - } - const QString command = group.readEntry(commandKey); - const QString parameters = group.readEntry(parametersKey); - list << command + ",-," + parameters; - KILE_DEBUG_MAIN << "\tAdding: " << command + " --> " + parameters; - } + KILE_DEBUG_MAIN << name; + if(!m_config->hasGroup(name)) { + KILE_DEBUG_MAIN << "\tGroup does not exist."; + return; + } + + KConfigGroup group = m_config->group(name); + int nrOfDefinedCommands = group.readEntry("Number of Commands", 0); + + for(int i = 0; i < nrOfDefinedCommands; ++i) { + const QString commandKey = "Command" + QString::number(i); + const QString parametersKey = "Parameters" + QString::number(i); + + if(!group.hasKey(commandKey) || !group.hasKey(parametersKey)) { + KILE_DEBUG_MAIN << "\tEntry" << i << "is invalid!"; + } + const QString command = group.readEntry(commandKey); + const QString parameters = group.readEntry(parametersKey); + list << command + ",-," + parameters; + KILE_DEBUG_MAIN << "\tAdding: " << command + " --> " + parameters; + } } // insert all entries into the dictionary void LatexCommands::insert(const QStringList &list) { - // now insert new entries, if they have the right number of attributes - QStringList::ConstIterator it; - for(it = list.begin(); it!=list.end(); ++it) { - int pos = (*it).indexOf(','); - if(pos >= 0) { - QString key = (*it).left(pos); - QString value = (*it).right( (*it).length()-pos-1 ); - QStringList valuelist = value.split(',', QString::KeepEmptyParts); - int attributes = ( key.at(0)=='\\' ) ? MaxCmdAttr : MaxEnvAttr; - if(valuelist.count() == attributes) { - m_latexCommands[key] = value; - } - else { - KILE_DEBUG_MAIN << "\tLatexCommands error: wrong number of attributes (" << key << " ---> " << value << ")"; - } - } - else { - KILE_DEBUG_MAIN << "\tLatexCommands error: no separator found (" << (*it) << ")" ; - } - } + // now insert new entries, if they have the right number of attributes + QStringList::ConstIterator it; + for(it = list.begin(); it!=list.end(); ++it) { + int pos = (*it).indexOf(','); + if(pos >= 0) { + QString key = (*it).left(pos); + QString value = (*it).right( (*it).length()-pos-1 ); + QStringList valuelist = value.split(',', QString::KeepEmptyParts); + int attributes = ( key.at(0)=='\\' ) ? MaxCmdAttr : MaxEnvAttr; + if(valuelist.count() == attributes) { + m_latexCommands[key] = value; + } + else { + KILE_DEBUG_MAIN << "\tLatexCommands error: wrong number of attributes (" << key << " ---> " << value << ")"; + } + } + else { + KILE_DEBUG_MAIN << "\tLatexCommands error: no separator found (" << (*it) << ")" ; + } + } } //////////////////// get value from dictionary //////////////////// // Get value of a key. A star at the end is stripped. QString LatexCommands::getValue(const QString &name) { - QString key = (name.indexOf('*',-1) >= 0) ? name.left(name.length()-1) : name; - return (m_latexCommands.contains(key)) ? m_latexCommands[key] : QString(); + QString key = (name.indexOf('*',-1) >= 0) ? name.left(name.length()-1) : name; + return (m_latexCommands.contains(key)) ? m_latexCommands[key] : QString(); } //////////////////// internal functions //////////////////// // get parameter at index QString LatexCommands::getAttrAt(const QString &name, int index) { - if(index < 0) { - return QString(); - } - int attributes = (name.at(0) == '\\') ? MaxCmdAttr : MaxEnvAttr; - QStringList list = getValue(name).split(',', QString::KeepEmptyParts); - return (index < attributes && list.count() == attributes) ? list[index] : QString(); + if(index < 0) { + return QString(); + } + int attributes = (name.at(0) == '\\') ? MaxCmdAttr : MaxEnvAttr; + QStringList list = getValue(name).split(',', QString::KeepEmptyParts); + return (index < attributes && list.count() == attributes) ? list[index] : QString(); } // check for a standard environment bool LatexCommands::isUserDefined(const QString &name) { - return ( getValue(name).at(0) == '-' ); + return ( getValue(name).at(0) == '-' ); } // check for a special environment type bool LatexCommands::isType(const QString &name, QChar ch) { - if(name.indexOf('*', -1) >= 0) { - QString envname = name.left(name.length() - 1); - QString value = getValue(envname); - return (value.length() >= 3 && value.at(2) == ch && isStarredEnv(envname)); - } - else { - QString value = getValue(name); - return (value.length() >= 3 && value.at(2) == ch); - } + if(name.indexOf('*', -1) >= 0) { + QString envname = name.left(name.length() - 1); + QString value = getValue(envname); + return (value.length() >= 3 && value.at(2) == ch && isStarredEnv(envname)); + } + else { + QString value = getValue(name); + return (value.length() >= 3 && value.at(2) == ch); + } } //////////////////// attributes and characters //////////////////// // convert attribute to character QChar LatexCommands::getAttrChar(CmdAttribute attr) { - QChar ch; - switch(attr) { - case CmdAttrAmsmath: ch = 'a'; break; - case CmdAttrMath: ch = 'm'; break; - case CmdAttrList: ch = 'l'; break; - case CmdAttrVerbatim: ch = 'v'; break; - case CmdAttrTabular: ch = 't'; break; - case CmdAttrLabel: ch = 'L'; break; - case CmdAttrReference: ch = 'R'; break; - case CmdAttrCitations: ch = 'C'; break; - case CmdAttrIncludes: ch = 'I'; break; - case CmdAttrBibliographies: ch = 'B'; break; - default: - KILE_DEBUG_MAIN << "\tLatexCommands error: unknown type of env/cmd: code " << attr; - return '?'; - } - - return ch; + QChar ch; + switch(attr) { + case CmdAttrAmsmath: + ch = 'a'; + break; + case CmdAttrMath: + ch = 'm'; + break; + case CmdAttrList: + ch = 'l'; + break; + case CmdAttrVerbatim: + ch = 'v'; + break; + case CmdAttrTabular: + ch = 't'; + break; + case CmdAttrLabel: + ch = 'L'; + break; + case CmdAttrReference: + ch = 'R'; + break; + case CmdAttrCitations: + ch = 'C'; + break; + case CmdAttrIncludes: + ch = 'I'; + break; + case CmdAttrBibliographies: + ch = 'B'; + break; + default: + KILE_DEBUG_MAIN << "\tLatexCommands error: unknown type of env/cmd: code " << attr; + return '?'; + } + + return ch; } // convert character to attribute CmdAttribute LatexCommands::getCharAttr(QChar ch) { - CmdAttribute attr; - switch(ch.unicode()) { - case 'a': - attr = CmdAttrAmsmath; - break; - case 'm': - attr = CmdAttrMath; - break; - case 'l': - attr = CmdAttrList; - break; - case 'v': - attr = CmdAttrVerbatim; - break; - case 't': - attr = CmdAttrTabular; - break; - case 'L': - attr = CmdAttrLabel; - break; - case 'R': - attr = CmdAttrReference; - break; - case 'C': - attr = CmdAttrCitations; - break; - case 'I': - attr = CmdAttrIncludes; - break; - case 'B': - attr = CmdAttrBibliographies; - break; - default: - KILE_DEBUG_MAIN << "\tLatexCommands error: unknown type of env/cmd: " << static_cast(ch.unicode()); - return CmdAttrNone; - } - - return attr; + CmdAttribute attr; + switch(ch.unicode()) { + case 'a': + attr = CmdAttrAmsmath; + break; + case 'm': + attr = CmdAttrMath; + break; + case 'l': + attr = CmdAttrList; + break; + case 'v': + attr = CmdAttrVerbatim; + break; + case 't': + attr = CmdAttrTabular; + break; + case 'L': + attr = CmdAttrLabel; + break; + case 'R': + attr = CmdAttrReference; + break; + case 'C': + attr = CmdAttrCitations; + break; + case 'I': + attr = CmdAttrIncludes; + break; + case 'B': + attr = CmdAttrBibliographies; + break; + default: + KILE_DEBUG_MAIN << "\tLatexCommands error: unknown type of env/cmd: " << static_cast(ch.unicode()); + return CmdAttrNone; + } + + return attr; } //////////////////// public attributes //////////////////// // check for environment types bool LatexCommands::isMathEnv(const QString &name) { - QString value = getValue(name); - if(value.length() < 3) { - return false; - } + QString value = getValue(name); + if(value.length() < 3) { + return false; + } - QChar ch = value.at(2); - return (ch == 'm' || ch == 'a'); + QChar ch = value.at(2); + return (ch == 'm' || ch == 'a'); } // check for some special attributes bool LatexCommands::isStarredEnv(const QString &name) { - return (getAttrAt(name, 2) == "*"); + return (getAttrAt(name, 2) == "*"); } bool LatexCommands::isCrEnv(const QString &name) { - return (getAttrAt(name, 3) == "\\\\"); + return (getAttrAt(name, 3) == "\\\\"); } bool LatexCommands::isMathModeEnv(const QString &name) { - return (getAttrAt(name, 4) == "$"); + return (getAttrAt(name, 4) == "$"); } bool LatexCommands::isDisplaymathModeEnv(const QString &name) { - return (getAttrAt(name, 4) == "$$"); + return (getAttrAt(name, 4) == "$$"); } bool LatexCommands::needsMathMode(const QString &name) { - return (isMathModeEnv(name) || isDisplaymathModeEnv(name)); + return (isMathModeEnv(name) || isDisplaymathModeEnv(name)); } QString LatexCommands::getTabulator(const QString &name) { - QString tab = getAttrAt(name, 5); - return (tab.indexOf('&') >= 0) ? tab : QString(); + QString tab = getAttrAt(name, 5); + return (tab.indexOf('&') >= 0) ? tab : QString(); } //////////////////// environments and commands //////////////////// // get a list of environments and commands. The search can be restricted // to given attributes and userdefined environments and commands void LatexCommands::commandList(QStringList &list, uint attr, bool userdefined) { - list.clear(); - - QMapIterator it(m_latexCommands); - while(it.hasNext()) { - it.next(); - // first check, if we need really need all environments and commands - // or if a restriction to some attributes is given - if(attr != (uint)CmdAttrNone) { - if(!(attr & (uint)getCharAttr( it.value().at(2)))) { - continue; - } - } - - // second check, if we need only user-defined environments or commands - if(!userdefined) { - list.append(it.key()); - } - else if(it.value().at(0) == '-') { - list.append(it.key()); - } - } + list.clear(); + + QMapIterator it(m_latexCommands); + while(it.hasNext()) { + it.next(); + // first check, if we need really need all environments and commands + // or if a restriction to some attributes is given + if(attr != (uint)CmdAttrNone) { + if(!(attr & (uint)getCharAttr( it.value().at(2)))) { + continue; + } + } + + // second check, if we need only user-defined environments or commands + if(!userdefined) { + list.append(it.key()); + } + else if(it.value().at(0) == '-') { + list.append(it.key()); + } + } } // get all attributes for a given environment and command bool LatexCommands::commandAttributes(const QString &name, LatexCmdAttributes &attr) { - int attributes = (name.at(0) == '\\') ? MaxCmdAttr : MaxEnvAttr; - - // split attribute list - QStringList list = getValue(name).split(',', QString::KeepEmptyParts); - - // check number of attributes - if(list.count() != attributes) { - return false; - } - - // check for a standard environment/command - attr.standard = (list[0] == "+"); - - // most important: type of environment or command - attr.type = getCharAttr(list[1].at(0)); - if(attr.type == CmdAttrNone) { - return false; - } - - // all environments/commands have starred attribute - attr.starred = (list[2] == "*"); - - // next attributes differ for environments and commands - if(attributes == MaxEnvAttr) { - attr.cr = (list[3] == "\\\\"); - attr.mathmode = (list[4] == "$"); - attr.displaymathmode = (list[4] == "$$"); - attr.tabulator = list[5]; - attr.option = list[6]; - attr.parameter = list[7]; - } - else { - attr.cr = false; - attr.mathmode = false; - attr.displaymathmode = false; - attr.tabulator.clear(); - attr.option = list[3]; - attr.parameter = list[4]; - } - - return true; + int attributes = (name.at(0) == '\\') ? MaxCmdAttr : MaxEnvAttr; + + // split attribute list + QStringList list = getValue(name).split(',', QString::KeepEmptyParts); + + // check number of attributes + if(list.count() != attributes) { + return false; + } + + // check for a standard environment/command + attr.standard = (list[0] == "+"); + + // most important: type of environment or command + attr.type = getCharAttr(list[1].at(0)); + if(attr.type == CmdAttrNone) { + return false; + } + + // all environments/commands have starred attribute + attr.starred = (list[2] == "*"); + + // next attributes differ for environments and commands + if(attributes == MaxEnvAttr) { + attr.cr = (list[3] == "\\\\"); + attr.mathmode = (list[4] == "$"); + attr.displaymathmode = (list[4] == "$$"); + attr.tabulator = list[5]; + attr.option = list[6]; + attr.parameter = list[7]; + } + else { + attr.cr = false; + attr.mathmode = false; + attr.displaymathmode = false; + attr.tabulator.clear(); + attr.option = list[3]; + attr.parameter = list[4]; + } + + return true; } //////////////////// determine config string //////////////////// QString LatexCommands::configString(LatexCmdAttributes &attr,bool env) { - // most important: type of environment or command - QChar ch = getAttrChar(attr.type); - if(ch == '?') { - return QString(); - } - QString s = ch + QString(','); - - // all environments/commands have starred attribute - if(attr.starred) { - s += "*,"; - } - else { - s += ','; - } - - // next attributes are only valid for environments - if(env) { - if(attr.cr) { - s += "\\\\,"; - } - else { - s += ','; - } - if(attr.mathmode) { - s += "$,"; - } - else if(attr.displaymathmode) { - s += "$$"; - } - else { - s += ','; - } - s += attr.tabulator + ','; - } - - // option and parameter are for both types again - s += attr.option + ','; - s += attr.parameter; - - return s; // s.left(s.length()-1); + // most important: type of environment or command + QChar ch = getAttrChar(attr.type); + if(ch == '?') { + return QString(); + } + QString s = ch + QString(','); + + // all environments/commands have starred attribute + if(attr.starred) { + s += "*,"; + } + else { + s += ','; + } + + // next attributes are only valid for environments + if(env) { + if(attr.cr) { + s += "\\\\,"; + } + else { + s += ','; + } + if(attr.mathmode) { + s += "$,"; + } + else if(attr.displaymathmode) { + s += "$$"; + } + else { + s += ','; + } + s += attr.tabulator + ','; + } + + // option and parameter are for both types again + s += attr.option + ','; + s += attr.parameter; + + return s; // s.left(s.length()-1); } // END LatexCommands } diff --git a/src/latexcmd.h b/src/latexcmd.h index 8d015752..7ce4dc27 100644 --- a/src/latexcmd.h +++ b/src/latexcmd.h @@ -1,118 +1,136 @@ /*************************************************************************** latexcmd.h ---------- date : Jul 25 2005 version : 0.20 copyright : (C) 2005 by Holger Danielsson email : holger.danielsson@t-online.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. * * * ***************************************************************************/ // kommandos mit weiteren Parametern #ifndef LATEXCMD_H #define LATEXCMD_H #include #include #include #include class KileInfo; namespace KileDocument { const int MaxEnvAttr = 8; const int MaxCmdAttr = 5; enum CmdAttribute { - CmdAttrNone = 0, // unknown - CmdAttrAmsmath = 1, CmdAttrMath = 2, CmdAttrList = 4, CmdAttrTabular = 8, CmdAttrVerbatim = 16, // environments - CmdAttrLabel = 32, CmdAttrReference = 64, CmdAttrCitations = 128, CmdAttrIncludes = 256, // commands - CmdAttrBibliographies = 512 //commands - continue + CmdAttrNone = 0, // unknown + CmdAttrAmsmath = 1, CmdAttrMath = 2, CmdAttrList = 4, CmdAttrTabular = 8, CmdAttrVerbatim = 16, // environments + CmdAttrLabel = 32, CmdAttrReference = 64, CmdAttrCitations = 128, CmdAttrIncludes = 256, // commands + CmdAttrBibliographies = 512 //commands - continue }; class LatexCmdAttributes { public: - bool standard; - CmdAttribute type; - bool starred; - bool cr; - bool mathmode; - bool displaymathmode; - QString tabulator; - QString option; - QString parameter; + bool standard; + CmdAttribute type; + bool starred; + bool cr; + bool mathmode; + bool displaymathmode; + QString tabulator; + QString option; + QString parameter; }; class LatexCommands : public QObject { - Q_OBJECT + Q_OBJECT public: - LatexCommands(KConfig *config, KileInfo *info); - ~LatexCommands() {}; - - QString envGroupName() { return m_envGroupName; } - QString cmdGroupName() { return m_cmdGroupName; } - QString configString(LatexCmdAttributes &attr,bool env); - - bool isMathEnv(const QString &name); - bool isListEnv(const QString &name) { return isType(name,'l'); } - bool isTabularEnv(const QString &name) { return isType(name,'t'); } - bool isVerbatimEnv(const QString &name) { return isType(name,'v'); } - - bool isLabelCmd(const QString &name) { return isType(name,'L'); } - bool isReferenceCmd(const QString &name) { return isType(name,'R'); } - bool isCitationCmd(const QString &name) { return isType(name,'C'); } - bool isInputCmd(const QString &name) { return isType(name,'I'); } - - bool isStarredEnv(const QString &name); - bool isCrEnv(const QString &name); - bool isMathModeEnv(const QString &name); - bool isDisplaymathModeEnv(const QString &name); - bool needsMathMode(const QString &name); - QString getTabulator(const QString &name); - - void commandList(QStringList &list, uint attr, bool userdefined); - bool commandAttributes(const QString &name, LatexCmdAttributes &attr); - - void resetCommands(); + LatexCommands(KConfig *config, KileInfo *info); + ~LatexCommands() {}; + + QString envGroupName() { + return m_envGroupName; + } + QString cmdGroupName() { + return m_cmdGroupName; + } + QString configString(LatexCmdAttributes &attr,bool env); + + bool isMathEnv(const QString &name); + bool isListEnv(const QString &name) { + return isType(name,'l'); + } + bool isTabularEnv(const QString &name) { + return isType(name,'t'); + } + bool isVerbatimEnv(const QString &name) { + return isType(name,'v'); + } + + bool isLabelCmd(const QString &name) { + return isType(name,'L'); + } + bool isReferenceCmd(const QString &name) { + return isType(name,'R'); + } + bool isCitationCmd(const QString &name) { + return isType(name,'C'); + } + bool isInputCmd(const QString &name) { + return isType(name,'I'); + } + + bool isStarredEnv(const QString &name); + bool isCrEnv(const QString &name); + bool isMathModeEnv(const QString &name); + bool isDisplaymathModeEnv(const QString &name); + bool needsMathMode(const QString &name); + QString getTabulator(const QString &name); + + void commandList(QStringList &list, uint attr, bool userdefined); + bool commandAttributes(const QString &name, LatexCmdAttributes &attr); + + void resetCommands(); private: - KConfig *m_config; - KileInfo *m_ki; + KConfig *m_config; + KileInfo *m_ki; - QString m_envGroupName, m_cmdGroupName; - QMap m_latexCommands; + QString m_envGroupName, m_cmdGroupName; + QMap m_latexCommands; - void addUserCommands(const QString &name, QStringList &list); - void insert(const QStringList &list); + void addUserCommands(const QString &name, QStringList &list); + void insert(const QStringList &list); - QString getValue(const QString &name); + QString getValue(const QString &name); - bool isUserDefined(const QString &name); - bool isType(const QString &name, QChar ch); - QString getAttrAt(const QString &name, int index); - QChar getAttrChar(CmdAttribute attr); - CmdAttribute getCharAttr(QChar ch); + bool isUserDefined(const QString &name); + bool isType(const QString &name, QChar ch); + QString getAttrAt(const QString &name, int index); + QChar getAttrChar(CmdAttribute attr); + CmdAttribute getCharAttr(QChar ch); }; } #endif diff --git a/src/livepreview.cpp b/src/livepreview.cpp index b7cee0ed..0717471d 100644 --- a/src/livepreview.cpp +++ b/src/livepreview.cpp @@ -1,1377 +1,1377 @@ /******************************************************************************** Copyright (C) 2011-2017 by Michel Ludwig (michel.ludwig@kdemail.net) ********************************************************************************/ /*************************************************************************** * * * 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. * * * ***************************************************************************/ #include "livepreview.h" #include "config.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "errorhandler.h" #include "kiledebug.h" #include "kiletool_enums.h" #include "kiledocmanager.h" #include "kileviewmanager.h" //TODO: it still has to be checked whether it is necessary to use LaTeXInfo objects namespace KileTool { class LivePreviewManager::PreviewInformation { public: - PreviewInformation() - : lastSynchronizationCursor(-1, -1) - { - initTemporaryDirectory(); - } - - ~PreviewInformation() { - delete m_tempDir; - } - - QString getTempDir() const { - return m_tempDir->path(); - } - - void clearPreviewPathMappings() { - pathToPreviewPathHash.clear(); - previewPathToPathHash.clear(); - } - - bool createSubDirectoriesForProject(KileProject *project, bool *containsInvalidRelativeItem = Q_NULLPTR) { - if(containsInvalidRelativeItem) { - *containsInvalidRelativeItem = false; - } - QList items = project->items(); - const QString tempCanonicalDir = QDir(m_tempDir->path()).canonicalPath(); - if(tempCanonicalDir.isEmpty()) { - return false; - } - Q_FOREACH(KileProjectItem *item, items) { - bool successful = true; - const QString itemRelativeDir = QFileInfo(tempCanonicalDir + '/' + item->path()).path(); - const QString itemAbsolutePath = QDir(itemRelativeDir).absolutePath(); - if(itemAbsolutePath.isEmpty()) { - successful = false; - } - else if(!itemAbsolutePath.startsWith(tempCanonicalDir)) { - if(containsInvalidRelativeItem) { - *containsInvalidRelativeItem = true; - } - successful = false; // we don't want to create directories below 'm_tempDir->name()' - } - else { - successful = QDir().mkpath(itemAbsolutePath); - } - if(!successful) { - return false; - } - } - return true; - } - - void setLastSynchronizationCursor(int line, int col) - { - lastSynchronizationCursor.setLine(line); - lastSynchronizationCursor.setColumn(col); - } + PreviewInformation() + : lastSynchronizationCursor(-1, -1) + { + initTemporaryDirectory(); + } + + ~PreviewInformation() { + delete m_tempDir; + } + + QString getTempDir() const { + return m_tempDir->path(); + } + + void clearPreviewPathMappings() { + pathToPreviewPathHash.clear(); + previewPathToPathHash.clear(); + } + + bool createSubDirectoriesForProject(KileProject *project, bool *containsInvalidRelativeItem = Q_NULLPTR) { + if(containsInvalidRelativeItem) { + *containsInvalidRelativeItem = false; + } + QList items = project->items(); + const QString tempCanonicalDir = QDir(m_tempDir->path()).canonicalPath(); + if(tempCanonicalDir.isEmpty()) { + return false; + } + Q_FOREACH(KileProjectItem *item, items) { + bool successful = true; + const QString itemRelativeDir = QFileInfo(tempCanonicalDir + '/' + item->path()).path(); + const QString itemAbsolutePath = QDir(itemRelativeDir).absolutePath(); + if(itemAbsolutePath.isEmpty()) { + successful = false; + } + else if(!itemAbsolutePath.startsWith(tempCanonicalDir)) { + if(containsInvalidRelativeItem) { + *containsInvalidRelativeItem = true; + } + successful = false; // we don't want to create directories below 'm_tempDir->name()' + } + else { + successful = QDir().mkpath(itemAbsolutePath); + } + if(!successful) { + return false; + } + } + return true; + } + + void setLastSynchronizationCursor(int line, int col) + { + lastSynchronizationCursor.setLine(line); + lastSynchronizationCursor.setColumn(col); + } private: - QTemporaryDir *m_tempDir; + QTemporaryDir *m_tempDir; - void initTemporaryDirectory() { - m_tempDir = new QTemporaryDir(QDir::tempPath() + QLatin1Char('/') + "kile-livepreview"); - } + void initTemporaryDirectory() { + m_tempDir = new QTemporaryDir(QDir::tempPath() + QLatin1Char('/') + "kile-livepreview"); + } public: - QHash pathToPreviewPathHash; - QHash previewPathToPathHash; - QString previewFile; - QHash textHash; - KTextEditor::Cursor lastSynchronizationCursor; + QHash pathToPreviewPathHash; + QHash previewPathToPathHash; + QString previewFile; + QHash textHash; + KTextEditor::Cursor lastSynchronizationCursor; }; LivePreviewManager::LivePreviewManager(KileInfo *ki, KActionCollection *ac) - : m_ki(ki), - m_bootUpMode(true), - m_previewStatusLed(Q_NULLPTR), - m_previewForCurrentDocumentAction(Q_NULLPTR), - m_recompileLivePreviewAction(Q_NULLPTR), - m_runningLaTeXInfo(Q_NULLPTR), m_runningTextView(Q_NULLPTR), m_runningProject(Q_NULLPTR), - m_runningPreviewInformation(Q_NULLPTR), m_shownPreviewInformation(Q_NULLPTR), m_masterDocumentPreviewInformation(Q_NULLPTR) + : m_ki(ki), + m_bootUpMode(true), + m_previewStatusLed(Q_NULLPTR), + m_previewForCurrentDocumentAction(Q_NULLPTR), + m_recompileLivePreviewAction(Q_NULLPTR), + m_runningLaTeXInfo(Q_NULLPTR), m_runningTextView(Q_NULLPTR), m_runningProject(Q_NULLPTR), + m_runningPreviewInformation(Q_NULLPTR), m_shownPreviewInformation(Q_NULLPTR), m_masterDocumentPreviewInformation(Q_NULLPTR) { - connect(m_ki->viewManager(), SIGNAL(textViewActivated(KTextEditor::View*)), - this, SLOT(handleTextViewActivated(KTextEditor::View*))); - connect(m_ki->viewManager(), SIGNAL(textViewClosed(KTextEditor::View*,bool)), - this, SLOT(handleTextViewClosed(KTextEditor::View*,bool))); - connect(m_ki->toolManager(), SIGNAL(childToolSpawned(KileTool::Base*,KileTool::Base*)), - this, SLOT(handleSpawnedChildTool(KileTool::Base*, KileTool::Base*))); - connect(m_ki->docManager(), SIGNAL(documentSavedAs(KTextEditor::View*, KileDocument::TextInfo*)), - this, SLOT(handleDocumentSavedAs(KTextEditor::View*, KileDocument::TextInfo*))); - connect(m_ki->docManager(), SIGNAL(documentOpened(KileDocument::TextInfo*)), - this, SLOT(handleDocumentOpened(KileDocument::TextInfo*))); - connect(m_ki->docManager(), SIGNAL(projectOpened(KileProject*)), - this, SLOT(handleProjectOpened(KileProject*))); - - createActions(ac); - populateViewerControlToolBar(); - - m_ledBlinkingTimer = new QTimer(this); - m_ledBlinkingTimer->setSingleShot(false); - m_ledBlinkingTimer->setInterval(500); - connect(m_ledBlinkingTimer, SIGNAL(timeout()), m_previewStatusLed, SLOT(toggle())); - - m_documentChangedTimer = new QTimer(this); - m_documentChangedTimer->setSingleShot(true); - connect(m_documentChangedTimer, SIGNAL(timeout()), this, SLOT(handleDocumentModificationTimerTimeout())); - - showPreviewDisabled(); + connect(m_ki->viewManager(), SIGNAL(textViewActivated(KTextEditor::View*)), + this, SLOT(handleTextViewActivated(KTextEditor::View*))); + connect(m_ki->viewManager(), SIGNAL(textViewClosed(KTextEditor::View*,bool)), + this, SLOT(handleTextViewClosed(KTextEditor::View*,bool))); + connect(m_ki->toolManager(), SIGNAL(childToolSpawned(KileTool::Base*,KileTool::Base*)), + this, SLOT(handleSpawnedChildTool(KileTool::Base*, KileTool::Base*))); + connect(m_ki->docManager(), SIGNAL(documentSavedAs(KTextEditor::View*, KileDocument::TextInfo*)), + this, SLOT(handleDocumentSavedAs(KTextEditor::View*, KileDocument::TextInfo*))); + connect(m_ki->docManager(), SIGNAL(documentOpened(KileDocument::TextInfo*)), + this, SLOT(handleDocumentOpened(KileDocument::TextInfo*))); + connect(m_ki->docManager(), SIGNAL(projectOpened(KileProject*)), + this, SLOT(handleProjectOpened(KileProject*))); + + createActions(ac); + populateViewerControlToolBar(); + + m_ledBlinkingTimer = new QTimer(this); + m_ledBlinkingTimer->setSingleShot(false); + m_ledBlinkingTimer->setInterval(500); + connect(m_ledBlinkingTimer, SIGNAL(timeout()), m_previewStatusLed, SLOT(toggle())); + + m_documentChangedTimer = new QTimer(this); + m_documentChangedTimer->setSingleShot(true); + connect(m_documentChangedTimer, SIGNAL(timeout()), this, SLOT(handleDocumentModificationTimerTimeout())); + + showPreviewDisabled(); } LivePreviewManager::~LivePreviewManager() { - KILE_DEBUG_MAIN; + KILE_DEBUG_MAIN; - qDeleteAll(m_livePreviewToolActionList); - m_livePreviewToolActionList.clear(); + qDeleteAll(m_livePreviewToolActionList); + m_livePreviewToolActionList.clear(); - deleteAllLivePreviewInformation(); + deleteAllLivePreviewInformation(); } void LivePreviewManager::disableBootUpMode() { - m_bootUpMode = false; - recompileLivePreview(); + m_bootUpMode = false; + recompileLivePreview(); } void LivePreviewManager::createActions(KActionCollection *ac) { - m_livePreviewToolActionGroup = new QActionGroup(ac); + m_livePreviewToolActionGroup = new QActionGroup(ac); - m_previewForCurrentDocumentAction = new KToggleAction(QIcon::fromTheme("document-preview"), i18n("Live Preview for Current Document or Project"), this); - m_previewForCurrentDocumentAction->setChecked(true); - connect(m_previewForCurrentDocumentAction, SIGNAL(triggered(bool)), this, SLOT(previewForCurrentDocumentActionTriggered(bool))); - ac->addAction("live_preview_for_current_document", m_previewForCurrentDocumentAction); + m_previewForCurrentDocumentAction = new KToggleAction(QIcon::fromTheme("document-preview"), i18n("Live Preview for Current Document or Project"), this); + m_previewForCurrentDocumentAction->setChecked(true); + connect(m_previewForCurrentDocumentAction, SIGNAL(triggered(bool)), this, SLOT(previewForCurrentDocumentActionTriggered(bool))); + ac->addAction("live_preview_for_current_document", m_previewForCurrentDocumentAction); - m_recompileLivePreviewAction = new QAction(i18n("Recompile Live Preview"), this); - connect(m_recompileLivePreviewAction, SIGNAL(triggered()), this, SLOT(recompileLivePreview())); - ac->addAction("live_preview_recompile", m_recompileLivePreviewAction); + m_recompileLivePreviewAction = new QAction(i18n("Recompile Live Preview"), this); + connect(m_recompileLivePreviewAction, SIGNAL(triggered()), this, SLOT(recompileLivePreview())); + ac->addAction("live_preview_recompile", m_recompileLivePreviewAction); } void LivePreviewManager::previewForCurrentDocumentActionTriggered(bool b) { - if(m_bootUpMode || !KileConfig::livePreviewEnabled()) { - return; - } - KTextEditor::View *view = m_ki->viewManager()->currentTextView(); - if(!view) { - return; - } - KileDocument::LaTeXInfo *latexInfo = dynamic_cast(m_ki->docManager()->textInfoFor(view->document())); - if(!latexInfo) { - return; - } - LivePreviewUserStatusHandler *userStatusHandler; - findPreviewInformation(latexInfo, Q_NULLPTR, &userStatusHandler); - Q_ASSERT(userStatusHandler); - - userStatusHandler->setLivePreviewEnabled(b); - - if(b) { - showPreviewCompileIfNecessary(latexInfo, view); - } - else { - disablePreview(); - } + if(m_bootUpMode || !KileConfig::livePreviewEnabled()) { + return; + } + KTextEditor::View *view = m_ki->viewManager()->currentTextView(); + if(!view) { + return; + } + KileDocument::LaTeXInfo *latexInfo = dynamic_cast(m_ki->docManager()->textInfoFor(view->document())); + if(!latexInfo) { + return; + } + LivePreviewUserStatusHandler *userStatusHandler; + findPreviewInformation(latexInfo, Q_NULLPTR, &userStatusHandler); + Q_ASSERT(userStatusHandler); + + userStatusHandler->setLivePreviewEnabled(b); + + if(b) { + showPreviewCompileIfNecessary(latexInfo, view); + } + else { + disablePreview(); + } } void LivePreviewManager::livePreviewToolActionTriggered() { - QAction *action = dynamic_cast(sender()); - if(!action) { - KILE_DEBUG_MAIN << "slot called from wrong object!!"; - return; - } - if(!m_actionToLivePreviewToolHash.contains(action)) { - KILE_DEBUG_MAIN << "action not found in hash!!"; - return; - } - const ToolConfigPair p = m_actionToLivePreviewToolHash[action]; - KTextEditor::View *view = m_ki->viewManager()->currentTextView(); - if(!view) { - KILE_DEBUG_MAIN << "no text view open!"; - return; - } - KileDocument::LaTeXInfo *latexInfo = dynamic_cast(m_ki->docManager()->textInfoFor(view->document())); - if(!latexInfo) { - KILE_DEBUG_MAIN << "current view is not LaTeX-compatible!"; - return; - } - - LivePreviewUserStatusHandler *userStatusHandler; - findPreviewInformation(latexInfo, Q_NULLPTR, &userStatusHandler); - if(!userStatusHandler) { - KILE_DEBUG_MAIN << "no preview information found!"; - return; - } - const bool changed = userStatusHandler->setLivePreviewTool(p); - if(changed) { - recompileLivePreview(); - } + QAction *action = dynamic_cast(sender()); + if(!action) { + KILE_DEBUG_MAIN << "slot called from wrong object!!"; + return; + } + if(!m_actionToLivePreviewToolHash.contains(action)) { + KILE_DEBUG_MAIN << "action not found in hash!!"; + return; + } + const ToolConfigPair p = m_actionToLivePreviewToolHash[action]; + KTextEditor::View *view = m_ki->viewManager()->currentTextView(); + if(!view) { + KILE_DEBUG_MAIN << "no text view open!"; + return; + } + KileDocument::LaTeXInfo *latexInfo = dynamic_cast(m_ki->docManager()->textInfoFor(view->document())); + if(!latexInfo) { + KILE_DEBUG_MAIN << "current view is not LaTeX-compatible!"; + return; + } + + LivePreviewUserStatusHandler *userStatusHandler; + findPreviewInformation(latexInfo, Q_NULLPTR, &userStatusHandler); + if(!userStatusHandler) { + KILE_DEBUG_MAIN << "no preview information found!"; + return; + } + const bool changed = userStatusHandler->setLivePreviewTool(p); + if(changed) { + recompileLivePreview(); + } } void LivePreviewManager::updateLivePreviewToolActions(LivePreviewUserStatusHandler *userStatusHandler) { - setLivePreviewToolActionsEnabled(true); - const ToolConfigPair p = userStatusHandler->livePreviewTool(); - if(!m_livePreviewToolToActionHash.contains(p)) { - return; - } - m_livePreviewToolToActionHash[p]->setChecked(true); + setLivePreviewToolActionsEnabled(true); + const ToolConfigPair p = userStatusHandler->livePreviewTool(); + if(!m_livePreviewToolToActionHash.contains(p)) { + return; + } + m_livePreviewToolToActionHash[p]->setChecked(true); } void LivePreviewManager::setLivePreviewToolActionsEnabled(bool b) { - Q_FOREACH(QAction *action, m_livePreviewToolActionList) { - action->setEnabled(b); - } + Q_FOREACH(QAction *action, m_livePreviewToolActionList) { + action->setEnabled(b); + } } void LivePreviewManager::buildLivePreviewMenu(KConfig *config) { - QMenu *menu = dynamic_cast(m_ki->mainWindow()->guiFactory()->container("menu_livepreview", m_ki->mainWindow())); - if(!menu) { - KILE_DEBUG_MAIN << "live preview menu not found!!"; - return; - } - - qDeleteAll(m_livePreviewToolActionList); - m_livePreviewToolActionList.clear(); - m_livePreviewToolToActionHash.clear(); - m_actionToLivePreviewToolHash.clear(); - - // necessary as it will be disabled otherwise in 'kile.cpp' (as it's empty initially) - menu->setEnabled(true); - menu->clear(); - menu->addAction(m_previewForCurrentDocumentAction); - menu->addSeparator(); - - QList toolList = toolsWithConfigurationsBasedOnClass(config, "LaTeXLivePreview"); - std::sort(toolList.begin(), toolList.end()); - for(QList::iterator i = toolList.begin(); i != toolList.end(); ++i) { - const QString shortToolName = QString((*i).first).remove("LivePreview-"); - QAction *action = new KToggleAction(ToolConfigPair::userStringRepresentation(shortToolName, (*i).second), this); - - m_livePreviewToolActionGroup->addAction(action); - connect(action, SIGNAL(triggered()), this, SLOT(livePreviewToolActionTriggered())); - m_livePreviewToolActionList.push_back(action); - m_livePreviewToolToActionHash[*i] = action; - m_actionToLivePreviewToolHash[action] = *i; - menu->addAction(action); - } - menu->addSeparator(); - menu->addAction(m_recompileLivePreviewAction); + QMenu *menu = dynamic_cast(m_ki->mainWindow()->guiFactory()->container("menu_livepreview", m_ki->mainWindow())); + if(!menu) { + KILE_DEBUG_MAIN << "live preview menu not found!!"; + return; + } + + qDeleteAll(m_livePreviewToolActionList); + m_livePreviewToolActionList.clear(); + m_livePreviewToolToActionHash.clear(); + m_actionToLivePreviewToolHash.clear(); + + // necessary as it will be disabled otherwise in 'kile.cpp' (as it's empty initially) + menu->setEnabled(true); + menu->clear(); + menu->addAction(m_previewForCurrentDocumentAction); + menu->addSeparator(); + + QList toolList = toolsWithConfigurationsBasedOnClass(config, "LaTeXLivePreview"); + std::sort(toolList.begin(), toolList.end()); + for(QList::iterator i = toolList.begin(); i != toolList.end(); ++i) { + const QString shortToolName = QString((*i).first).remove("LivePreview-"); + QAction *action = new KToggleAction(ToolConfigPair::userStringRepresentation(shortToolName, (*i).second), this); + + m_livePreviewToolActionGroup->addAction(action); + connect(action, SIGNAL(triggered()), this, SLOT(livePreviewToolActionTriggered())); + m_livePreviewToolActionList.push_back(action); + m_livePreviewToolToActionHash[*i] = action; + m_actionToLivePreviewToolHash[action] = *i; + menu->addAction(action); + } + menu->addSeparator(); + menu->addAction(m_recompileLivePreviewAction); } bool LivePreviewManager::isLivePreviewEnabledForCurrentDocument() { - return m_previewForCurrentDocumentAction->isChecked(); + return m_previewForCurrentDocumentAction->isChecked(); } void LivePreviewManager::setLivePreviewEnabledForCurrentDocument(bool b) { - m_previewForCurrentDocumentAction->setChecked(b); - previewForCurrentDocumentActionTriggered(b); + m_previewForCurrentDocumentAction->setChecked(b); + previewForCurrentDocumentActionTriggered(b); } void LivePreviewManager::disablePreview() { - stopAndClearPreview(); - setLivePreviewToolActionsEnabled(false); - m_previewForCurrentDocumentAction->setChecked(false); - m_ki->viewManager()->setLivePreviewModeForDocumentViewer(false); + stopAndClearPreview(); + setLivePreviewToolActionsEnabled(false); + m_previewForCurrentDocumentAction->setChecked(false); + m_ki->viewManager()->setLivePreviewModeForDocumentViewer(false); } void LivePreviewManager::stopAndClearPreview() { - KILE_DEBUG_MAIN; - stopLivePreview(); - clearLivePreview(); + KILE_DEBUG_MAIN; + stopLivePreview(); + clearLivePreview(); } void LivePreviewManager::clearLivePreview() { - KILE_DEBUG_MAIN; - showPreviewDisabled(); - - KParts::ReadOnlyPart *viewerPart = m_ki->viewManager()->viewerPart(); - if(m_shownPreviewInformation && viewerPart->url() == QUrl::fromLocalFile(m_shownPreviewInformation->previewFile)) { - viewerPart->closeUrl(); - } - m_shownPreviewInformation = Q_NULLPTR; + KILE_DEBUG_MAIN; + showPreviewDisabled(); + + KParts::ReadOnlyPart *viewerPart = m_ki->viewManager()->viewerPart(); + if(m_shownPreviewInformation && viewerPart->url() == QUrl::fromLocalFile(m_shownPreviewInformation->previewFile)) { + viewerPart->closeUrl(); + } + m_shownPreviewInformation = Q_NULLPTR; } void LivePreviewManager::stopLivePreview() { - m_documentChangedTimer->stop(); - m_ki->toolManager()->stopLivePreview(); + m_documentChangedTimer->stop(); + m_ki->toolManager()->stopLivePreview(); - clearRunningLivePreviewInformation(); + clearRunningLivePreviewInformation(); } void LivePreviewManager::clearRunningLivePreviewInformation() { - m_runningPathToPreviewPathHash.clear(); - m_runningPreviewPathToPathHash.clear(); - m_runningPreviewFile.clear(); - m_runningLaTeXInfo = Q_NULLPTR; - m_runningProject = Q_NULLPTR; - m_runningTextView = Q_NULLPTR; - m_runningPreviewInformation = Q_NULLPTR; - m_runningTextHash.clear(); + m_runningPathToPreviewPathHash.clear(); + m_runningPreviewPathToPathHash.clear(); + m_runningPreviewFile.clear(); + m_runningLaTeXInfo = Q_NULLPTR; + m_runningProject = Q_NULLPTR; + m_runningTextView = Q_NULLPTR; + m_runningPreviewInformation = Q_NULLPTR; + m_runningTextHash.clear(); } void LivePreviewManager::deleteAllLivePreviewInformation() { - // first, we have to make sure that nothing is shown anymore, - // and that no preview is running - stopAndClearPreview(); - - disablePreview(); - - // and now we can delete all the 'PreviewInformation' objects - delete m_masterDocumentPreviewInformation; - m_masterDocumentPreviewInformation = Q_NULLPTR; - - for(QHash::iterator i = m_latexInfoToPreviewInformationHash.begin(); - i != m_latexInfoToPreviewInformationHash.end(); ++i) { - delete i.value(); - } - - for(QHash::iterator i = m_projectToPreviewInformationHash.begin(); - i != m_projectToPreviewInformationHash.end(); ++i) { - delete i.value(); - } - m_latexInfoToPreviewInformationHash.clear(); - m_projectToPreviewInformationHash.clear(); + // first, we have to make sure that nothing is shown anymore, + // and that no preview is running + stopAndClearPreview(); + + disablePreview(); + + // and now we can delete all the 'PreviewInformation' objects + delete m_masterDocumentPreviewInformation; + m_masterDocumentPreviewInformation = Q_NULLPTR; + + for(QHash::iterator i = m_latexInfoToPreviewInformationHash.begin(); + i != m_latexInfoToPreviewInformationHash.end(); ++i) { + delete i.value(); + } + + for(QHash::iterator i = m_projectToPreviewInformationHash.begin(); + i != m_projectToPreviewInformationHash.end(); ++i) { + delete i.value(); + } + m_latexInfoToPreviewInformationHash.clear(); + m_projectToPreviewInformationHash.clear(); } void LivePreviewManager::readConfig(KConfig *config) { - Q_UNUSED(config); + Q_UNUSED(config); - buildLivePreviewMenu(config); + buildLivePreviewMenu(config); - m_previewForCurrentDocumentAction->setEnabled(KileConfig::livePreviewEnabled()); - m_previewStatusLed->setEnabled(KileConfig::livePreviewEnabled()); + m_previewForCurrentDocumentAction->setEnabled(KileConfig::livePreviewEnabled()); + m_previewStatusLed->setEnabled(KileConfig::livePreviewEnabled()); - if(m_bootUpMode || !KileConfig::livePreviewEnabled()) { - deleteAllLivePreviewInformation(); - } - else { - refreshLivePreview(); // e.g. in case the live preview was disabled and no preview is - // currently shown - } + if(m_bootUpMode || !KileConfig::livePreviewEnabled()) { + deleteAllLivePreviewInformation(); + } + else { + refreshLivePreview(); // e.g. in case the live preview was disabled and no preview is + // currently shown + } } void LivePreviewManager::writeConfig() { } void LivePreviewManager::readLivePreviewStatusSettings(KConfigGroup &configGroup, LivePreviewUserStatusHandler *handler) { - // the prefix 'kile_' is necessary as these settings might be written into a config group that is also modified - // by KatePart - if(configGroup.readEntry("kile_livePreviewStatusUserSpecified", false)) { - handler->setLivePreviewEnabled(configGroup.readEntry("kile_livePreviewEnabled", true)); - } - - const QString livePreviewToolConfigString = configGroup.readEntry("kile_livePreviewTool", ""); - if(livePreviewToolConfigString.isEmpty()) { - handler->setLivePreviewTool(ToolConfigPair(LIVEPREVIEW_DEFAULT_TOOL_NAME, DEFAULT_TOOL_CONFIGURATION)); - } - else { - handler->setLivePreviewTool(ToolConfigPair::fromConfigStringRepresentation(livePreviewToolConfigString)); - } + // the prefix 'kile_' is necessary as these settings might be written into a config group that is also modified + // by KatePart + if(configGroup.readEntry("kile_livePreviewStatusUserSpecified", false)) { + handler->setLivePreviewEnabled(configGroup.readEntry("kile_livePreviewEnabled", true)); + } + + const QString livePreviewToolConfigString = configGroup.readEntry("kile_livePreviewTool", ""); + if(livePreviewToolConfigString.isEmpty()) { + handler->setLivePreviewTool(ToolConfigPair(LIVEPREVIEW_DEFAULT_TOOL_NAME, DEFAULT_TOOL_CONFIGURATION)); + } + else { + handler->setLivePreviewTool(ToolConfigPair::fromConfigStringRepresentation(livePreviewToolConfigString)); + } } void LivePreviewManager::writeLivePreviewStatusSettings(KConfigGroup &configGroup, LivePreviewUserStatusHandler *handler) { - configGroup.writeEntry("kile_livePreviewTool", handler->livePreviewTool().configStringRepresentation()); - configGroup.writeEntry("kile_livePreviewEnabled", handler->isLivePreviewEnabled()); - configGroup.writeEntry("kile_livePreviewStatusUserSpecified", handler->userSpecifiedLivePreviewStatus()); + configGroup.writeEntry("kile_livePreviewTool", handler->livePreviewTool().configStringRepresentation()); + configGroup.writeEntry("kile_livePreviewEnabled", handler->isLivePreviewEnabled()); + configGroup.writeEntry("kile_livePreviewStatusUserSpecified", handler->userSpecifiedLivePreviewStatus()); } void LivePreviewManager::populateViewerControlToolBar() { - KToolBar* viewerControlToolBar = m_ki->viewManager()->getViewerControlToolBar(); - viewerControlToolBar->addAction(m_previewForCurrentDocumentAction); + KToolBar* viewerControlToolBar = m_ki->viewManager()->getViewerControlToolBar(); + viewerControlToolBar->addAction(m_previewForCurrentDocumentAction); - m_previewStatusLed = new KLed(viewerControlToolBar); - m_previewStatusLed->setShape(KLed::Circular); - m_previewStatusLed->setLook(KLed::Flat); - viewerControlToolBar->addWidget(m_previewStatusLed); + m_previewStatusLed = new KLed(viewerControlToolBar); + m_previewStatusLed->setShape(KLed::Circular); + m_previewStatusLed->setLook(KLed::Flat); + viewerControlToolBar->addWidget(m_previewStatusLed); } void LivePreviewManager::handleMasterDocumentChanged() { - if(m_bootUpMode || !KileConfig::livePreviewEnabled()) { - return; - } + if(m_bootUpMode || !KileConfig::livePreviewEnabled()) { + return; + } - deleteAllLivePreviewInformation(); - refreshLivePreview(); + deleteAllLivePreviewInformation(); + refreshLivePreview(); } void LivePreviewManager::handleTextChanged(KTextEditor::Document *doc) { - if(m_bootUpMode || !KileConfig::livePreviewEnabled()) { - return; - } + if(m_bootUpMode || !KileConfig::livePreviewEnabled()) { + return; + } - KILE_DEBUG_MAIN; - if(!isCurrentDocumentOrProject(doc)) { - return; - } + KILE_DEBUG_MAIN; + if(!isCurrentDocumentOrProject(doc)) { + return; + } - stopLivePreview(); - showPreviewOutOfDate(); + stopLivePreview(); + showPreviewOutOfDate(); - if(!KileConfig::livePreviewCompileOnlyAfterSaving()) { - m_documentChangedTimer->start(KileConfig::livePreviewCompilationDelay()); - } + if(!KileConfig::livePreviewCompileOnlyAfterSaving()) { + m_documentChangedTimer->start(KileConfig::livePreviewCompilationDelay()); + } } void LivePreviewManager::handleDocumentSavedOrUploaded(KTextEditor::Document *doc, bool savedAs) { - Q_UNUSED(savedAs); - - if(m_bootUpMode || !KileConfig::livePreviewEnabled()) { - return; - } - - KILE_DEBUG_MAIN; - - if(!KileConfig::livePreviewCompileOnlyAfterSaving()) { - return; - } - - if(!isCurrentDocumentOrProject(doc)) { - return; - } - KTextEditor::View *view = m_ki->viewManager()->currentTextView(); - KileDocument::LaTeXInfo *latexInfo = dynamic_cast(m_ki->docManager()->textInfoFor(view->document())); - if(!latexInfo) { - return; - } - - LivePreviewUserStatusHandler *userStatusHandler; - findPreviewInformation(latexInfo, Q_NULLPTR, &userStatusHandler); - Q_ASSERT(userStatusHandler); - if(userStatusHandler->isLivePreviewEnabled()) { - showPreviewCompileIfNecessary(latexInfo, view); - } + Q_UNUSED(savedAs); + + if(m_bootUpMode || !KileConfig::livePreviewEnabled()) { + return; + } + + KILE_DEBUG_MAIN; + + if(!KileConfig::livePreviewCompileOnlyAfterSaving()) { + return; + } + + if(!isCurrentDocumentOrProject(doc)) { + return; + } + KTextEditor::View *view = m_ki->viewManager()->currentTextView(); + KileDocument::LaTeXInfo *latexInfo = dynamic_cast(m_ki->docManager()->textInfoFor(view->document())); + if(!latexInfo) { + return; + } + + LivePreviewUserStatusHandler *userStatusHandler; + findPreviewInformation(latexInfo, Q_NULLPTR, &userStatusHandler); + Q_ASSERT(userStatusHandler); + if(userStatusHandler->isLivePreviewEnabled()) { + showPreviewCompileIfNecessary(latexInfo, view); + } } void LivePreviewManager::handleDocumentModificationTimerTimeout() { - if(m_bootUpMode || !KileConfig::livePreviewEnabled()) { - return; - } - - KILE_DEBUG_MAIN; - - KTextEditor::View *view = m_ki->viewManager()->currentTextView(); - KileDocument::LaTeXInfo *latexInfo = dynamic_cast(m_ki->docManager()->textInfoFor(view->document())); - if(!latexInfo) { - return; - } - - KTextEditor::CodeCompletionInterface *codeCompletionInterface = qobject_cast(view); - - // if the code completion box is currently shown, we don't trigger an update of the preview - // as this will cause the document to be saved and the completion box to be hidden as a consequence - if(codeCompletionInterface && codeCompletionInterface->isCompletionActive()) { - m_documentChangedTimer->start(); - return; - } - - LivePreviewUserStatusHandler *userStatusHandler; - findPreviewInformation(latexInfo, Q_NULLPTR, &userStatusHandler); - Q_ASSERT(userStatusHandler); - if(userStatusHandler->isLivePreviewEnabled()) { - compilePreview(latexInfo, view); - } + if(m_bootUpMode || !KileConfig::livePreviewEnabled()) { + return; + } + + KILE_DEBUG_MAIN; + + KTextEditor::View *view = m_ki->viewManager()->currentTextView(); + KileDocument::LaTeXInfo *latexInfo = dynamic_cast(m_ki->docManager()->textInfoFor(view->document())); + if(!latexInfo) { + return; + } + + KTextEditor::CodeCompletionInterface *codeCompletionInterface = qobject_cast(view); + + // if the code completion box is currently shown, we don't trigger an update of the preview + // as this will cause the document to be saved and the completion box to be hidden as a consequence + if(codeCompletionInterface && codeCompletionInterface->isCompletionActive()) { + m_documentChangedTimer->start(); + return; + } + + LivePreviewUserStatusHandler *userStatusHandler; + findPreviewInformation(latexInfo, Q_NULLPTR, &userStatusHandler); + Q_ASSERT(userStatusHandler); + if(userStatusHandler->isLivePreviewEnabled()) { + compilePreview(latexInfo, view); + } } void LivePreviewManager::showPreviewDisabled() { - KILE_DEBUG_MAIN; - m_ledBlinkingTimer->stop(); - if(m_previewStatusLed) { - m_previewStatusLed->off(); - } + KILE_DEBUG_MAIN; + m_ledBlinkingTimer->stop(); + if(m_previewStatusLed) { + m_previewStatusLed->off(); + } } void LivePreviewManager::showPreviewRunning() { - KILE_DEBUG_MAIN; - if(m_previewStatusLed) { - m_previewStatusLed->setColor(QColor(Qt::yellow)); - m_previewStatusLed->off(); - } - m_ledBlinkingTimer->start(); + KILE_DEBUG_MAIN; + if(m_previewStatusLed) { + m_previewStatusLed->setColor(QColor(Qt::yellow)); + m_previewStatusLed->off(); + } + m_ledBlinkingTimer->start(); } void LivePreviewManager::showPreviewFailed() { - KILE_DEBUG_MAIN; - m_ledBlinkingTimer->stop(); - if(m_previewStatusLed) { - m_previewStatusLed->on(); - m_previewStatusLed->setColor(QColor(Qt::red)); - } + KILE_DEBUG_MAIN; + m_ledBlinkingTimer->stop(); + if(m_previewStatusLed) { + m_previewStatusLed->on(); + m_previewStatusLed->setColor(QColor(Qt::red)); + } } void LivePreviewManager::showPreviewSuccessful() { - KILE_DEBUG_MAIN; - m_ledBlinkingTimer->stop(); - if(m_previewStatusLed) { - m_previewStatusLed->on(); - m_previewStatusLed->setColor(QColor(Qt::green)); - } + KILE_DEBUG_MAIN; + m_ledBlinkingTimer->stop(); + if(m_previewStatusLed) { + m_previewStatusLed->on(); + m_previewStatusLed->setColor(QColor(Qt::green)); + } } void LivePreviewManager::showPreviewOutOfDate() { - KILE_DEBUG_MAIN; - m_ledBlinkingTimer->stop(); - if(m_previewStatusLed) { - m_previewStatusLed->on(); - m_previewStatusLed->setColor(QColor(Qt::yellow)); - } + KILE_DEBUG_MAIN; + m_ledBlinkingTimer->stop(); + if(m_previewStatusLed) { + m_previewStatusLed->on(); + m_previewStatusLed->setColor(QColor(Qt::yellow)); + } } // If a LaTeXInfo* pointer is passed as first argument, it is guaranteed that '*userStatusHandler' won't be Q_NULLPTR. LivePreviewManager::PreviewInformation* LivePreviewManager::findPreviewInformation(KileDocument::TextInfo *textInfo, - KileProject* *locatedProject, - LivePreviewUserStatusHandler* *userStatusHandler, - LaTeXOutputHandler* *latexOutputHandler) + KileProject* *locatedProject, + LivePreviewUserStatusHandler* *userStatusHandler, + LaTeXOutputHandler* *latexOutputHandler) { - const QString masterDocumentFileName = m_ki->getMasterDocumentFileName(); - if(locatedProject) { - *locatedProject = Q_NULLPTR; - } - KileDocument::LaTeXInfo *latexInfo = dynamic_cast(textInfo); - if(userStatusHandler) { - *userStatusHandler = latexInfo; - } - if(latexOutputHandler) { - *latexOutputHandler = latexInfo; - } - if(!masterDocumentFileName.isEmpty()) { - KILE_DEBUG_MAIN << "master document defined"; - return m_masterDocumentPreviewInformation; - } - KileProject *project = m_ki->docManager()->projectForMember(textInfo->url()); - if(project) { - KILE_DEBUG_MAIN << "part of a project"; - if(locatedProject) { - *locatedProject = project; - } - if(userStatusHandler) { - *userStatusHandler = project; - } - if(latexOutputHandler) { - *latexOutputHandler = project; - } - if(m_projectToPreviewInformationHash.contains(project)) { - KILE_DEBUG_MAIN << "project found"; - return m_projectToPreviewInformationHash[project]; - } - else { - KILE_DEBUG_MAIN << "project not found"; - return Q_NULLPTR; - } - } - else if(latexInfo && m_latexInfoToPreviewInformationHash.contains(latexInfo)) { - KILE_DEBUG_MAIN << "not part of a project"; - return m_latexInfoToPreviewInformationHash[latexInfo]; - } - else { - KILE_DEBUG_MAIN << "not found"; - return Q_NULLPTR; - } + const QString masterDocumentFileName = m_ki->getMasterDocumentFileName(); + if(locatedProject) { + *locatedProject = Q_NULLPTR; + } + KileDocument::LaTeXInfo *latexInfo = dynamic_cast(textInfo); + if(userStatusHandler) { + *userStatusHandler = latexInfo; + } + if(latexOutputHandler) { + *latexOutputHandler = latexInfo; + } + if(!masterDocumentFileName.isEmpty()) { + KILE_DEBUG_MAIN << "master document defined"; + return m_masterDocumentPreviewInformation; + } + KileProject *project = m_ki->docManager()->projectForMember(textInfo->url()); + if(project) { + KILE_DEBUG_MAIN << "part of a project"; + if(locatedProject) { + *locatedProject = project; + } + if(userStatusHandler) { + *userStatusHandler = project; + } + if(latexOutputHandler) { + *latexOutputHandler = project; + } + if(m_projectToPreviewInformationHash.contains(project)) { + KILE_DEBUG_MAIN << "project found"; + return m_projectToPreviewInformationHash[project]; + } + else { + KILE_DEBUG_MAIN << "project not found"; + return Q_NULLPTR; + } + } + else if(latexInfo && m_latexInfoToPreviewInformationHash.contains(latexInfo)) { + KILE_DEBUG_MAIN << "not part of a project"; + return m_latexInfoToPreviewInformationHash[latexInfo]; + } + else { + KILE_DEBUG_MAIN << "not found"; + return Q_NULLPTR; + } } bool LivePreviewManager::isCurrentDocumentOrProject(KTextEditor::Document *doc) { - const KTextEditor::View *currentView = m_ki->viewManager()->currentTextView(); + const KTextEditor::View *currentView = m_ki->viewManager()->currentTextView(); - if(currentView->document() != doc) { - const KileProject *project = m_ki->docManager()->projectForMember(doc->url()); - const KileProject *currentProject = m_ki->docManager()->activeProject(); - if(!currentProject || (project != currentProject)) { - return false; - } - } + if(currentView->document() != doc) { + const KileProject *project = m_ki->docManager()->projectForMember(doc->url()); + const KileProject *currentProject = m_ki->docManager()->activeProject(); + if(!currentProject || (project != currentProject)) { + return false; + } + } - return true; + return true; } void LivePreviewManager::showCursorPositionInDocumentViewer() { - KTextEditor::View *view = m_ki->viewManager()->currentTextView(); - if(!view) { - return; - } - KileDocument::LaTeXInfo *latexInfo = dynamic_cast(m_ki->docManager()->textInfoFor(view->document())); - if(!latexInfo) { - return; - } - LivePreviewUserStatusHandler *userStatusHandler = Q_NULLPTR; - findPreviewInformation(latexInfo, Q_NULLPTR, &userStatusHandler); - if(!userStatusHandler->isLivePreviewEnabled()) { - return; - } - - synchronizeViewWithCursor(latexInfo, view, view->cursorPosition(), true); // called from a cursor position change + KTextEditor::View *view = m_ki->viewManager()->currentTextView(); + if(!view) { + return; + } + KileDocument::LaTeXInfo *latexInfo = dynamic_cast(m_ki->docManager()->textInfoFor(view->document())); + if(!latexInfo) { + return; + } + LivePreviewUserStatusHandler *userStatusHandler = Q_NULLPTR; + findPreviewInformation(latexInfo, Q_NULLPTR, &userStatusHandler); + if(!userStatusHandler->isLivePreviewEnabled()) { + return; + } + + synchronizeViewWithCursor(latexInfo, view, view->cursorPosition(), true); // called from a cursor position change } // Note: this method won't open a document again if it's open already bool LivePreviewManager::ensureDocumentIsOpenInViewer(PreviewInformation *previewInformation, bool *hadToOpen) { - if(hadToOpen) { - *hadToOpen = false; - } - const QFile previewFileInfo(previewInformation->previewFile); - if(!m_ki->viewManager()->viewerPart() || !previewFileInfo.exists() || previewFileInfo.size() == 0) { - return false; - } - const QUrl previewUrl(QUrl::fromLocalFile(previewInformation->previewFile)); - if(m_ki->viewManager()->viewerPart()->url().isEmpty() || m_ki->viewManager()->viewerPart()->url() != previewUrl) { - KILE_DEBUG_MAIN << "loading again"; - if(m_ki->viewManager()->viewerPart()->openUrl(previewUrl)) { - if(hadToOpen) { - *hadToOpen = true; - } - // don't forget this - m_shownPreviewInformation = previewInformation; - return true; - } - else { - m_shownPreviewInformation = Q_NULLPTR; - return false; - } - } - return true; + if(hadToOpen) { + *hadToOpen = false; + } + const QFile previewFileInfo(previewInformation->previewFile); + if(!m_ki->viewManager()->viewerPart() || !previewFileInfo.exists() || previewFileInfo.size() == 0) { + return false; + } + const QUrl previewUrl(QUrl::fromLocalFile(previewInformation->previewFile)); + if(m_ki->viewManager()->viewerPart()->url().isEmpty() || m_ki->viewManager()->viewerPart()->url() != previewUrl) { + KILE_DEBUG_MAIN << "loading again"; + if(m_ki->viewManager()->viewerPart()->openUrl(previewUrl)) { + if(hadToOpen) { + *hadToOpen = true; + } + // don't forget this + m_shownPreviewInformation = previewInformation; + return true; + } + else { + m_shownPreviewInformation = Q_NULLPTR; + return false; + } + } + return true; } void LivePreviewManager::synchronizeViewWithCursor(KileDocument::TextInfo *textInfo, KTextEditor::View *view, - const KTextEditor::Cursor& newPosition, - bool calledFromCursorPositionChange) + const KTextEditor::Cursor& newPosition, + bool calledFromCursorPositionChange) { - Q_UNUSED(view); - KILE_DEBUG_MAIN << "new position " << newPosition; - - PreviewInformation *previewInformation = findPreviewInformation(textInfo); - if(!previewInformation) { - KILE_DEBUG_MAIN << "couldn't find preview information for" << textInfo; - return; - } - - QFileInfo updatedFileInfo(textInfo->getDoc()->url().toLocalFile()); - QString filePath; - if(previewInformation->pathToPreviewPathHash.contains(updatedFileInfo.absoluteFilePath())) { - KILE_DEBUG_MAIN << "found"; - filePath = previewInformation->pathToPreviewPathHash[updatedFileInfo.absoluteFilePath()]; - } - else { - KILE_DEBUG_MAIN << "not found"; - filePath = textInfo->getDoc()->url().toLocalFile(); - } - KILE_DEBUG_MAIN << "filePath" << filePath; - - KILE_DEBUG_MAIN << "previewFile" << previewInformation->previewFile; - - if(!m_ki->viewManager()->viewerPart() || !QFile::exists(previewInformation->previewFile)) { - return; - } - - KILE_DEBUG_MAIN << "url" << m_ki->viewManager()->viewerPart()->url(); - - if(!ensureDocumentIsOpenInViewer(previewInformation)) { - clearLivePreview(); - // must happen after the call to 'clearLivePreview' only - showPreviewFailed(); - return; - } - - - // to increase the performance, if 'calledFromCursorPositionChange' is true, we only synchronize when the cursor line - // has changed from the last synchronization - // NOTE: the performance of SyncTeX has to be improved if changes in cursor columns should be taken into account as - // well (bug 305254) - if(!calledFromCursorPositionChange || (previewInformation->lastSynchronizationCursor.line() != newPosition.line())) { - m_ki->viewManager()->showSourceLocationInDocumentViewer(filePath, newPosition.line(), newPosition.column()); - previewInformation->setLastSynchronizationCursor(newPosition.line(), newPosition.column()); - } + Q_UNUSED(view); + KILE_DEBUG_MAIN << "new position " << newPosition; + + PreviewInformation *previewInformation = findPreviewInformation(textInfo); + if(!previewInformation) { + KILE_DEBUG_MAIN << "couldn't find preview information for" << textInfo; + return; + } + + QFileInfo updatedFileInfo(textInfo->getDoc()->url().toLocalFile()); + QString filePath; + if(previewInformation->pathToPreviewPathHash.contains(updatedFileInfo.absoluteFilePath())) { + KILE_DEBUG_MAIN << "found"; + filePath = previewInformation->pathToPreviewPathHash[updatedFileInfo.absoluteFilePath()]; + } + else { + KILE_DEBUG_MAIN << "not found"; + filePath = textInfo->getDoc()->url().toLocalFile(); + } + KILE_DEBUG_MAIN << "filePath" << filePath; + + KILE_DEBUG_MAIN << "previewFile" << previewInformation->previewFile; + + if(!m_ki->viewManager()->viewerPart() || !QFile::exists(previewInformation->previewFile)) { + return; + } + + KILE_DEBUG_MAIN << "url" << m_ki->viewManager()->viewerPart()->url(); + + if(!ensureDocumentIsOpenInViewer(previewInformation)) { + clearLivePreview(); + // must happen after the call to 'clearLivePreview' only + showPreviewFailed(); + return; + } + + + // to increase the performance, if 'calledFromCursorPositionChange' is true, we only synchronize when the cursor line + // has changed from the last synchronization + // NOTE: the performance of SyncTeX has to be improved if changes in cursor columns should be taken into account as + // well (bug 305254) + if(!calledFromCursorPositionChange || (previewInformation->lastSynchronizationCursor.line() != newPosition.line())) { + m_ki->viewManager()->showSourceLocationInDocumentViewer(filePath, newPosition.line(), newPosition.column()); + previewInformation->setLastSynchronizationCursor(newPosition.line(), newPosition.column()); + } } void LivePreviewManager::reloadDocumentInViewer() { - if(!m_ki->viewManager()->viewerPart()) { - return; - } + if(!m_ki->viewManager()->viewerPart()) { + return; + } - //FIXME ideally, this method should be integrated in an interface extending Okular... - QMetaObject::invokeMethod(m_ki->viewManager()->viewerPart(), "reload"); + //FIXME ideally, this method should be integrated in an interface extending Okular... + QMetaObject::invokeMethod(m_ki->viewManager()->viewerPart(), "reload"); } static QByteArray computeHashOfDocument(KTextEditor::Document *doc) { - QCryptographicHash cryptographicHash(QCryptographicHash::Sha1); - cryptographicHash.addData(doc->text().toUtf8()); - // allows to catch situations when the URL of the document has changed, - // e.g. after a save-as operation, which breaks the handling of source - // references for the displayed document - cryptographicHash.addData(doc->url().toEncoded()); - - return cryptographicHash.result(); + QCryptographicHash cryptographicHash(QCryptographicHash::Sha1); + cryptographicHash.addData(doc->text().toUtf8()); + // allows to catch situations when the URL of the document has changed, + // e.g. after a save-as operation, which breaks the handling of source + // references for the displayed document + cryptographicHash.addData(doc->url().toEncoded()); + + return cryptographicHash.result(); } static void fillTextHashForProject(KileProject *project, QHash &textHash) { - QList list = project->items(); - for(QList::iterator it = list.begin(); it != list.end(); ++it) { - KileProjectItem *item = *it; - - KileDocument::TextInfo *textInfo = item->getInfo(); - if(!textInfo) { - continue; - } - KTextEditor::Document *document = textInfo->getDoc(); - if(!document) { - continue; - } - textHash[textInfo] = computeHashOfDocument(document); - } + QList list = project->items(); + for(QList::iterator it = list.begin(); it != list.end(); ++it) { + KileProjectItem *item = *it; + + KileDocument::TextInfo *textInfo = item->getInfo(); + if(!textInfo) { + continue; + } + KTextEditor::Document *document = textInfo->getDoc(); + if(!document) { + continue; + } + textHash[textInfo] = computeHashOfDocument(document); + } } void LivePreviewManager::fillTextHashForMasterDocument(QHash &textHash) { - // we compute hashes over all the opened files - QList textDocumentInfos = m_ki->docManager()->textDocumentInfos(); - for(QList::iterator it = textDocumentInfos.begin(); it != textDocumentInfos.end(); ++it) { - KileDocument::TextInfo *textInfo = *it; - if(!textInfo) { - continue; - } - KTextEditor::Document *document = textInfo->getDoc(); - if(!document) { - continue; - } - textHash[textInfo] = computeHashOfDocument(document); - } + // we compute hashes over all the opened files + QList textDocumentInfos = m_ki->docManager()->textDocumentInfos(); + for(QList::iterator it = textDocumentInfos.begin(); it != textDocumentInfos.end(); ++it) { + KileDocument::TextInfo *textInfo = *it; + if(!textInfo) { + continue; + } + KTextEditor::Document *document = textInfo->getDoc(); + if(!document) { + continue; + } + textHash[textInfo] = computeHashOfDocument(document); + } } void LivePreviewManager::showPreviewCompileIfNecessary(KileDocument::LaTeXInfo *latexInfo, KTextEditor::View *view) { - KILE_DEBUG_MAIN; - // first, stop any running live preview - stopLivePreview(); - - KileProject *project = Q_NULLPTR; - LivePreviewUserStatusHandler *userStatusHandler = Q_NULLPTR; - PreviewInformation *previewInformation = findPreviewInformation(latexInfo, &project, &userStatusHandler); - if(!previewInformation) { - KILE_DEBUG_MAIN << "not found"; - compilePreview(latexInfo, view); - } - else { - Q_ASSERT(userStatusHandler); - updateLivePreviewToolActions(userStatusHandler); - QHash newHash; + KILE_DEBUG_MAIN; + // first, stop any running live preview + stopLivePreview(); + + KileProject *project = Q_NULLPTR; + LivePreviewUserStatusHandler *userStatusHandler = Q_NULLPTR; + PreviewInformation *previewInformation = findPreviewInformation(latexInfo, &project, &userStatusHandler); + if(!previewInformation) { + KILE_DEBUG_MAIN << "not found"; + compilePreview(latexInfo, view); + } + else { + Q_ASSERT(userStatusHandler); + updateLivePreviewToolActions(userStatusHandler); + QHash newHash; // QString fileName; // QFileInfo fileInfo(view->document()->url().path()); // if(previewInformation->pathToPreviewPathHash.contains(fileInfo.absoluteFilePath())) { // KILE_DEBUG_MAIN << "contains"; // fileName = previewInformation->pathToPreviewPathHash[fileInfo.absoluteFilePath()]; // } // else { // KILE_DEBUG_MAIN << "does not contain"; // fileName = fileInfo.absoluteFilePath(); // } // KILE_DEBUG_MAIN << "fileName:" << fileName; - bool masterDocumentSet = !m_ki->getMasterDocumentFileName().isEmpty(); - - if(masterDocumentSet) { - fillTextHashForMasterDocument(newHash); - } - else if(project) { - fillTextHashForProject(project, newHash); - } - else { - newHash[latexInfo] = computeHashOfDocument(view->document()); - } - - if(newHash != previewInformation->textHash || !QFile::exists(previewInformation->previewFile)) { - KILE_DEBUG_MAIN << "hashes don't match"; - compilePreview(latexInfo, view); - } - else { - KILE_DEBUG_MAIN << "hashes match"; - showPreviewSuccessful(); - synchronizeViewWithCursor(latexInfo, view, view->cursorPosition()); - } - } + bool masterDocumentSet = !m_ki->getMasterDocumentFileName().isEmpty(); + + if(masterDocumentSet) { + fillTextHashForMasterDocument(newHash); + } + else if(project) { + fillTextHashForProject(project, newHash); + } + else { + newHash[latexInfo] = computeHashOfDocument(view->document()); + } + + if(newHash != previewInformation->textHash || !QFile::exists(previewInformation->previewFile)) { + KILE_DEBUG_MAIN << "hashes don't match"; + compilePreview(latexInfo, view); + } + else { + KILE_DEBUG_MAIN << "hashes match"; + showPreviewSuccessful(); + synchronizeViewWithCursor(latexInfo, view, view->cursorPosition()); + } + } } void LivePreviewManager::compilePreview(KileDocument::LaTeXInfo *latexInfo, KTextEditor::View *view) { - KILE_DEBUG_MAIN << "updating preview"; - m_ki->viewManager()->setLivePreviewModeForDocumentViewer(true); - m_runningPathToPreviewPathHash.clear(); - m_runningPreviewPathToPathHash.clear(); - - //CAUTION: as saving launches an event loop, we don't want 'compilePreview' - // to be called from within 'compilePreview' - m_documentChangedTimer->blockSignals(true); - bool saveResult = m_ki->docManager()->fileSaveAll(); - m_documentChangedTimer->blockSignals(false); - // first, we have to save the documents - if(!saveResult) { - displayErrorMessage(i18n("Some documents could not be saved correctly")); - return; - } - - // document is new and hasn't been saved yet at all - if(view->document()->url().isEmpty()) { - displayErrorMessage(i18n("The document must have been saved before the live preview can be started")); - return; - } - - // first, stop any running live preview - stopLivePreview(); - - KileProject *project = Q_NULLPTR; - LivePreviewUserStatusHandler *userStatusHandler; - LaTeXOutputHandler *latexOutputHandler; - PreviewInformation *previewInformation = findPreviewInformation(latexInfo, &project, &userStatusHandler, &latexOutputHandler); - Q_ASSERT(userStatusHandler); - Q_ASSERT(latexOutputHandler); - if(!previewInformation) { - previewInformation = new PreviewInformation(); - if(!m_ki->getMasterDocumentFileName().isEmpty()) { - m_masterDocumentPreviewInformation = previewInformation; - } - else if(project) { - bool containsInvalidRelativeItem = false; - // in the case of a project, we might have to create a similar subdirectory - // structure as it is present in the real project in order for LaTeX - // to work correctly - if(!previewInformation->createSubDirectoriesForProject(project, &containsInvalidRelativeItem)) { - userStatusHandler->setLivePreviewEnabled(false); - if(containsInvalidRelativeItem) { - displayErrorMessage(i18n("The location of one project item is not relative to the project's base directory\n" - "Live preview for this project has been disabled"), true); - } - else { - displayErrorMessage(i18n("Failed to create the subdirectory structure")); - } - delete previewInformation; - disablePreview(); - return; - } - m_projectToPreviewInformationHash[project] = previewInformation; - } - else { - m_latexInfoToPreviewInformationHash[latexInfo] = previewInformation; - } - } - - connect(latexInfo, SIGNAL(aboutToBeDestroyed(KileDocument::TextInfo*)), - this, SLOT(removeLaTeXInfo(KileDocument::TextInfo*)), - Qt::UniqueConnection); - - if(project) { - handleProjectOpened(project); // create the necessary signal-slot connections - } - - updateLivePreviewToolActions(userStatusHandler); - KileTool::LivePreviewLaTeX *latex = dynamic_cast(m_ki->toolManager()->createTool(userStatusHandler->livePreviewTool(), - false)); - if(!latex) { - KILE_DEBUG_MAIN<< "couldn't create the live preview tool"; - return; - } - - // important! - latex->setPartOfLivePreview(); - connect(latex, SIGNAL(done(KileTool::Base*,int,bool)), this, SLOT(toolDone(KileTool::Base*,int,bool))); - connect(latex, SIGNAL(destroyed()), this, SLOT(toolDestroyed())); - - QFileInfo fileInfo; - const bool masterDocumentSet = !m_ki->getMasterDocumentFileName().isEmpty(); - if(masterDocumentSet) { - fileInfo = QFileInfo(m_ki->getMasterDocumentFileName()); - } - else if(project) { - fileInfo = QFileInfo(m_ki->getCompileNameForProject(project)); - } - else { - fileInfo = QFileInfo(m_ki->getCompileName()); - } - - const QString inputDir = previewInformation->getTempDir() + PATH_SEPARATOR + fileInfo.absolutePath(); - - // set value of texinput path (only for LivePreviewManager tools) - QString texInputPath = KileConfig::teXPaths(); - if(!texInputPath.isEmpty()) { - texInputPath = inputDir + PATH_SEPARATOR + texInputPath; - } - else { - texInputPath = inputDir; - } - latex->setTeXInputPaths(texInputPath); - - QString bibInputPath = KileConfig::bibInputPaths(); - if(!bibInputPath.isEmpty()) { - bibInputPath = inputDir + PATH_SEPARATOR + bibInputPath; - } - else { - bibInputPath = inputDir; - } - latex->setBibInputPaths(bibInputPath); - - QString bstInputPath = KileConfig::bstInputPaths(); - if(!bstInputPath.isEmpty()) { - bstInputPath = inputDir + PATH_SEPARATOR + bstInputPath; - } - else { - bstInputPath = inputDir; - } - latex->setBstInputPaths(bstInputPath); + KILE_DEBUG_MAIN << "updating preview"; + m_ki->viewManager()->setLivePreviewModeForDocumentViewer(true); + m_runningPathToPreviewPathHash.clear(); + m_runningPreviewPathToPathHash.clear(); + + //CAUTION: as saving launches an event loop, we don't want 'compilePreview' + // to be called from within 'compilePreview' + m_documentChangedTimer->blockSignals(true); + bool saveResult = m_ki->docManager()->fileSaveAll(); + m_documentChangedTimer->blockSignals(false); + // first, we have to save the documents + if(!saveResult) { + displayErrorMessage(i18n("Some documents could not be saved correctly")); + return; + } + + // document is new and hasn't been saved yet at all + if(view->document()->url().isEmpty()) { + displayErrorMessage(i18n("The document must have been saved before the live preview can be started")); + return; + } + + // first, stop any running live preview + stopLivePreview(); + + KileProject *project = Q_NULLPTR; + LivePreviewUserStatusHandler *userStatusHandler; + LaTeXOutputHandler *latexOutputHandler; + PreviewInformation *previewInformation = findPreviewInformation(latexInfo, &project, &userStatusHandler, &latexOutputHandler); + Q_ASSERT(userStatusHandler); + Q_ASSERT(latexOutputHandler); + if(!previewInformation) { + previewInformation = new PreviewInformation(); + if(!m_ki->getMasterDocumentFileName().isEmpty()) { + m_masterDocumentPreviewInformation = previewInformation; + } + else if(project) { + bool containsInvalidRelativeItem = false; + // in the case of a project, we might have to create a similar subdirectory + // structure as it is present in the real project in order for LaTeX + // to work correctly + if(!previewInformation->createSubDirectoriesForProject(project, &containsInvalidRelativeItem)) { + userStatusHandler->setLivePreviewEnabled(false); + if(containsInvalidRelativeItem) { + displayErrorMessage(i18n("The location of one project item is not relative to the project's base directory\n" + "Live preview for this project has been disabled"), true); + } + else { + displayErrorMessage(i18n("Failed to create the subdirectory structure")); + } + delete previewInformation; + disablePreview(); + return; + } + m_projectToPreviewInformationHash[project] = previewInformation; + } + else { + m_latexInfoToPreviewInformationHash[latexInfo] = previewInformation; + } + } + + connect(latexInfo, SIGNAL(aboutToBeDestroyed(KileDocument::TextInfo*)), + this, SLOT(removeLaTeXInfo(KileDocument::TextInfo*)), + Qt::UniqueConnection); + + if(project) { + handleProjectOpened(project); // create the necessary signal-slot connections + } + + updateLivePreviewToolActions(userStatusHandler); + KileTool::LivePreviewLaTeX *latex = dynamic_cast(m_ki->toolManager()->createTool(userStatusHandler->livePreviewTool(), + false)); + if(!latex) { + KILE_DEBUG_MAIN<< "couldn't create the live preview tool"; + return; + } + + // important! + latex->setPartOfLivePreview(); + connect(latex, SIGNAL(done(KileTool::Base*,int,bool)), this, SLOT(toolDone(KileTool::Base*,int,bool))); + connect(latex, SIGNAL(destroyed()), this, SLOT(toolDestroyed())); + + QFileInfo fileInfo; + const bool masterDocumentSet = !m_ki->getMasterDocumentFileName().isEmpty(); + if(masterDocumentSet) { + fileInfo = QFileInfo(m_ki->getMasterDocumentFileName()); + } + else if(project) { + fileInfo = QFileInfo(m_ki->getCompileNameForProject(project)); + } + else { + fileInfo = QFileInfo(m_ki->getCompileName()); + } + + const QString inputDir = previewInformation->getTempDir() + PATH_SEPARATOR + fileInfo.absolutePath(); + + // set value of texinput path (only for LivePreviewManager tools) + QString texInputPath = KileConfig::teXPaths(); + if(!texInputPath.isEmpty()) { + texInputPath = inputDir + PATH_SEPARATOR + texInputPath; + } + else { + texInputPath = inputDir; + } + latex->setTeXInputPaths(texInputPath); + + QString bibInputPath = KileConfig::bibInputPaths(); + if(!bibInputPath.isEmpty()) { + bibInputPath = inputDir + PATH_SEPARATOR + bibInputPath; + } + else { + bibInputPath = inputDir; + } + latex->setBibInputPaths(bibInputPath); + + QString bstInputPath = KileConfig::bstInputPaths(); + if(!bstInputPath.isEmpty()) { + bstInputPath = inputDir + PATH_SEPARATOR + bstInputPath; + } + else { + bstInputPath = inputDir; + } + latex->setBstInputPaths(bstInputPath); // m_runningPathToPreviewPathHash[fileInfo.absoluteFilePath()] = tempFile; // m_runningPreviewPathToPathHash[tempFile] = fileInfo.absoluteFilePath(); - // don't emit the 'requestSaveAll' signal + // don't emit the 'requestSaveAll' signal // latex->removeFlag(EmitSaveAllSignal); - latex->setTargetDir(previewInformation->getTempDir()); - latex->setSource(fileInfo.absoluteFilePath(), fileInfo.absolutePath()); - latex->setLaTeXOutputHandler(latexOutputHandler); + latex->setTargetDir(previewInformation->getTempDir()); + latex->setSource(fileInfo.absoluteFilePath(), fileInfo.absolutePath()); + latex->setLaTeXOutputHandler(latexOutputHandler); - latex->prepareToRun(); + latex->prepareToRun(); // latex->launcher()->setWorkingDirectory(previewInformation->getTempDir()); - KILE_DEBUG_MAIN << "dir:" << previewInformation->getTempDir(); - - m_runningTextView = view; - m_runningLaTeXInfo = latexInfo; - m_runningProject = project; - m_runningPreviewFile = previewInformation->getTempDir() + '/' + latex->target(); - m_runningTextHash.clear(); - if(masterDocumentSet) { - fillTextHashForMasterDocument(m_runningTextHash); - } - else if(project) { - fillTextHashForProject(project, m_runningTextHash); - } - else { - m_runningTextHash[latexInfo] = computeHashOfDocument(latexInfo->getDoc()); - } - m_runningPreviewInformation = previewInformation; - showPreviewRunning(); - - // finally, run the tool - m_ki->toolManager()->run(latex); + KILE_DEBUG_MAIN << "dir:" << previewInformation->getTempDir(); + + m_runningTextView = view; + m_runningLaTeXInfo = latexInfo; + m_runningProject = project; + m_runningPreviewFile = previewInformation->getTempDir() + '/' + latex->target(); + m_runningTextHash.clear(); + if(masterDocumentSet) { + fillTextHashForMasterDocument(m_runningTextHash); + } + else if(project) { + fillTextHashForProject(project, m_runningTextHash); + } + else { + m_runningTextHash[latexInfo] = computeHashOfDocument(latexInfo->getDoc()); + } + m_runningPreviewInformation = previewInformation; + showPreviewRunning(); + + // finally, run the tool + m_ki->toolManager()->run(latex); } bool LivePreviewManager::isLivePreviewActive() const { - KParts::ReadOnlyPart *viewerPart = m_ki->viewManager()->viewerPart(); + KParts::ReadOnlyPart *viewerPart = m_ki->viewManager()->viewerPart(); - return m_runningPreviewInformation - || (m_shownPreviewInformation - && viewerPart - && viewerPart->url() == QUrl::fromLocalFile(m_shownPreviewInformation->previewFile)); + return m_runningPreviewInformation + || (m_shownPreviewInformation + && viewerPart + && viewerPart->url() == QUrl::fromLocalFile(m_shownPreviewInformation->previewFile)); } bool LivePreviewManager::isLivePreviewPossible() const { - return true; + return true; } void LivePreviewManager::handleDocumentOpened(KileDocument::TextInfo *info) { - if(m_bootUpMode || !KileConfig::livePreviewEnabled()) { - return; - } - - KTextEditor::View *view = m_ki->viewManager()->currentTextView(); - if(view && view->document() == info->getDoc()) { - handleTextViewActivated(view); - } + if(m_bootUpMode || !KileConfig::livePreviewEnabled()) { + return; + } + + KTextEditor::View *view = m_ki->viewManager()->currentTextView(); + if(view && view->document() == info->getDoc()) { + handleTextViewActivated(view); + } } void LivePreviewManager::handleTextViewActivated(KTextEditor::View *view, bool clearPreview, bool forceCompilation) { - // when a file is currently being opened, we don't react to the view activation signal as the correct live preview - // tools might not be loaded yet for the document that belongs to 'view' - if(m_bootUpMode || !KileConfig::livePreviewEnabled() || m_ki->docManager()->isOpeningFile()) { - return; - } - if(clearPreview) { - stopAndClearPreview(); - } - else { - stopLivePreview(); - } - KileDocument::LaTeXInfo *latexInfo = dynamic_cast(m_ki->docManager()->textInfoFor(view->document())); - if(!latexInfo) { - return; - } - m_documentChangedTimer->stop(); - - LivePreviewUserStatusHandler *userStatusHandler = Q_NULLPTR; - findPreviewInformation(latexInfo, Q_NULLPTR, &userStatusHandler); - Q_ASSERT(userStatusHandler); - const bool livePreviewActive = userStatusHandler->isLivePreviewEnabled(); - updateLivePreviewToolActions(userStatusHandler); - // update the state of the live preview control button - m_previewForCurrentDocumentAction->setChecked(livePreviewActive); - - if(!livePreviewActive) { - disablePreview(); - } - else { - if(forceCompilation) { - compilePreview(latexInfo, view); - } - else { - showPreviewCompileIfNecessary(latexInfo, view); - } - } + // when a file is currently being opened, we don't react to the view activation signal as the correct live preview + // tools might not be loaded yet for the document that belongs to 'view' + if(m_bootUpMode || !KileConfig::livePreviewEnabled() || m_ki->docManager()->isOpeningFile()) { + return; + } + if(clearPreview) { + stopAndClearPreview(); + } + else { + stopLivePreview(); + } + KileDocument::LaTeXInfo *latexInfo = dynamic_cast(m_ki->docManager()->textInfoFor(view->document())); + if(!latexInfo) { + return; + } + m_documentChangedTimer->stop(); + + LivePreviewUserStatusHandler *userStatusHandler = Q_NULLPTR; + findPreviewInformation(latexInfo, Q_NULLPTR, &userStatusHandler); + Q_ASSERT(userStatusHandler); + const bool livePreviewActive = userStatusHandler->isLivePreviewEnabled(); + updateLivePreviewToolActions(userStatusHandler); + // update the state of the live preview control button + m_previewForCurrentDocumentAction->setChecked(livePreviewActive); + + if(!livePreviewActive) { + disablePreview(); + } + else { + if(forceCompilation) { + compilePreview(latexInfo, view); + } + else { + showPreviewCompileIfNecessary(latexInfo, view); + } + } } void LivePreviewManager::handleTextViewClosed(KTextEditor::View *view, bool wasActiveView) { - Q_UNUSED(view); - Q_UNUSED(wasActiveView); + Q_UNUSED(view); + Q_UNUSED(wasActiveView); - if(m_bootUpMode || !KileConfig::livePreviewEnabled()) { - return; - } + if(m_bootUpMode || !KileConfig::livePreviewEnabled()) { + return; + } - // check if there is still an open editor tab - if(!KTextEditor::Editor::instance()->application()->activeMainWindow()->activeView()) { - stopAndClearPreview(); - } + // check if there is still an open editor tab + if(!KTextEditor::Editor::instance()->application()->activeMainWindow()->activeView()) { + stopAndClearPreview(); + } } void LivePreviewManager::refreshLivePreview() { - KTextEditor::View *textView = m_ki->viewManager()->currentTextView(); - if(!textView) { - KILE_DEBUG_MAIN << "no text view is shown; hence, no preview can be shown"; - return; - } - handleTextViewActivated(textView, false); // don't automatically clear the preview + KTextEditor::View *textView = m_ki->viewManager()->currentTextView(); + if(!textView) { + KILE_DEBUG_MAIN << "no text view is shown; hence, no preview can be shown"; + return; + } + handleTextViewActivated(textView, false); // don't automatically clear the preview } void LivePreviewManager::recompileLivePreview() { - KTextEditor::View *textView = m_ki->viewManager()->currentTextView(); - if(!textView) { - KILE_DEBUG_MAIN << "no text view is shown; hence, no preview can be shown"; - return; - } - handleTextViewActivated(textView, false, true); // don't automatically clear the preview but force compilation + KTextEditor::View *textView = m_ki->viewManager()->currentTextView(); + if(!textView) { + KILE_DEBUG_MAIN << "no text view is shown; hence, no preview can be shown"; + return; + } + handleTextViewActivated(textView, false, true); // don't automatically clear the preview but force compilation } void LivePreviewManager::removeLaTeXInfo(KileDocument::TextInfo *textInfo) { - KileDocument::LaTeXInfo *latexInfo = dynamic_cast(textInfo); - if(!latexInfo) { - return; - } + KileDocument::LaTeXInfo *latexInfo = dynamic_cast(textInfo); + if(!latexInfo) { + return; + } - if(!m_latexInfoToPreviewInformationHash.contains(latexInfo)) { - return; // nothing to be done - } + if(!m_latexInfoToPreviewInformationHash.contains(latexInfo)) { + return; // nothing to be done + } - PreviewInformation *previewInformation = m_latexInfoToPreviewInformationHash[latexInfo]; + PreviewInformation *previewInformation = m_latexInfoToPreviewInformationHash[latexInfo]; - if(m_runningLaTeXInfo == latexInfo) { - stopLivePreview(); - } + if(m_runningLaTeXInfo == latexInfo) { + stopLivePreview(); + } - if(previewInformation == m_shownPreviewInformation) { - clearLivePreview(); - } + if(previewInformation == m_shownPreviewInformation) { + clearLivePreview(); + } - m_latexInfoToPreviewInformationHash.remove(latexInfo); - delete previewInformation; + m_latexInfoToPreviewInformationHash.remove(latexInfo); + delete previewInformation; } void LivePreviewManager::removeProject(KileProject *project) { - if(!m_projectToPreviewInformationHash.contains(project)) { - return; // nothing to be done - } + if(!m_projectToPreviewInformationHash.contains(project)) { + return; // nothing to be done + } - PreviewInformation *previewInformation = m_projectToPreviewInformationHash[project]; + PreviewInformation *previewInformation = m_projectToPreviewInformationHash[project]; - if(m_runningProject == project) { - stopLivePreview(); - } + if(m_runningProject == project) { + stopLivePreview(); + } - if(previewInformation == m_shownPreviewInformation) { - clearLivePreview(); - } + if(previewInformation == m_shownPreviewInformation) { + clearLivePreview(); + } - m_projectToPreviewInformationHash.remove(project); - delete previewInformation; + m_projectToPreviewInformationHash.remove(project); + delete previewInformation; } void LivePreviewManager::handleProjectOpened(KileProject *project) { - if(m_bootUpMode || !KileConfig::livePreviewEnabled()) { - return; - } - - connect(project, SIGNAL(aboutToBeDestroyed(KileProject*)), - this, SLOT(removeProject(KileProject*)), - Qt::UniqueConnection); - connect(project, SIGNAL(projectItemAdded(KileProject*,KileProjectItem*)), - this, SLOT(handleProjectItemAdded(KileProject*,KileProjectItem*)), - Qt::UniqueConnection); - connect(project, SIGNAL(projectItemRemoved(KileProject*,KileProjectItem*)), - this, SLOT(handleProjectItemRemoved(KileProject*,KileProjectItem*)), - Qt::UniqueConnection); + if(m_bootUpMode || !KileConfig::livePreviewEnabled()) { + return; + } + + connect(project, SIGNAL(aboutToBeDestroyed(KileProject*)), + this, SLOT(removeProject(KileProject*)), + Qt::UniqueConnection); + connect(project, SIGNAL(projectItemAdded(KileProject*,KileProjectItem*)), + this, SLOT(handleProjectItemAdded(KileProject*,KileProjectItem*)), + Qt::UniqueConnection); + connect(project, SIGNAL(projectItemRemoved(KileProject*,KileProjectItem*)), + this, SLOT(handleProjectItemRemoved(KileProject*,KileProjectItem*)), + Qt::UniqueConnection); } void LivePreviewManager::handleProjectItemAdditionOrRemoval(KileProject *project, KileProjectItem *item) { - if(m_bootUpMode || !KileConfig::livePreviewEnabled()) { - return; - } - - KILE_DEBUG_MAIN; - bool previewNeedsToBeRefreshed = false; - - // we can't use TextInfo pointers here as they might not be set in 'item' yet - KileDocument::LaTeXInfo *latexInfo = dynamic_cast(m_ki->docManager()->textInfoFor(item->url())); - if(latexInfo && m_latexInfoToPreviewInformationHash.contains(latexInfo)) { - PreviewInformation *previewInformation = m_latexInfoToPreviewInformationHash[latexInfo]; - if(previewInformation == m_shownPreviewInformation) { - previewNeedsToBeRefreshed = true; - } - removeLaTeXInfo(latexInfo); - } - - if(m_projectToPreviewInformationHash.contains(project)) { - PreviewInformation *previewInformation = m_projectToPreviewInformationHash[project]; - if(previewInformation == m_shownPreviewInformation) { - previewNeedsToBeRefreshed = true; - } - removeProject(project); - } - - // finally, check whether the currently activated text view is the 'modified' project item - if(!previewNeedsToBeRefreshed) { - KTextEditor::View *view = m_ki->viewManager()->currentTextView(); - // we can't use TextInfo pointers here as they might not be set in 'item' yet - if(view && (view->document()->url() == item->url())) { - previewNeedsToBeRefreshed = true; - } - } - - KILE_DEBUG_MAIN << "previewNeedsToBeRefreshed" << previewNeedsToBeRefreshed; - if(previewNeedsToBeRefreshed) { - // we can't do this here directly as 'item' might not be fully set up yet (e.g., if it has been added) - QTimer::singleShot(0, this, SLOT(refreshLivePreview())); - } + if(m_bootUpMode || !KileConfig::livePreviewEnabled()) { + return; + } + + KILE_DEBUG_MAIN; + bool previewNeedsToBeRefreshed = false; + + // we can't use TextInfo pointers here as they might not be set in 'item' yet + KileDocument::LaTeXInfo *latexInfo = dynamic_cast(m_ki->docManager()->textInfoFor(item->url())); + if(latexInfo && m_latexInfoToPreviewInformationHash.contains(latexInfo)) { + PreviewInformation *previewInformation = m_latexInfoToPreviewInformationHash[latexInfo]; + if(previewInformation == m_shownPreviewInformation) { + previewNeedsToBeRefreshed = true; + } + removeLaTeXInfo(latexInfo); + } + + if(m_projectToPreviewInformationHash.contains(project)) { + PreviewInformation *previewInformation = m_projectToPreviewInformationHash[project]; + if(previewInformation == m_shownPreviewInformation) { + previewNeedsToBeRefreshed = true; + } + removeProject(project); + } + + // finally, check whether the currently activated text view is the 'modified' project item + if(!previewNeedsToBeRefreshed) { + KTextEditor::View *view = m_ki->viewManager()->currentTextView(); + // we can't use TextInfo pointers here as they might not be set in 'item' yet + if(view && (view->document()->url() == item->url())) { + previewNeedsToBeRefreshed = true; + } + } + + KILE_DEBUG_MAIN << "previewNeedsToBeRefreshed" << previewNeedsToBeRefreshed; + if(previewNeedsToBeRefreshed) { + // we can't do this here directly as 'item' might not be fully set up yet (e.g., if it has been added) + QTimer::singleShot(0, this, SLOT(refreshLivePreview())); + } } void LivePreviewManager::handleProjectItemAdded(KileProject *project, KileProjectItem *item) { - if(m_bootUpMode || !KileConfig::livePreviewEnabled()) { - return; - } - KILE_DEBUG_MAIN; - - // the directory structure in the temporary directory will be updated when - // 'compilePreview' is called; 'handleProjectItemAdditionOrRemoval' will delete - // PreviewInformation objects - handleProjectItemAdditionOrRemoval(project, item); + if(m_bootUpMode || !KileConfig::livePreviewEnabled()) { + return; + } + KILE_DEBUG_MAIN; + + // the directory structure in the temporary directory will be updated when + // 'compilePreview' is called; 'handleProjectItemAdditionOrRemoval' will delete + // PreviewInformation objects + handleProjectItemAdditionOrRemoval(project, item); } void LivePreviewManager::handleProjectItemRemoved(KileProject *project, KileProjectItem *item) { - if(m_bootUpMode || !KileConfig::livePreviewEnabled()) { - return; - } + if(m_bootUpMode || !KileConfig::livePreviewEnabled()) { + return; + } - KILE_DEBUG_MAIN; - handleProjectItemAdditionOrRemoval(project, item); + KILE_DEBUG_MAIN; + handleProjectItemAdditionOrRemoval(project, item); } void LivePreviewManager::handleDocumentSavedAs(KTextEditor::View *view, KileDocument::TextInfo *info) { - Q_UNUSED(info); - - if(m_bootUpMode || !KileConfig::livePreviewEnabled()) { - return; - } - - KTextEditor::View *currentTextView = m_ki->viewManager()->currentTextView(); - if(view != currentTextView) { // might maybe happen at some point... - // preview will be refreshed the next time that view is activated as the hashes don't - // match anymore - return; - } - refreshLivePreview(); + Q_UNUSED(info); + + if(m_bootUpMode || !KileConfig::livePreviewEnabled()) { + return; + } + + KTextEditor::View *currentTextView = m_ki->viewManager()->currentTextView(); + if(view != currentTextView) { // might maybe happen at some point... + // preview will be refreshed the next time that view is activated as the hashes don't + // match anymore + return; + } + refreshLivePreview(); } void LivePreviewManager::toolDestroyed() { - KILE_DEBUG_MAIN << "\tLivePreviewManager: tool destroyed" << endl; + KILE_DEBUG_MAIN << "\tLivePreviewManager: tool destroyed" << endl; } void LivePreviewManager::handleSpawnedChildTool(KileTool::Base *parent, KileTool::Base *child) { - Q_UNUSED(parent); + Q_UNUSED(parent); - if(m_bootUpMode || !KileConfig::livePreviewEnabled()) { - return; - } + if(m_bootUpMode || !KileConfig::livePreviewEnabled()) { + return; + } - KILE_DEBUG_MAIN; - // only connect the signal for tools that are part of live preview! - if(parent->isPartOfLivePreview()) { - connect(child, SIGNAL(done(KileTool::Base*,int,bool)), this, SLOT(childToolDone(KileTool::Base*,int,bool))); - } + KILE_DEBUG_MAIN; + // only connect the signal for tools that are part of live preview! + if(parent->isPartOfLivePreview()) { + connect(child, SIGNAL(done(KileTool::Base*,int,bool)), this, SLOT(childToolDone(KileTool::Base*,int,bool))); + } } void LivePreviewManager::toolDone(KileTool::Base *base, int i, bool childToolSpawned) { - KILE_DEBUG_MAIN << "\t!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!" << i << endl; - KILE_DEBUG_MAIN << "\t!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!" << i << endl; - KILE_DEBUG_MAIN << "\tLivePreviewManager: tool done" << base->name() << i << childToolSpawned << endl; - if(i != Success) { - KILE_DEBUG_MAIN << "tool didn't return successfully, doing nothing"; - showPreviewFailed(); - clearRunningLivePreviewInformation(); - } - // a LaTeX variant must have finished for the preview to be complete - else if(!childToolSpawned && dynamic_cast(base)) { - updatePreviewInformationAfterCompilationFinished(); - clearRunningLivePreviewInformation(); - } + KILE_DEBUG_MAIN << "\t!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!" << i << endl; + KILE_DEBUG_MAIN << "\t!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!" << i << endl; + KILE_DEBUG_MAIN << "\tLivePreviewManager: tool done" << base->name() << i << childToolSpawned << endl; + if(i != Success) { + KILE_DEBUG_MAIN << "tool didn't return successfully, doing nothing"; + showPreviewFailed(); + clearRunningLivePreviewInformation(); + } + // a LaTeX variant must have finished for the preview to be complete + else if(!childToolSpawned && dynamic_cast(base)) { + updatePreviewInformationAfterCompilationFinished(); + clearRunningLivePreviewInformation(); + } } void LivePreviewManager::childToolDone(KileTool::Base *base, int i, bool childToolSpawned) { - KILE_DEBUG_MAIN << "\t!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!" << i << endl; - KILE_DEBUG_MAIN << "\t!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!" << i << endl; - KILE_DEBUG_MAIN << "\tLivePreviewManager: child tool done" << base->name() << i << childToolSpawned << endl; - if(!m_ki->viewManager()->viewerPart()) { - return; - } - if(i != Success) { - KILE_DEBUG_MAIN << "tool didn't return successfully, doing nothing"; - showPreviewFailed(); - clearRunningLivePreviewInformation(); - } - // a LaTeX variant must have finished for the preview to be complete - else if(!childToolSpawned && dynamic_cast(base)) { - updatePreviewInformationAfterCompilationFinished(); - clearRunningLivePreviewInformation(); - } + KILE_DEBUG_MAIN << "\t!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!" << i << endl; + KILE_DEBUG_MAIN << "\t!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!" << i << endl; + KILE_DEBUG_MAIN << "\tLivePreviewManager: child tool done" << base->name() << i << childToolSpawned << endl; + if(!m_ki->viewManager()->viewerPart()) { + return; + } + if(i != Success) { + KILE_DEBUG_MAIN << "tool didn't return successfully, doing nothing"; + showPreviewFailed(); + clearRunningLivePreviewInformation(); + } + // a LaTeX variant must have finished for the preview to be complete + else if(!childToolSpawned && dynamic_cast(base)) { + updatePreviewInformationAfterCompilationFinished(); + clearRunningLivePreviewInformation(); + } } void LivePreviewManager::updatePreviewInformationAfterCompilationFinished() { - if(!m_runningPreviewInformation) { // LivePreview has been stopped in the meantime - return; - } - - m_shownPreviewInformation = m_runningPreviewInformation; - m_shownPreviewInformation->pathToPreviewPathHash = m_runningPathToPreviewPathHash; - m_shownPreviewInformation->previewPathToPathHash = m_runningPreviewPathToPathHash; - m_shownPreviewInformation->textHash = m_runningTextHash; - m_shownPreviewInformation->previewFile = m_runningPreviewFile; - - bool hadToOpen = false; - if(!ensureDocumentIsOpenInViewer(m_shownPreviewInformation, &hadToOpen)) { - clearLivePreview(); - // must happen after the call to 'clearLivePreview' only - showPreviewFailed(); - return; - } - - // as 'ensureDocumentIsOpenInViewer' won't reload when the document is open - // already, we have to do it here - if(!hadToOpen) { - reloadDocumentInViewer(); - } - - if(m_ki->viewManager()->isSynchronisingCursorWithDocumentViewer()) { - synchronizeViewWithCursor(m_runningLaTeXInfo, m_runningTextView, m_runningTextView->cursorPosition()); - } - - showPreviewSuccessful(); + if(!m_runningPreviewInformation) { // LivePreview has been stopped in the meantime + return; + } + + m_shownPreviewInformation = m_runningPreviewInformation; + m_shownPreviewInformation->pathToPreviewPathHash = m_runningPathToPreviewPathHash; + m_shownPreviewInformation->previewPathToPathHash = m_runningPreviewPathToPathHash; + m_shownPreviewInformation->textHash = m_runningTextHash; + m_shownPreviewInformation->previewFile = m_runningPreviewFile; + + bool hadToOpen = false; + if(!ensureDocumentIsOpenInViewer(m_shownPreviewInformation, &hadToOpen)) { + clearLivePreview(); + // must happen after the call to 'clearLivePreview' only + showPreviewFailed(); + return; + } + + // as 'ensureDocumentIsOpenInViewer' won't reload when the document is open + // already, we have to do it here + if(!hadToOpen) { + reloadDocumentInViewer(); + } + + if(m_ki->viewManager()->isSynchronisingCursorWithDocumentViewer()) { + synchronizeViewWithCursor(m_runningLaTeXInfo, m_runningTextView, m_runningTextView->cursorPosition()); + } + + showPreviewSuccessful(); } void LivePreviewManager::displayErrorMessage(const QString &text, bool clearFirst) { - if(clearFirst) { - m_ki->errorHandler()->clearMessages(); - } - m_ki->errorHandler()->printMessage(KileTool::Error, text, i18n("LivePreview")); + if(clearFirst) { + m_ki->errorHandler()->clearMessages(); + } + m_ki->errorHandler()->printMessage(KileTool::Error, text, i18n("LivePreview")); } } diff --git a/src/livepreview.h b/src/livepreview.h index bc36fde8..35eda005 100644 --- a/src/livepreview.h +++ b/src/livepreview.h @@ -1,184 +1,186 @@ /******************************************************************************** Copyright (C) 2011-2017 by Michel Ludwig (michel.ludwig@kdemail.net) ********************************************************************************/ /*************************************************************************** * * * 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. * * * ***************************************************************************/ #ifndef LIVEPREVIEW_H #define LIVEPREVIEW_H #include "documentinfo.h" #include "kileinfo.h" #include "kileproject.h" #include "kiletool.h" #include "editorextension.h" #include "widgets/previewwidget.h" #include #include #include #include #include #include #include #include #include -namespace KileDocument { class TextInfo; } +namespace KileDocument { +class TextInfo; +} namespace KileTool { class LivePreviewManager : public QObject { - Q_OBJECT + Q_OBJECT public: - // has to be instatiated after the view manager only! - LivePreviewManager(KileInfo *ki, KActionCollection *ac); - ~LivePreviewManager(); + // has to be instatiated after the view manager only! + LivePreviewManager(KileInfo *ki, KActionCollection *ac); + ~LivePreviewManager(); - // live preview won't be run in 'boot up' mode, which is enabled by default - void disableBootUpMode(); + // live preview won't be run in 'boot up' mode, which is enabled by default + void disableBootUpMode(); - void readConfig(KConfig *config); - void writeConfig(); - static void readLivePreviewStatusSettings(KConfigGroup &configGroup, LivePreviewUserStatusHandler *handler); - static void writeLivePreviewStatusSettings(KConfigGroup &configGroup, LivePreviewUserStatusHandler *handler); + void readConfig(KConfig *config); + void writeConfig(); + static void readLivePreviewStatusSettings(KConfigGroup &configGroup, LivePreviewUserStatusHandler *handler); + static void writeLivePreviewStatusSettings(KConfigGroup &configGroup, LivePreviewUserStatusHandler *handler); - void compilePreview(KileDocument::LaTeXInfo *info, KTextEditor::View *view); - void showPreviewCompileIfNecessary(KileDocument::LaTeXInfo *info, KTextEditor::View *view); + void compilePreview(KileDocument::LaTeXInfo *info, KTextEditor::View *view); + void showPreviewCompileIfNecessary(KileDocument::LaTeXInfo *info, KTextEditor::View *view); - bool isLivePreviewActive() const; - bool isLivePreviewPossible() const; + bool isLivePreviewActive() const; + bool isLivePreviewPossible() const; - bool isLivePreviewEnabledForCurrentDocument(); - void setLivePreviewEnabledForCurrentDocument(bool b); + bool isLivePreviewEnabledForCurrentDocument(); + void setLivePreviewEnabledForCurrentDocument(bool b); - void buildLivePreviewMenu(KConfig *config); + void buildLivePreviewMenu(KConfig *config); public Q_SLOTS: - void handleTextChanged(KTextEditor::Document *doc); - void handleDocumentSavedOrUploaded(KTextEditor::Document *doc, bool savedAs); + void handleTextChanged(KTextEditor::Document *doc); + void handleDocumentSavedOrUploaded(KTextEditor::Document *doc, bool savedAs); - void handleMasterDocumentChanged(); + void handleMasterDocumentChanged(); - void recompileLivePreview(); - void refreshLivePreview(); + void recompileLivePreview(); + void refreshLivePreview(); - void showCursorPositionInDocumentViewer(); + void showCursorPositionInDocumentViewer(); private Q_SLOTS: - void handleDocumentModificationTimerTimeout(); + void handleDocumentModificationTimerTimeout(); - // TextInfo* object due to the signal 'aboutToBeDestroyed(KileDocument::TextInfo*)' - void removeLaTeXInfo(KileDocument::TextInfo *info); - void removeProject(KileProject *project); + // TextInfo* object due to the signal 'aboutToBeDestroyed(KileDocument::TextInfo*)' + void removeLaTeXInfo(KileDocument::TextInfo *info); + void removeProject(KileProject *project); - void toolDestroyed(); - void toolDone(KileTool::Base *base, int i, bool childToolSpawned); - void childToolDone(KileTool::Base *base, int i, bool childToolSpawned); + void toolDestroyed(); + void toolDone(KileTool::Base *base, int i, bool childToolSpawned); + void childToolDone(KileTool::Base *base, int i, bool childToolSpawned); - void handleTextViewActivated(KTextEditor::View *view, bool clearPreview = true, bool forceCompilation = false); - void handleTextViewClosed(KTextEditor::View *view, bool wasActiveView); + void handleTextViewActivated(KTextEditor::View *view, bool clearPreview = true, bool forceCompilation = false); + void handleTextViewClosed(KTextEditor::View *view, bool wasActiveView); - void handleDocumentOpened(KileDocument::TextInfo *info); + void handleDocumentOpened(KileDocument::TextInfo *info); - void handleProjectOpened(KileProject *project); - void handleProjectItemAdded(KileProject *project, KileProjectItem *item); - void handleProjectItemRemoved(KileProject *project, KileProjectItem *item); + void handleProjectOpened(KileProject *project); + void handleProjectItemAdded(KileProject *project, KileProjectItem *item); + void handleProjectItemRemoved(KileProject *project, KileProjectItem *item); - void handleDocumentSavedAs(KTextEditor::View*, KileDocument::TextInfo*); + void handleDocumentSavedAs(KTextEditor::View*, KileDocument::TextInfo*); - void handleSpawnedChildTool(KileTool::Base *parent, KileTool::Base *child); + void handleSpawnedChildTool(KileTool::Base *parent, KileTool::Base *child); - void previewForCurrentDocumentActionTriggered(bool b); + void previewForCurrentDocumentActionTriggered(bool b); - void livePreviewToolActionTriggered(); + void livePreviewToolActionTriggered(); private: - class PreviewInformation; + class PreviewInformation; - KileInfo *m_ki; - bool m_bootUpMode; - QPointer m_previewStatusLed; - KToggleAction *m_previewForCurrentDocumentAction; - QAction *m_recompileLivePreviewAction; - QTimer *m_ledBlinkingTimer, *m_documentChangedTimer; + KileInfo *m_ki; + bool m_bootUpMode; + QPointer m_previewStatusLed; + KToggleAction *m_previewForCurrentDocumentAction; + QAction *m_recompileLivePreviewAction; + QTimer *m_ledBlinkingTimer, *m_documentChangedTimer; - QHash m_runningPathToPreviewPathHash; - QHash m_runningPreviewPathToPathHash; - QString m_runningPreviewFile; - KileDocument::LaTeXInfo *m_runningLaTeXInfo; - KTextEditor::View *m_runningTextView; - KileProject *m_runningProject; - PreviewInformation *m_runningPreviewInformation; - QHash m_runningTextHash; + QHash m_runningPathToPreviewPathHash; + QHash m_runningPreviewPathToPathHash; + QString m_runningPreviewFile; + KileDocument::LaTeXInfo *m_runningLaTeXInfo; + KTextEditor::View *m_runningTextView; + KileProject *m_runningProject; + PreviewInformation *m_runningPreviewInformation; + QHash m_runningTextHash; - PreviewInformation *m_shownPreviewInformation; + PreviewInformation *m_shownPreviewInformation; - QHash m_latexInfoToPreviewInformationHash; - QHash m_projectToPreviewInformationHash; - PreviewInformation *m_masterDocumentPreviewInformation; + QHash m_latexInfoToPreviewInformationHash; + QHash m_projectToPreviewInformationHash; + PreviewInformation *m_masterDocumentPreviewInformation; - // all the members required to handle tool actions for live preview - QHash m_livePreviewToolToActionHash; - QHash m_actionToLivePreviewToolHash; - QActionGroup *m_livePreviewToolActionGroup; - QLinkedList m_livePreviewToolActionList; + // all the members required to handle tool actions for live preview + QHash m_livePreviewToolToActionHash; + QHash m_actionToLivePreviewToolHash; + QActionGroup *m_livePreviewToolActionGroup; + QLinkedList m_livePreviewToolActionList; - PreviewInformation* findPreviewInformation(KileDocument::TextInfo *textInfo, KileProject* *locatedProject = Q_NULLPTR, - LivePreviewUserStatusHandler* *userStatusHandler = Q_NULLPTR, - LaTeXOutputHandler* *latexOutputHandler = Q_NULLPTR); - bool isCurrentDocumentOrProject(KTextEditor::Document *doc); + PreviewInformation* findPreviewInformation(KileDocument::TextInfo *textInfo, KileProject* *locatedProject = Q_NULLPTR, + LivePreviewUserStatusHandler* *userStatusHandler = Q_NULLPTR, + LaTeXOutputHandler* *latexOutputHandler = Q_NULLPTR); + bool isCurrentDocumentOrProject(KTextEditor::Document *doc); - void updatePreviewInformationAfterCompilationFinished(); + void updatePreviewInformationAfterCompilationFinished(); - void displayErrorMessage(const QString &text, bool clearFirst = false); + void displayErrorMessage(const QString &text, bool clearFirst = false); - void createActions(KActionCollection *ac); - void populateViewerControlToolBar(); - void synchronizeViewWithCursor(KileDocument::TextInfo *info, KTextEditor::View *view, - const KTextEditor::Cursor& newPosition, - bool calledFromCursorPositionChange = false); + void createActions(KActionCollection *ac); + void populateViewerControlToolBar(); + void synchronizeViewWithCursor(KileDocument::TextInfo *info, KTextEditor::View *view, + const KTextEditor::Cursor& newPosition, + bool calledFromCursorPositionChange = false); - void stopAndClearPreview(); + void stopAndClearPreview(); - void showPreviewDisabled(); - void showPreviewRunning(); - void showPreviewFailed(); - void showPreviewSuccessful(); - void showPreviewOutOfDate(); + void showPreviewDisabled(); + void showPreviewRunning(); + void showPreviewFailed(); + void showPreviewSuccessful(); + void showPreviewOutOfDate(); - void stopLivePreview(); - void clearLivePreview(); + void stopLivePreview(); + void clearLivePreview(); - void deleteAllLivePreviewInformation(); + void deleteAllLivePreviewInformation(); - void handleProjectItemAdditionOrRemoval(KileProject *project, KileProjectItem *item); + void handleProjectItemAdditionOrRemoval(KileProject *project, KileProjectItem *item); - void fillTextHashForMasterDocument(QHash &textHash); + void fillTextHashForMasterDocument(QHash &textHash); - void disablePreview(); + void disablePreview(); - void clearRunningLivePreviewInformation(); + void clearRunningLivePreviewInformation(); - void updateLivePreviewToolActions(LivePreviewUserStatusHandler *statusHandler); - void setLivePreviewToolActionsEnabled(bool b); + void updateLivePreviewToolActions(LivePreviewUserStatusHandler *statusHandler); + void setLivePreviewToolActionsEnabled(bool b); - bool ensureDocumentIsOpenInViewer(PreviewInformation *previewInformation, bool *hadToOpen = Q_NULLPTR); - void reloadDocumentInViewer(); + bool ensureDocumentIsOpenInViewer(PreviewInformation *previewInformation, bool *hadToOpen = Q_NULLPTR); + void reloadDocumentInViewer(); }; } #endif diff --git a/src/livepreview_utils.cpp b/src/livepreview_utils.cpp index 5ed5d0db..7c70f302 100644 --- a/src/livepreview_utils.cpp +++ b/src/livepreview_utils.cpp @@ -1,57 +1,57 @@ /******************************************************************************** Copyright (C) 2012 by Michel Ludwig (michel.ludwig@kdemail.net) ********************************************************************************/ /*************************************************************************** * * * 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. * * * ***************************************************************************/ #include "livepreview_utils.h" #include "kileconfig.h" namespace KileTool { LivePreviewUserStatusHandler::LivePreviewUserStatusHandler() -: m_userSpecifiedLivePreviewStatus(false), - m_livePreviewEnabled(true), - m_livePreviewTool(LIVEPREVIEW_DEFAULT_TOOL_NAME, DEFAULT_TOOL_CONFIGURATION) + : m_userSpecifiedLivePreviewStatus(false), + m_livePreviewEnabled(true), + m_livePreviewTool(LIVEPREVIEW_DEFAULT_TOOL_NAME, DEFAULT_TOOL_CONFIGURATION) { } bool LivePreviewUserStatusHandler::userSpecifiedLivePreviewStatus() const { - return m_userSpecifiedLivePreviewStatus; + return m_userSpecifiedLivePreviewStatus; } bool LivePreviewUserStatusHandler::isLivePreviewEnabled() const { - return (m_userSpecifiedLivePreviewStatus ? m_livePreviewEnabled : KileConfig::previewEnabledForFreshlyOpenedDocuments()); + return (m_userSpecifiedLivePreviewStatus ? m_livePreviewEnabled : KileConfig::previewEnabledForFreshlyOpenedDocuments()); } void LivePreviewUserStatusHandler::setLivePreviewEnabled(bool b) { - m_userSpecifiedLivePreviewStatus = true; - m_livePreviewEnabled = b; + m_userSpecifiedLivePreviewStatus = true; + m_livePreviewEnabled = b; } ToolConfigPair LivePreviewUserStatusHandler::livePreviewTool() const { - return m_livePreviewTool; + return m_livePreviewTool; } bool LivePreviewUserStatusHandler::setLivePreviewTool(const ToolConfigPair& p) { - if(m_livePreviewTool == p) { - return false; - } - m_livePreviewTool = p; - return true; + if(m_livePreviewTool == p) { + return false; + } + m_livePreviewTool = p; + return true; } } diff --git a/src/livepreview_utils.h b/src/livepreview_utils.h index 057f7670..79c1552a 100644 --- a/src/livepreview_utils.h +++ b/src/livepreview_utils.h @@ -1,46 +1,46 @@ /******************************************************************************** Copyright (C) 2012 by Michel Ludwig (michel.ludwig@kdemail.net) ********************************************************************************/ /*************************************************************************** * * * 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. * * * ***************************************************************************/ #ifndef LIVEPREVIEW_UTILS_H #define LIVEPREVIEW_UTILS_H #include #include "tool_utils.h" #define LIVEPREVIEW_DEFAULT_TOOL_NAME "LivePreview-PDFLaTeX" namespace KileTool { class LivePreviewUserStatusHandler { public: - LivePreviewUserStatusHandler(); + LivePreviewUserStatusHandler(); - bool userSpecifiedLivePreviewStatus() const; - bool isLivePreviewEnabled() const; - void setLivePreviewEnabled(bool b); + bool userSpecifiedLivePreviewStatus() const; + bool isLivePreviewEnabled() const; + void setLivePreviewEnabled(bool b); - ToolConfigPair livePreviewTool() const; - // returns 'true' iff the live preview type has changed - bool setLivePreviewTool(const ToolConfigPair& p); + ToolConfigPair livePreviewTool() const; + // returns 'true' iff the live preview type has changed + bool setLivePreviewTool(const ToolConfigPair& p); private: - bool m_userSpecifiedLivePreviewStatus; - bool m_livePreviewEnabled; - ToolConfigPair m_livePreviewTool; + bool m_userSpecifiedLivePreviewStatus; + bool m_livePreviewEnabled; + ToolConfigPair m_livePreviewTool; }; } #endif diff --git a/src/main.cpp b/src/main.cpp index 9966cf81..bd1d2f60 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -1,213 +1,215 @@ /******************************************************************************************** begin : sam jui 13 09:50:06 CEST 2002 copyright : (C) 2002 - 2003 by Pascal Brachet 2003 - 2005 by Jeroen Wijnhout (Jeroen.Wijnhout@kdemail.net) 2011 - 2016 by Michel Ludwig (michel.ludwig@kdemail.net) ********************************************************************************************/ /*************************************************************************** * * * 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. * * * ***************************************************************************/ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "kile.h" #include "kileversion.h" #include "kiledebug.h" Q_LOGGING_CATEGORY(LOG_KILE_MAIN, "org.kde.kile.main", QtWarningMsg) Q_LOGGING_CATEGORY(LOG_KILE_PARSER, "org.kde.kile.parser", QtWarningMsg) Q_LOGGING_CATEGORY(LOG_KILE_CODECOMPLETION, "org.kde.kile.codecompletion", QtWarningMsg) bool isProject(const QUrl url) { - return url.fileName().endsWith(".kilepr"); + return url.fileName().endsWith(".kilepr"); } QString readDataFromStdin() { - KILE_DEBUG_MAIN; + KILE_DEBUG_MAIN; - QByteArray fileData; - QFile qstdin; - QTextCodec *codec = Q_NULLPTR; + QByteArray fileData; + QFile qstdin; + QTextCodec *codec = Q_NULLPTR; - qstdin.open( stdin, QIODevice::ReadOnly ); - fileData = qstdin.readAll(); - qstdin.close(); + qstdin.open( stdin, QIODevice::ReadOnly ); + fileData = qstdin.readAll(); + qstdin.close(); - QTemporaryDir *tempDir = new QTemporaryDir(QDir::tempPath() + QLatin1Char('/') + "kile-stdin"); - QString tempFileName = QFileInfo(tempDir->path(), i18n("StandardInput.tex")).absoluteFilePath(); - KILE_DEBUG_MAIN << "tempFile is " << tempFileName; + QTemporaryDir *tempDir = new QTemporaryDir(QDir::tempPath() + QLatin1Char('/') + "kile-stdin"); + QString tempFileName = QFileInfo(tempDir->path(), i18n("StandardInput.tex")).absoluteFilePath(); + KILE_DEBUG_MAIN << "tempFile is " << tempFileName; - QFile tempFile(tempFileName); - if(!tempFile.open(QIODevice::WriteOnly)) { - return QString(); - } + QFile tempFile(tempFileName); + if(!tempFile.open(QIODevice::WriteOnly)) { + return QString(); + } - QTextStream stream(&tempFile); + QTextStream stream(&tempFile); - KEncodingProber prober(KEncodingProber::Universal); - KEncodingProber::ProberState state = prober.feed(fileData); - KILE_DEBUG_MAIN << "KEncodingProber::state " << state; - KILE_DEBUG_MAIN << "KEncodingProber::prober.confidence() " << prober.confidence(); - KILE_DEBUG_MAIN << "KEncodingProber::encoding " << prober.encoding(); + KEncodingProber prober(KEncodingProber::Universal); + KEncodingProber::ProberState state = prober.feed(fileData); + KILE_DEBUG_MAIN << "KEncodingProber::state " << state; + KILE_DEBUG_MAIN << "KEncodingProber::prober.confidence() " << prober.confidence(); + KILE_DEBUG_MAIN << "KEncodingProber::encoding " << prober.encoding(); - codec = QTextCodec::codecForName(prober.encoding()); - if(codec){ - stream.setCodec(codec); - } + codec = QTextCodec::codecForName(prober.encoding()); + if(codec) { + stream.setCodec(codec); + } - stream << fileData; - tempFile.close(); + stream << fileData; + tempFile.close(); - return tempFileName; + return tempFileName; } -inline void initQtResources() { Q_INIT_RESOURCE(kile); } +inline void initQtResources() { + Q_INIT_RESOURCE(kile); +} extern "C" Q_DECL_EXPORT int kdemain(int argc, char **argv) { - KLocalizedString::setApplicationDomain("kile"); + KLocalizedString::setApplicationDomain("kile"); - QApplication app(argc, argv); + QApplication app(argc, argv); - initQtResources(); + initQtResources(); - // enable high dpi support - app.setAttribute(Qt::AA_UseHighDpiPixmaps, true); + // enable high dpi support + app.setAttribute(Qt::AA_UseHighDpiPixmaps, true); - KAboutData aboutData("kile", i18n("Kile"), kileFullVersion.toLatin1(), - i18n("KDE Integrated LaTeX Environment"), - KAboutLicense::GPL, - i18nc("the parameter is the last copyright year", "by the Kile Team (2003 - %1)", KILE_LAST_COPYRIGHT_YEAR), - QString(), - QStringLiteral("http://kile.sourceforge.net")); - aboutData.addAuthor(i18n("Michel Ludwig"), i18n("Project Management/Developer"), "michel.ludwig@kdemail.net"); - aboutData.addAuthor(i18n("Holger Danielsson"), i18n("Developer"), "holger.danielsson@versanet.de"); - aboutData.addAuthor(i18n("Thomas Braun"), i18n("Former Developer"), "thomas.braun@virtuell-zuhause.de"); - aboutData.addAuthor(i18n("Jeroen Wijnhout"), i18n("Former Maintainer/Developer"),"Jeroen.Wijnhout@kdemail.net"); - aboutData.addAuthor(i18n("Brachet Pascal")); + KAboutData aboutData("kile", i18n("Kile"), kileFullVersion.toLatin1(), + i18n("KDE Integrated LaTeX Environment"), + KAboutLicense::GPL, + i18nc("the parameter is the last copyright year", "by the Kile Team (2003 - %1)", KILE_LAST_COPYRIGHT_YEAR), + QString(), + QStringLiteral("http://kile.sourceforge.net")); + aboutData.addAuthor(i18n("Michel Ludwig"), i18n("Project Management/Developer"), "michel.ludwig@kdemail.net"); + aboutData.addAuthor(i18n("Holger Danielsson"), i18n("Developer"), "holger.danielsson@versanet.de"); + aboutData.addAuthor(i18n("Thomas Braun"), i18n("Former Developer"), "thomas.braun@virtuell-zuhause.de"); + aboutData.addAuthor(i18n("Jeroen Wijnhout"), i18n("Former Maintainer/Developer"),"Jeroen.Wijnhout@kdemail.net"); + aboutData.addAuthor(i18n("Brachet Pascal")); - aboutData.addCredit(i18n("Andrius Å tikonas"), i18n("Migration from Subversion to Git"), "andrius@stikonas.eu"); - aboutData.addCredit(i18n("Simon Martin"), i18n("KConfig XT, Various Improvements and Bug-Fixing")); - aboutData.addCredit(i18n("Roland Schulz"), i18n("KatePart Integration")); - aboutData.addCredit(i18n("Thorsten Lück"), i18n("Log Parsing")); - aboutData.addCredit(i18n("Jan-Marek Glogowski"), i18n("Find-in-Files Dialog")); - aboutData.addCredit(i18n("Jonathan Pechta"), i18n("Documentation")); - aboutData.addCredit(i18n("Federico Zenith"), i18n("Documentation")); + aboutData.addCredit(i18n("Andrius Å tikonas"), i18n("Migration from Subversion to Git"), "andrius@stikonas.eu"); + aboutData.addCredit(i18n("Simon Martin"), i18n("KConfig XT, Various Improvements and Bug-Fixing")); + aboutData.addCredit(i18n("Roland Schulz"), i18n("KatePart Integration")); + aboutData.addCredit(i18n("Thorsten Lück"), i18n("Log Parsing")); + aboutData.addCredit(i18n("Jan-Marek Glogowski"), i18n("Find-in-Files Dialog")); + aboutData.addCredit(i18n("Jonathan Pechta"), i18n("Documentation")); + aboutData.addCredit(i18n("Federico Zenith"), i18n("Documentation")); - aboutData.setOrganizationDomain(QByteArray("kde.org")); - aboutData.setDesktopFileName(QStringLiteral("org.kde.kile")); + aboutData.setOrganizationDomain(QByteArray("kde.org")); + aboutData.setDesktopFileName(QStringLiteral("org.kde.kile")); - aboutData.setProductName(QByteArray("kile")); + aboutData.setProductName(QByteArray("kile")); - KAboutData::setApplicationData(aboutData); + KAboutData::setApplicationData(aboutData); - app.setApplicationName(aboutData.componentName()); - app.setApplicationDisplayName(aboutData.displayName()); - app.setOrganizationDomain(aboutData.organizationDomain()); - app.setApplicationVersion(aboutData.version()); + app.setApplicationName(aboutData.componentName()); + app.setApplicationDisplayName(aboutData.displayName()); + app.setOrganizationDomain(aboutData.organizationDomain()); + app.setApplicationVersion(aboutData.version()); - QCommandLineParser parser; - aboutData.setupCommandLine(&parser); + QCommandLineParser parser; + aboutData.setupCommandLine(&parser); - parser.addOption(QCommandLineOption(QStringList() << QLatin1String("line"), i18n("Jump to line"), QLatin1String("line"))); - parser.addOption(QCommandLineOption(QStringList() << QLatin1String("new"), i18n("Start a new Kile mainwindow"))); + parser.addOption(QCommandLineOption(QStringList() << QLatin1String("line"), i18n("Jump to line"), QLatin1String("line"))); + parser.addOption(QCommandLineOption(QStringList() << QLatin1String("new"), i18n("Start a new Kile mainwindow"))); //TODO KF5 VERIFY THAT '-' STILL WORKS - parser.addPositionalArgument("urls", i18n("Files to open / specify '-' to read from standard input"), QLatin1String("[urls...]")); - - parser.process(app); - aboutData.processCommandLine(&parser); - - app.setApplicationName(aboutData.componentName()); - app.setApplicationDisplayName(aboutData.displayName()); - app.setOrganizationDomain(aboutData.organizationDomain()); - app.setApplicationVersion(aboutData.version()); - - - bool running = false; - - const KDBusService dbusService(KDBusService::Multiple | KDBusService::NoExitOnFailure); - - QDBusConnection dbus = QDBusConnection::sessionBus(); - running = dbus.interface()->isServiceRegistered("net.sourceforge.kile"); - - if(!running || parser.isSet("new")) { - bool restore = (parser.positionalArguments().count() == 0); - - Kile *kile = new Kile(restore); - - Q_FOREACH(QString argument, parser.positionalArguments()) { - if(argument == "-") { - kile->openDocument(readDataFromStdin()); - } - else { - const QUrl url = QUrl::fromUserInput(argument, QDir::currentPath(), QUrl::AssumeLocalFile); - - if(isProject(url)) { - kile->openProject(url); - } - else { - kile->openDocument(url); - } - } - } - - if(parser.isSet("line")){ - QString line = parser.value("line"); - kile->setLine(line); - } - - return app.exec(); - } - else { - QDBusInterface *interface = new QDBusInterface("net.sourceforge.kile","/main","net.sourceforge.kile.main"); - - Q_FOREACH(QString argument, parser.positionalArguments()) { - if(argument == "-") { - interface->call("openDocument", readDataFromStdin()); - } - else { - const QUrl url = QUrl::fromUserInput(argument, QDir::currentPath(), QUrl::AssumeLocalFile); - - if(isProject(url)) { - interface->call("openProject", url.url()); - } - else { - interface->call("openDocument", url.url()); - } - } - } - - if(parser.isSet("line")){ - QString line = parser.value("line"); - interface->call("setLine", line); - } - - KStartupInfo::appStarted(); - interface->call("setActive"); - delete interface; - } - - return EXIT_SUCCESS; + parser.addPositionalArgument("urls", i18n("Files to open / specify '-' to read from standard input"), QLatin1String("[urls...]")); + + parser.process(app); + aboutData.processCommandLine(&parser); + + app.setApplicationName(aboutData.componentName()); + app.setApplicationDisplayName(aboutData.displayName()); + app.setOrganizationDomain(aboutData.organizationDomain()); + app.setApplicationVersion(aboutData.version()); + + + bool running = false; + + const KDBusService dbusService(KDBusService::Multiple | KDBusService::NoExitOnFailure); + + QDBusConnection dbus = QDBusConnection::sessionBus(); + running = dbus.interface()->isServiceRegistered("net.sourceforge.kile"); + + if(!running || parser.isSet("new")) { + bool restore = (parser.positionalArguments().count() == 0); + + Kile *kile = new Kile(restore); + + Q_FOREACH(QString argument, parser.positionalArguments()) { + if(argument == "-") { + kile->openDocument(readDataFromStdin()); + } + else { + const QUrl url = QUrl::fromUserInput(argument, QDir::currentPath(), QUrl::AssumeLocalFile); + + if(isProject(url)) { + kile->openProject(url); + } + else { + kile->openDocument(url); + } + } + } + + if(parser.isSet("line")) { + QString line = parser.value("line"); + kile->setLine(line); + } + + return app.exec(); + } + else { + QDBusInterface *interface = new QDBusInterface("net.sourceforge.kile","/main","net.sourceforge.kile.main"); + + Q_FOREACH(QString argument, parser.positionalArguments()) { + if(argument == "-") { + interface->call("openDocument", readDataFromStdin()); + } + else { + const QUrl url = QUrl::fromUserInput(argument, QDir::currentPath(), QUrl::AssumeLocalFile); + + if(isProject(url)) { + interface->call("openProject", url.url()); + } + else { + interface->call("openDocument", url.url()); + } + } + } + + if(parser.isSet("line")) { + QString line = parser.value("line"); + interface->call("setLine", line); + } + + KStartupInfo::appStarted(); + interface->call("setActive"); + delete interface; + } + + return EXIT_SUCCESS; } diff --git a/src/outputinfo.cpp b/src/outputinfo.cpp index 4eefb8c3..4d9882d8 100644 --- a/src/outputinfo.cpp +++ b/src/outputinfo.cpp @@ -1,165 +1,165 @@ /************************************************************************************ Copyright (C) 2003 by Jeroen Wijnhout (wijnhout@science.uva.nl) 2008-2012 by Michel Ludwig (michel.ludwig@kdemail.net) ************************************************************************************/ /*************************************************************************** * * * 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. * * * ***************************************************************************/ #include "outputinfo.h" OutputInfo::OutputInfo() { - clear(); + clear(); } OutputInfo::OutputInfo(const QString& mainSourceFile, const QString& strSrcFile, int nSrcLine, int nOutputLine, const QString& strError, int nErrorID /*=-1*/) : m_mainSourceFile(mainSourceFile), m_strSrcFile(strSrcFile), m_nSrcLine(nSrcLine), m_strError(strError), m_nOutputLine(nOutputLine), m_nErrorID(nErrorID) { } void OutputInfo::clear() { - m_mainSourceFile.clear(); - m_strSrcFile.clear(); - m_nSrcLine = -1; - m_nOutputLine = -1; - m_strError.clear(); - m_nErrorID = -1; + m_mainSourceFile.clear(); + m_strSrcFile.clear(); + m_nSrcLine = -1; + m_nOutputLine = -1; + m_strError.clear(); + m_nErrorID = -1; } bool OutputInfo::operator==(const OutputInfo& info) const { - return (m_mainSourceFile == info.m_mainSourceFile - && m_strSrcFile == info.m_strSrcFile - && m_nSrcLine == info.m_nSrcLine - && m_strError == info.m_strError - && m_nOutputLine == info.m_nOutputLine - && m_nErrorID == info.m_nErrorID); + return (m_mainSourceFile == info.m_mainSourceFile + && m_strSrcFile == info.m_strSrcFile + && m_nSrcLine == info.m_nSrcLine + && m_strError == info.m_strError + && m_nOutputLine == info.m_nOutputLine + && m_nErrorID == info.m_nErrorID); } bool OutputInfo::isValid() const { - return !(m_mainSourceFile.isEmpty() && m_strSrcFile.isEmpty() && m_nSrcLine == -1 && m_nOutputLine == -1 - && m_strError.isEmpty() && m_nErrorID == -1); + return !(m_mainSourceFile.isEmpty() && m_strSrcFile.isEmpty() && m_nSrcLine == -1 && m_nOutputLine == -1 + && m_strError.isEmpty() && m_nErrorID == -1); } LatexOutputInfo::LatexOutputInfo() : OutputInfo() { } LatexOutputInfo::LatexOutputInfo(const QString& mainSourceFile, const QString& strSrcFile, int nSrcLine, int nOutputLine, const QString& strError, int nErrorID) -: OutputInfo(mainSourceFile, strSrcFile, nSrcLine, nOutputLine, strError, nErrorID) + : OutputInfo(mainSourceFile, strSrcFile, nSrcLine, nOutputLine, strError, nErrorID) { } /** * LatexOutputHandler */ LaTeXOutputHandler::LaTeXOutputHandler() -: m_nErrors(-1), m_nWarnings(-1), m_nBadBoxes(-1), m_currentError(-1) + : m_nErrors(-1), m_nWarnings(-1), m_nBadBoxes(-1), m_currentError(-1) { } LaTeXOutputHandler::~LaTeXOutputHandler() { } void LaTeXOutputHandler::storeLaTeXOutputParserResult(int nErrors, int nWarnings, int nBadBoxes, - const LatexOutputInfoArray& outputList, - const QString& logFile) + const LatexOutputInfoArray& outputList, + const QString& logFile) { - m_nErrors = nErrors; - m_nWarnings = nWarnings; - m_nBadBoxes = nBadBoxes; - m_latexOutputInfoList = outputList; - m_logFile = logFile; - m_currentError = -1; + m_nErrors = nErrors; + m_nWarnings = nWarnings; + m_nBadBoxes = nBadBoxes; + m_latexOutputInfoList = outputList; + m_logFile = logFile; + m_currentError = -1; } int LaTeXOutputHandler::numberOfWarnings() const { - return m_nWarnings; + return m_nWarnings; } int LaTeXOutputHandler::numberOfErrors() const { - return m_nErrors; + return m_nErrors; } int LaTeXOutputHandler::numberOfBadBoxes() const { - return m_nBadBoxes; + return m_nBadBoxes; } LatexOutputInfoArray LaTeXOutputHandler::outputList() const { - return m_latexOutputInfoList; + return m_latexOutputInfoList; } QString LaTeXOutputHandler::logFile() const { - return m_logFile; + return m_logFile; } int LaTeXOutputHandler::currentError() const { - return m_currentError; + return m_currentError; } void LaTeXOutputHandler::setCurrentError(int i) { - m_currentError = i; + m_currentError = i; } const KileTool::ToolConfigPair& LaTeXOutputHandler::bibliographyBackendToolUserOverride() const { - return m_userOverrideBibBackendToolConfigPair; + return m_userOverrideBibBackendToolConfigPair; } void LaTeXOutputHandler::setBibliographyBackendToolUserOverride(const KileTool::ToolConfigPair& p) { - m_userOverrideBibBackendToolConfigPair = p; + m_userOverrideBibBackendToolConfigPair = p; } const KileTool::ToolConfigPair& LaTeXOutputHandler::bibliographyBackendToolAutoDetected() const { - return m_autodetectBibBackendToolConfigPair; + return m_autodetectBibBackendToolConfigPair; } void LaTeXOutputHandler::setBibliographyBackendToolAutoDetected(const KileTool::ToolConfigPair& p) { - m_autodetectBibBackendToolConfigPair = p; + m_autodetectBibBackendToolConfigPair = p; } void LaTeXOutputHandler::readBibliographyBackendSettings(const KConfigGroup& group) { - const QString& bibBackendUserOverride = group.readEntry("bibliographyBackendUserOverride", QString()); - m_userOverrideBibBackendToolConfigPair = KileTool::ToolConfigPair::fromConfigStringRepresentation(bibBackendUserOverride); + const QString& bibBackendUserOverride = group.readEntry("bibliographyBackendUserOverride", QString()); + m_userOverrideBibBackendToolConfigPair = KileTool::ToolConfigPair::fromConfigStringRepresentation(bibBackendUserOverride); - const QString& bibBackendAutoDetected = group.readEntry("bibliographyBackendAutoDetected", QString()); - m_autodetectBibBackendToolConfigPair = KileTool::ToolConfigPair::fromConfigStringRepresentation(bibBackendAutoDetected); + const QString& bibBackendAutoDetected = group.readEntry("bibliographyBackendAutoDetected", QString()); + m_autodetectBibBackendToolConfigPair = KileTool::ToolConfigPair::fromConfigStringRepresentation(bibBackendAutoDetected); } void LaTeXOutputHandler::writeBibliographyBackendSettings(KConfigGroup& group) { - group.writeEntry("bibliographyBackendUserOverride", m_userOverrideBibBackendToolConfigPair.configStringRepresentation()); - group.writeEntry("bibliographyBackendAutoDetected", m_autodetectBibBackendToolConfigPair.configStringRepresentation()); + group.writeEntry("bibliographyBackendUserOverride", m_userOverrideBibBackendToolConfigPair.configStringRepresentation()); + group.writeEntry("bibliographyBackendAutoDetected", m_autodetectBibBackendToolConfigPair.configStringRepresentation()); } diff --git a/src/outputinfo.h b/src/outputinfo.h index bf5c24a4..ff6ab678 100644 --- a/src/outputinfo.h +++ b/src/outputinfo.h @@ -1,168 +1,192 @@ /************************************************************************************** Copyright (C) 2003 by Jeroen Wijnhout (wijnhout@science.uva.nl) 2008-2012 by Michel Ludwig (michel.ludwig@kdemail.net) **************************************************************************************/ /*************************************************************************** * * * 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. * * * ***************************************************************************/ #ifndef OUTPUTINFO_H #define OUTPUTINFO_H #include #include #include #include #include "tool_utils.h" /** * Class for output-information of third program (e.g. Latex-Output, C-Compiler output) * * @author Thorsten Lck * @author Jeroen Wijnhout **/ class OutputInfo { - public: - /** - * Constructs an invalid output information object. - **/ - OutputInfo(); - - OutputInfo(const QString& mainSourceFile, const QString& strSrcFile, int nSrcLine, int nOutputLine, const QString& strError = QString(), int nErrorID = -1); - - public: - /** - * Returns true if and only if this object contains valid output - * information. - **/ - bool isValid() const; - - /** File that was compiled. */ - QString mainSourceFile() const { return m_mainSourceFile; } - void setMainSourceFile(const QString& src) { m_mainSourceFile = src; } - - /** Source file where error occurred. */ - QString source() const { return m_strSrcFile; } - /** Source file where error occurred. */ - void setSource(const QString& src) { m_strSrcFile = src; } - - /** Line number in source file of the current message */ - int sourceLine() const { return m_nSrcLine; } - /** Line number in source file of the current message */ - void setSourceLine(int line) { m_nSrcLine = line; } - - /** Error message */ - QString message() const { return m_strError; } - /** Error message */ - void setMessage(const QString& message) { m_strError = message; } - - /** Error code */ - int type() const { return m_nErrorID; } - /** Error code */ - void setType(int type) { m_nErrorID = type; } - - /** Line number in the output, where error was reported. */ - int outputLine() const { return m_nOutputLine; } - /** Line number in the output, where error was reported. */ - void setOutputLine(int line) { m_nOutputLine = line; } - - /** - * Clears the information stored in this object, turning it - * into an invalid output information object. - **/ - void clear(); - - /** - * Comparison operator - **/ - bool operator==(const OutputInfo& info) const; +public: + /** + * Constructs an invalid output information object. + **/ + OutputInfo(); + + OutputInfo(const QString& mainSourceFile, const QString& strSrcFile, int nSrcLine, int nOutputLine, const QString& strError = QString(), int nErrorID = -1); + +public: + /** + * Returns true if and only if this object contains valid output + * information. + **/ + bool isValid() const; + + /** File that was compiled. */ + QString mainSourceFile() const { + return m_mainSourceFile; + } + void setMainSourceFile(const QString& src) { + m_mainSourceFile = src; + } + + /** Source file where error occurred. */ + QString source() const { + return m_strSrcFile; + } + /** Source file where error occurred. */ + void setSource(const QString& src) { + m_strSrcFile = src; + } + + /** Line number in source file of the current message */ + int sourceLine() const { + return m_nSrcLine; + } + /** Line number in source file of the current message */ + void setSourceLine(int line) { + m_nSrcLine = line; + } + + /** Error message */ + QString message() const { + return m_strError; + } + /** Error message */ + void setMessage(const QString& message) { + m_strError = message; + } + + /** Error code */ + int type() const { + return m_nErrorID; + } + /** Error code */ + void setType(int type) { + m_nErrorID = type; + } + + /** Line number in the output, where error was reported. */ + int outputLine() const { + return m_nOutputLine; + } + /** Line number in the output, where error was reported. */ + void setOutputLine(int line) { + m_nOutputLine = line; + } + + /** + * Clears the information stored in this object, turning it + * into an invalid output information object. + **/ + void clear(); + + /** + * Comparison operator + **/ + bool operator==(const OutputInfo& info) const; private: - QString m_mainSourceFile; - QString m_strSrcFile; - int m_nSrcLine; - QString m_strError; - int m_nOutputLine; - int m_nErrorID; + QString m_mainSourceFile; + QString m_strSrcFile; + int m_nSrcLine; + QString m_strError; + int m_nOutputLine; + int m_nErrorID; }; Q_DECLARE_METATYPE(OutputInfo) /** * Array of OutputInfo * @author Thorsten Lck **/ typedef QList OutputInfoArray; class LatexOutputInfo : public OutputInfo { - public: - LatexOutputInfo(); - LatexOutputInfo(const QString& mainSourceFile, const QString& strSrcFile, int nSrcLine, int nOutputLine, const QString& strError = QString(), int nErrorID = -1); - - public: - /** - * These constants are describing, which item types is currently - * parsed. (to be set as error code) - **/ - enum tagCookies - { - itmNone = 0, - itmError, - itmWarning, - itmBadBox - }; +public: + LatexOutputInfo(); + LatexOutputInfo(const QString& mainSourceFile, const QString& strSrcFile, int nSrcLine, int nOutputLine, const QString& strError = QString(), int nErrorID = -1); + +public: + /** + * These constants are describing, which item types is currently + * parsed. (to be set as error code) + **/ + enum tagCookies + { + itmNone = 0, + itmError, + itmWarning, + itmBadBox + }; }; /** * Array of LatexOutputInfo * @author Thorsten Lck **/ typedef QList LatexOutputInfoArray; class LaTeXOutputHandler { - public: - LaTeXOutputHandler(); - virtual ~LaTeXOutputHandler(); - - void storeLaTeXOutputParserResult(int nErrors, int nWarnings, int nBadBoxes, - const LatexOutputInfoArray& outputList, - const QString& logFile); - - int numberOfWarnings() const; - int numberOfErrors() const; - int numberOfBadBoxes() const; - LatexOutputInfoArray outputList() const; - QString logFile() const; - int currentError() const; - void setCurrentError(int i); - - void setBibliographyBackendToolUserOverride(const KileTool::ToolConfigPair& p); - const KileTool::ToolConfigPair& bibliographyBackendToolUserOverride() const; - - void setBibliographyBackendToolAutoDetected(const KileTool::ToolConfigPair& p); - const KileTool::ToolConfigPair& bibliographyBackendToolAutoDetected() const; - - void readBibliographyBackendSettings(const KConfigGroup& group); - void writeBibliographyBackendSettings(KConfigGroup& group); - - protected: - int m_nErrors, m_nWarnings, m_nBadBoxes, m_currentError; - LatexOutputInfoArray m_latexOutputInfoList; - QString m_logFile; - KileTool::ToolConfigPair m_userOverrideBibBackendToolConfigPair, m_autodetectBibBackendToolConfigPair; +public: + LaTeXOutputHandler(); + virtual ~LaTeXOutputHandler(); + + void storeLaTeXOutputParserResult(int nErrors, int nWarnings, int nBadBoxes, + const LatexOutputInfoArray& outputList, + const QString& logFile); + + int numberOfWarnings() const; + int numberOfErrors() const; + int numberOfBadBoxes() const; + LatexOutputInfoArray outputList() const; + QString logFile() const; + int currentError() const; + void setCurrentError(int i); + + void setBibliographyBackendToolUserOverride(const KileTool::ToolConfigPair& p); + const KileTool::ToolConfigPair& bibliographyBackendToolUserOverride() const; + + void setBibliographyBackendToolAutoDetected(const KileTool::ToolConfigPair& p); + const KileTool::ToolConfigPair& bibliographyBackendToolAutoDetected() const; + + void readBibliographyBackendSettings(const KConfigGroup& group); + void writeBibliographyBackendSettings(KConfigGroup& group); + +protected: + int m_nErrors, m_nWarnings, m_nBadBoxes, m_currentError; + LatexOutputInfoArray m_latexOutputInfoList; + QString m_logFile; + KileTool::ToolConfigPair m_userOverrideBibBackendToolConfigPair, m_autodetectBibBackendToolConfigPair; }; #endif diff --git a/src/parser/bibtexparser.cpp b/src/parser/bibtexparser.cpp index 0258a70d..b5c7dd0a 100644 --- a/src/parser/bibtexparser.cpp +++ b/src/parser/bibtexparser.cpp @@ -1,134 +1,135 @@ /********************************************************************************** * Copyright (C) 2003 by Jeroen Wijnhout (Jeroen.Wijnhout@kdemail.net) * * 2005-2007 by Holger Danielsson (holger.danielsson@versanet.de) * * 2006-2011 by Michel Ludwig (michel.ludwig@kdemail.net) * ***********************************************************************************/ /*************************************************************************** * * * 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. * * * ***************************************************************************/ #include "bibtexparser.h" #include #include #include #include #include "kiledebug.h" #include "codecompletion.h" #include "parserthread.h" namespace KileParser { BibTeXParserInput::BibTeXParserInput(const QUrl &url, QStringList textLines) -: ParserInput(url), - textLines(textLines) + : ParserInput(url), + textLines(textLines) { } BibTeXParserOutput::BibTeXParserOutput() { } BibTeXParserOutput::~BibTeXParserOutput() { qCDebug(LOG_KILE_PARSER); } BibTeXParser::BibTeXParser(ParserThread *parserThread, BibTeXParserInput *input, QObject *parent) -: Parser(parserThread, parent), - m_textLines(input->textLines) + : Parser(parserThread, parent), + m_textLines(input->textLines) { } BibTeXParser::~BibTeXParser() { qCDebug(LOG_KILE_PARSER); } ParserOutput* BibTeXParser::parse() { - BibTeXParserOutput *parserOutput = new BibTeXParserOutput(); + BibTeXParserOutput *parserOutput = new BibTeXParserOutput(); - qCDebug(LOG_KILE_PARSER); + qCDebug(LOG_KILE_PARSER); - static QRegExp reItem("^(\\s*)@([a-zA-Z]+)"); - static QRegExp reSpecial("string|preamble|comment"); + static QRegExp reItem("^(\\s*)@([a-zA-Z]+)"); + static QRegExp reSpecial("string|preamble|comment"); - QString s, key; - int col = 0, startcol, startline = 0; + QString s, key; + int col = 0, startcol, startline = 0; // emit(parsingStarted(m_doc->lines())); - for(int i = 0; i < m_textLines.size(); ++i) { - if(!m_parserThread->shouldContinueDocumentParsing()) { - qCDebug(LOG_KILE_PARSER) << "stopping..."; - delete(parserOutput); - return Q_NULLPTR; - } + for(int i = 0; i < m_textLines.size(); ++i) { + if(!m_parserThread->shouldContinueDocumentParsing()) { + qCDebug(LOG_KILE_PARSER) << "stopping..."; + delete(parserOutput); + return Q_NULLPTR; + } // emit(parsingUpdate(i)); - s = getTextLine(m_textLines, i); - if((s.indexOf(reItem) != -1) && !reSpecial.exactMatch(reItem.cap(2).toLower())) { - qCDebug(LOG_KILE_PARSER) << "found: " << reItem.cap(2); - //start looking for key - key = ""; - bool keystarted = false; - int state = 0; - startcol = reItem.cap(1).length(); - col = startcol + reItem.cap(2).length(); - - while(col < static_cast(s.length())) { - ++col; - if(col == static_cast(s.length())) { - do { - ++i; - s = getTextLine(m_textLines, i); - } - while((s.length() == 0) && (i < m_textLines.size())); - - if(i == m_textLines.size()) { - break; - } - col = 0; - } - - if(state == 0) { - if(s[col] == '{') { - state = 1; - } - else if(!s[col].isSpace()) { - break; - } - } - else if(state == 1) { - if(s[col] == ',') { - key = key.trimmed(); - qCDebug(LOG_KILE_PARSER) << "found: " << key; - parserOutput->bibItems.append(key); - parserOutput->structureViewItems.push_back(new StructureViewItem(key, startline+1, startcol, KileStruct::BibItem, 0, startline+1, startcol, "viewbib", reItem.cap(2).toLower())); - break; - } - else { - key += s[col]; - if(!keystarted) { - startcol = col; startline = i; - } - keystarted = true; - } - } - } - } - } - - return parserOutput;; + s = getTextLine(m_textLines, i); + if((s.indexOf(reItem) != -1) && !reSpecial.exactMatch(reItem.cap(2).toLower())) { + qCDebug(LOG_KILE_PARSER) << "found: " << reItem.cap(2); + //start looking for key + key = ""; + bool keystarted = false; + int state = 0; + startcol = reItem.cap(1).length(); + col = startcol + reItem.cap(2).length(); + + while(col < static_cast(s.length())) { + ++col; + if(col == static_cast(s.length())) { + do { + ++i; + s = getTextLine(m_textLines, i); + } + while((s.length() == 0) && (i < m_textLines.size())); + + if(i == m_textLines.size()) { + break; + } + col = 0; + } + + if(state == 0) { + if(s[col] == '{') { + state = 1; + } + else if(!s[col].isSpace()) { + break; + } + } + else if(state == 1) { + if(s[col] == ',') { + key = key.trimmed(); + qCDebug(LOG_KILE_PARSER) << "found: " << key; + parserOutput->bibItems.append(key); + parserOutput->structureViewItems.push_back(new StructureViewItem(key, startline+1, startcol, KileStruct::BibItem, 0, startline+1, startcol, "viewbib", reItem.cap(2).toLower())); + break; + } + else { + key += s[col]; + if(!keystarted) { + startcol = col; + startline = i; + } + keystarted = true; + } + } + } + } + } + + return parserOutput;; } } diff --git a/src/parser/bibtexparser.h b/src/parser/bibtexparser.h index 004c5127..618a36e9 100644 --- a/src/parser/bibtexparser.h +++ b/src/parser/bibtexparser.h @@ -1,59 +1,59 @@ /************************************************************************** * Copyright (C) 2011 by Michel Ludwig (michel.ludwig@kdemail.net) * ***************************************************************************/ /*************************************************************************** * * * 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. * * * ***************************************************************************/ #ifndef BIBTEXPARSER_H #define BIBTEXPARSER_H #include #include "documentinfo.h" #include "kileconstants.h" #include "kileextensions.h" #include "parser.h" namespace KileParser { class BibTeXParserInput : public ParserInput { public: - BibTeXParserInput(const QUrl &url, QStringList textLines); + BibTeXParserInput(const QUrl &url, QStringList textLines); - QStringList textLines; + QStringList textLines; }; class BibTeXParserOutput : public ParserOutput { public: - BibTeXParserOutput(); - virtual ~BibTeXParserOutput(); + BibTeXParserOutput(); + virtual ~BibTeXParserOutput(); - QStringList bibItems; + QStringList bibItems; }; class BibTeXParser : public Parser { - Q_OBJECT + Q_OBJECT public: - BibTeXParser(ParserThread *parserThread, BibTeXParserInput *input, QObject *parent = Q_NULLPTR); - virtual ~BibTeXParser(); + BibTeXParser(ParserThread *parserThread, BibTeXParserInput *input, QObject *parent = Q_NULLPTR); + virtual ~BibTeXParser(); - ParserOutput* parse(); + ParserOutput* parse(); protected: - QStringList m_textLines; + QStringList m_textLines; }; } #endif diff --git a/src/parser/latexoutputparser.cpp b/src/parser/latexoutputparser.cpp index 9f724409..9c60b421 100644 --- a/src/parser/latexoutputparser.cpp +++ b/src/parser/latexoutputparser.cpp @@ -1,712 +1,719 @@ /********************************************************************************** * Copyright (C) 2003 by Jeroen Wijnhout (Jeroen.Wijnhout@kdemail.net) * * 2011 by Michel Ludwig (michel.ludwig@kdemail.net) * ***********************************************************************************/ /*************************************************************************** * * * 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. * * * ***************************************************************************/ #include "latexoutputparser.h" #include #include #include #include "kiletool_enums.h" #include "parserthread.h" #include "widgets/logwidget.h" namespace KileParser { LaTeXOutputParserInput::LaTeXOutputParserInput(const QUrl &url, KileDocument::Extensions *extensions, const QString& sourceFile, - const QString &texfilename, int selrow, int docrow) -: ParserInput(url), - extensions(extensions), - sourceFile(sourceFile), - texfilename(texfilename), - selrow(selrow), - docrow(docrow) + const QString &texfilename, + int selrow, + int docrow) + : ParserInput(url), + extensions(extensions), + sourceFile(sourceFile), + texfilename(texfilename), + selrow(selrow), + docrow(docrow) { } LaTeXOutputParserOutput::LaTeXOutputParserOutput() { } LaTeXOutputParserOutput::~LaTeXOutputParserOutput() { qCDebug(LOG_KILE_PARSER); } LaTeXOutputParser::LaTeXOutputParser(ParserThread *parserThread, LaTeXOutputParserInput *input, QObject *parent) -: Parser(parserThread, parent), - m_extensions(input->extensions), - m_infoList(Q_NULLPTR), - m_logFile(input->url.toLocalFile()), - texfilename(input->texfilename), - selrow(input->selrow), - docrow(input->docrow) + : Parser(parserThread, parent), + m_extensions(input->extensions), + m_infoList(Q_NULLPTR), + m_logFile(input->url.toLocalFile()), + texfilename(input->texfilename), + selrow(input->selrow), + docrow(input->docrow) { - m_nErrors = 0; - m_nWarnings = 0; - m_nBadBoxes = 0; - setSource(input->sourceFile); + m_nErrors = 0; + m_nWarnings = 0; + m_nBadBoxes = 0; + setSource(input->sourceFile); } LaTeXOutputParser::~LaTeXOutputParser() { qCDebug(LOG_KILE_PARSER); } bool LaTeXOutputParser::fileExists(const QString & name) { - static QFileInfo fi; - - if (QDir::isAbsolutePath(name)) { - fi.setFile(name); - if(fi.exists() && !fi.isDir()) { - return true; - } - else { - return false; - } - } - - fi.setFile(path() + '/' + name); - if(fi.exists() && !fi.isDir()) { - return true; - } - - fi.setFile(path() + '/' + name + m_extensions->latexDocumentDefault()); - if(fi.exists() && !fi.isDir()) { - return true; - } - - // try to determine the LaTeX source file - QStringList extlist = m_extensions->latexDocuments().split(' '); - for(QStringList::Iterator it = extlist.begin(); it!=extlist.end(); ++it) { - fi.setFile(path() + '/' + name + (*it)); - if(fi.exists() && !fi.isDir()) { - return true; - } - } - - return false; + static QFileInfo fi; + + if (QDir::isAbsolutePath(name)) { + fi.setFile(name); + if(fi.exists() && !fi.isDir()) { + return true; + } + else { + return false; + } + } + + fi.setFile(path() + '/' + name); + if(fi.exists() && !fi.isDir()) { + return true; + } + + fi.setFile(path() + '/' + name + m_extensions->latexDocumentDefault()); + if(fi.exists() && !fi.isDir()) { + return true; + } + + // try to determine the LaTeX source file + QStringList extlist = m_extensions->latexDocuments().split(' '); + for(QStringList::Iterator it = extlist.begin(); it!=extlist.end(); ++it) { + fi.setFile(path() + '/' + name + (*it)); + if(fi.exists() && !fi.isDir()) { + return true; + } + } + + return false; } // There are basically two ways to detect the current file TeX is processing: // 1) Use \Input (i.c.w. srctex.sty or srcltx.sty) and \include exclusively. This will // cause (La)TeX to print the line ":<+ filename" in the log file when opening a file, // ":<-" when closing a file. Filenames pushed on the stack in this mode are marked // as reliable. // // 2) Since people will probably also use the \input command, we also have to be // to detect the old-fashioned way. TeX prints '(filename' when opening a file and a ')' // when closing one. It is impossible to detect this with 100% certainty (TeX prints many messages // and even text (a context) from the TeX source file, there could be unbalanced parentheses), // so we use a heuristic algorithm. In heuristic mode a ')' will only be considered as a signal that // TeX is closing a file if the top of the stack is not marked as "reliable". // Also, when scanning for a TeX error linenumber (which sometimes causes a context to be printed // to the log-file), updateFileStack is not called, helping not to pick up unbalanced parentheses // from the context. void LaTeXOutputParser::updateFileStack(const QString &strLine, short& dwCookie) { - //qCDebug(LOG_KILE_PARSER) << "==LaTeXOutputParser::updateFileStack()================" << endl; - static QString strPartialFileName; - - switch (dwCookie) { - //we're looking for a filename - case Start : case FileNameHeuristic : - //TeX is opening a file - if(strLine.startsWith(":<+ ")) { + //qCDebug(LOG_KILE_PARSER) << "==LaTeXOutputParser::updateFileStack()================" << endl; + static QString strPartialFileName; + + switch (dwCookie) { + //we're looking for a filename + case Start : + case FileNameHeuristic : + //TeX is opening a file + if(strLine.startsWith(":<+ ")) { // qCDebug(LOG_KILE_PARSER) << "filename detected" << endl; - //grab the filename, it might be a partial name (i.e. continued on the next line) - strPartialFileName = strLine.mid(4).trimmed(); - - //change the cookie so we remember we aren't sure the filename is complete - dwCookie = FileName; - } - //TeX closed a file - else if(strLine.contains(":<-")) { + //grab the filename, it might be a partial name (i.e. continued on the next line) + strPartialFileName = strLine.mid(4).trimmed(); + + //change the cookie so we remember we aren't sure the filename is complete + dwCookie = FileName; + } + //TeX closed a file + else if(strLine.contains(":<-")) { // qCDebug(LOG_KILE_PARSER) << "\tpopping : " << m_stackFile.top().file() << endl; - if(!m_stackFile.isEmpty()) { - m_stackFile.pop(); - } - dwCookie = Start; - } - else { - //fallback to the heuristic detection of filenames - updateFileStackHeuristic(strLine, dwCookie); - } - break; - - case FileName : - //The partial filename was followed by '(', this means that TeX is signalling it is - //opening the file. We are sure the filename is complete now. Don't call updateFileStackHeuristic - //since we don't want the filename on the stack twice. - if(strLine.startsWith('(') || strLine.startsWith("\\openout")) { - //push the filename on the stack and mark it as 'reliable' - m_stackFile.push(LOFStackItem(strPartialFileName, true)); + if(!m_stackFile.isEmpty()) { + m_stackFile.pop(); + } + dwCookie = Start; + } + else { + //fallback to the heuristic detection of filenames + updateFileStackHeuristic(strLine, dwCookie); + } + break; + + case FileName : + //The partial filename was followed by '(', this means that TeX is signalling it is + //opening the file. We are sure the filename is complete now. Don't call updateFileStackHeuristic + //since we don't want the filename on the stack twice. + if(strLine.startsWith('(') || strLine.startsWith("\\openout")) { + //push the filename on the stack and mark it as 'reliable' + m_stackFile.push(LOFStackItem(strPartialFileName, true)); // qCDebug(LOG_KILE_PARSER) << "\tpushed : " << strPartialFileName << endl; - strPartialFileName.clear(); - dwCookie = Start; - } - //The partial filename was followed by an TeX error, meaning the file doesn't exist. - //Don't push it on the stack, instead try to detect the error. - else if(strLine.startsWith('!')) { + strPartialFileName.clear(); + dwCookie = Start; + } + //The partial filename was followed by an TeX error, meaning the file doesn't exist. + //Don't push it on the stack, instead try to detect the error. + else if(strLine.startsWith('!')) { // qCDebug(LOG_KILE_PARSER) << "oops!" << endl; - dwCookie = Start; - strPartialFileName.clear(); - detectError(strLine, dwCookie); - } - else if(strLine.startsWith("No file")) { + dwCookie = Start; + strPartialFileName.clear(); + detectError(strLine, dwCookie); + } + else if(strLine.startsWith("No file")) { // qCDebug(LOG_KILE_PARSER) << "No file: " << strLine << endl; - dwCookie = Start; - strPartialFileName.clear(); - detectWarning(strLine, dwCookie); - } - //Partial filename still isn't complete. - else { + dwCookie = Start; + strPartialFileName.clear(); + detectWarning(strLine, dwCookie); + } + //Partial filename still isn't complete. + else { // qCDebug(LOG_KILE_PARSER) << "\tpartial file name, adding" << endl; - strPartialFileName = strPartialFileName + strLine.trimmed(); - } - break; + strPartialFileName = strPartialFileName + strLine.trimmed(); + } + break; - default: - break; - } + default: + break; + } } void LaTeXOutputParser::updateFileStackHeuristic(const QString &strLine, short & dwCookie) { - //qCDebug(LOG_KILE_PARSER) << "==LaTeXOutputParser::updateFileStackHeuristic()================"; - //qCDebug(LOG_KILE_PARSER) << strLine << dwCookie; - static QString strPartialFileName; - bool expectFileName = (dwCookie == FileNameHeuristic); - int index = 0; - - // handle special case (bug fix for 101810) - if(expectFileName && strLine.length() > 0 && strLine[0] == ')') { - m_stackFile.push(LOFStackItem(strPartialFileName)); - expectFileName = false; - dwCookie = Start; - } - - //scan for parentheses and grab filenames - for(int i = 0; i < strLine.length(); ++i) { - /* - We're expecting a filename. If a filename really ends at this position one of the following must be true: - 1) Next character is a space (indicating the end of a filename (yes, there can't be spaces in the - path, this is a TeX limitation). - comment by tbraun: there is a workround \include{{"file name"}} according to http://groups.google.com/group/comp.text.tex/browse_thread/thread/af873534f0644e4f/cd7e0cdb61a8b837?lnk=st&q=include+space+tex#cd7e0cdb61a8b837, - but this is currently not supported by kile. - 2) We're at the end of the line, the filename is probably continued on the next line. - 3) The TeX was closed already, signalled by the ')'. - */ - - bool isLastChar = (i+1 == strLine.length()); - bool nextIsTerminator = isLastChar ? false : (strLine[i+1].isSpace() || strLine[i+1] == ')'); - - if(expectFileName && (isLastChar || nextIsTerminator)) { - qCDebug(LOG_KILE_PARSER) << "Update the partial filename " << strPartialFileName; - strPartialFileName = strPartialFileName + strLine.mid(index, i-index + 1); - - if(strPartialFileName.isEmpty()){ // nothing left to do here - continue; - } - - //FIXME: improve these heuristics - if((isLastChar && (i < 78)) || nextIsTerminator || fileExists(strPartialFileName)) { - m_stackFile.push(LOFStackItem(strPartialFileName)); - //qCDebug(LOG_KILE_PARSER) << "\tpushed (i = " << i << " length = " << strLine.length() << "): " << strPartialFileName; - expectFileName = false; - dwCookie = Start; - } - //Guess the filename is continued on the next line, only if the current strPartialFileName does not exist, see bug # 162899 - else if(isLastChar) { - if(fileExists(strPartialFileName)) { - m_stackFile.push(LOFStackItem(strPartialFileName)); - qCDebug(LOG_KILE_PARSER) << "pushed (i = " << i << " length = " << strLine.length() << "): " << strPartialFileName << endl; - expectFileName = false; - dwCookie = Start; - } - else { - qCDebug(LOG_KILE_PARSER) << "Filename spans more than one line." << endl; - dwCookie = FileNameHeuristic; - } - } - //bail out - else { - dwCookie = Start; - strPartialFileName.clear(); - expectFileName = false; - } - } - //TeX is opening a file - else if(strLine[i] == '(') { - //we need to extract the filename - expectFileName = true; - strPartialFileName.clear(); - dwCookie = Start; - - //this is were the filename is supposed to start - index = i + 1; - } - //TeX is closing a file - else if(strLine[i] == ')') { - //qCDebug(LOG_KILE_PARSER) << "\tpopping : " << m_stackFile.top().file(); - //If this filename was pushed on the stack by the reliable ":<+-" method, don't pop - //a ":<-" will follow. This helps in preventing unbalanced ')' from popping filenames - //from the stack too soon. - if(m_stackFile.count() > 1 && !m_stackFile.top().reliable()) { - m_stackFile.pop(); - } - else { - qCDebug(LOG_KILE_PARSER) << "\t\toh no, forget about it!"; - } - } - } + //qCDebug(LOG_KILE_PARSER) << "==LaTeXOutputParser::updateFileStackHeuristic()================"; + //qCDebug(LOG_KILE_PARSER) << strLine << dwCookie; + static QString strPartialFileName; + bool expectFileName = (dwCookie == FileNameHeuristic); + int index = 0; + + // handle special case (bug fix for 101810) + if(expectFileName && strLine.length() > 0 && strLine[0] == ')') { + m_stackFile.push(LOFStackItem(strPartialFileName)); + expectFileName = false; + dwCookie = Start; + } + + //scan for parentheses and grab filenames + for(int i = 0; i < strLine.length(); ++i) { + /* + We're expecting a filename. If a filename really ends at this position one of the following must be true: + 1) Next character is a space (indicating the end of a filename (yes, there can't be spaces in the + path, this is a TeX limitation). + comment by tbraun: there is a workround \include{{"file name"}} according to http://groups.google.com/group/comp.text.tex/browse_thread/thread/af873534f0644e4f/cd7e0cdb61a8b837?lnk=st&q=include+space+tex#cd7e0cdb61a8b837, + but this is currently not supported by kile. + 2) We're at the end of the line, the filename is probably continued on the next line. + 3) The TeX was closed already, signalled by the ')'. + */ + + bool isLastChar = (i+1 == strLine.length()); + bool nextIsTerminator = isLastChar ? false : (strLine[i+1].isSpace() || strLine[i+1] == ')'); + + if(expectFileName && (isLastChar || nextIsTerminator)) { + qCDebug(LOG_KILE_PARSER) << "Update the partial filename " << strPartialFileName; + strPartialFileName = strPartialFileName + strLine.mid(index, i-index + 1); + + if(strPartialFileName.isEmpty()) { // nothing left to do here + continue; + } + + //FIXME: improve these heuristics + if((isLastChar && (i < 78)) || nextIsTerminator || fileExists(strPartialFileName)) { + m_stackFile.push(LOFStackItem(strPartialFileName)); + //qCDebug(LOG_KILE_PARSER) << "\tpushed (i = " << i << " length = " << strLine.length() << "): " << strPartialFileName; + expectFileName = false; + dwCookie = Start; + } + //Guess the filename is continued on the next line, only if the current strPartialFileName does not exist, see bug # 162899 + else if(isLastChar) { + if(fileExists(strPartialFileName)) { + m_stackFile.push(LOFStackItem(strPartialFileName)); + qCDebug(LOG_KILE_PARSER) << "pushed (i = " << i << " length = " << strLine.length() << "): " << strPartialFileName << endl; + expectFileName = false; + dwCookie = Start; + } + else { + qCDebug(LOG_KILE_PARSER) << "Filename spans more than one line." << endl; + dwCookie = FileNameHeuristic; + } + } + //bail out + else { + dwCookie = Start; + strPartialFileName.clear(); + expectFileName = false; + } + } + //TeX is opening a file + else if(strLine[i] == '(') { + //we need to extract the filename + expectFileName = true; + strPartialFileName.clear(); + dwCookie = Start; + + //this is were the filename is supposed to start + index = i + 1; + } + //TeX is closing a file + else if(strLine[i] == ')') { + //qCDebug(LOG_KILE_PARSER) << "\tpopping : " << m_stackFile.top().file(); + //If this filename was pushed on the stack by the reliable ":<+-" method, don't pop + //a ":<-" will follow. This helps in preventing unbalanced ')' from popping filenames + //from the stack too soon. + if(m_stackFile.count() > 1 && !m_stackFile.top().reliable()) { + m_stackFile.pop(); + } + else { + qCDebug(LOG_KILE_PARSER) << "\t\toh no, forget about it!"; + } + } + } } void LaTeXOutputParser::flushCurrentItem() { - //qCDebug(LOG_KILE_PARSER) << "==LaTeXOutputParser::flushCurrentItem()================" << endl; - int nItemType = m_currentItem.type(); - - while( m_stackFile.count() > 0 && !fileExists(m_stackFile.top().file()) ) { - m_stackFile.pop(); - } - - QString sourceFile = (m_stackFile.isEmpty()) ? QFileInfo(source()).fileName() : m_stackFile.top().file(); - m_currentItem.setSource(sourceFile); - m_currentItem.setMainSourceFile(source()); - - switch (nItemType) { - case itmError: - ++m_nErrors; - m_infoList->push_back(m_currentItem); - //qCDebug(LOG_KILE_PARSER) << "Flushing Error in" << m_currentItem.source() << "@" << m_currentItem.sourceLine() << " reported in line " << m_currentItem.outputLine() << endl; - break; - - case itmWarning: - ++m_nWarnings; - m_infoList->push_back(m_currentItem); - //qCDebug(LOG_KILE_PARSER) << "Flushing Warning in " << m_currentItem.source() << "@" << m_currentItem.sourceLine() << " reported in line " << m_currentItem.outputLine() << endl; - break; - - case itmBadBox: - ++m_nBadBoxes; - m_infoList->push_back(m_currentItem); - //qCDebug(LOG_KILE_PARSER) << "Flushing BadBox in " << m_currentItem.source() << "@" << m_currentItem.sourceLine() << " reported in line " << m_currentItem.outputLine() << endl; - break; - - default: break; - } - m_currentItem.clear(); + //qCDebug(LOG_KILE_PARSER) << "==LaTeXOutputParser::flushCurrentItem()================" << endl; + int nItemType = m_currentItem.type(); + + while( m_stackFile.count() > 0 && !fileExists(m_stackFile.top().file()) ) { + m_stackFile.pop(); + } + + QString sourceFile = (m_stackFile.isEmpty()) ? QFileInfo(source()).fileName() : m_stackFile.top().file(); + m_currentItem.setSource(sourceFile); + m_currentItem.setMainSourceFile(source()); + + switch (nItemType) { + case itmError: + ++m_nErrors; + m_infoList->push_back(m_currentItem); + //qCDebug(LOG_KILE_PARSER) << "Flushing Error in" << m_currentItem.source() << "@" << m_currentItem.sourceLine() << " reported in line " << m_currentItem.outputLine() << endl; + break; + + case itmWarning: + ++m_nWarnings; + m_infoList->push_back(m_currentItem); + //qCDebug(LOG_KILE_PARSER) << "Flushing Warning in " << m_currentItem.source() << "@" << m_currentItem.sourceLine() << " reported in line " << m_currentItem.outputLine() << endl; + break; + + case itmBadBox: + ++m_nBadBoxes; + m_infoList->push_back(m_currentItem); + //qCDebug(LOG_KILE_PARSER) << "Flushing BadBox in " << m_currentItem.source() << "@" << m_currentItem.sourceLine() << " reported in line " << m_currentItem.outputLine() << endl; + break; + + default: + break; + } + m_currentItem.clear(); } bool LaTeXOutputParser::detectError(const QString & strLine, short &dwCookie) { - //qCDebug(LOG_KILE_PARSER) << "==LaTeXOutputParser::detectError(" << strLine.length() << ")================" << endl; - - bool found = false, flush = false; - - static QRegExp reLaTeXError("^! LaTeX Error: (.*)$", Qt::CaseInsensitive); - static QRegExp rePDFLaTeXError("^Error: pdflatex (.*)$", Qt::CaseInsensitive); - static QRegExp reTeXError("^! (.*)\\.$"); - static QRegExp reLineNumber("^l\\.([0-9]+)(.*)"); - - switch (dwCookie) { - case Start : - if(reLaTeXError.indexIn(strLine) != -1) { - //qCDebug(LOG_KILE_PARSER) << "\tError : " << reLaTeXError.cap(1) << endl; - m_currentItem.setMessage(reLaTeXError.cap(1)); - found = true; - } - else if(rePDFLaTeXError.indexIn(strLine) != -1) { - //qCDebug(LOG_KILE_PARSER) << "\tError : " << rePDFLaTeXError.cap(1) << endl; - m_currentItem.setMessage(rePDFLaTeXError.cap(1)); - found = true; - } - else if(reTeXError.indexIn(strLine) != -1) { - //qCDebug(LOG_KILE_PARSER) << "\tError : " << reTeXError.cap(1) << endl; - m_currentItem.setMessage(reTeXError.cap(1)); - found = true; - } - if(found) { - dwCookie = strLine.endsWith('.') ? LineNumber : Error; - m_currentItem.setOutputLine(GetCurrentOutputLine()); - } - break; - - case Error : - //qCDebug(LOG_KILE_PARSER) << "\tError (cont'd): " << strLine << endl; - if(strLine.endsWith('.')) { - dwCookie = LineNumber; - m_currentItem.setMessage(m_currentItem.message() + strLine); - } - else if(GetCurrentOutputLine() - m_currentItem.outputLine() > 3) { - qWarning() << "\tBAILING OUT: error description spans more than three lines" << endl; - dwCookie = Start; - flush = true; - } - break; - - case LineNumber : - //qCDebug(LOG_KILE_PARSER) << "\tLineNumber " << endl; - if(reLineNumber.indexIn(strLine) != -1) { - dwCookie = Start; - flush = true; - //qCDebug(LOG_KILE_PARSER) << "\tline number: " << reLineNumber.cap(1) << endl; - m_currentItem.setSourceLine(reLineNumber.cap(1).toInt()); - m_currentItem.setMessage(m_currentItem.message() + reLineNumber.cap(2)); - } - else if(GetCurrentOutputLine() - m_currentItem.outputLine() > 10) { - dwCookie = Start; - flush = true; - qWarning() << "\tBAILING OUT: did not detect a TeX line number for an error" << endl; - m_currentItem.setSourceLine(0); - } - break; - - default : break; - } - - if(found) { - m_currentItem.setType(itmError); - m_currentItem.setOutputLine(GetCurrentOutputLine()); - } - - if(flush) { - flushCurrentItem(); - } - - return found; + //qCDebug(LOG_KILE_PARSER) << "==LaTeXOutputParser::detectError(" << strLine.length() << ")================" << endl; + + bool found = false, flush = false; + + static QRegExp reLaTeXError("^! LaTeX Error: (.*)$", Qt::CaseInsensitive); + static QRegExp rePDFLaTeXError("^Error: pdflatex (.*)$", Qt::CaseInsensitive); + static QRegExp reTeXError("^! (.*)\\.$"); + static QRegExp reLineNumber("^l\\.([0-9]+)(.*)"); + + switch (dwCookie) { + case Start : + if(reLaTeXError.indexIn(strLine) != -1) { + //qCDebug(LOG_KILE_PARSER) << "\tError : " << reLaTeXError.cap(1) << endl; + m_currentItem.setMessage(reLaTeXError.cap(1)); + found = true; + } + else if(rePDFLaTeXError.indexIn(strLine) != -1) { + //qCDebug(LOG_KILE_PARSER) << "\tError : " << rePDFLaTeXError.cap(1) << endl; + m_currentItem.setMessage(rePDFLaTeXError.cap(1)); + found = true; + } + else if(reTeXError.indexIn(strLine) != -1) { + //qCDebug(LOG_KILE_PARSER) << "\tError : " << reTeXError.cap(1) << endl; + m_currentItem.setMessage(reTeXError.cap(1)); + found = true; + } + if(found) { + dwCookie = strLine.endsWith('.') ? LineNumber : Error; + m_currentItem.setOutputLine(GetCurrentOutputLine()); + } + break; + + case Error : + //qCDebug(LOG_KILE_PARSER) << "\tError (cont'd): " << strLine << endl; + if(strLine.endsWith('.')) { + dwCookie = LineNumber; + m_currentItem.setMessage(m_currentItem.message() + strLine); + } + else if(GetCurrentOutputLine() - m_currentItem.outputLine() > 3) { + qWarning() << "\tBAILING OUT: error description spans more than three lines" << endl; + dwCookie = Start; + flush = true; + } + break; + + case LineNumber : + //qCDebug(LOG_KILE_PARSER) << "\tLineNumber " << endl; + if(reLineNumber.indexIn(strLine) != -1) { + dwCookie = Start; + flush = true; + //qCDebug(LOG_KILE_PARSER) << "\tline number: " << reLineNumber.cap(1) << endl; + m_currentItem.setSourceLine(reLineNumber.cap(1).toInt()); + m_currentItem.setMessage(m_currentItem.message() + reLineNumber.cap(2)); + } + else if(GetCurrentOutputLine() - m_currentItem.outputLine() > 10) { + dwCookie = Start; + flush = true; + qWarning() << "\tBAILING OUT: did not detect a TeX line number for an error" << endl; + m_currentItem.setSourceLine(0); + } + break; + + default : + break; + } + + if(found) { + m_currentItem.setType(itmError); + m_currentItem.setOutputLine(GetCurrentOutputLine()); + } + + if(flush) { + flushCurrentItem(); + } + + return found; } bool LaTeXOutputParser::detectWarning(const QString & strLine, short &dwCookie) { - //qCDebug(LOG_KILE_PARSER) << strLine << strLine.length(); - - bool found = false, flush = false; - QString warning; - - static QRegExp reLaTeXWarning("^(((! )?(La|pdf)TeX)|Package|Class) .*Warning.*:(.*)", Qt::CaseInsensitive); - static QRegExp reNoFile("No file (.*)"); - static QRegExp reNoAsyFile("File .* does not exist."); // FIXME can be removed when http://sourceforge.net/tracker/index.php?func=detail&aid=1772022&group_id=120000&atid=685683 has promoted to the users - - switch(dwCookie) { - //detect the beginning of a warning - case Start : - if(reLaTeXWarning.indexIn(strLine) != -1) { - warning = reLaTeXWarning.cap(5); - //qCDebug(LOG_KILE_PARSER) << "\tWarning found: " << warning << endl; - - found = true; - dwCookie = Start; - - m_currentItem.setMessage(warning); - m_currentItem.setOutputLine(GetCurrentOutputLine()); - - //do we expect a line number? - flush = detectLaTeXLineNumber(warning, dwCookie, strLine.length()); - } - else if(reNoFile.indexIn(strLine) != -1) { - found = true; - flush = true; - m_currentItem.setSourceLine(0); - m_currentItem.setMessage(reNoFile.cap(0)); - m_currentItem.setOutputLine(GetCurrentOutputLine()); - } - else if(reNoAsyFile.indexIn(strLine) != -1) { - found = true; - flush = true; - m_currentItem.setSourceLine(0); - m_currentItem.setMessage(reNoAsyFile.cap(0)); - m_currentItem.setOutputLine(GetCurrentOutputLine()); - } - - break; - - //warning spans multiple lines, detect the end - case Warning : - warning = m_currentItem.message() + strLine; - //qCDebug(LOG_KILE_PARSER) << "'\tWarning (cont'd) : " << warning << endl; - flush = detectLaTeXLineNumber(warning, dwCookie, strLine.length()); - m_currentItem.setMessage(warning); - break; - - default: - break; - } - - if(found) { - m_currentItem.setType(itmWarning); - m_currentItem.setOutputLine(GetCurrentOutputLine()); - } - - if(flush) { - flushCurrentItem(); - } - - return found; + //qCDebug(LOG_KILE_PARSER) << strLine << strLine.length(); + + bool found = false, flush = false; + QString warning; + + static QRegExp reLaTeXWarning("^(((! )?(La|pdf)TeX)|Package|Class) .*Warning.*:(.*)", Qt::CaseInsensitive); + static QRegExp reNoFile("No file (.*)"); + static QRegExp reNoAsyFile("File .* does not exist."); // FIXME can be removed when http://sourceforge.net/tracker/index.php?func=detail&aid=1772022&group_id=120000&atid=685683 has promoted to the users + + switch(dwCookie) { + //detect the beginning of a warning + case Start : + if(reLaTeXWarning.indexIn(strLine) != -1) { + warning = reLaTeXWarning.cap(5); + //qCDebug(LOG_KILE_PARSER) << "\tWarning found: " << warning << endl; + + found = true; + dwCookie = Start; + + m_currentItem.setMessage(warning); + m_currentItem.setOutputLine(GetCurrentOutputLine()); + + //do we expect a line number? + flush = detectLaTeXLineNumber(warning, dwCookie, strLine.length()); + } + else if(reNoFile.indexIn(strLine) != -1) { + found = true; + flush = true; + m_currentItem.setSourceLine(0); + m_currentItem.setMessage(reNoFile.cap(0)); + m_currentItem.setOutputLine(GetCurrentOutputLine()); + } + else if(reNoAsyFile.indexIn(strLine) != -1) { + found = true; + flush = true; + m_currentItem.setSourceLine(0); + m_currentItem.setMessage(reNoAsyFile.cap(0)); + m_currentItem.setOutputLine(GetCurrentOutputLine()); + } + + break; + + //warning spans multiple lines, detect the end + case Warning : + warning = m_currentItem.message() + strLine; + //qCDebug(LOG_KILE_PARSER) << "'\tWarning (cont'd) : " << warning << endl; + flush = detectLaTeXLineNumber(warning, dwCookie, strLine.length()); + m_currentItem.setMessage(warning); + break; + + default: + break; + } + + if(found) { + m_currentItem.setType(itmWarning); + m_currentItem.setOutputLine(GetCurrentOutputLine()); + } + + if(flush) { + flushCurrentItem(); + } + + return found; } bool LaTeXOutputParser::detectLaTeXLineNumber(QString & warning, short & dwCookie, int len) { - //qCDebug(LOG_KILE_PARSER) << "==LaTeXOutputParser::detectLaTeXLineNumber(" << warning.length() << ")================" << endl; - - static QRegExp reLaTeXLineNumber("(.*) on input line ([0-9]+)\\.$", Qt::CaseInsensitive); - static QRegExp reInternationalLaTeXLineNumber("(.*)([0-9]+)\\.$", Qt::CaseInsensitive); - if((reLaTeXLineNumber.indexIn(warning) != -1) || (reInternationalLaTeXLineNumber.indexIn(warning) != -1)) { - //qCDebug(LOG_KILE_PARSER) << "een" << endl; - m_currentItem.setSourceLine(reLaTeXLineNumber.cap(2).toInt()); - warning += reLaTeXLineNumber.cap(1); - dwCookie = Start; - return true; - } - else if(warning.endsWith('.')) { - //qCDebug(LOG_KILE_PARSER) << "twee" << endl; - m_currentItem.setSourceLine(0); - dwCookie = Start; - return true; - } - //bailing out, did not find a line number - else if((GetCurrentOutputLine() - m_currentItem.outputLine() > 4) || (len == 0)) { - //qCDebug(LOG_KILE_PARSER) << "drie current " << GetCurrentOutputLine() << " " << m_currentItem.outputLine() << " len " << len << endl; - m_currentItem.setSourceLine(0); - dwCookie = Start; - return true; - } - //error message is continued on the other line - else { - //qCDebug(LOG_KILE_PARSER) << "vier" << endl; - dwCookie = Warning; - return false; - } + //qCDebug(LOG_KILE_PARSER) << "==LaTeXOutputParser::detectLaTeXLineNumber(" << warning.length() << ")================" << endl; + + static QRegExp reLaTeXLineNumber("(.*) on input line ([0-9]+)\\.$", Qt::CaseInsensitive); + static QRegExp reInternationalLaTeXLineNumber("(.*)([0-9]+)\\.$", Qt::CaseInsensitive); + if((reLaTeXLineNumber.indexIn(warning) != -1) || (reInternationalLaTeXLineNumber.indexIn(warning) != -1)) { + //qCDebug(LOG_KILE_PARSER) << "een" << endl; + m_currentItem.setSourceLine(reLaTeXLineNumber.cap(2).toInt()); + warning += reLaTeXLineNumber.cap(1); + dwCookie = Start; + return true; + } + else if(warning.endsWith('.')) { + //qCDebug(LOG_KILE_PARSER) << "twee" << endl; + m_currentItem.setSourceLine(0); + dwCookie = Start; + return true; + } + //bailing out, did not find a line number + else if((GetCurrentOutputLine() - m_currentItem.outputLine() > 4) || (len == 0)) { + //qCDebug(LOG_KILE_PARSER) << "drie current " << GetCurrentOutputLine() << " " << m_currentItem.outputLine() << " len " << len << endl; + m_currentItem.setSourceLine(0); + dwCookie = Start; + return true; + } + //error message is continued on the other line + else { + //qCDebug(LOG_KILE_PARSER) << "vier" << endl; + dwCookie = Warning; + return false; + } } bool LaTeXOutputParser::detectBadBox(const QString & strLine, short & dwCookie) { - //qCDebug(LOG_KILE_PARSER) << "==LaTeXOutputParser::detectBadBox(" << strLine.length() << ")================" << endl; - - bool found = false, flush = false; - QString badbox; - - static QRegExp reBadBox("^(Over|Under)(full \\\\[hv]box .*)", Qt::CaseInsensitive); - - switch(dwCookie) { - case Start : - if(reBadBox.indexIn(strLine) != -1) { - found = true; - dwCookie = Start; - badbox = strLine; - flush = detectBadBoxLineNumber(badbox, dwCookie, strLine.length()); - m_currentItem.setMessage(badbox); - } - break; - - case BadBox : - badbox = m_currentItem.message() + strLine; - flush = detectBadBoxLineNumber(badbox, dwCookie, strLine.length()); - m_currentItem.setMessage(badbox); - break; - - default: - break; - } - - if(found) { - m_currentItem.setType(itmBadBox); - m_currentItem.setOutputLine(GetCurrentOutputLine()); - } - - if(flush) { - flushCurrentItem(); - } - - return found; + //qCDebug(LOG_KILE_PARSER) << "==LaTeXOutputParser::detectBadBox(" << strLine.length() << ")================" << endl; + + bool found = false, flush = false; + QString badbox; + + static QRegExp reBadBox("^(Over|Under)(full \\\\[hv]box .*)", Qt::CaseInsensitive); + + switch(dwCookie) { + case Start : + if(reBadBox.indexIn(strLine) != -1) { + found = true; + dwCookie = Start; + badbox = strLine; + flush = detectBadBoxLineNumber(badbox, dwCookie, strLine.length()); + m_currentItem.setMessage(badbox); + } + break; + + case BadBox : + badbox = m_currentItem.message() + strLine; + flush = detectBadBoxLineNumber(badbox, dwCookie, strLine.length()); + m_currentItem.setMessage(badbox); + break; + + default: + break; + } + + if(found) { + m_currentItem.setType(itmBadBox); + m_currentItem.setOutputLine(GetCurrentOutputLine()); + } + + if(flush) { + flushCurrentItem(); + } + + return found; } bool LaTeXOutputParser::detectBadBoxLineNumber(QString & strLine, short & dwCookie, int len) { - //qCDebug(LOG_KILE_PARSER) << "==LaTeXOutputParser::detectBadBoxLineNumber(" << strLine.length() << ")================" << endl; - - static QRegExp reBadBoxLines("(.*) at lines ([0-9]+)--([0-9]+)", Qt::CaseInsensitive); - static QRegExp reBadBoxLine("(.*) at line ([0-9]+)", Qt::CaseInsensitive); - //Use the following only, if you know how to get the source line for it. - // This is not simple, as TeX is not reporting it. - static QRegExp reBadBoxOutput("(.*)has occurred while \\output is active^", Qt::CaseInsensitive); - - if(reBadBoxLines.indexIn(strLine) != -1) { - dwCookie = Start; - strLine = reBadBoxLines.cap(1); - int n1 = reBadBoxLines.cap(2).toInt(); - int n2 = reBadBoxLines.cap(3).toInt(); - m_currentItem.setSourceLine(n1 < n2 ? n1 : n2); - return true; - } - else if(reBadBoxLine.indexIn(strLine) != -1) { - dwCookie = Start; - strLine = reBadBoxLine.cap(1); - m_currentItem.setSourceLine(reBadBoxLine.cap(2).toInt()); - //qCDebug(LOG_KILE_PARSER) << "\tBadBox@" << reBadBoxLine.cap(2) << "." << endl; - return true; - } - else if(reBadBoxOutput.indexIn(strLine) != -1) { - dwCookie = Start; - strLine = reBadBoxLines.cap(1); - m_currentItem.setSourceLine(0); - return true; - } - //bailing out, did not find a line number - else if((GetCurrentOutputLine() - m_currentItem.outputLine() > 3) || (len == 0)) { - dwCookie = Start; - m_currentItem.setSourceLine(0); - return true; - } - else { - dwCookie = BadBox; - } - - return false; + //qCDebug(LOG_KILE_PARSER) << "==LaTeXOutputParser::detectBadBoxLineNumber(" << strLine.length() << ")================" << endl; + + static QRegExp reBadBoxLines("(.*) at lines ([0-9]+)--([0-9]+)", Qt::CaseInsensitive); + static QRegExp reBadBoxLine("(.*) at line ([0-9]+)", Qt::CaseInsensitive); + //Use the following only, if you know how to get the source line for it. + // This is not simple, as TeX is not reporting it. + static QRegExp reBadBoxOutput("(.*)has occurred while \\output is active^", Qt::CaseInsensitive); + + if(reBadBoxLines.indexIn(strLine) != -1) { + dwCookie = Start; + strLine = reBadBoxLines.cap(1); + int n1 = reBadBoxLines.cap(2).toInt(); + int n2 = reBadBoxLines.cap(3).toInt(); + m_currentItem.setSourceLine(n1 < n2 ? n1 : n2); + return true; + } + else if(reBadBoxLine.indexIn(strLine) != -1) { + dwCookie = Start; + strLine = reBadBoxLine.cap(1); + m_currentItem.setSourceLine(reBadBoxLine.cap(2).toInt()); + //qCDebug(LOG_KILE_PARSER) << "\tBadBox@" << reBadBoxLine.cap(2) << "." << endl; + return true; + } + else if(reBadBoxOutput.indexIn(strLine) != -1) { + dwCookie = Start; + strLine = reBadBoxLines.cap(1); + m_currentItem.setSourceLine(0); + return true; + } + //bailing out, did not find a line number + else if((GetCurrentOutputLine() - m_currentItem.outputLine() > 3) || (len == 0)) { + dwCookie = Start; + m_currentItem.setSourceLine(0); + return true; + } + else { + dwCookie = BadBox; + } + + return false; } short LaTeXOutputParser::parseLine(const QString & strLine, short dwCookie) { - //qCDebug(LOG_KILE_PARSER) << "==LaTeXOutputParser::parseLine(" << strLine << dwCookie << strLine.length() << ")================" << endl; - - switch (dwCookie) { - case Start : - if(!(detectBadBox(strLine, dwCookie) || detectWarning(strLine, dwCookie) || detectError(strLine, dwCookie))) { - updateFileStack(strLine, dwCookie); - } - break; - - case Warning : - detectWarning(strLine, dwCookie); - break; - - case Error : case LineNumber : - detectError(strLine, dwCookie); - break; - - case BadBox : - detectBadBox(strLine, dwCookie); - break; - - case FileName : case FileNameHeuristic : - updateFileStack(strLine, dwCookie); - break; - - default: - dwCookie = Start; - break; - } - - return dwCookie; + //qCDebug(LOG_KILE_PARSER) << "==LaTeXOutputParser::parseLine(" << strLine << dwCookie << strLine.length() << ")================" << endl; + + switch (dwCookie) { + case Start : + if(!(detectBadBox(strLine, dwCookie) || detectWarning(strLine, dwCookie) || detectError(strLine, dwCookie))) { + updateFileStack(strLine, dwCookie); + } + break; + + case Warning : + detectWarning(strLine, dwCookie); + break; + + case Error : + case LineNumber : + detectError(strLine, dwCookie); + break; + + case BadBox : + detectBadBox(strLine, dwCookie); + break; + + case FileName : + case FileNameHeuristic : + updateFileStack(strLine, dwCookie); + break; + + default: + dwCookie = Start; + break; + } + + return dwCookie; } ParserOutput* LaTeXOutputParser::parse() { - LaTeXOutputParserOutput *parserOutput = new LaTeXOutputParserOutput(); - - qCDebug(LOG_KILE_PARSER); - - m_infoList = &(parserOutput->infoList); - m_nErrors = m_nWarnings = m_nBadBoxes = m_nParens = 0; - m_stackFile.clear(); - m_stackFile.push(LOFStackItem(QFileInfo(source()).fileName(), true)); - - short sCookie = 0; - QString s; - QFile f(m_logFile); - - m_log.clear(); - m_nOutputLines = 0; - - if(!f.open(QIODevice::ReadOnly)) { - parserOutput->problem = i18n("Cannot open log file; did you run LaTeX?"); - return parserOutput; - } - m_infoList = &parserOutput->infoList; - QTextStream t(&f); - while(!t.atEnd()) { - if(!m_parserThread->shouldContinueDocumentParsing()) { - qCDebug(LOG_KILE_PARSER) << "stopping..."; - delete(parserOutput); - f.close(); - return Q_NULLPTR; - } - s = t.readLine(); - sCookie = parseLine(s.trimmed(), sCookie); - ++m_nOutputLines; - - m_log += s + '\n'; - } - f.close(); - - parserOutput->nWarnings = m_nWarnings; - parserOutput->nErrors = m_nErrors; - parserOutput->nBadBoxes = m_nBadBoxes; - parserOutput->logFile = m_logFile; - - // for quick preview - if(!texfilename.isEmpty() && selrow >= 0 && docrow >= 0) { - updateInfoLists(texfilename, selrow, docrow); - } - - return parserOutput; + LaTeXOutputParserOutput *parserOutput = new LaTeXOutputParserOutput(); + + qCDebug(LOG_KILE_PARSER); + + m_infoList = &(parserOutput->infoList); + m_nErrors = m_nWarnings = m_nBadBoxes = m_nParens = 0; + m_stackFile.clear(); + m_stackFile.push(LOFStackItem(QFileInfo(source()).fileName(), true)); + + short sCookie = 0; + QString s; + QFile f(m_logFile); + + m_log.clear(); + m_nOutputLines = 0; + + if(!f.open(QIODevice::ReadOnly)) { + parserOutput->problem = i18n("Cannot open log file; did you run LaTeX?"); + return parserOutput; + } + m_infoList = &parserOutput->infoList; + QTextStream t(&f); + while(!t.atEnd()) { + if(!m_parserThread->shouldContinueDocumentParsing()) { + qCDebug(LOG_KILE_PARSER) << "stopping..."; + delete(parserOutput); + f.close(); + return Q_NULLPTR; + } + s = t.readLine(); + sCookie = parseLine(s.trimmed(), sCookie); + ++m_nOutputLines; + + m_log += s + '\n'; + } + f.close(); + + parserOutput->nWarnings = m_nWarnings; + parserOutput->nErrors = m_nErrors; + parserOutput->nBadBoxes = m_nBadBoxes; + parserOutput->logFile = m_logFile; + + // for quick preview + if(!texfilename.isEmpty() && selrow >= 0 && docrow >= 0) { + updateInfoLists(texfilename, selrow, docrow); + } + + return parserOutput; } void LaTeXOutputParser::updateInfoLists(const QString &texfilename, int selrow, int docrow) { - // get a short name for the original tex file - QString filename = "./" + QFileInfo(texfilename).fileName(); + // get a short name for the original tex file + QString filename = "./" + QFileInfo(texfilename).fileName(); // setSource(texfilename); - //print detailed error info - for(int i = 0; i < m_infoList->count(); ++i) { - // perhaps correct filename and line number in OutputInfo - OutputInfo &info = (*m_infoList)[i]; - info.setSource(filename); - - int linenumber = selrow + info.sourceLine() - docrow; - if(linenumber < 0) { - linenumber = 0; - } - info.setSourceLine(linenumber); - } + //print detailed error info + for(int i = 0; i < m_infoList->count(); ++i) { + // perhaps correct filename and line number in OutputInfo + OutputInfo &info = (*m_infoList)[i]; + info.setSource(filename); + + int linenumber = selrow + info.sourceLine() - docrow; + if(linenumber < 0) { + linenumber = 0; + } + info.setSourceLine(linenumber); + } } /** Return number of errors etc. found in log-file. */ void LaTeXOutputParser::getErrorCount(int *errors, int *warnings, int *badboxes) { *errors = m_nErrors; *warnings = m_nWarnings; *badboxes = m_nBadBoxes; } int LaTeXOutputParser::GetCurrentOutputLine() const { return m_nOutputLines; } void LaTeXOutputParser::setSource(const QString &src) { - m_source = src; - m_srcPath = QFileInfo(src).path(); + m_source = src; + m_srcPath = QFileInfo(src).path(); } } diff --git a/src/parser/latexoutputparser.h b/src/parser/latexoutputparser.h index d6b8f08f..f8a26f19 100644 --- a/src/parser/latexoutputparser.h +++ b/src/parser/latexoutputparser.h @@ -1,181 +1,197 @@ /********************************************************************************** * Copyright (C) 2003 by Jeroen Wijnhout (Jeroen.Wijnhout@kdemail.net) * * 2011 by Michel Ludwig (michel.ludwig@kdemail.net) * ***********************************************************************************/ /*************************************************************************** * * * 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. * * * ***************************************************************************/ #ifndef LATEXOUTPUTPARSER_H #define LATEXOUTPUTPARSER_H #include #include #include "kileconstants.h" #include "kileextensions.h" #include "outputinfo.h" #include "parser.h" namespace KileParser { class LaTeXOutputParserInput : public ParserInput { public: - LaTeXOutputParserInput(const QUrl &url, KileDocument::Extensions *extensions, - const QString& sourceFile, - // for QuickPreview - const QString &texfilename = "", int selrow = -1, int docrow = -1); - - KileDocument::Extensions *extensions; - QString sourceFile; - QString texfilename; - int selrow; - int docrow; + LaTeXOutputParserInput(const QUrl &url, KileDocument::Extensions *extensions, + const QString& sourceFile, + // for QuickPreview + const QString &texfilename = "", int selrow = -1, int docrow = -1); + + KileDocument::Extensions *extensions; + QString sourceFile; + QString texfilename; + int selrow; + int docrow; }; class LaTeXOutputParserOutput : public ParserOutput { public: - LaTeXOutputParserOutput(); - virtual ~LaTeXOutputParserOutput(); - - QString problem; - QString logFile; - LatexOutputInfoArray infoList; - int nWarnings; - int nErrors; - int nBadBoxes; + LaTeXOutputParserOutput(); + virtual ~LaTeXOutputParserOutput(); + + QString problem; + QString logFile; + LatexOutputInfoArray infoList; + int nWarnings; + int nErrors; + int nBadBoxes; }; class LOFStackItem { public: - explicit LOFStackItem(const QString& file = QString(), bool sure = false) : m_file(file), m_reliable(sure) {} - - const QString& file() const { return m_file; } - void setFile(const QString & file) { m_file = file; } - - bool reliable() const { return m_reliable; } - void setReliable(bool sure) { m_reliable = sure; } + explicit LOFStackItem(const QString& file = QString(), bool sure = false) : m_file(file), m_reliable(sure) {} + + const QString& file() const { + return m_file; + } + void setFile(const QString & file) { + m_file = file; + } + + bool reliable() const { + return m_reliable; + } + void setReliable(bool sure) { + m_reliable = sure; + } private: - QString m_file; - bool m_reliable; + QString m_file; + bool m_reliable; }; class LaTeXOutputParser : public Parser { - Q_OBJECT + Q_OBJECT public: - LaTeXOutputParser(ParserThread *parserThread, LaTeXOutputParserInput *input, QObject *parent = Q_NULLPTR); - virtual ~LaTeXOutputParser(); + LaTeXOutputParser(ParserThread *parserThread, LaTeXOutputParserInput *input, QObject *parent = Q_NULLPTR); + virtual ~LaTeXOutputParser(); - ParserOutput* parse(); + ParserOutput* parse(); - void updateInfoLists(const QString &texfilename, int selrow, int docrow); + void updateInfoLists(const QString &texfilename, int selrow, int docrow); - enum {Start = 0, FileName, FileNameHeuristic, Error, Warning, BadBox, LineNumber}; + enum {Start = 0, FileName, FileNameHeuristic, Error, Warning, BadBox, LineNumber}; - const QString& log() const { return m_log; } + const QString& log() const { + return m_log; + } - const QString& source() const { return m_source; } - const QString& path() const { return m_srcPath; } + const QString& source() const { + return m_source; + } + const QString& path() const { + return m_srcPath; + } protected: - /** - Parses the given line for the start of new files or the end of - old files. - */ - void updateFileStack(const QString &strLine, short & dwCookie); - void updateFileStackHeuristic(const QString &strLine, short & dwCookie); - - /** - Forwards the currently parsed item to the item list. - */ - void flushCurrentItem(); + /** + Parses the given line for the start of new files or the end of + old files. + */ + void updateFileStack(const QString &strLine, short & dwCookie); + void updateFileStackHeuristic(const QString &strLine, short & dwCookie); + + /** + Forwards the currently parsed item to the item list. + */ + void flushCurrentItem(); public: - /** Return number of errors etc. found in log-file. */ - void getErrorCount(int *errors, int *warnings, int *badboxes); - void clearErrorCount() { m_nErrors=m_nWarnings=m_nBadBoxes=0 ; } + /** Return number of errors etc. found in log-file. */ + void getErrorCount(int *errors, int *warnings, int *badboxes); + void clearErrorCount() { + m_nErrors=m_nWarnings=m_nBadBoxes=0 ; + } protected: - virtual short parseLine(const QString & strLine, short dwCookie); + virtual short parseLine(const QString & strLine, short dwCookie); - bool detectError(const QString & strLine, short &dwCookie); - bool detectWarning(const QString & strLine, short &dwCookie); - bool detectBadBox(const QString & strLine, short &dwCookie); - bool detectLaTeXLineNumber(QString & warning, short & dwCookie, int len); - bool detectBadBoxLineNumber(QString & strLine, short & dwCookie, int len); + bool detectError(const QString & strLine, short &dwCookie); + bool detectWarning(const QString & strLine, short &dwCookie); + bool detectBadBox(const QString & strLine, short &dwCookie); + bool detectLaTeXLineNumber(QString & warning, short & dwCookie, int len); + bool detectBadBoxLineNumber(QString & strLine, short & dwCookie, int len); - bool fileExists(const QString & name); + bool fileExists(const QString & name); protected: - /** - These constants are describing, which item types is currently - parsed. - */ - enum tagCookies - { - itmNone = 0, - itmError, - itmWarning, - itmBadBox - }; + /** + These constants are describing, which item types is currently + parsed. + */ + enum tagCookies + { + itmNone = 0, + itmError, + itmWarning, + itmBadBox + }; private: - KileDocument::Extensions *m_extensions; - /** number or errors detected */ - int m_nErrors; + KileDocument::Extensions *m_extensions; + /** number or errors detected */ + int m_nErrors; - /** number of warning detected */ - int m_nWarnings; + /** number of warning detected */ + int m_nWarnings; - /** number of bad boxes detected */ - int m_nBadBoxes; + /** number of bad boxes detected */ + int m_nBadBoxes; - int m_nParens; + int m_nParens; - int m_nOutputLines; - QString m_log, m_source, m_srcPath; + int m_nOutputLines; + QString m_log, m_source, m_srcPath; - /** Pointer to list of Latex output information */ - LatexOutputInfoArray *m_infoList; + /** Pointer to list of Latex output information */ + LatexOutputInfoArray *m_infoList; - QString m_logFile; + QString m_logFile; - // for QuickPreview - QString texfilename; - int selrow; - int docrow; + // for QuickPreview + QString texfilename; + int selrow; + int docrow; - /** - Stack containing the files parsed by the compiler. The top-most - element is the currently parsed file. - */ - QStack m_stackFile; + /** + Stack containing the files parsed by the compiler. The top-most + element is the currently parsed file. + */ + QStack m_stackFile; - /** The item currently parsed. */ - LatexOutputInfo m_currentItem; + /** The item currently parsed. */ + LatexOutputInfo m_currentItem; - /** - Returns the zero based index of the currently parsed line in the - output file. - */ - int GetCurrentOutputLine() const; + /** + Returns the zero based index of the currently parsed line in the + output file. + */ + int GetCurrentOutputLine() const; - void setSource(const QString &src); + void setSource(const QString &src); }; } #endif diff --git a/src/parser/latexparser.cpp b/src/parser/latexparser.cpp index 0148d0c8..8390aba1 100644 --- a/src/parser/latexparser.cpp +++ b/src/parser/latexparser.cpp @@ -1,428 +1,428 @@ /********************************************************************************** * Copyright (C) 2003 by Jeroen Wijnhout (Jeroen.Wijnhout@kdemail.net) * * 2005-2007 by Holger Danielsson (holger.danielsson@versanet.de) * * 2006-2017 by Michel Ludwig (michel.ludwig@kdemail.net) * ***********************************************************************************/ /*************************************************************************** * * * 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. * * * ***************************************************************************/ #include "latexparser.h" #include #include #include #include "codecompletion.h" #include "parserthread.h" namespace KileParser { LaTeXParserInput::LaTeXParserInput(const QUrl &url, QStringList textLines, - KileDocument::Extensions *extensions, - const QMap& dictStructLevel, - bool showSectioningLabels, - bool showStructureTodo) -: ParserInput(url), - textLines(textLines), - extensions(extensions), - dictStructLevel(dictStructLevel), - showSectioningLabels(showSectioningLabels), - showStructureTodo(showStructureTodo) + KileDocument::Extensions *extensions, + const QMap& dictStructLevel, + bool showSectioningLabels, + bool showStructureTodo) + : ParserInput(url), + textLines(textLines), + extensions(extensions), + dictStructLevel(dictStructLevel), + showSectioningLabels(showSectioningLabels), + showStructureTodo(showStructureTodo) { } LaTeXParserOutput::LaTeXParserOutput() -: bIsRoot(false) + : bIsRoot(false) { } LaTeXParserOutput::~LaTeXParserOutput() { qCDebug(LOG_KILE_PARSER); } LaTeXParser::LaTeXParser(ParserThread *parserThread, LaTeXParserInput *input, - QObject *parent) -: Parser(parserThread, parent), - m_extensions(input->extensions), - m_textLines(input->textLines), - m_dictStructLevel(input->dictStructLevel), - m_showSectioningLabels(input->showSectioningLabels), - m_showStructureTodo(input->showStructureTodo) + QObject *parent) + : Parser(parserThread, parent), + m_extensions(input->extensions), + m_textLines(input->textLines), + m_dictStructLevel(input->dictStructLevel), + m_showSectioningLabels(input->showSectioningLabels), + m_showStructureTodo(input->showStructureTodo) { } LaTeXParser::~LaTeXParser() { qCDebug(LOG_KILE_PARSER); } BracketResult LaTeXParser::matchBracket(const QStringList& textLines, int &l, int &pos) { - BracketResult result; - TodoResult todo; - - if((getTextLine(textLines, l))[pos] == '[') { - result.option = Parser::matchBracket(textLines, '[', l, pos); - int p = 0; - while(l < textLines.size()) { - if((p = processTextline(getTextLine(textLines, l), todo).indexOf('{', pos)) != -1) { - pos = p; - break; - } - else { - pos = 0; - ++l; - } - } - } - - if((getTextLine(textLines, l))[pos] == '{') { - result.line = l; - result.col = pos; - result.value = Parser::matchBracket(textLines, '{', l, pos); - } - - return result; + BracketResult result; + TodoResult todo; + + if((getTextLine(textLines, l))[pos] == '[') { + result.option = Parser::matchBracket(textLines, '[', l, pos); + int p = 0; + while(l < textLines.size()) { + if((p = processTextline(getTextLine(textLines, l), todo).indexOf('{', pos)) != -1) { + pos = p; + break; + } + else { + pos = 0; + ++l; + } + } + } + + if((getTextLine(textLines, l))[pos] == '{') { + result.line = l; + result.col = pos; + result.value = Parser::matchBracket(textLines, '{', l, pos); + } + + return result; } //FIXME: this has to be completely rewritten! ParserOutput* LaTeXParser::parse() { - LaTeXParserOutput *parserOutput = new LaTeXParserOutput(); - - qCDebug(LOG_KILE_PARSER) << m_textLines; - - QMap::const_iterator it; - static QRegExp reCommand("(\\\\[a-zA-Z]+)\\s*\\*?\\s*(\\{|\\[)"); - static QRegExp reRoot("\\\\documentclass|\\\\documentstyle"); - static QRegExp reBD("\\\\begin\\s*\\{\\s*document\\s*\\}"); - static QRegExp reReNewCommand("\\\\renewcommand.*$"); - static QRegExp reNumOfParams("\\s*\\[([1-9]+)\\]"); - static QRegExp reNumOfOptParams("\\s*\\[([1-9]+)\\]\\s*\\[([^\\{]*)\\]"); // the quantifier * isn't used by mistake, because also emtpy optional brackets are correct. - - int tagStart, bd = 0; - int tagEnd, tagLine = 0, tagCol = 0; - int tagStartLine = 0, tagStartCol = 0; - BracketResult result; - QString m, s, shorthand; - bool foundBD = false; // found \begin { document } - bool fire = true; //whether or not we should emit a foundItem signal - bool fireSuspended; // found an item, but it should not be fired (this time) - TodoResult todo; + LaTeXParserOutput *parserOutput = new LaTeXParserOutput(); + + qCDebug(LOG_KILE_PARSER) << m_textLines; + + QMap::const_iterator it; + static QRegExp reCommand("(\\\\[a-zA-Z]+)\\s*\\*?\\s*(\\{|\\[)"); + static QRegExp reRoot("\\\\documentclass|\\\\documentstyle"); + static QRegExp reBD("\\\\begin\\s*\\{\\s*document\\s*\\}"); + static QRegExp reReNewCommand("\\\\renewcommand.*$"); + static QRegExp reNumOfParams("\\s*\\[([1-9]+)\\]"); + static QRegExp reNumOfOptParams("\\s*\\[([1-9]+)\\]\\s*\\[([^\\{]*)\\]"); // the quantifier * isn't used by mistake, because also emtpy optional brackets are correct. + + int tagStart, bd = 0; + int tagEnd, tagLine = 0, tagCol = 0; + int tagStartLine = 0, tagStartCol = 0; + BracketResult result; + QString m, s, shorthand; + bool foundBD = false; // found \begin { document } + bool fire = true; //whether or not we should emit a foundItem signal + bool fireSuspended; // found an item, but it should not be fired (this time) + TodoResult todo; // emit(parsingStarted(m_doc->lines())); - for(int i = 0; i < m_textLines.size(); ++i) { - if(!m_parserThread->shouldContinueDocumentParsing()) { - qCDebug(LOG_KILE_PARSER) << "stopping..."; - delete(parserOutput); - return Q_NULLPTR; - } + for(int i = 0; i < m_textLines.size(); ++i) { + if(!m_parserThread->shouldContinueDocumentParsing()) { + qCDebug(LOG_KILE_PARSER) << "stopping..."; + delete(parserOutput); + return Q_NULLPTR; + } // emit(parsingUpdate(i)); - tagStart = tagEnd = 0; - fire = true; - s = processTextline(getTextLine(m_textLines, i), todo); - if(todo.type != -1 && m_showStructureTodo) { - QString folder = (todo.type == KileStruct::ToDo) ? "todo" : "fixme"; - parserOutput->structureViewItems.push_back(new StructureViewItem(todo.comment, i+1, todo.colComment, todo.type, KileStruct::Object, i+1, todo.colTag, QString(), folder)); - } + tagStart = tagEnd = 0; + fire = true; + s = processTextline(getTextLine(m_textLines, i), todo); + if(todo.type != -1 && m_showStructureTodo) { + QString folder = (todo.type == KileStruct::ToDo) ? "todo" : "fixme"; + parserOutput->structureViewItems.push_back(new StructureViewItem(todo.comment, i+1, todo.colComment, todo.type, KileStruct::Object, i+1, todo.colTag, QString(), folder)); + } - if(s.isEmpty()) { - continue; - } + if(s.isEmpty()) { + continue; + } - //ignore renewcommands - s.remove(reReNewCommand); + //ignore renewcommands + s.remove(reReNewCommand); - //find all commands in this line - while(tagStart != -1) { - if((!foundBD) && ((bd = s.indexOf(reBD, tagEnd)) != -1)) { - qCDebug(LOG_KILE_PARSER) << "\tfound \\begin{document}"; - foundBD = true; - parserOutput->preamble.clear(); + //find all commands in this line + while(tagStart != -1) { + if((!foundBD) && ((bd = s.indexOf(reBD, tagEnd)) != -1)) { + qCDebug(LOG_KILE_PARSER) << "\tfound \\begin{document}"; + foundBD = true; + parserOutput->preamble.clear(); //FIXME: improve this - if(bd == 0) { - if(i - 1 >= 0) { - for(int j = 0; j <= i - 1; ++j) { - parserOutput->preamble += getTextLine(m_textLines, j) + '\n'; - } - } - } - else { - if(i - 1 >= 0) { - for(int j = 0; j <= i - 1; ++j) { - parserOutput->preamble += getTextLine(m_textLines, j) + '\n'; - } - } - parserOutput->preamble += getTextLine(m_textLines, i).left(bd) + '\n'; - } - } - - if((!foundBD) && (s.indexOf(reRoot, tagEnd) != -1)) { - qCDebug(LOG_KILE_PARSER) << "\tsetting m_bIsRoot to true"; - tagEnd += reRoot.cap(0).length(); - parserOutput->bIsRoot = true; - } - - tagStart = reCommand.indexIn(s, tagEnd); - m.clear(); - shorthand.clear(); - - if(tagStart != -1) { - tagEnd = tagStart + reCommand.cap(0).length()-1; - - //look up the command in the dictionary - it = m_dictStructLevel.constFind(reCommand.cap(1)); - - //if it is was a structure element, find the title (or label) - if(it != m_dictStructLevel.constEnd()) { - tagLine = i+1; - tagCol = tagEnd+1; - tagStartLine = tagLine; - tagStartCol = tagStart+1; - - if(reCommand.cap(1) != "\\frame") { - result = matchBracket(m_textLines, i, tagEnd); - m = result.value.trimmed(); - shorthand = result.option.trimmed(); - if(i >= tagLine) { //matching brackets spanned multiple lines - s = getTextLine(m_textLines, i); - } - if(result.line > 0 || result.col > 0) { - tagLine = result.line + 1; - tagCol = result.col + 1; - } - //qCDebug(LOG_KILE_PARSER) << "\tgrabbed: " << reCommand.cap(1) << "[" << shorthand << "]{" << m << "}"; - } - else { - m = i18n("Frame"); - } - } - - //title (or label) found, add the element to the listview - if(!m.isNull()) { - // no problems so far ... - fireSuspended = false; - - // remove trailing ./ - if((*it).type & (KileStruct::Input | KileStruct::Graphics)) { - if(m.left(2) == "./") { - m = m.mid(2, m.length() - 2); - } - } - // update parameter for environments, because only - // floating environments and beamer frames are passed - if ( (*it).type == KileStruct::BeginEnv ) - { - if ( m=="figure" || m=="figure*" || m=="table" || m=="table*" ) - { - it = m_dictStructLevel.constFind("\\begin{" + m +'}'); - } - else if(m == "asy") { - it = m_dictStructLevel.constFind("\\begin{" + m +'}'); - parserOutput->asyFigures.append(m); - } - else if(m == "frame") { - const QString untitledFrameDisplayName = i18n("Frame"); - it = m_dictStructLevel.constFind("\\begin{frame}"); - if(tagEnd+1 < s.size() && s.at(tagEnd+1) == '{') { - tagEnd++; - result = matchBracket(m_textLines, i, tagEnd); - m = result.value.trimmed(); - if(m.isEmpty()) { - m = untitledFrameDisplayName; - } - } - else { - m = untitledFrameDisplayName; - } - } - else if(m=="block" || m=="exampleblock" || m=="alertblock") { - const QString untitledBlockDisplayName = i18n("Untitled Block"); - it = m_dictStructLevel.constFind("\\begin{block}"); - if(tagEnd+1 < s.size() && s.at(tagEnd+1) == '{') { - tagEnd++; - result = matchBracket(m_textLines, i, tagEnd); - m = result.value.trimmed(); - if(m.isEmpty()) { - m = untitledBlockDisplayName; - } - } - else { - m = untitledBlockDisplayName; - } - } - else { - fireSuspended = true; // only floats and beamer frames, no other environments - } - } - - // tell structure view that a floating environment or a beamer frame must be closed - else if ( (*it).type == KileStruct::EndEnv ) - { - if ( m=="figure" || m== "figure*" || m=="table" || m=="table*" || m=="asy") - { - it = m_dictStructLevel.constFind("\\end{float}"); - } - else if(m == "frame") { - it = m_dictStructLevel.constFind("\\end{frame}"); - } - else { - fireSuspended = true; // only floats, no other environments - } - } - // sectioning commands - else if((*it).type == KileStruct::Sect) { - if(!shorthand.isEmpty()) { - m = shorthand; - } - } - - // update the label list - else if((*it).type == KileStruct::Label) { - parserOutput->labels.append(m); - // label entry as child of sectioning - if(m_showSectioningLabels) { - parserOutput->structureViewItems.push_back(new StructureViewItem(m, tagLine, tagCol, KileStruct::Label, KileStruct::Object, tagStartLine, tagStartCol, "label", "root")); - fireSuspended = true; - } - } - - // update the references list - else if((*it).type == KileStruct::Reference) { - // m_references.append(m); - //fireSuspended = true; // don't emit references - } - - // update the dependencies - else if((*it).type == KileStruct::Input) { - // \input- or \include-commands can be used without extension. So we check - // if an extension exists. If not the default extension is added - // ( LaTeX reference says that this is '.tex'). This assures that - // all files, which are listed in the structure view, have an extension. - QString ext = QFileInfo(m).completeSuffix(); - if(ext.isEmpty()) { - m += m_extensions->latexDocumentDefault(); - } - parserOutput->deps.append(m); - } - - // update the referenced Bib files - else if((*it).type == KileStruct::Bibliography) { - qCDebug(LOG_KILE_PARSER) << "===TeXInfo::updateStruct()===appending Bibiliograph file(s) " << m; - - const QStringList bibs = m.split(','); - QString biblio; - - // assure that all files have an extension - const QString bibtexExtension = m_extensions->bibtexDefault(); - for(QString biblio : bibs) { - biblio = biblio.trimmed(); - { - QString ext = QFileInfo(biblio).suffix(); - if(ext.isEmpty()) { - biblio += m_extensions->bibtexDefault(); - } - } - parserOutput->bibliography.append(biblio); - if(biblio.left(2) == "./") { - biblio = biblio.mid(2, biblio.length() - 2); - } - parserOutput->deps.append(biblio); - parserOutput->structureViewItems.push_back(new StructureViewItem(biblio, tagLine, tagCol, (*it).type, (*it).level, tagStartLine, tagStartCol, (*it).pix, (*it).folder)); - } - fire = false; - } - - // update the bibitem list - else if((*it).type == KileStruct::BibItem) { - //qCDebug(LOG_KILE_PARSER) << "\tappending bibitem " << m; - parserOutput->bibItems.append(m); - } - - // update the package list - else if((*it).type == KileStruct::Package) { - QStringList pckgs = m.split(','); - uint cumlen = 0; - for(int p = 0; p < pckgs.count(); ++p) { - QString package = pckgs[p].trimmed(); - if(!package.isEmpty()) { - parserOutput->packages.append(package); - // hidden, so emit is useless - // emit( foundItem(package, tagLine, tagCol+cumlen, (*it).type, (*it).level, tagStartLine, tagStartCol, (*it).pix, (*it).folder) ); - cumlen += package.length() + 1; - } - } - fire = false; - } - - // newcommand found, add it to the newCommands list - else if((*it).type & (KileStruct::NewCommand | KileStruct::NewEnvironment)) { - QString optArg, mandArgs; - - //find how many parameters this command takes - if(s.indexOf(reNumOfParams, tagEnd + 1) != -1) { - bool ok; - int noo = reNumOfParams.cap(1).toInt(&ok); - - if(ok) { - if(s.indexOf(reNumOfOptParams, tagEnd + 1) != -1) { - qCDebug(LOG_KILE_PARSER) << "Opt param is " << reNumOfOptParams.cap(2) << "%EOL"; - noo--; // if we have an opt argument, we have one mandatory argument less, and noo=0 can't occur because then latex complains (and we don't macht them with reNumOfParams either) - optArg = '[' + reNumOfOptParams.cap(2) + ']'; - } - - for(int noo_index = 0; noo_index < noo; ++noo_index) { - mandArgs += '{' + s_bullet + '}'; - } - - } - if(!optArg.isEmpty()) { - if((*it).type == KileStruct::NewEnvironment) { - parserOutput->newCommands.append(QString("\\begin{%1}%2%3").arg(m).arg(optArg).arg(mandArgs)); - } - else { - parserOutput->newCommands.append(m + optArg + mandArgs); - } - } - } - if((*it).type == KileStruct::NewEnvironment) { - parserOutput->newCommands.append(QString("\\begin{%1}%3").arg(m).arg(mandArgs)); - parserOutput->newCommands.append(QString("\\end{%1}").arg(m)); - } - else { - parserOutput->newCommands.append(m + mandArgs); - } - //FIXME set tagEnd to the end of the command definition - break; - } - // and some other commands, which don't need special actions: - // \caption, ... - - // qCDebug(LOG_KILE_PARSER) << "\t\temitting: " << m; - if(fire && !fireSuspended) { - parserOutput->structureViewItems.push_back(new StructureViewItem(m, tagLine, tagCol, (*it).type, (*it).level, tagStartLine, tagStartCol, (*it).pix, (*it).folder)); - } - } //if m - } // if tagStart - } // while tagStart - } //for - - qCDebug(LOG_KILE_PARSER) << "done"; - return parserOutput; + if(bd == 0) { + if(i - 1 >= 0) { + for(int j = 0; j <= i - 1; ++j) { + parserOutput->preamble += getTextLine(m_textLines, j) + '\n'; + } + } + } + else { + if(i - 1 >= 0) { + for(int j = 0; j <= i - 1; ++j) { + parserOutput->preamble += getTextLine(m_textLines, j) + '\n'; + } + } + parserOutput->preamble += getTextLine(m_textLines, i).left(bd) + '\n'; + } + } + + if((!foundBD) && (s.indexOf(reRoot, tagEnd) != -1)) { + qCDebug(LOG_KILE_PARSER) << "\tsetting m_bIsRoot to true"; + tagEnd += reRoot.cap(0).length(); + parserOutput->bIsRoot = true; + } + + tagStart = reCommand.indexIn(s, tagEnd); + m.clear(); + shorthand.clear(); + + if(tagStart != -1) { + tagEnd = tagStart + reCommand.cap(0).length()-1; + + //look up the command in the dictionary + it = m_dictStructLevel.constFind(reCommand.cap(1)); + + //if it is was a structure element, find the title (or label) + if(it != m_dictStructLevel.constEnd()) { + tagLine = i+1; + tagCol = tagEnd+1; + tagStartLine = tagLine; + tagStartCol = tagStart+1; + + if(reCommand.cap(1) != "\\frame") { + result = matchBracket(m_textLines, i, tagEnd); + m = result.value.trimmed(); + shorthand = result.option.trimmed(); + if(i >= tagLine) { //matching brackets spanned multiple lines + s = getTextLine(m_textLines, i); + } + if(result.line > 0 || result.col > 0) { + tagLine = result.line + 1; + tagCol = result.col + 1; + } + //qCDebug(LOG_KILE_PARSER) << "\tgrabbed: " << reCommand.cap(1) << "[" << shorthand << "]{" << m << "}"; + } + else { + m = i18n("Frame"); + } + } + + //title (or label) found, add the element to the listview + if(!m.isNull()) { + // no problems so far ... + fireSuspended = false; + + // remove trailing ./ + if((*it).type & (KileStruct::Input | KileStruct::Graphics)) { + if(m.left(2) == "./") { + m = m.mid(2, m.length() - 2); + } + } + // update parameter for environments, because only + // floating environments and beamer frames are passed + if ( (*it).type == KileStruct::BeginEnv ) + { + if ( m=="figure" || m=="figure*" || m=="table" || m=="table*" ) + { + it = m_dictStructLevel.constFind("\\begin{" + m +'}'); + } + else if(m == "asy") { + it = m_dictStructLevel.constFind("\\begin{" + m +'}'); + parserOutput->asyFigures.append(m); + } + else if(m == "frame") { + const QString untitledFrameDisplayName = i18n("Frame"); + it = m_dictStructLevel.constFind("\\begin{frame}"); + if(tagEnd+1 < s.size() && s.at(tagEnd+1) == '{') { + tagEnd++; + result = matchBracket(m_textLines, i, tagEnd); + m = result.value.trimmed(); + if(m.isEmpty()) { + m = untitledFrameDisplayName; + } + } + else { + m = untitledFrameDisplayName; + } + } + else if(m=="block" || m=="exampleblock" || m=="alertblock") { + const QString untitledBlockDisplayName = i18n("Untitled Block"); + it = m_dictStructLevel.constFind("\\begin{block}"); + if(tagEnd+1 < s.size() && s.at(tagEnd+1) == '{') { + tagEnd++; + result = matchBracket(m_textLines, i, tagEnd); + m = result.value.trimmed(); + if(m.isEmpty()) { + m = untitledBlockDisplayName; + } + } + else { + m = untitledBlockDisplayName; + } + } + else { + fireSuspended = true; // only floats and beamer frames, no other environments + } + } + + // tell structure view that a floating environment or a beamer frame must be closed + else if ( (*it).type == KileStruct::EndEnv ) + { + if ( m=="figure" || m== "figure*" || m=="table" || m=="table*" || m=="asy") + { + it = m_dictStructLevel.constFind("\\end{float}"); + } + else if(m == "frame") { + it = m_dictStructLevel.constFind("\\end{frame}"); + } + else { + fireSuspended = true; // only floats, no other environments + } + } + // sectioning commands + else if((*it).type == KileStruct::Sect) { + if(!shorthand.isEmpty()) { + m = shorthand; + } + } + + // update the label list + else if((*it).type == KileStruct::Label) { + parserOutput->labels.append(m); + // label entry as child of sectioning + if(m_showSectioningLabels) { + parserOutput->structureViewItems.push_back(new StructureViewItem(m, tagLine, tagCol, KileStruct::Label, KileStruct::Object, tagStartLine, tagStartCol, "label", "root")); + fireSuspended = true; + } + } + + // update the references list + else if((*it).type == KileStruct::Reference) { + // m_references.append(m); + //fireSuspended = true; // don't emit references + } + + // update the dependencies + else if((*it).type == KileStruct::Input) { + // \input- or \include-commands can be used without extension. So we check + // if an extension exists. If not the default extension is added + // ( LaTeX reference says that this is '.tex'). This assures that + // all files, which are listed in the structure view, have an extension. + QString ext = QFileInfo(m).completeSuffix(); + if(ext.isEmpty()) { + m += m_extensions->latexDocumentDefault(); + } + parserOutput->deps.append(m); + } + + // update the referenced Bib files + else if((*it).type == KileStruct::Bibliography) { + qCDebug(LOG_KILE_PARSER) << "===TeXInfo::updateStruct()===appending Bibiliograph file(s) " << m; + + const QStringList bibs = m.split(','); + QString biblio; + + // assure that all files have an extension + const QString bibtexExtension = m_extensions->bibtexDefault(); + for(QString biblio : bibs) { + biblio = biblio.trimmed(); + { + QString ext = QFileInfo(biblio).suffix(); + if(ext.isEmpty()) { + biblio += m_extensions->bibtexDefault(); + } + } + parserOutput->bibliography.append(biblio); + if(biblio.left(2) == "./") { + biblio = biblio.mid(2, biblio.length() - 2); + } + parserOutput->deps.append(biblio); + parserOutput->structureViewItems.push_back(new StructureViewItem(biblio, tagLine, tagCol, (*it).type, (*it).level, tagStartLine, tagStartCol, (*it).pix, (*it).folder)); + } + fire = false; + } + + // update the bibitem list + else if((*it).type == KileStruct::BibItem) { + //qCDebug(LOG_KILE_PARSER) << "\tappending bibitem " << m; + parserOutput->bibItems.append(m); + } + + // update the package list + else if((*it).type == KileStruct::Package) { + QStringList pckgs = m.split(','); + uint cumlen = 0; + for(int p = 0; p < pckgs.count(); ++p) { + QString package = pckgs[p].trimmed(); + if(!package.isEmpty()) { + parserOutput->packages.append(package); + // hidden, so emit is useless + // emit( foundItem(package, tagLine, tagCol+cumlen, (*it).type, (*it).level, tagStartLine, tagStartCol, (*it).pix, (*it).folder) ); + cumlen += package.length() + 1; + } + } + fire = false; + } + + // newcommand found, add it to the newCommands list + else if((*it).type & (KileStruct::NewCommand | KileStruct::NewEnvironment)) { + QString optArg, mandArgs; + + //find how many parameters this command takes + if(s.indexOf(reNumOfParams, tagEnd + 1) != -1) { + bool ok; + int noo = reNumOfParams.cap(1).toInt(&ok); + + if(ok) { + if(s.indexOf(reNumOfOptParams, tagEnd + 1) != -1) { + qCDebug(LOG_KILE_PARSER) << "Opt param is " << reNumOfOptParams.cap(2) << "%EOL"; + noo--; // if we have an opt argument, we have one mandatory argument less, and noo=0 can't occur because then latex complains (and we don't macht them with reNumOfParams either) + optArg = '[' + reNumOfOptParams.cap(2) + ']'; + } + + for(int noo_index = 0; noo_index < noo; ++noo_index) { + mandArgs += '{' + s_bullet + '}'; + } + + } + if(!optArg.isEmpty()) { + if((*it).type == KileStruct::NewEnvironment) { + parserOutput->newCommands.append(QString("\\begin{%1}%2%3").arg(m).arg(optArg).arg(mandArgs)); + } + else { + parserOutput->newCommands.append(m + optArg + mandArgs); + } + } + } + if((*it).type == KileStruct::NewEnvironment) { + parserOutput->newCommands.append(QString("\\begin{%1}%3").arg(m).arg(mandArgs)); + parserOutput->newCommands.append(QString("\\end{%1}").arg(m)); + } + else { + parserOutput->newCommands.append(m + mandArgs); + } + //FIXME set tagEnd to the end of the command definition + break; + } + // and some other commands, which don't need special actions: + // \caption, ... + + // qCDebug(LOG_KILE_PARSER) << "\t\temitting: " << m; + if(fire && !fireSuspended) { + parserOutput->structureViewItems.push_back(new StructureViewItem(m, tagLine, tagCol, (*it).type, (*it).level, tagStartLine, tagStartCol, (*it).pix, (*it).folder)); + } + } //if m + } // if tagStart + } // while tagStart + } //for + + qCDebug(LOG_KILE_PARSER) << "done"; + return parserOutput; } } diff --git a/src/parser/latexparser.h b/src/parser/latexparser.h index 26b6ce0f..d12a72bc 100644 --- a/src/parser/latexparser.h +++ b/src/parser/latexparser.h @@ -1,89 +1,89 @@ /************************************************************************** * Copyright (C) 2011 by Michel Ludwig (michel.ludwig@kdemail.net) * ***************************************************************************/ /*************************************************************************** * * * 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. * * * ***************************************************************************/ #ifndef LATEXPARSER_H #define LATEXPARSER_H #include #include "documentinfo.h" #include "kileconstants.h" #include "kileextensions.h" #include "parser.h" namespace KileParser { struct BracketResult { - BracketResult() : line(0), col(0) {} - QString option, value; - int line, col; + BracketResult() : line(0), col(0) {} + QString option, value; + int line, col; }; class LaTeXParserInput : public ParserInput { public: - LaTeXParserInput(const QUrl &url, QStringList textLines, - KileDocument::Extensions *extensions, - const QMap& dictStructLevel, - bool showSectioningLabels, - bool showStructureTodo); - - QStringList textLines; - KileDocument::Extensions *extensions; - const QMap& dictStructLevel; - bool showSectioningLabels; - bool showStructureTodo; + LaTeXParserInput(const QUrl &url, QStringList textLines, + KileDocument::Extensions *extensions, + const QMap& dictStructLevel, + bool showSectioningLabels, + bool showStructureTodo); + + QStringList textLines; + KileDocument::Extensions *extensions; + const QMap& dictStructLevel; + bool showSectioningLabels; + bool showStructureTodo; }; class LaTeXParserOutput : public ParserOutput { public: - LaTeXParserOutput(); - virtual ~LaTeXParserOutput(); - - QStringList labels; - QStringList bibItems; - QStringList deps; - QStringList bibliography; - QStringList packages; - QStringList newCommands; - QStringList asyFigures; - QString preamble; - bool bIsRoot; + LaTeXParserOutput(); + virtual ~LaTeXParserOutput(); + + QStringList labels; + QStringList bibItems; + QStringList deps; + QStringList bibliography; + QStringList packages; + QStringList newCommands; + QStringList asyFigures; + QString preamble; + bool bIsRoot; }; class LaTeXParser : public Parser { - Q_OBJECT + Q_OBJECT public: - LaTeXParser(ParserThread *parserThread, LaTeXParserInput *input, - QObject *parent = Q_NULLPTR); - virtual ~LaTeXParser(); + LaTeXParser(ParserThread *parserThread, LaTeXParserInput *input, + QObject *parent = Q_NULLPTR); + virtual ~LaTeXParser(); - ParserOutput* parse(); + ParserOutput* parse(); protected: - KileDocument::Extensions *m_extensions; - QStringList m_textLines; - const QMap& m_dictStructLevel; - bool m_showSectioningLabels; - bool m_showStructureTodo; + KileDocument::Extensions *m_extensions; + QStringList m_textLines; + const QMap& m_dictStructLevel; + bool m_showSectioningLabels; + bool m_showStructureTodo; - BracketResult matchBracket(const QStringList& textLines, int &l, int &pos); + BracketResult matchBracket(const QStringList& textLines, int &l, int &pos); }; } #endif diff --git a/src/parser/parser.cpp b/src/parser/parser.cpp index 46b36730..44235638 100644 --- a/src/parser/parser.cpp +++ b/src/parser/parser.cpp @@ -1,162 +1,162 @@ /********************************************************************************** * Copyright (C) 2003 by Jeroen Wijnhout (Jeroen.Wijnhout@kdemail.net) * * 2005-2007 by Holger Danielsson (holger.danielsson@versanet.de) * * 2006-2011 by Michel Ludwig (michel.ludwig@kdemail.net) * ***********************************************************************************/ /*************************************************************************** * * * 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. * * * ***************************************************************************/ #include "parser.h" #include #include "parserthread.h" namespace KileParser { StructureViewItem::StructureViewItem(const QString &title, uint line, uint column, int type, int level, uint startline, uint startcol, - const QString &pix, const QString &folder) -: title(title), - line(line), - column(column), - type(type), - level(level), - startline(startline), - startcol(startcol), - pix(pix), - folder(folder) + const QString &pix, const QString &folder) + : title(title), + line(line), + column(column), + type(type), + level(level), + startline(startline), + startcol(startcol), + pix(pix), + folder(folder) { } StructureViewItem::~StructureViewItem() { } ParserInput::ParserInput(const QUrl &url) -: url(url) + : url(url) { } ParserInput::~ParserInput() { } ParserOutput::~ParserOutput() { - Q_FOREACH(StructureViewItem *item, structureViewItems) { - delete(item); - } + Q_FOREACH(StructureViewItem *item, structureViewItems) { + delete(item); + } } Parser::Parser(ParserThread *parserThread, QObject *parent) : - QObject(parent), - m_parserThread(parserThread) + QObject(parent), + m_parserThread(parserThread) { } Parser::~Parser() { } QString Parser::processTextline(const QString &line, TodoResult &todo) { - static QRegExp reComments("[^\\\\](%.*$)"); - QString s = line; - todo.type = -1; - if(!s.isEmpty()) { - // remove comment lines - if(s[0] == '%') { - searchTodoComment(s,0,todo); - s.clear(); - } - else { - //remove escaped \ characters - s.replace("\\\\", " "); - - //remove comments - int pos = s.indexOf(reComments); - if(pos != -1) { - searchTodoComment(s, pos,todo); - s = s.left(reComments.pos(1)); - } - } - } - return s; + static QRegExp reComments("[^\\\\](%.*$)"); + QString s = line; + todo.type = -1; + if(!s.isEmpty()) { + // remove comment lines + if(s[0] == '%') { + searchTodoComment(s,0,todo); + s.clear(); + } + else { + //remove escaped \ characters + s.replace("\\\\", " "); + + //remove comments + int pos = s.indexOf(reComments); + if(pos != -1) { + searchTodoComment(s, pos,todo); + s = s.left(reComments.pos(1)); + } + } + } + return s; } void Parser::searchTodoComment(const QString &s, uint startpos, TodoResult &todo) { - static QRegExp reTodoComment("\\b(TODO|FIXME)\\b(:|\\s)?\\s*(.*)"); - - if(s.indexOf(reTodoComment, startpos) != -1) { - todo.type = (reTodoComment.cap(1) == "TODO") ? KileStruct::ToDo : KileStruct::FixMe; - todo.colTag = reTodoComment.pos(1); - todo.colComment = reTodoComment.pos(3); - todo.comment = reTodoComment.cap(3).trimmed(); - } + static QRegExp reTodoComment("\\b(TODO|FIXME)\\b(:|\\s)?\\s*(.*)"); + + if(s.indexOf(reTodoComment, startpos) != -1) { + todo.type = (reTodoComment.cap(1) == "TODO") ? KileStruct::ToDo : KileStruct::FixMe; + todo.colTag = reTodoComment.pos(1); + todo.colComment = reTodoComment.pos(3); + todo.comment = reTodoComment.cap(3).trimmed(); + } } // match a { with the corresponding } // pos is the position of the { QString Parser::matchBracket(const QStringList& textLines, QChar obracket, int &l, int &pos) { - QChar cbracket; - if(obracket == '{') { - cbracket = '}'; - } - else if(obracket == '[') { - cbracket = ']'; - } - else if(obracket == '(') { - cbracket = ')'; - } - - QString line, grab = ""; - int count=0, len; - ++pos; - - TodoResult todo; - while(l < textLines.size()) { - line = processTextline(textLines[l], todo); - len = line.length(); - for (int i = pos; i < len; ++i) { - if(line[i] == '\\' && (line[i+1] == obracket || line[i+1] == cbracket)) { - ++i; - } - else if(line[i] == obracket) { - ++count; - } - else if(line[i] == cbracket) { - --count; - if (count < 0) { - pos = i; - return grab; - } - } - - grab += line[i]; - } - ++l; - pos = 0; - } - - return QString(); + QChar cbracket; + if(obracket == '{') { + cbracket = '}'; + } + else if(obracket == '[') { + cbracket = ']'; + } + else if(obracket == '(') { + cbracket = ')'; + } + + QString line, grab = ""; + int count=0, len; + ++pos; + + TodoResult todo; + while(l < textLines.size()) { + line = processTextline(textLines[l], todo); + len = line.length(); + for (int i = pos; i < len; ++i) { + if(line[i] == '\\' && (line[i+1] == obracket || line[i+1] == cbracket)) { + ++i; + } + else if(line[i] == obracket) { + ++count; + } + else if(line[i] == cbracket) { + --count; + if (count < 0) { + pos = i; + return grab; + } + } + + grab += line[i]; + } + ++l; + pos = 0; + } + + return QString(); } QString Parser::getTextLine(const QStringList& textLines, int line) { - if(line < 0 || line >= textLines.size()) { - return QString(); - } - return textLines[line]; + if(line < 0 || line >= textLines.size()) { + return QString(); + } + return textLines[line]; } } diff --git a/src/parser/parser.h b/src/parser/parser.h index 1c8cf5f5..9151362c 100644 --- a/src/parser/parser.h +++ b/src/parser/parser.h @@ -1,96 +1,96 @@ /************************************************************************** * Copyright (C) 2011 by Michel Ludwig (michel.ludwig@kdemail.net) * ***************************************************************************/ /*************************************************************************** * * * 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. * * * ***************************************************************************/ #ifndef PARSER_H #define PARSER_H #include #include #include class KileInfo; namespace KileDocument { - class Info; - class TextInfo; +class Info; +class TextInfo; } namespace KileParser { struct TodoResult { - int type; - uint colTag; - uint colComment; - QString comment; + int type; + uint colTag; + uint colComment; + QString comment; }; class ParserThread; class StructureViewItem { public: - StructureViewItem(const QString &title, uint line, uint column, int type, int level, uint startline, uint startcol, - const QString &pix, const QString &folder); - ~StructureViewItem(); - - QString title; - uint line; - uint column; - int type; - int level; - uint startline; - uint startcol; - QString pix; - QString folder; + StructureViewItem(const QString &title, uint line, uint column, int type, int level, uint startline, uint startcol, + const QString &pix, const QString &folder); + ~StructureViewItem(); + + QString title; + uint line; + uint column; + int type; + int level; + uint startline; + uint startcol; + QString pix; + QString folder; }; class ParserInput { public: - explicit ParserInput(const QUrl &url); - virtual ~ParserInput(); + explicit ParserInput(const QUrl &url); + virtual ~ParserInput(); - QUrl url; + QUrl url; }; class ParserOutput { public: - virtual ~ParserOutput(); + virtual ~ParserOutput(); - QLinkedList structureViewItems; + QLinkedList structureViewItems; }; class Parser : public QObject { - Q_OBJECT + Q_OBJECT public: - explicit Parser(ParserThread *parserThread, QObject *parent = Q_NULLPTR); - virtual ~Parser(); + explicit Parser(ParserThread *parserThread, QObject *parent = Q_NULLPTR); + virtual ~Parser(); - virtual ParserOutput* parse() = 0; + virtual ParserOutput* parse() = 0; protected: - ParserThread *m_parserThread; - - QString processTextline(const QString &line, TodoResult &todo); - void searchTodoComment(const QString &s, uint startpos, TodoResult &todo); - QString matchBracket(const QStringList& textLines, QChar obracket, int &l, int &pos); - // for now, we have to emulate the behaviour of 'KTextEditor::Document::line': - // we return an empty string if the given line number is invalid - QString getTextLine(const QStringList& textLines, int line); + ParserThread *m_parserThread; + + QString processTextline(const QString &line, TodoResult &todo); + void searchTodoComment(const QString &s, uint startpos, TodoResult &todo); + QString matchBracket(const QStringList& textLines, QChar obracket, int &l, int &pos); + // for now, we have to emulate the behaviour of 'KTextEditor::Document::line': + // we return an empty string if the given line number is invalid + QString getTextLine(const QStringList& textLines, int line); }; } #endif diff --git a/src/parser/parsermanager.cpp b/src/parser/parsermanager.cpp index 3c580f13..e441b62d 100644 --- a/src/parser/parsermanager.cpp +++ b/src/parser/parsermanager.cpp @@ -1,139 +1,139 @@ /************************************************************************** * Copyright (C) 2011-2014 by Michel Ludwig (michel.ludwig@kdemail.net) * ***************************************************************************/ /*************************************************************************** * * * 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. * * * ***************************************************************************/ #include "parsermanager.h" #include "documentinfo.h" #include "errorhandler.h" #include "kiledocmanager.h" #include "kileinfo.h" #include "kiletool_enums.h" #include "latexoutputparser.h" #include "parserthread.h" #include "widgets/logwidget.h" namespace KileParser { Manager::Manager(KileInfo *info, QObject *parent) : - QObject(parent), - m_ki(info) + QObject(parent), + m_ki(info) { - qCDebug(LOG_KILE_PARSER); - m_documentParserThread = new DocumentParserThread(m_ki, this); - // we have to make this connection 'blocking' to ensure that when 'ParserThread::isDocumentParsingComplete()' - // returns true, all document info objects have been passed the information obtained from parsing already - connect(m_documentParserThread, SIGNAL(parsingComplete(const QUrl&, KileParser::ParserOutput*)), - m_ki->docManager(), SLOT(handleParsingComplete(const QUrl&, KileParser::ParserOutput*)), Qt::BlockingQueuedConnection); - // the next two can't be made 'blocking' as they are emitted when a mutex is held - connect(m_documentParserThread, SIGNAL(parsingQueueEmpty()), - this, SIGNAL(documentParsingComplete()), Qt::QueuedConnection); - connect(m_documentParserThread, SIGNAL(parsingStarted()), - this, SIGNAL(documentParsingStarted()), Qt::QueuedConnection); - m_documentParserThread->start(); - - m_outputParserThread = new OutputParserThread(m_ki, this); - connect(m_outputParserThread, SIGNAL(parsingComplete(const QUrl&, KileParser::ParserOutput*)), - this, SLOT(handleOutputParsingComplete(const QUrl&, KileParser::ParserOutput*)), Qt::QueuedConnection); - m_outputParserThread->start(); + qCDebug(LOG_KILE_PARSER); + m_documentParserThread = new DocumentParserThread(m_ki, this); + // we have to make this connection 'blocking' to ensure that when 'ParserThread::isDocumentParsingComplete()' + // returns true, all document info objects have been passed the information obtained from parsing already + connect(m_documentParserThread, SIGNAL(parsingComplete(const QUrl&, KileParser::ParserOutput*)), + m_ki->docManager(), SLOT(handleParsingComplete(const QUrl&, KileParser::ParserOutput*)), Qt::BlockingQueuedConnection); + // the next two can't be made 'blocking' as they are emitted when a mutex is held + connect(m_documentParserThread, SIGNAL(parsingQueueEmpty()), + this, SIGNAL(documentParsingComplete()), Qt::QueuedConnection); + connect(m_documentParserThread, SIGNAL(parsingStarted()), + this, SIGNAL(documentParsingStarted()), Qt::QueuedConnection); + m_documentParserThread->start(); + + m_outputParserThread = new OutputParserThread(m_ki, this); + connect(m_outputParserThread, SIGNAL(parsingComplete(const QUrl&, KileParser::ParserOutput*)), + this, SLOT(handleOutputParsingComplete(const QUrl&, KileParser::ParserOutput*)), Qt::QueuedConnection); + m_outputParserThread->start(); } Manager::~Manager() { - qCDebug(LOG_KILE_PARSER) << "destroying..."; - m_documentParserThread->stopParsing(); - m_outputParserThread->stopParsing(); + qCDebug(LOG_KILE_PARSER) << "destroying..."; + m_documentParserThread->stopParsing(); + m_outputParserThread->stopParsing(); } void Manager::parseDocument(KileDocument::TextInfo* textInfo) { - qCDebug(LOG_KILE_PARSER) << textInfo; - m_documentParserThread->addDocument(textInfo); + qCDebug(LOG_KILE_PARSER) << textInfo; + m_documentParserThread->addDocument(textInfo); } void Manager::parseOutput(KileTool::Base *tool, const QString& fileName, const QString& sourceFile, - const QString& texFileName, int selrow, int docrow) + const QString& texFileName, int selrow, int docrow) { - qCDebug(LOG_KILE_PARSER) << fileName << sourceFile; - m_outputParserThread->addLaTeXLogFile(fileName, sourceFile, texFileName, selrow, docrow); - connect(tool, SIGNAL(aboutToBeDestroyed(KileTool::Base*)), - this, SLOT(removeToolFromUrlHash(KileTool::Base*)), Qt::UniqueConnection); - - // using 'fileName' directly is tricky as it might contain occurrences of '//' which are filtered out - // by QUrl (given as argument in 'handleOutputParsingComplete') and the matching won't work anymore; - // so we use QUrl already here - const QUrl url = QUrl::fromLocalFile(fileName); - if(!m_urlToToolHash.contains(url, tool)) { - m_urlToToolHash.insert(url, tool); - } + qCDebug(LOG_KILE_PARSER) << fileName << sourceFile; + m_outputParserThread->addLaTeXLogFile(fileName, sourceFile, texFileName, selrow, docrow); + connect(tool, SIGNAL(aboutToBeDestroyed(KileTool::Base*)), + this, SLOT(removeToolFromUrlHash(KileTool::Base*)), Qt::UniqueConnection); + + // using 'fileName' directly is tricky as it might contain occurrences of '//' which are filtered out + // by QUrl (given as argument in 'handleOutputParsingComplete') and the matching won't work anymore; + // so we use QUrl already here + const QUrl url = QUrl::fromLocalFile(fileName); + if(!m_urlToToolHash.contains(url, tool)) { + m_urlToToolHash.insert(url, tool); + } } bool Manager::isDocumentParsingComplete() { - return m_documentParserThread->isParsingComplete(); + return m_documentParserThread->isParsingComplete(); } void Manager::stopDocumentParsing(const QUrl &url) { - m_documentParserThread->removeDocument(url); + m_documentParserThread->removeDocument(url); } void Manager::handleOutputParsingComplete(const QUrl &url, KileParser::ParserOutput *output) { - qCDebug(LOG_KILE_PARSER) << url; - QList toolList = m_urlToToolHash.values(url); - m_urlToToolHash.remove(url); - - LaTeXOutputParserOutput *latexOutput = dynamic_cast(output); - if(!latexOutput) { - qCDebug(LOG_KILE_PARSER) << "Q_NULLPTR output given"; - return; - } - if(toolList.isEmpty()) { // no tool was found, which means that all the tools for 'url' - return; // have been killed and we do nothing - } - if(!latexOutput->problem.isEmpty()) { - m_ki->errorHandler()->printProblem(KileTool::Warning, latexOutput->problem); - return; - } - // use the returned list as the new global error information list - m_ki->errorHandler()->setMostRecentLogInformation(latexOutput->logFile, latexOutput->infoList); - // finally, inform the tools waiting for the error information - Q_FOREACH(KileTool::Base *tool, toolList) { - tool->installLaTeXOutputParserResult(latexOutput->nErrors, latexOutput->nWarnings, - latexOutput->nBadBoxes, - latexOutput->infoList, - latexOutput->logFile); - } + qCDebug(LOG_KILE_PARSER) << url; + QList toolList = m_urlToToolHash.values(url); + m_urlToToolHash.remove(url); + + LaTeXOutputParserOutput *latexOutput = dynamic_cast(output); + if(!latexOutput) { + qCDebug(LOG_KILE_PARSER) << "Q_NULLPTR output given"; + return; + } + if(toolList.isEmpty()) { // no tool was found, which means that all the tools for 'url' + return; // have been killed and we do nothing + } + if(!latexOutput->problem.isEmpty()) { + m_ki->errorHandler()->printProblem(KileTool::Warning, latexOutput->problem); + return; + } + // use the returned list as the new global error information list + m_ki->errorHandler()->setMostRecentLogInformation(latexOutput->logFile, latexOutput->infoList); + // finally, inform the tools waiting for the error information + Q_FOREACH(KileTool::Base *tool, toolList) { + tool->installLaTeXOutputParserResult(latexOutput->nErrors, latexOutput->nWarnings, + latexOutput->nBadBoxes, + latexOutput->infoList, + latexOutput->logFile); + } } void Manager::removeToolFromUrlHash(KileTool::Base *tool) { - QMultiHash::iterator i = m_urlToToolHash.begin(); - while(i != m_urlToToolHash.end()) { - const QUrl url = i.key(); - if(i.value() == tool) { - i = m_urlToToolHash.erase(i); - // any more mappings for 'url' -> 'tool' left? - if(!m_urlToToolHash.contains(url)) { - m_outputParserThread->removeFile(url.toLocalFile()); - } - } - else { - ++i; - } - } + QMultiHash::iterator i = m_urlToToolHash.begin(); + while(i != m_urlToToolHash.end()) { + const QUrl url = i.key(); + if(i.value() == tool) { + i = m_urlToToolHash.erase(i); + // any more mappings for 'url' -> 'tool' left? + if(!m_urlToToolHash.contains(url)) { + m_outputParserThread->removeFile(url.toLocalFile()); + } + } + else { + ++i; + } + } } } diff --git a/src/parser/parsermanager.h b/src/parser/parsermanager.h index 20ed4513..970abe36 100644 --- a/src/parser/parsermanager.h +++ b/src/parser/parsermanager.h @@ -1,77 +1,77 @@ /************************************************************************** * Copyright (C) 2011-2014 by Michel Ludwig (michel.ludwig@kdemail.net) * ***************************************************************************/ /*************************************************************************** * * * 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. * * * ***************************************************************************/ #ifndef PARSERMANAGER_H #define PARSERMANAGER_H #include #include #include #include #include class KileInfo; namespace KileDocument { - class Info; - class TextInfo; +class Info; +class TextInfo; } namespace KileTool { - class Base; +class Base; } namespace KileParser { class ParserOutput; class DocumentParserThread; class OutputParserThread; class Manager : public QObject { - Q_OBJECT + Q_OBJECT public: - explicit Manager(KileInfo *ki, QObject *parent = 0); - ~Manager(); + explicit Manager(KileInfo *ki, QObject *parent = 0); + ~Manager(); - void parseDocument(KileDocument::TextInfo* textInfo); + void parseDocument(KileDocument::TextInfo* textInfo); - void parseOutput(KileTool::Base *tool, const QString& fileName, const QString& sourceFile, - // for QuickPreview - const QString& texFileName = "", int selrow = -1, int docrow = -1); + void parseOutput(KileTool::Base *tool, const QString& fileName, const QString& sourceFile, + // for QuickPreview + const QString& texFileName = "", int selrow = -1, int docrow = -1); - bool isDocumentParsingComplete(); + bool isDocumentParsingComplete(); - void stopDocumentParsing(const QUrl &url); + void stopDocumentParsing(const QUrl &url); Q_SIGNALS: - void documentParsingComplete(); - void documentParsingStarted(); + void documentParsingComplete(); + void documentParsingStarted(); protected Q_SLOTS: - void handleOutputParsingComplete(const QUrl &url, KileParser::ParserOutput *output); + void handleOutputParsingComplete(const QUrl &url, KileParser::ParserOutput *output); - void removeToolFromUrlHash(KileTool::Base *tool); + void removeToolFromUrlHash(KileTool::Base *tool); private: - KileInfo *m_ki; - DocumentParserThread *m_documentParserThread; - OutputParserThread *m_outputParserThread; - QMultiHash m_urlToToolHash; + KileInfo *m_ki; + DocumentParserThread *m_documentParserThread; + OutputParserThread *m_outputParserThread; + QMultiHash m_urlToToolHash; }; } #endif diff --git a/src/parser/parserthread.cpp b/src/parser/parserthread.cpp index 8c7ea6d7..170d5eaf 100644 --- a/src/parser/parserthread.cpp +++ b/src/parser/parserthread.cpp @@ -1,305 +1,305 @@ /************************************************************************** * Copyright (C) 2011-2012 by Michel Ludwig (michel.ludwig@kdemail.net) * ***************************************************************************/ /*************************************************************************** * * * 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. * * * ***************************************************************************/ #include "parserthread.h" #include "documentinfo.h" #include "kiledocmanager.h" #include "kileinfo.h" #include "bibtexparser.h" #include "latexparser.h" #include "latexoutputparser.h" namespace KileParser { DocumentParserInput::DocumentParserInput(const QUrl &url, QStringList lines, - ParserType parserType, - const QMap* dictStructLevel, - bool showSectioningLabels, - bool showStructureTodo) -: ParserInput(url), - lines(lines), - parserType(parserType), - dictStructLevel(dictStructLevel), - showSectioningLabels(showSectioningLabels), - showStructureTodo(showStructureTodo) + ParserType parserType, + const QMap* dictStructLevel, + bool showSectioningLabels, + bool showStructureTodo) + : ParserInput(url), + lines(lines), + parserType(parserType), + dictStructLevel(dictStructLevel), + showSectioningLabels(showSectioningLabels), + showStructureTodo(showStructureTodo) { } ParserThread::ParserThread(KileInfo *info, QObject *parent) : - QThread(parent), - m_ki(info), - m_keepParserThreadAlive(true) + QThread(parent), + m_ki(info), + m_keepParserThreadAlive(true) { } ParserThread::~ParserThread() { - qCDebug(LOG_KILE_PARSER) << "destroying parser thread" << this; - stopParsing(); - // wait for the thread to finish before it is deleted at - // the end of this destructor - qCDebug(LOG_KILE_PARSER) << "waiting for parser thread to finish..."; - wait(); - // and delete remaining queue items (no mutex is required - // as the thread's execution has stopped) - qDeleteAll(m_parserQueue); + qCDebug(LOG_KILE_PARSER) << "destroying parser thread" << this; + stopParsing(); + // wait for the thread to finish before it is deleted at + // the end of this destructor + qCDebug(LOG_KILE_PARSER) << "waiting for parser thread to finish..."; + wait(); + // and delete remaining queue items (no mutex is required + // as the thread's execution has stopped) + qDeleteAll(m_parserQueue); } void ParserThread::addParserInput(ParserInput *input) { - qCDebug(LOG_KILE_PARSER) << input; - qCDebug(LOG_KILE_PARSER) << "trying to obtain m_parserMutex"; - - m_parserMutex.lock(); - // first, check whether the document is queued already - QQueue::iterator it = m_parserQueue.begin(); - for(; it != m_parserQueue.end(); ++it) { - if((*it)->url == input->url) { - break; - } - } - - if(it != m_parserQueue.end()) { - qCDebug(LOG_KILE_PARSER) << "document in queue already"; - *it = input; - } - else { - if(m_currentlyParsedUrl == input->url) { - qCDebug(LOG_KILE_PARSER) << "re-parsing document"; - // stop the parsing of the document - m_keepParsingDocument = false; - // and add it as first element to the queue - m_parserQueue.push_front(input); - } - else { - qCDebug(LOG_KILE_PARSER) << "adding to the end"; - m_parserQueue.push_back(input); - } - } - m_parserMutex.unlock(); - - // finally, wake up threads waiting for the queue to be filled - m_queueEmptyWaitCondition.wakeAll(); + qCDebug(LOG_KILE_PARSER) << input; + qCDebug(LOG_KILE_PARSER) << "trying to obtain m_parserMutex"; + + m_parserMutex.lock(); + // first, check whether the document is queued already + QQueue::iterator it = m_parserQueue.begin(); + for(; it != m_parserQueue.end(); ++it) { + if((*it)->url == input->url) { + break; + } + } + + if(it != m_parserQueue.end()) { + qCDebug(LOG_KILE_PARSER) << "document in queue already"; + *it = input; + } + else { + if(m_currentlyParsedUrl == input->url) { + qCDebug(LOG_KILE_PARSER) << "re-parsing document"; + // stop the parsing of the document + m_keepParsingDocument = false; + // and add it as first element to the queue + m_parserQueue.push_front(input); + } + else { + qCDebug(LOG_KILE_PARSER) << "adding to the end"; + m_parserQueue.push_back(input); + } + } + m_parserMutex.unlock(); + + // finally, wake up threads waiting for the queue to be filled + m_queueEmptyWaitCondition.wakeAll(); } void ParserThread::removeParserInput(const QUrl &url) { - qCDebug(LOG_KILE_PARSER) << url; - m_parserMutex.lock(); - // first, if the document is currently parsed, we stop the parsing - if(m_currentlyParsedUrl == url) { - qCDebug(LOG_KILE_PARSER) << "document currently being parsed"; - m_keepParsingDocument = false; - } - // nevertheless, we remove all traces of the document from the queue - for(QQueue::iterator it = m_parserQueue.begin(); it != m_parserQueue.end();) { - ParserInput *input = *it; - if(input->url == url) { - qCDebug(LOG_KILE_PARSER) << "found it"; - it = m_parserQueue.erase(it); - delete input; - } - else { - ++it; - } - } - m_parserMutex.unlock(); + qCDebug(LOG_KILE_PARSER) << url; + m_parserMutex.lock(); + // first, if the document is currently parsed, we stop the parsing + if(m_currentlyParsedUrl == url) { + qCDebug(LOG_KILE_PARSER) << "document currently being parsed"; + m_keepParsingDocument = false; + } + // nevertheless, we remove all traces of the document from the queue + for(QQueue::iterator it = m_parserQueue.begin(); it != m_parserQueue.end();) { + ParserInput *input = *it; + if(input->url == url) { + qCDebug(LOG_KILE_PARSER) << "found it"; + it = m_parserQueue.erase(it); + delete input; + } + else { + ++it; + } + } + m_parserMutex.unlock(); } void ParserThread::stopParsing() { - qCDebug(LOG_KILE_PARSER); - m_parserMutex.lock(); - - m_keepParserThreadAlive = false; - m_keepParsingDocument = false; - m_parserMutex.unlock(); - // wake all the threads that are still waiting for the queue to fill up - m_queueEmptyWaitCondition.wakeAll(); + qCDebug(LOG_KILE_PARSER); + m_parserMutex.lock(); + + m_keepParserThreadAlive = false; + m_keepParsingDocument = false; + m_parserMutex.unlock(); + // wake all the threads that are still waiting for the queue to fill up + m_queueEmptyWaitCondition.wakeAll(); } bool ParserThread::shouldContinueDocumentParsing() { - QMutexLocker locker(&m_parserMutex); - return m_keepParsingDocument; + QMutexLocker locker(&m_parserMutex); + return m_keepParsingDocument; } bool ParserThread::isParsingComplete() { - QMutexLocker locker(&m_parserMutex); - // as the parser queue might be empty but a document is still being parsed, - // we additionally have to check whether 'm_currentlyParsedUrl' is empty or not - return m_parserQueue.isEmpty() && m_currentlyParsedUrl.isEmpty(); + QMutexLocker locker(&m_parserMutex); + // as the parser queue might be empty but a document is still being parsed, + // we additionally have to check whether 'm_currentlyParsedUrl' is empty or not + return m_parserQueue.isEmpty() && m_currentlyParsedUrl.isEmpty(); } // the document that is currently parsed is always the head of the queue void ParserThread::run() { - ParserInput* currentParsedItem; - qCDebug(LOG_KILE_PARSER) << "starting up..."; - while(true) { - // first, try to extract the head of the queue - m_parserMutex.lock(); - // clear the variable currently parsed url; might be necessary from the previous iteration - m_currentlyParsedUrl = QUrl(); - // check if we should still be running before going to sleep - if(!m_keepParserThreadAlive) { - m_parserMutex.unlock(); - // remaining queue elements are deleted in the destructor - return; - } - // but if there are no items to be parsed, we go to sleep. - // However, we have to be careful and use a 'while' loop here - // as it can happen that an item is added to the queue but this - // thread is woken up only after it has been removed again. - while(m_parserQueue.size() == 0 && m_keepParserThreadAlive) { - qCDebug(LOG_KILE_PARSER) << "going to sleep..."; - emit(parsingQueueEmpty()); - m_queueEmptyWaitCondition.wait(&m_parserMutex); - qCDebug(LOG_KILE_PARSER) << "woken up..."; - } - // threads are woken up when an object of this class is destroyed; in - // that case the queue might still be empty - if(!m_keepParserThreadAlive) { - m_parserMutex.unlock(); - // remaining queue elements are deleted in the destructor - return; - } - Q_ASSERT(m_parserQueue.size() > 0); - qCDebug(LOG_KILE_PARSER) << "queue length" << m_parserQueue.length(); - // now, extract the head - currentParsedItem = m_parserQueue.dequeue(); - - m_keepParsingDocument = true; - m_currentlyParsedUrl = currentParsedItem->url; - emit(parsingStarted()); - m_parserMutex.unlock(); - - Parser *parser = createParser(currentParsedItem); - - ParserOutput *parserOutput = Q_NULLPTR; - if(parser) { - parserOutput = parser->parse(); - } - - delete currentParsedItem; - delete parser; - - // we also emit when 'parserOutput == Q_NULLPTR' as this will be used to indicate - // that some error has occurred; - // as this call will be blocking, one has to make sure that no mutex is held - emit(parsingComplete(m_currentlyParsedUrl, parserOutput)); - } - qCDebug(LOG_KILE_PARSER) << "leaving..."; - // remaining queue elements are deleted in the destructor + ParserInput* currentParsedItem; + qCDebug(LOG_KILE_PARSER) << "starting up..."; + while(true) { + // first, try to extract the head of the queue + m_parserMutex.lock(); + // clear the variable currently parsed url; might be necessary from the previous iteration + m_currentlyParsedUrl = QUrl(); + // check if we should still be running before going to sleep + if(!m_keepParserThreadAlive) { + m_parserMutex.unlock(); + // remaining queue elements are deleted in the destructor + return; + } + // but if there are no items to be parsed, we go to sleep. + // However, we have to be careful and use a 'while' loop here + // as it can happen that an item is added to the queue but this + // thread is woken up only after it has been removed again. + while(m_parserQueue.size() == 0 && m_keepParserThreadAlive) { + qCDebug(LOG_KILE_PARSER) << "going to sleep..."; + emit(parsingQueueEmpty()); + m_queueEmptyWaitCondition.wait(&m_parserMutex); + qCDebug(LOG_KILE_PARSER) << "woken up..."; + } + // threads are woken up when an object of this class is destroyed; in + // that case the queue might still be empty + if(!m_keepParserThreadAlive) { + m_parserMutex.unlock(); + // remaining queue elements are deleted in the destructor + return; + } + Q_ASSERT(m_parserQueue.size() > 0); + qCDebug(LOG_KILE_PARSER) << "queue length" << m_parserQueue.length(); + // now, extract the head + currentParsedItem = m_parserQueue.dequeue(); + + m_keepParsingDocument = true; + m_currentlyParsedUrl = currentParsedItem->url; + emit(parsingStarted()); + m_parserMutex.unlock(); + + Parser *parser = createParser(currentParsedItem); + + ParserOutput *parserOutput = Q_NULLPTR; + if(parser) { + parserOutput = parser->parse(); + } + + delete currentParsedItem; + delete parser; + + // we also emit when 'parserOutput == Q_NULLPTR' as this will be used to indicate + // that some error has occurred; + // as this call will be blocking, one has to make sure that no mutex is held + emit(parsingComplete(m_currentlyParsedUrl, parserOutput)); + } + qCDebug(LOG_KILE_PARSER) << "leaving..."; + // remaining queue elements are deleted in the destructor } DocumentParserThread::DocumentParserThread(KileInfo *info, QObject *parent) -: ParserThread(info, parent) + : ParserThread(info, parent) { } DocumentParserThread::~DocumentParserThread() { } Parser* DocumentParserThread::createParser(ParserInput *input) { - if(dynamic_cast(input)) { - return new LaTeXParser(this, dynamic_cast(input)); - } - else if(dynamic_cast(input)) { - return new BibTeXParser(this, dynamic_cast(input)); - } - - return Q_NULLPTR; + if(dynamic_cast(input)) { + return new LaTeXParser(this, dynamic_cast(input)); + } + else if(dynamic_cast(input)) { + return new BibTeXParser(this, dynamic_cast(input)); + } + + return Q_NULLPTR; } void DocumentParserThread::addDocument(KileDocument::TextInfo *textInfo) { - qCDebug(LOG_KILE_PARSER) << textInfo; - const QUrl url = m_ki->docManager()->urlFor(textInfo); - if(url.isEmpty()) { // if the url is empty (which can happen with new documents), - return; // we can't do anything as not even the results of the parsing can be displayed - } - - ParserInput* newItem = Q_NULLPTR; - if(dynamic_cast(textInfo)) { - newItem = new BibTeXParserInput(url, textInfo->documentContents()); - } - else { - newItem = new LaTeXParserInput(url, textInfo->documentContents(), - m_ki->extensions(), - textInfo->dictStructLevel(), - KileConfig::svShowSectioningLabels(), - KileConfig::svShowTodo()); - } - addParserInput(newItem); - - // It is not very useful to watch for the destruction of 'textInfo' here and stop the parsing - // for 'textInfo' whenever that happens as at that moment it probably won't have a document - // anymore nor would it still be associated with a project item. - // It is better to call 'removeDocument' from the point when 'textInfo' is going to be deleted! + qCDebug(LOG_KILE_PARSER) << textInfo; + const QUrl url = m_ki->docManager()->urlFor(textInfo); + if(url.isEmpty()) { // if the url is empty (which can happen with new documents), + return; // we can't do anything as not even the results of the parsing can be displayed + } + + ParserInput* newItem = Q_NULLPTR; + if(dynamic_cast(textInfo)) { + newItem = new BibTeXParserInput(url, textInfo->documentContents()); + } + else { + newItem = new LaTeXParserInput(url, textInfo->documentContents(), + m_ki->extensions(), + textInfo->dictStructLevel(), + KileConfig::svShowSectioningLabels(), + KileConfig::svShowTodo()); + } + addParserInput(newItem); + + // It is not very useful to watch for the destruction of 'textInfo' here and stop the parsing + // for 'textInfo' whenever that happens as at that moment it probably won't have a document + // anymore nor would it still be associated with a project item. + // It is better to call 'removeDocument' from the point when 'textInfo' is going to be deleted! } void DocumentParserThread::removeDocument(KileDocument::TextInfo *textInfo) { - qCDebug(LOG_KILE_PARSER); - KTextEditor::Document *document = textInfo->getDoc(); - if(!document) { - return; - } - removeParserInput(document->url()); + qCDebug(LOG_KILE_PARSER); + KTextEditor::Document *document = textInfo->getDoc(); + if(!document) { + return; + } + removeParserInput(document->url()); } void DocumentParserThread::removeDocument(const QUrl &url) { - removeParserInput(url); + removeParserInput(url); } OutputParserThread::OutputParserThread(KileInfo *info, QObject *parent) -: ParserThread(info, parent) + : ParserThread(info, parent) { } OutputParserThread::~OutputParserThread() { } Parser* OutputParserThread::createParser(ParserInput *input) { if(dynamic_cast(input)) { - return new LaTeXOutputParser(this, dynamic_cast(input)); + return new LaTeXOutputParser(this, dynamic_cast(input)); } return Q_NULLPTR; } void OutputParserThread::addLaTeXLogFile(const QString& logFile, const QString& sourceFile, - const QString& texFileName, int selrow, int docrow) + const QString& texFileName, int selrow, int docrow) { - qCDebug(LOG_KILE_PARSER) << logFile << sourceFile; + qCDebug(LOG_KILE_PARSER) << logFile << sourceFile; - ParserInput* newItem = new LaTeXOutputParserInput(QUrl::fromLocalFile(logFile), m_ki->extensions(), - sourceFile, - texFileName, selrow, docrow); - addParserInput(newItem); + ParserInput* newItem = new LaTeXOutputParserInput(QUrl::fromLocalFile(logFile), m_ki->extensions(), + sourceFile, + texFileName, selrow, docrow); + addParserInput(newItem); } void OutputParserThread::removeFile(const QString& fileName) { - removeParserInput(QUrl::fromLocalFile(fileName)); + removeParserInput(QUrl::fromLocalFile(fileName)); } } diff --git a/src/parser/parserthread.h b/src/parser/parserthread.h index 8496f338..7206ea70 100644 --- a/src/parser/parserthread.h +++ b/src/parser/parserthread.h @@ -1,146 +1,146 @@ /************************************************************************** * Copyright (C) 2011-2012 by Michel Ludwig (michel.ludwig@kdemail.net) * ***************************************************************************/ /*************************************************************************** * * * 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. * * * ***************************************************************************/ #ifndef PARSERTHREAD_H #define PARSERTHREAD_H #include #include #include #include #include #include #include "documentinfo.h" #include "parser.h" class KileInfo; namespace KileDocument { - class Info; - class TextInfo; +class Info; +class TextInfo; } namespace KileParser { class Parser; class ParserInput; class ParserOutput; enum ParserType { LaTeX = 0, BibTeX }; // NOTE: we cannot store pointer to TextInfo objects in the queue // as this would cause too many problems when they are deleted // and their content is still being parsed class DocumentParserInput : public ParserInput { public: - DocumentParserInput(const QUrl &url, QStringList lines, - ParserType parserType, - const QMap* dictStructLevel, - bool showSectioningLabels, - bool showStructureTodo); - - QStringList lines; - ParserType parserType; - const QMap* dictStructLevel; - bool showSectioningLabels; - bool showStructureTodo; + DocumentParserInput(const QUrl &url, QStringList lines, + ParserType parserType, + const QMap* dictStructLevel, + bool showSectioningLabels, + bool showStructureTodo); + + QStringList lines; + ParserType parserType; + const QMap* dictStructLevel; + bool showSectioningLabels; + bool showStructureTodo; }; class ParserThread : public QThread { - Q_OBJECT + Q_OBJECT public: - ParserThread(KileInfo *info, QObject *parent = 0); - virtual ~ParserThread(); + ParserThread(KileInfo *info, QObject *parent = 0); + virtual ~ParserThread(); - void stopParsing(); + void stopParsing(); - bool shouldContinueDocumentParsing(); + bool shouldContinueDocumentParsing(); - bool isParsingComplete(); + bool isParsingComplete(); Q_SIGNALS: - /** - * The ownership of the 'output' object is transferred to the slot(s) - * connected to this signal. - **/ - void parsingComplete(const QUrl &url, KileParser::ParserOutput* output); + /** + * The ownership of the 'output' object is transferred to the slot(s) + * connected to this signal. + **/ + void parsingComplete(const QUrl &url, KileParser::ParserOutput* output); - void parsingQueueEmpty(); - void parsingStarted(); + void parsingQueueEmpty(); + void parsingStarted(); protected: - KileInfo *m_ki; + KileInfo *m_ki; - void addParserInput(ParserInput *input); - void removeParserInput(const QUrl &url); + void addParserInput(ParserInput *input); + void removeParserInput(const QUrl &url); - void run(); + void run(); - virtual Parser* createParser(ParserInput *input) = 0; + virtual Parser* createParser(ParserInput *input) = 0; private: - bool m_keepParserThreadAlive; - bool m_keepParsingDocument; - QQueue m_parserQueue; - QUrl m_currentlyParsedUrl; - QMutex m_parserMutex; - QWaitCondition m_queueEmptyWaitCondition; + bool m_keepParserThreadAlive; + bool m_keepParsingDocument; + QQueue m_parserQueue; + QUrl m_currentlyParsedUrl; + QMutex m_parserMutex; + QWaitCondition m_queueEmptyWaitCondition; }; class DocumentParserThread : public ParserThread { - Q_OBJECT + Q_OBJECT public: - DocumentParserThread(KileInfo *info, QObject *parent = Q_NULLPTR); - virtual ~DocumentParserThread(); + DocumentParserThread(KileInfo *info, QObject *parent = Q_NULLPTR); + virtual ~DocumentParserThread(); public Q_SLOTS: - void addDocument(KileDocument::TextInfo *textInfo); - void removeDocument(KileDocument::TextInfo *textInfo); - void removeDocument(const QUrl &url); + void addDocument(KileDocument::TextInfo *textInfo); + void removeDocument(KileDocument::TextInfo *textInfo); + void removeDocument(const QUrl &url); protected: - virtual Parser* createParser(ParserInput *input); + virtual Parser* createParser(ParserInput *input); }; class OutputParserThread: public ParserThread { - Q_OBJECT + Q_OBJECT public: - OutputParserThread(KileInfo *info, QObject *parent = Q_NULLPTR); - virtual ~OutputParserThread(); + OutputParserThread(KileInfo *info, QObject *parent = Q_NULLPTR); + virtual ~OutputParserThread(); public Q_SLOTS: - void addLaTeXLogFile(const QString& logFile, const QString& sourceFile, - // for QuickPreview - const QString& texFileName = "", int selrow = -1, int docrow = -1); - void removeFile(const QString& fileName); + void addLaTeXLogFile(const QString& logFile, const QString& sourceFile, + // for QuickPreview + const QString& texFileName = "", int selrow = -1, int docrow = -1); + void removeFile(const QString& fileName); protected: - virtual Parser* createParser(ParserInput *input); + virtual Parser* createParser(ParserInput *input); }; } #endif diff --git a/src/plaintolatexconverter.cpp b/src/plaintolatexconverter.cpp index aeae250c..abc14d4a 100644 --- a/src/plaintolatexconverter.cpp +++ b/src/plaintolatexconverter.cpp @@ -1,66 +1,66 @@ /* * * Copyright (C) 2004 Simon Martin * * 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, see . * */ #include "plaintolatexconverter.h" PlainToLaTeXConverter::PlainToLaTeXConverter(void) { - // Fill the replacement map - //TODO Do it only once! - m_replaceMap.insert('$', "\\$"); - m_replaceMap.insert('%', "\\%"); - m_replaceMap.insert('^', "\\^"); - m_replaceMap.insert('&', "\\&"); - m_replaceMap.insert('_', "\\_"); - m_replaceMap.insert('#', "\\#"); - m_replaceMap.insert('{', "\\{"); - m_replaceMap.insert('}', "\\}"); - m_replaceMap.insert('~', "$\\sim$"); + // Fill the replacement map + //TODO Do it only once! + m_replaceMap.insert('$', "\\$"); + m_replaceMap.insert('%', "\\%"); + m_replaceMap.insert('^', "\\^"); + m_replaceMap.insert('&', "\\&"); + m_replaceMap.insert('_', "\\_"); + m_replaceMap.insert('#', "\\#"); + m_replaceMap.insert('{', "\\{"); + m_replaceMap.insert('}', "\\}"); + m_replaceMap.insert('~', "$\\sim$"); } PlainToLaTeXConverter::~PlainToLaTeXConverter(void) {} /** * Converts plain text to LaTeX. * @param toConv The string to convert * @return The conversion's result */ QString PlainToLaTeXConverter::ConvertToLaTeX(const QString& toConv) const { - QString result(toConv); + QString result(toConv); - // Replacing what must be... - uint sSize = result.length(); - QMap::const_iterator mapEnd = m_replaceMap.end(); - for(uint i = 0 ; i < sSize ; ++i) - { - QMap::const_iterator it = m_replaceMap.find(result.at(i)); + // Replacing what must be... + uint sSize = result.length(); + QMap::const_iterator mapEnd = m_replaceMap.end(); + for(uint i = 0 ; i < sSize ; ++i) + { + QMap::const_iterator it = m_replaceMap.find(result.at(i)); - if(it != mapEnd) { // The character must be replaced - result.replace(i, 1, *it); - uint len = (*it).length(); - if(1 < len) { - i += len - 1; - sSize += len - 1; - } - } - } + if(it != mapEnd) { // The character must be replaced + result.replace(i, 1, *it); + uint len = (*it).length(); + if(1 < len) { + i += len - 1; + sSize += len - 1; + } + } + } - return result; + return result; } diff --git a/src/plaintolatexconverter.h b/src/plaintolatexconverter.h index 7733f4b3..77aad8e9 100644 --- a/src/plaintolatexconverter.h +++ b/src/plaintolatexconverter.h @@ -1,42 +1,42 @@ /* * * Copyright (C) 2004 Simon Martin * * 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, see . * */ #ifndef _PLAINTOLATEXCONVERTER_H_ #define _PLAINTOLATEXCONVERTER_H_ #include #include /** * A class that replaces the selection in the document (plain text) by its * "LaTeX version" (ie. "_" -> "\_", "%" -> "\%"...). */ class PlainToLaTeXConverter { public: - PlainToLaTeXConverter(void); - ~PlainToLaTeXConverter(void); + PlainToLaTeXConverter(void); + ~PlainToLaTeXConverter(void); - QString ConvertToLaTeX(const QString&) const; + QString ConvertToLaTeX(const QString&) const; private: - QMap m_replaceMap; + QMap m_replaceMap; }; #endif /* _PLAINTOLATEXCONVERTER_H_ */ diff --git a/src/quickpreview.cpp b/src/quickpreview.cpp index a050901c..379dda6a 100644 --- a/src/quickpreview.cpp +++ b/src/quickpreview.cpp @@ -1,390 +1,390 @@ /************************************************************************************************** Copyright (C) 2005-2007 by Holger Danielsson (holger.danielsson@versanet.de) 2007-2009 by Michel Ludwig (michel.ludwig@kdemail.net) **************************************************************************************************/ /*************************************************************************** * * * 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. * * * ***************************************************************************/ #include "quickpreview.h" #include "kiletool_enums.h" #include "kiledocmanager.h" #include "widgets/logwidget.h" #include #include #include #include #include #include #include #include #include #include "errorhandler.h" #include "kileconstants.h" #include "kiledebug.h" namespace KileTool { QuickPreview::QuickPreview(KileInfo *ki) : m_ki(ki), m_running(0), m_tempDir(Q_NULLPTR) { - m_taskList << i18n("LaTeX ---> DVI (Okular)") - << i18n("LaTeX ---> DVI (Document Viewer)") - << i18n("LaTeX ---> PS (Okular)") - << i18n("LaTeX ---> PS (Document Viewer)") - << i18n("PDFLaTeX ---> PDF (Okular)") - << i18n("PDFLaTeX ---> PDF (Document Viewer)") - << i18n("XeLaTeX ---> PDF (Okular)") - << i18n("XeLaTeX ---> PDF (Document Viewer)") - << i18n("LuaLaTeX ---> PDF (Okular)") - << i18n("LuaLaTeX ---> PDF (Document Viewer)") - ; + m_taskList << i18n("LaTeX ---> DVI (Okular)") + << i18n("LaTeX ---> DVI (Document Viewer)") + << i18n("LaTeX ---> PS (Okular)") + << i18n("LaTeX ---> PS (Document Viewer)") + << i18n("PDFLaTeX ---> PDF (Okular)") + << i18n("PDFLaTeX ---> PDF (Document Viewer)") + << i18n("XeLaTeX ---> PDF (Okular)") + << i18n("XeLaTeX ---> PDF (Document Viewer)") + << i18n("LuaLaTeX ---> PDF (Okular)") + << i18n("LuaLaTeX ---> PDF (Document Viewer)") + ; } -QuickPreview::~QuickPreview() +QuickPreview::~QuickPreview() { - delete m_tempDir; + delete m_tempDir; } //////////////////// quick preview //////////////////// // compile and view current selection (singlemode and mastermode) void QuickPreview::previewSelection(KTextEditor::View *view, bool previewInWidgetConfig) { - if (view->selection()) { - int startLine = view->selectionRange().start().line(); - KTextEditor::Document *doc = view->document(); - if ( previewInWidgetConfig && KileConfig::selPreviewInWidget() ) { - m_ki->previewWidget()->showActivePreview(view->selectionText(), m_ki->getName(doc), startLine, KileTool::qpSelection); - } - else { - run(view->selectionText(), m_ki->getName(doc), startLine); - view->removeSelection(); - } - } - else { - showError( i18n("There is no selection to compile.") ); - } + if (view->selection()) { + int startLine = view->selectionRange().start().line(); + KTextEditor::Document *doc = view->document(); + if ( previewInWidgetConfig && KileConfig::selPreviewInWidget() ) { + m_ki->previewWidget()->showActivePreview(view->selectionText(), m_ki->getName(doc), startLine, KileTool::qpSelection); + } + else { + run(view->selectionText(), m_ki->getName(doc), startLine); + view->removeSelection(); + } + } + else { + showError( i18n("There is no selection to compile.") ); + } } // compile and view current environment (singlemode and mastermode) void QuickPreview::previewEnvironment(KTextEditor::Document *doc) { - int row, col; - QString envname; - QString text = m_ki->editorExtension()->getEnvironmentText(row, col, envname); - if (!text.isEmpty()) { - if(m_ki->latexCommands()->isMathModeEnv(envname)) { - text = '$' + text + '$'; - } - else if (m_ki->latexCommands()->isDisplaymathModeEnv(envname)) { - text = "\\[" + text + "\\]"; - } - - if(KileConfig::envPreviewInWidget()) { - m_ki->previewWidget()->showActivePreview(text, m_ki->getName(doc), row, KileTool::qpEnvironment); - } - else { - run(text, m_ki->getName(doc), row); - } - } - else { - showError(i18n("There is no surrounding environment.")); - } + int row, col; + QString envname; + QString text = m_ki->editorExtension()->getEnvironmentText(row, col, envname); + if (!text.isEmpty()) { + if(m_ki->latexCommands()->isMathModeEnv(envname)) { + text = '$' + text + '$'; + } + else if (m_ki->latexCommands()->isDisplaymathModeEnv(envname)) { + text = "\\[" + text + "\\]"; + } + + if(KileConfig::envPreviewInWidget()) { + m_ki->previewWidget()->showActivePreview(text, m_ki->getName(doc), row, KileTool::qpEnvironment); + } + else { + run(text, m_ki->getName(doc), row); + } + } + else { + showError(i18n("There is no surrounding environment.")); + } } // compile and view current subdocument (only mastermode) void QuickPreview::previewSubdocument(KTextEditor::Document *doc) { - // this mode is only useful with a master document - if(!m_ki->docManager()->activeProject() && m_ki->getSinglemode()) { - showError(i18n("This job is only useful with a master document.")); - return; - } - - // the current document should not be the master document - QString filename = doc->url().toLocalFile(); - if(filename == m_ki->getCompileName()) { - showError( i18n("This is not a subdocument, but the master document.")); - return; - } - - run(doc->text(), m_ki->getName(doc), 0); + // this mode is only useful with a master document + if(!m_ki->docManager()->activeProject() && m_ki->getSinglemode()) { + showError(i18n("This job is only useful with a master document.")); + return; + } + + // the current document should not be the master document + QString filename = doc->url().toLocalFile(); + if(filename == m_ki->getCompileName()) { + showError( i18n("This is not a subdocument, but the master document.")); + return; + } + + run(doc->text(), m_ki->getName(doc), 0); } // compile and view current mathgroup (singlemode and mastermode) void QuickPreview::previewMathgroup(KTextEditor::Document *doc) { - uint row,col; - QString text = m_ki->editorExtension()->getMathgroupText(row, col); - if (!text.isEmpty()) { - if(KileConfig::mathgroupPreviewInWidget()) { - m_ki->previewWidget()->showActivePreview(text, m_ki->getName(doc), row, KileTool::qpMathgroup); - } - else { - run(text, m_ki->getName(doc), row); - } - } - else { - showError(i18n("There is no surrounding mathgroup.")); - } + uint row,col; + QString text = m_ki->editorExtension()->getMathgroupText(row, col); + if (!text.isEmpty()) { + if(KileConfig::mathgroupPreviewInWidget()) { + m_ki->previewWidget()->showActivePreview(text, m_ki->getName(doc), row, KileTool::qpMathgroup); + } + else { + run(text, m_ki->getName(doc), row); + } + } + else { + showError(i18n("There is no surrounding mathgroup.")); + } } //////////////////// run quick preview //////////////////// void QuickPreview::getTaskList(QStringList &tasklist) { - tasklist.clear(); - tasklist << "Tool/ViewDVI/Okular=" + m_taskList[0] - << "Tool/ViewDVI/Document Viewer=" + m_taskList[1] - << "Tool/ViewPS/Okular=" + m_taskList[2] - << "Tool/ViewPS/Document Viewer=" + m_taskList[3] - << "Tool/ViewPDF/Okular=" + m_taskList[4] - << "Tool/ViewPDF/Document Viewer=" + m_taskList[5] - << "Tool/ViewPDF/Okular=" + m_taskList[6] - << "Tool/ViewPDF/Document Viewer=" + m_taskList[7] - << "Tool/ViewPDF/Okular=" + m_taskList[8] - << "Tool/ViewPDF/Document Viewer=" + m_taskList[9] - ; + tasklist.clear(); + tasklist << "Tool/ViewDVI/Okular=" + m_taskList[0] + << "Tool/ViewDVI/Document Viewer=" + m_taskList[1] + << "Tool/ViewPS/Okular=" + m_taskList[2] + << "Tool/ViewPS/Document Viewer=" + m_taskList[3] + << "Tool/ViewPDF/Okular=" + m_taskList[4] + << "Tool/ViewPDF/Document Viewer=" + m_taskList[5] + << "Tool/ViewPDF/Okular=" + m_taskList[6] + << "Tool/ViewPDF/Document Viewer=" + m_taskList[7] + << "Tool/ViewPDF/Okular=" + m_taskList[8] + << "Tool/ViewPDF/Document Viewer=" + m_taskList[9] + ; } bool QuickPreview::isRunning() { - return (m_running > 0); + return (m_running > 0); } -bool QuickPreview::run(const QString &text,const QString &textfilename,int startrow) +bool QuickPreview::run(const QString &text,const QString &textfilename,int startrow) { - // define possible tools - QMap map; - map[m_taskList[0]] = "PreviewLaTeX,,,ViewDVI,Okular,dvi"; - map[m_taskList[1]] = "PreviewLaTeX,,,ViewDVI,Document Viewer,dvi"; - map[m_taskList[2]] = "PreviewLaTeX,DVItoPS,Default,ViewPS,Okular,ps"; - map[m_taskList[3]] = "PreviewLaTeX,DVItoPS,Default,ViewPS,Document Viewer,ps"; - map[m_taskList[4]] = "PreviewPDFLaTeX,,,ViewPDF,Okular,pdf"; - map[m_taskList[5]] = "PreviewPDFLaTeX,,,ViewPDF,Document Viewer,pdf"; - map[m_taskList[6]] = "PreviewXeLaTeX,,,ViewPDF,Okular,pdf"; - map[m_taskList[7]] = "PreviewXeLaTeX,,,ViewPDF,Document Viewer,pdf"; - map[m_taskList[8]] = "PreviewLuaLaTeX,,,ViewPDF,Okular,pdf"; - map[m_taskList[9]] = "PreviewLuaLaTeX,,,ViewPDF,Document Viewer,pdf"; - - QString previewtask = KileConfig::previewTask(); - if(!map.contains(previewtask)) { - showError(i18n("Could not run QuickPreview:\nunknown task '%1'",previewtask)); - return false; - } - - return run (text, textfilename, startrow, map[previewtask]); + // define possible tools + QMap map; + map[m_taskList[0]] = "PreviewLaTeX,,,ViewDVI,Okular,dvi"; + map[m_taskList[1]] = "PreviewLaTeX,,,ViewDVI,Document Viewer,dvi"; + map[m_taskList[2]] = "PreviewLaTeX,DVItoPS,Default,ViewPS,Okular,ps"; + map[m_taskList[3]] = "PreviewLaTeX,DVItoPS,Default,ViewPS,Document Viewer,ps"; + map[m_taskList[4]] = "PreviewPDFLaTeX,,,ViewPDF,Okular,pdf"; + map[m_taskList[5]] = "PreviewPDFLaTeX,,,ViewPDF,Document Viewer,pdf"; + map[m_taskList[6]] = "PreviewXeLaTeX,,,ViewPDF,Okular,pdf"; + map[m_taskList[7]] = "PreviewXeLaTeX,,,ViewPDF,Document Viewer,pdf"; + map[m_taskList[8]] = "PreviewLuaLaTeX,,,ViewPDF,Okular,pdf"; + map[m_taskList[9]] = "PreviewLuaLaTeX,,,ViewPDF,Document Viewer,pdf"; + + QString previewtask = KileConfig::previewTask(); + if(!map.contains(previewtask)) { + showError(i18n("Could not run QuickPreview:\nunknown task '%1'",previewtask)); + return false; + } + + return run (text, textfilename, startrow, map[previewtask]); } -bool QuickPreview::run(const QString &text,const QString &textfilename,int startrow,const QString &spreviewlist) +bool QuickPreview::run(const QString &text,const QString &textfilename,int startrow,const QString &spreviewlist) { - KILE_DEBUG_MAIN << "==QuickPreview::run()==========================" << endl; - m_ki->errorHandler()->clearMessages(); - if(m_running > 0) { - showError( i18n("There is already a preview running that has to be finished to run this one.") ); - return false; - } - - // check if there is something to compile - if(text.isEmpty()) { - showError(i18n("There is nothing to compile and preview.")); - return false; - } - - delete m_tempDir; - m_tempDir = new QTemporaryDir(QDir::tempPath() + QLatin1Char('/') + "kile-preview"); - m_tempDir->setAutoRemove(true); - m_tempFile = QFileInfo(m_tempDir->path(), "preview.tex").absoluteFilePath(); - KILE_DEBUG_MAIN << "\tdefine tempfile: " << m_tempFile << endl; - - // create the temporary file with preamble and text - int preamblelines = createTempfile(text); - if(preamblelines == 0) { - return false; - } - - QStringList previewlist = spreviewlist.split(',', QString::KeepEmptyParts); - - // create preview tools - KILE_DEBUG_MAIN << "\tcreate latex tool for QuickPreview: " << previewlist[pvLatex] << endl; - KileTool::PreviewLaTeX *latex = dynamic_cast(m_ki->toolManager()->createTool(previewlist[pvLatex], QString(), false)); - if(!latex) { - showError(i18n("Could not run '%1' for QuickPreview.", QString("LaTeX"))); - return false; - } - - KileTool::Base *dvips = Q_NULLPTR; - if(!previewlist[1].isEmpty()) { - QString dvipstool = previewlist[pvDvips] + " (" + previewlist[pvDvipsCfg] + ')'; - KILE_DEBUG_MAIN << "\tcreate dvips tool for QuickPreview: " << previewlist[pvDvips] << endl; - dvips = m_ki->toolManager()->createTool(previewlist[pvDvips], previewlist[pvDvipsCfg]); - if(!dvips) { - showError(i18n("Could not run '%1' for QuickPreview.",dvipstool)); - return false; - } - } - - KileTool::Base *viewer = Q_NULLPTR; - if(!previewlist[pvViewer].isEmpty()) { - QString viewertool = previewlist[pvViewer] + " (" + previewlist[pvViewerCfg] + ')'; - KILE_DEBUG_MAIN << "\tcreate viewer for QuickPreview: " << viewertool << endl; - viewer = m_ki->toolManager()->createTool(previewlist[pvViewer], previewlist[pvViewerCfg], false); - if(!viewer) { - showError(i18n("Could not run '%1' for QuickPreview.",viewertool)); - return false; - } - } - - // set value of texinput path (only for QuickPreview tools) - QString texinputpath = KileConfig::teXPaths(); - QString inputdir = QFileInfo(m_ki->getCompileName()).absolutePath(); - if(!texinputpath.isEmpty()) { - inputdir += PATH_SEPARATOR + texinputpath; - } - KileConfig::setPreviewTeXPaths(inputdir); - KILE_DEBUG_MAIN << "\tQuickPreview: inputdir is '" << inputdir << "'" << endl; - - // prepare tools: previewlatex - QString filepath = m_tempFile.left(m_tempFile.length() - 3); - latex->setPreviewInfo(textfilename, startrow, preamblelines + 1); - latex->setSource(m_tempFile); - latex->prepareToRun(); - latex->setQuickie(); - connect(latex, SIGNAL(destroyed()), this, SLOT(toolDestroyed())); - m_ki->toolManager()->run(latex); - - m_running++; - - // dvips - if(dvips) { - dvips->setSource( filepath + "dvi" ); - dvips->setQuickie(); - connect(dvips, SIGNAL(destroyed()), this, SLOT(toolDestroyed())); - m_ki->toolManager()->run(dvips); - - m_running++; - } - - // viewer - if(viewer) { - connect(viewer, SIGNAL(destroyed()), this, SLOT(toolDestroyed())); - viewer->setSource( filepath + previewlist[pvExtension] ); - viewer->setQuickie(); - m_ki->toolManager()->run(viewer); - } - - return true; + KILE_DEBUG_MAIN << "==QuickPreview::run()==========================" << endl; + m_ki->errorHandler()->clearMessages(); + if(m_running > 0) { + showError( i18n("There is already a preview running that has to be finished to run this one.") ); + return false; + } + + // check if there is something to compile + if(text.isEmpty()) { + showError(i18n("There is nothing to compile and preview.")); + return false; + } + + delete m_tempDir; + m_tempDir = new QTemporaryDir(QDir::tempPath() + QLatin1Char('/') + "kile-preview"); + m_tempDir->setAutoRemove(true); + m_tempFile = QFileInfo(m_tempDir->path(), "preview.tex").absoluteFilePath(); + KILE_DEBUG_MAIN << "\tdefine tempfile: " << m_tempFile << endl; + + // create the temporary file with preamble and text + int preamblelines = createTempfile(text); + if(preamblelines == 0) { + return false; + } + + QStringList previewlist = spreviewlist.split(',', QString::KeepEmptyParts); + + // create preview tools + KILE_DEBUG_MAIN << "\tcreate latex tool for QuickPreview: " << previewlist[pvLatex] << endl; + KileTool::PreviewLaTeX *latex = dynamic_cast(m_ki->toolManager()->createTool(previewlist[pvLatex], QString(), false)); + if(!latex) { + showError(i18n("Could not run '%1' for QuickPreview.", QString("LaTeX"))); + return false; + } + + KileTool::Base *dvips = Q_NULLPTR; + if(!previewlist[1].isEmpty()) { + QString dvipstool = previewlist[pvDvips] + " (" + previewlist[pvDvipsCfg] + ')'; + KILE_DEBUG_MAIN << "\tcreate dvips tool for QuickPreview: " << previewlist[pvDvips] << endl; + dvips = m_ki->toolManager()->createTool(previewlist[pvDvips], previewlist[pvDvipsCfg]); + if(!dvips) { + showError(i18n("Could not run '%1' for QuickPreview.",dvipstool)); + return false; + } + } + + KileTool::Base *viewer = Q_NULLPTR; + if(!previewlist[pvViewer].isEmpty()) { + QString viewertool = previewlist[pvViewer] + " (" + previewlist[pvViewerCfg] + ')'; + KILE_DEBUG_MAIN << "\tcreate viewer for QuickPreview: " << viewertool << endl; + viewer = m_ki->toolManager()->createTool(previewlist[pvViewer], previewlist[pvViewerCfg], false); + if(!viewer) { + showError(i18n("Could not run '%1' for QuickPreview.",viewertool)); + return false; + } + } + + // set value of texinput path (only for QuickPreview tools) + QString texinputpath = KileConfig::teXPaths(); + QString inputdir = QFileInfo(m_ki->getCompileName()).absolutePath(); + if(!texinputpath.isEmpty()) { + inputdir += PATH_SEPARATOR + texinputpath; + } + KileConfig::setPreviewTeXPaths(inputdir); + KILE_DEBUG_MAIN << "\tQuickPreview: inputdir is '" << inputdir << "'" << endl; + + // prepare tools: previewlatex + QString filepath = m_tempFile.left(m_tempFile.length() - 3); + latex->setPreviewInfo(textfilename, startrow, preamblelines + 1); + latex->setSource(m_tempFile); + latex->prepareToRun(); + latex->setQuickie(); + connect(latex, SIGNAL(destroyed()), this, SLOT(toolDestroyed())); + m_ki->toolManager()->run(latex); + + m_running++; + + // dvips + if(dvips) { + dvips->setSource( filepath + "dvi" ); + dvips->setQuickie(); + connect(dvips, SIGNAL(destroyed()), this, SLOT(toolDestroyed())); + m_ki->toolManager()->run(dvips); + + m_running++; + } + + // viewer + if(viewer) { + connect(viewer, SIGNAL(destroyed()), this, SLOT(toolDestroyed())); + viewer->setSource( filepath + previewlist[pvExtension] ); + viewer->setQuickie(); + m_ki->toolManager()->run(viewer); + } + + return true; } void QuickPreview::toolDestroyed() { - KILE_DEBUG_MAIN << "\tQuickPreview: tool destroyed" << endl; - if(m_running > 0) { - --m_running; - } + KILE_DEBUG_MAIN << "\tQuickPreview: tool destroyed" << endl; + if(m_running > 0) { + --m_running; + } } QString QuickPreview::getPreviewFile(const QString &extension) { - if (m_tempFile.length () < 3) { - return QString(); - } + if (m_tempFile.length () < 3) { + return QString(); + } - QString filepath = m_tempFile.left(m_tempFile.length () - 3); - return filepath + extension; -} + QString filepath = m_tempFile.left(m_tempFile.length () - 3); + return filepath + extension; +} //////////////////// tempfile //////////////////// int QuickPreview::createTempfile(const QString &text) { - // determine main document to read the preamble - QString filename = m_ki->getCompileName(); - if(filename.isEmpty()) { - showError(i18n("Could not determine the main document.")); - return 0; - } - - // open to read - QFile fin(filename); - if(!fin.exists() || !fin.open(QIODevice::ReadOnly)) { - showError(i18n("Could not read the preamble.")); - return 0; - } - KILE_DEBUG_MAIN << "\tcreate a temporary file: " << m_tempFile << endl; - - // use a textstream - QTextStream preamble(&fin); - - // create the temporary file - QFile tempfile(m_tempFile); - if(!tempfile.open(QIODevice::WriteOnly)) { - showError(i18n("Could not create a temporary file.")); - return 0; - } - QTextStream stream(&tempfile); - - // set the encoding according to the original file (tbraun) - if(m_ki->activeTextDocument()) { - QTextCodec *codec = QTextCodec::codecForName(m_ki->activeTextDocument()->encoding().toLatin1()); - if(codec) { - stream.setCodec(codec); - } - } - // write the whole preamble into this temporary file - QString textline; - int preamblelines = 0; - bool begindocumentFound = false; - while(!preamble.atEnd()) { - textline = preamble.readLine(); - if (textline.indexOf("\\begin{document}") >= 0) { - begindocumentFound = true; - break; - } - stream << textline << "\n"; - preamblelines++; - } - - // look if we found '\begin{document}' to finish the preamble - if (!begindocumentFound) { - tempfile.close(); - showError(i18n("Could not find a '\\begin{document}' command.")); - return 0; - } - - // add the text to compile - stream << "\\pagestyle{empty}\n"; - stream << "\\begin{document}\n"; - stream << text; - stream << "\n\\end{document}\n"; - tempfile.close(); - - return preamblelines; + // determine main document to read the preamble + QString filename = m_ki->getCompileName(); + if(filename.isEmpty()) { + showError(i18n("Could not determine the main document.")); + return 0; + } + + // open to read + QFile fin(filename); + if(!fin.exists() || !fin.open(QIODevice::ReadOnly)) { + showError(i18n("Could not read the preamble.")); + return 0; + } + KILE_DEBUG_MAIN << "\tcreate a temporary file: " << m_tempFile << endl; + + // use a textstream + QTextStream preamble(&fin); + + // create the temporary file + QFile tempfile(m_tempFile); + if(!tempfile.open(QIODevice::WriteOnly)) { + showError(i18n("Could not create a temporary file.")); + return 0; + } + QTextStream stream(&tempfile); + + // set the encoding according to the original file (tbraun) + if(m_ki->activeTextDocument()) { + QTextCodec *codec = QTextCodec::codecForName(m_ki->activeTextDocument()->encoding().toLatin1()); + if(codec) { + stream.setCodec(codec); + } + } + // write the whole preamble into this temporary file + QString textline; + int preamblelines = 0; + bool begindocumentFound = false; + while(!preamble.atEnd()) { + textline = preamble.readLine(); + if (textline.indexOf("\\begin{document}") >= 0) { + begindocumentFound = true; + break; + } + stream << textline << "\n"; + preamblelines++; + } + + // look if we found '\begin{document}' to finish the preamble + if (!begindocumentFound) { + tempfile.close(); + showError(i18n("Could not find a '\\begin{document}' command.")); + return 0; + } + + // add the text to compile + stream << "\\pagestyle{empty}\n"; + stream << "\\begin{document}\n"; + stream << text; + stream << "\n\\end{document}\n"; + tempfile.close(); + + return preamblelines; } //////////////////// error messages //////////////////// void QuickPreview::showError(const QString &text) { - m_ki->errorHandler()->printMessage(KileTool::Error, text, i18n("QuickPreview")); + m_ki->errorHandler()->printMessage(KileTool::Error, text, i18n("QuickPreview")); } } diff --git a/src/quickpreview.h b/src/quickpreview.h index 6174e449..f756ec0f 100644 --- a/src/quickpreview.h +++ b/src/quickpreview.h @@ -1,100 +1,100 @@ /*************************************************************************** date : Feb 15 2007 version : 0.34 copyright : (C) 2005-2007 by Holger Danielsson email : holger.danielsson@versanet.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. * * * ***************************************************************************/ #ifndef QUICKPREVIEW_H #define QUICKPREVIEW_H #include "kileinfo.h" #include "kiletool.h" #include "editorextension.h" #include "widgets/previewwidget.h" #include #include #include #include namespace KileTool { enum { qpSelection=0, qpEnvironment, qpSubdocument, qpMathgroup }; class QuickPreview : public QObject { - Q_OBJECT + Q_OBJECT public: - QuickPreview(KileInfo *ki); - ~QuickPreview(); - - bool run(const QString &text,const QString &textfilename,int startrow); - bool isRunning(); - - void previewEnvironment(KTextEditor::Document *doc); - void previewSelection(KTextEditor::View *view, bool previewInWidgetConfig=true); - void previewSubdocument(KTextEditor::Document *doc); - void previewMathgroup(KTextEditor::Document *doc); - - /** - * run (text, textfilename, startrow) works with the - * default configuration for QuickPreview. This method - * supports a forth parameter to choose the configuration as - * comma - separated string as you can see them in run (text, textfilename, startrow) - * - * It is also possible not to specify a viewer, so the viewer is not - * executed. - * - * @param text Text to preview - * @param textfilename Filename of the document - * @param startrow Position of preview text in the document - * @param spreviewlist user-defined configuration, e.g. "PreviewLaTeX,DVItoPS,,,ps" (with no preview) - * @return true if method succeeds, else false - */ - bool run (const QString &text, const QString &textfilename, int startrow, const QString &spreviewlist); - void getTaskList(QStringList &tasklist); - - /** - * QuickPreview uses temporary files for processing the output. - * If you want to work with files from QuickPreview, you - * can use this method. The method run returns true, and then - * you can get the generated ps e.g. with getPreviewFile ("eps"); - * It works with all extensions which are generated while running - * the corresponding tools (e.g. tex, dvi, ps, pdf, ...) - * - * @param extension defines which file to use - * @return The temporary file with extension - */ - QString getPreviewFile(const QString &extension); - + QuickPreview(KileInfo *ki); + ~QuickPreview(); + + bool run(const QString &text,const QString &textfilename,int startrow); + bool isRunning(); + + void previewEnvironment(KTextEditor::Document *doc); + void previewSelection(KTextEditor::View *view, bool previewInWidgetConfig=true); + void previewSubdocument(KTextEditor::Document *doc); + void previewMathgroup(KTextEditor::Document *doc); + + /** + * run (text, textfilename, startrow) works with the + * default configuration for QuickPreview. This method + * supports a forth parameter to choose the configuration as + * comma - separated string as you can see them in run (text, textfilename, startrow) + * + * It is also possible not to specify a viewer, so the viewer is not + * executed. + * + * @param text Text to preview + * @param textfilename Filename of the document + * @param startrow Position of preview text in the document + * @param spreviewlist user-defined configuration, e.g. "PreviewLaTeX,DVItoPS,,,ps" (with no preview) + * @return true if method succeeds, else false + */ + bool run (const QString &text, const QString &textfilename, int startrow, const QString &spreviewlist); + void getTaskList(QStringList &tasklist); + + /** + * QuickPreview uses temporary files for processing the output. + * If you want to work with files from QuickPreview, you + * can use this method. The method run returns true, and then + * you can get the generated ps e.g. with getPreviewFile ("eps"); + * It works with all extensions which are generated while running + * the corresponding tools (e.g. tex, dvi, ps, pdf, ...) + * + * @param extension defines which file to use + * @return The temporary file with extension + */ + QString getPreviewFile(const QString &extension); + private Q_SLOTS: - void toolDestroyed(); + void toolDestroyed(); private: - enum { pvLatex=0, pvDvips=1, pvDvipsCfg=2, pvViewer=3, pvViewerCfg=4, pvExtension=5 }; - - KileInfo *m_ki; - QString m_tempFile; - QStringList m_taskList; - int m_running; - QTemporaryDir *m_tempDir; - - int createTempfile(const QString &text); - void showError(const QString &text); + enum { pvLatex=0, pvDvips=1, pvDvipsCfg=2, pvViewer=3, pvViewerCfg=4, pvExtension=5 }; + + KileInfo *m_ki; + QString m_tempFile; + QStringList m_taskList; + int m_running; + QTemporaryDir *m_tempDir; + + int createTempfile(const QString &text); + void showError(const QString &text); }; } #endif diff --git a/src/scripting/kilescriptdocument.cpp b/src/scripting/kilescriptdocument.cpp index 7afeedfa..789c6854 100644 --- a/src/scripting/kilescriptdocument.cpp +++ b/src/scripting/kilescriptdocument.cpp @@ -1,736 +1,736 @@ /****************************************************************************** Copyright (C) 2011-2012 by Holger Danielsson (holger.danielsson@versanet.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. * * * ***************************************************************************/ #include "scripting/kilescriptdocument.h" #include "kileinfo.h" #include "kileactions.h" namespace KileScript { KileScriptDocument::KileScriptDocument(QObject *parent, KileInfo* kileInfo, KileDocument::EditorExtension *editor, const QMap *scriptActions) - : QObject(parent) - , m_kileInfo(kileInfo) - , m_view(Q_NULLPTR) - , m_document(Q_NULLPTR) - , m_editor(editor) - , m_editingTransaction(Q_NULLPTR) - , m_scriptActions(scriptActions) + : QObject(parent) + , m_kileInfo(kileInfo) + , m_view(Q_NULLPTR) + , m_document(Q_NULLPTR) + , m_editor(editor) + , m_editingTransaction(Q_NULLPTR) + , m_scriptActions(scriptActions) { } ////////////////////////////////// view/document ////////////////////////////////////// void KileScriptDocument::setView(KTextEditor::View *view) { - m_view = view; - m_document = m_view->document(); + m_view = view; + m_document = m_view->document(); } ////////////////////////////////// insert/remove/replace ////////////////////////////////////// void KileScriptDocument::insertText(const QString &s) { - QString cursorpos = ( s.indexOf("%C") >= 0 ) ? QString() : "%C"; - m_editor->insertTag(KileAction::TagData(QString(),s,cursorpos,0,0), m_view); + QString cursorpos = ( s.indexOf("%C") >= 0 ) ? QString() : "%C"; + m_editor->insertTag(KileAction::TagData(QString(),s,cursorpos,0,0), m_view); } void KileScriptDocument::insertText(int line, int column, const QString &s) { - insertText(KTextEditor::Cursor(line, column),s); + insertText(KTextEditor::Cursor(line, column),s); } void KileScriptDocument::insertText(const KTextEditor::Cursor& cursor, const QString &s) { - m_view->setCursorPosition(cursor); - insertText(s); + m_view->setCursorPosition(cursor); + insertText(s); } bool KileScriptDocument::removeText(int fromLine, int fromColumn, int toLine, int toColumn) { - return removeText(KTextEditor::Range(fromLine, fromColumn, toLine, toColumn)); + return removeText(KTextEditor::Range(fromLine, fromColumn, toLine, toColumn)); } bool KileScriptDocument::removeText(const KTextEditor::Cursor& from, const KTextEditor::Cursor& to) { - return removeText(KTextEditor::Range(from, to)); + return removeText(KTextEditor::Range(from, to)); } bool KileScriptDocument::removeText(const KTextEditor::Range& range) { - return m_document->removeText(range); + return m_document->removeText(range); } bool KileScriptDocument::replaceText(const KTextEditor::Range& range, const QString &text) { - return m_document->replaceText(range,text); + return m_document->replaceText(range,text); } /////////////////////////////// document ////////////////////////////// int KileScriptDocument::lines() { - return m_document->lines(); + return m_document->lines(); } int KileScriptDocument::length() { - return m_document->totalCharacters(); + return m_document->totalCharacters(); } KTextEditor::Range KileScriptDocument::documentRange() { - return m_document->documentRange(); + return m_document->documentRange(); } KTextEditor::Cursor KileScriptDocument::documentEnd() { - return m_document->documentEnd(); + return m_document->documentEnd(); } /////////////////////////////// text ////////////////////////////// QString KileScriptDocument::text() { - return m_document->text(); + return m_document->text(); } QString KileScriptDocument::text(int fromLine, int fromColumn, int toLine, int toColumn) { - return text( KTextEditor::Range(fromLine, fromColumn, toLine, toColumn) ); + return text( KTextEditor::Range(fromLine, fromColumn, toLine, toColumn) ); } QString KileScriptDocument::text(const KTextEditor::Cursor& from, const KTextEditor::Cursor& to) { - return text( KTextEditor::Range(from, to) ); + return text( KTextEditor::Range(from, to) ); } QString KileScriptDocument::text(const KTextEditor::Range& range) { - return m_document->text(range); + return m_document->text(range); } bool KileScriptDocument::setText(const QString &s) { - return m_document->setText(s); + return m_document->setText(s); } bool KileScriptDocument::clear() { - return m_document->clear(); + return m_document->clear(); } /////////////////////////////// line ////////////////////////////// QString KileScriptDocument::line(int line) { - return m_document->line(line); + return m_document->line(line); } QString KileScriptDocument::line() { - return line( m_view->cursorPosition().line() ); + return line( m_view->cursorPosition().line() ); } int KileScriptDocument::lineLength() { - return lineLength( m_view->cursorPosition().line() ); + return lineLength( m_view->cursorPosition().line() ); } int KileScriptDocument::lineLength(int line) { - return m_document->lineLength(line); + return m_document->lineLength(line); } bool KileScriptDocument::insertLine(const QString &s) { - return insertLine(m_view->cursorPosition().line(), s); + return insertLine(m_view->cursorPosition().line(), s); } bool KileScriptDocument::insertLine(int line, const QString &s) { - return m_document->insertLine(line, s); + return m_document->insertLine(line, s); } bool KileScriptDocument::removeLine() { - return removeLine( m_view->cursorPosition().line() ); + return removeLine( m_view->cursorPosition().line() ); } bool KileScriptDocument::removeLine(int line) { - return m_document->removeLine(line); + return m_document->removeLine(line); } bool KileScriptDocument::replaceLine(const QString &s) { - return replaceLine( m_view->cursorPosition().line(),s ); + return replaceLine( m_view->cursorPosition().line(),s ); } bool KileScriptDocument::replaceLine(int line,const QString &s) { - return m_editor->replaceLine(line,s,m_view); + return m_editor->replaceLine(line,s,m_view); } bool KileScriptDocument::truncateLine() { - return truncate( m_view->cursorPosition() ); + return truncate( m_view->cursorPosition() ); } bool KileScriptDocument::truncate(int line, int column) { - QString textline = m_document->line(line); - if ( textline.isEmpty() || textline.length()line(line); + if ( textline.isEmpty() || textline.length()cursorPosition() ); + return getWord( m_view->cursorPosition() ); } QString KileScriptDocument::wordAt(int line, int column) { - return getWord( KTextEditor::Cursor(line, column) ); + return getWord( KTextEditor::Cursor(line, column) ); } QString KileScriptDocument::wordAt(const KTextEditor::Cursor& cursor) { - return getWord(cursor); + return getWord(cursor); } KTextEditor::Range KileScriptDocument::wordRange() { - return m_editor->wordRange( m_view->cursorPosition(),false,m_view ); + return m_editor->wordRange( m_view->cursorPosition(),false,m_view ); } QString KileScriptDocument::getWord(const KTextEditor::Cursor &cursor) { - return m_editor->word(cursor,false,m_view); + return m_editor->word(cursor,false,m_view); } /////////////////////////////// latex command ////////////////////////////// QString KileScriptDocument::latexCommand() { - return getLatexCommand( m_view->cursorPosition() ); + return getLatexCommand( m_view->cursorPosition() ); } QString KileScriptDocument::latexCommandAt(int line, int column) { - return getLatexCommand( KTextEditor::Cursor(line, column) ); + return getLatexCommand( KTextEditor::Cursor(line, column) ); } QString KileScriptDocument::latexCommandAt(const KTextEditor::Cursor &cursor) { - return getLatexCommand(cursor); + return getLatexCommand(cursor); } KTextEditor::Range KileScriptDocument::latexCommandRange() { - return m_editor->wordRange( m_view->cursorPosition(),true,m_view ); + return m_editor->wordRange( m_view->cursorPosition(),true,m_view ); } QString KileScriptDocument::getLatexCommand(const KTextEditor::Cursor &cursor) { - return m_editor->word(cursor,true,m_view); + return m_editor->word(cursor,true,m_view); } /////////////////////////////// char ////////////////////////////// QString KileScriptDocument::charAt(int line, int column) { - return charAt(KTextEditor::Cursor(line,column)); + return charAt(KTextEditor::Cursor(line,column)); } QString KileScriptDocument::charAt(const KTextEditor::Cursor& cursor) { - return QString(m_document->characterAt(cursor)); + return QString(m_document->characterAt(cursor)); } QString KileScriptDocument::firstChar(int line) { - QString textline = m_document->line(line); - int pos = nextNonSpaceChar(textline,0); - return ( pos >= 0 ) ? QString(textline.at(pos)) : QString(); + QString textline = m_document->line(line); + int pos = nextNonSpaceChar(textline,0); + return ( pos >= 0 ) ? QString(textline.at(pos)) : QString(); } QString KileScriptDocument::lastChar(int line) { - QString textline = m_document->line(line); - int pos = previousNonSpaceChar(textline,textline.length()-1); - return ( pos >= 0 ) ? QString(textline.at(pos)) : QString(); + QString textline = m_document->line(line); + int pos = previousNonSpaceChar(textline,textline.length()-1); + return ( pos >= 0 ) ? QString(textline.at(pos)) : QString(); } bool KileScriptDocument::isSpace(int line, int column) { - return isSpace(KTextEditor::Cursor(line,column)); + return isSpace(KTextEditor::Cursor(line,column)); } bool KileScriptDocument::isSpace(const KTextEditor::Cursor& cursor) { - return m_document->characterAt(cursor).isSpace(); + return m_document->characterAt(cursor).isSpace(); } /////////////////////////////// bullet ////////////////////////////// void KileScriptDocument::insertBullet() { - m_editor->insertBullet(m_view); + m_editor->insertBullet(m_view); } void KileScriptDocument::nextBullet() { - m_editor->nextBullet(m_view); + m_editor->nextBullet(m_view); } void KileScriptDocument::previousBullet() { - m_editor->prevBullet(m_view); + m_editor->prevBullet(m_view); } /////////////////////////////// environment ////////////////////////////// bool KileScriptDocument::hasEnvironment() { - return m_editor->hasEnvironment(m_view); + return m_editor->hasEnvironment(m_view); } QString KileScriptDocument::environmentName() { - return m_editor->environmentName(m_view); + return m_editor->environmentName(m_view); } QString KileScriptDocument::environment(bool inside) { - return m_editor->environmentText(inside,m_view); + return m_editor->environmentText(inside,m_view); } KTextEditor::Range KileScriptDocument::environmentRange(bool inside) { - return m_editor->environmentRange(inside,m_view); + return m_editor->environmentRange(inside,m_view); } void KileScriptDocument::removeEnvironment(bool inside) { - m_editor->deleteEnvironment(inside,m_view); + m_editor->deleteEnvironment(inside,m_view); } void KileScriptDocument::closeEnvironment() { - m_editor->closeEnvironment(m_view); + m_editor->closeEnvironment(m_view); } void KileScriptDocument::closeAllEnvironments() { - m_editor->closeAllEnvironments(m_view); + m_editor->closeAllEnvironments(m_view); } ////////////////////////////////// TexGroup ////////////////////////////////////// bool KileScriptDocument::hasTexgroup() { - return m_editor->hasTexgroup(m_view); + return m_editor->hasTexgroup(m_view); } QString KileScriptDocument::texgroup(bool inside) { - return m_editor->getTexgroupText(inside,m_view); + return m_editor->getTexgroupText(inside,m_view); } KTextEditor::Range KileScriptDocument::texgroupRange(bool inside) { - return m_editor->texgroupRange(inside,m_view); + return m_editor->texgroupRange(inside,m_view); } void KileScriptDocument::removeTexgroup(bool inside) { - return m_editor->deleteTexgroup(inside,m_view); + return m_editor->deleteTexgroup(inside,m_view); } ////////////////////////////////// MathGroup ////////////////////////////////////// bool KileScriptDocument::hasMathgroup() { - return m_editor->hasMathgroup(m_view); + return m_editor->hasMathgroup(m_view); } QString KileScriptDocument::mathgroup() { - return m_editor->getMathgroupText(m_view); + return m_editor->getMathgroupText(m_view); } KTextEditor::Range KileScriptDocument::mathgroupRange() { - return m_editor->mathgroupRange(m_view); + return m_editor->mathgroupRange(m_view); } void KileScriptDocument::removeMathgroup() { - m_editor->deleteMathgroup(m_view); + m_editor->deleteMathgroup(m_view); } ////////////////////////////////// Paragraph ////////////////////////////////////// QString KileScriptDocument::paragraph() { - return m_editor->getParagraphText(m_view); + return m_editor->getParagraphText(m_view); } KTextEditor::Range KileScriptDocument::paragraphRange() { - return m_editor->findCurrentParagraphRange(m_view); + return m_editor->findCurrentParagraphRange(m_view); } void KileScriptDocument::removeParagraph() { - m_editor->deleteParagraph(m_view); + m_editor->deleteParagraph(m_view); } ////////////////////////////////// matches ////////////////////////////////////// bool KileScriptDocument::matchesAt(int line, int column, const QString &s) { - return matchesAt(KTextEditor::Cursor(line,column),s); + return matchesAt(KTextEditor::Cursor(line,column),s); } bool KileScriptDocument::matchesAt(const KTextEditor::Cursor& cursor, const QString &s) { - QString textline = m_document->line(cursor.line()); - return textline.mid(cursor.column()).startsWith(s); + QString textline = m_document->line(cursor.line()); + return textline.mid(cursor.column()).startsWith(s); } bool KileScriptDocument::startsWith (int line, const QString &pattern, bool skipWhiteSpaces) { - QString textline = m_document->line(line); - if ( skipWhiteSpaces ) { - textline = textline.trimmed(); - } - return textline.startsWith(pattern); + QString textline = m_document->line(line); + if ( skipWhiteSpaces ) { + textline = textline.trimmed(); + } + return textline.startsWith(pattern); } bool KileScriptDocument::endsWith (int line, const QString &pattern, bool skipWhiteSpaces) { - QString textline = m_document->line(line); - if ( skipWhiteSpaces ) { - textline = textline.trimmed(); - } - return textline.endsWith(pattern); + QString textline = m_document->line(line); + if ( skipWhiteSpaces ) { + textline = textline.trimmed(); + } + return textline.endsWith(pattern); } ////////////////////////////////// columns/lines ////////////////////////////////////// int KileScriptDocument::firstColumn(int line) { - QString textline = m_document->line(line); - return ( textline.isEmpty() ) ? -1 : nextNonSpaceChar(textline,0); + QString textline = m_document->line(line); + return ( textline.isEmpty() ) ? -1 : nextNonSpaceChar(textline,0); } int KileScriptDocument::lastColumn(int line) { - QString textline = m_document->line(line); - return ( textline.isEmpty() ) ? -1 : previousNonSpaceChar(textline,textline.length()-1); + QString textline = m_document->line(line); + return ( textline.isEmpty() ) ? -1 : previousNonSpaceChar(textline,textline.length()-1); } int KileScriptDocument::prevNonSpaceColumn(int line, int column) { - QString textline = m_document->line(line); - return ( textline.isEmpty() || column==0 ) ? -1 : previousNonSpaceChar(textline,column-1); + QString textline = m_document->line(line); + return ( textline.isEmpty() || column==0 ) ? -1 : previousNonSpaceChar(textline,column-1); } int KileScriptDocument::prevNonSpaceColumn(const KTextEditor::Cursor& cursor) { - return prevNonSpaceColumn(cursor.line(), cursor.column()); + return prevNonSpaceColumn(cursor.line(), cursor.column()); } int KileScriptDocument::nextNonSpaceColumn(int line, int column) { - QString textline = m_document->line(line); - return ( textline.isEmpty() || column>=textline.length() ) ? -1 : nextNonSpaceChar(textline,column+1); + QString textline = m_document->line(line); + return ( textline.isEmpty() || column>=textline.length() ) ? -1 : nextNonSpaceChar(textline,column+1); } int KileScriptDocument::nextNonSpaceColumn(const KTextEditor::Cursor& cursor) { - return nextNonSpaceColumn(cursor.line(), cursor.column()); + return nextNonSpaceColumn(cursor.line(), cursor.column()); } int KileScriptDocument::prevNonEmptyLine(int line) { - return m_editor->prevNonEmptyLine(line,m_view); + return m_editor->prevNonEmptyLine(line,m_view); } int KileScriptDocument::nextNonEmptyLine(int line) { - return m_editor->nextNonEmptyLine(line,m_view); + return m_editor->nextNonEmptyLine(line,m_view); } int KileScriptDocument::previousNonSpaceChar(const QString &s, int pos) const { - if ( pos >= s.length() ) { - pos = s.length() - 1; - } + if ( pos >= s.length() ) { + pos = s.length() - 1; + } - for (int i=pos; i>=0; --i ) { - if ( !s[i].isSpace() ) { - return i; - } - } - return -1; + for (int i=pos; i>=0; --i ) { + if ( !s[i].isSpace() ) { + return i; + } + } + return -1; } int KileScriptDocument::nextNonSpaceChar(const QString &s, int pos) const { - if ( pos < 0 ) { - pos = 0; - } + if ( pos < 0 ) { + pos = 0; + } - for ( int i=pos; igotoEnvironment(true,m_view); + m_editor->gotoEnvironment(true,m_view); } void KileScriptDocument::gotoEndEnv() { - m_editor->gotoEnvironment(false,m_view); + m_editor->gotoEnvironment(false,m_view); } void KileScriptDocument::gotoBeginTexgroup() { - m_editor->gotoTexgroup(true,m_view); + m_editor->gotoTexgroup(true,m_view); } void KileScriptDocument::gotoEndTexgroup() { - m_editor->gotoTexgroup(false,m_view); + m_editor->gotoTexgroup(false,m_view); } void KileScriptDocument::gotoNextParagraph() { - m_editor->gotoNextParagraph(m_view); + m_editor->gotoNextParagraph(m_view); } void KileScriptDocument::gotoPrevParagraph() { - m_editor->gotoPrevParagraph(m_view); + m_editor->gotoPrevParagraph(m_view); } void KileScriptDocument::gotoNextSectioning() { - m_editor->gotoSectioning(false,m_view); + m_editor->gotoSectioning(false,m_view); } void KileScriptDocument::gotoPrevSectioning() { - m_editor->gotoSectioning(true,m_view); + m_editor->gotoSectioning(true,m_view); } void KileScriptDocument::gotoLine(int line) { - m_editor->goToLine(line,m_view); + m_editor->goToLine(line,m_view); } ////////////////////////////////// insert sectioning tags ////////////////////////////////////// void KileScriptDocument::insertChapter() { - triggerAction("tag_chapter"); + triggerAction("tag_chapter"); } void KileScriptDocument::insertSection() { - triggerAction("tag_section"); + triggerAction("tag_section"); } void KileScriptDocument::insertSubsection() { - triggerAction("tag_subsection"); + triggerAction("tag_subsection"); } void KileScriptDocument::insertSubsubsection() { - triggerAction("tag_subsubsection"); + triggerAction("tag_subsubsection"); } void KileScriptDocument::insertParagraph() { - triggerAction("tag_paragraph"); + triggerAction("tag_paragraph"); } void KileScriptDocument::insertSubparagraph() { - triggerAction("tag_subparagraph"); + triggerAction("tag_subparagraph"); } ////////////////////////////////// insert reference tags ////////////////////////////////////// void KileScriptDocument::insertLabel() { - triggerAction("tag_label"); + triggerAction("tag_label"); } void KileScriptDocument::insertReference() { - triggerAction("tag_ref"); + triggerAction("tag_ref"); } void KileScriptDocument::insertPageref() { - triggerAction("tag_pageref"); + triggerAction("tag_pageref"); } void KileScriptDocument::insertIndex() { - triggerAction("tag_index"); + triggerAction("tag_index"); } void KileScriptDocument::insertFootnote() { - triggerAction("tag_footnote"); + triggerAction("tag_footnote"); } void KileScriptDocument::insertCitation() { - triggerAction("tag_cite"); + triggerAction("tag_cite"); } bool KileScriptDocument::triggerAction(const QString &name) { - if ( m_scriptActions->contains(name) ) { - m_scriptActions->value(name)->trigger(); - return true; - } - else { - return false; - } + if ( m_scriptActions->contains(name) ) { + m_scriptActions->value(name)->trigger(); + return true; + } + else { + return false; + } } ////////////////////////////////// actions with selections////////////////////////////////////// void KileScriptDocument::comment() { - triggerSelectionAction("tools_comment"); + triggerSelectionAction("tools_comment"); } void KileScriptDocument::uncomment() { - triggerSelectionAction("tools_uncomment"); + triggerSelectionAction("tools_uncomment"); } void KileScriptDocument::uppercase() { - triggerSelectionAction("tools_uppercase"); + triggerSelectionAction("tools_uppercase"); } void KileScriptDocument::lowercase() { - triggerSelectionAction("tools_lowercase"); + triggerSelectionAction("tools_lowercase"); } void KileScriptDocument::capitalize() { - triggerSelectionAction("tools_capitalize"); + triggerSelectionAction("tools_capitalize"); } void KileScriptDocument::joinLines() { - triggerSelectionAction("tools_join_lines"); + triggerSelectionAction("tools_join_lines"); } bool KileScriptDocument::triggerSelectionAction(const QString &name) { - return ( m_view->selection() ) ? triggerAction(name) : false; + return ( m_view->selection() ) ? triggerAction(name) : false; } ////////////////////////////////// other ////////////////////////////////////// void KileScriptDocument::insertIntelligentNewline() { - m_editor->insertIntelligentNewline(m_view); + m_editor->insertIntelligentNewline(m_view); } void KileScriptDocument::insertIntelligentTabulator() { - m_editor->insertIntelligentTabulator(m_view); + m_editor->insertIntelligentTabulator(m_view); } void KileScriptDocument::editBegin() { - Q_ASSERT(!m_editingTransaction); - if (m_editingTransaction) { - KILE_DEBUG_MAIN << "editor editing transaction was active, forcefully closing it"; - m_editingTransaction->finish(); - delete m_editingTransaction; - } - m_editingTransaction = new KTextEditor::Document::EditingTransaction(m_document); - m_editingTransaction->start(); + Q_ASSERT(!m_editingTransaction); + if (m_editingTransaction) { + KILE_DEBUG_MAIN << "editor editing transaction was active, forcefully closing it"; + m_editingTransaction->finish(); + delete m_editingTransaction; + } + m_editingTransaction = new KTextEditor::Document::EditingTransaction(m_document); + m_editingTransaction->start(); } void KileScriptDocument::editEnd() { - Q_ASSERT(m_editingTransaction); - if (!m_editingTransaction) { - KILE_DEBUG_MAIN << "unexpectedly no editing transaction was active, aborting"; - return; - } + Q_ASSERT(m_editingTransaction); + if (!m_editingTransaction) { + KILE_DEBUG_MAIN << "unexpectedly no editing transaction was active, aborting"; + return; + } - m_editingTransaction->finish(); - delete m_editingTransaction; - m_editingTransaction = Q_NULLPTR; + m_editingTransaction->finish(); + delete m_editingTransaction; + m_editingTransaction = Q_NULLPTR; } ////////////////////////////////// Kile specific actions ////////////////////////////////////// void KileScriptDocument::refreshStructure() { - triggerAction("refreshstructure"); + triggerAction("refreshstructure"); } ////////////////////////////////// lists ////////////////////////////////////// QStringList KileScriptDocument::labelList() const { - return m_kileInfo->allLabels(); + return m_kileInfo->allLabels(); } QStringList KileScriptDocument::bibitemList() const { - return m_kileInfo->allBibItems(); + return m_kileInfo->allBibItems(); } } diff --git a/src/scripting/kilescriptdocument.h b/src/scripting/kilescriptdocument.h index f9e1f1a8..1f08c962 100644 --- a/src/scripting/kilescriptdocument.h +++ b/src/scripting/kilescriptdocument.h @@ -1,230 +1,230 @@ /****************************************************************************** Copyright (C) 2011-2012 by Holger Danielsson (holger.danielsson@versanet.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. * * * ***************************************************************************/ #ifndef KILE_SCRIPT_DOCUMENT_H #define KILE_SCRIPT_DOCUMENT_H #include #include #include #include #include #include #include #include "editorextension.h" class KileInfo; namespace KileScript { class KileScriptDocument : public QObject { - Q_OBJECT - - public: - KileScriptDocument(QObject *parent, KileInfo *kileInfo, KileDocument::EditorExtension *editor, - const QMap *scriptActions); - virtual ~KileScriptDocument() {} - - void setView(KTextEditor::View *view); - - // insert (extended insert using KileAction::TagData)/remove/replace - Q_INVOKABLE void insertText(const QString &s); - Q_INVOKABLE void insertText(int line, int column, const QString &s); - Q_INVOKABLE void insertText(const KTextEditor::Cursor& cursor, const QString &s); - - Q_INVOKABLE bool removeText(int fromLine, int fromColumn, int toLine, int toColumn); - Q_INVOKABLE bool removeText(const KTextEditor::Cursor& from, const KTextEditor::Cursor& to); - Q_INVOKABLE bool removeText(const KTextEditor::Range& range); - - Q_INVOKABLE bool replaceText(const KTextEditor::Range& range, const QString &text); - - // document - Q_INVOKABLE int lines(); - Q_INVOKABLE int length(); - Q_INVOKABLE KTextEditor::Range documentRange(); - Q_INVOKABLE KTextEditor::Cursor documentEnd(); - - // text - Q_INVOKABLE QString text(); - Q_INVOKABLE QString text(int fromLine, int fromColumn, int toLine, int toColumn); - Q_INVOKABLE QString text(const KTextEditor::Cursor& from, const KTextEditor::Cursor& to); - Q_INVOKABLE QString text(const KTextEditor::Range& range); - Q_INVOKABLE bool setText(const QString &s); - Q_INVOKABLE bool clear(); - - // line - Q_INVOKABLE QString line(); - Q_INVOKABLE QString line(int line); - Q_INVOKABLE int lineLength(); - Q_INVOKABLE int lineLength(int line); - - Q_INVOKABLE bool insertLine(const QString &s); - Q_INVOKABLE bool insertLine(int line, const QString &s); - - Q_INVOKABLE bool removeLine(); - Q_INVOKABLE bool removeLine(int line); - - Q_INVOKABLE bool replaceLine(const QString &s); - Q_INVOKABLE bool replaceLine(int line,const QString &s); - - Q_INVOKABLE bool truncateLine(); - Q_INVOKABLE bool truncate(int line, int column); - Q_INVOKABLE bool truncate(const KTextEditor::Cursor& cursor); - - // word - Q_INVOKABLE QString word(); - Q_INVOKABLE QString wordAt(int line, int column); - Q_INVOKABLE QString wordAt(const KTextEditor::Cursor& cursor); - Q_INVOKABLE KTextEditor::Range wordRange(); - - // latex command - Q_INVOKABLE QString latexCommand(); - Q_INVOKABLE QString latexCommandAt(int line, int column); - Q_INVOKABLE QString latexCommandAt(const KTextEditor::Cursor& cursor); - Q_INVOKABLE KTextEditor::Range latexCommandRange(); - - // char - Q_INVOKABLE QString charAt(int line, int column); - Q_INVOKABLE QString charAt(const KTextEditor::Cursor& cursor); - Q_INVOKABLE QString firstChar(int line); - Q_INVOKABLE QString lastChar(int line); - Q_INVOKABLE bool isSpace(int line, int column); - Q_INVOKABLE bool isSpace(const KTextEditor::Cursor& cursor); - - // bullet - Q_INVOKABLE void insertBullet(); - Q_INVOKABLE void nextBullet(); - Q_INVOKABLE void previousBullet(); - - // environment - Q_INVOKABLE bool hasEnvironment(); - Q_INVOKABLE QString environment(bool inside = false); - Q_INVOKABLE KTextEditor::Range environmentRange(bool inside = false); - Q_INVOKABLE QString environmentName(); - - Q_INVOKABLE void removeEnvironment(bool inside = false); - - Q_INVOKABLE void closeEnvironment(); - Q_INVOKABLE void closeAllEnvironments(); - - // texgroup - Q_INVOKABLE bool hasTexgroup(); - Q_INVOKABLE QString texgroup(bool inside = true); - Q_INVOKABLE KTextEditor::Range texgroupRange(bool inside = true); - - Q_INVOKABLE void removeTexgroup(bool inside = true); - - // mathgroup - Q_INVOKABLE bool hasMathgroup(); - Q_INVOKABLE QString mathgroup(); - Q_INVOKABLE KTextEditor::Range mathgroupRange(); - - Q_INVOKABLE void removeMathgroup(); - - // paragraph - Q_INVOKABLE QString paragraph(); - Q_INVOKABLE KTextEditor::Range paragraphRange(); - - Q_INVOKABLE void removeParagraph(); - - // match text - Q_INVOKABLE bool matchesAt(int line, int column, const QString &s); - Q_INVOKABLE bool matchesAt(const KTextEditor::Cursor& cursor, const QString &s); - Q_INVOKABLE bool startsWith (int line, const QString &pattern, bool skipWhiteSpaces = true); - Q_INVOKABLE bool endsWith (int line, const QString &pattern, bool skipWhiteSpaces = true); - - // columns/lines - Q_INVOKABLE int firstColumn(int line); - Q_INVOKABLE int lastColumn(int line); - Q_INVOKABLE int prevNonSpaceColumn(int line, int column); - Q_INVOKABLE int prevNonSpaceColumn(const KTextEditor::Cursor& cursor); - Q_INVOKABLE int nextNonSpaceColumn(int line, int column); - Q_INVOKABLE int nextNonSpaceColumn(const KTextEditor::Cursor& cursor); - Q_INVOKABLE int prevNonEmptyLine(int line); - Q_INVOKABLE int nextNonEmptyLine(int line); - - // goto - Q_INVOKABLE void gotoBeginEnv(); - Q_INVOKABLE void gotoEndEnv(); - Q_INVOKABLE void gotoBeginTexgroup(); - Q_INVOKABLE void gotoEndTexgroup(); - Q_INVOKABLE void gotoNextParagraph(); - Q_INVOKABLE void gotoPrevParagraph(); - Q_INVOKABLE void gotoNextSectioning(); - Q_INVOKABLE void gotoPrevSectioning(); - Q_INVOKABLE void gotoLine(int line); - - // insert sectioning - Q_INVOKABLE void insertChapter(); - Q_INVOKABLE void insertSection(); - Q_INVOKABLE void insertSubsection(); - Q_INVOKABLE void insertSubsubsection(); - Q_INVOKABLE void insertParagraph(); - Q_INVOKABLE void insertSubparagraph(); - - // insert references - Q_INVOKABLE void insertLabel(); - Q_INVOKABLE void insertReference(); - Q_INVOKABLE void insertCitation(); - Q_INVOKABLE void insertPageref(); - Q_INVOKABLE void insertIndex(); - Q_INVOKABLE void insertFootnote(); - - // KatePart actions with selections - Q_INVOKABLE void comment(); - Q_INVOKABLE void uncomment(); - Q_INVOKABLE void uppercase(); - Q_INVOKABLE void lowercase(); - Q_INVOKABLE void capitalize(); - Q_INVOKABLE void joinLines(); - - // other - Q_INVOKABLE void insertIntelligentNewline(); - Q_INVOKABLE void insertIntelligentTabulator(); - Q_INVOKABLE void editBegin(); - Q_INVOKABLE void editEnd(); - - // lists - Q_INVOKABLE QStringList labelList() const; - Q_INVOKABLE QStringList bibitemList() const; - - // Kile specific actions - Q_INVOKABLE void refreshStructure(); - - private: - KileInfo* m_kileInfo; - KTextEditor::View *m_view; - KTextEditor::Document *m_document; - KileDocument::EditorExtension *m_editor; - KTextEditor::Document::EditingTransaction *m_editingTransaction; - const QMap *m_scriptActions; - - QString getWord(const KTextEditor::Cursor &cursor); - QString getLatexCommand(const KTextEditor::Cursor &cursor); - - int previousNonSpaceChar(const QString &s, int pos) const; - int nextNonSpaceChar(const QString &s, int pos) const; - - bool triggerAction(const QString &name); - bool triggerSelectionAction(const QString &name); + Q_OBJECT + +public: + KileScriptDocument(QObject *parent, KileInfo *kileInfo, KileDocument::EditorExtension *editor, + const QMap *scriptActions); + virtual ~KileScriptDocument() {} + + void setView(KTextEditor::View *view); + + // insert (extended insert using KileAction::TagData)/remove/replace + Q_INVOKABLE void insertText(const QString &s); + Q_INVOKABLE void insertText(int line, int column, const QString &s); + Q_INVOKABLE void insertText(const KTextEditor::Cursor& cursor, const QString &s); + + Q_INVOKABLE bool removeText(int fromLine, int fromColumn, int toLine, int toColumn); + Q_INVOKABLE bool removeText(const KTextEditor::Cursor& from, const KTextEditor::Cursor& to); + Q_INVOKABLE bool removeText(const KTextEditor::Range& range); + + Q_INVOKABLE bool replaceText(const KTextEditor::Range& range, const QString &text); + + // document + Q_INVOKABLE int lines(); + Q_INVOKABLE int length(); + Q_INVOKABLE KTextEditor::Range documentRange(); + Q_INVOKABLE KTextEditor::Cursor documentEnd(); + + // text + Q_INVOKABLE QString text(); + Q_INVOKABLE QString text(int fromLine, int fromColumn, int toLine, int toColumn); + Q_INVOKABLE QString text(const KTextEditor::Cursor& from, const KTextEditor::Cursor& to); + Q_INVOKABLE QString text(const KTextEditor::Range& range); + Q_INVOKABLE bool setText(const QString &s); + Q_INVOKABLE bool clear(); + + // line + Q_INVOKABLE QString line(); + Q_INVOKABLE QString line(int line); + Q_INVOKABLE int lineLength(); + Q_INVOKABLE int lineLength(int line); + + Q_INVOKABLE bool insertLine(const QString &s); + Q_INVOKABLE bool insertLine(int line, const QString &s); + + Q_INVOKABLE bool removeLine(); + Q_INVOKABLE bool removeLine(int line); + + Q_INVOKABLE bool replaceLine(const QString &s); + Q_INVOKABLE bool replaceLine(int line,const QString &s); + + Q_INVOKABLE bool truncateLine(); + Q_INVOKABLE bool truncate(int line, int column); + Q_INVOKABLE bool truncate(const KTextEditor::Cursor& cursor); + + // word + Q_INVOKABLE QString word(); + Q_INVOKABLE QString wordAt(int line, int column); + Q_INVOKABLE QString wordAt(const KTextEditor::Cursor& cursor); + Q_INVOKABLE KTextEditor::Range wordRange(); + + // latex command + Q_INVOKABLE QString latexCommand(); + Q_INVOKABLE QString latexCommandAt(int line, int column); + Q_INVOKABLE QString latexCommandAt(const KTextEditor::Cursor& cursor); + Q_INVOKABLE KTextEditor::Range latexCommandRange(); + + // char + Q_INVOKABLE QString charAt(int line, int column); + Q_INVOKABLE QString charAt(const KTextEditor::Cursor& cursor); + Q_INVOKABLE QString firstChar(int line); + Q_INVOKABLE QString lastChar(int line); + Q_INVOKABLE bool isSpace(int line, int column); + Q_INVOKABLE bool isSpace(const KTextEditor::Cursor& cursor); + + // bullet + Q_INVOKABLE void insertBullet(); + Q_INVOKABLE void nextBullet(); + Q_INVOKABLE void previousBullet(); + + // environment + Q_INVOKABLE bool hasEnvironment(); + Q_INVOKABLE QString environment(bool inside = false); + Q_INVOKABLE KTextEditor::Range environmentRange(bool inside = false); + Q_INVOKABLE QString environmentName(); + + Q_INVOKABLE void removeEnvironment(bool inside = false); + + Q_INVOKABLE void closeEnvironment(); + Q_INVOKABLE void closeAllEnvironments(); + + // texgroup + Q_INVOKABLE bool hasTexgroup(); + Q_INVOKABLE QString texgroup(bool inside = true); + Q_INVOKABLE KTextEditor::Range texgroupRange(bool inside = true); + + Q_INVOKABLE void removeTexgroup(bool inside = true); + + // mathgroup + Q_INVOKABLE bool hasMathgroup(); + Q_INVOKABLE QString mathgroup(); + Q_INVOKABLE KTextEditor::Range mathgroupRange(); + + Q_INVOKABLE void removeMathgroup(); + + // paragraph + Q_INVOKABLE QString paragraph(); + Q_INVOKABLE KTextEditor::Range paragraphRange(); + + Q_INVOKABLE void removeParagraph(); + + // match text + Q_INVOKABLE bool matchesAt(int line, int column, const QString &s); + Q_INVOKABLE bool matchesAt(const KTextEditor::Cursor& cursor, const QString &s); + Q_INVOKABLE bool startsWith (int line, const QString &pattern, bool skipWhiteSpaces = true); + Q_INVOKABLE bool endsWith (int line, const QString &pattern, bool skipWhiteSpaces = true); + + // columns/lines + Q_INVOKABLE int firstColumn(int line); + Q_INVOKABLE int lastColumn(int line); + Q_INVOKABLE int prevNonSpaceColumn(int line, int column); + Q_INVOKABLE int prevNonSpaceColumn(const KTextEditor::Cursor& cursor); + Q_INVOKABLE int nextNonSpaceColumn(int line, int column); + Q_INVOKABLE int nextNonSpaceColumn(const KTextEditor::Cursor& cursor); + Q_INVOKABLE int prevNonEmptyLine(int line); + Q_INVOKABLE int nextNonEmptyLine(int line); + + // goto + Q_INVOKABLE void gotoBeginEnv(); + Q_INVOKABLE void gotoEndEnv(); + Q_INVOKABLE void gotoBeginTexgroup(); + Q_INVOKABLE void gotoEndTexgroup(); + Q_INVOKABLE void gotoNextParagraph(); + Q_INVOKABLE void gotoPrevParagraph(); + Q_INVOKABLE void gotoNextSectioning(); + Q_INVOKABLE void gotoPrevSectioning(); + Q_INVOKABLE void gotoLine(int line); + + // insert sectioning + Q_INVOKABLE void insertChapter(); + Q_INVOKABLE void insertSection(); + Q_INVOKABLE void insertSubsection(); + Q_INVOKABLE void insertSubsubsection(); + Q_INVOKABLE void insertParagraph(); + Q_INVOKABLE void insertSubparagraph(); + + // insert references + Q_INVOKABLE void insertLabel(); + Q_INVOKABLE void insertReference(); + Q_INVOKABLE void insertCitation(); + Q_INVOKABLE void insertPageref(); + Q_INVOKABLE void insertIndex(); + Q_INVOKABLE void insertFootnote(); + + // KatePart actions with selections + Q_INVOKABLE void comment(); + Q_INVOKABLE void uncomment(); + Q_INVOKABLE void uppercase(); + Q_INVOKABLE void lowercase(); + Q_INVOKABLE void capitalize(); + Q_INVOKABLE void joinLines(); + + // other + Q_INVOKABLE void insertIntelligentNewline(); + Q_INVOKABLE void insertIntelligentTabulator(); + Q_INVOKABLE void editBegin(); + Q_INVOKABLE void editEnd(); + + // lists + Q_INVOKABLE QStringList labelList() const; + Q_INVOKABLE QStringList bibitemList() const; + + // Kile specific actions + Q_INVOKABLE void refreshStructure(); + +private: + KileInfo* m_kileInfo; + KTextEditor::View *m_view; + KTextEditor::Document *m_document; + KileDocument::EditorExtension *m_editor; + KTextEditor::Document::EditingTransaction *m_editingTransaction; + const QMap *m_scriptActions; + + QString getWord(const KTextEditor::Cursor &cursor); + QString getLatexCommand(const KTextEditor::Cursor &cursor); + + int previousNonSpaceChar(const QString &s, int pos) const; + int nextNonSpaceChar(const QString &s, int pos) const; + + bool triggerAction(const QString &name); + bool triggerSelectionAction(const QString &name); }; } #endif diff --git a/src/scripting/kilescriptobject.cpp b/src/scripting/kilescriptobject.cpp index 7be71766..9cb05a6c 100644 --- a/src/scripting/kilescriptobject.cpp +++ b/src/scripting/kilescriptobject.cpp @@ -1,327 +1,327 @@ /****************************************************************************** Copyright (C) 2011-2012 by Holger Danielsson (holger.danielsson@versanet.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. * * * ***************************************************************************/ #include #include #include #include #include #include #include #include #include #include "scripting/kilescriptobject.h" #include "kileviewmanager.h" #include "dialogs/validatorinputdialog.h" #include "kileinfo.h" namespace KileScript { ////////////////////////////////// KileAlert object ////////////////////////////////////// KileAlert::KileAlert(QObject *parent, KParts::MainWindow *mainWindow) - : QObject(parent), m_mainWindow(mainWindow) + : QObject(parent), m_mainWindow(mainWindow) { } void KileAlert::information(const QString &text, const QString &caption) { - QString msgCaption = ( caption.isEmpty() ) ? i18n("Script: information") : caption; - KMessageBox::information(m_mainWindow,text,msgCaption); + QString msgCaption = ( caption.isEmpty() ) ? i18n("Script: information") : caption; + KMessageBox::information(m_mainWindow,text,msgCaption); } void KileAlert::sorry(const QString &text, const QString &caption) { - QString msgCaption = ( caption.isEmpty() ) ? i18n("Script: sorry") : caption; - KMessageBox::sorry(m_mainWindow,text,msgCaption); + QString msgCaption = ( caption.isEmpty() ) ? i18n("Script: sorry") : caption; + KMessageBox::sorry(m_mainWindow,text,msgCaption); } void KileAlert::error(const QString &text, const QString &caption) { - QString msgCaption = ( caption.isEmpty() ) ? i18n("Script: error") : caption; - KMessageBox::error(m_mainWindow,text,msgCaption); + QString msgCaption = ( caption.isEmpty() ) ? i18n("Script: error") : caption; + KMessageBox::error(m_mainWindow,text,msgCaption); } QString KileAlert::question(const QString &text, const QString &caption) { - QString msgCaption = ( caption.isEmpty() ) ? i18n("Script: question") : caption; - return ( KMessageBox::questionYesNo(m_mainWindow,text,msgCaption) == KMessageBox::No ) ? "no" : "yes"; + QString msgCaption = ( caption.isEmpty() ) ? i18n("Script: question") : caption; + return ( KMessageBox::questionYesNo(m_mainWindow,text,msgCaption) == KMessageBox::No ) ? "no" : "yes"; } QString KileAlert::warning(const QString &text, const QString &caption) { - QString msgCaption = ( caption.isEmpty() ) ? i18n("Script: warning") : caption; - return ( KMessageBox::warningContinueCancel(m_mainWindow,text,msgCaption) == KMessageBox::Continue ) ? "continue" : "cancel"; + QString msgCaption = ( caption.isEmpty() ) ? i18n("Script: warning") : caption; + return ( KMessageBox::warningContinueCancel(m_mainWindow,text,msgCaption) == KMessageBox::Continue ) ? "continue" : "cancel"; } ////////////////////////////////// KileInput object ////////////////////////////////////// KileInput::KileInput(QObject *parent) - : QObject(parent) + : QObject(parent) { } QString KileInput::getListboxItem(const QString &caption, const QString &label, const QStringList &list) { - return getItem(caption,label,list); + return getItem(caption,label,list); } QString KileInput::getText(const QString &caption, const QString &label) { - QStringList list = checkCaptionAndLabel(caption, label); - return QInputDialog::getText(Q_NULLPTR, list[0], list[1]); + QStringList list = checkCaptionAndLabel(caption, label); + return QInputDialog::getText(Q_NULLPTR, list[0], list[1]); } QString KileInput::getLatexCommand(const QString &caption, const QString &label) { - QRegExpValidator validator(QRegExp("[A-Za-z]+"),this); - QStringList list = checkCaptionAndLabel(caption, label); - return KileDialog::getText(list[0], list[1], QString(), Q_NULLPTR, &validator); + QRegExpValidator validator(QRegExp("[A-Za-z]+"),this); + QStringList list = checkCaptionAndLabel(caption, label); + return KileDialog::getText(list[0], list[1], QString(), Q_NULLPTR, &validator); } int KileInput::getInteger(const QString &caption, const QString &label, int min, int max) { - QStringList list = checkCaptionAndLabel(caption, label); - return QInputDialog::getInt(Q_NULLPTR, list[0], list[1], 0, min, max, 1); + QStringList list = checkCaptionAndLabel(caption, label); + return QInputDialog::getInt(Q_NULLPTR, list[0], list[1], 0, min, max, 1); } int KileInput::getPosInteger(const QString &caption, const QString &label, int min, int max) { - return getInteger(caption,label,min,max); + return getInteger(caption,label,min,max); } QString KileInput::getItem(const QString &caption, const QString &label, const QStringList &itemlist) { - QStringList list = checkCaptionAndLabel(caption, label); - return QInputDialog::getItem(Q_NULLPTR, list[0], list[1], itemlist, 0); + QStringList list = checkCaptionAndLabel(caption, label); + return QInputDialog::getItem(Q_NULLPTR, list[0], list[1], itemlist, 0); } QStringList KileInput::checkCaptionAndLabel(const QString &caption, const QString &label) { - QString checkedCaption = caption, checkedLabel = label; - if(caption.isEmpty()) { - checkedCaption = i18n("Enter Value"); - } - if(label.isEmpty()) { - checkedLabel = i18n("Please enter a value"); - } + QString checkedCaption = caption, checkedLabel = label; + if(caption.isEmpty()) { + checkedCaption = i18n("Enter Value"); + } + if(label.isEmpty()) { + checkedLabel = i18n("Please enter a value"); + } - return QStringList() << checkedCaption << checkedLabel; + return QStringList() << checkedCaption << checkedLabel; } ////////////////////////////////// KileWizard object ////////////////////////////////////// KileWizard::KileWizard(QObject *parent, KileInfo *kileInfo, const QMap *scriptActions) - : QObject(parent), m_kileInfo(kileInfo), m_scriptActions(scriptActions) + : QObject(parent), m_kileInfo(kileInfo), m_scriptActions(scriptActions) { } void KileWizard::tabular() { - triggerAction("wizard_tabular"); + triggerAction("wizard_tabular"); } void KileWizard::array() { - triggerAction("wizard_array"); + triggerAction("wizard_array"); } void KileWizard::tabbing() { - triggerAction("wizard_tabbing"); + triggerAction("wizard_tabbing"); } void KileWizard::floatEnvironment() { - triggerAction("wizard_float"); + triggerAction("wizard_float"); } void KileWizard::mathEnvironment() { - triggerAction("wizard_mathenv"); + triggerAction("wizard_mathenv"); } void KileWizard::postscript() { - triggerAction("wizard_postscript"); + triggerAction("wizard_postscript"); } void KileWizard::pdf() { - triggerAction("wizard_pdf"); + triggerAction("wizard_pdf"); } bool KileWizard::triggerAction(const QString &name) { - if ( name=="wizard_postscript" || name=="wizard_pdf" ) { - KTextEditor::View *view = m_kileInfo->viewManager()->currentTextView(); - if ( !view ) { - return false; - } - } + if ( name=="wizard_postscript" || name=="wizard_pdf" ) { + KTextEditor::View *view = m_kileInfo->viewManager()->currentTextView(); + if ( !view ) { + return false; + } + } - if ( m_scriptActions->contains(name) ) { - m_scriptActions->value(name)->trigger(); - return true; - } - else { - return false; - } + if ( m_scriptActions->contains(name) ) { + m_scriptActions->value(name)->trigger(); + return true; + } + else { + return false; + } } ////////////////////////////////// KileJavaScript object ////////////////////////////////////// KileJavaScript::KileJavaScript(QObject *parent) - : QObject(parent) + : QObject(parent) { } QString KileJavaScript::caption() { - return i18n("Script '%1.js'", m_scriptname); + return i18n("Script '%1.js'", m_scriptname); } ////////////////////////////////// KileFile object ////////////////////////////////////// KileFile::KileFile(QObject *parent, KileInfo *kileInfo) - : QObject(parent), m_kileInfo(kileInfo) + : QObject(parent), m_kileInfo(kileInfo) { } QMap KileFile::read(const QString& filename) const { - QMap result; + QMap result; // result["status"] = QVariant(); - result["message"] = QString(); - result["text"] = QString(); + result["message"] = QString(); + result["text"] = QString(); - QFile file(filename); - if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) { - result["message"] = i18n("File Handling Error: Unable to find the file '%1'", filename); - result["status"] = KileFile::ACCESS_FAILED; - return result; - } + QFile file(filename); + if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) { + result["message"] = i18n("File Handling Error: Unable to find the file '%1'", filename); + result["status"] = KileFile::ACCESS_FAILED; + return result; + } - // read data - QTextStream stream(&file); - stream.setCodec("UTF-8"); - result["text"] = stream.readAll(); - file.close(); + // read data + QTextStream stream(&file); + stream.setCodec("UTF-8"); + result["text"] = stream.readAll(); + file.close(); - result["status"] = KileFile::ACCESS_OK; + result["status"] = KileFile::ACCESS_OK; - return result; + return result; } QMap KileFile::read() const { - QString openedFile = m_kileInfo->getName(); - const QString filepath = (!openedFile.isEmpty()) ? QFileInfo(m_kileInfo->getName()).absolutePath() : QString(); - QString filename = QFileDialog::getOpenFileName(m_kileInfo->mainWindow(), i18n("Select File to Read"), filepath, QString()); - if(!filename.isEmpty()) { - return read(filename); - } - else { - return actionCancelled(); - } + QString openedFile = m_kileInfo->getName(); + const QString filepath = (!openedFile.isEmpty()) ? QFileInfo(m_kileInfo->getName()).absolutePath() : QString(); + QString filename = QFileDialog::getOpenFileName(m_kileInfo->mainWindow(), i18n("Select File to Read"), filepath, QString()); + if(!filename.isEmpty()) { + return read(filename); + } + else { + return actionCancelled(); + } } QMap KileFile::write(const QString& filename, const QString& text) const { - QMap result; + QMap result; - QFile file(filename); - if(!file.open(QIODevice::WriteOnly | QIODevice::Text)) { - result["status"] = KileFile::ACCESS_FAILED; - result["message"] = i18n("File Handling Error: Unable to create the output file '%1'", filename); - return result; - } + QFile file(filename); + if(!file.open(QIODevice::WriteOnly | QIODevice::Text)) { + result["status"] = KileFile::ACCESS_FAILED; + result["message"] = i18n("File Handling Error: Unable to create the output file '%1'", filename); + return result; + } - // write data - qint64 bytesWritten = 0; - const QByteArray dataToWrite = text.toUtf8(); - while(bytesWritten < dataToWrite.size()) { - qint64 bytesWrittenNow = file.write(dataToWrite.constData() + bytesWritten, dataToWrite.size() - bytesWritten); - if(bytesWrittenNow < 0) { - result["status"] = KileFile::ACCESS_FAILED; - result["message"] = i18n("File Handling Error: Unable to write to the output file '%1'", filename); - file.close(); - return result; - } - bytesWritten += bytesWrittenNow; - } - file.close(); + // write data + qint64 bytesWritten = 0; + const QByteArray dataToWrite = text.toUtf8(); + while(bytesWritten < dataToWrite.size()) { + qint64 bytesWrittenNow = file.write(dataToWrite.constData() + bytesWritten, dataToWrite.size() - bytesWritten); + if(bytesWrittenNow < 0) { + result["status"] = KileFile::ACCESS_FAILED; + result["message"] = i18n("File Handling Error: Unable to write to the output file '%1'", filename); + file.close(); + return result; + } + bytesWritten += bytesWrittenNow; + } + file.close(); - result["status"] = KileFile::ACCESS_OK; - result["message"] = QString(); + result["status"] = KileFile::ACCESS_OK; + result["message"] = QString(); - return result; + return result; } QMap KileFile::write(const QString& text) const { - QString openedFile = m_kileInfo->getName(); - const QString filepath = (!openedFile.isEmpty()) ? QFileInfo(m_kileInfo->getName()).absolutePath() : QString(); - QString filename = QFileDialog::getSaveFileName(m_kileInfo->mainWindow(), i18n("Save As"), filepath, QString()); - if(!filename.isEmpty()) { - return write(filename, text); - } - else { - return actionCancelled(); - } + QString openedFile = m_kileInfo->getName(); + const QString filepath = (!openedFile.isEmpty()) ? QFileInfo(m_kileInfo->getName()).absolutePath() : QString(); + QString filename = QFileDialog::getSaveFileName(m_kileInfo->mainWindow(), i18n("Save As"), filepath, QString()); + if(!filename.isEmpty()) { + return write(filename, text); + } + else { + return actionCancelled(); + } } QString KileFile::getOpenFileName(const QUrl &url, const QString& filter) { - QUrl startdir = (url.isEmpty()) ? QUrl::fromLocalFile(QFileInfo(m_kileInfo->getName()).absolutePath()) : url; - return QFileDialog::getOpenFileName(m_kileInfo->mainWindow(), i18n("Select File to Read"), startdir.toLocalFile(), filter); + QUrl startdir = (url.isEmpty()) ? QUrl::fromLocalFile(QFileInfo(m_kileInfo->getName()).absolutePath()) : url; + return QFileDialog::getOpenFileName(m_kileInfo->mainWindow(), i18n("Select File to Read"), startdir.toLocalFile(), filter); } QString KileFile::getSaveFileName(const QUrl &url, const QString& filter) { - QUrl startdir = (url.isEmpty()) ? QUrl::fromLocalFile(QFileInfo(m_kileInfo->getName()).absolutePath()) : url; - return QFileDialog::getSaveFileName(m_kileInfo->mainWindow(), i18n("Save As"), startdir.toLocalFile(), filter ); + QUrl startdir = (url.isEmpty()) ? QUrl::fromLocalFile(QFileInfo(m_kileInfo->getName()).absolutePath()) : url; + return QFileDialog::getSaveFileName(m_kileInfo->mainWindow(), i18n("Save As"), startdir.toLocalFile(), filter ); } QMap KileFile::actionCancelled() const { - QMap result; - result["status"] = KileFile::ACCESS_FAILED; - result["message"] = i18n("This action was canceled by the user."); - result["text"] = QString(); - return result; + QMap result; + result["status"] = KileFile::ACCESS_FAILED; + result["message"] = i18n("This action was canceled by the user."); + result["text"] = QString(); + return result; } ////////////////////////////////// KileScript object ////////////////////////////////////// KileScriptObject::KileScriptObject(QObject *parent, KileInfo* kileInfo, const QMap *scriptActions) - : QObject(parent), m_kileInfo(kileInfo) + : QObject(parent), m_kileInfo(kileInfo) { - m_kileAlert = new KileAlert(this,m_kileInfo->mainWindow()); - m_kileInput = new KileInput(this); - m_kileWizard = new KileWizard(this,m_kileInfo,scriptActions); - m_kileScript = new KileJavaScript(this); - m_kileFile = new KileFile(this,m_kileInfo); + m_kileAlert = new KileAlert(this,m_kileInfo->mainWindow()); + m_kileInput = new KileInput(this); + m_kileWizard = new KileWizard(this,m_kileInfo,scriptActions); + m_kileScript = new KileJavaScript(this); + m_kileFile = new KileFile(this,m_kileInfo); } void KileScriptObject::setScriptname(const QString &name) { - m_kileScript->setScriptname(name); + m_kileScript->setScriptname(name); } } diff --git a/src/scripting/kilescriptobject.h b/src/scripting/kilescriptobject.h index fe26c7e5..48314b42 100644 --- a/src/scripting/kilescriptobject.h +++ b/src/scripting/kilescriptobject.h @@ -1,193 +1,207 @@ /****************************************************************************** Copyright (C) 2011-2012 by Holger Danielsson (holger.danielsson@versanet.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. * * * ***************************************************************************/ #ifndef KILE_SCRIPT_OBJECT_H #define KILE_SCRIPT_OBJECT_H #include #include #include #include #include #include class KileInfo; class KileMainWindow; namespace KileScript { ////////////////////////////////// KileAlert object ////////////////////////////////////// class KileAlert : public QObject { - Q_OBJECT + Q_OBJECT - public: - KileAlert(QObject *parent, KParts::MainWindow *mainWindow); - virtual ~KileAlert() {} +public: + KileAlert(QObject *parent, KParts::MainWindow *mainWindow); + virtual ~KileAlert() {} - Q_INVOKABLE void information(const QString &text, const QString &caption = QString()); - Q_INVOKABLE void sorry(const QString &text, const QString &caption = QString()); - Q_INVOKABLE void error(const QString &text, const QString &caption = QString()); - Q_INVOKABLE QString question(const QString &text, const QString &caption = QString()); - Q_INVOKABLE QString warning(const QString &text, const QString &caption = QString()); + Q_INVOKABLE void information(const QString &text, const QString &caption = QString()); + Q_INVOKABLE void sorry(const QString &text, const QString &caption = QString()); + Q_INVOKABLE void error(const QString &text, const QString &caption = QString()); + Q_INVOKABLE QString question(const QString &text, const QString &caption = QString()); + Q_INVOKABLE QString warning(const QString &text, const QString &caption = QString()); - private: - KParts::MainWindow *m_mainWindow; +private: + KParts::MainWindow *m_mainWindow; }; ////////////////////////////////// KileInput object ////////////////////////////////////// class KileInput : public QObject { - Q_OBJECT - - public: - KileInput(QObject *parent); - virtual ~KileInput() {} - - // get input values - Q_INVOKABLE QString getListboxItem(const QString &caption, const QString &label, const QStringList &list); - Q_INVOKABLE QString getText(const QString &caption, const QString &label); - Q_INVOKABLE QString getLatexCommand(const QString &caption, const QString &label); - Q_INVOKABLE int getInteger(const QString &caption, const QString &label, int min = INT_MIN, int max = INT_MAX); - Q_INVOKABLE int getPosInteger(const QString &caption, const QString &label, int min = 1, int max = INT_MAX); - - private: - KileMainWindow *m_mainWindow; - QString getItem(const QString& caption, const QString& label, const QStringList &itemlist); - QStringList checkCaptionAndLabel(const QString& caption, const QString& label); + Q_OBJECT + +public: + KileInput(QObject *parent); + virtual ~KileInput() {} + + // get input values + Q_INVOKABLE QString getListboxItem(const QString &caption, const QString &label, const QStringList &list); + Q_INVOKABLE QString getText(const QString &caption, const QString &label); + Q_INVOKABLE QString getLatexCommand(const QString &caption, const QString &label); + Q_INVOKABLE int getInteger(const QString &caption, const QString &label, int min = INT_MIN, int max = INT_MAX); + Q_INVOKABLE int getPosInteger(const QString &caption, const QString &label, int min = 1, int max = INT_MAX); + +private: + KileMainWindow *m_mainWindow; + QString getItem(const QString& caption, const QString& label, const QStringList &itemlist); + QStringList checkCaptionAndLabel(const QString& caption, const QString& label); }; ////////////////////////////////// KileWizard object ////////////////////////////////////// class KileWizard : public QObject { - Q_OBJECT + Q_OBJECT - public: - KileWizard(QObject *parent, KileInfo *kileInfo, const QMap *scriptActions); - virtual ~KileWizard() {} +public: + KileWizard(QObject *parent, KileInfo *kileInfo, const QMap *scriptActions); + virtual ~KileWizard() {} - // wizards - Q_INVOKABLE void tabular(); - Q_INVOKABLE void array(); - Q_INVOKABLE void tabbing(); - Q_INVOKABLE void floatEnvironment(); - Q_INVOKABLE void mathEnvironment(); - Q_INVOKABLE void postscript(); - Q_INVOKABLE void pdf(); + // wizards + Q_INVOKABLE void tabular(); + Q_INVOKABLE void array(); + Q_INVOKABLE void tabbing(); + Q_INVOKABLE void floatEnvironment(); + Q_INVOKABLE void mathEnvironment(); + Q_INVOKABLE void postscript(); + Q_INVOKABLE void pdf(); - private: - KileInfo *m_kileInfo; - const QMap *m_scriptActions; +private: + KileInfo *m_kileInfo; + const QMap *m_scriptActions; - bool triggerAction(const QString &name); + bool triggerAction(const QString &name); }; ////////////////////////////////// KileJavaScript object ////////////////////////////////////// class KileJavaScript : public QObject { - Q_OBJECT + Q_OBJECT - public: - KileJavaScript(QObject *parent); - virtual ~KileJavaScript() {} +public: + KileJavaScript(QObject *parent); + virtual ~KileJavaScript() {} - void setScriptname(const QString &name) { m_scriptname = name; } + void setScriptname(const QString &name) { + m_scriptname = name; + } - Q_INVOKABLE QString name() const { return m_scriptname; } - Q_INVOKABLE QString caption(); + Q_INVOKABLE QString name() const { + return m_scriptname; + } + Q_INVOKABLE QString caption(); - private: - QString m_scriptname; +private: + QString m_scriptname; }; ////////////////////////////////// KileFile object ////////////////////////////////////// class KileFile : public QObject { - Q_OBJECT + Q_OBJECT - public: +public: - enum AccessResult { - ACCESS_OK = 0, - ACCESS_FAILED, - ACCESS_DENIED - }; + enum AccessResult { + ACCESS_OK = 0, + ACCESS_FAILED, + ACCESS_DENIED + }; - KileFile(QObject *parent, KileInfo *kileInfo); - virtual ~KileFile() {} + KileFile(QObject *parent, KileInfo *kileInfo); + virtual ~KileFile() {} - // Read the contents of a file. If no filename is given, getOpenFileName() is called first - Q_INVOKABLE QMap read(const QString& filename) const; - Q_INVOKABLE QMap read() const; + // Read the contents of a file. If no filename is given, getOpenFileName() is called first + Q_INVOKABLE QMap read(const QString& filename) const; + Q_INVOKABLE QMap read() const; - // Write text into a file. If no filename is given, getSaveFileName() is called first - Q_INVOKABLE QMap write(const QString& filename, const QString& text) const; - Q_INVOKABLE QMap write(const QString& text) const; + // Write text into a file. If no filename is given, getSaveFileName() is called first + Q_INVOKABLE QMap write(const QString& filename, const QString& text) const; + Q_INVOKABLE QMap write(const QString& text) const; - // Open/Save dialogs from KFileDialog - Q_INVOKABLE QString getOpenFileName(const QUrl &url = QUrl(), const QString& filter = QString()); - Q_INVOKABLE QString getSaveFileName(const QUrl &url = QUrl(), const QString& filter = QString()); + // Open/Save dialogs from KFileDialog + Q_INVOKABLE QString getOpenFileName(const QUrl &url = QUrl(), const QString& filter = QString()); + Q_INVOKABLE QString getSaveFileName(const QUrl &url = QUrl(), const QString& filter = QString()); - private: - KileInfo *m_kileInfo; +private: + KileInfo *m_kileInfo; - QMap actionCancelled() const; + QMap actionCancelled() const; }; ////////////////////////////////// KileScript object ////////////////////////////////////// class KileScriptObject : public QObject { - Q_OBJECT - - Q_PROPERTY(QObject* alert READ getAlert); - Q_PROPERTY(QObject* input READ getInput); - Q_PROPERTY(QObject* wizard READ getWizard); - Q_PROPERTY(QObject* script READ getScript); - Q_PROPERTY(QObject* file READ getFile); - - public: - KileScriptObject(QObject *parent, KileInfo *kileInfo, const QMap *scriptActions); - virtual ~KileScriptObject() {} - - QObject* getAlert() { return m_kileAlert; } - QObject* getInput() { return m_kileInput; } - QObject* getWizard() { return m_kileWizard; } - QObject* getScript() { return m_kileScript; } - QObject* getFile() { return m_kileFile; } - - void setScriptname(const QString &name); - - private: - KileInfo* m_kileInfo; - - KileAlert *m_kileAlert; - KileInput *m_kileInput; - KileWizard *m_kileWizard; - KileJavaScript *m_kileScript; - KileFile *m_kileFile; + Q_OBJECT + + Q_PROPERTY(QObject* alert READ getAlert); + Q_PROPERTY(QObject* input READ getInput); + Q_PROPERTY(QObject* wizard READ getWizard); + Q_PROPERTY(QObject* script READ getScript); + Q_PROPERTY(QObject* file READ getFile); + +public: + KileScriptObject(QObject *parent, KileInfo *kileInfo, const QMap *scriptActions); + virtual ~KileScriptObject() {} + + QObject* getAlert() { + return m_kileAlert; + } + QObject* getInput() { + return m_kileInput; + } + QObject* getWizard() { + return m_kileWizard; + } + QObject* getScript() { + return m_kileScript; + } + QObject* getFile() { + return m_kileFile; + } + + void setScriptname(const QString &name); + +private: + KileInfo* m_kileInfo; + + KileAlert *m_kileAlert; + KileInput *m_kileInput; + KileWizard *m_kileWizard; + KileJavaScript *m_kileScript; + KileFile *m_kileFile; }; } #endif diff --git a/src/scripting/kilescriptview.cpp b/src/scripting/kilescriptview.cpp index 1f3dfacc..7a1fb0d9 100644 --- a/src/scripting/kilescriptview.cpp +++ b/src/scripting/kilescriptview.cpp @@ -1,212 +1,212 @@ /****************************************************************************** Copyright (C) 2006-2008 by Michel Ludwig (michel.ludwig@kdemail.net) 2011-2012 by Holger Danielsson (holger.danielsson@versanet.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. * * * ***************************************************************************/ #include "kilescriptview.h" #include "kiledebug.h" namespace KileScript { KileScriptView::KileScriptView(QObject *parent, KileDocument::EditorExtension *editor) - : QObject(parent), m_view(0), m_editor(editor) + : QObject(parent), m_view(0), m_editor(editor) { } ////////////////////////////////// view ////////////////////////////////////// void KileScriptView::setView (KTextEditor::View *view) { - m_view = view; + m_view = view; } KTextEditor::View *KileScriptView::view() const { - return m_view; + return m_view; } ////////////////////////////////// cursor ////////////////////////////////////// void KileScriptView::backspace() { - QAction *action = m_view->action("backspace"); - if(action) { - action->trigger(); - } + QAction *action = m_view->action("backspace"); + if(action) { + action->trigger(); + } } KTextEditor::Cursor KileScriptView::cursorPosition() { - return m_view->cursorPosition(); + return m_view->cursorPosition(); } void KileScriptView::setCursorPosition(int line, int column) { - setCursorPosition( KTextEditor::Cursor(line, column) ); + setCursorPosition( KTextEditor::Cursor(line, column) ); } void KileScriptView::setCursorPosition (const KTextEditor::Cursor& cursor) { - m_view->setCursorPosition(cursor); + m_view->setCursorPosition(cursor); } KTextEditor::Cursor KileScriptView::virtualCursorPosition() { - return m_view->cursorPositionVirtual(); + return m_view->cursorPositionVirtual(); } void KileScriptView::cursorLeft() { - m_editor->moveCursorLeft(m_view); + m_editor->moveCursorLeft(m_view); } void KileScriptView::cursorRight() { - m_editor->moveCursorRight(m_view); + m_editor->moveCursorRight(m_view); } void KileScriptView::cursorUp() { - m_editor->moveCursorUp(m_view); + m_editor->moveCursorUp(m_view); } void KileScriptView::cursorDown() { - m_editor->moveCursorDown(m_view); + m_editor->moveCursorDown(m_view); } int KileScriptView::cursorLine() { - return m_view->cursorPosition().line(); + return m_view->cursorPosition().line(); } int KileScriptView::cursorColumn() { - return m_view->cursorPosition().column(); + return m_view->cursorPosition().column(); } void KileScriptView::setCursorLine(int l) { - KTextEditor::Cursor cursor = m_view->cursorPosition(); - cursor.setLine(l); - m_view->setCursorPosition(cursor); + KTextEditor::Cursor cursor = m_view->cursorPosition(); + cursor.setLine(l); + m_view->setCursorPosition(cursor); } void KileScriptView::setCursorColumn(int c) { - KTextEditor::Cursor cursor = m_view->cursorPosition(); - cursor.setColumn(c); - m_view->setCursorPosition(cursor); + KTextEditor::Cursor cursor = m_view->cursorPosition(); + cursor.setColumn(c); + m_view->setCursorPosition(cursor); } ////////////////////////////////// selection ////////////////////////////////////// bool KileScriptView::hasSelection() { - return m_view->selection(); + return m_view->selection(); } QString KileScriptView::selectedText() { - return m_view->selectionText(); + return m_view->selectionText(); } KTextEditor::Range KileScriptView::selectionRange() { - return m_view->selectionRange(); + return m_view->selectionRange(); } void KileScriptView::setSelection(const KTextEditor::Range& range) { - m_view->setSelection(range); + m_view->setSelection(range); } void KileScriptView::selectAll() { - m_view->setSelection( m_view->document()->documentRange() ); + m_view->setSelection( m_view->document()->documentRange() ); } void KileScriptView::clearSelection() { - m_view->removeSelection(); + m_view->removeSelection(); } void KileScriptView::removeSelectedText() { - m_view->removeSelectionText(); + m_view->removeSelectionText(); } /////////////////////////////// line ////////////////////////////// void KileScriptView::selectLine() { - m_editor->selectLine(m_view); + m_editor->selectLine(m_view); } void KileScriptView::selectLine(int line) { - m_editor->selectLine(line,m_view); + m_editor->selectLine(line,m_view); } void KileScriptView::selectLines(int from, int to) { - m_editor->selectLines(from,to,m_view); + m_editor->selectLines(from,to,m_view); } /////////////////////////////// word ////////////////////////////// void KileScriptView::selectWord() { - m_editor->selectWord(KileDocument::EditorExtension::smLetter,m_view); + m_editor->selectWord(KileDocument::EditorExtension::smLetter,m_view); } /////////////////////////////// latex command ////////////////////////////// void KileScriptView::selectLatexCommand() { - m_editor->selectWord(KileDocument::EditorExtension::smTex,m_view); + m_editor->selectWord(KileDocument::EditorExtension::smTex,m_view); } /////////////////////////////// environment ////////////////////////////// void KileScriptView::selectEnvironment(bool inside) { - m_editor->selectEnvironment(inside,m_view); + m_editor->selectEnvironment(inside,m_view); } ////////////////////////////////// TexGroup ////////////////////////////////////// void KileScriptView::selectTexgroup(bool inside) { - return m_editor->selectTexgroup(inside,m_view); + return m_editor->selectTexgroup(inside,m_view); } ////////////////////////////////// MathGroup ////////////////////////////////////// void KileScriptView::selectMathgroup() { - m_editor->selectMathgroup(m_view); + m_editor->selectMathgroup(m_view); } ////////////////////////////////// Paragraph ////////////////////////////////////// void KileScriptView::selectParagraph(bool wholeLines) { - m_editor->selectParagraph(m_view, wholeLines); + m_editor->selectParagraph(m_view, wholeLines); } } diff --git a/src/scripting/kilescriptview.h b/src/scripting/kilescriptview.h index b246c197..6d458d8d 100644 --- a/src/scripting/kilescriptview.h +++ b/src/scripting/kilescriptview.h @@ -1,102 +1,102 @@ /****************************************************************************** Copyright (C) 2006-2008 by Michel Ludwig (michel.ludwig@kdemail.net) 2011-2012 by Holger Danielsson (holger.danielsson@versanet.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. * * * ***************************************************************************/ #ifndef KILE_SCRIPT_VIEW_H #define KILE_SCRIPT_VIEW_H #include #include #include #include #include #include #include #include "editorextension.h" namespace KileScript { class KileScriptView : public QObject, protected QScriptable { - Q_OBJECT + Q_OBJECT - public: - KileScriptView (QObject *parent, KileDocument::EditorExtension *editor); - virtual ~KileScriptView() {} +public: + KileScriptView (QObject *parent, KileDocument::EditorExtension *editor); + virtual ~KileScriptView() {} - void setView(KTextEditor::View *view); - KTextEditor::View *view() const; + void setView(KTextEditor::View *view); + KTextEditor::View *view() const; - // cursor - Q_INVOKABLE KTextEditor::Cursor cursorPosition (); - Q_INVOKABLE void setCursorPosition(int line, int column); - Q_INVOKABLE void setCursorPosition(const KTextEditor::Cursor& cursor); + // cursor + Q_INVOKABLE KTextEditor::Cursor cursorPosition (); + Q_INVOKABLE void setCursorPosition(int line, int column); + Q_INVOKABLE void setCursorPosition(const KTextEditor::Cursor& cursor); - Q_INVOKABLE void backspace(); + Q_INVOKABLE void backspace(); - Q_INVOKABLE void cursorLeft(); - Q_INVOKABLE void cursorRight(); - Q_INVOKABLE void cursorUp(); - Q_INVOKABLE void cursorDown(); + Q_INVOKABLE void cursorLeft(); + Q_INVOKABLE void cursorRight(); + Q_INVOKABLE void cursorUp(); + Q_INVOKABLE void cursorDown(); - Q_INVOKABLE int cursorLine(); - Q_INVOKABLE int cursorColumn(); - Q_INVOKABLE void setCursorLine(int l); - Q_INVOKABLE void setCursorColumn(int c); + Q_INVOKABLE int cursorLine(); + Q_INVOKABLE int cursorColumn(); + Q_INVOKABLE void setCursorLine(int l); + Q_INVOKABLE void setCursorColumn(int c); - Q_INVOKABLE KTextEditor::Cursor virtualCursorPosition(); + Q_INVOKABLE KTextEditor::Cursor virtualCursorPosition(); - // selection - Q_INVOKABLE bool hasSelection(); - Q_INVOKABLE QString selectedText(); - Q_INVOKABLE KTextEditor::Range selectionRange(); - Q_INVOKABLE void setSelection(const KTextEditor::Range& range); - Q_INVOKABLE void selectAll(); + // selection + Q_INVOKABLE bool hasSelection(); + Q_INVOKABLE QString selectedText(); + Q_INVOKABLE KTextEditor::Range selectionRange(); + Q_INVOKABLE void setSelection(const KTextEditor::Range& range); + Q_INVOKABLE void selectAll(); - Q_INVOKABLE void clearSelection(); - Q_INVOKABLE void removeSelectedText(); + Q_INVOKABLE void clearSelection(); + Q_INVOKABLE void removeSelectedText(); - // line - Q_INVOKABLE void selectLine(); - Q_INVOKABLE void selectLine(int line); - Q_INVOKABLE void selectLines(int from, int to); + // line + Q_INVOKABLE void selectLine(); + Q_INVOKABLE void selectLine(int line); + Q_INVOKABLE void selectLines(int from, int to); - // word - Q_INVOKABLE void selectWord(); + // word + Q_INVOKABLE void selectWord(); - // latex command - Q_INVOKABLE void selectLatexCommand(); + // latex command + Q_INVOKABLE void selectLatexCommand(); - // environment - Q_INVOKABLE void selectEnvironment(bool inside = false); + // environment + Q_INVOKABLE void selectEnvironment(bool inside = false); - // texgroup - Q_INVOKABLE void selectTexgroup(bool inside = true); + // texgroup + Q_INVOKABLE void selectTexgroup(bool inside = true); - // mathgroup - Q_INVOKABLE void selectMathgroup(); + // mathgroup + Q_INVOKABLE void selectMathgroup(); - // paragraph - Q_INVOKABLE void selectParagraph(bool wholeLines = true); + // paragraph + Q_INVOKABLE void selectParagraph(bool wholeLines = true); - private: - KTextEditor::View *m_view; - KileDocument::EditorExtension *m_editor; +private: + KTextEditor::View *m_view; + KileDocument::EditorExtension *m_editor; }; } #endif diff --git a/src/scripting/script.cpp b/src/scripting/script.cpp index 4a6a047c..dcde7a4b 100644 --- a/src/scripting/script.cpp +++ b/src/scripting/script.cpp @@ -1,311 +1,311 @@ /****************************************************************************** Copyright (C) 2006-2017 by Michel Ludwig (michel.ludwig@kdemail.net) 2011-2012 by Holger Danielsson (holger.danielsson@versanet.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. * * * ***************************************************************************/ #include #include #include #include #include #include #include #include #include #include #include "kileinfo.h" #include "kiledebug.h" #include "scripting/script.h" #include "scripting/kilescriptobject.h" #include "scripting/kilescriptview.h" #include "scripting/kilescriptdocument.h" namespace KileScript { /* // Modified declaration from // Acknowledgements go to: // Copyright (C) 1999 Harri Porten (porten@kde.org) // Copyright (C) 2001 Peter Kelly (pmk@post.com) class KJSCPUGuard { public: KJSCPUGuard() {} void start(unsigned int msec=5000, unsigned int i_msec=0); void stop(); private: void (*oldAlarmHandler)(int); static void alarmHandler(int); itimerval oldtv; }; // Modified implementation originating from // Acknowledgements go to: // Copyright (C) 1999-2001 Harri Porten (porten@kde.org) // Copyright (C) 2001,2003 Peter Kelly (pmk@post.com) // Copyright (C) 2001-2003 David Faure (faure@kde.org) void KJSCPUGuard::start(unsigned int ms, unsigned int i_ms) { oldAlarmHandler = signal(SIGVTALRM, alarmHandler); itimerval tv = { { i_ms / 1000, (i_ms % 1000) * 1000 }, { ms / 1000, (ms % 1000) * 1000 } }; setitimer(ITIMER_VIRTUAL, &tv, &oldtv); } void KJSCPUGuard::stop() { setitimer(ITIMER_VIRTUAL, &oldtv, Q_NULLPTR); signal(SIGVTALRM, oldAlarmHandler); } void KJSCPUGuard::alarmHandler(int) { // KJS::ExecState::requestTerminate(); } */ #ifdef __GNUC__ #warning "Fix time limit functionality!" #endif //BEGIN QtScript conversion functions for Cursors and Ranges /** Conversion function from KTextEditor::Cursor to QtScript cursor */ static QScriptValue cursorToScriptValue(QScriptEngine *engine, const KTextEditor::Cursor &cursor) { - QString code = QString("new Cursor(%1, %2);").arg(cursor.line()) - .arg(cursor.column()); - return engine->evaluate(code); + QString code = QString("new Cursor(%1, %2);").arg(cursor.line()) + .arg(cursor.column()); + return engine->evaluate(code); } /** Conversion function from QtScript cursor to KTextEditor::Cursor */ static void cursorFromScriptValue(const QScriptValue &obj, KTextEditor::Cursor &cursor) { - cursor.setPosition(obj.property(QStringLiteral("line")).toInt32(), - obj.property(QStringLiteral("column")).toInt32()); + cursor.setPosition(obj.property(QStringLiteral("line")).toInt32(), + obj.property(QStringLiteral("column")).toInt32()); } /** Conversion function from QtScript range to KTextEditor::Range */ static QScriptValue rangeToScriptValue(QScriptEngine *engine, const KTextEditor::Range &range) { - QString code = QString("new Range(%1, %2, %3, %4);").arg(range.start().line()) - .arg(range.start().column()) - .arg(range.end().line()) - .arg(range.end().column()); - return engine->evaluate(code); + QString code = QString("new Range(%1, %2, %3, %4);").arg(range.start().line()) + .arg(range.start().column()) + .arg(range.end().line()) + .arg(range.end().column()); + return engine->evaluate(code); } /** Conversion function from QtScript range to KTextEditor::Range */ static void rangeFromScriptValue(const QScriptValue &obj, KTextEditor::Range &range) { - range.setStart(KTextEditor::Cursor(obj.property(QStringLiteral("start")).property(QStringLiteral("line")).toInt32(), - obj.property(QStringLiteral("start")).property(QStringLiteral("column")).toInt32())); - range.setEnd(KTextEditor::Cursor(obj.property(QStringLiteral("end")).property(QStringLiteral("line")).toInt32(), - obj.property(QStringLiteral("end")).property(QStringLiteral("column")).toInt32())); + range.setStart(KTextEditor::Cursor(obj.property(QStringLiteral("start")).property(QStringLiteral("line")).toInt32(), + obj.property(QStringLiteral("start")).property(QStringLiteral("column")).toInt32())); + range.setEnd(KTextEditor::Cursor(obj.property(QStringLiteral("end")).property(QStringLiteral("line")).toInt32(), + obj.property(QStringLiteral("end")).property(QStringLiteral("column")).toInt32())); } //END ////////////////////////////// Script ////////////////////////////// /* The IDs of the scripts are used to maintain correct bindings with QAction objects, i.e. for example, we * want to make sure the action script_execution_0 always refers to same script (the script with id 0 !), even * after reloading all the scripts. */ Script::Script(unsigned int id, const QString& file) - : m_id(id), m_file(file), m_action(Q_NULLPTR), m_sequencetype(KEY_SEQUENCE) + : m_id(id), m_file(file), m_action(Q_NULLPTR), m_sequencetype(KEY_SEQUENCE) { - m_name = QFileInfo(file).fileName(); + m_name = QFileInfo(file).fileName(); - if(m_name.endsWith(".js")) { // remove the extension - m_name = m_name.left(m_name.length() - 3); - } + if(m_name.endsWith(".js")) { // remove the extension + m_name = m_name.left(m_name.length() - 3); + } } QString Script::getCode() const { - return readFile(m_file); + return readFile(m_file); } QString Script::getName() const { - return m_name; + return m_name; } QString Script::getFileName() const { - return m_file; + return m_file; } unsigned int Script::getID() const { - return m_id; + return m_id; } void Script::setID(unsigned int id) { - m_id = id; + m_id = id; } void Script::setActionObject(QAction * action) { - m_action = action; + m_action = action; } // const QAction * Script::getActionObject() const // { // return m_action; // } QAction * Script::getActionObject() const { - return m_action; + return m_action; } void Script::setKeySequence(const QString& str) { - m_keySequence = str; + m_keySequence = str; } QString Script::getKeySequence() const { - return m_keySequence; + return m_keySequence; } int Script::getSequenceType() const { - return m_sequencetype; + return m_sequencetype; } void Script::setSequenceType(int type) { - m_sequencetype = type; + m_sequencetype = type; } QString Script::readFile(const QString &filename) { - QFile file(filename); - if ( !file.open(QIODevice::ReadOnly) ) { - KILE_DEBUG_MAIN << i18n("Unable to find '%1'", filename); - return QString(); - } else { - QTextStream stream(&file); - stream.setCodec("UTF-8"); - QString text = stream.readAll(); - file.close(); - return text; - } + QFile file(filename); + if ( !file.open(QIODevice::ReadOnly) ) { + KILE_DEBUG_MAIN << i18n("Unable to find '%1'", filename); + return QString(); + } else { + QTextStream stream(&file); + stream.setCodec("UTF-8"); + QString text = stream.readAll(); + file.close(); + return text; + } } ////////////////////////////// ScriptEnvironment ////////////////////////////// ScriptEnvironment::ScriptEnvironment(KileInfo *kileInfo, - KileScriptView *scriptView, KileScriptDocument *scriptDocument, - KileScriptObject *scriptObject, const QString &pluginCode) - : m_kileInfo(kileInfo), m_scriptView(scriptView), m_scriptDocument(scriptDocument), - m_kileScriptObject(scriptObject), m_enginePluginCode(pluginCode) + KileScriptView *scriptView, KileScriptDocument *scriptDocument, + KileScriptObject *scriptObject, const QString &pluginCode) + : m_kileInfo(kileInfo), m_scriptView(scriptView), m_scriptDocument(scriptDocument), + m_kileScriptObject(scriptObject), m_enginePluginCode(pluginCode) { - KILE_DEBUG_MAIN << "create ScriptEnvironment"; - m_engine = new QScriptEngine(); - qScriptRegisterMetaType(m_engine, cursorToScriptValue, cursorFromScriptValue); - qScriptRegisterMetaType(m_engine, rangeToScriptValue, rangeFromScriptValue); + KILE_DEBUG_MAIN << "create ScriptEnvironment"; + m_engine = new QScriptEngine(); + qScriptRegisterMetaType(m_engine, cursorToScriptValue, cursorFromScriptValue); + qScriptRegisterMetaType(m_engine, rangeToScriptValue, rangeFromScriptValue); } ScriptEnvironment::~ScriptEnvironment() { - delete m_engine; + delete m_engine; } // Executes script code in this environment. void ScriptEnvironment::execute(const Script *script) { - // initialize engine to work with Cursor and Range objects - m_engine->evaluate(m_enginePluginCode, i18n("Cursor/Range plugin")); - - if(m_engine->hasUncaughtException()) { - scriptError(i18n("Cursor/Range plugin")); - return; - } - else { - KILE_DEBUG_MAIN << "Cursor/Range plugin successfully installed "; - } - - // set global objects - if(m_scriptView->view()) { - m_engine->globalObject().setProperty("view", m_engine->newQObject(m_scriptView)); - m_engine->globalObject().setProperty("document", m_engine->newQObject(m_scriptDocument)); - } - m_engine->globalObject().setProperty("kile", m_engine->newQObject(m_kileScriptObject)); - - // export debug function - m_engine->globalObject().setProperty("debug", m_engine->newFunction(KileScript::debug)); - - // start engine - m_engine->evaluate(script->getCode()); - - // success or error - if(m_engine->hasUncaughtException()) { - scriptError(script->getName()); - } - else { - KILE_DEBUG_MAIN << "script finished without errors"; - } - - //FIXME: add time execution limit once it becomes available + // initialize engine to work with Cursor and Range objects + m_engine->evaluate(m_enginePluginCode, i18n("Cursor/Range plugin")); + + if(m_engine->hasUncaughtException()) { + scriptError(i18n("Cursor/Range plugin")); + return; + } + else { + KILE_DEBUG_MAIN << "Cursor/Range plugin successfully installed "; + } + + // set global objects + if(m_scriptView->view()) { + m_engine->globalObject().setProperty("view", m_engine->newQObject(m_scriptView)); + m_engine->globalObject().setProperty("document", m_engine->newQObject(m_scriptDocument)); + } + m_engine->globalObject().setProperty("kile", m_engine->newQObject(m_kileScriptObject)); + + // export debug function + m_engine->globalObject().setProperty("debug", m_engine->newFunction(KileScript::debug)); + + // start engine + m_engine->evaluate(script->getCode()); + + // success or error + if(m_engine->hasUncaughtException()) { + scriptError(script->getName()); + } + else { + KILE_DEBUG_MAIN << "script finished without errors"; + } + +//FIXME: add time execution limit once it becomes available // bool useGuard = KileConfig::timeLimitEnabled(); // uint timeLimit = (uint)KileConfig::timeLimit(); // KJSCPUGuard guard; // if(useGuard) { // guard.start(timeLimit*1000); // } // KJS::Completion completion = m_interpreter->evaluate(QString(), 0, s); // if(useGuard) { // guard.stop(); // } - QTimer::singleShot(0, m_scriptView->view(), SLOT(setFocus())); + QTimer::singleShot(0, m_scriptView->view(), SLOT(setFocus())); - // remove global objects - m_engine->globalObject().setProperty("view", QScriptValue()); - m_engine->globalObject().setProperty("document", QScriptValue()); - m_engine->globalObject().setProperty("kile", QScriptValue()); + // remove global objects + m_engine->globalObject().setProperty("view", QScriptValue()); + m_engine->globalObject().setProperty("document", QScriptValue()); + m_engine->globalObject().setProperty("kile", QScriptValue()); } // Executes script code in this environment. void ScriptEnvironment::scriptError(const QString &name) { - int errorline = m_engine->uncaughtExceptionLineNumber(); - QScriptValue exception = m_engine->uncaughtException(); - QString errormessage = ( exception.isError() ) ? exception.toString() : QString(); - QString message = i18n("An error has occurred at line %1 during the execution of the script \"%2\":\n%3", errorline, name, errormessage); - KMessageBox::sorry(m_kileInfo->mainWindow(), message, i18n("Error")); + int errorline = m_engine->uncaughtExceptionLineNumber(); + QScriptValue exception = m_engine->uncaughtException(); + QString errormessage = ( exception.isError() ) ? exception.toString() : QString(); + QString message = i18n("An error has occurred at line %1 during the execution of the script \"%2\":\n%3", errorline, name, errormessage); + KMessageBox::sorry(m_kileInfo->mainWindow(), message, i18n("Error")); } ////////////////////////////// ScriptHelpers ////////////////////////////// QScriptValue debug(QScriptContext *context, QScriptEngine *engine) { - QStringList message; - for(int i = 0; i < context->argumentCount(); ++i) { - message << context->argument(i).toString(); - } - // debug output in blue to distinguish it from other debug output - std::cout << "\033[34m" << qPrintable(message.join(' ')) << "\033[0m\n"; - return engine->nullValue(); + QStringList message; + for(int i = 0; i < context->argumentCount(); ++i) { + message << context->argument(i).toString(); + } + // debug output in blue to distinguish it from other debug output + std::cout << "\033[34m" << qPrintable(message.join(' ')) << "\033[0m\n"; + return engine->nullValue(); } } diff --git a/src/scripting/script.h b/src/scripting/script.h index 66cc8ad7..4399f15d 100644 --- a/src/scripting/script.h +++ b/src/scripting/script.h @@ -1,155 +1,155 @@ /****************************************************************************** Copyright (C) 2006-2008 by Michel Ludwig (michel.ludwig@kdemail.net) 2011-2012 by Holger Danielsson (holger.danielsson@versanet.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. * * * ***************************************************************************/ #ifndef SCRIPT_H #define SCRIPT_H #include #include #include #include #include class KileInfo; namespace KileScript { class KileScriptObject; class KileScriptView; class KileScriptDocument; ////////////////////////////// Script ////////////////////////////// /** * This class represents a script. **/ class Script { - public: - enum SequenceType { - KEY_SEQUENCE = 0, - KEY_SHORTCUT - }; - - /** - * Constructs a new JavaScript script. - * @param file the file that contains the script - **/ - Script(unsigned int id, const QString& file); - virtual ~Script() {} - - /** - * Returns the code of this script, i.e. the file is read and its contents are - * returned. - **/ - QString getCode() const; - - /** - * Returns the name of the script (the base name of the file). - **/ - QString getName() const; - - /** - * Returns the file of the script (the full path, including the base name). - **/ - QString getFileName() const; - - /** - * Returns the unique identifier of this script. - **/ - unsigned int getID() const; - - /** - * Sets the unique identifier of this script. - **/ - void setID(unsigned int id); - - - /** - * - **/ - void setActionObject(QAction * action); +public: + enum SequenceType { + KEY_SEQUENCE = 0, + KEY_SHORTCUT + }; + + /** + * Constructs a new JavaScript script. + * @param file the file that contains the script + **/ + Script(unsigned int id, const QString& file); + virtual ~Script() {} + + /** + * Returns the code of this script, i.e. the file is read and its contents are + * returned. + **/ + QString getCode() const; + + /** + * Returns the name of the script (the base name of the file). + **/ + QString getName() const; + + /** + * Returns the file of the script (the full path, including the base name). + **/ + QString getFileName() const; + + /** + * Returns the unique identifier of this script. + **/ + unsigned int getID() const; + + /** + * Sets the unique identifier of this script. + **/ + void setID(unsigned int id); + + + /** + * + **/ + void setActionObject(QAction * action); // const QAction * getActionObject() const; - QAction * getActionObject() const; + QAction * getActionObject() const; - void setKeySequence(const QString& str); - QString getKeySequence() const; + void setKeySequence(const QString& str); + QString getKeySequence() const; - int getSequenceType() const; - void setSequenceType(int type); + int getSequenceType() const; + void setSequenceType(int type); - static QString readFile(const QString &filename); + static QString readFile(const QString &filename); private: - unsigned int m_id; - QString m_code; - QString m_file; - QString m_name; - QAction *m_action; - QString m_keySequence; - int m_sequencetype; - + unsigned int m_id; + QString m_code; + QString m_file; + QString m_name; + QAction *m_action; + QString m_keySequence; + int m_sequencetype; + }; ////////////////////////////// ScriptEnvironment ////////////////////////////// /** * This class represents the environment that is used to execute Kile's scripts * in. **/ class ScriptEnvironment { - public: - /** - * Constructs a new environment. - **/ - ScriptEnvironment(KileInfo *kileInfo, KileScriptView *scriptView, KileScriptDocument *scriptDocument, - KileScriptObject *scriptObject, const QString &pluginCode); - virtual ~ScriptEnvironment(); - - /** - * Executes script code in this environment. - * @param s the script that should be executed - **/ - void execute(const Script *script); - - protected: - KileInfo *m_kileInfo; - KileScriptView *m_scriptView; - KileScriptDocument *m_scriptDocument; - KileScriptObject *m_kileScriptObject; - - QScriptEngine *m_engine; - QString m_enginePluginCode; - - void scriptError(const QString &name); +public: + /** + * Constructs a new environment. + **/ + ScriptEnvironment(KileInfo *kileInfo, KileScriptView *scriptView, KileScriptDocument *scriptDocument, + KileScriptObject *scriptObject, const QString &pluginCode); + virtual ~ScriptEnvironment(); + + /** + * Executes script code in this environment. + * @param s the script that should be executed + **/ + void execute(const Script *script); + +protected: + KileInfo *m_kileInfo; + KileScriptView *m_scriptView; + KileScriptDocument *m_scriptDocument; + KileScriptObject *m_kileScriptObject; + + QScriptEngine *m_engine; + QString m_enginePluginCode; + + void scriptError(const QString &name); }; ////////////////////////////// ScriptHelpers ////////////////////////////// QScriptValue debug(QScriptContext *context, QScriptEngine *engine); } // metatype registration only necessary until KF5 5.9 #include #if KTEXTEDITOR_VERSION < QT_VERSION_CHECK(5, 10, 0) Q_DECLARE_METATYPE(KTextEditor::Cursor) Q_DECLARE_METATYPE(KTextEditor::Range) #endif #endif diff --git a/src/scriptmanager.cpp b/src/scriptmanager.cpp index 778c1c58..b8054925 100644 --- a/src/scriptmanager.cpp +++ b/src/scriptmanager.cpp @@ -1,467 +1,467 @@ /************************************************************************** * Copyright (C) 2006-2016 by Michel Ludwig (michel.ludwig@kdemail.net) * ***************************************************************************/ /************************************************************************** * * * 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. * * * ***************************************************************************/ #include "scriptmanager.h" #include #include #include #include #include #include #include #include #include #include #include "kiledebug.h" #include "kileconfig.h" #include "kileinfo.h" #include "kileversion.h" #include "kileviewmanager.h" #include "editorkeysequencemanager.h" #include "scripting/script.h" namespace KileScript { ////////////////////////////// Manager ////////////////////////////// - Manager::Manager(KileInfo *kileInfo, KConfig *config, KActionCollection *actionCollection, QObject *parent, const char *name) - : QObject(parent), m_jScriptDirWatch(Q_NULLPTR), m_kileInfo(kileInfo), m_config(config), m_actionCollection(actionCollection) - { - setObjectName(name); - - // create a local scripts directory if it doesn't exist yet - m_localScriptDir = QStandardPaths::writableLocation(QStandardPaths::DataLocation) + "/scripts/"; - QDir testDir(m_localScriptDir); - if (!testDir.exists()) { - testDir.mkpath(m_localScriptDir); - } - - m_jScriptDirWatch = new KDirWatch(this); - m_jScriptDirWatch->setObjectName("KileScript::Manager::ScriptDirWatch"); - connect(m_jScriptDirWatch, SIGNAL(dirty(const QString&)), this, SLOT(scanScriptDirectories())); - connect(m_jScriptDirWatch, SIGNAL(created(const QString&)), this, SLOT(scanScriptDirectories())); - connect(m_jScriptDirWatch, SIGNAL(deleted(const QString&)), this, SLOT(scanScriptDirectories())); - m_jScriptDirWatch->startScan(); - - // read plugin code for QScriptEngine - readEnginePlugin(); - m_scriptActionMap = new QMap; - - // init script objects - m_kileScriptView = new KileScriptView(this, m_kileInfo->editorExtension()); - m_kileScriptDocument = new KileScriptDocument(this, m_kileInfo, m_kileInfo->editorExtension(), m_scriptActionMap); - m_kileScriptObject = new KileScriptObject(this, m_kileInfo, m_scriptActionMap); - } - - Manager::~Manager() - { - delete m_jScriptDirWatch; - delete m_scriptActionMap; - - delete m_kileScriptView; - delete m_kileScriptDocument; - delete m_kileScriptObject; - - //still need to delete the scripts - for(QList::iterator it = m_jScriptList.begin(); it != m_jScriptList.end(); ++it) { - delete *it; - } - } - - void Manager::executeScript(const Script *script) - { - KILE_DEBUG_MAIN << "execute script: " << script->getName(); - - // compatibility check - QString code = script->getCode(); - QRegExp endOfLineExp("(\r\n)|\n|\r"); - int i = code.indexOf(endOfLineExp); - QString firstLine = (i >= 0 ? code.left(i) : code); - QRegExp requiredVersionTagExp("(kile-version:\\s*)(\\d+\\.\\d+(.\\d+)?)"); - if(requiredVersionTagExp.indexIn(firstLine) != -1) { - QString requiredKileVersion = requiredVersionTagExp.cap(2); - if(compareVersionStrings(requiredKileVersion, kileFullVersion) > 0) { - KMessageBox::sorry(m_kileInfo->mainWindow(), i18n("Version %1 of Kile is at least required to execute the script \"%2\". The execution has been aborted.", requiredKileVersion, script->getName()), i18n("Version Error")); - return; - } - } - - // TODO only scripts with a current view can be started at this moment - KTextEditor::View *view = m_kileInfo->viewManager()->currentTextView(); - if(!view) { - KMessageBox::sorry(m_kileInfo->mainWindow(), i18n("Cannot start the script: no view available"), i18n("Script Error")); - return; - } - - // TODO setup script objects (with existing views at this moment) - m_kileScriptView->setView(view); - m_kileScriptDocument->setView(view); - m_kileScriptObject->setScriptname(script->getName()); - - // create environment for QtScript engine - ScriptEnvironment env(m_kileInfo, m_kileScriptView, m_kileScriptDocument, m_kileScriptObject,m_enginePlugin); - - env.execute(script); - } - - void Manager::executeScript(unsigned int id) - { - QMap::iterator i = m_idScriptMap.find(id); - if(i != m_idScriptMap.end()) { - executeScript(*i); - } - } - - const Script* Manager::getScript(unsigned int id) - { - QMap::iterator i = m_idScriptMap.find(id); - return ((i != m_idScriptMap.end()) ? (*i) : Q_NULLPTR); - } - - void Manager::scanScriptDirectories() - { - if(!KileConfig::scriptingEnabled()) { - return; - } - deleteScripts(); - populateDirWatch(); - - KConfigGroup configGroup = m_config->group("Scripts"); - QList idList = configGroup.readEntry("IDs", QList()); - unsigned int maxID = 0; - QMap pathIDMap; - QMap takenIDMap; - for(QList::iterator i = idList.begin(); i != idList.end(); ++i) { - QString fileName = configGroup.readPathEntry("Script" + QString::number(*i), QString()); - if(!fileName.isEmpty()) { - unsigned int id = *i; - pathIDMap[fileName] = id; - takenIDMap[id] = true; - maxID = qMax(maxID, id); - } - } - - // scan *.js files - QSet scriptFileNamesSet; - const QStringList dirs = QStandardPaths::locateAll(QStandardPaths::DataLocation, "scripts/", QStandardPaths::LocateDirectory); - Q_FOREACH (const QString &dir, dirs) { - QDirIterator it(dir, QStringList() << QStringLiteral("*.js"), QDir::Files | QDir::Readable, QDirIterator::Subdirectories); - while (it.hasNext()) { - scriptFileNamesSet.insert(it.next()); - } - } - - Q_FOREACH(const QString &scriptFileName, scriptFileNamesSet) { - registerScript(scriptFileName, pathIDMap, takenIDMap, maxID); - } - //rewrite the IDs that are currently in use - writeIDs(); - m_actionCollection->readSettings(); - emit scriptsChanged(); - } - - void Manager::deleteScripts() - { - QList scriptList = m_jScriptList; - m_jScriptList.clear(); // pretend that there are no scripts left - QStringList keySequenceList; - for(QList::iterator it = scriptList.begin(); it != scriptList.end(); ++it) { - keySequenceList.push_back((*it)->getKeySequence()); - } - m_idScriptMap.clear(); - m_kileInfo->editorKeySequenceManager()->removeKeySequence(keySequenceList); - for(QList::iterator it = scriptList.begin(); it != scriptList.end(); ++it) { - QAction *action = (*it)->getActionObject(); - if(action) { - foreach(QWidget *w, action->associatedWidgets()) { - w->removeAction(action); - } - m_actionCollection->takeAction(action); - delete action; - } - delete *it; - } - emit scriptsChanged(); - } - - QList Manager::getScripts() - { - return m_jScriptList; - } - - void Manager::registerScript(const QString& fileName, QMap& pathIDMap, QMap& takenIDMap, unsigned int &maxID) - { - unsigned int id; - QMap::iterator it = pathIDMap.find(fileName); - if(it != pathIDMap.end()) { - id = *it; - } - else { - id = findFreeID(takenIDMap, maxID); - pathIDMap[fileName] = id; - takenIDMap[id] = true; - maxID = qMax(maxID, id); - } - Script* script = new Script(id, fileName); - m_jScriptList.push_back(script); - m_idScriptMap[id] = script; - - // start with setting up the key sequence - KConfigGroup configGroup = m_config->group("Scripts"); - - int sequenceType = 0; - QString editorKeySequence = QString(); - QString seq = configGroup.readEntry("Script" + QString::number(id) + "KeySequence"); - if ( !seq.isEmpty() ) { - QRegExp re("(\\d+)-(.*)"); - if ( re.exactMatch(seq) ) { - sequenceType = re.cap(1).toInt(); - if ( sequenceTypeScript::KEY_SHORTCUT ) { - sequenceType = Script::KEY_SEQUENCE; - } - editorKeySequence = re.cap(2); - } - else { - sequenceType = Script::KEY_SEQUENCE; - editorKeySequence = re.cap(1); - } - } - KILE_DEBUG_MAIN << "script type=" << sequenceType << " seq=" << editorKeySequence; - - // now set up a regular action object - ScriptExecutionAction *action = new ScriptExecutionAction(id, this, m_actionCollection); - - // action with shortcut? - if(!editorKeySequence.isEmpty()) { - script->setSequenceType(sequenceType); - script->setKeySequence(editorKeySequence); - if ( sequenceType == Script::KEY_SEQUENCE ) { - m_kileInfo->editorKeySequenceManager()->addAction(editorKeySequence, new KileEditorKeySequence::ExecuteScriptAction(script, this)); - } - else { - action->setShortcut(editorKeySequence); - } - } - - // add to action collection - m_actionCollection->addAction("script" + QString::number(id) + "_execution", action); - script->setActionObject(action); - } - - void Manager::writeConfig() - { - // don't delete the key sequence settings if scripting has been disabled - if(!KileConfig::scriptingEnabled()) { - return; - } - m_config->deleteGroup("Scripts"); - writeIDs(); - - // write the key sequences - KConfigGroup configGroup = m_config->group("Scripts"); - for(QList::iterator i = m_jScriptList.begin(); i != m_jScriptList.end(); ++i) { - QString seq = (*i)->getKeySequence(); - QString sequenceEntry = ( seq.isEmpty() ) ? seq : QString("%1-%2").arg(QString::number((*i)->getSequenceType())).arg(seq); - configGroup.writeEntry("Script" + QString::number((*i)->getID()) + "KeySequence", sequenceEntry); - } - } - - void Manager::setEditorKeySequence(Script* script, int type, const QString& keySequence) - { - if(keySequence.isEmpty()) { - return; - } - if(script) { - int oldType = script->getSequenceType(); - QString oldSequence = script->getKeySequence(); - if( oldType==type && oldSequence==keySequence) { - return; - } - - if ( oldType == KileScript::Script::KEY_SEQUENCE ) { - m_kileInfo->editorKeySequenceManager()->removeKeySequence(oldSequence); - } - else { - script->getActionObject()->setShortcut(QString()); - } - script->setSequenceType(type); - script->setKeySequence(keySequence); - if ( type == KileScript::Script::KEY_SEQUENCE ) { - m_kileInfo->editorKeySequenceManager()->addAction(keySequence, new KileEditorKeySequence::ExecuteScriptAction(script, this)); - } - else { - script->getActionObject()->setShortcut(keySequence); - } - - writeConfig(); - } - } - - void Manager::removeEditorKeySequence(Script* script) - { - if(script) { - QString keySequence = script->getKeySequence(); - if(keySequence.isEmpty()) { - return; - } - script->setKeySequence(QString()); - - int sequenceType = script->getSequenceType(); - if ( sequenceType == Script::KEY_SEQUENCE ) { - m_kileInfo->editorKeySequenceManager()->removeKeySequence(keySequence); - } - else { - script->getActionObject()->setShortcut(QString()); - } - - writeConfig(); - } - } - - void Manager::populateDirWatch() - { - QStringList jScriptDirectories = QStandardPaths::locateAll(QStandardPaths::DataLocation, "scripts/", QStandardPaths::LocateDirectory); - for(QStringList::iterator i = jScriptDirectories.begin(); i != jScriptDirectories.end(); ++i) { - // FIXME: future KDE versions could support the recursive - // watching of directories out of the box. - addDirectoryToDirWatch(*i); - } - //we do not remove the directories that were once added as this apparently causes some strange - //bugs (on KDE 3.5.x) - } - - QString Manager::getLocalScriptDirectory() const - { - return m_localScriptDir; - } - - void Manager::readConfig() { - deleteScripts(); - scanScriptDirectories(); - } - - unsigned int Manager::findFreeID(const QMap& takenIDMap, unsigned int maxID) - { - if(takenIDMap.size() == 0) { - return 0; - } - // maxID should have a real meaning now - for(unsigned int i = 0; i < maxID; ++i) { - if(takenIDMap.find(i) == takenIDMap.end()) { - return i; - } - } - return (maxID + 1); - } - - void Manager::writeIDs() - { - KConfigGroup configGroup = m_config->group("Scripts"); - //delete old entries - QList idList = configGroup.readEntry("IDs", QList()); - for(QList::iterator i = idList.begin(); i != idList.end(); ++i) { - configGroup.deleteEntry("Script" + QString::number(*i)); - } - //write new ones - idList.clear(); - for(QMap::iterator i = m_idScriptMap.begin(); i != m_idScriptMap.end(); ++i) { - unsigned int id = i.key(); - idList.push_back(id); - configGroup.writePathEntry("Script" + QString::number(id), (*i)->getFileName()); - } - configGroup.writeEntry("IDs", idList); - } - - void Manager::addDirectoryToDirWatch(const QString& dir) - { - //FIXME: no recursive watching and no watching of files as it isn't implemented - // yet - //FIXME: check for KDE4 - if(!m_jScriptDirWatch->contains(dir)) { - m_jScriptDirWatch->addDir(dir, KDirWatch::WatchDirOnly); - } - QDir qDir(dir); - QStringList list = qDir.entryList(QDir::Dirs); - for(QStringList::iterator i = list.begin(); i != list.end(); ++i) { - QString subdir = *i; - if(subdir != "." && subdir != "..") { - addDirectoryToDirWatch(qDir.filePath(subdir)); - } - } - } - - void Manager::readEnginePlugin() - { - // TODO error message and disable scripting if not found - QString pluginUrl = QStandardPaths::locate(QStandardPaths::DataLocation, "script-plugins/cursor-range.js"); - m_enginePlugin = Script::readFile(pluginUrl); - } - - void Manager::initScriptActions() - { - QStringList m_scriptActionList = QStringList() - << "tag_chapter" << "tag_section" << "tag_subsection" - << "tag_subsubsection" << "tag_paragraph" << "tag_subparagraph" - - << "tag_label" << "tag_ref" << "tag_pageref" - << "tag_index" << "tag_footnote" << "tag_cite" - - << "tools_comment" << "tools_uncomment" << "tools_uppercase" - << "tools_lowercase" << "tools_capitalize" << "tools_join_lines" - - << "wizard_tabular" << "wizard_array" << "wizard_tabbing" - << "wizard_float" << "wizard_mathenv" - << "wizard_postscript" << "wizard_pdf" - ; - - - foreach ( KXMLGUIClient *client, m_kileInfo->mainWindow()->guiFactory()->clients() ) { - KILE_DEBUG_MAIN << "collection count: " << client->actionCollection()->count() ; - - foreach ( QAction *action, client->actionCollection()->actions() ) { - QString objectname = action->objectName(); - if ( m_scriptActionList.indexOf(objectname) >= 0 ) { - m_scriptActionMap->insert(objectname,action); - } - } - } - } +Manager::Manager(KileInfo *kileInfo, KConfig *config, KActionCollection *actionCollection, QObject *parent, const char *name) + : QObject(parent), m_jScriptDirWatch(Q_NULLPTR), m_kileInfo(kileInfo), m_config(config), m_actionCollection(actionCollection) +{ + setObjectName(name); + + // create a local scripts directory if it doesn't exist yet + m_localScriptDir = QStandardPaths::writableLocation(QStandardPaths::DataLocation) + "/scripts/"; + QDir testDir(m_localScriptDir); + if (!testDir.exists()) { + testDir.mkpath(m_localScriptDir); + } + + m_jScriptDirWatch = new KDirWatch(this); + m_jScriptDirWatch->setObjectName("KileScript::Manager::ScriptDirWatch"); + connect(m_jScriptDirWatch, SIGNAL(dirty(const QString&)), this, SLOT(scanScriptDirectories())); + connect(m_jScriptDirWatch, SIGNAL(created(const QString&)), this, SLOT(scanScriptDirectories())); + connect(m_jScriptDirWatch, SIGNAL(deleted(const QString&)), this, SLOT(scanScriptDirectories())); + m_jScriptDirWatch->startScan(); + + // read plugin code for QScriptEngine + readEnginePlugin(); + m_scriptActionMap = new QMap; + + // init script objects + m_kileScriptView = new KileScriptView(this, m_kileInfo->editorExtension()); + m_kileScriptDocument = new KileScriptDocument(this, m_kileInfo, m_kileInfo->editorExtension(), m_scriptActionMap); + m_kileScriptObject = new KileScriptObject(this, m_kileInfo, m_scriptActionMap); +} + +Manager::~Manager() +{ + delete m_jScriptDirWatch; + delete m_scriptActionMap; + + delete m_kileScriptView; + delete m_kileScriptDocument; + delete m_kileScriptObject; + + //still need to delete the scripts + for(QList::iterator it = m_jScriptList.begin(); it != m_jScriptList.end(); ++it) { + delete *it; + } +} + +void Manager::executeScript(const Script *script) +{ + KILE_DEBUG_MAIN << "execute script: " << script->getName(); + + // compatibility check + QString code = script->getCode(); + QRegExp endOfLineExp("(\r\n)|\n|\r"); + int i = code.indexOf(endOfLineExp); + QString firstLine = (i >= 0 ? code.left(i) : code); + QRegExp requiredVersionTagExp("(kile-version:\\s*)(\\d+\\.\\d+(.\\d+)?)"); + if(requiredVersionTagExp.indexIn(firstLine) != -1) { + QString requiredKileVersion = requiredVersionTagExp.cap(2); + if(compareVersionStrings(requiredKileVersion, kileFullVersion) > 0) { + KMessageBox::sorry(m_kileInfo->mainWindow(), i18n("Version %1 of Kile is at least required to execute the script \"%2\". The execution has been aborted.", requiredKileVersion, script->getName()), i18n("Version Error")); + return; + } + } + + // TODO only scripts with a current view can be started at this moment + KTextEditor::View *view = m_kileInfo->viewManager()->currentTextView(); + if(!view) { + KMessageBox::sorry(m_kileInfo->mainWindow(), i18n("Cannot start the script: no view available"), i18n("Script Error")); + return; + } + + // TODO setup script objects (with existing views at this moment) + m_kileScriptView->setView(view); + m_kileScriptDocument->setView(view); + m_kileScriptObject->setScriptname(script->getName()); + + // create environment for QtScript engine + ScriptEnvironment env(m_kileInfo, m_kileScriptView, m_kileScriptDocument, m_kileScriptObject,m_enginePlugin); + + env.execute(script); +} + +void Manager::executeScript(unsigned int id) +{ + QMap::iterator i = m_idScriptMap.find(id); + if(i != m_idScriptMap.end()) { + executeScript(*i); + } +} + +const Script* Manager::getScript(unsigned int id) +{ + QMap::iterator i = m_idScriptMap.find(id); + return ((i != m_idScriptMap.end()) ? (*i) : Q_NULLPTR); +} + +void Manager::scanScriptDirectories() +{ + if(!KileConfig::scriptingEnabled()) { + return; + } + deleteScripts(); + populateDirWatch(); + + KConfigGroup configGroup = m_config->group("Scripts"); + QList idList = configGroup.readEntry("IDs", QList()); + unsigned int maxID = 0; + QMap pathIDMap; + QMap takenIDMap; + for(QList::iterator i = idList.begin(); i != idList.end(); ++i) { + QString fileName = configGroup.readPathEntry("Script" + QString::number(*i), QString()); + if(!fileName.isEmpty()) { + unsigned int id = *i; + pathIDMap[fileName] = id; + takenIDMap[id] = true; + maxID = qMax(maxID, id); + } + } + + // scan *.js files + QSet scriptFileNamesSet; + const QStringList dirs = QStandardPaths::locateAll(QStandardPaths::DataLocation, "scripts/", QStandardPaths::LocateDirectory); + Q_FOREACH (const QString &dir, dirs) { + QDirIterator it(dir, QStringList() << QStringLiteral("*.js"), QDir::Files | QDir::Readable, QDirIterator::Subdirectories); + while (it.hasNext()) { + scriptFileNamesSet.insert(it.next()); + } + } + + Q_FOREACH(const QString &scriptFileName, scriptFileNamesSet) { + registerScript(scriptFileName, pathIDMap, takenIDMap, maxID); + } + //rewrite the IDs that are currently in use + writeIDs(); + m_actionCollection->readSettings(); + emit scriptsChanged(); +} + +void Manager::deleteScripts() +{ + QList scriptList = m_jScriptList; + m_jScriptList.clear(); // pretend that there are no scripts left + QStringList keySequenceList; + for(QList::iterator it = scriptList.begin(); it != scriptList.end(); ++it) { + keySequenceList.push_back((*it)->getKeySequence()); + } + m_idScriptMap.clear(); + m_kileInfo->editorKeySequenceManager()->removeKeySequence(keySequenceList); + for(QList::iterator it = scriptList.begin(); it != scriptList.end(); ++it) { + QAction *action = (*it)->getActionObject(); + if(action) { + foreach(QWidget *w, action->associatedWidgets()) { + w->removeAction(action); + } + m_actionCollection->takeAction(action); + delete action; + } + delete *it; + } + emit scriptsChanged(); +} + +QList Manager::getScripts() +{ + return m_jScriptList; +} + +void Manager::registerScript(const QString& fileName, QMap& pathIDMap, QMap& takenIDMap, unsigned int &maxID) +{ + unsigned int id; + QMap::iterator it = pathIDMap.find(fileName); + if(it != pathIDMap.end()) { + id = *it; + } + else { + id = findFreeID(takenIDMap, maxID); + pathIDMap[fileName] = id; + takenIDMap[id] = true; + maxID = qMax(maxID, id); + } + Script* script = new Script(id, fileName); + m_jScriptList.push_back(script); + m_idScriptMap[id] = script; + + // start with setting up the key sequence + KConfigGroup configGroup = m_config->group("Scripts"); + + int sequenceType = 0; + QString editorKeySequence = QString(); + QString seq = configGroup.readEntry("Script" + QString::number(id) + "KeySequence"); + if ( !seq.isEmpty() ) { + QRegExp re("(\\d+)-(.*)"); + if ( re.exactMatch(seq) ) { + sequenceType = re.cap(1).toInt(); + if ( sequenceTypeScript::KEY_SHORTCUT ) { + sequenceType = Script::KEY_SEQUENCE; + } + editorKeySequence = re.cap(2); + } + else { + sequenceType = Script::KEY_SEQUENCE; + editorKeySequence = re.cap(1); + } + } + KILE_DEBUG_MAIN << "script type=" << sequenceType << " seq=" << editorKeySequence; + + // now set up a regular action object + ScriptExecutionAction *action = new ScriptExecutionAction(id, this, m_actionCollection); + + // action with shortcut? + if(!editorKeySequence.isEmpty()) { + script->setSequenceType(sequenceType); + script->setKeySequence(editorKeySequence); + if ( sequenceType == Script::KEY_SEQUENCE ) { + m_kileInfo->editorKeySequenceManager()->addAction(editorKeySequence, new KileEditorKeySequence::ExecuteScriptAction(script, this)); + } + else { + action->setShortcut(editorKeySequence); + } + } + + // add to action collection + m_actionCollection->addAction("script" + QString::number(id) + "_execution", action); + script->setActionObject(action); +} + +void Manager::writeConfig() +{ + // don't delete the key sequence settings if scripting has been disabled + if(!KileConfig::scriptingEnabled()) { + return; + } + m_config->deleteGroup("Scripts"); + writeIDs(); + + // write the key sequences + KConfigGroup configGroup = m_config->group("Scripts"); + for(QList::iterator i = m_jScriptList.begin(); i != m_jScriptList.end(); ++i) { + QString seq = (*i)->getKeySequence(); + QString sequenceEntry = ( seq.isEmpty() ) ? seq : QString("%1-%2").arg(QString::number((*i)->getSequenceType())).arg(seq); + configGroup.writeEntry("Script" + QString::number((*i)->getID()) + "KeySequence", sequenceEntry); + } +} + +void Manager::setEditorKeySequence(Script* script, int type, const QString& keySequence) +{ + if(keySequence.isEmpty()) { + return; + } + if(script) { + int oldType = script->getSequenceType(); + QString oldSequence = script->getKeySequence(); + if( oldType==type && oldSequence==keySequence) { + return; + } + + if ( oldType == KileScript::Script::KEY_SEQUENCE ) { + m_kileInfo->editorKeySequenceManager()->removeKeySequence(oldSequence); + } + else { + script->getActionObject()->setShortcut(QString()); + } + script->setSequenceType(type); + script->setKeySequence(keySequence); + if ( type == KileScript::Script::KEY_SEQUENCE ) { + m_kileInfo->editorKeySequenceManager()->addAction(keySequence, new KileEditorKeySequence::ExecuteScriptAction(script, this)); + } + else { + script->getActionObject()->setShortcut(keySequence); + } + + writeConfig(); + } +} + +void Manager::removeEditorKeySequence(Script* script) +{ + if(script) { + QString keySequence = script->getKeySequence(); + if(keySequence.isEmpty()) { + return; + } + script->setKeySequence(QString()); + + int sequenceType = script->getSequenceType(); + if ( sequenceType == Script::KEY_SEQUENCE ) { + m_kileInfo->editorKeySequenceManager()->removeKeySequence(keySequence); + } + else { + script->getActionObject()->setShortcut(QString()); + } + + writeConfig(); + } +} + +void Manager::populateDirWatch() +{ + QStringList jScriptDirectories = QStandardPaths::locateAll(QStandardPaths::DataLocation, "scripts/", QStandardPaths::LocateDirectory); + for(QStringList::iterator i = jScriptDirectories.begin(); i != jScriptDirectories.end(); ++i) { + // FIXME: future KDE versions could support the recursive + // watching of directories out of the box. + addDirectoryToDirWatch(*i); + } + //we do not remove the directories that were once added as this apparently causes some strange + //bugs (on KDE 3.5.x) +} + +QString Manager::getLocalScriptDirectory() const +{ + return m_localScriptDir; +} + +void Manager::readConfig() { + deleteScripts(); + scanScriptDirectories(); +} + +unsigned int Manager::findFreeID(const QMap& takenIDMap, unsigned int maxID) +{ + if(takenIDMap.size() == 0) { + return 0; + } + // maxID should have a real meaning now + for(unsigned int i = 0; i < maxID; ++i) { + if(takenIDMap.find(i) == takenIDMap.end()) { + return i; + } + } + return (maxID + 1); +} + +void Manager::writeIDs() +{ + KConfigGroup configGroup = m_config->group("Scripts"); + //delete old entries + QList idList = configGroup.readEntry("IDs", QList()); + for(QList::iterator i = idList.begin(); i != idList.end(); ++i) { + configGroup.deleteEntry("Script" + QString::number(*i)); + } + //write new ones + idList.clear(); + for(QMap::iterator i = m_idScriptMap.begin(); i != m_idScriptMap.end(); ++i) { + unsigned int id = i.key(); + idList.push_back(id); + configGroup.writePathEntry("Script" + QString::number(id), (*i)->getFileName()); + } + configGroup.writeEntry("IDs", idList); +} + +void Manager::addDirectoryToDirWatch(const QString& dir) +{ + //FIXME: no recursive watching and no watching of files as it isn't implemented + // yet + //FIXME: check for KDE4 + if(!m_jScriptDirWatch->contains(dir)) { + m_jScriptDirWatch->addDir(dir, KDirWatch::WatchDirOnly); + } + QDir qDir(dir); + QStringList list = qDir.entryList(QDir::Dirs); + for(QStringList::iterator i = list.begin(); i != list.end(); ++i) { + QString subdir = *i; + if(subdir != "." && subdir != "..") { + addDirectoryToDirWatch(qDir.filePath(subdir)); + } + } +} + +void Manager::readEnginePlugin() +{ + // TODO error message and disable scripting if not found + QString pluginUrl = QStandardPaths::locate(QStandardPaths::DataLocation, "script-plugins/cursor-range.js"); + m_enginePlugin = Script::readFile(pluginUrl); +} + +void Manager::initScriptActions() +{ + QStringList m_scriptActionList = QStringList() + << "tag_chapter" << "tag_section" << "tag_subsection" + << "tag_subsubsection" << "tag_paragraph" << "tag_subparagraph" + + << "tag_label" << "tag_ref" << "tag_pageref" + << "tag_index" << "tag_footnote" << "tag_cite" + + << "tools_comment" << "tools_uncomment" << "tools_uppercase" + << "tools_lowercase" << "tools_capitalize" << "tools_join_lines" + + << "wizard_tabular" << "wizard_array" << "wizard_tabbing" + << "wizard_float" << "wizard_mathenv" + << "wizard_postscript" << "wizard_pdf" + ; + + + foreach ( KXMLGUIClient *client, m_kileInfo->mainWindow()->guiFactory()->clients() ) { + KILE_DEBUG_MAIN << "collection count: " << client->actionCollection()->count() ; + + foreach ( QAction *action, client->actionCollection()->actions() ) { + QString objectname = action->objectName(); + if ( m_scriptActionList.indexOf(objectname) >= 0 ) { + m_scriptActionMap->insert(objectname,action); + } + } + } +} ////////////////////////////// ScriptExecutionAction ////////////////////////////// - ScriptExecutionAction::ScriptExecutionAction(unsigned int id, KileScript::Manager *manager, QObject* parent) : QAction(parent), m_manager(manager), m_id(id) - { - const KileScript::Script *script = m_manager->getScript(m_id); - Q_ASSERT(script); - setText(i18n("Execution of %1", script->getName())); - connect(this, SIGNAL(triggered()), this, SLOT(executeScript())); - } - - ScriptExecutionAction::~ScriptExecutionAction() - { - } - - void ScriptExecutionAction::executeScript() - { - m_manager->executeScript(m_id); - } +ScriptExecutionAction::ScriptExecutionAction(unsigned int id, KileScript::Manager *manager, QObject* parent) : QAction(parent), m_manager(manager), m_id(id) +{ + const KileScript::Script *script = m_manager->getScript(m_id); + Q_ASSERT(script); + setText(i18n("Execution of %1", script->getName())); + connect(this, SIGNAL(triggered()), this, SLOT(executeScript())); +} + +ScriptExecutionAction::~ScriptExecutionAction() +{ +} + +void ScriptExecutionAction::executeScript() +{ + m_manager->executeScript(m_id); +} } diff --git a/src/scriptmanager.h b/src/scriptmanager.h index 527edf81..921d8312 100644 --- a/src/scriptmanager.h +++ b/src/scriptmanager.h @@ -1,207 +1,207 @@ /************************************************************************** * Copyright (C) 2006-2008 by Michel Ludwig (michel.ludwig@kdemail.net) * ***************************************************************************/ /************************************************************************** * * * 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. * * * ***************************************************************************/ #ifndef SCRIPTMANAGER_H #define SCRIPTMANAGER_H #include #include #include #include #include #include #include #include #include #include "scripting/kilescriptobject.h" #include "scripting/kilescriptview.h" #include "scripting/kilescriptdocument.h" class KileInfo; namespace KileScript { class Script; /** * This class handles the scripting functionality in Kile. **/ class Manager : public QObject { - Q_OBJECT - - public: - /** - * Constructs a new Manager object. - **/ - Manager(KileInfo *info, KConfig *config, KActionCollection *actionCollection, QObject *parent = 0, const char *name = 0); - virtual ~Manager(); - - /** - * Executes a script in Kile's scripting environment. - * @param script the script that should be executed - **/ - void executeScript(const Script *script); - - /** - * Executes a script in Kile's scripting environment. - * @param id the id of the script that should be executed - **/ - void executeScript(unsigned int id); - - /** - * Retrieves a list of all the scripts that are currently available. - **/ - QList getScripts(); - - /** - * Writes the key sequence-to-script bindings to the KConfig object that has - * passed in the constructor. - **/ - void writeConfig(); - - /** - * Assigns a key sequence to a script. If the parameter "keySequence" is empty, - * then nothing is done. - * @param script the script that is considered - * @param keySequence the key sequence that is assigned - **/ - void setEditorKeySequence(Script* script, int type, const QString& keySequence); - - /** - * Removes an assigned key sequence from a script. - * @param script the script that is considered - **/ - void removeEditorKeySequence(Script* script); - - /** - * Returns the directory that can be used by the used to store Kile's scripts. - * Usually $HOME/.kde/share/apps/kile/scripts - **/ - QString getLocalScriptDirectory() const; - - /** - * Returns the script object that corresponds to a script id. - * @param id the id of the script - **/ - const Script* getScript(unsigned int id); - - void initScriptActions(); - - Q_SIGNALS: - /** - * Signal emitted whenever the managed scripts haved changed, for example if the - * watched directories have been scanned for scripts and thus, the potentially - * available scripts (could) have changed. - * The signal is also emitted when the currently available scripts have been - * deleted internally in Kile (for example, after disabling the scripting feature). - **/ - void scriptsChanged(); - - public Q_SLOTS: - /** - * Does nothing if scripting has been disabled. - **/ - void scanScriptDirectories(); - - /** - * Reads and assigns the key sequence-to-script bindings from the KConfig - * object that has been passed in the constructor. - **/ - void readConfig(); - - protected: - QString m_localScriptDir; - QList m_jScriptList; - QMap m_idScriptMap; - KDirWatch *m_jScriptDirWatch; - - KileInfo *m_kileInfo; - KConfig *m_config; - KActionCollection *m_actionCollection; - - /** - * Registers the script contained in a file. - * @param fileName the file that contains the script - **/ - void registerScript(const QString& fileName, QMap& pathIDMap, QMap& takenIDMap, unsigned int &maxID); - - /** - * (Re-)Creates and initialises the KDirWatch object. - **/ - void populateDirWatch(); - - /** - * Deletes all the scripts that are handled by this manager. - **/ - void deleteScripts(); - - /** - * Finds the next free ID. - * @param takenIDMap map describing which IDs are already in use - * @param maxID the maximum ID that is currently in use (if there is no ID assigned, then - * any value can be passed here, but typically '0') - **/ - unsigned int findFreeID(const QMap& takenIDMap, unsigned int maxID); - - /** - * Writes the ID to file name mappings that are currently in use to the local - * KConfig object. - **/ - void writeIDs(); - - /** - * read the plugin to initialize Cursor and Range objects - **/ - void readEnginePlugin(); - - private: - /** - * Recursively adds a directory to a KDirWatch object. - * @param dir the directory that should be added - **/ - void addDirectoryToDirWatch(const QString& dir); - - KileScriptObject *m_kileScriptObject; - KileScriptView *m_kileScriptView; - KileScriptDocument *m_kileScriptDocument; - - QString m_enginePlugin; - QMap *m_scriptActionMap; + Q_OBJECT + +public: + /** + * Constructs a new Manager object. + **/ + Manager(KileInfo *info, KConfig *config, KActionCollection *actionCollection, QObject *parent = 0, const char *name = 0); + virtual ~Manager(); + + /** + * Executes a script in Kile's scripting environment. + * @param script the script that should be executed + **/ + void executeScript(const Script *script); + + /** + * Executes a script in Kile's scripting environment. + * @param id the id of the script that should be executed + **/ + void executeScript(unsigned int id); + + /** + * Retrieves a list of all the scripts that are currently available. + **/ + QList getScripts(); + + /** + * Writes the key sequence-to-script bindings to the KConfig object that has + * passed in the constructor. + **/ + void writeConfig(); + + /** + * Assigns a key sequence to a script. If the parameter "keySequence" is empty, + * then nothing is done. + * @param script the script that is considered + * @param keySequence the key sequence that is assigned + **/ + void setEditorKeySequence(Script* script, int type, const QString& keySequence); + + /** + * Removes an assigned key sequence from a script. + * @param script the script that is considered + **/ + void removeEditorKeySequence(Script* script); + + /** + * Returns the directory that can be used by the used to store Kile's scripts. + * Usually $HOME/.kde/share/apps/kile/scripts + **/ + QString getLocalScriptDirectory() const; + + /** + * Returns the script object that corresponds to a script id. + * @param id the id of the script + **/ + const Script* getScript(unsigned int id); + + void initScriptActions(); + +Q_SIGNALS: + /** + * Signal emitted whenever the managed scripts haved changed, for example if the + * watched directories have been scanned for scripts and thus, the potentially + * available scripts (could) have changed. + * The signal is also emitted when the currently available scripts have been + * deleted internally in Kile (for example, after disabling the scripting feature). + **/ + void scriptsChanged(); + +public Q_SLOTS: + /** + * Does nothing if scripting has been disabled. + **/ + void scanScriptDirectories(); + + /** + * Reads and assigns the key sequence-to-script bindings from the KConfig + * object that has been passed in the constructor. + **/ + void readConfig(); + +protected: + QString m_localScriptDir; + QList m_jScriptList; + QMap m_idScriptMap; + KDirWatch *m_jScriptDirWatch; + + KileInfo *m_kileInfo; + KConfig *m_config; + KActionCollection *m_actionCollection; + + /** + * Registers the script contained in a file. + * @param fileName the file that contains the script + **/ + void registerScript(const QString& fileName, QMap& pathIDMap, QMap& takenIDMap, unsigned int &maxID); + + /** + * (Re-)Creates and initialises the KDirWatch object. + **/ + void populateDirWatch(); + + /** + * Deletes all the scripts that are handled by this manager. + **/ + void deleteScripts(); + + /** + * Finds the next free ID. + * @param takenIDMap map describing which IDs are already in use + * @param maxID the maximum ID that is currently in use (if there is no ID assigned, then + * any value can be passed here, but typically '0') + **/ + unsigned int findFreeID(const QMap& takenIDMap, unsigned int maxID); + + /** + * Writes the ID to file name mappings that are currently in use to the local + * KConfig object. + **/ + void writeIDs(); + + /** + * read the plugin to initialize Cursor and Range objects + **/ + void readEnginePlugin(); + +private: + /** + * Recursively adds a directory to a KDirWatch object. + * @param dir the directory that should be added + **/ + void addDirectoryToDirWatch(const QString& dir); + + KileScriptObject *m_kileScriptObject; + KileScriptView *m_kileScriptView; + KileScriptDocument *m_kileScriptDocument; + + QString m_enginePlugin; + QMap *m_scriptActionMap; }; class ScriptExecutionAction : public QAction { - Q_OBJECT + Q_OBJECT - public: - ScriptExecutionAction(unsigned int scriptID, Manager *manager, QObject* parent = 0); +public: + ScriptExecutionAction(unsigned int scriptID, Manager *manager, QObject* parent = 0); - virtual ~ScriptExecutionAction(); + virtual ~ScriptExecutionAction(); - protected Q_SLOTS: - void executeScript(); +protected Q_SLOTS: + void executeScript(); - protected: - KileScript::Manager *m_manager; - unsigned int m_id; +protected: + KileScript::Manager *m_manager; + unsigned int m_id; }; } #endif diff --git a/src/symbolviewclasses.h b/src/symbolviewclasses.h index da6ee7e9..7ce8c140 100644 --- a/src/symbolviewclasses.h +++ b/src/symbolviewclasses.h @@ -1,44 +1,44 @@ /************************************************************************** * * * 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. * * * ***************************************************************************/ #ifndef SYMBOLVIEWCLASSES_H #define SYMBOLVIEWCLASSES_H #include #include -struct Preamble{ - QString className; - QString classArguments; - QString additional; +struct Preamble { + QString className; + QString classArguments; + QString additional; }; -struct Package{ - QString name; - QString arguments; +struct Package { + QString name; + QString arguments; }; -struct Command{ - QString latexCommand; - QString unicodeCommand; - QString ImageCommand; - QString comment; - bool mathMode; - QList packages; - QList unicodePackages; - int referenceCount; - QString path; +struct Command { + QString latexCommand; + QString unicodeCommand; + QString ImageCommand; + QString comment; + bool mathMode; + QList packages; + QList unicodePackages; + int referenceCount; + QString path; }; -struct Version{ - QString major; - QString minor; +struct Version { + QString major; + QString minor; }; #endif //SYMBOLVIEWCLASSES_H diff --git a/src/templates.cpp b/src/templates.cpp index f23ae76a..61a03e8f 100644 --- a/src/templates.cpp +++ b/src/templates.cpp @@ -1,441 +1,441 @@ /******************************************************************************************* begin : Sat Apr 26 2003 copyright : (C) 2003 by Jeroen Wijnhout (wijnhout@science.uva.nl) 2005 by Holger Danielsson (holger.danielsson@t-online.de) 2007-2014 by Michel Ludwig (michel.ludwig@kdemail.net) *******************************************************************************************/ /*************************************************************************** * * * 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. * * * ***************************************************************************/ #include "templates.h" #include #include #include #include #include #include #include #include #include #include #include #include "kileinfo.h" #include "kiledebug.h" // 2005-08-04: dani -// - added script support to search existing class files +// - added script support to search existing class files // (classes: Koma, Beamer, Prosper, HA-prosper) // - sort items ('Empty Document' will always be the first entry) // 2006-30-04: tbraun // - drag and drop makes no sense here // - use the Select mode namespace KileTemplate { ////////////////////// Info ////////////////////// Info::Info() : type(KileDocument::Undefined) { } bool Info::operator==(const Info ti) const { - return name==ti.name; + return name==ti.name; } ////////////////////// Manager ////////////////////// Manager::Manager(KileInfo* kileInfo, QObject* parent, const char* name) : QObject(parent), m_kileInfo(kileInfo) { - setObjectName(name); + setObjectName(name); } Manager::~Manager() { } bool Manager::copyAppData(const QUrl &src, const QString& subdir, const QString& fileName) { - //let saveLocation find and create the appropriate place to - //store the templates (usually $HOME/.kde/share/apps/kile/templates) - QString dir = QStandardPaths::writableLocation(QStandardPaths::DataLocation) + '/' + subdir; - - QUrl targetURL = QUrl::fromUserInput(dir); - targetURL = targetURL.adjusted(QUrl::StripTrailingSlash); - targetURL.setPath(targetURL.path() + '/' + fileName); - - //if a directory is found - if (!dir.isNull()) { - // create dir if not existing, needed for copyjob - QDir testDir(dir); - if (!testDir.exists()){ - testDir.mkpath(dir); - } - // copy file - KIO::FileCopyJob* copyJob = KIO::file_copy(src, targetURL); - KJobWidgets::setWindow(copyJob, m_kileInfo->mainWindow()); - return copyJob->exec(); - } - else { - KMessageBox::error(Q_NULLPTR, i18n("Could not find a folder to save %1 to.\nCheck whether you have a .kde folder with write permissions in your home folder.", fileName)); - return false; - } + //let saveLocation find and create the appropriate place to + //store the templates (usually $HOME/.kde/share/apps/kile/templates) + QString dir = QStandardPaths::writableLocation(QStandardPaths::DataLocation) + '/' + subdir; + + QUrl targetURL = QUrl::fromUserInput(dir); + targetURL = targetURL.adjusted(QUrl::StripTrailingSlash); + targetURL.setPath(targetURL.path() + '/' + fileName); + + //if a directory is found + if (!dir.isNull()) { + // create dir if not existing, needed for copyjob + QDir testDir(dir); + if (!testDir.exists()) { + testDir.mkpath(dir); + } + // copy file + KIO::FileCopyJob* copyJob = KIO::file_copy(src, targetURL); + KJobWidgets::setWindow(copyJob, m_kileInfo->mainWindow()); + return copyJob->exec(); + } + else { + KMessageBox::error(Q_NULLPTR, i18n("Could not find a folder to save %1 to.\nCheck whether you have a .kde folder with write permissions in your home folder.", fileName)); + return false; + } } bool Manager::removeAppData(const QString &file) { - QFileInfo fileInfo(file); - if(fileInfo.exists()) { - KIO::SimpleJob* deleteJob = KIO::file_delete(QUrl::fromUserInput(file)); - KJobWidgets::setWindow(deleteJob, m_kileInfo->mainWindow()); - return deleteJob->exec(); - } - return true; + QFileInfo fileInfo(file); + if(fileInfo.exists()) { + KIO::SimpleJob* deleteJob = KIO::file_delete(QUrl::fromUserInput(file)); + KJobWidgets::setWindow(deleteJob, m_kileInfo->mainWindow()); + return deleteJob->exec(); + } + return true; } bool Manager::searchForTemplate(const QString& name, KileDocument::Type& type) const { - for (KileTemplate::TemplateListConstIterator i = m_TemplateList.constBegin(); i != m_TemplateList.constEnd(); ++i) - { - KileTemplate::Info info = *i; - if(info.name == name && info.type == type) { - return true; - } - } - return false; + for (KileTemplate::TemplateListConstIterator i = m_TemplateList.constBegin(); i != m_TemplateList.constEnd(); ++i) + { + KileTemplate::Info info = *i; + if(info.name == name && info.type == type) { + return true; + } + } + return false; } bool Manager::add(const QUrl &templateSourceURL, const QString &name, const QUrl &icon) { - KileDocument::Extensions *extensions = m_kileInfo->extensions(); - KileDocument::Type type = extensions->determineDocumentType(templateSourceURL); - return add(templateSourceURL, type, name, icon); + KileDocument::Extensions *extensions = m_kileInfo->extensions(); + KileDocument::Type type = extensions->determineDocumentType(templateSourceURL); + return add(templateSourceURL, type, name, icon); } bool Manager::add(const QUrl &templateSourceURL, KileDocument::Type type, const QString &name, const QUrl &icon) { - KileDocument::Extensions *extensions = m_kileInfo->extensions(); - QString extension = extensions->defaultExtensionForDocumentType(type); + KileDocument::Extensions *extensions = m_kileInfo->extensions(); + QString extension = extensions->defaultExtensionForDocumentType(type); - return copyAppData(templateSourceURL, "templates", "template_" + name + extension) && copyAppData(icon, "pics", "type_" + name + extension + ".kileicon"); + return copyAppData(templateSourceURL, "templates", "template_" + name + extension) && copyAppData(icon, "pics", "type_" + name + extension + ".kileicon"); } bool Manager::remove(Info ti) { - return removeAppData(ti.path) && removeAppData(ti.icon); + return removeAppData(ti.path) && removeAppData(ti.icon); } bool Manager::replace(const KileTemplate::Info& toBeReplaced, const QUrl &newTemplateSourceURL, const QString& newName, const QUrl& newIcon) { - KileDocument::Type type = m_kileInfo->extensions()->determineDocumentType(newTemplateSourceURL); - - //start by copying the files that belong to the new template to a safe place - QString templateTempFile, iconTempFile; - - if( newTemplateSourceURL.isLocalFile() ) { - // file protocol. We do not need the network - templateTempFile = newTemplateSourceURL.toLocalFile(); - } - else { - QTemporaryFile tmpFile; - tmpFile.setAutoRemove( false ); - tmpFile.open(); - - templateTempFile = tmpFile.fileName(); - m_TempFilePath = tmpFile.fileName(); - KIO::FileCopyJob* fileCopyJob = KIO::file_copy( newTemplateSourceURL, QUrl::fromLocalFile(templateTempFile), -1, KIO::Overwrite ); - KJobWidgets::setWindow( fileCopyJob, m_kileInfo->mainWindow() ); - - if( ! fileCopyJob->exec() ) { - return false; - } - } - - if( newIcon.isLocalFile() ) { - // file protocol. We do not need the network - iconTempFile = newIcon.toLocalFile(); - } - else { - QTemporaryFile tmpFile; - tmpFile.setAutoRemove( false ); - tmpFile.open(); - - iconTempFile = tmpFile.fileName(); - m_TempFilePath = tmpFile.fileName(); - KIO::FileCopyJob* fileCopyJob = KIO::file_copy( newIcon, QUrl::fromLocalFile(iconTempFile), -1, KIO::Overwrite ); - KJobWidgets::setWindow( fileCopyJob, m_kileInfo->mainWindow() ); - - if( ! fileCopyJob->exec() ) { - if( ! templateTempFile.isEmpty() ) - QFile::remove( templateTempFile ); - return false; - } - } - - //now delete the template that should be replaced - if(!remove(toBeReplaced)) { - if( ! templateTempFile.isEmpty() ) - QFile::remove( templateTempFile ); - if( ! iconTempFile.isEmpty() ) - QFile::remove( iconTempFile ); - } - - //finally, create the new template - if(!add(QUrl::fromUserInput(templateTempFile), type, newName, QUrl::fromUserInput(iconTempFile))) { - if( ! templateTempFile.isEmpty() ) - QFile::remove( templateTempFile ); - if( ! iconTempFile.isEmpty() ) - QFile::remove( iconTempFile ); - return false; - } - - if( ! templateTempFile.isEmpty() ) - QFile::remove( templateTempFile ); - if( ! iconTempFile.isEmpty() ) - QFile::remove( iconTempFile ); - - return true; + KileDocument::Type type = m_kileInfo->extensions()->determineDocumentType(newTemplateSourceURL); + + //start by copying the files that belong to the new template to a safe place + QString templateTempFile, iconTempFile; + + if( newTemplateSourceURL.isLocalFile() ) { + // file protocol. We do not need the network + templateTempFile = newTemplateSourceURL.toLocalFile(); + } + else { + QTemporaryFile tmpFile; + tmpFile.setAutoRemove( false ); + tmpFile.open(); + + templateTempFile = tmpFile.fileName(); + m_TempFilePath = tmpFile.fileName(); + KIO::FileCopyJob* fileCopyJob = KIO::file_copy( newTemplateSourceURL, QUrl::fromLocalFile(templateTempFile), -1, KIO::Overwrite ); + KJobWidgets::setWindow( fileCopyJob, m_kileInfo->mainWindow() ); + + if( ! fileCopyJob->exec() ) { + return false; + } + } + + if( newIcon.isLocalFile() ) { + // file protocol. We do not need the network + iconTempFile = newIcon.toLocalFile(); + } + else { + QTemporaryFile tmpFile; + tmpFile.setAutoRemove( false ); + tmpFile.open(); + + iconTempFile = tmpFile.fileName(); + m_TempFilePath = tmpFile.fileName(); + KIO::FileCopyJob* fileCopyJob = KIO::file_copy( newIcon, QUrl::fromLocalFile(iconTempFile), -1, KIO::Overwrite ); + KJobWidgets::setWindow( fileCopyJob, m_kileInfo->mainWindow() ); + + if( ! fileCopyJob->exec() ) { + if( ! templateTempFile.isEmpty() ) + QFile::remove( templateTempFile ); + return false; + } + } + + //now delete the template that should be replaced + if(!remove(toBeReplaced)) { + if( ! templateTempFile.isEmpty() ) + QFile::remove( templateTempFile ); + if( ! iconTempFile.isEmpty() ) + QFile::remove( iconTempFile ); + } + + //finally, create the new template + if(!add(QUrl::fromUserInput(templateTempFile), type, newName, QUrl::fromUserInput(iconTempFile))) { + if( ! templateTempFile.isEmpty() ) + QFile::remove( templateTempFile ); + if( ! iconTempFile.isEmpty() ) + QFile::remove( iconTempFile ); + return false; + } + + if( ! templateTempFile.isEmpty() ) + QFile::remove( templateTempFile ); + if( ! iconTempFile.isEmpty() ) + QFile::remove( iconTempFile ); + + return true; } void Manager::scanForTemplates() { - KILE_DEBUG_MAIN << "===scanForTemplates()==================="; - QStringList dirs = QStandardPaths::locateAll(QStandardPaths::DataLocation, "templates", QStandardPaths::LocateDirectory); - QDir templates; - KileTemplate::Info ti; - KileDocument::Extensions *extensions = m_kileInfo->extensions(); - - m_TemplateList.clear(); - for(QStringList::iterator i = dirs.begin(); i != dirs.end(); ++i) { - templates = QDir(*i, "template_*"); - for (uint j = 0; j < templates.count(); ++j) { - ti.path = templates.path() + '/' + templates[j]; - QFileInfo fileInfo(ti.path); - ti.name = fileInfo.completeBaseName().mid(9); //remove "template_", do it this way to avoid problems with user input! - ti.type = extensions->determineDocumentType(QUrl::fromUserInput(ti.path)); - ti.icon = QStandardPaths::locate(QStandardPaths::DataLocation, "pics/type_" + ti.name + extensions->defaultExtensionForDocumentType(ti.type) + ".kileicon"); - if (m_TemplateList.contains(ti)) { - KILE_DEBUG_MAIN << "\tignoring: " << ti.path; - } - else { - m_TemplateList.append(ti); - KILE_DEBUG_MAIN << "\tadding: " << ti.name << " " << ti.path; - } - } - } + KILE_DEBUG_MAIN << "===scanForTemplates()==================="; + QStringList dirs = QStandardPaths::locateAll(QStandardPaths::DataLocation, "templates", QStandardPaths::LocateDirectory); + QDir templates; + KileTemplate::Info ti; + KileDocument::Extensions *extensions = m_kileInfo->extensions(); + + m_TemplateList.clear(); + for(QStringList::iterator i = dirs.begin(); i != dirs.end(); ++i) { + templates = QDir(*i, "template_*"); + for (uint j = 0; j < templates.count(); ++j) { + ti.path = templates.path() + '/' + templates[j]; + QFileInfo fileInfo(ti.path); + ti.name = fileInfo.completeBaseName().mid(9); //remove "template_", do it this way to avoid problems with user input! + ti.type = extensions->determineDocumentType(QUrl::fromUserInput(ti.path)); + ti.icon = QStandardPaths::locate(QStandardPaths::DataLocation, "pics/type_" + ti.name + extensions->defaultExtensionForDocumentType(ti.type) + ".kileicon"); + if (m_TemplateList.contains(ti)) { + KILE_DEBUG_MAIN << "\tignoring: " << ti.path; + } + else { + m_TemplateList.append(ti); + KILE_DEBUG_MAIN << "\tadding: " << ti.name << " " << ti.path; + } + } + } } QString Manager::defaultEmptyTemplateCaption() { - return i18n("Empty File"); + return i18n("Empty File"); } QString Manager::defaultEmptyLaTeXTemplateCaption() { - return i18n("Empty LaTeX File"); + return i18n("Empty LaTeX File"); } QString Manager::defaultEmptyBibTeXTemplateCaption() { - return i18n("Empty BibTeX File"); + return i18n("Empty BibTeX File"); } TemplateList Manager::getAllTemplates() const { - return m_TemplateList; + return m_TemplateList; } TemplateList Manager::getTemplates(KileDocument::Type type) const { - if(type == KileDocument::Undefined) { - return getAllTemplates(); - } - - TemplateList toReturn; - for (KileTemplate::TemplateListConstIterator i = m_TemplateList.constBegin(); i != m_TemplateList.constEnd(); ++i) { - KileTemplate::Info info = *i; - if(info.type == type) { - toReturn.push_back(info); - } - } - return toReturn; + if(type == KileDocument::Undefined) { + return getAllTemplates(); + } + + TemplateList toReturn; + for (KileTemplate::TemplateListConstIterator i = m_TemplateList.constBegin(); i != m_TemplateList.constEnd(); ++i) { + KileTemplate::Info info = *i; + if(info.type == type) { + toReturn.push_back(info); + } + } + return toReturn; } } ////////////////////// TemplateItem ////////////////////// // new compare function to make the "Empty (...) Document" items appear at the beginning TemplateItem::TemplateItem(QListWidget * parent, const KileTemplate::Info& info) - : QListWidgetItem(QPixmap(info.icon), info.name, parent) + : QListWidgetItem(QPixmap(info.icon), info.name, parent) { - m_info = info; + m_info = info; } bool TemplateItem::operator<(const QListWidgetItem &other) const { - if(text() == KileTemplate::Manager::defaultEmptyTemplateCaption()) { - return true; - } - else if(other.text() == KileTemplate::Manager::defaultEmptyTemplateCaption()) { - return false; - } - else { - return QListWidgetItem::operator<(other); - } + if(text() == KileTemplate::Manager::defaultEmptyTemplateCaption()) { + return true; + } + else if(other.text() == KileTemplate::Manager::defaultEmptyTemplateCaption()) { + return false; + } + else { + return QListWidgetItem::operator<(other); + } } ////////////////////// TemplateIconView ////////////////////// TemplateIconView::TemplateIconView(QWidget *parent) - : QListWidget(parent), m_templateManager(Q_NULLPTR), m_proc(Q_NULLPTR) { - setViewMode(QListView::IconMode); - setMovement(QListView::Static); - setResizeMode(QListView::Adjust); - setSelectionMode(QAbstractItemView::SingleSelection); - setFlow(QListView::TopToBottom); - setMinimumHeight(100); - setIconSize(QSize(48, 48)); + : QListWidget(parent), m_templateManager(Q_NULLPTR), m_proc(Q_NULLPTR) { + setViewMode(QListView::IconMode); + setMovement(QListView::Static); + setResizeMode(QListView::Adjust); + setSelectionMode(QAbstractItemView::SingleSelection); + setFlow(QListView::TopToBottom); + setMinimumHeight(100); + setIconSize(QSize(48, 48)); } TemplateIconView::~TemplateIconView() { } void TemplateIconView::setTemplateManager(KileTemplate::Manager *templateManager) { - m_templateManager = templateManager; + m_templateManager = templateManager; } void TemplateIconView::fillWithTemplates(KileDocument::Type type) { - if(!m_templateManager) { - return; - } - - clear(); - - if(type == KileDocument::LaTeX) { - searchLaTeXClassFiles(); - } - else { - addTemplateIcons(type); - } + if(!m_templateManager) { + return; + } + + clear(); + + if(type == KileDocument::LaTeX) { + searchLaTeXClassFiles(); + } + else { + addTemplateIcons(type); + } } void TemplateIconView::searchLaTeXClassFiles() { - if(!m_templateManager) { - return; - } + if(!m_templateManager) { + return; + } - m_output.clear(); + m_output.clear(); - QString command = "kpsewhich -format=tex scrartcl.cls beamer.cls prosper.cls HA-prosper.sty"; + QString command = "kpsewhich -format=tex scrartcl.cls beamer.cls prosper.cls HA-prosper.sty"; - delete m_proc; + delete m_proc; - m_proc = new KProcess(this); - (*m_proc) << KShell::splitArgs(command); + m_proc = new KProcess(this); + (*m_proc) << KShell::splitArgs(command); - m_proc->setOutputChannelMode(KProcess::MergedChannels); - m_proc->setReadChannel(QProcess::StandardOutput); + m_proc->setOutputChannelMode(KProcess::MergedChannels); + m_proc->setReadChannel(QProcess::StandardOutput); - connect(m_proc, SIGNAL(readyReadStandardOutput()), this, SLOT(slotProcessOutput())); - connect(m_proc, SIGNAL(finished(int, QProcess::ExitStatus)), this, SLOT(slotProcessExited(int, QProcess::ExitStatus))); - connect(m_proc, SIGNAL(error(QProcess::ProcessError)), this, SLOT(slotProcessError())); - KILE_DEBUG_MAIN << "=== NewFileWidget::searchClassFiles() ===================="; - KILE_DEBUG_MAIN << "\texecute: " << command; - m_proc->start(); + connect(m_proc, SIGNAL(readyReadStandardOutput()), this, SLOT(slotProcessOutput())); + connect(m_proc, SIGNAL(finished(int, QProcess::ExitStatus)), this, SLOT(slotProcessExited(int, QProcess::ExitStatus))); + connect(m_proc, SIGNAL(error(QProcess::ProcessError)), this, SLOT(slotProcessError())); + KILE_DEBUG_MAIN << "=== NewFileWidget::searchClassFiles() ===================="; + KILE_DEBUG_MAIN << "\texecute: " << command; + m_proc->start(); } void TemplateIconView::slotProcessOutput() { - QByteArray buf = m_proc->readAllStandardOutput(); - m_output += QString::fromLocal8Bit(buf.data(), buf.size()); + QByteArray buf = m_proc->readAllStandardOutput(); + m_output += QString::fromLocal8Bit(buf.data(), buf.size()); } void TemplateIconView::slotProcessError() { - addTemplateIcons(KileDocument::LaTeX); - emit classFileSearchFinished(); + addTemplateIcons(KileDocument::LaTeX); + emit classFileSearchFinished(); } void TemplateIconView::slotProcessExited(int /*exitCode*/, QProcess::ExitStatus exitStatus) { - if(exitStatus != QProcess::NormalExit) { - m_output.clear(); - } + if(exitStatus != QProcess::NormalExit) { + m_output.clear(); + } - addTemplateIcons(KileDocument::LaTeX); - emit classFileSearchFinished(); + addTemplateIcons(KileDocument::LaTeX); + emit classFileSearchFinished(); } void TemplateIconView::addTemplateIcons(KileDocument::Type type) { - if(!m_templateManager) { - return; - } - - QString emptyIcon = QStandardPaths::locate(QStandardPaths::DataLocation, "pics/" + QString(DEFAULT_EMPTY_ICON) + ".png" ); - - KileTemplate::Info emptyDocumentInfo; - emptyDocumentInfo.name = KileTemplate::Manager::defaultEmptyTemplateCaption(); - emptyDocumentInfo.icon = emptyIcon; - emptyDocumentInfo.type = type; - TemplateItem *emp = new TemplateItem(this, emptyDocumentInfo); - setCurrentItem(emp); - - if(type == KileDocument::LaTeX) { - // disable non standard templates - QMap map; - map["Scrartcl"] = false; - map["Scrbook"] = false; - map["Scrreprt"] = false; - map["Scrlttr2"] = false; - map["Beamer"] = false; - map["Prosper"] = false; - map["HA-prosper"] = false; - - // split search results and look, which class files are present - QStringList list = m_output.split('\n'); - for(QStringList::Iterator it=list.begin(); it!=list.end(); ++it) { - QString filename = QFileInfo(*it).fileName(); - if(filename=="scrartcl.cls") { - map["Scrartcl"] = true; - map["Scrbook"] = true; - map["Scrreprt"] = true; - map["Scrlttr2"] = true; - } - else if(filename=="beamer.cls") { - map["Beamer"] = true; - } - else if(filename=="prosper.cls") { - map["Prosper"] = true; - } - else if(filename=="HA-prosper.sty") { - map["HA-prosper"] = true; - } - } - - - KileTemplate::TemplateList templateList = m_templateManager->getTemplates(KileDocument::LaTeX); - // insert all standard templates, all user-defined templates - // and those templates, which have a present class - for (KileTemplate::TemplateListIterator i=templateList.begin(); i != templateList.end(); ++i) { - KileTemplate::Info info = *i; - QString classname = info.name; - if(!map.contains(classname) || map[classname]==true) { - new TemplateItem(this, info); - } - } - } - else { - KileTemplate::TemplateList templateList = m_templateManager->getTemplates(type); - for (KileTemplate::TemplateListIterator i=templateList.begin(); i != templateList.end(); ++i) { - new TemplateItem(this, *i); - } - } - - // sort all items (item for 'Empty Document' will always be the first one) - sortItems(); + if(!m_templateManager) { + return; + } + + QString emptyIcon = QStandardPaths::locate(QStandardPaths::DataLocation, "pics/" + QString(DEFAULT_EMPTY_ICON) + ".png" ); + + KileTemplate::Info emptyDocumentInfo; + emptyDocumentInfo.name = KileTemplate::Manager::defaultEmptyTemplateCaption(); + emptyDocumentInfo.icon = emptyIcon; + emptyDocumentInfo.type = type; + TemplateItem *emp = new TemplateItem(this, emptyDocumentInfo); + setCurrentItem(emp); + + if(type == KileDocument::LaTeX) { + // disable non standard templates + QMap map; + map["Scrartcl"] = false; + map["Scrbook"] = false; + map["Scrreprt"] = false; + map["Scrlttr2"] = false; + map["Beamer"] = false; + map["Prosper"] = false; + map["HA-prosper"] = false; + + // split search results and look, which class files are present + QStringList list = m_output.split('\n'); + for(QStringList::Iterator it=list.begin(); it!=list.end(); ++it) { + QString filename = QFileInfo(*it).fileName(); + if(filename=="scrartcl.cls") { + map["Scrartcl"] = true; + map["Scrbook"] = true; + map["Scrreprt"] = true; + map["Scrlttr2"] = true; + } + else if(filename=="beamer.cls") { + map["Beamer"] = true; + } + else if(filename=="prosper.cls") { + map["Prosper"] = true; + } + else if(filename=="HA-prosper.sty") { + map["HA-prosper"] = true; + } + } + + + KileTemplate::TemplateList templateList = m_templateManager->getTemplates(KileDocument::LaTeX); + // insert all standard templates, all user-defined templates + // and those templates, which have a present class + for (KileTemplate::TemplateListIterator i=templateList.begin(); i != templateList.end(); ++i) { + KileTemplate::Info info = *i; + QString classname = info.name; + if(!map.contains(classname) || map[classname]==true) { + new TemplateItem(this, info); + } + } + } + else { + KileTemplate::TemplateList templateList = m_templateManager->getTemplates(type); + for (KileTemplate::TemplateListIterator i=templateList.begin(); i != templateList.end(); ++i) { + new TemplateItem(this, *i); + } + } + + // sort all items (item for 'Empty Document' will always be the first one) + sortItems(); } diff --git a/src/templates.h b/src/templates.h index 3671af3e..d3421994 100644 --- a/src/templates.h +++ b/src/templates.h @@ -1,163 +1,171 @@ /*************************************************************************************** begin : Sat Apr 26 2003 copyright : (C) 2003 by Jeroen Wijnhout (wijnhout@science.uva.nl) 2007, 2008 by Michel Ludwig (michel.ludwig@kdemail.net) ***************************************************************************************/ /*************************************************************************** * * * 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. * * * ***************************************************************************/ #ifndef TEMPLATES_H #define TEMPLATES_H #include #include #include #include #include #include "kileconstants.h" #define DEFAULT_EMPTY_ICON "type_Empty" class KProcess; class KileInfo; namespace KileTemplate { struct Info { - public: - Info(); - - QString name; - QString path; - QString icon; - KileDocument::Type type; - - bool operator==(const Info ti) const; +public: + Info(); + + QString name; + QString path; + QString icon; + KileDocument::Type type; + + bool operator==(const Info ti) const; }; typedef QList TemplateList; typedef QList::iterator TemplateListIterator; typedef QList::const_iterator TemplateListConstIterator; class Manager : public QObject { - Q_OBJECT - - public: - explicit Manager(KileInfo *info, QObject* parent = Q_NULLPTR, const char* name = NULL); - virtual ~Manager(); - - void scanForTemplates(); - - /** - * Get all the templates. - **/ - TemplateList getAllTemplates() const; - - /** - * Get all the templates of a certain type. - * - * @param type The type of the templates that should be returned. You can pass "KileDocument::Undefined" to - * retrieve every template. - **/ - TemplateList getTemplates(KileDocument::Type type) const; - - /** - * Checks whether a template with a given name and type exists. - * - * @return true iff a template with the given name and type could be found - **/ - bool searchForTemplate(const QString& name, KileDocument::Type& type) const; - - // add a template in $HOME/kile/templates/ - bool add(const QUrl &templateSourceURL, const QString &name, const QUrl &icon); - - // remove a template from $HOME/kile/templates/ - bool remove(KileTemplate::Info ti); - - // replaces a template - bool replace(const KileTemplate::Info& toBeReplaced, const QUrl &newTemplateSourceURL, const QString& newName, const QUrl& newIcon); - - // these have to be methods as we cannot use i18n calls in global objects - static QString defaultEmptyTemplateCaption(); - static QString defaultEmptyLaTeXTemplateCaption(); - static QString defaultEmptyBibTeXTemplateCaption(); - - protected: - KileInfo* m_kileInfo; - - private: - bool copyAppData(const QUrl &src, const QString& subdir, const QString& fileName); - bool removeAppData(const QString &file); - - /** - * Adds a new template. This method differs from the other add method in that it does not try to determine - * the type of the template from the passed source URL. - **/ - bool add(const QUrl &templateSourceURL, KileDocument::Type type, const QString& name, const QUrl& icon); - - - private: - TemplateList m_TemplateList; - QString m_TempFilePath; + Q_OBJECT + +public: + explicit Manager(KileInfo *info, QObject* parent = Q_NULLPTR, const char* name = NULL); + virtual ~Manager(); + + void scanForTemplates(); + + /** + * Get all the templates. + **/ + TemplateList getAllTemplates() const; + + /** + * Get all the templates of a certain type. + * + * @param type The type of the templates that should be returned. You can pass "KileDocument::Undefined" to + * retrieve every template. + **/ + TemplateList getTemplates(KileDocument::Type type) const; + + /** + * Checks whether a template with a given name and type exists. + * + * @return true iff a template with the given name and type could be found + **/ + bool searchForTemplate(const QString& name, KileDocument::Type& type) const; + + // add a template in $HOME/kile/templates/ + bool add(const QUrl &templateSourceURL, const QString &name, const QUrl &icon); + + // remove a template from $HOME/kile/templates/ + bool remove(KileTemplate::Info ti); + + // replaces a template + bool replace(const KileTemplate::Info& toBeReplaced, const QUrl &newTemplateSourceURL, const QString& newName, const QUrl& newIcon); + + // these have to be methods as we cannot use i18n calls in global objects + static QString defaultEmptyTemplateCaption(); + static QString defaultEmptyLaTeXTemplateCaption(); + static QString defaultEmptyBibTeXTemplateCaption(); + +protected: + KileInfo* m_kileInfo; + +private: + bool copyAppData(const QUrl &src, const QString& subdir, const QString& fileName); + bool removeAppData(const QString &file); + + /** + * Adds a new template. This method differs from the other add method in that it does not try to determine + * the type of the template from the passed source URL. + **/ + bool add(const QUrl &templateSourceURL, KileDocument::Type type, const QString& name, const QUrl& icon); + + +private: + TemplateList m_TemplateList; + QString m_TempFilePath; }; } class TemplateItem : public QListWidgetItem { public: - TemplateItem( QListWidget * parent, const KileTemplate::Info & info); - ~TemplateItem() {} - - bool operator<(const QListWidgetItem &other) const; - - QString name() { return m_info.name; } - QString path() { return m_info.path; } - QString icon() { return m_info.icon; } - KileDocument::Type type() { return m_info.type; } + TemplateItem( QListWidget * parent, const KileTemplate::Info & info); + ~TemplateItem() {} + + bool operator<(const QListWidgetItem &other) const; + + QString name() { + return m_info.name; + } + QString path() { + return m_info.path; + } + QString icon() { + return m_info.icon; + } + KileDocument::Type type() { + return m_info.type; + } private: - KileTemplate::Info m_info; + KileTemplate::Info m_info; }; class TemplateIconView : public QListWidget { - Q_OBJECT - - public: - TemplateIconView(QWidget *parent = Q_NULLPTR); - virtual ~TemplateIconView(); + Q_OBJECT + +public: + TemplateIconView(QWidget *parent = Q_NULLPTR); + virtual ~TemplateIconView(); - void setTemplateManager(KileTemplate::Manager *templateManager); + void setTemplateManager(KileTemplate::Manager *templateManager); - void fillWithTemplates(KileDocument::Type type); + void fillWithTemplates(KileDocument::Type type); - Q_SIGNALS: - void classFileSearchFinished(); +Q_SIGNALS: + void classFileSearchFinished(); - protected: - KileTemplate::Manager *m_templateManager; - QString m_output; - KProcess *m_proc; +protected: + KileTemplate::Manager *m_templateManager; + QString m_output; + KProcess *m_proc; - void addTemplateIcons(KileDocument::Type type); - void searchLaTeXClassFiles(); + void addTemplateIcons(KileDocument::Type type); + void searchLaTeXClassFiles(); - protected Q_SLOTS: - void slotProcessError(); - void slotProcessOutput(); - void slotProcessExited(int exitCode, QProcess::ExitStatus exitStatus); +protected Q_SLOTS: + void slotProcessError(); + void slotProcessOutput(); + void slotProcessExited(int exitCode, QProcess::ExitStatus exitStatus); }; #endif diff --git a/src/tool_utils.cpp b/src/tool_utils.cpp index 36df9567..ec7857d4 100644 --- a/src/tool_utils.cpp +++ b/src/tool_utils.cpp @@ -1,92 +1,92 @@ /*************************************************************************** Copyright (C) 2012 by Michel Ludwig (michel.ludwig@kdemail.net) ***************************************************************************/ /*************************************************************************** * * * 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. * * * ***************************************************************************/ #include "tool_utils.h" #include namespace KileTool { ToolConfigPair::ToolConfigPair() -: QPair() + : QPair() { } ToolConfigPair::ToolConfigPair(const QString& toolName, const QString& configName) -: QPair(toolName, configName) + : QPair(toolName, configName) { } bool ToolConfigPair::operator<(const ToolConfigPair& p2) const { - const int firstCompare = first.localeAwareCompare(p2.first); + const int firstCompare = first.localeAwareCompare(p2.first); - if(firstCompare != 0) { - return (firstCompare < 0); - } + if(firstCompare != 0) { + return (firstCompare < 0); + } - if(second.isEmpty() || second == DEFAULT_TOOL_CONFIGURATION) { - if(p2.second.isEmpty() || p2.second == DEFAULT_TOOL_CONFIGURATION) { - return false; - } - else { - return true; - } - } - if(p2.second.isEmpty() || p2.second == DEFAULT_TOOL_CONFIGURATION) { - if(second.isEmpty() || second == DEFAULT_TOOL_CONFIGURATION) { - return true; - } - else { - return false; - } - } + if(second.isEmpty() || second == DEFAULT_TOOL_CONFIGURATION) { + if(p2.second.isEmpty() || p2.second == DEFAULT_TOOL_CONFIGURATION) { + return false; + } + else { + return true; + } + } + if(p2.second.isEmpty() || p2.second == DEFAULT_TOOL_CONFIGURATION) { + if(second.isEmpty() || second == DEFAULT_TOOL_CONFIGURATION) { + return true; + } + else { + return false; + } + } - return (second.localeAwareCompare(p2.second) < 0); + return (second.localeAwareCompare(p2.second) < 0); } QString ToolConfigPair::userStringRepresentation(const QString& toolName, const QString& toolConfig) { - return (toolConfig == DEFAULT_TOOL_CONFIGURATION) - ? toolName : i18nc(" - ", "%1 - %2", toolName, toolConfig); + return (toolConfig == DEFAULT_TOOL_CONFIGURATION) + ? toolName : i18nc(" - ", "%1 - %2", toolName, toolConfig); } QString ToolConfigPair::configStringRepresentation(const QString& toolName, const QString& toolConfig) { - QString configString = toolConfig; - if(configString == DEFAULT_TOOL_CONFIGURATION) { - configString.clear(); - } - if(toolName.isEmpty() && configString.isEmpty()) { - return ""; - } - if(configString.isEmpty()) { - return toolName; - } - return toolName + '/' + configString; + QString configString = toolConfig; + if(configString == DEFAULT_TOOL_CONFIGURATION) { + configString.clear(); + } + if(toolName.isEmpty() && configString.isEmpty()) { + return ""; + } + if(configString.isEmpty()) { + return toolName; + } + return toolName + '/' + configString; } ToolConfigPair ToolConfigPair::fromConfigStringRepresentation(const QString& s) { - const int separatorIndex = s.indexOf('/'); - if(separatorIndex < 0) { // for example, is 's' is empty - return ToolConfigPair(s, DEFAULT_TOOL_CONFIGURATION); - } - QString configString = s.mid(separatorIndex + 1); - if(configString.isEmpty()) { - configString = DEFAULT_TOOL_CONFIGURATION; - } - return ToolConfigPair(s.left(separatorIndex), configString); + const int separatorIndex = s.indexOf('/'); + if(separatorIndex < 0) { // for example, is 's' is empty + return ToolConfigPair(s, DEFAULT_TOOL_CONFIGURATION); + } + QString configString = s.mid(separatorIndex + 1); + if(configString.isEmpty()) { + configString = DEFAULT_TOOL_CONFIGURATION; + } + return ToolConfigPair(s.left(separatorIndex), configString); } } diff --git a/src/tool_utils.h b/src/tool_utils.h index 2734473e..476ed553 100644 --- a/src/tool_utils.h +++ b/src/tool_utils.h @@ -1,61 +1,61 @@ /*************************************************************************** Copyright (C) 2012 by Michel Ludwig (michel.ludwig@kdemail.net) ***************************************************************************/ /*************************************************************************** * * * 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. * * * ***************************************************************************/ #ifndef TOOL_UTILS_H #define TOOL_UTILS_H #include #include #include #define DEFAULT_TOOL_CONFIGURATION "Default" namespace KileTool { class ToolConfigPair : public QPair { public: - ToolConfigPair(); - ToolConfigPair(const QString& toolName, const QString& configName); - - inline bool isValid() const - { - return !first.isEmpty(); - } - - /** If the first components are equal, we compare the second one but - * an empty config name or the default tool config name should precede all others. - **/ - bool operator<(const ToolConfigPair& p2) const; - - static QString userStringRepresentation(const QString& toolName, const QString& toolConfig); - inline QString userStringRepresentation() const - { - return userStringRepresentation(first, second); - } - - static QString configStringRepresentation(const QString& toolName, const QString& toolConfig); - QString configStringRepresentation() const - { - return configStringRepresentation(first, second); - } - - static ToolConfigPair fromConfigStringRepresentation(const QString& s); + ToolConfigPair(); + ToolConfigPair(const QString& toolName, const QString& configName); + + inline bool isValid() const + { + return !first.isEmpty(); + } + + /** If the first components are equal, we compare the second one but + * an empty config name or the default tool config name should precede all others. + **/ + bool operator<(const ToolConfigPair& p2) const; + + static QString userStringRepresentation(const QString& toolName, const QString& toolConfig); + inline QString userStringRepresentation() const + { + return userStringRepresentation(first, second); + } + + static QString configStringRepresentation(const QString& toolName, const QString& toolConfig); + QString configStringRepresentation() const + { + return configStringRepresentation(first, second); + } + + static ToolConfigPair fromConfigStringRepresentation(const QString& s); }; } Q_DECLARE_METATYPE(KileTool::ToolConfigPair) #endif diff --git a/src/userhelp.cpp b/src/userhelp.cpp index 2c4064ba..e8432031 100644 --- a/src/userhelp.cpp +++ b/src/userhelp.cpp @@ -1,209 +1,209 @@ /********************************************************************************************** Copyright (C) 2005-2006 by Holger Danielsson (holger.danielsson@t-online.de) 2008-2017 by Michel Ludwig (michel.ludwig@kdemail.net) **********************************************************************************************/ /*************************************************************************** * * * 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. * * * ***************************************************************************/ #include "userhelp.h" #include #include #include #include #include #include #include "kileactions.h" #include "kileconfig.h" #include "kiledebug.h" #include "kilestdtools.h" #include "dialogs/userhelpdialog.h" namespace KileHelp { UserHelp::UserHelp(KileTool::Manager *manager, KActionMenu *userHelpActionMenu, QWidget* mainWindow) - : m_manager(manager), m_userHelpActionMenu(userHelpActionMenu), m_mainWindow(mainWindow) + : m_manager(manager), m_userHelpActionMenu(userHelpActionMenu), m_mainWindow(mainWindow) { - setupUserHelpMenu(); + setupUserHelpMenu(); } UserHelp::~UserHelp() { - clearActionList(); + clearActionList(); } void UserHelp::clearActionList() { - for(QList::iterator i = m_actionList.begin(); i != m_actionList.end(); ++i) { - delete *i; - } - m_actionList.clear(); + for(QList::iterator i = m_actionList.begin(); i != m_actionList.end(); ++i) { + delete *i; + } + m_actionList.clear(); } void UserHelp::readConfig(QStringList& menuList, QList& fileList) { - menuList.clear(); - fileList.clear(); - - // first read all entries - KConfig *config = m_manager->config(); - KConfigGroup configGroup = config->group("UserHelp"); - int entries = configGroup.readEntry("entries", int(0)); - for(int i = 0; i < entries; ++i) { - QString menu = configGroup.readEntry(QString("menu%1").arg(i)); - menuList << menu; - if(!menu.isEmpty() && menu != "-") { - fileList << configGroup.readEntry(QString("file%1").arg(i), QUrl()); - } - else { - fileList << QUrl(); - } - } + menuList.clear(); + fileList.clear(); + + // first read all entries + KConfig *config = m_manager->config(); + KConfigGroup configGroup = config->group("UserHelp"); + int entries = configGroup.readEntry("entries", int(0)); + for(int i = 0; i < entries; ++i) { + QString menu = configGroup.readEntry(QString("menu%1").arg(i)); + menuList << menu; + if(!menu.isEmpty() && menu != "-") { + fileList << configGroup.readEntry(QString("file%1").arg(i), QUrl()); + } + else { + fileList << QUrl(); + } + } } void UserHelp::writeConfig(const QStringList& menuList, const QList& fileList) { - //KILE_DEBUG_MAIN << "\tuserhelp: write config"; - int entries = menuList.count(); - - // first delete old entries - KConfig *config = m_manager->config(); - config->deleteGroup("UserHelp"); - - // then write new entries - KConfigGroup configGroup = config->group("UserHelp"); - configGroup.writeEntry("entries", entries); - for(int i = 0; i < entries; ++i) { - QString menu = menuList[i]; - configGroup.writeEntry(QString("menu%1").arg(i), menu); - if(menu != "-") { - configGroup.writeEntry(QString("file%1").arg(i), fileList[i]); - } - } + //KILE_DEBUG_MAIN << "\tuserhelp: write config"; + int entries = menuList.count(); + + // first delete old entries + KConfig *config = m_manager->config(); + config->deleteGroup("UserHelp"); + + // then write new entries + KConfigGroup configGroup = config->group("UserHelp"); + configGroup.writeEntry("entries", entries); + for(int i = 0; i < entries; ++i) { + QString menu = menuList[i]; + configGroup.writeEntry(QString("menu%1").arg(i), menu); + if(menu != "-") { + configGroup.writeEntry(QString("file%1").arg(i), fileList[i]); + } + } } void UserHelp::setupUserHelpMenu() { - QStringList menuList; - QList urlList; - readConfig(menuList, urlList); - - clearActionList(); - - m_userHelpActionMenu->setEnabled(menuList.count() > 0); - QList::iterator j = urlList.begin(); - - for(QStringList::iterator i = menuList.begin(); i != menuList.end(); ++i) { - QString menu = *i; - // first look, if this entry is a separator - if(menu == "-" ) { - QAction *action = m_userHelpActionMenu->addSeparator(); - m_actionList.append(action); - } - else { - QUrl url = *j; - - // some file types have an icon - QFileInfo fi(url.fileName()); - QString ext = fi.suffix(); - if(ext == "htm") { - ext = "html"; - } - KileAction::VariantSelection *action = new KileAction::VariantSelection(menu, QVariant::fromValue(url), this); - if(!url.isLocalFile() || ext == "html" || ext == "dvi" || ext == "ps" || ext == "pdf") { - QString icon = (!url.isLocalFile()) ? "viewhtml" : "view" + ext; - action->setIcon(QIcon::fromTheme(icon)); - } - connect(action, SIGNAL(triggered(const QUrl&)), this, SLOT(slotUserHelpActivated(const QUrl&))); - m_userHelpActionMenu->addAction(action); - m_actionList.append(action); - } - ++j; - } + QStringList menuList; + QList urlList; + readConfig(menuList, urlList); + + clearActionList(); + + m_userHelpActionMenu->setEnabled(menuList.count() > 0); + QList::iterator j = urlList.begin(); + + for(QStringList::iterator i = menuList.begin(); i != menuList.end(); ++i) { + QString menu = *i; + // first look, if this entry is a separator + if(menu == "-" ) { + QAction *action = m_userHelpActionMenu->addSeparator(); + m_actionList.append(action); + } + else { + QUrl url = *j; + + // some file types have an icon + QFileInfo fi(url.fileName()); + QString ext = fi.suffix(); + if(ext == "htm") { + ext = "html"; + } + KileAction::VariantSelection *action = new KileAction::VariantSelection(menu, QVariant::fromValue(url), this); + if(!url.isLocalFile() || ext == "html" || ext == "dvi" || ext == "ps" || ext == "pdf") { + QString icon = (!url.isLocalFile()) ? "viewhtml" : "view" + ext; + action->setIcon(QIcon::fromTheme(icon)); + } + connect(action, SIGNAL(triggered(const QUrl&)), this, SLOT(slotUserHelpActivated(const QUrl&))); + m_userHelpActionMenu->addAction(action); + m_actionList.append(action); + } + ++j; + } } void UserHelp::enableUserHelpEntries(bool state) { - QStringList menuList; - QList urlList; - readConfig(menuList, urlList); - m_userHelpActionMenu->setEnabled(state && (menuList.size() > 0)); + QStringList menuList; + QList urlList; + readConfig(menuList, urlList); + m_userHelpActionMenu->setEnabled(state && (menuList.size() > 0)); } void UserHelp::slotUserHelpActivated(const QUrl &url) { - KILE_DEBUG_MAIN << "==slotUserHelpActivated(" << url << ")============"; - - // does the files exist? - QFileInfo fi(url.toLocalFile()); - bool local = url.isLocalFile(); - if(local && !fi.exists()) { - KMessageBox::error(m_mainWindow, i18n("The file '%1' does not exist.", url.toDisplayString())); - return; - } - - // show help file - KILE_DEBUG_MAIN << "\tshow userhelpfile (" << url << ")"; - - // determine, how to show the file - QString type; - if(local) { - QString ext = fi.suffix(); - if(ext == "dvi") { - type = "ViewDVI"; - } - else if(ext == "ps") { - type = "ViewPS"; - } - else if(ext == "pdf") { - type = "ViewPDF"; - } - else if(ext == "html" || ext == "htm") { - type = "ViewHTML"; - } - } - - KileTool::Base *tool = Q_NULLPTR; - if(!type.isEmpty() && type != "ViewHTML") { - tool = m_manager->createTool(type, "Okular", false); - } - if(tool) { - tool->setFlags(0); - tool->setSource(url.toLocalFile()); - m_manager->run(tool); - } - else { - new KRun(url,m_mainWindow); - } + KILE_DEBUG_MAIN << "==slotUserHelpActivated(" << url << ")============"; + + // does the files exist? + QFileInfo fi(url.toLocalFile()); + bool local = url.isLocalFile(); + if(local && !fi.exists()) { + KMessageBox::error(m_mainWindow, i18n("The file '%1' does not exist.", url.toDisplayString())); + return; + } + + // show help file + KILE_DEBUG_MAIN << "\tshow userhelpfile (" << url << ")"; + + // determine, how to show the file + QString type; + if(local) { + QString ext = fi.suffix(); + if(ext == "dvi") { + type = "ViewDVI"; + } + else if(ext == "ps") { + type = "ViewPS"; + } + else if(ext == "pdf") { + type = "ViewPDF"; + } + else if(ext == "html" || ext == "htm") { + type = "ViewHTML"; + } + } + + KileTool::Base *tool = Q_NULLPTR; + if(!type.isEmpty() && type != "ViewHTML") { + tool = m_manager->createTool(type, "Okular", false); + } + if(tool) { + tool->setFlags(0); + tool->setSource(url.toLocalFile()); + m_manager->run(tool); + } + else { + new KRun(url,m_mainWindow); + } } void UserHelp::userHelpDialog() { - QStringList menuList; - QList fileList; - readConfig(menuList, fileList); - - KileDialog::UserHelpDialog *dialog = new KileDialog::UserHelpDialog(); - dialog->setParameter(menuList, fileList); - if(dialog->exec()) { - //KILE_DEBUG_MAIN << "\t new userhelp entries accepted"; - dialog->getParameter(menuList, fileList); - writeConfig(menuList, fileList); - setupUserHelpMenu(); - } - - delete dialog; + QStringList menuList; + QList fileList; + readConfig(menuList, fileList); + + KileDialog::UserHelpDialog *dialog = new KileDialog::UserHelpDialog(); + dialog->setParameter(menuList, fileList); + if(dialog->exec()) { + //KILE_DEBUG_MAIN << "\t new userhelp entries accepted"; + dialog->getParameter(menuList, fileList); + writeConfig(menuList, fileList); + setupUserHelpMenu(); + } + + delete dialog; } } diff --git a/src/userhelp.h b/src/userhelp.h index e2c2f7f0..fea54c87 100644 --- a/src/userhelp.h +++ b/src/userhelp.h @@ -1,66 +1,66 @@ /*********************************************************************************************** userhelp.h ---------------------------------------------------------------------------- date : Aug 17 2006 version : 0.15 copyright : (C) 2005-2006 by Holger Danielsson (holger.danielsson@t-online.de) 2008 by Michel Ludwig (michel.ludwig@kdemail.net) ***********************************************************************************************/ /*************************************************************************** * * * 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. * * * ***************************************************************************/ #ifndef USERHELP_H #define USERHELP_H #include #include #include #include #include #include #include #include "kiletoolmanager.h" namespace KileHelp { class UserHelp: public QObject { - Q_OBJECT + Q_OBJECT public: - UserHelp(KileTool::Manager *manager, KActionMenu *userHelpActionMenu, QWidget *mainWindow); - ~UserHelp(); - void userHelpDialog(); - void enableUserHelpEntries(bool state); + UserHelp(KileTool::Manager *manager, KActionMenu *userHelpActionMenu, QWidget *mainWindow); + ~UserHelp(); + void userHelpDialog(); + void enableUserHelpEntries(bool state); private Q_SLOTS: - void slotUserHelpActivated(const QUrl &url); - //void slotUserHelpDialog(); + void slotUserHelpActivated(const QUrl &url); + //void slotUserHelpDialog(); private: - void clearActionList(); - void readConfig(QStringList& menuList, QList& fileList); - void writeConfig(const QStringList& menuList, const QList& fileList); + void clearActionList(); + void readConfig(QStringList& menuList, QList& fileList); + void writeConfig(const QStringList& menuList, const QList& fileList); - void setupUserHelpMenu(); + void setupUserHelpMenu(); - KileTool::Manager *m_manager; - KActionMenu *m_userHelpActionMenu; - QWidget *m_mainWindow; + KileTool::Manager *m_manager; + KActionMenu *m_userHelpActionMenu; + QWidget *m_mainWindow; - QList m_actionList; + QList m_actionList; }; } #endif diff --git a/src/usermenu/usermenudata.cpp b/src/usermenu/usermenudata.cpp index 8bf2277f..55850760 100644 --- a/src/usermenu/usermenudata.cpp +++ b/src/usermenu/usermenudata.cpp @@ -1,99 +1,99 @@ /*********************************************************************************** Copyright (C) 2011-2012 by Holger Danielsson (holger.danielsson@versanet.de) (C) 2018 by Michel Ludwig (michel.ludwig@gmail.com) ***********************************************************************************/ /*************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ #include "usermenu/usermenudata.h" #include "kiledebug.h" namespace KileMenu { UserMenuData::UserMenuData() { - clear(); + clear(); } void UserMenuData::clear() { - menutype = Text; - menutitle.clear(); - filename.clear(); - parameter.clear(); - text.clear(); - icon.clear(); - shortcut.clear(); - - needsSelection = false; - useContextMenu = false; - replaceSelection = false; - insertOutput = false; - selectInsertion = false; + menutype = Text; + menutitle.clear(); + filename.clear(); + parameter.clear(); + text.clear(); + icon.clear(); + shortcut.clear(); + + needsSelection = false; + useContextMenu = false; + replaceSelection = false; + insertOutput = false; + selectInsertion = false; } // static list for xml menu attributes QStringList UserMenuData::xmlMenuAttrList = QStringList() << "text" << "file" << "program" << "separator" << "submenu"; // static list for xml menu tags QStringList UserMenuData::xmlMenuTagList = QStringList() << "text" << "filename" << "parameter" - << "icon" << "shortcut" - << "needsSelection" << "useContextMenu" << "replaceSelection" - << "selectInsertion" << "insertOutput" << "title"; + << "icon" << "shortcut" + << "needsSelection" << "useContextMenu" << "replaceSelection" + << "selectInsertion" << "insertOutput" << "title"; // static methods for xml menu attributes UserMenuData::MenuType UserMenuData::xmlMenuType(const QString &name) { - int index = xmlMenuAttrList.indexOf(name); - return ( index >= 0 ) ? (UserMenuData::MenuType)index : UserMenuData::Text; + int index = xmlMenuAttrList.indexOf(name); + return ( index >= 0 ) ? (UserMenuData::MenuType)index : UserMenuData::Text; } QString UserMenuData::xmlMenuTypeName(int index) { - return xmlMenuAttrList[index]; + return xmlMenuAttrList[index]; } // static methods for xml menu tags int UserMenuData::xmlMenuTag(const QString &tag) { - return xmlMenuTagList.indexOf(tag); + return xmlMenuTagList.indexOf(tag); } QString UserMenuData::xmlMenuTagName(int index) { - return xmlMenuTagList[index]; + return xmlMenuTagList[index]; } // first, every backslash is replaced with the string "\\;" (backslash, followed by ':') // then, every line feed character '\n' is replaced with the string "\\n" (backslash, followed by 'n') QString UserMenuData::encodeLineFeed(const QString& string) { - QString toReturn = string; + QString toReturn = string; toReturn = toReturn.replace(QLatin1Char('\\'), QLatin1String("\\;")); - toReturn = toReturn.replace(QLatin1Char('\n'), QLatin1String("\\n")); + toReturn = toReturn.replace(QLatin1Char('\n'), QLatin1String("\\n")); - return toReturn; + return toReturn; } QString UserMenuData::decodeLineFeed(const QString& string) { - QString toReturn = string; + QString toReturn = string; toReturn = toReturn.replace(QLatin1String("\\n"), QLatin1String("\n")); - toReturn = toReturn.replace(QLatin1String("\\;"), QLatin1String("\\")); + toReturn = toReturn.replace(QLatin1String("\\;"), QLatin1String("\\")); - return toReturn; + return toReturn; } } diff --git a/src/utilities.cpp b/src/utilities.cpp index 83ab9a97..8a9c5c0c 100644 --- a/src/utilities.cpp +++ b/src/utilities.cpp @@ -1,124 +1,124 @@ /************************************************************************** * Copyright (C) 2008-2017 by Michel Ludwig (michel.ludwig@kdemail.net) * ***************************************************************************/ /************************************************************************** * * * 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. * * * ***************************************************************************/ #include "utilities.h" #include #include #include #include #include #include #include #include "kiledebug.h" ServiceRunAction::ServiceRunAction(const KService& service, - const QList& urls, - QWidget* window, - bool tempFiles, - const QString& suggestedFileName, - const QByteArray& asn, - QObject *parent) -: QAction(QIcon::fromTheme(service.icon()), service.genericName(), parent), -m_service(service), -m_urlList(urls), -m_window(window), -m_tempFiles(tempFiles), -m_suggestedFileName(suggestedFileName), -m_asn(asn) + const QList& urls, + QWidget* window, + bool tempFiles, + const QString& suggestedFileName, + const QByteArray& asn, + QObject *parent) + : QAction(QIcon::fromTheme(service.icon()), service.genericName(), parent), + m_service(service), + m_urlList(urls), + m_window(window), + m_tempFiles(tempFiles), + m_suggestedFileName(suggestedFileName), + m_asn(asn) { - connect(this, SIGNAL(triggered()), this, SLOT(runService())); + connect(this, SIGNAL(triggered()), this, SLOT(runService())); } ServiceRunAction::~ServiceRunAction() { } void ServiceRunAction::runService() { - KRun::runService(m_service, m_urlList, m_window, - m_tempFiles, - m_suggestedFileName, - m_asn); + KRun::runService(m_service, m_urlList, m_window, + m_tempFiles, + m_suggestedFileName, + m_asn); } QString KileUtilities::lastModifiedFile(const QStringList& files, const QString& baseDir) { - KILE_DEBUG_MAIN << "==KileUtilities::lastModifiedFile()=====" << files << "baseDir:" << baseDir; - - if(files.empty()) { - return QString(); - } - - QStringList absoluteFileNames; - if(baseDir.isEmpty()) { - absoluteFileNames = files; - } - else { - QDir basePath(baseDir); - Q_FOREACH(const QString& file, files) { - absoluteFileNames.append(basePath.absoluteFilePath(file)); - } - } - - QDateTime lastModifiedTime; - const QString* lastModifiedFile = Q_NULLPTR; - - Q_FOREACH(const QString& file, absoluteFileNames) { - QFileInfo fileInfo(file); - if(!fileInfo.exists()) { - KILE_DEBUG_MAIN << "file does not exist:" << file << "files:" << files; - continue; - } - QDateTime modificationTime = fileInfo.lastModified(); - if(!lastModifiedTime.isValid() || modificationTime > lastModifiedTime) { - lastModifiedFile = &file; - lastModifiedTime = modificationTime; - } - } - - if(lastModifiedFile) { - return *lastModifiedFile; - } - else { - return QString(); - } + KILE_DEBUG_MAIN << "==KileUtilities::lastModifiedFile()=====" << files << "baseDir:" << baseDir; + + if(files.empty()) { + return QString(); + } + + QStringList absoluteFileNames; + if(baseDir.isEmpty()) { + absoluteFileNames = files; + } + else { + QDir basePath(baseDir); + Q_FOREACH(const QString& file, files) { + absoluteFileNames.append(basePath.absoluteFilePath(file)); + } + } + + QDateTime lastModifiedTime; + const QString* lastModifiedFile = Q_NULLPTR; + + Q_FOREACH(const QString& file, absoluteFileNames) { + QFileInfo fileInfo(file); + if(!fileInfo.exists()) { + KILE_DEBUG_MAIN << "file does not exist:" << file << "files:" << files; + continue; + } + QDateTime modificationTime = fileInfo.lastModified(); + if(!lastModifiedTime.isValid() || modificationTime > lastModifiedTime) { + lastModifiedFile = &file; + lastModifiedTime = modificationTime; + } + } + + if(lastModifiedFile) { + return *lastModifiedFile; + } + else { + return QString(); + } } void centerWidgetRelativeToParentRect(QWidget *widget, const QRect& parentRect) { - QRect alignedRect = QStyle::alignedRect(Qt::LeftToRight, Qt::AlignCenter, widget->size(), parentRect); - widget->move(alignedRect.x(), alignedRect.y()); + QRect alignedRect = QStyle::alignedRect(Qt::LeftToRight, Qt::AlignCenter, widget->size(), parentRect); + widget->move(alignedRect.x(), alignedRect.y()); } void KileUtilities::centerWidgetRelativeToParent(QWidget *widget) { - QWidget *parentWidget = widget->parentWidget(); - if(!parentWidget) { - centerWidgetRelativeToParentRect(widget, QApplication::desktop()->availableGeometry(widget)); - } - else { - QRect parentRect(parentWidget->mapToGlobal(QPoint(0, 0)), parentWidget->size()); - centerWidgetRelativeToParentRect(widget, parentRect); - } + QWidget *parentWidget = widget->parentWidget(); + if(!parentWidget) { + centerWidgetRelativeToParentRect(widget, QApplication::desktop()->availableGeometry(widget)); + } + else { + QRect parentRect(parentWidget->mapToGlobal(QPoint(0, 0)), parentWidget->size()); + centerWidgetRelativeToParentRect(widget, parentRect); + } } void KileUtilities::scheduleCenteringOfWidget(QWidget *widget) { - QTimer::singleShot(0, widget, [=] () { - centerWidgetRelativeToParent(widget); - }); + QTimer::singleShot(0, widget, [=] () { + centerWidgetRelativeToParent(widget); + }); } diff --git a/src/utilities.h b/src/utilities.h index 6bf53397..cebaac56 100644 --- a/src/utilities.h +++ b/src/utilities.h @@ -1,72 +1,72 @@ /************************************************************************** * Copyright (C) 2008-2017 by Michel Ludwig (michel.ludwig@kdemail.net) * ***************************************************************************/ /************************************************************************** * * * 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. * * * ***************************************************************************/ #ifndef UTILITIES_H #define UTILITIES_H #include #include #include class ServiceRunAction : public QAction { - Q_OBJECT + Q_OBJECT - public: - ServiceRunAction(const KService& service, - const QList& urls, - QWidget* window, - bool tempFiles = false, - const QString& suggestedFileName = QString(), - const QByteArray& asn = "", - QObject *parent = Q_NULLPTR); - ~ServiceRunAction(); +public: + ServiceRunAction(const KService& service, + const QList& urls, + QWidget* window, + bool tempFiles = false, + const QString& suggestedFileName = QString(), + const QByteArray& asn = "", + QObject *parent = Q_NULLPTR); + ~ServiceRunAction(); - protected Q_SLOTS: - void runService(); +protected Q_SLOTS: + void runService(); - protected: - const KService& m_service; - QList m_urlList; - QWidget* m_window; - bool m_tempFiles; - QString m_suggestedFileName; - QByteArray m_asn; +protected: + const KService& m_service; + QList m_urlList; + QWidget* m_window; + bool m_tempFiles; + QString m_suggestedFileName; + QByteArray m_asn; }; namespace KileUtilities { - /** - * @brief Finds the file with the most recent modification time from a list - * - * Checks last modification time for files and returns absolute (see @ref baseDir description) file name of - * file with the latest modification time - * @param files List of filenames, relative to @ref baseDir - * @param baseDir Path to base directory. If empty, @ref files are used as they are - * @return Absolute path of the file with the latest modification time or empty string if @ref files is empty - **/ - QString lastModifiedFile(const QStringList& files, const QString& baseDir = QString()); +/** + * @brief Finds the file with the most recent modification time from a list + * + * Checks last modification time for files and returns absolute (see @ref baseDir description) file name of + * file with the latest modification time + * @param files List of filenames, relative to @ref baseDir + * @param baseDir Path to base directory. If empty, @ref files are used as they are + * @return Absolute path of the file with the latest modification time or empty string if @ref files is empty + **/ +QString lastModifiedFile(const QStringList& files, const QString& baseDir = QString()); - /** - * Centers the given widget w.r.t. its parent. If it doesn't have a parent, the containing screen is used. - **/ - void centerWidgetRelativeToParent(QWidget *widget); +/** + * Centers the given widget w.r.t. its parent. If it doesn't have a parent, the containing screen is used. + **/ +void centerWidgetRelativeToParent(QWidget *widget); - /** - * Schedules the centering of the given widget w.r.t. its parent in the event loop. - **/ - void scheduleCenteringOfWidget(QWidget *widget); +/** + * Schedules the centering of the given widget w.r.t. its parent in the event loop. + **/ +void scheduleCenteringOfWidget(QWidget *widget); } #endif diff --git a/src/widgets/abbreviationview.cpp b/src/widgets/abbreviationview.cpp index bf5557f3..4469fa1f 100644 --- a/src/widgets/abbreviationview.cpp +++ b/src/widgets/abbreviationview.cpp @@ -1,184 +1,184 @@ /**************************************************************************************** begin : Feb 24 2007 copyright : 2007 by Holger Danielsson (holger.danielsson@versanet.de) 2008 - 2009 by Michel Ludwig (michel.ludwig@kdemail.net) *****************************************************************************************/ /*************************************************************************** * * * 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. * * * ***************************************************************************/ #include "widgets/abbreviationview.h" #include #include #include #include #include #include #include #include "abbreviationmanager.h" #include "dialogs/abbreviationinputdialog.h" #include "kiledebug.h" namespace KileWidget { AbbreviationView::AbbreviationView(KileAbbreviation::Manager *manager, QWidget *parent) - : QTreeWidget(parent), m_abbreviationManager(manager) + : QTreeWidget(parent), m_abbreviationManager(manager) { - setColumnCount(2); - QStringList headerLabelList; - headerLabelList << i18n("Short") << QString() << i18n("Expanded Text"); - setHeaderLabels(headerLabelList); - setAllColumnsShowFocus(true); + setColumnCount(2); + QStringList headerLabelList; + headerLabelList << i18n("Short") << QString() << i18n("Expanded Text"); + setHeaderLabels(headerLabelList); + setAllColumnsShowFocus(true); - header()->setSectionsMovable(false); // default: true - header()->setSectionResizeMode(QHeaderView::ResizeToContents); + header()->setSectionsMovable(false); // default: true + header()->setSectionResizeMode(QHeaderView::ResizeToContents); - setContextMenuPolicy(Qt::CustomContextMenu); + setContextMenuPolicy(Qt::CustomContextMenu); - connect(this, SIGNAL(itemActivated(QTreeWidgetItem*,int)), this, SLOT(slotItemClicked(QTreeWidgetItem*,int))); - connect(this, SIGNAL(customContextMenuRequested(const QPoint&)), this, SLOT(slotCustomContextMenuRequested(const QPoint&))); + connect(this, SIGNAL(itemActivated(QTreeWidgetItem*,int)), this, SLOT(slotItemClicked(QTreeWidgetItem*,int))); + connect(this, SIGNAL(customContextMenuRequested(const QPoint&)), this, SLOT(slotCustomContextMenuRequested(const QPoint&))); } AbbreviationView::~AbbreviationView() { } //////////////////// init abbreviation view with wordlists //////////////////// void AbbreviationView::updateAbbreviations() { -KILE_DEBUG_MAIN; - setUpdatesEnabled(false); - clear(); - const QMap >& abbreviationMap = m_abbreviationManager->getAbbreviationMap(); - QList itemList; - for(QMap >::const_iterator i = abbreviationMap.begin(); - i != abbreviationMap.end(); ++i) { - QPair pair = i.value(); - QTreeWidgetItem *item = new QTreeWidgetItem(); - item->setText(ALVabbrev, i.key()); - item->setText(ALVlocal, (pair.second) ? QString() : "*"); - item->setText(ALVexpansion, pair.first); - itemList.push_back(item); - } - addTopLevelItems(itemList); - - setUpdatesEnabled(true); + KILE_DEBUG_MAIN; + setUpdatesEnabled(false); + clear(); + const QMap >& abbreviationMap = m_abbreviationManager->getAbbreviationMap(); + QList itemList; + for(QMap >::const_iterator i = abbreviationMap.begin(); + i != abbreviationMap.end(); ++i) { + QPair pair = i.value(); + QTreeWidgetItem *item = new QTreeWidgetItem(); + item->setText(ALVabbrev, i.key()); + item->setText(ALVlocal, (pair.second) ? QString() : "*"); + item->setText(ALVexpansion, pair.first); + itemList.push_back(item); + } + addTopLevelItems(itemList); + + setUpdatesEnabled(true); } //////////////////// find abbreviation //////////////////// bool AbbreviationView::findAbbreviation(const QString &abbrev) { - QTreeWidgetItemIterator it(this); - while(*it) { - QTreeWidgetItem *current = *it; - if(current->text(AbbreviationView::ALVabbrev) == abbrev) { - return true; - } - - ++it; - } - return false; + QTreeWidgetItemIterator it(this); + while(*it) { + QTreeWidgetItem *current = *it; + if(current->text(AbbreviationView::ALVabbrev) == abbrev) { + return true; + } + + ++it; + } + return false; } //////////////////// item clicked //////////////////// void AbbreviationView::slotItemClicked(QTreeWidgetItem *item, int /* column */) { - if(item) { - QString s = item->text(AbbreviationView::ALVexpansion); - s.replace("%n","\n"); - emit( sendText(s) ); - } + if(item) { + QString s = item->text(AbbreviationView::ALVexpansion); + s.replace("%n","\n"); + emit( sendText(s) ); + } } //////////////////// context menu //////////////////// void AbbreviationView::slotCustomContextMenuRequested(const QPoint& p) { - QMenu popupMenu; - QAction *action = new QAction(i18n("&Add"), &popupMenu); - connect(action, SIGNAL(triggered()), this, SLOT(slotAddAbbreviation())); - popupMenu.addAction(action); - - QList selectedList = selectedItems(); - if(selectedList.count() > 0) { - QTreeWidgetItem *selectedItem = selectedList.first(); - if(!selectedItem->text(ALVlocal).isEmpty()) { - popupMenu.addSeparator(); - action = new QAction(i18n("&Edit"), &popupMenu); - connect(action, SIGNAL(triggered()), this, SLOT(slotChangeAbbreviation())); - popupMenu.addAction(action); - popupMenu.addSeparator(); - action = new QAction(i18n("&Delete"), &popupMenu); - connect(action, SIGNAL(triggered()), this, SLOT(slotDeleteAbbreviation())); - popupMenu.addAction(action); - } - } - - - popupMenu.exec(mapToGlobal(p)); + QMenu popupMenu; + QAction *action = new QAction(i18n("&Add"), &popupMenu); + connect(action, SIGNAL(triggered()), this, SLOT(slotAddAbbreviation())); + popupMenu.addAction(action); + + QList selectedList = selectedItems(); + if(selectedList.count() > 0) { + QTreeWidgetItem *selectedItem = selectedList.first(); + if(!selectedItem->text(ALVlocal).isEmpty()) { + popupMenu.addSeparator(); + action = new QAction(i18n("&Edit"), &popupMenu); + connect(action, SIGNAL(triggered()), this, SLOT(slotChangeAbbreviation())); + popupMenu.addAction(action); + popupMenu.addSeparator(); + action = new QAction(i18n("&Delete"), &popupMenu); + connect(action, SIGNAL(triggered()), this, SLOT(slotDeleteAbbreviation())); + popupMenu.addAction(action); + } + } + + + popupMenu.exec(mapToGlobal(p)); } void AbbreviationView::slotAddAbbreviation() { - KileDialog::AbbreviationInputDialog dialog(this, Q_NULLPTR, ALVadd); - if(dialog.exec() == QDialog::Accepted) { - QString abbrev, expansion; - dialog.abbreviation(abbrev, expansion); - m_abbreviationManager->updateLocalAbbreviation(abbrev, expansion); - } + KileDialog::AbbreviationInputDialog dialog(this, Q_NULLPTR, ALVadd); + if(dialog.exec() == QDialog::Accepted) { + QString abbrev, expansion; + dialog.abbreviation(abbrev, expansion); + m_abbreviationManager->updateLocalAbbreviation(abbrev, expansion); + } } void AbbreviationView::slotChangeAbbreviation() { - QList selectedList = selectedItems(); - if(selectedList.count() == 0) { - return; - } - QTreeWidgetItem *selectedItem = selectedList.first(); - QString oldAbbreviationText = selectedItem->text(ALVabbrev); - QString oldAbbreviationExpansion = selectedItem->text(ALVexpansion); - KileDialog::AbbreviationInputDialog dialog(this, selectedItem, ALVedit); - if(dialog.exec() == QDialog::Accepted) { - QString abbrev, expansion; - dialog.abbreviation(abbrev, expansion); - if(oldAbbreviationText != abbrev) { - m_abbreviationManager->removeLocalAbbreviation(oldAbbreviationText); - } - m_abbreviationManager->updateLocalAbbreviation(abbrev, expansion); - } + QList selectedList = selectedItems(); + if(selectedList.count() == 0) { + return; + } + QTreeWidgetItem *selectedItem = selectedList.first(); + QString oldAbbreviationText = selectedItem->text(ALVabbrev); + QString oldAbbreviationExpansion = selectedItem->text(ALVexpansion); + KileDialog::AbbreviationInputDialog dialog(this, selectedItem, ALVedit); + if(dialog.exec() == QDialog::Accepted) { + QString abbrev, expansion; + dialog.abbreviation(abbrev, expansion); + if(oldAbbreviationText != abbrev) { + m_abbreviationManager->removeLocalAbbreviation(oldAbbreviationText); + } + m_abbreviationManager->updateLocalAbbreviation(abbrev, expansion); + } } void AbbreviationView::slotDeleteAbbreviation() { - QList selectedList = selectedItems(); - if(selectedList.count() == 0) { - return; - } - QTreeWidgetItem *item = selectedList.first(); - QString abbreviationText = item->text(ALVabbrev); - QString abbreviationExpansion = item->text(ALVexpansion); - QString message = i18n("Delete the abbreviation '%1'?", abbreviationText); - if(KMessageBox::questionYesNo(this, - "
" + message + "
", - i18n("Delete Abbreviation") ) == KMessageBox::Yes) { - QString s = abbreviationText + '=' + abbreviationExpansion; - } - m_abbreviationManager->removeLocalAbbreviation(abbreviationText); + QList selectedList = selectedItems(); + if(selectedList.count() == 0) { + return; + } + QTreeWidgetItem *item = selectedList.first(); + QString abbreviationText = item->text(ALVabbrev); + QString abbreviationExpansion = item->text(ALVexpansion); + QString message = i18n("Delete the abbreviation '%1'?", abbreviationText); + if(KMessageBox::questionYesNo(this, + "
" + message + "
", + i18n("Delete Abbreviation") ) == KMessageBox::Yes) { + QString s = abbreviationText + '=' + abbreviationExpansion; + } + m_abbreviationManager->removeLocalAbbreviation(abbreviationText); } } diff --git a/src/widgets/abbreviationview.h b/src/widgets/abbreviationview.h index 7a899b36..77466da4 100644 --- a/src/widgets/abbreviationview.h +++ b/src/widgets/abbreviationview.h @@ -1,60 +1,62 @@ /**************************************************************************************** begin : Feb 24 2007 copyright : 2007 by Holger Danielsson (holger.danielsson@versanet.de) 2008 - 2009 by Michel Ludwig (michel.ludwig@kdemail.net) ****************************************************************************************/ /*************************************************************************** * * * 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. * * * ***************************************************************************/ #ifndef ABBREVIATIONVIEW_H #define ABBREVIATIONVIEW_H #include #include #include //////////////////// KlistView for abbreviations //////////////////// -namespace KileAbbreviation { class Manager; } +namespace KileAbbreviation { +class Manager; +} namespace KileWidget { class AbbreviationView : public QTreeWidget { - Q_OBJECT + Q_OBJECT public: - enum {ALVabbrev = 0, ALVlocal = 1, ALVexpansion = 2}; - enum {ALVnone = 0, ALVadd = 1, ALVedit = 2, ALVdelete = 3}; + enum {ALVabbrev = 0, ALVlocal = 1, ALVexpansion = 2}; + enum {ALVnone = 0, ALVadd = 1, ALVedit = 2, ALVdelete = 3}; - AbbreviationView(KileAbbreviation::Manager *manager, QWidget *parent = Q_NULLPTR); - ~AbbreviationView(); + AbbreviationView(KileAbbreviation::Manager *manager, QWidget *parent = Q_NULLPTR); + ~AbbreviationView(); - bool findAbbreviation(const QString &abbrev); + bool findAbbreviation(const QString &abbrev); Q_SIGNALS: - void sendText(const QString &text); - + void sendText(const QString &text); + private Q_SLOTS: - void updateAbbreviations(); - void slotItemClicked(QTreeWidgetItem *item, int column); - void slotCustomContextMenuRequested(const QPoint& p); - void slotAddAbbreviation(); - void slotChangeAbbreviation(); - void slotDeleteAbbreviation(); + void updateAbbreviations(); + void slotItemClicked(QTreeWidgetItem *item, int column); + void slotCustomContextMenuRequested(const QPoint& p); + void slotAddAbbreviation(); + void slotChangeAbbreviation(); + void slotDeleteAbbreviation(); private: - KileAbbreviation::Manager *m_abbreviationManager; + KileAbbreviation::Manager *m_abbreviationManager; }; } #endif diff --git a/src/widgets/appearanceconfigwidget.cpp b/src/widgets/appearanceconfigwidget.cpp index 272c554b..1dfd122a 100644 --- a/src/widgets/appearanceconfigwidget.cpp +++ b/src/widgets/appearanceconfigwidget.cpp @@ -1,37 +1,37 @@ /************************************************************************** * Copyright (C) 2011-2012 by Michel Ludwig (michel.ludwig@kdemail.net) * ***************************************************************************/ /************************************************************************** * * * 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. * * * ***************************************************************************/ #include "appearanceconfigwidget.h" #include KileWidgetAppearanceConfig::KileWidgetAppearanceConfig(KConfig *config, QWidget *parent) - : QWidget(parent), - m_config(config) + : QWidget(parent), + m_config(config) { - setupUi(this); + setupUi(this); } KileWidgetAppearanceConfig::~KileWidgetAppearanceConfig() { } void KileWidgetAppearanceConfig::readConfig() { } void KileWidgetAppearanceConfig::writeConfig() { } diff --git a/src/widgets/appearanceconfigwidget.h b/src/widgets/appearanceconfigwidget.h index 5992fd2b..70b03254 100644 --- a/src/widgets/appearanceconfigwidget.h +++ b/src/widgets/appearanceconfigwidget.h @@ -1,38 +1,38 @@ /************************************************************************** * Copyright (C) 2011 by Michel Ludwig (michel.ludwig@kdemail.net) * ***************************************************************************/ /************************************************************************** * * * 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. * * * ***************************************************************************/ #ifndef APPEARANCECONFIGWIDGET_H #define APPEARANCECONFIGWIDGET_H #include #include #include "ui_appearanceconfigwidget.h" class KileWidgetAppearanceConfig : public QWidget, public Ui::KileWidgetAppearanceConfig { - Q_OBJECT + Q_OBJECT - public: - KileWidgetAppearanceConfig(KConfig *config, QWidget *parent = Q_NULLPTR); - ~KileWidgetAppearanceConfig(); +public: + KileWidgetAppearanceConfig(KConfig *config, QWidget *parent = Q_NULLPTR); + ~KileWidgetAppearanceConfig(); - void readConfig(); - void writeConfig(); + void readConfig(); + void writeConfig(); - protected: - KConfig *m_config; +protected: + KConfig *m_config; }; #endif diff --git a/src/widgets/categorycombobox.cpp b/src/widgets/categorycombobox.cpp index ca2fb2a6..92027a39 100644 --- a/src/widgets/categorycombobox.cpp +++ b/src/widgets/categorycombobox.cpp @@ -1,89 +1,89 @@ /*************************************************************************** date : Dec 23 2007 version : 0.22 copyright : (C) 2004 by Mathias Soeken email : msoeken@tzi.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. * * * ***************************************************************************/ #include "categorycombobox.h" #include #include #include #include #include namespace KileWidget { class CategoryComboBoxDelegate : public QItemDelegate { - public: - void paint(QPainter *painter, const QStyleOptionViewItem& option, const QModelIndex& index) const { - bool category = index.model()->data(index, KileWidget::CategoryComboBox::Category).toBool(); - - if (category) { - painter->setPen(Qt::gray); - painter->drawLine(option.rect.x(), option.rect.y() + (option.rect.height() / 2), option.rect.x() + 4, option.rect.y() + (option.rect.height() / 2)); - - QFont newFont = painter->font(); - newFont.setPointSize(8); - painter->setFont(newFont); - - QRect boundingRect; - painter->drawText(QRect(option.rect.x() + 5, option.rect.y(), option.rect.width() - 5, option.rect.height()), Qt::AlignLeft | Qt::AlignVCenter, index.model()->data(index, Qt::DisplayRole).toString(), &boundingRect); - - painter->drawLine(boundingRect.right() + 1, option.rect.y() + (option.rect.height() / 2), option.rect.right(), option.rect.y() + (option.rect.height() / 2)); - } else { - QItemDelegate::paint(painter, option, index); - } - } +public: + void paint(QPainter *painter, const QStyleOptionViewItem& option, const QModelIndex& index) const { + bool category = index.model()->data(index, KileWidget::CategoryComboBox::Category).toBool(); + + if (category) { + painter->setPen(Qt::gray); + painter->drawLine(option.rect.x(), option.rect.y() + (option.rect.height() / 2), option.rect.x() + 4, option.rect.y() + (option.rect.height() / 2)); + + QFont newFont = painter->font(); + newFont.setPointSize(8); + painter->setFont(newFont); + + QRect boundingRect; + painter->drawText(QRect(option.rect.x() + 5, option.rect.y(), option.rect.width() - 5, option.rect.height()), Qt::AlignLeft | Qt::AlignVCenter, index.model()->data(index, Qt::DisplayRole).toString(), &boundingRect); + + painter->drawLine(boundingRect.right() + 1, option.rect.y() + (option.rect.height() / 2), option.rect.right(), option.rect.y() + (option.rect.height() / 2)); + } else { + QItemDelegate::paint(painter, option, index); + } + } }; CategoryComboBox::CategoryComboBox(QWidget *parent) : KComboBox(parent) { - setItemDelegate(new KileWidget::CategoryComboBoxDelegate()); - //view()->setAlternatingRowColors( true ); + setItemDelegate(new KileWidget::CategoryComboBoxDelegate()); + //view()->setAlternatingRowColors( true ); } CategoryComboBox::CategoryComboBox(bool rw, QWidget *parent) : KComboBox(rw, parent) { - setItemDelegate(new KileWidget::CategoryComboBoxDelegate()); - //view()->setAlternatingRowColors( true ); + setItemDelegate(new KileWidget::CategoryComboBoxDelegate()); + //view()->setAlternatingRowColors( true ); } CategoryComboBox::~CategoryComboBox() { } void CategoryComboBox::addCategoryItem(const QString &text) { - addItem(text); + addItem(text); - // row of the item - int row = count() - 1; + // row of the item + int row = count() - 1; - QStandardItemModel *pModel = qobject_cast(model()); - if (pModel) { - QStandardItem *item = pModel->item(row, 0); - if (item) { - item->setData(true, KileWidget::CategoryComboBox::Category); + QStandardItemModel *pModel = qobject_cast(model()); + if (pModel) { + QStandardItem *item = pModel->item(row, 0); + if (item) { + item->setData(true, KileWidget::CategoryComboBox::Category); - // make the item unselectable - item->setFlags(0); - } - } + // make the item unselectable + item->setFlags(0); + } + } - if (currentIndex() == row) { - setCurrentIndex(-1); - } + if (currentIndex() == row) { + setCurrentIndex(-1); + } } } // namespace KileWidget diff --git a/src/widgets/categorycombobox.h b/src/widgets/categorycombobox.h index 4a3950a2..8e89297f 100644 --- a/src/widgets/categorycombobox.h +++ b/src/widgets/categorycombobox.h @@ -1,42 +1,42 @@ /*************************************************************************** date : Dec 23 2007 version : 0.22 copyright : (C) 2004 by Mathias Soeken email : msoeken@tzi.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. * * * ***************************************************************************/ #ifndef CATEGORYCOMBOBOX_H #define CATEGORYCOMBOBOX_H #include namespace KileWidget { class CategoryComboBox : public KComboBox { - public: - enum { - Category = Qt::UserRole + 1 - }; +public: + enum { + Category = Qt::UserRole + 1 + }; - public: - explicit CategoryComboBox(QWidget *parent = 0); - explicit CategoryComboBox(bool rw, QWidget *parent = 0); +public: + explicit CategoryComboBox(QWidget *parent = 0); + explicit CategoryComboBox(bool rw, QWidget *parent = 0); - virtual ~CategoryComboBox(); + virtual ~CategoryComboBox(); - public: - void addCategoryItem(const QString &text); +public: + void addCategoryItem(const QString &text); }; } #endif diff --git a/src/widgets/codecompletionconfigwidget.cpp b/src/widgets/codecompletionconfigwidget.cpp index 7e1d5db6..3ef4f52b 100644 --- a/src/widgets/codecompletionconfigwidget.cpp +++ b/src/widgets/codecompletionconfigwidget.cpp @@ -1,403 +1,403 @@ /************************************************************************************************ Copyright (C) 2004-2007 by Holger Danielsson (holger.danielsson@versanet.de) 2009-2010 by Michel Ludwig (michel.ludwig@kdemail.net) ************************************************************************************************/ /*************************************************************************** * * * 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. * * * ***************************************************************************/ #include "widgets/codecompletionconfigwidget.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "dialogs/listselector.h" #include "codecompletion.h" #include "errorhandler.h" #include "kileconfig.h" #include "kiledebug.h" #include "kiletool_enums.h" CodeCompletionConfigWidget::CodeCompletionConfigWidget(KConfig *config, KileErrorHandler *errorHandler, QWidget *parent, const char *name) - : QWidget(parent), m_config(config), m_errorHandler(errorHandler), m_configChanged(false) + : QWidget(parent), m_config(config), m_errorHandler(errorHandler), m_configChanged(false) { - setObjectName(name); - setupUi(this); - - // add three pages: Tex/Latex, Dictionary, Abbreviation - addPage(m_tabWidget, TexPage, i18n("TeX/LaTeX"), "tex"); - addPage(m_tabWidget, DictionaryPage, i18n("Dictionary"), "dictionary"); - addPage(m_tabWidget, AbbreviationPage, i18n("Abbreviation"), "abbreviation"); - - cb_setcursor->setWhatsThis(i18n("Try to place the cursor.")); - cb_setbullets->setWhatsThis(i18n("Insert bullets where the user must input data.")); - cb_closeenv->setWhatsThis(i18n("Also close an environment when an opening command is inserted.")); - cb_autocomplete->setWhatsThis(i18n("Directional or popup-based completion of the TeX/LaTeX commands that are contained in the selected completion files.")); - sp_latexthreshold->setWhatsThis(i18n("Automatically show a completion list of TeX/LaTeX commands when the word has this length.")); - - cb_showabbrevview->setWhatsThis(i18n("Show abbreviations of the selected completion files in the sidebar")); - cb_autocompleteabbrev->setWhatsThis(i18n("Directional or popup-based completion of abbreviations that are contained in the selected completion files.")); - cb_showcwlview->setWhatsThis(i18n("Show LaTeX commands of the selected completion files in the sidebar")); - - connect(m_tabWidget, SIGNAL(currentChanged(int)), this, SLOT(showPage(int))); - connect(m_addFileButton, SIGNAL(clicked()), this, SLOT(addClicked())); - connect(m_removeFileButton, SIGNAL(clicked()), this, SLOT(removeClicked())); - - // find resource directories for cwl files - QPair p = KileCodeCompletion::Manager::getCwlBaseDirs(); - m_localCwlDir = p.first; - m_globalCwlDir = p.second; - - // Watch for changes in the directories - m_dirWatcher = new KDirWatch(this); - if (m_dirWatcher) { - m_dirWatcher->addDir(m_localCwlDir, KDirWatch::WatchSubDirs | KDirWatch::WatchFiles); - m_dirWatcher->addDir(m_globalCwlDir, KDirWatch::WatchSubDirs | KDirWatch::WatchFiles); - connect(m_dirWatcher, SIGNAL(created(const QString&)), this, SLOT(updateCompletionFilesTab(const QString&))); - connect(m_dirWatcher, SIGNAL(deleted(const QString&)), this, SLOT(updateCompletionFilesTab(const QString&))); - } + setObjectName(name); + setupUi(this); + + // add three pages: Tex/Latex, Dictionary, Abbreviation + addPage(m_tabWidget, TexPage, i18n("TeX/LaTeX"), "tex"); + addPage(m_tabWidget, DictionaryPage, i18n("Dictionary"), "dictionary"); + addPage(m_tabWidget, AbbreviationPage, i18n("Abbreviation"), "abbreviation"); + + cb_setcursor->setWhatsThis(i18n("Try to place the cursor.")); + cb_setbullets->setWhatsThis(i18n("Insert bullets where the user must input data.")); + cb_closeenv->setWhatsThis(i18n("Also close an environment when an opening command is inserted.")); + cb_autocomplete->setWhatsThis(i18n("Directional or popup-based completion of the TeX/LaTeX commands that are contained in the selected completion files.")); + sp_latexthreshold->setWhatsThis(i18n("Automatically show a completion list of TeX/LaTeX commands when the word has this length.")); + + cb_showabbrevview->setWhatsThis(i18n("Show abbreviations of the selected completion files in the sidebar")); + cb_autocompleteabbrev->setWhatsThis(i18n("Directional or popup-based completion of abbreviations that are contained in the selected completion files.")); + cb_showcwlview->setWhatsThis(i18n("Show LaTeX commands of the selected completion files in the sidebar")); + + connect(m_tabWidget, SIGNAL(currentChanged(int)), this, SLOT(showPage(int))); + connect(m_addFileButton, SIGNAL(clicked()), this, SLOT(addClicked())); + connect(m_removeFileButton, SIGNAL(clicked()), this, SLOT(removeClicked())); + + // find resource directories for cwl files + QPair p = KileCodeCompletion::Manager::getCwlBaseDirs(); + m_localCwlDir = p.first; + m_globalCwlDir = p.second; + + // Watch for changes in the directories + m_dirWatcher = new KDirWatch(this); + if (m_dirWatcher) { + m_dirWatcher->addDir(m_localCwlDir, KDirWatch::WatchSubDirs | KDirWatch::WatchFiles); + m_dirWatcher->addDir(m_globalCwlDir, KDirWatch::WatchSubDirs | KDirWatch::WatchFiles); + connect(m_dirWatcher, SIGNAL(created(const QString&)), this, SLOT(updateCompletionFilesTab(const QString&))); + connect(m_dirWatcher, SIGNAL(deleted(const QString&)), this, SLOT(updateCompletionFilesTab(const QString&))); + } } CodeCompletionConfigWidget::~CodeCompletionConfigWidget() { } void CodeCompletionConfigWidget::addPage(QTabWidget *tab, CompletionPage page, const QString &title, const QString &dirname) { - m_page[page] = new QWidget(tab); + m_page[page] = new QWidget(tab); - m_listview[page] = new QTreeWidget(m_page[page]); - m_listview[page]->setHeaderLabels(QStringList() << i18n("Completion Files") - << i18n("Local File")); - m_listview[page]->setAllColumnsShowFocus(true); - m_listview[page]->setRootIsDecorated(false); - m_listview[page]->setSelectionMode(QAbstractItemView::ExtendedSelection); + m_listview[page] = new QTreeWidget(m_page[page]); + m_listview[page]->setHeaderLabels(QStringList() << i18n("Completion Files") + << i18n("Local File")); + m_listview[page]->setAllColumnsShowFocus(true); + m_listview[page]->setRootIsDecorated(false); + m_listview[page]->setSelectionMode(QAbstractItemView::ExtendedSelection); - QGridLayout *grid = new QGridLayout(); - grid->setMargin(0); + QGridLayout *grid = new QGridLayout(); + grid->setMargin(0); //TODO PORT QT5 grid->setSpacing(QDialog::spacingHint()); - m_page[page]->setLayout(grid); - grid->addWidget(m_listview[page], 0, 0); + m_page[page]->setLayout(grid); + grid->addWidget(m_listview[page], 0, 0); - // add Tab - tab->addTab(m_page[page], title); + // add Tab + tab->addTab(m_page[page], title); - // remember directory name - m_dirname << dirname; + // remember directory name + m_dirname << dirname; - connect(m_listview[page], SIGNAL(itemSelectionChanged()), - this, SLOT(slotSelectionChanged())); + connect(m_listview[page], SIGNAL(itemSelectionChanged()), + this, SLOT(slotSelectionChanged())); } //////////////////// read/write configuration //////////////////// void CodeCompletionConfigWidget::readConfig(void) { - // read selected and deselected filenames with wordlists - m_wordlist[TexPage] = KileConfig::completeTex(); - m_wordlist[DictionaryPage] = KileConfig::completeDict(); - m_wordlist[AbbreviationPage] = KileConfig::completeAbbrev(); - - // set checkbox status - cb_setcursor->setChecked(KileConfig::completeCursor()); - cb_setbullets->setChecked(KileConfig::completeBullets()); - cb_closeenv->setChecked(KileConfig::completeCloseEnv()); - cb_showabbrevview->setChecked(KileConfig::completeShowAbbrev()); - cb_showcwlview->setChecked(KileConfig::showCwlCommands()); - - cb_autocomplete->setChecked(KileConfig::completeAuto()); - cb_autocompleteabbrev->setChecked(KileConfig::completeAutoAbbrev()); - - sp_latexthreshold->setValue(KileConfig::completeAutoThreshold()); - - // insert filenames into listview - for (uint i = TexPage; i < NumPages; ++i) { - setListviewEntries(CompletionPage(i)); - } + // read selected and deselected filenames with wordlists + m_wordlist[TexPage] = KileConfig::completeTex(); + m_wordlist[DictionaryPage] = KileConfig::completeDict(); + m_wordlist[AbbreviationPage] = KileConfig::completeAbbrev(); + + // set checkbox status + cb_setcursor->setChecked(KileConfig::completeCursor()); + cb_setbullets->setChecked(KileConfig::completeBullets()); + cb_closeenv->setChecked(KileConfig::completeCloseEnv()); + cb_showabbrevview->setChecked(KileConfig::completeShowAbbrev()); + cb_showcwlview->setChecked(KileConfig::showCwlCommands()); + + cb_autocomplete->setChecked(KileConfig::completeAuto()); + cb_autocompleteabbrev->setChecked(KileConfig::completeAutoAbbrev()); + + sp_latexthreshold->setValue(KileConfig::completeAutoThreshold()); + + // insert filenames into listview + for (uint i = TexPage; i < NumPages; ++i) { + setListviewEntries(CompletionPage(i)); + } } void CodeCompletionConfigWidget::writeConfig(void) { - // get listview entries - for (uint i = TexPage; i < NumPages; ++i) { - m_configChanged |= getListviewEntries(CompletionPage(i)); - } - - // Konfigurationslisten abspeichern - KileConfig::setCompleteTex(m_wordlist[TexPage]); - KileConfig::setCompleteDict(m_wordlist[DictionaryPage]); - KileConfig::setCompleteAbbrev(m_wordlist[AbbreviationPage]); - - // save checkbox status - KileConfig::setCompleteCursor(cb_setcursor->isChecked()); - KileConfig::setCompleteBullets(cb_setbullets->isChecked()); - KileConfig::setCompleteCloseEnv(cb_closeenv->isChecked()); - KileConfig::setCompleteShowAbbrev(cb_showabbrevview->isChecked()); - KileConfig::setShowCwlCommands(cb_showcwlview->isChecked()); - - // read autocompletion settings - bool autoModeLatex = cb_autocomplete->isChecked(); - bool autoModeAbbrev = cb_autocompleteabbrev->isChecked(); - - // save settings for Kile autocompletion modes - KileConfig::setCompleteAuto(autoModeLatex); - KileConfig::setCompleteAutoAbbrev(autoModeAbbrev); - KileConfig::setCompleteAutoThreshold(sp_latexthreshold->value()); - - // save changed wordlists? - KileConfig::setCompleteChangedLists(m_configChanged); + // get listview entries + for (uint i = TexPage; i < NumPages; ++i) { + m_configChanged |= getListviewEntries(CompletionPage(i)); + } + + // Konfigurationslisten abspeichern + KileConfig::setCompleteTex(m_wordlist[TexPage]); + KileConfig::setCompleteDict(m_wordlist[DictionaryPage]); + KileConfig::setCompleteAbbrev(m_wordlist[AbbreviationPage]); + + // save checkbox status + KileConfig::setCompleteCursor(cb_setcursor->isChecked()); + KileConfig::setCompleteBullets(cb_setbullets->isChecked()); + KileConfig::setCompleteCloseEnv(cb_closeenv->isChecked()); + KileConfig::setCompleteShowAbbrev(cb_showabbrevview->isChecked()); + KileConfig::setShowCwlCommands(cb_showcwlview->isChecked()); + + // read autocompletion settings + bool autoModeLatex = cb_autocomplete->isChecked(); + bool autoModeAbbrev = cb_autocompleteabbrev->isChecked(); + + // save settings for Kile autocompletion modes + KileConfig::setCompleteAuto(autoModeLatex); + KileConfig::setCompleteAutoAbbrev(autoModeAbbrev); + KileConfig::setCompleteAutoThreshold(sp_latexthreshold->value()); + + // save changed wordlists? + KileConfig::setCompleteChangedLists(m_configChanged); } //////////////////// listview //////////////////// // ListView fr den Konfigurationsdialog einstellen void CodeCompletionConfigWidget::setListviewEntries(CompletionPage page) { - QString listname = m_dirname[page]; - QString localdir = m_localCwlDir + listname + '/'; - QString globaldir = m_globalCwlDir + listname + '/'; - - // Daten aus der Konfigurationsliste in das ListView-Widget eintragen - m_listview[page]->setUpdatesEnabled(false); - m_listview[page]->clear(); - QStringList::ConstIterator it; - for (it = m_wordlist[page].constBegin(); it != m_wordlist[page].constEnd(); ++it) { - QString basename = (*it).right((*it).length() - 2); - bool localExists = QFileInfo(localdir + basename + ".cwl").exists(); - - QTreeWidgetItem *item = new QTreeWidgetItem(m_listview[page], QStringList(basename)); - item->setFlags(item->flags() | Qt::ItemIsUserCheckable); - if (localExists) { - item->setCheckState(0, (*it).at(0) == '1' ? Qt::Checked : Qt::Unchecked); - item->setText(1, i18n("yes")); - } - else { - if (QFileInfo(globaldir + basename + ".cwl").exists()) { - item->setCheckState(0, (*it).at(0) == '1' ? Qt::Checked : Qt::Unchecked); - item->setText(1, i18n("no")); - } - else { - item->setCheckState(0, Qt::Unchecked); - item->setText(1, i18n("File not found")); - } - } - } - - updateColumnWidth(m_listview[page]); - m_listview[page]->setUpdatesEnabled(true); + QString listname = m_dirname[page]; + QString localdir = m_localCwlDir + listname + '/'; + QString globaldir = m_globalCwlDir + listname + '/'; + + // Daten aus der Konfigurationsliste in das ListView-Widget eintragen + m_listview[page]->setUpdatesEnabled(false); + m_listview[page]->clear(); + QStringList::ConstIterator it; + for (it = m_wordlist[page].constBegin(); it != m_wordlist[page].constEnd(); ++it) { + QString basename = (*it).right((*it).length() - 2); + bool localExists = QFileInfo(localdir + basename + ".cwl").exists(); + + QTreeWidgetItem *item = new QTreeWidgetItem(m_listview[page], QStringList(basename)); + item->setFlags(item->flags() | Qt::ItemIsUserCheckable); + if (localExists) { + item->setCheckState(0, (*it).at(0) == '1' ? Qt::Checked : Qt::Unchecked); + item->setText(1, i18n("yes")); + } + else { + if (QFileInfo(globaldir + basename + ".cwl").exists()) { + item->setCheckState(0, (*it).at(0) == '1' ? Qt::Checked : Qt::Unchecked); + item->setText(1, i18n("no")); + } + else { + item->setCheckState(0, Qt::Unchecked); + item->setText(1, i18n("File not found")); + } + } + } + + updateColumnWidth(m_listview[page]); + m_listview[page]->setUpdatesEnabled(true); } void CodeCompletionConfigWidget::updateColumnWidth(QTreeWidget *listview) { - listview->resizeColumnToContents(0); - listview->resizeColumnToContents(1); - listview->setColumnWidth(0, listview->columnWidth(0) + 60); + listview->resizeColumnToContents(0); + listview->resizeColumnToContents(1); + listview->setColumnWidth(0, listview->columnWidth(0) + 60); } bool CodeCompletionConfigWidget::getListviewEntries(CompletionPage page) { - KILE_DEBUG_MAIN << "===bool CodeCompletionConfigWidget::getListviewEntries(CompletionPage" << page << ")"; - - bool changed = false; - - // count number of entries - int n = m_listview[page]->topLevelItemCount(); - - // there are changes if this number has changed - if(n != m_wordlist[page].count()) { - changed = true; - } - - // clear all stringlist with files, if there are no entries - if (n == 0) { - m_wordlist[page].clear(); - return changed; - } - - // now check all entries if they have changed - QStringList newfiles; - int index = 0; - QTreeWidgetItemIterator it(m_listview[page]); - while (*it) { - QString s = ((*it)->checkState(0) == Qt::Checked) ? "1-" : "0-"; - s += (*it)->text(0); - newfiles.append(s); - - // check for a change - if (index >= m_wordlist[page].count() || m_wordlist[page][index] != s) { - changed = true; - } - - // go on - ++it; - index++; - } - - // only update if there are changes - if (changed) { - m_wordlist[page] = newfiles; - } - - return changed; + KILE_DEBUG_MAIN << "===bool CodeCompletionConfigWidget::getListviewEntries(CompletionPage" << page << ")"; + + bool changed = false; + + // count number of entries + int n = m_listview[page]->topLevelItemCount(); + + // there are changes if this number has changed + if(n != m_wordlist[page].count()) { + changed = true; + } + + // clear all stringlist with files, if there are no entries + if (n == 0) { + m_wordlist[page].clear(); + return changed; + } + + // now check all entries if they have changed + QStringList newfiles; + int index = 0; + QTreeWidgetItemIterator it(m_listview[page]); + while (*it) { + QString s = ((*it)->checkState(0) == Qt::Checked) ? "1-" : "0-"; + s += (*it)->text(0); + newfiles.append(s); + + // check for a change + if (index >= m_wordlist[page].count() || m_wordlist[page][index] != s) { + changed = true; + } + + // go on + ++it; + index++; + } + + // only update if there are changes + if (changed) { + m_wordlist[page] = newfiles; + } + + return changed; } QTreeWidgetItem* CodeCompletionConfigWidget::getListviewEntry(QTreeWidget *listview, const QString &filename) { - QList items = listview->findItems(filename, Qt::MatchExactly); - if (items.empty()) { - return Q_NULLPTR; - } - else { - if (items.count() > 1) { - m_errorHandler->printMessage(KileTool::Info, i18n("Wordlist '%1' contains duplicate entries.", filename), i18n("Completion")); - } - return items.first(); - } + QList items = listview->findItems(filename, Qt::MatchExactly); + if (items.empty()) { + return Q_NULLPTR; + } + else { + if (items.count() > 1) { + m_errorHandler->printMessage(KileTool::Info, i18n("Wordlist '%1' contains duplicate entries.", filename), i18n("Completion")); + } + return items.first(); + } } //////////////////// tabpages parameter //////////////////// QTreeWidget *CodeCompletionConfigWidget::getListview(QWidget *page) { - for (uint i = TexPage; i < NumPages; ++i) { - if (page == m_page[i]) { - return m_listview[i]; - } - } - return 0; + for (uint i = TexPage; i < NumPages; ++i) { + if (page == m_page[i]) { + return m_listview[i]; + } + } + return 0; } QString CodeCompletionConfigWidget::getListname(QWidget *page) { - for (uint i = TexPage; i < NumPages; ++i) { - if(page == m_page[i]) { - return m_dirname[i]; - } - } - return QString(); + for (uint i = TexPage; i < NumPages; ++i) { + if(page == m_page[i]) { + return m_dirname[i]; + } + } + return QString(); } //////////////////// shwo tabpages //////////////////// void CodeCompletionConfigWidget::showPage(QWidget *page) { - QTreeWidget *listview = getListview(page); - if(listview) { - m_removeFileButton->setEnabled(listview->selectedItems().count() > 0); - } + QTreeWidget *listview = getListview(page); + if(listview) { + m_removeFileButton->setEnabled(listview->selectedItems().count() > 0); + } } void CodeCompletionConfigWidget::showPage(int index) { - showPage(m_tabWidget->widget(index)); + showPage(m_tabWidget->widget(index)); } //////////////////// add/remove new wordlists //////////////////// void CodeCompletionConfigWidget::addClicked() { - // determine current subdirectory for current tab page - QString listname = getListname(m_tabWidget->currentWidget()); - QString localPath = m_localCwlDir + listname, globalPath = m_globalCwlDir + listname; - - // dialog to add cwl files - ManageCompletionFilesDialog dlg(i18n("Completion Files"), localPath, globalPath, this); - - if (dlg.exec()) { - QSet filenames = dlg.selected(); - if (!filenames.isEmpty()) { - QTreeWidget *listview = getListview(m_tabWidget->currentWidget()); // get current page - for (QSet::ConstIterator it = filenames.constBegin(); it != filenames.constEnd(); ++it) { - QString filename = *it; - // Reload map of files. - QMap filemap = KileCodeCompletion::Manager::getAllCwlFiles(localPath, globalPath); - - // Could we accept the wordlist? - QFileInfo fi(filemap[filename]); - if (!filename.isEmpty() && fi.exists() && fi.isReadable()) { - QString basename = filename.left(filename.length() - 4); - - // Check if this entry already exists. - QTreeWidgetItem* entry = Q_NULLPTR; - if ((entry = getListviewEntry(listview, basename)) == Q_NULLPTR) { - // A new entry has to be created - entry = new QTreeWidgetItem(listview, QStringList(basename)); - } - - entry->setFlags(entry->flags() | Qt::ItemIsUserCheckable); - entry->setCheckState(0, Qt::Checked); - entry->setSelected(true); - if (filemap[filename].left(m_localCwlDir.length()) == m_localCwlDir) { - entry->setText(1, i18n("yes")); - } - else { - entry->setText(1, i18n("no")); - } - } - } - updateColumnWidth(listview); - } - } + // determine current subdirectory for current tab page + QString listname = getListname(m_tabWidget->currentWidget()); + QString localPath = m_localCwlDir + listname, globalPath = m_globalCwlDir + listname; + + // dialog to add cwl files + ManageCompletionFilesDialog dlg(i18n("Completion Files"), localPath, globalPath, this); + + if (dlg.exec()) { + QSet filenames = dlg.selected(); + if (!filenames.isEmpty()) { + QTreeWidget *listview = getListview(m_tabWidget->currentWidget()); // get current page + for (QSet::ConstIterator it = filenames.constBegin(); it != filenames.constEnd(); ++it) { + QString filename = *it; + // Reload map of files. + QMap filemap = KileCodeCompletion::Manager::getAllCwlFiles(localPath, globalPath); + + // Could we accept the wordlist? + QFileInfo fi(filemap[filename]); + if (!filename.isEmpty() && fi.exists() && fi.isReadable()) { + QString basename = filename.left(filename.length() - 4); + + // Check if this entry already exists. + QTreeWidgetItem* entry = Q_NULLPTR; + if ((entry = getListviewEntry(listview, basename)) == Q_NULLPTR) { + // A new entry has to be created + entry = new QTreeWidgetItem(listview, QStringList(basename)); + } + + entry->setFlags(entry->flags() | Qt::ItemIsUserCheckable); + entry->setCheckState(0, Qt::Checked); + entry->setSelected(true); + if (filemap[filename].left(m_localCwlDir.length()) == m_localCwlDir) { + entry->setText(1, i18n("yes")); + } + else { + entry->setText(1, i18n("no")); + } + } + } + updateColumnWidth(listview); + } + } } // delete a selected entry void CodeCompletionConfigWidget::removeClicked() { - QWidget *page = m_tabWidget->currentWidget(); - QTreeWidget *list = getListview(page); // determine page + QWidget *page = m_tabWidget->currentWidget(); + QTreeWidget *list = getListview(page); // determine page - foreach(QTreeWidgetItem *item, list->selectedItems()) { - delete item; - } + foreach(QTreeWidgetItem *item, list->selectedItems()) { + delete item; + } - showPage(page); + showPage(page); } void CodeCompletionConfigWidget::slotSelectionChanged() { - QTreeWidget *listview = getListview(m_tabWidget->currentWidget()); // get current page - m_removeFileButton->setEnabled(listview->selectedItems().count() > 0); + QTreeWidget *listview = getListview(m_tabWidget->currentWidget()); // get current page + m_removeFileButton->setEnabled(listview->selectedItems().count() > 0); } void CodeCompletionConfigWidget::updateCompletionFilesTab(const QString& path) { - int localLength = (path.startsWith(m_localCwlDir) ? m_localCwlDir.length() : m_globalCwlDir.length()); - // 'm_globalCwlDir' and 'm_localCwlDir' are guaranteed to end in '/' (see 'KileCodeCompletion::Manager::getCwlBaseDirs()') - QString dirname = path.mid(localLength, path.indexOf('/', localLength) - localLength); - - int dirnameIdx = m_dirname.indexOf(dirname); - if (dirnameIdx >= 0) { - m_configChanged |= getListviewEntries(CompletionPage(dirnameIdx)); - setListviewEntries(CompletionPage(dirnameIdx)); - } + int localLength = (path.startsWith(m_localCwlDir) ? m_localCwlDir.length() : m_globalCwlDir.length()); + // 'm_globalCwlDir' and 'm_localCwlDir' are guaranteed to end in '/' (see 'KileCodeCompletion::Manager::getCwlBaseDirs()') + QString dirname = path.mid(localLength, path.indexOf('/', localLength) - localLength); + + int dirnameIdx = m_dirname.indexOf(dirname); + if (dirnameIdx >= 0) { + m_configChanged |= getListviewEntries(CompletionPage(dirnameIdx)); + setListviewEntries(CompletionPage(dirnameIdx)); + } } diff --git a/src/widgets/codecompletionconfigwidget.h b/src/widgets/codecompletionconfigwidget.h index 017e7a7d..4f8ca1c1 100644 --- a/src/widgets/codecompletionconfigwidget.h +++ b/src/widgets/codecompletionconfigwidget.h @@ -1,80 +1,80 @@ /******************************************************************************** Copyright (C) 2004-2007 by Holger Danielsson (holger.danielsson@versanet.de) 2010 by Michel Ludwig (michel.ludwig@liverpool.ac.uk) ********************************************************************************/ /*************************************************************************** * * * 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. * * * ***************************************************************************/ #ifndef CODECOMPLETIONCONFIGWIDGET_H #define CODECOMPLETIONCONFIGWIDGET_H #include #include "ui_codecompletionconfigwidget.h" class QCheckBox; class QLabel; class QSpinBox; class QTabWidget; class QTreeWidget; class QTreeWidgetItem; class KConfig; class QPushButton; class QTabWidget; class KDirWatch; class KileErrorHandler; class CodeCompletionConfigWidget : public QWidget, public Ui::KileWidgetCodeCompletionConfig { - Q_OBJECT - public: - CodeCompletionConfigWidget(KConfig *config, KileErrorHandler *errorHandler, QWidget *parent = Q_NULLPTR, const char *name = Q_NULLPTR); - ~CodeCompletionConfigWidget(); - - void readConfig(void); - void writeConfig(void); - - private: - enum CompletionPage { TexPage = 0, DictionaryPage = 1, AbbreviationPage = 2, NumPages = 3 }; - - KConfig *m_config; - KileErrorHandler *m_errorHandler; - - // tabs, views, pages, wordlists - QTreeWidget *m_listview[NumPages]; - QWidget *m_page[NumPages]; - QStringList m_wordlist[NumPages]; - QStringList m_dirname; - - QTreeWidget *getListview(QWidget *page); - QString getListname(QWidget *page); - void addPage(QTabWidget *tab, CompletionPage page, const QString &title, const QString &dirname); - - void setListviewEntries(CompletionPage page); - bool getListviewEntries(CompletionPage page); - QTreeWidgetItem* getListviewEntry(QTreeWidget *listview, const QString &filename); - void updateColumnWidth(QTreeWidget *listview); - - bool m_configChanged; - QString m_localCwlDir, m_globalCwlDir; - KDirWatch *m_dirWatcher; - - private Q_SLOTS: - void showPage(QWidget *page); - void showPage(int index); - void addClicked(); - void removeClicked(); - void slotSelectionChanged(); - void updateCompletionFilesTab(const QString& path); + Q_OBJECT +public: + CodeCompletionConfigWidget(KConfig *config, KileErrorHandler *errorHandler, QWidget *parent = Q_NULLPTR, const char *name = Q_NULLPTR); + ~CodeCompletionConfigWidget(); + + void readConfig(void); + void writeConfig(void); + +private: + enum CompletionPage { TexPage = 0, DictionaryPage = 1, AbbreviationPage = 2, NumPages = 3 }; + + KConfig *m_config; + KileErrorHandler *m_errorHandler; + + // tabs, views, pages, wordlists + QTreeWidget *m_listview[NumPages]; + QWidget *m_page[NumPages]; + QStringList m_wordlist[NumPages]; + QStringList m_dirname; + + QTreeWidget *getListview(QWidget *page); + QString getListname(QWidget *page); + void addPage(QTabWidget *tab, CompletionPage page, const QString &title, const QString &dirname); + + void setListviewEntries(CompletionPage page); + bool getListviewEntries(CompletionPage page); + QTreeWidgetItem* getListviewEntry(QTreeWidget *listview, const QString &filename); + void updateColumnWidth(QTreeWidget *listview); + + bool m_configChanged; + QString m_localCwlDir, m_globalCwlDir; + KDirWatch *m_dirWatcher; + +private Q_SLOTS: + void showPage(QWidget *page); + void showPage(int index); + void addClicked(); + void removeClicked(); + void slotSelectionChanged(); + void updateCompletionFilesTab(const QString& path); }; #endif diff --git a/src/widgets/configcheckerwidget.cpp b/src/widgets/configcheckerwidget.cpp index fcf10720..4bde992b 100644 --- a/src/widgets/configcheckerwidget.cpp +++ b/src/widgets/configcheckerwidget.cpp @@ -1,40 +1,40 @@ /************************************************************************** * Copyright (C) 2007 by Michel Ludwig (michel.ludwig@kdemail.net) * ***************************************************************************/ /************************************************************************** * * * 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. * * * ***************************************************************************/ #include "widgets/configcheckerwidget.h" ConfigCheckerWidget::ConfigCheckerWidget(QWidget *parent) : QWidget(parent) { - setupUi(this); + setupUi(this); } ConfigCheckerWidget::~ConfigCheckerWidget() { } QProgressBar* ConfigCheckerWidget::progressBar() { - return m_progress; + return m_progress; } QLabel* ConfigCheckerWidget::label() { - return m_lbChecking; + return m_lbChecking; } QListWidget* ConfigCheckerWidget::listWidget() { - return m_lstResults; + return m_lstResults; } diff --git a/src/widgets/configcheckerwidget.h b/src/widgets/configcheckerwidget.h index c60c7c58..53878580 100644 --- a/src/widgets/configcheckerwidget.h +++ b/src/widgets/configcheckerwidget.h @@ -1,39 +1,39 @@ /************************************************************************** * Copyright (C) 2007 by Michel Ludwig (michel.ludwig@kdemail.net) * ***************************************************************************/ /************************************************************************** * * * 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. * * * ***************************************************************************/ #ifndef CONFIGCHECKERWIDGET_H #define CONFIGCHECKERWIDGET_H #include #include #include #include #include "ui_configcheckerwidget.h" class ConfigCheckerWidget : public QWidget, public Ui::ConfigCheckerWidget { - Q_OBJECT + Q_OBJECT - public: - ConfigCheckerWidget(QWidget *parent = 0); - ~ConfigCheckerWidget(); +public: + ConfigCheckerWidget(QWidget *parent = 0); + ~ConfigCheckerWidget(); - QProgressBar* progressBar(); - QLabel* label(); - QListWidget* listWidget(); + QProgressBar* progressBar(); + QLabel* label(); + QListWidget* listWidget(); }; #endif diff --git a/src/widgets/environmentconfigwidget.cpp b/src/widgets/environmentconfigwidget.cpp index 0ca457f5..f6a4c4d7 100644 --- a/src/widgets/environmentconfigwidget.cpp +++ b/src/widgets/environmentconfigwidget.cpp @@ -1,24 +1,24 @@ /************************************************************************** * Copyright (C) 2007 by Michel Ludwig (michel.ludwig@kdemail.net) * ***************************************************************************/ /************************************************************************** * * * 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. * * * ***************************************************************************/ #include "widgets/environmentconfigwidget.h" KileWidgetEnvironmentConfig::KileWidgetEnvironmentConfig(QWidget *parent) : QWidget(parent) { - setupUi(this); + setupUi(this); } KileWidgetEnvironmentConfig::~KileWidgetEnvironmentConfig() { } diff --git a/src/widgets/environmentconfigwidget.h b/src/widgets/environmentconfigwidget.h index 36e6f638..8c4e7fe8 100644 --- a/src/widgets/environmentconfigwidget.h +++ b/src/widgets/environmentconfigwidget.h @@ -1,30 +1,30 @@ /************************************************************************** * Copyright (C) 2007 by Michel Ludwig (michel.ludwig@kdemail.net) * ***************************************************************************/ /************************************************************************** * * * 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. * * * ***************************************************************************/ #ifndef ENVIRONMENTCONFIGWIDGET_H #define ENVIRONMENTCONFIGWIDGET_H #include #include "ui_environmentconfigwidget.h" class KileWidgetEnvironmentConfig : public QWidget, public Ui::KileWidgetEnvironmentConfig { - Q_OBJECT + Q_OBJECT - public: - KileWidgetEnvironmentConfig(QWidget *parent = 0); - ~KileWidgetEnvironmentConfig(); +public: + KileWidgetEnvironmentConfig(QWidget *parent = 0); + ~KileWidgetEnvironmentConfig(); }; #endif diff --git a/src/widgets/filebrowserwidget.cpp b/src/widgets/filebrowserwidget.cpp index 17e53238..d9b13a5c 100644 --- a/src/widgets/filebrowserwidget.cpp +++ b/src/widgets/filebrowserwidget.cpp @@ -1,188 +1,188 @@ /****************************************************************************************** begin : Wed Aug 14 2002 copyright : (C) 2003 by Jeroen Wijnhout (Jeroen.Wijnhout@kdemail.net) 2007-2014 by Michel Ludwig (michel.ludwig@kdemail.net) from Kate (C) 2001 by Matt Newell ******************************************************************************************/ /*************************************************************************** * * * 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. * * * ***************************************************************************/ // 2007-03-12 dani // - use KileDocument::Extensions #include "widgets/filebrowserwidget.h" #include #include #include #include #include #include #include #include #include #include #include #include #include "kileconfig.h" #include "kiledebug.h" namespace KileWidget { FileBrowserWidget::FileBrowserWidget(KileDocument::Extensions *extensions, QWidget *parent) -: QWidget(parent), m_extensions(extensions) + : QWidget(parent), m_extensions(extensions) { - m_configGroup = KConfigGroup(KSharedConfig::openConfig(),"FileBrowserWidget"); + m_configGroup = KConfigGroup(KSharedConfig::openConfig(),"FileBrowserWidget"); - QVBoxLayout* layout = new QVBoxLayout(this); - layout->setMargin(0); - layout->setSpacing(0); - setLayout(layout); + QVBoxLayout* layout = new QVBoxLayout(this); + layout->setMargin(0); + layout->setSpacing(0); + setLayout(layout); - m_toolbar = new KToolBar(this); - m_toolbar->setMovable(false); - m_toolbar->setToolButtonStyle(Qt::ToolButtonIconOnly); - m_toolbar->setContextMenuPolicy(Qt::NoContextMenu); - layout->addWidget(m_toolbar); + m_toolbar = new KToolBar(this); + m_toolbar->setMovable(false); + m_toolbar->setToolButtonStyle(Qt::ToolButtonIconOnly); + m_toolbar->setContextMenuPolicy(Qt::NoContextMenu); + layout->addWidget(m_toolbar); - KFilePlacesModel* model = new KFilePlacesModel(this); - m_urlNavigator = new KUrlNavigator(model, QUrl::fromLocalFile(QDir::homePath()), this); - layout->addWidget(m_urlNavigator); - connect(m_urlNavigator, SIGNAL(urlChanged(const QUrl&)), SLOT(setDir(const QUrl&))); + KFilePlacesModel* model = new KFilePlacesModel(this); + m_urlNavigator = new KUrlNavigator(model, QUrl::fromLocalFile(QDir::homePath()), this); + layout->addWidget(m_urlNavigator); + connect(m_urlNavigator, SIGNAL(urlChanged(const QUrl&)), SLOT(setDir(const QUrl&))); - m_dirOperator = new KDirOperator(QUrl(), this); - m_dirOperator->setViewConfig(m_configGroup); - m_dirOperator->readConfig(m_configGroup); - m_dirOperator->setView(KFile::Default); - m_dirOperator->setMode(KFile::Files); - setFocusProxy(m_dirOperator); + m_dirOperator = new KDirOperator(QUrl(), this); + m_dirOperator->setViewConfig(m_configGroup); + m_dirOperator->readConfig(m_configGroup); + m_dirOperator->setView(KFile::Default); + m_dirOperator->setMode(KFile::Files); + setFocusProxy(m_dirOperator); - connect(m_urlNavigator, SIGNAL(urlChanged(const QUrl&)), m_dirOperator, SLOT(setFocus())); - connect(m_dirOperator, SIGNAL(fileSelected(const KFileItem&)), this, SIGNAL(fileSelected(const KFileItem&))); - connect(m_dirOperator, SIGNAL(urlEntered(const QUrl&)), this, SLOT(dirUrlEntered(const QUrl&))); + connect(m_urlNavigator, SIGNAL(urlChanged(const QUrl&)), m_dirOperator, SLOT(setFocus())); + connect(m_dirOperator, SIGNAL(fileSelected(const KFileItem&)), this, SIGNAL(fileSelected(const KFileItem&))); + connect(m_dirOperator, SIGNAL(urlEntered(const QUrl&)), this, SLOT(dirUrlEntered(const QUrl&))); - setupToolbar(); + setupToolbar(); - layout->addWidget(m_dirOperator); - layout->setStretchFactor(m_dirOperator, 2); - readConfig(); + layout->addWidget(m_dirOperator); + layout->setStretchFactor(m_dirOperator, 2); + readConfig(); } FileBrowserWidget::~FileBrowserWidget() { } void FileBrowserWidget::readConfig() { - QString lastDir = KileConfig::lastDir(); - QFileInfo ldi(lastDir); - if (!ldi.isReadable()) { - KILE_DEBUG_MAIN << "lastDir is not readable"; - m_dirOperator->home(); - } - else { - setDir(QUrl::fromLocalFile(lastDir)); - } - - bool filterLatex = KileConfig::showLaTeXFilesOnly(); - toggleShowLaTeXFilesOnly(filterLatex); + QString lastDir = KileConfig::lastDir(); + QFileInfo ldi(lastDir); + if (!ldi.isReadable()) { + KILE_DEBUG_MAIN << "lastDir is not readable"; + m_dirOperator->home(); + } + else { + setDir(QUrl::fromLocalFile(lastDir)); + } + + bool filterLatex = KileConfig::showLaTeXFilesOnly(); + toggleShowLaTeXFilesOnly(filterLatex); } void FileBrowserWidget::writeConfig() { - KileConfig::setLastDir(m_dirOperator->url().toLocalFile()); - m_dirOperator->writeConfig(m_configGroup); + KileConfig::setLastDir(m_dirOperator->url().toLocalFile()); + m_dirOperator->writeConfig(m_configGroup); } void FileBrowserWidget::setupToolbar() { - KActionCollection *coll = m_dirOperator->actionCollection(); - m_toolbar->addAction(coll->action("back")); - m_toolbar->addAction(coll->action("forward")); - - QAction *action = new QAction(this); - action->setIcon(QIcon::fromTheme("document-open")); - action->setText(i18n("Open selected")); - connect(action, SIGNAL(triggered()), this, SLOT(emitFileSelectedSignal())); - m_toolbar->addAction(action); - - QAction *showOnlyLaTexFilesAction = new QAction(this); - showOnlyLaTexFilesAction->setText(i18n("Show LaTeX Files Only")); - showOnlyLaTexFilesAction->setCheckable(true); - showOnlyLaTexFilesAction->setChecked(KileConfig::showLaTeXFilesOnly()); - connect(showOnlyLaTexFilesAction, SIGNAL(triggered(bool)), this, SLOT(toggleShowLaTeXFilesOnly(bool))); - - // section for settings menu - KActionMenu *optionsMenu = new KActionMenu(QIcon::fromTheme("configure"), i18n("Options"), this); - optionsMenu->setDelayed(false); - optionsMenu->addAction(m_dirOperator->actionCollection()->action("short view")); - optionsMenu->addAction(m_dirOperator->actionCollection()->action("detailed view")); - optionsMenu->addAction(m_dirOperator->actionCollection()->action("tree view")); - optionsMenu->addAction(m_dirOperator->actionCollection()->action("detailed tree view")); - optionsMenu->addSeparator(); - optionsMenu->addAction(showOnlyLaTexFilesAction); - optionsMenu->addAction(m_dirOperator->actionCollection()->action("show hidden")); - - m_toolbar->addSeparator(); - m_toolbar->addAction(optionsMenu); + KActionCollection *coll = m_dirOperator->actionCollection(); + m_toolbar->addAction(coll->action("back")); + m_toolbar->addAction(coll->action("forward")); + + QAction *action = new QAction(this); + action->setIcon(QIcon::fromTheme("document-open")); + action->setText(i18n("Open selected")); + connect(action, SIGNAL(triggered()), this, SLOT(emitFileSelectedSignal())); + m_toolbar->addAction(action); + + QAction *showOnlyLaTexFilesAction = new QAction(this); + showOnlyLaTexFilesAction->setText(i18n("Show LaTeX Files Only")); + showOnlyLaTexFilesAction->setCheckable(true); + showOnlyLaTexFilesAction->setChecked(KileConfig::showLaTeXFilesOnly()); + connect(showOnlyLaTexFilesAction, SIGNAL(triggered(bool)), this, SLOT(toggleShowLaTeXFilesOnly(bool))); + + // section for settings menu + KActionMenu *optionsMenu = new KActionMenu(QIcon::fromTheme("configure"), i18n("Options"), this); + optionsMenu->setDelayed(false); + optionsMenu->addAction(m_dirOperator->actionCollection()->action("short view")); + optionsMenu->addAction(m_dirOperator->actionCollection()->action("detailed view")); + optionsMenu->addAction(m_dirOperator->actionCollection()->action("tree view")); + optionsMenu->addAction(m_dirOperator->actionCollection()->action("detailed tree view")); + optionsMenu->addSeparator(); + optionsMenu->addAction(showOnlyLaTexFilesAction); + optionsMenu->addAction(m_dirOperator->actionCollection()->action("show hidden")); + + m_toolbar->addSeparator(); + m_toolbar->addAction(optionsMenu); } void FileBrowserWidget::toggleShowLaTeXFilesOnly(bool filter) { - KileConfig::setShowLaTeXFilesOnly(filter); - - if(filter) { - // FileBrowserWidget filter for sidebar - QString filter = m_extensions->latexDocuments() - + ' ' + m_extensions->latexPackages() - + ' ' + m_extensions->bibtex() - + ' ' + m_extensions->metapost(); - filter.replace('.', "*."); - m_dirOperator->setNameFilter(filter); - } - else{ - m_dirOperator->clearFilter(); - } - m_dirOperator->rereadDir(); + KileConfig::setShowLaTeXFilesOnly(filter); + + if(filter) { + // FileBrowserWidget filter for sidebar + QString filter = m_extensions->latexDocuments() + + ' ' + m_extensions->latexPackages() + + ' ' + m_extensions->bibtex() + + ' ' + m_extensions->metapost(); + filter.replace('.', "*."); + m_dirOperator->setNameFilter(filter); + } + else { + m_dirOperator->clearFilter(); + } + m_dirOperator->rereadDir(); } QUrl FileBrowserWidget::currentUrl() const { - return m_dirOperator->url(); + return m_dirOperator->url(); } void FileBrowserWidget::dirUrlEntered(const QUrl &u) { - m_urlNavigator->setLocationUrl(u); + m_urlNavigator->setLocationUrl(u); } void FileBrowserWidget::setDir(const QUrl &url) { - m_dirOperator->setUrl(url, true); + m_dirOperator->setUrl(url, true); } void FileBrowserWidget::emitFileSelectedSignal() { - KFileItemList itemList = m_dirOperator->selectedItems(); - for(KFileItemList::iterator it = itemList.begin(); it != itemList.end(); ++it) { - emit(fileSelected(*it)); - } + KFileItemList itemList = m_dirOperator->selectedItems(); + for(KFileItemList::iterator it = itemList.begin(); it != itemList.end(); ++it) { + emit(fileSelected(*it)); + } - m_dirOperator->view()->clearSelection(); + m_dirOperator->view()->clearSelection(); } } diff --git a/src/widgets/filebrowserwidget.h b/src/widgets/filebrowserwidget.h index 0632e9af..f2863e32 100644 --- a/src/widgets/filebrowserwidget.h +++ b/src/widgets/filebrowserwidget.h @@ -1,74 +1,74 @@ /******************************************************************************************** begin : Wed Aug 14 2002 copyright : (C) 2002 - 2003 by Pascal Brachet 2003 by Jeroen Wijnhout (Jeroen.Wijnhout@kdemail.net) 2007, 2008 by Michel Ludwig (michel.ludwig@kdemail.net) from Kate (C) 2001 by Matt Newell ********************************************************************************************/ /*************************************************************************** * * * 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. * * * ***************************************************************************/ #ifndef FILEBROWSERWIDGET_H #define FILEBROWSERWIDGET_H #include #include #include #include #include #include #include "kileextensions.h" class KFileItem; class KToolBar; namespace KileWidget { class FileBrowserWidget : public QWidget { - Q_OBJECT + Q_OBJECT public: - FileBrowserWidget(KileDocument::Extensions *extensions, QWidget *parent); - ~FileBrowserWidget(); + FileBrowserWidget(KileDocument::Extensions *extensions, QWidget *parent); + ~FileBrowserWidget(); - QUrl currentUrl() const; + QUrl currentUrl() const; public Q_SLOTS: - void setDir(const QUrl &url); - void writeConfig(); + void setDir(const QUrl &url); + void writeConfig(); private Q_SLOTS: - void toggleShowLaTeXFilesOnly(bool filter); - void dirUrlEntered(const QUrl &u); - void emitFileSelectedSignal(); + void toggleShowLaTeXFilesOnly(bool filter); + void dirUrlEntered(const QUrl &u); + void emitFileSelectedSignal(); protected: - void setupToolbar(); - void readConfig(); + void setupToolbar(); + void readConfig(); Q_SIGNALS: - void fileSelected(const KFileItem& fileItem); + void fileSelected(const KFileItem& fileItem); private: - KToolBar *m_toolbar; - KUrlNavigator *m_urlNavigator; - KDirOperator *m_dirOperator; - KConfig *m_config; - KConfigGroup m_configGroup; - KileDocument::Extensions *m_extensions; + KToolBar *m_toolbar; + KUrlNavigator *m_urlNavigator; + KDirOperator *m_dirOperator; + KConfig *m_config; + KConfigGroup m_configGroup; + KileDocument::Extensions *m_extensions; }; } #endif diff --git a/src/widgets/generalconfigwidget.cpp b/src/widgets/generalconfigwidget.cpp index 3e973683..6e475109 100644 --- a/src/widgets/generalconfigwidget.cpp +++ b/src/widgets/generalconfigwidget.cpp @@ -1,47 +1,47 @@ /************************************************************************** * Copyright (C) 2007-2012 by Michel Ludwig (michel.ludwig@kdemail.net) * * 2011 by Felix Mauch (felix_mauch@web.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. * * * ***************************************************************************/ #include "widgets/generalconfigwidget.h" #include #include #include KileWidgetGeneralConfig::KileWidgetGeneralConfig(QWidget *parent) : QWidget(parent) { - setupUi(this); - m_defaultProjectLocationButton->setIcon(QIcon::fromTheme("folder-open")); + setupUi(this); + m_defaultProjectLocationButton->setIcon(QIcon::fromTheme("folder-open")); - connect(m_defaultProjectLocationButton, SIGNAL(clicked()), - this, SLOT(selectDefaultProjectLocation())); + connect(m_defaultProjectLocationButton, SIGNAL(clicked()), + this, SLOT(selectDefaultProjectLocation())); - KUrlCompletion *dirCompletion = new KUrlCompletion(); - dirCompletion->setMode(KUrlCompletion::DirCompletion); - kcfg_DefaultProjectLocation->setCompletionObject(dirCompletion); - kcfg_DefaultProjectLocation->setAutoDeleteCompletionObject(true); + KUrlCompletion *dirCompletion = new KUrlCompletion(); + dirCompletion->setMode(KUrlCompletion::DirCompletion); + kcfg_DefaultProjectLocation->setCompletionObject(dirCompletion); + kcfg_DefaultProjectLocation->setAutoDeleteCompletionObject(true); } KileWidgetGeneralConfig::~KileWidgetGeneralConfig() { } void KileWidgetGeneralConfig::selectDefaultProjectLocation() { - QString newDefaultLocation = QFileDialog::getExistingDirectory(this, QString(), kcfg_DefaultProjectLocation->text()); - if (!newDefaultLocation.isEmpty()) { - kcfg_DefaultProjectLocation->setText(newDefaultLocation); - } + QString newDefaultLocation = QFileDialog::getExistingDirectory(this, QString(), kcfg_DefaultProjectLocation->text()); + if (!newDefaultLocation.isEmpty()) { + kcfg_DefaultProjectLocation->setText(newDefaultLocation); + } } diff --git a/src/widgets/generalconfigwidget.h b/src/widgets/generalconfigwidget.h index 70a1c55a..a2fdd18e 100644 --- a/src/widgets/generalconfigwidget.h +++ b/src/widgets/generalconfigwidget.h @@ -1,34 +1,34 @@ /************************************************************************** * Copyright (C) 2007-2011 by Michel Ludwig (michel.ludwig@kdemail.net) * * 2011 by Felix Mauch (felix_mauch@web.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. * * * ***************************************************************************/ #ifndef GENERALCONFIGWIDGET_H #define GENERALCONFIGWIDGET_H #include #include "ui_generalconfigwidget.h" class KileWidgetGeneralConfig : public QWidget, public Ui::KileWidgetGeneralConfig { - Q_OBJECT + Q_OBJECT - public: - KileWidgetGeneralConfig(QWidget *parent = Q_NULLPTR); - ~KileWidgetGeneralConfig(); +public: + KileWidgetGeneralConfig(QWidget *parent = Q_NULLPTR); + ~KileWidgetGeneralConfig(); - private Q_SLOTS: - void selectDefaultProjectLocation(); +private Q_SLOTS: + void selectDefaultProjectLocation(); }; #endif diff --git a/src/widgets/graphicsconfigwidget.cpp b/src/widgets/graphicsconfigwidget.cpp index e3449407..b7caa2f2 100644 --- a/src/widgets/graphicsconfigwidget.cpp +++ b/src/widgets/graphicsconfigwidget.cpp @@ -1,24 +1,24 @@ /************************************************************************** * Copyright (C) 2007 by Michel Ludwig (michel.ludwig@kdemail.net) * ***************************************************************************/ /************************************************************************** * * * 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. * * * ***************************************************************************/ #include "widgets/graphicsconfigwidget.h" KileWidgetGraphicsConfig::KileWidgetGraphicsConfig(QWidget *parent) : QWidget(parent) { - setupUi(this); + setupUi(this); } KileWidgetGraphicsConfig::~KileWidgetGraphicsConfig() { } diff --git a/src/widgets/graphicsconfigwidget.h b/src/widgets/graphicsconfigwidget.h index 4e5dc676..0189d1fd 100644 --- a/src/widgets/graphicsconfigwidget.h +++ b/src/widgets/graphicsconfigwidget.h @@ -1,30 +1,30 @@ /************************************************************************** * Copyright (C) 2007 by Michel Ludwig (michel.ludwig@kdemail.net) * ***************************************************************************/ /************************************************************************** * * * 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. * * * ***************************************************************************/ #ifndef GRAPHICSCONFIGWIDGET_H #define GRAPHICSCONFIGWIDGET_H #include #include "ui_graphicsconfigwidget.h" class KileWidgetGraphicsConfig : public QWidget, public Ui::KileWidgetGraphicsConfig { - Q_OBJECT + Q_OBJECT - public: - KileWidgetGraphicsConfig(QWidget *parent = 0); - ~KileWidgetGraphicsConfig(); +public: + KileWidgetGraphicsConfig(QWidget *parent = 0); + ~KileWidgetGraphicsConfig(); }; #endif diff --git a/src/widgets/helpconfigwidget.cpp b/src/widgets/helpconfigwidget.cpp index 56781499..8fcf4c4f 100644 --- a/src/widgets/helpconfigwidget.cpp +++ b/src/widgets/helpconfigwidget.cpp @@ -1,80 +1,80 @@ /************************************************************************** * Copyright (C) 2007-2012 by Michel Ludwig (michel.ludwig@kdemail.net) * * 2011 by Felix Mauch (felix_mauch@web.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. * * * ***************************************************************************/ #include "widgets/helpconfigwidget.h" #include #include #include KileWidgetHelpConfig::KileWidgetHelpConfig(QWidget *parent) : QWidget(parent) { - setupUi(this); + setupUi(this); - m_helpLocationButton->setIcon(QIcon::fromTheme("folder-open")); - m_pbInformation->setIcon(QIcon::fromTheme("help-about")); + m_helpLocationButton->setIcon(QIcon::fromTheme("folder-open")); + m_pbInformation->setIcon(QIcon::fromTheme("help-about")); - connect(m_pbConfigure, SIGNAL(clicked()), this, SLOT(slotConfigure())); - connect(m_helpLocationButton, SIGNAL(clicked()), this, SLOT(selectHelpLocation())); - connect(m_pbInformation, SIGNAL(clicked()), this, SLOT(slotHelpInformation())); + connect(m_pbConfigure, SIGNAL(clicked()), this, SLOT(slotConfigure())); + connect(m_helpLocationButton, SIGNAL(clicked()), this, SLOT(selectHelpLocation())); + connect(m_pbInformation, SIGNAL(clicked()), this, SLOT(slotHelpInformation())); - KUrlCompletion *dirCompletion = new KUrlCompletion(); - dirCompletion->setMode(KUrlCompletion::DirCompletion); - kcfg_location->setCompletionObject(dirCompletion); - kcfg_location->setAutoDeleteCompletionObject(true); + KUrlCompletion *dirCompletion = new KUrlCompletion(); + dirCompletion->setMode(KUrlCompletion::DirCompletion); + kcfg_location->setCompletionObject(dirCompletion); + kcfg_location->setAutoDeleteCompletionObject(true); } KileWidgetHelpConfig::~KileWidgetHelpConfig() { } void KileWidgetHelpConfig::slotConfigure() { - m_help->userHelpDialog(); + m_help->userHelpDialog(); } void KileWidgetHelpConfig::setHelp(KileHelp::Help *help) { - m_help = help; + m_help = help; } void KileWidgetHelpConfig::selectHelpLocation() { - QString newLocation = QFileDialog::getExistingDirectory(this, QString(), kcfg_location->text()); - if (!newLocation.isEmpty()) { - kcfg_location->setText(newLocation); - } + QString newLocation = QFileDialog::getExistingDirectory(this, QString(), kcfg_location->text()); + if (!newLocation.isEmpty()) { + kcfg_location->setText(newLocation); + } } void KileWidgetHelpConfig::slotHelpInformation() { - QString message = i18n("

(La)TeX distributions use various locations for the base directory of the documentation files that they provide.
" - "Here are some suggestions:

" - "
    " - "
  • Debian: /usr/share/doc/texlive-doc
  • " - "
  • Ubuntu: /usr/share/doc/texlive-doc
  • " - "
  • OpenSuse: /usr/share/texmf/doc
  • " - "
  • TexLive 2009: /usr/share/doc/texlive-doc
  • " - "
  • TexLive 2010 (TUG): /usr/local/texlive/2010/texmf-dist/doc
  • " - "
  • TexLive 2011 (TUG): /usr/local/texlive/2011/texmf-dist/doc
  • " - "
" - "

Additionally, if you use TeXLive 2010 or above, the comprehensive collection of links to documentation topics
" - "that can be found in the top-level file doc.html may be helpful " - "(/usr/local/texlive/2011/doc.html or similar).
" - "You may want to consider placing it in the User Help section of the help menu.

" - ); + QString message = i18n("

(La)TeX distributions use various locations for the base directory of the documentation files that they provide.
" + "Here are some suggestions:

" + "
    " + "
  • Debian: /usr/share/doc/texlive-doc
  • " + "
  • Ubuntu: /usr/share/doc/texlive-doc
  • " + "
  • OpenSuse: /usr/share/texmf/doc
  • " + "
  • TexLive 2009: /usr/share/doc/texlive-doc
  • " + "
  • TexLive 2010 (TUG): /usr/local/texlive/2010/texmf-dist/doc
  • " + "
  • TexLive 2011 (TUG): /usr/local/texlive/2011/texmf-dist/doc
  • " + "
" + "

Additionally, if you use TeXLive 2010 or above, the comprehensive collection of links to documentation topics
" + "that can be found in the top-level file doc.html may be helpful " + "(/usr/local/texlive/2011/doc.html or similar).
" + "You may want to consider placing it in the User Help section of the help menu.

" + ); - KMessageBox::information(this, message, i18n("Location of Documentation Files")); + KMessageBox::information(this, message, i18n("Location of Documentation Files")); } diff --git a/src/widgets/helpconfigwidget.h b/src/widgets/helpconfigwidget.h index 60b84584..2250b3a3 100644 --- a/src/widgets/helpconfigwidget.h +++ b/src/widgets/helpconfigwidget.h @@ -1,43 +1,43 @@ /************************************************************************** * Copyright (C) 2007 by Michel Ludwig (michel.ludwig@kdemail.net) * * 2011 by Felix Mauch (felix_mauch@web.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. * * * ***************************************************************************/ #ifndef HELPCONFIGWIDGET_H #define HELPCONFIGWIDGET_H #include #include "kilehelp.h" #include "ui_helpconfigwidget.h" class KileWidgetHelpConfig : public QWidget, public Ui::KileWidgetHelpConfig { - Q_OBJECT + Q_OBJECT - public: - KileWidgetHelpConfig(QWidget *parent = 0); - ~KileWidgetHelpConfig(); +public: + KileWidgetHelpConfig(QWidget *parent = 0); + ~KileWidgetHelpConfig(); - void setHelp(KileHelp::Help *help); + void setHelp(KileHelp::Help *help); - protected Q_SLOTS: - void slotConfigure(); - void selectHelpLocation(); - void slotHelpInformation(); +protected Q_SLOTS: + void slotConfigure(); + void selectHelpLocation(); + void slotHelpInformation(); - protected: - KileHelp::Help *m_help; +protected: + KileHelp::Help *m_help; }; #endif diff --git a/src/widgets/konsolewidget.cpp b/src/widgets/konsolewidget.cpp index a796f6c2..76e3439f 100644 --- a/src/widgets/konsolewidget.cpp +++ b/src/widgets/konsolewidget.cpp @@ -1,162 +1,162 @@ /*************************************************************************************************** begin : Mon Dec 22 2003 copyright : (C) 2001 - 2003 by Brachet Pascal 2003 by Jeroen Wijnhout (Jeroen.Wijnhout@kdemail.net) 2007-2012 by Michel Ludwig (michel.ludwig@kdemail.net) ***************************************************************************************************/ /*************************************************************************** * * * 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. * * * ***************************************************************************/ #include "widgets/konsolewidget.h" #include "kileinfo.h" #include #include #include #include #include #include #include #include #include #include #include #include namespace KileWidget { - Konsole::Konsole(KileInfo * info, QWidget *parent) : - QFrame(parent), - m_part(Q_NULLPTR), - m_ki(info) - { - setLayout(new QVBoxLayout(this)); - layout()->setMargin(0); - setFrameStyle(QFrame::StyledPanel | QFrame::Sunken); - spawn(); - } - - Konsole::~Konsole() - { - } - - void Konsole::spawn() - { - KILE_DEBUG_MAIN << "void Konsole::spawn()"; - - KPluginFactory *factory = Q_NULLPTR; - KService::Ptr service = KService::serviceByDesktopName("konsolepart"); - if(!service) { - KILE_DEBUG_MAIN << "No service for konsolepart"; - return; - } - - factory = KPluginLoader(service->library()).factory(); - if(!factory) { - KILE_DEBUG_MAIN << "No factory for konsolepart"; - return; - } - - // the catalog for translations is added by the Konsole part constructor already - m_part = static_cast(factory->create(this, this)); - if(!m_part) { - return; - } - - if(!qobject_cast(m_part)){ - KILE_DEBUG_MAIN << "Did not find the TerminalInterface"; - delete m_part; - m_part = Q_NULLPTR; - return; - } - - layout()->addWidget(m_part->widget()); - setFocusProxy(m_part->widget()); - connect(m_part, SIGNAL(destroyed()), this, SLOT(slotDestroyed())); - - // necessary as older versions of Konsole (4.5) might not show a proper prompt otherwise - qobject_cast(m_part)->showShellInDir(QDir::currentPath()); - } - - - void Konsole::sync() - { - if(!KileConfig::syncConsoleDirWithTabs()) { - return; - } - - KTextEditor::Document *doc = m_ki->activeTextDocument(); - KTextEditor::View *view = Q_NULLPTR; - - if(doc) { - view = doc->views().first(); - } - - if(view) { - QString finame; - QUrl url = view->document()->url(); - - if(url.path().isEmpty()) { - return; - } - - QFileInfo fic(url.adjusted(QUrl::RemoveFilename|QUrl::StripTrailingSlash).path()); - if(fic.isReadable()) { - setDirectory(url.adjusted(QUrl::RemoveFilename|QUrl::StripTrailingSlash).path()); - } - } - } - - void Konsole::setDirectory(const QString &directory) - { - TerminalInterface *m_term = qobject_cast(m_part); - if(!m_term || m_term->foregroundProcessId() >= 0) { // check if a foreground process is running - return; - } - - //FIXME: KonsolePart should be extended in such a way that it isn't necessary - // anymore to send 'cd' commands - if(m_term && !directory.isEmpty() && directory != m_currentDir) { - m_term->sendInput(QChar(0x05)); // clear the shell command prompt by sending Ctrl+E and - m_term->sendInput(QChar(0x15)); // Ctrl+U (#301653) - m_term->sendInput("cd " + KShell::quoteArg(directory) + '\n'); - m_term->sendInput("clear\n"); - m_currentDir = directory; - } - } - - void Konsole::showEvent(QShowEvent *ev) - { - QWidget::showEvent(ev); - activate(); - } - - void Konsole::activate() - { - if (m_part) { - m_part->widget()->show(); - m_part->widget()->setFocus(); - } - } - - void Konsole::slotDestroyed () - { - // there is no need to remove the widget from the layout as this is done - // automatically when the widget is destroyed - m_part = Q_NULLPTR; - spawn(); - } +Konsole::Konsole(KileInfo * info, QWidget *parent) : + QFrame(parent), + m_part(Q_NULLPTR), + m_ki(info) +{ + setLayout(new QVBoxLayout(this)); + layout()->setMargin(0); + setFrameStyle(QFrame::StyledPanel | QFrame::Sunken); + spawn(); +} + +Konsole::~Konsole() +{ +} + +void Konsole::spawn() +{ + KILE_DEBUG_MAIN << "void Konsole::spawn()"; + + KPluginFactory *factory = Q_NULLPTR; + KService::Ptr service = KService::serviceByDesktopName("konsolepart"); + if(!service) { + KILE_DEBUG_MAIN << "No service for konsolepart"; + return; + } + + factory = KPluginLoader(service->library()).factory(); + if(!factory) { + KILE_DEBUG_MAIN << "No factory for konsolepart"; + return; + } + + // the catalog for translations is added by the Konsole part constructor already + m_part = static_cast(factory->create(this, this)); + if(!m_part) { + return; + } + + if(!qobject_cast(m_part)) { + KILE_DEBUG_MAIN << "Did not find the TerminalInterface"; + delete m_part; + m_part = Q_NULLPTR; + return; + } + + layout()->addWidget(m_part->widget()); + setFocusProxy(m_part->widget()); + connect(m_part, SIGNAL(destroyed()), this, SLOT(slotDestroyed())); + + // necessary as older versions of Konsole (4.5) might not show a proper prompt otherwise + qobject_cast(m_part)->showShellInDir(QDir::currentPath()); +} + + +void Konsole::sync() +{ + if(!KileConfig::syncConsoleDirWithTabs()) { + return; + } + + KTextEditor::Document *doc = m_ki->activeTextDocument(); + KTextEditor::View *view = Q_NULLPTR; + + if(doc) { + view = doc->views().first(); + } + + if(view) { + QString finame; + QUrl url = view->document()->url(); + + if(url.path().isEmpty()) { + return; + } + + QFileInfo fic(url.adjusted(QUrl::RemoveFilename|QUrl::StripTrailingSlash).path()); + if(fic.isReadable()) { + setDirectory(url.adjusted(QUrl::RemoveFilename|QUrl::StripTrailingSlash).path()); + } + } +} + +void Konsole::setDirectory(const QString &directory) +{ + TerminalInterface *m_term = qobject_cast(m_part); + if(!m_term || m_term->foregroundProcessId() >= 0) { // check if a foreground process is running + return; + } + + //FIXME: KonsolePart should be extended in such a way that it isn't necessary + // anymore to send 'cd' commands + if(m_term && !directory.isEmpty() && directory != m_currentDir) { + m_term->sendInput(QChar(0x05)); // clear the shell command prompt by sending Ctrl+E and + m_term->sendInput(QChar(0x15)); // Ctrl+U (#301653) + m_term->sendInput("cd " + KShell::quoteArg(directory) + '\n'); + m_term->sendInput("clear\n"); + m_currentDir = directory; + } +} + +void Konsole::showEvent(QShowEvent *ev) +{ + QWidget::showEvent(ev); + activate(); +} + +void Konsole::activate() +{ + if (m_part) { + m_part->widget()->show(); + m_part->widget()->setFocus(); + } +} + +void Konsole::slotDestroyed () +{ + // there is no need to remove the widget from the layout as this is done + // automatically when the widget is destroyed + m_part = Q_NULLPTR; + spawn(); +} } diff --git a/src/widgets/konsolewidget.h b/src/widgets/konsolewidget.h index e88946db..fc0a5e9b 100644 --- a/src/widgets/konsolewidget.h +++ b/src/widgets/konsolewidget.h @@ -1,56 +1,58 @@ /********************************************************************** Copyright (C) 2001 - 2003 by Brachet Pascal 2003 by Jeroen Wijnhout (Jeroen.Wijnhout@kdemail.net) 2007-2012 by Michel Ludwig (michel.ludwig@kdemail.net) **********************************************************************/ /*************************************************************************** * * * 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. * * * ***************************************************************************/ #ifndef KONSOLEWIDGET_H #define KONSOLEWIDGET_H #include #include -namespace KParts { class ReadOnlyPart; } +namespace KParts { +class ReadOnlyPart; +} class KileInfo; namespace KileWidget { - class Konsole : public QFrame - { - Q_OBJECT - - public: - Konsole(KileInfo *, QWidget* parent); - ~Konsole(); - - public Q_SLOTS: - void setDirectory(const QString& dir); - void activate(); - void sync(); - - private Q_SLOTS: - void slotDestroyed(); - - protected: - void showEvent(QShowEvent *ev); - void spawn(); - - private: - KParts::ReadOnlyPart *m_part; - bool m_bPresent; - KileInfo *m_ki; - QString m_currentDir; - }; +class Konsole : public QFrame +{ + Q_OBJECT + +public: + Konsole(KileInfo *, QWidget* parent); + ~Konsole(); + +public Q_SLOTS: + void setDirectory(const QString& dir); + void activate(); + void sync(); + +private Q_SLOTS: + void slotDestroyed(); + +protected: + void showEvent(QShowEvent *ev); + void spawn(); + +private: + KParts::ReadOnlyPart *m_part; + bool m_bPresent; + KileInfo *m_ki; + QString m_currentDir; +}; } #endif diff --git a/src/widgets/latexconfigwidget.cpp b/src/widgets/latexconfigwidget.cpp index 00e94839..5477597a 100644 --- a/src/widgets/latexconfigwidget.cpp +++ b/src/widgets/latexconfigwidget.cpp @@ -1,41 +1,41 @@ /************************************************************************** * Copyright (C) 2007 by Michel Ludwig (michel.ludwig@kdemail.net) * ***************************************************************************/ /************************************************************************** * * * 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. * * * ***************************************************************************/ #include "latexconfigwidget.h" #include "dialogs/latexcommanddialog.h" KileWidgetLatexConfig::KileWidgetLatexConfig(QWidget *parent) : QWidget(parent) { - setupUi(this); - connect(m_pbCommands, SIGNAL(clicked()), this, SLOT(slotConfigure())); + setupUi(this); + connect(m_pbCommands, SIGNAL(clicked()), this, SLOT(slotConfigure())); } KileWidgetLatexConfig::~KileWidgetLatexConfig() { } void KileWidgetLatexConfig::slotConfigure() { - KileDialog::LatexCommandsDialog *dlg = new KileDialog::LatexCommandsDialog(m_config, m_commands, this); - dlg->exec(); - delete dlg; + KileDialog::LatexCommandsDialog *dlg = new KileDialog::LatexCommandsDialog(m_config, m_commands, this); + dlg->exec(); + delete dlg; } void KileWidgetLatexConfig::setLatexCommands(KConfig *config, KileDocument::LatexCommands *commands) { - m_config = config; - m_commands = commands; + m_config = config; + m_commands = commands; } diff --git a/src/widgets/latexconfigwidget.h b/src/widgets/latexconfigwidget.h index 57b699d2..5441608d 100644 --- a/src/widgets/latexconfigwidget.h +++ b/src/widgets/latexconfigwidget.h @@ -1,43 +1,43 @@ /************************************************************************** * Copyright (C) 2007 by Michel Ludwig (michel.ludwig@kdemail.net) * ***************************************************************************/ /************************************************************************** * * * 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. * * * ***************************************************************************/ #ifndef LATEXCONFIGWIDGET_H #define LATEXCONFIGWIDGET_H #include #include "kconfig.h" #include "latexcmd.h" #include "ui_latexconfigwidget.h" class KileWidgetLatexConfig : public QWidget, public Ui::KileWidgetLatexConfig { - Q_OBJECT + Q_OBJECT - public: - KileWidgetLatexConfig(QWidget *parent = 0); - ~KileWidgetLatexConfig(); +public: + KileWidgetLatexConfig(QWidget *parent = 0); + ~KileWidgetLatexConfig(); - void setLatexCommands(KConfig *config, KileDocument::LatexCommands *commands); + void setLatexCommands(KConfig *config, KileDocument::LatexCommands *commands); - protected Q_SLOTS: - void slotConfigure(); +protected Q_SLOTS: + void slotConfigure(); - protected: - KConfig *m_config; - KileDocument::LatexCommands *m_commands; +protected: + KConfig *m_config; + KileDocument::LatexCommands *m_commands; }; #endif diff --git a/src/widgets/latextoolconfigwidget.cpp b/src/widgets/latextoolconfigwidget.cpp index 21dcb519..c3cbda36 100644 --- a/src/widgets/latextoolconfigwidget.cpp +++ b/src/widgets/latextoolconfigwidget.cpp @@ -1,24 +1,24 @@ /************************************************************************** * Copyright (C) 2007 by Michel Ludwig (michel.ludwig@kdemail.net) * ***************************************************************************/ /************************************************************************** * * * 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. * * * ***************************************************************************/ #include "widgets/latextoolconfigwidget.h" LaTeXToolConfigWidget::LaTeXToolConfigWidget(QWidget *parent) : QWidget(parent) { - setupUi(this); + setupUi(this); } LaTeXToolConfigWidget::~LaTeXToolConfigWidget() { } diff --git a/src/widgets/latextoolconfigwidget.h b/src/widgets/latextoolconfigwidget.h index 33c6614a..f3f13b9c 100644 --- a/src/widgets/latextoolconfigwidget.h +++ b/src/widgets/latextoolconfigwidget.h @@ -1,30 +1,30 @@ /************************************************************************** * Copyright (C) 2007 by Michel Ludwig (michel.ludwig@kdemail.net) * ***************************************************************************/ /************************************************************************** * * * 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. * * * ***************************************************************************/ #ifndef LATEXTOOLCONFIGWIDGET_H #define LATEXTOOLCONFIGWIDGET_H #include #include "ui_latextoolconfigwidget.h" class LaTeXToolConfigWidget : public QWidget, public Ui::LaTeXToolConfigWidget { - Q_OBJECT + Q_OBJECT - public: - LaTeXToolConfigWidget(QWidget *parent = 0); - ~LaTeXToolConfigWidget(); +public: + LaTeXToolConfigWidget(QWidget *parent = 0); + ~LaTeXToolConfigWidget(); }; #endif diff --git a/src/widgets/livepreviewconfigwidget.cpp b/src/widgets/livepreviewconfigwidget.cpp index 8bae74e5..502384a7 100644 --- a/src/widgets/livepreviewconfigwidget.cpp +++ b/src/widgets/livepreviewconfigwidget.cpp @@ -1,45 +1,45 @@ /************************************************************************** * Copyright (C) 2011-2012 by Michel Ludwig (michel.ludwig@kdemail.net) * ***************************************************************************/ /************************************************************************** * * * 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. * * * ***************************************************************************/ #include "livepreviewconfigwidget.h" #include "kileconfig.h" KileWidgetLivePreviewConfig::KileWidgetLivePreviewConfig(KConfig *config, QWidget *parent) - : QWidget(parent), - m_config(config) + : QWidget(parent), + m_config(config) { - setupUi(this); + setupUi(this); } KileWidgetLivePreviewConfig::~KileWidgetLivePreviewConfig() { } void KileWidgetLivePreviewConfig::readConfig() { - if(KileConfig::livePreviewCompileOnlyAfterSaving()) { - m_compileDocumentOnSaveRadioButton->setChecked(true); - } - else { - m_compileDocumentOnChangesRadioButton->setChecked(true); - } + if(KileConfig::livePreviewCompileOnlyAfterSaving()) { + m_compileDocumentOnSaveRadioButton->setChecked(true); + } + else { + m_compileDocumentOnChangesRadioButton->setChecked(true); + } } void KileWidgetLivePreviewConfig::writeConfig() { - KileConfig::setLivePreviewCompileOnlyAfterSaving(m_compileDocumentOnSaveRadioButton->isChecked()); + KileConfig::setLivePreviewCompileOnlyAfterSaving(m_compileDocumentOnSaveRadioButton->isChecked()); } diff --git a/src/widgets/livepreviewconfigwidget.h b/src/widgets/livepreviewconfigwidget.h index 14a56d0c..d2dad53a 100644 --- a/src/widgets/livepreviewconfigwidget.h +++ b/src/widgets/livepreviewconfigwidget.h @@ -1,38 +1,38 @@ /************************************************************************** * Copyright (C) 2011 by Michel Ludwig (michel.ludwig@kdemail.net) * ***************************************************************************/ /************************************************************************** * * * 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. * * * ***************************************************************************/ #ifndef LIVEPREVIEWCONFIGWIDGET_H #define LIVEPREVIEWCONFIGWIDGET_H #include #include #include "ui_livepreviewconfigwidget.h" class KileWidgetLivePreviewConfig : public QWidget, public Ui::KileWidgetLivePreviewConfig { - Q_OBJECT + Q_OBJECT - public: - KileWidgetLivePreviewConfig(KConfig *config, QWidget *parent = Q_NULLPTR); - ~KileWidgetLivePreviewConfig(); +public: + KileWidgetLivePreviewConfig(KConfig *config, QWidget *parent = Q_NULLPTR); + ~KileWidgetLivePreviewConfig(); - void readConfig(); - void writeConfig(); + void readConfig(); + void writeConfig(); - protected: - KConfig *m_config; +protected: + KConfig *m_config; }; #endif diff --git a/src/widgets/logwidget.cpp b/src/widgets/logwidget.cpp index 91edb216..f918b35b 100644 --- a/src/widgets/logwidget.cpp +++ b/src/widgets/logwidget.cpp @@ -1,408 +1,408 @@ /************************************************************************************** Copyright (C) 2003 by Jeroen Wijnhout (Jeroen.Wijnhout@kdemail.net) 2008-2012 by Michel Ludwig (michel.ludwig@kdemail.net) **************************************************************************************/ /*************************************************************************** * * * 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. * * * ****************************************************************************/ #include "widgets/logwidget.h" #include #include #include #include #include #include #include #include #include #include #include #include #include "kileconfig.h" #include "kiledebug.h" #include "kileinfo.h" #include "kiletool_enums.h" namespace KileWidget { - LogWidgetItemDelegate::LogWidgetItemDelegate(QObject* parent) - : QItemDelegate(parent) - { - } - - QSize LogWidgetItemDelegate::sizeHint(const QStyleOptionViewItem& /* option */, - const QModelIndex& index) const - { - QTextDocument *textDocument = constructTextDocument(index); - QSize size = textDocument->documentLayout()->documentSize().toSize(); - delete textDocument; - return size; - } - - void LogWidgetItemDelegate::paint(QPainter* painter, const QStyleOptionViewItem& option, - const QModelIndex& index) const - { - painter->save(); - QAbstractTextDocumentLayout::PaintContext context; - QVector selectionVector; - - painter->translate(option.rect.x(), option.rect.y()); - QTextDocument *textDocument = constructTextDocument(index); - - if(option.state & QStyle::State_MouseOver && index.data(Qt::UserRole).isValid()) { - QTextCursor cursor(textDocument); - cursor.select(QTextCursor::Document); - QTextCharFormat format; - format.setFontUnderline(true); - cursor.mergeCharFormat(format); - } - - if(option.state & QStyle::State_Selected) { - QTextCursor cursor(textDocument); - cursor.setPosition(0); - cursor.movePosition(QTextCursor::End, QTextCursor::KeepAnchor); - QTextCharFormat selectionTextCharFormat; - selectionTextCharFormat.setFontWeight(QFont::Bold); - selectionTextCharFormat.setBackground(option.palette.highlight()); - selectionTextCharFormat.setForeground(option.palette.highlightedText()); - QAbstractTextDocumentLayout::Selection selection; - selection.cursor = cursor; - selection.format = selectionTextCharFormat; - selectionVector.push_back(selection); - context.selections = selectionVector; - } - - textDocument->documentLayout()->draw(painter, context); - delete textDocument; - - painter->restore(); - } - - QTextDocument* LogWidgetItemDelegate::constructTextDocument(const QModelIndex& index) const - { - QTextDocument *textDocument = new QTextDocument(); - textDocument->setHtml(index.data().toString()); - return textDocument; - } - - LogWidget::LogWidget(PopupType popupType, QWidget *parent, const char *name) : - QListWidget(parent), m_popupType(popupType) - { - setObjectName(name); - connect(this, SIGNAL(itemClicked(QListWidgetItem*)), - this, SLOT(slotItemClicked(QListWidgetItem*))); - QPalette customPalette = palette(); - customPalette.setColor(QPalette::Window, QColor(Qt::white)); - setPalette(customPalette); - m_itemDelegate = new LogWidgetItemDelegate(this); - setSelectionMode(QAbstractItemView::MultiSelection); - QAbstractItemDelegate *delegate = itemDelegate(); - if(delegate) { - delete delegate; - } - setItemDelegate(m_itemDelegate); - setMouseTracking(true); - } - - LogWidget::~LogWidget() - { - } - - bool LogWidget::isShowingOutput() const - { - return (count() > 0); - } - - void LogWidget::highlight(const OutputInfo& info, bool startFromBottom) - { - for(int i = 0; i < count(); ++i) { - QListWidgetItem *listItem = item(startFromBottom ? count() - 1 - i : i); - QVariant variant = listItem->data(Qt::UserRole); - if(!variant.isValid()) { - continue; - } - OutputInfo info2 = variant.value(); - if(info == info2) { - deselectAllItems(); - scrollToItem(listItem); - listItem->setSelected(true); - break; - } - } - } - - void LogWidget::slotItemClicked(QListWidgetItem *item) - { - QVariant variant = item->data(Qt::UserRole); - if(!variant.isValid()) { - return; - } - - OutputInfo info = variant.value(); - - emit(outputInfoSelected(info)); - } - - void LogWidget::enterEvent(QEvent *) - { - adaptMouseCursor(mapFromGlobal(QCursor::pos())); - } - - void LogWidget::leaveEvent(QEvent *) - { - unsetCursor(); - } - - void LogWidget::mouseMoveEvent(QMouseEvent* event) - { - QPoint p = event->pos(); - adaptMouseCursor(p); - } - - void LogWidget::adaptMouseCursor(const QPoint& p) - { - QListWidgetItem *item = itemAt(p); - if(!item) { - unsetCursor(); - return; - } - - QVariant variant = item->data(Qt::UserRole); - if(variant.isValid()) { - setCursor(Qt::PointingHandCursor); - } - else { - unsetCursor(); - } - } - - void LogWidget::keyPressEvent(QKeyEvent *event) - { - QAbstractScrollArea::keyPressEvent(event); - } - - void LogWidget::deselectAllItems() - { - QList items = selectedItems(); - for(QList::iterator i = items.begin(); - i != items.end(); ++i) { - QListWidgetItem *item = *i; - item->setSelected(false); - } - } - - void LogWidget::printMessage(const QString& message) - { - KILE_DEBUG_MAIN << "\t" << message; - printMessage(-1, message, QString()); - } - - void LogWidget::printMessage(int type, const QString& message, const QString &tool, - const OutputInfo& outputInfo, bool allowSelection, - bool scroll) - { - QStringList messageList = message.split('\n'); - for(QStringList::iterator it = messageList.begin(); it != messageList.end(); ++it) { - printMessageLine(type, *it, tool, outputInfo, allowSelection, scroll); - } - } - - void LogWidget::printMessageLine(int type, const QString& message, const QString &tool, - const OutputInfo& outputInfo, bool allowSelection, - bool scroll) - { - if(type == KileTool::Error) { - KILE_DEBUG_MAIN << "showing error message emitted"; - emit showingErrorMessage(this); - } - - QString myMsg = message.toHtmlEscaped(); - QString fontColor; - - switch(type) { - case KileTool::Warning : - fontColor = ""; - break; - case KileTool::ProblemWarning : - if(KileConfig::hideProblemWarning()) { - return; - } - fontColor = ""; - break; - case KileTool::Error: // fall through - case KileTool::ProblemError: - fontColor = ""; - break; - case KileTool::ProblemBadBox: - if (KileConfig::hideProblemBadBox()) { - return; - } - { - // 'KColorScheme::scheme' doesn't take the background colour into account, so we have to do it manually - const QColor color = (KStatefulBrush(KColorScheme::View, KColorScheme::NormalBackground).brush(this).color().lightnessF() > 0.5) - ? KColorScheme::shade(KStatefulBrush(KColorScheme::View, KColorScheme::NeutralText).brush(this).color(), KColorScheme::DarkShade) - : KColorScheme::shade(KStatefulBrush(KColorScheme::View, KColorScheme::NeutralText).brush(this).color(), KColorScheme::LightShade); - fontColor = ""; - } - break; - default: - fontColor = ""; - break; - } - - QListWidgetItem *item = new QListWidgetItem(this); - - if(tool.isEmpty()) { - item->setText(fontColor + myMsg + ""); - } - else { - item->setText(fontColor + "[" + tool + "] " + myMsg + ""); - } - - - if(outputInfo.isValid()) { - item->setData(Qt::UserRole, QVariant::fromValue(outputInfo)); - } - if(!allowSelection) { - // Don't allow the user to manually select this item - item->setFlags(item->flags() & ~Qt::ItemIsSelectable); - } - - if((type == KileTool::Error || type == KileTool::ProblemError) - && !m_firstErrorMessgeInToolLog.isValid()) { - m_firstErrorMessgeInToolLog = outputInfo; - } - - if(scroll) { - scrollToItem(item); - } - } - - void LogWidget::printProblem(int type, const QString& problem, const OutputInfo& outputInfo) - { - KILE_DEBUG_MAIN << "\t" << problem; - printMessage(type, problem, QString(), outputInfo); - } - - void LogWidget::printProblems(const QList& list) - { - setUpdatesEnabled(false); - for(QList::const_iterator i = list.begin(); i != list.end(); ++i) { - printMessage((*i).type, (*i).message, QString(), (*i).outputInfo, false, false); - } - setUpdatesEnabled(true); - scrollToBottom(); - } - - void LogWidget::addEmptyLine() - { - printMessage(-1, QString(), QString()); - } - - void LogWidget::copy() - { - QList selectedList = selectedItems(); - QString toCopy; - int maxIndex = 0; - QHash itemHash; - for(QList::iterator i = selectedList.begin(); - i != selectedList.end(); ++i) { - QListWidgetItem* item = *i; - int row = indexFromItem(item).row(); - itemHash[row] = item; - maxIndex = qMax(maxIndex, row); - } - for(int i = 0; i <= maxIndex; ++i) { - QHash::iterator it = itemHash.find(i); - if(it != itemHash.end()) { - toCopy += (*it)->data(Qt::UserRole).value().message() + '\n'; - } - } - if(!toCopy.isEmpty()) { - QApplication::clipboard()->setText(toCopy); - } - } - - void LogWidget::startToolLogOutput() - { - m_firstErrorMessgeInToolLog = OutputInfo(); - } - - void LogWidget::endToolLogOutput() - { - if(m_firstErrorMessgeInToolLog.isValid()) { - highlight(m_firstErrorMessgeInToolLog, true); - } - } - - void LogWidget::contextMenuEvent(QContextMenuEvent *event) - { - QMenu popup; - - QAction *action = KStandardAction::copy(this, SLOT(copy()), this); - action->setShortcuts(QList()); - if(selectedItems().size() == 0) { - action->setEnabled(false); - } - popup.addAction(action); - - action = KStandardAction::selectAll(this, SLOT(selectAll()), this); - action->setShortcuts(QList()); - if(!containsSelectableItems()) { - action->setEnabled(false); - } - popup.addAction(action); - - - if(!(m_popupType & NoHideActions)) { - popup.addSeparator(); - - action = new QAction(i18n("Hide &Bad Boxes"), &popup); - action->setCheckable(true); - action->setChecked(KileConfig::hideProblemBadBox()); - connect(action, SIGNAL(triggered()), this, SLOT(toggleBadBoxHiding())); - popup.addAction(action); - - action = new QAction(i18n("Hide (La)TeX &Warnings"), &popup); - action->setCheckable(true); - action->setChecked(KileConfig::hideProblemWarning()); - connect(action, SIGNAL(triggered()), this, SLOT(toggleWarningsHiding())); - popup.addAction(action); - } - - popup.exec(event->globalPos()); - } - - void LogWidget::toggleBadBoxHiding() - { - KileConfig::setHideProblemBadBox(!KileConfig::hideProblemBadBox()); - } - - void LogWidget::toggleWarningsHiding() - { - KileConfig::setHideProblemWarning(!KileConfig::hideProblemWarning()); - } - - bool LogWidget::containsSelectableItems() const - { - for(int i = 0; i < count(); ++i) { - if(item(i)->flags() & Qt::ItemIsSelectable) { - return true; - } - } - - return false; - } +LogWidgetItemDelegate::LogWidgetItemDelegate(QObject* parent) + : QItemDelegate(parent) +{ +} + +QSize LogWidgetItemDelegate::sizeHint(const QStyleOptionViewItem& /* option */, + const QModelIndex& index) const +{ + QTextDocument *textDocument = constructTextDocument(index); + QSize size = textDocument->documentLayout()->documentSize().toSize(); + delete textDocument; + return size; +} + +void LogWidgetItemDelegate::paint(QPainter* painter, const QStyleOptionViewItem& option, + const QModelIndex& index) const +{ + painter->save(); + QAbstractTextDocumentLayout::PaintContext context; + QVector selectionVector; + + painter->translate(option.rect.x(), option.rect.y()); + QTextDocument *textDocument = constructTextDocument(index); + + if(option.state & QStyle::State_MouseOver && index.data(Qt::UserRole).isValid()) { + QTextCursor cursor(textDocument); + cursor.select(QTextCursor::Document); + QTextCharFormat format; + format.setFontUnderline(true); + cursor.mergeCharFormat(format); + } + + if(option.state & QStyle::State_Selected) { + QTextCursor cursor(textDocument); + cursor.setPosition(0); + cursor.movePosition(QTextCursor::End, QTextCursor::KeepAnchor); + QTextCharFormat selectionTextCharFormat; + selectionTextCharFormat.setFontWeight(QFont::Bold); + selectionTextCharFormat.setBackground(option.palette.highlight()); + selectionTextCharFormat.setForeground(option.palette.highlightedText()); + QAbstractTextDocumentLayout::Selection selection; + selection.cursor = cursor; + selection.format = selectionTextCharFormat; + selectionVector.push_back(selection); + context.selections = selectionVector; + } + + textDocument->documentLayout()->draw(painter, context); + delete textDocument; + + painter->restore(); +} + +QTextDocument* LogWidgetItemDelegate::constructTextDocument(const QModelIndex& index) const +{ + QTextDocument *textDocument = new QTextDocument(); + textDocument->setHtml(index.data().toString()); + return textDocument; +} + +LogWidget::LogWidget(PopupType popupType, QWidget *parent, const char *name) : + QListWidget(parent), m_popupType(popupType) +{ + setObjectName(name); + connect(this, SIGNAL(itemClicked(QListWidgetItem*)), + this, SLOT(slotItemClicked(QListWidgetItem*))); + QPalette customPalette = palette(); + customPalette.setColor(QPalette::Window, QColor(Qt::white)); + setPalette(customPalette); + m_itemDelegate = new LogWidgetItemDelegate(this); + setSelectionMode(QAbstractItemView::MultiSelection); + QAbstractItemDelegate *delegate = itemDelegate(); + if(delegate) { + delete delegate; + } + setItemDelegate(m_itemDelegate); + setMouseTracking(true); +} + +LogWidget::~LogWidget() +{ +} + +bool LogWidget::isShowingOutput() const +{ + return (count() > 0); +} + +void LogWidget::highlight(const OutputInfo& info, bool startFromBottom) +{ + for(int i = 0; i < count(); ++i) { + QListWidgetItem *listItem = item(startFromBottom ? count() - 1 - i : i); + QVariant variant = listItem->data(Qt::UserRole); + if(!variant.isValid()) { + continue; + } + OutputInfo info2 = variant.value(); + if(info == info2) { + deselectAllItems(); + scrollToItem(listItem); + listItem->setSelected(true); + break; + } + } +} + +void LogWidget::slotItemClicked(QListWidgetItem *item) +{ + QVariant variant = item->data(Qt::UserRole); + if(!variant.isValid()) { + return; + } + + OutputInfo info = variant.value(); + + emit(outputInfoSelected(info)); +} + +void LogWidget::enterEvent(QEvent *) +{ + adaptMouseCursor(mapFromGlobal(QCursor::pos())); +} + +void LogWidget::leaveEvent(QEvent *) +{ + unsetCursor(); +} + +void LogWidget::mouseMoveEvent(QMouseEvent* event) +{ + QPoint p = event->pos(); + adaptMouseCursor(p); +} + +void LogWidget::adaptMouseCursor(const QPoint& p) +{ + QListWidgetItem *item = itemAt(p); + if(!item) { + unsetCursor(); + return; + } + + QVariant variant = item->data(Qt::UserRole); + if(variant.isValid()) { + setCursor(Qt::PointingHandCursor); + } + else { + unsetCursor(); + } +} + +void LogWidget::keyPressEvent(QKeyEvent *event) +{ + QAbstractScrollArea::keyPressEvent(event); +} + +void LogWidget::deselectAllItems() +{ + QList items = selectedItems(); + for(QList::iterator i = items.begin(); + i != items.end(); ++i) { + QListWidgetItem *item = *i; + item->setSelected(false); + } +} + +void LogWidget::printMessage(const QString& message) +{ + KILE_DEBUG_MAIN << "\t" << message; + printMessage(-1, message, QString()); +} + +void LogWidget::printMessage(int type, const QString& message, const QString &tool, + const OutputInfo& outputInfo, bool allowSelection, + bool scroll) +{ + QStringList messageList = message.split('\n'); + for(QStringList::iterator it = messageList.begin(); it != messageList.end(); ++it) { + printMessageLine(type, *it, tool, outputInfo, allowSelection, scroll); + } +} + +void LogWidget::printMessageLine(int type, const QString& message, const QString &tool, + const OutputInfo& outputInfo, bool allowSelection, + bool scroll) +{ + if(type == KileTool::Error) { + KILE_DEBUG_MAIN << "showing error message emitted"; + emit showingErrorMessage(this); + } + + QString myMsg = message.toHtmlEscaped(); + QString fontColor; + + switch(type) { + case KileTool::Warning : + fontColor = ""; + break; + case KileTool::ProblemWarning : + if(KileConfig::hideProblemWarning()) { + return; + } + fontColor = ""; + break; + case KileTool::Error: // fall through + case KileTool::ProblemError: + fontColor = ""; + break; + case KileTool::ProblemBadBox: + if (KileConfig::hideProblemBadBox()) { + return; + } + { + // 'KColorScheme::scheme' doesn't take the background colour into account, so we have to do it manually + const QColor color = (KStatefulBrush(KColorScheme::View, KColorScheme::NormalBackground).brush(this).color().lightnessF() > 0.5) + ? KColorScheme::shade(KStatefulBrush(KColorScheme::View, KColorScheme::NeutralText).brush(this).color(), KColorScheme::DarkShade) + : KColorScheme::shade(KStatefulBrush(KColorScheme::View, KColorScheme::NeutralText).brush(this).color(), KColorScheme::LightShade); + fontColor = ""; + } + break; + default: + fontColor = ""; + break; + } + + QListWidgetItem *item = new QListWidgetItem(this); + + if(tool.isEmpty()) { + item->setText(fontColor + myMsg + ""); + } + else { + item->setText(fontColor + "[" + tool + "] " + myMsg + ""); + } + + + if(outputInfo.isValid()) { + item->setData(Qt::UserRole, QVariant::fromValue(outputInfo)); + } + if(!allowSelection) { + // Don't allow the user to manually select this item + item->setFlags(item->flags() & ~Qt::ItemIsSelectable); + } + + if((type == KileTool::Error || type == KileTool::ProblemError) + && !m_firstErrorMessgeInToolLog.isValid()) { + m_firstErrorMessgeInToolLog = outputInfo; + } + + if(scroll) { + scrollToItem(item); + } +} + +void LogWidget::printProblem(int type, const QString& problem, const OutputInfo& outputInfo) +{ + KILE_DEBUG_MAIN << "\t" << problem; + printMessage(type, problem, QString(), outputInfo); +} + +void LogWidget::printProblems(const QList& list) +{ + setUpdatesEnabled(false); + for(QList::const_iterator i = list.begin(); i != list.end(); ++i) { + printMessage((*i).type, (*i).message, QString(), (*i).outputInfo, false, false); + } + setUpdatesEnabled(true); + scrollToBottom(); +} + +void LogWidget::addEmptyLine() +{ + printMessage(-1, QString(), QString()); +} + +void LogWidget::copy() +{ + QList selectedList = selectedItems(); + QString toCopy; + int maxIndex = 0; + QHash itemHash; + for(QList::iterator i = selectedList.begin(); + i != selectedList.end(); ++i) { + QListWidgetItem* item = *i; + int row = indexFromItem(item).row(); + itemHash[row] = item; + maxIndex = qMax(maxIndex, row); + } + for(int i = 0; i <= maxIndex; ++i) { + QHash::iterator it = itemHash.find(i); + if(it != itemHash.end()) { + toCopy += (*it)->data(Qt::UserRole).value().message() + '\n'; + } + } + if(!toCopy.isEmpty()) { + QApplication::clipboard()->setText(toCopy); + } +} + +void LogWidget::startToolLogOutput() +{ + m_firstErrorMessgeInToolLog = OutputInfo(); +} + +void LogWidget::endToolLogOutput() +{ + if(m_firstErrorMessgeInToolLog.isValid()) { + highlight(m_firstErrorMessgeInToolLog, true); + } +} + +void LogWidget::contextMenuEvent(QContextMenuEvent *event) +{ + QMenu popup; + + QAction *action = KStandardAction::copy(this, SLOT(copy()), this); + action->setShortcuts(QList()); + if(selectedItems().size() == 0) { + action->setEnabled(false); + } + popup.addAction(action); + + action = KStandardAction::selectAll(this, SLOT(selectAll()), this); + action->setShortcuts(QList()); + if(!containsSelectableItems()) { + action->setEnabled(false); + } + popup.addAction(action); + + + if(!(m_popupType & NoHideActions)) { + popup.addSeparator(); + + action = new QAction(i18n("Hide &Bad Boxes"), &popup); + action->setCheckable(true); + action->setChecked(KileConfig::hideProblemBadBox()); + connect(action, SIGNAL(triggered()), this, SLOT(toggleBadBoxHiding())); + popup.addAction(action); + + action = new QAction(i18n("Hide (La)TeX &Warnings"), &popup); + action->setCheckable(true); + action->setChecked(KileConfig::hideProblemWarning()); + connect(action, SIGNAL(triggered()), this, SLOT(toggleWarningsHiding())); + popup.addAction(action); + } + + popup.exec(event->globalPos()); +} + +void LogWidget::toggleBadBoxHiding() +{ + KileConfig::setHideProblemBadBox(!KileConfig::hideProblemBadBox()); +} + +void LogWidget::toggleWarningsHiding() +{ + KileConfig::setHideProblemWarning(!KileConfig::hideProblemWarning()); +} + +bool LogWidget::containsSelectableItems() const +{ + for(int i = 0; i < count(); ++i) { + if(item(i)->flags() & Qt::ItemIsSelectable) { + return true; + } + } + + return false; +} } diff --git a/src/widgets/logwidget.h b/src/widgets/logwidget.h index e17e9d38..90833711 100644 --- a/src/widgets/logwidget.h +++ b/src/widgets/logwidget.h @@ -1,120 +1,120 @@ /************************************************************************************* Copyright (C) 2003 by Jeroen Wijnhout (Jeroen.Wijnhout@kdemail.net) 2008-2012 by Michel Ludwig (michel.ludwig@kdemail.net) *************************************************************************************/ /*************************************************************************** * * * 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. * * * ****************************************************************************/ #ifndef LOGWIDGET_H #define LOGWIDGET_H #include #include #include #include "outputinfo.h" class QString; class QPoint; class KileInfo; class QUrl; namespace KileWidget { - class LogWidgetItemDelegate : public QItemDelegate - { - Q_OBJECT +class LogWidgetItemDelegate : public QItemDelegate +{ + Q_OBJECT - public: - LogWidgetItemDelegate(QObject* parent = Q_NULLPTR); +public: + LogWidgetItemDelegate(QObject* parent = Q_NULLPTR); - virtual QSize sizeHint(const QStyleOptionViewItem& option, - const QModelIndex& index) const; + virtual QSize sizeHint(const QStyleOptionViewItem& option, + const QModelIndex& index) const; - protected: - virtual void paint(QPainter* painter, - const QStyleOptionViewItem& option, - const QModelIndex & index) const; +protected: + virtual void paint(QPainter* painter, + const QStyleOptionViewItem& option, + const QModelIndex & index) const; - QTextDocument* constructTextDocument(const QModelIndex& index) const; - }; + QTextDocument* constructTextDocument(const QModelIndex& index) const; +}; - class LogWidget : public QListWidget - { - Q_OBJECT +class LogWidget : public QListWidget +{ + Q_OBJECT - public: - struct ProblemInformation { - int type; - QString message; - OutputInfo outputInfo; - }; +public: + struct ProblemInformation { + int type; + QString message; + OutputInfo outputInfo; + }; - enum PopupType { AllPopupActions = 0, NoHideActions = 1}; + enum PopupType { AllPopupActions = 0, NoHideActions = 1}; - LogWidget(PopupType popupType = AllPopupActions, QWidget *parent = Q_NULLPTR, const char *name = Q_NULLPTR); - ~LogWidget(); + LogWidget(PopupType popupType = AllPopupActions, QWidget *parent = Q_NULLPTR, const char *name = Q_NULLPTR); + ~LogWidget(); - bool isShowingOutput() const; + bool isShowingOutput() const; - public Q_SLOTS: - void highlight(const OutputInfo& info, bool startFromBottom = false); +public Q_SLOTS: + void highlight(const OutputInfo& info, bool startFromBottom = false); - void printMessage(const QString& message); - void printMessage(int type, const QString& message, const QString &tool = "Kile", - const OutputInfo& outputInfo = OutputInfo(), bool allowSelection = false, - bool scroll = true); - void printProblem(int type, const QString& problem, const OutputInfo& outputInfo = OutputInfo()); - void printProblems(const QList& list); + void printMessage(const QString& message); + void printMessage(int type, const QString& message, const QString &tool = "Kile", + const OutputInfo& outputInfo = OutputInfo(), bool allowSelection = false, + bool scroll = true); + void printProblem(int type, const QString& problem, const OutputInfo& outputInfo = OutputInfo()); + void printProblems(const QList& list); - void addEmptyLine(); + void addEmptyLine(); - void copy(); + void copy(); - void startToolLogOutput(); - void endToolLogOutput(); + void startToolLogOutput(); + void endToolLogOutput(); - Q_SIGNALS: - void showingErrorMessage(QWidget*); - void outputInfoSelected(const OutputInfo&); +Q_SIGNALS: + void showingErrorMessage(QWidget*); + void outputInfoSelected(const OutputInfo&); - protected: - virtual void enterEvent(QEvent *event); - virtual void leaveEvent(QEvent *event); - virtual void mouseMoveEvent(QMouseEvent* event); +protected: + virtual void enterEvent(QEvent *event); + virtual void leaveEvent(QEvent *event); + virtual void mouseMoveEvent(QMouseEvent* event); - void adaptMouseCursor(const QPoint& p); - void keyPressEvent(QKeyEvent *event); + void adaptMouseCursor(const QPoint& p); + void keyPressEvent(QKeyEvent *event); - virtual void contextMenuEvent(QContextMenuEvent *event); + virtual void contextMenuEvent(QContextMenuEvent *event); - void printMessageLine(int type, const QString& message, const QString &tool = "Kile", - const OutputInfo& outputInfo = OutputInfo(), bool allowSelection = false, - bool scroll = true); + void printMessageLine(int type, const QString& message, const QString &tool = "Kile", + const OutputInfo& outputInfo = OutputInfo(), bool allowSelection = false, + bool scroll = true); - protected Q_SLOTS: - void slotItemClicked(QListWidgetItem *item); - void deselectAllItems(); +protected Q_SLOTS: + void slotItemClicked(QListWidgetItem *item); + void deselectAllItems(); - void toggleBadBoxHiding(); - void toggleWarningsHiding(); + void toggleBadBoxHiding(); + void toggleWarningsHiding(); - private: - int m_popupType; - int m_idWarning, m_idBadBox; - LogWidgetItemDelegate *m_itemDelegate; - OutputInfo m_firstErrorMessgeInToolLog; +private: + int m_popupType; + int m_idWarning, m_idBadBox; + LogWidgetItemDelegate *m_itemDelegate; + OutputInfo m_firstErrorMessgeInToolLog; - bool containsSelectableItems() const; - }; + bool containsSelectableItems() const; +}; } #endif diff --git a/src/widgets/maintoolconfigwidget.cpp b/src/widgets/maintoolconfigwidget.cpp index 790d39a3..777695f6 100644 --- a/src/widgets/maintoolconfigwidget.cpp +++ b/src/widgets/maintoolconfigwidget.cpp @@ -1,24 +1,24 @@ /************************************************************************** * Copyright (C) 2007 by Michel Ludwig (michel.ludwig@kdemail.net) * ***************************************************************************/ /************************************************************************** * * * 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. * * * ***************************************************************************/ #include "widgets/maintoolconfigwidget.h" ToolConfigWidget::ToolConfigWidget(QWidget *parent) : QWidget(parent) { - setupUi(this); + setupUi(this); } ToolConfigWidget::~ToolConfigWidget() { } diff --git a/src/widgets/maintoolconfigwidget.h b/src/widgets/maintoolconfigwidget.h index 3286d535..a07ad081 100644 --- a/src/widgets/maintoolconfigwidget.h +++ b/src/widgets/maintoolconfigwidget.h @@ -1,30 +1,30 @@ /************************************************************************** * Copyright (C) 2007 by Michel Ludwig (michel.ludwig@kdemail.net) * ***************************************************************************/ /************************************************************************** * * * 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. * * * ***************************************************************************/ #ifndef MAINTOOLCONFIGWIDGET_H #define MAINTOOLCONFIGWIDGET_H #include #include "ui_maintoolconfigwidget.h" class ToolConfigWidget : public QWidget, public Ui::ToolConfigWidget { - Q_OBJECT + Q_OBJECT - public: - ToolConfigWidget(QWidget *parent = 0); - ~ToolConfigWidget(); +public: + ToolConfigWidget(QWidget *parent = 0); + ~ToolConfigWidget(); }; #endif diff --git a/src/widgets/newdocumentwidget.cpp b/src/widgets/newdocumentwidget.cpp index e17b775c..19cf7bc7 100644 --- a/src/widgets/newdocumentwidget.cpp +++ b/src/widgets/newdocumentwidget.cpp @@ -1,24 +1,24 @@ /************************************************************************** * Copyright (C) 2007 by Michel Ludwig (michel.ludwig@kdemail.net) * ***************************************************************************/ /************************************************************************** * * * 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. * * * ***************************************************************************/ #include "widgets/newdocumentwidget.h" NewDocumentWidget::NewDocumentWidget(QWidget *parent) : QWidget(parent) { - setupUi(this); + setupUi(this); } NewDocumentWidget::~NewDocumentWidget() { } diff --git a/src/widgets/newdocumentwidget.h b/src/widgets/newdocumentwidget.h index 4b9aefb6..45db8bed 100644 --- a/src/widgets/newdocumentwidget.h +++ b/src/widgets/newdocumentwidget.h @@ -1,30 +1,30 @@ /************************************************************************** * Copyright (C) 2007 by Michel Ludwig (michel.ludwig@kdemail.net) * ***************************************************************************/ /************************************************************************** * * * 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. * * * ***************************************************************************/ #ifndef NEWDOCUMENTWIDGET_H #define NEWDOCUMENTWIDGET_H #include #include "ui_newdocumentwidget.h" class NewDocumentWidget : public QWidget, public Ui::NewDocumentWidget { - Q_OBJECT + Q_OBJECT - public: - NewDocumentWidget(QWidget *parent = 0); - ~NewDocumentWidget(); +public: + NewDocumentWidget(QWidget *parent = 0); + ~NewDocumentWidget(); }; #endif diff --git a/src/widgets/outputview.cpp b/src/widgets/outputview.cpp index ce4b0919..f3d43241 100644 --- a/src/widgets/outputview.cpp +++ b/src/widgets/outputview.cpp @@ -1,62 +1,62 @@ /************************************************************************************* begin : Sun Dec 21 2003 copyright : (C) 2003 by Jeroen Wijnhout (Jeroen.Wijnhout@kdemail.net) (C) 2009-2012 by Michel Ludwig (michel.ludwig@kdemail.net) *************************************************************************************/ /*************************************************************************** * * * 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. * * * ****************************************************************************/ #include "widgets/outputview.h" #include #include "kiledebug.h" namespace KileWidget { OutputView::OutputView(QWidget *parent) : KTextEdit(parent) { - setReadOnly(true); - setAcceptRichText(false); + setReadOnly(true); + setAcceptRichText(false); } OutputView::~OutputView() { } void OutputView::receive(const QString& str) { - static QString line; - - //find newline symbol - //only output if we have receive one or more - //full lines of text - int newLineAt = str.lastIndexOf('\n'); - if(newLineAt != -1) { - line += str.left(newLineAt); //don't copy the newline char - append(line); - line = str.mid(newLineAt + 1); - } - else { - line += str; - } + static QString line; + + //find newline symbol + //only output if we have receive one or more + //full lines of text + int newLineAt = str.lastIndexOf('\n'); + if(newLineAt != -1) { + line += str.left(newLineAt); //don't copy the newline char + append(line); + line = str.mid(newLineAt + 1); + } + else { + line += str; + } } void OutputView::paintEvent(QPaintEvent *ev) { - QPalette customPalette = palette(); - KColorScheme::adjustBackground(customPalette, KColorScheme::NormalBackground, - QPalette::Base, KColorScheme::View); - setPalette(customPalette); - KTextEdit::paintEvent(ev); + QPalette customPalette = palette(); + KColorScheme::adjustBackground(customPalette, KColorScheme::NormalBackground, + QPalette::Base, KColorScheme::View); + setPalette(customPalette); + KTextEdit::paintEvent(ev); } } diff --git a/src/widgets/outputview.h b/src/widgets/outputview.h index 575a13b4..06d6f605 100644 --- a/src/widgets/outputview.h +++ b/src/widgets/outputview.h @@ -1,39 +1,39 @@ /************************************************************************************** begin : Sun Dec 21 2003 copyright : (C) 2003 by Jeroen Wijnhout (Jeroen.Wijnhout@kdemail.net) (C) 2009 by Michel Ludwig (michel.ludwig@kdemail.net) **************************************************************************************/ /*************************************************************************** * * * 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. * * * ****************************************************************************/ #ifndef OUTPUTVIEW_H #define OUTPUTVIEW_H #include namespace KileWidget { class OutputView : public KTextEdit { - Q_OBJECT + Q_OBJECT - public: - OutputView(QWidget *parent); - ~OutputView(); +public: + OutputView(QWidget *parent); + ~OutputView(); - public Q_SLOTS: - void receive(const QString &); +public Q_SLOTS: + void receive(const QString &); - protected: - virtual void paintEvent(QPaintEvent *ev); +protected: + virtual void paintEvent(QPaintEvent *ev); }; } #endif diff --git a/src/widgets/previewconfigwidget.cpp b/src/widgets/previewconfigwidget.cpp index 026d1ad4..d60bedf3 100644 --- a/src/widgets/previewconfigwidget.cpp +++ b/src/widgets/previewconfigwidget.cpp @@ -1,351 +1,351 @@ /******************************************************************************** * Copyright (C) 2005-2006 by Holger Danielsson (holger.danielsson@t-online.de) * * (C) 2011 by Michel Ludwig (michel.ludwig@kdemail.net) * ********************************************************************************/ /*************************************************************************** * * * 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. * * * ***************************************************************************/ #include "previewconfigwidget.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "kileconfig.h" #include "kiledebug.h" KileWidgetPreviewConfig::KileWidgetPreviewConfig(KConfig *config, KileTool::QuickPreview *preview, QWidget *parent, const char *name) - : QWidget(parent), - m_config(config), - m_preview(preview) + : QWidget(parent), + m_config(config), + m_preview(preview) { - setObjectName(name); - // Layout - QVBoxLayout *vbox = new QVBoxLayout(); - vbox->setMargin(0); + setObjectName(name); + // Layout + QVBoxLayout *vbox = new QVBoxLayout(); + vbox->setMargin(0); //TODO PORT QT5 vbox->setSpacing(QDialog::spacingHint()); - setLayout(vbox); + setLayout(vbox); - QGroupBox *groupbox = new QGroupBox(i18n("Quick Preview in a Separate Window"), this); - groupbox->setFlat(false); - QGridLayout *groupboxLayout = new QGridLayout(); + QGroupBox *groupbox = new QGroupBox(i18n("Quick Preview in a Separate Window"), this); + groupbox->setFlat(false); + QGridLayout *groupboxLayout = new QGridLayout(); //TODO PORT QT5 groupboxLayout->setMargin(QDialog::marginHint()); //TODO PORT QT5 groupboxLayout->setSpacing(QDialog::spacingHint()); - groupboxLayout->setAlignment(Qt::AlignTop); - groupbox->setLayout(groupboxLayout); - - QLabel *label = new QLabel(i18n("Select a configuration:"), groupbox); - label->setObjectName("label"); - m_combobox = new KComboBox(false, groupbox); - m_combobox->setObjectName("combobox"); - - groupboxLayout->addWidget(label, 0, 0); - groupboxLayout->addWidget(m_combobox, 0, 2); - groupboxLayout->setColumnMinimumWidth(1, 8); - groupboxLayout->setColumnStretch(3, 1); - - QGroupBox *gbResolution = new QGroupBox(i18n("Quick Preview in Bottom Bar"), this); - gbResolution->setFlat(false); - QGridLayout *resLayout = new QGridLayout(); + groupboxLayout->setAlignment(Qt::AlignTop); + groupbox->setLayout(groupboxLayout); + + QLabel *label = new QLabel(i18n("Select a configuration:"), groupbox); + label->setObjectName("label"); + m_combobox = new KComboBox(false, groupbox); + m_combobox->setObjectName("combobox"); + + groupboxLayout->addWidget(label, 0, 0); + groupboxLayout->addWidget(m_combobox, 0, 2); + groupboxLayout->setColumnMinimumWidth(1, 8); + groupboxLayout->setColumnStretch(3, 1); + + QGroupBox *gbResolution = new QGroupBox(i18n("Quick Preview in Bottom Bar"), this); + gbResolution->setFlat(false); + QGridLayout *resLayout = new QGridLayout(); //TODO PORT QT5 resLayout->setMargin(QDialog::marginHint()); //TODO PORT QT5 resLayout->setSpacing(QDialog::spacingHint()); - resLayout->setAlignment(Qt::AlignTop); - gbResolution->setLayout(resLayout); - - QLabel *resLabel = new QLabel(i18n("&Resolution:"), gbResolution); - m_leDvipngResolution = new QLineEdit(gbResolution); - QLabel *resDpi = new QLabel(i18n("dpi"), gbResolution); - QLabel *resAllowed = new QLabel(i18n("(allowed values: 30-1000 dpi)"), gbResolution); - - QLabel *backgroundColorLabel = new QLabel(i18n("&Background Color:"), gbResolution); - m_backgroundColorButton = new KColorButton(gbResolution); - m_backgroundColorButton->setDefaultColor(QColor(Qt::white)); - backgroundColorLabel->setBuddy(m_backgroundColorButton); - // set validator - QValidator* validator = new QIntValidator(30, 1000, this); - m_leDvipngResolution->setValidator(validator); - resLabel->setBuddy(m_leDvipngResolution); - - QString sep = "    "; - QString title = i18n("Kile supports three kinds of conversion to png images"); - QString tool1 = i18n("dvi --> png") + sep + i18n("(uses dvipng)"); - QString tool2 = i18n("dvi --> ps --> png") + sep + i18n("(uses dvips/convert)"); - QString tool3 = i18n("pdf --> png") + sep + i18n("(uses convert)"); - QString description = QString("%1:
  • %2
  • %3
  • %4
").arg(title).arg(tool1).arg(tool2).arg(tool3); - - QLabel *labelDescription = new QLabel(description, gbResolution); - QLabel *labelDvipng = new QLabel(i18n("dvipng:"), gbResolution); - QLabel *labelConvert = new QLabel(i18n("convert:"), gbResolution); - m_lbDvipng = new QLabel(gbResolution); - m_lbConvert = new QLabel(gbResolution); - - resLayout->addWidget(resLabel, 0, 0); - resLayout->addWidget(m_leDvipngResolution, 0, 2); - resLayout->addWidget(resDpi, 0, 3); - resLayout->addWidget(resAllowed, 0, 5, Qt::AlignLeft); - resLayout->addWidget(backgroundColorLabel, 1, 0); - resLayout->addWidget(m_backgroundColorButton, 1, 2); - resLayout->addWidget(labelDescription, 2, 0, 1, 6); - resLayout->addWidget(labelDvipng, 3, 0); - resLayout->addWidget(m_lbDvipng, 3, 2); - resLayout->addWidget(labelConvert, 4, 0); - resLayout->addWidget(m_lbConvert, 4, 2); - resLayout->setColumnMinimumWidth(1, 8); - resLayout->setColumnMinimumWidth(4, 24); - resLayout->setColumnStretch(5, 1); - - m_gbPreview = new QGroupBox(i18n("Properties"), this); - m_gbPreview->setFlat(false); - m_gbPreview->setObjectName("gbpreview"); - QGridLayout *previewLayout = new QGridLayout(); + resLayout->setAlignment(Qt::AlignTop); + gbResolution->setLayout(resLayout); + + QLabel *resLabel = new QLabel(i18n("&Resolution:"), gbResolution); + m_leDvipngResolution = new QLineEdit(gbResolution); + QLabel *resDpi = new QLabel(i18n("dpi"), gbResolution); + QLabel *resAllowed = new QLabel(i18n("(allowed values: 30-1000 dpi)"), gbResolution); + + QLabel *backgroundColorLabel = new QLabel(i18n("&Background Color:"), gbResolution); + m_backgroundColorButton = new KColorButton(gbResolution); + m_backgroundColorButton->setDefaultColor(QColor(Qt::white)); + backgroundColorLabel->setBuddy(m_backgroundColorButton); + // set validator + QValidator* validator = new QIntValidator(30, 1000, this); + m_leDvipngResolution->setValidator(validator); + resLabel->setBuddy(m_leDvipngResolution); + + QString sep = "    "; + QString title = i18n("Kile supports three kinds of conversion to png images"); + QString tool1 = i18n("dvi --> png") + sep + i18n("(uses dvipng)"); + QString tool2 = i18n("dvi --> ps --> png") + sep + i18n("(uses dvips/convert)"); + QString tool3 = i18n("pdf --> png") + sep + i18n("(uses convert)"); + QString description = QString("%1:
  • %2
  • %3
  • %4
").arg(title).arg(tool1).arg(tool2).arg(tool3); + + QLabel *labelDescription = new QLabel(description, gbResolution); + QLabel *labelDvipng = new QLabel(i18n("dvipng:"), gbResolution); + QLabel *labelConvert = new QLabel(i18n("convert:"), gbResolution); + m_lbDvipng = new QLabel(gbResolution); + m_lbConvert = new QLabel(gbResolution); + + resLayout->addWidget(resLabel, 0, 0); + resLayout->addWidget(m_leDvipngResolution, 0, 2); + resLayout->addWidget(resDpi, 0, 3); + resLayout->addWidget(resAllowed, 0, 5, Qt::AlignLeft); + resLayout->addWidget(backgroundColorLabel, 1, 0); + resLayout->addWidget(m_backgroundColorButton, 1, 2); + resLayout->addWidget(labelDescription, 2, 0, 1, 6); + resLayout->addWidget(labelDvipng, 3, 0); + resLayout->addWidget(m_lbDvipng, 3, 2); + resLayout->addWidget(labelConvert, 4, 0); + resLayout->addWidget(m_lbConvert, 4, 2); + resLayout->setColumnMinimumWidth(1, 8); + resLayout->setColumnMinimumWidth(4, 24); + resLayout->setColumnStretch(5, 1); + + m_gbPreview = new QGroupBox(i18n("Properties"), this); + m_gbPreview->setFlat(false); + m_gbPreview->setObjectName("gbpreview"); + QGridLayout *previewLayout = new QGridLayout(); //TODO PORT QT5 previewLayout->setMargin(QDialog::marginHint()); //TODO PORT QT5 previewLayout->setSpacing(QDialog::spacingHint()); - previewLayout->setAlignment(Qt::AlignTop); - m_gbPreview->setLayout(previewLayout); - - QLabel *labelPreviewWidget = new QLabel(i18n("Show preview in bottom bar:"), m_gbPreview); - QLabel *labelPreviewType = new QLabel(i18n("Conversion to image:"), m_gbPreview); - QLabel *labelSelection = new QLabel(i18n("Selection:"), m_gbPreview); - QLabel *labelEnvironment = new QLabel(i18n("Environment:"), m_gbPreview); - QLabel *labelMathgroup = new QLabel(i18n("Mathgroup:"), m_gbPreview); - QLabel *labelSubdocument1 = new QLabel(i18n("Subdocument:"), m_gbPreview); - QLabel *labelSubdocument2 = new QLabel(i18n("Not available, opens always in a separate window."), m_gbPreview); - m_cbSelection = new QCheckBox(m_gbPreview); - m_cbEnvironment = new QCheckBox(m_gbPreview); - m_cbMathgroup = new QCheckBox(m_gbPreview); - m_coSelection = new KComboBox(false, m_gbPreview); - m_coEnvironment = new KComboBox(false, m_gbPreview); - m_coMathgroup = new KComboBox(false, m_gbPreview); - - previewLayout->addWidget(labelPreviewWidget, 0, 0, 1, 3); - previewLayout->addWidget(labelPreviewType, 0, 4); - previewLayout->addWidget(labelSelection, 1, 0); - previewLayout->addWidget(m_cbSelection, 1, 2); - previewLayout->addWidget(m_coSelection, 1, 4); - previewLayout->addWidget(labelEnvironment, 2, 0); - previewLayout->addWidget(m_cbEnvironment, 2, 2); - previewLayout->addWidget(m_coEnvironment, 2, 4); - previewLayout->addWidget(labelMathgroup, 3, 0); - previewLayout->addWidget(m_cbMathgroup, 3, 2); - previewLayout->addWidget(m_coMathgroup, 3, 4); - previewLayout->addWidget(labelSubdocument1, 4, 0); - previewLayout->addWidget(labelSubdocument2, 4, 2, 1, 4, Qt::AlignLeft); - previewLayout->setRowMinimumHeight(0, 3 * labelPreviewWidget->sizeHint().height() / 2); - previewLayout->setRowMinimumHeight(3, m_coEnvironment->sizeHint().height()); - previewLayout->setColumnMinimumWidth(1, 12); - previewLayout->setColumnMinimumWidth(3, 40); - previewLayout->setColumnStretch(5, 1); - - vbox->addWidget(groupbox); - vbox->addWidget(gbResolution); - vbox->addWidget(m_gbPreview); - vbox->addStretch(); - - connect(m_cbEnvironment, SIGNAL(clicked()), this, SLOT(updateConversionTools())); - connect(m_cbSelection, SIGNAL(clicked()), this, SLOT(updateConversionTools())); - connect(m_cbMathgroup, SIGNAL(clicked()), this, SLOT(updateConversionTools())); + previewLayout->setAlignment(Qt::AlignTop); + m_gbPreview->setLayout(previewLayout); + + QLabel *labelPreviewWidget = new QLabel(i18n("Show preview in bottom bar:"), m_gbPreview); + QLabel *labelPreviewType = new QLabel(i18n("Conversion to image:"), m_gbPreview); + QLabel *labelSelection = new QLabel(i18n("Selection:"), m_gbPreview); + QLabel *labelEnvironment = new QLabel(i18n("Environment:"), m_gbPreview); + QLabel *labelMathgroup = new QLabel(i18n("Mathgroup:"), m_gbPreview); + QLabel *labelSubdocument1 = new QLabel(i18n("Subdocument:"), m_gbPreview); + QLabel *labelSubdocument2 = new QLabel(i18n("Not available, opens always in a separate window."), m_gbPreview); + m_cbSelection = new QCheckBox(m_gbPreview); + m_cbEnvironment = new QCheckBox(m_gbPreview); + m_cbMathgroup = new QCheckBox(m_gbPreview); + m_coSelection = new KComboBox(false, m_gbPreview); + m_coEnvironment = new KComboBox(false, m_gbPreview); + m_coMathgroup = new KComboBox(false, m_gbPreview); + + previewLayout->addWidget(labelPreviewWidget, 0, 0, 1, 3); + previewLayout->addWidget(labelPreviewType, 0, 4); + previewLayout->addWidget(labelSelection, 1, 0); + previewLayout->addWidget(m_cbSelection, 1, 2); + previewLayout->addWidget(m_coSelection, 1, 4); + previewLayout->addWidget(labelEnvironment, 2, 0); + previewLayout->addWidget(m_cbEnvironment, 2, 2); + previewLayout->addWidget(m_coEnvironment, 2, 4); + previewLayout->addWidget(labelMathgroup, 3, 0); + previewLayout->addWidget(m_cbMathgroup, 3, 2); + previewLayout->addWidget(m_coMathgroup, 3, 4); + previewLayout->addWidget(labelSubdocument1, 4, 0); + previewLayout->addWidget(labelSubdocument2, 4, 2, 1, 4, Qt::AlignLeft); + previewLayout->setRowMinimumHeight(0, 3 * labelPreviewWidget->sizeHint().height() / 2); + previewLayout->setRowMinimumHeight(3, m_coEnvironment->sizeHint().height()); + previewLayout->setColumnMinimumWidth(1, 12); + previewLayout->setColumnMinimumWidth(3, 40); + previewLayout->setColumnStretch(5, 1); + + vbox->addWidget(groupbox); + vbox->addWidget(gbResolution); + vbox->addWidget(m_gbPreview); + vbox->addStretch(); + + connect(m_cbEnvironment, SIGNAL(clicked()), this, SLOT(updateConversionTools())); + connect(m_cbSelection, SIGNAL(clicked()), this, SLOT(updateConversionTools())); + connect(m_cbMathgroup, SIGNAL(clicked()), this, SLOT(updateConversionTools())); } //////////////////// read/write configuration //////////////////// void KileWidgetPreviewConfig::readConfig(void) { - setupSeparateWindow(); - setupBottomBar(); - setupProperties(); + setupSeparateWindow(); + setupBottomBar(); + setupProperties(); - updateConversionTools(); + updateConversionTools(); } void KileWidgetPreviewConfig::writeConfig(void) { - KileConfig::setPreviewTask(m_combobox->currentText()); - - bool ok; - QString resolution = m_leDvipngResolution->text(); - int dpi = resolution.toInt(&ok); - if(ok) { - if(dpi < 30) { - resolution = "30"; - } - else { - if(dpi > 1000) { - resolution = "1000"; - } - } - KileConfig::setDvipngResolution(resolution); - } - KileConfig::setPreviewPaneBackgroundColor(m_backgroundColorButton->color()); - if(m_gbPreview->isEnabled()) { - KileConfig::setSelPreviewInWidget(m_cbSelection->isChecked()); - KileConfig::setEnvPreviewInWidget(m_cbEnvironment->isChecked()); - KileConfig::setMathgroupPreviewInWidget(m_cbMathgroup->isChecked()); - } - else { - KileConfig::setEnvPreviewInWidget(false); - KileConfig::setSelPreviewInWidget(false); - KileConfig::setMathgroupPreviewInWidget(false); - } - - KileConfig::setSelPreviewTool(index2tool(m_coSelection->currentIndex())); - KileConfig::setEnvPreviewTool(index2tool(m_coEnvironment->currentIndex())); - KileConfig::setMathgroupPreviewTool(index2tool(m_coMathgroup->currentIndex())); + KileConfig::setPreviewTask(m_combobox->currentText()); + + bool ok; + QString resolution = m_leDvipngResolution->text(); + int dpi = resolution.toInt(&ok); + if(ok) { + if(dpi < 30) { + resolution = "30"; + } + else { + if(dpi > 1000) { + resolution = "1000"; + } + } + KileConfig::setDvipngResolution(resolution); + } + KileConfig::setPreviewPaneBackgroundColor(m_backgroundColorButton->color()); + if(m_gbPreview->isEnabled()) { + KileConfig::setSelPreviewInWidget(m_cbSelection->isChecked()); + KileConfig::setEnvPreviewInWidget(m_cbEnvironment->isChecked()); + KileConfig::setMathgroupPreviewInWidget(m_cbMathgroup->isChecked()); + } + else { + KileConfig::setEnvPreviewInWidget(false); + KileConfig::setSelPreviewInWidget(false); + KileConfig::setMathgroupPreviewInWidget(false); + } + + KileConfig::setSelPreviewTool(index2tool(m_coSelection->currentIndex())); + KileConfig::setEnvPreviewTool(index2tool(m_coEnvironment->currentIndex())); + KileConfig::setMathgroupPreviewTool(index2tool(m_coMathgroup->currentIndex())); } void KileWidgetPreviewConfig::setupSeparateWindow() { - // get all possible tasks for QuickPreview in a separate window - QStringList tasklist; - m_preview->getTaskList(tasklist); - - // split them into group and combobox entry - m_combobox->clear(); - for(int i = 0; i < tasklist.count(); ++i) { - QStringList list = tasklist[i].split('='); - if (m_config->hasGroup(list[0])) { - m_combobox->addItem(list[1]); - } - } - - // set current task - m_combobox->setCurrentIndex(m_combobox->findText(KileConfig::previewTask())); + // get all possible tasks for QuickPreview in a separate window + QStringList tasklist; + m_preview->getTaskList(tasklist); + + // split them into group and combobox entry + m_combobox->clear(); + for(int i = 0; i < tasklist.count(); ++i) { + QStringList list = tasklist[i].split('='); + if (m_config->hasGroup(list[0])) { + m_combobox->addItem(list[1]); + } + } + + // set current task + m_combobox->setCurrentIndex(m_combobox->findText(KileConfig::previewTask())); } void KileWidgetPreviewConfig::setupBottomBar() { - // setup resolution for QuickPreview in bottom bar - m_leDvipngResolution->setText(KileConfig::dvipngResolution()); + // setup resolution for QuickPreview in bottom bar + m_leDvipngResolution->setText(KileConfig::dvipngResolution()); - // setup tools - m_dvipngInstalled = KileConfig::dvipng(); - m_convertInstalled = KileConfig::convert(); + // setup tools + m_dvipngInstalled = KileConfig::dvipng(); + m_convertInstalled = KileConfig::convert(); - m_backgroundColorButton->setColor(KileConfig::previewPaneBackgroundColor()); + m_backgroundColorButton->setColor(KileConfig::previewPaneBackgroundColor()); - m_lbDvipng->setText((m_dvipngInstalled) ? i18n("installed") : i18n("not installed")); - m_lbConvert->setText((m_convertInstalled) ? i18n("installed") : i18n("not installed")); + m_lbDvipng->setText((m_dvipngInstalled) ? i18n("installed") : i18n("not installed")); + m_lbConvert->setText((m_convertInstalled) ? i18n("installed") : i18n("not installed")); } void KileWidgetPreviewConfig::setupProperties() { - // setup properties for QuickPreview - m_cbSelection->setChecked(KileConfig::selPreviewInWidget()); - m_cbEnvironment->setChecked(KileConfig::envPreviewInWidget()); - m_cbMathgroup->setChecked(KileConfig::mathgroupPreviewInWidget()); - - // setup conversion tools - QStringList toollist; - if(m_dvipngInstalled) { - toollist << i18n("dvi --> png"); - } - if(m_convertInstalled) { - toollist << i18n("dvi --> ps --> png"); - toollist << i18n("pdf --> png"); - } - - // setup comboboxes - if(installedTools() == 0) { - m_gbPreview->setEnabled(false); - } - else { - m_coSelection->addItems(toollist); - m_coEnvironment->addItems(toollist); - m_coMathgroup->addItems(toollist); - - m_coSelection->setCurrentIndex(tool2index(KileConfig::selPreviewTool())); - m_coEnvironment->setCurrentIndex(tool2index(KileConfig::envPreviewTool())); - m_coMathgroup->setCurrentIndex(tool2index(KileConfig::mathgroupPreviewTool())); - } + // setup properties for QuickPreview + m_cbSelection->setChecked(KileConfig::selPreviewInWidget()); + m_cbEnvironment->setChecked(KileConfig::envPreviewInWidget()); + m_cbMathgroup->setChecked(KileConfig::mathgroupPreviewInWidget()); + + // setup conversion tools + QStringList toollist; + if(m_dvipngInstalled) { + toollist << i18n("dvi --> png"); + } + if(m_convertInstalled) { + toollist << i18n("dvi --> ps --> png"); + toollist << i18n("pdf --> png"); + } + + // setup comboboxes + if(installedTools() == 0) { + m_gbPreview->setEnabled(false); + } + else { + m_coSelection->addItems(toollist); + m_coEnvironment->addItems(toollist); + m_coMathgroup->addItems(toollist); + + m_coSelection->setCurrentIndex(tool2index(KileConfig::selPreviewTool())); + m_coEnvironment->setCurrentIndex(tool2index(KileConfig::envPreviewTool())); + m_coMathgroup->setCurrentIndex(tool2index(KileConfig::mathgroupPreviewTool())); + } } //////////////////// manage tools //////////////////// // Tool is 0 (dvi->png), 1 (dvi->ps->png) or 2 (pdf->png). // But this may not be valid, when tools are not installed anymore. // So we have to calc a new index for the combobox // available = 0: doesn't matter, everything will be disabled // available = 1: only dvipng, so we use index 0 // available = 2: only convert: 0->0, 1->0, 2->1 // available = 3: dvipng/convert: index is valid int KileWidgetPreviewConfig::tool2index(int tool) { - int result = 0; - - int available = installedTools(); - if(available == 3) { - result = tool; - } - else { - if(available == 2 && tool > 0) { - result = tool - 1; - } - } - - return result; + int result = 0; + + int available = installedTools(); + if(available == 3) { + result = tool; + } + else { + if(available == 2 && tool > 0) { + result = tool - 1; + } + } + + return result; } int KileWidgetPreviewConfig::index2tool(int index) { - int result = 0; - - int available = installedTools(); - if(available == 3) { - result = index; - } - else { - if(available == 2) { - result = index + 1; - } - } - - return result; + int result = 0; + + int available = installedTools(); + if(available == 3) { + result = index; + } + else { + if(available == 2) { + result = index + 1; + } + } + + return result; } // calc installed tools: // - 0 : no tools installed // - 1 : dvipng installed // - 2 : convert installed // - 3 : dvipng/convert installed int KileWidgetPreviewConfig::installedTools() { - int tools = 0; - if(m_dvipngInstalled) { - tools += 1; - } - if(m_convertInstalled) { - tools += 2; - } - - return tools; + int tools = 0; + if(m_dvipngInstalled) { + tools += 1; + } + if(m_convertInstalled) { + tools += 2; + } + + return tools; } void KileWidgetPreviewConfig::updateConversionTools() { - m_coSelection->setEnabled(m_cbSelection->isChecked()); - m_coEnvironment->setEnabled(m_cbEnvironment->isChecked()); - m_coMathgroup->setEnabled(m_cbMathgroup->isChecked()); + m_coSelection->setEnabled(m_cbSelection->isChecked()); + m_coEnvironment->setEnabled(m_cbEnvironment->isChecked()); + m_coMathgroup->setEnabled(m_cbMathgroup->isChecked()); } diff --git a/src/widgets/previewconfigwidget.h b/src/widgets/previewconfigwidget.h index 7f442a62..749ab650 100644 --- a/src/widgets/previewconfigwidget.h +++ b/src/widgets/previewconfigwidget.h @@ -1,69 +1,69 @@ /******************************************************************************** * Copyright (C) 2005-2006 by Holger Danielsson (holger.danielsson@t-online.de) * * (C) 2011 by Michel Ludwig (michel.ludwig@kdemail.net) * ********************************************************************************/ /*************************************************************************** * * * 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. * * * ***************************************************************************/ #ifndef PREVIEWCONFIGWIDGET_H #define PREVIEWCONFIGWIDGET_H #include #include "quickpreview.h" class QCheckBox; class QGroupBox; class QLabel; class QLineEdit; class KColorButton; class KComboBox; class KConfig; /** *@author Holger Danielsson */ class KileWidgetPreviewConfig : public QWidget { - Q_OBJECT - public: - KileWidgetPreviewConfig(KConfig *config, KileTool::QuickPreview *preview, QWidget *parent = 0, const char *name = 0); - ~KileWidgetPreviewConfig() {} + Q_OBJECT +public: + KileWidgetPreviewConfig(KConfig *config, KileTool::QuickPreview *preview, QWidget *parent = 0, const char *name = 0); + ~KileWidgetPreviewConfig() {} - void readConfig(void); - void writeConfig(void); + void readConfig(void); + void writeConfig(void); - private: - KConfig *m_config; - KComboBox *m_combobox; - KileTool::QuickPreview *m_preview; - QLineEdit *m_leDvipngResolution; - QLabel *m_lbDvipng, *m_lbConvert; - QCheckBox *m_cbEnvironment, *m_cbSelection, *m_cbMathgroup; - KComboBox *m_coSelection, *m_coEnvironment, *m_coMathgroup; - QGroupBox *m_gbPreview; - KColorButton *m_backgroundColorButton; +private: + KConfig *m_config; + KComboBox *m_combobox; + KileTool::QuickPreview *m_preview; + QLineEdit *m_leDvipngResolution; + QLabel *m_lbDvipng, *m_lbConvert; + QCheckBox *m_cbEnvironment, *m_cbSelection, *m_cbMathgroup; + KComboBox *m_coSelection, *m_coEnvironment, *m_coMathgroup; + QGroupBox *m_gbPreview; + KColorButton *m_backgroundColorButton; - bool m_dvipngInstalled, m_convertInstalled; + bool m_dvipngInstalled, m_convertInstalled; - int tool2index(int tool); - int index2tool(int index); - int installedTools(); + int tool2index(int tool); + int index2tool(int index); + int installedTools(); - void setupSeparateWindow(); - void setupBottomBar(); - void setupProperties(); + void setupSeparateWindow(); + void setupBottomBar(); + void setupProperties(); - private Q_SLOTS: - void updateConversionTools(); +private Q_SLOTS: + void updateConversionTools(); }; #endif diff --git a/src/widgets/previewwidget.cpp b/src/widgets/previewwidget.cpp index e4531058..c7292dae 100644 --- a/src/widgets/previewwidget.cpp +++ b/src/widgets/previewwidget.cpp @@ -1,242 +1,242 @@ /***************************************************************************** * Copyright (C) 2006 by Mathias Soeken (msoeken@informatik.uni-bremen.de) * * (orginal version of this preview) * * (C) 2011 by Michel Ludwig (michel.ludwig@kdemail.net) * ******************************************************************************/ // dani/2006: // - signal/slot communication // - user-defined resolution of the png image // - add '%res' to the dictionary of KileTools // - install three possible conversion methods: dvipng, dvips/convert for documents // with postscript source and convert for source, which needs the pdftex driver // - preview configuration dialog /*************************************************************************** * * * 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. * * * ***************************************************************************/ #include "widgets/previewwidget.h" #include #include #include #include #include #include #include #include "editorextension.h" #include "errorhandler.h" #include "kileconfig.h" #include "kileinfo.h" #include "kileviewmanager.h" #include "kiletool.h" #include "kiletool_enums.h" #include "quickpreview.h" namespace KileWidget { // We can't use signals/slots in this class as the moc doesn't parse it. // Also, we better keep the declaration and implementation separate as // we might have to move it back at some point. class ImageDisplayWidget : public QWidget { - public: - ImageDisplayWidget(QWidget *parent); - virtual ~ImageDisplayWidget(); +public: + ImageDisplayWidget(QWidget *parent); + virtual ~ImageDisplayWidget(); - void clear(); - void setImageFile(const QString& fileName); + void clear(); + void setImageFile(const QString& fileName); - protected: - void paintEvent(QPaintEvent *event); +protected: + void paintEvent(QPaintEvent *event); - private: - QImage *m_image; +private: + QImage *m_image; }; ImageDisplayWidget::ImageDisplayWidget(QWidget *parent) - : QWidget(parent), - m_image(Q_NULLPTR) + : QWidget(parent), + m_image(Q_NULLPTR) { - setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); + setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); } ImageDisplayWidget::~ImageDisplayWidget() { - delete m_image; + delete m_image; } void ImageDisplayWidget::paintEvent(QPaintEvent * /* event */) { - QPainter p(this); - // draw the background first - p.fillRect(0, 0, width(), height(), KileConfig::previewPaneBackgroundColor()); - // and then the image - if(m_image) { - p.drawImage(3, 3, *m_image); - } + QPainter p(this); + // draw the background first + p.fillRect(0, 0, width(), height(), KileConfig::previewPaneBackgroundColor()); + // and then the image + if(m_image) { + p.drawImage(3, 3, *m_image); + } } void ImageDisplayWidget::clear() { - delete m_image; - m_image = Q_NULLPTR; - setMinimumSize(0, 0); - repaint(); + delete m_image; + m_image = Q_NULLPTR; + setMinimumSize(0, 0); + repaint(); } void ImageDisplayWidget::setImageFile(const QString& fileName) { - if(!m_image) { - delete m_image; - } + if(!m_image) { + delete m_image; + } - m_image = new QImage(fileName); - setMinimumSize(m_image->width() + 6, m_image->height() + 6); - repaint(); + m_image = new QImage(fileName); + setMinimumSize(m_image->width() + 6, m_image->height() + 6); + repaint(); } PreviewWidget::PreviewWidget(KileInfo *info, QWidget *parent, const char *name) - : QScrollArea(parent), m_info(info), m_running(false) + : QScrollArea(parent), m_info(info), m_running(false) { - setObjectName(name); - setFrameStyle(QFrame::StyledPanel | QFrame::Sunken); - setWidgetResizable(true); + setObjectName(name); + setFrameStyle(QFrame::StyledPanel | QFrame::Sunken); + setWidgetResizable(true); - m_imageDisplayWidget = new ImageDisplayWidget(this); - setWidget(m_imageDisplayWidget); + m_imageDisplayWidget = new ImageDisplayWidget(this); + setWidget(m_imageDisplayWidget); } PreviewWidget::~PreviewWidget() { } void PreviewWidget::showActivePreview(const QString &text,const QString &textfilename,int startrow,int previewtype) { - KILE_DEBUG_MAIN << "==PreviewWidget::showActivePreview()=========================="; - m_info->errorHandler()->clearMessages(); - if(m_running || m_info->quickPreview()->isRunning()) { - showError( i18n("There is already a preview running that has to be finished to run this one.") ); - return; - } - - // determine the type of conversion - int conversiontype; - switch(previewtype) { - case KileTool::qpSelection: - conversiontype = KileConfig::selPreviewTool(); - break; - case KileTool::qpEnvironment: - conversiontype = KileConfig::envPreviewTool(); - break; - case KileTool::qpMathgroup: - conversiontype = KileConfig::mathgroupPreviewTool(); - break; - default: // should not happen - conversiontype = pwDvipng; - break; - } - - - // set parameter for these tools - QString tasklist, tool, toolcfg, extension; - if(conversiontype == pwConvert) { - m_conversionTool = "convert"; - tasklist = "PreviewPDFLaTeX,,,,,png"; - tool = "Convert"; - toolcfg = "pdf2png"; - extension = "pdf"; - } - else if(conversiontype == pwDvipsConvert) { - m_conversionTool = "dvips/convert"; - tasklist = "PreviewLaTeX,DVItoPS,dvi2eps,,,png"; - tool = "Convert"; - toolcfg = "eps2png"; - extension = "eps"; - } - else { - m_conversionTool = "dvipng"; - tasklist = "PreviewLaTeX,,,,,png"; - tool = "DVItoPNG"; - toolcfg.clear(); - extension = "dvi"; - } - - if(!m_info->quickPreview()->run(text, textfilename, startrow, tasklist)) { - return; - } - - KileTool::Base *pngConverter = m_info->toolManager()->createTool(tool, toolcfg); - if(!pngConverter) { - showError(i18n("Could not run '%1' for QuickPreview.", tool)); - return; - } - pngConverter->setSource(m_info->quickPreview()->getPreviewFile(extension)); - - // First, we have to disconnect the old done() signal, because this is - // passed immediately to the toolmanager, whichs destroys the tool. This - // means, that all connections, which are done later, will never been called. - disconnect(pngConverter, SIGNAL(done(KileTool::Base*,int,bool)), m_info->toolManager(), SLOT(done(KileTool::Base*,int))); - - // Now we make some new connections, which are called in this sequence: - // 1) when the tool is finished, the preview will be shown - // 2) then the done() signal can be passed to the toolmanager, - // which destroys the tool - connect(pngConverter, SIGNAL(done(KileTool::Base*,int,bool)), this, SLOT(drawImage())); - connect(pngConverter, SIGNAL(done(KileTool::Base*,int,bool)), m_info->toolManager(), SLOT(done(KileTool::Base*,int))); - - // Finally we will send a signal, which will pass the focus from the log window - // to the formula preview (dvipng --> toolmanager --> kile) - // - // Remark: - // It's also possible to use only (!) the destroyed() signal. This must be sent - // to the toolmanager, which passes it over to the kile object. This object can - // call drawImage() and after it, we have to set the focus to the preview widget. - // This can only be done from the kile object, which explains this indirect way. - // - // But i (dani) prefer the chosen way above, because - // - we can distinguish between drawImage() and focusPreview(), which may be - // important some time - // - it is more complicated - connect(pngConverter, SIGNAL(destroyed()), m_info->toolManager(), SIGNAL(previewDone())); - connect(pngConverter, SIGNAL(destroyed()), this, SLOT(toolDestroyed())); - - // Now we are ready to start the process... - m_info->toolManager()->run(pngConverter); - m_running = true; + KILE_DEBUG_MAIN << "==PreviewWidget::showActivePreview()=========================="; + m_info->errorHandler()->clearMessages(); + if(m_running || m_info->quickPreview()->isRunning()) { + showError( i18n("There is already a preview running that has to be finished to run this one.") ); + return; + } + + // determine the type of conversion + int conversiontype; + switch(previewtype) { + case KileTool::qpSelection: + conversiontype = KileConfig::selPreviewTool(); + break; + case KileTool::qpEnvironment: + conversiontype = KileConfig::envPreviewTool(); + break; + case KileTool::qpMathgroup: + conversiontype = KileConfig::mathgroupPreviewTool(); + break; + default: // should not happen + conversiontype = pwDvipng; + break; + } + + + // set parameter for these tools + QString tasklist, tool, toolcfg, extension; + if(conversiontype == pwConvert) { + m_conversionTool = "convert"; + tasklist = "PreviewPDFLaTeX,,,,,png"; + tool = "Convert"; + toolcfg = "pdf2png"; + extension = "pdf"; + } + else if(conversiontype == pwDvipsConvert) { + m_conversionTool = "dvips/convert"; + tasklist = "PreviewLaTeX,DVItoPS,dvi2eps,,,png"; + tool = "Convert"; + toolcfg = "eps2png"; + extension = "eps"; + } + else { + m_conversionTool = "dvipng"; + tasklist = "PreviewLaTeX,,,,,png"; + tool = "DVItoPNG"; + toolcfg.clear(); + extension = "dvi"; + } + + if(!m_info->quickPreview()->run(text, textfilename, startrow, tasklist)) { + return; + } + + KileTool::Base *pngConverter = m_info->toolManager()->createTool(tool, toolcfg); + if(!pngConverter) { + showError(i18n("Could not run '%1' for QuickPreview.", tool)); + return; + } + pngConverter->setSource(m_info->quickPreview()->getPreviewFile(extension)); + + // First, we have to disconnect the old done() signal, because this is + // passed immediately to the toolmanager, whichs destroys the tool. This + // means, that all connections, which are done later, will never been called. + disconnect(pngConverter, SIGNAL(done(KileTool::Base*,int,bool)), m_info->toolManager(), SLOT(done(KileTool::Base*,int))); + + // Now we make some new connections, which are called in this sequence: + // 1) when the tool is finished, the preview will be shown + // 2) then the done() signal can be passed to the toolmanager, + // which destroys the tool + connect(pngConverter, SIGNAL(done(KileTool::Base*,int,bool)), this, SLOT(drawImage())); + connect(pngConverter, SIGNAL(done(KileTool::Base*,int,bool)), m_info->toolManager(), SLOT(done(KileTool::Base*,int))); + + // Finally we will send a signal, which will pass the focus from the log window + // to the formula preview (dvipng --> toolmanager --> kile) + // + // Remark: + // It's also possible to use only (!) the destroyed() signal. This must be sent + // to the toolmanager, which passes it over to the kile object. This object can + // call drawImage() and after it, we have to set the focus to the preview widget. + // This can only be done from the kile object, which explains this indirect way. + // + // But i (dani) prefer the chosen way above, because + // - we can distinguish between drawImage() and focusPreview(), which may be + // important some time + // - it is more complicated + connect(pngConverter, SIGNAL(destroyed()), m_info->toolManager(), SIGNAL(previewDone())); + connect(pngConverter, SIGNAL(destroyed()), this, SLOT(toolDestroyed())); + + // Now we are ready to start the process... + m_info->toolManager()->run(pngConverter); + m_running = true; } void PreviewWidget::clear() { - m_imageDisplayWidget->clear(); + m_imageDisplayWidget->clear(); } void PreviewWidget::drawImage() { - KILE_DEBUG_MAIN << "\tconversion tool '" << m_conversionTool << "' done, processing file (by dani)"; - m_imageDisplayWidget->setImageFile(m_info->quickPreview()->getPreviewFile ("png")); + KILE_DEBUG_MAIN << "\tconversion tool '" << m_conversionTool << "' done, processing file (by dani)"; + m_imageDisplayWidget->setImageFile(m_info->quickPreview()->getPreviewFile ("png")); } void PreviewWidget::toolDestroyed() { - KILE_DEBUG_MAIN << "\tQuickPreview: tool destroyed"; - m_running = false; + KILE_DEBUG_MAIN << "\tQuickPreview: tool destroyed"; + m_running = false; } void PreviewWidget::showError(const QString &text) { - m_info->errorHandler()->printMessage(KileTool::Error, text, i18n("QuickPreview")); + m_info->errorHandler()->printMessage(KileTool::Error, text, i18n("QuickPreview")); } } diff --git a/src/widgets/previewwidget.h b/src/widgets/previewwidget.h index 29d33bbd..d1c5a22d 100644 --- a/src/widgets/previewwidget.h +++ b/src/widgets/previewwidget.h @@ -1,107 +1,109 @@ /***************************************************************************** * Copyright (C) 2006 by Mathias Soeken (msoeken@informatik.uni-bremen.de) * * (C) 2011 by Michel Ludwig (michel.ludwig@kdemail.net) * ******************************************************************************/ /*************************************************************************** * * * 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. * * * ***************************************************************************/ #ifndef PREVIEWWIDGET_H #define PREVIEWWIDGET_H #include class QImage; class QLabel; class KileInfo; -namespace KileTool { class Base; } +namespace KileTool { +class Base; +} namespace KileWidget { // declared in the .cpp file class ImageDisplayWidget; /** * Widget which can display PNG images from Math LaTeX * Code - * + * * This is used to be inserted in the bottom bar of the kile - * main widget. When putting the cursor in a mathgroup, the LaTeX + * main widget. When putting the cursor in a mathgroup, the LaTeX * source should be extracted and rendered in this widget. - * + * * This widget uses one new Tool: DVItoPNG which converts * a dvi file to an png image, which is fitted to the size * of the formula). - * - * You could use this widget to implement a formula editor in Kile, + * + * You could use this widget to implement a formula editor in Kile, * where the editor is the editor, but with this widget you can see * the result in a appropriate size just in time. - * + * * @author Mathias Soeken */ class PreviewWidget : public QScrollArea { - Q_OBJECT + Q_OBJECT public: - explicit PreviewWidget(KileInfo *info, QWidget *parent = 0, const char *name = 0); - ~PreviewWidget(); - - /** - * Tries to paint the current mathgroup of - * the current document. - * - * If a document is open and the cursor is - * inside a mathgroup, a PNG is generated - * containing this mathgroup. - * - * This PNG image is then displayed on the - * widget. - **/ - void showActivePreview(const QString &text, const QString &textfilename, int startrow, int previewtype); + explicit PreviewWidget(KileInfo *info, QWidget *parent = 0, const char *name = 0); + ~PreviewWidget(); + + /** + * Tries to paint the current mathgroup of + * the current document. + * + * If a document is open and the cursor is + * inside a mathgroup, a PNG is generated + * containing this mathgroup. + * + * This PNG image is then displayed on the + * widget. + **/ + void showActivePreview(const QString &text, const QString &textfilename, int startrow, int previewtype); public Q_SLOTS: - void clear(); + void clear(); private: - enum { pwDvipng=0, pwDvipsConvert, pwConvert }; + enum { pwDvipng=0, pwDvipsConvert, pwConvert }; - KileInfo *m_info; - ImageDisplayWidget *m_imageDisplayWidget; - bool m_running; - QString m_conversionTool; + KileInfo *m_info; + ImageDisplayWidget *m_imageDisplayWidget; + bool m_running; + QString m_conversionTool; protected: - void showError(const QString &text); + void showError(const QString &text); public Q_SLOTS: - /** - * Notify, if the DVItoPNG tool is done. - * - * Because the tool runs async. we - * must wait, if the process is done. - * - * Then we try to generate a image of the - * temporary PNG filename and display it on - * the widget. - * - * The size of the widget is also adjusted - * to the size of the widget. - **/ - void drawImage(); - void toolDestroyed(); -}; + /** + * Notify, if the DVItoPNG tool is done. + * + * Because the tool runs async. we + * must wait, if the process is done. + * + * Then we try to generate a image of the + * temporary PNG filename and display it on + * the widget. + * + * The size of the widget is also adjusted + * to the size of the widget. + **/ + void drawImage(); + void toolDestroyed(); +}; } #endif diff --git a/src/widgets/processtoolconfigwidget.cpp b/src/widgets/processtoolconfigwidget.cpp index be962e3a..8f54b90c 100644 --- a/src/widgets/processtoolconfigwidget.cpp +++ b/src/widgets/processtoolconfigwidget.cpp @@ -1,24 +1,24 @@ /************************************************************************** * Copyright (C) 2007 by Michel Ludwig (michel.ludwig@kdemail.net) * ***************************************************************************/ /************************************************************************** * * * 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. * * * ***************************************************************************/ #include "widgets/processtoolconfigwidget.h" ProcessToolConfigWidget::ProcessToolConfigWidget(QWidget *parent) : QWidget(parent) { - setupUi(this); + setupUi(this); } ProcessToolConfigWidget::~ProcessToolConfigWidget() { } diff --git a/src/widgets/processtoolconfigwidget.h b/src/widgets/processtoolconfigwidget.h index 8ad6856b..5e131b0b 100644 --- a/src/widgets/processtoolconfigwidget.h +++ b/src/widgets/processtoolconfigwidget.h @@ -1,30 +1,30 @@ /************************************************************************** * Copyright (C) 2007 by Michel Ludwig (michel.ludwig@kdemail.net) * ***************************************************************************/ /************************************************************************** * * * 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. * * * ***************************************************************************/ #ifndef PROCESSTOOLCONFIGWIDGET_H #define PROCESSTOOLCONFIGWIDGET_H #include #include "ui_processtoolconfigwidget.h" class ProcessToolConfigWidget : public QWidget, public Ui::ProcessToolConfigWidget { - Q_OBJECT + Q_OBJECT - public: - ProcessToolConfigWidget(QWidget *parent = 0); - ~ProcessToolConfigWidget(); +public: + ProcessToolConfigWidget(QWidget *parent = 0); + ~ProcessToolConfigWidget(); }; #endif diff --git a/src/widgets/progressdialog.cpp b/src/widgets/progressdialog.cpp index a30c3dfe..f7e2b281 100644 --- a/src/widgets/progressdialog.cpp +++ b/src/widgets/progressdialog.cpp @@ -1,39 +1,39 @@ /* * Copyright 2015 Andreas Cord-Landwehr * * 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, see . */ #include "progressdialog.h" #include KileWidget::ProgressDialog::ProgressDialog(QWidget* parent) - : QProgressDialog(parent) + : QProgressDialog(parent) { - setCancelButtonText(QString()); // empty string disables cancel button + setCancelButtonText(QString()); // empty string disables cancel button } KileWidget::ProgressDialog::~ProgressDialog() { } void KileWidget::ProgressDialog::closeEvent(QCloseEvent *event) { - // only allow closing the dialog if progressbar is full - if (value() >= maximum()) { - QProgressDialog::closeEvent(event); - } - event->ignore(); + // only allow closing the dialog if progressbar is full + if (value() >= maximum()) { + QProgressDialog::closeEvent(event); + } + event->ignore(); } diff --git a/src/widgets/progressdialog.h b/src/widgets/progressdialog.h index a9d1495c..5eb43615 100644 --- a/src/widgets/progressdialog.h +++ b/src/widgets/progressdialog.h @@ -1,41 +1,41 @@ /* * Copyright 2015 Andreas Cord-Landwehr * * 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, see . */ #ifndef KILEPROGRESSDIALOG_H #define KILEPROGRESSDIALOG_H #include #include namespace KileWidget { class ProgressDialog : public QProgressDialog { - Q_OBJECT + Q_OBJECT public: - ProgressDialog(QWidget *parent = Q_NULLPTR); - ~ProgressDialog(); - virtual void closeEvent(QCloseEvent *event) Q_DECL_OVERRIDE; + ProgressDialog(QWidget *parent = Q_NULLPTR); + ~ProgressDialog(); + virtual void closeEvent(QCloseEvent *event) Q_DECL_OVERRIDE; public: private: }; } #endif diff --git a/src/widgets/projectview.cpp b/src/widgets/projectview.cpp index c3301877..4e8cbc8b 100644 --- a/src/widgets/projectview.cpp +++ b/src/widgets/projectview.cpp @@ -1,910 +1,910 @@ /**************************************************************************************** begin : Tue Aug 12 2003 copyright : (C) 2003 by Jeroen Wijnhout (Jeroen.Wijnhout@kdemail.net) 2006 - 2010 by Michel Ludwig (michel.ludwig@kdemail.net) ****************************************************************************************/ /*************************************************************************** * * * 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. * * * ***************************************************************************/ #include "widgets/projectview.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include "kileinfo.h" #include "documentinfo.h" #include "kiledocmanager.h" #include #include const int KPV_ID_OPEN = 0, KPV_ID_SAVE = 1, KPV_ID_CLOSE = 2, - KPV_ID_OPTIONS = 3, KPV_ID_ADD = 4, KPV_ID_REMOVE = 5, - KPV_ID_BUILDTREE = 6, KPV_ID_ARCHIVE = 7, KPV_ID_ADDFILES = 8, - KPV_ID_INCLUDE = 9, KPV_ID_OPENWITH = 10, KPV_ID_OPENALLFILES = 11; + KPV_ID_OPTIONS = 3, KPV_ID_ADD = 4, KPV_ID_REMOVE = 5, + KPV_ID_BUILDTREE = 6, KPV_ID_ARCHIVE = 7, KPV_ID_ADDFILES = 8, + KPV_ID_INCLUDE = 9, KPV_ID_OPENWITH = 10, KPV_ID_OPENALLFILES = 11; namespace KileWidget { /* * ProjectViewItem */ ProjectViewItem::ProjectViewItem(QTreeWidget *parent, KileProjectItem *item, bool ar) -: QTreeWidgetItem(parent, QStringList(item->url().fileName())), m_docinfo(Q_NULLPTR), m_folder(-1), m_projectItem(item) + : QTreeWidgetItem(parent, QStringList(item->url().fileName())), m_docinfo(Q_NULLPTR), m_folder(-1), m_projectItem(item) { - setArchiveState(ar); + setArchiveState(ar); } ProjectViewItem::ProjectViewItem(QTreeWidget *parent, QTreeWidgetItem *after, KileProjectItem *item, bool ar) -: QTreeWidgetItem(parent, after), m_docinfo(Q_NULLPTR), m_folder(-1), m_projectItem(item) + : QTreeWidgetItem(parent, after), m_docinfo(Q_NULLPTR), m_folder(-1), m_projectItem(item) { - setText(0, item->url().fileName()); - setArchiveState(ar); + setText(0, item->url().fileName()); + setArchiveState(ar); } ProjectViewItem::ProjectViewItem(QTreeWidgetItem *parent, KileProjectItem *item, bool ar) -: QTreeWidgetItem(parent, QStringList(item->url().fileName())), m_docinfo(Q_NULLPTR), m_folder(-1), m_projectItem(item) + : QTreeWidgetItem(parent, QStringList(item->url().fileName())), m_docinfo(Q_NULLPTR), m_folder(-1), m_projectItem(item) { - setArchiveState(ar); + setArchiveState(ar); } //use this to create folders ProjectViewItem::ProjectViewItem(QTreeWidgetItem *parent, const QString& name) -: QTreeWidgetItem(parent, QStringList(name)), m_docinfo(Q_NULLPTR), m_folder(-1), m_projectItem(Q_NULLPTR) + : QTreeWidgetItem(parent, QStringList(name)), m_docinfo(Q_NULLPTR), m_folder(-1), m_projectItem(Q_NULLPTR) { } //use this to create non-project files ProjectViewItem::ProjectViewItem(QTreeWidget *parent, const QString& name) -: QTreeWidgetItem(parent, QStringList(name)), m_docinfo(Q_NULLPTR), m_folder(-1), m_projectItem(Q_NULLPTR) + : QTreeWidgetItem(parent, QStringList(name)), m_docinfo(Q_NULLPTR), m_folder(-1), m_projectItem(Q_NULLPTR) { } ProjectViewItem::ProjectViewItem(QTreeWidget *parent, const KileProject *project) -: QTreeWidgetItem(parent, QStringList(project->name())), m_docinfo(Q_NULLPTR), m_folder(-1), m_projectItem(Q_NULLPTR) + : QTreeWidgetItem(parent, QStringList(project->name())), m_docinfo(Q_NULLPTR), m_folder(-1), m_projectItem(Q_NULLPTR) { } ProjectViewItem::~ProjectViewItem() { - KILE_DEBUG_MAIN << "DELETING PROJVIEWITEM " << m_url.fileName(); + KILE_DEBUG_MAIN << "DELETING PROJVIEWITEM " << m_url.fileName(); } KileProjectItem* ProjectViewItem::projectItem() { - return m_projectItem; + return m_projectItem; } ProjectViewItem* ProjectViewItem::parent() { - return dynamic_cast(QTreeWidgetItem::parent()); + return dynamic_cast(QTreeWidgetItem::parent()); } ProjectViewItem* ProjectViewItem::firstChild() { - return dynamic_cast(QTreeWidgetItem::child(0)); + return dynamic_cast(QTreeWidgetItem::child(0)); } void ProjectViewItem::setInfo(KileDocument::Info *docinfo) { - m_docinfo = docinfo; + m_docinfo = docinfo; } KileDocument::Info* ProjectViewItem::getInfo() { - return m_docinfo; + return m_docinfo; } void ProjectViewItem::setType(KileType::ProjectView type) { - m_type = type; + m_type = type; } KileType::ProjectView ProjectViewItem::type() const { - return m_type; + return m_type; } void ProjectViewItem::urlChanged(const QUrl &url) { - // don't allow empty URLs - if(!url.isEmpty()) { - setURL(url); - setText(0, url.fileName()); - } + // don't allow empty URLs + if(!url.isEmpty()) { + setURL(url); + setText(0, url.fileName()); + } } void ProjectViewItem::nameChanged(const QString & name) { - setText(0, name); + setText(0, name); } void ProjectViewItem::isrootChanged(bool isroot) { - KILE_DEBUG_MAIN << "SLOT isrootChanged " << text(0) << " to " << isroot; - if(isroot) { - setIcon(0, QIcon::fromTheme("masteritem")); - } - else { - if(m_projectItem && m_projectItem->type() == KileProjectItem::ProjectFile) { - setIcon(0, QIcon::fromTheme("kile")); - } - else if(m_projectItem && m_projectItem->type() == KileProjectItem::Bibliography) { - setIcon(0, QIcon::fromTheme("viewbib")); - } - else if(type() == KileType::ProjectItem) { - setIcon(0, QIcon::fromTheme("projectitem")); - } - else { - setIcon(0, QIcon::fromTheme("file")); - } - } + KILE_DEBUG_MAIN << "SLOT isrootChanged " << text(0) << " to " << isroot; + if(isroot) { + setIcon(0, QIcon::fromTheme("masteritem")); + } + else { + if(m_projectItem && m_projectItem->type() == KileProjectItem::ProjectFile) { + setIcon(0, QIcon::fromTheme("kile")); + } + else if(m_projectItem && m_projectItem->type() == KileProjectItem::Bibliography) { + setIcon(0, QIcon::fromTheme("viewbib")); + } + else if(type() == KileType::ProjectItem) { + setIcon(0, QIcon::fromTheme("projectitem")); + } + else { + setIcon(0, QIcon::fromTheme("file")); + } + } } void ProjectViewItem::slotURLChanged(KileDocument::Info*, const QUrl &url) { - urlChanged(url); + urlChanged(url); } bool ProjectViewItem::operator<(const QTreeWidgetItem& other) const { - try { - const ProjectViewItem& otherItem = dynamic_cast(other); - - // order in the tree: - // - first, root items without container (sorted in ascending order) - // - then, container items in fixed order (images, packages, other, projectfile) - if(otherItem.type() == KileType::Folder) { - if(type() != KileType::Folder) { - return true; - } - else { - // 'm_folder' is set to a type from 'KileProject::Type' - // we want: Image < Package < Other < ProjectFile - switch(m_folder) { - case KileProjectItem::Image: - return true; - - case KileProjectItem::Package: - return (otherItem.m_folder == KileProjectItem::Image) ? false : true; - - case KileProjectItem::Other: - return (otherItem.m_folder == KileProjectItem::Image - || otherItem.m_folder == KileProjectItem::Package) ? false : true; - - case KileProjectItem::ProjectFile: - return false; - - default: // dummy - return false; - } - } - } - else if(type() == KileType::Folder) { - return false; - } - else { - return QTreeWidgetItem::operator<(other); - } - } - catch(std::bad_cast&) { - return QTreeWidgetItem::operator<(other); - } + try { + const ProjectViewItem& otherItem = dynamic_cast(other); + + // order in the tree: + // - first, root items without container (sorted in ascending order) + // - then, container items in fixed order (images, packages, other, projectfile) + if(otherItem.type() == KileType::Folder) { + if(type() != KileType::Folder) { + return true; + } + else { + // 'm_folder' is set to a type from 'KileProject::Type' + // we want: Image < Package < Other < ProjectFile + switch(m_folder) { + case KileProjectItem::Image: + return true; + + case KileProjectItem::Package: + return (otherItem.m_folder == KileProjectItem::Image) ? false : true; + + case KileProjectItem::Other: + return (otherItem.m_folder == KileProjectItem::Image + || otherItem.m_folder == KileProjectItem::Package) ? false : true; + + case KileProjectItem::ProjectFile: + return false; + + default: // dummy + return false; + } + } + } + else if(type() == KileType::Folder) { + return false; + } + else { + return QTreeWidgetItem::operator<(other); + } + } + catch(std::bad_cast&) { + return QTreeWidgetItem::operator<(other); + } } void ProjectViewItem::setURL(const QUrl &url) { - m_url = url; + m_url = url; } const QUrl &ProjectViewItem::url() { - return m_url; + return m_url; } void ProjectViewItem::setArchiveState(bool ar) { - setText(1, ar ? "*" : ""); + setText(1, ar ? "*" : ""); } void ProjectViewItem::setFolder(int folder) { - m_folder = folder; + m_folder = folder; } int ProjectViewItem::folder() const { - return m_folder; + return m_folder; } /* * ProjectView */ ProjectView::ProjectView(QWidget *parent, KileInfo *ki) : QTreeWidget(parent), m_ki(ki), m_nProjects(0) { - setColumnCount(2); - QStringList labelList; - labelList << i18n("Files & Projects") << i18n("Include in Archive"); - setHeaderLabels(labelList); - setColumnWidth(1, 10); + setColumnCount(2); + QStringList labelList; + labelList << i18n("Files & Projects") << i18n("Include in Archive"); + setHeaderLabels(labelList); + setColumnWidth(1, 10); - setFocusPolicy(Qt::ClickFocus); - header()->hide(); - header()->setSectionResizeMode(QHeaderView::ResizeToContents); - setRootIsDecorated(true); - setAllColumnsShowFocus(true); - setSelectionMode(QTreeWidget::SingleSelection); + setFocusPolicy(Qt::ClickFocus); + header()->hide(); + header()->setSectionResizeMode(QHeaderView::ResizeToContents); + setRootIsDecorated(true); + setAllColumnsShowFocus(true); + setSelectionMode(QTreeWidget::SingleSelection); - connect(this, SIGNAL(itemClicked(QTreeWidgetItem*,int)), this, SLOT(slotClicked(QTreeWidgetItem*))); - setAcceptDrops(true); + connect(this, SIGNAL(itemClicked(QTreeWidgetItem*,int)), this, SLOT(slotClicked(QTreeWidgetItem*))); + setAcceptDrops(true); } void ProjectView::slotClicked(QTreeWidgetItem *item) { - if(!item) { - item = currentItem(); - } - - ProjectViewItem *itm = static_cast(item); - if(itm) { - if(itm->type() == KileType::File) { - emit(fileSelected(itm->url())); - } - else if(itm->type() == KileType::ProjectItem) { - emit(fileSelected(itm->projectItem())); - } - else if(itm->type() != KileType::Folder) { - // don't open project configuration files (*.kilepr) - if(itm->url().toLocalFile().right(7) != ".kilepr") { - //determine mimeType and open file with preferred application - QMimeDatabase db; - QMimeType pMime = db.mimeTypeForUrl(itm->url()); - if(pMime.name().startsWith("text/")) { - emit(fileSelected(itm->url())); - } - else { - KRun::runUrl(itm->url(), pMime.name(), this, KRun::RunFlags()); - } - } - } - clearSelection(); - } + if(!item) { + item = currentItem(); + } + + ProjectViewItem *itm = static_cast(item); + if(itm) { + if(itm->type() == KileType::File) { + emit(fileSelected(itm->url())); + } + else if(itm->type() == KileType::ProjectItem) { + emit(fileSelected(itm->projectItem())); + } + else if(itm->type() != KileType::Folder) { + // don't open project configuration files (*.kilepr) + if(itm->url().toLocalFile().right(7) != ".kilepr") { + //determine mimeType and open file with preferred application + QMimeDatabase db; + QMimeType pMime = db.mimeTypeForUrl(itm->url()); + if(pMime.name().startsWith("text/")) { + emit(fileSelected(itm->url())); + } + else { + KRun::runUrl(itm->url(), pMime.name(), this, KRun::RunFlags()); + } + } + } + clearSelection(); + } } void ProjectView::slotFile(int id) { - ProjectViewItem *item = dynamic_cast(currentItem()); - if(item) { - if(item->type() == KileType::File) { - switch(id) { - case KPV_ID_OPEN: - emit(fileSelected(item->url())); - break; - case KPV_ID_SAVE: - emit(saveURL(item->url())); - break; - case KPV_ID_ADD: - emit(addToProject(item->url())); - break; - case KPV_ID_CLOSE: - emit(closeURL(item->url())); - return; //don't access "item" later on - default: - break; - } - } - } + ProjectViewItem *item = dynamic_cast(currentItem()); + if(item) { + if(item->type() == KileType::File) { + switch(id) { + case KPV_ID_OPEN: + emit(fileSelected(item->url())); + break; + case KPV_ID_SAVE: + emit(saveURL(item->url())); + break; + case KPV_ID_ADD: + emit(addToProject(item->url())); + break; + case KPV_ID_CLOSE: + emit(closeURL(item->url())); + return; //don't access "item" later on + default: + break; + } + } + } } void ProjectView::slotProjectItem(int id) { - ProjectViewItem *item = dynamic_cast(currentItem()); - if(item) { - if(item->type() == KileType::ProjectItem || item->type() == KileType::ProjectExtra) { - switch(id) { - case KPV_ID_OPEN: - emit(fileSelected(item->projectItem())); - break; - case KPV_ID_SAVE: - emit(saveURL(item->url())); - break; - case KPV_ID_REMOVE: - emit(removeFromProject(item->projectItem())); - break; - case KPV_ID_INCLUDE : - if(item->text(1) == "*") { - item->setText(1, ""); - } - else { - item->setText(1, "*"); - } - emit(toggleArchive(item->projectItem())); - break; - case KPV_ID_CLOSE: - emit(closeURL(item->url())); - break; //we can access "item" later as it isn't deleted - case KPV_ID_OPENWITH: - KRun::displayOpenWithDialog(QList() << item->url(), this); - break; - default: - break; - } - } - } + ProjectViewItem *item = dynamic_cast(currentItem()); + if(item) { + if(item->type() == KileType::ProjectItem || item->type() == KileType::ProjectExtra) { + switch(id) { + case KPV_ID_OPEN: + emit(fileSelected(item->projectItem())); + break; + case KPV_ID_SAVE: + emit(saveURL(item->url())); + break; + case KPV_ID_REMOVE: + emit(removeFromProject(item->projectItem())); + break; + case KPV_ID_INCLUDE : + if(item->text(1) == "*") { + item->setText(1, ""); + } + else { + item->setText(1, "*"); + } + emit(toggleArchive(item->projectItem())); + break; + case KPV_ID_CLOSE: + emit(closeURL(item->url())); + break; //we can access "item" later as it isn't deleted + case KPV_ID_OPENWITH: + KRun::displayOpenWithDialog(QList() << item->url(), this); + break; + default: + break; + } + } + } } void ProjectView::slotProject(int id) { - ProjectViewItem *item = dynamic_cast(currentItem()); - if(item) { - if(item->type() == KileType::Project) { - switch(id) { - case KPV_ID_BUILDTREE: - emit(buildProjectTree(item->url())); - break; - case KPV_ID_OPTIONS: - emit(projectOptions(item->url())); - break; - case KPV_ID_CLOSE: - emit(closeProject(item->url())); - return; //don't access "item" later on - case KPV_ID_ARCHIVE: - emit(projectArchive(item->url())); - break; - case KPV_ID_ADDFILES: - emit(addFiles(item->url())); - break; - case KPV_ID_OPENALLFILES: - emit(openAllFiles(item->url())); - break; - default: - break; - } - } - } + ProjectViewItem *item = dynamic_cast(currentItem()); + if(item) { + if(item->type() == KileType::Project) { + switch(id) { + case KPV_ID_BUILDTREE: + emit(buildProjectTree(item->url())); + break; + case KPV_ID_OPTIONS: + emit(projectOptions(item->url())); + break; + case KPV_ID_CLOSE: + emit(closeProject(item->url())); + return; //don't access "item" later on + case KPV_ID_ARCHIVE: + emit(projectArchive(item->url())); + break; + case KPV_ID_ADDFILES: + emit(addFiles(item->url())); + break; + case KPV_ID_OPENALLFILES: + emit(openAllFiles(item->url())); + break; + default: + break; + } + } + } } void ProjectView::slotRun(int id) { - ProjectViewItem *itm = dynamic_cast(currentItem()); + ProjectViewItem *itm = dynamic_cast(currentItem()); - if(!itm) { - return; - } + if(!itm) { + return; + } - if(id == 0) { - KRun::displayOpenWithDialog(QList() << itm->url(), this); - } - else { - KRun::runService(*m_offerList[id-1], QList() << itm->url(), this); - } + if(id == 0) { + KRun::displayOpenWithDialog(QList() << itm->url(), this); + } + else { + KRun::runService(*m_offerList[id-1], QList() << itm->url(), this); + } - itm->setSelected(false); + itm->setSelected(false); } void ProjectView::makeTheConnection(ProjectViewItem *item, KileDocument::TextInfo *textInfo) { - KILE_DEBUG_MAIN << "\tmakeTheConnection " << item->text(0); - - if (item->type() == KileType::Project) { - KileProject *project = m_ki->docManager()->projectFor(item->url()); - if (!project) { - qWarning() << "makeTheConnection COULD NOT FIND AN PROJECT OBJECT FOR " << item->url().toLocalFile(); - } - else { - connect(project, SIGNAL(nameChanged(const QString &)), item, SLOT(nameChanged(const QString &))); - } - } - else { - if(!textInfo) { - textInfo = m_ki->docManager()->textInfoFor(item->url().toLocalFile()); - if(!textInfo) { - KILE_DEBUG_MAIN << "\tmakeTheConnection COULD NOT FIND A DOCINFO"; - return; - } - } - item->setInfo(textInfo); - connect(textInfo, SIGNAL(urlChanged(KileDocument::Info*, const QUrl&)), item, SLOT(slotURLChanged(KileDocument::Info*, const QUrl&))); - connect(textInfo, SIGNAL(isrootChanged(bool)), item, SLOT(isrootChanged(bool))); - //set the pixmap - item->isrootChanged(textInfo->isLaTeXRoot()); - } + KILE_DEBUG_MAIN << "\tmakeTheConnection " << item->text(0); + + if (item->type() == KileType::Project) { + KileProject *project = m_ki->docManager()->projectFor(item->url()); + if (!project) { + qWarning() << "makeTheConnection COULD NOT FIND AN PROJECT OBJECT FOR " << item->url().toLocalFile(); + } + else { + connect(project, SIGNAL(nameChanged(const QString &)), item, SLOT(nameChanged(const QString &))); + } + } + else { + if(!textInfo) { + textInfo = m_ki->docManager()->textInfoFor(item->url().toLocalFile()); + if(!textInfo) { + KILE_DEBUG_MAIN << "\tmakeTheConnection COULD NOT FIND A DOCINFO"; + return; + } + } + item->setInfo(textInfo); + connect(textInfo, SIGNAL(urlChanged(KileDocument::Info*, const QUrl&)), item, SLOT(slotURLChanged(KileDocument::Info*, const QUrl&))); + connect(textInfo, SIGNAL(isrootChanged(bool)), item, SLOT(isrootChanged(bool))); + //set the pixmap + item->isrootChanged(textInfo->isLaTeXRoot()); + } } ProjectViewItem* ProjectView::folder(const KileProjectItem *pi, ProjectViewItem *item) { - ProjectViewItem *parent = parentFor(pi, item); - - if(!parent) { - qCritical() << "no parent for " << pi->url().toLocalFile(); - return Q_NULLPTR; - } - - // we have already found the parent folder - if(parent->type() == KileType::Folder) { - return parent; - } - - // we are looking at the children, if there is an existing folder for this type - ProjectViewItem *folder; - - // determine the foldername for this type - QString foldername; - switch(pi->type()) { - case (KileProjectItem::ProjectFile): - foldername = i18n("Project File"); - break; - case (KileProjectItem::Package): - foldername = i18n("Packages"); - break; - case (KileProjectItem::Image): - foldername = i18n("Images"); - break; - case (KileProjectItem::Bibliography): - foldername = i18n("Bibliography"); - break; - case (KileProjectItem::Other): - default : - foldername = i18n("Other"); - break; - } - - // if there already a folder for this type on this level? - bool found = false; - QTreeWidgetItemIterator it(parent); - ++it; // skip 'parent' - while(*it) { - folder = dynamic_cast(*it); - if(folder && folder->text(0) == foldername) { - found = true; - break; - } - ++it; - } - - // if no folder was found, we must create a new one - if(!found) { - folder = new ProjectViewItem(parent, foldername); - KILE_DEBUG_MAIN << "new folder: parent=" << parent->url().url() - << ", foldername=" << foldername; - - folder->setFolder(pi->type()); - folder->setType(KileType::Folder); - } - - return folder; + ProjectViewItem *parent = parentFor(pi, item); + + if(!parent) { + qCritical() << "no parent for " << pi->url().toLocalFile(); + return Q_NULLPTR; + } + + // we have already found the parent folder + if(parent->type() == KileType::Folder) { + return parent; + } + + // we are looking at the children, if there is an existing folder for this type + ProjectViewItem *folder; + + // determine the foldername for this type + QString foldername; + switch(pi->type()) { + case (KileProjectItem::ProjectFile): + foldername = i18n("Project File"); + break; + case (KileProjectItem::Package): + foldername = i18n("Packages"); + break; + case (KileProjectItem::Image): + foldername = i18n("Images"); + break; + case (KileProjectItem::Bibliography): + foldername = i18n("Bibliography"); + break; + case (KileProjectItem::Other): + default : + foldername = i18n("Other"); + break; + } + + // if there already a folder for this type on this level? + bool found = false; + QTreeWidgetItemIterator it(parent); + ++it; // skip 'parent' + while(*it) { + folder = dynamic_cast(*it); + if(folder && folder->text(0) == foldername) { + found = true; + break; + } + ++it; + } + + // if no folder was found, we must create a new one + if(!found) { + folder = new ProjectViewItem(parent, foldername); + KILE_DEBUG_MAIN << "new folder: parent=" << parent->url().url() + << ", foldername=" << foldername; + + folder->setFolder(pi->type()); + folder->setType(KileType::Folder); + } + + return folder; } void ProjectView::add(const KileProject *project) { - ProjectViewItem *parent = new ProjectViewItem(this, project); - - parent->setType(KileType::Project); - parent->setURL(project->url()); - parent->setExpanded(true); - parent->setIcon(0, QIcon::fromTheme("relation")); - makeTheConnection(parent); + ProjectViewItem *parent = new ProjectViewItem(this, project); - //ProjectViewItem *nonsrc = new ProjectViewItem(parent, i18n("non-source")); - //parent->setNonSrc(nonsrc); + parent->setType(KileType::Project); + parent->setURL(project->url()); + parent->setExpanded(true); + parent->setIcon(0, QIcon::fromTheme("relation")); + makeTheConnection(parent); - refreshProjectTree(project); + //ProjectViewItem *nonsrc = new ProjectViewItem(parent, i18n("non-source")); + //parent->setNonSrc(nonsrc); - ++m_nProjects; + refreshProjectTree(project); + + ++m_nProjects; } ProjectViewItem* ProjectView::projectViewItemFor(const QUrl &url) { - ProjectViewItem *item = Q_NULLPTR; + ProjectViewItem *item = Q_NULLPTR; - //find project view item - QTreeWidgetItemIterator it(this); - while(*it) { - item = dynamic_cast(*it); - if(item && (item->type() == KileType::Project) && (item->url() == url)) { - break; - } - ++it; - } + //find project view item + QTreeWidgetItemIterator it(this); + while(*it) { + item = dynamic_cast(*it); + if(item && (item->type() == KileType::Project) && (item->url() == url)) { + break; + } + ++it; + } - return item; + return item; } ProjectViewItem* ProjectView::itemFor(const QUrl &url) { - ProjectViewItem *item = Q_NULLPTR; + ProjectViewItem *item = Q_NULLPTR; - QTreeWidgetItemIterator it(this); - while(*it) { - item = static_cast(*it); - if (item->url() == url) { - break; - } - ++it; - } + QTreeWidgetItemIterator it(this); + while(*it) { + item = static_cast(*it); + if (item->url() == url) { + break; + } + ++it; + } - return item; + return item; } ProjectViewItem* ProjectView::parentFor(const KileProjectItem *projitem, ProjectViewItem *projvi) { - //find parent projectviewitem of projitem - KileProjectItem *parpi = projitem->parent(); - ProjectViewItem *parpvi = projvi, *vi; - - if (parpi) { - //find parent viewitem that has an URL parpi->url() - QTreeWidgetItemIterator it(projvi); - KILE_DEBUG_MAIN << "\tlooking for " << parpi->url().toLocalFile(); - while(*it) { - vi = static_cast(*it); - KILE_DEBUG_MAIN << "\t\t" << vi->url().toLocalFile(); - if (vi->url() == parpi->url()) { - parpvi = vi; - KILE_DEBUG_MAIN << "\t\tfound" <type(); - QTreeWidgetItemIterator it(projvi); - ++it; // skip projvi - while(*it) { - ProjectViewItem *child = dynamic_cast(*it); - if(child && (child->type() == KileType::Folder) && (child->folder() == projitem->type())) { - KILE_DEBUG_MAIN << "\t\tfound"; - parpvi = child; - break; - } - ++it; - } - } - - return (!parpvi) ? projvi : parpvi; + //find parent projectviewitem of projitem + KileProjectItem *parpi = projitem->parent(); + ProjectViewItem *parpvi = projvi, *vi; + + if (parpi) { + //find parent viewitem that has an URL parpi->url() + QTreeWidgetItemIterator it(projvi); + KILE_DEBUG_MAIN << "\tlooking for " << parpi->url().toLocalFile(); + while(*it) { + vi = static_cast(*it); + KILE_DEBUG_MAIN << "\t\t" << vi->url().toLocalFile(); + if (vi->url() == parpi->url()) { + parpvi = vi; + KILE_DEBUG_MAIN << "\t\tfound" <type(); + QTreeWidgetItemIterator it(projvi); + ++it; // skip projvi + while(*it) { + ProjectViewItem *child = dynamic_cast(*it); + if(child && (child->type() == KileType::Folder) && (child->folder() == projitem->type())) { + KILE_DEBUG_MAIN << "\t\tfound"; + parpvi = child; + break; + } + ++it; + } + } + + return (!parpvi) ? projvi : parpvi; } ProjectViewItem* ProjectView::add(KileProjectItem *projitem, ProjectViewItem *projvi /* = Q_NULLPTR */) { - KILE_DEBUG_MAIN << "\tprojectitem=" << projitem->path() - << " projvi=" << projvi; - const KileProject *project = projitem->project(); - - if (!projvi) { - projvi = projectViewItemFor(project->url()); - } - - KILE_DEBUG_MAIN << "\tparent projectviewitem " << projvi->url().fileName(); - - ProjectViewItem *item = Q_NULLPTR, *parent = Q_NULLPTR; - - switch (projitem->type()) { - case (KileProjectItem::Source): - item = new ProjectViewItem(projvi, projitem); - item->setType(KileType::ProjectItem); - item->setIcon(0, QIcon::fromTheme("projectitem")); - break; - case (KileProjectItem::Package): - parent = folder(projitem, projvi); - item = new ProjectViewItem(parent, projitem); - item->setType(KileType::ProjectItem); - item->setIcon(0, QIcon::fromTheme("projectitem")); - break; - default: - parent = folder(projitem, projvi); - item = new ProjectViewItem(parent, projitem); - item->setType(KileType::ProjectExtra); - if(projitem->type() == KileProjectItem::ProjectFile) { - item->setIcon(0, QIcon::fromTheme("kile")); - } - else if(projitem->type() == KileProjectItem::Bibliography) { - item->setIcon(0, QIcon::fromTheme("viewbib")); - } - else { - item->setIcon(0, QIcon::fromTheme("file")); - } - break; - } - - item->setArchiveState(projitem->archive()); - item->setURL(projitem->url()); - makeTheConnection(item, projitem->getInfo()); - - projvi->sortChildren(0, Qt::AscendingOrder); - // seems to be necessary to get a correct refreh (Qt 4.4.3) - bool expanded = projvi->isExpanded(); - projvi->setExpanded(!expanded); - projvi->setExpanded(expanded); - - return item; + KILE_DEBUG_MAIN << "\tprojectitem=" << projitem->path() + << " projvi=" << projvi; + const KileProject *project = projitem->project(); + + if (!projvi) { + projvi = projectViewItemFor(project->url()); + } + + KILE_DEBUG_MAIN << "\tparent projectviewitem " << projvi->url().fileName(); + + ProjectViewItem *item = Q_NULLPTR, *parent = Q_NULLPTR; + + switch (projitem->type()) { + case (KileProjectItem::Source): + item = new ProjectViewItem(projvi, projitem); + item->setType(KileType::ProjectItem); + item->setIcon(0, QIcon::fromTheme("projectitem")); + break; + case (KileProjectItem::Package): + parent = folder(projitem, projvi); + item = new ProjectViewItem(parent, projitem); + item->setType(KileType::ProjectItem); + item->setIcon(0, QIcon::fromTheme("projectitem")); + break; + default: + parent = folder(projitem, projvi); + item = new ProjectViewItem(parent, projitem); + item->setType(KileType::ProjectExtra); + if(projitem->type() == KileProjectItem::ProjectFile) { + item->setIcon(0, QIcon::fromTheme("kile")); + } + else if(projitem->type() == KileProjectItem::Bibliography) { + item->setIcon(0, QIcon::fromTheme("viewbib")); + } + else { + item->setIcon(0, QIcon::fromTheme("file")); + } + break; + } + + item->setArchiveState(projitem->archive()); + item->setURL(projitem->url()); + makeTheConnection(item, projitem->getInfo()); + + projvi->sortChildren(0, Qt::AscendingOrder); + // seems to be necessary to get a correct refreh (Qt 4.4.3) + bool expanded = projvi->isExpanded(); + projvi->setExpanded(!expanded); + projvi->setExpanded(expanded); + + return item; } void ProjectView::addTree(KileProjectItem *projitem, ProjectViewItem *projvi) { - KILE_DEBUG_MAIN << "projitem=" << projitem - << "projvi=" << projvi; - ProjectViewItem * item = add(projitem, projvi); + KILE_DEBUG_MAIN << "projitem=" << projitem + << "projvi=" << projvi; + ProjectViewItem * item = add(projitem, projvi); - if(projitem->firstChild()) { - addTree(projitem->firstChild(), item); - } + if(projitem->firstChild()) { + addTree(projitem->firstChild(), item); + } - if (projitem->sibling()) { - addTree(projitem->sibling(), projvi); - } + if (projitem->sibling()) { + addTree(projitem->sibling(), projvi); + } } void ProjectView::refreshProjectTree(const KileProject *project) { - KILE_DEBUG_MAIN << "\tProjectView::refreshProjectTree(" << project->name() << ")"; - ProjectViewItem *parent= projectViewItemFor(project->url()); - - //clean the tree - if(parent) { - KILE_DEBUG_MAIN << "\tusing parent projectviewitem " << parent->url().fileName(); - parent->setFolder(-1); - QList children = parent->takeChildren(); - for(QList::iterator it = children.begin(); - it != children.end(); ++it) { - delete(*it); - } - } - else { - return; - } - - //create the non-sources dir - //ProjectViewItem *nonsrc = new ProjectViewItem(parent, i18n("non-sources")); - //parent->setNonSrc(nonsrc); - - QList list = project->rootItems(); - for(QList::iterator it = list.begin(); it != list.end(); ++it) { - addTree(*it, parent); - } - - parent->sortChildren(0, Qt::AscendingOrder); - // seems to be necessary to get a correct refreh (Qt 4.4.3) - bool expanded = parent->isExpanded(); - parent->setExpanded(!expanded); - parent->setExpanded(expanded); + KILE_DEBUG_MAIN << "\tProjectView::refreshProjectTree(" << project->name() << ")"; + ProjectViewItem *parent= projectViewItemFor(project->url()); + + //clean the tree + if(parent) { + KILE_DEBUG_MAIN << "\tusing parent projectviewitem " << parent->url().fileName(); + parent->setFolder(-1); + QList children = parent->takeChildren(); + for(QList::iterator it = children.begin(); + it != children.end(); ++it) { + delete(*it); + } + } + else { + return; + } + + //create the non-sources dir + //ProjectViewItem *nonsrc = new ProjectViewItem(parent, i18n("non-sources")); + //parent->setNonSrc(nonsrc); + + QList list = project->rootItems(); + for(QList::iterator it = list.begin(); it != list.end(); ++it) { + addTree(*it, parent); + } + + parent->sortChildren(0, Qt::AscendingOrder); + // seems to be necessary to get a correct refreh (Qt 4.4.3) + bool expanded = parent->isExpanded(); + parent->setExpanded(!expanded); + parent->setExpanded(expanded); } void ProjectView::add(const QUrl &url) { - KILE_DEBUG_MAIN << "\tProjectView::adding item " << url.toLocalFile(); - //check if file is already present - QTreeWidgetItemIterator it(this); - ProjectViewItem *item; - while(*it) { - item = static_cast(*it); - if((item->type() != KileType::Project) && (item->url() == url)) { - return; - } - ++it; - } + KILE_DEBUG_MAIN << "\tProjectView::adding item " << url.toLocalFile(); + //check if file is already present + QTreeWidgetItemIterator it(this); + ProjectViewItem *item; + while(*it) { + item = static_cast(*it); + if((item->type() != KileType::Project) && (item->url() == url)) { + return; + } + ++it; + } - item = new ProjectViewItem(this, url.fileName()); - item->setType(KileType::File); - item->setURL(url); - makeTheConnection(item); + item = new ProjectViewItem(this, url.fileName()); + item->setType(KileType::File); + item->setURL(url); + makeTheConnection(item); } void ProjectView::remove(const KileProject *project) { - for(int i = 0; i < topLevelItemCount(); ++i) { - ProjectViewItem *item = static_cast(topLevelItem(i)); + for(int i = 0; i < topLevelItemCount(); ++i) { + ProjectViewItem *item = static_cast(topLevelItem(i)); - if(item->url() == project->url()) { - item->setParent(Q_NULLPTR); - delete item; - --m_nProjects; - break; - } - } + if(item->url() == project->url()) { + item->setParent(Q_NULLPTR); + delete item; + --m_nProjects; + break; + } + } } /** * Removes a file from the projectview, does not remove project-items. Only files without a project. **/ void ProjectView::remove(const QUrl &url) { - for(int i = 0; i < topLevelItemCount(); ++i) { - ProjectViewItem *item = dynamic_cast(topLevelItem(i)); + for(int i = 0; i < topLevelItemCount(); ++i) { + ProjectViewItem *item = dynamic_cast(topLevelItem(i)); - if(item && (item->type() == KileType::File) && (item->url() == url)) { - item->setParent(Q_NULLPTR); - delete item; - break; - } - } + if(item && (item->type() == KileType::File) && (item->url() == url)) { + item->setParent(Q_NULLPTR); + delete item; + break; + } + } } void ProjectView::removeItem(const KileProjectItem *projitem, bool open) { - QTreeWidgetItemIterator it(this); - ProjectViewItem *item; - while(*it) { - item = dynamic_cast(*it); - if(item && (item->type() == KileType::ProjectItem) && (item->projectItem() == projitem)) { - KILE_DEBUG_MAIN << "removing projectviewitem"; - static_cast(item->parent())->removeChild(item); - delete item; - } - ++it; - } + QTreeWidgetItemIterator it(this); + ProjectViewItem *item; + while(*it) { + item = dynamic_cast(*it); + if(item && (item->type() == KileType::ProjectItem) && (item->projectItem() == projitem)) { + KILE_DEBUG_MAIN << "removing projectviewitem"; + static_cast(item->parent())->removeChild(item); + delete item; + } + ++it; + } - if(open) { - item = new ProjectViewItem(this, projitem->url().fileName()); - item->setType(KileType::File); - item->setURL(projitem->url()); - makeTheConnection(item); - } + if(open) { + item = new ProjectViewItem(this, projitem->url().fileName()); + item->setType(KileType::File); + item->setURL(projitem->url()); + makeTheConnection(item); + } } void ProjectView::contextMenuEvent(QContextMenuEvent *event) { - QSignalMapper signalMapper, serviceSignalMapper; - QMenu popup; - QAction *action = Q_NULLPTR; - - QTreeWidgetItem* treeWidgetItem = itemAt(event->pos()); - if(!treeWidgetItem) { - return; - } - - ProjectViewItem *projectViewItem = dynamic_cast(treeWidgetItem); - if(!projectViewItem) { - return; - } - - if(projectViewItem->type() == KileType::Folder) { - return; - } - - bool insertsep = false; - bool isKilePrFile = false; - if(projectViewItem->type() != KileType::Project && projectViewItem->projectItem() - && projectViewItem->projectItem()->project()) { - isKilePrFile = projectViewItem->projectItem()->project()->url() == projectViewItem->url(); - } - - if(projectViewItem->type() == KileType::ProjectExtra && !isKilePrFile) { - QMenu *servicesMenu = popup.addMenu(QIcon::fromTheme("fork"), i18n("&Open With")); - connect(&serviceSignalMapper, SIGNAL(mapped(int)), this, SLOT(slotRun(int))); -QMimeDatabase db; - m_offerList = KMimeTypeTrader::self()->query(db.mimeTypeForUrl(projectViewItem->url()).name(), "Application"); - for (int i = 0; i < m_offerList.count(); ++i) { - action = new QAction(servicesMenu); - action->setIcon(QIcon::fromTheme(m_offerList[i]->icon())); - action->setText(m_offerList[i]->name()); - connect(action, SIGNAL(triggered()), &serviceSignalMapper, SLOT(map())); - serviceSignalMapper.setMapping(action, i + 1); - servicesMenu->addAction(action); - } - - servicesMenu->addSeparator(); - action = servicesMenu->addAction(i18n("Other..."), &serviceSignalMapper, SLOT(map())); - serviceSignalMapper.setMapping(action, 0); - insertsep = true; - } - - if (projectViewItem->type() == KileType::File || projectViewItem->type() == KileType::ProjectItem) { - if(!m_ki->isOpen(projectViewItem->url())) { - action = popup.addAction(QIcon::fromTheme("document-open"), i18n("&Open"), &signalMapper, SLOT(map())); - signalMapper.setMapping(action, KPV_ID_OPEN); - } - else { - action = popup.addAction(QIcon::fromTheme("document-save"), i18n("&Save"), &signalMapper, SLOT(map())); - signalMapper.setMapping(action, KPV_ID_SAVE); - } - insertsep = true; - } - - if(projectViewItem->type() == KileType::File) { - if(m_nProjects > 0) { - if(insertsep) { - popup.addSeparator(); - } - action = popup.addAction(QIcon::fromTheme("project_add"), i18n("&Add to Project"), &signalMapper, SLOT(map())); - signalMapper.setMapping(action, KPV_ID_ADD); - insertsep = true; - } - connect(&signalMapper, SIGNAL(mapped(int)), this, SLOT(slotFile(int))); - } - else if(projectViewItem->type() == KileType::ProjectItem || projectViewItem->type() == KileType::ProjectExtra) { - KileProjectItem *pi = projectViewItem->projectItem(); - if(pi) { - if(insertsep) { - popup.addSeparator(); - } - action = popup.addAction(i18n("&Include in Archive"), &signalMapper, SLOT(map())); - signalMapper.setMapping(action, KPV_ID_INCLUDE); - action->setCheckable(true); - action->setChecked(pi->archive()); - insertsep = true; - } - if(!isKilePrFile) { - if(insertsep) { - popup.addSeparator(); - } - action = popup.addAction(QIcon::fromTheme("project_remove"),i18n("&Remove From Project"), &signalMapper, SLOT(map())); - signalMapper.setMapping(action, KPV_ID_REMOVE); - insertsep = true; - } - connect(&signalMapper, SIGNAL(mapped(int)), this, SLOT(slotProjectItem(int))); - } - else if(projectViewItem->type() == KileType::Project) { - if(insertsep) { - popup.addSeparator(); - } - action = popup.addAction(i18n("A&dd Files..."), &signalMapper, SLOT(map())); - signalMapper.setMapping(action, KPV_ID_ADDFILES); - popup.addSeparator(); - action = popup.addAction(i18n("Open All &Project Files"), &signalMapper, SLOT(map())); - signalMapper.setMapping(action, KPV_ID_OPENALLFILES); - popup.addSeparator(); - action = popup.addAction(QIcon::fromTheme("view-refresh"),i18n("Refresh Project &Tree"), &signalMapper, SLOT(map())); - signalMapper.setMapping(action, KPV_ID_BUILDTREE); - action = popup.addAction(QIcon::fromTheme("configure"), i18n("Project &Options"), &signalMapper, SLOT(map())); - signalMapper.setMapping(action, KPV_ID_OPTIONS); - action = popup.addAction(i18n("&Archive"), &signalMapper, SLOT(map())); - signalMapper.setMapping(action, KPV_ID_ARCHIVE); - connect(&signalMapper, SIGNAL(mapped(int)), this, SLOT(slotProject(int))); - insertsep = true; - } - - if((projectViewItem->type() == KileType::File) || (projectViewItem->type() == KileType::ProjectItem) - || (projectViewItem->type()== KileType::Project)) { - if(insertsep) { - popup.addSeparator(); - } - action = popup.addAction(QIcon::fromTheme("view-close"), i18n("&Close"), &signalMapper, SLOT(map())); - signalMapper.setMapping(action, KPV_ID_CLOSE); - } - - popup.exec(event->globalPos()); - m_offerList.clear(); + QSignalMapper signalMapper, serviceSignalMapper; + QMenu popup; + QAction *action = Q_NULLPTR; + + QTreeWidgetItem* treeWidgetItem = itemAt(event->pos()); + if(!treeWidgetItem) { + return; + } + + ProjectViewItem *projectViewItem = dynamic_cast(treeWidgetItem); + if(!projectViewItem) { + return; + } + + if(projectViewItem->type() == KileType::Folder) { + return; + } + + bool insertsep = false; + bool isKilePrFile = false; + if(projectViewItem->type() != KileType::Project && projectViewItem->projectItem() + && projectViewItem->projectItem()->project()) { + isKilePrFile = projectViewItem->projectItem()->project()->url() == projectViewItem->url(); + } + + if(projectViewItem->type() == KileType::ProjectExtra && !isKilePrFile) { + QMenu *servicesMenu = popup.addMenu(QIcon::fromTheme("fork"), i18n("&Open With")); + connect(&serviceSignalMapper, SIGNAL(mapped(int)), this, SLOT(slotRun(int))); + QMimeDatabase db; + m_offerList = KMimeTypeTrader::self()->query(db.mimeTypeForUrl(projectViewItem->url()).name(), "Application"); + for (int i = 0; i < m_offerList.count(); ++i) { + action = new QAction(servicesMenu); + action->setIcon(QIcon::fromTheme(m_offerList[i]->icon())); + action->setText(m_offerList[i]->name()); + connect(action, SIGNAL(triggered()), &serviceSignalMapper, SLOT(map())); + serviceSignalMapper.setMapping(action, i + 1); + servicesMenu->addAction(action); + } + + servicesMenu->addSeparator(); + action = servicesMenu->addAction(i18n("Other..."), &serviceSignalMapper, SLOT(map())); + serviceSignalMapper.setMapping(action, 0); + insertsep = true; + } + + if (projectViewItem->type() == KileType::File || projectViewItem->type() == KileType::ProjectItem) { + if(!m_ki->isOpen(projectViewItem->url())) { + action = popup.addAction(QIcon::fromTheme("document-open"), i18n("&Open"), &signalMapper, SLOT(map())); + signalMapper.setMapping(action, KPV_ID_OPEN); + } + else { + action = popup.addAction(QIcon::fromTheme("document-save"), i18n("&Save"), &signalMapper, SLOT(map())); + signalMapper.setMapping(action, KPV_ID_SAVE); + } + insertsep = true; + } + + if(projectViewItem->type() == KileType::File) { + if(m_nProjects > 0) { + if(insertsep) { + popup.addSeparator(); + } + action = popup.addAction(QIcon::fromTheme("project_add"), i18n("&Add to Project"), &signalMapper, SLOT(map())); + signalMapper.setMapping(action, KPV_ID_ADD); + insertsep = true; + } + connect(&signalMapper, SIGNAL(mapped(int)), this, SLOT(slotFile(int))); + } + else if(projectViewItem->type() == KileType::ProjectItem || projectViewItem->type() == KileType::ProjectExtra) { + KileProjectItem *pi = projectViewItem->projectItem(); + if(pi) { + if(insertsep) { + popup.addSeparator(); + } + action = popup.addAction(i18n("&Include in Archive"), &signalMapper, SLOT(map())); + signalMapper.setMapping(action, KPV_ID_INCLUDE); + action->setCheckable(true); + action->setChecked(pi->archive()); + insertsep = true; + } + if(!isKilePrFile) { + if(insertsep) { + popup.addSeparator(); + } + action = popup.addAction(QIcon::fromTheme("project_remove"),i18n("&Remove From Project"), &signalMapper, SLOT(map())); + signalMapper.setMapping(action, KPV_ID_REMOVE); + insertsep = true; + } + connect(&signalMapper, SIGNAL(mapped(int)), this, SLOT(slotProjectItem(int))); + } + else if(projectViewItem->type() == KileType::Project) { + if(insertsep) { + popup.addSeparator(); + } + action = popup.addAction(i18n("A&dd Files..."), &signalMapper, SLOT(map())); + signalMapper.setMapping(action, KPV_ID_ADDFILES); + popup.addSeparator(); + action = popup.addAction(i18n("Open All &Project Files"), &signalMapper, SLOT(map())); + signalMapper.setMapping(action, KPV_ID_OPENALLFILES); + popup.addSeparator(); + action = popup.addAction(QIcon::fromTheme("view-refresh"),i18n("Refresh Project &Tree"), &signalMapper, SLOT(map())); + signalMapper.setMapping(action, KPV_ID_BUILDTREE); + action = popup.addAction(QIcon::fromTheme("configure"), i18n("Project &Options"), &signalMapper, SLOT(map())); + signalMapper.setMapping(action, KPV_ID_OPTIONS); + action = popup.addAction(i18n("&Archive"), &signalMapper, SLOT(map())); + signalMapper.setMapping(action, KPV_ID_ARCHIVE); + connect(&signalMapper, SIGNAL(mapped(int)), this, SLOT(slotProject(int))); + insertsep = true; + } + + if((projectViewItem->type() == KileType::File) || (projectViewItem->type() == KileType::ProjectItem) + || (projectViewItem->type()== KileType::Project)) { + if(insertsep) { + popup.addSeparator(); + } + action = popup.addAction(QIcon::fromTheme("view-close"), i18n("&Close"), &signalMapper, SLOT(map())); + signalMapper.setMapping(action, KPV_ID_CLOSE); + } + + popup.exec(event->globalPos()); + m_offerList.clear(); } void ProjectView::dragEnterEvent(QDragEnterEvent *event) { - if(event->mimeData()->hasUrls()) { // only accept URL drags - event->acceptProposedAction(); - } + if(event->mimeData()->hasUrls()) { // only accept URL drags + event->acceptProposedAction(); + } } void ProjectView::dragMoveEvent(QDragMoveEvent *event) { - if(event->mimeData()->hasUrls()) { // only accept URL drags - event->acceptProposedAction(); - } + if(event->mimeData()->hasUrls()) { // only accept URL drags + event->acceptProposedAction(); + } } void ProjectView::dropEvent(QDropEvent *event) { - m_ki->docManager()->openDroppedURLs(event); + m_ki->docManager()->openDroppedURLs(event); } } diff --git a/src/widgets/projectview.h b/src/widgets/projectview.h index 341e6b8a..5263e3d0 100644 --- a/src/widgets/projectview.h +++ b/src/widgets/projectview.h @@ -1,162 +1,164 @@ /***************************************************************************************** begin : Tue Aug 12 2003 copyright : (C) 2003 by Jeroen Wijnhout (Jeroen.Wijnhout@kdemail.net) 2006 - 2010 by Michel Ludwig (michel.ludwig@kdemail.net) *****************************************************************************************/ /*************************************************************************** * * * 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. * * * ***************************************************************************/ #ifndef PROJECTVIEW_H #define PROJECTVIEW_H #include #include #include #include "kileproject.h" class QUrl; class QMenu; class KToggleAction; class KileInfo; -namespace KileType {enum ProjectView {Project = 0, ProjectItem, Bibliography, ProjectExtra, File, Folder};} +namespace KileType { +enum ProjectView {Project = 0, ProjectItem, Bibliography, ProjectExtra, File, Folder}; +} namespace KileWidget { class ProjectViewItem : public QObject, public QTreeWidgetItem { - Q_OBJECT + Q_OBJECT public: - ProjectViewItem(QTreeWidget *parent, KileProjectItem *item, bool ar = false); - ProjectViewItem(QTreeWidget *parent, QTreeWidgetItem *after, KileProjectItem *item, bool ar = false); - ProjectViewItem(QTreeWidgetItem *parent, KileProjectItem *item, bool ar = false); + ProjectViewItem(QTreeWidget *parent, KileProjectItem *item, bool ar = false); + ProjectViewItem(QTreeWidget *parent, QTreeWidgetItem *after, KileProjectItem *item, bool ar = false); + ProjectViewItem(QTreeWidgetItem *parent, KileProjectItem *item, bool ar = false); + + //use this to create folders + ProjectViewItem(QTreeWidgetItem *parent, const QString& name); + + //use this to create non-project files + ProjectViewItem(QTreeWidget *parent, const QString& name); - //use this to create folders - ProjectViewItem(QTreeWidgetItem *parent, const QString& name); + ProjectViewItem(QTreeWidget *parent, const KileProject *project); - //use this to create non-project files - ProjectViewItem(QTreeWidget *parent, const QString& name); - - ProjectViewItem(QTreeWidget *parent, const KileProject *project); - - ~ProjectViewItem(); + ~ProjectViewItem(); - KileProjectItem* projectItem(); + KileProjectItem* projectItem(); - ProjectViewItem* parent(); - ProjectViewItem* firstChild(); + ProjectViewItem* parent(); + ProjectViewItem* firstChild(); - void setInfo(KileDocument::Info *docinfo); - KileDocument::Info * getInfo(); + void setInfo(KileDocument::Info *docinfo); + KileDocument::Info * getInfo(); - void setType(KileType::ProjectView type); - KileType::ProjectView type() const; + void setType(KileType::ProjectView type); + KileType::ProjectView type() const; - virtual bool operator<(const QTreeWidgetItem& other) const; + virtual bool operator<(const QTreeWidgetItem& other) const; - void setURL(const QUrl &url); - const QUrl &url(); + void setURL(const QUrl &url); + const QUrl &url(); - void setArchiveState(bool ar); + void setArchiveState(bool ar); - void setFolder(int folder); - int folder() const; + void setFolder(int folder); + int folder() const; public Q_SLOTS: - /** - * @warning Does nothing if "url" is empty ! - **/ - void urlChanged(const QUrl &url); - void nameChanged(const QString& name); - void isrootChanged(bool isroot); + /** + * @warning Does nothing if "url" is empty ! + **/ + void urlChanged(const QUrl &url); + void nameChanged(const QString& name); + void isrootChanged(bool isroot); private Q_SLOTS: - /** - * Dummy slot, simply forwarding to urlChanged(const QUrl &url). - **/ - void slotURLChanged(KileDocument::Info*, const QUrl &url); + /** + * Dummy slot, simply forwarding to urlChanged(const QUrl &url). + **/ + void slotURLChanged(KileDocument::Info*, const QUrl &url); private: - QUrl m_url; - KileType::ProjectView m_type; - KileDocument::Info *m_docinfo; - int m_folder; - KileProjectItem *m_projectItem; + QUrl m_url; + KileType::ProjectView m_type; + KileDocument::Info *m_docinfo; + int m_folder; + KileProjectItem *m_projectItem; }; class ProjectView : public QTreeWidget { - Q_OBJECT + Q_OBJECT public: - ProjectView(QWidget *parent, KileInfo *ki); + ProjectView(QWidget *parent, KileInfo *ki); - void addTree(KileProjectItem *item, ProjectViewItem *projvi); + void addTree(KileProjectItem *item, ProjectViewItem *projvi); - ProjectViewItem* projectViewItemFor(const QUrl&); - ProjectViewItem* itemFor(const QUrl&); - ProjectViewItem* parentFor(const KileProjectItem *projitem, ProjectViewItem *projvi); + ProjectViewItem* projectViewItemFor(const QUrl&); + ProjectViewItem* itemFor(const QUrl&); + ProjectViewItem* parentFor(const KileProjectItem *projitem, ProjectViewItem *projvi); public Q_SLOTS: - void slotClicked(QTreeWidgetItem* item = Q_NULLPTR); + void slotClicked(QTreeWidgetItem* item = Q_NULLPTR); - void slotFile(int id); - void slotProjectItem(int id); - void slotProject(int id); + void slotFile(int id); + void slotProjectItem(int id); + void slotProject(int id); - void slotRun(int id); + void slotRun(int id); - void refreshProjectTree(const KileProject *); - void add(const QUrl &url); - void add(const KileProject *project); - void remove(const QUrl &url); - void remove(const KileProject *project); - void removeItem(const KileProjectItem *, bool); - ProjectViewItem* add(KileProjectItem *item, ProjectViewItem *projvi = Q_NULLPTR); + void refreshProjectTree(const KileProject *); + void add(const QUrl &url); + void add(const KileProject *project); + void remove(const QUrl &url); + void remove(const KileProject *project); + void removeItem(const KileProjectItem *, bool); + ProjectViewItem* add(KileProjectItem *item, ProjectViewItem *projvi = Q_NULLPTR); Q_SIGNALS: - void fileSelected(const KileProjectItem *); - void fileSelected(const QUrl&); - void saveURL(const QUrl&); - void closeURL(const QUrl&); - void projectOptions(const QUrl&); - void projectArchive(const QUrl&); - void addFiles(const QUrl&); - void openAllFiles(const QUrl&); - void toggleArchive(KileProjectItem*); - void closeProject(const QUrl&); - void addToProject(const QUrl&); - void removeFromProject(KileProjectItem*); - void buildProjectTree(const QUrl&); + void fileSelected(const KileProjectItem *); + void fileSelected(const QUrl&); + void saveURL(const QUrl&); + void closeURL(const QUrl&); + void projectOptions(const QUrl&); + void projectArchive(const QUrl&); + void addFiles(const QUrl&); + void openAllFiles(const QUrl&); + void toggleArchive(KileProjectItem*); + void closeProject(const QUrl&); + void addToProject(const QUrl&); + void removeFromProject(KileProjectItem*); + void buildProjectTree(const QUrl&); protected: - virtual void contextMenuEvent(QContextMenuEvent *event); - virtual void dragEnterEvent(QDragEnterEvent *event); - virtual void dragMoveEvent(QDragMoveEvent *event); - virtual void dropEvent(QDropEvent *event); + virtual void contextMenuEvent(QContextMenuEvent *event); + virtual void dragEnterEvent(QDragEnterEvent *event); + virtual void dragMoveEvent(QDragMoveEvent *event); + virtual void dropEvent(QDropEvent *event); private: - KileInfo *m_ki; - uint m_nProjects; + KileInfo *m_ki; + uint m_nProjects; - KService::List m_offerList; + KService::List m_offerList; - void makeTheConnection(ProjectViewItem *projectViewItem, KileDocument::TextInfo *textInfo = Q_NULLPTR); - ProjectViewItem* folder(const KileProjectItem *item, ProjectViewItem *); + void makeTheConnection(ProjectViewItem *projectViewItem, KileDocument::TextInfo *textInfo = Q_NULLPTR); + ProjectViewItem* folder(const KileProjectItem *item, ProjectViewItem *); }; } #endif diff --git a/src/widgets/quicktoolconfigwidget.cpp b/src/widgets/quicktoolconfigwidget.cpp index 6f25af96..f36bcafc 100644 --- a/src/widgets/quicktoolconfigwidget.cpp +++ b/src/widgets/quicktoolconfigwidget.cpp @@ -1,142 +1,142 @@ /******************************************************************************** * Copyright (C) 2007, 2008 by Michel Ludwig (michel.ludwig@kdemail.net) * *********************************************************************************/ /************************************************************************** * * * 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. * * * ***************************************************************************/ #include "widgets/quicktoolconfigwidget.h" #include "kiletoolmanager.h" #include QuickToolConfigWidget::QuickToolConfigWidget(QWidget *parent) : QWidget(parent) { - setupUi(this); - connect(m_pshbAdd, SIGNAL(clicked()), this, SLOT(add())); - connect(m_pshbRemove, SIGNAL(clicked()), this, SLOT(remove())); - connect(m_pshbUp, SIGNAL(clicked()), this, SLOT(up())); - connect(m_pshbDown, SIGNAL(clicked()), this, SLOT(down())); + setupUi(this); + connect(m_pshbAdd, SIGNAL(clicked()), this, SLOT(add())); + connect(m_pshbRemove, SIGNAL(clicked()), this, SLOT(remove())); + connect(m_pshbUp, SIGNAL(clicked()), this, SLOT(up())); + connect(m_pshbDown, SIGNAL(clicked()), this, SLOT(down())); } QuickToolConfigWidget::~QuickToolConfigWidget() { } void QuickToolConfigWidget::updateSequence(const QString &sequence) { - QStringList toollist = KileTool::toolList(KSharedConfig::openConfig().data(), true); - toollist.sort(); - m_cbTools->clear(); - m_cbTools->addItems(toollist); - - updateConfigs(m_cbTools->currentText()); - connect(m_cbTools, SIGNAL(activated(const QString&)), this, SLOT(updateConfigs(const QString&))); - - m_sequence = sequence; - QStringList list = sequence.split(',', QString::SkipEmptyParts); - QString tl, cfg; - m_lstbSeq->clear(); - for(QStringList::iterator i = list.begin(); i != list.end(); ++i) { - KileTool::extract(*i, tl, cfg); - if(!cfg.isEmpty()) { - m_lstbSeq->addItem(tl + " (" + cfg + ')'); - } - else { - m_lstbSeq->addItem(tl); - } - } + QStringList toollist = KileTool::toolList(KSharedConfig::openConfig().data(), true); + toollist.sort(); + m_cbTools->clear(); + m_cbTools->addItems(toollist); + + updateConfigs(m_cbTools->currentText()); + connect(m_cbTools, SIGNAL(activated(const QString&)), this, SLOT(updateConfigs(const QString&))); + + m_sequence = sequence; + QStringList list = sequence.split(',', QString::SkipEmptyParts); + QString tl, cfg; + m_lstbSeq->clear(); + for(QStringList::iterator i = list.begin(); i != list.end(); ++i) { + KileTool::extract(*i, tl, cfg); + if(!cfg.isEmpty()) { + m_lstbSeq->addItem(tl + " (" + cfg + ')'); + } + else { + m_lstbSeq->addItem(tl); + } + } } void QuickToolConfigWidget::updateConfigs(const QString &tool) { - m_cbConfigs->clear(); - QString currentConfig = KileTool::configName(tool, KSharedConfig::openConfig().data()); - if(!currentConfig.isEmpty()){ - m_currentDefaultConfig = i18n("Current Default (%1)",currentConfig); - } - else{ - m_currentDefaultConfig = i18n("Current Default"); - } - m_cbConfigs->addItem(m_currentDefaultConfig); - m_cbConfigs->addItems(KileTool::configNames(tool, KSharedConfig::openConfig().data())); + m_cbConfigs->clear(); + QString currentConfig = KileTool::configName(tool, KSharedConfig::openConfig().data()); + if(!currentConfig.isEmpty()) { + m_currentDefaultConfig = i18n("Current Default (%1)",currentConfig); + } + else { + m_currentDefaultConfig = i18n("Current Default"); + } + m_cbConfigs->addItem(m_currentDefaultConfig); + m_cbConfigs->addItems(KileTool::configNames(tool, KSharedConfig::openConfig().data())); } void QuickToolConfigWidget::down() { - QList selectedItems = m_lstbSeq->selectedItems(); - if(selectedItems.isEmpty()) { - return; - } - QListWidgetItem *selectedItem = selectedItems.first(); - int row = m_lstbSeq->row(selectedItem); - if(row < m_lstbSeq->count() - 1) { - QListWidgetItem *nextItem = m_lstbSeq->item(row + 1); - QString text = selectedItem->text(); - selectedItem->setText(nextItem->text()); - nextItem->setText(text); - nextItem->setSelected(true); - changed(); - } + QList selectedItems = m_lstbSeq->selectedItems(); + if(selectedItems.isEmpty()) { + return; + } + QListWidgetItem *selectedItem = selectedItems.first(); + int row = m_lstbSeq->row(selectedItem); + if(row < m_lstbSeq->count() - 1) { + QListWidgetItem *nextItem = m_lstbSeq->item(row + 1); + QString text = selectedItem->text(); + selectedItem->setText(nextItem->text()); + nextItem->setText(text); + nextItem->setSelected(true); + changed(); + } } void QuickToolConfigWidget::up() { - QList selectedItems = m_lstbSeq->selectedItems(); - if(selectedItems.isEmpty()) { - return; - } - QListWidgetItem *selectedItem = selectedItems.first(); - int row = m_lstbSeq->row(selectedItem); - if(row > 0) { - QListWidgetItem *previousItem = m_lstbSeq->item(row - 1); - QString text = selectedItem->text(); - selectedItem->setText(previousItem->text()); - previousItem->setText(text); - previousItem->setSelected(true); - changed(); - } + QList selectedItems = m_lstbSeq->selectedItems(); + if(selectedItems.isEmpty()) { + return; + } + QListWidgetItem *selectedItem = selectedItems.first(); + int row = m_lstbSeq->row(selectedItem); + if(row > 0) { + QListWidgetItem *previousItem = m_lstbSeq->item(row - 1); + QString text = selectedItem->text(); + selectedItem->setText(previousItem->text()); + previousItem->setText(text); + previousItem->setSelected(true); + changed(); + } } void QuickToolConfigWidget::remove() { - QList selectedItems = m_lstbSeq->selectedItems(); - if(selectedItems.isEmpty()) { - return; - } - QListWidgetItem *selectedItem = selectedItems.first(); - delete selectedItem; - changed(); + QList selectedItems = m_lstbSeq->selectedItems(); + if(selectedItems.isEmpty()) { + return; + } + QListWidgetItem *selectedItem = selectedItems.first(); + delete selectedItem; + changed(); } void QuickToolConfigWidget::add() { - QString entry = m_cbTools->currentText(); - if(m_cbConfigs->currentText() != m_currentDefaultConfig) { - entry += " (" + m_cbConfigs->currentText() + ')'; - } + QString entry = m_cbTools->currentText(); + if(m_cbConfigs->currentText() != m_currentDefaultConfig) { + entry += " (" + m_cbConfigs->currentText() + ')'; + } - m_lstbSeq->addItem(entry); - changed(); + m_lstbSeq->addItem(entry); + changed(); } void QuickToolConfigWidget::changed() { - QString sequence, tool, cfg; - for(int i = 0; i < m_lstbSeq->count(); ++i) { - KileTool::extract(m_lstbSeq->item(i)->text(), tool, cfg); - sequence += KileTool::format(tool, cfg) + ','; - } - if(sequence.endsWith(',')) { - sequence = sequence.left(sequence.length()-1); - } - m_sequence = sequence; - emit sequenceChanged(m_sequence); + QString sequence, tool, cfg; + for(int i = 0; i < m_lstbSeq->count(); ++i) { + KileTool::extract(m_lstbSeq->item(i)->text(), tool, cfg); + sequence += KileTool::format(tool, cfg) + ','; + } + if(sequence.endsWith(',')) { + sequence = sequence.left(sequence.length()-1); + } + m_sequence = sequence; + emit sequenceChanged(m_sequence); } diff --git a/src/widgets/quicktoolconfigwidget.h b/src/widgets/quicktoolconfigwidget.h index 64a71fe4..f09ba028 100644 --- a/src/widgets/quicktoolconfigwidget.h +++ b/src/widgets/quicktoolconfigwidget.h @@ -1,48 +1,48 @@ /************************************************************************** * Copyright (C) 2007 by Michel Ludwig (michel.ludwig@kdemail.net) * ***************************************************************************/ /************************************************************************** * * * 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. * * * ***************************************************************************/ #ifndef QUICKTOOLCONFIGWIDGET_H #define QUICKTOOLCONFIGWIDGET_H #include #include "ui_quicktoolconfigwidget.h" class QuickToolConfigWidget : public QWidget, public Ui::QuickToolConfigWidget { - Q_OBJECT + Q_OBJECT - public: - QuickToolConfigWidget(QWidget *parent = 0); - ~QuickToolConfigWidget(); +public: + QuickToolConfigWidget(QWidget *parent = 0); + ~QuickToolConfigWidget(); - public Q_SLOTS: - virtual void updateSequence(const QString& sequence); - virtual void updateConfigs(const QString& tool); +public Q_SLOTS: + virtual void updateSequence(const QString& sequence); + virtual void updateConfigs(const QString& tool); - Q_SIGNALS: - void sequenceChanged(const QString &); +Q_SIGNALS: + void sequenceChanged(const QString &); - private: - QString m_sequence; - QString m_currentDefaultConfig; +private: + QString m_sequence; + QString m_currentDefaultConfig; - private Q_SLOTS: - void down(); - void up(); - void remove(); - void add(); - void changed(); +private Q_SLOTS: + void down(); + void up(); + void remove(); + void add(); + void changed(); }; #endif diff --git a/src/widgets/scriptingconfigwidget.cpp b/src/widgets/scriptingconfigwidget.cpp index 8f25e80c..f7c1f319 100644 --- a/src/widgets/scriptingconfigwidget.cpp +++ b/src/widgets/scriptingconfigwidget.cpp @@ -1,24 +1,24 @@ /************************************************************************** * Copyright (C) 2007 by Michel Ludwig (michel.ludwig@kdemail.net) * ***************************************************************************/ /************************************************************************** * * * 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. * * * ***************************************************************************/ #include "widgets/scriptingconfigwidget.h" KileWidgetScriptingConfig::KileWidgetScriptingConfig(QWidget *parent) : QWidget(parent) { - setupUi(this); + setupUi(this); } KileWidgetScriptingConfig::~KileWidgetScriptingConfig() { } diff --git a/src/widgets/scriptingconfigwidget.h b/src/widgets/scriptingconfigwidget.h index 0e0396c6..787886aa 100644 --- a/src/widgets/scriptingconfigwidget.h +++ b/src/widgets/scriptingconfigwidget.h @@ -1,30 +1,30 @@ /************************************************************************** * Copyright (C) 2007 by Michel Ludwig (michel.ludwig@kdemail.net) * ***************************************************************************/ /************************************************************************** * * * 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. * * * ***************************************************************************/ #ifndef SCRIPTINGCONFIGWIDGET_H #define SCRIPTINGCONFIGWIDGET_H #include #include "ui_scriptingconfigwidget.h" class KileWidgetScriptingConfig : public QWidget, public Ui::KileWidgetScriptingConfig { - Q_OBJECT + Q_OBJECT - public: - KileWidgetScriptingConfig(QWidget *parent = 0); - ~KileWidgetScriptingConfig(); +public: + KileWidgetScriptingConfig(QWidget *parent = 0); + ~KileWidgetScriptingConfig(); }; #endif diff --git a/src/widgets/scriptsmanagementwidget.cpp b/src/widgets/scriptsmanagementwidget.cpp index a3a0d396..375f069e 100644 --- a/src/widgets/scriptsmanagementwidget.cpp +++ b/src/widgets/scriptsmanagementwidget.cpp @@ -1,255 +1,258 @@ /************************************************************************** * Copyright (C) 2006-2014 by Michel Ludwig (michel.ludwig@kdemail.net) * ***************************************************************************/ /************************************************************************** * * * 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. * * * ***************************************************************************/ #include "widgets/scriptsmanagementwidget.h" #include "dialogs/scriptshortcutdialog.h" #include #include #include #include #include #include #include #include #include "editorkeysequencemanager.h" #include "kiledocmanager.h" #include "kileinfo.h" #include "scriptmanager.h" #include "scripting/script.h" /* * We do not use the 'watchedKeySequencesChanged' signal as it creates lots of problems with the setKeySequences... methods. * This works fine as this class is the only one modifying the key sequences. */ namespace KileWidget { /** * This class represents an entry in the scripts tree widget. **/ class ScriptListItem : public QTreeWidgetItem { - public: - ScriptListItem(QTreeWidget *parent, KileScript::Script *script) : QTreeWidgetItem(parent), m_script(script) - { - } - - virtual ~ScriptListItem() - { - } - - KileScript::Script* getScript() - { - return m_script; - } - - protected: - KileScript::Script *m_script; +public: + ScriptListItem(QTreeWidget *parent, KileScript::Script *script) : QTreeWidgetItem(parent), m_script(script) + { + } + + virtual ~ScriptListItem() + { + } + + KileScript::Script* getScript() + { + return m_script; + } + +protected: + KileScript::Script *m_script; }; ScriptsManagement::ScriptsManagement(KileInfo *kileInfo, QWidget *parent, const char *name, Qt::WindowFlags f) - : QWidget(parent, f), m_kileInfo(kileInfo) { - setObjectName(name); - QVBoxLayout *baseLayout = new QVBoxLayout(this); - baseLayout->setMargin(0); - setLayout(baseLayout); - - m_toolBar = new KToolBar(this, "scriptControlToolBar"); - m_toolBar->setToolButtonStyle(Qt::ToolButtonIconOnly); - m_toolBar->setIconDimensions(KIconLoader::SizeSmall); - - m_runAction = new QAction(this); - m_runAction->setIcon(QIcon::fromTheme("run-build")); - m_runAction->setText(i18n("Run Selected Script")); - connect(m_runAction, SIGNAL(triggered()), this, SLOT(executeSelectedScript())); - m_toolBar->addAction(m_runAction); - - QAction *action = new QAction(this); - action->setIcon(QIcon::fromTheme("scriptnew")); - action->setText(i18n("Create New Script")); - connect(action, SIGNAL(triggered()), kileInfo->docManager(), SLOT(fileNewScript())); - m_toolBar->addAction(action); - - m_scriptOpenAction = new QAction(this); - m_scriptOpenAction->setIcon(QIcon::fromTheme("scriptopen")); - m_scriptOpenAction->setText(i18n("Open Selected Script in Editor")); - connect(m_scriptOpenAction, SIGNAL(triggered()), this, SLOT(openSelectedScript())); - m_toolBar->addAction(m_scriptOpenAction); - - m_configureKeySequenceAction = new QAction(this); - m_configureKeySequenceAction->setIcon(QIcon::fromTheme("configure-shortcuts")); - m_configureKeySequenceAction->setText(i18n("Configure Key Sequence")); - connect(m_configureKeySequenceAction, SIGNAL(triggered()), this, SLOT(configureSelectedKeySequence())); - m_toolBar->addAction(m_configureKeySequenceAction); - - m_removeKeySequenceAction = new QAction(this); - m_removeKeySequenceAction->setIcon(QIcon::fromTheme("edit-delete")); - m_removeKeySequenceAction->setText(i18n("Remove Key Sequence")); - connect(m_removeKeySequenceAction, SIGNAL(triggered()), this, SLOT(removeSelectedKeySequence())); - m_toolBar->addAction(m_removeKeySequenceAction); - - action = new QAction(this); - action->setIcon(QIcon::fromTheme("view-refresh")); - action->setText(i18n("Refresh List")); - connect(action, SIGNAL(triggered()), m_kileInfo->scriptManager(), SLOT(scanScriptDirectories())); - m_toolBar->addAction(action); - - baseLayout->addWidget(m_toolBar); - m_treeWidget = new QTreeWidget(this); - m_treeWidget->setSortingEnabled(true); - m_treeWidget->setColumnCount(2); - m_treeWidget->sortByColumn(0, Qt::AscendingOrder); - QStringList headerLabels; - headerLabels.push_back(i18n("Script Name")); - headerLabels.push_back(i18n("Sequence")); - m_treeWidget->setHeaderLabels(headerLabels); - m_treeWidget->setSelectionBehavior(QAbstractItemView::SelectRows); - m_treeWidget->setRootIsDecorated(false); - connect(m_kileInfo->scriptManager(), SIGNAL(scriptsChanged()), this, SLOT(update())); + : QWidget(parent, f), m_kileInfo(kileInfo) { + setObjectName(name); + QVBoxLayout *baseLayout = new QVBoxLayout(this); + baseLayout->setMargin(0); + setLayout(baseLayout); + + m_toolBar = new KToolBar(this, "scriptControlToolBar"); + m_toolBar->setToolButtonStyle(Qt::ToolButtonIconOnly); + m_toolBar->setIconDimensions(KIconLoader::SizeSmall); + + m_runAction = new QAction(this); + m_runAction->setIcon(QIcon::fromTheme("run-build")); + m_runAction->setText(i18n("Run Selected Script")); + connect(m_runAction, SIGNAL(triggered()), this, SLOT(executeSelectedScript())); + m_toolBar->addAction(m_runAction); + + QAction *action = new QAction(this); + action->setIcon(QIcon::fromTheme("scriptnew")); + action->setText(i18n("Create New Script")); + connect(action, SIGNAL(triggered()), kileInfo->docManager(), SLOT(fileNewScript())); + m_toolBar->addAction(action); + + m_scriptOpenAction = new QAction(this); + m_scriptOpenAction->setIcon(QIcon::fromTheme("scriptopen")); + m_scriptOpenAction->setText(i18n("Open Selected Script in Editor")); + connect(m_scriptOpenAction, SIGNAL(triggered()), this, SLOT(openSelectedScript())); + m_toolBar->addAction(m_scriptOpenAction); + + m_configureKeySequenceAction = new QAction(this); + m_configureKeySequenceAction->setIcon(QIcon::fromTheme("configure-shortcuts")); + m_configureKeySequenceAction->setText(i18n("Configure Key Sequence")); + connect(m_configureKeySequenceAction, SIGNAL(triggered()), this, SLOT(configureSelectedKeySequence())); + m_toolBar->addAction(m_configureKeySequenceAction); + + m_removeKeySequenceAction = new QAction(this); + m_removeKeySequenceAction->setIcon(QIcon::fromTheme("edit-delete")); + m_removeKeySequenceAction->setText(i18n("Remove Key Sequence")); + connect(m_removeKeySequenceAction, SIGNAL(triggered()), this, SLOT(removeSelectedKeySequence())); + m_toolBar->addAction(m_removeKeySequenceAction); + + action = new QAction(this); + action->setIcon(QIcon::fromTheme("view-refresh")); + action->setText(i18n("Refresh List")); + connect(action, SIGNAL(triggered()), m_kileInfo->scriptManager(), SLOT(scanScriptDirectories())); + m_toolBar->addAction(action); + + baseLayout->addWidget(m_toolBar); + m_treeWidget = new QTreeWidget(this); + m_treeWidget->setSortingEnabled(true); + m_treeWidget->setColumnCount(2); + m_treeWidget->sortByColumn(0, Qt::AscendingOrder); + QStringList headerLabels; + headerLabels.push_back(i18n("Script Name")); + headerLabels.push_back(i18n("Sequence")); + m_treeWidget->setHeaderLabels(headerLabels); + m_treeWidget->setSelectionBehavior(QAbstractItemView::SelectRows); + m_treeWidget->setRootIsDecorated(false); + connect(m_kileInfo->scriptManager(), SIGNAL(scriptsChanged()), this, SLOT(update())); // connect(m_treeWidget, SIGNAL(doubleClicked(QListViewItem*, const QPoint&, int)), this, SLOT(executed(QListViewItem*, const QPoint&, int))); // connect(m_treeWidget, SIGNAL(itemRenamed(QListViewItem*, const QString&, int)), this, SLOT(itemRenamed(QListViewItem*, const QString&, int))); - connect(m_treeWidget, SIGNAL(itemSelectionChanged()), this, SLOT(updateButtonPanel())); + connect(m_treeWidget, SIGNAL(itemSelectionChanged()), this, SLOT(updateButtonPanel())); - baseLayout->addWidget(m_treeWidget); - updateButtonPanel(); - update(); + baseLayout->addWidget(m_treeWidget); + updateButtonPanel(); + update(); } ScriptsManagement::~ScriptsManagement() { } int ScriptsManagement::scriptNameColumnWidth() { - return m_treeWidget->columnWidth(0); + return m_treeWidget->columnWidth(0); } void ScriptsManagement::setScriptNameColumnWidth(int width) { - if(width > 0) { - m_treeWidget->setColumnWidth(0, width); - } + if(width > 0) { + m_treeWidget->setColumnWidth(0, width); + } } void ScriptsManagement::update() { - m_treeWidget->clear(); - QList scriptList = m_kileInfo->scriptManager()->getScripts(); - QList childrenList; - for(QList::iterator i = scriptList.begin(); i != scriptList.end(); ++i) { - int sequenceType = (*i)->getSequenceType(); - QString sequence = (*i)->getKeySequence(); - ScriptListItem *item = new ScriptListItem(m_treeWidget, *i); - item->setText(0, (*i)->getName()); - item->setText(1, sequence); - if ( !sequence.isEmpty() ) { - QString icon = ( sequenceType == KileScript::Script::KEY_SHORTCUT ) ? "script-key-shortcut" : "script-key-sequence"; - item->setIcon(1, QIcon::fromTheme(icon)); - } - else { - item->setIcon(1, QIcon()); - } - childrenList.push_back(item); - } - m_treeWidget->addTopLevelItems(childrenList); + m_treeWidget->clear(); + QList scriptList = m_kileInfo->scriptManager()->getScripts(); + QList childrenList; + for(QList::iterator i = scriptList.begin(); i != scriptList.end(); ++i) { + int sequenceType = (*i)->getSequenceType(); + QString sequence = (*i)->getKeySequence(); + ScriptListItem *item = new ScriptListItem(m_treeWidget, *i); + item->setText(0, (*i)->getName()); + item->setText(1, sequence); + if ( !sequence.isEmpty() ) { + QString icon = ( sequenceType == KileScript::Script::KEY_SHORTCUT ) ? "script-key-shortcut" : "script-key-sequence"; + item->setIcon(1, QIcon::fromTheme(icon)); + } + else { + item->setIcon(1, QIcon()); + } + childrenList.push_back(item); + } + m_treeWidget->addTopLevelItems(childrenList); } void ScriptsManagement::openSelectedScript() { - QList selectedItems = m_treeWidget->selectedItems(); - if(selectedItems.isEmpty()) { - return; - } - KileScript::Script *script = static_cast(selectedItems.first())->getScript(); - m_kileInfo->docManager()->fileOpen(script->getFileName()); + QList selectedItems = m_treeWidget->selectedItems(); + if(selectedItems.isEmpty()) { + return; + } + KileScript::Script *script = static_cast(selectedItems.first())->getScript(); + m_kileInfo->docManager()->fileOpen(script->getFileName()); } void ScriptsManagement::executeSelectedScript() { - QList selectedItems = m_treeWidget->selectedItems(); - if(selectedItems.isEmpty()) { - return; - } - KileScript::Script *script = static_cast(selectedItems.first())->getScript(); - m_kileInfo->scriptManager()->executeScript(script); + QList selectedItems = m_treeWidget->selectedItems(); + if(selectedItems.isEmpty()) { + return; + } + KileScript::Script *script = static_cast(selectedItems.first())->getScript(); + m_kileInfo->scriptManager()->executeScript(script); } void ScriptsManagement::configureSelectedKeySequence() { - QList selectedItems = m_treeWidget->selectedItems(); - if(selectedItems.isEmpty()) { - return; - } - - KileScript::Script *script = static_cast(selectedItems.first())->getScript(); - // better not use the QTreeWidgetItem as it can be destroyed as a side effect of the setEditorKeySequence method. - int oldType = script->getSequenceType(); - QString oldSequence = script->getKeySequence(); - - // execute ScriptShortcutDialog - KileDialog::ScriptShortcutDialog *dialog = new KileDialog::ScriptShortcutDialog(this, m_kileInfo, oldType, oldSequence); - int result = dialog->exec(); - int newType = dialog->sequenceType(); - QString newSequence = dialog->sequenceValue(); - delete dialog; - - // cancelled or nothing to do? - if ( result==QDialog::Rejected || (newType==oldType && newSequence==oldSequence) ) { - return; - } - - if ( newSequence.isEmpty() ) { - m_kileInfo->scriptManager()->removeEditorKeySequence(script); - } - else { - if ( newType == KileScript::Script::KEY_SEQUENCE ) { - QPair pair = m_kileInfo->editorKeySequenceManager()->checkSequence(newSequence, oldSequence); - if(pair.first == 0) { - m_kileInfo->scriptManager()->setEditorKeySequence(script, newType, newSequence); - } - KileEditorKeySequence::Action *action = m_kileInfo->editorKeySequenceManager()->getAction(pair.second); - QString description = (!action) ? QString() : action->getDescription(); - switch(pair.first) { - case 1: - KMessageBox::sorry(m_kileInfo->mainWindow(), i18n("The sequence \"%1\" is already assigned to the action \"%2\"", newSequence, description), i18n("Sequence Already Assigned")); - return; - case 2: - KMessageBox::sorry(m_kileInfo->mainWindow(), i18n("The sequence \"%1\" is a subsequence of \"%2\", which is already assigned to the action \"%3\"", newSequence, pair.second, description), i18n("Sequence Already Assigned")); - return; - case 3: - KMessageBox::sorry(m_kileInfo->mainWindow(), i18n("The shorter sequence \"%1\" is already assigned to the action \"%2\"", pair.second, description), i18n("Sequence Already Assigned")); - return; - } - } - m_kileInfo->scriptManager()->setEditorKeySequence(script, newType, newSequence); - } - QTimer::singleShot(0, this, SLOT(update())); + QList selectedItems = m_treeWidget->selectedItems(); + if(selectedItems.isEmpty()) { + return; + } + + KileScript::Script *script = static_cast(selectedItems.first())->getScript(); + // better not use the QTreeWidgetItem as it can be destroyed as a side effect of the setEditorKeySequence method. + int oldType = script->getSequenceType(); + QString oldSequence = script->getKeySequence(); + + // execute ScriptShortcutDialog + KileDialog::ScriptShortcutDialog *dialog = new KileDialog::ScriptShortcutDialog(this, m_kileInfo, oldType, oldSequence); + int result = dialog->exec(); + int newType = dialog->sequenceType(); + QString newSequence = dialog->sequenceValue(); + delete dialog; + + // cancelled or nothing to do? + if ( result==QDialog::Rejected || (newType==oldType && newSequence==oldSequence) ) { + return; + } + + if ( newSequence.isEmpty() ) { + m_kileInfo->scriptManager()->removeEditorKeySequence(script); + } + else { + if ( newType == KileScript::Script::KEY_SEQUENCE ) { + QPair pair = m_kileInfo->editorKeySequenceManager()->checkSequence(newSequence, oldSequence); + if(pair.first == 0) { + m_kileInfo->scriptManager()->setEditorKeySequence(script, newType, newSequence); + } + KileEditorKeySequence::Action *action = m_kileInfo->editorKeySequenceManager()->getAction(pair.second); + QString description = (!action) ? QString() : action->getDescription(); + switch(pair.first) { + case 1: + KMessageBox::sorry(m_kileInfo->mainWindow(), i18n("The sequence \"%1\" is already assigned to the action \"%2\"", newSequence, description), + i18n("Sequence Already Assigned")); + return; + case 2: + KMessageBox::sorry(m_kileInfo->mainWindow(), i18n("The sequence \"%1\" is a subsequence of \"%2\", which is already assigned to the action \"%3\"", newSequence, pair.second, description), + i18n("Sequence Already Assigned")); + return; + case 3: + KMessageBox::sorry(m_kileInfo->mainWindow(), i18n("The shorter sequence \"%1\" is already assigned to the action \"%2\"", pair.second, description), + i18n("Sequence Already Assigned")); + return; + } + } + m_kileInfo->scriptManager()->setEditorKeySequence(script, newType, newSequence); + } + QTimer::singleShot(0, this, SLOT(update())); } void ScriptsManagement::removeSelectedKeySequence() // <--------------------- seq oder shortcut { - QList selectedItems = m_treeWidget->selectedItems(); - if(selectedItems.isEmpty()) { - return; - } - KileScript::Script *script = static_cast(selectedItems.first())->getScript(); - // better not use the QTreeWidgetItem as it can be destroyed as a side effect of the removeEditorKeySequence method. - m_kileInfo->scriptManager()->removeEditorKeySequence(script); - QTimer::singleShot(0, this, SLOT(update())); + QList selectedItems = m_treeWidget->selectedItems(); + if(selectedItems.isEmpty()) { + return; + } + KileScript::Script *script = static_cast(selectedItems.first())->getScript(); + // better not use the QTreeWidgetItem as it can be destroyed as a side effect of the removeEditorKeySequence method. + m_kileInfo->scriptManager()->removeEditorKeySequence(script); + QTimer::singleShot(0, this, SLOT(update())); } void ScriptsManagement::updateButtonPanel() { - bool b = m_treeWidget->selectionModel()->hasSelection(); - m_runAction->setEnabled(b); - m_scriptOpenAction->setEnabled(b); - m_configureKeySequenceAction->setEnabled(b); - m_removeKeySequenceAction->setEnabled(b); + bool b = m_treeWidget->selectionModel()->hasSelection(); + m_runAction->setEnabled(b); + m_scriptOpenAction->setEnabled(b); + m_configureKeySequenceAction->setEnabled(b); + m_removeKeySequenceAction->setEnabled(b); } } diff --git a/src/widgets/scriptsmanagementwidget.h b/src/widgets/scriptsmanagementwidget.h index 1ff79217..a92a3e85 100644 --- a/src/widgets/scriptsmanagementwidget.h +++ b/src/widgets/scriptsmanagementwidget.h @@ -1,79 +1,79 @@ /************************************************************************** * Copyright (C) 2006-2008 by Michel Ludwig (michel.ludwig@kdemail.net * ***************************************************************************/ /************************************************************************** * * * 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. * * * ***************************************************************************/ #ifndef SCRIPTSMANAGEMENTWIDGET_H #define SCRIPTSMANAGEMENTWIDGET_H #include #include #include #include class KileInfo; namespace KileScript { - class Manager; - class Script; +class Manager; +class Script; } namespace KileWidget { - /** - * This widget is used to control Kile's scripting features. - **/ - class ScriptsManagement : public QWidget { - Q_OBJECT - public: - ScriptsManagement(KileInfo *kileInfo, QWidget *parent = 0, const char *name = 0, Qt::WindowFlags f = 0); - ~ScriptsManagement(); - - public: - int scriptNameColumnWidth(); - void setScriptNameColumnWidth(int width); - - public Q_SLOTS: - /** - * Rebuilds the view. - **/ - void update(); - - protected Q_SLOTS: - /** - * Opens the currently selected script in Kile's editing area. - **/ - void openSelectedScript(); - - /** - * Executes the currently selected script. - **/ - void executeSelectedScript(); - - void configureSelectedKeySequence(); - - void removeSelectedKeySequence(); - - void updateButtonPanel(); - - protected: - KileInfo *m_kileInfo; - QTreeWidget *m_treeWidget; - - private: - QAction *m_runAction, *m_scriptOpenAction, *m_configureKeySequenceAction, *m_removeKeySequenceAction; - KToolBar *m_toolBar; - }; +/** + * This widget is used to control Kile's scripting features. + **/ +class ScriptsManagement : public QWidget { + Q_OBJECT +public: + ScriptsManagement(KileInfo *kileInfo, QWidget *parent = 0, const char *name = 0, Qt::WindowFlags f = 0); + ~ScriptsManagement(); + +public: + int scriptNameColumnWidth(); + void setScriptNameColumnWidth(int width); + +public Q_SLOTS: + /** + * Rebuilds the view. + **/ + void update(); + +protected Q_SLOTS: + /** + * Opens the currently selected script in Kile's editing area. + **/ + void openSelectedScript(); + + /** + * Executes the currently selected script. + **/ + void executeSelectedScript(); + + void configureSelectedKeySequence(); + + void removeSelectedKeySequence(); + + void updateButtonPanel(); + +protected: + KileInfo *m_kileInfo; + QTreeWidget *m_treeWidget; + +private: + QAction *m_runAction, *m_scriptOpenAction, *m_configureKeySequenceAction, *m_removeKeySequenceAction; + KToolBar *m_toolBar; +}; } #endif diff --git a/src/widgets/scrollwidget.cpp b/src/widgets/scrollwidget.cpp index f67c4c47..6ba72763 100644 --- a/src/widgets/scrollwidget.cpp +++ b/src/widgets/scrollwidget.cpp @@ -1,56 +1,56 @@ /************************************************************************************** Copyright (C) 2016 by Michel Ludwig (michel.ludwig@kdemail.net) (C) 2016 by Elvis Angelaccio (elvis.angelaccio@kde.org) **************************************************************************************/ /*************************************************************************** * * * 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. * * * ***************************************************************************/ #include "scrollwidget.h" #include #include "kiledebug.h" namespace KileWidget { ScrollWidget::ScrollWidget(QWidget *parent) : QScrollArea(parent) { setFrameShape(QFrame::NoFrame); } ScrollWidget::~ScrollWidget() { } QSize ScrollWidget::getPreferredSize() const { - return m_preferredSize; + return m_preferredSize; } void ScrollWidget::setPreferredSize(const QSize& size) { m_preferredSize = size; } QSize ScrollWidget::sizeHint() const { if(m_preferredSize.isValid()) { return m_preferredSize; } else if (widget()) { return widget()->sizeHint(); } return {}; } } diff --git a/src/widgets/scrollwidget.h b/src/widgets/scrollwidget.h index ff8df253..ba69b9e4 100644 --- a/src/widgets/scrollwidget.h +++ b/src/widgets/scrollwidget.h @@ -1,47 +1,47 @@ /************************************************************************************** Copyright (C) 2016 by Michel Ludwig (michel.ludwig@kdemail.net) **************************************************************************************/ /*************************************************************************** * * * 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. * * * ***************************************************************************/ #ifndef SCROLLWIDGET_H #define SCROLLWIDGET_H #include #include namespace KileWidget { class ScrollWidget : public QScrollArea { - Q_OBJECT + Q_OBJECT public: - explicit ScrollWidget(QWidget *parent = Q_NULLPTR); - virtual ~ScrollWidget(); + explicit ScrollWidget(QWidget *parent = Q_NULLPTR); + virtual ~ScrollWidget(); - /** - * Returns the preferred size if it has been set, otherwise the widget's size hint - **/ - virtual QSize sizeHint() const; + /** + * Returns the preferred size if it has been set, otherwise the widget's size hint + **/ + virtual QSize sizeHint() const; - /** - * Set the preferred size of this widget, which will be returned by 'sizeHint' - **/ - QSize getPreferredSize() const; - void setPreferredSize(const QSize& size); + /** + * Set the preferred size of this widget, which will be returned by 'sizeHint' + **/ + QSize getPreferredSize() const; + void setPreferredSize(const QSize& size); protected: - QSize m_preferredSize; + QSize m_preferredSize; }; } #endif diff --git a/src/widgets/sidebar.cpp b/src/widgets/sidebar.cpp index 13e99e5d..88e85e6d 100644 --- a/src/widgets/sidebar.cpp +++ b/src/widgets/sidebar.cpp @@ -1,295 +1,295 @@ /************************************************************************************** Copyright (C) 2004 by Jeroen Wijnhout (Jeroen.Wijnhout@kdemail.net) (C) 2006 by Thomas Braun (thomas.braun@virtuell-zuhause.de) (C) 2006-2018 by Michel Ludwig (michel.ludwig@kdemail.net) **************************************************************************************/ /*************************************************************************** * * * 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. * * * ***************************************************************************/ #include "sidebar.h" #include #include #include #include "kiledebug.h" namespace KileWidget { SideBar::SideBar(QWidget *parent, Qt::Orientation orientation /*= Vertical*/) - : QWidget(parent), - m_orientation(orientation), - m_minimized(true), - m_directionalSize(0) + : QWidget(parent), + m_orientation(orientation), + m_minimized(true), + m_directionalSize(0) { QBoxLayout *layout = Q_NULLPTR, *extraLayout = Q_NULLPTR; KMultiTabBar::KMultiTabBarPosition tabbarpos = KMultiTabBar::Top; m_extraWidget = new QWidget(this); if (orientation == Qt::Horizontal) { layout = new QVBoxLayout(this); extraLayout = new QHBoxLayout(m_extraWidget); tabbarpos = KMultiTabBar::Top; } else if(orientation == Qt::Vertical) { layout = new QHBoxLayout(this); extraLayout = new QVBoxLayout(m_extraWidget); tabbarpos = KMultiTabBar::Left; } m_tabStack = new QStackedWidget(this); m_tabStack->setSizePolicy(QSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding)); m_tabStack->setVisible(false); m_tabBar = new KMultiTabBar(tabbarpos, this); m_tabBar->setStyle(KMultiTabBar::KDEV3ICON); m_extraWidget->setLayout(extraLayout); extraLayout->addWidget(m_tabBar); if(orientation == Qt::Horizontal) { layout->addWidget(m_tabStack); layout->addWidget(m_extraWidget); m_tabBar->setSizePolicy(QSizePolicy(QSizePolicy::Expanding, QSizePolicy::Minimum)); } else if(orientation == Qt::Vertical) { layout->addWidget(m_extraWidget); layout->addWidget(m_tabStack); m_tabBar->setSizePolicy(QSizePolicy(QSizePolicy::Minimum, QSizePolicy::Expanding)); } layout->setMargin(0); layout->setSpacing(0); extraLayout->setMargin(0); extraLayout->setSpacing(0); setLayout(layout); } SideBar::~SideBar() { } int SideBar::addPage(QWidget *widget, const QIcon &pic, const QString &text /* = QString()*/) { int index = m_tabStack->addWidget(widget); m_tabBar->appendTab(pic, index, text); connect(m_tabBar->tab(index), SIGNAL(clicked(int)), this, SLOT(tabClicked(int))); switchToTab(index); return index; } void SideBar::removePage(QWidget *w) { int nTabs = m_tabStack->count(); int index = m_tabStack->indexOf(w); int currentIndex = currentTab(); m_tabStack->removeWidget(w); disconnect(m_tabBar->tab(index), SIGNAL(clicked(int)), this, SLOT(showTab(int))); m_tabBar->removeTab(index); if(index == currentIndex && nTabs >= 2) { switchToTab(findNextShownTab(index)); } } QWidget* SideBar::currentPage() { if(isMinimized()) { return Q_NULLPTR; } return m_tabStack->currentWidget(); } int SideBar::currentTab() { if(m_minimized) { return -1; } return m_tabStack->currentIndex(); } bool SideBar::isMinimized() { return m_minimized; } int SideBar::count() { return m_tabStack->count(); } void SideBar::shrink() { KILE_DEBUG_MAIN; if(isMinimized()) { return; } int currentIndex = currentTab(); // before changing m_minimized! m_tabStack->setVisible(false); m_minimized = true; if(m_orientation == Qt::Horizontal) { m_directionalSize = height(); setFixedHeight(m_tabBar->sizeHint().height()); } else if(m_orientation == Qt::Vertical) { m_directionalSize = width(); setFixedWidth(m_tabBar->sizeHint().width()); } // deselect the currect tab m_tabBar->setTab(currentIndex, false); emit visibilityChanged(false); } void SideBar::expand() { KILE_DEBUG_MAIN; if(!isMinimized()) { return; } KILE_DEBUG_MAIN << "directional size = " << m_directionalSize; if(m_orientation == Qt::Horizontal) { setMinimumHeight(0); setMaximumHeight(QWIDGETSIZE_MAX); m_tabStack->resize(m_tabStack->width(), m_directionalSize); } else if(m_orientation == Qt::Vertical) { setMinimumWidth(0); setMaximumWidth(QWIDGETSIZE_MAX); m_tabStack->resize(m_directionalSize, m_tabStack->height()); } m_tabStack->setVisible(true); m_minimized = false; emit visibilityChanged(true); } void SideBar::tabClicked(int i) { int currentIndex = currentTab(); if(i == currentIndex && !isMinimized()) { shrink(); } else { switchToTab(i); } } int SideBar::findNextShownTab(int i) { int nTabs = m_tabStack->count(); if(nTabs <= 0) { return -1; } for(int j = 1; j < nTabs; ++j) { int index = (i + j) % nTabs; if(m_tabBar->tab(index)->isVisible()) { return index; } } return -1; } void SideBar::setPageVisible(QWidget *w, bool b) { int nTabs = m_tabStack->count(); int index = m_tabStack->indexOf(w); int currentIndex = currentTab(); if(index < 0) { KILE_WARNING_MAIN << "widget" << w << "not found in side bar!"; return; } KMultiTabBarTab *tab = m_tabBar->tab(index); tab->setVisible(b); if(!b && index == currentIndex && nTabs >= 2) { switchToTab(findNextShownTab(index)); } } void SideBar::showPage(QWidget *widget) { KILE_DEBUG_MAIN << "===SideBar::showPage(" << widget << ")"; int i = m_tabStack->indexOf(widget); KILE_DEBUG_MAIN << "i is " << i; if(i >= 0) { switchToTab(i); } } int SideBar::directionalSize() { if(m_minimized) { return m_directionalSize; } if(m_orientation == Qt::Horizontal) { return m_tabStack->height(); } else if(m_orientation == Qt::Vertical) { return m_tabStack->width(); } return 0; } void SideBar::setDirectionalSize(int i) { KILE_DEBUG_MAIN << "size = " << i; m_directionalSize = i; if(m_orientation == Qt::Horizontal) { m_tabStack->resize(m_tabStack->width(), i); } else if(m_orientation == Qt::Vertical) { m_tabStack->resize(i, m_tabStack->height()); } } void SideBar::addExtraWidget(QWidget *w) { m_extraWidget->layout()->addWidget(w); } void SideBar::switchToTab(int id) { KILE_DEBUG_MAIN << "id = " << id; int nTabs = m_tabStack->count(); int currentIndex = currentTab(); if(id >= nTabs || id < 0 || m_tabBar->tab(id)->isHidden()) { shrink(); return; } // currentIndex == id is allowed if we are expanding, for example if(currentIndex >= 0) { m_tabBar->setTab(currentIndex, false); } m_tabBar->setTab(id, true); m_tabStack->setCurrentIndex(id); expand(); } BottomBar::BottomBar(QWidget *parent) : SideBar(parent, Qt::Horizontal) { } } diff --git a/src/widgets/statisticswidget.cpp b/src/widgets/statisticswidget.cpp index 89f1c679..49f5ebde 100644 --- a/src/widgets/statisticswidget.cpp +++ b/src/widgets/statisticswidget.cpp @@ -1,154 +1,154 @@ /*************************************************************************** begin : Tuesday Nov 15 2005 copyright : (C) 2005 by Holger Danielsson email : holger.danielsson@t-online.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. * * * ***************************************************************************/ #include "widgets/statisticswidget.h" #include #include #include #include #include #include #include #include #include #include #include "kiledebug.h" namespace KileWidget { StatisticsWidget::StatisticsWidget(QWidget* parent, const char *name, Qt::WindowFlags fl) - : QWidget(parent, fl) + : QWidget(parent, fl) { - setObjectName(name); - QVBoxLayout *vbox = new QVBoxLayout; - vbox->setMargin(0); + setObjectName(name); + QVBoxLayout *vbox = new QVBoxLayout; + vbox->setMargin(0); //TODO PORT QT5 vbox->setSpacing(QDialog::spacingHint()); - setLayout(vbox); + setLayout(vbox); - // characters groupbox - m_charactersGroup = new QGroupBox(i18n("Characters"), this); - chargrouplayout = new QGridLayout(); + // characters groupbox + m_charactersGroup = new QGroupBox(i18n("Characters"), this); + chargrouplayout = new QGridLayout(); //TODO PORT QT5 chargrouplayout->setMargin(QDialog::marginHint()); //TODO PORT QT5 chargrouplayout->setSpacing(QDialog::spacingHint()); - chargrouplayout->setAlignment(Qt::AlignTop); - m_charactersGroup->setLayout(chargrouplayout); - - m_wordCharText = new QLabel(i18n("Words and numbers:"), m_charactersGroup); - m_commandCharText = new QLabel(i18n("LaTeX commands and environments:"), m_charactersGroup); - m_whitespaceCharText = new QLabel(i18n("Punctuation, delimiter and whitespaces:"), m_charactersGroup); - m_totalCharText = new QLabel(i18n("Total characters:"), m_charactersGroup); - m_wordChar = new QLabel(m_charactersGroup); - m_wordChar->setObjectName("m_wordChar"); - m_commandChar = new QLabel(m_charactersGroup); - m_commandChar->setObjectName("m_commandChar"); - m_whitespaceChar = new QLabel(m_charactersGroup); - m_whitespaceChar->setObjectName("m_whitespaceChar"); - m_totalChar = new QLabel(m_charactersGroup); - m_totalChar->setObjectName("m_totalChar"); - - QFrame *charframe = new QFrame(m_charactersGroup); - charframe->setFrameShape(QFrame::HLine); - charframe->setFrameShadow(QFrame::Sunken); - charframe->setLineWidth(1); - - chargrouplayout->addWidget(m_wordCharText, 0, 0); - chargrouplayout->addWidget(m_commandCharText, 1, 0); - chargrouplayout->addWidget(m_whitespaceCharText, 2, 0); - chargrouplayout->addWidget(m_totalCharText, 4, 0); - chargrouplayout->addWidget(m_wordChar, 0, 2, Qt::AlignRight); - chargrouplayout->addWidget(m_commandChar, 1, 2, Qt::AlignRight); - chargrouplayout->addWidget(m_whitespaceChar, 2, 2, Qt::AlignRight); - chargrouplayout->addWidget(charframe, 3, 3, 1, 2); - chargrouplayout->addWidget(m_totalChar, 4, 2, Qt::AlignRight); - chargrouplayout->setColumnMinimumWidth(1, 16); - chargrouplayout->setColumnMinimumWidth(3, 1); - chargrouplayout->setColumnStretch(3, 1); - - // string groupbox - m_stringsGroup = new QGroupBox(i18n("Strings"), this); - stringgrouplayout = new QGridLayout(); + chargrouplayout->setAlignment(Qt::AlignTop); + m_charactersGroup->setLayout(chargrouplayout); + + m_wordCharText = new QLabel(i18n("Words and numbers:"), m_charactersGroup); + m_commandCharText = new QLabel(i18n("LaTeX commands and environments:"), m_charactersGroup); + m_whitespaceCharText = new QLabel(i18n("Punctuation, delimiter and whitespaces:"), m_charactersGroup); + m_totalCharText = new QLabel(i18n("Total characters:"), m_charactersGroup); + m_wordChar = new QLabel(m_charactersGroup); + m_wordChar->setObjectName("m_wordChar"); + m_commandChar = new QLabel(m_charactersGroup); + m_commandChar->setObjectName("m_commandChar"); + m_whitespaceChar = new QLabel(m_charactersGroup); + m_whitespaceChar->setObjectName("m_whitespaceChar"); + m_totalChar = new QLabel(m_charactersGroup); + m_totalChar->setObjectName("m_totalChar"); + + QFrame *charframe = new QFrame(m_charactersGroup); + charframe->setFrameShape(QFrame::HLine); + charframe->setFrameShadow(QFrame::Sunken); + charframe->setLineWidth(1); + + chargrouplayout->addWidget(m_wordCharText, 0, 0); + chargrouplayout->addWidget(m_commandCharText, 1, 0); + chargrouplayout->addWidget(m_whitespaceCharText, 2, 0); + chargrouplayout->addWidget(m_totalCharText, 4, 0); + chargrouplayout->addWidget(m_wordChar, 0, 2, Qt::AlignRight); + chargrouplayout->addWidget(m_commandChar, 1, 2, Qt::AlignRight); + chargrouplayout->addWidget(m_whitespaceChar, 2, 2, Qt::AlignRight); + chargrouplayout->addWidget(charframe, 3, 3, 1, 2); + chargrouplayout->addWidget(m_totalChar, 4, 2, Qt::AlignRight); + chargrouplayout->setColumnMinimumWidth(1, 16); + chargrouplayout->setColumnMinimumWidth(3, 1); + chargrouplayout->setColumnStretch(3, 1); + + // string groupbox + m_stringsGroup = new QGroupBox(i18n("Strings"), this); + stringgrouplayout = new QGridLayout(); //TODO PORT QT5 stringgrouplayout->setMargin(QDialog::marginHint()); //TODO PORT QT5 stringgrouplayout->setSpacing(QDialog::spacingHint()); - stringgrouplayout->setAlignment(Qt::AlignTop); - m_stringsGroup->setLayout(stringgrouplayout); - - m_wordStringText = new QLabel(i18n("Words:"), m_stringsGroup); - m_commandStringText = new QLabel(i18n("LaTeX commands:"), m_stringsGroup); - m_environmentStringText = new QLabel(i18n("LaTeX environments:"), m_stringsGroup); - m_totalStringText = new QLabel(i18n("Total strings:"), m_stringsGroup); - m_wordString = new QLabel(m_stringsGroup); - m_wordString->setObjectName("m_wordString"); - m_commandString = new QLabel(m_stringsGroup); - m_commandString->setObjectName("m_commandStringText"); - m_environmentString = new QLabel(m_stringsGroup); - m_environmentString->setObjectName("m_environmentStringText"); - m_totalString = new QLabel(m_stringsGroup); - m_totalString->setObjectName("m_totalStringText"); - - QFrame *stringframe = new QFrame(m_stringsGroup); - stringframe->setFrameShape(QFrame::HLine); - stringframe->setFrameShadow(QFrame::Sunken); - stringframe->setLineWidth(1); - - stringgrouplayout->addWidget(m_wordStringText, 0, 0); - stringgrouplayout->addWidget(m_commandStringText, 1, 0); - stringgrouplayout->addWidget(m_environmentStringText, 2, 0); - stringgrouplayout->addWidget(m_totalStringText, 4, 0); - stringgrouplayout->addWidget(m_wordString, 0, 2, Qt::AlignRight); - stringgrouplayout->addWidget(m_commandString, 1, 2, Qt::AlignRight); - stringgrouplayout->addWidget(m_environmentString, 2, 2, Qt::AlignRight); - stringgrouplayout->addWidget(stringframe, 3, 3, 1, 2); - stringgrouplayout->addWidget(m_totalString, 4, 2, Qt::AlignRight); - stringgrouplayout->setColumnMinimumWidth(1, 16); - stringgrouplayout->setColumnMinimumWidth(3, 1); - stringgrouplayout->setColumnStretch(3, 1); - - m_commentAboutHelp = new QLabel(parent); - m_warning = new QLabel(parent); - - vbox->addWidget(m_charactersGroup); - vbox->addWidget(m_stringsGroup); - vbox->addSpacing(12); - vbox->addWidget(m_commentAboutHelp); - vbox->addWidget(m_warning); - vbox->addStretch(1); - - int w = m_commandCharText->sizeHint().width(); - if (m_whitespaceCharText->sizeHint().width() > w) { - w = m_whitespaceCharText->sizeHint().width(); - } - stringgrouplayout->setColumnMinimumWidth(0, w); + stringgrouplayout->setAlignment(Qt::AlignTop); + m_stringsGroup->setLayout(stringgrouplayout); + + m_wordStringText = new QLabel(i18n("Words:"), m_stringsGroup); + m_commandStringText = new QLabel(i18n("LaTeX commands:"), m_stringsGroup); + m_environmentStringText = new QLabel(i18n("LaTeX environments:"), m_stringsGroup); + m_totalStringText = new QLabel(i18n("Total strings:"), m_stringsGroup); + m_wordString = new QLabel(m_stringsGroup); + m_wordString->setObjectName("m_wordString"); + m_commandString = new QLabel(m_stringsGroup); + m_commandString->setObjectName("m_commandStringText"); + m_environmentString = new QLabel(m_stringsGroup); + m_environmentString->setObjectName("m_environmentStringText"); + m_totalString = new QLabel(m_stringsGroup); + m_totalString->setObjectName("m_totalStringText"); + + QFrame *stringframe = new QFrame(m_stringsGroup); + stringframe->setFrameShape(QFrame::HLine); + stringframe->setFrameShadow(QFrame::Sunken); + stringframe->setLineWidth(1); + + stringgrouplayout->addWidget(m_wordStringText, 0, 0); + stringgrouplayout->addWidget(m_commandStringText, 1, 0); + stringgrouplayout->addWidget(m_environmentStringText, 2, 0); + stringgrouplayout->addWidget(m_totalStringText, 4, 0); + stringgrouplayout->addWidget(m_wordString, 0, 2, Qt::AlignRight); + stringgrouplayout->addWidget(m_commandString, 1, 2, Qt::AlignRight); + stringgrouplayout->addWidget(m_environmentString, 2, 2, Qt::AlignRight); + stringgrouplayout->addWidget(stringframe, 3, 3, 1, 2); + stringgrouplayout->addWidget(m_totalString, 4, 2, Qt::AlignRight); + stringgrouplayout->setColumnMinimumWidth(1, 16); + stringgrouplayout->setColumnMinimumWidth(3, 1); + stringgrouplayout->setColumnStretch(3, 1); + + m_commentAboutHelp = new QLabel(parent); + m_warning = new QLabel(parent); + + vbox->addWidget(m_charactersGroup); + vbox->addWidget(m_stringsGroup); + vbox->addSpacing(12); + vbox->addWidget(m_commentAboutHelp); + vbox->addWidget(m_warning); + vbox->addStretch(1); + + int w = m_commandCharText->sizeHint().width(); + if (m_whitespaceCharText->sizeHint().width() > w) { + w = m_whitespaceCharText->sizeHint().width(); + } + stringgrouplayout->setColumnMinimumWidth(0, w); } StatisticsWidget::~StatisticsWidget() { } void StatisticsWidget::updateColumns() { - int w = m_totalChar->sizeHint().width(); - if (m_totalString->sizeHint().width() > w) { - w = m_totalString->sizeHint().width(); - } - chargrouplayout->setColumnMinimumWidth(2, w); - stringgrouplayout->setColumnMinimumWidth(2, w); + int w = m_totalChar->sizeHint().width(); + if (m_totalString->sizeHint().width() > w) { + w = m_totalString->sizeHint().width(); + } + chargrouplayout->setColumnMinimumWidth(2, w); + stringgrouplayout->setColumnMinimumWidth(2, w); } } diff --git a/src/widgets/statisticswidget.h b/src/widgets/statisticswidget.h index b680c997..e50b54d5 100644 --- a/src/widgets/statisticswidget.h +++ b/src/widgets/statisticswidget.h @@ -1,72 +1,72 @@ /*************************************************************************** begin : Tuesday Nov 15 2005 copyright : (C) 2005 by Holger Danielsson email : holger.danielsson@t-online.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. * * * ***************************************************************************/ #ifndef STATISTICSWIDGET_H #define STATISTICSWIDGET_H #include #include class QLabel; class QGridLayout; namespace KileDialog { - class StatisticsDialog; +class StatisticsDialog; } namespace KileWidget { class StatisticsWidget : public QWidget { - friend class KileDialog::StatisticsDialog; - Q_OBJECT - - public: - explicit StatisticsWidget(QWidget* parent = 0, const char* name = 0, Qt::WindowFlags fl = 0); - ~StatisticsWidget(); - - void updateColumns(); - - private: - QLabel* m_commentAboutHelp; - QLabel* m_warning; - - QLabel* m_wordChar; - QLabel* m_commandChar; - QLabel* m_whitespaceChar; - QLabel* m_totalChar; - QLabel* m_wordCharText; - QLabel* m_commandCharText; - QLabel* m_whitespaceCharText; - QLabel* m_totalCharText; - - QLabel* m_wordString; - QLabel* m_environmentString; - QLabel* m_commandString; - QLabel* m_totalString; - QLabel* m_wordStringText; - QLabel* m_environmentStringText; - QLabel* m_commandStringText; - QLabel* m_totalStringText; - - QGroupBox *m_charactersGroup, *m_stringsGroup; - - QGridLayout *chargrouplayout; - QGridLayout *stringgrouplayout; + friend class KileDialog::StatisticsDialog; + Q_OBJECT + +public: + explicit StatisticsWidget(QWidget* parent = 0, const char* name = 0, Qt::WindowFlags fl = 0); + ~StatisticsWidget(); + + void updateColumns(); + +private: + QLabel* m_commentAboutHelp; + QLabel* m_warning; + + QLabel* m_wordChar; + QLabel* m_commandChar; + QLabel* m_whitespaceChar; + QLabel* m_totalChar; + QLabel* m_wordCharText; + QLabel* m_commandCharText; + QLabel* m_whitespaceCharText; + QLabel* m_totalCharText; + + QLabel* m_wordString; + QLabel* m_environmentString; + QLabel* m_commandString; + QLabel* m_totalString; + QLabel* m_wordStringText; + QLabel* m_environmentStringText; + QLabel* m_commandStringText; + QLabel* m_totalStringText; + + QGroupBox *m_charactersGroup, *m_stringsGroup; + + QGridLayout *chargrouplayout; + QGridLayout *stringgrouplayout; }; } #endif diff --git a/src/widgets/statusbar.cpp b/src/widgets/statusbar.cpp index 45547c7f..d5fffcd3 100644 --- a/src/widgets/statusbar.cpp +++ b/src/widgets/statusbar.cpp @@ -1,105 +1,105 @@ /************************************************************************************************* Copyright (C) 2015 Andreas Cord-Landwehr (cordlandwehr@kde.org) 2016 by Michel Ludwig (michel.ludwig@kdemail.net) *************************************************************************************************/ /*************************************************************************** * * * 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. * * * ***************************************************************************/ #include "statusbar.h" #include #include #include "errorhandler.h" #include "kiledebug.h" KileWidget::StatusBar::StatusBar(KileErrorHandler *errorHandler, QWidget* parent) - : QStatusBar(parent), - m_errorHandler(errorHandler) + : QStatusBar(parent), + m_errorHandler(errorHandler) { - m_hintTextLabel = new QLabel(); - m_parserStatusLabel = new QLabel(); - m_lineColumnLabel = new QLabel(); - m_viewModeLabel = new QLabel(); - m_selectionModeLabel = new QLabel(); - - addPermanentWidget(m_hintTextLabel, 10); - addPermanentWidget(m_errorHandler->compilationResultLabel()); - addPermanentWidget(m_parserStatusLabel, 0); - addPermanentWidget(m_lineColumnLabel, 0); - addPermanentWidget(m_viewModeLabel, 0); - addPermanentWidget(m_selectionModeLabel, 0); - - reset(); + m_hintTextLabel = new QLabel(); + m_parserStatusLabel = new QLabel(); + m_lineColumnLabel = new QLabel(); + m_viewModeLabel = new QLabel(); + m_selectionModeLabel = new QLabel(); + + addPermanentWidget(m_hintTextLabel, 10); + addPermanentWidget(m_errorHandler->compilationResultLabel()); + addPermanentWidget(m_parserStatusLabel, 0); + addPermanentWidget(m_lineColumnLabel, 0); + addPermanentWidget(m_viewModeLabel, 0); + addPermanentWidget(m_selectionModeLabel, 0); + + reset(); } KileWidget::StatusBar::~StatusBar() { } void KileWidget::StatusBar::setHintText(const QString& text) { - m_hintTextLabel->setText(text); + m_hintTextLabel->setText(text); } void KileWidget::StatusBar::clearHintText() { - m_hintTextLabel->clear(); + m_hintTextLabel->clear(); } void KileWidget::StatusBar::setParserStatus(const QString& text) { - m_parserStatusLabel->setText(text); + m_parserStatusLabel->setText(text); } void KileWidget::StatusBar::clearParserStatus() { - m_parserStatusLabel->clear(); + m_parserStatusLabel->clear(); } void KileWidget::StatusBar::setLineColumn(int line, int column) { - m_lineColumnLabel->setText(i18n("Line: %1 Col: %2", line, column)); + m_lineColumnLabel->setText(i18n("Line: %1 Col: %2", line, column)); } void KileWidget::StatusBar::clearLineColumn() { - m_lineColumnLabel->clear(); + m_lineColumnLabel->clear(); } void KileWidget::StatusBar::setViewMode(const QString& text) { - m_viewModeLabel->setText(text); + m_viewModeLabel->setText(text); } void KileWidget::StatusBar::clearViewMode() { - m_viewModeLabel->clear(); + m_viewModeLabel->clear(); } void KileWidget::StatusBar::setSelectionMode(const QString& text) { - m_selectionModeLabel->setText(text); + m_selectionModeLabel->setText(text); } void KileWidget::StatusBar::clearSelectionMode() { - m_selectionModeLabel->clear(); + m_selectionModeLabel->clear(); } void KileWidget::StatusBar::reset() { - clearHintText(); - clearParserStatus(); - clearLineColumn(); - clearViewMode(); - clearSelectionMode(); + clearHintText(); + clearParserStatus(); + clearLineColumn(); + clearViewMode(); + clearSelectionMode(); } diff --git a/src/widgets/statusbar.h b/src/widgets/statusbar.h index 65a2df3e..da47a9e0 100644 --- a/src/widgets/statusbar.h +++ b/src/widgets/statusbar.h @@ -1,61 +1,61 @@ /************************************************************************************************* Copyright (C) 2015 Andreas Cord-Landwehr (cordlandwehr@kde.org) 2016 by Michel Ludwig (michel.ludwig@kdemail.net) *************************************************************************************************/ /*************************************************************************** * * * 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. * * * ***************************************************************************/ #ifndef KILESTATUSBAR_H #define KILESTATUSBAR_H #include class QLabel; class KileErrorHandler; namespace KileWidget { class StatusBar : public QStatusBar { - Q_OBJECT + Q_OBJECT public: - StatusBar(KileErrorHandler *errorHandler, QWidget *parent = Q_NULLPTR); - ~StatusBar(); + StatusBar(KileErrorHandler *errorHandler, QWidget *parent = Q_NULLPTR); + ~StatusBar(); public: - void setHintText(const QString& text); - void clearHintText(); + void setHintText(const QString& text); + void clearHintText(); - void setParserStatus(const QString& text); - void clearParserStatus(); + void setParserStatus(const QString& text); + void clearParserStatus(); - void setLineColumn(int line, int column); - void clearLineColumn(); + void setLineColumn(int line, int column); + void clearLineColumn(); - void setViewMode(const QString& text); - void clearViewMode(); + void setViewMode(const QString& text); + void clearViewMode(); - void setSelectionMode(const QString& text); - void clearSelectionMode(); + void setSelectionMode(const QString& text); + void clearSelectionMode(); - void reset(); + void reset(); private: - KileErrorHandler * const m_errorHandler; - QLabel *m_hintTextLabel; - QLabel *m_lineColumnLabel; - QLabel *m_viewModeLabel; - QLabel *m_selectionModeLabel; - QLabel *m_parserStatusLabel; + KileErrorHandler * const m_errorHandler; + QLabel *m_hintTextLabel; + QLabel *m_lineColumnLabel; + QLabel *m_viewModeLabel; + QLabel *m_selectionModeLabel; + QLabel *m_parserStatusLabel; }; } #endif diff --git a/src/widgets/structureviewconfigwidget.cpp b/src/widgets/structureviewconfigwidget.cpp index f0e902de..04b9ddfc 100644 --- a/src/widgets/structureviewconfigwidget.cpp +++ b/src/widgets/structureviewconfigwidget.cpp @@ -1,24 +1,24 @@ /************************************************************************** * Copyright (C) 2007 by Michel Ludwig (michel.ludwig@kdemail.net) * ***************************************************************************/ /************************************************************************** * * * 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. * * * ***************************************************************************/ #include "structureviewconfigwidget.h" KileWidgetStructureViewConfig::KileWidgetStructureViewConfig(QWidget *parent) : QWidget(parent) { - setupUi(this); + setupUi(this); } KileWidgetStructureViewConfig::~KileWidgetStructureViewConfig() { } diff --git a/src/widgets/structureviewconfigwidget.h b/src/widgets/structureviewconfigwidget.h index 760cbe3f..aba9ece4 100644 --- a/src/widgets/structureviewconfigwidget.h +++ b/src/widgets/structureviewconfigwidget.h @@ -1,30 +1,30 @@ /************************************************************************** * Copyright (C) 2007 by Michel Ludwig (michel.ludwig@kdemail.net) * ***************************************************************************/ /************************************************************************** * * * 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. * * * ***************************************************************************/ #ifndef STRUCTUREVIEWCONFIGWIDGET_H #define STRUCTUREVIEWCONFIGWIDGET_H #include #include "ui_structureviewconfigwidget.h" class KileWidgetStructureViewConfig : public QWidget, public Ui::KileWidgetStructureViewConfig { - Q_OBJECT + Q_OBJECT - public: - KileWidgetStructureViewConfig(QWidget *parent = 0); - ~KileWidgetStructureViewConfig(); +public: + KileWidgetStructureViewConfig(QWidget *parent = 0); + ~KileWidgetStructureViewConfig(); }; #endif diff --git a/src/widgets/structurewidget.cpp b/src/widgets/structurewidget.cpp index c1134772..c3660bc1 100644 --- a/src/widgets/structurewidget.cpp +++ b/src/widgets/structurewidget.cpp @@ -1,1092 +1,1092 @@ /************************************************************************************************* Copyright (C) 2003 by Jeroen Wijnhout (Jeroen.Wijnhout@kdemail.net 2005-2007 by Holger Danielsson (holger.danielsson@versanet.de) 2008-2016 by Michel Ludwig (michel.ludwig@kdemail.net) *************************************************************************************************/ /*************************************************************************** * * * 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. * * * ***************************************************************************/ // 2005-11-02: dani // - cleaning up source (local variables etc.) // - added different QToolTips for each item // - add more types of KilelistViewItems // - KileStruct::Sect and KileStruct::BeginFloat will remember assigned labels, // which are displayed as QToolTips, if these labels are defined in the // same or the next line // - Caption for type KileStruct::BeginFloat are displayed in the title // of this item // - \includegraphics and float environment items are displayed // - if an item has a companion label, you can use the context menu (right mouse) // to insert this label as reference, as a page reference or only the keyword // into the text or copy it to the clipboard. // - graphics files have also a context menu to open them with a special program // 2005-12-08: dani // - make some items like labels, bibitems, graphics and float environments // configurable for the user // 2005-12-16: dani // - add listview item for undefined references // 2007-02-15: dani // - class StructureViewItem gets two new members to // save the real cursor position of the command // 2007-03-12 dani // - use KileDocument::Extensions // 2007-03-17 dani // - remember how document structure is collapsed, when structure view is refreshed // 2007-03-24: dani // - preliminary minimal support for Beamer class // - \begin{frame}...\end{frame} and \frame{...} are shown in the structure view // - if a \frametitle command follows as next LaTeX command, its parameter // is taken to replace the standard title of this entry in the structure view // - \begin{block}...\end{block} is taken as child of a frame // 2007-04-06 dani // - add TODO/FIXME section to structure view #include "widgets/structurewidget.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include "documentinfo.h" #include "errorhandler.h" #include "kileconfig.h" #include "kiledebug.h" #include "kiledocmanager.h" #include "kileinfo.h" #include "kileproject.h" #include "kiletool_enums.h" #include "parser/parsermanager.h" #include "widgets/logwidget.h" namespace KileWidget { ////////////////////// StructureViewItem with all info ////////////////////// StructureViewItem::StructureViewItem(QTreeWidgetItem* parent, const QString &title, const QUrl &url, uint line, uint column, int type, int level, uint startline, uint startcol) : - QTreeWidgetItem(parent), - m_title(title), m_url(url), m_line(line), m_column(column), m_type(type), m_level(level), - m_startline(startline), m_startcol(startcol) + QTreeWidgetItem(parent), + m_title(title), m_url(url), m_line(line), m_column(column), m_type(type), m_level(level), + m_startline(startline), m_startcol(startcol) { - setItemEntry(); + setItemEntry(); } StructureViewItem::StructureViewItem(QTreeWidget* parent, const QString& label) : - QTreeWidgetItem(parent, QStringList(label)), - m_title(label), m_url(QUrl()), m_line(0), m_column(0), m_type(KileStruct::None), m_level(0) + QTreeWidgetItem(parent, QStringList(label)), + m_title(label), m_url(QUrl()), m_line(0), m_column(0), m_type(KileStruct::None), m_level(0) { - setToolTip(0, i18n("Click left to jump to the line. A double click will open\n a text file or a graphics file. When a label is assigned\nto this item, it will be shown when the mouse is over\nthis item. Items for a graphics file or an assigned label\nalso offer a context menu (right mouse button).")); + setToolTip(0, i18n("Click left to jump to the line. A double click will open\n a text file or a graphics file. When a label is assigned\nto this item, it will be shown when the mouse is over\nthis item. Items for a graphics file or an assigned label\nalso offer a context menu (right mouse button).")); } StructureViewItem::StructureViewItem(const QString& label, QTreeWidgetItem* parent) : - QTreeWidgetItem(parent, QStringList(label)), - m_title(label), m_url(QUrl()), m_line(0), m_column(0), m_type(KileStruct::None), m_level(0) + QTreeWidgetItem(parent, QStringList(label)), + m_title(label), m_url(QUrl()), m_line(0), m_column(0), m_type(KileStruct::None), m_level(0) {} void StructureViewItem::setTitle(const QString &title) { - m_title = title; - setItemEntry(); + m_title = title; + setItemEntry(); } void StructureViewItem::setItemEntry() { - setText(0, i18nc("structure view entry: title (line)", "%1 (line %2)", m_title, QString::number(m_line))); - setToolTip(0, text(0)); + setText(0, i18nc("structure view entry: title (line)", "%1 (line %2)", m_title, QString::number(m_line))); + setToolTip(0, text(0)); } void StructureViewItem::setLabel(const QString &label) { - m_label = label; - if(!m_label.isEmpty()) { - setToolTip(0, i18n("Label: %1", m_label)); - } + m_label = label; + if(!m_label.isEmpty()) { + setToolTip(0, i18n("Label: %1", m_label)); + } } ////////////////////// StructureView tree widget ////////////////////// - StructureView::StructureView(StructureWidget *stack, KileDocument::Info *docinfo) : - QTreeWidget(stack), - m_stack(stack), m_docinfo(docinfo) - { - stack->addWidget(this); - setColumnCount(1); - QStringList labelList; - labelList << i18n("Structure"); - setHeaderLabels(labelList); - - header()->hide(); - header()->setSectionResizeMode(QHeaderView::ResizeToContents); - setAllColumnsShowFocus(true); - setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Ignored); - - //connect(this, SIGNAL(clicked(QListViewItem *)), m_stack, SLOT(slotClicked(QListViewItem *))); - connect(this, SIGNAL(itemDoubleClicked(QTreeWidgetItem*,int)), m_stack, SLOT(slotDoubleClicked(QTreeWidgetItem*))); - - connect(this, SIGNAL(itemClicked(QTreeWidgetItem*,int)), m_stack, SLOT(slotClicked(QTreeWidgetItem*))); - connect(m_stack, SIGNAL(configChanged()), this, SLOT(slotConfigChanged())); - - init(); - } - - StructureView::~StructureView() {} - - void StructureView::init() - { - QString title = (!m_docinfo) ? i18n("No \"structure data\" to display.") : m_docinfo->url().fileName(); - m_root = new StructureViewItem(this, title); - if(m_docinfo) { - m_root->setURL(m_docinfo->url()); - m_root->setExpanded(true); - m_root->setIcon(0, QIcon::fromTheme("contents")); - connect(m_docinfo, SIGNAL(foundItem(const QString&, uint, uint, int, int, uint, uint, const QString &, const QString &)), - this, SLOT(addItem(const QString&, uint, uint, int, int, uint, uint, const QString &, const QString &))); - } - - m_parent[0]=m_parent[1]=m_parent[2]=m_parent[3]=m_parent[4]=m_parent[5]=m_parent[6]=m_root; - m_lastType = KileStruct::None; - m_lastSectioning = Q_NULLPTR; - m_lastFloat = Q_NULLPTR; - m_lastFrame = Q_NULLPTR; - m_lastFrameEnv = Q_NULLPTR; - m_stop = false; - - m_folders.clear(); - m_references.clear(); - - if(m_docinfo) { - m_openStructureLabels = m_docinfo->openStructureLabels(); - m_openStructureReferences = m_docinfo->openStructureReferences(); - m_openStructureBibitems = m_docinfo->openStructureBibitems(); - m_openStructureTodo = m_docinfo->openStructureTodo(); - m_showStructureLabels = m_docinfo->showStructureLabels(); - } - else { - m_openStructureLabels = false; - m_openStructureReferences = false; - m_openStructureBibitems = false; - m_openStructureTodo = false; - m_showStructureLabels = false; - } - } - - void StructureView::updateRoot() - { - m_root->setURL( m_docinfo->url() ); - m_root->setText(0, m_docinfo->url().fileName() ); - } - - void StructureView::cleanUp(bool preserveState/* = true */) - { - KILE_DEBUG_MAIN << "==void StructureView::cleanUp()========"; - if(preserveState) { - saveState(); - } - clear(); - if(m_docinfo) { - disconnect(m_docinfo, 0, this, 0); - } - init(); - } - - void StructureView::slotConfigChanged(){ - QWidget *current = m_stack->currentWidget(); - if(!current) { - return; - } - cleanUp(false); - m_stack->update(m_docinfo, true); - } - - void StructureView::contextMenuEvent(QContextMenuEvent *event) - { - m_stack->viewContextMenuEvent(this, event); - } - - void StructureView::saveState() - { - KILE_DEBUG_MAIN << "===void StructureView::saveState()"; - m_openByTitle.clear(); - m_openByLine.clear(); - m_openByFolders.clear(); - - QTreeWidgetItemIterator it(this); - StructureViewItem *item = Q_NULLPTR; - while(*it) { - item = dynamic_cast(*it); - if(item && item->child(0)) { - //we don't accept duplicate entries in the map, remove this item alltogether - //and rely on the openByLine map instead - if(m_openByTitle.contains(item->title())) { - m_openByTitle.remove(item->title()); - } - else { - m_openByTitle[item->title()] = item->isExpanded(); - } - - m_openByLine[item->line()] = item->isExpanded(); - } - ++it; - } - - if(m_folders.contains("labels")) { - m_openByFolders["labels"] = m_folders["labels"]->isExpanded(); - } - if(m_folders.contains("refs")) { - m_openByFolders["refs"] = m_folders["refs"]->isExpanded(); - } - if(m_folders.contains("bibs")) { - m_openByFolders["bibs"] = m_folders["bibs"]->isExpanded(); - } - if(m_folders.contains("todo")) { - m_openByFolders["todo"] = m_folders["todo"]->isExpanded(); - } - if(m_folders.contains("fixme")) { - m_openByFolders["fixme"] = m_folders["fixme"]->isExpanded(); - } - } - - bool StructureView::shouldBeOpen(StructureViewItem *item, const QString & folder, int level) - { - if(!item->parent()) { - return true; - } - if(folder == "labels") { - if(m_openByFolders.contains("labels")) { - return m_openByFolders["labels"]; - } - else { - return m_openStructureLabels; - } - } - else if(folder == "refs") { - if(m_openByFolders.contains("refs")) { - return m_openByFolders["refs"]; - } - else { - return m_openStructureReferences; - } - } - else if(folder == "bibs") { - if(m_openByFolders.contains("bibs")) { - return m_openByFolders["bibs"]; - } - else { - return m_openStructureBibitems; - } - } - else if(folder=="todo" || folder=="fixme") { - if(m_openByFolders.contains(folder)) { - return m_openByFolders[folder]; - } - else { - return m_openStructureTodo; - } - } - - if(m_openByTitle.contains(item->title())) { - return m_openByTitle[item->title()]; - } - else if(m_openByLine.contains(item->line())) { - return m_openByLine[item->line()]; //TODO check surrounding lines as well - } - else { - return ((folder == "root") && level <= m_stack->level()); - } - } - - StructureViewItem* StructureView::createFolder(const QString &folder) - { - StructureViewItem *fldr = new StructureViewItem(folder); - // add it as a top-level child - m_root->insertChild(0, fldr); - fldr->setExpanded(false); - if(folder == "labels") { - fldr->setText(0, i18n("Labels")); - fldr->setIcon(0, QIcon::fromTheme("label")); - } - else if(folder == "bibs") { - fldr->setText(0, i18n("BibTeX References")); - fldr->setIcon(0, QIcon::fromTheme("viewbib")); - } - else if(folder == "refs") { - fldr->setText(0, i18n("Undefined References")); - fldr->setIcon(0, QIcon::fromTheme("dialog-error")); - } - else if(folder == "todo") { - fldr->setText(0, i18n("TODO")); - fldr->setIcon(0, QIcon::fromTheme("bookmarks")); - } - else if(folder == "fixme") { - fldr->setText(0, i18n("FIXME")); - fldr->setIcon(0, QIcon::fromTheme("bookmarks")); - } - - m_folders[folder] = fldr; - - return m_folders[folder]; - } - - StructureViewItem* StructureView::folder(const QString &folder) - { - StructureViewItem *item = m_folders[folder]; - if(!item) { - item = createFolder(folder); - } - return item; - } - - void StructureView::activate() - { - if(m_stack->indexOf(this) >= 0) { - m_stack->setCurrentWidget(this); - } - } - - StructureViewItem *StructureView::parentFor(int lev, const QString & fldr) - { - StructureViewItem *par = Q_NULLPTR; - - if(fldr == "root") { - switch(lev) { - case KileStruct::Object: - case KileStruct::File: - par = (!m_lastSectioning) ? m_root : m_lastSectioning; - break; - - case 0: - case 1: - par = m_root; - break; - - default: - par = m_parent[lev - 2]; - break; - } - } - else { - par = folder(fldr); - } - - return par; - } +StructureView::StructureView(StructureWidget *stack, KileDocument::Info *docinfo) : + QTreeWidget(stack), + m_stack(stack), m_docinfo(docinfo) +{ + stack->addWidget(this); + setColumnCount(1); + QStringList labelList; + labelList << i18n("Structure"); + setHeaderLabels(labelList); + + header()->hide(); + header()->setSectionResizeMode(QHeaderView::ResizeToContents); + setAllColumnsShowFocus(true); + setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Ignored); + + //connect(this, SIGNAL(clicked(QListViewItem *)), m_stack, SLOT(slotClicked(QListViewItem *))); + connect(this, SIGNAL(itemDoubleClicked(QTreeWidgetItem*,int)), m_stack, SLOT(slotDoubleClicked(QTreeWidgetItem*))); + + connect(this, SIGNAL(itemClicked(QTreeWidgetItem*,int)), m_stack, SLOT(slotClicked(QTreeWidgetItem*))); + connect(m_stack, SIGNAL(configChanged()), this, SLOT(slotConfigChanged())); + + init(); +} + +StructureView::~StructureView() {} + +void StructureView::init() +{ + QString title = (!m_docinfo) ? i18n("No \"structure data\" to display.") : m_docinfo->url().fileName(); + m_root = new StructureViewItem(this, title); + if(m_docinfo) { + m_root->setURL(m_docinfo->url()); + m_root->setExpanded(true); + m_root->setIcon(0, QIcon::fromTheme("contents")); + connect(m_docinfo, SIGNAL(foundItem(const QString&, uint, uint, int, int, uint, uint, const QString &, const QString &)), + this, SLOT(addItem(const QString&, uint, uint, int, int, uint, uint, const QString &, const QString &))); + } + + m_parent[0]=m_parent[1]=m_parent[2]=m_parent[3]=m_parent[4]=m_parent[5]=m_parent[6]=m_root; + m_lastType = KileStruct::None; + m_lastSectioning = Q_NULLPTR; + m_lastFloat = Q_NULLPTR; + m_lastFrame = Q_NULLPTR; + m_lastFrameEnv = Q_NULLPTR; + m_stop = false; + + m_folders.clear(); + m_references.clear(); + + if(m_docinfo) { + m_openStructureLabels = m_docinfo->openStructureLabels(); + m_openStructureReferences = m_docinfo->openStructureReferences(); + m_openStructureBibitems = m_docinfo->openStructureBibitems(); + m_openStructureTodo = m_docinfo->openStructureTodo(); + m_showStructureLabels = m_docinfo->showStructureLabels(); + } + else { + m_openStructureLabels = false; + m_openStructureReferences = false; + m_openStructureBibitems = false; + m_openStructureTodo = false; + m_showStructureLabels = false; + } +} + +void StructureView::updateRoot() +{ + m_root->setURL( m_docinfo->url() ); + m_root->setText(0, m_docinfo->url().fileName() ); +} + +void StructureView::cleanUp(bool preserveState/* = true */) +{ + KILE_DEBUG_MAIN << "==void StructureView::cleanUp()========"; + if(preserveState) { + saveState(); + } + clear(); + if(m_docinfo) { + disconnect(m_docinfo, 0, this, 0); + } + init(); +} + +void StructureView::slotConfigChanged() { + QWidget *current = m_stack->currentWidget(); + if(!current) { + return; + } + cleanUp(false); + m_stack->update(m_docinfo, true); +} + +void StructureView::contextMenuEvent(QContextMenuEvent *event) +{ + m_stack->viewContextMenuEvent(this, event); +} + +void StructureView::saveState() +{ + KILE_DEBUG_MAIN << "===void StructureView::saveState()"; + m_openByTitle.clear(); + m_openByLine.clear(); + m_openByFolders.clear(); + + QTreeWidgetItemIterator it(this); + StructureViewItem *item = Q_NULLPTR; + while(*it) { + item = dynamic_cast(*it); + if(item && item->child(0)) { + //we don't accept duplicate entries in the map, remove this item alltogether + //and rely on the openByLine map instead + if(m_openByTitle.contains(item->title())) { + m_openByTitle.remove(item->title()); + } + else { + m_openByTitle[item->title()] = item->isExpanded(); + } + + m_openByLine[item->line()] = item->isExpanded(); + } + ++it; + } + + if(m_folders.contains("labels")) { + m_openByFolders["labels"] = m_folders["labels"]->isExpanded(); + } + if(m_folders.contains("refs")) { + m_openByFolders["refs"] = m_folders["refs"]->isExpanded(); + } + if(m_folders.contains("bibs")) { + m_openByFolders["bibs"] = m_folders["bibs"]->isExpanded(); + } + if(m_folders.contains("todo")) { + m_openByFolders["todo"] = m_folders["todo"]->isExpanded(); + } + if(m_folders.contains("fixme")) { + m_openByFolders["fixme"] = m_folders["fixme"]->isExpanded(); + } +} + +bool StructureView::shouldBeOpen(StructureViewItem *item, const QString & folder, int level) +{ + if(!item->parent()) { + return true; + } + if(folder == "labels") { + if(m_openByFolders.contains("labels")) { + return m_openByFolders["labels"]; + } + else { + return m_openStructureLabels; + } + } + else if(folder == "refs") { + if(m_openByFolders.contains("refs")) { + return m_openByFolders["refs"]; + } + else { + return m_openStructureReferences; + } + } + else if(folder == "bibs") { + if(m_openByFolders.contains("bibs")) { + return m_openByFolders["bibs"]; + } + else { + return m_openStructureBibitems; + } + } + else if(folder=="todo" || folder=="fixme") { + if(m_openByFolders.contains(folder)) { + return m_openByFolders[folder]; + } + else { + return m_openStructureTodo; + } + } + + if(m_openByTitle.contains(item->title())) { + return m_openByTitle[item->title()]; + } + else if(m_openByLine.contains(item->line())) { + return m_openByLine[item->line()]; //TODO check surrounding lines as well + } + else { + return ((folder == "root") && level <= m_stack->level()); + } +} + +StructureViewItem* StructureView::createFolder(const QString &folder) +{ + StructureViewItem *fldr = new StructureViewItem(folder); + // add it as a top-level child + m_root->insertChild(0, fldr); + fldr->setExpanded(false); + if(folder == "labels") { + fldr->setText(0, i18n("Labels")); + fldr->setIcon(0, QIcon::fromTheme("label")); + } + else if(folder == "bibs") { + fldr->setText(0, i18n("BibTeX References")); + fldr->setIcon(0, QIcon::fromTheme("viewbib")); + } + else if(folder == "refs") { + fldr->setText(0, i18n("Undefined References")); + fldr->setIcon(0, QIcon::fromTheme("dialog-error")); + } + else if(folder == "todo") { + fldr->setText(0, i18n("TODO")); + fldr->setIcon(0, QIcon::fromTheme("bookmarks")); + } + else if(folder == "fixme") { + fldr->setText(0, i18n("FIXME")); + fldr->setIcon(0, QIcon::fromTheme("bookmarks")); + } + + m_folders[folder] = fldr; + + return m_folders[folder]; +} + +StructureViewItem* StructureView::folder(const QString &folder) +{ + StructureViewItem *item = m_folders[folder]; + if(!item) { + item = createFolder(folder); + } + return item; +} + +void StructureView::activate() +{ + if(m_stack->indexOf(this) >= 0) { + m_stack->setCurrentWidget(this); + } +} + +StructureViewItem *StructureView::parentFor(int lev, const QString & fldr) +{ + StructureViewItem *par = Q_NULLPTR; + + if(fldr == "root") { + switch(lev) { + case KileStruct::Object: + case KileStruct::File: + par = (!m_lastSectioning) ? m_root : m_lastSectioning; + break; + + case 0: + case 1: + par = m_root; + break; + + default: + par = m_parent[lev - 2]; + break; + } + } + else { + par = folder(fldr); + } + + return par; +} ////////////////////// add a new item to the tree widget ////////////////////// - /* some items have a special action: - - KileStruct::Sect: - The new item is saved in m_lastSectioning, so that all following entries - can be inserted as children. \part will drop back to level 0 of the Listview, - all other sectioning commands will be children of the last sectioning item. - If a \label command follows in the same or the next line, it is assigned - to this item. - - KileStruct::BeginFloat: - The new item is saved in m_lastFloat. If a \caption command follows before - the floating environment is closed, it is inserted into the title of this item. - If a \label command follows, it is assigned to this float item. - - KileStruct::EndFloat - Reset m_lastFloat to Q_NULLPTR to close this environment. No more \caption or \label - commands are assigned to this float after this. - - KileStruct::Caption - If a float environment is opened, the caption is assigned to the float item. - A caption item has hidden attribute, so that no other action is performed and - function addItem() will return immediately. - - KileStruct::Label - If we are inside a float, this label is assigned to this environment. If the last - type was a sectioning command on the current line or the line before, the label is - assigned to this sectioning item. Assigning means that a popup menu will open, - when the mouse is over this item. - - KileStruct::BeamerBeginFrame - The new item is saved in m_lastFrameEnv. If a \frametitle command follows before - the frame environment is closed, it is inserted into the title of this item. - If a \label command follows, it is assigned to this float item. - - KileStruct::BeamerEndFrame - Reset m_lastFloatEnv to Q_NULLPTR to close this environment. No more \frametitle - or \label commands are assigned to this frame after this. - - KileStruct::BeamerBeginBlock - Inside a beamer frame this environment is taken as child of this frame - - KileStruct::BeamerFrame - The new item is saved in m_lastFrame. If a \frametitle command follows - immediately as next command, it is inserted into the title of this item. - */ - - void StructureView::addItem(const QString &title, uint line, uint column, int type, int lev, - uint startline, uint startcol, - const QString &pix, const QString &fldr /* = "root" */) - { +/* some items have a special action: + - KileStruct::Sect: + The new item is saved in m_lastSectioning, so that all following entries + can be inserted as children. \part will drop back to level 0 of the Listview, + all other sectioning commands will be children of the last sectioning item. + If a \label command follows in the same or the next line, it is assigned + to this item. + - KileStruct::BeginFloat: + The new item is saved in m_lastFloat. If a \caption command follows before + the floating environment is closed, it is inserted into the title of this item. + If a \label command follows, it is assigned to this float item. + - KileStruct::EndFloat + Reset m_lastFloat to Q_NULLPTR to close this environment. No more \caption or \label + commands are assigned to this float after this. + - KileStruct::Caption + If a float environment is opened, the caption is assigned to the float item. + A caption item has hidden attribute, so that no other action is performed and + function addItem() will return immediately. + - KileStruct::Label + If we are inside a float, this label is assigned to this environment. If the last + type was a sectioning command on the current line or the line before, the label is + assigned to this sectioning item. Assigning means that a popup menu will open, + when the mouse is over this item. + - KileStruct::BeamerBeginFrame + The new item is saved in m_lastFrameEnv. If a \frametitle command follows before + the frame environment is closed, it is inserted into the title of this item. + If a \label command follows, it is assigned to this float item. + - KileStruct::BeamerEndFrame + Reset m_lastFloatEnv to Q_NULLPTR to close this environment. No more \frametitle + or \label commands are assigned to this frame after this. + - KileStruct::BeamerBeginBlock + Inside a beamer frame this environment is taken as child of this frame + - KileStruct::BeamerFrame + The new item is saved in m_lastFrame. If a \frametitle command follows + immediately as next command, it is inserted into the title of this item. + */ + +void StructureView::addItem(const QString &title, uint line, uint column, int type, int lev, + uint startline, uint startcol, + const QString &pix, const QString &fldr /* = "root" */) +{ // KILE_DEBUG_MAIN << "\t\taddItem: " << title << ", with type " << type; - if(m_stop) { - return; - } - - // some types need a special action - if(type == KileStruct::Reference) { - m_references.prepend(KileReferenceData(title, line, column)); - } - else if(type==KileStruct::Caption && m_lastFloat) { - QString floattitle = m_lastFloat->title(); - if(floattitle == "figure" || floattitle == "table") { - m_lastFloat->setTitle(floattitle+": "+title); - } - } - else if(type == KileStruct::EndFloat) { - m_lastFloat = Q_NULLPTR; - } - else if(type == KileStruct::BeamerFrametitle) { - if(m_lastFrameEnv) { - m_lastFrameEnv->setTitle(title); - } - else if(m_lastFrame) { - m_lastFrame->setTitle(title); - } - } - else if(type == KileStruct::BeamerEndFrame) { - m_lastFrameEnv = Q_NULLPTR; - } - m_lastFrame = Q_NULLPTR; - - // that's all for hidden types: we must immediately return - if(lev == KileStruct::Hidden) { - //KILE_DEBUG_MAIN << "\t\thidden item: not created"; - return; - } - - //KILE_DEBUG_MAIN << "\t\tcreate new item"; - // check if we have to update a label before loosing this item - if(type==KileStruct::Label) { - if(m_lastFloat) { - m_lastFloat->setLabel(title); - } - else if(m_lastType == KileStruct::Sect) { - // check if this is a follow up label for the last sectioning item - if(m_lastSectioning && (m_lastLine == line-1 || m_lastLine==line)) { - m_lastSectioning->setLabel(title); - } - } - else if(m_lastType == KileStruct::BeamerBeginFrame && m_lastFrameEnv) { - m_lastFrameEnv->setLabel(title); - } - - if(!m_showStructureLabels) { // if we don't want to have it displayed return here - return; - } - } - - // remember current type and line for the next call of addItem() - m_lastType = type; - m_lastLine = line; - - //find the parent for the new element - StructureViewItem *parentItem = (type == KileStruct::BeamerBeginBlock && m_lastFrameEnv) ? m_lastFrameEnv : parentFor(lev, fldr); - if(!parentItem) { - KMessageBox::error(m_stack->info()->mainWindow(), i18n("Cannot create a list view item: no parent found.")); - return; - } - - // create a new item - StructureViewItem *newChild = new StructureViewItem(parentItem, title, m_docinfo->url(), line, column, type, lev, startline, startcol); - if(!pix.isEmpty()) { - newChild->setIcon(0, QIcon::fromTheme(pix)); - } - //m_stop = true; - - //if the level is not greater than the defaultLevel - //open the parentItem to make this item visible - parentItem->setExpanded(shouldBeOpen(parentItem, fldr, lev)); - - //update the m_parent levels, such that section etc. get inserted at the correct level - //m_current = newChild; - if(lev > 0) { - m_parent[lev - 1] = newChild; - for(int l = lev; l < 7; ++l) { - m_parent[l] = newChild; - } - } - else if(lev == 0) { - m_lastSectioning = Q_NULLPTR; - for(int l = 0; l < 7; ++l) { - m_parent[l] = m_root; - } - } - - // check if we have to remember the new item for setting a label or caption - if(type == KileStruct::Sect) { - m_lastSectioning = newChild; - } - else if(type == KileStruct::BeginFloat) { - m_lastFloat = newChild; - } - else if(type == KileStruct::BeamerBeginFrame) { - m_lastFrameEnv = newChild; - } - else if(type == KileStruct::BeamerFrame) { - m_lastFrame = newChild; - } - } - - void StructureView::showReferences(KileInfo *ki) - { - // remove old listview item for references, if it exists - if(m_folders.contains("refs")) { - StructureViewItem *refitem = m_folders["refs"]; - m_root->removeChild(refitem); - delete refitem; - - m_folders.remove("refs"); - } - - //KILE_DEBUG_MAIN << "==void StructureView::showReferences()========"; - //KILE_DEBUG_MAIN << "\tfound " << m_references.count() << " references"; - if(m_references.count() == 0) { - return; - } - - // read list with all labels - QStringList list = ki->allLabels(); - //KILE_DEBUG_MAIN << "\tfound " << list.count() << " labels"; - QMap labelmap; - for (QStringList::const_iterator itmap = list.constBegin(); itmap != list.constEnd(); ++itmap) { - labelmap[(*itmap)] = true; - } - - // now check if there are unsolved references - for (QList::const_iterator it = m_references.constBegin(); it!=m_references.constEnd(); ++it) { - if(!labelmap.contains((*it).name())) { - StructureViewItem *refitem = folder("refs"); - refitem->setExpanded(shouldBeOpen(refitem, "refs", 0)); - new StructureViewItem(refitem, (*it).name(), m_docinfo->url(), (*it).line(), (*it).column(), KileStruct::Reference, KileStruct::NotSpecified, 0, 0); - } - } - } - - ////////////////////// StructureWidget: QWidgetStack ////////////////////// - - StructureWidget::StructureWidget(KileInfo *ki, QWidget * parent, const char* name) : - QStackedWidget(parent), - m_ki(ki), - m_docinfo(Q_NULLPTR), - m_showingContextMenu(Q_NULLPTR) - { - setObjectName(name); - KILE_DEBUG_MAIN << "==KileWidget::StructureWidget::StructureWidget()==========="; - setLineWidth(0); - setMidLineWidth(0); - setContentsMargins(0, 0, 0, 0); - setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Ignored); - - m_default = new StructureView(this, Q_NULLPTR); - m_default->activate(); - - connect(m_ki->parserManager(), SIGNAL(documentParsingStarted()), this, SLOT(handleDocumentParsingStarted())); - connect(m_ki->parserManager(), SIGNAL(documentParsingComplete()), this, SLOT(handleDocumentParsingCompleted())); - } - - StructureWidget::~StructureWidget() - { - } - - int StructureWidget::level() - { - return KileConfig::defaultLevel(); - } - - void StructureWidget::addDocumentInfo(KileDocument::Info *docinfo) - { - StructureView *view = new StructureView(this, docinfo); - addWidget(view); - m_map.insert(docinfo, view); - } - - void StructureWidget::slotClicked(QTreeWidgetItem * itm) - { - KILE_DEBUG_MAIN << "\tStructureWidget::slotClicked"; - - StructureViewItem *item = dynamic_cast(itm); - //return if user didn't click on an item - if(!item) { - return; - } - - if(!(item->type() & KileStruct::None)) { - emit(setCursor(item->url(), item->line()-1, item->column())); - } - else if(!item->parent()) { //root item - emit(setCursor(item->url(), 0, 0)); - } - } - - void StructureWidget::slotDoubleClicked(QTreeWidgetItem * itm) - { - KILE_DEBUG_MAIN << "\tStructureWidget::slotDoubleClicked"; - StructureViewItem *item = dynamic_cast(itm); - static QRegExp suffix("\\.[\\d\\w]*$"); - - if (!item) { - return; - } - - KILE_DEBUG_MAIN <<"item->url() is " << item->url() << ", item->title() is " << item->title(); - - if(item->type() & (KileStruct::Input | KileStruct::Bibliography | KileStruct::Graphics)) { - QString fname = item->title(); - - - if(fname.indexOf(suffix) != -1) { // check if we have a suffix, if not add standard suffixes - KILE_DEBUG_MAIN << "Suffix found: " << suffix.cap(0); - } - else { - // filename in structureview entry has no extension: this shouldn't happen anymore, - // because all have got one in function updateStruct(). But who knows? - if(item->type() == KileStruct::Input) { - fname += m_ki->extensions()->latexDocumentDefault(); - } - else if(item->type() == KileStruct::Bibliography) { - fname += m_ki->extensions()->bibtexDefault(); - } - else if(item->type() == KileStruct::Graphics){ - - KileProjectItem *kiItem = m_ki->docManager()->itemFor(item->url()); - KileProject *proj; - QString extToAdd; - bool fromProject = true; - - if(kiItem && (proj = kiItem->project())){ - extToAdd = proj->defaultGraphicExt(); - } - if(extToAdd.isEmpty()){ - extToAdd = KileConfig::svDefaultGraphicExt(); - fromProject = false; - } - - m_ki->errorHandler()->printMessage(KileTool::Info, - (fromProject ? - i18n("No extension specified for graphic file. Using .%1 from Project settings.", extToAdd) : - i18n("No extension specified for graphic file. Using .%1 from global Structure View settings.", extToAdd)), - i18n("File extension not specified")); - - fname += '.' + extToAdd; - - } - else{ - KILE_DEBUG_MAIN << "Suffixless item with unknown type found"; - } - - } - - if(QDir::isRelativePath(fname)) { // no absolute path - QString fn = m_ki->getCompileName(); - fname= QFileInfo(fn).path() + QDir::separator() + fname; - } - - QFileInfo fi(fname); - - if(fi.isReadable()) { - QUrl url = QUrl::fromLocalFile(fname); - if(item->type() == KileStruct::Graphics) { - QMimeDatabase db; - QMimeType pMime = db.mimeTypeForUrl(url); - KRun::runUrl(url, pMime.name(), this, KRun::RunFlags()); - } - else { - emit(fileOpen(url, QString())); - } - } - else { - QString otherFilename; - - if(item->type() == KileStruct::Bibliography) { - otherFilename = m_ki->checkOtherPaths(fi.path(), fi.fileName(), KileInfo::bibinputs); - } - else if(item->type() == KileStruct::Input) { - otherFilename = m_ki->checkOtherPaths(fi.path(), fi.fileName(), KileInfo::texinputs); - } - - fi.setFile(otherFilename); - - if(fi.isReadable()) { - emit(fileOpen(QUrl::fromLocalFile(otherFilename), QString())); - } - else { - if(KMessageBox::warningYesNo(this, i18n("Cannot find the included file. The file does not exist, is not readable or Kile is unable to determine the correct path to it. The filename causing this error was: %1.\nDo you want to create this file?", fname), i18n("Cannot Find File")) - == KMessageBox::Yes) { - emit(fileNew(QUrl::fromLocalFile(fname))); - } - } - } - } - } + if(m_stop) { + return; + } + + // some types need a special action + if(type == KileStruct::Reference) { + m_references.prepend(KileReferenceData(title, line, column)); + } + else if(type==KileStruct::Caption && m_lastFloat) { + QString floattitle = m_lastFloat->title(); + if(floattitle == "figure" || floattitle == "table") { + m_lastFloat->setTitle(floattitle+": "+title); + } + } + else if(type == KileStruct::EndFloat) { + m_lastFloat = Q_NULLPTR; + } + else if(type == KileStruct::BeamerFrametitle) { + if(m_lastFrameEnv) { + m_lastFrameEnv->setTitle(title); + } + else if(m_lastFrame) { + m_lastFrame->setTitle(title); + } + } + else if(type == KileStruct::BeamerEndFrame) { + m_lastFrameEnv = Q_NULLPTR; + } + m_lastFrame = Q_NULLPTR; + + // that's all for hidden types: we must immediately return + if(lev == KileStruct::Hidden) { + //KILE_DEBUG_MAIN << "\t\thidden item: not created"; + return; + } + + //KILE_DEBUG_MAIN << "\t\tcreate new item"; + // check if we have to update a label before loosing this item + if(type==KileStruct::Label) { + if(m_lastFloat) { + m_lastFloat->setLabel(title); + } + else if(m_lastType == KileStruct::Sect) { + // check if this is a follow up label for the last sectioning item + if(m_lastSectioning && (m_lastLine == line-1 || m_lastLine==line)) { + m_lastSectioning->setLabel(title); + } + } + else if(m_lastType == KileStruct::BeamerBeginFrame && m_lastFrameEnv) { + m_lastFrameEnv->setLabel(title); + } + + if(!m_showStructureLabels) { // if we don't want to have it displayed return here + return; + } + } + + // remember current type and line for the next call of addItem() + m_lastType = type; + m_lastLine = line; + + //find the parent for the new element + StructureViewItem *parentItem = (type == KileStruct::BeamerBeginBlock && m_lastFrameEnv) ? m_lastFrameEnv : parentFor(lev, fldr); + if(!parentItem) { + KMessageBox::error(m_stack->info()->mainWindow(), i18n("Cannot create a list view item: no parent found.")); + return; + } + + // create a new item + StructureViewItem *newChild = new StructureViewItem(parentItem, title, m_docinfo->url(), line, column, type, lev, startline, startcol); + if(!pix.isEmpty()) { + newChild->setIcon(0, QIcon::fromTheme(pix)); + } + //m_stop = true; + + //if the level is not greater than the defaultLevel + //open the parentItem to make this item visible + parentItem->setExpanded(shouldBeOpen(parentItem, fldr, lev)); + + //update the m_parent levels, such that section etc. get inserted at the correct level + //m_current = newChild; + if(lev > 0) { + m_parent[lev - 1] = newChild; + for(int l = lev; l < 7; ++l) { + m_parent[l] = newChild; + } + } + else if(lev == 0) { + m_lastSectioning = Q_NULLPTR; + for(int l = 0; l < 7; ++l) { + m_parent[l] = m_root; + } + } + + // check if we have to remember the new item for setting a label or caption + if(type == KileStruct::Sect) { + m_lastSectioning = newChild; + } + else if(type == KileStruct::BeginFloat) { + m_lastFloat = newChild; + } + else if(type == KileStruct::BeamerBeginFrame) { + m_lastFrameEnv = newChild; + } + else if(type == KileStruct::BeamerFrame) { + m_lastFrame = newChild; + } +} + +void StructureView::showReferences(KileInfo *ki) +{ + // remove old listview item for references, if it exists + if(m_folders.contains("refs")) { + StructureViewItem *refitem = m_folders["refs"]; + m_root->removeChild(refitem); + delete refitem; + + m_folders.remove("refs"); + } + + //KILE_DEBUG_MAIN << "==void StructureView::showReferences()========"; + //KILE_DEBUG_MAIN << "\tfound " << m_references.count() << " references"; + if(m_references.count() == 0) { + return; + } + + // read list with all labels + QStringList list = ki->allLabels(); + //KILE_DEBUG_MAIN << "\tfound " << list.count() << " labels"; + QMap labelmap; + for (QStringList::const_iterator itmap = list.constBegin(); itmap != list.constEnd(); ++itmap) { + labelmap[(*itmap)] = true; + } + + // now check if there are unsolved references + for (QList::const_iterator it = m_references.constBegin(); it!=m_references.constEnd(); ++it) { + if(!labelmap.contains((*it).name())) { + StructureViewItem *refitem = folder("refs"); + refitem->setExpanded(shouldBeOpen(refitem, "refs", 0)); + new StructureViewItem(refitem, (*it).name(), m_docinfo->url(), (*it).line(), (*it).column(), KileStruct::Reference, KileStruct::NotSpecified, 0, 0); + } + } +} + +////////////////////// StructureWidget: QWidgetStack ////////////////////// + +StructureWidget::StructureWidget(KileInfo *ki, QWidget * parent, const char* name) : + QStackedWidget(parent), + m_ki(ki), + m_docinfo(Q_NULLPTR), + m_showingContextMenu(Q_NULLPTR) +{ + setObjectName(name); + KILE_DEBUG_MAIN << "==KileWidget::StructureWidget::StructureWidget()==========="; + setLineWidth(0); + setMidLineWidth(0); + setContentsMargins(0, 0, 0, 0); + setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Ignored); + + m_default = new StructureView(this, Q_NULLPTR); + m_default->activate(); + + connect(m_ki->parserManager(), SIGNAL(documentParsingStarted()), this, SLOT(handleDocumentParsingStarted())); + connect(m_ki->parserManager(), SIGNAL(documentParsingComplete()), this, SLOT(handleDocumentParsingCompleted())); +} + +StructureWidget::~StructureWidget() +{ +} + +int StructureWidget::level() +{ + return KileConfig::defaultLevel(); +} + +void StructureWidget::addDocumentInfo(KileDocument::Info *docinfo) +{ + StructureView *view = new StructureView(this, docinfo); + addWidget(view); + m_map.insert(docinfo, view); +} + +void StructureWidget::slotClicked(QTreeWidgetItem * itm) +{ + KILE_DEBUG_MAIN << "\tStructureWidget::slotClicked"; + + StructureViewItem *item = dynamic_cast(itm); + //return if user didn't click on an item + if(!item) { + return; + } + + if(!(item->type() & KileStruct::None)) { + emit(setCursor(item->url(), item->line()-1, item->column())); + } + else if(!item->parent()) { //root item + emit(setCursor(item->url(), 0, 0)); + } +} + +void StructureWidget::slotDoubleClicked(QTreeWidgetItem * itm) +{ + KILE_DEBUG_MAIN << "\tStructureWidget::slotDoubleClicked"; + StructureViewItem *item = dynamic_cast(itm); + static QRegExp suffix("\\.[\\d\\w]*$"); + + if (!item) { + return; + } + + KILE_DEBUG_MAIN <<"item->url() is " << item->url() << ", item->title() is " << item->title(); + + if(item->type() & (KileStruct::Input | KileStruct::Bibliography | KileStruct::Graphics)) { + QString fname = item->title(); + + + if(fname.indexOf(suffix) != -1) { // check if we have a suffix, if not add standard suffixes + KILE_DEBUG_MAIN << "Suffix found: " << suffix.cap(0); + } + else { + // filename in structureview entry has no extension: this shouldn't happen anymore, + // because all have got one in function updateStruct(). But who knows? + if(item->type() == KileStruct::Input) { + fname += m_ki->extensions()->latexDocumentDefault(); + } + else if(item->type() == KileStruct::Bibliography) { + fname += m_ki->extensions()->bibtexDefault(); + } + else if(item->type() == KileStruct::Graphics) { + + KileProjectItem *kiItem = m_ki->docManager()->itemFor(item->url()); + KileProject *proj; + QString extToAdd; + bool fromProject = true; + + if(kiItem && (proj = kiItem->project())) { + extToAdd = proj->defaultGraphicExt(); + } + if(extToAdd.isEmpty()) { + extToAdd = KileConfig::svDefaultGraphicExt(); + fromProject = false; + } + + m_ki->errorHandler()->printMessage(KileTool::Info, + (fromProject ? + i18n("No extension specified for graphic file. Using .%1 from Project settings.", extToAdd) : + i18n("No extension specified for graphic file. Using .%1 from global Structure View settings.", extToAdd)), + i18n("File extension not specified")); + + fname += '.' + extToAdd; + + } + else { + KILE_DEBUG_MAIN << "Suffixless item with unknown type found"; + } + + } + + if(QDir::isRelativePath(fname)) { // no absolute path + QString fn = m_ki->getCompileName(); + fname= QFileInfo(fn).path() + QDir::separator() + fname; + } + + QFileInfo fi(fname); + + if(fi.isReadable()) { + QUrl url = QUrl::fromLocalFile(fname); + if(item->type() == KileStruct::Graphics) { + QMimeDatabase db; + QMimeType pMime = db.mimeTypeForUrl(url); + KRun::runUrl(url, pMime.name(), this, KRun::RunFlags()); + } + else { + emit(fileOpen(url, QString())); + } + } + else { + QString otherFilename; + + if(item->type() == KileStruct::Bibliography) { + otherFilename = m_ki->checkOtherPaths(fi.path(), fi.fileName(), KileInfo::bibinputs); + } + else if(item->type() == KileStruct::Input) { + otherFilename = m_ki->checkOtherPaths(fi.path(), fi.fileName(), KileInfo::texinputs); + } + + fi.setFile(otherFilename); + + if(fi.isReadable()) { + emit(fileOpen(QUrl::fromLocalFile(otherFilename), QString())); + } + else { + if(KMessageBox::warningYesNo(this, i18n("Cannot find the included file. The file does not exist, is not readable or Kile is unable to determine the correct path to it. The filename causing this error was: %1.\nDo you want to create this file?", fname), i18n("Cannot Find File")) + == KMessageBox::Yes) { + emit(fileNew(QUrl::fromLocalFile(fname))); + } + } + } + } +} // all popup items get different id's, so that we can see, what item is activated - // - label: 1 - 6 - // - sectioning: 10 - 16 - // - graphics: 100ff - void StructureWidget::viewContextMenuEvent(StructureView *view, QContextMenuEvent *event) - { - KILE_DEBUG_MAIN << "\tcalled"; - - QSignalMapper signalMapper; - connect(&signalMapper, SIGNAL(mapped(int)), this, SLOT(slotPopupActivated(int))); - QMenu popup; - QAction *action = Q_NULLPTR; - m_showingContextMenu = Q_NULLPTR; - - m_popupItem = dynamic_cast(view->itemAt(event->pos())); - if(!m_popupItem) { - KILE_DEBUG_MAIN << "not a pointer to a StructureViewItem object."; - return; - } - - bool hasLabel = !(m_popupItem->label().isEmpty()); - - if(m_popupItem->type() == KileStruct::Sect) { - if(hasLabel) { - popup.addSection(i18n("Sectioning")); - } - action = popup.addAction(i18n("Cu&t"), &signalMapper, SLOT(map())); - signalMapper.setMapping(action, SectioningCut); - action = popup.addAction(i18n("&Copy"), &signalMapper, SLOT(map())); - signalMapper.setMapping(action, SectioningCopy); - action = popup.addAction(i18n("&Paste below"), &signalMapper, SLOT(map())); - signalMapper.setMapping(action, SectioningPaste); - popup.addSeparator(); - action = popup.addAction(i18n("&Select"), &signalMapper, SLOT(map())); - signalMapper.setMapping(action, SectioningSelect); - action = popup.addAction(i18n("&Delete"), &signalMapper, SLOT(map())); - signalMapper.setMapping(action, SectioningDelete); - popup.addSeparator(); - action = popup.addAction(i18n("C&omment"), &signalMapper, SLOT(map())); - signalMapper.setMapping(action, SectioningComment); - popup.addSeparator(); - action = popup.addAction(i18n("Run QuickPreview"), &signalMapper, SLOT(map())); - signalMapper.setMapping(action, SectioningPreview); - } - else if(m_popupItem->type() == KileStruct::Graphics) { - m_popupInfo = m_popupItem->title(); - - if(!QDir::isAbsolutePath(m_popupInfo)) { - QString fn = m_ki->getCompileName(); - m_popupInfo = QFileInfo(fn).path() + '/' + m_popupInfo; - } - - QFileInfo fi(m_popupInfo); - if(fi.isReadable()) { - QUrl url; - url.setPath(m_popupInfo); - - QMimeDatabase db; - m_offerList = KMimeTypeTrader::self()->query(db.mimeTypeForUrl(url).name(), "Application"); - for(int i = 0; i < m_offerList.count(); ++i) { - action = popup.addAction(QIcon::fromTheme(m_offerList[i]->icon()), m_offerList[i]->name(), - &signalMapper, SLOT(map())); - signalMapper.setMapping(action, i + SectioningGraphicsOfferlist); - } - popup.addSeparator(); - action = popup.addAction(i18n("Other..."), &signalMapper, SLOT(map())); - signalMapper.setMapping(action, SectioningGraphicsOther); - } - } - - if(hasLabel) { - popup.addSection(i18n("Insert Label")); - action = popup.addAction(i18n("As &reference"), &signalMapper, SLOT(map())); - signalMapper.setMapping(action, 1); - action = popup.addAction(i18n("As &page reference"), &signalMapper, SLOT(map())); - signalMapper.setMapping(action, 2); - action = popup.addAction(i18n("Only the &label"), &signalMapper, SLOT(map())); - signalMapper.setMapping(action, 3); - popup.addSeparator(); - popup.addSection(i18n("Copy Label to Clipboard")); - action = popup.addAction(i18n("As reference"), &signalMapper, SLOT(map())); - signalMapper.setMapping(action, 4); - action = popup.addAction(i18n("As page reference"), &signalMapper, SLOT(map())); - signalMapper.setMapping(action, 5); - action = popup.addAction(i18n("Only the label"), &signalMapper, SLOT(map())); - signalMapper.setMapping(action, 6); - } - - if(!popup.isEmpty()) { - m_showingContextMenu = &popup; - popup.exec(event->globalPos()); - m_showingContextMenu = Q_NULLPTR; - } - } - - void StructureWidget::slotPopupActivated(int id) - { - KILE_DEBUG_MAIN << "id: " << id; - if(id >= 1 && id <= 6) { - slotPopupLabel(id); - } - else if(id >= SectioningCut && id <= SectioningPreview) { - slotPopupSectioning(id); - } - else if(id >= SectioningGraphicsOther && id <= SectioningGraphicsOfferlist + m_offerList.count()) { - slotPopupGraphics(id); - } - } - - // id's 1..6 (already checked) - void StructureWidget::slotPopupLabel(int id) - { - KILE_DEBUG_MAIN << "\tStructureWidget::slotPopupLabel (" << id << ")"<< endl; - - QString s = m_popupItem->label(); - if(id == 1 || id == 4) { - s = "\\ref{" + s + '}'; - } - else if(id == 2 || id == 5) { - s = "\\pageref{" + s + '}'; - } - - if(id <= 3) { - emit(sendText(s)); - } - else { - QApplication::clipboard()->setText(s); - } - } - - // id's 10..16 (already checked) - void StructureWidget::slotPopupSectioning(int id) - { - KILE_DEBUG_MAIN << "\tStructureWidget::slotPopupSectioning (" << id << ")"<< endl; - if(m_popupItem->level() >= 1 && m_popupItem->level() <= 7) { - emit(sectioningPopup(m_popupItem, id)); - } - } - - // id's 100ff (already checked) - void StructureWidget::slotPopupGraphics(int id) - { - KILE_DEBUG_MAIN << "\tStructureWidget::slotPopupGraphics (" << id << ")"<< endl; - - QUrl url; - url.setPath(m_popupInfo); - - if(id == SectioningGraphicsOther) { - KRun::displayOpenWithDialog(QList() << url, this); - } - else { - KRun::runService(*m_offerList[id-SectioningGraphicsOfferlist], QList() << url, this); - } - } - - StructureView* StructureWidget::viewFor(KileDocument::Info *info) - { - if(!info) { - return Q_NULLPTR; - } - - if(!viewExistsFor(info)) { - m_map.insert(info, new StructureView(this, info)); - } - - return m_map[info]; - } - - bool StructureWidget::viewExistsFor(KileDocument::Info *info) - { - if(!info) { - return false; - } - else { - return m_map.contains(info); - } - } - - void StructureWidget::closeDocumentInfo(KileDocument::Info *docinfo) - { - m_docinfo = Q_NULLPTR; - if(m_map.contains(docinfo)) { - StructureView *data = m_map[docinfo]; - m_map.remove(docinfo); - delete data; - } - - if(m_map.isEmpty()) { - m_default->activate(); - } - } - - void StructureWidget::clear() - { - QMap::iterator it; - QMap::iterator itend(m_map.end()); - for (it = m_map.begin(); it != itend; ++it) { - if(it.value()) { - delete it.value(); - } - } - - m_map.clear(); - m_docinfo = Q_NULLPTR; - - m_default->activate(); - } - - void StructureWidget::updateUrl(KileDocument::Info *docinfo) - { - StructureView *view = viewFor(docinfo); - if(view) { - view->updateRoot(); - } - } - - void StructureWidget::update(KileDocument::Info *docinfo) - { - update(docinfo, false); - } - - void StructureWidget::update(KileDocument::Info *docinfo, bool forceParsing) - { - KILE_DEBUG_MAIN << "==KileWidget::StructureWidget::update(" << docinfo << ")============="; - - if(!docinfo) { - m_default->activate(); - return; - } - - m_docinfo = docinfo; - bool needParsing = forceParsing || m_docinfo->isDirty() || !viewExistsFor(docinfo); - - //find structview-item for this docinfo - StructureView *view = viewFor(m_docinfo); - if(!view) { - m_default->activate(); - return; - } - - if(needParsing) { //need to reparse the doc - m_docinfo->updateStruct(); - } - - KILE_DEBUG_MAIN << "activating view"; - view->activate(); - } - - void StructureWidget::updateAfterParsing(KileDocument::Info *info, const QLinkedList& items) - { - KILE_DEBUG_MAIN; - StructureView *view = viewFor(info); - if(!view) { - m_default->activate(); - return; - } - - int xtop = view->horizontalScrollBar()->value(); - int ytop = view->verticalScrollBar()->value(); - // avoid flickering when parsing - view->setUpdatesEnabled(false); - view->cleanUp(); - Q_FOREACH( KileParser::StructureViewItem *item, items) { - view->addItem(item->title, item->line, item->column, item->type, item->level, item->startline, item->startcol, item->pix, item->folder); - } - view->setUpdatesEnabled(true); - view->showReferences(m_ki); - view->horizontalScrollBar()->setValue(xtop); - view->verticalScrollBar()->setValue(ytop); - } - - void StructureWidget::clean(KileDocument::Info *docinfo) - { - KILE_DEBUG_MAIN << "==void StructureWidget::clean()========"; - StructureView *view = viewFor(docinfo); - if(view) { - view->cleanUp(); - } - } - - void StructureWidget::updateReferences(KileDocument::Info *docinfo) - { - KILE_DEBUG_MAIN << "==void StructureView::updateReferences()========"; - StructureView *view = viewFor(docinfo); - if(view) { - view->showReferences(m_ki); - } - } - - ////////////////////// StructureWidget: find sectioning ////////////////////// - - bool StructureWidget::findSectioning(StructureViewItem *refItem, KTextEditor::Document *doc, int row, int col, bool backwards, bool checkLevel, int §Row, int §Col) - { - KileDocument::TextInfo *docinfo = m_ki->docManager()->textInfoFor(doc); - if(!docinfo) { - return false; - } - - if( checkLevel && !refItem ){ // only allow a refItem == Q_NULLPTR if checkLevel is false - return false; - } - - bool found = false; - int foundRow, foundCol; - StructureView *structurelist = viewFor(docinfo); - QTreeWidgetItemIterator it(structurelist); - while(*it) { - StructureViewItem *item = dynamic_cast(*it); - if (item && item->type() == KileStruct::Sect && (!checkLevel || item->level() <= refItem->level())){ - foundRow = item->startline() - 1; - foundCol = item->startcol() - 1; - if(backwards) { - if(foundRow < row || (foundRow==row && foundCol < col)) { - sectRow = foundRow; - sectCol = foundCol; - found = true; - } - else { - return found; - } - - } - else if(!backwards && (foundRow > row || (foundRow == row && foundCol > col))) { - sectRow = foundRow; - sectCol = foundCol; - return true; - } - } - ++it; - } - - return found; - } - - void StructureWidget::handleDocumentParsingStarted() - { - setEnabled(false); - // if a context menu is showing, we better close it - // as the StructureViewItems it operates on will be deleted - if(m_showingContextMenu) { - m_showingContextMenu->close(); - } - } - - void StructureWidget::handleDocumentParsingCompleted() - { - setEnabled(true); - } +// - label: 1 - 6 +// - sectioning: 10 - 16 +// - graphics: 100ff +void StructureWidget::viewContextMenuEvent(StructureView *view, QContextMenuEvent *event) +{ + KILE_DEBUG_MAIN << "\tcalled"; + + QSignalMapper signalMapper; + connect(&signalMapper, SIGNAL(mapped(int)), this, SLOT(slotPopupActivated(int))); + QMenu popup; + QAction *action = Q_NULLPTR; + m_showingContextMenu = Q_NULLPTR; + + m_popupItem = dynamic_cast(view->itemAt(event->pos())); + if(!m_popupItem) { + KILE_DEBUG_MAIN << "not a pointer to a StructureViewItem object."; + return; + } + + bool hasLabel = !(m_popupItem->label().isEmpty()); + + if(m_popupItem->type() == KileStruct::Sect) { + if(hasLabel) { + popup.addSection(i18n("Sectioning")); + } + action = popup.addAction(i18n("Cu&t"), &signalMapper, SLOT(map())); + signalMapper.setMapping(action, SectioningCut); + action = popup.addAction(i18n("&Copy"), &signalMapper, SLOT(map())); + signalMapper.setMapping(action, SectioningCopy); + action = popup.addAction(i18n("&Paste below"), &signalMapper, SLOT(map())); + signalMapper.setMapping(action, SectioningPaste); + popup.addSeparator(); + action = popup.addAction(i18n("&Select"), &signalMapper, SLOT(map())); + signalMapper.setMapping(action, SectioningSelect); + action = popup.addAction(i18n("&Delete"), &signalMapper, SLOT(map())); + signalMapper.setMapping(action, SectioningDelete); + popup.addSeparator(); + action = popup.addAction(i18n("C&omment"), &signalMapper, SLOT(map())); + signalMapper.setMapping(action, SectioningComment); + popup.addSeparator(); + action = popup.addAction(i18n("Run QuickPreview"), &signalMapper, SLOT(map())); + signalMapper.setMapping(action, SectioningPreview); + } + else if(m_popupItem->type() == KileStruct::Graphics) { + m_popupInfo = m_popupItem->title(); + + if(!QDir::isAbsolutePath(m_popupInfo)) { + QString fn = m_ki->getCompileName(); + m_popupInfo = QFileInfo(fn).path() + '/' + m_popupInfo; + } + + QFileInfo fi(m_popupInfo); + if(fi.isReadable()) { + QUrl url; + url.setPath(m_popupInfo); + + QMimeDatabase db; + m_offerList = KMimeTypeTrader::self()->query(db.mimeTypeForUrl(url).name(), "Application"); + for(int i = 0; i < m_offerList.count(); ++i) { + action = popup.addAction(QIcon::fromTheme(m_offerList[i]->icon()), m_offerList[i]->name(), + &signalMapper, SLOT(map())); + signalMapper.setMapping(action, i + SectioningGraphicsOfferlist); + } + popup.addSeparator(); + action = popup.addAction(i18n("Other..."), &signalMapper, SLOT(map())); + signalMapper.setMapping(action, SectioningGraphicsOther); + } + } + + if(hasLabel) { + popup.addSection(i18n("Insert Label")); + action = popup.addAction(i18n("As &reference"), &signalMapper, SLOT(map())); + signalMapper.setMapping(action, 1); + action = popup.addAction(i18n("As &page reference"), &signalMapper, SLOT(map())); + signalMapper.setMapping(action, 2); + action = popup.addAction(i18n("Only the &label"), &signalMapper, SLOT(map())); + signalMapper.setMapping(action, 3); + popup.addSeparator(); + popup.addSection(i18n("Copy Label to Clipboard")); + action = popup.addAction(i18n("As reference"), &signalMapper, SLOT(map())); + signalMapper.setMapping(action, 4); + action = popup.addAction(i18n("As page reference"), &signalMapper, SLOT(map())); + signalMapper.setMapping(action, 5); + action = popup.addAction(i18n("Only the label"), &signalMapper, SLOT(map())); + signalMapper.setMapping(action, 6); + } + + if(!popup.isEmpty()) { + m_showingContextMenu = &popup; + popup.exec(event->globalPos()); + m_showingContextMenu = Q_NULLPTR; + } +} + +void StructureWidget::slotPopupActivated(int id) +{ + KILE_DEBUG_MAIN << "id: " << id; + if(id >= 1 && id <= 6) { + slotPopupLabel(id); + } + else if(id >= SectioningCut && id <= SectioningPreview) { + slotPopupSectioning(id); + } + else if(id >= SectioningGraphicsOther && id <= SectioningGraphicsOfferlist + m_offerList.count()) { + slotPopupGraphics(id); + } +} + +// id's 1..6 (already checked) +void StructureWidget::slotPopupLabel(int id) +{ + KILE_DEBUG_MAIN << "\tStructureWidget::slotPopupLabel (" << id << ")"<< endl; + + QString s = m_popupItem->label(); + if(id == 1 || id == 4) { + s = "\\ref{" + s + '}'; + } + else if(id == 2 || id == 5) { + s = "\\pageref{" + s + '}'; + } + + if(id <= 3) { + emit(sendText(s)); + } + else { + QApplication::clipboard()->setText(s); + } +} + +// id's 10..16 (already checked) +void StructureWidget::slotPopupSectioning(int id) +{ + KILE_DEBUG_MAIN << "\tStructureWidget::slotPopupSectioning (" << id << ")"<< endl; + if(m_popupItem->level() >= 1 && m_popupItem->level() <= 7) { + emit(sectioningPopup(m_popupItem, id)); + } +} + +// id's 100ff (already checked) +void StructureWidget::slotPopupGraphics(int id) +{ + KILE_DEBUG_MAIN << "\tStructureWidget::slotPopupGraphics (" << id << ")"<< endl; + + QUrl url; + url.setPath(m_popupInfo); + + if(id == SectioningGraphicsOther) { + KRun::displayOpenWithDialog(QList() << url, this); + } + else { + KRun::runService(*m_offerList[id-SectioningGraphicsOfferlist], QList() << url, this); + } +} + +StructureView* StructureWidget::viewFor(KileDocument::Info *info) +{ + if(!info) { + return Q_NULLPTR; + } + + if(!viewExistsFor(info)) { + m_map.insert(info, new StructureView(this, info)); + } + + return m_map[info]; +} + +bool StructureWidget::viewExistsFor(KileDocument::Info *info) +{ + if(!info) { + return false; + } + else { + return m_map.contains(info); + } +} + +void StructureWidget::closeDocumentInfo(KileDocument::Info *docinfo) +{ + m_docinfo = Q_NULLPTR; + if(m_map.contains(docinfo)) { + StructureView *data = m_map[docinfo]; + m_map.remove(docinfo); + delete data; + } + + if(m_map.isEmpty()) { + m_default->activate(); + } +} + +void StructureWidget::clear() +{ + QMap::iterator it; + QMap::iterator itend(m_map.end()); + for (it = m_map.begin(); it != itend; ++it) { + if(it.value()) { + delete it.value(); + } + } + + m_map.clear(); + m_docinfo = Q_NULLPTR; + + m_default->activate(); +} + +void StructureWidget::updateUrl(KileDocument::Info *docinfo) +{ + StructureView *view = viewFor(docinfo); + if(view) { + view->updateRoot(); + } +} + +void StructureWidget::update(KileDocument::Info *docinfo) +{ + update(docinfo, false); +} + +void StructureWidget::update(KileDocument::Info *docinfo, bool forceParsing) +{ + KILE_DEBUG_MAIN << "==KileWidget::StructureWidget::update(" << docinfo << ")============="; + + if(!docinfo) { + m_default->activate(); + return; + } + + m_docinfo = docinfo; + bool needParsing = forceParsing || m_docinfo->isDirty() || !viewExistsFor(docinfo); + + //find structview-item for this docinfo + StructureView *view = viewFor(m_docinfo); + if(!view) { + m_default->activate(); + return; + } + + if(needParsing) { //need to reparse the doc + m_docinfo->updateStruct(); + } + + KILE_DEBUG_MAIN << "activating view"; + view->activate(); +} + +void StructureWidget::updateAfterParsing(KileDocument::Info *info, const QLinkedList& items) +{ + KILE_DEBUG_MAIN; + StructureView *view = viewFor(info); + if(!view) { + m_default->activate(); + return; + } + + int xtop = view->horizontalScrollBar()->value(); + int ytop = view->verticalScrollBar()->value(); + // avoid flickering when parsing + view->setUpdatesEnabled(false); + view->cleanUp(); + Q_FOREACH( KileParser::StructureViewItem *item, items) { + view->addItem(item->title, item->line, item->column, item->type, item->level, item->startline, item->startcol, item->pix, item->folder); + } + view->setUpdatesEnabled(true); + view->showReferences(m_ki); + view->horizontalScrollBar()->setValue(xtop); + view->verticalScrollBar()->setValue(ytop); +} + +void StructureWidget::clean(KileDocument::Info *docinfo) +{ + KILE_DEBUG_MAIN << "==void StructureWidget::clean()========"; + StructureView *view = viewFor(docinfo); + if(view) { + view->cleanUp(); + } +} + +void StructureWidget::updateReferences(KileDocument::Info *docinfo) +{ + KILE_DEBUG_MAIN << "==void StructureView::updateReferences()========"; + StructureView *view = viewFor(docinfo); + if(view) { + view->showReferences(m_ki); + } +} + +////////////////////// StructureWidget: find sectioning ////////////////////// + +bool StructureWidget::findSectioning(StructureViewItem *refItem, KTextEditor::Document *doc, int row, int col, bool backwards, bool checkLevel, int §Row, int §Col) +{ + KileDocument::TextInfo *docinfo = m_ki->docManager()->textInfoFor(doc); + if(!docinfo) { + return false; + } + + if( checkLevel && !refItem ) { // only allow a refItem == Q_NULLPTR if checkLevel is false + return false; + } + + bool found = false; + int foundRow, foundCol; + StructureView *structurelist = viewFor(docinfo); + QTreeWidgetItemIterator it(structurelist); + while(*it) { + StructureViewItem *item = dynamic_cast(*it); + if (item && item->type() == KileStruct::Sect && (!checkLevel || item->level() <= refItem->level())) { + foundRow = item->startline() - 1; + foundCol = item->startcol() - 1; + if(backwards) { + if(foundRow < row || (foundRow==row && foundCol < col)) { + sectRow = foundRow; + sectCol = foundCol; + found = true; + } + else { + return found; + } + + } + else if(!backwards && (foundRow > row || (foundRow == row && foundCol > col))) { + sectRow = foundRow; + sectCol = foundCol; + return true; + } + } + ++it; + } + + return found; +} + +void StructureWidget::handleDocumentParsingStarted() +{ + setEnabled(false); + // if a context menu is showing, we better close it + // as the StructureViewItems it operates on will be deleted + if(m_showingContextMenu) { + m_showingContextMenu->close(); + } +} + +void StructureWidget::handleDocumentParsingCompleted() +{ + setEnabled(true); +} } diff --git a/src/widgets/structurewidget.h b/src/widgets/structurewidget.h index ed5401ec..923bb9e5 100644 --- a/src/widgets/structurewidget.h +++ b/src/widgets/structurewidget.h @@ -1,239 +1,269 @@ /************************************************************************************************** begin : Sun Dec 28 2003 copyright : (C) 2003 by Jeroen Wijnhout (Jeroen.Wijnhout@kdemail.net) 2005-2007 by Holger Danielsson (holger.danielsson@versanet.de) 2008-2012 by Michel Ludwig (michel.ludwig@kdemail.net) **************************************************************************************************/ /*************************************************************************** * * * 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. * * * ***************************************************************************/ #ifndef STRUCTUREWIDGET_H #define STRUCTUREWIDGET_H #include #include #include #include #include #include #include #include "documentinfo.h" #include "parser/latexparser.h" //2007-02-15: dani // - class StructureViewItem not only saves the cursor position of the parameter, // but also the real cursor position of the command class KileInfo; /** * ListView items that can hold some additional information appropriate for the Structure View. The * additional information is: line number, title string. **/ namespace KileWidget { class StructureViewItem : public QTreeWidgetItem { public: - StructureViewItem(QTreeWidgetItem *parent, const QString &title, const QUrl &url, uint line, uint m_column, int type, int level, uint startline, uint startcol); - StructureViewItem(QTreeWidget *parent, const QString &label); - explicit StructureViewItem(const QString &label, QTreeWidgetItem *parent = Q_NULLPTR); - - /** @returns the title of this element (for a label it return the label), without the (line ...) part **/ - const QString& title() const { return m_title; } - /** @returns the line number of the structure element. **/ - uint line() const { return m_line; } - /** @returns the column number of the structure element, right after the { **/ - uint column() const { return m_column; } - /** @returns the type of element, see @ref KileStruct **/ - int type() const { return m_type; } - uint startline() const { return m_startline; } - uint startcol() const { return m_startcol; } - /**@returns the file in which this item was found*/ - const QUrl &url() const { return m_url; } - void setURL(const QUrl &url) { m_url = url; } - - int level() const { return m_level; } - const QString &label() const { return m_label; } - - void setTitle(const QString &title); - void setLabel(const QString &label); + StructureViewItem(QTreeWidgetItem *parent, const QString &title, const QUrl &url, uint line, uint m_column, int type, int level, uint startline, uint startcol); + StructureViewItem(QTreeWidget *parent, const QString &label); + explicit StructureViewItem(const QString &label, QTreeWidgetItem *parent = Q_NULLPTR); + + /** @returns the title of this element (for a label it return the label), without the (line ...) part **/ + const QString& title() const { + return m_title; + } + /** @returns the line number of the structure element. **/ + uint line() const { + return m_line; + } + /** @returns the column number of the structure element, right after the { **/ + uint column() const { + return m_column; + } + /** @returns the type of element, see @ref KileStruct **/ + int type() const { + return m_type; + } + uint startline() const { + return m_startline; + } + uint startcol() const { + return m_startcol; + } + /**@returns the file in which this item was found*/ + const QUrl &url() const { + return m_url; + } + void setURL(const QUrl &url) { + m_url = url; + } + + int level() const { + return m_level; + } + const QString &label() const { + return m_label; + } + + void setTitle(const QString &title); + void setLabel(const QString &label); private: - QString m_title; - QUrl m_url; - uint m_line; - uint m_column; - int m_type, m_level; - uint m_startline; - uint m_startcol; - QString m_label; - - void setItemEntry(); + QString m_title; + QUrl m_url; + uint m_line; + uint m_column; + int m_type, m_level; + uint m_startline; + uint m_startcol; + QString m_label; + + void setItemEntry(); }; class KileReferenceData { public: - KileReferenceData() {} - KileReferenceData(const QString &name, uint line, uint column) : m_name(name), m_line(line), m_column(column) {} - ~KileReferenceData() {} - - const QString &name() const { return m_name; } - uint line() const { return m_line; } - uint column() const { return m_column; } - + KileReferenceData() {} + KileReferenceData(const QString &name, uint line, uint column) : m_name(name), m_line(line), m_column(column) {} + ~KileReferenceData() {} + + const QString &name() const { + return m_name; + } + uint line() const { + return m_line; + } + uint column() const { + return m_column; + } + +private: + QString m_name; + uint m_line; + uint m_column; +}; + +class StructureWidget; //forward declaration + +class StructureView : public QTreeWidget +{ + Q_OBJECT + +public: + StructureView(StructureWidget *stack, KileDocument::Info *docinfo); + ~StructureView(); + + void activate(); + void cleanUp(bool preserveState = true); + void showReferences(KileInfo *ki); + + QUrl url() const { + return m_docinfo->url(); + } + void updateRoot(); + +public Q_SLOTS: + void addItem(const QString &title, uint line, uint column, int type, int level, uint startline, uint startcol, + const QString &pix, const QString &folder = "root"); + void slotConfigChanged(); + +protected: + virtual void contextMenuEvent(QContextMenuEvent *event); + +private: + StructureViewItem* parentFor(int lev, const QString &fldr); + + void init(); + StructureViewItem* createFolder(const QString &folder); + StructureViewItem* folder(const QString &folder); + + void saveState(); + bool shouldBeOpen(StructureViewItem *item, const QString &folder, int level); + private: - QString m_name; - uint m_line; - uint m_column; + StructureWidget *m_stack; + KileDocument::Info *m_docinfo; + QMap m_folders; + QMap m_openByTitle; + QMap m_openByLine; + QMap m_openByFolders; + StructureViewItem *m_parent[7], *m_root; + QList m_references; + bool m_openStructureLabels; + bool m_openStructureReferences; + bool m_openStructureBibitems; + bool m_openStructureTodo; + bool m_showStructureLabels; + + int m_lastType; + uint m_lastLine; + StructureViewItem *m_lastSectioning; + StructureViewItem *m_lastFloat; + StructureViewItem *m_lastFrame; + StructureViewItem *m_lastFrameEnv; + + bool m_stop; }; - class StructureWidget; //forward declaration - - class StructureView : public QTreeWidget - { - Q_OBJECT - - public: - StructureView(StructureWidget *stack, KileDocument::Info *docinfo); - ~StructureView(); - - void activate(); - void cleanUp(bool preserveState = true); - void showReferences(KileInfo *ki); - - QUrl url() const { return m_docinfo->url(); } - void updateRoot(); - - public Q_SLOTS: - void addItem(const QString &title, uint line, uint column, int type, int level, uint startline, uint startcol, - const QString &pix, const QString &folder = "root"); - void slotConfigChanged(); - - protected: - virtual void contextMenuEvent(QContextMenuEvent *event); - - private: - StructureViewItem* parentFor(int lev, const QString &fldr); - - void init(); - StructureViewItem* createFolder(const QString &folder); - StructureViewItem* folder(const QString &folder); - - void saveState(); - bool shouldBeOpen(StructureViewItem *item, const QString &folder, int level); - - private: - StructureWidget *m_stack; - KileDocument::Info *m_docinfo; - QMap m_folders; - QMap m_openByTitle; - QMap m_openByLine; - QMap m_openByFolders; - StructureViewItem *m_parent[7], *m_root; - QList m_references; - bool m_openStructureLabels; - bool m_openStructureReferences; - bool m_openStructureBibitems; - bool m_openStructureTodo; - bool m_showStructureLabels; - - int m_lastType; - uint m_lastLine; - StructureViewItem *m_lastSectioning; - StructureViewItem *m_lastFloat; - StructureViewItem *m_lastFrame; - StructureViewItem *m_lastFrameEnv; - - bool m_stop; - }; - - class StructureWidget : public QStackedWidget - { - friend class StructureView; - - Q_OBJECT - - public: - StructureWidget(KileInfo*, QWidget *parent, const char *name = Q_NULLPTR); - ~StructureWidget(); - - int level(); - KileInfo *info() { return m_ki; } - - bool findSectioning(StructureViewItem *item, KTextEditor::Document *doc, int row, - int col, bool backwards, bool checkLevel, int §Row, int §Col); - void updateUrl(KileDocument::Info *docinfo); - - void updateAfterParsing(KileDocument::Info *info, const QLinkedList& items); - - enum { SectioningCut = 10, SectioningCopy = 11, SectioningPaste = 12, - SectioningSelect = 13, SectioningDelete = 14, - SectioningComment = 15, - SectioningPreview = 16, - SectioningGraphicsOther = 100, SectioningGraphicsOfferlist = 101 - }; - - public Q_SLOTS: - void slotClicked(QTreeWidgetItem *); - void slotDoubleClicked(QTreeWidgetItem *); - void slotPopupActivated(int id); - - void addDocumentInfo(KileDocument::Info *); - void closeDocumentInfo(KileDocument::Info *); - void update(KileDocument::Info *); - void update(KileDocument::Info *, bool); - void clean(KileDocument::Info *); - void updateReferences(KileDocument::Info *); - - /** - * Clears the structure widget and empties the map between KileDocument::Info objects and their structure trees (QListViewItem). - **/ - void clear(); - - Q_SIGNALS: - void sendText(const QString&); - void setCursor(const QUrl&, int, int); - void fileOpen(const QUrl&, const QString&); - void fileNew(const QUrl&); - void configChanged(); - void sectioningPopup(KileWidget::StructureViewItem *item, int id); - - protected: - void viewContextMenuEvent(StructureView *view, QContextMenuEvent *event); - - private: - KileInfo *m_ki; - KileDocument::Info *m_docinfo; - QMap m_map; - StructureView *m_default; - StructureViewItem *m_popupItem; - QMenu *m_showingContextMenu; - QString m_popupInfo; - KService::List m_offerList; - - StructureView* viewFor(KileDocument::Info *info); - bool viewExistsFor(KileDocument::Info *info); - - void slotPopupLabel(int id); - void slotPopupSectioning(int id); - void slotPopupGraphics(int id); - - private Q_SLOTS: - void handleDocumentParsingStarted(); - void handleDocumentParsingCompleted(); - }; +class StructureWidget : public QStackedWidget +{ + friend class StructureView; + + Q_OBJECT + +public: + StructureWidget(KileInfo*, QWidget *parent, const char *name = Q_NULLPTR); + ~StructureWidget(); + + int level(); + KileInfo *info() { + return m_ki; + } + + bool findSectioning(StructureViewItem *item, KTextEditor::Document *doc, int row, + int col, bool backwards, bool checkLevel, int §Row, int §Col); + void updateUrl(KileDocument::Info *docinfo); + + void updateAfterParsing(KileDocument::Info *info, const QLinkedList& items); + + enum { SectioningCut = 10, SectioningCopy = 11, SectioningPaste = 12, + SectioningSelect = 13, SectioningDelete = 14, + SectioningComment = 15, + SectioningPreview = 16, + SectioningGraphicsOther = 100, SectioningGraphicsOfferlist = 101 + }; + +public Q_SLOTS: + void slotClicked(QTreeWidgetItem *); + void slotDoubleClicked(QTreeWidgetItem *); + void slotPopupActivated(int id); + + void addDocumentInfo(KileDocument::Info *); + void closeDocumentInfo(KileDocument::Info *); + void update(KileDocument::Info *); + void update(KileDocument::Info *, bool); + void clean(KileDocument::Info *); + void updateReferences(KileDocument::Info *); + + /** + * Clears the structure widget and empties the map between KileDocument::Info objects and their structure trees (QListViewItem). + **/ + void clear(); + +Q_SIGNALS: + void sendText(const QString&); + void setCursor(const QUrl&, int, int); + void fileOpen(const QUrl&, const QString&); + void fileNew(const QUrl&); + void configChanged(); + void sectioningPopup(KileWidget::StructureViewItem *item, int id); + +protected: + void viewContextMenuEvent(StructureView *view, QContextMenuEvent *event); + +private: + KileInfo *m_ki; + KileDocument::Info *m_docinfo; + QMap m_map; + StructureView *m_default; + StructureViewItem *m_popupItem; + QMenu *m_showingContextMenu; + QString m_popupInfo; + KService::List m_offerList; + + StructureView* viewFor(KileDocument::Info *info); + bool viewExistsFor(KileDocument::Info *info); + + void slotPopupLabel(int id); + void slotPopupSectioning(int id); + void slotPopupGraphics(int id); + +private Q_SLOTS: + void handleDocumentParsingStarted(); + void handleDocumentParsingCompleted(); +}; } #endif diff --git a/src/widgets/symbolview.cpp b/src/widgets/symbolview.cpp index fbc2ecff..ad7c07d8 100644 --- a/src/widgets/symbolview.cpp +++ b/src/widgets/symbolview.cpp @@ -1,475 +1,475 @@ /**************************************************************************************** begin : Fri Aug 1 2003 copyright : (C) 2003 by Jeroen Wijnhout (Jeroen.Wijnhout@kdemail.net) 2006 - 2009 by Thomas Braun 2012 by Michel Ludwig (michel.ludwig@kdemail.net) ****************************************************************************************/ /*************************************************************************** * * * 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. * * * ***************************************************************************/ /* dani 2005-11-22 - add some new symbols - rearranged source tbraun 2006-07-01 - added tooltips which show the keys, copied from kfileiconview - reorganized the hole thing, more flexible png loading, removing the old big code_array, more groups tbraun 2007-06-04 - Send a warning in the logwidget if needed packages are not included for the command tbraun 2007-06-13 - Added Most frequently used symbolview, including remembering icons upon restart, removing of least popular item and configurable max item count */ #include "symbolview.h" #include #include #include #include #include #include #include #include #include #include #include #include "kileconfig.h" #include "kiledebug.h" #include "kileinfo.h" #include "../symbolviewclasses.h" #define MFUS_GROUP "MostFrequentlyUsedSymbols" #define MFUS_PREFIX "MFUS" namespace KileWidget { SymbolView::SymbolView(KileInfo *kileInfo, QWidget *parent, int type, const char *name) - : QListWidget(parent), m_ki(kileInfo) + : QListWidget(parent), m_ki(kileInfo) { - setObjectName(name); - setViewMode(IconMode); - setGridSize(QSize(36, 36)); - setSpacing(5); - setWordWrap(false); - setResizeMode(Adjust); - setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); - setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded); - setMovement(Static); - setSortingEnabled(false); - setFlow(LeftToRight); - setDragDropMode(NoDragDrop); - m_brush = KStatefulBrush(KColorScheme::View, KColorScheme::NormalText); - initPage(type); + setObjectName(name); + setViewMode(IconMode); + setGridSize(QSize(36, 36)); + setSpacing(5); + setWordWrap(false); + setResizeMode(Adjust); + setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); + setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded); + setMovement(Static); + setSortingEnabled(false); + setFlow(LeftToRight); + setDragDropMode(NoDragDrop); + m_brush = KStatefulBrush(KColorScheme::View, KColorScheme::NormalText); + initPage(type); } SymbolView::~SymbolView() { } /* key format from old symbols with package info 1%\textonequarter%%%{textcomp}%%/home/kdedev/.kde4/share/apps/kile/mathsymbols/misc-text/img072misc-text.png from old symbols without package info 1%\oldstylenums{9}%%%%%/home/kdedev/.kde4/share/apps/kile/mathsymbols/misc-text/img070misc-text.png new symbol 1%\neq%≠%[utf8x,,]{inputenc,ucs,}%[fleqn,]{amsmath,}%This command gives nice weather!%/home/kdedev/.kde4/share/apps/kile/mathsymbols/user/img002math.png */ void SymbolView::extract(const QString& key, int& refCnt) { - if (!key.isEmpty()) { - refCnt = key.section('%', 0, 0).toInt(); - } + if (!key.isEmpty()) { + refCnt = key.section('%', 0, 0).toInt(); + } } void SymbolView::extractPackageString(const QString&string, QList &packages) { - QRegExp rePkgs("(?:\\[(.*)\\])?\\{(.*)\\}"); - QStringList args,pkgs; - Package pkg; - - if(string.isEmpty()) { - return; - } - - packages.clear(); - - if(rePkgs.exactMatch(string)) { - args = rePkgs.cap(1).split(','); - pkgs = rePkgs.cap(2).split(','); - } - else { - return; - } - - for(int i = 0 ; i < pkgs.count() && i < args.count() ; i++) { - const QString packageName = pkgs.at(i); - if(packageName.isEmpty()) { - continue; - } - pkg.name = packageName; - pkg.arguments = args.at(i); - packages.append(pkg); - } + QRegExp rePkgs("(?:\\[(.*)\\])?\\{(.*)\\}"); + QStringList args,pkgs; + Package pkg; + + if(string.isEmpty()) { + return; + } + + packages.clear(); + + if(rePkgs.exactMatch(string)) { + args = rePkgs.cap(1).split(','); + pkgs = rePkgs.cap(2).split(','); + } + else { + return; + } + + for(int i = 0 ; i < pkgs.count() && i < args.count() ; i++) { + const QString packageName = pkgs.at(i); + if(packageName.isEmpty()) { + continue; + } + pkg.name = packageName; + pkg.arguments = args.at(i); + packages.append(pkg); + } } void SymbolView::extract(const QString& key, Command &cmd) { - if (key.isEmpty()) { - return; - } - QStringList contents = key.split('%'); - QString packages; - - cmd.referenceCount = contents.at(0).toInt(); - cmd.latexCommand = contents.at(1); - cmd.unicodeCommand = contents.at(2); - - extractPackageString(contents.at(3), cmd.unicodePackages); - extractPackageString(contents.at(4), cmd.packages); - cmd.comment = contents.at(5); - cmd.path = contents.at(6); + if (key.isEmpty()) { + return; + } + QStringList contents = key.split('%'); + QString packages; + + cmd.referenceCount = contents.at(0).toInt(); + cmd.latexCommand = contents.at(1); + cmd.unicodeCommand = contents.at(2); + + extractPackageString(contents.at(3), cmd.unicodePackages); + extractPackageString(contents.at(4), cmd.packages); + cmd.comment = contents.at(5); + cmd.path = contents.at(6); } void SymbolView::initPage(int page) { - switch(page) { - case MFUS: - fillWidget(MFUS_PREFIX); - break; - - case Relation: - fillWidget("relation"); - break; - - case Operator: - fillWidget("operators"); - break; - - case Arrow: - fillWidget("arrows"); - break; - - case MiscMath: - fillWidget("misc-math"); - break; - - case MiscText: - fillWidget("misc-text"); - break; - - case Delimiters: - fillWidget("delimiters"); - break; - - case Greek: - fillWidget("greek"); - break; - - case Special: - fillWidget("special"); - break; - - case Cyrillic: - fillWidget("cyrillic"); - break; - - case User: - fillWidget("user"); - break; - - default: - qWarning() << "wrong argument in initPage()"; - break; - } + switch(page) { + case MFUS: + fillWidget(MFUS_PREFIX); + break; + + case Relation: + fillWidget("relation"); + break; + + case Operator: + fillWidget("operators"); + break; + + case Arrow: + fillWidget("arrows"); + break; + + case MiscMath: + fillWidget("misc-math"); + break; + + case MiscText: + fillWidget("misc-text"); + break; + + case Delimiters: + fillWidget("delimiters"); + break; + + case Greek: + fillWidget("greek"); + break; + + case Special: + fillWidget("special"); + break; + + case Cyrillic: + fillWidget("cyrillic"); + break; + + case User: + fillWidget("user"); + break; + + default: + qWarning() << "wrong argument in initPage()"; + break; + } } QString SymbolView::getToolTip(const QString &key) { - Command cmd; - extract(key, cmd); - - QString label = "

"; - label += "" + i18n("Command: %1", cmd.latexCommand.toHtmlEscaped()) + ""; - if(!cmd.unicodeCommand.isEmpty()) { - label += i18n("
Unicode: %1", cmd.unicodeCommand.toHtmlEscaped()); - } - - if(cmd.packages.count() > 0) { - QString packageString; - - if(cmd.packages.count() == 1) { - Package pkg = cmd.packages.at(0); - if(!pkg.arguments.isEmpty()) { - packageString += '[' + pkg.arguments + ']' + pkg.name; - } - else { - packageString += pkg.name; - } - } - else { - packageString = "

    "; - for (int i = 0; i < cmd.packages.count() ; ++i) { - Package pkg = cmd.packages.at(i); - if(!pkg.arguments.isEmpty()) { - packageString += "
  • [" + pkg.arguments + ']' + pkg.name + "
  • "; - } - else { - packageString += "
  • " + pkg.name + "
  • "; - } - } - packageString += "
"; - } - label += "
" + i18np("Required Package: %2", "Required Packages: %2", cmd.packages.count(), packageString); - } - - if(!cmd.comment.isEmpty()) { - label += "
" + i18n("Comment: %1", cmd.comment.toHtmlEscaped()) + ""; - } - - label += "

"; - return label; + Command cmd; + extract(key, cmd); + + QString label = "

"; + label += "" + i18n("Command: %1", cmd.latexCommand.toHtmlEscaped()) + ""; + if(!cmd.unicodeCommand.isEmpty()) { + label += i18n("
Unicode: %1", cmd.unicodeCommand.toHtmlEscaped()); + } + + if(cmd.packages.count() > 0) { + QString packageString; + + if(cmd.packages.count() == 1) { + Package pkg = cmd.packages.at(0); + if(!pkg.arguments.isEmpty()) { + packageString += '[' + pkg.arguments + ']' + pkg.name; + } + else { + packageString += pkg.name; + } + } + else { + packageString = "

    "; + for (int i = 0; i < cmd.packages.count() ; ++i) { + Package pkg = cmd.packages.at(i); + if(!pkg.arguments.isEmpty()) { + packageString += "
  • [" + pkg.arguments + ']' + pkg.name + "
  • "; + } + else { + packageString += "
  • " + pkg.name + "
  • "; + } + } + packageString += "
"; + } + label += "
" + i18np("Required Package: %2", "Required Packages: %2", cmd.packages.count(), packageString); + } + + if(!cmd.comment.isEmpty()) { + label += "
" + i18n("Comment: %1", cmd.comment.toHtmlEscaped()) + ""; + } + + label += "

"; + return label; } void SymbolView::mousePressEvent(QMouseEvent *event) { - Command cmd; - QString code_symbol; - QList packages; - QListWidgetItem *item = Q_NULLPTR; - bool math = false, bracket = false; - - if(event->button() == Qt::LeftButton && (item = itemAt(event->pos()))) { - bracket = event->modifiers() & Qt::ControlModifier; - math = event->modifiers() & Qt::ShiftModifier; - - extract(item->data(Qt::UserRole).toString(), cmd); - if(KileConfig::symbolViewUTF8()) { - code_symbol = cmd.unicodeCommand; - if(code_symbol.isEmpty()) { - code_symbol = cmd.latexCommand; - } - packages = cmd.unicodePackages; - } - else { - code_symbol = cmd.latexCommand; - packages = cmd.packages; - } - - if(math != bracket) { - if(math) { - code_symbol = '$' + code_symbol + '$'; - } - else if(bracket) { - code_symbol = '{' + code_symbol + '}'; - } - } - emit(insertText(code_symbol, packages)); - emit(addToList(item)); - m_ki->focusEditor(); - } - - KILE_DEBUG_MAIN << "math is " << math << ", bracket is " << bracket << " and item->data(Qt::UserRole).toString() is " << (item ? item->data(Qt::UserRole).toString() : ""); + Command cmd; + QString code_symbol; + QList packages; + QListWidgetItem *item = Q_NULLPTR; + bool math = false, bracket = false; + + if(event->button() == Qt::LeftButton && (item = itemAt(event->pos()))) { + bracket = event->modifiers() & Qt::ControlModifier; + math = event->modifiers() & Qt::ShiftModifier; + + extract(item->data(Qt::UserRole).toString(), cmd); + if(KileConfig::symbolViewUTF8()) { + code_symbol = cmd.unicodeCommand; + if(code_symbol.isEmpty()) { + code_symbol = cmd.latexCommand; + } + packages = cmd.unicodePackages; + } + else { + code_symbol = cmd.latexCommand; + packages = cmd.packages; + } + + if(math != bracket) { + if(math) { + code_symbol = '$' + code_symbol + '$'; + } + else if(bracket) { + code_symbol = '{' + code_symbol + '}'; + } + } + emit(insertText(code_symbol, packages)); + emit(addToList(item)); + m_ki->focusEditor(); + } + + KILE_DEBUG_MAIN << "math is " << math << ", bracket is " << bracket << " and item->data(Qt::UserRole).toString() is " << (item ? item->data(Qt::UserRole).toString() : ""); } QString convertLatin1StringtoUTF8(const QString &string) { - if(string.isEmpty()){ - return QString(); - } - - QVector stringAsIntVector; - QStringList stringList = string.split(',', QString::SkipEmptyParts); - - QStringList::const_iterator it; - QString str; - bool ok; - int stringAsInt; - for(it = stringList.constBegin(); it != stringList.constEnd(); it++) { - str = *it; - str.remove("U+"); - stringAsInt = str.toInt(&ok); - if(!ok) { - return QString(); - } - stringAsIntVector.append(stringAsInt); - } - - return QString::fromUcs4(stringAsIntVector.data(),stringAsIntVector.count()); + if(string.isEmpty()) { + return QString(); + } + + QVector stringAsIntVector; + QStringList stringList = string.split(',', QString::SkipEmptyParts); + + QStringList::const_iterator it; + QString str; + bool ok; + int stringAsInt; + for(it = stringList.constBegin(); it != stringList.constEnd(); it++) { + str = *it; + str.remove("U+"); + stringAsInt = str.toInt(&ok); + if(!ok) { + return QString(); + } + stringAsIntVector.append(stringAsInt); + } + + return QString::fromUcs4(stringAsIntVector.data(),stringAsIntVector.count()); } void SymbolView::fillWidget(const QString& prefix) { - KILE_DEBUG_MAIN << "===SymbolView::fillWidget(const QString& " << prefix << " )==="; - QImage image; - QListWidgetItem* item; - QStringList refCnts, paths, unicodeValues; - QString key; - - // find paths - if (prefix == MFUS_PREFIX) { // case: most frequently used symbols - KConfigGroup config = KSharedConfig::openConfig()->group(MFUS_GROUP); - QString configPaths = config.readEntry("paths"); - QString configrefCnts = config.readEntry("counts"); - paths = configPaths.split(',', QString::SkipEmptyParts); - refCnts = configrefCnts.split(',', QString::SkipEmptyParts); - KILE_DEBUG_MAIN << "Read " << paths.count() << " paths and " << refCnts.count() << " refCnts"; - if(paths.count() != refCnts.count()) { - KILE_DEBUG_MAIN << "error in saved LRU list"; - paths.clear(); - refCnts.clear(); - } - } - else { // case: any other group of math symbols - const QStringList dirs = QStandardPaths::locateAll(QStandardPaths::GenericDataLocation, "kile/mathsymbols/" + prefix, QStandardPaths::LocateDirectory); - Q_FOREACH (const QString &dir, dirs) { - const QStringList fileNames = QDir(dir).entryList(QStringList() << QStringLiteral("*.png")); - Q_FOREACH (const QString &file, fileNames) { - const QString path = dir + '/' + file; - if (!paths.contains(path)) { - paths.append(path); - } - } - } - paths.sort(); - for (int i = 0; i < paths.count(); i++) { - refCnts.append("1"); - } - } - - // render symbols - for (int i = 0; i < paths.count(); i++) { - if (image.load(paths[i])) { - item = new QListWidgetItem(this); - - key = refCnts[i] + '%' + image.text("Command"); - key += '%' + convertLatin1StringtoUTF8(image.text("CommandUnicode")); - key += '%' + image.text("UnicodePackages"); - key += '%' + image.text("Packages"); - key += '%' + convertLatin1StringtoUTF8(image.text("Comment")); - key += '%' + paths[i]; - - item->setData(Qt::UserRole, key); - item->setToolTip(getToolTip(key)); - - if (prefix != QLatin1String("user")){ - if (image.format() != QImage::Format_ARGB32_Premultiplied && image.format() != QImage::Format_ARGB32){ - image = image.convertToFormat(QImage::Format_ARGB32_Premultiplied); - } - - QPainter p; - p.begin(&image); - p.setCompositionMode(QPainter::CompositionMode_SourceAtop); - p.fillRect(image.rect(), m_brush.brush(QPalette::Active)); - p.end(); - } - item->setIcon(QPixmap::fromImage(image)); - } - else { - KILE_DEBUG_MAIN << "Loading file " << paths[i] << " failed"; - } - } + KILE_DEBUG_MAIN << "===SymbolView::fillWidget(const QString& " << prefix << " )==="; + QImage image; + QListWidgetItem* item; + QStringList refCnts, paths, unicodeValues; + QString key; + + // find paths + if (prefix == MFUS_PREFIX) { // case: most frequently used symbols + KConfigGroup config = KSharedConfig::openConfig()->group(MFUS_GROUP); + QString configPaths = config.readEntry("paths"); + QString configrefCnts = config.readEntry("counts"); + paths = configPaths.split(',', QString::SkipEmptyParts); + refCnts = configrefCnts.split(',', QString::SkipEmptyParts); + KILE_DEBUG_MAIN << "Read " << paths.count() << " paths and " << refCnts.count() << " refCnts"; + if(paths.count() != refCnts.count()) { + KILE_DEBUG_MAIN << "error in saved LRU list"; + paths.clear(); + refCnts.clear(); + } + } + else { // case: any other group of math symbols + const QStringList dirs = QStandardPaths::locateAll(QStandardPaths::GenericDataLocation, "kile/mathsymbols/" + prefix, QStandardPaths::LocateDirectory); + Q_FOREACH (const QString &dir, dirs) { + const QStringList fileNames = QDir(dir).entryList(QStringList() << QStringLiteral("*.png")); + Q_FOREACH (const QString &file, fileNames) { + const QString path = dir + '/' + file; + if (!paths.contains(path)) { + paths.append(path); + } + } + } + paths.sort(); + for (int i = 0; i < paths.count(); i++) { + refCnts.append("1"); + } + } + + // render symbols + for (int i = 0; i < paths.count(); i++) { + if (image.load(paths[i])) { + item = new QListWidgetItem(this); + + key = refCnts[i] + '%' + image.text("Command"); + key += '%' + convertLatin1StringtoUTF8(image.text("CommandUnicode")); + key += '%' + image.text("UnicodePackages"); + key += '%' + image.text("Packages"); + key += '%' + convertLatin1StringtoUTF8(image.text("Comment")); + key += '%' + paths[i]; + + item->setData(Qt::UserRole, key); + item->setToolTip(getToolTip(key)); + + if (prefix != QLatin1String("user")) { + if (image.format() != QImage::Format_ARGB32_Premultiplied && image.format() != QImage::Format_ARGB32) { + image = image.convertToFormat(QImage::Format_ARGB32_Premultiplied); + } + + QPainter p; + p.begin(&image); + p.setCompositionMode(QPainter::CompositionMode_SourceAtop); + p.fillRect(image.rect(), m_brush.brush(QPalette::Active)); + p.end(); + } + item->setIcon(QPixmap::fromImage(image)); + } + else { + KILE_DEBUG_MAIN << "Loading file " << paths[i] << " failed"; + } + } } void SymbolView::writeConfig() { - QListWidgetItem *item; - QStringList paths; - QList refCnts; - Command cmd; - - KConfigGroup grp = KSharedConfig::openConfig()->group(MFUS_GROUP); - - if (KileConfig::clearMFUS()) { - grp.deleteEntry("paths"); - grp.deleteEntry("counts"); - } - else { - for(int i = 0; i < count(); ++i) { - item = this->item(i); - extract(item->data(Qt::UserRole).toString(),cmd); - refCnts.append(cmd.referenceCount); - paths.append(cmd.path); - KILE_DEBUG_MAIN << "path=" << paths.last() << ", count is " << refCnts.last(); - } - grp.writeEntry("paths", paths); - grp.writeEntry("counts", refCnts); - } + QListWidgetItem *item; + QStringList paths; + QList refCnts; + Command cmd; + + KConfigGroup grp = KSharedConfig::openConfig()->group(MFUS_GROUP); + + if (KileConfig::clearMFUS()) { + grp.deleteEntry("paths"); + grp.deleteEntry("counts"); + } + else { + for(int i = 0; i < count(); ++i) { + item = this->item(i); + extract(item->data(Qt::UserRole).toString(),cmd); + refCnts.append(cmd.referenceCount); + paths.append(cmd.path); + KILE_DEBUG_MAIN << "path=" << paths.last() << ", count is " << refCnts.last(); + } + grp.writeEntry("paths", paths); + grp.writeEntry("counts", refCnts); + } } void SymbolView::slotAddToList(const QListWidgetItem *item) { - if(!item || item->icon().isNull()) { - return; - } - - QListWidgetItem *tmpItem = Q_NULLPTR; - bool found = false; - const QRegExp reCnt("^\\d+"); - - KILE_DEBUG_MAIN << "===void SymbolView::slotAddToList(const QIconViewItem *" << item << " )==="; - - for(int i = 0; i < count(); ++i) { - tmpItem = this->item(i); - if (item->data(Qt::UserRole).toString().section('%', 1) == tmpItem->data(Qt::UserRole).toString().section('%', 1)) { - found = true; - break; - } - } - - if(!found - && static_cast(this->count() + 1) > KileConfig::numSymbolsMFUS()) { // we check before adding the symbol - int refCnt, minRefCnt = 10000; - QListWidgetItem *unpopularItem = Q_NULLPTR; - - KILE_DEBUG_MAIN << "Removing most unpopular item"; - - for (int i = 0; i < count(); ++i) { - tmpItem = this->item(i); - extract(tmpItem->data(Qt::UserRole).toString(), refCnt); - - if (refCnt < minRefCnt) { - refCnt = minRefCnt; - unpopularItem = tmpItem; - } - } - KILE_DEBUG_MAIN << " minRefCnt is " << minRefCnt; - delete unpopularItem; - } - - if(found) { - KILE_DEBUG_MAIN << "item is already in the iconview"; - - int refCnt; - extract(tmpItem->data(Qt::UserRole).toString(), refCnt); - - QString key = tmpItem->data(Qt::UserRole).toString(); - key.replace(reCnt, QString::number(refCnt + 1)); - tmpItem->setData(Qt::UserRole, key); - tmpItem->setToolTip(getToolTip(key)); - } - else { - tmpItem = new QListWidgetItem(this); - tmpItem->setIcon(item->icon()); - QString key = item->data(Qt::UserRole).toString(); - tmpItem->setData(Qt::UserRole, key); - tmpItem->setToolTip(getToolTip(key)); - } + if(!item || item->icon().isNull()) { + return; + } + + QListWidgetItem *tmpItem = Q_NULLPTR; + bool found = false; + const QRegExp reCnt("^\\d+"); + + KILE_DEBUG_MAIN << "===void SymbolView::slotAddToList(const QIconViewItem *" << item << " )==="; + + for(int i = 0; i < count(); ++i) { + tmpItem = this->item(i); + if (item->data(Qt::UserRole).toString().section('%', 1) == tmpItem->data(Qt::UserRole).toString().section('%', 1)) { + found = true; + break; + } + } + + if(!found + && static_cast(this->count() + 1) > KileConfig::numSymbolsMFUS()) { // we check before adding the symbol + int refCnt, minRefCnt = 10000; + QListWidgetItem *unpopularItem = Q_NULLPTR; + + KILE_DEBUG_MAIN << "Removing most unpopular item"; + + for (int i = 0; i < count(); ++i) { + tmpItem = this->item(i); + extract(tmpItem->data(Qt::UserRole).toString(), refCnt); + + if (refCnt < minRefCnt) { + refCnt = minRefCnt; + unpopularItem = tmpItem; + } + } + KILE_DEBUG_MAIN << " minRefCnt is " << minRefCnt; + delete unpopularItem; + } + + if(found) { + KILE_DEBUG_MAIN << "item is already in the iconview"; + + int refCnt; + extract(tmpItem->data(Qt::UserRole).toString(), refCnt); + + QString key = tmpItem->data(Qt::UserRole).toString(); + key.replace(reCnt, QString::number(refCnt + 1)); + tmpItem->setData(Qt::UserRole, key); + tmpItem->setToolTip(getToolTip(key)); + } + else { + tmpItem = new QListWidgetItem(this); + tmpItem->setIcon(item->icon()); + QString key = item->data(Qt::UserRole).toString(); + tmpItem->setData(Qt::UserRole, key); + tmpItem->setToolTip(getToolTip(key)); + } } } diff --git a/src/widgets/symbolview.h b/src/widgets/symbolview.h index b850e5d0..f27fd3b4 100644 --- a/src/widgets/symbolview.h +++ b/src/widgets/symbolview.h @@ -1,67 +1,67 @@ /*************************************************************************************** begin : Fri Aug 1 2003 copyright : (C) 2002 - 2003 by Pascal Brachet 2003 Jeroen Wijnhout (Jeroen.Wijnhout@kdemail.net) 2006 - 2009 Thomas Braun ***************************************************************************************/ /*************************************************************************** * * * 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. * * * ***************************************************************************/ #ifndef SYMBOLVIEW_H #define SYMBOLVIEW_H #include #include #include "../symbolviewclasses.h" class QMouseEvent; class KileInfo; namespace KileWidget { class SymbolView : public QListWidget { - Q_OBJECT + Q_OBJECT - public: - explicit SymbolView(KileInfo *kileInfo, QWidget *parent = 0, int type = -1, const char *name = Q_NULLPTR); - ~SymbolView(); - enum { MFUS = 0, Relation, Operator, Arrow, MiscMath, MiscText, Delimiters, Greek, Special, Cyrillic, User }; - void writeConfig(); +public: + explicit SymbolView(KileInfo *kileInfo, QWidget *parent = 0, int type = -1, const char *name = Q_NULLPTR); + ~SymbolView(); + enum { MFUS = 0, Relation, Operator, Arrow, MiscMath, MiscText, Delimiters, Greek, Special, Cyrillic, User }; + void writeConfig(); - private: - void fillWidget(const QString &prefix); - void extractPackageString(const QString &string, QList &pkgs); - void extract(const QString& key, Command &cmd); - void extract(const QString& key, int& refCnt); - void initPage(int page); - QString getToolTip(const QString &key); +private: + void fillWidget(const QString &prefix); + void extractPackageString(const QString &string, QList &pkgs); + void extract(const QString& key, Command &cmd); + void extract(const QString& key, int& refCnt); + void initPage(int page); + QString getToolTip(const QString &key); - protected: - KileInfo *m_ki; - KStatefulBrush m_brush; +protected: + KileInfo *m_ki; + KStatefulBrush m_brush; - virtual void mousePressEvent(QMouseEvent *event); + virtual void mousePressEvent(QMouseEvent *event); - Q_SIGNALS: - void insertText(const QString& text, const QList &pkgs); - void addToList(const QListWidgetItem *item); +Q_SIGNALS: + void insertText(const QString& text, const QList &pkgs); + void addToList(const QListWidgetItem *item); - public Q_SLOTS: - void slotAddToList(const QListWidgetItem *item); +public Q_SLOTS: + void slotAddToList(const QListWidgetItem *item); }; } #endif diff --git a/src/widgets/symbolviewconfigwidget.cpp b/src/widgets/symbolviewconfigwidget.cpp index 2193083c..1b0b394d 100644 --- a/src/widgets/symbolviewconfigwidget.cpp +++ b/src/widgets/symbolviewconfigwidget.cpp @@ -1,24 +1,24 @@ /************************************************************************** * Copyright (C) 2007 by Michel Ludwig (michel.ludwig@kdemail.net) * ***************************************************************************/ /************************************************************************** * * * 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. * * * ***************************************************************************/ #include "widgets/symbolviewconfigwidget.h" KileWidgetSymbolViewConfig::KileWidgetSymbolViewConfig(QWidget *parent) : QWidget(parent) { - setupUi(this); + setupUi(this); } KileWidgetSymbolViewConfig::~KileWidgetSymbolViewConfig() { } diff --git a/src/widgets/symbolviewconfigwidget.h b/src/widgets/symbolviewconfigwidget.h index 155e3056..2c1a438d 100644 --- a/src/widgets/symbolviewconfigwidget.h +++ b/src/widgets/symbolviewconfigwidget.h @@ -1,30 +1,30 @@ /************************************************************************** * Copyright (C) 2007 by Michel Ludwig (michel.ludwig@kdemail.net) * ***************************************************************************/ /************************************************************************** * * * 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. * * * ***************************************************************************/ #ifndef SYMBOLVIEWCONFIGWIDGET_H #define SYMBOLVIEWCONFIGWIDGET_H #include #include "ui_symbolviewconfigwidget.h" class KileWidgetSymbolViewConfig : public QWidget, public Ui::KileWidgetSymbolViewConfig { - Q_OBJECT + Q_OBJECT - public: - KileWidgetSymbolViewConfig(QWidget *parent = 0); - ~KileWidgetSymbolViewConfig(); +public: + KileWidgetSymbolViewConfig(QWidget *parent = 0); + ~KileWidgetSymbolViewConfig(); }; #endif diff --git a/src/widgets/toolconfigwidget.cpp b/src/widgets/toolconfigwidget.cpp index db3d7d33..48b4c940 100644 --- a/src/widgets/toolconfigwidget.cpp +++ b/src/widgets/toolconfigwidget.cpp @@ -1,521 +1,555 @@ /****************************************************************************************** begin : Sat 3-1 20:40:00 CEST 2004 copyright : (C) 2004 by Jeroen Wijnhout (Jeroen.Wijnhout@kdemail.net) 2007-2017 by Michel Ludwig (michel.ludwig@kdemail.net) ******************************************************************************************/ /*************************************************************************** * * * 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. * * * ***************************************************************************/ #include "widgets/toolconfigwidget.h" #include #include #include #include #include #include #include #include #include #include "kiledebug.h" #include #include #include #include #include #include #include #include #include "kiletool_enums.h" #include "kiletoolmanager.h" #include "kilestdtools.h" #include "widgets/maintoolconfigwidget.h" #include "widgets/processtoolconfigwidget.h" #include "widgets/quicktoolconfigwidget.h" #include "widgets/latextoolconfigwidget.h" #include "dialogs/newtoolwizard.h" namespace KileWidget { - ToolConfig::ToolConfig(KileTool::Manager *mngr, QWidget *parent, const char *name) : - QWidget(parent), - m_manager(mngr) - { - setObjectName(name); - m_config = m_manager->config(); - QVBoxLayout *layout = new QVBoxLayout(); - layout->setMargin(0); +ToolConfig::ToolConfig(KileTool::Manager *mngr, QWidget *parent, const char *name) : + QWidget(parent), + m_manager(mngr) +{ + setObjectName(name); + m_config = m_manager->config(); + QVBoxLayout *layout = new QVBoxLayout(); + layout->setMargin(0); //TODO PORT QT5 layout->setSpacing(QDialog::spacingHint()); - setLayout(layout); - m_configWidget = new ToolConfigWidget(this); - layout->addWidget(m_configWidget); - - m_tabGeneral = m_configWidget->m_tab->widget(0); - m_tabAdvanced = m_configWidget->m_tab->widget(1); - m_tabMenu = m_configWidget->m_tab->widget(2); - - updateToollist(); - QListWidgetItem *item = m_configWidget->m_lstbTools->item(indexQuickBuild()); - if (item) - m_configWidget->m_lstbTools->setCurrentItem(item); - - connect(m_configWidget->m_cbConfig, SIGNAL(activated(int)), this, SLOT(switchConfig(int))); - - // 'm_cbMenu' also stores a mapping from English menu names to their translation - m_configWidget->m_cbMenu->addItem(i18n("Quick"), QVariant("Quick")); - m_configWidget->m_cbMenu->addItem(i18n("Compile"), QVariant("Compile")); - m_configWidget->m_cbMenu->addItem(i18n("Convert"), QVariant("Convert")); - m_configWidget->m_cbMenu->addItem(i18n("View"), QVariant("View")); - m_configWidget->m_cbMenu->addItem(i18n("Other"), QVariant("Other")); - connect(m_configWidget->m_cbMenu, SIGNAL(activated(int)), this, SLOT(setMenu(int))); - connect(m_configWidget->m_pshbIcon, SIGNAL(clicked()), this, SLOT(selectIcon())); - - connect(m_configWidget->m_pshbRemoveTool, SIGNAL(clicked()), this, SLOT(removeTool())); - connect(m_configWidget->m_pshbNewTool, SIGNAL(clicked()), this, SLOT(newTool())); - connect(m_configWidget->m_pshbRemoveConfig, SIGNAL(clicked()), this, SLOT(removeConfig())); - connect(m_configWidget->m_pshbNewConfig, SIGNAL(clicked()), this, SLOT(newConfig())); - connect(m_configWidget->m_pshbDefault, SIGNAL(clicked()), this, SLOT(writeDefaults())); - - //--->m_current = m_configWidget->m_lstbTools->text(0); - QListWidgetItem *currentItem = m_configWidget->m_lstbTools->currentItem(); - if(currentItem) { - m_current = currentItem->text(); - } - m_manager->retrieveEntryMap(m_current, m_map, false, false); - QString cfg = KileTool::configName(m_current, m_config); - m_configWidget->m_cbConfig->addItem(cfg); - - setupGeneral(); - setupAdvanced(); - - switchConfig(cfg); - switchTo(m_current, false); - connect(m_configWidget->m_lstbTools, SIGNAL(currentTextChanged(const QString &)), this, SLOT(switchTo(const QString &))); - - connect(this, SIGNAL(changed()), this, SLOT(updateAdvanced())); - connect(this, SIGNAL(changed()), this, SLOT(updateGeneral())); - } - - void ToolConfig::setupAdvanced() - { - m_configWidget->m_cbType->addItem(i18n("Run Outside of Kile")); - m_configWidget->m_cbType->addItem(i18n("Run in Konsole")); - m_configWidget->m_cbType->addItem(i18n("Use Document Viewer")); - m_configWidget->m_cbType->addItem(i18n("Run Sequence of Tools")); - connect(m_configWidget->m_cbType, SIGNAL(activated(int)), this, SLOT(switchType(int))); - connect(m_configWidget->m_ckClose, SIGNAL(toggled(bool)), this, SLOT(setClose(bool))); - - m_classes << "Compile" << "Convert" << "Archive" << KileTool::BibliographyCompile::ToolClass << "View" << "Sequence" << "LaTeX" << "ViewHTML" << "ViewBib" << "ForwardDVI" << "Base"; - m_configWidget->m_cbClass->addItems(m_classes); - connect(m_configWidget->m_cbClass, SIGNAL(activated(const QString &)), this, SLOT(switchClass(const QString &))); - - connect(m_configWidget->m_leSource, SIGNAL(textChanged(const QString &)), this, SLOT(setFrom(const QString &))); - connect(m_configWidget->m_leTarget, SIGNAL(textChanged(const QString &)), this, SLOT(setTo(const QString &))); - connect(m_configWidget->m_leFile, SIGNAL(textChanged(const QString &)), this, SLOT(setTarget(const QString &))); - connect(m_configWidget->m_leRelDir, SIGNAL(textChanged(const QString &)), this, SLOT(setRelDir(const QString &))); - } - - void ToolConfig::updateAdvanced() - { - bool enablekonsoleclose = false; - QString type = m_map["type"]; - if(type == "Process") { - m_configWidget->m_cbType->setCurrentIndex(0); - } - else if(type == "Konsole") { - m_configWidget->m_cbType->setCurrentIndex(1); - enablekonsoleclose = true; - } - else if(type == "DocumentViewer") { - m_configWidget->m_cbType->setCurrentIndex(2); - } - else if(type == "Sequence") { - m_configWidget->m_cbType->setCurrentIndex(3); - } - m_configWidget->m_ckClose->setEnabled(enablekonsoleclose); - - int index = m_classes.indexOf(m_map["class"]); - if(index == -1) { - index = m_classes.count() - 1; - } - m_configWidget->m_cbClass->setCurrentIndex(index); - m_configWidget->m_ckClose->setChecked(m_map["close"] == "yes"); - m_configWidget->m_leSource->setText(m_map["from"]); - m_configWidget->m_leTarget->setText(m_map["to"]); - m_configWidget->m_leFile->setText(m_map["target"]); - m_configWidget->m_leRelDir->setText(m_map["relDir"]); - } - - void ToolConfig::setupGeneral() - { - m_configWidget->m_stackBasic->insertWidget(GBS_None, new QLabel(i18n("Use the \"Advanced\" tab to configure this tool."), this)); - - m_ptcw = new ProcessToolConfigWidget(m_configWidget->m_stackBasic); - m_configWidget->m_stackBasic->insertWidget(GBS_Process, m_ptcw); - connect(m_ptcw->m_command, SIGNAL(textChanged(const QString &)), this, SLOT(setCommand(const QString &))); - connect(m_ptcw->m_options, SIGNAL(textChanged()), this, SLOT(setOptions())); - - m_qtcw = new QuickToolConfigWidget(m_configWidget->m_stackBasic); - m_configWidget->m_stackBasic->insertWidget(GBS_Sequence, m_qtcw); - connect(m_qtcw, SIGNAL(sequenceChanged(const QString &)), this, SLOT(setSequence(const QString &))); - - m_configWidget->m_stackBasic->insertWidget(GBS_Error, new QLabel(i18n("Unknown tool type; your configuration data is malformed.\nPerhaps it is a good idea to restore the default settings."), this)); - - m_configWidget->m_stackExtra->insertWidget(GES_None, new QWidget(this)); - - m_LaTeXtcw = new LaTeXToolConfigWidget(m_configWidget->m_stackExtra); - m_configWidget->m_stackExtra->insertWidget(GES_LaTeX, m_LaTeXtcw); - connect(m_LaTeXtcw->m_ckRootDoc, SIGNAL(toggled(bool)), this, SLOT(setLaTeXCheckRoot(bool))); - connect(m_LaTeXtcw->m_ckJump, SIGNAL(toggled(bool)), this, SLOT(setLaTeXJump(bool))); - connect(m_LaTeXtcw->m_ckAutoRun, SIGNAL(toggled(bool)), this, SLOT(setLaTeXAuto(bool))); - - } - - void ToolConfig::updateGeneral() - { - QString type = m_map["type"]; - - int basicPage = GBS_None; - int extraPage = GES_None; - - if(type == "Process" || type == "Konsole") { - basicPage = GBS_Process; - } - else if(type == "DocumentViewer") { - basicPage = GBS_None; - } - else if(type == "Sequence") { - basicPage = GBS_Sequence; - m_qtcw->updateSequence(m_map["sequence"]); - } - else { - basicPage = GBS_Error; - } - - QString cls = m_map["class"]; - if(cls == "LaTeX") { - extraPage = GES_LaTeX; - } - - m_ptcw->m_command->setText(m_map["command"]); - m_ptcw->m_options->setText(m_map["options"]); - - m_LaTeXtcw->m_ckRootDoc->setChecked(m_map["checkForRoot"] == "yes"); - m_LaTeXtcw->m_ckJump->setChecked(m_map["jumpToFirstError"] == "yes"); - m_LaTeXtcw->m_ckAutoRun->setChecked(m_map["autoRun"] == "yes"); - - KILE_DEBUG_MAIN << "showing pages " << basicPage << " " << extraPage; - m_configWidget->m_stackBasic->setCurrentIndex(basicPage); - m_configWidget->m_stackExtra->setCurrentIndex(extraPage); - - } - - void ToolConfig::writeDefaults() - { - if (KMessageBox::warningContinueCancel(this, i18n("All your tool settings will be overwritten with the default settings.\nAre you sure you want to continue?")) == KMessageBox::Continue) { - m_manager->factory()->resetToolConfigurations(); - m_config->sync(); - updateToollist(); - QStringList tools = KileTool::toolList(m_config, true); - for (int i = 0; i < tools.count(); ++i) { - switchTo(tools[i], false);// needed to retrieve the new map - switchTo(tools[i], true); // this writes the newly retrieved entry map (and not an perhaps changed old one) - } - int index = indexQuickBuild(); - if(!tools.empty()) { - switchTo(tools[index], false); - m_configWidget->m_lstbTools->item(index)->setSelected(true); - } - } - } - - void ToolConfig::updateToollist() - { - //KILE_DEBUG_MAIN << "==ToolConfig::updateToollist()===================="; - m_configWidget->m_lstbTools->clear(); - m_configWidget->m_lstbTools->addItems(KileTool::toolList(m_config, true)); - m_configWidget->m_lstbTools->sortItems(); - } - - void ToolConfig::setMenu(int index) - { - // internally, menu names are stored in English - m_map["menu"] = m_configWidget->m_cbMenu->itemData(index).toString(); - } - - void ToolConfig::writeConfig() - { - //KILE_DEBUG_MAIN << "==ToolConfig::writeConfig()===================="; - //save config - m_manager->saveEntryMap(m_current, m_map, false, false); - // internally, menu names are stored in English - KileTool::setGUIOptions(m_current, - m_configWidget->m_cbMenu->itemData(m_configWidget->m_cbMenu->currentIndex()).toString(), - m_icon, - m_config); - } - - int ToolConfig::indexQuickBuild() - { - QList itemsList = m_configWidget->m_lstbTools->findItems("QuickBuild", Qt::MatchExactly); - if(itemsList.isEmpty()) { - return 0; - } - - return m_configWidget->m_lstbTools->row(itemsList.first()); - } - - void ToolConfig::switchConfig(int /*index*/) - { - //KILE_DEBUG_MAIN << "==ToolConfig::switchConfig(int /*index*/)===================="; - switchTo(m_current); - } - - void ToolConfig::switchConfig(const QString & cfg) - { - //KILE_DEBUG_MAIN << "==ToolConfig::switchConfig(const QString & cfg)=========="; - for(int i = 0; i < m_configWidget->m_cbConfig->count(); ++i) { - if (m_configWidget->m_cbConfig->itemText(i) == cfg) { - m_configWidget->m_cbConfig->setCurrentIndex(i); - } - } - } - - void ToolConfig::switchTo(const QString & tool, bool save /* = true */) - { - //KILE_DEBUG_MAIN << "==ToolConfig::switchTo(const QString & tool, bool save /* = true */)===================="; - //save config - if(save) { - writeConfig(); - - //update the config number - QString cf = m_configWidget->m_cbConfig->currentText(); - KileTool::setConfigName(m_current, cf, m_config); - } - - m_current = tool; - - m_map.clear(); - if (!m_manager->retrieveEntryMap(m_current, m_map, false, false)) { - qWarning() << "no entrymap"; - } - - updateConfiglist(); - updateGeneral(); - updateAdvanced(); - - //show GUI info - QString menu = KileTool::menuFor(m_current, m_config); - int i = m_configWidget->m_cbMenu->findData(menu); - if(i >= 0) { - m_configWidget->m_cbMenu->setCurrentIndex(i); - } - else { - m_configWidget->m_cbMenu->addItem(menu, QVariant(menu)); - m_configWidget->m_cbMenu->setCurrentIndex(m_configWidget->m_cbMenu->count() - 1); - } - m_icon = KileTool::iconFor(m_current, m_config); - if(m_icon.isEmpty()) { - m_configWidget->m_pshbIcon->setIcon(QIcon::fromTheme(QString())); - } - else { - m_configWidget->m_pshbIcon->setIcon(QIcon::fromTheme(m_icon)); - } - } - - void ToolConfig::updateConfiglist() - { - //KILE_DEBUG_MAIN << "==ToolConfig::updateConfiglist()====================="; - m_configWidget->m_groupBox->setTitle(i18n("Choose a configuration for the tool %1",m_current)); - m_configWidget->m_cbConfig->clear(); - m_configWidget->m_cbConfig->addItems(KileTool::configNames(m_current, m_config)); - QString cfg = KileTool::configName(m_current, m_config); - switchConfig(cfg); - m_configWidget->m_cbConfig->setEnabled(m_configWidget->m_cbConfig->count() > 1); - } - - void ToolConfig::selectIcon() - { - KILE_DEBUG_MAIN << "icon ---> " << m_icon; - //KILE_DEBUG_MAIN << "==ToolConfig::selectIcon()====================="; - KIconDialog *dlg = new KIconDialog(this); - QString res = dlg->openDialog(); - if(m_icon != res) { - if(res.isEmpty()) { - return; - } - - m_icon = res; - writeConfig(); - if (m_icon.isEmpty()) { - m_configWidget->m_pshbIcon->setIcon(QIcon::fromTheme(QString())); - } - else { - m_configWidget->m_pshbIcon->setIcon(QIcon::fromTheme(m_icon)); - } - } - } - - void ToolConfig::newTool() - { - //KILE_DEBUG_MAIN << "==ToolConfig::newTool()====================="; - NewToolWizard *ntw = new NewToolWizard(this); - if (ntw->exec()) { - QString toolName = ntw->toolName(); - QString parentTool = ntw->parentTool(); - - writeStdConfig(toolName, "Default"); - if(parentTool != ntw->customTool()) { - //copy tool info - KileTool::Config tempMap; - m_manager->retrieveEntryMap(parentTool, tempMap, false, false); - KConfigGroup toolGroup = m_config->group(KileTool::groupFor(toolName, "Default")); - toolGroup.writeEntry("class", tempMap["class"]); - toolGroup.writeEntry("type", tempMap["type"]); - toolGroup.writeEntry("close", tempMap["close"]); - toolGroup.writeEntry("checkForRoot", tempMap["checkForRoot"]); - toolGroup.writeEntry("autoRun", tempMap["autoRun"]); - toolGroup.writeEntry("jumpToFirstError", tempMap["jumpToFirstError"]); - } - - m_configWidget->m_lstbTools->blockSignals(true); - updateToollist(); - switchTo(toolName); - for(int i = 0; i < m_configWidget->m_lstbTools->count(); ++i) { - if(m_configWidget->m_lstbTools->item(i)->text() == toolName) { - m_configWidget->m_lstbTools->setCurrentRow(i); - break; - } - } - m_configWidget->m_lstbTools->blockSignals(false); - } - } - - void ToolConfig::newConfig() - { - //KILE_DEBUG_MAIN << "==ToolConfig::newConfig()====================="; - writeConfig(); - bool ok; - QString cfg = QInputDialog::getText(this, i18n("New Configuration"), i18n("Enter new configuration name:"), QLineEdit::Normal, "", &ok); - if (ok && (!cfg.isEmpty())) { - //copy config - KConfigGroup toolGroup = m_config->group(KileTool::groupFor(m_current, cfg)); - for (QMap::Iterator it = m_map.begin(); it != m_map.end(); ++it) { - toolGroup.writeEntry(it.key(), it.value()); - } - KileTool::setConfigName(m_current, cfg, m_config); - switchTo(m_current, false); - switchConfig(cfg); - } - } - - void ToolConfig::writeStdConfig(const QString & tool, const QString & cfg) - { - KConfigGroup toolGroup = m_config->group(KileTool::groupFor(tool, cfg)); - toolGroup.writeEntry("class", "Compile"); - toolGroup.writeEntry("type", "Process"); - toolGroup.writeEntry("menu", "Compile"); - toolGroup.writeEntry("close", "no"); - - m_config->group("Tools").writeEntry(tool, cfg); - } - - void ToolConfig::removeTool() - { + setLayout(layout); + m_configWidget = new ToolConfigWidget(this); + layout->addWidget(m_configWidget); + + m_tabGeneral = m_configWidget->m_tab->widget(0); + m_tabAdvanced = m_configWidget->m_tab->widget(1); + m_tabMenu = m_configWidget->m_tab->widget(2); + + updateToollist(); + QListWidgetItem *item = m_configWidget->m_lstbTools->item(indexQuickBuild()); + if (item) + m_configWidget->m_lstbTools->setCurrentItem(item); + + connect(m_configWidget->m_cbConfig, SIGNAL(activated(int)), this, SLOT(switchConfig(int))); + + // 'm_cbMenu' also stores a mapping from English menu names to their translation + m_configWidget->m_cbMenu->addItem(i18n("Quick"), QVariant("Quick")); + m_configWidget->m_cbMenu->addItem(i18n("Compile"), QVariant("Compile")); + m_configWidget->m_cbMenu->addItem(i18n("Convert"), QVariant("Convert")); + m_configWidget->m_cbMenu->addItem(i18n("View"), QVariant("View")); + m_configWidget->m_cbMenu->addItem(i18n("Other"), QVariant("Other")); + connect(m_configWidget->m_cbMenu, SIGNAL(activated(int)), this, SLOT(setMenu(int))); + connect(m_configWidget->m_pshbIcon, SIGNAL(clicked()), this, SLOT(selectIcon())); + + connect(m_configWidget->m_pshbRemoveTool, SIGNAL(clicked()), this, SLOT(removeTool())); + connect(m_configWidget->m_pshbNewTool, SIGNAL(clicked()), this, SLOT(newTool())); + connect(m_configWidget->m_pshbRemoveConfig, SIGNAL(clicked()), this, SLOT(removeConfig())); + connect(m_configWidget->m_pshbNewConfig, SIGNAL(clicked()), this, SLOT(newConfig())); + connect(m_configWidget->m_pshbDefault, SIGNAL(clicked()), this, SLOT(writeDefaults())); + + //--->m_current = m_configWidget->m_lstbTools->text(0); + QListWidgetItem *currentItem = m_configWidget->m_lstbTools->currentItem(); + if(currentItem) { + m_current = currentItem->text(); + } + m_manager->retrieveEntryMap(m_current, m_map, false, false); + QString cfg = KileTool::configName(m_current, m_config); + m_configWidget->m_cbConfig->addItem(cfg); + + setupGeneral(); + setupAdvanced(); + + switchConfig(cfg); + switchTo(m_current, false); + connect(m_configWidget->m_lstbTools, SIGNAL(currentTextChanged(const QString &)), this, SLOT(switchTo(const QString &))); + + connect(this, SIGNAL(changed()), this, SLOT(updateAdvanced())); + connect(this, SIGNAL(changed()), this, SLOT(updateGeneral())); +} + +void ToolConfig::setupAdvanced() +{ + m_configWidget->m_cbType->addItem(i18n("Run Outside of Kile")); + m_configWidget->m_cbType->addItem(i18n("Run in Konsole")); + m_configWidget->m_cbType->addItem(i18n("Use Document Viewer")); + m_configWidget->m_cbType->addItem(i18n("Run Sequence of Tools")); + connect(m_configWidget->m_cbType, SIGNAL(activated(int)), this, SLOT(switchType(int))); + connect(m_configWidget->m_ckClose, SIGNAL(toggled(bool)), this, SLOT(setClose(bool))); + + m_classes << "Compile" << "Convert" << "Archive" << KileTool::BibliographyCompile::ToolClass << "View" << "Sequence" << "LaTeX" << "ViewHTML" << "ViewBib" << "ForwardDVI" << "Base"; + m_configWidget->m_cbClass->addItems(m_classes); + connect(m_configWidget->m_cbClass, SIGNAL(activated(const QString &)), this, SLOT(switchClass(const QString &))); + + connect(m_configWidget->m_leSource, SIGNAL(textChanged(const QString &)), this, SLOT(setFrom(const QString &))); + connect(m_configWidget->m_leTarget, SIGNAL(textChanged(const QString &)), this, SLOT(setTo(const QString &))); + connect(m_configWidget->m_leFile, SIGNAL(textChanged(const QString &)), this, SLOT(setTarget(const QString &))); + connect(m_configWidget->m_leRelDir, SIGNAL(textChanged(const QString &)), this, SLOT(setRelDir(const QString &))); +} + +void ToolConfig::updateAdvanced() +{ + bool enablekonsoleclose = false; + QString type = m_map["type"]; + if(type == "Process") { + m_configWidget->m_cbType->setCurrentIndex(0); + } + else if(type == "Konsole") { + m_configWidget->m_cbType->setCurrentIndex(1); + enablekonsoleclose = true; + } + else if(type == "DocumentViewer") { + m_configWidget->m_cbType->setCurrentIndex(2); + } + else if(type == "Sequence") { + m_configWidget->m_cbType->setCurrentIndex(3); + } + m_configWidget->m_ckClose->setEnabled(enablekonsoleclose); + + int index = m_classes.indexOf(m_map["class"]); + if(index == -1) { + index = m_classes.count() - 1; + } + m_configWidget->m_cbClass->setCurrentIndex(index); + m_configWidget->m_ckClose->setChecked(m_map["close"] == "yes"); + m_configWidget->m_leSource->setText(m_map["from"]); + m_configWidget->m_leTarget->setText(m_map["to"]); + m_configWidget->m_leFile->setText(m_map["target"]); + m_configWidget->m_leRelDir->setText(m_map["relDir"]); +} + +void ToolConfig::setupGeneral() +{ + m_configWidget->m_stackBasic->insertWidget(GBS_None, new QLabel(i18n("Use the \"Advanced\" tab to configure this tool."), this)); + + m_ptcw = new ProcessToolConfigWidget(m_configWidget->m_stackBasic); + m_configWidget->m_stackBasic->insertWidget(GBS_Process, m_ptcw); + connect(m_ptcw->m_command, SIGNAL(textChanged(const QString &)), this, SLOT(setCommand(const QString &))); + connect(m_ptcw->m_options, SIGNAL(textChanged()), this, SLOT(setOptions())); + + m_qtcw = new QuickToolConfigWidget(m_configWidget->m_stackBasic); + m_configWidget->m_stackBasic->insertWidget(GBS_Sequence, m_qtcw); + connect(m_qtcw, SIGNAL(sequenceChanged(const QString &)), this, SLOT(setSequence(const QString &))); + + m_configWidget->m_stackBasic->insertWidget(GBS_Error, new QLabel(i18n("Unknown tool type; your configuration data is malformed.\nPerhaps it is a good idea to restore the default settings."), this)); + + m_configWidget->m_stackExtra->insertWidget(GES_None, new QWidget(this)); + + m_LaTeXtcw = new LaTeXToolConfigWidget(m_configWidget->m_stackExtra); + m_configWidget->m_stackExtra->insertWidget(GES_LaTeX, m_LaTeXtcw); + connect(m_LaTeXtcw->m_ckRootDoc, SIGNAL(toggled(bool)), this, SLOT(setLaTeXCheckRoot(bool))); + connect(m_LaTeXtcw->m_ckJump, SIGNAL(toggled(bool)), this, SLOT(setLaTeXJump(bool))); + connect(m_LaTeXtcw->m_ckAutoRun, SIGNAL(toggled(bool)), this, SLOT(setLaTeXAuto(bool))); + +} + +void ToolConfig::updateGeneral() +{ + QString type = m_map["type"]; + + int basicPage = GBS_None; + int extraPage = GES_None; + + if(type == "Process" || type == "Konsole") { + basicPage = GBS_Process; + } + else if(type == "DocumentViewer") { + basicPage = GBS_None; + } + else if(type == "Sequence") { + basicPage = GBS_Sequence; + m_qtcw->updateSequence(m_map["sequence"]); + } + else { + basicPage = GBS_Error; + } + + QString cls = m_map["class"]; + if(cls == "LaTeX") { + extraPage = GES_LaTeX; + } + + m_ptcw->m_command->setText(m_map["command"]); + m_ptcw->m_options->setText(m_map["options"]); + + m_LaTeXtcw->m_ckRootDoc->setChecked(m_map["checkForRoot"] == "yes"); + m_LaTeXtcw->m_ckJump->setChecked(m_map["jumpToFirstError"] == "yes"); + m_LaTeXtcw->m_ckAutoRun->setChecked(m_map["autoRun"] == "yes"); + + KILE_DEBUG_MAIN << "showing pages " << basicPage << " " << extraPage; + m_configWidget->m_stackBasic->setCurrentIndex(basicPage); + m_configWidget->m_stackExtra->setCurrentIndex(extraPage); + +} + +void ToolConfig::writeDefaults() +{ + if (KMessageBox::warningContinueCancel(this, i18n("All your tool settings will be overwritten with the default settings.\nAre you sure you want to continue?")) == KMessageBox::Continue) { + m_manager->factory()->resetToolConfigurations(); + m_config->sync(); + updateToollist(); + QStringList tools = KileTool::toolList(m_config, true); + for (int i = 0; i < tools.count(); ++i) { + switchTo(tools[i], false);// needed to retrieve the new map + switchTo(tools[i], true); // this writes the newly retrieved entry map (and not an perhaps changed old one) + } + int index = indexQuickBuild(); + if(!tools.empty()) { + switchTo(tools[index], false); + m_configWidget->m_lstbTools->item(index)->setSelected(true); + } + } +} + +void ToolConfig::updateToollist() +{ + //KILE_DEBUG_MAIN << "==ToolConfig::updateToollist()===================="; + m_configWidget->m_lstbTools->clear(); + m_configWidget->m_lstbTools->addItems(KileTool::toolList(m_config, true)); + m_configWidget->m_lstbTools->sortItems(); +} + +void ToolConfig::setMenu(int index) +{ + // internally, menu names are stored in English + m_map["menu"] = m_configWidget->m_cbMenu->itemData(index).toString(); +} + +void ToolConfig::writeConfig() +{ + //KILE_DEBUG_MAIN << "==ToolConfig::writeConfig()===================="; + //save config + m_manager->saveEntryMap(m_current, m_map, false, false); + // internally, menu names are stored in English + KileTool::setGUIOptions(m_current, + m_configWidget->m_cbMenu->itemData(m_configWidget->m_cbMenu->currentIndex()).toString(), + m_icon, + m_config); +} + +int ToolConfig::indexQuickBuild() +{ + QList itemsList = m_configWidget->m_lstbTools->findItems("QuickBuild", Qt::MatchExactly); + if(itemsList.isEmpty()) { + return 0; + } + + return m_configWidget->m_lstbTools->row(itemsList.first()); +} + +void ToolConfig::switchConfig(int /*index*/) +{ + //KILE_DEBUG_MAIN << "==ToolConfig::switchConfig(int /*index*/)===================="; + switchTo(m_current); +} + +void ToolConfig::switchConfig(const QString & cfg) +{ + //KILE_DEBUG_MAIN << "==ToolConfig::switchConfig(const QString & cfg)=========="; + for(int i = 0; i < m_configWidget->m_cbConfig->count(); ++i) { + if (m_configWidget->m_cbConfig->itemText(i) == cfg) { + m_configWidget->m_cbConfig->setCurrentIndex(i); + } + } +} + +void ToolConfig::switchTo(const QString & tool, bool save /* = true */) +{ + //KILE_DEBUG_MAIN << "==ToolConfig::switchTo(const QString & tool, bool save /* = true */)===================="; + //save config + if(save) { + writeConfig(); + + //update the config number + QString cf = m_configWidget->m_cbConfig->currentText(); + KileTool::setConfigName(m_current, cf, m_config); + } + + m_current = tool; + + m_map.clear(); + if (!m_manager->retrieveEntryMap(m_current, m_map, false, false)) { + qWarning() << "no entrymap"; + } + + updateConfiglist(); + updateGeneral(); + updateAdvanced(); + + //show GUI info + QString menu = KileTool::menuFor(m_current, m_config); + int i = m_configWidget->m_cbMenu->findData(menu); + if(i >= 0) { + m_configWidget->m_cbMenu->setCurrentIndex(i); + } + else { + m_configWidget->m_cbMenu->addItem(menu, QVariant(menu)); + m_configWidget->m_cbMenu->setCurrentIndex(m_configWidget->m_cbMenu->count() - 1); + } + m_icon = KileTool::iconFor(m_current, m_config); + if(m_icon.isEmpty()) { + m_configWidget->m_pshbIcon->setIcon(QIcon::fromTheme(QString())); + } + else { + m_configWidget->m_pshbIcon->setIcon(QIcon::fromTheme(m_icon)); + } +} + +void ToolConfig::updateConfiglist() +{ + //KILE_DEBUG_MAIN << "==ToolConfig::updateConfiglist()====================="; + m_configWidget->m_groupBox->setTitle(i18n("Choose a configuration for the tool %1",m_current)); + m_configWidget->m_cbConfig->clear(); + m_configWidget->m_cbConfig->addItems(KileTool::configNames(m_current, m_config)); + QString cfg = KileTool::configName(m_current, m_config); + switchConfig(cfg); + m_configWidget->m_cbConfig->setEnabled(m_configWidget->m_cbConfig->count() > 1); +} + +void ToolConfig::selectIcon() +{ + KILE_DEBUG_MAIN << "icon ---> " << m_icon; + //KILE_DEBUG_MAIN << "==ToolConfig::selectIcon()====================="; + KIconDialog *dlg = new KIconDialog(this); + QString res = dlg->openDialog(); + if(m_icon != res) { + if(res.isEmpty()) { + return; + } + + m_icon = res; + writeConfig(); + if (m_icon.isEmpty()) { + m_configWidget->m_pshbIcon->setIcon(QIcon::fromTheme(QString())); + } + else { + m_configWidget->m_pshbIcon->setIcon(QIcon::fromTheme(m_icon)); + } + } +} + +void ToolConfig::newTool() +{ + //KILE_DEBUG_MAIN << "==ToolConfig::newTool()====================="; + NewToolWizard *ntw = new NewToolWizard(this); + if (ntw->exec()) { + QString toolName = ntw->toolName(); + QString parentTool = ntw->parentTool(); + + writeStdConfig(toolName, "Default"); + if(parentTool != ntw->customTool()) { + //copy tool info + KileTool::Config tempMap; + m_manager->retrieveEntryMap(parentTool, tempMap, false, false); + KConfigGroup toolGroup = m_config->group(KileTool::groupFor(toolName, "Default")); + toolGroup.writeEntry("class", tempMap["class"]); + toolGroup.writeEntry("type", tempMap["type"]); + toolGroup.writeEntry("close", tempMap["close"]); + toolGroup.writeEntry("checkForRoot", tempMap["checkForRoot"]); + toolGroup.writeEntry("autoRun", tempMap["autoRun"]); + toolGroup.writeEntry("jumpToFirstError", tempMap["jumpToFirstError"]); + } + + m_configWidget->m_lstbTools->blockSignals(true); + updateToollist(); + switchTo(toolName); + for(int i = 0; i < m_configWidget->m_lstbTools->count(); ++i) { + if(m_configWidget->m_lstbTools->item(i)->text() == toolName) { + m_configWidget->m_lstbTools->setCurrentRow(i); + break; + } + } + m_configWidget->m_lstbTools->blockSignals(false); + } +} + +void ToolConfig::newConfig() +{ + //KILE_DEBUG_MAIN << "==ToolConfig::newConfig()====================="; + writeConfig(); + bool ok; + QString cfg = QInputDialog::getText(this, i18n("New Configuration"), i18n("Enter new configuration name:"), QLineEdit::Normal, "", &ok); + if (ok && (!cfg.isEmpty())) { + //copy config + KConfigGroup toolGroup = m_config->group(KileTool::groupFor(m_current, cfg)); + for (QMap::Iterator it = m_map.begin(); it != m_map.end(); ++it) { + toolGroup.writeEntry(it.key(), it.value()); + } + KileTool::setConfigName(m_current, cfg, m_config); + switchTo(m_current, false); + switchConfig(cfg); + } +} + +void ToolConfig::writeStdConfig(const QString & tool, const QString & cfg) +{ + KConfigGroup toolGroup = m_config->group(KileTool::groupFor(tool, cfg)); + toolGroup.writeEntry("class", "Compile"); + toolGroup.writeEntry("type", "Process"); + toolGroup.writeEntry("menu", "Compile"); + toolGroup.writeEntry("close", "no"); + + m_config->group("Tools").writeEntry(tool, cfg); +} + +void ToolConfig::removeTool() +{ // KILE_DEBUG_MAIN << "==ToolConfig::removeTool()====================="; - if(KMessageBox::warningContinueCancel(this, i18n("Are you sure you want to remove the tool %1?", m_current)) == KMessageBox::Continue) { - QStringList cfgs = KileTool::configNames(m_current, m_config); + if(KMessageBox::warningContinueCancel(this, i18n("Are you sure you want to remove the tool %1?", m_current)) == KMessageBox::Continue) { + QStringList cfgs = KileTool::configNames(m_current, m_config); // KILE_DEBUG_MAIN << "cfgs " << cfgs.join(", "); - for(int i = 0; i < cfgs.count(); ++i) { + for(int i = 0; i < cfgs.count(); ++i) { // KILE_DEBUG_MAIN << "group " << KileTool::groupFor(m_current, cfgs[i]); - m_config->deleteGroup(KileTool::groupFor(m_current, cfgs[i])); - } - m_config->group("Tools").deleteEntry(m_current); - m_config->group("ToolsGUI").deleteEntry(m_current); - m_config->sync(); - - int index = m_configWidget->m_lstbTools->currentRow() - 1; - if(index < 0) { - index = 0; - } - QString tool = m_configWidget->m_lstbTools->item(index)->text(); + m_config->deleteGroup(KileTool::groupFor(m_current, cfgs[i])); + } + m_config->group("Tools").deleteEntry(m_current); + m_config->group("ToolsGUI").deleteEntry(m_current); + m_config->sync(); + + int index = m_configWidget->m_lstbTools->currentRow() - 1; + if(index < 0) { + index = 0; + } + QString tool = m_configWidget->m_lstbTools->item(index)->text(); // KILE_DEBUG_MAIN << "tool is " << tool; - m_configWidget->m_lstbTools->blockSignals(true); - updateToollist(); - m_configWidget->m_lstbTools->setCurrentRow(index); - switchTo(tool, false); - m_configWidget->m_lstbTools->blockSignals(false); - } - } - - void ToolConfig::removeConfig() - { - //KILE_DEBUG_MAIN << "==ToolConfig::removeConfig()====================="; - writeConfig(); - if ( m_configWidget->m_cbConfig->count() > 1) { - if(KMessageBox::warningContinueCancel(this, i18n("Are you sure that you want to remove this configuration?") ) - == KMessageBox::Continue) { - m_config->deleteGroup(KileTool::groupFor(m_current, m_configWidget->m_cbConfig->currentText())); - int currentIndex = m_configWidget->m_cbConfig->currentIndex(); - int newIndex = 0; - if(currentIndex == 0 ) - newIndex = 1; - KileTool::setConfigName(m_current, m_configWidget->m_cbConfig->itemText(newIndex), m_config); - m_config->reparseConfiguration(); // FIXME should be not needed - updateConfiglist(); - switchTo(m_current, false); - } - } - else { - KMessageBox::error(this, i18n("You need at least one configuration for each tool."), i18n("Cannot Remove Configuration")); - } - } - - void ToolConfig::switchClass(const QString & cls) - { - if(m_map["class"] != cls) { - setClass(cls); - emit(changed()); - } - } - - void ToolConfig::switchType(int index) - { - switch (index) { - case 0 : m_map["type"] = "Process"; break; - case 1 : m_map["type"] = "Konsole"; break; - case 2 : m_map["type"] = "DocumentViewer"; break; - case 3 : m_map["type"] = "Sequence"; break; - default : m_map["type"] = "Process"; break; - } - emit(changed()); - } - - void ToolConfig::setCommand(const QString & command) { m_map["command"] = command.trimmed(); } - void ToolConfig::setOptions() { m_map["options"] = m_ptcw->m_options->toPlainText().trimmed(); } - void ToolConfig::setSequence(const QString & sequence) { m_map["sequence"] = sequence.trimmed(); } - void ToolConfig::setClose(bool on) { m_map["close"] = on ? "yes" : "no"; } - void ToolConfig::setTarget(const QString & trg) { m_map["target"] = trg.trimmed(); } - void ToolConfig::setRelDir(const QString & rd) { m_map["relDir"] = rd.trimmed(); } - void ToolConfig::setLaTeXCheckRoot(bool ck) { m_map["checkForRoot"] = ck ? "yes" : "no"; } - void ToolConfig::setLaTeXJump(bool ck) { m_map["jumpToFirstError"] = ck ? "yes" : "no"; } - void ToolConfig::setLaTeXAuto(bool ck) { m_map["autoRun"] = ck ? "yes" : "no"; } - void ToolConfig::setRunLyxServer(bool ck) - { - //KILE_DEBUG_MAIN << "setRunLyxServer"; - m_config->group("Tools").writeEntry("RunLyxServer", ck); - } - void ToolConfig::setFrom(const QString & from) { m_map["from"] = from.trimmed(); } - void ToolConfig::setTo(const QString & to) { m_map["to"] = to.trimmed(); } - void ToolConfig::setClass(const QString & cls) { m_map["class"] = cls.trimmed(); } + m_configWidget->m_lstbTools->blockSignals(true); + updateToollist(); + m_configWidget->m_lstbTools->setCurrentRow(index); + switchTo(tool, false); + m_configWidget->m_lstbTools->blockSignals(false); + } +} + +void ToolConfig::removeConfig() +{ + //KILE_DEBUG_MAIN << "==ToolConfig::removeConfig()====================="; + writeConfig(); + if ( m_configWidget->m_cbConfig->count() > 1) { + if(KMessageBox::warningContinueCancel(this, i18n("Are you sure that you want to remove this configuration?") ) + == KMessageBox::Continue) { + m_config->deleteGroup(KileTool::groupFor(m_current, m_configWidget->m_cbConfig->currentText())); + int currentIndex = m_configWidget->m_cbConfig->currentIndex(); + int newIndex = 0; + if(currentIndex == 0 ) + newIndex = 1; + KileTool::setConfigName(m_current, m_configWidget->m_cbConfig->itemText(newIndex), m_config); + m_config->reparseConfiguration(); // FIXME should be not needed + updateConfiglist(); + switchTo(m_current, false); + } + } + else { + KMessageBox::error(this, i18n("You need at least one configuration for each tool."), i18n("Cannot Remove Configuration")); + } +} + +void ToolConfig::switchClass(const QString & cls) +{ + if(m_map["class"] != cls) { + setClass(cls); + emit(changed()); + } +} + +void ToolConfig::switchType(int index) +{ + switch (index) { + case 0 : + m_map["type"] = "Process"; + break; + case 1 : + m_map["type"] = "Konsole"; + break; + case 2 : + m_map["type"] = "DocumentViewer"; + break; + case 3 : + m_map["type"] = "Sequence"; + break; + default : + m_map["type"] = "Process"; + break; + } + emit(changed()); +} + +void ToolConfig::setCommand(const QString & command) { + m_map["command"] = command.trimmed(); +} +void ToolConfig::setOptions() { + m_map["options"] = m_ptcw->m_options->toPlainText().trimmed(); +} +void ToolConfig::setSequence(const QString & sequence) { + m_map["sequence"] = sequence.trimmed(); +} +void ToolConfig::setClose(bool on) { + m_map["close"] = on ? "yes" : "no"; +} +void ToolConfig::setTarget(const QString & trg) { + m_map["target"] = trg.trimmed(); +} +void ToolConfig::setRelDir(const QString & rd) { + m_map["relDir"] = rd.trimmed(); +} +void ToolConfig::setLaTeXCheckRoot(bool ck) { + m_map["checkForRoot"] = ck ? "yes" : "no"; +} +void ToolConfig::setLaTeXJump(bool ck) { + m_map["jumpToFirstError"] = ck ? "yes" : "no"; +} +void ToolConfig::setLaTeXAuto(bool ck) { + m_map["autoRun"] = ck ? "yes" : "no"; +} +void ToolConfig::setRunLyxServer(bool ck) +{ + //KILE_DEBUG_MAIN << "setRunLyxServer"; + m_config->group("Tools").writeEntry("RunLyxServer", ck); +} +void ToolConfig::setFrom(const QString & from) { + m_map["from"] = from.trimmed(); +} +void ToolConfig::setTo(const QString & to) { + m_map["to"] = to.trimmed(); +} +void ToolConfig::setClass(const QString & cls) { + m_map["class"] = cls.trimmed(); +} } diff --git a/src/widgets/toolconfigwidget.h b/src/widgets/toolconfigwidget.h index 1c042eb0..da2869b1 100644 --- a/src/widgets/toolconfigwidget.h +++ b/src/widgets/toolconfigwidget.h @@ -1,104 +1,106 @@ /*************************************************************************** Begin : Sat 3-1 20:40:00 CEST 2004 Copyright (C) 2004 by Jeroen Wijnhout (Jeroen.Wijnhout@kdemail.net) 2011 - 2017 by Michel Ludwig (michel.ludwig@kdemail.net) ***************************************************************************/ /*************************************************************************** * * * 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. * * * ***************************************************************************/ #ifndef TOOLCONFIGWIDGET_H #define TOOLCONFIGWIDGET_H #include #include #include "kiletool.h" -namespace KileTool { class Manager; } +namespace KileTool { +class Manager; +} class ToolConfigWidget; class ProcessToolConfigWidget; class LibraryToolConfigWidget; class QuickToolConfigWidget; class LaTeXToolConfigWidget; class ViewBibToolConfigWidget; namespace KileWidget { - class ToolConfig : public QWidget - { - Q_OBJECT - - enum GeneralBasicStack { GBS_None = 1, GBS_Process, GBS_Sequence, GBS_Error }; - enum GeneralExtraStack { GES_None = 1, GES_LaTeX/*, GES_ViewBib*/ }; - - public: - ToolConfig(KileTool::Manager *mngr, QWidget *parent, const char * name = 0); - - public Q_SLOTS: - void writeConfig(); - - private: - void setupAdvanced(); - void setupGeneral(); - int indexQuickBuild(); - - private Q_SLOTS: - void updateGeneral(); - void updateAdvanced(); - void switchTo(const QString & tool, bool save = true); - void updateToollist(); - void updateConfiglist(); - void selectIcon(); - void setMenu(int index); - void switchConfig(int index = -1); - void switchConfig(const QString &); - - void newTool(); - void newConfig(); - void removeTool(); - void removeConfig(); - void writeStdConfig(const QString &, const QString &); - void writeDefaults(); - - void setCommand(const QString &); - void setOptions(); - void setSequence(const QString &); - void setClose(bool); - void setTarget(const QString &); - void setRelDir(const QString &); - void setLaTeXCheckRoot(bool); - void setLaTeXJump(bool); - void setLaTeXAuto(bool); - void setRunLyxServer(bool); - void setFrom(const QString &); - void setTo(const QString &); - void setClass(const QString &); - void switchClass(const QString &); - void switchType(int); - - Q_SIGNALS: - void changed(); - - private: - ToolConfigWidget *m_configWidget; - KileTool::Manager *m_manager; - KConfig *m_config; - KileTool::Config m_map; - QString m_current, m_icon; - QStringList m_classes; - QWidget *m_tabGeneral, *m_tabAdvanced, *m_tabMenu; - ProcessToolConfigWidget *m_ptcw; - LibraryToolConfigWidget *m_ltcw; - QuickToolConfigWidget *m_qtcw; - LaTeXToolConfigWidget *m_LaTeXtcw; - }; +class ToolConfig : public QWidget +{ + Q_OBJECT + + enum GeneralBasicStack { GBS_None = 1, GBS_Process, GBS_Sequence, GBS_Error }; + enum GeneralExtraStack { GES_None = 1, GES_LaTeX/*, GES_ViewBib*/ }; + +public: + ToolConfig(KileTool::Manager *mngr, QWidget *parent, const char * name = 0); + +public Q_SLOTS: + void writeConfig(); + +private: + void setupAdvanced(); + void setupGeneral(); + int indexQuickBuild(); + +private Q_SLOTS: + void updateGeneral(); + void updateAdvanced(); + void switchTo(const QString & tool, bool save = true); + void updateToollist(); + void updateConfiglist(); + void selectIcon(); + void setMenu(int index); + void switchConfig(int index = -1); + void switchConfig(const QString &); + + void newTool(); + void newConfig(); + void removeTool(); + void removeConfig(); + void writeStdConfig(const QString &, const QString &); + void writeDefaults(); + + void setCommand(const QString &); + void setOptions(); + void setSequence(const QString &); + void setClose(bool); + void setTarget(const QString &); + void setRelDir(const QString &); + void setLaTeXCheckRoot(bool); + void setLaTeXJump(bool); + void setLaTeXAuto(bool); + void setRunLyxServer(bool); + void setFrom(const QString &); + void setTo(const QString &); + void setClass(const QString &); + void switchClass(const QString &); + void switchType(int); + +Q_SIGNALS: + void changed(); + +private: + ToolConfigWidget *m_configWidget; + KileTool::Manager *m_manager; + KConfig *m_config; + KileTool::Config m_map; + QString m_current, m_icon; + QStringList m_classes; + QWidget *m_tabGeneral, *m_tabAdvanced, *m_tabMenu; + ProcessToolConfigWidget *m_ptcw; + LibraryToolConfigWidget *m_ltcw; + QuickToolConfigWidget *m_qtcw; + LaTeXToolConfigWidget *m_LaTeXtcw; +}; } #endif diff --git a/src/widgets/usermenuconfigwidget.cpp b/src/widgets/usermenuconfigwidget.cpp index b326fa42..0e4085dc 100644 --- a/src/widgets/usermenuconfigwidget.cpp +++ b/src/widgets/usermenuconfigwidget.cpp @@ -1,96 +1,96 @@ /*********************************************************************************** Copyright (C) 2011-2012 by Holger Danielsson (holger.danielsson@versanet.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. * * * ***************************************************************************/ #include #include #include "widgets/usermenuconfigwidget.h" #include "kileconfig.h" #include "kiledebug.h" KileWidgetUsermenuConfig::KileWidgetUsermenuConfig(KileMenu::UserMenu *usermenu, QWidget *parent) - : QWidget(parent), - m_usermenu(usermenu) + : QWidget(parent), + m_usermenu(usermenu) { - Q_ASSERT(m_usermenu); - setupUi(this); - setXmlFile(m_usermenu->xmlFile()); + Q_ASSERT(m_usermenu); + setupUi(this); + setXmlFile(m_usermenu->xmlFile()); - if(KileConfig::userMenuLocation() == KileMenu::UserMenu::StandAloneLocation) { - m_rbStandAloneMenuLocation->setChecked(true); - } - else { - m_rbLaTeXMenuLocation->setChecked(true); - } + if(KileConfig::userMenuLocation() == KileMenu::UserMenu::StandAloneLocation) { + m_rbStandAloneMenuLocation->setChecked(true); + } + else { + m_rbLaTeXMenuLocation->setChecked(true); + } - connect(m_pbInstall, SIGNAL(clicked()), this, SLOT(slotInstallClicked())); - connect(m_pbRemove, SIGNAL(clicked()), this, SLOT(slotRemoveClicked())); + connect(m_pbInstall, SIGNAL(clicked()), this, SLOT(slotInstallClicked())); + connect(m_pbRemove, SIGNAL(clicked()), this, SLOT(slotRemoveClicked())); } KileWidgetUsermenuConfig::~KileWidgetUsermenuConfig() { } void KileWidgetUsermenuConfig::writeConfig() { - const int location = (m_rbStandAloneMenuLocation->isChecked()) - ? KileMenu::UserMenu::StandAloneLocation : KileMenu::UserMenu::LaTeXMenuLocation; - if(KileConfig::userMenuLocation() != location) { - KILE_DEBUG_MAIN << "menu position changed"; - KileConfig::setUserMenuLocation(location); - m_usermenu->updateGUI(); - } + const int location = (m_rbStandAloneMenuLocation->isChecked()) + ? KileMenu::UserMenu::StandAloneLocation : KileMenu::UserMenu::LaTeXMenuLocation; + if(KileConfig::userMenuLocation() != location) { + KILE_DEBUG_MAIN << "menu position changed"; + KileConfig::setUserMenuLocation(location); + m_usermenu->updateGUI(); + } } void KileWidgetUsermenuConfig::slotInstallClicked() { - KILE_DEBUG_MAIN << "install clicked"; - - QString directory = KileMenu::UserMenu::selectUserMenuDir(); - QString filter = i18n("User Menu Files (*.xml)"); - - QString xmlfile = QFileDialog::getOpenFileName(this, i18n("Select Menu File"), directory, filter); - if(xmlfile.isEmpty()) { - return; - } - - if(QFile::exists(xmlfile)) { - m_usermenu->installXmlFile(xmlfile); - setXmlFile(xmlfile); - } - else { - KMessageBox::error(this, i18n("File '%1' does not exist.", xmlfile)); - } + KILE_DEBUG_MAIN << "install clicked"; + + QString directory = KileMenu::UserMenu::selectUserMenuDir(); + QString filter = i18n("User Menu Files (*.xml)"); + + QString xmlfile = QFileDialog::getOpenFileName(this, i18n("Select Menu File"), directory, filter); + if(xmlfile.isEmpty()) { + return; + } + + if(QFile::exists(xmlfile)) { + m_usermenu->installXmlFile(xmlfile); + setXmlFile(xmlfile); + } + else { + KMessageBox::error(this, i18n("File '%1' does not exist.", xmlfile)); + } } void KileWidgetUsermenuConfig::slotRemoveClicked() { - KILE_DEBUG_MAIN << "remove clicked"; + KILE_DEBUG_MAIN << "remove clicked"; - m_usermenu->removeXmlFile(); - setXmlFile(QString()); + m_usermenu->removeXmlFile(); + setXmlFile(QString()); } void KileWidgetUsermenuConfig::setXmlFile(const QString &file) { - if(file.isEmpty()) { - m_usermenuFile->setText(i18n("no file installed")); - m_pbRemove->setEnabled(false); - } - else { - m_usermenuFile->setText(file); - m_pbRemove->setEnabled(true); - } + if(file.isEmpty()) { + m_usermenuFile->setText(i18n("no file installed")); + m_pbRemove->setEnabled(false); + } + else { + m_usermenuFile->setText(file); + m_pbRemove->setEnabled(true); + } } diff --git a/src/widgets/usermenuconfigwidget.h b/src/widgets/usermenuconfigwidget.h index 2a0d8d26..b664e3f3 100644 --- a/src/widgets/usermenuconfigwidget.h +++ b/src/widgets/usermenuconfigwidget.h @@ -1,43 +1,43 @@ /*********************************************************************************** Copyright (C) 2011-2012 by Holger Danielsson (holger.danielsson@versanet.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. * * * ***************************************************************************/ #ifndef USERMENUCONFIGWIDGET_H #define USERMENUCONFIGWIDGET_H #include #include "usermenu/usermenu.h" #include "ui_usermenuconfigwidget.h" class KileWidgetUsermenuConfig : public QWidget, public Ui::KileWidgetUsermenuConfig { - Q_OBJECT + Q_OBJECT - public: - KileWidgetUsermenuConfig(KileMenu::UserMenu *usermenu, QWidget *parent = Q_NULLPTR); - ~KileWidgetUsermenuConfig(); +public: + KileWidgetUsermenuConfig(KileMenu::UserMenu *usermenu, QWidget *parent = Q_NULLPTR); + ~KileWidgetUsermenuConfig(); - void writeConfig(); + void writeConfig(); - private Q_SLOTS: - void slotInstallClicked(); - void slotRemoveClicked(); +private Q_SLOTS: + void slotInstallClicked(); + void slotRemoveClicked(); - private: - KileMenu::UserMenu *m_usermenu; +private: + KileMenu::UserMenu *m_usermenu; - void setXmlFile(const QString &file); + void setXmlFile(const QString &file); }; #endif