diff --git a/src/Application.h b/src/Application.h index 98d44dd2..8da2a9eb 100644 --- a/src/Application.h +++ b/src/Application.h @@ -1,98 +1,98 @@ /* Copyright 2007-2008 by Robert Knight This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #ifndef APPLICATION_H #define APPLICATION_H // Qt #include // Konsole #include "Profile.h" #include "ViewSplitter.h" namespace Konsole { class MainWindow; class Session; /** * The Konsole Application. * * The application consists of one or more main windows and a set of * factories to create new sessions and views. * * To create a new main window with a default terminal session, call * the newInstance(). Empty main windows can be created using newMainWindow(). * * The factory used to create new terminal sessions can be retrieved using * the sessionManager() accessor. */ class Application : public QObject { Q_OBJECT public: /** Constructs a new Konsole application. */ explicit Application(QSharedPointer parser, const QStringList &customCommand); static void populateCommandLineParser(QCommandLineParser *parser); static QStringList getCustomCommand(QStringList &args); - ~Application() Q_DECL_OVERRIDE; + ~Application() override; /** Creates a new main window and opens a default terminal session */ int newInstance(); /** * Creates a new, empty main window and connects to its newSessionRequest() * and newWindowRequest() signals to trigger creation of new sessions or * windows when then they are emitted. */ MainWindow *newMainWindow(); private Q_SLOTS: void createWindow(const Profile::Ptr &profile, const QString &directory); void detachTerminals(ViewSplitter *splitter, const QHash& sessionsMap); void toggleBackgroundInstance(); public Q_SLOTS: void slotActivateRequested(QStringList args, const QString &workingDir); private: Q_DISABLE_COPY(Application) void listAvailableProfiles(); void listProfilePropertyInfo(); void startBackgroundMode(MainWindow *window); bool processHelpArgs(); MainWindow *processWindowArgs(bool &createdNewMainWindow); Profile::Ptr processProfileSelectArgs(); Profile::Ptr processProfileChangeArgs(Profile::Ptr baseProfile); bool processTabsFromFileArgs(MainWindow *window); void createTabFromArgs(MainWindow *window, const QHash &); void finalizeNewMainWindow(MainWindow *window); MainWindow *_backgroundInstance; QSharedPointer m_parser; QStringList m_customCommand; }; } #endif // APPLICATION_H diff --git a/src/BookmarkHandler.h b/src/BookmarkHandler.h index 7be535ed..5485771f 100644 --- a/src/BookmarkHandler.h +++ b/src/BookmarkHandler.h @@ -1,127 +1,127 @@ /* This file was part of the KDE libraries Copyright 2002 Carsten Pfeiffer Copyright 2007-2008 Robert Knight library 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, version 2 or (at your option) any later version. This library 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 Library 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. */ // Born as kdelibs/kio/kfile/kfilebookmarkhandler.h #ifndef BOOKMARKHANDLER_H #define BOOKMARKHANDLER_H // KDE #include // Konsole #include "konsoleprivate_export.h" class QMenu; class QUrl; class KActionCollection; namespace Konsole { class ViewProperties; /** * This class handles the communication between the bookmark menu and the active session, * providing a suggested title and URL when the user clicks the "Add Bookmark" item in * the bookmarks menu. * * The bookmark handler is associated with a session controller, which is used to * determine the working URL of the current session. When the user changes the active * view, the bookmark handler's controller should be changed using setController() * * When the user selects a bookmark, the openUrl() signal is emitted. */ class KONSOLEPRIVATE_EXPORT BookmarkHandler : public QObject, public KBookmarkOwner { Q_OBJECT public: /** * Constructs a new bookmark handler for Konsole bookmarks. * * @param collection The collection which the bookmark menu's actions should be added to * @param menu The menu which the bookmark actions should be added to * @param toplevel TODO: Document me * @param parent The parent object */ BookmarkHandler(KActionCollection *collection, QMenu *menu, bool toplevel, QObject *parent); - ~BookmarkHandler() Q_DECL_OVERRIDE; + ~BookmarkHandler() override; - QUrl currentUrl() const Q_DECL_OVERRIDE; - QString currentTitle() const Q_DECL_OVERRIDE; - QString currentIcon() const Q_DECL_OVERRIDE; - bool enableOption(BookmarkOption option) const Q_DECL_OVERRIDE; - void openFolderinTabs(const KBookmarkGroup &group) Q_DECL_OVERRIDE; + QUrl currentUrl() const override; + QString currentTitle() const override; + QString currentIcon() const override; + bool enableOption(BookmarkOption option) const override; + void openFolderinTabs(const KBookmarkGroup &group) override; /** * Returns the menu which this bookmark handler inserts its actions into. */ QMenu *menu() const { return _menu; } QList views() const; ViewProperties *activeView() const; public Q_SLOTS: /** * */ void setViews(const QList &views); void setActiveView(ViewProperties *view); Q_SIGNALS: /** * Emitted when the user selects a bookmark from the bookmark menu. * * @param url The url of the bookmark which was selected by the user. */ void openUrl(const QUrl &url); /** * Emitted when the user selects 'Open Folder in Tabs' * from the bookmark menu. * * @param urls The urls of the bookmarks in the folder whose * 'Open Folder in Tabs' action was triggered */ void openUrls(const QList &urls); private Q_SLOTS: - void openBookmark(const KBookmark &bm, Qt::MouseButtons, Qt::KeyboardModifiers) Q_DECL_OVERRIDE; + void openBookmark(const KBookmark &bm, Qt::MouseButtons, Qt::KeyboardModifiers) override; private: Q_DISABLE_COPY(BookmarkHandler) QString titleForView(ViewProperties *view) const; QUrl urlForView(ViewProperties *view) const; QString iconForView(ViewProperties *view) const; QMenu *_menu; QString _file; bool _toplevel; ViewProperties *_activeView; QList _views; }; } #endif // BOOKMARKHANDLER_H diff --git a/src/ColorSchemeEditor.h b/src/ColorSchemeEditor.h index 459aba3f..7a281405 100644 --- a/src/ColorSchemeEditor.h +++ b/src/ColorSchemeEditor.h @@ -1,99 +1,99 @@ /* Copyright 2007-2008 by Robert Knight This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #ifndef COLORSCHEMEEDITOR_H #define COLORSCHEMEEDITOR_H // Qt #include // KDE #include // Konsole #include "Profile.h" class QTableWidgetItem; namespace Ui { class ColorSchemeEditor; } namespace Konsole { class ColorScheme; /** * A dialog for editing color schemes. * * After creation, the dialog can be initialized with the settings * of a color scheme using the setup() method. * * The dialog creates a copy of the supplied color scheme to which * any changes made are applied. The modified color scheme * can be retrieved using the colorScheme() method. * * When changes are made the colorsChanged() signal is emitted. */ class KONSOLEPRIVATE_EXPORT ColorSchemeEditor : public QDialog { Q_OBJECT public: /** Constructs a new color scheme editor with the specified parent. */ explicit ColorSchemeEditor(QWidget *parent = nullptr); - ~ColorSchemeEditor() Q_DECL_OVERRIDE; + ~ColorSchemeEditor() override; /** Initializes the dialog with the properties of the specified color scheme. */ void setup(const ColorScheme *scheme, bool isNewScheme); /** Returns the modified color scheme. */ ColorScheme &colorScheme() const; bool isNewScheme() const; Q_SIGNALS: /** Emitted when the colors in the color scheme change. */ void colorsChanged(ColorScheme *scheme); /** Used to send back colorscheme changes into the profile edited */ void colorSchemeSaveRequested(const ColorScheme &scheme, bool isNewScheme); public Q_SLOTS: /** Sets the text displayed in the description edit field. */ void setDescription(const QString &description); private Q_SLOTS: void setTransparencyPercentLabel(int percent); void setBlur(bool blur); void setRandomizedBackgroundColor(bool randomized); void editColorItem(QTableWidgetItem *item); void wallpaperPathChanged(const QString &path); void selectWallpaper(); /** Triggered by apply/ok buttons */ void saveColorScheme(); private: Q_DISABLE_COPY(ColorSchemeEditor) void setupColorTable(const ColorScheme *table); bool _isNewScheme; Ui::ColorSchemeEditor *_ui; ColorScheme *_colors; }; } #endif // COLORSCHEMEEDITOR_H diff --git a/src/CopyInputDialog.h b/src/CopyInputDialog.h index f4dee6cb..0777decc 100644 --- a/src/CopyInputDialog.h +++ b/src/CopyInputDialog.h @@ -1,139 +1,139 @@ /* Copyright 2008 by Robert Knight This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #ifndef COPYINPUTDIALOG_H #define COPYINPUTDIALOG_H // Qt #include #include // KDE #include // Konsole #include "SessionManager.h" #include "Session.h" #include "SessionListModel.h" namespace Ui { class CopyInputDialog; } namespace Konsole { class CheckableSessionModel; /** * Dialog which allows the user to mark a list of sessions to copy * the input from the current session to. The current session is * set using setMasterSession(). After the dialog has been executed, * the set of chosen sessions can be retrieved using chosenSessions() */ class CopyInputDialog : public QDialog { Q_OBJECT public: explicit CopyInputDialog(QWidget *parent = nullptr); - ~CopyInputDialog() Q_DECL_OVERRIDE; + ~CopyInputDialog() override; /** * Sets the 'source' session whose input will be copied to * other sessions. This session is displayed grayed out in the list * and cannot be unchecked. */ void setMasterSession(Session *session); /** See setMasterSession() */ Session *masterSession() const; /** Sets the sessions in the list which are checked. */ void setChosenSessions(const QSet &sessions); /** Set setChosenSessions() */ QSet chosenSessions() const; private Q_SLOTS: void selectAll() { setSelectionChecked(true); } void deselectAll() { setSelectionChecked(false); } private: Q_DISABLE_COPY(CopyInputDialog) // Checks or unchecks selected sessions. If there are no // selected items then all sessions are checked or unchecked void setSelectionChecked(bool checked); void setRowChecked(int row, bool checked); Ui::CopyInputDialog *_ui; CheckableSessionModel *_model; QPointer _masterSession; }; /** * A list of sessions with a checkbox next to each one which allows the * user to select a subset of the available sessions to perform * some action on them. */ class CheckableSessionModel : public SessionListModel { Q_OBJECT public: explicit CheckableSessionModel(QObject *parent); void setCheckColumn(int column); int checkColumn() const; /** * Sets whether a session can be checked or un-checked. * Non-checkable items have the Qt::ItemIsEnabled flag unset. */ void setCheckable(Session *session, bool checkable); /** Sets the list of sessions which are currently checked. */ void setCheckedSessions(const QSet &sessions); /** Returns the set of checked sessions. */ QSet checkedSessions() const; // reimplemented from QAbstractItemModel - Qt::ItemFlags flags(const QModelIndex &index) const Q_DECL_OVERRIDE; - QVariant data(const QModelIndex &index, int role) const Q_DECL_OVERRIDE; - bool setData(const QModelIndex &index, const QVariant &value, int role) Q_DECL_OVERRIDE; + Qt::ItemFlags flags(const QModelIndex &index) const override; + QVariant data(const QModelIndex &index, int role) const override; + bool setData(const QModelIndex &index, const QVariant &value, int role) override; protected: - void sessionRemoved(Session *) Q_DECL_OVERRIDE; + void sessionRemoved(Session *) override; private: QSet _checkedSessions; QSet _fixedSessions; int _checkColumn; }; inline int CheckableSessionModel::checkColumn() const { return _checkColumn; } } #endif // COPYINPUTDIALOG_H diff --git a/src/EditProfileDialog.h b/src/EditProfileDialog.h index d9e9b6e8..f20727f8 100644 --- a/src/EditProfileDialog.h +++ b/src/EditProfileDialog.h @@ -1,471 +1,471 @@ /* Copyright 2007-2008 by Robert Knight Copyright 2018 by Harald Sitter This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #ifndef EDITPROFILEDIALOG_H #define EDITPROFILEDIALOG_H // Qt #include #include #include #include #include // KDE #include #include // Konsole #include "Profile.h" #include "Enumeration.h" #include "ColorScheme.h" #include "ColorSchemeEditor.h" #include "KeyboardTranslatorManager.h" #include "FontDialog.h" class KPluralHandlingSpinBox; class KLocalizedString; class QItemSelectionModel; namespace Ui { class EditProfileGeneralPage; class EditProfileTabsPage; class EditProfileAppearancePage; class EditProfileScrollingPage; class EditProfileKeyboardPage; class EditProfileMousePage; class EditProfileAdvancedPage; } namespace Konsole { /** * A dialog which allows the user to edit a profile. * After the dialog is created, it can be initialized with the settings * for a profile using setProfile(). When the user makes changes to the * dialog and accepts the changes, the dialog will update the * profile in the SessionManager by calling the SessionManager's * changeProfile() method. * * Some changes made in the dialog are preview-only changes which cause * the SessionManager's changeProfile() method to be called with * the persistent argument set to false. These changes are then * un-done when the dialog is closed. */ class KONSOLEPRIVATE_EXPORT EditProfileDialog: public KPageDialog { Q_OBJECT public: /** Constructs a new dialog with the specified parent. */ explicit EditProfileDialog(QWidget *parent = nullptr); - ~EditProfileDialog() Q_DECL_OVERRIDE; + ~EditProfileDialog() override; /** * Initializes the dialog with the settings for the specified session * type. * * When the dialog closes, the profile will be updated in the SessionManager * with the altered settings. * * @param profile The profile to be edited */ void setProfile(const Profile::Ptr &profile); /** * Selects the text in the profile name edit area. * When the dialog is being used to create a new profile, * this can be used to draw the user's attention to the profile name * and make it easy for them to change it. */ void selectProfileName(); const Profile::Ptr lookupProfile() const; public Q_SLOTS: // reimplemented - void accept() Q_DECL_OVERRIDE; + void accept() override; // reimplemented - void reject() Q_DECL_OVERRIDE; + void reject() override; void apply(); protected: - bool eventFilter(QObject *watched, QEvent *event) Q_DECL_OVERRIDE; + bool eventFilter(QObject *watched, QEvent *event) override; private Q_SLOTS: QSize sizeHint() const override; // sets up the specified tab page if necessary void preparePage(KPageWidgetItem *current, KPageWidgetItem *before = nullptr); // saves changes to profile void save(); // general page void selectInitialDir(); void selectIcon(); void profileNameChanged(const QString &name); void initialDirChanged(const QString &dir); void startInSameDir(bool); void commandChanged(const QString &command); void tabTitleFormatChanged(const QString &format); void remoteTabTitleFormatChanged(const QString &format); void terminalColumnsEntryChanged(int); void terminalRowsEntryChanged(int); void showTerminalSizeHint(bool); void setDimWhenInactive(bool); void showEnvironmentEditor(); void silenceSecondsChanged(int); // appearance page void setAntialiasText(bool enable); void setBoldIntense(bool enable); void useFontLineCharacters(bool enable); void newColorScheme(); void editColorScheme(); void saveColorScheme(const ColorScheme &scheme, bool isNewScheme); void removeColorScheme(); void gotNewColorSchemes(const KNS3::Entry::List &changedEntries); void toggleBlinkingCursor(bool); void setCursorShape(int); void autoCursorColor(); void customCursorColor(); void customCursorColorChanged(const QColor &); void terminalMarginChanged(int margin); void lineSpacingChanged(int); void setTerminalCenter(bool enable); /** * Deletes the selected colorscheme from the user's home dir location * so that the original one from the system-wide location can be used * instead */ void resetColorScheme(); void colorSchemeSelected(); void previewColorScheme(const QModelIndex &index); void showFontDialog(); void toggleMouseWheelZoom(bool enable); // scrolling page void historyModeChanged(Enum::HistoryModeEnum mode); void historySizeChanged(int); void scrollFullPage(); void scrollHalfPage(); // keyboard page void editKeyBinding(); void newKeyBinding(); void keyBindingSelected(); void removeKeyBinding(); void resetKeyBindings(); // mouse page void toggleUnderlineFiles(bool enable); void toggleUnderlineLinks(bool); void toggleOpenLinksByDirectClick(bool); void toggleCtrlRequiredForDrag(bool); void toggleDropUrlsAsText(bool); void toggleCopyTextToClipboard(bool); void toggleCopyTextAsHTML(bool); void toggleTrimLeadingSpacesInSelectedText(bool); void toggleTrimTrailingSpacesInSelectedText(bool); void pasteFromX11Selection(); void pasteFromClipboard(); void toggleAlternateScrolling(bool enable); void TripleClickModeChanged(int); void wordCharactersChanged(const QString &); // advanced page void toggleBlinkingText(bool); void toggleFlowControl(bool); void togglebidiRendering(bool); void updateUrlHintsModifier(bool); void toggleReverseUrlHints(bool); void setDefaultCodec(QTextCodec *); // apply the first previewed changes stored up by delayedPreview() void delayedPreviewActivate(); private: Q_DISABLE_COPY(EditProfileDialog) enum PageID { GeneralPage = 0, TabsPage, AppearancePage, ScrollingPage, KeyboardPage, MousePage, AdvancedPage, PagesCount }; // initialize various pages of the dialog void setupGeneralPage(const Profile::Ptr &profile); void setupTabsPage(const Profile::Ptr &profile); void setupAppearancePage(const Profile::Ptr &profile); void setupKeyboardPage(const Profile::Ptr &profile); void setupScrollingPage(const Profile::Ptr &profile); void setupAdvancedPage(const Profile::Ptr &profile); void setupMousePage(const Profile::Ptr &profile); int maxSpinBoxWidth(const KPluralHandlingSpinBox *spinBox, const KLocalizedString &suffix); // Returns the name of the colorScheme used in the current profile const QString currentColorSchemeName() const; // select @p selectedColorSchemeName after the changes are saved // in the colorScheme editor void updateColorSchemeList(const QString &selectedColorSchemeName = QString()); void updateColorSchemeButtons(); // Convenience method KeyboardTranslatorManager *_keyManager = KeyboardTranslatorManager::instance(); // Updates the key bindings list widget on the Keyboard tab and selects // @p selectKeyBindingsName void updateKeyBindingsList(const QString &selectKeyBindingsName = QString()); void updateKeyBindingsButtons(); void showKeyBindingEditor(bool isNewTranslator); void showColorSchemeEditor(bool isNewScheme); void closeColorSchemeEditor(); void preview(int property, const QVariant &value); void delayedPreview(int property, const QVariant &value); void unpreview(int property); void unpreviewAll(); void enableIfNonEmptySelection(QWidget *widget, QItemSelectionModel *selectionModel); void updateCaption(const Profile::Ptr &profile); void updateTransparencyWarning(); void updateFontPreview(QFont font); // Update _tempProfile in a way of respecting the apply button. // When used with some previewed property, this method should // always come after the preview operation. void updateTempProfileProperty(Profile::Property, const QVariant &value); // helper method for creating an empty & hidden profile and assigning // it to _tempProfile. void createTempProfile(); // Enable or disable apply button, used only within // updateTempProfileProperty(). void updateButtonApply(); static QString groupProfileNames(const ProfileGroup::Ptr &group, int maxLength = -1); struct RadioOption { QAbstractButton *button; int value; const char *slot; }; void setupRadio(const QVector& possibilities, int actual); struct BooleanOption { QAbstractButton *button; Profile::Property property; const char *slot; }; void setupCheckBoxes(const QVector& options, const Profile::Ptr &profile); struct ButtonGroupOption { QAbstractButton *button; int value; }; struct ButtonGroupOptions { QButtonGroup *group; Profile::Property profileProperty; bool preview; QVector buttons; }; void setupButtonGroup(const ButtonGroupOptions &options, const Profile::Ptr &profile); // returns false if: // - the profile name is empty // - the name matches the name of an already existing profile // - the existing profile config file is read-only // otherwise returns true. bool isValidProfileName(); Ui::EditProfileGeneralPage *_generalUi; Ui::EditProfileTabsPage *_tabsUi; Ui::EditProfileAppearancePage *_appearanceUi; Ui::EditProfileScrollingPage *_scrollingUi; Ui::EditProfileKeyboardPage *_keyboardUi; Ui::EditProfileMousePage *_mouseUi; Ui::EditProfileAdvancedPage *_advancedUi; using PageSetupMethod = void (EditProfileDialog::*)(const Profile::Ptr &); struct Page { Page(PageSetupMethod page = nullptr, bool update = false) : setupPage(page) , needsUpdate(update) {} PageSetupMethod setupPage; bool needsUpdate; }; QMap _pages; Profile::Ptr _tempProfile; Profile::Ptr _profile; QHash _previewedProperties; QHash _delayedPreviewProperties; QTimer *_delayedPreviewTimer; ColorSchemeEditor *_colorDialog; QDialogButtonBox *_buttonBox; FontDialog *_fontDialog; }; /** * A delegate which can display and edit color schemes in a view. */ class ColorSchemeViewDelegate : public QAbstractItemDelegate { Q_OBJECT public: explicit ColorSchemeViewDelegate(QObject *parent = nullptr); // reimplemented void paint(QPainter *painter, const QStyleOptionViewItem &option, - const QModelIndex &index) const Q_DECL_OVERRIDE; + const QModelIndex &index) const override; QSize sizeHint(const QStyleOptionViewItem &option, - const QModelIndex &index) const Q_DECL_OVERRIDE; + const QModelIndex &index) const override; }; /** * An utility class for aligning 0th column in multiple QGridLayouts. * * Limitations: * - a layout can't be nested in another layout * - reference widget must be an ancestor of all added layouts * - only 0th column is processed (widgets spanning multiple columns * are ignored) */ class LabelsAligner: public QObject { Q_OBJECT public: explicit LabelsAligner(QWidget *refWidget): _refWidget(refWidget) {} void addLayout(QGridLayout *layout) { _layouts.append(layout); } void addLayouts(const QVector &layouts) { _layouts.append(layouts); } void setReferenceWidget(QWidget *refWidget) { _refWidget = refWidget; } public Q_SLOTS: void updateLayouts() { for (const auto *layout: qAsConst(_layouts)) { QWidget *widget = layout->parentWidget(); Q_ASSERT(widget); do { QLayout *widgetLayout = widget->layout(); if (widgetLayout != nullptr) { widgetLayout->update(); widgetLayout->activate(); } widget = widget->parentWidget(); } while (widget != _refWidget && widget != nullptr); } } void align() { Q_ASSERT(_refWidget); if (_layouts.count() <= 1) { return; } int maxRight = 0; for (const auto *layout: qAsConst(_layouts)) { int left = getLeftMargin(layout); for (int row = 0; row < layout->rowCount(); ++row) { QLayoutItem *layoutItem = layout->itemAtPosition(row, LABELS_COLUMN); if (layoutItem == nullptr) { continue; } QWidget *widget = layoutItem->widget(); if (widget == nullptr) { continue; } const int idx = layout->indexOf(widget); int rows, cols, rowSpan, colSpan; layout->getItemPosition(idx, &rows, &cols, &rowSpan, &colSpan); if (colSpan > 1) { continue; } const int right = left + widget->sizeHint().width(); if (maxRight < right) { maxRight = right; } } } for (auto *l: qAsConst(_layouts)) { int left = getLeftMargin(l); l->setColumnMinimumWidth(LABELS_COLUMN, maxRight - left); } } private: int getLeftMargin(const QGridLayout *layout) { int left = layout->contentsMargins().left(); if (layout->parent()->isWidgetType()) { auto *parentWidget = layout->parentWidget(); Q_ASSERT(parentWidget); left += parentWidget->contentsMargins().left(); } else { auto *parentLayout = qobject_cast(layout->parent()); Q_ASSERT(parentLayout); left += parentLayout->contentsMargins().left(); } QWidget *parent = layout->parentWidget(); while (parent != _refWidget && parent != nullptr) { left = parent->mapToParent(QPoint(left, 0)).x(); parent = parent->parentWidget(); } return left; } static constexpr int LABELS_COLUMN = 0; QWidget *_refWidget; QVector _layouts; }; } #endif // EDITPROFILEDIALOG_H diff --git a/src/Emulation.h b/src/Emulation.h index a89d627b..cf99447c 100644 --- a/src/Emulation.h +++ b/src/Emulation.h @@ -1,525 +1,525 @@ /* This file is part of Konsole, an X terminal. Copyright 2007-2008 by Robert Knight Copyright 1997,1998 by Lars Doelle This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #ifndef EMULATION_H #define EMULATION_H // Qt #include #include #include // Konsole #include "Enumeration.h" #include "konsoleprivate_export.h" class QKeyEvent; namespace Konsole { class KeyboardTranslator; class HistoryType; class Screen; class ScreenWindow; class TerminalCharacterDecoder; /** * This enum describes the available states which * the terminal emulation may be set to. * * These are the values used by Emulation::stateChanged() */ enum { /** The emulation is currently receiving user input. */ NOTIFYNORMAL = 0, /** * The terminal program has triggered a bell event * to get the user's attention. */ NOTIFYBELL = 1, /** * The emulation is currently receiving data from its * terminal input. */ NOTIFYACTIVITY = 2, // unused here? NOTIFYSILENCE = 3 }; /** * Base class for terminal emulation back-ends. * * The back-end is responsible for decoding an incoming character stream and * producing an output image of characters. * * When input from the terminal is received, the receiveData() slot should be called with * the data which has arrived. The emulation will process the data and update the * screen image accordingly. The codec used to decode the incoming character stream * into the unicode characters used internally can be specified using setCodec() * * The size of the screen image can be specified by calling setImageSize() with the * desired number of lines and columns. When new lines are added, old content * is moved into a history store, which can be set by calling setHistory(). * * The screen image can be accessed by creating a ScreenWindow onto this emulation * by calling createWindow(). Screen windows provide access to a section of the * output. Each screen window covers the same number of lines and columns as the * image size returned by imageSize(). The screen window can be moved up and down * and provides transparent access to both the current on-screen image and the * previous output. The screen windows emit an outputChanged signal * when the section of the image they are looking at changes. * Graphical views can then render the contents of a screen window, listening for notifications * of output changes from the screen window which they are associated with and updating * accordingly. * * The emulation also is also responsible for converting input from the connected views such * as keypresses and mouse activity into a character string which can be sent * to the terminal program. Key presses can be processed by calling the sendKeyEvent() slot, * while mouse events can be processed using the sendMouseEvent() slot. When the character * stream has been produced, the emulation will emit a sendData() signal with a pointer * to the character buffer. This data should be fed to the standard input of the terminal * process. The translation of key presses into an output character stream is performed * using a lookup in a set of key bindings which map key sequences to output * character sequences. The name of the key bindings set used can be specified using * setKeyBindings() * * The emulation maintains certain state information which changes depending on the * input received. The emulation can be reset back to its starting state by calling * reset(). * * The emulation also maintains an activity state, which specifies whether * terminal is currently active ( when data is received ), normal * ( when the terminal is idle or receiving user input ) or trying * to alert the user ( also known as a "Bell" event ). The stateSet() signal * is emitted whenever the activity state is set. This can be used to determine * how long the emulation has been active/idle for and also respond to * a 'bell' event in different ways. */ class KONSOLEPRIVATE_EXPORT Emulation : public QObject { Q_OBJECT public: /** Constructs a new terminal emulation */ Emulation(); - ~Emulation() Q_DECL_OVERRIDE; + ~Emulation() override; /** * Creates a new window onto the output from this emulation. The contents * of the window are then rendered by views which are set to use this window using the * TerminalDisplay::setScreenWindow() method. */ ScreenWindow *createWindow(); /** Returns the size of the screen image which the emulation produces */ QSize imageSize() const; /** * Returns the total number of lines, including those stored in the history. */ int lineCount() const; /** * Sets the history store used by this emulation. When new lines * are added to the output, older lines at the top of the screen are transferred to a history * store. * * The number of lines which are kept and the storage location depend on the * type of store. */ void setHistory(const HistoryType &); /** Returns the history store used by this emulation. See setHistory() */ const HistoryType &history() const; /** Clears the history scroll. */ void clearHistory(); /** * Copies the output history from @p startLine to @p endLine * into @p stream, using @p decoder to convert the terminal * characters into text. * * @param decoder A decoder which converts lines of terminal characters with * appearance attributes into output text. PlainTextDecoder is the most commonly * used decoder. * @param startLine Index of first line to copy * @param endLine Index of last line to copy */ virtual void writeToStream(TerminalCharacterDecoder *decoder, int startLine, int endLine); /** Returns the codec used to decode incoming characters. See setCodec() */ const QTextCodec *codec() const { return _codec; } /** Sets the codec used to decode incoming characters. */ void setCodec(const QTextCodec *); /** * Convenience method. * Returns true if the current codec used to decode incoming * characters is UTF-8 */ bool utf8() const { Q_ASSERT(_codec); return _codec->mibEnum() == 106; } /** Returns the special character used for erasing character. */ virtual char eraseChar() const; /** * Sets the key bindings used to key events * ( received through sendKeyEvent() ) into character * streams to send to the terminal. */ void setKeyBindings(const QString &name); /** * Returns the name of the emulation's current key bindings. * See setKeyBindings() */ QString keyBindings() const; /** * Copies the current image into the history and clears the screen. */ virtual void clearEntireScreen() = 0; /** Resets the state of the terminal. */ virtual void reset() = 0; /** * Returns true if the active terminal program is interested in Mouse * Tracking events. * * The programRequestsMouseTracking() signal is emitted when a program * indicates it's interested in Mouse Tracking events. * * See MODE_Mouse100{0,1,2,3} in Vt102Emulation. */ bool programUsesMouseTracking() const; bool programBracketedPasteMode() const; public Q_SLOTS: /** Change the size of the emulation's image */ virtual void setImageSize(int lines, int columns); /** * Interprets a sequence of characters and sends the result to the terminal. * This is equivalent to calling sendKeyEvent() for each character in @p text in succession. */ virtual void sendText(const QString &text) = 0; /** * Interprets a key press event and emits the sendData() signal with * the resulting character stream. */ virtual void sendKeyEvent(QKeyEvent *); /** * Converts information about a mouse event into an xterm-compatible escape * sequence and emits the character sequence via sendData() */ virtual void sendMouseEvent(int buttons, int column, int line, int eventType); /** * Sends a string of characters to the foreground terminal process. * * @param string The characters to send. */ virtual void sendString(const QByteArray &string) = 0; /** * Processes an incoming stream of characters. receiveData() decodes the incoming * character buffer using the current codec(), and then calls receiveChar() for * each unicode character in the resulting buffer. * * receiveData() also starts a timer which causes the outputChanged() signal * to be emitted when it expires. The timer allows multiple updates in quick * succession to be buffered into a single outputChanged() signal emission. * * @param text A string of characters received from the terminal program. * @param length The length of @p text */ void receiveData(const char *text, int length); /** * Sends information about the focus lost event to the terminal. */ virtual void focusLost() = 0; /** * Sends information about the focus gained event to the terminal. */ virtual void focusGained() = 0; Q_SIGNALS: /** * Emitted when a buffer of data is ready to send to the * standard input of the terminal. * * @param data The buffer of data ready to be sent */ void sendData(const QByteArray &data); /** * Requests that the pty used by the terminal process * be set to UTF 8 mode. * * Refer to the IUTF8 entry in termios(3) for more information. */ void useUtf8Request(bool); /** * Emitted when the activity state of the emulation is set. * * @param state The new activity state, one of NOTIFYNORMAL, NOTIFYACTIVITY * or NOTIFYBELL */ void stateSet(int state); /** * Emitted when the special sequence indicating the request for data * transmission through ZModem protocol is detected. */ void zmodemDownloadDetected(); void zmodemUploadDetected(); /** * Requests that the color of the text used * to represent the tabs associated with this * emulation be changed. This is a Konsole-specific * extension from pre-KDE 4 times. * * TODO: Document how the parameter works. */ void changeTabTextColorRequest(int color); /** * This is emitted when the program (typically editors and other full-screen * applications, ones that take up the whole terminal display), running in * the terminal indicates whether or not it is interested in Mouse Tracking * events. This is an XTerm extension, for more information have a look at: * https://invisible-island.net/xterm/ctlseqs/ctlseqs.html#h2-Mouse-Tracking * * @param usesMouseTracking This will be true if the program is interested * in Mouse Tracking events or false otherwise. */ void programRequestsMouseTracking(bool usesMouseTracking); void enableAlternateScrolling(bool enable); void programBracketedPasteModeChanged(bool bracketedPasteMode); /** * Emitted when the contents of the screen image change. * The emulation buffers the updates from successive image changes, * and only emits outputChanged() at sensible intervals when * there is a lot of terminal activity. * * Normally there is no need for objects other than the screen windows * created with createWindow() to listen for this signal. * * ScreenWindow objects created using createWindow() will emit their * own outputChanged() signal in response to this signal. */ void outputChanged(); /** * Emitted when the program running in the terminal wishes to update * certain session attributes. This allows terminal programs to customize * certain aspects of the terminal emulation display. * * This signal is emitted when the escape sequence "\033]ARG;VALUE\007" * is received in an input string, where ARG is a number specifying * what should be changed and VALUE is a string specifying the new value. * * @param attribute Specifies which session attribute to change: *
    *
  • 0 - Set window icon text and session title to @p newValue
  • *
  • 1 - Set window icon text to @p newValue
  • *
  • 2 - Set session title to @p newValue
  • *
  • 11 - Set the session's default background color to @p newValue, * where @p newValue can be an HTML-style string ("#RRGGBB") or a * named color (e.g. 'red', 'blue'). For more details see: * https://doc.qt.io/qt-5/qcolor.html#setNamedColor *
  • *
  • 31 - Supposedly treats @p newValue as a URL and opens it (NOT * IMPLEMENTED) *
  • *
  • 32 - Sets the icon associated with the session. @p newValue * is the name of the icon to use, which can be the name of any * icon in the current KDE icon theme (eg: 'konsole', 'kate', * 'folder_home') *
  • *
