pax_global_header00006660000000000000000000000064137015777050014526gustar00rootroot0000000000000052 comment=808e0881d8b9ce88819d19faac0ff24b85112c32 deepin-terminal-5.2.11/000077500000000000000000000000001370157770500146715ustar00rootroot00000000000000deepin-terminal-5.2.11/.gitignore000066400000000000000000000001631370157770500166610ustar00rootroot00000000000000# User config *.user moc_*.h moc_*.cpp *.moc build/ .vscode/ build-*/ CMakeLists.txt.user deepin-terminal.pro.user deepin-terminal-5.2.11/.project.json000066400000000000000000000006261370157770500173140ustar00rootroot00000000000000 { "type": "homebrew", "3rdparty": ["./3rdparty"], "ignore": [".git", "translations", "debian", "color-schemes", "kb-layouts", "LineFont.src", "CMakeLists.txt.user", "README", "README.md", "CHANGELOG", "COPYING-CMAKE-SCRIPTS", "LICENSE", "LICENSE.*", "*.keytab", "*.spec", "*.cmake", "*.desktop", "./.tx", "*.qrc", "*.svg", "*.png", "*.qm", "*.ts"], "license": ["GPLv3"] } deepin-terminal-5.2.11/.tx/000077500000000000000000000000001370157770500154025ustar00rootroot00000000000000deepin-terminal-5.2.11/.tx/config000066400000000000000000000011611370157770500165710ustar00rootroot00000000000000[main] host = https://www.transifex.com minimum_perc = 80 mode = developer [deepin-terminal.deepin-terminal] file_filter = translations/deepin-terminal_.ts source_file = translations/deepin-terminal.ts source_lang = en_US type = QT [deepin-terminal.terminalwidget] file_filter = 3rdparty/terminalwidget/lib/translations/terminalwidget_.ts source_file = 3rdparty/terminalwidget/lib/translations/terminalwidget.ts source_lang = en_US type = QT [deepin-terminal.deepin-terminal-desktop] file_filter = translations/desktop/desktop_.ts source_file = translations/desktop/desktop.ts source_lang = en type = QT deepin-terminal-5.2.11/.tx/ts2desktop000066400000000000000000000002501370157770500174240ustar00rootroot00000000000000DESKTOP_TEMP_FILE=deepin-terminal.desktop.tmp DESKTOP_SOURCE_FILE=deepin-terminal.desktop DESKTOP_DEST_FILE=deepin-terminal.desktop DESKTOP_TS_DIR=translations/desktop deepin-terminal-5.2.11/3rdparty/000077500000000000000000000000001370157770500164415ustar00rootroot00000000000000deepin-terminal-5.2.11/3rdparty/terminalwidget/000077500000000000000000000000001370157770500214605ustar00rootroot00000000000000deepin-terminal-5.2.11/3rdparty/terminalwidget/AUTHORS000066400000000000000000000007011370157770500225260ustar00rootroot00000000000000Originally forked from Konsole by Revived by Petr Vanek Contributors: Adam Treat Chris Mueller Christian Surlykke Daniel O'Neill Francisco Ballina Georg Rudoy <0xd34df00d@gmail.com> Jerome Leclanche Petr Vanek @kulti deepin-terminal-5.2.11/3rdparty/terminalwidget/CHANGELOG000066400000000000000000000333211370157770500226740ustar00rootroot00000000000000qtermwidget-0.14.1 / 2019-02-25 =============================== * Bumped version to 0.14.1 * Only translations was changed. qtermwidget-0.14.0 / 2019-01-25 =============================== * Bumped version to 0.14.0 The big bump was needed to prevent conflicts with translations that were former built out of lxqt-l10n and have version 0.13.0 * Clarify the licenses used in qtermwidget and added the missed root licenses * Implementation fixes: - kpty: use openpty() on mac - kpty: make it work on OpenBSD - kptyprocess: ensure .bash_history is correctly written out - kb-layouts: Make Backspace behaves the same as xterm - tools: Drop the ability to bundle kb-layouts and colorschemes - SearchBar: Fix visual glitches in search-bar - TerminalDisplay: Fixed link mouseover after recent changes - TerminalDisplay: Redraw cursor after cursor type changed - Vt102Emulation: Fix handling of ST (String Terminator) for OSC (Operating System Commands) - qterminal: Correct deleting of HotSpot list items - qterminal: Removed unnecessary checks - ColorScheme: Fixed local variable will be copied despite being returned by name - ColorScheme: Fixed error return-std-move - Removed unnecessary checks - Suppressed compilation warnings - Don't use automatic string conversions - Marked some functions const - Implemented terminal margins * Improved cmake scripting - Set cmake_minimum_required to 3.1.0 - Removed locale compile definitons - Removed QUIET from find_package * Moved translations from lxqt-l10n back to qtermwidget - Removed obsolete translation fuctionality - Added translation promo in README.md * Translation updates qtermwidget-0.9.0 / 2018-05-21 ============================== * Bumped minor version to 9 * Take transient scrollbars into account * CMake: Prevent in-source builds * Refactor and fixes Python binding * kptyprocess: Try to terminate the shell process * New color scheme: Ubuntu inspired * Fixed some github pathes in uris * Add a comment for potential future breakage * Use wstring in TerminalCharacterDecoder for UCS-4 compatibility * Support UTF-32 characters correctly * Fix "bold and intensive" colors * New color scheme: Tango (#167) * Finish SGR mouse protocol (1006) * Fix build of example with latest lxqt-build-tools * Expose bracket text function * Drop Qt foreach. * Revert deletions in .sip file * fix python bindings * Expose terminal size hint API * Remove class name * Return something * Expose bidi option * Add an example for remote terminal * Makes the use of libutempter optional * Fix behavior of scroll up (SU) * Install cmake files in LIBDIR as they are architecture dependend * Check if utempter.h header exists (mainly for FreeBSD) * Need lxqt-build-tools 0.4.0 qtermwidget-0.8.0 / 2017-10-21 ================== * Release 0.8.0: Update changelog * FIX: #46 fix vertical font truncation * bump versions * Really fallback to /bin/sh when $SHELL is missing or invalid * README: don't recommend building from source * Improve README * Don't export github templates * Support REP escape sequence defined in ECMA-48, section 8.3.103 * Fix build issue related to utmpx in Mac OSX Sierra * Remove the deprecation notice * Handle DECSCUSR signals * Copied issue template * Update building instructions * Require Qt 5.6+ * This commit allows the consumer of qtermwidget to capture the (#111) * Allow the terminal display to be smaller than the size hint (#123) * Backport Vt102 emulation fixes (#113) * Backport the default.keytab from Konsole * Fixes (#122) * Updated README, Added support for PyQT 5.7 * Fix memory leak in hotspot (URLs & emails) detection * Adds superbuild support * Use target_compile_definitions() instead of add_definitions() * Update find_package() documentation * Use the lxqt_create_pkgconfig_file * Improve lxqt_translate_ts() use * Adds COMPONENT to the install files * Renames test app to example. Make it work * Drop include_directories() for in tree dirs * Use the CMake Targets way * Pack Utf8Proc stuff * Adds export header * Use LXQtCompilerSettings * Packs compile definitions * Adds package version file * Removes Qt4 stuff * Add translation mechanism * Use const iterators when possible. * Enable strict iterators for debug builds * TerminalDisplay: Make resizing "Size" translatable * Exposes receivedData signal to users of QTermWidget * Exposes sessions autoClose property to QTermWidget qtermwidget-0.7.1 / 2016-12-21 ================== * Release 0.7.1: Update changelog * Bump patch version (#105) * Added a modified Breeze color scheme (#104) * Accept hex color strings as well (#101) * Remove the stale lib/README (#102) * Implement background images (#95) * Implement other BOX DRAWING characters (#98) * Preparations for context menu actions on URLs (#97) * Drop the ancient wcwidth impl. and use utf8proc if possible (#99) * Remove widget size checks in setVTFont() (#86) * Delete unused tooltip code (#81) * Fix size of the array passed to memset() (#79) * Remove cpack (#93) qtermwidget-0.7.0 / 2016-09-24 ================== * Release 0.7.0: Add changelog * Bump version to 0.7.0 (#92) * Add Solarized Color Schemes * Update README.md * qtermwidget: Unify title & icon propagation * lib: Fix FTBFS (struct vs. class mismatch) * Add 'const' decorators * Expose titleChanged() signal * Fix building instructions * cmake support changes * Make addCustomColorSchemeDir() static and check for duplicates * Address review comments * Allow app to add custom color sheme locations * Avoid enums duplication * Add support for setting keyboard cursor shape * Remove assignment to self * Backport konsole changes to fix memory leaks * Remove __FILE__ macros * Replace assert() with Q_ASSERT() * Fix ASan error about delete size mismatch * Add support for GNU/Hurd to kpty.cpp. * fixes kfreebsd builds on debian and derivatives * Fix indenations (misleading-indentation warning) * Remove Q_DECL_OVERRIDE macros * typo Higlight * Remove noisy qDebugs * Bracketed paste mode implementation * Use function setWorldTranfer for Qpainter instead of setWorldMatrix * Modify treatment drawing double width character * pyqt5 bindings * pyqt5 bindings * Avoid checking uninitialized member + simplify condition * Use markdown for README and improve it a bit * Remove support for Qt <= 5.4 * Remove Designer plugin * Fix LICENSE text and name * Remove Changelog * Remove empty TODO file * Remove PyQt4 bindings * Sort out terminal resizing * Rebase Vt102Emulation to Konsole * Enable terminal resizing from the emulator * Clean up trailing whitespaces * implemented start TTY for external recipient; * Fix: typo in TerminalDisplay * add method for get pty slave fd; * add method for get pty slave fd; * Use GNUInstallDirs in CMakeLists.txt to stop hardcoding paths * Set the '_notifiedActivity' flag early * Also expose signals and slots to pyqt * Get/set selection end in python bindings * Avoid calling winId() on Qt5. * Fix TerminalDisplay::getCharacterPosition for proportional fonts * Handle proportional fonts a bit better * Expose more functionality through the python bindings (#23) * Allow stopping test.py with ctrl-C * Fix 'getSelectionEnd' * Make whitespace consistent (tabs->spaces) * Fix python binding compile errors #23 * Add event to notify the application that the shell application uses mouse. * Change mouseMarks only when needed. This might be useful if an application wants to be notified of the event. * Prevents deleting the last line when resizing. qtermwidget-0.6.0 / 2014-10-21 ================== * Release 0.6.0 * Update AUTHORS * Update INSTALL instructions * CMakeLists.txt cleanup * osx: link fixes * fixed #57 Linux emulation does not seem to support Ctrl+Arrows (warning: I have no clue what I did...) * Fix Qt4 compilation * qterminal #64 No drag & drop support * fixed qterminal #71 qt5 version ignoring page up / down * Fixed a typo in CMakeLists.txt. qtermwidget-0.5.1 / 2014-07-14 ================== * fixed 'make dist'; version bump * Url activation & filters #21 * Proxy activity/silence methods to Session in QTermWidget. * Emit activity() and silence() signals instead of KNotification. * Support bells. * Support bells. * Added QTermWidget::urlActivated(QUrl) signal. * Emit UrlFilter::activated() instead of QDesktopServices::openUrl(). * Derive Filter from QObject. * Add UrlFilter. * Activate link filters on ctrl+click. * Update filters on resize and screen events. * Const-correctness for QTermWidget API. * Load arbitrary schemes by path via setColorScheme(). * ColorSchemeManager::loadCustomColorScheme(const QString& path). * Unified schemeName() usage. * fixed #17 lib/ShellCommand.cpp:66: possible =/== mixup * Delete CMakeLists.txt.user * new API selectedText() * new API methods (thanks to William Brumley) * fixed #11 compile against Qt 5 (Qt4 and Qt5 supported and waguely tested) * build simplified: qtermwidget is versioned (libqtermwidget4 for Qt4, 5 for Qt5...). Better cmake support. * fixed broken API for sendText() - const missing * mail address change * Current Working Directory for linux. Part of #8. More implementations welcomed... * Add a method for get working directory in class QTermWidget * Fix missing cleanup for temporary history files * a potential improvement for #9 font fractional pixels causes spacing errors * fix #2 update various documentations for debian packaging * fix #10 Update FSF address qtermwidget-0.4.0 / 2013-04-16 ================== * readme updated * Added pasteSelection-slot and corrected two nonsense comments * qt/embedded doesn't ship with a Monospace font (and it won't use system fonts even if they exist). Using 'fixed' instead works fine * Without this, the terminal display area will permanently lose focus when consoleq's Find dialog is called up. * This is only needed when using Qt/E built for DirectFB display. DirectFB blocks SIGINT and some other signals, so any terminal app (be it Qt or otherwise) must call sigprocmask() to unblock them. Without this, ^C doesn't work. * The control and tab keys don't work in Qt/E. This fixes it, but maybe not in the most elegant way. The trouble seems to be that _codec->fromUnicode(event->text()) doesn't handle control characters in qt-embedded. * Fix resize label * Search code cleanup * Change searchbar background color to red(ish) when no match found * Fix search, find-next when selection is one character long * Hotkeys for search: Return->find-next, Shift-Return->find-previous, Escape->hide searchbar * Added search functionality * Add zoom. Add choice action after paste clipboard * Add zoom. Add choice action after paste clipboard * Add zoom. Add choice action after paste clipboard * Add zoom. Add choice action after paste clipboard * Add zoom. Add choice action after paste clipboard * Add zoom. Add choice action after paste clipboard * Add zoom. Add choice action after paste clipboard * Add zoom. Add choice action after paste clipboard * Add zoom. Add choice action after paste clipboard * Fix logical error * Add zoom. Add choice action after paste clipboard * Add zoom. Add choice action after paste clipboard * Add Shift+KeyEnd and Shift+KeyHome to go line 0 and line end. No move screenwindow when copy and paste with keyboard * fix for text drawing in qt>=4.8,x * constructor for Qt Designer * test commit * clear() slot implemented * fix the scroll at the end again * The escape key is always needed for terminal programs like vim. * Add resource files and the appropriate paths to enable bundling of color schemes and keyboard layouts into the actual executable. * Add a define which will be used to bundle the color schemes and keyboard layouts as resource files with the executable itself instead of putting them on disk. * scrollToEnd() method provided to trigger 'snapping' the terminal to cursor tracked position (typically the extreme value of the scrollbar, or the 'end') Some signal-fu particular to keyPressEvent(QKeyEvent *) done to make the above usable, no existing dependent implementations should be disturbed by this. * revert workaround for key on end * scroll to bottom on input * scrollToEnd() method provided to trigger 'snapping' the terminal to cursor tracked position (typically the extreme value of the scrollbar, or the 'end') Some signal-fu particular to keyPressEvent(QKeyEvent *) done to make the above usable, no existing dependent implementations should be disturbed by this. * improved sample app for testing * macosx compile fix * arguments work correctly for custom shells too * lib has to be built first in any case * merge changes from the experimental "bundle" repository * fix for kb-layout location on mac (mainly) * rpm builds * mac universal build helper * build cleanup; make dist; various readmes updated * make availableKeyBindings static * transparency support * font display fix on mac (widths in int) * qt designer plugin * correct lib ID for mac * remove the KDE legacy code * code reformatted after resync * display stuff synced from konsole again to improve color scheme handling * focus in/out signals * correct shell detection (BSD, Christopher VdoP) * library location on BSD * patches to build on BSD by Christopher VdoP * K&R formatting * K&R formatting * merge with qscite * fixed KB finding + sort * key layouts can be read and provided to widget * install keyboard bindings; handle KB in src code; allow to get and set KB * fix for includes and 64bit builds * port to macosx * initial import deepin-terminal-5.2.11/3rdparty/terminalwidget/CMakeLists.txt000066400000000000000000000226411370157770500242250ustar00rootroot00000000000000cmake_minimum_required(VERSION 3.1.0 FATAL_ERROR) # CMP0000: Call the cmake_minimum_required() command at the beginning of the top-level # CMakeLists.txt file even before calling the project() command. # The cmake_minimum_required(VERSION) command implicitly invokes the cmake_policy(VERSION) # command to specify that the current project code is written for the given range of CMake # versions. project(terminalwidget) include(GNUInstallDirs) include(GenerateExportHeader) include(CMakePackageConfigHelpers) include(CheckFunctionExists) include(CheckIncludeFile) option(UPDATE_TRANSLATIONS "Update source translation translations/*.ts files" OFF) option(BUILD_EXAMPLE "Build example application. Default OFF." OFF) option(TERMINALWIDGET_USE_UTEMPTER "Uses the libutempter library. Mainly for FreeBSD" OFF) option(TERMINALWIDGET_BUILD_PYTHON_BINDING "Build python binding" OFF) option(USE_UTF8PROC "Use libutf8proc for better Unicode support. Default OFF" OFF) # just change version for releases set(TERMINALWIDGET_VERSION_MAJOR "0") set(TERMINALWIDGET_VERSION_MINOR "14") set(TERMINALWIDGET_VERSION_PATCH "1") set(TERMINALWIDGET_VERSION "${TERMINALWIDGET_VERSION_MAJOR}.${TERMINALWIDGET_VERSION_MINOR}.${TERMINALWIDGET_VERSION_PATCH}") # additional cmake files set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} "${PROJECT_SOURCE_DIR}/cmake") set(CMAKE_INCLUDE_CURRENT_DIR ON) set(CMAKE_INSTALL_PREFIX "/usr") # Minimum Versions set(QT_MINIMUM_VERSION "5.7.1") set(LXQTBT_MINIMUM_VERSION "0.6.0") find_package(Qt5Widgets "${QT_MINIMUM_VERSION}" REQUIRED) find_package(Qt5LinguistTools "${QT_MINIMUM_VERSION}" REQUIRED) find_package(lxqt-build-tools ${LXQTBT_MINIMUM_VERSION} REQUIRED) if(USE_UTF8PROC) find_package(Utf8Proc REQUIRED) endif() include(LXQtPreventInSourceBuilds) include(LXQtTranslateTs) include(LXQtCompilerSettings NO_POLICY_SCOPE) include(LXQtCreatePkgConfigFile) if(APPLE) if(CMAKE_VERSION VERSION_GREATER 3.9) cmake_policy(SET CMP0068 NEW) set(CMAKE_BUILD_WITH_INSTALL_NAME_DIR ON) endif() endif() set(TERMINALWIDGET_LIBRARY_NAME terminalwidget5) # main library set(SRCS lib/BlockArray.cpp lib/ColorScheme.cpp lib/Emulation.cpp lib/Filter.cpp lib/History.cpp lib/HistorySearch.cpp lib/KeyboardTranslator.cpp lib/konsole_wcwidth.cpp lib/kprocess.cpp lib/kpty.cpp lib/kptydevice.cpp lib/kptyprocess.cpp lib/ProcessInfo.cpp lib/Pty.cpp lib/qtermwidget.cpp lib/Screen.cpp lib/ScreenWindow.cpp lib/SearchBar.cpp lib/Session.cpp lib/SessionManager.cpp lib/ShellCommand.cpp lib/TerminalCharacterDecoder.cpp lib/TerminalDisplay.cpp lib/tools.cpp lib/Vt102Emulation.cpp ) # Only the Headers that need to be moc'd go here set(HDRS lib/Emulation.h lib/Filter.h lib/HistorySearch.h lib/kprocess.h lib/kptydevice.h lib/kptyprocess.h lib/ProcessInfo.h lib/Pty.h lib/qtermwidget.h lib/ScreenWindow.h lib/SearchBar.h lib/Session.h lib/SessionManager.h lib/TerminalDisplay.h lib/Vt102Emulation.h ) set(UI lib/SearchBar.ui ) # for distribution set(HDRS_DISTRIB lib/qtermwidget.h lib/Emulation.h lib/Filter.h lib/Session.h lib/SessionManager.h lib/History.h lib/BlockArray.h lib/Character.h lib/CharacterColor.h lib/TerminalDisplay.h ) # dirs set(KB_LAYOUT_DIR "${CMAKE_INSTALL_FULL_DATADIR}/${TERMINALWIDGET_LIBRARY_NAME}/kb-layouts") message(STATUS "Keyboard layouts will be installed in: ${KB_LAYOUT_DIR}") set(COLORSCHEMES_DIR "${CMAKE_INSTALL_FULL_DATADIR}/${TERMINALWIDGET_LIBRARY_NAME}/color-schemes") message(STATUS "Color schemes will be installed in: ${COLORSCHEMES_DIR}" ) set(TRANSLATIONS_DIR "${CMAKE_INSTALL_FULL_DATADIR}/${TERMINALWIDGET_LIBRARY_NAME}/translations") message(STATUS "Translations will be installed in: ${TRANSLATIONS_DIR}") set(TERMINALWIDGET_INCLUDE_DIR "${CMAKE_INSTALL_FULL_INCLUDEDIR}/${TERMINALWIDGET_LIBRARY_NAME}") CHECK_FUNCTION_EXISTS(updwtmpx HAVE_UPDWTMPX) qt5_wrap_cpp(MOCS ${HDRS}) qt5_wrap_ui(UI_SRCS ${UI}) set(PKG_CONFIG_REQ "Qt5Widgets") lxqt_translate_ts(TERMINALWIDGET_QM TRANSLATION_DIR "lib/translations" UPDATE_TRANSLATIONS ${UPDATE_TRANSLATIONS} SOURCES ${SRCS} ${HDRS} ${UI} INSTALL_DIR ${TRANSLATIONS_DIR} COMPONENT Runtime ) add_library(${TERMINALWIDGET_LIBRARY_NAME} SHARED ${SRCS} ${MOCS} ${UI_SRCS} ${TERMINALWIDGET_QM}) target_link_libraries(${TERMINALWIDGET_LIBRARY_NAME} Qt5::Widgets) set_target_properties( ${TERMINALWIDGET_LIBRARY_NAME} PROPERTIES SOVERSION ${TERMINALWIDGET_VERSION_MAJOR} VERSION ${TERMINALWIDGET_VERSION} ) if(APPLE) target_compile_definitions(${TERMINALWIDGET_LIBRARY_NAME} PRIVATE "HAVE_UTMPX" "UTMPX_COMPAT" ) endif() if(HAVE_UPDWTMPX) target_compile_definitions(${TERMINALWIDGET_LIBRARY_NAME} PRIVATE "HAVE_UPDWTMPX" ) endif() if (TERMINALWIDGET_USE_UTEMPTER) CHECK_INCLUDE_FILE(utempter.h HAVE_UTEMPTER) if (HAVE_UTEMPTER) target_compile_definitions(${TERMINALWIDGET_LIBRARY_NAME} PRIVATE "HAVE_UTEMPTER" ) target_link_libraries(${TERMINALWIDGET_LIBRARY_NAME} ulog) endif() endif() if (UTF8PROC_FOUND) target_compile_definitions(${TERMINALWIDGET_LIBRARY_NAME} PRIVATE "HAVE_UTF8PROC" ) target_include_directories(${TERMINALWIDGET_LIBRARY_NAME} INTERFACE ${UTF8PROC_INCLUDE_DIRS} ) target_link_libraries(${TERMINALWIDGET_LIBRARY_NAME} ${UTF8PROC_LIBRARIES} ) string(APPEND PKG_CONFIG_REQ ", libutf8proc") endif() if(APPLE) set (CMAKE_SKIP_RPATH 1) # this is a must to load the lib correctly set_target_properties(${TERMINALWIDGET_LIBRARY_NAME} PROPERTIES INSTALL_NAME_DIR ${CMAKE_INSTALL_FULL_LIBDIR}) endif() target_compile_definitions(${TERMINALWIDGET_LIBRARY_NAME} PRIVATE "KB_LAYOUT_DIR=\"${KB_LAYOUT_DIR}\"" "COLORSCHEMES_DIR=\"${COLORSCHEMES_DIR}\"" "TRANSLATIONS_DIR=\"${TRANSLATIONS_DIR}\"" "HAVE_POSIX_OPENPT" "HAVE_SYS_TIME_H" ) generate_export_header(${TERMINALWIDGET_LIBRARY_NAME} EXPORT_FILE_NAME "${CMAKE_CURRENT_BINARY_DIR}/lib/qtermwidget_export.h" EXPORT_MACRO_NAME TERMINALWIDGET_EXPORT ) target_include_directories(${TERMINALWIDGET_LIBRARY_NAME} PUBLIC "$" "$" INTERFACE "$" "$" ) write_basic_package_version_file( "${CMAKE_BINARY_DIR}/${TERMINALWIDGET_LIBRARY_NAME}-config-version.cmake" VERSION ${TERMINALWIDGET_VERSION} COMPATIBILITY AnyNewerVersion ) install(FILES "${CMAKE_BINARY_DIR}/${TERMINALWIDGET_LIBRARY_NAME}-config-version.cmake" DESTINATION "${CMAKE_INSTALL_LIBDIR}/cmake/${TERMINALWIDGET_LIBRARY_NAME}" COMPONENT Devel ) install(EXPORT "${TERMINALWIDGET_LIBRARY_NAME}-targets" DESTINATION "${CMAKE_INSTALL_LIBDIR}/cmake/${TERMINALWIDGET_LIBRARY_NAME}" COMPONENT Devel ) install(FILES ${HDRS_DISTRIB} "${CMAKE_CURRENT_BINARY_DIR}/lib/qtermwidget_export.h" DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}/${TERMINALWIDGET_LIBRARY_NAME}" COMPONENT Devel ) # keyboard layouts install(DIRECTORY lib/kb-layouts/ DESTINATION "${KB_LAYOUT_DIR}" COMPONENT Runtime FILES_MATCHING PATTERN "*.keytab" ) # color schemes install(DIRECTORY lib/color-schemes/ DESTINATION "${COLORSCHEMES_DIR}" COMPONENT Runtime FILES_MATCHING PATTERN "*.*schem*" ) lxqt_create_pkgconfig_file( PACKAGE_NAME ${TERMINALWIDGET_LIBRARY_NAME} DESCRIPTIVE_NAME ${TERMINALWIDGET_LIBRARY_NAME} DESCRIPTION "TerminalWidget library for Qt ${TERMINALWIDGET_VERSION_MAJOR}.x" INCLUDEDIRS ${TERMINALWIDGET_LIBRARY_NAME} LIBS ${TERMINALWIDGET_LIBRARY_NAME} REQUIRES ${PKG_CONFIG_REQ} VERSION ${TERMINALWIDGET_VERSION} INSTALL COMPONENT Devel ) configure_file( "${PROJECT_SOURCE_DIR}/cmake/${TERMINALWIDGET_LIBRARY_NAME}-config.cmake.in" "${CMAKE_BINARY_DIR}/${TERMINALWIDGET_LIBRARY_NAME}-config.cmake" @ONLY ) install(FILES "${CMAKE_BINARY_DIR}/${TERMINALWIDGET_LIBRARY_NAME}-config.cmake" DESTINATION "${CMAKE_INSTALL_LIBDIR}/cmake/${TERMINALWIDGET_LIBRARY_NAME}" COMPONENT Devel ) install(TARGETS ${TERMINALWIDGET_LIBRARY_NAME} DESTINATION "${CMAKE_INSTALL_LIBDIR}" EXPORT "${TERMINALWIDGET_LIBRARY_NAME}-targets" LIBRARY DESTINATION "${CMAKE_INSTALL_LIBDIR}" PUBLIC_HEADER COMPONENT Runtime ) export(TARGETS ${TERMINALWIDGET_LIBRARY_NAME} FILE "${CMAKE_BINARY_DIR}/${TERMINALWIDGET_LIBRARY_NAME}-targets.cmake" EXPORT_LINK_INTERFACE_LIBRARIES ) # end of main library # example application if(BUILD_EXAMPLE) set(EXAMPLE_SRC example/main.cpp) add_executable(example ${EXAMPLE_SRC}) target_link_libraries(example ${TERMINALWIDGET_LIBRARY_NAME}) endif() # end of example application # python binding if (TERMINALWIDGET_BUILD_PYTHON_BINDING) add_subdirectory(pyqt) endif() # end of python binding CONFIGURE_FILE( "${CMAKE_CURRENT_SOURCE_DIR}/cmake/cmake_uninstall.cmake.in" "${CMAKE_CURRENT_BINARY_DIR}/cmake_uninstall.cmake" IMMEDIATE @ONLY ) ADD_CUSTOM_TARGET(uninstall "${CMAKE_COMMAND}" -P "${CMAKE_CURRENT_BINARY_DIR}/cmake_uninstall.cmake" ) deepin-terminal-5.2.11/3rdparty/terminalwidget/COPYING-CMAKE-SCRIPTS000066400000000000000000000000241370157770500244520ustar00rootroot00000000000000LICENSE.BSD-3-clausedeepin-terminal-5.2.11/3rdparty/terminalwidget/LICENSE000066400000000000000000000355641370157770500225020ustar00rootroot00000000000000 GNU GENERAL PUBLIC LICENSE Version 2, June 1991 Copyright (C) 1989, 1991 Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Lesser General Public License instead.) You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you". Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License. c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program. In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following: a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.) The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. 4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. 7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation. 10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS deepin-terminal-5.2.11/3rdparty/terminalwidget/LICENSE.BSD-3-clause000066400000000000000000000027331370157770500245130ustar00rootroot00000000000000Copyright (c) The Regents of the University of California. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the University nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. deepin-terminal-5.2.11/3rdparty/terminalwidget/LICENSE.LGPL2+000066400000000000000000000614471370157770500233730ustar00rootroot00000000000000 GNU LIBRARY GENERAL PUBLIC LICENSE Version 2, June 1991 Copyright (C) 1991 Free Software Foundation, Inc. 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. [This is the first released version of the library GPL. It is numbered 2 because it goes with version 2 of the ordinary GPL.] Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public Licenses are intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This license, the Library General Public License, applies to some specially designated Free Software Foundation software, and to any other libraries whose authors decide to use it. You can use it for your libraries, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the library, or if you modify it. For example, if you distribute copies of the library, whether gratis or for a fee, you must give the recipients all the rights that we gave you. You must make sure that they, too, receive or can get the source code. If you link a program with the library, you must provide complete object files to the recipients so that they can relink them with the library, after making changes to the library and recompiling it. And you must show them these terms so they know their rights. Our method of protecting your rights has two steps: (1) copyright the library, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the library. Also, for each distributor's protection, we want to make certain that everyone understands that there is no warranty for this free library. If the library is modified by someone else and passed on, we want its recipients to know that what they have is not the original version, so that any problems introduced by others will not reflect on the original authors' reputations. Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that companies distributing free software will individually obtain patent licenses, thus in effect transforming the program into proprietary software. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. Most GNU software, including some libraries, is covered by the ordinary GNU General Public License, which was designed for utility programs. This license, the GNU Library General Public License, applies to certain designated libraries. This license is quite different from the ordinary one; be sure to read it in full, and don't assume that anything in it is the same as in the ordinary license. The reason we have a separate public license for some libraries is that they blur the distinction we usually make between modifying or adding to a program and simply using it. Linking a program with a library, without changing the library, is in some sense simply using the library, and is analogous to running a utility program or application program. However, in a textual and legal sense, the linked executable is a combined work, a derivative of the original library, and the ordinary General Public License treats it as such. Because of this blurred distinction, using the ordinary General Public License for libraries did not effectively promote software sharing, because most developers did not use the libraries. We concluded that weaker conditions might promote sharing better. However, unrestricted linking of non-free programs would deprive the users of those programs of all benefit from the free status of the libraries themselves. This Library General Public License is intended to permit developers of non-free programs to use free libraries, while preserving your freedom as a user of such programs to change the free libraries that are incorporated in them. (We have not seen how to achieve this as regards changes in header files, but we have achieved it as regards changes in the actual functions of the Library.) The hope is that this will lead to faster development of free libraries. The precise terms and conditions for copying, distribution and modification follow. Pay close attention to the difference between a "work based on the library" and a "work that uses the library". The former contains code derived from the library, while the latter only works together with the library. Note that it is possible for a library to be covered by the ordinary General Public License rather than by this special one. GNU LIBRARY GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License Agreement applies to any software library which contains a notice placed by the copyright holder or other authorized party saying it may be distributed under the terms of this Library General Public License (also called "this License"). Each licensee is addressed as "you". A "library" means a collection of software functions and/or data prepared so as to be conveniently linked with application programs (which use some of those functions and data) to form executables. The "Library", below, refers to any such software library or work which has been distributed under these terms. A "work based on the Library" means either the Library or any derivative work under copyright law: that is to say, a work containing the Library or a portion of it, either verbatim or with modifications and/or translated straightforwardly into another language. (Hereinafter, translation is included without limitation in the term "modification".) "Source code" for a work means the preferred form of the work for making modifications to it. For a library, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the library. Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running a program using the Library is not restricted, and output from such a program is covered only if its contents constitute a work based on the Library (independent of the use of the Library in a tool for writing it). Whether that is true depends on what the Library does and what the program that uses the Library does. 1. You may copy and distribute verbatim copies of the Library's complete source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and distribute a copy of this License along with the Library. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Library or any portion of it, thus forming a work based on the Library, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) The modified work must itself be a software library. b) You must cause the files modified to carry prominent notices stating that you changed the files and the date of any change. c) You must cause the whole of the work to be licensed at no charge to all third parties under the terms of this License. d) If a facility in the modified Library refers to a function or a table of data to be supplied by an application program that uses the facility, other than as an argument passed when the facility is invoked, then you must make a good faith effort to ensure that, in the event an application does not supply such function or table, the facility still operates, and performs whatever part of its purpose remains meaningful. (For example, a function in a library to compute square roots has a purpose that is entirely well-defined independent of the application. Therefore, Subsection 2d requires that any application-supplied function or table used by this function must be optional: if the application does not supply it, the square root function must still compute square roots.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Library, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Library, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Library. In addition, mere aggregation of another work not based on the Library with the Library (or with a work based on the Library) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may opt to apply the terms of the ordinary GNU General Public License instead of this License to a given copy of the Library. To do this, you must alter all the notices that refer to this License, so that they refer to the ordinary GNU General Public License, version 2, instead of to this License. (If a newer version than version 2 of the ordinary GNU General Public License has appeared, then you can specify that version instead if you wish.) Do not make any other change in these notices. Once this change is made in a given copy, it is irreversible for that copy, so the ordinary GNU General Public License applies to all subsequent copies and derivative works made from that copy. This option is useful when you wish to copy part of the code of the Library into a program that is not a library. 4. You may copy and distribute the Library (or a portion or derivative of it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange. If distribution of object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place satisfies the requirement to distribute the source code, even though third parties are not compelled to copy the source along with the object code. 5. A program that contains no derivative of any portion of the Library, but is designed to work with the Library by being compiled or linked with it, is called a "work that uses the Library". Such a work, in isolation, is not a derivative work of the Library, and therefore falls outside the scope of this License. However, linking a "work that uses the Library" with the Library creates an executable that is a derivative of the Library (because it contains portions of the Library), rather than a "work that uses the library". The executable is therefore covered by this License. Section 6 states terms for distribution of such executables. When a "work that uses the Library" uses material from a header file that is part of the Library, the object code for the work may be a derivative work of the Library even though the source code is not. Whether this is true is especially significant if the work can be linked without the Library, or if the work is itself a library. The threshold for this to be true is not precisely defined by law. If such an object file uses only numerical parameters, data structure layouts and accessors, and small macros and small inline functions (ten lines or less in length), then the use of the object file is unrestricted, regardless of whether it is legally a derivative work. (Executables containing this object code plus portions of the Library will still fall under Section 6.) Otherwise, if the work is a derivative of the Library, you may distribute the object code for the work under the terms of Section 6. Any executables containing that work also fall under Section 6, whether or not they are linked directly with the Library itself. 6. As an exception to the Sections above, you may also compile or link a "work that uses the Library" with the Library to produce a work containing portions of the Library, and distribute that work under terms of your choice, provided that the terms permit modification of the work for the customer's own use and reverse engineering for debugging such modifications. You must give prominent notice with each copy of the work that the Library is used in it and that the Library and its use are covered by this License. You must supply a copy of this License. If the work during execution displays copyright notices, you must include the copyright notice for the Library among them, as well as a reference directing the user to the copy of this License. Also, you must do one of these things: a) Accompany the work with the complete corresponding machine-readable source code for the Library including whatever changes were used in the work (which must be distributed under Sections 1 and 2 above); and, if the work is an executable linked with the Library, with the complete machine-readable "work that uses the Library", as object code and/or source code, so that the user can modify the Library and then relink to produce a modified executable containing the modified Library. (It is understood that the user who changes the contents of definitions files in the Library will not necessarily be able to recompile the application to use the modified definitions.) b) Accompany the work with a written offer, valid for at least three years, to give the same user the materials specified in Subsection 6a, above, for a charge no more than the cost of performing this distribution. c) If distribution of the work is made by offering access to copy from a designated place, offer equivalent access to copy the above specified materials from the same place. d) Verify that the user has already received a copy of these materials or that you have already sent this user a copy. For an executable, the required form of the "work that uses the Library" must include any data and utility programs needed for reproducing the executable from it. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. It may happen that this requirement contradicts the license restrictions of other proprietary libraries that do not normally accompany the operating system. Such a contradiction means you cannot use both them and the Library together in an executable that you distribute. 7. You may place library facilities that are a work based on the Library side-by-side in a single library together with other library facilities not covered by this License, and distribute such a combined library, provided that the separate distribution of the work based on the Library and of the other library facilities is otherwise permitted, and provided that you do these two things: a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities. This must be distributed under the terms of the Sections above. b) Give prominent notice with the combined library of the fact that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. 8. You may not copy, modify, sublicense, link with, or distribute the Library except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense, link with, or distribute the Library is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 9. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Library or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Library (or any work based on the Library), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Library or works based on it. 10. Each time you redistribute the Library (or any work based on the Library), the recipient automatically receives a license from the original licensor to copy, distribute, link with or modify the Library subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. 11. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Library at all. For example, if a patent license would not permit royalty-free redistribution of the Library by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Library. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply, and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 12. If the distribution and/or use of the Library is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Library under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 13. The Free Software Foundation may publish revised and/or new versions of the Library General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Library specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Library does not specify a license version number, you may choose any version ever published by the Free Software Foundation. 14. If you wish to incorporate parts of the Library into other free programs whose distribution conditions are incompatible with these, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Libraries If you develop a new library, and you want it to be of the greatest possible use to the public, we recommend making it free software that everyone can redistribute and change. You can do so by permitting redistribution under these terms (or, alternatively, under the terms of the ordinary General Public License). To apply these terms, attach the following notices to the library. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This 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; either version 2 of the License, 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; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Also add information on how to contact you by electronic and paper mail. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the library, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the library `Frob' (a library for tweaking knobs) written by James Random Hacker. , 1 April 1990 Ty Coon, President of Vice That's all there is to it! deepin-terminal-5.2.11/3rdparty/terminalwidget/README.md000066400000000000000000000053051370157770500227420ustar00rootroot00000000000000# QTermWidget ## Overview A terminal emulator widget for Qt 5. QTermWidget is an open-source project originally based on the KDE4 Konsole application, but it took its own direction later on. The main goal of this project is to provide a unicode-enabled, embeddable Qt widget for using as a built-in console (or terminal emulation widget). It is compatible with BSD, Linux and OS X. This project is licensed under the terms of the [GPLv2](https://www.gnu.org/licenses/gpl-2.0.en.html) or any later version. See the LICENSE file for the full text of the license. Some files are published under compatible licenses: ``` Files: example/main.cpp lib/TerminalCharacterDecoder.cpp lib/TerminalCharacterDecoder.h lib/kprocess.cpp lib/kprocess.h lib/kpty.cpp lib/kpty.h lib/kpty_p.h lib/kptydevice.cpp lib/kptydevice.h lib/kptyprocess.cpp lib/kptyprocess.h lib/qtermwidget.cpp lib/qtermwidget.h Copyright: Author Adriaan de Groot 2010, KDE e.V 2002-2007, Oswald Buddenhagen 2006-2008, Robert Knight 2002, Waldo Bastian 2008, e_k License: LGPL-2+ Files: pyqt/cmake/* Copyright: 2012, Luca Beltrame 2012, Rolf Eike Beer 2007-2014, Simon Edwards License: BSD-3-clause Files: cmake/FindUtf8Proc.cmake Copyright: 2009-2011, Kitware, Inc 2009-2011, Philip Lowman License: BSD-3-clause Files: pyqt/cmake/PythonCompile.py License: public-domain ``` ## Installation ### Compiling sources The only runtime dependency is qtbase ≥ 5.7.1. In order to build CMake ≥ 3.0.2 and [lxqt-build-tools](https://github.com/lxqt/lxqt-build-tools/) >= 0.4.0 are needed as well as Git to pull translations and optionally latest VCS checkouts. Code configuration is handled by CMake. CMake variable `CMAKE_INSTALL_PREFIX` will normally have to be set to `/usr`, depending on the way library paths are dealt with on 64bit systems variables like `CMAKE_INSTALL_LIBDIR` may have to be set as well. To build run `make`, to install `make install` which accepts variable `DESTDIR` as usual. ### Binary packages The library is provided by all major Linux distributions like Arch Linux, Debian, Fedora and openSUSE. Just use the distributions' package managers to search for string `qtermwidget`. ### Translation (Weblate) Translation status deepin-terminal-5.2.11/3rdparty/terminalwidget/cmake/000077500000000000000000000000001370157770500225405ustar00rootroot00000000000000deepin-terminal-5.2.11/3rdparty/terminalwidget/cmake/FindUtf8Proc.cmake000066400000000000000000000034431370157770500260210ustar00rootroot00000000000000#.rst: # FindUtf8Proc # -------- # # Find utf8proc # # Find the UTF-8 processing library # # :: # # This module defines the following variables: # UTF8PROC_FOUND - True if UTF8PROC_INCLUDE_DIR & UTF8PROC_LIBRARY are found # UTF8PROC_LIBRARIES - Set when UTF8PROC_LIBRARY is found # UTF8PROC_INCLUDE_DIRS - Set when UTF8PROC_INCLUDE_DIR is found # # # # :: # # UTF8PROC_INCLUDE_DIR - where to find utf8proc.h # UTF8PROC_LIBRARY - the utf8proc library #============================================================================= # This module is adapted from FindALSA.cmake. Below are the original license # header. #============================================================================= # Copyright 2009-2011 Kitware, Inc. # Copyright 2009-2011 Philip Lowman # # Distributed under the OSI-approved BSD License (the "License"); # see accompanying file Copyright.txt for details. # # This software is distributed WITHOUT ANY WARRANTY; without even the # implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. # See the License for more information. #============================================================================= find_path( UTF8PROC_INCLUDE_DIR NAMES utf8proc.h DOC "The utf8proc include directory" ) find_library( UTF8PROC_LIBRARY NAMES utf8proc DOC "The utf8proc library" ) # handle the QUIETLY and REQUIRED arguments and set UTF8PROC_FOUND to TRUE if # all listed variables are TRUE include(FindPackageHandleStandardArgs) FIND_PACKAGE_HANDLE_STANDARD_ARGS( UTF8PROC REQUIRED_VARS UTF8PROC_LIBRARY UTF8PROC_INCLUDE_DIR ) if(UTF8PROC_FOUND) set( UTF8PROC_LIBRARIES ${UTF8PROC_LIBRARY} ) set( UTF8PROC_INCLUDE_DIRS ${UTF8PROC_INCLUDE_DIR} ) endif() mark_as_advanced(UTF8PROC_INCLUDE_DIR UTF8PROC_LIBRARY) deepin-terminal-5.2.11/3rdparty/terminalwidget/cmake/cmake_uninstall.cmake.in000066400000000000000000000017441370157770500273260ustar00rootroot00000000000000IF(NOT EXISTS "@CMAKE_CURRENT_BINARY_DIR@/install_manifest.txt") MESSAGE(FATAL_ERROR "Cannot find install manifest: \"@CMAKE_CURRENT_BINARY_DIR@/install_manifest.txt\"") ENDIF(NOT EXISTS "@CMAKE_CURRENT_BINARY_DIR@/install_manifest.txt") # this works on Linux, but not on mac. #FILE(READ "@CMAKE_CURRENT_BINARY_DIR@/install_manifest.txt" files) #STRING(REGEX REPLACE "\n" ";" files "${files}") #FOREACH(file ${files}) # MESSAGE(STATUS "Uninstalling \"${file}\"") # IF(NOT EXISTS "${file}") # MESSAGE(FATAL_ERROR "File \"${file}\" does not exists.") # ENDIF(NOT EXISTS "${file}") # EXEC_PROGRAM("@CMAKE_COMMAND@" ARGS "-E remove \"${file}\"" # OUTPUT_VARIABLE rm_out # RETURN_VARIABLE rm_retval) # IF("${rm_retval}" GREATER 0) # MESSAGE(FATAL_ERROR "Problem when removing \"${file}\"") # ENDIF("${rm_retval}" GREATER 0) #ENDFOREACH(file) EXEC_PROGRAM("xargs rm < @CMAKE_BINARY_DIR@/install_manifest.txt" OUTPUT_VARIABLE rm_out RETURN_VARIABLE rm_ret) deepin-terminal-5.2.11/3rdparty/terminalwidget/cmake/terminalwidget5-config.cmake.in000066400000000000000000000010361370157770500305160ustar00rootroot00000000000000# - Find the QTermWidget include and library # # Typical usage: # find_package(QTermWidget5 REQUIRED) # # add_executable(foo main.cpp) # target_link_libraries(foo qtermwidget5) @PACKAGE_INIT@ if (CMAKE_VERSION VERSION_LESS 3.0.2) message(FATAL_ERROR \"qtermwidget requires at least CMake version 3.0.2\") endif() if (NOT TARGET @TERMINALWIDGET_LIBRARY_NAME@) if (POLICY CMP0024) cmake_policy(SET CMP0024 NEW) endif() include("${CMAKE_CURRENT_LIST_DIR}/@TERMINALWIDGET_LIBRARY_NAME@-targets.cmake") endif() deepin-terminal-5.2.11/3rdparty/terminalwidget/debian/000077500000000000000000000000001370157770500227025ustar00rootroot00000000000000deepin-terminal-5.2.11/3rdparty/terminalwidget/debian/changelog000066400000000000000000000226241370157770500245620ustar00rootroot00000000000000qtermwidget (0.14.1-1) unstable; urgency=medium * Cherry-picking upstream release: 0.14.1. -- Alf Gaida Tue, 26 Feb 2019 01:00:03 +0100 qtermwidget (0.14.0-1) unstable; urgency=medium * Cherry-picking upstream release: 0.14.0. * Bumped Standards to 4.3.0, no changes needed * Dropped d/compat, use debhelper-compat = 12, no changes needed * Fixed years in d/copyright * Bumped minimum version lxqt-build-tools (>= 0.6.0~) * Removed obsolete PULL_TRANSLATIONS= OFF from dh_auto_configure * Added Build-Depends-Package field to symbols * Installed new translations in the data package. * Added two new symbols * Added d/upstream/metadata -- Alf Gaida Sun, 27 Jan 2019 15:29:16 +0100 qtermwidget (0.9.0-2) unstable; urgency=medium * Recommend fonts-hack instead of fonts-hack-ttf (Closes: #907279) * Bumped Standards to 4.2.1, no changes needed -- Alf Gaida Sun, 16 Sep 2018 14:16:19 +0200 qtermwidget (0.9.0-1) unstable; urgency=medium * Cherry-picking upstream release: 0.9.0. * Moved debian/.gitignore to ./.gitignore * Bumped build dependency lxqt-build-tools to >= 0.5.0~ * Removed cmake fix, applied upstream * Added some options to rules * Added some new symbols -- Alf Gaida Thu, 24 May 2018 01:11:06 +0200 qtermwidget (0.8.0-6) unstable; urgency=medium * Bumped compat to 11 * Bumped debhelper to >= 11~ * Removed not needed cmake minimim version * Bumped Standards to 4.1.4, no changes needed * Changed VCS fields for salsa * Changed Homepage, Source and watch to lxqt * Bumped years in copyright -- Alf Gaida Sat, 28 Apr 2018 19:31:10 +0200 qtermwidget (0.8.0-5) unstable; urgency=medium * Bumped Standards to 4.1.2, no changes needed * Removed branch from VCS fields * Removed gbp.conf -- Alf Gaida Fri, 15 Dec 2017 19:30:23 +0100 qtermwidget (0.8.0-4) unstable; urgency=medium * Transition to unstable -- Alf Gaida Mon, 04 Dec 2017 20:14:31 +0100 qtermwidget (0.8.0-3) experimental; urgency=medium * Fixed typo in changelog -- Alf Gaida Sun, 05 Nov 2017 02:05:43 +0100 qtermwidget (0.8.0-2) experimental; urgency=medium * Fixed cmake install directories (Closes: #880389) Thanks Andreas Beckmann for spotting this. * Removed superfluous whitespaces from changelog -- Alf Gaida Tue, 31 Oct 2017 15:18:42 +0100 qtermwidget (0.8.0-1) experimental; urgency=medium * Cherry-picking upstream release 0.8.0. * Switched to experimental * Bumped Standards to 4.1.1 * Bumped build tools to >= 0.4.0 * Fixed copyright * Fixed symbols -- Alf Gaida Sun, 22 Oct 2017 22:15:52 +0200 qtermwidget (0.7.1-7) unstable; urgency=medium * Fixed symbols for powerpcspe -- Alf Gaida Sun, 24 Sep 2017 14:05:24 +0200 qtermwidget (0.7.1-6) unstable; urgency=medium * Fixed symbols for all but powerpcspe - missed build deps and i don't want to guess. -- Alf Gaida Tue, 05 Sep 2017 23:56:54 +0200 qtermwidget (0.7.1-5) unstable; urgency=medium * fixed another round of symbols, work in progress (currently fixed amd64 and i386) (Closes: #874187) Thanks Adrian Bunk for spotting this. * bumped Standards to 4.1.0 - no changes needed * fix some colons and not needed versions in d/control -- Alf Gaida Tue, 05 Sep 2017 16:55:18 +0200 qtermwidget (0.7.1-4) unstable; urgency=medium * fixed symbols for gcc 7.1.0 (Closes: #871122) -- Alf Gaida Sat, 12 Aug 2017 19:34:55 +0200 qtermwidget (0.7.1-3) unstable; urgency=medium * Bumped Standards to 4.0.0 - no changes needed * Added 5 optional symbols (Closes: #853632) * Added build dependency lxqt-build-tools * Added Recommends: qtermwidget-l10n, fonts-hack-ttf -- Alf Gaida Mon, 03 Jul 2017 00:45:55 +0200 qtermwidget (0.7.1-2) unstable; urgency=medium * Added build-dependency libutf8proc-dev as the missed part for full utf-8 support. The use-trigger is already set. Thanks Riku Voipio , nice catch. (Closes: #851832) -- Alf Gaida Thu, 19 Jan 2017 14:52:26 -0500 qtermwidget (0.7.1-1) unstable; urgency=medium * Cherry-picking upstream release 0.7.1. * Fixed Symbols * Removed build dependency liblxqt0-dev * Activate new UTF8 processing in rules -- Alf Gaida Wed, 21 Dec 2016 23:50:11 +0100 qtermwidget (0.7.0-4) unstable; urgency=medium * Cherry-picking upstream release: 0.7.0 * Bumped compat to 10 * Removed --parallel from rules, standard in compat 10 * Bumped minimum version debhelper (>= 10) * Added build dependency liblxqt-dev (>= 0.11.0) * Followed Multiarch hinter suggestions - qtermwidget5-data marked as Multi-Arch: foreign - libqtermwidget5-0 marked as Multi-Arch: same - libqtermwidget5-0-dev marked as Multi-Arch: same * Simplified optional symbols -- Alf Gaida Tue, 18 Oct 2016 21:16:57 +0200 qtermwidget (0.6.1~55-gd572f39-1) unstable; urgency=medium * Bump version to 0.6.1~ * Added a renamed tarball to pristine-tar * Rework symbols (Closes: #831083), tested with i386 and amd64 * Fixed VCS fields, using plain /git/ * Fixed copyright Format field, using https * Exported LC_ALL=C.UTF-8, make builds reproducible * Set CMAKE_BUILD_TYPE=RelWithDebInfo -- Alf Gaida Sat, 06 Aug 2016 02:26:26 +0200 qtermwidget (0.6.0-55-gd572f39-1) unstable; urgency=medium * Cherry-picked snapshot: 0.6.0-55-gd572f39 * switch package numbering to git describe instead of dates * Remove patch, now integrated into upstream (Closes: #798053) * Bump standards to 3.9.8 -- Alf Gaida Sat, 14 May 2016 18:09:02 +0200 qtermwidget (0.6.0+20160108-6) unstable; urgency=medium * Fix two whitespace bugs, which i've had by mistake introduced after the test builds -- Alf Gaida Sat, 14 May 2016 03:09:49 +0200 qtermwidget (0.6.0+20160108-5) unstable; urgency=medium * Rework some symbols -- Alf Gaida Sat, 14 May 2016 02:01:05 +0200 qtermwidget (0.6.0+20160108-4) unstable; urgency=medium * Added kfreebsd-patch, thanks to Bas Couwenberg . -- Alf Gaida Fri, 13 May 2016 18:21:52 +0200 qtermwidget (0.6.0+20160108-3) unstable; urgency=medium * Fixed symbols for -03, thanks vorlon (Closes: #819225) * Bump standards to 3.9.7 * Use secured VCS-links * Added hardening =+ all to rules -- Alf Gaida Sun, 27 Mar 2016 12:24:03 +0200 qtermwidget (0.6.0+20160108-2) unstable; urgency=medium * patching: 798053 'TCGETS' not declared -- Alf Gaida Thu, 14 Jan 2016 00:47:51 +0100 qtermwidget (0.6.0+20160108-1) unstable; urgency=medium [ Alf Gaida ] * Cherry-picking upstream version 0.6.0+20160108, Modification of treatment of double-width character (e.g. Japanese) https://github.com/lxde/qtermwidget/pull/55#issuecomment-170615897 * Fixed copyright * No full stop in short descriptions, see lintian warning: 'description-synopsis-might-not-be-phrased-properly' [ Peter Mattern ] * Fixed descriptions in debian/control -- Alf Gaida Mon, 11 Jan 2016 20:41:00 +0100 qtermwidget (0.6.0+20151225-1) unstable; urgency=medium * Cherry-picking upstream version 0.6.0+201501225. * Cleaned up debian/control * Cleaned up debian/copyright, remove GPL-3+ because it is not used in the project any longer, relicense debian to GPL-2+ * Fixed symbols * Fixed LDFLAGS * Removed obsoleted overrides from debian/rules -- Alf Gaida Sun, 27 Dec 2015 13:34:09 +0100 qtermwidget (0.6.0+20150709-4) unstable; urgency=medium * Merge to unstable. -- ChangZhuo Chen (陳昌倬) Mon, 16 Nov 2015 23:23:00 +0800 qtermwidget (0.6.0+20150709-3) experimental; urgency=medium * reduce symbols mess again -- Alf Gaida Thu, 29 Oct 2015 00:09:51 +0100 qtermwidget (0.6.0+20150709-2) experimental; urgency=medium * revert most of the optional symbol marks * sort symbols and added some empty lines and comments * introduce arch specific symbols * switch to experimental -- Alf Gaida Sat, 03 Oct 2015 22:34:42 +0200 qtermwidget (0.6.0+20150709-1) unstable; urgency=medium [ Alf Gaida ] * Cherry-picking upstream version 0.6.0+20150709. * Symbols fixed for amd64 and i386 [ ChangZhuo Chen (陳昌倬) ] * Make all non QTermWidget symbols optional (Closes: #798050). -- ChangZhuo Chen (陳昌倬) Tue, 15 Sep 2015 20:34:04 +0800 qtermwidget (0.6.0-1) unstable; urgency=medium [ Alf Gaida ] * README added. * new debian $foo. * Initial release (Closes: #675355). [ Andrew Lee (李健秋) ] * Adding upstream version 0.6.0. [ ChangZhuo Chen (陳昌倬) ] * Update symbol control file. * Add watch. * Cleanup control. * Update copyright. * Cleanup rule. * Update changelog. [ Andrew Lee (李健秋) ] * Drop build-deps on quilt in control. * Refine package descriptions. * Added myself in copyright file. * Refine copyright file. -- Andrew Lee (李健秋) Wed, 19 Aug 2015 02:39:14 +0800 deepin-terminal-5.2.11/3rdparty/terminalwidget/debian/control000066400000000000000000000035531370157770500243130ustar00rootroot00000000000000Source: qtermwidget Maintainer: LXQt Packaging Team Uploaders: Alf Gaida , ChangZhuo Chen (陳昌倬) , Andrew Lee (李健秋) Section: libs Priority: optional Build-Depends: debhelper-compat (= 12), cmake, libutf8proc-dev, lxqt-build-tools (>= 0.6.0~), qtbase5-dev Standards-Version: 4.3.0 Vcs-Browser: https://salsa.debian.org/lxqt-team/qtermwidget Vcs-Git: https://salsa.debian.org/lxqt-team/qtermwidget.git Homepage: https://github.com/lxqt/qtermwidget Package: libqtermwidget5-0 Architecture: any Multi-Arch: same Depends: ${shlibs:Depends}, ${misc:Depends}, qtermwidget5-data (= ${source:Version}) Recommends: qtermwidget-l10n, fonts-hack Pre-Depends: ${misc:Pre-Depends} Description: Terminal emulator widget for Qt 5 (shared libraries) QTermWidget is a Unicode-enabled, embeddable Qt widget that can be used as built-in console or terminal emulation widget. . This package provides the shared libraries. Package: libqtermwidget5-0-dev Architecture: any Multi-Arch: same Section: libdevel Depends: ${misc:Depends}, libqtermwidget5-0 (= ${binary:Version}) Description: Terminal emulator widget for Qt 5 (development files) QTermWidget is a Unicode-enabled, embeddable Qt widget that can be used as built-in console or terminal emulation widget. . This package provides the development files. Package: qtermwidget5-data Architecture: all Multi-Arch: foreign Depends: ${misc:Depends} Description: Terminal emulator widget for Qt 5 (data files) QTermWidget is a Unicode-enabled, embeddable Qt widget that can be used as built-in console or terminal emulation widget. . This package provides data files like translations, keyboard layouts and color schemes. deepin-terminal-5.2.11/3rdparty/terminalwidget/debian/copyright000066400000000000000000000051451370157770500246420ustar00rootroot00000000000000Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/ Upstream-Name: qtermwidget Source: https://github.com/lxqt/qtermwidget Files: * Copyright: 2000 Stephan Kulow 2008 e_k 2007-2008 Robert Knight 1997,1998 Lars Doelle License: GPL-2+ Files: lib/kprocess.* lib/kpty* lib/qtermwidget.* lib/TerminalCharacterDecoder.* Copyright: 2007 Oswald Buddenhagen 2008 e_k (e_k@users.sourceforge.net) License: LGPL-2+ Files: debian/* Copyright: 2012-2019 Alf Gaida 2016 Peter Mattern 2015 ChangZhuo Chen (陳昌倬) 2015 Andrew Lee (李健秋) 2012 Thorsten Wohlfarth 2012 Henson Sturgill License: GPL-2+ License: LGPL-2+ This 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; either version 2 of the License, 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; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. . On Debian system, the complete text of GNU Lesser General Public License can be found in "/usr/share/common-licenses/LGPL-2". License: GPL-2+ This package is free software; you can redistribute it and/or modify it under the terms of the 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 package 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 . On Debian systems, the complete text of the GNU General Public License version 2 can be found in "/usr/share/common-licenses/GPL-2". deepin-terminal-5.2.11/3rdparty/terminalwidget/debian/docs000066400000000000000000000000221370157770500235470ustar00rootroot00000000000000AUTHORS README.md deepin-terminal-5.2.11/3rdparty/terminalwidget/debian/libqtermwidget5-0-dev.install000066400000000000000000000001641370157770500303140ustar00rootroot00000000000000usr/include usr/lib/*/libqtermwidget5.so usr/lib/*/pkgconfig/qtermwidget5.pc usr/lib/*/cmake/qtermwidget5/*.cmake deepin-terminal-5.2.11/3rdparty/terminalwidget/debian/libqtermwidget5-0.install000066400000000000000000000000371370157770500275370ustar00rootroot00000000000000usr/lib/*/libqtermwidget5.so.* deepin-terminal-5.2.11/3rdparty/terminalwidget/debian/libqtermwidget5-0.symbols000066400000000000000000000133501370157770500275630ustar00rootroot00000000000000libqtermwidget5.so.0 libqtermwidget5-0 #MINVER# * Build-Depends-Package: libqtermwidget5-0-dev (c++)"QTermWidget::QTermWidget(QWidget*)@Base" 0.6.0 (c++)"QTermWidget::QTermWidget(int, QWidget*)@Base" 0.6.0 (c++)"QTermWidget::activity()@Base" 0.6.0 (c++)"QTermWidget::addCustomColorSchemeDir(QString const&)@Base" 0.7.0 (c++)"QTermWidget::availableColorSchemes()@Base" 0.6.0 (c++)"QTermWidget::availableKeyBindings()@Base" 0.6.0 (c++)"QTermWidget::bell(QString const&)@Base" 0.6.0 (c++)"QTermWidget::bracketText(QString&)@Base" 0.9.0~ (c++)"QTermWidget::changeDir(QString const&)@Base" 0.6.0 (c++)"QTermWidget::clear()@Base" 0.6.0 (c++)"QTermWidget::copyAvailable(bool)@Base" 0.6.0 (c++)"QTermWidget::copyClipboard()@Base" 0.6.0 (c++)"QTermWidget::cursorChanged(Konsole::Emulation::KeyboardCursorShape, bool)@Base" 0.8.0 (c++)"QTermWidget::filterActions(QPoint const&)@Base" 0.7.1 (c++)"QTermWidget::find()@Base" 0.6.0 (c++)"QTermWidget::findNext()@Base" 0.6.0 (c++)"QTermWidget::findPrevious()@Base" 0.6.0 (c++)"QTermWidget::finished()@Base" 0.6.0 (c++)"QTermWidget::flowControlEnabled()@Base" 0.6.0 (c++)"QTermWidget::getHotSpotAt(QPoint const&) const@Base" 0.6.0 (c++)"QTermWidget::getHotSpotAt(int, int) const@Base" 0.6.0 (c++)"QTermWidget::getMargin() const@Base" 0.14.0~ (c++)"QTermWidget::getPtySlaveFd() const@Base" 0.6.0 (c++)"QTermWidget::getSelectionEnd(int&, int&)@Base" 0.6.0 (c++)"QTermWidget::getSelectionStart(int&, int&)@Base" 0.6.0 (c++)"QTermWidget::getShellPID()@Base" 0.6.0 (c++)"QTermWidget::getTerminalFont()@Base" 0.6.0 (c++)"QTermWidget::historyLinesCount()@Base" 0.6.0 (c++)"QTermWidget::icon() const@Base" 0.7.0 (c++)"QTermWidget::init(int)@Base" 0.6.0 (c++)"QTermWidget::isBidiEnabled()@Base" 0.9.0~ (c++)"QTermWidget::isTitleChanged() const@Base" 0.7.0 (c++)"QTermWidget::keyBindings()@Base" 0.6.0 (c++)"QTermWidget::matchFound(int, int, int, int)@Base" 0.6.0 (c++)"QTermWidget::metaObject() const@Base" 0.6.0 (c++)"QTermWidget::noMatchFound()@Base" 0.6.0 (c++)"QTermWidget::pasteClipboard()@Base" 0.6.0 (c++)"QTermWidget::pasteSelection()@Base" 0.6.0 (c++)"QTermWidget::profileChanged(QString const&)@Base" 0.8.0 (c++)"QTermWidget::qt_metacall(QMetaObject::Call, int, void**)@Base" 0.6.0 (c++)"QTermWidget::qt_metacast(char const*)@Base" 0.6.0 (c++)"QTermWidget::receivedData(QString const&)@Base" 0.8.0 (c++)"QTermWidget::resizeEvent(QResizeEvent*)@Base" 0.6.0 (c++)"QTermWidget::screenColumnsCount()@Base" 0.6.0 (c++)"QTermWidget::screenLinesCount()@Base" 0.6.0 (c++)"QTermWidget::scrollToEnd()@Base" 0.6.0 (c++)"QTermWidget::search(bool, bool)@Base" 0.6.0 (c++)"QTermWidget::selectedText(bool)@Base" 0.6.0 (c++)"QTermWidget::selectionChanged(bool)@Base" 0.6.0 (c++)"QTermWidget::sendData(char const*, int)@Base" 0.6.0 (c++)"QTermWidget::sendText(QString const&)@Base" 0.6.0 (c++)"QTermWidget::sessionFinished()@Base" 0.6.0 (c++)"QTermWidget::setArgs(QStringList const&)@Base" 0.6.0 (c++)"QTermWidget::setAutoClose(bool)@Base" 0.8.0 (c++)"QTermWidget::setBidiEnabled(bool)@Base" 0.9.0~ (c++)"QTermWidget::setBlinkingCursor(bool)@Base" 0.8.0 (c++)"QTermWidget::setColorScheme(QString const&)@Base" 0.6.0 (c++)"QTermWidget::setEnvironment(QStringList const&)@Base" 0.6.0 (c++)"QTermWidget::setFlowControlEnabled(bool)@Base" 0.6.0 (c++)"QTermWidget::setFlowControlWarningEnabled(bool)@Base" 0.6.0 (c++)"QTermWidget::setHistorySize(int)@Base" 0.6.0 (c++)"QTermWidget::setKeyBindings(QString const&)@Base" 0.6.0 (c++)"QTermWidget::setKeyboardCursorShape(Konsole::Emulation::KeyboardCursorShape)@Base" 0.8.0 (c++)"QTermWidget::setMargin(int)@Base" 0.14.0~ (c++)"QTermWidget::setMonitorActivity(bool)@Base" 0.6.0 (c++)"QTermWidget::setMonitorSilence(bool)@Base" 0.6.0 (c++)"QTermWidget::setMotionAfterPasting(int)@Base" 0.6.0 (c++)"QTermWidget::setScrollBarPosition(QTermWidget::ScrollBarPosition)@Base" 0.6.0 (c++)"QTermWidget::setSelectionEnd(int, int)@Base" 0.6.0 (c++)"QTermWidget::setSelectionStart(int, int)@Base" 0.6.0 (c++)"QTermWidget::setShellProgram(QString const&)@Base" 0.6.0 (c++)"QTermWidget::setSilenceTimeout(int)@Base" 0.6.0 (c++)"QTermWidget::setSize(QSize const&)@Base" 0.6.0 (c++)"QTermWidget::setTerminalBackgroundImage(QString)@Base" 0.7.1 (c++)"QTermWidget::setTerminalFont(QFont const&)@Base" 0.6.0 (c++)"QTermWidget::setTerminalOpacity(double)@Base" 0.6.0 (c++)"QTermWidget::setTerminalSizeHint(bool)@Base" 0.9.0~ (c++)"QTermWidget::setTextCodec(QTextCodec*)@Base" 0.6.0 (c++)"QTermWidget::setWorkingDirectory(QString const&)@Base" 0.6.0 (c++)"QTermWidget::setZoom(int)@Base" 0.6.0 (c++)"QTermWidget::silence()@Base" 0.6.0 (c++)"QTermWidget::sizeHint() const@Base" 0.6.0 (c++)"QTermWidget::startShellProgram()@Base" 0.6.0 (c++)"QTermWidget::startTerminalTeletype()@Base" 0.6.0 (c++)"QTermWidget::staticMetaObject@Base" 0.6.0 (c++)"QTermWidget::termGetFocus()@Base" 0.6.0 (c++)"QTermWidget::termKeyPressed(QKeyEvent*)@Base" 0.6.0 (c++)"QTermWidget::termLostFocus()@Base" 0.6.0 (c++)"QTermWidget::terminalSizeHint()@Base" 0.9.0~ (c++)"QTermWidget::title() const@Base" 0.7.0 (c++)"QTermWidget::titleChanged()@Base" 0.7.0 (c++)"QTermWidget::toggleShowSearchBar()@Base" 0.6.0 (c++)"QTermWidget::urlActivated(QUrl const&, bool)@Base" 0.7.1 (c++)"QTermWidget::workingDirectory()@Base" 0.6.0 (c++)"QTermWidget::zoomIn()@Base" 0.6.0 (c++)"QTermWidget::zoomOut()@Base" 0.6.0 (c++)"QTermWidget::~QTermWidget()@Base" 0.6.0 (c++)"non-virtual thunk to QTermWidget::~QTermWidget()@Base" 0.6.0 (c++)"typeinfo for QTermWidget@Base" 0.6.0 (c++)"typeinfo name for QTermWidget@Base" 0.6.0 (c++)"void std::__cxx11::basic_string, std::allocator >::_M_construct(wchar_t const*, wchar_t const*, std::forward_iterator_tag)@Base" 0.9.0~ (c++)"vtable for QTermWidget@Base" 0.6.0 deepin-terminal-5.2.11/3rdparty/terminalwidget/debian/qtermwidget5-data.install000066400000000000000000000001541370157770500276220ustar00rootroot00000000000000usr/share/qtermwidget5/color-schemes usr/share/qtermwidget5/kb-layouts usr/share/qtermwidget5/translations deepin-terminal-5.2.11/3rdparty/terminalwidget/debian/rules000066400000000000000000000010111370157770500237500ustar00rootroot00000000000000#!/usr/bin/make -f # export DH_VERBOSE=1 export LC_ALL=C.UTF-8 export DEB_LDFLAGS_MAINT_APPEND = -Wl,--as-needed export DEB_BUILD_MAINT_OPTIONS = hardening=+all %: dh ${@} --buildsystem cmake override_dh_missing: dh_missing --fail-missing override_dh_auto_configure: dh_auto_configure -- \ -DUPDATE_TRANSLATIONS=OFF \ -DBUILD_EXAMPLE=OFF \ -DTERMINALWIDGET_USE_UTEMPTER=OFF \ -DTERMINALWIDGET_BUILD_PYTHON_BINDING=OFF \ -DUSE_UTF8PROC=ON \ -DCMAKE_BUILD_TYPE=RelWithDebInfo deepin-terminal-5.2.11/3rdparty/terminalwidget/debian/source/000077500000000000000000000000001370157770500242025ustar00rootroot00000000000000deepin-terminal-5.2.11/3rdparty/terminalwidget/debian/source/format000066400000000000000000000000131370157770500254070ustar00rootroot000000000000003.0 (quilt)deepin-terminal-5.2.11/3rdparty/terminalwidget/debian/source/options000066400000000000000000000000261370157770500256160ustar00rootroot00000000000000tar-ignore=.gitignore deepin-terminal-5.2.11/3rdparty/terminalwidget/debian/upstream/000077500000000000000000000000001370157770500245425ustar00rootroot00000000000000deepin-terminal-5.2.11/3rdparty/terminalwidget/debian/upstream/metadata000066400000000000000000000004641370157770500262510ustar00rootroot00000000000000Name: qtermwidget Bug-Database: https://github.com/lxqt/qtermwidget/issues Bug-Submit: https://github.com/lxqt/qtermwidget/issues/new Changelog: https://github.com/lxqt/qtermwidget/blob/master/CHANGELOG Repository: https://github.com/lxqt/qtermwidget Repository-Browser: https://github.com/lxqt/qtermwidget deepin-terminal-5.2.11/3rdparty/terminalwidget/debian/upstream/signing-key.asc000066400000000000000000000057751370157770500274740ustar00rootroot00000000000000-----BEGIN PGP PUBLIC KEY BLOCK----- mQINBFXQeMMBEACif4+9pTrC6uNmRng0ZbzLh7p3cazmbnp2YFgDQDJZ7ZNmebxy ngRuRhjGuDcFAL/37BwJnrBpfZFK9ljoH4Fo5Jm9cOELaTy7AIcEiV9dKMyrKF1E C76d8jHVuzuPbI92DkFdLZAdk+qjrrAy0x43PvUd+aaBGLcFs1ZMk7gOvElc2d95 zWWSp5anjukmGbp+EsStnWJkF6VHj56qmklfYy5ioiVBOSpXo/RsACAcIlz8C8A1 d4tNMiB2uF2OrUfrL8DD6m3nBqep+AYbIQrxMl9kUQH3I33e9kH/L+SHQyE6phS8 Czq06WjV4TcJ9VWxm7hQCNLYSxhZYYr1AW45lS5+xmfBOq2qeLgvjbFxa8PPrsp6 Bqgt8MjwUkXjU5IB7YulUBvFU2l0MJZWDBuNy0oNtCe1cU3JyIqLKjvzQQQ9eD5L o3Ul704TLHz0z+67Rxh05Mi4JvyFMjnooSJkNH8/7yXoBN0ZGOh1/5zMU1gK5bmP 6hKgis2exSZNIS74mF6/PqGgcwk3PyI4T3keUQoNPj11M2EznLHxY19QZfQ5oMed 8xOlHKjpcm8PYMB4gduNXlV7gI9h7UxuC5GuPiP2lmM6wUyHu48divxDk5UYgPEC xlPI2wHCNDsuy0EruCYIvrMSZfpYCCSrmXiOORBLO5qXkauILLkJarHqjQARAQAB tCBBbGYgR2FpZGEgPGFnYWlkYUBzaWR1Y3Rpb24ub3JnPokCOAQTAQIAIgUCVdB4 wwIbAwYLCQgHAwIGFQgCCQoLBBYCAwECHgECF4AACgkQQsnI069epeOT2xAAgSHf 41103cnElGf6TokPl4J6hdRPy2CUAjmBtMfr8eajYvGDGgnmsh9AGYGURjfFVCCf Ag+8b6nF3xg03UmgsuSO8H78HGv9kKzF9aHmLt+SXq3jUX+LnIkFHErZWjFAKdJr luu1j6ltxLe9PQljxZnugzMaUbW8eEPKvcriiDn3S4/DtikW/jpGA0MTY4ZWs9pZ L/6iRRH99L2X/cWO4sCgDXCTt4oK0f5OvwiuCoVOM+PYoIm31JICCKOlqamkCn7d 2KH3nsy0v7tXgnrnb/zr8jVGsZLzUE51AFOzb5Ec74/2SAq8X4gbTppttLXEIooq nbepitW/PePkPY5gpfwHtFbl88qFnir+ABMefqRZkzeh0tsxJVLVHGP1KZykXpv7 96A6Q1h7Zo9Ny7WwN5Xl02g35LVCaPyzd3A8A4315uMuP3iziq57UktKqh9d5S3t jfK7e9UfFQZBLfxn2sNPsjdYSNUQp/PXTTk/599h359WVuUIR866T8K7N7EEon3p qLItZljQ9Nmr/yGwKi9iQgi2LtZj5KUcF1zBLzZKf95FvoqSZqBXdFSjm+eYGaCH Q2IBnhyP92lEknSK9ystUJXmY69tQKBFqJxScwaS+7a/rfLKssQjSWxqk+SX4QeW e9z9FUpo71bq0Zkc/M9aOCoEEmhg4Ob/JWy08oC5Ag0EVdB4wwEQAKZDCc/C41y0 omLFCAJybvHiFScM+jOpyGpQvceoviEhIT7h1br/pnSEMkgPQEDPWJGtKueg1/94 sXTH24uefr3Y6JdZoBtprxl4JXUoOndgq1QH1xuUsy3/9YWU8Qboy9j8a8w0oCDE T8Z03KHCwqzD3K+44jhmhF+0eLoaaY8ohS8ziP+DcFKVHyatmS5yCCdjVrj6PxMp uy/y5SXT1kmiPdVAIzQlM5DlN6o46TV+BH0pPvVYjtwf31o0FckJxy5S1v0koCNB vX2b7tTDPKzn8G18eUVhGoUTZBUCp1gg36wJ0YY4xgZ9vI/xDCeHeAkyvGtaTAoy qP4rHoUO5KVRSDh7frSlrdbLGWHaQwOhcqoKd4qP/164wHPGkgHL1vztdOc7l1wx q3gMh2uwmJR0NRrw4WVuaIqL9lEbGBNijlmGsuqXfsMRhc/qoqgVDWvrcCtEoOwl TONGobW3jpCCjpa9SeGNjxuY6IVLn0lfX4hItNVY9sFA+H+yj4uBQ7zsmMUXafxt Yllm0f98yGNg5lnJg4bLOYu3IkpogUKNA3qkZ+6vRtwH70/bJGp7qdx/3G4W5dMX asd/rJjdELW+R/NVULAmK1ETSklaa3Z6vbTu8bN8gvP8pmMJ8f/U8+qzkuAqc201 Z4O+s7ZsQfTiz5mm7zPGIYTnppDSno/rABEBAAGJAh8EGAECAAkFAlXQeMMCGwwA CgkQQsnI069epeMt0g/+JrwLhULD6NOxaLgxboh/KZkh/7ViU4cB+QPT8JIcWxkZ zj8uk85TUitEUzKmjp/ItCrhQE5WNNWbz/FBnAuLtaQuHhcHMA3Vu95UUCGi1vyZ ZRlS3YRM6S9BOzrjG7fGQJmO/RU3g6rb0TAwGFxDHj8t4JEDTc3zASG7wV/VTn06 d8XIH9CZOw3kUuhkQ3OR/PEj1BCeCC+caC+tBjO0fgvDp8RV7NFQQ9kH8R3/xlWd 6KMPtILE6fUft6LubWRGd1P5JBuzXivELolASajewbYtL/s87CCji3ngq0aT9raK m02wqFzNbX1iv+w2iqPQXq6pdRyxtJ8+Q8Z7zEBGJS5nkrYjsLTduZIjJHYHYH7f 3/ydVjQ3z12iqHKElgaRI7RUmpNiNxVIr+TtuxzeC6G+CF++XNkUtJODvCmRaoJS waYsitz8+LSv3tawZJ0iQkKc9nerQMuBD+AzIr3i4NgXiEIN513esUtnKzeyIIsL ntUcBjXKuLCj8OZrZtexjq7edWWbN57/3ikyS2Z7y0i3O30qk5jmccSaS6kA7xTY WCDFzbN2v2y+vGu9KYn+2HtrP2BtNa8JTh3waNeLUTpn4GV4mMrsZjOy6vhhHb91 1TKfI1gvjk7lE9xaWmcDjdI55dw3jIq8kK9SdgORGq9/S3g7KJNRjme+6GjqQfk= =h7ww -----END PGP PUBLIC KEY BLOCK----- deepin-terminal-5.2.11/3rdparty/terminalwidget/debian/watch000066400000000000000000000001721370157770500237330ustar00rootroot00000000000000version=4 opts="pgpsigurlmangle=s/$/.asc/" \ https://github.com/lxqt/qtermwidget/releases .*/qtermwidget-([\d\.]+).tar.xz deepin-terminal-5.2.11/3rdparty/terminalwidget/example/000077500000000000000000000000001370157770500231135ustar00rootroot00000000000000deepin-terminal-5.2.11/3rdparty/terminalwidget/example/README000066400000000000000000000001061370157770500237700ustar00rootroot00000000000000here is sample program which uses QTermWidet for displaying a terminaldeepin-terminal-5.2.11/3rdparty/terminalwidget/example/RemoteTerm/000077500000000000000000000000001370157770500251765ustar00rootroot00000000000000deepin-terminal-5.2.11/3rdparty/terminalwidget/example/RemoteTerm/README.md000066400000000000000000000007001370157770500264520ustar00rootroot00000000000000A simple example showing how to use QTermWidget to control and display a remote terminal. To run this example, you should: 1. Build client-side program. In my PC, I use 'apt-get' to install the QTermWidget library. 2. Start the shell-srv.py with specific paramenters.This will expose a shell via socket. 3. Start the client-side program from commandline with specific paramenters. Now you will get your own remote terminal work with QTermWidget.deepin-terminal-5.2.11/3rdparty/terminalwidget/example/RemoteTerm/RemoteTerm.pro000066400000000000000000000020171370157770500300030ustar00rootroot00000000000000#------------------------------------------------- # # Project created by QtCreator 2017-10-31T00:37:59 # #------------------------------------------------- QT += core gui network greaterThan(QT_MAJOR_VERSION, 4): QT += widgets TARGET = RemoteTerm TEMPLATE = app # The following define makes your compiler emit warnings if you use # any feature of Qt which as been marked as deprecated (the exact warnings # depend on your compiler). Please consult the documentation of the # deprecated API in order to know how to port your code away from it. DEFINES += QT_DEPRECATED_WARNINGS # You can also make your code fail to compile if you use deprecated APIs. # In order to do so, uncomment the following line. # You can also select to disable deprecated APIs only up to a certain version of Qt. #DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000 # disables all the APIs deprecated before Qt 6.0.0 CONFIG += c++11 SOURCES += \ main.cpp \ remoteterm.cpp HEADERS += \ remoteterm.h unix:!macx: LIBS += -lqtermwidget5 deepin-terminal-5.2.11/3rdparty/terminalwidget/example/RemoteTerm/main.cpp000066400000000000000000000007771370157770500266410ustar00rootroot00000000000000#include "remoteterm.h" #include #include int main(int argc, char *argv[]) { QApplication a(argc, argv); if(a.arguments().size() != 3){ qDebug() << "Example(client-side) for remote terminal of QTermWidget."; qDebug() << QString("Usage: %1 ipaddr port").arg(a.arguments()[0]); return 1; } QString ipaddr = a.arguments().at(1); quint16 port = a.arguments().at(2).toUShort(); RemoteTerm w(ipaddr,port); w.show(); return a.exec(); } deepin-terminal-5.2.11/3rdparty/terminalwidget/example/RemoteTerm/remoteterm.cpp000066400000000000000000000016451370157770500300730ustar00rootroot00000000000000#include "remoteterm.h" #include #include #include RemoteTerm::RemoteTerm(const QString &ipaddr, quint16 port, QWidget *parent) : QTermWidget(0,parent) { socket = new QTcpSocket(this); // Write what we input to remote terminal via socket connect(this, &RemoteTerm::sendData,[this](const char *data, int size){ this->socket->write(data, size); }); // Read anything from remote terminal via socket and show it on widget. connect(socket,&QTcpSocket::readyRead,[this](){ QByteArray data = socket->readAll(); write(this->getPtySlaveFd(), data.data(), data.size()); }); connect(socket, SIGNAL(error(QAbstractSocket::SocketError)),this,SLOT(atError())); // Here we start an empty pty. this->startTerminalTeletype(); socket->connectToHost(ipaddr, port); } void RemoteTerm::atError() { qDebug() << socket->errorString(); } deepin-terminal-5.2.11/3rdparty/terminalwidget/example/RemoteTerm/remoteterm.h000066400000000000000000000004771370157770500275420ustar00rootroot00000000000000#ifndef WIDGET_H #define WIDGET_H #include class QTcpSocket; class RemoteTerm : public QTermWidget { Q_OBJECT public: RemoteTerm(const QString &ipaddr, quint16 port, QWidget *parent = 0); public slots: void atError(); private: QTcpSocket *socket; }; #endif // WIDGET_H deepin-terminal-5.2.11/3rdparty/terminalwidget/example/RemoteTerm/shell-srv.py000066400000000000000000000015161370157770500274720ustar00rootroot00000000000000#!/usr/bin/env python import sys import os import socket import pty def usage(program): print "Example(server-side) for remote terminal of QTermWidget." print "Usage: %s ipaddr port" %program def main(): if len(sys.argv) != 3: usage(sys.argv[0]) sys.exit(1) s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: s.bind((sys.argv[1], int(sys.argv[2]))) s.listen(0) print "[+]Start Server." except Exception as e: print "[-]Error Happened: %s" %e.message sys.exit(2) while True: c = s.accept() os.dup2(c[0].fileno(), 0) os.dup2(c[0].fileno(), 1) os.dup2(c[0].fileno(), 2) # It's important to use pty to spawn the shell. pty.spawn("/bin/sh") c[0].close() if __name__ == "__main__": main() deepin-terminal-5.2.11/3rdparty/terminalwidget/example/main.cpp000066400000000000000000000053531370157770500245510ustar00rootroot00000000000000/* Copyright (C) 2008 e_k (e_k@users.sourceforge.net) This 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; either version 2 of the License, 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. */ #include #include #include #include #include #include "qtermwidget.h" int main(int argc, char *argv[]) { QApplication app(argc, argv); QIcon::setThemeName("oxygen"); QMainWindow *mainWindow = new QMainWindow(); QTermWidget *console = new QTermWidget(); QMenuBar *menuBar = new QMenuBar(mainWindow); QMenu *actionsMenu = new QMenu("Actions", menuBar); menuBar->addMenu(actionsMenu); actionsMenu->addAction("Find..", console, SLOT(toggleShowSearchBar()), QKeySequence(Qt::CTRL + Qt::SHIFT + Qt::Key_F)); actionsMenu->addAction("About Qt", &app, SLOT(aboutQt())); mainWindow->setMenuBar(menuBar); QFont font = QApplication::font(); #ifdef Q_WS_MAC font.setFamily("Monaco"); #elif defined(Q_WS_QWS) font.setFamily("fixed"); #else font.setFamily("Monospace"); #endif font.setPointSize(12); console->setTerminalFont(font); // console->setColorScheme(COLOR_SCHEME_BLACK_ON_LIGHT_YELLOW); console->setScrollBarPosition(QTermWidget::ScrollBarRight); const auto arguments = QApplication::arguments(); for (const QString& arg : arguments) { if (console->availableColorSchemes().contains(arg)) console->setColorScheme(arg); if (console->availableKeyBindings().contains(arg)) console->setKeyBindings(arg); } mainWindow->setCentralWidget(console); mainWindow->resize(600, 400); // info output qDebug() << "* INFO *************************"; qDebug() << " availableKeyBindings:" << console->availableKeyBindings(); qDebug() << " keyBindings:" << console->keyBindings(); qDebug() << " availableColorSchemes:" << console->availableColorSchemes(); qDebug() << "* INFO END *********************"; // real startup QObject::connect(console, SIGNAL(finished()), mainWindow, SLOT(close())); mainWindow->show(); return app.exec(); } deepin-terminal-5.2.11/3rdparty/terminalwidget/lib/000077500000000000000000000000001370157770500222265ustar00rootroot00000000000000deepin-terminal-5.2.11/3rdparty/terminalwidget/lib/BlockArray.cpp000066400000000000000000000175541370157770500247770ustar00rootroot00000000000000/* This file is part of Konsole, an X terminal. Copyright (C) 2000 by Stephan Kulow Rewritten for QT4 by e_k , Copyright (C)2008 This program is free software; you can redistribute it and/or modify it under the terms of the 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. */ #include // Own #include "BlockArray.h" // System #include #include #include #include using namespace Konsole; static int blocksize = 0; BlockArray::BlockArray() : size(0), current(size_t(-1)), index(size_t(-1)), lastmap(nullptr), lastmap_index(size_t(-1)), lastblock(nullptr), ion(-1), length(0) { // lastmap_index = index = current = size_t(-1); if (blocksize == 0) { blocksize = ((sizeof(Block) / getpagesize()) + 1) * getpagesize(); } } BlockArray::~BlockArray() { setHistorySize(0); Q_ASSERT(!lastblock); } size_t BlockArray::append(Block * block) { if (!size) { return size_t(-1); } ++current; if (current >= size) { current = 0; } int rc; rc = lseek(ion, current * blocksize, SEEK_SET); if (rc < 0) { perror("HistoryBuffer::add.seek"); setHistorySize(0); return size_t(-1); } rc = write(ion, block, blocksize); if (rc < 0) { perror("HistoryBuffer::add.write"); setHistorySize(0); return size_t(-1); } length++; if (length > size) { length = size; } ++index; delete block; return current; } size_t BlockArray::newBlock() { if (!size) { return size_t(-1); } append(lastblock); lastblock = new Block(); return index + 1; } Block * BlockArray::lastBlock() const { return lastblock; } bool BlockArray::has(size_t i) const { if (i == index + 1) { return true; } if (i > index) { return false; } if (index - i >= length) { return false; } return true; } const Block * BlockArray::at(size_t i) { if (i == index + 1) { return lastblock; } if (i == lastmap_index) { return lastmap; } if (i > index) { qDebug() << "BlockArray::at() i > index\n"; return nullptr; } // if (index - i >= length) { // kDebug(1211) << "BlockArray::at() index - i >= length\n"; // return 0; // } size_t j = i; // (current - (index - i) + (index/size+1)*size) % size ; Q_ASSERT(j < size); unmap(); Block * block = (Block *)mmap(nullptr, blocksize, PROT_READ, MAP_PRIVATE, ion, j * blocksize); if (block == (Block *)-1) { perror("mmap"); return nullptr; } lastmap = block; lastmap_index = i; return block; } void BlockArray::unmap() { if (lastmap) { int res = munmap((char *)lastmap, blocksize); if (res < 0) { perror("munmap"); } } lastmap = nullptr; lastmap_index = size_t(-1); } bool BlockArray::setSize(size_t newsize) { return setHistorySize(newsize * 1024 / blocksize); } bool BlockArray::setHistorySize(size_t newsize) { // kDebug(1211) << "setHistorySize " << size << " " << newsize; if (size == newsize) { return false; } unmap(); if (!newsize) { delete lastblock; lastblock = nullptr; if (ion >= 0) { close(ion); } ion = -1; current = size_t(-1); return true; } if (!size) { FILE * tmp = tmpfile(); if (!tmp) { perror("konsole: cannot open temp file.\n"); } else { ion = dup(fileno(tmp)); if (ion<0) { perror("konsole: cannot dup temp file.\n"); fclose(tmp); } } if (ion < 0) { return false; } Q_ASSERT(!lastblock); lastblock = new Block(); size = newsize; return false; } if (newsize > size) { increaseBuffer(); size = newsize; return false; } else { decreaseBuffer(newsize); ftruncate(ion, length*blocksize); size = newsize; return true; } } void moveBlock(FILE * fion, int cursor, int newpos, char * buffer2) { int res = fseek(fion, cursor * blocksize, SEEK_SET); if (res) { perror("fseek"); } res = fread(buffer2, blocksize, 1, fion); if (res != 1) { perror("fread"); } res = fseek(fion, newpos * blocksize, SEEK_SET); if (res) { perror("fseek"); } res = fwrite(buffer2, blocksize, 1, fion); if (res != 1) { perror("fwrite"); } // printf("moving block %d to %d\n", cursor, newpos); } void BlockArray::decreaseBuffer(size_t newsize) { if (index < newsize) { // still fits in whole return; } int offset = (current - (newsize - 1) + size) % size; if (!offset) { return; } // The Block constructor could do somthing in future... char * buffer1 = new char[blocksize]; FILE * fion = fdopen(dup(ion), "w+b"); if (!fion) { delete [] buffer1; perror("fdopen/dup"); return; } int firstblock; if (current <= newsize) { firstblock = current + 1; } else { firstblock = 0; } size_t oldpos; for (size_t i = 0, cursor=firstblock; i < newsize; i++) { oldpos = (size + cursor + offset) % size; moveBlock(fion, oldpos, cursor, buffer1); if (oldpos < newsize) { cursor = oldpos; } else { cursor++; } } current = newsize - 1; length = newsize; delete [] buffer1; fclose(fion); } void BlockArray::increaseBuffer() { if (index < size) { // not even wrapped once return; } int offset = (current + size + 1) % size; if (!offset) { // no moving needed return; } // The Block constructor could do somthing in future... char * buffer1 = new char[blocksize]; char * buffer2 = new char[blocksize]; int runs = 1; int bpr = size; // blocks per run if (size % offset == 0) { bpr = size / offset; runs = offset; } FILE * fion = fdopen(dup(ion), "w+b"); if (!fion) { perror("fdopen/dup"); delete [] buffer1; delete [] buffer2; return; } int res; for (int i = 0; i < runs; i++) { // free one block in chain int firstblock = (offset + i) % size; res = fseek(fion, firstblock * blocksize, SEEK_SET); if (res) { perror("fseek"); } res = fread(buffer1, blocksize, 1, fion); if (res != 1) { perror("fread"); } int newpos = 0; for (int j = 1, cursor=firstblock; j < bpr; j++) { cursor = (cursor + offset) % size; newpos = (cursor - offset + size) % size; moveBlock(fion, cursor, newpos, buffer2); } res = fseek(fion, i * blocksize, SEEK_SET); if (res) { perror("fseek"); } res = fwrite(buffer1, blocksize, 1, fion); if (res != 1) { perror("fwrite"); } } current = size - 1; length = size; delete [] buffer1; delete [] buffer2; fclose(fion); } deepin-terminal-5.2.11/3rdparty/terminalwidget/lib/BlockArray.h000066400000000000000000000061451370157770500244360ustar00rootroot00000000000000/* This file is part of Konsole, an X terminal. Copyright (C) 2000 by Stephan Kulow Rewritten for QT4 by e_k , Copyright (C)2008 This program is free software; you can redistribute it and/or modify it under the terms of the 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 BLOCKARRAY_H #define BLOCKARRAY_H #include //#error Do not use in KDE 2.1 #define QTERMWIDGET_BLOCKSIZE (1 << 12) #define ENTRIES ((QTERMWIDGET_BLOCKSIZE - sizeof(size_t) ) / sizeof(unsigned char)) namespace Konsole { struct Block { Block() { size = 0; } unsigned char data[ENTRIES]; size_t size; }; // /////////////////////////////////////////////////////// class BlockArray { public: /** * Creates a history file for holding * maximal size blocks. If more blocks * are requested, then it drops earlier * added ones. */ BlockArray(); /// destructor ~BlockArray(); /** * adds the Block at the end of history. * This may drop other blocks. * * The ownership on the block is transfered. * An unique index number is returned for accessing * it later (if not yet dropped then) * * Note, that the block may be dropped completely * if history is turned off. */ size_t append(Block * block); /** * gets the block at the index. Function may return * 0 if the block isn't available any more. * * The returned block is strictly readonly as only * maped in memory - and will be invalid on the next * operation on this class. */ const Block * at(size_t index); /** * reorders blocks as needed. If newsize is null, * the history is emptied completely. The indices * returned on append won't change their semantic, * but they may not be valid after this call. */ bool setHistorySize(size_t newsize); size_t newBlock(); Block * lastBlock() const; /** * Convenient function to set the size in KBytes * instead of blocks */ bool setSize(size_t newsize); size_t len() const { return length; } bool has(size_t index) const; size_t getCurrent() const { return current; } private: void unmap(); void increaseBuffer(); void decreaseBuffer(size_t newsize); size_t size; // current always shows to the last inserted block size_t current; size_t index; Block * lastmap; size_t lastmap_index; Block * lastblock; int ion; size_t length; }; } #endif deepin-terminal-5.2.11/3rdparty/terminalwidget/lib/Character.h000066400000000000000000000176521370157770500243060ustar00rootroot00000000000000/* This file is part of Konsole, KDE's 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 CHARACTER_H #define CHARACTER_H // Qt #include // Local #include "CharacterColor.h" namespace Konsole { typedef unsigned char LineProperty; static const int LINE_DEFAULT = 0; static const int LINE_WRAPPED = (1 << 0); static const int LINE_DOUBLEWIDTH = (1 << 1); static const int LINE_DOUBLEHEIGHT = (1 << 2); #define DEFAULT_RENDITION 0 #define RE_BOLD (1 << 0) #define RE_BLINK (1 << 1) #define RE_UNDERLINE (1 << 2) #define RE_REVERSE (1 << 3) // Screen only #define RE_INTENSIVE (1 << 3) // Widget only #define RE_ITALIC (1 << 4) #define RE_CURSOR (1 << 5) #define RE_EXTENDED_CHAR (1 << 6) #define RE_FAINT (1 << 7) #define RE_STRIKEOUT (1 << 8) #define RE_CONCEAL (1 << 9) #define RE_OVERLINE (1 << 10) /** * A single character in the terminal which consists of a unicode character * value, foreground and background colors and a set of rendition attributes * which specify how it should be drawn. */ class Character { public: /** * Constructs a new character. * * @param _c The unicode character value of this character. * @param _f The foreground color used to draw the character. * @param _b The color used to draw the character's background. * @param _r A set of rendition flags which specify how this character is to be drawn. */ inline Character(quint16 _c = ' ', CharacterColor _f = CharacterColor(COLOR_SPACE_DEFAULT,DEFAULT_FORE_COLOR), CharacterColor _b = CharacterColor(COLOR_SPACE_DEFAULT,DEFAULT_BACK_COLOR), quint8 _r = DEFAULT_RENDITION) : character(_c), rendition(_r), foregroundColor(_f), backgroundColor(_b) {} union { /** The unicode character value for this character. */ wchar_t character; /** * Experimental addition which allows a single Character instance to contain more than * one unicode character. * * charSequence is a hash code which can be used to look up the unicode * character sequence in the ExtendedCharTable used to create the sequence. */ quint16 charSequence; }; /** A combination of RENDITION flags which specify options for drawing the character. */ quint8 rendition; /** The foreground color used to draw this character. */ CharacterColor foregroundColor; /** The color used to draw this character's background. */ CharacterColor backgroundColor; /** * Returns true if this character has a transparent background when * it is drawn with the specified @p palette. */ bool isTransparent(const ColorEntry* palette) const; /** * Returns true if this character should always be drawn in bold when * it is drawn with the specified @p palette, independent of whether * or not the character has the RE_BOLD rendition flag. */ ColorEntry::FontWeight fontWeight(const ColorEntry* base) const; /** * returns true if the format (color, rendition flag) of the compared characters is equal */ bool equalsFormat(const Character &other) const; /** * Compares two characters and returns true if they have the same unicode character value, * rendition and colors. */ friend bool operator == (const Character& a, const Character& b); /** * Compares two characters and returns true if they have different unicode character values, * renditions or colors. */ friend bool operator != (const Character& a, const Character& b); }; inline bool operator == (const Character& a, const Character& b) { return a.character == b.character && a.rendition == b.rendition && a.foregroundColor == b.foregroundColor && a.backgroundColor == b.backgroundColor; } inline bool operator != (const Character& a, const Character& b) { return a.character != b.character || a.rendition != b.rendition || a.foregroundColor != b.foregroundColor || a.backgroundColor != b.backgroundColor; } inline bool Character::isTransparent(const ColorEntry* base) const { return ((backgroundColor._colorSpace == COLOR_SPACE_DEFAULT) && base[backgroundColor._u+0+(backgroundColor._v?BASE_COLORS:0)].transparent) || ((backgroundColor._colorSpace == COLOR_SPACE_SYSTEM) && base[backgroundColor._u+2+(backgroundColor._v?BASE_COLORS:0)].transparent); } inline bool Character::equalsFormat(const Character& other) const { return backgroundColor==other.backgroundColor && foregroundColor==other.foregroundColor && rendition==other.rendition; } inline ColorEntry::FontWeight Character::fontWeight(const ColorEntry* base) const { if (backgroundColor._colorSpace == COLOR_SPACE_DEFAULT) return base[backgroundColor._u+0+(backgroundColor._v?BASE_COLORS:0)].fontWeight; else if (backgroundColor._colorSpace == COLOR_SPACE_SYSTEM) return base[backgroundColor._u+2+(backgroundColor._v?BASE_COLORS:0)].fontWeight; else return ColorEntry::UseCurrentFormat; } extern unsigned short vt100_graphics[32]; /** * A table which stores sequences of unicode characters, referenced * by hash keys. The hash key itself is the same size as a unicode * character ( ushort ) so that it can occupy the same space in * a structure. */ class ExtendedCharTable { public: /** Constructs a new character table. */ ExtendedCharTable(); ~ExtendedCharTable(); /** * Adds a sequences of unicode characters to the table and returns * a hash code which can be used later to look up the sequence * using lookupExtendedChar() * * If the same sequence already exists in the table, the hash * of the existing sequence will be returned. * * @param unicodePoints An array of unicode character points * @param length Length of @p unicodePoints */ ushort createExtendedChar(ushort* unicodePoints , ushort length); /** * Looks up and returns a pointer to a sequence of unicode characters * which was added to the table using createExtendedChar(). * * @param hash The hash key returned by createExtendedChar() * @param length This variable is set to the length of the * character sequence. * * @return A unicode character sequence of size @p length. */ ushort* lookupExtendedChar(ushort hash , ushort& length) const; /** The global ExtendedCharTable instance. */ static ExtendedCharTable instance; private: // calculates the hash key of a sequence of unicode points of size 'length' ushort extendedCharHash(ushort* unicodePoints , ushort length) const; // tests whether the entry in the table specified by 'hash' matches the // character sequence 'unicodePoints' of size 'length' bool extendedCharMatch(ushort hash , ushort* unicodePoints , ushort length) const; // internal, maps hash keys to character sequence buffers. The first ushort // in each value is the length of the buffer, followed by the ushorts in the buffer // themselves. QHash extendedCharTable; }; } Q_DECLARE_TYPEINFO(Konsole::Character, Q_MOVABLE_TYPE); #endif // CHARACTER_H deepin-terminal-5.2.11/3rdparty/terminalwidget/lib/CharacterColor.h000066400000000000000000000202601370157770500252720ustar00rootroot00000000000000/* This file is part of Konsole, KDE's 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 CHARACTERCOLOR_H #define CHARACTERCOLOR_H // Qt #include //#include #define KDE_NO_EXPORT namespace Konsole { /** * An entry in a terminal display's color palette. * * A color palette is an array of 16 ColorEntry instances which map * system color indexes (from 0 to 15) into actual colors. * * Each entry can be set as bold, in which case any text * drawn using the color should be drawn in bold. * * Each entry can also be transparent, in which case the terminal * display should avoid drawing the background for any characters * using the entry as a background. */ class ColorEntry { public: /** Specifies the weight to use when drawing text with this color. */ enum FontWeight { /** Always draw text in this color with a bold weight. */ Bold, /** Always draw text in this color with a normal weight. */ Normal, /** * Use the current font weight set by the terminal application. * This is the default behavior. */ UseCurrentFormat }; /** * Constructs a new color palette entry. * * @param c The color value for this entry. * @param tr Specifies that the color should be transparent when used as a background color. * @param weight Specifies the font weight to use when drawing text with this color. */ ColorEntry(QColor c, bool tr, FontWeight weight = UseCurrentFormat) : color(c), transparent(tr), fontWeight(weight) {} /** * Constructs a new color palette entry with an undefined color, and * with the transparent and bold flags set to false. */ ColorEntry() : transparent(false), fontWeight(UseCurrentFormat) {} /** * Sets the color, transparency and boldness of this color to those of @p rhs. */ void operator=(const ColorEntry& rhs) { color = rhs.color; transparent = rhs.transparent; fontWeight = rhs.fontWeight; } /** The color value of this entry for display. */ QColor color; /** * If true character backgrounds using this color should be transparent. * This is not applicable when the color is used to render text. */ bool transparent; /** * Specifies the font weight to use when drawing text with this color. * This is not applicable when the color is used to draw a character's background. */ FontWeight fontWeight; }; // Attributed Character Representations /////////////////////////////// // Colors #define BASE_COLORS (2+8) #define INTENSITIES 2 #define TABLE_COLORS (INTENSITIES*BASE_COLORS) #define DEFAULT_FORE_COLOR 0 #define DEFAULT_BACK_COLOR 1 //a standard set of colors using black text on a white background. //defined in TerminalDisplay.cpp extern const ColorEntry base_color_table[TABLE_COLORS] KDE_NO_EXPORT; /* CharacterColor is a union of the various color spaces. Assignment is as follows: Type - Space - Values 0 - Undefined - u: 0, v:0 w:0 1 - Default - u: 0..1 v:intense w:0 2 - System - u: 0..7 v:intense w:0 3 - Index(256) - u: 16..255 v:0 w:0 4 - RGB - u: 0..255 v:0..256 w:0..256 Default colour space has two separate colours, namely default foreground and default background colour. */ #define COLOR_SPACE_UNDEFINED 0 #define COLOR_SPACE_DEFAULT 1 #define COLOR_SPACE_SYSTEM 2 #define COLOR_SPACE_256 3 #define COLOR_SPACE_RGB 4 /** * Describes the color of a single character in the terminal. */ class CharacterColor { friend class Character; public: /** Constructs a new CharacterColor whoose color and color space are undefined. */ CharacterColor() : _colorSpace(COLOR_SPACE_UNDEFINED), _u(0), _v(0), _w(0) {} /** * Constructs a new CharacterColor using the specified @p colorSpace and with * color value @p co * * The meaning of @p co depends on the @p colorSpace used. * * TODO : Document how @p co relates to @p colorSpace * * TODO : Add documentation about available color spaces. */ CharacterColor(quint8 colorSpace, int co) : _colorSpace(colorSpace), _u(0), _v(0), _w(0) { switch (colorSpace) { case COLOR_SPACE_DEFAULT: _u = co & 1; break; case COLOR_SPACE_SYSTEM: _u = co & 7; _v = (co >> 3) & 1; break; case COLOR_SPACE_256: _u = co & 255; break; case COLOR_SPACE_RGB: _u = co >> 16; _v = co >> 8; _w = co; break; default: _colorSpace = COLOR_SPACE_UNDEFINED; } } /** * Returns true if this character color entry is valid. */ bool isValid() const { return _colorSpace != COLOR_SPACE_UNDEFINED; } /** * Set the value of this color from a normal system color to the corresponding intensive * system color if it's not already an intensive system color. * * This is only applicable if the color is using the COLOR_SPACE_DEFAULT or COLOR_SPACE_SYSTEM * color spaces. */ void setIntensive(); /** * Returns the color within the specified color @p palette * * The @p palette is only used if this color is one of the 16 system colors, otherwise * it is ignored. */ QColor color(const ColorEntry* palette) const; /** * Compares two colors and returns true if they represent the same color value and * use the same color space. */ friend bool operator == (const CharacterColor& a, const CharacterColor& b); /** * Compares two colors and returns true if they represent different color values * or use different color spaces. */ friend bool operator != (const CharacterColor& a, const CharacterColor& b); private: quint8 _colorSpace; // bytes storing the character color quint8 _u; quint8 _v; quint8 _w; }; inline bool operator == (const CharacterColor& a, const CharacterColor& b) { return a._colorSpace == b._colorSpace && a._u == b._u && a._v == b._v && a._w == b._w; } inline bool operator != (const CharacterColor& a, const CharacterColor& b) { return !operator==(a,b); } inline const QColor color256(quint8 u, const ColorEntry* base) { // 0.. 16: system colors if (u < 8) return base[u+2 ].color; u -= 8; if (u < 8) return base[u+2+BASE_COLORS].color; u -= 8; // 16..231: 6x6x6 rgb color cube if (u < 216) return QColor(((u/36)%6) ? (40*((u/36)%6)+55) : 0, ((u/ 6)%6) ? (40*((u/ 6)%6)+55) : 0, ((u/ 1)%6) ? (40*((u/ 1)%6)+55) : 0); u -= 216; // 232..255: gray, leaving out black and white int gray = u*10+8; return QColor(gray,gray,gray); } inline QColor CharacterColor::color(const ColorEntry* base) const { switch (_colorSpace) { case COLOR_SPACE_DEFAULT: return base[_u+0+(_v?BASE_COLORS:0)].color; case COLOR_SPACE_SYSTEM: return base[_u+2+(_v?BASE_COLORS:0)].color; case COLOR_SPACE_256: return color256(_u,base); case COLOR_SPACE_RGB: return {_u,_v,_w}; case COLOR_SPACE_UNDEFINED: return QColor(); } Q_ASSERT(false); // invalid color space return QColor(); } inline void CharacterColor::setIntensive() { if (_colorSpace == COLOR_SPACE_SYSTEM || _colorSpace == COLOR_SPACE_DEFAULT) { _v = 1; } } } #endif // CHARACTERCOLOR_H deepin-terminal-5.2.11/3rdparty/terminalwidget/lib/ColorScheme.cpp000066400000000000000000000611351370157770500251430ustar00rootroot00000000000000/* 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. */ // Own #include "ColorScheme.h" #include "tools.h" // Qt #include #include #include #include #include #include #include // KDE //#include //#include //#include //#include //#include //#include using namespace Konsole; const ColorEntry ColorScheme::defaultTable[TABLE_COLORS] = // The following are almost IBM standard color codes, with some slight // gamma correction for the dim colors to compensate for bright X screens. // It contains the 8 ansiterm/xterm colors in 2 intensities. { ColorEntry( QColor(0x00,0x00,0x00), false), ColorEntry( QColor(0xFF,0xFF,0xFF), true), // Dfore, Dback ColorEntry( QColor(0x00,0x00,0x00), false), ColorEntry( QColor(0xB2,0x18,0x18), false), // Black, Red ColorEntry( QColor(0x18,0xB2,0x18), false), ColorEntry( QColor(0xB2,0x68,0x18), false), // Green, Yellow ColorEntry( QColor(0x18,0x18,0xB2), false), ColorEntry( QColor(0xB2,0x18,0xB2), false), // Blue, Magenta ColorEntry( QColor(0x18,0xB2,0xB2), false), ColorEntry( QColor(0xB2,0xB2,0xB2), false), // Cyan, White // intensive ColorEntry( QColor(0x00,0x00,0x00), false), ColorEntry( QColor(0xFF,0xFF,0xFF), true), ColorEntry( QColor(0x68,0x68,0x68), false), ColorEntry( QColor(0xFF,0x54,0x54), false), ColorEntry( QColor(0x54,0xFF,0x54), false), ColorEntry( QColor(0xFF,0xFF,0x54), false), ColorEntry( QColor(0x54,0x54,0xFF), false), ColorEntry( QColor(0xFF,0x54,0xFF), false), ColorEntry( QColor(0x54,0xFF,0xFF), false), ColorEntry( QColor(0xFF,0xFF,0xFF), false) }; const char* const ColorScheme::colorNames[TABLE_COLORS] = { "Foreground", "Background", "Color0", "Color1", "Color2", "Color3", "Color4", "Color5", "Color6", "Color7", "ForegroundIntense", "BackgroundIntense", "Color0Intense", "Color1Intense", "Color2Intense", "Color3Intense", "Color4Intense", "Color5Intense", "Color6Intense", "Color7Intense" }; // dummy silently comment out the tr_NOOP #define tr_NOOP const char* const ColorScheme::translatedColorNames[TABLE_COLORS] = { tr_NOOP("Foreground"), tr_NOOP("Background"), tr_NOOP("Color 1"), tr_NOOP("Color 2"), tr_NOOP("Color 3"), tr_NOOP("Color 4"), tr_NOOP("Color 5"), tr_NOOP("Color 6"), tr_NOOP("Color 7"), tr_NOOP("Color 8"), tr_NOOP("Foreground (Intense)"), tr_NOOP("Background (Intense)"), tr_NOOP("Color 1 (Intense)"), tr_NOOP("Color 2 (Intense)"), tr_NOOP("Color 3 (Intense)"), tr_NOOP("Color 4 (Intense)"), tr_NOOP("Color 5 (Intense)"), tr_NOOP("Color 6 (Intense)"), tr_NOOP("Color 7 (Intense)"), tr_NOOP("Color 8 (Intense)") }; ColorScheme::ColorScheme() { _table = nullptr; _randomTable = nullptr; _opacity = 1.0; } ColorScheme::ColorScheme(const ColorScheme& other) : _opacity(other._opacity) ,_table(nullptr) ,_randomTable(nullptr) { setName(other.name()); setDescription(other.description()); if ( other._table != nullptr ) { for ( int i = 0 ; i < TABLE_COLORS ; i++ ) setColorTableEntry(i,other._table[i]); } if ( other._randomTable != nullptr ) { for ( int i = 0 ; i < TABLE_COLORS ; i++ ) { const RandomizationRange& range = other._randomTable[i]; setRandomizationRange(i,range.hue,range.saturation,range.value); } } } ColorScheme::~ColorScheme() { delete[] _table; delete[] _randomTable; } void ColorScheme::setDescription(const QString& description) { _description = description; } QString ColorScheme::description() const { return _description; } void ColorScheme::setName(const QString& name) { _name = name; } QString ColorScheme::name() const { return _name; } void ColorScheme::setColorTableEntry(int index , const ColorEntry& entry) { Q_ASSERT( index >= 0 && index < TABLE_COLORS ); if ( !_table ) { _table = new ColorEntry[TABLE_COLORS]; for (int i=0;i= 0 && index < TABLE_COLORS ); if ( randomSeed != 0 ) qsrand(randomSeed); ColorEntry entry = colorTable()[index]; if ( randomSeed != 0 && _randomTable != nullptr && !_randomTable[index].isNull() ) { const RandomizationRange& range = _randomTable[index]; int hueDifference = range.hue ? (qrand() % range.hue) - range.hue/2 : 0; int saturationDifference = range.saturation ? (qrand() % range.saturation) - range.saturation/2 : 0; int valueDifference = range.value ? (qrand() % range.value) - range.value/2 : 0; QColor& color = entry.color; int newHue = qAbs( (color.hue() + hueDifference) % MAX_HUE ); int newValue = qMin( qAbs(color.value() + valueDifference) , 255 ); int newSaturation = qMin( qAbs(color.saturation() + saturationDifference) , 255 ); color.setHsv(newHue,newSaturation,newValue); } return entry; } void ColorScheme::getColorTable(ColorEntry* table , uint randomSeed) const { for ( int i = 0 ; i < TABLE_COLORS ; i++ ) table[i] = colorEntry(i,randomSeed); } bool ColorScheme::randomizedBackgroundColor() const { return _randomTable == nullptr ? false : !_randomTable[1].isNull(); } void ColorScheme::setRandomizedBackgroundColor(bool randomize) { // the hue of the background colour is allowed to be randomly // adjusted as much as possible. // // the value and saturation are left alone to maintain read-ability if ( randomize ) { setRandomizationRange( 1 /* background color index */ , MAX_HUE , 255 , 0 ); } else { if ( _randomTable ) setRandomizationRange( 1 /* background color index */ , 0 , 0 , 0 ); } } void ColorScheme::setRandomizationRange( int index , quint16 hue , quint8 saturation , quint8 value ) { Q_ASSERT( hue <= MAX_HUE ); Q_ASSERT( index >= 0 && index < TABLE_COLORS ); if ( _randomTable == nullptr ) _randomTable = new RandomizationRange[TABLE_COLORS]; _randomTable[index].hue = hue; _randomTable[index].value = value; _randomTable[index].saturation = saturation; } const ColorEntry* ColorScheme::colorTable() const { if ( _table ) return _table; else return defaultTable; } QColor ColorScheme::foregroundColor() const { return colorTable()[0].color; } QColor ColorScheme::backgroundColor() const { return colorTable()[1].color; } bool ColorScheme::hasDarkBackground() const { // value can range from 0 - 255, with larger values indicating higher brightness. // so 127 is in the middle, anything less is deemed 'dark' return backgroundColor().value() < 127; } void ColorScheme::setOpacity(qreal opacity) { _opacity = opacity; } qreal ColorScheme::opacity() const { return _opacity; } void ColorScheme::read(const QString & fileName) { QSettings s(fileName, QSettings::IniFormat); s.beginGroup(QLatin1String("General")); _description = s.value(QLatin1String("Description"), QObject::tr("Un-named Color Scheme")).toString(); _opacity = s.value(QLatin1String("Opacity"),qreal(1.0)).toDouble(); s.endGroup(); for (int i=0 ; i < TABLE_COLORS ; i++) { readColorEntry(&s, i); } } #if 0 // implemented upstream - user apps void ColorScheme::read(KConfig& config) { KConfigGroup configGroup = config.group("General"); QString description = configGroup.readEntry("Description", QObject::tr("Un-named Color Scheme")); _description = tr(description.toUtf8()); _opacity = configGroup.readEntry("Opacity",qreal(1.0)); for (int i=0 ; i < TABLE_COLORS ; i++) { readColorEntry(config,i); } } void ColorScheme::write(KConfig& config) const { KConfigGroup configGroup = config.group("General"); configGroup.writeEntry("Description",_description); configGroup.writeEntry("Opacity",_opacity); for (int i=0 ; i < TABLE_COLORS ; i++) { RandomizationRange random = _randomTable != 0 ? _randomTable[i] : RandomizationRange(); writeColorEntry(config,colorNameForIndex(i),colorTable()[i],random); } } #endif QString ColorScheme::colorNameForIndex(int index) { Q_ASSERT( index >= 0 && index < TABLE_COLORS ); return QString::fromLatin1(colorNames[index]); } QString ColorScheme::translatedColorNameForIndex(int index) { Q_ASSERT( index >= 0 && index < TABLE_COLORS ); return QString::fromLatin1(translatedColorNames[index]); } void ColorScheme::readColorEntry(QSettings * s , int index) { QString colorName = colorNameForIndex(index); s->beginGroup(colorName); ColorEntry entry; QVariant colorValue = s->value(QLatin1String("Color")); QString colorStr; int r, g, b; bool ok = false; // XXX: Undocumented(?) QSettings behavior: values with commas are parsed // as QStringList and others QString if (colorValue.type() == QVariant::StringList) { QStringList rgbList = colorValue.toStringList(); colorStr = rgbList.join(QLatin1Char(',')); if (rgbList.count() == 3) { bool parse_ok; ok = true; r = rgbList[0].toInt(&parse_ok); ok = ok && parse_ok && (r >= 0 && r <= 0xff); g = rgbList[1].toInt(&parse_ok); ok = ok && parse_ok && (g >= 0 && g <= 0xff); b = rgbList[2].toInt(&parse_ok); ok = ok && parse_ok && (b >= 0 && b <= 0xff); } } else { colorStr = colorValue.toString(); QRegularExpression hexColorPattern(QLatin1String("^#[0-9a-f]{6}$"), QRegularExpression::CaseInsensitiveOption); if (hexColorPattern.match(colorStr).hasMatch()) { // Parsing is always ok as already matched by the regexp r = colorStr.midRef(1, 2).toInt(nullptr, 16); g = colorStr.midRef(3, 2).toInt(nullptr, 16); b = colorStr.midRef(5, 2).toInt(nullptr, 16); ok = true; } } if (!ok) { qWarning().nospace() << "Invalid color value " << colorStr << " for " << colorName << ". Fallback to black."; r = g = b = 0; } entry.color = QColor(r, g, b); entry.transparent = s->value(QLatin1String("Transparent"),false).toBool(); // Deprecated key from KDE 4.0 which set 'Bold' to true to force // a color to be bold or false to use the current format // // TODO - Add a new tri-state key which allows for bold, normal or // current format if (s->contains(QLatin1String("Bold"))) entry.fontWeight = s->value(QLatin1String("Bold"),false).toBool() ? ColorEntry::Bold : ColorEntry::UseCurrentFormat; quint16 hue = s->value(QLatin1String("MaxRandomHue"),0).toInt(); quint8 value = s->value(QLatin1String("MaxRandomValue"),0).toInt(); quint8 saturation = s->value(QLatin1String("MaxRandomSaturation"),0).toInt(); setColorTableEntry( index , entry ); if ( hue != 0 || value != 0 || saturation != 0 ) setRandomizationRange( index , hue , saturation , value ); s->endGroup(); } #if 0 // implemented upstream - user apps void ColorScheme::writeColorEntry(KConfig& config , const QString& colorName, const ColorEntry& entry , const RandomizationRange& random) const { KConfigGroup configGroup(&config,colorName); configGroup.writeEntry("Color",entry.color); configGroup.writeEntry("Transparency",(bool)entry.transparent); if (entry.fontWeight != ColorEntry::UseCurrentFormat) { configGroup.writeEntry("Bold",entry.fontWeight == ColorEntry::Bold); } // record randomization if this color has randomization or // if one of the keys already exists if ( !random.isNull() || configGroup.hasKey("MaxRandomHue") ) { configGroup.writeEntry("MaxRandomHue",(int)random.hue); configGroup.writeEntry("MaxRandomValue",(int)random.value); configGroup.writeEntry("MaxRandomSaturation",(int)random.saturation); } } #endif // // Work In Progress - A color scheme for use on KDE setups for users // with visual disabilities which means that they may have trouble // reading text with the supplied color schemes. // // This color scheme uses only the 'safe' colors defined by the // KColorScheme class. // // A complication this introduces is that each color provided by // KColorScheme is defined as a 'background' or 'foreground' color. // Only foreground colors are allowed to be used to render text and // only background colors are allowed to be used for backgrounds. // // The ColorEntry and TerminalDisplay classes do not currently // support this restriction. // // Requirements: // - A color scheme which uses only colors from the KColorScheme class // - Ability to restrict which colors the TerminalDisplay widget // uses as foreground and background color // - Make use of KGlobalSettings::allowDefaultBackgroundImages() as // a hint to determine whether this accessible color scheme should // be used by default. // // // -- Robert Knight 21/07/2007 // AccessibleColorScheme::AccessibleColorScheme() : ColorScheme() { #if 0 // It's not finished in konsole and it breaks Qt4 compilation as well // basic attributes setName("accessible"); setDescription(QObject::tr("Accessible Color Scheme")); // setup colors const int ColorRoleCount = 8; const KColorScheme colorScheme(QPalette::Active); QBrush colors[ColorRoleCount] = { colorScheme.foreground( colorScheme.NormalText ), colorScheme.background( colorScheme.NormalBackground ), colorScheme.foreground( colorScheme.InactiveText ), colorScheme.foreground( colorScheme.ActiveText ), colorScheme.foreground( colorScheme.LinkText ), colorScheme.foreground( colorScheme.VisitedText ), colorScheme.foreground( colorScheme.NegativeText ), colorScheme.foreground( colorScheme.NeutralText ) }; for ( int i = 0 ; i < TABLE_COLORS ; i++ ) { ColorEntry entry; entry.color = colors[ i % ColorRoleCount ].color(); setColorTableEntry( i , entry ); } #endif } KDE3ColorSchemeReader::KDE3ColorSchemeReader( QIODevice* device ) : _device(device) { } ColorScheme* KDE3ColorSchemeReader::read() { Q_ASSERT( _device->openMode() == QIODevice::ReadOnly || _device->openMode() == QIODevice::ReadWrite ); ColorScheme* scheme = new ColorScheme(); QRegExp comment(QLatin1String("#.*$")); while ( !_device->atEnd() ) { QString line(QString::fromUtf8(_device->readLine())); line.remove(comment); line = line.simplified(); if ( line.isEmpty() ) continue; if ( line.startsWith(QLatin1String("color")) ) { if (!readColorLine(line,scheme)) qDebug() << "Failed to read KDE 3 color scheme line" << line; } else if ( line.startsWith(QLatin1String("title")) ) { if (!readTitleLine(line,scheme)) qDebug() << "Failed to read KDE 3 color scheme title line" << line; } else { qDebug() << "KDE 3 color scheme contains an unsupported feature, '" << line << "'"; } } return scheme; } bool KDE3ColorSchemeReader::readColorLine(const QString& line,ColorScheme* scheme) { QStringList list = line.split(QLatin1Char(' ')); if (list.count() != 7) return false; if (list.first() != QLatin1String("color")) return false; int index = list[1].toInt(); int red = list[2].toInt(); int green = list[3].toInt(); int blue = list[4].toInt(); int transparent = list[5].toInt(); int bold = list[6].toInt(); const int MAX_COLOR_VALUE = 255; if( (index < 0 || index >= TABLE_COLORS ) || (red < 0 || red > MAX_COLOR_VALUE ) || (blue < 0 || blue > MAX_COLOR_VALUE ) || (green < 0 || green > MAX_COLOR_VALUE ) || (transparent != 0 && transparent != 1 ) || (bold != 0 && bold != 1) ) return false; ColorEntry entry; entry.color = QColor(red,green,blue); entry.transparent = ( transparent != 0 ); entry.fontWeight = ( bold != 0 ) ? ColorEntry::Bold : ColorEntry::UseCurrentFormat; scheme->setColorTableEntry(index,entry); return true; } bool KDE3ColorSchemeReader::readTitleLine(const QString& line,ColorScheme* scheme) { if( !line.startsWith(QLatin1String("title")) ) return false; int spacePos = line.indexOf(QLatin1Char(' ')); if( spacePos == -1 ) return false; QString description = line.mid(spacePos+1); scheme->setDescription(description); return true; } ColorSchemeManager::ColorSchemeManager() : _haveLoadedAll(false) { } ColorSchemeManager::~ColorSchemeManager() { QHashIterator iter(_colorSchemes); while (iter.hasNext()) { iter.next(); delete iter.value(); } } void ColorSchemeManager::loadAllColorSchemes() { int failed = 0; QList nativeColorSchemes = listColorSchemes(); QListIterator nativeIter(nativeColorSchemes); while ( nativeIter.hasNext() ) { if ( !loadColorScheme( nativeIter.next() ) ) failed++; } QList kde3ColorSchemes = listKDE3ColorSchemes(); QListIterator kde3Iter(kde3ColorSchemes); while ( kde3Iter.hasNext() ) { if ( !loadKDE3ColorScheme( kde3Iter.next() ) ) failed++; } if ( failed > 0 ){ qDebug() << "failed to load " << failed << " color schemes."; } qDebug() << "load all color schemes"; //qDebug() << "nativeColorSchemes" << nativeColorSchemes ; //qDebug() << "kde3ColorSchemes" << kde3ColorSchemes; _haveLoadedAll = true; } QList ColorSchemeManager::allColorSchemes() { if ( !_haveLoadedAll ) { loadAllColorSchemes(); } return _colorSchemes.values(); } bool ColorSchemeManager::loadKDE3ColorScheme(const QString& filePath) { QFile file(filePath); if (!filePath.endsWith(QLatin1String(".schema")) || !file.open(QIODevice::ReadOnly)) return false; KDE3ColorSchemeReader reader(&file); ColorScheme* scheme = reader.read(); scheme->setName(QFileInfo(file).baseName()); file.close(); if (scheme->name().isEmpty()) { qDebug() << "color scheme name is not valid."; delete scheme; return false; } QFileInfo info(filePath); if ( !_colorSchemes.contains(info.baseName()) ) _colorSchemes.insert(scheme->name(),scheme); else { qDebug() << "color scheme with name" << scheme->name() << "has already been" << "found, ignoring."; delete scheme; } return true; } #if 0 void ColorSchemeManager::addColorScheme(ColorScheme* scheme) { _colorSchemes.insert(scheme->name(),scheme); // save changes to disk QString path = KGlobal::dirs()->saveLocation("data","konsole/") + scheme->name() + ".colorscheme"; KConfig config(path , KConfig::NoGlobals); scheme->write(config); } #endif bool ColorSchemeManager::loadCustomColorScheme(const QString& path) { if (path.endsWith(QLatin1String(".colorscheme"))) return loadColorScheme(path); else if (path.endsWith(QLatin1String(".schema"))) return loadKDE3ColorScheme(path); else return false; } void ColorSchemeManager::addCustomColorSchemeDir(const QString& custom_dir) { add_custom_color_scheme_dir(custom_dir); } bool ColorSchemeManager::loadColorScheme(const QString& filePath) { if ( !filePath.endsWith(QLatin1String(".colorscheme")) || !QFile::exists(filePath) ) return false; QFileInfo info(filePath); const QString& schemeName = info.baseName(); ColorScheme* scheme = new ColorScheme(); scheme->setName(schemeName); scheme->read(filePath); if (scheme->name().isEmpty()) { qDebug() << "Color scheme in" << filePath << "does not have a valid name and was not loaded."; delete scheme; return false; } if ( !_colorSchemes.contains(schemeName) ) { _colorSchemes.insert(schemeName,scheme); } else { qDebug() << "color scheme with name" << schemeName << "has already been" << "found, ignoring."; delete scheme; } return true; } QList ColorSchemeManager::listKDE3ColorSchemes() { QList ret; for (const QString &scheme_dir : get_color_schemes_dirs()) { const QString dname(scheme_dir); QDir dir(dname); QStringList filters; filters << QLatin1String("*.schema"); dir.setNameFilters(filters); const QStringList list = dir.entryList(filters); for (const QString &i : list) ret << dname + QLatin1Char('/') + i; } return ret; //return KGlobal::dirs()->findAllResources("data", // "konsole/*.schema", // KStandardDirs::NoDuplicates); // } QList ColorSchemeManager::listColorSchemes() { QList ret; for (const QString &scheme_dir : get_color_schemes_dirs()) { const QString dname(scheme_dir); QDir dir(dname); QStringList filters; filters << QLatin1String("*.colorscheme"); dir.setNameFilters(filters); const QStringList list = dir.entryList(filters); for (const QString &i : list) ret << dname + QLatin1Char('/') + i; } return ret; // return KGlobal::dirs()->findAllResources("data", // "konsole/*.colorscheme", // KStandardDirs::NoDuplicates); } const ColorScheme ColorSchemeManager::_defaultColorScheme; const ColorScheme* ColorSchemeManager::defaultColorScheme() const { return &_defaultColorScheme; } bool ColorSchemeManager::deleteColorScheme(const QString& name) { Q_ASSERT( _colorSchemes.contains(name) ); // lookup the path and delete QString path = findColorSchemePath(name); if ( QFile::remove(path) ) { _colorSchemes.remove(name); return true; } else { qDebug() << "Failed to remove color scheme -" << path; return false; } } QString ColorSchemeManager::findColorSchemePath(const QString& name) const { // QString path = KStandardDirs::locate("data","konsole/"+name+".colorscheme"); const QStringList dirs = get_color_schemes_dirs(); if ( dirs.isEmpty() ) return QString(); const QString dir = dirs.first(); QString path(dir + QLatin1Char('/')+ name + QLatin1String(".colorscheme")); if ( !path.isEmpty() ) return path; //path = KStandardDirs::locate("data","konsole/"+name+".schema"); path = dir + QLatin1Char('/')+ name + QLatin1String(".schema"); return path; } const ColorScheme* ColorSchemeManager::findColorScheme(const QString& name) { if ( name.isEmpty() ) return defaultColorScheme(); if ( _colorSchemes.contains(name) ) return _colorSchemes[name]; else { // look for this color scheme QString path = findColorSchemePath(name); if ( !path.isEmpty() && loadColorScheme(path) ) { return findColorScheme(name); } else { if (!path.isEmpty() && loadKDE3ColorScheme(path)) return findColorScheme(name); } qDebug() << "Could not find color scheme - " << name; return nullptr; } } Q_GLOBAL_STATIC(ColorSchemeManager, theColorSchemeManager) ColorSchemeManager* ColorSchemeManager::instance() { return theColorSchemeManager; } deepin-terminal-5.2.11/3rdparty/terminalwidget/lib/ColorScheme.h000066400000000000000000000266501370157770500246130ustar00rootroot00000000000000/* 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 COLORSCHEME_H #define COLORSCHEME_H // Qt #include #include #include #include #include #include // Konsole #include "CharacterColor.h" class QIODevice; //class KConfig; namespace Konsole { /** * Represents a color scheme for a terminal display. * * The color scheme includes the palette of colors used to draw the text and character backgrounds * in the display and the opacity level of the display background. */ class ColorScheme { public: /** * Constructs a new color scheme which is initialised to the default color set * for Konsole. */ ColorScheme(); ColorScheme(const ColorScheme& other); ~ColorScheme(); /** Sets the descriptive name of the color scheme. */ void setDescription(const QString& description); /** Returns the descriptive name of the color scheme. */ QString description() const; /** Sets the name of the color scheme */ void setName(const QString& name); /** Returns the name of the color scheme */ QString name() const; #if 0 // Implemented upstream - in user apps /** Reads the color scheme from the specified configuration source */ void read(KConfig& config); /** Writes the color scheme to the specified configuration source */ void write(KConfig& config) const; #endif void read(const QString & filename); /** Sets a single entry within the color palette. */ void setColorTableEntry(int index , const ColorEntry& entry); /** * Copies the color entries which form the palette for this color scheme * into @p table. @p table should be an array with TABLE_COLORS entries. * * @param table Array into which the color entries for this color scheme * are copied. * @param randomSeed Color schemes may allow certain colors in their * palette to be randomized. The seed is used to pick the random color. */ void getColorTable(ColorEntry* table, uint randomSeed = 0) const; /** * Retrieves a single color entry from the table. * * See getColorTable() */ ColorEntry colorEntry(int index , uint randomSeed = 0) const; /** * Convenience method. Returns the * foreground color for this scheme, * this is the primary color used to draw the * text in this scheme. */ QColor foregroundColor() const; /** * Convenience method. Returns the background color for * this scheme, this is the primary color used to * draw the terminal background in this scheme. */ QColor backgroundColor() const; /** * Returns true if this color scheme has a dark background. * The background color is said to be dark if it has a value of less than 127 * in the HSV color space. */ bool hasDarkBackground() const; /** * Sets the opacity level of the display background. @p opacity ranges * between 0 (completely transparent background) and 1 (completely * opaque background). * * Defaults to 1. * * TODO: More documentation */ void setOpacity(qreal opacity); /** * Returns the opacity level for this color scheme, see setOpacity() * TODO: More documentation */ qreal opacity() const; /** * Enables randomization of the background color. This will cause * the palette returned by getColorTable() and colorEntry() to * be adjusted depending on the value of the random seed argument * to them. */ void setRandomizedBackgroundColor(bool randomize); /** Returns true if the background color is randomized. */ bool randomizedBackgroundColor() const; static QString colorNameForIndex(int index); static QString translatedColorNameForIndex(int index); private: // specifies how much a particular color can be randomized by class RandomizationRange { public: RandomizationRange() : hue(0) , saturation(0) , value(0) {} bool isNull() const { return ( hue == 0 && saturation == 0 && value == 0 ); } quint16 hue; quint8 saturation; quint8 value; }; // returns the active color table. if none has been set specifically, // this is the default color table. const ColorEntry* colorTable() const; #if 0 // implemented upstream - user apps // reads a single colour entry from a KConfig source // and sets the palette entry at 'index' to the entry read. void readColorEntry(KConfig& config , int index); // writes a single colour entry to a KConfig source void writeColorEntry(KConfig& config , const QString& colorName, const ColorEntry& entry,const RandomizationRange& range) const; #endif void readColorEntry(QSettings *s, int index); // sets the amount of randomization allowed for a particular color // in the palette. creates the randomization table if // it does not already exist void setRandomizationRange( int index , quint16 hue , quint8 saturation , quint8 value ); QString _description; QString _name; qreal _opacity; ColorEntry* _table; // pointer to custom color table or 0 if the default // color scheme is being used static const quint16 MAX_HUE = 340; RandomizationRange* _randomTable; // pointer to randomization table or 0 // if no colors in the color scheme support // randomization static const char* const colorNames[TABLE_COLORS]; static const char* const translatedColorNames[TABLE_COLORS]; static const ColorEntry defaultTable[]; // table of default color entries }; /** * A color scheme which uses colors from the standard KDE color palette. * * This is designed primarily for the benefit of users who are using specially * designed colors. * * TODO Implement and make it the default on systems with specialized KDE * color schemes. */ class AccessibleColorScheme : public ColorScheme { public: AccessibleColorScheme(); }; /** * Reads a color scheme stored in the .schema format used in the KDE 3 incarnation * of Konsole * * Only the basic essentials ( title and color palette entries ) are currently * supported. Additional options such as background image and background * blend colors are ignored. */ class KDE3ColorSchemeReader { public: /** * Constructs a new reader which reads from the specified device. * The device should be open in read-only mode. */ KDE3ColorSchemeReader( QIODevice* device ); /** * Reads and parses the contents of the .schema file from the input * device and returns the ColorScheme defined within it. * * Returns a null pointer if an error occurs whilst parsing * the contents of the file. */ ColorScheme* read(); private: // reads a line from the file specifying a colour palette entry // format is: color [index] [red] [green] [blue] [transparent] [bold] bool readColorLine(const QString& line , ColorScheme* scheme); bool readTitleLine(const QString& line , ColorScheme* scheme); QIODevice* _device; }; /** * Manages the color schemes available for use by terminal displays. * See ColorScheme */ class ColorSchemeManager { public: /** * Constructs a new ColorSchemeManager and loads the list * of available color schemes. * * The color schemes themselves are not loaded until they are first * requested via a call to findColorScheme() */ ColorSchemeManager(); /** * Destroys the ColorSchemeManager and saves any modified color schemes to disk. */ ~ColorSchemeManager(); /** * Returns the default color scheme for Konsole */ const ColorScheme* defaultColorScheme() const; /** * Returns the color scheme with the given name or 0 if no * scheme with that name exists. If @p name is empty, the * default color scheme is returned. * * The first time that a color scheme with a particular name is * requested, the configuration information is loaded from disk. */ const ColorScheme* findColorScheme(const QString& name); #if 0 /** * Adds a new color scheme to the manager. If @p scheme has the same name as * an existing color scheme, it replaces the existing scheme. * * TODO - Ensure the old color scheme gets deleted */ void addColorScheme(ColorScheme* scheme); #endif /** * Deletes a color scheme. Returns true on successful deletion or false otherwise. */ bool deleteColorScheme(const QString& name); /** * Returns a list of the all the available color schemes. * This may be slow when first called because all of the color * scheme resources on disk must be located, read and parsed. * * Subsequent calls will be inexpensive. */ QList allColorSchemes(); /** Returns the global color scheme manager instance. */ static ColorSchemeManager* instance(); /** @brief Loads a custom color scheme under given \em path. * * The \em path may refer to either KDE 4 .colorscheme or KDE 3 * .schema file * * The loaded color scheme is available under the name equal to * the base name of the \em path via the allColorSchemes() and * findColorScheme() methods after this call if loaded successfully. * * @param[in] path The path to KDE 4 .colorscheme or KDE 3 .schema. * @return Whether the color scheme is loaded successfully. */ bool loadCustomColorScheme(const QString& path); /** * @brief Allows to add a custom location of color schemes. * * @param[in] custom_dir Custom location of color schemes (must end with /). */ void addCustomColorSchemeDir(const QString& custom_dir); private: // loads a color scheme from a KDE 4+ .colorscheme file bool loadColorScheme(const QString& path); // loads a color scheme from a KDE 3 .schema file bool loadKDE3ColorScheme(const QString& path); // returns a list of paths of color schemes in the KDE 4+ .colorscheme file format QList listColorSchemes(); // returns a list of paths of color schemes in the .schema file format // used in KDE 3 QList listKDE3ColorSchemes(); // loads all of the color schemes void loadAllColorSchemes(); // finds the path of a color scheme QString findColorSchemePath(const QString& name) const; QHash _colorSchemes; QSet _modifiedSchemes; bool _haveLoadedAll; static const ColorScheme _defaultColorScheme; }; } Q_DECLARE_METATYPE(const Konsole::ColorScheme*) #endif //COLORSCHEME_H deepin-terminal-5.2.11/3rdparty/terminalwidget/lib/ColorTables.h000066400000000000000000000063201370157770500246110ustar00rootroot00000000000000#ifndef _COLOR_TABLE_H #define _COLOR_TABLE_H #include "CharacterColor.h" //using namespace Konsole; #if 0 static const ColorEntry whiteonblack_color_table[TABLE_COLORS] = { // normal ColorEntry(QColor(0xFF,0xFF,0xFF), false ), ColorEntry( QColor(0x00,0x00,0x00), true ), // Dfore, Dback ColorEntry(QColor(0x00,0x00,0x00), false ), ColorEntry( QColor(0xB2,0x18,0x18), false ), // Black, Red ColorEntry(QColor(0x18,0xB2,0x18), false ), ColorEntry( QColor(0xB2,0x68,0x18), false ), // Green, Yellow ColorEntry(QColor(0x18,0x18,0xB2), false ), ColorEntry( QColor(0xB2,0x18,0xB2), false ), // Blue, Magenta ColorEntry(QColor(0x18,0xB2,0xB2), false ), ColorEntry( QColor(0xB2,0xB2,0xB2), false ), // Cyan, White // intensiv ColorEntry(QColor(0x00,0x00,0x00), false ), ColorEntry( QColor(0xFF,0xFF,0xFF), true ), ColorEntry(QColor(0x68,0x68,0x68), false ), ColorEntry( QColor(0xFF,0x54,0x54), false ), ColorEntry(QColor(0x54,0xFF,0x54), false ), ColorEntry( QColor(0xFF,0xFF,0x54), false ), ColorEntry(QColor(0x54,0x54,0xFF), false ), ColorEntry( QColor(0xFF,0x54,0xFF), false ), ColorEntry(QColor(0x54,0xFF,0xFF), false ), ColorEntry( QColor(0xFF,0xFF,0xFF), false ) }; static const ColorEntry greenonblack_color_table[TABLE_COLORS] = { ColorEntry(QColor( 24, 240, 24), false), ColorEntry(QColor( 0, 0, 0), true), ColorEntry(QColor( 0, 0, 0), false), ColorEntry(QColor( 178, 24, 24), false), ColorEntry(QColor( 24, 178, 24), false), ColorEntry(QColor( 178, 104, 24), false), ColorEntry(QColor( 24, 24, 178), false), ColorEntry(QColor( 178, 24, 178), false), ColorEntry(QColor( 24, 178, 178), false), ColorEntry(QColor( 178, 178, 178), false), // intensive colors ColorEntry(QColor( 24, 240, 24), false ), ColorEntry(QColor( 0, 0, 0), true ), ColorEntry(QColor( 104, 104, 104), false ), ColorEntry(QColor( 255, 84, 84), false ), ColorEntry(QColor( 84, 255, 84), false ), ColorEntry(QColor( 255, 255, 84), false ), ColorEntry(QColor( 84, 84, 255), false ), ColorEntry(QColor( 255, 84, 255), false ), ColorEntry(QColor( 84, 255, 255), false ), ColorEntry(QColor( 255, 255, 255), false ) }; static const ColorEntry blackonlightyellow_color_table[TABLE_COLORS] = { ColorEntry(QColor( 0, 0, 0), false), ColorEntry(QColor( 255, 255, 221), true), ColorEntry(QColor( 0, 0, 0), false), ColorEntry(QColor( 178, 24, 24), false), ColorEntry(QColor( 24, 178, 24), false), ColorEntry(QColor( 178, 104, 24), false), ColorEntry(QColor( 24, 24, 178), false), ColorEntry(QColor( 178, 24, 178), false), ColorEntry(QColor( 24, 178, 178), false), ColorEntry(QColor( 178, 178, 178), false), ColorEntry(QColor( 0, 0, 0), false), ColorEntry(QColor( 255, 255, 221), true), ColorEntry(QColor(104, 104, 104), false), ColorEntry(QColor( 255, 84, 84), false), ColorEntry(QColor( 84, 255, 84), false), ColorEntry(QColor( 255, 255, 84), false), ColorEntry(QColor( 84, 84, 255), false), ColorEntry(QColor( 255, 84, 255), false), ColorEntry(QColor( 84, 255, 255), false), ColorEntry(QColor( 255, 255, 255), false) }; #endif #endif deepin-terminal-5.2.11/3rdparty/terminalwidget/lib/DefaultTranslatorText.h000066400000000000000000000001001370157770500266710ustar00rootroot00000000000000"keyboard \"Fallback Key Translator\"\n" "key Tab : \"\\t\" \0" deepin-terminal-5.2.11/3rdparty/terminalwidget/lib/Emulation.cpp000066400000000000000000000420751370157770500246770ustar00rootroot00000000000000/* Copyright 2007-2008 Robert Knight Copyright 1997,1998 by Lars Doelle Copyright 1996 by Matthias Ettrich This program is free software; you can redistribute it and/or modify it under the terms of the 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. */ // Own #include "Emulation.h" // System #include #include #include #include // Qt #include #include #include #include #include #include #include #include #include // KDE //#include // Konsole #include "KeyboardTranslator.h" #include "Screen.h" #include "TerminalCharacterDecoder.h" #include "ScreenWindow.h" #include "Session.h" #include "SessionManager.h" using namespace Konsole; Emulation::Emulation() : _currentScreen(nullptr), _codec(nullptr), _decoder(nullptr), _keyTranslator(nullptr), _usesMouse(false), _bracketedPasteMode(false) { // create screens with a default size _screen[0] = new Screen(40, 80); _screen[1] = new Screen(40, 80); _currentScreen = _screen[0]; QObject::connect(&_bulkTimer1, SIGNAL(timeout()), this, SLOT(showBulk())); QObject::connect(&_bulkTimer2, SIGNAL(timeout()), this, SLOT(showBulk())); // listen for mouse status changes connect(this, SIGNAL(programUsesMouseChanged(bool)), SLOT(usesMouseChanged(bool))); connect(this, SIGNAL(programBracketedPasteModeChanged(bool)), SLOT(bracketedPasteModeChanged(bool))); connect(this, &Emulation::cursorChanged, [this](KeyboardCursorShape cursorShape, bool blinkingCursorEnabled) { emit titleChanged(50, QString(QLatin1String("CursorShape=%1;BlinkingCursorEnabled=%2")) .arg(static_cast(cursorShape)).arg(blinkingCursorEnabled)); }); } bool Emulation::programUsesMouse() const { return _usesMouse; } void Emulation::usesMouseChanged(bool usesMouse) { _usesMouse = usesMouse; } bool Emulation::programBracketedPasteMode() const { return _bracketedPasteMode; } void Emulation::bracketedPasteModeChanged(bool bracketedPasteMode) { _bracketedPasteMode = bracketedPasteMode; } ScreenWindow *Emulation::createWindow() { ScreenWindow *window = new ScreenWindow(); window->setScreen(_currentScreen); _windows << window; connect(window, SIGNAL(selectionChanged()), this, SLOT(bufferedUpdate())); connect(this, SIGNAL(outputChanged()), window, SLOT(notifyOutputChanged())); return window; } Emulation::~Emulation() { QListIterator windowIter(_windows); while (windowIter.hasNext()) { delete windowIter.next(); } delete _screen[0]; delete _screen[1]; delete _decoder; } void Emulation::setScreen(int n) { Screen *old = _currentScreen; _currentScreen = _screen[n & 1]; if (_currentScreen != old) { // tell all windows onto this emulation to switch to the newly active screen for (ScreenWindow *window : qAsConst(_windows)) window->setScreen(_currentScreen); } } void Emulation::clearHistory() { _screen[0]->setScroll(_screen[0]->getScroll(), false); } void Emulation::setHistory(const HistoryType &t) { _screen[0]->setScroll(t); showBulk(); } const HistoryType &Emulation::history() const { return _screen[0]->getScroll(); } void Emulation::setCodec(const QTextCodec *qtc) { if (qtc) _codec = qtc; else setCodec(LocaleCodec); delete _decoder; _decoder = _codec->makeDecoder(); emit useUtf8Request(utf8()); } void Emulation::setCodec(EmulationCodec codec) { if (codec == Utf8Codec) setCodec(QTextCodec::codecForName("utf8")); else if (codec == LocaleCodec) setCodec(QTextCodec::codecForLocale()); } void Emulation::setSessionId(int sessionId) { _sessionId = sessionId; } void Emulation::setBackspaceMode(char *key, int length) { KeyboardTranslator::Entry entry = _keyTranslator->findEntry( Qt::Key_Backspace, Qt::NoModifier, KeyboardTranslator::NoState); KeyboardTranslator::Entry newEntry; KeyboardTranslator::States flags = KeyboardTranslator::NoState; KeyboardTranslator::States flagMask = KeyboardTranslator::NoState; Qt::KeyboardModifiers modifiers = Qt::NoModifier; Qt::KeyboardModifiers modifierMask = Qt::NoModifier; KeyboardTranslator::Command command = KeyboardTranslator::NoCommand; newEntry.setKeyCode(Qt::Key_Backspace); newEntry.setState(flags); newEntry.setStateMask(flagMask); newEntry.setModifiers(modifiers); newEntry.setModifierMask(modifierMask); newEntry.setText(QByteArray(key, length)); newEntry.setCommand(command); _keyTranslator->replaceEntry(entry, newEntry); } void Emulation::setDeleteMode(char *key, int length) { KeyboardTranslator::Entry entry = _keyTranslator->findEntry( Qt::Key_Delete, Qt::NoModifier, KeyboardTranslator::NoState); KeyboardTranslator::Entry newEntry; KeyboardTranslator::States flags = KeyboardTranslator::NoState; KeyboardTranslator::States flagMask = KeyboardTranslator::NoState; Qt::KeyboardModifiers modifiers = Qt::NoModifier; Qt::KeyboardModifiers modifierMask = Qt::NoModifier; KeyboardTranslator::Command command = KeyboardTranslator::NoCommand; newEntry.setKeyCode(Qt::Key_Delete); newEntry.setState(flags); newEntry.setStateMask(flagMask); newEntry.setModifiers(modifiers); newEntry.setModifierMask(modifierMask); newEntry.setText(QByteArray(key, length)); newEntry.setCommand(command); _keyTranslator->replaceEntry(entry, newEntry); } void Emulation::setKeyBindings(const QString &name) { _keyTranslator = KeyboardTranslatorManager::instance()->getTranslator(name); } QString Emulation::keyBindings() const { return _keyTranslator->name(); } void Emulation::receiveChar(wchar_t c) // process application unicode input to terminal // this is a trivial scanner { c &= 0xff; switch (c) { case '\b' : _currentScreen->backspace(); break; case '\t' : _currentScreen->tab(); break; case '\n' : _currentScreen->newLine(); break; case '\r' : _currentScreen->toStartOfLine(); break; case 0x07 : emit stateSet(NOTIFYBELL); break; default : _currentScreen->displayCharacter(c); break; }; } void Emulation::sendKeyEvent(QKeyEvent *ev) { emit stateSet(NOTIFYNORMAL); if (!ev->text().isEmpty()) { // A block of text // Note that the text is proper unicode. // We should do a conversion here emit sendData(ev->text().toUtf8().constData(), ev->text().length()); } } void Emulation::sendString(const char *, int) { // default implementation does nothing } void Emulation::sendMouseEvent(int /*buttons*/, int /*column*/, int /*row*/, int /*eventType*/) { // default implementation does nothing } /* We are doing code conversion from locale to unicode first. TODO: Character composition from the old code. See #96536 */ void Emulation::receiveData(const char *text, int length) { emit stateSet(NOTIFYACTIVITY); bufferedUpdate(); /* XXX: the following code involves encoding & decoding of "UTF-16 * surrogate pairs", which does not work with characters higher than * U+10FFFF * https://unicodebook.readthedocs.io/unicode_encodings.html#surrogates */ QString utf16Text = _decoder->toUnicode(text, length); /******** Add by wangliang 2020-07-09 解决bug 22619:当shell名称较长时,鼠标拖动窗口大小会出现shell名称显示重复现象 Begin ***************/ // int maxPathDepth = 1; // bool bWindowResizing = false; // QList allSession = SessionManager::instance()->sessions(); // for (int i = 0; i < allSession.size(); ++i) { // Session *session = allSession.at(i); // int currSessionId = session->sessionId(); // //遍历所有Session, 如果有一个控件正在resize,则标记为窗口整体正在resize // if (SessionManager::instance()->isTerminalResizing(currSessionId)) { // bWindowResizing = true; // } // //获取所有Session中shell提示符路径最长的那个对应路径的路径深度 // int currPathDepth = SessionManager::instance()->getTerminalPathDepth(currSessionId); // if (currPathDepth >= maxPathDepth) { // maxPathDepth = currPathDepth; // } // } // //判断是bash发送过来的提示符数据[utf16Text.startsWith("\r\u001B[K\u001B")], 且当前正在调整窗口大小resizing时,才进行下面的处理 // if (utf16Text.length() > 0 && utf16Text.startsWith("\r\u001B[K\u001B") && bWindowResizing) { // //用于后面构造使用的转移字符,主要是通过对比bash5.0.3和bash4.4.x版本接收到的utf16Text差异得到 // QString codeLine = "\u001B[A"; // int pathDepth = utf16Text.count("/"); // //存储终端控件当前shell提示符的路径深度(比如/home/test 路径深度为2) // SessionManager::instance()->setTerminalPathDepth(_sessionId, pathDepth); // //取shell提示符路最大的那个路径深度 // if (pathDepth < maxPathDepth) { // pathDepth = maxPathDepth; // } // //发现了一个规律,路径深度越深,需要加入的\u001B[A越多才能够较好清除重复的shell提示符 // QString insertCode = codeLine; // if (pathDepth > 0) { // int codeLineCount = pathDepth; // for (int i=0; i 3) && (strncmp(text + i + 1, "B00", 3) == 0)) emit zmodemDetected(); } } } //OLDER VERSION //This version of onRcvBlock was commented out because // a) It decoded incoming characters one-by-one, which is slow in the current version of Qt (4.2 tech preview) // b) It messed up decoding of non-ASCII characters, with the result that (for example) chinese characters // were not printed properly. // //There is something about stopping the _decoder if "we get a control code halfway a multi-byte sequence" (see below) //which hasn't been ported into the newer function (above). Hopefully someone who understands this better //can find an alternative way of handling the check. /*void Emulation::onRcvBlock(const char *s, int len) { emit notifySessionState(NOTIFYACTIVITY); bufferedUpdate(); for (int i = 0; i < len; i++) { QString result = _decoder->toUnicode(&s[i],1); int reslen = result.length(); // If we get a control code halfway a multi-byte sequence // we flush the _decoder and continue with the control code. if ((s[i] < 32) && (s[i] > 0)) { // Flush _decoder while(!result.length()) result = _decoder->toUnicode(&s[i],1); reslen = 1; result.resize(reslen); result[0] = QChar(s[i]); } for (int j = 0; j < reslen; j++) { if (result[j].characterategory() == QChar::Mark_NonSpacing) _currentScreen->compose(result.mid(j,1)); else onRcvChar(result[j].unicode()); } if (s[i] == '\030') { if ((len-i-1 > 3) && (strncmp(s+i+1, "B00", 3) == 0)) emit zmodemDetected(); } } }*/ void Emulation::writeToStream(TerminalCharacterDecoder *_decoder, int startLine, int endLine) { _currentScreen->writeLinesToStream(_decoder, startLine, endLine); } int Emulation::lineCount() const { // sum number of lines currently on _screen plus number of lines in history return _currentScreen->getLines() + _currentScreen->getHistLines(); } #define BULK_TIMEOUT1 10 #define BULK_TIMEOUT2 40 void Emulation::showBulk() { _bulkTimer1.stop(); _bulkTimer2.stop(); emit outputChanged(); _currentScreen->resetScrolledLines(); _currentScreen->resetDroppedLines(); } void Emulation::bufferedUpdate() { _bulkTimer1.setSingleShot(true); _bulkTimer1.start(BULK_TIMEOUT1); if (!_bulkTimer2.isActive()) { _bulkTimer2.setSingleShot(true); _bulkTimer2.start(BULK_TIMEOUT2); } } char Emulation::eraseChar() const { return '\b'; } void Emulation::setImageSize(int lines, int columns) { if ((lines < 1) || (columns < 1)) return; QSize screenSize[2] = { QSize(_screen[0]->getColumns(), _screen[0]->getLines()), QSize(_screen[1]->getColumns(), _screen[1]->getLines()) }; QSize newSize(columns, lines); if (newSize == screenSize[0] && newSize == screenSize[1]) return; _screen[0]->resizeImage(lines, columns); _screen[1]->resizeImage(lines, columns); emit imageSizeChanged(lines, columns); bufferedUpdate(); } QSize Emulation::imageSize() const { return {_currentScreen->getColumns(), _currentScreen->getLines()}; } ushort ExtendedCharTable::extendedCharHash(ushort *unicodePoints, ushort length) const { ushort hash = 0; for (ushort i = 0 ; i < length ; i++) { hash = 31 * hash + unicodePoints[i]; } return hash; } bool ExtendedCharTable::extendedCharMatch(ushort hash, ushort *unicodePoints, ushort length) const { ushort *entry = extendedCharTable[hash]; // compare given length with stored sequence length ( given as the first ushort in the // stored buffer ) if (entry == nullptr || entry[0] != length) return false; // if the lengths match, each character must be checked. the stored buffer starts at // entry[1] for (int i = 0 ; i < length ; i++) { if (entry[i + 1] != unicodePoints[i]) return false; } return true; } ushort ExtendedCharTable::createExtendedChar(ushort *unicodePoints, ushort length) { // look for this sequence of points in the table ushort hash = extendedCharHash(unicodePoints, length); // check existing entry for match while (extendedCharTable.contains(hash)) { if (extendedCharMatch(hash, unicodePoints, length)) { // this sequence already has an entry in the table, // return its hash return hash; } else { // if hash is already used by another, different sequence of unicode character // points then try next hash hash++; } } // add the new sequence to the table and // return that index ushort *buffer = new ushort[length + 1]; buffer[0] = length; for (int i = 0 ; i < length ; i++) buffer[i + 1] = unicodePoints[i]; extendedCharTable.insert(hash, buffer); return hash; } ushort *ExtendedCharTable::lookupExtendedChar(ushort hash, ushort &length) const { // lookup index in table and if found, set the length // argument and return a pointer to the character sequence ushort *buffer = extendedCharTable[hash]; if (buffer) { length = buffer[0]; return buffer + 1; } else { length = 0; return nullptr; } } ExtendedCharTable::ExtendedCharTable() { } ExtendedCharTable::~ExtendedCharTable() { // free all allocated character buffers QHashIterator iter(extendedCharTable); while (iter.hasNext()) { iter.next(); delete[] iter.value(); } } // global instance ExtendedCharTable ExtendedCharTable::instance; //#include "Emulation.moc" deepin-terminal-5.2.11/3rdparty/terminalwidget/lib/Emulation.h000066400000000000000000000453621370157770500243460ustar00rootroot00000000000000/* 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 // System #include // Qt #include //#include #include #include #include #include "qtermwidget_export.h" 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 TERMINALWIDGET_EXPORT Emulation : public QObject { Q_OBJECT public: /** * This enum describes the available shapes for the keyboard cursor. * See setKeyboardCursorShape() */ enum class KeyboardCursorShape { /** A rectangular block which covers the entire area of the cursor character. */ BlockCursor = 0, /** * A single flat line which occupies the space at the bottom of the cursor * character's area. */ UnderlineCursor = 1, /** * An cursor shaped like the capital letter 'I', similar to the IBeam * cursor used in Qt/KDE text editors. */ IBeamCursor = 2 }; /** Constructs a new terminal emulation */ Emulation(); ~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; } /** TODO Document me */ 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 wants * mouse input events. * * The programUsesMouseChanged() signal is emitted when this * changes. */ bool programUsesMouse() const; bool programBracketedPasteMode() const; /******** Modify by ut000610 daizhengwen 2020-06-02: 重新设置键盘配置****************/ void setKeyTranslator(const KeyboardTranslator *keyTranslator); /********************* Modify by ut000610 daizhengwen End ************************/ /******** Modify by ut000610 daizhengwen 2020-06-02: 设置删除和退格按钮****************/ void setBackspaceMode(char *key, int length); void setDeleteMode(char *key, int length); /********************* Modify by ut000610 daizhengwen End ************************/ //用于保存当前Emulator对应的sessionId void setSessionId(int sessionId); public 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. * @param length Length of @p string or if set to a negative value, @p string will * be treated as a null-terminated string and its length will be determined automatically. */ virtual void sendString(const char *string, int length = -1) = 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 buffer A string of characters received from the terminal program. * @param len The length of @p buffer */ void receiveData(const char *buffer, int len); 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 * @param len The length of @p data in bytes */ void sendData(const char *data, int len); /** * Requests that sending of input to the emulation * from the terminal process be suspended or resumed. * * @param suspend If true, requests that sending of * input from the terminal process' stdout be * suspended. Otherwise requests that sending of * input be resumed. */ void lockPtyRequest(bool suspend); /** * Requests that the pty used by the terminal process * be set to UTF 8 mode. * * TODO: More documentation */ 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); /** TODO Document me */ void zmodemDetected(); /** * 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 running in the shell indicates whether or * not it is interested in mouse events. * * @param usesMouse This will be true if the program wants to be informed about * mouse events or false otherwise. */ void programUsesMouseChanged(bool usesMouse); 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 the * session's title. This also allows terminal programs to customize other * aspects of the terminal emulation display. * * This signal is emitted when the escape sequence "\033]ARG;VALUE\007" * is received in the input string, where ARG is a number specifying what * should change and VALUE is a string specifying the new value. * * TODO: The name of this method is not very accurate since this method * is used to perform a whole range of tasks besides just setting * the user-title of the session. * * @param title Specifies what to change. *
    *
  • 0 - Set window icon text and session title to @p newTitle
  • *
  • 1 - Set window icon text to @p newTitle
  • *
  • 2 - Set session title to @p newTitle
  • *
  • 11 - Set the session's default background color to @p newTitle, * where @p newTitle can be an HTML-style string ("#RRGGBB") or a named * color (eg 'red', 'blue'). * See http://doc.trolltech.com/4.2/qcolor.html#setNamedColor for more * details. *
  • *
  • 31 - Supposedly treats @p newTitle as a URL and opens it (NOT IMPLEMENTED)
  • *
  • 32 - Sets the icon associated with the session. @p newTitle 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 newTitle Specifies the new title */ void titleChanged(int title, const QString &newTitle); /** * Emitted when the program running in the terminal changes the * screen size. */ 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 cursor shape or its blinking state is changed via * DECSCUSR sequences. * * @param cursorShape One of 3 possible values in KeyboardCursorShape enum * @param blinkingCursorEnabled Whether to enable blinking or not */ void cursorChanged(KeyboardCursorShape cursorShape, bool blinkingCursorEnabled); protected: virtual void setMode(int mode) = 0; virtual void resetMode(int mode) = 0; /** * Processes an incoming character. See receiveData() * @p ch A unicode character code. */ virtual void receiveChar(wchar_t ch); /** * 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); // codec number, 0 = locale, 1=utf8 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; /******** Modify by ut000610 daizhengwen 2020-06-02: 让这个值能被修改****************/ /*const */KeyboardTranslator *_keyTranslator; // the keyboard layout /********************* Modify by ut000610 daizhengwen End ************************/ protected 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(); private slots: // triggered by timer, causes the emulation to send an updated screen image to each // view void showBulk(); void usesMouseChanged(bool usesMouse); void bracketedPasteModeChanged(bool bracketedPasteMode); private: bool _usesMouse; bool _bracketedPasteMode; QTimer _bulkTimer1; QTimer _bulkTimer2; int _sessionId; }; } #endif // ifndef EMULATION_H deepin-terminal-5.2.11/3rdparty/terminalwidget/lib/ExtendedDefaultTranslator.h000066400000000000000000000102151370157770500275150ustar00rootroot00000000000000"keyboard \"Default (XFree 4)\"" "key Escape : \"\\E\"" "key Tab -Shift : \"\\t\"\n" "key Tab +Shift+Ansi : \"\\E[Z\"\n" "key Tab +Shift-Ansi : \"\\t\"\n" "key Backtab +Ansi : \"\\E[Z\"\n" "key Backtab -Ansi : \"\\t\"\n" "key Return-Shift-NewLine : \"\\r\"\n" "key Return-Shift+NewLine : \"\\r\\n\"\n" "key Return+Shift : \"\\EOM\"\n" "key Backspace : \"\\x7f\"\n" "key Up -Shift-Ansi : \"\\EA\"\n" "key Down -Shift-Ansi : \"\\EB\"\n" "key Right-Shift-Ansi : \"\\EC\"\n" "key Left -Shift-Ansi : \"\\ED\"\n" "key Up -Shift-AnyMod+Ansi+AppCuKeys : \"\\EOA\"\n" "key Down -Shift-AnyMod+Ansi+AppCuKeys : \"\\EOB\"\n" "key Right -Shift-AnyMod+Ansi+AppCuKeys : \"\\EOC\"\n" "key Left -Shift-AnyMod+Ansi+AppCuKeys : \"\\EOD\"\n" "key Up -Shift-AnyMod+Ansi-AppCuKeys : \"\\E[A\"\n" "key Down -Shift-AnyMod+Ansi-AppCuKeys : \"\\E[B\"\n" "key Right -Shift-AnyMod+Ansi-AppCuKeys : \"\\E[C\"\n" "key Left -Shift-AnyMod+Ansi-AppCuKeys : \"\\E[D\"\n" "key Up -Shift+AnyMod+Ansi : \"\\E[1;*A\"\n" "key Down -Shift+AnyMod+Ansi : \"\\E[1;*B\"\n" "key Right -Shift+AnyMod+Ansi : \"\\E[1;*C\"\n" "key Left -Shift+AnyMod+Ansi : \"\\E[1;*D\"\n" "key Enter+NewLine : \"\\r\\n\"\n" "key Enter-NewLine : \"\\r\"\n" "key Home -AnyMod -AppCuKeys : \"\\E[H\" \n" "key End -AnyMod -AppCuKeys : \"\\E[F\" \n" "key Home -AnyMod +AppCuKeys : \"\\EOH\" \n" "key End -AnyMod +AppCuKeys : \"\\EOF\" \n" "key Home +AnyMod : \"\\E[1;*H\"\n" "key End +AnyMod : \"\\E[1;*F\"\n" "key Insert -AnyMod : \"\\E[2~\"\n" "key Delete -AnyMod : \"\\E[3~\"\n" "key Insert +AnyMod : \"\\E[2;*~\"\n" "key Delete +AnyMod : \"\\E[3;*~\"\n" "key Prior -Shift-AnyMod : \"\\E[5~\"\n" "key Next -Shift-AnyMod : \"\\E[6~\"\n" "key Prior -Shift+AnyMod : \"\\E[5;*~\"\n" "key Next -Shift+AnyMod : \"\\E[6;*~\"\n" "key F1 -AnyMod : \"\\EOP\"\n" "key F2 -AnyMod : \"\\EOQ\"\n" "key F3 -AnyMod : \"\\EOR\"\n" "key F4 -AnyMod : \"\\EOS\"\n" "key F5 -AnyMod : \"\\E[15~\"\n" "key F6 -AnyMod : \"\\E[17~\"\n" "key F7 -AnyMod : \"\\E[18~\"\n" "key F8 -AnyMod : \"\\E[19~\"\n" "key F9 -AnyMod : \"\\E[20~\"\n" "key F10 -AnyMod : \"\\E[21~\"\n" "key F11 -AnyMod : \"\\E[23~\"\n" "key F12 -AnyMod : \"\\E[24~\"\n" "key F1 +AnyMod : \"\\EO*P\"\n" "key F2 +AnyMod : \"\\EO*Q\"\n" "key F3 +AnyMod : \"\\EO*R\"\n" "key F4 +AnyMod : \"\\EO*S\"\n" "key F5 +AnyMod : \"\\E[15;*~\"\n" "key F6 +AnyMod : \"\\E[17;*~\"\n" "key F7 +AnyMod : \"\\E[18;*~\"\n" "key F8 +AnyMod : \"\\E[19;*~\"\n" "key F9 +AnyMod : \"\\E[20;*~\"\n" "key F10 +AnyMod : \"\\E[21;*~\"\n" "key F11 +AnyMod : \"\\E[23;*~\"\n" "key F12 +AnyMod : \"\\E[24;*~\"\n" "key Space +Control : \"\\x00\"\n" "key Up +Shift-AppScreen : scrollLineUp\n" "key Prior +Shift-AppScreen : scrollPageUp\n" "key Down +Shift-AppScreen : scrollLineDown\n" "key Next +Shift-AppScreen : scrollPageDown\n" "key ScrollLock : scrollLock\n" "\0" deepin-terminal-5.2.11/3rdparty/terminalwidget/lib/Filter.cpp000066400000000000000000000401401370157770500241560ustar00rootroot00000000000000/* 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. */ // Own #include "Filter.h" #include "SessionManager.h" // System #include // Qt #include #include #include #include #include #include #include #include #include #include // KDE //#include //#include // Konsole #include "TerminalCharacterDecoder.h" #include "konsole_wcwidth.h" using namespace Konsole; FilterChain::~FilterChain() { QMutableListIterator iter(*this); while (iter.hasNext()) { Filter *filter = iter.next(); iter.remove(); delete filter; } } void FilterChain::addFilter(Filter *filter) { append(filter); } void FilterChain::removeFilter(Filter *filter) { removeAll(filter); } bool FilterChain::containsFilter(Filter *filter) { return contains(filter); } void FilterChain::reset() { QListIterator iter(*this); while (iter.hasNext()) iter.next()->reset(); } void FilterChain::setBuffer(const QString *buffer, const QList *linePositions) { QListIterator iter(*this); while (iter.hasNext()) iter.next()->setBuffer(buffer, linePositions); } void FilterChain::process() { QListIterator iter(*this); while (iter.hasNext()) iter.next()->process(); } void FilterChain::clear() { QList::clear(); } Filter::HotSpot *FilterChain::hotSpotAt(int line, int column) const { QListIterator iter(*this); while (iter.hasNext()) { Filter *filter = iter.next(); Filter::HotSpot *spot = filter->hotSpotAt(line, column); if (spot != nullptr) { return spot; } } return nullptr; } QList FilterChain::hotSpots() const { QList list; QListIterator iter(*this); while (iter.hasNext()) { Filter *filter = iter.next(); list << filter->hotSpots(); } return list; } //QList FilterChain::hotSpotsAtLine(int line) const; void FilterChain::setSessionId(int sessionId) { _sessionId = sessionId; } TerminalImageFilterChain::TerminalImageFilterChain() : _buffer(nullptr) , _linePositions(nullptr) { } TerminalImageFilterChain::~TerminalImageFilterChain() { delete _buffer; delete _linePositions; } //判断是否包含>=两种类型的提示符结尾字符(比如: root@zhangsan-PC# echo $ XXXXX 这种情况) //防止截取shell提示符出错,比如将'root@zhangsan-PC# echo $ XXXXX'中的'root@zhangsan-PC# echo '截取出来当作提示符 bool isContainOtherPromptEnd(QString promptLine, QString currPromptEnd) { //四不同类型的提示符结尾字符 QString promptEnds = QString("$#%>"); promptEnds.remove(currPromptEnd); for (int i=0; i &lineProperties) { if (empty()) return; // reset all filters and hotspots reset(); PlainTextDecoder decoder; decoder.setTrailingWhitespace(false); // setup new shared buffers for the filters to process on QString *newBuffer = new QString(); QList *newLinePositions = new QList(); setBuffer(newBuffer, newLinePositions); // free the old buffers delete _buffer; delete _linePositions; _buffer = newBuffer; _linePositions = newLinePositions; QTextStream lineStream(_buffer); decoder.begin(&lineStream); QString lastLine = ""; for (int i = 0 ; i < lines ; i++) { _linePositions->append(_buffer->length()); decoder.decodeLine(image + i * columns, columns, LINE_DEFAULT); // pretend that each line ends with a newline character. // this prevents a link that occurs at the end of one line // being treated as part of a link that occurs at the start of the next line // // the downside is that links which are spread over more than one line are not // highlighted. // // TODO - Use the "line wrapped" attribute associated with lines in a // terminal image to avoid adding this imaginary character for wrapped // lines if (!(lineProperties.value(i, LINE_DEFAULT) & LINE_WRAPPED)) lineStream << QLatin1Char('\n'); QString tempLine = lineStream.readAll().trimmed(); if (tempLine.length() > 0) { lastLine = tempLine; } } decoder.end(); /* fix bug 33638 使用sudo apt-get install csh ksh zsh tcsh安装其它shell后,执行卸载终端未弹出卸载弹框 */ if (lastLine.length() > 0) { //优化了截取并保存当前shell提示符的判断,暂时没有考虑PS1被修改的情况(若考虑的话实现起来太复杂) //目前针对sh/bash/csh/tcsh/ksh/zsh这几种类型的shell做了处理 QString promptEnds = QString("$#%>"); for (int i=0; isaveCurrShellPrompt(_sessionId, lastLine); break; } } } QString strShellPrompt = SessionManager::instance()->getCurrShellPrompt(_sessionId); bool isRootUser = strShellPrompt.endsWith("#"); QString strCurrBuffer = (*_buffer).trimmed(); if (strCurrBuffer.length() > 0) { //获取并保存当前正在输入的命令 if (isRootUser) { QString strCommand = strCurrBuffer.split(strShellPrompt).last(); if (!strCommand.contains("sudo ")) { strCommand = QString("sudo %1").arg(strCommand); } SessionManager::instance()->saveCurrShellCommand(_sessionId, strCommand); } else { QString strCommand = strCurrBuffer.split(strShellPrompt).last(); SessionManager::instance()->saveCurrShellCommand(_sessionId, strCommand); } } } Filter::Filter() : _linePositions(nullptr), _buffer(nullptr) { } Filter::~Filter() { qDeleteAll(_hotspotList); _hotspotList.clear(); } void Filter::reset() { qDeleteAll(_hotspotList); _hotspots.clear(); _hotspotList.clear(); } void Filter::setBuffer(const QString *buffer, const QList *linePositions) { _buffer = buffer; _linePositions = linePositions; } void Filter::getLineColumn(int position, int &startLine, int &startColumn) { Q_ASSERT(_linePositions); Q_ASSERT(_buffer); for (int i = 0 ; i < _linePositions->count() ; i++) { int nextLine = 0; if (i == _linePositions->count() - 1) nextLine = _buffer->length() + 1; else nextLine = _linePositions->value(i + 1); if (_linePositions->value(i) <= position && position < nextLine) { startLine = i; startColumn = string_width(buffer()->mid(_linePositions->value(i), position - _linePositions->value(i)).toStdWString()); return; } } } /*void Filter::addLine(const QString& text) { _linePositions << _buffer.length(); _buffer.append(text); }*/ const QString *Filter::buffer() { return _buffer; } Filter::HotSpot::~HotSpot() { } void Filter::addHotSpot(HotSpot *spot) { _hotspotList << spot; for (int line = spot->startLine() ; line <= spot->endLine() ; line++) { _hotspots.insert(line, spot); } } QList Filter::hotSpots() const { return _hotspotList; } QList Filter::hotSpotsAtLine(int line) const { return _hotspots.values(line); } Filter::HotSpot *Filter::hotSpotAt(int line, int column) const { QListIterator spotIter(_hotspots.values(line)); while (spotIter.hasNext()) { HotSpot *spot = spotIter.next(); if (spot->startLine() == line && spot->startColumn() > column) continue; if (spot->endLine() == line && spot->endColumn() < column) continue; return spot; } return nullptr; } Filter::HotSpot::HotSpot(int startLine, int startColumn, int endLine, int endColumn) : _startLine(startLine) , _startColumn(startColumn) , _endLine(endLine) , _endColumn(endColumn) , _type(NotSpecified) { } QList Filter::HotSpot::actions() { return QList(); } int Filter::HotSpot::startLine() const { return _startLine; } int Filter::HotSpot::endLine() const { return _endLine; } int Filter::HotSpot::startColumn() const { return _startColumn; } int Filter::HotSpot::endColumn() const { return _endColumn; } Filter::HotSpot::Type Filter::HotSpot::type() const { return _type; } void Filter::HotSpot::setType(Type type) { _type = type; } RegExpFilter::RegExpFilter() { } RegExpFilter::HotSpot::HotSpot(int startLine, int startColumn, int endLine, int endColumn) : Filter::HotSpot(startLine, startColumn, endLine, endColumn) { setType(Marker); } void RegExpFilter::HotSpot::activate(const QString &) { } void RegExpFilter::HotSpot::setCapturedTexts(const QStringList &texts) { _capturedTexts = texts; } QStringList RegExpFilter::HotSpot::capturedTexts() const { return _capturedTexts; } void RegExpFilter::setRegExp(const QRegExp ®Exp) { _searchText = regExp; } QRegExp RegExpFilter::regExp() const { return _searchText; } /*void RegExpFilter::reset(int) { _buffer = QString(); }*/ void RegExpFilter::process() { int pos = 0; const QString *text = buffer(); Q_ASSERT(text); // ignore any regular expressions which match an empty string. // otherwise the while loop below will run indefinitely static const QString emptyString; if (_searchText.exactMatch(emptyString)) return; while (pos >= 0) { pos = _searchText.indexIn(*text, pos); if (pos >= 0) { int startLine = 0; int endLine = 0; int startColumn = 0; int endColumn = 0; getLineColumn(pos, startLine, startColumn); getLineColumn(pos + _searchText.matchedLength(), endLine, endColumn); RegExpFilter::HotSpot *spot = newHotSpot(startLine, startColumn, endLine, endColumn); spot->setCapturedTexts(_searchText.capturedTexts()); addHotSpot(spot); pos += _searchText.matchedLength(); // if matchedLength == 0, the program will get stuck in an infinite loop if (_searchText.matchedLength() == 0) pos = -1; } } } RegExpFilter::HotSpot *RegExpFilter::newHotSpot(int startLine, int startColumn, int endLine, int endColumn) { return new RegExpFilter::HotSpot(startLine, startColumn, endLine, endColumn); } RegExpFilter::HotSpot *UrlFilter::newHotSpot(int startLine, int startColumn, int endLine, int endColumn) { HotSpot *spot = new UrlFilter::HotSpot(startLine, startColumn, endLine, endColumn); connect(spot->getUrlObject(), &FilterObject::activated, this, &UrlFilter::activated); return spot; } UrlFilter::HotSpot::HotSpot(int startLine, int startColumn, int endLine, int endColumn) : RegExpFilter::HotSpot(startLine, startColumn, endLine, endColumn) , _urlObject(new FilterObject(this)) { setType(Link); } UrlFilter::HotSpot::UrlType UrlFilter::HotSpot::urlType() const { QString url = capturedTexts().constFirst(); if (FullUrlRegExp.exactMatch(url)) return StandardUrl; else if (EmailAddressRegExp.exactMatch(url)) return Email; else return Unknown; } void UrlFilter::HotSpot::activate(const QString &actionName) { QString url = capturedTexts().constFirst(); const UrlType kind = urlType(); if (actionName == QLatin1String("copy-action")) { QApplication::clipboard()->setText(url); return; } if (actionName.isEmpty() || actionName == QLatin1String("open-action") || actionName == QLatin1String("click-action")) { if (kind == StandardUrl) { // if the URL path does not include the protocol ( eg. "www.kde.org" ) then // prepend http:// ( eg. "www.kde.org" --> "http://www.kde.org" ) if (!url.contains(QLatin1String("://"))) { url.prepend(QLatin1String("http://")); } } else if (kind == Email) { url.prepend(QLatin1String("mailto:")); } _urlObject->emitActivated(QUrl(url, QUrl::StrictMode), actionName != QLatin1String("click-action")); } } // Note: Altering these regular expressions can have a major effect on the performance of the filters // used for finding URLs in the text, especially if they are very general and could match very long // pieces of text. // Please be careful when altering them. //regexp matches: // full url: // protocolname:// or www. followed by anything other than whitespaces, <, >, ' or ", and ends before whitespaces, <, >, ', ", ], !, comma and dot const QRegExp UrlFilter::FullUrlRegExp(QLatin1String("(www\\.(?!\\.)|[a-z][a-z0-9+.-]*://)[^\\s<>'\"]+[^!,\\.\\s<>'\"\\]]")); // email address: // [word chars, dots or dashes]@[word chars, dots or dashes].[word chars] const QRegExp UrlFilter::EmailAddressRegExp(QLatin1String("\\b(\\w|\\.|-)+@(\\w|\\.|-)+\\.\\w+\\b")); // matches full url or email address const QRegExp UrlFilter::CompleteUrlRegExp(QLatin1Char('(') + FullUrlRegExp.pattern() + QLatin1Char('|') + EmailAddressRegExp.pattern() + QLatin1Char(')')); UrlFilter::UrlFilter() { setRegExp(CompleteUrlRegExp); } UrlFilter::HotSpot::~HotSpot() { delete _urlObject; } void FilterObject::emitActivated(const QUrl &url, bool fromContextMenu) { emit activated(url, fromContextMenu); } void FilterObject::activate() { _filter->activate(sender()->objectName()); } FilterObject *UrlFilter::HotSpot::getUrlObject() const { return _urlObject; } QList UrlFilter::HotSpot::actions() { QList list; const UrlType kind = urlType(); QAction *openAction = new QAction(_urlObject); QAction *copyAction = new QAction(_urlObject);; Q_ASSERT(kind == StandardUrl || kind == Email); if (kind == StandardUrl) { openAction->setText(QObject::tr("Open link")); copyAction->setText(QObject::tr("Copy link")); } else if (kind == Email) { openAction->setText(QObject::tr("Send email to...")); copyAction->setText(QObject::tr("Copy email address")); } // object names are set here so that the hotspot performs the // correct action when activated() is called with the triggered // action passed as a parameter. openAction->setObjectName(QLatin1String("open-action")); copyAction->setObjectName(QLatin1String("copy-action")); QObject::connect(openAction, &QAction::triggered, _urlObject, &FilterObject::activate); QObject::connect(copyAction, &QAction::triggered, _urlObject, &FilterObject::activate); list << openAction; list << copyAction; return list; } //#include "Filter.moc" deepin-terminal-5.2.11/3rdparty/terminalwidget/lib/Filter.h000066400000000000000000000325021370157770500236260ustar00rootroot00000000000000/* 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 // Local #include "qtermwidget_export.h" namespace Konsole { typedef unsigned char LineProperty; class Character; /** * 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 TERMINALWIDGET_EXPORT Filter : public QObject { 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 an action associated with a hotspot to be triggered. * * @param action The action to trigger. This is * typically empty ( in which case the default action should be performed ) or * one of the object names from the actions() list. In which case the associated * action should be performed. */ virtual void activate(const QString &action = QString()) = 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(); ~Filter() override; /** 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(); /** Adds a new line of text to the filter and increments the line count */ //void addLine(const QString& string); /** 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 */ QList hotSpotsAtLine(int line) const; /** * 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: 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 TERMINALWIDGET_EXPORT 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); void activate(const QString &action = QString()) override; /** Sets the captured texts associated with this hotspot */ void setCapturedTexts(const QStringList &texts); /** 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 QRegExp &text); /** Returns the regular expression which the filter searches for in blocks of text */ QRegExp 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() 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); private: QRegExp _searchText; }; class FilterObject; /** A filter which matches URLs in blocks of text */ class TERMINALWIDGET_EXPORT UrlFilter : public RegExpFilter { Q_OBJECT 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); ~HotSpot() override; FilterObject *getUrlObject() const; QList actions() override; /** * Open a web browser at the current URL. The url itself can be determined using * the capturedTexts() method. */ void activate(const QString &action = QString()) override; private: enum UrlType { StandardUrl, Email, Unknown }; UrlType urlType() const; FilterObject *_urlObject; }; UrlFilter(); protected: RegExpFilter::HotSpot *newHotSpot(int, int, int, int) override; private: static const QRegExp FullUrlRegExp; static const QRegExp EmailAddressRegExp; // combined OR of FullUrlRegExp and EmailAddressRegExp static const QRegExp CompleteUrlRegExp; signals: void activated(const QUrl &url, bool fromContextMenu); }; class TERMINALWIDGET_EXPORT FilterObject : public QObject { Q_OBJECT public: FilterObject(Filter::HotSpot *filter) : _filter(filter) {} void emitActivated(const QUrl &url, bool fromContextMenu); public slots: void activate(); private: Filter::HotSpot *_filter; signals: void activated(const QUrl &url, bool fromContextMenu); }; /** * 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() and hotSpotsAtLine() method return all of the hotspots in the text and on * a given line respectively. */ class TERMINALWIDGET_EXPORT 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); /** Returns true if the chain contains @p filter */ bool containsFilter(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; /** Returns a list of all hotspots at the given line in all the chain's filters */ QList hotSpotsAtLine(int line) const; void setSessionId(int sessionId); protected: int _sessionId; }; /** A filter chain which processes character images from terminal displays */ class TERMINALWIDGET_EXPORT TerminalImageFilterChain : public FilterChain { public: TerminalImageFilterChain(); ~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: QString *_buffer; QList *_linePositions; }; } typedef Konsole::Filter Filter; #endif //FILTER_H deepin-terminal-5.2.11/3rdparty/terminalwidget/lib/History.cpp000066400000000000000000000553361370157770500244070ustar00rootroot00000000000000/* 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. */ // Own #include "History.h" // System #include #include #include #include #include #include #include #include #include // KDE //#include //#include // Reasonable line size #define LINE_SIZE 1024 #define KDE_lseek lseek using namespace Konsole; /* An arbitrary long scroll. One can modify the scroll only by adding either cells or newlines, but access it randomly. The model is that of an arbitrary wide typewriter scroll in that the scroll is a serie of lines and each line is a serie of cells with no overwriting permitted. The implementation provides arbitrary length and numbers of cells and line/column indexed read access to the scroll at constant costs. KDE4: Can we use QTemporaryFile here, instead of KTempFile? FIXME: some complain about the history buffer comsuming the memory of their machines. This problem is critical since the history does not behave gracefully in cases where the memory is used up completely. I put in a workaround that should handle it problem now gracefully. I'm not satisfied with the solution. FIXME: Terminating the history is not properly indicated in the menu. We should throw a signal. FIXME: There is noticeable decrease in speed, also. Perhaps, there whole feature needs to be revisited therefore. Disadvantage of a more elaborated, say block-oriented scheme with wrap around would be it's complexity. */ //FIXME: tempory replacement for tmpfile // this is here one for debugging purpose. //#define tmpfile xTmpFile // History File /////////////////////////////////////////// /* A Row(X) data type which allows adding elements to the end. */ HistoryFile::HistoryFile() : ion(-1), length(0), fileMap(nullptr) { if (tmpFile.open()) { tmpFile.setAutoRemove(true); ion = tmpFile.handle(); } } HistoryFile::~HistoryFile() { if (fileMap) unmap(); } //TODO: Mapping the entire file in will cause problems if the history file becomes exceedingly large, //(ie. larger than available memory). HistoryFile::map() should only map in sections of the file at a time, //to avoid this. void HistoryFile::map() { Q_ASSERT( fileMap == nullptr ); fileMap = (char*)mmap( nullptr , length , PROT_READ , MAP_PRIVATE , ion , 0 ); //if mmap'ing fails, fall back to the read-lseek combination if ( fileMap == MAP_FAILED ) { readWriteBalance = 0; fileMap = nullptr; //qDebug() << __FILE__ << __LINE__ << ": mmap'ing history failed. errno = " << errno; } } void HistoryFile::unmap() { int result = munmap( fileMap , length ); Q_ASSERT( result == 0 ); Q_UNUSED( result ); fileMap = nullptr; } bool HistoryFile::isMapped() const { return (fileMap != nullptr); } void HistoryFile::add(const unsigned char* bytes, int len) { if ( fileMap ) unmap(); readWriteBalance++; int rc = 0; rc = KDE_lseek(ion,length,SEEK_SET); if (rc < 0) { perror("HistoryFile::add.seek"); return; } rc = write(ion,bytes,len); if (rc < 0) { perror("HistoryFile::add.write"); return; } length += rc; } void HistoryFile::get(unsigned char* bytes, int len, int loc) { //count number of get() calls vs. number of add() calls. //If there are many more get() calls compared with add() //calls (decided by using MAP_THRESHOLD) then mmap the log //file to improve performance. readWriteBalance--; if ( !fileMap && readWriteBalance < MAP_THRESHOLD ) map(); if ( fileMap ) { for (int i=0;i length) fprintf(stderr,"getHist(...,%d,%d): invalid args.\n",len,loc); rc = KDE_lseek(ion,loc,SEEK_SET); if (rc < 0) { perror("HistoryFile::get.seek"); return; } rc = read(ion,bytes,len); if (rc < 0) { perror("HistoryFile::get.read"); return; } } } int HistoryFile::len() { return length; } // History Scroll abstract base class ////////////////////////////////////// HistoryScroll::HistoryScroll(HistoryType* t) : m_histType(t) { } HistoryScroll::~HistoryScroll() { delete m_histType; } bool HistoryScroll::hasScroll() { return true; } // History Scroll File ////////////////////////////////////// /* The history scroll makes a Row(Row(Cell)) from two history buffers. The index buffer contains start of line positions which refere to the cells buffer. Note that index[0] addresses the second line (line #1), while the first line (line #0) starts at 0 in cells. */ HistoryScrollFile::HistoryScrollFile(const QString &logFileName) : HistoryScroll(new HistoryTypeFile(logFileName)), m_logFileName(logFileName) { } HistoryScrollFile::~HistoryScrollFile() { } int HistoryScrollFile::getLines() { return index.len() / sizeof(int); } int HistoryScrollFile::getLineLen(int lineno) { return (startOfLine(lineno+1) - startOfLine(lineno)) / sizeof(Character); } bool HistoryScrollFile::isWrappedLine(int lineno) { if (lineno>=0 && lineno <= getLines()) { unsigned char flag; lineflags.get((unsigned char*)&flag,sizeof(unsigned char),(lineno)*sizeof(unsigned char)); return flag; } return false; } int HistoryScrollFile::startOfLine(int lineno) { if (lineno <= 0) return 0; if (lineno <= getLines()) { if (!index.isMapped()) index.map(); int res; index.get((unsigned char*)&res,sizeof(int),(lineno-1)*sizeof(int)); return res; } return cells.len(); } void HistoryScrollFile::getCells(int lineno, int colno, int count, Character res[]) { cells.get((unsigned char*)res,count*sizeof(Character),startOfLine(lineno)+colno*sizeof(Character)); } void HistoryScrollFile::addCells(const Character text[], int count) { cells.add((unsigned char*)text,count*sizeof(Character)); } void HistoryScrollFile::addLine(bool previousWrapped) { if (index.isMapped()) index.unmap(); int locn = cells.len(); index.add((unsigned char*)&locn,sizeof(int)); unsigned char flags = previousWrapped ? 0x01 : 0x00; lineflags.add((unsigned char*)&flags,sizeof(unsigned char)); } // History Scroll Buffer ////////////////////////////////////// HistoryScrollBuffer::HistoryScrollBuffer(unsigned int maxLineCount) : HistoryScroll(new HistoryTypeBuffer(maxLineCount)) ,_historyBuffer() ,_maxLineCount(0) ,_usedLines(0) ,_head(0) { setMaxNbLines(maxLineCount); } HistoryScrollBuffer::~HistoryScrollBuffer() { delete[] _historyBuffer; } void HistoryScrollBuffer::addCellsVector(const QVector& cells) { _head++; if ( _usedLines < _maxLineCount ) _usedLines++; if ( _head >= _maxLineCount ) { _head = 0; } _historyBuffer[bufferIndex(_usedLines-1)] = cells; _wrappedLine[bufferIndex(_usedLines-1)] = false; } void HistoryScrollBuffer::addCells(const Character a[], int count) { HistoryLine newLine(count); std::copy(a,a+count,newLine.begin()); addCellsVector(newLine); } void HistoryScrollBuffer::addLine(bool previousWrapped) { _wrappedLine[bufferIndex(_usedLines-1)] = previousWrapped; } int HistoryScrollBuffer::getLines() { return _usedLines; } int HistoryScrollBuffer::getLineLen(int lineNumber) { Q_ASSERT( lineNumber >= 0 && lineNumber < _maxLineCount ); if ( lineNumber < _usedLines ) { return _historyBuffer[bufferIndex(lineNumber)].size(); } else { return 0; } } bool HistoryScrollBuffer::isWrappedLine(int lineNumber) { Q_ASSERT( lineNumber >= 0 && lineNumber < _maxLineCount ); if (lineNumber < _usedLines) { //kDebug() << "Line" << lineNumber << "wrapped is" << _wrappedLine[bufferIndex(lineNumber)]; return _wrappedLine[bufferIndex(lineNumber)]; } else return false; } void HistoryScrollBuffer::getCells(int lineNumber, int startColumn, int count, Character buffer[]) { if ( count == 0 ) return; Q_ASSERT( lineNumber < _maxLineCount ); if (lineNumber >= _usedLines) { memset(static_cast(buffer), 0, count * sizeof(Character)); return; } const HistoryLine& line = _historyBuffer[bufferIndex(lineNumber)]; //kDebug() << "startCol " << startColumn; //kDebug() << "line.size() " << line.size(); //kDebug() << "count " << count; Q_ASSERT( startColumn <= line.size() - count ); memcpy(buffer, line.constData() + startColumn , count * sizeof(Character)); } void HistoryScrollBuffer::setMaxNbLines(unsigned int lineCount) { HistoryLine* oldBuffer = _historyBuffer; HistoryLine* newBuffer = new HistoryLine[lineCount]; for ( int i = 0 ; i < qMin(_usedLines,(int)lineCount) ; i++ ) { newBuffer[i] = oldBuffer[bufferIndex(i)]; } _usedLines = qMin(_usedLines,(int)lineCount); _maxLineCount = lineCount; _head = ( _usedLines == _maxLineCount ) ? 0 : _usedLines-1; _historyBuffer = newBuffer; delete[] oldBuffer; _wrappedLine.resize(lineCount); dynamic_cast(m_histType)->m_nbLines = lineCount; } int HistoryScrollBuffer::bufferIndex(int lineNumber) { Q_ASSERT( lineNumber >= 0 ); Q_ASSERT( lineNumber < _maxLineCount ); Q_ASSERT( (_usedLines == _maxLineCount) || lineNumber <= _head ); if ( _usedLines == _maxLineCount ) { return (_head+lineNumber+1) % _maxLineCount; } else { return lineNumber; } } // History Scroll None ////////////////////////////////////// HistoryScrollNone::HistoryScrollNone() : HistoryScroll(new HistoryTypeNone()) { } HistoryScrollNone::~HistoryScrollNone() { } bool HistoryScrollNone::hasScroll() { return false; } int HistoryScrollNone::getLines() { return 0; } int HistoryScrollNone::getLineLen(int) { return 0; } bool HistoryScrollNone::isWrappedLine(int /*lineno*/) { return false; } void HistoryScrollNone::getCells(int, int, int, Character []) { } void HistoryScrollNone::addCells(const Character [], int) { } void HistoryScrollNone::addLine(bool) { } // History Scroll BlockArray ////////////////////////////////////// HistoryScrollBlockArray::HistoryScrollBlockArray(size_t size) : HistoryScroll(new HistoryTypeBlockArray(size)) { m_blockArray.setHistorySize(size); // nb. of lines. } HistoryScrollBlockArray::~HistoryScrollBlockArray() { } int HistoryScrollBlockArray::getLines() { return m_lineLengths.count(); } int HistoryScrollBlockArray::getLineLen(int lineno) { if ( m_lineLengths.contains(lineno) ) return m_lineLengths[lineno]; else return 0; } bool HistoryScrollBlockArray::isWrappedLine(int /*lineno*/) { return false; } void HistoryScrollBlockArray::getCells(int lineno, int colno, int count, Character res[]) { if (!count) return; const Block *b = m_blockArray.at(lineno); if (!b) { memset(static_cast(res), 0, count * sizeof(Character)); // still better than random data return; } Q_ASSERT(((colno + count) * sizeof(Character)) < ENTRIES); memcpy(res, b->data + (colno * sizeof(Character)), count * sizeof(Character)); } void HistoryScrollBlockArray::addCells(const Character a[], int count) { Block *b = m_blockArray.lastBlock(); if (!b) return; // put cells in block's data Q_ASSERT((count * sizeof(Character)) < ENTRIES); memset(b->data, 0, sizeof(b->data)); memcpy(b->data, a, count * sizeof(Character)); b->size = count * sizeof(Character); size_t res = m_blockArray.newBlock(); Q_ASSERT(res > 0); Q_UNUSED( res ); m_lineLengths.insert(m_blockArray.getCurrent(), count); } void HistoryScrollBlockArray::addLine(bool) { } //////////////////////////////////////////////////////////////// // Compact History Scroll ////////////////////////////////////// //////////////////////////////////////////////////////////////// void* CompactHistoryBlock::allocate ( size_t length ) { Q_ASSERT ( length > 0 ); if ( tail-blockStart+length > blockLength ) return nullptr; void* block = tail; tail += length; //kDebug() << "allocated " << length << " bytes at address " << block; allocCount++; return block; } void CompactHistoryBlock::deallocate ( ) { allocCount--; Q_ASSERT ( allocCount >= 0 ); } void* CompactHistoryBlockList::allocate(size_t size) { CompactHistoryBlock* block; if ( list.isEmpty() || list.last()->remaining() < size) { block = new CompactHistoryBlock(); list.append ( block ); //kDebug() << "new block created, remaining " << block->remaining() << "number of blocks=" << list.size(); } else { block = list.last(); //kDebug() << "old block used, remaining " << block->remaining(); } return block->allocate(size); } void CompactHistoryBlockList::deallocate(void* ptr) { Q_ASSERT( !list.isEmpty()); int i=0; CompactHistoryBlock *block = list.at(i); while ( icontains(ptr) ) { i++; block=list.at(i); } Q_ASSERT( ideallocate(); if (!block->isInUse()) { list.removeAt(i); delete block; //kDebug() << "block deleted, new size = " << list.size(); } } CompactHistoryBlockList::~CompactHistoryBlockList() { qDeleteAll ( list.begin(), list.end() ); list.clear(); } void* CompactHistoryLine::operator new (size_t size, CompactHistoryBlockList& blockList) { return blockList.allocate(size); } CompactHistoryLine::CompactHistoryLine ( const TextLine& line, CompactHistoryBlockList& bList ) : blockList(bList), formatLength(0) { length=line.size(); if (line.size() > 0) { formatLength=1; int k=1; // count number of different formats in this text line Character c = line[0]; while ( k0) { blockList.deallocate(text); blockList.deallocate(formatArray); } blockList.deallocate(this); } void CompactHistoryLine::getCharacter ( int index, Character &r ) { Q_ASSERT ( index < length ); int formatPos=0; while ( ( formatPos+1 ) < formatLength && index >= formatArray[formatPos+1].startPos ) formatPos++; r.character=text[index]; r.rendition = formatArray[formatPos].rendition; r.foregroundColor = formatArray[formatPos].fgColor; r.backgroundColor = formatArray[formatPos].bgColor; } void CompactHistoryLine::getCharacters ( Character* array, int length, int startColumn ) { Q_ASSERT ( startColumn >= 0 && length >= 0 ); Q_ASSERT ( startColumn+length <= ( int ) getLength() ); for ( int i=startColumn; i ( int ) _maxLineCount ) { delete lines.takeAt ( 0 ); } lines.append ( line ); } void CompactHistoryScroll::addCells ( const Character a[], int count ) { TextLine newLine ( count ); std::copy ( a,a+count,newLine.begin() ); addCellsVector ( newLine ); } void CompactHistoryScroll::addLine ( bool previousWrapped ) { CompactHistoryLine *line = lines.last(); //kDebug() << "last line at address " << line; line->setWrapped(previousWrapped); } int CompactHistoryScroll::getLines() { return lines.size(); } int CompactHistoryScroll::getLineLen ( int lineNumber ) { Q_ASSERT ( lineNumber >= 0 && lineNumber < lines.size() ); CompactHistoryLine* line = lines[lineNumber]; //kDebug() << "request for line at address " << line; return line->getLength(); } void CompactHistoryScroll::getCells ( int lineNumber, int startColumn, int count, Character buffer[] ) { if ( count == 0 ) return; Q_ASSERT ( lineNumber < lines.size() ); CompactHistoryLine* line = lines[lineNumber]; Q_ASSERT ( startColumn >= 0 ); Q_ASSERT ( (unsigned int)startColumn <= line->getLength() - count ); line->getCharacters ( buffer, count, startColumn ); } void CompactHistoryScroll::setMaxNbLines ( unsigned int lineCount ) { _maxLineCount = lineCount; while (lines.size() > (int) lineCount) { delete lines.takeAt(0); } //kDebug() << "set max lines to: " << _maxLineCount; } bool CompactHistoryScroll::isWrappedLine ( int lineNumber ) { Q_ASSERT ( lineNumber < lines.size() ); return lines[lineNumber]->isWrapped(); } ////////////////////////////////////////////////////////////////////// // History Types ////////////////////////////////////////////////////////////////////// HistoryType::HistoryType() { } HistoryType::~HistoryType() { } ////////////////////////////// HistoryTypeNone::HistoryTypeNone() { } bool HistoryTypeNone::isEnabled() const { return false; } HistoryScroll* HistoryTypeNone::scroll(HistoryScroll *old) const { delete old; return new HistoryScrollNone(); } int HistoryTypeNone::maximumLineCount() const { return 0; } ////////////////////////////// HistoryTypeBlockArray::HistoryTypeBlockArray(size_t size) : m_size(size) { } bool HistoryTypeBlockArray::isEnabled() const { return true; } int HistoryTypeBlockArray::maximumLineCount() const { return m_size; } HistoryScroll* HistoryTypeBlockArray::scroll(HistoryScroll *old) const { delete old; return new HistoryScrollBlockArray(m_size); } ////////////////////////////// HistoryTypeBuffer::HistoryTypeBuffer(unsigned int nbLines) : m_nbLines(nbLines) { } bool HistoryTypeBuffer::isEnabled() const { return true; } int HistoryTypeBuffer::maximumLineCount() const { return m_nbLines; } HistoryScroll* HistoryTypeBuffer::scroll(HistoryScroll *old) const { if (old) { HistoryScrollBuffer *oldBuffer = dynamic_cast(old); if (oldBuffer) { oldBuffer->setMaxNbLines(m_nbLines); return oldBuffer; } HistoryScroll *newScroll = new HistoryScrollBuffer(m_nbLines); int lines = old->getLines(); int startLine = 0; if (lines > (int) m_nbLines) startLine = lines - m_nbLines; Character line[LINE_SIZE]; for(int i = startLine; i < lines; i++) { int size = old->getLineLen(i); if (size > LINE_SIZE) { Character *tmp_line = new Character[size]; old->getCells(i, 0, size, tmp_line); newScroll->addCells(tmp_line, size); newScroll->addLine(old->isWrappedLine(i)); delete [] tmp_line; } else { old->getCells(i, 0, size, line); newScroll->addCells(line, size); newScroll->addLine(old->isWrappedLine(i)); } } delete old; return newScroll; } return new HistoryScrollBuffer(m_nbLines); } ////////////////////////////// HistoryTypeFile::HistoryTypeFile(const QString& fileName) : m_fileName(fileName) { } bool HistoryTypeFile::isEnabled() const { return true; } const QString& HistoryTypeFile::getFileName() const { return m_fileName; } HistoryScroll* HistoryTypeFile::scroll(HistoryScroll *old) const { if (dynamic_cast(old)) return old; // Unchanged. HistoryScroll *newScroll = new HistoryScrollFile(m_fileName); Character line[LINE_SIZE]; int lines = (old != nullptr) ? old->getLines() : 0; for(int i = 0; i < lines; i++) { int size = old->getLineLen(i); if (size > LINE_SIZE) { Character *tmp_line = new Character[size]; old->getCells(i, 0, size, tmp_line); newScroll->addCells(tmp_line, size); newScroll->addLine(old->isWrappedLine(i)); delete [] tmp_line; } else { old->getCells(i, 0, size, line); newScroll->addCells(line, size); newScroll->addLine(old->isWrappedLine(i)); } } delete old; return newScroll; } int HistoryTypeFile::maximumLineCount() const { return 0; } ////////////////////////////// CompactHistoryType::CompactHistoryType ( unsigned int nbLines ) : m_nbLines ( nbLines ) { } bool CompactHistoryType::isEnabled() const { return true; } int CompactHistoryType::maximumLineCount() const { return m_nbLines; } HistoryScroll* CompactHistoryType::scroll ( HistoryScroll *old ) const { if ( old ) { CompactHistoryScroll *oldBuffer = dynamic_cast ( old ); if ( oldBuffer ) { oldBuffer->setMaxNbLines ( m_nbLines ); return oldBuffer; } delete old; } return new CompactHistoryScroll ( m_nbLines ); } deepin-terminal-5.2.11/3rdparty/terminalwidget/lib/History.h000066400000000000000000000320531370157770500240430ustar00rootroot00000000000000/* 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 TEHISTORY_H #define TEHISTORY_H // Qt #include #include #include #include // KDE //#include // Konsole #include "BlockArray.h" #include "Character.h" // map #include namespace Konsole { #if 1 /* An extendable tmpfile(1) based buffer. */ class HistoryFile { public: HistoryFile(); virtual ~HistoryFile(); virtual void add(const unsigned char* bytes, int len); virtual void get(unsigned char* bytes, int len, int loc); virtual int len(); //mmaps the file in read-only mode void map(); //un-mmaps the file void unmap(); //returns true if the file is mmap'ed bool isMapped() const; private: int ion; int length; QTemporaryFile tmpFile; //pointer to start of mmap'ed file data, or 0 if the file is not mmap'ed char* fileMap; //incremented whenver '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; }; #endif ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// // Abstract base class for file and buffer versions ////////////////////////////////////////////////////////////////////// class HistoryType; class HistoryScroll { public: 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 lineno) = 0; // backward compatibility (obsolete) Character getCell(int lineno, int colno) { Character res; getCells(lineno,colno,1,&res); return res; } // 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() { return *m_histType; } protected: HistoryType* m_histType; }; #if 1 ////////////////////////////////////////////////////////////////////// // File-based history (e.g. file log, no limitation in length) ////////////////////////////////////////////////////////////////////// class HistoryScrollFile : public HistoryScroll { public: HistoryScrollFile(const QString &logFileName); ~HistoryScrollFile() 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) override; void addLine(bool previousWrapped=false) override; private: int startOfLine(int lineno); QString m_logFileName; HistoryFile index; // lines Row(int) HistoryFile cells; // text Row(Character) HistoryFile lineflags; // flags Row(unsigned char) }; ////////////////////////////////////////////////////////////////////// // Buffer-based history (limited to a fixed nb of lines) ////////////////////////////////////////////////////////////////////// class HistoryScrollBuffer : public HistoryScroll { public: typedef QVector HistoryLine; HistoryScrollBuffer(unsigned int maxNbLines = 1000); ~HistoryScrollBuffer() 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) override; void addCellsVector(const QVector& cells) override; void addLine(bool previousWrapped=false) override; void setMaxNbLines(unsigned int nbLines); unsigned int maxNbLines() const { return _maxLineCount; } private: int bufferIndex(int lineNumber); HistoryLine* _historyBuffer; QBitArray _wrappedLine; int _maxLineCount; int _usedLines; int _head; //QVector m_histBuffer; //QBitArray m_wrappedLine; //unsigned int m_maxNbLines; //unsigned int m_nbLines; //unsigned int m_arrayIndex; //bool m_buffFilled; }; /*class HistoryScrollBufferV2 : public HistoryScroll { public: virtual int getLines(); virtual int getLineLen(int lineno); virtual void getCells(int lineno, int colno, int count, Character res[]); virtual bool isWrappedLine(int lineno); virtual void addCells(const Character a[], int count); virtual void addCells(const QVector& cells); virtual void addLine(bool previousWrapped=false); };*/ #endif ////////////////////////////////////////////////////////////////////// // Nothing-based history (no history :-) ////////////////////////////////////////////////////////////////////// class HistoryScrollNone : public HistoryScroll { public: HistoryScrollNone(); ~HistoryScrollNone() override; bool hasScroll() 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) override; void addLine(bool previousWrapped=false) override; }; ////////////////////////////////////////////////////////////////////// // BlockArray-based history ////////////////////////////////////////////////////////////////////// class HistoryScrollBlockArray : public HistoryScroll { public: HistoryScrollBlockArray(size_t size); ~HistoryScrollBlockArray() 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) override; void addLine(bool previousWrapped=false) override; protected: BlockArray m_blockArray; QHash m_lineLengths; }; ////////////////////////////////////////////////////////////////////// // 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==rendition && other.fgColor==fgColor && other.bgColor==bgColor; } bool equalsFormat(const Character &c) const { return c.rendition==rendition && c.foregroundColor==fgColor && c.backgroundColor==bgColor; } void setFormat(const Character& c) { rendition=c.rendition; fgColor=c.foregroundColor; bgColor=c.backgroundColor; } CharacterColor fgColor, bgColor; quint16 startPos; quint8 rendition; }; class CompactHistoryBlock { public: CompactHistoryBlock(){ blockLength = 4096*64; // 256kb head = (quint8*) mmap(nullptr, blockLength, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANON, -1, 0); //head = (quint8*) malloc(blockLength); Q_ASSERT(head != MAP_FAILED); tail = blockStart = head; allocCount=0; } 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 length); 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() {}; ~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 length, int startColumn) ; virtual void getCharacter(int index, Character &r) ; virtual bool isWrapped() const {return wrapped;}; virtual void setWrapped(bool isWrapped) { wrapped=isWrapped;}; virtual unsigned int getLength() const {return length;}; protected: CompactHistoryBlockList& blockList; CharacterFormat* formatArray; quint16 length; quint16* text; quint16 formatLength; bool wrapped; }; class CompactHistoryScroll : public HistoryScroll { typedef QList HistoryArray; public: CompactHistoryScroll(unsigned int maxNbLines = 1000); ~CompactHistoryScroll() 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) override; void addCellsVector(const TextLine& cells) override; void addLine(bool previousWrapped=false) override; void setMaxNbLines(unsigned int nbLines); unsigned int maxNbLines() const { return _maxLineCount; } private: bool hasDifferentColors(const TextLine& line) const; HistoryArray lines; CompactHistoryBlockList blockList; unsigned int _maxLineCount; }; ////////////////////////////////////////////////////////////////////// // History type ////////////////////////////////////////////////////////////////////// class 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 true if the history size is unlimited. */ bool isUnlimited() const { return maximumLineCount() == 0; } /** * Returns the maximum number of lines which this history type * can store or 0 if the history can store an unlimited number of lines. */ virtual int maximumLineCount() const = 0; virtual HistoryScroll* scroll(HistoryScroll *) const = 0; }; class HistoryTypeNone : public HistoryType { public: HistoryTypeNone(); bool isEnabled() const override; int maximumLineCount() const override; HistoryScroll* scroll(HistoryScroll *) const override; }; class HistoryTypeBlockArray : public HistoryType { public: HistoryTypeBlockArray(size_t size); bool isEnabled() const override; int maximumLineCount() const override; HistoryScroll* scroll(HistoryScroll *) const override; protected: size_t m_size; }; #if 1 class HistoryTypeFile : public HistoryType { public: HistoryTypeFile(const QString& fileName=QString()); bool isEnabled() const override; virtual const QString& getFileName() const; int maximumLineCount() const override; HistoryScroll* scroll(HistoryScroll *) const override; protected: QString m_fileName; }; class HistoryTypeBuffer : public HistoryType { friend class HistoryScrollBuffer; public: HistoryTypeBuffer(unsigned int nbLines); bool isEnabled() const override; int maximumLineCount() const override; HistoryScroll* scroll(HistoryScroll *) const override; protected: unsigned int m_nbLines; }; class CompactHistoryType : public HistoryType { public: CompactHistoryType(unsigned int size); bool isEnabled() const override; int maximumLineCount() const override; HistoryScroll* scroll(HistoryScroll *) const override; protected: unsigned int m_nbLines; }; #endif } #endif // TEHISTORY_H deepin-terminal-5.2.11/3rdparty/terminalwidget/lib/HistorySearch.cpp000066400000000000000000000207371370157770500255320ustar00rootroot00000000000000/* Copyright 2013 Christian Surlykke This program is free software; you can redistribute it and/or modify it under the terms of the 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. */ #include #include #include #include "TerminalCharacterDecoder.h" #include "Emulation.h" #include "HistorySearch.h" HistorySearch::HistorySearch(EmulationPtr emulation, QRegExp regExp, bool forwards, int startColumn, int startLine, QObject *parent) : QObject(parent), m_emulation(emulation), m_regExp(regExp), m_forwards(forwards), m_startColumn(startColumn), m_startLine(startLine) { } HistorySearch::~HistorySearch() { } void HistorySearch::search() { bool found = false; if (! m_regExp.isEmpty()) { if (m_forwards) { found = search(m_startColumn, m_startLine, -1, m_emulation->lineCount()) || search(0, 0, m_startColumn, m_startLine); } else { found = search(0, 0, m_startColumn, m_startLine) || search(m_startColumn, m_startLine, -1, m_emulation->lineCount()); } if (found) { emit matchFound(m_foundStartColumn, m_foundStartLine, m_foundEndColumn, m_foundEndLine, m_loseChinese, m_matchChinese); } else { emit noMatchFound(); } } deleteLater(); } bool HistorySearch::search(int startColumn, int startLine, int endColumn, int endLine) { qDebug() << "search from" << startColumn << "," << startLine << "to" << endColumn << "," << endLine; int linesRead = 0; int linesToRead = endLine - startLine + 1; qDebug() << "linesToRead:" << linesToRead; // We read process history from (and including) startLine to (and including) endLine in // blocks of at most 10K lines so that we do not use unhealthy amounts of memory int blockSize; while ((blockSize = qMin(10000, linesToRead - linesRead)) > 0) { QString string; QTextStream searchStream(&string); PlainTextDecoder decoder; decoder.begin(&searchStream); decoder.setRecordLinePositions(true); // Calculate lines to read and read them int blockStartLine = m_forwards ? startLine + linesRead : endLine - linesRead - blockSize + 1; int chunkEndLine = blockStartLine + blockSize - 1; m_emulation->writeToStream(&decoder, blockStartLine, chunkEndLine); // We search between startColumn in the first line of the string and endColumn in the last // line of the string. First we calculate the position (in the string) of endColumn in the // last line of the string int endPosition; // The String that Emulator.writeToStream produces has a newline at the end, and so ends with an // empty line - we ignore that. int numberOfLinesInString = decoder.linePositions().size() - 1; if (numberOfLinesInString > 0 && endColumn > -1) { endPosition = decoder.linePositions().at(numberOfLinesInString - 1) + endColumn; } else { endPosition = string.size(); } // So now we can log for m_regExp in the string between startColumn and endPosition int matchStart; if (m_forwards) { matchStart = string.indexOf(m_regExp, startColumn); if (matchStart >= endPosition) { matchStart = -1; } } else { matchStart = string.lastIndexOf(m_regExp, endPosition - 1); if (matchStart < startColumn) { matchStart = -1; } } if (matchStart > -1) { int matchEnd = matchStart + m_regExp.matchedLength() - 1; qDebug() << "Found in string from" << matchStart << "to" << matchEnd; // Translate startPos and endPos to startColum, startLine, endColumn and endLine in history. int startLineNumberInString = findLineNumberInString(decoder.linePositions(), matchStart); m_foundStartColumn = matchStart - decoder.linePositions().at(startLineNumberInString); m_foundStartLine = startLineNumberInString + startLine + linesRead; int endLineNumberInString = findLineNumberInString(decoder.linePositions(), matchEnd); m_foundEndColumn = matchEnd - decoder.linePositions().at(endLineNumberInString); m_foundEndLine = endLineNumberInString + startLine + linesRead; qDebug() << "m_foundStartColumn" << m_foundStartColumn << "m_foundStartLine" << m_foundStartLine << "m_foundEndColumn" << m_foundEndColumn << "m_foundEndLine" << m_foundEndLine; /***add begin by ut001121 zhangmeng 20200515 修复BUG22626***/ /** string: aaa-------------bbbbbbbbbbbbb-------ccc | || | match pos:| |matchStart matchEnd lose pos: loseStart loseEnd | line pos: lineStart lineEnd 存在特殊情况:一个完整的物理行显示在终端被分成多个逻辑行 */ //中文字符正则表达式 QRegExp regEx("[\u4E00-\u9FA5,《。》、?;:【】~!¥()]+"); //未匹配的串-物理行开始和结束位置 int loseEnd = matchStart; int loseStart = string.lastIndexOf('\n', loseEnd) + 1; //qDebug() << "loseStart" << loseStart << "loseEnd" << loseEnd ; // if (loseStart < 0 || loseStart > loseEnd) { // qDebug() << "========loseStart and loseEnd is not expected" << loseStart << loseEnd; // exit(-1); // } //未匹配的串-物理行字符串 QString loseStr = string.mid(loseStart, loseEnd - loseStart); //qDebug() << "loseStr" << loseStr << m_lineChinese; //未匹配的串-逻辑行字符串 int loseEndLineNumberInString = findLineNumberInString(decoder.linePositions(), loseEnd); int loseEndColumn = matchStart - decoder.linePositions().at(loseEndLineNumberInString); QString logicLoseStr = loseStr.right(loseEndColumn); m_loseChinese = logicLoseStr.count(regEx); //qDebug() << "logicLoseStr" << logicLoseStr << m_lineChinese << loseEndColumn; //匹配内容是否跨多个逻辑行 if (m_foundStartLine == m_foundEndLine) { /* * 单逻辑行匹配情况 * 匹配字符的当前逻辑行:(匹配字符-当前逻辑行-开始位置)--->(匹配字符-当前逻辑行-结束位置 */ //匹配字符包含中文字符数量 QString txt = m_regExp.pattern(); m_matchChinese = txt.count(regEx); m_matchChinese += m_loseChinese; } else { /* * 多逻辑行匹配情况 * 匹配字符的尾行逻辑行:(匹配字符-尾行逻辑行-开始位置)--->(匹配字符-尾行逻辑行-结束位置) */ QString macthStr = string.mid(loseStart, matchEnd - loseStart + 1); QString tailMacthStr = macthStr.right(m_foundEndColumn + 1); //qDebug() << "tailMacthStr" << tailMacthStr; m_matchChinese = tailMacthStr.count(regEx) ; /* * 跨行匹配不计算m_loseChinese * m_matchChinese += m_loseChinese; */ } /***add end by ut001121***/ return true; } linesRead += blockSize; } qDebug() << "Not found"; return false; } int HistorySearch::findLineNumberInString(QList linePositions, int position) { int lineNum = 0; while (lineNum + 1 < linePositions.size() && linePositions[lineNum + 1] <= position) lineNum++; return lineNum; } deepin-terminal-5.2.11/3rdparty/terminalwidget/lib/HistorySearch.h000066400000000000000000000035771370157770500252020ustar00rootroot00000000000000/* Copyright 2013 Christian Surlykke This program is free software; you can redistribute it and/or modify it under the terms of the 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 TASK_H #define TASK_H #include #include #include #include #include #include "Emulation.h" #include "TerminalCharacterDecoder.h" using namespace Konsole; typedef QPointer EmulationPtr; class HistorySearch : public QObject { Q_OBJECT public: explicit HistorySearch(EmulationPtr emulation, QRegExp regExp, bool forwards, int startColumn, int startLine, QObject* parent); ~HistorySearch() override; void search(); signals: void matchFound(int startColumn, int startLine, int endColumn, int endLine, int loseChinese, int matchChinese); void noMatchFound(); private: bool search(int startColumn, int startLine, int endColumn, int endLine); int findLineNumberInString(QList linePositions, int position); EmulationPtr m_emulation; QRegExp m_regExp; bool m_forwards; int m_startColumn; int m_startLine; int m_foundStartColumn; int m_foundStartLine; int m_foundEndColumn; int m_foundEndLine; int m_loseChinese; int m_matchChinese; }; #endif /* TASK_H */ deepin-terminal-5.2.11/3rdparty/terminalwidget/lib/KeyboardTranslator.cpp000066400000000000000000000732201370157770500265500ustar00rootroot00000000000000/* 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. */ // Own #include "KeyboardTranslator.h" // System #include #include // Qt #include #include #include #include #include #include #include #include "tools.h" // KDE //#include //#include //#include using namespace Konsole; const QByteArray KeyboardTranslatorManager::defaultTranslatorText( "keyboard \"Fallback Key Translator\"\n" "key Tab : \"\\t\"" ); #ifdef Q_OS_MAC // On Mac, Qt::ControlModifier means Cmd, and MetaModifier means Ctrl const Qt::KeyboardModifier KeyboardTranslator::CTRL_MOD = Qt::MetaModifier; #else const Qt::KeyboardModifier KeyboardTranslator::CTRL_MOD = Qt::ControlModifier; #endif KeyboardTranslatorManager::KeyboardTranslatorManager() : _haveLoadedAll(false) { } KeyboardTranslatorManager::~KeyboardTranslatorManager() { qDeleteAll(_translators); } QString KeyboardTranslatorManager::findTranslatorPath(const QString& name) { return QString(get_kb_layout_dir() + name + QLatin1String(".keytab")); //return KGlobal::dirs()->findResource("data","konsole/"+name+".keytab"); } void KeyboardTranslatorManager::findTranslators() { QDir dir(get_kb_layout_dir()); QStringList filters; filters << QLatin1String("*.keytab"); dir.setNameFilters(filters); QStringList list = dir.entryList(filters); // QStringList list = KGlobal::dirs()->findAllResources("data", // "konsole/*.keytab", // KStandardDirs::NoDuplicates); // add the name of each translator to the list and associated // the name with a null pointer to indicate that the translator // has not yet been loaded from disk QStringListIterator listIter(list); while (listIter.hasNext()) { QString translatorPath = listIter.next(); QString name = QFileInfo(translatorPath).baseName(); if ( !_translators.contains(name) ) _translators.insert(name,0); } _haveLoadedAll = true; } const KeyboardTranslator* KeyboardTranslatorManager::findTranslator(const QString& name) { if ( name.isEmpty() ) return defaultTranslator(); if ( _translators.contains(name) && _translators[name] != 0 ) return _translators[name]; KeyboardTranslator* translator = loadTranslator(name); if ( translator != nullptr ) _translators[name] = translator; else if ( !name.isEmpty() ) qDebug() << "Unable to load translator" << name; return translator; } bool KeyboardTranslatorManager::saveTranslator(const KeyboardTranslator* translator) { qDebug() << "KeyboardTranslatorManager::saveTranslator" << "unimplemented"; Q_UNUSED(translator); #if 0 const QString path = KGlobal::dirs()->saveLocation("data","konsole/")+translator->name() +".keytab"; //kDebug() << "Saving translator to" << path; QFile destination(path); if (!destination.open(QIODevice::WriteOnly | QIODevice::Text)) { qDebug() << "Unable to save keyboard translation:" << destination.errorString(); return false; } { KeyboardTranslatorWriter writer(&destination); writer.writeHeader(translator->description()); QListIterator iter(translator->entries()); while ( iter.hasNext() ) writer.writeEntry(iter.next()); } destination.close(); #endif return true; } KeyboardTranslator* KeyboardTranslatorManager::loadTranslator(const QString& name) { const QString& path = findTranslatorPath(name); QFile source(path); if (name.isEmpty() || !source.open(QIODevice::ReadOnly | QIODevice::Text)) return nullptr; return loadTranslator(&source,name); } const KeyboardTranslator* KeyboardTranslatorManager::defaultTranslator() { // Try to find the default.keytab file if it exists, otherwise // fall back to the hard-coded one const KeyboardTranslator* translator = findTranslator(QLatin1String("default")); if (!translator) { QBuffer textBuffer; textBuffer.setData(defaultTranslatorText); textBuffer.open(QIODevice::ReadOnly); translator = loadTranslator(&textBuffer,QLatin1String("fallback")); } return translator; } KeyboardTranslator* KeyboardTranslatorManager::loadTranslator(QIODevice* source,const QString& name) { KeyboardTranslator* translator = new KeyboardTranslator(name); KeyboardTranslatorReader reader(source); translator->setDescription( reader.description() ); while ( reader.hasNextEntry() ) translator->addEntry(reader.nextEntry()); source->close(); if ( !reader.parseError() ) { return translator; } else { delete translator; return nullptr; } } KeyboardTranslatorWriter::KeyboardTranslatorWriter(QIODevice* destination) : _destination(destination) { Q_ASSERT( destination && destination->isWritable() ); _writer = new QTextStream(_destination); } KeyboardTranslatorWriter::~KeyboardTranslatorWriter() { delete _writer; } void KeyboardTranslatorWriter::writeHeader( const QString& description ) { *_writer << "keyboard \"" << description << '\"' << '\n'; } void KeyboardTranslatorWriter::writeEntry( const KeyboardTranslator::Entry& entry ) { QString result; if ( entry.command() != KeyboardTranslator::NoCommand ) result = entry.resultToString(); else result = QLatin1Char('\"') + entry.resultToString() + QLatin1Char('\"'); *_writer << QLatin1String("key ") << entry.conditionToString() << QLatin1String(" : ") << result << QLatin1Char('\n'); } // each line of the keyboard translation file is one of: // // - keyboard "name" // - key KeySequence : "characters" // - key KeySequence : CommandName // // KeySequence begins with the name of the key ( taken from the Qt::Key enum ) // and is followed by the keyboard modifiers and state flags ( with + or - in front // of each modifier or flag to indicate whether it is required ). All keyboard modifiers // and flags are optional, if a particular modifier or state is not specified it is // assumed not to be a part of the sequence. The key sequence may contain whitespace // // eg: "key Up+Shift : scrollLineUp" // "key Next-Shift : "\E[6~" // // (lines containing only whitespace are ignored, parseLine assumes that comments have // already been removed) // KeyboardTranslatorReader::KeyboardTranslatorReader( QIODevice* source ) : _source(source) , _hasNext(false) { // read input until we find the description while ( _description.isEmpty() && !source->atEnd() ) { QList tokens = tokenize( QString::fromUtf8(source->readLine()) ); if ( !tokens.isEmpty() && tokens.first().type == Token::TitleKeyword ) _description = tokens[1].text; } // read first entry (if any) readNext(); } void KeyboardTranslatorReader::readNext() { // find next entry while ( !_source->atEnd() ) { const QList& tokens = tokenize( QString::fromUtf8(_source->readLine()) ); if ( !tokens.isEmpty() && tokens.first().type == Token::KeyKeyword ) { KeyboardTranslator::States flags = KeyboardTranslator::NoState; KeyboardTranslator::States flagMask = KeyboardTranslator::NoState; Qt::KeyboardModifiers modifiers = Qt::NoModifier; Qt::KeyboardModifiers modifierMask = Qt::NoModifier; int keyCode = Qt::Key_unknown; decodeSequence(tokens[1].text.toLower(), keyCode, modifiers, modifierMask, flags, flagMask); KeyboardTranslator::Command command = KeyboardTranslator::NoCommand; QByteArray text; // get text or command if ( tokens[2].type == Token::OutputText ) { text = tokens[2].text.toLocal8Bit(); } else if ( tokens[2].type == Token::Command ) { // identify command if (!parseAsCommand(tokens[2].text,command)) qDebug() << "Command" << tokens[2].text << "not understood."; } KeyboardTranslator::Entry newEntry; newEntry.setKeyCode( keyCode ); newEntry.setState( flags ); newEntry.setStateMask( flagMask ); newEntry.setModifiers( modifiers ); newEntry.setModifierMask( modifierMask ); newEntry.setText( text ); newEntry.setCommand( command ); _nextEntry = newEntry; _hasNext = true; return; } } _hasNext = false; } bool KeyboardTranslatorReader::parseAsCommand(const QString& text,KeyboardTranslator::Command& command) { if ( text.compare(QLatin1String("erase"),Qt::CaseInsensitive) == 0 ) command = KeyboardTranslator::EraseCommand; else if ( text.compare(QLatin1String("scrollpageup"),Qt::CaseInsensitive) == 0 ) command = KeyboardTranslator::ScrollPageUpCommand; else if ( text.compare(QLatin1String("scrollpagedown"),Qt::CaseInsensitive) == 0 ) command = KeyboardTranslator::ScrollPageDownCommand; else if ( text.compare(QLatin1String("scrolllineup"),Qt::CaseInsensitive) == 0 ) command = KeyboardTranslator::ScrollLineUpCommand; else if ( text.compare(QLatin1String("scrolllinedown"),Qt::CaseInsensitive) == 0 ) command = KeyboardTranslator::ScrollLineDownCommand; else if ( text.compare(QLatin1String("scrolllock"),Qt::CaseInsensitive) == 0 ) command = KeyboardTranslator::ScrollLockCommand; else if ( text.compare(QLatin1String("scrolluptotop"),Qt::CaseInsensitive) == 0) command = KeyboardTranslator::ScrollUpToTopCommand; else if ( text.compare(QLatin1String("scrolldowntobottom"),Qt::CaseInsensitive) == 0) command = KeyboardTranslator::ScrollDownToBottomCommand; else return false; return true; } bool KeyboardTranslatorReader::decodeSequence(const QString& text, int& keyCode, Qt::KeyboardModifiers& modifiers, Qt::KeyboardModifiers& modifierMask, KeyboardTranslator::States& flags, KeyboardTranslator::States& flagMask) { bool isWanted = true; bool endOfItem = false; QString buffer; Qt::KeyboardModifiers tempModifiers = modifiers; Qt::KeyboardModifiers tempModifierMask = modifierMask; KeyboardTranslator::States tempFlags = flags; KeyboardTranslator::States tempFlagMask = flagMask; for ( int i = 0 ; i < text.count() ; i++ ) { const QChar& ch = text[i]; bool isFirstLetter = i == 0; bool isLastLetter = ( i == text.count()-1 ); endOfItem = true; if ( ch.isLetterOrNumber() ) { endOfItem = false; buffer.append(ch); } else if ( isFirstLetter ) { buffer.append(ch); } if ( (endOfItem || isLastLetter) && !buffer.isEmpty() ) { Qt::KeyboardModifier itemModifier = Qt::NoModifier; int itemKeyCode = 0; KeyboardTranslator::State itemFlag = KeyboardTranslator::NoState; if ( parseAsModifier(buffer,itemModifier) ) { tempModifierMask |= itemModifier; if ( isWanted ) tempModifiers |= itemModifier; } else if ( parseAsStateFlag(buffer,itemFlag) ) { tempFlagMask |= itemFlag; if ( isWanted ) tempFlags |= itemFlag; } else if ( parseAsKeyCode(buffer,itemKeyCode) ) keyCode = itemKeyCode; else qDebug() << "Unable to parse key binding item:" << buffer; buffer.clear(); } // check if this is a wanted / not-wanted flag and update the // state ready for the next item if ( ch == QLatin1Char('+') ) isWanted = true; else if ( ch == QLatin1Char('-') ) isWanted = false; } modifiers = tempModifiers; modifierMask = tempModifierMask; flags = tempFlags; flagMask = tempFlagMask; return true; } bool KeyboardTranslatorReader::parseAsModifier(const QString& item , Qt::KeyboardModifier& modifier) { if ( item == QLatin1String("shift") ) modifier = Qt::ShiftModifier; else if ( item == QLatin1String("ctrl") || item == QLatin1String("control") ) modifier = Qt::ControlModifier; else if ( item == QLatin1String("alt") ) modifier = Qt::AltModifier; else if ( item == QLatin1String("meta") ) modifier = Qt::MetaModifier; else if ( item == QLatin1String("keypad") ) modifier = Qt::KeypadModifier; else return false; return true; } bool KeyboardTranslatorReader::parseAsStateFlag(const QString& item , KeyboardTranslator::State& flag) { if ( item == QLatin1String("appcukeys") || item == QLatin1String("appcursorkeys") ) flag = KeyboardTranslator::CursorKeysState; else if ( item == QLatin1String("ansi") ) flag = KeyboardTranslator::AnsiState; else if ( item == QLatin1String("newline") ) flag = KeyboardTranslator::NewLineState; else if ( item == QLatin1String("appscreen") ) flag = KeyboardTranslator::AlternateScreenState; else if ( item == QLatin1String("anymod") || item == QLatin1String("anymodifier") ) flag = KeyboardTranslator::AnyModifierState; else if ( item == QLatin1String("appkeypad") ) flag = KeyboardTranslator::ApplicationKeypadState; else return false; return true; } bool KeyboardTranslatorReader::parseAsKeyCode(const QString& item , int& keyCode) { QKeySequence sequence = QKeySequence::fromString(item); if ( !sequence.isEmpty() ) { keyCode = sequence[0]; if ( sequence.count() > 1 ) { qDebug() << "Unhandled key codes in sequence: " << item; } } // additional cases implemented for backwards compatibility with KDE 3 else if ( item == QLatin1String("prior") ) keyCode = Qt::Key_PageUp; else if ( item == QLatin1String("next") ) keyCode = Qt::Key_PageDown; else return false; return true; } QString KeyboardTranslatorReader::description() const { return _description; } bool KeyboardTranslatorReader::hasNextEntry() { return _hasNext; } KeyboardTranslator::Entry KeyboardTranslatorReader::createEntry( const QString& condition , const QString& result ) { QString entryString = QString::fromLatin1("keyboard \"temporary\"\nkey "); entryString.append(condition); entryString.append(QLatin1String(" : ")); // if 'result' is the name of a command then the entry result will be that command, // otherwise the result will be treated as a string to echo when the key sequence // specified by 'condition' is pressed KeyboardTranslator::Command command; if (parseAsCommand(result,command)) entryString.append(result); else entryString.append(QLatin1Char('\"') + result + QLatin1Char('\"')); QByteArray array = entryString.toUtf8(); QBuffer buffer(&array); buffer.open(QIODevice::ReadOnly); KeyboardTranslatorReader reader(&buffer); KeyboardTranslator::Entry entry; if ( reader.hasNextEntry() ) entry = reader.nextEntry(); return entry; } KeyboardTranslator::Entry KeyboardTranslatorReader::nextEntry() { Q_ASSERT( _hasNext ); KeyboardTranslator::Entry entry = _nextEntry; readNext(); return entry; } bool KeyboardTranslatorReader::parseError() { return false; } QList KeyboardTranslatorReader::tokenize(const QString& line) { QString text = line; // remove comments bool inQuotes = false; int commentPos = -1; for (int i=text.length()-1;i>=0;i--) { QChar ch = text[i]; if (ch == QLatin1Char('\"')) inQuotes = !inQuotes; else if (ch == QLatin1Char('#') && !inQuotes) commentPos = i; } if (commentPos != -1) text.remove(commentPos,text.length()); text = text.simplified(); // title line: keyboard "title" static QRegExp title(QLatin1String("keyboard\\s+\"(.*)\"")); // key line: key KeySequence : "output" // key line: key KeySequence : command static QRegExp key(QLatin1String("key\\s+([\\w\\+\\s\\-\\*\\.]+)\\s*:\\s*(\"(.*)\"|\\w+)")); QList list; if ( text.isEmpty() ) { return list; } if ( title.exactMatch(text) ) { Token titleToken = { Token::TitleKeyword , QString() }; Token textToken = { Token::TitleText , title.capturedTexts().at(1) }; list << titleToken << textToken; } else if ( key.exactMatch(text) ) { Token keyToken = { Token::KeyKeyword , QString() }; Token sequenceToken = { Token::KeySequence , key.capturedTexts().value(1).remove(QLatin1Char(' ')) }; list << keyToken << sequenceToken; if ( key.capturedTexts().at(3).isEmpty() ) { // capturedTexts()[2] is a command Token commandToken = { Token::Command , key.capturedTexts().at(2) }; list << commandToken; } else { // capturedTexts()[3] is the output string Token outputToken = { Token::OutputText , key.capturedTexts().at(3) }; list << outputToken; } } else { qDebug() << "Line in keyboard translator file could not be understood:" << text; } return list; } QList KeyboardTranslatorManager::allTranslators() { if ( !_haveLoadedAll ) { findTranslators(); } return _translators.keys(); } KeyboardTranslator *KeyboardTranslatorManager::getTranslator(const QString &name) { if ( name.isEmpty() ) { // Try to find the default.keytab file if it exists, otherwise // fall back to the hard-coded one KeyboardTranslator *translator = loadTranslator(QLatin1String("default")); if (!translator) { QBuffer textBuffer; textBuffer.setData(defaultTranslatorText); textBuffer.open(QIODevice::ReadOnly); translator = loadTranslator(&textBuffer, QLatin1String("fallback")); } return translator; } if ( _translators.contains(name) && _translators[name] != 0 ) return _translators[name]; KeyboardTranslator *translator = loadTranslator(name); if ( translator != 0 ) _translators[name] = translator; else if ( !name.isEmpty() ) qDebug() << "Unable to load translator" << name; return translator; } KeyboardTranslator::Entry::Entry() : _keyCode(0) , _modifiers(Qt::NoModifier) , _modifierMask(Qt::NoModifier) , _state(NoState) , _stateMask(NoState) , _command(NoCommand) { } bool KeyboardTranslator::Entry::operator==(const Entry& rhs) const { return _keyCode == rhs._keyCode && _modifiers == rhs._modifiers && _modifierMask == rhs._modifierMask && _state == rhs._state && _stateMask == rhs._stateMask && _command == rhs._command && _text == rhs._text; } bool KeyboardTranslator::Entry::matches(int keyCode , Qt::KeyboardModifiers modifiers, States testState) const { #ifdef Q_OS_MAC // On Mac, arrow keys are considered part of keypad. Ignore that. modifiers &= ~Qt::KeypadModifier; #endif if ( _keyCode != keyCode ) return false; if ( (modifiers & _modifierMask) != (_modifiers & _modifierMask) ) return false; // if modifiers is non-zero, the 'any modifier' state is implicit if ( (modifiers & ~Qt::KeypadModifier) != 0 ) testState |= AnyModifierState; if ( (testState & _stateMask) != (_state & _stateMask) ) return false; // special handling for the 'Any Modifier' state, which checks for the presence of // any or no modifiers. In this context, the 'keypad' modifier does not count. bool anyModifiersSet = modifiers != 0 && modifiers != Qt::KeypadModifier; bool wantAnyModifier = _state & KeyboardTranslator::AnyModifierState; if ( _stateMask & KeyboardTranslator::AnyModifierState ) { if ( wantAnyModifier != anyModifiersSet ) return false; } return true; } QByteArray KeyboardTranslator::Entry::escapedText(bool expandWildCards,Qt::KeyboardModifiers modifiers) const { QByteArray result(text(expandWildCards,modifiers)); for ( int i = 0 ; i < result.count() ; i++ ) { char ch = result[i]; char replacement = 0; switch ( ch ) { case 27 : replacement = 'E'; break; case 8 : replacement = 'b'; break; case 12 : replacement = 'f'; break; case 9 : replacement = 't'; break; case 13 : replacement = 'r'; break; case 10 : replacement = 'n'; break; default: // any character which is not printable is replaced by an equivalent // \xhh escape sequence (where 'hh' are the corresponding hex digits) if ( !QChar(QLatin1Char(ch)).isPrint() ) replacement = 'x'; } if ( replacement == 'x' ) { result.replace(i,1,"\\x"+QByteArray(1,ch).toHex()); } else if ( replacement != 0 ) { result.remove(i,1); result.insert(i,'\\'); result.insert(i+1,replacement); } } return result; } QByteArray KeyboardTranslator::Entry::unescape(const QByteArray& input) const { QByteArray result(input); for ( int i = 0 ; i < result.count()-1 ; i++ ) { QByteRef ch = result[i]; if ( ch == '\\' ) { char replacement[2] = {0,0}; int charsToRemove = 2; bool escapedChar = true; switch ( result[i+1] ) { case 'E' : replacement[0] = 27; break; case 'b' : replacement[0] = 8 ; break; case 'f' : replacement[0] = 12; break; case 't' : replacement[0] = 9 ; break; case 'r' : replacement[0] = 13; break; case 'n' : replacement[0] = 10; break; case 'x' : { // format is \xh or \xhh where 'h' is a hexadecimal // digit from 0-9 or A-F which should be replaced // with the corresponding character value char hexDigits[3] = {0}; if ( (i < result.count()-2) && isxdigit(result[i+2]) ) hexDigits[0] = result[i+2]; if ( (i < result.count()-3) && isxdigit(result[i+3]) ) hexDigits[1] = result[i+3]; unsigned charValue = 0; sscanf(hexDigits,"%x",&charValue); replacement[0] = (char)charValue; charsToRemove = 2 + strlen(hexDigits); } break; default: escapedChar = false; } if ( escapedChar ) result.replace(i,charsToRemove,replacement); } } return result; } void KeyboardTranslator::Entry::insertModifier( QString& item , int modifier ) const { if ( !(modifier & _modifierMask) ) return; if ( modifier & _modifiers ) item += QLatin1Char('+'); else item += QLatin1Char('-'); if ( modifier == Qt::ShiftModifier ) item += QLatin1String("Shift"); else if ( modifier == Qt::ControlModifier ) item += QLatin1String("Ctrl"); else if ( modifier == Qt::AltModifier ) item += QLatin1String("Alt"); else if ( modifier == Qt::MetaModifier ) item += QLatin1String("Meta"); else if ( modifier == Qt::KeypadModifier ) item += QLatin1String("KeyPad"); } void KeyboardTranslator::Entry::insertState( QString& item , int state ) const { if ( !(state & _stateMask) ) return; if ( state & _state ) item += QLatin1Char('+') ; else item += QLatin1Char('-') ; if ( state == KeyboardTranslator::AlternateScreenState ) item += QLatin1String("AppScreen"); else if ( state == KeyboardTranslator::NewLineState ) item += QLatin1String("NewLine"); else if ( state == KeyboardTranslator::AnsiState ) item += QLatin1String("Ansi"); else if ( state == KeyboardTranslator::CursorKeysState ) item += QLatin1String("AppCursorKeys"); else if ( state == KeyboardTranslator::AnyModifierState ) item += QLatin1String("AnyModifier"); else if ( state == KeyboardTranslator::ApplicationKeypadState ) item += QLatin1String("AppKeypad"); } QString KeyboardTranslator::Entry::resultToString(bool expandWildCards,Qt::KeyboardModifiers modifiers) const { if ( !_text.isEmpty() ) return QString::fromLatin1(escapedText(expandWildCards,modifiers)); else if ( _command == EraseCommand ) return QLatin1String("Erase"); else if ( _command == ScrollPageUpCommand ) return QLatin1String("ScrollPageUp"); else if ( _command == ScrollPageDownCommand ) return QLatin1String("ScrollPageDown"); else if ( _command == ScrollLineUpCommand ) return QLatin1String("ScrollLineUp"); else if ( _command == ScrollLineDownCommand ) return QLatin1String("ScrollLineDown"); else if ( _command == ScrollLockCommand ) return QLatin1String("ScrollLock"); else if (_command == ScrollUpToTopCommand) return QLatin1String("ScrollUpToTop"); else if (_command == ScrollDownToBottomCommand) return QLatin1String("ScrollDownToBottom"); return QString(); } QString KeyboardTranslator::Entry::conditionToString() const { QString result = QKeySequence(_keyCode).toString(); insertModifier( result , Qt::ShiftModifier ); insertModifier( result , Qt::ControlModifier ); insertModifier( result , Qt::AltModifier ); insertModifier( result , Qt::MetaModifier ); insertModifier( result , Qt::KeypadModifier ); insertState( result , KeyboardTranslator::AlternateScreenState ); insertState( result , KeyboardTranslator::NewLineState ); insertState( result , KeyboardTranslator::AnsiState ); insertState( result , KeyboardTranslator::CursorKeysState ); insertState( result , KeyboardTranslator::AnyModifierState ); insertState( result , KeyboardTranslator::ApplicationKeypadState ); return result; } KeyboardTranslator::KeyboardTranslator(const QString& name) : _name(name) { } void KeyboardTranslator::setDescription(const QString& description) { _description = description; } QString KeyboardTranslator::description() const { return _description; } void KeyboardTranslator::setName(const QString& name) { _name = name; } QString KeyboardTranslator::name() const { return _name; } QList KeyboardTranslator::entries() const { return _entries.values(); } void KeyboardTranslator::addEntry(const Entry& entry) { const int keyCode = entry.keyCode(); _entries.insert(keyCode,entry); } void KeyboardTranslator::replaceEntry(const Entry& existing , const Entry& replacement) { if ( !existing.isNull() ) _entries.remove(existing.keyCode(),existing); _entries.insert(replacement.keyCode(),replacement); } void KeyboardTranslator::removeEntry(const Entry& entry) { _entries.remove(entry.keyCode(),entry); } KeyboardTranslator::Entry KeyboardTranslator::findEntry(int keyCode, Qt::KeyboardModifiers modifiers, States state) const { for (auto it = _entries.cbegin(), end = _entries.cend(); it != end; ++it) { if (it.key() == keyCode) if ( it.value().matches(keyCode,modifiers,state) ) return *it; } return Entry(); // entry not found } void KeyboardTranslatorManager::addTranslator(KeyboardTranslator* translator) { _translators.insert(translator->name(),translator); if ( !saveTranslator(translator) ) qDebug() << "Unable to save translator" << translator->name() << "to disk."; } bool KeyboardTranslatorManager::deleteTranslator(const QString& name) { Q_ASSERT( _translators.contains(name) ); // locate and delete QString path = findTranslatorPath(name); if ( QFile::remove(path) ) { _translators.remove(name); return true; } else { qDebug() << "Failed to remove translator - " << path; return false; } } Q_GLOBAL_STATIC( KeyboardTranslatorManager , theKeyboardTranslatorManager ) KeyboardTranslatorManager* KeyboardTranslatorManager::instance() { return theKeyboardTranslatorManager; } deepin-terminal-5.2.11/3rdparty/terminalwidget/lib/KeyboardTranslator.h000066400000000000000000000475071370157770500262260ustar00rootroot00000000000000/* 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 KEYBOARDTRANSLATOR_H #define KEYBOARDTRANSLATOR_H // Qt #include #include #include #include #include // Konsole //#include "konsole_export.h" #define KONSOLEPRIVATE_EXPORT class QIODevice; class QTextStream; namespace Konsole { /** * A convertor which maps between key sequences pressed by the user and the * character strings which should be sent to the terminal and commands * which should be invoked when those character sequences are pressed. * * Konsole supports multiple keyboard translators, allowing the user to * specify the character sequences which are sent to the terminal * when particular key sequences are pressed. * * A key sequence is defined as a key code, associated keyboard modifiers * (Shift,Ctrl,Alt,Meta etc.) and state flags which indicate the state * which the terminal must be in for the key sequence to apply. */ class KeyboardTranslator { public: /** * The meaning of a particular key sequence may depend upon the state which * the terminal emulation is in. Therefore findEntry() may return a different * Entry depending upon the state flags supplied. * * This enum describes the states which may be associated with with a particular * entry in the keyboard translation entry. */ enum State { /** Indicates that no special state is active */ NoState = 0, /** * TODO More documentation */ NewLineState = 1, /** * Indicates that the terminal is in 'Ansi' mode. * TODO: More documentation */ AnsiState = 2, /** * TODO More documentation */ CursorKeysState = 4, /** * Indicates that the alternate screen ( typically used by interactive programs * such as screen or vim ) is active */ AlternateScreenState = 8, /** Indicates that any of the modifier keys is active. */ AnyModifierState = 16, /** Indicates that the numpad is in application mode. */ ApplicationKeypadState = 32 }; Q_DECLARE_FLAGS(States,State) /** * This enum describes commands which are associated with particular key sequences. */ enum Command { /** Indicates that no command is associated with this command sequence */ NoCommand = 0, /** TODO Document me */ SendCommand = 1, /** Scroll the terminal display up one page */ ScrollPageUpCommand = 2, /** Scroll the terminal display down one page */ ScrollPageDownCommand = 4, /** Scroll the terminal display up one line */ ScrollLineUpCommand = 8, /** Scroll the terminal display down one line */ ScrollLineDownCommand = 16, /** Toggles scroll lock mode */ ScrollLockCommand = 32, /** Scroll the terminal display up to the start of history */ ScrollUpToTopCommand = 64, /** Scroll the terminal display down to the end of history */ ScrollDownToBottomCommand = 128, /** Echos the operating system specific erase character. */ EraseCommand = 256 }; Q_DECLARE_FLAGS(Commands,Command) /** * Represents an association between a key sequence pressed by the user * and the character sequence and commands associated with it for a particular * KeyboardTranslator. */ class Entry { public: /** * Constructs a new entry for a keyboard translator. */ Entry(); /** * Returns true if this entry is null. * This is true for newly constructed entries which have no properties set. */ bool isNull() const; /** Returns the commands associated with this entry */ Command command() const; /** Sets the command associated with this entry. */ void setCommand(Command command); /** * Returns the character sequence associated with this entry, optionally replacing * wildcard '*' characters with numbers to indicate the keyboard modifiers being pressed. * * TODO: The numbers used to replace '*' characters are taken from the Konsole/KDE 3 code. * Document them. * * @param expandWildCards Specifies whether wild cards (occurrences of the '*' character) in * the entry should be replaced with a number to indicate the modifier keys being pressed. * * @param modifiers The keyboard modifiers being pressed. */ QByteArray text(bool expandWildCards = false, Qt::KeyboardModifiers modifiers = Qt::NoModifier) const; /** Sets the character sequence associated with this entry */ void setText(const QByteArray& text); /** * Returns the character sequence associated with this entry, * with any non-printable characters replaced with escape sequences. * * eg. \\E for Escape, \\t for tab, \\n for new line. * * @param expandWildCards See text() * @param modifiers See text() */ QByteArray escapedText(bool expandWildCards = false, Qt::KeyboardModifiers modifiers = Qt::NoModifier) const; /** Returns the character code ( from the Qt::Key enum ) associated with this entry */ int keyCode() const; /** Sets the character code associated with this entry */ void setKeyCode(int keyCode); /** * Returns a bitwise-OR of the enabled keyboard modifiers associated with this entry. * If a modifier is set in modifierMask() but not in modifiers(), this means that the entry * only matches when that modifier is NOT pressed. * * If a modifier is not set in modifierMask() then the entry matches whether the modifier * is pressed or not. */ Qt::KeyboardModifiers modifiers() const; /** Returns the keyboard modifiers which are valid in this entry. See modifiers() */ Qt::KeyboardModifiers modifierMask() const; /** See modifiers() */ void setModifiers( Qt::KeyboardModifiers modifiers ); /** See modifierMask() and modifiers() */ void setModifierMask( Qt::KeyboardModifiers modifiers ); /** * Returns a bitwise-OR of the enabled state flags associated with this entry. * If flag is set in stateMask() but not in state(), this means that the entry only * matches when the terminal is NOT in that state. * * If a state is not set in stateMask() then the entry matches whether the terminal * is in that state or not. */ States state() const; /** Returns the state flags which are valid in this entry. See state() */ States stateMask() const; /** See state() */ void setState( States state ); /** See stateMask() */ void setStateMask( States mask ); /** * Returns the key code and modifiers associated with this entry * as a QKeySequence */ //QKeySequence keySequence() const; /** * Returns this entry's conditions ( ie. its key code, modifier and state criteria ) * as a string. */ QString conditionToString() const; /** * Returns this entry's result ( ie. its command or character sequence ) * as a string. * * @param expandWildCards See text() * @param modifiers See text() */ QString resultToString(bool expandWildCards = false, Qt::KeyboardModifiers modifiers = Qt::NoModifier) const; /** * Returns true if this entry matches the given key sequence, specified * as a combination of @p keyCode , @p modifiers and @p state. */ bool matches( int keyCode , Qt::KeyboardModifiers modifiers , States flags ) const; bool operator==(const Entry& rhs) const; private: void insertModifier( QString& item , int modifier ) const; void insertState( QString& item , int state ) const; QByteArray unescape(const QByteArray& text) const; int _keyCode; Qt::KeyboardModifiers _modifiers; Qt::KeyboardModifiers _modifierMask; States _state; States _stateMask; Command _command; QByteArray _text; }; /** Constructs a new keyboard translator with the given @p name */ KeyboardTranslator(const QString& name); //KeyboardTranslator(const KeyboardTranslator& other); /** Returns the name of this keyboard translator */ QString name() const; /** Sets the name of this keyboard translator */ void setName(const QString& name); /** Returns the descriptive name of this keyboard translator */ QString description() const; /** Sets the descriptive name of this keyboard translator */ void setDescription(const QString& description); /** * Looks for an entry in this keyboard translator which matches the given * key code, keyboard modifiers and state flags. * * Returns the matching entry if found or a null Entry otherwise ( ie. * entry.isNull() will return true ) * * @param keyCode A key code from the Qt::Key enum * @param modifiers A combination of modifiers * @param state Optional flags which specify the current state of the terminal */ Entry findEntry(int keyCode , Qt::KeyboardModifiers modifiers , States state = NoState) const; /** * Adds an entry to this keyboard translator's table. Entries can be looked up according * to their key sequence using findEntry() */ void addEntry(const Entry& entry); /** * Replaces an entry in the translator. If the @p existing entry is null, * then this is equivalent to calling addEntry(@p replacement) */ void replaceEntry(const Entry& existing , const Entry& replacement); /** * Removes an entry from the table. */ void removeEntry(const Entry& entry); /** Returns a list of all entries in the translator. */ QList entries() const; /** The modifier code for the actual Ctrl key on this OS. */ static const Qt::KeyboardModifier CTRL_MOD; private: QMultiHash _entries; // entries in this keyboard translation, // entries are indexed according to // their keycode QString _name; QString _description; }; Q_DECLARE_OPERATORS_FOR_FLAGS(KeyboardTranslator::States) Q_DECLARE_OPERATORS_FOR_FLAGS(KeyboardTranslator::Commands) /** * Parses the contents of a Keyboard Translator (.keytab) file and * returns the entries found in it. * * Usage example: * * @code * QFile source( "/path/to/keytab" ); * source.open( QIODevice::ReadOnly ); * * KeyboardTranslator* translator = new KeyboardTranslator( "name-of-translator" ); * * KeyboardTranslatorReader reader(source); * while ( reader.hasNextEntry() ) * translator->addEntry(reader.nextEntry()); * * source.close(); * * if ( !reader.parseError() ) * { * // parsing succeeded, do something with the translator * } * else * { * // parsing failed * } * @endcode */ class KeyboardTranslatorReader { public: /** Constructs a new reader which parses the given @p source */ KeyboardTranslatorReader( QIODevice* source ); /** * Returns the description text. * TODO: More documentation */ QString description() const; /** Returns true if there is another entry in the source stream */ bool hasNextEntry(); /** Returns the next entry found in the source stream */ KeyboardTranslator::Entry nextEntry(); /** * Returns true if an error occurred whilst parsing the input or * false if no error occurred. */ bool parseError(); /** * Parses a condition and result string for a translator entry * and produces a keyboard translator entry. * * The condition and result strings are in the same format as in */ static KeyboardTranslator::Entry createEntry( const QString& condition , const QString& result ); private: struct Token { enum Type { TitleKeyword, TitleText, KeyKeyword, KeySequence, Command, OutputText }; Type type; QString text; }; QList tokenize(const QString&); void readNext(); bool decodeSequence(const QString& , int& keyCode, Qt::KeyboardModifiers& modifiers, Qt::KeyboardModifiers& modifierMask, KeyboardTranslator::States& state, KeyboardTranslator::States& stateFlags); static bool parseAsModifier(const QString& item , Qt::KeyboardModifier& modifier); static bool parseAsStateFlag(const QString& item , KeyboardTranslator::State& state); static bool parseAsKeyCode(const QString& item , int& keyCode); static bool parseAsCommand(const QString& text , KeyboardTranslator::Command& command); QIODevice* _source; QString _description; KeyboardTranslator::Entry _nextEntry; bool _hasNext; }; /** Writes a keyboard translation to disk. */ class KeyboardTranslatorWriter { public: /** * Constructs a new writer which saves data into @p destination. * The caller is responsible for closing the device when writing is complete. */ KeyboardTranslatorWriter(QIODevice* destination); ~KeyboardTranslatorWriter(); /** * Writes the header for the keyboard translator. * @param description Description of the keyboard translator. */ void writeHeader( const QString& description ); /** Writes a translator entry. */ void writeEntry( const KeyboardTranslator::Entry& entry ); private: QIODevice* _destination; QTextStream* _writer; }; /** * Manages the keyboard translations available for use by terminal sessions, * see KeyboardTranslator. */ class KONSOLEPRIVATE_EXPORT KeyboardTranslatorManager { public: /** * Constructs a new KeyboardTranslatorManager and loads the list of * available keyboard translations. * * The keyboard translations themselves are not loaded until they are * first requested via a call to findTranslator() */ KeyboardTranslatorManager(); ~KeyboardTranslatorManager(); KeyboardTranslatorManager(const KeyboardTranslatorManager&) = delete; KeyboardTranslatorManager& operator=(const KeyboardTranslatorManager&) = delete; /** * Adds a new translator. If a translator with the same name * already exists, it will be replaced by the new translator. * * TODO: More documentation. */ void addTranslator(KeyboardTranslator* translator); /** * Deletes a translator. Returns true on successful deletion or false otherwise. * * TODO: More documentation */ bool deleteTranslator(const QString& name); /** Returns the default translator for Konsole. */ const KeyboardTranslator* defaultTranslator(); /** * Returns the keyboard translator with the given name or 0 if no translator * with that name exists. * * The first time that a translator with a particular name is requested, * the on-disk .keyboard file is loaded and parsed. */ const KeyboardTranslator* findTranslator(const QString& name); /** * Returns a list of the names of available keyboard translators. * * The first time this is called, a search for available * translators is started. */ QList allTranslators(); /******** Modify by ut000610 daizhengwen 2020-06-02: 用于修改数据****************/ KeyboardTranslator *getTranslator(const QString &name); /********************* Modify by ut000610 daizhengwen End ************************/ /** Returns the global KeyboardTranslatorManager instance. */ static KeyboardTranslatorManager* instance(); private: static const QByteArray defaultTranslatorText; void findTranslators(); // locate the available translators KeyboardTranslator* loadTranslator(const QString& name); // loads the translator // with the given name KeyboardTranslator* loadTranslator(QIODevice* device,const QString& name); bool saveTranslator(const KeyboardTranslator* translator); QString findTranslatorPath(const QString& name); QHash _translators; // maps translator-name -> KeyboardTranslator // instance bool _haveLoadedAll; }; inline int KeyboardTranslator::Entry::keyCode() const { return _keyCode; } inline void KeyboardTranslator::Entry::setKeyCode(int keyCode) { _keyCode = keyCode; } inline void KeyboardTranslator::Entry::setModifiers( Qt::KeyboardModifiers modifier ) { _modifiers = modifier; } inline Qt::KeyboardModifiers KeyboardTranslator::Entry::modifiers() const { return _modifiers; } inline void KeyboardTranslator::Entry::setModifierMask( Qt::KeyboardModifiers mask ) { _modifierMask = mask; } inline Qt::KeyboardModifiers KeyboardTranslator::Entry::modifierMask() const { return _modifierMask; } inline bool KeyboardTranslator::Entry::isNull() const { return ( *this == Entry() ); } inline void KeyboardTranslator::Entry::setCommand( Command command ) { _command = command; } inline KeyboardTranslator::Command KeyboardTranslator::Entry::command() const { return _command; } inline void KeyboardTranslator::Entry::setText( const QByteArray& text ) { _text = unescape(text); } inline int oneOrZero(int value) { return value ? 1 : 0; } inline QByteArray KeyboardTranslator::Entry::text(bool expandWildCards,Qt::KeyboardModifiers modifiers) const { QByteArray expandedText = _text; if (expandWildCards) { int modifierValue = 1; modifierValue += oneOrZero(modifiers & Qt::ShiftModifier); modifierValue += oneOrZero(modifiers & Qt::AltModifier) << 1; modifierValue += oneOrZero(modifiers & KeyboardTranslator::CTRL_MOD) << 2; for (int i=0;i<_text.length();i++) { if (expandedText[i] == '*') expandedText[i] = '0' + modifierValue; } } return expandedText; } inline void KeyboardTranslator::Entry::setState( States state ) { _state = state; } inline KeyboardTranslator::States KeyboardTranslator::Entry::state() const { return _state; } inline void KeyboardTranslator::Entry::setStateMask( States stateMask ) { _stateMask = stateMask; } inline KeyboardTranslator::States KeyboardTranslator::Entry::stateMask() const { return _stateMask; } } Q_DECLARE_METATYPE(Konsole::KeyboardTranslator::Entry) Q_DECLARE_METATYPE(const Konsole::KeyboardTranslator*) #endif // KEYBOARDTRANSLATOR_H deepin-terminal-5.2.11/3rdparty/terminalwidget/lib/LineFont.h000066400000000000000000000033231370157770500241160ustar00rootroot00000000000000// WARNING: Autogenerated by "fontembedder ./linefont.src". // You probably do not want to hand-edit this! static const quint32 LineChars[] = { 0x00007c00, 0x000fffe0, 0x00421084, 0x00e739ce, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00427000, 0x004e7380, 0x00e77800, 0x00ef7bc0, 0x00421c00, 0x00439ce0, 0x00e73c00, 0x00e7bde0, 0x00007084, 0x000e7384, 0x000079ce, 0x000f7bce, 0x00001c84, 0x00039ce4, 0x00003dce, 0x0007bdee, 0x00427084, 0x004e7384, 0x004279ce, 0x00e77884, 0x00e779ce, 0x004f7bce, 0x00ef7bc4, 0x00ef7bce, 0x00421c84, 0x00439ce4, 0x00423dce, 0x00e73c84, 0x00e73dce, 0x0047bdee, 0x00e7bde4, 0x00e7bdee, 0x00427c00, 0x0043fce0, 0x004e7f80, 0x004fffe0, 0x004fffe0, 0x00e7fde0, 0x006f7fc0, 0x00efffe0, 0x00007c84, 0x0003fce4, 0x000e7f84, 0x000fffe4, 0x00007dce, 0x0007fdee, 0x000f7fce, 0x000fffee, 0x00427c84, 0x0043fce4, 0x004e7f84, 0x004fffe4, 0x00427dce, 0x00e77c84, 0x00e77dce, 0x0047fdee, 0x004e7fce, 0x00e7fde4, 0x00ef7f84, 0x004fffee, 0x00efffe4, 0x00e7fdee, 0x00ef7fce, 0x00efffee, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x000f83e0, 0x00a5294a, 0x004e1380, 0x00a57800, 0x00ad0bc0, 0x004390e0, 0x00a53c00, 0x00a5a1e0, 0x000e1384, 0x0000794a, 0x000f0b4a, 0x000390e4, 0x00003d4a, 0x0007a16a, 0x004e1384, 0x00a5694a, 0x00ad2b4a, 0x004390e4, 0x00a52d4a, 0x00a5a16a, 0x004f83e0, 0x00a57c00, 0x00ad83e0, 0x000f83e4, 0x00007d4a, 0x000f836a, 0x004f93e4, 0x00a57d4a, 0x00ad836a, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00001c00, 0x00001084, 0x00007000, 0x00421000, 0x00039ce0, 0x000039ce, 0x000e7380, 0x00e73800, 0x000e7f80, 0x00e73884, 0x0003fce0, 0x004239ce }; deepin-terminal-5.2.11/3rdparty/terminalwidget/lib/LineFont.src000066400000000000000000000106211370157770500244550ustar00rootroot00000000000000#2500: single horizontal line 2500 ----- #2501: triple horizontal line 2501 ----- ----- ----- #2502: single vertical line 2502 | | | | | #2503: triple vertical line 2503 ||| ||| ||| ||| ||| #2504-250B are dashed - not handled #250C: top-left corner (lines on bottom + right) 250C .-- | | #250D: as above, but top line triple-width 250D .-- .-- |-- | #250E: now the vert line triple-width 250E ..-- ||| ||| #250F: and now both lines triple-width 250F .___ |.-- ||._ ||| #2510: top-right corner 2510 --. | | 2511 ==. ==. ==| | 2512 ==.. ||| ||| 2513 ===. ==.| =.|| ||| #2514: bottom-left corner 2514 | | .== 2515 | |== |== === 2516 ||| ||| |.== 2517 ||| ||.= |.== .=== #2518: bottm-right corner 2518 | | ==. 2519 | ==| ==| === 251A ||| ||| ==== 251B ||| =.|| ==.| ===. #251C: Join of vertical line and one from the right 251C | | |== | | 251D | |== |== |== | 251E ||| ||| ||== | | 251F | | ||== ||| ||| 2520 ||| ||| ||== ||| ||| 2521 ||| |||= ||== .|== | 2522 | .|== ||== |||= ||| 2523 ||| ||.= ||== ||.= ||| #2524: Join of vertical line and one from the left 2524 | | ==| | | 2525 | ==| ==| ==| | 2526 ||| ||| ==+| | | 2527 | | ==+| ||| ||| 2528 ||| ||| ==+| ||| ||| 2529 ||| =+|| ==+| ===+ | 252A | =+|| ==+| ===+ ||| 252B ||| =+|| ==+| =+|| ||| #252C: horizontal line joined to from below 252C ===== | | 252D === ==|== ==| | 252E === ==|== |== | 252F ==+== ==|== ==|== | 2530 ===== ===== ==|== | 2531 ===| ==||= =||| ||| 2532 |=== =||== ||== || 2533 ===== ==|== =+|+= ||| #2534: bottom line, connected to from top 2534 | | ===== 2535 | ==| ===== === 2536 | |== ===== === 2537 | ==|== ===== ===== 2538 ||| ||| ===== 2539 ||| ==|| ===== ===| 253A ||| ||== =|=== |=== 253B ||| ==|== ===== ===== #253C: vertical + horizontal lines intersecting 253C | | ===== | | 253D | ==| ===== ==| | 253E | |== ===== |== | 253F | ==|== ===== ==|== | 2540 ||| ||| ===== | | 2541 | | ===== ||| ||| 2542 ||| ||| ===== ||| ||| 2543 ||| =||| ===== ==|+ | 2544 ||| ||== ===== |== | 2545 | ==|+ ===== =||| ||| 2546 | |== ===== ||== ||| 2547 ||| =|||= ===== =|||= | 2548 | =|||= ===== =|||= ||| 2549 ||| =||| ===== =||| ||| 254A ||| |||= ===== |||= ||| 254B ||| =|||= ===== =|||= ||| #254C-254F are dashed 2550 _____ _____ 2551 | | | | | | | | | | 2552 |-- | |-- | 2553 ---- | | | | 2554 +--- | + +- | | 2555 --+ | --+ | 2556 -+-+ | | | | 2557 ---+ | -+ | | | 2558 | +-- | +-- 2559 | | | | +-+- 255A | | | +- | +--- 255B | --+ | --+ 255C | | | | -+-+ 255D | | -+ | | ---+ 255E | +-- | +-- | 255F | | | | | +- | | | | 2560 | | | +- | | | +- | | 2561 | --+ | --+ | 2562 | | | | -+ + | | | | 2563 | | -+ | | -+ | | | 2564 ----- --+-- | 2565 -+-+- | | | | 2566 ----- -+ +- | | 2567 | --+-- ----- 2568 | | | | -+-+- 2569 | | -+ +- ----- 256A | --+-- | --+-- | 256B | | | | -+-+- | | | | 256C | | -+ +- -+ +- | | #256F-2570 are curly, #2571-2573 are slashes and X 2574 ___ 2575 | | | 2576 ___ 2577 | | | 2578 ___ ___ ___ 2579 ||| ||| ||| 257A ___ ___ ___ 257B ||| ||| ||| 257C ___ _____ ___ 257D | | ||| ||| ||| 257E ___ _____ ___ 257F ||| ||| ||| | | deepin-terminal-5.2.11/3rdparty/terminalwidget/lib/ProcessInfo.cpp000066400000000000000000000264631370157770500251770ustar00rootroot00000000000000/* 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. */ // Own #include "ProcessInfo.h" // Unix #include #include #include #include #include #include #include // Qt #include #include #include #include #include #include #include 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::~ProcessInfo() { } 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, QString()); current->update(); currentPid = current->parentPid(&ok); dir = current->currentDir(&ok); delete current; } return dir; } 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; } 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() { _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); } } UnixProcessInfo::UnixProcessInfo(int pid, const QString &titleFormat) : ProcessInfo(pid) { setUserNameRequired(titleFormat.contains(QLatin1String("%u"))); } 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); } } 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[static_cast(getpwBufferSize)]; if (getpwBuffer == nullptr) { return; } getpwStatus = getpwuid_r(static_cast<__uid_t>(uid), &passwdStruct, getpwBuffer, static_cast(getpwBufferSize), &getpwResult); if ((getpwStatus == 0) && (getpwResult != nullptr)) { setUserName(QLatin1String(passwdStruct.pw_name)); } else { setUserName(QString()); qWarning() << "getpwuid_r returned error : " << getpwStatus; } delete [] getpwBuffer; } LinuxProcessInfo::LinuxProcessInfo(int pid, const QString &titleFormat) : UnixProcessInfo(pid, titleFormat) { } bool LinuxProcessInfo::readCurrentDir(int pid) { char path_buffer[MAXPATHLEN + 1]; path_buffer[MAXPATHLEN] = 0; QByteArray procCwd = QFile::encodeName(QStringLiteral("/proc/%1/cwd").arg(pid)); const int 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; } bool LinuxProcessInfo::readProcInfo(int pid) { // 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(); } } 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 (int i = 0; i < argList.size(); i++) { const QString &entry = argList.at(i); if (!entry.isEmpty()) { addArgument(entry); } } } else { setFileError(argumentsFile.error()); } return true; } // // ProcessInfo::newInstance() is way at the bottom so it can see all of the // implementations of the UnixProcessInfo abstract class. // ProcessInfo *ProcessInfo::newInstance(int pid, const QString &titleFormat) { ProcessInfo *info; info = new LinuxProcessInfo(pid, titleFormat); info->readProcessInfo(pid); return info; } deepin-terminal-5.2.11/3rdparty/terminalwidget/lib/ProcessInfo.h000066400000000000000000000243121370157770500246330ustar00rootroot00000000000000/* 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 #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 : QObject { Q_OBJECT 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 * @param titleFormat The local title format - used to determine if it * contains %u which requires expensive prodecures to be used. */ static ProcessInfo *newInstance(int pid, const QString &titleFormat); 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 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 }; typedef QFlags Fields; // 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; }; Q_DECLARE_OPERATORS_FOR_FLAGS(ProcessInfo::Fields) /** * 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, const QString &titleFormat); protected: /** * Implementation of ProcessInfo::readProcessInfo(); calls the * four private methods below in turn. */ void readProcessInfo(int pid) Q_DECL_OVERRIDE; void readUserName(void) Q_DECL_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; }; class LinuxProcessInfo : public UnixProcessInfo { public: LinuxProcessInfo(int pid, const QString &titleFormat); protected: bool readCurrentDir(int pid) Q_DECL_OVERRIDE; private: bool readProcInfo(int pid) Q_DECL_OVERRIDE; bool readArguments(int pid) Q_DECL_OVERRIDE; }; } #endif //PROCESSINFO_H deepin-terminal-5.2.11/3rdparty/terminalwidget/lib/Pty.cpp000066400000000000000000000423621370157770500235150ustar00rootroot00000000000000/* * This file is a part of QTerminal - http://gitorious.org/qterminal * * This file was un-linked from KDE and modified * by Maxim Bourmistrov * */ /* 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. */ // Own #include "Pty.h" #include "SessionManager.h" // System #include #include #include #include #include #include // Qt #include #include #include #include #include #include #include "kpty.h" #include "kptydevice.h" using namespace Konsole; void Pty::setWindowSize(int lines, int cols) { _windowColumns = cols; _windowLines = lines; if (pty()->masterFd() >= 0) pty()->setWinSize(lines, cols); } QSize Pty::windowSize() const { return {_windowColumns, _windowLines}; } void Pty::setFlowControlEnabled(bool enable) { _xonXoff = enable; if (pty()->masterFd() >= 0) { struct ::termios ttmode; pty()->tcGetAttr(&ttmode); if (!enable) ttmode.c_iflag &= ~(IXOFF | IXON); else ttmode.c_iflag |= (IXOFF | IXON); if (!pty()->tcSetAttr(&ttmode)) qWarning() << "Unable to set terminal attributes."; } } bool Pty::flowControlEnabled() const { if (pty()->masterFd() >= 0) { struct ::termios ttmode; pty()->tcGetAttr(&ttmode); return ttmode.c_iflag & IXOFF && ttmode.c_iflag & IXON; } qWarning() << "Unable to get flow control status, terminal not connected."; return false; } void Pty::setUtf8Mode(bool enable) { #ifdef IUTF8 // XXX not a reasonable place to check it. _utf8 = enable; if (pty()->masterFd() >= 0) { struct ::termios ttmode; pty()->tcGetAttr(&ttmode); if (!enable) ttmode.c_iflag &= ~IUTF8; else ttmode.c_iflag |= IUTF8; if (!pty()->tcSetAttr(&ttmode)) qWarning() << "Unable to set terminal attributes."; } #endif } void Pty::setErase(char erase) { _eraseChar = erase; if (pty()->masterFd() >= 0) { struct ::termios ttmode; pty()->tcGetAttr(&ttmode); ttmode.c_cc[VERASE] = erase; if (!pty()->tcSetAttr(&ttmode)) qWarning() << "Unable to set terminal attributes."; } } char Pty::erase() const { if (pty()->masterFd() >= 0) { struct ::termios ttyAttributes; pty()->tcGetAttr(&ttyAttributes); return ttyAttributes.c_cc[VERASE]; } return _eraseChar; } void Pty::addEnvironmentVariables(const QStringList &environment) { QListIterator iter(environment); while (iter.hasNext()) { QString pair = iter.next(); // split on the first '=' character int pos = pair.indexOf(QLatin1Char('=')); if (pos >= 0) { QString variable = pair.left(pos); QString value = pair.mid(pos + 1); setEnv(variable, value); } } } int Pty::start(const QString &program, const QStringList &programArguments, const QStringList &environment, ulong winid, bool addToUtmp //const QString& dbusService, //const QString& dbusSession ) { clearProgram(); // For historical reasons, the first argument in programArguments is the // name of the program to execute, so create a list consisting of all // but the first argument to pass to setProgram() Q_ASSERT(programArguments.count() >= 1); setProgram(program, programArguments.mid(1)); addEnvironmentVariables(environment); setEnv(QLatin1String("WINDOWID"), QString::number(winid)); setEnv(QLatin1String("COLORTERM"), QLatin1String("truecolor")); // unless the LANGUAGE environment variable has been set explicitly // set it to a null string // this fixes the problem where KCatalog sets the LANGUAGE environment // variable during the application's startup to something which // differs from LANG,LC_* etc. and causes programs run from // the terminal to display messages in the wrong language // // this can happen if LANG contains a language which KDE // does not have a translation for // // BR:149300 setEnv(QLatin1String("LANGUAGE"), QString(), false /* do not overwrite existing value if any */); setUseUtmp(addToUtmp); struct ::termios ttmode; pty()->tcGetAttr(&ttmode); if (!_xonXoff) ttmode.c_iflag &= ~(IXOFF | IXON); else ttmode.c_iflag |= (IXOFF | IXON); #ifdef IUTF8 // XXX not a reasonable place to check it. if (!_utf8) ttmode.c_iflag &= ~IUTF8; else ttmode.c_iflag |= IUTF8; #endif if (_eraseChar != 0) ttmode.c_cc[VERASE] = _eraseChar; if (!pty()->tcSetAttr(&ttmode)) qWarning() << "Unable to set terminal attributes."; pty()->setWinSize(_windowLines, _windowColumns); KProcess::start(); if (!waitForStarted()) return -1; return 0; } void Pty::setEmptyPTYProperties() { struct ::termios ttmode; pty()->tcGetAttr(&ttmode); if (!_xonXoff) ttmode.c_iflag &= ~(IXOFF | IXON); else ttmode.c_iflag |= (IXOFF | IXON); #ifdef IUTF8 // XXX not a reasonable place to check it. if (!_utf8) ttmode.c_iflag &= ~IUTF8; else ttmode.c_iflag |= IUTF8; #endif if (_eraseChar != 0) ttmode.c_cc[VERASE] = _eraseChar; if (!pty()->tcSetAttr(&ttmode)) qWarning() << "Unable to set terminal attributes."; } void Pty::setWriteable(bool writeable) { struct stat sbuf; stat(pty()->ttyName(), &sbuf); if (writeable) chmod(pty()->ttyName(), sbuf.st_mode | S_IWGRP); else chmod(pty()->ttyName(), sbuf.st_mode & ~(S_IWGRP | S_IWOTH)); } Pty::Pty(int masterFd, QObject *parent) : KPtyProcess(masterFd, parent) { init(); } Pty::Pty(QObject *parent) : KPtyProcess(parent) { init(); } void Pty::init() { _windowColumns = 0; _windowLines = 0; _eraseChar = 0; _xonXoff = true; _utf8 = true; _bUninstall = false; connect(pty(), SIGNAL(readyRead()), this, SLOT(dataReceived())); setPtyChannels(KPtyProcess::AllChannels); } Pty::~Pty() { } bool Pty::isTerminalRemoved() { QFile terminalExecFile("/usr/bin/deepin-terminal"); if (terminalExecFile.exists()) { return false; } return true; } bool isPatternAcceptable(QString strCommand, QString strPattern) { QString strTrimmedCmd = strCommand.trimmed(); QRegExp cmdRegExp; cmdRegExp.setPattern(strPattern); QRegExpValidator cmdREValidator(cmdRegExp, nullptr); int pos = 0; QValidator::State validateState = cmdREValidator.validate(strTrimmedCmd, pos); return (validateState == QValidator::Acceptable); } //判断当前命令是否是要删除终端 bool Pty::bWillRemoveTerminal(QString strCommand) { QString packageName = "deepin-terminal"; QStringList strCommandList; strCommandList.append(strCommand); if (strCommand.contains("&&")) { QStringList cmdList = strCommand.split("&&"); for (int i = 0; i < cmdList.size(); i++) { QString currCmd = cmdList.at(i).trimmed(); if (currCmd.length() > 0 && currCmd.contains(packageName)) { strCommandList.append(currCmd); } } } if (strCommand.contains(";")) { QStringList cmdList = strCommand.split(";"); for (int i = 0; i < cmdList.size(); i++) { QString currCmd = cmdList.at(i).trimmed(); if (currCmd.length() > 0 && currCmd.contains(packageName)) { strCommandList.append(currCmd); } } } QList acceptableList; QStringList packageNameList; packageNameList << packageName; for (int i = 0; i < strCommandList.size(); i++) { QString strCurrCommand = strCommandList.at(i); for (int j = 0; j < packageNameList.size(); j++) { QString packageName = packageNameList.at(j); QString removePattern = QString("sudo\\s+apt-get\\s+remove\\s+%1").arg(packageName); acceptableList << isPatternAcceptable(strCurrCommand, removePattern); removePattern = QString("sudo\\s+apt\\s+remove\\s+%1").arg(packageName); acceptableList << isPatternAcceptable(strCurrCommand, removePattern); /******** Modify by nt001000 renfeixiang 2020-05-27:修改 放到bWillPurgeTerminal函数中 Begin***************/ // removePattern = QString("sudo\\s+dpkg\\s+-P\\s+%1").arg(packageName); // acceptableList << isPatternAcceptable(strCurrCommand, removePattern); /******** Modify by nt001000 renfeixiang 2020-05-27:修改 放到bWillPurgeTerminal函数中 End***************/ removePattern = QString("sudo\\s+dpkg\\s+-r\\s+%1").arg(packageName); acceptableList << isPatternAcceptable(strCurrCommand, removePattern); removePattern = QString("sudo\\s+rm\\s+.+\\s+/usr/bin/deepin-terminal"); acceptableList << isPatternAcceptable(strCurrCommand, removePattern); removePattern = QString("sudo\\s+rm\\s+/usr/bin/deepin-terminal"); acceptableList << isPatternAcceptable(strCurrCommand, removePattern); } } return acceptableList.contains(true); } /******** Add by nt001000 renfeixiang 2020-05-27:增加 Purge卸载命令的判断,显示不同的卸载提示框 Begin***************/ bool Pty::bWillPurgeTerminal(QString strCommand) { QString packageName = "deepin-terminal"; QStringList strCommandList; strCommandList.append(strCommand); if (strCommand.contains("&&")) { QStringList cmdList = strCommand.split("&&"); for (int i = 0; i < cmdList.size(); i++) { QString currCmd = cmdList.at(i).trimmed(); if (currCmd.length() > 0 && currCmd.contains(packageName)) { strCommandList.append(currCmd); } } } if (strCommand.contains(";")) { QStringList cmdList = strCommand.split(";"); for (int i = 0; i < cmdList.size(); i++) { QString currCmd = cmdList.at(i).trimmed(); if (currCmd.length() > 0 && currCmd.contains(packageName)) { strCommandList.append(currCmd); } } } QList acceptableList; QStringList packageNameList; packageNameList << packageName; for (int i = 0; i < strCommandList.size(); i++) { QString strCurrCommand = strCommandList.at(i); for (int j = 0; j < packageNameList.size(); j++) { QString packageName = packageNameList.at(j); QString removePattern = QString("sudo\\s+apt-get\\s+purge\\s+%1").arg(packageName); acceptableList << isPatternAcceptable(strCurrCommand, removePattern); removePattern = QString("sudo\\s+apt-get\\s+purge\\s+-y\\s+%1").arg(packageName); acceptableList << isPatternAcceptable(strCurrCommand, removePattern); removePattern = QString("sudo\\s+apt-get\\s+remove\\s+--purge\\s+%1").arg(packageName); acceptableList << isPatternAcceptable(strCurrCommand, removePattern); removePattern = QString("sudo\\s+apt-get\\s+--purge\\s+remove\\s+%1").arg(packageName); acceptableList << isPatternAcceptable(strCurrCommand, removePattern); removePattern = QString("sudo\\s+apt\\s+purge\\s+%1").arg(packageName); acceptableList << isPatternAcceptable(strCurrCommand, removePattern); removePattern = QString("sudo\\s+apt\\s+purge\\s+-y\\s+%1").arg(packageName); acceptableList << isPatternAcceptable(strCurrCommand, removePattern); removePattern = QString("sudo\\s+apt\\s+remove\\s+--purge\\s+%1").arg(packageName); acceptableList << isPatternAcceptable(strCurrCommand, removePattern); removePattern = QString("sudo\\s+apt\\s+--purge\\s+remove\\s+%1").arg(packageName); acceptableList << isPatternAcceptable(strCurrCommand, removePattern); removePattern = QString("sudo\\s+dpkg\\s+-P\\s+%1").arg(packageName); acceptableList << isPatternAcceptable(strCurrCommand, removePattern); } } return acceptableList.contains(true); } /******** Add by nt001000 renfeixiang 2020-05-27:增加 Purge卸载命令的判断,显示不同的卸载提示框 End***************/ void Pty::sendData(const char *data, int length) { if (!length) { return; } bool isCustomCommand = false; QString currCommand = QString::fromLatin1(data); if (currCommand.length() > 0 && currCommand.endsWith('\n')) { isCustomCommand = true; } //检测到按了回车键 if (((*data) == '\r' || isCustomCommand) && _bUninstall == false) { QString strCurrCommand = SessionManager::instance()->getCurrShellCommand(_sessionId); if (isCustomCommand) { strCurrCommand = currCommand; } /******** Modify by nt001000 renfeixiang 2020-05-27:修改 根据remove和purge卸载命令,发送信号不同参数值 Begin***************/ bool bPurgeTerminal = bWillPurgeTerminal(strCurrCommand); bool bRemoveTerminal = bWillRemoveTerminal(strCurrCommand); if (!isTerminalRemoved() && (bPurgeTerminal || bRemoveTerminal)) { QString strname = "remove"; if (bPurgeTerminal) { strname = "purge"; } QMetaObject::invokeMethod(this, "ptyUninstallTerminal", Qt::AutoConnection, Q_RETURN_ARG(bool, _bUninstall), Q_ARG(QString, strname)); /******** Modify by nt001000 renfeixiang 2020-05-27:修改 根据remove和purge卸载命令,发送信号不同参数值 End***************/ if (_bUninstall) { qDebug() << "确认卸载终端!" << _bUninstall << endl; connect(SessionManager::instance(), &SessionManager::sessionIdle, this, [ = ](bool isIdle) { //卸载完成,关闭所有终端窗口 if (isIdle) { if (isTerminalRemoved()) { pclose(popen("killall deepin-terminal", "r")); } } if (!isTerminalRemoved()) { _bUninstall = false; } }); } else { qDebug() << "不卸载终端!" << _bUninstall << endl; return; } } } if (!pty()->write(data, length)) { qWarning() << "Pty::doSendJobs - Could not send input data to terminal process."; return; } } void Pty::dataReceived() { QByteArray data = pty()->readAll(); QString recvData = QString(data); /******** Modify by m000714 daizhengwen 2020-04-30: 处理上传下载时乱码显示命令不执行****************/ // 乱码提示信息不显示 if (recvData.contains("bash: $'\\212") || recvData.contains("bash: **0800000000022d:") || recvData.contains("**^XB0800000000022d") || recvData.startsWith("**\u0018B0800000000022d\r\u008A")) { return; } // "\u008A"这个乱码不替换调会导致显示时有\b的效果导致命令错乱bug#23741 if (recvData.contains("\u008A")) { recvData.replace("\u008A", "\b \b #"); data = recvData.toUtf8(); } if (recvData == "rz waiting to receive.") { recvData += "\r\n"; data = recvData.toUtf8(); } /********************* Modify by m000714 daizhengwen End ************************/ emit receivedData(data.constData(), data.count()); } void Pty::lockPty(bool lock) { Q_UNUSED(lock); // TODO: Support for locking the Pty //if (lock) //suspend(); //else //resume(); } int Pty::foregroundProcessGroup() const { int pid = tcgetpgrp(pty()->masterFd()); if (pid != -1) { return pid; } return 0; } void Pty::setSessionId(int sessionId) { _sessionId = sessionId; } void Pty::setupChildProcess() { KPtyProcess::setupChildProcess(); // reset all signal handlers // this ensures that terminal applications respond to // signals generated via key sequences such as Ctrl+C // (which sends SIGINT) struct sigaction action; sigset_t sigset; sigemptyset(&action.sa_mask); sigemptyset(&sigset); action.sa_handler = SIG_DFL; action.sa_flags = 0; for (int signal = 1; signal < NSIG; signal++) { sigaction(signal, &action, nullptr); sigaddset(&sigset, signal); } sigprocmask(SIG_UNBLOCK, &sigset, nullptr); } deepin-terminal-5.2.11/3rdparty/terminalwidget/lib/Pty.h000066400000000000000000000160031370157770500231530ustar00rootroot00000000000000/* * This file is a part of QTerminal - http://gitorious.org/qterminal * * This file was un-linked from KDE and modified * by Maxim Bourmistrov * */ /* 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 #include #include #include // KDE #include "kptyprocess.h" 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 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() 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. * @param winid Specifies the value of the WINDOWID environment variable * in the process's environment. * @param addToUtmp Specifies whether a utmp entry should be created for * the pty used. See K3Process::setUsePty() * @param dbusService Specifies the value of the KONSOLE_DBUS_SERVICE * environment variable in the process's environment. * @param dbusSession Specifies the value of the KONSOLE_DBUS_SESSION * environment variable in the process's environment. */ int start( const QString& program, const QStringList& arguments, const QStringList& environment, ulong winid, bool addToUtmp ); /** * set properties for "EmptyPTY" */ void setEmptyPTYProperties(); /** TODO: Document me */ 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 lines and columns of characters) * used by this teletype. */ void setWindowSize(int lines, int cols); /** Returns the size of the window used by this teletype. See setWindowSize() */ QSize windowSize() const; /** TODO Document me */ void setErase(char erase); /** */ char erase() const; /** * 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; void setSessionId(int sessionId); public slots: /** * Put the pty into UTF-8 mode on systems which support it. */ void setUtf8Mode(bool on); /** * Suspend or resume processing of data from the standard * output of the terminal process. * * See K3Process::suspend() and K3Process::resume() * * @param lock If true, processing of output is suspended, * otherwise processing is resumed. */ void lockPty(bool lock); /** * Sends data to the process currently controlling the * teletype ( whose id is returned by foregroundProcessGroup() ) * * @param buffer Pointer to the data to send. * @param length Length of @p buffer. */ void sendData(const char* buffer, int length); 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); /******** Modify by nt001000 renfeixiang 2020-05-27:修改 增加参数区别remove和purge卸载命令 Begin***************/ bool ptyUninstallTerminal(QString commandname); /******** Modify by nt001000 renfeixiang 2020-05-14:修改 增加参数区别remove和purge卸载命令 End***************/ protected: void setupChildProcess() override; private slots: // called when data is received from the terminal process void dataReceived(); private: void init(); bool isTerminalRemoved(); bool bWillRemoveTerminal(QString strCommand); /******** Add by nt001000 renfeixiang 2020-05-14:增加 Purge卸载命令的判断,显示不同的卸载提示框 Begin***************/ bool bWillPurgeTerminal(QString strCommand); /******** Add by nt001000 renfeixiang 2020-05-14:增加 Purge卸载命令的判断,显示不同的卸载提示框 End***************/ // 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; int _sessionId; bool _bUninstall; }; } #endif // PTY_H deepin-terminal-5.2.11/3rdparty/terminalwidget/lib/Screen.cpp000066400000000000000000001061321370157770500241540ustar00rootroot00000000000000/* 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. */ // Own #include "Screen.h" // Standard #include #include #include #include #include // Qt #include #include // KDE //#include // Konsole #include "konsole_wcwidth.h" #include "TerminalCharacterDecoder.h" using namespace Konsole; //FIXME: this is emulation specific. Use false for xterm, true for ANSI. //FIXME: see if we can get this from terminfo. #define BS_CLEARS false //Macro to convert x,y position on screen to position within an image. // //Originally the image was stored as one large contiguous block of //memory, so a position within the image could be represented as an //offset from the beginning of the block. For efficiency reasons this //is no longer the case. //Many internal parts of this class still use this representation for parameters and so on, //notably moveImage() and clearImage(). //This macro converts from an X,Y position into an image offset. #ifndef loc #define loc(X,Y) ((Y)*columns+(X)) #endif Character Screen::defaultChar = Character(' ', CharacterColor(COLOR_SPACE_DEFAULT,DEFAULT_FORE_COLOR), CharacterColor(COLOR_SPACE_DEFAULT,DEFAULT_BACK_COLOR), DEFAULT_RENDITION); //#define REVERSE_WRAPPED_LINES // for wrapped line debug Screen::Screen(int l, int c) : lines(l), columns(c), screenLines(new ImageLine[lines+1] ), _scrolledLines(0), _droppedLines(0), history(new HistoryScrollNone()), cuX(0), cuY(0), currentRendition(0), _topMargin(0), _bottomMargin(0), selBegin(0), selTopLeft(0), selBottomRight(0), blockSelectionMode(false), effectiveForeground(CharacterColor()), effectiveBackground(CharacterColor()), effectiveRendition(0), lastPos(-1) { lineProperties.resize(lines+1); for (int i=0;i _bottomMargin ? lines-1 : _bottomMargin; cuX = qMin(columns-1,cuX); // nowrap! cuY = qMin(stop,cuY+n); } void Screen::cursorLeft(int n) //=CUB { if (n == 0) n = 1; // Default cuX = qMin(columns-1,cuX); // nowrap! cuX = qMax(0,cuX-n); } void Screen::cursorRight(int n) //=CUF { if (n == 0) n = 1; // Default cuX = qMin(columns-1,cuX+n); } void Screen::setMargins(int top, int bot) //=STBM { if (top == 0) top = 1; // Default if (bot == 0) bot = lines; // Default top = top - 1; // Adjust to internal lineno bot = bot - 1; // Adjust to internal lineno if ( !( 0 <= top && top < bot && bot < lines ) ) { //Debug()<<" setRegion("< 0) cuY -= 1; } void Screen::nextLine() //=NEL { toStartOfLine(); index(); } void Screen::eraseChars(int n) { if (n == 0) n = 1; // Default int p = qMax(0,qMin(cuX+n-1,columns-1)); clearImage(loc(cuX,cuY),loc(p,cuY),' '); } void Screen::deleteChars(int n) { Q_ASSERT( n >= 0 ); // always delete at least one char if (n == 0) n = 1; // if cursor is beyond the end of the line there is nothing to do if ( cuX >= screenLines[cuY].count() ) return; if ( cuX+n > screenLines[cuY].count() ) n = screenLines[cuY].count() - cuX; Q_ASSERT( n >= 0 ); Q_ASSERT( cuX+n <= screenLines[cuY].count() ); screenLines[cuY].remove(cuX,n); } void Screen::insertChars(int n) { if (n == 0) n = 1; // Default if ( screenLines[cuY].size() < cuX ) screenLines[cuY].resize(cuX); screenLines[cuY].insert(cuX,n,' '); if ( screenLines[cuY].count() > columns ) screenLines[cuY].resize(columns); } void Screen::repeatChars(int count) //=REP { if (count == 0) { count = 1; } /** * From ECMA-48 version 5, section 8.3.103 * If the character preceding REP is a control function or part of a * control function, the effect of REP is not defined by this Standard. * * So, a "normal" program should always use REP immediately after a visible * character (those other than escape sequences). So, lastDrawnChar can be * safely used. */ for (int i = 0; i < count; i++) { displayCharacter(lastDrawnChar); } } void Screen::deleteLines(int n) { if (n == 0) n = 1; // Default scrollUp(cuY,n); } void Screen::insertLines(int n) { if (n == 0) n = 1; // Default scrollDown(cuY,n); } void Screen::setMode(int m) { currentModes[m] = true; switch(m) { case MODE_Origin : cuX = 0; cuY = _topMargin; break; //FIXME: home } } void Screen::resetMode(int m) { currentModes[m] = false; switch(m) { case MODE_Origin : cuX = 0; cuY = 0; break; //FIXME: home } } void Screen::saveMode(int m) { savedModes[m] = currentModes[m]; } void Screen::restoreMode(int m) { currentModes[m] = savedModes[m]; } bool Screen::getMode(int m) const { return currentModes[m]; } void Screen::saveCursor() { savedState.cursorColumn = cuX; savedState.cursorLine = cuY; savedState.rendition = currentRendition; savedState.foreground = currentForeground; savedState.background = currentBackground; } void Screen::restoreCursor() { cuX = qMin(savedState.cursorColumn,columns-1); cuY = qMin(savedState.cursorLine,lines-1); currentRendition = savedState.rendition; currentForeground = savedState.foreground; currentBackground = savedState.background; updateEffectiveRendition(); } void Screen::resizeImage(int new_lines, int new_columns) { if ((new_lines==lines) && (new_columns==columns)) return; if (cuY > new_lines-1) { // attempt to preserve focus and lines _bottomMargin = lines-1; //FIXME: margin lost for (int i = 0; i < cuY-(new_lines-1); i++) { addHistLine(); scrollUp(0,1); } } // create new screen lines and copy from old to new ImageLine* newScreenLines = new ImageLine[new_lines+1]; for (int i=0; i < qMin(lines,new_lines+1) ;i++) newScreenLines[i]=screenLines[i]; for (int i=lines;(i > 0) && (i 0) && (ir &= ~RE_TRANSPARENT; } void Screen::updateEffectiveRendition() { effectiveRendition = currentRendition; if (currentRendition & RE_REVERSE) { effectiveForeground = currentBackground; effectiveBackground = currentForeground; } else { effectiveForeground = currentForeground; effectiveBackground = currentBackground; } if (currentRendition & RE_BOLD) effectiveForeground.setIntensive(); } void Screen::copyFromHistory(Character* dest, int startLine, int count) const { Q_ASSERT( startLine >= 0 && count > 0 && startLine + count <= history->getLines() ); for (int line = startLine; line < startLine + count; line++) { const int length = qMin(columns,history->getLineLen(line)); const int destLineOffset = (line-startLine)*columns; history->getCells(line,0,length,dest + destLineOffset); for (int column = length; column < columns; column++) dest[destLineOffset+column] = defaultChar; // invert selected text if (selBegin !=-1) { for (int column = 0; column < columns; column++) { if (isSelected(column,line)) { reverseRendition(dest[destLineOffset + column]); } } } } } void Screen::copyFromScreen(Character* dest , int startLine , int count) const { Q_ASSERT( startLine >= 0 && count > 0 && startLine + count <= lines ); for (int line = startLine; line < (startLine+count) ; line++) { int srcLineStartIndex = line*columns; int destLineStartIndex = (line-startLine)*columns; for (int column = 0; column < columns; column++) { int srcIndex = srcLineStartIndex + column; int destIndex = destLineStartIndex + column; dest[destIndex] = screenLines[srcIndex/columns].value(srcIndex%columns,defaultChar); // invert selected text if (selBegin != -1 && isSelected(column,line + history->getLines())) reverseRendition(dest[destIndex]); } } } void Screen::getImage( Character* dest, int size, int startLine, int endLine ) const { Q_ASSERT( startLine >= 0 ); Q_ASSERT( endLine >= startLine && endLine < history->getLines() + lines ); const int mergedLines = endLine - startLine + 1; Q_ASSERT( size >= mergedLines * columns ); Q_UNUSED( size ); const int linesInHistoryBuffer = qBound(0,history->getLines()-startLine,mergedLines); const int linesInScreenBuffer = mergedLines - linesInHistoryBuffer; // copy lines from history buffer if (linesInHistoryBuffer > 0) copyFromHistory(dest,startLine,linesInHistoryBuffer); // copy lines from screen buffer if (linesInScreenBuffer > 0) copyFromScreen(dest + linesInHistoryBuffer*columns, startLine + linesInHistoryBuffer - history->getLines(), linesInScreenBuffer); // invert display when in screen mode if (getMode(MODE_Screen)) { for (int i = 0; i < mergedLines*columns; i++) reverseRendition(dest[i]); // for reverse display } // mark the character at the current cursor position int cursorIndex = loc(cuX, cuY + linesInHistoryBuffer); if(getMode(MODE_Cursor) && cursorIndex < columns*mergedLines) dest[cursorIndex].rendition |= RE_CURSOR; } QVector Screen::getLineProperties( int startLine , int endLine ) const { Q_ASSERT( startLine >= 0 ); Q_ASSERT( endLine >= startLine && endLine < history->getLines() + lines ); const int mergedLines = endLine-startLine+1; const int linesInHistory = qBound(0,history->getLines()-startLine,mergedLines); const int linesInScreen = mergedLines - linesInHistory; QVector result(mergedLines); int index = 0; // copy properties for lines in history for (int line = startLine; line < startLine + linesInHistory; line++) { //TODO Support for line properties other than wrapped lines if (history->isWrappedLine(line)) { result[index] = (LineProperty)(result[index] | LINE_WRAPPED); } index++; } // copy properties for lines in screen buffer const int firstScreenLine = startLine + linesInHistory - history->getLines(); for (int line = firstScreenLine; line < firstScreenLine+linesInScreen; line++) { result[index]=lineProperties[line]; index++; } return result; } void Screen::reset(bool clearScreen) { setMode(MODE_Wrap ); saveMode(MODE_Wrap ); // wrap at end of margin resetMode(MODE_Origin); saveMode(MODE_Origin); // position refere to [1,1] resetMode(MODE_Insert); saveMode(MODE_Insert); // overstroke setMode(MODE_Cursor); // cursor visible resetMode(MODE_Screen); // screen not inverse resetMode(MODE_NewLine); _topMargin=0; _bottomMargin=lines-1; setDefaultRendition(); saveCursor(); if ( clearScreen ) clear(); } void Screen::clear() { clearEntireScreen(); home(); } void Screen::backspace() { cuX = qMin(columns-1,cuX); // nowrap! cuX = qMax(0,cuX-1); if (screenLines[cuY].size() < cuX+1) screenLines[cuY].resize(cuX+1); if (BS_CLEARS) screenLines[cuY][cuX].character = ' '; } void Screen::tab(int n) { // note that TAB is a format effector (does not write ' '); if (n == 0) n = 1; while((n > 0) && (cuX < columns-1)) { cursorRight(1); while((cuX < columns-1) && !tabStops[cuX]) cursorRight(1); n--; } } void Screen::backtab(int n) { // note that TAB is a format effector (does not write ' '); if (n == 0) n = 1; while((n > 0) && (cuX > 0)) { cursorLeft(1); while((cuX > 0) && !tabStops[cuX]) cursorLeft(1); n--; } } void Screen::clearTabStops() { for (int i = 0; i < columns; i++) tabStops[i] = false; } void Screen::changeTabStop(bool set) { if (cuX >= columns) return; tabStops[cuX] = set; } void Screen::initTabStops() { tabStops.resize(columns); // Arrg! The 1st tabstop has to be one longer than the other. // i.e. the kids start counting from 0 instead of 1. // Other programs might behave correctly. Be aware. for (int i = 0; i < columns; i++) tabStops[i] = (i%8 == 0 && i != 0); } void Screen::newLine() { if (getMode(MODE_NewLine)) toStartOfLine(); index(); } void Screen::checkSelection(int from, int to) { if (selBegin == -1) return; int scr_TL = loc(0, history->getLines()); //Clear entire selection if it overlaps region [from, to] if ( (selBottomRight >= (from+scr_TL)) && (selTopLeft <= (to+scr_TL)) ) clearSelection(); } void Screen::displayCharacter(wchar_t c) { // Note that VT100 does wrapping BEFORE putting the character. // This has impact on the assumption of valid cursor positions. // We indicate the fact that a newline has to be triggered by // putting the cursor one right to the last column of the screen. int w = konsole_wcwidth(c); if (w <= 0) return; if (cuX+w > columns) { if (getMode(MODE_Wrap)) { lineProperties[cuY] = (LineProperty)(lineProperties[cuY] | LINE_WRAPPED); nextLine(); } else cuX = columns-w; } // ensure current line vector has enough elements int size = screenLines[cuY].size(); if (size < cuX+w) { screenLines[cuY].resize(cuX+w); } if (getMode(MODE_Insert)) insertChars(w); lastPos = loc(cuX,cuY); // check if selection is still valid. checkSelection(lastPos, lastPos); Character& currentChar = screenLines[cuY][cuX]; currentChar.character = c; currentChar.foregroundColor = effectiveForeground; currentChar.backgroundColor = effectiveBackground; currentChar.rendition = effectiveRendition; lastDrawnChar = c; int i = 0; int newCursorX = cuX + w--; while(w) { i++; if ( screenLines[cuY].size() < cuX + i + 1 ) screenLines[cuY].resize(cuX+i+1); Character& ch = screenLines[cuY][cuX + i]; ch.character = 0; ch.foregroundColor = effectiveForeground; ch.backgroundColor = effectiveBackground; ch.rendition = effectiveRendition; w--; } cuX = newCursorX; } void Screen::compose(const QString& /*compose*/) { Q_ASSERT( 0 /*Not implemented yet*/ ); /* if (lastPos == -1) return; QChar c(image[lastPos].character); compose.prepend(c); //compose.compose(); ### FIXME! image[lastPos].character = compose[0].unicode();*/ } int Screen::scrolledLines() const { return _scrolledLines; } int Screen::droppedLines() const { return _droppedLines; } void Screen::resetDroppedLines() { _droppedLines = 0; } void Screen::resetScrolledLines() { _scrolledLines = 0; } void Screen::scrollUp(int n) { if (n == 0) n = 1; // Default if (_topMargin == 0) addHistLine(); // history.history scrollUp(_topMargin, n); } QRect Screen::lastScrolledRegion() const { return _lastScrolledRegion; } void Screen::scrollUp(int from, int n) { if (n <= 0) return; if (from > _bottomMargin) return; if (from + n > _bottomMargin) n = _bottomMargin + 1 - from; _scrolledLines -= n; _lastScrolledRegion = QRect(0,_topMargin,columns-1,(_bottomMargin-_topMargin)); //FIXME: make sure `topMargin', `bottomMargin', `from', `n' is in bounds. moveImage(loc(0,from),loc(0,from+n),loc(columns,_bottomMargin)); clearImage(loc(0,_bottomMargin-n+1),loc(columns-1,_bottomMargin),' '); } void Screen::scrollDown(int n) { if (n == 0) n = 1; // Default scrollDown(_topMargin, n); } void Screen::scrollDown(int from, int n) { _scrolledLines += n; //FIXME: make sure `topMargin', `bottomMargin', `from', `n' is in bounds. if (n <= 0) return; if (from > _bottomMargin) return; if (from + n > _bottomMargin) n = _bottomMargin - from; moveImage(loc(0,from+n),loc(0,from),loc(columns-1,_bottomMargin-n)); clearImage(loc(0,from),loc(columns-1,from+n-1),' '); } void Screen::setCursorYX(int y, int x) { setCursorY(y); setCursorX(x); } void Screen::setCursorX(int x) { if (x == 0) x = 1; // Default x -= 1; // Adjust cuX = qMax(0,qMin(columns-1, x)); } void Screen::setCursorY(int y) { if (y == 0) y = 1; // Default y -= 1; // Adjust cuY = qMax(0,qMin(lines -1, y + (getMode(MODE_Origin) ? _topMargin : 0) )); } void Screen::home() { cuX = 0; cuY = 0; } void Screen::toStartOfLine() { cuX = 0; } int Screen::getCursorX() const { return cuX; } int Screen::getCursorY() const { return cuY; } void Screen::clearImage(int loca, int loce, char c) { int scr_TL=loc(0,history->getLines()); //FIXME: check positions //Clear entire selection if it overlaps region to be moved... if ( (selBottomRight > (loca+scr_TL) )&&(selTopLeft < (loce+scr_TL)) ) { clearSelection(); } int topLine = loca/columns; int bottomLine = loce/columns; Character clearCh(c,currentForeground,currentBackground,DEFAULT_RENDITION); //if the character being used to clear the area is the same as the //default character, the affected lines can simply be shrunk. bool isDefaultCh = (clearCh == Character()); for (int y=topLine;y<=bottomLine;y++) { lineProperties[y] = 0; int endCol = ( y == bottomLine) ? loce%columns : columns-1; int startCol = ( y == topLine ) ? loca%columns : 0; QVector& line = screenLines[y]; if ( isDefaultCh && endCol == columns-1 ) { line.resize(startCol); } else { if (line.size() < endCol + 1) line.resize(endCol+1); Character* data = line.data(); for (int i=startCol;i<=endCol;i++) data[i]=clearCh; } } } void Screen::moveImage(int dest, int sourceBegin, int sourceEnd) { Q_ASSERT( sourceBegin <= sourceEnd ); int lines=(sourceEnd-sourceBegin)/columns; //move screen image and line properties: //the source and destination areas of the image may overlap, //so it matters that we do the copy in the right order - //forwards if dest < sourceBegin or backwards otherwise. //(search the web for 'memmove implementation' for details) if (dest < sourceBegin) { for (int i=0;i<=lines;i++) { screenLines[ (dest/columns)+i ] = screenLines[ (sourceBegin/columns)+i ]; lineProperties[(dest/columns)+i]=lineProperties[(sourceBegin/columns)+i]; } } else { for (int i=lines;i>=0;i--) { screenLines[ (dest/columns)+i ] = screenLines[ (sourceBegin/columns)+i ]; lineProperties[(dest/columns)+i]=lineProperties[(sourceBegin/columns)+i]; } } if (lastPos != -1) { int diff = dest - sourceBegin; // Scroll by this amount lastPos += diff; if ((lastPos < 0) || (lastPos >= (lines*columns))) lastPos = -1; } // Adjust selection to follow scroll. if (selBegin != -1) { bool beginIsTL = (selBegin == selTopLeft); int diff = dest - sourceBegin; // Scroll by this amount int scr_TL=loc(0,history->getLines()); int srca = sourceBegin+scr_TL; // Translate index from screen to global int srce = sourceEnd+scr_TL; // Translate index from screen to global int desta = srca+diff; int deste = srce+diff; if ((selTopLeft >= srca) && (selTopLeft <= srce)) selTopLeft += diff; else if ((selTopLeft >= desta) && (selTopLeft <= deste)) selBottomRight = -1; // Clear selection (see below) if ((selBottomRight >= srca) && (selBottomRight <= srce)) selBottomRight += diff; else if ((selBottomRight >= desta) && (selBottomRight <= deste)) selBottomRight = -1; // Clear selection (see below) if (selBottomRight < 0) { clearSelection(); } else { if (selTopLeft < 0) selTopLeft = 0; } if (beginIsTL) selBegin = selTopLeft; else selBegin = selBottomRight; } } void Screen::clearToEndOfScreen() { clearImage(loc(cuX,cuY),loc(columns-1,lines-1),' '); } void Screen::clearToBeginOfScreen() { clearImage(loc(0,0),loc(cuX,cuY),' '); } void Screen::clearEntireScreen() { // Add entire screen to history for (int i = 0; i < (lines-1); i++) { addHistLine(); scrollUp(0,1); } clearImage(loc(0,0),loc(columns-1,lines-1),' '); } /*! fill screen with 'E' This is to aid screen alignment */ void Screen::helpAlign() { clearImage(loc(0,0),loc(columns-1,lines-1),'E'); } void Screen::clearToEndOfLine() { clearImage(loc(cuX,cuY),loc(columns-1,cuY),' '); } void Screen::clearToBeginOfLine() { clearImage(loc(0,cuY),loc(cuX,cuY),' '); } void Screen::clearEntireLine() { clearImage(loc(0,cuY),loc(columns-1,cuY),' '); } void Screen::setRendition(int re) { currentRendition |= re; updateEffectiveRendition(); } void Screen::resetRendition(int re) { currentRendition &= ~re; updateEffectiveRendition(); } void Screen::setDefaultRendition() { setForeColor(COLOR_SPACE_DEFAULT,DEFAULT_FORE_COLOR); setBackColor(COLOR_SPACE_DEFAULT,DEFAULT_BACK_COLOR); currentRendition = DEFAULT_RENDITION; updateEffectiveRendition(); } void Screen::setForeColor(int space, int color) { currentForeground = CharacterColor(space, color); if ( currentForeground.isValid() ) updateEffectiveRendition(); else setForeColor(COLOR_SPACE_DEFAULT,DEFAULT_FORE_COLOR); } void Screen::setBackColor(int space, int color) { currentBackground = CharacterColor(space, color); if ( currentBackground.isValid() ) updateEffectiveRendition(); else setBackColor(COLOR_SPACE_DEFAULT,DEFAULT_BACK_COLOR); } void Screen::clearSelection() { selBottomRight = -1; selTopLeft = -1; selBegin = -1; } void Screen::getSelectionStart(int& column , int& line) const { if ( selTopLeft != -1 ) { column = selTopLeft % columns; line = selTopLeft / columns; } else { column = cuX + getHistLines(); line = cuY + getHistLines(); } } void Screen::getSelectionEnd(int& column , int& line) const { if ( selBottomRight != -1 ) { column = selBottomRight % columns; line = selBottomRight / columns; } else { column = cuX + getHistLines(); line = cuY + getHistLines(); } } void Screen::setSelectionStart(const int x, const int y, const bool mode) { selBegin = loc(x,y); /* FIXME, HACK to correct for x too far to the right... */ if (x == columns) selBegin--; selBottomRight = selBegin; selTopLeft = selBegin; blockSelectionMode = mode; } void Screen::setSelectionEnd( const int x, const int y) { if (selBegin == -1) return; int endPos = loc(x,y); if (endPos < selBegin) { selTopLeft = endPos; selBottomRight = selBegin; } else { /* FIXME, HACK to correct for x too far to the right... */ if (x == columns) endPos--; selTopLeft = selBegin; selBottomRight = endPos; } // Normalize the selection in column mode if (blockSelectionMode) { int topRow = selTopLeft / columns; int topColumn = selTopLeft % columns; int bottomRow = selBottomRight / columns; int bottomColumn = selBottomRight % columns; selTopLeft = loc(qMin(topColumn,bottomColumn),topRow); selBottomRight = loc(qMax(topColumn,bottomColumn),bottomRow); } } /******************************************************************** 1. @函数: setSelectionAll 2. @作者: 王培利 3. @日期: 2020-02-13 4. @说明: 屏幕全选功能 ********************************************************************/ void Screen::setSelectionAll() { selBegin = 0; selTopLeft = 0; int endPos = (getHistLines() + getCursorY() + 1) * columns - 1; selBottomRight = endPos; } bool Screen::isSelected(const int x, const int y) const { bool columnInSelection = true; if (blockSelectionMode) { columnInSelection = x >= (selTopLeft % columns) && x <= (selBottomRight % columns); } int pos = loc(x,y); return pos >= selTopLeft && pos <= selBottomRight && columnInSelection; } QString Screen::selectedText(bool preserveLineBreaks) const { QString result; QTextStream stream(&result, QIODevice::ReadWrite); PlainTextDecoder decoder; decoder.begin(&stream); writeSelectionToStream(&decoder , preserveLineBreaks); decoder.end(); return result; } bool Screen::isSelectionValid() const { return selTopLeft >= 0 && selBottomRight >= 0; } void Screen::writeSelectionToStream(TerminalCharacterDecoder* decoder , bool preserveLineBreaks) const { if (!isSelectionValid()) return; writeToStream(decoder,selTopLeft,selBottomRight,preserveLineBreaks); } void Screen::writeToStream(TerminalCharacterDecoder* decoder, int startIndex, int endIndex, bool preserveLineBreaks) const { int top = startIndex / columns; int left = startIndex % columns; int bottom = endIndex / columns; int right = endIndex % columns; Q_ASSERT( top >= 0 && left >= 0 && bottom >= 0 && right >= 0 ); for (int y=top;y<=bottom;y++) { int start = 0; if ( y == top || blockSelectionMode ) start = left; int count = -1; if ( y == bottom || blockSelectionMode ) count = right - start + 1; const bool appendNewLine = ( y != bottom ); int copied = copyLineToStream( y, start, count, decoder, appendNewLine, preserveLineBreaks ); // if the selection goes beyond the end of the last line then // append a new line character. // // this makes it possible to 'select' a trailing new line character after // the text on a line. if ( y == bottom && copied < count ) { Character newLineChar('\n'); decoder->decodeLine(&newLineChar,1,0); } } } int Screen::copyLineToStream(int line , int start, int count, TerminalCharacterDecoder* decoder, bool appendNewLine, bool preserveLineBreaks) const { //buffer to hold characters for decoding //the buffer is static to avoid initialising every //element on each call to copyLineToStream //(which is unnecessary since all elements will be overwritten anyway) static const int MAX_CHARS = 1024; static Character characterBuffer[MAX_CHARS]; Q_ASSERT( count < MAX_CHARS ); LineProperty currentLineProperties = 0; //determine if the line is in the history buffer or the screen image if (line < history->getLines()) { const int lineLength = history->getLineLen(line); // ensure that start position is before end of line start = qMin(start,qMax(0,lineLength-1)); // retrieve line from history buffer. It is assumed // that the history buffer does not store trailing white space // at the end of the line, so it does not need to be trimmed here if (count == -1) { count = lineLength-start; } else { count = qMin(start+count,lineLength)-start; } // safety checks Q_ASSERT( start >= 0 ); Q_ASSERT( count >= 0 ); Q_ASSERT( (start+count) <= history->getLineLen(line) ); history->getCells(line,start,count,characterBuffer); if ( history->isWrappedLine(line) ) currentLineProperties |= LINE_WRAPPED; } else { if ( count == -1 ) count = columns - start; Q_ASSERT( count >= 0 ); const int screenLine = line-history->getLines(); Character* data = screenLines[screenLine].data(); int length = screenLines[screenLine].count(); //retrieve line from screen image for (int i=start;i < qMin(start+count,length);i++) { characterBuffer[i-start] = data[i]; } // count cannot be any greater than length count = qBound(0,count,length-start); Q_ASSERT( screenLine < lineProperties.count() ); currentLineProperties |= lineProperties[screenLine]; } // add new line character at end const bool omitLineBreak = (currentLineProperties & LINE_WRAPPED) || !preserveLineBreaks; if ( !omitLineBreak && appendNewLine && (count+1 < MAX_CHARS) ) { characterBuffer[count] = '\n'; count++; } //decode line and write to text stream decoder->decodeLine( (Character*) characterBuffer , count, currentLineProperties ); return count; } void Screen::writeLinesToStream(TerminalCharacterDecoder* decoder, int fromLine, int toLine) const { writeToStream(decoder,loc(0,fromLine),loc(columns-1,toLine)); } void Screen::addHistLine() { // add line to history buffer // we have to take care about scrolling, too... if (hasScroll()) { int oldHistLines = history->getLines(); history->addCellsVector(screenLines[0]); history->addLine( lineProperties[0] & LINE_WRAPPED ); int newHistLines = history->getLines(); bool beginIsTL = (selBegin == selTopLeft); // If the history is full, increment the count // of dropped lines if ( newHistLines == oldHistLines ) _droppedLines++; // Adjust selection for the new point of reference if (newHistLines > oldHistLines) { if (selBegin != -1) { selTopLeft += columns; selBottomRight += columns; } } if (selBegin != -1) { // Scroll selection in history up int top_BR = loc(0, 1+newHistLines); if (selTopLeft < top_BR) selTopLeft -= columns; if (selBottomRight < top_BR) selBottomRight -= columns; if (selBottomRight < 0) clearSelection(); else { if (selTopLeft < 0) selTopLeft = 0; } if (beginIsTL) selBegin = selTopLeft; else selBegin = selBottomRight; } } } int Screen::getHistLines() const { return history->getLines(); } void Screen::setScroll(const HistoryType& t , bool copyPreviousScroll) { clearSelection(); if ( copyPreviousScroll ) history = t.scroll(history); else { HistoryScroll* oldScroll = history; history = t.scroll(nullptr); delete oldScroll; } } bool Screen::hasScroll() const { return history->hasScroll(); } const HistoryType& Screen::getScroll() const { return history->getType(); } void Screen::setLineProperty(LineProperty property , bool enable) { if ( enable ) lineProperties[cuY] = (LineProperty)(lineProperties[cuY] | property); else lineProperties[cuY] = (LineProperty)(lineProperties[cuY] & ~property); } void Screen::fillWithDefaultChar(Character* dest, int count) { for (int i=0;i 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 SCREEN_H #define SCREEN_H // Qt #include #include #include // Konsole #include "Character.h" #include "History.h" #define MODE_Origin 0 #define MODE_Wrap 1 #define MODE_Insert 2 #define MODE_Screen 3 #define MODE_Cursor 4 #define MODE_NewLine 5 #define MODES_SCREEN 6 namespace Konsole { class TerminalCharacterDecoder; /** \brief An image of characters with associated attributes. The terminal emulation ( Emulation ) receives a serial stream of characters from the program currently running in the terminal. From this stream it creates an image of characters which is ultimately rendered by the display widget ( TerminalDisplay ). Some types of emulation may have more than one screen image. getImage() is used to retrieve the currently visible image which is then used by the display widget to draw the output from the terminal. The number of lines of output history which are kept in addition to the current screen image depends on the history scroll being used to store the output. The scroll is specified using setScroll() The output history can be retrieved using writeToStream() The screen image has a selection associated with it, specified using setSelectionStart() and setSelectionEnd(). The selected text can be retrieved using selectedText(). When getImage() is used to retrieve the visible image, characters which are part of the selection have their colours inverted. */ class Screen { public: /** Construct a new screen image of size @p lines by @p columns. */ Screen(int lines, int columns); ~Screen(); // VT100/2 Operations // Cursor Movement /** * Move the cursor up by @p n lines. The cursor will stop at the * top margin. */ void cursorUp(int n); /** * Move the cursor down by @p n lines. The cursor will stop at the * bottom margin. */ void cursorDown(int n); /** * Move the cursor to the left by @p n columns. * The cursor will stop at the first column. */ void cursorLeft(int n); /** * Move the cursor to the right by @p n columns. * The cursor will stop at the right-most column. */ void cursorRight(int n); /** Position the cursor on line @p y. */ void setCursorY(int y); /** Position the cursor at column @p x. */ void setCursorX(int x); /** Position the cursor at line @p y, column @p x. */ void setCursorYX(int y, int x); /** * Sets the margins for scrolling the screen. * * @param topLine The top line of the new scrolling margin. * @param bottomLine The bottom line of the new scrolling margin. */ void setMargins(int topLine , int bottomLine); /** Returns the top line of the scrolling region. */ int topMargin() const; /** Returns the bottom line of the scrolling region. */ int bottomMargin() const; /** * Resets the scrolling margins back to the top and bottom lines * of the screen. */ void setDefaultMargins(); /** * Moves the cursor down one line, if the MODE_NewLine mode * flag is enabled then the cursor is returned to the leftmost * column first. * * Equivalent to NextLine() if the MODE_NewLine flag is set * or index() otherwise. */ void newLine(); /** * Moves the cursor down one line and positions it at the beginning * of the line. Equivalent to calling Return() followed by index() */ void nextLine(); /** * Move the cursor down one line. If the cursor is on the bottom * line of the scrolling region (as returned by bottomMargin()) the * scrolling region is scrolled up by one line instead. */ void index(); /** * Move the cursor up one line. If the cursor is on the top line * of the scrolling region (as returned by topMargin()) the scrolling * region is scrolled down by one line instead. */ void reverseIndex(); /** * Scroll the scrolling region of the screen up by @p n lines. * The scrolling region is initially the whole screen, but can be changed * using setMargins() */ void scrollUp(int n); /** * Scroll the scrolling region of the screen down by @p n lines. * The scrolling region is initially the whole screen, but can be changed * using setMargins() */ void scrollDown(int n); /** * Moves the cursor to the beginning of the current line. * Equivalent to setCursorX(0) */ void toStartOfLine(); /** * Moves the cursor one column to the left and erases the character * at the new cursor position. */ void backspace(); /** Moves the cursor @p n tab-stops to the right. */ void tab(int n = 1); /** Moves the cursor @p n tab-stops to the left. */ void backtab(int n); // Editing /** * Erase @p n characters beginning from the current cursor position. * This is equivalent to over-writing @p n characters starting with the current * cursor position with spaces. * If @p n is 0 then one character is erased. */ void eraseChars(int n); /** * Delete @p n characters beginning from the current cursor position. * If @p n is 0 then one character is deleted. */ void deleteChars(int n); /** * Insert @p n blank characters beginning from the current cursor position. * The position of the cursor is not altered. * If @p n is 0 then one character is inserted. */ void insertChars(int n); /** * Repeat the preceeding graphic character @count times, including SPACE. * If @count is 0 then the character is repeated once. */ void repeatChars(int count); /** * Removes @p n lines beginning from the current cursor position. * The position of the cursor is not altered. * If @p n is 0 then one line is removed. */ void deleteLines(int n); /** * Inserts @p lines beginning from the current cursor position. * The position of the cursor is not altered. * If @p n is 0 then one line is inserted. */ void insertLines(int n); /** Clears all the tab stops. */ void clearTabStops(); /** Sets or removes a tab stop at the cursor's current column. */ void changeTabStop(bool set); /** Resets (clears) the specified screen @p mode. */ void resetMode(int mode); /** Sets (enables) the specified screen @p mode. */ void setMode(int mode); /** * Saves the state of the specified screen @p mode. It can be restored * using restoreMode() */ void saveMode(int mode); /** Restores the state of a screen @p mode saved by calling saveMode() */ void restoreMode(int mode); /** Returns whether the specified screen @p mode is enabled or not .*/ bool getMode(int mode) const; /** * Saves the current position and appearance (text color and style) of the cursor. * It can be restored by calling restoreCursor() */ void saveCursor(); /** Restores the position and appearance of the cursor. See saveCursor() */ void restoreCursor(); /** Clear the whole screen, moving the current screen contents into the history first. */ void clearEntireScreen(); /** * Clear the area of the screen from the current cursor position to the end of * the screen. */ void clearToEndOfScreen(); /** * Clear the area of the screen from the current cursor position to the start * of the screen. */ void clearToBeginOfScreen(); /** Clears the whole of the line on which the cursor is currently positioned. */ void clearEntireLine(); /** Clears from the current cursor position to the end of the line. */ void clearToEndOfLine(); /** Clears from the current cursor position to the beginning of the line. */ void clearToBeginOfLine(); /** Fills the entire screen with the letter 'E' */ void helpAlign(); /** * Enables the given @p rendition flag. Rendition flags control the appearance * of characters on the screen. * * @see Character::rendition */ void setRendition(int rendition); /** * Disables the given @p rendition flag. Rendition flags control the appearance * of characters on the screen. * * @see Character::rendition */ void resetRendition(int rendition); /** * Sets the cursor's foreground color. * @param space The color space used by the @p color argument * @param color The new foreground color. The meaning of this depends on * the color @p space used. * * @see CharacterColor */ void setForeColor(int space, int color); /** * Sets the cursor's background color. * @param space The color space used by the @p color argumnet. * @param color The new background color. The meaning of this depends on * the color @p space used. * * @see CharacterColor */ void setBackColor(int space, int color); /** * Resets the cursor's color back to the default and sets the * character's rendition flags back to the default settings. */ void setDefaultRendition(); /** Returns the column which the cursor is positioned at. */ int getCursorX() const; /** Returns the line which the cursor is positioned on. */ int getCursorY() const; /** Clear the entire screen and move the cursor to the home position. * Equivalent to calling clearEntireScreen() followed by home(). */ void clear(); /** * Sets the position of the cursor to the 'home' position at the top-left * corner of the screen (0,0) */ void home(); /** * Resets the state of the screen. This resets the various screen modes * back to their default states. The cursor style and colors are reset * (as if setDefaultRendition() had been called) * *
    *
  • Line wrapping is enabled.
  • *
  • Origin mode is disabled.
  • *
  • Insert mode is disabled.
  • *
  • Cursor mode is enabled. TODO Document me
  • *
  • Screen mode is disabled. TODO Document me
  • *
  • New line mode is disabled. TODO Document me
  • *
* * If @p clearScreen is true then the screen contents are erased entirely, * otherwise they are unaltered. */ void reset(bool clearScreen = true); /** * Displays a new character at the current cursor position. * * If the cursor is currently positioned at the right-edge of the screen and * line wrapping is enabled then the character is added at the start of a new * line below the current one. * * If the MODE_Insert screen mode is currently enabled then the character * is inserted at the current cursor position, otherwise it will replace the * character already at the current cursor position. */ void displayCharacter(wchar_t c); // Do composition with last shown character FIXME: Not implemented yet for KDE 4 void compose(const QString& compose); /** * Resizes the image to a new fixed size of @p new_lines by @p new_columns. * In the case that @p new_columns is smaller than the current number of columns, * existing lines are not truncated. This prevents characters from being lost * if the terminal display is resized smaller and then larger again. * * The top and bottom margins are reset to the top and bottom of the new * screen size. Tab stops are also reset and the current selection is * cleared. */ void resizeImage(int new_lines, int new_columns); /** * Returns the current screen image. * The result is an array of Characters of size [getLines()][getColumns()] which * must be freed by the caller after use. * * @param dest Buffer to copy the characters into * @param size Size of @p dest in Characters * @param startLine Index of first line to copy * @param endLine Index of last line to copy */ void getImage( Character* dest , int size , int startLine , int endLine ) const; /** * Returns the additional attributes associated with lines in the image. * The most important attribute is LINE_WRAPPED which specifies that the * line is wrapped, * other attributes control the size of characters in the line. */ QVector getLineProperties( int startLine , int endLine ) const; /** Return the number of lines. */ int getLines() const { return lines; } /** Return the number of columns. */ int getColumns() const { return columns; } /** Return the number of lines in the history buffer. */ int getHistLines() const; /** * Sets the type of storage used to keep lines in the history. * If @p copyPreviousScroll is true then the contents of the previous * history buffer are copied into the new scroll. */ void setScroll(const HistoryType& , bool copyPreviousScroll = true); /** Returns the type of storage used to keep lines in the history. */ const HistoryType& getScroll() const; /** * Returns true if this screen keeps lines that are scrolled off the screen * in a history buffer. */ bool hasScroll() const; /** * Sets the start of the selection. * * @param column The column index of the first character in the selection. * @param line The line index of the first character in the selection. * @param blockSelectionMode True if the selection is in column mode. */ void setSelectionStart(const int column, const int line, const bool blockSelectionMode); /** * Sets the end of the current selection. * * @param column The column index of the last character in the selection. * @param line The line index of the last character in the selection. */ void setSelectionEnd(const int column, const int line); /******** Modify by n014361 wangpeili 2020-02-13: 新增屏幕全选功能***********×****/ void setSelectionAll(); /***************** Modify by n014361 End *************************/ /** * Retrieves the start of the selection or the cursor position if there * is no selection. */ void getSelectionStart(int& column , int& line) const; /** * Retrieves the end of the selection or the cursor position if there * is no selection. */ void getSelectionEnd(int& column , int& line) const; /** Clears the current selection */ void clearSelection(); /** * Returns true if the character at (@p column, @p line) is part of the * current selection. */ bool isSelected(const int column,const int line) const; /** * Convenience method. Returns the currently selected text. * @param preserveLineBreaks Specifies whether new line characters should * be inserted into the returned text at the end of each terminal line. */ QString selectedText(bool preserveLineBreaks) const; /** * Copies part of the output to a stream. * * @param decoder A decoder which converts terminal characters into text * @param fromLine The first line in the history to retrieve * @param toLine The last line in the history to retrieve */ void writeLinesToStream(TerminalCharacterDecoder* decoder, int fromLine, int toLine) const; /** * Copies the selected characters, set using @see setSelBeginXY and @see setSelExtentXY * into a stream. * * @param decoder A decoder which converts terminal characters into text. * PlainTextDecoder is the most commonly used decoder which converts characters * into plain text with no formatting. * @param preserveLineBreaks Specifies whether new line characters should * be inserted into the returned text at the end of each terminal line. */ void writeSelectionToStream(TerminalCharacterDecoder* decoder , bool preserveLineBreaks = true) const; /** * Checks if the text between from and to is inside the current * selection. If this is the case, the selection is cleared. The * from and to are coordinates in the current viewable window. * The loc(x,y) macro can be used to generate these values from a * column,line pair. * * @param from The start of the area to check. * @param to The end of the area to check */ void checkSelection(int from, int to); /** * Sets or clears an attribute of the current line. * * @param property The attribute to set or clear * Possible properties are: * LINE_WRAPPED: Specifies that the line is wrapped. * LINE_DOUBLEWIDTH: Specifies that the characters in the current line * should be double the normal width. * LINE_DOUBLEHEIGHT:Specifies that the characters in the current line * should be double the normal height. * Double-height lines are formed of two lines containing the same characters, * with both having the LINE_DOUBLEHEIGHT attribute. * This allows other parts of the code to work on the * assumption that all lines are the same height. * * @param enable true to apply the attribute to the current line or false to remove it */ void setLineProperty(LineProperty property , bool enable); /** * Returns the number of lines that the image has been scrolled up or down by, * since the last call to resetScrolledLines(). * * a positive return value indicates that the image has been scrolled up, * a negative return value indicates that the image has been scrolled down. */ int scrolledLines() const; /** * Returns the region of the image which was last scrolled. * * This is the area of the image from the top margin to the * bottom margin when the last scroll occurred. */ QRect lastScrolledRegion() const; /** * Resets the count of the number of lines that the image has been scrolled up or down by, * see scrolledLines() */ void resetScrolledLines(); /** * Returns the number of lines of output which have been * dropped from the history since the last call * to resetDroppedLines() * * If the history is not unlimited then it will drop * the oldest lines of output if new lines are added when * it is full. */ int droppedLines() const; /** * Resets the count of the number of lines dropped from * the history. */ void resetDroppedLines(); /** * Fills the buffer @p dest with @p count instances of the default (ie. blank) * Character style. */ static void fillWithDefaultChar(Character* dest, int count); private: //copies a line of text from the screen or history into a stream using a //specified character decoder. Returns the number of lines actually copied, //which may be less than 'count' if (start+count) is more than the number of characters on //the line // //line - the line number to copy, from 0 (the earliest line in the history) up to // history->getLines() + lines - 1 //start - the first column on the line to copy //count - the number of characters on the line to copy //decoder - a decoder which converts terminal characters (an Character array) into text //appendNewLine - if true a new line character (\n) is appended to the end of the line int copyLineToStream(int line, int start, int count, TerminalCharacterDecoder* decoder, bool appendNewLine, bool preserveLineBreaks) const; //fills a section of the screen image with the character 'c' //the parameters are specified as offsets from the start of the screen image. //the loc(x,y) macro can be used to generate these values from a column,line pair. void clearImage(int loca, int loce, char c); //move screen image between 'sourceBegin' and 'sourceEnd' to 'dest'. //the parameters are specified as offsets from the start of the screen image. //the loc(x,y) macro can be used to generate these values from a column,line pair. // //NOTE: moveImage() can only move whole lines void moveImage(int dest, int sourceBegin, int sourceEnd); // scroll up 'i' lines in current region, clearing the bottom 'i' lines void scrollUp(int from, int i); // scroll down 'i' lines in current region, clearing the top 'i' lines void scrollDown(int from, int i); void addHistLine(); void initTabStops(); void updateEffectiveRendition(); void reverseRendition(Character& p) const; bool isSelectionValid() const; // copies text from 'startIndex' to 'endIndex' to a stream // startIndex and endIndex are positions generated using the loc(x,y) macro void writeToStream(TerminalCharacterDecoder* decoder, int startIndex, int endIndex, bool preserveLineBreaks = true) const; // copies 'count' lines from the screen buffer into 'dest', // starting from 'startLine', where 0 is the first line in the screen buffer void copyFromScreen(Character* dest, int startLine, int count) const; // copies 'count' lines from the history buffer into 'dest', // starting from 'startLine', where 0 is the first line in the history void copyFromHistory(Character* dest, int startLine, int count) const; // screen image ---------------- int lines; int columns; typedef QVector ImageLine; // [0..columns] ImageLine* screenLines; // [lines] int _scrolledLines; QRect _lastScrolledRegion; int _droppedLines; QVarLengthArray lineProperties; // history buffer --------------- HistoryScroll* history; // cursor location int cuX; int cuY; // cursor color and rendition info CharacterColor currentForeground; CharacterColor currentBackground; quint8 currentRendition; // margins ---------------- int _topMargin; int _bottomMargin; // states ---------------- bool currentModes[MODES_SCREEN]; bool savedModes[MODES_SCREEN]; // ---------------------------- QBitArray tabStops; // selection ------------------- int selBegin; // The first location selected. int selTopLeft; // TopLeft Location. int selBottomRight; // Bottom Right Location. bool blockSelectionMode; // Column selection mode // effective colors and rendition ------------ CharacterColor effectiveForeground; // These are derived from CharacterColor effectiveBackground; // the cu_* variables above quint8 effectiveRendition; // to speed up operation class SavedState { public: SavedState() : cursorColumn(0),cursorLine(0),rendition(0) {} int cursorColumn; int cursorLine; quint8 rendition; CharacterColor foreground; CharacterColor background; }; SavedState savedState; // last position where we added a character int lastPos; // used in REP (repeating char) unsigned short lastDrawnChar; static Character defaultChar; }; } #endif // SCREEN_H deepin-terminal-5.2.11/3rdparty/terminalwidget/lib/ScreenWindow.cpp000066400000000000000000000172131370157770500253450ustar00rootroot00000000000000/* Copyright (C) 2007 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. */ // Own #include "ScreenWindow.h" // Qt #include // Konsole #include "Screen.h" using namespace Konsole; ScreenWindow::ScreenWindow(QObject* parent) : QObject(parent) , _windowBuffer(nullptr) , _windowBufferSize(0) , _bufferNeedsUpdate(true) , _windowLines(1) , _currentLine(0) , _trackOutput(true) , _scrollCount(0) { } ScreenWindow::~ScreenWindow() { delete[] _windowBuffer; } void ScreenWindow::setScreen(Screen* screen) { Q_ASSERT( screen ); _screen = screen; } Screen* ScreenWindow::screen() const { return _screen; } Character* ScreenWindow::getImage() { // reallocate internal buffer if the window size has changed int size = windowLines() * windowColumns(); if (_windowBuffer == nullptr || _windowBufferSize != size) { delete[] _windowBuffer; _windowBufferSize = size; _windowBuffer = new Character[size]; _bufferNeedsUpdate = true; } if (!_bufferNeedsUpdate) return _windowBuffer; _screen->getImage(_windowBuffer,size, currentLine(),endWindowLine()); // this window may look beyond the end of the screen, in which // case there will be an unused area which needs to be filled // with blank characters fillUnusedArea(); _bufferNeedsUpdate = false; return _windowBuffer; } void ScreenWindow::fillUnusedArea() { int screenEndLine = _screen->getHistLines() + _screen->getLines() - 1; int windowEndLine = currentLine() + windowLines() - 1; int unusedLines = windowEndLine - screenEndLine; int charsToFill = unusedLines * windowColumns(); Screen::fillWithDefaultChar(_windowBuffer + _windowBufferSize - charsToFill,charsToFill); } // return the index of the line at the end of this window, or if this window // goes beyond the end of the screen, the index of the line at the end // of the screen. // // when passing a line number to a Screen method, the line number should // never be more than endWindowLine() // int ScreenWindow::endWindowLine() const { return qMin(currentLine() + windowLines() - 1, lineCount() - 1); } QVector ScreenWindow::getLineProperties() { QVector result = _screen->getLineProperties(currentLine(),endWindowLine()); if (result.count() != windowLines()) result.resize(windowLines()); return result; } QString ScreenWindow::selectedText( bool preserveLineBreaks ) const { return _screen->selectedText( preserveLineBreaks ); } void ScreenWindow::getSelectionStart( int& column , int& line ) { _screen->getSelectionStart(column,line); line -= currentLine(); } void ScreenWindow::getSelectionEnd( int& column , int& line ) { _screen->getSelectionEnd(column,line); line -= currentLine(); } void ScreenWindow::setSelectionStart( int column , int line , bool columnMode ) { _screen->setSelectionStart( column , qMin(line + currentLine(),endWindowLine()) , columnMode); _bufferNeedsUpdate = true; emit selectionChanged(); } void ScreenWindow::setSelectionEnd( int column , int line ) { _screen->setSelectionEnd( column , qMin(line + currentLine(),endWindowLine()) ); _bufferNeedsUpdate = true; emit selectionChanged(); } /******************************************************************** 1. @函数: setSelectionAll 2. @作者: 王培利 3. @日期: 2020-02-13 4. @说明: 屏幕全选功能 ********************************************************************/ void ScreenWindow::setSelectionAll() { _screen->setSelectionAll(); _bufferNeedsUpdate = true; emit selectionChanged(); } bool ScreenWindow::isSelected(int column, int line) { return _screen->isSelected(column, qMin(line + currentLine(), endWindowLine())); } void ScreenWindow::clearSelection() { _screen->clearSelection(); emit selectionChanged(); } void ScreenWindow::setWindowLines(int lines) { Q_ASSERT(lines > 0); _windowLines = lines; } int ScreenWindow::windowLines() const { return _windowLines; } int ScreenWindow::windowColumns() const { return _screen->getColumns(); } int ScreenWindow::lineCount() const { return _screen->getHistLines() + _screen->getLines(); } int ScreenWindow::columnCount() const { return _screen->getColumns(); } QPoint ScreenWindow::cursorPosition() const { QPoint position; position.setX( _screen->getCursorX() ); position.setY( _screen->getCursorY() ); return position; } int ScreenWindow::currentLine() const { return qBound(0,_currentLine,lineCount()-windowLines()); } void ScreenWindow::scrollBy( RelativeScrollMode mode , int amount ) { if ( mode == ScrollLines ) { scrollTo( currentLine() + amount ); } else if ( mode == ScrollPages ) { scrollTo( currentLine() + amount * ( windowLines() / 2 ) ); } } bool ScreenWindow::atEndOfOutput() const { return currentLine() == (lineCount()-windowLines()); } void ScreenWindow::scrollTo( int line ) { int maxCurrentLineNumber = lineCount() - windowLines(); line = qBound(0,line,maxCurrentLineNumber); const int delta = line - _currentLine; _currentLine = line; // keep track of number of lines scrolled by, // this can be reset by calling resetScrollCount() _scrollCount += delta; _bufferNeedsUpdate = true; emit scrolled(_currentLine); } void ScreenWindow::setTrackOutput(bool trackOutput) { _trackOutput = trackOutput; } bool ScreenWindow::trackOutput() const { return _trackOutput; } int ScreenWindow::scrollCount() const { return _scrollCount; } void ScreenWindow::resetScrollCount() { _scrollCount = 0; } QRect ScreenWindow::scrollRegion() const { bool equalToScreenSize = windowLines() == _screen->getLines(); if ( atEndOfOutput() && equalToScreenSize ) return _screen->lastScrolledRegion(); else return {0,0,windowColumns(),windowLines()}; } void ScreenWindow::notifyOutputChanged() { // move window to the bottom of the screen and update scroll count // if this window is currently tracking the bottom of the screen if ( _trackOutput ) { _scrollCount -= _screen->scrolledLines(); _currentLine = qMax(0,_screen->getHistLines() - (windowLines()-_screen->getLines())); } else { // if the history is not unlimited then it may // have run out of space and dropped the oldest // lines of output - in this case the screen // window's current line number will need to // be adjusted - otherwise the output will scroll _currentLine = qMax(0,_currentLine - _screen->droppedLines()); // ensure that the screen window's current position does // not go beyond the bottom of the screen _currentLine = qMin( _currentLine , _screen->getHistLines() ); } _bufferNeedsUpdate = true; emit outputChanged(); } //#include "ScreenWindow.moc" deepin-terminal-5.2.11/3rdparty/terminalwidget/lib/ScreenWindow.h000066400000000000000000000213421370157770500250100ustar00rootroot00000000000000/* 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" namespace Konsole { class Screen; /** * 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. */ ScreenWindow(QObject* parent = nullptr); ~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; /** * 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 ); /******** Modify by n014361 wangpeili 2020-02-13: 新增屏幕全选功能***********×****/ void setSelectionAll(); /***************** Modify by n014361 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. */ void scrollBy( RelativeScrollMode mode , int amount ); /** * 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 preserveLineBreaks See Screen::selectedText() */ QString selectedText( bool preserveLineBreaks ) const; public 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(); signals: /** * Emitted when the contents of the associated terminal screen (see screen()) changes. */ void outputChanged(); /** * 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: int endWindowLine() const; void fillUnusedArea(); Screen* _screen; // see setScreen() , screen() Character* _windowBuffer; int _windowBufferSize; bool _bufferNeedsUpdate; int _windowLines; int _currentLine; // see scrollTo() , currentLine() 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 deepin-terminal-5.2.11/3rdparty/terminalwidget/lib/SearchBar.cpp000066400000000000000000000070501370157770500245660ustar00rootroot00000000000000/* Copyright 2013 Christian Surlykke This program is free software; you can redistribute it and/or modify it under the terms of the 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. */ #include #include #include #include #include "SearchBar.h" SearchBar::SearchBar(QWidget *parent) : QWidget(parent) { widget.setupUi(this); setAutoFillBackground(true); // make it always opaque, especially inside translucent windows connect(widget.closeButton, SIGNAL(clicked()), this, SLOT(hide())); connect(widget.searchTextEdit, SIGNAL(textChanged(QString)), this, SIGNAL(searchCriteriaChanged())); connect(widget.findPreviousButton, SIGNAL(clicked()), this, SIGNAL(findPrevious())); connect(widget.findNextButton, SIGNAL(clicked()), this, SIGNAL(findNext())); connect(this, SIGNAL(searchCriteriaChanged()), this, SLOT(clearBackgroundColor())); QMenu *optionsMenu = new QMenu(widget.optionsButton); widget.optionsButton->setMenu(optionsMenu); m_matchCaseMenuEntry = optionsMenu->addAction(tr("Match case")); m_matchCaseMenuEntry->setCheckable(true); m_matchCaseMenuEntry->setChecked(true); connect(m_matchCaseMenuEntry, SIGNAL(toggled(bool)), this, SIGNAL(searchCriteriaChanged())); m_useRegularExpressionMenuEntry = optionsMenu->addAction(tr("Regular expression")); m_useRegularExpressionMenuEntry->setCheckable(true); connect(m_useRegularExpressionMenuEntry, SIGNAL(toggled(bool)), this, SIGNAL(searchCriteriaChanged())); m_highlightMatchesMenuEntry = optionsMenu->addAction(tr("Highlight all matches")); m_highlightMatchesMenuEntry->setCheckable(true); m_highlightMatchesMenuEntry->setChecked(true); connect(m_highlightMatchesMenuEntry, SIGNAL(toggled(bool)), this, SIGNAL(highlightMatchesChanged(bool))); } SearchBar::~SearchBar() { } QString SearchBar::searchText() { return widget.searchTextEdit->text(); } bool SearchBar::useRegularExpression() { return m_useRegularExpressionMenuEntry->isChecked(); } bool SearchBar::matchCase() { return m_matchCaseMenuEntry->isChecked(); } bool SearchBar::highlightAllMatches() { return m_highlightMatchesMenuEntry->isChecked(); } void SearchBar::show() { QWidget::show(); widget.searchTextEdit->setFocus(); } void SearchBar::noMatchFound() { QPalette palette; palette.setColor(widget.searchTextEdit->backgroundRole(), QColor(255, 128, 128)); widget.searchTextEdit->setPalette(palette); } void SearchBar::keyReleaseEvent(QKeyEvent* keyEvent) { if (keyEvent->key() == Qt::Key_Return || keyEvent->key() == Qt::Key_Enter) { if (keyEvent->modifiers() == Qt::ShiftModifier) { Q_EMIT findPrevious(); } else { Q_EMIT findNext(); } } else if (keyEvent->key() == Qt::Key_Escape) { hide(); } } void SearchBar::clearBackgroundColor() { QPalette p; p.setColor(QPalette::Base, Qt::white); widget.searchTextEdit->setPalette(p); } deepin-terminal-5.2.11/3rdparty/terminalwidget/lib/SearchBar.h000066400000000000000000000031551370157770500242350ustar00rootroot00000000000000/* Copyright 2013 Christian Surlykke This program is free software; you can redistribute it and/or modify it under the terms of the 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 _SEARCHBAR_H #define _SEARCHBAR_H #include #include "ui_SearchBar.h" #include "HistorySearch.h" class SearchBar : public QWidget { Q_OBJECT public: SearchBar(QWidget* parent = nullptr); virtual ~SearchBar(); virtual void show(); QString searchText(); bool useRegularExpression(); bool matchCase(); bool highlightAllMatches(); public slots: void noMatchFound(); signals: void searchCriteriaChanged(); void highlightMatchesChanged(bool highlightMatches); void findNext(); void findPrevious(); protected: virtual void keyReleaseEvent(QKeyEvent* keyEvent); private slots: void clearBackgroundColor(); private: Ui::SearchBar widget; QAction *m_matchCaseMenuEntry; QAction *m_useRegularExpressionMenuEntry; QAction *m_highlightMatchesMenuEntry; }; #endif /* _SEARCHBAR_H */ deepin-terminal-5.2.11/3rdparty/terminalwidget/lib/SearchBar.ui000066400000000000000000000035121370157770500244200ustar00rootroot00000000000000 SearchBar 0 0 399 40 SearchBar X Find: < > ... QToolButton::InstantPopup deepin-terminal-5.2.11/3rdparty/terminalwidget/lib/Session.cpp000066400000000000000000001050221370157770500243550ustar00rootroot00000000000000/* This file is part of Konsole Copyright (C) 2006-2007 by Robert Knight Copyright (C) 1997,1998 by Lars Doelle Rewritten for QT4 by e_k , Copyright (C)2008 This program is free software; you can redistribute it and/or modify it under the terms of the 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. */ // Own #include "Session.h" // Standard #include // Qt #include #include #include #include #include #include #include #include #include "Pty.h" #include "ProcessInfo.h" //#include "kptyprocess.h" #include "TerminalDisplay.h" #include "ShellCommand.h" #include "Vt102Emulation.h" using namespace Konsole; int Session::lastSessionId = 0; Session::Session(QObject* parent) : QObject(parent), _shellProcess(nullptr) , _emulation(nullptr) , _monitorActivity(false) , _monitorSilence(false) , _notifiedActivity(false) , _autoClose(true) , _wantedClose(false) , _silenceSeconds(10) , _isTitleChanged(false) , _addToUtmp(false) // disabled by default because of a bug encountered on certain systems // which caused Konsole to hang when closing a tab and then opening a new // one. A 'QProcess destroyed while still running' warning was being // printed to the terminal. Likely a problem in KPty::logout() // or KPty::login() which uses a QProcess to start /usr/bin/utempter , _flowControl(true) , _fullScripting(false) , _sessionId(0) , _sessionProcessInfo(nullptr) , _foregroundProcessInfo(nullptr) // , _zmodemBusy(false) // , _zmodemProc(0) // , _zmodemProgress(0) , _hasDarkBackground(false) { //prepare DBus communication // new SessionAdaptor(this); _sessionId = ++lastSessionId; // QDBusConnection::sessionBus().registerObject(QLatin1String("/Sessions/")+QString::number(_sessionId), this); //create teletype for I/O with shell process _shellProcess = new Pty(); _shellProcess->setSessionId(_sessionId); ptySlaveFd = _shellProcess->pty()->slaveFd(); //create emulation backend _emulation = new Vt102Emulation(); _emulation->setSessionId(_sessionId); connect( _emulation, SIGNAL( titleChanged( int, const QString & ) ), this, SLOT( setUserTitle( int, const QString & ) ) ); connect( _emulation, SIGNAL( stateSet(int) ), this, SLOT( activityStateSet(int) ) ); // connect( _emulation, SIGNAL( zmodemDetected() ), this , // SLOT( fireZModemDetected() ) ); connect( _emulation, SIGNAL( changeTabTextColorRequest( int ) ), this, SIGNAL( changeTabTextColorRequest( int ) ) ); connect( _emulation, SIGNAL(profileChangeCommandReceived(const QString &)), this, SIGNAL( profileChangeCommandReceived(const QString &)) ); connect(_emulation, SIGNAL(imageResizeRequest(QSize)), this, SLOT(onEmulationSizeChange(QSize))); connect(_emulation, SIGNAL(imageSizeChanged(int, int)), this, SLOT(onViewSizeChange(int, int))); connect(_emulation, &Vt102Emulation::cursorChanged, this, &Session::cursorChanged); //connect teletype to emulation backend _shellProcess->setUtf8Mode(_emulation->utf8()); connect( _shellProcess,SIGNAL(receivedData(const char *,int)),this, SLOT(onReceiveBlock(const char *,int)) ); connect( _emulation,SIGNAL(sendData(const char *,int)),_shellProcess, SLOT(sendData(const char *,int)) ); connect( _emulation,SIGNAL(lockPtyRequest(bool)),_shellProcess,SLOT(lockPty(bool)) ); connect( _emulation,SIGNAL(useUtf8Request(bool)),_shellProcess,SLOT(setUtf8Mode(bool)) ); connect( _shellProcess,SIGNAL(finished(int,QProcess::ExitStatus)), this, SLOT(done(int)) ); // not in kprocess anymore connect( _shellProcess,SIGNAL(done(int)), this, SLOT(done(int)) ); /******** Modify by nt001000 renfeixiang 2020-05-27:修改 增加参数区别remove和purge卸载命令 Begin***************/ // 用于卸载终端弹出框提示 connect( _shellProcess,SIGNAL(ptyUninstallTerminal(QString)), this, SIGNAL(sessionUninstallTerminal(QString)) ); /******** Modify by nt001000 renfeixiang 2020-05-27:修改 增加参数区别remove和purge卸载命令 Begin***************/ //setup timer for monitoring session activity _monitorTimer = new QTimer(this); _monitorTimer->setSingleShot(true); connect(_monitorTimer, SIGNAL(timeout()), this, SLOT(monitorTimerDone())); } WId Session::windowId() const { // On Qt5, requesting window IDs breaks QQuickWidget and the likes, // for example, see the following bug reports: // https://bugreports.qt.io/browse/QTBUG-40765 // https://codereview.qt-project.org/#/c/94880/ return 0; } void Session::setDarkBackground(bool darkBackground) { _hasDarkBackground = darkBackground; } bool Session::hasDarkBackground() const { return _hasDarkBackground; } bool Session::isRunning() const { return _shellProcess->state() == QProcess::Running; } void Session::setCodec(QTextCodec * codec) { emulation()->setCodec(codec); } void Session::setProgram(const QString & program) { _program = ShellCommand::expand(program); } void Session::setInitialWorkingDirectory(const QString & dir) { _initialWorkingDir = ShellCommand::expand(dir); } void Session::setArguments(const QStringList & arguments) { _arguments = ShellCommand::expand(arguments); } QList Session::views() const { return _views; } void Session::addView(TerminalDisplay * widget) { Q_ASSERT( !_views.contains(widget) ); _views.append(widget); if ( _emulation != nullptr ) { // connect emulation - view signals and slots connect( widget , SIGNAL(keyPressedSignal(QKeyEvent *)) , _emulation , SLOT(sendKeyEvent(QKeyEvent *)) ); connect( widget , SIGNAL(mouseSignal(int,int,int,int)) , _emulation , SLOT(sendMouseEvent(int,int,int,int)) ); connect( widget , SIGNAL(sendStringToEmu(const char *)) , _emulation , SLOT(sendString(const char *)) ); // allow emulation to notify view when the foreground process // indicates whether or not it is interested in mouse signals connect( _emulation , SIGNAL(programUsesMouseChanged(bool)) , widget , SLOT(setUsesMouse(bool)) ); widget->setUsesMouse( _emulation->programUsesMouse() ); connect( _emulation , SIGNAL(programBracketedPasteModeChanged(bool)) , widget , SLOT(setBracketedPasteMode(bool)) ); widget->setBracketedPasteMode(_emulation->programBracketedPasteMode()); widget->setScreenWindow(_emulation->createWindow()); } //connect view signals and slots QObject::connect( widget ,SIGNAL(changedContentSizeSignal(int,int)),this, SLOT(onViewSizeChange(int,int))); QObject::connect( widget ,SIGNAL(destroyed(QObject *)) , this , SLOT(viewDestroyed(QObject *)) ); //slot for close QObject::connect(this, SIGNAL(finished()), widget, SLOT(close())); } void Session::viewDestroyed(QObject * view) { TerminalDisplay * display = (TerminalDisplay *)view; Q_ASSERT( _views.contains(display) ); removeView(display); } void Session::removeView(TerminalDisplay * widget) { _views.removeAll(widget); disconnect(widget,nullptr,this,nullptr); if ( _emulation != nullptr ) { // disconnect // - key presses signals from widget // - mouse activity signals from widget // - string sending signals from widget // // ... and any other signals connected in addView() disconnect( widget, nullptr, _emulation, nullptr); // disconnect state change signals emitted by emulation disconnect( _emulation , nullptr , widget , nullptr); } // close the session automatically when the last view is removed if ( _views.count() == 0 ) { close(); } } void Session::run() { // Upon a KPty error, there is no description on what that error was... // Check to see if the given program is executable. /* ok iam not exactly sure where _program comes from - however it was set to /bin/bash on my system * Thats bad for BSD as its /usr/local/bin/bash there - its also bad for arch as its /usr/bin/bash there too! * So i added a check to see if /bin/bash exists - if no then we use $SHELL - if that does not exist either, we fall back to /bin/sh * As far as i know /bin/sh exists on every unix system.. You could also just put some ifdef __FREEBSD__ here but i think these 2 filechecks are worth * their computing time on any system - especially with the problem on arch linux beeing there too. */ QString exec = QString::fromLocal8Bit(QFile::encodeName(_program)); // if 'exec' is not specified, fall back to default shell. if that // is not set then fall back to /bin/sh // here we expect full path. If there is no fullpath let's expect it's // a custom shell (eg. python, etc.) available in the PATH. if (exec.startsWith(QLatin1Char('/')) || exec.isEmpty()) { const QString defaultShell{QLatin1String("/bin/sh")}; QFile excheck(exec); if ( exec.isEmpty() || !excheck.exists() ) { exec = QString::fromLocal8Bit(qgetenv("SHELL")); } excheck.setFileName(exec); if ( exec.isEmpty() || !excheck.exists() ) { qWarning() << "Neither default shell nor $SHELL is set to a correct path. Fallback to" << defaultShell; exec = defaultShell; } } // _arguments sometimes contain ("") so isEmpty() // or count() does not work as expected... QString argsTmp(_arguments.join(QLatin1Char(' ')).trimmed()); QStringList arguments; arguments << exec; if (argsTmp.length()) arguments << _arguments; QString cwd = QDir::currentPath(); if (!_initialWorkingDir.isEmpty()) { _shellProcess->setWorkingDirectory(_initialWorkingDir); } else { _shellProcess->setWorkingDirectory(cwd); } _shellProcess->setFlowControlEnabled(_flowControl); _shellProcess->setErase(_emulation->eraseChar()); // this is not strictly accurate use of the COLORFGBG variable. This does not // tell the terminal exactly which colors are being used, but instead approximates // the color scheme as "black on white" or "white on black" depending on whether // the background color is deemed dark or not QString backgroundColorHint = _hasDarkBackground ? QLatin1String("COLORFGBG=15;0") : QLatin1String("COLORFGBG=0;15"); /* if we do all the checking if this shell exists then we use it ;) * Dont know about the arguments though.. maybe youll need some more checking im not sure * However this works on Arch and FreeBSD now. */ int result = _shellProcess->start(exec, arguments, _environment << backgroundColorHint, windowId(), _addToUtmp); if (result < 0) { //qDebug() << "CRASHED! result: " << result<setWriteable(false); // We are reachable via kwrited. emit started(); } void Session::runEmptyPTY() { _shellProcess->setFlowControlEnabled(_flowControl); _shellProcess->setErase(_emulation->eraseChar()); _shellProcess->setWriteable(false); // disconnet send data from emulator to internal terminal process disconnect( _emulation,SIGNAL(sendData(const char *,int)), _shellProcess, SLOT(sendData(const char *,int)) ); _shellProcess->setEmptyPTYProperties(); emit started(); } void Session::setUserTitle( int what, const QString & caption ) { //set to true if anything is actually changed (eg. old _nameTitle != new _nameTitle ) bool modified = false; // (btw: what=0 changes _userTitle and icon, what=1 only icon, what=2 only _nameTitle if ((what == 0) || (what == 2)) { _isTitleChanged = true; if ( _userTitle != caption ) { _userTitle = caption; modified = true; } } if ((what == 0) || (what == 1)) { _isTitleChanged = true; if ( _iconText != caption ) { _iconText = caption; modified = true; } } if (what == 11) { QString colorString = caption.section(QLatin1Char(';'),0,0); //qDebug() << __FILE__ << __LINE__ << ": setting background colour to " << colorString; QColor backColor = QColor(colorString); if (backColor.isValid()) { // change color via \033]11;Color\007 if (backColor != _modifiedBackground) { _modifiedBackground = backColor; // bail out here until the code to connect the terminal display // to the changeBackgroundColor() signal has been written // and tested - just so we don't forget to do this. Q_ASSERT( 0 ); emit changeBackgroundColorRequest(backColor); } } } if (what == 30) { _isTitleChanged = true; if ( _nameTitle != caption ) { setTitle(Session::NameRole,caption); return; } } if (what == 31) { QString cwd=caption; cwd=cwd.replace( QRegExp(QLatin1String("^~")), QDir::homePath() ); emit openUrlRequest(cwd); } // change icon via \033]32;Icon\007 if (what == 32) { _isTitleChanged = true; if ( _iconName != caption ) { _iconName = caption; modified = true; } } if (what == 50) { emit profileChangeCommandReceived(caption); return; } if ( modified ) { emit titleChanged(); } } QString Session::userTitle() const { return _userTitle; } void Session::setTabTitleFormat(TabTitleContext context , const QString & format) { if ( context == LocalTabTitle ) { _localTabTitleFormat = format; ProcessInfo *process = getProcessInfo(); process->setUserNameRequired(format.contains(QLatin1String("%u"))); } else if ( context == RemoteTabTitle ) { _remoteTabTitleFormat = format; } } QString Session::tabTitleFormat(TabTitleContext context) const { if ( context == LocalTabTitle ) { return _localTabTitleFormat; } else if ( context == RemoteTabTitle ) { return _remoteTabTitleFormat; } return QString(); } void Session::monitorTimerDone() { //FIXME: The idea here is that the notification popup will appear to tell the user than output from //the terminal has stopped and the popup will disappear when the user activates the session. // //This breaks with the addition of multiple views of a session. The popup should disappear //when any of the views of the session becomes active //FIXME: Make message text for this notification and the activity notification more descriptive. if (_monitorSilence) { emit silence(); emit stateChanged(NOTIFYSILENCE); } else { emit stateChanged(NOTIFYNORMAL); } _notifiedActivity=false; } void Session::activityStateSet(int state) { if (state==NOTIFYBELL) { emit bellRequest(QString("Bell in session '%1'").arg(_nameTitle)); } else if (state==NOTIFYACTIVITY) { if (_monitorSilence) { _monitorTimer->start(_silenceSeconds*1000); } if ( _monitorActivity ) { //FIXME: See comments in Session::monitorTimerDone() if (!_notifiedActivity) { _notifiedActivity=true; emit activity(); } } } if ( state==NOTIFYACTIVITY && !_monitorActivity ) { state = NOTIFYNORMAL; } if ( state==NOTIFYSILENCE && !_monitorSilence ) { state = NOTIFYNORMAL; } emit stateChanged(state); } void Session::onViewSizeChange(int height, int width) { updateTerminalSize(height, width); } void Session::onEmulationSizeChange(QSize size) { setSize(size); } void Session::updateTerminalSize(int height, int width) { QListIterator viewIter(_views); int minLines = -1; int minColumns = -1; // minimum number of lines and columns that views require for // their size to be taken into consideration ( to avoid problems // with new view widgets which haven't yet been set to their correct size ) /***mod by ut001121 zhangmeng 20200615 窗口初始化完成之后修改终端显示内容为最小一行 修复BUG32779, BUG32778***/ const int VIEW_LINES_THRESHOLD = (height==1 || width==1) ? 2 : 1; const int VIEW_COLUMNS_THRESHOLD = 2; //select largest number of lines and columns that will fit in all visible views while ( viewIter.hasNext() ) { TerminalDisplay * view = viewIter.next(); if ( view->isHidden() == false && view->lines() >= VIEW_LINES_THRESHOLD && view->columns() >= VIEW_COLUMNS_THRESHOLD ) { minLines = (minLines == -1) ? view->lines() : qMin( minLines , view->lines() ); minColumns = (minColumns == -1) ? view->columns() : qMin( minColumns , view->columns() ); } } // backend emulation must have a _terminal of at least 1 column x 1 line in size if ( minLines > 0 && minColumns > 0 ) { _emulation->setImageSize( minLines , minColumns ); _shellProcess->setWindowSize( minLines , minColumns ); } } void Session::refresh() { // attempt to get the shell process to redraw the display // // this requires the program running in the shell // to cooperate by sending an update in response to // a window size change // // the window size is changed twice, first made slightly larger and then // resized back to its normal size so that there is actually a change // in the window size (some shells do nothing if the // new and old sizes are the same) // // if there is a more 'correct' way to do this, please // send an email with method or patches to konsole-devel@kde.org const QSize existingSize = _shellProcess->windowSize(); _shellProcess->setWindowSize(existingSize.height(),existingSize.width()+1); _shellProcess->setWindowSize(existingSize.height(),existingSize.width()); } bool Session::sendSignal(int signal) { int result = ::kill(_shellProcess->pid(),signal); if ( result == 0 ) { _shellProcess->waitForFinished(); return true; } else return false; } void Session::close() { _autoClose = true; _wantedClose = true; if (!_shellProcess->isRunning() || !sendSignal(SIGHUP)) { // Forced close. QTimer::singleShot(1, this, SIGNAL(finished())); } } void Session::sendText(const QString & text) const { _emulation->sendText(text); } void Session::sendKeyEvent(QKeyEvent* e) const { _emulation->sendKeyEvent(e); } Session::~Session() { _wantedClose = true; if(nullptr != _foregroundProcessInfo){ delete _foregroundProcessInfo; } if(nullptr != _sessionProcessInfo){ delete _sessionProcessInfo; } if(nullptr != _emulation){ delete _emulation; } if(nullptr != _shellProcess){ delete _shellProcess; } // delete _zmodemProc; } void Session::setProfileKey(const QString & key) { _profileKey = key; emit profileChanged(key); } QString Session::profileKey() const { return _profileKey; } void Session::done(int exitStatus) { qDebug()<<"done exitStatus:"<exitStatus(); if (_autoClose || _wantedClose) { emit finished(); return; } if(exitStatus != 0) { QString message; QString infoText; if (exitStatus == -1){ infoText.sprintf("There was an error ctreating the child processfor this teminal. \n" "Faild to execute child process \"%s\"(No such file or directory)!", _program.toUtf8().data()); message = "Session crashed."; } else { infoText.sprintf("The child process exit normally with status %d.", exitStatus); message.sprintf("Session '%s' exited with status %d.", _nameTitle.toUtf8().data(), exitStatus); } _userTitle = message; //sendText(infoText); emit titleChanged(); } } Emulation * Session::emulation() const { return _emulation; } QString Session::keyBindings() const { return _emulation->keyBindings(); } void Session::setBackspaceMode(char *key, int length) { _emulation->setBackspaceMode(key, length); } void Session::setDeleteMode(char *key, int length) { _emulation->setDeleteMode(key, length); } QStringList Session::environment() const { return _environment; } void Session::setEnvironment(const QStringList & environment) { _environment = environment; } int Session::sessionId() const { return _sessionId; } void Session::setKeyBindings(const QString & id) { _emulation->setKeyBindings(id); } void Session::setTitle(TitleRole role , const QString & newTitle) { if ( title(role) != newTitle ) { if ( role == NameRole ) { _nameTitle = newTitle; } else if ( role == DisplayedTitleRole ) { _displayTitle = newTitle; // without these, that title will be overridden by the expansion of // title format shortly after, which will confuses users. _localTabTitleFormat = newTitle; _remoteTabTitleFormat = newTitle; // qDebug() << "curr running process:" << newTitle << endl; } emit titleChanged(); } } QString Session::title(TitleRole role) const { if ( role == NameRole ) { return _nameTitle; } else if ( role == DisplayedTitleRole ) { return _displayTitle; } else { return QString(); } } void Session::setIconName(const QString & iconName) { if ( iconName != _iconName ) { _iconName = iconName; emit titleChanged(); } } void Session::setIconText(const QString & iconText) { _iconText = iconText; //kDebug(1211)<<"Session setIconText " << _iconText; } QString Session::iconName() const { return _iconName; } QString Session::iconText() const { return _iconText; } bool Session::isTitleChanged() const { return _isTitleChanged; } void Session::setHistoryType(const HistoryType & hType) { _emulation->setHistory(hType); } const HistoryType & Session::historyType() const { return _emulation->history(); } void Session::clearHistory() { _emulation->clearHistory(); } QStringList Session::arguments() const { return _arguments; } QString Session::program() const { return _program; } // unused currently bool Session::isMonitorActivity() const { return _monitorActivity; } // unused currently bool Session::isMonitorSilence() const { return _monitorSilence; } void Session::setMonitorActivity(bool _monitor) { _monitorActivity=_monitor; _notifiedActivity=false; activityStateSet(NOTIFYNORMAL); } void Session::setMonitorSilence(bool _monitor) { if (_monitorSilence==_monitor) { return; } _monitorSilence=_monitor; if (_monitorSilence) { _monitorTimer->start(_silenceSeconds*1000); } else { _monitorTimer->stop(); } activityStateSet(NOTIFYNORMAL); } void Session::setMonitorSilenceSeconds(int seconds) { _silenceSeconds=seconds; if (_monitorSilence) { _monitorTimer->start(_silenceSeconds*1000); } } void Session::setAddToUtmp(bool set) { _addToUtmp = set; } void Session::setFlowControlEnabled(bool enabled) { if (_flowControl == enabled) { return; } _flowControl = enabled; if (_shellProcess) { _shellProcess->setFlowControlEnabled(_flowControl); } emit flowControlEnabledChanged(enabled); } bool Session::flowControlEnabled() const { return _flowControl; } //void Session::fireZModemDetected() //{ // if (!_zmodemBusy) // { // QTimer::singleShot(10, this, SIGNAL(zmodemDetected())); // _zmodemBusy = true; // } //} //void Session::cancelZModem() //{ // _shellProcess->sendData("\030\030\030\030", 4); // Abort // _zmodemBusy = false; //} //void Session::startZModem(const QString &zmodem, const QString &dir, const QStringList &list) //{ // _zmodemBusy = true; // _zmodemProc = new KProcess(); // _zmodemProc->setOutputChannelMode( KProcess::SeparateChannels ); // // *_zmodemProc << zmodem << "-v" << list; // // if (!dir.isEmpty()) // _zmodemProc->setWorkingDirectory(dir); // // _zmodemProc->start(); // // connect(_zmodemProc,SIGNAL (readyReadStandardOutput()), // this, SLOT(zmodemReadAndSendBlock())); // connect(_zmodemProc,SIGNAL (readyReadStandardError()), // this, SLOT(zmodemReadStatus())); // connect(_zmodemProc,SIGNAL (finished(int,QProcess::ExitStatus)), // this, SLOT(zmodemFinished())); // // disconnect( _shellProcess,SIGNAL(block_in(const char*,int)), this, SLOT(onReceiveBlock(const char*,int)) ); // connect( _shellProcess,SIGNAL(block_in(const char*,int)), this, SLOT(zmodemRcvBlock(const char*,int)) ); // // _zmodemProgress = new ZModemDialog(QApplication::activeWindow(), false, // i18n("ZModem Progress")); // // connect(_zmodemProgress, SIGNAL(user1Clicked()), // this, SLOT(zmodemDone())); // // _zmodemProgress->show(); //} /*void Session::zmodemReadAndSendBlock() { _zmodemProc->setReadChannel( QProcess::StandardOutput ); QByteArray data = _zmodemProc->readAll(); if ( data.count() == 0 ) return; _shellProcess->sendData(data.constData(),data.count()); } */ /* void Session::zmodemReadStatus() { _zmodemProc->setReadChannel( QProcess::StandardError ); QByteArray msg = _zmodemProc->readAll(); while(!msg.isEmpty()) { int i = msg.indexOf('\015'); int j = msg.indexOf('\012'); QByteArray txt; if ((i != -1) && ((j == -1) || (i < j))) { msg = msg.mid(i+1); } else if (j != -1) { txt = msg.left(j); msg = msg.mid(j+1); } else { txt = msg; msg.truncate(0); } if (!txt.isEmpty()) _zmodemProgress->addProgressText(QString::fromLocal8Bit(txt)); } } */ /* void Session::zmodemRcvBlock(const char *data, int len) { QByteArray ba( data, len ); _zmodemProc->write( ba ); } */ /* void Session::zmodemFinished() { if (_zmodemProc) { delete _zmodemProc; _zmodemProc = 0; _zmodemBusy = false; disconnect( _shellProcess,SIGNAL(block_in(const char*,int)), this ,SLOT(zmodemRcvBlock(const char*,int)) ); connect( _shellProcess,SIGNAL(block_in(const char*,int)), this, SLOT(onReceiveBlock(const char*,int)) ); _shellProcess->sendData("\030\030\030\030", 4); // Abort _shellProcess->sendData("\001\013\n", 3); // Try to get prompt back _zmodemProgress->transferDone(); } } */ void Session::onReceiveBlock( const char * buf, int len ) { _emulation->receiveData( buf, len ); emit receivedData( QString::fromLatin1( buf, len ) ); } QSize Session::size() { return _emulation->imageSize(); } void Session::setSize(const QSize & size) { if ((size.width() <= 1) || (size.height() <= 1)) { return; } emit resizeRequest(size); } QString Session::getDynamicProcessName() { bool ok = false; QString processName = getProcessInfo()->name(&ok); if (ok) { return processName; } return QString::fromLocal8Bit(qgetenv("SHELL")); } int Session::getDynamicProcessId() { bool ok = false; int pid = getProcessInfo()->pid(&ok); if (ok) { if (this->isForegroundProcessActive()) { return pid; } } return 0; } void Session::updateWorkingDirectory() { updateSessionProcessInfo(); const QString currentDir = _sessionProcessInfo->validCurrentDir(); if (currentDir != _currentWorkingDir) { _currentWorkingDir = currentDir; emit currentDirectoryChanged(_currentWorkingDir); } } int Session::foregroundProcessId() { int pid; bool ok = false; pid = getProcessInfo()->pid(&ok); if (!ok) { pid = -1; } return pid; } bool Session::isForegroundProcessActive() { // foreground process info is always updated after this return (_shellProcess->pid() != _shellProcess->foregroundProcessGroup()); } QString Session::foregroundProcessName() { QString name; if (updateForegroundProcessInfo()) { bool ok = false; name = _foregroundProcessInfo->name(&ok); if (!ok) { name.clear(); } } return name; } int Session::processId() const { return _shellProcess->pid(); } ProcessInfo *Session::getProcessInfo() { ProcessInfo *process = nullptr; if (isForegroundProcessActive() && updateForegroundProcessInfo()) { process = _foregroundProcessInfo; } else { updateSessionProcessInfo(); process = _sessionProcessInfo; } return process; } void Session::updateSessionProcessInfo() { Q_ASSERT(_shellProcess); bool ok; // The checking for pid changing looks stupid, but it is needed // at the moment to workaround the problem that processId() might // return 0 if ((_sessionProcessInfo == nullptr) || (processId() != 0 && processId() != _sessionProcessInfo->pid(&ok))) { delete _sessionProcessInfo; _sessionProcessInfo = ProcessInfo::newInstance(processId(), tabTitleFormat(Session::LocalTabTitle)); _sessionProcessInfo->setUserHomeDir(); } _sessionProcessInfo->update(); } bool Session::updateForegroundProcessInfo() { Q_ASSERT(_shellProcess); const int foregroundPid = _shellProcess->foregroundProcessGroup(); if (foregroundPid != _foregroundPid) { if(nullptr != _foregroundProcessInfo){ delete _foregroundProcessInfo; } _foregroundProcessInfo = ProcessInfo::newInstance(foregroundPid, tabTitleFormat(Session::LocalTabTitle)); _foregroundPid = foregroundPid; } if (_foregroundProcessInfo != nullptr) { _foregroundProcessInfo->update(); return _foregroundProcessInfo->isValid(); } else { return false; } } int Session::getPtySlaveFd() const { return ptySlaveFd; } /******************************************************************************* 1. @函数: getEraseChar 2. @作者: ut000610 戴正文 3. @日期: 2020-06-02 4. @说明: 获取tty的erase的字符 *******************************************************************************/ char Session::getEraseChar() { return _shellProcess->erase(); } SessionGroup::SessionGroup() : _masterMode(0) { } SessionGroup::~SessionGroup() { // disconnect all connectAll(false); } int SessionGroup::masterMode() const { return _masterMode; } QList SessionGroup::sessions() const { return _sessions.keys(); } bool SessionGroup::masterStatus(Session * session) const { return _sessions[session]; } void SessionGroup::addSession(Session * session) { _sessions.insert(session,false); QListIterator masterIter(masters()); while ( masterIter.hasNext() ) { connectPair(masterIter.next(),session); } } void SessionGroup::removeSession(Session * session) { setMasterStatus(session,false); QListIterator masterIter(masters()); while ( masterIter.hasNext() ) { disconnectPair(masterIter.next(),session); } _sessions.remove(session); } void SessionGroup::setMasterMode(int mode) { _masterMode = mode; connectAll(false); connectAll(true); } QList SessionGroup::masters() const { return _sessions.keys(true); } void SessionGroup::connectAll(bool connect) { QListIterator masterIter(masters()); while ( masterIter.hasNext() ) { Session * master = masterIter.next(); QListIterator otherIter(_sessions.keys()); while ( otherIter.hasNext() ) { Session * other = otherIter.next(); if ( other != master ) { if ( connect ) { connectPair(master,other); } else { disconnectPair(master,other); } } } } } void SessionGroup::setMasterStatus(Session * session, bool master) { bool wasMaster = _sessions[session]; _sessions[session] = master; if ((!wasMaster && !master) || (wasMaster && master)) { return; } QListIterator iter(_sessions.keys()); while (iter.hasNext()) { Session * other = iter.next(); if (other != session) { if (master) { connectPair(session, other); } else { disconnectPair(session, other); } } } } void SessionGroup::connectPair(Session * master , Session * other) { // qDebug() << k_funcinfo; if ( _masterMode & CopyInputToAll ) { qDebug() << "Connection session " << master->nameTitle() << "to" << other->nameTitle(); connect( master->emulation() , SIGNAL(sendData(const char *,int)) , other->emulation() , SLOT(sendString(const char *,int)) ); } } void SessionGroup::disconnectPair(Session * master , Session * other) { // qDebug() << k_funcinfo; if ( _masterMode & CopyInputToAll ) { qDebug() << "Disconnecting session " << master->nameTitle() << "from" << other->nameTitle(); disconnect( master->emulation() , SIGNAL(sendData(const char *,int)) , other->emulation() , SLOT(sendString(const char *,int)) ); } } //#include "moc_Session.cpp" deepin-terminal-5.2.11/3rdparty/terminalwidget/lib/Session.h000066400000000000000000000531201370157770500240230ustar00rootroot00000000000000/* This file is part of Konsole, an X terminal. Copyright (C) 2007 by Robert Knight Copyright (C) 1997,1998 by Lars Doelle Rewritten for QT4 by e_k , Copyright (C)2008 This program is free software; you can redistribute it and/or modify it under the terms of the 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 #include #include #include "Emulation.h" #include "History.h" class KProcess; namespace Konsole { class Emulation; class Pty; class TerminalDisplay; class ProcessInfo; //class ZModemDialog; /** * 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 Session : public QObject { Q_OBJECT 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. */ Session(QObject* parent = nullptr); ~Session() override; /** * Returns true if the session is currently running. This will be true * after run() has been called successfully. */ bool isRunning() const; /** * Sets the profile associated with this session. * * @param profileKey A key which can be used to obtain the current * profile settings from the SessionManager */ void setProfileKey(const QString & profileKey); /** * Returns the profile key associated with this session. * This can be passed to the SessionManager to obtain the current * profile settings. */ QString profileKey() 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 environment of this session as a list of strings like * VARIABLE=VALUE */ QStringList environment() const; /** * Sets the environment for this session. * @p environment should be a list of strings like * VARIABLE=VALUE */ void setEnvironment(const QStringList & environment); /** Returns the unique ID for this session. */ int sessionId() const; /** * 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; /** * 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 }; /** * Sets the format used by this session for tab titles. * * @param context The context whoose 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 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 ); /** * 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 & type); /** * Returns the type of history store used by this session. */ const HistoryType & historyType() const; /** * Clears the history store used by this session. */ void clearHistory(); /** * 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. */ void setMonitorActivity(bool); /** Returns true if monitoring for activity is enabled. */ 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() */ void setMonitorSilence(bool); /** * Returns true if monitoring for inactivity (silence) * in the session is enabled. */ bool isMonitorSilence() const; /** See setMonitorSilence() */ void setMonitorSilenceSeconds(int seconds); /** * 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 id 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 & id); /** Returns the name of the key bindings used by this session. */ QString keyBindings() const; /******** Modify by ut000610 daizhengwen 2020-06-02: 设置删除和退格按钮****************/ void setBackspaceMode(char *key, int length); void setDeleteMode(char *key, int length); /********************* Modify by ut000610 daizhengwen End ************************/ /** * 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 }; /** Sets the session's title for the specified @p role to @p title. */ void setTitle(TitleRole role , const QString & title); /** Returns the session's title for the specified @p role. */ QString title(TitleRole role) const; /** Convenience method used to read the name property. Returns title(Session::NameRole). */ QString nameTitle() const { return title(Session::NameRole); } /** 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; /** 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; /** Flag if the title/icon was changed by user/shell. */ bool isTitleChanged() const; /** Specifies whether a utmp entry should be created for the pty used by this session. */ void setAddToUtmp(bool); /** Sends the specified @p signal to the terminal process. */ bool sendSignal(int signal); /** * Specifies whether to close the session automatically when the terminal * process terminates. */ void setAutoClose(bool b) { _autoClose = b; } /** * Sets whether flow control is enabled for this terminal * session. */ void setFlowControlEnabled(bool enabled); /** Returns whether flow control is enabled for this terminal session. */ bool flowControlEnabled() const; /** * Sends @p text to the current foreground terminal program. */ void sendText(const QString & text) const; void sendKeyEvent(QKeyEvent* e) const; /** Returns dynamic process name. */ QString getDynamicProcessName(); /** Returns dynamic process id */ int getDynamicProcessId(); /** * Returns the process id of the terminal process. * This is the id used by the system API to refer to the process. */ int processId() const; /** * Returns foreground process's name */ QString foregroundProcessName(); /** * Get process info of current Session */ ProcessInfo *getProcessInfo(); void updateSessionProcessInfo(); bool updateForegroundProcessInfo(); void updateWorkingDirectory(); /** * 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. */ int foregroundProcessId(); /** Returns true if the user has started a program in the session. */ bool isForegroundProcessActive(); /** 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); /** Sets the text codec used by this session's terminal emulation. */ void setCodec(QTextCodec * codec); /** * 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); /** * Returns true if the session has a dark background. * See setDarkBackground() */ bool hasDarkBackground() const; /** * 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 &rz, const QString &dir, const QStringList &list); // void cancelZModem(); // bool isZModemBusy() { return _zmodemBusy; } /** * Returns a pty slave file descriptor. * This can be used for display and control * a remote terminal. */ int getPtySlaveFd() const; // 获取此时tty的eraseChar char getEraseChar(); public slots: /** * Starts the terminal session. * * This creates the terminal process and connects the teletype to it. */ void run(); /** * Starts the terminal session for "as is" PTY * (without the direction a data to internal terminal process). * It can be used for control or display a remote/external terminal. */ void runEmptyPTY(); /** * Closes the terminal session. This sends a hangup signal * (SIGHUP) to the terminal process and causes the done(Session*) * signal to be emitted. */ void close(); /** * Changes the session title or other customizable aspects of the terminal * emulation display. For a list of what may be changed see the * Emulation::titleChanged() signal. */ void setUserTitle( int, const QString & caption ); signals: /** Emitted when the terminal process starts. */ void started(); /** * Emitted when the terminal process exits. */ void finished(); /** * Emitted when output is received from the terminal process. */ void receivedData( const QString & text ); /** Emitted when the session's title has changed. */ void titleChanged(); /** Emitted when the session's profile has changed. */ void profileChanged(const QString & profile); /** * 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 color the text for any tabs associated with * this session should be changed; * * TODO: Document what the parameter does */ void changeTabTextColorRequest(int); /** * Requests that the background color of views on this session * should be changed. */ void changeBackgroundColorRequest(const QColor &); /** TODO: Document me. */ void openUrlRequest(const QString & url); /** TODO: Document me. */ // void zmodemDetected(); /** * 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); /** * Broker for Emulation::cursorChanged() signal */ void cursorChanged(Emulation::KeyboardCursorShape cursorShape, bool blinkingCursorEnabled); void silence(); void activity(); /******** Modify by nt001000 renfeixiang 2020-05-27:修改 增加参数区别remove和purge卸载命令 Begin***************/ bool sessionUninstallTerminal(QString commandname); /******** Modify by nt001000 renfeixiang 2020-05-27:修改 增加参数区别remove和purge卸载命令 end***************/ private slots: void done(int); // void fireZModemDetected(); void onReceiveBlock( const char * buffer, int len ); void monitorTimerDone(); void onViewSizeChange(int height, int width); void onEmulationSizeChange(QSize); void activityStateSet(int); //automatically detach views from sessions when view is destroyed void viewDestroyed(QObject * view); // void zmodemReadStatus(); // void zmodemReadAndSendBlock(); // void zmodemRcvBlock(const char *data, int len); // void zmodemFinished(); private: void updateTerminalSize(int height, int width); WId windowId() const; int _uniqueIdentifier; Pty *_shellProcess; Emulation * _emulation; QList _views; bool _monitorActivity; bool _monitorSilence; bool _notifiedActivity; bool _masterMode; bool _autoClose; bool _wantedClose; QTimer * _monitorTimer; int _silenceSeconds; QString _nameTitle; QString _displayTitle; QString _userTitle; QString _localTabTitleFormat; QString _remoteTabTitleFormat; QString _iconName; QString _iconText; // as set by: echo -en '\033]1;IconText\007 bool _isTitleChanged; ///< flag if the title/icon was changed by user bool _addToUtmp; bool _flowControl; bool _fullScripting; QString _program; QStringList _arguments; QStringList _environment; int _sessionId; QString _initialWorkingDir; QString _currentWorkingDir; QUrl _reportedWorkingUrl; ProcessInfo *_sessionProcessInfo = nullptr; ProcessInfo *_foregroundProcessInfo = nullptr; int _foregroundPid; // ZModem // bool _zmodemBusy; // KProcess* _zmodemProc; // ZModemDialog* _zmodemProgress; // Color/Font Changes by ESC Sequences QColor _modifiedBackground; // as set by: echo -en '\033]11;Color\007 QString _profileKey; bool _hasDarkBackground; static int lastSessionId; int ptySlaveFd; }; /** * 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. */ SessionGroup(); /** Destroys the session group and removes all connections between master and slave sessions. */ ~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 whoose 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: void connectPair(Session * master , Session * other); void disconnectPair(Session * master , Session * other); void connectAll(bool connect); QList masters() const; // maps sessions to their master status QHash _sessions; int _masterMode; }; } #endif deepin-terminal-5.2.11/3rdparty/terminalwidget/lib/SessionManager.cpp000066400000000000000000000073511370157770500256560ustar00rootroot00000000000000/* This file is part of Konsole, KDE's 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. */ // Own #include "SessionManager.h" // Qt #include #include #include // Konsole #include "Session.h" using namespace Konsole; Q_GLOBAL_STATIC(SessionManager, theSessionManager) SessionManager *SessionManager::instance() { return theSessionManager; } SessionManager::SessionManager() { } SessionManager::~SessionManager() { //closeAllSessions(); } void SessionManager::closeAllSessions() { // close remaining sessions for (int i = 0; i < _sessions.size(); i++) { Session *session = _sessions.at(i); session->close(); } _sessions.clear(); } QList SessionManager::sessions() const { return _sessions; } void SessionManager::sessionTerminated(Session *session) { Q_ASSERT(session); _sessions.removeAll(session); session->deleteLater(); } void SessionManager::saveSession(Session *session) { _sessions << session; } bool SessionManager::removeSession(int id) { if (_sessions.count() == 0) { return false; } int removeIndex = -1; for (int i = 0; i < _sessions.size(); i++) { Session *session = _sessions.at(i); if (session->sessionId() == id) { removeIndex = i; break; } } if (removeIndex >= 0) { _sessions.removeAt(removeIndex); return true; } return false; } int SessionManager::getSessionId(Session *session) { return session->sessionId(); } Session *SessionManager::idToSession(int id) { for (int i = 0; i < _sessions.size(); i++) { Session *session = _sessions.at(i); if (session->sessionId() == id) { return session; } } // this should not happen qDebug() << "Failed to find session for ID" << id; return nullptr; } void SessionManager::saveCurrShellPrompt(int sessionId, QString strPrompt) { strPrompt = strPrompt.trimmed(); _shellPromptSessionMap.insert(sessionId, strPrompt); } QString SessionManager::getCurrShellPrompt(int sessionId) { return _shellPromptSessionMap.value(sessionId); } void SessionManager::saveCurrShellCommand(int sessionId, QString strCommand) { strCommand = strCommand.trimmed(); _shellCommandSessionMap.insert(sessionId, strCommand); } QString SessionManager::getCurrShellCommand(int sessionId) { return _shellCommandSessionMap.value(sessionId); } void SessionManager::setTerminalResizing(int sessionId, bool bTerminalResizing) { _terminalResizeStateMap.insert(sessionId, bTerminalResizing); } bool SessionManager::isTerminalResizing(int sessionId) { return _terminalResizeStateMap.value(sessionId); } void SessionManager::setTerminalPathDepth(int sessionId, int pathDepth) { _terminalPathDepthMap.insert(sessionId, pathDepth); } int SessionManager::getTerminalPathDepth(int sessionId) { return _terminalPathDepthMap.value(sessionId); } deepin-terminal-5.2.11/3rdparty/terminalwidget/lib/SessionManager.h000066400000000000000000000066771370157770500253350ustar00rootroot00000000000000/* This file is part of Konsole, KDE's 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 SESSIONMANAGER_H #define SESSIONMANAGER_H // Qt #include #include #include #include namespace Konsole { class Session; /** * Manages running terminal sessions. */ class 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; /** * Returns the session manager instance. */ static SessionManager *instance(); /** Kill all running sessions. */ void closeAllSessions(); /** * Returns a list of active sessions. */ QList sessions() const; // System session management void saveSession(Session *session); bool removeSession(int id); int getSessionId(Session *session); Session *idToSession(int id); //用于存储当前的命令提示符 void saveCurrShellPrompt(int sessionId, QString strPrompt); QString getCurrShellPrompt(int sessionId); //用于存储当前的执行的命令字符串 void saveCurrShellCommand(int sessionId, QString strCommand); QString getCurrShellCommand(int sessionId); //用于存储终端控件是否正在resize的状态值 true表示正在resize void setTerminalResizing(int sessionId, bool bTerminalResizing); bool isTerminalResizing(int sessionId); //用于存储当前shell提示符的路径深度(比如/home/test 路径深度为2) void setTerminalPathDepth(int sessionId, int pathDepth); int getTerminalPathDepth(int sessionId); signals: void sessionIdle(bool isIdle); 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: QList _sessions; // list of running sessions QHash _restoreMapping; int _currTabSessionId; //存储当前的命令提示符Map QMap _shellPromptSessionMap; //存储当前的执行的命令字符串Map QMap _shellCommandSessionMap; //存储终端控件是否正在resize的状态值Map QMap _terminalResizeStateMap; //存储当前shell提示符的路径深度Map QMap _terminalPathDepthMap; }; } #endif //SESSIONMANAGER_H deepin-terminal-5.2.11/3rdparty/terminalwidget/lib/ShellCommand.cpp000066400000000000000000000107071370157770500253050ustar00rootroot00000000000000/* Copyright (C) 2007 by Robert Knight Rewritten for QT4 by e_k , Copyright (C)2008 This program is free software; you can redistribute it and/or modify it under the terms of the 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. */ // Own #include "ShellCommand.h" //some versions of gcc(4.3) require explicit include #include using namespace Konsole; // expands environment variables in 'text' // function copied from kdelibs/kio/kio/kurlcompletion.cpp static bool expandEnv(QString & text); ShellCommand::ShellCommand(const QString & fullCommand) { bool inQuotes = false; QString builder; for ( int i = 0 ; i < fullCommand.count() ; i++ ) { QChar ch = fullCommand[i]; const bool isLastChar = ( i == fullCommand.count() - 1 ); const bool isQuote = ( ch == QLatin1Char('\'') || ch == QLatin1Char('\"') ); if ( !isLastChar && isQuote ) { inQuotes = !inQuotes; } else { if ( (!ch.isSpace() || inQuotes) && !isQuote ) { builder.append(ch); } if ( (ch.isSpace() && !inQuotes) || ( i == fullCommand.count()-1 ) ) { _arguments << builder; builder.clear(); } } } } ShellCommand::ShellCommand(const QString & command , const QStringList & arguments) { _arguments = arguments; if ( !_arguments.isEmpty() ) { _arguments[0] = command; } } QString ShellCommand::fullCommand() const { return _arguments.join(QLatin1Char(' ')); } QString ShellCommand::command() const { if ( !_arguments.isEmpty() ) { return _arguments[0]; } else { return QString(); } } QStringList ShellCommand::arguments() const { return _arguments; } bool ShellCommand::isRootCommand() const { Q_ASSERT(0); // not implemented yet return false; } bool ShellCommand::isAvailable() const { Q_ASSERT(0); // not implemented yet return false; } QStringList ShellCommand::expand(const QStringList & items) { QStringList result; for(const QString &item : items) { result << expand(item); } return result; } QString ShellCommand::expand(const QString & text) { QString result = text; expandEnv(result); return result; } /* * expandEnv * * Expand environment variables in text. Escaped '$' characters are ignored. * Return true if any variables were expanded */ static bool expandEnv( QString & text ) { // Find all environment variables beginning with '$' // int pos = 0; bool expanded = false; while ( (pos = text.indexOf(QLatin1Char('$'), pos)) != -1 ) { // Skip escaped '$' // if ( pos > 0 && text.at(pos-1) == QLatin1Char('\\') ) { pos++; } // Variable found => expand // else { // Find the end of the variable = next '/' or ' ' // int pos2 = text.indexOf( QLatin1Char(' '), pos+1 ); int pos_tmp = text.indexOf( QLatin1Char('/'), pos+1 ); if ( pos2 == -1 || (pos_tmp != -1 && pos_tmp < pos2) ) { pos2 = pos_tmp; } if ( pos2 == -1 ) { pos2 = text.length(); } // Replace if the variable is terminated by '/' or ' ' // and defined // if ( pos2 >= 0 ) { int len = pos2 - pos; QString key = text.mid( pos+1, len-1); QString value = QString::fromLocal8Bit( qgetenv(key.toLocal8Bit().constData()) ); if ( !value.isEmpty() ) { expanded = true; text.replace( pos, len, value ); pos = pos + value.length(); } else { pos = pos2; } } } } return expanded; } deepin-terminal-5.2.11/3rdparty/terminalwidget/lib/ShellCommand.h000066400000000000000000000053651370157770500247560ustar00rootroot00000000000000/* Copyright (C) 2007 by Robert Knight Rewritten for QT4 by e_k , Copyright (C)2008 This program is free software; you can redistribute it and/or modify it under the terms of the 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 SHELLCOMMAND_H #define SHELLCOMMAND_H // Qt #include namespace Konsole { /** * A class to parse and extract information about shell commands. * * ShellCommand can be used to: * *
    *
  • Take a command-line (eg "/bin/sh -c /path/to/my/script") and split it * into its component parts (eg. the command "/bin/sh" and the arguments * "-c","/path/to/my/script") *
  • *
  • Take a command and a list of arguments and combine them to * form a complete command line. *
  • *
  • Determine whether the binary specified by a command exists in the * user's PATH. *
  • *
  • Determine whether a command-line specifies the execution of * another command as the root user using su/sudo etc. *
  • *
*/ class ShellCommand { public: /** * Constructs a ShellCommand from a command line. * * @param fullCommand The command line to parse. */ ShellCommand(const QString & fullCommand); /** * Constructs a ShellCommand with the specified @p command and @p arguments. */ ShellCommand(const QString & command , const QStringList & arguments); /** Returns the command. */ QString command() const; /** Returns the arguments. */ QStringList arguments() const; /** * Returns the full command line. */ QString fullCommand() const; /** Returns true if this is a root command. */ bool isRootCommand() const; /** Returns true if the program specified by @p command() exists. */ bool isAvailable() const; /** Expands environment variables in @p text .*/ static QString expand(const QString & text); /** Expands environment variables in each string in @p list. */ static QStringList expand(const QStringList & items); private: QStringList _arguments; }; } #endif // SHELLCOMMAND_H deepin-terminal-5.2.11/3rdparty/terminalwidget/lib/TerminalCharacterDecoder.cpp000066400000000000000000000152421370157770500276140ustar00rootroot00000000000000/* 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. */ // Own #include "TerminalCharacterDecoder.h" // std #include // Qt #include // KDE //#include // Konsole #include "konsole_wcwidth.h" #include using namespace Konsole; PlainTextDecoder::PlainTextDecoder() : _output(nullptr) , _includeTrailingWhitespace(true) , _recordLinePositions(false) { } void PlainTextDecoder::setTrailingWhitespace(bool enable) { _includeTrailingWhitespace = enable; } bool PlainTextDecoder::trailingWhitespace() const { return _includeTrailingWhitespace; } void PlainTextDecoder::begin(QTextStream* output) { _output = output; if (!_linePositions.isEmpty()) _linePositions.clear(); } void PlainTextDecoder::end() { _output = nullptr; } void PlainTextDecoder::setRecordLinePositions(bool record) { _recordLinePositions = record; } QList PlainTextDecoder::linePositions() const { return _linePositions; } void PlainTextDecoder::decodeLine(const Character* const characters, int count, LineProperty /*properties*/ ) { Q_ASSERT( _output ); if (_recordLinePositions && _output->string()) { int pos = _output->string()->count(); _linePositions << pos; } //TODO should we ignore or respect the LINE_WRAPPED line property? //note: we build up a QString and send it to the text stream rather writing into the text //stream a character at a time because it is more efficient. //(since QTextStream always deals with QStrings internally anyway) std::wstring plainText; plainText.reserve(count); int outputCount = count; // if inclusion of trailing whitespace is disabled then find the end of the // line if ( !_includeTrailingWhitespace ) { for (int i = count-1 ; i >= 0 ; i--) { if ( characters[i].character != L' ' ) break; else outputCount--; } } for (int i=0;i') text.append(L">"); else text.push_back(ch); } else { text.append(L" "); //HTML truncates multiple spaces, so use a space marker instead } } //close any remaining open inner spans if ( _innerSpanOpen ) closeSpan(text); //start new line text.append(L"
"); *_output << QString::fromStdWString(text); } void HTMLDecoder::openSpan(std::wstring& text , const QString& style) { text.append( QString(QLatin1String("")).arg(style).toStdWString() ); } void HTMLDecoder::closeSpan(std::wstring& text) { text.append(L""); } void HTMLDecoder::setColorTable(const ColorEntry* table) { _colorTable = table; } deepin-terminal-5.2.11/3rdparty/terminalwidget/lib/TerminalCharacterDecoder.h000066400000000000000000000107371370157770500272650ustar00rootroot00000000000000/* 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 #include "Character.h" #include 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 colours and other appearance-related properties into text strings. * * Derived classes may produce either plain text with no other colour or appearance information, or * they may produce text which incorporates these additional properties. */ class 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 colours and other appearance-related * properties of the original characters. */ class PlainTextDecoder : public TerminalCharacterDecoder { public: PlainTextDecoder(); /** * Set whether trailing whitespace at the end of lines should be included * in the output. * Defaults to true. */ void setTrailingWhitespace(bool enable); /** * Returns whether trailing whitespace at the end of lines is included * in the output. */ bool trailingWhitespace() const; /** * 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) override; void end() override; void decodeLine(const Character* const characters, int count, LineProperty properties) override; private: QTextStream* _output; bool _includeTrailingWhitespace; bool _recordLinePositions; QList _linePositions; }; /** * A terminal character decoder which produces pretty HTML markup */ class HTMLDecoder : public TerminalCharacterDecoder { public: /** * Constructs an HTML decoder using a default black-on-white color scheme. */ HTMLDecoder(); /** * Sets the colour table which the decoder uses to produce the HTML colour codes in its * output */ void setColorTable( const ColorEntry* table ); void decodeLine(const Character* const characters, int count, LineProperty properties) override; void begin(QTextStream* output) override; void end() override; private: void openSpan(std::wstring& text , const QString& style); void closeSpan(std::wstring& text); QTextStream* _output; const ColorEntry* _colorTable; bool _innerSpanOpen; quint8 _lastRendition; CharacterColor _lastForeColor; CharacterColor _lastBackColor; }; } #endif deepin-terminal-5.2.11/3rdparty/terminalwidget/lib/TerminalDisplay.cpp000066400000000000000000003322231370157770500260400ustar00rootroot00000000000000/* This file is part of Konsole, a terminal emulator for KDE. Copyright 2006-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. */ // Own #include "TerminalDisplay.h" #include "SessionManager.h" // Qt #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include // KDE //#include //#include //#include //#include //#include //#include //#include //#include //#include //#include // Konsole //#include #include "Filter.h" #include "konsole_wcwidth.h" #include "ScreenWindow.h" #include "TerminalCharacterDecoder.h" using namespace Konsole; #ifndef loc #define loc(X,Y) ((Y)*_columns+(X)) #endif #define yMouseScroll 1 #define REPCHAR "ABCDEFGHIJKLMNOPQRSTUVWXYZ" \ "abcdefgjijklmnopqrstuvwxyz" \ "0123456789./+@" const ColorEntry Konsole::base_color_table[TABLE_COLORS] = // The following are almost IBM standard color codes, with some slight // gamma correction for the dim colors to compensate for bright X screens. // It contains the 8 ansiterm/xterm colors in 2 intensities. { // Fixme: could add faint colors here, also. // normal ColorEntry(QColor(0x00,0x00,0x00), false), ColorEntry( QColor(0xB2,0xB2,0xB2), true), // Dfore, Dback ColorEntry(QColor(0x00,0x00,0x00), false), ColorEntry( QColor(0xB2,0x18,0x18), false), // Black, Red ColorEntry(QColor(0x18,0xB2,0x18), false), ColorEntry( QColor(0xB2,0x68,0x18), false), // Green, Yellow ColorEntry(QColor(0x18,0x18,0xB2), false), ColorEntry( QColor(0xB2,0x18,0xB2), false), // Blue, Magenta ColorEntry(QColor(0x18,0xB2,0xB2), false), ColorEntry( QColor(0xB2,0xB2,0xB2), false), // Cyan, White // intensiv ColorEntry(QColor(0x00,0x00,0x00), false), ColorEntry( QColor(0xFF,0xFF,0xFF), true), ColorEntry(QColor(0x68,0x68,0x68), false), ColorEntry( QColor(0xFF,0x54,0x54), false), ColorEntry(QColor(0x54,0xFF,0x54), false), ColorEntry( QColor(0xFF,0xFF,0x54), false), ColorEntry(QColor(0x54,0x54,0xFF), false), ColorEntry( QColor(0xFF,0x54,0xFF), false), ColorEntry(QColor(0x54,0xFF,0xFF), false), ColorEntry( QColor(0xFF,0xFF,0xFF), false) }; // scroll increment used when dragging selection at top/bottom of window. // static bool TerminalDisplay::_antialiasText = true; bool TerminalDisplay::HAVE_TRANSPARENCY = true; // we use this to force QPainter to display text in LTR mode // more information can be found in: http://unicode.org/reports/tr9/ const QChar LTR_OVERRIDE_CHAR( 0x202D ); /* ------------------------------------------------------------------------- */ /* */ /* Colors */ /* */ /* ------------------------------------------------------------------------- */ /* Note that we use ANSI color order (bgr), while IBMPC color order is (rgb) Code 0 1 2 3 4 5 6 7 ----------- ------- ------- ------- ------- ------- ------- ------- ------- ANSI (bgr) Black Red Green Yellow Blue Magenta Cyan White IBMPC (rgb) Black Blue Green Cyan Red Magenta Yellow White */ ScreenWindow* TerminalDisplay::screenWindow() const { return _screenWindow; } void TerminalDisplay::setScreenWindow(ScreenWindow* window) { // disconnect existing screen window if any if ( _screenWindow ) { disconnect( _screenWindow , nullptr , this , nullptr ); } _screenWindow = window; if ( window ) { // TODO: Determine if this is an issue. //#warning "The order here is not specified - does it matter whether updateImage or updateLineProperties comes first?" connect( _screenWindow , SIGNAL(outputChanged()) , this , SLOT(updateLineProperties()) ); connect( _screenWindow , SIGNAL(outputChanged()) , this , SLOT(updateImage()) ); connect( _screenWindow , SIGNAL(outputChanged()) , this , SLOT(updateFilters()) ); connect( _screenWindow , SIGNAL(scrolled(int)) , this , SLOT(updateFilters()) ); window->setWindowLines(_lines); } } const ColorEntry* TerminalDisplay::colorTable() const { return _colorTable; } void TerminalDisplay::setBackgroundColor(const QColor& color) { _colorTable[DEFAULT_BACK_COLOR].color = color; QPalette p = palette(); p.setColor( backgroundRole(), color ); setPalette( p ); // Avoid propagating the palette change to the scroll bar _scrollBar->setPalette( QApplication::palette() ); update(); } void TerminalDisplay::setForegroundColor(const QColor& color) { _colorTable[DEFAULT_FORE_COLOR].color = color; update(); } void TerminalDisplay::setColorTable(const ColorEntry table[]) { for (int i = 0; i < TABLE_COLORS; i++) _colorTable[i] = table[i]; setBackgroundColor(_colorTable[DEFAULT_BACK_COLOR].color); } /* ------------------------------------------------------------------------- */ /* */ /* Font */ /* */ /* ------------------------------------------------------------------------- */ /* The VT100 has 32 special graphical characters. The usual vt100 extended xterm fonts have these at 0x00..0x1f. QT's iso mapping leaves 0x00..0x7f without any changes. But the graphicals come in here as proper unicode characters. We treat non-iso10646 fonts as VT100 extended and do the requiered mapping from unicode to 0x00..0x1f. The remaining translation is then left to the QCodec. */ bool TerminalDisplay::isLineChar(wchar_t c) const { return _drawLineChars && ((c & 0xFF80) == 0x2500); } bool TerminalDisplay::isLineCharString(const std::wstring& string) const { return (string.length() > 0) && (isLineChar(string[0])); } // assert for i in [0..31] : vt100extended(vt100_graphics[i]) == i. unsigned short Konsole::vt100_graphics[32] = { // 0/8 1/9 2/10 3/11 4/12 5/13 6/14 7/15 0x0020, 0x25C6, 0x2592, 0x2409, 0x240c, 0x240d, 0x240a, 0x00b0, 0x00b1, 0x2424, 0x240b, 0x2518, 0x2510, 0x250c, 0x2514, 0x253c, 0xF800, 0xF801, 0x2500, 0xF803, 0xF804, 0x251c, 0x2524, 0x2534, 0x252c, 0x2502, 0x2264, 0x2265, 0x03C0, 0x2260, 0x00A3, 0x00b7 }; void TerminalDisplay::fontChange(const QFont&) { QFontMetrics fm(font()); /******** Modify by ut001000 renfeixiang 2020-06-24:修改字体高度的获取方法,由QFontMetrics的height获取,改成_fontWidth + font().pointSize() bug#34902 Begin***************/ //_fontHeight = fm.height() + _lineSpacing; //条幅黑体字体使用QFontMetrics的height获取字体高度是统一的1值,显示字体失败,现在忽略字体原有高度 // waba TerminalDisplay 1.123: // "Base character width on widest ASCII character. This prevents too wide // characters in the presence of double wide (e.g. Japanese) characters." // Get the width from representative normal width characters _fontWidth = qRound((double)fm.width(QLatin1String(REPCHAR))/(double)qstrlen(REPCHAR)); //修改方法:修改字体高度的获取方法,修改成字体宽度+字体的大小:_fontWidth + font().pointSize() _fontHeight = _fontWidth + font().pointSize() + _lineSpacing; /******** Modify by ut001000 renfeixiang 2020-06-24: bug#34902 End***************/ _fixedFont = true; int fw = fm.width(QLatin1Char(REPCHAR[0])); for(unsigned int i=1; i< qstrlen(REPCHAR); i++) { if (fw != fm.width(QLatin1Char(REPCHAR[i]))) { _fixedFont = false; break; } } if (_fontWidth < 1) _fontWidth=1; _fontAscent = fm.ascent(); emit changedFontMetricSignal( _fontHeight, _fontWidth ); propagateSize(); // We will run paint event testing procedure. // Although this operation will destory the orignal content, // the content will be drawn again after the test. //_drawTextTestFlag = true;// //----------add by nyq to slove the twinkle of the window-- _drawTextTestFlag = false; //--------------------------------------------------------- update(); } void TerminalDisplay::calDrawTextAdditionHeight(QPainter& painter) { QRect test_rect, feedback_rect; test_rect.setRect(1, 1, _fontWidth * 4, _fontHeight); painter.drawText(test_rect, Qt::AlignBottom, LTR_OVERRIDE_CHAR + QLatin1String("Mq"), &feedback_rect); //qDebug() << "test_rect:" << test_rect << "feeback_rect:" << feedback_rect; _drawTextAdditionHeight = (feedback_rect.height() - _fontHeight) / 2; if(_drawTextAdditionHeight < 0) { _drawTextAdditionHeight = 0; } // update the original content _drawTextTestFlag = false; update(); } void TerminalDisplay::setVTFont(const QFont& f) { QFont font = f; // This was originally set for OS X only: // mac uses floats for font width specification. // this ensures the same handling for all platforms // but then there was revealed that various Linux distros // have this problem too... font.setStyleStrategy(QFont::ForceIntegerMetrics); QFontMetrics metrics(font); if ( !QFontInfo(font).fixedPitch() ) { qDebug() << "Using a variable-width font in the terminal. This may cause performance degradation and display/alignment errors."; } // hint that text should be drawn without anti-aliasing. // depending on the user's font configuration, this may not be respected if (!_antialiasText) font.setStyleStrategy( QFont::NoAntialias ); // experimental optimization. Konsole assumes that the terminal is using a // mono-spaced font, in which case kerning information should have an effect. // Disabling kerning saves some computation when rendering text. font.setKerning(false); QWidget::setFont(font); fontChange(font); } void TerminalDisplay::setFont(const QFont &) { // ignore font change request if not coming from konsole itself } /* ------------------------------------------------------------------------- */ /* */ /* Constructor / Destructor */ /* */ /* ------------------------------------------------------------------------- */ TerminalDisplay::TerminalDisplay(QWidget *parent) :QWidget(parent) ,_screenWindow(nullptr) ,_allowBell(true) ,_gridLayout(nullptr) ,_fontHeight(1) ,_fontWidth(1) ,_fontAscent(1) ,_boldIntense(true) ,_lines(1) ,_columns(1) ,_usedLines(1) ,_usedColumns(1) ,_contentHeight(1) ,_contentWidth(1) ,_image(nullptr) ,_randomSeed(0) ,_resizing(false) ,_terminalSizeHint(false) ,_terminalSizeStartup(true) ,_bidiEnabled(false) ,_mouseMarks(false) ,_actSel(0) ,_wordSelectionMode(false) ,_lineSelectionMode(false) ,_preserveLineBreaks(false) ,_columnSelectionMode(false) ,_scrollbarLocation(QTermWidget::NoScrollBar) ,_wordCharacters(QLatin1String(":@-./_~")) ,_bellMode(SystemBeepBell) ,_blinking(false) ,_hasBlinker(false) ,_cursorBlinking(false) ,_hasBlinkingCursor(false) ,_allowBlinkingText(true) ,_ctrlDrag(false) ,_tripleClickMode(SelectWholeLine) ,_isFixedSize(false) ,_possibleTripleClick(false) ,_resizeWidget(nullptr) ,_resizeTimer(nullptr) ,_flowControlWarningEnabled(false) ,_hideCursor(false) ,_outputSuspendedLabel(nullptr) ,_lineSpacing(0) ,_colorsInverted(false) ,_blendColor(qRgba(0,0,0,0xff)) ,_filterChain(new TerminalImageFilterChain()) ,_cursorShape(Emulation::KeyboardCursorShape::BlockCursor) ,mMotionAfterPasting(NoMoveScreenWindow) ,_leftBaseMargin(1) ,_topBaseMargin(1) ,_drawLineChars(true) ,_headerBar(new TerminalHeaderBar(this)) { // variables for draw text _drawTextAdditionHeight = 0; _drawTextTestFlag = false; // terminal applications are not designed with Right-To-Left in mind, // so the layout is forced to Left-To-Right setLayoutDirection(Qt::LeftToRight); // The offsets are not yet calculated. // Do not calculate these too often to be more smoothly when resizing // konsole in opaque mode. _topMargin = _topBaseMargin; _leftMargin = _leftBaseMargin; // create scroll bar for scrolling output up and down // set the scroll bar's slider to occupy the whole area of the scroll bar initially _scrollBar = new QScrollBar(this); /******** Modify by ut000439 wangpeili 2020-06-24: 适应窗口特效圆角 ****************/ //qDebug()<<"_scrollBar->width()"<<_scrollBar->width(); // 设置15px宽度=6? _scrollBar->setStyleSheet("margin: 0px 0 15px 0;width: 15"); //qDebug()<<"_scrollBar->width()"<<_scrollBar->width(); /********************* Modify by n014361 wangpeili End ************************/ // since the contrast with the terminal background may not be enough, // the scrollbar should be auto-filled if not transient if (!_scrollBar->style()->styleHint(QStyle::SH_ScrollBar_Transient, nullptr, _scrollBar)) _scrollBar->setAutoFillBackground(true); setScroll(0,0); _scrollBar->setCursor( Qt::ArrowCursor ); connect(_scrollBar, SIGNAL(valueChanged(int)), this, SLOT(scrollBarPositionChanged(int))); // qtermwidget: we have to hide it here due the _scrollbarLocation==NoScrollBar // check in TerminalDisplay::setScrollBarPosition(ScrollBarPosition position) _scrollBar->hide(); // setup timers for blinking cursor and text _blinkTimer = new QTimer(this); connect(_blinkTimer, SIGNAL(timeout()), this, SLOT(blinkEvent())); _blinkCursorTimer = new QTimer(this); connect(_blinkCursorTimer, SIGNAL(timeout()), this, SLOT(blinkCursorEvent())); // KCursor::setAutoHideCursor( this, true ); setUsesMouse(true); setBracketedPasteMode(false); setColorTable(base_color_table); setMouseTracking(true); // Enable drag and drop setAcceptDrops(true); // attempt dragInfo.state = diNone; setFocusPolicy( Qt::WheelFocus ); // enable input method support setAttribute(Qt::WA_InputMethodEnabled, true); // this is an important optimization, it tells Qt // that TerminalDisplay will handle repainting its entire area. setAttribute(Qt::WA_OpaquePaintEvent); _gridLayout = new QGridLayout(this); _gridLayout->setContentsMargins(0, 0, 0, 0); _gridLayout->addWidget(_headerBar); setLayout( _gridLayout ); new AutoScrollHandler(this); m_bUserIsResizing = false; } TerminalDisplay::~TerminalDisplay() { disconnect(_blinkTimer); disconnect(_blinkCursorTimer); qApp->removeEventFilter( this ); delete[] _image; delete _gridLayout; delete _outputSuspendedLabel; delete _filterChain; } /* ------------------------------------------------------------------------- */ /* */ /* Display Operations */ /* */ /* ------------------------------------------------------------------------- */ /** A table for emulating the simple (single width) unicode drawing chars. It represents the 250x - 257x glyphs. If it's zero, we can't use it. if it's not, it's encoded as follows: imagine a 5x5 grid where the points are numbered 0 to 24 left to top, top to bottom. Each point is represented by the corresponding bit. Then, the pixels basically have the following interpretation: _|||_ -...- -...- -...- _|||_ where _ = none | = vertical line. - = horizontal line. */ enum LineEncode { TopL = (1<<1), TopC = (1<<2), TopR = (1<<3), LeftT = (1<<5), Int11 = (1<<6), Int12 = (1<<7), Int13 = (1<<8), RightT = (1<<9), LeftC = (1<<10), Int21 = (1<<11), Int22 = (1<<12), Int23 = (1<<13), RightC = (1<<14), LeftB = (1<<15), Int31 = (1<<16), Int32 = (1<<17), Int33 = (1<<18), RightB = (1<<19), BotL = (1<<21), BotC = (1<<22), BotR = (1<<23) }; #include "LineFont.h" static void drawLineChar(QPainter& paint, int x, int y, int w, int h, uint8_t code) { //Calculate cell midpoints, end points. int cx = x + w/2; int cy = y + h/2; int ex = x + w - 1; int ey = y + h - 1; quint32 toDraw = LineChars[code]; //Top _lines: if (toDraw & TopL) paint.drawLine(cx-1, y, cx-1, cy-2); if (toDraw & TopC) paint.drawLine(cx, y, cx, cy-2); if (toDraw & TopR) paint.drawLine(cx+1, y, cx+1, cy-2); //Bot _lines: if (toDraw & BotL) paint.drawLine(cx-1, cy+2, cx-1, ey); if (toDraw & BotC) paint.drawLine(cx, cy+2, cx, ey); if (toDraw & BotR) paint.drawLine(cx+1, cy+2, cx+1, ey); //Left _lines: if (toDraw & LeftT) paint.drawLine(x, cy-1, cx-2, cy-1); if (toDraw & LeftC) paint.drawLine(x, cy, cx-2, cy); if (toDraw & LeftB) paint.drawLine(x, cy+1, cx-2, cy+1); //Right _lines: if (toDraw & RightT) paint.drawLine(cx+2, cy-1, ex, cy-1); if (toDraw & RightC) paint.drawLine(cx+2, cy, ex, cy); if (toDraw & RightB) paint.drawLine(cx+2, cy+1, ex, cy+1); //Intersection points. if (toDraw & Int11) paint.drawPoint(cx-1, cy-1); if (toDraw & Int12) paint.drawPoint(cx, cy-1); if (toDraw & Int13) paint.drawPoint(cx+1, cy-1); if (toDraw & Int21) paint.drawPoint(cx-1, cy); if (toDraw & Int22) paint.drawPoint(cx, cy); if (toDraw & Int23) paint.drawPoint(cx+1, cy); if (toDraw & Int31) paint.drawPoint(cx-1, cy+1); if (toDraw & Int32) paint.drawPoint(cx, cy+1); if (toDraw & Int33) paint.drawPoint(cx+1, cy+1); } static void drawOtherChar(QPainter& paint, int x, int y, int w, int h, uchar code) { //Calculate cell midpoints, end points. const int cx = x + w / 2; const int cy = y + h / 2; const int ex = x + w - 1; const int ey = y + h - 1; // Double dashes if (0x4C <= code && code <= 0x4F) { const int xHalfGap = qMax(w / 15, 1); const int yHalfGap = qMax(h / 15, 1); switch (code) { case 0x4D: // BOX DRAWINGS HEAVY DOUBLE DASH HORIZONTAL paint.drawLine(x, cy - 1, cx - xHalfGap - 1, cy - 1); paint.drawLine(x, cy + 1, cx - xHalfGap - 1, cy + 1); paint.drawLine(cx + xHalfGap, cy - 1, ex, cy - 1); paint.drawLine(cx + xHalfGap, cy + 1, ex, cy + 1); /* Falls through. */ case 0x4C: // BOX DRAWINGS LIGHT DOUBLE DASH HORIZONTAL paint.drawLine(x, cy, cx - xHalfGap - 1, cy); paint.drawLine(cx + xHalfGap, cy, ex, cy); break; case 0x4F: // BOX DRAWINGS HEAVY DOUBLE DASH VERTICAL paint.drawLine(cx - 1, y, cx - 1, cy - yHalfGap - 1); paint.drawLine(cx + 1, y, cx + 1, cy - yHalfGap - 1); paint.drawLine(cx - 1, cy + yHalfGap, cx - 1, ey); paint.drawLine(cx + 1, cy + yHalfGap, cx + 1, ey); /* Falls through. */ case 0x4E: // BOX DRAWINGS LIGHT DOUBLE DASH VERTICAL paint.drawLine(cx, y, cx, cy - yHalfGap - 1); paint.drawLine(cx, cy + yHalfGap, cx, ey); break; } } // Rounded corner characters else if (0x6D <= code && code <= 0x70) { const int r = w * 3 / 8; const int d = 2 * r; switch (code) { case 0x6D: // BOX DRAWINGS LIGHT ARC DOWN AND RIGHT paint.drawLine(cx, cy + r, cx, ey); paint.drawLine(cx + r, cy, ex, cy); paint.drawArc(cx, cy, d, d, 90 * 16, 90 * 16); break; case 0x6E: // BOX DRAWINGS LIGHT ARC DOWN AND LEFT paint.drawLine(cx, cy + r, cx, ey); paint.drawLine(x, cy, cx - r, cy); paint.drawArc(cx - d, cy, d, d, 0 * 16, 90 * 16); break; case 0x6F: // BOX DRAWINGS LIGHT ARC UP AND LEFT paint.drawLine(cx, y, cx, cy - r); paint.drawLine(x, cy, cx - r, cy); paint.drawArc(cx - d, cy - d, d, d, 270 * 16, 90 * 16); break; case 0x70: // BOX DRAWINGS LIGHT ARC UP AND RIGHT paint.drawLine(cx, y, cx, cy - r); paint.drawLine(cx + r, cy, ex, cy); paint.drawArc(cx, cy - d, d, d, 180 * 16, 90 * 16); break; } } // Diagonals else if (0x71 <= code && code <= 0x73) { switch (code) { case 0x71: // BOX DRAWINGS LIGHT DIAGONAL UPPER RIGHT TO LOWER LEFT paint.drawLine(ex, y, x, ey); break; case 0x72: // BOX DRAWINGS LIGHT DIAGONAL UPPER LEFT TO LOWER RIGHT paint.drawLine(x, y, ex, ey); break; case 0x73: // BOX DRAWINGS LIGHT DIAGONAL CROSS paint.drawLine(ex, y, x, ey); paint.drawLine(x, y, ex, ey); break; } } } void TerminalDisplay::drawLineCharString( QPainter& painter, int x, int y, const std::wstring& str, const Character* attributes) { const QPen& currentPen = painter.pen(); if ( (attributes->rendition & RE_BOLD) && _boldIntense ) { QPen boldPen(currentPen); boldPen.setWidth(3); painter.setPen( boldPen ); } for (size_t i=0 ; i < str.length(); i++) { uint8_t code = static_cast(str[i] & 0xffU); if (LineChars[code]) drawLineChar(painter, x + (_fontWidth*i), y, _fontWidth, _fontHeight, code); else drawOtherChar(painter, x + (_fontWidth * i), y, _fontWidth, _fontHeight, code); } painter.setPen( currentPen ); } void TerminalDisplay::setKeyboardCursorShape(QTermWidget::KeyboardCursorShape shape) { _cursorShape = shape; updateCursor(); } QTermWidget::KeyboardCursorShape TerminalDisplay::keyboardCursorShape() const { return _cursorShape; } void TerminalDisplay::setKeyboardCursorColor(bool useForegroundColor, const QColor& color) { if (useForegroundColor) _cursorColor = QColor(); // an invalid color means that // the foreground color of the // current character should // be used else _cursorColor = color; } QColor TerminalDisplay::keyboardCursorColor() const { return _cursorColor; } void TerminalDisplay::setOpacity(qreal opacity) { QColor color(_blendColor); color.setAlphaF(opacity); // enable automatic background filling to prevent the display // flickering if there is no transparency /*if ( color.alpha() == 255 ) { setAutoFillBackground(true); } else { setAutoFillBackground(false); }*/ _blendColor = color.rgba(); } void TerminalDisplay::setBackgroundImage(QString backgroundImage) { if (!backgroundImage.isEmpty()) { _backgroundImage.load(backgroundImage); setAttribute(Qt::WA_OpaquePaintEvent, false); } else { _backgroundImage = QPixmap(); setAttribute(Qt::WA_OpaquePaintEvent, true); } } void TerminalDisplay::drawBackground(QPainter& painter, const QRect& rect, const QColor& backgroundColor, bool useOpacitySetting ) { // The whole widget rectangle is filled by the background color from // the color scheme set in setColorTable(), while the scrollbar is // left to the widget style for a consistent look. if ( HAVE_TRANSPARENCY && qAlpha(_blendColor) < 0xff && useOpacitySetting ) { if (_backgroundImage.isNull()) { QColor color(backgroundColor); color.setAlpha(qAlpha(_blendColor)); painter.save(); painter.setCompositionMode(QPainter::CompositionMode_Source); painter.fillRect(rect, color); painter.restore(); } } else painter.fillRect(rect, backgroundColor); } void TerminalDisplay::drawCursor(QPainter& painter, const QRect& rect, const QColor& foregroundColor, const QColor& /*backgroundColor*/, bool& invertCharacterColor) { QRectF cursorRect = rect; cursorRect.setHeight(_fontHeight - _lineSpacing - 1); if (!_cursorBlinking) { if ( _cursorColor.isValid() ) painter.setPen(_cursorColor); else painter.setPen(foregroundColor); if ( _cursorShape == Emulation::KeyboardCursorShape::BlockCursor ) { if ( hasFocus() ) { painter.fillRect(cursorRect, _cursorColor.isValid() ? _cursorColor : foregroundColor); if ( !_cursorColor.isValid() ) { // invert the colour used to draw the text to ensure that the character at // the cursor position is readable invertCharacterColor = true; } } else { // draw the cursor outline, adjusting the area so that // it is draw entirely inside 'rect' int penWidth = 1; painter.drawRect(cursorRect.adjusted(penWidth/2, penWidth/2, - penWidth/2 - penWidth%2, - penWidth/2 - penWidth%2)); } } else if ( _cursorShape == Emulation::KeyboardCursorShape::UnderlineCursor ) painter.drawLine(cursorRect.left(), cursorRect.bottom(), cursorRect.right(), cursorRect.bottom()); else if ( _cursorShape == Emulation::KeyboardCursorShape::IBeamCursor ) painter.drawLine(cursorRect.left(), cursorRect.top(), cursorRect.left(), cursorRect.bottom()); } } void TerminalDisplay::drawCharacters(QPainter& painter, const QRect& rect, const std::wstring& text, const Character* style, bool invertCharacterColor) { // don't draw text which is currently blinking if ( _blinking && (style->rendition & RE_BLINK) ) return; // don't draw concealed characters if (style->rendition & RE_CONCEAL) return; // setup bold and underline bool useBold = ((style->rendition & RE_BOLD) && _boldIntense) || font().bold(); const bool useUnderline = style->rendition & RE_UNDERLINE || font().underline(); const bool useItalic = style->rendition & RE_ITALIC || font().italic(); const bool useStrikeOut = style->rendition & RE_STRIKEOUT || font().strikeOut(); const bool useOverline = style->rendition & RE_OVERLINE || font().overline(); QFont font = painter.font(); if ( font.bold() != useBold || font.underline() != useUnderline || font.italic() != useItalic || font.strikeOut() != useStrikeOut || font.overline() != useOverline) { font.setBold(useBold); font.setUnderline(useUnderline); font.setItalic(useItalic); font.setStrikeOut(useStrikeOut); font.setOverline(useOverline); painter.setFont(font); } // setup pen const CharacterColor& textColor = ( invertCharacterColor ? style->backgroundColor : style->foregroundColor ); const QColor color = textColor.color(_colorTable); QPen pen = painter.pen(); if ( pen.color() != color ) { pen.setColor(color); painter.setPen(color); } // draw text if ( isLineCharString(text) ) drawLineCharString(painter,rect.x(),rect.y(),text,style); else { // Force using LTR as the document layout for the terminal area, because // there is no use cases for RTL emulator and RTL terminal application. // // This still allows RTL characters to be rendered in the RTL way. painter.setLayoutDirection(Qt::LeftToRight); if (_bidiEnabled) { painter.drawText(rect.x(), rect.y() + _fontAscent + _lineSpacing, QString::fromStdWString(text)); } else { { QRect drawRect(rect.topLeft(), rect.size()); drawRect.setHeight(rect.height() + _drawTextAdditionHeight); painter.drawText(drawRect, Qt::AlignBottom, LTR_OVERRIDE_CHAR + QString::fromStdWString(text)); } } } } void TerminalDisplay::drawTextFragment(QPainter& painter , const QRect& rect, const std::wstring& text, const Character* style) { painter.save(); // setup painter //const QColor foregroundColor = style->foregroundColor.color(_colorTable); const QColor backgroundColor = style->backgroundColor.color(_colorTable); // draw background if different from the display's background color if ( backgroundColor != palette().background().color() ) drawBackground(painter,rect,backgroundColor, false /* do not use transparency */); // draw cursor shape if the current character is the cursor // this may alter the foreground and background colors bool invertCharacterColor = false; if (!_hideCursor) { if ( style->rendition & RE_CURSOR ) { const QColor cursorBackground = _colorTable[DEFAULT_BACK_COLOR].color; const QColor cursorForeground = _colorTable[DEFAULT_FORE_COLOR].color; drawCursor(painter,rect,cursorForeground,cursorBackground,invertCharacterColor); } } // draw text drawCharacters(painter,rect,text,style,invertCharacterColor); painter.restore(); } void TerminalDisplay::setRandomSeed(uint randomSeed) { _randomSeed = randomSeed; } uint TerminalDisplay::randomSeed() const { return _randomSeed; } #if 0 /*! Set XIM Position */ void TerminalDisplay::setCursorPos(const int curx, const int cury) { QPoint tL = contentsRect().topLeft(); int tLx = tL.x(); int tLy = tL.y(); int xpos, ypos; ypos = _topMargin + tLy + _fontHeight*(cury-1) + _fontAscent; xpos = _leftMargin + tLx + _fontWidth*curx; //setMicroFocusHint(xpos, ypos, 0, _fontHeight); //### ??? // fprintf(stderr, "x/y = %d/%d\txpos/ypos = %d/%d\n", curx, cury, xpos, ypos); _cursorLine = cury; _cursorCol = curx; } #endif // scrolls the image by 'lines', down if lines > 0 or up otherwise. // // the terminal emulation keeps track of the scrolling of the character // image as it receives input, and when the view is updated, it calls scrollImage() // with the final scroll amount. this improves performance because scrolling the // display is much cheaper than re-rendering all the text for the // part of the image which has moved up or down. // Instead only new lines have to be drawn void TerminalDisplay::scrollImage(int lines , const QRect& screenWindowRegion) { // if the flow control warning is enabled this will interfere with the // scrolling optimizations and cause artifacts. the simple solution here // is to just disable the optimization whilst it is visible if ( _outputSuspendedLabel && _outputSuspendedLabel->isVisible() ) return; // constrain the region to the display // the bottom of the region is capped to the number of lines in the display's // internal image - 2, so that the height of 'region' is strictly less // than the height of the internal image. QRect region = screenWindowRegion; region.setBottom( qMin(region.bottom(),this->_lines-2) ); // return if there is nothing to do if ( lines == 0 || _image == nullptr || !region.isValid() || (region.top() + abs(lines)) >= region.bottom() || this->_lines <= region.height() ) return; // hide terminal size label to prevent it being scrolled if (_resizeWidget && _resizeWidget->isVisible()) _resizeWidget->hide(); // Note: With Qt 4.4 the left edge of the scrolled area must be at 0 // to get the correct (newly exposed) part of the widget repainted. // // The right edge must be before the left edge of the scroll bar to // avoid triggering a repaint of the entire widget, the distance is // given by SCROLLBAR_CONTENT_GAP // // Set the QT_FLUSH_PAINT environment variable to '1' before starting the // application to monitor repainting. // int scrollBarWidth = _scrollBar->isHidden() ? 0 : _scrollBar->style()->styleHint(QStyle::SH_ScrollBar_Transient, nullptr, _scrollBar) ? 0 : _scrollBar->width(); const int SCROLLBAR_CONTENT_GAP = scrollBarWidth == 0 ? 0 : 1; QRect scrollRect; if ( _scrollbarLocation == QTermWidget::ScrollBarLeft ) { scrollRect.setLeft(scrollBarWidth+SCROLLBAR_CONTENT_GAP); scrollRect.setRight(width()); } else { scrollRect.setLeft(0); scrollRect.setRight(width() - scrollBarWidth - SCROLLBAR_CONTENT_GAP); } void* firstCharPos = &_image[ region.top() * this->_columns ]; void* lastCharPos = &_image[ (region.top() + abs(lines)) * this->_columns ]; int top = _topMargin + (region.top() * _fontHeight); int linesToMove = region.height() - abs(lines); int bytesToMove = linesToMove * this->_columns * sizeof(Character); Q_ASSERT( linesToMove > 0 ); Q_ASSERT( bytesToMove > 0 ); //scroll internal image if ( lines > 0 ) { // check that the memory areas that we are going to move are valid Q_ASSERT( (char*)lastCharPos + bytesToMove < (char*)(_image + (this->_lines * this->_columns)) ); Q_ASSERT( (lines*this->_columns) < _imageSize ); //scroll internal image down memmove( firstCharPos , lastCharPos , bytesToMove ); //set region of display to scroll scrollRect.setTop(top); } else { // check that the memory areas that we are going to move are valid Q_ASSERT( (char*)firstCharPos + bytesToMove < (char*)(_image + (this->_lines * this->_columns)) ); //scroll internal image up memmove( lastCharPos , firstCharPos , bytesToMove ); //set region of the display to scroll scrollRect.setTop(top + abs(lines) * _fontHeight); } scrollRect.setHeight(linesToMove * _fontHeight ); Q_ASSERT(scrollRect.isValid() && !scrollRect.isEmpty()); //scroll the display vertically to match internal _image scroll( 0 , _fontHeight * (-lines) , scrollRect ); } QRegion TerminalDisplay::hotSpotRegion() const { QRegion region; const auto hotSpots = _filterChain->hotSpots(); for( Filter::HotSpot* const hotSpot : hotSpots ) { QRect r; if (hotSpot->startLine()==hotSpot->endLine()) { r.setLeft(hotSpot->startColumn()); r.setTop(hotSpot->startLine()); r.setRight(hotSpot->endColumn()); r.setBottom(hotSpot->endLine()); region |= imageToWidget(r);; } else { r.setLeft(hotSpot->startColumn()); r.setTop(hotSpot->startLine()); r.setRight(_columns); r.setBottom(hotSpot->startLine()); region |= imageToWidget(r);; for ( int line = hotSpot->startLine()+1 ; line < hotSpot->endLine() ; line++ ) { r.setLeft(0); r.setTop(line); r.setRight(_columns); r.setBottom(line); region |= imageToWidget(r);; } r.setLeft(0); r.setTop(hotSpot->endLine()); r.setRight(hotSpot->endColumn()); r.setBottom(hotSpot->endLine()); region |= imageToWidget(r);; } } return region; } void TerminalDisplay::processFilters() { if (!_screenWindow) return; QRegion preUpdateHotSpots = hotSpotRegion(); // use _screenWindow->getImage() here rather than _image because // other classes may call processFilters() when this display's // ScreenWindow emits a scrolled() signal - which will happen before // updateImage() is called on the display and therefore _image is // out of date at this point _filterChain->setImage( _screenWindow->getImage(), _screenWindow->windowLines(), _screenWindow->windowColumns(), _screenWindow->getLineProperties() ); _filterChain->process(); QRegion postUpdateHotSpots = hotSpotRegion(); update( preUpdateHotSpots | postUpdateHotSpots ); } void TerminalDisplay::updateImage() { if ( !_screenWindow ) return; // optimization - scroll the existing image where possible and // avoid expensive text drawing for parts of the image that // can simply be moved up or down scrollImage( _screenWindow->scrollCount() , _screenWindow->scrollRegion() ); _screenWindow->resetScrollCount(); if (!_image) { // Create _image. // The emitted changedContentSizeSignal also leads to getImage being recreated, so do this first. updateImageSize(); } Character* const newimg = _screenWindow->getImage(); int lines = _screenWindow->windowLines(); int columns = _screenWindow->windowColumns(); setScroll( _screenWindow->currentLine() , _screenWindow->lineCount() ); //--added by qinyaning(nyq) to slove the problem of scroll init show--/ setScrollBarPosition(_lines > 1 && _screenWindow->lineCount() > _lines? QTermWidget::ScrollBarRight : QTermWidget::NoScrollBar); //--------------------------------------------------------------------/ Q_ASSERT( this->_usedLines <= this->_lines ); Q_ASSERT( this->_usedColumns <= this->_columns ); int y,x,len; QPoint tL = contentsRect().topLeft(); int tLx = tL.x(); int tLy = tL.y(); _hasBlinker = false; CharacterColor cf; // undefined CharacterColor _clipboard; // undefined int cr = -1; // undefined const int linesToUpdate = qMin(this->_lines, qMax(0,lines )); const int columnsToUpdate = qMin(this->_columns,qMax(0,columns)); wchar_t *disstrU = new wchar_t[columnsToUpdate]; char *dirtyMask = new char[columnsToUpdate+2]; QRegion dirtyRegion; // debugging variable, this records the number of lines that are found to // be 'dirty' ( ie. have changed from the old _image to the new _image ) and // which therefore need to be repainted int dirtyLineCount = 0; for (y = 0; y < linesToUpdate; ++y) { const Character* currentLine = &_image[y*this->_columns]; const Character* const newLine = &newimg[y*columns]; bool updateLine = false; // The dirty mask indicates which characters need repainting. We also // mark surrounding neighbours dirty, in case the character exceeds // its cell boundaries memset(dirtyMask, 0, columnsToUpdate+2); for( x = 0 ; x < columnsToUpdate ; ++x) { if ( newLine[x] != currentLine[x] ) { dirtyMask[x] = true; } } if (!_resizing) // not while _resizing, we're expecting a paintEvent for (x = 0; x < columnsToUpdate; ++x) { _hasBlinker |= (newLine[x].rendition & RE_BLINK); // Start drawing if this character or the next one differs. // We also take the next one into account to handle the situation // where characters exceed their cell width. if (dirtyMask[x]) { wchar_t c = newLine[x+0].character; if ( !c ) continue; int p = 0; disstrU[p++] = c; //fontMap(c); bool lineDraw = isLineChar(c); bool doubleWidth = (x+1 == columnsToUpdate) ? false : (newLine[x+1].character == 0); cr = newLine[x].rendition; _clipboard = newLine[x].backgroundColor; if (newLine[x].foregroundColor != cf) cf = newLine[x].foregroundColor; int lln = columnsToUpdate - x; for (len = 1; len < lln; ++len) { const Character& ch = newLine[x+len]; if (!ch.character) continue; // Skip trailing part of multi-col chars. bool nextIsDoubleWidth = (x+len+1 == columnsToUpdate) ? false : (newLine[x+len+1].character == 0); if ( ch.foregroundColor != cf || ch.backgroundColor != _clipboard || ch.rendition != cr || !dirtyMask[x+len] || isLineChar(c) != lineDraw || nextIsDoubleWidth != doubleWidth ) break; disstrU[p++] = c; //fontMap(c); } std::wstring unistr(disstrU, p); bool saveFixedFont = _fixedFont; if (lineDraw) _fixedFont = false; if (doubleWidth) _fixedFont = false; updateLine = true; _fixedFont = saveFixedFont; x += len - 1; } } //both the top and bottom halves of double height _lines must always be redrawn //although both top and bottom halves contain the same characters, only //the top one is actually //drawn. if (_lineProperties.count() > y) updateLine |= (_lineProperties[y] & LINE_DOUBLEHEIGHT); // if the characters on the line are different in the old and the new _image // then this line must be repainted. if (updateLine) { dirtyLineCount++; // add the area occupied by this line to the region which needs to be // repainted QRect dirtyRect = QRect( _leftMargin+tLx , _topMargin+tLy+_fontHeight*y , _fontWidth * columnsToUpdate , _fontHeight ); dirtyRegion |= dirtyRect; } // replace the line of characters in the old _image with the // current line of the new _image memcpy((void*)currentLine,(const void*)newLine,columnsToUpdate*sizeof(Character)); } // if the new _image is smaller than the previous _image, then ensure that the area // outside the new _image is cleared if ( linesToUpdate < _usedLines ) { dirtyRegion |= QRect( _leftMargin+tLx , _topMargin+tLy+_fontHeight*linesToUpdate , _fontWidth * this->_columns , _fontHeight * (_usedLines-linesToUpdate) ); } _usedLines = linesToUpdate; if ( columnsToUpdate < _usedColumns ) { dirtyRegion |= QRect( _leftMargin+tLx+columnsToUpdate*_fontWidth , _topMargin+tLy , _fontWidth * (_usedColumns-columnsToUpdate) , _fontHeight * this->_lines ); } _usedColumns = columnsToUpdate; dirtyRegion |= _inputMethodData.previousPreeditRect; // update the parts of the display which have changed //--modified and added by qinyaning(nyq) to solve When the screen zooms to 1.25 and 2.75, /*the terminal interface will display colored lines. time: 2020.4.10 14:18 * */ //update(dirtyRegion); update(); //------------------------------------------------- if ( _hasBlinker && !_blinkTimer->isActive()) _blinkTimer->start( TEXT_BLINK_DELAY ); if (!_hasBlinker && _blinkTimer->isActive()) { _blinkTimer->stop(); _blinking = false; } delete[] dirtyMask; delete[] disstrU; } void TerminalDisplay::showResizeNotification() { if (_terminalSizeHint && isVisible()) { if (_terminalSizeStartup) { _terminalSizeStartup=false; return; } if (!_resizeWidget) { const QString label = tr("Size: XXX x XXX"); _resizeWidget = new QLabel(label, this); _resizeWidget->setMinimumWidth(_resizeWidget->fontMetrics().width(label)); _resizeWidget->setMinimumHeight(_resizeWidget->sizeHint().height()); _resizeWidget->setAlignment(Qt::AlignCenter); _resizeWidget->setStyleSheet(QLatin1String("background-color:palette(window);border-style:solid;border-width:1px;border-color:palette(dark)")); _resizeTimer = new QTimer(this); _resizeTimer->setSingleShot(true); connect(_resizeTimer, &QTimer::timeout, this, [this](){ //计时器timeout,终端控件结束调整大小 this->m_bUserIsResizing = false; SessionManager::instance()->setTerminalResizing(_sessionId, m_bUserIsResizing); }); } //显示resizeWidget的时候,标记当前session对应终端控件正在调整大小 SessionManager::instance()->setTerminalResizing(_sessionId, true); _resizeWidget->setText(tr("Size: %1 x %2").arg(_columns).arg(_lines)); _resizeWidget->move((width()-_resizeWidget->width())/2, (height()-_resizeWidget->height())/2+20); //fix bug 17684 在放大,正常窗口,最大化之间切换,终端窗口会显示size _resizeWidget->hide(); _resizeTimer->start(1000); } } void TerminalDisplay::setBlinkingCursor(bool blink) { _hasBlinkingCursor=blink; if (blink && !_blinkCursorTimer->isActive()) _blinkCursorTimer->start(QApplication::cursorFlashTime() / 2); if (!blink && _blinkCursorTimer->isActive()) { _blinkCursorTimer->stop(); if (_cursorBlinking) blinkCursorEvent(); else _cursorBlinking = false; } /******** Modify by n014361 wangpeili 2020-02-13: 修复“设置光标闪烁后,非焦点光标也在闪烁”***********×****/ if (hasFocus()) { focusInEvent(nullptr); } else { focusOutEvent(nullptr); } /***************** Modify by n014361 End *************************/ } void TerminalDisplay::setBlinkingTextEnabled(bool blink) { _allowBlinkingText = blink; if (blink && !_blinkTimer->isActive()) _blinkTimer->start(TEXT_BLINK_DELAY); if (!blink && _blinkTimer->isActive()) { _blinkTimer->stop(); _blinking = false; } } void TerminalDisplay::focusOutEvent(QFocusEvent*) { emit termLostFocus(); // trigger a repaint of the cursor so that it is both visible (in case // it was hidden during blinking) // and drawn in a focused out state _cursorBlinking = false; updateCursor(); _blinkCursorTimer->stop(); if (_blinking) blinkEvent(); _blinkTimer->stop(); } void TerminalDisplay::focusInEvent(QFocusEvent*) { //qDebug()<<"focusInEvent"; emit termGetFocus(); if (_hasBlinkingCursor) { _blinkCursorTimer->start(); } updateCursor(); if (_hasBlinker) _blinkTimer->start(); } void TerminalDisplay::paintEvent( QPaintEvent* pe ) { QPainter paint(this); if ( !_backgroundImage.isNull() && qAlpha(_blendColor) < 0xff ) { paint.drawPixmap(0, 0, _backgroundImage); QColor background = _colorTable[DEFAULT_BACK_COLOR].color; background.setAlpha(qAlpha(_blendColor)); paint.fillRect(contentsRect(), background); } if(_drawTextTestFlag) { calDrawTextAdditionHeight(paint); } const auto rects = (pe->region() & contentsRect()).rects(); for (const QRect &rect : rects) { drawBackground(paint,rect,palette().background().color(), true /* use opacity setting */); drawContents(paint, rect); } drawInputMethodPreeditString(paint,preeditRect()); paintFilters(paint); } QPoint TerminalDisplay::cursorPosition() const { if (_screenWindow) return _screenWindow->cursorPosition(); else return {0,0}; } QRect TerminalDisplay::preeditRect() const { const int preeditLength = string_width(_inputMethodData.preeditString); if ( preeditLength == 0 ) return {}; return QRect(_leftMargin + _fontWidth*cursorPosition().x(), _topMargin + _fontHeight*cursorPosition().y(), _fontWidth*preeditLength, _fontHeight); } void TerminalDisplay::drawInputMethodPreeditString(QPainter& painter , const QRect& rect) { if ( _inputMethodData.preeditString.empty() ) return; const QPoint cursorPos = cursorPosition(); bool invertColors = false; const QColor background = _colorTable[DEFAULT_BACK_COLOR].color; const QColor foreground = _colorTable[DEFAULT_FORE_COLOR].color; const Character* style = &_image[loc(cursorPos.x(),cursorPos.y())]; drawBackground(painter,rect,background,true); drawCursor(painter,rect,foreground,background,invertColors); drawCharacters(painter,rect,_inputMethodData.preeditString,style,invertColors); _inputMethodData.previousPreeditRect = rect; } FilterChain* TerminalDisplay::filterChain() const { return _filterChain; } void TerminalDisplay::paintFilters(QPainter& painter) { // get color of character under mouse and use it to draw // lines for filters QPoint cursorPos = mapFromGlobal(QCursor::pos()); int cursorLine; int cursorColumn; int leftMargin = _leftBaseMargin + ((_scrollbarLocation == QTermWidget::ScrollBarLeft && !_scrollBar->style()->styleHint(QStyle::SH_ScrollBar_Transient, nullptr, _scrollBar)) ? _scrollBar->width() : 0); getCharacterPosition( cursorPos , cursorLine , cursorColumn ); Character cursorCharacter = _image[loc(cursorColumn,cursorLine)]; painter.setPen( QPen(cursorCharacter.foregroundColor.color(colorTable())) ); /***add begin by ut001121 zhangmeng 20200624 光标悬浮在链接上面时变成手形光标 修复BUG34676***/ bool bDrawLineForHotSpotLink = false; // iterate over hotspots identified by the display's currently active filters // and draw appropriate visuals to indicate the presence of the hotspot QList spots = _filterChain->hotSpots(); QListIterator iter(spots); while (iter.hasNext()) { Filter::HotSpot* spot = iter.next(); QRegion region; if ( spot->type() == Filter::HotSpot::Link ) { QRect r; if (spot->startLine()==spot->endLine()) { r.setCoords( spot->startColumn()*_fontWidth + 1 + leftMargin, spot->startLine()*_fontHeight + 1 + _topBaseMargin, spot->endColumn()*_fontWidth - 1 + leftMargin, (spot->endLine()+1)*_fontHeight - 1 + _topBaseMargin ); region |= r; } else { r.setCoords( spot->startColumn()*_fontWidth + 1 + leftMargin, spot->startLine()*_fontHeight + 1 + _topBaseMargin, _columns*_fontWidth - 1 + leftMargin, (spot->startLine()+1)*_fontHeight - 1 + _topBaseMargin ); region |= r; for ( int line = spot->startLine()+1 ; line < spot->endLine() ; line++ ) { r.setCoords( 0*_fontWidth + 1 + leftMargin, line*_fontHeight + 1 + _topBaseMargin, _columns*_fontWidth - 1 + leftMargin, (line+1)*_fontHeight - 1 + _topBaseMargin ); region |= r; } r.setCoords( 0*_fontWidth + 1 + leftMargin, spot->endLine()*_fontHeight + 1 + _topBaseMargin, spot->endColumn()*_fontWidth - 1 + leftMargin, (spot->endLine()+1)*_fontHeight - 1 + _topBaseMargin ); region |= r; } } for ( int line = spot->startLine() ; line <= spot->endLine() ; line++ ) { int startColumn = 0; int endColumn = _columns-1; // TODO use number of _columns which are actually // occupied on this line rather than the width of the // display in _columns // ignore whitespace at the end of the lines while ( QChar(_image[loc(endColumn,line)].character).isSpace() && endColumn > 0 ) endColumn--; // increment here because the column which we want to set 'endColumn' to // is the first whitespace character at the end of the line endColumn++; if ( line == spot->startLine() ) startColumn = spot->startColumn(); if ( line == spot->endLine() ) endColumn = spot->endColumn(); // subtract one pixel from // the right and bottom so that // we do not overdraw adjacent // hotspots // // subtracting one pixel from all sides also prevents an edge case where // moving the mouse outside a link could still leave it underlined // because the check below for the position of the cursor // finds it on the border of the target area QRect r; r.setCoords( startColumn*_fontWidth + 1 + leftMargin, line*_fontHeight + 1 + _topBaseMargin, endColumn*_fontWidth - 1 + leftMargin, (line+1)*_fontHeight - 1 + _topBaseMargin ); // Underline link hotspots if ( spot->type() == Filter::HotSpot::Link ) { QFontMetrics metrics(font()); // find the baseline (which is the invisible line that the characters in the font sit on, // with some having tails dangling below) int baseline = r.bottom() - metrics.descent(); // find the position of the underline below that int underlinePos = baseline + metrics.underlinePos(); if ( region.contains( mapFromGlobal(QCursor::pos()) ) ){ painter.drawLine( r.left() , underlinePos , r.right() , underlinePos ); /***add begin by ut001121 zhangmeng 20200624 光标悬浮在链接上面时变成手形光标 修复BUG34676***/ bDrawLineForHotSpotLink = true; } } // Marker hotspots simply have a transparent rectanglular shape // drawn on top of them else if ( spot->type() == Filter::HotSpot::Marker ) { //TODO - Do not use a hardcoded colour for this painter.fillRect(r,QBrush(QColor(255,0,0,120))); } } } /***add begin by ut001121 zhangmeng 20200624 光标悬浮在链接上面时变成手形光标 修复BUG34676***/ if(bDrawLineForHotSpotLink){ if(cursor().shape() != Qt::PointingHandCursor) setCursor(Qt::PointingHandCursor); } else if(cursor().shape() != Qt::IBeamCursor){ setCursor(Qt::IBeamCursor); } /***add end by ut001121***/ } int TerminalDisplay::textWidth(const int startColumn, const int length, const int line) const { QFontMetrics fm(font()); int result = 0; for (int column = 0; column < length; column++) { result += fm.width(_image[loc(startColumn + column, line)].character); } return result; } QRect TerminalDisplay::calculateTextArea(int topLeftX, int topLeftY, int startColumn, int line, int length) { int left = _fixedFont ? _fontWidth * startColumn : textWidth(0, startColumn, line); int top = _fontHeight * line; int width = _fixedFont ? _fontWidth * length : textWidth(startColumn, length, line); return {_leftMargin + topLeftX + left, _topMargin + topLeftY + top, width, _fontHeight}; } void TerminalDisplay::drawContents(QPainter &paint, const QRect &rect) { QPoint tL = contentsRect().topLeft(); int tLx = tL.x(); int tLy = tL.y(); int lux = qMin(_usedColumns-1, qMax(0,(rect.left() - tLx - _leftMargin ) / _fontWidth)); int luy = qMin(_usedLines-1, qMax(0,(rect.top() - tLy - _topMargin ) / _fontHeight)); int rlx = qMin(_usedColumns-1, qMax(0,(rect.right() - tLx - _leftMargin ) / _fontWidth)); int rly = qMin(_usedLines-1, qMax(0,(rect.bottom() - tLy - _topMargin ) / _fontHeight)); const int bufferSize = _usedColumns; std::wstring unistr; unistr.reserve(bufferSize); for (int y = luy; y <= rly; y++) { quint32 c = _image[loc(lux,y)].character; int x = lux; if(!c && x) x--; // Search for start of multi-column character for (; x <= rlx; x++) { int len = 1; int p = 0; // reset our buffer to the maximal size unistr.resize(bufferSize); // is this a single character or a sequence of characters ? if ( _image[loc(x,y)].rendition & RE_EXTENDED_CHAR ) { // sequence of characters ushort extendedCharLength = 0; ushort* chars = ExtendedCharTable::instance .lookupExtendedChar(_image[loc(x,y)].charSequence,extendedCharLength); for ( int index = 0 ; index < extendedCharLength ; index++ ) { Q_ASSERT( p < bufferSize ); unistr[p++] = chars[index]; } } else { // single character c = _image[loc(x,y)].character; if (c) { Q_ASSERT( p < bufferSize ); unistr[p++] = c; //fontMap(c); } } bool lineDraw = isLineChar(c); bool doubleWidth = (_image[ qMin(loc(x,y)+1,_imageSize) ].character == 0); CharacterColor currentForeground = _image[loc(x,y)].foregroundColor; CharacterColor currentBackground = _image[loc(x,y)].backgroundColor; quint8 currentRendition = _image[loc(x,y)].rendition; while (x+len <= rlx && _image[loc(x+len,y)].foregroundColor == currentForeground && _image[loc(x+len,y)].backgroundColor == currentBackground && _image[loc(x+len,y)].rendition == currentRendition && (_image[ qMin(loc(x+len,y)+1,_imageSize) ].character == 0) == doubleWidth && isLineChar( c = _image[loc(x+len,y)].character) == lineDraw) // Assignment! { if (c) unistr[p++] = c; //fontMap(c); if (doubleWidth) // assert((_image[loc(x+len,y)+1].character == 0)), see above if condition len++; // Skip trailing part of multi-column character len++; } if ((x+len < _usedColumns) && (!_image[loc(x+len,y)].character)) len++; // Adjust for trailing part of multi-column character bool save__fixedFont = _fixedFont; if (lineDraw) _fixedFont = false; unistr.resize(p); // Create a text scaling matrix for double width and double height lines. QTransform textScale; if (y < _lineProperties.size()) { if (_lineProperties[y] & LINE_DOUBLEWIDTH) textScale.scale(2,1); if (_lineProperties[y] & LINE_DOUBLEHEIGHT) textScale.scale(1,2); } //Apply text scaling matrix. paint.setWorldTransform(textScale, true); //calculate the area in which the text will be drawn QRect textArea = calculateTextArea(tLx, tLy, x, y, len); //move the calculated area to take account of scaling applied to the painter. //the position of the area from the origin (0,0) is scaled //by the opposite of whatever //transformation has been applied to the painter. this ensures that //painting does actually start from textArea.topLeft() //(instead of textArea.topLeft() * painter-scale) textArea.moveTopLeft( textScale.inverted().map(textArea.topLeft()) ); //paint text fragment drawTextFragment( paint, textArea, unistr, &_image[loc(x,y)] ); //, //0, //!_isPrinting ); _fixedFont = save__fixedFont; //reset back to single-width, single-height _lines paint.setWorldTransform(textScale.inverted(), true); if (y < _lineProperties.size()-1) { //double-height _lines are represented by two adjacent _lines //containing the same characters //both _lines will have the LINE_DOUBLEHEIGHT attribute. //If the current line has the LINE_DOUBLEHEIGHT attribute, //we can therefore skip the next line if (_lineProperties[y] & LINE_DOUBLEHEIGHT) y++; } x += len - 1; } } } void TerminalDisplay::blinkEvent() { if (!_allowBlinkingText) return; _blinking = !_blinking; //TODO: Optimize to only repaint the areas of the widget // where there is blinking text // rather than repainting the whole widget. update(); } QRect TerminalDisplay::imageToWidget(const QRect& imageArea) const { QRect result; result.setLeft( _leftMargin + _fontWidth * imageArea.left() ); result.setTop( _topMargin + _fontHeight * imageArea.top() ); result.setWidth( _fontWidth * imageArea.width() ); result.setHeight( _fontHeight * imageArea.height() ); return result; } void TerminalDisplay::updateCursor() { // QRect cursorRect = imageToWidget( QRect(cursorPosition(),QSize(1,1)) ); update(); } void TerminalDisplay::blinkCursorEvent() { _cursorBlinking = !_cursorBlinking; updateCursor(); } /* ------------------------------------------------------------------------- */ /* */ /* Resizing */ /* */ /* ------------------------------------------------------------------------- */ void TerminalDisplay::resizeEvent(QResizeEvent*) { updateImageSize(); processFilters(); } void TerminalDisplay::propagateSize() { if (_isFixedSize) { setSize(_columns, _lines); QWidget::setFixedSize(sizeHint()); parentWidget()->adjustSize(); parentWidget()->setFixedSize(parentWidget()->sizeHint()); return; } if (_image) updateImageSize(); } void TerminalDisplay::updateImageSize() { Character* oldimg = _image; int oldlin = _lines; int oldcol = _columns; makeImage(); // copy the old image to reduce flicker int lines = qMin(oldlin,_lines); int columns = qMin(oldcol,_columns); if (oldimg) { for (int line = 0; line < lines; line++) { memcpy((void*)&_image[_columns*line], (void*)&oldimg[oldcol*line],columns*sizeof(Character)); } delete[] oldimg; } if (_screenWindow) _screenWindow->setWindowLines(_lines); _resizing = (oldlin!=_lines) || (oldcol!=_columns); if ( _resizing ) { showResizeNotification(); emit changedContentSizeSignal(oldlin, oldcol); // expose resizeEvent } _resizing = false; } //showEvent and hideEvent are reimplemented here so that it appears to other classes that the //display has been resized when the display is hidden or shown. // //TODO: Perhaps it would be better to have separate signals for show and hide instead of using //the same signal as the one for a content size change void TerminalDisplay::showEvent(QShowEvent*) { emit changedContentSizeSignal(_contentHeight,_contentWidth); } void TerminalDisplay::hideEvent(QHideEvent*) { emit changedContentSizeSignal(_contentHeight,_contentWidth); } /* ------------------------------------------------------------------------- */ /* */ /* Scrollbar */ /* */ /* ------------------------------------------------------------------------- */ void TerminalDisplay::scrollBarPositionChanged(int) { if ( !_screenWindow ) return; _screenWindow->scrollTo( _scrollBar->value() ); // if the thumb has been moved to the bottom of the _scrollBar then set // the display to automatically track new output, // that is, scroll down automatically // to how new _lines as they are added const bool atEndOfOutput = (_scrollBar->value() == _scrollBar->maximum()); _screenWindow->setTrackOutput( atEndOfOutput ); updateImage(); } void TerminalDisplay::setScroll(int cursor, int slines) { // update _scrollBar if the range or value has changed, // otherwise return // // setting the range or value of a _scrollBar will always trigger // a repaint, so it should be avoided if it is not necessary if ( _scrollBar->minimum() == 0 && _scrollBar->maximum() == (slines - _lines) && _scrollBar->value() == cursor ) { return; } disconnect(_scrollBar, SIGNAL(valueChanged(int)), this, SLOT(scrollBarPositionChanged(int))); _scrollBar->setRange(0,slines - _lines); _scrollBar->setSingleStep(1); _scrollBar->setPageStep(_lines); _scrollBar->setValue(cursor); connect(_scrollBar, SIGNAL(valueChanged(int)), this, SLOT(scrollBarPositionChanged(int))); } void TerminalDisplay::scrollToEnd() { disconnect(_scrollBar, SIGNAL(valueChanged(int)), this, SLOT(scrollBarPositionChanged(int))); _scrollBar->setValue( _scrollBar->maximum() ); connect(_scrollBar, SIGNAL(valueChanged(int)), this, SLOT(scrollBarPositionChanged(int))); _screenWindow->scrollTo( _scrollBar->value() + 1 ); _screenWindow->setTrackOutput( _screenWindow->atEndOfOutput() ); } void TerminalDisplay::setScrollBarPosition(QTermWidget::ScrollBarPosition position) { if (_scrollbarLocation == position) return; if ( position == QTermWidget::NoScrollBar ) _scrollBar->hide(); else _scrollBar->show(); _topMargin = _leftMargin = 1; _scrollbarLocation = position; propagateSize(); update(); } void TerminalDisplay::mousePressEvent(QMouseEvent* ev) { if ( _possibleTripleClick && (ev->button()==Qt::LeftButton) ) { mouseTripleClickEvent(ev); return; } if ( !contentsRect().contains(ev->pos()) ) return; if ( !_screenWindow ) return; int charLine; int charColumn; getCharacterPosition(ev->pos(),charLine,charColumn); QPoint pos = QPoint(charColumn,charLine); if ( ev->button() == Qt::LeftButton) { _lineSelectionMode = false; _wordSelectionMode = false; if(!hasFocus()) { setFocus(); } emit leftMouseClick(); emit isBusySelecting(true); // Keep it steady... // Drag only when the Control key is hold bool selected = false; // The receiver of the testIsSelected() signal will adjust // 'selected' accordingly. //emit testIsSelected(pos.x(), pos.y(), selected); selected = _screenWindow->isSelected(pos.x(),pos.y()); if ((!_ctrlDrag || ev->modifiers() & Qt::ControlModifier) && selected ) { // The user clicked inside selected text dragInfo.state = diPending; dragInfo.start = ev->pos(); } else { // No reason to ever start a drag event dragInfo.state = diNone; _preserveLineBreaks = !( ( ev->modifiers() & Qt::ControlModifier ) && !(ev->modifiers() & Qt::AltModifier) ); _columnSelectionMode = (ev->modifiers() & Qt::AltModifier) && (ev->modifiers() & Qt::ControlModifier); if (_mouseMarks || (ev->modifiers() & Qt::ShiftModifier)) { _screenWindow->clearSelection(); //emit clearSelectionSignal(); pos.ry() += _scrollBar->value(); _iPntSel = _pntSel = pos; _actSel = 1; // left mouse button pressed but nothing selected yet. } else { emit mouseSignal( 0, charColumn + 1, charLine + 1 +_scrollBar->value() -_scrollBar->maximum() , 0); } Filter::HotSpot *spot = _filterChain->hotSpotAt(charLine, charColumn); if (spot && spot->type() == Filter::HotSpot::Link) spot->activate(QLatin1String("click-action")); } } else if ( ev->button() == Qt::MidButton ) { if ( _mouseMarks || (ev->modifiers() & Qt::ShiftModifier) ) emitSelection(true,ev->modifiers() & Qt::ControlModifier); else emit mouseSignal( 1, charColumn +1, charLine +1 +_scrollBar->value() -_scrollBar->maximum() , 0); } else if ( ev->button() == Qt::RightButton ) { if (_mouseMarks || (ev->modifiers() & Qt::ShiftModifier)) emit configureRequest(ev->pos()); else emit mouseSignal( 2, charColumn +1, charLine +1 +_scrollBar->value() -_scrollBar->maximum() , 0); } /******** Modify by m000714 daizhengwen 2020-04-28: 调用父类的QMousePressEvent****************/ QWidget::mousePressEvent(ev); /********************* Modify by m000714 daizhengwen End ************************/ } QList TerminalDisplay::filterActions(const QPoint& position) { int charLine, charColumn; getCharacterPosition(position,charLine,charColumn); Filter::HotSpot* spot = _filterChain->hotSpotAt(charLine,charColumn); return spot ? spot->actions() : QList(); } void TerminalDisplay::mouseMoveEvent(QMouseEvent* ev) { int charLine = 0; int charColumn = 0; int leftMargin = _leftBaseMargin + ((_scrollbarLocation == QTermWidget::ScrollBarLeft && !_scrollBar->style()->styleHint(QStyle::SH_ScrollBar_Transient, nullptr, _scrollBar)) ? _scrollBar->width() : 0); getCharacterPosition(ev->pos(),charLine,charColumn); // handle filters // change link hot-spot appearance on mouse-over Filter::HotSpot* spot = _filterChain->hotSpotAt(charLine,charColumn); if ( spot && spot->type() == Filter::HotSpot::Link) { QRegion previousHotspotArea = _mouseOverHotspotArea; _mouseOverHotspotArea = QRegion(); QRect r; if (spot->startLine()==spot->endLine()) { r.setCoords( spot->startColumn()*_fontWidth + leftMargin, spot->startLine()*_fontHeight + _topBaseMargin, spot->endColumn()*_fontWidth + leftMargin, (spot->endLine()+1)*_fontHeight - 1 + _topBaseMargin ); _mouseOverHotspotArea |= r; } else { r.setCoords( spot->startColumn()*_fontWidth + leftMargin, spot->startLine()*_fontHeight + _topBaseMargin, _columns*_fontWidth - 1 + leftMargin, (spot->startLine()+1)*_fontHeight + _topBaseMargin ); _mouseOverHotspotArea |= r; for ( int line = spot->startLine()+1 ; line < spot->endLine() ; line++ ) { r.setCoords( 0*_fontWidth + leftMargin, line*_fontHeight + _topBaseMargin, _columns*_fontWidth + leftMargin, (line+1)*_fontHeight + _topBaseMargin ); _mouseOverHotspotArea |= r; } r.setCoords( 0*_fontWidth + leftMargin, spot->endLine()*_fontHeight + _topBaseMargin, spot->endColumn()*_fontWidth + leftMargin, (spot->endLine()+1)*_fontHeight + _topBaseMargin ); _mouseOverHotspotArea |= r; } update( _mouseOverHotspotArea | previousHotspotArea ); } else if ( !_mouseOverHotspotArea.isEmpty() ) { update( _mouseOverHotspotArea ); // set hotspot area to an invalid rectangle _mouseOverHotspotArea = QRegion(); } // for auto-hiding the cursor, we need mouseTracking if (ev->buttons() == Qt::NoButton ) return; // if the terminal is interested in mouse movements // then emit a mouse movement signal, unless the shift // key is being held down, which overrides this. if (!_mouseMarks && !(ev->modifiers() & Qt::ShiftModifier)) { int button = 3; if (ev->buttons() & Qt::LeftButton) button = 0; if (ev->buttons() & Qt::MidButton) button = 1; if (ev->buttons() & Qt::RightButton) button = 2; emit mouseSignal( button, charColumn + 1, charLine + 1 +_scrollBar->value() -_scrollBar->maximum(), 1 ); return; } if (dragInfo.state == diPending) { // we had a mouse down, but haven't confirmed a drag yet // if the mouse has moved sufficiently, we will confirm // int distance = KGlobalSettings::dndEventDelay(); int distance = QApplication::startDragDistance(); if ( ev->x() > dragInfo.start.x() + distance || ev->x() < dragInfo.start.x() - distance || ev->y() > dragInfo.start.y() + distance || ev->y() < dragInfo.start.y() - distance) { // we've left the drag square, we can start a real drag operation now emit isBusySelecting(false); // Ok.. we can breath again. _screenWindow->clearSelection(); doDrag(); } return; } else if (dragInfo.state == diDragging) { // this isn't technically needed because mouseMoveEvent is suppressed during // Qt drag operations, replaced by dragMoveEvent return; } if (_actSel == 0) return; // don't extend selection while pasting if (ev->buttons() & Qt::MidButton) return; extendSelection( ev->pos() ); } void TerminalDisplay::extendSelection( const QPoint& position ) { QPoint pos = position; if ( !_screenWindow ) return; //if ( !contentsRect().contains(ev->pos()) ) return; QPoint tL = contentsRect().topLeft(); int tLx = tL.x(); int tLy = tL.y(); int scroll = _scrollBar->value(); // we're in the process of moving the mouse with the left button pressed // the mouse cursor will kept caught within the bounds of the text in // this widget. int linesBeyondWidget = 0; QRect textBounds(tLx + _leftMargin, tLy + _topMargin, _usedColumns*_fontWidth-1, _usedLines*_fontHeight-1); // Adjust position within text area bounds. QPoint oldpos = pos; pos.setX( qBound(textBounds.left(),pos.x(),textBounds.right()) ); pos.setY( qBound(textBounds.top(),pos.y(),textBounds.bottom()) ); if ( oldpos.y() > textBounds.bottom() ) { linesBeyondWidget = (oldpos.y()-textBounds.bottom()) / _fontHeight; _scrollBar->setValue(_scrollBar->value()+linesBeyondWidget+1); // scrollforward } if ( oldpos.y() < textBounds.top() ) { linesBeyondWidget = (textBounds.top()-oldpos.y()) / _fontHeight; _scrollBar->setValue(_scrollBar->value()-linesBeyondWidget-1); // history } int charColumn = 0; int charLine = 0; getCharacterPosition(pos,charLine,charColumn); QPoint here = QPoint(charColumn,charLine); //QPoint((pos.x()-tLx-_leftMargin+(_fontWidth/2))/_fontWidth,(pos.y()-tLy-_topMargin)/_fontHeight); QPoint ohere; QPoint _iPntSelCorr = _iPntSel; _iPntSelCorr.ry() -= _scrollBar->value(); QPoint _pntSelCorr = _pntSel; _pntSelCorr.ry() -= _scrollBar->value(); bool swapping = false; if ( _wordSelectionMode ) { // Extend to word boundaries int i; QChar selClass; bool left_not_right = ( here.y() < _iPntSelCorr.y() || ( here.y() == _iPntSelCorr.y() && here.x() < _iPntSelCorr.x() ) ); bool old_left_not_right = ( _pntSelCorr.y() < _iPntSelCorr.y() || ( _pntSelCorr.y() == _iPntSelCorr.y() && _pntSelCorr.x() < _iPntSelCorr.x() ) ); swapping = left_not_right != old_left_not_right; // Find left (left_not_right ? from here : from start) QPoint left = left_not_right ? here : _iPntSelCorr; i = loc(left.x(),left.y()); if (i>=0 && i<=_imageSize) { selClass = charClass(_image[i].character); while ( ((left.x()>0) || (left.y()>0 && (_lineProperties[left.y()-1] & LINE_WRAPPED) )) && charClass(_image[i-1].character) == selClass ) { i--; if (left.x()>0) left.rx()--; else {left.rx()=_usedColumns-1; left.ry()--;} } } // Find left (left_not_right ? from start : from here) QPoint right = left_not_right ? _iPntSelCorr : here; i = loc(right.x(),right.y()); if (i>=0 && i<=_imageSize) { selClass = charClass(_image[i].character); while( ((right.x()<_usedColumns-1) || (right.y()<_usedLines-1 && (_lineProperties[right.y()] & LINE_WRAPPED) )) && charClass(_image[i+1].character) == selClass ) { i++; if (right.x()<_usedColumns-1) right.rx()++; else {right.rx()=0; right.ry()++; } } } // Pick which is start (ohere) and which is extension (here) if ( left_not_right ) { here = left; ohere = right; } else { here = right; ohere = left; } ohere.rx()++; } if ( _lineSelectionMode ) { // Extend to complete line bool above_not_below = ( here.y() < _iPntSelCorr.y() ); QPoint above = above_not_below ? here : _iPntSelCorr; QPoint below = above_not_below ? _iPntSelCorr : here; while (above.y()>0 && (_lineProperties[above.y()-1] & LINE_WRAPPED) ) above.ry()--; while (below.y()<_usedLines-1 && (_lineProperties[below.y()] & LINE_WRAPPED) ) below.ry()++; above.setX(0); below.setX(_usedColumns-1); // Pick which is start (ohere) and which is extension (here) if ( above_not_below ) { here = above; ohere = below; } else { here = below; ohere = above; } QPoint newSelBegin = QPoint( ohere.x(), ohere.y() ); swapping = !(_tripleSelBegin==newSelBegin); _tripleSelBegin = newSelBegin; ohere.rx()++; } int offset = 0; if ( !_wordSelectionMode && !_lineSelectionMode ) { int i; QChar selClass; bool left_not_right = ( here.y() < _iPntSelCorr.y() || ( here.y() == _iPntSelCorr.y() && here.x() < _iPntSelCorr.x() ) ); bool old_left_not_right = ( _pntSelCorr.y() < _iPntSelCorr.y() || ( _pntSelCorr.y() == _iPntSelCorr.y() && _pntSelCorr.x() < _iPntSelCorr.x() ) ); swapping = left_not_right != old_left_not_right; // Find left (left_not_right ? from here : from start) QPoint left = left_not_right ? here : _iPntSelCorr; // Find left (left_not_right ? from start : from here) QPoint right = left_not_right ? _iPntSelCorr : here; if ( right.x() > 0 && !_columnSelectionMode ) { i = loc(right.x(),right.y()); if (i>=0 && i<=_imageSize) { selClass = charClass(_image[i-1].character); /* if (selClass == ' ') { while ( right.x() < _usedColumns-1 && charClass(_image[i+1].character) == selClass && (right.y()<_usedLines-1) && !(_lineProperties[right.y()] & LINE_WRAPPED)) { i++; right.rx()++; } if (right.x() < _usedColumns-1) right = left_not_right ? _iPntSelCorr : here; else right.rx()++; // will be balanced later because of offset=-1; }*/ } } // Pick which is start (ohere) and which is extension (here) if ( left_not_right ) { here = left; ohere = right; offset = 0; } else { here = right; ohere = left; offset = -1; } } if ((here == _pntSelCorr) && (scroll == _scrollBar->value())) return; // not moved if (here == ohere) return; // It's not left, it's not right. if ( _actSel < 2 || swapping ) { if ( _columnSelectionMode && !_lineSelectionMode && !_wordSelectionMode ) { _screenWindow->setSelectionStart( ohere.x() , ohere.y() , true ); } else { _screenWindow->setSelectionStart( ohere.x()-1-offset , ohere.y() , false ); } } _actSel = 2; // within selection _pntSel = here; _pntSel.ry() += _scrollBar->value(); if ( _columnSelectionMode && !_lineSelectionMode && !_wordSelectionMode ) { _screenWindow->setSelectionEnd( here.x() , here.y() ); } else { _screenWindow->setSelectionEnd( here.x()+offset , here.y() ); } } void TerminalDisplay::mouseReleaseEvent(QMouseEvent* ev) { if ( !_screenWindow ) return; int charLine; int charColumn; getCharacterPosition(ev->pos(),charLine,charColumn); if ( ev->button() == Qt::LeftButton) { emit isBusySelecting(false); if(dragInfo.state == diPending) { // We had a drag event pending but never confirmed. Kill selection _screenWindow->clearSelection(); //emit clearSelectionSignal(); } else { if ( _actSel > 1 ) { setSelection( _screenWindow->selectedText(_preserveLineBreaks) ); } _actSel = 0; //FIXME: emits a release event even if the mouse is // outside the range. The procedure used in `mouseMoveEvent' // applies here, too. if (!_mouseMarks && !(ev->modifiers() & Qt::ShiftModifier)) emit mouseSignal( 0, charColumn + 1, charLine + 1 +_scrollBar->value() -_scrollBar->maximum() , 2); } dragInfo.state = diNone; } if ( !_mouseMarks && ((ev->button() == Qt::RightButton && !(ev->modifiers() & Qt::ShiftModifier)) || ev->button() == Qt::MidButton) ) { emit mouseSignal( ev->button() == Qt::MidButton ? 1 : 2, charColumn + 1, charLine + 1 +_scrollBar->value() -_scrollBar->maximum() , 2); } } void TerminalDisplay::getCharacterPosition(const QPoint& widgetPoint,int& line,int& column) const { line = (widgetPoint.y()-contentsRect().top()-_topMargin) / _fontHeight; if (line < 0) line = 0; if (line >= _usedLines) line = _usedLines - 1; int x = widgetPoint.x() + _fontWidth / 2 - contentsRect().left() - _leftMargin; if ( _fixedFont ) column = x / _fontWidth; else { column = 0; while(column + 1 < _usedColumns && x > textWidth(0, column + 1, line)) column++; } if ( column < 0 ) column = 0; // the column value returned can be equal to _usedColumns, which // is the position just after the last character displayed in a line. // // this is required so that the user can select characters in the right-most // column (or left-most for right-to-left input) if ( column > _usedColumns ) column = _usedColumns; } void TerminalDisplay::setHideCursor(bool hideCursor) { _hideCursor = hideCursor; update(); } void TerminalDisplay::setSessionId(int sessionId) { _sessionId = sessionId; _filterChain->setSessionId(sessionId); } void TerminalDisplay::updateFilters() { if ( !_screenWindow ) return; processFilters(); } void TerminalDisplay::updateLineProperties() { if ( !_screenWindow ) return; _lineProperties = _screenWindow->getLineProperties(); } void TerminalDisplay::mouseDoubleClickEvent(QMouseEvent* ev) { if ( ev->button() != Qt::LeftButton) return; if ( !_screenWindow ) return; int charLine = 0; int charColumn = 0; getCharacterPosition(ev->pos(),charLine,charColumn); QPoint pos(charColumn,charLine); // pass on double click as two clicks. if (!_mouseMarks && !(ev->modifiers() & Qt::ShiftModifier)) { // Send just _ONE_ click event, since the first click of the double click // was already sent by the click handler emit mouseSignal( 0, pos.x()+1, pos.y()+1 +_scrollBar->value() -_scrollBar->maximum(), 0 ); // left button return; } _screenWindow->clearSelection(); QPoint bgnSel = pos; QPoint endSel = pos; int i = loc(bgnSel.x(),bgnSel.y()); _iPntSel = bgnSel; _iPntSel.ry() += _scrollBar->value(); _wordSelectionMode = true; // find word boundaries... QChar selClass = charClass(_image[i].character); { // find the start of the word int x = bgnSel.x(); while ( ((x>0) || (bgnSel.y()>0 && (_lineProperties[bgnSel.y()-1] & LINE_WRAPPED) )) && charClass(_image[i-1].character) == selClass ) { i--; if (x>0) x--; else { x=_usedColumns-1; bgnSel.ry()--; } } bgnSel.setX(x); _screenWindow->setSelectionStart( bgnSel.x() , bgnSel.y() , false ); // find the end of the word i = loc( endSel.x(), endSel.y() ); x = endSel.x(); while( ((x<_usedColumns-1) || (endSel.y()<_usedLines-1 && (_lineProperties[endSel.y()] & LINE_WRAPPED) )) && charClass(_image[i+1].character) == selClass ) { i++; if (x<_usedColumns-1) x++; else { x=0; endSel.ry()++; } } endSel.setX(x); // In word selection mode don't select @ (64) if at end of word. if ( ( QChar( _image[i].character ) == QLatin1Char('@') ) && ( ( endSel.x() - bgnSel.x() ) > 0 ) ) endSel.setX( x - 1 ); _actSel = 2; // within selection _screenWindow->setSelectionEnd( endSel.x() , endSel.y() ); setSelection( _screenWindow->selectedText(_preserveLineBreaks) ); } _possibleTripleClick=true; QTimer::singleShot(QApplication::doubleClickInterval(),this, SLOT(tripleClickTimeout())); } void TerminalDisplay::wheelEvent( QWheelEvent* ev ) { if (ev->orientation() != Qt::Vertical) return; // if the terminal program is not interested mouse events // then send the event to the scrollbar if the slider has room to move // or otherwise send simulated up / down key presses to the terminal program // for the benefit of programs such as 'less' if ( _mouseMarks ) { bool canScroll = _scrollBar->maximum() > 0; if (canScroll) _scrollBar->event(ev); else { // assume that each Up / Down key event will cause the terminal application // to scroll by one line. // // to get a reasonable scrolling speed, scroll by one line for every 5 degrees // of mouse wheel rotation. Mouse wheels typically move in steps of 15 degrees, // giving a scroll of 3 lines // commit this to fix bug 17772, Because this code will turn the scrolling operation // into the up and down keys of the keyboard and send the keyboard signal /* int key = ev->delta() > 0 ? Qt::Key_Up : Qt::Key_Down; // QWheelEvent::delta() gives rotation in eighths of a degree int wheelDegrees = ev->delta() / 8; int linesToScroll = abs(wheelDegrees) / 5; QKeyEvent keyScrollEvent(QEvent::KeyPress,key,Qt::NoModifier); for (int i=0;ipos() , charLine , charColumn ); emit mouseSignal( ev->delta() > 0 ? 4 : 5, charColumn + 1, charLine + 1 +_scrollBar->value() -_scrollBar->maximum() , 0); } } void TerminalDisplay::tripleClickTimeout() { _possibleTripleClick=false; } void TerminalDisplay::mouseTripleClickEvent(QMouseEvent* ev) { if ( !_screenWindow ) return; int charLine; int charColumn; getCharacterPosition(ev->pos(),charLine,charColumn); _iPntSel = QPoint(charColumn,charLine); _screenWindow->clearSelection(); _lineSelectionMode = true; _wordSelectionMode = false; _actSel = 2; // within selection emit isBusySelecting(true); // Keep it steady... while (_iPntSel.y()>0 && (_lineProperties[_iPntSel.y()-1] & LINE_WRAPPED) ) _iPntSel.ry()--; if (_tripleClickMode == SelectForwardsFromCursor) { // find word boundary start int i = loc(_iPntSel.x(),_iPntSel.y()); QChar selClass = charClass(_image[i].character); int x = _iPntSel.x(); while ( ((x>0) || (_iPntSel.y()>0 && (_lineProperties[_iPntSel.y()-1] & LINE_WRAPPED) ) ) && charClass(_image[i-1].character) == selClass ) { i--; if (x>0) x--; else { x=_columns-1; _iPntSel.ry()--; } } _screenWindow->setSelectionStart( x , _iPntSel.y() , false ); _tripleSelBegin = QPoint( x, _iPntSel.y() ); } else if (_tripleClickMode == SelectWholeLine) { _screenWindow->setSelectionStart( 0 , _iPntSel.y() , false ); _tripleSelBegin = QPoint( 0, _iPntSel.y() ); } while (_iPntSel.y()<_lines-1 && (_lineProperties[_iPntSel.y()] & LINE_WRAPPED) ) _iPntSel.ry()++; _screenWindow->setSelectionEnd( _columns - 1 , _iPntSel.y() ); setSelection(_screenWindow->selectedText(_preserveLineBreaks)); _iPntSel.ry() += _scrollBar->value(); } bool TerminalDisplay::focusNextPrevChild( bool next ) { if (next) return false; // This disables changing the active part in konqueror // when pressing Tab return QWidget::focusNextPrevChild( next ); } QChar TerminalDisplay::charClass(QChar qch) const { if ( qch.isSpace() ) return QLatin1Char(' '); if ( qch.isLetterOrNumber() || _wordCharacters.contains(qch, Qt::CaseInsensitive ) ) return QLatin1Char('a'); return qch; } void TerminalDisplay::setWordCharacters(const QString& wc) { _wordCharacters = wc; } void TerminalDisplay::setUsesMouse(bool on) { if (_mouseMarks != on) { _mouseMarks = on; setCursor( _mouseMarks ? Qt::IBeamCursor : Qt::ArrowCursor ); emit usesMouseChanged(); } } bool TerminalDisplay::usesMouse() const { return _mouseMarks; } void TerminalDisplay::setBracketedPasteMode(bool on) { _bracketedPasteMode = on; } bool TerminalDisplay::bracketedPasteMode() const { return _bracketedPasteMode; } /* ------------------------------------------------------------------------- */ /* */ /* Clipboard */ /* */ /* ------------------------------------------------------------------------- */ #undef KeyPress void TerminalDisplay::emitSelection(bool useXselection,bool appendReturn) { if ( !_screenWindow ) return; // Paste Clipboard by simulating keypress events QString text = QApplication::clipboard()->text(useXselection ? QClipboard::Selection : QClipboard::Clipboard); if(appendReturn) text.append(QLatin1Char('\r')); if ( ! text.isEmpty() ) { text.replace(QLatin1Char('\n'), QLatin1Char('\r')); bracketText(text); QKeyEvent e(QEvent::KeyPress, 0, Qt::NoModifier, text); emit keyPressedSignal(&e); // expose as a big fat keypress event _screenWindow->clearSelection(); } } void TerminalDisplay::bracketText(QString& text) { if (bracketedPasteMode()) { text.prepend(QLatin1String("\033[200~")); text.append(QLatin1String("\033[201~")); } } void TerminalDisplay::setSelection(const QString& t) { /******** Modify by n014361 wangpeili 2020-02-12: 自动拷贝功能,需发出可拷贝信号***********×****/ if(t != QApplication::clipboard()->text(QClipboard::Selection)) { selectionChanged(); } QApplication::clipboard()->setText(t, QClipboard::Selection); /***************** Modify by n014361 End *************************/ } /******************************************************************** 1. @函数: setSelectionAll 2. @作者: 王培利 3. @日期: 2020-02-13 4. @说明: 屏幕全选功能 ********************************************************************/ void TerminalDisplay::setSelectionAll() { _screenWindow->setSelectionAll(); setSelection(_screenWindow->selectedText(_preserveLineBreaks)); } void TerminalDisplay::copyClipboard() { if ( !_screenWindow ) return; QString text = _screenWindow->selectedText(_preserveLineBreaks); if (!text.isEmpty()) QApplication::clipboard()->setText(text); } void TerminalDisplay::pasteClipboard() { emitSelection(false,false); } void TerminalDisplay::pasteSelection() { emitSelection(true,false); } /* ------------------------------------------------------------------------- */ /* */ /* Keyboard */ /* */ /* ------------------------------------------------------------------------- */ void TerminalDisplay::setFlowControlWarningEnabled( bool enable ) { _flowControlWarningEnabled = enable; // if the dialog is currently visible and the flow control warning has // been disabled then hide the dialog if (!enable) outputSuspended(false); } void TerminalDisplay::setMotionAfterPasting(MotionAfterPasting action) { mMotionAfterPasting = action; } int TerminalDisplay::motionAfterPasting() { return mMotionAfterPasting; } void TerminalDisplay::keyPressEvent( QKeyEvent* event ) { bool emitKeyPressSignal = true; // Keyboard-based navigation if ( event->modifiers() == Qt::ShiftModifier ) { bool update = true; if ( event->key() == Qt::Key_PageUp ) { _screenWindow->scrollBy( ScreenWindow::ScrollPages , -1 ); } else if ( event->key() == Qt::Key_PageDown ) { _screenWindow->scrollBy( ScreenWindow::ScrollPages , 1 ); } else if ( event->key() == Qt::Key_Up ) { _screenWindow->scrollBy( ScreenWindow::ScrollLines , -1 ); } else if ( event->key() == Qt::Key_Down ) { _screenWindow->scrollBy( ScreenWindow::ScrollLines , 1 ); } else if ( event->key() == Qt::Key_End) { scrollToEnd(); } else if ( event->key() == Qt::Key_Home) { _screenWindow->scrollTo(0); } else update = false; if ( update ) { _screenWindow->setTrackOutput( _screenWindow->atEndOfOutput() ); updateLineProperties(); updateImage(); // do not send key press to terminal emitKeyPressSignal = false; } } _actSel=0; // Key stroke implies a screen update, so TerminalDisplay won't // know where the current selection is. if (_hasBlinkingCursor) { _blinkCursorTimer->start(QApplication::cursorFlashTime() / 2); if (_cursorBlinking) blinkCursorEvent(); else _cursorBlinking = false; } if ( emitKeyPressSignal ) { emit keyPressedSignal(event); /******** Modify by wangpeili n014361 2020-02-14: 按键滚动功能***********/ // 按键滚动原为默认。现在修改为可以设置是否滚动 // 暂时取消了原系统shift/alt/ctrl键的单独跳转功能。 // if(event->modifiers().testFlag(Qt::ShiftModifier) // || event->modifiers().testFlag(Qt::ControlModifier) // || event->modifiers().testFlag(Qt::AltModifier)) // { switch(mMotionAfterPasting) { case MoveStartScreenWindow: _screenWindow->scrollTo(0); break; case MoveEndScreenWindow: scrollToEnd(); break; case NoMoveScreenWindow: break; } // } // else // { // scrollToEnd(); // } /***************** Modify by wangpeili n014361 End *****************/ } event->accept(); } void TerminalDisplay::inputMethodEvent( QInputMethodEvent* event ) { QKeyEvent keyEvent(QEvent::KeyPress,0,Qt::NoModifier,event->commitString()); emit keyPressedSignal(&keyEvent); _inputMethodData.preeditString = event->preeditString().toStdWString(); update(preeditRect() | _inputMethodData.previousPreeditRect); event->accept(); } QVariant TerminalDisplay::inputMethodQuery( Qt::InputMethodQuery query ) const { const QPoint cursorPos = _screenWindow ? _screenWindow->cursorPosition() : QPoint(0,0); switch ( query ) { case Qt::ImMicroFocus: return imageToWidget(QRect(cursorPos.x(),cursorPos.y(),1,1)); break; case Qt::ImFont: return font(); break; case Qt::ImCursorPosition: // return the cursor position within the current line return cursorPos.x(); break; case Qt::ImSurroundingText: { // return the text from the current line QString lineText; QTextStream stream(&lineText); PlainTextDecoder decoder; decoder.begin(&stream); decoder.decodeLine(&_image[loc(0,cursorPos.y())],_usedColumns,_lineProperties[cursorPos.y()]); decoder.end(); return lineText; } break; case Qt::ImCurrentSelection: return QString(); break; default: break; } return QVariant(); } bool TerminalDisplay::handleShortcutOverrideEvent(QKeyEvent* keyEvent) { int modifiers = keyEvent->modifiers(); // When a possible shortcut combination is pressed, // emit the overrideShortcutCheck() signal to allow the host // to decide whether the terminal should override it or not. if (modifiers != Qt::NoModifier) { int modifierCount = 0; unsigned int currentModifier = Qt::ShiftModifier; while (currentModifier <= Qt::KeypadModifier) { if (modifiers & currentModifier) modifierCount++; currentModifier <<= 1; } if (modifierCount < 2) { bool override = false; emit overrideShortcutCheck(keyEvent,override); if (override) { keyEvent->accept(); return true; } } } // Override any of the following shortcuts because // they are needed by the terminal int keyCode = keyEvent->key() | modifiers; switch ( keyCode ) { // list is taken from the QLineEdit::event() code case Qt::Key_Tab: case Qt::Key_Delete: case Qt::Key_Home: case Qt::Key_End: case Qt::Key_Backspace: case Qt::Key_Left: case Qt::Key_Right: case Qt::Key_Escape: keyEvent->accept(); return true; } return false; } bool TerminalDisplay::event(QEvent* event) { bool eventHandled = false; switch (event->type()) { case QEvent::ShortcutOverride: eventHandled = handleShortcutOverrideEvent((QKeyEvent*)event); break; case QEvent::PaletteChange: case QEvent::ApplicationPaletteChange: _scrollBar->setPalette( QApplication::palette() ); break; default: break; } return eventHandled ? true : QWidget::event(event); } void TerminalDisplay::setBellMode(int mode) { _bellMode=mode; } void TerminalDisplay::enableBell() { _allowBell = true; } void TerminalDisplay::bell(const QString& message) { if (_bellMode==NoBell) return; //limit the rate at which bells can occur //...mainly for sound effects where rapid bells in sequence //produce a horrible noise if ( _allowBell ) { _allowBell = false; QTimer::singleShot(500,this,SLOT(enableBell())); if (_bellMode==SystemBeepBell) { QApplication::beep(); } else if (_bellMode==NotifyBell) { emit notifyBell(message); } else if (_bellMode==VisualBell) { swapColorTable(); QTimer::singleShot(200,this,SLOT(swapColorTable())); } } } void TerminalDisplay::selectionChanged() { emit copyAvailable(_screenWindow->selectedText(false).isEmpty() == false); } void TerminalDisplay::swapColorTable() { ColorEntry color = _colorTable[1]; _colorTable[1]=_colorTable[0]; _colorTable[0]= color; _colorsInverted = !_colorsInverted; update(); } void TerminalDisplay::clearImage() { // We initialize _image[_imageSize] too. See makeImage() for (int i = 0; i <= _imageSize; i++) { _image[i].character = ' '; _image[i].foregroundColor = CharacterColor(COLOR_SPACE_DEFAULT, DEFAULT_FORE_COLOR); _image[i].backgroundColor = CharacterColor(COLOR_SPACE_DEFAULT, DEFAULT_BACK_COLOR); _image[i].rendition = DEFAULT_RENDITION; } } void TerminalDisplay::calcGeometry() { _scrollBar->resize(_scrollBar->sizeHint().width(), contentsRect().height()); int scrollBarWidth = _scrollBar->style()->styleHint(QStyle::SH_ScrollBar_Transient, nullptr, _scrollBar) ? 0 : _scrollBar->width(); switch(_scrollbarLocation) { case QTermWidget::NoScrollBar : _leftMargin = _leftBaseMargin; _contentWidth = contentsRect().width() - 2 * _leftBaseMargin; break; case QTermWidget::ScrollBarLeft : _leftMargin = _leftBaseMargin + scrollBarWidth; _contentWidth = contentsRect().width() - 2 * _leftBaseMargin - scrollBarWidth; _scrollBar->move(contentsRect().topLeft()); break; case QTermWidget::ScrollBarRight: _leftMargin = _leftBaseMargin; _contentWidth = contentsRect().width() - 2 * _leftBaseMargin - scrollBarWidth; _scrollBar->move(contentsRect().topRight() - QPoint(_scrollBar->width()-1, 0)); break; } _topMargin = _topBaseMargin; _contentHeight = contentsRect().height() - 2 * _topBaseMargin + /* mysterious */ 1; if (!_isFixedSize) { // ensure that display is always at least one column wide _columns = qMax(1,_contentWidth / _fontWidth); _usedColumns = qMin(_usedColumns,_columns); // ensure that display is always at least one line high _lines = qMax(1,_contentHeight / _fontHeight); _usedLines = qMin(_usedLines,_lines); } } void TerminalDisplay::makeImage() { calcGeometry(); // confirm that array will be of non-zero size, since the painting code // assumes a non-zero array length Q_ASSERT( _lines > 0 && _columns > 0 ); Q_ASSERT( _usedLines <= _lines && _usedColumns <= _columns ); _imageSize=_lines*_columns; // We over-commit one character so that we can be more relaxed in dealing with // certain boundary conditions: _image[_imageSize] is a valid but unused position _image = new Character[_imageSize+1]; clearImage(); } // calculate the needed size, this must be synced with calcGeometry() void TerminalDisplay::setSize(int columns, int lines) { int scrollBarWidth = (_scrollBar->isHidden() || _scrollBar->style()->styleHint(QStyle::SH_ScrollBar_Transient, nullptr, _scrollBar)) ? 0 : _scrollBar->sizeHint().width(); int horizontalMargin = 2 * _leftBaseMargin; int verticalMargin = 2 * _topBaseMargin; QSize newSize = QSize( horizontalMargin + scrollBarWidth + (columns * _fontWidth) , verticalMargin + (lines * _fontHeight) ); if ( newSize != size() ) { _size = newSize; updateGeometry(); } } void TerminalDisplay::setFixedSize(int cols, int lins) { _isFixedSize = true; //ensure that display is at least one line by one column in size _columns = qMax(1,cols); _lines = qMax(1,lins); _usedColumns = qMin(_usedColumns,_columns); _usedLines = qMin(_usedLines,_lines); if (_image) { delete[] _image; makeImage(); } setSize(cols, lins); QWidget::setFixedSize(_size); } QSize TerminalDisplay::sizeHint() const { return _size; } /* --------------------------------------------------------------------- */ /* */ /* Drag & Drop */ /* */ /* --------------------------------------------------------------------- */ void TerminalDisplay::dragEnterEvent(QDragEnterEvent* event) { if (event->mimeData()->hasFormat(QLatin1String("text/plain"))) event->acceptProposedAction(); if (event->mimeData()->urls().count()) event->acceptProposedAction(); } void TerminalDisplay::dropEvent(QDropEvent* event) { //KUrl::List urls = KUrl::List::fromMimeData(event->mimeData()); QList urls = event->mimeData()->urls(); QString dropText; if (!urls.isEmpty()) { // TODO/FIXME: escape or quote pasted things if neccessary... qDebug() << "TerminalDisplay: handling urls. It can be broken. Report any errors, please"; for ( int i = 0 ; i < urls.count() ; i++ ) { //KUrl url = KIO::NetAccess::mostLocalUrl( urls[i] , 0 ); QUrl url = urls[i]; QString urlText; if (url.isLocalFile()) urlText = url.path(); else urlText = url.toString(); // in future it may be useful to be able to insert file names with drag-and-drop // without quoting them (this only affects paths with spaces in) //urlText = KShell::quoteArg(urlText); dropText += urlText; if ( i != urls.count()-1 ) dropText += QLatin1Char(' '); } } else { dropText = event->mimeData()->text(); } emit sendStringToEmu(dropText.toLocal8Bit().constData()); } void TerminalDisplay::doDrag() { dragInfo.state = diDragging; dragInfo.dragObject = new QDrag(this); QMimeData *mimeData = new QMimeData; mimeData->setText(QApplication::clipboard()->text(QClipboard::Selection)); dragInfo.dragObject->setMimeData(mimeData); dragInfo.dragObject->start(Qt::CopyAction); // Don't delete the QTextDrag object. Qt will delete it when it's done with it. } void TerminalDisplay::outputSuspended(bool suspended) { //create the label when this function is first called if (!_outputSuspendedLabel) { //This label includes a link to an English language website //describing the 'flow control' (Xon/Xoff) feature found in almost //all terminal emulators. //If there isn't a suitable article available in the target language the link //can simply be removed. _outputSuspendedLabel = new QLabel( tr("Output has been " "suspended" " by pressing Ctrl+S." " Press Ctrl+Q to resume."), this ); QPalette palette(_outputSuspendedLabel->palette()); //KColorScheme::adjustBackground(palette,KColorScheme::NeutralBackground); _outputSuspendedLabel->setPalette(palette); _outputSuspendedLabel->setAutoFillBackground(true); _outputSuspendedLabel->setBackgroundRole(QPalette::Base); _outputSuspendedLabel->setFont(QApplication::font()); _outputSuspendedLabel->setContentsMargins(5, 5, 5, 5); //enable activation of "Xon/Xoff" link in label _outputSuspendedLabel->setTextInteractionFlags(Qt::LinksAccessibleByMouse | Qt::LinksAccessibleByKeyboard); _outputSuspendedLabel->setOpenExternalLinks(true); _outputSuspendedLabel->setVisible(false); _gridLayout->addWidget(_outputSuspendedLabel); _gridLayout->addItem( new QSpacerItem(0,0,QSizePolicy::Expanding, QSizePolicy::Expanding), 1,0); } _outputSuspendedLabel->setVisible(suspended); } uint TerminalDisplay::lineSpacing() const { return _lineSpacing; } void TerminalDisplay::setLineSpacing(uint i) { _lineSpacing = i; setVTFont(font()); // Trigger an update. } int TerminalDisplay::margin() const { return _topBaseMargin; } void TerminalDisplay::setMargin(int i) { _topBaseMargin = i; _leftBaseMargin = i; } AutoScrollHandler::AutoScrollHandler(QWidget* parent) : QObject(parent) , _timerId(0) { parent->installEventFilter(this); } void AutoScrollHandler::timerEvent(QTimerEvent* event) { if (event->timerId() != _timerId) return; QMouseEvent mouseEvent( QEvent::MouseMove, widget()->mapFromGlobal(QCursor::pos()), Qt::NoButton, Qt::LeftButton, Qt::NoModifier); QApplication::sendEvent(widget(),&mouseEvent); } bool AutoScrollHandler::eventFilter(QObject* watched,QEvent* event) { Q_ASSERT( watched == parent() ); Q_UNUSED( watched ); QMouseEvent* mouseEvent = (QMouseEvent*)event; switch (event->type()) { case QEvent::MouseMove: { bool mouseInWidget = widget()->rect().contains(mouseEvent->pos()); if (mouseInWidget) { if (_timerId) killTimer(_timerId); _timerId = 0; } else { if (!_timerId && (mouseEvent->buttons() & Qt::LeftButton)) _timerId = startTimer(100); } break; } case QEvent::MouseButtonRelease: if (_timerId && (mouseEvent->buttons() & ~Qt::LeftButton)) { killTimer(_timerId); _timerId = 0; } break; default: break; }; return false; } //#include "TerminalDisplay.moc" deepin-terminal-5.2.11/3rdparty/terminalwidget/lib/TerminalDisplay.h000066400000000000000000000722011370157770500255020ustar00rootroot00000000000000/* 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 "Filter.h" #include "Character.h" #include "qtermwidget.h" //#include "konsole_export.h" #include "tools.h" #define KONSOLEPRIVATE_EXPORT class QDrag; class QDragEnterEvent; class QDropEvent; class QLabel; class QTimer; class QEvent; class QGridLayout; class QKeyEvent; class QScrollBar; class QShowEvent; class QHideEvent; class QTimerEvent; class QWidget; //class KMenu; namespace Konsole { enum MotionAfterPasting { // No move screenwindow after pasting NoMoveScreenWindow = 0, // Move start of screenwindow after pasting MoveStartScreenWindow = 1, // Move end of screenwindow after pasting MoveEndScreenWindow = 2 }; extern unsigned short vt100_graphics[32]; class ScreenWindow; /** * 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. */ TerminalDisplay(QWidget *parent=nullptr); ~TerminalDisplay() override; /** 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 seed); /** * 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 image of the terminal display. */ void setBackgroundImage(QString backgroundImage); /** * 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(QTermWidget::ScrollBarPosition position); /** * Sets the current position and range of the display's scroll bar. * * @param cursor The position of the scroll bar's thumb. * @param lines The maximum value of the scroll bar. */ void setScroll(int cursor, int lines); /** * Scroll to the bottom of the terminal (reset scrolling). */ void scrollToEnd(); /** * 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); /** Returns true if the cursor is set to blink or false otherwise. */ bool blinkingCursor() { return _hasBlinkingCursor; } /** Specifies whether or not the cursor blinks. */ void setBlinkingCursor(bool blink); /** Specifies whether or not text can blink. */ void setBlinkingTextEnabled(bool blink); void setCtrlDrag(bool enable) { _ctrlDrag=enable; } bool ctrlDrag() { return _ctrlDrag; } /** * This enum describes the methods for selecting text when * the user triple-clicks within the display. */ enum TripleClickMode { /** Select the whole line underneath the cursor. */ SelectWholeLine, /** Select from the current cursor position to the end of the line. */ SelectForwardsFromCursor }; /** Sets how the text is selected when the user triple clicks within the display. */ void setTripleClickMode(TripleClickMode mode) { _tripleClickMode = mode; } /** See setTripleClickSelectionMode() */ TripleClickMode tripleClickMode() { return _tripleClickMode; } void setLineSpacing(uint); void setMargin(int); int margin() const; uint lineSpacing() const; void emitSelection(bool useXselection,bool appendReturn); /** change and wrap text corresponding to paste mode **/ void bracketText(QString& text); /** * 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(QTermWidget::KeyboardCursorShape shape); /** * Returns the shape of the keyboard cursor. See setKeyboardCursorShape() */ QTermWidget::KeyboardCursorShape keyboardCursorShape() const; /** * Sets the color used to draw the keyboard cursor. * * The keyboard cursor defaults to using the foreground color of the character * underneath it. * * @param useForegroundColor If true, the cursor color will change to match * the foreground color of the character underneath it as it is moved, in this * case, the @p color parameter is ignored and the color of the character * under the cursor is inverted to ensure that it is still readable. * @param color The color to use to draw the cursor. This is only taken into * account if @p useForegroundColor is false. */ void setKeyboardCursorColor(bool useForegroundColor , 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() { 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() { return _columns; } /** * Returns the height of the characters in the font used to draw the text in the display. */ int fontHeight() { return _fontHeight; } /** * Returns the width of the characters in the display. * This assumes the use of a fixed-width font. */ int fontWidth() { return _fontWidth; } void setSize(int cols, int lins); void setFixedSize(int cols, int lins); // reimplemented 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); /** * Returns the characters which are considered part of a word for the * purpose of selecting words in the display with the mouse. * * @see setWordCharacters() */ QString wordCharacters() { return _wordCharacters; } /** * 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() { return _bellMode; } /** * This enum describes the different types of sounds and visual effects which * can be used to alert the user when a 'bell' occurs in the terminal * session. */ enum BellMode { /** A system beep. */ SystemBeepBell=0, /** * KDE notification. This may play a sound, show a passive popup * or perform some other action depending on the user's settings. */ NotifyBell=1, /** A silent, visual bell (eg. inverting the display's colors briefly) */ VisualBell=2, /** No bell effects */ NoBell=3 }; void setSelection(const QString &t); void setSelectionAll(); /** * Reimplemented. Has no effect. Use setVTFont() to change the font * used to draw characters in the display. */ virtual void setFont(const QFont &); /** Returns the font used to draw characters in the display */ QFont getVTFont() { return font(); } /** * 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& font); /** * Specified whether anti-aliasing of text in the terminal display * is enabled or not. Defaults to enabled. */ static void setAntialias( bool antialias ) { _antialiasText = antialias; } /** * Returns true if anti-aliasing of text in the terminal is enabled. */ static bool antialias() { return _antialiasText; } /** * Specify whether line chars should be drawn by ourselves or left to * underlying font rendering libraries. */ void setDrawLineChars(bool drawLineChars) { _drawLineChars = drawLineChars; } /** * Specifies whether characters with intense colors should be rendered * as bold. Defaults to true. */ void setBoldIntense(bool value) { _boldIntense = value; } /** * Returns true if characters with intense colors are rendered in bold. */ bool getBoldIntense() { return _boldIntense; } /** * Sets whether or not the current height and width of the * terminal in lines and columns is displayed whilst the widget * is being resized. */ void setTerminalSizeHint(bool on) { _terminalSizeHint=on; } /** * Returns whether or not the current height and width of * the terminal in lines and columns is displayed whilst the widget * is being resized. */ bool terminalSizeHint() { return _terminalSizeHint; } /** * Sets whether the terminal size display is shown briefly * after the widget is first shown. * * See setTerminalSizeHint() , isTerminalSizeHint() */ void setTerminalSizeStartup(bool on) { _terminalSizeStartup=on; } /** * Sets the status of the BiDi rendering inside the terminal display. * Defaults to disabled. */ void setBidiEnabled(bool set) { _bidiEnabled=set; } /** * Returns the status of the BiDi rendering in this widget. */ bool isBidiEnabled() { return _bidiEnabled; } /** * 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; static bool HAVE_TRANSPARENCY; void setMotionAfterPasting(MotionAfterPasting action); int motionAfterPasting(); // maps a point on the widget to the position ( ie. line and column ) // of the character at that point. void getCharacterPosition(const QPoint& widgetPoint,int& line,int& column) const; void setHideCursor(bool hideCursor); void setSessionId(int sessionId); public slots: /** * Causes the terminal display to fetch the latest character image from the associated * terminal screen ( see setScreenWindow() ) and redraw the display. */ void updateImage(); /** Essentially calles processFilters(). */ void updateFilters(); /** * Causes the terminal display to fetch the latest line status flags from the * associated terminal screen ( see setScreenWindow() ). */ void updateLineProperties(); /** Copies the selected text to the clipboard. */ void copyClipboard(); /** * Pastes the content of the clipboard into the * display. */ void pasteClipboard(); /** * Pastes the content of the selection into the * display. */ void pasteSelection(); /** * Changes whether the flow control warning box should be shown when the flow control * stop key (Ctrl+S) are pressed. */ void setFlowControlWarningEnabled(bool enabled); /** * Returns true if the flow control warning box is enabled. * See outputSuspended() and setFlowControlWarningEnabled() */ bool flowControlWarningEnabled() const { return _flowControlWarningEnabled; } /** * 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 whoose output is being displayed in the view * is interested in mouse events. * * If this is set to true, mouse signals will be emitted by the view when the user clicks, drags * or otherwise moves the mouse inside the view. * The user interaction needed to create selections will also change, 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 usesMouse Set to true if the program running in the terminal is interested in mouse events * or false otherwise. */ void setUsesMouse(bool usesMouse); /** See setUsesMouse() */ bool usesMouse() const; void setBracketedPasteMode(bool bracketedPasteMode); bool bracketedPasteMode() const; /** * 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(), setForegroundColor() */ void setBackgroundColor(const QColor& color); /** * Sets the text of the display to the specified color. * @see setColorTable(), setBackgroundColor() */ void setForegroundColor(const QColor& color); void selectionChanged(); signals: /** * Emitted when the user presses a key whilst the terminal widget has focus. */ void keyPressedSignal(QKeyEvent *e); /** * 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 usesMouse() 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 isBusySelecting(bool); void sendStringToEmu(const char*); // qtermwidget signals void copyAvailable(bool); void termGetFocus(); void termLostFocus(); void leftMouseClick(); void notifyBell(const QString&); void usesMouseChanged(); protected: bool event( QEvent * ) override; void paintEvent( QPaintEvent * ) override; void showEvent(QShowEvent*) override; void hideEvent(QHideEvent*) override; void resizeEvent(QResizeEvent*) override; virtual void fontChange(const QFont &font); void focusInEvent(QFocusEvent* event) override; void focusOutEvent(QFocusEvent* event) override; void keyPressEvent(QKeyEvent* event) override; void mouseDoubleClickEvent(QMouseEvent* ev) override; void mousePressEvent( QMouseEvent* ) override; void mouseReleaseEvent( QMouseEvent* ) override; void mouseMoveEvent( QMouseEvent* ) override; virtual void extendSelection( const QPoint& pos ); void wheelEvent( QWheelEvent* ) override; bool focusNextPrevChild( bool next ) override; // drag and drop 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(QChar ch) const; void clearImage(); void mouseTripleClickEvent(QMouseEvent* ev); // reimplemented void inputMethodEvent ( QInputMethodEvent* event ) override; QVariant inputMethodQuery( Qt::InputMethodQuery query ) const override; protected slots: void scrollBarPositionChanged(int value); void blinkEvent(); void blinkCursorEvent(); //Renables bell noises and visuals. Used to disable further bells for a short period of time //after emitting the first in a sequence of bell events. void enableBell(); private slots: void swapColorTable(); void tripleClickTimeout(); // resets possibleTripleClick private: // -- Drawing helpers -- // determine the width of this text int textWidth(int startColumn, int length, int line) const; // determine the area that encloses this series of characters QRect calculateTextArea(int topLeftX, int topLeftY, int startColumn, int line, int length); // divides the part of the display specified by 'rect' into // fragments according to their colors and styles and calls // drawTextFragment() to draw the fragments void drawContents(QPainter &paint, const QRect &rect); // 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 std::wstring& 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& color, bool useOpacitySetting); // draws the cursor character void drawCursor(QPainter& painter, const QRect& rect , const QColor& foregroundColor, const QColor& backgroundColor , bool& invertColors); // draws the characters or line graphics in a text fragment void drawCharacters(QPainter& painter, const QRect& rect, const std::wstring& text, const Character* style, bool invertCharacterColor); // draws a string of line graphics void drawLineCharString(QPainter& painter, int x, int y, const std::wstring& 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; // 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& region); void calcGeometry(); void propagateSize(); void updateImageSize(); void makeImage(); void paintFilters(QPainter& painter); void calDrawTextAdditionHeight(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; // redraws the cursor void updateCursor(); bool handleShortcutOverrideEvent(QKeyEvent* event); bool isLineChar(wchar_t c) const; bool isLineCharString(const std::wstring& string) const; // the window onto the terminal screen which this display // is currently showing. QPointer _screenWindow; bool _allowBell; QGridLayout* _gridLayout; 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 _drawTextAdditionHeight; // additional height to prevent font trancation bool _drawTextTestFlag; // indicate it is a testing or not int _leftMargin; // offset int _topMargin; // offset 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 int _contentHeight; int _contentWidth; 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 _terminalSizeHint; bool _terminalSizeStartup; bool _bidiEnabled; bool _mouseMarks; 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; QClipboard* _clipboard; QScrollBar* _scrollBar; QTermWidget::ScrollBarPosition _scrollbarLocation; QString _wordCharacters; int _bellMode; bool _blinking; // hide text in paintEvent bool _hasBlinker; // has characters to blink bool _cursorBlinking; // hide cursor in paintEvent bool _hasBlinkingCursor; // has blinking cursor enabled bool _allowBlinkingText; // allow text to blink bool _ctrlDrag; // require Ctrl key for drag TripleClickMode _tripleClickMode; bool _isFixedSize; //Columns / lines are locked. QTimer* _blinkTimer; // active when hasBlinker QTimer* _blinkCursorTimer; // active when hasBlinkingCursor //QMenu* _drop; QString _dropText; int _dndFileCount; bool _possibleTripleClick; // is set in mouseDoubleClickEvent and deleted // after QApplication::doubleClickInterval() delay bool m_bUserIsResizing; //用于判断当前控件是否正在resize QLabel* _resizeWidget; QTimer* _resizeTimer; bool _flowControlWarningEnabled; bool _hideCursor; //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 QLabel* _outputSuspendedLabel; uint _lineSpacing; bool _colorsInverted; // true during visual bell QSize _size; QRgb _blendColor; QPixmap _backgroundImage; // list of filters currently applied to the display. used for links and // search highlight TerminalImageFilterChain* _filterChain; QRegion _mouseOverHotspotArea; QTermWidget::KeyboardCursorShape _cursorShape; // custom cursor color. if this is invalid then the foreground // color of the character under the cursor is used QColor _cursorColor; MotionAfterPasting mMotionAfterPasting; struct InputMethodData { std::wstring preeditString; QRect previousPreeditRect; }; InputMethodData _inputMethodData; static bool _antialiasText; // do we antialias or not //the delay in milliseconds between redrawing blinking text static const int TEXT_BLINK_DELAY = 500; int _leftBaseMargin; int _topBaseMargin; int _sessionId; bool _drawLineChars; TerminalHeaderBar *_headerBar; public: static void setTransparencyEnabled(bool enable) { HAVE_TRANSPARENCY = enable; } }; class AutoScrollHandler : public QObject { Q_OBJECT public: AutoScrollHandler(QWidget* parent); protected: 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 deepin-terminal-5.2.11/3rdparty/terminalwidget/lib/Vt102Emulation.cpp000066400000000000000000001647271370157770500254450ustar00rootroot00000000000000/* 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. */ // Own #include "Vt102Emulation.h" // XKB //#include // this allows konsole to be compiled without XKB and XTEST extensions // even though it might be available on a particular system. #if defined(AVOID_XKB) #undef HAVE_XKB #endif #if defined(HAVE_XKB) void scrolllock_set_off(); void scrolllock_set_on(); #endif // Standard #include #include // Qt #include #include #include // KDE //#include //#include // Konsole #include "KeyboardTranslator.h" #include "Screen.h" using namespace Konsole; Vt102Emulation::Vt102Emulation() : Emulation(), prevCC(0), _titleUpdateTimer(new QTimer(this)), _reportFocusEvents(false) { _titleUpdateTimer->setSingleShot(true); QObject::connect(_titleUpdateTimer , SIGNAL(timeout()) , this , SLOT(updateTitle())); initTokenizer(); reset(); } Vt102Emulation::~Vt102Emulation() {} void Vt102Emulation::clearEntireScreen() { _currentScreen->clearEntireScreen(); bufferedUpdate(); } void Vt102Emulation::reset() { resetTokenizer(); resetModes(); resetCharset(0); _screen[0]->reset(); resetCharset(1); _screen[1]->reset(); setCodec(LocaleCodec); bufferedUpdate(); } /* ------------------------------------------------------------------------- */ /* */ /* Processing the incoming byte stream */ /* */ /* ------------------------------------------------------------------------- */ /* Incoming Bytes Event pipeline This section deals with decoding the incoming character stream. Decoding means here, that the stream is first separated into `tokens' which are then mapped to a `meaning' provided as operations by the `Screen' class or by the emulation class itself. The pipeline proceeds as follows: - Tokenizing the ESC codes (onReceiveChar) - VT100 code page translation of plain characters (applyCharset) - Interpretation of ESC codes (processToken) The escape codes and their meaning are described in the technical reference of this program. */ // Tokens ------------------------------------------------------------------ -- /* Since the tokens are the central notion if this section, we've put them in front. They provide the syntactical elements used to represent the terminals operations as byte sequences. They are encodes here into a single machine word, so that we can later switch over them easily. Depending on the token itself, additional argument variables are filled with parameter values. The tokens are defined below: - CHR - Printable characters (32..255 but DEL (=127)) - CTL - Control characters (0..31 but ESC (= 27), DEL) - ESC - Escape codes of the form - ESC_DE - Escape codes of the form C - CSI_PN - Escape codes of the form '[' {Pn} ';' {Pn} C - CSI_PS - Escape codes of the form '[' {Pn} ';' ... C - CSI_PS_SP - Escape codes of the form '[' {Pn} ';' ... {Space} C - CSI_PR - Escape codes of the form '[' '?' {Pn} ';' ... C - CSI_PE - Escape codes of the form '[' '!' {Pn} ';' ... C - VT52 - VT52 escape codes - - 'Y'{Pc}{Pc} - XTE_HA - Xterm window/terminal attribute commands of the form `]' {Pn} `;' {Text} (Note that these are handled differently to the other formats) The last two forms allow list of arguments. Since the elements of the lists are treated individually the same way, they are passed as individual tokens to the interpretation. Further, because the meaning of the parameters are names (althought represented as numbers), they are includes within the token ('N'). */ #define TY_CONSTRUCT(T,A,N) ( (((static_cast(N)) & 0xffff) << 16) | (((static_cast(A)) & 0xff) << 8) | ((static_cast(T)) & 0xff) ) #define TY_CHR( ) TY_CONSTRUCT(0,0,0) #define TY_CTL(A ) TY_CONSTRUCT(1,A,0) #define TY_ESC(A ) TY_CONSTRUCT(2,A,0) #define TY_ESC_CS(A,B) TY_CONSTRUCT(3,A,B) #define TY_ESC_DE(A ) TY_CONSTRUCT(4,A,0) #define TY_CSI_PS(A,N) TY_CONSTRUCT(5,A,N) #define TY_CSI_PN(A ) TY_CONSTRUCT(6,A,0) #define TY_CSI_PR(A,N) TY_CONSTRUCT(7,A,N) #define TY_CSI_PS_SP(A,N) TY_CONSTRUCT(11,A,N) #define TY_VT52(A) TY_CONSTRUCT(8,A,0) #define TY_CSI_PG(A) TY_CONSTRUCT(9,A,0) #define TY_CSI_PE(A) TY_CONSTRUCT(10,A,0) #define MAX_ARGUMENT 4096 // Tokenizer --------------------------------------------------------------- -- /* The tokenizer's state The state is represented by the buffer (tokenBuffer, tokenBufferPos), and accompanied by decoded arguments kept in (argv,argc). Note that they are kept internal in the tokenizer. */ void Vt102Emulation::resetTokenizer() { tokenBufferPos = 0; argc = 0; argv[0] = 0; argv[1] = 0; prevCC = 0; } void Vt102Emulation::addDigit(int digit) { if (argv[argc] < MAX_ARGUMENT) argv[argc] = 10*argv[argc] + digit; } void Vt102Emulation::addArgument() { argc = qMin(argc+1,MAXARGS-1); argv[argc] = 0; } void Vt102Emulation::addToCurrentToken(wchar_t cc) { tokenBuffer[tokenBufferPos] = cc; tokenBufferPos = qMin(tokenBufferPos+1,MAX_TOKEN_LENGTH-1); } // Character Class flags used while decoding #define CTL 1 // Control character #define CHR 2 // Printable character #define CPN 4 // TODO: Document me #define DIG 8 // Digit #define SCS 16 // TODO: Document me #define GRP 32 // TODO: Document me #define CPS 64 // Character which indicates end of window resize // escape sequence '\e[8;;t' void Vt102Emulation::initTokenizer() { int i; const char* s; for(i = 0;i < 256; ++i) charClass[i] = 0; for(i = 0;i < 32; ++i) charClass[i] |= CTL; for(i = 32;i < 256; ++i) charClass[i] |= CHR; for(s = "@ABCDGHILMPSTXZbcdfry"; *s; ++s) charClass[static_cast(*s)] |= CPN; // resize = \e[8;;t for(s = "t"; *s; ++s) charClass[static_cast(*s)] |= CPS; for(s = "0123456789"; *s; ++s) charClass[static_cast(*s)] |= DIG; for(s = "()+*%"; *s; ++s) charClass[static_cast(*s)] |= SCS; for(s = "()+*#[]%"; *s; ++s) charClass[static_cast(*s)] |= GRP; resetTokenizer(); } /* Ok, here comes the nasty part of the decoder. Instead of keeping an explicit state, we deduce it from the token scanned so far. It is then immediately combined with the current character to form a scanning decision. This is done by the following defines. - P is the length of the token scanned so far. - L (often P-1) is the position on which contents we base a decision. - C is a character or a group of characters (taken from 'charClass'). - 'cc' is the current character - 's' is a pointer to the start of the token buffer - 'p' is the current position within the token buffer Note that they need to applied in proper order. */ #define lec(P,L,C) (p == (P) && s[(L)] == (C)) #define lun( ) (p == 1 && cc >= 32 ) #define les(P,L,C) (p == (P) && s[L] < 256 && (charClass[s[(L)]] & (C)) == (C)) #define eec(C) (p >= 3 && cc == (C)) #define ees(C) (p >= 3 && cc < 256 && (charClass[cc] & (C)) == (C)) #define eps(C) (p >= 3 && s[2] != '?' && s[2] != '!' && s[2] != '>' && cc < 256 && (charClass[cc] & (C)) == (C)) #define epp( ) (p >= 3 && s[2] == '?') #define epe( ) (p >= 3 && s[2] == '!') #define egt( ) (p >= 3 && s[2] == '>') #define esp( ) (p == 4 && s[3] == ' ') #define Xpe (tokenBufferPos >= 2 && tokenBuffer[1] == ']') #define Xte (Xpe && (cc == 7 || (prevCC == 27 && cc == 92) )) // 27, 92 => "\e\\" (ST, String Terminator) #define ces(C) (cc < 256 && (charClass[cc] & (C)) == (C) && !Xte) #define CNTL(c) ((c)-'@') #define ESC 27 #define DEL 127 // process an incoming unicode character void Vt102Emulation::receiveChar(wchar_t cc) { if (cc == DEL) return; //VT100: ignore. if (ces(CTL)) { // ignore control characters in the text part of Xpe (aka OSC) "ESC]" // escape sequences; this matches what XTERM docs say if (Xpe) { prevCC = cc; return; } // DEC HACK ALERT! Control Characters are allowed *within* esc sequences in VT100 // This means, they do neither a resetTokenizer() nor a pushToToken(). Some of them, do // of course. Guess this originates from a weakly layered handling of the X-on // X-off protocol, which comes really below this level. if (cc == CNTL('X') || cc == CNTL('Z') || cc == ESC) resetTokenizer(); //VT100: CAN or SUB if (cc != ESC) { processToken(TY_CTL(cc+'@' ),0,0); return; } } // advance the state addToCurrentToken(cc); wchar_t* s = tokenBuffer; int p = tokenBufferPos; if (getMode(MODE_Ansi)) { if (lec(1,0,ESC)) { return; } if (lec(1,0,ESC+128)) { s[0] = ESC; receiveChar('['); return; } if (les(2,1,GRP)) { return; } if (Xte ) { processWindowAttributeChange(); resetTokenizer(); return; } if (Xpe ) { prevCC = cc; return; } if (lec(3,2,'?')) { return; } if (lec(3,2,'>')) { return; } if (lec(3,2,'!')) { return; } if (lun( )) { processToken( TY_CHR(), applyCharset(cc), 0); resetTokenizer(); return; } if (lec(2,0,ESC)) { processToken( TY_ESC(s[1]), 0, 0); resetTokenizer(); return; } if (les(3,1,SCS)) { processToken( TY_ESC_CS(s[1],s[2]), 0, 0); resetTokenizer(); return; } if (lec(3,1,'#')) { processToken( TY_ESC_DE(s[2]), 0, 0); resetTokenizer(); return; } if (eps( CPN)) { processToken( TY_CSI_PN(cc), argv[0],argv[1]); resetTokenizer(); return; } if (esp( )) { return; } if (lec(5, 4, 'q') && s[3] == ' ') { processToken( TY_CSI_PS_SP(cc, argv[0]), argv[0], 0); resetTokenizer(); return; } // resize = \e[8;;t if (eps(CPS)) { processToken( TY_CSI_PS(cc, argv[0]), argv[1], argv[2]); resetTokenizer(); return; } if (epe( )) { processToken( TY_CSI_PE(cc), 0, 0); resetTokenizer(); return; } if (ees(DIG)) { addDigit(cc-'0'); return; } if (eec(';') || eec(':')) { addArgument(); return; } for (int i=0;i<=argc;i++) { if (epp()) processToken( TY_CSI_PR(cc,argv[i]), 0, 0); else if (egt()) processToken( TY_CSI_PG(cc), 0, 0); // spec. case for ESC]>0c or ESC]>c else if (cc == 'm' && argc - i >= 4 && (argv[i] == 38 || argv[i] == 48) && argv[i+1] == 2) { // ESC[ ... 48;2;;; ... m -or- ESC[ ... 38;2;;; ... m i += 2; processToken( TY_CSI_PS(cc, argv[i-2]), COLOR_SPACE_RGB, (argv[i] << 16) | (argv[i+1] << 8) | argv[i+2]); i += 2; } else if (cc == 'm' && argc - i >= 2 && (argv[i] == 38 || argv[i] == 48) && argv[i+1] == 5) { // ESC[ ... 48;5; ... m -or- ESC[ ... 38;5; ... m i += 2; processToken( TY_CSI_PS(cc, argv[i-2]), COLOR_SPACE_256, argv[i]); } else processToken( TY_CSI_PS(cc,argv[i]), 0, 0); } resetTokenizer(); } else { // VT52 Mode if (lec(1,0,ESC)) return; if (les(1,0,CHR)) { processToken( TY_CHR(), s[0], 0); resetTokenizer(); return; } if (lec(2,1,'Y')) return; if (lec(3,1,'Y')) return; if (p < 4) { processToken( TY_VT52(s[1] ), 0, 0); resetTokenizer(); return; } processToken( TY_VT52(s[1]), s[2], s[3]); resetTokenizer(); return; } } void Vt102Emulation::processWindowAttributeChange() { // Describes the window or terminal session attribute to change // See Session::UserTitleChange for possible values int attributeToChange = 0; int i; for (i = 2; i < tokenBufferPos && tokenBuffer[i] >= '0' && tokenBuffer[i] <= '9'; i++) { attributeToChange = 10 * attributeToChange + (tokenBuffer[i]-'0'); } if (tokenBuffer[i] != ';') { reportDecodingError(); return; } // copy from the first char after ';', and skipping the ending delimiter // 0x07 or 0x92. Note that as control characters in OSC text parts are // ignored, only the second char in ST ("\e\\") is appended to tokenBuffer. QString newValue = QString::fromWCharArray(tokenBuffer + i + 1, tokenBufferPos-i-2); _pendingTitleUpdates[attributeToChange] = newValue; _titleUpdateTimer->start(20); } void Vt102Emulation::updateTitle() { QListIterator iter( _pendingTitleUpdates.keys() ); while (iter.hasNext()) { int arg = iter.next(); emit titleChanged( arg , _pendingTitleUpdates[arg] ); } _pendingTitleUpdates.clear(); } // Interpreting Codes --------------------------------------------------------- /* Now that the incoming character stream is properly tokenized, meaning is assigned to them. These are either operations of the current _screen, or of the emulation class itself. The token to be interpreteted comes in as a machine word possibly accompanied by two parameters. Likewise, the operations assigned to, come with up to two arguments. One could consider to make up a proper table from the function below. The technical reference manual provides more information about this mapping. */ void Vt102Emulation::processToken(int token, wchar_t p, int q) { switch (token) { case TY_CHR( ) : _currentScreen->displayCharacter (p ); break; //UTF16 // 127 DEL : ignored on input case TY_CTL('@' ) : /* NUL: ignored */ break; case TY_CTL('A' ) : /* SOH: ignored */ break; case TY_CTL('B' ) : /* STX: ignored */ break; case TY_CTL('C' ) : /* ETX: ignored */ break; case TY_CTL('D' ) : /* EOT: ignored */ break; case TY_CTL('E' ) : reportAnswerBack ( ); break; //VT100 case TY_CTL('F' ) : /* ACK: ignored */ break; case TY_CTL('G' ) : emit stateSet(NOTIFYBELL); break; //VT100 case TY_CTL('H' ) : _currentScreen->backspace ( ); break; //VT100 case TY_CTL('I' ) : _currentScreen->tab ( ); break; //VT100 case TY_CTL('J' ) : _currentScreen->newLine ( ); break; //VT100 case TY_CTL('K' ) : _currentScreen->newLine ( ); break; //VT100 case TY_CTL('L' ) : _currentScreen->newLine ( ); break; //VT100 case TY_CTL('M' ) : _currentScreen->toStartOfLine ( ); break; //VT100 case TY_CTL('N' ) : useCharset ( 1); break; //VT100 case TY_CTL('O' ) : useCharset ( 0); break; //VT100 case TY_CTL('P' ) : /* DLE: ignored */ break; case TY_CTL('Q' ) : /* DC1: XON continue */ break; //VT100 case TY_CTL('R' ) : /* DC2: ignored */ break; case TY_CTL('S' ) : /* DC3: XOFF halt */ break; //VT100 case TY_CTL('T' ) : /* DC4: ignored */ break; case TY_CTL('U' ) : /* NAK: ignored */ break; case TY_CTL('V' ) : /* SYN: ignored */ break; case TY_CTL('W' ) : /* ETB: ignored */ break; case TY_CTL('X' ) : _currentScreen->displayCharacter ( 0x2592); break; //VT100 case TY_CTL('Y' ) : /* EM : ignored */ break; case TY_CTL('Z' ) : _currentScreen->displayCharacter ( 0x2592); break; //VT100 case TY_CTL('[' ) : /* ESC: cannot be seen here. */ break; case TY_CTL('\\' ) : /* FS : ignored */ break; case TY_CTL(']' ) : /* GS : ignored */ break; case TY_CTL('^' ) : /* RS : ignored */ break; case TY_CTL('_' ) : /* US : ignored */ break; case TY_ESC('D' ) : _currentScreen->index ( ); break; //VT100 case TY_ESC('E' ) : _currentScreen->nextLine ( ); break; //VT100 case TY_ESC('H' ) : _currentScreen->changeTabStop (true ); break; //VT100 case TY_ESC('M' ) : _currentScreen->reverseIndex ( ); break; //VT100 case TY_ESC('Z' ) : reportTerminalType ( ); break; case TY_ESC('c' ) : reset ( ); break; case TY_ESC('n' ) : useCharset ( 2); break; case TY_ESC('o' ) : useCharset ( 3); break; case TY_ESC('7' ) : saveCursor ( ); break; case TY_ESC('8' ) : restoreCursor ( ); break; case TY_ESC('=' ) : setMode (MODE_AppKeyPad); break; case TY_ESC('>' ) : resetMode (MODE_AppKeyPad); break; case TY_ESC('<' ) : setMode (MODE_Ansi ); break; //VT100 case TY_ESC_CS('(', '0') : setCharset (0, '0'); break; //VT100 case TY_ESC_CS('(', 'A') : setCharset (0, 'A'); break; //VT100 case TY_ESC_CS('(', 'B') : setCharset (0, 'B'); break; //VT100 case TY_ESC_CS(')', '0') : setCharset (1, '0'); break; //VT100 case TY_ESC_CS(')', 'A') : setCharset (1, 'A'); break; //VT100 case TY_ESC_CS(')', 'B') : setCharset (1, 'B'); break; //VT100 case TY_ESC_CS('*', '0') : setCharset (2, '0'); break; //VT100 case TY_ESC_CS('*', 'A') : setCharset (2, 'A'); break; //VT100 case TY_ESC_CS('*', 'B') : setCharset (2, 'B'); break; //VT100 case TY_ESC_CS('+', '0') : setCharset (3, '0'); break; //VT100 case TY_ESC_CS('+', 'A') : setCharset (3, 'A'); break; //VT100 case TY_ESC_CS('+', 'B') : setCharset (3, 'B'); break; //VT100 case TY_ESC_CS('%', 'G') : setCodec (Utf8Codec ); break; //LINUX case TY_ESC_CS('%', '@') : setCodec (LocaleCodec ); break; //LINUX case TY_ESC_DE('3' ) : /* Double height line, top half */ _currentScreen->setLineProperty( LINE_DOUBLEWIDTH , true ); _currentScreen->setLineProperty( LINE_DOUBLEHEIGHT , true ); break; case TY_ESC_DE('4' ) : /* Double height line, bottom half */ _currentScreen->setLineProperty( LINE_DOUBLEWIDTH , true ); _currentScreen->setLineProperty( LINE_DOUBLEHEIGHT , true ); break; case TY_ESC_DE('5' ) : /* Single width, single height line*/ _currentScreen->setLineProperty( LINE_DOUBLEWIDTH , false); _currentScreen->setLineProperty( LINE_DOUBLEHEIGHT , false); break; case TY_ESC_DE('6' ) : /* Double width, single height line*/ _currentScreen->setLineProperty( LINE_DOUBLEWIDTH , true); _currentScreen->setLineProperty( LINE_DOUBLEHEIGHT , false); break; case TY_ESC_DE('8' ) : _currentScreen->helpAlign ( ); break; // resize = \e[8;;t case TY_CSI_PS('t', 8) : setImageSize( p /*lines */, q /* columns */ ); emit imageResizeRequest(QSize(q, p)); break; // change tab text color : \e[28;t color: 0-16,777,215 case TY_CSI_PS('t', 28) : emit changeTabTextColorRequest ( p ); break; case TY_CSI_PS('K', 0) : _currentScreen->clearToEndOfLine ( ); break; case TY_CSI_PS('K', 1) : _currentScreen->clearToBeginOfLine ( ); break; case TY_CSI_PS('K', 2) : _currentScreen->clearEntireLine ( ); break; case TY_CSI_PS('J', 0) : _currentScreen->clearToEndOfScreen ( ); break; case TY_CSI_PS('J', 1) : _currentScreen->clearToBeginOfScreen ( ); break; case TY_CSI_PS('J', 2) : _currentScreen->clearEntireScreen ( ); break; case TY_CSI_PS('J', 3) : clearHistory(); break; case TY_CSI_PS('g', 0) : _currentScreen->changeTabStop (false ); break; //VT100 case TY_CSI_PS('g', 3) : _currentScreen->clearTabStops ( ); break; //VT100 case TY_CSI_PS('h', 4) : _currentScreen-> setMode (MODE_Insert ); break; case TY_CSI_PS('h', 20) : setMode (MODE_NewLine ); break; case TY_CSI_PS('i', 0) : /* IGNORE: attached printer */ break; //VT100 case TY_CSI_PS('l', 4) : _currentScreen-> resetMode (MODE_Insert ); break; case TY_CSI_PS('l', 20) : resetMode (MODE_NewLine ); break; case TY_CSI_PS('s', 0) : saveCursor ( ); break; case TY_CSI_PS('u', 0) : restoreCursor ( ); break; case TY_CSI_PS('m', 0) : _currentScreen->setDefaultRendition ( ); break; case TY_CSI_PS('m', 1) : _currentScreen-> setRendition (RE_BOLD ); break; //VT100 case TY_CSI_PS('m', 2) : _currentScreen-> setRendition (RE_FAINT ); break; case TY_CSI_PS('m', 3) : _currentScreen-> setRendition (RE_ITALIC ); break; //VT100 case TY_CSI_PS('m', 4) : _currentScreen-> setRendition (RE_UNDERLINE); break; //VT100 case TY_CSI_PS('m', 5) : _currentScreen-> setRendition (RE_BLINK ); break; //VT100 case TY_CSI_PS('m', 7) : _currentScreen-> setRendition (RE_REVERSE ); break; case TY_CSI_PS('m', 8) : _currentScreen-> setRendition (RE_CONCEAL ); break; case TY_CSI_PS('m', 9) : _currentScreen-> setRendition (RE_STRIKEOUT); break; case TY_CSI_PS('m', 53) : _currentScreen-> setRendition (RE_OVERLINE ); break; case TY_CSI_PS('m', 10) : /* IGNORED: mapping related */ break; //LINUX case TY_CSI_PS('m', 11) : /* IGNORED: mapping related */ break; //LINUX case TY_CSI_PS('m', 12) : /* IGNORED: mapping related */ break; //LINUX case TY_CSI_PS('m', 21) : _currentScreen->resetRendition (RE_BOLD ); break; case TY_CSI_PS('m', 22) : _currentScreen->resetRendition (RE_BOLD ); _currentScreen->resetRendition (RE_FAINT ); break; case TY_CSI_PS('m', 23) : _currentScreen->resetRendition (RE_ITALIC ); break; //VT100 case TY_CSI_PS('m', 24) : _currentScreen->resetRendition (RE_UNDERLINE); break; case TY_CSI_PS('m', 25) : _currentScreen->resetRendition (RE_BLINK ); break; case TY_CSI_PS('m', 27) : _currentScreen->resetRendition (RE_REVERSE ); break; case TY_CSI_PS('m', 28) : _currentScreen->resetRendition (RE_CONCEAL ); break; case TY_CSI_PS('m', 29) : _currentScreen->resetRendition (RE_STRIKEOUT); break; case TY_CSI_PS('m', 55) : _currentScreen->resetRendition (RE_OVERLINE ); break; case TY_CSI_PS('m', 30) : _currentScreen->setForeColor (COLOR_SPACE_SYSTEM, 0); break; case TY_CSI_PS('m', 31) : _currentScreen->setForeColor (COLOR_SPACE_SYSTEM, 1); break; case TY_CSI_PS('m', 32) : _currentScreen->setForeColor (COLOR_SPACE_SYSTEM, 2); break; case TY_CSI_PS('m', 33) : _currentScreen->setForeColor (COLOR_SPACE_SYSTEM, 3); break; case TY_CSI_PS('m', 34) : _currentScreen->setForeColor (COLOR_SPACE_SYSTEM, 4); break; case TY_CSI_PS('m', 35) : _currentScreen->setForeColor (COLOR_SPACE_SYSTEM, 5); break; case TY_CSI_PS('m', 36) : _currentScreen->setForeColor (COLOR_SPACE_SYSTEM, 6); break; case TY_CSI_PS('m', 37) : _currentScreen->setForeColor (COLOR_SPACE_SYSTEM, 7); break; case TY_CSI_PS('m', 38) : _currentScreen->setForeColor (p, q); break; case TY_CSI_PS('m', 39) : _currentScreen->setForeColor (COLOR_SPACE_DEFAULT, 0); break; case TY_CSI_PS('m', 40) : _currentScreen->setBackColor (COLOR_SPACE_SYSTEM, 0); break; case TY_CSI_PS('m', 41) : _currentScreen->setBackColor (COLOR_SPACE_SYSTEM, 1); break; case TY_CSI_PS('m', 42) : _currentScreen->setBackColor (COLOR_SPACE_SYSTEM, 2); break; case TY_CSI_PS('m', 43) : _currentScreen->setBackColor (COLOR_SPACE_SYSTEM, 3); break; case TY_CSI_PS('m', 44) : _currentScreen->setBackColor (COLOR_SPACE_SYSTEM, 4); break; case TY_CSI_PS('m', 45) : _currentScreen->setBackColor (COLOR_SPACE_SYSTEM, 5); break; case TY_CSI_PS('m', 46) : _currentScreen->setBackColor (COLOR_SPACE_SYSTEM, 6); break; case TY_CSI_PS('m', 47) : _currentScreen->setBackColor (COLOR_SPACE_SYSTEM, 7); break; case TY_CSI_PS('m', 48) : _currentScreen->setBackColor (p, q); break; case TY_CSI_PS('m', 49) : _currentScreen->setBackColor (COLOR_SPACE_DEFAULT, 1); break; case TY_CSI_PS('m', 90) : _currentScreen->setForeColor (COLOR_SPACE_SYSTEM, 8); break; case TY_CSI_PS('m', 91) : _currentScreen->setForeColor (COLOR_SPACE_SYSTEM, 9); break; case TY_CSI_PS('m', 92) : _currentScreen->setForeColor (COLOR_SPACE_SYSTEM, 10); break; case TY_CSI_PS('m', 93) : _currentScreen->setForeColor (COLOR_SPACE_SYSTEM, 11); break; case TY_CSI_PS('m', 94) : _currentScreen->setForeColor (COLOR_SPACE_SYSTEM, 12); break; case TY_CSI_PS('m', 95) : _currentScreen->setForeColor (COLOR_SPACE_SYSTEM, 13); break; case TY_CSI_PS('m', 96) : _currentScreen->setForeColor (COLOR_SPACE_SYSTEM, 14); break; case TY_CSI_PS('m', 97) : _currentScreen->setForeColor (COLOR_SPACE_SYSTEM, 15); break; case TY_CSI_PS('m', 100) : _currentScreen->setBackColor (COLOR_SPACE_SYSTEM, 8); break; case TY_CSI_PS('m', 101) : _currentScreen->setBackColor (COLOR_SPACE_SYSTEM, 9); break; case TY_CSI_PS('m', 102) : _currentScreen->setBackColor (COLOR_SPACE_SYSTEM, 10); break; case TY_CSI_PS('m', 103) : _currentScreen->setBackColor (COLOR_SPACE_SYSTEM, 11); break; case TY_CSI_PS('m', 104) : _currentScreen->setBackColor (COLOR_SPACE_SYSTEM, 12); break; case TY_CSI_PS('m', 105) : _currentScreen->setBackColor (COLOR_SPACE_SYSTEM, 13); break; case TY_CSI_PS('m', 106) : _currentScreen->setBackColor (COLOR_SPACE_SYSTEM, 14); break; case TY_CSI_PS('m', 107) : _currentScreen->setBackColor (COLOR_SPACE_SYSTEM, 15); break; case TY_CSI_PS('n', 5) : reportStatus ( ); break; case TY_CSI_PS('n', 6) : reportCursorPosition ( ); break; case TY_CSI_PS('q', 0) : /* IGNORED: LEDs off */ break; //VT100 case TY_CSI_PS('q', 1) : /* IGNORED: LED1 on */ break; //VT100 case TY_CSI_PS('q', 2) : /* IGNORED: LED2 on */ break; //VT100 case TY_CSI_PS('q', 3) : /* IGNORED: LED3 on */ break; //VT100 case TY_CSI_PS('q', 4) : /* IGNORED: LED4 on */ break; //VT100 case TY_CSI_PS('x', 0) : reportTerminalParms ( 2); break; //VT100 case TY_CSI_PS('x', 1) : reportTerminalParms ( 3); break; //VT100 case TY_CSI_PS_SP('q', 0) : /* fall through */ case TY_CSI_PS_SP('q', 1) : emit cursorChanged(KeyboardCursorShape::BlockCursor, true ); break; case TY_CSI_PS_SP('q', 2) : emit cursorChanged(KeyboardCursorShape::BlockCursor, false); break; case TY_CSI_PS_SP('q', 3) : emit cursorChanged(KeyboardCursorShape::UnderlineCursor, true ); break; case TY_CSI_PS_SP('q', 4) : emit cursorChanged(KeyboardCursorShape::UnderlineCursor, false); break; case TY_CSI_PS_SP('q', 5) : emit cursorChanged(KeyboardCursorShape::IBeamCursor, true ); break; case TY_CSI_PS_SP('q', 6) : emit cursorChanged(KeyboardCursorShape::IBeamCursor, false); break; case TY_CSI_PN('@' ) : _currentScreen->insertChars (p ); break; case TY_CSI_PN('A' ) : _currentScreen->cursorUp (p ); break; //VT100 case TY_CSI_PN('B' ) : _currentScreen->cursorDown (p ); break; //VT100 case TY_CSI_PN('C' ) : _currentScreen->cursorRight (p ); break; //VT100 case TY_CSI_PN('D' ) : _currentScreen->cursorLeft (p ); break; //VT100 case TY_CSI_PN('E' ) : /* Not implemented: cursor next p lines */ break; //VT100 case TY_CSI_PN('F' ) : /* Not implemented: cursor preceding p lines */ break; //VT100 case TY_CSI_PN('G' ) : _currentScreen->setCursorX (p ); break; //LINUX case TY_CSI_PN('H' ) : _currentScreen->setCursorYX (p, q); break; //VT100 case TY_CSI_PN('I' ) : _currentScreen->tab (p ); break; case TY_CSI_PN('L' ) : _currentScreen->insertLines (p ); break; case TY_CSI_PN('M' ) : _currentScreen->deleteLines (p ); break; case TY_CSI_PN('P' ) : _currentScreen->deleteChars (p ); break; case TY_CSI_PN('S' ) : _currentScreen->scrollUp (p ); break; case TY_CSI_PN('T' ) : _currentScreen->scrollDown (p ); break; case TY_CSI_PN('X' ) : _currentScreen->eraseChars (p ); break; case TY_CSI_PN('Z' ) : _currentScreen->backtab (p ); break; case TY_CSI_PN('b' ) : _currentScreen->repeatChars (p ); break; case TY_CSI_PN('c' ) : reportTerminalType ( ); break; //VT100 case TY_CSI_PN('d' ) : _currentScreen->setCursorY (p ); break; //LINUX case TY_CSI_PN('f' ) : _currentScreen->setCursorYX (p, q); break; //VT100 case TY_CSI_PN('r' ) : setMargins (p, q); break; //VT100 case TY_CSI_PN('y' ) : /* IGNORED: Confidence test */ break; //VT100 case TY_CSI_PR('h', 1) : setMode (MODE_AppCuKeys); break; //VT100 case TY_CSI_PR('l', 1) : resetMode (MODE_AppCuKeys); break; //VT100 case TY_CSI_PR('s', 1) : saveMode (MODE_AppCuKeys); break; //FIXME case TY_CSI_PR('r', 1) : restoreMode (MODE_AppCuKeys); break; //FIXME case TY_CSI_PR('l', 2) : resetMode (MODE_Ansi ); break; //VT100 case TY_CSI_PR('h', 3) : setMode (MODE_132Columns);break; //VT100 case TY_CSI_PR('l', 3) : resetMode (MODE_132Columns);break; //VT100 case TY_CSI_PR('h', 4) : /* IGNORED: soft scrolling */ break; //VT100 case TY_CSI_PR('l', 4) : /* IGNORED: soft scrolling */ break; //VT100 case TY_CSI_PR('h', 5) : _currentScreen-> setMode (MODE_Screen ); break; //VT100 case TY_CSI_PR('l', 5) : _currentScreen-> resetMode (MODE_Screen ); break; //VT100 case TY_CSI_PR('h', 6) : _currentScreen-> setMode (MODE_Origin ); break; //VT100 case TY_CSI_PR('l', 6) : _currentScreen-> resetMode (MODE_Origin ); break; //VT100 case TY_CSI_PR('s', 6) : _currentScreen-> saveMode (MODE_Origin ); break; //FIXME case TY_CSI_PR('r', 6) : _currentScreen->restoreMode (MODE_Origin ); break; //FIXME case TY_CSI_PR('h', 7) : _currentScreen-> setMode (MODE_Wrap ); break; //VT100 case TY_CSI_PR('l', 7) : _currentScreen-> resetMode (MODE_Wrap ); break; //VT100 case TY_CSI_PR('s', 7) : _currentScreen-> saveMode (MODE_Wrap ); break; //FIXME case TY_CSI_PR('r', 7) : _currentScreen->restoreMode (MODE_Wrap ); break; //FIXME case TY_CSI_PR('h', 8) : /* IGNORED: autorepeat on */ break; //VT100 case TY_CSI_PR('l', 8) : /* IGNORED: autorepeat off */ break; //VT100 case TY_CSI_PR('s', 8) : /* IGNORED: autorepeat on */ break; //VT100 case TY_CSI_PR('r', 8) : /* IGNORED: autorepeat off */ break; //VT100 case TY_CSI_PR('h', 9) : /* IGNORED: interlace */ break; //VT100 case TY_CSI_PR('l', 9) : /* IGNORED: interlace */ break; //VT100 case TY_CSI_PR('s', 9) : /* IGNORED: interlace */ break; //VT100 case TY_CSI_PR('r', 9) : /* IGNORED: interlace */ break; //VT100 case TY_CSI_PR('h', 12) : /* IGNORED: Cursor blink */ break; //att610 case TY_CSI_PR('l', 12) : /* IGNORED: Cursor blink */ break; //att610 case TY_CSI_PR('s', 12) : /* IGNORED: Cursor blink */ break; //att610 case TY_CSI_PR('r', 12) : /* IGNORED: Cursor blink */ break; //att610 case TY_CSI_PR('h', 25) : setMode (MODE_Cursor ); break; //VT100 case TY_CSI_PR('l', 25) : resetMode (MODE_Cursor ); break; //VT100 case TY_CSI_PR('s', 25) : saveMode (MODE_Cursor ); break; //VT100 case TY_CSI_PR('r', 25) : restoreMode (MODE_Cursor ); break; //VT100 case TY_CSI_PR('h', 40) : setMode(MODE_Allow132Columns ); break; // XTERM case TY_CSI_PR('l', 40) : resetMode(MODE_Allow132Columns ); break; // XTERM case TY_CSI_PR('h', 41) : /* IGNORED: obsolete more(1) fix */ break; //XTERM case TY_CSI_PR('l', 41) : /* IGNORED: obsolete more(1) fix */ break; //XTERM case TY_CSI_PR('s', 41) : /* IGNORED: obsolete more(1) fix */ break; //XTERM case TY_CSI_PR('r', 41) : /* IGNORED: obsolete more(1) fix */ break; //XTERM case TY_CSI_PR('h', 47) : setMode (MODE_AppScreen); break; //VT100 case TY_CSI_PR('l', 47) : resetMode (MODE_AppScreen); break; //VT100 case TY_CSI_PR('s', 47) : saveMode (MODE_AppScreen); break; //XTERM case TY_CSI_PR('r', 47) : restoreMode (MODE_AppScreen); break; //XTERM case TY_CSI_PR('h', 67) : /* IGNORED: DECBKM */ break; //XTERM case TY_CSI_PR('l', 67) : /* IGNORED: DECBKM */ break; //XTERM case TY_CSI_PR('s', 67) : /* IGNORED: DECBKM */ break; //XTERM case TY_CSI_PR('r', 67) : /* IGNORED: DECBKM */ break; //XTERM // XTerm defines the following modes: // SET_VT200_MOUSE 1000 // SET_VT200_HIGHLIGHT_MOUSE 1001 // SET_BTN_EVENT_MOUSE 1002 // SET_ANY_EVENT_MOUSE 1003 // //Note about mouse modes: //There are four mouse modes which xterm-compatible terminals can support - 1000,1001,1002,1003 //Konsole currently supports mode 1000 (basic mouse press and release) and mode 1002 (dragging the mouse). //TODO: Implementation of mouse modes 1001 (something called hilight tracking) and //1003 (a slight variation on dragging the mouse) // case TY_CSI_PR('h', 1000) : setMode (MODE_Mouse1000); break; //XTERM case TY_CSI_PR('l', 1000) : resetMode (MODE_Mouse1000); break; //XTERM case TY_CSI_PR('s', 1000) : saveMode (MODE_Mouse1000); break; //XTERM case TY_CSI_PR('r', 1000) : restoreMode (MODE_Mouse1000); break; //XTERM case TY_CSI_PR('h', 1001) : /* IGNORED: hilite mouse tracking */ break; //XTERM case TY_CSI_PR('l', 1001) : resetMode (MODE_Mouse1001); break; //XTERM case TY_CSI_PR('s', 1001) : /* IGNORED: hilite mouse tracking */ break; //XTERM case TY_CSI_PR('r', 1001) : /* IGNORED: hilite mouse tracking */ break; //XTERM case TY_CSI_PR('h', 1002) : setMode (MODE_Mouse1002); break; //XTERM case TY_CSI_PR('l', 1002) : resetMode (MODE_Mouse1002); break; //XTERM case TY_CSI_PR('s', 1002) : saveMode (MODE_Mouse1002); break; //XTERM case TY_CSI_PR('r', 1002) : restoreMode (MODE_Mouse1002); break; //XTERM case TY_CSI_PR('h', 1003) : setMode (MODE_Mouse1003); break; //XTERM case TY_CSI_PR('l', 1003) : resetMode (MODE_Mouse1003); break; //XTERM case TY_CSI_PR('s', 1003) : saveMode (MODE_Mouse1003); break; //XTERM case TY_CSI_PR('r', 1003) : restoreMode (MODE_Mouse1003); break; //XTERM case TY_CSI_PR('h', 1004) : _reportFocusEvents = true; break; case TY_CSI_PR('l', 1004) : _reportFocusEvents = false; break; case TY_CSI_PR('h', 1005) : setMode (MODE_Mouse1005); break; //XTERM case TY_CSI_PR('l', 1005) : resetMode (MODE_Mouse1005); break; //XTERM case TY_CSI_PR('s', 1005) : saveMode (MODE_Mouse1005); break; //XTERM case TY_CSI_PR('r', 1005) : restoreMode (MODE_Mouse1005); break; //XTERM case TY_CSI_PR('h', 1006) : setMode (MODE_Mouse1006); break; //XTERM case TY_CSI_PR('l', 1006) : resetMode (MODE_Mouse1006); break; //XTERM case TY_CSI_PR('s', 1006) : saveMode (MODE_Mouse1006); break; //XTERM case TY_CSI_PR('r', 1006) : restoreMode (MODE_Mouse1006); break; //XTERM case TY_CSI_PR('h', 1015) : setMode (MODE_Mouse1015); break; //URXVT case TY_CSI_PR('l', 1015) : resetMode (MODE_Mouse1015); break; //URXVT case TY_CSI_PR('s', 1015) : saveMode (MODE_Mouse1015); break; //URXVT case TY_CSI_PR('r', 1015) : restoreMode (MODE_Mouse1015); break; //URXVT case TY_CSI_PR('h', 1034) : /* IGNORED: 8bitinput activation */ break; //XTERM case TY_CSI_PR('h', 1047) : setMode (MODE_AppScreen); break; //XTERM case TY_CSI_PR('l', 1047) : _screen[1]->clearEntireScreen(); resetMode(MODE_AppScreen); break; //XTERM case TY_CSI_PR('s', 1047) : saveMode (MODE_AppScreen); break; //XTERM case TY_CSI_PR('r', 1047) : restoreMode (MODE_AppScreen); break; //XTERM //FIXME: Unitoken: save translations case TY_CSI_PR('h', 1048) : saveCursor ( ); break; //XTERM case TY_CSI_PR('l', 1048) : restoreCursor ( ); break; //XTERM case TY_CSI_PR('s', 1048) : saveCursor ( ); break; //XTERM case TY_CSI_PR('r', 1048) : restoreCursor ( ); break; //XTERM //FIXME: every once new sequences like this pop up in xterm. // Here's a guess of what they could mean. case TY_CSI_PR('h', 1049) : saveCursor(); _screen[1]->clearEntireScreen(); setMode(MODE_AppScreen); break; //XTERM case TY_CSI_PR('l', 1049) : resetMode(MODE_AppScreen); restoreCursor(); break; //XTERM case TY_CSI_PR('h', 2004) : setMode (MODE_BracketedPaste); break; //XTERM case TY_CSI_PR('l', 2004) : resetMode (MODE_BracketedPaste); break; //XTERM case TY_CSI_PR('s', 2004) : saveMode (MODE_BracketedPaste); break; //XTERM case TY_CSI_PR('r', 2004) : restoreMode (MODE_BracketedPaste); break; //XTERM //FIXME: weird DEC reset sequence case TY_CSI_PE('p' ) : /* IGNORED: reset ( ) */ break; //FIXME: when changing between vt52 and ansi mode evtl do some resetting. case TY_VT52('A' ) : _currentScreen->cursorUp ( 1); break; //VT52 case TY_VT52('B' ) : _currentScreen->cursorDown ( 1); break; //VT52 case TY_VT52('C' ) : _currentScreen->cursorRight ( 1); break; //VT52 case TY_VT52('D' ) : _currentScreen->cursorLeft ( 1); break; //VT52 case TY_VT52('F' ) : setAndUseCharset (0, '0'); break; //VT52 case TY_VT52('G' ) : setAndUseCharset (0, 'B'); break; //VT52 case TY_VT52('H' ) : _currentScreen->setCursorYX (1,1 ); break; //VT52 case TY_VT52('I' ) : _currentScreen->reverseIndex ( ); break; //VT52 case TY_VT52('J' ) : _currentScreen->clearToEndOfScreen ( ); break; //VT52 case TY_VT52('K' ) : _currentScreen->clearToEndOfLine ( ); break; //VT52 case TY_VT52('Y' ) : _currentScreen->setCursorYX (p-31,q-31 ); break; //VT52 case TY_VT52('Z' ) : reportTerminalType ( ); break; //VT52 case TY_VT52('<' ) : setMode (MODE_Ansi ); break; //VT52 case TY_VT52('=' ) : setMode (MODE_AppKeyPad); break; //VT52 case TY_VT52('>' ) : resetMode (MODE_AppKeyPad); break; //VT52 case TY_CSI_PG('c' ) : reportSecondaryAttributes( ); break; //VT100 default: reportDecodingError(); break; }; } void Vt102Emulation::clearScreenAndSetColumns(int columnCount) { setImageSize(_currentScreen->getLines(),columnCount); clearEntireScreen(); setDefaultMargins(); _currentScreen->setCursorYX(0,0); } void Vt102Emulation::sendString(const char* s , int length) { if ( length >= 0 ) emit sendData(s,length); else emit sendData(s,static_cast(strlen(s))); } void Vt102Emulation::reportCursorPosition() { const int sz = 20; char tmp[sz]; const int r = snprintf(tmp, sz, "\033[%d;%dR",_currentScreen->getCursorY()+1,_currentScreen->getCursorX()+1); if (sz <= r) { qWarning("Vt102Emulation::reportCursorPosition: Buffer too small\n"); } sendString(tmp); } void Vt102Emulation::reportTerminalType() { // Primary device attribute response (Request was: ^[[0c or ^[[c (from TT321 Users Guide)) // VT220: ^[[?63;1;2;3;6;7;8c (list deps on emul. capabilities) // VT100: ^[[?1;2c // VT101: ^[[?1;0c // VT102: ^[[?6v if (getMode(MODE_Ansi)) sendString("\033[?1;2c"); // I'm a VT100 else sendString("\033/Z"); // I'm a VT52 } void Vt102Emulation::reportSecondaryAttributes() { // Seconday device attribute response (Request was: ^[[>0c or ^[[>c) if (getMode(MODE_Ansi)) sendString("\033[>0;115;0c"); // Why 115? ;) else sendString("\033/Z"); // FIXME I don't think VT52 knows about it but kept for // konsoles backward compatibility. } void Vt102Emulation::reportTerminalParms(int p) // DECREPTPARM { const int sz = 100; char tmp[sz]; const int r = snprintf(tmp, sz, "\033[%d;1;1;112;112;1;0x",p); // not really true. if (sz <= r) { qWarning("Vt102Emulation::reportTerminalParms: Buffer too small\n"); } sendString(tmp); } void Vt102Emulation::reportStatus() { sendString("\033[0n"); //VT100. Device status report. 0 = Ready. } void Vt102Emulation::reportAnswerBack() { // FIXME - Test this with VTTEST // This is really obsolete VT100 stuff. const char* ANSWER_BACK = ""; sendString(ANSWER_BACK); } /*! `cx',`cy' are 1-based. `cb' indicates the button pressed or released (0-2) or scroll event (4-5). eventType represents the kind of mouse action that occurred: 0 = Mouse button press 1 = Mouse drag 2 = Mouse button release */ void Vt102Emulation::sendMouseEvent( int cb, int cx, int cy , int eventType ) { if (cx < 1 || cy < 1) return; // With the exception of the 1006 mode, button release is encoded in cb. // Note that if multiple extensions are enabled, the 1006 is used, so it's okay to check for only that. if (eventType == 2 && !getMode(MODE_Mouse1006)) cb = 3; // normal buttons are passed as 0x20 + button, // mouse wheel (buttons 4,5) as 0x5c + button if (cb >= 4) cb += 0x3c; //Mouse motion handling if ((getMode(MODE_Mouse1002) || getMode(MODE_Mouse1003)) && eventType == 1) cb += 0x20; //add 32 to signify motion event char command[32]; command[0] = '\0'; // Check the extensions in decreasing order of preference. Encoding the release event above assumes that 1006 comes first. if (getMode(MODE_Mouse1006)) { snprintf(command, sizeof(command), "\033[<%d;%d;%d%c", cb, cx, cy, eventType == 2 ? 'm' : 'M'); } else if (getMode(MODE_Mouse1015)) { snprintf(command, sizeof(command), "\033[%d;%d;%dM", static_cast(cb) + 0x20, cx, cy); } else if (getMode(MODE_Mouse1005)) { if (cx <= 2015 && cy <= 2015) { // The xterm extension uses UTF-8 (up to 2 bytes) to encode // coordinate+32, no matter what the locale is. We could easily // convert manually, but QString can also do it for us. QChar coords[2]; coords[0] = cx + 0x20; coords[1] = cy + 0x20; QString coordsStr = QString(coords, 2); QByteArray utf8 = coordsStr.toUtf8(); snprintf(command, sizeof(command), "\033[M%c%s", cb + 0x20, utf8.constData()); } } else if (cx <= 223 && cy <= 223) { snprintf(command, sizeof(command), "\033[M%c%c%c", cb + 0x20, cx + 0x20, cy + 0x20); } sendString(command); } /** * The focus lost event can be used by Vim (or other terminal applications) * to recognize that the konsole window has lost focus. * The escape sequence is also used by iTerm2. * Vim needs the following plugin to be installed to convert the escape * sequence into the FocusLost autocmd: https://github.com/sjl/vitality.vim */ void Vt102Emulation::focusLost(void) { if (_reportFocusEvents) sendString("\033[O"); } /** * The focus gained event can be used by Vim (or other terminal applications) * to recognize that the konsole window has gained focus again. * The escape sequence is also used by iTerm2. * Vim needs the following plugin to be installed to convert the escape * sequence into the FocusGained autocmd: https://github.com/sjl/vitality.vim */ void Vt102Emulation::focusGained(void) { if (_reportFocusEvents) sendString("\033[I"); } void Vt102Emulation::sendText( const QString& text ) { if (!text.isEmpty()) { QKeyEvent event(QEvent::KeyPress, 0, Qt::NoModifier, text); sendKeyEvent(&event); // expose as a big fat keypress event } } void Vt102Emulation::sendKeyEvent( QKeyEvent* event ) { Qt::KeyboardModifiers modifiers = event->modifiers(); KeyboardTranslator::States states = KeyboardTranslator::NoState; // get current states if (getMode(MODE_NewLine) ) states |= KeyboardTranslator::NewLineState; if (getMode(MODE_Ansi) ) states |= KeyboardTranslator::AnsiState; if (getMode(MODE_AppCuKeys)) states |= KeyboardTranslator::CursorKeysState; if (getMode(MODE_AppScreen)) states |= KeyboardTranslator::AlternateScreenState; if (getMode(MODE_AppKeyPad) && (modifiers & Qt::KeypadModifier)) states |= KeyboardTranslator::ApplicationKeypadState; // check flow control state if (modifiers & KeyboardTranslator::CTRL_MOD) { switch (event->key()) { case Qt::Key_S: emit flowControlKeyPressed(true); break; case Qt::Key_Q: case Qt::Key_C: // cancel flow control emit flowControlKeyPressed(false); break; } } // lookup key binding if ( _keyTranslator ) { KeyboardTranslator::Entry entry = _keyTranslator->findEntry( event->key() , modifiers, states ); // send result to terminal QByteArray textToSend; // special handling for the Alt (aka. Meta) modifier. pressing // Alt+[Character] results in Esc+[Character] being sent // (unless there is an entry defined for this particular combination // in the keyboard modifier) bool wantsAltModifier = entry.modifiers() & entry.modifierMask() & Qt::AltModifier; bool wantsMetaModifier = entry.modifiers() & entry.modifierMask() & Qt::MetaModifier; bool wantsAnyModifier = entry.state() & entry.stateMask() & KeyboardTranslator::AnyModifierState; if ( modifiers & Qt::AltModifier && !(wantsAltModifier || wantsAnyModifier) && !event->text().isEmpty() ) { textToSend.prepend("\033"); } if ( modifiers & Qt::MetaModifier && !(wantsMetaModifier || wantsAnyModifier) && !event->text().isEmpty() ) { textToSend.prepend("\030@s"); } if ( entry.command() != KeyboardTranslator::NoCommand ) { if (entry.command() & KeyboardTranslator::EraseCommand) textToSend += eraseChar(); // TODO command handling } else if ( !entry.text().isEmpty() ) { textToSend += _codec->fromUnicode(QString::fromUtf8(entry.text(true,modifiers))); } else if((modifiers & KeyboardTranslator::CTRL_MOD) && event->key() >= 0x40 && event->key() < 0x5f) { textToSend += (event->key() & 0x1f); } else if(event->key() == Qt::Key_Tab) { textToSend += 0x09; } else if (event->key() == Qt::Key_PageUp) { textToSend += "\033[5~"; } else if (event->key() == Qt::Key_PageDown) { textToSend += "\033[6~"; } else { textToSend += _codec->fromUnicode(event->text()); } Q_EMIT sendData( textToSend.constData() , textToSend.length() ); } else { // print an error message to the terminal if no key translator has been // set QString translatorError = tr("No keyboard translator available. " "The information needed to convert key presses " "into characters to send to the terminal " "is missing."); reset(); receiveData( translatorError.toUtf8().constData() , translatorError.count() ); } } /* ------------------------------------------------------------------------- */ /* */ /* VT100 Charsets */ /* */ /* ------------------------------------------------------------------------- */ // Character Set Conversion ------------------------------------------------ -- /* The processing contains a VT100 specific code translation layer. It's still in use and mainly responsible for the line drawing graphics. These and some other glyphs are assigned to codes (0x5f-0xfe) normally occupied by the latin letters. Since this codes also appear within control sequences, the extra code conversion does not permute with the tokenizer and is placed behind it in the pipeline. It only applies to tokens, which represent plain characters. This conversion it eventually continued in TerminalDisplay.C, since it might involve VT100 enhanced fonts, which have these particular glyphs allocated in (0x00-0x1f) in their code page. */ #define CHARSET _charset[_currentScreen==_screen[1]] // Apply current character map. wchar_t Vt102Emulation::applyCharset(wchar_t c) { if (CHARSET.graphic && 0x5f <= c && c <= 0x7e) return vt100_graphics[c-0x5f]; if (CHARSET.pound && c == '#' ) return 0xa3; //This mode is obsolete return c; } /* "Charset" related part of the emulation state. This configures the VT100 charset filter. While most operation work on the current _screen, the following two are different. */ void Vt102Emulation::resetCharset(int scrno) { _charset[scrno].cu_cs = 0; qstrncpy(_charset[scrno].charset,"BBBB",4); _charset[scrno].sa_graphic = false; _charset[scrno].sa_pound = false; _charset[scrno].graphic = false; _charset[scrno].pound = false; } void Vt102Emulation::setCharset(int n, int cs) // on both screens. { _charset[0].charset[n&3] = static_cast(cs); useCharset(_charset[0].cu_cs); _charset[1].charset[n&3] = static_cast(cs); useCharset(_charset[1].cu_cs); } void Vt102Emulation::setAndUseCharset(int n, int cs) { CHARSET.charset[n&3] = static_cast(cs); useCharset(n&3); } void Vt102Emulation::useCharset(int n) { CHARSET.cu_cs = n&3; CHARSET.graphic = (CHARSET.charset[n&3] == '0'); CHARSET.pound = (CHARSET.charset[n&3] == 'A'); //This mode is obsolete } void Vt102Emulation::setDefaultMargins() { _screen[0]->setDefaultMargins(); _screen[1]->setDefaultMargins(); } void Vt102Emulation::setMargins(int t, int b) { _screen[0]->setMargins(t, b); _screen[1]->setMargins(t, b); } void Vt102Emulation::saveCursor() { CHARSET.sa_graphic = CHARSET.graphic; CHARSET.sa_pound = CHARSET.pound; //This mode is obsolete // we are not clear about these //sa_charset = charsets[cScreen->_charset]; //sa_charset_num = cScreen->_charset; _currentScreen->saveCursor(); } void Vt102Emulation::restoreCursor() { CHARSET.graphic = CHARSET.sa_graphic; CHARSET.pound = CHARSET.sa_pound; //This mode is obsolete _currentScreen->restoreCursor(); } /* ------------------------------------------------------------------------- */ /* */ /* Mode Operations */ /* */ /* ------------------------------------------------------------------------- */ /* Some of the emulations state is either added to the state of the screens. This causes some scoping problems, since different emulations choose to located the mode either to the current _screen or to both. For strange reasons, the extend of the rendition attributes ranges over all screens and not over the actual _screen. We decided on the precise precise extend, somehow. */ // "Mode" related part of the state. These are all booleans. void Vt102Emulation::resetModes() { // MODE_Allow132Columns is not reset here // to match Xterm's behaviour (see Xterm's VTReset() function) resetMode(MODE_132Columns); saveMode(MODE_132Columns); resetMode(MODE_Mouse1000); saveMode(MODE_Mouse1000); resetMode(MODE_Mouse1001); saveMode(MODE_Mouse1001); resetMode(MODE_Mouse1002); saveMode(MODE_Mouse1002); resetMode(MODE_Mouse1003); saveMode(MODE_Mouse1003); resetMode(MODE_Mouse1005); saveMode(MODE_Mouse1005); resetMode(MODE_Mouse1006); saveMode(MODE_Mouse1006); resetMode(MODE_Mouse1015); saveMode(MODE_Mouse1015); resetMode(MODE_BracketedPaste); saveMode(MODE_BracketedPaste); resetMode(MODE_AppScreen); saveMode(MODE_AppScreen); resetMode(MODE_AppCuKeys); saveMode(MODE_AppCuKeys); resetMode(MODE_AppKeyPad); saveMode(MODE_AppKeyPad); resetMode(MODE_NewLine); setMode(MODE_Ansi); } void Vt102Emulation::setMode(int m) { _currentModes.mode[m] = true; switch (m) { case MODE_132Columns: if (getMode(MODE_Allow132Columns)) clearScreenAndSetColumns(132); else _currentModes.mode[m] = false; break; case MODE_Mouse1000: case MODE_Mouse1001: case MODE_Mouse1002: case MODE_Mouse1003: emit programUsesMouseChanged(false); break; case MODE_BracketedPaste: emit programBracketedPasteModeChanged(true); break; case MODE_AppScreen : _screen[1]->clearSelection(); setScreen(1); break; } if (m < MODES_SCREEN || m == MODE_NewLine) { _screen[0]->setMode(m); _screen[1]->setMode(m); } } void Vt102Emulation::resetMode(int m) { _currentModes.mode[m] = false; switch (m) { case MODE_132Columns: if (getMode(MODE_Allow132Columns)) clearScreenAndSetColumns(80); break; case MODE_Mouse1000 : case MODE_Mouse1001 : case MODE_Mouse1002 : case MODE_Mouse1003 : emit programUsesMouseChanged(true); break; case MODE_BracketedPaste: emit programBracketedPasteModeChanged(false); break; case MODE_AppScreen : _screen[0]->clearSelection(); setScreen(0); break; } if (m < MODES_SCREEN || m == MODE_NewLine) { _screen[0]->resetMode(m); _screen[1]->resetMode(m); } } void Vt102Emulation::saveMode(int m) { _savedModes.mode[m] = _currentModes.mode[m]; } void Vt102Emulation::restoreMode(int m) { if (_savedModes.mode[m]) setMode(m); else resetMode(m); } bool Vt102Emulation::getMode(int m) { return _currentModes.mode[m]; } char Vt102Emulation::eraseChar() const { KeyboardTranslator::Entry entry = _keyTranslator->findEntry( Qt::Key_Backspace, Qt::NoModifier, KeyboardTranslator::NoState); if ( entry.text().count() > 0 ) return entry.text().at(0); else return '\b'; } // print contents of the scan buffer static void hexdump(wchar_t* s, int len) { int i; for (i = 0; i < len; i++) { if (s[i] == '\\') printf("\\\\"); else if ((s[i]) > 32 && s[i] < 127) printf("%c",s[i]); else printf("\\%04x(hex)",s[i]); } } void Vt102Emulation::reportDecodingError() { if (tokenBufferPos == 0 || ( tokenBufferPos == 1 && (tokenBuffer[0] & 0xff) >= 32) ) return; printf("Undecodable sequence: "); hexdump(tokenBuffer,tokenBufferPos); printf("\n"); } //#include "Vt102Emulation.moc" deepin-terminal-5.2.11/3rdparty/terminalwidget/lib/Vt102Emulation.h000066400000000000000000000142541370157770500250770ustar00rootroot00000000000000/* 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 // Standard Library #include // Qt #include #include #include // Konsole #include "Emulation.h" #include "Screen.h" #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_Mouse1015 (MODES_SCREEN+9) // Urxvt-style extended coordinates #define MODE_Ansi (MODES_SCREEN+10) // Use US Ascii for character sets G0-G3 (DECANM) #define MODE_132Columns (MODES_SCREEN+11) // 80 <-> 132 column mode switch (DECCOLM) #define MODE_Allow132Columns (MODES_SCREEN+12) // Allow DECCOLM mode #define MODE_BracketedPaste (MODES_SCREEN+13) // Xterm-style bracketed paste mode #define MODE_total (MODES_SCREEN+14) namespace Konsole { 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 http://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() override; // reimplemented from Emulation void clearEntireScreen() override; void reset() override; char eraseChar() const override; public slots: // reimplemented from Emulation void sendString(const char*,int length = -1) override; void sendText(const QString& text) override; void sendKeyEvent(QKeyEvent*) override; void sendMouseEvent(int buttons, int column, int line, int eventType) override; virtual void focusLost(); virtual void focusGained(); protected: // reimplemented from Emulation void setMode(int mode) override; void resetMode(int mode) override; void receiveChar(wchar_t cc) override; private slots: //causes changeTitle() to be emitted for each (int,QString) pair in pendingTitleUpdates //used to buffer multiple title updates void updateTitle(); private: wchar_t applyCharset(wchar_t 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(wchar_t cc); wchar_t tokenBuffer[MAX_TOKEN_LENGTH]; //FIXME: overflow? int tokenBufferPos; #define MAXARGS 15 void addDigit(int dig); void addArgument(); int argv[MAXARGS]; int argc; void initTokenizer(); int prevCC; // 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, wchar_t p, int q); void processWindowAttributeChange(); void requestWindowAttribute(int); void reportTerminalType(); void reportSecondaryAttributes(); void reportStatus(); void reportAnswerBack(); void reportCursorPosition(); void reportTerminalParms(int p); void onScrollLock(); void scrollLock(const bool lock); // 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,false,MODE_total * sizeof(bool)); } bool mode[MODE_total]; }; TerminalState _currentModes; TerminalState _savedModes; //hash table and timer for buffering calls to the session instance //to update the name of the session //or window title. //these calls occur when certain escape sequences are seen in the //output from the terminal QHash _pendingTitleUpdates; QTimer* _titleUpdateTimer; bool _reportFocusEvents; }; } #endif // VT102EMULATION_H deepin-terminal-5.2.11/3rdparty/terminalwidget/lib/color-schemes/000077500000000000000000000000001370157770500247715ustar00rootroot00000000000000deepin-terminal-5.2.11/3rdparty/terminalwidget/lib/color-schemes/BlackOnLightYellow.schema000066400000000000000000000026451370157770500316570ustar00rootroot00000000000000# example scheme for konsole # the title is to appear in the menu. title Black on Light Yellow # foreground colors # note that the default background color is flagged # to become transparent when an image is present. # slot transparent bold # | | | # V V--color--V V V color 0 0 0 0 0 0 # regular foreground color (Black) color 1 255 255 221 1 0 # regular background color (Light Yellow) color 2 0 0 0 0 0 # regular color 0 Black color 3 178 24 24 0 0 # regular color 1 Red color 4 24 178 24 0 0 # regular color 2 Green color 5 178 104 24 0 0 # regular color 3 Yellow color 6 24 24 178 0 0 # regular color 4 Blue color 7 178 24 178 0 0 # regular color 5 Magenta color 8 24 178 178 0 0 # regular color 6 Cyan color 9 178 178 178 0 0 # regular color 7 White # intensive colors # instead of changing the colors, we've flaged the text to become bold color 10 0 0 0 0 1 # intensive foreground color color 11 255 255 221 1 0 # intensive background color color 12 104 104 104 0 0 # intensive color 0 color 13 255 84 84 0 0 # intensive color 1 color 14 84 255 84 0 0 # intensive color 2 color 15 255 255 84 0 0 # intensive color 3 color 16 84 84 255 0 0 # intensive color 4 color 17 255 84 255 0 0 # intensive color 5 color 18 84 255 255 0 0 # intensive color 6 color 19 255 255 255 0 0 # intensive color 7 deepin-terminal-5.2.11/3rdparty/terminalwidget/lib/color-schemes/BlackOnRandomLight.colorscheme000066400000000000000000000023761370157770500326700ustar00rootroot00000000000000[Background] Bold=false Color=247,247,214 Transparency=true MaxRandomHue=340 [BackgroundIntense] Bold=false Color=255,255,221 Transparency=true [Color0] Bold=false Color=0,0,0 Transparency=false [Color0Intense] Bold=false Color=104,104,104 Transparency=false [Color1] Bold=false Color=178,24,24 Transparency=false [Color1Intense] Bold=false Color=255,84,84 Transparency=false [Color2] Bold=false Color=24,178,24 Transparency=false [Color2Intense] Bold=false Color=84,255,84 Transparency=false [Color3] Bold=false Color=178,104,24 Transparency=false [Color3Intense] Bold=false Color=255,255,84 Transparency=false [Color4] Bold=false Color=24,24,178 Transparency=false [Color4Intense] Bold=false Color=84,84,255 Transparency=false [Color5] Bold=false Color=178,24,178 Transparency=false [Color5Intense] Bold=false Color=255,84,255 Transparency=false [Color6] Bold=false Color=24,178,178 Transparency=false [Color6Intense] Bold=false Color=84,255,255 Transparency=false [Color7] Bold=false Color=178,178,178 Transparency=false [Color7Intense] Bold=false Color=255,255,255 Transparency=false [Foreground] Bold=false Color=0,0,0 Transparency=false [ForegroundIntense] Bold=true Color=0,0,0 Transparency=false [General] Description=Black on Random Light Opacity=1 deepin-terminal-5.2.11/3rdparty/terminalwidget/lib/color-schemes/BlackOnWhite.schema000066400000000000000000000026271370157770500304740ustar00rootroot00000000000000# example scheme for konsole # the title is to appear in the menu. title Black on White # foreground colors # note that the default background color is flagged # to become transparent when an image is present. # slot transparent bold # | | | # V V--color--V V V color 0 0 0 0 0 0 # regular foreground color (Black) color 1 248 248 248 1 0 # regular background color (White) color 2 0 0 0 0 0 # regular color 0 Black color 3 178 24 24 0 0 # regular color 1 Red color 4 24 178 24 0 0 # regular color 2 Green color 5 178 104 24 0 0 # regular color 3 Yellow color 6 24 24 178 0 0 # regular color 4 Blue color 7 178 24 178 0 0 # regular color 5 Magenta color 8 24 178 178 0 0 # regular color 6 Cyan color 9 178 178 178 0 0 # regular color 7 White # intensive colors # instead of changing the colors, we've flaged the text to become bold color 10 0 0 0 0 1 # intensive foreground color color 11 255 255 255 1 0 # intensive background color color 12 104 104 104 0 0 # intensive color 0 color 13 255 84 84 0 0 # intensive color 1 color 14 84 255 84 0 0 # intensive color 2 color 15 255 255 84 0 0 # intensive color 3 color 16 84 84 255 0 0 # intensive color 4 color 17 255 84 255 0 0 # intensive color 5 color 18 84 255 255 0 0 # intensive color 6 color 19 255 255 255 0 0 # intensive color 7 deepin-terminal-5.2.11/3rdparty/terminalwidget/lib/color-schemes/BreezeModified.colorscheme000066400000000000000000000017471370157770500321040ustar00rootroot00000000000000[Background] Color=49,54,59 [BackgroundFaint] Color=49,54,59 [BackgroundIntense] Color=35,38,41 [Color0] Color=7,54,66 [Color0Faint] Color=32,43,54 [Color0Intense] Color=255,85,0 [Color1] Color=237,21,21 [Color1Faint] Color=120,50,40 [Color1Intense] Color=192,57,43 [Color2] Color=17,209,22 [Color2Faint] Color=23,162,98 [Color2Intense] Color=28,220,154 [Color3] Color=246,116,0 [Color3Faint] Color=182,86,25 [Color3Intense] Color=253,188,75 [Color4] Color=29,153,243 [Color4Faint] Color=27,102,143 [Color4Intense] Color=61,174,233 [Color5] Color=155,89,182 [Color5Faint] Color=97,74,115 [Color5Intense] Color=142,68,173 [Color6] Color=26,188,156 [Color6Faint] Color=24,108,96 [Color6Intense] Color=22,160,133 [Color7] Color=239,240,241 [Color7Faint] Color=99,104,109 [Color7Intense] Color=252,252,252 [Foreground] Color=239,240,241 [ForegroundFaint] Color=220,230,231 [ForegroundIntense] Color=252,252,252 [General] Description=BreezeModified Opacity=0.95 Wallpaper= deepin-terminal-5.2.11/3rdparty/terminalwidget/lib/color-schemes/Dark.colorscheme000066400000000000000000000023221370157770500300760ustar00rootroot00000000000000 [Background] Bold=true Color=37,37,37 Transparency=false [BackgroundIntense] Bold=true Color=0,0,0 Transparency=false [Color0] Bold=true Color=0,0,0 Transparency=false [Color0Intense] Bold=true Color=104,104,104 Transparency=false [Color1] Bold=true Color=181,137,0 Transparency=false [Color1Intense] Bold=true Color=139,0,0 Transparency=false [Color2] Bold=true Color=24,178,24 Transparency=false [Color2Intense] Bold=true Color=133,153,0 Transparency=false [Color3] Bold=true Color=178,104,24 Transparency=false [Color3Intense] Bold=true Color=255,255,84 Transparency=false [Color4] Bold=true Color=52,101,164 Transparency=false [Color4Intense] Bold=true Color=52,101,164 Transparency=false [Color5] Bold=true Color=225,30,225 Transparency=false [Color5Intense] Bold=true Color=30,144,255 Transparency=false [Color6] Bold=true Color=24,178,178 Transparency=false [Color6Intense] Bold=true Color=253,246,227 Transparency=false [Color7] Bold=true Color=238,232,213 Transparency=false [Color7Intense] Bold=true Color=255,255,255 Transparency=false [Foreground] Bold=true Color=0,205,0 Transparency=false [ForegroundIntense] Bold=true Color=0,205,0 Transparency=false [General] Description=Green on Black Opacity=1 deepin-terminal-5.2.11/3rdparty/terminalwidget/lib/color-schemes/DarkPastels.colorscheme000066400000000000000000000023651370157770500314410ustar00rootroot00000000000000[Background] Bold=false Color=44,44,44 Transparency=false [BackgroundIntense] Bold=true Color=44,44,44 Transparency=false [Color0] Bold=false Color=63,63,63 Transparency=false [Color0Intense] Bold=true Color=112,144,128 Transparency=false [Color1] Bold=false Color=112,80,80 Transparency=false [Color1Intense] Bold=true Color=220,163,163 Transparency=false [Color2] Bold=false Color=96,180,138 Transparency=false [Color2Intense] Bold=true Color=114,213,163 Transparency=false [Color3] Bold=false Color=223,175,143 Transparency=false [Color3Intense] Bold=true Color=240,223,175 Transparency=false [Color4] Bold=false Color=154,184,215 Transparency=false [Color4Intense] Bold=true Color=148,191,243 Transparency=false [Color5] Bold=false Color=220,140,195 Transparency=false [Color5Intense] Bold=true Color=236,147,211 Transparency=false [Color6] Bold=false Color=140,208,211 Transparency=false [Color6Intense] Bold=true Color=147,224,227 Transparency=false [Color7] Bold=false Color=220,220,204 Transparency=false [Color7Intense] Bold=true Color=255,255,255 Transparency=false [Foreground] Bold=false Color=220,220,204 Transparency=false [ForegroundIntense] Bold=true Color=220,220,204 Transparency=false [General] Description=Dark Pastels Opacity=1 deepin-terminal-5.2.11/3rdparty/terminalwidget/lib/color-schemes/GreenOnBlack.colorscheme000066400000000000000000000023461370157770500315150ustar00rootroot00000000000000 [Background] Bold=false Color=0,0,0 Transparency=false [BackgroundIntense] Bold=false Color=0,0,0 Transparency=false [Color0] Bold=false Color=0,0,0 Transparency=false [Color0Intense] Bold=false Color=104,104,104 Transparency=false [Color1] Bold=false Color=250,75,75 Transparency=false [Color1Intense] Bold=false Color=255,84,84 Transparency=false [Color2] Bold=false Color=24,178,24 Transparency=false [Color2Intense] Bold=false Color=84,255,84 Transparency=false [Color3] Bold=false Color=178,104,24 Transparency=false [Color3Intense] Bold=false Color=255,255,84 Transparency=false [Color4] Bold=false Color=92,167,251 Transparency=false [Color4Intense] Bold=false Color=84,84,255 Transparency=false [Color5] Bold=false Color=225,30,225 Transparency=false [Color5Intense] Bold=false Color=255,84,255 Transparency=false [Color6] Bold=false Color=24,178,178 Transparency=false [Color6Intense] Bold=false Color=84,255,255 Transparency=false [Color7] Bold=false Color=178,178,178 Transparency=false [Color7Intense] Bold=false Color=255,255,255 Transparency=false [Foreground] Bold=false Color=24,240,24 Transparency=false [ForegroundIntense] Bold=true Color=24,240,24 Transparency=false [General] Description=Green on Black Opacity=1 deepin-terminal-5.2.11/3rdparty/terminalwidget/lib/color-schemes/Light.colorscheme000066400000000000000000000023271370157770500302710ustar00rootroot00000000000000 [Background] Bold=true Color=248,248,248 Transparency=false [BackgroundIntense] Bold=true Color=255,255,255 Transparency=false [Color0] Bold=true Color=0,0,0 Transparency=false [Color0Intense] Bold=true Color=104,104,104 Transparency=false [Color1] Bold=true Color=181,137,0 Transparency=false [Color1Intense] Bold=true Color=139,0,0 Transparency=false [Color2] Bold=true Color=24,178,24 Transparency=false [Color2Intense] Bold=true Color=133,153,0 Transparency=false [Color3] Bold=true Color=178,104,24 Transparency=false [Color3Intense] Bold=true Color=255,255,84 Transparency=false [Color4] Bold=true Color=52,101,164 Transparency=false [Color4Intense] Bold=true Color=52,101,164 Transparency=false [Color5] Bold=true Color=225,30,225 Transparency=false [Color5Intense] Bold=true Color=30,144,255 Transparency=false [Color6] Bold=true Color=24,178,178 Transparency=false [Color6Intense] Bold=true Color=253,246,227 Transparency=false [Color7] Bold=true Color=238,232,213 Transparency=false [Color7Intense] Bold=true Color=255,255,255 Transparency=false [Foreground] Bold=true Color=0,0,0 Transparency=false [ForegroundIntense] Bold=true Color=0,0,0 Transparency=false [General] Description=Green on Black Opacity=1 deepin-terminal-5.2.11/3rdparty/terminalwidget/lib/color-schemes/Linux.colorscheme000066400000000000000000000015711370157770500303210ustar00rootroot00000000000000[Background] Bold=false Color=0,0,0 [BackgroundIntense] Bold=false Color=104,104,104 [Color0] Bold=false Color=0,0,0 [Color0Intense] Bold=false Color=104,104,104 [Color1] Bold=false Color=178,24,24 [Color1Intense] Bold=false Color=255,84,84 [Color2] Bold=false Color=24,178,24 [Color2Intense] Bold=false Color=84,255,84 [Color3] Bold=false Color=178,104,24 [Color3Intense] Bold=false Color=255,255,84 [Color4] Bold=false Color=24,24,178 [Color4Intense] Bold=false Color=84,84,255 [Color5] Bold=false Color=178,24,178 [Color5Intense] Bold=false Color=255,84,255 [Color6] Bold=false Color=24,178,178 [Color6Intense] Bold=false Color=84,255,255 [Color7] Bold=false Color=178,178,178 [Color7Intense] Bold=false Color=255,255,255 [Foreground] Bold=false Color=178,178,178 [ForegroundIntense] Bold=false Color=255,255,255 [General] Description=Linux Colors deepin-terminal-5.2.11/3rdparty/terminalwidget/lib/color-schemes/Solarized.colorscheme000066400000000000000000000017201370157770500311520ustar00rootroot00000000000000[Color0] Color=7,54,66 [Color0Intense] Color=0,43,54 [Color0Faint] Color=6,48,59 [Color1] Color=220,50,47 [Color1Intense] Color=203,75,22 [Color1Faint] Color=147,33,31 [Color2] Color=133,153,0 [Color2Intense] Color=88,110,117 [Color2Faint] Color=94,106,0 [Color3] Color=181,137,0 [Color3Intense] Color=101,123,131 [Color3Faint] Color=138,103,0 [Color4] Color=38,139,210 [Color4Intense] Color=131,148,150 [Color4Faint] Color=20,77,115 [Color5] Color=211,54,130 [Color5Intense] Color=108,113,196 [Color5Faint] Color=120,30,75 [Color6] Color=42,161,152 [Color6Intense] Color=147,161,161 [Color6Faint] Color=24,94,88 [Color7] Color=238,232,213 [Color7Intense] Color=253,246,227 [Color7Faint] Color=171,167,154 [Background] Color=0,43,54 [BackgroundIntense] Color=7,54,66 [BackgroundFaint] Color=0,43,54 [Foreground] Color=131,148,150 [ForegroundIntense] Color=147,161,161 [ForegroundFaint] Color=106,119,121 [General] Description=Solarized Opacity=1 deepin-terminal-5.2.11/3rdparty/terminalwidget/lib/color-schemes/SolarizedLight.colorscheme000066400000000000000000000017501370157770500321450ustar00rootroot00000000000000[Color0] Color=7,54,66 [Color0Intense] Color=0,43,54 [Color0Faint] Color=8,65,80 [Color1] Color=220,50,47 [Color1Intense] Color=203,75,22 [Color1Faint] Color=222,81,81 [Color2] Color=133,153,0 [Color2Intense] Color=88,110,117 [Color2Faint] Color=153,168,39 [Color3] Color=181,137,0 [Color3Intense] Color=101,123,131 [Color3Faint] Color=213,170,49 [Color4] Color=38,139,210 [Color4Intense] Color=131,148,150 [Color4Faint] Color=80,173,226 [Color5] Color=211,54,130 [Color5Intense] Color=108,113,196 [Color5Faint] Color=223,92,158 [Color6] Color=42,161,152 [Color6Intense] Color=147,161,161 [Color6Faint] Color=78,211,200 [Color7] Color=238,232,213 [Color7Intense] Color=253,246,227 [Color7Faint] Color=238,232,213 [Background] Color=253,246,227 [BackgroundIntense] Color=238,232,213 [BackgroundFaint] Color=253,246,227 [Foreground] Color=101,123,131 [ForegroundIntense] Color=88,110,117 [ForegroundFaint] Color=141,172,182 [General] Description=Solarized Light Opacity=1 deepin-terminal-5.2.11/3rdparty/terminalwidget/lib/color-schemes/Tango.colorscheme000066400000000000000000000013221370157770500302640ustar00rootroot00000000000000[General] Description=Tango [Background] Color=0,0,0 [BackgroundIntense] Color=104,104,104 [Foreground] ;Color=211,215,207 Color=255,255,255 [ForegroundIntense] Color=255,255,255 ; black [Color0] Color=0,0,0 [Color0Intense] Color=85,87,83 ; red [Color1] Color=204,0,0 [Color1Intense] Color=239,41,41 ; green [Color2] Color=78,154,6 [Color2Intense] Color=138,226,52 ; yellow [Color3] Color=196,160,0 [Color3Intense] Color=252,233,79 ; blue [Color4] Color=52,101,164 [Color4Intense] Color=114,159,207 ; magenta [Color5] Color=117,80,123 [Color5Intense] Color=173,127,168 ; aqua [Color6] Color=6,152,154 [Color6Intense] Color=52,226,226 ; grey [Color7] Color=211,215,207 [Color7Intense] Color=238,238,236 deepin-terminal-5.2.11/3rdparty/terminalwidget/lib/color-schemes/Ubuntu.colorscheme000066400000000000000000000013171370157770500305020ustar00rootroot00000000000000[General] Description=Ubuntu Opacity=1 Wallpaper= [Background] Color=48,10,36 MaxRandomHue=0 MaxRandomSaturation=0 MaxRandomValue=0 [BackgroundIntense] Color=48,10,36 [Color0] Color=46,52,54 [Color0Intense] Color=85,87,83 [Color1] Color=204,0,0 [Color1Intense] Color=239,41,41 [Color2] Color=78,154,6 [Color2Intense] Color=138,226,52 [Color3] Color=196,160,0 [Color3Intense] Color=252,233,79 [Color4] Color=52,101,164 [Color4Intense] Color=114,159,207 [Color5] Color=117,80,123 [Color5Intense] Color=173,127,168 [Color6] Color=6,152,154 [Color6Intense] Color=52,226,226 [Color7] Color=211,215,207 [Color7Intense] Color=238,238,236 [Foreground] Color=238,238,236 [ForegroundIntense] Color=238,238,236deepin-terminal-5.2.11/3rdparty/terminalwidget/lib/color-schemes/WhiteOnBlack.schema000066400000000000000000000026271370157770500304740ustar00rootroot00000000000000# example scheme for konsole # the title is to appear in the menu. title White on Black # foreground colors # note that the default background color is flagged # to become transparent when an image is present. # slot transparent bold # | | | # V V--color--V V V color 0 255 255 255 0 0 # regular foreground color (White) color 1 0 0 0 1 0 # regular background color (Black) color 2 0 0 0 0 0 # regular color 0 Black color 3 178 24 24 0 0 # regular color 1 Red color 4 24 178 24 0 0 # regular color 2 Green color 5 178 104 24 0 0 # regular color 3 Yellow color 6 24 24 178 0 0 # regular color 4 Blue color 7 178 24 178 0 0 # regular color 5 Magenta color 8 24 178 178 0 0 # regular color 6 Cyan color 9 178 178 178 0 0 # regular color 7 White # intensive colors # instead of changing the colors, we've flaged the text to become bold color 10 255 255 255 0 1 # intensive foreground color color 11 0 0 0 1 0 # intensive background color color 12 104 104 104 0 0 # intensive color 0 color 13 255 84 84 0 0 # intensive color 1 color 14 84 255 84 0 0 # intensive color 2 color 15 255 255 84 0 0 # intensive color 3 color 16 84 84 255 0 0 # intensive color 4 color 17 255 84 255 0 0 # intensive color 5 color 18 84 255 255 0 0 # intensive color 6 color 19 255 255 255 0 0 # intensive color 7 deepin-terminal-5.2.11/3rdparty/terminalwidget/lib/color-schemes/historic/000077500000000000000000000000001370157770500266155ustar00rootroot00000000000000deepin-terminal-5.2.11/3rdparty/terminalwidget/lib/color-schemes/historic/BlackOnLightColor.schema000066400000000000000000000026431370157770500333040ustar00rootroot00000000000000# example scheme for konsole # the title is to appear in the menu. title Black on Light Color # foreground colors # note that the default background color is flagged # to become transparent when an image is present. # slot transparent bold # | | | # V V--color--V V V color 0 0 0 0 0 0 # regular foreground color (Black) rcolor 1 30 255 1 0 # regular background color (Light Color) color 2 0 0 0 0 0 # regular color 0 Black color 3 178 24 24 0 0 # regular color 1 Red color 4 24 178 24 0 0 # regular color 2 Green color 5 178 104 24 0 0 # regular color 3 Yellow color 6 24 24 178 0 0 # regular color 4 Blue color 7 178 24 178 0 0 # regular color 5 Magenta color 8 24 178 178 0 0 # regular color 6 Cyan color 9 178 178 178 0 0 # regular color 7 White # intensive colors # instead of changing the colors, we've flaged the text to become bold color 10 0 0 0 0 1 # intensive foreground color color 11 255 255 221 1 0 # intensive background color color 12 104 104 104 0 0 # intensive color 0 color 13 255 84 84 0 0 # intensive color 1 color 14 84 255 84 0 0 # intensive color 2 color 15 255 255 84 0 0 # intensive color 3 color 16 84 84 255 0 0 # intensive color 4 color 17 255 84 255 0 0 # intensive color 5 color 18 84 255 255 0 0 # intensive color 6 color 19 255 255 255 0 0 # intensive color 7 deepin-terminal-5.2.11/3rdparty/terminalwidget/lib/color-schemes/historic/DarkPicture.schema000066400000000000000000000026511370157770500322200ustar00rootroot00000000000000# example scheme for konsole # the title is to appear in the menu. title Marble image tile Blkmarble.jpg # foreground colors # note that the default background color is flagged # to become transparent when an image is present. # slot transparent bold # | | | # V V--color--V V V color 0 255 255 255 0 0 # regular foreground color (White) color 1 0 0 0 1 0 # regular background color (Black) color 2 0 0 0 0 0 # regular color 0 Black color 3 178 24 24 0 0 # regular color 1 Red color 4 24 178 24 0 0 # regular color 2 Green color 5 178 104 24 0 0 # regular color 3 Yellow color 6 24 24 178 0 0 # regular color 4 Blue color 7 178 24 178 0 0 # regular color 5 Magenta color 8 24 178 178 0 0 # regular color 6 Cyan color 9 178 178 178 0 0 # regular color 7 White # intensive colors # instead of changing the colors, we've flaged the text to become bold color 10 255 255 255 0 1 # intensive foreground color color 11 0 0 0 1 0 # intensive background color color 12 104 104 104 0 0 # intensive color 0 color 13 255 84 84 0 0 # intensive color 1 color 14 84 255 84 0 0 # intensive color 2 color 15 255 255 84 0 0 # intensive color 3 color 16 84 84 255 0 0 # intensive color 4 color 17 255 84 255 0 0 # intensive color 5 color 18 84 255 255 0 0 # intensive color 6 color 19 255 255 255 0 0 # intensive color 7 deepin-terminal-5.2.11/3rdparty/terminalwidget/lib/color-schemes/historic/Example.Schema000066400000000000000000000031031370157770500313270ustar00rootroot00000000000000# example scheme for konsole # the title is to appear in the menu. title Ugly 1 # add a wallpaper, if you like. Second word one of { tile,center,full } image tile /opt/kde/share/wallpapers/dancy_pants.jpg # foreground colors # note that the default background color is flagged # to become transparent when an image is present. # slot transparent bold # | | | # V V--color--V V V color 0 0 0 0 0 0 # regular foreground color (Black) color 1 255 255 255 1 0 # regular background color (White) color 2 0 0 0 0 0 # regular color 0 Black color 3 255 0 0 0 0 # regular color 1 Red color 4 0 255 0 0 0 # regular color 2 Green color 5 255 255 0 0 0 # regular color 3 Yellow color 6 0 0 255 0 0 # regular color 4 Blue color 7 255 0 255 0 0 # regular color 5 Magenta color 8 0 255 255 0 0 # regular color 6 Cyan color 9 255 255 255 0 0 # regular color 7 White # intensive colors # instead of changing the colors, we've flaged the text to become bold color 10 0 0 0 0 1 # intensive foreground color color 11 255 255 255 1 1 # intensive background color color 12 0 0 0 0 1 # intensive color 0 color 13 255 0 0 0 1 # intensive color 1 color 14 0 255 0 0 1 # intensive color 2 color 15 255 255 0 0 1 # intensive color 3 color 16 0 0 255 0 1 # intensive color 4 color 17 255 0 255 0 1 # intensive color 5 color 18 0 255 255 0 1 # intensive color 6 color 19 255 255 255 0 1 # intensive color 7 deepin-terminal-5.2.11/3rdparty/terminalwidget/lib/color-schemes/historic/GreenOnBlack.schema000066400000000000000000000026271370157770500323000ustar00rootroot00000000000000# example scheme for konsole # the title is to appear in the menu. title Green on Black # foreground colors # note that the default background color is flagged # to become transparent when an image is present. # slot transparent bold # | | | # V V--color--V V V color 0 24 240 24 0 0 # regular foreground color (Green) color 1 0 0 0 1 0 # regular background color (Black) color 2 0 0 0 0 0 # regular color 0 Black color 3 178 24 24 0 0 # regular color 1 Red color 4 24 178 24 0 0 # regular color 2 Green color 5 178 104 24 0 0 # regular color 3 Yellow color 6 24 24 178 0 0 # regular color 4 Blue color 7 178 24 178 0 0 # regular color 5 Magenta color 8 24 178 178 0 0 # regular color 6 Cyan color 9 178 178 178 0 0 # regular color 7 White # intensive colors # instead of changing the colors, we've flaged the text to become bold color 10 24 240 24 0 1 # intensive foreground color color 11 0 0 0 1 0 # intensive background color color 12 104 104 104 0 0 # intensive color 0 color 13 255 84 84 0 0 # intensive color 1 color 14 84 255 84 0 0 # intensive color 2 color 15 255 255 84 0 0 # intensive color 3 color 16 84 84 255 0 0 # intensive color 4 color 17 255 84 255 0 0 # intensive color 5 color 18 84 255 255 0 0 # intensive color 6 color 19 255 255 255 0 0 # intensive color 7 deepin-terminal-5.2.11/3rdparty/terminalwidget/lib/color-schemes/historic/GreenTint.schema000066400000000000000000000031141370157770500316750ustar00rootroot00000000000000# linux color schema for konsole title Green Tint transparency 0.3 0 150 0 # FIXME # # The flaw in this schema is that "blick" comes out on the # Linux console as intensive background, really. # Since this is not used in clients you'll hardly notice # it in practice. # foreground colors # note that the default background color is flagged # to become transparent when an image is present. # slot transparent bold # | red grn blu | | # V V--color--V V V color 0 178 178 178 0 0 # regular foreground color (White) color 1 0 0 0 1 0 # regular background color (Black) color 2 0 0 0 0 0 # regular color 0 Black color 3 178 24 24 0 0 # regular color 1 Red color 4 24 178 24 0 0 # regular color 2 Green color 5 178 104 24 0 0 # regular color 3 Yellow color 6 24 24 178 0 0 # regular color 4 Blue color 7 178 24 178 0 0 # regular color 5 Magenta color 8 24 178 178 0 0 # regular color 6 Cyan color 9 178 178 178 0 0 # regular color 7 White # intensive colors # instead of changing the colors, we've flaged the text to become bold color 10 255 255 255 0 0 # intensive foreground color color 11 104 104 104 1 0 # intensive background color color 12 104 104 104 0 0 # intensive color 0 color 13 255 84 84 0 0 # intensive color 1 color 14 84 255 84 0 0 # intensive color 2 color 15 255 255 84 0 0 # intensive color 3 color 16 84 84 255 0 0 # intensive color 4 color 17 255 84 255 0 0 # intensive color 5 color 18 84 255 255 0 0 # intensive color 6 color 19 255 255 255 0 0 # intensive color 7 deepin-terminal-5.2.11/3rdparty/terminalwidget/lib/color-schemes/historic/GreenTint_MC.schema000066400000000000000000000031401370157770500322530ustar00rootroot00000000000000# linux color schema for konsole title Green Tint with Transparent MC transparency 0.3 0 150 0 # FIXME # # The flaw in this schema is that "blick" comes out on the # Linux console as intensive background, really. # Since this is not used in clients you'll hardly notice # it in practice. # foreground colors # note that the default background color is flagged # to become transparent when an image is present. # slot transparent bold # | red grn blu | | # V V--color--V V V color 0 178 178 178 0 0 # regular foreground color (White) color 1 0 0 0 1 0 # regular background color (Black) color 2 0 0 0 0 0 # regular color 0 Black color 3 178 24 24 0 0 # regular color 1 Red color 4 24 178 24 0 0 # regular color 2 Green color 5 178 104 24 0 0 # regular color 3 Yellow color 6 0 0 0 1 0 # regular color 4 Blue color 7 178 24 178 0 0 # regular color 5 Magenta color 8 24 178 178 0 0 # regular color 6 Cyan color 9 178 178 178 0 0 # regular color 7 White # intensive colors # instead of changing the colors, we've flaged the text to become bold color 10 255 255 255 0 0 # intensive foreground color color 11 104 104 104 1 0 # intensive background color color 12 104 104 104 0 0 # intensive color 0 color 13 255 84 84 0 0 # intensive color 1 color 14 84 255 84 0 0 # intensive color 2 color 15 255 255 84 0 0 # intensive color 3 color 16 84 84 255 0 0 # intensive color 4 color 17 255 84 255 0 0 # intensive color 5 color 18 84 255 255 0 0 # intensive color 6 color 19 255 255 255 0 0 # intensive color 7 deepin-terminal-5.2.11/3rdparty/terminalwidget/lib/color-schemes/historic/LightPicture.schema000066400000000000000000000026461370157770500324120ustar00rootroot00000000000000# example scheme for konsole # the title is to appear in the menu. title Paper image tile Paper01.jpg # foreground colors # note that the default background color is flagged # to become transparent when an image is present. # slot transparent bold # | | | # V V--color--V V V color 0 0 0 0 0 0 # regular foreground color (Black) color 1 255 255 255 1 0 # regular background color (White) color 2 0 0 0 0 0 # regular color 0 Black color 3 178 24 24 0 0 # regular color 1 Red color 4 24 178 24 0 0 # regular color 2 Green color 5 178 104 24 0 0 # regular color 3 Yellow color 6 24 24 178 0 0 # regular color 4 Blue color 7 178 24 178 0 0 # regular color 5 Magenta color 8 24 178 178 0 0 # regular color 6 Cyan color 9 178 178 178 0 0 # regular color 7 White # intensive colors # instead of changing the colors, we've flaged the text to become bold color 10 0 0 0 0 1 # intensive foreground color color 11 255 255 255 1 0 # intensive background color color 12 104 104 104 0 0 # intensive color 0 color 13 255 84 84 0 0 # intensive color 1 color 14 84 255 84 0 0 # intensive color 2 color 15 255 255 84 0 0 # intensive color 3 color 16 84 84 255 0 0 # intensive color 4 color 17 255 84 255 0 0 # intensive color 5 color 18 84 255 255 0 0 # intensive color 6 color 19 255 255 255 0 0 # intensive color 7 deepin-terminal-5.2.11/3rdparty/terminalwidget/lib/color-schemes/historic/Linux.schema000066400000000000000000000030641370157770500311010ustar00rootroot00000000000000# linux color schema for konsole title Linux Colors # FIXME # # The flaw in this schema is that "blick" comes out on the # Linux console as intensive background, really. # Since this is not used in clients you'll hardly notice # it in practice. # foreground colors # note that the default background color is flagged # to become transparent when an image is present. # slot transparent bold # | red grn blu | | # V V--color--V V V color 0 178 178 178 0 0 # regular foreground color (White) color 1 0 0 0 1 0 # regular background color (Black) color 2 0 0 0 0 0 # regular color 0 Black color 3 178 24 24 0 0 # regular color 1 Red color 4 24 178 24 0 0 # regular color 2 Green color 5 178 104 24 0 0 # regular color 3 Yellow color 6 24 24 178 0 0 # regular color 4 Blue color 7 178 24 178 0 0 # regular color 5 Magenta color 8 24 178 178 0 0 # regular color 6 Cyan color 9 178 178 178 0 0 # regular color 7 White # intensive colors # instead of changing the colors, we've flaged the text to become bold color 10 255 255 255 0 0 # intensive foreground color color 11 104 104 104 1 0 # intensive background color color 12 104 104 104 0 0 # intensive color 0 color 13 255 84 84 0 0 # intensive color 1 color 14 84 255 84 0 0 # intensive color 2 color 15 255 255 84 0 0 # intensive color 3 color 16 84 84 255 0 0 # intensive color 4 color 17 255 84 255 0 0 # intensive color 5 color 18 84 255 255 0 0 # intensive color 6 color 19 255 255 255 0 0 # intensive color 7 deepin-terminal-5.2.11/3rdparty/terminalwidget/lib/color-schemes/historic/README.Schema000066400000000000000000000102441370157770500306750ustar00rootroot00000000000000[README.Schema] The schemata offered in the Options/Schema menu are taken from from configurations files with a *.schema pattern either located in $KDEDIR/share/apps/konsole or ~/.kde/share/apps/konsole. Schemata allow to configure the color set that konsole uses, together with some more information on rendition processing. Syntax File :: { [Line] ['#' Comment] '\n' } Line :: "title" Title :: "image" Usage PathToPictureFile :: "transparency" Fade Red Green Blue :: "color" Slot Red Green Blue Transparent Bold :: "rcolor" Slot Saturation Value Transparent Bold :: "sysfg" Slot Transparent Bold :: "sysbg" Slot Transparent Bold Meaning - Title is the text to appear in the Option/Schema menu. It should be unique among all other schemata therefore. - The "image" clause allows to place an image on the konsole's background. - Usage can be either - "tile" - the image is tilewise replicated. - "center" - the image is centered. - "full" - the image is stretched to fit the window size. - The Path of the picture can both be relative (to kde wallpapers) or absolute. When a schema uses a background image (or transparency) one has to make at least one color slot transparent to achive any visible effect. Please read below about the "Transparent" field in color,sysbg,sysfg. - The "transparency" clause picks and uses the background of the desktop as if it where an image together with a fade effect. This effect will fade the background to the specified color. The "Fade" is a real value between 0 and 1, indicating the strength of the fade. A value of 0 will not change the image, a value of 1 will make it the fade color everywhere, and in between. This will make the "glas" of the window be of the color given in the clause and being more(1) or less(0) intransparent. - The remaining clauses (color,sysbg,sysfg) are used to setup konsoles rendition system. To this end, konsole offers 20 color slots. Slot Meaning ----- -------------------------- 0 regular foreground color 1 regular background color 2-9 regular bgr color 0-7 10 intensive foreground color 11 intensive background color 12-19 intensive bgr color 0-7 The traditional meaning of the "bgr" color codes has a bitwise interpretation of an additive three primary color scheme inherited from early EGA color terminals. Color Bits Colors ----- ---- ------- 0 000 Black 1 001 Red 2 010 Green 3 011 Yellow 4 100 Blue 5 101 Magenta 6 110 Cyan 7 111 White One may or may not stick to this tradition. Konsole allows to assign colors freely to slots. The slots fall apart into two groups, regular and intensive colors. The later are used when BOLD rendition is used by the client. Each of the groups have a default fore- and background color and the said bgr colors. Normal terminal processing will simply use the default colors. The color desired for a slot is indicated in the Red Green Blue fields of the color clause. Use the sysfg or the sysbg clause to indicate the default fore and background colors of the desktop. To specify randomized color for a slot use the clause rcolor. The two parameters to it being Saturation - the amount of colour, and Value, the darkness of the colour. To use transparency/images and to simulate the behavior of the xterm, one can supply two additional tags to each slot: - Transparent (0/1) meaning to show the background picture, if any. - Bold (0/1) to render characters bold. If you know about the escape codes, you might have noticed that intensive and bold rendition are sort of confused. This is inherited by the xterm which konsole is simulating. One can use the colortest.sh script supplied with the konsole source distribution to test a schema. The schema installed with konsole are more or less demonstrations and not really beauty, beside the Linux.schema, perhaps, which is made after the VGA colors. deepin-terminal-5.2.11/3rdparty/terminalwidget/lib/color-schemes/historic/README.default.Schema000066400000000000000000000027621370157770500323260ustar00rootroot00000000000000# default scheme for konsole (only here for documentation purposes) # the title is to appear in the menu. title Konsole Defaults # image tile /opt/kde/share/wallpapers/gray2.jpg # foreground colors # note that the default background color is flagged # to become transparent when an image is present. # slot transparent bold # | | | # V V--color--V V V color 0 0 0 0 0 0 # regular foreground color (Black) color 1 255 255 255 1 0 # regular background color (White) color 2 0 0 0 0 0 # regular color 0 Black color 3 178 24 24 0 0 # regular color 1 Red color 4 24 178 24 0 0 # regular color 2 Green color 5 178 104 24 0 0 # regular color 3 Yellow color 6 24 24 178 0 0 # regular color 4 Blue color 7 178 24 178 0 0 # regular color 5 Magenta color 8 24 178 178 0 0 # regular color 6 Cyan color 9 178 178 178 0 0 # regular color 7 White # intensive colors # instead of changing the colors, we've flaged the text to become bold color 10 0 0 0 0 1 # intensive foreground color color 11 255 255 255 1 0 # intensive background color color 12 104 104 104 0 0 # intensive color 0 color 13 255 84 84 0 0 # intensive color 1 color 14 84 255 84 0 0 # intensive color 2 color 15 255 255 84 0 0 # intensive color 3 color 16 84 84 255 0 0 # intensive color 4 color 17 255 84 255 0 0 # intensive color 5 color 18 84 255 255 0 0 # intensive color 6 color 19 255 255 255 0 0 # intensive color 7 deepin-terminal-5.2.11/3rdparty/terminalwidget/lib/color-schemes/historic/Transparent.schema000066400000000000000000000031241370157770500323000ustar00rootroot00000000000000# linux color schema for konsole title Transparent Konsole transparency 0.35 0 0 0 # FIXME # # The flaw in this schema is that "blick" comes out on the # Linux console as intensive background, really. # Since this is not used in clients you'll hardly notice # it in practice. # foreground colors # note that the default background color is flagged # to become transparent when an image is present. # slot transparent bold # | red grn blu | | # V V--color--V V V color 0 178 178 178 0 0 # regular foreground color (White) color 1 0 0 0 1 0 # regular background color (Black) color 2 0 0 0 0 0 # regular color 0 Black color 3 178 24 24 0 0 # regular color 1 Red color 4 24 178 24 0 0 # regular color 2 Green color 5 178 104 24 0 0 # regular color 3 Yellow color 6 24 24 178 0 0 # regular color 4 Blue color 7 178 24 178 0 0 # regular color 5 Magenta color 8 24 178 178 0 0 # regular color 6 Cyan color 9 178 178 178 0 0 # regular color 7 White # intensive colors # instead of changing the colors, we've flaged the text to become bold color 10 255 255 255 0 0 # intensive foreground color color 11 104 104 104 1 0 # intensive background color color 12 104 104 104 0 0 # intensive color 0 color 13 255 84 84 0 0 # intensive color 1 color 14 84 255 84 0 0 # intensive color 2 color 15 255 255 84 0 0 # intensive color 3 color 16 84 84 255 0 0 # intensive color 4 color 17 255 84 255 0 0 # intensive color 5 color 18 84 255 255 0 0 # intensive color 6 color 19 255 255 255 0 0 # intensive color 7 deepin-terminal-5.2.11/3rdparty/terminalwidget/lib/color-schemes/historic/Transparent_MC.schema000066400000000000000000000032051370157770500326570ustar00rootroot00000000000000# linux color schema for konsole title Transparent for MC transparency 0.35 0 0 0 # FIXME # # The flaw in this schema is that "blick" comes out on the # Linux console as intensive background, really. # Since this is not used in clients you'll hardly notice # it in practice. # foreground colors # note that the default background color is flagged # to become transparent when an image is present. # slot transparent bold # | red grn blu | | # V V--color--V V V color 0 178 178 178 0 0 # regular foreground color (White) color 1 0 0 0 1 0 # regular background color (Black) color 2 0 0 0 0 0 # regular color 0 Black color 3 178 24 24 0 0 # regular color 1 Red color 4 24 178 24 0 0 # regular color 2 Green color 5 178 104 24 0 0 # regular color 3 Yellow #color 6 24 24 178 0 0 # regular color 4 Blue color 6 0 0 0 1 0 # regular color 4 Blue color 7 178 24 178 0 0 # regular color 5 Magenta color 8 24 178 178 0 0 # regular color 6 Cyan color 9 178 178 178 0 0 # regular color 7 White # intensive colors # instead of changing the colors, we've flaged the text to become bold color 10 255 255 255 0 0 # intensive foreground color color 11 104 104 104 1 0 # intensive background color color 12 104 104 104 0 0 # intensive color 0 color 13 255 84 84 0 0 # intensive color 1 color 14 84 255 84 0 0 # intensive color 2 color 15 255 255 84 0 0 # intensive color 3 color 16 84 84 255 0 0 # intensive color 4 color 17 255 84 255 0 0 # intensive color 5 color 18 84 255 255 0 0 # intensive color 6 color 19 255 255 255 0 0 # intensive color 7 deepin-terminal-5.2.11/3rdparty/terminalwidget/lib/color-schemes/historic/Transparent_darkbg.schema000066400000000000000000000026331370157770500336160ustar00rootroot00000000000000# linux color schema for konsole title Transparent, Dark Background transparency 0.75 0 0 0 # foreground colors # note that the default background color is flagged # to become transparent when an image is present. # slot transparent bold # | red grn blu | | # V V--color--V V V color 0 255 255 255 0 0 # regular foreground color (White) color 1 0 0 0 1 0 # regular background color (Black) color 2 0 0 0 0 0 # regular color 0 Black color 3 178 24 24 0 0 # regular color 1 Red color 4 24 178 24 0 0 # regular color 2 Green color 5 178 104 24 0 0 # regular color 3 Yellow color 6 24 24 178 0 0 # regular color 4 Blue color 7 178 24 178 0 0 # regular color 5 Magenta color 8 24 178 178 0 0 # regular color 6 Cyan color 9 178 178 178 0 0 # regular color 7 White # intensive colors # instead of changing the colors, we've flaged the text to become bold color 10 255 255 255 0 0 # intensive foreground color color 11 104 104 104 1 0 # intensive background color color 12 104 104 104 0 0 # intensive color 0 color 13 255 84 84 0 0 # intensive color 1 color 14 84 255 84 0 0 # intensive color 2 color 15 255 255 84 0 0 # intensive color 3 color 16 84 84 255 0 0 # intensive color 4 color 17 255 84 255 0 0 # intensive color 5 color 18 84 255 255 0 0 # intensive color 6 color 19 255 255 255 0 0 # intensive color 7 deepin-terminal-5.2.11/3rdparty/terminalwidget/lib/color-schemes/historic/Transparent_lightbg.schema000066400000000000000000000034421370157770500340030ustar00rootroot00000000000000# linux color schema for konsole title Transparent, Light Background transparency 0.1 0 0 0 # This is a schema for very light backgrounds. It makes some # hacks about the colors to make Midnight Commander transparent # and with suitable colors. # foreground colors # note that the default background color is flagged # to become transparent when an image is present. # slot transparent bold # | red grn blu | | # V V--color--V V V color 0 50 50 50 0 0 # regular foreground color (DarkGray) color 1 200 200 200 1 0 # regular background color (White) # color 2 0 0 0 0 0 # regular color 0 Black color 2 200 200 200 1 0 # regular background color (White) color 3 178 24 24 0 0 # regular color 1 Red color 4 24 178 24 0 0 # regular color 2 Green color 5 178 104 24 0 0 # regular color 3 Yellow #color 6 24 24 178 0 0 # regular color 4 Blue color 6 0 0 0 1 0 # regular color 4 Blue # Blue is transparent, to make MC transparent color 7 178 24 178 0 0 # regular color 5 Magenta color 8 24 178 178 0 0 # regular color 6 Cyan # color 9 178 178 178 0 0 # regular color 7 White color 9 50 50 50 0 0 # regular foreground color (DarkGray) # intensive colors # instead of changing the colors, we've flaged the text to become bold color 10 0 0 0 0 0 # intensive foreground color color 11 255 255 255 1 0 # intensive background color color 12 104 104 104 0 0 # intensive color 0 color 13 255 84 84 0 0 # intensive color 1 color 14 84 255 84 0 0 # intensive color 2 color 15 255 255 84 0 0 # intensive color 3 color 16 84 84 255 0 0 # intensive color 4 color 17 255 84 255 0 0 # intensive color 5 color 18 84 255 255 0 0 # intensive color 6 color 19 255 255 255 0 0 # intensive color 7 deepin-terminal-5.2.11/3rdparty/terminalwidget/lib/color-schemes/historic/XTerm.schema000066400000000000000000000031551370157770500310420ustar00rootroot00000000000000# xterm color schema for konsole # xterm colors can be configured (almost) like # konsole colors can. This is the uncustomized # xterm schema. # Please refere to your local xterm setup files # if this schema differs. title XTerm Colors # foreground colors ------------------------------- # note that the default background color is flagged # to become transparent when an image is present. # slot transparent bold # | red grn blu | | # V V--color--V V V color 0 0 0 0 0 0 # regular foreground color (Black) color 1 255 255 255 1 0 # regular background color (White) color 2 0 0 0 0 0 # regular color 0 Black color 3 205 0 0 0 0 # regular color 1 Red color 4 0 205 0 0 0 # regular color 2 Green color 5 205 205 0 0 0 # regular color 3 Yellow color 6 0 0 205 0 0 # regular color 4 Blue color 7 205 0 205 0 0 # regular color 5 Magenta color 8 0 205 205 0 0 # regular color 6 Cyan color 9 229 229 229 0 0 # regular color 7 White # intensive colors ------------------------------------------- # for some strange reason, intensive colors are bold, also. color 10 77 77 77 0 1 # intensive foreground color color 11 255 255 255 1 1 # intensive background color color 12 77 77 77 0 1 # intensive color 0 color 13 255 0 0 0 1 # intensive color 1 color 14 0 255 0 0 1 # intensive color 2 color 15 255 255 0 0 1 # intensive color 3 color 16 0 0 255 0 1 # intensive color 4 color 17 255 0 255 0 1 # intensive color 5 color 18 0 255 255 0 1 # intensive color 6 color 19 255 255 255 0 1 # intensive color 7 deepin-terminal-5.2.11/3rdparty/terminalwidget/lib/color-schemes/historic/syscolor.schema000066400000000000000000000026521370157770500316610ustar00rootroot00000000000000# schema that uses system colors # the title is to appear in the menu. title System Colors # image none # foreground colors # note that the default background color is flagged # to become transparent when an image is present. # slot transparent bold # | | | # V V--color--V V V sysfg 0 0 0 # regular foreground color (system) sysbg 1 1 0 # regular background color (system) color 2 0 0 0 0 0 # regular color 0 Black color 3 178 24 24 0 0 # regular color 1 Red color 4 24 178 24 0 0 # regular color 2 Green color 5 178 104 24 0 0 # regular color 3 Yellow color 6 24 24 178 0 0 # regular color 4 Blue color 7 178 24 178 0 0 # regular color 5 Magenta color 8 24 178 178 0 0 # regular color 6 Cyan color 9 178 178 178 0 0 # regular color 7 White # intensive colors # instead of changing the colors, we've flaged the text to become bold color 10 0 0 0 0 1 # intensive foreground color color 11 255 255 255 1 0 # intensive background color color 12 104 104 104 0 0 # intensive color 0 color 13 255 84 84 0 0 # intensive color 1 color 14 84 255 84 0 0 # intensive color 2 color 15 255 255 84 0 0 # intensive color 3 color 16 84 84 255 0 0 # intensive color 4 color 17 255 84 255 0 0 # intensive color 5 color 18 84 255 255 0 0 # intensive color 6 color 19 255 255 255 0 0 # intensive color 7 deepin-terminal-5.2.11/3rdparty/terminalwidget/lib/color-schemes/historic/vim.schema000066400000000000000000000027071370157770500306000ustar00rootroot00000000000000# VIM-recommended color schema for konsole # VIM (VI improved) in "help xiterm" recommends these colors for xterm. title VIM Colors # foreground colors ------------------------------- # note that the default background color is flagged # to become transparent when an image is present. # slot transparent bold # | red grn blu | | # V V--color--V V V color 0 0 0 0 0 0 # regular foreground color (Black) color 1 255 255 255 1 0 # regular background color (White) color 2 0 0 0 0 0 # regular color 0 Black color 3 192 0 0 0 0 # regular color 1 Red color 4 0 128 0 0 0 # regular color 2 Green color 5 128 128 0 0 0 # regular color 3 Yellow color 6 0 0 192 0 0 # regular color 4 Blue color 7 192 0 192 0 0 # regular color 5 Magenta color 8 0 128 128 0 0 # regular color 6 Cyan color 9 192 192 192 0 0 # regular color 7 White # intensive colors ------------------------------------------- color 10 77 77 77 0 1 # intensive foreground color color 11 255 255 255 1 1 # intensive background color color 12 128 128 128 0 0 # intensive color 0 color 13 255 96 96 0 0 # intensive color 1 color 14 0 255 0 0 0 # intensive color 2 color 15 255 255 0 0 0 # intensive color 3 color 16 128 128 255 0 0 # intensive color 4 color 17 255 64 255 0 0 # intensive color 5 color 18 0 255 255 0 0 # intensive color 6 color 19 255 255 255 0 0 # intensive color 7 deepin-terminal-5.2.11/3rdparty/terminalwidget/lib/default.keytab000066400000000000000000000114211370157770500250520ustar00rootroot00000000000000# [README.default.Keytab] Buildin Keyboard Table # # To customize your keyboard, copy this file to something # ending with .keytab and change it to meet you needs. # Please read the README.KeyTab and the README.keyboard # in this case. # # -------------------------------------------------------------- keyboard "Default (XFree 4)" # -------------------------------------------------------------- # # Note that this particular table is a "risc" version made to # ease customization without bothering with obsolete details. # See VT100.keytab for the more hairy stuff. # # -------------------------------------------------------------- # common keys key Escape : "\E" key Tab -Shift : "\t" key Tab +Shift+Ansi : "\E[Z" key Tab +Shift-Ansi : "\t" key Backtab +Ansi : "\E[Z" key Backtab -Ansi : "\t" key Return-Shift-NewLine : "\r" key Return-Shift+NewLine : "\r\n" key Return+Shift : "\EOM" # Backspace and Delete codes are preserving CTRL-H. key Backspace : "\x7f" # Arrow keys in VT52 mode # shift up/down are reserved for scrolling. # shift left/right are reserved for switching between tabs (this is hardcoded). key Up -Shift-Ansi : "\EA" key Down -Shift-Ansi : "\EB" key Right-Shift-Ansi : "\EC" key Left -Shift-Ansi : "\ED" # Arrow keys in ANSI mode with Application - and Normal Cursor Mode) key Up -Shift-AnyMod+Ansi+AppCuKeys : "\EOA" key Down -Shift-AnyMod+Ansi+AppCuKeys : "\EOB" key Right -Shift-AnyMod+Ansi+AppCuKeys : "\EOC" key Left -Shift-AnyMod+Ansi+AppCuKeys : "\EOD" key Up -Shift-AnyMod+Ansi-AppCuKeys : "\E[A" key Down -Shift-AnyMod+Ansi-AppCuKeys : "\E[B" key Right -Shift-AnyMod+Ansi-AppCuKeys : "\E[C" key Left -Shift-AnyMod+Ansi-AppCuKeys : "\E[D" key Up -Shift+AnyMod+Ansi : "\E[1;*A" key Down -Shift+AnyMod+Ansi : "\E[1;*B" key Right -Shift+AnyMod+Ansi : "\E[1;*C" key Left -Shift+AnyMod+Ansi : "\E[1;*D" # other grey PC keys key Enter+NewLine : "\r\n" key Enter-NewLine : "\r" key Home -AnyMod -AppCuKeys : "\E[H" key End -AnyMod -AppCuKeys : "\E[F" key Home -AnyMod +AppCuKeys : "\EOH" key End -AnyMod +AppCuKeys : "\EOF" key Home +AnyMod : "\E[1;*H" key End +AnyMod : "\E[1;*F" key Insert -AnyMod : "\E[2~" key Delete -AnyMod : "\E[3~" key Insert +AnyMod : "\E[2;*~" key Delete +AnyMod : "\E[3;*~" key Prior -Shift-AnyMod : "\E[5~" key Next -Shift-AnyMod : "\E[6~" key Prior -Shift+AnyMod : "\E[5;*~" key Next -Shift+AnyMod : "\E[6;*~" # Function keys key F1 -AnyMod : "\EOP" key F2 -AnyMod : "\EOQ" key F3 -AnyMod : "\EOR" key F4 -AnyMod : "\EOS" key F5 -AnyMod : "\E[15~" key F6 -AnyMod : "\E[17~" key F7 -AnyMod : "\E[18~" key F8 -AnyMod : "\E[19~" key F9 -AnyMod : "\E[20~" key F10 -AnyMod : "\E[21~" key F11 -AnyMod : "\E[23~" key F12 -AnyMod : "\E[24~" key F1 +AnyMod : "\EO*P" key F2 +AnyMod : "\EO*Q" key F3 +AnyMod : "\EO*R" key F4 +AnyMod : "\EO*S" key F5 +AnyMod : "\E[15;*~" key F6 +AnyMod : "\E[17;*~" key F7 +AnyMod : "\E[18;*~" key F8 +AnyMod : "\E[19;*~" key F9 +AnyMod : "\E[20;*~" key F10 +AnyMod : "\E[21;*~" key F11 +AnyMod : "\E[23;*~" key F12 +AnyMod : "\E[24;*~" # Work around dead keys key Space +Control : "\x00" # Some keys are used by konsole to cause operations. # The scroll* operations refer to the history buffer. key Up +Shift-AppScreen : scrollLineUp key Prior +Shift-AppScreen : scrollPageUp key Down +Shift-AppScreen : scrollLineDown key Next +Shift-AppScreen : scrollPageDown key ScrollLock : scrollLock # keypad characters are not offered differently by Qt. deepin-terminal-5.2.11/3rdparty/terminalwidget/lib/kb-layouts/000077500000000000000000000000001370157770500243205ustar00rootroot00000000000000deepin-terminal-5.2.11/3rdparty/terminalwidget/lib/kb-layouts/README000066400000000000000000000044151370157770500252040ustar00rootroot00000000000000[README.KeyTab] The keytabs offered in the Options/Keyboard menu are taken from from configurations files with a *.keytab pattern either located in $KDEDIR/share/apps/konsole or ~/.kde/share/apps/konsole. Keytabs allow to configure the behavior of konsole on keyboard events, especially for functions keys. Please have a look into the README.keyboard file, too. The syntax is that each entry has the form : "key" Keyname { ("+"|"-") Modename } ":" (String|Operation) Keynames are those defined in with the "Qt::Key_" prefix removed. Mode names are: - Shift : Shift Key pressed - Alt : Alt Key pressed - Control : Control Key pressed ( The VT100 emulation has modes that can affect the sequences emitted by certain keys. These modes are under control of the client program. - Newline : effects Return and Enter key. - Application : effects Up and Down key. - Ansi : effects Up and Down key (This is for VT52, really). Since sending a state to a program that has set the state itself is positivly wrong and obsolete design, better forget about this nasty detail. I may well remove this "feature" in a future clean up round. ) A "+" preceeding a Modename means the Key is pressed. A "-" preceeding a Modename means the Key is not pressed. If no mode is given it means don't care. Note that the combination of Key and Modes (set/reset) has to be unique. This means, that key A + Shift : "A" key A : "a" will not accept the small letter "a" rule as expected, one has to add a "- Shift" to the last clause. Use the stdout/stderr dianostics of konsole when modifying keytabs to find problems like this. Operations are - scrollUpLine : scroll up one line in the history log - scrollUpPage : scroll up one page in the history log - scrollDownLine : scroll down one line in the history log - scrollDownPage : scroll down one page in the history log - emitClipboard : "paste" the current clipboard - emitSelection : "paste" the current selection Strings have the syntax of C strings, one may use the following escapes: - \E - escape - \\ - backslash - \" - double quote - \t - tab - \r - return - \n - newline - \b - backspace - \xHH - where HH are two hex digits deepin-terminal-5.2.11/3rdparty/terminalwidget/lib/kb-layouts/default.keytab000066400000000000000000000130401370157770500271430ustar00rootroot00000000000000# [README.default.Keytab] Default Keyboard Table # # To customize your keyboard, copy this file to something # ending with .keytab and change it to meet you needs. # Please read the README.KeyTab and the README.keyboard # in this case. # # -------------------------------------------------------------- keyboard "Default (XFree 4)" # -------------------------------------------------------------- # # Note that this particular table is a "risc" version made to # ease customization without bothering with obsolete details. # See VT100.keytab for the more hairy stuff. # # -------------------------------------------------------------- # common keys key Escape : "\E" key Tab -Shift : "\t" key Tab +Shift+Ansi : "\E[Z" key Tab +Shift-Ansi : "\t" key Backtab +Ansi : "\E[Z" key Backtab -Ansi : "\t" key Return-Shift-NewLine : "\r" key Return-Shift+NewLine : "\r\n" key Return+Shift : "\EOM" # Backspace and Delete codes are preserving CTRL-H. # # old # Backspace without CTRL sends '^H'; this matches XTerm behaviour # BS, hex \x08, \b # new # Backspace without CTRL sends '^?'; this matches gnome-terminal key Backspace -Control : "\x7f" # Match xterm behaviour: Backspace sends '^?' when Control is pressed key Backspace +Control : "\x7f" # Arrow keys in VT52 mode # shift up/down are reserved for scrolling. # shift left/right are reserved for switching between tabs (this is hardcoded). key Up -Shift-Ansi : "\EA" key Down -Shift-Ansi : "\EB" key Right-Shift-Ansi : "\EC" key Left -Shift-Ansi : "\ED" # Arrow keys in ANSI mode with Application - and Normal Cursor Mode) key Up -Shift-AnyMod+Ansi+AppCuKeys : "\EOA" key Down -Shift-AnyMod+Ansi+AppCuKeys : "\EOB" key Right -Shift-AnyMod+Ansi+AppCuKeys : "\EOC" key Left -Shift-AnyMod+Ansi+AppCuKeys : "\EOD" key Up -Shift-AnyMod+Ansi-AppCuKeys : "\E[A" key Down -Shift-AnyMod+Ansi-AppCuKeys : "\E[B" key Right -Shift-AnyMod+Ansi-AppCuKeys : "\E[C" key Left -Shift-AnyMod+Ansi-AppCuKeys : "\E[D" key Up -Shift+AnyMod+Ansi : "\E[1;*A" key Down -Shift+AnyMod+Ansi : "\E[1;*B" key Right -Shift+AnyMod+Ansi : "\E[1;*C" key Left -Shift+AnyMod+Ansi : "\E[1;*D" key Up +Shift+AppScreen : "\E[1;*A" key Down +Shift+AppScreen : "\E[1;*B" key Left +Shift+AppScreen : "\E[1;*D" key Right +Shift+AppScreen : "\E[1;*C" # Keypad keys with NumLock ON # (see "Numeric Keypad" section at http://www.nw.com/nw/WWW/products/wizcon/vt100.html ) # # Not enabled for now because it breaks the keypad in Vim. # #key 0 +KeyPad+AppKeyPad : "\EOp" #key 1 +KeyPad+AppKeyPad : "\EOq" #key 2 +KeyPad+AppKeyPad : "\EOr" #key 3 +KeyPad+AppKeyPad : "\EOs" #key 4 +KeyPad+AppKeyPad : "\EOt" #key 5 +KeyPad+AppKeyPad : "\EOu" #key 6 +KeyPad+AppKeyPad : "\EOv" #key 7 +KeyPad+AppKeyPad : "\EOw" #key 8 +KeyPad+AppKeyPad : "\EOx" #key 9 +KeyPad+AppKeyPad : "\EOy" #key + +KeyPad+AppKeyPad : "\EOl" #key - +KeyPad+AppKeyPad : "\EOm" #key . +KeyPad+AppKeyPad : "\EOn" #key * +KeyPad+AppKeyPad : "\EOM" #key Enter +KeyPad+AppKeyPad : "\r" # Keypad keys with NumLock Off key Up -Shift+Ansi+AppCuKeys+KeyPad : "\EOA" key Down -Shift+Ansi+AppCuKeys+KeyPad : "\EOB" key Right -Shift+Ansi+AppCuKeys+KeyPad : "\EOC" key Left -Shift+Ansi+AppCuKeys+KeyPad : "\EOD" key Up -Shift+Ansi-AppCuKeys+KeyPad : "\E[A" key Down -Shift+Ansi-AppCuKeys+KeyPad : "\E[B" key Right -Shift+Ansi-AppCuKeys+KeyPad : "\E[C" key Left -Shift+Ansi-AppCuKeys+KeyPad : "\E[D" key Home +AppCuKeys+KeyPad : "\EOH" key End +AppCuKeys+KeyPad : "\EOF" key Home -AppCuKeys+KeyPad : "\E[H" key End -AppCuKeys+KeyPad : "\E[F" key Insert +KeyPad : "\E[2~" key Delete +KeyPad : "\E[3~" key PgUp -Shift+KeyPad : "\E[5~" key PgDown -Shift+KeyPad : "\E[6~" # other grey PC keys key Enter+NewLine : "\r\n" key Enter-NewLine : "\r" key Home -AnyMod-AppCuKeys : "\E[H" key End -AnyMod-AppCuKeys : "\E[F" key Home -AnyMod+AppCuKeys : "\EOH" key End -AnyMod+AppCuKeys : "\EOF" key Home +AnyMod : "\E[1;*H" key End +AnyMod : "\E[1;*F" key Insert -AnyMod : "\E[2~" key Delete -AnyMod : "\E[3~" key Insert +AnyMod : "\E[2;*~" key Delete +AnyMod : "\E[3;*~" key PgUp -Shift-AnyMod : "\E[5~" key PgDown -Shift-AnyMod : "\E[6~" key PgUp -Shift+AnyMod : "\E[5;*~" key PgDown -Shift+AnyMod : "\E[6;*~" # Function keys key F1 -AnyMod : "\EOP" key F2 -AnyMod : "\EOQ" key F3 -AnyMod : "\EOR" key F4 -AnyMod : "\EOS" key F5 -AnyMod : "\E[15~" key F6 -AnyMod : "\E[17~" key F7 -AnyMod : "\E[18~" key F8 -AnyMod : "\E[19~" key F9 -AnyMod : "\E[20~" key F10 -AnyMod : "\E[21~" key F11 -AnyMod : "\E[23~" key F12 -AnyMod : "\E[24~" key F1 +AnyMod : "\EO*P" key F2 +AnyMod : "\EO*Q" key F3 +AnyMod : "\EO*R" key F4 +AnyMod : "\EO*S" key F5 +AnyMod : "\E[15;*~" key F6 +AnyMod : "\E[17;*~" key F7 +AnyMod : "\E[18;*~" key F8 +AnyMod : "\E[19;*~" key F9 +AnyMod : "\E[20;*~" key F10 +AnyMod : "\E[21;*~" key F11 +AnyMod : "\E[23;*~" key F12 +AnyMod : "\E[24;*~" # Work around dead keys key Space +Control : "\x00" # Some keys are used by konsole to cause operations. # The scroll* operations refer to the history buffer. key Up +Shift-AppScreen : scrollLineUp key PgUp +Shift-AppScreen : scrollPageUp key Home +Shift-AppScreen : scrollUpToTop key Down +Shift-AppScreen : scrollLineDown key PgDown +Shift-AppScreen : scrollPageDown key End +Shift-AppScreen : scrollDownToBottom key ScrollLock : scrollLock deepin-terminal-5.2.11/3rdparty/terminalwidget/lib/kb-layouts/historic/000077500000000000000000000000001370157770500261445ustar00rootroot00000000000000deepin-terminal-5.2.11/3rdparty/terminalwidget/lib/kb-layouts/historic/vt100.keytab000066400000000000000000000061701370157770500302230ustar00rootroot00000000000000# [vt100.keytab] Konsole Keyboard Table (VT100 keys) # # -------------------------------------------------------------- keyboard "vt100 (historical)" # -------------------------------------------------------------- # # This configuration table allows to customize the # meaning of the keys. # # The syntax is that each entry has the form : # # "key" Keyname { ("+"|"-") Modename } ":" (String|Operation) # # Keynames are those defined in with the # "Qt::Key_" removed. (We'd better insert the list here) # # Mode names are : # # - Shift # - Alt # - Control # # The VT100 emulation has two modes that can affect the # sequences emitted by certain keys. These modes are # under control of the client program. # # - Newline : effects Return and Enter key. # - Application : effects Up and Down key. # # - Ansi : effects Up and Down key (This is for VT52, really). # # Operations are # # - scrollUpLine # - scrollUpPage # - scrollDownLine # - scrollDownPage # # - emitSelection # # If the key is not found here, the text of the # key event as provided by QT is emitted, possibly # preceeded by ESC if the Alt key is pressed. # # -------------------------------------------------------------- key Escape : "\E" key Tab : "\t" # VT100 can add an extra \n after return. # The NewLine mode is set by an escape sequence. key Return-NewLine : "\r" key Return+NewLine : "\r\n" # Some desperately try to save the ^H. key Backspace : "\x7f" key Delete : "\E[3~" # These codes are for the VT52 mode of VT100 # The Ansi mode (i.e. VT100 mode) is set by # an escape sequence key Up -Shift-Ansi : "\EA" key Down -Shift-Ansi : "\EB" key Right-Shift-Ansi : "\EC" key Left -Shift-Ansi : "\ED" # VT100 emits a mode bit together # with the arrow keys.The AppCuKeys # mode is set by an escape sequence. key Up -Shift+Ansi+AppCuKeys : "\EOA" key Down -Shift+Ansi+AppCuKeys : "\EOB" key Right-Shift+Ansi+AppCuKeys : "\EOC" key Left -Shift+Ansi+AppCuKeys : "\EOD" key Up -Shift+Ansi-AppCuKeys : "\E[A" key Down -Shift+Ansi-AppCuKeys : "\E[B" key Right-Shift+Ansi-AppCuKeys : "\E[C" key Left -Shift+Ansi-AppCuKeys : "\E[D" # function keys (FIXME: make pf1-pf4) key F1 : "\E[11~" key F2 : "\E[12~" key F3 : "\E[13~" key F4 : "\E[14~" key F5 : "\E[15~" key F6 : "\E[17~" key F7 : "\E[18~" key F8 : "\E[19~" key F9 : "\E[20~" key F10 : "\E[21~" key F11 : "\E[23~" key F12 : "\E[24~" key Home : "\E[H" key End : "\E[F" key PgUp -Shift : "\E[5~" key PgDown -Shift : "\E[6~" key Insert -Shift : "\E[2~" # Keypad-Enter. See comment on Return above. key Enter+NewLine : "\r\n" key Enter-NewLine : "\r" key Space +Control : "\x00" # some of keys are used by konsole. key Up +Shift : scrollLineUp key PgUp +Shift : scrollPageUp key Down +Shift : scrollLineDown key PgDown +Shift : scrollPageDown key ScrollLock : scrollLock #---------------------------------------------------------- # keypad characters as offered by Qt # cannot be recognized as such. #---------------------------------------------------------- # Following other strings as emitted by konsole. deepin-terminal-5.2.11/3rdparty/terminalwidget/lib/kb-layouts/historic/x11r5.keytab000066400000000000000000000032161370157770500302270ustar00rootroot00000000000000# [x11r5.Keytab] Keyboard Table for X11 R5 keyboard "XTerm (XFree 3.x.x)" # -------------------------------------------------------------- # # Note that this particular table is a "risc" version made to # ease customization without bothering with obsolete details. # See VT100.keytab for the more hairy stuff. # # -------------------------------------------------------------- # common keys key Escape : "\E" key Tab : "\t" key Return : "\r" # Backspace and Delete codes are preserving CTRL-H. key Backspace : "\x7f" # cursor keys key Up -Shift : "\EOA" key Down -Shift : "\EOB" key Right -Shift : "\EOC" key Left -Shift : "\EOD" # other grey PC keys key Enter : "\r" key Home : "\E[1~" key Insert-Shift : "\E[2~" key Delete : "\E[3~" key End : "\E[4~" key PgUp -Shift : "\E[5~" key PgDown -Shift : "\E[6~" # function keys key F1 : "\E[11~" key F2 : "\E[12~" key F3 : "\E[13~" key F4 : "\E[14~" key F5 : "\E[15~" key F6 : "\E[17~" key F7 : "\E[18~" key F8 : "\E[19~" key F9 : "\E[20~" key F10 : "\E[21~" key F11 : "\E[23~" key F12 : "\E[24~" # Work around dead keys key Space +Control : "\x00" # Some keys are used by konsole to cause operations. # The scroll* operations refer to the history buffer. key Up +Shift : scrollLineUp key PgUp +Shift : scrollPageUp key Down +Shift : scrollLineDown key PgDown +Shift : scrollPageDown key ScrollLock : scrollLock # keypad characters are not offered differently by Qt. deepin-terminal-5.2.11/3rdparty/terminalwidget/lib/kb-layouts/linux.keytab000066400000000000000000000065471370157770500266740ustar00rootroot00000000000000# [linux.keytab] Konsole Keyboard Table (Linux console keys) # # -------------------------------------------------------------- # NOT TESTED, MAY NEED SOME CLEANUPS keyboard "Linux console" # -------------------------------------------------------------- # # This configuration table allows to customize the # meaning of the keys. # # The syntax is that each entry has the form : # # "key" Keyname { ("+"|"-") Modename } ":" (String|Operation) # # Keynames are those defined in with the # "Qt::Key_" removed. (We'd better insert the list here) # # Mode names are : # # - Shift # - Alt # - Control # # The VT100 emulation has two modes that can affect the # sequences emitted by certain keys. These modes are # under control of the client program. # # - Newline : effects Return and Enter key. # - Application : effects Up and Down key. # # - Ansi : effects Up and Down key (This is for VT52, really). # # Operations are # # - scrollUpLine # - scrollUpPage # - scrollDownLine # - scrollDownPage # # - emitSelection # # If the key is not found here, the text of the # key event as provided by QT is emitted, possibly # preceeded by ESC if the Alt key is pressed. # # -------------------------------------------------------------- key Escape : "\E" key Tab : "\t" # VT100 can add an extra \n after return. # The NewLine mode is set by an escape sequence. key Return-NewLine : "\r" key Return+NewLine : "\r\n" # Some desperately try to save the ^H. key Backspace : "\x7f" key Delete : "\E[3~" # These codes are for the VT52 mode of VT100 # The Ansi mode (i.e. VT100 mode) is set by # an escape sequence key Up -Shift-Ansi : "\EA" key Down -Shift-Ansi : "\EB" key Right-Shift-Ansi : "\EC" key Left -Shift-Ansi : "\ED" # VT100 emits a mode bit together # with the arrow keys.The AppCuKeys # mode is set by an escape sequence. key Up -Shift+Ansi+AppCuKeys : "\EOA" key Down -Shift+Ansi+AppCuKeys : "\EOB" key Right-Shift+Ansi+AppCuKeys : "\EOC" key Left -Shift+Ansi+AppCuKeys : "\EOD" key Up -Shift+Ansi-AppCuKeys : "\E[A" key Down -Shift+Ansi-AppCuKeys : "\E[B" key Right-Shift+Ansi-AppCuKeys : "\E[C" key Left -Shift+Ansi-AppCuKeys : "\E[D" key Up -Shift+AnyMod+Ansi : "\E[1;*A" key Down -Shift+AnyMod+Ansi : "\E[1;*B" key Right -Shift+AnyMod+Ansi : "\E[1;*C" key Left -Shift+AnyMod+Ansi : "\E[1;*D" # linux functions keys F1-F5 differ from xterm key F1 : "\E[[A" key F2 : "\E[[B" key F3 : "\E[[C" key F4 : "\E[[D" key F5 : "\E[[E" key F6 : "\E[17~" key F7 : "\E[18~" key F8 : "\E[19~" key F9 : "\E[20~" key F10 : "\E[21~" key F11 : "\E[23~" key F12 : "\E[24~" key Home : "\E[1~" key End : "\E[4~" key PgUp -Shift : "\E[5~" key PgDown -Shift : "\E[6~" key Insert -Shift : "\E[2~" # Keypad-Enter. See comment on Return above. key Enter+NewLine : "\r\n" key Enter-NewLine : "\r" key Space +Control : "\x00" # some of keys are used by konsole. key Up +Shift : scrollLineUp key PgUp +Shift : scrollPageUp key Down +Shift : scrollLineDown key PgDown +Shift : scrollPageDown key ScrollLock : scrollLock #---------------------------------------------------------- # keypad characters as offered by Qt # cannot be recognized as such. #---------------------------------------------------------- # Following other strings as emitted by konsole. deepin-terminal-5.2.11/3rdparty/terminalwidget/lib/kb-layouts/macbook.keytab000066400000000000000000000144161370157770500271420ustar00rootroot00000000000000# [README.default.Keytab] Buildin Keyboard Table # # To customize your keyboard, copy this file to something # ending with .keytab and change it to meet you needs. # Please read the README.KeyTab and the README.keyboard # in this case. # # -------------------------------------------------------------- keyboard "Default (XFree 4)" # -------------------------------------------------------------- # # Note that this particular table is a "risc" version made to # ease customization without bothering with obsolete details. # See VT100.keytab for the more hairy stuff. # # -------------------------------------------------------------- # common keys key Escape : "\x1b" #key Control : "^" key Tab -Shift : "\t" key Tab +Shift+Ansi : "\E[Z" key Tab +Shift-Ansi : "\t" key Backtab +Ansi : "\E[Z" key Backtab -Ansi : "\t" key Return-Shift-NewLine : "\r" key Return-Shift+NewLine : "\r\n" key Return+Shift : "\EOM" # Backspace and Delete codes are preserving CTRL-H. key Backspace : "\x7f" # Arrow keys in VT52 mode # shift up/down are reserved for scrolling. # shift left/right are reserved for switching between tabs (this is hardcoded). # Command + C # on mac - Control=Command, Meta=Ctrl # do not use Control+C for interrupt signal - it's used for "Copy to clipboard" #key Control +C : "\x03" key Meta +C: "\x03" # Arrow keys in ANSI mode with Application - and Normal Cursor Mode) key Up -Shift+Ansi-AppCuKeys : "\E[A" key Down -Shift+Ansi-AppCuKeys : "\E[B" key Right-Shift+Ansi-AppCuKeys : "\E[C" key Left -Shift+Ansi-AppCuKeys : "\E[D" key Up -Ansi : "\E[1;*A" key Down -Ansi : "\E[1;*B" key Right -Ansi : "\E[1;*C" key Left -Ansi : "\E[1;*D" #key Up -Shift-Ansi : "\EA" #key Down -Shift-Ansi : "\EB" #key Right-Shift-Ansi : "\EC" #key Left -Shift-Ansi : "\ED" #key Up -Shift-AnyMod+Ansi-AppCuKeys : "\E[A" #key Down -Shift-AnyMod+Ansi-AppCuKeys : "\E[B" #key Right -Shift-AnyMod+Ansi-AppCuKeys : "\E[C" #key Left -Shift-AnyMod+Ansi-AppCuKeys : "\E[D" #key Up -Shift-AnyMod+Ansi-AppCuKeys : "\EOA" #key Down -Shift-AnyMod+Ansi-AppCuKeys : "\EOB" #key Right -Shift-AnyMod+Ansi-AppCuKeys : "\EOC" #key Left -Shift-AnyMod+Ansi-AppCuKeys : "\EOD" #key Up -Shift-AnyMod+Ansi : "\E[1;*A" #key Down -Shift-AnyMod+Ansi : "\E[1;*B" #key Right -Shift-AnyMod+Ansi : "\E[1;*C" #key Left -Shift-AnyMod+Ansi : "\E[1;*D" # other grey PC keys key Enter+NewLine : "\r\n" key Enter-NewLine : "\r" key Home -AnyMod -AppCuKeys : "\E[H" key End -AnyMod -AppCuKeys : "\E[F" key Home -AnyMod +AppCuKeys : "\EOH" key End -AnyMod +AppCuKeys : "\EOF" key Home +AnyMod : "\E[1;*H" key End +AnyMod : "\E[1;*F" key Insert -AnyMod : "\E[2~" key Delete -AnyMod : "\E[3~" key Insert +AnyMod : "\E[2;*~" key Delete +AnyMod : "\E[3;*~" key PgUp -Shift-AnyMod : "\E[5~" key PgDown -Shift-AnyMod : "\E[6~" key PgUp -Shift+AnyMod : "\E[5;*~" key PgDown -Shift+AnyMod : "\E[6;*~" # Function keys #key F1 -AnyMod : "\EOP" #key F2 -AnyMod : "\EOQ" #key F3 -AnyMod : "\EOR" #key F4 -AnyMod : "\EOS" #define ALT_KP_0 "\033Op" #define ALT_KP_1 "\033Oq" #define ALT_KP_2 "\033Or" #define ALT_KP_3 "\033Os" #define ALT_KP_4 "\033Ot" #define ALT_KP_5 "\033Ou" #define ALT_KP_6 "\033Ov" #define ALT_KP_7 "\033Ow" #define ALT_KP_8 "\033Ox" #define ALT_KP_9 "\033Oy" key F1 -AnyMod : "\EOP" key F2 -AnyMod : "\EOQ" key F3 -AnyMod : "\EOR" key F4 -AnyMod : "\EOS" key F5 -AnyMod : "\EOT" key F6 -AnyMod : "\EOU" key F7 -AnyMod : "\EOV" key F8 -AnyMod : "\EOW" key F9 -AnyMod : "\EOX" key F10 -AnyMod : "\EOY" #key F5 -AnyMod : "\E[15~" #key F6 -AnyMod : "\E[17~" #key F7 -AnyMod : "\E[18~" #key F8 -AnyMod : "\E[19~" #key F9 -AnyMod : "\E[20~" #key F10 -AnyMod : "\E[21~" #key F11 -AnyMod : "\E[23~" #key F12 -AnyMod : "\E[24~" #key F1 +AnyMod : "\EO*P" #key F2 +AnyMod : "\EO*Q" #key F3 +AnyMod : "\EO*R" #key F4 +AnyMod : "\EO*S" #key F5 +AnyMod : "\E[15;*~" #key F6 +AnyMod : "\E[17;*~" #key F7 +AnyMod : "\E[18;*~" #key F8 +AnyMod : "\E[19;*~" #key F9 +AnyMod : "\E[20;*~" #key F10 +AnyMod : "\E[21;*~" #key F11 +AnyMod : "\E[23;*~" #key F12 +AnyMod : "\E[24;*~" # Work around dead keys key Space +Control : "\x00" # Some keys are used by konsole to cause operations. # The scroll* operations refer to the history buffer. key Up +Shift-AppScreen : scrollLineUp key PgUp +Shift-AppScreen : scrollPageUp key Down +Shift-AppScreen : scrollLineDown key PgDown +Shift-AppScreen : scrollPageDown #key Up +Shift : scrollLineUp #key Prior +Shift : scrollPageUp #key Down +Shift : scrollLineDown #key Next +Shift : scrollPageDown key ScrollLock : scrollLock # keypad characters are not offered differently by Qt. deepin-terminal-5.2.11/3rdparty/terminalwidget/lib/kb-layouts/solaris.keytab000066400000000000000000000050601370157770500271760ustar00rootroot00000000000000# [solaris.keytab] Konsole Keyboard Table # keyboard "Solaris console" # -------------------------------------------------------------- # # This configuration table allows to customize the # meaning of the keys. # # The syntax is that each entry has the form : # # "key" Keyname { ("+"|"-") Modename } ":" (String|Operation) # # Keynames are those defined in with the # "Qt::Key_" removed. (We'd better insert the list here) # # Mode names are : # # - Shift # - Alt # - Control # # The VT100 emulation has two modes that can affect the # sequences emitted by certain keys. These modes are # under control of the client program. # # # - Newline : effects Return and Enter key. # - Application : effects Up and Down key. # # - Ansi : effects Up and Down key (This is for VT52, really). # # Operations are # # - scrollUpLine # - scrollUpPage # - scrollDownLine # - scrollDownPage # # - emitSelection # # If the key is not found here, the text of the # key event as provided by QT is emitted, possibly # preceeded by ESC if the Alt key is pressed. # # -------------------------------------------------------------- key Escape : "\E" key Tab : "\t" key Return-Alt : "\r" key Return+Alt : "\E\r" # Backspace and Delete codes are preserving CTRL-H. key Backspace : "\x08" #key Delete : "\x7F" # cursor keys key Up -Shift : "\EOA" key Down -Shift : "\EOB" key Right -Shift : "\EOC" key Left -Shift : "\EOD" # other grey PC keys key Enter : "\r" key Home : "\E[1~" key Insert-Shift : "\E[2~" key Delete : "\E[3~" key End : "\E[4~" key PgUp -Shift : "\E[5~" key PgDown -Shift : "\E[6~" # function keys key F1 : "\E[11~" key F2 : "\E[12~" key F3 : "\E[13~" key F4 : "\E[14~" key F5 : "\E[15~" key F6 : "\E[17~" key F7 : "\E[18~" key F8 : "\E[19~" key F9 : "\E[20~" key F10 : "\E[21~" key F11 : "\E[23~" key F12 : "\E[24~" # Work around dead keys key Space +Control : "\x00" # Some keys are used by konsole to cause operations. # The scroll* operations refer to the history buffer. #key Left +Shift : prevSession #key Right +Shift : nextSession key Up +Shift : scrollLineUp key PgUp +Shift : scrollPageUp key Down +Shift : scrollLineDown key PgDown +Shift : scrollPageDown #key Insert+Shift : emitSelection # keypad characters are not offered differently by Qt. deepin-terminal-5.2.11/3rdparty/terminalwidget/lib/kb-layouts/vt420pc.keytab000066400000000000000000000105501370157770500267240ustar00rootroot00000000000000# # NOTE: This keyboard binding is not installed because it # apparently doesn't work with actual VT420 systems # (see BUG:170220) # # [vt420pc.keytab] Konsole Keyboard Table (VT420pc keys) # adapted by ferdinand gassauer f.gassauer@aon.at # Nov 2000 # ################################################################ # # The escape sequences emmited by the # keys Shift+F1 to Shift+F12 might not fit your needs # ################# IMPORTANT NOTICE ############################# # the key bindings (Kcontrol -> look and feel -> keybindgs) # overrule the settings in this file. The key bindings might be # changed by the user WITHOUT notification of the maintainer of # the keytab file. Konsole will not work as expected by # the maintainer of the keytab file. ################################################################ # # -------------------------------------------------------------- keyboard "DEC VT420 Terminal" # -------------------------------------------------------------- # # This configuration table allows to customize the # meaning of the keys. # # The syntax is that each entry has the form : # # "key" Keyname { ("+"|"-") Modename } ":" (String|Operation) # # Keynames are those defined in with the # "Qt::Key_" removed. (We'd better insert the list here) # # Mode names are : # # - Shift # - Alt # - Control # # The VT100 emulation has two modes that can affect the # sequences emitted by certain keys. These modes are # under control of the client program. # # - Newline : effects Return and Enter key. # - Application : effects Up and Down key. # # - Ansi : effects Up and Down key (This is for VT52, really). # # Operations are # # - scrollUpLine # - scrollUpPage # - scrollDownLine # - scrollDownPage # # - emitSelection # # If the key is not found here, the text of the # key event as provided by QT is emitted, possibly # preceeded by ESC if the Alt key is pressed. # # -------------------------------------------------------------- key Escape : "\E" key Tab : "\t" key Backtab: "\E[Z" # VT100 can add an extra \n after return. # The NewLine mode is set by an escape sequence. key Return-NewLine : "\r" key Return+NewLine : "\r\n" # Some desperately try to save the ^H. # may be not everyone wants this key Backspace : "\x08" # Control H key Delete : "\x7f" # These codes are for the VT420pc # The Ansi mode (i.e. VT100 mode) is set by # an escape sequence key Up -Shift-Ansi : "\EA" key Down -Shift-Ansi : "\EB" key Right-Shift-Ansi : "\EC" key Left -Shift-Ansi : "\ED" # VT100 emits a mode bit together # with the arrow keys.The AppCuKeys # mode is set by an escape sequence. key Up -Shift+Ansi+AppCuKeys : "\EOA" key Down -Shift+Ansi+AppCuKeys : "\EOB" key Right-Shift+Ansi+AppCuKeys : "\EOC" key Left -Shift+Ansi+AppCuKeys : "\EOD" key Up -Shift+Ansi-AppCuKeys : "\E[A" key Down -Shift+Ansi-AppCuKeys : "\E[B" key Right-Shift+Ansi-AppCuKeys : "\E[C" key Left -Shift+Ansi-AppCuKeys : "\E[D" # function keys key F1 -Shift : "\E[11~" key F2 -Shift : "\E[12~" key F3 -Shift : "\E[13~" key F4 -Shift : "\E[14~" key F5 -Shift : "\E[15~" key F6 -Shift : "\E[17~" key F7 -Shift : "\E[18~" key F8 -Shift : "\E[19~" key F9 -Shift : "\E[20~" key F10-Shift : "\E[21~" key F11-Shift : "\E[23~" key F12-Shift : "\E[24~" # # Shift F1-F12 # key F1 +Shift : "\E[11;2~" key F2 +Shift : "\E[12;2~" key F3 +Shift : "\E[13;2~" key F4 +Shift : "\E[14;2~" key F5 +Shift : "\E[15;2~" key F6 +Shift : "\E[17;2~" key F7 +Shift : "\E[18;2~" key F8 +Shift : "\E[19;2~" key F9 +Shift : "\E[20;2~" key F10+Shift : "\E[21;2~" key F11+Shift : "\E[23;2~" key F12+Shift : "\E[24;2~" key Home : "\E[H" key End : "\E[F" key PgUp -Shift : "\E[5~" key PgDown -Shift : "\E[6~" key Insert -Shift : "\E[2~" # Keypad-Enter. See comment on Return above. key Enter+NewLine : "\r\n" key Enter-NewLine : "\r" key Space +Control : "\x00" # some of keys are used by konsole. key Up +Shift : scrollLineUp key PgUp +Shift : scrollPageUp key Down +Shift : scrollLineDown key PgDown +Shift : scrollPageDown key ScrollLock : scrollLock #---------------------------------------------------------- # keypad characters as offered by Qt # cannot be recognized as such. #---------------------------------------------------------- # Following other strings as emitted by konsole. deepin-terminal-5.2.11/3rdparty/terminalwidget/lib/konsole_wcwidth.cpp000066400000000000000000000021001370157770500261260ustar00rootroot00000000000000/* $XFree86: xc/programs/xterm/wcwidth.character,v 1.3 2001/07/29 22:08:16 tsi Exp $ */ /* * This is an implementation of wcwidth() and wcswidth() as defined in * "The Single UNIX Specification, Version 2, The Open Group, 1997" * * * Markus Kuhn -- 2001-01-12 -- public domain */ #include #ifdef HAVE_UTF8PROC #include #else #include #endif #include "konsole_wcwidth.h" int konsole_wcwidth(wchar_t ucs) { #ifdef HAVE_UTF8PROC utf8proc_category_t cat = utf8proc_category( ucs ); if (cat == UTF8PROC_CATEGORY_CO) { // Co: Private use area. libutf8proc makes them zero width, while tmux // assumes them to be width 1, and glibc's default width is also 1 return 1; } return utf8proc_charwidth( ucs ); #else return wcwidth( ucs ); #endif } // single byte char: +1, multi byte char: +2 int string_width( const std::wstring & wstr ) { int w = 0; for ( size_t i = 0; i < wstr.length(); ++i ) { w += konsole_wcwidth( wstr[ i ] ); } return w; } deepin-terminal-5.2.11/3rdparty/terminalwidget/lib/konsole_wcwidth.h000066400000000000000000000006661370157770500256120ustar00rootroot00000000000000/* $XFree86: xc/programs/xterm/wcwidth.h,v 1.2 2001/06/18 19:09:27 dickey Exp $ */ /* Markus Kuhn -- 2001-01-12 -- public domain */ /* Adaptions for KDE by Waldo Bastian */ /* Rewritten for QT4 by e_k */ #ifndef _KONSOLE_WCWIDTH_H_ #define _KONSOLE_WCWIDTH_H_ // Standard #include int konsole_wcwidth(wchar_t ucs); int string_width( const std::wstring & wstr ); #endif deepin-terminal-5.2.11/3rdparty/terminalwidget/lib/kprocess.cpp000066400000000000000000000236621370157770500245740ustar00rootroot00000000000000/* * This file is a part of QTerminal - http://gitorious.org/qterminal * * This file was un-linked from KDE and modified * by Maxim Bourmistrov * */ /* This file is part of the KDE libraries Copyright (C) 2007 Oswald Buddenhagen This 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; either version 2 of the License, 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. */ #include "kprocess.h" #include #ifdef Q_OS_WIN # include #else # include # include #endif #ifndef Q_OS_WIN # define STD_OUTPUT_HANDLE 1 # define STD_ERROR_HANDLE 2 #endif #ifdef _WIN32_WCE #include #endif void KProcessPrivate::writeAll(const QByteArray &buf, int fd) { #ifdef Q_OS_WIN #ifndef _WIN32_WCE HANDLE h = GetStdHandle(fd); if (h) { DWORD wr; WriteFile(h, buf.data(), buf.size(), &wr, 0); } #else fwrite(buf.data(), 1, buf.size(), (FILE*)fd); #endif #else int off = 0; do { int ret = ::write(fd, buf.data() + off, buf.size() - off); if (ret < 0) { if (errno != EINTR) return; } else { off += ret; } } while (off < buf.size()); #endif } void KProcessPrivate::forwardStd(KProcess::ProcessChannel good, int fd) { Q_Q(KProcess); QProcess::ProcessChannel oc = q->readChannel(); q->setReadChannel(good); writeAll(q->readAll(), fd); q->setReadChannel(oc); } void KProcessPrivate::_k_forwardStdout() { #ifndef _WIN32_WCE forwardStd(KProcess::StandardOutput, STD_OUTPUT_HANDLE); #else forwardStd(KProcess::StandardOutput, (int)stdout); #endif } void KProcessPrivate::_k_forwardStderr() { #ifndef _WIN32_WCE forwardStd(KProcess::StandardError, STD_ERROR_HANDLE); #else forwardStd(KProcess::StandardError, (int)stderr); #endif } ///////////////////////////// // public member functions // ///////////////////////////// KProcess::KProcess(QObject *parent) : QProcess(parent), d_ptr(new KProcessPrivate) { d_ptr->q_ptr = this; setOutputChannelMode(ForwardedChannels); } KProcess::KProcess(KProcessPrivate *d, QObject *parent) : QProcess(parent), d_ptr(d) { d_ptr->q_ptr = this; setOutputChannelMode(ForwardedChannels); } KProcess::~KProcess() { delete d_ptr; } void KProcess::setOutputChannelMode(OutputChannelMode mode) { Q_D(KProcess); d->outputChannelMode = mode; disconnect(this, SIGNAL(readyReadStandardOutput())); disconnect(this, SIGNAL(readyReadStandardError())); switch (mode) { case OnlyStdoutChannel: connect(this, SIGNAL(readyReadStandardError()), SLOT(_k_forwardStderr())); break; case OnlyStderrChannel: connect(this, SIGNAL(readyReadStandardOutput()), SLOT(_k_forwardStdout())); break; default: QProcess::setProcessChannelMode((ProcessChannelMode)mode); return; } QProcess::setProcessChannelMode(QProcess::SeparateChannels); } KProcess::OutputChannelMode KProcess::outputChannelMode() const { Q_D(const KProcess); return d->outputChannelMode; } void KProcess::setNextOpenMode(QIODevice::OpenMode mode) { Q_D(KProcess); d->openMode = mode; } #define DUMMYENV "_KPROCESS_DUMMY_=" void KProcess::clearEnvironment() { setEnvironment(QStringList() << QString::fromLatin1(DUMMYENV)); } void KProcess::setEnv(const QString &name, const QString &value, bool overwrite) { QStringList env = environment(); if (env.isEmpty()) { env = systemEnvironment(); env.removeAll(QString::fromLatin1(DUMMYENV)); } QString fname(name); fname.append(QLatin1Char('=')); for (QStringList::Iterator it = env.begin(); it != env.end(); ++it) if ((*it).startsWith(fname)) { if (overwrite) { *it = fname.append(value); setEnvironment(env); } return; } env.append(fname.append(value)); setEnvironment(env); } void KProcess::unsetEnv(const QString &name) { QStringList env = environment(); if (env.isEmpty()) { env = systemEnvironment(); env.removeAll(QString::fromLatin1(DUMMYENV)); } QString fname(name); fname.append(QLatin1Char('=')); for (QStringList::Iterator it = env.begin(); it != env.end(); ++it) if ((*it).startsWith(fname)) { env.erase(it); if (env.isEmpty()) env.append(QString::fromLatin1(DUMMYENV)); setEnvironment(env); return; } } void KProcess::setProgram(const QString &exe, const QStringList &args) { Q_D(KProcess); d->prog = exe; d->args = args; #ifdef Q_OS_WIN setNativeArguments(QString()); #endif } void KProcess::setProgram(const QStringList &argv) { Q_D(KProcess); Q_ASSERT( !argv.isEmpty() ); d->args = argv; d->prog = d->args.takeFirst(); #ifdef Q_OS_WIN setNativeArguments(QString()); #endif } KProcess &KProcess::operator<<(const QString &arg) { Q_D(KProcess); if (d->prog.isEmpty()) d->prog = arg; else d->args << arg; return *this; } KProcess &KProcess::operator<<(const QStringList &args) { Q_D(KProcess); if (d->prog.isEmpty()) setProgram(args); else d->args << args; return *this; } void KProcess::clearProgram() { Q_D(KProcess); d->prog.clear(); d->args.clear(); #ifdef Q_OS_WIN setNativeArguments(QString()); #endif } #if 0 void KProcess::setShellCommand(const QString &cmd) { Q_D(KProcess); KShell::Errors err; d->args = KShell::splitArgs( cmd, KShell::AbortOnMeta | KShell::TildeExpand, &err); if (err == KShell::NoError && !d->args.isEmpty()) { d->prog = KStandardDirs::findExe(d->args[0]); if (!d->prog.isEmpty()) { d->args.removeFirst(); #ifdef Q_OS_WIN setNativeArguments(QString()); #endif return; } } d->args.clear(); #ifdef Q_OS_UNIX // #ifdef NON_FREE // ... as they ship non-POSIX /bin/sh # if !defined(__linux__) && !defined(__FreeBSD__) && !defined(__NetBSD__) && !defined(__OpenBSD__) && !defined(__DragonFly__) && !defined(__GNU__) // If /bin/sh is a symlink, we can be pretty sure that it points to a // POSIX shell - the original bourne shell is about the only non-POSIX // shell still in use and it is always installed natively as /bin/sh. d->prog = QFile::symLinkTarget(QString::fromLatin1("/bin/sh")); if (d->prog.isEmpty()) { // Try some known POSIX shells. d->prog = KStandardDirs::findExe(QString::fromLatin1("ksh")); if (d->prog.isEmpty()) { d->prog = KStandardDirs::findExe(QString::fromLatin1("ash")); if (d->prog.isEmpty()) { d->prog = KStandardDirs::findExe(QString::fromLatin1("bash")); if (d->prog.isEmpty()) { d->prog = KStandardDirs::findExe(QString::fromLatin1("zsh")); if (d->prog.isEmpty()) // We're pretty much screwed, to be honest ... d->prog = QString::fromLatin1("/bin/sh"); } } } } # else d->prog = QString::fromLatin1("/bin/sh"); # endif d->args << QString::fromLatin1("-c") << cmd; #else // Q_OS_UNIX // KMacroExpander::expandMacrosShellQuote(), KShell::quoteArg() and // KShell::joinArgs() may generate these for security reasons. setEnv(PERCENT_VARIABLE, QLatin1String("%")); #ifndef _WIN32_WCE WCHAR sysdir[MAX_PATH + 1]; UINT size = GetSystemDirectoryW(sysdir, MAX_PATH + 1); d->prog = QString::fromUtf16((const ushort *) sysdir, size); d->prog += QLatin1String("\\cmd.exe"); setNativeArguments(QLatin1String("/V:OFF /S /C \"") + cmd + QLatin1Char('"')); #else d->prog = QLatin1String("\\windows\\cmd.exe"); setNativeArguments(QLatin1String("/S /C \"") + cmd + QLatin1Char('"')); #endif #endif } #endif QStringList KProcess::program() const { Q_D(const KProcess); QStringList argv = d->args; argv.prepend(d->prog); return argv; } void KProcess::start() { Q_D(KProcess); QProcess::start(d->prog, d->args, d->openMode); } int KProcess::execute(int msecs) { start(); if (!waitForFinished(msecs)) { kill(); waitForFinished(-1); return -2; } return (exitStatus() == QProcess::NormalExit) ? exitCode() : -1; } // static int KProcess::execute(const QString &exe, const QStringList &args, int msecs) { KProcess p; p.setProgram(exe, args); return p.execute(msecs); } // static int KProcess::execute(const QStringList &argv, int msecs) { KProcess p; p.setProgram(argv); return p.execute(msecs); } int KProcess::startDetached() { Q_D(KProcess); qint64 pid; if (!QProcess::startDetached(d->prog, d->args, workingDirectory(), &pid)) return 0; return (int) pid; } // static int KProcess::startDetached(const QString &exe, const QStringList &args) { qint64 pid; if (!QProcess::startDetached(exe, args, QString(), &pid)) return 0; return (int) pid; } // static int KProcess::startDetached(const QStringList &argv) { QStringList args = argv; QString prog = args.takeFirst(); return startDetached(prog, args); } int KProcess::pid() const { #ifdef Q_OS_UNIX return (int) QProcess::pid(); #else return QProcess::pid() ? QProcess::pid()->dwProcessId : 0; #endif } deepin-terminal-5.2.11/3rdparty/terminalwidget/lib/kprocess.h000066400000000000000000000264161370157770500242410ustar00rootroot00000000000000/* * This file is a part of QTerminal - http://gitorious.org/qterminal * * This file was un-linked from KDE and modified * by Maxim Bourmistrov * */ /* This file is part of the KDE libraries Copyright (C) 2007 Oswald Buddenhagen This 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; either version 2 of the License, 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. */ #ifndef KPROCESS_H #define KPROCESS_H //#include #include class KProcessPrivate; /** * \class KProcess kprocess.h * * Child process invocation, monitoring and control. * * This class extends QProcess by some useful functionality, overrides * some defaults with saner values and wraps parts of the API into a more * accessible one. * This is the preferred way of spawning child processes in KDE; don't * use QProcess directly. * * @author Oswald Buddenhagen **/ class KProcess : public QProcess { Q_OBJECT Q_DECLARE_PRIVATE(KProcess) public: /** * Modes in which the output channels can be opened. */ enum OutputChannelMode { SeparateChannels = QProcess::SeparateChannels, /**< Standard output and standard error are handled by KProcess as separate channels */ MergedChannels = QProcess::MergedChannels, /**< Standard output and standard error are handled by KProcess as one channel */ ForwardedChannels = QProcess::ForwardedChannels, /**< Both standard output and standard error are forwarded to the parent process' respective channel */ OnlyStdoutChannel, /**< Only standard output is handled; standard error is forwarded */ OnlyStderrChannel /**< Only standard error is handled; standard output is forwarded */ }; /** * Constructor */ explicit KProcess(QObject *parent = nullptr); /** * Destructor */ ~KProcess() override; /** * Set how to handle the output channels of the child process. * * The default is ForwardedChannels, which is unlike in QProcess. * Do not request more than you actually handle, as this output is * simply lost otherwise. * * This function must be called before starting the process. * * @param mode the output channel handling mode */ void setOutputChannelMode(OutputChannelMode mode); /** * Query how the output channels of the child process are handled. * * @return the output channel handling mode */ OutputChannelMode outputChannelMode() const; /** * Set the QIODevice open mode the process will be opened in. * * This function must be called before starting the process, obviously. * * @param mode the open mode. Note that this mode is automatically * "reduced" according to the channel modes and redirections. * The default is QIODevice::ReadWrite. */ void setNextOpenMode(QIODevice::OpenMode mode); /** * Adds the variable @p name to the process' environment. * * This function must be called before starting the process. * * @param name the name of the environment variable * @param value the new value for the environment variable * @param overwrite if @c false and the environment variable is already * set, the old value will be preserved */ void setEnv(const QString &name, const QString &value, bool overwrite = true); /** * Removes the variable @p name from the process' environment. * * This function must be called before starting the process. * * @param name the name of the environment variable */ void unsetEnv(const QString &name); /** * Empties the process' environment. * * Note that LD_LIBRARY_PATH/DYLD_LIBRARY_PATH is automatically added * on *NIX. * * This function must be called before starting the process. */ void clearEnvironment(); /** * Set the program and the command line arguments. * * This function must be called before starting the process, obviously. * * @param exe the program to execute * @param args the command line arguments for the program, * one per list element */ void setProgram(const QString &exe, const QStringList &args = QStringList()); /** * @overload * * @param argv the program to execute and the command line arguments * for the program, one per list element */ void setProgram(const QStringList &argv); /** * Append an element to the command line argument list for this process. * * If no executable is set yet, it will be set instead. * * For example, doing an "ls -l /usr/local/bin" can be achieved by: * \code * KProcess p; * p << "ls" << "-l" << "/usr/local/bin"; * ... * \endcode * * This function must be called before starting the process, obviously. * * @param arg the argument to add * @return a reference to this KProcess */ KProcess &operator<<(const QString& arg); /** * @overload * * @param args the arguments to add * @return a reference to this KProcess */ KProcess &operator<<(const QStringList& args); /** * Clear the program and command line argument list. */ void clearProgram(); /** * Set a command to execute through a shell (a POSIX sh on *NIX * and cmd.exe on Windows). * * Using this for anything but user-supplied commands is usually a bad * idea, as the command's syntax depends on the platform. * Redirections including pipes, etc. are better handled by the * respective functions provided by QProcess. * * If KProcess determines that the command does not really need a * shell, it will trasparently execute it without one for performance * reasons. * * This function must be called before starting the process, obviously. * * @param cmd the command to execute through a shell. * The caller must make sure that all filenames etc. are properly * quoted when passed as argument. Failure to do so often results in * serious security holes. See KShell::quoteArg(). */ void setShellCommand(const QString &cmd); /** * Obtain the currently set program and arguments. * * @return a list, the first element being the program, the remaining ones * being command line arguments to the program. */ QStringList program() const; /** * Start the process. * * @see QProcess::start(const QString &, const QStringList &, OpenMode) */ void start(); /** * Start the process, wait for it to finish, and return the exit code. * * This method is roughly equivalent to the sequence: * * start(); * waitForFinished(msecs); * return exitCode(); * * * Unlike the other execute() variants this method is not static, * so the process can be parametrized properly and talked to. * * @param msecs time to wait for process to exit before killing it * @return -2 if the process could not be started, -1 if it crashed, * otherwise its exit code */ int execute(int msecs = -1); /** * @overload * * @param exe the program to execute * @param args the command line arguments for the program, * one per list element * @param msecs time to wait for process to exit before killing it * @return -2 if the process could not be started, -1 if it crashed, * otherwise its exit code */ static int execute(const QString &exe, const QStringList &args = QStringList(), int msecs = -1); /** * @overload * * @param argv the program to execute and the command line arguments * for the program, one per list element * @param msecs time to wait for process to exit before killing it * @return -2 if the process could not be started, -1 if it crashed, * otherwise its exit code */ static int execute(const QStringList &argv, int msecs = -1); /** * Start the process and detach from it. See QProcess::startDetached() * for details. * * Unlike the other startDetached() variants this method is not static, * so the process can be parametrized properly. * @note Currently, only the setProgram()/setShellCommand() and * setWorkingDirectory() parametrizations are supported. * * The KProcess object may be re-used immediately after calling this * function. * * @return the PID of the started process or 0 on error */ int startDetached(); /** * @overload * * @param exe the program to start * @param args the command line arguments for the program, * one per list element * @return the PID of the started process or 0 on error */ static int startDetached(const QString &exe, const QStringList &args = QStringList()); /** * @overload * * @param argv the program to start and the command line arguments * for the program, one per list element * @return the PID of the started process or 0 on error */ static int startDetached(const QStringList &argv); /** * Obtain the process' ID as known to the system. * * Unlike with QProcess::pid(), this is a real PID also on Windows. * * This function can be called only while the process is running. * It cannot be applied to detached processes. * * @return the process ID */ int pid() const; protected: /** * @internal */ KProcess(KProcessPrivate *d, QObject *parent); /** * @internal */ KProcessPrivate * const d_ptr; private: // hide those using QProcess::setReadChannelMode; using QProcess::readChannelMode; using QProcess::setProcessChannelMode; using QProcess::processChannelMode; Q_PRIVATE_SLOT(d_func(), void _k_forwardStdout()) Q_PRIVATE_SLOT(d_func(), void _k_forwardStderr()) }; /* ----------- kprocess_p.h ---------------- */ class KProcessPrivate { Q_DECLARE_PUBLIC(KProcess) protected: KProcessPrivate() : openMode(QIODevice::ReadWrite) { } virtual ~KProcessPrivate() { } void writeAll(const QByteArray &buf, int fd); void forwardStd(KProcess::ProcessChannel good, int fd); void _k_forwardStdout(); void _k_forwardStderr(); QString prog; QStringList args; KProcess::OutputChannelMode outputChannelMode; QIODevice::OpenMode openMode; KProcess *q_ptr; }; /* ------------------------------------------- */ #endif deepin-terminal-5.2.11/3rdparty/terminalwidget/lib/kpty.cpp000066400000000000000000000415741370157770500237340ustar00rootroot00000000000000/* This file is part of the KDE libraries Copyright (C) 2002 Waldo Bastian Copyright (C) 2002-2003,2007 Oswald Buddenhagen Rewritten for QT4 by e_k , Copyright (C)2008 This 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; either version 2 of the License, 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. */ #include "kpty_p.h" #include #if defined(__FreeBSD__) || defined(__DragonFly__) #define HAVE_LOGIN #define HAVE_LIBUTIL_H #endif #if defined(__OpenBSD__) #define HAVE_LOGIN #define HAVE_UTIL_H #endif #if defined(__NetBSD__) #define HAVE_LOGIN #define HAVE_UTIL_H #define HAVE_OPENPTY #endif #if defined(__APPLE__) #define HAVE_OPENPTY #define HAVE_UTIL_H #endif #ifdef __sgi #define __svr4__ #endif #ifdef __osf__ #define _OSF_SOURCE #include #endif #ifdef _AIX #define _ALL_SOURCE #endif // __USE_XOPEN isn't defined by default in ICC // (needed for ptsname(), grantpt() and unlockpt()) #ifdef __INTEL_COMPILER # ifndef __USE_XOPEN # define __USE_XOPEN # endif #endif #include #include #include #include #include #include #include #include #include #include #include #include #include #include #if defined(HAVE_PTY_H) # include #endif #ifdef HAVE_LIBUTIL_H # include #elif defined(HAVE_UTIL_H) # include #endif #ifdef HAVE_UTEMPTER extern "C" { # include } #else # include # ifdef HAVE_UTMPX # include # endif # if !defined(_PATH_UTMPX) && defined(_UTMPX_FILE) # define _PATH_UTMPX _UTMPX_FILE # endif # ifdef HAVE_UPDWTMPX # if !defined(_PATH_WTMPX) && defined(_WTMPX_FILE) # define _PATH_WTMPX _WTMPX_FILE # endif # endif #endif /* for HP-UX (some versions) the extern C is needed, and for other platforms it doesn't hurt */ extern "C" { #include #if defined(HAVE_TERMIO_H) # include // struct winsize on some systems #endif } #if defined (_HPUX_SOURCE) # define _TERMIOS_INCLUDED # include #endif #ifdef HAVE_SYS_STROPTS_H # include // Defines I_PUSH # define _NEW_TTY_CTRL #endif #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__) || defined (__NetBSD__) || defined (__OpenBSD__) || defined (__bsdi__) || defined(__APPLE__) || defined (__DragonFly__) # define _tcgetattr(fd, ttmode) ioctl(fd, TIOCGETA, (char *)ttmode) #else # if defined(_HPUX_SOURCE) || defined(__Lynx__) || defined (__CYGWIN__) || defined(__GNU__) # define _tcgetattr(fd, ttmode) tcgetattr(fd, ttmode) # else # define _tcgetattr(fd, ttmode) ioctl(fd, TCGETS, (char *)ttmode) # endif #endif #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__) || defined (__NetBSD__) || defined (__OpenBSD__) || defined (__bsdi__) || defined(__APPLE__) || defined (__DragonFly__) # define _tcsetattr(fd, ttmode) ioctl(fd, TIOCSETA, (char *)ttmode) #else # if defined(_HPUX_SOURCE) || defined(__CYGWIN__) || defined(__GNU__) # define _tcsetattr(fd, ttmode) tcsetattr(fd, TCSANOW, ttmode) # else # define _tcsetattr(fd, ttmode) ioctl(fd, TCSETS, (char *)ttmode) # endif #endif //#include //#include // findExe // not defined on HP-UX for example #ifndef CTRL # define CTRL(x) ((x) & 037) #endif #define TTY_GROUP "tty" /////////////////////// // private functions // /////////////////////// ////////////////// // private data // ////////////////// KPtyPrivate::KPtyPrivate(KPty* parent) : masterFd(-1), slaveFd(-1), ownMaster(true), q_ptr(parent) { } KPtyPrivate::~KPtyPrivate() { } bool KPtyPrivate::chownpty(bool) { // return !QProcess::execute(KStandardDirs::findExe("kgrantpty"), // QStringList() << (grant?"--grant":"--revoke") << QString::number(masterFd)); return true; } ///////////////////////////// // public member functions // ///////////////////////////// KPty::KPty() : d_ptr(new KPtyPrivate(this)) { } KPty::KPty(KPtyPrivate *d) : d_ptr(d) { d_ptr->q_ptr = this; } KPty::~KPty() { close(); delete d_ptr; } bool KPty::open() { Q_D(KPty); if (d->masterFd >= 0) return true; d->ownMaster = true; QByteArray ptyName; // Find a master pty that we can open //////////////////////////////// // Because not all the pty animals are created equal, they want to // be opened by several different methods. // We try, as we know them, one by one. #ifdef HAVE_OPENPTY char ptsn[PATH_MAX]; if (::openpty( &d->masterFd, &d->slaveFd, ptsn, 0, 0)) { d->masterFd = -1; d->slaveFd = -1; qWarning() << "Can't open a pseudo teletype"; return false; } d->ttyName = ptsn; #else #ifdef HAVE__GETPTY // irix char *ptsn = _getpty(&d->masterFd, O_RDWR|O_NOCTTY, S_IRUSR|S_IWUSR, 0); if (ptsn) { d->ttyName = ptsn; goto grantedpt; } #elif defined(HAVE_PTSNAME) || defined(TIOCGPTN) #ifdef HAVE_POSIX_OPENPT d->masterFd = ::posix_openpt(O_RDWR|O_NOCTTY); #elif defined(HAVE_GETPT) d->masterFd = ::getpt(); #elif defined(PTM_DEVICE) d->masterFd = ::open(PTM_DEVICE, O_RDWR|O_NOCTTY); #else # error No method to open a PTY master detected. #endif if (d->masterFd >= 0) { #ifdef HAVE_PTSNAME char *ptsn = ptsname(d->masterFd); if (ptsn) { d->ttyName = ptsn; #else int ptyno; if (!ioctl(d->masterFd, TIOCGPTN, &ptyno)) { d->ttyName = QByteArray("/dev/pts/") + QByteArray::number(ptyno); #endif #ifdef HAVE_GRANTPT if (!grantpt(d->masterFd)) { goto grantedpt; } #else goto gotpty; #endif } ::close(d->masterFd); d->masterFd = -1; } #endif // HAVE_PTSNAME || TIOCGPTN // Linux device names, FIXME: Trouble on other systems? for (const char * s3 = "pqrstuvwxyzabcde"; *s3; s3++) { for (const char * s4 = "0123456789abcdef"; *s4; s4++) { ptyName = QByteArrayLiteral("/dev/pty") + *s3 + *s4; d->ttyName = QByteArrayLiteral("/dev/tty") + *s3 + *s4; d->masterFd = ::open(ptyName.data(), O_RDWR); if (d->masterFd >= 0) { #ifdef Q_OS_SOLARIS /* Need to check the process group of the pty. * If it exists, then the slave pty is in use, * and we need to get another one. */ int pgrp_rtn; if (ioctl(d->masterFd, TIOCGPGRP, &pgrp_rtn) == 0 || errno != EIO) { ::close(d->masterFd); d->masterFd = -1; continue; } #endif /* Q_OS_SOLARIS */ if (!access(d->ttyName.data(),R_OK|W_OK)) { // checks availability based on permission bits if (!geteuid()) { struct group * p = getgrnam(TTY_GROUP); if (!p) { p = getgrnam("wheel"); } gid_t gid = p ? p->gr_gid : getgid (); if (!chown(d->ttyName.data(), getuid(), gid)) { chmod(d->ttyName.data(), S_IRUSR|S_IWUSR|S_IWGRP); } } goto gotpty; } ::close(d->masterFd); d->masterFd = -1; } } } qWarning() << "Can't open a pseudo teletype"; return false; gotpty: struct stat st; if (stat(d->ttyName.data(), &st)) { return false; // this just cannot happen ... *cough* Yeah right, I just // had it happen when pty #349 was allocated. I guess // there was some sort of leak? I only had a few open. } if (((st.st_uid != getuid()) || (st.st_mode & (S_IRGRP|S_IXGRP|S_IROTH|S_IWOTH|S_IXOTH))) && !d->chownpty(true)) { qWarning() << "chownpty failed for device " << ptyName << "::" << d->ttyName << "\nThis means the communication can be eavesdropped." << endl; } #if defined (HAVE__GETPTY) || defined (HAVE_GRANTPT) grantedpt: #endif #ifdef HAVE_REVOKE revoke(d->ttyName.data()); #endif #ifdef HAVE_UNLOCKPT unlockpt(d->masterFd); #elif defined(TIOCSPTLCK) int flag = 0; ioctl(d->masterFd, TIOCSPTLCK, &flag); #endif d->slaveFd = ::open(d->ttyName.data(), O_RDWR | O_NOCTTY); if (d->slaveFd < 0) { qWarning() << "Can't open slave pseudo teletype"; ::close(d->masterFd); d->masterFd = -1; return false; } #if (defined(__svr4__) || defined(__sgi__)) // Solaris ioctl(d->slaveFd, I_PUSH, "ptem"); ioctl(d->slaveFd, I_PUSH, "ldterm"); #endif #endif /* HAVE_OPENPTY */ fcntl(d->masterFd, F_SETFD, FD_CLOEXEC); fcntl(d->slaveFd, F_SETFD, FD_CLOEXEC); return true; } bool KPty::open(int fd) { #if !defined(HAVE_PTSNAME) && !defined(TIOCGPTN) qWarning() << "Unsupported attempt to open pty with fd" << fd; return false; #else Q_D(KPty); if (d->masterFd >= 0) { qWarning() << "Attempting to open an already open pty"; return false; } d->ownMaster = false; # ifdef HAVE_PTSNAME char *ptsn = ptsname(fd); if (ptsn) { d->ttyName = ptsn; # else int ptyno; if (!ioctl(fd, TIOCGPTN, &ptyno)) { const size_t sz = 32; char buf[sz]; const size_t r = snprintf(buf, sz, "/dev/pts/%d", ptyno); if (sz <= r) { qWarning("KPty::open: Buffer too small\n"); } d->ttyName = buf; # endif } else { qWarning() << "Failed to determine pty slave device for fd" << fd; return false; } d->masterFd = fd; if (!openSlave()) { d->masterFd = -1; return false; } return true; #endif } void KPty::closeSlave() { Q_D(KPty); if (d->slaveFd < 0) { return; } ::close(d->slaveFd); d->slaveFd = -1; } bool KPty::openSlave() { Q_D(KPty); if (d->slaveFd >= 0) return true; if (d->masterFd < 0) { qDebug() << "Attempting to open pty slave while master is closed"; return false; } //d->slaveFd = KDE_open(d->ttyName.data(), O_RDWR | O_NOCTTY); d->slaveFd = ::open(d->ttyName.data(), O_RDWR | O_NOCTTY); if (d->slaveFd < 0) { qDebug() << "Can't open slave pseudo teletype"; return false; } fcntl(d->slaveFd, F_SETFD, FD_CLOEXEC); return true; } void KPty::close() { Q_D(KPty); if (d->masterFd < 0) { return; } closeSlave(); // don't bother resetting unix98 pty, it will go away after closing master anyway. if (memcmp(d->ttyName.data(), "/dev/pts/", 9)) { if (!geteuid()) { struct stat st; if (!stat(d->ttyName.data(), &st)) { chown(d->ttyName.data(), 0, st.st_gid == getgid() ? 0 : -1); chmod(d->ttyName.data(), S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP|S_IROTH|S_IWOTH); } } else { fcntl(d->masterFd, F_SETFD, 0); d->chownpty(false); } } ::close(d->masterFd); d->masterFd = -1; } void KPty::setCTty() { Q_D(KPty); // Setup job control ////////////////////////////////// // Become session leader, process group leader, // and get rid of the old controlling terminal. setsid(); // make our slave pty the new controlling terminal. #ifdef TIOCSCTTY ioctl(d->slaveFd, TIOCSCTTY, 0); #else // __svr4__ hack: the first tty opened after setsid() becomes controlling tty ::close(::open(d->ttyName, O_WRONLY, 0)); #endif // make our new process group the foreground group on the pty int pgrp = getpid(); #if defined(_POSIX_VERSION) || defined(__svr4__) tcsetpgrp(d->slaveFd, pgrp); #elif defined(TIOCSPGRP) ioctl(d->slaveFd, TIOCSPGRP, (char *)&pgrp); #endif } void KPty::login(const char * user, const char * remotehost) { #ifdef HAVE_UTEMPTER Q_D(KPty); addToUtmp(d->ttyName.constData(), remotehost, d->masterFd); Q_UNUSED(user); #else # ifdef HAVE_UTMPX struct utmpx l_struct; # else struct utmp l_struct; # endif memset(&l_struct, 0, sizeof(l_struct)); // note: strncpy without terminators _is_ correct here. man 4 utmp if (user) { # ifdef HAVE_UTMPX strncpy(l_struct.ut_user, user, sizeof(l_struct.ut_user)); # else strncpy(l_struct.ut_name, user, sizeof(l_struct.ut_name)); # endif } if (remotehost) { strncpy(l_struct.ut_host, remotehost, sizeof(l_struct.ut_host)); # ifdef HAVE_STRUCT_UTMP_UT_SYSLEN l_struct.ut_syslen = qMin(strlen(remotehost), sizeof(l_struct.ut_host)); # endif } # ifndef __GLIBC__ Q_D(KPty); const char * str_ptr = d->ttyName.data(); if (!memcmp(str_ptr, "/dev/", 5)) { str_ptr += 5; } strncpy(l_struct.ut_line, str_ptr, sizeof(l_struct.ut_line)); # ifdef HAVE_STRUCT_UTMP_UT_ID strncpy(l_struct.ut_id, str_ptr + strlen(str_ptr) - sizeof(l_struct.ut_id), sizeof(l_struct.ut_id)); # endif # endif # ifdef HAVE_UTMPX gettimeofday(&l_struct.ut_tv, 0); # else l_struct.ut_time = time(nullptr); # endif # ifdef HAVE_LOGIN # ifdef HAVE_LOGINX ::loginx(&l_struct); # else ::login(&l_struct); # endif # else # ifdef HAVE_STRUCT_UTMP_UT_TYPE l_struct.ut_type = USER_PROCESS; # endif # ifdef HAVE_STRUCT_UTMP_UT_PID l_struct.ut_pid = getpid(); # ifdef HAVE_STRUCT_UTMP_UT_SESSION l_struct.ut_session = getsid(0); # endif # endif # ifdef HAVE_UTMPX utmpxname(_PATH_UTMPX); setutxent(); pututxline(&l_struct); endutxent(); # ifdef HAVE_UPDWTMPX updwtmpx(_PATH_WTMPX, &l_struct); # endif # else utmpname(_PATH_UTMP); setutent(); pututline(&l_struct); endutent(); updwtmp(_PATH_WTMP, &l_struct); # endif # endif #endif } void KPty::logout() { #ifdef HAVE_UTEMPTER Q_D(KPty); removeLineFromUtmp(d->ttyName.constData(), d->masterFd); #else Q_D(KPty); const char *str_ptr = d->ttyName.data(); if (!memcmp(str_ptr, "/dev/", 5)) { str_ptr += 5; } # ifdef __GLIBC__ else { const char * sl_ptr = strrchr(str_ptr, '/'); if (sl_ptr) { str_ptr = sl_ptr + 1; } } # endif # ifdef HAVE_LOGIN # ifdef HAVE_LOGINX ::logoutx(str_ptr, 0, DEAD_PROCESS); # else ::logout(str_ptr); # endif # else # ifdef HAVE_UTMPX struct utmpx l_struct, *ut; # else struct utmp l_struct, *ut; # endif memset(&l_struct, 0, sizeof(l_struct)); strncpy(l_struct.ut_line, str_ptr, sizeof(l_struct.ut_line)); # ifdef HAVE_UTMPX utmpxname(_PATH_UTMPX); setutxent(); if ((ut = getutxline(&l_struct))) { # else utmpname(_PATH_UTMP); setutent(); if ((ut = getutline(&l_struct))) { # endif # ifdef HAVE_UTMPX memset(ut->ut_user, 0, sizeof(*ut->ut_user)); # else memset(ut->ut_name, 0, sizeof(*ut->ut_name)); # endif memset(ut->ut_host, 0, sizeof(*ut->ut_host)); # ifdef HAVE_STRUCT_UTMP_UT_SYSLEN ut->ut_syslen = 0; # endif # ifdef HAVE_STRUCT_UTMP_UT_TYPE ut->ut_type = DEAD_PROCESS; # endif # ifdef HAVE_UTMPX gettimeofday(&ut->ut_tv, 0); pututxline(ut); } endutxent(); # else ut->ut_time = time(nullptr); pututline(ut); } endutent(); # endif # endif #endif } // XXX Supposedly, tc[gs]etattr do not work with the master on Solaris. // Please verify. bool KPty::tcGetAttr(struct ::termios * ttmode) const { Q_D(const KPty); return _tcgetattr(d->masterFd, ttmode) == 0; } bool KPty::tcSetAttr(struct ::termios * ttmode) { Q_D(KPty); return _tcsetattr(d->masterFd, ttmode) == 0; } bool KPty::setWinSize(int lines, int columns) { Q_D(KPty); struct winsize winSize; memset(&winSize, 0, sizeof(winSize)); winSize.ws_row = (unsigned short)lines; winSize.ws_col = (unsigned short)columns; return ioctl(d->masterFd, TIOCSWINSZ, (char *)&winSize) == 0; } bool KPty::setEcho(bool echo) { struct ::termios ttmode; if (!tcGetAttr(&ttmode)) { return false; } if (!echo) { ttmode.c_lflag &= ~ECHO; } else { ttmode.c_lflag |= ECHO; } return tcSetAttr(&ttmode); } const char * KPty::ttyName() const { Q_D(const KPty); return d->ttyName.data(); } int KPty::masterFd() const { Q_D(const KPty); return d->masterFd; } int KPty::slaveFd() const { Q_D(const KPty); return d->slaveFd; } deepin-terminal-5.2.11/3rdparty/terminalwidget/lib/kpty.h000066400000000000000000000125671370157770500234010ustar00rootroot00000000000000/* This file is part of the KDE libraries Copyright (C) 2003,2007 Oswald Buddenhagen Rewritten for QT4 by e_k , Copyright (C)2008 This 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; either version 2 of the License, 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. */ #ifndef kpty_h #define kpty_h #include class KPtyPrivate; struct termios; /** * Provides primitives for opening & closing a pseudo TTY pair, assigning the * controlling TTY, utmp registration and setting various terminal attributes. */ class KPty { Q_DECLARE_PRIVATE(KPty) public: /** * Constructor */ KPty(); /** * Destructor: * * If the pty is still open, it will be closed. Note, however, that * an utmp registration is @em not undone. */ ~KPty(); /** * Create a pty master/slave pair. * * @return true if a pty pair was successfully opened */ bool open(); bool open(int fd); /** * Close the pty master/slave pair. */ void close(); /** * Close the pty slave descriptor. * * When creating the pty, KPty also opens the slave and keeps it open. * Consequently the master will never receive an EOF notification. * Usually this is the desired behavior, as a closed pty slave can be * reopened any time - unlike a pipe or socket. However, in some cases * pipe-alike behavior might be desired. * * After this function was called, slaveFd() and setCTty() cannot be * used. */ void closeSlave(); bool openSlave(); /** * Creates a new session and process group and makes this pty the * controlling tty. */ void setCTty(); /** * Creates an utmp entry for the tty. * This function must be called after calling setCTty and * making this pty the stdin. * @param user the user to be logged on * @param remotehost the host from which the login is coming. This is * @em not the local host. For remote logins it should be the hostname * of the client. For local logins from inside an X session it should * be the name of the X display. Otherwise it should be empty. */ void login(const char * user = nullptr, const char * remotehost = nullptr); /** * Removes the utmp entry for this tty. */ void logout(); /** * Wrapper around tcgetattr(3). * * This function can be used only while the PTY is open. * You will need an #include <termios.h> to do anything useful * with it. * * @param ttmode a pointer to a termios structure. * Note: when declaring ttmode, @c struct @c ::termios must be used - * without the '::' some version of HP-UX thinks, this declares * the struct in your class, in your method. * @return @c true on success, false otherwise */ bool tcGetAttr(struct ::termios * ttmode) const; /** * Wrapper around tcsetattr(3) with mode TCSANOW. * * This function can be used only while the PTY is open. * * @param ttmode a pointer to a termios structure. * @return @c true on success, false otherwise. Note that success means * that @em at @em least @em one attribute could be set. */ bool tcSetAttr(struct ::termios * ttmode); /** * Change the logical (screen) size of the pty. * The default is 24 lines by 80 columns. * * This function can be used only while the PTY is open. * * @param lines the number of rows * @param columns the number of columns * @return @c true on success, false otherwise */ bool setWinSize(int lines, int columns); /** * Set whether the pty should echo input. * * Echo is on by default. * If the output of automatically fed (non-interactive) PTY clients * needs to be parsed, disabling echo often makes it much simpler. * * This function can be used only while the PTY is open. * * @param echo true if input should be echoed. * @return @c true on success, false otherwise */ bool setEcho(bool echo); /** * @return the name of the slave pty device. * * This function should be called only while the pty is open. */ const char * ttyName() const; /** * @return the file descriptor of the master pty * * This function should be called only while the pty is open. */ int masterFd() const; /** * @return the file descriptor of the slave pty * * This function should be called only while the pty slave is open. */ int slaveFd() const; protected: /** * @internal */ KPty(KPtyPrivate * d); /** * @internal */ KPtyPrivate * const d_ptr; }; #endif deepin-terminal-5.2.11/3rdparty/terminalwidget/lib/kpty_p.h000066400000000000000000000024331370157770500237070ustar00rootroot00000000000000/* This file is part of the KDE libraries Copyright (C) 2003,2007 Oswald Buddenhagen Rewritten for QT4 by e_k , Copyright (C)2008 This 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; either version 2 of the License, 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. */ #ifndef kpty_p_h #define kpty_p_h #include "kpty.h" #include class KPtyPrivate { public: Q_DECLARE_PUBLIC(KPty) KPtyPrivate(KPty* parent); virtual ~KPtyPrivate(); bool chownpty(bool grant); int masterFd; int slaveFd; bool ownMaster:1; QByteArray ttyName; KPty *q_ptr; }; #endif deepin-terminal-5.2.11/3rdparty/terminalwidget/lib/kptydevice.cpp000066400000000000000000000252531370157770500251100ustar00rootroot00000000000000/* * This file is a part of QTerminal - http://gitorious.org/qterminal * * This file was un-linked from KDE and modified * by Maxim Bourmistrov * */ /* This file is part of the KDE libraries Copyright (C) 2007 Oswald Buddenhagen Copyright (C) 2010 KDE e.V. Author Adriaan de Groot This 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; either version 2 of the License, 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. */ #include "kptydevice.h" #include "kpty_p.h" #include #include #include #include #include #include #include #ifdef HAVE_SYS_FILIO_H # include #endif #ifdef HAVE_SYS_TIME_H # include #endif #if defined(Q_OS_FREEBSD) || defined(Q_OS_MAC) // "the other end's output queue size" - kinda braindead, huh? # define PTY_BYTES_AVAILABLE TIOCOUTQ #elif defined(TIOCINQ) // "our end's input queue size" # define PTY_BYTES_AVAILABLE TIOCINQ #else // likewise. more generic ioctl (theoretically) # define PTY_BYTES_AVAILABLE FIONREAD #endif ////////////////// // private data // ////////////////// // Lifted from Qt. I don't think they would mind. ;) // Re-lift again from Qt whenever a proper replacement for pthread_once appears static void qt_ignore_sigpipe() { static QBasicAtomicInt atom = Q_BASIC_ATOMIC_INITIALIZER(0); if (atom.testAndSetRelaxed(0, 1)) { struct sigaction noaction; memset(&noaction, 0, sizeof(noaction)); noaction.sa_handler = SIG_IGN; sigaction(SIGPIPE, &noaction, nullptr); } } #define NO_INTR(ret,func) do { ret = func; } while (ret < 0 && errno == EINTR) bool KPtyDevicePrivate::_k_canRead() { Q_Q(KPtyDevice); qint64 readBytes = 0; #ifdef Q_OS_IRIX // this should use a config define, but how to check it? size_t available; #else int available; #endif if (!::ioctl(q->masterFd(), PTY_BYTES_AVAILABLE, (char *) &available)) { #ifdef Q_OS_SOLARIS // A Pty is a STREAMS module, and those can be activated // with 0 bytes available. This happens either when ^C is // pressed, or when an application does an explicit write(a,b,0) // which happens in experiments fairly often. When 0 bytes are // available, you must read those 0 bytes to clear the STREAMS // module, but we don't want to hit the !readBytes case further down. if (!available) { char c; // Read the 0-byte STREAMS message NO_INTR(readBytes, read(q->masterFd(), &c, 0)); // Should return 0 bytes read; -1 is error if (readBytes < 0) { readNotifier->setEnabled(false); emit q->readEof(); return false; } return true; } #endif char *ptr = readBuffer.reserve(available); #ifdef Q_OS_SOLARIS // Even if available > 0, it is possible for read() // to return 0 on Solaris, due to 0-byte writes in the stream. // Ignore them and keep reading until we hit *some* data. // In Solaris it is possible to have 15 bytes available // and to (say) get 0, 0, 6, 0 and 9 bytes in subsequent reads. // Because the stream is set to O_NONBLOCK in finishOpen(), // an EOF read will return -1. readBytes = 0; while (!readBytes) #endif // Useless block braces except in Solaris { NO_INTR(readBytes, read(q->masterFd(), ptr, available)); } if (readBytes < 0) { readBuffer.unreserve(available); q->setErrorString(QLatin1String("Error reading from PTY")); return false; } readBuffer.unreserve(available - readBytes); // *should* be a no-op } if (!readBytes) { readNotifier->setEnabled(false); emit q->readEof(); return false; } else { if (!emittedReadyRead) { emittedReadyRead = true; emit q->readyRead(); emittedReadyRead = false; } return true; } } bool KPtyDevicePrivate::_k_canWrite() { Q_Q(KPtyDevice); writeNotifier->setEnabled(false); if (writeBuffer.isEmpty()) return false; qt_ignore_sigpipe(); int wroteBytes; NO_INTR(wroteBytes, write(q->masterFd(), writeBuffer.readPointer(), writeBuffer.readSize())); if (wroteBytes < 0) { q->setErrorString(QLatin1String("Error writing to PTY")); return false; } writeBuffer.free(wroteBytes); if (!emittedBytesWritten) { emittedBytesWritten = true; emit q->bytesWritten(wroteBytes); emittedBytesWritten = false; } if (!writeBuffer.isEmpty()) writeNotifier->setEnabled(true); return true; } #ifndef timeradd // Lifted from GLIBC # define timeradd(a, b, result) \ do { \ (result)->tv_sec = (a)->tv_sec + (b)->tv_sec; \ (result)->tv_usec = (a)->tv_usec + (b)->tv_usec; \ if ((result)->tv_usec >= 1000000) { \ ++(result)->tv_sec; \ (result)->tv_usec -= 1000000; \ } \ } while (0) # define timersub(a, b, result) \ do { \ (result)->tv_sec = (a)->tv_sec - (b)->tv_sec; \ (result)->tv_usec = (a)->tv_usec - (b)->tv_usec; \ if ((result)->tv_usec < 0) { \ --(result)->tv_sec; \ (result)->tv_usec += 1000000; \ } \ } while (0) #endif bool KPtyDevicePrivate::doWait(int msecs, bool reading) { Q_Q(KPtyDevice); #ifndef __linux__ struct timeval etv; #endif struct timeval tv, *tvp; if (msecs < 0) tvp = nullptr; else { tv.tv_sec = msecs / 1000; tv.tv_usec = (msecs % 1000) * 1000; #ifndef __linux__ gettimeofday(&etv, 0); timeradd(&tv, &etv, &etv); #endif tvp = &tv; } while (reading ? readNotifier->isEnabled() : !writeBuffer.isEmpty()) { fd_set rfds; fd_set wfds; FD_ZERO(&rfds); FD_ZERO(&wfds); if (readNotifier->isEnabled()) FD_SET(q->masterFd(), &rfds); if (!writeBuffer.isEmpty()) FD_SET(q->masterFd(), &wfds); #ifndef __linux__ if (tvp) { gettimeofday(&tv, 0); timersub(&etv, &tv, &tv); if (tv.tv_sec < 0) tv.tv_sec = tv.tv_usec = 0; } #endif switch (select(q->masterFd() + 1, &rfds, &wfds, nullptr, tvp)) { case -1: if (errno == EINTR) break; return false; case 0: q->setErrorString(QLatin1String("PTY operation timed out")); return false; default: if (FD_ISSET(q->masterFd(), &rfds)) { bool canRead = _k_canRead(); if (reading && canRead) return true; } if (FD_ISSET(q->masterFd(), &wfds)) { bool canWrite = _k_canWrite(); if (!reading) return canWrite; } break; } } return false; } void KPtyDevicePrivate::finishOpen(QIODevice::OpenMode mode) { Q_Q(KPtyDevice); q->QIODevice::open(mode); fcntl(q->masterFd(), F_SETFL, O_NONBLOCK); readBuffer.clear(); readNotifier = new QSocketNotifier(q->masterFd(), QSocketNotifier::Read, q); writeNotifier = new QSocketNotifier(q->masterFd(), QSocketNotifier::Write, q); QObject::connect(readNotifier, SIGNAL(activated(int)), q, SLOT(_k_canRead())); QObject::connect(writeNotifier, SIGNAL(activated(int)), q, SLOT(_k_canWrite())); readNotifier->setEnabled(true); } ///////////////////////////// // public member functions // ///////////////////////////// KPtyDevice::KPtyDevice(QObject *parent) : QIODevice(parent), KPty(new KPtyDevicePrivate(this)) { } KPtyDevice::~KPtyDevice() { close(); } bool KPtyDevice::open(OpenMode mode) { Q_D(KPtyDevice); if (masterFd() >= 0) return true; if (!KPty::open()) { setErrorString(QLatin1String("Error opening PTY")); return false; } d->finishOpen(mode); return true; } bool KPtyDevice::open(int fd, OpenMode mode) { Q_D(KPtyDevice); if (!KPty::open(fd)) { setErrorString(QLatin1String("Error opening PTY")); return false; } d->finishOpen(mode); return true; } void KPtyDevice::close() { Q_D(KPtyDevice); if (masterFd() < 0) return; delete d->readNotifier; delete d->writeNotifier; QIODevice::close(); KPty::close(); } bool KPtyDevice::isSequential() const { return true; } bool KPtyDevice::canReadLine() const { Q_D(const KPtyDevice); return QIODevice::canReadLine() || d->readBuffer.canReadLine(); } bool KPtyDevice::atEnd() const { Q_D(const KPtyDevice); return QIODevice::atEnd() && d->readBuffer.isEmpty(); } qint64 KPtyDevice::bytesAvailable() const { Q_D(const KPtyDevice); return QIODevice::bytesAvailable() + d->readBuffer.size(); } qint64 KPtyDevice::bytesToWrite() const { Q_D(const KPtyDevice); return d->writeBuffer.size(); } bool KPtyDevice::waitForReadyRead(int msecs) { Q_D(KPtyDevice); return d->doWait(msecs, true); } bool KPtyDevice::waitForBytesWritten(int msecs) { Q_D(KPtyDevice); return d->doWait(msecs, false); } void KPtyDevice::setSuspended(bool suspended) { Q_D(KPtyDevice); d->readNotifier->setEnabled(!suspended); } bool KPtyDevice::isSuspended() const { Q_D(const KPtyDevice); return !d->readNotifier->isEnabled(); } // protected qint64 KPtyDevice::readData(char *data, qint64 maxlen) { Q_D(KPtyDevice); return d->readBuffer.read(data, (int)qMin(maxlen, KMAXINT)); } // protected qint64 KPtyDevice::readLineData(char *data, qint64 maxlen) { Q_D(KPtyDevice); return d->readBuffer.readLine(data, (int)qMin(maxlen, KMAXINT)); } // protected qint64 KPtyDevice::writeData(const char *data, qint64 len) { Q_D(KPtyDevice); Q_ASSERT(len <= KMAXINT); d->writeBuffer.write(data, len); d->writeNotifier->setEnabled(true); return len; } deepin-terminal-5.2.11/3rdparty/terminalwidget/lib/kptydevice.h000066400000000000000000000222131370157770500245460ustar00rootroot00000000000000/* * This file is a part of QTerminal - http://gitorious.org/qterminal * * This file was un-linked from KDE and modified * by Maxim Bourmistrov * */ /* This file is part of the KDE libraries Copyright (C) 2007 Oswald Buddenhagen This 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; either version 2 of the License, 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. */ #ifndef kptydev_h #define kptydev_h #include "kpty_p.h" #include #define KMAXINT ((int)(~0U >> 1)) struct KPtyDevicePrivate; class QSocketNotifier; #define Q_DECLARE_PRIVATE_MI(Class, SuperClass) \ inline Class##Private* d_func() { return reinterpret_cast(SuperClass::d_ptr); } \ inline const Class##Private* d_func() const { return reinterpret_cast(SuperClass::d_ptr); } \ friend struct Class##Private; /** * Encapsulates KPty into a QIODevice, so it can be used with Q*Stream, etc. */ class KPtyDevice : public QIODevice, public KPty { Q_OBJECT Q_DECLARE_PRIVATE_MI(KPtyDevice, KPty) public: /** * Constructor */ KPtyDevice(QObject *parent = nullptr); /** * Destructor: * * If the pty is still open, it will be closed. Note, however, that * an utmp registration is @em not undone. */ ~KPtyDevice() override; /** * Create a pty master/slave pair. * * @return true if a pty pair was successfully opened */ bool open(OpenMode mode = ReadWrite | Unbuffered) override; /** * Open using an existing pty master. The ownership of the fd * remains with the caller, i.e., close() will not close the fd. * * This is useful if you wish to attach a secondary "controller" to an * existing pty device such as a terminal widget. * Note that you will need to use setSuspended() on both devices to * control which one gets the incoming data from the pty. * * @param fd an open pty master file descriptor. * @param mode the device mode to open the pty with. * @return true if a pty pair was successfully opened */ bool open(int fd, OpenMode mode = ReadWrite | Unbuffered); /** * Close the pty master/slave pair. */ void close() override; /** * Sets whether the KPtyDevice monitors the pty for incoming data. * * When the KPtyDevice is suspended, it will no longer attempt to buffer * data that becomes available from the pty and it will not emit any * signals. * * Do not use on closed ptys. * After a call to open(), the pty is not suspended. If you need to * ensure that no data is read, call this function before the main loop * is entered again (i.e., immediately after opening the pty). */ void setSuspended(bool suspended); /** * Returns true if the KPtyDevice is not monitoring the pty for incoming * data. * * Do not use on closed ptys. * * See setSuspended() */ bool isSuspended() const; /** * @return always true */ bool isSequential() const override; /** * @reimp */ bool canReadLine() const override; /** * @reimp */ bool atEnd() const override; /** * @reimp */ qint64 bytesAvailable() const override; /** * @reimp */ qint64 bytesToWrite() const override; bool waitForBytesWritten(int msecs = -1) override; bool waitForReadyRead(int msecs = -1) override; Q_SIGNALS: /** * Emitted when EOF is read from the PTY. * * Data may still remain in the buffers. */ void readEof(); protected: qint64 readData(char *data, qint64 maxSize) override; qint64 readLineData(char *data, qint64 maxSize) override; qint64 writeData(const char *data, qint64 maxSize) override; private: Q_PRIVATE_SLOT(d_func(), bool _k_canRead()) Q_PRIVATE_SLOT(d_func(), bool _k_canWrite()) }; ///////////////////////////////////////////////////// // Helper. Remove when QRingBuffer becomes public. // ///////////////////////////////////////////////////// #include #include #define CHUNKSIZE 4096 class KRingBuffer { public: KRingBuffer() { clear(); } void clear() { buffers.clear(); QByteArray tmp; tmp.resize(CHUNKSIZE); buffers.push_back(tmp); head = tail = 0; totalSize = 0; } inline bool isEmpty() const { return buffers.size() == 1 && !tail; } inline int size() const { return totalSize; } inline int readSize() const { return (buffers.size() == 1 ? tail : buffers.front().size()) - head; } inline const char *readPointer() const { Q_ASSERT(totalSize > 0); return buffers.front().constData() + head; } void free(int bytes) { totalSize -= bytes; Q_ASSERT(totalSize >= 0); forever { int nbs = readSize(); if (bytes < nbs) { head += bytes; if (head == tail && buffers.size() == 1) { buffers.front().resize(CHUNKSIZE); head = tail = 0; } break; } bytes -= nbs; if (buffers.size() == 1) { buffers.front().resize(CHUNKSIZE); head = tail = 0; break; } buffers.pop_front(); head = 0; } } char *reserve(int bytes) { totalSize += bytes; char *ptr; if (tail + bytes <= buffers.back().size()) { ptr = buffers.back().data() + tail; tail += bytes; } else { buffers.back().resize(tail); QByteArray tmp; tmp.resize(qMax(CHUNKSIZE, bytes)); ptr = tmp.data(); buffers.push_back(tmp); tail = bytes; } return ptr; } // release a trailing part of the last reservation inline void unreserve(int bytes) { totalSize -= bytes; tail -= bytes; } inline void write(const char *data, int len) { memcpy(reserve(len), data, len); } // Find the first occurrence of c and return the index after it. // If c is not found until maxLength, maxLength is returned, provided // it is smaller than the buffer size. Otherwise -1 is returned. int indexAfter(char c, int maxLength = KMAXINT) const { int index = 0; int start = head; std::list::const_iterator it = buffers.cbegin(); forever { if (!maxLength) return index; if (index == size()) return -1; const QByteArray &buf = *it; ++it; int len = qMin((it == buffers.cend() ? tail : buf.size()) - start, maxLength); const char *ptr = buf.data() + start; if (const char *rptr = (const char *)memchr(ptr, c, len)) return index + (rptr - ptr) + 1; index += len; maxLength -= len; start = 0; } } inline int lineSize(int maxLength = KMAXINT) const { return indexAfter('\n', maxLength); } inline bool canReadLine() const { return lineSize() != -1; } int read(char *data, int maxLength) { int bytesToRead = qMin(size(), maxLength); int readSoFar = 0; while (readSoFar < bytesToRead) { const char *ptr = readPointer(); int bs = qMin(bytesToRead - readSoFar, readSize()); memcpy(data + readSoFar, ptr, bs); readSoFar += bs; free(bs); } return readSoFar; } int readLine(char *data, int maxLength) { return read(data, lineSize(qMin(maxLength, size()))); } private: std::list buffers; int head, tail; int totalSize; }; struct KPtyDevicePrivate : public KPtyPrivate { Q_DECLARE_PUBLIC(KPtyDevice) KPtyDevicePrivate(KPty* parent) : KPtyPrivate(parent), emittedReadyRead(false), emittedBytesWritten(false), readNotifier(nullptr), writeNotifier(nullptr) { } bool _k_canRead(); bool _k_canWrite(); bool doWait(int msecs, bool reading); void finishOpen(QIODevice::OpenMode mode); bool emittedReadyRead; bool emittedBytesWritten; QSocketNotifier *readNotifier; QSocketNotifier *writeNotifier; KRingBuffer readBuffer; KRingBuffer writeBuffer; }; #endif deepin-terminal-5.2.11/3rdparty/terminalwidget/lib/kptyprocess.cpp000066400000000000000000000070711370157770500253250ustar00rootroot00000000000000/* * This file is a part of QTerminal - http://gitorious.org/qterminal * * This file was un-linked from KDE and modified * by Maxim Bourmistrov * */ /* This file is part of the KDE libraries Copyright (C) 2007 Oswald Buddenhagen This 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; either version 2 of the License, 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. */ #include "kptyprocess.h" #include "kprocess.h" #include "kptydevice.h" #include #include #include #include KPtyProcess::KPtyProcess(QObject *parent) : KProcess(new KPtyProcessPrivate, parent) { Q_D(KPtyProcess); d->pty = new KPtyDevice(this); d->pty->open(); connect(this, SIGNAL(stateChanged(QProcess::ProcessState)), SLOT(_k_onStateChanged(QProcess::ProcessState))); } KPtyProcess::KPtyProcess(int ptyMasterFd, QObject *parent) : KProcess(new KPtyProcessPrivate, parent) { Q_D(KPtyProcess); d->pty = new KPtyDevice(this); d->pty->open(ptyMasterFd); connect(this, SIGNAL(stateChanged(QProcess::ProcessState)), SLOT(_k_onStateChanged(QProcess::ProcessState))); } KPtyProcess::~KPtyProcess() { Q_D(KPtyProcess); if (state() != QProcess::NotRunning) { if (d->addUtmp) { d->pty->logout(); disconnect(SIGNAL(stateChanged(QProcess::ProcessState)), this, SLOT(_k_onStateChanged(QProcess::ProcessState))); } } delete d->pty; waitForFinished(300); // give it some time to finish if (state() != QProcess::NotRunning) { qWarning() << Q_FUNC_INFO << "the terminal process is still running, trying to stop it by SIGHUP"; ::kill(pid(), SIGHUP); waitForFinished(300); if (state() != QProcess::NotRunning) qCritical() << Q_FUNC_INFO << "process didn't stop upon SIGHUP and will be SIGKILL-ed"; } } void KPtyProcess::setPtyChannels(PtyChannels channels) { Q_D(KPtyProcess); d->ptyChannels = channels; } KPtyProcess::PtyChannels KPtyProcess::ptyChannels() const { Q_D(const KPtyProcess); return d->ptyChannels; } void KPtyProcess::setUseUtmp(bool value) { Q_D(KPtyProcess); d->addUtmp = value; } bool KPtyProcess::isUseUtmp() const { Q_D(const KPtyProcess); return d->addUtmp; } KPtyDevice *KPtyProcess::pty() const { Q_D(const KPtyProcess); return d->pty; } void KPtyProcess::setupChildProcess() { Q_D(KPtyProcess); d->pty->setCTty(); #if 0 if (d->addUtmp) d->pty->login(KUser(KUser::UseRealUserID).loginName().toLocal8Bit().data(), qgetenv("DISPLAY")); #endif if (d->ptyChannels & StdinChannel) dup2(d->pty->slaveFd(), 0); if (d->ptyChannels & StdoutChannel) dup2(d->pty->slaveFd(), 1); if (d->ptyChannels & StderrChannel) dup2(d->pty->slaveFd(), 2); KProcess::setupChildProcess(); } //#include "kptyprocess.moc" deepin-terminal-5.2.11/3rdparty/terminalwidget/lib/kptyprocess.h000066400000000000000000000113201370157770500247620ustar00rootroot00000000000000/* * This file is a part of QTerminal - http://gitorious.org/qterminal * * This file was un-linked from KDE and modified * by Maxim Bourmistrov * */ /* This file is part of the KDE libraries Copyright (C) 2007 Oswald Buddenhagen This 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; either version 2 of the License, 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. */ #ifndef KPTYPROCESS_H #define KPTYPROCESS_H #include "kprocess.h" #include "kptydevice.h" #include class KPtyDevice; class KPtyProcessPrivate; /** * This class extends KProcess by support for PTYs (pseudo TTYs). * * The PTY is opened as soon as the class is instantiated. Verify that * it was opened successfully by checking that pty()->masterFd() is not -1. * * The PTY is always made the process' controlling TTY. * Utmp registration and connecting the stdio handles to the PTY are optional. * * No attempt to integrate with QProcess' waitFor*() functions was made, * for it is impossible. Note that execute() does not work with the PTY, too. * Use the PTY device's waitFor*() functions or use it asynchronously. * * @author Oswald Buddenhagen */ class KPtyProcess : public KProcess { Q_OBJECT Q_DECLARE_PRIVATE(KPtyProcess) public: enum PtyChannelFlag { NoChannels = 0, /**< The PTY is not connected to any channel. */ StdinChannel = 1, /**< Connect PTY to stdin. */ StdoutChannel = 2, /**< Connect PTY to stdout. */ StderrChannel = 4, /**< Connect PTY to stderr. */ AllOutputChannels = 6, /**< Connect PTY to all output channels. */ AllChannels = 7 /**< Connect PTY to all channels. */ }; Q_DECLARE_FLAGS(PtyChannels, PtyChannelFlag) /** * Constructor */ explicit KPtyProcess(QObject *parent = nullptr); /** * Construct a process using an open pty master. * * @param ptyMasterFd an open pty master file descriptor. * The process does not take ownership of the descriptor; * it will not be automatically closed at any point. */ KPtyProcess(int ptyMasterFd, QObject *parent = nullptr); /** * Destructor */ ~KPtyProcess() override; /** * Set to which channels the PTY should be assigned. * * This function must be called before starting the process. * * @param channels the output channel handling mode */ void setPtyChannels(PtyChannels channels); bool isRunning() const { bool rval; (pid() > 0) ? rval= true : rval= false; return rval; } /** * Query to which channels the PTY is assigned. * * @return the output channel handling mode */ PtyChannels ptyChannels() const; /** * Set whether to register the process as a TTY login in utmp. * * Utmp is disabled by default. * It should enabled for interactively fed processes, like terminal * emulations. * * This function must be called before starting the process. * * @param value whether to register in utmp. */ void setUseUtmp(bool value); /** * Get whether to register the process as a TTY login in utmp. * * @return whether to register in utmp */ bool isUseUtmp() const; /** * Get the PTY device of this process. * * @return the PTY device */ KPtyDevice *pty() const; protected: /** * @reimp */ void setupChildProcess() override; private: Q_PRIVATE_SLOT(d_func(), void _k_onStateChanged(QProcess::ProcessState)) }; ////////////////// // private data // ////////////////// class KPtyProcessPrivate : public KProcessPrivate { public: KPtyProcessPrivate() : ptyChannels(KPtyProcess::NoChannels), addUtmp(false) { } void _k_onStateChanged(QProcess::ProcessState newState) { if (newState == QProcess::NotRunning && addUtmp) pty->logout(); } KPtyDevice *pty; KPtyProcess::PtyChannels ptyChannels; bool addUtmp : 1; }; Q_DECLARE_OPERATORS_FOR_FLAGS(KPtyProcess::PtyChannels) #endif deepin-terminal-5.2.11/3rdparty/terminalwidget/lib/qtermwidget.cpp000066400000000000000000000723601370157770500252760ustar00rootroot00000000000000/* Copyright (C) 2008 e_k (e_k@users.sourceforge.net) This 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; either version 2 of the License, 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. */ #include #include #include #include #include #include "ColorTables.h" #include "Session.h" #include "SessionManager.h" #include "Screen.h" #include "ScreenWindow.h" #include "Emulation.h" #include "TerminalDisplay.h" #include "KeyboardTranslator.h" #include "ColorScheme.h" #include "SearchBar.h" #include "qtermwidget.h" #ifdef Q_OS_MACOS // Qt does not support fontconfig on macOS, so we need to use a "real" font name. #define DEFAULT_FONT_FAMILY "Menlo" #else #define DEFAULT_FONT_FAMILY "Monospace" #endif #define STEP_ZOOM 1 using namespace Konsole; void *createTermWidget(int startnow, void *parent) { return (void *) new QTermWidget(startnow, (QWidget *)parent); } struct TermWidgetImpl { TermWidgetImpl(QWidget *parent = 0); TerminalDisplay *m_terminalDisplay; Session *m_session; Session *createSession(QWidget *parent); TerminalDisplay *createTerminalDisplay(Session *session, QWidget *parent); }; TermWidgetImpl::TermWidgetImpl(QWidget *parent) { this->m_session = createSession(parent); SessionManager::instance()->saveSession(this->m_session); this->m_terminalDisplay = createTerminalDisplay(this->m_session, parent); this->m_terminalDisplay->setSessionId(this->m_session->sessionId()); } Session *TermWidgetImpl::createSession(QWidget *parent) { Session *session = new Session(parent); session->setTitle(Session::NameRole, QLatin1String("QTermWidget")); /* Thats a freaking bad idea!!!! * /bin/bash is not there on every system * better set it to the current $SHELL * Maybe you can also make a list available and then let the widget-owner decide what to use. * By setting it to $SHELL right away we actually make the first filecheck obsolete. * But as iam not sure if you want to do anything else ill just let both checks in and set this to $SHELL anyway. */ //session->setProgram("/bin/bash"); session->setProgram(QString::fromLocal8Bit(qgetenv("SHELL"))); QStringList args = QStringList(QString()); session->setArguments(args); session->setAutoClose(true); session->setCodec(QTextCodec::codecForName("UTF-8")); session->setFlowControlEnabled(true); session->setHistoryType(HistoryTypeBuffer(1000)); session->setDarkBackground(true); session->setKeyBindings(QString()); return session; } TerminalDisplay *TermWidgetImpl::createTerminalDisplay(Session *session, QWidget *parent) { //TerminalDisplay* display = new TerminalDisplay(this); TerminalDisplay *display = new TerminalDisplay(parent); display->setBellMode(TerminalDisplay::NotifyBell); display->setTerminalSizeHint(true); display->setTripleClickMode(TerminalDisplay::SelectWholeLine); display->setTerminalSizeStartup(true); display->setHideCursor(true); display->setRandomSeed(session->sessionId() * 31); return display; } QTermWidget::QTermWidget(int startnow, QWidget *parent) : QWidget(parent) { init(startnow); } QTermWidget::QTermWidget(QWidget *parent) : QWidget(parent) { init(1); } void QTermWidget::selectionChanged(bool textSelected) { emit copyAvailable(textSelected); } void QTermWidget::find() { search(true, false); } void QTermWidget::findNext() { search(true, true); } void QTermWidget::findPrevious() { search(false, false); } void QTermWidget::search(bool forwards, bool next) { /***mod begin by ut001121 zhangmeng 20200515 修复BUG22626***/ int startColumn, startLine; if (m_bHasSelect) { if (next) { startColumn = m_endColumn + 1; startLine = m_endLine; } else { if (m_startColumn == 0) { startColumn = -1; startLine = m_startLine - 1; } else { startColumn = m_startColumn; startLine = m_startLine; } } } else if (next) { // search from just after current selection m_impl->m_terminalDisplay->screenWindow()->screen()->getSelectionEnd(startColumn, startLine); startColumn++; } else { // search from start of current selection m_impl->m_terminalDisplay->screenWindow()->screen()->getSelectionStart(startColumn, startLine); } qDebug() << "current selection starts at: " << startColumn << startLine; qDebug() << "current cursor position: " << m_impl->m_terminalDisplay->screenWindow()->cursorPosition(); QRegExp regExp(m_searchBar->searchText()); regExp.setPatternSyntax(m_searchBar->useRegularExpression() ? QRegExp::RegExp : QRegExp::FixedString); regExp.setCaseSensitivity(m_searchBar->matchCase() ? Qt::CaseSensitive : Qt::CaseInsensitive); HistorySearch *historySearch = new HistorySearch(m_impl->m_session->emulation(), regExp, forwards, startColumn, startLine, this); connect(historySearch, SIGNAL(matchFound(int, int, int, int, int, int)), this, SLOT(matchFound(int, int, int, int, int, int))); connect(historySearch, SIGNAL(sig_noMatchFound()), this, SLOT(clearSelection())); connect(historySearch, SIGNAL(sig_noMatchFound()), m_searchBar, SLOT(clearSelection())); historySearch->search(); /***mod end by ut001121***/ } void QTermWidget::search(QString txt, bool forwards, bool next) { /***mod begin by ut001121 zhangmeng 20200515 修复BUG22626***/ int startColumn, startLine; if (m_bHasSelect) { if (next) { startColumn = m_endColumn + 1; startLine = m_endLine; } else { if (m_startColumn == 0) { startColumn = -1; startLine = m_startLine - 1; } else { startColumn = m_startColumn; startLine = m_startLine; } } } else if (next) { // search from just after current selection m_impl->m_terminalDisplay->screenWindow()->screen()->getSelectionEnd(startColumn, startLine); startColumn++; } else { // search from start of current selection m_impl->m_terminalDisplay->screenWindow()->screen()->getSelectionStart(startColumn, startLine); } qDebug() << "current selection starts at: " << startColumn << startLine; qDebug() << "current cursor position: " << m_impl->m_terminalDisplay->screenWindow()->cursorPosition(); QRegExp regExp(txt); // qDebug() << "regExp??????" << regExp.isEmpty(); regExp.setPatternSyntax(m_searchBar->useRegularExpression() ? QRegExp::RegExp : QRegExp::FixedString); regExp.setCaseSensitivity(m_searchBar->matchCase() ? Qt::CaseSensitive : Qt::CaseInsensitive); HistorySearch *historySearch = new HistorySearch(m_impl->m_session->emulation(), regExp, forwards, startColumn, startLine, this); connect(historySearch, SIGNAL(matchFound(int, int, int, int, int, int)), this, SLOT(matchFound(int, int, int, int, int, int))); connect(historySearch, SIGNAL(sig_noMatchFound()), this, SLOT(clearSelection())); connect(historySearch, &HistorySearch::noMatchFound, this, [this]() { emit sig_noMatchFound(); }); // connect(historySearch, SIGNAL(noMatchFound()), m_searchBar, SLOT(noMatchFound())); historySearch->search(); /***mod end by ut001121***/ } void QTermWidget::matchFound(int startColumn, int startLine, int endColumn, int endLine, int loseChinese, int matchChinese) { /***mod begin by ut001121 zhangmeng 20200515 修复BUG22626***/ m_bHasSelect = true; m_startColumn = startColumn; m_startLine = startLine; m_endColumn = endColumn; m_endLine = endLine; ScreenWindow *sw = m_impl->m_terminalDisplay->screenWindow(); qDebug() << "Scroll to" << startLine; sw->scrollTo(startLine); sw->setTrackOutput(false); sw->setSelectionStart(startColumn + loseChinese, startLine - sw->currentLine(), false); sw->setSelectionEnd(endColumn + matchChinese, endLine - sw->currentLine()); sw->notifyOutputChanged(); /***mod end by ut001121***/ } void QTermWidget::clearSelection() { /***add by ut001121 zhangmeng 20200515 修复BUG22626***/ m_bHasSelect = false; m_impl->m_terminalDisplay->screenWindow()->clearSelection(); } void QTermWidget::noMatchFound() { /***add by ut001121 zhangmeng 20200515 修复BUG22626***/ m_bHasSelect = false; m_impl->m_terminalDisplay->screenWindow()->clearSelection(); } int QTermWidget::getShellPID() { return m_impl->m_session->processId(); } int QTermWidget::getSessionId() { int currSessionId = m_impl->m_session->sessionId(); return currSessionId; } void QTermWidget::snapshot() { Q_ASSERT(m_impl->m_session != nullptr); Session *currSession = m_impl->m_session; // use process name as tab title, which not for display QString title = currSession->getDynamicProcessName(); title = title.simplified(); // use the fallback title if needed if (title.isEmpty()) { title = currSession->title(Session::NameRole); } // apply new title currSession->setTitle(Session::DisplayedTitleRole, title); if (currSession->isForegroundProcessActive()) { emit isTermIdle(false); } else { emit isTermIdle(true); } } void QTermWidget::changeDir(const QString &dir) { /* this is a very hackish way of trying to determine if the shell is in the foreground before attempting to change the directory. It may not be portable to anything other than Linux. */ QString strCmd; strCmd.setNum(getShellPID()); strCmd.prepend(QLatin1String("ps -j ")); strCmd.append(QLatin1String(" | tail -1 | awk '{ print $5 }' | grep -q \\+")); int retval = system(strCmd.toStdString().c_str()); if (!retval) { QString cmd = QLatin1String("cd ") + dir + QLatin1Char('\n'); sendText(cmd); } } QSize QTermWidget::sizeHint() const { QSize size = m_impl->m_terminalDisplay->sizeHint(); size.rheight() = 150; return size; } void QTermWidget::setTerminalSizeHint(bool on) { m_impl->m_terminalDisplay->setTerminalSizeHint(on); } bool QTermWidget::terminalSizeHint() { return m_impl->m_terminalDisplay->terminalSizeHint(); } void QTermWidget::startShellProgram() { if (m_impl->m_session->isRunning()) { return; } m_impl->m_session->run(); // add snapshot timer when session start running addSnapShotTimer(); } // take a snapshot of the session state every so often when // user activity occurs void QTermWidget::addSnapShotTimer() { // the timer is owned by the session so that it will be destroyed along // with the session Session *currSession = m_impl->m_session; m_interactionTimer = new QTimer(currSession); m_interactionTimer->setSingleShot(true); m_interactionTimer->setInterval(500); m_termDisplay = m_impl->m_terminalDisplay; connect(m_interactionTimer, &QTimer::timeout, this, &QTermWidget::snapshot); connect(m_termDisplay.data(), &Konsole::TerminalDisplay::keyPressedSignal, this, &QTermWidget::interactionHandler); // take a snapshot of the session state periodically in the background auto backgroundTimer = new QTimer(currSession); backgroundTimer->setSingleShot(false); backgroundTimer->setInterval(2000); connect(backgroundTimer, &QTimer::timeout, this, &QTermWidget::snapshot); backgroundTimer->start(); } void QTermWidget::interactionHandler() { m_interactionTimer->start(); } void QTermWidget::startTerminalTeletype() { if (m_impl->m_session->isRunning()) { return; } m_impl->m_session->runEmptyPTY(); // redirect data from TTY to external recipient connect( m_impl->m_session->emulation(), SIGNAL(sendData(const char *, int)), this, SIGNAL(sendData(const char *, int))); } void QTermWidget::init(int startnow) { m_layout = new QVBoxLayout(); m_layout->setMargin(0); setLayout(m_layout); // translations // First check $XDG_DATA_DIRS. This follows the implementation in libqtxdg QString d = QFile::decodeName(qgetenv("XDG_DATA_DIRS")); QStringList dirs = d.split(QLatin1Char(':'), QString::SkipEmptyParts); if (dirs.isEmpty()) { dirs.append(QString::fromLatin1("/usr/local/share")); dirs.append(QString::fromLatin1("/usr/share")); } dirs.append(QFile::decodeName(TRANSLATIONS_DIR)); m_translator = new QTranslator(this); for (const QString &dir : qAsConst(dirs)) { qDebug() << "Trying to load translation file from dir" << dir; if (m_translator->load( QLocale::system(), QLatin1String("terminalwidget"), QLatin1String(QLatin1String("_")), dir)) { qApp->installTranslator(m_translator); qDebug() << "Translations found in" << dir; break; } } m_impl = new TermWidgetImpl(this); m_layout->addWidget(m_impl->m_terminalDisplay); connect(m_impl->m_session, SIGNAL(bellRequest(QString)), m_impl->m_terminalDisplay, SLOT(bell(QString))); connect(m_impl->m_terminalDisplay, SIGNAL(notifyBell(QString)), this, SIGNAL(bell(QString))); connect(m_impl->m_session, SIGNAL(activity()), this, SIGNAL(activity())); connect(m_impl->m_session, SIGNAL(silence()), this, SIGNAL(silence())); connect(m_impl->m_session, &Session::profileChangeCommandReceived, this, &QTermWidget::profileChanged); connect(m_impl->m_session, &Session::receivedData, this, &QTermWidget::receivedData); connect(m_impl->m_session, &Session::started, this, &QTermWidget::processStarted); /******** Modify by nt001000 renfeixiang 2020-05-27:修改 增加参数区别remove和purge卸载命令 Begin***************/ // 用于卸载终端弹出框提示 connect(m_impl->m_session, SIGNAL(sessionUninstallTerminal(QString)), this, SIGNAL(uninstallTerminal(QString))); /******** Modify by nt001000 renfeixiang 2020-05-27:修改 增加参数区别remove和purge卸载命令 Begin***************/ connect(m_impl->m_session, &Session::titleChanged, this, [ = ] { m_impl->m_terminalDisplay->setHideCursor(false); }); // That's OK, FilterChain's dtor takes care of UrlFilter. UrlFilter *urlFilter = new UrlFilter(); connect(urlFilter, &UrlFilter::activated, this, &QTermWidget::urlActivated); m_impl->m_terminalDisplay->filterChain()->addFilter(urlFilter); m_impl->m_terminalDisplay->filterChain()->setSessionId(m_impl->m_session->sessionId()); m_searchBar = new SearchBar(this); m_searchBar->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Maximum); connect(m_searchBar, SIGNAL(searchCriteriaChanged()), this, SLOT(find())); connect(m_searchBar, SIGNAL(findNext()), this, SLOT(findNext())); connect(m_searchBar, SIGNAL(findPrevious()), this, SLOT(findPrevious())); m_layout->addWidget(m_searchBar); m_searchBar->hide(); if (startnow && m_impl->m_session) { m_impl->m_session->run(); } this->setFocus(Qt::OtherFocusReason); this->setFocusPolicy(Qt::WheelFocus); m_impl->m_terminalDisplay->resize(this->size()); this->setFocusProxy(m_impl->m_terminalDisplay); connect(m_impl->m_terminalDisplay, SIGNAL(copyAvailable(bool)), this, SLOT(selectionChanged(bool))); connect(m_impl->m_terminalDisplay, SIGNAL(termGetFocus()), this, SIGNAL(termGetFocus())); connect(m_impl->m_terminalDisplay, SIGNAL(leftMouseClick()), this, SIGNAL(leftMouseClick())); connect(m_impl->m_terminalDisplay, SIGNAL(termLostFocus()), this, SIGNAL(termLostFocus())); connect( m_impl->m_terminalDisplay, SIGNAL(keyPressedSignal(QKeyEvent *)), this, SIGNAL(termKeyPressed(QKeyEvent *))); // m_impl->m_terminalDisplay->setSize(80, 40); QFont font = QApplication::font(); font.setFamily(QLatin1String(DEFAULT_FONT_FAMILY)); font.setPointSize(10); font.setStyleHint(QFont::TypeWriter); setTerminalFont(font); m_searchBar->setFont(font); setScrollBarPosition(NoScrollBar); setKeyboardCursorShape(Emulation::KeyboardCursorShape::BlockCursor); m_impl->m_session->addView(m_impl->m_terminalDisplay); connect(m_impl->m_session, SIGNAL(resizeRequest(QSize)), this, SLOT(setSize(QSize))); connect(m_impl->m_session, SIGNAL(finished()), this, SLOT(sessionFinished())); connect(m_impl->m_session, &Session::titleChanged, this, &QTermWidget::titleChanged); connect(m_impl->m_session, &Session::cursorChanged, this, &QTermWidget::cursorChanged); //将终端活动状态传给SessionManager单例 connect(this, SIGNAL(isTermIdle(bool)), SessionManager::instance(), SIGNAL(sessionIdle(bool))); } QTermWidget::~QTermWidget() { SessionManager::instance()->removeSession(m_impl->m_session->sessionId()); delete m_impl; emit destroyed(); } QList QTermWidget::getRunningSessionIdList() { SessionManager *sessionMgr = SessionManager::instance(); QList sessionList = sessionMgr->sessions(); QList sessionIdList; for (int i = 0; i < sessionList.size(); i++) { Session *session = sessionList.at(i); if ((session == nullptr) || !session->isForegroundProcessActive()) { continue; } sessionIdList.append(session->sessionId()); } return sessionIdList; } bool QTermWidget::hasRunningProcess() { QList sessionIdList = getRunningSessionIdList(); for (int i = 0; i < sessionIdList.size(); i++) { int sessionId = sessionIdList.at(i); int currSessionId = m_impl->m_session->sessionId(); if (sessionId == currSessionId) { return true; } } return false; } void QTermWidget::setTerminalFont(const QFont &font) { m_impl->m_terminalDisplay->setVTFont(font); } QFont QTermWidget::getTerminalFont() { return m_impl->m_terminalDisplay->getVTFont(); } void QTermWidget::setTerminalOpacity(qreal level) { m_impl->m_terminalDisplay->setOpacity(level); } void QTermWidget::setTerminalBackgroundImage(QString backgroundImage) { m_impl->m_terminalDisplay->setBackgroundImage(backgroundImage); } void QTermWidget::setShellProgram(const QString &progname) { if (!m_impl->m_session) return; m_impl->m_session->setProgram(progname); qDebug() << "set Program" << progname; } void QTermWidget::setWorkingDirectory(const QString &dir) { if (!m_impl->m_session) return; m_impl->m_session->setInitialWorkingDirectory(dir); } QString QTermWidget::workingDirectory() { if (!m_impl->m_session) return QString(); #ifdef Q_OS_LINUX // Christian Surlykke: On linux we could look at /proc//cwd which should be a link to current // working directory (: process id of the shell). I don't know about BSD. // Maybe we could just offer it when running linux, for a start. QDir d(QString::fromLatin1("/proc/%1/cwd").arg(getShellPID())); if (!d.exists()) { qDebug() << "Cannot find" << d.dirName(); goto fallback; } return d.canonicalPath(); #endif fallback: // fallback, initial WD return m_impl->m_session->initialWorkingDirectory(); } void QTermWidget::setArgs(const QStringList &args) { if (!m_impl->m_session) return; m_impl->m_session->setArguments(args); qDebug() << "set Arguments" << args; } void QTermWidget::setTextCodec(QTextCodec *codec) { if (!m_impl->m_session) return; m_impl->m_session->setCodec(codec); } void QTermWidget::setColorScheme(const QString &origName) { const ColorScheme *cs = nullptr; const bool isFile = QFile::exists(origName); const QString &name = isFile ? QFileInfo(origName).baseName() : origName; // avoid legacy (int) solution if (!availableColorSchemes().contains(name)) { if (isFile) { if (ColorSchemeManager::instance()->loadCustomColorScheme(origName)) cs = ColorSchemeManager::instance()->findColorScheme(name); else qWarning() << Q_FUNC_INFO << "cannot load color scheme from" << origName; } if (!cs) cs = ColorSchemeManager::instance()->defaultColorScheme(); } else cs = ColorSchemeManager::instance()->findColorScheme(name); if (!cs) { QMessageBox::information(this, tr("Color Scheme Error"), tr("Cannot load color scheme: %1").arg(name)); return; } ColorEntry table[TABLE_COLORS]; cs->getColorTable(table); m_impl->m_terminalDisplay->setColorTable(table); } QStringList QTermWidget::availableColorSchemes() { QStringList ret; const auto allColorSchemes = ColorSchemeManager::instance()->allColorSchemes(); for (const ColorScheme *cs : allColorSchemes) ret.append(cs->name()); return ret; } void QTermWidget::addCustomColorSchemeDir(const QString &custom_dir) { ColorSchemeManager::instance()->addCustomColorSchemeDir(custom_dir); } void QTermWidget::setSize(const QSize &size) { m_impl->m_terminalDisplay->setSize(size.width(), size.height()); } void QTermWidget::setHistorySize(int lines) { if (lines < 0) m_impl->m_session->setHistoryType(HistoryTypeFile()); else m_impl->m_session->setHistoryType(HistoryTypeBuffer(lines)); } void QTermWidget::setScrollBarPosition(ScrollBarPosition pos) { m_impl->m_terminalDisplay->setScrollBarPosition(pos); } void QTermWidget::scrollToEnd() { m_impl->m_terminalDisplay->scrollToEnd(); } /******************************************************************************* 1. @函数: setTrackOutput 2. @作者: n014361 王培利 3. @日期: 2020-02-17 4. @说明: 设置当前屏幕是否滚动 *******************************************************************************/ void QTermWidget::setTrackOutput(bool enable) { m_impl->m_terminalDisplay->screenWindow()->setTrackOutput(enable); } void QTermWidget::sendText(const QString &text) { m_impl->m_session->sendText(text); } void QTermWidget::sendKeyEvent(QKeyEvent *e) { m_impl->m_session->sendKeyEvent(e); } void QTermWidget::resizeEvent(QResizeEvent *) { // qDebug("global window resizing...with %d %d", this->size().width(), this->size().height()); m_impl->m_terminalDisplay->resize(this->size()); } void QTermWidget::sessionFinished() { emit finished(); } void QTermWidget::bracketText(QString &text) { m_impl->m_terminalDisplay->bracketText(text); } void QTermWidget::copyClipboard() { m_impl->m_terminalDisplay->copyClipboard(); } void QTermWidget::pasteClipboard() { if (m_impl->m_terminalDisplay->hasFocus()) { m_impl->m_terminalDisplay->pasteClipboard(); } } void QTermWidget::pasteSelection() { m_impl->m_terminalDisplay->pasteSelection(); } void QTermWidget::setZoom(int step) { QFont font = m_impl->m_terminalDisplay->getVTFont(); font.setPointSize(font.pointSize() + step); setTerminalFont(font); } void QTermWidget::zoomIn() { setZoom(STEP_ZOOM); } void QTermWidget::zoomOut() { setZoom(-STEP_ZOOM); } void QTermWidget::setKeyBindings(const QString &kb) { m_impl->m_session->setKeyBindings(kb); } void QTermWidget::clear() { m_impl->m_session->emulation()->reset(); m_impl->m_session->refresh(); m_impl->m_session->clearHistory(); } void QTermWidget::setFlowControlEnabled(bool enabled) { m_impl->m_session->setFlowControlEnabled(enabled); } QStringList QTermWidget::availableKeyBindings() { return KeyboardTranslatorManager::instance()->allTranslators(); } QString QTermWidget::keyBindings() { return m_impl->m_session->keyBindings(); } void QTermWidget::toggleShowSearchBar() { m_searchBar->isHidden() ? m_searchBar->show() : m_searchBar->hide(); } bool QTermWidget::flowControlEnabled(void) { return m_impl->m_session->flowControlEnabled(); } void QTermWidget::setFlowControlWarningEnabled(bool enabled) { if (flowControlEnabled()) { // Do not show warning label if flow control is disabled m_impl->m_terminalDisplay->setFlowControlWarningEnabled(enabled); } } void QTermWidget::setEnvironment(const QStringList &environment) { m_impl->m_session->setEnvironment(environment); } void QTermWidget::setMotionAfterPasting(int action) { m_impl->m_terminalDisplay->setMotionAfterPasting((Konsole::MotionAfterPasting)action); } int QTermWidget::historyLinesCount() { return m_impl->m_terminalDisplay->screenWindow()->screen()->getHistLines(); } int QTermWidget::screenColumnsCount() { return m_impl->m_terminalDisplay->screenWindow()->screen()->getColumns(); } int QTermWidget::screenLinesCount() { return m_impl->m_terminalDisplay->screenWindow()->screen()->getLines(); } void QTermWidget::setSelectionStart(int row, int column) { m_impl->m_terminalDisplay->screenWindow()->screen()->setSelectionStart(column, row, true); } void QTermWidget::setSelectionEnd(int row, int column) { m_impl->m_terminalDisplay->screenWindow()->screen()->setSelectionEnd(column, row); } /******************************************************************** 1. @函数: setSelectionAll 2. @作者: 王培利 3. @日期: 2020-02-13 4. @说明: 屏幕全选功能 ********************************************************************/ void QTermWidget::setSelectionAll() { m_impl->m_terminalDisplay->setSelectionAll(); } void QTermWidget::getSelectionStart(int &row, int &column) { m_impl->m_terminalDisplay->screenWindow()->screen()->getSelectionStart(column, row); } void QTermWidget::getSelectionEnd(int &row, int &column) { m_impl->m_terminalDisplay->screenWindow()->screen()->getSelectionEnd(column, row); } char QTermWidget::getErase() { return m_impl->m_session->getEraseChar(); } void QTermWidget::setDeleteMode(char *key, int length) { m_impl->m_session->setDeleteMode(key, length); } void QTermWidget::setBackspaceMode(char *key, int length) { m_impl->m_session->setBackspaceMode(key, length); } QString QTermWidget::selectedText(bool preserveLineBreaks) { return m_impl->m_terminalDisplay->screenWindow()->screen()->selectedText(preserveLineBreaks); } void QTermWidget::setMonitorActivity(bool monitor) { m_impl->m_session->setMonitorActivity(monitor); } void QTermWidget::setMonitorSilence(bool monitor) { m_impl->m_session->setMonitorSilence(monitor); } void QTermWidget::setSilenceTimeout(int seconds) { m_impl->m_session->setMonitorSilenceSeconds(seconds); } Filter::HotSpot *QTermWidget::getHotSpotAt(const QPoint &pos) const { int row = 0, column = 0; m_impl->m_terminalDisplay->getCharacterPosition(pos, row, column); return getHotSpotAt(row, column); } Filter::HotSpot *QTermWidget::getHotSpotAt(int row, int column) const { return m_impl->m_terminalDisplay->filterChain()->hotSpotAt(row, column); } QList QTermWidget::filterActions(const QPoint &position) { return m_impl->m_terminalDisplay->filterActions(position); } int QTermWidget::getPtySlaveFd() const { return m_impl->m_session->getPtySlaveFd(); } void QTermWidget::setKeyboardCursorShape(KeyboardCursorShape shape) { m_impl->m_terminalDisplay->setKeyboardCursorShape(shape); } void QTermWidget::setBlinkingCursor(bool blink) { m_impl->m_terminalDisplay->setBlinkingCursor(blink); } void QTermWidget::setBidiEnabled(bool enabled) { m_impl->m_terminalDisplay->setBidiEnabled(enabled); } bool QTermWidget::isBidiEnabled() { return m_impl->m_terminalDisplay->isBidiEnabled(); } QString QTermWidget::title() const { QString title = m_impl->m_session->userTitle(); if (title.isEmpty()) title = m_impl->m_session->title(Konsole::Session::NameRole); return title; } QString QTermWidget::icon() const { QString icon = m_impl->m_session->iconText(); if (icon.isEmpty()) icon = m_impl->m_session->iconName(); return icon; } bool QTermWidget::isTitleChanged() const { return m_impl->m_session->isTitleChanged(); } void QTermWidget::setAutoClose(bool autoClose) { m_impl->m_session->setAutoClose(autoClose); } void QTermWidget::cursorChanged(Konsole::Emulation::KeyboardCursorShape cursorShape, bool blinkingCursorEnabled) { // TODO: A switch to enable/disable DECSCUSR? setKeyboardCursorShape(cursorShape); setBlinkingCursor(blinkingCursorEnabled); } void QTermWidget::setMargin(int margin) { m_impl->m_terminalDisplay->setMargin(margin); } int QTermWidget::getMargin() const { return m_impl->m_terminalDisplay->margin(); } void QTermWidget::saveHistory(QIODevice *device) { QTextStream stream(device); PlainTextDecoder decoder; decoder.begin(&stream); m_impl->m_session->emulation()->writeToStream(&decoder, 0, m_impl->m_session->emulation()->lineCount()); } void QTermWidget::setDrawLineChars(bool drawLineChars) { m_impl->m_terminalDisplay->setDrawLineChars(drawLineChars); } void QTermWidget::setBoldIntense(bool boldIntense) { m_impl->m_terminalDisplay->setBoldIntense(boldIntense); } int QTermWidget::getForegroundProcessId() const { return m_impl->m_session->foregroundProcessId(); } deepin-terminal-5.2.11/3rdparty/terminalwidget/lib/qtermwidget.h000066400000000000000000000302551370157770500247400ustar00rootroot00000000000000/* Copyright (C) 2008 e_k (e_k@users.sourceforge.net) This 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; either version 2 of the License, 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. */ #ifndef _Q_TERM_WIDGET #define _Q_TERM_WIDGET #include #include #include #include "Emulation.h" #include "Filter.h" #ifdef USE_QMAKE #include "../build/lib/qtermwidget_export.h" #else #include "qtermwidget_export.h" #endif class QVBoxLayout; class TermWidgetImpl; class SearchBar; class QUrl; namespace Konsole { class TerminalDisplay; } class TERMINALWIDGET_EXPORT QTermWidget : public QWidget { Q_OBJECT public: /** * This enum describes the location where the scroll bar is positioned in the display widget. */ enum ScrollBarPosition { /** Do not show the scroll bar. */ NoScrollBar = 0, /** Show the scroll bar on the left side of the display. */ ScrollBarLeft = 1, /** Show the scroll bar on the right side of the display. */ ScrollBarRight = 2 }; using KeyboardCursorShape = Konsole::Emulation::KeyboardCursorShape; //Creation of widget QTermWidget(int startnow, // 1 = start shell programm immediatelly QWidget *parent = nullptr); // A dummy constructor for Qt Designer. startnow is 1 by default QTermWidget(QWidget *parent = nullptr); ~QTermWidget() override; //Initial size QSize sizeHint() const override; // expose TerminalDisplay::TerminalSizeHint, setTerminalSizeHint void setTerminalSizeHint(bool on); bool terminalSizeHint(); //start shell program if it was not started in constructor void startShellProgram(); // Returns session id list of processes running in the terminal window QList getRunningSessionIdList(); // Determine whether the terminal control has running process bool hasRunningProcess(); /** * Start terminal teletype as is * and redirect data for external recipient. * It can be used for display and control a remote terminal. */ void startTerminalTeletype(); int getShellPID(); // Get current terminal's session id int getSessionId(); void changeDir(const QString &dir); // look-n-feel, if you don`t like defaults // Terminal font // Default is application font with family Monospace, size 10 // Beware of a performance penalty and display/alignment issues when using a proportional font. void setTerminalFont(const QFont &font); QFont getTerminalFont(); void setTerminalOpacity(qreal level); void setTerminalBackgroundImage(QString backgroundImage); // environment void setEnvironment(const QStringList &environment); // Shell program, default is /bin/bash void setShellProgram(const QString &progname); // working directory void setWorkingDirectory(const QString &dir); QString workingDirectory(); // Shell program args, default is none void setArgs(const QStringList &args); // Text codec, default is UTF-8 void setTextCodec(QTextCodec *codec); /** @brief Sets the color scheme, default is white on black * * @param[in] name The name of the color scheme, either returned from * availableColorSchemes() or a full path to a color scheme. */ void setColorScheme(const QString &name); static QStringList availableColorSchemes(); static void addCustomColorSchemeDir(const QString &custom_dir); // History size for scrolling void setHistorySize(int lines); // infinite if lines < 0 // Presence of scrollbar void setScrollBarPosition(ScrollBarPosition); // Wrapped, scroll to end. void scrollToEnd(); /******** Modify by n014361 wangpeili 2020-02-17:设置当前屏幕是否滚动****************/ void setTrackOutput(bool enable); /********************* Modify by n014361 wangpeili End ************************/ // Send some text to terminal void sendText(const QString &text); // Send key event to terminal void sendKeyEvent(QKeyEvent *e); // Sets whether flow control is enabled void setFlowControlEnabled(bool enabled); // Returns whether flow control is enabled bool flowControlEnabled(void); /** * Sets whether the flow control warning box should be shown * when the flow control stop key (Ctrl+S) is pressed. */ void setFlowControlWarningEnabled(bool enabled); /*! Get all available keyboard bindings */ static QStringList availableKeyBindings(); //! Return current key bindings QString keyBindings(); void setMotionAfterPasting(int); /** Return the number of lines in the history buffer. */ int historyLinesCount(); int screenColumnsCount(); int screenLinesCount(); void setSelectionStart(int row, int column); void setSelectionEnd(int row, int column); /******** Modify by n014361 wangpeili 2020-02-13: 新增屏幕全选功能***********×****/ void setSelectionAll(); /***************** Modify by n014361 End *************************/ void getSelectionStart(int &row, int &column); void getSelectionEnd(int &row, int &column); /******** Modify by ut000610 daizhengwen 2020-06-02: 获得pty erase模式****************/ char getErase(); /********************* Modify by ut000610 daizhengwen End ************************/ // 设置删除键模式(修改内存接口) void setDeleteMode(char *key, int length); // 设置退格按键模式(用户选择接口) void setBackspaceMode(char *key, int length); /** * Returns the currently selected text. * @param preserveLineBreaks Specifies whether new line characters should * be inserted into the returned text at the end of each terminal line. */ QString selectedText(bool preserveLineBreaks = true); void setMonitorActivity(bool); void setMonitorSilence(bool); void setSilenceTimeout(int seconds); /** Returns the available hotspot for the given point \em pos. * * This method may return a nullptr if no hotspot is available. * * @param[in] pos The point of interest in the QTermWidget coordinates. * @return Hotspot for the given position, or nullptr if no hotspot. */ Filter::HotSpot *getHotSpotAt(const QPoint &pos) const; /** Returns the available hotspots for the given row and column. * * @return Hotspot for the given position, or nullptr if no hotspot. */ Filter::HotSpot *getHotSpotAt(int row, int column) const; /* * Proxy for TerminalDisplay::filterActions * */ QList filterActions(const QPoint &position); /** * Returns a pty slave file descriptor. * This can be used for display and control * a remote terminal. */ int getPtySlaveFd() const; /** * Sets the shape of the keyboard cursor. This is the cursor drawn * at the position in the terminal where keyboard input will appear. */ void setKeyboardCursorShape(KeyboardCursorShape shape); void setBlinkingCursor(bool blink); /** Enables or disables bidi text in the terminal. */ void setBidiEnabled(bool enabled); bool isBidiEnabled(); /** * Automatically close the terminal session after the shell process exits or * keep it running. */ void setAutoClose(bool); QString title() const; QString icon() const; /** True if the title() or icon() was (ever) changed by the session. */ bool isTitleChanged() const; /** change and wrap text corresponding to paste mode **/ void bracketText(QString &text); /** Set the empty space outside the terminal */ void setMargin(int); /** Get the empty space outside the terminal */ int getMargin() const; /** Get the foreground pid in terminal */ int getForegroundProcessId() const; void setDrawLineChars(bool drawLineChars); void setBoldIntense(bool boldIntense); signals: void finished(); void copyAvailable(bool); void termGetFocus(); void termLostFocus(); void leftMouseClick(); void termKeyPressed(QKeyEvent *); void urlActivated(const QUrl &, bool fromContextMenu); void bell(const QString &message); void activity(); void silence(); /******** Modify by nt001000 renfeixiang 2020-05-27:修改 增加参数区别remove和purge卸载命令 Begin***************/ bool uninstallTerminal(QString commandname); /******** Modify by nt001000 renfeixiang 2020-05-27:修改 增加参数区别remove和purge卸载命令 Begin***************/ /******** Modify by ut000610 daizhengwen 2020-06-11: QProcess start finished signal****************/ void processStarted(); /********************* Modify by ut000610 daizhengwen End ************************/ /** * Emitted when emulator send data to the terminal process * (redirected for external recipient). It can be used for * control and display the remote terminal. */ void sendData(const char *, int); void profileChanged(const QString &profile); void titleChanged(); /** * Signals that we received new data from the process running in the * terminal emulator */ void receivedData(const QString &text); /** * Signals for dynamically determine whether current terminal is busy or idle */ void isTermIdle(bool bIdle); // 将库里返回信号透传出来。原来的noMatchFound方法改名为clearSelection void sig_noMatchFound(); public slots: // Copy selection to clipboard void copyClipboard(); // Paste clipboard to terminal void pasteClipboard(); // Paste selection to terminal void pasteSelection(); // Set zoom void zoomIn(); void zoomOut(); // Set size void setSize(const QSize &); /*! Set named key binding for given widget */ void setKeyBindings(const QString &kb); /*! Clear the terminal content and move to home position */ void clear(); void toggleShowSearchBar(); /******** Modify by n014361 wangpeili 2020-02-24: ****************/ // 新增外部搜索接口,不用qterminal内置的搜索接口 void search(QString txt, bool forwards, bool next); // 清除选中框 void clearSelection(); void noMatchFound(); /********************* Modify by n014361 wangpeili End ************************/ void saveHistory(QIODevice *device); protected: void resizeEvent(QResizeEvent *) override; protected slots: void sessionFinished(); void selectionChanged(bool textSelected); private slots: void find(); void findNext(); void findPrevious(); void matchFound(int startColumn, int startLine, int endColumn, int endLine, int loseChinese, int matchChinese); /** * Emulation::cursorChanged() signal propogates to here and QTermWidget * sends the specified cursor states to the terminal display */ void cursorChanged(Konsole::Emulation::KeyboardCursorShape cursorShape, bool blinkingCursorEnabled); void snapshot(); private: void search(bool forwards, bool next); void setZoom(int step); void init(int startnow); void addSnapShotTimer(); void interactionHandler(); TermWidgetImpl *m_impl; SearchBar *m_searchBar; QVBoxLayout *m_layout; QTranslator *m_translator; QPointer m_termDisplay; QTimer *m_interactionTimer = nullptr; bool m_bHasSelect = false; int m_startColumn = 0; int m_startLine = 0; int m_endColumn = 0; int m_endLine = 0; }; // Maybe useful, maybe not #ifdef __cplusplus extern "C" #endif void *createTermWidget(int startnow, void *parent); #endif deepin-terminal-5.2.11/3rdparty/terminalwidget/lib/tools.cpp000066400000000000000000000070531370157770500240770ustar00rootroot00000000000000#include "tools.h" #include #include #include #include /*! Helper function to get possible location of layout files. By default the KB_LAYOUT_DIR is used (linux/BSD/macports). But in some cases (apple bundle) there can be more locations). */ QString get_kb_layout_dir() { // qDebug() << __FILE__ << __FUNCTION__; QString rval = QString(); QString k(QLatin1String(KB_LAYOUT_DIR)); QDir d(k); //qDebug() << "default KB_LAYOUT_DIR: " << k; if (d.exists()) { rval = k.append(QLatin1Char('/')); return rval; } #ifdef Q_OS_MAC // subdir in the app location d.setPath(QCoreApplication::applicationDirPath() + QLatin1String("/kb-layouts/")); //qDebug() << d.path(); if (d.exists()) return QCoreApplication::applicationDirPath() + QLatin1String("/kb-layouts/"); d.setPath(QCoreApplication::applicationDirPath() + QLatin1String("/../Resources/kb-layouts/")); if (d.exists()) return QCoreApplication::applicationDirPath() + QLatin1String("/../Resources/kb-layouts/"); #endif //qDebug() << "Cannot find KB_LAYOUT_DIR. Default:" << k; return QString(); } /*! Helper function to add custom location of color schemes. */ namespace { QStringList custom_color_schemes_dirs; } void add_custom_color_scheme_dir(const QString& custom_dir) { if (!custom_color_schemes_dirs.contains(custom_dir)) custom_color_schemes_dirs << custom_dir; } /*! Helper function to get possible locations of color schemes. By default the COLORSCHEMES_DIR is used (linux/BSD/macports). But in some cases (apple bundle) there can be more locations). */ const QStringList get_color_schemes_dirs() { // qDebug() << __FILE__ << __FUNCTION__; QStringList rval; QString k(QLatin1String(COLORSCHEMES_DIR)); QDir d(k); // qDebug() << "default COLORSCHEMES_DIR: " << k; if (d.exists()) rval << k.append(QLatin1Char('/')); #ifdef Q_OS_MAC // subdir in the app location d.setPath(QCoreApplication::applicationDirPath() + QLatin1String("/color-schemes/")); //qDebug() << d.path(); if (d.exists()) { if (!rval.isEmpty()) rval.clear(); rval << (QCoreApplication::applicationDirPath() + QLatin1String("/color-schemes/")); } d.setPath(QCoreApplication::applicationDirPath() + QLatin1String("/../Resources/color-schemes/")); if (d.exists()) { if (!rval.isEmpty()) rval.clear(); rval << (QCoreApplication::applicationDirPath() + QLatin1String("/../Resources/color-schemes/")); } #endif for (const QString& custom_dir : qAsConst(custom_color_schemes_dirs)) { d.setPath(custom_dir); if (d.exists()) rval << custom_dir; } #ifdef QT_DEBUG if(!rval.isEmpty()) { qDebug() << "Using color-schemes: " << rval; } else { qDebug() << "Cannot find color-schemes in any location!"; } #endif return rval; } TerminalHeaderBar::TerminalHeaderBar(QWidget *parent) : QWidget(parent) { m_boxLayout = new QBoxLayout(QBoxLayout::LeftToRight); m_boxLayout->setSpacing(0); m_boxLayout->setContentsMargins(0, 0, 0, 0); //通过查看Konsole 20.04.2版本源码发现加QToolButton作为Header放在TerminalDisplay控件布局顶部, //可以在分屏拖拽的时候减少提示符出现残存在界面上的情况 for(int i=0; i<6; i++) { QToolButton *toolBtn = new QToolButton(this); toolBtn->setFixedHeight(1); m_boxLayout->addWidget(toolBtn); } setLayout(m_boxLayout); } deepin-terminal-5.2.11/3rdparty/terminalwidget/lib/tools.h000066400000000000000000000007371370157770500235460ustar00rootroot00000000000000#ifndef TOOLS_H #define TOOLS_H #include #include #include #include QString get_kb_layout_dir(); void add_custom_color_scheme_dir(const QString& custom_dir); const QStringList get_color_schemes_dirs(); //参考了Konsole中的TerminalHeaderBar class TerminalHeaderBar : public QWidget { Q_OBJECT public: explicit TerminalHeaderBar(QWidget *parent = nullptr); private: QBoxLayout *m_boxLayout = nullptr; }; #endif deepin-terminal-5.2.11/3rdparty/terminalwidget/lib/translations/000077500000000000000000000000001370157770500247475ustar00rootroot00000000000000deepin-terminal-5.2.11/3rdparty/terminalwidget/lib/translations/CMakeLists.txt000066400000000000000000000001441370157770500275060ustar00rootroot00000000000000project(qtermwidget) build_component("." "${CMAKE_INSTALL_FULL_DATADIR}/qtermwidget/translations") deepin-terminal-5.2.11/3rdparty/terminalwidget/lib/translations/terminalwidget.ts000066400000000000000000000106351370157770500303430ustar00rootroot00000000000000 Konsole::TerminalDisplay Size: XXX x XXX Size: %1 x %2 <qt>Output has been <a href="http://en.wikipedia.org/wiki/Flow_control">suspended</a> by pressing Ctrl+S. Press <b>Ctrl+Q</b> to resume.</qt> Konsole::Vt102Emulation No keyboard translator available. The information needed to convert key presses into characters to send to the terminal is missing. QObject Un-named Color Scheme Accessible Color Scheme Open link Copy link Send email to... Copy email address QTermWidget Color Scheme Error Cannot load color scheme: %1 SearchBar Match case Regular expression Highlight all matches SearchBar X Find: < > ... deepin-terminal-5.2.11/3rdparty/terminalwidget/lib/translations/terminalwidget_arn.ts000066400000000000000000000106641370157770500312050ustar00rootroot00000000000000 Konsole::TerminalDisplay Size: XXX x XXX Size: %1 x %2 <qt>Output has been <a href="http://en.wikipedia.org/wiki/Flow_control">suspended</a> by pressing Ctrl+S. Press <b>Ctrl+Q</b> to resume.</qt> Konsole::Vt102Emulation No keyboard translator available. The information needed to convert key presses into characters to send to the terminal is missing. QObject Un-named Color Scheme Accessible Color Scheme Open Link Copy Link Address Send Email To... Copy Email Address QTermWidget Color Scheme Error Cannot load color scheme: %1 SearchBar Match case Regular expression Highlight all matches SearchBar X Find: < > ... deepin-terminal-5.2.11/3rdparty/terminalwidget/lib/translations/terminalwidget_ast.ts000066400000000000000000000106641370157770500312140ustar00rootroot00000000000000 Konsole::TerminalDisplay Size: XXX x XXX Size: %1 x %2 <qt>Output has been <a href="http://en.wikipedia.org/wiki/Flow_control">suspended</a> by pressing Ctrl+S. Press <b>Ctrl+Q</b> to resume.</qt> Konsole::Vt102Emulation No keyboard translator available. The information needed to convert key presses into characters to send to the terminal is missing. QObject Un-named Color Scheme Accessible Color Scheme Open Link Copy Link Address Send Email To... Copy Email Address QTermWidget Color Scheme Error Cannot load color scheme: %1 SearchBar Match case Regular expression Highlight all matches SearchBar X Find: < > ... deepin-terminal-5.2.11/3rdparty/terminalwidget/lib/translations/terminalwidget_ca.ts000066400000000000000000000114321370157770500310020ustar00rootroot00000000000000 Konsole::TerminalDisplay Size: XXX x XXX Mida: XXX x XXX Size: %1 x %2 Mida: %1 x %2 <qt>Output has been <a href="http://en.wikipedia.org/wiki/Flow_control">suspended</a> by pressing Ctrl+S. Press <b>Ctrl+Q</b> to resume.</qt> <qt>La sortida ha estat <a href="http://en.wikipedia.org/wiki/Flow_control">suspesa</a> en prémer Ctrl+S. Premeu <b>Ctrl+Q</b> per reprendre-la.</qt> Konsole::Vt102Emulation No keyboard translator available. The information needed to convert key presses into characters to send to the terminal is missing. No hi ha disponible cap traductor de teclat. No es disposa de la informació necessària per convertir la pressió de les tecles a caràcters al terminal. QObject Un-named Color Scheme Esquema de color sense nom Accessible Color Scheme Esquema de color accessible Open Link Obre l'enllaç Copy Link Address Copia l'adreça de l'enllaç Send Email To... Envia un correu electrònic a... Copy Email Address Copia l'adreça de correu electrònic QTermWidget Color Scheme Error Error de l'esquema de color Cannot load color scheme: %1 No es pot carregar l'esquema de color: %1 SearchBar Match case Coincidència Regular expression Expressió regular Highlight all matches Ressalta totes les coincidències SearchBar Barra de cerca X X Find: Troba: < < > > ... ... deepin-terminal-5.2.11/3rdparty/terminalwidget/lib/translations/terminalwidget_cs.ts000066400000000000000000000114101370157770500310200ustar00rootroot00000000000000 Konsole::TerminalDisplay Size: XXX x XXX Velikost: XXX x XXX Size: %1 x %2 Velikost: %1 x %2 <qt>Output has been <a href="http://en.wikipedia.org/wiki/Flow_control">suspended</a> by pressing Ctrl+S. Press <b>Ctrl+Q</b> to resume.</qt> <qt>Výstup byl <a href="http://en.wikipedia.org/wiki/Flow_control">pozastaven</a> stisknutím Ctrl+S. Znovu ho spustíte stisknutím <b>Ctrl+Q</b>.</qt> Konsole::Vt102Emulation No keyboard translator available. The information needed to convert key presses into characters to send to the terminal is missing. Není k dispozici žádný překladač klávesnice. Chybí informace pro převod kódů stisknutých kláves na znaky posílané na terminál. QObject Un-named Color Scheme Nepojmenované barevné schéma Accessible Color Scheme Barevné schéma pro zrakově hendikepované uživatele Open Link Otevřít odkaz Copy Link Address Zkopírovat adresu odkazu Send Email To... Poslat e-mail na… Copy Email Address Zkopírovat e-mailovou adresu QTermWidget Color Scheme Error Chyba barevného schématu Cannot load color scheme: %1 Nedaří se načíst barevné schéma: %1 SearchBar Match case Rozlišovat malá/VELKÁ písmena Regular expression Regulární výraz Highlight all matches Zvýraznit všechny shody SearchBar Pruh hledání X Find: Najít: < > ... deepin-terminal-5.2.11/3rdparty/terminalwidget/lib/translations/terminalwidget_cy.ts000066400000000000000000000100711370157770500310300ustar00rootroot00000000000000 Konsole::TerminalDisplay Size: XXX x XXX Size: %1 x %2 <qt>Output has been <a href="http://en.wikipedia.org/wiki/Flow_control">suspended</a> by pressing Ctrl+S. Press <b>Ctrl+Q</b> to resume.</qt> Konsole::Vt102Emulation No keyboard translator available. The information needed to convert key presses into characters to send to the terminal is missing. QObject Un-named Color Scheme Accessible Color Scheme Open Link Copy Link Address Send Email To... Copy Email Address QTermWidget Color Scheme Error Cannot load color scheme: %1 SearchBar Match case Regular expression Highlight all matches SearchBar X Find: < > ... deepin-terminal-5.2.11/3rdparty/terminalwidget/lib/translations/terminalwidget_da.ts000066400000000000000000000113071370157770500310040ustar00rootroot00000000000000 Konsole::TerminalDisplay Size: XXX x XXX Størrelse: XXX x XXX Size: %1 x %2 Størrelse: %1 x %2 <qt>Output has been <a href="http://en.wikipedia.org/wiki/Flow_control">suspended</a> by pressing Ctrl+S. Press <b>Ctrl+Q</b> to resume.</qt> <qt>Output er blevet <a href="http://en.wikipedia.org/wiki/Flow_control">suspenderet</a> ved tryk på Ctrl+S. Tryk på <b>Ctrl+Q</b> for at genoptage.</qt> Konsole::Vt102Emulation No keyboard translator available. The information needed to convert key presses into characters to send to the terminal is missing. Ingen tastaturoversætter tilgængelig. Informationen, som er nødvendig for at konvertere tastetryk til tegn, som sendes til terminalen, mangler. QObject Un-named Color Scheme Unavngivet farveskema Accessible Color Scheme Tilgængeligt farveskema Open Link Åbn link Copy Link Address Kopiér linkadresse Send Email To... Send e-mail til... Copy Email Address Kopiér e-mailadresse QTermWidget Color Scheme Error Fejl ved farveskema Cannot load color scheme: %1 Kan ikke indlæse farveskema: %1 SearchBar Match case Der skelnes mellem store og små bogstaver Regular expression Regulært udtryk Highlight all matches Fremhæv alle match SearchBar SøgeLinje X X Find: Find: < < > > ... ... deepin-terminal-5.2.11/3rdparty/terminalwidget/lib/translations/terminalwidget_de.ts000066400000000000000000000113041370157770500310050ustar00rootroot00000000000000 Konsole::TerminalDisplay Size: XXX x XXX Größe: XXX x XXX Size: %1 x %2 Größe: %1 x %2 <qt>Output has been <a href="http://en.wikipedia.org/wiki/Flow_control">suspended</a> by pressing Ctrl+S. Press <b>Ctrl+Q</b> to resume.</qt> <qt>Ausgabe wurde <a href="http://en.wikipedia.org/wiki/Flow_control">ausgesetzt</a> beim Drücken von Strg+S. Drücke <b>Strg+Q</b> um fortzufahren.</qt> Konsole::Vt102Emulation No keyboard translator available. The information needed to convert key presses into characters to send to the terminal is missing. Kein Tastaturinterpretierer verfügbar. Die benötigte Information, um Tastenbefehle in Zeichen umzuwandeln und anschließenfd zum Terminal zu schicken, fehlt. QObject Un-named Color Scheme Unbenanntes Farbschema Accessible Color Scheme Zugängliches Farbschema Open Link Link öffnen Copy Link Address Linkadresse kopieren Send Email To... E-Mail senden an... Copy Email Address E-Mail-Adresse kopieren QTermWidget Color Scheme Error Farbschemafehler Cannot load color scheme: %1 Kann Farbschema nicht laden: %1 SearchBar Match case Groß-/Kleinschreibung beachten Regular expression Regulärer Ausdruck Highlight all matches Alle Treffer hervorheben SearchBar Suchleiste X Find: Finde: < > ... deepin-terminal-5.2.11/3rdparty/terminalwidget/lib/translations/terminalwidget_el.ts000066400000000000000000000124701370157770500310220ustar00rootroot00000000000000 Konsole::TerminalDisplay Size: XXX x XXX Μέγεθος: XXX x XXX Size: %1 x %2 Μέγεθος: %1 x %2 <qt>Output has been <a href="http://en.wikipedia.org/wiki/Flow_control">suspended</a> by pressing Ctrl+S. Press <b>Ctrl+Q</b> to resume.</qt> <qt>Η έξοδος έχει <a href="http://en.wikipedia.org/wiki/Flow_control">ανασταλεί</a> με τον συνδυασμό πλήκτρων Ctrl+S. Πιέστε <b>Ctrl+Q</b> για επαναφορά.</qt> Konsole::Vt102Emulation No keyboard translator available. The information needed to convert key presses into characters to send to the terminal is missing. Δεν υπάρχει κάποιος μεταφραστής πληκτρολογίου διαθέσιμος. Η απαιτούμενη πληροφορία για την μετατροπή των πατημάτων πλήκτρων σε χαρακτήρες στο τερματικό λείπει. QObject Un-named Color Scheme Ανώνυμος χρωματικός συνδυασμός Accessible Color Scheme Προσπελάσιμος χρωματικός σχηματισμός Open Link Άνοιγμα του δεσμού Copy Link Address Αντιγραφή διεύθυνσης του δεσμού Send Email To... Αποστολή ηλ. αλληλογραφίας προς... Copy Email Address Αντιγραφή της ηλ. διεύθυνσης QTermWidget Color Scheme Error Σφάλμα του χρωματικού συνδυασμού Cannot load color scheme: %1 Αδύνατη η φόρτωση του χρωματικού συνδυασμού: %1 SearchBar Match case Ταίριασμα πεζών/κεφαλαίων Regular expression Κανονική έκφραση Highlight all matches Τονισμός όλων των ταιριαστών SearchBar Γραμμή αναζήτησης X X Find: Εύρεση: < < > > ... ... deepin-terminal-5.2.11/3rdparty/terminalwidget/lib/translations/terminalwidget_es.ts000066400000000000000000000114201370157770500310230ustar00rootroot00000000000000 Konsole::TerminalDisplay Size: XXX x XXX Tamaño: XXX x XXX Size: %1 x %2 Tamaño: %1 x %2 <qt>Output has been <a href="http://en.wikipedia.org/wiki/Flow_control">suspended</a> by pressing Ctrl+S. Press <b>Ctrl+Q</b> to resume.</qt> <qt>La salida ha sido <a href="http://en.wikipedia.org/wiki/Flow_control">suspendida</a> al pulsar Ctrl+S. Pulse <b>Ctrl+Q</b> para reanudarla.</qt> Konsole::Vt102Emulation No keyboard translator available. The information needed to convert key presses into characters to send to the terminal is missing. No hay traductor de teclado disponible. La información necesaria para convertir pulsaciones de tecla en caracteres para enviarlos a la terminal está ausente. QObject Un-named Color Scheme Esquema de color sin nombre Accessible Color Scheme Esquema de color accesible Open Link Abrir el enlace Copy Link Address Copiar la dirección del enlace Send Email To... Enviar correo a... Copy Email Address Copiar la dirección de correo QTermWidget Color Scheme Error Error del esquema de color Cannot load color scheme: %1 No se puede cargar el esquema de color: %1 SearchBar Match case Distinguir mayúsculas de minúsculas Regular expression Expresión regular Highlight all matches Resaltar todas las coincidencias SearchBar Barra de búsqueda X X Find: Buscar: < < > > ... ... deepin-terminal-5.2.11/3rdparty/terminalwidget/lib/translations/terminalwidget_fr.ts000066400000000000000000000113541370157770500310310ustar00rootroot00000000000000 Konsole::TerminalDisplay Size: XXX x XXX Taille : XXX x XXX Size: %1 x %2 Taille : %1 x %2 <qt>Output has been <a href="http://en.wikipedia.org/wiki/Flow_control">suspended</a> by pressing Ctrl+S. Press <b>Ctrl+Q</b> to resume.</qt> <qt>La sortie a été <a href="http://en.wikipedia.org/wiki/Flow_control">suspendue</a> en pressant Ctrl+S. Pressez <b>Ctrl+Q</b> pour reprendre.</qt> Konsole::Vt102Emulation No keyboard translator available. The information needed to convert key presses into characters to send to the terminal is missing. Aucun traducteur disponible. L'information nécessaire à la conversion des touches pressées en caractères à envoyer au terminal est absente. QObject Un-named Color Scheme Schéma des couleurs non nommé Accessible Color Scheme Schéma des couleur accessible Open link Ouvrir le lien Copy link Copier le lien Send email to... Envoyer un email à... Copy email address Copier l'adresse email QTermWidget Color Scheme Error Erreur du schéma des couleurs Cannot load color scheme: %1 Impossible de charger le schéma de couleurs : %1 SearchBar Match case Sensible à la casse Regular expression Expression régulière Highlight all matches Surbrillance de toutes les concordances SearchBar Barre de recherche X X Find: Trouver : < < > > ... ... deepin-terminal-5.2.11/3rdparty/terminalwidget/lib/translations/terminalwidget_gl.ts000066400000000000000000000114121370157770500310170ustar00rootroot00000000000000 Konsole::TerminalDisplay Size: XXX x XXX Tamaño: XXX x XXX Size: %1 x %2 Tamaño: %1 x %2 <qt>Output has been <a href="http://en.wikipedia.org/wiki/Flow_control">suspended</a> by pressing Ctrl+S. Press <b>Ctrl+Q</b> to resume.</qt> <qt>A saída foi <a href="http://en.wikipedia.org/wiki/Flow_control">suspendida</a> ao premer Ctrl+S. Prema <b>Ctrl+Q</b> para continuar.</qt> Konsole::Vt102Emulation No keyboard translator available. The information needed to convert key presses into characters to send to the terminal is missing. Non hai dispoñíbel ningún tradutor de teclado. Non está dispoñíbel a información necesaria para converter pulsacións de tecla en caracteres para envialos o terminal. QObject Un-named Color Scheme Esquema de cor sen nome Accessible Color Scheme Esquema de cor accesíbel Open Link Abrir a ligazón Copy Link Address Copiar o enderezo da ligazón Send Email To... Enviar correo a... Copy Email Address Copiar o enderezo de correo QTermWidget Color Scheme Error Produciuse un erro no esquema de cor Cannot load color scheme: %1 Non é posíbel cargar o esquema de cor: %1 SearchBar Match case Distinguir maiúsculas de minúsculas Regular expression Expresión regular Highlight all matches Resaltar todas as coincidencias SearchBar Barra de buscas X Find: Atopar: < > ... deepin-terminal-5.2.11/3rdparty/terminalwidget/lib/translations/terminalwidget_he.ts000066400000000000000000000114641370157770500310200ustar00rootroot00000000000000 Konsole::TerminalDisplay Size: XXX x XXX גודל: XXX × XXX Size: %1 x %2 גודל: %1 × %2 <qt>Output has been <a href="http://en.wikipedia.org/wiki/Flow_control">suspended</a> by pressing Ctrl+S. Press <b>Ctrl+Q</b> to resume.</qt> <qt>הפלט <a href="http://en.wikipedia.org/wiki/Flow_control">הושהה</a> בלחיצה על Ctrl+S. יש ללחוץ על <b>Ctrl+Q</b> כדי להמשיך.</qt> Konsole::Vt102Emulation No keyboard translator available. The information needed to convert key presses into characters to send to the terminal is missing. אין מתרגם מקלדת זמין. המידע שנדרש לצורך המרת לחיצות מקשים לתווים לשליחה למסוף חסר. QObject Un-named Color Scheme ערכת צבעים ללא שם Accessible Color Scheme ערכת צבעים נגישה Open Link פתיחת קישור Copy Link Address העתקת כתובת קישור Send Email To... שליחת דוא״ל אל… Copy Email Address העתקת כתובת דוא״ל QTermWidget Color Scheme Error שגיאת ערכת צבעים Cannot load color scheme: %1 לא ניתן לטעון ערכת צבעים: %1 SearchBar Match case התאמת רישיות Regular expression ביטוי רגולרי Highlight all matches הדגשת כל המופעים SearchBar סרגל חיפוש X Find: חיפוש: < > ... deepin-terminal-5.2.11/3rdparty/terminalwidget/lib/translations/terminalwidget_hu.ts000066400000000000000000000112621370157770500310340ustar00rootroot00000000000000 Konsole::TerminalDisplay Size: XXX x XXX Méret: XXX x XXX Size: %1 x %2 Méret: %1 x %2 <qt>Output has been <a href="http://en.wikipedia.org/wiki/Flow_control">suspended</a> by pressing Ctrl+S. Press <b>Ctrl+Q</b> to resume.</qt> <qt>A kimenet <a href="http://en.wikipedia.org/wiki/Flow_control">el van nyomva</a> a Ctrl+S megnyomásával. Nyomj <b>Ctrl+Q -t</b> a visszatéréshez.</qt> Konsole::Vt102Emulation No keyboard translator available. The information needed to convert key presses into characters to send to the terminal is missing. Nincs billentyűzet átalakító. Hiányzik az információ, ami a billentyű lenyomásnak a terminálhoz küldendő karakterekké alakításához szükséges. QObject Un-named Color Scheme Névtelen Színséma Accessible Color Scheme Elérhető színséma Open Link Link megnyitás Copy Link Address Link cím másolás Send Email To... Email küldés ... Copy Email Address Email cím másolás QTermWidget Color Scheme Error Színséma hiba Cannot load color scheme: %1 A %1 színséma elérhetetlen SearchBar Match case Nagybetű érzékeny Regular expression Szaabályos kifejezés Highlight all matches Találatok kiemelése SearchBar Keresősáv X Find: Keres: < > ... deepin-terminal-5.2.11/3rdparty/terminalwidget/lib/translations/terminalwidget_ja.ts000066400000000000000000000110551370157770500310120ustar00rootroot00000000000000 Konsole::TerminalDisplay Size: XXX x XXX Size: %1 x %2 <qt>Output has been <a href="http://en.wikipedia.org/wiki/Flow_control">suspended</a> by pressing Ctrl+S. Press <b>Ctrl+Q</b> to resume.</qt> Konsole::Vt102Emulation No keyboard translator available. The information needed to convert key presses into characters to send to the terminal is missing. QObject Un-named Color Scheme 名前のないカラースキーム Accessible Color Scheme アクセス可能なカラースキーム Open Link リンクを開く Copy Link Address リンクのアドレスをコピー Send Email To... メールを送信... Copy Email Address メールアドレスをコピー QTermWidget Color Scheme Error カラースキームのエラー Cannot load color scheme: %1 カラースキームをロードすることができません: %1 SearchBar Match case Regular expression 正規表現 Highlight all matches 一致するものをハイライト SearchBar サーチバー X Find: 探す: < > ... deepin-terminal-5.2.11/3rdparty/terminalwidget/lib/translations/terminalwidget_lt.ts000066400000000000000000000113111370157770500310320ustar00rootroot00000000000000 Konsole::TerminalDisplay Size: XXX x XXX Dydis: XXX x XXX Size: %1 x %2 Dydis: %1 x %2 <qt>Output has been <a href="http://en.wikipedia.org/wiki/Flow_control">suspended</a> by pressing Ctrl+S. Press <b>Ctrl+Q</b> to resume.</qt> <qt>Išvestis buvo <a href="http://en.wikipedia.org/wiki/Flow_control">pristabdyta,</a> paspaudžiant Ctrl(Vald)+S. Paspauskite <b>Ctrl(Vald)+Q</b>, norėdami pratęsti.</qt> Konsole::Vt102Emulation No keyboard translator available. The information needed to convert key presses into characters to send to the terminal is missing. Nėra prieinamas joks klaviatūros vertėjas. Informacijos, kurios reikia, norint konvertuoti klavišų paspaudimus į simbolius ir siųsti į terminalą, nėra. QObject Un-named Color Scheme Nepavadintas spalvų rinkinys Accessible Color Scheme Pasiekiamas spalvų rinkinys Open link Atverti nuorodą Copy link Kopijuoti nuorodą Send email to... Copy email address QTermWidget Color Scheme Error Spalvų rinkinio klaida Cannot load color scheme: %1 Nepavyksta įkelti spalvų rinkinio: %1 SearchBar Match case Skirti raidžių dydį Regular expression Reguliarusis reiškinys Highlight all matches Paryškinti visus atitikmenis SearchBar Paieškos juosta X X Find: Rasti: < < > > ... ... deepin-terminal-5.2.11/3rdparty/terminalwidget/lib/translations/terminalwidget_nb_NO.ts000066400000000000000000000113011370157770500314050ustar00rootroot00000000000000 Konsole::TerminalDisplay Size: XXX x XXX Størrelse: XXX x XXX Size: %1 x %2 Størrelse: %1 x %2 <qt>Output has been <a href="http://en.wikipedia.org/wiki/Flow_control">suspended</a> by pressing Ctrl+S. Press <b>Ctrl+Q</b> to resume.</qt> <qt>Utgangssignalet ble <a href="http://en.wikipedia.org/wiki/Flow_control">stoppet</a> da Ctrl+S ble trykket. Trykk <b>Ctrl+Q</b> for å fortsette.</qt> Konsole::Vt102Emulation No keyboard translator available. The information needed to convert key presses into characters to send to the terminal is missing. Ingen tastaturoversetter er tilgjengelig. Informasjonen som trengs for å gjøre tastetrykk om til tegn å sende til terminalen mangler. QObject Un-named Color Scheme Fargemønster uten navn Accessible Color Scheme Fargemønster for funksjonshemmede Open Link Åpne lenke Copy Link Address Kopier lenkeadresse Send Email To... Send epost til... Copy Email Address Kopier epostadressen QTermWidget Color Scheme Error Feil med fargemønster Cannot load color scheme: %1 Kan ikke åpne fargemønster: %1 SearchBar Match case Bruk STORE og små bokstaver Regular expression Bokstavmønstre (regex) Highlight all matches Lys opp alle søkeresultat SearchBar Søkefelt X Find: Finn: < > ... deepin-terminal-5.2.11/3rdparty/terminalwidget/lib/translations/terminalwidget_pl.ts000066400000000000000000000112201370157770500310250ustar00rootroot00000000000000 Konsole::TerminalDisplay Size: XXX x XXX Rozmiar: XXX x XXX Size: %1 x %2 Rozmiar: %1 x %2 <qt>Output has been <a href="http://en.wikipedia.org/wiki/Flow_control">suspended</a> by pressing Ctrl+S. Press <b>Ctrl+Q</b> to resume.</qt> <qt>Wyjście zostało <a href="http://en.wikipedia.org/wiki/Flow_control">wstrzymane</a> skrótem Ctrl+S. Wciśnij <b>Ctrl+Q</b> aby wznowić.</qt> Konsole::Vt102Emulation No keyboard translator available. The information needed to convert key presses into characters to send to the terminal is missing. Brak sterownika klawiatury. Nie wiadomo jak przełożyć wciśniecia przycisków na znaki wysyłane do terminalu. QObject Un-named Color Scheme Nienazwana paleta Accessible Color Scheme Paleta o zwiększonej przystępności Open link Otwórz link Copy link Kopiuj odnośnik Send email to... Wyślij email do... Copy email address Skopiuj adres e-mail QTermWidget Color Scheme Error Błąd w palecie Cannot load color scheme: %1 Nie można wczytać palety: %1 SearchBar Match case Rozróżniaj wielkość liter Regular expression Wyrażenie regularne Highlight all matches Podświetl wszystkie dopasowania SearchBar Pasek wyszukiwania X X Find: Znajdź: < < > > ... deepin-terminal-5.2.11/3rdparty/terminalwidget/lib/translations/terminalwidget_pt.ts000066400000000000000000000113251370157770500310430ustar00rootroot00000000000000 Konsole::TerminalDisplay Size: XXX x XXX Tamanho: XXX x XXX Size: %1 x %2 Tamanho: %1 x %2 <qt>Output has been <a href="http://en.wikipedia.org/wiki/Flow_control">suspended</a> by pressing Ctrl+S. Press <b>Ctrl+Q</b> to resume.</qt> <qt>A saída foi <a href="http://en.wikipedia.org/wiki/Flow_control"> suspensa</a> ao premir Ctrl+S. Prima <b>Ctrl+Q</b> para continuar.</qt> Konsole::Vt102Emulation No keyboard translator available. The information needed to convert key presses into characters to send to the terminal is missing. Nenhum tradutor de teclado disponível. A informação necessária para converter a pressão da tecla nos caracteres a enviar ao terminal não existe. QObject Un-named Color Scheme Esquema de cores sem nome Accessible Color Scheme Esquema de cores acessível Open link Abrir ligação Copy link Copiar ligação Send email to... Enviar um email a... Copy email address Copiar endereço de email QTermWidget Color Scheme Error Erro no esquema de cores Cannot load color scheme: %1 Não foi possível carregar o esquema de cores: %1 SearchBar Match case Diferenciar maiúsculas/minúsculas Regular expression Expressão regular Highlight all matches Realçar todas as ocorrências SearchBar Barra de pesquisa X X Find: Localizar: < < > > ... ... deepin-terminal-5.2.11/3rdparty/terminalwidget/lib/translations/terminalwidget_pt_BR.ts000066400000000000000000000113711370157770500314270ustar00rootroot00000000000000 Konsole::TerminalDisplay Size: XXX x XXX Tamanho: XXX x XXX Size: %1 x %2 Tamanho: %1 x %2 <qt>Output has been <a href="http://en.wikipedia.org/wiki/Flow_control">suspended</a> by pressing Ctrl+S. Press <b>Ctrl+Q</b> to resume.</qt> <qt>A saída foi <a href="http://en.wikipedia.org/wiki/Flow_control">suspensa</a> pressionando Ctrl+S. Precione <b>Ctrl+Q</b> para continuar.</qt> Konsole::Vt102Emulation No keyboard translator available. The information needed to convert key presses into characters to send to the terminal is missing. Nenhum tradutor de teclado disponível. A informação necessária para converter a tecla pressionada em caracteres para enviar para o terminal está faltando. QObject Un-named Color Scheme Esquema de cor sem nome Accessible Color Scheme Esquema de cor acessível Open Link Abrir Link Copy Link Address Copiar Endereço do Link Send Email To... Enviar E-mail Para... Copy Email Address Copiar Endereço de E-mail QTermWidget Color Scheme Error Erro no esquema de cor Cannot load color scheme: %1 Não foi possível carregar o esquema de cor: %1 SearchBar Match case Caso de compatibilidade Regular expression Expressão Regular Highlight all matches Destacar todas as correspondências SearchBar Barra de Pesquisa X X Find: Encontrar: < < > > ... ... deepin-terminal-5.2.11/3rdparty/terminalwidget/lib/translations/terminalwidget_tr.ts000066400000000000000000000112251370157770500310440ustar00rootroot00000000000000 Konsole::TerminalDisplay Size: XXX x XXX Boyut: XXX x XXX Size: %1 x %2 Boyut: %1 x %2 <qt>Output has been <a href="http://en.wikipedia.org/wiki/Flow_control">suspended</a> by pressing Ctrl+S. Press <b>Ctrl+Q</b> to resume.</qt> <qt>Çıktı <a href="http://en.wikipedia.org/wiki/Flow_control">suspended</a> Ctrl+S basınız. <b>Ctrl+Q</b> bas devam etmek için.</qt> Konsole::Vt102Emulation No keyboard translator available. The information needed to convert key presses into characters to send to the terminal is missing. Hiçbir klavye çevirici yok. Tuş vuruşlarını karaktere dönüştürüp terminale göndermek için gereken bilgi eksik. QObject Un-named Color Scheme İsimsiz Renk Şeması Accessible Color Scheme Erişilebilir Renk Şeması Open Link Bağlantıyı Aç Copy Link Address Bağlantı Adresini Kopyala Send Email To... E-posta gönder... Copy Email Address E-posta Adresini Kopyala QTermWidget Color Scheme Error Renk Şema Hatası Cannot load color scheme: %1 Renk şeması yüklenemedi: %1 SearchBar Match case Tam eşleştir Regular expression Düzenli ifade Highlight all matches Tüm eşleşenleri vurgula SearchBar Arama Çubuğu X X Find: Bul: < < > > ... ... deepin-terminal-5.2.11/3rdparty/terminalwidget/lib/translations/terminalwidget_zh_CN.ts000066400000000000000000000110261370157770500314170ustar00rootroot00000000000000 Konsole::TerminalDisplay Size: XXX x XXX 大小: XXX x XXX Size: %1 x %2 大小: %1 x %2 <qt>Output has been <a href="http://en.wikipedia.org/wiki/Flow_control">suspended</a> by pressing Ctrl+S. Press <b>Ctrl+Q</b> to resume.</qt> <qt>输出已被 Ctrl+S <a href="http://en.wikipedia.org/wiki/Flow_control">暂停</a>。按 <b>Ctrl+Q</b> 复原。</qt> Konsole::Vt102Emulation No keyboard translator available. The information needed to convert key presses into characters to send to the terminal is missing. 没有可用的键码转换表。找不到需要把按键转换至符号以传送至终端的信息。 QObject Un-named Color Scheme 未命名配色 Accessible Color Scheme 可用配色 Open link 打开链接 Copy link 复制链接 Send email to... 发送邮件至... Copy email address 复制邮件地址 QTermWidget Color Scheme Error 配色错误 Cannot load color scheme: %1 无法加载配色: %1 SearchBar Match case 匹配大小写 Regular expression 正则表达式 Highlight all matches 高亮所有匹配项 SearchBar 搜索栏 X X Find: 寻找: < < > > ... ... deepin-terminal-5.2.11/3rdparty/terminalwidget/lib/translations/terminalwidget_zh_TW.ts000066400000000000000000000110271370157770500314520ustar00rootroot00000000000000 Konsole::TerminalDisplay Size: XXX x XXX 大小:XXX x XXX Size: %1 x %2 大小:%1 x %2 <qt>Output has been <a href="http://en.wikipedia.org/wiki/Flow_control">suspended</a> by pressing Ctrl+S. Press <b>Ctrl+Q</b> to resume.</qt> <qt>輸出已被Ctrl+S<a href="http://en.wikipedia.org/wiki/Flow_control">暫停</a>。按<b>Ctrl+Q</b>復原。</qt> Konsole::Vt102Emulation No keyboard translator available. The information needed to convert key presses into characters to send to the terminal is missing. 沒有可用的鍵碼轉換表。用來將按鍵轉換成終端機字元的資訊遺失。 QObject Un-named Color Scheme 未命名的配色 Accessible Color Scheme 可用的配色 Open link 開啟連結 Copy link 複製連結 Send email to... 發送郵件至... Copy email address 複製郵件地址 QTermWidget Color Scheme Error 配色錯誤 Cannot load color scheme: %1 無法載入配色:%1 SearchBar Match case 符合大小寫 Regular expression 正規表示式 Highlight all matches 標亮所有相符的項目 SearchBar 搜尋列 X X Find: 搜尋: < < > > ... ... deepin-terminal-5.2.11/3rdparty/terminalwidget/pyqt/000077500000000000000000000000001370157770500224555ustar00rootroot00000000000000deepin-terminal-5.2.11/3rdparty/terminalwidget/pyqt/CMakeLists.txt000066400000000000000000000036361370157770500252250ustar00rootroot00000000000000set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} ${CMAKE_CURRENT_SOURCE_DIR}/cmake) # Match what's used in the main macros cmake_policy(SET CMP0002 OLD) find_package(PythonLibrary) include(PythonMacros) find_package(SIP) include(SIPMacros) if(SIP_VERSION STRLESS "040f03") # These version numbers also appear in ../CMakeLists.txt message(FATAL_ERROR "The version of SIP found is too old. 4.15.3 or later is needed.") endif() find_package(PyQt5) if(PYQT5_VERSION STRLESS "050101") # These version numbers also appear in ../CMakeLists.txt message(FATAL_ERROR "The version of PyQt found is too old. 5.1.1 or later is required.") endif() set(SIP_INCLUDES ${PYQT5_SIP_DIR} sip) set(SIP_CONCAT_PARTS 8) set(SIP_TAGS ALL WS_X11 ${PYQT5_VERSION_TAG}) set(SIP_DISABLE_FEATURES VendorID PyQt_NoPrintRangeBug) # Use an extra option when compiling on Python 3. if (PYTHON_VERSION_MAJOR GREATER 2) if(PYQT5_VERSION STRGREATER "040904") # Disable for newer PyQt set(SIP_EXTRA_OPTIONS -P -g) else () set(SIP_EXTRA_OPTIONS -g) endif() else (PYTHON_VERSION_MAJOR GREATER 2) if(PYQT5_VERSION STRGREATER "040904") # Disable for newer PyQt set(SIP_EXTRA_OPTIONS -P -g -x Py_v3) else () set(SIP_EXTRA_OPTIONS -g -x Py_v3) endif() endif () include_directories( "${SIP_INCLUDE_DIR}" ) add_definitions(-D_REENTRANT -DSIP_PROTECTED_IS_PUBLIC -Dprotected=public) file(GLOB qtermwidget_files_sip sip/*.sip) set(SIP_EXTRA_FILES_DEPEND "${qtermwidget_files_sip}") add_sip_python_module(QTermWidget sip/qtermwidget.sip qtermwidget5) python_install(__init__.py "${PYTHON_SITE_PACKAGES_INSTALL_DIR}/PyQt5/qtermwidget") set (SIP_FILES_INSTALL_DIR "${CMAKE_INSTALL_DATAROOTDIR}/sip") install(DIRECTORY sip/ DESTINATION "${SIP_FILES_INSTALL_DIR}/PyQt5/qtermwidget" PATTERN "*~" EXCLUDE # This sucks, why can't I just whitelist what I _do_ want? PATTERN ".svn" EXCLUDE PATTERN "*.in" EXCLUDE ) deepin-terminal-5.2.11/3rdparty/terminalwidget/pyqt/__init__.py000066400000000000000000000000001370157770500245540ustar00rootroot00000000000000deepin-terminal-5.2.11/3rdparty/terminalwidget/pyqt/cmake/000077500000000000000000000000001370157770500235355ustar00rootroot00000000000000deepin-terminal-5.2.11/3rdparty/terminalwidget/pyqt/cmake/COPYING-CMAKE-SCRIPTS000066400000000000000000000025261370157770500265400ustar00rootroot00000000000000 Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. The name of the author may not be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. deepin-terminal-5.2.11/3rdparty/terminalwidget/pyqt/cmake/FindPyQt5.cmake000066400000000000000000000037051370157770500263270ustar00rootroot00000000000000# Find PyQt5 # ~~~~~~~~~~ # Copyright (c) 2014, Simon Edwards # Redistribution and use is allowed according to the terms of the BSD license. # For details see the accompanying COPYING-CMAKE-SCRIPTS file. # # PyQt5 website: http://www.riverbankcomputing.co.uk/pyqt/index.php # # Find the installed version of PyQt5. FindPyQt5 should only be called after # Python has been found. # # This file defines the following variables: # # PYQT5_VERSION - The version of PyQt5 found expressed as a 6 digit hex number # suitable for comparison as a string # # PYQT5_VERSION_STR - The version of PyQt5 as a human readable string. # # PYQT5_VERSION_TAG - The PyQt version tag using by PyQt's sip files. # # PYQT5_SIP_DIR - The directory holding the PyQt5 .sip files. # # PYQT5_SIP_FLAGS - The SIP flags used to build PyQt. IF(EXISTS PYQT5_VERSION) # Already in cache, be silent SET(PYQT5_FOUND TRUE) ELSE(EXISTS PYQT5_VERSION) FIND_FILE(_find_pyqt5_py FindPyQt5.py PATHS ${CMAKE_MODULE_PATH}) EXECUTE_PROCESS(COMMAND ${PYTHON_EXECUTABLE} ${_find_pyqt5_py} OUTPUT_VARIABLE pyqt5_config) IF(pyqt5_config) STRING(REGEX REPLACE "^pyqt_version:([^\n]+).*$" "\\1" PYQT5_VERSION ${pyqt5_config}) STRING(REGEX REPLACE ".*\npyqt_version_str:([^\n]+).*$" "\\1" PYQT5_VERSION_STR ${pyqt5_config}) STRING(REGEX REPLACE ".*\npyqt_version_tag:([^\n]+).*$" "\\1" PYQT5_VERSION_TAG ${pyqt5_config}) STRING(REGEX REPLACE ".*\npyqt_sip_dir:([^\n]+).*$" "\\1" PYQT5_SIP_DIR ${pyqt5_config}) STRING(REGEX REPLACE ".*\npyqt_sip_flags:([^\n]+).*$" "\\1" PYQT5_SIP_FLAGS ${pyqt5_config}) SET(PYQT5_FOUND TRUE) ENDIF(pyqt5_config) IF(PYQT5_FOUND) IF(NOT PYQT5_FIND_QUIETLY) MESSAGE(STATUS "Found PyQt5 version: ${PYQT5_VERSION_STR}") ENDIF(NOT PYQT5_FIND_QUIETLY) ELSE(PYQT5_FOUND) IF(PYQT5_FIND_REQUIRED) MESSAGE(FATAL_ERROR "Could not find PyQt5.") ENDIF(PYQT5_FIND_REQUIRED) ENDIF(PYQT5_FOUND) ENDIF(EXISTS PYQT5_VERSION) deepin-terminal-5.2.11/3rdparty/terminalwidget/pyqt/cmake/FindPyQt5.py000066400000000000000000000015741370157770500257010ustar00rootroot00000000000000# Copyright (c) 2014, Simon Edwards # Redistribution and use is allowed according to the terms of the BSD license. # For details see the accompanying COPYING-CMAKE-SCRIPTS file. import PyQt5.Qt import sys import os.path print("pyqt_version:%06.0x" % PyQt5.Qt.PYQT_VERSION) print("pyqt_version_str:%s" % PyQt5.Qt.PYQT_VERSION_STR) pyqt_version_tag = "" in_t = False for item in PyQt5.Qt.PYQT_CONFIGURATION["sip_flags"].split(' '): if item=="-t": in_t = True elif in_t: if item.startswith("Qt_5"): pyqt_version_tag = item else: in_t = False print("pyqt_version_tag:%s" % pyqt_version_tag) # FIXME This next line is just a little bit too crude. pyqt_sip_dir = os.path.join(sys.prefix, "share", "sip", "PyQt5") print("pyqt_sip_dir:%s" % pyqt_sip_dir) print("pyqt_sip_flags:%s" % PyQt5.Qt.PYQT_CONFIGURATION["sip_flags"]) deepin-terminal-5.2.11/3rdparty/terminalwidget/pyqt/cmake/FindPythonLibrary.cmake000066400000000000000000000061541370157770500301540ustar00rootroot00000000000000# Find Python # ~~~~~~~~~~~ # Find the Python interpreter and related Python directories. # # This file defines the following variables: # # PYTHON_EXECUTABLE - The path and filename of the Python interpreter. # # PYTHON_SHORT_VERSION - The version of the Python interpreter found, # excluding the patch version number. (e.g. 2.5 and not 2.5.1)) # # PYTHON_LONG_VERSION - The version of the Python interpreter found as a human # readable string. # # PYTHON_SITE_PACKAGES_INSTALL_DIR - this cache variable can be used for installing # own python modules. You may want to adjust this to be the # same as ${PYTHON_SITE_PACKAGES_DIR}, but then admin # privileges may be required for installation. # # PYTHON_SITE_PACKAGES_DIR - Location of the Python site-packages directory. # # PYTHON_INCLUDE_PATH - Directory holding the python.h include file. # # PYTHON_LIBRARY, PYTHON_LIBRARIES- Location of the Python library. # Copyright (c) 2007, Simon Edwards # Copyright (c) 2012, Luca Beltrame # Redistribution and use is allowed according to the terms of the BSD license. # For details see the accompanying COPYING-CMAKE-SCRIPTS file. include(FindPackageHandleStandardArgs) find_package(PythonInterp) if (PYTHONINTERP_FOUND) option(INSTALL_PYTHON_FILES_IN_PYTHON_PREFIX "Install the Python files in the Python packages dir" FALSE) # Set the Python libraries to what we actually found for interpreters set(Python_ADDITIONAL_VERSIONS "${PYTHON_VERSION_MAJOR}.${PYTHON_VERSION_MINOR}") # These are kept for compatibility set(PYTHON_SHORT_VERSION "${PYTHON_VERSION_MAJOR}.${PYTHON_VERSION_MINOR}") set(PYTHON_LONG_VERSION ${PYTHON_VERSION_STRING}) find_package(PythonLibs) if(PYTHONLIBS_FOUND) set(PYTHON_LIBRARY ${PYTHON_LIBRARIES}) endif(PYTHONLIBS_FOUND) # Auto detect Python site-packages directory execute_process(COMMAND ${PYTHON_EXECUTABLE} -c "from distutils.sysconfig import get_python_lib; print(get_python_lib(True))" OUTPUT_VARIABLE PYTHON_SITE_PACKAGES_DIR OUTPUT_STRIP_TRAILING_WHITESPACE ) message(STATUS "Python system site-packages directory: ${PYTHON_SITE_PACKAGES_DIR}") if(INSTALL_PYTHON_FILES_IN_PYTHON_PREFIX) set(PYTHON_SITE_PACKAGES_INSTALL_DIR ${PYTHON_SITE_PACKAGES_DIR}) else() execute_process(COMMAND ${PYTHON_EXECUTABLE} -c "from distutils.sysconfig import get_python_lib; print(get_python_lib(True, prefix='${CMAKE_INSTALL_PREFIX}'))" OUTPUT_VARIABLE PYTHON_SITE_PACKAGES_INSTALL_DIR OUTPUT_STRIP_TRAILING_WHITESPACE ) endif() if(NOT PYTHON_SITE_PACKAGES_INSTALL_DIR STREQUAL PYTHON_SITE_PACKAGES_DIR) message(STATUS "The Python files will be installed to ${PYTHON_SITE_PACKAGES_INSTALL_DIR}. Make sure to add them to the Python search path (e.g. by setting PYTHONPATH)") endif() endif(PYTHONINTERP_FOUND) find_package_handle_standard_args(PythonLibrary DEFAULT_MSG PYTHON_LIBRARY) deepin-terminal-5.2.11/3rdparty/terminalwidget/pyqt/cmake/FindSIP.cmake000066400000000000000000000043431370157770500257770ustar00rootroot00000000000000# Find SIP # ~~~~~~~~ # # SIP website: http://www.riverbankcomputing.co.uk/sip/index.php # # Find the installed version of SIP. FindSIP should be called after Python # has been found. # # This file defines the following variables: # # SIP_VERSION - The version of SIP found expressed as a 6 digit hex number # suitable for comparison as a string. # # SIP_VERSION_STR - The version of SIP found as a human readable string. # # SIP_EXECUTABLE - Path and filename of the SIP command line executable. # # SIP_INCLUDE_DIR - Directory holding the SIP C++ header file. # # SIP_DEFAULT_SIP_DIR - Default directory where .sip files should be installed # into. # Copyright (c) 2007, Simon Edwards # Redistribution and use is allowed according to the terms of the BSD license. # For details see the accompanying COPYING-CMAKE-SCRIPTS file. IF(SIP_VERSION) # Already in cache, be silent SET(SIP_FOUND TRUE) ELSE(SIP_VERSION) FIND_FILE(_find_sip_py FindSIP.py PATHS ${CMAKE_MODULE_PATH}) EXECUTE_PROCESS(COMMAND ${PYTHON_EXECUTABLE} ${_find_sip_py} OUTPUT_VARIABLE sip_config) IF(sip_config) STRING(REGEX REPLACE "^sip_version:([^\n]+).*$" "\\1" SIP_VERSION ${sip_config}) STRING(REGEX REPLACE ".*\nsip_version_str:([^\n]+).*$" "\\1" SIP_VERSION_STR ${sip_config}) STRING(REGEX REPLACE ".*\nsip_bin:([^\n]+).*$" "\\1" SIP_EXECUTABLE ${sip_config}) IF(NOT SIP_DEFAULT_SIP_DIR) STRING(REGEX REPLACE ".*\ndefault_sip_dir:([^\n]+).*$" "\\1" SIP_DEFAULT_SIP_DIR ${sip_config}) ENDIF(NOT SIP_DEFAULT_SIP_DIR) STRING(REGEX REPLACE ".*\nsip_inc_dir:([^\n]+).*$" "\\1" SIP_INCLUDE_DIR ${sip_config}) FILE(TO_CMAKE_PATH ${SIP_DEFAULT_SIP_DIR} SIP_DEFAULT_SIP_DIR) FILE(TO_CMAKE_PATH ${SIP_INCLUDE_DIR} SIP_INCLUDE_DIR) IF(EXISTS ${SIP_EXECUTABLE}) SET(SIP_FOUND TRUE) ELSE() MESSAGE(STATUS "Found SIP configuration but the sip executable could not be found.") ENDIF() ENDIF(sip_config) IF(SIP_FOUND) IF(NOT SIP_FIND_QUIETLY) MESSAGE(STATUS "Found SIP version: ${SIP_VERSION_STR}") ENDIF(NOT SIP_FIND_QUIETLY) ELSE(SIP_FOUND) IF(SIP_FIND_REQUIRED) MESSAGE(FATAL_ERROR "Could not find SIP") ENDIF(SIP_FIND_REQUIRED) ENDIF(SIP_FOUND) ENDIF(SIP_VERSION) deepin-terminal-5.2.11/3rdparty/terminalwidget/pyqt/cmake/FindSIP.py000066400000000000000000000010051370157770500253370ustar00rootroot00000000000000# FindSIP.py # # Copyright (c) 2007, Simon Edwards # Redistribution and use is allowed according to the terms of the BSD license. # For details see the accompanying COPYING-CMAKE-SCRIPTS file. import sys import sipconfig sipcfg = sipconfig.Configuration() print("sip_version:%06.0x" % sipcfg.sip_version) print("sip_version_str:%s" % sipcfg.sip_version_str) print("sip_bin:%s" % sipcfg.sip_bin) print("default_sip_dir:%s" % sipcfg.default_sip_dir) print("sip_inc_dir:%s" % sipcfg.sip_inc_dir) deepin-terminal-5.2.11/3rdparty/terminalwidget/pyqt/cmake/PythonCompile.py000066400000000000000000000002011370157770500266720ustar00rootroot00000000000000# By Simon Edwards # This file is in the public domain. import py_compile, sys sys.exit(py_compile.main()) deepin-terminal-5.2.11/3rdparty/terminalwidget/pyqt/cmake/PythonMacros.cmake000066400000000000000000000062221370157770500271670ustar00rootroot00000000000000# Python macros # ~~~~~~~~~~~~~ # Copyright (c) 2007, Simon Edwards # Copyright (c) 2012, Luca Beltrame # Copyright (c) 2012, Rolf Eike Beer # # Redistribution and use is allowed according to the terms of the BSD license. # For details see the accompanying COPYING-CMAKE-SCRIPTS file. # # This file defines the following macros: # # PYTHON_INSTALL (SOURCE_FILE DESTINATION_DIR) # Install the SOURCE_FILE, which is a Python .py file, into the # destination directory during install. The file will be byte compiled # and both the .py file and .pyc file will be installed. set(PYTHON_MACROS_MODULE_PATH ${CMAKE_CURRENT_LIST_DIR}) macro(PYTHON_INSTALL SOURCE_FILE DESTINATION_DIR) find_file(_python_compile_py PythonCompile.py PATHS ${CMAKE_MODULE_PATH}) # Install the source file. install(FILES ${SOURCE_FILE} DESTINATION ${DESTINATION_DIR}) # Byte compile and install the .pyc file, unless explicitly prevented by env.. if("$ENV{PYTHONDONTWRITEBYTECODE}" STREQUAL "") get_filename_component(_absfilename ${SOURCE_FILE} ABSOLUTE) get_filename_component(_filename ${SOURCE_FILE} NAME) get_filename_component(_filenamebase ${SOURCE_FILE} NAME_WE) get_filename_component(_basepath ${SOURCE_FILE} PATH) if(WIN32) # remove drive letter string(REGEX REPLACE "^[a-zA-Z]:/" "/" _basepath "${_basepath}") endif(WIN32) set(_bin_py ${CMAKE_CURRENT_BINARY_DIR}/${_basepath}/${_filename}) # Python 3.2 changed the pyc file location if(PYTHON_VERSION_STRING VERSION_GREATER 3.1) # To get the right version for suffix set(_bin_pyc "${CMAKE_CURRENT_BINARY_DIR}/${_basepath}/__pycache__/${_filenamebase}.cpython-${PYTHON_VERSION_MAJOR}${PYTHON_VERSION_MINOR}.pyc") set(_py_install_dir "${DESTINATION_DIR}/__pycache__/") else() set(_bin_pyc "${CMAKE_CURRENT_BINARY_DIR}/${_basepath}/${_filenamebase}.pyc") set(_py_install_dir "${DESTINATION_DIR}") endif() file(MAKE_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/${_basepath}) # Setting because it will be displayed later, in compile_python_files set(_message "Byte-compiling ${_bin_py} to ${_bin_pyc}") string(REPLACE "/" "_" _rule_name "${_basepath}/${_bin_pyc}") add_custom_target("${_rule_name}" ALL) get_filename_component(_abs_bin_py ${_bin_py} ABSOLUTE) if(_abs_bin_py STREQUAL _absfilename) # Don't copy the file onto itself. add_custom_command( TARGET "${_rule_name}" COMMAND "${CMAKE_COMMAND}" -E echo "${_message}" COMMAND "${PYTHON_EXECUTABLE}" "${_python_compile_py}" "${_bin_py}" DEPENDS "${_absfilename}" ) else() add_custom_command( TARGET "${_rule_name}" COMMAND "${CMAKE_COMMAND}" -E echo "${_message}" COMMAND "${CMAKE_COMMAND}" -E copy "${_absfilename}" "${_bin_py}" COMMAND "${PYTHON_EXECUTABLE}" "${_python_compile_py}" "${_bin_py}" DEPENDS "${_absfilename}" ) endif() install(FILES ${_bin_pyc} DESTINATION "${_py_install_dir}") unset(_py_install_dir) unset(_message) endif("$ENV{PYTHONDONTWRITEBYTECODE}" STREQUAL "") endmacro(PYTHON_INSTALL) deepin-terminal-5.2.11/3rdparty/terminalwidget/pyqt/cmake/SIPMacros.cmake000066400000000000000000000120501370157770500263350ustar00rootroot00000000000000# Macros for SIP # ~~~~~~~~~~~~~~ # Copyright (c) 2007, Simon Edwards # Redistribution and use is allowed according to the terms of the BSD license. # For details see the accompanying COPYING-CMAKE-SCRIPTS file. # # SIP website: http://www.riverbankcomputing.co.uk/sip/index.php # # This file defines the following macros: # # ADD_SIP_PYTHON_MODULE (MODULE_NAME MODULE_SIP [library1, libaray2, ...]) # Specifies a SIP file to be built into a Python module and installed. # MODULE_NAME is the name of Python module including any path name. (e.g. # os.sys, Foo.bar etc). MODULE_SIP the path and filename of the .sip file # to process and compile. libraryN are libraries that the Python module, # which is typically a shared library, should be linked to. The built # module will also be install into Python's site-packages directory. # # The behaviour of the ADD_SIP_PYTHON_MODULE macro can be controlled by a # number of variables: # # SIP_INCLUDES - List of directories which SIP will scan through when looking # for included .sip files. (Corresponds to the -I option for SIP.) # # SIP_TAGS - List of tags to define when running SIP. (Corresponds to the -t # option for SIP.) # # SIP_CONCAT_PARTS - An integer which defines the number of parts the C++ code # of each module should be split into. Defaults to 8. (Corresponds to the # -j option for SIP.) # # SIP_DISABLE_FEATURES - List of feature names which should be disabled # running SIP. (Corresponds to the -x option for SIP.) # # SIP_EXTRA_OPTIONS - Extra command line options which should be passed on to # SIP. SET(SIP_INCLUDES) SET(SIP_TAGS) SET(SIP_CONCAT_PARTS 8) SET(SIP_DISABLE_FEATURES) SET(SIP_EXTRA_OPTIONS) MACRO(ADD_SIP_PYTHON_MODULE MODULE_NAME MODULE_SIP) SET(EXTRA_LINK_LIBRARIES ${ARGN}) STRING(REPLACE "." "/" _x ${MODULE_NAME}) GET_FILENAME_COMPONENT(_parent_module_path ${_x} PATH) GET_FILENAME_COMPONENT(_child_module_name ${_x} NAME) GET_FILENAME_COMPONENT(_module_path ${MODULE_SIP} PATH) if(_module_path STREQUAL "") set(CMAKE_CURRENT_SIP_OUTPUT_DIR "${CMAKE_CURRENT_BINARY_DIR}") else(_module_path STREQUAL "") set(CMAKE_CURRENT_SIP_OUTPUT_DIR "${CMAKE_CURRENT_BINARY_DIR}/${_module_path}") endif(_module_path STREQUAL "") GET_FILENAME_COMPONENT(_abs_module_sip ${MODULE_SIP} ABSOLUTE) # We give this target a long logical target name. # (This is to avoid having the library name clash with any already # install library names. If that happens then cmake dependancy # tracking get confused.) STRING(REPLACE "." "_" _logical_name ${MODULE_NAME}) SET(_logical_name "python_module_${_logical_name}") FILE(MAKE_DIRECTORY ${CMAKE_CURRENT_SIP_OUTPUT_DIR}) # Output goes in this dir. SET(_sip_includes) FOREACH (_inc ${SIP_INCLUDES}) GET_FILENAME_COMPONENT(_abs_inc ${_inc} ABSOLUTE) LIST(APPEND _sip_includes -I ${_abs_inc}) ENDFOREACH (_inc ) SET(_sip_tags) FOREACH (_tag ${SIP_TAGS}) LIST(APPEND _sip_tags -t ${_tag}) ENDFOREACH (_tag) SET(_sip_x) FOREACH (_x ${SIP_DISABLE_FEATURES}) LIST(APPEND _sip_x -x ${_x}) ENDFOREACH (_x ${SIP_DISABLE_FEATURES}) SET(_message "-DMESSAGE=Generating CPP code for module ${MODULE_NAME}") SET(_sip_output_files) FOREACH(CONCAT_NUM RANGE 0 ${SIP_CONCAT_PARTS} ) IF( ${CONCAT_NUM} LESS ${SIP_CONCAT_PARTS} ) SET(_sip_output_files ${_sip_output_files} ${CMAKE_CURRENT_SIP_OUTPUT_DIR}/sip${_child_module_name}part${CONCAT_NUM}.cpp ) ENDIF( ${CONCAT_NUM} LESS ${SIP_CONCAT_PARTS} ) ENDFOREACH(CONCAT_NUM RANGE 0 ${SIP_CONCAT_PARTS} ) IF(NOT WIN32) SET(TOUCH_COMMAND touch) ELSE(NOT WIN32) SET(TOUCH_COMMAND echo) # instead of a touch command, give out the name and append to the files # this is basically what the touch command does. FOREACH(filename ${_sip_output_files}) FILE(APPEND filename "") ENDFOREACH(filename ${_sip_output_files}) ENDIF(NOT WIN32) ADD_CUSTOM_COMMAND( OUTPUT ${_sip_output_files} COMMAND ${CMAKE_COMMAND} -E echo ${message} COMMAND ${TOUCH_COMMAND} ${_sip_output_files} COMMAND ${SIP_EXECUTABLE} ${_sip_tags} ${_sip_x} ${SIP_EXTRA_OPTIONS} -j ${SIP_CONCAT_PARTS} -c ${CMAKE_CURRENT_SIP_OUTPUT_DIR} ${_sip_includes} ${_abs_module_sip} DEPENDS ${_abs_module_sip} ${SIP_EXTRA_FILES_DEPEND} ) # not sure if type MODULE could be uses anywhere, limit to cygwin for now IF (CYGWIN) ADD_LIBRARY(${_logical_name} MODULE ${_sip_output_files} ) ELSE (CYGWIN) ADD_LIBRARY(${_logical_name} SHARED ${_sip_output_files} ) ENDIF (CYGWIN) TARGET_LINK_LIBRARIES(${_logical_name} ${PYTHON_LIBRARY}) TARGET_LINK_LIBRARIES(${_logical_name} ${EXTRA_LINK_LIBRARIES}) SET_TARGET_PROPERTIES(${_logical_name} PROPERTIES PREFIX "" OUTPUT_NAME ${_child_module_name}) INSTALL(TARGETS ${_logical_name} DESTINATION "${PYTHON_SITE_PACKAGES_INSTALL_DIR}/${_parent_module_path}") ENDMACRO(ADD_SIP_PYTHON_MODULE) deepin-terminal-5.2.11/3rdparty/terminalwidget/pyqt/sip/000077500000000000000000000000001370157770500232505ustar00rootroot00000000000000deepin-terminal-5.2.11/3rdparty/terminalwidget/pyqt/sip/qtermwidget.sip000066400000000000000000000066251370157770500263320ustar00rootroot00000000000000%Module QTermWidget %ModuleHeaderCode #pragma GCC visibility push(default) %End %Import QtGui/QtGuimod.sip %Import QtCore/QtCoremod.sip %Import QtWidgets/QtWidgetsmod.sip class QTermWidget : QWidget { %TypeHeaderCode #include <../lib/qtermwidget.h> %End public: enum ScrollBarPosition { NoScrollBar=0, ScrollBarLeft=1, ScrollBarRight=2 }; enum class KeyboardCursorShape { BlockCursor=0, UnderlineCursor=1, IBeamCursor=2 }; QTermWidget(int startnow = 1, QWidget *parent = 0); ~QTermWidget(); void startTerminalTeletype(); QSize sizeHint() const; void setTerminalSizeHint(bool on); bool terminalSizeHint(); void startShellProgram(); int getShellPID(); void changeDir(const QString & dir); void setTerminalFont(QFont &font); QFont getTerminalFont(); void setTerminalOpacity(qreal level); void setEnvironment(const QStringList & environment); void setShellProgram(const QString & progname); void setWorkingDirectory(const QString & dir); QString workingDirectory(); void setArgs(QStringList & args); void setTextCodec(QTextCodec *codec); void setColorScheme(const QString & name); static QStringList availableColorSchemes(); static void addCustomColorSchemeDir(const QString& custom_dir); void setHistorySize(int lines); void setScrollBarPosition(ScrollBarPosition); void scrollToEnd(); void sendText(QString &text); void setFlowControlEnabled(bool enabled); bool flowControlEnabled(); void setFlowControlWarningEnabled(bool enabled); static QStringList availableKeyBindings(); QString keyBindings(); void setMotionAfterPasting(int); int historyLinesCount(); int screenColumnsCount(); void setSelectionStart(int row, int column); void setSelectionEnd(int row, int column); void getSelectionStart(int& row, int& column); void getSelectionEnd(int& row, int& column); QString selectedText(bool preserveLineBreaks = true); void setMonitorActivity(bool); void setMonitorSilence(bool); void setSilenceTimeout(int seconds); int getPtySlaveFd() const; void setKeyboardCursorShape(KeyboardCursorShape shape); void setAutoClose(bool); QString title() const; QString icon() const; signals: void finished(); void copyAvailable(bool); void termGetFocus(); void termLostFocus(); void termKeyPressed(QKeyEvent *); void urlActivated(const QUrl&, bool fromContextMenu); void bell(const QString& message); void activity(); void silence(); void sendData(const char *,int); void titleChanged(); void receivedData(const QString &text); void profileChanged(const QString & profile); public slots: void copyClipboard(); void pasteClipboard(); void pasteSelection(); void zoomIn(); void zoomOut(); void setSize(const QSize &); void setKeyBindings(const QString & kb); void clear(); void toggleShowSearchBar(); protected: virtual void resizeEvent(QResizeEvent *); protected slots: void sessionFinished(); void selectionChanged(bool textSelected); private: void search(bool forwards, bool next); void setZoom(int step); void init(int startnow); private slots: void find(); void findNext(); void findPrevious(); void matchFound(int startColumn, int startLine, int endColumn, int endLine); void noMatchFound(); }; deepin-terminal-5.2.11/3rdparty/terminalwidget/qtermwidget.spec000066400000000000000000000056001370157770500246710ustar00rootroot00000000000000# norootforbuild %define libname libqtermwidget0 Name: qtermwidget Summary: Qt4 terminal widget Version: 0.2.0 Release: 1 License: GPL Source: %{name}-%{version}.tar.bz2 Group: Utility URL: https://github.com/qterminal Vendor: petr@yarpen.cz %if 0%{?fedora_version} %define breq qt4-devel %define pref %{buildroot}/usr %endif %if 0%{?mandriva_version} %define breq libqt4-devel %define pref %{buildroot}/usr %endif %if 0%{?suse_version} %define breq libqt4-devel %define pref %{_prefix} %endif BuildRequires: gcc-c++, %{breq}, cmake BuildRoot: %{_tmppath}/%{name}-%{version}-build Prefix: %{_prefix} %description QTermWidget is an opensource project based on KDE4 Konsole application. The main goal of this project is to provide unicode-enabled, embeddable QT4 widget for using as a built-in console (or terminal emulation widget). Of course I`m aware about embedding abilities of original Konsole, but once I had Qt without KDE, and it was a serious problem. I decided not to rely on a chance. I could not find any interesting related project, so I had to write it. The original Konsole`s code was rewritten entirely with QT4 only; also I have to include in the project some parts of code from kde core library. All code dealing with user interface parts and session management was removed (maybe later I bring it back somehow), and the result is quite useful, I suppose. This library was compiled and tested on three linux systems, based on 2.4.32, 2.6.20, 2.6.23 kernels, x86 and amd64. Ther is also a sample application provided for quick start. %package -n %{libname} Summary: Qt4 terminal widget - base package Group: "Development/Libraries/C and C++" %description -n %{libname} QTermWidget is an opensource project based on KDE4 Konsole application. The main goal of this project is to provide unicode-enabled, embeddable QT4 widget for using as a built-in console (or terminal emulation widget). %package devel Summary: Qt4 terminal widget - development package Group: "Development/Libraries/C and C++" Requires: %{libname} %description devel Development package for QTermWidget. Contains headers and dev-libs. %prep %setup %build cmake \ -DCMAKE_C_FLAGS="%{optflags}" \ -DCMAKE_CXX_FLAGS="%{optflags}" \ -DCMAKE_BUILD_TYPE=Debug \ -DCMAKE_INSTALL_PREFIX=%{pref} \ %{_builddir}/%{name}-%{version} %{__make} %{?jobs:-j%jobs} %install %makeinstall %clean %{__rm} -rf %{buildroot} %post -n %{libname} ldconfig %postun -n %{libname} ldconfig %files -n %{libname} %defattr(-,root,root,-) %doc AUTHORS LICENSE Changelog INSTALL README %{_libdir}/lib%{name}.so.%{version} %{_datadir}/%{name} %{_datadir}/%{name}/* %files devel %defattr(-,root,root,-) %{_includedir}/*.h %{_libdir}/*.so %{_libdir}/*.so.0 %changelog * Mon Oct 29 2010 Petr Vanek 0.2 - version bump, cmake builds * Sat Jul 26 2008 TI_Eugene 0.100 - Initial build deepin-terminal-5.2.11/CMakeLists.txt000066400000000000000000000224611370157770500174360ustar00rootroot00000000000000project(deepin-terminal) cmake_minimum_required(VERSION 3.9.5) list(APPEND CMAKE_MODULE_PATH ${CMAKE_CURRENT_LIST_DIR}) include (src/DtkSettingsToolsMacros) set(CMAKE_C_STANDARD 11) set(CMAKE_C_STANDARD_REQUIRED ON) set(CMAKE_CXX_STANDARD 11) # Find includes in corresponding build directories set(CMAKE_INCLUDE_CURRENT_DIR ON) # Instruct CMake to run moc automatically when needed set(CMAKE_AUTOMOC ON) set(CMAKE_AUTORCC ON) set(QT_MINIMUM_VERSION "5.7.1") if (${CMAKE_SYSTEM_PROCESSOR} MATCHES "sw_64") set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -mieee") endif () #compile flags if (CMAKE_BUILD_TYPE MATCHES Debug) set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -g -Wall -Wextra") set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -g -Wall -Wextra") # Enable Qt builtin debug mode add_definitions("-DQT_MESSAGELOGCONTEXT") else() # -Wl, -O2 Enable linker optimizations # -Wl, --gc-sections set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wall -O2 -Wl,-O1 -Wl,--gc-sections") set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -O2 -Wl,-O1 -Wl,--gc-sections") endif() configure_file(src/environments.h.in environments.h @ONLY) # Find the QtWidgets library find_package(PkgConfig REQUIRED) find_package(Qt5Core REQUIRED) find_package(Qt5DBus REQUIRED) find_package(Qt5Gui REQUIRED) find_package(Qt5Widgets REQUIRED) find_package(Qt5LinguistTools REQUIRED) find_package(Qt5Network REQUIRED) #find_package(DtkWidget REQUIRED) #find_package(DtkCore REQUIRED) #find_package(DtkGui REQUIRED) include(FindPkgConfig) pkg_search_module(DtkWidget REQUIRED dtkwidget) pkg_search_module(DtkGui REQUIRED dtkgui) pkg_search_module(DtkCore REQUIRED dtkcore) pkg_search_module(GOBJECT REQUIRED gobject-2.0) pkg_check_modules(ATSPI2 REQUIRED atspi-2) pkg_check_modules(DFrameworkDBus REQUIRED dframeworkdbus) # Compile definitions for TerminalWidget # So we can use QT_VERSION_CHECK set(TERMINALWIDGET_VERSION_MAJOR "0") set(TERMINALWIDGET_VERSION_MINOR "14") set(TERMINALWIDGET_VERSION_PATCH "1") add_subdirectory(3rdparty/terminalwidget) include_directories(${DtkWidget_INCLUDE_DIRS}) include_directories(${DtkGui_INCLUDE_DIRS}) include_directories(${DtkCore_INCLUDE_DIRS}) include_directories("src/common") include_directories("src/customcommand") include_directories("src/encodeplugin") include_directories("src/main") include_directories("src/quaketerminal") include_directories("src/remotemanage") include_directories("src/settings") include_directories("src/theme") include_directories("src/views") include_directories("3rdparty/terminalwidget/lib") set(LINK_LIBS Qt5::Core Qt5::DBus Qt5::Widgets Qt5::WidgetsPrivate Qt5::Network ${DtkWidget_LIBRARIES} ${DtkCore_LIBRARIES} ${DtkGUI_LIBRARIES} ${DFrameworkDBus_LIBRARIES} ${ATSPI2_LIBRARIES} ${GOBJECT_LIBRARIES} ) # Populate a CMake variable with the sources # TODO: portable headers? set (DTNG_CPP_FILES src/common/utils.cpp src/customcommand/customcommanddelegate.cpp src/customcommand/customcommanditemmodel.cpp src/customcommand/customcommandlist.cpp src/customcommand/customcommandoptdlg.cpp src/customcommand/customcommandpanel.cpp src/customcommand/customcommandplugin.cpp src/customcommand/customcommandsearchrstpanel.cpp src/customcommand/customcommandtoppanel.cpp src/encodeplugin/encodepanelplugin.cpp src/encodeplugin/encodepanel.cpp src/encodeplugin/encodelistview.cpp src/encodeplugin/encodelistmodel.cpp src/main/main.cpp src/main/service.cpp src/main/windowsmanager.cpp src/main/mainwindow.cpp src/main/terminalapplication.cpp src/main/termproperties.cpp src/main/dbusmanager.cpp src/main/atspidesktop.cpp src/quaketerminal/quaketerminaladapter.cpp src/quaketerminal/quaketerminalproxy.cpp src/quaketerminal/termargumentparser.cpp src/remotemanage/remotemanagementpanel.cpp src/remotemanage/remotemanagementplugn.cpp src/remotemanage/remotemanagementsearchpanel.cpp src/remotemanage/remotemanagementtoppanel.cpp src/remotemanage/serverconfigdelegate.cpp src/remotemanage/serverconfiggrouppanel.cpp src/remotemanage/serverconfigitemmodel.cpp src/remotemanage/serverconfiglist.cpp src/remotemanage/serverconfigmanager.cpp src/remotemanage/serverconfigoptdlg.cpp src/settings/newdspinbox.cpp src/settings/settings.cpp src/settings/settings_translation.cpp src/settings/shortcutmanager.cpp src/theme/themeitemdelegate.cpp src/theme/themelistmodel.cpp src/theme/themelistview.cpp src/theme/themepanel.cpp src/theme/themepanelplugin.cpp src/views/commonpanel.cpp src/views/myiconbutton.cpp src/views/warnningdlg.cpp src/views/operationconfirmdlg.cpp src/views/pagesearchbar.cpp src/views/rightpanel.cpp src/views/tabbar.cpp src/views/termwidget.cpp src/views/termwidgetpage.cpp src/views/termbasedialog.cpp src/views/terminputdialog.cpp src/views/termcommandlinkbutton.cpp src/views/titlebar.cpp ) set (DTNG_HEADER_FILES src/common/define.h src/common/utils.h src/customcommand/customcommanddelegate.h src/customcommand/customcommanditemmodel.h src/customcommand/customcommandlist.h src/customcommand/customcommandoptdlg.h src/customcommand/customcommandpanel.h src/customcommand/customcommandplugin.h src/customcommand/customcommandsearchrstpanel.h src/customcommand/customcommandtoppanel.h src/encodeplugin/encodepanelplugin.h src/encodeplugin/encodepanel.h src/encodeplugin/encodelistview.h src/encodeplugin/encodelistmodel.h src/main/windowsmanager.h src/main/mainwindow.h src/main/mainwindowplugininterface.h src/main/service.h src/main/terminalapplication.h src/main/termproperties.h src/main/dbusmanager.h src/main/atspidesktop.h src/quaketerminal/quaketerminaladapter.h src/quaketerminal/quaketerminalproxy.h src/quaketerminal/termargumentparser.h src/remotemanage/remotemanagementpanel.h src/remotemanage/remotemanagementplugn.h src/remotemanage/remotemanagementsearchpanel.h src/remotemanage/remotemanagementtoppanel.h src/remotemanage/serverconfigdelegate.h src/remotemanage/serverconfiggrouppanel.h src/remotemanage/serverconfigitemmodel.h src/remotemanage/serverconfiglist.h src/remotemanage/serverconfigmanager.h src/remotemanage/serverconfigoptdlg.h src/settings/newdspinbox.h src/settings/settings.h src/settings/shortcutmanager.h src/theme/themeitemdelegate.h src/theme/themelistmodel.h src/theme/themelistview.h src/theme/themepanel.h src/theme/themepanelplugin.h src/views/commonpanel.h src/views/myiconbutton.h src/views/operationconfirmdlg.h src/views/warnningdlg.h src/views/pagesearchbar.h src/views/rightpanel.h src/views/tabbar.h src/views/termwidget.h src/views/termwidgetpage.h src/views/titlebar.h src/views/termbasedialog.h src/views/terminputdialog.h src/views/termcommandlinkbutton.h ) set (DTNG_QRC_FILES src/assets/resources.qrc ) # Program set (EXE_NAME deepin-terminal) # Translation file (GLOB DTNG_TS_FILES translations/*.ts) set (DTNG_CPP_FILES_FOR_I18N ${DTNG_CPP_FILES}) dtk_create_i18n_from_json(DTNG_SETTINGS_I18N_FILES default-config.json settings_translation.cpp) list (APPEND DTNG_CPP_FILES_FOR_I18N ${DTNG_SETTINGS_I18N_FILES}) qt5_create_translation(DTNG_QM_FILES ${DTNG_CPP_FILES_FOR_I18N} ${DTNG_TS_FILES}) add_executable (${EXE_NAME} ${DTNG_HEADER_FILES} ${DTNG_CPP_FILES} ${DTNG_QRC_FILES} ${DTNG_QM_FILES} ) target_include_directories(${EXE_NAME} PUBLIC ${Qt5Widgets_LIBRARIES} ${Qt5DBus_LIBRARIES} ${Qt5Widgets_PRIVATE_INCLUDE_DIRS} ${Qt5Core_PRIVATE_INCLUDE_DIRS} ${Qt5Gui_PRIVATE_INCLUDE_DIRS} ${PROJECT_BINARY_DIR} ${DtkWidget_INCLUDE_DIRS} ${DtkCore_LIBRARIES} ${DtkGUI_INCLUDE_DIRS} ${DFrameworkDBus_INCLUDE_DIRS} ${ATSPI2_INCLUDE_DIRS} ${GOBJECT_INCLUDE_DIRS}) target_link_libraries (deepin-terminal ${LINK_LIBS} terminalwidget5) # Install settings if (CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT) set(CMAKE_INSTALL_PREFIX /usr) endif () # Installation #install(TARGETS deepin-terminal DESTINATION ${CMAKE_INSTALL_PREFIX}/share/deepin-terminal) install(FILES src/deepin-terminal.desktop DESTINATION ${CMAKE_INSTALL_PREFIX}/share/applications/) install(FILES src/assets/logo/deepin-terminal.svg DESTINATION ${CMAKE_INSTALL_PREFIX}/share/icons/hicolor/scalable/apps/) # add this empty file for first install/reinstall judge install(FILES src/assets/other/install_flag DESTINATION $ENV{HOME}/.config/deepin/deepin-terminal/) install(FILES ${CMAKE_CURRENT_BINARY_DIR}/deepin-terminal DESTINATION ${CMAKE_INSTALL_PREFIX}/bin PERMISSIONS OWNER_READ OWNER_EXECUTE GROUP_READ GROUP_EXECUTE WORLD_READ WORLD_EXECUTE) install(FILES ${DTNG_QM_FILES} DESTINATION ${CMAKE_INSTALL_PREFIX}/share/deepin-terminal/translations) deepin-terminal-5.2.11/LICENSE000066400000000000000000001045131370157770500157020ustar00rootroot00000000000000 GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: Copyright (C) This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read . deepin-terminal-5.2.11/README.md000066400000000000000000000033121370157770500161470ustar00rootroot00000000000000# Deepin Terminal Deepin Terminal is an advanced terminal emulator with workspace , multiple windows, remote management, quake mode and other features. ## Dependencies ### Build dependencies * cmake * pkg-config * Qt5(>= 5.7.1) with modules: - qt5-default - qtbase5-dev - qtbase5-private-dev - qttools5-dev-tools * libdtkwidget-dev(>=5.1.0) with modules: - dtkcore-dev - dtkwidget-dev - dtkgui-dev * lxqt-build-tools(>= 0.6.0) * libutf8proc-dev ### Debian based distro for lazy guy ``` shell $ cd /path/to/the/source/ $ sudo apt build-dep . ``` ### Other distro CMake will tell you which package you are missing. ### Build: Generic CMake way: ``` shell $ cd /path/to/the/source/ $ mkdir build && cd build $ cmake .. $ make $ ./deepin-terminal ``` ## Config file * Terminal Settings's configure save at:
~/.config/deepin/deepin-terminal/config.conf * Remote Servers' configure save at:
~/.config/deepin/deepin-terminal/server-config.conf * Custom Command's configure save at:
~/.config/deepin/deepin-terminal/command-config.conf ## Getting help Any usage issues can ask for help via * [Gitter](https://gitter.im/orgs/linuxdeepin/rooms) * [IRC channel](https://webchat.freenode.net/?channels=deepin) * [Forum](https://bbs.deepin.org) * [WiKi](https://wiki.deepin.org/) ## Getting involved We encourage you to report issues and contribute changes * [Contribution guide for developers](https://github.com/linuxdeepin/developer-center/wiki/Contribution-Guidelines-for-Developers-en). (English) * [开发者代码贡献指南](https://github.com/linuxdeepin/developer-center/wiki/Contribution-Guidelines-for-Developers) (中文) ## License Deepin Terminal is licensed under [GPLv3](LICENSE). deepin-terminal-5.2.11/debian/000077500000000000000000000000001370157770500161135ustar00rootroot00000000000000deepin-terminal-5.2.11/debian/changelog000066400000000000000000000002331370157770500177630ustar00rootroot00000000000000deepin-terminal (5.2.0) unstable; urgency=medium * Initial Release. -- Deepin Packages Builder Mon, 13 Jan 2020 16:13:35 +0800 deepin-terminal-5.2.11/debian/compat000066400000000000000000000000021370157770500173110ustar00rootroot000000000000009 deepin-terminal-5.2.11/debian/control000066400000000000000000000011031370157770500175110ustar00rootroot00000000000000Source: deepin-terminal Section: utils Priority: optional Maintainer: Deepin Terminal Build-Depends: debhelper (>= 9), cmake, pkg-config, qt5-default, qtbase5-dev, qttools5-dev-tools, qtbase5-private-dev, libdtkwidget-dev, libdframeworkdbus-dev, lxqt-build-tools (>= 0.6.0~), libutf8proc-dev, libatspi2.0-dev, libglib2.0-dev Standards-Version: 3.9.8 Homepage: https://www.deepin.com/ Package: deepin-terminal Architecture: any Depends: ${shlibs:Depends}, ${misc:Depends}, expect, zssh, qt-at-spi, at-spi2-core Description: deepin terminal Deepin Terminal deepin-terminal-5.2.11/debian/deepin-terminal.postrm000066400000000000000000000001671370157770500224420ustar00rootroot00000000000000#!/bin/sh userName=$(who) if [ $1 = "purge" ]; then rm -rf /home/${userName%% *}/.config/deepin/deepin-terminal/* fi deepin-terminal-5.2.11/debian/rules000066400000000000000000000010021370157770500171610ustar00rootroot00000000000000#!/usr/bin/make -f export QT_SELECT=5 export DH_VERBOSE=1 include /usr/share/dpkg/default.mk DEB_BUILD_ARCH ?= $(shell dpkg-architecture -qDEB_BUILD_ARCH) %: dh $@ --parallel override_dh_shlibdeps: dh_shlibdeps --dpkg-shlibdeps-params=--ignore-missing-info -l/usr/lib override_dh_auto_configure: dh_auto_configure -- \ -DCMAKE_BUILD_TYPE=Release \ -DCMAKE_INSTALL_PREFIX=/usr \ -DAPP_VERSION=$(DEB_VERSION_UPSTREAM) \ -DVERSION=$(DEB_VERSION_UPSTREAM) \ LIB_INSTALL_DIR=/usr/lib/$(DEB_HOST_MULTIARCH) deepin-terminal-5.2.11/src/000077500000000000000000000000001370157770500154605ustar00rootroot00000000000000deepin-terminal-5.2.11/src/DtkSettingsToolsMacros.cmake000066400000000000000000000052441370157770500231200ustar00rootroot00000000000000#============================================================================= # Copyright 2019 Gary Wang # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # # * Neither the name of Gary Wang nor the names of its # contributors may be used to endorse or promote products derived # from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #============================================================================= function(DTK_CREATE_I18N_FROM_JSON _generated_file_list _input_json_file _output_cpp_file_name) set (DTK_SETTINGS_TOOLS_EXECUTABLE ${DTKCORE_TOOL_DIR}/dtk-settings) set (generated_file_list) # 0(failed) or 1(successed) files in the list. get_filename_component(_input_json_abs_path ${_input_json_file} ABSOLUTE) get_filename_component(_input_json_abs_dir ${_input_json_abs_path} DIRECTORY) set (_output_cpp_abs_path ${_input_json_abs_dir}/${_output_cpp_file_name}) if (EXISTS ${DTK_SETTINGS_TOOLS_EXECUTABLE}) add_custom_command(OUTPUT ${_output_cpp_abs_path} COMMAND ${DTK_SETTINGS_TOOLS_EXECUTABLE} ARGS ${_input_json_abs_path} -o ${_output_cpp_abs_path} DEPENDS ${_input_json_abs_path} VERBATIM) list(APPEND generated_file_list ${_output_cpp_abs_path}) else () message ("dtk-settings-tools could not be found at ${DTK_SETTINGS_TOOLS_EXECUTABLE}") endif () set(${_generated_file_list} ${generated_file_list} PARENT_SCOPE) endfunction() deepin-terminal-5.2.11/src/assets/000077500000000000000000000000001370157770500167625ustar00rootroot00000000000000deepin-terminal-5.2.11/src/assets/icons/000077500000000000000000000000001370157770500200755ustar00rootroot00000000000000deepin-terminal-5.2.11/src/assets/icons/deepin/000077500000000000000000000000001370157770500213415ustar00rootroot00000000000000deepin-terminal-5.2.11/src/assets/icons/deepin/builtin/000077500000000000000000000000001370157770500230075ustar00rootroot00000000000000deepin-terminal-5.2.11/src/assets/icons/deepin/builtin/dark/000077500000000000000000000000001370157770500237305ustar00rootroot00000000000000deepin-terminal-5.2.11/src/assets/icons/deepin/builtin/dark/icons/000077500000000000000000000000001370157770500250435ustar00rootroot00000000000000deepin-terminal-5.2.11/src/assets/icons/deepin/builtin/dark/icons/dt_arrow_right_12px.svg000066400000000000000000000015411370157770500314550ustar00rootroot00000000000000 arrow/right_dark 3 Created with Sketch. deepin-terminal-5.2.11/src/assets/icons/deepin/builtin/dark/icons/dt_command_44px.svg000066400000000000000000000033211370157770500305470ustar00rootroot00000000000000 command_dark_light Created with Sketch. deepin-terminal-5.2.11/src/assets/icons/deepin/builtin/dark/icons/dt_edit_20px.svg000066400000000000000000000022111370157770500300450ustar00rootroot00000000000000 edit Created with Sketch. deepin-terminal-5.2.11/src/assets/icons/deepin/builtin/dark/icons/dt_opacity_left_20px.svg000066400000000000000000000021031370157770500316020ustar00rootroot00000000000000 Opacity0 Created with Sketch. deepin-terminal-5.2.11/src/assets/icons/deepin/builtin/dark/icons/dt_opacity_right_20px.svg000066400000000000000000000020651370157770500317740ustar00rootroot00000000000000 Opacity1 Created with Sketch. deepin-terminal-5.2.11/src/assets/icons/deepin/builtin/dark/icons/dt_server_44px.svg000066400000000000000000004430451370157770500304520ustar00rootroot00000000000000 server Created with Sketch. deepin-terminal-5.2.11/src/assets/icons/deepin/builtin/dark/icons/dt_server_group_44px.svg000066400000000000000000004430641370157770500316670ustar00rootroot00000000000000 server group Created with Sketch. deepin-terminal-5.2.11/src/assets/icons/deepin/builtin/dark/texts/000077500000000000000000000000001370157770500250775ustar00rootroot00000000000000deepin-terminal-5.2.11/src/assets/icons/deepin/builtin/dark/texts/dt_exit_fullscreen_36px.svg000066400000000000000000000026611370157770500323670ustar00rootroot00000000000000 exit hover dark Created with Sketch. deepin-terminal-5.2.11/src/assets/icons/deepin/builtin/light/000077500000000000000000000000001370157770500241165ustar00rootroot00000000000000deepin-terminal-5.2.11/src/assets/icons/deepin/builtin/light/icons/000077500000000000000000000000001370157770500252315ustar00rootroot00000000000000deepin-terminal-5.2.11/src/assets/icons/deepin/builtin/light/icons/dt_arrow_right_12px.svg000066400000000000000000000017161370157770500316470ustar00rootroot00000000000000 arrow/right Created with Sketch. deepin-terminal-5.2.11/src/assets/icons/deepin/builtin/light/icons/dt_command_44px.svg000066400000000000000000000035161370157770500307430ustar00rootroot00000000000000 command_dark_light Created with Sketch. deepin-terminal-5.2.11/src/assets/icons/deepin/builtin/light/icons/dt_edit_20px.svg000066400000000000000000000021731370157770500302420ustar00rootroot00000000000000 edit Created with Sketch. deepin-terminal-5.2.11/src/assets/icons/deepin/builtin/light/icons/dt_opacity_left_20px.svg000066400000000000000000000021041370157770500317710ustar00rootroot00000000000000 Opacity0 Created with Sketch. deepin-terminal-5.2.11/src/assets/icons/deepin/builtin/light/icons/dt_opacity_right_20px.svg000066400000000000000000000020661370157770500321630ustar00rootroot00000000000000 Opacity1 Created with Sketch. deepin-terminal-5.2.11/src/assets/icons/deepin/builtin/light/icons/dt_server_44px.svg000066400000000000000000004430451370157770500306400ustar00rootroot00000000000000 server Created with Sketch. deepin-terminal-5.2.11/src/assets/icons/deepin/builtin/light/icons/dt_server_group_44px.svg000066400000000000000000004431011370157770500320450ustar00rootroot00000000000000 server group Created with Sketch. deepin-terminal-5.2.11/src/assets/icons/deepin/builtin/light/texts/000077500000000000000000000000001370157770500252655ustar00rootroot00000000000000deepin-terminal-5.2.11/src/assets/icons/deepin/builtin/light/texts/dt_exit_fullscreen_36px.svg000066400000000000000000000026551370157770500325600ustar00rootroot00000000000000 exit hover Created with Sketch. deepin-terminal-5.2.11/src/assets/logo/000077500000000000000000000000001370157770500177225ustar00rootroot00000000000000deepin-terminal-5.2.11/src/assets/logo/deepin-terminal.svg000066400000000000000000000053111370157770500235200ustar00rootroot00000000000000 deepin-terminal-32px Created with Sketch. deepin-terminal-5.2.11/src/assets/other/000077500000000000000000000000001370157770500201035ustar00rootroot00000000000000deepin-terminal-5.2.11/src/assets/other/default-config.json000066400000000000000000000261621370157770500236740ustar00rootroot00000000000000{ "groups": [ { "key": "basic", "name": "Basic", "groups": [ { "key": "interface", "name": "Interface", "options": [ { "key": "opacity", "name": "Opacity", "type": "slider", "max": 100, "min": 20, "default": 100 }, { "key": "font", "name": "Font", "type": "fontcombobox", "default": "Noto Sans Mono" }, { "key": "font_size", "name": "Font size", "type": "spinbutton", "default": 11, "max": 50, "min": 5 }, { "key": "theme", "hide": true, "reset": true, "default": "Linux" } ] } ] }, { "key": "shortcuts", "name": "Shortcuts", "groups": [ { "key" : "terminal", "name" : "Terminal", "options" : [ { "key": "copy", "name": "Copy", "type": "shortcut", "default": "Ctrl+Shift+C" }, { "key": "paste", "name": "Paste", "type": "shortcut", "default": "Ctrl+Shift+V" }, { "key": "find", "name": "Find", "type": "shortcut", "default": "Ctrl+Alt+F" }, { "key": "zoom_in", "name": "Zoom in", "type": "shortcut", "default": "Ctrl+=" }, { "key": "zoom_out", "name": "Zoom out", "type": "shortcut", "default": "Ctrl+-" }, { "key": "default_size", "name": "Default size", "type": "shortcut", "default": "Ctrl+0" }, { "key": "select_all", "name": "Select all", "type": "shortcut", "default": "Ctrl+Shift+A" } ] }, { "key" : "workspace", "name" : "Workspace", "options" : [ { "key": "new_workspace", "name": "New workspace", "type": "shortcut", "default": "Ctrl+Shift+T" }, { "key": "close_workspace", "name": "Close workspace", "type": "shortcut", "default": "Alt+W" }, { "key": "close_other_workspace", "name": "Close other workspaces", "type": "shortcut", "default": "Ctrl+Shift+W" }, { "key": "previous_workspace", "name": "Previous workspace", "type": "shortcut", "default": "Ctrl+Tab" }, { "key": "next_workspace", "name": "Next workspace", "type": "shortcut", "default": "Ctrl+Shift+Tab" }, { "key": "vertical_split", "name": "Vertical split", "type": "shortcut", "default": "Ctrl+Shift+J" }, { "key": "horionzal_split", "name": "Horizontal split", "type": "shortcut", "default": "Ctrl+Shift+H" }, { "key": "select_upper_window", "name": "Select upper window", "type": "shortcut", "default": "Alt+Up" }, { "key": "select_lower_window", "name": "Select lower window", "type": "shortcut", "default": "Alt+Down" }, { "key": "select_left_window", "name": "Select left window", "type": "shortcut", "default": "Alt+Left" }, { "key": "select_right_window", "name": "Select right window", "type": "shortcut", "default": "Alt+Right" }, { "key": "close_window", "name": "Close window", "type": "shortcut", "default": "Alt+Q" }, { "key": "close_other_windows", "name": "Close other windows", "type": "shortcut", "default": "Ctrl+Shift+Q" } ] }, { "key" : "advanced", "name" : "Others", "options" : [ { "key": "switch_fullscreen", "name": "Fullscreen", "type": "shortcut", "default": "F11" }, { "key": "rename_title", "name": "Rename title", "type": "shortcut", "default": "F2" }, { "key": "display_shortcuts", "name": "Display shortcuts", "type": "shortcut", "default": "Ctrl+Shift+?" }, { "key": "custom_command", "name": "Custom commands", "type": "shortcut", "default": "Alt+Ins" }, { "key": "remote_management", "name": "Remote management", "type": "shortcut", "default": "Alt+Del" } ] } ] }, { "key": "advanced", "name": "Advanced", "groups": [ { "key": "cursor", "name": "Cursor", "options": [ { "key": "cursor_shape", "name": "Cursor style", "type": "buttongroup", "items": ["▐","_","|"], "default": 0, "i18n_skip_keys": ["items"] }, { "key": "cursor_blink", "type": "checkbox", "text": "Cursor blink", "default": true }, { "key": "auto_copy_selection", "type": "checkbox", "text": "Copy on select", "default": false } ] }, { "key": "scroll", "name": "Scroll", "options": [ { "key": "scroll_on_key", "type": "checkbox", "text": "Scroll on keystroke", "default": true }, { "key": "scroll_on_output", "type": "checkbox", "text": "Scroll on output", "default": true } ] }, { "key": "window", "name": "Window", "options": [ { "key": "use_on_starting", "name": "Use on starting", "type": "combobox", "default": "window_normal" }, { "key": "blurred_background", "text": "Blur background", "type": "checkbox", "default": "false" }, { "key": "auto_hide_raytheon_window", "text": "Hide Quake window after losing focus", "type": "checkbox", "default": "false" } ] } ] } ] } deepin-terminal-5.2.11/src/assets/other/install_flag000066400000000000000000000000001370157770500224530ustar00rootroot00000000000000deepin-terminal-5.2.11/src/assets/other/ssh_login.sh000066400000000000000000000037751370157770500224400ustar00rootroot00000000000000#! /usr/bin/expect -f # Copyright (C) 2011 ~ 2016 Deepin, Inc. # 2011 ~ 2016 Wang Yong # # Author: Wang Yong # Maintainer: Wang Yong # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . ## All possible interactive messages: # Are you sure you want to continue connecting (yes/no)? # password: # Enter passphrase for key ## Main # Delete self for secret, will not affect the following code file delete $argv0 # Setup variables # Set timeout -1 to avoid remote server dis-connect. set timeout -1 set user {<>} set server {<>} set password "<>" set private_key {<>} set port {<>} set authentication {<>} set ssh_cmd {zssh -X -o ServerAliveInterval=60} set ssh_opt {$user@$server -p $port -o PubkeyAuthentication=$authentication} set remote_command {<>} # This code is use for synchronous pty's size to avoid terminal not update if login in remote server. trap { stty rows [stty rows] columns [stty columns] < $spawn_out(slave,name) } WINCH # Spawn and expect eval spawn $ssh_cmd $ssh_opt $private_key -t $remote_command exec \\\$SHELL -l if {[string length $password]} { expect { timeout {send_user "ssh connection time out, please operate manually\n"} -nocase "(yes/no)\\?" {send "yes\r"; exp_continue} -nocase -re "password:|enter passphrase for key" { send "$password\r" } } } interact deepin-terminal-5.2.11/src/assets/resources.qrc000066400000000000000000000027051370157770500215070ustar00rootroot00000000000000 other/default-config.json other/ssh_login.sh logo/deepin-terminal.svg icons/deepin/builtin/light/icons/dt_server_44px.svg icons/deepin/builtin/light/icons/dt_server_group_44px.svg icons/deepin/builtin/light/icons/dt_arrow_right_12px.svg icons/deepin/builtin/light/icons/dt_command_44px.svg icons/deepin/builtin/light/icons/dt_edit_20px.svg icons/deepin/builtin/dark/icons/dt_server_44px.svg icons/deepin/builtin/dark/icons/dt_server_group_44px.svg icons/deepin/builtin/dark/icons/dt_arrow_right_12px.svg icons/deepin/builtin/dark/icons/dt_command_44px.svg icons/deepin/builtin/dark/icons/dt_edit_20px.svg icons/deepin/builtin/light/icons/dt_opacity_left_20px.svg icons/deepin/builtin/light/icons/dt_opacity_right_20px.svg icons/deepin/builtin/dark/icons/dt_opacity_left_20px.svg icons/deepin/builtin/dark/icons/dt_opacity_right_20px.svg icons/deepin/builtin/light/texts/dt_exit_fullscreen_36px.svg icons/deepin/builtin/dark/texts/dt_exit_fullscreen_36px.svg deepin-terminal-5.2.11/src/common/000077500000000000000000000000001370157770500167505ustar00rootroot00000000000000deepin-terminal-5.2.11/src/common/define.h000066400000000000000000000006011370157770500203500ustar00rootroot00000000000000#ifndef DTNG_DEFINE_H #define DTNG_DEFINE_H #include /* TERMINALWIDGET_VERSION is (major << 16) + (minor << 8) + patch. can be used like #if (TERMINALWIDGET_VERSION >= QT_VERSION_CHECK(0, 7, 1)) */ #define TERMINALWIDGET_VERSION QT_VERSION_CHECK(TERMINALWIDGET_VERSION_MAJOR, TERMINALWIDGET_VERSION_MINOR, TERMINALWIDGET_VERSION_PATCH) #endif // DTNG_DEFINE_H deepin-terminal-5.2.11/src/common/utils.cpp000066400000000000000000001235741370157770500206300ustar00rootroot00000000000000/* * Copyright (C) 2017 ~ 2018 Deepin Technology Co., Ltd. * * Author: rekols * Maintainer: rekols * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #include "utils.h" #include "operationconfirmdlg.h" #include "warnningdlg.h" #include "termwidget.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "terminputdialog.h" #include "dbusmanager.h" QHash Utils::m_imgCacheHash; QHash Utils::m_fontNameCache; Utils::Utils(QObject *parent) : QObject(parent) { } Utils::~Utils() { } QString Utils::getQssContent(const QString &filePath) { QFile file(filePath); QString qss; if (file.open(QIODevice::ReadOnly)) { qss = file.readAll(); } return qss; } QString Utils::getConfigPath() { static QStringList list = QStandardPaths::standardLocations(QStandardPaths::ConfigLocation); const QString path = list.first(); QDir dir( QDir(path).filePath(qApp->organizationName())); return dir.filePath(qApp->applicationName()); } QString Utils::suffixList() { return QString("Font Files (*.ttf *.ttc *.otf)"); } QPixmap Utils::renderSVG(const QString &filePath, const QSize &size) { if (m_imgCacheHash.contains(filePath)) { return m_imgCacheHash.value(filePath); } QImageReader reader; QPixmap pixmap; reader.setFileName(filePath); if (reader.canRead()) { const qreal ratio = qApp->devicePixelRatio(); reader.setScaledSize(size * ratio); pixmap = QPixmap::fromImage(reader.read()); pixmap.setDevicePixelRatio(ratio); } else { pixmap.load(filePath); } m_imgCacheHash.insert(filePath, pixmap); return pixmap; } QString Utils::loadFontFamilyFromFiles(const QString &fontFileName) { if (m_fontNameCache.contains(fontFileName)) { return m_fontNameCache.value(fontFileName); } QString fontFamilyName = ""; QFile fontFile(fontFileName); if (!fontFile.open(QIODevice::ReadOnly)) { qDebug() << "Open font file error"; return fontFamilyName; } int loadedFontID = QFontDatabase::addApplicationFontFromData(fontFile.readAll()); QStringList loadedFontFamilies = QFontDatabase::applicationFontFamilies(loadedFontID); if (!loadedFontFamilies.empty()) { fontFamilyName = loadedFontFamilies.at(0); } fontFile.close(); m_fontNameCache.insert(fontFileName, fontFamilyName); return fontFamilyName; } QString Utils::getElidedText(QFont font, QString text, int MaxWith, Qt::TextElideMode elideMode) { if (text.isEmpty()) { return ""; } QFontMetrics fontWidth(font); // 计算字符串宽度 int width = fontWidth.width(text); // 当字符串宽度大于最大宽度时进行转换 if (width >= MaxWith) { // 右部显示省略号 text = fontWidth.elidedText(text, elideMode, MaxWith); } return text; } const QString Utils::holdTextInRect(const QFont &font, QString text, const QSize &size) { QFontMetrics fm(font); QTextLayout layout(text); layout.setFont(font); QStringList lines; QTextOption &text_option = *const_cast(&layout.textOption()); text_option.setWrapMode(QTextOption::WordWrap); text_option.setAlignment(Qt::AlignTop | Qt::AlignLeft); layout.beginLayout(); QTextLine line = layout.createLine(); int height = 0; int lineHeight = fm.height(); while (line.isValid()) { height += lineHeight; if (height + lineHeight > size.height()) { const QString &end_str = fm.elidedText(text.mid(line.textStart()), Qt::ElideRight, size.width()); layout.endLayout(); layout.setText(end_str); text_option.setWrapMode(QTextOption::NoWrap); layout.beginLayout(); line = layout.createLine(); line.setLineWidth(size.width() - 1); text = end_str; } else { line.setLineWidth(size.width()); } lines.append(text.mid(line.textStart(), line.textLength())); if (height + lineHeight > size.height()) break; line = layout.createLine(); } layout.endLayout(); return lines.join(""); } QString Utils::convertToPreviewString(QString fontFilePath, QString srcString) { if (fontFilePath.isEmpty()) { return srcString; } QString strFontPreview = srcString; QRawFont rawFont(fontFilePath, 0, QFont::PreferNoHinting); bool isSupport = rawFont.supportsCharacter(QChar('a')); bool isSupportF = rawFont.supportsCharacter(QChar('a' | 0xf000)); if ((!isSupport && isSupportF)) { QChar *chArr = new QChar[srcString.length() + 1]; for (int i = 0; i < srcString.length(); i++) { int ch = srcString.at(i).toLatin1(); //判断字符ascii在32~126范围内(共95个) if (ch >= 32 && ch <= 126) { ch |= 0xf000; chArr[i] = QChar(ch); } else { chArr[i] = srcString.at(i); } } chArr[srcString.length()] = '\0'; QString strResult(chArr); strFontPreview = strResult; delete[] chArr; } return strFontPreview; } QString Utils::getRandString() { int max = 6; //字符串长度 QString tmp = QString("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"); QString str; QTime t; t = QTime::currentTime(); qsrand(t.msec() + t.second() * 1000); for (int i = 0; i < max; i++) { int len = qrand() % tmp.length(); str[i] = tmp.at(len); } return str; } QString Utils::showDirDialog(QWidget *widget) { QString curPath = QDir::currentPath(); QString dlgTitle = QObject::tr("Select a directory to save the file"); DFileDialog dialog(widget, dlgTitle, curPath); dialog.setAcceptMode(QFileDialog::AcceptOpen); dialog.setFileMode(QFileDialog::Directory); dialog.setOption(DFileDialog::DontConfirmOverwrite); dialog.setLabelText(QFileDialog::Accept, QObject::tr("Select")); int code = dialog.exec(); if (code == QDialog::Accepted && !dialog.selectedFiles().isEmpty()) { QStringList list = dialog.selectedFiles(); const QString dirName = list.first(); return dirName; } else { return ""; } } QStringList Utils::showFilesSelectDialog(QWidget *widget) { QString curPath = QDir::currentPath(); QString dlgTitle = QObject::tr("Select file to upload"); DFileDialog dialog(widget, dlgTitle, curPath); dialog.setAcceptMode(QFileDialog::AcceptOpen); dialog.setFileMode(QFileDialog::ExistingFiles); dialog.setLabelText(QFileDialog::Accept, QObject::tr("Upload")); // 选择文件,却点击了叉号 int code = dialog.exec(); if (code == QDialog::Accepted) { return dialog.selectedFiles(); } else { return QStringList(); } } bool Utils::showExitConfirmDialog(CloseType type, int count) { /******** Modify by m000714 daizhengwen 2020-04-17: 统一使用dtk Dialog****************/ #ifndef USE_DTK OperationConfirmDlg optDlg; optDlg.setFixedSize(380, 160); optDlg.setOperatTypeName(QObject::tr("Programs are still running in terminal")); optDlg.setTipInfo(QObject::tr("Are you sure you want to exit?")); optDlg.setOKCancelBtnText(QObject::tr("Exit"), QObject::tr("Cancel")); optDlg.exec(); return (optDlg.getConfirmResult() == QDialog::Accepted); #else // count < 1 不提示 if (count < 1) { return true; } QString title; QString txt; if (type != CloseType_Window) { // 默认的count = 1的提示 title = QObject::tr("Close this terminal?"); txt = QObject::tr("There is still a process running in this terminal. " "Closing the terminal will kill it."); // count > 1 提示 if (count > 1) { txt = QObject::tr("There are still %1 processes running in this terminal. " "Closing the terminal will kill all of them.") .arg(count); } } else { title = QObject::tr("Close this window?"); txt = QObject::tr("There are still processes running in this window. Closing the window will kill all of them."); } DDialog dlg(title, txt); dlg.setIcon(QIcon::fromTheme("deepin-terminal")); dlg.addButton(QString(tr("Cancel")), false, DDialog::ButtonNormal); /******** Modify by nt001000 renfeixiang 2020-05-21:修改Exit成Close Begin***************/ dlg.addButton(QString(tr("Close")), true, DDialog::ButtonWarning); /******** Modify by nt001000 renfeixiang 2020-05-21:修改Exit成Close End***************/ return (dlg.exec() == DDialog::Accepted); #endif /********************* Modify by m000714 daizhengwen End ************************/ } void Utils::getExitDialogText(CloseType type, QString &title, QString &txt, int count) { // count < 1 不提示 if (count < 1) { return ; } //QString title; //QString txt; if (type == CloseType_Window) { title = QObject::tr("Close this window?"); txt = QObject::tr("There are still processes running in this window. Closing the window will kill all of them."); } else { // 默认的count = 1的提示 title = QObject::tr("Close this terminal?"); txt = QObject::tr("There is still a process running in this terminal. " "Closing the terminal will kill it."); // count > 1 提示 if (count > 1) { txt = QObject::tr("There are still %1 processes running in this terminal. " "Closing the terminal will kill all of them.") .arg(count); } } } bool Utils::showExitUninstallConfirmDialog() { DDialog dlg(QObject::tr("Programs are still running in terminal"), QObject::tr("Are you sure you want to uninstall it?")); dlg.setIcon(QIcon::fromTheme("deepin-terminal")); dlg.addButton(QString(tr("Cancel")), false, DDialog::ButtonNormal); dlg.addButton(QString(tr("OK")), true, DDialog::ButtonWarning); return (dlg.exec() == DDialog::Accepted); } bool Utils::showUnistallConfirmDialog(QString commandname) { #ifndef USE_DTK OperationConfirmDlg dlg; dlg.setFixedSize(380, 160); dlg.setOperatTypeName(QObject::tr("Are you sure you want to uninstall this application?")); dlg.setTipInfo(QObject::tr("You will not be able to use Terminal any longer.")); dlg.setOKCancelBtnText(QObject::tr("OK"), QObject::tr("Cancel")); dlg.exec(); return (dlg.getConfirmResult() == QDialog::Accepted); #else /******** Modify by nt001000 renfeixiang 2020-05-27:修改 根据remove和purge卸载命令,显示不同的弹框信息 Begin***************/ QString title = "", text = ""; if (commandname == "remove") { title = QObject::tr("Are you sure you want to uninstall this application?"); text = QObject::tr("You will not be able to use Terminal any longer."); } else if (commandname == "purge") { //后面根据产品提供的信息,修改此处purge命令卸载时的弹框信息 title = QObject::tr("Are you sure you want to uninstall this application?"); text = QObject::tr("You will not be able to use Terminal any longer."); } DDialog dlg(title, text); /******** Modify by nt001000 renfeixiang 2020-05-27:修改 根据remove和purge卸载命令,显示不同的弹框信息 Begin***************/ dlg.setIcon(QIcon::fromTheme("dialog-warning")); dlg.addButton(QObject::tr("Cancel"), false, DDialog::ButtonNormal); dlg.addButton(QObject::tr("OK"), true, DDialog::ButtonWarning); return (dlg.exec() == DDialog::Accepted); #endif } /******************************************************************************* 1. @函数: showShortcutConflictDialog 2. @作者: n014361 王培利 3. @日期: 2020-03-31 4. @说明: 快捷键冲突框显示 *******************************************************************************/ bool Utils::showShortcutConflictDialog(QString conflictkey) { QString str = qApp->translate("DSettingsDialog", "This shortcut conflicts with %1") .arg(QString("%1").arg(conflictkey)); OperationConfirmDlg optDlg; QPixmap warnning = QIcon::fromTheme("dialog-warning").pixmap(QSize(32, 32)); optDlg.setIconPixmap(warnning); optDlg.setOperatTypeName(str); optDlg.setTipInfo(QObject::tr("Click on Add to make this shortcut effective immediately")); optDlg.setOKCancelBtnText(QObject::tr("Replace"), QObject::tr("Cancel")); optDlg.setFixedSize(380, 160); optDlg.exec(); return optDlg.getConfirmResult() == QDialog::Accepted; } bool Utils::showShortcutConflictMsgbox(QString txt) { #ifndef USE_DTK WarnningDlg dlg; dlg.setOperatTypeName(txt); dlg.setTipInfo(QObject::tr("please set another one.")); dlg.exec(); #else DDialog dlg; // dlg.setTitle(QString(txt )); // dlg.setMessage(QObject::tr(" please set another one.")); dlg.setIcon(QIcon::fromTheme("dialog-warning")); dlg.setTitle(QString(txt + QObject::tr("please set another one."))); /***mod by ut001121 zhangmeng 20200521 将确认按钮设置为默认按钮 修复BUG26960***/ dlg.addButton(QString(tr("OK")), true, DDialog::ButtonNormal); dlg.exec(); #endif return true; } /******************************************************************************* 1. @函数: setSpaceInWord 2. @作者: m000714 戴正文 3. @日期: 2020-04-10 4. @说明: 为按钮两个中文之间添加空格 *******************************************************************************/ void Utils::setSpaceInWord(DPushButton *button) { const QString &text = button->text(); if (text.count() == 2) { for (const QChar &ch : text) { switch (ch.script()) { case QChar::Script_Han: case QChar::Script_Katakana: case QChar::Script_Hiragana: case QChar::Script_Hangul: break; default: return; } } button->setText(QString().append(text.at(0)).append(QChar::Nbsp).append(text.at(1))); } } void Utils::showRenameTitleDialog(QString oldTitle, QWidget *parentWidget) { TermInputDialog *pDialog = new TermInputDialog(parentWidget); pDialog->setWindowModality(Qt::ApplicationModal); pDialog->setFixedSize(380, 180); pDialog->setIcon(QIcon::fromTheme("deepin-terminal")); pDialog->setFocusPolicy(Qt::NoFocus); pDialog->showDialog(oldTitle, parentWidget); } /******************************************************************************* 1. @函数: showSameNameDialog 2. @作者: ut000610 戴正文 3. @日期: 2020-04-16 4. @说明: 当有相同名称时,弹出弹窗给用户确认 *******************************************************************************/ void Utils::showSameNameDialog(QWidget *parent, const QString &firstLine, const QString &secondLine) { DDialog *dlg = new DDialog(parent); dlg->setAttribute(Qt::WA_DeleteOnClose); dlg->setWindowModality(Qt::WindowModal); dlg->setTitle(QString(firstLine + secondLine)); dlg->setIcon(QIcon::fromTheme("dialog-warning")); dlg->addButton(QString(QObject::tr("OK")), true, DDialog::ButtonNormal); dlg->show(); moveToCenter(dlg); } /******************************************************************************* 1. @函数: clearChildrenFocus 2. @作者: n014361 王培利 3. @日期: 2020-05-08 4. @说明: 清空控件内部所有子控件的焦点获取        安全考虑,不要全局使用.仅在个别控件中使用 *******************************************************************************/ void Utils::clearChildrenFocus(QObject *objParent) { // 可以获取焦点的控件名称列表 QStringList foucswidgetlist; foucswidgetlist << "QLineEdit" << "Konsole::TerminalDisplay"; //qDebug() << "checkChildrenFocus start" << objParent->children().size(); for (QObject *obj : objParent->children()) { if (!obj->isWidgetType()) { continue; } QWidget *widget = static_cast(obj); if (Qt::NoFocus != widget->focusPolicy()) { //qDebug() << widget << widget->focusPolicy() << widget->metaObject()->className(); if (!foucswidgetlist.contains(widget->metaObject()->className())) { widget->setFocusPolicy(Qt::NoFocus); } } clearChildrenFocus(obj); } //qDebug() << "checkChildrenFocus over" << objParent->children().size(); } /******************************************************************************* 1. @函数: parseCommandLine 2. @作者: ut000439 王培利 3. @日期: 2020-06-01 4. @说明: 函数参数解析 appControl = true, 为main函数使用,遇到-h -v 时,整个进程会退出 为false时,为唯一进程使用,主要是解析变量出来。 *******************************************************************************/ void Utils::parseCommandLine(QStringList arguments, TermProperties &Properties, bool appControl) { QCommandLineParser parser; parser.setApplicationDescription(qApp->applicationDescription()); parser.addHelpOption(); parser.addVersionOption(); parser.setOptionsAfterPositionalArgumentsMode(QCommandLineParser::ParseAsOptions); parser.setSingleDashWordOptionMode(QCommandLineParser::ParseAsCompactedShortOptions); QCommandLineOption optWorkDirectory({ "w", "work-directory" }, QObject::tr("Set the work directory"), "path"); QCommandLineOption optWindowState({ "m", "window-mode" }, QString(QObject::tr("Set the window mode on starting") + " (normal, maximum, fullscreen, splitscreen)"), "state-mode"); QCommandLineOption optExecute({ "e", "execute" }, QObject::tr("Execute a command in the terminal"), "command"); QCommandLineOption optScript({ "C", "run-script" }, QObject::tr("Run script string in the terminal"), "script"); // QCommandLineOption optionExecute2({"x", "Execute" }, "Execute command in the terminal", "command"); QCommandLineOption optQuakeMode({ "q", "quake-mode" }, QObject::tr("Run in quake mode"), ""); QCommandLineOption optKeepOpen("keep-open", QObject::tr("Keep terminal open when command finishes"), ""); // parser.addPositionalArgument("e", "Execute command in the terminal", "command"); parser.addOptions({ optWorkDirectory, optExecute, /*optionExecute2,*/ optQuakeMode, optWindowState, optKeepOpen, optScript }); // parser.addPositionalArgument("-e", QObject::tr("Execute command in the terminal"), "command"); // 解析参数 if (!parser.parse(arguments)) { qDebug() << "parser error:" << parser.errorText(); } if (parser.isSet(optExecute)) { Properties[Execute] = parseExecutePara(arguments); } if (parser.isSet(optWorkDirectory)) { Properties[WorkingDir] = parser.value(optWorkDirectory); } if (parser.isSet(optKeepOpen)) { Properties[KeepOpen] = ""; } if (parser.isSet(optScript)) { Properties[Script] = parser.value(optScript); } if (parser.isSet(optQuakeMode)) { Properties[QuakeMode] = true; } else { Properties[QuakeMode] = false; } // 默认均为非首个 Properties[SingleFlag] = false; if (parser.isSet(optWindowState)) { Properties[StartWindowState] = parser.value(optWindowState); if (appControl) { QStringList validString = { "maximum", "fullscreen", "splitscreen", "normal" }; // 参数不合法时,会显示help以后,直接退出。 if (!validString.contains(parser.value(optWindowState))) { parser.showHelp(); qApp->quit(); } } } if (appControl) { // 处理相应参数,当遇到-v -h参数的时候,这里进程会退出。 //qDebug() << "parse commandLine"; parser.process(arguments); } else { qDebug() << "input args:" << qPrintable(arguments.join(" ")); qDebug() << "arg: optionWorkDirectory" << parser.value(optWorkDirectory); qDebug() << "arg: optionExecute" << Properties[Execute].toStringList().join(" "); // qDebug() << "optionExecute2"< keys; keys << "-e" << "--execute"; keys << "-h" << "--help"; keys << "-v" << "--version"; keys << "-w" << "--work-directory"; keys << "-q" << "--quake-mode"; keys << "-m" << "--window-mode"; keys << "--keep-open"; keys << "-C" << "--run-script"; QString opt = "-e"; int index = arguments.indexOf(opt); if (index == -1) { opt = "--execute"; index = arguments.indexOf(opt); } index++; int startIndex = index; QStringList paraList; while (index < arguments.size()) { QString str = arguments.at(index); // qDebug()<<"check arg"< "bash", "-c", "ping 127.0.0.1" 如:'bash -c "ping 127.0.0.1"' -> "bash, "-c", "ping 127.0.0.1" 如:"bash -c ping 127.0.0.1"-> "bash, "-c", "ping 127.0.0.1" *******************************************************************************/ QStringList Utils::parseNestedQString(QString str) { QStringList paraList; int iLeft = NOT_FOUND; int iRight = NOT_FOUND; // 如果只有一个引号 if (str.count("\"") >= 1) { iLeft = str.indexOf("\""); iRight = str.lastIndexOf("\""); } else if (str.count("\'") >= 1) { iLeft = str.indexOf("\'"); iRight = str.lastIndexOf("\'"); } else { paraList.append(str.split(QRegExp(QStringLiteral("\\s+")), QString::SkipEmptyParts)); return paraList; } paraList.append(str.left(iLeft).split(QRegExp(QStringLiteral("\\s+")), QString::SkipEmptyParts)); paraList.append(str.mid(iLeft + 1, iRight - iLeft - 1)); if (str.size() != iRight + 1) { paraList.append(str.right(str.size() - iRight - 1).split(QRegExp(QStringLiteral("\\s+")), QString::SkipEmptyParts)); } return paraList; } /******************************************************************************* 1. @函数: encodeList 2. @作者: ut000610 戴正文 3. @日期: 2020-05-27 4. @说明: 获取编码列表 *******************************************************************************/ QList Utils::encodeList() { QList all = QTextCodec::availableCodecs(); QList showEncodeList; // 这是ubuntu18.04支持的编码格式,按国家排列的 // showEncodeList << "GB18030" << "GB2312" << "GBK" // << "BIG5" << "BIG5-HKSCS" << "EUC-TW" // << "EUC-JP" << "ISO-2022-JP" << "SHIFT_JIS" // << "EUC-KR" << "ISO-2022-KR" << "UHC" // << "IBM864" << "ISO-8859-6" << "MAC_ARABIC" << "WINDOWS-1256" // << "ARMSCII-8" // << "ISO-8859-13" << "ISO-8859-4" << "WINDOWS-1257" // << "ISO-8859-14" // << "IBM-852" << "ISO-8859-2" << "MAC_CE" << "WINDOWS-1250" // << "MAC_CROATIAN" // << "IBM855" << "ISO-8859-5" << "ISO-IR-111" << "ISO-IR-111" << "KOI8-R" << "MAC-CYRILLIC" << "WINDOWS-1251" // << "CP866" // << "KOI8-U" << "MAC_UKRAINIAN" // << "GEORGIAN-PS" // << "ISO-8859-7" << "MAC_GREEK" << "WINDOWS-1253" // << "MAC_GUJARATI" // << "MAC_GURMUKHI" // << "IBM862" << "ISO-8859-8-I" << "MAC_HEBREW" << "WINDOWS-1255" // << "ISO-8859-8" // << "MAC_DEVANAGARI" // << "MAC_ICELANDIC" // << "ISO-8859-10" // << "MAC_FARSI" // << "ISO-8859-16" << "MAC_ROMANIAN" // << "ISO-8859-3" // << "TIS-620" // << "IBM857" << "ISO-8859-9" << "MAC_TURKISH" << "WINDOWS-1254" // << "TCVN" << "VISCII" << "WINDOWS-1258" // << "IBM850" << "ISO-8859-1" << "ISO-8859-15" << "MAC_ROMAN" << "WINDOWS-1252"; showEncodeList << "UTF-8" << "GB18030" << "GB2312" << "GBK" /*简体中文*/ << "BIG5" << "BIG5-HKSCS" //<< "EUC-TW" /*繁体中文*/ << "EUC-JP" << "SHIFT_JIS" //<< "ISO-2022-JP"/*日语*/ << "EUC-KR" //<< "ISO-2022-KR" //<< "UHC" /*韩语*/ << "IBM864" << "ISO-8859-6" << "ARABIC" << "WINDOWS-1256" /*阿拉伯语*/ //<< "ARMSCII-8" /*美国语*/ << "ISO-8859-13" << "ISO-8859-4" << "WINDOWS-1257" /*波罗的海各国语*/ << "ISO-8859-14" /*凯尔特语*/ << "IBM-852" << "ISO-8859-2" << "x-mac-CE" << "WINDOWS-1250" /*中欧*/ //<< "x-mac-CROATIAN" /*克罗地亚*/ << "IBM855" << "ISO-8859-5" << "KOI8-R" << "MAC-CYRILLIC" << "WINDOWS-1251" //<< "ISO-IR-111" /*西里尔语*/ << "CP866" /*西里尔语或俄语*/ << "KOI8-U" << "x-MacUkraine" /*西里尔语或乌克兰语*/ //<< "GEORGIAN-PS" << "ISO-8859-7" << "x-mac-GREEK" << "WINDOWS-1253" /*希腊语*/ //<< "x-mac-GUJARATI" //<< "x-mac-GURMUKHI" << "IBM862" << "ISO-8859-8-I" << "WINDOWS-1255"//<< "x-mac-HEBREW" /*希伯来语*/ << "ISO-8859-8" /*希伯来语*/ //<< "x-mac-DEVANAGARI" //<< "x-mac-ICELANDIC" /*冰岛语*/ << "ISO-8859-10" /*北欧语*/ //<< "x-mac-FARSI" /*波斯语*/ //<< "x-mac-ROMANIAN" //<< "ISO-8859-16" /*罗马尼亚语*/ << "ISO-8859-3" /*西欧语*/ << "TIS-620" /*泰语*/ << "IBM857" << "ISO-8859-9" << "x-mac-TURKISH" << "WINDOWS-1254" /*土耳其语*/ << "WINDOWS-1258" //<< "TCVN" << "VISCII" /*越南语*/ << "IBM850" << "ISO-8859-1" << "ISO-8859-15" << "x-ROMAN8" << "WINDOWS-1252"; /*西方国家*/ // meld提供的编码格式,按名称排列的 // showEncodeList<<"UTF-8" // <<"ISO-8859-1" // <<"ISO-8859-2" // <<"ISO-8859-3" // <<"ISO-8859-4" // <<"ISO-8859-5" // <<"ISO-8859-6" // <<"ISO-8859-7" // <<"ISO-8859-8" // <<"ISO-8859-9" // <<"ISO-8859-10" // <<"ISO-8859-13" // <<"ISO-8859-14" // <<"ISO-8859-15" // //<<"ISO-8859-16" // <<"UTF-7" // <<"UTF-16" // <<"UTF-16BE" // <<"UTF-16LE" // <<"UTF-32" // <<"UCS-2" // <<"UCS-4" // //<<"ARMSCII-8" // <<"BIG5" // <<"BIG5-HKSCS" // <<"CP866" // <<"EUC-JP" // //<<"EUC-JP-MS" // <<"CP932" // <<"EUC-KR" // //<<"EUC-TW" // <<"GB18030" // <<"GB2312" // <<"GBK" // //<<"GEORGIAN-ACADEMY" // <<"IBM850" // <<"IBM852" // <<"IBM855" // <<"IBM857" // <<"IBM862" // <<"IBM864" // <<"ISO-2022-JP" // <<"ISO-2022-KR" // //<<"ISO-IR-111" // //<<"JOHAB" // <<"KOI8-R" // <<"KOI8-U" // <<"SHIFT_JIS" // //<<"TCVN" // <<"TIS-620" // //<<"UHC" // //<<"VISCII" // <<"WINDOWS-1250" // <<"WINDOWS-1251" // <<"WINDOWS-1252" // <<"WINDOWS-1253" // <<"WINDOWS-1254" // <<"WINDOWS-1255" // <<"WINDOWS-1256" // <<"WINDOWS-1257" // <<"WINDOWS-1258"; QList encodeList; // 自定义的名称,系统里不一定大小写完全一样,再同步一下。 for (QByteArray &name : showEncodeList) { QString strname1 = name; bool bFind = false; QByteArray encodename; for (QByteArray &name2 : all) { QString strname2 = name2; if (strname1.compare(strname2, Qt::CaseInsensitive) == 0) { bFind = true; encodename = name2; break; } } if (!bFind) { qDebug() << "encode name :" << name << "not find!"; } else { encodeList << encodename; } } // 返回需要的值 return encodeList; } /******************************************************************************* 1. @函数: getMainWindow 2. @作者: ut000125 sunchengxi 3. @日期: 2020-06-02 4. @说明: 根据当前窗口获取最外层的主窗口,当前窗口:currWidget,返回值非空就找到最外层主窗口:MainWindow *******************************************************************************/ MainWindow *Utils::getMainWindow(QWidget *currWidget) { MainWindow *main = nullptr; QWidget *pWidget = currWidget->parentWidget(); while (pWidget != nullptr) { qDebug() << pWidget->metaObject()->className(); if ((pWidget->objectName() == "NormalWindow") || (pWidget->objectName() == "QuakeWindow")) { qDebug() << "has find MainWindow"; main = static_cast(pWidget); break; } pWidget = pWidget->parentWidget(); } return main; } /******** Add by ut001000 renfeixiang 2020-06-15:增加 处理等宽字体的类 Begin***************/ Q_GLOBAL_STATIC(FontFilter, FontFilters) FontFilter *FontFilter::instance() { return FontFilters; } FontFilter::FontFilter() { m_thread = new QThread(); this->moveToThread(m_thread); QObject::connect(m_thread, &QThread::started, this, [ = ]() { CompareWhiteList(); m_thread->quit(); }); } FontFilter::~FontFilter() { if (m_thread != nullptr) { setStop(true); m_thread->quit(); m_thread->wait(); delete m_thread; m_thread = nullptr; } } //启动thread,打印等宽字体函数 void FontFilter::HandleWidthFont() { if (!m_thread->isRunning()) { m_thread->start(); return; } qDebug() << "m_thread is Running"; } //设置线程结束标志 true = 结束 false = 正常 void FontFilter::setStop(bool stop) { m_bstop = stop; } //打印DBUS获取等宽字体和比较字体字符方法获取等宽字体,用来定位DBUS获取字体失败后的问题 void FontFilter::CompareWhiteList() { QStringList DBUSWhitelist = DBusManager::callAppearanceFont("monospacefont"); std::sort(DBUSWhitelist.begin(), DBUSWhitelist.end(), [ = ](const QString & str1, const QString & str2) { QCollator qc; return qc.compare(str1, str2) < 0; }); //在REPCHAR中增加了一个空格,空格在非等宽字体中长度和字符长度不同 char REPCHAR[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "abcdefgjijklmnopqrstuvwxyz" "0123456789 ./+@"; QFontDatabase fontDatabase; QStringList fontLst = fontDatabase.families(); QStringList Whitelist; Whitelist << "Courier 10 Pitch" << "DejaVu Sans Mono" << "Liberation Mono" << "Monospace" << "Noto Mono" << "Noto Sans Mono" << "Noto Sans Mono CJK JP" << "Noto Sans Mono CJK JP Bold" << "Noto Sans Mono CJK KR" << "Noto Sans Mono CJK KR Bold" << "Noto Sans Mono CJK SC" << "Noto Sans Mono CJK SC Bold" << "Noto Sans Mono CJK TC" << "Noto Sans Mono CJK TC Bold" << "Unifont"; QStringList Blacklist; Blacklist << "webdings" << "Symbol" << "MT Extra [unknown]" << "Bitstream Charter" << "CESI仿宋-GB13000" << "CESI仿宋-GB18030" << "CESI仿宋-GB2312" << "CESI宋体-GB13000" << "CESI宋体-GB18030" << "CESI宋体-GB2312" << "CESI小标宋-GB13000" << "CESI小标宋-GB18030" << "CESI小标宋-GB2312" << "CESI楷体-GB13000" << "CESI楷体-GB18030" << "CESI楷体-GB2312" << "CESI黑体-GB13000" << "CESI黑体-GB18030" << "CESI黑体-GB2312" << "DejaVu Math TeX Gyre" << "DejaVu Sans" << "DejaVu Serif" << "Liberation Sans" << "Liberation Sans Narrow" << "Liberation Serif" << "Lohit Devanagari" << "MT Extra [PfEd]" << "Noto Kufi Arabic" << "Noto Music" << "Noto Naskh Arabic" << "Noto Nastaliq Urdu" << "Noto Sans" << "Noto Sans Adlam" << "Noto Sans Adlam Unjoined" << "Noto Sans Anatolian Hieroglyphs" << "Noto Sans Arabic" << "Noto Sans Armenian" << "Noto Sans Avestan" << "Noto Sans Bamum" << "Noto Sans Bassa Vah" << "Noto Sans Batak" << "Noto Sans Bengali" << "Noto Sans Bhaiksuki" << "Noto Sans Brahmi" << "Noto Sans Buginese" << "Noto Sans Buhid" << "Noto Sans Canadian Aboriginal" << "Noto Sans Carian" << "Noto Sans Caucasian Albanian" << "Noto Sans Chakma" << "Noto Sans Cham" << "Noto Sans Cherokee" << "Noto Sans CJK JP" << "Noto Sans CJK JP Bold" << "Noto Sans CJK KR" << "Noto Sans CJK KR Bold" << "Noto Sans CJK SC" << "Noto Sans CJK SC Bold" << "Noto Sans CJK TC" << "Noto Sans CJK TC Bold" << "Noto Sans Coptic" << "Noto Sans Cuneiform" << "Noto Sans Cypriot" << "Noto Sans Deseret" << "Noto Sans Devanagari" << "Noto Sans Display" << "Noto Sans Duployan" << "Noto Sans Egyptian Hieroglyphs" << "Noto Sans Elbasan" << "Noto Sans Ethiopic" << "Noto Sans Georgian" << "Noto Sans Glagolitic" << "Noto Sans Gothic" << "Noto Sans Grantha" << "Noto Sans Gujarati" << "Noto Sans Gurmukhi" << "Noto Sans Hanunoo" << "Noto Sans Hatran" << "Noto Sans Hebrew" << "Noto Sans Imperial Aramaic" << "Noto Sans Inscriptional Pahlavi" << "Noto Sans Inscriptional Parthian" << "Noto Sans Javanese" << "Noto Sans Kaithi" << "Noto Sans Kannada" << "Noto Sans Kayah Li" << "Noto Sans Kharoshthi" << "Noto Sans Khmer" << "Noto Sans Khojki" << "Noto Sans Khudawadi" << "Noto Sans Lao" << "Noto Sans Lepcha" << "Noto Sans Limbu" << "Noto Sans Linear A" << "Noto Sans Linear B" << "Noto Sans Lisu" << "Noto Sans Lycian" << "Noto Sans Lydian" << "Noto Sans Mahajani" << "Noto Sans Malayalam" << "Noto Sans Mandaic" << "Noto Sans Manichaean" << "Noto Sans Marchen" << "Noto Sans Math" << "Noto Sans Meetei Mayek" << "Noto Sans Mende Kikakui" << "Noto Sans Meroitic" << "Noto Sans Miao" << "Noto Sans Modi" << "Noto Sans Mongolian" << "Noto Sans Mro" << "Noto Sans Multani" << "Noto Sans Myanmar" << "Noto Sans Nabataean" << "Noto Sans New Tai Lue" << "Noto Sans Newa" << "Noto Sans NKo" << "Noto Sans Ogham" << "Noto Sans Ol Chiki" << "Noto Sans Old Hungarian" << "Noto Sans Old Italic" << "Noto Sans Old North Arabian" << "Noto Sans Old Permic" << "Noto Sans Old Persian" << "Noto Sans Old South Arabian" << "Noto Sans Old Turkic" << "Noto Sans Oriya" << "Noto Sans Osage" << "Noto Sans Osmanya" << "Noto Sans Pahawh Hmong" << "Noto Sans Palmyrene" << "Noto Sans Pau Cin Hau" << "Noto Sans PhagsPa" << "Noto Sans Phoenician" << "Noto Sans Psalter Pahlavi" << "Noto Sans Rejang" << "Noto Sans Runic" << "Noto Sans Samaritan" << "Noto Sans Saurashtra" << "Noto Sans Sharada" << "Noto Sans Shavian" << "Noto Sans Sinhala" << "Noto Sans Sora Sompeng" << "Noto Sans Sundanese" << "Noto Sans Syloti Nagri" << "Noto Sans Symbols" << "Noto Sans Symbols2" << "Noto Sans Syriac" << "Noto Sans Syriac Eastern" << "Noto Sans Syriac Estrangela" << "Noto Sans Syriac Western" << "Noto Sans Tagalog" << "Noto Sans Tagbanwa" << "Noto Sans Tai Le" << "Noto Sans Tai Tham" << "Noto Sans Tai Viet" << "Noto Sans Takri" << "Noto Sans Tamil" << "Noto Sans Telugu" << "Noto Sans Thaana" << "Noto Sans Thai" << "Noto Sans Tibetan" << "Noto Sans Tifinagh" << "Noto Sans Tirhuta" << "Noto Sans Ugaritic" << "Noto Sans Vai" << "Noto Sans Warang Citi" << "Noto Sans Yi" << "Noto Serif" << "Noto Serif Ahom" << "Noto Serif Armenian" << "Noto Serif Balinese" << "Noto Serif Bengali" << "Noto Serif CJK JP" << "Noto Serif CJK KR" << "Noto Serif CJK SC" << "Noto Serif CJK TC" << "Noto Serif Devanagari" << "Noto Serif Display" << "Noto Serif Ethiopic" << "Noto Serif Georgian" << "Noto Serif Gujarati" << "Noto Serif Gurmukhi" << "Noto Serif Hebrew" << "Noto Serif Kannada" << "Noto Serif Khmer" << "Noto Serif Lao" << "Noto Serif Malayalam" << "Noto Serif Myanmar" << "Noto Serif Sinhala" << "Noto Serif Tamil" << "Noto Serif Tamil Slanted" << "Noto Serif Telugu" << "Noto Serif Thai" << "Noto Serif Tibetan" << "Sans Serif" << "Serif" << "Symbola" << "Unifont CSUR" << "Unifont Upper" << "Wingdings" << "Wingdings 2" << "Wingdings 3"; for (QString &sfont : fontLst) { if (m_bstop) { break; } if (Whitelist.contains(sfont) | Blacklist.contains(sfont)) { continue; } bool fixedFont = true; QFont font(sfont); QFontMetrics fm(font); int fw = fm.width(REPCHAR[0]); //qDebug() << "sfont" << sfont; for (unsigned int i = 1; i < qstrlen(REPCHAR); i++) { if (fw != fm.width(QLatin1Char(REPCHAR[i]))) { fixedFont = false; break; } } if (fixedFont) { Whitelist.append(sfont); } else { Blacklist.append(sfont); } } qDebug() << "DBUS get font:" << DBUSWhitelist; qDebug() << "Compare font get font:" << Whitelist; } /******** Add by ut001000 renfeixiang 2020-06-15:增加 处理等宽字体的类 End***************/ deepin-terminal-5.2.11/src/common/utils.h000066400000000000000000000112501370157770500202600ustar00rootroot00000000000000/* * Copyright (C) 2017 ~ 2018 Deepin Technology Co., Ltd. * * Author: rekols * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #ifndef UTILS_H #define UTILS_H #include "settings.h" #include "termproperties.h" #include #include #include #include #include #include #include #include #include /******** Modify by m000714 daizhengwen 2020-04-03: 自绘的显示控件限制item的宽度****************/ #define ITEMMAXWIDTH 140 /********************* Modify by m000714 daizhengwen End ************************/ /******** Modify by m000714 daizhengwen 2020-04-17: 使用DTK的Dialog****************/ #define USE_DTK /********************* Modify by m000714 daizhengwen End ************************/ // kwin dbus #define KWinDBusService "org.kde.KWin" #define KWinDBusPath "/KWin" #define MAX_NAME_LEN 32 class MainWindow; class Utils : public QObject { Q_OBJECT public: Utils(QObject *parent = nullptr); ~Utils(); enum CloseType { CloseType_Window, CloseType_Tab, CloseType_OtherTab, CloseType_Terminal, CloseType_OtherTerminals, }; static QHash m_imgCacheHash; static QHash m_fontNameCache; static QString getQssContent(const QString &filePath); static QString getConfigPath(); static QString suffixList(); static QPixmap renderSVG(const QString &filePath, const QSize &size); static QString loadFontFamilyFromFiles(const QString &fontFileName); static QString getElidedText(QFont font, QString str, int MaxWith, Qt::TextElideMode elideMode = Qt::ElideRight); static const QString holdTextInRect(const QFont &font, QString text, const QSize &size); static QString convertToPreviewString(QString fontFilePath, QString srcString); static QString getRandString(); static QString showDirDialog(QWidget *widget); static QStringList showFilesSelectDialog(QWidget *widget); static bool showExitConfirmDialog(CloseType type, int count = 1); static void getExitDialogText(CloseType type, QString &title, QString &txt, int count = 1); static bool showExitUninstallConfirmDialog(); /******** Modify by nt001000 renfeixiang 2020-05-27:修改 增加参数区别remove和purge卸载命令 Begin***************/ static bool showUnistallConfirmDialog(QString commandname); /******** Modify by nt001000 renfeixiang 2020-05-27:修改 增加参数区别remove和purge卸载命令 Begin***************/ static bool showShortcutConflictDialog(QString conflictkey); static bool showShortcutConflictMsgbox(QString txt); static void setSpaceInWord(DPushButton *button); static void showRenameTitleDialog(QString oldTitle, QWidget *parentWidget); static void showSameNameDialog(QWidget *parent, const QString &firstLine, const QString &secondLine); static void clearChildrenFocus(QObject *objParent); static void parseCommandLine(QStringList arguments, TermProperties &Properties, bool appControl = false); static QStringList parseExecutePara(QStringList &arguments); static QStringList parseNestedQString(QString str); static MainWindow *getMainWindow(QWidget *currWidget); static QList encodeList(); static const int NOT_FOUND = -1; }; /******** Add by ut001000 renfeixiang 2020-06-15:增加 处理等宽字体的类 Begin***************/ class FontFilter : public QObject { Q_OBJECT public: static FontFilter * instance(); FontFilter(); ~FontFilter(); //启动thread,打印等宽字体函数 void HandleWidthFont(); //设置线程结束标志 true = 结束 false = 正常 void setStop(bool stop); private: //打印DBUS获取等宽字体和比较字体字符方法获取等宽字体,用来定位DBUS获取字体失败后的问题 void CompareWhiteList(); //线程成员变量 QThread *m_thread = nullptr; //线程结束标志位 bool m_bstop = false; }; /******** Add by ut001000 renfeixiang 2020-06-15:增加 处理等宽字体的类 End***************/ #endif deepin-terminal-5.2.11/src/customcommand/000077500000000000000000000000001370157770500203315ustar00rootroot00000000000000deepin-terminal-5.2.11/src/customcommand/customcommanddelegate.cpp000066400000000000000000000125061370157770500254050ustar00rootroot00000000000000#include "customcommanddelegate.h" #include "customcommanditemmodel.h" #include "utils.h" #include #include #include #include #include #include #include #include CustomCommandDelegate::CustomCommandDelegate(QAbstractItemView *parent) : DStyledItemDelegate(parent) , m_parentView(parent) { } void CustomCommandDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const { if (index.isValid()) { painter->save(); painter->setRenderHint(QPainter::Antialiasing, true); QVariant varDisplay = index.data(Qt::DisplayRole); CustomCommandItemData itemData = varDisplay.value(); QStyleOptionViewItem viewOption(option); //用来在视图中画一个item DPalette::ColorGroup cg = option.state & QStyle::State_Enabled ? DPalette::Normal : DPalette::Disabled; if (cg == DPalette::Normal && !(option.state & QStyle::State_Active)) { cg = DPalette::Inactive; } QRect bgRect; bgRect.setX(option.rect.x() + 10); bgRect.setY(option.rect.y() + 10); bgRect.setWidth(option.rect.width() - 20); bgRect.setHeight(option.rect.height() - 10); QPainterPath path; int cornerSize = 16; int arcRadius = 8; path.moveTo(bgRect.left() + arcRadius, bgRect.top()); path.arcTo(bgRect.left(), bgRect.top(), cornerSize, cornerSize, 90.0, 90.0); path.lineTo(bgRect.left(), bgRect.bottom() - arcRadius); path.arcTo(bgRect.left(), bgRect.bottom() - cornerSize, cornerSize, cornerSize, 180.0, 90.0); path.lineTo(bgRect.right() - arcRadius, bgRect.bottom()); path.arcTo(bgRect.right() - cornerSize, bgRect.bottom() - cornerSize, cornerSize, cornerSize, 270.0, 90.0); path.lineTo(bgRect.right(), bgRect.top() + arcRadius); path.arcTo(bgRect.right() - cornerSize, bgRect.top(), cornerSize, cornerSize, 0.0, 90.0); if (option.state & QStyle::State_MouseOver) { DStyleHelper styleHelper; QColor fillColor = styleHelper.getColor(static_cast(&option), DPalette::ToolTipText); fillColor.setAlphaF(0.3); painter->setBrush(QBrush(fillColor)); painter->fillPath(path, fillColor); } else { DPalette pa = DApplicationHelper::instance()->palette(m_parentView); DStyleHelper styleHelper; QColor fillColor = styleHelper.getColor(static_cast(&option), pa, DPalette::ItemBackground); painter->setBrush(QBrush(fillColor)); painter->fillPath(path, fillColor); } int cmdIconSize = 44; int editIconSize = 20; QRect cmdIconRect = QRect(bgRect.left() + 6, bgRect.top() + (bgRect.height() - cmdIconSize) / 2, cmdIconSize, cmdIconSize); painter->drawPixmap(cmdIconRect, QIcon::fromTheme("dt_command").pixmap(QSize(cmdIconSize, cmdIconSize))); if (option.state & QStyle::State_MouseOver) { QRect editIconRect = QRect(bgRect.right() - editIconSize - 6, bgRect.top() + (bgRect.height() - editIconSize) / 2, editIconSize, editIconSize); painter->drawPixmap(editIconRect, QIcon::fromTheme("dt_edit").pixmap(QSize(editIconSize, editIconSize))); } QString strCmdName = itemData.m_cmdName; QString strCmdShortcut = itemData.m_cmdShortcut; QFont textFont = painter->font(); int cmdNameFontSize = DFontSizeManager::instance()->fontPixelSize(DFontSizeManager::T7); textFont.setPixelSize(cmdNameFontSize); strCmdName = Utils::getElidedText(textFont, strCmdName, ITEMMAXWIDTH); painter->setFont(textFont); int lineSpace = 8; int offsetY = 22 - cmdNameFontSize; int leftOffset = cmdIconRect.left() + cmdIconSize + 6; DGuiApplicationHelper *appHelper = DGuiApplicationHelper::instance(); DPalette pa = appHelper->standardPalette(appHelper->themeType()); painter->setPen(pa.color(DPalette::Text)); QRect cmdNameRect = QRect(leftOffset, bgRect.top() + offsetY, bgRect.width() - cmdIconSize - editIconSize, 35); painter->drawText(cmdNameRect, Qt::AlignLeft | Qt::AlignTop, strCmdName); textFont.setPixelSize(DFontSizeManager::instance()->fontPixelSize(DFontSizeManager::T8)); painter->setFont(textFont); DStyleHelper styleHelper; DPalette palette = DApplicationHelper::instance()->palette(m_parentView); painter->setPen(QPen(styleHelper.getColor(static_cast(&option), palette, DPalette::TextTips))); QRect cmdShortcutRect = QRect(leftOffset, cmdNameRect.top() + cmdNameFontSize + lineSpace, bgRect.width() - cmdIconSize - editIconSize, 35); painter->drawText(cmdShortcutRect, Qt::AlignLeft | Qt::AlignTop, strCmdShortcut); painter->restore(); } else { DStyledItemDelegate::paint(painter, option, index); } } QSize CustomCommandDelegate::sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const { Q_UNUSED(index) return QSize(option.rect.width(), 70); } deepin-terminal-5.2.11/src/customcommand/customcommanddelegate.h000066400000000000000000000011461370157770500250500ustar00rootroot00000000000000#ifndef CUSTOMCOMMANDDELEGATE_H #define CUSTOMCOMMANDDELEGATE_H #include DWIDGET_USE_NAMESPACE class CustomCommandDelegate : public DStyledItemDelegate { public: explicit CustomCommandDelegate(QAbstractItemView *parent = nullptr); void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const Q_DECL_OVERRIDE; QSize sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const Q_DECL_OVERRIDE; private: QAbstractItemView *m_parentView = nullptr; }; #endif // CUSTOMCOMMANDDELEGATE_H deepin-terminal-5.2.11/src/customcommand/customcommanditemmodel.cpp000066400000000000000000000022021370157770500256020ustar00rootroot00000000000000#include "customcommanditemmodel.h" #include #include CustomCommandItemModel::CustomCommandItemModel(QObject *parent) : QSortFilterProxyModel(parent) { } void CustomCommandItemModel::initCommandListData(const QList &cmdListData) { QStandardItemModel *sourceModel = qobject_cast(this->sourceModel()); for (int i = 0; i < cmdListData.size(); i++) { CustomCommandItemData itemData = cmdListData.at(i); QStandardItem *item = new QStandardItem; item->setFlags(item->flags() & ~Qt::ItemIsSelectable & ~Qt::ItemIsEnabled); item->setData(QVariant::fromValue(itemData), Qt::DisplayRole); sourceModel->appendRow(item); } } void CustomCommandItemModel::addNewCommandData(const CustomCommandItemData itemData) { QStandardItemModel *sourceModel = qobject_cast(this->sourceModel()); QStandardItem *item = new QStandardItem; item->setFlags(item->flags() & ~Qt::ItemIsSelectable & ~Qt::ItemIsEnabled); item->setData(QVariant::fromValue(itemData), Qt::DisplayRole); sourceModel->appendRow(item); } deepin-terminal-5.2.11/src/customcommand/customcommanditemmodel.h000066400000000000000000000011321370157770500252500ustar00rootroot00000000000000#ifndef CUSTOMCOMMANDITEMMODEL_H #define CUSTOMCOMMANDITEMMODEL_H #include #include typedef struct { QString m_cmdName; QString m_cmdText; QString m_cmdShortcut; } CustomCommandItemData; Q_DECLARE_METATYPE(CustomCommandItemData) class CustomCommandItemModel : public QSortFilterProxyModel { Q_OBJECT public: CustomCommandItemModel(QObject *parent = nullptr); void initCommandListData(const QList &cmdListData); void addNewCommandData(const CustomCommandItemData itemData); }; #endif // CUSTOMCOMMANDITEMMODEL_H deepin-terminal-5.2.11/src/customcommand/customcommandlist.cpp000066400000000000000000000221511370157770500246030ustar00rootroot00000000000000#include "customcommandlist.h" #include "customcommanddelegate.h" #include "customcommandoptdlg.h" #include "operationconfirmdlg.h" #include "shortcutmanager.h" #include "utils.h" #include"service.h" #include #include #include #include #include CustomCommandList::CustomCommandList(QWidget *parent) : DListView(parent) { setBackgroundRole(QPalette::NoRole); setAutoFillBackground(false); setUpdatesEnabled(true); setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn); setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); initData(); } CustomCommandList::~CustomCommandList() { if (m_pdlg) { delete m_pdlg; m_pdlg = nullptr; } } void CustomCommandList::initData() { m_cmdListModel = new QStandardItemModel(this); m_cmdProxyModel = new CustomCommandItemModel(this); m_cmdProxyModel->setSourceModel(m_cmdListModel); m_cmdProxyModel->setFilterRole(Qt::UserRole); m_cmdProxyModel->setDynamicSortFilter(true); m_cmdDelegate = new CustomCommandDelegate(this); this->setModel(m_cmdProxyModel); this->setItemDelegate(m_cmdDelegate); } void CustomCommandList::refreshCommandListData(const QString &strFilter) { m_cmdListModel->clear(); m_cmdItemDataList.clear(); QList &customCommandActionList = ShortcutManager::instance()->getCustomCommandActionList(); qDebug() << __FUNCTION__ << strFilter << " : " << customCommandActionList.size(); if (strFilter.isEmpty()) { for (int i = 0; i < customCommandActionList.size(); i++) { QAction *curAction = customCommandActionList[i]; QString strCmdName = curAction->text(); QString strCmdText = curAction->data().toString(); QKeySequence keySeq = curAction->shortcut(); QString strKeySeq = keySeq.toString(); CustomCommandItemData itemData; itemData.m_cmdName = strCmdName; itemData.m_cmdText = strCmdText; itemData.m_cmdShortcut = strKeySeq; m_cmdItemDataList.append(itemData); } } else { for (int i = 0; i < customCommandActionList.size(); i++) { QAction *curAction = customCommandActionList[i]; QString strCmdName = curAction->text(); QString strCmdText = curAction->data().toString(); QKeySequence keySeq = curAction->shortcut(); QString strKeySeq = keySeq.toString(); if (strCmdName.contains(strFilter, Qt::CaseSensitivity::CaseInsensitive) || strCmdText.contains(strFilter, Qt::CaseSensitivity::CaseInsensitive) || strKeySeq.contains(strFilter, Qt::CaseSensitivity::CaseInsensitive)) { CustomCommandItemData itemData; itemData.m_cmdName = strCmdName; itemData.m_cmdText = strCmdText; itemData.m_cmdShortcut = strKeySeq; m_cmdItemDataList.append(itemData); } } } m_cmdProxyModel->initCommandListData(m_cmdItemDataList); } void CustomCommandList::addNewCustomCommandData(QAction *actionData) { if (actionData == nullptr) { return; } QAction *curAction = actionData; QString strCmdName = curAction->text(); QString strCmdText = curAction->data().toString(); QKeySequence keySeq = curAction->shortcut(); QString strKeySeq = keySeq.toString(); CustomCommandItemData itemData; itemData.m_cmdName = strCmdName; itemData.m_cmdText = strCmdText; itemData.m_cmdShortcut = strKeySeq; m_cmdProxyModel->addNewCommandData(itemData); } void CustomCommandList::handleModifyCustomCommand(CustomCommandItemData &itemData, QModelIndex modelIndex) { qDebug() << __FUNCTION__ << __LINE__; if (m_pdlg) { delete m_pdlg; m_pdlg = nullptr; } // 弹窗显示 Service::instance()->setIsDialogShow(window(), true); m_pdlg = new CustomCommandOptDlg(CustomCommandOptDlg::CCT_MODIFY, &itemData, this); m_pdlg->setModelIndex(modelIndex); connect(m_pdlg, &CustomCommandOptDlg::finished, this, [ &](int result) { // 弹窗隐藏或消失 Service::instance()->setIsDialogShow(window(), false); if (result == QDialog::Accepted) { qDebug() << __FUNCTION__ << __LINE__ << ":mod Custom Command"; QAction *newAction = m_pdlg->getCurCustomCmd(); CustomCommandItemData itemData = *(m_pdlg->m_currItemData); CustomCommandItemData itemDel = itemData; itemData.m_cmdName = newAction->text(); itemData.m_cmdText = newAction->data().toString(); itemData.m_cmdShortcut = newAction->shortcut().toString(); newAction->setData(newAction->data()); newAction->setShortcut(newAction->shortcut()); ShortcutManager::instance()->delCustomCommand(itemDel); //ShortcutManager::instance()->delCustomCommandForModify(itemDel); //ShortcutManager::instance()->delCustomCommandForModify(itemData); addNewCustomCommandData(newAction); ShortcutManager::instance()->addCustomCommand(*newAction); removeCommandItem(m_pdlg->modelIndex); scrollToBottom(); m_pdlg->closeRefreshDataConnection(); emit Service::instance()->refreshCommandPanel(itemDel.m_cmdName, itemData.m_cmdName); } else if (result == QDialog::Rejected) { //Delete custom command if (m_pdlg->isDelCurCommand()) { qDebug() << __FUNCTION__ << __LINE__ << ":del Custom Command"; DDialog *dlgDelete = new DDialog(this); dlgDelete->setAttribute(Qt::WA_DeleteOnClose); dlgDelete->setWindowModality(Qt::WindowModal); m_pdlg->m_dlgDelete = dlgDelete; dlgDelete->setIcon(QIcon::fromTheme("deepin-terminal")); dlgDelete->setTitle(tr("Are you sure you want to delete %1?").arg(m_pdlg->m_currItemData->m_cmdName)); dlgDelete->addButton(QObject::tr("Cancel"), false, DDialog::ButtonNormal); dlgDelete->addButton(QObject::tr("Confirm"), true, DDialog::ButtonWarning); connect(dlgDelete, &DDialog::finished, this, [ & ](int result) { if (result == QDialog::Accepted) { CustomCommandItemData itemData = *(m_pdlg->m_currItemData); ShortcutManager::instance()->delCustomCommand(*(m_pdlg->m_currItemData)); removeCommandItem(m_pdlg->modelIndex); emit listItemCountChange(); m_pdlg->closeRefreshDataConnection(); emit Service::instance()->refreshCommandPanel(m_pdlg->m_currItemData->m_cmdName, m_pdlg->m_currItemData->m_cmdName);//emit Service::instance()->refreshCommandPanel("", ""); } }); dlgDelete->show(); } } }); m_pdlg->show(); } void CustomCommandList::removeCommandItem(QModelIndex modelIndex) { qDebug() << __FUNCTION__ << __LINE__; Q_UNUSED(modelIndex) if (m_cmdListModel && m_cmdListModel->rowCount() == 0) { return; } // m_cmdProxyModel->removeRow(modelIndex.row(), modelIndex.parent()); refreshCommandListData(""); } int CustomCommandList::getItemRow(CustomCommandItemData itemData) { for (int i = 0; i < count(); i++) { CustomCommandItemData data = m_cmdItemDataList.at(i); if (itemData.m_cmdName == data.m_cmdName && itemData.m_cmdText == data.m_cmdText && itemData.m_cmdShortcut == data.m_cmdShortcut) { return i; } } return -1; } QRect getModifyIconRect(QRect visualRect) { int modifyIconSize = 30; return QRect(visualRect.right() - modifyIconSize - 10, visualRect.top() + (visualRect.height() - modifyIconSize) / 2, modifyIconSize, modifyIconSize); } void CustomCommandList::mouseMoveEvent(QMouseEvent *event) { DListView::mouseMoveEvent(event); } void CustomCommandList::mousePressEvent(QMouseEvent *event) { if (event->button() == Qt::LeftButton) { m_bLeftMouse = true; } else { m_bLeftMouse = false; } DListView::mousePressEvent(event); if (false == m_bLeftMouse) { return; } if (m_cmdListModel && m_cmdListModel->rowCount() == 0) { return; } if (!m_cmdProxyModel) { return; } QPoint clickPoint = event->pos(); QModelIndex modelIndex = indexAt(clickPoint); QRect rect = visualRect(modelIndex); if (!modelIndex.isValid()) { return; } CustomCommandItemData itemData = qvariant_cast(m_cmdProxyModel->data(modelIndex)); if (getModifyIconRect(rect).contains(clickPoint)) { handleModifyCustomCommand(itemData, modelIndex); } else { emit itemClicked(itemData, modelIndex); } } void CustomCommandList::mouseReleaseEvent(QMouseEvent *event) { DListView::mouseReleaseEvent(event); } void CustomCommandList::setSelection(const QRect &rect, QItemSelectionModel::SelectionFlags command) { DListView::setSelection(rect, command); } deepin-terminal-5.2.11/src/customcommand/customcommandlist.h000066400000000000000000000030271370157770500242510ustar00rootroot00000000000000#ifndef CUSTOMCOMMANDLIST_H #define CUSTOMCOMMANDLIST_H #include "customcommanditemmodel.h" #include #include #include #include #include #include DWIDGET_USE_NAMESPACE class CustomCommandDelegate; class CustomCommandItemModel; class CustomCommandItem; class CustomCommandOptDlg; class CustomCommandList : public DListView { Q_OBJECT public: explicit CustomCommandList(QWidget *parent = nullptr); ~CustomCommandList(); void refreshCommandListData(const QString &strFilter); void addNewCustomCommandData(QAction *actionData); protected: void mouseMoveEvent(QMouseEvent *event); void mousePressEvent(QMouseEvent *event); void mouseReleaseEvent(QMouseEvent *event); void setSelection(const QRect &rect, QItemSelectionModel::SelectionFlags command); signals: void listItemCountChange(); void itemClicked(CustomCommandItemData itemData, QModelIndex modelIndex); private slots: void handleModifyCustomCommand(CustomCommandItemData &itemData, QModelIndex modelIndex); private: void initData(); int getItemRow(CustomCommandItemData itemData); void removeCommandItem(QModelIndex modelIndex); CustomCommandDelegate *m_cmdDelegate = nullptr; QStandardItemModel *m_cmdListModel = nullptr; CustomCommandItemModel *m_cmdProxyModel = nullptr; QList m_cmdItemDataList; bool m_bLeftMouse = true; CustomCommandOptDlg *m_pdlg = nullptr; }; #endif // CUSTOMCOMMANDLIST_H deepin-terminal-5.2.11/src/customcommand/customcommandoptdlg.cpp000066400000000000000000000545321370157770500251310ustar00rootroot00000000000000#include "customcommandoptdlg.h" #include "termcommandlinkbutton.h" #include "shortcutmanager.h" #include "shortcutmanager.h" #include "utils.h" #include"service.h" //#include "mainwindow.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include CustomCommandOptDlg::CustomCommandOptDlg(CustomCmdOptType type, CustomCommandItemData *currItemData, QWidget *parent) : DAbstractDialog(parent), m_type(type), m_nameLineEdit(new DLineEdit), m_commandLineEdit(new DLineEdit), m_shortCutLineEdit(new DKeySequenceEdit), m_bDelOpt(false) { setWindowModality(Qt::WindowModal); if (currItemData) { m_currItemData = new CustomCommandItemData; *m_currItemData = *currItemData; } initUITitle(); initTitleConnections(); initUI(); connect(Service::instance(), &Service::refreshCommandPanel, this, &CustomCommandOptDlg::slotRefreshData); } CustomCommandOptDlg::~CustomCommandOptDlg() { if (m_currItemData) { delete m_currItemData; m_currItemData = nullptr; } if (m_newAction) { delete m_newAction; } } void CustomCommandOptDlg::slotRefreshData(QString oldCmdName, QString newCmdName) { if (m_type == CCT_ADD) { return; } if (oldCmdName == "" && newCmdName == "") { return; } if (m_currItemData->m_cmdName != oldCmdName) { return; } m_bRefreshCheck = true; qDebug() << "slotRefreshData---" << m_nameLineEdit->text(); QAction *currAction = new QAction(ShortcutManager::instance()); if (currAction == nullptr) { qDebug() << "slotRefreshData---new QAction error!!!"; close(); } currAction->setText(newCmdName); QAction *existAction = nullptr; existAction = ShortcutManager::instance()->checkActionIsExist(*currAction); if (existAction == nullptr) { delete currAction; if (m_dlgDelete && m_dlgDelete->isVisible()) { m_dlgDelete->close(); m_dlgDelete = nullptr; } close(); } else { delete currAction; m_nameLineEdit->setText(existAction->text()); m_commandLineEdit->setText(existAction->data().toString()); m_shortCutLineEdit->setKeySequence(existAction->shortcut()); m_currItemData->m_cmdName = newCmdName; } } void CustomCommandOptDlg::closeRefreshDataConnection() { disconnect(Service::instance(), &Service::refreshCommandPanel, this, &CustomCommandOptDlg::slotRefreshData); } void CustomCommandOptDlg::initUI() { QWidget *contentFrame = new QWidget; QVBoxLayout *contentLayout = new QVBoxLayout; contentLayout->setSpacing(10); contentLayout->setContentsMargins(0, 0, 0, 0); QWidget *nameFrame = new QWidget; nameFrame->setFixedWidth(459); QHBoxLayout *nameLayout = new QHBoxLayout; nameLayout->setSpacing(0); nameLayout->setContentsMargins(28, 0, 30, 0); nameFrame->setLayout(nameLayout); QWidget *cmdFrame = new QWidget; QHBoxLayout *cmdLayout = new QHBoxLayout; cmdLayout->setSpacing(0); cmdLayout->setContentsMargins(28, 0, 30, 0); cmdFrame->setLayout(cmdLayout); QWidget *scFrame = new QWidget; QHBoxLayout *scLayout = new QHBoxLayout; scLayout->setSpacing(0); scLayout->setContentsMargins(28, 0, 30, 0); scFrame->setLayout(scLayout); DLabel *nameLabel = new DLabel(tr("Name:")); DLabel *cmdLabel = new DLabel(tr("Command:")); DLabel *shortCutLabel = new DLabel(tr("Shortcuts:")); m_nameLineEdit->setFixedWidth(285); m_commandLineEdit->setFixedWidth(285); m_shortCutLineEdit->setFixedWidth(285); m_nameLineEdit->lineEdit()->setPlaceholderText(tr("Required")); m_commandLineEdit->lineEdit()->setPlaceholderText(tr("Required")); m_shortCutLineEdit->ShortcutDirection(Qt::AlignLeft); nameLayout->addWidget(nameLabel); nameLayout->addWidget(m_nameLineEdit); cmdLayout->addWidget(cmdLabel); cmdLayout->addWidget(m_commandLineEdit); scLayout->addWidget(shortCutLabel); scLayout->addWidget(m_shortCutLineEdit); contentLayout->addWidget(nameFrame); contentLayout->addWidget(cmdFrame); contentLayout->addWidget(scFrame); contentFrame->setLayout(contentLayout); connect(m_nameLineEdit, &DLineEdit::editingFinished, this, [ = ] { if (m_nameLineEdit->text().isEmpty()) { m_nameLineEdit->lineEdit()->setPlaceholderText(tr("Required")); } }); connect(m_commandLineEdit, &DLineEdit::editingFinished, this, [ = ] { if (m_commandLineEdit->text().isEmpty()) { m_commandLineEdit->lineEdit()->setPlaceholderText(tr("Required")); } }); addContent(contentFrame); if (m_type == CCT_ADD) { setFixedSize(459, 262); setTitle(tr("Add Command")); initCommandFromClipBoardText(); getMainLayout()->addSpacing(18); } else { setFixedSize(459, 296); setTitle(tr("Edit Command")); QWidget *deleteCmdWidget = new QWidget; deleteCmdWidget->setFixedHeight(54); QHBoxLayout *deleteCmdLayout = new QHBoxLayout(); deleteCmdLayout->setSpacing(0); deleteCmdLayout->setContentsMargins(0, 0, 0, 0); TermCommandLinkButton *deleteCmdBtn = new TermCommandLinkButton(); deleteCmdBtn->setText(tr("Delete Command")); deleteCmdLayout->addStretch(); deleteCmdLayout->addWidget(deleteCmdBtn); deleteCmdLayout->addStretch(); deleteCmdWidget->setLayout(deleteCmdLayout); getMainLayout()->addWidget(deleteCmdWidget); connect(deleteCmdBtn, &DCommandLinkButton::clicked, this, &CustomCommandOptDlg::slotDelCurCustomCommand); QString strName = m_currItemData->m_cmdName; QString strCommad = m_currItemData->m_cmdText; QKeySequence keyseq = QKeySequence(m_currItemData->m_cmdShortcut); m_lastCmdShortcut = m_currItemData->m_cmdShortcut; m_nameLineEdit->setText(strName); m_commandLineEdit->setText(strCommad); m_shortCutLineEdit->setKeySequence(keyseq); #ifdef UI_DEBUG deleteCmdWidget->setStyleSheet("background:green"); #endif } addCancelConfirmButtons(); setCancelBtnText(tr("Cancel")); if (m_type == CCT_ADD) { setConfirmBtnText(tr("Add")); } else { setConfirmBtnText(tr("Save")); } m_lastCmdShortcut = m_shortCutLineEdit->keySequence().toString(); connect(this, &CustomCommandOptDlg::confirmBtnClicked, this, &CustomCommandOptDlg::slotAddSaveButtonClicked); connect(m_shortCutLineEdit, &KeySequenceEdit::editingFinished, this, [ = ](const QKeySequence & sequence) { //删除 if (sequence.toString() == "Backspace") { m_shortCutLineEdit->clear(); m_lastCmdShortcut = ""; return ; } // 取消 if (sequence.toString() == "Esc") { m_shortCutLineEdit->clear(); m_shortCutLineEdit->setKeySequence(QKeySequence(m_lastCmdShortcut)); /***add by ut001121 zhangmeng 20200521 在快捷键编辑框中按下ESC键时退出窗口 修复BUG27554***/ close(); return ; } QString checkName; //QString seq = m_shortCutLineEdit->text(); if (m_type != CCT_ADD) { checkName = m_nameLineEdit->text(); } QString reason; // 判断快捷键是否冲突 if (!ShortcutManager::instance()->checkShortcutValid(checkName, sequence.toString(), reason)) { // 冲突 if (sequence.toString() != "Esc") { showShortcutConflictMsgbox(reason); } m_shortCutLineEdit->clear(); m_shortCutLineEdit->setKeySequence(QKeySequence(m_lastCmdShortcut)); return; } m_lastCmdShortcut = sequence.toString(); }); #ifdef UI_DEBUG contentFrame->setStyleSheet("background:cyan"); nameLabel->setStyleSheet("background:#0000ff"); cmdLabel->setStyleSheet("background:#00ff00"); shortCutLabel->setStyleSheet("background:yellow"); m_nameLineEdit->setStyleSheet("background:#ff00ff"); m_commandLineEdit->setStyleSheet("background:#ff00ff"); m_shortCutLineEdit->setStyleSheet("background:#ff00ff"); #endif } // fix bug 18366 终端中选中内容,创建自定义命令,选中内容没有自动粘贴到命令输入框 void CustomCommandOptDlg::initCommandFromClipBoardText() { if (m_commandLineEdit) { // QString clipText = ShortcutManager::instance()->getClipboardCommandData(); MainWindow *main = Utils::getMainWindow(this);//;getMainWindow(); if (main != nullptr) { QString clipText = main->selectedText(true); m_commandLineEdit->setText(clipText.trimmed()); } } } QAction *CustomCommandOptDlg::getCurCustomCmd() { return m_newAction; } bool CustomCommandOptDlg::isDelCurCommand() { return m_bDelOpt; } void CustomCommandOptDlg::slotAddSaveButtonClicked() { qDebug() << __FUNCTION__ << __LINE__; QString strName = m_nameLineEdit->text(); QString strCommand = m_commandLineEdit->text(); QKeySequence keytmp = m_shortCutLineEdit->keySequence(); if (strName.isEmpty()) { m_nameLineEdit->showAlertMessage(tr("Please enter a name"), m_nameLineEdit->parentWidget()); return; } /***add begin by ut001121 zhangmeng 20200615 限制名称字符长度 修复BUG31286***/ if (strName.length() > MAX_NAME_LEN) { m_nameLineEdit->showAlertMessage(QObject::tr("The name should be no more than 32 characters"), m_nameLineEdit->parentWidget()); return; } /***add end by ut001121***/ if (strCommand.isEmpty()) { m_commandLineEdit->showAlertMessage(tr("Please enter a command"), m_commandLineEdit->parentWidget()); return; } m_newAction = new QAction(ShortcutManager::instance()); m_newAction->setText(strName); m_newAction->setData(strCommand); m_newAction->setShortcut(m_shortCutLineEdit->keySequence()); /************************ Mod by m000743 sunchengxi 2020-04-21:自定义命令修改的异常问题 Begin************************/ QAction *existAction = nullptr; int icount = 0; if (m_type == CCT_MODIFY) { //if (m_bRefreshCheck && (!checkSequence(m_shortCutLineEdit->keySequence()))) { // return; //} if (m_bRefreshCheck) { QAction *refreshExitAction = nullptr; refreshExitAction = ShortcutManager::instance()->checkActionIsExist(*m_newAction); if (refreshExitAction) { accept(); return; } } if (strName == m_currItemData->m_cmdName && strCommand == m_currItemData->m_cmdText && keytmp == QKeySequence(m_currItemData->m_cmdShortcut)) { accept(); return; } existAction = ShortcutManager::instance()->checkActionIsExistForModify(*m_newAction); if (strName != m_currItemData->m_cmdName) { QList &customCommandActionList = ShortcutManager::instance()->getCustomCommandActionList(); for (int i = 0; i < customCommandActionList.size(); i++) { QAction *curAction = customCommandActionList[i]; QString strCmdName = curAction->text(); if (strCmdName == strName) { icount++; } } } } else { existAction = ShortcutManager::instance()->checkActionIsExist(*m_newAction); } if (nullptr != existAction || icount) { QString strFistLine = tr("The name already exists,"); QString strSecondeLine = tr("please input another one."); Utils::showSameNameDialog(this, strFistLine, strSecondeLine); } else { accept(); } /************************ Mod by m000743 sunchengxi 2020-04-21:自定义命令修改的异常问题 End ************************/ } bool CustomCommandOptDlg::checkSequence(const QKeySequence &sequence) { QString checkName = m_nameLineEdit->text(); if (sequence.toString() == "") { return true; } QString reason; // 判断快捷键是否冲突 if (!ShortcutManager::instance()->checkShortcutValid(checkName, sequence.toString(), reason)) { // 冲突 if (sequence.toString() != "Esc") { showShortcutConflictMsgbox(reason); } m_shortCutLineEdit->clear(); m_shortCutLineEdit->setKeySequence(QKeySequence(m_lastCmdShortcut)); QTimer::singleShot(30, this, [&]() { m_shortCutLineEdit->setFocus(); }); return false; } return true; } void CustomCommandOptDlg::setModelIndex(QModelIndex mi) { modelIndex = mi; } void CustomCommandOptDlg::slotDelCurCustomCommand() { m_bDelOpt = true; reject(); } void CustomCommandOptDlg::initUITitle() { QVBoxLayout *mainLayout = new QVBoxLayout(); mainLayout->setSpacing(0); mainLayout->setContentsMargins(0, 0, 0, 10); QHBoxLayout *titleLayout = new QHBoxLayout(); titleLayout->setSpacing(0); titleLayout->setContentsMargins(0, 0, 0, 0); m_titleBar = new QWidget(this); m_titleBar->setFixedHeight(50); m_titleBar->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); m_titleBar->setLayout(titleLayout); m_logoIcon = new DLabel(this); m_logoIcon->setFixedSize(QSize(50, 50)); m_logoIcon->setFocusPolicy(Qt::NoFocus); m_logoIcon->setAttribute(Qt::WA_TransparentForMouseEvents); m_closeButton = new DWindowCloseButton(this); m_closeButton->setFocusPolicy(Qt::NoFocus); m_closeButton->setIconSize(QSize(50, 50)); m_titleText = new DLabel(this); m_titleText->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred); m_titleText->setAlignment(Qt::AlignCenter); DFontSizeManager::instance()->bind(m_titleText, DFontSizeManager::T5, QFont::DemiBold); // 字色 DPalette palette = m_titleText->palette(); // palette.setColor(QPalette::WindowText, palette.color(DPalette::TextTitle)); QColor color; if (DApplicationHelper::instance()->themeType() == DApplicationHelper::DarkType) { color = QColor::fromRgb(192, 198, 212, 255); } else { color = QColor::fromRgb(0, 26, 46, 255); } palette.setBrush(QPalette::WindowText, color); m_titleText->setPalette(palette); titleLayout->addWidget(m_logoIcon, 0, Qt::AlignLeft | Qt::AlignVCenter); titleLayout->addWidget(m_titleText, 0, Qt::AlignHCenter); titleLayout->addWidget(m_closeButton, 0, Qt::AlignRight | Qt::AlignTop); //Dialog content m_contentLayout = new QVBoxLayout(); m_contentLayout->setSpacing(0); m_contentLayout->setContentsMargins(0, 0, 0, 0); m_content = new QWidget(this); m_content->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); m_content->setLayout(m_contentLayout); mainLayout->addWidget(m_titleBar, 0, Qt::AlignTop); mainLayout->addWidget(m_content); setLayout(mainLayout); m_mainLayout = mainLayout; } void CustomCommandOptDlg::addCancelConfirmButtons() { QHBoxLayout *buttonsLayout = new QHBoxLayout(); buttonsLayout->setSpacing(9); buttonsLayout->setContentsMargins(10, 0, 10, 0); QFont btnFont; m_cancelBtn = new DPushButton(this); m_cancelBtn->setFixedWidth(209); m_cancelBtn->setFixedHeight(36); m_cancelBtn->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Fixed); m_cancelBtn->setFont(btnFont); m_confirmBtn = new DSuggestButton(this); m_confirmBtn->setFixedWidth(209); m_confirmBtn->setFixedHeight(36); m_confirmBtn->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Fixed); m_confirmBtn->setFont(btnFont); //设置回车键默认响应的按钮 m_confirmBtn->setDefault(true); DVerticalLine *verticalLine = new DVerticalLine(this); DPalette pa = DApplicationHelper::instance()->palette(verticalLine); QColor splitColor = pa.color(DPalette::ItemBackground); pa.setBrush(DPalette::Background, splitColor); verticalLine->setPalette(pa); verticalLine->setBackgroundRole(QPalette::Background); verticalLine->setAutoFillBackground(true); verticalLine->setFixedSize(3, 28); buttonsLayout->addWidget(m_cancelBtn); buttonsLayout->addWidget(verticalLine); buttonsLayout->addWidget(m_confirmBtn); /************************ Add by m000743 sunchengxi 2020-04-15:默认enter回车按下,走确认校验流程 Begin************************/ m_confirmBtn->setDefault(true); /************************ Add by m000743 sunchengxi 2020-04-15:默认enter回车按下,走确认校验流程 End ************************/ connect(m_cancelBtn, &DPushButton::clicked, this, [ = ]() { qDebug() << "cancelBtnClicked"; m_confirmResultCode = QDialog::Rejected; reject(); close(); }); connect(m_confirmBtn, &DPushButton::clicked, this, [ = ]() { qDebug() << "confirmBtnClicked"; m_confirmResultCode = QDialog::Accepted; emit confirmBtnClicked(); }); /************************ Add by m000743 sunchengxi 2020-04-21:快捷键编辑结束后,enter按下可以响应校验 Begin************************/ connect(m_shortCutLineEdit, &DKeySequenceEdit::editingFinished, this, [ = ]() { qDebug() << "shourtCut editingFinished"; /******** Add by nt001000 renfeixiang 2020-05-14:修改快捷框输入后,添加(m_confirmBtn)按钮高亮问题,将光标从添加按钮取消,设置到快捷框上 Begin***************/ //m_confirmBtn->setFocus(); m_shortCutLineEdit->setFocus(); /******** Add by nt001000 renfeixiang 2020-05-14:修改快捷框输入后,添加(m_confirmBtn)按钮高亮问题,将光标从添加按钮取消,设置到快捷框上 End***************/ }); /************************ Add by m000743 sunchengxi 2020-04-21:快捷键编辑结束后,enter按下可以响应校验 End ************************/ m_mainLayout->addLayout(buttonsLayout); } QVBoxLayout *CustomCommandOptDlg::getMainLayout() { return m_mainLayout; } void CustomCommandOptDlg::initTitleConnections() { connect(m_closeButton, &DWindowCloseButton::clicked, this, [this]() { this->close(); }); // 字体颜色随主题变化变化 connect(DApplicationHelper::instance(), &DGuiApplicationHelper::themeTypeChanged, m_titleText, [ = ](DGuiApplicationHelper::ColorType themeType) { DPalette palette = m_titleText->palette(); //palette.setBrush(QPalette::WindowText, palette.color(DPalette::TextTitle)); QColor color; if (themeType == DApplicationHelper::DarkType) { color = QColor::fromRgb(192, 198, 212, 255); } else { color = QColor::fromRgb(0, 26, 46, 255); } palette.setBrush(QPalette::WindowText, color); m_titleText->setPalette(palette); }); } QDialog::DialogCode CustomCommandOptDlg::getConfirmResult() { return m_confirmResultCode; } void CustomCommandOptDlg::setLogoVisable(bool visible) { if (nullptr != m_logoIcon) { m_logoIcon->setVisible(visible); } } void CustomCommandOptDlg::setTitle(const QString &title) { if (nullptr != m_titleText) { m_titleText->setText(title); } } QLayout *CustomCommandOptDlg::getContentLayout() { return m_contentLayout; } void CustomCommandOptDlg::setCancelBtnText(const QString &strCancel) { m_cancelBtn->setText(strCancel); Utils::setSpaceInWord(m_cancelBtn); } void CustomCommandOptDlg::setConfirmBtnText(const QString &strConfirm) { m_confirmBtn->setText(strConfirm); Utils::setSpaceInWord(m_confirmBtn); } /******************************************************************************* 1. @函数: showShortcutConflictMsgbox 2. @作者: ut000610 戴正文 3. @日期: 2020-05-21 4. @说明: 显示快捷键冲突弹窗 *******************************************************************************/ void CustomCommandOptDlg::showShortcutConflictMsgbox(QString txt) { /******** Modify by ut000610 daizhengwen 2020-05-27: 出现提示和快捷键显示不一致的问题 bug#28507****************/ if (txt.contains("Return")) { txt.replace("Return", "Enter"); } /********************* Modify by ut000610 daizhengwen End ************************/ // 若没有弹窗,初始化 if (nullptr == m_shortcutConflictDialog) { m_shortcutConflictDialog = new DDialog(this); /******** Modify by nt001000 renfeixiang 2020-05-29:修改 因为弹框改为非模态之后,快捷框冲突选中快捷框功能移动这 Begin***************/ connect(m_shortcutConflictDialog, &DDialog::finished, m_shortcutConflictDialog, [this]() { m_shortcutConflictDialog->hide(); /******** Add by nt001000 renfeixiang 2020-05-14:快捷框输入已经存在的快捷后,快捷框依然是选中状态 Begin***************/ QTimer::singleShot(30, this, [&]() { m_shortCutLineEdit->setFocus(); }); /******** Add by nt001000 renfeixiang 2020-05-14:快捷框输入已经存在的快捷后,快捷框依然是选中状态 End***************/ }); /******** Modify by nt001000 renfeixiang 2020-05-29:修改 修改因为弹框改为非模态之后,快捷框冲突选中快捷框功能移动这 End***************/ m_shortcutConflictDialog->setIcon(QIcon::fromTheme("dialog-warning")); /***mod by ut001121 zhangmeng 20200521 将确认按钮设置为默认按钮 修复BUG26960***/ m_shortcutConflictDialog->addButton(QString(tr("OK")), true, DDialog::ButtonNormal); } // 存在后显示 m_shortcutConflictDialog->setTitle(QString(txt + QObject::tr("please set another one."))); m_shortcutConflictDialog->show(); } void CustomCommandOptDlg::addContent(QWidget *content) { Q_ASSERT(nullptr != getContentLayout()); getContentLayout()->addWidget(content); } void CustomCommandOptDlg::setIconPixmap(const QPixmap &iconPixmap) { if (nullptr != m_logoIcon) { m_logoIcon->setVisible(true); m_logoIcon->setPixmap(iconPixmap); } } void CustomCommandOptDlg::closeEvent(QCloseEvent *event) { Q_UNUSED(event) done(-1); Q_EMIT closed(); } deepin-terminal-5.2.11/src/customcommand/customcommandoptdlg.h000066400000000000000000000055711370157770500245750ustar00rootroot00000000000000#ifndef CUSTOMCOMMANDOPTDLG_H #define CUSTOMCOMMANDOPTDLG_H #include "termbasedialog.h" #include "customcommanditemmodel.h" #include #include #include #include #include #include #include #include #include #include #include DWIDGET_USE_NAMESPACE class CustomCommandOptDlg : public DAbstractDialog { Q_OBJECT public: enum CustomCmdOptType { CCT_ADD, // the add type of custom command operation CCT_MODIFY, // the modify type of custom command operation }; explicit CustomCommandOptDlg(CustomCmdOptType type = CCT_ADD, CustomCommandItemData *currItemData = nullptr, QWidget *parent = nullptr); ~CustomCommandOptDlg(); void addContent(QWidget *content); void addCancelConfirmButtons(); void setIconPixmap(const QPixmap &iconPixmap); void setCancelBtnText(const QString &strCancel); void setConfirmBtnText(const QString &strConfirm); // 快捷键冲突弹窗 void showShortcutConflictMsgbox(QString txt); void closeRefreshDataConnection(); bool checkSequence(const QKeySequence &sequence); void setModelIndex(QModelIndex mi); QDialog::DialogCode getConfirmResult(); QVBoxLayout *getMainLayout(); QAction *getCurCustomCmd(); bool isDelCurCommand(); CustomCommandItemData *m_currItemData = nullptr; QModelIndex modelIndex; DDialog *m_dlgDelete = nullptr; protected: void initUITitle(); void initTitleConnections(); void setLogoVisable(bool visible = true); void setTitle(const QString &title); QLayout *getContentLayout(); //Overrides void closeEvent(QCloseEvent *event) override; signals: void closed(); void confirmBtnClicked(); private slots: void slotAddSaveButtonClicked(); void slotDelCurCustomCommand(); void slotRefreshData(QString oldCmdName, QString newCmdName); private: void initUI(); void initCommandFromClipBoardText(); CustomCmdOptType m_type; QAction *m_newAction = nullptr; DLineEdit *m_nameLineEdit = nullptr; DLineEdit *m_commandLineEdit = nullptr; DKeySequenceEdit *m_shortCutLineEdit = nullptr; QString m_lastCmdShortcut; bool m_bDelOpt; QWidget *m_titleBar = nullptr; DLabel *m_logoIcon = nullptr; DLabel *m_titleText = nullptr; DWindowCloseButton *m_closeButton = nullptr; QWidget *m_content = nullptr; QVBoxLayout *m_contentLayout = nullptr; QVBoxLayout *m_mainLayout = nullptr; DPushButton *m_cancelBtn = nullptr; DSuggestButton *m_confirmBtn = nullptr; QDialog::DialogCode m_confirmResultCode; // 快捷键冲突弹窗 DDialog *m_shortcutConflictDialog = nullptr; bool m_bRefreshCheck = false; }; #endif // CUSTOMCOMMANDOPTDLG_H deepin-terminal-5.2.11/src/customcommand/customcommandpanel.cpp000066400000000000000000000123631370157770500247330ustar00rootroot00000000000000#include "customcommandpanel.h" #include "customcommandoptdlg.h" #include "shortcutmanager.h" #include "operationconfirmdlg.h" #include"service.h" #include #include #include #include #include #include #include #include CustomCommandPanel::CustomCommandPanel(QWidget *parent) : CommonPanel(parent) { initUI(); } CustomCommandPanel::~CustomCommandPanel() { if (m_pdlg) { delete m_pdlg; m_pdlg = nullptr; } } void CustomCommandPanel::showCurSearchResult() { QString strTxt = m_searchEdit->text(); if (strTxt.isEmpty()) return; emit showSearchResult(strTxt); } void CustomCommandPanel::showAddCustomCommandDlg() { qDebug() << __FUNCTION__ << __LINE__; if (m_pdlg) { delete m_pdlg; m_pdlg = nullptr; } // 弹窗显示 Service::instance()->setIsDialogShow(window(), true); m_pdlg = new CustomCommandOptDlg(CustomCommandOptDlg::CCT_ADD, nullptr, this); connect(m_pdlg, &CustomCommandOptDlg::finished, this, [ &](int result) { // 弹窗隐藏或消失 Service::instance()->setIsDialogShow(window(), false); if (result == QDialog::Accepted) { QAction *newAction = m_pdlg->getCurCustomCmd(); m_cmdListWidget->addNewCustomCommandData(newAction); /************************ Add by m000743 sunchengxi 2020-04-20:解决自定义命令无法添加 Begin************************/ ShortcutManager::instance()->addCustomCommand(*newAction); /************************ Add by m000743 sunchengxi 2020-04-20:解决自定义命令无法添加 End ************************/ emit Service::instance()->refreshCommandPanel("", ""); refreshCmdSearchState(); /******** Modify by m000714 daizhengwen 2020-04-10: 滚动条滑至最底端****************/ m_cmdListWidget->scrollToBottom(); /********************* Modify by m000714 daizhengwen End ************************/ } }); m_pdlg->show(); } void CustomCommandPanel::doCustomCommand(CustomCommandItemData itemData, QModelIndex index) { qDebug() << __FUNCTION__ << __LINE__; Q_UNUSED(index) QString strCommand = itemData.m_cmdText; if (!strCommand.endsWith('\n')) { strCommand.append('\n'); } emit handleCustomCurCommand(strCommand); } void CustomCommandPanel::refreshCmdPanel() { qDebug() << __FUNCTION__ << __LINE__; clearSearchInfo(); m_cmdListWidget->refreshCommandListData(""); refreshCmdSearchState(); } void CustomCommandPanel::refreshCmdSearchState() { qDebug() << __FUNCTION__ << m_cmdListWidget->count() << endl; if (m_cmdListWidget->count() >= 2) { /************************ Add by m000743 sunchengxi 2020-04-22:自定义命令搜索显示异常 Begin************************/ m_searchEdit->clearEdit(); /************************ Add by m000743 sunchengxi 2020-04-22:自定义命令搜索显示异常 End ************************/ m_searchEdit->show(); m_vlayout->setContentsMargins(0, 10, 0, 0); } else { m_searchEdit->hide(); m_vlayout->setContentsMargins(0, 0, 0, 0); } } void CustomCommandPanel::initUI() { setBackgroundRole(QPalette::Base); setAutoFillBackground(true); m_pushButton = new DPushButton(); m_cmdListWidget = new CustomCommandList(); m_searchEdit = new DSearchEdit(); m_searchEdit->setClearButtonEnabled(true); DFontSizeManager::instance()->bind(m_searchEdit, DFontSizeManager::T6); m_cmdListWidget->setSelectionMode(QAbstractItemView::NoSelection); m_cmdListWidget->setVerticalScrollMode(QAbstractItemView::ScrollMode::ScrollPerItem); m_cmdListWidget->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn); m_cmdListWidget->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); m_cmdListWidget->setSizePolicy(QSizePolicy::Policy::Expanding, QSizePolicy::Policy::Expanding); m_pushButton->setFixedHeight(36); m_pushButton->setText(tr("Add Command")); QHBoxLayout *btnLayout = new QHBoxLayout(); btnLayout->addSpacing(10); btnLayout->addWidget(m_pushButton); btnLayout->addSpacing(10); QHBoxLayout *hlayout = new QHBoxLayout(); hlayout->setSpacing(0); hlayout->setMargin(0); hlayout->setContentsMargins(0, 0, 0, 0); hlayout->addSpacing(10); hlayout->addWidget(m_searchEdit); hlayout->addSpacing(10); QVBoxLayout *vlayout = new QVBoxLayout(this); m_vlayout = vlayout; vlayout->setSpacing(0); vlayout->setMargin(0); vlayout->setContentsMargins(0, 0, 0, 0); //vlayout->addSpacing(10); vlayout->addLayout(hlayout); vlayout->addWidget(m_cmdListWidget); vlayout->addLayout(btnLayout); vlayout->addSpacing(12); setLayout(vlayout); connect(m_searchEdit, &DSearchEdit::returnPressed, this, &CustomCommandPanel::showCurSearchResult); // connect(m_pushButton, &DPushButton::clicked, this, &CustomCommandPanel::showAddCustomCommandDlg); connect(m_cmdListWidget, &CustomCommandList::itemClicked, this, &CustomCommandPanel::doCustomCommand); connect(m_cmdListWidget, &CustomCommandList::listItemCountChange, this, &CustomCommandPanel::refreshCmdSearchState); } deepin-terminal-5.2.11/src/customcommand/customcommandpanel.h000066400000000000000000000021011370157770500243650ustar00rootroot00000000000000#ifndef CUSTOMCOMMANDPANEL_H #define CUSTOMCOMMANDPANEL_H #include "rightpanel.h" #include "customcommandlist.h" #include "customcommandsearchrstpanel.h" #include "commonpanel.h" #include #include #include #include #include #include DWIDGET_USE_NAMESPACE class CustomCommandOptDlg; class CustomCommandPanel : public CommonPanel { Q_OBJECT public: explicit CustomCommandPanel(QWidget *parent = nullptr); ~CustomCommandPanel(); void refreshCmdPanel(); void refreshCmdSearchState(); signals: void handleCustomCurCommand(const QString &strCommand); void focusOut(); void showSearchResult(const QString &strCommand); public slots: void showCurSearchResult(); void showAddCustomCommandDlg(); void doCustomCommand(CustomCommandItemData itemData, QModelIndex index); private: void initUI(); private: CustomCommandList *m_cmdListWidget = nullptr; CustomCommandOptDlg *m_pdlg = nullptr; QVBoxLayout *m_vlayout = nullptr; }; #endif // CUSTOMCOMMANDPANEL_H deepin-terminal-5.2.11/src/customcommand/customcommandplugin.cpp000066400000000000000000000064031370157770500251300ustar00rootroot00000000000000#include "customcommandplugin.h" #include "customcommandpanel.h" #include "customcommandtoppanel.h" #include "mainwindow.h" #include "termwidgetpage.h" #include "settings.h" #include "shortcutmanager.h" #include #include #include CustomCommandPlugin::CustomCommandPlugin(QObject *parent) : MainWindowPluginInterface(parent) { m_pluginName = "Custom Command"; } void CustomCommandPlugin::initPlugin(MainWindow *mainWindow) { m_mainWindow = mainWindow; initCustomCommandTopPanel(); connect(m_mainWindow, &MainWindow::showPluginChanged, this, [ = ](const QString name) { if (MainWindow::PLUGIN_TYPE_CUSTOMCOMMAND != name) { getCustomCommandTopPanel()->hideAnim(); } else { /******** Add by nt001000 renfeixiang 2020-05-18:修改雷神窗口太小时,自定义界面使用不方便,将雷神窗口变大适应正常的自定义界面 Begin***************/ if (m_mainWindow->isQuakeMode() && m_mainWindow->height() < 220) { m_mainWindow->resize(m_mainWindow->width(), 220); //首先设置雷神界面的大小 m_mainWindow->showPlugin(MainWindow::PLUGIN_TYPE_CUSTOMCOMMAND);//重新打开自定义界面,当前流程结束 return; } /******** Add by nt001000 renfeixiang 2020-05-18:修改雷神窗口太小时,自定义界面使用不方便,将雷神窗口变大适应正常的自定义界面 End***************/ getCustomCommandTopPanel()->show(); } }); connect(m_mainWindow, &MainWindow::quakeHidePlugin, this, [ = ]() { getCustomCommandTopPanel()->hide(); }); } QAction *CustomCommandPlugin::titlebarMenu(MainWindow *mainWindow) { QAction *customCommandAction(new QAction(tr("Custom commands"), mainWindow)); connect(customCommandAction, &QAction::triggered, mainWindow, [mainWindow]() { mainWindow->showPlugin(MainWindow::PLUGIN_TYPE_CUSTOMCOMMAND); }); return customCommandAction; } void CustomCommandPlugin::initCustomCommandTopPanel() { m_customCommandTopPanel = new CustomCommandTopPanel(m_mainWindow->centralWidget()); connect(m_customCommandTopPanel, &CustomCommandTopPanel::handleCustomCurCommand, this, &CustomCommandPlugin::doCustomCommand); } CustomCommandTopPanel *CustomCommandPlugin::getCustomCommandTopPanel() { if (!m_customCommandTopPanel) { initCustomCommandTopPanel(); } return m_customCommandTopPanel; } void CustomCommandPlugin::doCustomCommand(const QString &strTxt) { if (!strTxt.isEmpty()) { m_mainWindow->currentPage()->sendTextToCurrentTerm(strTxt); m_mainWindow->focusCurrentPage(); /******** Add by nt001000 renfeixiang 2020-05-28:增加 使用mainwindow的hideplugin函数隐藏自定义窗口bug#21992 Begin***************/ m_mainWindow->showPlugin(MainWindow::PLUGIN_TYPE_NONE); /******** Add by nt001000 renfeixiang 2020-05-28:增加 使用mainwindow的hideplugin函数隐藏自定义窗口bug#21992 End***************/ } emit doHide(); } void CustomCommandPlugin::hidePlugn() { if (m_customCommandTopPanel && m_customCommandTopPanel->isVisible()) { m_customCommandTopPanel->hide(); } } deepin-terminal-5.2.11/src/customcommand/customcommandplugin.h000066400000000000000000000015471370157770500246010ustar00rootroot00000000000000#ifndef CUSTOMCOMMANDPLUGIN_H #define CUSTOMCOMMANDPLUGIN_H #include "customcommandtoppanel.h" #include "mainwindowplugininterface.h" #include #include class CustomCommandSearchRstPanel; class CustomCommandPanel; class MainWindow; class CustomCommandPlugin : public MainWindowPluginInterface { Q_OBJECT public: explicit CustomCommandPlugin(QObject *parent = nullptr); void initPlugin(MainWindow *mainWindow) override; QAction *titlebarMenu(MainWindow *mainWindow) override; CustomCommandTopPanel *getCustomCommandTopPanel(); void initCustomCommandTopPanel(); void hidePlugn(); signals: void doHide(); public slots: void doCustomCommand(const QString &strTxt); private: MainWindow *m_mainWindow = nullptr; CustomCommandTopPanel *m_customCommandTopPanel = nullptr; }; #endif // CUSTOMCOMMANDPLUGIN_H deepin-terminal-5.2.11/src/customcommand/customcommandsearchrstpanel.cpp000066400000000000000000000072021370157770500266460ustar00rootroot00000000000000#include "customcommandsearchrstpanel.h" #include "customcommandoptdlg.h" #include "shortcutmanager.h" #include #include #include #include CustomCommandSearchRstPanel::CustomCommandSearchRstPanel(QWidget *parent) : CommonPanel(parent), m_cmdListWidget(new CustomCommandList()) { initUI(); } void CustomCommandSearchRstPanel::setSearchFilter(const QString &filter) { m_strFilter = filter; QString showText = filter; showText = Utils::getElidedText(m_label->font(), showText, ITEMMAXWIDTH, Qt::ElideMiddle); m_label->setText(QString("%1:%2").arg(tr("Search"), showText)); } void CustomCommandSearchRstPanel::refreshData() { m_cmdListWidget->refreshCommandListData(m_strFilter); } void CustomCommandSearchRstPanel::refreshData(const QString &strFilter) { setSearchFilter(strFilter); m_cmdListWidget->refreshCommandListData(strFilter); } void CustomCommandSearchRstPanel::doCustomCommand(CustomCommandItemData itemData, QModelIndex index) { Q_UNUSED(index) QString strCommand = itemData.m_cmdText; if (!strCommand.endsWith('\n')) { strCommand.append('\n'); } emit handleCustomCurCommand(strCommand); emit focusOut(); } void CustomCommandSearchRstPanel::initUI() { setBackgroundRole(QPalette::Base); setAutoFillBackground(true); m_backButton = new DIconButton(this); m_backButton->setIcon(DStyle::StandardPixmap::SP_ArrowLeave); m_backButton->setFixedSize(QSize(40, 40)); m_backButton->setFocusPolicy(Qt::NoFocus); m_label = new DLabel(this); m_label->setAlignment(Qt::AlignCenter); // 字体颜色随主题变化变化 DPalette palette = m_label->palette(); QColor color; if (DApplicationHelper::instance()->themeType() == DApplicationHelper::DarkType) { color = QColor::fromRgb(192, 198, 212, 102); } else { color = QColor::fromRgb(85, 85, 85, 102); } palette.setBrush(QPalette::Text, color); m_label->setPalette(palette); m_cmdListWidget->setSelectionMode(QAbstractItemView::NoSelection); m_cmdListWidget->setVerticalScrollMode(QAbstractItemView::ScrollMode::ScrollPerItem); m_cmdListWidget->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn); m_cmdListWidget->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); m_cmdListWidget->setSizePolicy(QSizePolicy::Policy::Expanding, QSizePolicy::Policy::Expanding); QHBoxLayout *hlayout = new QHBoxLayout(); hlayout->addSpacing(10); hlayout->addWidget(m_backButton); // 搜索框居中显示 hlayout->addWidget(m_label, 0, Qt::AlignCenter); hlayout->setSpacing(0); hlayout->setMargin(0); QVBoxLayout *vlayout = new QVBoxLayout(); vlayout->addSpacing(10); vlayout->addLayout(hlayout); vlayout->addWidget(m_cmdListWidget); vlayout->setMargin(0); vlayout->setSpacing(0); setLayout(vlayout); connect(m_cmdListWidget, &CustomCommandList::itemClicked, this, &CustomCommandSearchRstPanel::doCustomCommand); connect(m_backButton, &DIconButton::clicked, this, &CustomCommandSearchRstPanel::showCustomCommandPanel); // 字体颜色随主题变化变化 connect(DApplicationHelper::instance(), &DGuiApplicationHelper::themeTypeChanged, m_label, [ = ](DGuiApplicationHelper::ColorType themeType) { DPalette palette = m_label->palette(); QColor color; if (themeType == DApplicationHelper::DarkType) { color = QColor::fromRgb(192, 198, 212, 102); } else { color = QColor::fromRgb(85, 85, 85, 102); } palette.setBrush(QPalette::Text, color); m_label->setPalette(palette); }); } deepin-terminal-5.2.11/src/customcommand/customcommandsearchrstpanel.h000066400000000000000000000015661370157770500263220ustar00rootroot00000000000000#ifndef CUSTOMCOMMANDSEARCHRSTPANEL_H #define CUSTOMCOMMANDSEARCHRSTPANEL_H #include "rightpanel.h" #include "commonpanel.h" #include #include #include DWIDGET_USE_NAMESPACE class CustomCommandItem; class CustomCommandSearchRstPanel : public CommonPanel { Q_OBJECT public: explicit CustomCommandSearchRstPanel(QWidget *parent = nullptr); void refreshData(const QString &strFilter); void refreshData(); signals: void handleCustomCurCommand(const QString &strCommand); void showCustomCommandPanel(); public slots: void doCustomCommand(CustomCommandItemData itemData, QModelIndex index); private: void initUI(); void setSearchFilter(const QString &filter); void showPreviousPanel(); CustomCommandList *m_cmdListWidget = nullptr; QString m_strFilter; }; #endif // CUSTOMCOMMANDSEARCHRSTPANEL_H deepin-terminal-5.2.11/src/customcommand/customcommandtoppanel.cpp000066400000000000000000000135521370157770500254570ustar00rootroot00000000000000#include "customcommandtoppanel.h" #include "service.h" #include #include #include #include #include #include const int iAnimationDuration = 300; CustomCommandTopPanel::CustomCommandTopPanel(QWidget *parent) : RightPanel(parent), m_customCommandPanel(new CustomCommandPanel(this)), m_customCommandSearchPanel(new CustomCommandSearchRstPanel(this)) { setAttribute(Qt::WA_TranslucentBackground); connect(m_customCommandPanel, &CustomCommandPanel::showSearchResult, this, &CustomCommandTopPanel::showCustomCommandSearchPanel); connect(m_customCommandPanel, &CustomCommandPanel::handleCustomCurCommand, this, &CustomCommandTopPanel::handleCustomCurCommand); connect(m_customCommandSearchPanel, &CustomCommandSearchRstPanel::showCustomCommandPanel, this, &CustomCommandTopPanel::showCustomCommandPanel); connect(m_customCommandSearchPanel, &CustomCommandSearchRstPanel::handleCustomCurCommand, this, &CustomCommandTopPanel::handleCustomCurCommand); /******** Modify by nt001000 renfeixiang 2020-05-28:修改将该行隐藏,RightPanel::hideAnim函数不会将自定义窗口标志设置未PLUGIN_TYPE_NONEbug#21992 Begin***************/ // connect(this, &CustomCommandTopPanel::handleCustomCurCommand, this, &RightPanel::hideAnim); /******** Modify by nt001000 renfeixiang 2020-05-28:修改将该行隐藏,RightPanel::hideAnim函数不会将自定义窗口标志设置未PLUGIN_TYPE_NONEbug#21992 Begin***************/ connect(Service::instance(), &Service::refreshCommandPanel, this, &CustomCommandTopPanel::slotsRefreshCommandPanel); } void CustomCommandTopPanel::showCustomCommandPanel() { qDebug() << "showCustomCommandPanel" << endl; m_customCommandPanel->resize(size()); m_customCommandPanel->refreshCmdPanel(); m_customCommandPanel->show(); QPropertyAnimation *animation = new QPropertyAnimation(m_customCommandSearchPanel, "geometry"); animation->setDuration(iAnimationDuration); animation->setEasingCurve(QEasingCurve::OutQuad); QRect rect = geometry(); animation->setStartValue(QRect(0, rect.y(), rect.width(), rect.height())); animation->setEndValue(QRect(rect.width(), rect.y(), rect.width(), rect.height())); connect(animation, &QPropertyAnimation::finished, m_customCommandSearchPanel, &QWidget::hide); connect(animation, &QPropertyAnimation::finished, animation, &QPropertyAnimation::deleteLater); QPropertyAnimation *animation1 = new QPropertyAnimation(m_customCommandPanel, "geometry"); animation1->setDuration(iAnimationDuration); animation1->setEasingCurve(QEasingCurve::OutQuad); animation1->setStartValue(QRect(-rect.width(), rect.y(), rect.width(), rect.height())); animation1->setEndValue(QRect(0, rect.y(), rect.width(), rect.height())); connect(animation1, &QPropertyAnimation::finished, animation1, &QPropertyAnimation::deleteLater); QParallelAnimationGroup *group = new QParallelAnimationGroup(this); group->addAnimation(animation); group->addAnimation(animation1); // 已验证:这个设定,会释放group以及所有组内动画。 group->start(QAbstractAnimation::DeleteWhenStopped); } void CustomCommandTopPanel::showCustomCommandSearchPanel(const QString &strFilter) { qDebug() << "showCustomCommandSearchPanel" << endl; m_customCommandSearchPanel->refreshData(strFilter); m_customCommandSearchPanel->show(); m_customCommandSearchPanel->setFocus(); QPropertyAnimation *animation = new QPropertyAnimation(m_customCommandSearchPanel, "geometry"); animation->setDuration(iAnimationDuration); animation->setEasingCurve(QEasingCurve::OutQuad); QRect rect = geometry(); animation->setStartValue(QRect(rect.width(), rect.y(), rect.width(), rect.height())); animation->setEndValue(QRect(0, rect.y(), rect.width(), rect.height())); connect(animation, &QPropertyAnimation::finished, animation, &QPropertyAnimation::deleteLater); QPropertyAnimation *animation1 = new QPropertyAnimation(m_customCommandPanel, "geometry"); animation1->setDuration(iAnimationDuration); animation->setEasingCurve(QEasingCurve::OutQuad); animation1->setStartValue(QRect(0, rect.y(), rect.width(), rect.height())); animation1->setEndValue(QRect(-rect.width(), rect.y(), rect.width(), rect.height())); connect(animation1, &QPropertyAnimation::finished, m_customCommandPanel, &QWidget::hide); connect(animation1, &QPropertyAnimation::finished, animation1, &QPropertyAnimation::deleteLater); QParallelAnimationGroup *group = new QParallelAnimationGroup(this); group->addAnimation(animation1); group->addAnimation(animation); // 已验证:这个设定,会释放group以及所有组内动画。 group->start(QAbstractAnimation::DeleteWhenStopped); } void CustomCommandTopPanel::show() { RightPanel::show(); m_customCommandPanel->resize(size()); m_customCommandPanel->move(0, 0); m_customCommandPanel->show(); m_customCommandPanel->refreshCmdPanel(); m_customCommandSearchPanel->resize(size()); m_customCommandSearchPanel->hide(); } /******** Modify by nt001000 renfeixiang 2020-05-15:修改自定义界面,在Alt+F2时,隐藏在显示,高度变大问题 Begin***************/ //void CustomCommandTopPanel::resizeEvent(QResizeEvent *event) //{ // m_customCommandPanel->resize(size()); //} /******** Modify by nt001000 renfeixiang 2020-05-15:修改自定义界面,在Alt+F2时,隐藏在显示,高度变大问题 End***************/ void CustomCommandTopPanel::slotsRefreshCommandPanel() { m_customCommandPanel->resize(size()); m_customCommandPanel->show(); m_customCommandPanel->refreshCmdPanel(); m_customCommandSearchPanel->refreshData(); } deepin-terminal-5.2.11/src/customcommand/customcommandtoppanel.h000066400000000000000000000021451370157770500251200ustar00rootroot00000000000000#ifndef CUSTOMCOMMANDTOPPANEL_H #define CUSTOMCOMMANDTOPPANEL_H #include "rightpanel.h" #include "customcommandpanel.h" #include "customcommandsearchrstpanel.h" #include class CustomCommandTopPanel : public RightPanel { Q_OBJECT public: explicit CustomCommandTopPanel(QWidget *parent = nullptr); void show(); protected: /******** Modify by nt001000 renfeixiang 2020-05-15:修改自定义界面,在Alt+F2时,隐藏在显示,高度变大问题 Begin***************/ //void resizeEvent(QResizeEvent *event) override; /******** Modify by nt001000 renfeixiang 2020-05-15:修改自定义界面,在Alt+F2时,隐藏在显示,高度变大问题 End***************/ signals: void focusOut(); void handleCustomCurCommand(const QString &strCommand); public slots: void showCustomCommandPanel(); void showCustomCommandSearchPanel(const QString &strFilter); void slotsRefreshCommandPanel(); private: CustomCommandPanel *m_customCommandPanel = nullptr; CustomCommandSearchRstPanel *m_customCommandSearchPanel = nullptr; }; #endif // CUSTOMCOMMANDTOPPANEL_H deepin-terminal-5.2.11/src/deepin-terminal.desktop000066400000000000000000000226051370157770500221350ustar00rootroot00000000000000[Desktop Entry] Categories=DDE;Utility;System;TerminalEmulator; Comment=Use the command line Exec=deepin-terminal GenericName=Terminal Icon=deepin-terminal Keywords=shell;prompt;command;commandline; Name=Deepin Terminal StartupNotify=false TryExec=deepin-terminal Type=Application X-Deepin-Vendor=deepin # Translations: # Do not manually modify! Comment[am_ET]=የ ትእዛዝ መስመር ይጠቀሙ Comment[ar]=استخدام سطر الأوامر Comment[ast]=Usa la llinia de comandos Comment[az]=Əmr sətirindən istifadə et Comment[bg]=Използване на команден ред Comment[ca]=Useu la línia d'ordres Comment[cs]=Použít příkazový řádek Comment[da]=Brug kommandolinjen Comment[de]=Kommandozeile benutzen Comment[el]=Χρήση της γραμμής εντολών Comment[en_AU]=Use the command line Comment[eo]=Uzi la komandlinio Comment[es]=Usar la línea de comando Comment[es_419]=Usar la línea de comandos Comment[fa]=استفاده از خط فرمان Comment[fi]=Käytä komentoriviä Comment[fr]=Utiliser la ligne de commande Comment[gl_ES]=Empregar a liña de comandos Comment[he]=השתמש בשורת פקודה Comment[hi_IN]=आदेश रेखा का उपयोग करें Comment[hr]=Koristi naredbeni redak Comment[hu]= Parancssor használata Comment[hy]=Օգտագործել հրամանների տողը Comment[id]=Gunakan baris perintah Comment[it]=Usa linea di comando Comment[ja]=コマンドラインを使用する Comment[ko]=명령 행 사용 Comment[lt]=Naudoti komandų eilutę Comment[ml]=കമാൻഡ് ലൈൻ ഉപയോഗിക്കുക Comment[mn]=Комманд мѳр ашиглах Comment[ms]=guna baris perintah Comment[nb]=Bruk kommandolinjen Comment[nl]=Gebruik de opdrachtregel Comment[pam]=Gamitan ing command line Comment[pl]=Użyj wiersza poleceń Comment[pt]=Utilize a linha de comandos Comment[pt_BR]=Usar a linha de comando Comment[ro]=Utilizare linia de comandă Comment[ru]=Использовать командную строку Comment[sk]=Použiť príkazový riadok Comment[sl]=Uporabi ukazno vrstico Comment[sq]=Përdorni rresht urdhrash Comment[sr]=Користите командну линију Comment[sv]=Använd kommandoraden Comment[tr]=Komut satırını kullan Comment[uk]=Використовувати командний рядок Comment[zh_CN]=使用命令行 Comment[zh_HK]=使用命令列 Comment[zh_TW]=使用命令列介面 GenericName[af]=Terminaal GenericName[am_ET]=ተርሚናል GenericName[ar]=الطرفية GenericName[ast]=Terminal GenericName[az]=Terminal GenericName[bg]=Терминал GenericName[bn]=প্রান্তিক GenericName[ca]=Terminal GenericName[cs]=Terminál GenericName[da]=Terminal GenericName[de]=Terminal GenericName[el]=Τερματικό GenericName[en_AU]=Terminal GenericName[eo]=Terminalo GenericName[es]=Terminal GenericName[es_419]=Terminal GenericName[fa]=ترمینال GenericName[fi]=Pääte GenericName[fr]=Terminal GenericName[gl_ES]=Terminal GenericName[he]=מסוף GenericName[hi_IN]=टर्मिनल GenericName[hr]=Terminal GenericName[hu]=Terminál GenericName[id]=Terminal GenericName[it]=Terminale GenericName[ja]=ターミナル GenericName[ko]=터미널 GenericName[lt]=Terminalas GenericName[ml]=ടെർമിനൽ GenericName[mn]=Терминал GenericName[ms]=Terminal GenericName[nb]=Terminal GenericName[ne]=टर्मिनल GenericName[nl]=Terminal GenericName[pl]=Terminal GenericName[pt]=Terminal GenericName[pt_BR]=Terminal GenericName[ro]=Terminalul GenericName[ru]=Терминал GenericName[sk]=Terminál GenericName[sl]=Terminal GenericName[sq]=Terminal GenericName[sr]=Терминал GenericName[sv]=Terminal GenericName[ta]=முனையம் GenericName[tr]=Uçbirim GenericName[ug]=تېرمىنال GenericName[uk]=Термінал GenericName[vi]=Đầu cuối GenericName[zh_CN]=终端 GenericName[zh_HK]=終端機 GenericName[zh_TW]=終端機 Keywords[ar]=shell;prompt;command;commandline; Keywords[ast]=shell;comandu;llinia;llinia de comandos;comandos; Keywords[bg]=shell;prompt;command;commandline; Keywords[ca]=shell;intèrpret;intèrpret d'ordres;ordres;ordre;línia d'ordres; Keywords[cs]=shell;prompt;příkaz;příkazový řádek; Keywords[da]=skal;prompt;kommando;kommandolinje; Keywords[de]=shell;prompt;command;commandline; Keywords[el]=κέλυφος;προτροπή;εντολή;γραμμή-εντολών; Keywords[es]=shell;prompt;command;comando;commandline;lineadecomandos; Keywords[es_419]=shell;prompt;command;commandline; Keywords[fa]=پوسته ؛ سریع ؛ فرمان ؛ خط فرمان ؛ Keywords[fi]=shell;kehote;komento;komentorivi;pääte;terminaali; Keywords[fr]=shell;prompt;command;commandline; Keywords[hu]=shell;prompt;parancs;parancssor Keywords[id]=shell;prompt;perintah;barisperintah; Keywords[it]=shell;prompt;command;commandline;terminale;cmd;script;bash; Keywords[ko]=shell;prompt;command;commandline;쉘;프롬프트;명령;명령행; Keywords[lt]=apvalkalas;užklausa;komanda;komandų eilutė;eilutė;komandos; Keywords[ms]=shell;prom;perintah;barisperintah; Keywords[nl]=shell;prompt;opdracht;opdrachtregel; Keywords[pl]=powłoka;zapytanie;polecenie;wiersz;poleceń; Keywords[pt]=shell;prompt;comando;commandline; Keywords[pt_BR]=shell;prompt;command;commandline; Keywords[ro]=shell;prompt;comandă;liniecomandă; Keywords[ru]=shell;prompt;command;commandline; Keywords[sk]=shell;prompt;command;commandline; Keywords[sq]=shell;prompt;command;commandline; Keywords[sr]=shell;prompt;команда;командна линија; Keywords[sv]=shell;prompt;command;commandline; Keywords[tr]=shell;prompt;command;commandline;kabuk;komut;komutsatırı; Keywords[uk]=shell;prompt;command;commandline;оболонка;запит;команда;командна;рядок; Keywords[zh_CN]=shell;prompt;command;commandline; Keywords[zh_TW]=shell;prompt;command;commandline;提示;指令;指令列; Name[am_ET]=የ ዲፕኢን ተርሚናል Name[ar]=طرفية ديبين Name[ast]=Deepin Terminal Name[az]=Deepin Terminal Name[bg]=Deepin терминал Name[ca]=Terminal del Deepin Name[cs]=Terminál Name[da]=Deepin terminal Name[de]=Deepin Terminal Name[el]=Deepin Tερματικό Name[en_AU]=Deepin Terminal Name[eo]=Deepin terminalo Name[es]=Terminal Deepin Name[es_419]=Terminal Deepin Name[fa]=ترمینال دیپین Name[fi]=Deepin pääte Name[fil]=Deepin Terminal Name[fr]=Deepin Terminal Name[gl_ES]=Terminal Name[he]=מסוף Deepin Name[hi_IN]=डीपइन छोर Name[hr]=Deepin terminal Name[hu]=Deepin Terminál Name[hy]=Deepin Տերմինալ Name[id]=Terminal Deepin Name[it]=Terminale di Deepin Name[ja]=Deepin ターミナル Name[ko]=Deepin 터미널 Name[lt]=Deepin terminalas Name[ml]=ഡീപിൻ ടെർമിനൽ Name[mn]=Дээпин Терминал Name[ms]=Terminal Deepin Name[nb]=Deepin terminal Name[nl]=Deepin Terminal Name[pam]=Deepin Terminal Name[pl]=Terminal Deepin Name[pt]=Terminal Deepin Name[pt_BR]=Terminal Deepin Name[ro]=Terminalul Deepin Name[ru]= Терминал Deepin Name[sk]=Deepin Terminál Name[sl]=Terminal Deepin Name[sq]=Terminali Deepin Name[sr]=Дипин Терминал Name[sv]=Deepin-terminal Name[tr]=Deepin Uçbirim Name[ug]=Deepin تېرمىنالى Name[uk]=Термінал Deepin Name[vi]=Deepin Terminal Name[zh_CN]=终端 Name[zh_HK]=終端機 Name[zh_TW]=終端器 [NewWindow Shortcut Group] Exec=deepin-terminal Name=New Window # Translations: # Do not manually modify! Name[ar]=نافذة جديدة Name[ast]=Ventana nueva Name[bg]=Нов прозорец Name[ca]=Finestra nova Name[cs]=Nové okno Name[da]=Nyt vindue Name[de]=Neues Fenster Name[el]=Νέο παράθυρο Name[es]=Nueva ventana Name[es_419]=Nueva ventana Name[fa]=پنجره جدید Name[fi]=Uusi ikkuna Name[fr]=Nouvelle fenêtre Name[hr]=Novi prozor Name[hu]=Új ablak Name[id]=Jendela Baru Name[it]=Nuova finestra Name[ja]=新しいウィンドウ Name[ko]=새 창 Name[lt]=Naujas langas Name[mn]=Шинэ Цонх Name[ms]=Terminal Baharu Name[nl]=Nieuw venster Name[pl]=Nowe okno Name[pt]=Nova janela Name[pt_BR]=Nova Janela Name[ro]=Fereastră Nouă Name[ru]=Новое Окно Name[sk]=Nové okno Name[sq]=Dritare e Re Name[sr]=Нови прозор Name[sv]=Nytt fönster Name[tr]=Yeni Pencere Name[uk]=Нове вікно Name[zh_CN]=新建窗口 Name[zh_TW]=開新視窗 [Quake Shortcut Group] Exec=deepin-terminal --quake-mode Name=Quake Terminal # Translations: # Do not manually modify! Name[ar]=طرفية كواك Name[ast]=Terminal Quake Name[bg]=Quake терминал Name[ca]=Terminal Quake Name[cs]=Vysouvací terminál (quake) Name[da]=Quake-terminal Name[de]=Quake Terminal Name[el]=Τερματικό "Quake" Name[es]=Terminal Quake Name[es_419]=Terminal en modo Quake Name[fa]=ترمینال Quake Name[fi]=Quake pääte Name[fr]=Terminal Quake Name[hr]=Quake terminal Name[hu]=Quake Terminál Name[id]=Terminal Quake Name[it]=Terminale in primo piano Name[ja]=ターミナルを振動させる Name[ko]=퀘이크 터미널 Name[lt]=Quake terminalas Name[mn]=Куаке Терминал Name[ms]=Terminal Quake Name[nl]=Quake-terminal Name[pl]=Terminal Quake Name[pt]=Terminal deslizante Name[pt_BR]=Terminal Quake Name[ro]=Terminal Quake Name[ru]=Выпадающий Терминал Name[sk]=Quake terminál Name[sq]=Terminal Quake Name[sr]=Спуштајући терминал Name[sv]=Quake Terminal Name[tr]=Quake Uçbirim Name[uk]=Термінал Quake Name[zh_CN]=雷神终端 Name[zh_TW]=雷神模式終端器 deepin-terminal-5.2.11/src/encodeplugin/000077500000000000000000000000001370157770500201345ustar00rootroot00000000000000deepin-terminal-5.2.11/src/encodeplugin/encodelistmodel.cpp000066400000000000000000000164341370157770500240220ustar00rootroot00000000000000#include "encodelistmodel.h" #include #include #include #include DWIDGET_USE_NAMESPACE EncodeListModel::EncodeListModel(QObject *parent) : QStandardItemModel(parent) { initEncodeData(); } int EncodeListModel::rowCount(const QModelIndex &parent) const { Q_UNUSED(parent); // return m_encodeData.count(); } QVariant EncodeListModel::data(const QModelIndex &index, int role) const { Q_UNUSED(role); const int row = index.row(); return m_encodeData[row]; } QList EncodeListModel::listData() { return m_encodeData; } void EncodeListModel::initEncodeData() { QList all = QTextCodec::availableCodecs(); // m_encodeData = QTextCodec::availableCodecs().toSet().toList(); QList showEncodeList; // 这是ubuntu18.04支持的编码格式,按国家排列的 // showEncodeList << "GB18030" << "GB2312" << "GBK" // << "BIG5" << "BIG5-HKSCS" << "EUC-TW" // << "EUC-JP" << "ISO-2022-JP" << "SHIFT_JIS" // << "EUC-KR" << "ISO-2022-KR" << "UHC" // << "IBM864" << "ISO-8859-6" << "MAC_ARABIC" << "WINDOWS-1256" // << "ARMSCII-8" // << "ISO-8859-13" << "ISO-8859-4" << "WINDOWS-1257" // << "ISO-8859-14" // << "IBM-852" << "ISO-8859-2" << "MAC_CE" << "WINDOWS-1250" // << "MAC_CROATIAN" // << "IBM855" << "ISO-8859-5" << "ISO-IR-111" << "ISO-IR-111" << "KOI8-R" << "MAC-CYRILLIC" << "WINDOWS-1251" // << "CP866" // << "KOI8-U" << "MAC_UKRAINIAN" // << "GEORGIAN-PS" // << "ISO-8859-7" << "MAC_GREEK" << "WINDOWS-1253" // << "MAC_GUJARATI" // << "MAC_GURMUKHI" // << "IBM862" << "ISO-8859-8-I" << "MAC_HEBREW" << "WINDOWS-1255" // << "ISO-8859-8" // << "MAC_DEVANAGARI" // << "MAC_ICELANDIC" // << "ISO-8859-10" // << "MAC_FARSI" // << "ISO-8859-16" << "MAC_ROMANIAN" // << "ISO-8859-3" // << "TIS-620" // << "IBM857" << "ISO-8859-9" << "MAC_TURKISH" << "WINDOWS-1254" // << "TCVN" << "VISCII" << "WINDOWS-1258" // << "IBM850" << "ISO-8859-1" << "ISO-8859-15" << "MAC_ROMAN" << "WINDOWS-1252"; showEncodeList << "UTF-8" << "GB18030" << "GB2312" << "GBK" /*简体中文*/ << "BIG5" << "BIG5-HKSCS" //<< "EUC-TW" /*繁体中文*/ << "EUC-JP" << "SHIFT_JIS" //<< "ISO-2022-JP"/*日语*/ << "EUC-KR" //<< "ISO-2022-KR" //<< "UHC" /*韩语*/ << "IBM864" << "ISO-8859-6" << "ARABIC" << "WINDOWS-1256" /*阿拉伯语*/ //<< "ARMSCII-8" /*美国语*/ << "ISO-8859-13" << "ISO-8859-4" << "WINDOWS-1257" /*波罗的海各国语*/ << "ISO-8859-14" /*凯尔特语*/ << "IBM-852" << "ISO-8859-2" << "x-mac-CE" << "WINDOWS-1250" /*中欧*/ //<< "x-mac-CROATIAN" /*克罗地亚*/ << "IBM855" << "ISO-8859-5" << "KOI8-R" << "MAC-CYRILLIC" << "WINDOWS-1251" //<< "ISO-IR-111" /*西里尔语*/ << "CP866" /*西里尔语或俄语*/ << "KOI8-U" << "x-MacUkraine" /*西里尔语或乌克兰语*/ //<< "GEORGIAN-PS" << "ISO-8859-7" << "x-mac-GREEK" << "WINDOWS-1253" /*希腊语*/ //<< "x-mac-GUJARATI" //<< "x-mac-GURMUKHI" << "IBM862" << "ISO-8859-8-I" << "WINDOWS-1255"//<< "x-mac-HEBREW" /*希伯来语*/ << "ISO-8859-8" /*希伯来语*/ //<< "x-mac-DEVANAGARI" //<< "x-mac-ICELANDIC" /*冰岛语*/ << "ISO-8859-10" /*北欧语*/ //<< "x-mac-FARSI" /*波斯语*/ //<< "x-mac-ROMANIAN" //<< "ISO-8859-16" /*罗马尼亚语*/ << "ISO-8859-3" /*西欧语*/ << "TIS-620" /*泰语*/ << "IBM857" << "ISO-8859-9" << "x-mac-TURKISH" << "WINDOWS-1254" /*土耳其语*/ << "WINDOWS-1258" //<< "TCVN" << "VISCII" /*越南语*/ << "IBM850" << "ISO-8859-1" << "ISO-8859-15" << "x-ROMAN8" << "WINDOWS-1252"; /*西方国家*/ // meld提供的编码格式,按名称排列的 // showEncodeList<<"UTF-8" // <<"ISO-8859-1" // <<"ISO-8859-2" // <<"ISO-8859-3" // <<"ISO-8859-4" // <<"ISO-8859-5" // <<"ISO-8859-6" // <<"ISO-8859-7" // <<"ISO-8859-8" // <<"ISO-8859-9" // <<"ISO-8859-10" // <<"ISO-8859-13" // <<"ISO-8859-14" // <<"ISO-8859-15" // //<<"ISO-8859-16" // <<"UTF-7" // <<"UTF-16" // <<"UTF-16BE" // <<"UTF-16LE" // <<"UTF-32" // <<"UCS-2" // <<"UCS-4" // //<<"ARMSCII-8" // <<"BIG5" // <<"BIG5-HKSCS" // <<"CP866" // <<"EUC-JP" // //<<"EUC-JP-MS" // <<"CP932" // <<"EUC-KR" // //<<"EUC-TW" // <<"GB18030" // <<"GB2312" // <<"GBK" // //<<"GEORGIAN-ACADEMY" // <<"IBM850" // <<"IBM852" // <<"IBM855" // <<"IBM857" // <<"IBM862" // <<"IBM864" // <<"ISO-2022-JP" // <<"ISO-2022-KR" // //<<"ISO-IR-111" // //<<"JOHAB" // <<"KOI8-R" // <<"KOI8-U" // <<"SHIFT_JIS" // //<<"TCVN" // <<"TIS-620" // //<<"UHC" // //<<"VISCII" // <<"WINDOWS-1250" // <<"WINDOWS-1251" // <<"WINDOWS-1252" // <<"WINDOWS-1253" // <<"WINDOWS-1254" // <<"WINDOWS-1255" // <<"WINDOWS-1256" // <<"WINDOWS-1257" // <<"WINDOWS-1258"; // 自定义的名称,系统里不一定大小写完全一样,再同步一下。 for (QByteArray &name : showEncodeList) { QString strname1 = name; bool bFind = false; QByteArray encodename; for (QByteArray &name2 : all) { QString strname2 = name2; if (strname1.compare(strname2, Qt::CaseInsensitive) == 0) { bFind = true; encodename = name2; break; } } if (!bFind) { qDebug() << "encode name :" << name << "not find!"; } else { m_encodeData << encodename; } } //qDebug()<<"all encode name :"< class EncodeListModel : public QStandardItemModel { Q_OBJECT public: EncodeListModel(QObject *parent = nullptr); int rowCount(const QModelIndex &parent) const override; QVariant data(const QModelIndex &index, int role) const override; QList listData(); private: void initEncodeData(); QList m_encodeData; }; #endif // THEMELISTMODEL_H deepin-terminal-5.2.11/src/encodeplugin/encodelistview.cpp000066400000000000000000000111411370157770500236620ustar00rootroot00000000000000#include "encodelistview.h" #include "encodelistmodel.h" #include "settings.h" #include "service.h" #include "termwidget.h" //#include "encodeitemdelegate.h" #include #include #include #include EncodeListView::EncodeListView(QWidget *parent) : DListView(parent), m_encodeModel(new EncodeListModel(this)) { m_standardModel = new QStandardItemModel(this); m_Mainwindow = qobject_cast(parentWidget()->parentWidget()->parentWidget()); // init view. this->setModel(m_standardModel); setBackgroundRole(QPalette::NoRole); setAutoFillBackground(false); setSelectionMode(QListView::NoSelection); setVerticalScrollMode(ScrollPerItem); setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn); setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); //add by ameng 设置属性,修复BUG#20074 setFixedWidth(m_ContentWidth+20); setItemSize(QSize(m_ContentWidth, m_ContentHeight + m_Space)); /***add by ut001121 zhangmeng 20200628 设置视图边距,留出空间给滚动条显示 修复BUG35378***/ setViewportMargins(10,10,10,10); /***add by ut001121 zhangmeng 20200521 设置非编辑模式 修复BUG27443***/ setEditTriggers(QAbstractItemView::NoEditTriggers); initEncodeItems(); update(); connect(this, &DListView::clicked, this, &EncodeListView::onListViewClicked); connect(this, &DListView::activated, this, &QListView::clicked); connect(Service::instance(), &Service::checkEncode, this, &EncodeListView::checkEncode); } void EncodeListView::initEncodeItems() { QList encodeDataList = m_encodeModel->listData(); for (int i = 0; i < encodeDataList.size(); i++) { QByteArray encodeData = encodeDataList.at(i); QString strEncode = QString(encodeData); DStandardItem *item = new DStandardItem; item->setText(strEncode); item->setCheckable(true); m_standardModel->appendRow(item); } // 默认起动选择第一个。 m_standardModel->item(0)->setCheckState(Qt::Checked); } void EncodeListView::focusOutEvent(QFocusEvent *event) { emit focusOut(); DListView::focusOutEvent(event); } void EncodeListView::selectionChanged(const QItemSelection &selected, const QItemSelection &deselected) { DListView::selectionChanged(selected, deselected); } void EncodeListView::setSelection(const QRect &rect, QItemSelectionModel::SelectionFlags command) { DListView::setSelection(rect, command); } /******************************************************************************* 1. @函数: resizeEvent 2. @作者: ut001121 张猛 3. @日期: 2020-07-01 4. @说明: 处理尺寸变化事件 *******************************************************************************/ void EncodeListView::resizeEvent(QResizeEvent *event) { /***add by ut001121 zhangmeng 20200701 修改滚动条高度,解决滚动条被窗口特效圆角切割的问题***/ verticalScrollBar()->setFixedHeight(height()-10); return DListView::resizeEvent(event); } void EncodeListView::resizeContents(int width, int height) { Q_UNUSED(width) Q_UNUSED(height) } QSize EncodeListView::contentsSize() const { return itemSize(); } void EncodeListView::onListViewClicked(const QModelIndex &index) { if (!index.isValid()) { return; } qDebug() << "check encode " << index.data().toString(); QStandardItemModel *model = qobject_cast(this->model()); for (int row = 0; row < model->rowCount(); row++) { DStandardItem *modelItem = dynamic_cast(model->item(row)); if (row == index.row()) { modelItem->setCheckState(Qt::Checked); // 修改配置生效。 m_Mainwindow->currentPage()->currentTerminal()->selectEncode(index.data().toString()); } else { modelItem->setCheckState(Qt::Unchecked); } } } void EncodeListView::checkEncode(QString encode) { // 判断是否是当前窗口 if (this->isActiveWindow()) { qDebug() << "check encode " << encode; QStandardItemModel *model = qobject_cast(this->model()); for (int row = 0; row < model->rowCount(); row++) { QModelIndex modelindex = model->index(row, 0); DStandardItem *modelItem = dynamic_cast(model->item(row)); if (modelindex.data().toString() == encode) { modelItem->setCheckState(Qt::Checked); scrollTo(modelindex); } else { modelItem->setCheckState(Qt::Unchecked); } } } } deepin-terminal-5.2.11/src/encodeplugin/encodelistview.h000066400000000000000000000021441370157770500233320ustar00rootroot00000000000000#ifndef ENCODELISTVIEW_H #define ENCODELISTVIEW_H #include "mainwindow.h" #include DWIDGET_USE_NAMESPACE class EncodeListModel; class EncodeListView : public DListView { Q_OBJECT public: EncodeListView(QWidget *parent = nullptr); protected: void focusOutEvent(QFocusEvent *event) override; void selectionChanged(const QItemSelection &selected, const QItemSelection &deselected) override; void setSelection(const QRect &rect, QItemSelectionModel::SelectionFlags command) override; void resizeEvent(QResizeEvent *event); void resizeContents(int width, int height); QSize contentsSize() const; signals: void focusOut(); public slots: void onListViewClicked(const QModelIndex &index); void checkEncode(QString encode); private: void initEncodeItems(); MainWindow *m_Mainwindow = nullptr; EncodeListModel *m_encodeModel = nullptr; QStandardItemModel *m_standardModel = nullptr; const int m_Space = 10; const int m_ContentWidth = 220; const int m_ContentHeight = 50; const int m_ListLenth = 1500; }; #endif // THEMELISTVIEW_H deepin-terminal-5.2.11/src/encodeplugin/encodepanel.cpp000066400000000000000000000042411370157770500231160ustar00rootroot00000000000000#include "encodepanel.h" #include "encodelistview.h" #include "encodelistmodel.h" #include "settings.h" #include #include #include EncodePanel::EncodePanel(QWidget *parent) : RightPanel(parent), m_encodeView(new EncodeListView(this)) { setBackgroundRole(QPalette::Base); setAutoFillBackground(true); setFocusProxy(m_encodeView); /******** Modify by m000714 daizhengwen 2020-03-31: 设置本窗口不获得主场口的焦点****************/ setFocusPolicy(Qt::NoFocus); /********************* Modify by m000714 daizhengwen End ************************/ QScroller::grabGesture(m_encodeView, QScroller::TouchGesture); QHBoxLayout *hLayout = new QHBoxLayout(); // hLayout->addSpacing(10); hLayout->addWidget(m_encodeView); // hLayout->addSpacing(10); // init layout. QVBoxLayout *layout = new QVBoxLayout(this); /******** Modify by nt001000 renfeixiang 2020-05-16:解决Alt+F2显示Encode时,高度变长的问题 Begin***************/ //layout->addSpacing(10);//增加的spacing会影响m_encodeView的高度 layout->addLayout(hLayout); layout->addStretch(); layout->setMargin(0);//增加的Margin会影响m_encodeView的高度 layout->setSpacing(0); /******** Modify by nt001000 renfeixiang 2020-05-16:解决Alt+F2显示Encode时,高度变长的问题 Begin***************/ connect(m_encodeView, &EncodeListView::focusOut, this, &RightPanel::hideAnim); } /******** Add by nt001000 renfeixiang 2020-05-16:解决Alt+F2显示Encode时,高度变长的问题 Begin***************/ //增加一个show函数,设置m_encodeView的大小 void EncodePanel::show() { RightPanel::show(); qDebug() << "EncodePanelEncodePanelshow" << size().height(); //解决Alt+F2显示Encode时,高度变长的问题 每次显示时,设置固定高度 Begin m_encodeView->setFixedHeight(size().height()); //解决Alt+F2显示Encode时,高度变长的问题 End } void EncodePanel::updateEncode(QString encode) { m_encodeView->checkEncode(encode); } /******** Add by nt001000 renfeixiang 2020-05-16:解决Alt+F2显示Encode时,高度变长的问题 End***************/ deepin-terminal-5.2.11/src/encodeplugin/encodepanel.h000066400000000000000000000014361370157770500225660ustar00rootroot00000000000000#ifndef ENCODEPANEL_H #define ENCODEPANEL_H #include "rightpanel.h" class EncodeListView; class EncodePanel : public RightPanel { Q_OBJECT public: explicit EncodePanel(QWidget *parent = nullptr); /******** Add by nt001000 renfeixiang 2020-05-16:解决Alt+F2显示Encode时,高度变长的问题 Begin***************/ void show(); /******** Add by nt001000 renfeixiang 2020-05-16:解决Alt+F2显示Encode时,高度变长的问题 End***************/ /******** Modify by ut000610 daizhengwen 2020-05-29: 根据焦点变换更新编码****************/ void updateEncode(QString encode); /********************* Modify by ut000610 daizhengwen End ************************/ signals: private: EncodeListView *m_encodeView = nullptr; }; #endif // THEMEPANEL_H deepin-terminal-5.2.11/src/encodeplugin/encodepanelplugin.cpp000066400000000000000000000061461370157770500243430ustar00rootroot00000000000000#include "encodepanelplugin.h" #include "mainwindow.h" #include "encodepanel.h" #include "termwidgetpage.h" #include "termwidget.h" #include "settings.h" #include "service.h" #include #include EncodePanelPlugin::EncodePanelPlugin(QObject *parent) : MainWindowPluginInterface(parent) { m_pluginName = "Encoding"; } void EncodePanelPlugin::initPlugin(MainWindow *mainWindow) { m_mainWindow = mainWindow; initEncodePanel(); connect(m_mainWindow, &MainWindow::showPluginChanged, this, [ = ](const QString name) { if (MainWindow::PLUGIN_TYPE_ENCODING != name) { getEncodePanel()->hideAnim(); } else { /******** Add by nt001000 renfeixiang 2020-05-18:修改雷神窗口太小时,编码界面使用不方便,将雷神窗口变大适应正常的编码界面 Begin***************/ if (m_mainWindow->isQuakeMode() && m_mainWindow->height() < 220) { m_mainWindow->resize(m_mainWindow->width(), 220); //首先设置雷神界面的大小 m_mainWindow->showPlugin(MainWindow::PLUGIN_TYPE_ENCODING);//重新打开编码界面,当前流程结束 return; } /******** Add by nt001000 renfeixiang 2020-05-18:修改雷神窗口太小时,编码界面使用不方便,将雷神窗口变大适应正常的编码界面 End***************/ /******** Modify by ut000610 daizhengwen 2020-05-28: 判断此时是服务器还是终端****************/ TermWidget *term = m_mainWindow->currentPage()->currentTerminal(); setCurrentTermEncode(term); getEncodePanel()->show(); } }); connect(m_mainWindow, &MainWindow::quakeHidePlugin, this, [ = ]() { getEncodePanel()->hide(); }); } QAction *EncodePanelPlugin::titlebarMenu(MainWindow *mainWindow) { QAction *switchThemeAction(new QAction("Switch Encoding", mainWindow)); connect(switchThemeAction, &QAction::triggered, mainWindow, [mainWindow]() { mainWindow->showPlugin(MainWindow::PLUGIN_TYPE_ENCODING); }); return switchThemeAction; } EncodePanel *EncodePanelPlugin::getEncodePanel() { if (m_encodePanel == nullptr) { initEncodePanel(); } return m_encodePanel; } void EncodePanelPlugin::initEncodePanel() { m_encodePanel = new EncodePanel(m_mainWindow->centralWidget()); connect(Service::instance(), &Service::currentTermChange, m_encodePanel, [ = ](QWidget * term) { TermWidget *pterm = m_mainWindow->currentPage()->currentTerminal(); // 列表显示时,切换了当前终端 if (!m_encodePanel->isHidden() && pterm == term) { // 判断是否是当前页的term TermWidget *curterm = qobject_cast(term); setCurrentTermEncode(curterm); } }); } void EncodePanelPlugin::setCurrentTermEncode(TermWidget *term) { QString encode; if (term->isConnectRemote()) { encode = term->RemoteEncode(); // 远程编码 } else { encode = term->encode(); // 终端编码 } m_encodePanel->updateEncode(encode); } deepin-terminal-5.2.11/src/encodeplugin/encodepanelplugin.h000066400000000000000000000013411370157770500240000ustar00rootroot00000000000000#ifndef ENCODEPANELPLUGIN_H #define ENCODEPANELPLUGIN_H #include "mainwindowplugininterface.h" #include "encodepanel.h" #include "termwidget.h" #include //class EncodePanel; class MainWindow; class TermWidget; class EncodePanelPlugin : public MainWindowPluginInterface { Q_OBJECT public: EncodePanelPlugin(QObject *parent); void initPlugin(MainWindow *mainWindow) override; QAction *titlebarMenu(MainWindow *mainWindow) override; EncodePanel *getEncodePanel(); void initEncodePanel(); // 设置当前term编码 inline void setCurrentTermEncode(TermWidget *term); private: MainWindow *m_mainWindow = nullptr; EncodePanel *m_encodePanel = nullptr; }; #endif // THEMEPANELPLUGIN_H deepin-terminal-5.2.11/src/environments.h.in000066400000000000000000000001651370157770500207670ustar00rootroot00000000000000#ifndef __ENVIRONMENTS_H_ #define __ENVIRONMENTS_H_ #define VERSION "@VERSION@" #endif // __ENVIRONMENTS_H_ deepin-terminal-5.2.11/src/main/000077500000000000000000000000001370157770500164045ustar00rootroot00000000000000deepin-terminal-5.2.11/src/main/atspidesktop.cpp000066400000000000000000000042541370157770500216270ustar00rootroot00000000000000#include "atspidesktop.h" //qt #include AtspiDesktop::AtspiDesktop() { } /******************************************************************************* 1. @函数: stopThread 2. @作者: ut000610 戴正文 3. @日期: 2020-07-09 4. @说明: 负责退出spi事件循环 *******************************************************************************/ void AtspiDesktop::stopThread() { // 初始化为成功直接退出 if (!m_isLoop) { qDebug() << "AtspiDesktop thread atspi_event_main do not run"; return; } // 退出插件循环 atspi_event_quit(); // 加上会报错 // atspi_exit(); // 等待退出线程 quit(); wait(); qDebug() << "quit AtspiDesktop thread!"; m_isLoop = false; } /******************************************************************************* 1. @函数: on_event 2. @作者: ut000610 戴正文 3. @日期: 2020-07-09 4. @说明: 注册监听事件需要此函数 需要对g_object进行处理 *******************************************************************************/ void AtspiDesktop::on_event(AtspiEvent *event, void *data) { g_object_unref(event->source); g_free(event->type); g_value_unset(&event->any_data); g_free(event); Q_UNUSED(data); } void AtspiDesktop::run() { // 设置accessibility参数 char cmdGsettings[128] = "gsettings set org.gnome.desktop.interface toolkit-accessibility true"; if (0 == system(cmdGsettings)) { qDebug() << "exec:[gsettings set org.gnome.desktop.interface toolkit-accessibility true]success"; } else { qDebug() << "exec gsettings failed"; } int result = atspi_init(); qDebug() << "atspi_init result : " << result; if (result != 0) { // 初始化失败 qDebug() << "atspi_init failed : " << result; return; } AtspiEventListener *listener = atspi_event_listener_new(on_event, NULL, NULL); if (listener) { qDebug() << "object:state-changed:focused" << atspi_event_listener_register(listener, "object:state-changed:focused", NULL); m_isLoop = true; // 主循环 atspi_event_main(); } } deepin-terminal-5.2.11/src/main/atspidesktop.h000066400000000000000000000012361370157770500212710ustar00rootroot00000000000000#ifndef ATSPIDESKTOP_H #define ATSPIDESKTOP_H // qt #include // lib #include // 该类负责初始化qt-at-spi // 无障碍辅助工具 // 相关链接 : https://github.com/infapi00/at-spi2-examples/blob/master/c/notify-value-changes.c // qt-at-spi 快捷键映射依赖此库 让Qt可以识别ctrl + shift + ?快捷键 class AtspiDesktop : public QThread { Q_OBJECT public: AtspiDesktop(); void stopThread(); // 事件负责处理g_object static void on_event(AtspiEvent *event, void *data); protected: void run() override; private: // 是否进入循环 bool m_isLoop = false; }; #endif // ATSPIDESKTOP_H deepin-terminal-5.2.11/src/main/dbusmanager.cpp000066400000000000000000000205331370157770500214030ustar00rootroot00000000000000#include "dbusmanager.h" #include "utils.h" #include #include #include #include #include #include #include DBusManager::DBusManager() { } DBusManager::~DBusManager() { // 注销时结束连接dbus QDBusConnection conn = QDBusConnection::sessionBus(); if (conn.registerService(TERMINALSERVER)) { conn.unregisterService(TERMINALSERVER); qDebug() << "Terminal DBus disconnected!"; } } /******************************************************************************* 1. @函数: initDBus 2. @作者: ut000610 戴正文 3. @日期: 2020-05-19 4. @说明: deepin-terminal DBUS注册的统一接口 *******************************************************************************/ bool DBusManager::initDBus() { //用于雷神窗口通信的DBus QDBusConnection conn = QDBusConnection::sessionBus(); if (!conn.registerService(TERMINALSERVER)) { qDebug() << "Terminal DBus has connected!"; return false; } if (!conn.registerObject(TERMINALINTERFACE, this, QDBusConnection::ExportAllSlots)) { qDebug() << "Terminal DBus creates Object failed!"; return false; } return true; } /******************************************************************************* 1. @函数: callKDECurrentDesktop 2. @作者: ut000610 戴正文 3. @日期: 2020-05-15 4. @说明: 获取当前桌面index *******************************************************************************/ int DBusManager::callKDECurrentDesktop() { QDBusMessage msg = QDBusMessage::createMethodCall(KWinDBusService, KWinDBusPath, KWinDBusService, "currentDesktop"); QDBusMessage response = QDBusConnection::sessionBus().call(msg); if (response.type() == QDBusMessage::ReplyMessage) { qDebug() << "call currentDesktop Success!"; QList list = response.arguments(); return list.takeFirst().toInt(); } else { qDebug() << "call currentDesktop Fail!" << response.errorMessage(); return -1; } } /******************************************************************************* 1. @函数: callKDESetCurrentDesktop 2. @作者: ut000610 戴正文 3. @日期: 2020-05-15 4. @说明: 将桌面跳转到index所指桌面 *******************************************************************************/ void DBusManager::callKDESetCurrentDesktop(int index) { QDBusMessage msg = QDBusMessage::createMethodCall(KWinDBusService, KWinDBusPath, KWinDBusService, "setCurrentDesktop"); msg << index; QDBusMessage response = QDBusConnection::sessionBus().call(msg); if (response.type() == QDBusMessage::ReplyMessage) { qDebug() << "call setCurrentDesktop Success!"; } else { qDebug() << "call setCurrentDesktop Fail!" << response.errorMessage(); } } /******************************************************************************* 1. @函数: callAppearanceFont 2. @作者: ut000610 戴正文 3. @日期: 2020-06-09 4. @说明: 获取字体列表,输入参数后获取得到的参数列表 参数 : fontType : standardfont 标准字体 monospacefont 等宽字体 *******************************************************************************/ QStringList DBusManager::callAppearanceFont(QString fontType) { QStringList fontList; QDBusMessage msg = QDBusMessage::createMethodCall(AppearanceService, AppearancePath, AppearanceService, "List"); msg << fontType; QDBusMessage response = QDBusConnection::sessionBus().call(msg); if (response.type() == QDBusMessage::ReplyMessage) { qDebug() << "call List Success!"; QList list = response.arguments(); QString fonts = list.takeFirst().toString(); // 原本的返回值为QDBusPendingReply => QString fonts.replace("[", ""); fonts.replace("]", ""); fonts.replace("\"", ""); // 用逗号分隔 fontList = fonts.split(","); // for (QString font : fontList) { // qDebug() << fontType << " : " << font; // } fontList = callAppearanceShowFont(fontList, fontType); } else { qDebug() << "call List Fail!" << response.errorMessage(); } return fontList; } /******** Add by ut001000 renfeixiang 2020-06-16:增加 调用DBUS的show获取的等宽字体,并转换成QStringList Begin***************/ //将QJsonArray文件转换成QStringList QStringList DBusManager::converToList(const QString &type, const QJsonArray &array) { QStringList list; for (int i = 0; i != array.size(); i++) { QJsonObject object = array.at(i).toObject(); object.insert("type", QJsonValue(type)); list.append(object["Name"].toString()); } return list; } //调用DBUS的SHow方法 QStringList DBusManager::callAppearanceShowFont(QStringList fontList, QString fontType) { QStringList List; QDBusMessage msg = QDBusMessage::createMethodCall(AppearanceService, AppearancePath, AppearanceService, "Show"); msg << fontType << fontList; QDBusMessage response = QDBusConnection::sessionBus().call(msg); if (response.type() == QDBusMessage::ReplyMessage) { qDebug() << "call Show Success!"; QList list = response.arguments(); QString fonts = list.takeFirst().toString(); QJsonArray array = QJsonDocument::fromJson(fonts.toLocal8Bit().data()).array(); List = converToList(fontType, array); qDebug() << "Show value" << List; } else { qDebug() << "call Show Fail!" << response.errorMessage(); } return List; } /******** Add by ut001000 renfeixiang 2020-06-16:增加 调用DBUS的show获取的等宽字体,并转换成QStringList End***************/ bool DBusManager::callCreateRequest() { QDBusMessage msg = QDBusMessage::createMethodCall(TERMINALSERVER, TERMINALINTERFACE, TERMINALSERVER, "createRequest"); QDBusMessage response = QDBusConnection::sessionBus().call(msg, QDBus::AutoDetect); if (response.type() == QDBusMessage::ReplyMessage) { QList list = response.arguments(); qDebug() << "call createRequest Success!" << list.takeFirst().toBool(); return list.takeFirst().toBool(); } else { qDebug() << "call createRequest!" << response.errorMessage(); return false; } } /******************************************************************************* 1. @函数: callTerminalEntry 2. @作者: ut000610 戴正文 3. @日期: 2020-05-19 4. @说明: 调用主进程的创建或显示窗口入口 *******************************************************************************/ void DBusManager::callTerminalEntry(QStringList args) { QDBusMessage msg = QDBusMessage::createMethodCall(TERMINALSERVER, TERMINALINTERFACE, TERMINALSERVER, "entry"); msg << args; QDBusMessage response = QDBusConnection::sessionBus().call(msg, QDBus::NoBlock); if (response.type() == QDBusMessage::ReplyMessage) { qDebug() << "call callTerminalEntry Success!"; } else { qDebug() << "call callTerminalEntry!" << response.errorMessage(); } } /******************************************************************************* 1. @函数: entry 2. @作者: ut000610 戴正文 3. @日期: 2020-05-19 4. @说明: dbus上开放的槽函数,用于调用service的Entry接口 *******************************************************************************/ void DBusManager::entry(QStringList args) { qDebug() << "recv args" << args; emit entryArgs(args); } /******************************************************************************* 1. @函数: createRequest 2. @作者: ut000610 戴正文 3. @日期: 2020-06-11 4. @说明: 判断当前是否允许创建窗口 true 允许 false 不允许 返回true需要将他置为false,阻止其他窗口创建 用于新建窗口 *******************************************************************************/ bool DBusManager::createRequest() { bool result = Service::instance()->getEnable(); if (result) { // 允许当前请求创建,阻止其他窗口创建 Service::instance()->setMemoryEnable(false); } qDebug() << "create enable " << result; return result; } deepin-terminal-5.2.11/src/main/dbusmanager.h000066400000000000000000000033461370157770500210530ustar00rootroot00000000000000#ifndef DBUSMANAGER_H #define DBUSMANAGER_H #include "service.h" #include #include #include // deepin-terminal #define TERMINALSERVER "com.deepin.terminal.reborn" #define TERMINALINTERFACE "/window" // kwin dbus #define KWinDBusService "org.kde.KWin" #define KWinDBusPath "/KWin" // deepin Appearance #define AppearanceService "com.deepin.daemon.Appearance" #define AppearancePath "/com/deepin/daemon/Appearance" class DBusManager : public QObject { Q_OBJECT Q_CLASSINFO("D-Bus Interface", TERMINALSERVER) public: DBusManager(); ~DBusManager(); // 初始化terminal相关dbus bool initDBus(); // kwin dbus static int callKDECurrentDesktop(); static void callKDESetCurrentDesktop(int index); // Appearance static QStringList callAppearanceFont(QString fontType); /******** Add by ut001000 renfeixiang 2020-06-16:增加 调用DBUS的show获取的等宽字体,并转换成QStringList Begin***************/ //将QJsonArray文件转换成QStringList static QStringList converToList(const QString &type, const QJsonArray &array); //调用DBUS的SHow方法 static QStringList callAppearanceShowFont(QStringList fontList, QString fontType); /******** Add by ut001000 renfeixiang 2020-06-16:增加 调用DBUS的show获取的等宽字体,并转换成QStringList End***************/ // deepin terminal // 获取能否创建窗口的状态值 static bool callCreateRequest(); // 创建窗口 static void callTerminalEntry(QStringList args); public slots: void entry(QStringList args); // 获取状态值 bool createRequest(); signals: // To Service entry function void entryArgs(QStringList args); }; #endif // DBUSMANAGER_H deepin-terminal-5.2.11/src/main/dterminalsingleapplication.cpp000066400000000000000000000065621370157770500245260ustar00rootroot00000000000000#include "dterminalsingleapplication.h" #include "mainwindow.h" #include DTerminalSingleApplication::DTerminalSingleApplication(int &argc, char *argv[], const QString uniqueKey) : DApplication(argc, argv), _uniqueKey(uniqueKey) { sharedMemory.setKey(_uniqueKey); if (sharedMemory.attach()) { _isRunning = true; } else { _isRunning = false; // create shared memory. if (!sharedMemory.create(1)) { qDebug("Unable to create single instance."); return; } // create local server and listen to incomming messages from other instances. localServer = new QLocalServer(this); connect(localServer, SIGNAL(newConnection()), this, SLOT(receiveMessage())); localServer->listen(_uniqueKey); } } //fix bug 22670 bool DTerminalSingleApplication::isRunning() { DTerminalSingleApplication *dApp = (static_cast(QCoreApplication::instance())); QString cachePath = QStandardPaths::standardLocations(QStandardPaths::CacheLocation).at(0); QFile processFile(QString("%1/%2").arg(cachePath).arg("process.pid")); if (processFile.exists()) { if (processFile.open(QIODevice::ReadWrite)) { int historyId = processFile.readAll().toInt(); QDir hisProcessDir(QString("/proc/%1").arg(historyId)); processFile.close(); // use /proc/pid to judge process running state if (hisProcessDir.exists()) { return true; } if (processFile.open(QIODevice::ReadWrite | QIODevice::Truncate)) { QTextStream pidInfo(&processFile); pidInfo << dApp->applicationPid(); processFile.close(); } else { qDebug() << "process File open failed!"; } } } else { if (processFile.open(QIODevice::WriteOnly | QIODevice::Text)) { QTextStream pidInfo(&processFile); pidInfo << dApp->applicationPid(); processFile.close(); } else { qDebug() << "process File open failed!"; } } return false; } // public slots. void DTerminalSingleApplication::receiveMessage() { QLocalSocket *localSocket = localServer->nextPendingConnection(); if (!localSocket->waitForReadyRead(timeout)) { qDebug(localSocket->errorString().toLatin1()); return; } QByteArray byteArray = localSocket->readAll(); QString message = QString::fromUtf8(byteArray.constData()); emit messageAvailable(message); localSocket->disconnectFromServer(); } bool DTerminalSingleApplication::sendMessage(const QString &message) { if (!_isRunning) { return false; } QLocalSocket localSocket(this); localSocket.connectToServer(_uniqueKey, QIODevice::WriteOnly); if (!localSocket.waitForConnected(timeout)) { qDebug(localSocket.errorString().toLatin1()); return false; } localSocket.write(message.toUtf8()); if (!localSocket.waitForBytesWritten(timeout)) { qDebug(localSocket.errorString().toLatin1()); return false; } localSocket.disconnectFromServer(); return true; } void DTerminalSingleApplication::handleQuitAction() { foreach (MainWindow *window, MainWindow::getWindowList()) { window->close(); } } deepin-terminal-5.2.11/src/main/dterminalsingleapplication.h000066400000000000000000000013501370157770500241610ustar00rootroot00000000000000#ifndef DTERMINALSINGLEAPPLICATION_H #define DTERMINALSINGLEAPPLICATION_H #include #include #include DWIDGET_USE_NAMESPACE class DTerminalSingleApplication : public DApplication { Q_OBJECT public: DTerminalSingleApplication(int &argc, char *argv[], const QString uniqueKey); bool isRunning(); bool sendMessage(const QString &message); protected: void handleQuitAction() override; public slots: void receiveMessage(); signals: void messageAvailable(QString message); private: bool _isRunning; QString _uniqueKey; QSharedMemory sharedMemory; QLocalServer *localServer; static const int timeout = 1000; }; #endif // DTERMINALSINGLEAPPLICATION_H deepin-terminal-5.2.11/src/main/main.cpp000066400000000000000000000101211370157770500200270ustar00rootroot00000000000000#include "mainwindow.h" #include "termargumentparser.h" #include "termproperties.h" #include "environments.h" #include "dbusmanager.h" #include "service.h" #include "utils.h" #include "terminalapplication.h" #include #include #include #include #include #include #include DWIDGET_USE_NAMESPACE /******** Modify by n014361 wangpeili 2020-01-10:增加日志需要 ***********×****/ DCORE_USE_NAMESPACE /********************* Modify by n014361 wangpeili End ************************/ int main(int argc, char *argv[]) { //计时 qint64 starttime = QDateTime::currentMSecsSinceEpoch(); DApplication::loadDXcbPlugin(); //DApplication app(argc, argv); TerminalApplication app(argc, argv); app.loadTranslator(); app.setOrganizationName("deepin"); app.setOrganizationDomain("deepin.org"); app.setApplicationVersion(VERSION); app.setApplicationName("deepin-terminal"); app.setApplicationDisplayName(QObject::tr("Terminal")); app.setAttribute(Qt::AA_UseHighDpiPixmaps, true); app.setProductIcon(QIcon::fromTheme("deepin-terminal")); /***add by ut001121 zhangmeng 20200617 禁用应用程序自动退出 修复BUG33541***/ app.setQuitOnLastWindowClosed(false); QString appDesc = QObject::tr("Terminal is an advanced terminal emulator with workspace" ", multiple windows, remote management, quake mode and other features."); app.setApplicationDescription(appDesc); DApplicationSettings set(&app); #ifdef QT_DEBUG QTranslator translator; translator.load(QString("deepin-terminal_%1").arg(QLocale::system().name())); app.installTranslator(&translator); #endif // QT_DEBUG /******** Modify by n014361 wangpeili 2020-01-10: 增加日志 ***********×****/ DLogManager::registerConsoleAppender(); DLogManager::registerFileAppender(); /********************* Modify by n014361 wangpeili End *****************/ // 参数解析 TermProperties Properties; Utils::parseCommandLine(app.arguments(), Properties, true); DBusManager manager; if (!manager.initDBus()) { // 初始化失败,则已经注册过dbus // 判断是否能创建新的的窗口 // 不是雷神且正在创建 if (!Properties[QuakeMode].toBool() && !Service::instance()->getEnable()) { qint64 endtime = QDateTime::currentMSecsSinceEpoch(); qDebug() << "[sub app] Server can't create, drop this create request! time use " << endtime - starttime <<"ms"; return 0; } // 调用entry接口 /******** Modify by ut000610 daizhengwen 2020-05-25: 在终端中打开****************/ QStringList args = app.arguments(); bool isCurrentPaht = false; for (QString &arg : args) { // 若已有-w和--work-directory参数,直接将参数传给主进程执行 if (arg == "-w" || arg == "--work-directory") { isCurrentPaht = true; break; } } if (!isCurrentPaht) { args += "-w"; args += QDir::currentPath(); } /********************* Modify by ut000610 daizhengwen End ************************/ qDebug() << "[sub app] start to call main terminal entry! app args " << args; DBusManager::callTerminalEntry(args); qint64 endtime2 = QDateTime::currentMSecsSinceEpoch(); qDebug() << "[sub app] task complete! sub app quit, time use " << endtime2 - starttime<<"ms"; return 0; } // 这行不要删除 qputenv("TERM", "xterm-256color"); // 主进程 Service *service = Service::instance(); service->connect(&manager, &DBusManager::entryArgs, service, &Service::Entry); // 初始化数据 service->init(); // 创建窗口 service->Entry(app.arguments()); qint64 endtime3 = QDateTime::currentMSecsSinceEpoch(); qDebug() << "First Terminal Window create complete! time use " << endtime3 - starttime <<"ms"; return app.exec(); } deepin-terminal-5.2.11/src/main/mainwindow.cpp000066400000000000000000002213351370157770500212720ustar00rootroot00000000000000#include "mainwindow.h" #include "mainwindowplugininterface.h" #include "settings.h" #include "shortcutmanager.h" #include "tabbar.h" #include "termproperties.h" #include "termwidgetpage.h" #include "termwidget.h" #include "titlebar.h" #include "operationconfirmdlg.h" #include "encodepanelplugin.h" #include "customcommandplugin.h" #include "serverconfigmanager.h" #include "utils.h" #include "dbusmanager.h" #include "windowsmanager.h" #include "service.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include using std::ifstream; using std::ofstream; DWIDGET_USE_NAMESPACE MainWindow::MainWindow(TermProperties properties, QWidget *parent) : DMainWindow(parent), m_menu(new QMenu(this)), m_tabbar(nullptr), m_centralWidget(new QWidget(this)), m_centralLayout(new QVBoxLayout(m_centralWidget)), m_termStackWidget(new QStackedWidget), m_properties(properties), m_isQuakeWindow(properties[QuakeMode].toBool()), m_winInfoConfig(new QSettings(getWinInfoConfigPath(), QSettings::IniFormat, this)) { } void MainWindow::initUI() { initWindow(); // Plugin may need centralWidget() to work so make sure initPlugin() is after setCentralWidget() // Other place (eg. create titlebar menu) will call plugin method so we should create plugins before init other // parts. initPlugins(); initTabBar(); initTitleBar(); initWindowAttribute(); qApp->installEventFilter(this); } void MainWindow::initWindow() { setAttribute(Qt::WA_TranslucentBackground); setMinimumSize(m_MinWidth, m_MinHeight); setEnableBlurWindow(Settings::instance()->backgroundBlur()); setWindowIcon(QIcon::fromTheme("deepin-terminal")); // Init layout m_centralLayout->setMargin(0); m_centralLayout->setSpacing(0); m_centralLayout->addWidget(m_termStackWidget); setCentralWidget(m_centralWidget); } void MainWindow::initTabBar() { m_tabbar = new TabBar(this); m_tabbar->setFocusPolicy(Qt::NoFocus); connect(m_tabbar, &DTabBar::tabBarClicked, this, [ = ](int index) { TermWidgetPage *tabPage = qobject_cast(m_termStackWidget->widget(index)); TermWidget *term = tabPage->currentTerminal(); bool bIdle = !(term->hasRunningProcess()); int currSessionId = term->getSessionId(); if (bIdle && isTabChangeColor(currSessionId)) { m_tabVisitMap.insert(currSessionId, true); m_tabChangeColorMap.insert(currSessionId, false); m_tabbar->removeNeedChangeTextColor(index); } }); // 点击TAB上页触发 connect(m_tabbar, &DTabBar::currentChanged, this, [this](int index) { focusPage(m_tabbar->identifier(index)); }, Qt::QueuedConnection); // 点击TAB上的"+"触发 connect(m_tabbar, &DTabBar::tabAddRequested, this, [this]() { createNewWorkspace(); }, Qt::QueuedConnection); // 点击TAB上的"X"触发 connect(m_tabbar, &DTabBar::tabCloseRequested, this, [this](int index) { closeTab(m_tabbar->identifier(index)); }, Qt::QueuedConnection); // TAB菜单发来的关闭请求 connect(m_tabbar, &TabBar::menuCloseTab, this, [ = ](QString Identifier) { closeTab(Identifier); return; }); // TAB菜单发来的关闭其它窗口请求,需要逐一关闭 connect(m_tabbar, &TabBar::menuCloseOtherTab, this, [ = ](QString Identifier) { closeOtherTab(Identifier); return; }); addTab(m_properties); } /******************************************************************************* 1. @函数: initOptionButton 2. @作者: n014361 王培利 3. @日期: 2020-04-22 4. @说明: 普通模式下,option button需要在全屏时切换控件 *******************************************************************************/ void MainWindow::initOptionButton() { // 全屏退出按钮 // DTK的全屏按钮不能满足UI要求,隐去DTK最右侧的全屏 QWidget *dtkbutton = titlebar()->findChild("DTitlebarDWindowQuitFullscreenButton"); if (dtkbutton) { dtkbutton->hide(); } m_exitFullScreen = new DToolButton(this); m_exitFullScreen->setCheckable(false); m_exitFullScreen->setIcon(QIcon::fromTheme("dt_exit_fullscreen")); m_exitFullScreen->setIconSize(QSize(36, 36)); m_exitFullScreen->setFixedSize(QSize(36, 36)); titlebar()->addWidget(m_exitFullScreen, Qt::AlignRight | Qt::AlignHCenter); m_exitFullScreen->setVisible(false); connect(m_exitFullScreen, &DPushButton::clicked, this, [this]() { switchFullscreen(); }); // option button DIconButton *optionBtn = titlebar()->findChild("DTitlebarDWindowOptionButton"); if (optionBtn != nullptr) { optionBtn->setFocusPolicy(Qt::NoFocus); // mainwindow的设置按钮触发 connect(titlebar()->findChild("DTitlebarDWindowOptionButton"), &DIconButton::pressed, this, [this]() { showPlugin(PLUGIN_TYPE_NONE); // 判断是否超过最大数量限制 QList actionList = m_menu->actions(); for (auto item : actionList) { if (item->text() == tr("New window")) { // 菜单根据数量自动设置true or false item->setEnabled(Service::instance()->isCountEnable()); } } }); } } /******************************************************************************* 1. @函数: initOptionMenu 2. @作者: n014361 王培利 3. @日期: 2020-04-22 4. @说明: option menu初始化 *******************************************************************************/ void MainWindow::initOptionMenu() { titlebar()->setMenu(m_menu); /******** Modify by m000714 daizhengwen 2020-04-03: 新建窗口****************/ QAction *newWindowAction(new QAction(tr("New window"), this)); connect(newWindowAction, &QAction::triggered, this, [this]() { qDebug() << "menu click new window"; TermWidgetPage *tabPage = currentPage(); TermWidget *term = tabPage->currentTerminal(); QString currWorkingDir = term->workingDirectory(); emit newWindowRequest(currWorkingDir); }); m_menu->addAction(newWindowAction); /********************* Modify by m000714 daizhengwen End ************************/ for (auto &plugin : m_plugins) { QAction *pluginMenu = plugin->titlebarMenu(this); // 取消Encoding插件的菜单展示 if (plugin->getPluginName() == PLUGIN_TYPE_ENCODING) { continue; } if (pluginMenu) { m_menu->addAction(pluginMenu); } } QAction *settingAction(new QAction(tr("Settings"), this)); m_menu->addAction(settingAction); m_menu->addSeparator(); connect(settingAction, &QAction::triggered, Service::instance(), [ = ] { Service::instance()->showSettingDialog(this); }); } void MainWindow::initPlugins() { // Todo: real plugin loader and plugin support. // ThemePanelPlugin *testPlugin = new ThemePanelPlugin(this); // testPlugin->initPlugin(this); EncodePanelPlugin *encodePlugin = new EncodePanelPlugin(this); encodePlugin->initPlugin(this); customCommandPlugin = new CustomCommandPlugin(this); customCommandPlugin->initPlugin(this); remoteManagPlugin = new RemoteManagementPlugn(this); remoteManagPlugin->initPlugin(this); m_plugins.append(encodePlugin); m_plugins.append(customCommandPlugin); m_plugins.append(remoteManagPlugin); } MainWindow::~MainWindow() { } /******************************************************************************* 1. @函数: setDefaultLocation 2. @作者: n014361 王培利 3. @日期: 2020-04-22 4. @说明: 设置默认位置,最大化,全屏还原使用 *******************************************************************************/ void MainWindow::setDefaultLocation() { resize(QSize(1000, 600)); singleFlagMove(); } /******************************************************************************* 1. @函数: singleFlagMove 2. @作者: ut000439 王培利 3. @日期: 2020-06-02 4. @说明: 首个普通窗口,需要居中显示 *******************************************************************************/ void MainWindow::singleFlagMove() { if (m_properties[SingleFlag].toBool()) { Dtk::Widget::moveToCenter(this); qDebug() << "SingleFlag move" ; } } bool MainWindow::isTabVisited(int tabSessionId) { return m_tabVisitMap.value(tabSessionId); } bool MainWindow::isTabChangeColor(int tabSessionId) { return m_tabChangeColorMap.value(tabSessionId); } void MainWindow::addTab(TermProperties properties, bool activeTab) { /***add by ut001121 zhangmeng 修复BUG#24452 点击“+”按钮新建工作区,自定义命令/编码/远程管理插件未消失***/ showPlugin(PLUGIN_TYPE_NONE); if (WindowsManager::instance()->widgetCount() >= MAXWIDGETCOUNT) { // 没有雷神,且是雷神让通过,不然不让通过 if (!(nullptr == WindowsManager::instance()->getQuakeWindow() && m_isQuakeWindow)) { // 非雷神窗口不得超过MAXWIDGETCOUNT qDebug() << "addTab failed, can't create number more than " << MAXWIDGETCOUNT; return; } } TermWidgetPage *termPage = new TermWidgetPage(properties, this); setNewTermPage(termPage, activeTab); // pageID存在 tab中,所以page增删改操作都要由tab发起。 int index = m_tabbar->addTab(termPage->identifier(), m_tabbar->tabText(m_tabbar->currentIndex())); qDebug() << "addTab index" << index; if (activeTab) { m_tabbar->setCurrentIndex(index); m_tabbar->removeNeedChangeTextColor(index); } TermWidget *term = termPage->currentTerminal(); m_tabbar->saveSessionIdWithTabIndex(term->getSessionId(), index); m_tabbar->saveSessionIdWithTabId(term->getSessionId(), termPage->identifier()); connect(termPage, &TermWidgetPage::termTitleChanged, this, &MainWindow::onTermTitleChanged); connect(termPage, &TermWidgetPage::tabTitleChanged, this, &MainWindow::onTabTitleChanged); connect(termPage, &TermWidgetPage::lastTermClosed, this, [this](const QString & identifier) { closeTab(identifier); }); /******** Modify by m000714 daizhengwen 2020-03-31: 避免多次菜单弹出****************/ // 菜单弹出在时间过滤器获取,不需要从terminal事件中获取 // connect(termPage, &TermWidgetPage::termGetFocus, this, [ = ]() { // showPlugin(PLUGIN_TYPE_NONE); // }); /********************* Modify by m000714 daizhengwen End ************************/ connect(this, &MainWindow::showPluginChanged, termPage, [ = ](const QString name) { termPage->showSearchBar(PLUGIN_TYPE_SEARCHBAR == name && (this->currentPage() == termPage)); }); connect(termPage->currentTerminal(), &TermWidget::termIsIdle, this, [ = ](int currSessionId, bool bIdle) { int tabIndex = m_tabbar->queryIndexBySessionId(currSessionId); //如果标签被点过,移除标签颜色 if (isTabVisited(currSessionId) && bIdle) { m_tabVisitMap.insert(currSessionId, false); m_tabChangeColorMap.insert(currSessionId, false); m_tabbar->removeNeedChangeTextColor(tabIndex); return; } if (bIdle) { //空闲状态如果标签被标记变色,则改变标签颜色 if (m_tabbar->isNeedChangeTextColor(tabIndex)) { m_tabChangeColorMap.insert(currSessionId, true); m_tabbar->setChangeTextColor(tabIndex); } } else { //如果当前标签是活动标签,移除变色请求 int activeTabIndex = m_tabbar->currentIndex(); if (activeTabIndex == tabIndex) { m_tabVisitMap.insert(currSessionId, false); m_tabChangeColorMap.insert(currSessionId, false); m_tabbar->removeNeedChangeTextColor(tabIndex); return; } //标记变色,发起请求,稍后等空闲状态变色 m_tabChangeColorMap.insert(currSessionId, false); DGuiApplicationHelper *appHelper = DGuiApplicationHelper::instance(); DPalette pa = appHelper->standardPalette(appHelper->themeType()); m_tabbar->setNeedChangeTextColor(tabIndex, pa.color(DPalette::Highlight)); } }); } bool MainWindow::hasRunningProcesses() { for (int i = 0, count = m_termStackWidget->count(); i < count; i++) { TermWidgetPage *tabPage = qobject_cast(m_termStackWidget->widget(i)); /******** Modify by nt001000 renfeixiang 2020-05-28:修改 判断当前tab中是否有其它分屏正在执行 bug#28910 Begin***************/ //没有校验当前tab中是否有其它正在执行的分屏 //TermWidget *term = tabPage->currentTerminal(); if (tabPage->runningTerminalCount() != 0) { /******** Modify by nt001000 renfeixiang 2020-05-28:修改 判断当前tab中是否有其它分屏正在执行 End***************/ qDebug() << "here are processes running in this terminal tab... " << tabPage->identifier() << endl; return true; } else { qDebug() << "no processes running in this terminal tab... " << tabPage->identifier() << endl; } } return false; } /******************************************************************************* 1. @函数: closeTab 2. @作者: n014361 王培利 3. @日期: 2020-05-07 4. @说明: 一个tab只提示一次, 检测后需要重入,hasCheck=true 或者不需要提示,hasCheck=true即可 *******************************************************************************/ void MainWindow::closeTab(const QString &identifier, bool hasConfirmed) { /***add by ut001121 zhangmeng 20200508 修复BUG#24457 点击标签栏“x”按钮,右键菜单关闭工作区,关闭其它工作区,自定义命令/编码/远程管理插件未消失***/ showPlugin(PLUGIN_TYPE_NONE); TermWidgetPage *tabPage = getPageByIdentifier(identifier); if (tabPage == nullptr) { return; } // 关闭前必须要切换过去先 if (m_tabbar->currentIndex() != m_tabbar->getIndexByIdentifier(identifier)) { m_tabbar->setCurrentIndex(m_tabbar->getIndexByIdentifier(identifier)); } // 默认每个窗口关闭都提示一次. if (!hasConfirmed && tabPage->runningTerminalCount() != 0) { showExitConfirmDialog(Utils::CloseType_Tab, tabPage->runningTerminalCount(), this); return; } qDebug() << "Tab closed" << identifier; int currSessionId = tabPage->currentTerminal()->getSessionId(); m_tabVisitMap.remove(currSessionId); m_tabChangeColorMap.remove(currSessionId); m_tabbar->removeTab(identifier); m_termStackWidget->removeWidget(tabPage); tabPage->deleteLater(); if (m_tabbar->count() != 0) { updateTabStatus(); focusCurrentPage(); return; } qDebug() << "mainwindow close"; close(); } void MainWindow::updateTabStatus() { for (int i = 0; i < m_tabbar->count(); i++) { TermWidgetPage *tabPage = qobject_cast(m_termStackWidget->widget(i)); TermWidget *term = tabPage->currentTerminal(); bool bIdle = !(term->hasRunningProcess()); int currSessionId = term->getSessionId(); if (bIdle) { if (isTabVisited(currSessionId)) { m_tabVisitMap.insert(currSessionId, false); m_tabChangeColorMap.insert(currSessionId, false); m_tabbar->removeNeedChangeTextColor(i); } else if (isTabChangeColor(currSessionId)) { m_tabbar->setChangeTextColor(i); } else { m_tabbar->removeNeedChangeTextColor(i); } } else { m_tabbar->removeNeedChangeTextColor(i); } } } QString MainWindow::getCurrTabTitle() { return m_tabbar->tabText(m_tabbar->currentIndex()); } /******************************************************************************* 1. @函数: closeOtherTab 2. @作者: n014361 王培利 3. @日期: 2020-05-07 4. @说明: 关闭其它窗口 *******************************************************************************/ void MainWindow::closeOtherTab(const QString &identifier, bool hasConfirmed) { int runningCount = 0; QList closeTabIdList; for (int i = 0, count = m_termStackWidget->count(); i < count; i++) { TermWidgetPage *tabPage = qobject_cast(m_termStackWidget->widget(i)); if (tabPage && tabPage->identifier() != identifier) { closeTabIdList.append(tabPage->identifier()); runningCount += tabPage->runningTerminalCount(); } } if (!hasConfirmed && runningCount != 0) { // 全部关闭时,仅提示一次. showExitConfirmDialog(Utils::CloseType_OtherTab, runningCount, this); return; } // 关闭其它窗口,需要检测 for (QString &id : closeTabIdList) { closeTab(id, true); qDebug() << " close" << id; } //如果是不关闭当前页的,最后回到当前页来. m_tabbar->setCurrentIndex(m_tabbar->getIndexByIdentifier(identifier)); return; } /******************************************************************************* 1. @函数: closeOtherTab 2. @作者: n014361 王培利 3. @日期: 2020-01-10 4. @说明: 关闭所有标签页功能 *******************************************************************************/ void MainWindow::closeAllTab() { QList closeTabIdList; for (int i = 0, count = m_termStackWidget->count(); i < count; i++) { TermWidgetPage *tabPage = qobject_cast(m_termStackWidget->widget(i)); closeTabIdList.append(tabPage->identifier()); } // 全部关闭时,不再检测了, for (QString &id : closeTabIdList) { closeTab(id, true); qDebug() << " close" << id; } return; } void MainWindow::showExitConfirmDialog(Utils::CloseType type, int count, QWidget *parent) { // count < 1 不提示 if (count < 1) { return; } QString title; QString txt; Utils::CloseType temtype = type; // 关闭窗口的时候,如果只有一个tab,提示的内容要为终端. if (type == Utils::CloseType_Window && m_tabbar->count() == 1) { temtype = Utils::CloseType_Terminal; } Utils::getExitDialogText(temtype, title, txt, count); // 有弹窗显示 Service::instance()->setIsDialogShow(this, true); DDialog *dlg = new DDialog(title, txt, parent); dlg->setIcon(QIcon::fromTheme("deepin-terminal")); dlg->addButton(QString(tr("Cancel")), false, DDialog::ButtonNormal); /******** Modify by nt001000 renfeixiang 2020-05-21:修改Exit成Close Begin***************/ dlg->addButton(QString(tr("Close")), true, DDialog::ButtonWarning); /******** Modify by nt001000 renfeixiang 2020-05-21:修改Exit成Close End***************/ dlg->setWindowModality(Qt::WindowModal); dlg->setAttribute(Qt::WA_DeleteOnClose); dlg->show(); dlg->setProperty("type", type); /******** Modify by ut001000 renfeixiang 2020-06-03:修改 将dlg的槽函数修改为OnHandleCloseType,处理全部在OnHandleCloseType函数中 Begin***************/ connect(dlg, &DDialog::finished, this, [this](int result) { OnHandleCloseType(result, Utils::CloseType(qobject_cast(sender())->property("type").toInt())); }); /******** Modify by ut001000 renfeixiang 2020-06-03:修改 将dlg的槽函数修改为OnHandleCloseType,处理全部在OnHandleCloseType函数中 End***************/ // if (type == Utils::CloseType_Window) { // connect(dlg, &DDialog::finished, this, [this](int result) { // qDebug() << result; // //setEnabled(true); // // 弹窗隐藏或消失 // Service::instance()->setIsDialogShow(this, false); // if (result == 1) { // //接口二次重入 // m_hasConfirmedClose = true; // close(); // } // }); // } // if (type == Utils::CloseType_Tab) { // connect(dlg, &DDialog::finished, this, [this](int result) { // qDebug() << result; // //setEnabled(true); // // 弹窗隐藏或消失 // Service::instance()->setIsDialogShow(this, false); // if (result == 1) { // TermWidgetPage *page = currentPage(); // if (page) { // //接口二次重入 // closeTab(page->identifier(), true); // } // } // }); // } // if (type == Utils::CloseType_OtherTab) { // connect(dlg, &DDialog::finished, this, [this](int result) { // qDebug() << result; // //setEnabled(true); // // 弹窗隐藏或消失 // Service::instance()->setIsDialogShow(this, false); // if (result == 1) { // TermWidgetPage *page = currentPage(); // if (page) { // //接口二次重入 // closeOtherTab(page->identifier(), true); // } // } // }); // } //while (1) { // QCoreApplication::processEvents(QEventLoop::ExcludeUserInputEvents); //} //bool result = (dlg->exec() == DDialog::Accepted); //qDebug()<<"receive result = "<setCurrentWidget(tabPage); tabPage->focusCurrentTerm(); return; } qDebug() << "focusTab nullptr identifier" << identifier; } void MainWindow::focusCurrentPage() { focusPage(m_tabbar->identifier(m_tabbar->currentIndex())); } TermWidgetPage *MainWindow::currentPage() { return qobject_cast(m_termStackWidget->currentWidget()); } TermWidgetPage *MainWindow::getPageByIdentifier(const QString &identifier) { for (int i = 0, count = m_termStackWidget->count(); i < count; i++) { TermWidgetPage *tabPage = qobject_cast(m_termStackWidget->widget(i)); if (tabPage && tabPage->identifier() == identifier) { return tabPage; } } qDebug() << "getPageByIdentifier nullptr identifier" << identifier; return nullptr; } void MainWindow::forAllTabPage(const std::function &func) { for (int i = 0, count = m_termStackWidget->count(); i < count; i++) { TermWidgetPage *tabPage = qobject_cast(m_termStackWidget->widget(i)); if (tabPage) { func(tabPage); } } } void MainWindow::resizeEvent(QResizeEvent *event) { // 保存窗口位置 saveWindowSize(); // 通知隐藏插件 hidePlugin(); DMainWindow::resizeEvent(event); } void MainWindow::closeEvent(QCloseEvent *event) { saveWindowSize(); // 注销和关机时不需要确认了 if (qApp->isSavingSession()) { DMainWindow::closeEvent(event); } // 一页一页退出,当全部退出以后,mainwindow自然关闭. event->ignore(); int runningCount = 0; QList closeTabIdList; for (int i = 0, count = m_termStackWidget->count(); i < count; i++) { TermWidgetPage *tabPage = qobject_cast(m_termStackWidget->widget(i)); closeTabIdList.append(tabPage->identifier()); runningCount += tabPage->runningTerminalCount(); } if (!m_hasConfirmedClose && runningCount != 0) { // 如果不能马上关闭,并且还在没有最小化. if (runningCount != 0 && isMinimized()) { qDebug() << "isMinimized........... " << endl; setWindowState((windowState() & ~Qt::WindowMinimized) | Qt::WindowActive); } // 全部关闭时,仅提示一次. showExitConfirmDialog(Utils::CloseType_Window, runningCount, this); return; } closeAllTab(); if (m_tabbar->count() == 0) { DMainWindow::closeEvent(event); emit mainwindowClosed(this); } } /******************************************************************************* 1. @函数: closeConfirm 2. @作者: n014361 王培利 3. @日期: 2020-04-29 4. @说明: mainwindow关闭确认        当前方案为一页一页确认 *******************************************************************************/ bool MainWindow::closeConfirm() { int runningCount = 0; QList closeTabIdList; for (int i = 0, count = m_termStackWidget->count(); i < count; i++) { TermWidgetPage *tabPage = qobject_cast(m_termStackWidget->widget(i)); closeTabIdList.append(tabPage->identifier()); runningCount += tabPage->runningTerminalCount(); } // 如果不能马上关闭,并且还在没有最小化. if (runningCount != 0 && isMinimized()) { qDebug() << "isMinimized........... " << endl; setWindowState((windowState() & ~Qt::WindowMinimized) | Qt::WindowActive); } if (runningCount != 0) { // 全部关闭时,仅提示一次. showExitConfirmDialog(Utils::CloseType_Window, runningCount, this); return false; } return true; } bool MainWindow::isQuakeMode() { return m_isQuakeWindow; } void MainWindow::onTermTitleChanged(QString title) { TermWidgetPage *tabPage = qobject_cast(sender()); const bool customName = tabPage->property("TAB_CUSTOM_NAME_PROPERTY").toBool(); if (!customName) { m_tabbar->setTabText(tabPage->identifier(), title); } } void MainWindow::onTabTitleChanged(QString title) { TermWidgetPage *tabPage = qobject_cast(sender()); TermWidget *term = tabPage->currentTerminal(); term->setProperty("currTabTitle", QVariant::fromValue(title)); m_tabbar->setTabText(tabPage->identifier(), title); } QString MainWindow::getConfigWindowState() { QString windowState = Settings::instance()->settings->option("advanced.window.use_on_starting")->value().toString(); // 启动参数配置的状态值优先于 内部配置的状态值 if (m_properties.contains(StartWindowState)) { QString state = m_properties[StartWindowState].toString(); qDebug() << "use line state set:" << state; if (state == "maximum") { windowState = "window_maximum"; } else if (state == "splitscreen") { windowState = "split_screen"; } else if (state == "normal") { windowState = "window_normal"; } else if (state == "fullscreen") { windowState = state; } else { qDebug() << "error line state set:" << state << "ignore it!"; } } return windowState; } /******************************************************************************* 1. @函数: halfScreenSize 2. @作者: n014361 王培利 3. @日期: 2020-04-22 4. @说明: 获取半屏大小(高度-1,如果不-1,最大后无法正常还原) *******************************************************************************/ QSize MainWindow::halfScreenSize() { QDesktopWidget w; int x = w.availableGeometry().width() / 2; int y = w.availableGeometry().height() - 1; QSize size(x, y); //qDebug() << "halfScreenSize:" << size; return size; } QString MainWindow::getWinInfoConfigPath() { QDir winInfoPath(QStandardPaths::writableLocation(QStandardPaths::AppConfigLocation)); if (!winInfoPath.exists()) { winInfoPath.mkpath(QStandardPaths::writableLocation(QStandardPaths::AppConfigLocation)); } QString winInfoFilePath(winInfoPath.filePath("wininfo-config.conf")); return winInfoFilePath; } void MainWindow::initWindowPosition(MainWindow *mainwindow) { int m_WindowNumber = executeCMD(cmd); if (m_WindowNumber == 1) { mainwindow->move((QApplication::desktop()->width() - width()) / 2, (QApplication::desktop()->height() - height()) / 2); } } void MainWindow::initShortcuts() { ShortcutManager::instance()->initConnect(this); connect(ShortcutManager::instance(), &ShortcutManager::addCustomCommandSignal, this, &MainWindow::addCustomCommandSlot); connect(ShortcutManager::instance(), &ShortcutManager::removeCustomCommandSignal, this, &MainWindow::removeCustomCommandSlot); /******** Modify by n014361 wangpeili 2020-01-10: 增加设置的各种快捷键修改关联***********×****/ // new_workspace connect(createNewShotcut("shortcuts.workspace.new_workspace", false), &QShortcut::activated, this, [this]() { this->addTab(currentPage()->createCurrentTerminalProperties(), true); }); // close_workspace connect(createNewShotcut("shortcuts.workspace.close_workspace"), &QShortcut::activated, this, [this]() { TermWidgetPage *page = currentPage(); if (page) { closeTab(page->identifier()); } }); // Close_other_workspaces connect(createNewShotcut("shortcuts.workspace.close_other_workspace"), &QShortcut::activated, this, [this]() { TermWidgetPage *page = currentPage(); if (page) { closeOtherTab(page->identifier()); } }); // previous_workspace connect(createNewShotcut("shortcuts.workspace.previous_workspace"), &QShortcut::activated, this, [this]() { TermWidgetPage *page = currentPage(); if (page) { int index = m_tabbar->currentIndex(); index -= 1; if (index < 0) { index = m_tabbar->count() - 1; } m_tabbar->setCurrentIndex(index); } }); // next_workspace connect(createNewShotcut("shortcuts.workspace.next_workspace"), &QShortcut::activated, this, [this]() { TermWidgetPage *page = currentPage(); if (page) { int index = m_tabbar->currentIndex(); index += 1; if (index == m_tabbar->count()) { index = 0; } m_tabbar->setCurrentIndex(index); } }); // horionzal_split connect(createNewShotcut("shortcuts.workspace.horionzal_split", false), &QShortcut::activated, this, [this]() { // 判读数量是否允许分屏 if (Service::instance()->isCountEnable()) { TermWidgetPage *page = currentPage(); if (page) { if (page->currentTerminal()) { int layer = page->currentTerminal()->getTermLayer(); Qt::Orientation orientation = static_cast(page->currentTerminal()->parentWidget())->orientation(); if (layer == 1 || (layer == 2 && orientation == Qt::Horizontal)) { page->split(Qt::Horizontal); return ; } } } } qDebug() << "can't split vertical again"; }); // vertical_split connect(createNewShotcut("shortcuts.workspace.vertical_split", false), &QShortcut::activated, this, [this]() { // 判读数量是否允许分屏 if (Service::instance()->isCountEnable()) { TermWidgetPage *page = currentPage(); if (page) { if (page->currentTerminal()) { int layer = page->currentTerminal()->getTermLayer(); Qt::Orientation orientation = static_cast(page->currentTerminal()->parentWidget())->orientation(); if (layer == 1 || (layer == 2 && orientation == Qt::Vertical)) { page->split(Qt::Vertical); return ; } } } } qDebug() << "can't split vertical again"; }); // select_upper_window connect(createNewShotcut("shortcuts.workspace.select_upper_window"), &QShortcut::activated, this, [this]() { qDebug() << "Alt+k"; TermWidgetPage *page = currentPage(); if (page) { page->focusNavigation(Qt::TopEdge); } }); // select_lower_window connect(createNewShotcut("shortcuts.workspace.select_lower_window"), &QShortcut::activated, this, [this]() { TermWidgetPage *page = currentPage(); if (page) { page->focusNavigation(Qt::BottomEdge); } }); // select_left_window connect(createNewShotcut("shortcuts.workspace.select_left_window"), &QShortcut::activated, this, [this]() { TermWidgetPage *page = currentPage(); if (page) { page->focusNavigation(Qt::LeftEdge); } }); // select_right_window connect(createNewShotcut("shortcuts.workspace.select_right_window"), &QShortcut::activated, this, [this]() { TermWidgetPage *page = currentPage(); if (page) { page->focusNavigation(Qt::RightEdge); // QMouseEvent e(QEvent::MouseButtonPress, ) QApplication::sendEvent(focusWidget(), &keyPress); } }); // close_window connect(createNewShotcut("shortcuts.workspace.close_window"), &QShortcut::activated, this, [this]() { TermWidgetPage *page = currentPage(); if (page) { qDebug() << "CloseWindow"; page->closeSplit(page->currentTerminal()); } }); // close_other_windows connect(createNewShotcut("shortcuts.workspace.close_other_windows"), &QShortcut::activated, this, [this]() { TermWidgetPage *page = currentPage(); if (page) { page->closeOtherTerminal(); } }); // copy connect(createNewShotcut("shortcuts.terminal.copy"), &QShortcut::activated, this, [this]() { TermWidgetPage *page = currentPage(); if (page) { page->copyClipboard(); } }); // paste connect(createNewShotcut("shortcuts.terminal.paste"), &QShortcut::activated, this, [this]() { TermWidgetPage *page = currentPage(); if (page) { page->pasteClipboard(); } }); // search connect(createNewShotcut("shortcuts.terminal.find"), &QShortcut::activated, this, [this]() { showPlugin(PLUGIN_TYPE_SEARCHBAR); }); // zoom_in connect(createNewShotcut("shortcuts.terminal.zoom_in"), &QShortcut::activated, this, [this]() { TermWidgetPage *page = currentPage(); if (page) { page->zoomInCurrentTierminal(); } /******** Add by nt001000 renfeixiang 2020-05-20:增加 雷神窗口根据字体大小设置最小高度函数 Begin***************/ setWindowMinHeightForFont(); /******** Add by nt001000 renfeixiang 2020-05-20:增加 雷神窗口根据字体大小设置最小高度函数 End***************/ }); // zoom_out connect(createNewShotcut("shortcuts.terminal.zoom_out"), &QShortcut::activated, this, [this]() { TermWidgetPage *page = currentPage(); if (page) { page->zoomOutCurrentTerminal(); } /******** Add by nt001000 renfeixiang 2020-05-20:增加 雷神窗口根据字体大小设置最小高度函数 Begin***************/ setWindowMinHeightForFont(); /******** Add by nt001000 renfeixiang 2020-05-20:增加 雷神窗口根据字体大小设置最小高度函数 End***************/ }); // default_size connect(createNewShotcut("shortcuts.terminal.default_size"), &QShortcut::activated, this, [this]() { TermWidgetPage *page = currentPage(); if (page) { page->setFontSize(Settings::instance()->fontSize()); } /******** Add by nt001000 renfeixiang 2020-05-20:增加 雷神窗口根据字体大小设置最小高度函数 Begin***************/ setWindowMinHeightForFont(); /******** Add by nt001000 renfeixiang 2020-05-20:增加 雷神窗口根据字体大小设置最小高度函数 End***************/ }); // select_all connect(createNewShotcut("shortcuts.terminal.select_all"), &QShortcut::activated, this, [this]() { TermWidgetPage *page = currentPage(); if (page) { qDebug() << "selectAll"; page->selectAll(); } }); // switch_fullscreen connect(createNewShotcut("shortcuts.advanced.switch_fullscreen"), &QShortcut::activated, this, [this]() { switchFullscreen(); }); // rename_tab connect(createNewShotcut("shortcuts.advanced.rename_title"), &QShortcut::activated, this, [this]() { showPlugin(PLUGIN_TYPE_NONE); TermWidgetPage *page = currentPage(); if (page) { QString currTabTitle = m_tabbar->tabText(m_tabbar->currentIndex()); page->showRenameTitleDialog(currTabTitle); } }); // display_shortcuts connect(createNewShotcut("shortcuts.advanced.display_shortcuts"), &QShortcut::activated, this, [this]() { qDebug() << "displayShortcuts"; displayShortcuts(); }); // custom_command connect(createNewShotcut("shortcuts.advanced.custom_command"), &QShortcut::activated, this, [this]() { if (m_CurrentShowPlugin == PLUGIN_TYPE_CUSTOMCOMMAND) { showPlugin(PLUGIN_TYPE_NONE); } else { showPlugin(PLUGIN_TYPE_CUSTOMCOMMAND); } }); // remote_management connect(createNewShotcut("shortcuts.advanced.remote_management"), &QShortcut::activated, this, [this]() { if (m_CurrentShowPlugin == PLUGIN_TYPE_REMOTEMANAGEMENT) { showPlugin(PLUGIN_TYPE_NONE); } else { showPlugin(PLUGIN_TYPE_REMOTEMANAGEMENT); } }); /********************* Modify by n014361 wangpeili End ************************/ for (int i = 1; i <= 9; i++) { QString shortCutStr = QString("ctrl+shift+%1").arg(i); //qDebug() << shortCutStr; QShortcut *switchTabSC = new QShortcut(QKeySequence(shortCutStr), this); connect(switchTabSC, &QShortcut::activated, this, [this, i]() { TermWidgetPage *page = currentPage(); if (page) { if (9 == i && m_tabbar->count() > 9) { m_tabbar->setCurrentIndex(m_tabbar->count() - 1); return; } if (i - 1 >= m_tabbar->count()) { qDebug() << "i - 1 > tabcount" << i - 1 << m_tabbar->count() << endl; return; } qDebug() << "index" << i - 1 << endl; m_tabbar->setCurrentIndex(i - 1); return; } qDebug() << "currentPage nullptr ??"; }); } } void MainWindow::initConnections() { connect(this, &MainWindow::mainwindowClosed, WindowsManager::instance(), &WindowsManager::onMainwindowClosed); connect(Settings::instance(), &Settings::windowSettingChanged, this, &MainWindow::onWindowSettingChanged); connect(Settings::instance(), &Settings::shortcutSettingChanged, this, &MainWindow::onShortcutSettingChanged); connect(this, &MainWindow::newWindowRequest, this, &MainWindow::onCreateNewWindow); connect(DApplicationHelper::instance(), &DApplicationHelper::themeTypeChanged, this, [ = ]() { //变成自动变色的图标以后,不需要来回变了。 // applyTheme(); }); connect(qApp, &QGuiApplication::applicationStateChanged, this, &MainWindow::onApplicationStateChanged); } void MainWindow::handleTitleBarMenuFocusPolicy() { QLayout *layout = titlebar()->layout(); for (int i = 0; i < layout->count(); ++i) { QWidget *widget = layout->itemAt(i)->widget(); if (widget != nullptr && QString(widget->metaObject()->className()) == QString("QWidget")) { QLayout *widgetLayout = widget->layout(); for (int j = 0; j < widgetLayout->count(); ++j) { QWidget *widget = widgetLayout->itemAt(j)->widget(); if (widget != nullptr && QString(widget->metaObject()->className()) == QString("QWidget")) { QLayout *wLayout = widget->layout(); for (int k = 0; k < wLayout->count(); ++k) { QWidget *widget = wLayout->itemAt(k)->widget(); if (widget != nullptr && QString(widget->metaObject()->className()).contains("Button")) { widget->setFocusPolicy(Qt::NoFocus); } } } } } } } int MainWindow::executeCMD(const char *cmd) { char *result; char buf_ps[1024] = {0}; FILE *ptr; ptr = popen(cmd, "r"); result = fgets(buf_ps, 1024, ptr); QString qStr(result); int num = qStr.toInt() ; pclose(ptr); return num; } /******************************************************************************* 1. @函数: showPlugin 2. @作者: n014361 王培利 3. @日期: 2020-03-26 4. @说明: 由mainwindow统一指令当前显示哪个插件 *******************************************************************************/ void MainWindow::showPlugin(const QString &name) { m_CurrentShowPlugin = name; if (name != PLUGIN_TYPE_NONE) { qDebug() << "show Plugin" << name; } emit showPluginChanged(name); } /******************************************************************************* 1. @函数: hidePlugin 2. @作者: n014361 王培利 3. @日期: 2020-04-22 4. @说明: 快速隐藏所有插件,resize专用的。 *******************************************************************************/ void MainWindow::hidePlugin() { if (m_CurrentShowPlugin == PLUGIN_TYPE_NONE) { return; } qDebug() << "hide Plugin" << m_CurrentShowPlugin; m_CurrentShowPlugin = PLUGIN_TYPE_NONE; emit quakeHidePlugin(); } QString MainWindow::selectedText(bool preserveLineBreaks) { TermWidgetPage *page = currentPage(); if (page) { if (page->currentTerminal()) { return page->currentTerminal()->selectedText(preserveLineBreaks); } } qDebug() << "not point terminal??"; return ""; } void MainWindow::onCreateNewWindow(QString workingDir) { Q_UNUSED(workingDir); // 调用一个新的进程,开启终端 QProcess process; process.startDetached(QCoreApplication::applicationFilePath()); } bool MainWindow::eventFilter(QObject *watched, QEvent *event) { if (event->type() == QEvent::KeyPress) { TermWidget *term = currentPage()->currentTerminal(); QKeyEvent *keyEvent = static_cast(event); if (keyEvent->key() == Qt::Key_Return || keyEvent->key() == Qt::Key_Enter) { if (term->enterSzCommand() && term->isActiveWindow()) { //--added by qinyaning(nyq) to slove Unable to download file from server, time: 2020.4.13 18:21--// pressEnterKey("\nsz \"${files[@]}\""); //------------------------------------- executeDownloadFile(); term->setEnterSzCommand(false); } } if ((keyEvent->modifiers() == Qt::ControlModifier) && (keyEvent->key() == Qt::Key_C || keyEvent->key() == Qt::Key_D)) { if (term->enterSzCommand()) { term->setEnterSzCommand(false); } } } return DMainWindow::eventFilter(watched, event); } /******************************************************************************* 1. @函数: onSettingValueChanged 2. @作者: n014361 王培利 3. @日期: 2020-02-19 4. @说明: 参数修改统一接口 *******************************************************************************/ void MainWindow::onWindowSettingChanged(const QString &keyName) // void MainWindow::onSettingValueChanged(const int &keyIndex, const QVariant &value) { if (keyName == "advanced.window.blurred_background") { setEnableBlurWindow(Settings::instance()->backgroundBlur()); return; } // use_on_starting重启生效 if (keyName == "advanced.window.use_on_starting") { QString state = Settings::instance()->settings->option("advanced.window.use_on_starting")->value().toString(); if ("window_normal" == state) { m_IfUseLastSize = true; /******** Modify by nt001000 renfeixiang 2020-05-25: 文件wininfo-config.conf中参数,使用定义更换window_width,window_height Begin***************/ m_winInfoConfig->setValue(CONFIG_WINDOW_WIDTH, 1000); m_winInfoConfig->setValue(CONFIG_WINDOW_HEIGHT, 600); /******** Modify by nt001000 renfeixiang 2020-05-25: 文件wininfo-config.conf中参数,使用定义更换window_width,window_height End***************/ qDebug() << "change value change value change value"; } else { m_IfUseLastSize = false; } qDebug() << "settingValue[" << keyName << "] changed to " << state << ", auto effective when next start!"; return; } // auto_hide_raytheon_window在使用中自动读取生效 if ((keyName == "advanced.window.auto_hide_raytheon_window") || (keyName == "advanced.window.use_on_starting")) { qDebug() << "settingValue[" << keyName << "] changed to " << Settings::instance()->OutputtingScroll() << ", auto effective when happen"; /***mod begin by ut001121 zhangmeng 20200528 修复BUG28920***/ //onApplicationStateChanged(QApplication::applicationState()); onAppFocusChangeForQuake(); /***mod end by ut001121***/ return; } qDebug() << "settingValue[" << keyName << "] changed is not effective"; } void MainWindow::onShortcutSettingChanged(const QString &keyName) { qDebug() << "Shortcut[" << keyName << "] changed"; if (m_BuiltInShortcut.contains(keyName)) { QString value = Settings::instance()->settings->option(keyName)->value().toString(); m_BuiltInShortcut[keyName]->setKey(QKeySequence(value)); return; } qDebug() << "Shortcut[" << keyName << "] changed is unknown!"; } void MainWindow::setNewTermPage(TermWidgetPage *termPage, bool activePage) { m_termStackWidget->addWidget(termPage); if (activePage) { m_termStackWidget->setCurrentWidget(termPage); } } void MainWindow::createNewWorkspace() { addTab(currentPage()->createCurrentTerminalProperties(), true); } /******************************************************************************* 1. @函数: applyTheme 2. @作者: n014361 王培利 3. @日期: 2020-03-09 4. @说明: 非DTK控件手动匹配系统主题的修改 *******************************************************************************/ void MainWindow::applyTheme() { return; } MainWindowPluginInterface *MainWindow::getPluginByName(const QString &name) { for (int i = 0; i < m_plugins.count(); i++) { if (m_plugins.at(i)->getPluginName() == name) { return m_plugins.at(i); } } return nullptr; } /******************************************************************************* 1. @函数:void MainWindow::displayShortcuts() 2. @作者: n014361 王培利 3. @日期: 2020-01-10 4. @说明: 显示快捷键列表信息 *******************************************************************************/ void MainWindow::displayShortcuts() { QPoint pos = calculateShortcutsPreviewPoint(); QJsonArray jsonGroups; createJsonGroup("terminal", jsonGroups); createJsonGroup("workspace", jsonGroups); createJsonGroup("advanced", jsonGroups); QJsonObject shortcutObj; shortcutObj.insert("shortcut", jsonGroups); QJsonDocument doc(shortcutObj); QStringList shortcutString; QByteArray array = doc.toJson(); QString param1 = "-j=" + QString(array.data()); QString param2 = "-p=" + QString::number(pos.x()) + "," + QString::number(pos.y()); shortcutString << param1 << param2; QProcess *shortcutViewProcess = new QProcess(); shortcutViewProcess->startDetached("deepin-shortcut-viewer", shortcutString); connect(shortcutViewProcess, SIGNAL(finished(int)), shortcutViewProcess, SLOT(deleteLater())); } /******************************************************************************* 1. @函数: void MainWindow::createJsonGroup(const QString &keyCategory, QJsonArray &jsonGroups) 2. @作者: n014361 王培利 3. @日期: 2020-01-10 4. @说明: 创建JsonGroup组 *******************************************************************************/ void MainWindow::createJsonGroup(const QString &keyCategory, QJsonArray &jsonGroups) { qDebug() << keyCategory; QString strGroupName = ""; if (keyCategory == "workspace") { strGroupName = QObject::tr("Workspace"); } else if (keyCategory == "terminal") { strGroupName = QObject::tr("Terminal"); } else if (keyCategory == "advanced") { strGroupName = QObject::tr("Others"); } else { return; } QString groupname = "shortcuts." + keyCategory; QJsonArray JsonArry; for (auto &opt : Settings::instance()->settings->group(groupname)->options()) { // Settings::instance()->settings->keys()) QJsonObject jsonItem; QString name = QObject::tr(opt->name().toUtf8().data()); /***del begin by ut001121 zhangmeng 修复BUG#23269 快捷键菜单“切换全屏”显示与文案不一致***/ /*if (opt->name() == "Fullscreen") name = tr("Toggle fullscreen"); */ /***del end by ut001121 zhangmeng***/ jsonItem.insert("name", name); jsonItem.insert("value", opt->value().toString()); JsonArry.append(jsonItem); } if (keyCategory == "workspace") { QJsonObject jsonItem; jsonItem.insert("name", tr("Select workspace")); jsonItem.insert("value", "Ctrl+Shift+1~9"); JsonArry.append(jsonItem); } /************************ Add by sunchengxi 2020-06-08:json重新排序,快捷键显示顺序调整 Begin************************/ //default-config.json 文件增加的跟此处相关字段,此处相应添加,保证显示。 //用三个条件分开,清晰,方便后续调整扩展维护,代码稍微多点。 if (keyCategory == "terminal") { QStringList strList; strList << QObject::tr("Copy") << QObject::tr("Paste") << QObject::tr("Find") << QObject::tr("Zoom in") << QObject::tr("Zoom out") << QObject::tr("Default size") << QObject::tr("Select all"); QJsonArray newJsonArry; for (int i = 0; i < strList.size(); i++) { for (int j = 0; j < JsonArry.size(); j++) { QJsonObject jsonItem = JsonArry[j].toObject(); if (jsonItem.value("name") == strList[i]) { newJsonArry.append(jsonItem); break; } } } JsonArry = newJsonArry; } if (keyCategory == "workspace") { QStringList strList; strList << QObject::tr("New workspace") << QObject::tr("Close workspace") << QObject::tr("Close other workspaces") << QObject::tr("Previous workspace") << QObject::tr("Next workspace") << QObject::tr("Select workspace") << QObject::tr("Vertical split") << QObject::tr("Horizontal split") << QObject::tr("Select upper window") << QObject::tr("Select lower window") << QObject::tr("Select left window") << QObject::tr("Select right window") << QObject::tr("Close window") << QObject::tr("Close other windows"); QJsonArray newJsonArry; for (int i = 0; i < strList.size(); i++) { for (int j = 0; j < JsonArry.size(); j++) { QJsonObject jsonItem = JsonArry[j].toObject(); if (jsonItem.value("name") == strList[i]) { newJsonArry.append(jsonItem); break; } } } JsonArry = newJsonArry; } if (keyCategory == "advanced") { QStringList strList; strList << QObject::tr("Fullscreen") << QObject::tr("Rename title") << QObject::tr("Display shortcuts") << QObject::tr("Custom commands") << QObject::tr("Remote management"); QJsonArray newJsonArry; for (int i = 0; i < strList.size(); i++) { for (int j = 0; j < JsonArry.size(); j++) { QJsonObject jsonItem = JsonArry[j].toObject(); if (jsonItem.value("name") == strList[i]) { newJsonArry.append(jsonItem); break; } } } JsonArry = newJsonArry; } /************************ Add by sunchengxi 2020-06-08:json重新排序,快捷键显示顺序调整 End************************/ QJsonObject JsonGroup; JsonGroup.insert("groupName", strGroupName); JsonGroup.insert("groupItems", JsonArry); jsonGroups.append(JsonGroup); } /******************************************************************************* 1. @函数: createNewShotcut 2. @作者: n014361 王培利 3. @日期: 2020-02-20 4. @说明: 创建内置快捷键管理, AutoRepeat 是否可以连续触发快捷键, 默认可以 *******************************************************************************/ QShortcut *MainWindow::createNewShotcut(const QString &key, bool AutoRepeat) { QString value = Settings::instance()->settings->option(key)->value().toString(); QShortcut *shortcut = new QShortcut(QKeySequence(value), this); m_BuiltInShortcut[key] = shortcut; shortcut->setAutoRepeat(AutoRepeat); // qDebug() << "createNewShotcut" << key << value; return shortcut; } /** * Upload file to remote server */ void MainWindow::remoteUploadFile() { QStringList fileName = Utils::showFilesSelectDialog(this); if (!fileName.isEmpty()) { pressCtrlAt(); sleep(100); QString strTxt = "sz "; for (QString &str : fileName) { strTxt += str + " "; } currentPage()->sendTextToCurrentTerm(strTxt); currentPage()->sendTextToCurrentTerm("\n"); } } /** * Download file from remote server */ void MainWindow::remoteDownloadFile() { TermWidget *term = currentPage()->currentTerminal(); downloadFilePath = Utils::showDirDialog(this); if (!downloadFilePath.isNull() && !downloadFilePath.isEmpty()) { //QString strTxt = "read -e -a files -p \"" + tr("Type path to download file") + ": \"; sz \"${files[@]}\"\n"; //currentTab()->sendTextToCurrentTerm(strTxt); //--added by qinyaning(nyq) to slove Unable to download file from server, time: 2020.4.13 18:21--// QString strTxt = QString("read -e -a files -p \"%1: \"").arg(tr("Type path to download file")); pressEnterKey(strTxt); currentPage()->sendTextToCurrentTerm("\n"); //------------------- term->setEnterSzCommand(true); //sleep(100);// } } /******************************************************************************* 1. @函数: onApplicationStateChanged 2. @作者: n014361 王培利 3. @日期: 2020-04-28 4. @说明: 当雷神窗口处于非激动状态自动隐藏 *******************************************************************************/ void MainWindow::onApplicationStateChanged(Qt::ApplicationState state) { Q_UNUSED(state) return; } void MainWindow::addCustomCommandSlot(QAction *newAction) { qDebug() << " MainWindow::addCustomCommandSlot"; QAction *action = newAction; addAction(action); connect(action, &QAction::triggered, this, [this, action]() { if (!this->isActiveWindow()) { return ; } QString command = action->data().toString(); if (!command.endsWith('\n')) { command.append('\n'); } currentPage()->sendTextToCurrentTerm(command); }); } void MainWindow::removeCustomCommandSlot(QAction *newAction) { qDebug() << " MainWindow::removeCustomCommandSlot"; removeAction(newAction); } /******************************************************************************* 1. @函数: OnHandleCloseType 2. @作者: ut001000 任飞翔 3. @日期: 2020-06-03 4. @说明: 处理CloseType的关闭窗口 *******************************************************************************/ void MainWindow::OnHandleCloseType(int result, Utils::CloseType type) { qDebug() << "OnHandleCloseType type is" << type; // 弹窗隐藏或消失 Service::instance()->setIsDialogShow(this, false); if (result != 1) { qDebug() << "user cancle close"; return; } TermWidgetPage *page = currentPage(); if (page == nullptr) { qDebug() << "null pointer of currentPage ???"; return; } //以下所有接口二次重入 switch (type) { case Utils::CloseType_Window: m_hasConfirmedClose = true; close(); break; case Utils::CloseType_Tab: closeTab(page->identifier(), true); break; case Utils::CloseType_OtherTab: closeOtherTab(page->identifier(), true); break; case Utils::CloseType_Terminal://Terminal相关的关闭弹框操作 page->closeSplit(page->currentTerminal(), true); break; case Utils::CloseType_OtherTerminals: page->closeOtherTerminal(true); break; } } /** * after sz command,wait input file and download file. */ void MainWindow::executeDownloadFile() { //--modified by qinyaning(nyq) to slove Unable to download file from server, time: 2020.4.13 18:21--// currentPage()->sendTextToCurrentTerm("\r\n"); sleep(1000); pressCtrlAt(); sleep(100); QString strCd = "cd " + downloadFilePath; currentPage()->sendTextToCurrentTerm(strCd); //sleep(100); QString strRz = "\r\nrz -be"; currentPage()->sendTextToCurrentTerm(strRz); downloadFilePath = ""; //------------------------------------------- } void MainWindow::pressCtrlAt() { QKeyEvent keyPress(QEvent::KeyPress, Qt::Key_At, Qt::ControlModifier); QApplication::sendEvent(focusWidget(), &keyPress); } void MainWindow::pressCtrlU() { QKeyEvent keyPress(QEvent::KeyPress, Qt::Key_U, Qt::ControlModifier); QApplication::sendEvent(focusWidget(), &keyPress); } void MainWindow::pressCtrlC() { QKeyEvent keyPress(QEvent::KeyPress, Qt::Key_C, Qt::ControlModifier); QApplication::sendEvent(focusWidget(), &keyPress); } void MainWindow::sleep(int msec) { QTime dieTime = QTime::currentTime().addMSecs(msec); while (QTime::currentTime() < dieTime) { QCoreApplication::processEvents(QEventLoop::AllEvents, 100); } } //--added by qinyaning(nyq) to slove Unable to download file from server, time: 2020.4.13 18:21--// void MainWindow::pressEnterKey(const QString &text) { QKeyEvent event(QEvent::KeyPress, 0, Qt::NoModifier, text); QApplication::sendEvent(focusWidget(), &event); // expose as a big fat keypress event } int MainWindow::getDesktopIndex() const { return m_desktopIndex; } ///////////////////////////////////////////////////////////////////////////////////////////////////// /** 普通终端窗口 */ NormalWindow::NormalWindow(TermProperties properties, QWidget *parent): MainWindow(properties, parent) { Q_ASSERT(m_isQuakeWindow == false); setObjectName("NormalWindow"); initUI(); initConnections(); initShortcuts(); } NormalWindow::~NormalWindow() { } void NormalWindow::initTitleBar() { // titleba在普通模式和雷神模型不一样的功能 m_titleBar = new TitleBar(this, false); m_titleBar->setTabBar(m_tabbar); titlebar()->setCustomWidget(m_titleBar); titlebar()->setAutoHideOnFullscreen(true); titlebar()->setTitle(""); //设置titlebar焦点策略为不抢占焦点策略,防止点击titlebar后终端失去输入焦点 titlebar()->setFocusPolicy(Qt::NoFocus); initOptionButton(); initOptionMenu(); //fix bug 17566 正常窗口下,新建和关闭窗口菜单栏会高亮 //handleTitleBarMenuFocusPolicy(); // titlebar所有控件不可获取焦点 Utils::clearChildrenFocus(titlebar()); } /******************************************************************************* 1. @函数: initWindowAttribute copy from setNormalWindow 2. @作者: n014361 王培利 3. @日期: 2020-04-22 4. @说明: 标准模式的窗口设置 *******************************************************************************/ void NormalWindow::initWindowAttribute() { // init window state. QString windowState = getConfigWindowState(); if (windowState == "window_maximum") { show(); setDefaultLocation(); showMaximized(); } else if (windowState == "fullscreen") { setDefaultLocation(); switchFullscreen(true); } else if (windowState == "split_screen") { setWindowRadius(0); resize(halfScreenSize()); } else { m_IfUseLastSize = true; /******** Modify by nt001000 renfeixiang 2020-05-25: 文件wininfo-config.conf中参数,使用定义更换window_width,window_height Begin***************/ int saveWidth = m_winInfoConfig->value(CONFIG_WINDOW_WIDTH).toInt(); int saveHeight = m_winInfoConfig->value(CONFIG_WINDOW_HEIGHT).toInt(); qDebug() << "load window_width: " << saveWidth; qDebug() << "load window_height: " << saveHeight; /******** Modify by nt001000 renfeixiang 2020-05-25:文件wininfo-config.conf中参数,使用定义更换window_width,window_height End***************/ // 如果配置文件没有数据 if (saveWidth == 0 || saveHeight == 0) { saveWidth = 1000; saveHeight = 600; } resize(QSize(saveWidth, saveHeight)); singleFlagMove(); } } void NormalWindow::saveWindowSize() { // 过滤普通模式的特殊窗口 if (!m_IfUseLastSize) { return; } // (真.假)半屏窗口大小时就不记录了 /******** Modify by ut001000 renfeixiang 2020-07-03:fix# 36482 ***************/ // 1.高度-1,如果不-1,最大后无法正常还原 // 2.+ QSize(0, 1) 适应原始高度 // 3.- QSize(0, 1) 适应关闭窗口特效, 半屏后无法还原 if ((size() == halfScreenSize()) || (size() == (halfScreenSize() + QSize(0, 1)))|| (size() == (halfScreenSize() - QSize(0, 1)))) { return; } if (windowState() == Qt::WindowNoState) { /******** Modify by nt001000 renfeixiang 2020-05-25: 文件wininfo-config.conf中参数,使用定义更换window_width,window_height Begin***************/ // 记录最后一个正常窗口的大小 m_winInfoConfig->setValue(CONFIG_WINDOW_WIDTH, width()); m_winInfoConfig->setValue(CONFIG_WINDOW_HEIGHT, height()); qDebug() << "save windows size:" << width() << height(); /******** Modify by nt001000 renfeixiang 2020-05-25: 文件wininfo-config.conf中参数,使用定义更换window_width,window_height End***************/ } } void NormalWindow::switchFullscreen(bool forceFullscreen) { if (forceFullscreen || !window()->windowState().testFlag(Qt::WindowFullScreen)) { window()->setWindowState(windowState() | Qt::WindowFullScreen); } else { window()->setWindowState(windowState() & ~Qt::WindowFullScreen); } } QPoint NormalWindow::calculateShortcutsPreviewPoint() { QRect rect = window()->geometry(); return QPoint(rect.x() + rect.width() / 2, rect.y() + rect.height() / 2); } void NormalWindow::onAppFocusChangeForQuake() { return; } void NormalWindow::changeEvent(QEvent *event) { if (m_exitFullScreen) { bool isFullscreen = window()->windowState().testFlag(Qt::WindowFullScreen); m_exitFullScreen->setVisible(isFullscreen); titlebar()->setMenuVisible(!isFullscreen); titlebar()->findChild("DTitlebarDWindowQuitFullscreenButton")->hide(); } QMainWindow::changeEvent(event); } ///////////////////////////////////////////////////////////////////////////////////////////////////// /** 雷神终端窗口 */ QuakeWindow::QuakeWindow(TermProperties properties, QWidget *parent): MainWindow(properties, parent) { Q_ASSERT(m_isQuakeWindow == true); setObjectName("QuakeWindow"); initUI(); initConnections(); initShortcuts(); } QuakeWindow::~QuakeWindow() { } void QuakeWindow::initTitleBar() { // titleba在普通模式和雷神模型不一样的功能 m_titleBar = new TitleBar(this, true); m_titleBar->setTabBar(m_tabbar); titlebar()->setFixedHeight(0); m_centralLayout->addWidget(m_titleBar); // titlebar所有控件不可获取焦点 Utils::clearChildrenFocus(titlebar()); } /******************************************************************************* 1. @函数: initWindowAttribute copy from setQuakeWindow 2. @作者: n014361 王培利 3. @日期: 2020-04-22 4. @说明: 雷神窗口的特殊设置 *******************************************************************************/ void QuakeWindow::initWindowAttribute() { /************************ Add by m000743 sunchengxi 2020-04-27:雷神窗口任务栏移动后位置异常问题 Begin************************/ setWindowRadius(0); //QRect deskRect = QApplication::desktop()->availableGeometry();//获取可用桌面大小 QDesktopWidget *desktopWidget = QApplication::desktop(); QRect screenRect = desktopWidget->screenGeometry(); //获取设备屏幕大小 Qt::WindowFlags windowFlags = this->windowFlags(); setWindowFlags(windowFlags | Qt::WindowStaysOnTopHint | Qt::FramelessWindowHint /*| Qt::Dialog*/); //add a line by ut001121 zhangmeng 2020-04-27雷神窗口禁用移动(修复bug#22975) setEnableSystemMove(false);// setAttribute(Qt::WA_Disabled, true); /******** Modify by m000714 daizhengwen 2020-03-26: 窗口高度超过2/3****************/ setMinimumSize(screenRect.size().width(), 60); setMaximumHeight(screenRect.size().height() * 2 / 3); /********************* Modify by m000714 daizhengwen End ************************/ setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); setFixedWidth(QApplication::desktop()->availableGeometry().width()); connect(desktopWidget, &QDesktopWidget::workAreaResized, this, [this]() { qDebug() << "workAreaResized" << QApplication::desktop()->availableGeometry(); /******** Modify by nt001000 renfeixiang 2020-05-20:修改成只需要设置雷神窗口宽度,根据字体高度设置雷神最小高度 Begin***************/ setMinimumWidth(QApplication::desktop()->availableGeometry().width()); setWindowMinHeightForFont(); /******** Modify by nt001000 renfeixiang 2020-05-20:修改成只需要设置雷神窗口宽度,根据字体高度设置雷神最小高度 End***************/ move(QApplication::desktop()->availableGeometry().x(), QApplication::desktop()->availableGeometry().y()); qDebug() << "size" << size(); setFixedWidth(QApplication::desktop()->availableGeometry().width()); return ; }); /******** Modify by nt001000 renfeixiang 2020-05-25: 文件wininfo-config.conf中参数,使用定义更换quake_window_Height Begin***************/ int saveHeight = m_winInfoConfig->value(CONFIG_QUAKE_WINDOW_HEIGHT).toInt(); /******** Modify by nt001000 renfeixiang 2020-05-25: 文件wininfo-config.conf中参数,使用定义更换quake_window_Height End***************/ qDebug() << "quake_window_Height: " << saveHeight; qDebug() << "quake_window_Height: " << minimumSize(); // 如果配置文件没有数据 if (saveHeight == 0) { saveHeight = screenRect.size().height() / 3; } int saveWidth = screenRect.size().width(); resize(QSize(saveWidth, saveHeight)); move(0, 0); /************************ Add by m000743 sunchengxi 2020-04-27:雷神窗口任务栏移动后位置异常问题 End ************************/ /******** Add by nt001000 renfeixiang 2020-05-20:增加setQuakeWindowMinHeight函数,设置雷神最小高度 Begin***************/ setWindowMinHeightForFont(); /******** Add by nt001000 renfeixiang 2020-05-20:增加setQuakeWindowMinHeight函数,设置雷神最小高度 End***************/ } void QuakeWindow::saveWindowSize() { // 记录最后一个正常窗口的大小 /******** Modify by nt001000 renfeixiang 2020-05-25: 文件wininfo-config.conf中参数,使用定义更换quake_window_Height Begin***************/ m_winInfoConfig->setValue(CONFIG_QUAKE_WINDOW_HEIGHT, height()); /******** Modify by nt001000 renfeixiang 2020-05-25: 文件wininfo-config.conf中参数,使用定义更换quake_window_Height End***************/ qDebug() << "save quake_window_Height:" << height(); } void QuakeWindow::switchFullscreen(bool forceFullscreen) { Q_UNUSED(forceFullscreen) return; } QPoint QuakeWindow::calculateShortcutsPreviewPoint() { //--added by qinyaning(nyq) to solve the problem of can't show center--// QRect rect = QApplication::desktop()->availableGeometry(); //---------------------------------------------------------------------// return QPoint(rect.x() + rect.width() / 2, rect.y() + rect.height() / 2); } /******************************************************************************* 1. @函数: onAppFocusChangeForQuake 2. @作者: ut001121 张猛 3. @日期: 2020-05-22 4. @说明: 处理雷神窗口丢失焦点自动隐藏功能 *******************************************************************************/ void QuakeWindow::onAppFocusChangeForQuake() { // 开关关闭,不处理 if (!Settings::instance()->settings->option("advanced.window.auto_hide_raytheon_window")->value().toBool()) { return; } // 雷神窗口隐藏,不处理 if (!isVisible()) { return; } // 雷神的普通对话框,不处理 if (Service::instance()->getIsDialogShow()) { return; } // 雷神设置框显示,不处理 if (Service::instance()->isSettingDialogVisible() && Service::instance()->getSettingOwner() == this) { return; } // 处于激活状态,不处理 if (isActiveWindow()) { return; } hide(); } /******************************************************************************* 1. @函数: setQuakeWindowMinHeight 2. @作者: ut001000 任飞翔 3. @日期: 2020-05-20 4. @说明: 雷神窗口根据字体和字体大小设置最小高度 *******************************************************************************/ /******** Add by nt001000 renfeixiang 2020-05-20:增加雷神窗口根据字体和字体大小设置最小高度函数 Begin***************/ void QuakeWindow::setWindowMinHeightForFont() { int height = 0; QFontMetrics fm(currentPage()->currentTerminal()->getTerminalFont()); height = fm.height(); height = 60 + height * 2; setMinimumHeight(height); } /******** Add by nt001000 renfeixiang 2020-05-20:增加雷神窗口根据字体和字体大小设置最小高度函数 End***************/ void QuakeWindow::changeEvent(QEvent *event) { // 不是激活事件,不处理 if (event->type() == QEvent::ActivationChange) { onAppFocusChangeForQuake(); } return QMainWindow::changeEvent(event); } /******************************************************************************* 1. @函数: showEvent 2. @作者: ut001121 张猛 3. @日期: 2020-05-28 4. @说明: 窗口显示事件 *******************************************************************************/ void QuakeWindow::showEvent(QShowEvent *event) { /***add begin by ut001121 zhangmeng 20200528 重新获取桌面索引 修复BUG29082***/ m_desktopIndex = DBusManager::callKDECurrentDesktop(); /***add end by ut001121***/ /***add by ut001121 zhangmeng 20200606 切换窗口拉伸属性 修复BUG24430***/ switchEnableResize(); DMainWindow::showEvent(event); } /******************************************************************************* 1. @函数: event 2. @作者: ut001121 张猛 3. @日期: 2020-06-06 4. @说明: 窗口事件 *******************************************************************************/ bool QuakeWindow::event(QEvent *event) { /***add begin by ut001121 zhangmeng 20200606 切换窗口拉伸属性 修复BUG24430***/ if (event->type() == QEvent::HoverMove) { switchEnableResize(); } /***add end by ut001121***/ return MainWindow::event(event); } /******************************************************************************* 1. @函数: switchEnableResize 2. @作者: ut001121 张猛 3. @日期: 2020-06-06 4. @说明: 切换窗口拉伸属性 *******************************************************************************/ void QuakeWindow::switchEnableResize() { // 如果(桌面光标Y坐标)>(雷神窗口Y坐标+雷神高度的1/2),则启用拉伸属性.否则禁用拉伸属性 setEnableSystemResize(QCursor::pos().y() > pos().y() + height() / 2); } deepin-terminal-5.2.11/src/main/mainwindow.h000066400000000000000000000256251370157770500207430ustar00rootroot00000000000000#ifndef MAINWINDOW_H #define MAINWINDOW_H #include "termproperties.h" #include "titlebar.h" #include "termwidgetpage.h" #include "remotemanagementplugn.h" #include "utils.h" #include #include #include #include #include #include #include #include #include #include #include DWIDGET_USE_NAMESPACE class TabBar; class TermWidgetPage; class TermProperties; class ShortcutManager; class MainWindowPluginInterface; class CustomCommandPlugin; class MainWindow : public DMainWindow { Q_OBJECT public: explicit MainWindow(TermProperties properties, QWidget *parent = nullptr); ~MainWindow() override; void addTab(TermProperties properties, bool activeTab = false); /******** Modify by n014361 wangpeili 2020-01-07: 关闭其它标签页功能 ************/ // 点击,右键,快捷键以及被调用. void closeTab(const QString &identifier, bool hasConfirmed = false); // Tab右键或者快捷键 void closeOtherTab(const QString &identifier, bool hasConfirmed = false); // 整体关闭事件 void closeAllTab(); /********************* Modify by n014361 wangpeili End ************************/ void showExitConfirmDialog(Utils::CloseType type, int count = 1, QWidget *parent = nullptr); /************************ Mod by sunchengxi 2020-04-30:分屏修改标题异常问题 Begin************************/ QString getCurrTabTitle(); /************************ Mod by sunchengxi 2020-04-30:分屏修改标题异常问题 End ************************/ void focusPage(const QString &identifier); void focusCurrentPage(); TermWidgetPage *currentPage(); void setCurrentPage(TermWidgetPage *page); TermWidgetPage *getPageByIdentifier(const QString &identifier); void forAllTabPage(const std::function &func); //ShortcutManager *getShortcutManager(); void executeDownloadFile(); void pressCtrlAt(); void pressCtrlU(); void pressCtrlC(); void sleep(int msec); // 由mainwindow统一指令当前显示哪个插件 void showPlugin(const QString &name); // 快速隐藏插件 void hidePlugin(); // 新建工作区 void createNewWorkspace(); // 由mainwindow统一获取当前选择的文本。 QString selectedText(bool preserveLineBreaks = true); bool hasRunningProcesses(); bool isQuakeMode(); static constexpr const char *PLUGIN_TYPE_SEARCHBAR = "Search Bar"; static constexpr const char *PLUGIN_TYPE_THEME = "Theme"; static constexpr const char *PLUGIN_TYPE_CUSTOMCOMMAND = "Custom Command"; static constexpr const char *PLUGIN_TYPE_REMOTEMANAGEMENT = "Remote Management"; static constexpr const char *PLUGIN_TYPE_ENCODING = "Encoding"; static constexpr const char *PLUGIN_TYPE_NONE = "None"; /******** Add by nt001000 renfeixiang 2020-05-25:增加 定义 Begin***************/ static constexpr const char *CONFIG_WINDOW_WIDTH = "window_width"; static constexpr const char *CONFIG_WINDOW_HEIGHT = "window_height"; //Modify by ut001000 renfeixiang 2020-06-18:修改quake_window_Height为quake_window_height bug#33779 static constexpr const char *CONFIG_QUAKE_WINDOW_HEIGHT = "quake_window_height"; /******** Add by nt001000 renfeixiang 2020-05-25:增加 定义 End***************/ int getDesktopIndex() const; signals: void newWindowRequest(const QString &directory); // !这两个信号被封装了,请不要单独调用! void showPluginChanged(const QString &name); void quakeHidePlugin(); void mainwindowClosed(MainWindow *); // 编码方式,仅当前mainwindow有效. void changeEncodeSig(const QString &name); public slots: // void onSettingValueChanged(const int &keyIndex, const QVariant &value); void onWindowSettingChanged(const QString &keyName); void onShortcutSettingChanged(const QString &keyName); void remoteUploadFile(); void remoteDownloadFile(); // 处理雷神窗口自动隐藏功能以及window+D一起显示的问题 void onApplicationStateChanged(Qt::ApplicationState state); void addCustomCommandSlot(QAction *newAction); void removeCustomCommandSlot(QAction *newAction); /******** Add by ut001000 renfeixiang 2020-06-03:增加 Begin***************/ //处理关闭类型的参数 void OnHandleCloseType(int result, Utils::CloseType type); /******** Add by ut001000 renfeixiang 2020-06-03:增加 End***************/ protected: void closeEvent(QCloseEvent *event) override; void resizeEvent(QResizeEvent *event) override; bool eventFilter(QObject *watched, QEvent *event) override; //------------------------------------------------------------ protected slots: void onTermTitleChanged(QString title); void onTabTitleChanged(QString title); void onCreateNewWindow(QString workingDir); protected: void initUI(); void initWindow(); void setDefaultLocation(); void singleFlagMove(); QString getConfigWindowState(); QSize halfScreenSize(); // 加载插件 void initPlugins(); void initShortcuts(); void initConnections(); // 初始化标签 void initTabBar(); void initOptionButton(); void initOptionMenu(); void setNewTermPage(TermWidgetPage *termPage, bool activePage = true); QString getWinInfoConfigPath(); void initWindowPosition(MainWindow *mainwindow); void handleTitleBarMenuFocusPolicy(); int executeCMD(const char *cmd); bool isTabVisited(int tabSessionId); bool isTabChangeColor(int tabSessionId); void updateTabStatus(); /******** Modify by n014361 wangpeili 2020-03-09: 非DTK控件手动匹配系统主题的修改 **********/ void applyTheme(); /********************* Modify by n014361 wangpeili End ************************/ /**************** Modify by n013252 wangliang 2020-01-20: 终端退出保护 ****************/ bool closeConfirm(); /**************** Modify by n013252 wangliang End ****************/ MainWindowPluginInterface *getPluginByName(const QString &name); /******** Modify by n014361 wangpeili 2020-01-06:增加显示快捷键功能***********×****/ // 显示快捷键功能 void displayShortcuts(); // 创建Json组信息 void createJsonGroup(const QString &keyCategory, QJsonArray &jsonGroups); /********************* Modify by n014361 wangpeili End ************************/ /******** Modify by n014361 wangpeili 2020-02-20: 创建快捷键管理 ****************/ QShortcut *createNewShotcut(const QString &key, bool AutoRepeat = true); /********************* Modify by n014361 wangpeili End ************************/ //--added by qinyaning(nyq) to slove Unable to download file from server, time: 2020.4.13 18:21--// void pressEnterKey(const QString &text); //--------------------------------------- protected: // 初始化标题栏 virtual void initTitleBar() = 0; // 初始化窗口属性 virtual void initWindowAttribute() = 0; public: // 保存窗口尺寸 virtual void saveWindowSize() = 0; // 切换全屏 virtual void switchFullscreen(bool forceFullscreen = false) = 0; // 显示快捷键功能 virtual QPoint calculateShortcutsPreviewPoint() = 0; // 处理雷神窗口丢失焦点自动隐藏功能 virtual void onAppFocusChangeForQuake() = 0; // 根据字体和字体大小设置最小高度 virtual void setWindowMinHeightForFont() = 0; protected: QMenu *m_menu = nullptr; DToolButton *m_exitFullScreen = nullptr; TabBar *m_tabbar = nullptr; QWidget *m_centralWidget = nullptr; QVBoxLayout *m_centralLayout = nullptr; QStackedWidget *m_termStackWidget = nullptr; QList m_plugins; TermProperties m_properties; TitleBar *m_titleBar = nullptr; bool m_isQuakeWindow = false; QMap m_tabVisitMap; QMap m_tabChangeColorMap; /******** Modify by n014361 wangpeili 2020-02-20: 内置快捷键集中管理 ****************/ QMap m_BuiltInShortcut; /********************* Modify by n014361 wangpeili End ************************/ QString downloadFilePath = ""; RemoteManagementPlugn *remoteManagPlugin = nullptr; CustomCommandPlugin *customCommandPlugin = nullptr; QString m_strWindowId; const char *cmd = "ps -elf|grep deepin-terminal$ |wc -l"; /******** Modify by m000714 daizhengwen 2020-03-29: 终端窗口配置 ****************/ QSettings *m_winInfoConfig = nullptr; /********************* Modify by m000714 daizhengwen End ************************/ QString m_CurrentShowPlugin = PLUGIN_TYPE_NONE; protected: // 窗口最小宽度 const int m_MinWidth = 450; // 窗口最小高度 const int m_MinHeight = 250; // 是否需要保存位置开关,雷神窗口不关心这个参数 bool m_IfUseLastSize = false; // 雷神终端所在桌面 int m_desktopIndex; bool m_hasConfirmedClose = false; }; class NormalWindow : public MainWindow { Q_OBJECT public: explicit NormalWindow(TermProperties properties, QWidget *parent = nullptr); ~NormalWindow() override; protected: // 初始化标题栏 virtual void initTitleBar() override; // 初始化窗口属性 virtual void initWindowAttribute() override; // 保存窗口尺寸 virtual void saveWindowSize() override; // 切换全屏 virtual void switchFullscreen(bool forceFullscreen = false) override; // 计算快捷预览显示坐标 virtual QPoint calculateShortcutsPreviewPoint() override; // 处理雷神窗口丢失焦点自动隐藏功能 virtual void onAppFocusChangeForQuake() override; // 根据字体和字体大小设置最小高度 virtual void setWindowMinHeightForFont() override {return;} protected: void changeEvent(QEvent *event) override; }; class QuakeWindow : public MainWindow { Q_OBJECT public: explicit QuakeWindow(TermProperties properties, QWidget *parent = nullptr); ~QuakeWindow() override; protected: // 初始化标题栏 virtual void initTitleBar() override; // 初始化窗口属性 virtual void initWindowAttribute() override; // 保存窗口尺寸 virtual void saveWindowSize() override; // 切换全屏 virtual void switchFullscreen(bool forceFullscreen = false) override; // 计算快捷预览显示坐标 virtual QPoint calculateShortcutsPreviewPoint() override; // 处理雷神窗口丢失焦点自动隐藏功能 virtual void onAppFocusChangeForQuake() override; // 根据字体和字体大小设置最小高度 virtual void setWindowMinHeightForFont() override; protected: void changeEvent(QEvent *event) override; void showEvent(QShowEvent *event) override; bool event(QEvent *event) override; protected: // 切换窗口拉伸属性 inline void switchEnableResize(); }; #endif // MAINWINDOW_H deepin-terminal-5.2.11/src/main/mainwindowplugininterface.h000066400000000000000000000010111370157770500240220ustar00rootroot00000000000000#ifndef MAINWINDOWPLUGININTERFACE_H #define MAINWINDOWPLUGININTERFACE_H #include class MainWindow; class MainWindowPluginInterface : public QObject { Q_OBJECT public: MainWindowPluginInterface(QObject *parent) : QObject(parent) { } virtual void initPlugin(MainWindow *mainWindow) = 0; virtual QAction *titlebarMenu(MainWindow *mainWindow) = 0; QString getPluginName() { return m_pluginName; } QString m_pluginName; }; #endif // MAINWINDOWPLUGININTERFACE_H deepin-terminal-5.2.11/src/main/service.cpp000066400000000000000000000464101370157770500205550ustar00rootroot00000000000000#include "service.h" #include "utils.h" #include #include #include #include #include #include #include #include #include Service *Service::pService = new Service(); Service *Service::instance() { return pService; } Service::~Service() { qDebug() << __FUNCTION__; if (nullptr != m_atspiThread) { // 结束线程 m_atspiThread->stopThread(); delete m_atspiThread; } releaseShareMemory(); if (nullptr != m_settingDialog) { delete m_settingDialog; } if (nullptr != m_settingOwner) { delete m_settingOwner; } if (nullptr != m_settingShortcutConflictDialog) { delete m_settingShortcutConflictDialog; } qDebug() << "service release finish!"; } void Service::init() { /******** Modify by ut000610 daizhengwen 2020-07-09:在linux上兼容快捷键 Begin***************/ // 初始化qt-at-spi // 该线程负责在linux上兼容快捷键,如ctrl+shift+? (服务器版暂不支持此兼容) m_atspiThread = new AtspiDesktop; // 运行线程 m_atspiThread->start(); /********************* Modify by ut000610 daizhengwen End ************************/ // 初始化配置 Settings::instance()->init(); // 初始化自定义快捷键 ShortcutManager::instance()->initShortcuts(); // 初始化远程管理数据 ServerConfigManager::instance()->initServerConfig(); // 主进程:共享内存如果不存在即创建 if (!m_enableShareMemory->attach()) { m_enableShareMemory->create(sizeof(ShareMemoryInfo)); qDebug() << "m_enableShareMemory create"; } // 创建好以后,保持共享内存连接,防止释放。 m_enableShareMemory->attach(); // 主进程:首次赋值m_pShareMemoryInfo m_pShareMemoryInfo = static_cast(m_enableShareMemory->data()); // 主进程:首次连接设置默认值为false setMemoryEnable(false); qDebug() << "All init data complete!"; //监听窗口特效变化 listenWindowEffectSwitcher(); } /******************************************************************************* 1. @函数: initSetting 2. @作者: ut000610 戴正文 3. @日期: 2020-06-05 4. @说明: 初始化设置框,在窗口现实后初始化,使第一次出现设置框不至于卡顿 *******************************************************************************/ void Service::initSetting() { if (nullptr != m_settingDialog) { return; } QDateTime startTime = QDateTime::currentDateTime(); m_settingDialog = new DSettingsDialog(); // 关闭后将指针置空,下次重新new connect(m_settingDialog, &DSettingsDialog::finished, this, [ = ](int result) { Q_UNUSED(result) //激活设置框的有拥者 if (m_settingOwner) { m_settingOwner->activateWindow(); m_settingOwner->focusCurrentPage(); } }); // 关闭时delete m_settingDialog->widgetFactory()->registerWidget("fontcombobox", Settings::createFontComBoBoxHandle); m_settingDialog->widgetFactory()->registerWidget("slider", Settings::createCustomSliderHandle); m_settingDialog->widgetFactory()->registerWidget("spinbutton", Settings::createSpinButtonHandle); m_settingDialog->widgetFactory()->registerWidget("shortcut", Settings::createShortcutEditOptionHandle); // 将数据重新读入 m_settingDialog->updateSettings(Settings::instance()->settings); // 设置窗口模态为没有模态,不阻塞窗口和进程 m_settingDialog->setWindowModality(Qt::NonModal); // 让设置与窗口等效,隐藏后显示就不会被遮挡 m_settingDialog->setWindowFlags(Qt::Window | Qt::WindowCloseButtonHint); moveToCenter(m_settingDialog); QDateTime endTime = QDateTime::currentDateTime(); qDebug() << "Setting init cost time " << endTime.toMSecsSinceEpoch() - startTime.toMSecsSinceEpoch() << "ms"; //判断为UOS服务器版本时,隐藏透明度/背景模糊选项 if (DSysInfo::deepinType() == DSysInfo::DeepinServer) { showHideOpacityAndBlurOptions(false); return; } showHideOpacityAndBlurOptions(isWindowEffectEnabled()); } /******************************************************************************* 1. @函数: showHideOpacityAndBlurOptions 2. @作者: ut000438 王亮 3. @日期: 2020-06-24 4. @说明: 显示/隐藏设置的透明度和背景模糊选项-- 仅UOS服务器版本使用 *******************************************************************************/ void Service::showHideOpacityAndBlurOptions(bool isShow) { QWidget *rightFrame = m_settingDialog->findChild("RightFrame"); if (nullptr == rightFrame) { return; } QList rightWidgetList = rightFrame->findChildren(); for (int i = 0; i < rightWidgetList.size(); i++) { QWidget *widget = rightWidgetList.at(i); if (strcmp(widget->metaObject()->className(), "QCheckBox") == 0) { QString checkText = (qobject_cast(widget))->text(); if (checkText == QObject::tr("Blur background")) { QWidget *optionWidget = widget; QWidget *parentWidget = widget->parentWidget(); qDebug() << parentWidget << endl; if (parentWidget && strcmp(parentWidget->metaObject()->className(), "Dtk::Widget::DFrame") == 0) { optionWidget = parentWidget; } if (isShow) { optionWidget->show(); } else { optionWidget->hide(); } } } else if (strcmp(widget->metaObject()->className(), "Dtk::Widget::DSlider") == 0) { QWidget *optionWidget = widget; QWidget *parentWidget = widget->parentWidget(); qDebug() << parentWidget << endl; if (parentWidget && strcmp(parentWidget->metaObject()->className(), "Dtk::Widget::DFrame") == 0) { optionWidget = parentWidget; } if (isShow) { optionWidget->show(); } else { optionWidget->hide(); } } else if (strcmp(widget->metaObject()->className(), "QLabel") == 0) { QString lblText = (qobject_cast(widget))->text(); if (lblText == QObject::tr("Opacity")) { QWidget *optionWidget = widget; QWidget *parentWidget = widget->parentWidget(); qDebug() << parentWidget << endl; if (parentWidget && strcmp(parentWidget->metaObject()->className(), "Dtk::Widget::DFrame") == 0) { optionWidget = parentWidget; } if (isShow) { optionWidget->show(); } else { optionWidget->hide(); } } } else { //do nothing } } } /******************************************************************************* 1. @函数: listenWindowEffectSwitcher 2. @作者: ut000438 王亮 3. @日期: 2020-06-24 4. @说明: 监听窗口特效开关对应DBus信号,并实时显示/隐藏设置的透明度和背景模糊选项 *******************************************************************************/ void Service::listenWindowEffectSwitcher() { if (nullptr == m_wmSwitcher) { m_wmSwitcher = new WMSwitcher(WMSwitcherService, WMSwitcherPath, QDBusConnection::sessionBus(), this); connect(m_wmSwitcher, &WMSwitcher::WMChanged, this, [this](const QString & wmName) { qDebug() << "changed wm name:" << wmName; bool isWinEffectEnabled = false; if (wmName == "deepin wm") { isWinEffectEnabled = true; } showHideOpacityAndBlurOptions(isWinEffectEnabled); emit Service::instance()->onWindowEffectEnabled(isWinEffectEnabled); }, Qt::QueuedConnection); } } /******************************************************************************* 1. @函数: isWindowEffectEnabled 2. @作者: ut000438 王亮 3. @日期: 2020-06-24 4. @说明: 判断当前是否开启窗口特效 开启-true 关闭-false *******************************************************************************/ bool Service::isWindowEffectEnabled() { QDBusMessage msg = QDBusMessage::createMethodCall(WMSwitcherService, WMSwitcherPath, WMSwitcherService, "CurrentWM"); QDBusMessage response = QDBusConnection::sessionBus().call(msg); if (response.type() == QDBusMessage::ReplyMessage) { QList list = response.arguments(); QString wmName = list.first().toString(); if (wmName == "deepin wm") { qDebug() << "窗口特效已开启"; return true; } } else { qDebug() << "call CurrentWM Fail!" << response.errorMessage(); } qDebug() << "窗口特效已关闭"; return false; } /******************************************************************************* 1. @函数: showSettingDialog 2. @作者: ut000610 戴正文 3. @日期: 2020-05-20 4. @说明: 唯一显示设置框 *******************************************************************************/ void Service::showSettingDialog(MainWindow *pOwner) { // 第一次初始化dialog initSetting(); QDateTime startTime = QDateTime::currentDateTime(); //保存设置框的有拥者 m_settingOwner = pOwner; if (nullptr != m_settingDialog) { /******** Modify by ut000610 daizhengwen 2020-06-23:每当点击设置,都重新new一个settingDialog Begin***************/ delete m_settingDialog; m_settingDialog = nullptr; // 重新new dialog ----由于设置文字大小,窗口不会自适应,所以需要重新new,如果dtk设置框随设置变化大小,此处可去 initSetting(); /********************* Modify by ut000610 daizhengwen End ************************/ //雷神需要让窗口置顶,可是普通窗口不要 if (m_settingOwner == WindowsManager::instance()->getQuakeWindow()) { m_settingDialog->setWindowFlag(Qt::WindowStaysOnTopHint); } else { // 雷神窗口失去焦点自动隐藏 if (WindowsManager::instance()->getQuakeWindow()) { WindowsManager::instance()->getQuakeWindow()->onAppFocusChangeForQuake(); } m_settingDialog->setWindowFlag(Qt::WindowStaysOnTopHint, false); } // 显示窗口 m_settingDialog->move(m_settingDialog->pos()); /******** Add by ut001000 renfeixiang 2020-06-15:增加 每次显示设置窗口时,执行等宽字体出来 Begin***************/ Settings::instance()->HandleWidthFont(); FontFilter::instance()->HandleWidthFont(); /******** Add by ut001000 renfeixiang 2020-06-15:增加 每次显示设置窗口时,执行等宽字体出来 End***************/ m_settingDialog->show(); } else { qDebug() << "No setting dialog."; return; } // 若设置窗口已显示,则激活窗口 if (!m_settingDialog->isActiveWindow()) { m_settingDialog->activateWindow(); } QDateTime endTime = QDateTime::currentDateTime(); qDebug() << "Setting show cost time " << endTime.toMSecsSinceEpoch() - startTime.toMSecsSinceEpoch() << "ms"; } /******************************************************************************* 1. @函数: showShortcutConflictMsgbox 2. @作者: ut000610 戴正文 3. @日期: 2020-05-21 4. @说明: 设置弹窗的快捷键冲突弹窗 *******************************************************************************/ void Service::showShortcutConflictMsgbox(QString txt) { /******** Modify by ut000610 daizhengwen 2020-05-27: 出现提示和快捷键显示不一致的问题 bug#28507****************/ if (txt.contains("Return")) { txt.replace("Return", "Enter"); } /********************* Modify by ut000610 daizhengwen End ************************/ // 若没有设置弹框则退出,谈不上显示设置的快捷键冲突 if (nullptr == m_settingDialog) { return; } // 若没有弹窗,初始化 if (nullptr == m_settingShortcutConflictDialog) { m_settingShortcutConflictDialog = new DDialog(m_settingDialog); connect(m_settingShortcutConflictDialog, &DDialog::finished, m_settingShortcutConflictDialog, [ = ]() { delete m_settingShortcutConflictDialog; m_settingShortcutConflictDialog = nullptr; }); m_settingShortcutConflictDialog->setIcon(QIcon::fromTheme("dialog-warning")); /***mod by ut001121 zhangmeng 20200521 将确认按钮设置为默认按钮 修复BUG26960***/ m_settingShortcutConflictDialog->addButton(QString(tr("OK")), true, DDialog::ButtonNormal); } m_settingShortcutConflictDialog->setTitle(QString(txt + QObject::tr("please set another one."))); m_settingShortcutConflictDialog->show(); // 将冲突窗口移到窗口中央 moveToCenter(m_settingShortcutConflictDialog); } /******************************************************************************* 1. @函数: isCountEnable 2. @作者: ut000610 戴正文 3. @日期: 2020-06-15 4. @说明: 从term数量的角度判断是否允许继续创建 *******************************************************************************/ bool Service::isCountEnable() { return WindowsManager::instance()->widgetCount() < MAXWIDGETCOUNT; } void Service::Entry(QStringList arguments) { TermProperties properties; Utils::parseCommandLine(arguments, properties); // 雷神处理入口 if (properties[QuakeMode].toBool()) { WindowsManager::instance()->runQuakeWindow(properties); return; } // // 到达窗口最大值,则返回,不做创建 // if (WindowsManager::instance()->widgetCount() >= MAXWIDGETCOUNT) { // // 当前不创建,要将enable还原 // Service::instance()->setEnable(true); // return; // } // 普通窗口处理入口 WindowsManager::instance()->createNormalWindow(properties); return; } Service::Service(QObject *parent) : QObject(parent) { m_enableShareMemory = new QSharedMemory(QString("enableCreateTerminal")); } /******************************************************************************* 1. @函数: getEnable 2. @作者: ut000439 王培利 3. @日期: 2020-06-17 4. @说明: 子进程获取是否可以创建窗口许可,获取到权限立即将标志位置为false *******************************************************************************/ bool Service::getEnable() { if (!Service::instance()->isCountEnable()) { return false; } // 如果共享内存无法访问?这是极为异常的情况。正常共享内存的建立由主进程创建,并保持attach不释放。 if (!m_enableShareMemory->attach()) { qDebug() << "[sub app] m_enableShareMemory can't attach"; return false; } // sub app首次赋值m_pShareMemoryInfo m_pShareMemoryInfo = static_cast(m_enableShareMemory->data()); if (Service::instance()->getShareMemoryCount() >= MAXWIDGETCOUNT) { qDebug() << "[sub app] current Terminals count = " << m_pShareMemoryInfo->TerminalsCount << ", can't create terminal any more."; return false; } qDebug() << "[sub app] current Terminals count = " << m_pShareMemoryInfo->TerminalsCount; // 如果标志位为false,则表示正在创建窗口,不可以再创建 if (!Service::instance()->getMemoryEnable()) { Service::instance()->releaseShareMemory(); qDebug() << "[sub app] server m_enableShareMemory is busy create!"; return false; } // 可以创建了,立马将标识位置为false. Service::instance()->setMemoryEnable(false); Service::instance()->releaseShareMemory(); return true; } /******************************************************************************* 1. @函数: updateShareMemoryCount 2. @作者: ut000439 王培利 3. @日期: 2020-07-02 4. @说明: ShareMemoryCount这个为当前总的终端数,但是雷神创建的第一个不包括在内 *******************************************************************************/ void Service::updateShareMemoryCount(int count) { if (!m_enableShareMemory->isAttached()) { qDebug() << "m_enableShareMemory isAttached failed?????"; return ; } m_pShareMemoryInfo->TerminalsCount = count; qDebug() << "[main app] TerminalsCount set " << count; return ; } int Service::getShareMemoryCount() { return m_pShareMemoryInfo->TerminalsCount; } /******************************************************************************* 1. @函数: setMemoryEnable 2. @作者: ut000439 王培利 3. @日期: 2020-06-17 4. @说明: 设置共享内存信息,1=true(主进程), 0=false(主进程首次或子进程获得许可以后) *******************************************************************************/ bool Service::setMemoryEnable(bool enable) { if (!m_enableShareMemory->isAttached()) { qDebug() << "m_enableShareMemory isAttached failed?????"; return false; } if (enable) { m_pShareMemoryInfo->enableCreateTerminal = 1; } else { m_pShareMemoryInfo->enableCreateTerminal = 0; } qDebug() << "m_enableShareMemory set" << enable << m_pShareMemoryInfo->enableCreateTerminal; return true; } /******************************************************************************* 1. @函数: releaseShareMemory 2. @作者: ut000439 王培利 3. @日期: 2020-06-17 4. @说明: 释放共享内存连接 *******************************************************************************/ void Service::releaseShareMemory() { qDebug() << "[sub app] m_enableShareMemory released"; m_enableShareMemory->detach(); m_enableShareMemory->deleteLater(); } /******************************************************************************* 1. @函数: getMemoryEnable 2. @作者: ut000439 王培利 3. @日期: 2020-06-17 4. @说明: 获取共享内存标志, 1=true,0=false *******************************************************************************/ bool Service::getMemoryEnable() { if (m_pShareMemoryInfo->enableCreateTerminal == 0) { qDebug() << "[sub app] current m_enableShareMemory is false" << m_pShareMemoryInfo->enableCreateTerminal; return false; } qDebug() << "[sub app] current m_enableShareMemory is true" << m_pShareMemoryInfo->enableCreateTerminal; return true; } bool Service::getIsDialogShow() const { return m_isDialogShow; } void Service::setIsDialogShow(QWidget *parent, bool isDialogShow) { MainWindow *window = static_cast(parent); if (window == WindowsManager::instance()->getQuakeWindow()) { qDebug() << "QuakeWindow show or hide dialog " << isDialogShow; m_isDialogShow = isDialogShow; } if (true == isDialogShow) { // 对话框显示,终端窗口禁用 window->setEnabled(false); } else { // 对话框隐藏或关闭,终端窗口启用,焦点重回终端 window->setEnabled(true); window->focusCurrentPage(); } } deepin-terminal-5.2.11/src/main/service.h000066400000000000000000000070311370157770500202160ustar00rootroot00000000000000#ifndef SERVICE_H #define SERVICE_H /******************************************************************************* 1. @类名: Service 2. @作者: ut000439 王培利 3. @日期: 2020-05-19 4. @说明: 全局的后台服务类.         管理所有底层数据的加载         管理所有特殊的通知信号         管理所有程序入口 *******************************************************************************/ #include "termproperties.h" #include "windowsmanager.h" #include "shortcutmanager.h" #include "settings.h" #include "atspidesktop.h" #include #include #include #include #include using WMSwitcher = com::deepin::WMSwitcher; #define WMSwitcherService "com.deepin.WMSwitcher" #define WMSwitcherPath "/com/deepin/WMSwitcher" DWIDGET_USE_NAMESPACE struct ShareMemoryInfo { int enableCreateTerminal = 0; int TerminalsCount = 0; }; class Service : public QObject { Q_OBJECT public: static Service *instance(); ~Service(); void init(); // 初始化设置框 void initSetting(); // 显示设置框 void showSettingDialog(MainWindow *pOwner); // 显示设置快捷键冲突弹窗 void showShortcutConflictMsgbox(QString txt); // 设置框是否显示 bool isSettingDialogVisible() { return m_settingDialog ? m_settingDialog->isVisible() : false; } //获取设置框的所有者 MainWindow *getSettingOwner() { return m_settingOwner; } //重置设置框的所有者 void resetSettingOwner() { m_settingOwner = nullptr; } // 是否允许继续创建 bool isCountEnable(); bool getIsDialogShow() const; void setIsDialogShow(QWidget *parent, bool isDialogShow); bool getEnable() ; void updateShareMemoryCount(int count); int getShareMemoryCount(); bool setMemoryEnable(bool enable); bool getMemoryEnable(); void releaseShareMemory(); //判断当前是否开启窗口特效 开启-true 关闭-false bool isWindowEffectEnabled(); signals: void refreshCommandPanel(QString oldCmdName, QString newCmdName); // 切换编码列表的编码 void checkEncode(QString encode); // 当前终端切换 void currentTermChange(QWidget *term); void onWindowEffectEnabled(bool isEnabled); public slots: void Entry(QStringList arguments); private: explicit Service(QObject *parent = nullptr); //显示/隐藏设置透明度和背景模糊选项-- 仅UOS服务器版本使用 void showHideOpacityAndBlurOptions(bool isShow); //监听窗口特效开关对应DBus信号,并实时显示/隐藏透明度和背景模糊选项 void listenWindowEffectSwitcher(); static Service *pService ; // 设置框 全局唯一显示 DSettingsDialog *m_settingDialog = nullptr; WMSwitcher *m_wmSwitcher = nullptr; //设置框的所有者 MainWindow *m_settingOwner = nullptr; // 设置框,快捷键冲突弹窗 DDialog *m_settingShortcutConflictDialog = nullptr; // 雷神用来判断是否有弹窗显示 bool m_isDialogShow = false; // 是否允许创建新的窗口 bool m_enable = false; QSharedMemory *m_enableShareMemory = nullptr; // 这个指针实际上与上面指针指向同一地址,不需要二次释放 ShareMemoryInfo *m_pShareMemoryInfo = nullptr; // 初始化和运行无障碍辅助工具的线程 AtspiDesktop *m_atspiThread = nullptr; }; #endif // SERVICE_H deepin-terminal-5.2.11/src/main/terminalapplication.cpp000066400000000000000000000007451370157770500231550ustar00rootroot00000000000000#include "terminalapplication.h" #include "mainwindow.h" #include "service.h" // qt #include TerminalApplication::TerminalApplication(int &argc, char *argv[]) : DApplication(argc, argv) { } TerminalApplication::~TerminalApplication() { // app结束时,释放Service if (nullptr != Service::instance()) { delete Service::instance(); } } void TerminalApplication::handleQuitAction() { qDebug() << "handleQuitAction"; activeWindow()->close(); } deepin-terminal-5.2.11/src/main/terminalapplication.h000066400000000000000000000006171370157770500226200ustar00rootroot00000000000000#ifndef TERMINALAPPLICATION_H #define TERMINALAPPLICATION_H #include DWIDGET_USE_NAMESPACE class TerminalApplication : public DApplication { Q_OBJECT public: TerminalApplication(int &argc, char *argv[]); ~TerminalApplication(); protected: // 重写了app.quit为当前窗口close. void handleQuitAction() override; private: }; #endif // TERMINALAPPLICATION_H deepin-terminal-5.2.11/src/main/termproperties.cpp000066400000000000000000000016551370157770500222030ustar00rootroot00000000000000#include "termproperties.h" TermProperties::TermProperties(QString workingDir) { m_properties.insert(WorkingDir, workingDir); } TermProperties::TermProperties(QString workingDir, QString colorScheme) { m_properties.insert(WorkingDir, workingDir); m_properties.insert(ColorScheme, colorScheme); } TermProperties::TermProperties(QMap list) { m_properties = list; } void TermProperties::setWorkingDir(QString workingDir) { m_properties.insert(WorkingDir, workingDir); } void TermProperties::setTermPropertyMap(QMap list) { m_properties = list; } bool TermProperties::contains(TermProperty propertyType) const { return m_properties.contains(propertyType); } QVariant &TermProperties::operator[](const TermProperty &key) { return m_properties[key]; } const QVariant TermProperties::operator[](const TermProperty &key) const { return m_properties[key]; } deepin-terminal-5.2.11/src/main/termproperties.h000066400000000000000000000023461370157770500216460ustar00rootroot00000000000000#ifndef TERMPROPERTIES_H #define TERMPROPERTIES_H #include enum TermProperty { SingleFlag, // mainwindow使用, 默认为false QuakeMode, // mainwindow使用, 右键菜单要用到. WorkingDir, // 每个terminal单独使用 ColorScheme, // 未使用 ShellProgram, // 仅供第一个terminal使用 Execute, // 仅供第一个terminal使用,任意长,任意位置,QStringList StartWindowState, // mainwindow使用 KeepOpen, // 仅供第一个terminal使用 Script // 仅供第一个terminal使用 }; class TermProperties { Q_GADGET public: explicit TermProperties() = default; explicit TermProperties(QString workingDir); explicit TermProperties(QString workingDir, QString colorScheme); explicit TermProperties(QMap list); bool contains(TermProperty propertyType) const; void setTermPropertyMap(QMap list); void setWorkingDir(QString workingDir); QVariant &operator[](const TermProperty &key); const QVariant operator[](const TermProperty &key) const; private: QMap m_properties; }; #endif // TERMPROPERTIES_H deepin-terminal-5.2.11/src/main/windowsmanager.cpp000066400000000000000000000107751370157770500221470ustar00rootroot00000000000000#include "windowsmanager.h" #include "dbusmanager.h" #include "utils.h" #include "service.h" #include WindowsManager *WindowsManager::pManager = new WindowsManager(); WindowsManager *WindowsManager::instance() { return pManager; } void WindowsManager::runQuakeWindow(TermProperties properties) { if (m_quakeWindow == nullptr) { qDebug() << "runQuakeWindow :create"; m_quakeWindow = new QuakeWindow(properties); m_quakeWindow->show(); // 雷神创建的第一个时候,m_quakeWindow仍为null,需要在这里更正一下. Service::instance()->updateShareMemoryCount(m_quakeWindow == nullptr? m_widgetCount: m_widgetCount -1); return; } // Alt+F2的显隐功能实现点 quakeWindowShowOrHide(); } void WindowsManager::quakeWindowShowOrHide() { //MainWindow *mainWindow = getMainWindow(); qDebug() << "ShowOrHide" << m_quakeWindow->winId(); // 没有显示,就显示. if (!m_quakeWindow->isVisible()) { qDebug() << "!mainWindow isVisible now show !" << m_quakeWindow->winId(); m_quakeWindow->show(); } // 没有激活就激活 if (!m_quakeWindow->isActiveWindow()) { qDebug() << "QuakeWindow is activate, now activateWindow" << m_quakeWindow->winId(); int index = DBusManager::callKDECurrentDesktop(); if (index != -1 && m_quakeWindow->getDesktopIndex() != index) { // 不在同一个桌面 DBusManager::callKDESetCurrentDesktop(m_quakeWindow->getDesktopIndex()); } m_quakeWindow->activateWindow(); return; } // 如果已经激活,那么就隐藏 qDebug() << "isWinVisible mainWindow->isActiveWindow() : start hide" << m_quakeWindow->winId(); // 雷神的普通对话框,不处理 if (Service::instance()->getIsDialogShow()) { return; } // 雷神设置框显示,不处理 if (Service::instance()->isSettingDialogVisible() && Service::instance()->getSettingOwner() == m_quakeWindow) { if (m_quakeWindow->isActiveWindow()) { Service::instance()->showSettingDialog(m_quakeWindow); } return; } m_quakeWindow->hide(); } void WindowsManager::createNormalWindow(TermProperties properties) { TermProperties newProperties = properties; if (m_normalWindowList.count() == 0) { newProperties[SingleFlag] = true; } MainWindow *newWindow = new NormalWindow(newProperties); m_normalWindowList << newWindow; qDebug() << "create NormalWindow, current count =" << m_normalWindowList.count() << ", SingleFlag" << newProperties[SingleFlag].toBool(); newWindow->show(); } void WindowsManager::onMainwindowClosed(MainWindow *window) { /***add begin by ut001121 zhangmeng 20200527 关闭终端窗口时重置设置框所有者 修复BUG28636***/ if (window == Service::instance()->getSettingOwner()) { Service::instance()->resetSettingOwner(); } /***add end by ut001121 zhangmeng***/ /***mod begin by ut001121 zhangmeng 20200617 应用程序主动控制退出 修复BUG33541***/ if (window == m_quakeWindow) { Q_ASSERT(window->isQuakeMode() == true); m_quakeWindow = nullptr; } else if (m_normalWindowList.contains(window)) { Q_ASSERT(window->isQuakeMode() == false); m_normalWindowList.removeOne(window); } else { //Q_ASSERT(false); qDebug() << "unkown windows closed " << window; } window->deleteLater(); // 程序退出判断 add by ut001121 if(m_normalWindowList.size() == 0 && m_quakeWindow == nullptr){ qApp->quit(); } /***mod end by ut001121***/ } WindowsManager::WindowsManager(QObject *parent) : QObject(parent) { } int WindowsManager::widgetCount() const { if (nullptr == WindowsManager::instance()->getQuakeWindow()) { return m_widgetCount; } else { // 不将雷神统计在内 return m_widgetCount - 1; } } void WindowsManager::terminalCountIncrease() { ++m_widgetCount; // 雷神首次创建的时候m_quakeWindow = nullptr, 统计数据会多出来一个,后面流程会修正. Service::instance()->updateShareMemoryCount(m_quakeWindow == nullptr? m_widgetCount: m_widgetCount -1); qDebug() << "++ Terminals Count : " << m_widgetCount; } void WindowsManager::terminalCountReduce() { --m_widgetCount; Service::instance()->updateShareMemoryCount(m_quakeWindow == nullptr? m_widgetCount: m_widgetCount -1); qDebug() << "-- Terminals Count : " << m_widgetCount; } deepin-terminal-5.2.11/src/main/windowsmanager.h000066400000000000000000000027671370157770500216160ustar00rootroot00000000000000#ifndef WINDOWSMANAGER_H #define WINDOWSMANAGER_H /******************************************************************************* 1. @类名: WindowsManager 2. @作者: ut000439 王培利 3. @日期: 2020-05-19 4. @说明: 全局窗口管理,维护mainwindow列表.         普通窗口的创建,关闭.         雷神窗口的创建,关闭,显与隐 *******************************************************************************/ #include "termproperties.h" #include "mainwindow.h" #include // 窗口最大数量 #define MAXWIDGETCOUNT 197 class WindowsManager : public QObject { Q_OBJECT public: static WindowsManager *instance(); void runQuakeWindow(TermProperties properties); void quakeWindowShowOrHide(); void createNormalWindow(TermProperties properties); // 窗口数量增加 void terminalCountIncrease(); // 窗口数量减少 void terminalCountReduce(); // 获取当前窗口数量 int widgetCount() const; // 获取雷神窗口 MainWindow *getQuakeWindow() { return m_quakeWindow; } signals: public slots: void onMainwindowClosed(MainWindow *); private: QList m_normalWindowList; MainWindow *m_quakeWindow = nullptr; TermWidgetPage *m_currentPage = nullptr; private: explicit WindowsManager(QObject *parent = nullptr); static WindowsManager *pManager; // 窗口数量 int m_widgetCount = 0; }; #endif // WINDOWSMANAGER_H deepin-terminal-5.2.11/src/quaketerminal/000077500000000000000000000000001370157770500203225ustar00rootroot00000000000000deepin-terminal-5.2.11/src/quaketerminal/quaketerminaladapter.cpp000066400000000000000000000012171370157770500252320ustar00rootroot00000000000000#include "quaketerminaladapter.h" #include #include #include #include #include #include #include /* * Implementation of adaptor class QuakeTerminalAdapter */ QuakeTerminalAdapter::QuakeTerminalAdapter(QObject *parent) : QDBusAbstractAdaptor(parent) { // constructor setAutoRelaySignals(true); } QuakeTerminalAdapter::~QuakeTerminalAdapter() { // destructor } void QuakeTerminalAdapter::ShowOrHide() { qDebug() << "QuakeTerminalAdapter::ShowOrHide"; QMetaObject::invokeMethod(parent(), "ShowOrHide"); } deepin-terminal-5.2.11/src/quaketerminal/quaketerminaladapter.h000066400000000000000000000016701370157770500247020ustar00rootroot00000000000000#ifndef QUAKETERMINALADAPTER_H #define QUAKETERMINALADAPTER_H #include #include #define kQuakeTerminalService "com.deepin.quake_terminal" #define kQuakeTerminalIface "/com/deepin/quake_terminal" /* * Adaptor class for interface com.deepin.quake_terminal */ class QuakeTerminalAdapter : public QDBusAbstractAdaptor { Q_OBJECT Q_CLASSINFO("D-Bus Interface", "com.deepin.quake_terminal") Q_CLASSINFO("D-Bus Introspection", "" " \n" " \n" " \n" " \n" "") public: QuakeTerminalAdapter(QObject *parent); virtual ~QuakeTerminalAdapter(); public Q_SLOTS: void ShowOrHide(); }; #endif // QUAKETERMINALADAPTER_H deepin-terminal-5.2.11/src/quaketerminal/quaketerminalproxy.cpp000066400000000000000000000030501370157770500247700ustar00rootroot00000000000000#include "quaketerminalproxy.h" #include "mainwindow.h" #include "dbusmanager.h" #include "utils.h" #include #include #include #include QuakeTerminalProxy::QuakeTerminalProxy(QObject *parent) : QObject(parent) { this->setObjectName("QuakeTerminalProxy"); } QuakeTerminalProxy::~QuakeTerminalProxy() { } MainWindow *getMainWindow() { MainWindow *mainWin = nullptr; foreach (QWidget *w, qApp->topLevelWidgets()) { mainWin = qobject_cast(w); if (mainWin) { return mainWin; } } return nullptr; } void QuakeTerminalProxy::ShowOrHide() { MainWindow *mainWindow = getMainWindow(); qDebug() << "ShowOrHide" << mainWindow->winId(); // 没有显示,就显示. if (!mainWindow->isVisible()) { qDebug() << "!mainWindow isVisible now show !" << mainWindow->winId(); mainWindow->show(); } // 没有激活就激活 if (!mainWindow->isActiveWindow()) { qDebug() << "QuakeWindow is activate, now activateWindow" << mainWindow->winId(); int index = DBusManager::callKDECurrentDesktop(); if (index != -1 && mainWindow->getDesktopIndex() != index) { // 不在同一个桌面 DBusManager::callKDESetCurrentDesktop(mainWindow->getDesktopIndex()); } mainWindow->activateWindow(); return; } // 如果已经激活,那么就隐藏 qDebug() << "isWinVisible mainWindow->isActiveWindow() : start hide" << mainWindow->winId(); mainWindow->hide(); } deepin-terminal-5.2.11/src/quaketerminal/quaketerminalproxy.h000066400000000000000000000005411370157770500244370ustar00rootroot00000000000000#ifndef QUAKETERMINALPROXY_H #define QUAKETERMINALPROXY_H #include #include #include class QuakeTerminalProxy : public QObject { Q_OBJECT public: explicit QuakeTerminalProxy(QObject *parent = nullptr); ~QuakeTerminalProxy(); public slots: void ShowOrHide(); }; #endif // QUAKETERMINALPROXY_H deepin-terminal-5.2.11/src/quaketerminal/termargumentparser.cpp000066400000000000000000000052321370157770500247570ustar00rootroot00000000000000#include "termargumentparser.h" #include "mainwindow.h" #include "quaketerminaladapter.h" #include "quaketerminalproxy.h" #include #include #include #include #include #include TermArgumentParser::TermArgumentParser(QObject *parent) : QObject(parent) { } TermArgumentParser::~TermArgumentParser() { } bool TermArgumentParser::parseArguments(MainWindow *mainWindow, bool isQuakeMode) { if (isQuakeMode) { bool isDBusRegSuccess = initDBus(); if (!isDBusRegSuccess) { return true; } } //mainWindow->setQuakeWindow(isQuakeMode); mainWindow->show(); /******** Modify by n014361 wangpeili 2020-01-20: 雷神窗口打开不能自动激活 ********/ mainWindow->activateWindow(); /********************* Modify by n014361 wangpeili End ************************/ return false; } //--解决窗口不居中问题 added by nyq bool TermArgumentParser::ParseArguments(MainWindow *mainWindow, bool isQuakeMode, bool isSingleApp) { bool res = parseArguments(mainWindow, isQuakeMode); //---------------added by qinyaning(nyq): 解决窗口不居中问题----------------------/ qDebug() << (isSingleApp ? "is single in TermArgumentParser::ParseArguments" : "is not single in TermArgumentParser::ParseArguments"); if (!isQuakeMode && isSingleApp) { Dtk::Widget::moveToCenter(mainWindow); } //-----------------------------------------------------------------------------/ return res; } //-- bool TermArgumentParser::initDBus() { //用于雷神窗口通信的DBus QDBusConnection conn = QDBusConnection::sessionBus(); m_quakeTerminalProxy = new QuakeTerminalProxy(this); QuakeTerminalAdapter *adapter = new QuakeTerminalAdapter(m_quakeTerminalProxy); Q_UNUSED(adapter); if (!conn.registerService(kQuakeTerminalService) || !conn.registerObject(kQuakeTerminalIface, m_quakeTerminalProxy)) { qDebug() << "Failed to register dbus" << qApp->applicationPid(); showOrHideQuakeTerminal(); return false; } qDebug() << "Register dbus service successfully" << qApp->applicationPid(); return true; } void TermArgumentParser::showOrHideQuakeTerminal() { QDBusMessage msg = QDBusMessage::createMethodCall(kQuakeTerminalService, kQuakeTerminalIface, kQuakeTerminalService, "ShowOrHide"); QDBusMessage response = QDBusConnection::sessionBus().call(msg); if (response.type() == QDBusMessage::ReplyMessage) { qDebug() << "call ShowOrHide Success!"; } else { qDebug() << "call ShowOrHide Fail!" << response.errorMessage(); } } deepin-terminal-5.2.11/src/quaketerminal/termargumentparser.h000066400000000000000000000013131370157770500244200ustar00rootroot00000000000000#ifndef TERMARGUMENTPARSER_H #define TERMARGUMENTPARSER_H #include "mainwindow.h" #include "termproperties.h" #include class QuakeTerminalProxy; class TermArgumentParser : public QObject { Q_OBJECT public: explicit TermArgumentParser(QObject *parent = nullptr); ~TermArgumentParser() override; bool initDBus(); //不用了 bool parseArguments(MainWindow *mainWindow, bool isQuakeMode); //不用了 bool ParseArguments(MainWindow *mainWindow, bool isQuakeMode, bool isSingleApp); //-- void showOrHideQuakeTerminal(); private: MainWindow *m_mainWindow = nullptr; QuakeTerminalProxy *m_quakeTerminalProxy = nullptr; }; #endif // TERMARGUMENTPARSER_H deepin-terminal-5.2.11/src/remotemanage/000077500000000000000000000000001370157770500201245ustar00rootroot00000000000000deepin-terminal-5.2.11/src/remotemanage/remotemanagementpanel.cpp000066400000000000000000000104061370157770500252010ustar00rootroot00000000000000#include "remotemanagementpanel.h" #include "serverconfigitem.h" #include "shortcutmanager.h" #include "service.h" #include RemoteManagementPanel::RemoteManagementPanel(QWidget *parent) : CommonPanel(parent) { initUI(); } void RemoteManagementPanel::refreshPanel() { clearSearchInfo(); //--added byq qinyaning(nyq) to solve the show when not exist the server-config.conf--// // ServerConfigManager::instance()->initServerConfig(); //---------------------------// m_listWidget->refreshAllDatas(); refreshSearchState(); } void RemoteManagementPanel::refreshSearchState() { if (m_listWidget->count() >= 2) { /************************ Add by m000743 sunchengxi 2020-04-22:搜索显示异常 Begin************************/ m_searchEdit->clearEdit(); /************************ Add by m000743 sunchengxi 2020-04-22:搜索显示异常 End ************************/ m_searchEdit->show(); } else { m_searchEdit->hide(); } } void RemoteManagementPanel::showCurSearchResult() { QString strTxt = m_searchEdit->text(); if (strTxt.isEmpty()) return; emit showSearchPanel(strTxt); } void RemoteManagementPanel::showAddServerConfigDlg() { // 弹窗显示 Service::instance()->setIsDialogShow(window(), true); ServerConfigOptDlg *dlg = new ServerConfigOptDlg(ServerConfigOptDlg::SCT_ADD, nullptr, this); connect(dlg, &ServerConfigOptDlg::finished, this, [ = ](int result) { // 弹窗隐藏或消失 Service::instance()->setIsDialogShow(window(), false); if (result == QDialog::Accepted) { QModelIndex index = m_listWidget->currentIndex(dlg->getServerName()); m_listWidget->scrollTo(index); } }); dlg->show(); } void RemoteManagementPanel::initUI() { this->setBackgroundRole(QPalette::Base); this->setAutoFillBackground(true); m_searchEdit = new DSearchEdit(this); m_listWidget = new ServerConfigList(this); m_pushButton = new DPushButton(this); m_searchEdit->setClearButtonEnabled(true); m_listWidget->setSelectionMode(QAbstractItemView::NoSelection); m_listWidget->setVerticalScrollMode(QAbstractItemView::ScrollMode::ScrollPerItem); m_listWidget->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn); m_listWidget->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); m_listWidget->setSizePolicy(QSizePolicy::Policy::Expanding, QSizePolicy::Policy::Expanding); m_pushButton->setFixedHeight(36); m_pushButton->setText(tr("Add Server")); QHBoxLayout *hlayout = new QHBoxLayout(); hlayout->setContentsMargins(0, 0, 0, 0); hlayout->addSpacing(10); hlayout->addWidget(m_searchEdit); hlayout->addSpacing(10); hlayout->setSpacing(0); hlayout->setMargin(0); QHBoxLayout *btnLayout = new QHBoxLayout(); btnLayout->setContentsMargins(0, 0, 0, 0); btnLayout->addSpacing(10); btnLayout->addWidget(m_pushButton); btnLayout->addSpacing(10); btnLayout->setSpacing(0); btnLayout->setMargin(0); QVBoxLayout *vlayout = new QVBoxLayout(); vlayout->setContentsMargins(0, 0, 0, 0); vlayout->addSpacing(10); vlayout->addLayout(hlayout); vlayout->addWidget(m_listWidget); vlayout->addLayout(btnLayout); vlayout->addSpacing(12); vlayout->setMargin(0); vlayout->setSpacing(10); setLayout(vlayout); connect(m_searchEdit, &DSearchEdit::returnPressed, this, &RemoteManagementPanel::showCurSearchResult); connect(m_pushButton, &DPushButton::clicked, this, &RemoteManagementPanel::showAddServerConfigDlg); connect(m_listWidget, &ServerConfigList::itemClicked, this, &RemoteManagementPanel::listItemClicked); connect(m_listWidget, &ServerConfigList::groupClicked, this, &RemoteManagementPanel::showServerConfigGroupPanel); connect(m_listWidget, &ServerConfigList::listItemCountChange, this, &RemoteManagementPanel::refreshSearchState); connect(ServerConfigManager::instance(), &ServerConfigManager::refreshList, this, [ = ]() { if (m_isShow) { refreshPanel(); } }); } void RemoteManagementPanel::listItemClicked(ServerConfig *curItemServer) { if (nullptr != curItemServer) { emit doConnectServer(curItemServer); } else { qDebug() << "remote item from panel is null"; } } deepin-terminal-5.2.11/src/remotemanage/remotemanagementpanel.h000066400000000000000000000014441370157770500246500ustar00rootroot00000000000000#ifndef REMOTEMANAGEMENTPANEL_H #define REMOTEMANAGEMENTPANEL_H #include "commonpanel.h" #include "serverconfiglist.h" #include "serverconfigoptdlg.h" #include class RemoteManagementPanel : public CommonPanel { Q_OBJECT public: explicit RemoteManagementPanel(QWidget *parent = nullptr); void refreshPanel(); signals: void showSearchPanel(const QString &strFilter); void showServerConfigGroupPanel(const QString &strGroup); void doConnectServer(ServerConfig *curItemServer); public slots: void showCurSearchResult(); void showAddServerConfigDlg(); void listItemClicked(ServerConfig *curItemServer); void refreshSearchState(); private: void initUI(); private: ServerConfigList *m_listWidget = nullptr; }; #endif // REMOTEMANAGEMENTPANEL_H deepin-terminal-5.2.11/src/remotemanage/remotemanagementplugn.cpp000066400000000000000000000205341370157770500252320ustar00rootroot00000000000000#include "remotemanagementplugn.h" #include "mainwindow.h" #include "utils.h" #include "service.h" #include "../views/termwidget.h"//added by nyq #include #include RemoteManagementPlugn::RemoteManagementPlugn(QObject *parent) : MainWindowPluginInterface(parent) { m_pluginName = "Remote Management"; } void RemoteManagementPlugn::initPlugin(MainWindow *mainWindow) { m_mainWindow = mainWindow; initRemoteManagementTopPanel(); connect(m_mainWindow, &MainWindow::showPluginChanged, this, [ = ](const QString name) { if (MainWindow::PLUGIN_TYPE_REMOTEMANAGEMENT != name) { getRemoteManagementTopPanel()->hideAnim(); } else { /******** Add by nt001000 renfeixiang 2020-05-18:修改雷神窗口太小时,远程连接界面使用不方便,将雷神窗口变大适应正常的远程连接界面 Begin***************/ if (m_mainWindow->isQuakeMode() && m_mainWindow->height() < 220) { m_mainWindow->resize(m_mainWindow->width(), 220); //首先设置雷神界面的大小 m_mainWindow->showPlugin(MainWindow::PLUGIN_TYPE_REMOTEMANAGEMENT);//重新打开远程连接界面,当前流程结束 return; } /******** Add by nt001000 renfeixiang 2020-05-18:修改雷神窗口太小时,远程连接界面使用不方便,将雷神窗口变大适应正常的远程连接界面 End***************/ getRemoteManagementTopPanel()->show(); } }); connect(m_mainWindow, &MainWindow::quakeHidePlugin, this, [ = ]() { getRemoteManagementTopPanel()->hide(); }); } QAction *RemoteManagementPlugn::titlebarMenu(MainWindow *mainWindow) { QAction *remoteManagementAction(new QAction(tr("Remote management"), mainWindow)); connect(remoteManagementAction, &QAction::triggered, mainWindow, [mainWindow]() { mainWindow->showPlugin(MainWindow::PLUGIN_TYPE_REMOTEMANAGEMENT); }); return remoteManagementAction; } RemoteManagementTopPanel *RemoteManagementPlugn::getRemoteManagementTopPanel() { if (nullptr == m_remoteManagementTopPanel) { initRemoteManagementTopPanel(); } return m_remoteManagementTopPanel; } void RemoteManagementPlugn::initRemoteManagementTopPanel() { m_remoteManagementTopPanel = new RemoteManagementTopPanel(m_mainWindow->centralWidget()); connect(m_remoteManagementTopPanel, &RemoteManagementTopPanel::doConnectServer, this, &RemoteManagementPlugn::doCennectServer, Qt::QueuedConnection); } void RemoteManagementPlugn::doCennectServer(ServerConfig *curServer) { if (nullptr != curServer) { QString shellFile = createShellFile(curServer); QString strTxt = "expect -f " + shellFile + "\n"; //--added by qinyaning(nyq) to solve the probelm which Connecting to the remote server /*does not connect to the remote server directly in the new TAB. time: 2020.4.13 18:15 * */ if (m_mainWindow->currentPage()->currentTerminal()->hasRunningProcess()) { m_mainWindow->addTab(m_mainWindow->currentPage()->createCurrentTerminalProperties(), true); } //--------------------------------// /******** Modify by m000714 daizhengwen 2020-04-30: 将当前还没执行的命令清空****************/ m_mainWindow->focusCurrentPage(); m_mainWindow->pressCtrlU(); m_mainWindow->sleep(100); /********************* Modify by m000714 daizhengwen End ************************/ m_mainWindow->currentPage()->sendTextToCurrentTerm(strTxt); // 等待连接 QTimer::singleShot(100, this, [ = ]() { TermWidget *term = m_mainWindow->currentPage()->currentTerminal(); // 判断是否连接服务器 if (!term->isInRemoteServer()) { // 没有连接上 qDebug() << "disconnect to server"; return; } // 标记此term连接远程 term->setIsConnectRemote(true); qDebug() << "connect to server"; // 编码 setRemoteEncode(curServer->m_encoding); // 退格键 setBackspaceKey(term, curServer->m_backspaceKey); // 删除键 setDeleteKey(term, curServer->m_deleteKey); }); } /******** Modify by ut000610 daizhengwen 2020-06-04: 点击连接服务器后,隐藏列表,焦点回到主窗口****************/ m_mainWindow->showPlugin(MainWindow::PLUGIN_TYPE_NONE); QTimer::singleShot(100, this, [&]() { if (m_mainWindow->isActiveWindow()) { m_mainWindow->focusCurrentPage(); } }); /********************* Modify by ut000610 daizhengwen End ************************/ } QString RemoteManagementPlugn::createShellFile(ServerConfig *curServer) { QFile sourceFile(":/other/ssh_login.sh"); QString fileString; if (sourceFile.open(QIODevice::ReadOnly)) { fileString = sourceFile.readAll(); sourceFile.close(); } fileString.replace("<>", curServer->m_userName); fileString.replace("<>", curServer->m_address.trimmed()); fileString.replace("<>", curServer->m_port); if (curServer->m_privateKey.isNull() || curServer->m_privateKey.isEmpty()) { fileString.replace("<>", ""); QRegExp rx("([\"$\\\\])"); QString password = curServer->m_password; password.replace(rx, "\\\\\\1"); fileString.replace("<>", password); fileString.replace("<>", "no"); } else { fileString.replace("<>", QString("-i " + curServer->m_privateKey)); fileString.replace("<>", ""); fileString.replace("<>", "yes"); } QString path = curServer->m_path; QString command = curServer->m_command; QString remote_command = "echo " + tr("Make sure that rz and sz commands have been installed in the server before right clicking to upload and download files.") + " && "; if (!path.isNull() && !path.isEmpty()) { remote_command = remote_command + "cd " + path + " && "; } if (!command.isNull() && !command.isEmpty()) { remote_command = remote_command + command + " && "; } fileString.replace("<>", remote_command); QString toFileStr = "/tmp/terminal-" + Utils::getRandString(); QFile toFile(toFileStr); toFile.open(QIODevice::WriteOnly | QIODevice::Text); toFile.write(fileString.toUtf8()); toFile.close(); return toFileStr; } void RemoteManagementPlugn::hidePlugn() { if (m_remoteManagementTopPanel && m_remoteManagementTopPanel->isVisible()) { m_remoteManagementTopPanel->hide(); } } void RemoteManagementPlugn::setRemoteEncode(QString encode) { TermWidget *term = m_mainWindow->currentPage()->currentTerminal(); if (!encode.isNull() && !encode.isEmpty()) { // 设置当前窗口的编码 term->setTextCodec(QTextCodec::codecForName(encode.toLocal8Bit())); qDebug() << "Remote encode " << encode; } // 记录远程编码 term->setRemoteEncode(encode); // 切换编码列表的编码 emit Service::instance()->checkEncode(encode); } void RemoteManagementPlugn::setBackspaceKey(TermWidget *term, QString backspaceKey) { if (backspaceKey == "control-h") { term->setBackspaceMode(EraseMode_Control_H); } else if (backspaceKey == "auto") { term->setBackspaceMode(EraseMode_Auto); } else if (backspaceKey == "escape-sequence") { term->setBackspaceMode(EraseMode_Escape_Sequeue); } else if (backspaceKey == "ascii-del") { term->setBackspaceMode(EraseMode_Ascii_Delete); } else if (backspaceKey == "tty") { term->setBackspaceMode(EraseMode_TTY); } qDebug() << "backspace mode " << backspaceKey; } void RemoteManagementPlugn::setDeleteKey(TermWidget *term, QString deleteKey) { if (deleteKey == "control-h") { term->setDeleteMode(EraseMode_Control_H); } else if (deleteKey == "auto") { term->setDeleteMode(EraseMode_Auto); } else if (deleteKey == "escape-sequence") { term->setDeleteMode(EraseMode_Escape_Sequeue); } else if (deleteKey == "ascii-del") { term->setDeleteMode(EraseMode_Ascii_Delete); } else if (deleteKey == "tty") { term->setDeleteMode(EraseMode_TTY); } qDebug() << "delete mode " << deleteKey; } deepin-terminal-5.2.11/src/remotemanage/remotemanagementplugn.h000066400000000000000000000022061370157770500246730ustar00rootroot00000000000000#ifndef REMOTEMANAGEMENTPLUGN_H #define REMOTEMANAGEMENTPLUGN_H #include "mainwindowplugininterface.h" #include "remotemanagementtoppanel.h" #include #include class TermWidget; class MainWindow; class RemoteManagementPlugn : public MainWindowPluginInterface { Q_OBJECT public: explicit RemoteManagementPlugn(QObject *parent = nullptr); void initPlugin(MainWindow *mainWindow) override; QAction *titlebarMenu(MainWindow *mainWindow) override; RemoteManagementTopPanel *getRemoteManagementTopPanel(); void initRemoteManagementTopPanel(); QString createShellFile(ServerConfig *curServer); void hidePlugn(); // 设置远程编码 void setRemoteEncode(QString encode); // 设置退格模式 void setBackspaceKey(TermWidget *term, QString backspaceKey); // 设置删除模式 void setDeleteKey(TermWidget *term, QString deleteKey); signals: void doHide(); public slots: void doCennectServer(ServerConfig *curServer); private: MainWindow *m_mainWindow = nullptr; RemoteManagementTopPanel *m_remoteManagementTopPanel = nullptr; }; #endif // REMOTEMANAGEMENTPLUGN_H deepin-terminal-5.2.11/src/remotemanage/remotemanagementsearchpanel.cpp000066400000000000000000000112741370157770500263730ustar00rootroot00000000000000#include "remotemanagementsearchpanel.h" #include "serverconfigmanager.h" #include "utils.h" #include #include #include RemoteManagementSearchPanel::RemoteManagementSearchPanel(QWidget *parent) : CommonPanel(parent) { initUI(); } void RemoteManagementSearchPanel::initUI() { this->setBackgroundRole(QPalette::Base); this->setAutoFillBackground(true); m_backButton = new DIconButton(this); m_backButton->setIcon(DStyle::StandardPixmap::SP_ArrowLeave); m_backButton->setFixedSize(QSize(40, 40)); m_backButton->setFocusPolicy(Qt::NoFocus); m_listWidget = new ServerConfigList(this); m_label = new DLabel(this); m_label->setAlignment(Qt::AlignCenter); // 字体颜色随主题变化而变化 DPalette palette = m_label->palette(); QColor color; if (DApplicationHelper::instance()->themeType() == DApplicationHelper::DarkType) { color = QColor::fromRgb(192, 198, 212, 102); } else { color = QColor::fromRgb(85, 85, 85, 102); } palette.setBrush(QPalette::Text, color); m_label->setPalette(palette); m_listWidget->setSelectionMode(QAbstractItemView::NoSelection); m_listWidget->setVerticalScrollMode(QAbstractItemView::ScrollMode::ScrollPerItem); m_listWidget->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn); m_listWidget->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); m_listWidget->setSizePolicy(QSizePolicy::Policy::Expanding, QSizePolicy::Policy::Expanding); QHBoxLayout *hlayout = new QHBoxLayout(); hlayout->addSpacing(10); hlayout->addWidget(m_backButton); // hlayout->addSpacing(10); hlayout->addWidget(m_label, 0, Qt::AlignCenter); // hlayout->addStretch(); hlayout->setSpacing(0); hlayout->setMargin(0); QVBoxLayout *vlayout = new QVBoxLayout(); vlayout->addSpacing(10); vlayout->addLayout(hlayout); vlayout->addWidget(m_listWidget); vlayout->setMargin(0); vlayout->setSpacing(10); setLayout(vlayout); connect(m_backButton, &DIconButton::clicked, this, &RemoteManagementSearchPanel::showPreviousPanel); // connect(m_listWidget, &ServerConfigList::itemClicked, this, &RemoteManagementSearchPanel::listItemClicked); connect(m_listWidget, &ServerConfigList::groupClicked, this, &RemoteManagementSearchPanel::showServerConfigGroupPanelFromSearch); connect(ServerConfigManager::instance(), &ServerConfigManager::refreshList, this, [ = ]() { if (m_isShow) { if (m_isGroupOrNot) { refreshDataByGroupAndFilter(m_strGroupName, m_strFilter); } else { refreshDataByFilter(m_strFilter); } } }); // 字体颜色随主题变化变化 connect(DApplicationHelper::instance(), &DGuiApplicationHelper::themeTypeChanged, m_label, [ = ](DGuiApplicationHelper::ColorType themeType) { DPalette palette = m_label->palette(); QColor color; if (themeType == DApplicationHelper::DarkType) { color = QColor::fromRgb(192, 198, 212, 102); } else { color = QColor::fromRgb(85, 85, 85, 102); } palette.setBrush(QPalette::Text, color); m_label->setPalette(palette); }); } void RemoteManagementSearchPanel::refreshDataByGroupAndFilter(const QString &strGroup, const QString &strFilter) { setSearchFilter(strFilter); m_isGroupOrNot = true; m_strGroupName = strGroup; m_strFilter = strFilter; m_listWidget->clearData(); m_listWidget->refreshDataByGroupAndFilter(strGroup, strFilter); } void RemoteManagementSearchPanel::refreshDataByFilter(const QString &strFilter) { setSearchFilter(strFilter); m_isGroupOrNot = false; m_strFilter = strFilter; m_listWidget->clearData(); m_listWidget->refreshDataByFilter(strFilter); } void RemoteManagementSearchPanel::showPreviousPanel() { if (m_previousPanel == REMOTE_MANAGEMENT_PANEL) { emit showRemoteManagementPanel(); } if (m_previousPanel == REMOTE_MANAGEMENT_GROUP) { emit showServerConfigGroupPanel(m_strGroupName); } } void RemoteManagementSearchPanel::setPreviousPanelType(RemoteManagementPanelType type) { m_previousPanel = type; } void RemoteManagementSearchPanel::listItemClicked(ServerConfig *curItemServer) { if (nullptr != curItemServer) { emit doConnectServer(curItemServer); } else { qDebug() << "remote item is null"; } } void RemoteManagementSearchPanel::setSearchFilter(const QString &filter) { m_strFilter = filter; QString showText = filter; showText = Utils::getElidedText(m_label->font(), showText, ITEMMAXWIDTH, Qt::ElideMiddle); m_label->setText(QString("%1:%2").arg(tr("Search"), showText)); } deepin-terminal-5.2.11/src/remotemanage/remotemanagementsearchpanel.h000066400000000000000000000031571370157770500260410ustar00rootroot00000000000000#ifndef REMOTEMANAGEMENTSEARCHPANEL_H #define REMOTEMANAGEMENTSEARCHPANEL_H #include "commonpanel.h" #include "serverconfiglist.h" #include class RemoteManagementSearchPanel : public CommonPanel { Q_OBJECT public: enum RemoteManagementPanelType { REMOTE_MANAGEMENT_PANEL = 0, //远程管理主界面,对应RemoteManagementPanel类 REMOTE_MANAGEMENT_GROUP, //远程管理分组面,对应ServerConfigGroupPanel类 REMOTE_MANAGEMENT_SERARCH, //远程管理搜索结果界面,对应RemoteManagementSearchPanel类 }; explicit RemoteManagementSearchPanel(QWidget *parent = nullptr); void refreshDataByGroupAndFilter(const QString &strGroup, const QString &strFilter); void refreshDataByFilter(const QString &strFilter); void setPreviousPanelType(RemoteManagementPanelType type); signals: void showServerConfigGroupPanelFromSearch(const QString &strGroup); void doConnectServer(ServerConfig *curItemServer); void showRemoteManagementPanel(); void showServerConfigGroupPanel(const QString &strGroup); public slots: void listItemClicked(ServerConfig *curItemServer); //显示调用本搜索页面的前置页面 void showPreviousPanel(); private: void initUI(); void setSearchFilter(const QString &filter); private: ServerConfigList *m_listWidget; RemoteManagementPanelType m_previousPanel; //用来保存调用当前搜索结果页的对象类型 QString m_strGroupName; QString m_strFilter; // 判断是组内搜索还是组外搜索 bool m_isGroupOrNot = false; }; #endif // REMOTEMANAGEMENTSEARCHPANEL_H deepin-terminal-5.2.11/src/remotemanage/remotemanagementtoppanel.cpp000066400000000000000000000304561370157770500257330ustar00rootroot00000000000000#include "remotemanagementtoppanel.h" #include #include const int animationDuration = 300; RemoteManagementTopPanel::RemoteManagementTopPanel(QWidget *parent) : RightPanel(parent) { m_remoteManagementPanel = new RemoteManagementPanel(this); // connect(this, &RemoteManagementTopPanel::focusOut, this, &RightPanel::hideAnim); connect(m_remoteManagementPanel, &RemoteManagementPanel::showServerConfigGroupPanel, this, &RemoteManagementTopPanel::showServerConfigGroupPanelFromRemotePanel); connect(m_remoteManagementPanel, &RemoteManagementPanel::showSearchPanel, this, &RemoteManagementTopPanel::showSearchPanelFromRemotePanel); connect( m_remoteManagementPanel, &RemoteManagementPanel::doConnectServer, this, &RemoteManagementTopPanel::doConnectServer, Qt::QueuedConnection); m_serverConfigGroupPanel = new ServerConfigGroupPanel(this); connect(m_serverConfigGroupPanel, &ServerConfigGroupPanel::showRemoteManagementPanel, this, &RemoteManagementTopPanel::showRemotePanelFromGroupPanel); connect(m_serverConfigGroupPanel, &ServerConfigGroupPanel::showSearchResult, this, &RemoteManagementTopPanel::showSearchPanelFromGroupPanel); connect( m_serverConfigGroupPanel, &ServerConfigGroupPanel::doConnectServer, this, &RemoteManagementTopPanel::doConnectServer, Qt::QueuedConnection); m_remoteManagementSearchPanel = new RemoteManagementSearchPanel(this); connect(m_remoteManagementSearchPanel, &RemoteManagementSearchPanel::showRemoteManagementPanel, this, &RemoteManagementTopPanel::showRemoteManagementPanelFromSearchPanel); connect(m_remoteManagementSearchPanel, &RemoteManagementSearchPanel::showServerConfigGroupPanelFromSearch, this, &RemoteManagementTopPanel::slotShowGroupPanelFromSearchPanel); connect(m_remoteManagementSearchPanel, &RemoteManagementSearchPanel::showServerConfigGroupPanel, this, &RemoteManagementTopPanel::showGroupPanelFromSearchPanel); connect( m_remoteManagementSearchPanel, &RemoteManagementSearchPanel::doConnectServer, this, &RemoteManagementTopPanel::doConnectServer, Qt::QueuedConnection); m_serverConfigGroupPanel->hide(); m_remoteManagementSearchPanel->hide(); } void RemoteManagementTopPanel::showSearchPanelFromRemotePanel(const QString &strFilter) { qDebug() << __FUNCTION__; //--added by qinyaning(nyq) to solve the repeat history recoed--// m_remoteManagementPanel->clearSearchInfo(); m_serverConfigGroupPanel->clearSearchInfo(); //--------------------------------------------------------------// m_remoteManagementSearchPanel->resize(size()); m_remoteManagementSearchPanel->setPreviousPanelType(RemoteManagementSearchPanel::REMOTE_MANAGEMENT_PANEL); m_remoteManagementSearchPanel->refreshDataByFilter(strFilter); animationPrepare(m_serverConfigGroupPanel, m_remoteManagementSearchPanel); QPropertyAnimation *animation = new QPropertyAnimation(m_remoteManagementPanel, "geometry"); connect(animation, &QPropertyAnimation::finished, m_remoteManagementPanel, &QWidget::hide); connect(animation, &QPropertyAnimation::finished, animation, &QPropertyAnimation::deleteLater); QPropertyAnimation *animation1 = new QPropertyAnimation(m_remoteManagementSearchPanel, "geometry"); connect(animation1, &QPropertyAnimation::finished, animation1, &QPropertyAnimation::deleteLater); panelRightToLeft(animation, animation1); } void RemoteManagementTopPanel::showRemotePanelFromGroupPanel() { qDebug() << __FUNCTION__; //--------------------------------------------------------------// m_remoteManagementPanel->resize(size()); m_remoteManagementPanel->refreshPanel(); animationPrepare(m_remoteManagementSearchPanel, m_remoteManagementPanel); QPropertyAnimation *animation = new QPropertyAnimation(m_serverConfigGroupPanel, "geometry"); connect(animation, &QPropertyAnimation::finished, m_serverConfigGroupPanel, &QWidget::hide); connect(animation, &QPropertyAnimation::finished, animation, &QPropertyAnimation::deleteLater); QPropertyAnimation *animation1 = new QPropertyAnimation(m_remoteManagementPanel, "geometry"); connect(animation1, &QPropertyAnimation::finished, animation1, &QPropertyAnimation::deleteLater); panelLeftToRight(animation, animation1); } void RemoteManagementTopPanel::show() { RightPanel::show(); m_remoteManagementPanel->resize(size()); m_remoteManagementPanel->move(0, 0); m_remoteManagementPanel->show(); m_remoteManagementPanel->m_isShow = true; m_remoteManagementPanel->refreshPanel(); m_serverConfigGroupPanel->hide(); m_serverConfigGroupPanel->m_isShow = false; m_remoteManagementSearchPanel->hide(); m_remoteManagementSearchPanel->m_isShow = false; } /******** Modify by nt001000 renfeixiang 2020-05-14:修改远程管理界面,在Alt+F2时,隐藏在显示,高度变大问题 Begin***************/ //void RemoteManagementTopPanel::resizeEvent(QResizeEvent *event) //{ // Q_UNUSED(event) // m_remoteManagementPanel->resize(size()); //} /******** Modify by nt001000 renfeixiang 2020-05-14:修改远程管理界面,在Alt+F2时,隐藏在显示,高度变大问题 End***************/ void RemoteManagementTopPanel::showServerConfigGroupPanelFromRemotePanel(const QString &strGroup) { qDebug() << __FUNCTION__; m_serverConfigGroupPanel->resize(size()); m_serverConfigGroupPanel->refreshData(strGroup); animationPrepare(m_remoteManagementSearchPanel, m_serverConfigGroupPanel); QPropertyAnimation *animation = new QPropertyAnimation(m_remoteManagementPanel, "geometry"); connect(animation, &QPropertyAnimation::finished, m_remoteManagementPanel, &QWidget::hide); connect(animation, &QPropertyAnimation::finished, animation, &QPropertyAnimation::deleteLater); QPropertyAnimation *animation1 = new QPropertyAnimation(m_serverConfigGroupPanel, "geometry"); connect(animation1, &QPropertyAnimation::finished, animation1, &QPropertyAnimation::deleteLater); panelRightToLeft(animation, animation1); } void RemoteManagementTopPanel::showSearchPanelFromGroupPanel(const QString &strGroup, const QString &strFilter) { qDebug() << __FUNCTION__; m_remoteManagementSearchPanel->resize(size()); m_remoteManagementSearchPanel->setPreviousPanelType(RemoteManagementSearchPanel::REMOTE_MANAGEMENT_GROUP); m_remoteManagementSearchPanel->refreshDataByGroupAndFilter(strGroup, strFilter); animationPrepare(m_remoteManagementPanel, m_remoteManagementSearchPanel); QPropertyAnimation *animation = new QPropertyAnimation(m_serverConfigGroupPanel, "geometry"); connect(animation, &QPropertyAnimation::finished, m_serverConfigGroupPanel, &QWidget::hide); connect(animation, &QPropertyAnimation::finished, animation, &QPropertyAnimation::deleteLater); QPropertyAnimation *animation1 = new QPropertyAnimation(m_remoteManagementSearchPanel, "geometry"); connect(animation1, &QPropertyAnimation::finished, animation1, &QPropertyAnimation::deleteLater); panelRightToLeft(animation, animation1); } void RemoteManagementTopPanel::showRemoteManagementPanelFromSearchPanel() { qDebug() << __FUNCTION__; //--------------------------------------------------------------// m_remoteManagementPanel->resize(size()); m_remoteManagementPanel->refreshPanel(); animationPrepare(m_serverConfigGroupPanel, m_remoteManagementPanel); QPropertyAnimation *animation = new QPropertyAnimation(m_remoteManagementSearchPanel, "geometry"); connect(animation, &QPropertyAnimation::finished, m_remoteManagementSearchPanel, &QWidget::hide); connect(animation, &QPropertyAnimation::finished, animation, &QPropertyAnimation::deleteLater); QPropertyAnimation *animation1 = new QPropertyAnimation(m_remoteManagementPanel, "geometry"); connect(animation1, &QPropertyAnimation::finished, animation1, &QPropertyAnimation::deleteLater); panelLeftToRight(animation, animation1); } void RemoteManagementTopPanel::slotShowGroupPanelFromSearchPanel(const QString &strGroup) { qDebug() << __FUNCTION__; // m_remoteManagementPanel->hide(); // m_remoteManagementPanel->m_isShow = false; //--added by qinyaning(nyq) to solve the repeat history recoed--// // m_serverConfigGroupPanel->clearSearchInfo(); //--------------------------------------------------------------// m_serverConfigGroupPanel->resize(size()); m_serverConfigGroupPanel->refreshData(strGroup); // m_serverConfigGroupPanel->show(); // m_serverConfigGroupPanel->m_isShow = true; animationPrepare(m_remoteManagementPanel, m_serverConfigGroupPanel); QPropertyAnimation *animation = new QPropertyAnimation(m_remoteManagementSearchPanel, "geometry"); connect(animation, &QPropertyAnimation::finished, m_remoteManagementSearchPanel, &QWidget::hide); connect(animation, &QPropertyAnimation::finished, animation, &QPropertyAnimation::deleteLater); QPropertyAnimation *animation1 = new QPropertyAnimation(m_serverConfigGroupPanel, "geometry"); connect(animation1, &QPropertyAnimation::finished, animation1, &QPropertyAnimation::deleteLater); panelRightToLeft(animation, animation1); } void RemoteManagementTopPanel::animationPrepare(CommonPanel *hidePanel, CommonPanel *showPanel) { hidePanel->hide(); hidePanel->m_isShow = false; hidePanel->clearSearchInfo(); showPanel->show(); showPanel->m_isShow = true; m_remoteManagementPanel->refreshPanel(); } void RemoteManagementTopPanel::panelLeftToRight(QPropertyAnimation *animation, QPropertyAnimation *animation1) { animation->setDuration(animationDuration); animation->setEasingCurve(QEasingCurve::OutQuad); QRect rect = geometry(); animation->setStartValue(QRect(0, rect.y(), rect.width(), rect.height())); animation->setEndValue(QRect(rect.width(), rect.y(), rect.width(), rect.height())); animation1->setDuration(animationDuration); animation1->setEasingCurve(QEasingCurve::OutQuad); animation1->setStartValue(QRect(-rect.width(), rect.y(), rect.width(), rect.height())); animation1->setEndValue(QRect(0, rect.y(), rect.width(), rect.height())); QParallelAnimationGroup *group = new QParallelAnimationGroup(this); group->addAnimation(animation); group->addAnimation(animation1); // 已验证:这个设定,会释放group以及所有组内动画。 group->start(QAbstractAnimation::DeleteWhenStopped); } void RemoteManagementTopPanel::panelRightToLeft(QPropertyAnimation *animation, QPropertyAnimation *animation1) { animation->setDuration(animationDuration); animation->setEasingCurve(QEasingCurve::OutQuad); QRect rect = geometry(); animation->setStartValue(QRect(0, rect.y(), rect.width(), rect.height())); animation->setEndValue(QRect(-rect.width(), rect.y(), rect.width(), rect.height())); animation1->setDuration(animationDuration); animation1->setEasingCurve(QEasingCurve::OutQuad); animation1->setStartValue(QRect(rect.width(), rect.y(), rect.width(), rect.height())); animation1->setEndValue(QRect(0, rect.y(), rect.width(), rect.height())); QParallelAnimationGroup *group = new QParallelAnimationGroup(this); group->addAnimation(animation); group->addAnimation(animation1); // 已验证:这个设定,会释放group以及所有组内动画。 group->start(QAbstractAnimation::DeleteWhenStopped); } void RemoteManagementTopPanel::showGroupPanelFromSearchPanel(const QString &strGroup) { qDebug() << __FUNCTION__; //--------------------------------------------------------------// m_serverConfigGroupPanel->resize(size()); m_serverConfigGroupPanel->refreshData(strGroup); animationPrepare(m_remoteManagementPanel, m_serverConfigGroupPanel); QPropertyAnimation *animation = new QPropertyAnimation(m_remoteManagementSearchPanel, "geometry"); connect(animation, &QPropertyAnimation::finished, m_remoteManagementSearchPanel, &QWidget::hide); connect(animation, &QPropertyAnimation::finished, animation, &QPropertyAnimation::deleteLater); QPropertyAnimation *animation1 = new QPropertyAnimation(m_serverConfigGroupPanel, "geometry"); connect(animation1, &QPropertyAnimation::finished, animation1, &QPropertyAnimation::deleteLater); panelLeftToRight(animation, animation1); } deepin-terminal-5.2.11/src/remotemanage/remotemanagementtoppanel.h000066400000000000000000000035371370157770500254000ustar00rootroot00000000000000#ifndef REMOTEMANAGEMENTTOPPANEL_H #define REMOTEMANAGEMENTTOPPANEL_H #include "rightpanel.h" #include "commonpanel.h" #include "remotemanagementpanel.h" #include "serverconfiggrouppanel.h" #include "remotemanagementsearchpanel.h" #include #include class RemoteManagementTopPanel : public RightPanel { Q_OBJECT public: explicit RemoteManagementTopPanel(QWidget *parent = nullptr); void show(); protected: /******** Modify by nt001000 renfeixiang 2020-05-14:修改远程管理界面,在Alt+F2时,隐藏在显示,高度变大问题 Begin***************/ //void resizeEvent(QResizeEvent *event) override; /******** Modify by nt001000 renfeixiang 2020-05-14:修改远程管理界面,在Alt+F2时,隐藏在显示,高度变大问题 End***************/ signals: void focusOut(); void doConnectServer(ServerConfig *curServer); public slots: void showSearchPanelFromRemotePanel(const QString &strFilter); void showServerConfigGroupPanelFromRemotePanel(const QString &strGroup); void showRemotePanelFromGroupPanel(); void showSearchPanelFromGroupPanel(const QString &strGroup, const QString &strFilter); void showGroupPanelFromSearchPanel(const QString &strGroup); void showRemoteManagementPanelFromSearchPanel(); void slotShowGroupPanelFromSearchPanel(const QString &strGroup); private: void animationPrepare(CommonPanel *hidePanel, CommonPanel *showPanel); void panelLeftToRight(QPropertyAnimation *animation, QPropertyAnimation *animation1); void panelRightToLeft(QPropertyAnimation *animation, QPropertyAnimation *animation1); RemoteManagementPanel *m_remoteManagementPanel = nullptr; ServerConfigGroupPanel *m_serverConfigGroupPanel = nullptr; RemoteManagementSearchPanel *m_remoteManagementSearchPanel = nullptr; }; #endif // REMOTEMANAGEMENTTOPPANEL_H deepin-terminal-5.2.11/src/remotemanage/serverconfigdelegate.cpp000066400000000000000000000147401370157770500250250ustar00rootroot00000000000000#include "serverconfigdelegate.h" #include "serverconfigitemmodel.h" #include "utils.h" #include #include #include #include #include #include #include ServerConfigDelegate::ServerConfigDelegate(QAbstractItemView *parent) : DStyledItemDelegate(parent) , m_parentView(parent) { } void ServerConfigDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const { if (index.isValid()) { painter->save(); painter->setRenderHint(QPainter::Antialiasing, true); QVariant varDisplay = index.data(Qt::DisplayRole); ServerConfigItemData itemData = varDisplay.value(); bool isgroup = isGroup(itemData); QStyleOptionViewItem viewOption(option); //用来在视图中画一个item DPalette::ColorGroup cg = option.state & QStyle::State_Enabled ? DPalette::Normal : DPalette::Disabled; if (cg == DPalette::Normal && !(option.state & QStyle::State_Active)) { cg = DPalette::Inactive; } QRect bgRect; bgRect.setX(option.rect.x() + 10); bgRect.setY(option.rect.y() /*+ 10*/); bgRect.setWidth(option.rect.width() - 20); bgRect.setHeight(option.rect.height() - 10); QPainterPath path; int cornerSize = 16; int arcRadius = 8; path.moveTo(bgRect.left() + arcRadius, bgRect.top()); path.arcTo(bgRect.left(), bgRect.top(), cornerSize, cornerSize, 90.0, 90.0); path.lineTo(bgRect.left(), bgRect.bottom() - arcRadius); path.arcTo(bgRect.left(), bgRect.bottom() - cornerSize, cornerSize, cornerSize, 180.0, 90.0); path.lineTo(bgRect.right() - arcRadius, bgRect.bottom()); path.arcTo(bgRect.right() - cornerSize, bgRect.bottom() - cornerSize, cornerSize, cornerSize, 270.0, 90.0); path.lineTo(bgRect.right(), bgRect.top() + arcRadius); path.arcTo(bgRect.right() - cornerSize, bgRect.top(), cornerSize, cornerSize, 0.0, 90.0); if (option.state & QStyle::State_MouseOver) { DStyleHelper styleHelper; QColor fillColor = styleHelper.getColor(static_cast(&option), DPalette::ToolTipText); fillColor.setAlphaF(0.3); painter->setBrush(QBrush(fillColor)); painter->fillPath(path, fillColor); } else { DPalette pa = DApplicationHelper::instance()->palette(m_parentView); DStyleHelper styleHelper; QColor fillColor = styleHelper.getColor(static_cast(&option), pa, DPalette::ItemBackground); painter->setBrush(QBrush(fillColor)); painter->fillPath(path, fillColor); } int cmdIconSize = 44; int editIconSize = 20; QRect cmdIconRect = QRect(bgRect.left() + 8, bgRect.top() + (bgRect.height() - cmdIconSize) / 2, cmdIconSize, cmdIconSize); QIcon icon = QIcon::fromTheme("dt_server"); if (isgroup) { icon = QIcon::fromTheme("dt_server_group"); } QPixmap cmdIconPixmap = icon.pixmap(QSize(cmdIconSize, cmdIconSize)); painter->drawPixmap(cmdIconRect, cmdIconPixmap); QString strServerName = itemData.m_serverName; QString strAddress = QString("%1@%2").arg(itemData.m_userName, itemData.m_address); if (isgroup) { strServerName = itemData.m_group; strAddress = itemData.m_number; editIconSize = 12; QRect editIconRect = QRect(bgRect.right() - editIconSize - 6, bgRect.top() + (bgRect.height() - editIconSize) / 2, editIconSize, editIconSize); painter->drawPixmap(editIconRect, QIcon::fromTheme("dt_arrow_right").pixmap(QSize(editIconSize, editIconSize))); } else { if (option.state & QStyle::State_MouseOver) { QRect editIconRect = QRect(bgRect.right() - editIconSize - 6, bgRect.top() + (bgRect.height() - editIconSize) / 2, editIconSize, editIconSize); painter->drawPixmap(editIconRect, QIcon::fromTheme("dt_edit").pixmap(QSize(editIconSize, editIconSize))); } } QFont textFont = painter->font(); int textFontSize = DFontSizeManager::instance()->fontPixelSize(DFontSizeManager::T7); textFont.setPixelSize(textFontSize); strServerName = Utils::getElidedText(textFont, strServerName, ITEMMAXWIDTH); painter->setFont(textFont); int lineSpace = 8; int offsetY = 22 - textFontSize; int leftOffset = cmdIconRect.left() + cmdIconSize + 6; DGuiApplicationHelper *appHelper = DGuiApplicationHelper::instance(); DPalette pa = appHelper->standardPalette(appHelper->themeType()); painter->setPen(pa.color(DPalette::Text)); QRect serverNameRect = QRect(leftOffset, bgRect.top() + offsetY, bgRect.width() - cmdIconSize - editIconSize, 35); painter->drawText(serverNameRect, Qt::AlignLeft | Qt::AlignTop, strServerName); textFont.setPixelSize(DFontSizeManager::instance()->fontPixelSize(DFontSizeManager::T8)); strAddress = Utils::getElidedText(textFont, strAddress, ITEMMAXWIDTH); painter->setFont(textFont); DStyleHelper styleHelper; DPalette palette = DApplicationHelper::instance()->palette(m_parentView); painter->setPen(QPen(styleHelper.getColor(static_cast(&option), palette, DPalette::TextTips))); QRect addressRect = QRect(leftOffset, serverNameRect.top() + textFontSize + lineSpace, bgRect.width() - cmdIconSize - editIconSize, 35); painter->drawText(addressRect, Qt::AlignLeft | Qt::AlignTop, strAddress); painter->restore(); } else { DStyledItemDelegate::paint(painter, option, index); } } QSize ServerConfigDelegate::sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const { Q_UNUSED(index) return QSize(option.rect.width(), 70); } /** * @brief 判断是否分组方式显示(根据配置信息中分组字段是否为空),如果已经在分组界面,直接返回false * @param itemData * @return */ bool ServerConfigDelegate::isGroup(ServerConfigItemData &itemData) const { if (itemData.m_IsInGrouppanel) { return false; } return itemData.m_IsGroupItem; } deepin-terminal-5.2.11/src/remotemanage/serverconfigdelegate.h000066400000000000000000000012751370157770500244710ustar00rootroot00000000000000#ifndef SERVERCONFIGDELEGATE_H #define SERVERCONFIGDELEGATE_H #include "serverconfigitemmodel.h" #include DWIDGET_USE_NAMESPACE class ServerConfigDelegate : public DStyledItemDelegate { public: explicit ServerConfigDelegate(QAbstractItemView *parent = nullptr); void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const Q_DECL_OVERRIDE; QSize sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const Q_DECL_OVERRIDE; bool isGroup(ServerConfigItemData &itemData) const; private: QAbstractItemView *m_parentView = nullptr; }; #endif // SERVERCONFIGDELEGATE_H deepin-terminal-5.2.11/src/remotemanage/serverconfiggrouppanel.cpp000066400000000000000000000073121370157770500254240ustar00rootroot00000000000000#include "serverconfiggrouppanel.h" #include "serverconfigitem.h" #include ServerConfigGroupPanel::ServerConfigGroupPanel(QWidget *parent) : CommonPanel(parent) { initUI(); } void ServerConfigGroupPanel::initUI() { this->setBackgroundRole(QPalette::Base); this->setAutoFillBackground(true); m_backButton = new DIconButton(this); m_searchEdit = new DSearchEdit(this); m_listWidget = new ServerConfigList(this); m_backButton->setIcon(DStyle::StandardPixmap::SP_ArrowLeave); m_backButton->setFixedSize(QSize(36, 36)); m_backButton->setFocusPolicy(Qt::NoFocus); m_searchEdit->setClearButtonEnabled(true); m_searchEdit->lineEdit()->setFocusPolicy(Qt::ClickFocus); m_listWidget->setSelectionMode(QAbstractItemView::NoSelection); m_listWidget->setVerticalScrollMode(QAbstractItemView::ScrollMode::ScrollPerItem); m_listWidget->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn); m_listWidget->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); m_listWidget->setSizePolicy(QSizePolicy::Policy::Expanding, QSizePolicy::Policy::Expanding); QHBoxLayout *hlayout = new QHBoxLayout(); hlayout->setContentsMargins(0, 0, 0, 0); hlayout->addSpacing(10); hlayout->addWidget(m_backButton); hlayout->addSpacing(10); hlayout->addWidget(m_searchEdit); hlayout->addSpacing(10); // 没有搜索框,返回按钮仍显示在左边 hlayout->addStretch(); hlayout->setSpacing(0); hlayout->setMargin(0); QVBoxLayout *vlayout = new QVBoxLayout(); vlayout->setContentsMargins(0, 0, 0, 0); vlayout->addSpacing(10); vlayout->addLayout(hlayout); vlayout->addWidget(m_listWidget); vlayout->setMargin(0); vlayout->setSpacing(10); setLayout(vlayout); connect(m_searchEdit, &DSearchEdit::returnPressed, this, &ServerConfigGroupPanel::handleShowSearchResult); // connect(m_listWidget, &ServerConfigList::itemClicked, this, &ServerConfigGroupPanel::listItemClicked); connect(m_backButton, &DIconButton::clicked, this, &ServerConfigGroupPanel::showRemoteManagementPanel); connect(m_listWidget, &ServerConfigList::listItemCountChange, this, &ServerConfigGroupPanel::refreshSearchState); connect(ServerConfigManager::instance(), &ServerConfigManager::refreshList, this, [ = ]() { if (m_isShow) { refreshData(m_groupName); QMap> &configMap = ServerConfigManager::instance()->getServerConfigs(); if (!configMap.contains(m_groupName)) { // 没有这个组 ==> 组内没成员,则返回 emit showRemoteManagementPanel(); m_isShow = false; } } }); } void ServerConfigGroupPanel::refreshData(const QString &groupName) { m_groupName = groupName; m_listWidget->clearData(); m_listWidget->refreshDataByGroup(groupName, true); refreshSearchState(); } void ServerConfigGroupPanel::handleShowSearchResult() { QString strFilter = m_searchEdit->text(); emit showSearchResult(m_groupName, strFilter); } void ServerConfigGroupPanel::refreshSearchState() { if (m_listWidget->count() >= 2) { /************************ Add by m000743 sunchengxi 2020-04-22:搜索显示异常 Begin************************/ m_searchEdit->clearEdit(); /************************ Add by m000743 sunchengxi 2020-04-22:搜索显示异常 End ************************/ m_searchEdit->show(); } else { m_searchEdit->hide(); } } void ServerConfigGroupPanel::listItemClicked(ServerConfig *curItemServer) { if (nullptr != curItemServer) { emit doConnectServer(curItemServer); } else { qDebug() << "remote item from group is null"; } } deepin-terminal-5.2.11/src/remotemanage/serverconfiggrouppanel.h000066400000000000000000000014271370157770500250720ustar00rootroot00000000000000#ifndef SERVERCONFIGGROUPPANEL_H #define SERVERCONFIGGROUPPANEL_H #include "commonpanel.h" #include "serverconfiglist.h" #include class ServerConfigGroupPanel : public CommonPanel { Q_OBJECT public: explicit ServerConfigGroupPanel(QWidget *parent = nullptr); void refreshData(const QString &groupName); signals: void showSearchResult(const QString &strGroup, const QString &strFilter); void doConnectServer(ServerConfig *curServer); void showRemoteManagementPanel(); public slots: void handleShowSearchResult(); void refreshSearchState(); void listItemClicked(ServerConfig *curItemServer); private: void initUI(); private: ServerConfigList *m_listWidget = nullptr; QString m_groupName; }; #endif // SERVERCONFIGGROUPPANEL_H deepin-terminal-5.2.11/src/remotemanage/serverconfigitem.cpp000066400000000000000000000067641370157770500242200ustar00rootroot00000000000000#include "serverconfigitem.h" #include "serverconfigmanager.h" #include #include #include ServerConfigItem::ServerConfigItem(ServerConfig *config, bool bGroup, const QString &group, QWidget *parent) : DWidget(parent), m_serverConfig(config), m_nameLabel(new DLabel(this)), m_detailsLabel(new DLabel(this)), m_leftIcon(new DLabel(this)), m_bGroup(bGroup), m_strGroupName(group) { setFixedWidth(230); QImage img(":/resources/images/icon/hover/server.svg"); m_leftIcon->setPixmap(QPixmap::fromImage(img)); m_leftIcon->setFixedSize(QSize(70, 70)); m_leftIcon->setFocusPolicy(Qt::NoFocus); m_leftIcon->setContentsMargins(10, 0, 0, 0); if (!m_bGroup) { m_rightIconButton = new MyIconButton(this); m_rightIconButton->setFixedSize(QSize(30, 30)); m_rightIconButton->setIconSize(QSize(30, 30)); m_rightIconButton->setIcon(QIcon(":/resources/images/icon/hover/edit_hover.svg")); connect(m_rightIconButton, &DIconButton::clicked, this, &ServerConfigItem::editServerConfig); m_rightIcon = nullptr; } else { m_rightIcon = new DLabel(this); m_rightIcon->setPixmap(QPixmap::fromImage(QImage(":/resources/images/icon/hover/arrowr.svg"))); m_rightIcon->setFixedSize(QSize(30, 30)); m_rightIcon->setAlignment(Qt::AlignCenter); m_rightIcon->setFocusPolicy(Qt::NoFocus); m_rightIconButton = nullptr; } QVBoxLayout *vLayout = new QVBoxLayout(); vLayout->addWidget(m_nameLabel); vLayout->addWidget(m_detailsLabel); vLayout->setSpacing(0); vLayout->setMargin(0); QHBoxLayout *mainLayout = new QHBoxLayout(); mainLayout->addWidget(m_leftIcon); mainLayout->addLayout(vLayout); if (m_bGroup) { mainLayout->addWidget(m_rightIcon, 0, Qt::AlignRight); } else { mainLayout->addWidget(m_rightIconButton); } mainLayout->setSpacing(0); mainLayout->setContentsMargins(0, 0, 20, 0); setLayout(mainLayout); if (m_bGroup) { QMap> &configMap = ServerConfigManager::instance()->getServerConfigs(); m_nameLabel->setText(group); m_detailsLabel->setText(QString("%1 server").arg(configMap[group].count())); } else { m_rightIconButton->hide(); if (m_serverConfig) { m_nameLabel->setText(m_serverConfig->m_serverName); m_detailsLabel->setText(QString("%1@%2@%3") .arg(m_serverConfig->m_userName) .arg(m_serverConfig->m_address) .arg(m_serverConfig->m_port)); } } } ServerConfig *ServerConfigItem::getCurServerConfig() { return m_serverConfig; } void ServerConfigItem::editServerConfig() { emit modifyServerConfig(this); } void ServerConfigItem::enterEvent(QEvent *event) { if (!m_bGroup && m_rightIconButton) { m_rightIconButton->show(); } this->setAutoFillBackground(true); this->setBackgroundRole(DPalette::ColorRole::Light); DWidget::enterEvent(event); } void ServerConfigItem::leaveEvent(QEvent *event) { if (!m_bGroup && m_rightIconButton) { m_rightIconButton->hide(); } this->setAutoFillBackground(true); this->setBackgroundRole(DPalette::ColorRole::NoRole); DWidget::enterEvent(event); } bool ServerConfigItem::isGroup() { return m_bGroup; } QString ServerConfigItem::getGroupName() { return m_strGroupName; } deepin-terminal-5.2.11/src/remotemanage/serverconfigitem.h000066400000000000000000000020711370157770500236500ustar00rootroot00000000000000#ifndef SERVERCONFIGITEM_H #define SERVERCONFIGITEM_H #include "myiconbutton.h" #include "serverconfigmanager.h" #include #include #include #include #include DWIDGET_USE_NAMESPACE class ServerConfigItem : public DWidget { Q_OBJECT public: explicit ServerConfigItem(ServerConfig *config, bool bGroup = false, const QString &group = "", QWidget *parent = nullptr); ServerConfig *getCurServerConfig(); bool isGroup(); QString getGroupName(); signals: void modifyServerConfig(ServerConfigItem *item); private slots: void editServerConfig(); protected: void enterEvent(QEvent *event) override; void leaveEvent(QEvent *event) override; private: ServerConfig *m_serverConfig = nullptr; DLabel *m_nameLabel = nullptr; DLabel *m_detailsLabel = nullptr; MyIconButton *m_rightIconButton = nullptr; DLabel *m_leftIcon = nullptr; DLabel *m_rightIcon = nullptr; bool m_bGroup; QString m_strGroupName; }; #endif // SERVERCONFIGITEM_H deepin-terminal-5.2.11/src/remotemanage/serverconfigitemmodel.cpp000066400000000000000000000022051370157770500252230ustar00rootroot00000000000000#include "serverconfigitemmodel.h" #include #include ServerConfigItemModel::ServerConfigItemModel(QObject *parent) : QSortFilterProxyModel(parent) { } void ServerConfigItemModel::initServerListData(const QList &serCfgsListData) { QStandardItemModel *sourceModel = qobject_cast(this->sourceModel()); for (int i = 0; i < serCfgsListData.size(); i++) { ServerConfigItemData itemData = serCfgsListData.at(i); QStandardItem *item = new QStandardItem; item->setFlags(item->flags() & ~Qt::ItemIsSelectable & ~Qt::ItemIsEnabled); item->setData(QVariant::fromValue(itemData), Qt::DisplayRole); sourceModel->appendRow(item); } } void ServerConfigItemModel::addNewServerData(const ServerConfigItemData itemData) { QStandardItemModel *sourceModel = qobject_cast(this->sourceModel()); QStandardItem *item = new QStandardItem; item->setFlags(item->flags() & ~Qt::ItemIsSelectable & ~Qt::ItemIsEnabled); item->setData(QVariant::fromValue(itemData), Qt::DisplayRole); sourceModel->appendRow(item); } deepin-terminal-5.2.11/src/remotemanage/serverconfigitemmodel.h000066400000000000000000000016741370157770500247010ustar00rootroot00000000000000#ifndef SERVERCONFIGITEMMODEL_H #define SERVERCONFIGITEMMODEL_H #include #include typedef struct { QString m_serverName; QString m_address; QString m_userName; QString m_password; QString m_privateKey; QString m_port; QString m_group; QString m_path; QString m_command; QString m_encoding; QString m_backspaceKey; QString m_deleteKey; QString m_number; bool m_IsInGrouppanel = false; bool m_IsGroupItem = false; // 判断是否以组形式展示 } ServerConfigItemData; Q_DECLARE_METATYPE(ServerConfigItemData) class ServerConfigItemModel : public QSortFilterProxyModel { Q_OBJECT public: ServerConfigItemModel(QObject *parent = nullptr); void initServerListData(const QList &serCfgsListData); void addNewServerData(const ServerConfigItemData itemData); }; #endif // SERVERCONFIGITEMMODEL_H deepin-terminal-5.2.11/src/remotemanage/serverconfiglist.cpp000066400000000000000000000353211370157770500242240ustar00rootroot00000000000000#include "serverconfiglist.h" #include "operationconfirmdlg.h" #include "serverconfigitem.h" #include "serverconfigmanager.h" #include "serverconfigoptdlg.h" #include "serverconfigdelegate.h" #include "serverconfigitemmodel.h" #include "service.h" #include "utils.h" #include #include #include ServerConfigList::ServerConfigList(QWidget *parent) : DListView(parent) { setBackgroundRole(QPalette::NoRole); setAutoFillBackground(false); setUpdatesEnabled(true); setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn); setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); initData(); } void ServerConfigList::initData() { m_serCfgListModel = new QStandardItemModel(this); m_serCfgProxyModel = new ServerConfigItemModel(this); m_serCfgProxyModel->setSourceModel(m_serCfgListModel); m_serCfgProxyModel->setFilterRole(Qt::UserRole); m_serCfgProxyModel->setDynamicSortFilter(true); m_serCfgDelegate = new ServerConfigDelegate(this); this->setModel(m_serCfgProxyModel); this->setItemDelegate(m_serCfgDelegate); } void ServerConfigList::refreshAllDatas() { state = 1; clearData(); QMap> &configMap = ServerConfigManager::instance()->getServerConfigs(); QMap>::const_iterator iter = configMap.constBegin(); while (iter != configMap.constEnd()) { if (iter.key().isEmpty()) { iter++; continue; } int count = configMap[iter.key()].count(); ServerConfigItemData itemData; itemData.m_group = iter.key(); itemData.m_number = QString("%1 server").arg(count); /******** Modify by m000714 daizhengwen 2020-04-13: 组不为空则以组形式展示****************/ if (!itemData.m_group.isNull() && !itemData.m_group.isEmpty() && "" != itemData.m_group) { itemData.m_IsGroupItem = true; } /********************* Modify by m000714 daizhengwen End ************************/ m_serCfgItemDataList.append(itemData); iter++; } refreshDataByGroup("", false); } ServerConfigItemData changePointerToObject(ServerConfig *cfg) { ServerConfigItemData itemData; itemData.m_userName = cfg->m_userName; itemData.m_address = cfg->m_address; itemData.m_port = cfg->m_port; itemData.m_serverName = cfg->m_serverName; itemData.m_password = cfg->m_password; itemData.m_group = cfg->m_group; itemData.m_command = cfg->m_command; itemData.m_path = cfg->m_path; itemData.m_encoding = cfg->m_encoding; itemData.m_backspaceKey = cfg->m_backspaceKey; itemData.m_deleteKey = cfg->m_deleteKey; itemData.m_privateKey = cfg->m_privateKey; return itemData; } void ServerConfigList::refreshDataByGroup(const QString &strGroupName, bool isFromGroupPanel) { m_GroupName = strGroupName; if (isFromGroupPanel) { state = 2; } QMap> &configMap = ServerConfigManager::instance()->getServerConfigs(); // 判断组是否被删除 if (!configMap.contains(strGroupName)) { m_serCfgProxyModel->initServerListData(m_serCfgItemDataList); // 已被删除,则返回 return; } // 还有,将剩下的添加 QList &configList = configMap[strGroupName]; for (auto cfg : configList) { ServerConfigItemData itemData = changePointerToObject(cfg); if (isFromGroupPanel) { itemData.m_IsInGrouppanel = true; } m_serCfgItemDataList.append(itemData); } m_serCfgProxyModel->initServerListData(m_serCfgItemDataList); } //根据分组信息和搜索信息联合查询 void ServerConfigList::refreshDataByGroupAndFilter(const QString &strGroupName, const QString &strFilter) { state = 4; m_GroupName = strGroupName; m_Filter = strFilter; QMap> &configMap = ServerConfigManager::instance()->getServerConfigs(); if (!configMap.contains(strGroupName)) { // 若分组不存在则返回 return; } QList &configList = configMap[strGroupName]; for (auto cfg : configList) { if (cfg->m_serverName.contains(strFilter, Qt::CaseSensitivity::CaseInsensitive) //----commented by qinyaning(nyq) to solve search problems--// || cfg->m_userName.contains(strFilter, Qt::CaseSensitivity::CaseInsensitive) || cfg->m_address.contains(strFilter, Qt::CaseSensitivity::CaseInsensitive)) { //地址 //----------------------------------------------------------// ServerConfigItemData itemData = changePointerToObject(cfg); itemData.m_IsGroupItem = false; m_serCfgItemDataList.append(itemData); } } m_serCfgProxyModel->initServerListData(m_serCfgItemDataList); } void ServerConfigList::refreshDataByFilter(const QString &strFilter) { state = 3; m_Filter = strFilter; QMap> &configMap = ServerConfigManager::instance()->getServerConfigs(); QMap>::const_iterator iter = configMap.constBegin(); // 优先搜索分组 while (iter != configMap.constEnd()) { QList configList = iter.value(); //----------added by qinyaning(nyq) to slove search problems---------// if (!configList.isEmpty() && (configList[0]->m_group.contains(strFilter, Qt::CaseSensitivity::CaseInsensitive))) { ServerConfigItemData itemData = changePointerToObject(configList[0]); itemData.m_IsGroupItem = true; int count = configMap[iter.key()].count(); itemData.m_number = QString(tr("%1 server")).arg(count); m_serCfgItemDataList.append(itemData); }//---------------------------------------------------------------// iter++; } // 接着搜索服务器 iter = configMap.constBegin(); while (iter != configMap.constEnd()) { QList configList = iter.value(); for (auto cfg : configList) { if (cfg->m_serverName.contains(strFilter, Qt::CaseSensitivity::CaseInsensitive)//服务名 //------commented by qinyaning(nyq) to solve search problems-----------------// || cfg->m_userName.contains(strFilter, Qt::CaseSensitivity::CaseInsensitive)//用户名 || cfg->m_address.contains(strFilter, Qt::CaseSensitivity::CaseInsensitive)//地址 // ||cfg->m_group.contains(strFilter, Qt::CaseSensitivity::CaseInsensitive) // 分组 ) { //--------------------------------------------------------------------------// ServerConfigItemData itemData = changePointerToObject(cfg); //----------added by qinyaning(nyq) to slove search problems---------// itemData.m_IsGroupItem = false; //-------------------------------------------------------------------// m_serCfgItemDataList.append(itemData); } } iter++; } m_serCfgProxyModel->initServerListData(m_serCfgItemDataList); } void ServerConfigList::handleModifyServerConfig(ServerConfig *curItemServer, QModelIndex modelIndex) { qDebug() << __FUNCTION__ << "modify remote " << curItemServer->m_serverName; // 弹窗显示 Service::instance()->setIsDialogShow(window(), true); Q_UNUSED(modelIndex) // 1.显示弹窗 ServerConfigOptDlg *dlg = new ServerConfigOptDlg(ServerConfigOptDlg::SCT_MODIFY, curItemServer, this); connect(dlg, &ServerConfigOptDlg::finished, this, [ = ](int result) { // 弹窗隐藏或消失 Service::instance()->setIsDialogShow(window(), false); // 3. 对弹窗操作进行分析 // 判断是否删除 if (result == ServerConfigOptDlg::Accepted) { // 判断是否需要删除 if (dlg->isDelServer()) { qDebug() << "delete " << dlg->getCurServer()->m_serverName << dlg; DDialog *deleteDialog = new DDialog(tr("Delete Server"), tr("Are you sure you want to delete %1?").arg(dlg->getServerName()), dlg); deleteDialog->setAttribute(Qt::WA_DeleteOnClose); connect(deleteDialog, &DDialog::finished, this, [ = ](int result2) { // 删除 if (result2 == DDialog::Accepted) { // 关闭所有相关弹窗 ServerConfigManager::instance()->closeAllDialog(dlg->getCurServer()->m_serverName); ServerConfigManager::instance()->delServerConfig(dlg->getCurServer()); emit listItemCountChange(); } else { // 关闭后及时将弹窗删除 ServerConfigManager::instance()->removeDialog(dlg); } }); deleteDialog->setWindowModality(Qt::WindowModal); deleteDialog->setIcon(QIcon::fromTheme("deepin-terminal")); deleteDialog->addButton(QObject::tr("Cancel"), false, DDialog::ButtonNormal); deleteDialog->addButton(QObject::tr("Delete"), true, DDialog::ButtonWarning); deleteDialog->show(); } else { // 不删除,修改 // 修改后会有信号刷新列表 // 不需要删除,修改了转到这条修改的记录 QModelIndex index = currentIndex(dlg->getServerName()); scrollTo(index); // 关闭后及时将弹窗删除 ServerConfigManager::instance()->removeDialog(dlg); } } else { // 取消后及时将弹窗删除 ServerConfigManager::instance()->removeDialog(dlg); } }); // 2. 记录弹窗 ServerConfigManager::instance()->setModifyDialog(curItemServer->m_serverName, dlg); dlg->show(); } /******************************************************************************* 1. @函数: currentIndex 2. @作者: m000714 戴正文 3. @日期: 2020-04-13 4. @说明: 获取给定服务器名的index *******************************************************************************/ QModelIndex ServerConfigList::currentIndex(const QString &serverName) { return m_serCfgProxyModel->index(getServerIndex(serverName), 0); } /******************************************************************************* 1. @函数: getServerIndex 2. @作者: m000714 戴正文 3. @日期: 2020-04-13 4. @说明: 获取当前服务的index(行数) *******************************************************************************/ int ServerConfigList::getServerIndex(const QString &serverName) { int index = 0; QMap> &configMap = ServerConfigManager::instance()->getServerConfigs(); QMap>::const_iterator iter = configMap.constBegin(); // 组内查找服务器 while (iter != configMap.constEnd()) { if (iter.key().isEmpty()) { iter++; continue; } foreach (auto item, iter.value()) { if (item->m_serverName == serverName) { // 组没有匹配的,给组的index return index; } } index++; iter++; } // 查找没有分组的 QList &configList = configMap[""]; foreach (auto cfg, configList) { if (cfg->m_serverName == serverName) { return index; } index++; } return -1; } void ServerConfigList::refreshPanelData(QModelIndex modelIndex) { Q_UNUSED(modelIndex) if (m_serCfgListModel && m_serCfgListModel->rowCount() == 0) { return; } switch (state) { case 1: refreshAllDatas(); break; case 2: clearData(); refreshDataByGroup(m_GroupName, true); break; case 3: clearData(); refreshDataByFilter(m_Filter); break; case 4: clearData(); refreshDataByGroupAndFilter(m_GroupName, m_Filter); break; } } QRect getModifyIconRectS(QRect visualRect) { int modifyIconSize = 30; return QRect(visualRect.right() - modifyIconSize - 10, visualRect.top() + (visualRect.height() - modifyIconSize) / 2, modifyIconSize, modifyIconSize); } void ServerConfigList::mouseMoveEvent(QMouseEvent *event) { DListView::mouseMoveEvent(event); } void ServerConfigList::mousePressEvent(QMouseEvent *event) { if (event->button() == Qt::LeftButton) { m_bLeftMouse = true; } else { m_bLeftMouse = false; } DListView::mousePressEvent(event); // 不是左键点击,不响应 if (!m_bLeftMouse) { return; } if (m_serCfgListModel && m_serCfgListModel->rowCount() == 0) { return; } if (!m_serCfgListModel) { return; } QPoint clickPoint = event->pos(); QModelIndex modelIndex = indexAt(clickPoint); QRect rect = visualRect(modelIndex); if (!modelIndex.isValid()) { return; } ServerConfigItemData itemData = qvariant_cast(m_serCfgProxyModel->data(modelIndex)); // 找到配置里这个值 ServerConfig *curItemServer = nullptr; QMap> &configMap = ServerConfigManager::instance()->getServerConfigs(); for (auto &item : configMap[itemData.m_group]) { if (item->m_serverName == itemData.m_serverName) { curItemServer = item; } } // 说明是分组,没指到任何数据 if (curItemServer == nullptr) { // 取分组的第一个数据 if (0 != configMap[itemData.m_group].count()) { curItemServer = configMap[itemData.m_group][0]; } } if (itemData.m_IsGroupItem) { // 有组进组 qDebug() << "remote list click group " << itemData.m_group << state; emit groupClicked(itemData.m_group); return DListView::mousePressEvent(event); } if (getModifyIconRectS(rect).contains(clickPoint)) { qDebug() << "remote list click modify ServerConfig"; handleModifyServerConfig(curItemServer, modelIndex); return DListView::mousePressEvent(event); } else { qDebug() << "remote list click item " << itemData.m_serverName << state;; emit itemClicked(curItemServer); } } void ServerConfigList::mouseReleaseEvent(QMouseEvent *event) { DListView::mouseReleaseEvent(event); } void ServerConfigList::setSelection(const QRect &rect, QItemSelectionModel::SelectionFlags command) { DListView::setSelection(rect, command); } void ServerConfigList::clearData() { m_serCfgListModel->clear(); m_serCfgItemDataList.clear(); } int ServerConfigList::getState() { return state; } deepin-terminal-5.2.11/src/remotemanage/serverconfiglist.h000066400000000000000000000035301370157770500236660ustar00rootroot00000000000000#ifndef SERVERCONFIGLIST_H #define SERVERCONFIGLIST_H #include "serverconfigitemmodel.h" #include #include #include #include DWIDGET_USE_NAMESPACE class ServerConfigDelegate; class ServerConfig; class ServerConfigItemModel; class ServerConfigList : public DListView { Q_OBJECT public: ServerConfigList(QWidget *parent = nullptr); //显示所有的服务器信息 void refreshAllDatas(); //根据分组信息和搜索信息联合查询 void refreshDataByGroup(const QString &strGroupName, bool isFromGroupPanel); //根据分组信息和搜索信息联合查询 void refreshDataByGroupAndFilter(const QString &strGroupName, const QString &strFilter); void refreshDataByFilter(const QString &strFilter); void clearData(); void refreshPanelData(QModelIndex modelIndex); QModelIndex currentIndex(const QString &serverName); private: void initData(); protected: void mouseMoveEvent(QMouseEvent *event); void mousePressEvent(QMouseEvent *event); void mouseReleaseEvent(QMouseEvent *event); void setSelection(const QRect &rect, QItemSelectionModel::SelectionFlags command); signals: void listItemCountChange(); void itemClicked(ServerConfig *curItemServer); void groupClicked(QString group); private slots: void handleModifyServerConfig(ServerConfig *curItemServer, QModelIndex modelIndex); private: ServerConfigDelegate *m_serCfgDelegate = nullptr; QStandardItemModel *m_serCfgListModel = nullptr; ServerConfigItemModel *m_serCfgProxyModel = nullptr; QList m_serCfgItemDataList; bool m_bLeftMouse = true; //1:all 2:group 3:search int state = 1; QString m_GroupName; QString m_Filter; int getState(); int getServerIndex(const QString &serverName); }; #endif // SERVERCONFIGLIST_H deepin-terminal-5.2.11/src/remotemanage/serverconfigmanager.cpp000066400000000000000000000231331370157770500246610ustar00rootroot00000000000000#include "serverconfigmanager.h" #include "serverconfigoptdlg.h" #include ServerConfigManager *ServerConfigManager::m_instance = nullptr; ServerConfigManager::ServerConfigManager(QObject *parent) : QObject(parent) { } /******************************************************************************* 1. @函数: settServerConfig 2. @作者: m000714 戴正文 3. @日期: 2020-04-17 4. @说明: 写服务器配置文件 *******************************************************************************/ void ServerConfigManager::settServerConfig(QSettings &commandsSettings, const QString &strGroupName, ServerConfig *config) { commandsSettings.beginGroup(strGroupName); commandsSettings.setValue("Name", config->m_serverName); commandsSettings.setValue("Password", config->m_password); commandsSettings.setValue("GroupName", config->m_group); commandsSettings.setValue("Command", config->m_command); commandsSettings.setValue("Path", config->m_path); commandsSettings.setValue("Encode", config->m_encoding); commandsSettings.setValue("Backspace", config->m_backspaceKey); commandsSettings.setValue("Del", config->m_deleteKey); commandsSettings.setValue("PrivateKey", config->m_privateKey); commandsSettings.endGroup(); } ServerConfigManager *ServerConfigManager::instance() { if (nullptr == m_instance) { m_instance = new ServerConfigManager(); } return m_instance; } void ServerConfigManager::initServerConfig() { m_serverConfigs.clear(); //---------------------------------------------------------------------------// QDir serverConfigBasePath(QStandardPaths::writableLocation(QStandardPaths::AppConfigLocation)); if (!serverConfigBasePath.exists()) { return; } QString serverConfigFilePath(serverConfigBasePath.filePath("server-config.conf")); qDebug() << "load Server Config: " << serverConfigFilePath; if (!QFile::exists(serverConfigFilePath)) { return; } QSettings serversSettings(serverConfigFilePath, QSettings::IniFormat); QStringList serverGroups = serversSettings.childGroups(); for (const QString &serverName : serverGroups) { serversSettings.beginGroup(serverName); QStringList strList = serverName.split("@"); qDebug() << "Group Name : " << serverName; /******** Modify by m000714 daizhengwen 2020-04-17: 兼容旧版本,旧版本GroupName为三个****************/ // 不读三个参数的和旧版本互不影响,QSetting写配置文件和旧版本不一致 if (strList.count() == 3) { qDebug() << "continue"; continue; } ServerConfig *pServerConfig = new ServerConfig(); pServerConfig->m_userName = strList.at(0); pServerConfig->m_address = strList.at(1); pServerConfig->m_port = strList.at(2); pServerConfig->m_serverName = strList.at(3); /********************* Modify by m000714 daizhengwen End ************************/ pServerConfig->m_password = serversSettings.value("Password").toString(); pServerConfig->m_group = serversSettings.value("GroupName").toString(); pServerConfig->m_command = serversSettings.value("Command").toString(); pServerConfig->m_path = serversSettings.value("Path").toString(); pServerConfig->m_encoding = serversSettings.value("Encode").toString(); pServerConfig->m_backspaceKey = serversSettings.value("Backspace").toString(); pServerConfig->m_deleteKey = serversSettings.value("Del").toString(); pServerConfig->m_privateKey = serversSettings.value("PrivateKey").toString(); serversSettings.endGroup(); m_serverConfigs[pServerConfig->m_group].append(pServerConfig); } return; } void ServerConfigManager::saveServerConfig(ServerConfig *config) { QDir customCommandBasePath(QStandardPaths::writableLocation(QStandardPaths::AppConfigLocation)); if (!customCommandBasePath.exists()) { customCommandBasePath.mkpath(QStandardPaths::writableLocation(QStandardPaths::AppConfigLocation)); } QString customCommandConfigFilePath(customCommandBasePath.filePath("server-config.conf")); QSettings commandsSettings(customCommandConfigFilePath, QSettings::IniFormat); //--modified by qinyaning to solve probel(bug 19338) when added ftp--// QString strConfigGroupName = QString("%1@%2@%3@%4").arg( config->m_userName, config->m_address, config->m_port, config->m_serverName); //------------------------------ settServerConfig(commandsSettings, strConfigGroupName, config); if (m_serverConfigs.contains(config->m_group)) { m_serverConfigs[config->m_group].append(config); qDebug() << "append success!" << config->m_group << config->m_serverName; } else { QList configlist; configlist.append(config); m_serverConfigs[config->m_group] = configlist; } // 现实当前分组和没有分组的远程个数 //qDebug() << m_serverConfigs.count() << m_serverConfigs[""].count(); emit refreshList(config->m_serverName); } void ServerConfigManager::delServerConfig(ServerConfig *config) { // 防止重复删除 if (nullptr == config) { return; } // 读写配置文件 QDir customCommandBasePath(QStandardPaths::writableLocation(QStandardPaths::AppConfigLocation)); if (!customCommandBasePath.exists()) { customCommandBasePath.mkpath(QStandardPaths::writableLocation(QStandardPaths::AppConfigLocation)); } QString customCommandConfigFilePath(customCommandBasePath.filePath("server-config.conf")); QSettings commandsSettings(customCommandConfigFilePath, QSettings::IniFormat); //--modified by qinyaning to solve probel(bug 19338) when added ftp--// QString strConfigGroupName = QString("%1@%2@%3@%4").arg( config->m_userName, config->m_address, config->m_port, config->m_serverName); //------------------------- // 配置中清除数据 commandsSettings.remove(strConfigGroupName); //将map中数据清除 // 删除数据 m_serverConfigs[config->m_group].removeOne(config); // 判断组成员 if (m_serverConfigs[config->m_group].count() == 0) { // 若组内无成员 m_serverConfigs.remove(config->m_group); } emit refreshList(""); // 所有弹窗都消失才能delete config delete config; } void ServerConfigManager::modifyServerConfig(ServerConfig *newConfig, ServerConfig *oldConfig) { SyncData(oldConfig->m_serverName, newConfig); // 刷新已有数据 delServerConfig(oldConfig); saveServerConfig(newConfig); } QMap> &ServerConfigManager::getServerConfigs() { return m_serverConfigs; } void ServerConfigManager::setModifyDialog(QString key, ServerConfigOptDlg *dlg) { // 添加编辑弹窗 m_serverConfigDialogMap[key].append(dlg); qDebug() << "show edit dialog" << key << m_serverConfigDialogMap[key].count() << dlg; } /******************************************************************************* 1. @函数: removeDialog 2. @作者: ut000610 戴正文 3. @日期: 2020-05-23 4. @说明: 从m_serverConfigDialogMap中将dlg数据删除 *******************************************************************************/ void ServerConfigManager::removeDialog(ServerConfigOptDlg *dlg) { QString key; ServerConfigOptDlg *removeOne = nullptr; // 1.查找dlg指针 // 遍历map for (serverConfigDialogMapIterator item = m_serverConfigDialogMap.begin(); item != m_serverConfigDialogMap.end(); ++item) { //遍历列表 for (auto &dlgItem : item.value()) { if (dlgItem == dlg) { key = item.key(); removeOne = dlgItem; } } } // 2.删除数据 if (nullptr != removeOne) { qDebug() << "delete dialog from remote name : " << key; m_serverConfigDialogMap[key].removeOne(removeOne); } if (m_serverConfigDialogMap[key].count() == 0) { qDebug() << "remote dialog is 0, remove remote name : " << key; m_serverConfigDialogMap.remove(key); } if (nullptr != removeOne) { qDebug() << "delete remote dialog" << removeOne; removeOne->deleteLater(); } removeOne = nullptr; } void ServerConfigManager::SyncData(QString key, ServerConfig *newConfig) { qDebug() << key << newConfig->m_serverName; //前提是key唯一 // serverName被修改 if (key != newConfig->m_serverName) { // 将数据放入新的键值对 QList serverConfigOptDlgList; for (auto &item : m_serverConfigDialogMap[key]) { serverConfigOptDlgList.append(item); } m_serverConfigDialogMap[newConfig->m_serverName] = serverConfigOptDlgList; m_serverConfigDialogMap.remove(key); } for (auto &dlg : m_serverConfigDialogMap[newConfig->m_serverName]) { dlg->updataData(newConfig); } } void ServerConfigManager::closeAllDialog(QString key) { qDebug() << __FUNCTION__ << "remote name : " << key << m_serverConfigDialogMap.count(); // 判读此时这个key是否存在 if (!m_serverConfigDialogMap.contains(key)) { // 不存在退出 qDebug() << __FUNCTION__ << "not contains " << key; return; } for (auto &item : m_serverConfigDialogMap[key]) { if (item != nullptr) { qDebug() << __FUNCTION__ << "reject : " << item; // reject就会把当前的窗口删除 item->reject(); } } // removeDialog会做此操作 // m_serverConfigDialogMap.remove(key); } deepin-terminal-5.2.11/src/remotemanage/serverconfigmanager.h000066400000000000000000000036711370157770500243330ustar00rootroot00000000000000#ifndef SERVERCONFIGMANAGER_H #define SERVERCONFIGMANAGER_H #include #include #include #include #include #include #include struct ServerConfig { QString m_serverName; QString m_address; QString m_userName; QString m_password; QString m_privateKey; QString m_port; QString m_group; QString m_path; QString m_command; QString m_encoding; QString m_backspaceKey; QString m_deleteKey; }; class ServerConfigOptDlg; class ServerConfigManager : public QObject { Q_OBJECT public: static ServerConfigManager *instance(); void initServerConfig(); void saveServerConfig(ServerConfig *config); void delServerConfig(ServerConfig *config); void modifyServerConfig(ServerConfig *newConfig, ServerConfig *oldConfig); QMap> &getServerConfigs(); // 添加修改弹窗 void setModifyDialog(QString key, ServerConfigOptDlg *dlg); // 删除弹窗 void removeDialog(ServerConfigOptDlg *dlg); // 同步弹窗数据 void SyncData(QString key, ServerConfig *newConfig); // 删除数据,关闭所有同类弹窗 void closeAllDialog(QString key); signals: void refreshList(QString serverName); private: ServerConfigManager(QObject *parent = nullptr); private: static ServerConfigManager *m_instance; // QList m_serverConfigs; // 配置文件数据 QMap> m_serverConfigs; // 展示的弹窗的键值及弹窗的指针 <服务器名,同类服务器弹窗列表> 弹窗只需存储修改弹窗 QMap> m_serverConfigDialogMap; inline void settServerConfig(QSettings &commandsSettings, const QString &strGroupName, ServerConfig *config); }; typedef QMap>::Iterator serverConfigDialogMapIterator; #endif // SERVERCONFIGMANAGER_H deepin-terminal-5.2.11/src/remotemanage/serverconfigoptdlg.cpp000066400000000000000000000523461370157770500245500ustar00rootroot00000000000000#include "serverconfigoptdlg.h" #include "serverconfigmanager.h" #include "termcommandlinkbutton.h" #include "../views/operationconfirmdlg.h" #include "utils.h" #include #include #include #include #include #include #include #include #include #include #include #include #include //added byq qinyaning #include ServerConfigOptDlg::ServerConfigOptDlg(ServerConfigOptType type, ServerConfig *curServer, QWidget *parent) : DAbstractDialog(parent), m_type(type), m_curServer(curServer), m_titleLabel(new DLabel), m_iconLabel(new DLabel), m_closeButton(new DWindowCloseButton(this)), m_serverName(new DLineEdit), m_address(new DLineEdit), m_port(new DSpinBox), m_userName(new DLineEdit), m_password(new DPasswordEdit), // m_privateKey(new DFileChooserEdit), m_privateKey(new DLineEdit), m_fileDialog(new DSuggestButton), m_group(new DLineEdit), m_path(new DLineEdit), m_command(new DLineEdit), m_coding(new DComboBox), m_backSapceKey(new DComboBox), m_deleteKey(new DComboBox), m_advancedOptions(new DCommandLinkButton(tr("Advanced options"))), m_delServer(new TermCommandLinkButton()) { setWindowModality(Qt::WindowModal); setFixedWidth(459); setAutoFillBackground(true); initUI(); initData(); } void ServerConfigOptDlg::initUI() { //all layout QVBoxLayout *m_VBoxLayout = new QVBoxLayout(); m_VBoxLayout->setSpacing(10); m_VBoxLayout->setContentsMargins(0, 0, 0, 10); this->setFixedHeight(392); //head layout m_iconLabel->setFixedSize(50, 50); m_titleLabel->setText(tr("Add Server")); m_titleLabel->setAlignment(Qt::AlignHCenter | Qt::AlignVCenter); //m_titleLabel->setFixedWidth(85); m_closeButton->setFocusPolicy(Qt::NoFocus); m_closeButton->setFixedWidth(50); m_closeButton->setIconSize(QSize(50, 50)); // 字体 DFontSizeManager::instance()->bind(m_titleLabel, DFontSizeManager::T5, QFont::DemiBold); // 字色 DPalette palette = m_titleLabel->palette(); //palette.setBrush(QPalette::WindowText, palette.color(DPalette::TextTitle)); QColor color; if (DApplicationHelper::instance()->themeType() == DApplicationHelper::DarkType) { color = QColor::fromRgb(192, 198, 212, 255); } else { color = QColor::fromRgb(0, 26, 46, 255); } palette.setBrush(QPalette::WindowText, color); m_titleLabel->setPalette(palette); QHBoxLayout *headLayout = new QHBoxLayout(); headLayout->setSpacing(0); headLayout->setContentsMargins(0, 0, 0, 0); // 为了和closebutton对应是标题居中 headLayout->addWidget(m_iconLabel, 0, Qt::AlignLeft | Qt::AlignVCenter); headLayout->addWidget(m_titleLabel, 0, Qt::AlignHCenter); headLayout->addWidget(m_closeButton, 0, Qt::AlignRight | Qt::AlignTop); connect(m_closeButton, &DDialogCloseButton::clicked, this, [ = ]() { reject(); }); m_VBoxLayout->addLayout(headLayout, Qt::AlignTop); m_VBoxLayout->addStretch(10); //main layout QGridLayout *pGridLayout = new QGridLayout(); pGridLayout->setColumnStretch(1, 1); pGridLayout->setContentsMargins(28, 0, 30, 0); pGridLayout->setSpacing(10); DLabel *pServerNameLabel = new DLabel(tr("Server name:")); setLabelStyle(pServerNameLabel); m_serverName->lineEdit()->setPlaceholderText(tr("Required")); pGridLayout->addWidget(pServerNameLabel); pGridLayout->addWidget(m_serverName); DLabel *pAddressLabel = new DLabel(tr("Address:")); setLabelStyle(pAddressLabel); m_address->lineEdit()->setPlaceholderText(tr("Required")); m_address->setFixedWidth(150); pGridLayout->addWidget(pAddressLabel); pGridLayout->addWidget(m_address); QHBoxLayout *portLayout = new QHBoxLayout(); DLabel *pPortLabel = new DLabel(tr("Port:")); pPortLabel->setAlignment(Qt::AlignLeft); pPortLabel->setAlignment(Qt::AlignVCenter); pPortLabel->setFixedWidth(40); DFontSizeManager::instance()->bind(pPortLabel, DFontSizeManager::T6); m_port->setRange(0, 65535); m_port->setValue(22); m_port->setSingleStep(1); m_port->setFixedWidth(70); //comment code for old version dtk build #if (DTK_VERSION_MAJOR > 5 || (DTK_VERSION_MAJOR >= 5 && (DTK_VERSION_MINOR > 1 || (DTK_VERSION_MINOR >= 1 && DTK_VERSION_BUILD >= 2)))) m_port->lineEdit()->setClearButtonEnabled(false); #endif // 去除上下按钮 m_port->setButtonSymbols(DSpinBox::NoButtons); // 禁用输入法 m_port->setAttribute(Qt::WA_InputMethodEnabled, false); portLayout->addWidget(pPortLabel); portLayout->addWidget(m_port); pGridLayout->addLayout(portLayout, 1, 1, Qt::AlignRight); DLabel *pUsernameLabel = new DLabel(tr("Username:")); setLabelStyle(pUsernameLabel); m_userName->lineEdit()->setPlaceholderText(tr("Required")); pGridLayout->addWidget(pUsernameLabel); pGridLayout->addWidget(m_userName); DLabel *pPasswordLabel = new DLabel(tr("Password:")); setLabelStyle(pPasswordLabel); m_password->lineEdit()->setAttribute(Qt::WA_InputMethodEnabled, false); pGridLayout->addWidget(pPasswordLabel); pGridLayout->addWidget(m_password); DLabel *pPrivateKeyLabel = new DLabel(tr("Certificate:")); setLabelStyle(pPrivateKeyLabel); /******** Modify by m000714 daizhengwen 2020-04-20: 添加DFileChooseEditDialog****************/ pGridLayout->addWidget(pPrivateKeyLabel); QHBoxLayout *privateKeyLayout = new QHBoxLayout(); privateKeyLayout->setSpacing(5); privateKeyLayout->setContentsMargins(0, 0, 0, 0); privateKeyLayout->addWidget(m_privateKey); privateKeyLayout->addWidget(m_fileDialog); m_fileDialog->setIcon(DStyleHelper(m_fileDialog->style()).standardIcon(DStyle::SP_SelectElement, nullptr)); m_fileDialog->setIconSize(QSize(24, 24)); connect(m_fileDialog, &DSuggestButton::clicked, this, &ServerConfigOptDlg::slotFileChooseDialog); pGridLayout->addLayout(privateKeyLayout, 4, 1); /********************* Modify by m000714 daizhengwen End ************************/ //senior layout DWidget *seniorWidget = new DWidget; seniorWidget->setFixedWidth(459); seniorWidget->setContentsMargins(0, 0, 0, 0); QGridLayout *seniorLayout = new QGridLayout(); seniorLayout->setAlignment(Qt::AlignTop); seniorLayout->setSpacing(10); seniorLayout->setContentsMargins(28, 0, 30, 0); seniorLayout->setColumnStretch(1, 1); DLabel *pGroupLabel = new DLabel(tr("Group:")); setLabelStyle(pGroupLabel); seniorLayout->addWidget(pGroupLabel); seniorLayout->addWidget(m_group); m_group->setFixedWidth(290); DLabel *pPathLabel = new DLabel(tr("Path:")); setLabelStyle(pPathLabel); seniorLayout->addWidget(pPathLabel); seniorLayout->addWidget(m_path); m_path->setFixedWidth(290); DLabel *pCommandLabel = new DLabel(tr("Command:")); setLabelStyle(pCommandLabel); seniorLayout->addWidget(pCommandLabel); seniorLayout->addWidget(m_command); m_command->setFixedWidth(290); DLabel *pCodingLabel = new DLabel(tr("Encoding:")); setLabelStyle(pCodingLabel); seniorLayout->addWidget(pCodingLabel); seniorLayout->addWidget(m_coding); m_coding->setFixedWidth(290); DLabel *pBackspaceKeyLabel = new DLabel(tr("Backspace key:")); setLabelStyle(pBackspaceKeyLabel); seniorLayout->addWidget(pBackspaceKeyLabel); seniorLayout->addWidget(m_backSapceKey); m_backSapceKey->setFixedWidth(290); DLabel *pDeleteKeyLabel = new DLabel(tr("Delete key:")); setLabelStyle(pDeleteKeyLabel); seniorLayout->addWidget(pDeleteKeyLabel); seniorLayout->addWidget(m_deleteKey); m_deleteKey->setFixedWidth(290); seniorWidget->setLayout(seniorLayout); m_VBoxLayout->addLayout(pGridLayout, Qt::AlignHCenter); QSpacerItem *upItem = new QSpacerItem(this->width(), 10); m_VBoxLayout->addSpacerItem(upItem); m_VBoxLayout->addWidget(m_advancedOptions, 0, Qt::AlignHCenter); QSpacerItem *downItem = new QSpacerItem(this->width(), 10); m_VBoxLayout->addSpacerItem(downItem); m_VBoxLayout->addWidget(seniorWidget, 0, Qt::AlignHCenter); m_delServer->setText(tr("Delete server")); m_VBoxLayout->addWidget(m_delServer, 0, Qt::AlignHCenter); m_delServer->hide(); seniorWidget->hide(); DFontSizeManager::instance()->bind(m_advancedOptions, DFontSizeManager::T8, QFont::Normal); connect(m_advancedOptions, &DCommandLinkButton::clicked, this, [ = ]() { m_advancedOptions->hide(); seniorWidget->show(); upItem->changeSize(this->width(), 0); downItem->changeSize(this->width(), 0); if (m_type == SCT_MODIFY) { m_delServer->show(); this->setFixedHeight(670); qDebug() << "remote dialog show advance options"; } else { this->setFixedHeight(630); } }); DPushButton *pCancelButton = new DPushButton(tr("Cancel")); DSuggestButton *pAddSaveButton = new DSuggestButton(tr("Add")); //Add a line by m000750 zhangmeng 2020-04-22设置回车触发默认按钮 pAddSaveButton->setDefault(true); if (m_type == SCT_MODIFY) { m_titleLabel->setText(tr("Edit Server")); pAddSaveButton->setText(tr("Save")); } Utils::setSpaceInWord(pCancelButton); Utils::setSpaceInWord(pAddSaveButton); DPalette pa = DApplicationHelper::instance()->palette(pAddSaveButton); QBrush brush = pa.textLively().color(); pa.setBrush(DPalette::ButtonText, brush); pAddSaveButton->setPalette(pa); QHBoxLayout *pBtHbLayout = new QHBoxLayout(); DVerticalLine *line = new DVerticalLine(); pBtHbLayout->setContentsMargins(10, 0, 10, 0); pBtHbLayout->setSpacing(9); pBtHbLayout->addWidget(pCancelButton); pBtHbLayout->addWidget(line); pBtHbLayout->addWidget(pAddSaveButton); m_VBoxLayout->addStretch(10); m_VBoxLayout->addLayout(pBtHbLayout, Qt::AlignBottom); setLayout(m_VBoxLayout); connect(pCancelButton, &DPushButton::clicked, this, [ = ]() { reject(); }); connect(pAddSaveButton, &DPushButton::clicked, this, &ServerConfigOptDlg::slotAddSaveButtonClicked); connect(m_delServer, &TermCommandLinkButton::clicked, this, [ = ]() { setDelServer(true); accept(); }); // 字体颜色随主题变化变化 connect(DApplicationHelper::instance(), &DGuiApplicationHelper::themeTypeChanged, m_titleLabel, [ = ](DGuiApplicationHelper::ColorType themeType) { DPalette palette = m_titleLabel->palette(); //palette.setBrush(QPalette::WindowText, palette.color(DPalette::TextTitle)); QColor color; if (themeType == DApplicationHelper::DarkType) { color = QColor::fromRgb(192, 198, 212, 255); } else { color = QColor::fromRgb(0, 26, 46, 255); } palette.setBrush(QPalette::WindowText, color); m_titleLabel->setPalette(palette); }); } void ServerConfigOptDlg::initData() { QList textCodeList = getTextCodec(); m_coding->addItems(textCodeList); QList backSpaceKeyList = getBackSpaceKey(); m_backSapceKey->addItems(backSpaceKeyList); QList deleteKeyList = getDeleteKey(); m_deleteKey->addItems(deleteKeyList); if (m_type == SCT_MODIFY && m_curServer != nullptr) { m_serverName->setText(m_curServer->m_serverName); m_currentServerName = m_serverName->text(); m_address->setText(m_curServer->m_address); m_port->setValue(m_curServer->m_port.toInt()); m_userName->setText(m_curServer->m_userName); m_password->setText(m_curServer->m_password); m_privateKey->setText(m_curServer->m_privateKey); m_group->setText(m_curServer->m_group); m_path->setText(m_curServer->m_path); m_command->setText(m_curServer->m_command); if (!m_curServer->m_encoding.isEmpty()) { int textCodeIndex = textCodeList.indexOf(m_curServer->m_encoding); m_coding->setCurrentIndex(textCodeIndex); } if (!m_curServer->m_backspaceKey.isEmpty()) { int backSpaceKeyIndex = backSpaceKeyList.indexOf(m_curServer->m_backspaceKey); m_backSapceKey->setCurrentIndex(backSpaceKeyIndex); } if (!m_curServer->m_deleteKey.isEmpty()) { int deleteKeyIndex = deleteKeyList.indexOf(m_curServer->m_deleteKey); m_deleteKey->setCurrentIndex(deleteKeyIndex); } } } QList ServerConfigOptDlg::getTextCodec() { /******** Modify by ut000610 daizhengwen 2020-05-28: 编码列表和编码插件一致****************/ // QList list = QTextCodec::availableCodecs(); QList list = Utils::encodeList(); /********************* Modify by ut000610 daizhengwen End ************************/ QList textCodecList; for (QByteArray &byteArr : list) { QString str = QString(byteArr); if (!textCodecList.contains(str)) { textCodecList.append(str); } } return textCodecList; } QList ServerConfigOptDlg::getBackSpaceKey() { QList eraseKeyList; eraseKeyList.append(tr("ascii-del")); eraseKeyList.append(tr("auto")); eraseKeyList.append(tr("control-h")); eraseKeyList.append(tr("escape-sequence")); eraseKeyList.append(tr("tty")); return eraseKeyList; } QList ServerConfigOptDlg::getDeleteKey() { QList eraseKeyList; eraseKeyList.append(tr("escape-sequence")); eraseKeyList.append(tr("ascii-del")); eraseKeyList.append(tr("auto")); eraseKeyList.append(tr("control-h")); eraseKeyList.append(tr("tty")); return eraseKeyList; } /******************************************************************************* 1. @函数: setLabelStyle 2. @作者: m000714 戴正文 3. @日期: 2020-04-16 4. @说明: 设置label格式 *******************************************************************************/ void ServerConfigOptDlg::setLabelStyle(DLabel *label) { label->setAlignment(Qt::AlignLeft); label->setAlignment(Qt::AlignVCenter); label->setFixedWidth(100); label->setMinimumHeight(36); DFontSizeManager::instance()->bind(label, DFontSizeManager::T6); } ServerConfigOptDlg::~ServerConfigOptDlg() { } void ServerConfigOptDlg::updataData(ServerConfig *curServer) { // 读取配置 QList textCodeList = getTextCodec(); QList backSpaceKeyList = getBackSpaceKey(); QList deleteKeyList = getDeleteKey(); // 重置m_curServer // resetCurServer(curServer); m_curServer = curServer; // 设置数据 m_serverName->setText(curServer->m_serverName); m_address->setText(curServer->m_address); m_port->setValue(curServer->m_port.toInt()); m_userName->setText(curServer->m_userName); m_password->setText(curServer->m_password); m_privateKey->setText(curServer->m_privateKey); m_group->setText(curServer->m_group); m_path->setText(curServer->m_path); m_command->setText(curServer->m_command); if (!curServer->m_encoding.isEmpty()) { int textCodeIndex = textCodeList.indexOf(curServer->m_encoding); m_coding->setCurrentIndex(textCodeIndex); } if (!curServer->m_backspaceKey.isEmpty()) { int backSpaceKeyIndex = backSpaceKeyList.indexOf(curServer->m_backspaceKey); m_backSapceKey->setCurrentIndex(backSpaceKeyIndex); } if (!curServer->m_deleteKey.isEmpty()) { int deleteKeyIndex = deleteKeyList.indexOf(curServer->m_deleteKey); m_deleteKey->setCurrentIndex(deleteKeyIndex); } m_currentServerName = m_serverName->text(); } ServerConfig ServerConfigOptDlg::getData() { ServerConfig config; config.m_serverName = m_serverName->text(); config.m_address = m_address->text(); config.m_userName = m_userName->text(); config.m_password = m_password->text(); config.m_privateKey = m_privateKey->text(); config.m_port = m_port->text(); config.m_group = m_group->text(); config.m_path = m_path->text(); config.m_command = m_command->text(); config.m_encoding = m_coding->currentText(); config.m_backspaceKey = m_backSapceKey->currentText(); config.m_deleteKey = m_deleteKey->currentText(); return config; } void ServerConfigOptDlg::resetCurServer(ServerConfig config) { m_curServer->m_serverName = config.m_serverName; m_curServer->m_address = config.m_address; m_curServer->m_userName = config.m_userName; m_curServer->m_password = config.m_password; m_curServer->m_privateKey = config.m_privateKey; m_curServer->m_port = config.m_port; m_curServer->m_group = config.m_group; m_curServer->m_path = config.m_path; m_curServer->m_command = config.m_command; m_curServer->m_encoding = config.m_encoding; m_curServer->m_backspaceKey = config.m_backspaceKey; m_curServer->m_deleteKey = config.m_deleteKey; } void ServerConfigOptDlg::slotAddSaveButtonClicked() { // 服务器名为空 if (m_serverName->text().trimmed().isEmpty()) { m_serverName->showAlertMessage(tr("Please enter a server name"), m_serverName); return; } /***add begin by ut001121 zhangmeng 20200615 限制名称字符长度 修复BUG31286***/ if (m_serverName->text().length() > MAX_NAME_LEN) { m_serverName->showAlertMessage(QObject::tr("The name should be no more than 32 characters"), m_serverName); return; } /***add end by ut001121***/ // 地址为空 if (m_address->text().trimmed().isEmpty()) { m_address->showAlertMessage(tr("Please enter an IP address"), m_address); return; } // 端口为空 if (m_port->text().trimmed().isEmpty()) { m_address->showAlertMessage(tr("Please enter a port"), m_port); return; } //---added by qinyaning(nyq) to show the tip when username is empty---// if (m_userName->text().trimmed().isEmpty()) { //如果用户名为空, 提示用户名为空, 添加失败 m_userName->showAlertMessage(tr("Please enter a username"), m_userName); return; } m_currentServerName = m_serverName->text(); //------------------------------------------------------------------// //--added by qinyaning(nyq) to solve the bug 19116: You can create a new remote server with the same name--// if ((m_type == SCT_ADD) || ((m_type == SCT_MODIFY && m_curServer != nullptr) && (m_curServer->m_serverName.trimmed() != m_serverName->text().trimmed()))) { /*此时用户已经在修改模式下修改了服务器名称*/ QMap> severConfigs = ServerConfigManager::instance()->getServerConfigs(); for (QMap>::iterator iter = severConfigs.begin(); iter != severConfigs.end(); iter++) { QList value = iter.value(); for (int i = 0; i < value.size(); i++) { if (value[i]->m_serverName.trimmed() == m_serverName->text().trimmed()) { //服务器名相同 QString strFirstLine = tr("The server name already exists,"); QString strSecondeLine = tr("please input another one. "); Utils::showSameNameDialog(this, strFirstLine, strSecondeLine); return; } } } } //-------------------------------------------------------------------// ServerConfig *config = new ServerConfig(); config->m_serverName = m_serverName->text(); config->m_address = m_address->text(); config->m_userName = m_userName->text(); config->m_password = m_password->text(); config->m_privateKey = m_privateKey->text(); config->m_port = m_port->text(); config->m_group = m_group->text(); config->m_path = m_path->text(); config->m_command = m_command->text(); config->m_encoding = m_coding->currentText(); config->m_backspaceKey = m_backSapceKey->currentText(); config->m_deleteKey = m_deleteKey->currentText(); if (m_type == SCT_ADD) { ServerConfigManager::instance()->saveServerConfig(config); } else if (m_type == SCT_MODIFY && m_curServer != nullptr) { ServerConfigManager::instance()->modifyServerConfig(config, m_curServer); } qDebug() << __FUNCTION__ << "add or save remote config"; accept(); qDebug() << __FUNCTION__ << "add or save remote config finish"; } /******************************************************************************* 1. @函数: slotFileChooseDialog 2. @作者: m000714 戴正文 3. @日期: 2020-04-20 4. @说明: 获取FileName *******************************************************************************/ void ServerConfigOptDlg::slotFileChooseDialog() { DFileDialog dialog(this, QObject::tr("Select the private key file")); dialog.setAcceptMode(QFileDialog::AcceptOpen); dialog.setFileMode(QFileDialog::ExistingFile); dialog.setFilter(QDir::Files | QDir::Dirs | QDir::NoDotAndDotDot | QDir::Hidden); dialog.setLabelText(QFileDialog::Accept, QObject::tr("Select")); int code = dialog.exec(); if (code == QDialog::Accepted && !dialog.selectedFiles().isEmpty()) { QStringList list = dialog.selectedFiles(); const QString fileName = list.first(); m_privateKey->setText(fileName); } } deepin-terminal-5.2.11/src/remotemanage/serverconfigoptdlg.h000066400000000000000000000050621370157770500242060ustar00rootroot00000000000000#ifndef SERVERCONFIGOPTDLG_H #define SERVERCONFIGOPTDLG_H #include "serverconfigmanager.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include DWIDGET_USE_NAMESPACE class TermCommandLinkButton; class ServerConfigOptDlg : public DAbstractDialog { Q_OBJECT public: enum ServerConfigOptType { SCT_ADD, // the add type of server config operation SCT_MODIFY, // the modify type of server config operation }; explicit ServerConfigOptDlg(ServerConfigOptType type = SCT_ADD, ServerConfig *curServer = nullptr, QWidget *parent = nullptr); ~ServerConfigOptDlg(); ServerConfig *getCurServer() { return m_curServer; } bool isDelServer() { return m_bDelOpt; } void setDelServer(bool isDel) { m_bDelOpt = isDel; } const QString &getServerName() { return m_currentServerName; } void updataData(ServerConfig *curServer); ServerConfig getData(); void resetCurServer(ServerConfig curServer); private slots: void slotAddSaveButtonClicked(); void slotFileChooseDialog(); private: ServerConfigOptType m_type; ServerConfig *m_curServer = nullptr; DLabel *m_titleLabel = nullptr; DLabel *m_iconLabel = nullptr; DWindowCloseButton *m_closeButton = nullptr; DLineEdit *m_serverName = nullptr; DLineEdit *m_address = nullptr; DSpinBox *m_port = nullptr; DLineEdit *m_userName = nullptr; DPasswordEdit *m_password = nullptr; // DFileChooserEdit *m_privateKey = nullptr; DLineEdit *m_privateKey = nullptr; DSuggestButton *m_fileDialog = nullptr; DLineEdit *m_group = nullptr; DLineEdit *m_path = nullptr; DLineEdit *m_command = nullptr; DComboBox *m_coding = nullptr; DComboBox *m_backSapceKey = nullptr; DComboBox *m_deleteKey = nullptr; DCommandLinkButton *m_advancedOptions = nullptr; TermCommandLinkButton *m_delServer = nullptr; bool m_bDelOpt = false; void initUI(); void initData(); QList getTextCodec(); QList getBackSpaceKey(); QList getDeleteKey(); QString m_currentServerName = ""; inline void setLabelStyle(DLabel *); }; #endif // SERVERCONFIGOPTDLG_H deepin-terminal-5.2.11/src/settings/000077500000000000000000000000001370157770500173205ustar00rootroot00000000000000deepin-terminal-5.2.11/src/settings/newdspinbox.cpp000066400000000000000000000205461370157770500223730ustar00rootroot00000000000000/* -*- Mode: C++; indent-tabs-mode: nil; tab-width: 4 -*- * -*- coding: utf-8 -*- * * Copyright (C) 2011 ~ 2018 Deepin, Inc. * * Author: Wang Peili * Maintainer: Rekols * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #include "newdspinbox.h" #include #include #include #include NewDspinBox::NewDspinBox(QWidget *parent) : DWidget(parent) { m_DIconBtnAdd = new DIconButton(DStyle::SP_IncreaseElement); m_DIconBtnAdd->setFixedSize(36, 36); m_DIconBtnSubtract = new DIconButton(DStyle::SP_DecreaseElement); m_DIconBtnSubtract->setFixedSize(36, 36); m_DLineEdit = new DLineEdit(); m_DLineEdit->setClearButtonEnabled(false); m_DLineEdit->lineEdit()->setAttribute(Qt::WA_InputMethodEnabled, false); QHBoxLayout *pHBoxLayout = new QHBoxLayout(); pHBoxLayout->setSpacing(10); pHBoxLayout->setContentsMargins(0, 0, 0, 0); pHBoxLayout->addWidget(m_DLineEdit); pHBoxLayout->addWidget(m_DIconBtnAdd); pHBoxLayout->addWidget(m_DIconBtnSubtract); setLayout(pHBoxLayout); // m_QIntValidator = new QIntValidator(m_MinValue, m_MaxValue, this); // m_DLineEdit->lineEdit()->setValidator(m_QIntValidator); // m_DLineEdit->lineEdit()->setValidator(new QIntValidator(0, m_MaxValue, this)); /******** Add by nt001000 renfeixiang 2020-05-26:增加正则表达式限制00000现象 Begin***************/ QRegExp regExp("(^[1-4][0-9]$)|(^[5][0]$)|(^[5-9]$)"); m_DLineEdit->lineEdit()->setValidator(new QRegExpValidator(regExp, this)); /******** Add by nt001000 renfeixiang 2020-05-26:增加正则表达式限制00000现象 End***************/ m_DLineEdit->setFocusPolicy(Qt::NoFocus); connect(m_DIconBtnAdd, &QAbstractButton::clicked, this, [ = ] { /***add by ut001121 zhangmeng 20200509 修复BUG#24848 设置中点击“+”“-”按钮修改字体大小,前方输入框未高亮***/ m_DLineEdit->lineEdit()->setFocus(); int value = m_DLineEdit->lineEdit()->text().toInt(); if (value < m_MaxValue) { m_DLineEdit->lineEdit()->setText(QString::number(value + 1)); emit valueChanged(m_DLineEdit->lineEdit()->text().toInt()); } }); connect(m_DIconBtnSubtract, &QAbstractButton::clicked, this, [ = ] { /***add by ut001121 zhangmeng 20200509 修复BUG#24848 设置中点击“+”“-”按钮修改字体大小,前方输入框未高亮***/ m_DLineEdit->lineEdit()->setFocus(); int value = m_DLineEdit->lineEdit()->text().toInt(); if (value > m_MinValue) { m_DLineEdit->lineEdit()->setText(QString::number(value - 1)); emit valueChanged(m_DLineEdit->lineEdit()->text().toInt()); } }); // 回车即脱离焦点 connect(m_DLineEdit, &DLineEdit::returnPressed, this, [ = ] { m_DLineEdit->lineEdit()->clearFocus(); }); // 回车即脱离焦点 connect(m_DLineEdit, &DLineEdit::editingFinished, this, [ = ] { m_DLineEdit->lineEdit()->clearFocus(); }); // 脱离焦点后校正生效. connect(m_DLineEdit, &DLineEdit::focusChanged, this, [ = ](bool var) { // 退出编辑的时候,数据做个校正 if (!var) { /******** Add by nt001000 renfeixiang 2020-05-25:增加正常数据的过滤不需要处理,textChanged信号已经处理 Begin***************/ int value = m_DLineEdit->lineEdit()->text().toInt(); if(value >= 5) return ; /******** Add by nt001000 renfeixiang 2020-05-25:增加正常数据的过滤不需要处理,textChanged信号已经处理 End***************/ correctValue(); emit valueChanged(m_DLineEdit->lineEdit()->text().toInt()); } }); /******** Add by nt001000 renfeixiang 2020-05-25:增加m_DLineEdit的textChanged信号的响应 Begin***************/ connect(m_DLineEdit, &DLineEdit::textChanged, this, [ = ](const QString &value) { //过滤范围之外的数据 if(value.toInt() < 5) return ; // 对输入的数据做个校正 //correctValue(); emit valueChanged(m_DLineEdit->lineEdit()->text().toInt()); }); /******** Add by nt001000 renfeixiang 2020-05-25:增加m_DLineEdit的textChanged信号的响应 End***************/ // 选择即进入 connect(m_DLineEdit, &DLineEdit::selectionChanged, this, [ = ] { if (!m_DLineEdit->lineEdit()->hasFocus() && !m_DLineEdit->lineEdit()->selectedText().isEmpty()) { m_DLineEdit->lineEdit()->setFocus(); } }); } void NewDspinBox::setValue(int val) { m_DLineEdit->setText(QString::number(val)); } void NewDspinBox::setMaximum(int val) { if (val > m_MinValue) { m_MaxValue = val; // m_QIntValidator->setTop(m_MaxValue); // m_DLineEdit->lineEdit()->setValidator(m_QIntValidator); } } void NewDspinBox::setMinimum(int val) { if (val < m_MaxValue) { m_MinValue = val; // m_QIntValidator->setBottom(m_MinValue); // m_DLineEdit->lineEdit()->setValidator(m_QIntValidator); } } void NewDspinBox::correctValue() { int val = m_DLineEdit->text().toInt(); if (val > m_MaxValue) { m_DLineEdit->lineEdit()->setText(QString::number(m_MaxValue)); } if (val < m_MinValue) { m_DLineEdit->lineEdit()->setText(QString::number(m_MinValue)); } } //拷贝了Qt QTextLayout类的源码 void QTextLayout::drawCursor(QPainter *p, const QPointF &pos, int cursorPosition, int width) const { Q_UNUSED(width) if (d->lines.isEmpty()) return; if (!d->layoutData) d->itemize(); QPointF position = pos + d->position; cursorPosition = qBound(0, cursorPosition, d->layoutData->string.length()); int line = d->lineNumberForTextPosition(cursorPosition); if (line < 0) line = 0; if (line >= d->lines.size()) return; QTextLine l(line, d); const QScriptLine &sl = d->lines.at(line); qreal x = position.x() + l.cursorToX(cursorPosition); int itm; if (d->visualCursorMovement()) { if (cursorPosition == sl.from + sl.length) cursorPosition--; itm = d->findItem(cursorPosition); } else itm = d->findItem(cursorPosition - 1); QFixed base = sl.base(); QFixed descent = sl.descent; bool rightToLeft = d->isRightToLeft(); if (itm >= 0) { const QScriptItem &si = d->layoutData->items.at(itm); if (si.ascent > 0) base = si.ascent; if (si.descent > 0) descent = si.descent; rightToLeft = si.analysis.bidiLevel % 2; } qreal y = position.y() + (sl.y + sl.base() - base).toReal(); bool toggleAntialiasing = !(p->renderHints() & QPainter::Antialiasing) && (p->transform().type() > QTransform::TxTranslate); if (toggleAntialiasing) p->setRenderHint(QPainter::Antialiasing); QPainter::CompositionMode origCompositionMode = p->compositionMode(); if (p->paintEngine()->hasFeature(QPaintEngine::RasterOpModes)) p->setCompositionMode(QPainter::RasterOp_NotDestination); //fix bug 25203 字体输入框的光标显示较粗 //直接将原有的qreal(width) 替换成了0.1 p->fillRect(QRectF(x, y, 0.1, (base + descent).toReal()), p->pen().brush()); p->setCompositionMode(origCompositionMode); if (toggleAntialiasing) p->setRenderHint(QPainter::Antialiasing, false); if (d->layoutData->hasBidi) { const int arrow_extent = 4; int sign = rightToLeft ? -1 : 1; p->drawLine(QLineF(x, y, x + (sign * arrow_extent/2), y + arrow_extent/2)); p->drawLine(QLineF(x, y+arrow_extent, x + (sign * arrow_extent/2), y + arrow_extent/2)); } return; } deepin-terminal-5.2.11/src/settings/newdspinbox.h000066400000000000000000000034241370157770500220340ustar00rootroot00000000000000/* -*- Mode: C++; indent-tabs-mode: nil; tab-width: 4 -*- * -*- coding: utf-8 -*- * * Copyright (C) 2011 ~ 2018 Deepin, Inc. * * Author: Wang Yong * Maintainer: Rekols * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #ifndef NEWDSPINBOX_H #define NEWDSPINBOX_H #include #include #include #include #include DWIDGET_USE_NAMESPACE class NewDspinBox : public DWidget { Q_OBJECT public: explicit NewDspinBox(QWidget *parent = nullptr); void setValue(int val); void setMaximum(int val); void setMinimum(int val); signals: void valueChanged(int value); private: void correctValue(); private: DLineEdit *m_DLineEdit = nullptr; DIconButton *m_DIconBtnAdd = nullptr; DIconButton *m_DIconBtnSubtract = nullptr; QIntValidator *m_QIntValidator = nullptr; /******** Modify by nt001000 renfeixiang 2020-05-25:从100修改50,设置最大只能输入50 Begin***************/ int m_MaxValue = 50; /******** Modify by nt001000 renfeixiang 2020-05-25:从100修改50,设置最大只能输入50 End***************/ int m_MinValue = 0; }; #endif deepin-terminal-5.2.11/src/settings/settings.cpp000066400000000000000000000467061370157770500217010ustar00rootroot00000000000000#include "settings.h" #include "newdspinbox.h" #include "utils.h" #include "shortcutmanager.h" #include "../views/operationconfirmdlg.h" #include "service.h" #include #include #include #include #include #include #include #include /******** Modify by n014361 wangpeili 2020-01-04: ***********×****/ #include /********************* Modify by n014361 wangpeili End ************************/ /******** Add by ut001000 renfeixiang 2020-06-08:增加 Begin***************/ #include "dbusmanager.h" /******** Add by ut001000 renfeixiang 2020-06-08:增加 End***************/ DWIDGET_USE_NAMESPACE #define PRIVATE_PROPERTY_translateContext "_d_DSettingsWidgetFactory_translateContext" Settings *Settings::m_settings_instance = new Settings(); /******** Add by ut001000 renfeixiang 2020-06-15:增加 将comboBox初始化 Begin***************/ DComboBox *Settings::comboBox = nullptr; /******** Add by ut001000 renfeixiang 2020-06-15:增加 将comboBox初始化 Begin***************/ Settings::Settings() : QObject(qApp) { } Settings *Settings::instance() { return m_settings_instance; } Settings::~Settings() { if(nullptr != m_Watcher){ m_Watcher->deleteLater(); } if(nullptr != m_backend){ m_backend->deleteLater(); } if(nullptr != settings){ settings->deleteLater(); } } // 统一初始化以后方可使用。 void Settings::init() { m_configPath = QString("%1/%2/%3/config.conf") .arg(QStandardPaths::writableLocation(QStandardPaths::ConfigLocation), qApp->organizationName(), qApp->applicationName()); m_backend = new QSettingBackend(m_configPath); // 默认配置 settings = DSettings::fromJsonFile(":/other/default-config.json"); // 加载自定义配置 settings->setBackend(m_backend); /******** Modify by n014361 wangpeili 2020-01-10: 增加窗口状态选项 ************/ auto windowState = settings->option("advanced.window.use_on_starting"); QMap windowStateMap; windowStateMap.insert("keys", QStringList() << "window_normal" << "split_screen" << "window_maximum" << "fullscreen"); windowStateMap.insert("values", QStringList() << tr("Normal window") << tr("Split screen") << tr("Maximum") << tr("Fullscreen")); windowState->setData("items", windowStateMap); for (QString &key : settings->keys()) { qDebug() << key << settings->value(key); } /********************* Modify by n014361 wangpeili End ************************/ initConnection(); loadDefaultsWhenReinstall(); /******** Modify by ut000439 wangpeili 2020-06-12: 多进程模式,暂时取消使用*********/ /* //增加文件昨监视,以便多进程共享配置文件 m_Watcher = new QFileSystemWatcher(); m_Watcher->addPath(m_configPath); connect(m_Watcher, &QFileSystemWatcher::fileChanged, this, [this](QString file) { qDebug() << "fileChanged" << file; reload(); //监控完一次就不再监控了,所以要再添加 m_Watcher->addPath(m_configPath); }); */ /********************* Modify by n014361 wangpeili End ************************/ } //重新安装终端后在这里重置状态 void Settings::loadDefaultsWhenReinstall() { QDir installFlagPath(QStandardPaths::writableLocation(QStandardPaths::AppConfigLocation)); if (!installFlagPath.exists()) { installFlagPath.mkpath(QStandardPaths::writableLocation(QStandardPaths::AppConfigLocation)); } QString installFlagFilePath(installFlagPath.filePath("install_flag")); QFile installFlagFile(installFlagFilePath); if (installFlagFile.exists()) { //fix bug: 17676 终端窗口透明度较低,能够看到桌面上文案 this->settings->setOption("basic.interface.opacity", 100); installFlagFile.remove(); } } void Settings::initConnection() { connect(settings, &Dtk::Core::DSettings::valueChanged, this, [ = ](const QString & key, const QVariant & value) { Q_UNUSED(value) if (key.contains("basic.interface.") || key.contains("advanced.cursor.") || key.contains("advanced.scroll.")) { emit terminalSettingChanged(key); } else if (key.contains("shortcuts.")) { emit shortcutSettingChanged(key); } else { emit windowSettingChanged(key); } }); QPointer opacity = settings->option("basic.interface.opacity"); connect(opacity, &Dtk::Core::DSettingsOption::valueChanged, this, [ = ](QVariant value) { emit opacityChanged(value.toInt() / 100.0); }); QPointer cursorShape = settings->option("advanced.cursor.cursor_shape"); connect(cursorShape, &Dtk::Core::DSettingsOption::valueChanged, this, [ = ](QVariant value) { emit cursorShapeChanged(value.toInt()); }); QPointer cursorBlink = settings->option("advanced.cursor.cursor_blink"); connect(cursorBlink, &Dtk::Core::DSettingsOption::valueChanged, this, [ = ](QVariant value) { emit cursorBlinkChanged(value.toBool()); }); QPointer backgroundBlur = settings->option("advanced.window.blurred_background"); connect(backgroundBlur, &Dtk::Core::DSettingsOption::valueChanged, this, [ = ](QVariant value) { emit backgroundBlurChanged(value.toBool()); }); /******** Modify by n014361 wangpeili 2020-01-06: 字体,字体大小实时生效 ****************/ QPointer fontSize = settings->option("basic.interface.font_size"); connect(fontSize, &Dtk::Core::DSettingsOption::valueChanged, this, [ = ](QVariant value) { emit fontSizeChanged(value.toInt()); }); QPointer family = settings->option("basic.interface.font"); connect(family, &Dtk::Core::DSettingsOption::valueChanged, this, [ = ](QVariant value) { emit fontChanged(value.toString()); }); QPointer PressingScroll = settings->option("advanced.scroll.scroll_on_key"); connect(PressingScroll, &Dtk::Core::DSettingsOption::valueChanged, this, [ = ](QVariant value) { emit pressingScrollChanged(value.toBool()); }); // 取消了这个修改信号,设置信息为实时读取 // QPointer OutputtingScroll = settings->option("advanced.scroll.scroll_on_output"); // connect(OutputtingScroll, &Dtk::Core::DSettingsOption::valueChanged, this, [=](QVariant value) { // emit OutputScrollChanged(value.toBool()); // }); /********************* Modify by n014361 wangpeili End ************************/ } qreal Settings::opacity() const { return settings->option("basic.interface.opacity")->value().toInt() / 100.0; } QString Settings::colorScheme() const { return settings->option("basic.interface.theme")->value().toString(); } QString Settings::encoding() const { return m_EncodeName; } QString Settings::fontName() { return settings->option("basic.interface.font")->value().toString(); } int Settings::fontSize() { return settings->option("basic.interface.font_size")->value().toInt(); } bool Settings::PressingScroll() { return settings->option("advanced.scroll.scroll_on_key")->value().toBool(); } bool Settings::OutputtingScroll() { return settings->option("advanced.scroll.scroll_on_output")->value().toBool(); } void Settings::reload() { QSettings newSettings(m_configPath, QSettings::IniFormat); for (QString &key : newSettings.childGroups()) { // 当系统变更键值的时候,配置文件中会有一些"垃圾"配置,删除他 if (!settings->keys().contains(key)) { qDebug() << "reload failed: system not found " << key << "now remove it"; newSettings.remove(key); continue; } if (settings->value(key) != newSettings.value(key + "/value")) { qDebug() << "reload update:" << key << settings->value(key); settings->option(key)->setValue(newSettings.value(key + "/value")); } } } int Settings::cursorShape() const { return settings->option("advanced.cursor.cursor_shape")->value().toInt(); } bool Settings::cursorBlink() const { return settings->option("advanced.cursor.cursor_blink")->value().toBool(); } bool Settings::backgroundBlur() const { return settings->option("advanced.window.blurred_background")->value().toBool(); } void Settings::setColorScheme(const QString &name) { return settings->option("basic.interface.theme")->setValue(name); } void Settings::setEncoding(const QString &name) { if (name != m_EncodeName) { m_EncodeName = name; emit encodeSettingChanged(name); qDebug() << "encode changed to" << name; } } void Settings::setKeyValue(const QString &name, const QString &value) { settings->option(name)->setValue(value); } /******************************************************************************* 1. @函数: bool Settings::IsPasteSelection() 2. @作者: n014361 王培利 3. @日期: 2020-01-10 4. @说明: 获取当前配置粘贴是否为选择内容 *******************************************************************************/ bool Settings::IsPasteSelection() { return settings->option("advanced.cursor.auto_copy_selection")->value().toBool(); } /******************************************************************************* 1. @函数: isShortcutConflict 2. @作者: n014361 王培利 3. @日期: 2020-04-09 4. @说明: 与设置里的快捷键冲突检测 *******************************************************************************/ bool Settings::isShortcutConflict(const QString &Name, const QString &Key) { for (QString &tmpKey : settings->keys()) { if (settings->value(tmpKey).toString() == Key) { if (Name != tmpKey) { qDebug() << Name << Key << "is conflict with Settings!" << tmpKey << settings->value(tmpKey); return true; } } } return false; } /******** Add by ut001000 renfeixiang 2020-06-15:增加 每次显示设置界面时,更新设置的等宽字体 Begin***************/ void Settings::HandleWidthFont() { QStringList Whitelist; Whitelist = DBusManager::callAppearanceFont("monospacefont"); //将新安装的字体,加载到字体库中 QFontDatabase base; for (int i = 0; i < Whitelist.count(); ++i) { QString name = Whitelist.at(i); // qDebug() << "find combox font" << comboBox->findText(name); if (-1 == comboBox->findText(name)) { QString fontpath = QDir::homePath() + "/.local/share/fonts/" + name + "/";// + name + ".ttf"; QDir dir(fontpath); if(dir.count() > 2){ fontpath = fontpath + dir[2]; } // qDebug() << "load font path" << fontpath; int ret = base.addApplicationFont(fontpath); if(-1 == ret){ qDebug() << "load " << name << " font faild"; } } } std::sort(Whitelist.begin(), Whitelist.end(), [ = ](const QString & str1, const QString & str2) { QCollator qc; return qc.compare(str1, str2) < 0; }); QString fontname = comboBox->currentText(); comboBox->clear(); comboBox->addItems(Whitelist); qDebug() << "HandleWidthFont has update"; if (Whitelist.contains(fontname)) { comboBox->setCurrentText(fontname); } } /******** Add by ut001000 renfeixiang 2020-06-15:增加 每次显示设置界面时,更新设置的等宽字体 End***************/ QString Settings::getKeyshortcutFromKeymap(const QString &keyCategory, const QString &keyName) { return settings->option(QString("shortcuts.%1.%2").arg(keyCategory, keyName))->value().toString(); } /******** Modify by n014361 wangpeili 2020-01-04: 创建Combox控件 ***********×****/ QPair Settings::createFontComBoBoxHandle(QObject *obj) { auto option = qobject_cast(obj); /******** Modify by ut001000 renfeixiang 2020-06-15:修改 comboBox修改成成员变量,修改DBUS获取失败场景,设置成系统默认等宽字体 Begin***************/ comboBox = new DComboBox; //DComboBox *comboBox = new DComboBox; // QWidget *optionWidget = DSettingsWidgetFactory::createTwoColumWidget(option, comboBox); QPair optionWidget = DSettingsWidgetFactory::createStandardItem(QByteArray(), option, comboBox); QStringList Whitelist; Whitelist = DBusManager::callAppearanceFont("monospacefont"); std::sort(Whitelist.begin(), Whitelist.end(), [ = ](const QString & str1, const QString & str2) { QCollator qc; return qc.compare(str1, str2) < 0; }); qDebug() << "createFontComBoBoxHandle get system monospacefont"; if (Whitelist.size() <= 0) { //一般不会走这个分支,除非DBUS出现问题 qDebug() << "DBusManager::callAppearanceFont failed, get control font failed."; //DBUS获取字体失败后,设置系统默认的等宽字体 Whitelist << "Courier 10 Pitch" << "DejaVu Sans Mono" << "Liberation Mono" << "Noto Mono" << "Noto Sans Mono" << "Noto Sans Mono CJK JP" << "Noto Sans Mono CJK KR" << "Noto Sans Mono CJK SC" << "Noto Sans Mono CJK TC"; } comboBox->addItems(Whitelist); /******** Modify by ut001000 renfeixiang 2020-06-15:修改 comboBox修改成成员变量,修改DBUS获取失败场景,设置成系统默认等宽字体 End***************/ // comboBox->setItemDelegate(new FontItemDelegate); // comboBox->setFixedSize(240, 36); if (option->value().toString().isEmpty()) { option->setValue(QFontDatabase::systemFont(QFontDatabase::FixedFont).family()); } // init. comboBox->setCurrentText(option->value().toString()); connect(option, &DSettingsOption::valueChanged, comboBox, [ = ](QVariant var) { comboBox->setCurrentText(var.toString()); }); option->connect( comboBox, &QComboBox::currentTextChanged, option, [ = ](const QString & text) { option->setValue(text); }); return optionWidget; } /******************************************************************************* 1. @函数: createCustomSliderHandle 2. @作者: n014361 王培利 3. @日期: 2020-03-14 4. @说明: 自定义slider控件样式 *******************************************************************************/ QPair Settings::createCustomSliderHandle(QObject *obj) { auto option = qobject_cast(obj); DSlider *slider = new DSlider; //--added by qinyaning(nyq) to slove the problem of hide the right icon--// //const int SLIDER_FIXED_WIDTH = 296; //slider->setFixedWidth(SLIDER_FIXED_WIDTH); //------------------------------------------------------------------------s slider->setIconSize(QSize(20, 20)); slider->setLeftIcon(QIcon::fromTheme("dt_opacity_left")); slider->setRightIcon(QIcon::fromTheme("dt_opacity_right")); slider->setMaximum(option->data("max").toInt()); slider->setMinimum(option->data("min").toInt()); slider->setValue(int(instance()->opacity() * 100)); QPair optionWidget = DSettingsWidgetFactory::createStandardItem(QByteArray(), option, slider); connect(option, &DSettingsOption::valueChanged, slider, [ = ](QVariant var) { slider->setValue(var.toInt()); }); option->connect(slider, &DSlider::valueChanged, option, [ = ](QVariant var) { option->setValue(var.toInt()); }); return optionWidget; } QPair Settings::createSpinButtonHandle(QObject *obj) { auto option = qobject_cast(obj); auto rightWidget = new NewDspinBox(); // rightWidget->setObjectName("OptionDSpinBox"); rightWidget->setValue(option->value().toInt()); if (option->data("max").isValid()) { rightWidget->setMaximum(option->data("max").toInt()); } if (option->data("min").isValid()) { rightWidget->setMinimum(option->data("min").toInt()); } QPair optionWidget = DSettingsWidgetFactory::createStandardItem(QByteArray(), option, rightWidget); connect( option, &DSettingsOption::valueChanged, rightWidget, [ = ](QVariant var) { rightWidget->setValue(var.toInt()); }); option->connect(rightWidget, &NewDspinBox::valueChanged, option, [ = ](const QVariant & value) { option->setValue(value.toInt()); }); return optionWidget; } /********************* Modify by n014361 wangpeili End ************************/ QPair Settings::createShortcutEditOptionHandle(/*DSettingsWidgetFactoryPrivate *p,*/ QObject *opt) { auto option = qobject_cast(opt); auto rightWidget = new KeySequenceEdit(option); rightWidget->setObjectName("OptionShortcutEdit"); rightWidget->ShortcutDirection(Qt::AlignLeft); auto optionValue = option->value(); auto translateContext = opt->property(PRIVATE_PROPERTY_translateContext).toByteArray(); //QString optname = option->key(); //qDebug() << "optname" << optname; // 控件初始加载配置文件的值 auto updateWidgetValue = [ = ](const QVariant & optionValue, DTK_CORE_NAMESPACE::DSettingsOption * opt) { Q_UNUSED(opt) QKeySequence sequence(optionValue.toString()); QString keyseq = sequence.toString(); if (keyseq == SHORTCUT_VALUE) { return; } //qDebug() << "sequence set" << sequence; rightWidget->setKeySequence(sequence); }; updateWidgetValue(optionValue, option); // 控件输入 option->connect(rightWidget, &KeySequenceEdit::editingFinished, rightWidget, [ = ](const QKeySequence & sequence) { rightWidget->clearFocus(); // 删除 if (sequence.toString() == "Backspace") { rightWidget->clear(); option->setValue(SHORTCUT_VALUE); return ; } // 取消 if (sequence.toString() == "Esc") { rightWidget->clear(); rightWidget->setKeySequence(QKeySequence(rightWidget->option()->value().toString())); return ; } QString reason; // 有效查询 if (!ShortcutManager::instance()->checkShortcutValid(rightWidget->option()->key(), sequence.toString(), reason)) { if (sequence.toString() != "Esc") { Service::instance()->showShortcutConflictMsgbox(reason); } // 界面数据还原 rightWidget->clear(); rightWidget->setKeySequence(QKeySequence(rightWidget->option()->value().toString())); return ; } option->setValue(sequence.toString()); }); // 配置修改 option->connect(option, &DTK_CORE_NAMESPACE::DSettingsOption::valueChanged, rightWidget, [ = ](const QVariant & value) { QString keyseq = value.toString(); qDebug() << "valueChanged" << rightWidget->option()->key() << keyseq; if (keyseq == SHORTCUT_VALUE || keyseq.isEmpty()) { rightWidget->clear(); return; } rightWidget->setKeySequence(QKeySequence(keyseq)); }); return DSettingsWidgetFactory::createStandardItem(translateContext, option, rightWidget); } deepin-terminal-5.2.11/src/settings/settings.h000066400000000000000000000101711370157770500213310ustar00rootroot00000000000000#ifndef SETTINGS_H #define SETTINGS_H #include #include #include #include #include DCORE_USE_NAMESPACE DWIDGET_USE_NAMESPACE class DSettingsWidgetFactoryPrivate; class Settings : public QObject { Q_OBJECT public: static Settings *instance(); ~Settings(); void init(); void initConnection(); qreal opacity() const; int cursorShape() const; bool cursorBlink() const; bool backgroundBlur() const; QString colorScheme() const; QString encoding() const; QString fontName(); int fontSize(); bool PressingScroll(); bool OutputtingScroll(); void reload(); // 设置主题 void setColorScheme(const QString &name); // 设置编码格式, 这个现在限定当前mainwindow生效,不再使用这个全局接口了 void setEncoding(const QString &name); // 通用设置 void setKeyValue(const QString &name, const QString &value); DSettings *settings; /******** Add by ut001000 renfeixiang 2020-06-15:增加 将comboBox改成成员变量 Begin***************/ static DComboBox *comboBox; /******** Add by ut001000 renfeixiang 2020-06-15:增加 将comboBox改成成员变量 End***************/ /******** Modify by n014361 wangpeili 2020-01-04: 获取当前配置粘贴是否为选择内容 *************×****/ bool IsPasteSelection(); // 与设置里的快捷键冲突检测 bool isShortcutConflict(const QString &Name, const QString &Key); /******** Add by ut001000 renfeixiang 2020-06-15:增加 每次显示设置界面时,更新设置的等宽字体 Begin***************/ void HandleWidthFont(); /******** Add by ut001000 renfeixiang 2020-06-15:增加 每次显示设置界面时,更新设置的等宽字体 Begin***************/ public: QString getKeyshortcutFromKeymap(const QString &keyCategory, const QString &keyName); static QPair createFontComBoBoxHandle(QObject *obj); // 新增自定义slider控件 static QPair createCustomSliderHandle(QObject *obj); // 新增自定义spinbutton控件 static QPair createSpinButtonHandle(QObject *obj); // 新增自定义ShortcutEdit控件处理 static QPair createShortcutEditOptionHandle(QObject *opt); /******** Modify by n014361 wangpeili 2020-01-04: ****************/ signals: // void settingValueChanged(const QString &key, const QVariant &value); void windowSettingChanged(const QString &key); void terminalSettingChanged(const QString &key); void shortcutSettingChanged(const QString &key); void encodeSettingChanged(const QString &Name); void opacityChanged(qreal opacity); void cursorShapeChanged(int shape); void cursorBlinkChanged(bool blink); void backgroundBlurChanged(bool enabled); void pressingScrollChanged(bool enabled); void OutputScrollChanged(bool enabled); /******** Modify by n014361 wangpeili 2020-01-06:字体,字体大小修改功能 ******×****/ void fontSizeChanged(int fontSize); void fontChanged(QString fontName); /********************* Modify by n014361 wangpeili End ************************/ private: Settings(); void loadDefaultsWhenReinstall(); static Settings *m_settings_instance; Dtk::Core::QSettingBackend *m_backend; QString m_configPath; // 配置文件监视 QFileSystemWatcher * m_Watcher = nullptr; // 编码格式为当前mainwindow有效参数,不记录在文件中. QString m_EncodeName = "UTF-8"; }; class KeySequenceEdit : public DKeySequenceEdit { public: KeySequenceEdit(DTK_CORE_NAMESPACE::DSettingsOption *opt, QWidget *parent = nullptr): DKeySequenceEdit(parent) { m_poption = opt; } DTK_CORE_NAMESPACE::DSettingsOption *option() { return m_poption; } private: DTK_CORE_NAMESPACE::DSettingsOption *m_poption = nullptr; }; QPair createShortcutEditOptionHandle(DSettingsWidgetFactoryPrivate *p, QObject *opt); #define SHORTCUT_VALUE "shortcut_null" #endif // SETTINGS_H deepin-terminal-5.2.11/src/settings/settings_translation.cpp000066400000000000000000000142641370157770500243110ustar00rootroot00000000000000// This file was generated by dtk-settings-tools version 0.1.2 #include void GenerateSettingTranslate() { auto advanced_cursor_auto_copy_selectionText = QObject::tr("Copy on select"); Q_UNUSED(advanced_cursor_auto_copy_selectionText); // auto advanced_cursor_auto_hideText = QObject::tr("Cursor autohide"); auto advanced_cursor_cursor_blinkText = QObject::tr("Cursor blink"); Q_UNUSED(advanced_cursor_cursor_blinkText); auto advanced_cursor_cursor_shapeName = QObject::tr("Cursor style"); Q_UNUSED(advanced_cursor_cursor_shapeName); auto advanced_scroll_scroll_on_keyText = QObject::tr("Scroll on keystroke"); Q_UNUSED(advanced_scroll_scroll_on_keyText); auto advanced_scroll_scroll_on_outputText = QObject::tr("Scroll on output"); Q_UNUSED(advanced_scroll_scroll_on_outputText); auto advanced_window_auto_hide_raytheon_windowText = QObject::tr("Hide Quake window after losing focus"); Q_UNUSED(advanced_window_auto_hide_raytheon_windowText); auto advanced_window_blurred_backgroundText = QObject::tr("Blur background"); Q_UNUSED(advanced_window_blurred_backgroundText); auto advanced_window_use_on_startingName = QObject::tr("Use on starting"); Q_UNUSED(advanced_window_use_on_startingName); auto basic_interface_fontName = QObject::tr("Font"); Q_UNUSED(basic_interface_fontName); auto basic_interface_font_sizeName = QObject::tr("Font size"); Q_UNUSED(basic_interface_font_sizeName); auto basic_interface_opacityName = QObject::tr("Opacity"); Q_UNUSED(basic_interface_opacityName); auto group_advancedName = QObject::tr("Advanced"); Q_UNUSED(group_advancedName); auto group_advanced_cursorName = QObject::tr("Cursor"); Q_UNUSED(group_advanced_cursorName); auto group_advanced_scrollName = QObject::tr("Scroll"); Q_UNUSED(group_advanced_scrollName); auto group_advanced_windowName = QObject::tr("Window"); Q_UNUSED(group_advanced_windowName); auto group_basicName = QObject::tr("Basic"); Q_UNUSED(group_basicName); auto group_basic_interfaceName = QObject::tr("Interface"); Q_UNUSED(group_basic_interfaceName); auto group_shortcutsName = QObject::tr("Shortcuts"); Q_UNUSED(group_shortcutsName); auto group_shortcuts_advancedName = QObject::tr("Others"); Q_UNUSED(group_shortcuts_advancedName); auto group_shortcuts_terminalName = QObject::tr("Terminal"); Q_UNUSED(group_shortcuts_terminalName); auto group_shortcuts_workspaceName = QObject::tr("Workspace"); Q_UNUSED(group_shortcuts_workspaceName); auto shortcuts_advanced_custom_commandName = QObject::tr("Custom commands"); Q_UNUSED(shortcuts_advanced_custom_commandName); auto shortcuts_advanced_display_shortcutsName = QObject::tr("Display shortcuts"); Q_UNUSED(shortcuts_advanced_display_shortcutsName); auto shortcuts_advanced_remote_managementName = QObject::tr("Remote management"); Q_UNUSED(shortcuts_advanced_remote_managementName); auto shortcuts_advanced_rename_tabName = QObject::tr("Rename title"); Q_UNUSED(shortcuts_advanced_rename_tabName); auto shortcuts_advanced_switch_fullscreenName = QObject::tr("Fullscreen"); Q_UNUSED(shortcuts_advanced_switch_fullscreenName); auto shortcuts_terminal_copyName = QObject::tr("Copy"); Q_UNUSED(shortcuts_terminal_copyName); auto shortcuts_terminal_default_sizeName = QObject::tr("Default size"); Q_UNUSED(shortcuts_terminal_default_sizeName); auto shortcuts_terminal_pasteName = QObject::tr("Paste"); Q_UNUSED(shortcuts_terminal_pasteName); auto shortcuts_terminal_searchName = QObject::tr("Search"); Q_UNUSED(shortcuts_terminal_searchName); auto shortcuts_terminal_select_allName = QObject::tr("Select all"); Q_UNUSED(shortcuts_terminal_select_allName); auto shortcuts_terminal_skip_to_next_commandName = QObject::tr("Jump to next command"); Q_UNUSED(shortcuts_terminal_skip_to_next_commandName); auto shortcuts_terminal_skip_to_previous_commandName = QObject::tr("Jump to previous command"); Q_UNUSED(shortcuts_terminal_skip_to_previous_commandName); auto shortcuts_terminal_zoom_inName = QObject::tr("Zoom in"); Q_UNUSED(shortcuts_terminal_zoom_inName); auto shortcuts_terminal_zoom_outName = QObject::tr("Zoom out"); Q_UNUSED(shortcuts_terminal_zoom_outName); auto shortcuts_workspace_close_other_windowsName = QObject::tr("Close other windows"); Q_UNUSED(shortcuts_workspace_close_other_windowsName); auto shortcuts_workspace_close_other_workspace = QObject::tr("Close other workspaces"); Q_UNUSED(shortcuts_workspace_close_other_workspace); auto shortcuts_workspace_close_windowName = QObject::tr("Close window"); Q_UNUSED(shortcuts_workspace_close_windowName); auto shortcuts_workspace_close_workspaceName = QObject::tr("Close workspace"); Q_UNUSED(shortcuts_workspace_close_workspaceName); auto shortcuts_workspace_horionzal_splitName = QObject::tr("Horizontal split"); Q_UNUSED(shortcuts_workspace_horionzal_splitName); auto shortcuts_workspace_new_workspaceName = QObject::tr("New workspace"); Q_UNUSED(shortcuts_workspace_new_workspaceName); auto shortcuts_workspace_next_workspaceName = QObject::tr("Next workspace"); Q_UNUSED(shortcuts_workspace_next_workspaceName); auto shortcuts_workspace_previous_workspaceName = QObject::tr("Previous workspace"); Q_UNUSED(shortcuts_workspace_previous_workspaceName); auto shortcuts_workspace_select_left_windowName = QObject::tr("Select left window"); Q_UNUSED(shortcuts_workspace_select_left_windowName); auto shortcuts_workspace_select_lower_windowName = QObject::tr("Select lower window"); Q_UNUSED(shortcuts_workspace_select_lower_windowName); auto shortcuts_workspace_select_right_windowName = QObject::tr("Select right window"); Q_UNUSED(shortcuts_workspace_select_right_windowName); auto shortcuts_workspace_select_upper_windowName = QObject::tr("Select upper window"); Q_UNUSED(shortcuts_workspace_select_upper_windowName); auto shortcuts_workspace_vertical_splitName = QObject::tr("Vertical split"); Q_UNUSED(shortcuts_workspace_vertical_splitName); auto shortcuts_terminal_FindName = QObject::tr("Find"); Q_UNUSED(shortcuts_terminal_FindName); } deepin-terminal-5.2.11/src/settings/shortcutmanager.cpp000066400000000000000000000353561370157770500232460ustar00rootroot00000000000000#include "shortcutmanager.h" #include "termwidgetpage.h" #include "mainwindow.h" #include "settings.h" #include #include #include #include #include #define INI_FILE_CODEC QTextCodec::codecForName("UTF-8") // this class only provided for convenience, do not do anything in the construct function, // let the caller decided when to create the shortcuts. ShortcutManager *ShortcutManager::m_instance = nullptr; ShortcutManager::ShortcutManager(QObject *parent) : QObject(parent) { // Q_UNUSED(parent); // make sure it is NOT a nullptr since we'll use it all the time. // Q_CHECK_PTR(parent); } ShortcutManager *ShortcutManager::instance() { if (nullptr == m_instance) { m_instance = new ShortcutManager(); } return m_instance; } void ShortcutManager::initShortcuts() { //m_builtinShortcuts = createBuiltinShortcutsFromConfig(); // use QAction or QShortcut ? //QStringList builtinShortcuts; m_builtinShortcuts << "F1"; m_builtinShortcuts << "Ctrl+C"; m_builtinShortcuts << "Ctrl+D"; for (int i = 0; i <= 9; i++) { m_builtinShortcuts << QString("ctrl+shift+%1").arg(i); } // for(int i = 0; i < m_builtinShortcuts.size(); i++) // { // m_GloableShortctus[QString("builtin_%1").arg(i)] = m_builtinShortcuts.at(i); // } createCustomCommandsFromConfig(); } ShortcutManager::~ShortcutManager() { qDeleteAll(m_customCommandActionList.begin(), m_customCommandActionList.end()); m_customCommandActionList.clear(); } void ShortcutManager::initConnect(MainWindow *mainWindow) { for (auto &commandAction : m_customCommandActionList) { connect(commandAction, &QAction::triggered, mainWindow, [ = ]() { qDebug() << "commandAction->data().toString() is triggered" << mainWindow; qDebug() << commandAction->parent(); if (!mainWindow->isActiveWindow()) { return ; } QString command = commandAction->data().toString(); if (!command.endsWith('\n')) { command.append('\n'); } mainWindow->currentPage()->sendTextToCurrentTerm(command); }); } mainWindow->addActions(m_customCommandActionList); } void ShortcutManager::createCustomCommandsFromConfig() { QDir customCommandBasePath(QStandardPaths::writableLocation(QStandardPaths::AppConfigLocation)); if (!customCommandBasePath.exists()) { return ; } QString customCommandConfigFilePath(customCommandBasePath.filePath("command-config.conf")); qDebug() << "load Custom Commands Config: " << customCommandConfigFilePath; if (!QFile::exists(customCommandConfigFilePath)) { return ; } QSettings commandsSettings(customCommandConfigFilePath, QSettings::IniFormat); commandsSettings.setIniCodec(INI_FILE_CODEC); QStringList commandGroups = commandsSettings.childGroups(); // qDebug() << commandGroups.size() << endl; for (const QString &commandName : commandGroups) { commandsSettings.beginGroup(commandName); if (!commandsSettings.contains("Command")) { continue; } QAction *action = new QAction(commandName, this); action->setData(commandsSettings.value("Command").toString()); // make sure it is a QString if (commandsSettings.contains("Shortcut")) { QVariant shortcutVariant = commandsSettings.value("Shortcut"); if (shortcutVariant.type() == QVariant::KeySequence) { action->setShortcut(shortcutVariant.convert(QMetaType::QKeySequence)); } else if (shortcutVariant.type() == QVariant::String) { // to make it compatible to deepin-terminal config file. QString shortcutStr = shortcutVariant.toString().remove(QChar(' ')); action->setShortcut(QKeySequence(shortcutStr)); } } // if (isShortcutExistInSetting(action->shortcut().toString())) { // action->setEnabled(false); // } // connect(action, &QAction::triggered, m_mainWindow, [this, action]() { // QString command = action->data().toString(); // if (!command.endsWith('\n')) { // command.append('\n'); // } // m_mainWindow->currentPage()->sendTextToCurrentTerm(command); // }); commandsSettings.endGroup(); m_customCommandActionList.append(action); } } QList ShortcutManager::createBuiltinShortcutsFromConfig() { QList actionList; // TODO. // QAction *action = nullptr; // action = new QAction("__builtin_focus_nav_up", this); // // blumia: in Qt 5.7.1 (from Debian stretch) if we pass something like "Ctrl+Shift+Q" to QKeySequence then it // won't works. // // in Qt 5.11.3 (from Debian buster) it works fine. // action->setShortcut(QKeySequence("Alt+k")); // connect(action, &QAction::triggered, m_mainWindow, [this](){ // TermWidgetPage *page = m_mainWindow->currentTab(); // if (page) page->focusNavigation(Up); // }); // actionList.append(action); return actionList; } QList &ShortcutManager::getCustomCommandActionList() { qDebug() << __FUNCTION__ << m_customCommandActionList; return m_customCommandActionList; } //void ShortcutManager::setMainWindow(MainWindow *curMainWindow) //{ // m_mainWindow = curMainWindow; //} QAction *ShortcutManager::addCustomCommand(QAction &action) { qDebug() << __FUNCTION__ << __LINE__; QAction *addAction = new QAction(action.text(), this); addAction->setData(action.data()); addAction->setShortcut(action.shortcut()); m_customCommandActionList.append(addAction); //m_mainWindow->addAction(addAction); // mainWindowAddAction(addAction); // connect(addAction, &QAction::triggered, m_mainWindow, [this, addAction]() { // QString command = addAction->data().toString(); // if (!command.endsWith('\n')) { // command.append('\n'); // } // m_mainWindow->currentPage()->sendTextToCurrentTerm(command); // }); saveCustomCommandToConfig(addAction, -1); emit addCustomCommandSignal(addAction); return addAction; } //void ShortcutManager::mainWindowAddAction(QAction *action) //{ // //if (!isShortcutExistInSetting(action->shortcut().toString())) { // m_mainWindow->addAction(action); // //} //} QAction *ShortcutManager::checkActionIsExist(QAction &action) { QString strNewActionName = action.text(); for (int i = 0; i < m_customCommandActionList.size(); i++) { QAction *currAction = m_customCommandActionList[i]; if (strNewActionName == currAction->text()) { return currAction; } } return nullptr; } /************************ Mod by m000743 sunchengxi 2020-04-21:自定义命令修改的异常问题 Begin************************/ QAction *ShortcutManager::checkActionIsExistForModify(QAction &action) { QString strNewActionName = action.text(); for (int i = 0; i < m_customCommandActionList.size(); i++) { QAction *currAction = m_customCommandActionList[i]; if (strNewActionName == currAction->text() && action.data() == currAction->data() && action.shortcut() == currAction->shortcut()) { return currAction; } } return nullptr; } /************************ Mod by m000743 sunchengxi 2020-04-21:自定义命令修改的异常问题 End ************************/ /******************************************************************************* 1. @函数: isShortcutConflictInCustom 2. @作者: n014361 王培利 3. @日期: 2020-04-09 4. @说明: 快捷键是否已被自定义设置 *******************************************************************************/ bool ShortcutManager::isShortcutConflictInCustom(const QString &Name, const QString &Key) { //qDebug()<<"isShortcutConflictInCustom"; for (auto &currAction : m_customCommandActionList) { if (Key == currAction->shortcut().toString()) { if (Name != currAction->text()) { qDebug() << Name << Key << "is conflict with custom shortcut!"; return true; } } } return false; } /******************************************************************************* 1. @函数: isValidShortcut 2. @作者: n014361 王培利 3. @日期: 2020-03-31 4. @说明: 判断快捷键是否合法可用,并进行界面处理 *******************************************************************************/ bool ShortcutManager::isValidShortcut(const QString &Name, const QString &Key) { QString reason; if (!checkShortcutValid(Name, Key, reason)) { if (Key != "Esc") { Utils::showShortcutConflictMsgbox(reason); } return false; } return true; } /******************************************************************************* 1. @函数: checkShortcutValid 2. @作者: n014361 王培利 3. @日期: 2020-04-09 4. @说明: 判断快捷键是否合法可用 目前单键除了F1-F12, 其它单键均不可以设置 内置,自定义,设置分别检测冲突 *******************************************************************************/ bool ShortcutManager::checkShortcutValid(const QString &Name, const QString &Key, QString &Reason) { QString style = QString("%1").arg(Key); // 单键 if (Key.count("+") == 0) { //F1-F12是允许的,这个正则不够精确,但是没关系。 QRegExp regexp("^F[0-9]{1,2}$"); if (!Key.contains(regexp)) { qDebug() << Key << "is invalid!"; Reason = tr("The shortcut %1 is invalid, ") .arg(style); return false; } } // 小键盘单键都不允许 QRegExp regexpNum("^Num+.*"); if (Key.contains(regexpNum)) { qDebug() << Key << "is invalid!"; Reason = tr("The shortcut %1 is invalid, ") .arg(style); return false; } // 内置快捷键都不允许 if (m_builtinShortcuts.contains(Key)) { qDebug() << Key << "is conflict with builtin shortcut!"; Reason = tr("The shortcut %1 was already in use, ") .arg(style); return false; } // 与设置里的快捷键冲突检测 if (Settings::instance()->isShortcutConflict(Name, Key)) { Reason = tr("The shortcut %1 was already in use, ") .arg(style); return false; } // 与自定义快捷键冲突检测 if (isShortcutConflictInCustom(Name, Key)) { Reason = tr("The shortcut %1 was already in use, ") .arg(style); return false; } return true; } void ShortcutManager::delCustomCommand(CustomCommandItemData itemData) { qDebug() << __FUNCTION__ << __LINE__; delCustomCommandToConfig(itemData); QString actionCmdName = itemData.m_cmdName; //QString actionCmdText = itemData.m_cmdText; //QString actionKeySeq = itemData.m_cmdShortcut; for (int i = 0; i < m_customCommandActionList.size(); i++) { QAction *currAction = m_customCommandActionList.at(i); QString currCmdName = currAction->text(); //QString currCmdText = currAction->data().toString(); //QString currKeySeq = currAction->shortcut().toString(); //if (actionCmdName == currCmdName // && actionCmdText == currCmdText // && actionKeySeq == currKeySeq) { if (actionCmdName == currCmdName) { // m_mainWindow->removeAction(m_customCommandActionList.at(i)); emit removeCustomCommandSignal(m_customCommandActionList.at(i)); m_customCommandActionList.at(i)->deleteLater(); m_customCommandActionList.removeAt(i); break; } } } void ShortcutManager::saveCustomCommandToConfig(QAction *action, int saveIndex) { qDebug() << __FUNCTION__ << __LINE__; QDir customCommandBasePath(QStandardPaths::writableLocation(QStandardPaths::AppConfigLocation)); if (!customCommandBasePath.exists()) { customCommandBasePath.mkpath(QStandardPaths::writableLocation(QStandardPaths::AppConfigLocation)); } QString customCommandConfigFilePath(customCommandBasePath.filePath("command-config.conf")); QSettings commandsSettings(customCommandConfigFilePath, QSettings::IniFormat); commandsSettings.setIniCodec(INI_FILE_CODEC); commandsSettings.beginGroup(action->text()); commandsSettings.setValue("Command", action->data()); //QString tmp = action->shortcut().toString(); commandsSettings.setValue("Shortcut", action->shortcut().toString()); commandsSettings.endGroup(); qDebug() << "saveIndex:" << saveIndex; if (saveIndex >= 0) { QAction *saveAction = new QAction; saveAction->setText(action->text()); saveAction->setData(action->data()); saveAction->setShortcut(action->shortcut()); qDebug() << "old" << m_customCommandActionList[saveIndex]->shortcut(); //m_mainWindow->removeAction(m_customCommandActionList[saveIndex]); m_customCommandActionList[saveIndex] = saveAction; //m_mainWindow->addAction(saveAction); // mainWindowAddAction(saveAction); // connect(saveAction, &QAction::triggered, m_mainWindow, [this, saveAction]() { // QString command = saveAction->data().toString(); // if (!command.endsWith('\n')) { // command.append('\n'); // } // m_mainWindow->currentPage()->sendTextToCurrentTerm(command); // }); qDebug() << "new" << m_customCommandActionList[saveIndex]->shortcut(); } } int ShortcutManager::delCustomCommandToConfig(CustomCommandItemData itemData) { qDebug() << __FUNCTION__ << __LINE__; QDir customCommandBasePath(QStandardPaths::writableLocation(QStandardPaths::AppConfigLocation)); if (!customCommandBasePath.exists()) { customCommandBasePath.mkpath(QStandardPaths::writableLocation(QStandardPaths::AppConfigLocation)); } QString customCommandConfigFilePath(customCommandBasePath.filePath("command-config.conf")); QSettings commandsSettings(customCommandConfigFilePath, QSettings::IniFormat); commandsSettings.setIniCodec(INI_FILE_CODEC); commandsSettings.remove(itemData.m_cmdName); int removeIndex = -1; for (int i = 0; i < m_customCommandActionList.size(); i++) { QAction *currAction = m_customCommandActionList[i]; if (itemData.m_cmdName == currAction->text()) { removeIndex = i; break; } } return removeIndex; } //QString ShortcutManager::getClipboardCommandData() //{ // // 从mainwindwo 绕了一圈过来的数据 // return m_mainWindow->selectedText(true); //} deepin-terminal-5.2.11/src/settings/shortcutmanager.h000066400000000000000000000033401370157770500226770ustar00rootroot00000000000000#ifndef SHORTCUTMANAGER_H #define SHORTCUTMANAGER_H #include "define.h" #include "customcommanditemmodel.h" #include "utils.h" #include #include class MainWindow; class ShortcutManager : public QObject { Q_OBJECT public: ShortcutManager(QObject *parent = nullptr); //void setMainWindow(MainWindow *curMainWindow); static ShortcutManager *instance(); ~ShortcutManager(); void initShortcuts(); void initConnect(MainWindow *mainWindow); void createCustomCommandsFromConfig(); QList createBuiltinShortcutsFromConfig(); QList &getCustomCommandActionList(); QAction *addCustomCommand(QAction &action); //void mainWindowAddAction(QAction *action); void delCustomCommand(CustomCommandItemData itemData); void saveCustomCommandToConfig(QAction *action, int saveIndex); int delCustomCommandToConfig(CustomCommandItemData itemData); // check same name of the action is exist QAction *checkActionIsExist(QAction &action); QAction *checkActionIsExistForModify(QAction &action); // 判断快捷键是否合法可用,进行界面处理 bool isValidShortcut(const QString &Name, const QString &Key); // 检测快捷键是否合法可用,无界面 bool checkShortcutValid(const QString &Name, const QString &Key, QString &Reason); // 快捷键是否已被自定义设置 bool isShortcutConflictInCustom(const QString &Name, const QString &Key); signals: void addCustomCommandSignal(QAction *newAction); void removeCustomCommandSignal(QAction *newAction); private: QList m_customCommandActionList; QStringList m_builtinShortcuts; static ShortcutManager *m_instance; }; #endif // SHORTCUTMANAGER_H deepin-terminal-5.2.11/src/theme/000077500000000000000000000000001370157770500165625ustar00rootroot00000000000000deepin-terminal-5.2.11/src/theme/themeitemdelegate.cpp000066400000000000000000000042271370157770500227470ustar00rootroot00000000000000#include "themeitemdelegate.h" #include #include ThemeItemDelegate::ThemeItemDelegate(QAbstractItemView *parent) : DStyledItemDelegate(parent) { } void ThemeItemDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const { const QRect &rect = option.rect; const QString &themeName = index.data(114514).toString(); painter->setRenderHint(QPainter::Antialiasing, true); QFont font; font.setPointSize(10); painter->setFont(font); int paddingX = 15; int paddingY = 8; int m_frameRadius = 5; QString backgroundColor = "black"; QString frameSelectedColor = "green"; QString frameNormalColor = "blue"; QString otherColor = "white"; // draw background. QPainterPath backgroundPath; backgroundPath.addRoundedRect( QRect(rect.x() + paddingX, rect.y() + paddingY, rect.width() - paddingX * 2, rect.height() - paddingY * 2), m_frameRadius, m_frameRadius); painter->setOpacity(0.8); painter->fillPath(backgroundPath, QColor(backgroundColor)); // draw border frame. QPainterPath framePath; framePath.addRoundedRect( QRect(rect.x() + paddingX, rect.y() + paddingY, rect.width() - paddingX * 2, rect.height() - paddingY * 2), m_frameRadius, m_frameRadius); QPen framePen; if (option.state & QStyle::State_Selected) { painter->setOpacity(1); framePen = QPen(QColor(frameSelectedColor), 2); } else { painter->setOpacity(0.3); framePen = QPen(QColor(frameNormalColor), 1); } painter->setPen(framePen); painter->drawPath(framePath); // draw color theme prevew text. painter->setOpacity(1); //QFontMetrics fm(font); int lineHeight = 20; int nameX = paddingX + 8; int nameY = paddingY + 8; painter->setPen(QPen(QColor(otherColor))); painter->drawText( QRect(rect.x() + nameX, rect.y() + nameY, rect.width(), lineHeight), Qt::AlignLeft | Qt::AlignTop, themeName); } QSize ThemeItemDelegate::sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const { Q_UNUSED(option) Q_UNUSED(index) return QSize(-1, 61); } deepin-terminal-5.2.11/src/theme/themeitemdelegate.h000066400000000000000000000007471370157770500224170ustar00rootroot00000000000000#ifndef THEMEITEMDELEGATE_H #define THEMEITEMDELEGATE_H #include DWIDGET_USE_NAMESPACE class ThemeItemDelegate : public DStyledItemDelegate { Q_OBJECT public: ThemeItemDelegate(QAbstractItemView *parent = nullptr); protected: void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const; QSize sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const; }; #endif // THEMEITEMDELEGATE_H deepin-terminal-5.2.11/src/theme/themelistmodel.cpp000066400000000000000000000010271370157770500223050ustar00rootroot00000000000000#include "themelistmodel.h" #include "qtermwidget.h" ThemeListModel::ThemeListModel(QObject *parent) : QAbstractListModel(parent) { initThemeData(); } int ThemeListModel::rowCount(const QModelIndex &parent) const { Q_UNUSED(parent); return m_themeData.count(); } QVariant ThemeListModel::data(const QModelIndex &index, int role) const { Q_UNUSED(role); const int row = index.row(); return m_themeData[row]; } void ThemeListModel::initThemeData() { m_themeData = QTermWidget::availableColorSchemes(); } deepin-terminal-5.2.11/src/theme/themelistmodel.h000066400000000000000000000006611370157770500217550ustar00rootroot00000000000000#ifndef THEMELISTMODEL_H #define THEMELISTMODEL_H #include class ThemeListModel : public QAbstractListModel { Q_OBJECT public: ThemeListModel(QObject *parent = nullptr); int rowCount(const QModelIndex &parent) const override; QVariant data(const QModelIndex &index, int role) const override; private: void initThemeData(); QList m_themeData; }; #endif // THEMELISTMODEL_H deepin-terminal-5.2.11/src/theme/themelistview.cpp000066400000000000000000000016371370157770500221660ustar00rootroot00000000000000#include "themelistview.h" ThemeListView::ThemeListView(QWidget *parent) : QListView(parent) { setVerticalScrollMode(ScrollPerPixel); setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn); setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); } void ThemeListView::focusOutEvent(QFocusEvent *event) { emit focusOut(); QListView::focusOutEvent(event); } void ThemeListView::selectionChanged(const QItemSelection &selected, const QItemSelection &deselected) { // Theme changed. QModelIndexList list = selected.indexes(); const QModelIndex &index = list.first(); const QString &themeName = index.data(1919810).toString(); emit themeChanged(themeName); // for (const QModelIndex &index : list) { // const QString &themeName = index.data(1919810).toString(); // emit themeChanged(themeName); // break; // } QListView::selectionChanged(selected, deselected); } deepin-terminal-5.2.11/src/theme/themelistview.h000066400000000000000000000007111370157770500216230ustar00rootroot00000000000000#ifndef THEMELISTVIEW_H #define THEMELISTVIEW_H #include class ThemeListView : public QListView { Q_OBJECT public: ThemeListView(QWidget *parent = nullptr); protected: void focusOutEvent(QFocusEvent *event) override; void selectionChanged(const QItemSelection &selected, const QItemSelection &deselected) override; signals: void focusOut(); void themeChanged(const QString themeName); }; #endif // THEMELISTVIEW_H deepin-terminal-5.2.11/src/theme/themepanel.cpp000066400000000000000000000015741370157770500214170ustar00rootroot00000000000000#include "themepanel.h" #include "themelistview.h" #include "themelistmodel.h" #include "themeitemdelegate.h" #include #include #include ThemePanel::ThemePanel(QWidget *parent) : RightPanel(parent), m_themeView(new ThemeListView(this)), m_themeModel(new ThemeListModel(this)) { // init view. m_themeView->setModel(m_themeModel); m_themeView->setItemDelegate(new ThemeItemDelegate(m_themeView)); setFocusProxy(m_themeView); QScroller::grabGesture(m_themeView, QScroller::TouchGesture); // init layout. QVBoxLayout *layout = new QVBoxLayout(this); layout->addWidget(m_themeView); layout->setMargin(0); layout->setSpacing(0); connect(m_themeView, &ThemeListView::focusOut, this, &RightPanel::hideAnim); connect(m_themeView, &ThemeListView::themeChanged, this, &ThemePanel::themeChanged); } deepin-terminal-5.2.11/src/theme/themepanel.h000066400000000000000000000006251370157770500210600ustar00rootroot00000000000000#ifndef THEMEPANEL_H #define THEMEPANEL_H #include "rightpanel.h" class ThemeListView; class ThemeListModel; class ThemePanel : public RightPanel { Q_OBJECT public: explicit ThemePanel(QWidget *parent = nullptr); signals: void themeChanged(const QString themeName); private: ThemeListView *m_themeView = nullptr; ThemeListModel *m_themeModel = nullptr; }; #endif // THEMEPANEL_H deepin-terminal-5.2.11/src/theme/themepanelplugin.cpp000066400000000000000000000022171370157770500226310ustar00rootroot00000000000000#include "themepanelplugin.h" #include "mainwindow.h" #include "themepanel.h" #include "termwidgetpage.h" #include "settings.h" ThemePanelPlugin::ThemePanelPlugin(QObject *parent) : MainWindowPluginInterface(parent) { m_pluginName = "Theme"; } void ThemePanelPlugin::initPlugin(MainWindow *mainWindow) { m_mainWindow = mainWindow; } QAction *ThemePanelPlugin::titlebarMenu(MainWindow *mainWindow) { QAction *switchThemeAction(new QAction("Switch theme", mainWindow)); connect(switchThemeAction, &QAction::triggered, this, [this]() { getThemePanel()->show(); }); return switchThemeAction; } ThemePanel *ThemePanelPlugin::getThemePanel() { if (!m_themePanel) { initThemePanel(); } return m_themePanel; } void ThemePanelPlugin::initThemePanel() { m_themePanel = new ThemePanel(m_mainWindow->centralWidget()); connect(m_themePanel, &ThemePanel::themeChanged, this, [ = ](const QString themeName) { m_mainWindow->forAllTabPage([themeName](TermWidgetPage * tabPage) { tabPage->setColorScheme(themeName); }); Settings::instance()->setColorScheme(themeName); }); } deepin-terminal-5.2.11/src/theme/themepanelplugin.h000066400000000000000000000010471370157770500222760ustar00rootroot00000000000000#ifndef THEMEPANELPLUGIN_H #define THEMEPANELPLUGIN_H #include "mainwindowplugininterface.h" class ThemePanel; class MainWindow; class ThemePanelPlugin : public MainWindowPluginInterface { Q_OBJECT public: ThemePanelPlugin(QObject *parent); void initPlugin(MainWindow *mainWindow) override; QAction *titlebarMenu(MainWindow *mainWindow) override; ThemePanel *getThemePanel(); void initThemePanel(); private: MainWindow *m_mainWindow = nullptr; ThemePanel *m_themePanel = nullptr; }; #endif // THEMEPANELPLUGIN_H deepin-terminal-5.2.11/src/views/000077500000000000000000000000001370157770500166155ustar00rootroot00000000000000deepin-terminal-5.2.11/src/views/commonpanel.cpp000066400000000000000000000005241370157770500216320ustar00rootroot00000000000000#include "commonpanel.h" #include #include #include CommonPanel::CommonPanel(QWidget *parent) : QFrame(parent) { } void CommonPanel::clearSearchInfo() { if (m_searchEdit) { m_searchEdit->blockSignals(true); m_searchEdit->clear(); m_searchEdit->blockSignals(false); } } deepin-terminal-5.2.11/src/views/commonpanel.h000066400000000000000000000012021370157770500212710ustar00rootroot00000000000000#ifndef COMMONPANEL_H #define COMMONPANEL_H #include "rightpanel.h" #include "customcommandlist.h" #include #include #include #include #include #include DWIDGET_USE_NAMESPACE class CommonPanel : public QFrame { Q_OBJECT public: explicit CommonPanel(QWidget *parent = nullptr); void clearSearchInfo(); signals: void focusOut(); public: DIconButton *m_backButton = nullptr; DSearchEdit *m_searchEdit = nullptr; DPushButton *m_pushButton = nullptr; DLabel *m_label = nullptr; bool m_isShow = false; }; #endif // COMMONPANEL_H deepin-terminal-5.2.11/src/views/myiconbutton.cpp000066400000000000000000000006441370157770500220570ustar00rootroot00000000000000#include "myiconbutton.h" #include MyIconButton::MyIconButton(QWidget *parent) : DIconButton(parent) { } void MyIconButton::enterEvent(QEvent *event) { setIcon(QIcon(":/icons/deepin/builtin/focus/edit_press.svg")); DIconButton::enterEvent(event); } void MyIconButton::leaveEvent(QEvent *event) { setIcon(QIcon(":/icons/deepin/builtin/hover/edit_hover.svg")); DIconButton::leaveEvent(event); } deepin-terminal-5.2.11/src/views/myiconbutton.h000066400000000000000000000006131370157770500215200ustar00rootroot00000000000000#ifndef MYICONBUTTON_H #define MYICONBUTTON_H #include #include DWIDGET_USE_NAMESPACE class MyIconButton : public DIconButton { Q_OBJECT public: explicit MyIconButton(QWidget *parent = nullptr); signals: void sigHoverd(); protected: void enterEvent(QEvent *event) override; void leaveEvent(QEvent *event) override; }; #endif // MYICONBUTTON_H deepin-terminal-5.2.11/src/views/operationconfirmdlg.cpp000066400000000000000000000151051370157770500233700ustar00rootroot00000000000000#include "operationconfirmdlg.h" #include "utils.h" #include #include #include #include #include #include #include OperationConfirmDlg::OperationConfirmDlg(QWidget *parent) : DAbstractDialog(parent) { initUI(); initContentLayout(); initConnections(); } void OperationConfirmDlg::initUI() { setWindowModality(Qt::ApplicationModal); setFixedSize(422, 202); QVBoxLayout *mainLayout = new QVBoxLayout(); mainLayout->setSpacing(0); mainLayout->setContentsMargins(0, 0, 0, 0); QHBoxLayout *titleLayout = new QHBoxLayout(); titleLayout->setSpacing(0); titleLayout->setContentsMargins(10, 0, 0, 0); m_titleBar = new QWidget(this); m_titleBar->setFixedHeight(50); m_titleBar->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); m_titleBar->setLayout(titleLayout); m_logoIcon = new DLabel(this); m_logoIcon->setFixedSize(QSize(32, 32)); m_logoIcon->setFocusPolicy(Qt::NoFocus); m_logoIcon->setAttribute(Qt::WA_TransparentForMouseEvents); m_logoIcon->setPixmap(QIcon::fromTheme("deepin-terminal").pixmap(QSize(32, 32))); m_closeButton = new DWindowCloseButton(this); m_closeButton->setFocusPolicy(Qt::NoFocus); m_closeButton->setIconSize(QSize(50, 50)); m_titleText = new DLabel(this); m_titleText->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred); m_titleText->setAlignment(Qt::AlignCenter); DFontSizeManager::instance()->bind(m_titleText, DFontSizeManager::T6); titleLayout->addWidget(m_logoIcon, 0, Qt::AlignLeft | Qt::AlignVCenter); titleLayout->addWidget(m_titleText); titleLayout->addWidget(m_closeButton, 0, Qt::AlignRight | Qt::AlignVCenter); //Dialog content m_contentLayout = new QVBoxLayout(); m_contentLayout->setSpacing(0); m_contentLayout->setContentsMargins(0, 0, 0, 0); m_content = new QWidget(this); m_content->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); m_content->setLayout(m_contentLayout); mainLayout->addWidget(m_titleBar); mainLayout->addWidget(m_content); setLayout(mainLayout); } void OperationConfirmDlg::initContentLayout() { m_mainLayout = new QVBoxLayout(); m_mainLayout->setSpacing(0); m_mainLayout->setContentsMargins(10, 0, 10, 10); QWidget *mainFrame = new QWidget(this); mainFrame->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); m_operateTypeName = new DLabel(this); //m_operateTypeName->setFixedHeight(20); m_operateTypeName->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); // 字色 DPalette titlepalette = m_operateTypeName->palette(); titlepalette.setBrush(QPalette::WindowText, titlepalette.color(DPalette::BrightText)); m_operateTypeName->setPalette(titlepalette); // 字号 DFontSizeManager::instance()->bind(m_operateTypeName, DFontSizeManager::T6, QFont::Medium); m_tipInfo = new DLabel(this); //m_tipInfo->setFixedHeight(20); m_tipInfo->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); // 字号 DFontSizeManager::instance()->bind(m_tipInfo, DFontSizeManager::T6, QFont::Normal); // 字色 DPalette palette = m_tipInfo->palette(); QColor color = DGuiApplicationHelper::adjustColor(palette.color(QPalette::WindowText), 0, 0, 0, 0, 0, 0, -30); palette.setColor(QPalette::WindowText, color); m_tipInfo->setPalette(palette); m_actionLayout = new QHBoxLayout(); m_actionLayout->setSpacing(0); m_actionLayout->setContentsMargins(0, 0, 0, 0); QFont btnFont; m_cancelBtn = new DPushButton(this); m_cancelBtn->setFixedHeight(38); m_cancelBtn->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Fixed); m_cancelBtn->setFont(btnFont); m_confirmBtn = new DWarningButton(this); m_confirmBtn->setFixedHeight(38); m_confirmBtn->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Fixed); m_confirmBtn->setFont(btnFont); //设置回车键默认响应的按钮 m_confirmBtn->setDefault(true); DVerticalLine *verticalLine = new DVerticalLine(this); verticalLine->setFixedSize(1, 28); m_actionLayout->addWidget(m_cancelBtn); m_actionLayout->addSpacing(8); m_actionLayout->addWidget(verticalLine); m_actionLayout->addSpacing(8); m_actionLayout->addWidget(m_confirmBtn); mainFrame->setLayout(m_mainLayout); addContent(mainFrame); } void OperationConfirmDlg::setDialogFrameSize(int width, int height) { setFixedSize(width, height); } void OperationConfirmDlg::initConnections() { connect(m_cancelBtn, &DPushButton::clicked, this, [ = ]() { qDebug() << "cancelBtnClicked"; m_confirmResultCode = QDialog::Rejected; reject(); close(); }); connect(m_confirmBtn, &DPushButton::clicked, this, [ = ]() { qDebug() << "confirmBtnClicked"; m_confirmResultCode = QDialog::Accepted; close(); }); connect(m_closeButton, &DIconButton::clicked, this, [ = ]() { qDebug() << "dialog close Btn Clicked"; m_confirmResultCode = QDialog::Rejected; close(); }); } void OperationConfirmDlg::closeEvent(QCloseEvent *event) { Q_UNUSED(event) done(-1); Q_EMIT closed(); } void OperationConfirmDlg::setTitle(const QString &title) { if (nullptr != m_titleText) { m_titleText->setText(title); } } QLayout *OperationConfirmDlg::getContentLayout() { return m_contentLayout; } void OperationConfirmDlg::addContent(QWidget *content) { Q_ASSERT(nullptr != getContentLayout()); getContentLayout()->addWidget(content); } void OperationConfirmDlg::setIconPixmap(const QPixmap &iconPixmap) { if (nullptr != m_logoIcon) { m_logoIcon->setPixmap(iconPixmap); } } void OperationConfirmDlg::setOperatTypeName(const QString &strName) { m_mainLayout->addWidget(m_operateTypeName, 0, Qt::AlignVCenter | Qt::AlignHCenter); m_mainLayout->addSpacing(8); m_operateTypeName->setText(strName); } void OperationConfirmDlg::setTipInfo(const QString &strInfo) { m_mainLayout->addWidget(m_tipInfo, 0, Qt::AlignVCenter | Qt::AlignHCenter); m_mainLayout->addStretch(); m_tipInfo->setText(strInfo); } void OperationConfirmDlg::setOKCancelBtnText(const QString &strConfirm, const QString &strCancel) { m_mainLayout->addLayout(m_actionLayout); m_confirmBtn->setText(strConfirm); m_cancelBtn->setText(strCancel); Utils::setSpaceInWord(m_confirmBtn); Utils::setSpaceInWord(m_cancelBtn); } QDialog::DialogCode OperationConfirmDlg::getConfirmResult() { return m_confirmResultCode; } deepin-terminal-5.2.11/src/views/operationconfirmdlg.h000066400000000000000000000031361370157770500230360ustar00rootroot00000000000000#ifndef OPERATIONCONFIRMDLG_H #define OPERATIONCONFIRMDLG_H #include #include #include #include #include #include #include #include #include #include DWIDGET_USE_NAMESPACE class OperationConfirmDlg : public DAbstractDialog { Q_OBJECT public: explicit OperationConfirmDlg(QWidget *parent = nullptr); void addContent(QWidget *content); void setIconPixmap(const QPixmap &iconPixmap); void setTitle(const QString &title); void setOperatTypeName(const QString &strName); void setTipInfo(const QString &strInfo); void setOKCancelBtnText(const QString &strConfirm, const QString &strCancel); QDialog::DialogCode getConfirmResult(); void setDialogFrameSize(int width, int height); protected: QLayout *getContentLayout(); void closeEvent(QCloseEvent *event) override; private: void initUI(); void initContentLayout(); void initConnections(); DLabel *m_logoIcon = nullptr; QWidget *m_titleBar = nullptr; DLabel *m_titleText = nullptr; QWidget *m_content = nullptr; QVBoxLayout *m_contentLayout = nullptr; QVBoxLayout *m_mainLayout = nullptr; QHBoxLayout *m_actionLayout = nullptr; DLabel *m_operateTypeName = nullptr; DLabel *m_tipInfo = nullptr; DPushButton *m_cancelBtn = nullptr; DWarningButton *m_confirmBtn = nullptr; DWindowCloseButton *m_closeButton = nullptr; QDialog::DialogCode m_confirmResultCode; signals: void closed(); }; #endif // OPERATIONCONFIRMDLG_H deepin-terminal-5.2.11/src/views/pagesearchbar.cpp000066400000000000000000000144371370157770500221210ustar00rootroot00000000000000/* -*- Mode: C++; indent-tabs-mode: nil; tab-width: 4 -*- * -*- coding: utf-8 -*- * * Copyright (C) 2011 ~ 2018 Deepin, Inc. * * Author: Wang Peili * Maintainer: Rekols * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #include "pagesearchbar.h" #include "utils.h" #include #include #include #include #include #include #include PageSearchBar::PageSearchBar(QWidget *parent) : DFloatingWidget(parent) { // Init hide(); setFixedSize(barWidth, barHight + 12); // 设置窗体透明度的,需求为100% QGraphicsOpacityEffect *opacityEffect = new QGraphicsOpacityEffect; setGraphicsEffect(opacityEffect); opacityEffect->setOpacity(opacity); initSearchEdit(); initFindNextButton(); initFindPrevButton(); // Init layout and widgets. QHBoxLayout *m_layout = new QHBoxLayout(); m_layout->setSpacing(widgetSpace); m_layout->setContentsMargins(layoutMargins, layoutMargins, layoutMargins, layoutMargins); m_layout->addWidget(m_searchEdit); m_layout->addWidget(m_findPrevButton); m_layout->addWidget(m_findNextButton); setLayout(m_layout); // Esc隐藏 QShortcut *shortcut = new QShortcut(QKeySequence::Cancel, this); connect(shortcut, &QShortcut::activated, this, [this]() { findCancel(); }); } bool PageSearchBar::isFocus() { return m_searchEdit->lineEdit()->hasFocus(); } void PageSearchBar::focus() { m_searchEdit->lineEdit()->setFocus(); m_searchEdit->lineEdit()->selectAll(); // 焦点一进入以后,就设置文字和图标,用于失去焦点后显示 recoveryHoldContent(); } QString PageSearchBar::searchKeytxt() { return m_searchEdit->text(); } void PageSearchBar::saveOldHoldContent() { m_originalPlaceHolder = m_searchEdit->placeHolder(); } //查找DSearchEdit中的DIconButton DIconButton *findIconBtn(DSearchEdit *searchEdit) { QWidget *iconWidget = searchEdit->findChild("iconWidget"); if (iconWidget) { DIconButton *iconBtn = iconWidget->findChild(); return iconBtn; } else { return searchEdit->findChild(); } } void PageSearchBar::clearHoldContent() { // 置空内容 m_searchEdit->setPlaceHolder(""); DIconButton *iconBtn = findIconBtn(m_searchEdit); if (iconBtn) { iconBtn->setIcon(QIcon("")); } } void PageSearchBar::recoveryHoldContent() { // 还原文本 m_searchEdit->setPlaceHolder(m_originalPlaceHolder); DIconButton *iconBtn = findIconBtn(m_searchEdit); if (iconBtn) { // 还原图标 iconBtn->setIcon(DStyle::SP_IndicatorSearch); } } void PageSearchBar::findCancel() { QWidget::hide(); emit closeSearchBar(); } void PageSearchBar::initFindPrevButton() { m_findPrevButton = new DIconButton(QStyle::SP_ArrowUp); m_findPrevButton->setFixedSize(widgetHight, widgetHight); m_findPrevButton->setFocusPolicy(Qt::NoFocus); connect(m_findPrevButton, &QAbstractButton::clicked, this, [this]() { if (!m_searchEdit->lineEdit()->text().isEmpty()) { emit findPrev(); } }); QAction *action = new QAction(m_findPrevButton); QList lstShortcut; lstShortcut << QKeySequence("Shift+Enter") << QKeySequence("Shift+Return"); action->setShortcuts(lstShortcut); m_findPrevButton->addAction(action); connect(action, &QAction::triggered, this, [this]() { m_findPrevButton->animateClick(80); }); } void PageSearchBar::initFindNextButton() { m_findNextButton = new DIconButton(QStyle::SP_ArrowDown); m_findNextButton->setFixedSize(widgetHight, widgetHight); m_findNextButton->setFocusPolicy(Qt::NoFocus); connect(m_findNextButton, &QAbstractButton::clicked, this, [this]() { if (!m_searchEdit->lineEdit()->text().isEmpty()) { emit findNext(); } }); // 界面上输入回车就相当于直接点击下一个:Key_Enter OR Key_Return // 控件本身不支持设置多个快捷键 QAction *action = new QAction(m_findNextButton); QList lstShortcut; lstShortcut << QKeySequence(Qt::Key_Enter) << QKeySequence(Qt::Key_Return); action->setShortcuts(lstShortcut); m_findNextButton->addAction(action); connect(action, &QAction::triggered, this, [this]() { m_findNextButton->animateClick(80); }); } void PageSearchBar::initSearchEdit() { m_searchEdit = new DSearchEdit(this); m_searchEdit->lineEdit()->setMinimumHeight(widgetHight); // 保留原文字,图标 saveOldHoldContent(); // 置空 clearHoldContent(); // 把DTK好容易改造的功能,还原了........ // 把那个"X"控件功能还原成仅为清空文本 QList list = m_searchEdit->lineEdit()->findChildren(); QAction *clearAction = m_searchEdit->lineEdit()->findChild(QLatin1String("_q_qlineeditclearaction")); for (int i = 0; i < list.count(); i++) { if (list.at(i)->defaultAction() == clearAction) { QToolButton *clearBtn = list.at(i); //屏蔽lineedit清除按钮的槽函数,_q_clearFocus()获得有效的判断条件 clearBtn->disconnect(SIGNAL(clicked())); connect(clearBtn, &QToolButton::clicked, this, [this]() { m_searchEdit->lineEdit()->setText(""); }); } } // 需求不让自动查找,这个接口预留 connect(m_searchEdit, &DSearchEdit::textChanged, this, [this]() { emit keywordChanged(m_searchEdit->lineEdit()->text()); }); } void PageSearchBar::setNoMatchAlert(bool isAlert) { m_searchEdit->setAlert(isAlert); } deepin-terminal-5.2.11/src/views/pagesearchbar.h000066400000000000000000000041031370157770500215530ustar00rootroot00000000000000/* -*- Mode: C++; indent-tabs-mode: nil; tab-width: 4 -*- * -*- coding: utf-8 -*- * * Copyright (C) 2011 ~ 2018 Deepin, Inc. * * Author: Wang Yong * Maintainer: Rekols * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #ifndef PAGESEARCHBAR_H #define PAGESEARCHBAR_H #include #include #include #include #include #include #include DWIDGET_USE_NAMESPACE class PageSearchBar : public DFloatingWidget { Q_OBJECT public: PageSearchBar(QWidget *parent = nullptr); bool isFocus(); void focus(); void setNoMatchAlert(bool isAlert); QString searchKeytxt(); void saveOldHoldContent(); void clearHoldContent(); void recoveryHoldContent(); signals: void findNext(); void findPrev(); void keywordChanged(QString keyword); void closeSearchBar(); public slots: void findCancel(); private: void initFindPrevButton(); void initFindNextButton(); void initSearchEdit(); DIconButton *m_findNextButton = nullptr; DIconButton *m_findPrevButton = nullptr; DSearchEdit *m_searchEdit = nullptr; const int barHight = 50; const int barWidth = 382; const int layoutMargins = 7; const int widgetHight = 36; const int widgetSpace = 10; const int iconHight = 6; const int iconWidth = 12; const qreal opacity = 0.9; QString m_originalPlaceHolder; //原文字 }; #endif deepin-terminal-5.2.11/src/views/rightpanel.cpp000066400000000000000000000057331370157770500214660ustar00rootroot00000000000000#include "rightpanel.h" #include #include DWIDGET_USE_NAMESPACE RightPanel::RightPanel(QWidget *parent) : QWidget(parent) { // hide by default. QWidget::hide(); setFixedWidth(240 + 2); // Init theme panel. // 插件不支持resize,下面代码不需要了 // DAnchorsBase::setAnchor(this, Qt::AnchorTop, parent, Qt::AnchorTop); // DAnchorsBase::setAnchor(this, Qt::AnchorBottom, parent, Qt::AnchorBottom); // DAnchorsBase::setAnchor(this, Qt::AnchorRight, parent, Qt::AnchorRight); } void RightPanel::show() { QWidget::show(); QWidget::raise(); QRect rect = geometry(); QRect windowRect = window()->geometry(); QPropertyAnimation *animation = new QPropertyAnimation(this, "geometry"); animation->setDuration(250); animation->setEasingCurve(QEasingCurve::OutQuad); //animation->setStartValue(QRect(windowRect.width(), rect.y(), rect.width(), windowRect.height() - 50)); //animation->setEndValue(QRect(windowRect.width() - rect.width(), rect.y(), rect.width(), windowRect.height() - 50)); if (window()->isFullScreen()) { animation->setStartValue(QRect(windowRect.width(), rect.y(), rect.width(), windowRect.height())); animation->setEndValue(QRect(windowRect.width() - rect.width(), rect.y(), rect.width(), windowRect.height())); } else { animation->setStartValue(QRect(windowRect.width(), rect.y(), rect.width(), windowRect.height() - 50)); animation->setEndValue(QRect(windowRect.width() - rect.width(), rect.y(), rect.width(), windowRect.height() - 50)); } animation->start(QAbstractAnimation::DeleteWhenStopped); // connect(animation, &QPropertyAnimation::valueChanged, this, [=] { m_themeView->adjustScrollbarMargins(); }); } void RightPanel::hideAnim() { // 隐藏状态不处理 if (!isVisible()) { return; } QRect rect = geometry(); QRect windowRect = window()->geometry(); QPropertyAnimation *animation = new QPropertyAnimation(this, "geometry"); animation->setDuration(250); animation->setEasingCurve(QEasingCurve::OutQuad); //animation->setStartValue( // QRect(windowRect.width() - rect.width(), rect.y(), rect.width(), windowRect.height() - 50)); //animation->setEndValue(QRect(windowRect.width(), rect.y(), rect.width(), windowRect.height() - 50)); if (window()->isFullScreen()) { animation->setStartValue(QRect(windowRect.width() - rect.width(), rect.y(), rect.width(), windowRect.height())); animation->setEndValue(QRect(windowRect.width(), rect.y(), rect.width(), windowRect.height())); } else { animation->setStartValue(QRect(windowRect.width() - rect.width(), rect.y(), rect.width(), windowRect.height() - 50)); animation->setEndValue(QRect(windowRect.width(), rect.y(), rect.width(), windowRect.height() - 50)); } animation->start(QAbstractAnimation::DeleteWhenStopped); connect(animation, &QPropertyAnimation::finished, this, &QWidget::hide); } deepin-terminal-5.2.11/src/views/rightpanel.h000066400000000000000000000003761370157770500211310ustar00rootroot00000000000000#ifndef RIGHTPANEL_H #define RIGHTPANEL_H #include class RightPanel : public QWidget { Q_OBJECT public: explicit RightPanel(QWidget *parent = nullptr); public slots: void show(); void hideAnim(); }; #endif // RIGHTPANEL_H deepin-terminal-5.2.11/src/views/tabbar.cpp000066400000000000000000000334151370157770500205620ustar00rootroot00000000000000#include "tabbar.h" #include "private/qtabbar_p.h" #include #include #include #include #include #include #include #include #include //TermTabStyle start TermTabStyle::TermTabStyle() : m_tabCount(0) { } TermTabStyle::~TermTabStyle() { } void TermTabStyle::setTabTextColor(const QColor &color) { m_tabTextColor = color; } void TermTabStyle::setTabStatusMap(const QMap &tabStatusMap) { m_tabStatusMap = tabStatusMap; } QSize TermTabStyle::sizeFromContents(ContentsType type, const QStyleOption *option, const QSize &size, const QWidget *widget) const { return QProxyStyle::sizeFromContents(type, option, size, widget); } int TermTabStyle::pixelMetric(QStyle::PixelMetric metric, const QStyleOption *option, const QWidget *widget) const { return QProxyStyle::pixelMetric(metric, option, widget); } void TermTabStyle::drawControl(ControlElement element, const QStyleOption *option, QPainter *painter, const QWidget *widget) const { if (element == CE_TabBarTabLabel) { if (const QStyleOptionTab *tab = qstyleoption_cast(option)) { DGuiApplicationHelper *appHelper = DGuiApplicationHelper::instance(); QTextOption textOption; textOption.setAlignment(Qt::AlignCenter); QFont textFont = QApplication::font(); int fontSize = DFontSizeManager::instance()->fontPixelSize(DFontSizeManager::T6); textFont.setPixelSize(fontSize); textFont.setWeight(QFont::Medium); painter->setFont(textFont); QString content = tab->text; QRect tabRect = tab->rect; if (m_tabStatusMap.value(tab->row) == 2) { if (tab->state & QStyle::State_Selected) { DPalette pa = appHelper->standardPalette(appHelper->themeType()); painter->setPen(pa.color(DPalette::HighlightedText)); } else if (tab->state & QStyle::State_MouseOver) { painter->setPen(m_tabTextColor); } else { painter->setPen(m_tabTextColor); } } else { DPalette pa = appHelper->standardPalette(appHelper->themeType()); if (tab->state & QStyle::State_Selected) { painter->setPen(pa.color(DPalette::HighlightedText)); } else if (tab->state & QStyle::State_MouseOver) { painter->setPen(pa.color(DPalette::TextTitle)); } else { painter->setPen(pa.color(DPalette::TextTitle)); } } QFontMetrics fontMetric(textFont); QString elidedText = fontMetric.elidedText(content, Qt::ElideRight, tabRect.width() - 30, Qt::TextShowMnemonic); painter->drawText(tabRect, elidedText, textOption); } else { QProxyStyle::drawControl(element, option, painter, widget); } } else { QProxyStyle::drawControl(element, option, painter, widget); } } void TermTabStyle::drawPrimitive(QStyle::PrimitiveElement element, const QStyleOption *option, QPainter *painter, const QWidget *widget) const { QProxyStyle::drawPrimitive(element, option, painter, widget); } //TermTabStyle end void QTabBar::initStyleOption(QStyleOptionTab *option, int tabIndex) const { Q_D(const QTabBar); d->initBasicStyleOption(option, tabIndex); QRect textRect = style()->subElementRect(QStyle::SE_TabBarTabText, option, this); option->text = fontMetrics().elidedText(option->text, d->elideMode, textRect.width(), Qt::TextShowMnemonic); // 保存tab的索引值到row字段 option->row = tabIndex; } TabBar::TabBar(QWidget *parent) : DTabBar(parent), m_rightClickTab(-1) { setStyle(new TermTabStyle()); m_sessionIdTabIndexMap.clear(); m_sessionIdTabIdMap.clear(); m_tabStatusMap.clear(); installEventFilter(this); //启用关闭tab动画效果 setEnableCloseTabAnimation(true); setTabsClosable(true); setVisibleAddButton(true); setElideMode(Qt::ElideRight); setFocusPolicy(Qt::NoFocus); setTabHeight(36); setTabItemMinWidth(110); setTabItemMaxWidth(450); DIconButton *addButton = findChild("AddButton"); if (nullptr != addButton) { addButton->setFocusPolicy(Qt::NoFocus); } connect(this, &DTabBar::tabBarClicked, this, &TabBar::tabBarClicked); } TabBar::~TabBar() { if(m_rightMenu != nullptr){ m_rightMenu->deleteLater(); } } void TabBar::setTabHeight(int tabHeight) { m_tabHeight = tabHeight; setFixedHeight(tabHeight); } void TabBar::setTabItemMinWidth(int tabItemMinWidth) { m_tabItemMinWidth = tabItemMinWidth; } void TabBar::setTabItemMaxWidth(int tabItemMaxWidth) { m_tabItemMaxWidth = tabItemMaxWidth; } const QString TabBar::identifier(int index) const { return tabData(index).toString(); } int TabBar::addTab(const QString &tabIdentifier, const QString &tabName) { int index = DTabBar::addTab(tabName); setTabData(index, QVariant::fromValue(tabIdentifier)); return index; } void TabBar::saveSessionIdWithTabIndex(int sessionId, int index) { m_sessionIdTabIndexMap.insert(sessionId, index); } void TabBar::saveSessionIdWithTabId(int sessionId, const QString &tabIdentifier) { m_sessionIdTabIdMap.insert(sessionId, tabIdentifier); } QMap TabBar::getSessionIdTabIndexMap() { return m_sessionIdTabIndexMap; } int TabBar::queryIndexBySessionId(int sessionId) { if (m_sessionIdTabIndexMap.isEmpty()) { return -1; } QString tabIdentifier = m_sessionIdTabIdMap.value(sessionId); for (int i = 0; i < count(); i++) { if (identifier(i) == tabIdentifier) { return i; } } return -1; } int TabBar::getIndexByIdentifier(QString id) { for (int i = 0; i < count(); i++) { if (identifier(i) == id) { return i; } } return -1; } /*! Removes the tab at position \a index. \sa SelectionBehavior */ void QTabBar::removeTab(int index) { Q_D(QTabBar); if (d->validIndex(index)) { if (d->dragInProgress) d->moveTabFinished(d->pressedIndex); #ifndef QT_NO_SHORTCUT releaseShortcut(d->tabList.at(index).shortcutId); #endif if (d->tabList[index].leftWidget) { d->tabList[index].leftWidget->hide(); d->tabList[index].leftWidget->deleteLater(); d->tabList[index].leftWidget = nullptr; } if (d->tabList[index].rightWidget) { d->tabList[index].rightWidget->hide(); d->tabList[index].rightWidget->deleteLater(); d->tabList[index].rightWidget = nullptr; } int newIndex = d->tabList[index].lastTab; d->tabList.removeAt(index); for (int i = 0; i < d->tabList.count(); ++i) { if (d->tabList[i].lastTab == index) d->tabList[i].lastTab = -1; if (d->tabList[i].lastTab > index) --d->tabList[i].lastTab; } if (index == d->currentIndex) { // The current tab is going away, in order to make sure // we emit that "current has changed", we need to reset this // around. d->currentIndex = -1; if (d->tabList.size() > 0) { switch (d->selectionBehaviorOnRemove) { case SelectPreviousTab: if (newIndex > index) newIndex--; if (d->validIndex(newIndex)) break; Q_FALLTHROUGH(); case SelectRightTab: newIndex = index; if (newIndex >= d->tabList.size()) newIndex = d->tabList.size() - 1; break; case SelectLeftTab: newIndex = index - 1; if (newIndex < 0) newIndex = 0; break; } if (d->validIndex(newIndex)) { // don't loose newIndex's old through setCurrentIndex int bump = d->tabList[newIndex].lastTab; setCurrentIndex(newIndex); d->tabList[newIndex].lastTab = bump; } } else { emit currentChanged(-1); } } else if (index < d->currentIndex) { setCurrentIndex(d->currentIndex - 1); } d->refresh(); d->autoHideTabs(); if (!d->hoverRect.isEmpty()) { for (int i = 0; i < d->tabList.count(); ++i) { const QRect area = tabRect(i); if (area.contains(mapFromGlobal(QCursor::pos()))) { d->hoverIndex = i; d->hoverRect = area; break; } } update(d->hoverRect); } tabRemoved(index); } TabBar *tabBar = qobject_cast(this->parent()); if (tabBar && tabBar->isEnableCloseTabAnimation()) { //tab关闭动画 if (d->rightB->isVisible()) { for (int i = 0; i < index; i++) { QTabBarPrivate::Tab *tab = &d->tabList[i]; if (!tab->animation) tab->animation = reinterpret_cast(new QTabBarPrivate::Tab::TabBarAnimation(tab, d)); tab->animation->setStartValue(-100); tab->animation->setEndValue(0); tab->animation->setEasingCurve(QEasingCurve::OutCubic); tab->animation->setDuration(300); tab->animation->start(); } } } } void TabBar::removeTab(const QString &tabIdentifier) { for (int i = 0; i < count(); i++) { if (tabData(i).toString() == tabIdentifier) { DTabBar::removeTab(i); break; } } } bool TabBar::setTabText(const QString &tabIdentifier, const QString &text) { bool termFound = false; for (int i = 0; i < count(); i++) { if (tabData(i).toString() == tabIdentifier) { termFound = true; DTabBar::setTabText(i, text); break; } } return termFound; } bool TabBar::eventFilter(QObject *watched, QEvent *event) { Q_UNUSED(watched) if (event->type() == QEvent::MouseButtonPress) { QMouseEvent *mouseEvent = static_cast(event); if (mouseEvent->button() == Qt::RightButton) { QPoint position = mouseEvent->pos(); m_rightClickTab = -1; for (int i = 0; i < this->count(); i++) { if (tabRect(i).contains(position)) { m_rightClickTab = i; break; } } qDebug() << "currIndex" << m_rightClickTab << endl; // popup right menu on tab. if (m_rightClickTab >= 0) { if(m_rightMenu == nullptr){ m_rightMenu = new DMenu(this); } else{ // clear时,对于绑在menu下面的action会自动释放,无需单独处理action释放 m_rightMenu->clear(); } m_closeTabAction = new QAction(tr("Close workspace"), m_rightMenu); m_closeOtherTabAction = new QAction(tr("Close other workspaces"), m_rightMenu); connect(m_closeTabAction, &QAction::triggered, this, [ = ] { Q_EMIT tabCloseRequested(m_rightClickTab); }); connect(m_closeOtherTabAction, &QAction::triggered, this, [ = ] { emit menuCloseOtherTab(identifier(m_rightClickTab)); }); m_rightMenu->addAction(m_closeTabAction); m_rightMenu->addAction(m_closeOtherTabAction); m_closeOtherTabAction->setEnabled(true); if (this->count() < 2) { m_closeOtherTabAction->setEnabled(false); } m_rightMenu->exec(mapToGlobal(position)); return true; } } } return false; } QSize TabBar::minimumTabSizeHint(int index) const { Q_UNUSED(index) return QSize(m_tabItemMinWidth, m_tabHeight); } QSize TabBar::maximumTabSizeHint(int index) const { Q_UNUSED(index) return QSize(m_tabItemMaxWidth, m_tabHeight); } void TabBar::setNeedChangeTextColor(int index, const QColor &color) { m_tabStatusMap.insert(index, 1); m_tabChangedTextColor = color; } void TabBar::removeNeedChangeTextColor(int index) { m_tabStatusMap.remove(index); TermTabStyle *style = qobject_cast(this->style()); style->setTabStatusMap(m_tabStatusMap); style->polish(this); } void TabBar::setChangeTextColor(int index) { m_tabStatusMap.insert(index, 2); QColor color = m_tabChangedTextColor; TermTabStyle *style = qobject_cast(this->style()); style->setTabTextColor(color); style->setTabStatusMap(m_tabStatusMap); style->polish(this); } bool TabBar::isNeedChangeTextColor(int index) { return (m_tabStatusMap.value(index) == 1); } void TabBar::setClearTabColor(int index) { m_tabStatusMap.insert(index, 0); TermTabStyle *style = qobject_cast(this->style()); style->setTabStatusMap(m_tabStatusMap); style->polish(this); } void TabBar::setTabStatusMap(const QMap &tabStatusMap) { m_tabStatusMap = tabStatusMap; } void TabBar::setEnableCloseTabAnimation(bool bEnableCloseTabAnimation) { m_bEnableCloseTabAnimation = bEnableCloseTabAnimation; } bool TabBar::isEnableCloseTabAnimation() { return m_bEnableCloseTabAnimation; } deepin-terminal-5.2.11/src/views/tabbar.h000066400000000000000000000056651370157770500202350ustar00rootroot00000000000000#ifndef TABBAR_H #define TABBAR_H #include #include #include DWIDGET_USE_NAMESPACE class TermTabStyle : public QProxyStyle { Q_OBJECT public: TermTabStyle(); virtual ~TermTabStyle(); void setTabTextColor(const QColor &color); void setTabStatusMap(const QMap &tabStatusMap); QSize sizeFromContents(ContentsType type, const QStyleOption *option, const QSize &size, const QWidget *widget) const; int pixelMetric(QStyle::PixelMetric metric, const QStyleOption* option, const QWidget* widget) const; void drawControl(ControlElement element, const QStyleOption *option, QPainter *painter, const QWidget *widget) const; void drawPrimitive(PrimitiveElement element, const QStyleOption *option, QPainter *painter, const QWidget *widget = Q_NULLPTR) const; private: int m_tabCount; QColor m_tabTextColor; QMap m_tabStatusMap; }; class TabBar : public DTabBar { Q_OBJECT public: explicit TabBar(QWidget *parent = nullptr); ~TabBar(); const QString identifier(int index) const; void setTabHeight(int tabHeight); void setTabItemMinWidth(int tabItemMinWidth); void setTabItemMaxWidth(int tabItemMaxWidth); int addTab(const QString &tabIdentifier, const QString &tabName); void removeTab(const QString &tabIdentifier); bool setTabText(const QString &tabIdentifier, const QString &text); void saveSessionIdWithTabIndex(int sessionId, int index); void saveSessionIdWithTabId(int sessionId, const QString &tabIdentifier); QMap getSessionIdTabIndexMap(); int queryIndexBySessionId(int sessionId); int getIndexByIdentifier(QString id); //set tab label's title color void setChangeTextColor(int index); void setNeedChangeTextColor(int index, const QColor &color); void removeNeedChangeTextColor(int index); bool isNeedChangeTextColor(int index); void setClearTabColor(int index); void setTabStatusMap(const QMap &tabStatusMap); //设置是否启用关闭tab动画效果 void setEnableCloseTabAnimation(bool bEnableCloseTabAnimation); bool isEnableCloseTabAnimation(); protected: bool eventFilter(QObject *watched, QEvent *event); QSize minimumTabSizeHint(int index) const; QSize maximumTabSizeHint(int index) const; signals: void tabBarClicked(int index); void menuCloseTab(QString Identifier); void menuCloseOtherTab(QString Identifier); private: QAction *m_closeOtherTabAction = nullptr; QAction *m_closeTabAction = nullptr; DMenu *m_rightMenu = nullptr; int m_rightClickTab; int m_tabHeight; int m_tabItemMinWidth; int m_tabItemMaxWidth; QMap m_sessionIdTabIndexMap; // key--sessionId, value--tabIndex QMap m_sessionIdTabIdMap; // key--sessionId, value--tabIdentifier QMap m_tabStatusMap; QColor m_tabChangedTextColor; bool m_bEnableCloseTabAnimation; }; #endif // TABBAR_H deepin-terminal-5.2.11/src/views/termbasedialog.cpp000066400000000000000000000016671370157770500223150ustar00rootroot00000000000000#include "termbasedialog.h" #include #include static void palrtteTransparency(QWidget *widget, qint8 alphaFloat) { QPalette palette = widget->palette(); QColor color = DGuiApplicationHelper::adjustColor(palette.color(QPalette::BrightText), 0, 0, 0, 0, 0, 0, alphaFloat); palette.setColor(QPalette::WindowText, color); widget->setPalette(palette); } //fix bug 23481 主菜单切换主题,弹框字体颜色没有随主题及时变换 void QWidget::paintEvent(QPaintEvent *e) { Q_UNUSED(e) if (strcmp(this->metaObject()->className(), "Dtk::Widget::DDialog") != 0) { return; } QLabel *titleLabel = this->findChild("TitleLabel"); QLabel *messageLabel = this->findChild("MessageLabel"); if (titleLabel) { palrtteTransparency(titleLabel, -10); } if (messageLabel) { palrtteTransparency(messageLabel, -30); } } deepin-terminal-5.2.11/src/views/termbasedialog.h000066400000000000000000000001161370157770500217460ustar00rootroot00000000000000#ifndef TERMBASEDIALOG_H #define TERMBASEDIALOG_H #endif // TERMBASEDIALOG_H deepin-terminal-5.2.11/src/views/termcommandlinkbutton.cpp000066400000000000000000000006271370157770500237460ustar00rootroot00000000000000#include "termcommandlinkbutton.h" #include TermCommandLinkButton::TermCommandLinkButton(QWidget *parent) : DPushButton(parent) { DPalette palette = DApplicationHelper::instance()->palette(this); palette.setColor(DPalette::ButtonText, palette.color(DPalette::TextWarning)); this->setPalette(palette); this->setFlat(true); this->setFocusPolicy(Qt::NoFocus); } deepin-terminal-5.2.11/src/views/termcommandlinkbutton.h000066400000000000000000000004351370157770500234100ustar00rootroot00000000000000#ifndef TERMCOMMANDLINKBUTTON_H #define TERMCOMMANDLINKBUTTON_H #include DWIDGET_USE_NAMESPACE class TermCommandLinkButton : public DPushButton { Q_OBJECT public: explicit TermCommandLinkButton(QWidget *parent = nullptr); }; #endif // TERMCOMMANDLINKBUTTON_H deepin-terminal-5.2.11/src/views/terminputdialog.cpp000066400000000000000000000210641370157770500225330ustar00rootroot00000000000000#include "terminputdialog.h" #include "utils.h" #include "termwidget.h" #include #include #include #include #include DWIDGET_USE_NAMESPACE TermInputDialog::TermInputDialog(QWidget *parent) : DAbstractDialog(parent) { initUI(); initConnections(); } void TermInputDialog::initUI() { QVBoxLayout *mainLayout = new QVBoxLayout(); mainLayout->setSpacing(0); mainLayout->setContentsMargins(0, 0, 0, 10); QHBoxLayout *titleLayout = new QHBoxLayout(); titleLayout->setSpacing(0); titleLayout->setContentsMargins(0, 0, 0, 0); m_titleBar = new QWidget(this); m_titleBar->setFixedHeight(50); m_titleBar->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); m_titleBar->setLayout(titleLayout); m_logoIcon = new DIconButton(this); m_logoIcon->setIconSize(QSize(32, 32)); m_logoIcon->setWindowFlags(Qt::WindowTransparentForInput); m_logoIcon->setFocusPolicy(Qt::NoFocus); m_logoIcon->setFlat(true); // 默认无图标,所以隐藏 m_logoIcon->hide(); m_closeButton = new DWindowCloseButton(this); m_closeButton->setFocusPolicy(Qt::NoFocus); m_closeButton->setIconSize(QSize(50, 50)); m_titleText = new DLabel(this); m_titleText->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred); m_titleText->setAlignment(Qt::AlignCenter); DFontSizeManager::instance()->bind(m_titleText, DFontSizeManager::T5, QFont::DemiBold); // 字色 DPalette palette = m_titleText->palette(); palette.setColor(QPalette::WindowText, palette.color(DPalette::TextTitle)); m_titleText->setPalette(palette); titleLayout->addSpacing(10); titleLayout->addWidget(m_logoIcon, 0, Qt::AlignLeading | Qt::AlignVCenter); titleLayout->addSpacing(50 - 32); titleLayout->addWidget(m_titleText); titleLayout->addWidget(m_closeButton, 0, Qt::AlignRight | Qt::AlignTop); //Dialog content m_contentLayout = new QVBoxLayout(); m_contentLayout->setSpacing(0); m_contentLayout->setContentsMargins(0, 0, 0, 0); m_content = new QWidget(this); m_content->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); m_content->setLayout(m_contentLayout); mainLayout->addWidget(m_titleBar, 0, Qt::AlignTop); mainLayout->addWidget(m_content); setLayout(mainLayout); m_mainLayout = mainLayout; } void TermInputDialog::addCancelConfirmButtons(int width, int height, int topOffset, int outerSpace, int innerSpace) { QHBoxLayout *buttonsLayout = new QHBoxLayout(); buttonsLayout->setSpacing(innerSpace); buttonsLayout->setContentsMargins(outerSpace, 0, outerSpace, 0); QFont btnFont; m_cancelBtn = new DPushButton(this); m_cancelBtn->setFixedWidth(width); m_cancelBtn->setFixedHeight(height); m_cancelBtn->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Fixed); m_cancelBtn->setFont(btnFont); m_confirmBtn = new DSuggestButton(this); m_confirmBtn->setFixedWidth(width); m_confirmBtn->setFixedHeight(height); m_confirmBtn->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Fixed); m_confirmBtn->setFont(btnFont); //设置回车键默认响应的按钮 m_confirmBtn->setDefault(true); DVerticalLine *verticalLine = new DVerticalLine(this); verticalLine->setFixedSize(1, 28); buttonsLayout->addWidget(m_cancelBtn); buttonsLayout->addWidget(verticalLine); buttonsLayout->addWidget(m_confirmBtn); /************************ Add by m000743 sunchengxi 2020-04-15:默认enter回车按下,走确认校验流程 Begin************************/ m_confirmBtn->setDefault(true); /************************ Add by m000743 sunchengxi 2020-04-15:默认enter回车按下,走确认校验流程 End ************************/ // connect(m_cancelBtn, &DPushButton::clicked, this, [ = ]() { // qDebug() << "cancelBtnClicked"; // m_confirmResultCode = QDialog::Rejected; // reject(); // close(); // }); // connect(m_confirmBtn, &DPushButton::clicked, this, [ = ]() { // qDebug() << "confirmBtnClicked"; // m_confirmResultCode = QDialog::Accepted; // emit confirmBtnClicked(); // }); if (topOffset > 0) { m_mainLayout->addSpacing(topOffset); } m_mainLayout->addLayout(buttonsLayout); } void TermInputDialog::showDialog(QString oldTitle, QWidget *parentWidget) { /***mod begin by ut001121 zhangmeng 20200428 修复BUG#22995 标签截断显示的问题***/ m_lineEdit = new DLineEdit(this); /* delete * lineEdit->setFixedSize(360, 36);*/ /* add */ m_lineEdit->setFixedWidth(360); /***mod end by ut001121 zhangmeng***/ m_lineEdit->setText(oldTitle); m_lineEdit->setClearButtonEnabled(false); m_lineEdit->setFocusPolicy(Qt::ClickFocus); this->setFocusProxy(m_lineEdit->lineEdit()); /******** Modify by ut000610 daizhengwen 2020-05-21: 初始化重命名lineEdit全选****************/ connect(m_lineEdit, &DLineEdit::focusChanged, m_lineEdit->lineEdit(), [ = ](bool onFocus) { // 初始化重命名lineEdit全选 if (onFocus) { m_lineEdit->lineEdit()->selectAll(); } }); /********************* Modify by ut000610 daizhengwen End ************************/ DLabel *label = new DLabel(tr("Rename title")); /***mod begin by ut001121 zhangmeng 20200428 修复BUG#22995 标签截断显示的问题***/ /* delete * label->setFixedSize(360, 20);*/ /* add */ label->setFixedWidth(360); /***mod end by ut001121 zhangmeng***/ label->setAlignment(Qt::AlignHCenter); DPalette palette = label->palette(); palette.setBrush(DPalette::WindowText, palette.color(DPalette::BrightText)); label->setPalette(palette); // 字号 DFontSizeManager::instance()->bind(label, DFontSizeManager::T6, QFont::Medium); QVBoxLayout *contentLayout = new QVBoxLayout; contentLayout->setContentsMargins(10, 0, 10, 0); contentLayout->addWidget(label, Qt::AlignHCenter); contentLayout->addSpacing(8); contentLayout->addWidget(m_lineEdit, Qt::AlignHCenter); QWidget *contentWidget = new QWidget; contentWidget->setLayout(contentLayout); this->addContent(contentWidget); this->addCancelConfirmButtons(170, 36, 15, 10, 9); this->setCancelBtnText(tr("Cancel")); this->setConfirmBtnText(tr("Confirm")); connect(m_cancelBtn, &DPushButton::clicked, this, [ = ]() { qDebug() << "cancelBtnClicked"; m_confirmResultCode = QDialog::Rejected; reject(); close(); }); connect(m_confirmBtn, &DPushButton::clicked, this, [ = ]() { qDebug() << "confirmBtnClicked"; m_confirmResultCode = QDialog::Accepted; emit confirmBtnClicked(); TermWidgetPage *page = qobject_cast(parentWidget); //emit page->onTermRequestRenameTab(m_lineEdit->text()); page->onTermRequestRenameTab(m_lineEdit->text()); close(); }); // 设置为半模态 this->setWindowModality(Qt::WindowModal); // 显示 this->show(); } void TermInputDialog::showDialog(QString oldTitle) { // lineEdit不为空,show if (nullptr != m_lineEdit) { m_lineEdit->setText(oldTitle); this->show(); } } QVBoxLayout *TermInputDialog::getMainLayout() { return m_mainLayout; } void TermInputDialog::initConnections() { connect(m_closeButton, &DWindowCloseButton::clicked, this, [this]() { this->close(); }); } QDialog::DialogCode TermInputDialog::getConfirmResult() { return m_confirmResultCode; } void TermInputDialog::setLogoVisable(bool visible) { if (nullptr != m_logoIcon) { m_logoIcon->setVisible(visible); } } void TermInputDialog::setTitle(const QString &title) { if (nullptr != m_titleText) { m_titleText->setText(title); } } QLayout *TermInputDialog::getContentLayout() { return m_contentLayout; } void TermInputDialog::setCancelBtnText(const QString &strCancel) { m_cancelBtn->setText(strCancel); Utils::setSpaceInWord(m_cancelBtn); } void TermInputDialog::setConfirmBtnText(const QString &strConfirm) { m_confirmBtn->setText(strConfirm); Utils::setSpaceInWord(m_confirmBtn); } void TermInputDialog::addContent(QWidget *content) { Q_ASSERT(nullptr != getContentLayout()); getContentLayout()->addWidget(content); } void TermInputDialog::setIcon(const QIcon &icon) { if (nullptr != m_logoIcon) { m_logoIcon->setIcon(icon); m_logoIcon->setVisible(true); } } void TermInputDialog::closeEvent(QCloseEvent *event) { Q_UNUSED(event) done(-1); Q_EMIT closed(); } deepin-terminal-5.2.11/src/views/terminputdialog.h000066400000000000000000000032121370157770500221730ustar00rootroot00000000000000#ifndef TERMINPUTDIALOG_H #define TERMINPUTDIALOG_H #include #include #include #include #include #include #include DWIDGET_USE_NAMESPACE class TermInputDialog : public DAbstractDialog { Q_OBJECT public: explicit TermInputDialog(QWidget *parent = nullptr); void setIcon(const QIcon &icon); void setTitleHeight(int height); void addContent(QWidget *content); void addCancelConfirmButtons(int width, int height, int topOffset, int outerSpace, int innerSpace); void setCancelBtnText(const QString &strCancel); void setConfirmBtnText(const QString &strConfirm); void showDialog(QString oldTitle, QWidget *parentWidget); void showDialog(QString oldTitle); QDialog::DialogCode getConfirmResult(); QVBoxLayout *getMainLayout(); protected: void initUI(); void initConnections(); void setLogoVisable(bool visible = true); void setTitle(const QString &title); QLayout *getContentLayout(); //Overrides void closeEvent(QCloseEvent *event) override; signals: void closed(); void confirmBtnClicked(); private: QWidget *m_titleBar = nullptr; DIconButton *m_logoIcon = nullptr; DLabel *m_titleText = nullptr; DWindowCloseButton *m_closeButton = nullptr; DLineEdit *m_lineEdit = nullptr; QWidget *m_content = nullptr; QVBoxLayout *m_contentLayout = nullptr; QVBoxLayout *m_mainLayout = nullptr; DPushButton *m_cancelBtn = nullptr; DSuggestButton *m_confirmBtn = nullptr; QDialog::DialogCode m_confirmResultCode; }; #endif // TERMINPUTDIALOG_H deepin-terminal-5.2.11/src/views/termwidget.cpp000066400000000000000000000660471370157770500215110ustar00rootroot00000000000000#include "termwidget.h" #include "define.h" #include "settings.h" #include "termproperties.h" #include "mainwindow.h" #include "shortcutmanager.h" #include "operationconfirmdlg.h" #include "utils.h" #include "service.h" #include "windowsmanager.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include DWIDGET_USE_NAMESPACE using namespace Konsole; TermWidget::TermWidget(TermProperties properties, QWidget *parent) : QTermWidget(0, parent), m_properties(properties) { // 窗口数量加1 WindowsManager::instance()->terminalCountIncrease(); //qDebug() << " TermWidgetparent " << parentWidget(); m_Page = static_cast(parentWidget()); setContextMenuPolicy(Qt::CustomContextMenu); setHistorySize(5000); // set shell program QString shell{ getenv("SHELL") }; setShellProgram(shell.isEmpty() ? "/bin/bash" : shell); /******** Modify by ut000610 daizhengwen 2020-07-08:初始化透明度 Begin***************/ // 若没有窗口特效,则不生效 // 若有窗口特效,生效 // 此方法会丢失焦点(show hide方法丢失焦点) // setTermOpacity(Settings::instance()->opacity()); // 底层方法,设置当前窗口的透明度 if (Service::instance()->isWindowEffectEnabled()) { // 判断当前是否有窗口特效 setTerminalOpacity(Settings::instance()->opacity()); } /********************* Modify by ut000610 daizhengwen End ************************/ //setScrollBarPosition(QTermWidget::ScrollBarRight);//commend byq nyq /******** Modify by n014361 wangpeili 2020-01-13: ****************/ // theme QString theme = "Dark"; if (DGuiApplicationHelper::instance()->themeType() == DGuiApplicationHelper::LightType) { theme = "Light"; } setColorScheme(theme); Settings::instance()->setColorScheme(theme); // 这个参数启动为默认值UTF-8 setTextCodec(QTextCodec::codecForName("UTF-8")); /******** Modify by n014361 wangpeili 2020-03-04: 增加保持打开参数控制,默认自动关闭**/ setAutoClose(!m_properties.contains(KeepOpen)); /********************* Modify by n014361 wangpeili End ************************/ // WorkingDir if (m_properties.contains(WorkingDir)) { setWorkingDirectory(m_properties[WorkingDir].toString()); } if (m_properties.contains(Execute)) { //QString args = m_properties[Execute].toString(); //QStringList argList = args.split(QRegExp(QStringLiteral("\\s+")), QString::SkipEmptyParts); QStringList argList = m_properties[Execute].toStringList(); qDebug() << "Execute args:" << argList; if (argList.count() > 0) { setShellProgram(argList.at(0)); argList.removeAt(0); if (argList.count()) { setArgs(argList); } } } // 字体和字体大小, 8#字体立即设置的时候会有BUG显示,做个延迟生效就好了。 if (Settings::instance()->fontSize() == 8) { QTimer::singleShot(10, this, [this]() { QFont font = getTerminalFont(); font.setFamily(Settings::instance()->fontName()); font.setPointSize(Settings::instance()->fontSize()); setTerminalFont(font); }); } else { QFont font = getTerminalFont(); font.setFamily(Settings::instance()->fontName()); font.setPointSize(Settings::instance()->fontSize()); setTerminalFont(font); } // 光标形状 setKeyboardCursorShape(static_cast(Settings::instance()->cursorShape())); // 光标闪烁 setBlinkingCursor(Settings::instance()->cursorBlink()); // 按键滚动 setPressingScroll(Settings::instance()->PressingScroll()); // 输出滚动,会在每个输出判断是否设置了滚动,即时设置 connect(this, &QTermWidget::receivedData, this, [this](QString value) { Q_UNUSED(value) setTrackOutput(Settings::instance()->OutputtingScroll()); }); // 接收到输出 connect(this, &TermWidget::receivedData, this, [this](QString value) { /******** Modify by ut000610 daizhengwen 2020-05-25: quit download****************/ if (value.contains("Transfer incomplete")) { QKeyEvent keyPress(QEvent::KeyPress, Qt::Key_C, Qt::ControlModifier); QApplication::sendEvent(focusWidget(), &keyPress); } if (value.endsWith("\b \b #")) { // 结束的时候有乱码的话,将它清除 QKeyEvent keyPress(QEvent::KeyPress, Qt::Key_U, Qt::ControlModifier); QApplication::sendEvent(focusWidget(), &keyPress); } /********************* Modify by ut000610 daizhengwen End ************************/ // 退出远程后,设置成false if (value.contains("Connection to") && value.contains(" closed.")) { QTimer::singleShot(100, this, [&]() { // 判断是否此时退出远程 if (!isInRemoteServer()) { qDebug() << "exit remote"; setIsConnectRemote(false); // 还原编码 setTextCodec(QTextCodec::codecForName(encode().toLocal8Bit())); qDebug() << "current encode " << encode(); setBackspaceMode(m_backspaceMode); setDeleteMode(m_deleteMode); emit Service::instance()->checkEncode(encode()); } }); } }); connect(this, &QTermWidget::urlActivated, this, [](const QUrl & url, bool fromContextMenu) { if (QApplication::keyboardModifiers() & Qt::ControlModifier || fromContextMenu) { QDesktopServices::openUrl(url); } }); connect(this, &QWidget::customContextMenuRequested, this, &TermWidget::customContextMenuCall); connect(DApplicationHelper::instance(), &DApplicationHelper::themeTypeChanged, this, [ = ](DGuiApplicationHelper::ColorType builtInTheme) { qDebug() << "themeChanged" << builtInTheme; // ThemePanelPlugin *plugin = qobject_cast(getPluginByName("Theme")); QString theme = "Dark"; if (builtInTheme == DGuiApplicationHelper::LightType) { theme = "Light"; } setColorScheme(theme); Settings::instance()->setColorScheme(theme); }); connect(this, &QTermWidget::sig_noMatchFound, this, [this]() { parentPage()->setMismatchAlert(true); }); /********************* Modify by n014361 wangpeili End ************************/ connect(this, &QTermWidget::isTermIdle, this, [this](bool bIdle) { emit termIsIdle(getSessionId(), bIdle); }); TermWidgetPage *parentPage = qobject_cast(parent); //qDebug() << parentPage << endl; connect(this, &QTermWidget::uninstallTerminal, parentPage, &TermWidgetPage::uninstallTerminal); /******** Modify by ut000610 daizhengwen 2020-06-11: 启动成功,则允许下一个窗口创建****************/ connect(this, &TermWidget::processStarted, Service::instance(), [ = ]() { QTimer::singleShot(200, this, [ = ]() { Service::instance()->setMemoryEnable(true); }); }); /********************* Modify by ut000610 daizhengwen End ************************/ startShellProgram(); // 增加可以自动运行脚本的命令,不需要的话,可以删除 if (m_properties.contains(Script)) { QString args = m_properties[Script].toString(); qDebug() << "run cmd:" << args; args.append("\n"); if (!m_properties.contains(KeepOpen)) { args.append("exit\n"); } sendText(args); } connect(this, &QTermWidget::titleChanged, this, [this] { emit termTitleChanged(TermWidget::title()); }); connect(this, &TermWidget::copyAvailable, this, [this](bool enable) { if (Settings::instance()->IsPasteSelection() && enable) { qDebug() << "hasCopySelection"; QString strSelected = selectedText(); QApplication::clipboard()->setText(strSelected, QClipboard::Clipboard); } }); connect(Settings::instance(), &Settings::terminalSettingChanged, this, &TermWidget::onSettingValueChanged); //窗口特效开启则使用设置的透明度,窗口特效关闭时直接把窗口置为不透明 connect(Service::instance(), &Service::onWindowEffectEnabled, this, [this](bool isWinEffectEnabled) { if (isWinEffectEnabled) { this->setTermOpacity(Settings::instance()->opacity()); } else { this->setTermOpacity(1.0); } }); } TermWidget::~TermWidget() { // 窗口减1 WindowsManager::instance()->terminalCountReduce(); } TermWidgetPage *TermWidget::parentPage() { //qDebug() << "parentPage" << parentWidget(); return m_Page; } void TermWidget::handleTermIdle(bool bIdle) { emit termIsIdle(this->getSessionId(), bIdle); } /*** 修复 bug 28162 鼠标左右键一起按终端会退出 ***/ void TermWidget::addMenuActions(const QPoint &pos) { bool isRemoting = isInRemoteServer(); QList termActions = filterActions(pos); for (QAction *&action : termActions) { m_menu->addAction(action); } if (!m_menu->isEmpty()) { m_menu->addSeparator(); } // add other actions here. if (!selectedText().isEmpty()) { m_menu->addAction(tr("Copy"), this, [this] { copyClipboard(); }); } if (!QApplication::clipboard()->text(QClipboard::Clipboard).isEmpty()) { m_menu->addAction(tr("Paste"), this, [this] { pasteClipboard(); }); } /******** Modify by n014361 wangpeili 2020-02-26: 添加打开(文件)菜单功能 **********/ if (!isRemoting && !selectedText().isEmpty()) { QFileInfo tempfile(workingDirectory() + "/" + selectedText()); if (tempfile.exists()) { m_menu->addAction(tr("Open"), this, [this] { QString file = workingDirectory() + "/" + selectedText(); QString cmd = QString("xdg-open ") + file; //在linux下,可以通过system来xdg-open命令调用默认程序打开文件; system(cmd.toStdString().c_str()); // qDebug() << file << " open"; }); } } /********************* Modify by n014361 wangpeili End ************************/ m_menu->addAction(tr("Open in file manager"), this, [this] { DDesktopServices::showFolder(QUrl::fromLocalFile(workingDirectory())); }); m_menu->addSeparator(); Qt::Orientation orientation = static_cast(parentWidget())->orientation(); int layer = getTermLayer(); if (layer == 1 || (layer == 2 && orientation == Qt::Horizontal)) { m_menu->addAction(tr("Horizontal split"), this, [this] { getTermLayer(); parentPage()->split(Qt::Horizontal); }); } if (layer == 1 || (layer == 2 && orientation == Qt::Vertical)) { m_menu->addAction(tr("Vertical split"), this, [this] { getTermLayer(); parentPage()->split(Qt::Vertical); }); } /******** Modify by n014361 wangpeili 2020-02-21: 增加关闭窗口和关闭其它窗口菜单 ****************/ m_menu->addAction(tr("Close window"), this, [this] { parentPage()->closeSplit(parentPage()->currentTerminal()); }); //m_menu->addAction(tr("Close Window"), this, [this] { ((TermWidgetPage *)m_Page)->close();}); if (parentPage()->getTerminalCount() > 1) { m_menu->addAction(tr("Close other windows"), this, [this] { parentPage()->closeOtherTerminal(); }); }; /********************* Modify by n014361 wangpeili End ************************/ m_menu->addSeparator(); m_menu->addAction(tr("New workspace"), this, [this] { parentPage()->parentMainWindow()->createNewWorkspace(); }); m_menu->addSeparator(); if (!parentPage()->parentMainWindow()->isQuakeMode()) { bool isFullScreen = this->window()->windowState().testFlag(Qt::WindowFullScreen); if (isFullScreen) { m_menu->addAction(tr("Exit fullscreen"), this, [this] { parentPage()->parentMainWindow()->switchFullscreen(); }); } else { m_menu->addAction(tr("Fullscreen"), this, [this] { parentPage()->parentMainWindow()->switchFullscreen(); }); } } m_menu->addAction(tr("Find"), this, [this] { parentPage()->parentMainWindow()->showPlugin(MainWindow::PLUGIN_TYPE_SEARCHBAR); }); m_menu->addSeparator(); if (!selectedText().isEmpty()) { DMenu *search = new DMenu(tr("Search"), this); search->addAction("Bing", this, [this] { QString strurl = "https://cn.bing.com/search?q=" + selectedText(); QDesktopServices::openUrl(QUrl(strurl)); }); search->addAction("Baidu", this, [this] { QString strurl = "https://www.baidu.com/s?wd=" + selectedText(); QDesktopServices::openUrl(QUrl(strurl)); }); search->addAction("Github", this, [this] { QString strurl = "https://github.com/search?q=" + selectedText(); QDesktopServices::openUrl(QUrl(strurl)); }); search->addAction("Stack Overflow", this, [this] { QString strurl = "https://stackoverflow.com/search?q=" + selectedText(); QDesktopServices::openUrl(QUrl(strurl)); }); m_menu->addMenu(search); m_menu->addSeparator(); } m_menu->addAction(tr("Rename title"), this, [this] { //QString currTabTitle = this->property("currTabTitle").toString(); /************************ Mod by sunchengxi 2020-04-30:分屏修改标题异常问题 Begin************************/ QString currTabTitle = parentPage()->parentMainWindow()->getCurrTabTitle(); if (currTabTitle.isEmpty()) { currTabTitle = this->property("currTabTitle").toString(); } /************************ Mod by sunchengxi 2020-04-30:分屏修改标题异常问题 End ************************/ if (currTabTitle.isNull()) { currTabTitle = this->title(); } qDebug() << "currTabTitle" << currTabTitle << endl; parentPage()->showRenameTitleDialog(currTabTitle); }); m_menu->addAction(tr("Encoding"), this, [this] { parentPage()->parentMainWindow()->showPlugin(MainWindow::PLUGIN_TYPE_ENCODING); }); m_menu->addAction(tr("Custom commands"), this, [this] { parentPage()->parentMainWindow()->showPlugin(MainWindow::PLUGIN_TYPE_CUSTOMCOMMAND); }); m_menu->addAction(tr("Remote management"), this, [this] { parentPage()->parentMainWindow()->showPlugin(MainWindow::PLUGIN_TYPE_REMOTEMANAGEMENT); }); if (isInRemoteServer()) { m_menu->addSeparator(); m_menu->addAction(tr("Upload file"), this, [this] { parentPage()->parentMainWindow()->remoteUploadFile(); }); m_menu->addAction(tr("Download file"), this, [this] { parentPage()->parentMainWindow()->remoteDownloadFile(); }); } m_menu->addSeparator(); m_menu->addAction(tr("Settings"), this, [ = ] { Service::instance()->showSettingDialog(parentPage()->parentMainWindow()); }); // 判断是否到达最大数量 if (!Service::instance()->isCountEnable()) { QList actionList = m_menu->actions(); for (auto item : actionList) { if (item->text() == tr("New workspace") || item->text() == tr("Horizontal split") || item->text() == tr("Vertical split")) { // 无法点击的菜单项置灰 item->setEnabled(false); } } } } QString TermWidget::RemoteEncode() const { return m_RemoteEncode; } void TermWidget::setRemoteEncode(const QString &RemoteEncode) { m_RemoteEncode = RemoteEncode; } /******************************************************************************* 1. @函数: setBackspaceMode 2. @作者: ut000610 戴正文 3. @日期: 2020-06-02 4. @说明: 根据设置的模式改变退格模式 *******************************************************************************/ void TermWidget::setBackspaceMode(const EraseMode &backspaceMode) { char ch; int length; switch (backspaceMode) { case EraseMode_Auto: ch = getErase(); if (ch == 0) { ch = '\010'; } length = 1; break; case EraseMode_Control_H: ch = '\010'; length = 1; break; case EraseMode_Ascii_Delete: ch = '\177'; length = 1; break; case EraseMode_TTY: ch = getErase(); length = 1; qDebug() << "tty erase : " << QByteArray(&ch, length).toHex(); break; case EraseMode_Escape_Sequeue: length = 4; char sequeue[] = "\e[3~"; QTermWidget::setBackspaceMode(sequeue, 4); return; } QTermWidget::setBackspaceMode(&ch, length); } /******************************************************************************* 1. @函数: setDeleteMode 2. @作者: ut000610 戴正文 3. @日期: 2020-06-02 4. @说明: 根据设置的模式改变删除模式 *******************************************************************************/ void TermWidget::setDeleteMode(const EraseMode &deleteMode) { char ch; int length; switch (deleteMode) { case EraseMode_Control_H: ch = '\010'; length = 1; break; case EraseMode_Ascii_Delete: ch = '\177'; length = 1; break; case EraseMode_TTY: ch = getErase(); length = 1; qDebug() << "tty erase : " << QByteArray(&ch, length).toHex(); break; case EraseMode_Auto: case EraseMode_Escape_Sequeue: length = 4; char sequeue[] = "\e[3~"; QTermWidget::setDeleteMode(sequeue, 4); return; } QTermWidget::setDeleteMode(&ch, length); } /******************************************************************************* 1. @函数: getTermLayer 2. @作者: ut000439 王培利 3. @日期: 2020-06-06 4. @说明: 获取当前terminal距离page的层次.用于限定分屏. *******************************************************************************/ int TermWidget::getTermLayer() { int layer = 1; QWidget *currentW = this; while (currentW->parentWidget() != parentPage()) { layer++; currentW = currentW->parentWidget(); } qDebug() << "getTermLayer = " << layer; return layer; } QString TermWidget::encode() const { return m_encode; } void TermWidget::setEncode(const QString &encode) { m_encode = encode; } bool TermWidget::isConnectRemote() const { return m_isConnectRemote; } void TermWidget::setIsConnectRemote(bool isConnectRemote) { m_isConnectRemote = isConnectRemote; } bool TermWidget::enterSzCommand() const { return m_enterSzCommand; } void TermWidget::setEnterSzCommand(bool enterSzCommand) { m_enterSzCommand = enterSzCommand; } void TermWidget::customContextMenuCall(const QPoint &pos) { /***add by ut001121 zhangmeng 20200514 右键获取焦点, 修复BUG#26003***/ setFocus(); // 右键清理插件 parentPage()->parentMainWindow()->showPlugin(MainWindow::PLUGIN_TYPE_NONE); /*** 修复 bug 28162 鼠标左右键一起按终端会退出 ***/ if (nullptr == m_menu) { m_menu = new DMenu(this); } m_menu->clear(); addMenuActions(pos); // display the menu. m_menu->exec(mapToGlobal(pos)); } bool TermWidget::isInRemoteServer() { int pid = getForegroundProcessId(); if (pid <= 0) { return false; } QString pidFilepath = "/proc/" + QString::number(pid) + "/comm"; QFile pidFile(pidFilepath); if (pidFile.exists()) { pidFile.open(QIODevice::ReadOnly | QIODevice::Text); QString commString(pidFile.readLine()); pidFile.close(); if ("expect" == commString.trimmed()) { return true; } } return false; } void TermWidget::setTermOpacity(qreal opacity) { //这里再次判断一遍,因为刚启动时,还是需要判断一次当前是否开启了窗口特效 qreal termOpacity = opacity; if (!Service::instance()->isWindowEffectEnabled()) { termOpacity = 1.0; } setTerminalOpacity(termOpacity); /******* Modify by n014361 wangpeili 2020-01-04: 修正实时设置透明度问题************/ hide(); show(); /********************* Modify by n014361 wangpeili End ************************/ } /******************************************************************************* 1. @函数: void TermWidgetWrapper::setTerminalFont(const QString &fontName) 2. @作者: n014361 王培利 3. @日期: 2020-01-10 4. @说明: 设置字体 *******************************************************************************/ void TermWidget::setTermFont(const QString &fontName) { QFont font = getTerminalFont(); font.setFamily(fontName); setTerminalFont(font); } /******************************************************************************* 1. @函数: void TermWidgetWrapper::setTerminalFontSize(const int fontSize) 2. @作者: n014361 王培利 3. @日期: 2020-01-10 4. @说明: 设置字体大小 *******************************************************************************/ void TermWidget::setTermFontSize(const int fontSize) { QFont font = getTerminalFont(); font.setFixedPitch(true); font.setPointSize(fontSize); setTerminalFont(font); } /******************************************************************************* 1. @函数: void TermWidgetWrapper::skipToNextCommand() 2. @作者: n014361 王培利 3. @日期: 2020-01-10 4. @说明: 跳转到下一个命令(这个功能没找到库的接口,现在是暂时是以虚拟键形式实现) *******************************************************************************/ void TermWidget::skipToNextCommand() { qDebug() << "skipToNextCommand"; } /******************************************************************************* 1. @函数: void TermWidgetWrapper::skipToPreCommand() 2. @作者: n014361 王培利 3. @日期: 2020-01-10 4. @说明: 跳转到前一个命令(这个功能没找到库的接口,现在是暂时是以虚拟键形式实现) *******************************************************************************/ void TermWidget::skipToPreCommand() { qDebug() << "skipToPreCommand"; } /******************************************************************************* 1. @函数: void TermWidgetWrapper::setCursorShape(int shape) 2. @作者: n014361 王培利 3. @日期: 2020-01-10 4. @说明: 设置光标形状 *******************************************************************************/ void TermWidget::setCursorShape(int shape) { Konsole::Emulation::KeyboardCursorShape cursorShape = Konsole::Emulation::KeyboardCursorShape(shape); setKeyboardCursorShape(cursorShape); } void TermWidget::setPressingScroll(bool enable) { if (enable) { setMotionAfterPasting(2); } else { setMotionAfterPasting(0); } } void TermWidget::selectEncode(QString encode) { // 直接设置终端 setTextCodec(QTextCodec::codecForName(encode.toUtf8())); // 是否连接远程 if (!isConnectRemote()) { // 记录当前的encode setEncode(encode); qDebug() << "current encode " << encode; } else { // 记录远程的encode setRemoteEncode(encode); qDebug() << "Remote encode " << encode; } } /******************************************************************************* 1. @函数: void TermWidgetWrapper::pasteSelection() 2. @作者: n014361 王培利 3. @日期: 2020-01-10 4. @说明: 粘贴选择内容 *******************************************************************************/ void TermWidget::wpasteSelection() { int x1, y1, x2, y2; getSelectionStart(x1, y1); qDebug() << x1 << y1; getSelectionEnd(x2, y2); qDebug() << x2 << y2; pasteSelection(); } /******************************************************************************* 1. @函数: onSettingValueChanged 2. @作者: n014361 王培利 3. @日期: 2020-02-20 4. @说明: Terminal的各项设置生效 *******************************************************************************/ void TermWidget::onSettingValueChanged(const QString &keyName) { qDebug() << "onSettingValueChanged:" << keyName; if (keyName == "basic.interface.opacity") { setTermOpacity(Settings::instance()->opacity()); return; } if (keyName == "basic.interface.font") { setTermFont(Settings::instance()->fontName()); /******** Add by nt001000 renfeixiang 2020-05-20:增加字体变化时设置雷神窗口最小高度 Begin***************/ m_Page->parentMainWindow()->setWindowMinHeightForFont(); //qDebug() << "font_sizefont_sizefont_sizefont_size" << Settings::instance()->fontSize(); /******** Add by nt001000 renfeixiang 2020-05-20:增加字体变化时设置雷神窗口最小高度 End***************/ return; } if (keyName == "basic.interface.font_size") { setTermFontSize(Settings::instance()->fontSize()); /******** Add by nt001000 renfeixiang 2020-05-20:增加字体大小变化时设置雷神窗口最小高度 Begin***************/ m_Page->parentMainWindow()->setWindowMinHeightForFont(); //qDebug() << "font_sizefont_sizefont_sizefont_size" << Settings::instance()->fontSize(); /******** Add by nt001000 renfeixiang 2020-05-20:增加字体大小变化时设置雷神窗口最小高度 End***************/ return; } if (keyName == "advanced.cursor.cursor_shape") { setCursorShape(Settings::instance()->cursorShape()); return; } if (keyName == "advanced.cursor.cursor_blink") { setBlinkingCursor(Settings::instance()->cursorBlink()); return; } if (keyName == "advanced.scroll.scroll_on_key") { setPressingScroll(Settings::instance()->PressingScroll()); return; } if (keyName == "basic.interface.theme") { return; } // 这里只是立即生效一次,真正生效起作用的地方在初始的connect中 if (keyName == "advanced.cursor.auto_copy_selection") { if (Settings::instance()->IsPasteSelection()) { copyClipboard(); } else { QApplication::clipboard()->clear(QClipboard::Clipboard); } return; } if (keyName == "advanced.scroll.scroll_on_output") { qDebug() << "settingValue[" << keyName << "] changed to " << Settings::instance()->OutputtingScroll() << ", auto effective when happen"; return; } qDebug() << "settingValue[" << keyName << "] changed is not effective"; } deepin-terminal-5.2.11/src/views/termwidget.h000066400000000000000000000060151370157770500211430ustar00rootroot00000000000000#ifndef TERMWIDGET_H #define TERMWIDGET_H #include "qtermwidget.h" #include "termwidgetpage.h" // 删除和退格键可选模式 enum EraseMode { EraseMode_Auto, EraseMode_Ascii_Delete, EraseMode_Control_H, EraseMode_TTY, EraseMode_Escape_Sequeue }; class TermProperties; class TermWidget : public QTermWidget { Q_OBJECT public: TermWidget(TermProperties properties, QWidget *parent = nullptr); ~TermWidget(); TermWidgetPage *parentPage(); bool isInRemoteServer(); public: // 跳转到下一个命令 void skipToNextCommand(); // 跳转到前一个命令 void skipToPreCommand(); void setTermOpacity(qreal opacity); // 修改字体 void setTermFont(const QString &fontName); // 修改字体大小 void setTermFontSize(const int fontSize); // 修改光标形状 void setCursorShape(int shape); void setPressingScroll(bool enable); // 设置编码 void selectEncode(QString encode); // // session支持最大值.再多了就起不来了. // static const int MaxTermwidgetCount = 199; bool enterSzCommand() const; void setEnterSzCommand(bool enterSzCommand); bool isConnectRemote() const; void setIsConnectRemote(bool isConnectRemote); QString encode() const; void setEncode(const QString &encode); QString RemoteEncode() const; void setRemoteEncode(const QString &RemoteEncode); // 设置退格键模式(用户选择接口) void setBackspaceMode(const EraseMode &backspaceMode); // 设置删除键模式(用户选择接口) void setDeleteMode(const EraseMode &deleteMode); // 获取该终端距离page的层次 int getTermLayer(); public slots: void wpasteSelection(); void onSettingValueChanged(const QString &keyName); signals: void termRequestRenameTab(QString newTabName); void termIsIdle(int currSessionId, bool bIdle); void termTitleChanged(QString titleText); private slots: void customContextMenuCall(const QPoint &pos); void handleTermIdle(bool bIdle); private: /*** 修复 bug 28162 鼠标左右键一起按终端会退出 ***/ void addMenuActions(const QPoint &pos); TermWidgetPage *m_Page = nullptr; TermProperties m_properties; DMenu *m_menu = nullptr; /******** Modify by ut000610 daizhengwen 2020-05-27: 当前窗口是否要进行下载操作****************/ bool m_enterSzCommand = false; /********************* Modify by ut000610 daizhengwen End ************************/ /******** Modify by ut000610 daizhengwen 2020-05-28: 当前窗口是否连接远程服务器****************/ bool m_isConnectRemote = false; /********************* Modify by ut000610 daizhengwen End ************************/ // 当前编码 QString m_encode = "UTF-8"; // 远程编码 QString m_RemoteEncode = "UTF-8"; // 当前终端退格信号 EraseMode m_backspaceMode = EraseMode_Ascii_Delete; // 当前终端删除信号 EraseMode m_deleteMode = EraseMode_Escape_Sequeue; }; #endif // TERMWIDGET_H deepin-terminal-5.2.11/src/views/termwidgetpage.cpp000066400000000000000000000670671370157770500223510ustar00rootroot00000000000000#include "termwidgetpage.h" #include "termwidget.h" #include "settings.h" #include "utils.h" #include "service.h" #include "windowsmanager.h" #include #include #include #include #include TermWidgetPage::TermWidgetPage(TermProperties properties, QWidget *parent) : QWidget(parent), m_findBar(new PageSearchBar(this)) { //qDebug() << "parentTermWidgetPage" << parentWidget(); m_MainWindow = static_cast(parentWidget()); setFocusPolicy(Qt::NoFocus); setProperty("TAB_CUSTOM_NAME_PROPERTY", false); // 生成唯一 pageID setProperty("TAB_IDENTIFIER_PROPERTY", QUuid::createUuid().toString()); TermWidget *w = createTerm(properties); m_layout = new QVBoxLayout(this); m_layout->setSpacing(0); m_layout->setContentsMargins(0, 0, 0, 0); m_layout->addWidget(w); setLayout(m_layout); //qDebug() << "w->parent()" << w->parent(); // Init find bar. m_findBar->move(this->x() - 100, this->y() - 100); connect(m_findBar, &PageSearchBar::findNext, this, &TermWidgetPage::handleFindNext); connect(m_findBar, &PageSearchBar::findPrev, this, &TermWidgetPage::handleFindPrev); connect(m_findBar, &PageSearchBar::keywordChanged, this, [ = ](QString keyword) { handleUpdateSearchKeyword(keyword); }); connect(DApplicationHelper::instance(), &DApplicationHelper::themeTypeChanged, this, [ = ]() { applyTheme(); }); /******** Modify by nt001000 renfeixiang 2020-05-27:修改 增加参数区别remove和purge卸载命令 2020-05-28 优化代码 Begin***************/ connect(this, &TermWidgetPage::uninstallTerminal, this, [this](QString commandname) { //MainWindow *mainWindow = qobject_cast(parent); //构造函数中已经获取了mainwindow窗口,无需在获取一遍 if (m_MainWindow->hasRunningProcesses()) { if (!Utils::showExitUninstallConfirmDialog()) { return false; } } return Utils::showUnistallConfirmDialog(commandname); }); /******** Modify by nt001000 renfeixiang 2020-05-27:修改 增加参数区别remove和purge卸载命令 Begin***************/ m_currentTerm = w; } MainWindow *TermWidgetPage::parentMainWindow() { //qDebug()<<"parentMainWindow" <setHandleWidth(1); QSplitterHandle *handle = splitter->handle(1); if (handle) { //分割线颜色暂时设置为Highlight颜色,需要和UI确认下 DPalette pa = DApplicationHelper::instance()->palette(handle); QColor splitBrush = pa.color(DPalette::Highlight); pa.setBrush(DPalette::Background, splitBrush); handle->setPalette(pa); handle->setBackgroundRole(QPalette::Background); handle->setAutoFillBackground(true); } } TermWidget *TermWidgetPage::currentTerminal() { return m_currentTerm; } //TermWidget *TermWidgetPage::split(Qt::Orientation orientation) //{ // return split(currentTerminal(), orientation); //} /******************************************************************************* 1. @函数: 2. @作者: ut000439 王培利 3. @日期: 2020-05-14 4. @说明: *******************************************************************************/ void TermWidgetPage::split(Qt::Orientation orientation) { parentMainWindow()->showPlugin(MainWindow::PLUGIN_TYPE_NONE); TermWidget *term = m_currentTerm; if (getTerminalCount() == 1) { qDebug() << "first split"; QSplitter *firstSplit = createSubSplit(term, orientation); m_layout->addWidget(firstSplit); return ; } qDebug() << "not first split"; QSplitter *upSplit = qobject_cast(term->parent()); int index = upSplit->indexOf(term); QList parentSizes = upSplit->sizes(); // 用新的Split分割布局替换原来的位置 QSplitter *subSplit = createSubSplit(term, orientation); upSplit->insertWidget(index, subSplit); upSplit->setSizes(parentSizes); setSplitStyle(upSplit); return ; } /******************************************************************************* 1. @函数: createSubSplit 2. @作者: ut000439 王培利 3. @日期: 2020-05-14 4. @说明: 创建分屏 *******************************************************************************/ DSplitter *TermWidgetPage::createSubSplit(TermWidget *term, Qt::Orientation orientation) { TermProperties properties(term->workingDirectory()); term->setParent(nullptr); TermWidget *newTerm = createTerm(properties); // 意义与名称是相反的 DSplitter *subSplit = new DSplitter(orientation == Qt::Horizontal ? Qt::Vertical : Qt::Horizontal, this); subSplit->setFocusPolicy(Qt::NoFocus); subSplit->insertWidget(0, term); subSplit->insertWidget(1, newTerm); subSplit->setSizes({ 1, 1 }); setSplitStyle(subSplit); setCurrentTerminal(newTerm); return subSplit; } /******************************************************************************* 1. @函数: 2. @作者: ut000439 王培利 3. @日期: 2020-05-15 4. @说明: *******************************************************************************/ void TermWidgetPage::closeSplit(TermWidget *term, bool hasConfirmed) { qDebug() << "TermWidgetPage::closeSplit:" << term->getSessionId(); if (getTerminalCount() > 1) { if (!hasConfirmed && term->hasRunningProcess()) { showExitConfirmDialog(Utils::CloseType_Terminal, 1, parentMainWindow()); return; } QSplitter *upSplit = qobject_cast(term->parent()); term->setParent(nullptr); // 另一个兄弟也可能是终端,也可能是split, QWidget *brother = upSplit->widget(0); TermWidget *nextTerm = upSplit->findChild(); // 如果上级是分屏 if ("QSplitter" == QString(upSplit->parent()->metaObject()->className())) { QSplitter *upupSplit = qobject_cast(upSplit->parent()); //兄弟替换parent split upupSplit->replaceWidget(upupSplit->indexOf(upSplit), brother); } // 上级不是分屏控件,就是布局在控制了 else { qDebug() << "TermWidgetPage only one term exist!"; m_layout->addWidget(brother); } // 子控件的变化会引起焦点的变化,控制焦点要放在最后 if (nextTerm != nullptr) { qDebug() << "nextTerm change" << m_currentTerm->getSessionId(); nextTerm->setFocus(); } // 释放控件 term->deleteLater(); upSplit->setParent(nullptr); upSplit->deleteLater(); qDebug() << "page terminal count =" << getTerminalCount(); return; } parentMainWindow()->closeTab(identifier()); return; } void TermWidgetPage::showExitConfirmDialog(Utils::CloseType type, int count, QWidget *parent) { /******** Modify by ut001000 renfeixiang 2020-06-03:修改 直接调用MainWindow中的showExitConfirmDialog函数中 Begin***************/ parentMainWindow()->showExitConfirmDialog(type, count, parent); /******** Modify by ut001000 renfeixiang 2020-06-03:修改 直接调用MainWindow中的showExitConfirmDialog函数中 End***************/ // // count < 1 不提示 // if (count < 1) { // return; // } // QString title; // QString txt; // Utils::getExitDialogText(type, title, txt, count); // // 有弹窗显示 // Service::instance()->setIsDialogShow(window(), true); // DDialog *dlg = new DDialog(title, txt, parent); // dlg->setIcon(QIcon::fromTheme("deepin-terminal")); // dlg->addButton(QString(tr("Cancel")), false, DDialog::ButtonNormal); // /******** Modify by nt001000 renfeixiang 2020-05-21:修改Exit成Close Begin***************/ // dlg->addButton(QString(tr("Close")), true, DDialog::ButtonWarning); // /******** Modify by nt001000 renfeixiang 2020-05-21:修改Exit成Close End***************/ // dlg->setWindowModality(Qt::WindowModal); // setAttribute(Qt::WA_ShowModal); // dlg->show(); // if (type == Utils::CloseType_Terminal) { // connect(dlg, &DDialog::finished, this, [this](int result) { // qDebug() << result; // // 有弹窗消失 // Service::instance()->setIsDialogShow(window(), false); // if (result == 1) { // //接口二次重入 // closeSplit(currentTerminal(), true); // } // }); // } // if (type == Utils::CloseType_OtherTerminals) { // connect(dlg, &DDialog::finished, this, [this](int result) { // qDebug() << result; // // 有弹窗消失 // Service::instance()->setIsDialogShow(window(), false); // if (result == 1) { // //接口二次重入 // closeOtherTerminal(true); // } // }); // } return ; } const QString TermWidgetPage::identifier() { return property("TAB_IDENTIFIER_PROPERTY").toString(); } void TermWidgetPage::focusCurrentTerm() { m_currentTerm->setFocus(); } void TermWidgetPage::closeOtherTerminal(bool hasConfirmed) { int runningCount = runningTerminalCount() - static_cast(currentTerminal()->hasRunningProcess()); if (!hasConfirmed && runningCount != 0) { showExitConfirmDialog(Utils::CloseType_OtherTerminals, runningCount, parentMainWindow()); return; } QList termList = findChildren(); int currSessionId = m_currentTerm->getSessionId(); //exit protection for (TermWidget *term : qAsConst(termList)) { if (term->getSessionId() != currSessionId) { // 前面已经检测过了,不用重复检测 closeSplit(term, true); } } setTerminalOpacity(Settings::instance()->opacity()); } #if 0 // 待删除 typedef struct { QPoint topLeft; QPoint middle; QPoint bottomRight; } CoordinateRect; // 待删除 static void transpose(QPoint *point) { int x = point->x(); point->setX(point->y()); point->setY(x); } // 待删除 static void transposeTransform(CoordinateRect *point) { transpose(&point->topLeft); transpose(&point->middle); transpose(&point->bottomRight); } // 待删除 static void flipTransform(CoordinateRect *point) { QPoint oldTopLeft = point->topLeft; point->topLeft = -(point->bottomRight); point->bottomRight = -(oldTopLeft); point->middle = -(point->middle); } // 待删除 static void normalizeToRight(CoordinateRect *point, Qt::Edge dir) { switch (dir) { case Qt::LeftEdge: flipTransform(point); break; case Qt::RightEdge: // No-op break; case Qt::TopEdge: flipTransform(point); transposeTransform(point); break; case Qt::BottomEdge: transposeTransform(point); break; default: qFatal("Invalid navigation"); return; } } #endif /******** Modify by ut000439 wangpeili 2020-01-07: 修改了计算上下左右判断的方法 ********×****/ void TermWidgetPage::focusNavigation(Qt::Edge dir) { QPoint comparPoint = GetComparePoint(currentTerminal(), dir); TermWidget *dst = nullptr; QList termList = findChildren(); //QMap mapTermRect; for (TermWidget *term : qAsConst(termList)) { if (GetRect(term).contains(comparPoint)) { qDebug() << "yes!" << comparPoint.x() << comparPoint.y(); dst = term; break; } } if (dst) { dst->setFocus(); } } /******************************************************************************* 1. @函数: getTerminalCount 2. @作者: ut000439 王培利 3. @日期: 2020-02-21 4. @说明: 获取当前页的终端个数 *******************************************************************************/ int TermWidgetPage::getTerminalCount() { return findChildren().size(); } /********************* Modify by ut000439 wangpeili End ************************/ /******************************************************************************* 1. @函数: QRect TermWidgetPage::GetRect(TermWidgetWrapper *term) 2. @作者: ut000439 王培利 3. @日期: 2020-01-10 4. @说明: 获取标签页内所有子窗体的区域 *******************************************************************************/ QRect TermWidgetPage::GetRect(TermWidget *term) { QPoint leftTop = term->mapTo(term->window(), QPoint(0, 0)); QPoint rightBottom = term->mapTo(term->window(), QPoint(term->width(), term->height())); QRect rec(leftTop, rightBottom); qDebug() << "leftTop: " << leftTop.x() << leftTop.y() << "rightBottom: " << rightBottom.x() << rightBottom.y(); return rec; } /******************************************************************************* 1. @函数: QPoint TermWidgetPage::GetComparePoint(TermWidgetWrapper *term, Qt::Edge dir) 2. @作者: ut000439 王培利 3. @日期: 2020-01-08 4. @说明: 获取窗口上下左右键需要判断的点位信息 *******************************************************************************/ QPoint TermWidgetPage::GetComparePoint(TermWidget *term, Qt::Edge dir) { QPoint leftTop = term->mapTo(term->window(), QPoint(0, 0)); QPoint leftBottom = term->mapTo(term->window(), QPoint(0, term->height())); QPoint rightTop = term->mapTo(term->window(), QPoint(term->width(), 0)); QPoint ret; switch (dir) { case Qt::LeftEdge: ret = leftTop + QPoint(-1, 1); break; case Qt::RightEdge: ret = rightTop + QPoint(1, 1); break; case Qt::TopEdge: ret = leftTop + QPoint(1, -1); break; case Qt::BottomEdge: ret = leftBottom + QPoint(1, 1); break; } return ret; } int TermWidgetPage::runningTerminalCount() { int count = 0; QList termList = findChildren(); for (TermWidget *term : termList) { if (term->hasRunningProcess()) { count++; } } return count; } TermProperties TermWidgetPage::createCurrentTerminalProperties() { TermProperties properties; TermWidget *term = currentTerminal(); if (term) { properties[WorkingDir] = currentTerminal()->workingDirectory(); } return properties; } void TermWidgetPage::setTerminalOpacity(qreal opacity) { QList termList = findChildren(); for (TermWidget *term : termList) { term->setTermOpacity(opacity); } } void TermWidgetPage::setColorScheme(const QString &name) { QList termList = findChildren(); for (TermWidget *term : termList) { term->setColorScheme(name); } } void TermWidgetPage::sendTextToCurrentTerm(const QString &text) { TermWidget *term = currentTerminal(); if (term) { term->sendText(text); } } void TermWidgetPage::copyClipboard() { TermWidget *term = currentTerminal(); if (term) { term->copyClipboard(); } } /******************************************************************************* 1. @函数: void TermWidgetPage::pasteClipboard() 2. @作者: ut000439 王培利 3. @日期: 2020-01-10 4. @说明: 用户粘贴时候,直接粘贴剪切板内容 *******************************************************************************/ void TermWidgetPage::pasteClipboard() { TermWidget *term = currentTerminal(); if (term) { term->pasteClipboard(); } } void TermWidgetPage::toggleShowSearchBar() { TermWidget *term = currentTerminal(); if (term) { term->toggleShowSearchBar(); } } void TermWidgetPage::zoomInCurrentTierminal() { TermWidget *term = currentTerminal(); if (term) { term->zoomIn(); } } void TermWidgetPage::zoomOutCurrentTerminal() { TermWidget *term = currentTerminal(); if (term) { term->zoomOut(); } } /******************************************************************************* 1. @函数: void TermWidgetPage::setFontSize(int fontSize) 2. @作者: ut000439 王培利 3. @日期: 2020-01-10 4. @说明: 设置字体大小 *******************************************************************************/ void TermWidgetPage::setFontSize(int fontSize) { QList termList = findChildren(); for (TermWidget *term : termList) { term->setTermFontSize(fontSize); } } /******************************************************************************* 1. @函数: void TermWidgetPage::setFont(QString fontName) 2. @作者: ut000439 王培利 3. @日期: 2020-01-10 4. @说明: 设置字体 *******************************************************************************/ void TermWidgetPage::setFont(QString fontName) { QList termList = findChildren(); for (TermWidget *term : termList) { term->setTermFont(fontName); } } /******************************************************************************* 1. @函数: void TermWidgetPage::selectAll() 2. @作者: ut000439 王培利 3. @日期: 2020-01-10 4. @说明: 全选 *******************************************************************************/ void TermWidgetPage::selectAll() { TermWidget *term = currentTerminal(); if (term) { term->setSelectionAll(); } } /******************************************************************************* 1. @函数: void TermWidgetPage::skipToNextCommand() 2. @作者: ut000439 王培利 3. @日期: 2020-01-10 4. @说明: 跳转到下一命令 *******************************************************************************/ void TermWidgetPage::skipToNextCommand() { TermWidget *term = currentTerminal(); if (term) { term->skipToNextCommand(); } } /******************************************************************************* 1. @函数: void TermWidgetPage::skipToPreCommand() 2. @作者: ut000439 王培利 3. @日期: 2020-01-10 4. @说明: 跳转到前一命令 *******************************************************************************/ void TermWidgetPage::skipToPreCommand() { TermWidget *term = currentTerminal(); if (term) { term->skipToPreCommand(); } } /******************************************************************************* 1. @函数: void TermWidgetPage::setcursorShape() 2. @作者: ut000439 王培利 3. @日期: 2020-01-10 4. @说明: 设置鼠标形状 *******************************************************************************/ void TermWidgetPage::setcursorShape(int shape) { QList termList = findChildren(); for (TermWidget *term : termList) { term->setCursorShape(shape); } } /******************************************************************************* 1. @函数: setBlinkingCursor(bool enable) 2. @作者: 王培利ut000439 3. @日期: 2020-01-10 4. @说明: 设置鼠标闪烁 *******************************************************************************/ void TermWidgetPage::setBlinkingCursor(bool enable) { QList termList = findChildren(); for (TermWidget *term : termList) { term->setBlinkingCursor(enable); } } void TermWidgetPage::setPressingScroll(bool enable) { QList termList = findChildren(); for (TermWidget *term : termList) { term->setPressingScroll(enable); } } /******************************************************************************* 1. @函数: showSearchBar(bool enable) 2. @作者: ut000439 王培利 3. @日期: 2020-02-24 4. @说明: 是否显示搜索框 *******************************************************************************/ void TermWidgetPage::showSearchBar(bool enable) { if (enable) { /******** Add by nt001000 renfeixiang 2020-05-18:修改雷神窗口太小时,查询界面使用不方便,将雷神窗口变大适应正常的查询界面 Begin***************/ if (m_MainWindow->isQuakeMode() && m_MainWindow->height() < 220) { m_MainWindow->resize(m_MainWindow->width(), 220); //首先设置雷神界面的大小 m_MainWindow->showPlugin(MainWindow::PLUGIN_TYPE_SEARCHBAR);//重新打开查询界面,当前流程结束 return; } /******** Add by nt001000 renfeixiang 2020-05-18:修改雷神窗口太小时,查询界面使用不方便,将雷神窗口变大适应正常的查询界面 End***************/ m_findBar->raise(); m_findBar->clearHoldContent(); m_findBar->show(); m_findBar->move(width() - 382, 0); QTimer::singleShot(10, this, [ = ] { m_findBar->focus(); }); } else { m_findBar->hide(); } } /******************************************************************************* 1. @函数: showRenameTitleDialog 2. @作者: ut000610 戴正文 3. @日期: 2020-05-21 4. @说明: 判断是否有重命名弹窗,有则显示,没有则创建 *******************************************************************************/ void TermWidgetPage::showRenameTitleDialog(QString oldTitle) { // 弹窗显示 Service::instance()->setIsDialogShow(window(), true); if (nullptr == m_renameDialog) { m_renameDialog = new TermInputDialog(this); m_renameDialog->setAttribute(Qt::WA_DeleteOnClose); connect(m_renameDialog, &TermInputDialog::finished, m_renameDialog, [ = ]() { // 弹窗隐藏或消失 Service::instance()->setIsDialogShow(window(), false); m_renameDialog = nullptr; }); m_renameDialog->setFixedSize(380, 180); m_renameDialog->setIcon(QIcon::fromTheme("deepin-terminal")); m_renameDialog->setFocusPolicy(Qt::NoFocus); m_renameDialog->showDialog(oldTitle, this); } } void TermWidgetPage::onTermRequestRenameTab(QString newTabName) { if (newTabName.isEmpty()) { setProperty("TAB_CUSTOM_NAME_PROPERTY", false); emit termTitleChanged(m_currentTerm->title()); } else { // Mark it as we renamed it. setProperty("TAB_CUSTOM_NAME_PROPERTY", true); // Yeah, TermWidgetPage doesn't store the tab name, only the tab bar did it. emit tabTitleChanged(newTabName); } } void TermWidgetPage::onTermTitleChanged(QString title) const { TermWidget *term = qobject_cast(sender()); if (m_currentTerm == term) { emit termTitleChanged(title); } } void TermWidgetPage::onTermGetFocus() { TermWidget *term = qobject_cast(sender()); setCurrentTerminal(term); emit Service::instance()->currentTermChange(m_currentTerm); qDebug() << "onTermGetFocus" << m_currentTerm->getSessionId(); emit termGetFocus(); } void TermWidgetPage::onTermClosed() { TermWidget *w = qobject_cast(sender()); if (!w) { qDebug() << "TermWidgetPage::onTermClosed: Unknown object to handle" << w; Q_ASSERT(0); } closeSplit(w); } /******************************************************************************* 1. @函数: handleFindNext 2. @作者: ut000439 王培利 3. @日期: 2020-02-24 4. @说明: 查找下一个接口 *******************************************************************************/ void TermWidgetPage::handleFindNext() { qDebug() << m_findBar->searchKeytxt(); setMismatchAlert(false); m_currentTerm->search(m_findBar->searchKeytxt(), true, true); } /******************************************************************************* 1. @函数: handleFindPrev 2. @作者: ut000439 王培利 3. @日期: 2020-02-24 4. @说明: 查找上一个接口 *******************************************************************************/ void TermWidgetPage::handleFindPrev() { setMismatchAlert(false); m_currentTerm->search(m_findBar->searchKeytxt(), false, false); } void TermWidgetPage::slotFindbarClose() { // EditWrapper *wrapper = currentWrapper(); // if (wrapper->bottomBar()->isHidden()) // { // wrapper->bottomBar()->show(); // } } void TermWidgetPage::handleRemoveSearchKeyword() { // currentWrapper()->textEditor()->removeKeywords(); } /******************************************************************************* 1. @函数: handleUpdateSearchKeyword 2. @作者: ut000439 王培利 3. @日期: 2020-02-24 4. @说明: 更新key(没有输入回车情况),自动查找接口 *******************************************************************************/ void TermWidgetPage::handleUpdateSearchKeyword(const QString &keyword) { setMismatchAlert(false); if (keyword.isEmpty()) { m_currentTerm->clearSelection(); } else { // 输入时直接查找,被禁用 // m_currentTerm->search(m_findBar->SearchKeytxt(), true, false); } } /******************************************************************************* 1. @函数: applyTheme 2. @作者: ut000439 王培利 3. @日期: 2020-03-011 4. @说明: 非DTK控件手动匹配系统主题的修改 *******************************************************************************/ void TermWidgetPage::applyTheme() { updateSplitStyle(); } void TermWidgetPage::updateSplitStyle() { QList splitList = findChildren(); for (DSplitter *splitter : qAsConst(splitList)) { setSplitStyle(splitter); } } void TermWidgetPage::setCurrentTerminal(TermWidget *term) { TermWidget *oldTerm = m_currentTerm; m_currentTerm = term; if (oldTerm != m_currentTerm) { qDebug() << "m_currentTerm change" << m_currentTerm->getSessionId(); if (m_currentTerm->isTitleChanged()) { emit termTitleChanged(m_currentTerm->title()); } else { emit termTitleChanged(windowTitle()); } } } TermWidget *TermWidgetPage::createTerm(TermProperties properties) { TermWidget *term = new TermWidget(properties, this); connect(term, &TermWidget::termRequestRenameTab, this, &TermWidgetPage::onTermRequestRenameTab); connect(term, &TermWidget::termTitleChanged, this, &TermWidgetPage::onTermTitleChanged); connect(term, &TermWidget::termGetFocus, this, &TermWidgetPage::onTermGetFocus); connect(term, &TermWidget::leftMouseClick, this, [this]() { parentMainWindow()->showPlugin(MainWindow::PLUGIN_TYPE_NONE); }); connect(term, &TermWidget::finished, this, &TermWidgetPage::onTermClosed); qDebug() << "create Terminal, sessionId = " << term->getSessionId(); return term; } void TermWidgetPage::setTextCodec(QTextCodec *codec) { TermWidget *term = currentTerminal(); if (term) { term->setTextCodec(codec); } } /******************************************************************************* 1. @函数: setMismatchAlert 2. @作者: ut000439 王培利 3. @日期: 2020-02-24 4. @说明: 是否将输入框标为警告 *******************************************************************************/ void TermWidgetPage::setMismatchAlert(bool alert) { m_findBar->setNoMatchAlert(alert); } /******************************************************************************* 1. @函数: resizeEvent 2. @作者: ut000439 王培利 3. @日期: 2020-02-24 4. @说明: 重绘时候,调整查找框的位置 *******************************************************************************/ void TermWidgetPage::resizeEvent(QResizeEvent *event) { Q_UNUSED(event) //qDebug() << "resizeEvent" << x() << y(); this->m_findBar->move(width() - 382, 0); } deepin-terminal-5.2.11/src/views/termwidgetpage.h000066400000000000000000000107011370157770500217750ustar00rootroot00000000000000#ifndef TERMWIDGETPAGE_H #define TERMWIDGETPAGE_H #include "define.h" #include "termproperties.h" #include "pagesearchbar.h" #include "mainwindow.h" #include "utils.h" #include "terminputdialog.h" #include #include DWIDGET_USE_NAMESPACE class TermWidget; class MainWindow; class TermWidgetPage : public QWidget { Q_OBJECT public: TermWidgetPage(TermProperties properties, QWidget *parent = nullptr); // mainwindow指针,parent()会变化???所以要在构造的时候保存。 MainWindow *parentMainWindow(); TermWidget *currentTerminal(); // 分屏功能 void split(Qt::Orientation orientation); DSplitter *createSubSplit(TermWidget *term, Qt::Orientation orientation); void closeSplit(TermWidget *term, bool hasConfirmed = false); void showExitConfirmDialog(Utils::CloseType type, int count = 1, QWidget *parent = nullptr); // 标识page的唯一ID, 和tab匹配,存在tab中,tabid 用的index,是变化的。 const QString identifier(); void focusCurrentTerm(); void closeOtherTerminal(bool hasConfirmed = false); void focusNavigation(Qt::Edge dir); int getTerminalCount(); /******** Modify by n014361 wangpeili 2020-01-08: 计算上下左右判断方法 ******×****/ QRect GetRect(TermWidget *term); QPoint GetComparePoint(TermWidget *term, Qt::Edge dir); /********************* Modify by n014361 wangpeili End ************************/ int runningTerminalCount(); TermProperties createCurrentTerminalProperties(); void setTerminalOpacity(qreal opacity); void setColorScheme(const QString &name); void sendTextToCurrentTerm(const QString &text); void copyClipboard(); void pasteClipboard(); void toggleShowSearchBar(); void zoomInCurrentTierminal(); void zoomOutCurrentTerminal(); /******** Modify by n014361 wangpeili 2020-01-06:增加相关设置功能 ***********×****/ // 字体大小 void setFontSize(int fontSize); // 字体 void setFont(QString fontName); // 全选 void selectAll(); // 跳转到下一命令 void skipToNextCommand(); // 跳转到前一命令 void skipToPreCommand(); // 设置光标形状 void setcursorShape(int shape); // 设置光标闪烁 void setBlinkingCursor(bool enable); void setPressingScroll(bool enable); void showSearchBar(bool enable); /********************* Modify by n014361 wangpeili End ************************/ void setTextCodec(QTextCodec *codec); void setMismatchAlert(bool alert); // 显示重命名弹窗 void showRenameTitleDialog(QString oldTitle); protected: //将窗口设置为随着窗口变化而变化 virtual void resizeEvent(QResizeEvent *event) override; public slots: void onTermRequestRenameTab(QString newTabName); void onTermTitleChanged(QString title) const; void onTermGetFocus(); void onTermClosed(); // 查找下一个接口 void handleFindNext(); // 查找上一个接口 void handleFindPrev(); // 预留 void slotFindbarClose(); // 预留 void handleRemoveSearchKeyword(); // 更新搜索关键词接口 void handleUpdateSearchKeyword(const QString &keyword); /******** Modify by n014361 wangpeili 2020-03-11: 非DTK控件手动匹配系统主题的修改 **********/ void applyTheme(); /********************* Modify by n014361 wangpeili End ************************/ void updateSplitStyle(); signals: void tabTitleChanged(QString title) const; void termTitleChanged(QString title) const; void lastTermClosed(QString pageIdentifier) const; void termRequestOpenSettings() const; void termGetFocus() const; /******** Modify by nt001000 renfeixiang 2020-05-27:修改 增加参数区别remove和purge卸载命令 Begin***************/ bool uninstallTerminal(QString commandname); /******** Modify by nt001000 renfeixiang 2020-05-27:修改 增加参数区别remove和purge卸载命令 Begin***************/ // 下载失败时退出下载 void quitDownload(); private slots: void setCurrentTerminal(TermWidget *term); private: TermWidget *createTerm(TermProperties properties); void setSplitStyle(DSplitter *splitter); TermWidget *m_currentTerm = nullptr; PageSearchBar *m_findBar = nullptr; MainWindow *m_MainWindow = nullptr; QVBoxLayout *m_layout = nullptr; // 重命名弹框 TermInputDialog *m_renameDialog = nullptr; }; #endif // TERMWIDGETPAGE_H deepin-terminal-5.2.11/src/views/titlebar.cpp000066400000000000000000000033651370157770500211360ustar00rootroot00000000000000#include "titlebar.h" #include #include #include DWIDGET_USE_NAMESPACE TitleBar::TitleBar(QWidget *parent, bool isQuakeWindowStyle) : QWidget(parent), m_layout(new QHBoxLayout(this)) { /******** Modify by m000714 daizhengwen 2020-04-15: 标签栏和Dtk标签色保持一致****************/ // DPalette palette = this->palette(); // palette.setBrush(DPalette::Background, palette.color(DPalette::Base)); // this->setPalette(palette); this->setBackgroundRole(DPalette::Base); this->setAutoFillBackground(true); // daizhengwen fix bug#22927 动画出的矩形框会 -50 设置标题栏为50 this->setFixedHeight(50); /********************* Modify by m000714 daizhengwen End ************************/ m_layout->setContentsMargins(0, 0, 0, 0); if (isQuakeWindowStyle) { return; } if (DApplication::isDXcbPlatform()) { QPixmap iconPixmap = QIcon::fromTheme("deepin-terminal").pixmap(36, 36); QLabel *iconLabel = new QLabel(this); iconLabel->setFixedSize(36, 36); iconLabel->setPixmap(iconPixmap); m_layout->addSpacing(10); /******** Modify by n014361 wangpeili 2020-02-12: 修改居中样式***********×****/ m_layout->addWidget(iconLabel, 0, Qt::AlignVCenter); /***************** Modify by n014361 End ********************×****/ m_layout->addSpacing(10); } } TitleBar::~TitleBar() { } void TitleBar::setTabBar(QWidget *widget) { /******** Modify by n014361 wangpeili 2020-02-12: 修改居中样式***********×****/ m_layout->addWidget(widget, 0, Qt::AlignVCenter); /***************** Modify by n014361 End ********************×****/ } int TitleBar::rightSpace() { return m_rightSpace; } deepin-terminal-5.2.11/src/views/titlebar.h000066400000000000000000000005771370157770500206050ustar00rootroot00000000000000#ifndef TITLEBAR_H #define TITLEBAR_H #include #include class TitleBar : public QWidget { Q_OBJECT public: TitleBar(QWidget *parent = nullptr, bool isQuakeWindowStyle = false); ~TitleBar(); void setTabBar(QWidget *widget); int rightSpace(); private: QHBoxLayout *m_layout = nullptr; int m_rightSpace; }; #endif // TITLEBAR_H deepin-terminal-5.2.11/src/views/warnningdlg.cpp000066400000000000000000000124151370157770500216360ustar00rootroot00000000000000#include "warnningdlg.h" #include "utils.h" #include #include #include #include #include #include #include #include WarnningDlg::WarnningDlg(QWidget *parent) : DAbstractDialog(parent) { initUI(); initContentLayout(); initConnections(); } void WarnningDlg::initUI() { setWindowModality(Qt::ApplicationModal); setFixedSize(m_dlgWidth, m_dlgHeight); QVBoxLayout *mainLayout = new QVBoxLayout(); mainLayout->setSpacing(0); mainLayout->setContentsMargins(0, 0, 0, 0); QHBoxLayout *titleLayout = new QHBoxLayout(); titleLayout->setSpacing(0); titleLayout->setContentsMargins(10, 0, 0, 0); m_titleBar = new QWidget(this); m_titleBar->setFixedHeight(50); m_titleBar->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); m_titleBar->setLayout(titleLayout); m_logoIcon = new DLabel(this); m_logoIcon->setFixedSize(QSize(m_IconWidth, m_IconHeight)); m_logoIcon->setFocusPolicy(Qt::NoFocus); m_logoIcon->setAttribute(Qt::WA_TransparentForMouseEvents); m_logoIcon->setPixmap(QIcon::fromTheme("dialog-warning").pixmap(QSize(m_IconWidth, m_IconHeight))); m_closeButton = new DWindowCloseButton(this); m_closeButton->setFocusPolicy(Qt::NoFocus); m_closeButton->setIconSize(QSize(50, 50)); m_titleText = new DLabel(this); m_titleText->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred); m_titleText->setAlignment(Qt::AlignCenter); DFontSizeManager::instance()->bind(m_titleText, DFontSizeManager::T6); titleLayout->addWidget(m_logoIcon, 0, Qt::AlignLeft | Qt::AlignVCenter); titleLayout->addWidget(m_titleText); titleLayout->addWidget(m_closeButton, 0, Qt::AlignRight | Qt::AlignVCenter); //Dialog content m_contentLayout = new QVBoxLayout(); m_contentLayout->setSpacing(0); m_contentLayout->setContentsMargins(0, 0, 0, 0); m_content = new QWidget(this); m_content->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); m_content->setLayout(m_contentLayout); mainLayout->addWidget(m_titleBar); mainLayout->addWidget(m_content); setLayout(mainLayout); } void WarnningDlg::initContentLayout() { QVBoxLayout *mainLayout = new QVBoxLayout(); mainLayout->setSpacing(0); mainLayout->setContentsMargins(10, 0, 10, 10); QWidget *mainFrame = new QWidget(this); mainFrame->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); m_operateTypeName = new DLabel(this); m_operateTypeName->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); DFontSizeManager::instance()->bind(m_operateTypeName, DFontSizeManager::T6, QFont::Medium); DPalette palette = DApplicationHelper::instance()->palette(m_operateTypeName); palette.setBrush(DPalette::WindowText, palette.color(DPalette::BrightText)); m_operateTypeName->setPalette(palette); m_tipInfo = new DLabel(this); m_tipInfo->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); DFontSizeManager::instance()->bind(m_tipInfo, DFontSizeManager::T6, QFont::Medium); DPalette patitInfo = DApplicationHelper::instance()->palette(m_tipInfo); patitInfo.setBrush(DPalette::WindowText, patitInfo.color(DPalette::BrightText)); m_tipInfo->setPalette(patitInfo); QHBoxLayout *actionBarLayout = new QHBoxLayout(); actionBarLayout->setSpacing(0); actionBarLayout->setContentsMargins(0, 0, 0, 0); m_confirmBtn = new DPushButton(this); m_confirmBtn->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Fixed); m_confirmBtn->setText(QObject::tr("OK")); Utils::setSpaceInWord(m_confirmBtn); actionBarLayout->addWidget(m_confirmBtn); mainLayout->addWidget(m_operateTypeName, 0, Qt::AlignCenter); mainLayout->addSpacing(8); mainLayout->addWidget(m_tipInfo, 0, Qt::AlignCenter); mainLayout->addStretch(); mainLayout->addLayout(actionBarLayout); mainFrame->setLayout(mainLayout); addContent(mainFrame); } void WarnningDlg::setDialogFrameSize(int width, int height) { setFixedSize(width, height); } void WarnningDlg::initConnections() { connect(m_confirmBtn, &DPushButton::clicked, this, [ = ]() { qDebug() << "confirmBtnClicked"; close(); }); connect(m_closeButton, &DIconButton::clicked, this, [ = ]() { qDebug() << "dialog close Btn Clicked"; close(); }); } void WarnningDlg::closeEvent(QCloseEvent *event) { Q_UNUSED(event) done(-1); Q_EMIT closed(); } void WarnningDlg::setTitle(const QString &title) { if (nullptr != m_titleText) { m_titleText->setText(title); } } QLayout *WarnningDlg::getContentLayout() { return m_contentLayout; } void WarnningDlg::addContent(QWidget *content) { Q_ASSERT(nullptr != getContentLayout()); getContentLayout()->addWidget(content); } void WarnningDlg::setIconPixmap(const QPixmap &iconPixmap) { if (nullptr != m_logoIcon) { m_logoIcon->setPixmap(iconPixmap); } } void WarnningDlg::setOperatTypeName(const QString &strName) { m_operateTypeName->setText(strName); } void WarnningDlg::setTipInfo(const QString &strInfo) { m_tipInfo->setText(strInfo); } void WarnningDlg::setOKBtnText(const QString &strConfirm) { m_confirmBtn->setText(strConfirm); } deepin-terminal-5.2.11/src/views/warnningdlg.h000066400000000000000000000027661370157770500213130ustar00rootroot00000000000000#ifndef WARNNINGDLG_H #define WARNNINGDLG_H #include #include #include #include #include #include #include #include DWIDGET_USE_NAMESPACE class WarnningDlg : public DAbstractDialog { Q_OBJECT public: explicit WarnningDlg(QWidget *parent = nullptr); void addContent(QWidget *content); void setIconPixmap(const QPixmap &iconPixmap); void setTitle(const QString &title); void setOperatTypeName(const QString &strName); void setTipInfo(const QString &strInfo); void setOKBtnText(const QString &strConfirm); void setDialogFrameSize(int width, int height); protected: QLayout *getContentLayout(); void closeEvent(QCloseEvent *event) override; private: void initUI(); void initContentLayout(); void initConnections(); // 第一行:logo+title+close QWidget *m_titleBar = nullptr; DLabel *m_logoIcon = nullptr; DLabel *m_titleText = nullptr; DWindowCloseButton *m_closeButton = nullptr; // 第二行:content : operateTypeName + tip QWidget *m_content = nullptr; QVBoxLayout *m_contentLayout = nullptr; DLabel *m_operateTypeName = nullptr; DLabel *m_tipInfo = nullptr; // 第三行: m_confirmBtn DPushButton *m_confirmBtn = nullptr; int m_dlgHeight = 160; int m_dlgWidth = 380; int m_IconHeight = 32; int m_IconWidth = 32; signals: void closed(); }; #endif // OPERATIONCONFIRMDLG_H deepin-terminal-5.2.11/translations/000077500000000000000000000000001370157770500174125ustar00rootroot00000000000000deepin-terminal-5.2.11/translations/deepin-terminal.ts000066400000000000000000001241711370157770500230450ustar00rootroot00000000000000 CustomCommandList Are you sure you want to delete %1? CustomCommandOptDlg Name: Command: Shortcuts: Required Add Command Edit Command Delete Command Cancel Add Save Please enter a name Please enter a command The name already exists, please input another one. OK CustomCommandPanel Add Command CustomCommandPlugin Custom commands CustomCommandSearchRstPanel Search DSettingsDialog This shortcut conflicts with %1 MainWindow New window Settings Cancel Close Select workspace Type path to download file QObject OK Copy on select Cursor blink Cursor style Scroll on keystroke Scroll on output Hide Quake window after losing focus Blur background Use on starting Font Font size Opacity Advanced Cursor Scroll Window Basic Interface Shortcuts Others Terminal Workspace Custom commands Display shortcuts Remote management Rename title Fullscreen Copy Default size Paste Search Select all Jump to next command Jump to previous command Zoom in Zoom out Close other windows Close other workspaces Close window Close workspace Horizontal split New workspace Next workspace Previous workspace Select left window Select lower window Select right window Select upper window Vertical split Find Cancel Delete please set another one. Terminal is an advanced terminal emulator with workspace, multiple windows, remote management, quake mode and other features. Select file to upload Upload Programs are still running in terminal Are you sure you want to exit? Exit Close this terminal? There is still a process running in this terminal. Closing the terminal will kill it. There are still %1 processes running in this terminal. Closing the terminal will kill all of them. Close this window? There are still processes running in this window. Closing the window will kill all of them. Select a directory to save the file Are you sure you want to uninstall it? Are you sure you want to uninstall this application? You will not be able to use Terminal any longer. Click on Add to make this shortcut effective immediately Replace Execute a command in the terminal Run script string in the terminal Set the work directory Set the window mode on starting Run in quake mode Keep terminal open when command finishes The name should be no more than 32 characters Select Select the private key file Confirm Select workspace RemoteManagementPanel Add Server RemoteManagementPlugn Remote management Make sure that rz and sz commands have been installed in the server before right clicking to upload and download files. RemoteManagementSearchPanel Search ServerConfigList %1 server Delete Server Are you sure you want to delete %1? ServerConfigOptDlg Advanced options Add Server Server name: Required Address: Port: Username: Password: Certificate: Group: Path: Command: Encoding: Backspace key: Delete key: Delete server Cancel Add Edit Server tty Please enter a server name Please enter an IP address Please enter a port Please enter a username Save ascii-del auto control-h escape-sequence The server name already exists, please input another one. Service OK Settings Split screen Fullscreen Normal window Maximum ShortcutManager The shortcut %1 is invalid, The shortcut %1 was already in use, TabBar Close workspace Close other workspaces TermInputDialog Rename title Cancel Confirm TermWidget Rename title Copy Paste Open Open in file manager Horizontal split Vertical split Close window Close other windows New workspace Exit fullscreen Fullscreen Find Search Encoding Custom commands Remote management Upload file Download file Settings Utils Cancel Close OK deepin-terminal-5.2.11/translations/deepin-terminal_zh_CN.ts000066400000000000000000001234361370157770500241310ustar00rootroot00000000000000 CustomCommandList Are you sure you want to delete %1? 您确定要删除 %1 吗? CustomCommandOptDlg Name: 名称: Command: 命令: Shortcuts: 快捷键: Required 必填 Add Command 添加命令 Edit Command 编辑命令 Delete Command 删除命令 Cancel 取消 Add 添加 Save 保存 Please enter a name 请输入名称 Please enter a command 请输入命令 The name already exists, 该名称已存在, please input another one. 请重新输入 OK 确定 CustomCommandPanel Add Command 添加命令 CustomCommandPlugin Custom commands 自定义命令 CustomCommandSearchRstPanel Search 搜索 DSettingsDialog This shortcut conflicts with %1 此快捷键与%1冲突 MainWindow New window 新建窗口 Settings 设置 Cancel 取消 Close 关闭 Select workspace 选择工作区 Type path to download file 请输入下载文件的路径 QObject OK 确定 Copy on select 选中文字时自动复制到剪切板 Cursor blink 光标闪烁 Cursor style 光标风格 Scroll on keystroke 按键时滚动 Scroll on output 输出时滚动 Hide Quake window after losing focus 丢失焦点后隐藏雷神窗口 Blur background 背景模糊 Use on starting 启动时使用 Font 字体 Font size 字体大小 Opacity 透明度 Advanced 高级设置 Cursor 光标 Scroll 滚动 Window 窗口 Basic 基础设置 Interface 界面 Shortcuts 快捷键 Others 其他 Terminal 终端 Workspace 工作区 Custom commands 自定义命令 Display shortcuts 显示快捷键 Remote management 远程管理 Rename title 重命名标题 Fullscreen 全屏 Copy 复制 Default size 默认大小 Paste 粘贴 Search 搜索 Select all 全选 Jump to next command 跳转到下一个命令 Jump to previous command 跳转到上一个命令 Zoom in 放大 Zoom out 缩小 Close other windows 关闭其他窗口 Close other workspaces 关闭其他工作区 Close window 关闭窗口 Close workspace 关闭工作区 Horizontal split 横向分屏 New workspace 新建工作区 Next workspace 下一个工作区 Previous workspace 上一个工作区 Select left window 选择左边的窗口 Select lower window 选择下面的窗口 Select right window 选择右边的窗口 Select upper window 选择上面的窗口 Vertical split 纵向分屏 Find 查找 Cancel 取消 Delete 删除 please set another one. 请重新设置 Terminal is an advanced terminal emulator with workspace, multiple windows, remote management, quake mode and other features. 终端是⼀款集⼯作区、多窗⼝、远程管理、雷神模式等功能的⾼级终端模拟器。 Select file to upload 选择要上传的文件 Upload 上传 Programs are still running in terminal 终端仍然有程序在运行 Are you sure you want to exit? 您确定要退出吗? Exit 退出 Close this terminal? 关闭此终端? There is still a process running in this terminal. Closing the terminal will kill it. 该终端中仍然有1个进程在运行,关闭终端将杀死进程。 There are still %1 processes running in this terminal. Closing the terminal will kill all of them. 该终端中仍然有%1个进程在运行,关闭终端将杀死进程。 Close this window? 关闭这个窗口? There are still processes running in this window. Closing the window will kill all of them. 窗口内一些终端仍然有进程在运行,关闭窗口会杀死所有进程。 Select a directory to save the file 选择下载文件的保存目录 Are you sure you want to uninstall it? 您确定要卸载它吗? Are you sure you want to uninstall this application? 您确定要卸载终端吗? You will not be able to use Terminal any longer. 卸载后将无法再使用该应用。 Click on Add to make this shortcut effective immediately 点击添加使这个快捷键立即生效 Replace 替换 Execute a command in the terminal 在终端中运⾏⼀个程序 Run script string in the terminal 在终端中允许脚本字符串 Set the work directory 设置终端的启动⽬录 Set the window mode on starting 设置终端开启的模式 Run in quake mode 设置终端以雷神模式启动 Keep terminal open when command finishes 设置终端显示命令或脚本执行后的结果 The name should be no more than 32 characters 名称长度不得超过32个字符 Select 选择 Select the private key file 选择私钥文件 Confirm 确定 Select workspace 选择工作区 RemoteManagementPanel Add Server 添加服务器 RemoteManagementPlugn Remote management 远程管理 Make sure that rz and sz commands have been installed in the server before right clicking to upload and download files. 在您使⽤右键菜单进⾏上传和下载⽂件之前, 请先确保服务器已经安装了 rz和sz 命令。 RemoteManagementSearchPanel Search 搜索 ServerConfigList %1 server %1服务器 Delete Server 删除服务器 Are you sure you want to delete %1? 您确定要删除 %1 吗? ServerConfigOptDlg Advanced options 高级选项 Add Server 添加服务器 Server name: 服务器名: Required 必填 Address: 地址: Port: 端口: Username: 用户名: Password: 密码: Certificate: 证书: Group: 分组: Path: 路径: Command: 命令: Encoding: 编码: Backspace key: 退格键: Delete key: 删除键: Delete server 删除服务器 Cancel 取消 Add 添加 Edit Server 编辑服务器 tty tty Please enter a server name 请输入服务器名称 Please enter an IP address 请输入IP地址 Please enter a port 请输入端口 Please enter a username 请输入用户名 Save 保存 ascii-del ascii-del auto auto control-h control-h escape-sequence escape-sequence The server name already exists, 该服务器名已存在, please input another one. 请重新输入 Service OK 确定 Settings Split screen 分屏 Fullscreen 全屏 Normal window 正常窗口 Maximum 最⼤化 ShortcutManager The shortcut %1 is invalid, %1为无效快捷键, The shortcut %1 was already in use, 快捷键%1已被占用, TabBar Close workspace 关闭工作区 Close other workspaces 关闭其他工作区 TermInputDialog Rename title 重命名标题 Cancel 取消 Confirm 确定 TermWidget Rename title 重命名标题 Copy 复制 Paste 粘贴 Open 打开 Open in file manager 在文件管理器中打开 Horizontal split 横向分屏 Vertical split 纵向分屏 Close window 关闭窗口 Close other windows 关闭其他窗口 New workspace 新建工作区 Exit fullscreen 退出全屏 Fullscreen 全屏 Find 查找 Search 搜索 Encoding 编码 Custom commands 自定义命令 Remote management 远程管理 Upload file 上传文件 Download file 下载文件 Settings 设置 Utils Cancel 取消 Close 关闭 OK 确定 deepin-terminal-5.2.11/translations/desktop/000077500000000000000000000000001370157770500210635ustar00rootroot00000000000000deepin-terminal-5.2.11/translations/desktop/desktop.ts000066400000000000000000000017751370157770500231160ustar00rootroot00000000000000desktopDeepin TerminalDeepin TerminalNew WindowNew WindowQuake TerminalQuake TerminalTerminalTerminalUse the command lineUse the command lineshell;prompt;command;commandline;shell;prompt;command;commandline;deepin-terminal-5.2.11/translations/desktop/desktop_af.ts000066400000000000000000000016731370157770500235610ustar00rootroot00000000000000desktopDeepin TerminalNew WindowQuake TerminalTerminalTerminaalUse the command lineshell;prompt;command;commandline;deepin-terminal-5.2.11/translations/desktop/desktop_am_ET.ts000066400000000000000000000020041370157770500241450ustar00rootroot00000000000000desktopDeepin Terminalየ ዲፕኢን ተርሚናልNew WindowQuake TerminalTerminalተርሚናልUse the command lineየ ትእዛዝ መስመር ይጠቀሙshell;prompt;command;commandline;deepin-terminal-5.2.11/translations/desktop/desktop_ar.ts000066400000000000000000000020511370157770500235640ustar00rootroot00000000000000desktopDeepin Terminalطرفية ديبينNew Windowنافذة جديدةQuake Terminalطرفية كواكTerminalالطرفيةUse the command lineاستخدام سطر الأوامرshell;prompt;command;commandline;shell;prompt;command;commandline;deepin-terminal-5.2.11/translations/desktop/desktop_ast.ts000066400000000000000000000020261370157770500237530ustar00rootroot00000000000000desktopDeepin TerminalDeepin TerminalNew WindowVentana nuevaQuake TerminalTerminal QuakeTerminalTerminalUse the command lineUsa la llinia de comandosshell;prompt;command;commandline;shell;comandu;llinia;llinia de comandos;comandos;deepin-terminal-5.2.11/translations/desktop/desktop_az.ts000066400000000000000000000017351370157770500236040ustar00rootroot00000000000000desktopDeepin TerminalDeepin TerminalNew WindowQuake TerminalTerminalTerminalUse the command lineƏmr sətirindən istifadə etshell;prompt;command;commandline;deepin-terminal-5.2.11/translations/desktop/desktop_bg.ts000066400000000000000000000020771370157770500235620ustar00rootroot00000000000000desktopDeepin TerminalDeepin терминалNew WindowНов прозорецQuake TerminalQuake терминалTerminalТерминалUse the command lineИзползване на команден редshell;prompt;command;commandline;shell;prompt;command;commandline;deepin-terminal-5.2.11/translations/desktop/desktop_bn.ts000066400000000000000000000017151370157770500235670ustar00rootroot00000000000000desktopDeepin TerminalNew WindowQuake TerminalTerminalপ্রান্তিকUse the command lineshell;prompt;command;commandline;deepin-terminal-5.2.11/translations/desktop/desktop_ca.ts000066400000000000000000000020701370157770500235460ustar00rootroot00000000000000desktopDeepin TerminalTerminal del Deepin New WindowFinestra novaQuake TerminalTerminal QuakeTerminalTerminalUse the command lineUseu la línia d'ordresshell;prompt;command;commandline;shell;intèrpret;intèrpret d'ordres;ordres;ordre;línia d'ordres;deepin-terminal-5.2.11/translations/desktop/desktop_cs.ts000066400000000000000000000020311370157770500235650ustar00rootroot00000000000000desktopDeepin TerminalTerminálNew WindowNové oknoQuake TerminalVysouvací terminál (quake)TerminalTerminálUse the command linePoužít příkazový řádekshell;prompt;command;commandline;shell;prompt;příkaz;příkazový řádek;deepin-terminal-5.2.11/translations/desktop/desktop_da.ts000066400000000000000000000017761370157770500235630ustar00rootroot00000000000000desktopDeepin TerminalDeepin terminalNew WindowNyt vindueQuake TerminalQuake-terminalTerminalTerminalUse the command lineBrug kommandolinjenshell;prompt;command;commandline;skal;prompt;kommando;kommandolinje;deepin-terminal-5.2.11/translations/desktop/desktop_de.ts000066400000000000000000000020021370157770500235460ustar00rootroot00000000000000desktopDeepin TerminalDeepin TerminalNew WindowNeues FensterQuake TerminalQuake TerminalTerminalTerminalUse the command lineKommandozeile benutzenshell;prompt;command;commandline;shell;prompt;command;commandline;deepin-terminal-5.2.11/translations/desktop/desktop_el.ts000066400000000000000000000021661370157770500235710ustar00rootroot00000000000000desktopDeepin TerminalDeepin TερματικόNew WindowΝέο παράθυροQuake TerminalΤερματικό "Quake"TerminalΤερματικόUse the command lineΧρήση της γραμμής εντολώνshell;prompt;command;commandline;κέλυφος;προτροπή;εντολή;γραμμή-εντολών;deepin-terminal-5.2.11/translations/desktop/desktop_en_AU.ts000066400000000000000000000017261370157770500241610ustar00rootroot00000000000000desktopDeepin TerminalDeepin TerminalNew WindowQuake TerminalTerminalTerminalUse the command lineUse the command lineshell;prompt;command;commandline;deepin-terminal-5.2.11/translations/desktop/desktop_eo.ts000066400000000000000000000017231370157770500235720ustar00rootroot00000000000000desktopDeepin TerminalDeepin terminaloNew WindowQuake TerminalTerminalTerminaloUse the command lineUzi la komandlinioshell;prompt;command;commandline;deepin-terminal-5.2.11/translations/desktop/desktop_es.ts000066400000000000000000000020361370157770500235740ustar00rootroot00000000000000desktopDeepin TerminalTerminal DeepinNew WindowNueva ventanaQuake TerminalTerminal QuakeTerminalTerminal Use the command lineUsar la línea de comandoshell;prompt;command;commandline;shell;prompt;command;comando;commandline;lineadecomandos;deepin-terminal-5.2.11/translations/desktop/desktop_es_419.ts000066400000000000000000000020231370157770500241650ustar00rootroot00000000000000desktopDeepin TerminalTerminal DeepinNew WindowNueva ventanaQuake TerminalTerminal en modo QuakeTerminalTerminal Use the command lineUsar la línea de comandosshell;prompt;command;commandline;shell;prompt;command;commandline;deepin-terminal-5.2.11/translations/desktop/desktop_fa.ts000066400000000000000000000021051370157770500235500ustar00rootroot00000000000000desktopDeepin Terminalترمینال دیپینNew Windowپنجره جدیدQuake Terminalترمینال QuakeTerminalترمینالUse the command lineاستفاده از خط فرمانshell;prompt;command;commandline;پوسته ؛ سریع ؛ فرمان ؛ خط فرمان ؛deepin-terminal-5.2.11/translations/desktop/desktop_fi.ts000066400000000000000000000020171370157770500235620ustar00rootroot00000000000000desktopDeepin TerminalDeepin pääteNew WindowUusi ikkunaQuake TerminalQuake pääteTerminalPääteUse the command lineKäytä komentoriviäshell;prompt;command;commandline;shell;kehote;komento;komentorivi;pääte;terminaali;deepin-terminal-5.2.11/translations/desktop/desktop_fil.ts000066400000000000000000000017021370157770500237360ustar00rootroot00000000000000desktopDeepin TerminalDeepin TerminalNew WindowQuake TerminalTerminalUse the command lineshell;prompt;command;commandline;deepin-terminal-5.2.11/translations/desktop/desktop_fr.ts000066400000000000000000000020151370157770500235710ustar00rootroot00000000000000desktopDeepin TerminalDeepin TerminalNew WindowNouvelle fenêtreQuake TerminalTerminal QuakeTerminalTerminalUse the command lineUtiliser la ligne de commandeshell;prompt;command;commandline;shell;prompt;command;commandline;deepin-terminal-5.2.11/translations/desktop/desktop_gl_ES.ts000066400000000000000000000017271370157770500241640ustar00rootroot00000000000000desktopDeepin TerminalTerminalNew WindowQuake TerminalTerminalTerminalUse the command lineEmpregar a liña de comandosshell;prompt;command;commandline;deepin-terminal-5.2.11/translations/desktop/desktop_he.ts000066400000000000000000000017371370157770500235700ustar00rootroot00000000000000desktopDeepin Terminalמסוף DeepinNew WindowQuake TerminalTerminalמסוףUse the command lineהשתמש בשורת פקודהshell;prompt;command;commandline;deepin-terminal-5.2.11/translations/desktop/desktop_hi_IN.ts000066400000000000000000000020261370157770500241520ustar00rootroot00000000000000desktopDeepin Terminalडीपइन छोरNew WindowQuake TerminalTerminalटर्मिनलUse the command lineआदेश रेखा का उपयोग करेंshell;prompt;command;commandline;deepin-terminal-5.2.11/translations/desktop/desktop_hr.ts000066400000000000000000000017451370157770500236040ustar00rootroot00000000000000desktopDeepin TerminalDeepin terminalNew WindowNovi prozorQuake TerminalQuake terminalTerminalTerminalUse the command lineKoristi naredbeni redakshell;prompt;command;commandline;deepin-terminal-5.2.11/translations/desktop/desktop_hu.ts000066400000000000000000000020001370157770500235700ustar00rootroot00000000000000desktopDeepin TerminalDeepin TerminálNew WindowÚj ablakQuake TerminalQuake TerminálTerminalTerminálUse the command line Parancssor használatashell;prompt;command;commandline;shell;prompt;parancs;parancssordeepin-terminal-5.2.11/translations/desktop/desktop_hy.ts000066400000000000000000000017661370157770500236160ustar00rootroot00000000000000desktopDeepin TerminalDeepin ՏերմինալNew WindowQuake TerminalTerminalUse the command lineՕգտագործել հրամանների տողըshell;prompt;command;commandline;deepin-terminal-5.2.11/translations/desktop/desktop_id.ts000066400000000000000000000020041370157770500235540ustar00rootroot00000000000000desktopDeepin TerminalTerminal DeepinNew WindowJendela BaruQuake TerminalTerminal QuakeTerminalTerminalUse the command lineGunakan baris perintahshell;prompt;command;commandline;shell;prompt;perintah;barisperintah;deepin-terminal-5.2.11/translations/desktop/desktop_it.ts000066400000000000000000000020521370157770500235770ustar00rootroot00000000000000desktopDeepin TerminalTerminale di DeepinNew WindowNuova finestraQuake TerminalTerminale in primo pianoTerminalTerminaleUse the command lineUsa linea di comandoshell;prompt;command;commandline;shell;prompt;command;commandline;terminale;cmd;script;bash;deepin-terminal-5.2.11/translations/desktop/desktop_ja.ts000066400000000000000000000020401370157770500235520ustar00rootroot00000000000000desktopDeepin TerminalDeepin ターミナルNew Window新しいウィンドウQuake Terminalターミナルを振動させるTerminalターミナルUse the command lineコマンドラインを使用するshell;prompt;command;commandline;deepin-terminal-5.2.11/translations/desktop/desktop_ko.ts000066400000000000000000000020401370157770500235710ustar00rootroot00000000000000desktopDeepin TerminalDeepin 터미널New Window새 창Quake Terminal퀘이크 터미널Terminal터미널Use the command line명령 행 사용shell;prompt;command;commandline;shell;prompt;command;commandline;쉘;프롬프트;명령;명령행;deepin-terminal-5.2.11/translations/desktop/desktop_lt.ts000066400000000000000000000020501370157770500236000ustar00rootroot00000000000000desktopDeepin TerminalDeepin terminalasNew WindowNaujas langasQuake TerminalQuake terminalasTerminalTerminalasUse the command lineNaudoti komandų eilutęshell;prompt;command;commandline;apvalkalas;užklausa;komanda;komandų eilutė;eilutė;komandos;deepin-terminal-5.2.11/translations/desktop/desktop_ml.ts000066400000000000000000000020401370157770500235700ustar00rootroot00000000000000desktopDeepin Terminalഡീപിൻ ടെർമിനൽNew WindowQuake TerminalTerminalടെർമിനൽUse the command lineകമാൻഡ് ലൈൻ ഉപയോഗിക്കുകshell;prompt;command;commandline;deepin-terminal-5.2.11/translations/desktop/desktop_mn.ts000066400000000000000000000020331370157770500235740ustar00rootroot00000000000000desktopDeepin TerminalДээпин ТерминалNew WindowШинэ ЦонхQuake TerminalКуаке ТерминалTerminalТерминалUse the command lineКомманд мѳр ашиглахshell;prompt;command;commandline;deepin-terminal-5.2.11/translations/desktop/desktop_ms.ts000066400000000000000000000020021370157770500235750ustar00rootroot00000000000000desktopDeepin TerminalTerminal DeepinNew WindowTerminal BaharuQuake TerminalTerminal QuakeTerminalTerminalUse the command lineguna baris perintahshell;prompt;command;commandline;shell;prom;perintah;barisperintah;deepin-terminal-5.2.11/translations/desktop/desktop_nb.ts000066400000000000000000000017221370157770500235650ustar00rootroot00000000000000desktopDeepin TerminalDeepin terminalNew WindowQuake TerminalTerminalTerminalUse the command lineBruk kommandolinjenshell;prompt;command;commandline;deepin-terminal-5.2.11/translations/desktop/desktop_ne.ts000066400000000000000000000017071370157770500235730ustar00rootroot00000000000000desktopDeepin TerminalNew WindowQuake TerminalTerminalटर्मिनलUse the command lineshell;prompt;command;commandline;deepin-terminal-5.2.11/translations/desktop/desktop_nl.ts000066400000000000000000000020071370157770500235740ustar00rootroot00000000000000desktopDeepin TerminalDeepin TerminalNew WindowNieuw vensterQuake TerminalQuake-terminalTerminalTerminalUse the command lineGebruik de opdrachtregelshell;prompt;command;commandline;shell;prompt;opdracht;opdrachtregel;deepin-terminal-5.2.11/translations/desktop/desktop_pam.ts000066400000000000000000000017251370157770500237460ustar00rootroot00000000000000desktopDeepin TerminalDeepin TerminalNew WindowQuake TerminalTerminalUse the command lineGamitan ing command lineshell;prompt;command;commandline;deepin-terminal-5.2.11/translations/desktop/desktop_pl.ts000066400000000000000000000020121370157770500235720ustar00rootroot00000000000000desktopDeepin TerminalTerminal DeepinNew WindowNowe oknoQuake TerminalTerminal QuakeTerminalTerminalUse the command lineUżyj wiersza poleceńshell;prompt;command;commandline;powłoka;zapytanie;polecenie;wiersz;poleceń;deepin-terminal-5.2.11/translations/desktop/desktop_pt.ts000066400000000000000000000020121370157770500236020ustar00rootroot00000000000000desktopDeepin TerminalTerminal DeepinNew WindowNova janelaQuake TerminalTerminal deslizanteTerminalTerminalUse the command lineUtilize a linha de comandosshell;prompt;command;commandline;shell;prompt;comando;commandline;deepin-terminal-5.2.11/translations/desktop/desktop_pt_BR.ts000066400000000000000000000020041370157770500241660ustar00rootroot00000000000000desktopDeepin TerminalTerminal DeepinNew WindowNova JanelaQuake TerminalTerminal QuakeTerminalTerminalUse the command lineUsar a linha de comandoshell;prompt;command;commandline;shell;prompt;command;commandline;deepin-terminal-5.2.11/translations/desktop/desktop_ro.ts000066400000000000000000000020211370157770500235770ustar00rootroot00000000000000desktopDeepin TerminalTerminalul DeepinNew WindowFereastră NouăQuake TerminalTerminal QuakeTerminalTerminalulUse the command lineUtilizare linia de comandăshell;prompt;command;commandline;shell;prompt;comandă;liniecomandă;deepin-terminal-5.2.11/translations/desktop/desktop_ru.ts000066400000000000000000000021231370157770500236100ustar00rootroot00000000000000desktopDeepin Terminal Терминал Deepin New WindowНовое ОкноQuake TerminalВыпадающий ТерминалTerminalТерминалUse the command lineИспользовать командную строкуshell;prompt;command;commandline;shell;prompt;command;commandline;deepin-terminal-5.2.11/translations/desktop/desktop_sk.ts000066400000000000000000000020071370157770500236000ustar00rootroot00000000000000desktopDeepin TerminalDeepin TerminálNew WindowNové oknoQuake TerminalQuake terminálTerminalTerminálUse the command linePoužiť príkazový riadokshell;prompt;command;commandline;shell;prompt;command;commandline;deepin-terminal-5.2.11/translations/desktop/desktop_sl.ts000066400000000000000000000017251370157770500236070ustar00rootroot00000000000000desktopDeepin TerminalTerminal DeepinNew WindowQuake TerminalTerminalTerminalUse the command lineUporabi ukazno vrsticoshell;prompt;command;commandline;deepin-terminal-5.2.11/translations/desktop/desktop_sq.ts000066400000000000000000000020051370157770500236040ustar00rootroot00000000000000desktopDeepin TerminalTerminali DeepinNew WindowDritare e ReQuake TerminalTerminal QuakeTerminalTerminalUse the command linePërdorni rresht urdhrashshell;prompt;command;commandline;shell;prompt;command;commandline;deepin-terminal-5.2.11/translations/desktop/desktop_sr.ts000066400000000000000000000021501370157770500236060ustar00rootroot00000000000000desktopDeepin TerminalДипин ТерминалNew WindowНови прозорQuake TerminalСпуштајући терминалTerminalТерминалUse the command lineКористите командну линијуshell;prompt;command;commandline;shell;prompt;команда;командна линија;deepin-terminal-5.2.11/translations/desktop/desktop_sv.ts000066400000000000000000000020011370157770500236050ustar00rootroot00000000000000desktopDeepin TerminalDeepin-terminalNew WindowNytt fönsterQuake TerminalQuake TerminalTerminalTerminalUse the command lineAnvänd kommandoradenshell;prompt;command;commandline;shell;prompt;command;commandline;deepin-terminal-5.2.11/translations/desktop/desktop_ta.ts000066400000000000000000000017071370157770500235750ustar00rootroot00000000000000desktopDeepin TerminalNew WindowQuake TerminalTerminalமுனையம்Use the command lineshell;prompt;command;commandline;deepin-terminal-5.2.11/translations/desktop/desktop_tr.ts000066400000000000000000000020351370157770500236110ustar00rootroot00000000000000desktopDeepin TerminalDeepin UçbirimNew WindowYeni PencereQuake TerminalQuake UçbirimTerminalUçbirimUse the command lineKomut satırını kullanshell;prompt;command;commandline;shell;prompt;command;commandline;kabuk;komut;komutsatırı;deepin-terminal-5.2.11/translations/desktop/desktop_ug.ts000066400000000000000000000017261370157770500236050ustar00rootroot00000000000000desktopDeepin TerminalDeepin تېرمىنالىNew WindowQuake TerminalTerminalتېرمىنالUse the command lineshell;prompt;command;commandline;deepin-terminal-5.2.11/translations/desktop/desktop_uk.ts000066400000000000000000000022151370157770500236030ustar00rootroot00000000000000desktopDeepin TerminalТермінал DeepinNew WindowНове вікноQuake TerminalТермінал QuakeTerminalТерміналUse the command lineВикористовувати командний рядокshell;prompt;command;commandline;shell;prompt;command;commandline;оболонка;запит;команда;командна;рядок;deepin-terminal-5.2.11/translations/desktop/desktop_vi.ts000066400000000000000000000017111370157770500236020ustar00rootroot00000000000000desktopDeepin TerminalDeepin TerminalNew WindowQuake TerminalTerminalĐầu cuốiUse the command lineshell;prompt;command;commandline;deepin-terminal-5.2.11/translations/desktop/desktop_zh_CN.ts000066400000000000000000000017611370157770500241720ustar00rootroot00000000000000desktopDeepin Terminal终端New Window新建窗口Quake Terminal雷神终端Terminal终端Use the command line使用命令行shell;prompt;command;commandline;shell;prompt;command;commandline; deepin-terminal-5.2.11/translations/desktop/desktop_zh_HK.ts000066400000000000000000000017151370157770500241730ustar00rootroot00000000000000desktopDeepin Terminal終端機New WindowQuake TerminalTerminal終端機Use the command line使用命令列shell;prompt;command;commandline; deepin-terminal-5.2.11/translations/desktop/desktop_zh_TW.ts000066400000000000000000000020361370157770500242200ustar00rootroot00000000000000desktopDeepin Terminal終端器New Window開新視窗Quake Terminal雷神模式終端器Terminal終端機Use the command line使用命令列介面shell;prompt;command;commandline;shell;prompt;command;commandline;提示;指令;指令列;