* @param newValue Specifies the new value of the session attribute */ void sessionAttributeChanged(int attribute, const QString &newValue); /** * Emitted when the terminal emulator's size has changed */ void imageSizeChanged(int lineCount, int columnCount); /** * Emitted when the setImageSize() is called on this emulation for * the first time. */ void imageSizeInitialized(); /** * Emitted after receiving the escape sequence which asks to change * the terminal emulator's size */ void imageResizeRequest(const QSize &sizz); /** * Emitted when the terminal program requests to change various properties * of the terminal display. * * A profile change command occurs when a special escape sequence, followed * by a string containing a series of name and value pairs is received. * This string can be parsed using a ProfileCommandParser instance. * * @param text A string expected to contain a series of key and value pairs in * the form: name=value;name2=value2 ... */ void profileChangeCommandReceived(const QString &text); /** * Emitted when a flow control key combination ( Ctrl+S or Ctrl+Q ) is pressed. * @param suspendKeyPressed True if Ctrl+S was pressed to suspend output or Ctrl+Q to * resume output. */ void flowControlKeyPressed(bool suspendKeyPressed); /** * Emitted when the active screen is switched, to indicate whether the primary * screen is in use. */ void primaryScreenInUse(bool use); /** * Emitted when the text selection is changed */ void selectionChanged(const QString &text); /** * Emitted when terminal code requiring terminal's response received. */ void sessionAttributeRequest(int id); /** * Emitted when Set Cursor Style (DECSCUSR) escape sequences are sent * to the terminal. * @p shape cursor shape * @p isBlinking if true, the cursor will be set to blink */ void setCursorStyleRequest(Enum::CursorShapeEnum shape = Enum::BlockCursor, bool isBlinking = false); /** * Emitted when reset() is called to reset the cursor style to the * current profile cursor shape and blinking settings. */ void resetCursorStyleRequest(); protected: virtual void setMode(int mode) = 0; virtual void resetMode(int mode) = 0; /** * Processes an incoming character. See receiveData() * @p c A unicode character code. */ virtual void receiveChar(uint c); /** * Sets the active screen. The terminal has two screens, primary and alternate. * The primary screen is used by default. When certain interactive programs such * as Vim are run, they trigger a switch to the alternate screen. * * @param index 0 to switch to the primary screen, or 1 to switch to the alternate screen */ void setScreen(int index); enum EmulationCodec { LocaleCodec = 0, Utf8Codec = 1 }; void setCodec(EmulationCodec codec); QList _windows; Screen *_currentScreen; // pointer to the screen which is currently active, // this is one of the elements in the screen[] array Screen *_screen[2]; // 0 = primary screen ( used by most programs, including the shell // scrollbars are enabled in this mode ) // 1 = alternate ( used by vi , emacs etc. // scrollbars are not enabled in this mode ) //decodes an incoming C-style character stream into a unicode QString using //the current text codec. (this allows for rendering of non-ASCII characters in text files etc.) const QTextCodec *_codec; QTextDecoder *_decoder; const KeyboardTranslator *_keyTranslator; // the keyboard layout protected Q_SLOTS: /** * Schedules an update of attached views. * Repeated calls to bufferedUpdate() in close succession will result in only a single update, * much like the Qt buffered update of widgets. */ void bufferedUpdate(); // used to emit the primaryScreenInUse(bool) signal void checkScreenInUse(); // used to emit the selectionChanged(QString) signal void checkSelectedText(); private Q_SLOTS: // triggered by timer, causes the emulation to send an updated screen image to each // view void showBulk(); void setUsesMouseTracking(bool usesMouseTracking); void bracketedPasteModeChanged(bool bracketedPasteMode); private: Q_DISABLE_COPY(Emulation) bool _usesMouseTracking; bool _bracketedPasteMode; QTimer _bulkTimer1; QTimer _bulkTimer2; bool _imageSizeInitialized; }; } #endif // ifndef EMULATION_H diff --git a/src/Filter.h b/src/Filter.h index 8f7272e5..20de7f69 100644 --- a/src/Filter.h +++ b/src/Filter.h @@ -1,413 +1,413 @@ /* Copyright 2007-2008 by Robert Knight This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #ifndef FILTER_H #define FILTER_H // Qt #include #include #include #include #include #include #include // Konsole #include "Character.h" class QAction; namespace Konsole { class Session; /** * A filter processes blocks of text looking for certain patterns (such as URLs or keywords from a list) * and marks the areas which match the filter's patterns as 'hotspots'. * * Each hotspot has a type identifier associated with it ( such as a link or a highlighted section ), * and an action. When the user performs some activity such as a mouse-click in a hotspot area ( the exact * action will depend on what is displaying the block of text which the filter is processing ), the hotspot's * activate() method should be called. Depending on the type of hotspot this will trigger a suitable response. * * For example, if a hotspot represents a URL then a suitable action would be opening that URL in a web browser. * Hotspots may have more than one action, in which case the list of actions can be obtained using the * actions() method. * * Different subclasses of filter will return different types of hotspot. * Subclasses must reimplement the process() method to examine a block of text and identify sections of interest. * When processing the text they should create instances of Filter::HotSpot subclasses for sections of interest * and add them to the filter's list of hotspots using addHotSpot() */ class Filter { public: /** * Represents an area of text which matched the pattern a particular filter has been looking for. * * Each hotspot has a type identifier associated with it ( such as a link or a highlighted section ), * and an action. When the user performs some activity such as a mouse-click in a hotspot area ( the exact * action will depend on what is displaying the block of text which the filter is processing ), the hotspot's * activate() method should be called. Depending on the type of hotspot this will trigger a suitable response. * * For example, if a hotspot represents a URL then a suitable action would be opening that URL in a web browser. * Hotspots may have more than one action, in which case the list of actions can be obtained using the * actions() method. These actions may then be displayed in a popup menu or toolbar for example. */ class HotSpot { public: /** * Constructs a new hotspot which covers the area from (@p startLine,@p startColumn) to (@p endLine,@p endColumn) * in a block of text. */ HotSpot(int startLine, int startColumn, int endLine, int endColumn); virtual ~HotSpot(); enum Type { // the type of the hotspot is not specified NotSpecified, // this hotspot represents a clickable link Link, // this hotspot represents a marker Marker }; /** Returns the line when the hotspot area starts */ int startLine() const; /** Returns the line where the hotspot area ends */ int endLine() const; /** Returns the column on startLine() where the hotspot area starts */ int startColumn() const; /** Returns the column on endLine() where the hotspot area ends */ int endColumn() const; /** * Returns the type of the hotspot. This is usually used as a hint for views on how to represent * the hotspot graphically. eg. Link hotspots are typically underlined when the user mouses over them */ Type type() const; /** * Causes the action associated with a hotspot to be triggered. * * @param object The object which caused the hotspot to be triggered. This is * typically null ( in which case the default action should be performed ) or * one of the objects from the actions() list. In which case the associated * action should be performed. */ virtual void activate(QObject *object = nullptr) = 0; /** * Returns a list of actions associated with the hotspot which can be used in a * menu or toolbar */ virtual QList actions(); protected: /** Sets the type of a hotspot. This should only be set once */ void setType(Type type); private: int _startLine; int _startColumn; int _endLine; int _endColumn; Type _type; }; /** Constructs a new filter. */ Filter(); virtual ~Filter(); /** Causes the filter to process the block of text currently in its internal buffer */ virtual void process() = 0; /** * Empties the filters internal buffer and resets the line count back to 0. * All hotspots are deleted. */ void reset(); /** Returns the hotspot which covers the given @p line and @p column, or 0 if no hotspot covers that area */ HotSpot *hotSpotAt(int line, int column) const; /** Returns the list of hotspots identified by the filter */ QList hotSpots() const; /** Returns the list of hotspots identified by the filter which occur on a given line */ /** * TODO: Document me */ void setBuffer(const QString *buffer, const QList *linePositions); protected: /** Adds a new hotspot to the list */ void addHotSpot(HotSpot *); /** Returns the internal buffer */ const QString *buffer(); /** Converts a character position within buffer() to a line and column */ void getLineColumn(int position, int &startLine, int &startColumn); private: Q_DISABLE_COPY(Filter) QMultiHash _hotspots; QList _hotspotList; const QList *_linePositions; const QString *_buffer; }; /** * A filter which searches for sections of text matching a regular expression and creates a new RegExpFilter::HotSpot * instance for them. * * Subclasses can reimplement newHotSpot() to return custom hotspot types when matches for the regular expression * are found. */ class RegExpFilter : public Filter { public: /** * Type of hotspot created by RegExpFilter. The capturedTexts() method can be used to find the text * matched by the filter's regular expression. */ class HotSpot : public Filter::HotSpot { public: HotSpot(int startLine, int startColumn, int endLine, int endColumn, const QStringList &capturedTexts); - void activate(QObject *object = nullptr) Q_DECL_OVERRIDE; + void activate(QObject *object = nullptr) override; /** Returns the texts found by the filter when matching the filter's regular expression */ QStringList capturedTexts() const; private: QStringList _capturedTexts; }; /** Constructs a new regular expression filter */ RegExpFilter(); /** * Sets the regular expression which the filter searches for in blocks of text. * * Regular expressions which match the empty string are treated as not matching * anything. */ void setRegExp(const QRegularExpression ®Exp); /** Returns the regular expression which the filter searches for in blocks of text */ QRegularExpression regExp() const; /** * Reimplemented to search the filter's text buffer for text matching regExp() * * If regexp matches the empty string, then process() will return immediately * without finding results. */ - void process() Q_DECL_OVERRIDE; + void process() override; protected: /** * Called when a match for the regular expression is encountered. Subclasses should reimplement this * to return custom hotspot types */ virtual RegExpFilter::HotSpot *newHotSpot(int startLine, int startColumn, int endLine, int endColumn, const QStringList &capturedTexts); private: QRegularExpression _searchText; }; class FilterObject; /** A filter which matches URLs in blocks of text */ class UrlFilter : public RegExpFilter { public: /** * Hotspot type created by UrlFilter instances. The activate() method opens a web browser * at the given URL when called. */ class HotSpot : public RegExpFilter::HotSpot { public: HotSpot(int startLine, int startColumn, int endLine, int endColumn, const QStringList &capturedTexts); - ~HotSpot() Q_DECL_OVERRIDE; + ~HotSpot() override; - QList actions() Q_DECL_OVERRIDE; + QList actions() override; /** * Open a web browser at the current URL. The url itself can be determined using * the capturedTexts() method. */ - void activate(QObject *object = nullptr) Q_DECL_OVERRIDE; + void activate(QObject *object = nullptr) override; private: enum UrlType { StandardUrl, Email, Unknown }; UrlType urlType() const; FilterObject *_urlObject; }; UrlFilter(); protected: - RegExpFilter::HotSpot *newHotSpot(int, int, int, int, const QStringList &) Q_DECL_OVERRIDE; + RegExpFilter::HotSpot *newHotSpot(int, int, int, int, const QStringList &) override; private: static const QRegularExpression FullUrlRegExp; static const QRegularExpression EmailAddressRegExp; // combined OR of FullUrlRegExp and EmailAddressRegExp static const QRegularExpression CompleteUrlRegExp; }; /** * A filter which matches files according to POSIX Portable Filename Character Set * https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap03.html#tag_03_267 */ class FileFilter : public RegExpFilter { public: /** * Hotspot type created by FileFilter instances. */ class HotSpot : public RegExpFilter::HotSpot { public: HotSpot(int startLine, int startColumn, int endLine, int endColumn, const QStringList &capturedTexts, const QString &filePath); - ~HotSpot() Q_DECL_OVERRIDE; + ~HotSpot() override; - QList actions() Q_DECL_OVERRIDE; + QList actions() override; /** * Opens kate for editing the file. */ - void activate(QObject *object = nullptr) Q_DECL_OVERRIDE; + void activate(QObject *object = nullptr) override; private: FilterObject *_fileObject; QString _filePath; }; explicit FileFilter(Session *session); - void process() Q_DECL_OVERRIDE; + void process() override; protected: - RegExpFilter::HotSpot *newHotSpot(int, int, int, int, const QStringList &) Q_DECL_OVERRIDE; + RegExpFilter::HotSpot *newHotSpot(int, int, int, int, const QStringList &) override; private: QPointer _session; QString _dirPath; QSet _currentFiles; }; class FilterObject : public QObject { Q_OBJECT public: explicit FilterObject(Filter::HotSpot *filter) : _filter(filter) { } public Q_SLOTS: void activated(); private: Q_DISABLE_COPY(FilterObject) Filter::HotSpot *_filter; }; /** * A chain which allows a group of filters to be processed as one. * The chain owns the filters added to it and deletes them when the chain itself is destroyed. * * Use addFilter() to add a new filter to the chain. * When new text to be filtered arrives, use addLine() to add each additional * line of text which needs to be processed and then after adding the last line, use * process() to cause each filter in the chain to process the text. * * After processing a block of text, the reset() method can be used to set the filter chain's * internal cursor back to the first line. * * The hotSpotAt() method will return the first hotspot which covers a given position. * * The hotSpots() method return all of the hotspots in the text and on * a given line respectively. */ class FilterChain : protected QList { public: virtual ~FilterChain(); /** Adds a new filter to the chain. The chain will delete this filter when it is destroyed */ void addFilter(Filter *filter); /** Removes a filter from the chain. The chain will no longer delete the filter when destroyed */ void removeFilter(Filter *filter); /** Removes all filters from the chain */ void clear(); /** Resets each filter in the chain */ void reset(); /** * Processes each filter in the chain */ void process(); /** Sets the buffer for each filter in the chain to process. */ void setBuffer(const QString *buffer, const QList *linePositions); /** Returns the first hotspot which occurs at @p line, @p column or 0 if no hotspot was found */ Filter::HotSpot *hotSpotAt(int line, int column) const; /** Returns a list of all the hotspots in all the chain's filters */ QList hotSpots() const; }; /** A filter chain which processes character images from terminal displays */ class TerminalImageFilterChain : public FilterChain { public: TerminalImageFilterChain(); - ~TerminalImageFilterChain() Q_DECL_OVERRIDE; + ~TerminalImageFilterChain() override; /** * Set the current terminal image to @p image. * * @param image The terminal image * @param lines The number of lines in the terminal image * @param columns The number of columns in the terminal image * @param lineProperties The line properties to set for image */ void setImage(const Character * const image, int lines, int columns, const QVector &lineProperties); private: Q_DISABLE_COPY(TerminalImageFilterChain) QString *_buffer; QList *_linePositions; }; } #endif //FILTER_H diff --git a/src/History.h b/src/History.h index d89297d4..e22ce73e 100644 --- a/src/History.h +++ b/src/History.h @@ -1,410 +1,410 @@ /* This file is part of Konsole, an X terminal. Copyright 1997,1998 by Lars Doelle This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #ifndef HISTORY_H #define HISTORY_H // System #include // Qt #include #include #include #include "konsoleprivate_export.h" // Konsole #include "Character.h" namespace Konsole { /* An extendable tmpfile(1) based buffer. */ class HistoryFile { public: HistoryFile(); virtual ~HistoryFile(); virtual void add(const char *buffer, qint64 count); virtual void get(char *buffer, qint64 size, qint64 loc); virtual qint64 len() const; //mmaps the file in read-only mode void map(); //un-mmaps the file void unmap(); private: qint64 _length; QTemporaryFile _tmpFile; //pointer to start of mmap'ed file data, or 0 if the file is not mmap'ed uchar *_fileMap; //incremented whenever 'add' is called and decremented whenever //'get' is called. //this is used to detect when a large number of lines are being read and processed from the history //and automatically mmap the file for better performance (saves the overhead of many lseek-read calls). int _readWriteBalance; //when _readWriteBalance goes below this threshold, the file will be mmap'ed automatically static const int MAP_THRESHOLD = -1000; }; ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// // Abstract base class for file and buffer versions ////////////////////////////////////////////////////////////////////// class HistoryType; class KONSOLEPRIVATE_EXPORT HistoryScroll { public: explicit HistoryScroll(HistoryType *); virtual ~HistoryScroll(); virtual bool hasScroll(); // access to history virtual int getLines() = 0; virtual int getLineLen(int lineno) = 0; virtual void getCells(int lineno, int colno, int count, Character res[]) = 0; virtual bool isWrappedLine(int lineNumber) = 0; // adding lines. virtual void addCells(const Character a[], int count) = 0; // convenience method - this is virtual so that subclasses can take advantage // of QVector's implicit copying virtual void addCellsVector(const QVector &cells) { addCells(cells.data(), cells.size()); } virtual void addLine(bool previousWrapped = false) = 0; // // FIXME: Passing around constant references to HistoryType instances // is very unsafe, because those references will no longer // be valid if the history scroll is deleted. // const HistoryType &getType() const { return *_historyType; } protected: HistoryType *_historyType; }; ////////////////////////////////////////////////////////////////////// // File-based history (e.g. file log, no limitation in length) ////////////////////////////////////////////////////////////////////// class KONSOLEPRIVATE_EXPORT HistoryScrollFile : public HistoryScroll { public: explicit HistoryScrollFile(); - ~HistoryScrollFile() Q_DECL_OVERRIDE; + ~HistoryScrollFile() override; - int getLines() Q_DECL_OVERRIDE; - int getLineLen(int lineno) Q_DECL_OVERRIDE; - void getCells(int lineno, int colno, int count, Character res[]) Q_DECL_OVERRIDE; - bool isWrappedLine(int lineno) Q_DECL_OVERRIDE; + int getLines() override; + int getLineLen(int lineno) override; + void getCells(int lineno, int colno, int count, Character res[]) override; + bool isWrappedLine(int lineno) override; - void addCells(const Character text[], int count) Q_DECL_OVERRIDE; - void addLine(bool previousWrapped = false) Q_DECL_OVERRIDE; + void addCells(const Character text[], int count) override; + void addLine(bool previousWrapped = false) override; private: qint64 startOfLine(int lineno); HistoryFile _index; // lines Row(qint64) HistoryFile _cells; // text Row(Character) HistoryFile _lineflags; // flags Row(unsigned char) }; ////////////////////////////////////////////////////////////////////// // Nothing-based history (no history :-) ////////////////////////////////////////////////////////////////////// class KONSOLEPRIVATE_EXPORT HistoryScrollNone : public HistoryScroll { public: HistoryScrollNone(); - ~HistoryScrollNone() Q_DECL_OVERRIDE; + ~HistoryScrollNone() override; - bool hasScroll() Q_DECL_OVERRIDE; + bool hasScroll() override; - int getLines() Q_DECL_OVERRIDE; - int getLineLen(int lineno) Q_DECL_OVERRIDE; - void getCells(int lineno, int colno, int count, Character res[]) Q_DECL_OVERRIDE; - bool isWrappedLine(int lineno) Q_DECL_OVERRIDE; + int getLines() override; + int getLineLen(int lineno) override; + void getCells(int lineno, int colno, int count, Character res[]) override; + bool isWrappedLine(int lineno) override; - void addCells(const Character a[], int count) Q_DECL_OVERRIDE; - void addLine(bool previousWrapped = false) Q_DECL_OVERRIDE; + void addCells(const Character a[], int count) override; + void addLine(bool previousWrapped = false) override; }; ////////////////////////////////////////////////////////////////////// // History using compact storage // This implementation uses a list of fixed-sized blocks // where history lines are allocated in (avoids heap fragmentation) ////////////////////////////////////////////////////////////////////// typedef QVector TextLine; class CharacterFormat { public: bool equalsFormat(const CharacterFormat &other) const { return (other.rendition & ~RE_EXTENDED_CHAR) == (rendition & ~RE_EXTENDED_CHAR) && other.fgColor == fgColor && other.bgColor == bgColor; } bool equalsFormat(const Character &c) const { return (c.rendition & ~RE_EXTENDED_CHAR) == (rendition & ~RE_EXTENDED_CHAR) && c.foregroundColor == fgColor && c.backgroundColor == bgColor; } void setFormat(const Character &c) { rendition = c.rendition; fgColor = c.foregroundColor; bgColor = c.backgroundColor; isRealCharacter = c.isRealCharacter; } CharacterColor fgColor, bgColor; quint16 startPos; RenditionFlags rendition; bool isRealCharacter; }; class CompactHistoryBlock { public: CompactHistoryBlock() : _blockLength(4096 * 64), // 256kb _head(static_cast(mmap(nullptr, _blockLength, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON, -1, 0))), _tail(nullptr), _blockStart(nullptr), _allocCount(0) { Q_ASSERT(_head != MAP_FAILED); _tail = _blockStart = _head; } virtual ~CompactHistoryBlock() { //free(_blockStart); munmap(_blockStart, _blockLength); } virtual unsigned int remaining() { return _blockStart + _blockLength - _tail; } virtual unsigned length() { return _blockLength; } virtual void *allocate(size_t size); virtual bool contains(void *addr) { return addr >= _blockStart && addr < (_blockStart + _blockLength); } virtual void deallocate(); virtual bool isInUse() { return _allocCount != 0; } private: size_t _blockLength; quint8 *_head; quint8 *_tail; quint8 *_blockStart; int _allocCount; }; class CompactHistoryBlockList { public: CompactHistoryBlockList() : list(QList()) { } ~CompactHistoryBlockList(); void *allocate(size_t size); void deallocate(void *); int length() { return list.size(); } private: QList list; }; class CompactHistoryLine { public: CompactHistoryLine(const TextLine &, CompactHistoryBlockList &blockList); virtual ~CompactHistoryLine(); // custom new operator to allocate memory from custom pool instead of heap static void *operator new(size_t size, CompactHistoryBlockList &blockList); static void operator delete(void *) { /* do nothing, deallocation from pool is done in destructor*/ } virtual void getCharacters(Character *array, int size, int startColumn); virtual void getCharacter(int index, Character &r); virtual bool isWrapped() const { return _wrapped; } virtual void setWrapped(bool value) { _wrapped = value; } virtual unsigned int getLength() const { return _length; } protected: CompactHistoryBlockList &_blockListRef; CharacterFormat *_formatArray; quint16 _length; uint *_text; quint16 _formatLength; bool _wrapped; }; class KONSOLEPRIVATE_EXPORT CompactHistoryScroll : public HistoryScroll { typedef QList HistoryArray; public: explicit CompactHistoryScroll(unsigned int maxLineCount = 1000); - ~CompactHistoryScroll() Q_DECL_OVERRIDE; + ~CompactHistoryScroll() override; - int getLines() Q_DECL_OVERRIDE; - int getLineLen(int lineNumber) Q_DECL_OVERRIDE; - void getCells(int lineNumber, int startColumn, int count, Character buffer[]) Q_DECL_OVERRIDE; - bool isWrappedLine(int lineNumber) Q_DECL_OVERRIDE; + int getLines() override; + int getLineLen(int lineNumber) override; + void getCells(int lineNumber, int startColumn, int count, Character buffer[]) override; + bool isWrappedLine(int lineNumber) override; - void addCells(const Character a[], int count) Q_DECL_OVERRIDE; - void addCellsVector(const TextLine &cells) Q_DECL_OVERRIDE; - void addLine(bool previousWrapped = false) Q_DECL_OVERRIDE; + void addCells(const Character a[], int count) override; + void addCellsVector(const TextLine &cells) override; + void addLine(bool previousWrapped = false) override; void setMaxNbLines(unsigned int lineCount); private: bool hasDifferentColors(const TextLine &line) const; HistoryArray _lines; CompactHistoryBlockList _blockList; unsigned int _maxLineCount; }; ////////////////////////////////////////////////////////////////////// // History type ////////////////////////////////////////////////////////////////////// class KONSOLEPRIVATE_EXPORT HistoryType { public: HistoryType(); virtual ~HistoryType(); /** * Returns true if the history is enabled ( can store lines of output ) * or false otherwise. */ virtual bool isEnabled() const = 0; /** * Returns the maximum number of lines which this history type * can store or -1 if the history can store an unlimited number of lines. */ virtual int maximumLineCount() const = 0; /** * Converts from one type of HistoryScroll to another or if given the * same type, returns it. */ virtual HistoryScroll *scroll(HistoryScroll *) const = 0; /** * Returns true if the history size is unlimited. */ bool isUnlimited() const { return maximumLineCount() == -1; } }; class KONSOLEPRIVATE_EXPORT HistoryTypeNone : public HistoryType { public: HistoryTypeNone(); - bool isEnabled() const Q_DECL_OVERRIDE; - int maximumLineCount() const Q_DECL_OVERRIDE; + bool isEnabled() const override; + int maximumLineCount() const override; - HistoryScroll *scroll(HistoryScroll *) const Q_DECL_OVERRIDE; + HistoryScroll *scroll(HistoryScroll *) const override; }; class KONSOLEPRIVATE_EXPORT HistoryTypeFile : public HistoryType { public: explicit HistoryTypeFile(); - bool isEnabled() const Q_DECL_OVERRIDE; - int maximumLineCount() const Q_DECL_OVERRIDE; + bool isEnabled() const override; + int maximumLineCount() const override; - HistoryScroll *scroll(HistoryScroll *) const Q_DECL_OVERRIDE; + HistoryScroll *scroll(HistoryScroll *) const override; }; class KONSOLEPRIVATE_EXPORT CompactHistoryType : public HistoryType { public: explicit CompactHistoryType(unsigned int nbLines); - bool isEnabled() const Q_DECL_OVERRIDE; - int maximumLineCount() const Q_DECL_OVERRIDE; + bool isEnabled() const override; + int maximumLineCount() const override; - HistoryScroll *scroll(HistoryScroll *) const Q_DECL_OVERRIDE; + HistoryScroll *scroll(HistoryScroll *) const override; protected: unsigned int _maxLines; }; } #endif // HISTORY_H diff --git a/src/HistorySizeDialog.h b/src/HistorySizeDialog.h index 8750cb45..4b9799a8 100644 --- a/src/HistorySizeDialog.h +++ b/src/HistorySizeDialog.h @@ -1,62 +1,62 @@ /* Copyright 2007-2008 by Robert Knight Copyright 2012 by Kurt Hindenburg This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #ifndef HISTORYSIZEDIALOG_H #define HISTORYSIZEDIALOG_H // KDE #include // Konsole #include "Enumeration.h" namespace Ui { class HistorySizeDialog; } namespace Konsole { class HistorySizeDialog : public QDialog { Q_OBJECT public: explicit HistorySizeDialog(QWidget *parent = nullptr); - ~HistorySizeDialog() Q_DECL_OVERRIDE; + ~HistorySizeDialog() override; /** See HistorySizeWidget::setMode. */ void setMode(Enum::HistoryModeEnum aMode); /** See HistorySizeWidget::mode. */ Enum::HistoryModeEnum mode() const; /** See HistorySizeWidget::setLineCount. */ void setLineCount(int lines); /** See HistorySizeWidget::lineCount. */ int lineCount() const; QSize sizeHint() const override; private: Ui::HistorySizeDialog *_ui; }; } #endif // HISTORYSIZEDIALOG_H diff --git a/src/HistorySizeWidget.h b/src/HistorySizeWidget.h index 66515263..b14abd17 100644 --- a/src/HistorySizeWidget.h +++ b/src/HistorySizeWidget.h @@ -1,88 +1,88 @@ /* Copyright 2007-2008 by Robert Knight Copyright 2012 by Jekyll Wu This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #ifndef HISTORYSIZEWIDGET_H #define HISTORYSIZEWIDGET_H // Qt #include // Konsole #include "Enumeration.h" class QAbstractButton; namespace Ui { class HistorySizeWidget; } namespace Konsole { /** * A widget for controlling history related options */ class HistorySizeWidget : public QWidget { Q_OBJECT public: explicit HistorySizeWidget(QWidget *parent); - ~HistorySizeWidget() Q_DECL_OVERRIDE; + ~HistorySizeWidget() override; /** Specifies the history mode. */ void setMode(Enum::HistoryModeEnum aMode); /** Returns the history mode chosen by the user. */ Enum::HistoryModeEnum mode() const; /** Sets the number of lines for the fixed size history mode. */ void setLineCount(int lines); /** * Returns the number of lines of history to remember. * This is only valid when mode() == FixedSizeHistory, * and returns 0 otherwise. */ int lineCount() const; /** * Return height which should be set on the widget's label * to align with the first widget's item */ int preferredLabelHeight(); Q_SIGNALS: /** Emitted when the history mode is changed. */ void historyModeChanged(Enum::HistoryModeEnum); /** Emitted when the history size is changed. */ void historySizeChanged(int); private Q_SLOTS: void buttonClicked(QAbstractButton *); private: Ui::HistorySizeWidget *_ui; // 1000 lines was the default in the KDE3 series static const int DefaultLineCount = 1000; }; } #endif // HISTORYSIZEWIDGET_H diff --git a/src/IncrementalSearchBar.h b/src/IncrementalSearchBar.h index b6606e92..a5559547 100644 --- a/src/IncrementalSearchBar.h +++ b/src/IncrementalSearchBar.h @@ -1,162 +1,162 @@ /* Copyright 2006-2008 by Robert Knight This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #ifndef INCREMENTALSEARCHBAR_H #define INCREMENTALSEARCHBAR_H // Qt #include #include class QAction; class QTimer; class QLineEdit; class QToolButton; namespace Konsole { /** * A widget which allows users to search incrementally through a document for a * a text string or regular expression. * * The widget consists of a text box into which the user can enter their search text and * buttons to trigger a search for the next and previous matches for the search text. * * When the search text is changed, the searchChanged() signal is emitted. A search through * the document for the new text should begin immediately and the active view of the document * should jump to display any matches if found. setFoundMatch() should be called whenever the * search text changes to indicate whether a match for the text was found in the document. * * findNextClicked() and findPreviousClicked() signals are emitted when the user presses buttons * to find next and previous matches respectively. * * The first indicates whether searches are case sensitive. * The matchCaseToggled() signal is emitted when this is changed. * The second indicates whether the search text should be treated as a plain string or * as a regular expression. * The matchRegExpToggled() signal is emitted when this is changed. */ class IncrementalSearchBar : public QWidget { Q_OBJECT public: /** * This enum defines the options that can be checked. */ enum SearchOptions { /** Highlight all matches */ HighlightMatches = 0, /** Searches are case-sensitive or not */ MatchCase = 1, /** Searches use regular expressions */ RegExp = 2, /** Search from the bottom and up **/ ReverseSearch = 3 }; /** * Constructs a new incremental search bar with the given parent widget */ explicit IncrementalSearchBar(QWidget *parent = nullptr); /* Returns search options that are checked */ const QBitArray optionsChecked(); /** * Sets an indicator for the user as to whether or not a match for the * current search text was found in the document. * * The indicator will not be shown if the search text is empty ( because * the user has not yet entered a query ). * * @param match True if a match was found or false otherwise. If true, * and the search text is non-empty, an indicator that no matches were * found will be shown. */ void setFoundMatch(bool match); /** Returns the current search text */ QString searchText(); void setSearchText(const QString &text); void focusLineEdit(); void setOptions(); // reimplemented - void setVisible(bool visible) Q_DECL_OVERRIDE; + void setVisible(bool visible) override; Q_SIGNALS: /** Emitted when the text entered in the search box is altered */ void searchChanged(const QString &text); /** Emitted when the user clicks the button to find the next match */ void findNextClicked(); /** Emitted when the user clicks the button to find the previous match */ void findPreviousClicked(); /** The search from beginning/end button */ void searchFromClicked(); /** * Emitted when the user toggles the checkbox to indicate whether * matches for the search text should be highlighted */ void highlightMatchesToggled(bool); /** * Emitted when the user toggles the checkbox to indicate whether * matching for the search text should be case sensitive */ void matchCaseToggled(bool); /** * Emitted when the user toggles the checkbox to indicate whether * the search text should be treated as a plain string or a regular expression */ void matchRegExpToggled(bool); /** Emitted when the close button is clicked */ void closeClicked(); /** Emitted when the return button is pressed in the search box */ void searchReturnPressed(const QString &text); /** Emitted when shift+return buttons are pressed in the search box */ void searchShiftPlusReturnPressed(); /** A movement key not handled is forwarded to the terminal display */ void unhandledMovementKeyPressed(QKeyEvent *event); protected: - bool eventFilter(QObject *watched, QEvent *event) Q_DECL_OVERRIDE; - void keyPressEvent(QKeyEvent *event) Q_DECL_OVERRIDE; + bool eventFilter(QObject *watched, QEvent *event) override; + void keyPressEvent(QKeyEvent *event) override; public Q_SLOTS: void clearLineEdit(); private Q_SLOTS: void notifySearchChanged(); void updateButtonsAccordingToReverseSearchSetting(); private: Q_DISABLE_COPY(IncrementalSearchBar) QLineEdit *_searchEdit; QAction *_caseSensitive; QAction *_regExpression; QAction *_highlightMatches; QAction *_reverseSearch; QToolButton *_findNextButton; QToolButton *_findPreviousButton; QToolButton *_searchFromButton; QTimer *_searchTimer; }; } #endif // INCREMENTALSEARCHBAR_H diff --git a/src/KeyBindingEditor.h b/src/KeyBindingEditor.h index a27b28c3..dadceb34 100644 --- a/src/KeyBindingEditor.h +++ b/src/KeyBindingEditor.h @@ -1,149 +1,149 @@ /* Copyright 2007-2008 by Robert Knight This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #ifndef KEYBINDINGEDITOR_H #define KEYBINDINGEDITOR_H // Qt #include // Konsole #include "Profile.h" class QTableWidgetItem; namespace Ui { class KeyBindingEditor; } namespace Konsole { class KeyboardTranslator; /** * A dialog which allows the user to edit a key bindings scheme * which maps between key combinations input by the user and * the character sequence sent to the terminal when those * combinations are pressed. * * The dialog can be initialized with the settings of an * existing key bindings scheme using the setup() method. * * The dialog creates a copy of the supplied keyboard translator * to which any changes are applied. The modified translator * can be retrieved using the translator() method. */ class KeyBindingEditor : public QDialog { Q_OBJECT public: /** Constructs a new key bindings editor with the specified parent. */ explicit KeyBindingEditor(QWidget *parent = nullptr); - ~KeyBindingEditor() Q_DECL_OVERRIDE; + ~KeyBindingEditor() override; /** * Initializes the dialog with the bindings and other settings * from the specified @p translator. * @p currentProfileTranslator the name of the translator set in the * current profile * @p isNewTranslator specifies whether the translator being edited * is an already existing one or a newly created * one, defaults to false. */ void setup(const KeyboardTranslator *translator, const QString ¤tProfileTranslator, bool isNewTranslator = false); /** * Returns the modified translator describing the changes to the bindings * and other settings which the user made. */ KeyboardTranslator *translator() const; /** * Sets the text of the editor's description field. */ void setDescription(const QString &description); /** * Returns the text of the editor's description field. */ QString description() const; // reimplemented to handle test area input - bool eventFilter(QObject *watched, QEvent *event) Q_DECL_OVERRIDE; + bool eventFilter(QObject *watched, QEvent *event) override; Q_SIGNALS: /** * Emitted when the user clicks the OK button to save the changes. This * signal is connected to EditProfileDialog::updateKeyBindingsList() * to update the key bindings list on the Keyboard tab in the Edit * Profile dialog. * @p translatorName is the translator that has just been edited */ void updateKeyBindingsListRequest(const QString &translatorName); /** * Emitted when the user clicks the OK button to save the changes to * the translator that's set in the current profile; this signal is * connected to EditProfileDialog::updateTempProfileProperty() to * request applying the changes to the _tempProfile. * @p newTranslatorName is the name of the translator, that has just * been edited/saved, and which is also the translator * set in the current Profile */ void updateTempProfileKeyBindingsRequest(Profile::Property, const QString &newTranslatorName); private Q_SLOTS: // reimplemented - void accept() Q_DECL_OVERRIDE; + void accept() override; void setTranslatorDescription(const QString &description); void bindingTableItemChanged(QTableWidgetItem *item); void removeSelectedEntry(); void addNewEntry(); private: Q_DISABLE_COPY(KeyBindingEditor) void setupKeyBindingTable(const KeyboardTranslator *translator); Ui::KeyBindingEditor *_ui; // translator to which modifications are made as the user makes // changes in the UI. // this is initialized as a copy of the translator specified // when setup() is called KeyboardTranslator *_translator; // Show only the rows that match the text entered by the user in the // filter search box void filterRows(const QString &text); bool _isNewTranslator; // The translator set in the current profile QString _currentProfileTranslator; // Sets the size hint of the dialog to be slightly smaller than the // size of EditProfileDialog - QSize sizeHint() const Q_DECL_OVERRIDE; + QSize sizeHint() const override; }; } #endif //KEYBINDINGEDITOR_H diff --git a/src/MainWindow.h b/src/MainWindow.h index 89958fc0..f296d41e 100644 --- a/src/MainWindow.h +++ b/src/MainWindow.h @@ -1,204 +1,204 @@ /* Copyright 2006-2008 by Robert Knight This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #ifndef MAINWINDOW_H #define MAINWINDOW_H // Qt #include #include // KDE #include // Konsole #include "Profile.h" #include "ViewSplitter.h" class QAction; class KActionMenu; class KToggleAction; namespace Konsole { class ViewManager; class ViewProperties; class Session; class SessionController; class ProfileList; class BookmarkHandler; /** * The main window. This contains the menus and an area which contains the terminal displays. * * The main window does not create the views or the container widgets which hold the views. * This is done by the ViewManager class. When a MainWindow is instantiated, it creates * a new ViewManager. The ViewManager can then be used to create new terminal displays * inside the window. * * Do not construct new main windows directly, use Application's newMainWindow() method. */ class MainWindow : public KXmlGuiWindow { Q_OBJECT public: /** * Constructs a new main window. Do not create new main windows directly, use Application's * newMainWindow() method instead. */ MainWindow(); /** * Returns the view manager associated with this window. The view manager can be used to * create new views on particular session objects inside this window. */ ViewManager *viewManager() const; /** * Create a new session. * * @param profile The profile to use to create the new session. * @param directory Initial working directory for the new session or empty * if the default working directory associated with the profile should be used. */ Session *createSession(Profile::Ptr profile, const QString &directory); /** * create a new SSH session. * * @param profile The profile to use to create the new session. * @param url the URL representing the new SSH connection */ Session *createSSHSession(Profile::Ptr profile, const QUrl &url); /** * Helper method to make this window get input focus */ void setFocus(); /** * Set the initial visibility of the menubar. */ void setMenuBarInitialVisibility(bool visible); /** * @brief Set the frameless state * * @param frameless If true, no titlebar or frame is displayed. */ void setRemoveWindowTitleBarAndFrame(bool frameless); Q_SIGNALS: /** * Emitted by the main window to request the creation of a * new session in a new window. * * @param profile The profile to use to create the * first session in the new window. * @param directory Initial working directory for the new window or empty * if the default working directory associated with the profile should * be used. */ void newWindowRequest(const Profile::Ptr &profile, const QString &directory); /** * Emitted when a view for one session is detached from this window */ void terminalsDetached(ViewSplitter *splitter, QHash sessionsMap); protected: // Reimplemented for internal reasons. - void showEvent(QShowEvent *event) Q_DECL_OVERRIDE; - bool eventFilter(QObject *obj, QEvent *event) Q_DECL_OVERRIDE; + void showEvent(QShowEvent *event) override; + bool eventFilter(QObject *obj, QEvent *event) override; // reimplemented from KMainWindow - bool queryClose() Q_DECL_OVERRIDE; - void saveProperties(KConfigGroup &group) Q_DECL_OVERRIDE; - void readProperties(const KConfigGroup &group) Q_DECL_OVERRIDE; - void saveGlobalProperties(KConfig *config) Q_DECL_OVERRIDE; - void readGlobalProperties(KConfig *config) Q_DECL_OVERRIDE; + bool queryClose() override; + void saveProperties(KConfigGroup &group) override; + void readProperties(const KConfigGroup &group) override; + void saveGlobalProperties(KConfig *config) override; + void readGlobalProperties(KConfig *config) override; // reimplemented from QWidget - bool focusNextPrevChild(bool next) Q_DECL_OVERRIDE; + bool focusNextPrevChild(bool next) override; private Q_SLOTS: void newTab(); void cloneTab(); void newWindow(); void showManageProfilesDialog(); void activateMenuBar(); void showSettingsDialog(bool showProfilePage = false); void showShortcutsDialog(); void newFromProfile(const Profile::Ptr &profile); void activeViewChanged(SessionController *controller); void disconnectController(SessionController *controller); void activeViewTitleChanged(ViewProperties *); void profileListChanged(const QList &sessionActions); void configureNotifications(); void setBlur(bool blur); void updateWindowIcon(); void updateWindowCaption(); void openUrls(const QList &urls); // Sets the list of profiles to be displayed under the "New Tab" action void setProfileList(ProfileList *list); void applyKonsoleSettings(); void updateUseTransparency(); public Q_SLOTS: void viewFullScreen(bool fullScreen); private: void correctStandardShortcuts(); void rememberMenuAccelerators(); void removeMenuAccelerators(); void restoreMenuAccelerators(); void setupActions(); QString activeSessionDir() const; void triggerAction(const QString &name) const; /** * Returns the bookmark handler associated with this window. */ BookmarkHandler *bookmarkHandler() const; // sets the active shortcuts of actions in 'dest' to the shortcuts of actions // with the same name in 'source' (see QAction::ActiveShortcut) static void syncActiveShortcuts(KActionCollection *dest, const KActionCollection *source); private: ViewManager *_viewManager; BookmarkHandler *_bookmarkHandler; KToggleAction *_toggleMenuBarAction; KActionMenu *_newTabMenuAction; QPointer _pluggedController; bool _menuBarInitialVisibility; bool _menuBarInitialVisibilityApplied; }; } #endif // MAINWINDOW_H diff --git a/src/Part.h b/src/Part.h index afda8e5e..283d7d9f 100644 --- a/src/Part.h +++ b/src/Part.h @@ -1,221 +1,221 @@ /* Copyright 2007-2008 by Robert Knight This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #ifndef PART_H #define PART_H // KDE #include #include // Qt #include // Konsole #include "config-konsole.h" class QStringList; class QKeyEvent; namespace Konsole { class Session; class SessionController; class ViewManager; class ViewProperties; /** * A re-usable terminal emulator component using the KParts framework which can * be used to embed terminal emulators into other applications. */ #ifdef USE_TERMINALINTERFACEV2 class Part : public KParts::ReadOnlyPart, public TerminalInterfaceV2 { Q_OBJECT Q_INTERFACES(TerminalInterface TerminalInterfaceV2) #else class TerminalInterfaceV2; class Part : public KParts::ReadOnlyPart, public TerminalInterface { Q_OBJECT Q_INTERFACES(TerminalInterface) #endif public: /** Constructs a new Konsole part with the specified parent. */ explicit Part(QWidget *parentWidget, QObject *parent, const QVariantList &); - ~Part() Q_DECL_OVERRIDE; + ~Part() override; /** Reimplemented from TerminalInterface. */ void startProgram(const QString &program, const QStringList &arguments) override; /** Reimplemented from TerminalInterface. */ void showShellInDir(const QString &dir) override; /** Reimplemented from TerminalInterface. */ void sendInput(const QString &text) override; /** Reimplemented from TerminalInterface. */ int terminalProcessId() override; /** Reimplemented from TerminalInterface. */ int foregroundProcessId() override; /** Reimplemented from TerminalInterface. */ QString foregroundProcessName() override; /** Reimplemented from TerminalInterface. */ QString currentWorkingDirectory() const override; #ifdef USE_TERMINALINTERFACEV2 /** Reimplemented from TerminalInterfaceV2 */ QStringList availableProfiles() const override; /** Reimplemented from TerminalInterfaceV2 */ QString currentProfileName() const override; /** Reimplemented from TerminalInterfaceV2 */ bool setCurrentProfile(const QString &profileName) override; /** Reimplemented from TerminalInterfaceV2 */ QVariant profileProperty(const QString &profileProperty) const override; #endif public Q_SLOTS: /** * creates and run a session using the specified profile and directory * * @param profileName Specifies the name of the profile to create session * @param directory specifies The initial working directory of the created session * * This is highly experimental. Do not use it at the moment */ void createSession(const QString &profileName = QString(), const QString &directory = QString()); void showManageProfilesDialog(QWidget* parent); /** * Shows the dialog used to edit the profile used by the active session. The * dialog will be non-modal and will delete itself when it is closed. * * This is experimental API and not guaranteed to be present in later KDE 4 * releases. * * @param parent The parent widget of the new dialog. */ void showEditCurrentProfileDialog(QWidget *parent); /** * Sends a profile change command to the active session. This is equivalent to using * the konsoleprofile tool within the session to change its settings. The @p text string * is a semi-colon separated list of property=value pairs, eg. "colors=Linux Colors" * * See the documentation for konsoleprofile for information on the format of @p text * * This is experimental API and not guaranteed to be present in later KDE 4 releases. */ void changeSessionSettings(const QString &text); /** * Connects to an existing pseudo-teletype. See Session::openTeletype(). * This must be called before the session is started by startProgram(), * or showShellInDir() * * @param ptyMasterFd The file descriptor of the pseudo-teletype (pty) master */ void openTeletype(int ptyMasterFd); /** * Toggles monitoring for silence in the active session. If silence is detected, * the silenceDetected() signal is emitted. * * @param enabled Whether to enable or disable monitoring for silence. * */ void setMonitorSilenceEnabled(bool enabled); /** * Toggles monitoring for activity in the active session. If activity is detected, * the activityDetected() signal is emitted. * * @param enabled Whether to enable or disable monitoring for activity. * */ void setMonitorActivityEnabled(bool enabled); /** * Returns the status of the blur of the current profile. * * @return True if blur is enabled for the current active Konsole color profile. * */ bool isBlurEnabled(); Q_SIGNALS: /** * Emitted when the key sequence for a shortcut, which is also a valid terminal key sequence, * is pressed while the terminal has focus. By responding to this signal, the * controlling application can choose whether to execute the action associated with * the shortcut or ignore the shortcut and send the key * sequence to the terminal application. * * In the embedded terminal, shortcuts are overridden and sent to the terminal by default. * Set @p override to false to prevent this happening and allow the shortcut to be triggered * normally. * * overrideShortcut() is not called for shortcuts which are not valid terminal key sequences, * eg. shortcuts with two or more modifiers. * * @param event Describes the keys that were pressed. * @param override Set this to false to prevent the terminal display from overriding the shortcut */ void overrideShortcut(QKeyEvent *event, bool &override); /** * Emitted when silence has been detected in the active session. Monitoring * for silence has to be enabled first using setMonitorSilenceEnabled(). */ void silenceDetected(); /** * Emitted when activity has been detected in the active session. Monitoring * for activity has to be enabled first using setMonitorActivityEnabled(). */ void activityDetected(); /** * Emitted when the current working directory of the active session has changed. */ void currentDirectoryChanged(const QString &dir); protected: /** Reimplemented from KParts::PartBase. */ - bool openFile() Q_DECL_OVERRIDE; - bool openUrl(const QUrl &url) Q_DECL_OVERRIDE; + bool openFile() override; + bool openUrl(const QUrl &url) override; private Q_SLOTS: void activeViewChanged(SessionController *controller); void activeViewTitleChanged(ViewProperties *properties); void terminalExited(); void newTab(); void overrideTerminalShortcut(QKeyEvent *, bool &override); void sessionStateChanged(int state); private: Session *activeSession() const; private: ViewManager *_viewManager; SessionController *_pluggedController; }; } #endif // PART_H diff --git a/src/PrintOptions.h b/src/PrintOptions.h index 81659657..014fc9cd 100644 --- a/src/PrintOptions.h +++ b/src/PrintOptions.h @@ -1,40 +1,40 @@ /* Copyright 2012 Kasper Laudrup 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) version 3 or any later version accepted by the membership of KDE e.V. (or its successor appro- ved by the membership of KDE e.V.), which shall act as a proxy defined in Section 14 of version 3 of the license. 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 http://www.gnu.org/licenses/. */ #ifndef PRINTOPTIONS_H #define PRINTOPTIONS_H #include "ui_PrintOptions.h" namespace Konsole { class PrintOptions : public QWidget, private Ui::PrintOptions { Q_OBJECT public: explicit PrintOptions(QWidget *parent = nullptr); - ~PrintOptions() Q_DECL_OVERRIDE; + ~PrintOptions() override; public Q_SLOTS: void saveSettings(); }; } #endif diff --git a/src/ProcessInfo.cpp b/src/ProcessInfo.cpp index b3889914..93f5740f 100644 --- a/src/ProcessInfo.cpp +++ b/src/ProcessInfo.cpp @@ -1,1195 +1,1195 @@ /* Copyright 2007-2008 by Robert Knight This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ // Config #include "config-konsole.h" // Own #include "ProcessInfo.h" // Unix #include #include #include #include #include #include #include // Qt #include #include #include #include #include // KDE #include #include #include #if defined(Q_OS_FREEBSD) || defined(Q_OS_OPENBSD) || defined(Q_OS_MACOS) #include #endif #if defined(Q_OS_MACOS) #include #include #endif #if defined(Q_OS_FREEBSD) || defined(Q_OS_OPENBSD) #include #include #include # if defined(Q_OS_FREEBSD) # include # include # include # endif #endif using namespace Konsole; ProcessInfo::ProcessInfo(int pid) : _fields(ARGUMENTS) // arguments // are currently always valid, // they just return an empty // vector / map respectively // if no arguments // have been explicitly set , _pid(pid), _parentPid(0), _foregroundPid(0), _userId(0), _lastError(NoError), _name(QString()), _userName(QString()), _userHomeDir(QString()), _currentDir(QString()), _userNameRequired(true), _arguments(QVector()) { } ProcessInfo::Error ProcessInfo::error() const { return _lastError; } void ProcessInfo::setError(Error error) { _lastError = error; } void ProcessInfo::update() { readCurrentDir(_pid); } QString ProcessInfo::validCurrentDir() const { bool ok = false; // read current dir, if an error occurs try the parent as the next // best option int currentPid = parentPid(&ok); QString dir = currentDir(&ok); while (!ok && currentPid != 0) { ProcessInfo *current = ProcessInfo::newInstance(currentPid); current->update(); currentPid = current->parentPid(&ok); dir = current->currentDir(&ok); delete current; } return dir; } QSet ProcessInfo::_commonDirNames; QSet ProcessInfo::commonDirNames() { static bool forTheFirstTime = true; if (forTheFirstTime) { const KSharedConfigPtr &config = KSharedConfig::openConfig(); const KConfigGroup &configGroup = config->group("ProcessInfo"); _commonDirNames = QSet::fromList(configGroup.readEntry("CommonDirNames", QStringList())); forTheFirstTime = false; } return _commonDirNames; } QString ProcessInfo::formatShortDir(const QString &input) const { if(input == QLatin1String("/")) { return QStringLiteral("/"); } QString result; const QStringList &parts = input.split(QDir::separator()); QSet dirNamesToShorten = commonDirNames(); QListIterator iter(parts); iter.toBack(); // go backwards through the list of the path's parts // adding abbreviations of common directory names // and stopping when we reach a dir name which is not // in the commonDirNames set while (iter.hasPrevious()) { const QString &part = iter.previous(); if (dirNamesToShorten.contains(part)) { result.prepend(QDir::separator() + part[0]); } else { result.prepend(part); break; } } return result; } QVector ProcessInfo::arguments(bool *ok) const { *ok = _fields.testFlag(ARGUMENTS); return _arguments; } bool ProcessInfo::isValid() const { return _fields.testFlag(PROCESS_ID); } int ProcessInfo::pid(bool *ok) const { *ok = _fields.testFlag(PROCESS_ID); return _pid; } int ProcessInfo::parentPid(bool *ok) const { *ok = _fields.testFlag(PARENT_PID); return _parentPid; } int ProcessInfo::foregroundPid(bool *ok) const { *ok = _fields.testFlag(FOREGROUND_PID); return _foregroundPid; } QString ProcessInfo::name(bool *ok) const { *ok = _fields.testFlag(NAME); return _name; } int ProcessInfo::userId(bool *ok) const { *ok = _fields.testFlag(UID); return _userId; } QString ProcessInfo::userName() const { return _userName; } QString ProcessInfo::userHomeDir() const { return _userHomeDir; } QString ProcessInfo::localHost() { return QHostInfo::localHostName(); } void ProcessInfo::setPid(int pid) { _pid = pid; _fields |= PROCESS_ID; } void ProcessInfo::setUserId(int uid) { _userId = uid; _fields |= UID; } void ProcessInfo::setUserName(const QString &name) { _userName = name; setUserHomeDir(); } void ProcessInfo::setUserHomeDir() { const QString &usersName = userName(); if (!usersName.isEmpty()) { _userHomeDir = KUser(usersName).homeDir(); } else { _userHomeDir = QDir::homePath(); } } void ProcessInfo::setParentPid(int pid) { _parentPid = pid; _fields |= PARENT_PID; } void ProcessInfo::setForegroundPid(int pid) { _foregroundPid = pid; _fields |= FOREGROUND_PID; } void ProcessInfo::setUserNameRequired(bool need) { _userNameRequired = need; } bool ProcessInfo::userNameRequired() const { return _userNameRequired; } QString ProcessInfo::currentDir(bool *ok) const { if (ok != nullptr) { *ok = (_fields & CURRENT_DIR) != 0; } return _currentDir; } void ProcessInfo::setCurrentDir(const QString &dir) { _fields |= CURRENT_DIR; _currentDir = dir; } void ProcessInfo::setName(const QString &name) { _name = name; _fields |= NAME; } void ProcessInfo::addArgument(const QString &argument) { _arguments << argument; } void ProcessInfo::clearArguments() { _arguments.clear(); } void ProcessInfo::setFileError(QFile::FileError error) { switch (error) { case QFile::PermissionsError: setError(ProcessInfo::PermissionsError); break; case QFile::NoError: setError(ProcessInfo::NoError); break; default: setError(ProcessInfo::UnknownError); } } // // ProcessInfo::newInstance() is way at the bottom so it can see all of the // implementations of the UnixProcessInfo abstract class. // NullProcessInfo::NullProcessInfo(int pid) : ProcessInfo(pid) { } void NullProcessInfo::readProcessInfo(int /*pid*/) { } bool NullProcessInfo::readCurrentDir(int /*pid*/) { return false; } void NullProcessInfo::readUserName() { } #if !defined(Q_OS_WIN) UnixProcessInfo::UnixProcessInfo(int pid) : ProcessInfo(pid) { setUserNameRequired(true); } void UnixProcessInfo::readProcessInfo(int pid) { // prevent _arguments from growing longer and longer each time this // method is called. clearArguments(); if (readProcInfo(pid)) { readArguments(pid); readCurrentDir(pid); bool ok = false; const QString &processNameString = name(&ok); if (ok && processNameString == QLatin1String("sudo")) { //Append process name along with sudo const QVector &args = arguments(&ok); if (ok && args.size() > 1) { setName(processNameString + QStringLiteral(" ") + args[1]); } } } } void UnixProcessInfo::readUserName() { bool ok = false; const int uid = userId(&ok); if (!ok) { return; } struct passwd passwdStruct; struct passwd *getpwResult; char *getpwBuffer; long getpwBufferSize; int getpwStatus; getpwBufferSize = sysconf(_SC_GETPW_R_SIZE_MAX); if (getpwBufferSize == -1) { getpwBufferSize = 16384; } getpwBuffer = new char[getpwBufferSize]; if (getpwBuffer == nullptr) { return; } getpwStatus = getpwuid_r(uid, &passwdStruct, getpwBuffer, getpwBufferSize, &getpwResult); if ((getpwStatus == 0) && (getpwResult != nullptr)) { setUserName(QLatin1String(passwdStruct.pw_name)); } else { setUserName(QString()); qWarning() << "getpwuid_r returned error : " << getpwStatus; } delete [] getpwBuffer; } #endif #if defined(Q_OS_LINUX) class LinuxProcessInfo : public UnixProcessInfo { public: LinuxProcessInfo(int pid) : UnixProcessInfo(pid) { } protected: - bool readCurrentDir(int pid) Q_DECL_OVERRIDE + bool readCurrentDir(int pid) override { char path_buffer[MAXPATHLEN + 1]; path_buffer[MAXPATHLEN] = 0; QByteArray procCwd = QFile::encodeName(QStringLiteral("/proc/%1/cwd").arg(pid)); const auto length = static_cast(readlink(procCwd.constData(), path_buffer, MAXPATHLEN)); if (length == -1) { setError(UnknownError); return false; } path_buffer[length] = '\0'; QString path = QFile::decodeName(path_buffer); setCurrentDir(path); return true; } private: - bool readProcInfo(int pid) Q_DECL_OVERRIDE + bool readProcInfo(int pid) override { // indicies of various fields within the process status file which // contain various information about the process const int PARENT_PID_FIELD = 3; const int PROCESS_NAME_FIELD = 1; const int GROUP_PROCESS_FIELD = 7; QString parentPidString; QString processNameString; QString foregroundPidString; QString uidLine; QString uidString; QStringList uidStrings; // For user id read process status file ( /proc//status ) // Can not use getuid() due to it does not work for 'su' QFile statusInfo(QStringLiteral("/proc/%1/status").arg(pid)); if (statusInfo.open(QIODevice::ReadOnly)) { QTextStream stream(&statusInfo); QString statusLine; do { statusLine = stream.readLine(); if (statusLine.startsWith(QLatin1String("Uid:"))) { uidLine = statusLine; } } while (!statusLine.isNull() && uidLine.isNull()); uidStrings << uidLine.split(QLatin1Char('\t'), QString::SkipEmptyParts); // Must be 5 entries: 'Uid: %d %d %d %d' and // uid string must be less than 5 chars (uint) if (uidStrings.size() == 5) { uidString = uidStrings[1]; } if (uidString.size() > 5) { uidString.clear(); } bool ok = false; const int uid = uidString.toInt(&ok); if (ok) { setUserId(uid); } // This will cause constant opening of /etc/passwd if (userNameRequired()) { readUserName(); setUserNameRequired(false); } } else { setFileError(statusInfo.error()); return false; } // read process status file ( /proc//cmdline // the expected format is a list of strings delimited by null characters, // and ending in a double null character pair. QFile argumentsFile(QStringLiteral("/proc/%1/cmdline").arg(pid)); if (argumentsFile.open(QIODevice::ReadOnly)) { QTextStream stream(&argumentsFile); const QString &data = stream.readAll(); const QStringList &argList = data.split(QLatin1Char('\0')); for (const QString &entry : argList) { if (!entry.isEmpty()) { addArgument(entry); } } } else { setFileError(argumentsFile.error()); } return true; } }; #elif defined(Q_OS_FREEBSD) class FreeBSDProcessInfo : public UnixProcessInfo { public: FreeBSDProcessInfo(int pid) : UnixProcessInfo(pid) { } protected: - bool readCurrentDir(int pid) Q_DECL_OVERRIDE + bool readCurrentDir(int pid) override { #if defined(HAVE_OS_DRAGONFLYBSD) char buf[PATH_MAX]; int managementInfoBase[4]; size_t len; managementInfoBase[0] = CTL_KERN; managementInfoBase[1] = KERN_PROC; managementInfoBase[2] = KERN_PROC_CWD; managementInfoBase[3] = pid; len = sizeof(buf); if (sysctl(managementInfoBase, 4, buf, &len, NULL, 0) == -1) { return false; } setCurrentDir(QString::fromUtf8(buf)); return true; #else int numrecords; struct kinfo_file *info = nullptr; info = kinfo_getfile(pid, &numrecords); if (!info) { return false; } for (int i = 0; i < numrecords; ++i) { if (info[i].kf_fd == KF_FD_TYPE_CWD) { setCurrentDir(QString::fromUtf8(info[i].kf_path)); free(info); return true; } } free(info); return false; #endif } private: - bool readProcInfo(int pid) Q_DECL_OVERRIDE + bool readProcInfo(int pid) override { int managementInfoBase[4]; size_t mibLength; struct kinfo_proc *kInfoProc; managementInfoBase[0] = CTL_KERN; managementInfoBase[1] = KERN_PROC; managementInfoBase[2] = KERN_PROC_PID; managementInfoBase[3] = pid; if (sysctl(managementInfoBase, 4, NULL, &mibLength, NULL, 0) == -1) { return false; } kInfoProc = new struct kinfo_proc [mibLength]; if (sysctl(managementInfoBase, 4, kInfoProc, &mibLength, NULL, 0) == -1) { delete [] kInfoProc; return false; } #if defined(HAVE_OS_DRAGONFLYBSD) setName(QString::fromUtf8(kInfoProc->kp_comm)); setPid(kInfoProc->kp_pid); setParentPid(kInfoProc->kp_ppid); setForegroundPid(kInfoProc->kp_pgid); setUserId(kInfoProc->kp_uid); #else setName(QString::fromUtf8(kInfoProc->ki_comm)); setPid(kInfoProc->ki_pid); setParentPid(kInfoProc->ki_ppid); setForegroundPid(kInfoProc->ki_pgid); setUserId(kInfoProc->ki_uid); #endif readUserName(); delete [] kInfoProc; return true; } - bool readArguments(int pid) Q_DECL_OVERRIDE + bool readArguments(int pid) override { char args[ARG_MAX]; int managementInfoBase[4]; size_t len; managementInfoBase[0] = CTL_KERN; managementInfoBase[1] = KERN_PROC; managementInfoBase[2] = KERN_PROC_ARGS; managementInfoBase[3] = pid; len = sizeof(args); if (sysctl(managementInfoBase, 4, args, &len, NULL, 0) == -1) { return false; } // len holds the length of the string const QStringList argurments = QString::fromLocal8Bit(args, len).split(QLatin1Char('\u0000')); for (const QString &value : argurments) { if (!value.isEmpty()) { addArgument(value); } } return true; } }; #elif defined(Q_OS_OPENBSD) class OpenBSDProcessInfo : public UnixProcessInfo { public: OpenBSDProcessInfo(int pid) : UnixProcessInfo(pid) { } protected: - bool readCurrentDir(int pid) Q_DECL_OVERRIDE + bool readCurrentDir(int pid) override { char buf[PATH_MAX]; int managementInfoBase[3]; size_t len; managementInfoBase[0] = CTL_KERN; managementInfoBase[1] = KERN_PROC_CWD; managementInfoBase[2] = pid; len = sizeof(buf); if (::sysctl(managementInfoBase, 3, buf, &len, NULL, 0) == -1) { qWarning() << "sysctl() call failed with code" << errno; return false; } setCurrentDir(QString::fromUtf8(buf)); return true; } private: - bool readProcInfo(int pid) Q_DECL_OVERRIDE + bool readProcInfo(int pid) override { int managementInfoBase[6]; size_t mibLength; struct kinfo_proc *kInfoProc; managementInfoBase[0] = CTL_KERN; managementInfoBase[1] = KERN_PROC; managementInfoBase[2] = KERN_PROC_PID; managementInfoBase[3] = pid; managementInfoBase[4] = sizeof(struct kinfo_proc); managementInfoBase[5] = 1; if (::sysctl(managementInfoBase, 6, NULL, &mibLength, NULL, 0) == -1) { qWarning() << "first sysctl() call failed with code" << errno; return false; } kInfoProc = (struct kinfo_proc *)malloc(mibLength); if (::sysctl(managementInfoBase, 6, kInfoProc, &mibLength, NULL, 0) == -1) { qWarning() << "second sysctl() call failed with code" << errno; free(kInfoProc); return false; } setName(kInfoProc->p_comm); setPid(kInfoProc->p_pid); setParentPid(kInfoProc->p_ppid); setForegroundPid(kInfoProc->p_tpgid); setUserId(kInfoProc->p_uid); setUserName(kInfoProc->p_login); free(kInfoProc); return true; } char **readProcArgs(int pid, int whatMib) { void *buf = NULL; void *nbuf; size_t len = 4096; int rc = -1; int managementInfoBase[4]; managementInfoBase[0] = CTL_KERN; managementInfoBase[1] = KERN_PROC_ARGS; managementInfoBase[2] = pid; managementInfoBase[3] = whatMib; do { len *= 2; nbuf = realloc(buf, len); if (nbuf == NULL) { break; } buf = nbuf; rc = ::sysctl(managementInfoBase, 4, buf, &len, NULL, 0); qWarning() << "sysctl() call failed with code" << errno; } while (rc == -1 && errno == ENOMEM); if (nbuf == NULL || rc == -1) { free(buf); return NULL; } return (char **)buf; } - bool readArguments(int pid) Q_DECL_OVERRIDE + bool readArguments(int pid) override { char **argv; argv = readProcArgs(pid, KERN_PROC_ARGV); if (argv == NULL) { return false; } for (char **p = argv; *p != NULL; p++) { addArgument(QString(*p)); } free(argv); return true; } }; #elif defined(Q_OS_MACOS) class MacProcessInfo : public UnixProcessInfo { public: MacProcessInfo(int pid) : UnixProcessInfo(pid) { } protected: - bool readCurrentDir(int pid) Q_DECL_OVERRIDE + bool readCurrentDir(int pid) override { struct proc_vnodepathinfo vpi; const int nb = proc_pidinfo(pid, PROC_PIDVNODEPATHINFO, 0, &vpi, sizeof(vpi)); if (nb == sizeof(vpi)) { setCurrentDir(QString::fromUtf8(vpi.pvi_cdir.vip_path)); return true; } return false; } private: - bool readProcInfo(int pid) Q_DECL_OVERRIDE + bool readProcInfo(int pid) override { int managementInfoBase[4]; size_t mibLength; struct kinfo_proc *kInfoProc; QT_STATBUF statInfo; // Find the tty device of 'pid' (Example: /dev/ttys001) managementInfoBase[0] = CTL_KERN; managementInfoBase[1] = KERN_PROC; managementInfoBase[2] = KERN_PROC_PID; managementInfoBase[3] = pid; if (sysctl(managementInfoBase, 4, nullptr, &mibLength, nullptr, 0) == -1) { return false; } else { kInfoProc = new struct kinfo_proc [mibLength]; if (sysctl(managementInfoBase, 4, kInfoProc, &mibLength, nullptr, 0) == -1) { delete [] kInfoProc; return false; } else { const QString deviceNumber = QString::fromUtf8(devname(((&kInfoProc->kp_eproc)->e_tdev), S_IFCHR)); const QString fullDeviceName = QStringLiteral("/dev/") + deviceNumber.rightJustified(3, QLatin1Char('0')); delete [] kInfoProc; const QByteArray deviceName = fullDeviceName.toLatin1(); const char *ttyName = deviceName.data(); if (QT_STAT(ttyName, &statInfo) != 0) { return false; } // Find all processes attached to ttyName managementInfoBase[0] = CTL_KERN; managementInfoBase[1] = KERN_PROC; managementInfoBase[2] = KERN_PROC_TTY; managementInfoBase[3] = statInfo.st_rdev; mibLength = 0; if (sysctl(managementInfoBase, sizeof(managementInfoBase) / sizeof(int), nullptr, &mibLength, nullptr, 0) == -1) { return false; } kInfoProc = new struct kinfo_proc [mibLength]; if (sysctl(managementInfoBase, sizeof(managementInfoBase) / sizeof(int), kInfoProc, &mibLength, nullptr, 0) == -1) { return false; } // The foreground program is the first one setName(QString::fromUtf8(kInfoProc->kp_proc.p_comm)); delete [] kInfoProc; } setPid(pid); } return true; } - bool readArguments(int pid) Q_DECL_OVERRIDE + bool readArguments(int pid) override { Q_UNUSED(pid); return false; } }; #elif defined(Q_OS_SOLARIS) // The procfs structure definition requires off_t to be // 32 bits, which only applies if FILE_OFFSET_BITS=32. // Futz around here to get it to compile regardless, // although some of the structure sizes might be wrong. // Fortunately, the structures we actually use don't use // off_t, and we're safe. #if defined(_FILE_OFFSET_BITS) && (_FILE_OFFSET_BITS == 64) #undef _FILE_OFFSET_BITS #endif #include class SolarisProcessInfo : public UnixProcessInfo { public: SolarisProcessInfo(int pid) : UnixProcessInfo(pid) { } protected: // FIXME: This will have the same issues as BKO 251351; the Linux // version uses readlink. - bool readCurrentDir(int pid) Q_DECL_OVERRIDE + bool readCurrentDir(int pid) override { QFileInfo info(QString("/proc/%1/path/cwd").arg(pid)); const bool readable = info.isReadable(); if (readable && info.isSymLink()) { setCurrentDir(info.symLinkTarget()); return true; } else { if (!readable) { setError(PermissionsError); } else { setError(UnknownError); } return false; } } private: - bool readProcInfo(int pid) Q_DECL_OVERRIDE + bool readProcInfo(int pid) override { QFile psinfo(QString("/proc/%1/psinfo").arg(pid)); if (psinfo.open(QIODevice::ReadOnly)) { struct psinfo info; if (psinfo.read((char *)&info, sizeof(info)) != sizeof(info)) { return false; } setParentPid(info.pr_ppid); setForegroundPid(info.pr_pgid); setName(info.pr_fname); setPid(pid); // Bogus, because we're treating the arguments as one single string info.pr_psargs[PRARGSZ - 1] = 0; addArgument(info.pr_psargs); } return true; } - bool readArguments(int /*pid*/) Q_DECL_OVERRIDE + bool readArguments(int /*pid*/) override { // Handled in readProcInfo() return false; } }; #endif SSHProcessInfo::SSHProcessInfo(const ProcessInfo &process) : _process(process), _user(QString()), _host(QString()), _port(QString()), _command(QString()) { bool ok = false; // check that this is a SSH process const QString &name = _process.name(&ok); if (!ok || name != QLatin1String("ssh")) { if (!ok) { qWarning() << "Could not read process info"; } else { qWarning() << "Process is not a SSH process"; } return; } // read arguments const QVector &args = _process.arguments(&ok); // SSH options // these are taken from the SSH manual ( accessed via 'man ssh' ) // options which take no arguments static const QString noArgumentOptions(QStringLiteral("1246AaCfgKkMNnqsTtVvXxYy")); // options which take one argument static const QString singleArgumentOptions(QStringLiteral("bcDeFIiLlmOopRSWw")); if (ok) { // find the username, host and command arguments // // the username/host is assumed to be the first argument // which is not an option // ( ie. does not start with a dash '-' character ) // or an argument to a previous option. // // the command, if specified, is assumed to be the argument following // the username and host // // note that we skip the argument at index 0 because that is the // program name ( expected to be 'ssh' in this case ) for (int i = 1; i < args.count(); i++) { // If this one is an option ... // Most options together with its argument will be skipped. if (args[i].startsWith(QLatin1Char('-'))) { const QChar optionChar = (args[i].length() > 1) ? args[i][1] : QLatin1Char('\0'); // for example: -p2222 or -p 2222 ? const bool optionArgumentCombined = args[i].length() > 2; if (noArgumentOptions.contains(optionChar)) { continue; } else if (singleArgumentOptions.contains(optionChar)) { QString argument; if (optionArgumentCombined) { argument = args[i].mid(2); } else { // Verify correct # arguments are given if ((i + 1) < args.count()) { argument = args[i + 1]; } i++; } // support using `-l user` to specify username. if (optionChar == QLatin1Char('l')) { _user = argument; } // support using `-p port` to specify port. else if (optionChar == QLatin1Char('p')) { _port = argument; } continue; } } // check whether the host has been found yet // if not, this must be the username/host argument if (_host.isEmpty()) { // check to see if only a hostname is specified, or whether // both a username and host are specified ( in which case they // are separated by an '@' character: username@host ) const int separatorPosition = args[i].indexOf(QLatin1Char('@')); if (separatorPosition != -1) { // username and host specified _user = args[i].left(separatorPosition); _host = args[i].mid(separatorPosition + 1); } else { // just the host specified _host = args[i]; } } else { // host has already been found, this must be part of the // command arguments. // Note this is not 100% correct. If any of the above // noArgumentOptions or singleArgumentOptions are found, this // will not be correct (example ssh server top -i 50) // Suggest putting ssh command in quotes if (_command.isEmpty()) { _command = args[i]; } else { _command = _command + QLatin1Char(' ') + args[i]; } } } } else { qWarning() << "Could not read arguments"; return; } } QString SSHProcessInfo::userName() const { return _user; } QString SSHProcessInfo::host() const { return _host; } QString SSHProcessInfo::port() const { return _port; } QString SSHProcessInfo::command() const { return _command; } QString SSHProcessInfo::format(const QString &input) const { QString output(input); // search for and replace known markers output.replace(QLatin1String("%u"), _user); // provide 'user@' if user is defined -- this makes nicer // remote tabs possible: "%U%h %c" => User@Host Command // => Host Command // Depending on whether -l was passed to ssh (which is mostly not the // case due to ~/.ssh/config). if (_user.isEmpty()) { output.remove(QLatin1String("%U")); } else { output.replace(QLatin1String("%U"), _user + QLatin1Char('@')); } // test whether host is an ip address // in which case 'short host' and 'full host' // markers in the input string are replaced with // the full address struct in_addr address; const bool isIpAddress = inet_aton(_host.toLocal8Bit().constData(), &address) != 0; if (isIpAddress) { output.replace(QLatin1String("%h"), _host); } else { output.replace(QLatin1String("%h"), _host.left(_host.indexOf(QLatin1Char('.')))); } output.replace(QLatin1String("%H"), _host); output.replace(QLatin1String("%c"), _command); return output; } ProcessInfo *ProcessInfo::newInstance(int pid) { ProcessInfo *info; #if defined(Q_OS_LINUX) info = new LinuxProcessInfo(pid); #elif defined(Q_OS_SOLARIS) info = new SolarisProcessInfo(pid); #elif defined(Q_OS_MACOS) info = new MacProcessInfo(pid); #elif defined(Q_OS_FREEBSD) info = new FreeBSDProcessInfo(pid); #elif defined(Q_OS_OPENBSD) info = new OpenBSDProcessInfo(pid); #else info = new NullProcessInfo(pid); #endif info->readProcessInfo(pid); return info; } diff --git a/src/ProcessInfo.h b/src/ProcessInfo.h index 3581598e..7ae1e3f8 100644 --- a/src/ProcessInfo.h +++ b/src/ProcessInfo.h @@ -1,411 +1,411 @@ /* Copyright 2007-2008 by Robert Knight This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #ifndef PROCESSINFO_H #define PROCESSINFO_H // Qt #include #include #include namespace Konsole { /** * Takes a snapshot of the state of a process and provides access to * information such as the process name, parent process, * the foreground process in the controlling terminal, * the arguments with which the process was started. * * To create a new snapshot, construct a new ProcessInfo instance, * using ProcessInfo::newInstance(), * passing the process identifier of the process you are interested in. * * After creating a new instance, call the update() method to take a * snapshot of the current state of the process. * * Before calling any additional methods, check that the process state * was read successfully using the isValid() method. * * Each accessor method which provides information about the process state ( such as pid(), * currentDir(), name() ) takes a pointer to a boolean as an argument. If the information * requested was read successfully then the boolean is set to true, otherwise it is set * to false, in which case the return value from the function should be ignored. * If this boolean is set to false, it may indicate an error reading the process information, * or it may indicate that the information is not available on the current platform. * * eg. * * @code * ProcessInfo* info = ProcessInfo::newInstance(pid); * info->update(); * * if ( info->isValid() ) * { * bool ok; * * QString name = info->name(&ok); * if ( ok ) qDebug() << "process name - " << name; * int parentPid = info->parentPid(&ok); * if ( ok ) qDebug() << "parent process - " << parentPid; * int foregroundPid = info->foregroundPid(&ok); * if ( ok ) qDebug() << "foreground process - " << foregroundPid; * } * @endcode */ class ProcessInfo { public: /** * Constructs a new instance of a suitable ProcessInfo sub-class for * the current platform which provides information about a given process. * * @param pid The pid of the process to examine */ static ProcessInfo *newInstance(int pid); virtual ~ProcessInfo() { } /** * Updates the information about the process. This must * be called before attempting to use any of the accessor methods. */ void update(); /** Returns true if the process state was read successfully. */ bool isValid() const; /** * Returns the process id. * * @param ok Set to true if the process id was read successfully or false otherwise */ int pid(bool *ok) const; /** * Returns the id of the parent process id was read successfully or false otherwise * * @param ok Set to true if the parent process id */ int parentPid(bool *ok) const; /** * Returns the id of the current foreground process * * NOTE: Using the foregroundProcessGroup() method of the Pty * instance associated with the terminal of interest is preferred * over using this method. * * @param ok Set to true if the foreground process id was read successfully or false otherwise */ int foregroundPid(bool *ok) const; /* Returns the user id of the process */ int userId(bool *ok) const; /** Returns the user's name of the process */ QString userName() const; /** Returns the user's home directory of the process */ QString userHomeDir() const; /** Returns the local host */ static QString localHost(); /** Returns the name of the current process */ QString name(bool *ok) const; /** * Returns the command-line arguments which the process * was started with. * * The first argument is the name used to launch the process. * * @param ok Set to true if the arguments were read successfully or false otherwise. */ QVector arguments(bool *ok) const; /** * Returns the current working directory of the process * * @param ok Set to true if the current working directory was read successfully or false otherwise */ QString currentDir(bool *ok) const; /** * Returns the current working directory of the process (or its parent) */ QString validCurrentDir() const; /** Forces the user home directory to be calculated */ void setUserHomeDir(); /** * This enum describes the errors which can occur when trying to read * a process's information. */ enum Error { /** No error occurred. */ NoError, /** The nature of the error is unknown. */ UnknownError, /** Konsole does not have permission to obtain the process information. */ PermissionsError }; /** * Returns the last error which occurred. */ Error error() const; enum Field { PROCESS_ID = 1, PARENT_PID = 2, FOREGROUND_PID = 4, ARGUMENTS = 8, NAME = 16, CURRENT_DIR = 32, UID = 64 }; Q_DECLARE_FLAGS(Fields, Field) // takes a full directory path and returns a // shortened version suitable for display in // space-constrained UI elements (eg. tabs) QString formatShortDir(const QString &dirPath) const; void setUserNameRequired(bool need); protected: /** * Constructs a new process instance. You should not call the constructor * of ProcessInfo or its subclasses directly. Instead use the * static ProcessInfo::newInstance() method which will return * a suitable ProcessInfo instance for the current platform. */ explicit ProcessInfo(int pid); /** * This is called on construction to read the process state * Subclasses should reimplement this function to provide * platform-specific process state reading functionality. * * When called, readProcessInfo() should attempt to read all * of the necessary state information. If the attempt is successful, * it should set the process id using setPid(), and update * the other relevant information using setParentPid(), setName(), * setArguments() etc. * * Calls to isValid() will return true only if the process id * has been set using setPid() * * @param pid The process id of the process to read */ virtual void readProcessInfo(int pid) = 0; /** * Determine the current directory of the process. * @param pid process ID to use * @return true on success */ virtual bool readCurrentDir(int pid) = 0; /* Read the user name */ virtual void readUserName(void) = 0; /** Sets the process id associated with this ProcessInfo instance */ void setPid(int pid); /** Sets the parent process id as returned by parentPid() */ void setParentPid(int pid); /** Sets the foreground process id as returned by foregroundPid() */ void setForegroundPid(int pid); /** Sets the user id associated with this ProcessInfo instance */ void setUserId(int uid); /** Sets the user name of the process as set by readUserName() */ void setUserName(const QString &name); /** Sets the name of the process as returned by name() */ void setName(const QString &name); /** Sets the current working directory for the process */ void setCurrentDir(const QString &dir); /** Sets the error */ void setError(Error error); /** Convenience method. Sets the error based on a QFile error code. */ void setFileError(QFile::FileError error); /** * Adds a commandline argument for the process, as returned * by arguments() */ void addArgument(const QString &argument); /** * clear the commandline arguments for the process, as returned * by arguments() */ void clearArguments(); bool userNameRequired() const; private: Fields _fields; int _pid; int _parentPid; int _foregroundPid; int _userId; Error _lastError; QString _name; QString _userName; QString _userHomeDir; QString _currentDir; bool _userNameRequired; QVector _arguments; static QSet commonDirNames(); static QSet _commonDirNames; }; Q_DECLARE_OPERATORS_FOR_FLAGS(ProcessInfo::Fields) /** * Implementation of ProcessInfo which does nothing. * Used on platforms where a suitable ProcessInfo subclass is not * available. * * isValid() will always return false for instances of NullProcessInfo */ class NullProcessInfo : public ProcessInfo { public: /** * Constructs a new NullProcessInfo instance. * See ProcessInfo::newInstance() */ explicit NullProcessInfo(int pid); protected: - void readProcessInfo(int pid) Q_DECL_OVERRIDE; - bool readCurrentDir(int pid) Q_DECL_OVERRIDE; - void readUserName(void) Q_DECL_OVERRIDE; + void readProcessInfo(int pid) override; + bool readCurrentDir(int pid) override; + void readUserName(void) override; }; #if !defined(Q_OS_WIN) /** * Implementation of ProcessInfo for Unix platforms which uses * the /proc filesystem */ class UnixProcessInfo : public ProcessInfo { public: /** * Constructs a new instance of UnixProcessInfo. * See ProcessInfo::newInstance() */ explicit UnixProcessInfo(int pid); protected: /** * Implementation of ProcessInfo::readProcessInfo(); calls the * four private methods below in turn. */ - void readProcessInfo(int pid) Q_DECL_OVERRIDE; + void readProcessInfo(int pid) override; - void readUserName(void) Q_DECL_OVERRIDE; + void readUserName(void) override; private: /** * Read the standard process information -- PID, parent PID, foreground PID. * @param pid process ID to use * @return true on success */ virtual bool readProcInfo(int pid) = 0; /** * Determine what arguments were passed to the process. Sets _arguments. * @param pid process ID to use * @return true on success */ virtual bool readArguments(int pid) = 0; }; #endif /** * Lightweight class which provides additional information about SSH processes. */ class SSHProcessInfo { public: /** * Constructs a new SSHProcessInfo instance which provides additional * information about the specified SSH process. * * @param process A ProcessInfo instance for a SSH process. */ explicit SSHProcessInfo(const ProcessInfo &process); /** * Returns the user name which the user initially logged into on * the remote computer. */ QString userName() const; /** * Returns the host which the user has connected to. */ QString host() const; /** * Returns the port on host which the user has connected to. */ QString port() const; /** * Returns the command which the user specified to execute on the * remote computer when starting the SSH process. */ QString command() const; /** * Operates in the same way as ProcessInfo::format(), except * that the set of markers understood is different: * * %u - Replaced with user name which the user initially logged * into on the remote computer. * %h - Replaced with the first part of the host name which * is connected to. * %H - Replaced with the full host name of the computer which * is connected to. * %c - Replaced with the command which the user specified * to execute when starting the SSH process. */ QString format(const QString &input) const; private: const ProcessInfo &_process; QString _user; QString _host; QString _port; QString _command; }; } #endif //PROCESSINFO_H diff --git a/src/Profile.h b/src/Profile.h index eee5f766..eb9ce9e7 100644 --- a/src/Profile.h +++ b/src/Profile.h @@ -1,810 +1,810 @@ /* This source file is part of Konsole, a terminal emulator. Copyright 2007-2008 by Robert Knight This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #ifndef PROFILE_H #define PROFILE_H // Qt #include #include #include #include #include // Konsole #include "konsoleprivate_export.h" namespace Konsole { class ProfileGroup; /** * Represents a terminal set-up which can be used to * set the initial state of new terminal sessions or applied * to existing sessions. Profiles consist of a number of named * properties, which can be retrieved using property() and * set using setProperty(). isPropertySet() can be used to check * whether a particular property has been set in a profile. * * Profiles support a simple form of inheritance. When a new Profile * is constructed, a pointer to a parent profile can be passed to * the constructor. When querying a particular property of a profile * using property(), the profile will return its own value for that * property if one has been set or otherwise it will return the * parent's value for that property. * * Profiles can be loaded from disk using ProfileReader instances * and saved to disk using ProfileWriter instances. */ class KONSOLEPRIVATE_EXPORT Profile : public QSharedData { Q_GADGET friend class ProfileReader; friend class ProfileWriter; friend class ProfileGroup; public: using Ptr = QExplicitlySharedDataPointer; using GroupPtr = QExplicitlySharedDataPointer; /** * This enum describes the available properties * which a Profile may consist of. * * Properties can be set using setProperty() and read * using property() */ enum Property { /** (QString) Path to the profile's configuration file on-disk. */ Path, /** (QString) The descriptive name of this profile. */ Name, /** (QString) The untranslated name of this profile. * Warning: this is an internal property. Do not touch it. */ UntranslatedName, /** (QString) The name of the icon associated with this profile. * This is used in menus and tabs to represent the profile. */ Icon, /** (QString) The command to execute ( excluding arguments ) when * creating a new terminal session using this profile. */ Command, /** (QStringList) The arguments which are passed to the program * specified by the Command property when creating a new terminal * session using this profile. */ Arguments, /** (QStringList) Additional environment variables (in the form of * NAME=VALUE pairs) which are passed to the program specified by * the Command property when creating a new terminal session using * this profile. */ Environment, /** (QString) The initial working directory for sessions created * using this profile. */ Directory, /** (QString) The format used for tab titles when running normal * commands. */ LocalTabTitleFormat, /** (QString) The format used for tab titles when the session is * running a remote command (eg. SSH) */ RemoteTabTitleFormat, /** (bool) Specifies whether show hint for terminal size after * resizing the application window. */ ShowTerminalSizeHint, /** (bool) If the background color should change to indicate if the window is active */ DimWhenInactive, /** (QFont) The font to use in terminal displays using this profile. */ Font, /** (QString) The name of the color scheme to use in terminal * displays using this profile. * Color schemes are managed by the ColorSchemeManager class. */ ColorScheme, /** (QString) The name of the key bindings. * Key bindings are managed by the KeyboardTranslatorManager class. */ KeyBindings, /** (HistoryModeEnum) Specifies the storage type used for keeping * the output produced by terminal sessions using this profile. * * See Enum::HistoryModeEnum */ HistoryMode, /** (int) Specifies the number of lines of output to remember in * terminal sessions using this profile. Once the limit is reached, * the oldest lines are lost if the HistoryMode property is * FixedSizeHistory */ HistorySize, /** (ScrollBarPositionEnum) Specifies the position of the scroll bar * in terminal displays using this profile. * * See Enum::ScrollBarPositionEnum */ ScrollBarPosition, /** (bool) Specifies whether the PageUp/Down will scroll the full * height or half height. */ ScrollFullPage, /** (bool) Specifies whether the terminal will enable Bidirectional * text display */ BidiRenderingEnabled, /** (bool) Specifies whether text in terminal displays is allowed * to blink. */ BlinkingTextEnabled, /** (bool) Specifies whether the flow control keys (typically Ctrl+S, * Ctrl+Q) have any effect. Also known as Xon/Xoff */ FlowControlEnabled, /** (int) Specifies the pixels between the terminal lines. */ LineSpacing, /** (bool) Specifies whether the cursor blinks ( in a manner similar * to text editing applications ) */ BlinkingCursorEnabled, /** (bool) If true, terminal displays use a fixed color to draw the * cursor, specified by the CustomCursorColor property. Otherwise * the cursor changes color to match the character underneath it. */ UseCustomCursorColor, /** (CursorShapeEnum) The shape used by terminal displays to * represent the cursor. * * See Enum::CursorShapeEnum */ CursorShape, /** (QColor) The color used by terminal displays to draw the cursor. * Only applicable if the UseCustomCursorColor property is true. */ CustomCursorColor, /** (QString) A string consisting of the characters used to delimit * words when selecting text in the terminal display. */ WordCharacters, /** (TripleClickModeEnum) Specifies which part of current line should * be selected with triple click action. * * See Enum::TripleClickModeEnum */ TripleClickMode, /** (bool) If true, text that matches a link or an email address is * underlined when hovered by the mouse pointer. */ UnderlineLinksEnabled, /** (bool) If true, text that matches a file is * underlined when hovered by the mouse pointer. */ UnderlineFilesEnabled, /** (bool) If true, links can be opened by direct mouse click.*/ OpenLinksByDirectClickEnabled, /** (bool) If true, control key must be pressed to click and drag selected text. */ CtrlRequiredForDrag, /** (bool) If true, automatically copy selected text into the clipboard */ AutoCopySelectedText, /** (bool) The QMimeData object used when copying text always * has the plain/text MIME set and if this is @c true then the * text/html MIME is set too in that object i.e. the copied * text will include formatting, font faces, colors... etc; users * can paste the text as HTML (default) or as plain/text by using * e.g. the "Paste Special" functionality in LibreOffice. */ CopyTextAsHTML, /** (bool) If true, leading spaces are trimmed in selected text */ TrimLeadingSpacesInSelectedText, /** (bool) If true, trailing spaces are trimmed in selected text */ TrimTrailingSpacesInSelectedText, /** (bool) If true, then dropped URLs will be pasted as text without asking */ DropUrlsAsText, /** (bool) If true, middle mouse button pastes from X Selection */ PasteFromSelectionEnabled, /** (bool) If true, middle mouse button pastes from Clipboard */ PasteFromClipboardEnabled, /** (MiddleClickPasteModeEnum) Specifies the source from which mouse * middle click pastes data. * * See Enum::MiddleClickPasteModeEnum */ MiddleClickPasteMode, /** (String) Default text codec */ DefaultEncoding, /** (bool) Whether fonts should be aliased or not */ AntiAliasFonts, /** (bool) Whether character with intense colors should be rendered * in bold font or just in bright color. */ BoldIntense, /** (bool) Whether to use font's line characters instead of the * builtin code. */ UseFontLineCharacters, /** (bool) Whether new sessions should be started in the same * directory as the currently active session. */ StartInCurrentSessionDir, /** (int) Specifies the threshold of detected silence in seconds. */ SilenceSeconds, /** (BellModeEnum) Specifies the behavior of bell. * * See Enum::BellModeEnum */ BellMode, /** (int) Specifies the preferred columns. */ TerminalColumns, /** (int) Specifies the preferred rows. */ TerminalRows, /** Index of profile in the File Menu * WARNING: this is currently an internal field, which is * expected to be zero on disk. Do not modify it manually. * * In future, the format might be #.#.# to account for levels */ MenuIndex, /** (int) Margin width in pixels */ TerminalMargin, /** (bool) Center terminal when there is a margin */ TerminalCenter, /** (bool) If true, mouse wheel scroll with Ctrl key pressed * increases/decreases the terminal font size. */ MouseWheelZoomEnabled, /** (bool) Specifies whether emulated up/down key press events are * sent, for mouse scroll wheel events, to programs using the * Alternate Screen buffer; this is mainly for the benefit of * programs that don't natively support mouse scroll events, e.g. * less. * * This also works for scrolling in applications that support Mouse * Tracking events but don't indicate they're interested in those * events; for example, when vim doesn't indicate it's interested * in Mouse Tracking events (i.e. when the mouse is in Normal * (not Visual) mode): https://vimhelp.org/intro.txt.html#vim-modes-intro * mouse wheel scroll events will send up/down key press events. * * Default value is true. * See also, MODE_Mouse1007 in the Emulation header, which toggles * Alternate Scrolling with escape sequences. */ AlternateScrolling, /** (int) Keyboard modifiers to show URL hints */ UrlHintsModifiers, /** (bool) Reverse the order of URL hints */ ReverseUrlHints }; Q_ENUM(Property) /** * Constructs a new profile * * @param parent The parent profile. When querying the value of a * property using property(), if the property has not been set in this * profile then the parent's value for the property will be returned. */ explicit Profile(const Ptr &parent = Ptr()); virtual ~Profile(); /** * Copies all properties except Name and Path from the specified @p * profile into this profile * * @param profile The profile to copy properties from * @param differentOnly If true, only properties in @p profile which have * a different value from this profile's current value (either set via * setProperty() or inherited from the parent profile) will be set. */ void clone(Ptr profile, bool differentOnly = true); /** * A profile which contains a number of default settings for various * properties. This can be used as a parent for other profiles or a * fallback in case a profile cannot be loaded from disk. */ void useFallback(); /** * Changes the parent profile. When calling the property() method, * if the specified property has not been set for this profile, * the parent's value for the property will be returned instead. */ void setParent(const Ptr &parent); /** Returns the parent profile. */ const Ptr parent() const; /** Returns this profile as a group or null if this profile is not a * group. */ const GroupPtr asGroup() const; GroupPtr asGroup(); /** * Returns the current value of the specified @p property, cast to type T. * Internally properties are stored using the QVariant type and cast to T * using QVariant::value(); * * If the specified @p property has not been set in this profile, * and a non-null parent was specified in the Profile's constructor, * the parent's value for @p property will be returned. */ template T property(Property p) const; /** Sets the value of the specified @p property to @p value. */ virtual void setProperty(Property p, const QVariant &value); /** Returns true if the specified property has been set in this Profile * instance. */ virtual bool isPropertySet(Property p) const; /** Returns a map of the properties set in this Profile instance. */ virtual QHash setProperties() const; /** Returns true if no properties have been set in this Profile instance. */ bool isEmpty() const; /** * Returns true if this is a 'hidden' profile which should not be * displayed in menus or saved to disk. * * This is used for the fallback profile, in case there are no profiles on * disk which can be loaded, or for overlay profiles created to handle * command-line arguments which change profile properties. */ bool isHidden() const; /** Specifies whether this is a hidden profile. See isHidden() */ void setHidden(bool hidden); // // Convenience methods for property() and setProperty() go here // /** Convenience method for property(Profile::Path) */ QString path() const { return property(Profile::Path); } /** Convenience method for property(Profile::Name) */ QString name() const { return property(Profile::Name); } /** Convenience method for property(Profile::UntranslatedName) */ QString untranslatedName() const { return property(Profile::UntranslatedName); } /** Convenience method for property(Profile::Directory) */ QString defaultWorkingDirectory() const { return property(Profile::Directory); } /** Convenience method for property(Profile::Icon) */ QString icon() const { return property(Profile::Icon); } /** Convenience method for property(Profile::Command) */ QString command() const { return property(Profile::Command); } /** Convenience method for property(Profile::Arguments) */ QStringList arguments() const { return property(Profile::Arguments); } /** Convenience method for property(Profile::LocalTabTitleFormat) */ QString localTabTitleFormat() const { return property(Profile::LocalTabTitleFormat); } /** Convenience method for property(Profile::RemoteTabTitleFormat) */ QString remoteTabTitleFormat() const { return property(Profile::RemoteTabTitleFormat); } /** Convenience method for property(Profile::ShowTerminalSizeHint) */ bool showTerminalSizeHint() const { return property(Profile::ShowTerminalSizeHint); } /** Convenience method for property(Profile::DimWhenInactive) */ bool dimWhenInactive() const { return property(Profile::DimWhenInactive); } /** Convenience method for property(Profile::Font) */ QFont font() const { return property(Profile::Font); } /** Convenience method for property(Profile::ColorScheme) */ QString colorScheme() const { return property(Profile::ColorScheme); } /** Convenience method for property(Profile::Environment) */ QStringList environment() const { return property(Profile::Environment); } /** Convenience method for property(Profile::KeyBindings) */ QString keyBindings() const { return property(Profile::KeyBindings); } /** Convenience method for property(Profile::HistorySize) */ int historySize() const { return property(Profile::HistorySize); } /** Convenience method for property(Profile::BidiRenderingEnabled) */ bool bidiRenderingEnabled() const { return property(Profile::BidiRenderingEnabled); } /** Convenience method for property(Profile::LineSpacing) */ int lineSpacing() const { return property(Profile::LineSpacing); } /** Convenience method for property(Profile::BlinkingTextEnabled) */ bool blinkingTextEnabled() const { return property(Profile::BlinkingTextEnabled); } /** Convenience method for property(Profile::MouseWheelZoomEnabled) */ bool mouseWheelZoomEnabled() const { return property(Profile::MouseWheelZoomEnabled); } /** Convenience method for property(Profile::BlinkingCursorEnabled) */ bool blinkingCursorEnabled() const { return property(Profile::BlinkingCursorEnabled); } /** Convenience method for property(Profile::FlowControlEnabled) */ bool flowControlEnabled() const { return property(Profile::FlowControlEnabled); } /** Convenience method for property(Profile::UseCustomCursorColor) */ bool useCustomCursorColor() const { return property(Profile::UseCustomCursorColor); } /** Convenience method for property(Profile::CustomCursorColor) */ QColor customCursorColor() const { return property(Profile::CustomCursorColor); } /** Convenience method for property(Profile::WordCharacters) */ QString wordCharacters() const { return property(Profile::WordCharacters); } /** Convenience method for property(Profile::UnderlineLinksEnabled) */ bool underlineLinksEnabled() const { return property(Profile::UnderlineLinksEnabled); } /** Convenience method for property(Profile::UnderlineFilesEnabled) */ bool underlineFilesEnabled() const { return property(Profile::UnderlineFilesEnabled); } bool autoCopySelectedText() const { return property(Profile::AutoCopySelectedText); } /** Convenience method for property(Profile::DefaultEncoding) */ QString defaultEncoding() const { return property(Profile::DefaultEncoding); } /** Convenience method for property(Profile::AntiAliasFonts) */ bool antiAliasFonts() const { return property(Profile::AntiAliasFonts); } /** Convenience method for property(Profile::BoldIntense) */ bool boldIntense() const { return property(Profile::BoldIntense); } /** Convenience method for property(Profile::UseFontLineCharacters)*/ bool useFontLineCharacters() const { return property(Profile::UseFontLineCharacters); } /** Convenience method for property(Profile::StartInCurrentSessionDir) */ bool startInCurrentSessionDir() const { return property(Profile::StartInCurrentSessionDir); } /** Convenience method for property(Profile::SilenceSeconds) */ int silenceSeconds() const { return property(Profile::SilenceSeconds); } /** Convenience method for property(Profile::TerminalColumns) */ int terminalColumns() const { return property(Profile::TerminalColumns); } /** Convenience method for property(Profile::TerminalRows) */ int terminalRows() const { return property(Profile::TerminalRows); } /** Convenience method for property(Profile::TerminalMargin) */ int terminalMargin() const { return property(Profile::TerminalMargin); } /** Convenience method for property(Profile::TerminalCenter) */ bool terminalCenter() const { return property(Profile::TerminalCenter); } /** Convenience method for property(Profile::MenuIndex) */ QString menuIndex() const { return property(Profile::MenuIndex); } int menuIndexAsInt() const; /** Return a list of all properties names and their type * (for use with -p option). */ const QStringList propertiesInfoList() const; /** * Returns the element from the Property enum associated with the * specified @p name. * * @param name The name of the property to look for, this is case * insensitive. */ static Property lookupByName(const QString &name); private: struct PropertyInfo; // Defines a new property, this property is then available // to all Profile instances. static void registerProperty(const PropertyInfo &info); // fills the table with default names for profile properties // the first time it is called. // subsequent calls return immediately static void fillTableWithDefaultNames(); // returns true if the property can be inherited static bool canInheritProperty(Property p); QHash _propertyValues; Ptr _parent; bool _hidden; static QHash PropertyInfoByName; static QHash PropertyInfoByProperty; // Describes a property. Each property has a name and group // which is used when saving/loading the profile. struct PropertyInfo { Property property; const char *name; const char *group; QVariant::Type type; }; static const PropertyInfo DefaultPropertyNames[]; }; inline bool Profile::canInheritProperty(Property p) { return p != Name && p != Path; } template inline T Profile::property(Property p) const { return property(p).value(); } template<> inline QVariant Profile::property(Property p) const { if (_propertyValues.contains(p)) { return _propertyValues[p]; } else if (_parent && canInheritProperty(p)) { return _parent->property(p); } else { return QVariant(); } } /** * A composite profile which allows a group of profiles to be treated as one. * When setting a property, the new value is applied to all profiles in the * group. When reading a property, if all profiles in the group have the same * value then that value is returned, otherwise the result is null. * * Profiles can be added to the group using addProfile(). When all profiles * have been added updateValues() must be called * to sync the group's property values with those of the group's profiles. * * The Profile::Name and Profile::Path properties are unique to individual * profiles, setting these properties on a ProfileGroup has no effect. */ class KONSOLEPRIVATE_EXPORT ProfileGroup : public Profile { public: using Ptr = QExplicitlySharedDataPointer; /** Construct a new profile group, which is hidden by default. */ explicit ProfileGroup(const Profile::Ptr &profileParent = Profile::Ptr()); /** Add a profile to the group. Calling setProperty() will update this * profile. When creating a group, add the profiles to the group then * call updateValues() to make the group's property values reflect the * profiles currently in the group. */ void addProfile(const Profile::Ptr &profile) { _profiles.append(profile); } /** Remove a profile from the group. Calling setProperty() will no longer * affect this profile. */ void removeProfile(const Profile::Ptr &profile) { _profiles.removeAll(profile); } /** Returns the profiles in this group .*/ QList profiles() const { return _profiles; } /** * Updates the property values in this ProfileGroup to match those from * the group's profiles() * * For each available property, if each profile in the group has the same * value then the ProfileGroup will use that value for the property. * Otherwise the value for the property will be set to a null QVariant * * Some properties such as the name and the path of the profile * will always be set to null if the group has more than one profile. */ void updateValues(); /** Sets the value of @p property in each of the group's profiles to * @p value. */ - void setProperty(Property p, const QVariant &value) Q_DECL_OVERRIDE; + void setProperty(Property p, const QVariant &value) override; private: Q_DISABLE_COPY(ProfileGroup) QList _profiles; }; inline ProfileGroup::ProfileGroup(const Profile::Ptr &profileParent) : Profile(profileParent), _profiles(QList()) { setHidden(true); } inline const Profile::GroupPtr Profile::asGroup() const { const Profile::GroupPtr ptr(dynamic_cast( const_cast(this))); return ptr; } inline Profile::GroupPtr Profile::asGroup() { return Profile::GroupPtr(dynamic_cast(this)); } /** * Parses an input string consisting of property names * and assigned values and returns a table of properties * and values. * * The input string will typically look like this: * * @code * PropertyName=Value;PropertyName=Value ... * @endcode * * For example: * * @code * Icon=konsole;Directory=/home/bob * @endcode */ class KONSOLEPRIVATE_EXPORT ProfileCommandParser { public: /** * Parses an input string consisting of property names * and assigned values and returns a table of * properties and values. */ QHash parse(const QString &input); }; } Q_DECLARE_METATYPE(Konsole::Profile::Ptr) #endif // PROFILE_H diff --git a/src/ProfileManager.h b/src/ProfileManager.h index 2a117f1c..69d39577 100644 --- a/src/ProfileManager.h +++ b/src/ProfileManager.h @@ -1,323 +1,323 @@ /* This source file is part of Konsole, a terminal emulator. Copyright 2006-2008 by Robert Knight This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #ifndef PROFILEMANAGER_H #define PROFILEMANAGER_H // Qt #include #include #include #include #include #include #include // Konsole #include "Profile.h" namespace Konsole { /** * Manages profiles which specify various settings for terminal sessions * and their displays. * * Profiles in the manager have a concept of favorite status, which can be used * by widgets and dialogs in the application decide which profiles to list and * how to display them. The favorite status of a profile can be altered using * setFavorite() and retrieved using isFavorite() */ class KONSOLEPRIVATE_EXPORT ProfileManager : public QObject { Q_OBJECT public: /** * Constructs a new profile manager and loads information about the available * profiles. */ ProfileManager(); /** * Destroys the ProfileManager. */ - ~ProfileManager() Q_DECL_OVERRIDE; + ~ProfileManager() override; /** * Returns the profile manager instance. */ static ProfileManager *instance(); /** * Returns a list of all available profiles * * Initially only the profile currently set as the default is loaded. * * Favorite profiles are loaded automatically when findFavorites() is called. * * When this method is called, it calls loadAllProfiles() internally to * ensure all available profiles are loaded and usable. */ QList allProfiles(); /** * Returns a list of already loaded profiles */ QList loadedProfiles() const; /** * Loads all available profiles. This involves reading each * profile configuration file from disk and parsing it. * Therefore it should only be done when necessary. */ void loadAllProfiles(); /** * Loads a profile from the specified path and registers * it with the ProfileManager. * * @p path may be relative or absolute. The path may just be the * base name of the profile to load (eg. if the profile's full path * is "/My Profile.profile" then both * "konsole/My Profile.profile" , "My Profile.profile" and * "My Profile" will be accepted) * * @return Pointer to a profile which can be passed to * SessionManager::createSession() to create a new session using * this profile. */ Profile::Ptr loadProfile(const QString &shortPath); /** * Searches for available profiles on-disk and returns a list * of paths of profiles which can be loaded. */ QStringList availableProfilePaths() const; /** * Returns a list of names of all available profiles */ QStringList availableProfileNames() const; /** * Registers a new type of session. * The favorite status of the session ( as returned by isFavorite() ) is set to false by default. */ void addProfile(const Profile::Ptr &profile); /** * Deletes the configuration file used to store a profile. * The profile will continue to exist while sessions are still using it. The profile * will be marked as hidden (see Profile::setHidden() ) so that it does not show * up in profile lists and future changes to the profile are not stored to disk. * * Returns true if the profile was successfully deleted or false otherwise. */ bool deleteProfile(Profile::Ptr profile); /** * Updates a @p profile with the changes specified in @p propertyMap. * * All sessions currently using the profile will be updated to reflect the new settings. * * After the profile is updated, the profileChanged() signal will be emitted. * * @param profile The profile to change * @param propertyMap A map between profile properties and values describing the changes * @param persistent If true, the changes are saved to the profile's configuration file, * set this to false if you want to preview possible changes to a profile but do not * wish to make them permanent. */ void changeProfile(Profile::Ptr profile, QHash propertyMap, bool persistent = true); /** * Sets the @p profile as the default profile for creating new sessions */ void setDefaultProfile(const Profile::Ptr &profile); /** * Returns a Profile object describing the default profile */ Profile::Ptr defaultProfile() const; /** * Returns a Profile object with hard-coded settings which is always available. * This can be used as a parent for new profiles which provides suitable default settings * for all properties. */ Profile::Ptr fallbackProfile() const; /** * Specifies whether a profile should be included in the user's * list of favorite profiles. */ void setFavorite(const Profile::Ptr &profile, bool favorite); /** * Returns the set of the user's favorite profiles. */ QSet findFavorites(); QList sortedFavorites(); /** * Sorts the profile list by menuindex; those without an menuindex, sort by name. * The menuindex list is first and then the non-menuindex list. * * @param list The profile list to sort */ void sortProfiles(QList &list); /** * Associates a shortcut with a particular profile. */ void setShortcut(Profile::Ptr profile, const QKeySequence &keySequence); /** Returns the shortcut associated with a particular profile. */ QKeySequence shortcut(Profile::Ptr profile) const; /** * Returns the list of shortcut key sequences which * can be used to create new sessions based on * existing profiles * * When one of the shortcuts is activated, * use findByShortcut() to load the profile associated * with the shortcut. */ QList shortcuts(); /** * Finds and loads the profile associated with * the specified @p shortcut key sequence and returns a pointer to it. */ Profile::Ptr findByShortcut(const QKeySequence &shortcut); Q_SIGNALS: /** Emitted when a profile is added to the manager. */ void profileAdded(const Profile::Ptr &ptr); /** Emitted when a profile is removed from the manager. */ void profileRemoved(const Profile::Ptr &ptr); /** Emitted when a profile's properties are modified. */ void profileChanged(const Profile::Ptr &ptr); /** * Emitted when the favorite status of a profile changes. * * @param profile The profile to change * @param favorite Specifies whether the profile is a favorite or not */ void favoriteStatusChanged(const Profile::Ptr &profile, bool favorite); /** * Emitted when the shortcut for a profile is changed. * * @param profile The profile whose status was changed * @param newShortcut The new shortcut key sequence for the profile */ void shortcutChanged(const Profile::Ptr &profile, const QKeySequence &newShortcut); public Q_SLOTS: /** Saves settings (favorites, shortcuts, default profile etc.) to disk. */ void saveSettings(); protected Q_SLOTS: private Q_SLOTS: private: Q_DISABLE_COPY(ProfileManager) // loads the mappings between shortcut key sequences and // profile paths void loadShortcuts(); // saves the mappings between shortcut key sequences and // profile paths void saveShortcuts(); //loads the set of favorite profiles void loadFavorites(); //saves the set of favorite profiles void saveFavorites(); // records which profile is set as the default profile // Note: it does not save the profile itself into disk. That is // what saveProfile() does. void saveDefaultProfile(); // saves a profile to a file // returns the path to which the profile was saved, which will // be the same as the path property of profile if valid or a newly generated path // otherwise QString saveProfile(const Profile::Ptr &profile); QSet _profiles; // list of all loaded profiles QSet _favorites; // list of favorite profiles Profile::Ptr _defaultProfile; Profile::Ptr _fallbackProfile; bool _loadedAllProfiles; // set to true after loadAllProfiles has been called bool _loadedFavorites; // set to true after loadFavorites has been called struct ShortcutData { Profile::Ptr profileKey; QString profilePath; }; QMap _shortcuts; // shortcut keys -> profile path // finds out if it's a internal profile or an external one, // fixing the path to point to the correct location for the profile. QString normalizePath(const QString& path) const; }; /** * PopStackOnExit is a utility to remove all values from a QStack which are added during * the lifetime of a PopStackOnExit instance. * * When a PopStackOnExit instance is destroyed, elements are removed from the stack * until the stack count is reduced the value when the PopStackOnExit instance was created. */ template class PopStackOnExit { public: explicit PopStackOnExit(QStack &stack) : _stack(stack), _count(stack.count()) { } ~PopStackOnExit() { while (_stack.count() > _count) { _stack.pop(); } } private: Q_DISABLE_COPY(PopStackOnExit) QStack &_stack; int _count; }; } #endif //PROFILEMANAGER_H diff --git a/src/Pty.h b/src/Pty.h index 7a79d97c..6cbee2e5 100644 --- a/src/Pty.h +++ b/src/Pty.h @@ -1,191 +1,191 @@ /* This file is part of Konsole, KDE's terminal emulator. Copyright 2007-2008 by Robert Knight Copyright 1997,1998 by Lars Doelle This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #ifndef PTY_H #define PTY_H // Qt #include // KDE #include // Konsole #include "konsoleprivate_export.h" class QStringList; namespace Konsole { /** * The Pty class is used to start the terminal process, * send data to it, receive data from it and manipulate * various properties of the pseudo-teletype interface * used to communicate with the process. * * To use this class, construct an instance and connect * to the sendData slot and receivedData signal to * send data to or receive data from the process. * * To start the terminal process, call the start() method * with the program name and appropriate arguments. */ class KONSOLEPRIVATE_EXPORT Pty : public KPtyProcess { Q_OBJECT public: /** * Constructs a new Pty. * * Connect to the sendData() slot and receivedData() signal to prepare * for sending and receiving data from the terminal process. * * To start the terminal process, call the run() method with the * name of the program to start and appropriate arguments. */ explicit Pty(QObject *parent = nullptr); /** * Construct a process using an open pty master. * See KPtyProcess::KPtyProcess() */ explicit Pty(int ptyMasterFd, QObject *parent = nullptr); - ~Pty() Q_DECL_OVERRIDE; + ~Pty() override; /** * Starts the terminal process. * * Returns 0 if the process was started successfully or non-zero * otherwise. * * @param program Path to the program to start * @param arguments Arguments to pass to the program being started * @param environment A list of key=value pairs which will be added * to the environment for the new process. At the very least this * should include an assignment for the TERM environment variable. */ int start(const QString &program, const QStringList &arguments, const QStringList &environment); /** Control whether the pty device is writeable by group members. */ void setWriteable(bool writeable); /** * Enables or disables Xon/Xoff flow control. The flow control setting * may be changed later by a terminal application, so flowControlEnabled() * may not equal the value of @p on in the previous call to setFlowControlEnabled() */ void setFlowControlEnabled(bool on); /** Queries the terminal state and returns true if Xon/Xoff flow control is enabled. */ bool flowControlEnabled() const; /** * Sets the size of the window (in columns and lines of characters) * used by this teletype. */ void setWindowSize(int columns, int lines); /** Returns the size of the window used by this teletype. See setWindowSize() */ QSize windowSize() const; /** * Sets the special character for erasing previous not-yet-erased character. * See termios(3) for detailed description. */ void setEraseChar(char eraseChar); /** */ char eraseChar() const; /** * Sets the initial working directory. */ void setInitialWorkingDirectory(const QString &dir); /** * Returns the process id of the teletype's current foreground * process. This is the process which is currently reading * input sent to the terminal via. sendData() * * If there is a problem reading the foreground process group, * 0 will be returned. */ int foregroundProcessGroup() const; /** * Close the underlying pty master/slave pair. */ void closePty(); /** * Sends EOF to the controlled process, this is the preferred method of telling e. g. bash to close */ void sendEof(); public Q_SLOTS: /** * Put the pty into UTF-8 mode on systems which support it. */ void setUtf8Mode(bool on); /** * Sends data to the process currently controlling the * teletype ( whose id is returned by foregroundProcessGroup() ) * * @param data the data to send. */ void sendData(const QByteArray &data); Q_SIGNALS: /** * Emitted when a new block of data is received from * the teletype. * * @param buffer Pointer to the data received. * @param length Length of @p buffer */ void receivedData(const char *buffer, int length); protected: - void setupChildProcess() Q_DECL_OVERRIDE; + void setupChildProcess() override; private Q_SLOTS: // called when data is received from the terminal process void dataReceived(); private: void init(); // takes a list of key=value pairs and adds them // to the environment for the process void addEnvironmentVariables(const QStringList &environment); int _windowColumns; int _windowLines; char _eraseChar; bool _xonXoff; bool _utf8; }; } #endif // PTY_H diff --git a/src/RenameTabDialog.h b/src/RenameTabDialog.h index 05313875..c8922c11 100644 --- a/src/RenameTabDialog.h +++ b/src/RenameTabDialog.h @@ -1,54 +1,54 @@ /* Copyright 2010 by Kurt Hindenburg This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #ifndef RENAMETABDIALOG_H #define RENAMETABDIALOG_H // KDE #include namespace Ui { class RenameTabDialog; } namespace Konsole { class RenameTabDialog : public QDialog { Q_OBJECT public: explicit RenameTabDialog(QWidget *parent = nullptr); - ~RenameTabDialog() Q_DECL_OVERRIDE; + ~RenameTabDialog() override; QString tabTitleText() const; QString remoteTabTitleText() const; void setTabTitleText(const QString &); void setRemoteTabTitleText(const QString &); void focusTabTitleText(); void focusRemoteTabTitleText(); private: Q_DISABLE_COPY(RenameTabDialog) Ui::RenameTabDialog *_ui; }; } #endif diff --git a/src/RenameTabWidget.h b/src/RenameTabWidget.h index 5739e1c0..60cd3981 100644 --- a/src/RenameTabWidget.h +++ b/src/RenameTabWidget.h @@ -1,60 +1,60 @@ /* Copyright 2010 by Kurt Hindenburg This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #ifndef RENAMETABWIDGET_H #define RENAMETABWIDGET_H // Qt #include namespace Ui { class RenameTabWidget; } namespace Konsole { class RenameTabWidget : public QWidget { Q_OBJECT public: explicit RenameTabWidget(QWidget *parent = nullptr); - ~RenameTabWidget() Q_DECL_OVERRIDE; + ~RenameTabWidget() override; QString tabTitleText() const; QString remoteTabTitleText() const; void setTabTitleText(const QString &); void setRemoteTabTitleText(const QString &); void focusTabTitleText(); void focusRemoteTabTitleText(); Q_SIGNALS: void tabTitleFormatChanged(const QString &); void remoteTabTitleFormatChanged(const QString &); public Q_SLOTS: void insertTabTitleText(const QString &text); void insertRemoteTabTitleText(const QString &text); private: Ui::RenameTabWidget *_ui; }; } #endif diff --git a/src/SaveHistoryTask.h b/src/SaveHistoryTask.h index 65504d6f..1359edb1 100644 --- a/src/SaveHistoryTask.h +++ b/src/SaveHistoryTask.h @@ -1,77 +1,77 @@ /* Copyright 2006-2008 by Robert Knight Copyright 2009 by Thomas Dreibholz This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #ifndef SAVEHISTORYTASK_H #define SAVEHISTORYTASK_H #include "SessionTask.h" #include "TerminalCharacterDecoder.h" #include namespace Konsole { /** * A task which prompts for a URL for each session and saves that session's output * to the given URL */ class SaveHistoryTask : public SessionTask { Q_OBJECT public: /** Constructs a new task to save session output to URLs */ explicit SaveHistoryTask(QObject *parent = nullptr); - ~SaveHistoryTask() Q_DECL_OVERRIDE; + ~SaveHistoryTask() override; /** * Opens a save file dialog for each session in the group and begins saving * each session's history to the given URL. * * The data transfer is performed asynchronously and will continue after execute() returns. */ - void execute() Q_DECL_OVERRIDE; + void execute() override; private Q_SLOTS: void jobDataRequested(KIO::Job *job, QByteArray &data); void jobResult(KJob *job); private: class SaveJob // structure to keep information needed to process // incoming data requests from jobs { public: QPointer session; // the session associated with a history save job int lastLineFetched; // the last line processed in the previous data request // set this to -1 at the start of the save job TerminalCharacterDecoder *decoder; // decoder used to convert terminal characters // into output }; QHash _jobSession; static QString _saveDialogRecentURL; }; } #endif diff --git a/src/ScreenWindow.h b/src/ScreenWindow.h index 8be16990..a3738975 100644 --- a/src/ScreenWindow.h +++ b/src/ScreenWindow.h @@ -1,279 +1,279 @@ /* Copyright 2007-2008 by Robert Knight This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #ifndef SCREENWINDOW_H #define SCREENWINDOW_H // Qt #include #include #include // Konsole #include "Character.h" #include "Screen.h" namespace Konsole { /** * Provides a window onto a section of a terminal screen. A terminal widget can then render * the contents of the window and use the window to change the terminal screen's selection * in response to mouse or keyboard input. * * A new ScreenWindow for a terminal session can be created by calling Emulation::createWindow() * * Use the scrollTo() method to scroll the window up and down on the screen. * Use the getImage() method to retrieve the character image which is currently visible in the window. * * setTrackOutput() controls whether the window moves to the bottom of the associated screen when new * lines are added to it. * * Whenever the output from the underlying screen is changed, the notifyOutputChanged() slot should * be called. This in turn will update the window's position and emit the outputChanged() signal * if necessary. */ class ScreenWindow : public QObject { Q_OBJECT public: /** * Constructs a new screen window with the given parent. * A screen must be specified by calling setScreen() before calling getImage() or getLineProperties(). * * You should not call this constructor directly, instead use the Emulation::createWindow() method * to create a window on the emulation which you wish to view. This allows the emulation * to notify the window when the associated screen has changed and synchronize selection updates * between all views on a session. */ explicit ScreenWindow(Screen *screen, QObject *parent = nullptr); - ~ScreenWindow() Q_DECL_OVERRIDE; + ~ScreenWindow() override; /** Sets the screen which this window looks onto */ void setScreen(Screen *screen); /** Returns the screen which this window looks onto */ Screen *screen() const; /** * Returns the image of characters which are currently visible through this window * onto the screen. * * The returned buffer is managed by the ScreenWindow instance and does not need to be * deleted by the caller. */ Character *getImage(); /** * Returns the line attributes associated with the lines of characters which * are currently visible through this window */ QVector getLineProperties(); /** * Returns the number of lines which the region of the window * specified by scrollRegion() has been scrolled by since the last call * to resetScrollCount(). scrollRegion() is in most cases the * whole window, but will be a smaller area in, for example, applications * which provide split-screen facilities. * * This is not guaranteed to be accurate, but allows views to optimize * rendering by reducing the amount of costly text rendering that * needs to be done when the output is scrolled. */ int scrollCount() const; /** * Resets the count of scrolled lines returned by scrollCount() */ void resetScrollCount(); /** * Returns the area of the window which was last scrolled, this is * usually the whole window area. * * Like scrollCount(), this is not guaranteed to be accurate, * but allows views to optimize rendering. */ QRect scrollRegion() const; /** * What line the next search will start from */ void setCurrentResultLine(int line); int currentResultLine() const; /** * Sets the start of the selection to the given @p line and @p column within * the window. */ void setSelectionStart(int column, int line, bool columnMode); /** * Sets the end of the selection to the given @p line and @p column within * the window. */ void setSelectionEnd(int column, int line); /** * Sets the selection as the range specified by line @p start and line @p * end in the whole history. * * Both @p start and @p end are absolute line number in the whole history, * not relative line number in the window. This make it possible to select * range larger than the window . A good use case is selecting the whole * history. */ void setSelectionByLineRange(int start, int end); /** * Retrieves the start of the selection within the window. */ void getSelectionStart(int &column, int &line); /** * Retrieves the end of the selection within the window. */ void getSelectionEnd(int &column, int &line); /** * Returns true if the character at @p line , @p column is part of the selection. */ bool isSelected(int column, int line); /** * Clears the current selection */ void clearSelection(); /** Sets the number of lines in the window */ void setWindowLines(int lines); /** Returns the number of lines in the window */ int windowLines() const; /** Returns the number of columns in the window */ int windowColumns() const; /** Returns the total number of lines in the screen */ int lineCount() const; /** Returns the total number of columns in the screen */ int columnCount() const; /** Returns the index of the line which is currently at the top of this window */ int currentLine() const; /** * Returns the position of the cursor * within the window. */ QPoint cursorPosition() const; /** * Convenience method. Returns true if the window is currently at the bottom * of the screen. */ bool atEndOfOutput() const; /** Scrolls the window so that @p line is at the top of the window */ void scrollTo(int line); /** Describes the units which scrollBy() moves the window by. */ enum RelativeScrollMode { /** Scroll the window down by a given number of lines. */ ScrollLines, /** * Scroll the window down by a given number of pages, where * one page is windowLines() lines */ ScrollPages }; /** * Scrolls the window relative to its current position on the screen. * * @param mode Specifies whether @p amount refers to the number of lines or the number * of pages to scroll. * @param amount The number of lines or pages ( depending on @p mode ) to scroll by. If * this number is positive, the view is scrolled down. If this number is negative, the view * is scrolled up. * @param fullPage Specifies whether to scroll by full page or half page. */ void scrollBy(RelativeScrollMode mode, int amount, bool fullPage); /** * Specifies whether the window should automatically move to the bottom * of the screen when new output is added. * * If this is set to true, the window will be moved to the bottom of the associated screen ( see * screen() ) when the notifyOutputChanged() method is called. */ void setTrackOutput(bool trackOutput); /** * Returns whether the window automatically moves to the bottom of the screen as * new output is added. See setTrackOutput() */ bool trackOutput() const; /** * Returns the text which is currently selected. * * @param options See Screen::DecodingOptions */ QString selectedText(const Screen::DecodingOptions options) const; public Q_SLOTS: /** * Notifies the window that the contents of the associated terminal screen have changed. * This moves the window to the bottom of the screen if trackOutput() is true and causes * the outputChanged() signal to be emitted. */ void notifyOutputChanged(); Q_SIGNALS: /** * Emitted when the contents of the associated terminal screen (see screen()) changes. */ void outputChanged(); void currentResultLineChanged(); /** * Emitted when the screen window is scrolled to a different position. * * @param line The line which is now at the top of the window. */ void scrolled(int line); /** Emitted when the selection is changed. */ void selectionChanged(); private: Q_DISABLE_COPY(ScreenWindow) int endWindowLine() const; void fillUnusedArea(); Screen *_screen; // see setScreen() , screen() Character *_windowBuffer; int _windowBufferSize; bool _bufferNeedsUpdate; int _windowLines; int _currentLine; // see scrollTo() , currentLine() int _currentResultLine; bool _trackOutput; // see setTrackOutput() , trackOutput() int _scrollCount; // count of lines which the window has been scrolled by since // the last call to resetScrollCount() }; } #endif // SCREENWINDOW_H diff --git a/src/SearchHistoryTask.h b/src/SearchHistoryTask.h index 16d06fca..bdd0b24c 100644 --- a/src/SearchHistoryTask.h +++ b/src/SearchHistoryTask.h @@ -1,102 +1,102 @@ /* Copyright 2006-2008 by Robert Knight Copyright 2009 by Thomas Dreibholz This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #ifndef SEARCHHISTORYTASK_H #define SEARCHHISTORYTASK_H #include #include #include #include "SessionTask.h" #include "Enumeration.h" #include "ScreenWindow.h" #include "Session.h" namespace Konsole { //class SearchHistoryThread; /** * A task which searches through the output of sessions for matches for a given regular expression. * SearchHistoryTask operates on ScreenWindow instances rather than sessions added by addSession(). * A screen window can be added to the list to search using addScreenWindow() * * When execute() is called, the search begins in the direction specified by searchDirection(), * starting at the position of the current selection. * * FIXME - This is not a proper implementation of SessionTask, in that it ignores sessions specified * with addSession() * * TODO - Implementation requirements: * May provide progress feedback to the user when searching very large output logs. */ class SearchHistoryTask : public SessionTask { Q_OBJECT public: /** * Constructs a new search task. */ explicit SearchHistoryTask(QObject *parent = nullptr); /** Adds a screen window to the list to search when execute() is called. */ void addScreenWindow(Session *session, ScreenWindow *searchWindow); /** Sets the regular expression which is searched for when execute() is called */ void setRegExp(const QRegularExpression &expression); /** Returns the regular expression which is searched for when execute() is called */ QRegularExpression regExp() const; /** Specifies the direction to search in when execute() is called. */ void setSearchDirection(Enum::SearchDirection direction); /** Returns the current search direction. See setSearchDirection(). */ Enum::SearchDirection searchDirection() const; /** The line from which the search will be done **/ void setStartLine(int line); /** * Performs a search through the session's history, starting at the position * of the current selection, in the direction specified by setSearchDirection(). * * If it finds a match, the ScreenWindow specified in the constructor is * scrolled to the position where the match occurred and the selection * is set to the matching text. execute() then returns immediately. * * To continue the search looking for further matches, call execute() again. */ - void execute() Q_DECL_OVERRIDE; + void execute() override; private: using ScreenWindowPtr = QPointer; void executeOnScreenWindow(const QPointer &session, const ScreenWindowPtr& window); void highlightResult(const ScreenWindowPtr& window, int findPos); QMap< QPointer, ScreenWindowPtr > _windows; QRegularExpression _regExp; Enum::SearchDirection _direction; int _startLine; }; } #endif diff --git a/src/Session.h b/src/Session.h index 9d5ad6a2..b1a14bb4 100644 --- a/src/Session.h +++ b/src/Session.h @@ -1,904 +1,904 @@ /* This file is part of Konsole, an X terminal. Copyright 2007-2008 by Robert Knight Copyright 1997,1998 by Lars Doelle Copyright 2009 by Thomas Dreibholz This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #ifndef SESSION_H #define SESSION_H // Qt #include #include #include #include #include #include #include // Konsole #include "konsoleprivate_export.h" #include "config-konsole.h" #include "Shortcut_p.h" class QColor; class KConfigGroup; class KProcess; namespace Konsole { class Emulation; class Pty; class ProcessInfo; class TerminalDisplay; class ZModemDialog; class HistoryType; /** * Represents a terminal session consisting of a pseudo-teletype and a terminal emulation. * The pseudo-teletype (or PTY) handles I/O between the terminal process and Konsole. * The terminal emulation ( Emulation and subclasses ) processes the output stream from the * PTY and produces a character image which is then shown on views connected to the session. * * Each Session can be connected to one or more views by using the addView() method. * The attached views can then display output from the program running in the terminal * or send input to the program in the terminal in the form of keypresses and mouse * activity. */ class KONSOLEPRIVATE_EXPORT Session : public QObject { Q_OBJECT Q_CLASSINFO("D-Bus Interface", "org.kde.konsole.Session") public: Q_PROPERTY(QString name READ nameTitle) Q_PROPERTY(int processId READ processId) Q_PROPERTY(QString keyBindings READ keyBindings WRITE setKeyBindings) Q_PROPERTY(QSize size READ size WRITE setSize) /** * Constructs a new session. * * To start the terminal process, call the run() method, * after specifying the program and arguments * using setProgram() and setArguments() * * If no program or arguments are specified explicitly, the Session * falls back to using the program specified in the SHELL environment * variable. */ explicit Session(QObject *parent = nullptr); - ~Session() Q_DECL_OVERRIDE; + ~Session() override; /** * Connect to an existing terminal. When a new Session() is constructed it * automatically searches for and opens a new teletype. If you want to * use an existing teletype (given its file descriptor) call this after * constructing the session. * * Calling openTeletype() while a session is running has no effect. * * @param fd The file descriptor of the pseudo-teletype master (See KPtyProcess::KPtyProcess()) */ void openTeletype(int fd); /** * Returns true if the session is currently running. This will be true * after run() has been called successfully. */ bool isRunning() const; /** * Adds a new view for this session. * * The viewing widget will display the output from the terminal and * input from the viewing widget (key presses, mouse activity etc.) * will be sent to the terminal. * * Views can be removed using removeView(). The session is automatically * closed when the last view is removed. */ void addView(TerminalDisplay *widget); /** * Removes a view from this session. When the last view is removed, * the session will be closed automatically. * * @p widget will no longer display output from or send input * to the terminal */ void removeView(TerminalDisplay *widget); /** * Returns the views connected to this session */ QList views() const; /** * Returns the terminal emulation instance being used to encode / decode * characters to / from the process. */ Emulation *emulation() const; /** Returns the unique ID for this session. */ int sessionId() const; /** * This enum describes the contexts for which separate * tab title formats may be specified. */ enum TabTitleContext { /** Default tab title format */ LocalTabTitle, /** * Tab title format used session currently contains * a connection to a remote computer (via SSH) */ RemoteTabTitle }; /** * Returns true if the session currently contains a connection to a * remote computer. It currently supports ssh. */ bool isRemote(); /** * Sets the format used by this session for tab titles. * * @param context The context whose format should be set. * @param format The tab title format. This may be a mixture * of plain text and dynamic elements denoted by a '%' character * followed by a letter. (eg. %d for directory). The dynamic * elements available depend on the @p context */ void setTabTitleFormat(TabTitleContext context, const QString &format); /** Returns the format used by this session for tab titles. */ QString tabTitleFormat(TabTitleContext context) const; /** * Returns true if the tab title has been changed by the user via the * rename-tab dialog. */ bool isTabTitleSetByUser() const; /** Returns the arguments passed to the shell process when run() is called. */ QStringList arguments() const; /** Returns the program name of the shell process started when run() is called. */ QString program() const; /** * Sets the command line arguments which the session's program will be passed when * run() is called. */ void setArguments(const QStringList &arguments); /** Sets the program to be executed when run() is called. */ void setProgram(const QString &program); /** Returns the session's current working directory. */ QString initialWorkingDirectory() { return _initialWorkingDir; } /** * Sets the initial working directory for the session when it is run * This has no effect once the session has been started. */ void setInitialWorkingDirectory(const QString &dir); /** * Returns the current directory of the foreground process in the session */ QString currentWorkingDirectory(); /** * Sets the type of history store used by this session. * Lines of output produced by the terminal are added * to the history store. The type of history store * used affects the number of lines which can be * remembered before they are lost and the storage * (in memory, on-disk etc.) used. */ void setHistoryType(const HistoryType &hType); /** * Returns the type of history store used by this session. */ const HistoryType &historyType() const; /** * Clears the history store used by this session. */ void clearHistory(); /** * Sets the key bindings used by this session. The bindings * specify how input key sequences are translated into * the character stream which is sent to the terminal. * * @param name The name of the key bindings to use. The * names of available key bindings can be determined using the * KeyboardTranslatorManager class. */ void setKeyBindings(const QString &name); /** Returns the name of the key bindings used by this session. */ QString keyBindings() const; /** * This enum describes the available title roles. */ enum TitleRole { /** The name of the session. */ NameRole, /** The title of the session which is displayed in tabs etc. */ DisplayedTitleRole }; /** * Return the session title set by the user (ie. the program running * in the terminal), or an empty string if the user has not set a custom title */ QString userTitle() const; /** Convenience method used to read the name property. Returns title(Session::NameRole). */ QString nameTitle() const { return title(Session::NameRole); } /** Returns a title generated from tab format and process information. */ QString getDynamicTitle(); /** Sets the name of the icon associated with this session. */ void setIconName(const QString &iconName); /** Returns the name of the icon associated with this session. */ QString iconName() const; /** Return URL for the session. */ QUrl getUrl(); /** Sets the text of the icon associated with this session. */ void setIconText(const QString &iconText); /** Returns the text of the icon associated with this session. */ QString iconText() const; /** Sets the session's title for the specified @p role to @p title. */ void setTitle(TitleRole role, const QString &newTitle); /** Returns the session's title for the specified @p role. */ QString title(TitleRole role) const; /** * Specifies whether a utmp entry should be created for the pty used by this session. * If true, KPty::login() is called when the session is started. */ void setAddToUtmp(bool); /** * Specifies whether to close the session automatically when the terminal * process terminates. */ void setAutoClose(bool close); /** See setAutoClose() */ bool autoClose() const; /** Returns true if the user has started a program in the session. */ bool isForegroundProcessActive(); /** Returns the name of the current foreground process. */ QString foregroundProcessName(); /** Returns the terminal session's window size in lines and columns. */ QSize size(); /** * Emits a request to resize the session to accommodate * the specified window size. * * @param size The size in lines and columns to request. */ void setSize(const QSize &size); QSize preferredSize() const; void setPreferredSize(const QSize &size); /** * Sets whether the session has a dark background or not. The session * uses this information to set the COLORFGBG variable in the process's * environment, which allows the programs running in the terminal to determine * whether the background is light or dark and use appropriate colors by default. * * This has no effect once the session is running. */ void setDarkBackground(bool darkBackground); /** * Attempts to get the shell program to redraw the current display area. * This can be used after clearing the screen, for example, to get the * shell to redraw the prompt line. */ void refresh(); void startZModem(const QString &zmodem, const QString &dir, const QStringList &list); void cancelZModem(); bool isZModemBusy() { return _zmodemBusy; } void setZModemBusy(bool busy) { _zmodemBusy = busy; } /** * Possible values of the @p what parameter for setSessionAttribute(). * See the "Operating System Commands" section at: * https://invisible-island.net/xterm/ctlseqs/ctlseqs.html#h3-Operating-System-Commands */ enum SessionAttributes { IconNameAndWindowTitle = 0, IconName = 1, WindowTitle = 2, CurrentDirectory = 7, // From VTE (supposedly 6 was for dir, 7 for file, but whatever) TextColor = 10, BackgroundColor = 11, SessionName = 30, // Non-standard SessionIcon = 32, // Non-standard ProfileChange = 50 // this clashes with Xterm's font change command }; // Sets the text codec used by this sessions terminal emulation. void setCodec(QTextCodec *codec); // session management void saveSession(KConfigGroup &group); void restoreSession(KConfigGroup &group); void sendSignal(int signal); void reportBackgroundColor(const QColor &c); bool isReadOnly() const; void setReadOnly(bool readOnly); // Returns true if the current screen is the secondary/alternate one // or false if it's the primary/normal buffer bool isPrimaryScreen(); void tabTitleSetByUser(bool set); public Q_SLOTS: /** * Starts the terminal session. * * This creates the terminal process and connects the teletype to it. */ void run(); /** * Returns the environment of this session as a list of strings like * VARIABLE=VALUE */ Q_SCRIPTABLE QStringList environment() const; /** * Sets the environment for this session. * @p environment should be a list of strings like * VARIABLE=VALUE */ Q_SCRIPTABLE void setEnvironment(const QStringList &environment); /** * Adds one entry for the environment of this session * @p entry should be like VARIABLE=VALUE */ void addEnvironmentEntry(const QString &entry); /** * Closes the terminal session. It kills the terminal process by calling * closeInNormalWay() and, optionally, closeInForceWay(). */ //Q_SCRIPTABLE void close(); // This cause the menu issues bko 185466 void close(); /** * Kill the terminal process in normal way. This sends a hangup signal * (SIGHUP) to the terminal process and causes the finished() signal to * be emitted. If the process does not respond to the SIGHUP signal then * the terminal connection (the pty) is closed and Konsole waits for the * process to exit. This method works most of the time, but fails with some * programs which respond to SIGHUP signal in special way, such as autossh * and irssi. */ bool closeInNormalWay(); /** * kill terminal process in force way. This send a SIGKILL signal to the * terminal process. It should be called only after closeInNormalWay() has * failed. Take it as last resort. */ bool closeInForceWay(); /** * Changes one of certain session attributes in the terminal emulation * display. For a list of what may be changed see the * Emulation::sessionAttributeChanged() signal. * * @param what The session attribute being changed, it is one of the * SessionAttributes enum * @param caption The text part of the terminal command */ void setSessionAttribute(int what, const QString &caption); /** * Enables monitoring for activity in the session. * This will cause notifySessionState() to be emitted * with the NOTIFYACTIVITY state flag when output is * received from the terminal. */ Q_SCRIPTABLE void setMonitorActivity(bool); /** Returns true if monitoring for activity is enabled. */ Q_SCRIPTABLE bool isMonitorActivity() const; /** * Enables monitoring for silence in the session. * This will cause notifySessionState() to be emitted * with the NOTIFYSILENCE state flag when output is not * received from the terminal for a certain period of * time, specified with setMonitorSilenceSeconds() */ Q_SCRIPTABLE void setMonitorSilence(bool); /** * Returns true if monitoring for inactivity (silence) * in the session is enabled. */ Q_SCRIPTABLE bool isMonitorSilence() const; /** See setMonitorSilence() */ Q_SCRIPTABLE void setMonitorSilenceSeconds(int seconds); /** * Sets whether flow control is enabled for this terminal * session. */ Q_SCRIPTABLE void setFlowControlEnabled(bool enabled); /** Returns whether flow control is enabled for this terminal session. */ Q_SCRIPTABLE bool flowControlEnabled() const; /** * @param text to send to the current foreground terminal program. * @param eol send this after @p text */ void sendTextToTerminal(const QString &text, const QChar &eol = QChar()) const; #if defined(REMOVE_SENDTEXT_RUNCOMMAND_DBUS_METHODS) void sendText(const QString &text) const; #else Q_SCRIPTABLE void sendText(const QString &text) const; #endif /** * Sends @p command to the current foreground terminal program. */ #if defined(REMOVE_SENDTEXT_RUNCOMMAND_DBUS_METHODS) void runCommand(const QString &command) const; #else Q_SCRIPTABLE void runCommand(const QString &command) const; #endif /** * Sends a mouse event of type @p eventType emitted by button * @p buttons on @p column/@p line to the current foreground * terminal program */ Q_SCRIPTABLE void sendMouseEvent(int buttons, int column, int line, int eventType); /** * Returns the process id of the terminal process. * This is the id used by the system API to refer to the process. */ Q_SCRIPTABLE int processId() const; /** * Returns the process id of the terminal's foreground process. * This is initially the same as processId() but can change * as the user starts other programs inside the terminal. */ Q_SCRIPTABLE int foregroundProcessId(); /** Sets the text codec used by this sessions terminal emulation. * Overloaded to accept a QByteArray for convenience since DBus * does not accept QTextCodec directly. */ Q_SCRIPTABLE bool setCodec(const QByteArray &name); /** Returns the codec used to decode incoming characters in this * terminal emulation */ Q_SCRIPTABLE QByteArray codec(); /** Sets the session's title for the specified @p role to @p title. * This is an overloaded member function for setTitle(TitleRole, QString) * provided for convenience since enum data types may not be * exported directly through DBus */ Q_SCRIPTABLE void setTitle(int role, const QString &title); /** Returns the session's title for the specified @p role. * This is an overloaded member function for setTitle(TitleRole) * provided for convenience since enum data types may not be * exported directly through DBus */ Q_SCRIPTABLE QString title(int role) const; /** Returns the "friendly" version of the QUuid of this session. * This is a QUuid with the braces and dashes removed, so it cannot be * used to construct a new QUuid. The same text appears in the * SHELL_SESSION_ID environment variable. */ Q_SCRIPTABLE QString shellSessionId() const; /** Sets the session's tab title format for the specified @p context to @p format. * This is an overloaded member function for setTabTitleFormat(TabTitleContext, QString) * provided for convenience since enum data types may not be * exported directly through DBus */ Q_SCRIPTABLE void setTabTitleFormat(int context, const QString &format); /** Returns the session's tab title format for the specified @p context. * This is an overloaded member function for tabTitleFormat(TitleRole) * provided for convenience since enum data types may not be * exported directly through DBus */ Q_SCRIPTABLE QString tabTitleFormat(int context) const; /** * Sets the history capacity of this session. * * @param lines The history capacity in unit of lines. Its value can be: *
    *
  • positive integer - fixed size history
  • *
  • 0 - no history
  • *
  • negative integer - unlimited history
  • *
*/ Q_SCRIPTABLE void setHistorySize(int lines); /** * Returns the history capacity of this session. */ Q_SCRIPTABLE int historySize() const; /** * Sets the current session's profile */ Q_SCRIPTABLE void setProfile(const QString &profileName); /** * Returns the current session's profile name */ Q_SCRIPTABLE QString profile(); Q_SIGNALS: /** Emitted when the terminal process starts. */ void started(); /** * Emitted when the terminal process exits. */ void finished(); /** * Emitted when one of certain session attributes has been changed. * See setSessionAttribute(). */ void sessionAttributeChanged(); /** Emitted when the session gets locked / unlocked. */ void readOnlyChanged(); /** * Emitted when the activity state of this session changes. * * @param state The new state of the session. This may be one * of NOTIFYNORMAL, NOTIFYSILENCE or NOTIFYACTIVITY */ void stateChanged(int state); /** * Emitted when the current working directory of this session changes. * * @param dir The new current working directory of the session. */ void currentDirectoryChanged(const QString &dir); /** Emitted when a bell event occurs in the session. */ void bellRequest(const QString &message); /** * Requests that the background color of views on this session * should be changed. */ void changeBackgroundColorRequest(const QColor &); /** * Requests that the text color of views on this session should * be changed to @p color. */ void changeForegroundColorRequest(const QColor &); /** TODO: Document me. */ void openUrlRequest(const QString &url); /** * Emitted when the request for data transmission through ZModem * protocol is detected. */ void zmodemDownloadDetected(); void zmodemUploadDetected(); /** * Emitted when the terminal process requests a change * in the size of the terminal window. * * @param size The requested window size in terms of lines and columns. */ void resizeRequest(const QSize &size); /** * Emitted when a profile change command is received from the terminal. * * @param text The text of the command. This is a string of the form * "PropertyName=Value;PropertyName=Value ..." */ void profileChangeCommandReceived(const QString &text); /** * Emitted when the flow control state changes. * * @param enabled True if flow control is enabled or false otherwise. */ void flowControlEnabledChanged(bool enabled); /** * Emitted when the active screen is switched, to indicate whether the primary * screen is in use. * * This signal serves as a relayer of Emulation::priamyScreenInUse(bool), * making it usable for higher level component. */ void primaryScreenInUse(bool use); /** * Emitted when the text selection is changed. * * This signal serves as a relayer of Emulation::selectedText(QString), * making it usable for higher level component. */ void selectionChanged(const QString &text); /** * Emitted when background request ("\033]11;?\a") terminal code received. * Terminal is expected send "\033]11;rgb:RRRR/GGGG/BBBB\a" response. * * Originally implemented to support vim's background detection feature * (without explictly setting 'bg=dark' within local/remote vimrc) */ void getBackgroundColor(); private Q_SLOTS: void done(int, QProcess::ExitStatus); void fireZModemDownloadDetected(); void fireZModemUploadDetected(); void onReceiveBlock(const char *buf, int len); void silenceTimerDone(); void activityTimerDone(); void onViewSizeChange(int height, int width); void activityStateSet(int); //automatically detach views from sessions when view is destroyed void viewDestroyed(QObject *view); void zmodemReadStatus(); void zmodemReadAndSendBlock(); void zmodemReceiveBlock(const char *data, int len); void zmodemFinished(); void updateFlowControlState(bool suspended); void updateWindowSize(int lines, int columns); // Relays the signal from Emulation and sets _isPrimaryScreen void onPrimaryScreenInUse(bool use); void sessionAttributeRequest(int id); /** * Requests that the color the text for any tabs associated with * this session should be changed; * * TODO: Document what the parameter does */ void changeTabTextColor(int); private: Q_DISABLE_COPY(Session) // checks that the binary 'program' is available and can be executed // returns the binary name if available or an empty string otherwise static QString checkProgram(const QString &program); void updateTerminalSize(); WId windowId() const; bool kill(int signal); // print a warning message in the terminal. This is used // if the program fails to start, or if the shell exits in // an unsuccessful manner void terminalWarning(const QString &message); ProcessInfo *getProcessInfo(); void updateSessionProcessInfo(); bool updateForegroundProcessInfo(); void updateWorkingDirectory(); QString validDirectory(const QString &dir) const; QUuid _uniqueIdentifier; // SHELL_SESSION_ID Pty *_shellProcess; Emulation *_emulation; QList _views; // monitor activity & silence bool _monitorActivity; bool _monitorSilence; bool _notifiedActivity; int _silenceSeconds; QTimer *_silenceTimer; QTimer *_activityTimer; bool _autoClose; bool _closePerUserRequest; QString _nameTitle; QString _displayTitle; QString _userTitle; QString _localTabTitleFormat; QString _remoteTabTitleFormat; bool _tabTitleSetByUser; QString _iconName; QString _iconText; // not actually used bool _addToUtmp; bool _flowControlEnabled; QString _program; QStringList _arguments; QStringList _environment; int _sessionId; QString _initialWorkingDir; QString _currentWorkingDir; QUrl _reportedWorkingUrl; ProcessInfo *_sessionProcessInfo; ProcessInfo *_foregroundProcessInfo; int _foregroundPid; // ZModem bool _zmodemBusy; KProcess *_zmodemProc; ZModemDialog *_zmodemProgress; bool _hasDarkBackground; QSize _preferredSize; bool _readOnly; static int lastSessionId; bool _isPrimaryScreen; }; /** * Provides a group of sessions which is divided into master and slave sessions. * Activity in master sessions can be propagated to all sessions within the group. * The type of activity which is propagated and method of propagation is controlled * by the masterMode() flags. */ class SessionGroup : public QObject { Q_OBJECT public: /** Constructs an empty session group. */ explicit SessionGroup(QObject *parent); /** Destroys the session group and removes all connections between master and slave sessions. */ - ~SessionGroup() Q_DECL_OVERRIDE; + ~SessionGroup() override; /** Adds a session to the group. */ void addSession(Session *session); /** Removes a session from the group. */ void removeSession(Session *session); /** Returns the list of sessions currently in the group. */ QList sessions() const; /** * Sets whether a particular session is a master within the group. * Changes or activity in the group's master sessions may be propagated * to all the sessions in the group, depending on the current masterMode() * * @param session The session whose master status should be changed. * @param master True to make this session a master or false otherwise */ void setMasterStatus(Session *session, bool master); /** Returns the master status of a session. See setMasterStatus() */ bool masterStatus(Session *session) const; /** * This enum describes the options for propagating certain activity or * changes in the group's master sessions to all sessions in the group. */ enum MasterMode { /** * Any input key presses in the master sessions are sent to all * sessions in the group. */ CopyInputToAll = 1 }; /** * Specifies which activity in the group's master sessions is propagated * to all sessions in the group. * * @param mode A bitwise OR of MasterMode flags. */ void setMasterMode(int mode); /** * Returns a bitwise OR of the active MasterMode flags for this group. * See setMasterMode() */ int masterMode() const; private Q_SLOTS: void sessionFinished(); void forwardData(const QByteArray &data); private: QList masters() const; // maps sessions to their master status QHash _sessions; int _masterMode; }; } #endif diff --git a/src/SessionController.h b/src/SessionController.h index ca03abdf..be1b1995 100644 --- a/src/SessionController.h +++ b/src/SessionController.h @@ -1,366 +1,366 @@ /* Copyright 2006-2008 by Robert Knight Copyright 2009 by Thomas Dreibholz This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #ifndef SESSIONCONTROLLER_H #define SESSIONCONTROLLER_H // Qt #include #include #include #include // KDE #include // Konsole #include "ViewProperties.h" #include "Profile.h" #include "Enumeration.h" class QAction; class QTextCodec; class QKeyEvent; class QTimer; class QUrl; class KCodecAction; class QAction; class KActionMenu; namespace Konsole { class Session; class SessionGroup; class ScreenWindow; class TerminalDisplay; class IncrementalSearchBar; class ProfileList; class RegExpFilter; class UrlFilter; class FileFilter; class EditProfileDialog; using SessionPtr = QPointer; /** * Provides the menu actions to manipulate a single terminal session and view pair. * The actions provided by this class are defined in the sessionui.rc XML file. * * SessionController monitors the session and provides access to basic information * about the session such as title(), icon() and currentDir(). SessionController * provides notifications of activity in the session via the activity() signal. * * When the controlled view receives the focus, the focused() signal is emitted * with a pointer to the controller. This can be used by main application window * which contains the view to plug the controller's actions into the menu when * the view is focused. */ class KONSOLEPRIVATE_EXPORT SessionController : public ViewProperties, public KXMLGUIClient { Q_OBJECT public: enum CopyInputToEnum { /** Copy keyboard input to all the other tabs in current window */ CopyInputToAllTabsMode = 0, /** Copy keyboard input to user selected tabs in current window */ CopyInputToSelectedTabsMode = 1, /** Do not copy keyboard input to other tabs */ CopyInputToNoneMode = 2 }; /** * Constructs a new SessionController which operates on @p session and @p view. */ SessionController(Session *session, TerminalDisplay *view, QObject *parent); - ~SessionController() Q_DECL_OVERRIDE; + ~SessionController() override; /** Returns the session associated with this controller */ QPointer session() { return _session; } /** Returns the view associated with this controller */ QPointer view() { return _view; } /** * Returns the "window title" of the associated session. */ QString userTitle() const; /** * Returns true if the controller is valid. * A valid controller is one which has a non-null session() and view(). * * Equivalent to "!session().isNull() && !view().isNull()" */ bool isValid() const; /** Set the start line from which the next search will be done **/ void setSearchStartTo(int line); /** set start line to the first or last line (depending on the reverse search * setting) in the terminal display **/ void setSearchStartToWindowCurrentLine(); /** * Sets the action displayed in the session's context menu to hide or * show the menu bar. */ void setShowMenuAction(QAction *action); EditProfileDialog *profileDialogPointer(); // reimplemented - QUrl url() const Q_DECL_OVERRIDE; - QString currentDir() const Q_DECL_OVERRIDE; - void rename() Q_DECL_OVERRIDE; - bool confirmClose() const Q_DECL_OVERRIDE; + QUrl url() const override; + QString currentDir() const override; + void rename() override; + bool confirmClose() const override; virtual bool confirmForceClose() const; // Reimplemented to watch for events happening to the view - bool eventFilter(QObject *watched, QEvent *event) Q_DECL_OVERRIDE; + bool eventFilter(QObject *watched, QEvent *event) override; /** Returns the set of all controllers that exist. */ static QSet allControllers() { return _allControllers; } /* Returns true if called within a KPart; false if called within Konsole. */ bool isKonsolePart() const; bool isReadOnly() const; Q_SIGNALS: /** * Emitted when the view associated with the controller is focused. * This can be used by other classes to plug the controller's actions into a window's * menus. */ void focused(SessionController *controller); void rawTitleChanged(); /** * Emitted when the current working directory of the session associated with * the controller is changed. */ void currentDirectoryChanged(const QString &dir); /** * Emitted when the user changes the tab title. */ void tabRenamedByUser(bool renamed) const; public Q_SLOTS: /** * Issues a command to the session to navigate to the specified URL. * This may not succeed if the foreground program does not understand * the command sent to it ( 'cd path' for local URLs ) or is not * responding to input. * * openUrl() currently supports urls for local paths and those * using the 'ssh' protocol ( eg. "ssh://joebloggs@hostname" ) */ void openUrl(const QUrl &url); /** * update actions which are meaningful only when primary screen is in use. */ void setupPrimaryScreenSpecificActions(bool use); /** * update actions which are closely related with the selected text. */ void selectionChanged(const QString &selectedText); /** * close the associated session. This might involve user interaction for * confirmation. */ void closeSession(); /** Increase font size */ void increaseFontSize(); /** Decrease font size */ void decreaseFontSize(); /** Reset font size */ void resetFontSize(); /** Close the incremental search */ void searchClosed(); // called when the user clicks on the private Q_SLOTS: // menu item handlers void openBrowser(); void copy(); void paste(); void selectAll(); void selectLine(); void pasteFromX11Selection(); // shortcut only void copyInputActionsTriggered(QAction *action); void copyInputToAllTabs(); void copyInputToSelectedTabs(); void copyInputToNone(); void editCurrentProfile(); void changeCodec(QTextCodec *codec); void enableSearchBar(bool showSearchBar); void searchHistory(bool showSearchBar); void searchBarEvent(); void searchFrom(); void findNextInHistory(); void findPreviousInHistory(); void changeSearchMatch(); void print_screen(); void saveHistory(); void showHistoryOptions(); void clearHistory(); void clearHistoryAndReset(); void monitorActivity(bool monitor); void monitorSilence(bool monitor); void renameSession(); void switchProfile(const Profile::Ptr &profile); void handleWebShortcutAction(); void configureWebShortcuts(); void sendSignal(QAction *action); void sendBackgroundColor(); void toggleReadOnly(); // other void setupSearchBar(); void prepareSwitchProfileMenu(); void updateCodecAction(); void showDisplayContextMenu(const QPoint &position); void movementKeyFromSearchBarReceived(QKeyEvent *event); void sessionStateChanged(int state); void sessionAttributeChanged(); void sessionReadOnlyChanged(); void searchTextChanged(const QString &text); void searchCompleted(bool success); void updateFilterList(Profile::Ptr profile); // Called when the profile has changed, so we might need to change the list of filters void interactionHandler(); void snapshot(); // called periodically as the user types // to take a snapshot of the state of the // foreground process in the terminal void highlightMatches(bool highlight); void scrollBackOptionsChanged(int mode, int lines); void sessionResizeRequest(const QSize &size); void trackOutput(QKeyEvent *event); // move view to end of current output // when a key press occurs in the // display area void updateSearchFilter(); void zmodemDownload(); void zmodemUpload(); // update actions related with selected text void updateCopyAction(const QString &selectedText); void updateWebSearchMenu(); private: Q_DISABLE_COPY(SessionController) // begins the search // text - pattern to search for // direction - value from SearchHistoryTask::SearchDirection enum to specify // the search direction void beginSearch(const QString &text, Enum::SearchDirection direction); QRegularExpression regexpFromSearchBarOptions() const; bool reverseSearchChecked() const; void setupCommonActions(); void setupExtraActions(); void removeSearchFilter(); // remove and delete the current search filter if set void setFindNextPrevEnabled(bool enabled); void listenForScreenWindowUpdates(); private: void updateSessionIcon(); void updateReadOnlyActionStates(); QPointer _session; QPointer _view; SessionGroup *_copyToGroup; ProfileList *_profileList; QIcon _sessionIcon; QString _sessionIconName; int _previousState; RegExpFilter *_searchFilter; UrlFilter *_urlFilter; FileFilter *_fileFilter; QAction *_copyInputToAllTabsAction; QAction *_findAction; QAction *_findNextAction; QAction *_findPreviousAction; QTimer *_interactionTimer; int _searchStartLine; int _prevSearchResultLine; KCodecAction *_codecAction; KActionMenu *_switchProfileMenu; KActionMenu *_webSearchMenu; bool _listenForScreenWindowUpdates; bool _preventClose; bool _keepIconUntilInteraction; QString _selectedText; QAction *_showMenuAction; static QSet _allControllers; static int _lastControllerId; QStringList _bookmarkValidProgramsToClear; bool _isSearchBarEnabled; QPointer _editProfileDialog; QString _searchText; QPointer _searchBar; }; inline bool SessionController::isValid() const { return !_session.isNull() && !_view.isNull(); } } #endif //SESSIONCONTROLLER_H diff --git a/src/SessionListModel.h b/src/SessionListModel.h index 5a150030..b3711941 100644 --- a/src/SessionListModel.h +++ b/src/SessionListModel.h @@ -1,76 +1,76 @@ /* This source file is part of Konsole, a terminal emulator. Copyright 2006-2008 by Robert Knight This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #ifndef SESSIONLISTMODEL_H #define SESSIONLISTMODEL_H // Qt #include #include namespace Konsole { class Session; /** * Item-view model which contains a flat list of sessions. * After constructing the model, call setSessions() to set the sessions displayed * in the list. When a session ends (after emitting the finished() signal) it is * automatically removed from the list. * * The internal pointer for each item in the model (index.internalPointer()) is the * associated Session* */ class SessionListModel : public QAbstractListModel { Q_OBJECT public: explicit SessionListModel(QObject *parent = nullptr); /** * Sets the list of sessions displayed in the model. * To display all sessions that are currently running in the list, * call setSessions(SessionManager::instance()->sessions()) */ void setSessions(const QList &sessions); // reimplemented from QAbstractItemModel - QModelIndex index(int row, int column, const QModelIndex &parent) const Q_DECL_OVERRIDE; - QVariant data(const QModelIndex &index, int role) const Q_DECL_OVERRIDE; - QVariant headerData(int section, Qt::Orientation orientation, int role) const Q_DECL_OVERRIDE; - int columnCount(const QModelIndex &parent) const Q_DECL_OVERRIDE; - int rowCount(const QModelIndex &parent) const Q_DECL_OVERRIDE; - QModelIndex parent(const QModelIndex &index) const Q_DECL_OVERRIDE; + QModelIndex index(int row, int column, const QModelIndex &parent) const override; + QVariant data(const QModelIndex &index, int role) const override; + QVariant headerData(int section, Qt::Orientation orientation, int role) const override; + int columnCount(const QModelIndex &parent) const override; + int rowCount(const QModelIndex &parent) const override; + QModelIndex parent(const QModelIndex &index) const override; protected: virtual void sessionRemoved(Session *) { } private Q_SLOTS: void sessionFinished(); private: QList _sessions; }; } #endif //SESSIONLISTMODEL_H diff --git a/src/SessionManager.h b/src/SessionManager.h index 3bfc39fe..e5ee76d7 100644 --- a/src/SessionManager.h +++ b/src/SessionManager.h @@ -1,159 +1,159 @@ /* This source file is part of Konsole, a terminal emulator. Copyright 2006-2008 by Robert Knight This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #ifndef SESSIONMANAGER_H #define SESSIONMANAGER_H // Qt #include #include // Konsole #include "Profile.h" class KConfig; namespace Konsole { class Session; /** * Manages running terminal sessions. */ class KONSOLEPRIVATE_EXPORT SessionManager : public QObject { Q_OBJECT public: /** * Constructs a new session manager and loads information about the available * profiles. */ SessionManager(); /** * Destroys the SessionManager. All running sessions should be closed * (via closeAllSessions()) before the SessionManager is destroyed. */ - ~SessionManager() Q_DECL_OVERRIDE; + ~SessionManager() override; /** * Returns the session manager instance. */ static SessionManager *instance(); /** Kill all running sessions. */ void closeAllSessions(); /** * Creates a new session using the settings specified by the specified * profile. * * The new session has no views associated with it. A new TerminalDisplay view * must be created in order to display the output from the terminal session and * send keyboard or mouse input to it. * * @param profile A profile containing the settings for the new session. If @p profile * is null the default profile (see ProfileManager::defaultProfile()) will be used. */ Session *createSession(Profile::Ptr profile = Profile::Ptr()); /** Sets the profile associated with a session. */ void setSessionProfile(Session *session, Profile::Ptr profile); /** Returns the profile associated with a session. */ Profile::Ptr sessionProfile(Session *session) const; /** * Returns a list of active sessions. */ const QList sessions() const; // System session management void saveSessions(KConfig *config); void restoreSessions(KConfig *config); int getRestoreId(Session *session); Session *idToSession(int id); bool isClosingAllSessions() const; Q_SIGNALS: /** * Emitted when a session's settings are updated to match * its current profile. */ void sessionUpdated(Session *session); protected Q_SLOTS: /** * Called to inform the manager that a session has finished executing. * * @param session The Session which has finished executing. */ void sessionTerminated(Session *session); private Q_SLOTS: void sessionProfileCommandReceived(const QString &text); void profileChanged(const Profile::Ptr &profile); private: Q_DISABLE_COPY(SessionManager) // applies updates to a profile // to all sessions currently using that profile // if modifiedPropertiesOnly is true, only properties which // are set in the profile @p key are updated void applyProfile(const Profile::Ptr &profile, bool modifiedPropertiesOnly); // applies updates to the profile @p profile to the session @p session // if modifiedPropertiesOnly is true, only properties which // are set in @p profile are update ( ie. properties for which profile->isPropertySet() // returns true ) void applyProfile(Session *session, const Profile::Ptr &profile, bool modifiedPropertiesOnly); QList _sessions; // list of running sessions QHash _sessionProfiles; QHash _sessionRuntimeProfiles; QHash _restoreMapping; bool _isClosingAllSessions; }; /** Utility class to simplify code in SessionManager::applyProfile(). */ class ShouldApplyProperty { public: ShouldApplyProperty(const Profile::Ptr &profile, bool modifiedOnly) : _profile(profile), _modifiedPropertiesOnly(modifiedOnly) { } bool shouldApply(Profile::Property property) const { return !_modifiedPropertiesOnly || _profile->isPropertySet(property); } private: const Profile::Ptr _profile; bool _modifiedPropertiesOnly; }; } #endif //SESSIONMANAGER_H diff --git a/src/TabTitleFormatButton.h b/src/TabTitleFormatButton.h index 73cb272d..b8209ca2 100644 --- a/src/TabTitleFormatButton.h +++ b/src/TabTitleFormatButton.h @@ -1,62 +1,62 @@ /* Copyright 2007-2008 by Robert Knight This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #ifndef TABTITLEFORMATBUTTON_H #define TABTITLEFORMATBUTTON_H // Qt #include #include // Konsole #include "Session.h" namespace Konsole { class TabTitleFormatButton : public QPushButton { Q_OBJECT public: explicit TabTitleFormatButton(QWidget *parent); - ~TabTitleFormatButton() Q_DECL_OVERRIDE; + ~TabTitleFormatButton() override; void setContext(Session::TabTitleContext titleContext); Session::TabTitleContext context() const; Q_SIGNALS: void dynamicElementSelected(const QString &); private Q_SLOTS: void fireElementSelected(QAction *); private: Session::TabTitleContext _context; struct Element { QString element; const char *description; }; static const Element _localElements[]; static const int _localElementCount; static const Element _remoteElements[]; static const int _remoteElementCount; }; } #endif // TABTITLEFORMATBUTTON_H diff --git a/src/TerminalCharacterDecoder.h b/src/TerminalCharacterDecoder.h index 394067e7..f2fd0d6d 100644 --- a/src/TerminalCharacterDecoder.h +++ b/src/TerminalCharacterDecoder.h @@ -1,145 +1,145 @@ /* This file is part of Konsole, an X terminal. Copyright 2006-2008 by Robert Knight This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser 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 Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #ifndef TERMINAL_CHARACTER_DECODER_H #define TERMINAL_CHARACTER_DECODER_H // Qt #include // Konsole #include "Character.h" #include "Profile.h" #include "konsoleprivate_export.h" class QTextStream; namespace Konsole { /** * Base class for terminal character decoders * * The decoder converts lines of terminal characters which consist of a unicode character, foreground * and background colors and other appearance-related properties into text strings. * * Derived classes may produce either plain text with no other color or appearance information, or * they may produce text which incorporates these additional properties. */ class KONSOLEPRIVATE_EXPORT TerminalCharacterDecoder { public: virtual ~TerminalCharacterDecoder() { } /** Begin decoding characters. The resulting text is appended to @p output. */ virtual void begin(QTextStream *output) = 0; /** End decoding. */ virtual void end() = 0; /** * Converts a line of terminal characters with associated properties into a text string * and writes the string into an output QTextStream. * * @param characters An array of characters of length @p count. * @param count The number of characters * @param properties Additional properties which affect all characters in the line */ virtual void decodeLine(const Character * const characters, int count, LineProperty properties) = 0; }; /** * A terminal character decoder which produces plain text, ignoring colors and other appearance-related * properties of the original characters. */ class KONSOLEPRIVATE_EXPORT PlainTextDecoder : public TerminalCharacterDecoder { public: PlainTextDecoder(); /** * Set whether leading whitespace at the end of lines should be included * in the output. * Defaults to true. */ void setLeadingWhitespace(bool enable); /** * Set whether trailing whitespace at the end of lines should be included * in the output. * Defaults to true. */ void setTrailingWhitespace(bool enable); /** * Returns of character positions in the output stream * at which new lines where added. Returns an empty if setTrackLinePositions() is false or if * the output device is not a string. */ QList linePositions() const; /** Enables recording of character positions at which new lines are added. See linePositions() */ void setRecordLinePositions(bool record); - void begin(QTextStream *output) Q_DECL_OVERRIDE; - void end() Q_DECL_OVERRIDE; + void begin(QTextStream *output) override; + void end() override; void decodeLine(const Character * const characters, int count, - LineProperty properties) Q_DECL_OVERRIDE; + LineProperty properties) override; private: QTextStream *_output; bool _includeLeadingWhitespace; bool _includeTrailingWhitespace; bool _recordLinePositions; QList _linePositions; }; /** * A terminal character decoder which produces pretty HTML markup */ class KONSOLEPRIVATE_EXPORT HTMLDecoder : public TerminalCharacterDecoder { public: /** * Constructs an HTML decoder using a default black-on-white color scheme. */ explicit HTMLDecoder(const Profile::Ptr &profile = Profile::Ptr()); void decodeLine(const Character * const characters, int count, - LineProperty properties) Q_DECL_OVERRIDE; + LineProperty properties) override; - void begin(QTextStream *output) Q_DECL_OVERRIDE; - void end() Q_DECL_OVERRIDE; + void begin(QTextStream *output) override; + void end() override; private: void openSpan(QString &text, const QString &style); void closeSpan(QString &text); QTextStream *_output; Profile::Ptr _profile; ColorEntry _colorTable[TABLE_COLORS]; bool _innerSpanOpen; RenditionFlags _lastRendition; CharacterColor _lastForeColor; CharacterColor _lastBackColor; }; } #endif diff --git a/src/TerminalDisplay.h b/src/TerminalDisplay.h index 7c78dafb..507fd6a1 100644 --- a/src/TerminalDisplay.h +++ b/src/TerminalDisplay.h @@ -1,889 +1,889 @@ /* Copyright 2007-2008 by Robert Knight Copyright 1997,1998 by Lars Doelle This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #ifndef TERMINALDISPLAY_H #define TERMINALDISPLAY_H // Qt #include #include #include // Konsole #include "Character.h" #include "konsoleprivate_export.h" #include "ScreenWindow.h" #include "ColorScheme.h" #include "Enumeration.h" #include "ScrollState.h" #include "Profile.h" #include "TerminalHeaderBar.h" class QDrag; class QDragEnterEvent; class QDropEvent; class QLabel; class QTimer; class QEvent; class QVBoxLayout; class QKeyEvent; class QScrollBar; class QShowEvent; class QHideEvent; class QTimerEvent; class KMessageWidget; namespace Konsole { class FilterChain; class TerminalImageFilterChain; class SessionController; class IncrementalSearchBar; /** * A widget which displays output from a terminal emulation and sends input keypresses and mouse activity * to the terminal. * * When the terminal emulation receives new output from the program running in the terminal, * it will update the display by calling updateImage(). * * TODO More documentation */ class KONSOLEPRIVATE_EXPORT TerminalDisplay : public QWidget { Q_OBJECT public: /** Constructs a new terminal display widget with the specified parent. */ explicit TerminalDisplay(QWidget *parent = nullptr); - ~TerminalDisplay() Q_DECL_OVERRIDE; + ~TerminalDisplay() override; void showDragTarget(const QPoint& pos); void hideDragTarget(); void applyProfile(const Profile::Ptr& profile); /** Returns the terminal color palette used by the display. */ const ColorEntry *colorTable() const; /** Sets the terminal color palette used by the display. */ void setColorTable(const ColorEntry table[]); /** * Sets the seed used to generate random colors for the display * (in color schemes that support them). */ void setRandomSeed(uint randomSeed); /** * Returns the seed used to generate random colors for the display * (in color schemes that support them). */ uint randomSeed() const; /** Sets the opacity of the terminal display. */ void setOpacity(qreal opacity); /** Sets the background picture */ void setWallpaper(const ColorSchemeWallpaper::Ptr &p); /** * Specifies whether the terminal display has a vertical scroll bar, and if so whether it * is shown on the left or right side of the display. */ void setScrollBarPosition(Enum::ScrollBarPositionEnum position); /** * Sets the current position and range of the display's scroll bar. * * @param cursor The position of the scroll bar's thumb. * @param slines The maximum value of the scroll bar. */ void setScroll(int cursor, int slines); void setScrollFullPage(bool fullPage); bool scrollFullPage() const; /** * Returns the display's filter chain. When the image for the display is updated, * the text is passed through each filter in the chain. Each filter can define * hotspots which correspond to certain strings (such as URLs or particular words). * Depending on the type of the hotspots created by the filter ( returned by Filter::Hotspot::type() ) * the view will draw visual cues such as underlines on mouse-over for links or translucent * rectangles for markers. * * To add a new filter to the view, call: * viewWidget->filterChain()->addFilter( filterObject ); */ FilterChain *filterChain() const; /** * Updates the filters in the display's filter chain. This will cause * the hotspots to be updated to match the current image. * * WARNING: This function can be expensive depending on the * image size and number of filters in the filterChain() * * TODO - This API does not really allow efficient usage. Revise it so * that the processing can be done in a better way. * * eg: * - Area of interest may be known ( eg. mouse cursor hovering * over an area ) */ void processFilters(); /** * Returns a list of menu actions created by the filters for the content * at the given @p position. */ QList filterActions(const QPoint &position); /** Specifies whether or not the cursor can blink. */ void setBlinkingCursorEnabled(bool blink); /** Specifies whether or not text can blink. */ void setBlinkingTextEnabled(bool blink); void setLineSpacing(uint); uint lineSpacing() const; void setSessionController(SessionController *controller); SessionController *sessionController(); /** * Sets the shape of the keyboard cursor. This is the cursor drawn * at the position in the terminal where keyboard input will appear. * * In addition the terminal display widget also has a cursor for * the mouse pointer, which can be set using the QWidget::setCursor() * method. * * Defaults to BlockCursor */ void setKeyboardCursorShape(Enum::CursorShapeEnum shape); /** * Returns the shape of the keyboard cursor. See setKeyboardCursorShape() */ Enum::CursorShapeEnum keyboardCursorShape() const; /** * Sets the Cursor Style (DECSCUSR) via escape sequences * @p shape cursor shape * @p isBlinking if true, the cursor will be set to blink */ void setCursorStyle(Enum::CursorShapeEnum shape, bool isBlinking); /** * Resets the cursor style to the current profile cursor shape and * blinking settings */ void resetCursorStyle(); /** * Sets the color used to draw the keyboard cursor. * * The keyboard cursor defaults to using the foreground color of the character * underneath it. * * @param color By default, the widget uses the color of the * character under the cursor to draw the cursor, and inverts the * color of that character to make sure it is still readable. If @p * color is a valid QColor, the widget uses that color to draw the * cursor. If @p color is not an valid QColor, the widget falls back * to the default behavior. */ void setKeyboardCursorColor(const QColor &color); /** * Returns the color of the keyboard cursor, or an invalid color if the keyboard * cursor color is set to change according to the foreground color of the character * underneath it. */ QColor keyboardCursorColor() const; /** * Returns the number of lines of text which can be displayed in the widget. * * This will depend upon the height of the widget and the current font. * See fontHeight() */ int lines() const { return _lines; } /** * Returns the number of characters of text which can be displayed on * each line in the widget. * * This will depend upon the width of the widget and the current font. * See fontWidth() */ int columns() const { return _columns; } /** * Returns the height of the characters in the font used to draw the text in the display. */ int fontHeight() const { return _fontHeight; } /** * Returns the width of the characters in the display. * This assumes the use of a fixed-width font. */ int fontWidth() const { return _fontWidth; } void setSize(int columns, int lines); // reimplemented - QSize sizeHint() const Q_DECL_OVERRIDE; + QSize sizeHint() const override; /** * Sets which characters, in addition to letters and numbers, * are regarded as being part of a word for the purposes * of selecting words in the display by double clicking on them. * * The word boundaries occur at the first and last characters which * are either a letter, number, or a character in @p wc * * @param wc An array of characters which are to be considered parts * of a word ( in addition to letters and numbers ). */ void setWordCharacters(const QString &wc); /** * Sets the type of effect used to alert the user when a 'bell' occurs in the * terminal session. * * The terminal session can trigger the bell effect by calling bell() with * the alert message. */ void setBellMode(int mode); /** * Returns the type of effect used to alert the user when a 'bell' occurs in * the terminal session. * * See setBellMode() */ int bellMode() const; /** Play a visual bell for prompt or warning. */ void visualBell(); /** Returns the font used to draw characters in the display */ QFont getVTFont() { return font(); } TerminalHeaderBar *headerBar() const { return _headerBar; } /** * Sets the font used to draw the display. Has no effect if @p font * is larger than the size of the display itself. */ void setVTFont(const QFont &f); /** Increases the font size */ void increaseFontSize(); /** Decreases the font size */ void decreaseFontSize(); /** Reset the font size */ void resetFontSize(); /** * Sets the terminal screen section which is displayed in this widget. * When updateImage() is called, the display fetches the latest character image from the * the associated terminal screen window. * * In terms of the model-view paradigm, the ScreenWindow is the model which is rendered * by the TerminalDisplay. */ void setScreenWindow(ScreenWindow *window); /** Returns the terminal screen section which is displayed in this widget. See setScreenWindow() */ ScreenWindow *screenWindow() const; // Select the current line. void selectCurrentLine(); /** * Selects everything in the terminal */ void selectAll(); void printContent(QPainter &painter, bool friendly); /** * Gets the background of the display * @see setBackgroundColor(), setColorTable(), setForegroundColor() */ QColor getBackgroundColor() const; bool bracketedPasteMode() const; /** * Returns true if the flow control warning box is enabled. * See outputSuspended() and setFlowControlWarningEnabled() */ bool flowControlWarningEnabled() const { return _flowControlWarningEnabled; } /** See setUsesMouseTracking() */ bool usesMouseTracking() const; /** See setAlternateScrolling() */ bool alternateScrolling() const; public Q_SLOTS: /** * Scrolls current ScreenWindow * * it's needed for proper handling scroll commands in the Vt102Emulation class */ void scrollScreenWindow(enum ScreenWindow::RelativeScrollMode mode, int amount); /** * Causes the terminal display to fetch the latest character image from the associated * terminal screen ( see setScreenWindow() ) and redraw the display. */ void updateImage(); /** * Causes the terminal display to fetch the latest line status flags from the * associated terminal screen ( see setScreenWindow() ). */ void updateLineProperties(); void setAutoCopySelectedText(bool enabled); void setCopyTextAsHTML(bool enabled); void setMiddleClickPasteMode(Enum::MiddleClickPasteModeEnum mode); /** Copies the selected text to the X11 Selection. */ void copyToX11Selection(); /** Copies the selected text to the system clipboard. */ void copyToClipboard(); /** * Pastes the content of the clipboard into the display. * * URLs of local files are treated specially: * - The scheme part, "file://", is removed from each URL * - The URLs are pasted as a space-separated list of file paths */ void pasteFromClipboard(bool appendEnter = false); /** * Pastes the content of the X11 selection into the * display. */ void pasteFromX11Selection(bool appendEnter = false); /** * Changes whether the flow control warning box should be shown when the flow control * stop key (Ctrl+S) are pressed. */ void setFlowControlWarningEnabled(bool enable); /** * Causes the widget to display or hide a message informing the user that terminal * output has been suspended (by using the flow control key combination Ctrl+S) * * @param suspended True if terminal output has been suspended and the warning message should * be shown or false to indicate that terminal output has been resumed and that * the warning message should disappear. */ void outputSuspended(bool suspended); /** * Sets whether the program currently running in the terminal is interested * in Mouse Tracking events. * * When set to true, Konsole will send Mouse Tracking events. * * The user interaction needed to create text selections will change * also, and the user will be required to hold down the Shift key to * create a selection or perform other mouse activities inside the view * area, since the program running in the terminal is being allowed * to handle normal mouse events itself. * * @param on Set to true if the program running in the terminal is * interested in Mouse Tracking events or false otherwise. */ void setUsesMouseTracking(bool on); /** * Sets the AlternateScrolling profile property which controls whether * to emulate up/down key presses for mouse scroll wheel events. * For more details, check the documentation of that property in the * Profile header. * Enabled by default. */ void setAlternateScrolling(bool enable); void setBracketedPasteMode(bool on); /** * Shows a notification that a bell event has occurred in the terminal. * TODO: More documentation here */ void bell(const QString &message); /** * Sets the background of the display to the specified color. * @see setColorTable(), getBackgroundColor(), setForegroundColor() */ void setBackgroundColor(const QColor &color); /** * Sets the text of the display to the specified color. * @see setColorTable(), setBackgroundColor(), getBackgroundColor() */ void setForegroundColor(const QColor &color); /** * Sets the display's contents margins. */ void setMargin(int margin); /** * Sets whether the contents are centered between the margins. */ void setCenterContents(bool enable); /** * Return the current color scheme */ ColorScheme const *colorScheme() const { return _colorScheme; } Enum::ScrollBarPositionEnum scrollBarPosition() const { return _scrollbarLocation; } Qt::Edge droppedEdge() const { return _overlayEdge; } // Used to show/hide the message widget void updateReadOnlyState(bool readonly); IncrementalSearchBar *searchBar() const; Q_SIGNALS: void requestToggleExpansion(); /** * Emitted when the user presses a key whilst the terminal widget has focus. */ void keyPressedSignal(QKeyEvent *event); /** * A mouse event occurred. * @param button The mouse button (0 for left button, 1 for middle button, 2 for right button, 3 for release) * @param column The character column where the event occurred * @param line The character row where the event occurred * @param eventType The type of event. 0 for a mouse press / release or 1 for mouse motion */ void mouseSignal(int button, int column, int line, int eventType); void changedFontMetricSignal(int height, int width); void changedContentSizeSignal(int height, int width); /** * Emitted when the user right clicks on the display, or right-clicks * with the Shift key held down if usesMouseTracking() is true. * * This can be used to display a context menu. */ void configureRequest(const QPoint &position); /** * When a shortcut which is also a valid terminal key sequence is pressed while * the terminal widget has focus, this signal is emitted to allow the host to decide * whether the shortcut should be overridden. * When the shortcut is overridden, the key sequence will be sent to the terminal emulation instead * and the action associated with the shortcut will not be triggered. * * @p override is set to false by default and the shortcut will be triggered as normal. */ void overrideShortcutCheck(QKeyEvent *keyEvent, bool &override); void sendStringToEmu(const QByteArray &local8BitString); void focusLost(); void focusGained(); protected: // events - bool event(QEvent *event) Q_DECL_OVERRIDE; - void paintEvent(QPaintEvent *pe) Q_DECL_OVERRIDE; - void showEvent(QShowEvent *event) Q_DECL_OVERRIDE; - void hideEvent(QHideEvent *event) Q_DECL_OVERRIDE; - void resizeEvent(QResizeEvent *event) Q_DECL_OVERRIDE; - void contextMenuEvent(QContextMenuEvent *event) Q_DECL_OVERRIDE; - void focusInEvent(QFocusEvent *event) Q_DECL_OVERRIDE; - void focusOutEvent(QFocusEvent *event) Q_DECL_OVERRIDE; - void keyPressEvent(QKeyEvent *event) Q_DECL_OVERRIDE; - void keyReleaseEvent(QKeyEvent *event) Q_DECL_OVERRIDE; - void leaveEvent(QEvent *event) Q_DECL_OVERRIDE; - void mouseDoubleClickEvent(QMouseEvent *ev) Q_DECL_OVERRIDE; - void mousePressEvent(QMouseEvent *ev) Q_DECL_OVERRIDE; - void mouseReleaseEvent(QMouseEvent *ev) Q_DECL_OVERRIDE; - void mouseMoveEvent(QMouseEvent *ev) Q_DECL_OVERRIDE; - void wheelEvent(QWheelEvent *ev) Q_DECL_OVERRIDE; - bool focusNextPrevChild(bool next) Q_DECL_OVERRIDE; + bool event(QEvent *event) override; + void paintEvent(QPaintEvent *pe) override; + void showEvent(QShowEvent *event) override; + void hideEvent(QHideEvent *event) override; + void resizeEvent(QResizeEvent *event) override; + void contextMenuEvent(QContextMenuEvent *event) override; + void focusInEvent(QFocusEvent *event) override; + void focusOutEvent(QFocusEvent *event) override; + void keyPressEvent(QKeyEvent *event) override; + void keyReleaseEvent(QKeyEvent *event) override; + void leaveEvent(QEvent *event) override; + void mouseDoubleClickEvent(QMouseEvent *ev) override; + void mousePressEvent(QMouseEvent *ev) override; + void mouseReleaseEvent(QMouseEvent *ev) override; + void mouseMoveEvent(QMouseEvent *ev) override; + void wheelEvent(QWheelEvent *ev) override; + bool focusNextPrevChild(bool next) override; void fontChange(const QFont &); void extendSelection(const QPoint &position); // drag and drop - void dragEnterEvent(QDragEnterEvent *event) Q_DECL_OVERRIDE; - void dropEvent(QDropEvent *event) Q_DECL_OVERRIDE; + void dragEnterEvent(QDragEnterEvent *event) override; + void dropEvent(QDropEvent *event) override; void doDrag(); enum DragState { diNone, diPending, diDragging }; struct DragInfo { DragState state; QPoint start; QDrag *dragObject; } _dragInfo; // classifies the 'ch' into one of three categories // and returns a character to indicate which category it is in // // - A space (returns ' ') // - Part of a word (returns 'a') // - Other characters (returns the input character) QChar charClass(const Character &ch) const; void clearImage(); void mouseTripleClickEvent(QMouseEvent *ev); void selectLine(QPoint pos, bool entireLine); // reimplemented - void inputMethodEvent(QInputMethodEvent *event) Q_DECL_OVERRIDE; - QVariant inputMethodQuery(Qt::InputMethodQuery query) const Q_DECL_OVERRIDE; + void inputMethodEvent(QInputMethodEvent *event) override; + QVariant inputMethodQuery(Qt::InputMethodQuery query) const override; void onColorsChanged(); protected Q_SLOTS: void scrollBarPositionChanged(int value); void blinkTextEvent(); void blinkCursorEvent(); private Q_SLOTS: void swapFGBGColors(); void viewScrolledByUser(); void dismissOutputSuspendedMessage(); private: Q_DISABLE_COPY(TerminalDisplay) // -- Drawing helpers -- // divides the part of the display specified by 'rect' into // fragments according to their colors and styles and calls // drawTextFragment() or drawPrinterFriendlyTextFragment() // to draw the fragments void drawContents(QPainter &painter, const QRect &rect); // draw a transparent rectangle over the line of the current match void drawCurrentResultRect(QPainter &painter); // draws a section of text, all the text in this section // has a common color and style void drawTextFragment(QPainter &painter, const QRect &rect, const QString &text, const Character *style); void drawPrinterFriendlyTextFragment(QPainter &painter, const QRect &rect, const QString &text, const Character *style); // draws the background for a text fragment // if useOpacitySetting is true then the color's alpha value will be set to // the display's transparency (set with setOpacity()), otherwise the background // will be drawn fully opaque void drawBackground(QPainter &painter, const QRect &rect, const QColor &backgroundColor, bool useOpacitySetting); // draws the cursor character void drawCursor(QPainter &painter, const QRect &rect, const QColor &foregroundColor, const QColor &backgroundColor, bool &invertCharacterColor); // draws the characters or line graphics in a text fragment void drawCharacters(QPainter &painter, const QRect &rect, const QString &text, const Character *style, bool invertCharacterColor); // draws a string of line graphics void drawLineCharString(QPainter &painter, int x, int y, const QString &str, const Character *attributes); // draws the preedit string for input methods void drawInputMethodPreeditString(QPainter &painter, const QRect &rect); // -- // maps an area in the character image to an area on the widget QRect imageToWidget(const QRect &imageArea) const; QRect widgetToImage(const QRect &widgetArea) const; // maps a point on the widget to the position ( ie. line and column ) // of the character at that point. When the edge is true, it maps to // a character which left edge is closest to the point. void getCharacterPosition(const QPoint &widgetPoint, int &line, int &column, bool edge) const; // the area where the preedit string for input methods will be draw QRect preeditRect() const; // shows a notification window in the middle of the widget indicating the terminal's // current size in columns and lines void showResizeNotification(); // scrolls the image by a number of lines. // 'lines' may be positive ( to scroll the image down ) // or negative ( to scroll the image up ) // 'region' is the part of the image to scroll - currently only // the top, bottom and height of 'region' are taken into account, // the left and right are ignored. void scrollImage(int lines, const QRect &screenWindowRegion); void calcGeometry(); void propagateSize(); void updateImageSize(); void makeImage(); void paintFilters(QPainter &painter); // returns a region covering all of the areas of the widget which contain // a hotspot QRegion hotSpotRegion() const; // returns the position of the cursor in columns and lines QPoint cursorPosition() const; // returns true if the cursor's position is on display. bool isCursorOnDisplay() const; // redraws the cursor void updateCursor(); bool handleShortcutOverrideEvent(QKeyEvent *keyEvent); void doPaste(QString text, bool appendReturn); void processMidButtonClick(QMouseEvent *ev); QPoint findLineStart(const QPoint &pnt); QPoint findLineEnd(const QPoint &pnt); QPoint findWordStart(const QPoint &pnt); QPoint findWordEnd(const QPoint &pnt); // Uses the current settings for trimming whitespace and preserving linebreaks to create a proper flag value for Screen Screen::DecodingOptions currentDecodingOptions(); // Boilerplate setup for MessageWidget KMessageWidget* createMessageWidget(const QString &text); int loc(int x, int y) const; // the window onto the terminal screen which this display // is currently showing. QPointer _screenWindow; bool _bellMasked; QVBoxLayout *_verticalLayout; bool _fixedFont; // has fixed pitch int _fontHeight; // height int _fontWidth; // width int _fontAscent; // ascend bool _boldIntense; // Whether intense colors should be rendered with bold font int _lines; // the number of lines that can be displayed in the widget int _columns; // the number of columns that can be displayed in the widget int _usedLines; // the number of lines that are actually being used, this will be less // than 'lines' if the character image provided with setImage() is smaller // than the maximum image size which can be displayed int _usedColumns; // the number of columns that are actually being used, this will be less // than 'columns' if the character image provided with setImage() is smaller // than the maximum image size which can be displayed QRect _contentRect; Character *_image; // [lines][columns] // only the area [usedLines][usedColumns] in the image contains valid data int _imageSize; QVector _lineProperties; ColorEntry _colorTable[TABLE_COLORS]; uint _randomSeed; bool _resizing; bool _showTerminalSizeHint; bool _bidiEnabled; bool _usesMouseTracking; bool _alternateScrolling; bool _bracketedPasteMode; QPoint _iPntSel; // initial selection point QPoint _pntSel; // current selection point QPoint _tripleSelBegin; // help avoid flicker int _actSel; // selection state bool _wordSelectionMode; bool _lineSelectionMode; bool _preserveLineBreaks; bool _columnSelectionMode; bool _autoCopySelectedText; bool _copyTextAsHTML; Enum::MiddleClickPasteModeEnum _middleClickPasteMode; QScrollBar *_scrollBar; Enum::ScrollBarPositionEnum _scrollbarLocation; bool _scrollFullPage; QString _wordCharacters; int _bellMode; bool _allowBlinkingText; // allow text to blink bool _allowBlinkingCursor; // allow cursor to blink bool _textBlinking; // text is blinking, hide it when drawing bool _cursorBlinking; // cursor is blinking, hide it when drawing bool _hasTextBlinker; // has characters to blink QTimer *_blinkTextTimer; QTimer *_blinkCursorTimer; Qt::KeyboardModifiers _urlHintsModifiers; bool _showUrlHint; bool _reverseUrlHints; bool _openLinksByDirectClick; // Open URL and hosts by single mouse click bool _ctrlRequiredForDrag; // require Ctrl key for drag selected text bool _dropUrlsAsText; // always paste URLs as text without showing copy/move menu Enum::TripleClickModeEnum _tripleClickMode; bool _possibleTripleClick; // is set in mouseDoubleClickEvent and deleted // after QApplication::doubleClickInterval() delay QLabel *_resizeWidget; QTimer *_resizeTimer; bool _flowControlWarningEnabled; //widgets related to the warning message that appears when the user presses Ctrl+S to suspend //terminal output - informing them what has happened and how to resume output KMessageWidget *_outputSuspendedMessageWidget; uint _lineSpacing; QSize _size; QRgb _blendColor; ColorScheme const* _colorScheme; ColorSchemeWallpaper::Ptr _wallpaper; // list of filters currently applied to the display. used for links and // search highlight TerminalImageFilterChain *_filterChain; QRegion _mouseOverHotspotArea; bool _filterUpdateRequired; Enum::CursorShapeEnum _cursorShape; // cursor color. If it is invalid (by default) then the foreground // color of the character under the cursor is used QColor _cursorColor; struct InputMethodData { QString preeditString; QRect previousPreeditRect; }; InputMethodData _inputMethodData; bool _antialiasText; // do we anti-alias or not bool _useFontLineCharacters; bool _printerFriendly; // are we currently painting to a printer in black/white mode //the delay in milliseconds between redrawing blinking text static const int TEXT_BLINK_DELAY = 500; //the duration of the size hint in milliseconds static const int SIZE_HINT_DURATION = 1000; SessionController *_sessionController; bool _trimLeadingSpaces; // trim leading spaces in selected text bool _trimTrailingSpaces; // trim trailing spaces in selected text bool _mouseWheelZoom; // enable mouse wheel zooming or not int _margin; // the contents margin bool _centerContents; // center the contents between margins KMessageWidget *_readOnlyMessageWidget; // Message shown at the top when read-only mode gets activated // Needed to know whether the mode really changed between update calls bool _readOnly; qreal _opacity; bool _dimWhenInactive; ScrollState _scrollWheelState; IncrementalSearchBar *_searchBar; TerminalHeaderBar *_headerBar; QRect _searchResultRect; friend class TerminalDisplayAccessible; bool _drawOverlay; Qt::Edge _overlayEdge; }; class AutoScrollHandler : public QObject { Q_OBJECT public: explicit AutoScrollHandler(QWidget *parent); protected: - void timerEvent(QTimerEvent *event) Q_DECL_OVERRIDE; - bool eventFilter(QObject *watched, QEvent *event) Q_DECL_OVERRIDE; + void timerEvent(QTimerEvent *event) override; + bool eventFilter(QObject *watched, QEvent *event) override; private: QWidget *widget() const { return static_cast(parent()); } int _timerId; }; } #endif // TERMINALDISPLAY_H diff --git a/src/ViewContainer.h b/src/ViewContainer.h index 5932f3bc..d96a0c92 100644 --- a/src/ViewContainer.h +++ b/src/ViewContainer.h @@ -1,223 +1,223 @@ /* This file is part of the Konsole Terminal. Copyright 2006-2008 Robert Knight This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #ifndef VIEWCONTAINER_H #define VIEWCONTAINER_H // Qt #include #include // Konsole #include "Profile.h" #include "ViewManager.h" // Qt class QPoint; class QToolButton; class QMenu; namespace Konsole { class ViewProperties; class ViewManager; class TabbedViewContainer; /** * An interface for container widgets which can hold one or more views. * * The container widget typically displays a list of the views which * it has and provides a means of switching between them. * * Subclasses should reimplement the addViewWidget() and removeViewWidget() functions * to actually add or remove view widgets from the container widget, as well * as updating any navigation aids. */ class KONSOLEPRIVATE_EXPORT TabbedViewContainer : public QTabWidget { Q_OBJECT public: /** * Constructs a new view container with the specified parent. * * @param connectedViewManager Connect the new view to this manager * @param parent The parent object of the container */ TabbedViewContainer(ViewManager *connectedViewManager, QWidget *parent); /** * Called when the ViewContainer is destroyed. When reimplementing this in * subclasses, use object->deleteLater() to delete any widgets or other objects * instead of 'delete object'. */ - ~TabbedViewContainer() Q_DECL_OVERRIDE; + ~TabbedViewContainer() override; /** Adds a new view to the container widget */ void addView(TerminalDisplay *view); void addSplitter(ViewSplitter *splitter, int index = -1); /** splits the currently focused Splitter */ void splitView(TerminalDisplay *view, Qt::Orientation orientation); void setTabActivity(int index, bool activity); void updateTitle(ViewProperties *item); void updateIcon(ViewProperties *item); void updateActivity(ViewProperties *item); /** Changes the active view to the next view */ void activateNextView(); /** Changes the active view to the previous view */ void activatePreviousView(); /** Changes the active view to the last view */ void activateLastView(); void setCss(const QString& styleSheet = QString()); void setCssFromFile(const QUrl& url); ViewSplitter *activeViewSplitter(); /** * This enum describes the directions * in which views can be re-arranged within the container * using the moveActiveView() method. */ enum MoveDirection { /** Moves the view to the left. */ MoveViewLeft, /** Moves the view to the right. */ MoveViewRight }; /** * Moves the active view within the container and * updates the order in which the views are shown * in the container's navigation widget. * * The default implementation does nothing. */ void moveActiveView(MoveDirection direction); /** Sets the menu to be shown when the new view button is clicked. * Only valid if the QuickNewView feature is enabled. * The default implementation does nothing. */ // TODO: Reenable this later. // void setNewViewMenu(QMenu *menu); void renameTab(int index); ViewManager *connectedViewManager(); void currentTabChanged(int index); void closeCurrentTab(); void wheelScrolled(int delta); void currentSessionControllerChanged(SessionController *controller); void tabDoubleClicked(int index); void openTabContextMenu(const QPoint &point); void setNavigationVisibility(ViewManager::NavigationVisibility navigationVisibility); void moveTabToWindow(int index, QWidget *window); void toggleMaximizeCurrentTerminal(); /* return the widget(int index) casted to TerminalDisplay* * * The only thing that this class holds are TerminalDisplays, so * this is the only thing that should be used to retrieve widgets. */ ViewSplitter *viewSplitterAt(int index); void connectTerminalDisplay(TerminalDisplay *view); void disconnectTerminalDisplay(TerminalDisplay *view); void moveTabLeft(); void moveTabRight(); /** * This enum describes where newly created tab should be placed. */ enum NewTabBehavior { /** Put newly created tab at the end. */ PutNewTabAtTheEnd = 0, /** Put newly created tab right after current tab. */ PutNewTabAfterCurrentTab = 1 }; void setNavigationBehavior(int behavior); void terminalDisplayDropped(TerminalDisplay* terminalDisplay); QSize sizeHint() const override; Q_SIGNALS: /** Emitted when the container has no more children */ void empty(TabbedViewContainer *container); /** Emitted when the user requests to open a new view */ void newViewRequest(); /** Requests creation of a new view, with the selected profile. */ void newViewWithProfileRequest(const Profile::Ptr&); /** a terminalDisplay was dropped in a child Splitter */ /** * Emitted when the user requests to move a view from another container * into this container. If 'success' is set to true by a connected slot * then the original view will be removed. * * @param index Index at which to insert the new view in the container * or -1 to append it. This index should be passed to addView() when * the new view has been created. * @param sessionControllerId The identifier of the view. */ void moveViewRequest(int index, int sessionControllerId); /** Emitted when the active view changes */ void activeViewChanged(TerminalDisplay *view); /** Emitted when a view is added to the container. */ void viewAdded(TerminalDisplay *view); /** Emitted when a view is removed from the container. */ void viewRemoved(TerminalDisplay *view); /** detach the specific tab */ void detachTab(int tabIdx); protected: // close tabs and unregister void closeTerminalTab(int idx); - void keyReleaseEvent(QKeyEvent *event) Q_DECL_OVERRIDE; + void keyReleaseEvent(QKeyEvent *event) override; private Q_SLOTS: void viewDestroyed(QObject *view); void konsoleConfigChanged(); private: void forgetView(ViewSplitter *view); ViewManager *_connectedViewManager; QMenu *_contextPopupMenu; QToolButton *_newTabButton; QToolButton *_closeTabButton; int _contextMenuTabIndex; ViewManager::NavigationVisibility _navigationVisibility; NewTabBehavior _newTabBehavior; }; } #endif //VIEWCONTAINER_H diff --git a/src/ViewManager.h b/src/ViewManager.h index cded6a38..6f5ea4e5 100644 --- a/src/ViewManager.h +++ b/src/ViewManager.h @@ -1,447 +1,447 @@ /* Copyright 2006-2008 by Robert Knight This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #ifndef VIEWMANAGER_H #define VIEWMANAGER_H // Qt #include #include #include #include // Konsole #include "Profile.h" class KActionCollection; class KConfigGroup; namespace Konsole { class ColorScheme; class Session; class TerminalDisplay; class TabbedViewContainer; class SessionController; class ViewProperties; class ViewSplitter; class TabbedViewContainer; /** * Manages the terminal display widgets in a Konsole window or part. * * When a view manager is created, it constructs a tab widget ( accessed via * widget() ) to hold one or more view splitters. Each view splitter holds * one or more terminal displays and splitters. * * The view manager provides menu actions ( defined in the 'konsoleui.rc' XML file ) * to manipulate the views and view containers - for example, actions to split the view * left/right or top/bottom, detach a view from the current window and navigate between * views and containers. These actions are added to the collection specified in the * ViewManager's constructor. * * The view manager provides facilities to construct display widgets for a terminal * session and also to construct the SessionController which provides the menus and other * user interface elements specific to each display/session pair. * */ class KONSOLEPRIVATE_EXPORT ViewManager : public QObject { Q_OBJECT Q_CLASSINFO("D-Bus Interface", "org.kde.konsole.Window") public: /** * Constructs a new view manager with the specified @p parent. * View-related actions defined in 'konsoleui.rc' are created * and added to the specified @p collection. */ ViewManager(QObject *parent, KActionCollection *collection); - ~ViewManager() Q_DECL_OVERRIDE; + ~ViewManager() override; /** * Creates a new view to display the output from and deliver input to @p session. * Constructs a new container to hold the views if no container has yet been created. */ void createView(TabbedViewContainer *tabWidget, Session *session); /* * Applies the view-specific settings associated with specified @p profile * to the terminal display @p view. */ void applyProfileToView(TerminalDisplay *view, const Profile::Ptr &profile); void toggleActionsBasedOnState(); /** * Return the main widget for the view manager which * holds all of the views managed by this ViewManager instance. */ QWidget *widget() const; /** * Returns the view manager's active view. */ QWidget *activeView() const; /** * Returns the list of view properties for views in the active container. * Each view widget is associated with a ViewProperties instance which * provides access to basic information about the session being * displayed in the view, such as title, current directory and * associated icon. */ QList viewProperties() const; /** * This enum describes the available types of navigation widget * which newly created containers can provide to allow navigation * between open sessions. */ enum NavigationMethod { /** * Each container has a row of tabs (one per session) which the user * can click on to navigate between open sessions. */ TabbedNavigation, /** The container has no navigation widget. */ NoNavigation }; /** * Describes the options for showing or hiding the container's navigation widget. */ enum NavigationVisibility { NavigationNotSet, // Don't rely on this information, Only use the settings. AlwaysShowNavigation, ShowNavigationAsNeeded, AlwaysHideNavigation }; /** * Sets the visibility of the view container's navigation widget. * The ViewContainer subclass is responsible for ensuring that this * setting is respected as views are dded or removed from the container */ void setNavigationVisibility(NavigationVisibility navigationVisibility); /** Returns the current mode for controlling the visibility of the * view container's navigation widget. */ NavigationVisibility navigationVisibility() const; /** * Sets the type of widget provided to navigate between open sessions * in a container. The changes will only apply to newly created containers. * * The default method is TabbedNavigation. To disable navigation widgets, call * setNavigationMethod(ViewManager::NoNavigation) before creating any sessions. */ void setNavigationMethod(NavigationMethod method); /** * Returns the type of navigation widget created in new containers. * See setNavigationMethod() */ NavigationMethod navigationMethod() const; /** * Returns the controller for the active view. activeViewChanged() is * emitted when this changes. */ SessionController *activeViewController() const; /** * Session management */ void saveSessions(KConfigGroup &group); void restoreSessions(const KConfigGroup &group); int managerId() const; /** Returns a list of sessions in this ViewManager */ QList sessions() { return _sessionMap.values(); } /** * Returns whether the @p profile has the blur setting enabled */ static bool profileHasBlurEnabled(const Profile::Ptr &profile); /** returns the active tab from the view */ TabbedViewContainer *activeContainer(); TerminalDisplay *createView(Session *session); void attachView(TerminalDisplay *terminal, Session *session); static const ColorScheme *colorSchemeForProfile(const Profile::Ptr &profile); /** Reorder the terminal display history list */ void updateTerminalDisplayHistory(TerminalDisplay *terminalDisplay = nullptr, bool remove = false); QHash forgetAll(ViewSplitter* splitter); Session* forgetTerminal(TerminalDisplay* terminal); /** * Creates and returns new session * * The session has specified @p profile, working @p directory * and configured environment. */ Session* createSession(const Profile::Ptr &profile, const QString &directory = QString()); Q_SIGNALS: /** Emitted when the last view is removed from the view manager */ void empty(); /** Emitted when a session is detached from a view owned by this ViewManager */ void terminalsDetached(ViewSplitter *splitter, QHash sessionsMap); /** * Emitted when the active view changes. * @param controller The controller associated with the active view */ void activeViewChanged(SessionController *controller); /** * Emitted when the current session needs unplugged from factory(). * @param controller The controller associated with the active view */ void unplugController(SessionController *controller); /** * Emitted when the list of view properties ( as returned by viewProperties() ) changes. * This occurs when views are added to or removed from the active container, or * if the active container is changed. */ void viewPropertiesChanged(const QList &propertiesList); /** * Emitted when menu bar visibility changes because a profile that requires so is * activated. */ void setMenuBarVisibleRequest(bool); void updateWindowIcon(); void blurSettingChanged(bool); /** Requests creation of a new view with the default profile. */ void newViewRequest(); /** Requests creation of a new view, with the selected profile. */ void newViewWithProfileRequest(const Profile::Ptr&); public Q_SLOTS: /** DBus slot that returns the number of sessions in the current view. */ Q_SCRIPTABLE int sessionCount(); /** * DBus slot that returns the unique ids of the sessions in the * current view. The returned list is not sorted. * QList is not printable by qdbus so we use QStringList */ Q_SCRIPTABLE QStringList sessionList(); /** DBus slot that returns the current (active) session window */ Q_SCRIPTABLE int currentSession(); /** DBus slot that sets the current (active) session window */ Q_SCRIPTABLE void setCurrentSession(int sessionId); /** DBus slot that creates a new session in the current view with the associated * default profile and the default working directory */ Q_SCRIPTABLE int newSession(); /** DBus slot that creates a new session in the current view. * @param profile the name of the profile to be used * started. */ Q_SCRIPTABLE int newSession(const QString &profile); /** DBus slot that creates a new session in the current view. * @param profile the name of the profile to be used * @param directory the working directory where the session is * started. */ Q_SCRIPTABLE int newSession(const QString &profile, const QString &directory); // TODO: its semantic is application-wide. Move it to more appropriate place // DBus slot that returns the name of default profile Q_SCRIPTABLE QString defaultProfile(); // TODO: its semantic is application-wide. Move it to more appropriate place // DBus slot that returns a string list of defined (known) profiles Q_SCRIPTABLE QStringList profileList(); /** DBus slot that changes the view port to the next session */ Q_SCRIPTABLE void nextSession(); /** DBus slot that changes the view port to the previous session */ Q_SCRIPTABLE void prevSession(); /** DBus slot that switches the current session (as returned by * currentSession()) with the left (or previous) one in the * navigation tab. */ Q_SCRIPTABLE void moveSessionLeft(); /** DBus slot that Switches the current session (as returned by * currentSession()) with the right (or next) one in the navigation * tab. */ Q_SCRIPTABLE void moveSessionRight(); /** DBus slot that sets ALL tabs' width to match their text */ Q_SCRIPTABLE void setTabWidthToText(bool); private Q_SLOTS: // called when the "Split View Left/Right" menu item is selected void splitLeftRight(); void splitTopBottom(); void expandActiveContainer(); void shrinkActiveContainer(); // called when the "Detach View" menu item is selected void detachActiveView(); void detachActiveTab(); // called when a session terminates - the view manager will delete any // views associated with the session void sessionFinished(); // called when one view has been destroyed void viewDestroyed(QWidget *view); // controller detects when an associated view is given the focus // and emits a signal. ViewManager listens for that signal // and then plugs the action into the UI //void viewFocused( SessionController* controller ); // called when the active view in a ViewContainer changes, so // that we can plug the appropriate actions into the UI void viewActivated(TerminalDisplay *view); void focusUp(); void focusDown(); void focusLeft(); void focusRight(); // called when "Next View" shortcut is activated void nextView(); // called when "Previous View" shortcut is activated void previousView(); // called when "Switch to last tab" shortcut is activated void lastView(); // called when "Switch to last used tab" shortcut is activated void lastUsedView(); // called when "Switch to last used tab (reverse)" shortcut is activated void lastUsedViewReverse(); // called when "Next View Container" shortcut is activated void nextContainer(); // called when "Toggle Two tabs" shortcut is activated void toggleTwoViews(); // called when the views in a container owned by this view manager // changes void containerViewsChanged(TabbedViewContainer *container); // called when a profile changes void profileChanged(const Profile::Ptr &profile); void updateViewsForSession(Session *session); // moves active view to the left void moveActiveViewLeft(); // moves active view to the right void moveActiveViewRight(); // switches to the view at visual position 'index' // in the current container void switchToView(int index); // gives focus and switches the terminal display, changing tab if needed void switchToTerminalDisplay(TerminalDisplay *terminalDisplay); // called when a SessionController gains focus void controllerChanged(SessionController *controller); /* Detaches the tab at index tabIdx */ void detachTab(int tabIdx); private: Q_DISABLE_COPY(ViewManager) void createView(Session *session, TabbedViewContainer *container, int index); void setupActions(); // takes a view from a view container owned by a different manager and places it in // newContainer owned by this manager void takeView(ViewManager *otherManager, TabbedViewContainer *otherContainer, TabbedViewContainer *newContainer, TerminalDisplay *view); void splitView(Qt::Orientation orientation); // creates a new container which can hold terminal displays TabbedViewContainer *createContainer(); // creates a new terminal display // the 'session' is used so that the terminal display's random seed // can be set to something which depends uniquely on that session TerminalDisplay *createTerminalDisplay(Session *session = nullptr); // creates a new controller for a session/display pair which provides the menu // actions associated with that view, and exposes basic information // about the session ( such as title and associated icon ) to the display. SessionController *createController(Session *session, TerminalDisplay *view); void removeController(SessionController* controller); // Activates a different terminal when the TerminalDisplay // closes or is detached and another one should be focused. // It will activate the last used terminal within the same splitView // if possible otherwise it will focus the last used tab void focusAnotherTerminal(ViewSplitter *toplevelSplitter); void activateLastUsedView(bool reverse); private: QPointer _viewContainer; QPointer _pluggedController; QHash _sessionMap; KActionCollection *_actionCollection; NavigationMethod _navigationMethod; NavigationVisibility _navigationVisibility; int _managerId; static int lastManagerId; QList _terminalDisplayHistory; int _terminalDisplayHistoryIndex; // List of actions that should only be enabled when there are multiple view // containers open QList _multiTabOnlyActions; QList _multiSplitterOnlyActions; }; } #endif diff --git a/src/ViewProperties.h b/src/ViewProperties.h index c128605c..22b0fafd 100644 --- a/src/ViewProperties.h +++ b/src/ViewProperties.h @@ -1,128 +1,128 @@ /* Copyright 2007-2008 by Robert Knight This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #ifndef VIEWPROPERTIES_H #define VIEWPROPERTIES_H // Qt #include #include #include #include // Konsole #include "konsoleprivate_export.h" namespace Konsole { /** * Encapsulates user-visible information about the terminal session currently being displayed in a view, * such as the associated title and icon. * * This can be used by navigation widgets in a ViewContainer sub-class to provide a tab, label or other * item for switching between views. */ class KONSOLEPRIVATE_EXPORT ViewProperties : public QObject { Q_OBJECT public: explicit ViewProperties(QObject *parent); - ~ViewProperties() Q_DECL_OVERRIDE; + ~ViewProperties() override; /** Returns the icon associated with a view */ QIcon icon() const; /** Returns the title associated with a view */ QString title() const; /** * Returns the URL current associated with a view. * The default implementation returns an empty URL. */ virtual QUrl url() const; /** * Returns the current directory associated with a view. * This may be the same as url() * The default implementation returns an empty string. */ virtual QString currentDir() const; /** * A unique identifier associated with this * ViewProperties instance. */ int identifier() const; /** * Sub-classes may re-implement this method to display a message to the user * to allow them to confirm whether to close a view. * The default implementation always returns true */ virtual bool confirmClose() const { return true; } /** Finds a ViewProperties instance given its numeric identifier. */ static ViewProperties *propertiesById(int id); Q_SIGNALS: /** Emitted when the icon for a view changes */ void iconChanged(ViewProperties *properties); /** Emitted when the title for a view changes */ void titleChanged(ViewProperties *properties); /** Emitted when activity has occurred in this view. */ void activity(ViewProperties *item); public Q_SLOTS: /** * Requests the renaming of this view. * The default implementation does nothing. */ virtual void rename(); protected Q_SLOTS: /** Emits the activity() signal. */ void fireActivity(); protected: /** * Subclasses may call this method to change the title. This causes * a titleChanged() signal to be emitted */ void setTitle(const QString &title); /** * Subclasses may call this method to change the icon. This causes * an iconChanged() signal to be emitted */ void setIcon(const QIcon &icon); /** Subclasses may call this method to change the identifier. */ void setIdentifier(int id); private: Q_DISABLE_COPY(ViewProperties) QIcon _icon; QString _title; int _identifier; static QHash _viewProperties; }; } #endif //VIEWPROPERTIES_H diff --git a/src/Vt102Emulation.h b/src/Vt102Emulation.h index 7fa395d7..163f68c1 100644 --- a/src/Vt102Emulation.h +++ b/src/Vt102Emulation.h @@ -1,195 +1,195 @@ /* This file is part of Konsole, an X terminal. Copyright 2007-2008 by Robert Knight Copyright 1997,1998 by Lars Doelle This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #ifndef VT102EMULATION_H #define VT102EMULATION_H // Qt #include // Konsole #include "Emulation.h" #include "Screen.h" class QTimer; class QKeyEvent; #define MODE_AppScreen (MODES_SCREEN+0) // Mode #1 #define MODE_AppCuKeys (MODES_SCREEN+1) // Application cursor keys (DECCKM) #define MODE_AppKeyPad (MODES_SCREEN+2) // #define MODE_Mouse1000 (MODES_SCREEN+3) // Send mouse X,Y position on press and release #define MODE_Mouse1001 (MODES_SCREEN+4) // Use Hilight mouse tracking #define MODE_Mouse1002 (MODES_SCREEN+5) // Use cell motion mouse tracking #define MODE_Mouse1003 (MODES_SCREEN+6) // Use all motion mouse tracking #define MODE_Mouse1005 (MODES_SCREEN+7) // Xterm-style extended coordinates #define MODE_Mouse1006 (MODES_SCREEN+8) // 2nd Xterm-style extended coordinates #define MODE_Mouse1007 (MODES_SCREEN+9) // XTerm Alternate Scroll mode; also check AlternateScrolling profile property #define MODE_Mouse1015 (MODES_SCREEN+10) // Urxvt-style extended coordinates #define MODE_Ansi (MODES_SCREEN+11) // Use US Ascii for character sets G0-G3 (DECANM) #define MODE_132Columns (MODES_SCREEN+12) // 80 <-> 132 column mode switch (DECCOLM) #define MODE_Allow132Columns (MODES_SCREEN+13) // Allow DECCOLM mode #define MODE_BracketedPaste (MODES_SCREEN+14) // Xterm-style bracketed paste mode #define MODE_total (MODES_SCREEN+15) namespace Konsole { extern unsigned short vt100_graphics[32]; struct CharCodes { // coding info char charset[4]; // int cu_cs; // actual charset. bool graphic; // Some VT100 tricks bool pound; // Some VT100 tricks bool sa_graphic; // saved graphic bool sa_pound; // saved pound }; /** * Provides an xterm compatible terminal emulation based on the DEC VT102 terminal. * A full description of this terminal can be found at https://vt100.net/docs/vt102-ug/ * * In addition, various additional xterm escape sequences are supported to provide * features such as mouse input handling. * See http://rtfm.etla.org/xterm/ctlseq.html for a description of xterm's escape * sequences. * */ class Vt102Emulation : public Emulation { Q_OBJECT public: /** Constructs a new emulation */ Vt102Emulation(); - ~Vt102Emulation() Q_DECL_OVERRIDE; + ~Vt102Emulation() override; // reimplemented from Emulation - void clearEntireScreen() Q_DECL_OVERRIDE; - void reset() Q_DECL_OVERRIDE; - char eraseChar() const Q_DECL_OVERRIDE; + void clearEntireScreen() override; + void reset() override; + char eraseChar() const override; public Q_SLOTS: // reimplemented from Emulation - void sendString(const QByteArray &string) Q_DECL_OVERRIDE; - void sendText(const QString &text) Q_DECL_OVERRIDE; - void sendKeyEvent(QKeyEvent *) Q_DECL_OVERRIDE; - void sendMouseEvent(int buttons, int column, int line, int eventType) Q_DECL_OVERRIDE; - void focusLost() Q_DECL_OVERRIDE; - void focusGained() Q_DECL_OVERRIDE; + void sendString(const QByteArray &string) override; + void sendText(const QString &text) override; + void sendKeyEvent(QKeyEvent *) override; + void sendMouseEvent(int buttons, int column, int line, int eventType) override; + void focusLost() override; + void focusGained() override; protected: // reimplemented from Emulation - void setMode(int mode) Q_DECL_OVERRIDE; - void resetMode(int mode) Q_DECL_OVERRIDE; - void receiveChar(uint cc) Q_DECL_OVERRIDE; + void setMode(int mode) override; + void resetMode(int mode) override; + void receiveChar(uint cc) override; private Q_SLOTS: // Causes sessionAttributeChanged() to be emitted for each (int,QString) // pair in _pendingSessionAttributesUpdates. // Used to buffer multiple attribute updates in the current session void updateSessionAttributes(); private: unsigned int applyCharset(uint c); void setCharset(int n, int cs); void useCharset(int n); void setAndUseCharset(int n, int cs); void saveCursor(); void restoreCursor(); void resetCharset(int scrno); void setMargins(int top, int bottom); //set margins for all screens back to their defaults void setDefaultMargins(); // returns true if 'mode' is set or false otherwise bool getMode(int mode); // saves the current boolean value of 'mode' void saveMode(int mode); // restores the boolean value of 'mode' void restoreMode(int mode); // resets all modes // (except MODE_Allow132Columns) void resetModes(); void resetTokenizer(); #define MAX_TOKEN_LENGTH 256 // Max length of tokens (e.g. window title) void addToCurrentToken(uint cc); uint tokenBuffer[MAX_TOKEN_LENGTH]; //FIXME: overflow? int tokenBufferPos; #define MAXARGS 15 void addDigit(int dig); void addArgument(); int argv[MAXARGS]; int argc; void initTokenizer(); // Set of flags for each of the ASCII characters which indicates // what category they fall into (printable character, control, digit etc.) // for the purposes of decoding terminal output int charClass[256]; void reportDecodingError(); void processToken(int code, int p, int q); void processSessionAttributeRequest(int tokenSize); void reportTerminalType(); void reportSecondaryAttributes(); void reportStatus(); void reportAnswerBack(); void reportCursorPosition(); void reportTerminalParms(int p); // clears the screen and resizes it to the specified // number of columns void clearScreenAndSetColumns(int columnCount); CharCodes _charset[2]; class TerminalState { public: // Initializes all modes to false TerminalState() { memset(&mode, 0, MODE_total * sizeof(bool)); } bool mode[MODE_total]; }; TerminalState _currentModes; TerminalState _savedModes; // Hash table and timer for buffering calls to update certain session // attributes (e.g. the name of the session, window title). // These calls occur when certain escape sequences are detected in the // output from the terminal. See Emulation::sessionAttributeChanged() QHash _pendingSessionAttributesUpdates; QTimer *_sessionAttributesUpdateTimer; bool _reportFocusEvents; }; } #endif // VT102EMULATION_H diff --git a/src/settings/GeneralSettings.h b/src/settings/GeneralSettings.h index 058a0772..307f903d 100644 --- a/src/settings/GeneralSettings.h +++ b/src/settings/GeneralSettings.h @@ -1,40 +1,40 @@ /* Copyright 2011 Kurt Hindenburg 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) version 3 or any later version accepted by the membership of KDE e.V. (or its successor appro- ved by the membership of KDE e.V.), which shall act as a proxy defined in Section 14 of version 3 of the license. 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 http://www.gnu.org/licenses/. */ #ifndef GENERALSETTINGS_H #define GENERALSETTINGS_H #include "ui_GeneralSettings.h" namespace Konsole { class GeneralSettings : public QWidget, private Ui::GeneralSettings { Q_OBJECT public: explicit GeneralSettings(QWidget *aParent = nullptr); - ~GeneralSettings() Q_DECL_OVERRIDE; + ~GeneralSettings() override; public Q_SLOTS: void slotEnableAllMessages(); }; } #endif diff --git a/src/settings/PartInfo.h b/src/settings/PartInfo.h index 423d09b2..f504a4bb 100644 --- a/src/settings/PartInfo.h +++ b/src/settings/PartInfo.h @@ -1,37 +1,37 @@ /* Copyright 2017 Kurt Hindenburg 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) version 3 or any later version accepted by the membership of KDE e.V. (or its successor appro- ved by the membership of KDE e.V.), which shall act as a proxy defined in Section 14 of version 3 of the license. 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 http://www.gnu.org/licenses/. */ #ifndef PARTINFO_H #define PARTINFO_H #include "ui_PartInfo.h" namespace Konsole { class PartInfoSettings : public QWidget, private Ui::PartInfoSettings { Q_OBJECT public: explicit PartInfoSettings(QWidget *parent = nullptr); - ~PartInfoSettings() Q_DECL_OVERRIDE; + ~PartInfoSettings() override; }; } #endif diff --git a/src/settings/ProfileSettings.h b/src/settings/ProfileSettings.h index 66b09366..1e1d93f3 100644 --- a/src/settings/ProfileSettings.h +++ b/src/settings/ProfileSettings.h @@ -1,163 +1,163 @@ /* Copyright 2007-2008 by Robert Knight This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #ifndef PROFILESETTINGS_H #define PROFILESETTINGS_H // Qt #include #include #include // KDE // Konsole #include "Profile.h" #include "ui_ProfileSettings.h" class QItemSelection; class QStandardItem; class QStandardItemModel; namespace Konsole { /** * A dialog which lists the available types of profiles and allows * the user to add new profiles, and remove or edit existing * profile types. */ class ProfileSettings : public QWidget, private Ui::ProfileSettings { Q_OBJECT friend class ShortcutItemDelegate; public: /** Constructs a new profile type with the specified parent. */ explicit ProfileSettings(QWidget *parent = nullptr); - ~ProfileSettings() Q_DECL_OVERRIDE; + ~ProfileSettings() override; /** * Specifies whether the shortcut editor should be show. * The shortcut editor allows shortcuts to be associated with * profiles. When a shortcut is changed, the dialog will call * SessionManager::instance()->setShortcut() to update the shortcut * associated with the profile. * * By default the editor is visible. */ void setShortcutEditorVisible(bool visible); protected: private Q_SLOTS: void slotAccepted(); void deleteSelected(); void setSelectedAsDefault(); void createProfile(); void editSelected(); void itemDataChanged(QStandardItem *item); // enables or disables Edit/Delete/Set as Default buttons when the // selection changes void tableSelectionChanged(const QItemSelection &); void updateFavoriteStatus(const Profile::Ptr &profile, bool favorite); void addItems(const Profile::Ptr&); void updateItems(const Profile::Ptr&); void removeItems(const Profile::Ptr&); // double clicking the profile name opens the edit profile dialog void doubleClicked(const QModelIndex &index); private: Profile::Ptr currentProfile() const; QList selectedProfiles() const; bool isProfileDeletable(Profile::Ptr profile) const; // updates the font of the items to match // their default / non-default profile status void updateDefaultItem(); void updateItemsForProfile(const Profile::Ptr &profile,const QList &items) const; void updateShortcutField(QStandardItem *item, bool isFavorite) const; // updates the profile table to be in sync with the // session manager void populateTable(); int rowForProfile(const Profile::Ptr &profile) const; QStandardItemModel *_sessionModel; enum Column { FavoriteStatusColumn = 0, ProfileNameColumn = 1, ShortcutColumn = 2, ProfileColumn = 3, }; enum Role { ProfilePtrRole = Qt::UserRole + 1, ShortcutRole, }; }; class StyledBackgroundPainter { public: static void drawBackground(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index); }; class FilteredKeySequenceEdit: public QKeySequenceEdit { Q_OBJECT public: explicit FilteredKeySequenceEdit(QWidget *parent = nullptr): QKeySequenceEdit(parent) {} protected: - void keyPressEvent(QKeyEvent *event) Q_DECL_OVERRIDE; + void keyPressEvent(QKeyEvent *event) override; }; class ShortcutItemDelegate : public QStyledItemDelegate { Q_OBJECT public: explicit ShortcutItemDelegate(QObject *parent = nullptr); void setModelData(QWidget *editor, QAbstractItemModel *model, - const QModelIndex &index) const Q_DECL_OVERRIDE; + const QModelIndex &index) const override; QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &option, - const QModelIndex &index) const Q_DECL_OVERRIDE; + const QModelIndex &index) const override; void paint(QPainter *painter, const QStyleOptionViewItem &option, - const QModelIndex &index) const Q_DECL_OVERRIDE; + const QModelIndex &index) const override; QSize sizeHint(const QStyleOptionViewItem &option, - const QModelIndex &index) const Q_DECL_OVERRIDE; - void destroyEditor(QWidget *editor, const QModelIndex &index) const Q_DECL_OVERRIDE; + const QModelIndex &index) const override; + void destroyEditor(QWidget *editor, const QModelIndex &index) const override; private Q_SLOTS: void editorModified(); private: mutable QSet _modifiedEditors; mutable QSet _itemsBeingEdited; }; } #endif // MANAGEPROFILESDIALOG_H diff --git a/src/settings/TabBarSettings.h b/src/settings/TabBarSettings.h index 220347f2..53fe2193 100644 --- a/src/settings/TabBarSettings.h +++ b/src/settings/TabBarSettings.h @@ -1,37 +1,37 @@ /* Copyright 2011 Kurt Hindenburg 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) version 3 or any later version accepted by the membership of KDE e.V. (or its successor appro- ved by the membership of KDE e.V.), which shall act as a proxy defined in Section 14 of version 3 of the license. 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 http://www.gnu.org/licenses/. */ #ifndef TABBARSETTINGS_H #define TABBARSETTINGS_H #include "ui_TabBarSettings.h" namespace Konsole { class TabBarSettings : public QWidget, private Ui::TabBarSettings { Q_OBJECT public: explicit TabBarSettings(QWidget *parent = nullptr); - ~TabBarSettings() Q_DECL_OVERRIDE; + ~TabBarSettings() override; }; } #endif