id
int64
0
755k
file_name
stringlengths
3
109
file_path
stringlengths
13
185
content
stringlengths
31
9.38M
size
int64
31
9.38M
language
stringclasses
1 value
extension
stringclasses
11 values
total_lines
int64
1
340k
avg_line_length
float64
2.18
149k
max_line_length
int64
7
2.22M
alphanum_fraction
float64
0
1
repo_name
stringlengths
6
65
repo_stars
int64
100
47.3k
repo_forks
int64
0
12k
repo_open_issues
int64
0
3.4k
repo_license
stringclasses
9 values
repo_extraction_date
stringclasses
92 values
exact_duplicates_redpajama
bool
2 classes
near_duplicates_redpajama
bool
2 classes
exact_duplicates_githubcode
bool
2 classes
exact_duplicates_stackv2
bool
1 class
exact_duplicates_stackv1
bool
2 classes
near_duplicates_githubcode
bool
2 classes
near_duplicates_stackv1
bool
2 classes
near_duplicates_stackv2
bool
1 class
25,087
browse_mdns.hpp
badaix_snapcast/client/browseZeroConf/browse_mdns.hpp
/*** This file is part of snapcast Copyright (C) 2014-2024 Johannes Pohl This program is free software: you can 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 <http://www.gnu.org/licenses/>. ***/ #pragma once // standard headers #include <cstdint> #include <string> enum IPVersion { IPv4 = 0, IPv6 = 1 }; struct mDNSResult { mDNSResult() : ip_version(IPv4), iface_idx(0), port(0), valid(false) { } IPVersion ip_version; int iface_idx; std::string ip; std::string host; uint16_t port; bool valid; }; class BrowsemDNS { public: virtual bool browse(const std::string& serviceName, mDNSResult& result, int timeout) = 0; }; #if defined(HAS_AVAHI) #include "browse_avahi.hpp" using BrowseZeroConf = BrowseAvahi; #elif defined(HAS_BONJOUR) #include "browse_bonjour.hpp" using BrowseZeroConf = BrowseBonjour; #endif
1,408
C++
.h
47
26.680851
93
0.733333
badaix/snapcast
6,105
452
82
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
25,088
flac_decoder.hpp
badaix_snapcast/client/decoder/flac_decoder.hpp
/*** This file is part of snapcast Copyright (C) 2014-2024 Johannes Pohl This program is free software: you can 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 <http://www.gnu.org/licenses/>. ***/ #pragma once // local headers #include "decoder.hpp" // 3rd party headers #include <FLAC/stream_decoder.h> // standard headers #include <memory> namespace decoder { struct CacheInfo { CacheInfo() : sampleRate_(0) { reset(); } void reset() { isCachedChunk_ = true; cachedBlocks_ = 0; } bool isCachedChunk_; size_t cachedBlocks_; size_t sampleRate_; }; class FlacDecoder : public Decoder { public: FlacDecoder(); ~FlacDecoder() override; bool decode(msg::PcmChunk* chunk) override; SampleFormat setHeader(msg::CodecHeader* chunk) override; CacheInfo cacheInfo_; std::unique_ptr<FLAC__StreamDecoderErrorStatus> lastError_; }; } // namespace decoder
1,483
C++
.h
49
26.244898
73
0.720028
badaix/snapcast
6,105
452
82
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
25,091
opus_decoder.hpp
badaix_snapcast/client/decoder/opus_decoder.hpp
/*** This file is part of snapcast Copyright (C) 2015 Hannes Ellinger Copyright (C) 2016-2024 Johannes Pohl This program is free software: you can 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 <http://www.gnu.org/licenses/>. ***/ #pragma once // local headers #include "decoder/decoder.hpp" // 3rd party headers #ifdef MACOS #include <opus.h> #else #include <opus/opus.h> #endif // standard headers #include <vector> namespace decoder { class OpusDecoder : public Decoder { public: OpusDecoder(); ~OpusDecoder(); bool decode(msg::PcmChunk* chunk) override; SampleFormat setHeader(msg::CodecHeader* chunk) override; private: ::OpusDecoder* dec_; std::vector<opus_int16> pcm_; SampleFormat sample_format_; }; } // namespace decoder
1,369
C++
.h
41
28.878049
77
0.715046
badaix/snapcast
6,105
452
82
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
25,092
null_decoder.hpp
badaix_snapcast/client/decoder/null_decoder.hpp
/*** This file is part of snapcast Copyright (C) 2014-2023 Johannes Pohl This program is free software: you can 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 <http://www.gnu.org/licenses/>. ***/ #pragma once // local headers #include "decoder.hpp" namespace decoder { class NullDecoder : public Decoder { public: NullDecoder(); bool decode(msg::PcmChunk* chunk) override; SampleFormat setHeader(msg::CodecHeader* chunk) override; }; } // namespace decoder
1,019
C++
.h
27
34.185185
73
0.75178
badaix/snapcast
6,105
452
82
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
25,093
ogg_decoder.hpp
badaix_snapcast/client/decoder/ogg_decoder.hpp
/*** This file is part of snapcast Copyright (C) 2014-2024 Johannes Pohl This program is free software: you can 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 <http://www.gnu.org/licenses/>. ***/ #pragma once // local headers #include "decoder.hpp" // 3rd party headers #ifdef HAS_TREMOR #include <tremor/ivorbiscodec.h> #else #include <vorbis/codec.h> #endif #include <ogg/ogg.h> namespace decoder { class OggDecoder : public Decoder { public: OggDecoder(); ~OggDecoder() override; bool decode(msg::PcmChunk* chunk) override; SampleFormat setHeader(msg::CodecHeader* chunk) override; private: bool decodePayload(msg::PcmChunk* chunk); template <typename T, typename IN_TYPE> T clip(const IN_TYPE& value, const T& lower, const T& upper) const { auto val = static_cast<int64_t>(value); if (val > upper) return upper; if (val < lower) return lower; return static_cast<T>(value); } ogg_sync_state oy; /// sync and verify incoming physical bitstream ogg_stream_state os; /// take physical pages, weld into a logical stream of packets ogg_page og; /// one Ogg bitstream page. Vorbis packets are inside ogg_packet op; /// one raw packet of data for decode vorbis_info vi; /// struct that stores all the static vorbis bitstream settings vorbis_comment vc; /// struct that stores all the bitstream user comments vorbis_dsp_state vd; /// central working state for the packet->PCM decoder vorbis_block vb; /// local working space for packet->PCM decode SampleFormat sampleFormat_; }; } // namespace decoder
2,206
C++
.h
56
35.017857
88
0.709874
badaix/snapcast
6,105
452
82
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
25,094
ApiServer.cpp
ethereum-mining_ethminer/libapicore/ApiServer.cpp
#include "ApiServer.h" #include <ethminer/buildinfo.h> #include <libethcore/Farm.h> #ifndef HOST_NAME_MAX #define HOST_NAME_MAX 255 #endif // Define grayscale palette #define HTTP_HDR0_COLOR "#e8e8e8" #define HTTP_HDR1_COLOR "#f0f0f0" #define HTTP_ROW0_COLOR "#f8f8f8" #define HTTP_ROW1_COLOR "#ffffff" #define HTTP_ROWRED_COLOR "#f46542" /* helper functions getting values from a JSON request */ static bool getRequestValue(const char* membername, bool& refValue, Json::Value& jRequest, bool optional, Json::Value& jResponse) { if (!jRequest.isMember(membername)) { if (!optional) { jResponse["error"]["code"] = -32602; jResponse["error"]["message"] = std::string("Missing '") + std::string(membername) + std::string("'"); } return optional; } if (!jRequest[membername].isBool()) { jResponse["error"]["code"] = -32602; jResponse["error"]["message"] = std::string("Invalid type of value '") + std::string(membername) + std::string("'"); return false; } if (jRequest[membername].empty()) { jResponse["error"]["code"] = -32602; jResponse["error"]["message"] = std::string("Empty '") + std::string(membername) + std::string("'"); return false; } refValue = jRequest[membername].asBool(); return true; } static bool getRequestValue(const char* membername, unsigned& refValue, Json::Value& jRequest, bool optional, Json::Value& jResponse) { if (!jRequest.isMember(membername)) { if (!optional) { jResponse["error"]["code"] = -32602; jResponse["error"]["message"] = std::string("Missing '") + std::string(membername) + std::string("'"); } return optional; } if (!jRequest[membername].isUInt()) { jResponse["error"]["code"] = -32602; jResponse["error"]["message"] = std::string("Invalid type of value '") + std::string(membername) + std::string("'"); return false; } if (jRequest[membername].empty()) { jResponse["error"]["code"] = -32602; jResponse["error"]["message"] = std::string("Empty '") + std::string(membername) + std::string("'"); return false; } refValue = jRequest[membername].asUInt(); return true; } static bool getRequestValue(const char* membername, uint64_t& refValue, Json::Value& jRequest, bool optional, Json::Value& jResponse) { if (!jRequest.isMember(membername)) { if (!optional) { jResponse["error"]["code"] = -32602; jResponse["error"]["message"] = std::string("Missing '") + std::string(membername) + std::string("'"); } return optional; } /* as there is no isUInt64() function we can not check the type */ if (jRequest[membername].empty()) { jResponse["error"]["code"] = -32602; jResponse["error"]["message"] = std::string("Empty '") + std::string(membername) + std::string("'"); return false; } try { refValue = jRequest[membername].asUInt64(); } catch (...) { jRequest["error"]["code"] = -32602; jResponse["error"]["message"] = std::string("Bad value in '") + std::string(membername) + std::string("'"); return false; } return true; } static bool getRequestValue(const char* membername, Json::Value& refValue, Json::Value& jRequest, bool optional, Json::Value& jResponse) { if (!jRequest.isMember(membername)) { if (!optional) { jResponse["error"]["code"] = -32602; jResponse["error"]["message"] = std::string("Missing '") + std::string(membername) + std::string("'"); } return optional; } if (!jRequest[membername].isObject()) { jResponse["error"]["code"] = -32602; jResponse["error"]["message"] = std::string("Invalid type of value '") + std::string(membername) + std::string("'"); return false; } if (jRequest[membername].empty()) { jResponse["error"]["code"] = -32602; jResponse["error"]["message"] = std::string("Empty '") + std::string(membername) + std::string("'"); return false; } refValue = jRequest[membername]; return true; } static bool getRequestValue(const char* membername, std::string& refValue, Json::Value& jRequest, bool optional, Json::Value& jResponse) { if (!jRequest.isMember(membername)) { if (!optional) { jResponse["error"]["code"] = -32602; jResponse["error"]["message"] = std::string("Missing '") + std::string(membername) + std::string("'"); } return optional; } if (!jRequest[membername].isString()) { jResponse["error"]["code"] = -32602; jResponse["error"]["message"] = std::string("Invalid type of value '") + std::string(membername) + std::string("'"); return false; } if (jRequest[membername].empty()) { jResponse["error"]["code"] = -32602; jResponse["error"]["message"] = std::string("Empty '") + std::string(membername) + std::string("'"); return false; } refValue = jRequest[membername].asString(); return true; } static bool checkApiWriteAccess(bool is_read_only, Json::Value& jResponse) { if (is_read_only) { jResponse["error"]["code"] = -32601; jResponse["error"]["message"] = "Method not available"; } return !is_read_only; } static bool parseRequestId(Json::Value& jRequest, Json::Value& jResponse) { const char* membername = "id"; // NOTE: all errors have the same code (-32600) indicating this is an invalid request // be sure id is there and it's not empty, otherwise raise an error if (!jRequest.isMember(membername) || jRequest[membername].empty()) { jResponse[membername] = Json::nullValue; jResponse["error"]["code"] = -32600; jResponse["error"]["message"] = "Invalid Request (missing or empty id)"; return false; } // try to parse id as Uint if (jRequest[membername].isUInt()) { jResponse[membername] = jRequest[membername].asUInt(); return true; } // try to parse id as String if (jRequest[membername].isString()) { jResponse[membername] = jRequest[membername].asString(); return true; } // id has invalid type jResponse[membername] = Json::nullValue; jResponse["error"]["code"] = -32600; jResponse["error"]["message"] = "Invalid Request (id has invalid type)"; return false; } ApiServer::ApiServer(string address, int portnum, string password) : m_password(std::move(password)), m_address(address), m_acceptor(g_io_service), m_io_strand(g_io_service) { if (portnum < 0) { m_portnumber = -portnum; m_readonly = true; } else { m_portnumber = portnum; m_readonly = false; } } void ApiServer::start() { // cnote << "ApiServer::start"; if (m_portnumber == 0) return; tcp::endpoint endpoint(boost::asio::ip::address::from_string(m_address), m_portnumber); // Try to bind to port number // if exception occurs it may be due to the fact that // requested port is already in use by another service try { m_acceptor.open(endpoint.protocol()); m_acceptor.set_option(boost::asio::ip::tcp::acceptor::reuse_address(true)); m_acceptor.bind(endpoint); m_acceptor.listen(64); } catch (const std::exception&) { cwarn << "Could not start API server on port: " + to_string(m_acceptor.local_endpoint().port()); cwarn << "Ensure port is not in use by another service"; return; } cnote << "Api server listening on port " + to_string(m_acceptor.local_endpoint().port()) << (m_password.empty() ? "." : ". Authentication needed."); m_running.store(true, std::memory_order_relaxed); m_workThread = std::thread{boost::bind(&ApiServer::begin_accept, this)}; } void ApiServer::stop() { // Exit if not started if (!m_running.load(std::memory_order_relaxed)) return; m_acceptor.cancel(); m_acceptor.close(); m_workThread.join(); m_running.store(false, std::memory_order_relaxed); // Dispose all sessions (if any) m_sessions.clear(); } void ApiServer::begin_accept() { if (!isRunning()) return; auto session = std::make_shared<ApiConnection>(m_io_strand, ++lastSessionId, m_readonly, m_password); m_acceptor.async_accept( session->socket(), m_io_strand.wrap(boost::bind(&ApiServer::handle_accept, this, session, boost::asio::placeholders::error))); } void ApiServer::handle_accept(std::shared_ptr<ApiConnection> session, boost::system::error_code ec) { // Start new connection // cnote << "ApiServer::handle_accept"; if (!ec) { session->onDisconnected([&](int id) { // Destroy pointer to session auto it = find_if(m_sessions.begin(), m_sessions.end(), [&id](const std::shared_ptr<ApiConnection> session) { return session->getId() == id; }); if (it != m_sessions.end()) { auto index = std::distance(m_sessions.begin(), it); m_sessions.erase(m_sessions.begin() + index); } }); m_sessions.push_back(session); cnote << "New API session from " << session->socket().remote_endpoint(); session->start(); } else { session.reset(); } // Resubmit new accept begin_accept(); } void ApiConnection::disconnect() { // cnote << "ApiConnection::disconnect"; // Cancel pending operations m_socket.cancel(); if (m_socket.is_open()) { boost::system::error_code ec; m_socket.shutdown(boost::asio::ip::tcp::socket::shutdown_both, ec); m_socket.close(ec); } if (m_onDisconnected) { m_onDisconnected(this->getId()); } } ApiConnection::ApiConnection( boost::asio::io_service::strand& _strand, int id, bool readonly, string password) : m_sessionId(id), m_socket(g_io_service), m_io_strand(_strand), m_readonly(readonly), m_password(std::move(password)) { m_jSwBuilder.settings_["indentation"] = ""; if (!m_password.empty()) m_is_authenticated = false; } void ApiConnection::start() { // cnote << "ApiConnection::start"; recvSocketData(); } void ApiConnection::processRequest(Json::Value& jRequest, Json::Value& jResponse) { jResponse["jsonrpc"] = "2.0"; // Strict sanity checks over jsonrpc v2 if (!parseRequestId(jRequest, jResponse)) return; std::string jsonrpc; std::string _method; if (!getRequestValue("jsonrpc", jsonrpc, jRequest, false, jResponse) || jsonrpc != "2.0" || !getRequestValue("method", _method, jRequest, false, jResponse)) { jResponse["error"]["code"] = -32600; jResponse["error"]["message"] = "Invalid Request"; return; } // Check authentication if (!m_is_authenticated || _method == "api_authorize") { if (_method != "api_authorize") { // Use error code like http 403 Forbidden jResponse["error"]["code"] = -403; jResponse["error"]["message"] = "Authorization needed"; return; } m_is_authenticated = false; /* we allow api_authorize method even if already authenticated */ Json::Value jRequestParams; if (!getRequestValue("params", jRequestParams, jRequest, false, jResponse)) return; std::string psw; if (!getRequestValue("psw", psw, jRequestParams, false, jResponse)) return; // max password length that we actually verify // (this limit can be removed by introducing a collision-resistant compressing hash, // like blake2b/sha3, but 500 should suffice and is much easier to implement) const int max_length = 500; char input_copy[max_length] = {0}; char password_copy[max_length] = {0}; // note: copy() is not O(1) , but i don't think it matters psw.copy(&input_copy[0], max_length); // ps, the following line can be optimized to only run once on startup and thus save a // minuscule amount of cpu cycles. m_password.copy(&password_copy[0], max_length); int result = 0; for (int i = 0; i < max_length; ++i) { result |= input_copy[i] ^ password_copy[i]; } if (result == 0) { m_is_authenticated = true; } else { // Use error code like http 401 Unauthorized jResponse["error"]["code"] = -401; jResponse["error"]["message"] = "Invalid password"; cerr << "API : Invalid password provided."; // Should we close the connection in the outer function after invalid password ? } /* * possible wait here a fixed time of eg 10s before respond after 5 invalid authentications were submitted to prevent brute force password attacks. */ return; } assert(m_is_authenticated); cnote << "API : Method " << _method << " requested"; if (_method == "miner_getstat1") { jResponse["result"] = getMinerStat1(); } else if (_method == "miner_getstatdetail") { jResponse["result"] = getMinerStatDetail(); } else if (_method == "miner_shuffle") { if (!checkApiWriteAccess(m_readonly, jResponse)) return; // Gives nonce scrambler a new range jResponse["result"] = true; Farm::f().shuffle(); } else if (_method == "miner_ping") { // Replies back to (check for liveness) jResponse["result"] = "pong"; } else if (_method == "miner_restart") { // Send response to client of success // and invoke an async restart // to prevent locking if (!checkApiWriteAccess(m_readonly, jResponse)) return; jResponse["result"] = true; Farm::f().restart_async(); } else if (_method == "miner_reboot") { if (!checkApiWriteAccess(m_readonly, jResponse)) return; jResponse["result"] = Farm::f().reboot({{"api_miner_reboot"}}); } else if (_method == "miner_getconnections") { // Returns a list of configured pools jResponse["result"] = PoolManager::p().getConnectionsJson(); } else if (_method == "miner_addconnection") { if (!checkApiWriteAccess(m_readonly, jResponse)) return; Json::Value jRequestParams; if (!getRequestValue("params", jRequestParams, jRequest, false, jResponse)) return; std::string sUri; if (!getRequestValue("uri", sUri, jRequestParams, false, jResponse)) return; try { // If everything ok then add this new uri PoolManager::p().addConnection(sUri); jResponse["result"] = true; } catch (...) { jResponse["error"]["code"] = -422; jResponse["error"]["message"] = "Bad URI : " + sUri; } } else if (_method == "miner_setactiveconnection") { if (!checkApiWriteAccess(m_readonly, jResponse)) return; Json::Value jRequestParams; if (!getRequestValue("params", jRequestParams, jRequest, false, jResponse)) return; if (jRequestParams.isMember("index")) { unsigned index; if (getRequestValue("index", index, jRequestParams, false, jResponse)) { try { PoolManager::p().setActiveConnection(index); } catch (const std::exception& _ex) { std::string what = _ex.what(); jResponse["error"]["code"] = -422; jResponse["error"]["message"] = what; return; } } else { jResponse["error"]["code"] = -422; jResponse["error"]["message"] = "Invalid index"; return; } } else { string uri; if (getRequestValue("URI", uri, jRequestParams, false, jResponse)) { try { PoolManager::p().setActiveConnection(uri); } catch (const std::exception& _ex) { std::string what = _ex.what(); jResponse["error"]["code"] = -422; jResponse["error"]["message"] = what; return; } } else { jResponse["error"]["code"] = -422; jResponse["error"]["message"] = "Invalid index"; return; } } jResponse["result"] = true; } else if (_method == "miner_removeconnection") { if (!checkApiWriteAccess(m_readonly, jResponse)) return; Json::Value jRequestParams; if (!getRequestValue("params", jRequestParams, jRequest, false, jResponse)) return; unsigned index; if (!getRequestValue("index", index, jRequestParams, false, jResponse)) return; try { PoolManager::p().removeConnection(index); jResponse["result"] = true; } catch (const std::exception& _ex) { std::string what = _ex.what(); jResponse["error"]["code"] = -422; jResponse["error"]["message"] = what; return; } } else if (_method == "miner_getscramblerinfo") { jResponse["result"] = Farm::f().get_nonce_scrambler_json(); } else if (_method == "miner_setscramblerinfo") { if (!checkApiWriteAccess(m_readonly, jResponse)) return; Json::Value jRequestParams; if (!getRequestValue("params", jRequestParams, jRequest, false, jResponse)) return; bool any_value_provided = false; uint64_t nonce = Farm::f().get_nonce_scrambler(); unsigned exp = Farm::f().get_segment_width(); if (jRequestParams.isMember("noncescrambler")) { string nonceHex; any_value_provided = true; nonceHex = jRequestParams["noncescrambler"].asString(); if (nonceHex.substr(0, 2) == "0x") { try { nonce = std::stoul(nonceHex, nullptr, 16); } catch (const std::exception&) { jResponse["error"]["code"] = -422; jResponse["error"]["message"] = "Invalid nonce"; return; } } else { // as we already know there is a "noncescrambler" element we can use optional=false if (!getRequestValue("noncescrambler", nonce, jRequestParams, false, jResponse)) return; } } if (jRequestParams.isMember("segmentwidth")) { any_value_provided = true; if (!getRequestValue("segmentwidth", exp, jRequestParams, false, jResponse)) return; } if (!any_value_provided) { jResponse["error"]["code"] = -32602; jResponse["error"]["message"] = "Missing parameters"; return; } if (exp < 10) exp = 10; // Not below if (exp > 50) exp = 40; // Not above Farm::f().set_nonce_scrambler(nonce); Farm::f().set_nonce_segment_width(exp); jResponse["result"] = true; } else if (_method == "miner_pausegpu") { if (!checkApiWriteAccess(m_readonly, jResponse)) return; Json::Value jRequestParams; if (!getRequestValue("params", jRequestParams, jRequest, false, jResponse)) return; unsigned index; if (!getRequestValue("index", index, jRequestParams, false, jResponse)) return; bool pause; if (!getRequestValue("pause", pause, jRequestParams, false, jResponse)) return; auto const& miner = Farm::f().getMiner(index); if (miner) { if (pause) miner->pause(MinerPauseEnum::PauseDueToAPIRequest); else miner->resume(MinerPauseEnum::PauseDueToAPIRequest); jResponse["result"] = true; } else { jResponse["error"]["code"] = -422; jResponse["error"]["message"] = "Index out of bounds"; return; } } else if (_method == "miner_setverbosity") { if (!checkApiWriteAccess(m_readonly, jResponse)) return; Json::Value jRequestParams; if (!getRequestValue("params", jRequestParams, jRequest, false, jResponse)) return; unsigned verbosity; if (!getRequestValue("verbosity", verbosity, jRequestParams, false, jResponse)) return; if (verbosity >= LOG_NEXT) { jResponse["error"]["code"] = -422; jResponse["error"]["message"] = "Verbosity out of bounds (0-" + to_string(LOG_NEXT - 1) + ")"; return; } cnote << "Setting verbosity level to " << verbosity; g_logOptions = verbosity; jResponse["result"] = true; } else { // Any other method not found jResponse["error"]["code"] = -32601; jResponse["error"]["message"] = "Method not found"; } } void ApiConnection::recvSocketData() { boost::asio::async_read(m_socket, m_recvBuffer, boost::asio::transfer_at_least(1), m_io_strand.wrap(boost::bind(&ApiConnection::onRecvSocketDataCompleted, this, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred))); } void ApiConnection::onRecvSocketDataCompleted( const boost::system::error_code& ec, std::size_t bytes_transferred) { /* Standard http request detection pattern 1st group : any UPPERCASE word 2nd group : the path 3rd group : HTTP version */ static std::regex http_pattern("^([A-Z]{1,6}) (\\/[\\S]*) (HTTP\\/1\\.[0-9]{1})"); std::smatch http_matches; if (!ec && bytes_transferred > 0) { // Extract received message and free the buffer std::string rx_message( boost::asio::buffer_cast<const char*>(m_recvBuffer.data()), bytes_transferred); m_recvBuffer.consume(bytes_transferred); m_message.append(rx_message); std::string line; std::string linedelimiter; std::size_t linedelimiteroffset; if (m_message.size() < 4) return; // Wait for other data to come in if (std::regex_search( m_message, http_matches, http_pattern, std::regex_constants::match_default)) { // We got an HTTP request std::string http_method = http_matches[1].str(); std::string http_path = http_matches[2].str(); std::string http_ver = http_matches[3].str(); // Do we support method ? if (http_method != "GET") { std::string what = "Method " + http_method + " not allowed"; std::stringstream ss; ss << http_ver << " " << "405 Method not allowed\r\n" << "Server: " << ethminer_get_buildinfo()->project_name_with_version << "\r\n" << "Content-Type: text/plain\r\n" << "Content-Length: " << what.size() << "\r\n\r\n" << what << "\r\n"; sendSocketData(ss.str(), true); m_message.clear(); return; } // Do we support path ? if (http_path != "/" && http_path != "/getstat1") { std::string what = "The requested resource " + http_path + " not found on this server"; std::stringstream ss; ss << http_ver << " " << "404 Not Found\r\n" << "Server: " << ethminer_get_buildinfo()->project_name_with_version << "\r\n" << "Content-Type: text/plain\r\n" << "Content-Length: " << what.size() << "\r\n\r\n" << what << "\r\n"; sendSocketData(ss.str(), true); m_message.clear(); return; } //// Get all the lines - we actually don't care much //// until we support other http methods or paths //// Keep this for future use (if any) //// Remember to #include <boost/algorithm/string.hpp> // std::vector<std::string> lines; // boost::split(lines, m_message, [](char _c) { return _c == '\n'; }); std::stringstream ss; // Builder of the response if (http_method == "GET" && (http_path == "/" || http_path == "/getstat1")) { try { std::string body = getHttpMinerStatDetail(); ss.clear(); ss << http_ver << " " << "200 Ok Error\r\n" << "Server: " << ethminer_get_buildinfo()->project_name_with_version << "\r\n" << "Content-Type: text/html; charset=utf-8\r\n" << "Content-Length: " << body.size() << "\r\n\r\n" << body << "\r\n"; } catch (const std::exception& _ex) { std::string what = "Internal error : " + std::string(_ex.what()); ss.clear(); ss << http_ver << " " << "500 Internal Server Error\r\n" << "Server: " << ethminer_get_buildinfo()->project_name_with_version << "\r\n" << "Content-Type: text/plain\r\n" << "Content-Length: " << what.size() << "\r\n\r\n" << what << "\r\n"; } } sendSocketData(ss.str(), true); m_message.clear(); } else { // We got a Json request // Process each line in the transmission linedelimiter = "\n"; linedelimiteroffset = m_message.find(linedelimiter); while (linedelimiteroffset != string::npos) { if (linedelimiteroffset > 0) { line = m_message.substr(0, linedelimiteroffset); boost::trim(line); if (!line.empty()) { // Test validity of chunk and process Json::Value jMsg; Json::Value jRes; Json::Reader jRdr; if (jRdr.parse(line, jMsg)) { try { // Run in sync so no 2 different async reads may overlap processRequest(jMsg, jRes); } catch (const std::exception& _ex) { jRes = Json::Value(); jRes["jsonrpc"] = "2.0"; jRes["id"] = Json::Value::null; jRes["error"]["errorcode"] = "500"; jRes["error"]["message"] = _ex.what(); } } else { jRes = Json::Value(); jRes["jsonrpc"] = "2.0"; jRes["id"] = Json::Value::null; jRes["error"]["errorcode"] = "-32700"; string what = jRdr.getFormattedErrorMessages(); boost::replace_all(what, "\n", " "); cwarn << "API : Got invalid Json message " << what; jRes["error"]["message"] = "Json parse error : " + what; } // Send response to client sendSocketData(jRes); } } // Next line (if any) m_message.erase(0, linedelimiteroffset + 1); linedelimiteroffset = m_message.find(linedelimiter); } // Eventually keep reading from socket if (m_socket.is_open()) recvSocketData(); } } else { disconnect(); } } void ApiConnection::sendSocketData(Json::Value const& jReq, bool _disconnect) { if (!m_socket.is_open()) return; std::stringstream line; line << Json::writeString(m_jSwBuilder, jReq) << std::endl; sendSocketData(line.str(), _disconnect); } void ApiConnection::sendSocketData(std::string const& _s, bool _disconnect) { if (!m_socket.is_open()) return; std::ostream os(&m_sendBuffer); os << _s; async_write(m_socket, m_sendBuffer, m_io_strand.wrap(boost::bind(&ApiConnection::onSendSocketDataCompleted, this, boost::asio::placeholders::error, _disconnect))); } void ApiConnection::onSendSocketDataCompleted(const boost::system::error_code& ec, bool _disconnect) { if (ec || _disconnect) disconnect(); } Json::Value ApiConnection::getMinerStat1() { auto connection = PoolManager::p().getActiveConnection(); TelemetryType t = Farm::f().Telemetry(); auto runningTime = std::chrono::duration_cast<std::chrono::minutes>(steady_clock::now() - t.start); ostringstream totalMhEth; ostringstream totalMhDcr; ostringstream detailedMhEth; ostringstream detailedMhDcr; ostringstream tempAndFans; ostringstream poolAddresses; ostringstream invalidStats; totalMhEth << std::fixed << std::setprecision(0) << t.farm.hashrate / 1000.0f << ";" << t.farm.solutions.accepted << ";" << t.farm.solutions.rejected; totalMhDcr << "0;0;0"; // DualMining not supported invalidStats << t.farm.solutions.failed << ";0"; // Invalid + Pool switches poolAddresses << connection->Host() << ':' << connection->Port(); invalidStats << ";0;0"; // DualMining not supported int gpuIndex; int numGpus = t.miners.size(); for (gpuIndex = 0; gpuIndex < numGpus; gpuIndex++) { detailedMhEth << std::fixed << std::setprecision(0) << t.miners.at(gpuIndex).hashrate / 1000.0f << (((numGpus - 1) > gpuIndex) ? ";" : ""); detailedMhDcr << "off" << (((numGpus - 1) > gpuIndex) ? ";" : ""); // DualMining not supported } for (gpuIndex = 0; gpuIndex < numGpus; gpuIndex++) { tempAndFans << t.miners.at(gpuIndex).sensors.tempC << ";" << t.miners.at(gpuIndex).sensors.fanP << (((numGpus - 1) > gpuIndex) ? ";" : ""); // Fetching Temp and Fans } Json::Value jRes; jRes[0] = ethminer_get_buildinfo()->project_name_with_version; // miner version. jRes[1] = toString(runningTime.count()); // running time, in minutes. jRes[2] = totalMhEth.str(); // total ETH hashrate in MH/s, number of ETH shares, number of ETH // rejected shares. jRes[3] = detailedMhEth.str(); // detailed ETH hashrate for all GPUs. jRes[4] = totalMhDcr.str(); // total DCR hashrate in MH/s, number of DCR shares, number of DCR // rejected shares. jRes[5] = detailedMhDcr.str(); // detailed DCR hashrate for all GPUs. jRes[6] = tempAndFans.str(); // Temperature and Fan speed(%) pairs for all GPUs. jRes[7] = poolAddresses.str(); // current mining pool. For dual mode, there will be two pools here. jRes[8] = invalidStats.str(); // number of ETH invalid shares, number of ETH pool switches, // number of DCR invalid shares, number of DCR pool switches. return jRes; } Json::Value ApiConnection::getMinerStatDetailPerMiner( const TelemetryType& _t, std::shared_ptr<Miner> _miner) { unsigned _index = _miner->Index(); std::chrono::steady_clock::time_point _now = std::chrono::steady_clock::now(); Json::Value jRes; DeviceDescriptor minerDescriptor = _miner->getDescriptor(); jRes["_index"] = _index; jRes["_mode"] = (minerDescriptor.subscriptionType == DeviceSubscriptionTypeEnum::Cuda ? "CUDA" : "OpenCL"); /* Hardware Info */ Json::Value hwinfo; hwinfo["pci"] = minerDescriptor.uniqueId; hwinfo["type"] = (minerDescriptor.type == DeviceTypeEnum::Gpu ? "GPU" : (minerDescriptor.type == DeviceTypeEnum::Accelerator ? "ACCELERATOR" : "CPU")); ostringstream ss; ss << (minerDescriptor.clDetected ? minerDescriptor.clName : minerDescriptor.cuName) << " " << dev::getFormattedMemory((double)minerDescriptor.totalMemory); hwinfo["name"] = ss.str(); /* Hardware Sensors*/ Json::Value sensors = Json::Value(Json::arrayValue); sensors.append(_t.miners.at(_index).sensors.tempC); sensors.append(_t.miners.at(_index).sensors.fanP); sensors.append(_t.miners.at(_index).sensors.powerW); hwinfo["sensors"] = sensors; /* Mining Info */ Json::Value mininginfo; Json::Value jshares = Json::Value(Json::arrayValue); Json::Value jsegment = Json::Value(Json::arrayValue); jshares.append(_t.miners.at(_index).solutions.accepted); jshares.append(_t.miners.at(_index).solutions.rejected); jshares.append(_t.miners.at(_index).solutions.failed); auto solution_lastupdated = std::chrono::duration_cast<std::chrono::seconds>( _now - _t.miners.at(_index).solutions.tstamp); jshares.append(uint64_t(solution_lastupdated.count())); // interval in seconds from last found // share mininginfo["shares"] = jshares; mininginfo["paused"] = _miner->paused(); mininginfo["pause_reason"] = _miner->paused() ? _miner->pausedString() : Json::Value::null; /* Nonce infos */ auto segment_width = Farm::f().get_segment_width(); uint64_t gpustartnonce = Farm::f().get_nonce_scrambler() + ((uint64_t)_index << segment_width); jsegment.append(toHex(uint64_t(gpustartnonce), HexPrefix::Add)); jsegment.append(toHex(uint64_t(gpustartnonce + (1LL << segment_width)), HexPrefix::Add)); mininginfo["segment"] = jsegment; /* Hash & Share infos */ mininginfo["hashrate"] = toHex((uint32_t)_t.miners.at(_index).hashrate, HexPrefix::Add); jRes["hardware"] = hwinfo; jRes["mining"] = mininginfo; return jRes; } std::string ApiConnection::getHttpMinerStatDetail() { Json::Value jStat = getMinerStatDetail(); uint64_t durationSeconds = jStat["host"]["runtime"].asUInt64(); int hours = (int)(durationSeconds / 3600); durationSeconds -= (hours * 3600); int minutes = (int)(durationSeconds / 60); int hoursSize = (hours > 9 ? (hours > 99 ? 3 : 2) : 1); /* Build up header*/ std::stringstream _ret; _ret << "<!doctype html>" << "<html lang=en>" << "<head>" << "<meta charset=utf-8>" << "<meta http-equiv=\"refresh\" content=\"30\">" << "<title>" << jStat["host"]["name"].asString() << "</title>" << "<style>" << "body{font-family:-apple-system,BlinkMacSystemFont,\"Segoe UI\",Roboto," << "\"Helvetica Neue\",Helvetica,Arial,sans-serif;font-size:16px;line-height:1.5;" << "text-align:center;}" << "table,td,th{border:1px inset #000;}" << "table{border-spacing:0;}" << "td,th{padding:3px;}" << "tbody tr:nth-child(even){background-color:" << HTTP_ROW0_COLOR << ";}" << "tbody tr:nth-child(odd){background-color:" << HTTP_ROW1_COLOR << ";}" << ".mx-auto{margin-left:auto;margin-right:auto;}" << ".bg-header1{background-color:" << HTTP_HDR1_COLOR << ";}" << ".bg-header0{background-color:" << HTTP_HDR0_COLOR << ";}" << ".bg-red{color:" << HTTP_ROWRED_COLOR << ";}" << ".right{text-align: right;}" << "</style>" << "<meta http-equiv=refresh content=30>" << "</head>" << "<body>" << "<table class=mx-auto>" << "<thead>" << "<tr class=bg-header1>" << "<th colspan=9>" << jStat["host"]["version"].asString() << " - " << setw(hoursSize) << hours << ":" << setw(2) << setfill('0') << fixed << minutes << "<br>Pool: " << jStat["connection"]["uri"].asString() << "</th>" << "</tr>" << "<tr class=bg-header0>" << "<th>PCI</th>" << "<th>Device</th>" << "<th>Mode</th>" << "<th>Paused</th>" << "<th class=right>Hash Rate</th>" << "<th class=right>Solutions</th>" << "<th class=right>Temp.</th>" << "<th class=right>Fan %</th>" << "<th class=right>Power</th>" << "</tr>" << "</thead><tbody>"; /* Loop miners */ double total_hashrate = 0; double total_power = 0; unsigned int total_solutions = 0; for (Json::Value::ArrayIndex i = 0; i != jStat["devices"].size(); i++) { Json::Value device = jStat["devices"][i]; double hashrate = std::stoul(device["mining"]["hashrate"].asString(), nullptr, 16); double power = device["hardware"]["sensors"][2].asDouble(); unsigned int solutions = device["mining"]["shares"][0].asUInt(); total_hashrate += hashrate; total_power += power; total_solutions += solutions; _ret << "<tr" << (device["mining"]["paused"].asBool() ? " class=\"bg-red\"" : "") << ">"; // Open row _ret << "<td>" << device["hardware"]["pci"].asString() << "</td>"; _ret << "<td>" << device["hardware"]["name"].asString() << "</td>"; _ret << "<td>" << device["_mode"].asString() << "</td>"; _ret << "<td>" << (device["mining"]["paused"].asBool() ? device["mining"]["pause_reason"].asString() : "No") << "</td>"; _ret << "<td class=right>" << dev::getFormattedHashes(hashrate) << "</td>"; string solString = "A" + device["mining"]["shares"][0].asString() + ":R" + device["mining"]["shares"][1].asString() + ":F" + device["mining"]["shares"][2].asString(); _ret << "<td class=right>" << solString << "</td>"; _ret << "<td class=right>" << device["hardware"]["sensors"][0].asString() << "</td>"; _ret << "<td class=right>" << device["hardware"]["sensors"][1].asString() << "</td>"; stringstream powerStream; // Round the power to 2 decimal places to remove floating point garbage powerStream << fixed << setprecision(2) << device["hardware"]["sensors"][2].asDouble(); _ret << "<td class=right>" << powerStream.str() << "</td>"; _ret << "</tr>"; // Close row } _ret << "</tbody>"; /* Summarize */ _ret << "<tfoot><tr class=bg-header0><td colspan=4 class=right>Total</td><td class=right>" << dev::getFormattedHashes(total_hashrate) << "</td><td class=right>" << total_solutions << "</td><td colspan=3 class=right>" << setprecision(2) << total_power << "</td></tfoot>"; _ret << "</table></body></html>"; return _ret.str(); } /** * @brief Return a total and per GPU detailed list of current status * As we return here difficulty and share counts (which are not getting resetted if we * switch pool) the results may "lie". * Eg: Calculating runtime, (current) difficulty and submitted shares must not match the hashrate. * Inspired by Andrea Lanfranchi comment on issue 1232: * https://github.com/ethereum-mining/ethminer/pull/1232#discussion_r193995891 * @return The json result */ Json::Value ApiConnection::getMinerStatDetail() { const std::chrono::steady_clock::time_point now = std::chrono::steady_clock::now(); TelemetryType t = Farm::f().Telemetry(); auto runningTime = std::chrono::duration_cast<std::chrono::seconds>( std::chrono::steady_clock::now() - t.start); // ostringstream version; Json::Value devices = Json::Value(Json::arrayValue); Json::Value jRes; /* Host Info */ Json::Value hostinfo; hostinfo["version"] = ethminer_get_buildinfo()->project_name_with_version; // miner version. hostinfo["runtime"] = uint64_t(runningTime.count()); // running time, in seconds. { // Even the client should know which host was queried char hostName[HOST_NAME_MAX + 1]; if (!gethostname(hostName, HOST_NAME_MAX + 1)) hostinfo["name"] = hostName; else hostinfo["name"] = Json::Value::null; } /* Connection info */ Json::Value connectioninfo; auto connection = PoolManager::p().getActiveConnection(); connectioninfo["uri"] = connection->str(); connectioninfo["connected"] = PoolManager::p().isConnected(); connectioninfo["switches"] = PoolManager::p().getConnectionSwitches(); /* Mining Info */ Json::Value mininginfo; Json::Value sharesinfo = Json::Value(Json::arrayValue); mininginfo["hashrate"] = toHex(uint32_t(t.farm.hashrate), HexPrefix::Add); mininginfo["epoch"] = PoolManager::p().getCurrentEpoch(); mininginfo["epoch_changes"] = PoolManager::p().getEpochChanges(); mininginfo["difficulty"] = PoolManager::p().getCurrentDifficulty(); sharesinfo.append(t.farm.solutions.accepted); sharesinfo.append(t.farm.solutions.rejected); sharesinfo.append(t.farm.solutions.failed); auto solution_lastupdated = std::chrono::duration_cast<std::chrono::seconds>(now - t.farm.solutions.tstamp); sharesinfo.append(uint64_t(solution_lastupdated.count())); // interval in seconds from last // found share mininginfo["shares"] = sharesinfo; /* Monitors Info */ Json::Value monitorinfo; auto tstop = Farm::f().get_tstop(); if (tstop) { Json::Value tempsinfo = Json::Value(Json::arrayValue); tempsinfo.append(Farm::f().get_tstart()); tempsinfo.append(tstop); monitorinfo["temperatures"] = tempsinfo; } /* Devices related info */ for (shared_ptr<Miner> miner : Farm::f().getMiners()) devices.append(getMinerStatDetailPerMiner(t, miner)); jRes["devices"] = devices; jRes["monitors"] = monitorinfo; jRes["connection"] = connectioninfo; jRes["host"] = hostinfo; jRes["mining"] = mininginfo; return jRes; }
44,046
C++
.cpp
1,124
29.545374
105
0.551559
ethereum-mining/ethminer
5,969
2,283
327
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
true
false
true
false
25,095
PoolManager.cpp
ethereum-mining_ethminer/libpoolprotocols/PoolManager.cpp
#include <chrono> #include "PoolManager.h" using namespace std; using namespace dev; using namespace eth; PoolManager* PoolManager::m_this = nullptr; PoolManager::PoolManager(PoolSettings _settings) : m_Settings(std::move(_settings)), m_io_strand(g_io_service), m_failovertimer(g_io_service), m_submithrtimer(g_io_service), m_reconnecttimer(g_io_service) { DEV_BUILD_LOG_PROGRAMFLOW(cnote, "PoolManager::PoolManager() begin"); m_this = this; m_currentWp.header = h256(); Farm::f().onMinerRestart([&]() { cnote << "Restart miners..."; if (Farm::f().isMining()) { cnote << "Shutting down miners..."; Farm::f().stop(); } cnote << "Spinning up miners..."; Farm::f().start(); }); Farm::f().onSolutionFound([&](const Solution& sol) { // Solution should passthrough only if client is // properly connected. Otherwise we'll have the bad behavior // to log nonce submission but receive no response if (p_client && p_client->isConnected()) { p_client->submitSolution(sol); } else { cnote << string(EthOrange "Solution 0x") + toHex(sol.nonce) << " wasted. Waiting for connection..."; } return false; }); DEV_BUILD_LOG_PROGRAMFLOW(cnote, "PoolManager::PoolManager() end"); } void PoolManager::setClientHandlers() { p_client->onConnected([&]() { { // If HostName is already an IP address no need to append the // effective ip address. if (p_client->getConnection()->HostNameType() == dev::UriHostNameType::Dns || p_client->getConnection()->HostNameType() == dev::UriHostNameType::Basic) { string ep = p_client->ActiveEndPoint(); if (!ep.empty()) m_selectedHost = p_client->getConnection()->Host() + ep; } cnote << "Established connection to " << m_selectedHost; m_connectionAttempt = 0; // Reset current WorkPackage m_currentWp.job.clear(); m_currentWp.header = h256(); // Shuffle if needed if (Farm::f().get_ergodicity() == 1U) Farm::f().shuffle(); // Rough implementation to return to primary pool // after specified amount of time if (m_activeConnectionIdx != 0 && m_Settings.poolFailoverTimeout) { m_failovertimer.expires_from_now( boost::posix_time::minutes(m_Settings.poolFailoverTimeout)); m_failovertimer.async_wait(m_io_strand.wrap(boost::bind( &PoolManager::failovertimer_elapsed, this, boost::asio::placeholders::error))); } else { m_failovertimer.cancel(); } } if (!Farm::f().isMining()) { cnote << "Spinning up miners..."; Farm::f().start(); } else if (Farm::f().paused()) { cnote << "Resume mining ..."; Farm::f().resume(); } // Activate timing for HR submission if (m_Settings.reportHashrate) { m_submithrtimer.expires_from_now(boost::posix_time::seconds(m_Settings.hashRateInterval)); m_submithrtimer.async_wait(m_io_strand.wrap(boost::bind( &PoolManager::submithrtimer_elapsed, this, boost::asio::placeholders::error))); } // Signal async operations have completed m_async_pending.store(false, std::memory_order_relaxed); }); p_client->onDisconnected([&]() { cnote << "Disconnected from " << m_selectedHost; // Clear current connection p_client->unsetConnection(); m_currentWp.header = h256(); // Stop timing actors m_failovertimer.cancel(); m_submithrtimer.cancel(); if (m_stopping.load(std::memory_order_relaxed)) { if (Farm::f().isMining()) { cnote << "Shutting down miners..."; Farm::f().stop(); } m_running.store(false, std::memory_order_relaxed); } else { // Signal we will reconnect async m_async_pending.store(true, std::memory_order_relaxed); // Suspend mining and submit new connection request cnote << "No connection. Suspend mining ..."; Farm::f().pause(); g_io_service.post(m_io_strand.wrap(boost::bind(&PoolManager::rotateConnect, this))); } }); p_client->onWorkReceived([&](WorkPackage const& wp) { // Should not happen ! if (!wp) return; int _currentEpoch = m_currentWp.epoch; bool newEpoch = (_currentEpoch == -1); // In EthereumStratum/2.0.0 epoch number is set in session if (!newEpoch) { if (p_client->getConnection()->StratumMode() == 3) newEpoch = (wp.epoch != m_currentWp.epoch); else newEpoch = (wp.seed != m_currentWp.seed); } bool newDiff = (wp.boundary != m_currentWp.boundary); m_currentWp = wp; if (newEpoch) { m_epochChanges.fetch_add(1, std::memory_order_relaxed); // If epoch is valued in workpackage take it if (wp.epoch == -1) { if (m_currentWp.block >= 0) m_currentWp.epoch = m_currentWp.block / 30000; else m_currentWp.epoch = ethash::find_epoch_number( ethash::hash256_from_bytes(m_currentWp.seed.data())); } } else { m_currentWp.epoch = _currentEpoch; } if (newDiff || newEpoch) showMiningAt(); cnote << "Job: " EthWhite << m_currentWp.header.abridged() << (m_currentWp.block != -1 ? (" block " + to_string(m_currentWp.block)) : "") << EthReset << " " << m_selectedHost; Farm::f().setWork(m_currentWp); }); p_client->onSolutionAccepted( [&](std::chrono::milliseconds const& _responseDelay, unsigned const& _minerIdx, bool _asStale) { std::stringstream ss; ss << std::setw(4) << std::setfill(' ') << _responseDelay.count() << " ms. " << m_selectedHost; cnote << EthLime "**Accepted" << (_asStale ? " stale": "") << EthReset << ss.str(); Farm::f().accountSolution(_minerIdx, SolutionAccountingEnum::Accepted); }); p_client->onSolutionRejected( [&](std::chrono::milliseconds const& _responseDelay, unsigned const& _minerIdx) { std::stringstream ss; ss << std::setw(4) << std::setfill(' ') << _responseDelay.count() << " ms. " << m_selectedHost; cwarn << EthRed "**Rejected" EthReset << ss.str(); Farm::f().accountSolution(_minerIdx, SolutionAccountingEnum::Rejected); }); } void PoolManager::stop() { DEV_BUILD_LOG_PROGRAMFLOW(cnote, "PoolManager::stop() begin"); if (m_running.load(std::memory_order_relaxed)) { m_async_pending.store(true, std::memory_order_relaxed); m_stopping.store(true, std::memory_order_relaxed); if (p_client && p_client->isConnected()) { p_client->disconnect(); // Wait for async operations to complete while (m_running.load(std::memory_order_relaxed)) this_thread::sleep_for(chrono::milliseconds(500)); p_client = nullptr; } else { // Stop timing actors m_failovertimer.cancel(); m_submithrtimer.cancel(); m_reconnecttimer.cancel(); if (Farm::f().isMining()) { cnote << "Shutting down miners..."; Farm::f().stop(); } } } DEV_BUILD_LOG_PROGRAMFLOW(cnote, "PoolManager::stop() end"); } void PoolManager::addConnection(std::string _connstring) { m_Settings.connections.push_back(std::shared_ptr<URI>(new URI(_connstring))); } void PoolManager::addConnection(std::shared_ptr<URI> _uri) { m_Settings.connections.push_back(_uri); } /* * Remove a connection * Returns: 0 on success * -1 failure (out of bounds) * -2 failure (active connection should be deleted) */ void PoolManager::removeConnection(unsigned int idx) { // Are there any outstanding operations ? if (m_async_pending.load(std::memory_order_relaxed)) throw std::runtime_error("Outstanding operations. Retry ..."); // Check bounds if (idx >= m_Settings.connections.size()) throw std::runtime_error("Index out-of bounds."); // Can't delete active connection if (idx == m_activeConnectionIdx) throw std::runtime_error("Can't remove active connection"); // Remove the selected connection m_Settings.connections.erase(m_Settings.connections.begin() + idx); if (m_activeConnectionIdx > idx) m_activeConnectionIdx--; } void PoolManager::setActiveConnectionCommon(unsigned int idx) { // Are there any outstanding operations ? bool ex = false; if (!m_async_pending.compare_exchange_strong(ex, true)) throw std::runtime_error("Outstanding operations. Retry ..."); if (idx != m_activeConnectionIdx) { m_connectionSwitches.fetch_add(1, std::memory_order_relaxed); m_activeConnectionIdx = idx; m_connectionAttempt = 0; p_client->disconnect(); } else { // Release the flag immediately m_async_pending.store(false, std::memory_order_relaxed); } } /* * Sets the active connection * Returns: 0 on success, -1 on failure (out of bounds) */ void PoolManager::setActiveConnection(unsigned int idx) { // Sets the active connection to the requested index if (idx >= m_Settings.connections.size()) throw std::runtime_error("Index out-of bounds."); setActiveConnectionCommon(idx); } void PoolManager::setActiveConnection(std::string& _connstring) { for (size_t idx = 0; idx < m_Settings.connections.size(); idx++) if (boost::iequals(m_Settings.connections[idx]->str(), _connstring)) { setActiveConnectionCommon(idx); return; } throw std::runtime_error("Not found."); } std::shared_ptr<URI> PoolManager::getActiveConnection() { try { return m_Settings.connections.at(m_activeConnectionIdx); } catch (const std::exception&) { return nullptr; } } Json::Value PoolManager::getConnectionsJson() { // Returns the list of configured connections Json::Value jRes; for (size_t i = 0; i < m_Settings.connections.size(); i++) { Json::Value JConn; JConn["index"] = (unsigned)i; JConn["active"] = (i == m_activeConnectionIdx ? true : false); JConn["uri"] = m_Settings.connections[i]->str(); jRes.append(JConn); } return jRes; } void PoolManager::start() { m_running.store(true, std::memory_order_relaxed); m_async_pending.store(true, std::memory_order_relaxed); m_connectionSwitches.fetch_add(1, std::memory_order_relaxed); g_io_service.post(m_io_strand.wrap(boost::bind(&PoolManager::rotateConnect, this))); } void PoolManager::rotateConnect() { if (p_client && p_client->isConnected()) return; // Check we're within bounds if (m_activeConnectionIdx >= m_Settings.connections.size()) m_activeConnectionIdx = 0; // If this connection is marked Unrecoverable then discard it if (m_Settings.connections.at(m_activeConnectionIdx)->IsUnrecoverable()) { m_Settings.connections.erase(m_Settings.connections.begin() + m_activeConnectionIdx); m_connectionAttempt = 0; if (m_activeConnectionIdx >= m_Settings.connections.size()) m_activeConnectionIdx = 0; m_connectionSwitches.fetch_add(1, std::memory_order_relaxed); } else if (m_connectionAttempt >= m_Settings.connectionMaxRetries) { // If this is the only connection we can't rotate // forever if (m_Settings.connections.size() == 1) { m_Settings.connections.erase(m_Settings.connections.begin() + m_activeConnectionIdx); } // Rotate connections if above max attempts threshold else { m_connectionAttempt = 0; m_activeConnectionIdx++; if (m_activeConnectionIdx >= m_Settings.connections.size()) m_activeConnectionIdx = 0; m_connectionSwitches.fetch_add(1, std::memory_order_relaxed); } } if (!m_Settings.connections.empty() && m_Settings.connections.at(m_activeConnectionIdx)->Host() != "exit") { if (p_client) p_client = nullptr; if (m_Settings.connections.at(m_activeConnectionIdx)->Family() == ProtocolFamily::GETWORK) p_client = std::unique_ptr<PoolClient>(new EthGetworkClient(m_Settings.noWorkTimeout, m_Settings.getWorkPollInterval)); if (m_Settings.connections.at(m_activeConnectionIdx)->Family() == ProtocolFamily::STRATUM) p_client = std::unique_ptr<PoolClient>( new EthStratumClient(m_Settings.noWorkTimeout, m_Settings.noResponseTimeout)); if (m_Settings.connections.at(m_activeConnectionIdx)->Family() == ProtocolFamily::SIMULATION) p_client = std::unique_ptr<PoolClient>(new SimulateClient(m_Settings.benchmarkBlock)); if (p_client) setClientHandlers(); // Count connectionAttempts m_connectionAttempt++; // Invoke connections m_selectedHost = m_Settings.connections.at(m_activeConnectionIdx)->Host() + ":" + to_string(m_Settings.connections.at(m_activeConnectionIdx)->Port()); p_client->setConnection(m_Settings.connections.at(m_activeConnectionIdx)); cnote << "Selected pool " << m_selectedHost; if ((m_connectionAttempt > 1) && (m_Settings.delayBeforeRetry > 0)) { cnote << "Next connection attempt in " << m_Settings.delayBeforeRetry << " seconds"; m_reconnecttimer.expires_from_now(boost::posix_time::seconds(m_Settings.delayBeforeRetry)); m_reconnecttimer.async_wait(m_io_strand.wrap(boost::bind( &PoolManager::reconnecttimer_elapsed, this, boost::asio::placeholders::error))); } else { p_client->connect(); } } else { if (m_Settings.connections.empty()) cnote << "No more connections to try. Exiting..."; else cnote << "'exit' failover just got hit. Exiting..."; // Stop mining if applicable if (Farm::f().isMining()) { cnote << "Shutting down miners..."; Farm::f().stop(); } m_running.store(false, std::memory_order_relaxed); raise(SIGTERM); } } void PoolManager::showMiningAt() { // Should not happen if (!m_currentWp) return; double d = dev::getHashesToTarget(m_currentWp.boundary.hex(HexPrefix::Add)); cnote << "Epoch : " EthWhite << m_currentWp.epoch << EthReset << " Difficulty : " EthWhite << dev::getFormattedHashes(d) << EthReset; } void PoolManager::failovertimer_elapsed(const boost::system::error_code& ec) { if (!ec) { if (m_running.load(std::memory_order_relaxed)) { if (m_activeConnectionIdx != 0) { m_activeConnectionIdx = 0; m_connectionAttempt = 0; m_connectionSwitches.fetch_add(1, std::memory_order_relaxed); cnote << "Failover timeout reached, retrying connection to primary pool"; p_client->disconnect(); } } } } void PoolManager::submithrtimer_elapsed(const boost::system::error_code& ec) { if (!ec) { if (m_running.load(std::memory_order_relaxed)) { if (p_client && p_client->isConnected()) p_client->submitHashrate((uint32_t)Farm::f().HashRate(), m_Settings.hashRateId); // Resubmit actor m_submithrtimer.expires_from_now(boost::posix_time::seconds(m_Settings.hashRateInterval)); m_submithrtimer.async_wait(m_io_strand.wrap(boost::bind( &PoolManager::submithrtimer_elapsed, this, boost::asio::placeholders::error))); } } } void PoolManager::reconnecttimer_elapsed(const boost::system::error_code& ec) { if (ec) return; if (m_running.load(std::memory_order_relaxed)) { if (p_client && !p_client->isConnected()) { p_client->connect(); } } } int PoolManager::getCurrentEpoch() { return m_currentWp.epoch; } double PoolManager::getCurrentDifficulty() { if (!m_currentWp) return 0.0; return dev::getHashesToTarget(m_currentWp.boundary.hex(HexPrefix::Add)); } unsigned PoolManager::getConnectionSwitches() { return m_connectionSwitches.load(std::memory_order_relaxed); } unsigned PoolManager::getEpochChanges() { return m_epochChanges.load(std::memory_order_relaxed); }
17,514
C++
.cpp
468
28.826923
124
0.59659
ethereum-mining/ethminer
5,969
2,283
327
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
true
false
true
false
25,096
PoolURI.cpp
ethereum-mining_ethminer/libpoolprotocols/PoolURI.cpp
/* This file is part of ethminer. ethminer is free software: you can 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. ethminer 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 ethminer. If not, see <http://www.gnu.org/licenses/>. */ #include <algorithm> #include <iostream> #include <map> #include <sstream> #include <cstring> #include <libpoolprotocols/PoolURI.h> using namespace dev; struct SchemeAttributes { ProtocolFamily family; SecureLevel secure; unsigned version; }; static std::map<std::string, SchemeAttributes> s_schemes = { /* This schemes are kept for backwards compatibility. Ethminer do perform stratum autodetection */ {"stratum+tcp", {ProtocolFamily::STRATUM, SecureLevel::NONE, 0}}, {"stratum1+tcp", {ProtocolFamily::STRATUM, SecureLevel::NONE, 1}}, {"stratum2+tcp", {ProtocolFamily::STRATUM, SecureLevel::NONE, 2}}, {"stratum3+tcp", {ProtocolFamily::STRATUM, SecureLevel::NONE, 3}}, {"stratum+tls", {ProtocolFamily::STRATUM, SecureLevel::TLS, 0}}, {"stratum1+tls", {ProtocolFamily::STRATUM, SecureLevel::TLS, 1}}, {"stratum2+tls", {ProtocolFamily::STRATUM, SecureLevel::TLS, 2}}, {"stratum3+tls", {ProtocolFamily::STRATUM, SecureLevel::TLS, 3}}, {"stratum+tls12", {ProtocolFamily::STRATUM, SecureLevel::TLS12, 0}}, {"stratum1+tls12", {ProtocolFamily::STRATUM, SecureLevel::TLS12, 1}}, {"stratum2+tls12", {ProtocolFamily::STRATUM, SecureLevel::TLS12, 2}}, {"stratum3+tls12", {ProtocolFamily::STRATUM, SecureLevel::TLS12, 3}}, {"stratum+ssl", {ProtocolFamily::STRATUM, SecureLevel::TLS12, 0}}, {"stratum1+ssl", {ProtocolFamily::STRATUM, SecureLevel::TLS12, 1}}, {"stratum2+ssl", {ProtocolFamily::STRATUM, SecureLevel::TLS12, 2}}, {"stratum3+ssl", {ProtocolFamily::STRATUM, SecureLevel::TLS12, 3}}, {"http", {ProtocolFamily::GETWORK, SecureLevel::NONE, 0}}, {"getwork", {ProtocolFamily::GETWORK, SecureLevel::NONE, 0}}, /* Any TCP scheme has, at the moment, only STRATUM protocol thus reiterating "stratum" word would be pleonastic Version 9 means auto-detect stratum mode */ {"stratum", {ProtocolFamily::STRATUM, SecureLevel::NONE, 999}}, {"stratums", {ProtocolFamily::STRATUM, SecureLevel::TLS, 999}}, {"stratumss", {ProtocolFamily::STRATUM, SecureLevel::TLS12, 999}}, /* The following scheme is only meant for simulation operations It's not meant to be used with -P arguments */ {"simulation", {ProtocolFamily::SIMULATION, SecureLevel::NONE, 999}} }; static bool url_decode(const std::string& in, std::string& out) { out.clear(); out.reserve(in.size()); for (std::size_t i = 0; i < in.size(); ++i) { if (in[i] == '%') { if (i + 3 <= in.size()) { int value = 0; std::istringstream is(in.substr(i + 1, 2)); if (is >> std::hex >> value) { out += static_cast<char>(value); i += 2; } else { return false; } } else { return false; } } else if (in[i] == '+') { out += ' '; } else { out += in[i]; } } return true; } /* For a well designed explanation of URI parts refer to https://cpp-netlib.org/0.10.1/in_depth/uri.html */ URI::URI(std::string uri, bool _sim) : m_uri{std::move(uri)} { std::regex sch_auth("^([a-zA-Z0-9\\+]{1,})\\:\\/\\/(.*)$"); std::smatch matches; if (!std::regex_search(m_uri, matches, sch_auth, std::regex_constants::match_default)) return; // Split scheme and authoority // Authority MUST be valued m_scheme = matches[1].str(); boost::algorithm::to_lower(m_scheme); m_authority = matches[2].str(); // Missing authority is not possible if (m_authority.empty()) throw std::runtime_error("Invalid authority"); // Simulation scheme is only allowed if specifically set if (!_sim && m_scheme == "simulation") throw std::runtime_error("Invalid scheme"); // Check scheme is allowed if ((s_schemes.find(m_scheme) == s_schemes.end())) throw std::runtime_error("Invalid scheme"); // Now let's see if authority part can be split into userinfo and "the rest" std::regex usr_url("^(.*)\\@(.*)$"); if (std::regex_search(m_authority, matches, usr_url, std::regex_constants::match_default)) { m_userinfo = matches[1].str(); m_urlinfo = matches[2].str(); } else { m_urlinfo = m_authority; } /* If m_userinfo present and valued it can be composed by either : - user - user.worker - user.worker:password - user:password In other words . delimits the beginning of worker and : delimits the beginning of password */ if (!m_userinfo.empty()) { // Save all parts enclosed in backticks into a dictionary // and replace them with tokens in the authority std::regex btick("`((?:[^`])*)`"); std::map<std::string, std::string> btick_blocks; auto btick_blocks_begin = std::sregex_iterator(m_authority.begin(), m_authority.end(), btick); auto btick_blocks_end = std::sregex_iterator(); int i = 0; for (std::sregex_iterator it = btick_blocks_begin; it != btick_blocks_end; ++it) { std::smatch match = *it; std::string match_str = match[1].str(); btick_blocks["_" + std::to_string(i++)] = match[1].str(); } if (btick_blocks.size()) { std::map<std::string, std::string>::iterator it; for (it = btick_blocks.begin(); it != btick_blocks.end(); it++) boost::replace_all(m_userinfo, "`" + it->second + "`", "`" + it->first + "`"); } std::vector<std::regex> usr_patterns; usr_patterns.push_back(std::regex("^(.*)\\.(.*)\\:(.*)$")); usr_patterns.push_back(std::regex("^(.*)\\:(.*)$")); usr_patterns.push_back(std::regex("^(.*)\\.(.*)$")); bool usrMatchFound = false; for (size_t i = 0; i < usr_patterns.size() && !usrMatchFound; i++) { if (std::regex_search( m_userinfo, matches, usr_patterns.at(i), std::regex_constants::match_default)) { usrMatchFound = true; switch (i) { case 0: m_user = matches[1].str(); m_worker = matches[2].str(); m_password = matches[3].str(); break; case 1: m_user = matches[1]; m_password = matches[2]; break; case 2: m_user = matches[1]; m_worker = matches[2]; break; default: break; } } } // If no matches found after this loop it means all the user // part is only user login if (!usrMatchFound) m_user = m_userinfo; // Replace all tokens with their respective values if (btick_blocks.size()) { std::map<std::string, std::string>::iterator it; for (it = btick_blocks.begin(); it != btick_blocks.end(); it++) { boost::replace_all(m_userinfo, "`" + it->first + "`", it->second); boost::replace_all(m_user, "`" + it->first + "`", it->second); boost::replace_all(m_worker, "`" + it->first + "`", it->second); boost::replace_all(m_password, "`" + it->first + "`", it->second); } } } /* Let's process the url part which must contain at least a host an optional port and eventually a path (which may include a query and a fragment) Host can be a DNS host or an IP address. Thus we can have - host - host/path - host:port - host:port/path */ size_t offset = m_urlinfo.find('/'); if (offset != std::string::npos) { m_hostinfo = m_urlinfo.substr(0, offset); m_pathinfo = m_urlinfo.substr(offset); } else { m_hostinfo = m_urlinfo; } boost::algorithm::to_lower(m_hostinfo); // needed to ensure we properly hit "exit" as host std::regex host_pattern("^(.*)\\:([0-9]{1,5})$"); if (std::regex_search(m_hostinfo, matches, host_pattern, std::regex_constants::match_default)) { m_host = matches[1].str(); m_port = boost::lexical_cast<uint16_t>(matches[2].str()); } else { m_host = m_hostinfo; } // Host info must be present and valued if (m_host.empty()) throw std::runtime_error("Missing host"); /* Eventually split path info into path query fragment */ if (!m_pathinfo.empty()) { // Url Decode Path std::vector<std::regex> path_patterns; path_patterns.push_back(std::regex("(\\/.*)\\?(.*)\\#(.*)$")); path_patterns.push_back(std::regex("(\\/.*)\\#(.*)$")); path_patterns.push_back(std::regex("(\\/.*)\\?(.*)$")); bool pathMatchFound = false; for (size_t i = 0; i < path_patterns.size() && !pathMatchFound; i++) { if (std::regex_search( m_pathinfo, matches, path_patterns.at(i), std::regex_constants::match_default)) { pathMatchFound = true; switch (i) { case 0: m_path = matches[1].str(); m_query = matches[2].str(); m_fragment = matches[3].str(); break; case 1: m_path = matches[1].str(); m_fragment = matches[2].str(); break; case 2: m_path = matches[1].str(); m_query = matches[2].str(); break; default: break; } } // If no matches found after this loop it means all the pathinfo // part is only path login if (!pathMatchFound) m_path = m_pathinfo; } } // Determine host type boost::system::error_code ec; boost::asio::ip::address address = boost::asio::ip::address::from_string(m_host, ec); if (!ec) { // This is a valid Ip Address if (address.is_v4()) m_hostType = UriHostNameType::IPV4; if (address.is_v6()) m_hostType = UriHostNameType::IPV6; m_isLoopBack = address.is_loopback(); } else { // Check if valid DNS hostname std::regex hostNamePattern( "^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\\-]*[a-zA-Z0-9])\\.)*([A-Za-z0-9]|[A-Za-z0-9][A-" "Za-z0-9\\-]*[A-Za-z0-9])$"); if (std::regex_match(m_host, hostNamePattern)) m_hostType = UriHostNameType::Dns; else m_hostType = UriHostNameType::Basic; } if (!m_user.empty()) boost::replace_all(m_user, "`", ""); if (!m_password.empty()) boost::replace_all(m_password, "`", ""); if (!m_worker.empty()) boost::replace_all(m_worker, "`", ""); // Eventually decode every encoded char std::string tmpStr; if (url_decode(m_userinfo, tmpStr)) m_userinfo = tmpStr; if (url_decode(m_urlinfo, tmpStr)) m_urlinfo = tmpStr; if (url_decode(m_hostinfo, tmpStr)) m_hostinfo = tmpStr; if (url_decode(m_pathinfo, tmpStr)) m_pathinfo = tmpStr; if (url_decode(m_path, tmpStr)) m_path = tmpStr; if (url_decode(m_query, tmpStr)) m_query = tmpStr; if (url_decode(m_fragment, tmpStr)) m_fragment = tmpStr; if (url_decode(m_user, tmpStr)) m_user = tmpStr; if (url_decode(m_password, tmpStr)) m_password = tmpStr; if (url_decode(m_worker, tmpStr)) m_worker = tmpStr; } ProtocolFamily URI::Family() const { return s_schemes[m_scheme].family; } unsigned URI::Version() const { return s_schemes[m_scheme].version; } std::string URI::UserDotWorker() const { std::string _ret = m_user; if (!m_worker.empty()) _ret.append("." + m_worker); return _ret; } SecureLevel URI::SecLevel() const { return s_schemes[m_scheme].secure; } UriHostNameType URI::HostNameType() const { return m_hostType; } bool URI::IsLoopBack() const { return m_isLoopBack; } std::string URI::KnownSchemes(ProtocolFamily family) { std::string schemes; for (const auto& s : s_schemes) { if ((s.second.family == family) && (s.second.version != 999)) schemes += s.first + " "; } return schemes; }
13,541
C++
.cpp
381
27.062992
99
0.556259
ethereum-mining/ethminer
5,969
2,283
327
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
true
false
true
false
25,099
SimulateClient.cpp
ethereum-mining_ethminer/libpoolprotocols/testing/SimulateClient.cpp
#include <libdevcore/Log.h> #include <chrono> #include "SimulateClient.h" using namespace std; using namespace std::chrono; using namespace dev; using namespace eth; SimulateClient::SimulateClient(unsigned const& block) : PoolClient(), Worker("sim") { m_block = block; } SimulateClient::~SimulateClient() = default; void SimulateClient::connect() { // Initialize new session m_connected.store(true, memory_order_relaxed); m_session = unique_ptr<Session>(new Session); m_session->subscribed.store(true, memory_order_relaxed); m_session->authorized.store(true, memory_order_relaxed); if (m_onConnected) m_onConnected(); // No need to worry about starting again. // Worker class prevents that startWorking(); } void SimulateClient::disconnect() { cnote << "Simulation results : " << EthWhiteBold << "Max " << dev::getFormattedHashes((double)hr_max, ScaleSuffix::Add, 6) << " Mean " << dev::getFormattedHashes((double)hr_mean, ScaleSuffix::Add, 6) << EthReset; m_conn->addDuration(m_session->duration()); m_session = nullptr; m_connected.store(false, memory_order_relaxed); if (m_onDisconnected) m_onDisconnected(); } void SimulateClient::submitHashrate(uint64_t const& rate, string const& id) { (void)rate; (void)id; } void SimulateClient::submitSolution(const Solution& solution) { // This is a fake submission only evaluated locally std::chrono::steady_clock::time_point submit_start = std::chrono::steady_clock::now(); bool accepted = EthashAux::eval(solution.work.epoch, solution.work.header, solution.nonce).value <= solution.work.boundary; std::chrono::milliseconds response_delay_ms = std::chrono::duration_cast<std::chrono::milliseconds>( std::chrono::steady_clock::now() - submit_start); if (accepted) { if (m_onSolutionAccepted) m_onSolutionAccepted(response_delay_ms, solution.midx, false); } else { if (m_onSolutionRejected) m_onSolutionRejected(response_delay_ms, solution.midx); } } // Handles all logic here void SimulateClient::workLoop() { m_start_time = std::chrono::steady_clock::now(); // apply exponential sliding average // ref: https://en.wikipedia.org/wiki/Moving_average#Exponential_moving_average WorkPackage current; current.seed = h256::random(); // We don't actually need a real seed as the epoch // is calculated upon block number (see poolmanager) current.header = h256::random(); current.block = m_block; current.boundary = h256(dev::getTargetFromDiff(1)); m_onWorkReceived(current); // submit new fake job while (m_session) { float hr = Farm::f().HashRate(); hr_max = std::max(hr_max, hr); hr_mean = hr_alpha * hr_mean + (1.0f - hr_alpha) * hr; this_thread::sleep_for(chrono::milliseconds(200)); } }
2,991
C++
.cpp
83
30.710843
91
0.676256
ethereum-mining/ethminer
5,969
2,283
327
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
25,100
Log.cpp
ethereum-mining_ethminer/libdevcore/Log.cpp
/* This file is part of ethminer. ethminer is free software: you can 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. ethminer 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 ethminer. If not, see <http://www.gnu.org/licenses/>. */ #include "Log.h" #include <map> #include <thread> #ifdef __APPLE__ #include <pthread.h> #endif #include "Guards.h" using namespace std; using namespace dev; //⊳⊲◀▶■▣▢□▷◁▧▨▩▲◆◉◈◇◎●◍◌○◼☑☒☎☢☣☰☀♽♥♠✩✭❓✔✓✖✕✘✓✔✅⚒⚡⦸⬌∅⁕«««»»»⚙ // Logging unsigned g_logOptions = 0; bool g_logNoColor = false; bool g_logSyslog = false; bool g_logStdout = false; const char* LogChannel::name() { return EthGray ".."; } const char* WarnChannel::name() { return EthRed " X"; } const char* NoteChannel::name() { return EthBlue " i"; } LogOutputStreamBase::LogOutputStreamBase(char const* _id) { static std::locale logLocl = std::locale(""); m_sstr.imbue(logLocl); if (g_logSyslog) m_sstr << std::left << std::setw(8) << getThreadName() << " " EthReset; else { time_t rawTime = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now()); char buf[24]; if (strftime(buf, 24, "%X", localtime(&rawTime)) == 0) buf[0] = '\0'; // empty if case strftime fails m_sstr << _id << " " EthViolet << buf << " " EthBlue << std::left << std::setw(8) << getThreadName() << " " EthReset; } } /// Associate a name with each thread for nice logging. struct ThreadLocalLogName { ThreadLocalLogName(char const* _name) { name = _name; } thread_local static char const* name; }; thread_local char const* ThreadLocalLogName::name; ThreadLocalLogName g_logThreadName("main"); string dev::getThreadName() { #if defined(__linux__) || defined(__APPLE__) char buffer[128]; pthread_getname_np(pthread_self(), buffer, 127); buffer[127] = 0; return buffer; #else return ThreadLocalLogName::name ? ThreadLocalLogName::name : "<unknown>"; #endif } void dev::setThreadName(char const* _n) { #if defined(__linux__) pthread_setname_np(pthread_self(), _n); #elif defined(__APPLE__) pthread_setname_np(_n); #else ThreadLocalLogName::name = _n; #endif } void dev::simpleDebugOut(std::string const& _s) { try { std::ostream& os = g_logStdout ? std::cout : std::clog; if (!g_logNoColor) { os << _s + '\n'; os.flush(); return; } bool skip = false; std::stringstream ss; for (auto it : _s) { if (!skip && it == '\x1b') skip = true; else if (skip && it == 'm') skip = false; else if (!skip) ss << it; } ss << '\n'; os << ss.str(); os.flush(); } catch (...) { return; } }
3,454
C++
.cpp
116
23.508621
100
0.598442
ethereum-mining/ethminer
5,969
2,283
327
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
true
false
true
false
25,101
Worker.cpp
ethereum-mining_ethminer/libdevcore/Worker.cpp
/* This file is part of ethminer. ethminer is free software: you can 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. ethminer 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 ethminer. If not, see <http://www.gnu.org/licenses/>. */ /** @file Worker.cpp * @author Gav Wood <i@gavwood.com> * @date 2014 */ #include <chrono> #include <thread> #include "Log.h" #include "Worker.h" using namespace std; using namespace dev; void Worker::startWorking() { DEV_BUILD_LOG_PROGRAMFLOW(cnote, "Worker::startWorking() begin"); // cnote << "startWorking for thread" << m_name; Guard l(x_work); if (m_work) { WorkerState ex = WorkerState::Stopped; m_state.compare_exchange_strong(ex, WorkerState::Starting); } else { m_state = WorkerState::Starting; m_work.reset(new thread([&]() { setThreadName(m_name.c_str()); // cnote << "Thread begins"; while (m_state != WorkerState::Killing) { WorkerState ex = WorkerState::Starting; bool ok = m_state.compare_exchange_strong(ex, WorkerState::Started); // cnote << "Trying to set Started: Thread was" << (unsigned)ex << "; " //<< ok; (void)ok; try { workLoop(); } catch (std::exception const& _e) { clog(WarnChannel) << "Exception thrown in Worker thread: " << _e.what(); if (g_exitOnError) { clog(WarnChannel) << "Terminating due to --exit"; raise(SIGTERM); } } // ex = WorkerState::Stopping; // m_state.compare_exchange_strong(ex, WorkerState::Stopped); ex = m_state.exchange(WorkerState::Stopped); // cnote << "State: Stopped: Thread was" << (unsigned)ex; if (ex == WorkerState::Killing || ex == WorkerState::Starting) m_state.exchange(ex); while (m_state == WorkerState::Stopped) this_thread::sleep_for(chrono::milliseconds(20)); } })); // cnote << "Spawning" << m_name; } while (m_state == WorkerState::Starting) this_thread::sleep_for(chrono::microseconds(20)); DEV_BUILD_LOG_PROGRAMFLOW(cnote, "Worker::startWorking() end"); } void Worker::triggerStopWorking() { DEV_GUARDED(x_work) if (m_work) { WorkerState ex = WorkerState::Started; m_state.compare_exchange_strong(ex, WorkerState::Stopping); } } void Worker::stopWorking() { DEV_BUILD_LOG_PROGRAMFLOW(cnote, "Worker::stopWorking() begin"); DEV_GUARDED(x_work) if (m_work) { WorkerState ex = WorkerState::Started; m_state.compare_exchange_strong(ex, WorkerState::Stopping); DEV_BUILD_LOG_PROGRAMFLOW(cnote, "Worker::stopWorking() waiting for WorkerState::Stopped begin"); while (m_state != WorkerState::Stopped) this_thread::sleep_for(chrono::microseconds(20)); DEV_BUILD_LOG_PROGRAMFLOW(cnote, "Worker::stopWorking() waiting for WorkerState::Stopped end"); } DEV_BUILD_LOG_PROGRAMFLOW(cnote, "Worker::stopWorking() end"); } Worker::~Worker() { DEV_BUILD_LOG_PROGRAMFLOW(cnote, "Worker::~Worker() begin"); DEV_GUARDED(x_work) if (m_work) { m_state.exchange(WorkerState::Killing); m_work->join(); m_work.reset(); } DEV_BUILD_LOG_PROGRAMFLOW(cnote, "Worker::~Worker() end"); }
4,117
C++
.cpp
111
28.540541
105
0.591581
ethereum-mining/ethminer
5,969
2,283
327
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
true
false
true
false
25,103
FixedHash.cpp
ethereum-mining_ethminer/libdevcore/FixedHash.cpp
/* This file is part of ethminer. ethminer is free software: you can 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. ethminer 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 ethminer. If not, see <http://www.gnu.org/licenses/>. */ /** @file FixedHash.cpp * @author Gav Wood <i@gavwood.com> * @date 2014 */ #include <boost/algorithm/string.hpp> #include "FixedHash.h" using namespace std; using namespace dev; std::random_device dev::s_fixedHashEngine;
910
C++
.cpp
22
37.909091
72
0.753689
ethereum-mining/ethminer
5,969
2,283
327
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
true
true
true
false
25,104
wrapnvml.cpp
ethereum-mining_ethminer/libhwmon/wrapnvml.cpp
/* * A trivial little dlopen()-based wrapper library for the * NVIDIA NVML library, to allow runtime discovery of NVML on an * arbitrary system. This is all very hackish and simple-minded, but * it serves my immediate needs in the short term until NVIDIA provides * a static NVML wrapper library themselves, hopefully in * CUDA 6.5 or maybe sometime shortly after. * * This trivial code is made available under the "new" 3-clause BSD license, * and/or any of the GPL licenses you prefer. * Feel free to use the code and modify as you see fit. * * John E. Stone - john.stone@gmail.com * * Modified to work with ethminer by * * Philipp Andreas - github@smurfy.de */ #include <stdio.h> #include <stdlib.h> #include "wrapnvml.h" #if defined(__cplusplus) extern "C" { #endif wrap_nvml_handle* wrap_nvml_create() { wrap_nvml_handle* nvmlh = nullptr; /* * We use hard-coded library installation locations for the time being... * No idea where or if libnvidia-ml.so is installed on MacOS X, a * deep scouring of the filesystem on one of the Mac CUDA build boxes * I used turned up nothing, so for now it's not going to work on OSX. */ #if defined(_WIN32) /* Windows */ #define libnvidia_ml "%PROGRAMFILES%/NVIDIA Corporation/NVSMI/nvml.dll" #elif defined(__linux) && (defined(__i386__) || defined(__ARM_ARCH_7A__)) /* In rpm based linux distributions link name is with extension .1 */ /* 32-bit linux assumed */ #define libnvidia_ml "libnvidia-ml.so.1" #elif defined(__linux) /* 64-bit linux assumed */ #define libnvidia_ml "libnvidia-ml.so.1" #else #define libnvidia_ml "" #warning "Unrecognized platform: need NVML DLL path for this platform..." return nullptr; #endif #ifdef _WIN32 char tmp[512]; ExpandEnvironmentStringsA(libnvidia_ml, tmp, sizeof(tmp)); #else char tmp[512] = libnvidia_ml; #endif void* nvml_dll = wrap_dlopen(tmp); if (nvml_dll == nullptr) { cwarn << "Failed to obtain all required NVML function pointers"; cwarn << "NVIDIA hardware monitoring disabled"; return nullptr; } nvmlh = (wrap_nvml_handle*)calloc(1, sizeof(wrap_nvml_handle)); nvmlh->nvml_dll = nvml_dll; nvmlh->nvmlInit = (wrap_nvmlReturn_t(*)(void))wrap_dlsym(nvmlh->nvml_dll, "nvmlInit"); nvmlh->nvmlDeviceGetCount = (wrap_nvmlReturn_t(*)(int*))wrap_dlsym(nvmlh->nvml_dll, "nvmlDeviceGetCount_v2"); nvmlh->nvmlDeviceGetHandleByIndex = (wrap_nvmlReturn_t(*)(int, wrap_nvmlDevice_t*))wrap_dlsym( nvmlh->nvml_dll, "nvmlDeviceGetHandleByIndex_v2"); nvmlh->nvmlDeviceGetPciInfo = (wrap_nvmlReturn_t(*)( wrap_nvmlDevice_t, wrap_nvmlPciInfo_t*))wrap_dlsym(nvmlh->nvml_dll, "nvmlDeviceGetPciInfo"); nvmlh->nvmlDeviceGetName = (wrap_nvmlReturn_t(*)(wrap_nvmlDevice_t, char*, int))wrap_dlsym( nvmlh->nvml_dll, "nvmlDeviceGetName"); nvmlh->nvmlDeviceGetTemperature = (wrap_nvmlReturn_t(*)(wrap_nvmlDevice_t, int, unsigned int*))wrap_dlsym(nvmlh->nvml_dll, "nvmlDeviceGetTemperature"); nvmlh->nvmlDeviceGetFanSpeed = (wrap_nvmlReturn_t(*)( wrap_nvmlDevice_t, unsigned int*))wrap_dlsym(nvmlh->nvml_dll, "nvmlDeviceGetFanSpeed"); nvmlh->nvmlDeviceGetPowerUsage = (wrap_nvmlReturn_t(*)( wrap_nvmlDevice_t, unsigned int*))wrap_dlsym(nvmlh->nvml_dll, "nvmlDeviceGetPowerUsage"); nvmlh->nvmlShutdown = (wrap_nvmlReturn_t(*)())wrap_dlsym(nvmlh->nvml_dll, "nvmlShutdown"); if (nvmlh->nvmlInit == nullptr || nvmlh->nvmlShutdown == nullptr || nvmlh->nvmlDeviceGetCount == nullptr || nvmlh->nvmlDeviceGetHandleByIndex == nullptr || nvmlh->nvmlDeviceGetPciInfo == nullptr || nvmlh->nvmlDeviceGetName == nullptr || nvmlh->nvmlDeviceGetTemperature == nullptr || nvmlh->nvmlDeviceGetFanSpeed == nullptr || nvmlh->nvmlDeviceGetPowerUsage == nullptr) { cwarn << "Failed to obtain all required NVML function pointers"; cwarn << "NVIDIA hardware monitoring disabled"; wrap_dlclose(nvmlh->nvml_dll); free(nvmlh); return nullptr; } nvmlh->nvmlInit(); nvmlh->nvmlDeviceGetCount(&nvmlh->nvml_gpucount); nvmlh->devs = (wrap_nvmlDevice_t*)calloc(nvmlh->nvml_gpucount, sizeof(wrap_nvmlDevice_t)); nvmlh->nvml_pci_domain_id = (unsigned int*)calloc(nvmlh->nvml_gpucount, sizeof(unsigned int)); nvmlh->nvml_pci_bus_id = (unsigned int*)calloc(nvmlh->nvml_gpucount, sizeof(unsigned int)); nvmlh->nvml_pci_device_id = (unsigned int*)calloc(nvmlh->nvml_gpucount, sizeof(unsigned int)); /* Obtain GPU device handles we're going to need repeatedly... */ for (int i = 0; i < nvmlh->nvml_gpucount; i++) { nvmlh->nvmlDeviceGetHandleByIndex(i, &nvmlh->devs[i]); } /* Query PCI info for each NVML device, and build table for mapping of */ /* CUDA device IDs to NVML device IDs and vice versa */ for (int i = 0; i < nvmlh->nvml_gpucount; i++) { wrap_nvmlPciInfo_t pciinfo; nvmlh->nvmlDeviceGetPciInfo(nvmlh->devs[i], &pciinfo); nvmlh->nvml_pci_domain_id[i] = pciinfo.domain; nvmlh->nvml_pci_bus_id[i] = pciinfo.bus; nvmlh->nvml_pci_device_id[i] = pciinfo.device; } return nvmlh; } int wrap_nvml_destroy(wrap_nvml_handle* nvmlh) { nvmlh->nvmlShutdown(); wrap_dlclose(nvmlh->nvml_dll); free(nvmlh); return 0; } int wrap_nvml_get_gpucount(wrap_nvml_handle* nvmlh, int* gpucount) { *gpucount = nvmlh->nvml_gpucount; return 0; } int wrap_nvml_get_gpu_name(wrap_nvml_handle* nvmlh, int gpuindex, char* namebuf, int bufsize) { if (gpuindex < 0 || gpuindex >= nvmlh->nvml_gpucount) return -1; if (nvmlh->nvmlDeviceGetName(nvmlh->devs[gpuindex], namebuf, bufsize) != WRAPNVML_SUCCESS) return -1; return 0; } int wrap_nvml_get_tempC(wrap_nvml_handle* nvmlh, int gpuindex, unsigned int* tempC) { if (gpuindex < 0 || gpuindex >= nvmlh->nvml_gpucount) return -1; if (nvmlh->nvmlDeviceGetTemperature( nvmlh->devs[gpuindex], 0u /* NVML_TEMPERATURE_GPU */, tempC) != WRAPNVML_SUCCESS) return -1; return 0; } int wrap_nvml_get_fanpcnt(wrap_nvml_handle* nvmlh, int gpuindex, unsigned int* fanpcnt) { if (gpuindex < 0 || gpuindex >= nvmlh->nvml_gpucount) return -1; if (nvmlh->nvmlDeviceGetFanSpeed(nvmlh->devs[gpuindex], fanpcnt) != WRAPNVML_SUCCESS) return -1; return 0; } int wrap_nvml_get_power_usage(wrap_nvml_handle* nvmlh, int gpuindex, unsigned int* milliwatts) { if (gpuindex < 0 || gpuindex >= nvmlh->nvml_gpucount) return -1; if (nvmlh->nvmlDeviceGetPowerUsage(nvmlh->devs[gpuindex], milliwatts) != WRAPNVML_SUCCESS) return -1; return 0; } #if defined(__cplusplus) } #endif
6,814
C++
.cpp
162
37.32716
100
0.68785
ethereum-mining/ethminer
5,969
2,283
327
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
25,105
wrapadl.cpp
ethereum-mining_ethminer/libhwmon/wrapadl.cpp
/* * Wrapper for ADL, inspired by wrapnvml from John E. Stone * * By Philipp Andreas - github@smurfy.de */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <string> #include "wrapadl.h" #include "wraphelper.h" #if defined(__cplusplus) extern "C" { #endif void* ADL_API_CALL ADL_Main_Memory_Alloc(int iSize) { void* lpBuffer = malloc(iSize); return lpBuffer; } wrap_adl_handle* wrap_adl_create() { wrap_adl_handle* adlh = nullptr; #if defined(_WIN32) /* Windows */ #define libatiadlxx "atiadlxx.dll" #elif defined(__linux) && (defined(__i386__) || defined(__ARM_ARCH_7A__)) /* 32-bit linux assumed */ #define libatiadlxx "libatiadlxx.so" #elif defined(__linux) /* 64-bit linux assumed */ #define libatiadlxx "libatiadlxx.so" #else #define libatiadlxx "" #warning "Unrecognized platform: need ADL DLL path for this platform..." return nullptr; #endif #ifdef _WIN32 char tmp[512]; ExpandEnvironmentStringsA(libatiadlxx, tmp, sizeof(tmp)); #else char tmp[512] = libatiadlxx; #endif void* adl_dll = wrap_dlopen(tmp); if (adl_dll == nullptr) { cwarn << "Failed to obtain all required ADL function pointers"; cwarn << "AMD hardware monitoring disabled"; return nullptr; } adlh = (wrap_adl_handle*)calloc(1, sizeof(wrap_adl_handle)); adlh->adl_dll = adl_dll; adlh->adlMainControlCreate = (wrap_adlReturn_t(*)(ADL_MAIN_MALLOC_CALLBACK, int))wrap_dlsym( adlh->adl_dll, "ADL_Main_Control_Create"); adlh->adlAdapterNumberOfAdapters = (wrap_adlReturn_t(*)(int*))wrap_dlsym(adlh->adl_dll, "ADL_Adapter_NumberOfAdapters_Get"); adlh->adlAdapterAdapterInfoGet = (wrap_adlReturn_t(*)(LPAdapterInfo, int))wrap_dlsym( adlh->adl_dll, "ADL_Adapter_AdapterInfo_Get"); adlh->adlAdapterAdapterIdGet = (wrap_adlReturn_t(*)(int, int*))wrap_dlsym(adlh->adl_dll, "ADL_Adapter_ID_Get"); adlh->adlOverdrive5TemperatureGet = (wrap_adlReturn_t(*)(int, int, ADLTemperature*))wrap_dlsym( adlh->adl_dll, "ADL_Overdrive5_Temperature_Get"); adlh->adlOverdrive5FanSpeedGet = (wrap_adlReturn_t(*)(int, int, ADLFanSpeedValue*))wrap_dlsym( adlh->adl_dll, "ADL_Overdrive5_FanSpeed_Get"); adlh->adlMainControlRefresh = (wrap_adlReturn_t(*)(void))wrap_dlsym(adlh->adl_dll, "ADL_Main_Control_Refresh"); adlh->adlMainControlDestroy = (wrap_adlReturn_t(*)(void))wrap_dlsym(adlh->adl_dll, "ADL_Main_Control_Destroy"); adlh->adl2MainControlCreate = (wrap_adlReturn_t(*)(ADL_MAIN_MALLOC_CALLBACK, int, ADL_CONTEXT_HANDLE*))wrap_dlsym(adlh->adl_dll, "ADL2_Main_Control_Create"); adlh->adl2MainControlDestroy = (wrap_adlReturn_t(*)(ADL_CONTEXT_HANDLE))wrap_dlsym( adlh->adl_dll, "ADL_Main_Control_Destroy"); adlh->adl2Overdrive6CurrentPowerGet = (wrap_adlReturn_t(*)(ADL_CONTEXT_HANDLE, int, int, int*))wrap_dlsym(adlh->adl_dll, "ADL2_Overdrive6_CurrentPower_Get"); adlh->adl2MainControlRefresh = (wrap_adlReturn_t(*)(ADL_CONTEXT_HANDLE))wrap_dlsym( adlh->adl_dll, "ADL2_Main_Control_Refresh"); if (adlh->adlMainControlCreate == nullptr || adlh->adlMainControlDestroy == nullptr || adlh->adlMainControlRefresh == nullptr || adlh->adlAdapterNumberOfAdapters == nullptr || adlh->adlAdapterAdapterInfoGet == nullptr || adlh->adlAdapterAdapterIdGet == nullptr || adlh->adlOverdrive5TemperatureGet == nullptr || adlh->adlOverdrive5FanSpeedGet == nullptr || adlh->adl2MainControlCreate == nullptr || adlh->adl2MainControlRefresh == nullptr || adlh->adl2MainControlDestroy == nullptr || adlh->adl2Overdrive6CurrentPowerGet == nullptr) { cwarn << "Failed to obtain all required ADL function pointers"; cwarn << "AMD hardware monitoring disabled"; wrap_dlclose(adlh->adl_dll); free(adlh); return nullptr; } adlh->adlMainControlCreate(ADL_Main_Memory_Alloc, 1); adlh->adlMainControlRefresh(); adlh->context = nullptr; adlh->adl2MainControlCreate(ADL_Main_Memory_Alloc, 1, &(adlh->context)); adlh->adl2MainControlRefresh(adlh->context); int logicalGpuCount = 0; adlh->adlAdapterNumberOfAdapters(&logicalGpuCount); adlh->phys_logi_device_id = (int*)calloc(logicalGpuCount, sizeof(int)); adlh->adl_gpucount = 0; int last_adapter = 0; if (logicalGpuCount > 0) { adlh->log_gpucount = logicalGpuCount; adlh->devs = (LPAdapterInfo)malloc(sizeof(AdapterInfo) * logicalGpuCount); memset(adlh->devs, '\0', sizeof(AdapterInfo) * logicalGpuCount); adlh->devs->iSize = sizeof(adlh->devs); int res = adlh->adlAdapterAdapterInfoGet(adlh->devs, sizeof(AdapterInfo) * logicalGpuCount); if (res != WRAPADL_OK) { cwarn << "Failed to obtain using adlAdapterAdapterInfoGet()."; cwarn << "AMD hardware monitoring disabled"; wrap_dlclose(adlh->adl_dll); free(adlh); return nullptr; } for (int i = 0; i < logicalGpuCount; i++) { int adapterIndex = adlh->devs[i].iAdapterIndex; int adapterID = 0; res = adlh->adlAdapterAdapterIdGet(adapterIndex, &adapterID); if (res != WRAPADL_OK) { continue; } adlh->phys_logi_device_id[adlh->adl_gpucount] = adapterIndex; if (adapterID == last_adapter) { continue; } last_adapter = adapterID; adlh->adl_gpucount++; } } return adlh; } int wrap_adl_destroy(wrap_adl_handle* adlh) { adlh->adlMainControlDestroy(); adlh->adl2MainControlDestroy(adlh->context); wrap_dlclose(adlh->adl_dll); free(adlh); return 0; } int wrap_adl_get_gpucount(wrap_adl_handle* adlh, int* gpucount) { *gpucount = adlh->adl_gpucount; return 0; } int wrap_adl_get_gpu_name(wrap_adl_handle* adlh, int gpuindex, char* namebuf, int bufsize) { if (gpuindex < 0 || gpuindex >= adlh->adl_gpucount) return -1; memcpy(namebuf, adlh->devs[adlh->phys_logi_device_id[gpuindex]].strAdapterName, bufsize); return 0; } int wrap_adl_get_gpu_pci_id(wrap_adl_handle* adlh, int gpuindex, char* idbuf, int bufsize) { if (gpuindex < 0 || gpuindex >= adlh->adl_gpucount) return -1; char buf[256]; sprintf(buf, "%04x:%02x:%02x", 0, // Is probably 0 adlh->devs[adlh->phys_logi_device_id[gpuindex]].iBusNumber, adlh->devs[adlh->phys_logi_device_id[gpuindex]].iDeviceNumber); memcpy(idbuf, buf, bufsize); return 0; } int wrap_adl_get_tempC(wrap_adl_handle* adlh, int gpuindex, unsigned int* tempC) { if (gpuindex < 0 || gpuindex >= adlh->adl_gpucount) return -1; ADLTemperature* temperature = new ADLTemperature(); if (adlh->adlOverdrive5TemperatureGet(adlh->phys_logi_device_id[gpuindex], 0, temperature) != WRAPADL_OK) return -1; *tempC = unsigned(temperature->iTemperature / 1000); delete temperature; return 0; } int wrap_adl_get_fanpcnt(wrap_adl_handle* adlh, int gpuindex, unsigned int* fanpcnt) { if (gpuindex < 0 || gpuindex >= adlh->adl_gpucount) return -1; ADLFanSpeedValue* fan = new ADLFanSpeedValue(); fan->iSpeedType = 1; if (adlh->adlOverdrive5FanSpeedGet(adlh->phys_logi_device_id[gpuindex], 0, fan) != WRAPADL_OK) return -1; *fanpcnt = unsigned(fan->iFanSpeed); delete fan; return 0; } int wrap_adl_get_power_usage(wrap_adl_handle* adlh, int gpuindex, unsigned int* miliwatts) { if (gpuindex < 0 || gpuindex >= adlh->adl_gpucount) return -1; int power = 0; if (adlh->adl2Overdrive6CurrentPowerGet( adlh->context, adlh->phys_logi_device_id[gpuindex], 0, &power) != WRAPADL_OK) return -1; *miliwatts = (unsigned int)(power * 3.90625); return 0; } #if defined(__cplusplus) } #endif
8,015
C++
.cpp
203
33.536946
100
0.664389
ethereum-mining/ethminer
5,969
2,283
327
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
25,106
wrapamdsysfs.cpp
ethereum-mining_ethminer/libhwmon/wrapamdsysfs.cpp
/* * Wrapper for AMD SysFS on linux, using adapted code from amdcovc by matszpk * * By Philipp Andreas - github@smurfy.de */ #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <sys/types.h> #if defined(__linux) #include <dirent.h> #endif #include <boost/algorithm/string.hpp> #include <boost/filesystem.hpp> #include <algorithm> #include <climits> #include <cstdint> #include <cstring> #include <fstream> #include <iostream> #include <limits> #include <regex> #include <string> #include "wrapamdsysfs.h" #include "wraphelper.h" static bool getFileContentValue(const char* filename, unsigned int& value) { value = 0; std::ifstream ifs(filename, std::ios::binary); std::string line; std::getline(ifs, line); char* p = (char*)line.c_str(); char* p2; errno = 0; value = strtoul(p, &p2, 0); if (errno != 0) return false; return (p != p2); } wrap_amdsysfs_handle* wrap_amdsysfs_create() { wrap_amdsysfs_handle* sysfsh = nullptr; #if defined(__linux) namespace fs = boost::filesystem; std::vector<pciInfo> devices; // Used to collect devices char dbuf[120]; // Check directory exist fs::path drm_dir("/sys/class/drm"); if (!fs::exists(drm_dir) || !fs::is_directory(drm_dir)) return nullptr; // Regex patterns to identify directory elements std::regex cardPattern("^card[0-9]{1,}$"); std::regex hwmonPattern("^hwmon[0-9]{1,}$"); // Loop directory contents for (fs::directory_iterator dirEnt(drm_dir); dirEnt != fs::directory_iterator(); ++dirEnt) { // Skip non relevant entries if (!fs::is_directory(dirEnt->path()) || !std::regex_match(dirEnt->path().filename().string(), cardPattern)) continue; std::string devName = dirEnt->path().filename().string(); unsigned int devIndex = std::stoi(devName.substr(4), nullptr, 10); unsigned int vendorId = 0; unsigned int hwmonIndex = UINT_MAX; // Get AMD cards only (vendor 4098) fs::path vendor_file("/sys/class/drm/" + devName + "/device/vendor"); snprintf(dbuf, 120, "/sys/class/drm/%s/device/vendor", devName.c_str()); if (!fs::exists(vendor_file) || !fs::is_regular_file(vendor_file) || !getFileContentValue(dbuf, vendorId) || vendorId != 4098) continue; // Check it has dependant hwmon directory fs::path hwmon_dir("/sys/class/drm/" + devName + "/device/hwmon"); if (!fs::exists(hwmon_dir) || !fs::is_directory(hwmon_dir)) continue; // Loop subelements in hwmon directory for (fs::directory_iterator hwmonEnt(hwmon_dir); hwmonEnt != fs::directory_iterator(); ++hwmonEnt) { // Skip non relevant entries if (!fs::is_directory(hwmonEnt->path()) || !std::regex_match(hwmonEnt->path().filename().string(), hwmonPattern)) continue; unsigned int v = std::stoi(hwmonEnt->path().filename().string().substr(5), nullptr, 10); hwmonIndex = std::min(hwmonIndex, v); } if (hwmonIndex == UINT_MAX) continue; // Detect Pci Id fs::path uevent_file("/sys/class/drm/" + devName + "/device/uevent"); if (!fs::exists(uevent_file) || !fs::is_regular_file(uevent_file)) continue; snprintf(dbuf, 120, "/sys/class/drm/card%d/device/uevent", devIndex); std::ifstream ifs(dbuf, std::ios::binary); std::string line; int PciDomain = -1, PciBus = -1, PciDevice = -1, PciFunction = -1; while (std::getline(ifs, line)) { if (line.length() > 24 && line.substr(0, 13) == "PCI_SLOT_NAME") { std::string pciId = line.substr(14); std::vector<std::string> pciIdParts; boost::split(pciIdParts, pciId, [](char c) { return (c == ':' || c == '.'); }); try { PciDomain = std::stoi(pciIdParts.at(0), nullptr, 16); PciBus = std::stoi(pciIdParts.at(1), nullptr, 16); PciDevice = std::stoi(pciIdParts.at(2), nullptr, 16); PciFunction = std::stoi(pciIdParts.at(3), nullptr, 16); } catch (const std::exception&) { PciDomain = PciBus = PciDevice = PciFunction = -1; } break; } } // If we got an error skip if (PciDomain == -1) continue; // We got all information needed // push in the list of collected devices pciInfo pInfo = pciInfo(); pInfo.DeviceId = devIndex; pInfo.HwMonId = hwmonIndex; pInfo.PciDomain = PciDomain; pInfo.PciBus = PciBus; pInfo.PciDevice = PciDevice; devices.push_back(pInfo); } // Nothing collected - exit if (!devices.size()) { cwarn << "Failed to obtain all required AMD file pointers"; cwarn << "AMD hardware monitoring disabled"; return nullptr; } unsigned int gpucount = devices.size(); sysfsh = (wrap_amdsysfs_handle*)calloc(1, sizeof(wrap_amdsysfs_handle)); if (sysfsh == nullptr) { cwarn << "Failed allocate memory"; cwarn << "AMD hardware monitoring disabled"; return sysfsh; } sysfsh->sysfs_gpucount = gpucount; sysfsh->sysfs_device_id = (unsigned int*)calloc(gpucount, sizeof(unsigned int)); sysfsh->sysfs_hwmon_id = (unsigned int*)calloc(gpucount, sizeof(unsigned int)); sysfsh->sysfs_pci_domain_id = (unsigned int*)calloc(gpucount, sizeof(unsigned int)); sysfsh->sysfs_pci_bus_id = (unsigned int*)calloc(gpucount, sizeof(unsigned int)); sysfsh->sysfs_pci_device_id = (unsigned int*)calloc(gpucount, sizeof(unsigned int)); gpucount = 0; for (auto const& device : devices) { sysfsh->sysfs_device_id[gpucount] = device.DeviceId; sysfsh->sysfs_hwmon_id[gpucount] = device.HwMonId; sysfsh->sysfs_pci_domain_id[gpucount] = device.PciDomain; sysfsh->sysfs_pci_bus_id[gpucount] = device.PciBus; sysfsh->sysfs_pci_device_id[gpucount] = device.PciDevice; gpucount++; } #endif return sysfsh; } int wrap_amdsysfs_destroy(wrap_amdsysfs_handle* sysfsh) { free(sysfsh); return 0; } int wrap_amdsysfs_get_gpucount(wrap_amdsysfs_handle* sysfsh, int* gpucount) { *gpucount = sysfsh->sysfs_gpucount; return 0; } int wrap_amdsysfs_get_tempC(wrap_amdsysfs_handle* sysfsh, int index, unsigned int* tempC) { if (index < 0 || index >= sysfsh->sysfs_gpucount) return -1; int gpuindex = sysfsh->sysfs_device_id[index]; int hwmonindex = sysfsh->sysfs_hwmon_id[index]; if (hwmonindex < 0) return -1; char dbuf[120]; snprintf( dbuf, 120, "/sys/class/drm/card%d/device/hwmon/hwmon%d/temp1_input", gpuindex, hwmonindex); unsigned int temp = 0; getFileContentValue(dbuf, temp); if (temp > 0) *tempC = temp / 1000; return 0; } int wrap_amdsysfs_get_fanpcnt(wrap_amdsysfs_handle* sysfsh, int index, unsigned int* fanpcnt) { if (index < 0 || index >= sysfsh->sysfs_gpucount) return -1; int gpuindex = sysfsh->sysfs_device_id[index]; int hwmonindex = sysfsh->sysfs_hwmon_id[index]; if (hwmonindex < 0) return -1; unsigned int pwm = 0, pwmMax = 255, pwmMin = 0; char dbuf[120]; snprintf(dbuf, 120, "/sys/class/drm/card%d/device/hwmon/hwmon%d/pwm1", gpuindex, hwmonindex); getFileContentValue(dbuf, pwm); snprintf( dbuf, 120, "/sys/class/drm/card%d/device/hwmon/hwmon%d/pwm1_max", gpuindex, hwmonindex); getFileContentValue(dbuf, pwmMax); snprintf( dbuf, 120, "/sys/class/drm/card%d/device/hwmon/hwmon%d/pwm1_min", gpuindex, hwmonindex); getFileContentValue(dbuf, pwmMin); *fanpcnt = (unsigned int)(double(pwm - pwmMin) / double(pwmMax - pwmMin) * 100.0); return 0; } int wrap_amdsysfs_get_power_usage(wrap_amdsysfs_handle* sysfsh, int index, unsigned int* milliwatts) { try { if (index < 0 || index >= sysfsh->sysfs_gpucount) return -1; int gpuindex = sysfsh->sysfs_device_id[index]; char dbuf[120]; snprintf(dbuf, 120, "/sys/kernel/debug/dri/%d/amdgpu_pm_info", gpuindex); std::ifstream ifs(dbuf, std::ios::binary); std::string line; while (std::getline(ifs, line)) { std::smatch sm; std::regex regex(R"(([\d|\.]+) W \(average GPU\))"); if (std::regex_search(line, sm, regex)) { if (sm.size() == 2) { double watt = atof(sm.str(1).c_str()); *milliwatts = (unsigned int)(watt * 1000); return 0; } } } } catch (const std::exception& ex) { cwarn << "Error in amdsysfs_get_power_usage: " << ex.what(); } return -1; }
9,118
C++
.cpp
243
29.946502
100
0.601586
ethereum-mining/ethminer
5,969
2,283
327
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
25,110
CPUMiner.cpp
ethereum-mining_ethminer/libethash-cpu/CPUMiner.cpp
/* This file is part of ethminer. ethminer is free software: you can 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. ethminer 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 ethminer. If not, see <http://www.gnu.org/licenses/>. */ /* CPUMiner simulates mining devices but does NOT real mine! USE FOR DEVELOPMENT ONLY ! */ #if defined(__linux__) #if !defined(_GNU_SOURCE) #define _GNU_SOURCE /* we need sched_setaffinity() */ #endif #include <error.h> #include <sched.h> #include <unistd.h> #endif #include <libethcore/Farm.h> #include <ethash/ethash.hpp> #include <boost/version.hpp> #if 0 #include <boost/fiber/numa/pin_thread.hpp> #include <boost/fiber/numa/topology.hpp> #endif #include "CPUMiner.h" /* Sanity check for defined OS */ #if defined(__APPLE__) || defined(__MACOSX) /* MACOSX */ #include <mach/mach.h> #elif defined(__linux__) /* linux */ #elif defined(_WIN32) /* windows */ #else #error "Invalid OS configuration" #endif using namespace std; using namespace dev; using namespace eth; /* ################## OS-specific functions ################## */ /* * returns physically available memory (no swap) */ static size_t getTotalPhysAvailableMemory() { #if defined(__APPLE__) || defined(__MACOSX) vm_statistics64_data_t vm_stat; vm_size_t page_size; host_name_port_t host = mach_host_self(); kern_return_t rv = host_page_size(host, &page_size); if( rv != KERN_SUCCESS) { cwarn << "Error in func " << __FUNCTION__ << " at host_page_size(...) \"" << "\"\n"; mach_error("host_page_size(...) error :", rv); return 0; } mach_msg_type_number_t count = HOST_VM_INFO_COUNT; rv = host_statistics (host, HOST_VM_INFO, (host_info_t)&vm_stat, &count); if (rv != KERN_SUCCESS) { cwarn << "Error in func " << __FUNCTION__ << " at host_statistics(...) \"" << "\"\n"; mach_error("host_statistics(...) error :", rv); return 0; } return vm_stat.free_count*page_size; #elif defined(__linux__) long pages = sysconf(_SC_AVPHYS_PAGES); if (pages == -1L) { cwarn << "Error in func " << __FUNCTION__ << " at sysconf(_SC_AVPHYS_PAGES) \"" << strerror(errno) << "\"\n"; return 0; } long page_size = sysconf(_SC_PAGESIZE); if (page_size == -1L) { cwarn << "Error in func " << __FUNCTION__ << " at sysconf(_SC_PAGESIZE) \"" << strerror(errno) << "\"\n"; return 0; } return (size_t)pages * (size_t)page_size; #else MEMORYSTATUSEX memInfo; memInfo.dwLength = sizeof(MEMORYSTATUSEX); if (GlobalMemoryStatusEx(&memInfo) == 0) { // Handle Errorcode (GetLastError) ?? return 0; } return memInfo.ullAvailPhys; #endif } /* * return numbers of available CPUs */ unsigned CPUMiner::getNumDevices() { #if 0 static unsigned cpus = 0; if (cpus == 0) { std::vector< boost::fibers::numa::node > topo = boost::fibers::numa::topology(); for (auto n : topo) { cpus += n.logical_cpus.size(); } } return cpus; #elif defined(__APPLE__) || defined(__MACOSX) unsigned int cpus_available = std::thread::hardware_concurrency(); if (cpus_available <= 0) { cwarn << "Error in func " << __FUNCTION__ << " at std::thread::hardware_concurrency \"" << cpus_available << " were found." << "\"\n"; return 0; } return cpus_available; #elif defined(__linux__) long cpus_available; cpus_available = sysconf(_SC_NPROCESSORS_ONLN); if (cpus_available == -1L) { cwarn << "Error in func " << __FUNCTION__ << " at sysconf(_SC_NPROCESSORS_ONLN) \"" << strerror(errno) << "\"\n"; return 0; } return cpus_available; #else SYSTEM_INFO sysinfo; GetSystemInfo(&sysinfo); return sysinfo.dwNumberOfProcessors; #endif } /* ######################## CPU Miner ######################## */ struct CPUChannel : public LogChannel { static const char* name() { return EthOrange "cp"; } static const int verbosity = 2; }; #define cpulog clog(CPUChannel) CPUMiner::CPUMiner(unsigned _index, CPSettings _settings, DeviceDescriptor& _device) : Miner("cpu-", _index), m_settings(_settings) { m_deviceDescriptor = _device; } CPUMiner::~CPUMiner() { DEV_BUILD_LOG_PROGRAMFLOW(cpulog, "cp-" << m_index << " CPUMiner::~CPUMiner() begin"); stopWorking(); kick_miner(); DEV_BUILD_LOG_PROGRAMFLOW(cpulog, "cp-" << m_index << " CPUMiner::~CPUMiner() end"); } /* * Bind the current thread to a spcific CPU */ bool CPUMiner::initDevice() { DEV_BUILD_LOG_PROGRAMFLOW(cpulog, "cp-" << m_index << " CPUMiner::initDevice begin"); cpulog << "Using CPU: " << m_deviceDescriptor.cpCpuNumer << " " << m_deviceDescriptor.cuName << " Memory : " << dev::getFormattedMemory((double)m_deviceDescriptor.totalMemory); #if defined(__APPLE__) || defined(__MACOSX) /* Not supported on MAC OSX. See https://developer.apple.com/library/archive/releasenotes/Performance/RN-AffinityAPI/ */ #elif defined(__linux__) cpu_set_t cpuset; int err; CPU_ZERO(&cpuset); CPU_SET(m_deviceDescriptor.cpCpuNumer, &cpuset); err = sched_setaffinity(0, sizeof(cpuset), &cpuset); if (err != 0) { cwarn << "Error in func " << __FUNCTION__ << " at sched_setaffinity() \"" << strerror(errno) << "\"\n"; cwarn << "cp-" << m_index << "could not bind thread to cpu" << m_deviceDescriptor.cpCpuNumer << "\n"; } #else DWORD_PTR dwThreadAffinityMask = 1i64 << m_deviceDescriptor.cpCpuNumer; DWORD_PTR previous_mask; previous_mask = SetThreadAffinityMask(GetCurrentThread(), dwThreadAffinityMask); if (previous_mask == NULL) { cwarn << "cp-" << m_index << "could not bind thread to cpu" << m_deviceDescriptor.cpCpuNumer << "\n"; // Handle Errorcode (GetLastError) ?? } #endif DEV_BUILD_LOG_PROGRAMFLOW(cpulog, "cp-" << m_index << " CPUMiner::initDevice end"); return true; } /* * A new epoch was receifed with last work package (called from Miner::initEpoch()) * * If we get here it means epoch has changed so it's not necessary * to check again dag sizes. They're changed for sure * We've all related infos in m_epochContext (.dagSize, .dagNumItems, .lightSize, .lightNumItems) */ bool CPUMiner::initEpoch_internal() { return true; } /* Miner should stop working on the current block This happens if a * new work arrived or * miner should stop (eg exit ethminer) or * miner should pause */ void CPUMiner::kick_miner() { m_new_work.store(true, std::memory_order_relaxed); m_new_work_signal.notify_one(); } void CPUMiner::search(const dev::eth::WorkPackage& w) { constexpr size_t blocksize = 30; const auto& context = ethash::get_global_epoch_context_full(w.epoch); const auto header = ethash::hash256_from_bytes(w.header.data()); const auto boundary = ethash::hash256_from_bytes(w.boundary.data()); auto nonce = w.startNonce; while (true) { if (m_new_work.load(std::memory_order_relaxed)) // new work arrived ? { m_new_work.store(false, std::memory_order_relaxed); break; } if (shouldStop()) break; auto r = ethash::search(context, header, boundary, nonce, blocksize); if (r.solution_found) { h256 mix{reinterpret_cast<byte*>(r.mix_hash.bytes), h256::ConstructFromPointer}; auto sol = Solution{r.nonce, mix, w, std::chrono::steady_clock::now(), m_index}; cpulog << EthWhite << "Job: " << w.header.abridged() << " Sol: " << toHex(sol.nonce, HexPrefix::Add) << EthReset; Farm::f().submitProof(sol); } nonce += blocksize; // Update the hash rate updateHashRate(blocksize, 1); } } /* * The main work loop of a Worker thread */ void CPUMiner::workLoop() { DEV_BUILD_LOG_PROGRAMFLOW(cpulog, "cp-" << m_index << " CPUMiner::workLoop() begin"); WorkPackage current; current.header = h256(); if (!initDevice()) return; while (!shouldStop()) { // Wait for work or 3 seconds (whichever the first) const WorkPackage w = work(); if (!w) { boost::system_time const timeout = boost::get_system_time() + boost::posix_time::seconds(3); boost::mutex::scoped_lock l(x_work); m_new_work_signal.timed_wait(l, timeout); continue; } if (w.algo == "ethash") { // Epoch change ? if (current.epoch != w.epoch) { if (!initEpoch()) break; // This will simply exit the thread // As DAG generation takes a while we need to // ensure we're on latest job, not on the one // which triggered the epoch change current = w; continue; } // Persist most recent job. // Job's differences should be handled at higher level current = w; // Start searching search(w); } else { throw std::runtime_error("Algo : " + w.algo + " not yet implemented"); } } DEV_BUILD_LOG_PROGRAMFLOW(cpulog, "cp-" << m_index << " CPUMiner::workLoop() end"); } void CPUMiner::enumDevices(std::map<string, DeviceDescriptor>& _DevicesCollection) { unsigned numDevices = getNumDevices(); for (unsigned i = 0; i < numDevices; i++) { string uniqueId; ostringstream s; DeviceDescriptor deviceDescriptor; s << "cpu-" << i; uniqueId = s.str(); if (_DevicesCollection.find(uniqueId) != _DevicesCollection.end()) deviceDescriptor = _DevicesCollection[uniqueId]; else deviceDescriptor = DeviceDescriptor(); s.str(""); s.clear(); s << "ethash::eval()/boost " << (BOOST_VERSION / 100000) << "." << (BOOST_VERSION / 100 % 1000) << "." << (BOOST_VERSION % 100); deviceDescriptor.name = s.str(); deviceDescriptor.uniqueId = uniqueId; deviceDescriptor.type = DeviceTypeEnum::Cpu; deviceDescriptor.totalMemory = getTotalPhysAvailableMemory(); deviceDescriptor.cpCpuNumer = i; _DevicesCollection[uniqueId] = deviceDescriptor; } }
10,997
C++
.cpp
323
28.226006
120
0.612347
ethereum-mining/ethminer
5,969
2,283
327
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
true
false
true
false
25,112
EthashAux.cpp
ethereum-mining_ethminer/libethcore/EthashAux.cpp
/* This file is part of ethminer. ethminer is free software: you can 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. ethminer 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 ethminer. If not, see <http://www.gnu.org/licenses/>. */ #include "EthashAux.h" #include <ethash/ethash.hpp> using namespace dev; using namespace eth; Result EthashAux::eval(int epoch, h256 const& _headerHash, uint64_t _nonce) noexcept { auto headerHash = ethash::hash256_from_bytes(_headerHash.data()); auto& context = ethash::get_global_epoch_context(epoch); auto result = ethash::hash(context, headerHash, _nonce); h256 mix{reinterpret_cast<byte*>(result.mix_hash.bytes), h256::ConstructFromPointer}; h256 final{reinterpret_cast<byte*>(result.final_hash.bytes), h256::ConstructFromPointer}; return {final, mix}; }
1,269
C++
.cpp
26
44.961538
93
0.751011
ethereum-mining/ethminer
5,969
2,283
327
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
25,113
Miner.cpp
ethereum-mining_ethminer/libethcore/Miner.cpp
/* This file is part of ethereum. ethminer is free software: you can 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. ethereum 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 ethminer. If not, see <http://www.gnu.org/licenses/>. */ #include "Miner.h" namespace dev { namespace eth { unsigned Miner::s_dagLoadMode = 0; unsigned Miner::s_dagLoadIndex = 0; unsigned Miner::s_minersCount = 0; FarmFace* FarmFace::m_this = nullptr; DeviceDescriptor Miner::getDescriptor() { return m_deviceDescriptor; } void Miner::setWork(WorkPackage const& _work) { { boost::mutex::scoped_lock l(x_work); // Void work if this miner is paused if (paused()) m_work.header = h256(); else m_work = _work; #ifdef DEV_BUILD m_workSwitchStart = std::chrono::steady_clock::now(); #endif } kick_miner(); } void Miner::pause(MinerPauseEnum what) { boost::mutex::scoped_lock l(x_pause); m_pauseFlags.set(what); m_work.header = h256(); kick_miner(); } bool Miner::paused() { boost::mutex::scoped_lock l(x_pause); return m_pauseFlags.any(); } bool Miner::pauseTest(MinerPauseEnum what) { boost::mutex::scoped_lock l(x_pause); return m_pauseFlags.test(what); } std::string Miner::pausedString() { boost::mutex::scoped_lock l(x_pause); std::string retVar; if (m_pauseFlags.any()) { for (int i = 0; i < MinerPauseEnum::Pause_MAX; i++) { if (m_pauseFlags[(MinerPauseEnum)i]) { if (!retVar.empty()) retVar.append("; "); if (i == MinerPauseEnum::PauseDueToOverHeating) retVar.append("Overheating"); else if (i == MinerPauseEnum::PauseDueToAPIRequest) retVar.append("Api request"); else if (i == MinerPauseEnum::PauseDueToFarmPaused) retVar.append("Farm suspended"); else if (i == MinerPauseEnum::PauseDueToInsufficientMemory) retVar.append("Insufficient GPU memory"); else if (i == MinerPauseEnum::PauseDueToInitEpochError) retVar.append("Epoch initialization error"); } } } return retVar; } void Miner::resume(MinerPauseEnum fromwhat) { boost::mutex::scoped_lock l(x_pause); m_pauseFlags.reset(fromwhat); //if (!m_pauseFlags.any()) //{ // // TODO Push most recent job from farm ? // // If we do not push a new job the miner will stay idle // // till a new job arrives //} } float Miner::RetrieveHashRate() noexcept { return m_hashRate.load(std::memory_order_relaxed); } void Miner::TriggerHashRateUpdate() noexcept { bool b = false; if (m_hashRateUpdate.compare_exchange_strong(b, true)) return; // GPU didn't respond to last trigger, assume it's dead. // This can happen on CUDA if: // runtime of --cuda-grid-size * --cuda-streams exceeds time of m_collectInterval m_hashRate = 0.0; } bool Miner::initEpoch() { // When loading of DAG is sequential wait for // this instance to become current if (s_dagLoadMode == DAG_LOAD_MODE_SEQUENTIAL) { while (s_dagLoadIndex < m_index) { boost::system_time const timeout = boost::get_system_time() + boost::posix_time::seconds(3); boost::mutex::scoped_lock l(x_work); m_dag_loaded_signal.timed_wait(l, timeout); } if (shouldStop()) return false; } // Run the internal initialization // specific for miner bool result = initEpoch_internal(); // Advance to next miner or reset to zero for // next run if all have processed if (s_dagLoadMode == DAG_LOAD_MODE_SEQUENTIAL) { s_dagLoadIndex = (m_index + 1); if (s_minersCount == s_dagLoadIndex) s_dagLoadIndex = 0; else m_dag_loaded_signal.notify_all(); } return result; } WorkPackage Miner::work() const { boost::mutex::scoped_lock l(x_work); return m_work; } void Miner::updateHashRate(uint32_t _groupSize, uint32_t _increment) noexcept { m_groupCount += _increment; bool b = true; if (!m_hashRateUpdate.compare_exchange_strong(b, false)) return; using namespace std::chrono; auto t = steady_clock::now(); auto us = duration_cast<microseconds>(t - m_hashTime).count(); m_hashTime = t; m_hashRate.store( us ? (float(m_groupCount * _groupSize) * 1.0e6f) / us : 0.0f, std::memory_order_relaxed); m_groupCount = 0; } } // namespace eth } // namespace dev
5,100
C++
.cpp
162
25.62963
97
0.639495
ethereum-mining/ethminer
5,969
2,283
327
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
25,114
CUDAMiner.cpp
ethereum-mining_ethminer/libethash-cuda/CUDAMiner.cpp
/* This file is part of ethminer. ethminer is free software: you can 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. ethminer 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 ethminer. If not, see <http://www.gnu.org/licenses/>. */ #include <libethcore/Farm.h> #include <ethash/ethash.hpp> #include "CUDAMiner.h" using namespace std; using namespace dev; using namespace eth; struct CUDAChannel : public LogChannel { static const char* name() { return EthOrange "cu"; } static const int verbosity = 2; }; #define cudalog clog(CUDAChannel) CUDAMiner::CUDAMiner(unsigned _index, CUSettings _settings, DeviceDescriptor& _device) : Miner("cuda-", _index), m_settings(_settings), m_batch_size(_settings.gridSize * _settings.blockSize), m_streams_batch_size(_settings.gridSize * _settings.blockSize * _settings.streams) { m_deviceDescriptor = _device; } CUDAMiner::~CUDAMiner() { DEV_BUILD_LOG_PROGRAMFLOW(cudalog, "cuda-" << m_index << " CUDAMiner::~CUDAMiner() begin"); stopWorking(); kick_miner(); DEV_BUILD_LOG_PROGRAMFLOW(cudalog, "cuda-" << m_index << " CUDAMiner::~CUDAMiner() end"); } bool CUDAMiner::initDevice() { cudalog << "Using Pci Id : " << m_deviceDescriptor.uniqueId << " " << m_deviceDescriptor.cuName << " (Compute " + m_deviceDescriptor.cuCompute + ") Memory : " << dev::getFormattedMemory((double)m_deviceDescriptor.totalMemory); // Set Hardware Monitor Info m_hwmoninfo.deviceType = HwMonitorInfoType::NVIDIA; m_hwmoninfo.devicePciId = m_deviceDescriptor.uniqueId; m_hwmoninfo.deviceIndex = -1; // Will be later on mapped by nvml (see Farm() constructor) try { CUDA_SAFE_CALL(cudaSetDevice(m_deviceDescriptor.cuDeviceIndex)); CUDA_SAFE_CALL(cudaDeviceReset()); } catch (const cuda_runtime_error& ec) { cudalog << "Could not set CUDA device on Pci Id " << m_deviceDescriptor.uniqueId << " Error : " << ec.what(); cudalog << "Mining aborted on this device."; return false; } return true; } bool CUDAMiner::initEpoch_internal() { // If we get here it means epoch has changed so it's not necessary // to check again dag sizes. They're changed for sure bool retVar = false; m_current_target = 0; auto startInit = std::chrono::steady_clock::now(); size_t RequiredTotalMemory = (m_epochContext.dagSize + m_epochContext.lightSize); size_t RequiredDagMemory = m_epochContext.dagSize; // Release the pause flag if any resume(MinerPauseEnum::PauseDueToInsufficientMemory); resume(MinerPauseEnum::PauseDueToInitEpochError); bool lightOnHost = false; try { hash128_t* dag; hash64_t* light; // If we have already enough memory allocated, we just have to // copy light_cache and regenerate the DAG if (m_allocated_memory_dag < m_epochContext.dagSize || m_allocated_memory_light_cache < m_epochContext.lightSize) { // We need to reset the device and (re)create the dag // cudaDeviceReset() frees all previous allocated memory CUDA_SAFE_CALL(cudaDeviceReset()); CUDA_SAFE_CALL(cudaSetDeviceFlags(m_settings.schedule)); CUDA_SAFE_CALL(cudaDeviceSetCacheConfig(cudaFuncCachePreferL1)); // Check whether the current device has sufficient memory every time we recreate the dag if (m_deviceDescriptor.totalMemory < RequiredTotalMemory) { if (m_deviceDescriptor.totalMemory < RequiredDagMemory) { cudalog << "Epoch " << m_epochContext.epochNumber << " requires " << dev::getFormattedMemory((double)RequiredDagMemory) << " memory."; cudalog << "This device hasn't enough memory available. Mining suspended ..."; pause(MinerPauseEnum::PauseDueToInsufficientMemory); return true; // This will prevent to exit the thread and // Eventually resume mining when changing coin or epoch (NiceHash) } else lightOnHost = true; } cudalog << "Generating DAG + Light(on " << (lightOnHost ? "host" : "GPU") << ") : " << dev::getFormattedMemory((double)RequiredTotalMemory); // create buffer for cache if (lightOnHost) { CUDA_SAFE_CALL(cudaHostAlloc(reinterpret_cast<void**>(&light), m_epochContext.lightSize, cudaHostAllocDefault)); cudalog << "WARNING: Generating DAG will take minutes, not seconds"; } else CUDA_SAFE_CALL( cudaMalloc(reinterpret_cast<void**>(&light), m_epochContext.lightSize)); m_allocated_memory_light_cache = m_epochContext.lightSize; CUDA_SAFE_CALL(cudaMalloc(reinterpret_cast<void**>(&dag), m_epochContext.dagSize)); m_allocated_memory_dag = m_epochContext.dagSize; // create mining buffers for (unsigned i = 0; i != m_settings.streams; ++i) { CUDA_SAFE_CALL(cudaMallocHost(&m_search_buf[i], sizeof(Search_results))); CUDA_SAFE_CALL(cudaStreamCreateWithFlags(&m_streams[i], cudaStreamNonBlocking)); } } else { cudalog << "Generating DAG + Light (reusing buffers): " << dev::getFormattedMemory((double)RequiredTotalMemory); get_constants(&dag, NULL, &light, NULL); } CUDA_SAFE_CALL(cudaMemcpy(reinterpret_cast<void*>(light), m_epochContext.lightCache, m_epochContext.lightSize, cudaMemcpyHostToDevice)); set_constants(dag, m_epochContext.dagNumItems, light, m_epochContext.lightNumItems); // in ethash_cuda_miner_kernel.cu ethash_generate_dag( m_epochContext.dagSize, m_settings.gridSize, m_settings.blockSize, m_streams[0]); cudalog << "Generated DAG + Light in " << std::chrono::duration_cast<std::chrono::milliseconds>( std::chrono::steady_clock::now() - startInit) .count() << " ms. " << dev::getFormattedMemory( lightOnHost ? (double)(m_deviceDescriptor.totalMemory - RequiredDagMemory) : (double)(m_deviceDescriptor.totalMemory - RequiredTotalMemory)) << " left."; retVar = true; } catch (const cuda_runtime_error& ec) { cudalog << "Unexpected error " << ec.what() << " on CUDA device " << m_deviceDescriptor.uniqueId; cudalog << "Mining suspended ..."; pause(MinerPauseEnum::PauseDueToInitEpochError); retVar = true; } return retVar; } void CUDAMiner::workLoop() { WorkPackage current; current.header = h256(); m_search_buf.resize(m_settings.streams); m_streams.resize(m_settings.streams); if (!initDevice()) return; try { while (!shouldStop()) { // Wait for work or 3 seconds (whichever the first) const WorkPackage w = work(); if (!w) { boost::system_time const timeout = boost::get_system_time() + boost::posix_time::seconds(3); boost::mutex::scoped_lock l(x_work); m_new_work_signal.timed_wait(l, timeout); continue; } // Epoch change ? if (current.epoch != w.epoch) { if (!initEpoch()) break; // This will simply exit the thread // As DAG generation takes a while we need to // ensure we're on latest job, not on the one // which triggered the epoch change current = w; continue; } // Persist most recent job. // Job's differences should be handled at higher level current = w; uint64_t upper64OfBoundary = (uint64_t)(u64)((u256)current.boundary >> 192); // Eventually start searching search(current.header.data(), upper64OfBoundary, current.startNonce, w); } // Reset miner and stop working CUDA_SAFE_CALL(cudaDeviceReset()); } catch (cuda_runtime_error const& _e) { string _what = "GPU error: "; _what.append(_e.what()); throw std::runtime_error(_what); } } void CUDAMiner::kick_miner() { m_new_work.store(true, std::memory_order_relaxed); m_new_work_signal.notify_one(); } int CUDAMiner::getNumDevices() { int deviceCount; cudaError_t err = cudaGetDeviceCount(&deviceCount); if (err == cudaSuccess) return deviceCount; if (err == cudaErrorInsufficientDriver) { int driverVersion = 0; cudaDriverGetVersion(&driverVersion); if (driverVersion == 0) std::cerr << "CUDA Error : No CUDA driver found" << std::endl; else std::cerr << "CUDA Error : Insufficient CUDA driver " << std::to_string(driverVersion) << std::endl; } else { std::cerr << "CUDA Error : " << cudaGetErrorString(err) << std::endl; } return 0; } void CUDAMiner::enumDevices(std::map<string, DeviceDescriptor>& _DevicesCollection) { int numDevices = getNumDevices(); for (int i = 0; i < numDevices; i++) { string uniqueId; ostringstream s; DeviceDescriptor deviceDescriptor; cudaDeviceProp props; try { size_t freeMem, totalMem; CUDA_SAFE_CALL(cudaGetDeviceProperties(&props, i)); CUDA_SAFE_CALL(cudaMemGetInfo(&freeMem, &totalMem)); s << setw(2) << setfill('0') << hex << props.pciBusID << ":" << setw(2) << props.pciDeviceID << ".0"; uniqueId = s.str(); if (_DevicesCollection.find(uniqueId) != _DevicesCollection.end()) deviceDescriptor = _DevicesCollection[uniqueId]; else deviceDescriptor = DeviceDescriptor(); deviceDescriptor.name = string(props.name); deviceDescriptor.cuDetected = true; deviceDescriptor.uniqueId = uniqueId; deviceDescriptor.type = DeviceTypeEnum::Gpu; deviceDescriptor.cuDeviceIndex = i; deviceDescriptor.cuDeviceOrdinal = i; deviceDescriptor.cuName = string(props.name); deviceDescriptor.totalMemory = freeMem; deviceDescriptor.cuCompute = (to_string(props.major) + "." + to_string(props.minor)); deviceDescriptor.cuComputeMajor = props.major; deviceDescriptor.cuComputeMinor = props.minor; _DevicesCollection[uniqueId] = deviceDescriptor; } catch (const cuda_runtime_error& _e) { std::cerr << _e.what() << std::endl; } } } void CUDAMiner::search( uint8_t const* header, uint64_t target, uint64_t start_nonce, const dev::eth::WorkPackage& w) { set_header(*reinterpret_cast<hash32_t const*>(header)); if (m_current_target != target) { set_target(target); m_current_target = target; } // prime each stream, clear search result buffers and start the search uint32_t current_index; for (current_index = 0; current_index < m_settings.streams; current_index++, start_nonce += m_batch_size) { cudaStream_t stream = m_streams[current_index]; volatile Search_results& buffer(*m_search_buf[current_index]); buffer.count = 0; // Run the batch for this stream run_ethash_search(m_settings.gridSize, m_settings.blockSize, stream, &buffer, start_nonce); } // process stream batches until we get new work. bool done = false; while (!done) { // Exit next time around if there's new work awaiting bool t = true; done = m_new_work.compare_exchange_strong(t, false); // Check on every batch if we need to suspend mining if (!done) done = paused(); // This inner loop will process each cuda stream individually for (current_index = 0; current_index < m_settings.streams; current_index++, start_nonce += m_batch_size) { // Each pass of this loop will wait for a stream to exit, // save any found solutions, then restart the stream // on the next group of nonces. cudaStream_t stream = m_streams[current_index]; // Wait for the stream complete CUDA_SAFE_CALL(cudaStreamSynchronize(stream)); if (shouldStop()) { m_new_work.store(false, std::memory_order_relaxed); done = true; } // Detect solutions in current stream's solution buffer volatile Search_results& buffer(*m_search_buf[current_index]); uint32_t found_count = std::min((unsigned)buffer.count, MAX_SEARCH_RESULTS); uint32_t gids[MAX_SEARCH_RESULTS]; h256 mixes[MAX_SEARCH_RESULTS]; if (found_count) { buffer.count = 0; // Extract solution and pass to higer level // using io_service as dispatcher for (uint32_t i = 0; i < found_count; i++) { gids[i] = buffer.result[i].gid; memcpy(mixes[i].data(), (void*)&buffer.result[i].mix, sizeof(buffer.result[i].mix)); } } // restart the stream on the next batch of nonces // unless we are done for this round. if (!done) run_ethash_search( m_settings.gridSize, m_settings.blockSize, stream, &buffer, start_nonce); if (found_count) { uint64_t nonce_base = start_nonce - m_streams_batch_size; for (uint32_t i = 0; i < found_count; i++) { uint64_t nonce = nonce_base + gids[i]; Farm::f().submitProof( Solution{nonce, mixes[i], w, std::chrono::steady_clock::now(), m_index}); cudalog << EthWhite << "Job: " << w.header.abridged() << " Sol: 0x" << toHex(nonce) << EthReset; } } } // Update the hash rate updateHashRate(m_batch_size, m_settings.streams); // Bail out if it's shutdown time if (shouldStop()) { m_new_work.store(false, std::memory_order_relaxed); break; } } #ifdef DEV_BUILD // Optionally log job switch time if (!shouldStop() && (g_logOptions & LOG_SWITCH)) cudalog << "Switch time: " << std::chrono::duration_cast<std::chrono::milliseconds>( std::chrono::steady_clock::now() - m_workSwitchStart) .count() << " ms."; #endif }
15,796
C++
.cpp
377
31.689655
100
0.591546
ethereum-mining/ethminer
5,969
2,283
327
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
25,115
ApiServer.h
ethereum-mining_ethminer/libapicore/ApiServer.h
#pragma once #include <regex> #include <boost/asio.hpp> #include <boost/bind.hpp> #include <boost/shared_ptr.hpp> #include <json/json.h> #include <libethcore/Farm.h> #include <libethcore/Miner.h> #include <libpoolprotocols/PoolManager.h> using namespace dev; using namespace dev::eth; using namespace std::chrono; using boost::asio::ip::tcp; class ApiConnection { public: ApiConnection(boost::asio::io_service::strand& _strand, int id, bool readonly, string password); ~ApiConnection() = default; void start(); Json::Value getMinerStat1(); using Disconnected = std::function<void(int const&)>; void onDisconnected(Disconnected const& _handler) { m_onDisconnected = _handler; } int getId() { return m_sessionId; } tcp::socket& socket() { return m_socket; } private: void disconnect(); void processRequest(Json::Value& jRequest, Json::Value& jResponse); void recvSocketData(); void onRecvSocketDataCompleted( const boost::system::error_code& ec, std::size_t bytes_transferred); void sendSocketData(Json::Value const& jReq, bool _disconnect = false); void sendSocketData(std::string const& _s, bool _disconnect = false); void onSendSocketDataCompleted(const boost::system::error_code& ec, bool _disconnect = false); Json::Value getMinerStatDetail(); Json::Value getMinerStatDetailPerMiner(const TelemetryType& _t, std::shared_ptr<Miner> _miner); std::string getHttpMinerStatDetail(); Disconnected m_onDisconnected; int m_sessionId; tcp::socket m_socket; boost::asio::io_service::strand& m_io_strand; boost::asio::streambuf m_sendBuffer; boost::asio::streambuf m_recvBuffer; Json::StreamWriterBuilder m_jSwBuilder; std::string m_message; // The internal message string buffer bool m_readonly = false; std::string m_password = ""; bool m_is_authenticated = true; }; class ApiServer { public: ApiServer(string address, int portnum, string password); bool isRunning() { return m_running.load(std::memory_order_relaxed); }; void start(); void stop(); private: void begin_accept(); void handle_accept(std::shared_ptr<ApiConnection> session, boost::system::error_code ec); int lastSessionId = 0; std::thread m_workThread; std::atomic<bool> m_readonly = {false}; std::string m_password = ""; std::atomic<bool> m_running = {false}; string m_address; uint16_t m_portnumber; tcp::acceptor m_acceptor; boost::asio::io_service::strand m_io_strand; std::vector<std::shared_ptr<ApiConnection>> m_sessions; };
2,608
C++
.h
69
33.666667
100
0.718041
ethereum-mining/ethminer
5,969
2,283
327
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
25,116
PoolManager.h
ethereum-mining_ethminer/libpoolprotocols/PoolManager.h
#pragma once #include <iostream> #include <json/json.h> #include <libdevcore/Worker.h> #include <libethcore/Farm.h> #include <libethcore/Miner.h> #include "PoolClient.h" #include "getwork/EthGetworkClient.h" #include "stratum/EthStratumClient.h" #include "testing/SimulateClient.h" using namespace std; namespace dev { namespace eth { struct PoolSettings { std::vector<std::shared_ptr<URI>> connections; // List of connection definitions unsigned getWorkPollInterval = 500; // Interval (ms) between getwork requests unsigned noWorkTimeout = 180; // If no new jobs in this number of seconds drop connection unsigned noResponseTimeout = 2; // If no response in this number of seconds drop connection unsigned poolFailoverTimeout = 0; // Return to primary pool after this number of minutes bool reportHashrate = false; // Whether or not to report hashrate to pool unsigned hashRateInterval = 60; // Interval in seconds among hashrate submissions std::string hashRateId = h256::random().hex(HexPrefix::Add); // Unique identifier for HashRate submission unsigned connectionMaxRetries = 3; // Max number of connection retries unsigned delayBeforeRetry = 0; // Delay seconds before connect retry unsigned benchmarkBlock = 0; // Block number used by SimulateClient to test performances }; class PoolManager { public: PoolManager(PoolSettings _settings); static PoolManager& p() { return *m_this; } void addConnection(std::string _connstring); void addConnection(std::shared_ptr<URI> _uri); Json::Value getConnectionsJson(); void setActiveConnection(unsigned int idx); void setActiveConnection(std::string& _connstring); std::shared_ptr<URI> getActiveConnection(); void removeConnection(unsigned int idx); void start(); void stop(); bool isConnected() { return p_client->isConnected(); }; bool isRunning() { return m_running; }; int getCurrentEpoch(); double getCurrentDifficulty(); unsigned getConnectionSwitches(); unsigned getEpochChanges(); private: void rotateConnect(); void setClientHandlers(); void showMiningAt(); void setActiveConnectionCommon(unsigned int idx); PoolSettings m_Settings; void failovertimer_elapsed(const boost::system::error_code& ec); void submithrtimer_elapsed(const boost::system::error_code& ec); void reconnecttimer_elapsed(const boost::system::error_code& ec); std::atomic<bool> m_running = {false}; std::atomic<bool> m_stopping = {false}; std::atomic<bool> m_async_pending = {false}; unsigned m_connectionAttempt = 0; std::string m_selectedHost = ""; // Holds host name (and endpoint) of selected connection std::atomic<unsigned> m_connectionSwitches = {0}; unsigned m_activeConnectionIdx = 0; WorkPackage m_currentWp; boost::asio::io_service::strand m_io_strand; boost::asio::deadline_timer m_failovertimer; boost::asio::deadline_timer m_submithrtimer; boost::asio::deadline_timer m_reconnecttimer; std::unique_ptr<PoolClient> p_client = nullptr; std::atomic<unsigned> m_epochChanges = {0}; static PoolManager* m_this; }; } // namespace eth } // namespace dev
3,274
C++
.h
77
38.467532
99
0.727473
ethereum-mining/ethminer
5,969
2,283
327
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
25,117
PoolURI.h
ethereum-mining_ethminer/libpoolprotocols/PoolURI.h
/* This file is part of ethminer. ethminer is free software: you can 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. ethminer 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 ethminer. If not, see <http://www.gnu.org/licenses/>. */ #pragma once #include <regex> #include <string> #include <boost/algorithm/string.hpp> #include <boost/asio.hpp> #include <boost/lexical_cast.hpp> // A simple URI parser specifically for mining pool endpoints namespace dev { enum class SecureLevel { NONE = 0, TLS12, TLS }; enum class ProtocolFamily { GETWORK = 0, STRATUM, SIMULATION }; enum class UriHostNameType { Unknown = 0, // The type of the host name is not supplied Basic = 1, // The host is set, but the type cannot be determined Dns = 2, // The host name is a domain name system(DNS) style host name IPV4 = 3, // The host name is an Internet Protocol(IP) version 4 host address IPV6 = 4 // The host name is an Internet Protocol(IP) version 6 host address. }; class URI { public: URI() = delete; URI(std::string uri, bool _sim = false); std::string Scheme() const { return m_scheme; } std::string Host() const { return m_host; } std::string Path() const { return m_path; } unsigned short Port() const { return m_port; } std::string User() const { return m_user; } std::string Pass() const { return m_password; } std::string Workername() const { return m_worker; } std::string UserDotWorker() const; SecureLevel SecLevel() const; ProtocolFamily Family() const; UriHostNameType HostNameType() const; bool IsLoopBack() const; unsigned Version() const; std::string str() const { return m_uri; } static std::string KnownSchemes(ProtocolFamily family); void SetStratumMode(unsigned mode, bool confirmed) { m_stratumMode = mode; m_stratumModeConfirmed = confirmed; } void SetStratumMode(unsigned mode) { m_stratumMode = mode; } unsigned StratumMode() { return m_stratumMode; } bool StratumModeConfirmed() { return m_stratumModeConfirmed; } bool IsUnrecoverable() { return m_unrecoverable; } void MarkUnrecoverable() { m_unrecoverable = true; } bool Responds() { return m_responds; } void Responds(bool _value) { m_responds = _value; } void addDuration(unsigned long _minutes) { m_totalDuration += _minutes; } unsigned long getDuration() { return m_totalDuration; } private: std::string m_scheme; std::string m_authority; // Contains all text after scheme std::string m_userinfo; // Contains the userinfo part std::string m_urlinfo; // Contains the urlinfo part std::string m_hostinfo; // Contains the hostinfo part std::string m_pathinfo; // Contains the pathinfo part std::string m_host; std::string m_path; std::string m_query; std::string m_fragment; std::string m_user; std::string m_password = "X"; std::string m_worker; std::string m_uri; unsigned short m_stratumMode = 999; // Initial value 999 means not tested yet unsigned short m_port = 0; bool m_stratumModeConfirmed = false; bool m_unrecoverable = false; bool m_responds = false; UriHostNameType m_hostType = UriHostNameType::Unknown; bool m_isLoopBack; unsigned long m_totalDuration; // Total duration on this connection in minutes }; } // namespace dev
3,863
C++
.h
101
33.990099
86
0.701417
ethereum-mining/ethminer
5,969
2,283
327
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
25,118
PoolClient.h
ethereum-mining_ethminer/libpoolprotocols/PoolClient.h
#pragma once #include <queue> #include <boost/asio/ip/address.hpp> #include <libethcore/Miner.h> #include <libpoolprotocols/PoolURI.h> extern boost::asio::io_service g_io_service; using namespace std; namespace dev { namespace eth { struct Session { // Tstamp of sessio start chrono::steady_clock::time_point start = chrono::steady_clock::now(); // Whether or not worker is subscribed atomic<bool> subscribed = {false}; // Whether or not worker is authorized atomic<bool> authorized = {false}; // Total duration of session in minutes unsigned long duration() { return (chrono::duration_cast<chrono::minutes>(chrono::steady_clock::now() - start)) .count(); } // EthereumStratum (1 and 2) // Extranonce currently active uint64_t extraNonce = 0; // Length of extranonce in bytes unsigned int extraNonceSizeBytes = 0; // Next work target h256 nextWorkBoundary = h256("0x00000000ffff0000000000000000000000000000000000000000000000000000"); // EthereumStratum (2 only) bool firstMiningSet = false; unsigned int timeout = 30; // Default to 30 seconds string sessionId = ""; string workerId = ""; string algo = "ethash"; unsigned int epoch = 0; chrono::steady_clock::time_point lastTxStamp = chrono::steady_clock::now(); }; class PoolClient { public: virtual ~PoolClient() noexcept = default; // Sets the connection definition to be used by the client void setConnection(std::shared_ptr<URI> _conn) { m_conn = _conn; m_conn->Responds(false); } // Gets a pointer to the currently active connection definition std::shared_ptr<URI> getConnection() { return m_conn; } // Releases the pointer to the connection definition void unsetConnection() { m_conn = nullptr; } virtual void connect() = 0; virtual void disconnect() = 0; virtual void submitHashrate(uint64_t const& rate, string const& id) = 0; virtual void submitSolution(const Solution& solution) = 0; virtual bool isConnected() { return m_connected.load(memory_order_relaxed); } virtual bool isPendingState() { return false; } virtual bool isSubscribed() { return (m_session ? m_session->subscribed.load(memory_order_relaxed) : false); } virtual bool isAuthorized() { return (m_session ? m_session->authorized.load(memory_order_relaxed) : false); } virtual string ActiveEndPoint() { return (m_connected.load(memory_order_relaxed) ? " [" + toString(m_endpoint) + "]" : ""); } using SolutionAccepted = function<void(chrono::milliseconds const&, unsigned const&, bool)>; using SolutionRejected = function<void(chrono::milliseconds const&, unsigned const&)>; using Disconnected = function<void()>; using Connected = function<void()>; using WorkReceived = function<void(WorkPackage const&)>; void onSolutionAccepted(SolutionAccepted const& _handler) { m_onSolutionAccepted = _handler; } void onSolutionRejected(SolutionRejected const& _handler) { m_onSolutionRejected = _handler; } void onDisconnected(Disconnected const& _handler) { m_onDisconnected = _handler; } void onConnected(Connected const& _handler) { m_onConnected = _handler; } void onWorkReceived(WorkReceived const& _handler) { m_onWorkReceived = _handler; } protected: unique_ptr<Session> m_session = nullptr; std::atomic<bool> m_connected = {false}; // This is related to socket ! Not session boost::asio::ip::basic_endpoint<boost::asio::ip::tcp> m_endpoint; std::shared_ptr<URI> m_conn = nullptr; SolutionAccepted m_onSolutionAccepted; SolutionRejected m_onSolutionRejected; Disconnected m_onDisconnected; Connected m_onConnected; WorkReceived m_onWorkReceived; }; } // namespace eth } // namespace dev
3,875
C++
.h
97
35.195876
98
0.704315
ethereum-mining/ethminer
5,969
2,283
327
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
25,120
EthGetworkClient.h
ethereum-mining_ethminer/libpoolprotocols/getwork/EthGetworkClient.h
#pragma once #include <iostream> #include <string> #include <boost/asio.hpp> #include <boost/algorithm/string/predicate.hpp> #include <boost/lexical_cast.hpp> #include <boost/lockfree/queue.hpp> #include <json/json.h> #include "../PoolClient.h" using namespace std; using namespace dev; using namespace eth; class EthGetworkClient : public PoolClient { public: EthGetworkClient(int worktimeout, unsigned farmRecheckPeriod); ~EthGetworkClient(); void connect() override; void disconnect() override; void submitHashrate(uint64_t const& rate, string const& id) override; void submitSolution(const Solution& solution) override; private: unsigned m_farmRecheckPeriod = 500; // In milliseconds void begin_connect(); void handle_resolve( const boost::system::error_code& ec, boost::asio::ip::tcp::resolver::iterator i); void handle_connect(const boost::system::error_code& ec); void handle_write(const boost::system::error_code& ec); void handle_read(const boost::system::error_code& ec, std::size_t bytes_transferred); std::string processError(Json::Value& JRes); void processResponse(Json::Value& JRes); void send(Json::Value const& jReq); void send(std::string const& sReq); void getwork_timer_elapsed(const boost::system::error_code& ec); WorkPackage m_current; std::atomic<bool> m_connecting = {false}; // Whether or not socket is on first try connect std::atomic<bool> m_txPending = {false}; // Whether or not an async socket operation is pending boost::lockfree::queue<std::string*> m_txQueue; boost::asio::io_service::strand m_io_strand; boost::asio::ip::tcp::socket m_socket; boost::asio::ip::tcp::resolver m_resolver; std::queue<boost::asio::ip::basic_endpoint<boost::asio::ip::tcp>> m_endpoints; boost::asio::streambuf m_request; boost::asio::streambuf m_response; Json::StreamWriterBuilder m_jSwBuilder; std::string m_jsonGetWork; Json::Value m_pendingJReq; std::chrono::time_point<std::chrono::steady_clock> m_pending_tstamp; boost::asio::deadline_timer m_getwork_timer; // The timer which triggers getWork requests // seconds to trigger a work_timeout (overwritten in constructor) int m_worktimeout; std::chrono::time_point<std::chrono::steady_clock> m_current_tstamp; unsigned m_solution_submitted_max_id; // maximum json id we used to send a solution };
2,438
C++
.h
54
41
100
0.729501
ethereum-mining/ethminer
5,969
2,283
327
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
25,121
SimulateClient.h
ethereum-mining_ethminer/libpoolprotocols/testing/SimulateClient.h
#pragma once #include <iostream> #include <libdevcore/Worker.h> #include <libethcore/EthashAux.h> #include <libethcore/Farm.h> #include <libethcore/Miner.h> #include "../PoolClient.h" using namespace std; using namespace dev; using namespace eth; class SimulateClient : public PoolClient, Worker { public: SimulateClient(unsigned const& block); ~SimulateClient() override; void connect() override; void disconnect() override; bool isPendingState() override { return false; } string ActiveEndPoint() override { return ""; }; void submitHashrate(uint64_t const& rate, string const& id) override; void submitSolution(const Solution& solution) override; private: void workLoop() override; unsigned m_block; std::chrono::steady_clock::time_point m_start_time; float hr_alpha = 0.45f; float hr_max = 0.0f; float hr_mean = 0.0f; };
892
C++
.h
29
27.448276
73
0.737089
ethereum-mining/ethminer
5,969
2,283
327
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
25,124
Common.h
ethereum-mining_ethminer/libdevcore/Common.h
// ethminer -- Ethereum miner with OpenCL, CUDA and stratum support. // Copyright 2018 ethminer Authors. // Licensed under GNU General Public License, Version 3. See the LICENSE file. /// @file /// Very common stuff (i.e. that every other header needs except vector_ref.h). #pragma once #include "vector_ref.h" #include <string> #include <vector> #include <boost/multiprecision/cpp_int.hpp> using byte = uint8_t; namespace dev { // Binary data types. using bytes = std::vector<byte>; using bytesRef = vector_ref<byte>; using bytesConstRef = vector_ref<byte const>; // Numeric types. using bigint = boost::multiprecision::number<boost::multiprecision::cpp_int_backend<>>; using u64 = boost::multiprecision::number<boost::multiprecision::cpp_int_backend<64, 64, boost::multiprecision::unsigned_magnitude, boost::multiprecision::unchecked, void>>; using u128 = boost::multiprecision::number<boost::multiprecision::cpp_int_backend<128, 128, boost::multiprecision::unsigned_magnitude, boost::multiprecision::unchecked, void>>; using u256 = boost::multiprecision::number<boost::multiprecision::cpp_int_backend<256, 256, boost::multiprecision::unsigned_magnitude, boost::multiprecision::unchecked, void>>; using u160 = boost::multiprecision::number<boost::multiprecision::cpp_int_backend<160, 160, boost::multiprecision::unsigned_magnitude, boost::multiprecision::unchecked, void>>; using u512 = boost::multiprecision::number<boost::multiprecision::cpp_int_backend<512, 512, boost::multiprecision::unsigned_magnitude, boost::multiprecision::unchecked, void>>; // Null/Invalid values for convenience. static const u256 Invalid256 = ~(u256)0; /// Converts arbitrary value to string representation using std::stringstream. template <class _T> std::string toString(_T const& _t) { std::ostringstream o; o << _t; return o.str(); } } // namespace dev
1,882
C++
.h
40
44.975
91
0.764063
ethereum-mining/ethminer
5,969
2,283
327
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
25,131
wrapamdsysfs.h
ethereum-mining_ethminer/libhwmon/wrapamdsysfs.h
/* * Wrapper for AMD SysFS on linux, using adapted code from amdcovc by matszpk * * By Philipp Andreas - github@smurfy.de Reworked and simplified by Andrea Lanfranchi (github @AndreaLanfranchi) */ #pragma once typedef struct { int sysfs_gpucount; unsigned int* sysfs_device_id; unsigned int* sysfs_hwmon_id; unsigned int* sysfs_pci_domain_id; unsigned int* sysfs_pci_bus_id; unsigned int* sysfs_pci_device_id; } wrap_amdsysfs_handle; typedef struct { int DeviceId = -1; int HwMonId = -1; int PciDomain = -1; int PciBus = -1; int PciDevice = -1; } pciInfo; wrap_amdsysfs_handle* wrap_amdsysfs_create(); int wrap_amdsysfs_destroy(wrap_amdsysfs_handle* sysfsh); int wrap_amdsysfs_get_gpucount(wrap_amdsysfs_handle* sysfsh, int* gpucount); int wrap_amdsysfs_get_tempC(wrap_amdsysfs_handle* sysfsh, int index, unsigned int* tempC); int wrap_amdsysfs_get_fanpcnt(wrap_amdsysfs_handle* sysfsh, int index, unsigned int* fanpcnt); int wrap_amdsysfs_get_power_usage( wrap_amdsysfs_handle* sysfsh, int index, unsigned int* milliwatts);
1,089
C++
.h
31
32.064516
94
0.746425
ethereum-mining/ethminer
5,969
2,283
327
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
25,132
wrapadl.h
ethereum-mining_ethminer/libhwmon/wrapadl.h
/* * Wrapper for ADL, inspired by wrapnvml from John E. Stone * * By Philipp Andreas - github@smurfy.de * ADL power by Davesmacer */ #pragma once #if defined(__cplusplus) extern "C" { #endif typedef enum wrap_adlReturn_enum { WRAPADL_OK = 0 } wrap_adlReturn_t; // Some ADL defines and structs from adl sdk #if defined(__MSC_VER) #define ADL_API_CALL __cdecl #elif defined(_WIN32) #define ADL_API_CALL __stdcall #else #define ADL_API_CALL #endif typedef void*(ADL_API_CALL* ADL_MAIN_MALLOC_CALLBACK)(int); /// \brief Handle to ADL client context. /// /// ADL clients obtain context handle from initial call to \ref ADL2_Main_Control_Create. /// Clients have to pass the handle to each subsequent ADL call and finally destroy /// the context with call to \ref ADL2_Main_Control_Destroy /// \nosubgrouping typedef void* ADL_CONTEXT_HANDLE; #define ADL_MAX_PATH 256 typedef struct AdapterInfo { /// \ALL_STRUCT_MEM /// Size of the structure. int iSize; /// The ADL index handle. One GPU may be associated with one or two index handles int iAdapterIndex; /// The unique device ID associated with this adapter. char strUDID[ADL_MAX_PATH]; /// The BUS number associated with this adapter. int iBusNumber; /// The driver number associated with this adapter. int iDeviceNumber; /// The function number. int iFunctionNumber; /// The vendor ID associated with this adapter. int iVendorID; /// Adapter name. char strAdapterName[ADL_MAX_PATH]; /// Display name. For example, "\\Display0" for Windows or ":0:0" for Linux. char strDisplayName[ADL_MAX_PATH]; /// Present or not; 1 if present and 0 if not present.It the logical adapter is present, the /// display name such as \\.\Display1 can be found from OS int iPresent; // @} #if defined(_WIN32) /// \WIN_STRUCT_MEM /// Exist or not; 1 is exist and 0 is not present. int iExist; /// Driver registry path. char strDriverPath[ADL_MAX_PATH]; /// Driver registry path Ext for. char strDriverPathExt[ADL_MAX_PATH]; /// PNP string from Windows. char strPNPString[ADL_MAX_PATH]; /// It is generated from EnumDisplayDevices. int iOSDisplayIndex; // @} #endif /* (_WIN32) */ #if defined(LINUX) /// \LNX_STRUCT_MEM /// Internal X screen number from GPUMapInfo (DEPRICATED use XScreenInfo) int iXScreenNum; /// Internal driver index from GPUMapInfo int iDrvIndex; /// \deprecated Internal x config file screen identifier name. Use XScreenInfo instead. char strXScreenConfigName[ADL_MAX_PATH]; // @} #endif /* (LINUX) */ } AdapterInfo, *LPAdapterInfo; typedef struct ADLTemperature { /// Must be set to the size of the structure int iSize; /// Temperature in millidegrees Celsius. int iTemperature; } ADLTemperature; typedef struct ADLFanSpeedValue { /// Must be set to the size of the structure int iSize; /// Possible valies: \ref ADL_DL_FANCTRL_SPEED_TYPE_PERCENT or \ref /// ADL_DL_FANCTRL_SPEED_TYPE_RPM int iSpeedType; /// Fan speed value int iFanSpeed; /// The only flag for now is: \ref ADL_DL_FANCTRL_FLAG_USER_DEFINED_SPEED int iFlags; } ADLFanSpeedValue; /* * Handle to hold the function pointers for the entry points we need, * and the shared library itself. */ typedef struct { void* adl_dll; int adl_gpucount; int log_gpucount; int* phys_logi_device_id; LPAdapterInfo devs; ADL_CONTEXT_HANDLE context; wrap_adlReturn_t (*adlMainControlCreate)(ADL_MAIN_MALLOC_CALLBACK, int); wrap_adlReturn_t (*adlAdapterNumberOfAdapters)(int*); wrap_adlReturn_t (*adlAdapterAdapterInfoGet)(LPAdapterInfo, int); wrap_adlReturn_t (*adlAdapterAdapterIdGet)(int, int*); wrap_adlReturn_t (*adlOverdrive5TemperatureGet)(int, int, ADLTemperature*); wrap_adlReturn_t (*adlOverdrive5FanSpeedGet)(int, int, ADLFanSpeedValue*); wrap_adlReturn_t (*adlMainControlRefresh)(void); wrap_adlReturn_t (*adlMainControlDestroy)(void); wrap_adlReturn_t (*adl2MainControlCreate)(ADL_MAIN_MALLOC_CALLBACK, int, ADL_CONTEXT_HANDLE*); wrap_adlReturn_t (*adl2MainControlDestroy)(ADL_CONTEXT_HANDLE); wrap_adlReturn_t (*adl2Overdrive6CurrentPowerGet)(ADL_CONTEXT_HANDLE, int, int, int*); wrap_adlReturn_t (*adl2MainControlRefresh)(ADL_CONTEXT_HANDLE); } wrap_adl_handle; wrap_adl_handle* wrap_adl_create(); int wrap_adl_destroy(wrap_adl_handle* adlh); int wrap_adl_get_gpucount(wrap_adl_handle* adlh, int* gpucount); int wrap_adl_get_gpu_name(wrap_adl_handle* adlh, int gpuindex, char* namebuf, int bufsize); int wrap_adl_get_gpu_pci_id(wrap_adl_handle* adlh, int gpuindex, char* idbuf, int bufsize); int wrap_adl_get_tempC(wrap_adl_handle* adlh, int gpuindex, unsigned int* tempC); int wrap_adl_get_fanpcnt(wrap_adl_handle* adlh, int gpuindex, unsigned int* fanpcnt); int wrap_adl_get_power_usage(wrap_adl_handle* adlh, int gpuindex, unsigned int* milliwatts); #if defined(__cplusplus) } #endif
5,024
C++
.h
133
34.315789
98
0.724528
ethereum-mining/ethminer
5,969
2,283
327
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
25,133
wrapnvml.h
ethereum-mining_ethminer/libhwmon/wrapnvml.h
/* * A trivial little dlopen()-based wrapper library for the * NVIDIA NVML library, to allow runtime discovery of NVML on an * arbitrary system. This is all very hackish and simple-minded, but * it serves my immediate needs in the short term until NVIDIA provides * a static NVML wrapper library themselves, hopefully in * CUDA 6.5 or maybe sometime shortly after. * * This trivial code is made available under the "new" 3-clause BSD license, * and/or any of the GPL licenses you prefer. * Feel free to use the code and modify as you see fit. * * John E. Stone - john.stone@gmail.com * */ #pragma once #include "wraphelper.h" #if defined(__cplusplus) extern "C" { #endif /* * Ugly hacks to avoid dependencies on the real nvml.h until it starts * getting included with the CUDA toolkit or a GDK that's got a known * install location, etc. */ typedef enum wrap_nvmlReturn_enum { WRAPNVML_SUCCESS = 0 } wrap_nvmlReturn_t; typedef void* wrap_nvmlDevice_t; /* our own version of the PCI info struct */ typedef struct { char bus_id_str[16]; /* string form of bus info */ unsigned int domain; unsigned int bus; unsigned int device; unsigned int pci_device_id; /* combined device and vendor id */ unsigned int pci_subsystem_id; unsigned int res0; /* NVML internal use only */ unsigned int res1; unsigned int res2; unsigned int res3; } wrap_nvmlPciInfo_t; /* * Handle to hold the function pointers for the entry points we need, * and the shared library itself. */ typedef struct { void* nvml_dll; int nvml_gpucount; unsigned int* nvml_pci_domain_id; unsigned int* nvml_pci_bus_id; unsigned int* nvml_pci_device_id; wrap_nvmlDevice_t* devs; wrap_nvmlReturn_t (*nvmlInit)(void); wrap_nvmlReturn_t (*nvmlDeviceGetCount)(int*); wrap_nvmlReturn_t (*nvmlDeviceGetHandleByIndex)(int, wrap_nvmlDevice_t*); wrap_nvmlReturn_t (*nvmlDeviceGetPciInfo)(wrap_nvmlDevice_t, wrap_nvmlPciInfo_t*); wrap_nvmlReturn_t (*nvmlDeviceGetName)(wrap_nvmlDevice_t, char*, int); wrap_nvmlReturn_t (*nvmlDeviceGetTemperature)(wrap_nvmlDevice_t, int, unsigned int*); wrap_nvmlReturn_t (*nvmlDeviceGetFanSpeed)(wrap_nvmlDevice_t, unsigned int*); wrap_nvmlReturn_t (*nvmlDeviceGetPowerUsage)(wrap_nvmlDevice_t, unsigned int*); wrap_nvmlReturn_t (*nvmlShutdown)(void); } wrap_nvml_handle; wrap_nvml_handle* wrap_nvml_create(); int wrap_nvml_destroy(wrap_nvml_handle* nvmlh); /* * Query the number of GPUs seen by NVML */ int wrap_nvml_get_gpucount(wrap_nvml_handle* nvmlh, int* gpucount); /* * query the name of the GPU model from the CUDA device ID * */ int wrap_nvml_get_gpu_name(wrap_nvml_handle* nvmlh, int gpuindex, char* namebuf, int bufsize); /* * Query the current GPU temperature (Celsius), from the CUDA device ID */ int wrap_nvml_get_tempC(wrap_nvml_handle* nvmlh, int gpuindex, unsigned int* tempC); /* * Query the current GPU fan speed (percent) from the CUDA device ID */ int wrap_nvml_get_fanpcnt(wrap_nvml_handle* nvmlh, int gpuindex, unsigned int* fanpcnt); /* * Query the current GPU power usage in milliwatts from the CUDA device ID * * This feature is only available on recent GPU generations and may be * limited in some cases only to Tesla series GPUs. * If the query is run on an unsupported GPU, this routine will return -1. */ int wrap_nvml_get_power_usage(wrap_nvml_handle* nvmlh, int gpuindex, unsigned int* milliwatts); #if defined(__cplusplus) } #endif
3,495
C++
.h
93
34.935484
95
0.740916
ethereum-mining/ethminer
5,969
2,283
327
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
25,134
wraphelper.h
ethereum-mining_ethminer/libhwmon/wraphelper.h
/* * Wrappers to emulate dlopen() on other systems like Windows */ #pragma once #include <libdevcore/Log.h> #if defined(_WIN32) #include <windows.h> void* wrap_dlopen(const char* filename); void* wrap_dlsym(void* h, const char* sym); int wrap_dlclose(void* h); #else /* assume we can use dlopen itself... */ #include <dlfcn.h> void* wrap_dlopen(const char* filename); void* wrap_dlsym(void* h, const char* sym); int wrap_dlclose(void* h); #endif
451
C++
.h
17
25.235294
61
0.733179
ethereum-mining/ethminer
5,969
2,283
327
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
25,137
DBusInt.h
ethereum-mining_ethminer/ethminer/DBusInt.h
#pragma once #include <dbus/dbus.h> using namespace std; class DBusInt { public: DBusInt() { dbus_error_init(&err); conn = dbus_bus_get(DBUS_BUS_SESSION, &err); if (!conn) { minelog << "DBus error " << err.name << ": " << err.message; } dbus_bus_request_name(conn, "eth.miner", DBUS_NAME_FLAG_REPLACE_EXISTING, &err); if (dbus_error_is_set(&err)) { minelog << "DBus error " << err.name << ": " << err.message; dbus_connection_close(conn); } minelog << "DBus initialized!"; } void send(const char* hash) { DBusMessage* msg; msg = dbus_message_new_signal("/eth/miner/hash", "eth.miner.monitor", "Hash"); if (msg == nullptr) { minelog << "Message is null!"; } dbus_message_append_args(msg, DBUS_TYPE_STRING, &hash, DBUS_TYPE_INVALID); if (!dbus_connection_send(conn, msg, nullptr)) cerr << "Error sending message!"; dbus_message_unref(msg); } private: DBusError err; DBusConnection* conn; };
1,130
C++
.h
39
21.794872
88
0.554328
ethereum-mining/ethminer
5,969
2,283
327
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
25,138
CPUMiner.h
ethereum-mining_ethminer/libethash-cpu/CPUMiner.h
/* This file is part of ethminer. ethminer is free software: you can 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. ethminer 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 ethminer. If not, see <http://www.gnu.org/licenses/>. */ #pragma once #include <libdevcore/Worker.h> #include <libethcore/EthashAux.h> #include <libethcore/Miner.h> #include <functional> namespace dev { namespace eth { class CPUMiner : public Miner { public: CPUMiner(unsigned _index, CPSettings _settings, DeviceDescriptor& _device); ~CPUMiner() override; static unsigned getNumDevices(); static void enumDevices(std::map<string, DeviceDescriptor>& _DevicesCollection); void search(const dev::eth::WorkPackage& w); protected: bool initDevice() override; bool initEpoch_internal() override; void kick_miner() override; private: atomic<bool> m_new_work = {false}; void workLoop() override; CPSettings m_settings; }; } // namespace eth } // namespace dev
1,390
C++
.h
41
31.512195
84
0.773204
ethereum-mining/ethminer
5,969
2,283
327
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
25,141
EthashAux.h
ethereum-mining_ethminer/libethcore/EthashAux.h
/* This file is part of ethminer. ethminer is free software: you can 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. ethminer 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 ethminer. If not, see <http://www.gnu.org/licenses/>. */ #pragma once #include <libdevcore/Common.h> #include <libdevcore/Exceptions.h> #include <libdevcore/Worker.h> #include <ethash/ethash.hpp> namespace dev { namespace eth { struct Result { h256 value; h256 mixHash; }; class EthashAux { public: static Result eval(int epoch, h256 const& _headerHash, uint64_t _nonce) noexcept; }; struct EpochContext { int epochNumber; int lightNumItems; size_t lightSize; const ethash_hash512* lightCache; int dagNumItems; uint64_t dagSize; }; struct WorkPackage { WorkPackage() = default; explicit operator bool() const { return header != h256(); } std::string job; // Job identifier can be anything. Not necessarily a hash h256 boundary; h256 header; ///< When h256() means "pause until notified a new work package is available". h256 seed; int epoch = -1; int block = -1; uint64_t startNonce = 0; uint16_t exSizeBytes = 0; std::string algo = "ethash"; }; struct Solution { uint64_t nonce; // Solution found nonce h256 mixHash; // Mix hash WorkPackage work; // WorkPackage this solution refers to std::chrono::steady_clock::time_point tstamp; // Timestamp of found solution unsigned midx; // Originating miner Id }; } // namespace eth } // namespace dev
2,114
C++
.h
65
29.030769
96
0.679961
ethereum-mining/ethminer
5,969
2,283
327
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
25,142
CUDAMiner.h
ethereum-mining_ethminer/libethash-cuda/CUDAMiner.h
/* This file is part of ethminer. ethminer is free software: you can 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. ethminer 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 ethminer. If not, see <http://www.gnu.org/licenses/>. */ #pragma once #include "ethash_cuda_miner_kernel.h" #include <libdevcore/Worker.h> #include <libethcore/EthashAux.h> #include <libethcore/Miner.h> #include <functional> namespace dev { namespace eth { class CUDAMiner : public Miner { public: CUDAMiner(unsigned _index, CUSettings _settings, DeviceDescriptor& _device); ~CUDAMiner() override; static int getNumDevices(); static void enumDevices(std::map<string, DeviceDescriptor>& _DevicesCollection); void search( uint8_t const* header, uint64_t target, uint64_t _startN, const dev::eth::WorkPackage& w); protected: bool initDevice() override; bool initEpoch_internal() override; void kick_miner() override; private: atomic<bool> m_new_work = {false}; void workLoop() override; std::vector<volatile Search_results*> m_search_buf; std::vector<cudaStream_t> m_streams; uint64_t m_current_target = 0; CUSettings m_settings; const uint32_t m_batch_size; const uint32_t m_streams_batch_size; uint64_t m_allocated_memory_dag = 0; // dag_size is a uint64_t in EpochContext struct size_t m_allocated_memory_light_cache = 0; }; } // namespace eth } // namespace dev
1,844
C++
.h
50
33.86
98
0.755781
ethereum-mining/ethminer
5,969
2,283
327
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
25,143
ethash_cuda_miner_kernel_globals.h
ethereum-mining_ethminer/libethash-cuda/ethash_cuda_miner_kernel_globals.h
#pragma once __constant__ uint32_t d_dag_size; __constant__ hash128_t* d_dag; __constant__ uint32_t d_light_size; __constant__ hash64_t* d_light; __constant__ hash32_t d_header; __constant__ uint64_t d_target; #if (__CUDACC_VER_MAJOR__ > 8) #define SHFL(x, y, z) __shfl_sync(0xFFFFFFFF, (x), (y), (z)) #else #define SHFL(x, y, z) __shfl((x), (y), (z)) #endif #if (__CUDA_ARCH__ >= 320) #define LDG(x) __ldg(&(x)) #else #define LDG(x) (x) #endif
448
C++
.h
17
25.176471
60
0.630841
ethereum-mining/ethminer
5,969
2,283
327
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
25,144
cuda_helper.h
ethereum-mining_ethminer/libethash-cuda/cuda_helper.h
#pragma once #include <cuda.h> #include <cuda_runtime.h> #define DEV_INLINE __device__ __forceinline__ #ifdef __INTELLISENSE__ /* reduce vstudio warnings (__byteperm, blockIdx...) */ #include <device_functions.h> #include <device_launch_parameters.h> #define __launch_bounds__(max_tpb, min_blocks) #define asm("a" : "=l"(result) : "l"(a)) #define __CUDA_ARCH__ 520 // highlight shuffle code by default. uint32_t __byte_perm(uint32_t x, uint32_t y, uint32_t z); uint32_t __shfl(uint32_t x, uint32_t y, uint32_t z); uint32_t atomicExch(uint32_t* x, uint32_t y); uint32_t atomicAdd(uint32_t* x, uint32_t y); void __syncthreads(void); void __threadfence(void); void __threadfence_block(void); #endif #include <stdint.h> #ifndef MAX_GPUS #define MAX_GPUS 32 #endif extern "C" int device_map[MAX_GPUS]; extern "C" long device_sm[MAX_GPUS]; extern cudaStream_t gpustream[MAX_GPUS]; // common functions extern void cuda_check_cpu_init(int thr_id, uint32_t threads); extern void cuda_check_cpu_setTarget(const void* ptarget); extern void cuda_check_cpu_setTarget_mod(const void* ptarget, const void* ptarget2); extern uint32_t cuda_check_hash( int thr_id, uint32_t threads, uint32_t startNounce, uint32_t* d_inputHash); extern uint32_t cuda_check_hash_suppl( int thr_id, uint32_t threads, uint32_t startNounce, uint32_t* d_inputHash, uint32_t foundnonce); extern void cudaReportHardwareFailure(int thr_id, cudaError_t error, const char* func); #ifndef __CUDA_ARCH__ // define blockDim and threadIdx for host extern const dim3 blockDim; extern const uint3 threadIdx; #endif #ifndef SPH_C32 #define SPH_C32(x) ((x##U)) // #define SPH_C32(x) ((uint32_t)(x ## U)) #endif #ifndef SPH_C64 #define SPH_C64(x) ((x##ULL)) // #define SPH_C64(x) ((uint64_t)(x ## ULL)) #endif #ifndef SPH_T32 #define SPH_T32(x) (x) // #define SPH_T32(x) ((x) & SPH_C32(0xFFFFFFFF)) #endif #ifndef SPH_T64 #define SPH_T64(x) (x) // #define SPH_T64(x) ((x) & SPH_C64(0xFFFFFFFFFFFFFFFF)) #endif #define ROTL32c(x, n) ((x) << (n)) | ((x) >> (32 - (n))) #if __CUDA_ARCH__ < 320 // Kepler (Compute 3.0) #define ROTL32(x, n) ((x) << (n)) | ((x) >> (32 - (n))) #else // Kepler (Compute 3.5, 5.0) DEV_INLINE uint32_t ROTL32(const uint32_t x, const uint32_t n) { return (__funnelshift_l((x), (x), (n))); } #endif #if __CUDA_ARCH__ < 320 // Kepler (Compute 3.0) #define ROTR32(x, n) (((x) >> (n)) | ((x) << (32 - (n)))) #else DEV_INLINE uint32_t ROTR32(const uint32_t x, const uint32_t n) { return (__funnelshift_r((x), (x), (n))); } #endif DEV_INLINE uint64_t MAKE_ULONGLONG(uint32_t LO, uint32_t HI) { uint64_t result; asm("mov.b64 %0,{%1,%2}; \n\t" : "=l"(result) : "r"(LO), "r"(HI)); return result; } // Endian Drehung für 32 Bit Typen #ifdef __CUDA_ARCH__ DEV_INLINE uint32_t cuda_swab32(const uint32_t x) { /* device */ return __byte_perm(x, x, 0x0123); } #else /* host */ #define cuda_swab32(x) \ ((((x) << 24) & 0xff000000u) | (((x) << 8) & 0x00ff0000u) | (((x) >> 8) & 0x0000ff00u) | \ (((x) >> 24) & 0x000000ffu)) #endif #ifdef __CUDA_ARCH__ DEV_INLINE uint64_t cuda_swab64(const uint64_t x) { uint64_t result; uint2 t; asm("mov.b64 {%0,%1},%2; \n\t" : "=r"(t.x), "=r"(t.y) : "l"(x)); t.x = __byte_perm(t.x, 0, 0x0123); t.y = __byte_perm(t.y, 0, 0x0123); asm("mov.b64 %0,{%1,%2}; \n\t" : "=l"(result) : "r"(t.y), "r"(t.x)); return result; } #else /* host */ #define cuda_swab64(x) \ ((uint64_t)((((uint64_t)(x)&0xff00000000000000ULL) >> 56) | \ (((uint64_t)(x)&0x00ff000000000000ULL) >> 40) | \ (((uint64_t)(x)&0x0000ff0000000000ULL) >> 24) | \ (((uint64_t)(x)&0x000000ff00000000ULL) >> 8) | \ (((uint64_t)(x)&0x00000000ff000000ULL) << 8) | \ (((uint64_t)(x)&0x0000000000ff0000ULL) << 24) | \ (((uint64_t)(x)&0x000000000000ff00ULL) << 40) | \ (((uint64_t)(x)&0x00000000000000ffULL) << 56))) #endif #ifdef _WIN64 #define USE_XOR_ASM_OPTS 0 #else #define USE_XOR_ASM_OPTS 1 #endif #if USE_XOR_ASM_OPTS // device asm for whirpool DEV_INLINE uint64_t xor1(const uint64_t a, const uint64_t b) { uint64_t result; asm("xor.b64 %0, %1, %2;" : "=l"(result) : "l"(a), "l"(b)); return result; } #else #define xor1(a, b) (a ^ b) #endif /* #if USE_XOR_ASM_OPTS // device asm for whirpool DEV_INLINE uint64_t xor3(const uint64_t a, const uint64_t b, const uint64_t c) { uint64_t result; asm("xor.b64 %0, %2, %3;\n\t" "xor.b64 %0, %0, %1;\n\t" //output : input registers : "=l"(result) : "l"(a), "l"(b), "l"(c)); return result; } #else #define xor3(a,b,c) (a ^ b ^ c) #endif */ #if USE_XOR_ASM_OPTS // device asm for whirpool DEV_INLINE uint64_t xor8(const uint64_t a, const uint64_t b, const uint64_t c, const uint64_t d, const uint64_t e, const uint64_t f, const uint64_t g, const uint64_t h) { uint64_t result; asm("xor.b64 %0, %1, %2;" : "=l"(result) : "l"(g), "l"(h)); asm("xor.b64 %0, %0, %1;" : "+l"(result) : "l"(f)); asm("xor.b64 %0, %0, %1;" : "+l"(result) : "l"(e)); asm("xor.b64 %0, %0, %1;" : "+l"(result) : "l"(d)); asm("xor.b64 %0, %0, %1;" : "+l"(result) : "l"(c)); asm("xor.b64 %0, %0, %1;" : "+l"(result) : "l"(b)); asm("xor.b64 %0, %0, %1;" : "+l"(result) : "l"(a)); return result; } #else #define xor8(a, b, c, d, e, f, g, h) ((a ^ b) ^ (c ^ d) ^ (e ^ f) ^ (g ^ h)) #endif // device asm for x17 DEV_INLINE uint64_t xandx(const uint64_t a, const uint64_t b, const uint64_t c) { uint64_t result; asm("{\n\t" ".reg .u64 n;\n\t" "xor.b64 %0, %2, %3;\n\t" "and.b64 n, %0, %1;\n\t" "xor.b64 %0, n, %3;" "}\n" : "=l"(result) : "l"(a), "l"(b), "l"(c)); return result; } // device asm for x17 DEV_INLINE uint64_t andor(uint64_t a, uint64_t b, uint64_t c) { uint64_t result; asm("{\n\t" ".reg .u64 m,n;\n\t" "and.b64 m, %1, %2;\n\t" " or.b64 n, %1, %2;\n\t" "and.b64 %0, n, %3;\n\t" " or.b64 %0, %0, m ;\n\t" "}\n" : "=l"(result) : "l"(a), "l"(b), "l"(c)); return result; } // device asm for x17 DEV_INLINE uint64_t shr_t64(uint64_t x, uint32_t n) { uint64_t result; asm("shr.b64 %0,%1,%2;\n\t" : "=l"(result) : "l"(x), "r"(n)); return result; } // device asm for ? DEV_INLINE uint64_t shl_t64(uint64_t x, uint32_t n) { uint64_t result; asm("shl.b64 %0,%1,%2;\n\t" : "=l"(result) : "l"(x), "r"(n)); return result; } #ifndef USE_ROT_ASM_OPT #define USE_ROT_ASM_OPT 2 #endif // 64-bit ROTATE RIGHT #if __CUDA_ARCH__ >= 320 && USE_ROT_ASM_OPT == 1 /* complicated sm >= 3.5 one (with Funnel Shifter beschleunigt), to bench */ DEV_INLINE uint64_t ROTR64(const uint64_t value, const int offset) { uint2 result; if (offset < 32) { asm("shf.r.wrap.b32 %0, %1, %2, %3;" : "=r"(result.x) : "r"(__double2loint(__longlong_as_double(value))), "r"(__double2hiint(__longlong_as_double(value))), "r"(offset)); asm("shf.r.wrap.b32 %0, %1, %2, %3;" : "=r"(result.y) : "r"(__double2hiint(__longlong_as_double(value))), "r"(__double2loint(__longlong_as_double(value))), "r"(offset)); } else { asm("shf.r.wrap.b32 %0, %1, %2, %3;" : "=r"(result.x) : "r"(__double2hiint(__longlong_as_double(value))), "r"(__double2loint(__longlong_as_double(value))), "r"(offset)); asm("shf.r.wrap.b32 %0, %1, %2, %3;" : "=r"(result.y) : "r"(__double2loint(__longlong_as_double(value))), "r"(__double2hiint(__longlong_as_double(value))), "r"(offset)); } return __double_as_longlong(__hiloint2double(result.y, result.x)); } #elif __CUDA_ARCH__ >= 120 && USE_ROT_ASM_OPT == 2 DEV_INLINE uint64_t ROTR64(const uint64_t x, const int offset) { uint64_t result; asm("{\n\t" ".reg .b64 lhs;\n\t" ".reg .u32 roff;\n\t" "shr.b64 lhs, %1, %2;\n\t" "sub.u32 roff, 64, %2;\n\t" "shl.b64 %0, %1, roff;\n\t" "add.u64 %0, %0, lhs;\n\t" "}\n" : "=l"(result) : "l"(x), "r"(offset)); return result; } #else /* host */ #define ROTR64(x, n) (((x) >> (n)) | ((x) << (64 - (n)))) #endif // 64-bit ROTATE LEFT #if __CUDA_ARCH__ >= 320 && USE_ROT_ASM_OPT == 1 DEV_INLINE uint64_t ROTL64(const uint64_t value, const int offset) { uint2 result; if (offset >= 32) { asm("shf.l.wrap.b32 %0, %1, %2, %3;" : "=r"(result.x) : "r"(__double2loint(__longlong_as_double(value))), "r"(__double2hiint(__longlong_as_double(value))), "r"(offset)); asm("shf.l.wrap.b32 %0, %1, %2, %3;" : "=r"(result.y) : "r"(__double2hiint(__longlong_as_double(value))), "r"(__double2loint(__longlong_as_double(value))), "r"(offset)); } else { asm("shf.l.wrap.b32 %0, %1, %2, %3;" : "=r"(result.x) : "r"(__double2hiint(__longlong_as_double(value))), "r"(__double2loint(__longlong_as_double(value))), "r"(offset)); asm("shf.l.wrap.b32 %0, %1, %2, %3;" : "=r"(result.y) : "r"(__double2loint(__longlong_as_double(value))), "r"(__double2hiint(__longlong_as_double(value))), "r"(offset)); } return __double_as_longlong(__hiloint2double(result.y, result.x)); } #elif __CUDA_ARCH__ >= 120 && USE_ROT_ASM_OPT == 2 DEV_INLINE uint64_t ROTL64(const uint64_t x, const int offset) { uint64_t result; asm("{\n\t" ".reg .b64 lhs;\n\t" ".reg .u32 roff;\n\t" "shl.b64 lhs, %1, %2;\n\t" "sub.u32 roff, 64, %2;\n\t" "shr.b64 %0, %1, roff;\n\t" "add.u64 %0, lhs, %0;\n\t" "}\n" : "=l"(result) : "l"(x), "r"(offset)); return result; } #elif __CUDA_ARCH__ >= 320 && USE_ROT_ASM_OPT == 3 __device__ uint64_t ROTL64(const uint64_t x, const int offset) { uint64_t res; asm("{\n\t" ".reg .u32 tl,th,vl,vh;\n\t" ".reg .pred p;\n\t" "mov.b64 {tl,th}, %1;\n\t" "shf.l.wrap.b32 vl, tl, th, %2;\n\t" "shf.l.wrap.b32 vh, th, tl, %2;\n\t" "setp.lt.u32 p, %2, 32;\n\t" "@!p mov.b64 %0, {vl,vh};\n\t" "@p mov.b64 %0, {vh,vl};\n\t" "}" : "=l"(res) : "l"(x), "r"(offset)); return res; } #else /* host */ #define ROTL64(x, n) (((x) << (n)) | ((x) >> (64 - (n)))) #endif DEV_INLINE uint64_t SWAPDWORDS(uint64_t value) { #if __CUDA_ARCH__ >= 320 uint2 temp; asm("mov.b64 {%0, %1}, %2; " : "=r"(temp.x), "=r"(temp.y) : "l"(value)); asm("mov.b64 %0, {%1, %2}; " : "=l"(value) : "r"(temp.y), "r"(temp.x)); return value; #else return ROTL64(value, 32); #endif } /* lyra2 - int2 operators */ DEV_INLINE void LOHI(uint32_t& lo, uint32_t& hi, uint64_t x) { asm("mov.b64 {%0,%1},%2; \n\t" : "=r"(lo), "=r"(hi) : "l"(x)); } DEV_INLINE uint64_t devectorize(uint2 x) { uint64_t result; asm("mov.b64 %0,{%1,%2}; \n\t" : "=l"(result) : "r"(x.x), "r"(x.y)); return result; } DEV_INLINE uint2 vectorize(const uint64_t x) { uint2 result; asm("mov.b64 {%0,%1},%2; \n\t" : "=r"(result.x), "=r"(result.y) : "l"(x)); return result; } DEV_INLINE void devectorize2(uint4 inn, uint2& x, uint2& y) { x.x = inn.x; x.y = inn.y; y.x = inn.z; y.y = inn.w; } DEV_INLINE uint4 vectorize2(uint2 x, uint2 y) { uint4 result; result.x = x.x; result.y = x.y; result.z = y.x; result.w = y.y; return result; } DEV_INLINE uint4 vectorize2(uint2 x) { uint4 result; result.x = x.x; result.y = x.y; result.z = x.x; result.w = x.y; return result; } DEV_INLINE uint4 vectorize4(uint64_t x, uint64_t y) { uint4 result; asm("mov.b64 {%0,%1},%2; \n\t" : "=r"(result.x), "=r"(result.y) : "l"(x)); asm("mov.b64 {%0,%1},%2; \n\t" : "=r"(result.z), "=r"(result.w) : "l"(y)); return result; } DEV_INLINE void devectorize4(uint4 inn, uint64_t& x, uint64_t& y) { asm("mov.b64 %0,{%1,%2}; \n\t" : "=l"(x) : "r"(inn.x), "r"(inn.y)); asm("mov.b64 %0,{%1,%2}; \n\t" : "=l"(y) : "r"(inn.z), "r"(inn.w)); } static DEV_INLINE uint2 vectorizelow(uint32_t v) { uint2 result; result.x = v; result.y = 0; return result; } static DEV_INLINE uint2 vectorizehigh(uint32_t v) { uint2 result; result.x = 0; result.y = v; return result; } static DEV_INLINE uint2 operator^(uint2 a, uint32_t b) { return make_uint2(a.x ^ b, a.y); } static DEV_INLINE uint2 operator^(uint2 a, uint2 b) { return make_uint2(a.x ^ b.x, a.y ^ b.y); } static DEV_INLINE uint2 operator&(uint2 a, uint2 b) { return make_uint2(a.x & b.x, a.y & b.y); } static DEV_INLINE uint2 operator|(uint2 a, uint2 b) { return make_uint2(a.x | b.x, a.y | b.y); } static DEV_INLINE uint2 operator~(uint2 a) { return make_uint2(~a.x, ~a.y); } static DEV_INLINE void operator^=(uint2& a, uint2 b) { a = a ^ b; } static DEV_INLINE uint2 operator+(uint2 a, uint2 b) { uint2 result; asm("{\n\t" "add.cc.u32 %0,%2,%4; \n\t" "addc.u32 %1,%3,%5; \n\t" "}\n\t" : "=r"(result.x), "=r"(result.y) : "r"(a.x), "r"(a.y), "r"(b.x), "r"(b.y)); return result; } static DEV_INLINE uint2 operator+(uint2 a, uint32_t b) { uint2 result; asm("{\n\t" "add.cc.u32 %0,%2,%4; \n\t" "addc.u32 %1,%3,%5; \n\t" "}\n\t" : "=r"(result.x), "=r"(result.y) : "r"(a.x), "r"(a.y), "r"(b), "r"(0)); return result; } static DEV_INLINE uint2 operator-(uint2 a, uint32_t b) { uint2 result; asm("{\n\t" "sub.cc.u32 %0,%2,%4; \n\t" "subc.u32 %1,%3,%5; \n\t" "}\n\t" : "=r"(result.x), "=r"(result.y) : "r"(a.x), "r"(a.y), "r"(b), "r"(0)); return result; } static DEV_INLINE uint2 operator-(uint2 a, uint2 b) { uint2 result; asm("{\n\t" "sub.cc.u32 %0,%2,%4; \n\t" "subc.u32 %1,%3,%5; \n\t" "}\n\t" : "=r"(result.x), "=r"(result.y) : "r"(a.x), "r"(a.y), "r"(b.x), "r"(b.y)); return result; } static DEV_INLINE uint4 operator^(uint4 a, uint4 b) { return make_uint4(a.x ^ b.x, a.y ^ b.y, a.z ^ b.z, a.w ^ b.w); } static DEV_INLINE uint4 operator&(uint4 a, uint4 b) { return make_uint4(a.x & b.x, a.y & b.y, a.z & b.z, a.w & b.w); } static DEV_INLINE uint4 operator|(uint4 a, uint4 b) { return make_uint4(a.x | b.x, a.y | b.y, a.z | b.z, a.w | b.w); } static DEV_INLINE uint4 operator~(uint4 a) { return make_uint4(~a.x, ~a.y, ~a.z, ~a.w); } static DEV_INLINE void operator^=(uint4& a, uint4 b) { a = a ^ b; } static DEV_INLINE uint4 operator^(uint4 a, uint2 b) { return make_uint4(a.x ^ b.x, a.y ^ b.y, a.z ^ b.x, a.w ^ b.y); } static DEV_INLINE void operator+=(uint2& a, uint2 b) { a = a + b; } /** * basic multiplication between 64bit no carry outside that range (ie mul.lo.b64(a*b)) * (what does uint64 "*" operator) */ static DEV_INLINE uint2 operator*(uint2 a, uint2 b) { uint2 result; asm("{\n\t" "mul.lo.u32 %0,%2,%4; \n\t" "mul.hi.u32 %1,%2,%4; \n\t" "mad.lo.cc.u32 %1,%3,%4,%1; \n\t" "madc.lo.u32 %1,%3,%5,%1; \n\t" "}\n\t" : "=r"(result.x), "=r"(result.y) : "r"(a.x), "r"(a.y), "r"(b.x), "r"(b.y)); return result; } // uint2 method #if __CUDA_ARCH__ >= 350 DEV_INLINE uint2 ROR2(const uint2 a, const int offset) { uint2 result; if (offset < 32) { asm("shf.r.wrap.b32 %0, %1, %2, %3;" : "=r"(result.x) : "r"(a.x), "r"(a.y), "r"(offset)); asm("shf.r.wrap.b32 %0, %1, %2, %3;" : "=r"(result.y) : "r"(a.y), "r"(a.x), "r"(offset)); } else { asm("shf.r.wrap.b32 %0, %1, %2, %3;" : "=r"(result.x) : "r"(a.y), "r"(a.x), "r"(offset)); asm("shf.r.wrap.b32 %0, %1, %2, %3;" : "=r"(result.y) : "r"(a.x), "r"(a.y), "r"(offset)); } return result; } #else DEV_INLINE uint2 ROR2(const uint2 v, const int n) { uint2 result; if (n <= 32) { result.y = ((v.y >> (n)) | (v.x << (32 - n))); result.x = ((v.x >> (n)) | (v.y << (32 - n))); } else { result.y = ((v.x >> (n - 32)) | (v.y << (64 - n))); result.x = ((v.y >> (n - 32)) | (v.x << (64 - n))); } return result; } #endif DEV_INLINE uint32_t ROL8(const uint32_t x) { return __byte_perm(x, x, 0x2103); } DEV_INLINE uint32_t ROL16(const uint32_t x) { return __byte_perm(x, x, 0x1032); } DEV_INLINE uint32_t ROL24(const uint32_t x) { return __byte_perm(x, x, 0x0321); } DEV_INLINE uint2 ROR8(const uint2 a) { uint2 result; result.x = __byte_perm(a.y, a.x, 0x0765); result.y = __byte_perm(a.y, a.x, 0x4321); return result; } DEV_INLINE uint2 ROR16(const uint2 a) { uint2 result; result.x = __byte_perm(a.y, a.x, 0x1076); result.y = __byte_perm(a.y, a.x, 0x5432); return result; } DEV_INLINE uint2 ROR24(const uint2 a) { uint2 result; result.x = __byte_perm(a.y, a.x, 0x2107); result.y = __byte_perm(a.y, a.x, 0x6543); return result; } DEV_INLINE uint2 ROL8(const uint2 a) { uint2 result; result.x = __byte_perm(a.y, a.x, 0x6543); result.y = __byte_perm(a.y, a.x, 0x2107); return result; } DEV_INLINE uint2 ROL16(const uint2 a) { uint2 result; result.x = __byte_perm(a.y, a.x, 0x5432); result.y = __byte_perm(a.y, a.x, 0x1076); return result; } DEV_INLINE uint2 ROL24(const uint2 a) { uint2 result; result.x = __byte_perm(a.y, a.x, 0x4321); result.y = __byte_perm(a.y, a.x, 0x0765); return result; } #if __CUDA_ARCH__ >= 350 __inline__ __device__ uint2 ROL2(const uint2 a, const int offset) { uint2 result; if (offset >= 32) { asm("shf.l.wrap.b32 %0, %1, %2, %3;" : "=r"(result.x) : "r"(a.x), "r"(a.y), "r"(offset)); asm("shf.l.wrap.b32 %0, %1, %2, %3;" : "=r"(result.y) : "r"(a.y), "r"(a.x), "r"(offset)); } else { asm("shf.l.wrap.b32 %0, %1, %2, %3;" : "=r"(result.x) : "r"(a.y), "r"(a.x), "r"(offset)); asm("shf.l.wrap.b32 %0, %1, %2, %3;" : "=r"(result.y) : "r"(a.x), "r"(a.y), "r"(offset)); } return result; } #else __inline__ __device__ uint2 ROL2(const uint2 v, const int n) { uint2 result; if (n <= 32) { result.y = ((v.y << (n)) | (v.x >> (32 - n))); result.x = ((v.x << (n)) | (v.y >> (32 - n))); } else { result.y = ((v.x << (n - 32)) | (v.y >> (64 - n))); result.x = ((v.y << (n - 32)) | (v.x >> (64 - n))); } return result; } #endif DEV_INLINE uint64_t ROTR16(uint64_t x) { #if __CUDA_ARCH__ > 500 short4 temp; asm("mov.b64 { %0, %1, %2, %3 }, %4; " : "=h"(temp.x), "=h"(temp.y), "=h"(temp.z), "=h"(temp.w) : "l"(x)); asm("mov.b64 %0, {%1, %2, %3 , %4}; " : "=l"(x) : "h"(temp.y), "h"(temp.z), "h"(temp.w), "h"(temp.x)); return x; #else return ROTR64(x, 16); #endif } DEV_INLINE uint64_t ROTL16(uint64_t x) { #if __CUDA_ARCH__ > 500 short4 temp; asm("mov.b64 { %0, %1, %2, %3 }, %4; " : "=h"(temp.x), "=h"(temp.y), "=h"(temp.z), "=h"(temp.w) : "l"(x)); asm("mov.b64 %0, {%1, %2, %3 , %4}; " : "=l"(x) : "h"(temp.w), "h"(temp.x), "h"(temp.y), "h"(temp.z)); return x; #else return ROTL64(x, 16); #endif } static __forceinline__ __device__ uint2 SHL2(uint2 a, int offset) { #if __CUDA_ARCH__ > 300 uint2 result; if (offset < 32) { asm("{\n\t" "shf.l.clamp.b32 %1,%2,%3,%4; \n\t" "shl.b32 %0,%2,%4; \n\t" "}\n\t" : "=r"(result.x), "=r"(result.y) : "r"(a.x), "r"(a.y), "r"(offset)); } else { asm("{\n\t" "shf.l.clamp.b32 %1,%2,%3,%4; \n\t" "shl.b32 %0,%2,%4; \n\t" "}\n\t" : "=r"(result.x), "=r"(result.y) : "r"(a.y), "r"(a.x), "r"(offset)); } return result; #else if (offset <= 32) { a.y = (a.y << offset) | (a.x >> (32 - offset)); a.x = (a.x << offset); } else { a.y = (a.x << (offset - 32)); a.x = 0; } return a; #endif } static __forceinline__ __device__ uint2 SHR2(uint2 a, int offset) { #if __CUDA_ARCH__ > 300 uint2 result; if (offset < 32) { asm("{\n\t" "shf.r.clamp.b32 %0,%2,%3,%4; \n\t" "shr.b32 %1,%3,%4; \n\t" "}\n\t" : "=r"(result.x), "=r"(result.y) : "r"(a.x), "r"(a.y), "r"(offset)); } else { asm("{\n\t" "shf.l.clamp.b32 %0,%2,%3,%4; \n\t" "shl.b32 %1,%3,%4; \n\t" "}\n\t" : "=r"(result.x), "=r"(result.y) : "r"(a.y), "r"(a.x), "r"(offset)); } return result; #else if (offset <= 32) { a.x = (a.x >> offset) | (a.y << (32 - offset)); a.y = (a.y >> offset); } else { a.x = (a.y >> (offset - 32)); a.y = 0; } return a; #endif } static DEV_INLINE uint64_t devectorizeswap(uint2 v) { return MAKE_ULONGLONG(cuda_swab32(v.y), cuda_swab32(v.x)); } static DEV_INLINE uint2 vectorizeswap(uint64_t v) { uint2 result; LOHI(result.y, result.x, v); result.x = cuda_swab32(result.x); result.y = cuda_swab32(result.y); return result; } DEV_INLINE uint32_t devectorize16(ushort2 x) { uint32_t result; asm("mov.b32 %0,{%1,%2}; \n\t" : "=r"(result) : "h"(x.x), "h"(x.y)); return result; } DEV_INLINE ushort2 vectorize16(uint32_t x) { ushort2 result; asm("mov.b32 {%0,%1},%2; \n\t" : "=h"(result.x), "=h"(result.y) : "r"(x)); return result; } static DEV_INLINE uint4 mul4(uint4 a) { uint4 result; asm("{\n\t" "mul.lo.u32 %0,%4,%5; \n\t" "mul.hi.u32 %1,%4,%5; \n\t" "mul.lo.u32 %2,%6,%7; \n\t" "mul.hi.u32 %3,%6,%7; \n\t" "}\n\t" : "=r"(result.x), "=r"(result.y), "=r"(result.z), "=r"(result.w) : "r"(a.x), "r"(a.y), "r"(a.z), "r"(a.w)); return result; } static DEV_INLINE uint4 add4(uint4 a, uint4 b) { uint4 result; asm("{\n\t" "add.cc.u32 %0,%4,%8; \n\t" "addc.u32 %1,%5,%9; \n\t" "add.cc.u32 %2,%6,%10; \n\t" "addc.u32 %3,%7,%11; \n\t" "}\n\t" : "=r"(result.x), "=r"(result.y), "=r"(result.z), "=r"(result.w) : "r"(a.x), "r"(a.y), "r"(a.z), "r"(a.w), "r"(b.x), "r"(b.y), "r"(b.z), "r"(b.w)); return result; } static DEV_INLINE uint4 madd4(uint4 a, uint4 b) { uint4 result; asm("{\n\t" "mad.lo.cc.u32 %0,%4,%5,%8; \n\t" "madc.hi.u32 %1,%4,%5,%9; \n\t" "mad.lo.cc.u32 %2,%6,%7,%10; \n\t" "madc.hi.u32 %3,%6,%7,%11; \n\t" "}\n\t" : "=r"(result.x), "=r"(result.y), "=r"(result.z), "=r"(result.w) : "r"(a.x), "r"(a.y), "r"(a.z), "r"(a.w), "r"(b.x), "r"(b.y), "r"(b.z), "r"(b.w)); return result; } static DEV_INLINE ulonglong2 madd4long(ulonglong2 a, ulonglong2 b) { ulonglong2 result; asm("{\n\t" ".reg .u32 a0,a1,a2,a3,b0,b1,b2,b3;\n\t" "mov.b64 {a0,a1}, %2;\n\t" "mov.b64 {a2,a3}, %3;\n\t" "mov.b64 {b0,b1}, %4;\n\t" "mov.b64 {b2,b3}, %5;\n\t" "mad.lo.cc.u32 b0,a0,a1,b0; \n\t" "madc.hi.u32 b1,a0,a1,b1; \n\t" "mad.lo.cc.u32 b2,a2,a3,b2; \n\t" "madc.hi.u32 b3,a2,a3,b3; \n\t" "mov.b64 %0, {b0,b1};\n\t" "mov.b64 %1, {b2,b3};\n\t" "}\n\t" : "=l"(result.x), "=l"(result.y) : "l"(a.x), "l"(a.y), "l"(b.x), "l"(b.y)); return result; } static DEV_INLINE void madd4long2(ulonglong2& a, ulonglong2 b) { asm("{\n\t" ".reg .u32 a0,a1,a2,a3,b0,b1,b2,b3;\n\t" "mov.b64 {a0,a1}, %0;\n\t" "mov.b64 {a2,a3}, %1;\n\t" "mov.b64 {b0,b1}, %2;\n\t" "mov.b64 {b2,b3}, %3;\n\t" "mad.lo.cc.u32 b0,a0,a1,b0; \n\t" "madc.hi.u32 b1,a0,a1,b1; \n\t" "mad.lo.cc.u32 b2,a2,a3,b2; \n\t" "madc.hi.u32 b3,a2,a3,b3; \n\t" "mov.b64 %0, {b0,b1};\n\t" "mov.b64 %1, {b2,b3};\n\t" "}\n\t" : "+l"(a.x), "+l"(a.y) : "l"(b.x), "l"(b.y)); } DEV_INLINE uint32_t xor3b(uint32_t a, uint32_t b, uint32_t c) { uint32_t result; asm("{ .reg .u32 t1;\n\t" "xor.b32 t1, %2, %3;\n\t" "xor.b32 %0, %1, t1;\n\t" "}" : "=r"(result) : "r"(a), "r"(b), "r"(c)); return result; } DEV_INLINE uint32_t shr_t32(uint32_t x, uint32_t n) { uint32_t result; asm("shr.b32 %0,%1,%2;" : "=r"(result) : "r"(x), "r"(n)); return result; } DEV_INLINE uint32_t shl_t32(uint32_t x, uint32_t n) { uint32_t result; asm("shl.b32 %0,%1,%2;" : "=r"(result) : "r"(x), "r"(n)); return result; } // device asm 32 for pluck DEV_INLINE uint32_t andor32(uint32_t a, uint32_t b, uint32_t c) { uint32_t result; asm("{ .reg .u32 m,n,o;\n\t" "and.b32 m, %1, %2;\n\t" " or.b32 n, %1, %2;\n\t" "and.b32 o, n, %3;\n\t" " or.b32 %0, m, o ;\n\t" "}\n\t" : "=r"(result) : "r"(a), "r"(b), "r"(c)); return result; } DEV_INLINE uint32_t bfe(uint32_t x, uint32_t bit, uint32_t numBits) { uint32_t ret; asm("bfe.u32 %0, %1, %2, %3;" : "=r"(ret) : "r"(x), "r"(bit), "r"(numBits)); return ret; } DEV_INLINE uint32_t bfi(uint32_t x, uint32_t a, uint32_t bit, uint32_t numBits) { uint32_t ret; asm("bfi.b32 %0, %1, %2, %3,%4;" : "=r"(ret) : "r"(x), "r"(a), "r"(bit), "r"(numBits)); return ret; }
26,050
C++
.h
899
24.300334
100
0.514026
ethereum-mining/ethminer
5,969
2,283
327
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
25,146
scintillahexeditview.cpp
cxasm_notepad--/src/scintillahexeditview.cpp
#include "scintillahexeditview.h" #include "styleset.h" #include "ccnotepad.h" #include <stdexcept> #include <QMimeData> #include <QScrollBar> bool ScintillaHexEditView::_SciInit = false; #define DEFAULT_FONT_NAME "Courier New" const int STYLE_COLOR_SELECT = 1; ScintillaHexEditView::ScintillaHexEditView(QWidget *parent):QsciScintilla(parent), m_NoteWin(nullptr) { init(); } ScintillaHexEditView::~ScintillaHexEditView() { } void ScintillaHexEditView::setNoteWidget(QWidget * win) { CCNotePad* pv = dynamic_cast<CCNotePad*>(win); if (pv != nullptr) { m_NoteWin = pv; } } sptr_t ScintillaHexEditView::execute(quint32 Msg, uptr_t wParam, sptr_t lParam) const { try { return (m_pScintillaFunc) ? m_pScintillaFunc(m_pScintillaPtr, Msg, wParam, lParam) : -1; } catch (...) { return -1; } }; void ScintillaHexEditView::init() { if (!_SciInit) { _SciInit = true; } m_pScintillaFunc = (SCINTILLA_FUNC)this->SendScintillaPtrResult(SCI_GETDIRECTFUNCTION); m_pScintillaPtr = (SCINTILLA_PTR)this->SendScintillaPtrResult(SCI_GETDIRECTPOINTER); if (!m_pScintillaFunc) { throw std::runtime_error("ScintillaEditView::init : SCI_GETDIRECTFUNCTION message failed"); } if (!m_pScintillaPtr) { throw std::runtime_error("ScintillaEditView::init : SCI_GETDIRECTPOINTER message failed"); } //设置字体 #if defined (Q_OS_MAC) QFont font(DEFAULT_FONT_NAME, 12, QFont::Normal); #else QFont font(DEFAULT_FONT_NAME, 11, QFont::Normal); #endif setFont(font); setMarginsFont(font); execute(SCI_SETTABWIDTH, 4); updateThemes(); connect(this->verticalScrollBar(), &QScrollBar::valueChanged, this, &ScintillaHexEditView::slot_scrollYValueChange); } //Y方向滚动条值变化后的槽函数 void ScintillaHexEditView::slot_scrollYValueChange(int value) { if (value >= this->verticalScrollBar()->maximum()) { if (m_NoteWin != nullptr) { m_NoteWin->showChangePageTips(this); } } else if (value == this->verticalScrollBar()->minimum()) { if (m_NoteWin != nullptr) { m_NoteWin->showChangePageTips(this); } } } void ScintillaHexEditView::dragEnterEvent(QDragEnterEvent* event) { event->accept(); } void ScintillaHexEditView::dropEvent(QDropEvent* e) { QList<QUrl> urls = e->mimeData()->urls(); if (urls.isEmpty()) return; CCNotePad* pv = dynamic_cast<CCNotePad*>(m_NoteWin); if (pv != nullptr) pv->receiveEditDrop(e); //qDebug() << ui.leftSrc->geometry() << ui.rightSrc->geometry() << QCursor::pos() << this->mapFromGlobal(QCursor::pos()); } void ScintillaHexEditView::updateThemes() { //如果是黑色主题,则单独做一些风格设置 setColor(StyleSet::s_global_style->default_style.fgColor); setMarginsBackgroundColor(StyleSet::s_global_style->line_number_margin.bgColor); setPaper(StyleSet::s_global_style->default_style.bgColor); } void ScintillaHexEditView::setStyle(int style, int startPos, int length) { SendScintilla(SCI_STARTSTYLING, startPos); SendScintilla(SCI_SETSTYLING, length, style); }
3,127
C++
.cpp
105
25.742857
123
0.728562
cxasm/notepad--
5,942
234
284
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
25,147
optionsview.cpp
cxasm_notepad--/src/optionsview.cpp
#include "optionsview.h" #include "doctypelistview.h" #include "texteditsetwin.h" #include "ccnotepad.h" OptionsView::OptionsView(QWidget* pNotepadWin, QWidget *parent) : QWidget(parent), m_pNotepadWin(pNotepadWin) { ui.setupUi(this); //只在文件对比中出现;在编辑框模式下不出现,这个关联文件容易误解。 if (pNotepadWin == nullptr) { DocTypeListView* p = new DocTypeListView(this); ui.stackedWidget->addWidget(p); //文件关联 file correlation ui.optionListWidget->addItem(tr("File Correlation")); } ui.optionListWidget->addItem(tr("Compare File Types")); TextEditSetWin* p2 = new TextEditSetWin(this); p2->setNotePadWin(pNotepadWin); ui.stackedWidget->addWidget(p2); ui.optionListWidget->addItem(tr("Text And Fonts")); connect(ui.optionListWidget, &QListWidget::currentRowChanged, this, &OptionsView::slot_curRowChanged); connect(p2, &TextEditSetWin::sendTabFormatChange, this, &OptionsView::sendTabFormatChange); connect(p2, &TextEditSetWin::signProLangFontChange, this, &OptionsView::signProLangFontChange); } OptionsView::~OptionsView() { } void OptionsView::slot_curRowChanged(int row) { if (row < ui.stackedWidget->count()) { ui.stackedWidget->setCurrentIndex(row); } } void OptionsView::slot_ok() { close(); }
1,337
C++
.cpp
39
29.179487
104
0.759367
cxasm/notepad--
5,942
234
284
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
25,148
nddsetting.cpp
cxasm_notepad--/src/nddsetting.cpp
#include "nddsetting.h" #include <QObject> #include <QtDebug> #include <QCoreApplication> #include <QDate> #include <QFile> #include <QStorageInfo> #include <QSettings> static short version_num = 29; //1.22.0 是29 //配置文件是否存在。如果初始化失败,则不存在 bool NddSetting::s_isExistDb = false; int NddSetting::s_reference = 0; bool NddSetting::s_isContentChanged = false; QSettings* NddSetting::s_nddSet = nullptr; QSettings* NddSetting::s_nddDelaySet = nullptr; //如果key不存在,则新增key-value。存在:返回true bool NddSetting::checkNoExistAdd(QString key, QVariant& value) { //每次新加字段后,这里要检查一下,不存在则新增 if (!s_nddSet->contains(key)) { s_nddSet->setValue(key, value); if (!s_isContentChanged) { s_isContentChanged = true; } return false; } return true; } //20220402这里隐含了一个前置条件:数据库句柄是在主线程创建的,最好不要在子线程中调用。 //避免因为跨线程访问和多线程冲突访问引发的闪退问题。所以最好配置文件的读写都在主线程中进行 void NddSetting::init() { ++s_reference; //如果已经初始化过了,则直接返回 if (s_isExistDb) { return; } QString settingDir = QString("notepad/nddsets"); QSettings qs(QSettings::IniFormat, QSettings::UserScope, settingDir); QString qsSetPath = qs.fileName(); s_nddSet = new QSettings(QSettings::IniFormat, QSettings::UserScope, settingDir); s_nddSet->setIniCodec("UTF-8"); bool initOk = true; auto initNddSet = []() { QString key = "signdate"; //QString date = QDate::currentDate().toString(QString("yyyy/M/d")); //不写今天的时间,否则第一次运行,无条件不会发送心跳。 //直接写一个过去的时间,让第一次运行,总是要签到 addKeyValueToSets(key, "2022/2/20"); QString str; //tab的长度,默认为4 addKeyValueToNumSets("tablens", 4); //space replace tab空格替换tab,默认0, 1为true,0为false addKeyValueToNumSets("tabnouse", 0); addKeyValueToSets("mac", "0"); addKeyValueToNumSets("padtimes", 0); addKeyValueToNumSets("serverip", 0); //是否高亮不同处背景 addKeyValueToNumSets("hexhigh", 1); addKeyValueToNumSets(VERSION, version_num); //皮肤id addKeyValueToNumSets(SKIN_KEY, 0); //语言index 0:自动选择 1:中文 2 英文 addKeyValueToNumSets(LANGS_KEY, 0); //开启自动换行 addKeyValueToNumSets(AUTOWARP_KEY, 0); //开启自动缩进 addKeyValueToNumSets(INDENT_KEY, 0); //显示空白。0都不显示 1 单显示空格 2 单显示行尾 3 都显示 addKeyValueToNumSets(SHOWSPACE_KEY, 0); //最大文本文件的门限。默认100M.(50-600) addKeyValueToNumSets(MAX_BIG_TEXT, 100); addKeyValueToSets(SOFT_KEY, "0"); addKeyValueToNumSets(RESTORE_CLOSE_FILE, 1); //0 24 1 36 2 48 addKeyValueToNumSets(ICON_SIZE, 1); addKeyValueToNumSets(ZOOMVALUE, 100); addKeyValueToNumSets(FINDRESULTPOS, Qt::BottomDockWidgetArea); addKeyValueToNumSets(FILELISTPOS, Qt::LeftDockWidgetArea); //默认0不显示 addKeyValueToNumSets(FILELISTSHOW, 0); //默认显示工具栏 addKeyValueToNumSets(TOOLBARSHOW, 1); //打开网页,默认不勾选,资源耗费多 addKeyValueToNumSets(SHOWWEBADDR, 0); //查找结果框的默认字体大小 addKeyValueToNumSets(FIND_RESULT_FONT_SIZE, 14); }; if (!s_nddSet->contains(VERSION)) { //不存在走初始化流程 initNddSet(); s_isContentChanged = true; } else { do { { QVariant v(VERSION); if (checkNoExistAdd(VERSION, v)) { //如果存在,而且版本是最新,不需要走后面自动检查流程了 int curVersion = s_nddSet->value(VERSION).toInt(); if (curVersion == version_num) { break; } else if (curVersion < version_num) { //更新版本到最新 updataKeyValueFromNumSets(VERSION, version_num); } } } //每次新加字段后,这里要检查一下,不存在则新增 { QVariant v(1); checkNoExistAdd(SKIN_KEY, v); } { QVariant langs(0); checkNoExistAdd(LANGS_KEY, langs); } { QVariant v(0); checkNoExistAdd(AUTOWARP_KEY, v); } { QVariant v(0); checkNoExistAdd(INDENT_KEY, v); } { QVariant v(0); checkNoExistAdd(SHOWSPACE_KEY, v); } { QVariant v(100); checkNoExistAdd(MAX_BIG_TEXT, v); } { QVariant v(0); checkNoExistAdd(SOFT_STATUS, v); } { QVariant v("0"); checkNoExistAdd(SOFT_KEY, v); } { QVariant v(1); checkNoExistAdd(RESTORE_CLOSE_FILE, v); } { QVariant v(1); checkNoExistAdd(ICON_SIZE, v); } { QVariant v(100); checkNoExistAdd(ZOOMVALUE, v); } { QVariant v(Qt::BottomDockWidgetArea); checkNoExistAdd(FINDRESULTPOS, v); } { QVariant v(Qt::LeftDockWidgetArea); checkNoExistAdd(FILELISTPOS, v); } { QVariant v(0); checkNoExistAdd(FILELISTSHOW, v); } { QVariant v(1); checkNoExistAdd(TOOLBARSHOW, v); } { QVariant v(0); checkNoExistAdd(SHOWWEBADDR, v); } { QVariant v(14); checkNoExistAdd(FIND_RESULT_FONT_SIZE, v); } { QVariant v(0); checkNoExistAdd(LAST_ACTION_TAB_INDEX, v); } } while (false); } s_isExistDb = initOk; } //写一个总的获取配置的接口,避免以后每个字段都需要写一个读写接口 QString NddSetting::getKeyValueFromSets(QString key) { return s_nddSet->value(key,"").toString(); } bool NddSetting::updataKeyValueFromSets(QString key, QString value) { s_nddSet->setValue(key,value); s_isContentChanged = true; return true; } //写一个总的获取配置的接口,避免以后每个字段都需要写一个读写接口 QByteArray NddSetting::getKeyByteArrayValue(QString key) { return s_nddSet->value(key, "").toByteArray(); } void NddSetting::updataKeyByteArrayValue(QString key, QByteArray& value) { s_nddSet->setValue(key, QVariant(value)); s_isContentChanged = true; } //第一次加一条记录,用于初始化 void NddSetting::addKeyValueToSets(QString key, QString value) { s_nddSet->setValue(key, QVariant(value)); } //写一个总的获取配置的接口,避免以后每个字段都需要写一个读写接口.0做默认值,外部最好不用0做初始化值 int NddSetting::getKeyValueFromNumSets(const QString key) { QVariant v = s_nddSet->value(key, QVariant(0)); return v.toInt(); } bool NddSetting::updataKeyValueFromNumSets(const QString key, int value) { s_nddSet->setValue(key, QVariant(value)); return true; } //第一次加一条记录,用于初始化 void NddSetting::addKeyValueToNumSets(QString key, int value) { s_nddSet->setValue(key, QVariant(value)); } void NddSetting::close() { if (s_reference > 0) { --s_reference; if (s_reference == 0) { s_isExistDb = false; //做一次真正的保存 if (s_isContentChanged) { s_nddSet->sync(); delete s_nddSet; s_nddSet = nullptr; s_isContentChanged = false; } //在这里保存一下子窗口的位置。不排除有可能子窗口还在,主窗口已经退出的情况,不过问题不大。 if (s_nddDelaySet != nullptr) { s_nddDelaySet->sync(); s_nddDelaySet = nullptr; } } } } //子窗口的位置,单独放在一个winpos.ini文件中,而且启动程序时,不需要读取,可避免启动时拖慢速度 QByteArray NddSetting::getWinPos(QString key) { nddDelaySetInit(); return s_nddDelaySet->value(key, "").toByteArray(); } void NddSetting::updataWinPos(QString key, QByteArray& value) { nddDelaySetInit(); s_nddDelaySet->setValue(key, QVariant(value)); } void NddSetting::nddDelaySetInit() { if (s_nddDelaySet == nullptr) { QString settingDir = QString("notepad/delayset"); QSettings qs(QSettings::IniFormat, QSettings::UserScope, settingDir); QString qsSetPath = qs.fileName(); s_nddDelaySet = new QSettings(QSettings::IniFormat, QSettings::UserScope, settingDir); s_nddDelaySet->setIniCodec("UTF-8"); } } //写一个总的获取配置的接口,避免以后每个字段都需要写一个读写接口 QString NddSetting::getKeyValueFromDelaySets(QString key) { nddDelaySetInit(); return s_nddDelaySet->value(key, "").toString(); } bool NddSetting::updataKeyValueFromDelaySets(QString key, QString value) { nddDelaySetInit(); s_nddDelaySet->setValue(key, value); s_isContentChanged = true; return true; } //写一个总的获取配置的接口,避免以后每个字段都需要写一个读写接口 int NddSetting::getKeyValueFromDelayNumSets(QString key) { nddDelaySetInit(); return s_nddDelaySet->value(key, "").toInt(); } bool NddSetting::updataKeyValueFromDelayNumSets(QString key, int value) { nddDelaySetInit(); s_nddDelaySet->setValue(key, value); s_isContentChanged = true; return true; }
9,300
C++
.cpp
309
21.313916
89
0.698154
cxasm/notepad--
5,942
234
284
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
25,149
CmpareMode.cpp
cxasm_notepad--/src/CmpareMode.cpp
#include "CmpareMode.h" #include "Encode.h" #include "rcglobal.h" #include <QFile> #include <QFileDevice> #include <QVector> #include <QCryptographicHash> #include <functional> #include <QDataStream> #include <QtConcurrent> CmpareMode::CmpareMode() { } CmpareMode::~CmpareMode() { } //识别文字编码,并将文字按照原始编码格式,转换为QString。如果失败,默认按照utf8的格式进行转换; bool CmpareMode::recognizeTextCode(QByteArray & text, LineFileInfo &lineInfo, QString &outUnicodeText) { int lineNums = lineInfo.lineNums; int length = text.count(); int result = false; //第一行时,检测一下文件编码,返回值也是文件的编码 if (0 == lineNums) { int skip = 0; lineInfo.code = Encode::DetectEncode((uchar*) text.data(), length, skip); //根据编码跳过第一行前面的几个字符编码标识字段 if (skip > 0) { text = text.mid(skip); } return Encode::tranStrToUNICODE((CODE_ID)lineInfo.code, text.data(), text.count(), outUnicodeText); } else { /*对于头部没有标识的行,需要每行进行详细检查,比较耗时 *对于第一行已经是GBK的编码,标识出所有的确是GBK的行号 *严格来说,如果以后要做国际版,不应该只考虑GBK,而是要考虑本地ASNI编码。 *对中国而言,本地ASNI编码是GBK,对其它国家,比如日本/韩国而言,这些ASNI是它们本国 *对应的本地编码。 */ //#if 0 // //全部都在ascii范围以内,就作为ascii码。注意ASCII处理时其它地方时按照UTF8进行编码的 // if (Encode::CheckTextIsAllAscii((uchar*)text.data(), length)) // { // lineInfo.code = CODE_ID::ASCII; // return Encode::tranStrToUNICODE((CODE_ID)lineInfo.code, text.data(), length, outUnicodeText); // } // else // { //#endif CODE_ID actualCode = Encode::CheckUnicodeWithoutBOM((uchar*)text.data(), length, outUnicodeText); if (CODE_ID::UTF8_NOBOM == actualCode) { lineInfo.code = CODE_ID::UTF8_NOBOM; result = true; } else if (CODE_ID::GBK == actualCode) { //如果发现存在GBK,则要以GBK作为字符编码。这里识别gbk是因为显示的时候,需要转化gbk进行显示 lineInfo.code = CODE_ID::GBK; result = true; } else if (CODE_ID::ANSI == actualCode) { lineInfo.code = CODE_ID::UNKOWN; //这里就是乱码了。即不是utf8也不是GBK,也不能说乱码,目前其它国家未处理的码 result = false; } //#if 0 // } //#endif } return result; } //LE编码要特殊对待。 bool CmpareMode::isUnicodeLeBomFile(uchar* fileFpr, int fileLength) { if (fileLength >= 2 && fileFpr[0] == 0xFF && fileFpr[1] == 0xFE) { return true; } return false; } //isCheckHead:是否检测头。只有文件开头,才有。如果是分块加载,中间打开的文件,则不需要检测。默认检测 CODE_ID CmpareMode::getTextFileEncodeType(uchar* fileFpr, int fileLength, QString filePath, bool isCheckHead) { if (isCheckHead) { if (fileLength >= 2 && fileFpr[0] == 0xFF && fileFpr[1] == 0xFE) { return CODE_ID::UNICODE_LE; //skip 2 } else if (fileLength >= 2 && fileFpr[0] == 0xFE && fileFpr[1] == 0xFF) { return CODE_ID::UNICODE_BE; //skip 2 } else if (fileLength >= 3 && fileFpr[0] == 0xEF && fileFpr[1] == 0xBB && fileFpr[2] == 0xBF) { return CODE_ID::UTF8_BOM; //skip 3 with BOM } } //走到这里说明没有文件头BOM,进行全盘文件扫描 if (!filePath.isEmpty()) { return scanFileRealCode(filePath); } return CODE_ID::UNKOWN; } //20230201新增:把Unicode_LE的字节流,转换为QString 发现如果是CODE_ID::UNICODE_LE,\r\n变成了\r\0\n\0,读取readLine遇到\n就结束了,而且toUnicode也会变成乱码失败 //所以UNICODE_LE需要单独处理。该函数只处理Unicode_LE编码文件,事先一定要检查文件编码 //返回字符数,不是编码类型,注意是字符数,不是bytes //这里有个问题,当初读取文件分块是,是无条件读取到\n就结束,则可能最后不是\n\0,而是\n。这种情况要特殊处理。标记为A。 //是否跳过前面的LE头。默认不跳过。只有文件块开头第一块,才需要跳过。 bool CmpareMode::tranUnicodeLeToUtf8Bytes(uchar* fileFpr, const int fileLength, QString &outUtf8Bytes, bool isSkipHead) { CODE_ID code = CODE_ID::UNICODE_LE; int lineStartPos = (isSkipHead ? 2:0); //uicode_le前面有2个特殊标识,故跳过2 //获取一行在文件中 auto getOneLineFromFile = [fileFpr](int& startPos, const int fileLength, QByteArray& ret)->bool { if (startPos < fileLength) { ret.clear(); int lineLens = 0; bool isFindLine = false; for (int i = startPos; i < fileLength; ++i, ++lineLens) { //遇到换行符号 if (fileFpr[i] == 0x0A) { //lineLens需要加2,因为当前这个没有加,而且后面还有一个\0,这是le格式规定的。 //特殊对待A。如果后续还要一个\0,及长度足够,则+2,否则只能加1 if (startPos + lineLens + 2 < fileLength) { ret.append((char*)(fileFpr + startPos), lineLens + 2); startPos += lineLens + 2; } else { //这里就是特殊情况,尾部后面没有\0,只能前进1个。 ret.append((char*)(fileFpr + startPos), lineLens + 1); //必须手动补上一个\0。避免格式残缺 ret.append('\0'); startPos += lineLens + 1; } isFindLine = true; break; } } //没有找到一行 if (!isFindLine) { //最后一行,可能没有带\r\0直接返回 ret.append((char*)(fileFpr + startPos), fileLength - startPos); startPos = fileLength; } return true; } return false; }; QByteArray line; QByteArray tempUtf8Bytes; tempUtf8Bytes.reserve(fileLength+1); while (getOneLineFromFile(lineStartPos, fileLength, line)) { tempUtf8Bytes.append(line); } return Encode::tranStrToUNICODE(code, tempUtf8Bytes.data(), tempUtf8Bytes.count(), outUtf8Bytes); } //20210802:发现如果是CODE_ID::UNICODE_LE,\r\n变成了\r\0\n\0,读取readLine遇到\n就结束了,而且toUnicode也会变成乱码失败 //所以UNICODE_LE需要单独处理。该函数只处理Unicode_LE编码文件,事先一定要检查文件编码 //返回字符数,不是编码类型,注意是字符数,不是bytes quint32 CmpareMode::readLineFromFileWithUnicodeLe(uchar* m_fileFpr, const int fileLength, QList<LineFileInfo>& lineInfoVec, QList<LineFileInfo>& blankLineInfoVec,int mode, int &maxLineSize) { QCryptographicHash md4(QCryptographicHash::Md4); int lineNums = 0; CODE_ID code = CODE_ID::UNICODE_LE; int lineStartPos = 2; //uicode_le前面有2个特殊标识,故跳过2 //获取一行在文件中 auto getOneLineFromFile = [m_fileFpr](int& startPos, const int fileLength, QByteArray& ret)->bool{ if (startPos < fileLength) { ret.clear(); int lineLens = 0; bool isFindLine = false; for (int i = startPos; i < fileLength; ++i,++lineLens) { //遇到换行符号 if (m_fileFpr[i] == 0x0A) { if (startPos + lineLens + 2 < fileLength) { //lineLens需要加2,因为当前这个没有加,而且后面还有一个\0,这是le格式规定的 ret.append((char*)(m_fileFpr + startPos), lineLens + 2); startPos += lineLens + 2; } else { //这里就是特殊情况,尾部后面没有\0,只能前进1个。 //其实是容错,可能最后一个没有\0 ret.append((char*)(m_fileFpr + startPos), lineLens + 1); //必须手动补上一个\0。避免格式残缺 ret.append('\0'); startPos += lineLens + 1; } isFindLine = true; break; } } //没有找到一行 if (!isFindLine) { //最后一行,可能没有带\r\0直接返回 ret.append((char*)(m_fileFpr + startPos), fileLength - startPos); startPos = fileLength; } return true; } return false; }; QByteArray line; quint32 charNums = 0; auto work = [mode, &md4](LineFileInfo& lineInfo, const int n) { if (mode == 0) { md4.addData(lineInfo.unicodeStr.trimmed().toUtf8()); } else if (mode == 1) { md4.addData(lineInfo.unicodeStr.left(lineInfo.unicodeStr.length() - n).toUtf8()); } else if (mode == 2) { QString temp = lineInfo.unicodeStr; md4.addData(temp.replace(QRegExp("\\s"), QString("")).toUtf8()); } }; while (getOneLineFromFile(lineStartPos, fileLength,line)) { LineFileInfo lineInfo; lineInfo.lineNums = lineNums; /* 这种方式读取文件会包含后面的行尾 */ int length = line.length(); if (maxLineSize < length) { maxLineSize = length; } //如果是头部有标识的格式,则后续不用详细检查每行编码,直接按照头部标识走 Encode::tranStrToUNICODE(code, line.data(), line.count(), lineInfo.unicodeStr); lineInfo.code = code; charNums += lineInfo.unicodeStr.size(); if (lineInfo.unicodeStr.endsWith("\r\r\n")) { //这里是一种错误,但确实可能出现 if (length > 3) { work(lineInfo, 3); } else { //空白行 lineInfo.isLcsExist = false; lineInfo.isEmptyLine = true; } lineInfo.lineEndFormat = RC_LINE_FORM::DOS_LINE; } else if (lineInfo.unicodeStr.endsWith("\r\n")) { if (length > 2) { work(lineInfo, 2); } else { //空白行 lineInfo.isLcsExist = false; lineInfo.isEmptyLine = true; } lineInfo.lineEndFormat = RC_LINE_FORM::DOS_LINE; } else if (lineInfo.unicodeStr.endsWith("\n")) { if (length > 1) { work(lineInfo, 1); } else { lineInfo.isLcsExist = false; lineInfo.isEmptyLine = true; } lineInfo.lineEndFormat = RC_LINE_FORM::UNIX_LINE; } else if (lineInfo.unicodeStr.endsWith("\r")) { if (length > 1) { work(lineInfo, 1); } else { lineInfo.isLcsExist = false; lineInfo.isEmptyLine = true; } lineInfo.lineEndFormat = RC_LINE_FORM::MAC_LINE; } else { if (length > 0) { work(lineInfo, 0); } else { lineInfo.isLcsExist = false; lineInfo.isEmptyLine = true; } lineInfo.lineEndFormat = RC_LINE_FORM::UNKNOWN_LINE; } if (lineInfo.isEmptyLine) { blankLineInfoVec.append(lineInfo); } else { lineInfo.md4 = md4.result(); //qDebug() << lineInfo.md4; md4.reset(); lineInfoVec.append(lineInfo); } ++lineNums; } return charNums; } //读取每一行,将空白行和非空白行分开。非空白行取他们的行md4值(不包含尾部的换行符) //返回值:文件扫描出来的字符编码 //在对比行的md5值时,忽略了后面的行尾类型。即只对比字符内容,忽略了行尾。 //20210802:发现如果是CODE_ID::UNICODE_LE,\r\n变成了\r\0\n\0,读取readLine遇到\n就结束了,而且toUnicode也会变成乱码失败 //所以UNICODE_LE需要单独处理。注意UNICODE_BE没有这个问题,因为BE是\0\r\0\n,0在前面就没有这个问题 //20210901 发现使用readLine的方式来读取一行不可靠。因为有些文件中一行中间有个\r,这种情况没有识别为多行。readLine是根据\n来识别的。 //进而导致中间的\r没有识别为多行,但是在编辑器中却多一行,导致对比错误。还是要自己来识别行。不依赖于readLine //CODE_ID fileCode 事先预判定的编码 CODE_ID CmpareMode::readLineFromFile(uchar* m_fileFpr, const int fileLength, const CODE_ID fileCode, QList<LineFileInfo>&lineInfoVec, QList<LineFileInfo>&blankLineInfoVec, int mode, int &maxLineSize) { QCryptographicHash md4(QCryptographicHash::Md4); int lineNums = 0; CODE_ID code = fileCode; bool isExistGbk = false; bool isExistUnKownCode = false; bool isExistUtf8 = false; int lineStartPos = 0; //跳过前面的BOM头部。LE不在这里处理,在外面 if (fileCode == CODE_ID::UNICODE_BE || fileCode == CODE_ID::UNICODE_LE) { lineStartPos = 2; } else if (fileCode == CODE_ID::UTF8_BOM) { lineStartPos = 3; } //获取一行在文件中 auto getOneLineFromFile = [m_fileFpr](int& startPos, const int fileLength, const CODE_ID fileCode, QByteArray& ret)->bool { if (startPos < fileLength) { ret.clear(); int lineLens = 0; bool isFindLine = false; for (int i = startPos; i < fileLength; ++i, ++lineLens) { //遇到符号CR if (m_fileFpr[i] == 0x0D) { //后一个是LF,即以CRLF结尾 if ((i + 1 < fileLength) && (m_fileFpr[i+1] == 0x0A)) { //lineLens需要加2,因为当前这个没有加,而且后面还有一个\n ret.append((char*)(m_fileFpr + startPos), lineLens + 2); startPos += lineLens + 2; isFindLine = true; break; } else if ((fileCode == UNICODE_BE)&&((i>0) && m_fileFpr[i-1] == '\0')) { //事先发现就是BE格式,以\0\r\0\n为结尾的 if ((i + 2 < fileLength) && (m_fileFpr[i + 1] == 0x0) && (m_fileFpr[i + 2] == 0x0A)) { //lineLens需要加3,因为当前这个没有加,而且后面还有一个\0\n ret.append((char*)(m_fileFpr + startPos), lineLens + 3); startPos += lineLens + 3; isFindLine = true; break; } else { //虽然说是BE格式,但是后面没有以\0\n结尾,而是以\r结尾。这种多半就是错误。直接按\0\r结尾 //lineLens需要加1,因为当前这个没有加 ret.append((char*)(m_fileFpr + startPos), lineLens + 1); startPos += lineLens + 1; isFindLine = true; break; } } else { //直接以\r结尾了,后面没有\n或者\0\n。符合MAC格式,windows可能编码只有\r,没有\n的错误情况。 //lineLens需要加1,因为当前这个没有加 ret.append((char*)(m_fileFpr + startPos), lineLens + 1); startPos += lineLens + 1; isFindLine = true; break; } } else if(m_fileFpr[i] == 0x0A) { //没有先遇到\r,直接遇到\n.20210903发现忘记处理该情况le //lineLens需要加1,因为当前这个没有加 ret.append((char*)(m_fileFpr + startPos), lineLens + 1); startPos += lineLens + 1; isFindLine = true; break; } } //没有找到一行 if (!isFindLine) { //最后一行,可能没有带\r\0直接返回 ret.append((char*)(m_fileFpr + startPos), fileLength - startPos); startPos = fileLength; } return true; } return false; }; QByteArray line; auto work = [mode,&md4](LineFileInfo& lineInfo, const int n) { if (mode == 0) { md4.addData(lineInfo.unicodeStr.trimmed().toUtf8()); } else if (mode == 1) { md4.addData(lineInfo.unicodeStr.left(lineInfo.unicodeStr.length() - n).toUtf8()); } else if (mode == 2) { QString temp = lineInfo.unicodeStr; md4.addData(temp.replace(QRegExp("\\s"), QString("")).toUtf8()); } }; while (getOneLineFromFile(lineStartPos, fileLength, code, line)) { LineFileInfo lineInfo; lineInfo.lineNums = lineNums; /* 这种方式读取文件会包含后面的行尾 */ int length = line.length(); if (maxLineSize < length) { maxLineSize = length; } //外面必须把code先检测好了 //if (fileCode == CODE_ID::UNICODE_BE /*|| fileCode == CODE_ID::UNICODE_LE */ || fileCode == CODE_ID::UTF8_BOM) if(fileCode != CODE_ID::UNKOWN) { //如果是头部有标识的格式,则后续不用详细检查每行编码,直接按照头部标识走 Encode::tranStrToUNICODE(code, line.data(), line.count(), lineInfo.unicodeStr); lineInfo.code = fileCode; } else if(fileCode == CODE_ID::UNKOWN) { /*对于头部没有标识的行,需要每行进行详细检查,比较耗时 *对于第一行已经是GBK的编码,标识出所有的确是GBK的行号 *严格来说,如果以后要做国际版,不应该只考虑GBK,而是要考虑本地ASNI编码。 *对中国而言,本地ASNI编码是GBK,对其它国家,比如日本/韩国而言,这些ASNI是它们本国 *对应的本地编码。 */ recognizeTextCode(line, lineInfo, lineInfo.unicodeStr); if (CODE_ID::UTF8_NOBOM == lineInfo.code) { isExistUtf8 = true; } else if (CODE_ID::GBK == lineInfo.code) { //如果发现存在GBK,则要以GBK作为字符编码。这里识别gbk是因为显示的时候,需要转化gbk进行显示 isExistGbk = true; } else if (CODE_ID::UNKOWN == lineInfo.code) { isExistUnKownCode = true; } } if (lineInfo.unicodeStr.endsWith("\r\r\n")) { //这里是一种错误,但确实可能出现 if (length > 3) { work(lineInfo,3); } else { //空白行 lineInfo.isLcsExist = false; lineInfo.isEmptyLine = true; } lineInfo.lineEndFormat = RC_LINE_FORM::DOS_LINE; } else if (lineInfo.unicodeStr.endsWith("\r\n")) { if (length > 2) { work(lineInfo, 2); } else { //空白行 lineInfo.isLcsExist = false; lineInfo.isEmptyLine = true; } lineInfo.lineEndFormat = RC_LINE_FORM::DOS_LINE; } else if (lineInfo.unicodeStr.endsWith("\n")) { if (length > 1) { work(lineInfo, 1); } else { lineInfo.isLcsExist = false; lineInfo.isEmptyLine = true; } lineInfo.lineEndFormat = RC_LINE_FORM::UNIX_LINE; } else if (lineInfo.unicodeStr.endsWith("\r")) { if (length > 1) { work(lineInfo, 1); } else { lineInfo.isLcsExist = false; lineInfo.isEmptyLine = true; } lineInfo.lineEndFormat = RC_LINE_FORM::MAC_LINE; } else { if (length > 0) { work(lineInfo, 0); } else { lineInfo.isLcsExist = false; lineInfo.isEmptyLine = true; } lineInfo.lineEndFormat = RC_LINE_FORM::UNKNOWN_LINE; } if (lineInfo.isEmptyLine) { blankLineInfoVec.append(lineInfo); } else { lineInfo.md4 = md4.result(); md4.reset(); lineInfoVec.append(lineInfo); } ++lineNums; } //如果外部指定了格式,则直接返回外部格式 if (fileCode != CODE_ID::UNKOWN) { return fileCode; } return judgeFinalTextCode(code, isExistUnKownCode, isExistGbk, isExistUtf8); } CODE_ID CmpareMode::judgeFinalTextCode(CODE_ID code, bool isExistUnKownCode, bool isExistGbk, bool isExistUtf8) { //如果是三种有明确标识的字符编码,则严格按照标识的逻辑去读取。哪怕里面存在错误编码,也只能按照头部标识为准 if (CODE_ID::UNICODE_LE == code || CODE_ID::UNICODE_BE == code || CODE_ID::UTF8_BOM == code || code == CODE_ID::GBK) { return code; } //剩下的是在文件头没有严格标识编码的文件 //存在不能识别的编码,则应该是ASNI,需要用户指定编码 if (isExistUnKownCode) { return CODE_ID::UNKOWN; } if (isExistGbk) { //如果没有错误码,而且发现gbk,则是gbk编码 return CODE_ID::GBK; } //如果不存在错误和gbk,就是纯粹的ut8_nobom if (isExistUtf8) { return CODE_ID::UTF8_NOBOM; } return code; } //读取用于纯输出,不做比较。bool &isMaybeHexFile 是否是hex文件,不一定准确,做一个推测 // int& charsNums 输出字符个数 CODE_ID CmpareMode::readLineFromFile(uchar* m_fileFpr, const int fileLength, const CODE_ID fileCode, QList<LineFileInfo>&lineInfoVec, int& maxLineSize, int& charsNums, bool &isMaybeHexFile) { int lineNums = 0; CODE_ID code = fileCode; bool isExistGbk = false; bool isExistUnKownCode = false; bool isExistUtf8 = false; int lineStartPos = 0; int errorCodeLines = 0; charsNums = 0; if (fileCode == CODE_ID::UNICODE_BE || fileCode == CODE_ID::UNICODE_LE) { lineStartPos = 2; } else if (fileCode == CODE_ID::UTF8_BOM) { lineStartPos = 3; } //获取一行在文件中 auto getOneLineFromFile = [m_fileFpr](int& startPos, const int fileLength, const CODE_ID fileCode, QByteArray& ret)->bool { if (startPos < fileLength) { ret.clear(); int lineLens = 0; bool isFindLine = false; for (int i = startPos; i < fileLength; ++i, ++lineLens) { //遇到符号CR if (m_fileFpr[i] == 0x0D) { //后一个是LF,即以CRLF结尾 if ((i + 1 < fileLength) && (m_fileFpr[i + 1] == 0x0A)) { //lineLens需要加2,因为当前这个没有加,而且后面还有一个\n ret.append((char*)(m_fileFpr + startPos), lineLens + 2); startPos += lineLens + 2; isFindLine = true; break; } else if ((fileCode == UNICODE_BE) && ((i > 0) && m_fileFpr[i - 1] == '\0')) { //事先发现就是BE格式,以\0\r\0\n为结尾的 if ((i + 2 < fileLength) && (m_fileFpr[i + 1] == 0x0) && (m_fileFpr[i + 2] == 0x0A)) { //lineLens需要加3,因为当前这个没有加,而且后面还有一个\0\n ret.append((char*)(m_fileFpr + startPos), lineLens + 3); startPos += lineLens + 3; isFindLine = true; break; } else { //虽然说是BE格式,但是后面没有以\0\n结尾,而是以\r结尾。这种多半就是错误。直接按\0\r结尾 //lineLens需要加1,因为当前这个没有加 ret.append((char*)(m_fileFpr + startPos), lineLens + 1); startPos += lineLens + 1; isFindLine = true; break; } } else { //直接以\r结尾了,后面没有\n或者\0\n。符合MAC格式,windows可能编码只有\r,没有\n的错误情况。 //lineLens需要加1,因为当前这个没有加 ret.append((char*)(m_fileFpr + startPos), lineLens + 1); startPos += lineLens + 1; isFindLine = true; break; } } else if (m_fileFpr[i] == 0x0A) { //没有先遇到\r,直接遇到\n.20210903发现忘记处理该情况le //lineLens需要加1,因为当前这个没有加 ret.append((char*)(m_fileFpr + startPos), lineLens + 1); startPos += lineLens + 1; isFindLine = true; break; } } //没有找到一行 if (!isFindLine) { //最后一行,可能没有带\r\0直接返回 ret.append((char*)(m_fileFpr + startPos), fileLength - startPos); startPos = fileLength; } return true; } return false; }; QByteArray line; while (getOneLineFromFile(lineStartPos, fileLength, code, line)) { LineFileInfo lineInfo; lineInfo.lineNums = lineNums; /* 这种方式读取文件会包含后面的行尾 */ int length = line.length(); if (maxLineSize < length) { maxLineSize = length; } //外面必须把code先检测好了 //if (fileCode == CODE_ID::UNICODE_BE /*|| fileCode == CODE_ID::UNICODE_LE */ || fileCode == CODE_ID::UTF8_BOM) if(fileCode != CODE_ID::UNKOWN) { //如果是头部有标识的格式,则后续不用详细检查每行编码,直接按照头部标识走 Encode::tranStrToUNICODE(code, line.data(), line.count(), lineInfo.unicodeStr); lineInfo.code = fileCode; } else if (fileCode == CODE_ID::UNKOWN) { /*对于头部没有标识的行,需要每行进行详细检查,比较耗时 *对于第一行已经是GBK的编码,标识出所有的确是GBK的行号 *严格来说,如果以后要做国际版,不应该只考虑GBK,而是要考虑本地ASNI编码。 *对中国而言,本地ASNI编码是GBK,对其它国家,比如日本/韩国而言,这些ASNI是它们本国 *对应的本地编码。 */ recognizeTextCode(line, lineInfo, lineInfo.unicodeStr); if (CODE_ID::UTF8_NOBOM == lineInfo.code) { isExistUtf8 = true; } else if (CODE_ID::GBK == lineInfo.code) { //如果发现存在GBK,则要以GBK作为字符编码。这里识别gbk是因为显示的时候,需要转化gbk进行显示 isExistGbk = true; } else if (CODE_ID::UNKOWN == lineInfo.code) { isExistUnKownCode = true; //增加错误行的计数 errorCodeLines++; } } if (lineInfo.unicodeStr.endsWith("\r\r\n")) { //这里是一种错误,但确实可能出现 if (length > 3) { } else { //空白行 lineInfo.isLcsExist = false; lineInfo.isEmptyLine = true; } lineInfo.lineEndFormat = RC_LINE_FORM::DOS_LINE; } else if (lineInfo.unicodeStr.endsWith("\r\n")) { if (length > 2) { } else { //空白行 lineInfo.isLcsExist = false; lineInfo.isEmptyLine = true; } lineInfo.lineEndFormat = RC_LINE_FORM::DOS_LINE; } else if (lineInfo.unicodeStr.endsWith("\n")) { if (length > 1) { } else { lineInfo.isLcsExist = false; lineInfo.isEmptyLine = true; } lineInfo.lineEndFormat = RC_LINE_FORM::UNIX_LINE; } else if (lineInfo.unicodeStr.endsWith("\r")) { if (length > 1) { } else { lineInfo.isLcsExist = false; lineInfo.isEmptyLine = true; } lineInfo.lineEndFormat = RC_LINE_FORM::MAC_LINE; } else { if (length > 0) { } else { lineInfo.isLcsExist = false; lineInfo.isEmptyLine = true; } lineInfo.lineEndFormat = RC_LINE_FORM::UNKNOWN_LINE; } lineInfoVec.append(lineInfo); charsNums += lineInfo.unicodeStr.size(); ++lineNums; } //如果超过一半的行都是错误的,则考虑为hex文件。 if (lineNums >= 10 && (errorCodeLines * 100 / lineNums > 50)) { isMaybeHexFile = true; } else { isMaybeHexFile = false; //如果前面三行中含有\0字符,也可能是二进制文件 if (lineNums > 3) { for (int i = 0; i < 3; ++i) { if (lineInfoVec.at(i).unicodeStr.contains(QChar('\0'))) { isMaybeHexFile = true; break; } } } } //如果用户外部强制编码,则直接按改编码返回 if (fileCode != CODE_ID::UNKOWN) { return fileCode; } return judgeFinalTextCode(code, isExistUnKownCode, isExistGbk, isExistUtf8); } //扫描文件的字符编码,不输出文件 //扫描多少行scanLineNum 默认100 //如果是-1 之前全部扫描 CODE_ID CmpareMode::scanFileRealCode(QString filePath, int scanLineNum) { QFile file(filePath); file.open(QIODevice::ReadOnly); CODE_ID code = CODE_ID::UNKOWN; int lineNums = 0; bool isExistGbk = false; bool isExistUnKownCode = false; bool isExistUtf8 = false; while (!file.atEnd()) { LineFileInfo lineInfo; QByteArray line = file.readLine(); lineInfo.lineNums = lineNums; /* 这种方式读取文件会包含后面的行尾 */ //int length = line.length(); //第一行时,检测一下文件编码,返回值也是文件的编码 if (0 == lineNums) { recognizeTextCode(line, lineInfo, lineInfo.unicodeStr); code = (CODE_ID)lineInfo.code; //已经找到文本的标签,相信标签,之前返回 if (code == CODE_ID::UNICODE_BE || code == CODE_ID::UNICODE_LE || code == CODE_ID::UTF8_BOM || code == CODE_ID::GBK) { break; } } else { /*对于头部没有标识的行,需要每行进行详细检查,比较耗时 *对于第一行已经是GBK的编码,标识出所有的确是GBK的行号 *严格来说,如果以后要做国际版,不应该只考虑GBK,而是要考虑本地ASNI编码。 *对中国而言,本地ASNI编码是GBK,对其它国家,比如日本/韩国而言,这些ASNI是它们本国 *对应的本地编码。 */ recognizeTextCode(line, lineInfo, lineInfo.unicodeStr); if (CODE_ID::UTF8_NOBOM == lineInfo.code) { isExistUtf8 = true; } else if (CODE_ID::GBK == lineInfo.code) { //如果发现存在GBK,则要以GBK作为字符编码。这里识别gbk是因为显示的时候,需要转化gbk进行显示 isExistGbk = true; } else if (CODE_ID::UNKOWN == lineInfo.code) { isExistUnKownCode = true; //20220127一旦发现错误编码,或者说不能识别的编码,则直接跳出。 //因为肯定是不能识别的编码ASNI break; } } ++lineNums; //默认最多扫描200行,加块速度。速度与精确性的权衡 //对于打开文件,默认扫描前面的200行,加快速度。 //对于编码转换,为了精确,默认全部都要处理 if ((scanLineNum != -1) && (lineNums >= scanLineNum)) { break; } } file.close(); return judgeFinalTextCode(code, isExistUnKownCode, isExistGbk, isExistUtf8); } //读取文件,并输出 //bytescharsNums:文件字符个数,不是文件大小 //20220908 自动判断是否是二进制文件。isHexFile 是输出 CODE_ID CmpareMode::scanFileOutPut(CODE_ID code, QString filePath, QList<LineFileInfo>& outputLineInfoVec, int &maxLineSize, int& charsNums, bool &isHexFile) { QFile* file = new QFile(filePath); file->open(QIODevice::ReadOnly); uchar* m_fileFpr = file->map(0, file->size()); if (code == UNKOWN) { code = getTextFileEncodeType(m_fileFpr, file->size(), filePath); } //UNICODE_LE格式需要单独处理 if (code == UNICODE_LE) { charsNums = readLineFromFileWithUnicodeLe(m_fileFpr, file->size(), outputLineInfoVec, outputLineInfoVec, 0, maxLineSize); } else { code = readLineFromFile(m_fileFpr, file->size(), code, outputLineInfoVec, maxLineSize, charsNums, isHexFile); } file->unmap(m_fileFpr); file->close(); delete file; return code; } //读取文件,并输出 //bytes charsNums:文件字符个数,不是文件大小 //20220908 自动判断是否是二进制文件。isHexFile 是输出 //20230304 新增,一次性读取文件,不检测每行文本,加快速度。existGrbledCode 是否存在乱码 CODE_ID CmpareMode::scanFileOutPut(QFile& pFile, CODE_ID code, QString filePath, QString& outText, bool & existGrbledCode) { QByteArray outTextBytes = pFile.readAll(); if (outTextBytes.size() == 0) { outText = ""; existGrbledCode = false; return CODE_ID::UTF8_NOBOM; } if (code == UNKOWN) { code = getTextFileEncodeType((uchar * )outTextBytes.data(), pFile.size(), filePath); //编码还是检测失败,这里概率是比较小的。 if (code == CODE_ID::UNKOWN) { //无条件按照ANSI/GBK编码打开 code = CODE_ID::GBK; } } int lineStartPos = 0; //uicode_le前面有2个特殊标识,故跳过2 if (code == CODE_ID::UNICODE_BE || code == CODE_ID::UNICODE_LE) { lineStartPos = 2; } else if (code == CODE_ID::UTF8_BOM) { lineStartPos = 3; } bool codeSucess = Encode::tranStrToUNICODE(code, outTextBytes.data()+ lineStartPos, outTextBytes.size()- lineStartPos, outText); //如果存在乱码,而且不是以gbk编码打开,再无条件尝试ASNI/GBK编码打开。如果是国际版,后续还得完善策略,得无条件以ASNI本地编码打开。 if (!codeSucess && (code != CODE_ID::GBK)) { code = CODE_ID::GBK; outText.clear(); codeSucess = Encode::tranStrToUNICODE(code, outTextBytes.data() + lineStartPos, outTextBytes.size() - lineStartPos, outText); } existGrbledCode = !codeSucess; return code; }
32,065
C++
.cpp
966
21.949275
200
0.648284
cxasm/notepad--
5,942
234
284
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
25,150
textfind.cpp
cxasm_notepad--/src/textfind.cpp
#include "textfind.h" TextFind::TextFind(int dire, QWidget *parent): QWidget(parent) { ui.setupUi(this); } TextFind::~TextFind() { } void TextFind::slot_findPrev() { QString text = ui.textLineEdit->text(); text = text.trimmed(); emit signFindFile(0, text); } void TextFind::slot_findNext() { QString text = ui.textLineEdit->text(); text = text.trimmed(); emit signFindFile(1, text); }
431
C++
.cpp
20
18.25
63
0.695652
cxasm/notepad--
5,942
234
284
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
25,151
hexfilegoto.cpp
cxasm_notepad--/src/hexfilegoto.cpp
#include "hexfilegoto.h" HexFileGoto::HexFileGoto(QWidget *parent) : QWidget(parent) { ui.setupUi(this); connect(ui.lineEditDecAddr, &QLineEdit::textChanged, this, &HexFileGoto::slot_showDecInfo); connect(ui.lineEditHexAddr, &QLineEdit::textChanged, this, &HexFileGoto::slot_showHexInfo); } HexFileGoto::~HexFileGoto() { } //ÏÔʾΪ void HexFileGoto::slot_showDecInfo(const QString &text) { bool ok; qlonglong num = text.toLongLong(&ok, 10); if (ok) { QString v = QString("Dec : %1 \nHex : 0x%2 ").arg(QString::number(num, 10)).arg(QString::number(num, 16)); ui.textBrowser->setText(v); } else { QString v = QString("Dec : error \nHex : error "); ui.textBrowser->setText(v); } } void HexFileGoto::slot_showHexInfo(const QString &text) { bool ok; qlonglong num = text.toLongLong(&ok, 16); if (ok) { QString v = QString("Dec : %1 \nHex : 0x%2 ").arg(QString::number(num, 10)).arg(QString::number(num, 16)); ui.textBrowser->setText(v); } else { QString v = QString("Dec : error \nHex : error "); ui.textBrowser->setText(v); } } qint64 HexFileGoto::getFileAddr() { bool ok; qint64 ret = 0; if (ui.radioButtonHex->isChecked()) { ret = ui.lineEditHexAddr->text().toLongLong(&ok,16); ui.lineEditDecAddr->setText(QString::number(ret)); } else { ret = ui.lineEditDecAddr->text().toLongLong(&ok); ui.lineEditHexAddr->setText(QString::number(ret,16)); } return (ok ? ret: -1); } void HexFileGoto::slot_goto() { emit gotoClick(getFileAddr()); }
1,574
C++
.cpp
62
22.096774
109
0.679677
cxasm/notepad--
5,942
234
284
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
25,152
statuswidget.cpp
cxasm_notepad--/src/statuswidget.cpp
#include "statuswidget.h" StatusWidget::StatusWidget(QWidget *parent) : QWidget(parent) { ui.setupUi(this); } StatusWidget::~StatusWidget() { } void StatusWidget::setTipMsg(QString msg) { ui.msgLable->setText(msg); }
244
C++
.cpp
13
15.692308
44
0.736364
cxasm/notepad--
5,942
234
284
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
25,153
progresswin.cpp
cxasm_notepad--/src/progresswin.cpp
#include "progresswin.h" #include <QCoreApplication> #include <QMessageBox> ProgressWin::ProgressWin(QWidget *parent) : QDialog(parent), m_curStep(0),m_isCancel(false) { ui.setupUi(this); } ProgressWin::~ProgressWin() { } void ProgressWin::info(QString text) { ui.output->append(text); } void ProgressWin::setTotalSteps(int step) { ui.progressBar->setValue(0); ui.progressBar->setMaximum(step); m_curStep = 0; } void ProgressWin::moveStep(bool isRest) { ++m_curStep; ui.progressBar->setValue(m_curStep); ui.progressBar->update(); if (isRest) { QCoreApplication::processEvents(); } } int ProgressWin::getTotalStep() { return ui.progressBar->maximum(); } void ProgressWin::setStep(int step) { ui.progressBar->setValue(step); ui.progressBar->update(); m_curStep = step; //QCoreApplication::processEvents(); } bool ProgressWin::isCancel() { return m_isCancel; } void ProgressWin::setCancel() { m_isCancel = true; emit quitClick(); } void ProgressWin::closeEvent(QCloseEvent* e) { e->ignore(); } void ProgressWin::slot_quitBt() { if (QMessageBox::Yes != QMessageBox::question(this, tr("Notice"), tr("Are you sure to cancel?"))) { return; } m_isCancel = true; emit quitClick(); }
1,298
C++
.cpp
64
17.34375
99
0.710723
cxasm/notepad--
5,942
234
284
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
25,154
MediatorFileTree.cpp
cxasm_notepad--/src/MediatorFileTree.cpp
#include "MediatorFileTree.h" /* 文件夹对比界面的中介者,使用中介者是为了让消息经过中介对象统一调度,避免左右互相依赖导致交互混乱 */ MediatorFileTree::MediatorFileTree() :QObject(nullptr) { } MediatorFileTree::~MediatorFileTree() { } void MediatorFileTree::setLeftScrollValue(int value) { m_leftScrollValue = value; //如果左右不相等,则推动对方去同步 if (m_leftScrollValue != m_rightScrollValue) { emit syncCurScrollValue(0); } } void MediatorFileTree::setRightScrollValue(int value) { m_rightScrollValue = value; if (m_leftScrollValue != m_rightScrollValue) { emit syncCurScrollValue(1); } } int MediatorFileTree::getLeftScrollValue() { return m_leftScrollValue; } int MediatorFileTree::getRightScrollValue() { return m_rightScrollValue; } //设置item。中介本身不保存ITEM,因为太多,发送消息给外面空间 void MediatorFileTree::setLeftItemStatus(QString name, int status) { emit syncExpandStatus(name, RC_LEFT, status); } void MediatorFileTree::setRightItemStatus(QString name, int status) { emit syncExpandStatus(name, RC_RIGHT, status); }
1,220
C++
.cpp
43
21.069767
68
0.779503
cxasm/notepad--
5,942
234
284
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
25,155
dirfindfile.cpp
cxasm_notepad--/src/dirfindfile.cpp
#include "dirfindfile.h" DirFindFile::DirFindFile(int dire, QWidget *parent): QWidget(parent) { ui.setupUi(this); if (dire == 0) { ui.findLeftRadioButton->setChecked(true); } else if (dire == 1) { ui.findRightRadioButton->setChecked(true); } } DirFindFile::~DirFindFile() { } void DirFindFile::slot_findPrev() { QString name = ui.fileNameLineEdit->text(); name = name.trimmed(); int dire = (ui.findLeftRadioButton->isChecked() ? 0:1); bool sens = ui.caseSensitiveCheckBox->isChecked(); emit signFindFile(dire, 0, name, sens); } void DirFindFile::slot_findNext() { QString name = ui.fileNameLineEdit->text(); name = name.trimmed(); int dire = (ui.findLeftRadioButton->isChecked() ? 0 : 1); bool sens = ui.caseSensitiveCheckBox->isChecked(); emit signFindFile(dire, 1, name, sens); }
862
C++
.cpp
32
23.4375
69
0.702366
cxasm/notepad--
5,942
234
284
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
25,156
renamewin.cpp
cxasm_notepad--/src/renamewin.cpp
#include "renamewin.h" #include "progresswin.h" #include <QFileDialog> #include <QRadioButton> #include <QMessageBox> #include <QInputDialog> //批量修改文件夹下文件名称的功能 ReNameWin::ReNameWin(QWidget *parent) : QWidget(parent), m_extComBoxNum(0) { ui.setupUi(this); connect(ui.radioButtonAddPrefix, &QRadioButton::toggled, this, [this](bool status) {slot_renameOptionsChange(1,status); }); connect(ui.radioButtonDelPrefix, &QRadioButton::toggled, this, [this](bool status) {slot_renameOptionsChange(2, status); }); connect(ui.radioButtonAddSuffix, &QRadioButton::toggled, this, [this](bool status) {slot_renameOptionsChange(3, status); }); connect(ui.radioButtonDelSuffix, &QRadioButton::toggled, this, [this](bool status) {slot_renameOptionsChange(4, status); }); connect(ui.radioButtonLower, &QRadioButton::toggled, this, [this](bool status) {slot_renameOptionsChange(5, status); }); connect(ui.radioButtonUpper, &QRadioButton::toggled, this, [this](bool status) {slot_renameOptionsChange(6, status); }); } ReNameWin::~ReNameWin() { } void ReNameWin::slot_selectDir() { QString workDir = ui.lineEditDir->text(); QString rootpath = QFileDialog::getExistingDirectory(this, tr("Open Directory"), workDir, QFileDialog::DontResolveSymlinks); if (!rootpath.isEmpty()) { ui.lineEditDir->setText(rootpath); } } //改名,前缀后缀名称的修改 void ReNameWin::slot_renameOptionsChange(int id, bool status) { switch (id) { case 1: ui.lineEditAddPrefix->setEnabled(status); break; case 2: ui.lineEditDelPrefix->setEnabled(status); break; case 3: ui.lineEditAddSuffix->setEnabled(status); break; case 4: ui.lineEditDelSuffix->setEnabled(status); break; default: break; } } void ReNameWin::slot_userDefineExt() { bool ok = false; QString text = QInputDialog::getText(this, tr("input file ext()"), tr("ext (Start With .)"), QLineEdit::Normal, QString(".cpp"), &ok); if (ok && !text.isEmpty()) { text = text.trimmed(); ui.comboBoxExt->addItem(text); ++m_extComBoxNum; ui.comboBoxExt->setCurrentIndex(m_extComBoxNum); } } void ReNameWin::slot_startRename() { if (ui.optionsTab->currentIndex() == 0) { changeFileName(); } else if (ui.optionsTab->currentIndex() == 1) { changeFileExt(); } } void ReNameWin::changeFileName() { QString dealDir = ui.lineEditDir->text(); if (dealDir.isEmpty()) { QMessageBox::warning(this, tr("Notice"), tr("Please Select Dir")); return; } int type = -1; QString extrenFileName; bool addPrefix = ui.radioButtonAddPrefix->isChecked(); if (addPrefix && ui.lineEditAddPrefix->text().isEmpty()) { QMessageBox::warning(this, tr("Notice"), tr("Please Input Add File Prefix")); return; } if (addPrefix) { type = 0; extrenFileName = ui.lineEditAddPrefix->text(); } bool delPrefix = ui.radioButtonDelPrefix->isChecked(); if (delPrefix && ui.lineEditDelPrefix->text().isEmpty()) { QMessageBox::warning(this, tr("Notice"), tr("Please Input Del File Prefix")); return; } if (delPrefix) { type = 1; extrenFileName = ui.lineEditDelPrefix->text(); } bool addSuffix = ui.radioButtonAddSuffix->isChecked(); if (addSuffix && ui.lineEditAddSuffix->text().isEmpty()) { QMessageBox::warning(this, tr("Notice"), tr("Please Input Add File Suffix")); return; } if (addSuffix) { type = 2; extrenFileName = ui.lineEditAddSuffix->text(); } bool delSuffix = ui.radioButtonDelSuffix->isChecked(); if (delSuffix && ui.lineEditDelSuffix->text().isEmpty()) { QMessageBox::warning(this, tr("Notice"), tr("Please Input Del File Suffix")); return; } if (delSuffix) { type = 3; extrenFileName = ui.lineEditDelSuffix->text(); } bool toLowerFileName = ui.radioButtonLower->isChecked(); if (toLowerFileName) { type = 4; } bool toUpperFileName = ui.radioButtonUpper->isChecked(); if (toUpperFileName) { type = 5; } if (type == -1) { QMessageBox::warning(this, tr("Notice"), tr("Please Select One Operator")); return; } QList<QString> dirsList; dirsList.append(dealDir); int fileNums = 0; int failNums = 0; bool dealChildDir = ui.checkBoxDealChildDir->isChecked(); QString oldName; QString newName; auto getNewName = [](QString oldName, int type, const QString& addOrDelFix)->QString { QFileInfo fi(oldName); QDir dir = fi.absoluteDir(); switch (type) { //增加前缀 case 0: return QString("%1/%2.%3").arg(dir.absolutePath()).arg(addOrDelFix+fi.baseName()).arg(fi.suffix()); case 1: {//删除前缀 if (fi.baseName().startsWith(addOrDelFix) && (fi.baseName() != addOrDelFix)) { return QString("%1/%2.%3").arg(dir.absolutePath()).arg(fi.baseName().mid(addOrDelFix.length())).arg(fi.suffix()); } } break; case 2: { //增加后缀 return QString("%1/%2.%3").arg(dir.absolutePath()).arg(fi.baseName()+ addOrDelFix).arg(fi.suffix()); } break; case 3: //删除后缀 { if (fi.baseName().endsWith(addOrDelFix) && (fi.baseName() != addOrDelFix)) { return QString("%1/%2.%3").arg(dir.absolutePath()).arg(fi.baseName().mid(0, fi.baseName().length() - addOrDelFix.length())).arg(fi.suffix()); } } break; case 4: return QString("%1/%2.%3").arg(dir.absolutePath()).arg(fi.baseName().toLower()).arg(fi.suffix()); case 5: return QString("%1/%2.%3").arg(dir.absolutePath()).arg(fi.baseName().toUpper()).arg(fi.suffix()); default: break; } return QString(); }; ProgressWin* m_loadFileProcessWin = new ProgressWin(this); m_loadFileProcessWin->setWindowModality(Qt::WindowModal); m_loadFileProcessWin->info(tr("rename file in progress, please wait ...")); m_loadFileProcessWin->show(); int processTotal = 0; bool isExistChildDir = false; while (!dirsList.isEmpty()) { QString path = dirsList.takeFirst(); /*添加path路径文件*/ QDir dir(path); //遍历各级子目录 if (dealChildDir) { QFileInfoList folder_list = dir.entryInfoList(QDir::Dirs | QDir::NoDotAndDotDot | QDir::Hidden | QDir::NoSymLinks); //获取当前所有目录 for (int i = 0; i != folder_list.size(); ++i) //自动递归添加各目录到上一级目录 { QString namepath = folder_list.at(i).absoluteFilePath(); //获取路径 //必须放前面,因为以文件夹个数处理为进度条计数 dirsList.push_front(namepath); } if ((processTotal == 0) && dirsList.size() > 0) { //以目录个数大概去统计进度 processTotal = dirsList.size(); m_loadFileProcessWin->setTotalSteps(processTotal); isExistChildDir = true; } if (dirsList.size() < processTotal) { m_loadFileProcessWin->moveStep(); } } QDir dir_file(path); dir_file.setFilter(QDir::Files | QDir::NoDotAndDotDot | QDir::NoSymLinks);//获取当前所有文件 QFileInfoList list_file = dir_file.entryInfoList(); //说明没有子文件夹 if ((processTotal == 0) && list_file.size() > 0) { processTotal = list_file.size(); m_loadFileProcessWin->setTotalSteps(processTotal); } for (int i = 0; i < list_file.size(); ++i) { QFileInfo fileInfo = list_file.at(i); oldName = fileInfo.absoluteFilePath(); newName = getNewName(oldName,type, extrenFileName); if (!newName.isEmpty() && (newName != oldName)) { if (!QFile::rename(oldName, newName)) { failNums++; m_loadFileProcessWin->info(tr("failed %1 file path %2, please check").arg(failNums).arg(oldName)); } fileNums++; } //没有子文件夹时,按文件数量走 if (!isExistChildDir) { m_loadFileProcessWin->moveStep(); } } } QMessageBox::information(this, tr("Notice"), tr("Deal Finished, totol %1 files, failed %2 files").arg(fileNums).arg(failNums)); delete m_loadFileProcessWin; } void ReNameWin::changeFileExt() { QString dealDir = ui.lineEditDir->text(); QString destExt = ui.lineEditDestExt->text(); if (destExt.startsWith('.')) { destExt = destExt.mid(1, destExt.length() - 1); } if (dealDir.isEmpty() || destExt.isEmpty()) { QMessageBox::warning(this, tr("Notice"), tr("Please Select Dir Or Dest Ext")); return; } QString filterExt; bool isNeedFilterExt = false; if (0 != ui.comboBoxExt->currentIndex()) { filterExt = ui.comboBoxExt->currentText(); if (filterExt.startsWith('.')) { filterExt = filterExt.mid(1, filterExt.length() - 1); } } //检查是否需要过滤只处理ext类型 if (!filterExt.isEmpty()) { isNeedFilterExt = true; } QList<QString> dirsList; dirsList.append(dealDir); int fileNums = 0; int failNums = 0; bool dealChildDir = ui.checkBoxDealChildDir->isChecked(); QString oldName; QString newName; auto getNewName = [](QString oldName, const QString& destExt)->QString{ QFileInfo fi(oldName); //没有后缀名,则不修改 if (fi.suffix().isEmpty()) { return QString(); } int oldExtSize = fi.suffix().length(); return QString("%1%2").arg(oldName.mid(0, oldName.size()-oldExtSize)).arg(destExt); }; ProgressWin* m_loadFileProcessWin = new ProgressWin(this); m_loadFileProcessWin->setWindowModality(Qt::WindowModal); m_loadFileProcessWin->info(tr("rename file in progress, please wait ...")); m_loadFileProcessWin->show(); int processTotal = 0; bool isExistChildDir = false; while (!dirsList.isEmpty()) { QString path = dirsList.takeFirst(); /*添加path路径文件*/ QDir dir(path); //遍历各级子目录 if (dealChildDir) { QFileInfoList folder_list = dir.entryInfoList(QDir::Dirs | QDir::NoDotAndDotDot | QDir::Hidden | QDir::NoSymLinks); //获取当前所有目录 for (int i = 0; i != folder_list.size(); ++i) //自动递归添加各目录到上一级目录 { QString namepath = folder_list.at(i).absoluteFilePath(); //获取路径 //必须放前面,因为以文件夹个数处理为进度条计数 dirsList.push_front(namepath); } if ((processTotal == 0) && dirsList.size() > 0) { //以目录个数大概去统计进度 processTotal = dirsList.size(); m_loadFileProcessWin->setTotalSteps(processTotal); isExistChildDir = true; } if (dirsList.size() < processTotal) { m_loadFileProcessWin->moveStep(); } } QDir dir_file(path); dir_file.setFilter(QDir::Files | QDir::NoDotAndDotDot | QDir::NoSymLinks);//获取当前所有文件 QFileInfoList list_file = dir_file.entryInfoList(); //说明没有子文件夹 if ((processTotal == 0) && list_file.size() > 0) { processTotal = list_file.size(); m_loadFileProcessWin->setTotalSteps(processTotal); } for (int i = 0; i < list_file.size(); ++i) { QFileInfo fileInfo = list_file.at(i); oldName = fileInfo.absoluteFilePath(); if (isNeedFilterExt) { if (fileInfo.suffix() != filterExt) { continue; } } newName = getNewName(oldName, destExt); if (!newName.isEmpty() && (newName != oldName)) { if (!QFile::rename(oldName, newName)) { failNums++; m_loadFileProcessWin->info(tr("failed %1 file path %2, please check").arg(failNums).arg(oldName)); } } //没有子文件夹时,按文件数量走 if (!isExistChildDir) { m_loadFileProcessWin->moveStep(); } } fileNums += list_file.size(); } QMessageBox::information(this, tr("Notice"), tr("Deal Finished, totol %1 files, failed %2 files").arg(fileNums).arg(failNums)); delete m_loadFileProcessWin; }
11,868
C++
.cpp
374
25.938503
146
0.673416
cxasm/notepad--
5,942
234
284
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
25,157
draglineedit.cpp
cxasm_notepad--/src/draglineedit.cpp
#include "draglineedit.h" DragLineEdit::DragLineEdit(QWidget *parent) : QLineEdit(parent) { setAcceptDrops(true); } DragLineEdit::~DragLineEdit() { } void DragLineEdit::dragEnterEvent(QDragEnterEvent* event) { if (event->mimeData()->hasFormat("text/uri-list")) //只能打开文本文件 { event->accept(); //可以在这个窗口部件上拖放对象 } else { event->ignore(); } } void DragLineEdit::dragMoveEvent(QDragMoveEvent* ) { } void DragLineEdit::dropEvent(QDropEvent* e) { QList<QUrl> urls = e->mimeData()->urls(); if (urls.isEmpty()) return; QString fileName = urls.first().toLocalFile(); if (fileName.isEmpty()) { return; } if (!QFile::exists(fileName)) { return; } this->setText(fileName); e->accept(); emit this->returnPressed(); }
817
C++
.cpp
41
16.121951
63
0.687158
cxasm/notepad--
5,942
234
284
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
25,158
closeDlg.cpp
cxasm_notepad--/src/closeDlg.cpp
#include "closeDlg.h" closeDlg::closeDlg(QWidget *parent): QDialog(parent) { ui.setupUi(this); } closeDlg::~closeDlg() { } void closeDlg::save() { if (ui.leftBox->isChecked() && ui.rightBox->isChecked()) { done(3); } else if (ui.leftBox->isChecked()) { done(1); } else if (ui.rightBox->isChecked()) { done(2); } else { done(0); } } void closeDlg::discard() { done(-1); } void closeDlg::cancel() { done(-2); }
478
C++
.cpp
35
10.685714
58
0.607889
cxasm/notepad--
5,942
234
284
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
25,159
dectfilechanges.cpp
cxasm_notepad--/src/dectfilechanges.cpp
#include "dectfilechanges.h" #ifdef WIN32 DectFileChanges::DectFileChanges():m_lastFileSize(0), m_curFileSize(0) { _szFile = NULL; _dwNotifyFilter = 0; } DectFileChanges::~DectFileChanges() { } BOOL DectFileChanges::DetectChanges() { WIN32_FILE_ATTRIBUTE_DATA fInfo; BOOL rValue = FALSE; ::GetFileAttributesEx(_szFile, GetFileExInfoStandard, &fInfo); if ((_dwNotifyFilter & FILE_NOTIFY_CHANGE_SIZE) && (fInfo.nFileSizeHigh != _lastFileInfo.nFileSizeHigh || fInfo.nFileSizeLow != _lastFileInfo.nFileSizeLow)) { rValue = TRUE; } if ((_dwNotifyFilter & FILE_NOTIFY_CHANGE_LAST_WRITE) && (fInfo.ftLastWriteTime.dwHighDateTime != _lastFileInfo.ftLastWriteTime.dwHighDateTime || fInfo.ftLastWriteTime.dwLowDateTime != _lastFileInfo.ftLastWriteTime.dwLowDateTime)) { rValue = TRUE; } if (rValue) { m_lastFileSize = getFileSize(_lastFileInfo); } _lastFileInfo = fInfo; if (rValue) { m_curFileSize = getFileSize(_lastFileInfo); } return rValue; } void DectFileChanges::AddFile(LPCTSTR szFile, DWORD dwNotifyFilter) { _szFile = szFile; _dwNotifyFilter = dwNotifyFilter; ::GetFileAttributesEx(szFile, GetFileExInfoStandard, &_lastFileInfo); } void DectFileChanges::Terminate() { _szFile = NULL; _dwNotifyFilter = 0; } quint64 DectFileChanges::getFileSize(WIN32_FILE_ATTRIBUTE_DATA& data) { quint64 fileSize = data.nFileSizeHigh; fileSize = (fileSize << 32); fileSize += data.nFileSizeLow; return fileSize; } void DectFileChanges::getDiffFileSize(quint64& lastSize, quint64& curSize) { lastSize = m_lastFileSize; curSize = m_curFileSize; } #endif
1,588
C++
.cpp
55
26.909091
233
0.777704
cxasm/notepad--
5,942
234
284
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
25,160
RcTreeWidget.cpp
cxasm_notepad--/src/RcTreeWidget.cpp
#include "RcTreeWidget.h" #include "MediatorFileTree.h" #include <QScrollBar> #include <QMenu> #include <QProcess> RcTreeWidget::RcTreeWidget(QWidget *parent):QTreeWidget(parent), m_userAddMenu(nullptr) { connect(this->verticalScrollBar(), &QScrollBar::valueChanged, this, &RcTreeWidget::slot_scrollValueChange); //收起和伸开子项 connect(this, &QTreeWidget::itemCollapsed, this, &RcTreeWidget::slot_itemCollapsed); connect(this, &QTreeWidget::itemExpanded, this, &RcTreeWidget::slot_itemExpanded); setContextMenuPolicy(Qt::CustomContextMenu); //设置枚举值 connect(this, &QTreeWidget::customContextMenuRequested, this, &RcTreeWidget::slot_ShowPopMenu); } RcTreeWidget::~RcTreeWidget() { } //给用户进行菜单增加的回调函数 void RcTreeWidget::setContextUserDefineItemMenuCallBack(std::function<void(int dire,QMenu*, QTreeWidgetItem*)>* userAddMenu) { m_userAddMenu = userAddMenu; } //右键菜单 void RcTreeWidget::slot_ShowPopMenu(const QPoint& pos) { QTreeWidgetItem* curItem = this->itemAt(pos); if (curItem != nullptr) { QMenu* menu = new QMenu(this); if (m_userAddMenu != nullptr) { (*m_userAddMenu)(m_direction, menu, curItem); } QAction* action = menu->addAction(tr("Show File in Explorer"), this, [&]() { QString path = QString("%1/%2").arg(m_rootDir).arg(curItem->data(0, Qt::ToolTipRole).toString()); showFileInExplorer(path); }); //没有名称表示是对齐的item,不存在对应的文件,只是占位 if (curItem->text(0).isEmpty()) { action->setEnabled(false); } if (menu) { menu->setAttribute(Qt::WA_DeleteOnClose); menu->exec(QCursor::pos()); } } } //点击收起的槽函数 void RcTreeWidget::slot_itemCollapsed(QTreeWidgetItem *item) { QString name = item->data(0, Qt::ToolTipRole).toString(); //左边变化,通知右边去改变 if (m_direction == RC_LEFT) { //通知右边去收起 m_mediator->setRightItemStatus(name,RC_COLLAPSED); } else { //通知左边去收起 m_mediator->setLeftItemStatus(name, RC_COLLAPSED); } } //点击展开的槽函数 void RcTreeWidget::slot_itemExpanded(QTreeWidgetItem *item) { QString name = item->data(0, Qt::ToolTipRole).toString(); //左边变化,通知右边去改变 if (m_direction == RC_LEFT) { //右边展开 m_mediator->setRightItemStatus(name, RC_EXPANDED); } else { //左边收起 m_mediator->setLeftItemStatus(name, RC_EXPANDED); } } void RcTreeWidget::setDirection(RC_DIRECTION direction) { m_direction = direction; } void RcTreeWidget::setMediator(MediatorFileTree *mediator) { m_mediator = mediator; } //滚动条值变化后的槽函数。一旦滚动则会出发这里,发送消息给中介,让中介去同步另外一方 void RcTreeWidget::slot_scrollValueChange(int value) { if (m_direction == RC_LEFT) { if (m_mediator->getLeftScrollValue() != value) { m_mediator->setLeftScrollValue(value); } } else { if (m_mediator->getRightScrollValue() != value) { m_mediator->setRightScrollValue(value); } } } //注意,这里一旦开始调整后,又会引发滚动条值的变化 void RcTreeWidget::setVerticalValue(int value) { //不相等才需要设置 if (verticalScrollBar()->value() != value) { //超过最大值,只能设置为最大值 if (value > verticalScrollBar()->maximum()) { verticalScrollBar()->setValue(verticalScrollBar()->maximum()); } else { verticalScrollBar()->setValue(value); } } }
3,632
C++
.cpp
124
22.451613
125
0.71241
cxasm/notepad--
5,942
234
284
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
25,161
shortcutkeymgr.cpp
cxasm_notepad--/src/shortcutkeymgr.cpp
#include "shortcutkeymgr.h" #include "shortcutkeyeditwin.h" #include "ccnotepad.h" #include <QTableWidgetItem> #include <QSettings> #include <Qsci/qscicommandset.h> #include <Qsci/qsciscintilla.h> #include <QDebug> QMap<QString, int>* ShortcutKeyMgr::s_shortcutKeysMap = nullptr; struct ShortcutKeySt { QString iniTag;//保存在Ini文件中的名称 QString name;//显示在表格中的名称 QKeySequence key; bool canModify;//能否修改 ShortcutKeySt() = default; ShortcutKeySt(QString name_, QString iniTag_, bool canMofidy=true) :name(name_), iniTag(iniTag_), canModify(canMofidy) { } ShortcutKeySt(QString name_, QString iniTag_, QString keySeq, bool canMofidy = true) :name(name_), iniTag(iniTag_), canModify(canMofidy) { key = QKeySequence(keySeq); } }; QVector<ShortcutKeySt> shortCutTable; ShortcutKeyMgr::ShortcutKeyMgr(QWidget *parent) : QMainWindow(parent) { ui.setupUi(this); initShortcutKeysMap(); initNddShortcutTable(); m_pNoteEdit = parent; initQscintShortcutTable(); connect(ui.tableWidget, &QTableWidget::itemDoubleClicked, this, &ShortcutKeyMgr::slot_edit); ui.tableWidget->horizontalHeader()->setSectionResizeMode(0, QHeaderView::ResizeToContents); ui.tableWidget->horizontalHeader()->setSectionResizeMode(1, QHeaderView::ResizeToContents); ui.tableWidget->horizontalHeader()->setSectionResizeMode(2, QHeaderView::ResizeToContents); ui.qscintTableWidget->horizontalHeader()->setSectionResizeMode(0, QHeaderView::ResizeToContents); ui.qscintTableWidget->horizontalHeader()->setSectionResizeMode(1, QHeaderView::ResizeToContents); ui.qscintTableWidget->horizontalHeader()->setSectionResizeMode(2, QHeaderView::ResizeToContents); QString tabQss = "QHeaderView::section{" "border-top:0px solid #E5E5E5;" "border-left:0px solid #E5E5E5;" "border-right:0.5px solid #E5E5E5;" "border-bottom: 0.5px solid #E5E5E5;" "background-color:white;" "padding:4px;" "}"; ui.tableWidget->horizontalHeader()->setStyleSheet(tabQss); ui.tableWidget->verticalHeader()->setStyleSheet(tabQss); ui.qscintTableWidget->horizontalHeader()->setStyleSheet(tabQss); ui.qscintTableWidget->verticalHeader()->setStyleSheet(tabQss); } ShortcutKeyMgr::~ShortcutKeyMgr() {} void ShortcutKeyMgr::initShortcutKeysMap() { if (s_shortcutKeysMap == nullptr) { s_shortcutKeysMap = new QMap<QString, int>(); shortCutTable << ShortcutKeySt(tr("New File"), New_File, QString("Ctrl+T")) \ << ShortcutKeySt(tr("Open File"), Open_File, QString("Ctrl+O")) \ << ShortcutKeySt(tr("Save File"), Save_File, QString("Ctrl+S"), false) \ << ShortcutKeySt(tr("Save All File"), Save_All_File) \ << ShortcutKeySt(tr("Close"), Close, QString("Ctrl+W")) \ << ShortcutKeySt(tr("Close All"), Close_All, QString("Ctrl+Shift+W")) \ << ShortcutKeySt(tr("Cut"), Cut, QString("Ctrl+X"), false) \ << ShortcutKeySt(tr("Copy"), Copy, QString("Ctrl+C"), false) \ << ShortcutKeySt(tr("Paste"), Paste, QString("Ctrl+V"), false) \ << ShortcutKeySt(tr("Undo"), Undo, QString("Ctrl+Z"), false) \ << ShortcutKeySt(tr("Redo"), Redo, QString("Ctrl+Y"), false) \ << ShortcutKeySt(tr("Find"), Find, QString("Ctrl+F"), false) \ << ShortcutKeySt(tr("Replace"), Replace, QString("Ctrl+H")) \ << ShortcutKeySt(tr("Dir Find"), DirFind, QString("Ctrl+Shift+D")) \ << ShortcutKeySt(tr("Mark"), Mark) \ << ShortcutKeySt(tr("word highlight(F8)"), Word_highlight, QString("F8"))\ << ShortcutKeySt(tr("clear all highlight(F7)"), Clear_all_highlight, QString("F7")) \ << ShortcutKeySt(tr("Zoom In"), Zoom_In) \ << ShortcutKeySt(tr("Zoom Out"), Zoom_Out) \ << ShortcutKeySt(tr("Word Wrap"), Word_Wrap) \ << ShortcutKeySt(tr("Show Blank"), Show_Blank) \ << ShortcutKeySt(tr("Indent Guide"), Indent_Guide) \ << ShortcutKeySt(tr("Pre Hex Page"), Pre_Page) \ << ShortcutKeySt(tr("Next Hex Page"), Next_Page)\ << ShortcutKeySt(tr("Goto Hex Page"), Goto_Page, QString("Ctrl+G")) \ << ShortcutKeySt(tr("File Compare"), File_Compare) \ << ShortcutKeySt(tr("Dir Compare"), Dir_Compare) \ << ShortcutKeySt(tr("Bin Compare"), Bin_Compare) \ << ShortcutKeySt(tr("transform encoding"), Trans_code) \ << ShortcutKeySt(tr("batch rename file"), Batch_rename) \ << ShortcutKeySt(tr("Format Xml"), Format_Xml) \ << ShortcutKeySt(tr("Format Json"), Format_Json) \ << ShortcutKeySt(tr("Add/Del Line Comment"), ADD_DELETE_LINE_COMMENT, QString("Ctrl+Q")) \ << ShortcutKeySt(tr("Add Block Comment"), ADD_BLOCK_COMMENT, QString("Ctrl+K")) \ << ShortcutKeySt(tr("Del Block Comment"), CANCEL_BLOCK_COMMENT, QString("Ctrl+Shift+K")) \ << ShortcutKeySt(tr("Fold Level 1"), FOLD_1, QString("Alt+1")) \ << ShortcutKeySt(tr("Fold Level 2"), FOLD_2, QString("Alt+2")) \ << ShortcutKeySt(tr("Fold Level 3"), FOLD_3, QString("Alt+3")) \ << ShortcutKeySt(tr("Fold Level 4"), FOLD_4, QString("Alt+4")) \ << ShortcutKeySt(tr("Fold Level 5"), FOLD_5, QString("Alt+5")) \ << ShortcutKeySt(tr("Fold Level 6"), FOLD_6, QString("Alt+6")) \ << ShortcutKeySt(tr("Fold Level 7"), FOLD_7, QString("Alt+7")) \ << ShortcutKeySt(tr("Fold Level 8"), FOLD_8, QString("Alt+8")) \ << ShortcutKeySt(tr("UNFold Level 1"), UNFOLD_1, QString("Alt+Shift+1")) \ << ShortcutKeySt(tr("UNFold Level 2"), UNFOLD_2, QString("Alt+Shift+2")) \ << ShortcutKeySt(tr("UNFold Level 3"), UNFOLD_3, QString("Alt+Shift+3")) \ << ShortcutKeySt(tr("UNFold Level 4"), UNFOLD_4, QString("Alt+Shift+4")) \ << ShortcutKeySt(tr("UNFold Level 5"), UNFOLD_5, QString("Alt+Shift+5")) \ << ShortcutKeySt(tr("UNFold Level 6"), UNFOLD_6, QString("Alt+Shift+6")) \ << ShortcutKeySt(tr("UNFold Level 7"), UNFOLD_7, QString("Alt+Shift+7")) \ << ShortcutKeySt(tr("UNFold Level 8"), UNFOLD_8, QString("Alt+Shift+8")); for (int i = 0; i < shortCutTable.size(); ++i) { s_shortcutKeysMap->insert(shortCutTable.at(i).iniTag, i); } //从文件中读取用户修改过的配置表。 loadUserDefSet(); } } //务必先调用initShortcutKeysMap() QKeySequence ShortcutKeyMgr::getUserDefShortcutKey(QString iniTag) { if (s_shortcutKeysMap->contains(iniTag)) { return shortCutTable.at(s_shortcutKeysMap->value(iniTag)).key; } return QKeySequence(); } //从用户ini配置中加载快捷键配置 void ShortcutKeyMgr::loadUserDefSet() { QString userDefFile = QString("notepad/shortcuttab"); QSettings qs(QSettings::IniFormat, QSettings::UserScope, userDefFile); qs.setIniCodec("UTF-8"); QStringList keys = qs.allKeys(); QString keySeqStr; for (int i = 0; i < keys.size(); ++i) { const QString & initTag = keys.at(i); keySeqStr = qs.value(initTag).toString(); if (s_shortcutKeysMap->contains(initTag)) { int index = s_shortcutKeysMap->value(initTag); shortCutTable[index].key = QKeySequence(keySeqStr); } } } //修改配置文件中的快捷键定义。inittag ini的key, keySeqStr ini的value。内存也修改了 bool ShortcutKeyMgr::ModifyShortCutKey(QString initTag, QString keySeqStr) { QString userDefFile = QString("notepad/shortcuttab"); QSettings qs(QSettings::IniFormat, QSettings::UserScope, userDefFile); qs.setIniCodec("UTF-8"); if (s_shortcutKeysMap->contains(initTag)) { int index = s_shortcutKeysMap->value(initTag); if (!shortCutTable[index].canModify) { return false; } shortCutTable[index].key = QKeySequence(keySeqStr); qs.setValue(initTag, keySeqStr); qs.sync(); return true; } return false; } void ShortcutKeyMgr::initNddShortcutTable() { for (int i = 0; i < shortCutTable.size(); ++i) { ui.tableWidget->insertRow(i); QTableWidgetItem* item = new QTableWidgetItem(shortCutTable.at(i).name); item->setFlags(item->flags() & ~Qt::ItemIsEditable); ui.tableWidget->setItem(i, 0, item); qDebug() << shortCutTable.at(i).key.toString(); QTableWidgetItem* item1 = new QTableWidgetItem(shortCutTable.at(i).key.toString()); ui.tableWidget->setItem(i, 1, item1); if (!shortCutTable.at(i).canModify) { QTableWidgetItem* item2 = new QTableWidgetItem(tr("Can't Modify")); ui.tableWidget->setItem(i, 2, item2); } else { QTableWidgetItem* item2 = new QTableWidgetItem(tr("Double Click To Modify")); ui.tableWidget->setItem(i, 2, item2); } } } //初始化qscint内部的快捷键。目前这部分不能修改。 void ShortcutKeyMgr::initQscintShortcutTable() { QsciScintilla* pNote = new QsciScintilla(nullptr); QsciCommandSet* cmdSet = pNote->standardCommands(); QList<QsciCommand*>& cmdList = cmdSet->commands(); int rowNum = 0; for (int i = 0; i < cmdList.size(); ++i) { if (cmdList.at(i)->key() == 0) { continue; } ui.qscintTableWidget->insertRow(rowNum); QTableWidgetItem* item = new QTableWidgetItem(cmdList.at(i)->description()); item->setFlags(item->flags() & ~Qt::ItemIsEditable); ui.qscintTableWidget->setItem(rowNum, 0, item); QTableWidgetItem* item1 = new QTableWidgetItem(QKeySequence(cmdList.at(i)->key()).toString()); ui.qscintTableWidget->setItem(rowNum, 1, item1); QTableWidgetItem* item2 = new QTableWidgetItem(tr("Can't Modify")); ui.qscintTableWidget->setItem(rowNum, 2, item2); ++rowNum; } delete pNote; } //type 0 ndd 1 qscint int ShortcutKeyMgr::isKeySeqExist(int row, QString keySeq, int &type) { int c = ui.tableWidget->rowCount(); for (int i = 0; i < c; ++i) { if (i == row) { continue; } if (ui.tableWidget->item(i, 1)->text() == keySeq) { type = 0; return i; } } c = ui.qscintTableWidget->rowCount(); for (int i = 0; i < c; ++i) { if (ui.qscintTableWidget->item(i, 1)->text() == keySeq) { type = 1; return i; } } return -1; } //双击修改槽函数 void ShortcutKeyMgr::slot_edit(QTableWidgetItem* item) { int row = item->row(); if (!shortCutTable.at(row).canModify) { ui.plainTextEdit->setPlainText(tr("row %1 shortcut key '%2' can't modify !").arg(row + 1).arg(shortCutTable.at(row).key.toString())); return; } ShortcutKeyEditWin* pWin = new ShortcutKeyEditWin(this); pWin->setTitle(shortCutTable.at(row).name); pWin->setCurKeyDesc(shortCutTable.at(row).key.toString()); int ret = pWin->exec(); if (1 == ret) //确定 { QKeySequence newKeySeq = pWin->getNewKeySeq(); QTableWidgetItem* item = ui.tableWidget->item(row, 1); if (item != nullptr) { //检查是否冲突,如果冲突,则不设置。先预留 int conflictType = 0; int existId = isKeySeqExist(row, newKeySeq.toString(), conflictType); if (-1 == existId) { if (ModifyShortCutKey(shortCutTable.at(row).iniTag, newKeySeq.toString())) { CCNotePad* pNotePad = dynamic_cast<CCNotePad*>(m_pNoteEdit); if (pNotePad != nullptr) { pNotePad->setUserDefShortcutKey(row); } item->setText(newKeySeq.toString()); ui.plainTextEdit->setPlainText(tr("modify row %1 to '%2' shortcut key success!").arg(row + 1).arg(newKeySeq.toString())); } else { ui.plainTextEdit->setPlainText(tr("error:modify row %1 to '%2' shortcut key failed !").arg(row + 1).arg(newKeySeq.toString())); } } else { if (conflictType == 0) { ui.plainTextEdit->setPlainText(tr("conflict error! '%1' Already exist at row %2").arg(newKeySeq.toString()).arg(existId + 1)); } else { ui.plainTextEdit->setPlainText(tr("conflict error! '%1' Already exist at qscint row %2").arg(newKeySeq.toString()).arg(existId + 1)); } } } } else if (2 == ret)//删除 { QKeySequence newKeySeq(QKeySequence::UnknownKey); QTableWidgetItem* item = ui.tableWidget->item(row, 1); if (item != nullptr) { if (ModifyShortCutKey(shortCutTable.at(row).iniTag, newKeySeq.toString())) { CCNotePad* pNotePad = dynamic_cast<CCNotePad*>(m_pNoteEdit); if (pNotePad != nullptr) { pNotePad->setUserDefShortcutKey(row); } item->setText(newKeySeq.toString()); ui.plainTextEdit->setPlainText(tr("modify row %1 to '%2' shortcut key success!").arg(row + 1).arg("NULL")); } else { ui.plainTextEdit->setPlainText(tr("error:modify row %1 to '%2' shortcut key failed !").arg(row + 1).arg("NULL")); } } } else { ui.plainTextEdit->setPlainText(tr("modify canceled !")); } }
12,542
C++
.cpp
320
34.128125
139
0.682593
cxasm/notepad--
5,942
234
284
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
25,162
gotolinewin.cpp
cxasm_notepad--/src/gotolinewin.cpp
#include "gotolinewin.h" GoToLineWin::GoToLineWin(QWidget *parent) : QWidget(parent) { ui.setupUi(this); } GoToLineWin::~GoToLineWin() { } void GoToLineWin::slot_ok() { bool ok; int lineNums = ui.lineEditNum->text().toInt(&ok); if (ok && lineNums>=1) { int dire = (ui.radioButton->isChecked() ? 0 : 1); emit sign_gotoLine(dire, lineNums-1); close(); } }
393
C++
.cpp
20
16.7
52
0.659401
cxasm/notepad--
5,942
234
284
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
25,163
rcglobal.cpp
cxasm_notepad--/src/rcglobal.cpp
#include "rcglobal.h" #include <QSettings> #include <QFileInfo> #include <QDir> #include <QProcess> QString s_userLangDirPath; QString getUserLangDirPath() { if (s_userLangDirPath.isEmpty()) { QString settingDir = QString("notepad/userlang/test"); QSettings qs(QSettings::IniFormat, QSettings::UserScope, settingDir); QString qsSavePath = qs.fileName(); QFileInfo fi(qsSavePath); s_userLangDirPath = fi.dir().absolutePath(); //保存起来userLangPath,避免后续每次都要去查找。注意这个目录是在notepad/userlang这个级别 } return s_userLangDirPath; } const int M_SIZE = 1024 * 1024; const int G_SIZE = 1024 * 1024 * 1024; //把字节大小文件,转换为M 或 G 单位 QString tranFileSize(qint64 fileSize) { float num = 0.0f; QString unit; if (fileSize >= G_SIZE) { num = double(fileSize) / G_SIZE; unit = "GB"; } else if (fileSize >= M_SIZE) { num = double(fileSize) / M_SIZE; unit = "MB"; } else if (fileSize > 1024) { num = float(fileSize) / 1024; unit = "KB"; } else { return QString("%1").arg(fileSize); } return QString("%1 %2").arg(num, 0, 'f' , 2).arg(unit); } void showFileInExplorer(QString path) { QString cmd; #ifdef _WIN32 path = path.replace("/", "\\"); cmd = QString("explorer.exe /select,%1").arg(path); #endif #ifdef ubu path = path.replace("\\", "/"); cmd = QString("nautilus %1").arg(path); #endif #ifdef uos path = path.replace("\\", "/"); cmd = QString("dde-file-manager %1").arg(path); #endif #if defined(Q_OS_MAC) path = path.replace("\\", "/"); cmd = QString("open -R %1").arg(path); #endif QProcess process; process.startDetached(cmd); }
1,743
C++
.cpp
69
20.782609
72
0.661538
cxasm/notepad--
5,942
234
284
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
25,164
main.cpp
cxasm_notepad--/src/main.cpp
#include "ccnotepad.h" #include "nddsetting.h" #include "styleset.h" #include <QtWidgets/QApplication> #include <QTextCodec> #include <QMessageBox> #include <QSharedMemory> #include <QFile> #include <QStatusBar> #include <qobject.h> #include <QThread> #include <QDir> #ifdef Q_OS_UNIX #include <QStyleFactory> #include <signal.h> #include <unistd.h> #include <QDebug> #include <QWidget> #endif #ifdef Q_OS_WIN #pragma comment(lib, "user32.lib") #if _DEBUG #pragma comment(lib, "qmyedit_qt5d.lib") #else #pragma comment(lib, "qmyedit_qt5.lib") #endif #include <qt_windows.h> const ULONG_PTR CUSTOM_TYPE = 10000; const ULONG_PTR OPEN_NOTEPAD_TYPE = 10001; const ULONG_PTR CUSTOM_TYPE_FILE_LINENUM = 10002; bool s_isAdminAuth = false; #endif const QString c_strTitle = "Ndd"; #ifdef Q_OS_UNIX #if defined(Q_OS_MAC) QSharedMemory shared("CCNotebook123");;//mac下面后面带一个版本号,避免新的打不开 #else QSharedMemory shared("CCNotebook"); #endif QSharedMemory nppShared("notepad--"); static void sig_usr(int signo) { if(signo == SIGUSR1) { qlonglong winId; shared.lock(); memcpy(&winId,shared.data(),sizeof(qlonglong)); shared.unlock(); QWidget *pMain = QWidget::find((WId)winId); CCNotePad* pNotePad = dynamic_cast<CCNotePad*>(pMain); if(pNotePad != nullptr) { QString filePath((char*)nppShared.data()+4); if(!filePath.isEmpty()) { pNotePad->openFile(filePath); } pNotePad->activateWindow(); pNotePad->showNormal(); qDebug() << "sig_usr" << filePath; } } } #endif #ifdef Q_OS_MAC static void openfile(QString filePath) { qlonglong winId; shared.lock(); memcpy(&winId,shared.data(),sizeof(qlonglong)); shared.unlock(); QWidget *pMain = QWidget::find((WId)winId); CCNotePad* pNotePad = dynamic_cast<CCNotePad*>(pMain); if(pNotePad != nullptr) { if(!filePath.isEmpty()) { pNotePad->openFile(filePath); } pNotePad->activateWindow(); pNotePad->showNormal(); } } class MyApplication : public QApplication { public: MyApplication(int &argc, char **argv) : QApplication(argc, argv) { } bool event(QEvent *event) { if (event->type() == QEvent::FileOpen) { QFileOpenEvent *openEvent = static_cast<QFileOpenEvent *>(event); qDebug() << "Open file" << openEvent->file(); s_openfile = openEvent->file(); openfile(s_openfile); } return QApplication::event(event); } QString s_openfile; }; #endif int main(int argc, char *argv[]) { //可以防止某些屏幕下的字体拥挤重叠问题。暂时屏蔽,不使用qt方法,使用windows自带方案 // 发现windows自带方案模糊。//发现下面打开后,在win10上反而效果不好,界面会变得很大,默认还是不开启的好。 //QApplication::setAttribute(Qt::AA_EnableHighDpiScaling); //QApplication::setHighDpiScaleFactorRoundingPolicy(Qt::HighDpiScaleFactorRoundingPolicy::PassThrough); //QApplication::setHighDpiScaleFactorRoundingPolicy(Qt::HighDpiScaleFactorRoundingPolicy::RoundPreferFloor); #ifdef Q_OS_MAC MyApplication a(argc, argv); #else QApplication a(argc, argv); #endif //不能开启,开启后相对路径打开文件失败 //QDir::setCurrent(QCoreApplication::applicationDirPath()); #if defined(Q_OS_UNIX) QApplication::setStyle(QStyleFactory::create("fusion")); #endif a.setApplicationDisplayName(c_strTitle); a.setApplicationName(c_strTitle); QStringList arguments = QCoreApplication::arguments(); //目前就三种 //1) ndd filepath //2) ndd filepath -n linenum //3) ndd -multi filepath //只有 1 2 需要处理短路径 if ((arguments.size() == 2) || (arguments.size() == 4)) { QFileInfo fi(arguments[1]); if (fi.isRelative()) { QString absDir = QDir::currentPath(); //获取绝对路径 arguments[1] = QString("%1/%2").arg(absDir).arg(arguments.at(1)); } } #ifdef uos QFont font("Noto Sans CJK SC,9,-1,5,50,0,0,0,0,0,Regular", 9); QApplication::setFont(font); #endif #ifdef Q_OS_MAC //这里的字体大小,务必要和查找结果框的高度匹配,否则会结构字体拥挤 QFont font("Courier New,11,-1,5,50,0,0,0,0,0,Regular", 11); // qDebug() << "font name mac"; QApplication::setFont(font); // qDebug() << QApplication::font().toString(); #endif bool isGotoLine = false; #ifdef Q_OS_WIN QSharedMemory shared("ccnotepad"); if (arguments.size() > 2) { //如果是多开请求,这种是从管理员权限申请后重开过来的 if (arguments[1] == QString("-muti")) { s_isAdminAuth = true; QString title = QString(u8"%1 管理员").arg(c_strTitle); a.setApplicationDisplayName(title); //删除-muti这个参数 arguments.removeAt(1); //管理员不占用共享标志。这样的目的是,当管理员窗口存在时 //打开原来的文件,原来的文件可以占用共享标志,作为主窗口打开。 //管理员窗口永远不做主窗口打开 goto authAdmin; } else if ((arguments.size() == 4) && arguments[2] == QString("-n")) { //使用的是 file -n lineNums 方式。目前只有windows下支持 xxxfile -n linenum的格式 isGotoLine = true; } } #else if ((arguments.size() == 4) && (arguments[2] == QString("-n"))) { //使用的是 file -n lineNums 方式。目前只有windows下支持 xxxfile -n linenum的格式 isGotoLine = true; } #endif //attach成功表示已经存在该内存了,表示当前存在实例 if (shared.attach())//共享内存被占用则直接返回 { //发现在文件中如果存在空格时,参数不止1个,所以不能单纯用2个参数表示 if (arguments.size() > 1) { #if defined(Q_OS_WIN) int tryTimes = 0; do { qlonglong hwndId; shared.lock(); memcpy(&hwndId, shared.data(), sizeof(qlonglong)); shared.unlock(); HWND hwnd = (HWND)hwndId; if (::IsWindow(hwnd)) { if (!isGotoLine) { //就是ndd filepath的命令行格式 //去掉第一个参数,后续的参数拼接起来。其实参数中间有空格还是需要使用""引用起来,避免空格参数分隔为多个 arguments.takeFirst(); QString filename = arguments.join(""); QByteArray data = filename.toUtf8(); COPYDATASTRUCT copydata; copydata.dwData = CUSTOM_TYPE; //自定义类型 copydata.lpData = data.data(); //数据大小 copydata.cbData = data.size(); // 指向数据的指针 ::SendMessage(hwnd, WM_COPYDATA, reinterpret_cast<WPARAM>(nullptr), reinterpret_cast<LPARAM>(&copydata)); } else { //是 filepath -n linenums 方式。不考虑filepath含有空格的情况,因为前面做了严格判断 QString para = QString("%1|%2").arg(arguments[1]).arg(arguments[3]); QByteArray data = para.toUtf8(); COPYDATASTRUCT copydata; copydata.dwData = CUSTOM_TYPE_FILE_LINENUM; //自定义类型 copydata.lpData = data.data(); //数据大小 copydata.cbData = data.size(); // 指向数据的指针 ::SendMessage(hwnd, WM_COPYDATA, reinterpret_cast<WPARAM>(nullptr), reinterpret_cast<LPARAM>(&copydata)); } break; } else { //20230304 右键多个文件同时打开,比如3个。此时只有第1个可获取锁,其余2个均走这里。 //因为第个还没有来的及写入hwnd。此时不要goto drop_old。等一下再重试 QThread::sleep(1); ++tryTimes; //2次识别后,没法了,只能通过继续往下走。 //失败了,此时说明前一个窗口极可能状态错误了。如果不处理,则再也打不开程序了 if (tryTimes > 2) { goto drop_old; } } } while (true); #elif defined (Q_OS_MAC) { //mac下面不需要,有他自身的机制保证 } #else pid_t pid; arguments.takeFirst(); QString filename = arguments.join(""); QByteArray data = filename.toUtf8(); nppShared.attach(); nppShared.lock(); memcpy(&pid, nppShared.data(), sizeof(pid_t)); memset((char*)nppShared.data()+sizeof(pid_t),0, 1024-sizeof(pid_t)); memcpy((char*)nppShared.data()+sizeof(pid_t),data.data(),data.size()); nppShared.unlock(); //if kill failed, then open a new process if(0 != kill(pid,SIGUSR1)) { goto unix_goon; } #endif } else if (arguments.size() == 1) { #if defined(Q_OS_WIN) //把窗口设置到最前 qlonglong hwndId; shared.lock(); memcpy(&hwndId, shared.data(), sizeof(qlonglong)); shared.unlock(); HWND hwnd = (HWND)hwndId; if (::IsWindow(hwnd)) { QString filename("open"); QByteArray data = filename.toUtf8(); COPYDATASTRUCT copydata; copydata.dwData = OPEN_NOTEPAD_TYPE; //自定义类型 copydata.lpData = data.data(); //数据大小 copydata.cbData = data.size(); // 指向数据的指针 ::SendMessage(hwnd, WM_COPYDATA, reinterpret_cast<WPARAM>(nullptr), reinterpret_cast<LPARAM>(&copydata)); } else { //失败了,此时说明前一个窗口极可能状态错误了。如果不处理,则再也打不开程序了 //继续新开一个窗口,放弃之前的旧内容 goto drop_old; } #elif defined (Q_OS_MAC) { //mac下面不需要,有他自身的机制保证 } #else pid_t pid; nppShared.attach(); nppShared.lock(); memcpy(&pid, nppShared.data(), sizeof(pid_t)); memset((char*)nppShared.data()+sizeof(pid_t),0, 1024-sizeof(pid_t)); nppShared.unlock(); qDebug()<<"empty file send"; if(0 != kill(pid,SIGUSR1)) { goto unix_goon; } #endif } return 0; } #if defined(Q_OS_WIN) shared.create(32); #elif defined (Q_OS_MAC) { //mac下面不需要,有他自身的机制保证。当程序已经在线时,再打开程序,系统会自动调用已经存在的程序出现 //不需要使用类似linux下面的机制。 shared.create(32); nppShared.create(32); } #else unix_goon: shared.create(32); nppShared.create(2048); if(signal(SIGUSR1,sig_usr) == SIG_ERR) { qDebug()<<"linux create sign failed"; } #endif #if defined(Q_OS_WIN) authAdmin: drop_old: #endif //20221009发现有小概率出现窗口没有,但是进程还在的诡异问题,加个保护一下 QApplication::setQuitOnLastWindowClosed(true); NddSetting::init(); int id = NddSetting::getKeyValueFromNumSets(SKIN_KEY); StyleSet::setSkin(id); CCNotePad *pMainNotepad = new CCNotePad(true); pMainNotepad->setAttribute(Qt::WA_DeleteOnClose); pMainNotepad->setShareMem(&shared); pMainNotepad->quickshow(); pMainNotepad->syncCurSkinToMenu(id); #ifdef Q_OS_WIN //HWND hwnd = ::FindWindowA("Qt5QWindowIcon", "CCNotebook"); //发现hwnd就是和effectiveWinId相等的,不需要查询了 //管理员可以多开,暂时不把管理员的权限作为主窗口,因为其他用户没有权限右键菜单发送消息给管理员窗口去打开文件 if (!s_isAdminAuth) { qlonglong winId = (qlonglong)pMainNotepad->effectiveWinId(); shared.lock(); memcpy(shared.data(), &winId, sizeof(qlonglong)); shared.unlock(); } #else qlonglong winId = (qlonglong)pMainNotepad->effectiveWinId(); shared.lock(); memcpy(shared.data(), &winId, sizeof(qlonglong)); shared.unlock(); nppShared.attach(); //get proceess id to share memory pid_t pid = getpid(); nppShared.lock(); memcpy(nppShared.data(), &pid, sizeof(pid_t)); nppShared.unlock(); #endif // Q_OS_WIN //恢复上次关闭时的文件 #ifdef Q_OS_WIN if (!s_isAdminAuth) { if (0 == pMainNotepad->restoreLastFiles() && (arguments.size() == 1)) { pMainNotepad->initTabNewOne(); } } #else if (0 == pMainNotepad->restoreLastFiles()) { pMainNotepad->initTabNewOne(); } #endif if (arguments.size() == 2) { #ifdef Q_OS_WIN if (!s_isAdminAuth) { pMainNotepad->openFile(arguments[1]); } else { //如果是管理员,还不能直接打开文件,需要恢复之前文件的修改内容 //恢复不了,再直接打开 pMainNotepad->tryRestoreFile(arguments[1]); } #else pMainNotepad->openFile(arguments[1]); #endif } else if (isGotoLine) { //是filepath -n xxx 格式。 bool ok = true; int lineNum = arguments[3].toInt(&ok); if (!ok) { lineNum = -1; } pMainNotepad->openFile(arguments[1], lineNum); } #ifdef Q_OS_WIN pMainNotepad->checkAppFont(); #endif a.exec(); NddSetting::close(); return 0; }
13,468
C++
.cpp
408
22.568627
112
0.633424
cxasm/notepad--
5,942
234
284
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
25,165
userlexdef.cpp
cxasm_notepad--/src/userlexdef.cpp
#include "userlexdef.h" #include "rcglobal.h" #include <QSettings> UserLexDef::UserLexDef(QObject *parent):QObject(parent) { } UserLexDef::~UserLexDef() { } //自己定义一套读取和保存配置的接口 bool UserLexDef::readUserSettings(QString langTagName) { //自定义语言格式。 //mz:ndd //name:xxx //mother:xxx none/cpp/html 就三种 //keword:xxx QString userLangFile = QString("notepad/userlang/%1").arg(langTagName); QSettings qs(QSettings::IniFormat, QSettings::UserScope, userLangFile); qs.setIniCodec("UTF-8"); if (!qs.contains(QString("mz"))) { //必须包含Mz为Ndd的键,否则错误 return false; } if (qs.value("mz").toString() != QString("ndd")) { return false; } m_motherLang = qs.value("mother").toString(); m_keyword = qs.value("keword").toString().toUtf8(); /*m_keyword.append("\0");*/ return true; } void UserLexDef::setKeyword(QString words) { m_keyword = words.toUtf8(); if (!m_keyword.endsWith('\0')) { m_keyword.append('\0'); } } void UserLexDef::setExtFileTypes(QString extType) { m_extTypes = extType; } QString UserLangMotherToName(UserLangMother words) { QString name; switch (words) { case MOTHER_NONE: name = "None"; break; case MOTHER_CPP: name = "Cpp"; break; default: name = "None"; break; } return name; } void UserLexDef::setMotherLang(UserLangMother words) { m_motherLang = UserLangMotherToName(words); } bool UserLexDef::writeUserSettings(QString langTagName) { //自定义语言格式。 //mz:ndd //name:xxx //mother:xxx none/cpp/html 就三种 //ext:xx xx xx 文件关联后缀名 //keyword:xxx QString userLangFile = QString("notepad/userlang/%1").arg(langTagName); QSettings qs(QSettings::IniFormat, QSettings::UserScope, userLangFile); qs.setIniCodec("UTF-8"); qs.clear(); qs.setValue("mz", langTagName); qs.setValue("mother", m_motherLang); qs.setValue("ext", m_extTypes); qs.setValue("keyword", m_keyword.data()); return true; } const char * UserLexDef::keywords(int set) const { if (m_keyword.isEmpty()) { return nullptr; } return m_keyword.data(); }
2,170
C++
.cpp
93
19.387097
73
0.698477
cxasm/notepad--
5,942
234
284
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
25,166
qscidisplaywindow.cpp
cxasm_notepad--/src/qscidisplaywindow.cpp
#include "qscidisplaywindow.h" #include "MediatorDisplay.h" #include "textfind.h" #include "common.h" #include "styleset.h" #include "rcglobal.h" #include <QScrollBar> #include <QFileInfo> #include <QProcess> #include <QMessageBox> #include <stdexcept> #include <SciLexer.h> QsciDisplayWindow::QsciDisplayWindow(QWidget *parent):QsciScintilla(parent), m_textFindWin(nullptr), m_preFirstLineNum(0), m_isShowFindItem(true), m_hasHighlight(false) { //20210815 左右行同步还有问题,暂时不屏蔽,不实现 connect(this->verticalScrollBar(), &QScrollBar::valueChanged, this, &QsciDisplayWindow::slot_scrollYValueChange); connect(this->horizontalScrollBar(), &QScrollBar::valueChanged, this, &QsciDisplayWindow::slot_scrollXValueChange); setAcceptDrops(false); m_findStartPos = 0; m_findEndPos = 0; m_findCurPos = 0; m_pScintillaFunc = (SCINTILLA_FUNC)this->SendScintillaPtrResult(SCI_GETDIRECTFUNCTION); m_pScintillaPtr = (SCINTILLA_PTR)this->SendScintillaPtrResult(SCI_GETDIRECTPOINTER); if (!m_pScintillaFunc) { throw std::runtime_error("ScintillaEditView::init : SCI_GETDIRECTFUNCTION message failed"); } if (!m_pScintillaPtr) { throw std::runtime_error("ScintillaEditView::init : SCI_GETDIRECTPOINTER message failed"); } //这个无比要设置false,否则双击后高亮单词,拷贝时会拷贝多个选择。 execute(SCI_SETMULTIPLESELECTION, true); execute(SCI_SETMULTIPASTE, 1); execute(SCI_SETADDITIONALCARETSVISIBLE, false); execute(SCI_SETSELFORE, true, 0x0); execute(SCI_SETSELBACK, true, 0x00ffff); //QColor foldfgColor(StyleSet::foldfgColor); //QColor foldbgColor(StyleSet::foldbgColor);//默认0xff,0xff,0xff ////通过fold发现,尽量使用qscint的功能,因为他做了大量封装和简化 //setFolding(BoxedTreeFoldStyle, 2); //setFoldMarginColors(foldfgColor, foldbgColor); //setMarginsBackgroundColor(StyleSet::marginsBackgroundColor); //0xea, 0xf7, 0xff //默认0xf0f0f0 //双击后同样的字段进行高亮 execute(SCI_INDICSETSTYLE, SCE_UNIVERSAL_FOUND_STYLE_SMART, INDIC_ROUNDBOX); execute(SCI_INDICSETALPHA, SCE_UNIVERSAL_FOUND_STYLE_SMART, 100); execute(SCI_INDICSETUNDER, SCE_UNIVERSAL_FOUND_STYLE_SMART, false); execute(SCI_INDICSETFORE, SCE_UNIVERSAL_FOUND_STYLE_SMART, 0x00ff00); setStyleOptions(); //开启后可以保证长行在滚动条下完整显示 execute(SCI_SETSCROLLWIDTHTRACKING, true); connect(this, &QsciScintilla::selectionChanged, this, &QsciDisplayWindow::slot_clearHightWord, Qt::QueuedConnection); connect(this, &QsciDisplayWindow::delayWork, this, &QsciDisplayWindow::slot_delayWork, Qt::QueuedConnection); } QsciDisplayWindow::~QsciDisplayWindow() { if (m_textFindWin != nullptr) { delete m_textFindWin; m_textFindWin = nullptr; } } void QsciDisplayWindow::setFoldColor(int margin, QColor fgClack, QColor bkColor) { SendScintilla(SCI_MARKERSETFORE, margin, fgClack); SendScintilla(SCI_MARKERSETBACK, margin, bkColor); } void QsciDisplayWindow::setStyleOptions() { //if (StyleSet::m_curStyleId != BLACK_SE) //{ setMarginsForegroundColor(QColor(0x80, 0x80, 0x80)); //默认0x80, 0x80, 0x80 //} //else //{ // setMarginsForegroundColor(QColor(0xde, 0xde, 0xde)); //默认0x80, 0x80, 0x80 //} //setMarginsBackgroundColor(StyleSet::marginsBackgroundColor); //setFoldMarginColors(StyleSet::marginsBackgroundColor, StyleSet::marginsBackgroundColor); setMarginsBackgroundColor(0xf0f0f0); setFoldMarginColors(0xf0f0f0, 0xf0f0f0); { //setCaretLineBackgroundColor(QColor(0xe8e8ff)); setCaretLineBackgroundColor(QColor(0xFAF9DE)); setMatchedBraceForegroundColor(QColor(191, 141, 255)); setMatchedBraceBackgroundColor(QColor(222, 222, 222)); setCaretForegroundColor(QColor(0, 0, 0)); setFoldColor(SC_MARKNUM_FOLDEROPEN, QColor(Qt::white), QColor(128, 128, 128)); setFoldColor(SC_MARKNUM_FOLDER, QColor(Qt::white), QColor(128, 128, 128)); setFoldColor(SC_MARKNUM_FOLDERSUB, QColor(Qt::white), QColor(128, 128, 128)); setFoldColor(SC_MARKNUM_FOLDERTAIL, QColor(Qt::white), QColor(128, 128, 128)); setFoldColor(SC_MARKNUM_FOLDEREND, QColor(Qt::white), QColor(128, 128, 128)); setFoldColor(SC_MARKNUM_FOLDEROPENMID, QColor(Qt::white), QColor(128, 128, 128)); setFoldColor(SC_MARKNUM_FOLDERMIDTAIL, QColor(Qt::white), QColor(128, 128, 128)); } } void QsciDisplayWindow::setIsShowFindItem(bool v) { m_isShowFindItem = v; } sptr_t QsciDisplayWindow::execute(quint32 Msg, uptr_t wParam, sptr_t lParam) const { try { return (m_pScintillaFunc) ? m_pScintillaFunc(m_pScintillaPtr, Msg, wParam, lParam) : -1; } catch (...) { return -1; } }; void QsciDisplayWindow::mouseDoubleClickEvent(QMouseEvent * e) { QsciScintilla::mouseDoubleClickEvent(e); if (hasSelectedText()) { emit delayWork(); } } void QsciDisplayWindow::clearIndicator(int indicatorNumber) { size_t docStart = 0; size_t docEnd = length(); execute(SCI_SETINDICATORCURRENT, indicatorNumber); execute(SCI_INDICATORCLEARRANGE, docStart, docEnd - docStart); }; const int MAXLINEHIGHLIGHT = 400; void QsciDisplayWindow::slot_clearHightWord() { if (m_hasHighlight) { m_hasHighlight = false; clearIndicator(SCE_UNIVERSAL_FOUND_STYLE_SMART); } } void QsciDisplayWindow::highlightViewWithWord(QString & word2Hilite) { int originalStartPos = execute(SCI_GETTARGETSTART); int originalEndPos = execute(SCI_GETTARGETEND); int firstLine = static_cast<int>(this->execute(SCI_GETFIRSTVISIBLELINE)); int nbLineOnScreen = this->execute(SCI_LINESONSCREEN); int nbLines = std::min(nbLineOnScreen, MAXLINEHIGHLIGHT) + 1; int lastLine = firstLine + nbLines; int startPos = 0; int endPos = 0; auto currentLine = firstLine; int prevDocLineChecked = -1; //invalid start auto searchMark = [this](int &startPos, int &endPos, QByteArray &word2Mark) { int targetStart = 0; int targetEnd = 0; long lens = word2Mark.length(); while (targetStart >= 0) { execute(SCI_SETTARGETRANGE, startPos, endPos); targetStart = SendScintilla(SCI_SEARCHINTARGET, lens, word2Mark.data()); if (targetStart == -1 || targetStart == -2) break; targetEnd = int(this->execute(SCI_GETTARGETEND)); if (targetEnd > endPos) { //we found a result but outside our range, therefore do not process it break; } int foundTextLen = targetEnd - targetStart; if (foundTextLen > 0) { this->execute(SCI_SETINDICATORCURRENT, SCE_UNIVERSAL_FOUND_STYLE_SMART); this->execute(SCI_INDICATORFILLRANGE, targetStart, foundTextLen); } if (targetStart + foundTextLen == endPos) break; startPos = targetStart + foundTextLen; } }; QByteArray whatMark = word2Hilite.toUtf8(); SendScintilla(SCI_SETSEARCHFLAGS, SCFIND_REGEXP | SCFIND_MATCHCASE | SCFIND_WHOLEWORD | SCFIND_REGEXP_SKIPCRLFASONE); for (; currentLine < lastLine; ++currentLine) { int docLine = static_cast<int>(this->execute(SCI_DOCLINEFROMVISIBLE, currentLine)); if (docLine == prevDocLineChecked) continue; //still on same line (wordwrap) prevDocLineChecked = docLine; startPos = static_cast<int>(this->execute(SCI_POSITIONFROMLINE, docLine)); endPos = static_cast<int>(this->execute(SCI_POSITIONFROMLINE, docLine + 1)); if (endPos == -1) { //past EOF endPos = this->length() - 1; searchMark(startPos, endPos, whatMark); break; } else { searchMark(startPos, endPos, whatMark); } } m_hasHighlight = true; // restore the original targets to avoid conflicts with the search/replace functions this->execute(SCI_SETTARGETRANGE, originalStartPos, originalEndPos); } void QsciDisplayWindow::slot_delayWork() { if (!hasSelectedText()) { return; } QString word = selectedText(); if (!word.isEmpty()) { highlightViewWithWord(word); } #if 0 if (!hasSelectedText()) { return; } QString word = selectedText(); if (!word.isEmpty()) { QVector<int>resultPos; resultPos.reserve(50); int firstLine = execute(SCI_GETFIRSTVISIBLELINE); int nbLineOnScreen = execute(SCI_LINESONSCREEN); int nbLines = std::min(nbLineOnScreen, MAXLINEHIGHLIGHT) + 1; int lastLine = firstLine + nbLines; long startPos = execute(SCI_POSITIONFROMLINE, firstLine); long endPos = execute(SCI_POSITIONFROMLINE, lastLine); if (endPos == -1) { endPos = execute(SCI_GETLENGTH); } int curpos = execute(SCI_GETCURRENTPOS); int mainSelect = 1; struct Sci_TextToFind findOptions; findOptions.chrg.cpMin = startPos; findOptions.chrg.cpMax = endPos; std::string wordStr = word.toStdString(); findOptions.lpstrText = wordStr.c_str(); int pos = execute(SCI_FINDTEXT, SCFIND_MATCHCASE | SCFIND_WHOLEWORD, reinterpret_cast<sptr_t>(&findOptions)); while (pos != -1) { resultPos.append(pos); if (pos <= curpos) { mainSelect = resultPos.size(); } findOptions.chrg.cpMin = findOptions.chrgText.cpMax; pos = execute(SCI_FINDTEXT, SCFIND_MATCHCASE | SCFIND_WHOLEWORD, reinterpret_cast<sptr_t>(&findOptions)); } for (int i = 0, size = resultPos.size(); i < size; ++i) { execute(SCI_ADDSELECTION, resultPos.at(i), resultPos.at(i) + word.size()); } if (!resultPos.isEmpty()) { execute(SCI_SETMAINSELECTION, mainSelect - 1); } } #endif } void QsciDisplayWindow::setMediator(MediatorDisplay* mediator) { m_mediator = mediator; } //滚动条值变化后的槽函数。一旦滚动则会出发这里,发送消息给中介,让中介去同步另外一方 void QsciDisplayWindow::slot_scrollYValueChange(int value) { if (m_direction == RC_LEFT) { if (m_mediator->getLeftScrollValue() != value) { m_mediator->setLeftScrollValue(value); } } else { if (m_mediator->getRightScrollValue() != value) { m_mediator->setRightScrollValue(value); } } autoAdjustLineWidth(value); slot_delayWork(); //qDebug("-- dir s n %d %d", m_direction, contentY()); } //根据现有滚动条来决定是否更新屏幕线宽长度。每滚动2000个单位必须调整line宽 void QsciDisplayWindow::autoAdjustLineWidth(int xScrollValue) { if (std::abs(xScrollValue - m_preFirstLineNum) > 400) { m_preFirstLineNum = xScrollValue; updateLineNumberWidth(); } } void QsciDisplayWindow::updateLineNumberWidth() { auto linesVisible = execute(SCI_LINESONSCREEN); if (linesVisible) { int nbDigits = 0; auto firstVisibleLineVis = execute(SCI_GETFIRSTVISIBLELINE); auto lastVisibleLineVis = linesVisible + firstVisibleLineVis + 1; auto lastVisibleLineDoc = execute(SCI_DOCLINEFROMVISIBLE, lastVisibleLineVis); nbDigits = nbDigitsFromNbLines(lastVisibleLineDoc); nbDigits = nbDigits < 4 ? 4 : nbDigits; auto pixelWidth = 8 + nbDigits * execute(SCI_TEXTWIDTH, STYLE_LINENUMBER, reinterpret_cast<sptr_t>("8")); execute(SCI_SETMARGINWIDTHN, MARGIN_LINE_NUM, pixelWidth); } } //X方向滚动条值变化后的槽函数。一旦滚动则会出发这里,发送消息给中介,让中介去同步另外一方 void QsciDisplayWindow::slot_scrollXValueChange(int value) { if (m_direction == RC_LEFT) { if (m_mediator->getLeftScrollXValue() != value) { m_mediator->setLeftScrollXValue(value); } } else { if (m_mediator->getRightScrollXValue() != value) { m_mediator->setRightScrollXValue(value); } } //qDebug("-- dir s n %d %d", m_direction, contentY()); } void QsciDisplayWindow::setDirection(RC_DIRECTION direction) { m_direction = direction; } int QsciDisplayWindow::getCurVerticalScrollValue() { return this->verticalScrollBar()->value(); } void QsciDisplayWindow::contextUserDefineMenuEvent(QMenu* menu) { //QAction* action; if (menu != nullptr) { menu->addAction(tr("Find Text"), this, SLOT(slot_findText())); menu->addAction(tr("Show File in Explorer"), this, SLOT(slot_showFileInExplorer())); menu->addAction(tr("Save As ..."), this, &QsciDisplayWindow::sign_saveAsFile); } menu->show(); } void QsciDisplayWindow::inputMethodEvent(QInputMethodEvent* event) { if (!event->preeditString().isEmpty()) { return; } QsciScintilla::inputMethodEvent(event); } void QsciDisplayWindow::slot_findText() { if (m_isShowFindItem) { if (m_textFindWin == nullptr) { m_textFindWin = new TextFind(m_direction); connect(m_textFindWin, &TextFind::signFindFile, this, &QsciDisplayWindow::slot_FindTextWithPara); m_textFindWin->activateWindow(); m_textFindWin->show(); } else { m_textFindWin->activateWindow(); m_textFindWin->showNormal(); } m_findCurPos = 0; } else { //不使用这里的查找,直接发信号到外面 emit sign_find(); } } void QsciDisplayWindow::slot_FindTextWithPara(int prevOrNext, QString text) { std::string str = text.toStdString(); int length = SendScintilla(SCI_GETLENGTH); if (length > 0) { if (prevOrNext == 1) { SendScintilla(SCI_SETTARGETSTART, m_findCurPos); SendScintilla(SCI_SETTARGETEND, length); int ret = SendScintilla(SCI_SEARCHINTARGET, str.length(), str.c_str()); if (ret >= 0) { m_findCurPos = ret + str.length(); SendScintilla(SCI_GOTOPOS, ret); SendScintilla(SCI_SETSELECTION, ret, ret + str.length()); } else { QMessageBox::information(this, tr("Not Find"), tr("Not Find Next!")); m_textFindWin->activateWindow(); } } else if (prevOrNext == 0) { SendScintilla(SCI_SETTARGETSTART, m_findCurPos); SendScintilla(SCI_SETTARGETEND, 0); int ret = SendScintilla(SCI_SEARCHINTARGET, str.length(), str.c_str()); if (ret >= 0) { m_findCurPos = ret - 1; SendScintilla(SCI_GOTOPOS, ret); SendScintilla(SCI_SETSELECTION, ret, ret + str.length()); } else { QMessageBox::information(this, tr("Not Find"), tr("Not Find Prev!")); m_textFindWin->activateWindow(); } } } } //定位到文件夹 void QsciDisplayWindow::slot_showFileInExplorer() { showFileInExplorer(m_filePath); }
14,302
C++
.cpp
422
28.793839
169
0.727197
cxasm/notepad--
5,942
234
284
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
25,167
common.cpp
cxasm_notepad--/src/common.cpp
#include "common.h" int nbDigitsFromNbLines(size_t nbLines) { int nbDigits = 0; // minimum number of digit should be 4 if (nbLines < 10) nbDigits = 1; else if (nbLines < 100) nbDigits = 2; else if (nbLines < 1000) nbDigits = 3; else if (nbLines < 10000) nbDigits = 4; else if (nbLines < 100000) nbDigits = 5; else if (nbLines < 1000000) nbDigits = 6; else // rare case { nbDigits = 7; nbLines /= 1000000; while (nbLines) { nbLines /= 10; ++nbDigits; } } return nbDigits; }
526
C++
.cpp
22
20.5
58
0.645291
cxasm/notepad--
5,942
234
284
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
25,168
styleset.cpp
cxasm_notepad--/src/styleset.cpp
#include "styleset.h" #include "ccnotepad.h" #include <QFile> #include <QPalette> #include <QApplication> #include <QDebug> #include <Qsci/qscilexerglobal.h> QColor StyleSet::foldfgColor(0xe9, 0xe9, 0xe9, 100); QColor StyleSet::foldbgColor(0xff, 0xff, 0xff); QColor StyleSet::marginsBackgroundColor(0xf0f0f0); QColor StyleSet::bookmarkBkColor(0xececec); int StyleSet::m_curStyleId = 0; GLOBAL_STYLE_OPS* StyleSet::s_global_style = nullptr; StyleSet::StyleSet() { init(); } StyleSet::~StyleSet() {} void StyleSet::init() { if (s_global_style == nullptr) { s_global_style = new GLOBAL_STYLE_OPS(); s_global_style->default_style.styleId = 32; s_global_style->indent_guideline.styleId = 37; s_global_style->brace_highight.styleId = 34; s_global_style->bad_brace_color.styleId = 35; s_global_style->current_line_background_color.styleId = -1; s_global_style->select_text_color.styleId = -1; s_global_style->caret_colour.styleId = 2069; s_global_style->edge_colour.styleId = -1; s_global_style->line_number_margin.styleId = 33; s_global_style->bookmark_margin.styleId = -1; s_global_style->fold.styleId = -1; s_global_style->fold_active.styleId = -1; s_global_style->fold_margin.styleId = -1; s_global_style->white_space_stybol.styleId = -1; s_global_style->smart_highlighting.styleId = 29; s_global_style->find_mark_style.styleId = 31; s_global_style->mark_style_1.styleId = 25; s_global_style->mark_style_2.styleId = 24; s_global_style->mark_style_3.styleId = 23; s_global_style->mark_style_4.styleId = 22; s_global_style->mark_style_5.styleId = 21; s_global_style->incremental_highlight.styleId = 28; s_global_style->tags_match_highlight.styleId = 27; s_global_style->tags_attribute.styleId = 26; //s_global_style->active_tab_focused.styleId = -1; //s_global_style->active_tab_unfocused.styleId = -1; //s_global_style->active_tab_text.styleId = -1; //s_global_style->inactive_tabs.styleId = -1; s_global_style->url_hoverred.styleId = -1; } } void StyleSet::setCommonStyle(QColor foldfgColor_, QColor foldbgColor_, QColor marginsBackgroundColor_, QString colorName) { foldfgColor = foldfgColor_; foldbgColor = foldbgColor_; marginsBackgroundColor = marginsBackgroundColor_; QFile file(":/qss/lightbluestyle.qss"); //qss文件路径:/lightblue.qss QString styleSheet; if (file.open(QIODevice::Text | QIODevice::ReadOnly)) { styleSheet = file.readAll(); QPalette palette; palette.setColor(QPalette::Window, foldbgColor_); palette.setColor(QPalette::Base, foldbgColor_); palette.setColor(QPalette::Button, foldbgColor_); qApp->setPalette(palette); if (colorName != "#EAF7FF") { styleSheet.replace("#EAF7FF", colorName); } qApp->setStyleSheet(styleSheet); } file.close(); } void StyleSet::setSkin(int id) { m_curStyleId = id; QsciLexer::setCurThemes(m_curStyleId); StyleSet::init(); loadGolbalStyle(); switch (id) { case DEFAULT_SE: setDefaultStyle(); break; case BESPIN: case BLACK_BOARD: case BLUE_LIGHT: case CHOCO: case DANSLE_RUSH_DARK: case DEEP_BLACK: case LAVENDER: case HOT_FUDGE_SUNDAE: case MISTY_ROSE: case MONO_INDUSTRIAL: case MONOKAI: case OBSIDIAN: case PLASTIC_CODE: case RUBY_BLUE: case TWILIGHT: case VIBRANT_INK: case YELLOW_RICE: setCommonStyle(); break; case MAX_SE: break; default: break; } } //重新加载Global全局风格 void StyleSet::reloadGolbalStyleFromSetFile() { loadGolbalStyle(); } void StyleSet::loadGolbalStyle() { QsciLexer* pLexer = ScintillaEditView::createLexer(L_GLOBAL); QsciLexerGlobal* pGlobalLexer = dynamic_cast<QsciLexerGlobal*>(pLexer); if (pGlobalLexer != nullptr) { //获取其属性颜色,然后填入。后续在ScintillaEditView中直接设置这些One_Stype_Info的属性值 One_Stype_Info* pAddr = &s_global_style->global_style; for (int i = 0; i <= URL_HOVERRED; ++i) { pAddr[i].fgColor = pGlobalLexer->color(i); pAddr[i].bgColor = pGlobalLexer->paper(i); pAddr[i].font = pGlobalLexer->font(i); } } delete pLexer; } QString StyleSet::getCurrentStyle() { return getStyleName(m_curStyleId); } //是否深色风格系列 bool StyleSet::isCurrentDeepStyle() { switch (m_curStyleId) { case DEFAULT_SE: case BLUE_LIGHT: case YELLOW_RICE: case MISTY_ROSE: case LAVENDER: return false; case BESPIN: case BLACK_BOARD: case CHOCO: case DANSLE_RUSH_DARK: case DEEP_BLACK: case HOT_FUDGE_SUNDAE: case MONO_INDUSTRIAL: case MONOKAI: case OBSIDIAN: case PLASTIC_CODE: case RUBY_BLUE: case TWILIGHT: case VIBRANT_INK: return true; default: break; } return false; } QString StyleSet::getStyleName(int styleId) { static const QString style[MAX_SE] = { "Default","Bespin","Black board","Blue light",\ "Choco","DansLeRuSH-Dark",\ "Deep Black","lavender","HotFudgeSundae","misty rose",\ "Mono Industrial","Monokai","Obsidian","Plastic Code Wrap",\ "Ruby Blue","Twilight","Vibrant Ink",\ "yellow rice" }; return style[styleId]; } void StyleSet::setCurrentStyle(int themes) { setSkin(themes); } void StyleSet::setDefaultStyle() { m_curStyleId = DEFAULT_SE; foldfgColor = QColor(0xe9, 0xe9, 0xe9, 100); foldbgColor = QColor(0xff, 0xff, 0xff); marginsBackgroundColor = QColor(0xf0f0f0); bookmarkBkColor = QColor(0xececec); QFile file(":/qss/mystyle.qss"); //qss文件路径:/lightblue.qss QString styleSheet; if (file.open(QIODevice::Text | QIODevice::ReadOnly)) { styleSheet = file.readAll(); QPalette palette; palette.setColor(QPalette::Window, QColor(0xf0, 0xf0, 0xf0)); palette.setColor(QPalette::Base, QColor(0xff, 0xff, 0xff)); palette.setColor(QPalette::Button, QColor(0xf0, 0xf0, 0xf0)); qApp->setPalette(palette); qApp->setStyleSheet(styleSheet); } file.close(); } void StyleSet::setLightStyle() { //m_curStyleId = LIGHT_SE; bookmarkBkColor = QColor(0xE0F3Fc); setCommonStyle(QColor(0xea, 0xf7, 0xff, 100), QColor(0xeaf7ff), QColor(0xe8f5fd), "#EAF7FF"); } void StyleSet::setThinBlueStyle() { //m_curStyleId = THIN_BLUE_SE; bookmarkBkColor = QColor(0xE3e0F0); setCommonStyle(QColor(0xd7, 0xe3, 0xf4, 100), QColor(0xd7e3f4), QColor(0xd5e1f1), "#D7E3F4"); } //纸黄 void StyleSet::setThinYellowStyle() { //m_curStyleId = THIN_YELLOW_SE; bookmarkBkColor = QColor(0xF4F0E0); setCommonStyle(QColor(0xf9, 0xf0, 0xe1, 100), QColor(0xf9f0e1), QColor(0xf7f0e0), "#F9F0E1"); } //宣纸黄 void StyleSet::setRiceYellowStyle() { //m_curStyleId = RICE_YELLOW_SE; bookmarkBkColor = QColor(0xF0F0E8); setCommonStyle(QColor(0xf6, 0xf3, 0xea, 100), QColor(0xf6f3ea), QColor(0xf4f1e9), "#F6F3EA"); } //银色 void StyleSet::setSilverStyle() { //m_curStyleId = SILVER_SE; bookmarkBkColor = QColor(0xE4E4E4); setCommonStyle(QColor(0xe9, 0xe8, 0xe4, 100), QColor(0xe9e8e4), QColor(0xe7e6e2), "#E9E8E4"); } //谈紫色#FFF0F5 void StyleSet::setLavenderBlushStyle() { //m_curStyleId = LAVENDER_SE; bookmarkBkColor = QColor(0xFCF0F0); setCommonStyle(QColor(0xff, 0xf0, 0xf5, 100), QColor(0xFFF0F5), QColor(0xFdF0F3), "#FFF0F5"); } //MistyRose void StyleSet::setMistyRoseStyle() { //m_curStyleId = MISTYROSE_SE; bookmarkBkColor = QColor(0xFCE0E0); setCommonStyle(QColor(0xff, 0xe4, 0xe1, 100), QColor(0xFFE4E1), QColor(0xFdE2E0), "#FFE4E1"); } void StyleSet::setBlackStyle() { #if 0 m_curStyleId = BLACK_SE; foldfgColor = QColor(0,0, 0); foldbgColor = QColor(32, 32, 40); //注意暗黑模式是单独的窗口背景颜色。上面的foldbgColor决定了编辑器的背景颜色。 //暗黑模式窗体背景不完全是黑色,而是686868 QColor blackPaletteColor(68,68,68); marginsBackgroundColor = QColor(57, 58, 60); bookmarkBkColor = QColor(53,54,56); QFile file(":/qss/black.qss"); //qss文件路径:/lightblue.qss QString styleSheet; if (file.open(QIODevice::Text | QIODevice::ReadOnly)) { QPalette palette; palette.setColor(QPalette::Window, blackPaletteColor); palette.setColor(QPalette::Base, blackPaletteColor); palette.setColor(QPalette::Button, blackPaletteColor); qApp->setPalette(palette); styleSheet = file.readAll(); qApp->setStyleSheet(styleSheet); } file.close(); #endif m_curStyleId = BLACK_SE; foldfgColor = QColor(0xe9, 0xe9, 0xe9, 100); foldbgColor = QColor(0xff, 0xff, 0xff); marginsBackgroundColor = QColor(57, 58, 60); bookmarkBkColor = QColor(53, 54, 56); QFile file(":/qss/myblack.qss"); //qss文件路径:/lightblue.qss QString styleSheet; if (file.open(QIODevice::Text | QIODevice::ReadOnly)) { styleSheet = file.readAll(); QPalette palette; palette.setColor(QPalette::Window, QColor(0xf0, 0xf0, 0xf0)); palette.setColor(QPalette::Base, QColor(0xff, 0xff, 0xff)); palette.setColor(QPalette::Button, QColor(0xf0, 0xf0, 0xf0)); qApp->setPalette(palette); qApp->setStyleSheet(styleSheet); } file.close(); } void StyleSet::setCommonStyle() { QFile file(":/qss/common.qss"); QString styleSheet; if (file.open(QIODevice::Text | QIODevice::ReadOnly)) { styleSheet = file.readAll(); styleSheet.replace("#ffffff", s_global_style->default_style.fgColor.name()); styleSheet.replace("#444444", s_global_style->default_style.bgColor.name()); if (isCurrentDeepStyle()) { styleSheet.replace("#00CCFF", "#0000ff"); } QPalette palette; palette.setColor(QPalette::Window, QColor(0xf0, 0xf0, 0xf0)); palette.setColor(QPalette::Base, QColor(0xff, 0xff, 0xff)); palette.setColor(QPalette::Button, QColor(0xf0, 0xf0, 0xf0)); qApp->setPalette(palette); qApp->setStyleSheet(styleSheet); } file.close(); } void StyleSet::setGlobalFgColor(int style, QColor color) { One_Stype_Info* pStyle = &StyleSet::s_global_style->global_style; if (pStyle[style].fgColor != color) { pStyle[style].fgColor = color; } } void StyleSet::setGlobalBgColor(int style, QColor color) { One_Stype_Info* pStyle = &StyleSet::s_global_style->global_style; if (pStyle[style].bgColor != color) { pStyle[style].bgColor = color; } } void StyleSet::setGlobalFont(int style, QFont font) { One_Stype_Info* pStyle = &StyleSet::s_global_style->global_style; if (pStyle[style].font != font) { pStyle[style].font = font; } }
10,391
C++
.cpp
342
26.692982
123
0.718852
cxasm/notepad--
5,942
234
284
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
25,169
findwin.cpp
cxasm_notepad--/src/findwin.cpp
#include "findwin.h" #include "scintillaeditview.h" #include "ccnotepad.h" #include "progresswin.h" #include "doctypelistview.h" #include "filemanager.h" #include "ccnotepad.h" #include "nddsetting.h" #include <QMimeDatabase> #include <QRadioButton> #include <QMessageBox> #include <QFileDialog> #include <functional> #include <BoostRegexSearch.h> #include <QClipboard> #include <QDebug> enum TAB_TYPES { FIND_TYPE=0, RELPACE_TYPE, DIR_FIND_TYPE, MARK_TYPE, }; const int MAX_RECORD_KEY_LENGTH = 20; FindWin::FindWin(QWidget *parent):QMainWindow(parent), m_editTabWidget(nullptr), m_isFindFirst(true), m_findHistory(nullptr), \ pEditTemp(nullptr), m_curEditWin(nullptr), m_isStatic(false), m_isReverseFind(false), m_pMainPad(parent) { ui.setupUi(this); //默认值要与界面初始值一样。 m_BackwardDir = false; m_matchWhole = false; m_matchCase = false; m_matchWrap = true; m_extend = false; m_searchMode = 1; m_re = false; m_cs = false; m_wo = false; m_wrap = true; m_forward = true;;//是否向前查找。注意如果向后,要为false m_extend = false; m_isFound = false; connect(ui.findModeRegularBt, &QRadioButton::toggled, this, &FindWin::slot_findModeRegularBtChange); connect(ui.replaceModeRegularBt, &QRadioButton::toggled, this, &FindWin::slot_replaceModeRegularBtChange); connect(ui.dealFileType, &QCheckBox::stateChanged, this,&FindWin::slot_dealFileTypeChange); connect(ui.skipDir, &QCheckBox::stateChanged, this, &FindWin::slot_skipDirChange); connect(ui.clearBt, &QAbstractButton::clicked, this, &FindWin::sign_clearResult); connect(ui.findClearBt, &QAbstractButton::clicked, this, &FindWin::sign_clearResult); connect(ui.findinfilesTab, &QTabWidget::currentChanged, this, &FindWin::slot_tabIndexChange); #if 0 //这样是无效的,记住一下,不删除,避免后面再做无用功 Qt::WindowFlags m_flags = windowFlags(); //这样使得窗口在上面,不至于总是到后面被挡住。 #if defined (Q_MAC_OS) setWindowFlags(m_flags | Qt::WindowStaysOnTopHint); #endif #endif raise(); setFocusPolicy(Qt::StrongFocus); setFocus(); ui.findinfilesTab->setAttribute(Qt::WA_StyledBackground); ui.findComboBox->installEventFilter(this); } FindWin::~FindWin() { m_findHistory = nullptr; if (pEditTemp != nullptr) { delete pEditTemp; pEditTemp = nullptr; } } void FindWin::slot_tabIndexChange(int index) { TAB_TYPES type = (TAB_TYPES)index; if (RELPACE_TYPE == type) { ui.replaceTextBox->setFocus(); ui.replaceTextBox->lineEdit()->selectAll(); if (ui.replaceTextBox->currentText().isEmpty() && !ui.findComboBox->currentText().isEmpty()) { if (ui.findComboBox->currentText().size() < MAX_RECORD_KEY_LENGTH) { ui.replaceTextBox->setCurrentText(ui.findComboBox->currentText()); } } } else if(FIND_TYPE == type) { ui.findComboBox->setFocus(); ui.findComboBox->lineEdit()->selectAll(); if (ui.findComboBox->currentText().isEmpty() && !ui.replaceTextBox->currentText().isEmpty()) { if (ui.replaceTextBox->currentText().size() < MAX_RECORD_KEY_LENGTH) { ui.findComboBox->setCurrentText(ui.replaceTextBox->currentText()); } } } else if (DIR_FIND_TYPE == type) { ui.dirFindWhat->setFocus(); ui.dirFindWhat->lineEdit()->selectAll(); } else if (MARK_TYPE == type) { ui.markTextBox->setFocus(); ui.markTextBox->lineEdit()->selectAll(); } m_isFindFirst = true; if (m_findHistory->isEmpty()) { return; } } void FindWin::slot_dealFileTypeChange(int state) { if (state == Qt::Checked) { ui.fileType->setEnabled(true); if (ui.fileType->text().isEmpty()) { ui.fileType->setText(ui.fileType->placeholderText()); } ui.fileType->setFocus(); ui.fileType->selectAll(); } else { ui.fileType->setEnabled(false); } } void FindWin::slot_skipDirChange(int state) { if (state == Qt::Checked) { ui.skipDirNames->setEnabled(true); if (ui.skipDirNames->text().isEmpty()) { ui.skipDirNames->setText(ui.skipDirNames->placeholderText()); } ui.skipDirNames->setFocus(); ui.skipDirNames->selectAll(); } else { ui.skipDirNames->setEnabled(false); } } //自动调整当前窗口的状态,如果发生了变化,则需要认定为是首次查找 QWidget* FindWin::autoAdjustCurrentEditWin() { QWidget* pw = m_editTabWidget->currentWidget(); if (m_curEditWin != pw) { m_curEditWin = pw; m_isFindFirst = true; } return pw; } void FindWin::setCurrentTab(FindTabIndex index) { ui.findinfilesTab->setCurrentIndex(index); if (FIND_TAB == index) { ui.findComboBox->setFocus(); ui.findComboBox->lineEdit()->selectAll(); } else if(REPLACE_TAB == index) { ui.replaceTextBox->setFocus(); ui.replaceTextBox->lineEdit()->selectAll(); } raise(); } void FindWin::setTabWidget(QTabWidget *editTabWidget) { m_editTabWidget = editTabWidget; } void FindWin::setFindText(QString &text) { ui.findComboBox->setEditText(text); addFindHistory(text); } void FindWin::keywordWinGetFouse(FindTabIndex tabIndex) { switch (tabIndex) { case FIND_TAB: this->setFocus(); ui.findComboBox->setFocus(); ui.findComboBox->lineEdit()->selectAll(); break; case REPLACE_TAB: ui.replaceTextBox->setFocus(); ui.replaceTextBox->lineEdit()->selectAll(); break; case DIR_FIND_TAB: ui.dirFindWhat->setFocus(); ui.dirFindWhat->lineEdit()->selectAll(); break; case MARK_TAB: ui.markTextBox->setFocus(); ui.markTextBox->lineEdit()->selectAll(); break; default: break; } } void FindWin::setReplaceFindText(QString& text) { ui.replaceTextBox->setEditText(text); addFindHistory(text); } void FindWin::setDirFindText(QString& text) { ui.dirFindWhat->setEditText(text); addFindHistory(text); } void FindWin::setMarkFindText(QString& text) { ui.markTextBox->setEditText(text); addFindHistory(text); } void FindWin::disableReplace() { ui.tab_replace->setEnabled(false); } void FindWin::setFindHistory(QList<QString>* findHistory) { m_findHistory = findHistory; if ((m_findHistory != nullptr) && !m_findHistory->isEmpty()) { ui.findComboBox->addItems(*m_findHistory); ui.replaceTextBox->addItems(*m_findHistory); ui.dirFindWhat->addItems(*m_findHistory); ui.markTextBox->addItems(*m_findHistory); ui.findComboBox->clearEditText(); ui.replaceTextBox->clearEditText(); ui.dirFindWhat->clearEditText(); ui.markTextBox->clearEditText(); } } void FindWin::setReplaceHistory(QList<QString>* replaceHistory) { m_replaceHistory = replaceHistory; if ((m_replaceHistory != nullptr) && !m_replaceHistory->isEmpty()) { ui.replaceWithBox->addItems(*m_replaceHistory); ui.replaceWithBox->clearEditText(); ui.dirReplaceWhat->addItems(*m_replaceHistory); ui.dirReplaceWhat->clearEditText(); } } //标记高亮所有word单词 int FindWin::markAllWord(QString & word) { ui.markTextBox->setCurrentText(word); ui.findinfilesTab->setCurrentIndex(3); //发现中文在全词匹配下面不能匹配到单词。最好是英文全词匹配,中文不需要 //但是好像没有一个现成的方法来判断word中的字符。暂时不做全词匹配 ui.markMatchWholeBox->setChecked(false); ui.markMatchCaseBox->setChecked(true); return markAll(); } //删除行首尾的空白字符 void FindWin::removeLineHeadEndBlank(int mode) { QWidget* pw = autoAdjustCurrentEditWin(); ScintillaEditView* pEdit = dynamic_cast<ScintillaEditView*>(pw); if (pEdit != nullptr) { if (pEdit->isReadOnly()) { ui.statusbar->showMessage(tr("The ReadOnly document does not allow this operation."), 8000); QApplication::beep(); return; } ui.findinfilesTab->setCurrentIndex(1); if (mode == 1) { ui.replaceTextBox->setCurrentText("^[ ]+"); } else if (mode == 2) { ui.replaceTextBox->setCurrentText("[ ]+$"); } ui.replaceWithBox->setEditText(""); ui.replaceModeRegularBt->setChecked(true); m_isStatic = true; slot_replaceAll(); m_isStatic = false; } } void FindWin::focusInEvent(QFocusEvent * ev) { QWidget::focusInEvent(ev); setWindowOpacity(1.0); } void FindWin::focusOutEvent(QFocusEvent * ev) { QWidget::focusOutEvent(ev); if (this->isActiveWindow()) { //当前还是活动窗口,不设置透明 return; } else { setWindowOpacity(0.6); //static int i = 0; //qDebug() << ++i; } } bool FindWin::eventFilter(QObject* watched, QEvent *event) { if (watched == ui.findComboBox) { if (event->type() == QEvent::KeyPress) { QKeyEvent *ke = static_cast<QKeyEvent*>(event); if (ke->key() == Qt::Key_Enter || ke->key() == Qt::Key_Return) { emit ui.findTextNext->click(); return true; //该事件已经被处理 } return false; } else { return false; } } return QWidget::eventFilter(watched, event); // 最后将事件交给上层对话框 } //从ui读取参数配置到成员变量 void FindWin::updateParameterFromUI() { bool extend = false; if (ui.findinfilesTab->currentIndex() == 0) { int searchMode = 0; if (ui.findModeNormalBt->isChecked()) { searchMode = 1; extend = false; } else if (ui.findModeRegularBt->isChecked()) { searchMode = 2; extend = false; } else if (ui.findModeExtendBt->isChecked()) { searchMode = 1; extend = true; } if (m_searchMode != searchMode) { m_searchMode = searchMode; m_isFindFirst = true; } if (m_expr != ui.findComboBox->currentText()) { m_expr = ui.findComboBox->currentText(); m_isFindFirst = true; } if (m_BackwardDir != ui.findBackwardBox->isChecked()) { m_BackwardDir = ui.findBackwardBox->isChecked(); m_isFindFirst = true; } if (m_matchWhole != ui.findMatchWholeBox->isChecked()) { m_matchWhole = ui.findMatchWholeBox->isChecked(); m_isFindFirst = true; } if (m_matchCase != ui.findMatchCaseBox->isChecked()) { m_matchCase = ui.findMatchCaseBox->isChecked(); m_isFindFirst = true; } if (m_matchWrap != ui.findWrapBox->isChecked()) { m_matchWrap = ui.findWrapBox->isChecked(); m_isFindFirst = true; } } else if (ui.findinfilesTab->currentIndex() == 1) { int searchMode = 0; if (ui.replaceModeNormalBox->isChecked()) { searchMode = 1; extend = false; } else if (ui.replaceModeRegularBt->isChecked()) { searchMode = 2; extend = false; } else if (ui.replaceModeExtendBox->isChecked()) { searchMode = 1; extend = true; } if (m_searchMode != searchMode) { m_searchMode = searchMode; m_isFindFirst = true; } if (m_expr != ui.replaceTextBox->currentText()) { m_expr = ui.replaceTextBox->currentText(); m_isFindFirst = true; } if (m_replaceWithText != ui.replaceWithBox->currentText()) { m_replaceWithText = ui.replaceWithBox->currentText(); m_isFindFirst = true; } if (m_BackwardDir != ui.replaceBackwardBox->isChecked()) { m_BackwardDir = ui.replaceBackwardBox->isChecked(); m_isFindFirst = true; } if (m_matchWhole != ui.replaceMatchWholeBox->isChecked()) { m_matchWhole = ui.replaceMatchWholeBox->isChecked(); m_isFindFirst = true; } if (m_matchCase != ui.replaceMatchCaseBox->isChecked()) { m_matchCase = ui.replaceMatchCaseBox->isChecked(); m_isFindFirst = true; } if (m_matchWrap != ui.replaceWrapBox->isChecked()) { m_matchWrap = ui.replaceWrapBox->isChecked(); m_isFindFirst = true; } } else if (ui.findinfilesTab->currentIndex() == 2) { int searchMode = 0; if (ui.dirFindModeNormalBox->isChecked()) { searchMode = 1; extend = false; } else if (ui.dirFindModeRegularBt->isChecked()) { searchMode = 2; extend = false; } else if (ui.dirFindModeExtendBox->isChecked()) { searchMode = 1; extend = true; } if (m_searchMode != searchMode) { m_searchMode = searchMode; m_isFindFirst = true; } if (m_expr != ui.dirFindWhat->currentText()) { m_expr = ui.dirFindWhat->currentText(); m_isFindFirst = true; } if (m_replaceWithText != ui.dirReplaceWhat->currentText()) { m_replaceWithText = ui.dirReplaceWhat->currentText(); m_isFindFirst = true; } m_BackwardDir = false; if (m_matchWhole != ui.dirFindMatchWholeBox->isChecked()) { m_matchWhole = ui.dirFindMatchWholeBox->isChecked(); m_isFindFirst = true; } if (m_matchCase != ui.dirFindMatchCaseBox->isChecked()) { m_matchCase = ui.dirFindMatchCaseBox->isChecked(); m_isFindFirst = true; } m_matchWrap = true; } else if (ui.findinfilesTab->currentIndex() == 3) { int searchMode = 0; if (ui.markModeNormalBox->isChecked()) { searchMode = 1; extend = false; } else if (ui.markModeRegularBt->isChecked()) { searchMode = 2; extend = false; } else if (ui.markModeExtendBox->isChecked()) { searchMode = 1; extend = true; } if (m_searchMode != searchMode) { m_searchMode = searchMode; m_isFindFirst = true; } if (m_expr != ui.markTextBox->currentText()) { m_expr = ui.markTextBox->currentText(); m_isFindFirst = true; } m_BackwardDir = false; if (m_matchWhole != ui.markMatchWholeBox->isChecked()) { m_matchWhole = ui.markMatchWholeBox->isChecked(); m_isFindFirst = true; } if (m_matchCase != ui.markMatchCaseBox->isChecked()) { m_matchCase = ui.markMatchCaseBox->isChecked(); m_isFindFirst = true; } m_matchWrap = true; } m_re = ((m_searchMode == 2) ? true : false); if (m_cs != m_matchCase) { m_cs = m_matchCase; } if (m_wo != m_matchWhole) { m_wo = m_matchWhole; } if (m_wrap != m_matchWrap) { m_wrap = m_matchWrap; } if (m_extend != extend) { m_extend = extend; m_isFindFirst = true; } //本来的m_BackwardDir只控制是否勾选反向 m_forward = !m_BackwardDir; //m_isReverseFind 控制是否还需要反向一直,只在查找前一个生效,只影响查找界面 if (ui.findinfilesTab->currentIndex() == 0) { m_forward = (m_isReverseFind ? !m_forward : m_forward); } } #if 0 //开始做了历史记录重复删除的,后面发现时序有问题,暂时不做 void findItemAndRemove(QComboBox* pCombox, QString& text) { int index = pCombox->findText(text); if (index != -1) { pCombox->removeItem(index); } } #endif void FindWin::addFindHistory(QString &text) { //太长会导致看起来很杂乱,也不记录 if (text.isEmpty() || text.size() >= MAX_RECORD_KEY_LENGTH) { return; } if (m_findHistory != nullptr) { int index = m_findHistory->indexOf(text,0); //已经是最上面一个了,直接返回 if (0 == index) { return; } //没有直接添加到最前面。不做查找删除重复,一是慢,而是删除会引起信号逻辑时许有误 if (-1 == index) { m_findHistory->push_front(text); ui.findComboBox->insertItem(0, text); ui.replaceTextBox->insertItem(0, text); ui.dirFindWhat->insertItem(0, text); ui.markTextBox->insertItem(0, text); } else { //有了怎么办,删除旧的,加新的 m_findHistory->removeAt(index); m_findHistory->push_front(text); //发现不能只删除旧的,有bug,一旦删除后,查找框乱了,被切换到下一个。 ui.findComboBox->removeItem(index); ui.replaceTextBox->removeItem(index); ui.dirFindWhat->removeItem(index); ui.markTextBox->removeItem(index); ui.findComboBox->insertItem(0, text); ui.replaceTextBox->insertItem(0, text); ui.dirFindWhat->insertItem(0, text); ui.markTextBox->insertItem(0, text); //发现不能只删除旧的,有bug,一旦删除后,查找框乱了,被切换到下一个。 //必须重新设置一下,否则查找框里面字段乱跳到下一个去了 ui.findComboBox->setCurrentIndex(0); ui.replaceTextBox->setCurrentIndex(0); ui.dirFindWhat->setCurrentIndex(0); ui.markTextBox->setCurrentIndex(0); } if (m_findHistory->size() >= 15) { m_findHistory->takeLast(); } } } void FindWin::addReplaceHistory(QString& text) { //太长会导致看起来很杂乱,也不记录 if (text.isEmpty() || text.size() >= MAX_RECORD_KEY_LENGTH) { return; } if (m_replaceHistory != nullptr) { int index = m_replaceHistory->indexOf(text, 0); //已经是最上面一个了,直接返回 if (0 == index) { return; } //没有直接添加到最前面。不做查找删除重复,一是慢,而是删除会引起信号逻辑时序有误 if (-1 == index) { m_replaceHistory->push_front(text); ui.replaceWithBox->insertItem(0, text); ui.dirReplaceWhat->insertItem(0, text); } else { //有了怎么办,删除旧的,加新的 m_replaceHistory->removeAt(index); m_replaceHistory->push_front(text); //发现不能只删除旧的,有bug,一旦删除后,查找框乱了,被切换到下一个。 ui.replaceWithBox->removeItem(index); ui.dirReplaceWhat->removeItem(index); ui.replaceWithBox->insertItem(0, text); ui.dirReplaceWhat->insertItem(0, text); //发现不能只删除旧的,有bug,一旦删除后,查找框乱了,被切换到下一个。 //必须重新设置一下,否则查找框里面字段乱跳到下一个去了 ui.replaceWithBox->setCurrentIndex(0); ui.dirReplaceWhat->setCurrentIndex(0); } if (m_replaceHistory->size() >= 15) { m_replaceHistory->takeLast(); } } } //检查是否是第一次查找,凡是参数变化了,则认定为是第一次查找。 //因为查找分firstFirst和firstNext,则是qscint特性决定的。所以正确识别第一次查找是必要的 bool FindWin::isFirstFind() { return m_isFindFirst; } //const QChar *constData() const bool readBase(const QChar * str, int * value, int base, int size) { int i = 0, temp = 0; *value = 0; QChar max = QChar(QChar('0').digitValue() + base - 1); QChar current; while (i < size) { current = str[i]; if (current >= 'A') { current = current.digitValue() & 0xdf; current = current.digitValue() - ('A' - '0' - 10); } else if (current > '9') return false; if (current >= '0' && current <= max) { temp *= base; temp += (current.digitValue() - '0'); } else { return false; } ++i; } *value = temp; return true; } int convertExtendedToString(QString& query, QString &result) { //query may equal to result, since it always gets smaller int i = 0, j = 0; int length = query.length(); int charLeft = length; QChar current; while (i < length) { //because the backslash escape quences always reduce the size of the generic_string, no overflow checks have to be made for target, assuming parameters are correct current = query.at(i); --charLeft; if (current == '\\' && charLeft) { //possible escape sequence ++i; --charLeft; current = query.at(i); switch (current.toLatin1()) { case 'r': result[j] = '\r'; break; case 'n': result[j] = '\n'; break; case '0': result[j] = '\0'; break; case 't': result[j] = '\t'; break; case '\\': result[j] = '\\'; break; case 'b': case 'd': case 'o': case 'x': case 'u': { int size = 0, base = 0; if (current == 'b') { //11111111 size = 8, base = 2; } else if (current == 'o') { //377 size = 3, base = 8; } else if (current == 'd') { //255 size = 3, base = 10; } else if (current == 'x') { //0xFF size = 2, base = 16; } else if (current == 'u') { //0xCDCD size = 4, base = 16; } if (charLeft >= size) { int res = 0; if (readBase(query.constData() + (i + 1), &res, base, size)) { result[j] = QChar(res); i += size; break; } } //not enough chars to make parameter, use default method as fallback } default: { //unknown sequence, treat as regular text result[j] = '\\'; ++j; result[j] = current; break; } } } else { result[j] = query[i]; } ++i; ++j; } return j; } void FindWin::showCallTip(QsciScintilla* pEdit, int pos) { QString zeroString(tr("find-regex-zero-length-match")); QByteArray bytes = zeroString.toUtf8(); bytes.append('\0'); /*int size = bytes.size(); char* newStr = new char[size + 1]; memcpy(newStr, bytes.data(), size); newStr[bytes.size()] = '\0';*/ pEdit->SendScintilla(SCI_CALLTIPSHOW, pos, (void*)(bytes.data())); /*delete[]newStr;*/ } //删除空白行 void FindWin::removeEmptyLine(bool isBlankContained) { QWidget* pw = autoAdjustCurrentEditWin(); ScintillaEditView* pEdit = dynamic_cast<ScintillaEditView*>(pw); if (pEdit != nullptr) { if (pEdit->isReadOnly()) { ui.statusbar->showMessage(tr("The ReadOnly document does not allow this operation."), 8000); QApplication::beep(); return; } ui.findinfilesTab->setCurrentIndex(1); if (isBlankContained) { ui.replaceTextBox->setCurrentText("^[\\t ]*$(\\r\\n|\\r|\\n)"); } else { ui.replaceTextBox->setCurrentText("^$(\\r\\n|\\r|\\n)"); } ui.replaceWithBox->setEditText(""); ui.replaceModeRegularBt->setChecked(true); m_isStatic = true; slot_replaceAll(); m_isStatic = false; } } void FindWin::findNext() { slot_findNext(); } void FindWin::findPrev() { slot_findPrev(); } /*处理查找时零长的问题。一定要处理,否则会死循环,因为每次都在原地查找。 * 就是把下次查找的startpos往前一个,否则每次都从这个startpos找到自己 */ void FindWin::dealWithZeroFound(QsciScintilla* pEdit) { FindState& state = pEdit->getLastFindState(); if (state.targstart == state.targend) { //强行加1,否则每次查找总是在同一个地方。 state.startpos++; } } //调整光标变化后,查找位置需要调整的情况 void FindWin::adjustSearchStartPosChange(QsciScintilla* pEdit) { int caretPos = pEdit->SendScintilla(SCI_GETCURRENTPOS); FindState& state = pEdit->getLastFindState(); if (state.targend != caretPos) { state.startpos = caretPos; } } /*处理查找时零长的问题。一定要处理,否则会死循环,因为每次都在原地查找。 * 就是把下次查找的startpos往前一个,否则每次都从这个startpos找到自己 * 和dealWithZeroFound是一样的,就是要显示消息而已 */ void FindWin::dealWithZeroFoundShowTip(QsciScintilla* pEdit, bool isShowTip) { if (!isShowTip) { return dealWithZeroFound(pEdit); } FindState& state = pEdit->getLastFindState(); //int linpos = pEdit->SendScintilla(SCI_POSITIONFROMLINE, state.linenum); int line = 0; int indexStart = 0; int indexEnd = 0; pEdit->lineIndexFromPosition(state.targstart, &line, &indexStart); pEdit->lineIndexFromPosition(state.targend, &line, &indexEnd); ui.statusbar->showMessage(tr("target info linenum %1 pos is %2 - %3").arg(state.linenum + 1).arg(indexStart).arg(indexEnd), 8000); if (state.targstart == state.targend) { //强行加1,否则每次查找总是在同一个地方。 //这里有个问题,如果是反向查找,则应该是pos减去1才对。 //不过只有在正则查找才会出现零长,而正则查找时我们不允许反向查找。反向是回调的。 state.startpos++; showCallTip(pEdit, state.targstart); } } void FindWin::dofindNext() { if (ui.findComboBox->currentText().isEmpty()) { ui.statusbar->showMessage(tr("what find is null !"), 8000); QApplication::beep(); return; } updateParameterFromUI(); QWidget* pw = autoAdjustCurrentEditWin(); QsciScintilla* pEdit = dynamic_cast<QsciScintilla*>(pw); //第一次查找 if (isFirstFind()) { if (pEdit != nullptr) { QString whatFind = ui.findComboBox->currentText(); addFindHistory(whatFind); if (m_extend) { QString extendFind; convertExtendedToString(whatFind, extendFind); whatFind = extendFind; } if (!pEdit->findFirst(whatFind, m_re, m_cs, m_wo, m_wrap, m_forward, FINDNEXTTYPE_FINDNEXT, -1, -1, true, false, false)) { ui.statusbar->showMessage(tr("cant't find text \'%1\'").arg(m_expr), 8000); QApplication::beep(); m_isFindFirst = true; } else { m_isFindFirst = false; dealWithZeroFoundShowTip(pEdit); } } } else { //查找下一个 if (pEdit != nullptr) { adjustSearchStartPosChange(pEdit); if (!pEdit->findNext()) { ui.statusbar->showMessage(tr("no more find text \'%1\'").arg(m_expr), 8000); m_isFindFirst = true; QApplication::beep(); } else { dealWithZeroFoundShowTip(pEdit); } } } } //一旦修改条件发生变化,则认定为第一次查找 void FindWin::slot_findNext() { if (m_isReverseFind) { m_isReverseFind = false; m_isFindFirst = true; } dofindNext(); } void FindWin::setFindBackward(bool isBackward) { if (ui.findBackwardBox->isChecked() != isBackward) { ui.findBackwardBox->setChecked(isBackward); } } void FindWin::slot_findPrev() { if (!m_isReverseFind) { m_isReverseFind = true; m_isFindFirst = true; } dofindNext(); } //查找计数 void FindWin::slot_findCount() { if (ui.findComboBox->currentText().isEmpty()) { ui.statusbar->showMessage(tr("what find is null !"), 8000); QApplication::beep(); return; } QWidget* pw = autoAdjustCurrentEditWin(); ScintillaEditView* pEdit = dynamic_cast<ScintillaEditView*>(pw); if (pEdit != nullptr) { if (pEdit->isReadOnly()) { ui.statusbar->showMessage(tr("The ReadOnly document does not allow this operation."), 8000); QApplication::beep(); return; } updateParameterFromUI(); int srcPostion = pEdit->execute(SCI_GETCURRENTPOS); int firstDisLineNum = pEdit->execute(SCI_GETFIRSTVISIBLELINE); int countNums = 0; //无条件进行第一次查找,从0行0列开始查找,而且不回环。如果没有找到,则替换完毕 QString whatFind = ui.findComboBox->currentText(); //这里不能直接修改results.findText的值,该值在外部显示还需要。如果修改则会显示紊乱 if (m_extend) { QString extendFind; convertExtendedToString(whatFind, extendFind); whatFind = extendFind; } //这里的forward一定要是true。回环一定是false if (!pEdit->findFirst(whatFind, m_re, m_cs, m_wo, false, true, FINDNEXTTYPE_FINDNEXT, 0, 0,false)) { ui.statusbar->showMessage(tr("count %1 times with \'%2\'").arg(countNums).arg(m_expr)); QApplication::beep(); m_isFindFirst = true; return; } else { dealWithZeroFound(pEdit); } ++countNums; //找到了,增加计数 while (pEdit->findNext()) { ++countNums; dealWithZeroFound(pEdit); } pEdit->execute(SCI_GOTOPOS, srcPostion); pEdit->execute(SCI_SETFIRSTVISIBLELINE, firstDisLineNum); //pEdit->execute(SCI_SETXOFFSET, 0); //全部替换后,下次查找,必须算第一次查找 m_isFindFirst = true; ui.statusbar->showMessage(tr("count %1 times with \'%2\'").arg(countNums).arg(m_expr)); } else { ui.statusbar->showMessage(tr("The mode of the current document does not allow this operation."), 8000); QApplication::beep(); } } //去掉行尾的\n\r符号 static QString trimmedEnd(QString lineText) { if (lineText.endsWith("\r\n")) { return lineText.mid(0, lineText.length()-2); } if (lineText.endsWith("\r")) { return lineText.mid(0, lineText.length()-1); } if (lineText.endsWith("\n")) { return lineText.mid(0, lineText.length()-1); } return lineText; } //getResult:是否提取结果目标字符串。在正则查找时,还是有用的 QString FindWin::addCurFindRecord(ScintillaEditView* pEdit, FindRecords& recordRet,bool isMark, bool getResult) { FindRecord aRecord; QString ret; //看了源码,当前查找到的结果,是会被选中的。所以可通过选中范围,来记录当前被查找中的结果 //光标在选择词的尾部下一个位置 #if 0 aRecord.pos = pEdit->execute(SCI_GETSELECTIONSTART); aRecord.end = pEdit->execute(SCI_GETSELECTIONEND); #endif //加速 FindState& state = pEdit->getLastFindState(); aRecord.pos = state.targstart; aRecord.end = state.targend; aRecord.lineNum = state.linenum; //mark模式不需要这么多信息,可直接返回 if (!isMark) { //静默查找,在后台批量查找时,不会返回这个state.linenum。需要手动获取一下 if (aRecord.lineNum == -1) { aRecord.lineNum = pEdit->execute(SCI_LINEFROMPOSITION, aRecord.pos); } aRecord.lineStartPos = pEdit->execute(SCI_POSITIONFROMLINE, aRecord.lineNum); int lineLens = pEdit->execute(SCI_LINELENGTH, aRecord.lineNum); if (lineLens <= 0) { return ret; } char* lineText = new char[lineLens + 1]; memset(lineText, 0, lineLens + 1); //这里有个bug,是qscint的,查找最后一行,会漏掉最后一个字符 pEdit->execute(SCI_GETLINE, aRecord.lineNum, reinterpret_cast<sptr_t>(lineText)); //务必要去掉行位的换行,否则显示结果列表会显示换行 aRecord.lineContents = trimmedEnd(QString(lineText)); delete[]lineText; //如果需要结果,再把结果提取一下 if (getResult && (state.targend - state.targstart > 0)) { Sci_TextRange lineText; lineText.chrg.cpMin = static_cast<Sci_Position>(state.targstart); lineText.chrg.cpMax = static_cast<Sci_Position>(state.targend); QByteArray result; result.resize(state.targend - state.targstart); lineText.lpstrText = result.data(); //获取原始行的内容 pEdit->SendScintilla(SCI_GETTEXTRANGE, 0, &lineText); ret = QString(result); } } recordRet.records.append(aRecord); return ret; } //在后台批量查找 int FindWin::findAtBack(QStringList& keyword) { if (keyword.isEmpty()) { return 0; } QWidget* pw = autoAdjustCurrentEditWin(); ScintillaEditView* pEdit = dynamic_cast<ScintillaEditView*>(pw); if (pEdit != nullptr) { if (pEdit->isReadOnly()) { ui.statusbar->showMessage(tr("The ReadOnly document does not allow replacement."), 8000); QApplication::beep(); return 0; } } m_isStatic = true; int times = 0; ProgressWin* loadFileProcessWin = nullptr; if (keyword.size() > 1000) { loadFileProcessWin = new ProgressWin(this); loadFileProcessWin->setWindowModality(Qt::WindowModal); loadFileProcessWin->info(tr("total %1 keyword, please wait ...").arg(keyword.size())); loadFileProcessWin->setTotalSteps(keyword.size() / 100); loadFileProcessWin->show(); } QString text = pEdit->text(); QByteArray bytes = text.toUtf8(); QByteArray findBytes; int keyLens = 0; int index = 0; for (int i = 0; i < keyword.size(); ++i) { if ((loadFileProcessWin != nullptr) && loadFileProcessWin->isCancel()) { break; } index = 0; //20230223 不走老的逻辑了,批量替换太慢。直接把文件读取处理,在内存中一次性处理完毕。 //但是这样就不知道到底有多少字符串被替换了 findBytes = keyword.at(i).toUtf8(); keyLens = findBytes.size(); while (true) { index = bytes.indexOf(findBytes,index); if (index == -1) { break; } ++times; index += keyLens; } if ((loadFileProcessWin != nullptr)&& ((i % 100) == 0)) { loadFileProcessWin->moveStep(); QCoreApplication::processEvents(); } } if (loadFileProcessWin != nullptr) { delete loadFileProcessWin; } return times; } //在后台批量替换 int FindWin::replaceAtBack(QStringList& keyword, QStringList& replace) { assert(keyword.size() == replace.size()); //this->setCurrentTab(REPLACE_TAB); if (keyword.isEmpty()) { return 0; } QWidget* pw = autoAdjustCurrentEditWin(); ScintillaEditView* pEdit = dynamic_cast<ScintillaEditView*>(pw); if (pEdit != nullptr) { if (pEdit->isReadOnly()) { ui.statusbar->showMessage(tr("The ReadOnly document does not allow replacement."), 8000); QApplication::beep(); return 0; } } m_isStatic = true; int times = 0; pEdit->execute(SCI_BEGINUNDOACTION); ProgressWin* loadFileProcessWin = nullptr; if (keyword.size() > 1000) { loadFileProcessWin = new ProgressWin(this); loadFileProcessWin->setWindowModality(Qt::WindowModal); loadFileProcessWin->info(tr("total %1 keyword, please wait ...").arg(keyword.size())); loadFileProcessWin->setTotalSteps(keyword.size() / 10); loadFileProcessWin->show(); } QString text = pEdit->text(); for (int i = 0; i < keyword.size(); ++i) { if ((loadFileProcessWin!=nullptr) && loadFileProcessWin->isCancel()) { break; } //20230223 不走老的逻辑了,批量替换太慢。直接把文件读取处理,在内存中一次性处理完毕。 //但是这样就不知道到底有多少字符串被替换了 text.replace(keyword.at(i), replace.at(i)); if ((loadFileProcessWin != nullptr) && ((i % 10) == 0)) { loadFileProcessWin->moveStep(); QCoreApplication::processEvents(); } } //替换外部后,一次性整体替换 int selectionEnd = pEdit->length(); pEdit->execute(SCI_SETTARGETRANGE, 0, selectionEnd); QByteArray bytes = text.toUtf8(); pEdit->execute(SCI_REPLACETARGET, bytes.size(), reinterpret_cast<sptr_t>(bytes.data())); if (loadFileProcessWin != nullptr) { delete loadFileProcessWin; } pEdit->execute(SCI_ENDUNDOACTION); m_isStatic = false; return times; } //在后台批量高亮 int FindWin::markAtBack(QStringList& keyword) { if (keyword.isEmpty()) { return 0; } QWidget* pw = autoAdjustCurrentEditWin(); ScintillaEditView* pEdit = dynamic_cast<ScintillaEditView*>(pw); if (pEdit != nullptr) { if (pEdit->isReadOnly()) { ui.statusbar->showMessage(tr("The ReadOnly document does not allow replacement."), 8000); QApplication::beep(); return 0; } } m_isStatic = true; int times = 0; ProgressWin* loadFileProcessWin = nullptr; if (keyword.size() > 1000) { loadFileProcessWin = new ProgressWin(this); loadFileProcessWin->setWindowModality(Qt::WindowModal); loadFileProcessWin->info(tr("total %1 keyword, please wait ...").arg(keyword.size())); loadFileProcessWin->setTotalSteps(keyword.size() / 100); loadFileProcessWin->show(); } QString text = pEdit->text(); QByteArray bytes = text.toUtf8(); QByteArray findBytes; int keyLens = 0; int index = 0; QMap<QByteArray, QVector<int>* > keyPos; for (int i = 0; i < keyword.size(); ++i) { if ((loadFileProcessWin != nullptr) && loadFileProcessWin->isCancel()) { break; } index = 0; //20230223 不走老的逻辑了,批量替换太慢。直接把文件读取处理,在内存中一次性处理完毕。 //但是这样就不知道到底有多少字符串被替换了 findBytes = keyword.at(i).toUtf8(); keyLens = findBytes.size(); if (keyLens == 0) { continue; } QVector<int>* vec = new QVector<int>(); vec->reserve(128); keyPos.insert(findBytes, vec); while (true) { index = bytes.indexOf(findBytes, index); if (index == -1) { break; } ++times; vec->append(index); index += keyLens; } if ((loadFileProcessWin != nullptr) && ((i % 100) == 0)) { loadFileProcessWin->moveStep(); QCoreApplication::processEvents(); } } //把结果高亮起来。 for (QMap<QByteArray, QVector<int>* >::iterator it = keyPos.begin(); it != keyPos.end(); ++it) { int foundTextLen = it.key().size(); QVector<int>* pVect = (*it); for (int i = 0, s = pVect->size(); i < s; ++i) { pEdit->execute(SCI_SETINDICATORCURRENT, CCNotePad::s_curMarkColorId); pEdit->execute(SCI_INDICATORFILLRANGE, pVect->at(i), foundTextLen); } delete pVect; } if (loadFileProcessWin != nullptr) { delete loadFileProcessWin; } return times; } int FindWin::findAllInCurDoc(QStringList* reResult) { if (ui.findComboBox->currentText().isEmpty()) { ui.statusbar->showMessage(tr("what find is null !"), 8000); QApplication::beep(); return 0; } QWidget* pw = autoAdjustCurrentEditWin(); ScintillaEditView* pEdit = dynamic_cast<ScintillaEditView*>(pw); if (pEdit != nullptr) { if (pEdit->isReadOnly()) { if (!m_isStatic) { ui.statusbar->showMessage(tr("The ReadOnly document does not allow this operation."), 8000); } QApplication::beep(); return 0; } QString resultDestStr; int askAbortTimes = 0; FindRecords results; results.pEdit = pEdit; results.findFilePath = pw->property("filePath").toString(); updateParameterFromUI(); //正则模式下面,拷贝所有结果到剪切板 bool isNeedResult(m_re && (reResult != nullptr)); int srcPostion = pEdit->execute(SCI_GETCURRENTPOS); int firstDisLineNum = pEdit->execute(SCI_GETFIRSTVISIBLELINE); int findNums = 0; //无条件进行第一次查找,从0行0列开始查找,而且不回环。如果没有找到,则替换完毕 QString whatFind = ui.findComboBox->currentText(); results.findText = whatFind; //这里不能直接修改results.findText的值,该值在外部显示还需要。如果修改则会显示紊乱 if (m_extend) { QString extendFind; convertExtendedToString(whatFind, extendFind); whatFind = extendFind; } //这里的forward一定要是true。回环一定是false if (!pEdit->findFirst(whatFind, m_re, m_cs, m_wo, false, true, FINDNEXTTYPE_FINDNEXT, 0, 0)) { ui.statusbar->showMessage(tr("cant't find text \'%1\'").arg(m_expr), 8000); if (!m_isStatic) { QApplication::beep(); emit sign_findAllInCurDoc(&results); } m_isFindFirst = true; return 0; } else { dealWithZeroFound(pEdit); } resultDestStr = addCurFindRecord(pEdit, results, false, isNeedResult); //正则模式下面,拷贝所有结果到剪切板 if (isNeedResult) { reResult->append(resultDestStr); } ++findNums; //找到了,把结果收集起来 while (pEdit->findNext()) { resultDestStr = addCurFindRecord(pEdit, results, false, isNeedResult); ++findNums; //正则模式下面,拷贝所有结果到剪切板 if (isNeedResult) { reResult->append(resultDestStr); } dealWithZeroFound(pEdit); //2000 和 4000时各询问一次,避免查询结果过大 if (((askAbortTimes == 0) && findNums > 2000) || ((askAbortTimes == 1) && findNums > 4000)) { int ret = QMessageBox::question(this, tr("Continue Find ?"), tr("The search results have been greater than %1 times in %2 files, and more may be slow. Continue to search?").arg(findNums).arg(1), tr("Yes"), tr("Abort")); if (ret == 1) { break; } ++askAbortTimes; } } pEdit->execute(SCI_GOTOPOS, srcPostion); pEdit->execute(SCI_SETFIRSTVISIBLELINE, firstDisLineNum); //pEdit->execute(SCI_SETXOFFSET, 0); //全部替换后,下次查找,必须算第一次查找 m_isFindFirst = true; if (!isNeedResult) { ui.statusbar->showMessage(tr("find finished, total %1 found!").arg(findNums), 10000); } else { ui.statusbar->showMessage(tr("find finished, total %1 found! Result in clipboard.").arg(findNums), 10000); } emit sign_findAllInCurDoc(&results); return findNums; } else { if (!m_isStatic) { ui.statusbar->showMessage(tr("The mode of the current document does not allow this operation."), 8000); QApplication::beep(); } } return 0; } void FindWin::slot_findAllInCurDoc() { //findAllInCurDoc(); int index = m_editTabWidget->currentIndex(); if (index >= 0) { findAllInOpenDoc(index); } } void FindWin::findAllInOpenDoc(int index) { if (ui.findComboBox->currentText().isEmpty()) { ui.statusbar->showMessage(tr("what find is null !"), 8000); QApplication::beep(); return; } QString whatFind = ui.findComboBox->currentText(); QString originWhatFine = whatFind; if (m_extend) { QString extendFind; convertExtendedToString(whatFind, extendFind); whatFind = extendFind; } int replaceNums = 0; QVector<FindRecords*>* allOpenFileRecord = new QVector<FindRecords*>(); for (int i = 0; i < m_editTabWidget->count(); ++i) { //是否只查找一个文档 if ((index != -1) && (i != index)) { continue; } QWidget* pw = m_editTabWidget->widget(i); ScintillaEditView* pEdit = dynamic_cast<ScintillaEditView*>(pw); if (pEdit != nullptr) { if (pEdit->isReadOnly()) { continue; } FindRecords* results = new FindRecords(); results->pEdit = pEdit; results->findFilePath = pw->property("filePath").toString(); updateParameterFromUI(); //无条件进行第一次查找,从0行0列开始查找,而且不回环。如果没有找到,则替换完毕 //results->findText要是有原来的值,因为扩展模式下\r\n不会转义,直接输出会换行显示 results->findText = originWhatFine; if (!pEdit->findFirst(whatFind, m_re, m_cs, m_wo, false, true, FINDNEXTTYPE_FINDNEXT, 0, 0)) { delete results; continue; } else { dealWithZeroFound(pEdit); } addCurFindRecord(pEdit, *results); ++replaceNums; //找到了,把结果收集起来 while (pEdit->findNext()) { addCurFindRecord(pEdit, *results); ++replaceNums; dealWithZeroFound(pEdit); } allOpenFileRecord->append(results); } } //全部替换后,下次查找,必须算第一次查找 m_isFindFirst = true; ui.statusbar->showMessage(tr("find finished, total %1 found!").arg(replaceNums), 10000); emit sign_findAllInOpenDoc(allOpenFileRecord, replaceNums, whatFind); //释放元素 for (int i = 0; i < allOpenFileRecord->size(); ++i) { delete allOpenFileRecord->at(i); } delete allOpenFileRecord; } void FindWin::slot_findAllInOpenDoc() { findAllInOpenDoc(-1); #if 0 if (ui.findComboBox->currentText().isEmpty()) { ui.statusbar->showMessage(tr("what find is null !"), 8000); QApplication::beep(); return; } QString whatFind = ui.findComboBox->currentText(); QString originWhatFine = whatFind; if (m_extend) { QString extendFind; convertExtendedToString(whatFind, extendFind); whatFind = extendFind; } int replaceNums = 0; QVector<FindRecords*>* allOpenFileRecord = new QVector<FindRecords*>(); for (int i = 0; i < m_editTabWidget->count(); ++i) { QWidget* pw = m_editTabWidget->widget(i); ScintillaEditView* pEdit = dynamic_cast<ScintillaEditView*>(pw); if (pEdit != nullptr) { if (pEdit->isReadOnly()) { continue; } FindRecords* results = new FindRecords(); results->pEdit = pEdit; results->findFilePath = pw->property("filePath").toString(); updateParameterFromUI(); //无条件进行第一次查找,从0行0列开始查找,而且不回环。如果没有找到,则替换完毕 //results->findText要是有原来的值,因为扩展模式下\r\n不会转义,直接输出会换行显示 results->findText = originWhatFine; if (!pEdit->findFirst(whatFind, m_re, m_cs, m_wo, false, true, FINDNEXTTYPE_FINDNEXT, 0, 0)) { delete results; continue; } else { dealWithZeroFound(pEdit); } addCurFindRecord(pEdit, *results); ++replaceNums; //找到了,把结果收集起来 while (pEdit->findNext()) { addCurFindRecord(pEdit, *results); ++replaceNums; dealWithZeroFound(pEdit); } allOpenFileRecord->append(results); } } //全部替换后,下次查找,必须算第一次查找 m_isFindFirst = true; ui.statusbar->showMessage(tr("find finished, total %1 found!").arg(replaceNums), 10000); emit sign_findAllInOpenDoc(allOpenFileRecord, replaceNums, whatFind); //释放元素 for (int i = 0; i < allOpenFileRecord->size(); ++i) { delete allOpenFileRecord->at(i); } delete allOpenFileRecord; #endif } //返回是否查找得到内容 bool FindWin::replaceFindNext(QsciScintilla* pEdit, bool showZeroFindTip) { m_isFound = false; //第一次查找 if (m_isFindFirst) { if (pEdit != nullptr) { QString whatFind = ui.replaceTextBox->currentText(); addFindHistory(whatFind); QString replaceWith = ui.replaceWithBox->currentText(); addReplaceHistory(replaceWith); if (m_extend) { QString extendFind; convertExtendedToString(whatFind, extendFind); whatFind = extendFind; } if (!pEdit->findFirst(whatFind, m_re, m_cs, m_wo, m_wrap, m_forward, FINDNEXTTYPE_REPLACENEXT)) { ui.statusbar->showMessage(tr("cant't find text \'%1\'").arg(m_expr), 8000); QApplication::beep(); m_isFindFirst = true; } else { m_isFound = true; m_isFindFirst = false; dealWithZeroFoundShowTip(pEdit, showZeroFindTip); } } } else { //查找下一个 if (pEdit != nullptr) { adjustSearchStartPosChange(pEdit); if (!pEdit->findNext()) { ui.statusbar->showMessage(tr("no more find text \'%1\'").arg(m_expr), 8000); m_isFindFirst = true; QApplication::beep(); } else { m_isFound = true; dealWithZeroFoundShowTip(pEdit, showZeroFindTip); } } } return m_isFound; } void FindWin::slot_replaceFindNext() { if (ui.replaceTextBox->currentText().isEmpty()) { ui.statusbar->showMessage(tr("what find is null !"), 8000); QApplication::beep(); return; } updateParameterFromUI(); QWidget* pw = autoAdjustCurrentEditWin(); QsciScintilla* pEdit = dynamic_cast<QsciScintilla*>(pw); replaceFindNext(pEdit, true); } //返回值:是否还可以继续替换 bool FindWin::replace(ScintillaEditView* pEdit) { if (isFirstFind()) { replaceFindNext(pEdit, false); //如果没有找到,则不替换 if (!m_isFound) { return false; } } QString findText = ui.replaceTextBox->currentText(); QString replaceText = ui.replaceWithBox->currentText(); if (m_extend) { QString extendFind; convertExtendedToString(findText, extendFind); findText = extendFind; QString extendReplace; convertExtendedToString(replaceText, extendReplace); replaceText = extendReplace; } //当前有选中内容,而且与待替换内容一样,则直接替换 if (m_isFound && pEdit->hasSelectedText()) { //如果选中内容,与待查找替换的内容一致,进行替换。前提是在normal模式下 if ((m_searchMode == 1) && (pEdit->selectedText().compare(findText, (m_cs ? Qt::CaseSensitive : Qt::CaseInsensitive)) == 0)) { pEdit->replace(replaceText); return replaceFindNext(pEdit,false); } else if (m_searchMode == 2) { //如果是正则表达式模式,则不能使用全部匹配才替换,要使用正则匹配,那样会比较麻烦 //只有上次查找成功,才替换? if (m_isFound) { pEdit->replace(replaceText); return replaceFindNext(pEdit,false); } else { ui.statusbar->showMessage(tr("no more replace text \'%1\'").arg(m_expr), 8000); QApplication::beep(); return false; } } else { ui.statusbar->showMessage(tr("no more replace text \'%1\'").arg(m_expr), 8000); QApplication::beep(); return false; } } else if (m_isFound && m_searchMode == 2) { //找到了内容,但是因为是0长,而无法选中。这种情况就是0长的情况。只在正则表达式情况出现 pEdit->replace(replaceText); //每次替换后,因为是0长替换,再把下次查找位置加1,否则会一直在原地查找 dealWithZeroFound(pEdit); return replaceFindNext(pEdit,false); } //当前没有查找到 return replaceFindNext(pEdit,false); } //把当前选中的内容,使用文本替换掉 void FindWin::slot_replace() { if (ui.replaceTextBox->currentText().isEmpty()) { ui.statusbar->showMessage(tr("what find is null !"), 8000); QApplication::beep(); return; } QWidget* pw = autoAdjustCurrentEditWin(); ScintillaEditView* pEdit = dynamic_cast<ScintillaEditView*>(pw); if (pEdit != nullptr) { if (pEdit->isReadOnly()) { ui.statusbar->showMessage(tr("The ReadOnly document does not allow replacement."), 8000); QApplication::beep(); return; } //切换查询条件后,则是第一次查找。防止前后查找条件发生了变化, //导致选中的内容不是需要替换的,所以检查是第一次查找,则查找一下 updateParameterFromUI(); replace(pEdit); } else { ui.statusbar->showMessage(tr("The mode of the current document does not allow replacement."), 8000); QApplication::beep(); } } void FindWin::slot_findModeRegularBtChange(bool checked) { if (checked) { ui.findBackwardBox->setEnabled(false); ui.findBackwardBox->setChecked(false); ui.findMatchWholeBox->setEnabled(false); ui.findMatchWholeBox->setChecked(false); } else { ui.findBackwardBox->setEnabled(true); ui.findMatchWholeBox->setEnabled(true); } m_isFindFirst = true; } void FindWin::slot_replaceModeRegularBtChange(bool checked) { if (checked) { ui.replaceBackwardBox->setEnabled(false); ui.replaceBackwardBox->setChecked(false); ui.replaceMatchWholeBox->setEnabled(false); ui.replaceMatchWholeBox->setChecked(false); } else { ui.replaceBackwardBox->setEnabled(true); ui.replaceMatchWholeBox->setEnabled(true); } m_isFindFirst = true; } #if 0 //替换当前文档里面的所有 void FindWin::slot_replaceAll() { if (ui.replaceTextBox->currentText().isEmpty()) { ui.statusbar->showMessage(tr("what find is null !"), 8000); return; } if (!m_isStatic && QMessageBox::Yes != QMessageBox::question(this, tr("Replace All current Doc"), tr("Are you sure replace all occurrences in current documents?"))) { return; } QWidget* pw = autoAdjustCurrentEditWin(); ScintillaEditView* pEdit = dynamic_cast<ScintillaEditView*>(pw); if (pEdit != nullptr) { if (pEdit->isReadOnly()) { ui.statusbar->showMessage(tr("The ReadOnly document does not allow replacement."), 8000); QApplication::beep(); return; } updateParameterFromUI(); int srcPostion = pEdit->execute(SCI_GETCURRENTPOS); int firstDisLineNum = pEdit->execute(SCI_GETFIRSTVISIBLELINE); int replaceNums = 0; //无条件进行第一次查找,从0行0列开始查找,而且不回环。如果没有找到,则替换完毕 QString whatFind = ui.replaceTextBox->currentText(); QString replaceText = ui.replaceWithBox->currentText(); if (m_extend) { QString extendFind; convertExtendedToString(whatFind, extendFind); whatFind = extendFind; QString extendReplace; convertExtendedToString(replaceText, extendReplace); replaceText = extendReplace; } if (!pEdit->findFirst(whatFind, m_re, m_cs, m_wo, false, true, FINDNEXTTYPE_REPLACENEXT, 0,0)) { ui.statusbar->showMessage(tr("cant't find text \'%1\'").arg(m_expr), 8000); QApplication::beep(); m_isFindFirst = true; return; } pEdit->execute(SCI_BEGINUNDOACTION); pEdit->replace(replaceText); dealWithZeroFound(pEdit); ++replaceNums; //找到了,则自动进行全部替换 while(pEdit->findNext()) { pEdit->replace(replaceText); ++replaceNums; dealWithZeroFound(pEdit); } pEdit->execute(SCI_ENDUNDOACTION); pEdit->execute(SCI_GOTOPOS, srcPostion); pEdit->execute(SCI_SETFIRSTVISIBLELINE, firstDisLineNum); pEdit->execute(SCI_SETXOFFSET, 0); //全部替换后,下次查找,必须算第一次查找 m_isFindFirst = true; ui.statusbar->showMessage(tr("replace finished, total %1 replaced!").arg(replaceNums), 10000); } else { ui.statusbar->showMessage(tr("The mode of the current document does not allow replacement."), 8000); QApplication::beep(); } } #endif // Find the first occurrence of a string. int buildSearchFlags(bool re, bool cs, bool wo, bool wrap, bool forward, FindNextType findNextType, bool posix, bool cxx11) { int flags = 0; flags = (cs ? SCFIND_MATCHCASE : 0) | (wo ? SCFIND_WHOLEWORD : 0) | (re ? SCFIND_REGEXP : 0) | (posix ? SCFIND_POSIX : 0) | (cxx11 ? SCFIND_CXX11REGEX : 0); switch (findNextType) { case FINDNEXTTYPE_FINDNEXT: flags |= SCFIND_REGEXP_EMPTYMATCH_ALL | SCFIND_REGEXP_SKIPCRLFASONE; break; case FINDNEXTTYPE_REPLACENEXT: flags |= SCFIND_REGEXP_EMPTYMATCH_NOTAFTERMATCH | SCFIND_REGEXP_SKIPCRLFASONE; break; case FINDNEXTTYPE_FINDNEXTFORREPLACE: flags |= SCFIND_REGEXP_EMPTYMATCH_ALL | SCFIND_REGEXP_EMPTYMATCH_ALLOWATSTART | SCFIND_REGEXP_SKIPCRLFASONE; break; } return flags; } struct FindReplaceInfo { intptr_t _startRange = -1; intptr_t _endRange = -1; }; //返回值替换数量 int FindWin::doReplaceAll(ScintillaEditView* pEdit, QString &whatFind, QString& replaceText, bool isCombineUndo) { int replaceNums = 0; int srcPostion = pEdit->execute(SCI_GETCURRENTPOS); int firstDisLineNum = pEdit->execute(SCI_GETFIRSTVISIBLELINE); if (isCombineUndo) { pEdit->execute(SCI_BEGINUNDOACTION); } int flags = buildSearchFlags(m_re, m_cs, m_wo, false, true, FINDNEXTTYPE_REPLACENEXT, 0, 0); intptr_t targetStart = 0; intptr_t targetEnd = 0; //Initial range for searching pEdit->execute(SCI_SETSEARCHFLAGS, flags); FindReplaceInfo findReplaceInfo; findReplaceInfo._startRange = 0; findReplaceInfo._endRange = pEdit->execute(SCI_GETLENGTH); QByteArray pTextFind = whatFind.toUtf8(); QByteArray pTextReplace = replaceText.toUtf8(); while (targetStart >= 0) { targetStart = pEdit->searchInTarget(pTextFind, findReplaceInfo._startRange, findReplaceInfo._endRange); // If we've not found anything, just break out of the loop if (targetStart == -1 || targetStart == -2) break; targetEnd = pEdit->execute(SCI_GETTARGETEND); if (targetEnd > findReplaceInfo._endRange) { //we found a result but outside our range, therefore do not process it break; } intptr_t foundTextLen = targetEnd - targetStart; intptr_t replaceDelta = 0; intptr_t replacedLength; if (m_re) { replacedLength = pEdit->replaceTargetRegExMode(pTextReplace); } else { replacedLength = pEdit->replaceTarget(pTextReplace); } replaceDelta = replacedLength - foundTextLen; ++replaceNums; // After the processing of the last string occurrence the search loop should be stopped // This helps to avoid the endless replacement during the EOL ("$") searching if (targetStart + foundTextLen == findReplaceInfo._endRange) break; findReplaceInfo._startRange = targetStart + foundTextLen + replaceDelta; //search from result onwards findReplaceInfo._endRange += replaceDelta; //adjust end of range in case of replace } if (isCombineUndo) { pEdit->execute(SCI_ENDUNDOACTION); } pEdit->execute(SCI_GOTOPOS, srcPostion); pEdit->execute(SCI_SETFIRSTVISIBLELINE, firstDisLineNum); //pEdit->execute(SCI_SETXOFFSET, 0); return replaceNums; } int FindWin::replaceAll() { if (ui.replaceTextBox->currentText().isEmpty()) { ui.statusbar->showMessage(tr("what find is null !"), 8000); return 0; } if (!m_isStatic && QMessageBox::Yes != QMessageBox::question(this, tr("Replace All current Doc"), tr("Are you sure replace all occurrences in current documents?"))) { return 0; } QWidget* pw = autoAdjustCurrentEditWin(); ScintillaEditView* pEdit = dynamic_cast<ScintillaEditView*>(pw); if (pEdit != nullptr) { if (pEdit->isReadOnly()) { ui.statusbar->showMessage(tr("The ReadOnly document does not allow replacement."), 8000); QApplication::beep(); return 0; } } updateParameterFromUI(); QString whatFind = ui.replaceTextBox->currentText(); QString replaceText = ui.replaceWithBox->currentText(); if (m_extend) { QString extendFind; convertExtendedToString(whatFind, extendFind); whatFind = extendFind; QString extendReplace; convertExtendedToString(replaceText, extendReplace); replaceText = extendReplace; } int replaceNums = doReplaceAll(pEdit, whatFind, replaceText); //全部替换后,下次查找,必须算第一次查找 m_isFindFirst = true; ui.statusbar->showMessage(tr("replace finished, total %1 replaced!").arg(replaceNums), 10000); return replaceNums; } //替换当前文档里面的所有。之前的要慢,是因为qscintilla中实时计算了行在屏幕需要的长度。 //大量的这种计算一行实时长度的操作,非常耗时。查找、标记均不耗时,只有替换修改了文本才耗时。 void FindWin::slot_replaceAll() { replaceAll(); } void FindWin::slot_replaceAllInOpenDoc() { if (ui.replaceTextBox->currentText().isEmpty()) { ui.statusbar->showMessage(tr("what find is null !"), 8000); QApplication::beep(); return; } if (QMessageBox::Yes != QMessageBox::question(this, tr("Replace All Open Doc"), tr("Are you sure replace all occurrences in all open documents?"))) { return; } updateParameterFromUI(); int replaceNums = 0; QString whatFind = ui.replaceTextBox->currentText(); QString whatReplace = m_replaceWithText; if (m_extend) { QString extendFind; convertExtendedToString(whatFind, extendFind); whatFind = extendFind; QString extendReplace; convertExtendedToString(whatReplace, extendReplace); whatReplace = extendReplace; } for (int i = 0; i < m_editTabWidget->count(); ++i) { QWidget* pw = m_editTabWidget->widget(i); ScintillaEditView* pEdit = dynamic_cast<ScintillaEditView*>(pw); if (pEdit != nullptr) { //只读的文档不能替换 if (pEdit->isReadOnly()) { continue; } replaceNums += doReplaceAll(pEdit, whatFind, whatReplace); #if 0 //无条件进行第一次查找,从0行0列开始查找,而且不回环。如果没有找到,则替换完毕 if (!pEdit->findFirst(whatFind, m_re, m_cs, m_wo, false, true, FINDNEXTTYPE_REPLACENEXT,0, 0)) { continue; } pEdit->replace(whatReplace); dealWithZeroFound(pEdit); ++replaceNums; //找到了,则自动进行全部替换 while (pEdit->findNext()) { pEdit->replace(whatReplace); ++replaceNums; dealWithZeroFound(pEdit); } #endif } } //全部替换后,下次查找,必须算第一次查找 m_isFindFirst = true; ui.statusbar->showMessage(tr("Replace in Opened Files: %1 occurrences were replaced.").arg(replaceNums), 10000); } int FindWin::markAll(QSet<int>* outLineNum) { if (ui.markTextBox->currentText().isEmpty()) { ui.statusbar->showMessage(tr("what mark is null !"), 8000); QApplication::beep(); return 0; } QWidget* pw = autoAdjustCurrentEditWin(); ScintillaEditView* pEdit = dynamic_cast<ScintillaEditView*>(pw); if (pEdit != nullptr) { FindRecords* results = new FindRecords; results->pEdit = pEdit; results->hightLightColor = CCNotePad::s_curMarkColorId; results->findFilePath = pw->property("filePath").toString(); updateParameterFromUI(); int replaceNums = 0; //无条件进行第一次查找,从0行0列开始查找,而且不回环。如果没有找到,则替换完毕 QString whatMark = ui.markTextBox->currentText(); results->findText = whatMark; if (m_extend) { QString extendFind; convertExtendedToString(whatMark, extendFind); whatMark = extendFind; } int srcPostion = pEdit->execute(SCI_GETCURRENTPOS); int firstDisLineNum = pEdit->execute(SCI_GETFIRSTVISIBLELINE); if (!pEdit->findFirst(whatMark, m_re, m_cs, m_wo, false, true, FINDNEXTTYPE_FINDNEXT, 0, 0)) { ui.statusbar->showMessage(tr("cant't find text \'%1\'").arg(m_expr), 8000); //QApplication::beep(); return 0; } else { //不支持零长的高亮。0长不高亮 FindState& state = pEdit->getLastFindState(); if (state.targstart == state.targend) { ui.statusbar->showMessage(tr("cant't mark text \'%1\'").arg(m_expr), 8000); QApplication::beep(); return 0; } } addCurFindRecord(pEdit, *results, true); ++replaceNums; //找到了,把结果收集起来 while (pEdit->findNext()) { addCurFindRecord(pEdit, *results, true); ++replaceNums; } //把结果高亮起来。 int foundTextLen = 0; for (int i = 0, s = results->records.size(); i < s; ++i) { const FindRecord& rs = results->records.at(i); foundTextLen = rs.end - rs.pos; if (foundTextLen > 0) { pEdit->execute(SCI_SETINDICATORCURRENT, CCNotePad::s_curMarkColorId); pEdit->execute(SCI_INDICATORFILLRANGE, rs.pos, foundTextLen); } if (outLineNum != nullptr) { outLineNum->insert(rs.lineNum); } } if (!results->records.isEmpty()) { pEdit->appendMarkRecord(results); } pEdit->execute(SCI_GOTOPOS, srcPostion); pEdit->execute(SCI_SETFIRSTVISIBLELINE, firstDisLineNum); //pEdit->execute(SCI_SETXOFFSET, 0); //全部替换后,下次查找,必须算第一次查找 m_isFindFirst = true; ui.statusbar->showMessage(tr("mark finished, total %1 found!").arg(replaceNums), 10000); return replaceNums; } else { ui.statusbar->showMessage(tr("The mode of the current document does not allow mark."), 8000); QApplication::beep(); } return 0; } //标记高亮单词 void FindWin::slot_markAll() { markAll(); } //取消高亮当前关键字 void FindWin::slot_clearMark() { if (ui.markTextBox->currentText().isEmpty()) { ui.statusbar->showMessage(tr("what mark is null !"), 8000); QApplication::beep(); return; } CCNotePad* pMainPad = dynamic_cast<CCNotePad*>(m_pMainPad); if (pMainPad != nullptr) { pMainPad->clearHighlightWord(ui.markTextBox->currentText()); } } //取消所有高亮 void FindWin::slot_clearAllMark() { CCNotePad* pMainPad = dynamic_cast<CCNotePad*>(m_pMainPad); if (pMainPad != nullptr) { pMainPad->slot_clearMark(); } } //选择查找目录 void FindWin::slot_dirSelectDest() { QString curDirPath = ui.destFindDir->text(); if (curDirPath.isEmpty()) { if (CCNotePad::s_lastOpenDirPath.isEmpty()) { CCNotePad::s_lastOpenDirPath = NddSetting::getKeyValueFromDelaySets(LAST_OPEN_DIR); } curDirPath = CCNotePad::s_lastOpenDirPath; } QString destDir = QFileDialog::getExistingDirectory(this, tr("Open Directory"), curDirPath, QFileDialog::DontResolveSymlinks); if (!destDir.isEmpty()) { ui.destFindDir->setText(destDir); } } //在walkDirfile中用作回调函数处理。命中则返回true bool FindWin::findTextInFile(QString &filePath, int &findNums, QVector<FindRecords*>* allfileInDirRecord) { pEditTemp->clear(); if (0 != FileManager::getInstance().loadFileForSearch(pEditTemp, filePath)) { return false; } FindRecords* results = new FindRecords(); //返回结果的edit无条件写无。注意不要忘记 results->pEdit = nullptr; results->findFilePath = filePath; //无条件进行第一次查找,从0行0列开始查找,而且不回环。如果没有找到,则替换完毕 results->findText = m_expr; QString whatFind = m_expr; if (m_extend) { QString extendFind; convertExtendedToString(whatFind, extendFind); whatFind = extendFind; } if (!pEditTemp->findFirst(whatFind, m_re, m_cs, m_wo, false, m_forward, FINDNEXTTYPE_FINDNEXT, 0, 0,false)) { delete results; return false; } else { dealWithZeroFound(pEditTemp); } addCurFindRecord(pEditTemp, *results); ++findNums; //找到了,把结果收集起来 while (pEditTemp->findNext()) { addCurFindRecord(pEditTemp, *results); ++findNums; dealWithZeroFound(pEditTemp); } allfileInDirRecord->append(results); return true; } //在walkDirfile中用作回调函数处理。命中则返回true 第三个参数不需要,为了复用walkdir,暂时保留和findTextInFile一致 bool FindWin::replaceTextInFile(QString &filePath, int &replaceNums, QVector<FindRecords*>*) { pEditTemp->clear(); if (0 != FileManager::getInstance().loadFileForSearch(pEditTemp, filePath)) { return false; } QString find = m_expr; QString replace = m_replaceWithText; if (m_extend) { QString extendFind; convertExtendedToString(find, extendFind); find = extendFind; QString extendReplace; convertExtendedToString(replace, extendReplace); replace = extendReplace; } int modifyTimes = doReplaceAll(pEditTemp, find, replace); if (modifyTimes > 0) { replaceNums += modifyTimes; //如果进行过替换,则必须要保存一下;否则不能保存,不然文件被修改。 emit sign_replaceSaveFile(filePath, pEditTemp); } return true; } //非递归版本的递归文件,从CompareDirs中修改而来 //isSkipBinary:是否跳过二进制 //isSkipHide:是否处理隐藏文件 //skipMaxSize::处理文件的最大大小,超过则不处理。如果是0,则表示不跳过任何文件 //isfilterFileType:过滤类型,只处理这类类型文件 为true时 fileExtType 不能为空 //fileExtType的格式为:.cpp .h 类似,但是不需要前面的.,传递的时候不传递下来 int FindWin::walkDirfile(QString path, int &foundTimes, bool isSkipBinary, bool isSkipHide, int skipMaxSize, bool isfilterFileType, QStringList& fileExtType, bool isSkipDir, QStringList & skipDirNames, bool isSkipChildDirs, std::function<bool(QString &, int &, QVector<FindRecords*>* allfileInDirRecord)> foundCallBack, bool isAskAbort) { QList<QString> dirsList; QString oneDir(path); dirsList.append(oneDir); int fileNums = 0; int hitFileNums = 0; //再获取文件夹到列表 QDir::Filters dirfilter; if (!isSkipHide) { dirfilter = QDir::Dirs | QDir::NoDotAndDotDot | QDir::Hidden | QDir::NoSymLinks; } else { dirfilter = QDir::Dirs | QDir::NoDotAndDotDot | QDir::NoSymLinks; } //过滤文件类型。true 合格,需要处理, false 不合格,跳过 auto fileTypeFilter = [&fileExtType](QFileInfo& fileInfo)->bool { QString suffix = fileInfo.suffix(); if (!suffix.isEmpty()) { return (-1 != fileExtType.indexOf(suffix)); } //对于没有后缀的文件,一律跳过 return false; }; //是否二进制文件 auto binaryFiltre = [](QFileInfo& fi)->bool { return DocTypeListView::isHexExt(fi.suffix()); }; ProgressWin* loadFileProcessWin = new ProgressWin(this); loadFileProcessWin->setWindowModality(Qt::WindowModal); loadFileProcessWin->info(tr("load dir file in progress\n, please wait ...")); loadFileProcessWin->show(); int dirNums = 0; bool firstChildDirs = true; int totalStep = 0; bool canAbort = true; bool canAbortSecond = true; if (!isAskAbort) { canAbort = false; canAbortSecond = false; } while (!dirsList.isEmpty()) { QString curDir = dirsList.takeFirst(); if (!isSkipChildDirs) { /*添加path路径文件*/ QDir dir(curDir); //遍历各级子目录 QFileInfoList folder_list = dir.entryInfoList(dirfilter); //获取当前所有目录 for (int i = 0; i != folder_list.size(); ++i) //自动递归添加各目录到上一级目录 { QString namepath = folder_list.at(i).absoluteFilePath(); //获取路径 QFileInfo folderinfo = folder_list.at(i); if (folderinfo.baseName().isEmpty()) { loadFileProcessWin->info(tr("skip dir %1").arg(namepath)); continue; } QString name = folderinfo.fileName(); //获取目录名 if (isSkipDir && (-1 != skipDirNames.indexOf(name))) { loadFileProcessWin->info(tr("skip dir %1").arg(namepath)); continue; } dirsList.push_front(namepath); dirNums++; loadFileProcessWin->info(tr("found %1 dir %2").arg(dirNums).arg(namepath)); QCoreApplication::processEvents(/*QEventLoop::ExcludeUserInputEvents*/); } if (firstChildDirs) { totalStep = dirNums; loadFileProcessWin->setTotalSteps(dirNums); firstChildDirs = false; } if (dirsList.size() < totalStep) { totalStep = dirsList.size(); loadFileProcessWin->moveStep(); } } QDir dir_file(curDir); if (!isSkipHide) { dir_file.setFilter(QDir::Files | QDir::NoDotAndDotDot | QDir::Hidden | QDir::NoSymLinks);//获取当前所有文件 } else { dir_file.setFilter(QDir::Files | QDir::NoDotAndDotDot | QDir::NoSymLinks);//获取当前所有文件 } QFileInfoList list_file = dir_file.entryInfoList(); for (int i = 0; i < list_file.size(); ++i) { //将当前目录中所有文件添加到treewidget中 QFileInfo fileInfo = list_file.at(i); QString namepath = list_file.at(i).absoluteFilePath(); //获取路径 //不支持所有文件,仅仅支持指定类型文件。没有通过 if (isfilterFileType && !fileTypeFilter(fileInfo)) { loadFileProcessWin->info(tr("ext type skip file %1").arg(namepath)); continue; } //大小过滤 if ((skipMaxSize != 0) && fileInfo.size() > skipMaxSize) { continue; } //二进制过滤//对于二进制文件该如何处理,我觉得必须要过滤,暂时不处理 if (isSkipBinary &&binaryFiltre(fileInfo)) { continue; } //回调处理该函数 if (foundCallBack(namepath, foundTimes, nullptr)) { ++hitFileNums; } if (i % 2 == 0) { if (loadFileProcessWin->isCancel()) { loadFileProcessWin->info(tr("found in dir canceled ...")); break; } QCoreApplication::processEvents(); } if ((canAbort && (hitFileNums > 100 || foundTimes > 1000)) || (canAbortSecond && foundTimes > 8000)) { int ret = QMessageBox::question(this, tr("Continue Find ?"), tr("The search results have been greater than %1 times in %2 files, and more may be slow. Continue to search?").arg(foundTimes).arg(hitFileNums), tr("Yes"), tr("Abort")); if(ret == 1) { loadFileProcessWin->setCancel(); break; } else { if (canAbort && (hitFileNums > 100 || foundTimes > 1000)) { canAbort = false; } if ((canAbortSecond && foundTimes > 8000)) { canAbortSecond = false; } } } } fileNums += list_file.size(); if (loadFileProcessWin->isCancel()) { break; } } if (loadFileProcessWin != nullptr) { delete loadFileProcessWin; loadFileProcessWin = nullptr; } return fileNums; } //在目标文件夹中查找 void FindWin::slot_dirFindAll() { QString dirPath = ui.destFindDir->text().trimmed(); QString whatFind = ui.dirFindWhat->currentText(); if (dirPath.isEmpty()) { ui.statusbar->showMessage(tr("please select find dest dir !"), 8000); QApplication::beep(); return; } if(whatFind.isEmpty()) { ui.statusbar->showMessage(tr("what find is null !"), 8000); QApplication::beep(); return; } QDir dir(dirPath); if (!dir.exists()) { ui.statusbar->showMessage(tr("dest dir %1 not exist !").arg(dirPath), 8000); QApplication::beep(); return; } bool isfilterFileType = ui.dealFileType->isChecked(); bool isSkipDirs = ui.skipDir->isChecked(); QStringList fileExtTypeList; QStringList skipDirNameList; if (isfilterFileType) { QString fileExtType = ui.fileType->text().trimmed(); if (fileExtType.isEmpty() || (fileExtType == "*.*")) { isfilterFileType = false; } else { //格式是*.h:*.c:*.cpp类似的 QStringList typeList = fileExtType.split(":"); foreach (QString var, typeList) { if (var.size() >= 3) { //只取后面的h或或cpp后缀 fileExtTypeList.append(var.mid(2)); } } if (fileExtTypeList.isEmpty()) { isfilterFileType = false; } } } if (isSkipDirs) { QString dirNames = ui.skipDirNames->text().trimmed(); if (dirNames.isEmpty()) { isSkipDirs = false; } else { QStringList nameList = dirNames.split(":"); foreach(QString var, nameList) { if (var.size() > 0) { //只取后面的h或或cpp后缀 skipDirNameList.append(var); } } if (skipDirNameList.isEmpty()) { isSkipDirs = false; } } } bool isSkipBinary = ui.skipBinary->isChecked(); bool isSkipHide = ui.skipHideFile->isChecked(); int skipMaxSize = (ui.skipFileMaxSize->isChecked()) ? ui.maxFileSizeSpinBox->value()*1024*1024:0; bool isSkipChildDir = ui.skipChildDirs->isChecked(); updateParameterFromUI(); if (pEditTemp == nullptr) { pEditTemp = ScintillaEditView::createEditForSearch(); } int foundNums = 0; QVector<FindRecords*>* allfileInDirRecord = new QVector<FindRecords*>(); std::function<bool(QString &, int &, QVector<FindRecords*>* allfileInDirRecord)> foundCallBack = std::bind(&FindWin::findTextInFile, this, std::placeholders::_1, std::placeholders::_2, allfileInDirRecord); int filesNum = walkDirfile(dirPath, foundNums, isSkipBinary, isSkipHide, skipMaxSize, isfilterFileType, fileExtTypeList, isSkipDirs, skipDirNameList, isSkipChildDir, foundCallBack); //全部替换后,下次查找,必须算第一次查找 m_isFindFirst = true; ui.statusbar->showMessage(tr("find finished, walk %1 files, total %2 found in %3 file!").arg(filesNum).arg(foundNums).arg(allfileInDirRecord->size())); //复用了这个信号函数,没有新做消息,要注意 emit sign_findAllInOpenDoc(allfileInDirRecord, foundNums, whatFind); addFindHistory(whatFind); //释放元素 for (int i = 0; i < allfileInDirRecord->size(); ++i) { delete allfileInDirRecord->at(i); } delete allfileInDirRecord; } //目录中直接替换 void FindWin::slot_dirReplaceAll() { QString dirPath = ui.destFindDir->text(); QString whatFind = ui.dirFindWhat->currentText(); QString dirReplaceWhat = ui.dirReplaceWhat->currentText(); if (dirPath.isEmpty()) { ui.statusbar->showMessage(tr("please select find dest dir !"), 8000); QApplication::beep(); return; } if (whatFind.isEmpty()) { ui.statusbar->showMessage(tr("what find is null !"), 8000); QApplication::beep(); return; } if (QMessageBox::Yes != QMessageBox::question(this, tr("Replace All Dirs"), tr("Are you sure replace all \"%1\" to \"%2\" occurrences in selected dirs ?").arg(whatFind).arg(dirReplaceWhat))) { return; } bool isfilterFileType = ui.dealFileType->isChecked(); QStringList fileExtTypeList; bool isSkipDirs = ui.skipDir->isChecked(); QStringList skipDirNameList; if (isfilterFileType) { QString fileExtType = ui.fileType->text().trimmed(); if (fileExtType.isEmpty() || (fileExtType == "*.*")) { isfilterFileType = false; } else { //格式是*.h:*.c:*.cpp类似的 QStringList typeList = fileExtType.split(":"); foreach(QString var, typeList) { if (var.size() >= 3) { //只取后面的h或或cpp后缀 fileExtTypeList.append(var.mid(2)); } } if (fileExtTypeList.isEmpty()) { isfilterFileType = false; } } } if (isSkipDirs) { QString dirNames = ui.skipDirNames->text().trimmed(); if (dirNames.isEmpty()) { isSkipDirs = false; } else { QStringList nameList = dirNames.split(":"); foreach(QString var, nameList) { if (var.size() > 0) { //只取后面的h或或cpp后缀 skipDirNameList.append(var); } } if (skipDirNameList.isEmpty()) { isSkipDirs = false; } } } bool isSkipBinary = ui.skipBinary->isChecked(); bool isSkipHide = ui.skipHideFile->isChecked(); int skipMaxSize = (ui.skipFileMaxSize->isChecked()) ? ui.maxFileSizeSpinBox->value() * 1024 * 1024 : 0; bool isSkipChildDir = ui.skipChildDirs->isChecked(); addReplaceHistory(dirReplaceWhat); updateParameterFromUI(); if (pEditTemp == nullptr) { pEditTemp = ScintillaEditView::createEditForSearch(); } int replaceNums = 0; std::function<bool(QString &, int &, QVector<FindRecords*>* allfileInDirRecord)> foundCallBack = std::bind(&FindWin::replaceTextInFile, this, std::placeholders::_1, std::placeholders::_2, nullptr); int filesNum = walkDirfile(dirPath, replaceNums, isSkipBinary, isSkipHide, skipMaxSize, isfilterFileType, fileExtTypeList, isSkipDirs, skipDirNameList,isSkipChildDir, foundCallBack,false); //全部替换后,下次查找,必须算第一次查找 m_isFindFirst = true; ui.statusbar->showMessage(tr("replace finished, walk %1 files, total %2 replace !").arg(filesNum).arg(replaceNums)); } //把正则查找的结果,拷贝到剪切板 void FindWin::on_copyReFindResult() { if (!ui.findModeRegularBt->isChecked()) { ui.statusbar->showMessage(tr("Only regular lookup mode can be used!"),10000); return; } QStringList reResult; findAllInCurDoc(&reResult); if (!reResult.isEmpty()) { QClipboard* clipboard = QApplication::clipboard(); clipboard->setText(reResult.join("\n")); } } void FindWin::on_markAndBook() { QSet<int> outLineNum; markAll(&outLineNum); QWidget* pw = autoAdjustCurrentEditWin(); ScintillaEditView* pEdit = dynamic_cast<ScintillaEditView*>(pw); if (pEdit != nullptr) { pEdit->bookmarkAdd(outLineNum); } }
78,960
C++
.cpp
2,638
23.279757
337
0.684123
cxasm/notepad--
5,942
234
284
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
25,170
ndstyleditemdelegate.cpp
cxasm_notepad--/src/ndstyleditemdelegate.cpp
#include "ndstyleditemdelegate.h" #include <QTextDocument> #include <QApplication> #include <QAbstractTextDocumentLayout> #include <QPainter> #include <QTextEdit> NdStyledItemDelegate::NdStyledItemDelegate(QObject *parent) : QStyledItemDelegate(parent), m_defaultFontSize(14) { } NdStyledItemDelegate::~NdStyledItemDelegate() { } void NdStyledItemDelegate::setFontSize(int size) { m_defaultFontSize = size; } //重载使可以支持富文本格式的文字 void NdStyledItemDelegate::paint(QPainter * painter, const QStyleOptionViewItem & option, const QModelIndex & index) const { QStyleOptionViewItem viewOption(option); initStyleOption(&viewOption, index); if (option.state.testFlag(QStyle::State_HasFocus)) viewOption.state = viewOption.state ^ QStyle::State_HasFocus; // ... 省略 // 设置显示文本为空,使用默认样式 QStyle *pStyle = viewOption.widget ? viewOption.widget->style() : QApplication::style(); QTextDocument doc; //外部修改了字体大小后,内部进行富文本的修改绘制。 if (m_defaultFontSize != 14) { viewOption.text.replace("font-size:14px",QString("font-size:%1px").arg(m_defaultFontSize)); } doc.setHtml(viewOption.text); viewOption.text.clear(); pStyle->drawControl(QStyle::CE_ItemViewItem, &viewOption, painter, viewOption.widget); QAbstractTextDocumentLayout::PaintContext paintContext; QRect textRect = pStyle->subElementRect(QStyle::SE_ItemViewItemText, &viewOption); painter->save(); // 坐标变换,将左上角设置为原点 painter->translate(textRect.topLeft()); // 设置HTML绘制区域 painter->setClipRect(textRect.translated(-textRect.topLeft())); doc.documentLayout()->draw(painter, paintContext); painter->restore(); }
1,696
C++
.cpp
46
32.456522
123
0.78244
cxasm/notepad--
5,942
234
284
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
25,171
findresultwin.cpp
cxasm_notepad--/src/findresultwin.cpp
#include "findresultwin.h" #include "findwin.h" #include "common.h" #include "styleset.h" #include "nddsetting.h" #include "findresultview.h" #include <qsciscintilla.h> #include <Scintilla.h> //#include <QTreeWidgetItem> //#include <QStyleFactory> //#include <QToolButton> //#include <qtreeview.h> //#include <QStandardItem> //#include <QStandardItemModel> #include <QClipboard> #include <QTextEdit> #include <qscrollbar.h> //目前可以高亮,使用富文本进行了高亮设置。但是有个问题:富文本与html有一些冲突,在<>存在时,可能导致乱。这是一个问题。20220609 //使用Html的转义解决了该问题 FindResultWin::FindResultWin(QWidget *parent) : QWidget(parent), m_menu(nullptr), m_parent(parent),m_defaultFontSize(14), m_defFontSizeChange(false) { ui.setupUi(this); connect(ui.displayView, &FindResultView::lineDoubleClick, this, &FindResultWin::on_lineDoubleClick); } FindResultWin::~FindResultWin() { if (m_defFontSizeChange) { NddSetting::updataKeyValueFromNumSets(FIND_RESULT_FONT_SIZE, m_defaultFontSize); } clear(); } void FindResultWin::clear() { for (int i = 0; i < m_resultLineFilePath.size(); ++i) { delete m_resultLineFilePath.at(i); } m_resultLineFilePath.clear(); m_resultLineInfo.clear(); } void FindResultWin::slot_clearAllContents() { clear(); ui.displayView->clear(); } #if 0 //老的机制,暂时屏蔽,后续可删除 //高亮查找的关键字文本。Index表示是第几次出现,前面的要跳过 void FindResultWin::highlightFindText(int index, QString &srcText, QString &findText, Qt::CaseSensitivity cs) { #if 0 int pos = 0; int findPos = 0; //先把< > 转义为因为会与原来的html标签冲突。这是一个很厉害的方法,如果不转义,会导致显示丢失 srcText = srcText.toHtmlEscaped(); findText = findText.toHtmlEscaped(); int lens = findText.size(); while (index > 0) { pos = srcText.indexOf(findText, findPos, cs); if (pos == -1) { //错误,不替换 return; } else { findPos = pos + lens; } index--; } srcText.replace(pos, lens, QString("<font style='font-size:14px;background-color:#ffffbf'>%1</font>").arg(srcText.mid(pos,lens))); #endif } #endif const int MAX_HEAD_LENTGH = 20; const int MAX_TAIL_LENGTH = 80; #if 0 //更复杂的高亮:在全词语匹配,大小写敏感,甚至正则表达式情况下,上面的highlightFindText是不够的。需要精确定位 QString FindResultWin::highlightFindText(FindRecord& record) { #if 0 QByteArray utf8bytes = record.lineContents.toUtf8(); int lineLens = utf8bytes.length(); bool isNeedCut = false; //行太长的进行缩短显示 if (lineLens > 300) { isNeedCut = true; } //高亮的开始、结束位置 int targetStart = record.pos - record.lineStartPos; int targetLens = record.end - record.pos; int tailStart = record.end - record.lineStartPos; QString head; QString src; QString tail; if (!StyleSet::isCurrentDeepStyle()) { if (!isNeedCut) { head = QString("<font style='font-size:14px;'>%1</font>").arg(QString(utf8bytes.mid(0, targetStart)).toHtmlEscaped()); src = QString("<font style='font-size:14px;background-color:#ffffbf'>%1</font>").arg(QString(utf8bytes.mid(targetStart, targetLens)).toHtmlEscaped()); tail = QString("<font style='font-size:14px;'>%1</font>").arg(QString(utf8bytes.mid(tailStart)).toHtmlEscaped()); } else { head = QString(utf8bytes.mid(0, targetStart)); if (head.size() > MAX_HEAD_LENTGH) { head = (head.mid(0, MAX_HEAD_LENTGH) + "...").toHtmlEscaped(); } else { head = head.toHtmlEscaped(); } head = QString("<font style='font-size:14px;'>%1</font>").arg(head); src = QString("<font style='font-size:14px;background-color:#ffffbf'>%1</font>").arg(QString(utf8bytes.mid(targetStart, targetLens)).toHtmlEscaped()); tail = QString(utf8bytes.mid(tailStart)); if (tail > MAX_TAIL_LENGTH) { tail = (tail.mid(0, MAX_TAIL_LENGTH) + "...").toHtmlEscaped(); } else { tail = tail.toHtmlEscaped(); } tail = QString("<font style='font-size:14px;'>%1</font>").arg(tail); } } else { if (!isNeedCut) { head = QString("<font style='font-size:14px;color:#dcdcdc'>%1</font>").arg(QString(utf8bytes.mid(0, targetStart)).toHtmlEscaped()); src = QString("<font style='font-size:14px;font-weight:bold;color:#ffaa00'>%1</font>").arg(QString(utf8bytes.mid(targetStart, targetLens)).toHtmlEscaped()); tail = QString("<font style='font-size:14px;color:#dcdcdc'>%1</font>").arg(QString(utf8bytes.mid(tailStart)).toHtmlEscaped()); } else { QString headContens = QString(utf8bytes.mid(0, targetStart)); if (headContens.size() > MAX_HEAD_LENTGH) { headContens = (headContens.mid(0, MAX_HEAD_LENTGH) + "...").toHtmlEscaped(); } else { headContens = headContens.toHtmlEscaped(); } head = QString("<font style='font-size:14px;color:#dcdcdc'>%1</font>").arg(headContens); src = QString("<font style='font-size:14px;font-weight:bold;color:#ffaa00'>%1</font>").arg(QString(utf8bytes.mid(targetStart, targetLens)).toHtmlEscaped()); QString tailContens = QString(utf8bytes.mid(tailStart)); if (tailContens > MAX_TAIL_LENGTH) { tailContens = (tailContens.mid(0, MAX_TAIL_LENGTH) + "...").toHtmlEscaped(); } else { tailContens = tailContens.toHtmlEscaped(); } tail = QString("<font style='font-size:14px;color:#dcdcdc'>%1</font>").arg(tailContens); } } return QString("%1%2%3").arg(head).arg(src).arg(tail); #endif return ""; } //在当前文件查找字段,结果是一个单一的FindRecords void FindResultWin::appendResultsToShow(FindRecords* record) { #if 0 if (record == nullptr) { return; } FindResultView* pDisplay = ui.displayView; QString findTitle = tr("Search \"%1\" (%2 hits)\n").arg(record->findText).arg(record->records.size()); //pDisplay->append(findTitle); pDisplay->insertAt(findTitle,0,0); pDisplay->SendScintilla(SCI_SETFOLDLEVEL, 0, (long)(0|SC_FOLDLEVELHEADERFLAG)); QStringList contents; for (int i = 0; i < record->records.size(); ++i) { FindRecord v = record->records.at(i); const QString & richText = v.lineContents; QString text; if (!StyleSet::isCurrentDeepStyle()) { text = tr("Line %1 : %2\n").arg(v.lineNum + 1).arg(richText); } else { text = tr("Line %1 : %2\n").arg(v.lineNum + 1).arg(richText); } contents.append(text); } pDisplay->insertAt(contents.join(""), 1, 0); for (int i = 0; i < record->records.size(); ++i) { pDisplay->SendScintilla(SCI_SETFOLDLEVEL, i+1, 1); } #endif #if 0 QString findTitle; findTitle = tr("<font style='font-size:14px;font-weight:bold;color:#343497'>Search \"%1\" (%2 hits)</font>").arg(record->findText.toHtmlEscaped()).arg(record->records.size()); QStandardItem* titleItem = new QStandardItem(findTitle); setItemBackground(titleItem, QColor(0xbbbbff)); m_model->insertRow(0, titleItem); titleItem->setData(QVariant(true), ResultItemRoot); int rowNum = m_model->rowCount(); //把其余的行收起来。把第一行张开 for (int i = 1; i < rowNum; ++i) { ui.resultTreeView->collapse(m_model->index(i, 0)); } ui.resultTreeView->expand(m_model->index(0, 0)); if (record->records.size() == 0) { return; } QString desc; if (!StyleSet::isCurrentDeepStyle()) { desc = tr("<font style='font-size:14px;font-weight:bold;color:#309730'>%1 (%2 hits)</font>").arg(record->findFilePath.toHtmlEscaped()).arg(record->records.size()); } else { desc = tr("<font style='font-size:14px;color:#99cc99'>%1 (%2 hits)</font>").arg(record->findFilePath.toHtmlEscaped()).arg(record->records.size()); } QStandardItem* descItem = new QStandardItem(desc); if (!StyleSet::isCurrentDeepStyle()) { setItemBackground(descItem, QColor(0xd5ffd5)); } else { setItemBackground(descItem, QColor(0x484848)); } titleItem->appendRow(descItem); descItem->setData(QVariant((qlonglong)record->pEdit), ResultItemEditor); descItem->setData(QVariant(record->findFilePath), ResultItemEditorFilePath); descItem->setData(QVariant(record->findText), ResultWhatFind); //描述行双击不响应 descItem->setData(QVariant(true), ResultItemDesc); for (int i =0 ; i < record->records.size(); ++i) { FindRecord v = record->records.at(i); QString richText = highlightFindText(v); QString text; if (!StyleSet::isCurrentDeepStyle()) { text = tr("<font style='font-size:14px;'>Line </font><font style='font-size:14px;color:#ff8040'>%1</font> : %2").arg(v.lineNum + 1).arg(richText); } else { text = tr("<font style='font-size:14px;color:#ffffff'>Line </font><font style='font-size:14px;color:#ff8040'>%1</font> : %2").arg(v.lineNum + 1).arg(richText); } QStandardItem* childItem = new QStandardItem(text); childItem->setData(QVariant(v.pos), ResultItemPos); childItem->setData(QVariant(v.end - v.pos), ResultItemLen); #if defined(Q_OS_MAC) childItem->setTextAlignment(Qt::AlignVCenter); #endif descItem->appendRow(childItem); } if (!record->records.isEmpty()) { ui.resultTreeView->expand(m_model->index(0, 0, m_model->index(0, 0))); } #endif } #endif void FindResultWin::appendResultsToShow(QVector<FindRecords*>* record, int hits, QString whatFind) { if (record == nullptr) { return; } if (this->isHidden()) { this->setVisible(true); } ResultLineInfo lineInfo; QString findTitle = tr("Search \"%1\" (%2 hits in %3 files)\n").arg(whatFind).arg(hits).arg(record->size()); FindResultView* pDisplay = ui.displayView; pDisplay->on_foldAll(); pDisplay->insertAt(findTitle, 0, 0); lineInfo.level = 0; m_resultLineInfo.insert(0,lineInfo); pDisplay->SendScintilla(SCI_SETFOLDLEVEL, 0, (long)(0 | SC_FOLDLEVELHEADERFLAG)); if (record->size() == 0) { return; } QStringList contents; QList<int> keyworkOffsetPos; QString text; QString linePrefix; int insertIndex = 1; for (int i = 0, count = record->size(); i < count; ++i) { FindRecords* pr = record->at(i); QString* pFilePath = new QString(pr->findFilePath); QString desc; if (!StyleSet::isCurrentDeepStyle()) { desc = tr(" %1 (%2 hits)\n").arg(pr->findFilePath).arg(pr->records.size()); } else { desc = tr(" %1 (%2 hits)\n").arg(pr->findFilePath).arg(pr->records.size()); } contents.append(desc); m_resultLineFilePath.append(pFilePath); lineInfo.level = 1; m_resultLineInfo.insert(insertIndex, lineInfo); ++insertIndex; for (int j = 0; j < pr->records.size(); ++j) { FindRecord v = pr->records.at(j); QString richText = v.lineContents; linePrefix = tr(" Line %1: ").arg(v.lineNum + 1); if (!StyleSet::isCurrentDeepStyle()) { text = tr("%1%2\n").arg(linePrefix).arg(richText); } else { text = tr("%1%2\n").arg(linePrefix).arg(richText); } contents.append(text); keyworkOffsetPos.append(linePrefix.toUtf8().size()); lineInfo.level = 2; lineInfo.resultPos = v.pos; lineInfo.resultEnd = v.end; lineInfo.pFilePath = pFilePath; m_resultLineInfo.insert(insertIndex, lineInfo); ++insertIndex; QCoreApplication::processEvents(QEventLoop::ExcludeUserInputEvents); } } pDisplay->insertAt(contents.join(""), 1, 0); int lineNum = 1; QList<int> destFileLineNum; for (int i = 0, count = record->size(); i < count; ++i) { FindRecords* pr = record->at(i); pDisplay->SendScintilla(SCI_SETFOLDLEVEL, lineNum, (long)(1 | SC_FOLDLEVELHEADERFLAG)); destFileLineNum.append(lineNum); ++lineNum; for (int j = 0; j < pr->records.size(); ++j) { pDisplay->SendScintilla(SCI_SETFOLDLEVEL, lineNum, (long)2| SC_FOLDLEVELBASE); ++lineNum; } } //着色 pDisplay->setLineBackColorStyle(0, STYLE_COLOUR_TITLE); for (int i = 0, count = destFileLineNum.size(); i < count; ++i) { pDisplay->setLineBackColorStyle(destFileLineNum.at(i), (StyleSet::isCurrentDeepStyle()? STYLE_DEEP_COLOUR_DEST_FILE:STYLE_COLOUR_DEST_FILE)); } //关键字高亮 //高亮的开始、结束位置 int targetStart = 0; int targetLens = 0; lineNum = 1; int lineOffsetPosIndex = 0; int lineOffsetPos = 0; QString lineNumStr = tr(" Line "); int skipLineNumOffset = lineNumStr.toUtf8().size(); for (int i = 0, count = record->size(); i < count; ++i) { FindRecords* pr = record->at(i); ++lineNum; for (int j = 0; j < pr->records.size(); ++j) { lineOffsetPos = keyworkOffsetPos.at(lineOffsetPosIndex); const FindRecord &v = pr->records.at(j); targetStart = v.pos - v.lineStartPos + lineOffsetPos; targetLens = v.end - v.pos; pDisplay->setLineColorStyle(lineNum, skipLineNumOffset, lineOffsetPos-skipLineNumOffset-2, STYLE_COLOUR_KEYWORD_HIGH); pDisplay->setLineColorStyle(lineNum, targetStart, targetLens, (StyleSet::isCurrentDeepStyle()? STYLE_DEEP_COLOUR_KEYWORD_HIGH:STYLE_COLOUR_KEYWORD_BACK_HIGH)); ++lineNum; ++lineOffsetPosIndex; } } pDisplay->SendScintilla(SCI_GOTOLINE, 0); } int FindResultWin::getDefaultFontSize() { return m_defaultFontSize; } void FindResultWin::setDefaultFontSize(int defSize) { m_defaultFontSize = defSize; } void FindResultWin::on_lineDoubleClick(int lineNum) { if (lineNum < m_resultLineInfo.size()) { const ResultLineInfo& lineInfo = m_resultLineInfo.at(lineNum); if (lineInfo.level == 2) { //文件定位到行 emit lineDoubleClicked(lineInfo.pFilePath, lineInfo.resultPos, lineInfo.resultEnd); } else if ((lineInfo.level == 0) || (lineInfo.level == 1)) { ui.displayView->SendScintilla(SCI_FOLDLINE, lineNum, SC_FOLDACTION_TOGGLE); } } }
14,066
C++
.cpp
414
28.623188
177
0.685402
cxasm/notepad--
5,942
234
284
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
25,172
findresultview.cpp
cxasm_notepad--/src/findresultview.cpp
#include "findresultview.h" #include "styleset.h" #include "findresultwin.h" #include "ctipwin.h" #include "Scintilla.h" #include <QClipboard> const int MARGE_FOLDER = 1; const int STYLE_COLOUR_TITLE = 1; const int STYLE_COLOUR_DEST_FILE = 2; const int STYLE_COLOUR_KEYWORD_HIGH = 3; const int STYLE_COLOUR_KEYWORD_BACK_HIGH = 4; const int STYLE_DEEP_COLOUR_KEYWORD_HIGH = 5; //深色模式下面的前景色 const int STYLE_DEEP_COLOUR_DEST_FILE = 6; static void getFoldColor(QColor& fgColor, QColor& bgColor, QColor& activeFgColor) { //这里看起来反了,但是实际代码就是如此 fgColor = StyleSet::s_global_style->fold.bgColor; bgColor = StyleSet::s_global_style->fold.fgColor; activeFgColor = StyleSet::s_global_style->fold_active.fgColor; } void FindResultView::setFoldColor(int margin, QColor fgClack, QColor bkColor, QColor foreActive) { SendScintilla(SCI_MARKERSETFORE, margin, fgClack); SendScintilla(SCI_MARKERSETBACK, margin, bkColor); SendScintilla(SCI_MARKERSETBACKSELECTED, margin, foreActive); } FindResultView::FindResultView(QWidget *parent) : QsciScintilla(parent) { //通过fold发现,尽量使用qscint的功能,因为他做了大量封装和简化 setFolding(BoxedTreeFoldStyle, MARGE_FOLDER); SendScintilla(SCI_SETMARGINWIDTHN, MARGE_FOLDER, 14); SendScintilla(SCI_MARKERSETFORE, SC_MARKNUM_FOLDERSUB, QColor(0xff,0,0)); setCaretLineVisible(true); SendScintilla(SCI_SETSCROLLWIDTHTRACKING, true); SendScintilla(SCI_SETCARETLINEBACK, StyleSet::s_global_style->current_line_background_color.bgColor); QColor foldfgColor = Qt::white, foldbgColor = Qt::gray, activeFoldFgColor = Qt::red; getFoldColor(foldfgColor, foldbgColor, activeFoldFgColor); setFoldMarginColors(StyleSet::s_global_style->fold_margin.fgColor, StyleSet::s_global_style->fold_margin.bgColor); setFoldColor(SC_MARKNUM_FOLDEROPEN, foldfgColor, foldbgColor, activeFoldFgColor); setFoldColor(SC_MARKNUM_FOLDER, foldfgColor, foldbgColor, activeFoldFgColor); setFoldColor(SC_MARKNUM_FOLDERSUB, foldfgColor, foldbgColor, activeFoldFgColor); setFoldColor(SC_MARKNUM_FOLDERTAIL, foldfgColor, foldbgColor, activeFoldFgColor); setFoldColor(SC_MARKNUM_FOLDEREND, foldfgColor, foldbgColor, activeFoldFgColor); setFoldColor(SC_MARKNUM_FOLDEROPENMID, foldfgColor, foldbgColor, activeFoldFgColor); setFoldColor(SC_MARKNUM_FOLDERMIDTAIL, foldfgColor, foldbgColor, activeFoldFgColor); SendScintilla(SCI_STYLESETSIZE, STYLE_DEFAULT, 12); if (!StyleSet::isCurrentDeepStyle()) { this->setPaper(StyleSet::s_global_style->default_style.bgColor); SendScintilla(SCI_STYLESETBACK, STYLE_COLOUR_TITLE, 0xffbbbb); SendScintilla(SCI_STYLESETBACK, STYLE_COLOUR_DEST_FILE, 0xd5ffd5); SendScintilla(SCI_STYLESETEOLFILLED, STYLE_COLOUR_TITLE, true); SendScintilla(SCI_STYLESETEOLFILLED, STYLE_COLOUR_DEST_FILE, true); SendScintilla(SCI_STYLESETFORE, STYLE_COLOUR_KEYWORD_HIGH, 0x4080ff); SendScintilla(SCI_STYLESETBACK, STYLE_COLOUR_KEYWORD_BACK_HIGH, 0xbfffff); } else { this->setColor(StyleSet::s_global_style->default_style.fgColor); this->setPaper(StyleSet::s_global_style->default_style.bgColor); //QColor& col = StyleSet::s_global_style->default_style.fgColor; //sptr_t fgLParam = (col.blue() << 16) | (col.green() << 8) | col.red(); QColor& col2 = StyleSet::s_global_style->default_style.bgColor; sptr_t bklParam = (col2.blue() << 16) | (col2.green() << 8) | col2.red(); SendScintilla(SCI_STYLESETBACK, STYLE_COLOUR_TITLE, 0xffbbbb); SendScintilla(SCI_STYLESETEOLFILLED, STYLE_COLOUR_TITLE, true); //SendScintilla(SCI_STYLESETFORE, STYLE_COLOUR_TITLE, fgLParam); SendScintilla(SCI_STYLESETBACK, STYLE_DEEP_COLOUR_DEST_FILE, bklParam); SendScintilla(SCI_STYLESETFORE, STYLE_DEEP_COLOUR_DEST_FILE, 0x99cc99); //SendScintilla(SCI_STYLESETFORE, STYLE_DEEP_COLOUR_DEST_FILE, fgLParam); //SendScintilla(SCI_STYLESETBOLD, STYLE_DEEP_COLOUR_DEST_FILE, 1);//这个无法生效。可能是qscint bug //文字要大一号,然后颜色是绿色 SendScintilla(SCI_STYLESETSIZE, STYLE_DEEP_COLOUR_DEST_FILE, 14); SendScintilla(SCI_STYLESETFORE, STYLE_DEEP_COLOUR_KEYWORD_HIGH, 0x00aaff); SendScintilla(SCI_STYLESETBACK, STYLE_DEEP_COLOUR_KEYWORD_HIGH, bklParam); //给行号使用 SendScintilla(SCI_STYLESETFORE, STYLE_COLOUR_KEYWORD_HIGH, 0x4080ff); SendScintilla(SCI_STYLESETBACK, STYLE_COLOUR_KEYWORD_HIGH, bklParam); } this->setReadOnly(true); m_resultWin = dynamic_cast<FindResultWin*>(parent); } FindResultView::~FindResultView() {} //设置行背景色 void FindResultView::setLineBackColorStyle(int line, int style) { int startPos = SendScintilla(SCI_POSITIONFROMLINE, line); int len = SendScintilla(SCI_LINELENGTH, line); SendScintilla(SCI_STARTSTYLING, startPos); SendScintilla(SCI_SETSTYLING, len, style); } //设置行前景色。line 行号,从相对行pos的位置开始 void FindResultView::setLineColorStyle(int line, int offsetPos, int length, int style) { int startPos = SendScintilla(SCI_POSITIONFROMLINE, line); SendScintilla(SCI_STARTSTYLING, startPos + offsetPos); SendScintilla(SCI_SETSTYLING, length, style); } void FindResultView::mouseDoubleClickEvent(QMouseEvent* /*e*/) { //QsciScintilla::mouseDoubleClickEvent(e); int line = 0; int index = 0; this->getCursorPosition(&line,&index); emit lineDoubleClick(line); } void FindResultView::contextUserDefineMenuEvent(QMenu* menu) { if (menu != nullptr) { //移动一下位置 QAction* pCopy = menu->findChild<QAction*>("copy"); if (pCopy != nullptr) { menu->removeAction(pCopy); } menu->addAction(tr("Fold All"), this, &FindResultView::on_foldAll); menu->addAction(tr("Expand All"), this, &FindResultView::on_expandAll); menu->addSeparator(); if (pCopy != nullptr) { menu->addAction(pCopy); } menu->addAction(tr("copy select line"), this, &FindResultView::on_copySelectLine); menu->addAction(tr("warp"), this, &FindResultView::on_warp); menu->addSeparator(); menu->addAction(tr("clear"), this, &FindResultView::on_clear); menu->addAction(tr("close"), this, &FindResultView::on_close); } menu->move(cursor().pos()); //让菜单显示的位置在鼠标的坐标上 menu->show(); } void FindResultView::on_foldAll() { for (int i = 0; i < m_resultWin->m_resultLineInfo.size(); ++i) { const ResultLineInfo& lineInfo = m_resultWin->m_resultLineInfo.at(i); //如果是1级别的行,则进行一个收起操作 if ((lineInfo.level == 1) || (lineInfo.level == 0)) { SendScintilla(SCI_FOLDLINE, i, (long)SC_FOLDACTION_CONTRACT); } } } void FindResultView::on_expandAll() { for (int i = 0; i < m_resultWin->m_resultLineInfo.size(); ++i) { const ResultLineInfo& lineInfo = m_resultWin->m_resultLineInfo.at(i); //如果是1级别的行,则进行一个收起操作 if ((lineInfo.level == 1) || (lineInfo.level == 0)) { SendScintilla(SCI_FOLDLINE, i, SC_FOLDACTION_EXPAND); } } } //复制选中的内容 //void FindResultView::on_copySelect() //{ // QString word = selectedText(); // if (!word.isEmpty()) // { // QClipboard* clipboard = QApplication::clipboard(); // clipboard->setText(word); // // CTipWin::showTips(this, tr("Copy to clipboard Finished!"), 1200,true); // } //} //复制选中行 void FindResultView::on_copySelectLine() { int startPos = SendScintilla(SCI_GETSELECTIONSTART); int endPos = SendScintilla(SCI_GETSELECTIONEND); int startLine = SendScintilla(SCI_LINEFROMPOSITION, startPos); int endLine = SendScintilla(SCI_LINEFROMPOSITION, endPos); int start = SendScintilla(SCI_POSITIONFROMLINE, startLine); int end = SendScintilla(SCI_POSITIONFROMLINE, endLine+1); char *dest = new char[end - start + 1]; dest[end - start] = '\0'; Sci_TextRange tr; tr.chrg.cpMin = static_cast<Sci_PositionCR>(start); tr.chrg.cpMax = static_cast<Sci_PositionCR>(end); tr.lpstrText = dest; this->SendScintilla(SCI_GETTEXTRANGE, 0, &tr); QString text(dest); QStringList lineText = text.split("\n"); QString selectConnect; for (int i = 0; i < lineText.size(); ++i) { const QString& t = lineText.at(i); int pos = t.indexOf(": "); if (pos != -1) { QString v = t.mid(pos + 2); selectConnect.append(v); selectConnect.append("\n"); } } QClipboard* clipboard = QApplication::clipboard(); clipboard->setText(selectConnect); //CTipWin::showTips(this, tr("Copy to clipboard Finished!"), 1200, true); } void FindResultView::on_clear() { this->clear(); m_resultWin->clear(); } void FindResultView::on_close() { m_resultWin->m_parent->close(); } void FindResultView::on_warp() { if (SC_WRAP_CHAR != wrapMode()) { this->setWrapMode(QsciScintilla::WrapCharacter); } else { this->setWrapMode(QsciScintilla::WrapNone); } }
8,847
C++
.cpp
224
35.120536
116
0.739063
cxasm/notepad--
5,942
234
284
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
25,173
markdownview.cpp
cxasm_notepad--/src/markdownview.cpp
#include "markdownview.h" MarkdownView::MarkdownView(QWidget *parent) : QMainWindow(parent) { ui.setupUi(this); } MarkdownView::~MarkdownView() { } void MarkdownView::viewMarkdown(QString& text) { ui.textEdit->setMarkdown(text); }
255
C++
.cpp
13
16.769231
47
0.751073
cxasm/notepad--
5,942
234
284
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
25,174
aboutndd.cpp
cxasm_notepad--/src/aboutndd.cpp
#include "aboutndd.h" AboutNdd::AboutNdd(QWidget *parent) : QWidget(parent) { ui.setupUi(this); ui.label->setOpenExternalLinks(true); // 隐藏最大化、最小化按钮 setWindowFlags(windowFlags() & ~Qt::WindowMinMaxButtonsHint); connect(ui.aboutPushButton, &QPushButton::clicked, this, &AboutNdd::onButtonOkayClicked); } AboutNdd::~AboutNdd() {} void AboutNdd::appendText(QString text) { ui.nddMsgText->appendPlainText(text); } void AboutNdd::onButtonOkayClicked() { close(); }
520
C++
.cpp
20
22
91
0.75
cxasm/notepad--
5,942
234
284
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
25,175
md5hash.cpp
cxasm_notepad--/src/md5hash.cpp
#include "md5hash.h" #include "ccnotepad.h" #include "ctipwin.h" #include <QCryptographicHash> #include <QFile> #include <QFileDialog> #include <QClipboard> Md5hash::Md5hash(QWidget *parent) : QWidget(parent), m_isFile(false) { ui.setupUi(this); m_btGroup.addButton(ui.md4RadioBt, 0); m_btGroup.addButton(ui.md5RadioBt, 1); m_btGroup.addButton(ui.sha1RadioBt, 2); m_btGroup.addButton(ui.sha256RadioBt, 4); m_btGroup.addButton(ui.sha3RadioBt, 12); m_btGroup.addButton(ui.kec256RadioBt, 8); #if (QT_VERSION <= QT_VERSION_CHECK(5,15,0)) connect(&m_btGroup, QOverload<int>::of(&QButtonGroup::buttonClicked), this, &Md5hash::on_methodIdChange); #else connect(&m_btGroup, &QButtonGroup::idClicked, this, &Md5hash::on_methodIdChange); #endif connect(ui.srcTextEdit,&QPlainTextEdit::textChanged,this,&Md5hash::on_hash); } Md5hash::~Md5hash() {} void Md5hash::slot_select() { QFileDialog fd(this, QString(), CCNotePad::s_lastOpenDirPath); fd.setFileMode(QFileDialog::ExistingFile); m_fileList.clear(); if (fd.exec() == QDialog::Accepted) //如果成功的执行 { m_fileList = fd.selectedFiles(); //返回文件列表的名称 if (!m_fileList.isEmpty()) { m_isFile = true; ui.srcTextEdit->setPlainText(m_fileList.join("\n")); } } else { fd.close(); } } void Md5hash::on_methodIdChange(int id) { on_hash(); } void Md5hash::on_hash() { QCryptographicHash::Algorithm method = QCryptographicHash::Md5; if (ui.md5RadioBt->isChecked()) { method = QCryptographicHash::Md5; } else if (ui.md4RadioBt->isChecked()) { method = QCryptographicHash::Md4; } else if (ui.sha1RadioBt->isChecked()) { method = QCryptographicHash::Sha1; } else if (ui.sha256RadioBt->isChecked()) { method = QCryptographicHash::Sha256; } else if (ui.sha3RadioBt->isChecked()) { method = QCryptographicHash::Sha3_256; } else if (ui.kec256RadioBt->isChecked()) { method = QCryptographicHash::Keccak_256; } //如果是文本 if (!m_isFile) { QString text = ui.srcTextEdit->toPlainText(); QByteArray data = text.toUtf8(); if (!text.isEmpty()) { QByteArray result = QCryptographicHash::hash(data, method); ui.hashTextEdit->setPlainText(result.toHex()); } } else { QCryptographicHash fileHash(method); QByteArray rs; QList<QByteArray> result; for (int i = 0; i < m_fileList.size(); ++i) { rs.clear(); QFile file(m_fileList.at(i)); if (file.open(QIODevice::ReadOnly)) { if (fileHash.addData(&file)) { rs = fileHash.result(); result.append(rs.toHex()); } else { result.append("Error Null"); } file.close(); } else { result.append("Error Null"); } } for (int i = 0; i < result.size(); ++i) { QString info = QString("File %1 cyp hash is \n%2").arg(m_fileList.at(i)).arg(QString(result.at(i))); ui.hashTextEdit->appendPlainText(info); } m_isFile = false; } } void Md5hash::on_copyClipboard() { if (!ui.hashTextEdit->toPlainText().isEmpty()) { QClipboard* clipboard = QApplication::clipboard(); clipboard->setText(ui.hashTextEdit->toPlainText()); CTipWin::showTips(this, tr("Copy to clipboard Finished!"), 1200); } }
3,319
C++
.cpp
131
21.320611
107
0.672756
cxasm/notepad--
5,942
234
284
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
25,176
hexcmprangewin.cpp
cxasm_notepad--/src/hexcmprangewin.cpp
#include "hexcmprangewin.h" #include <QLineEdit> #include <QMessageBox> HexCmpRangeWin::HexCmpRangeWin(QWidget *parent) : QDialog(parent), m_isCancel(true) { ui.setupUi(this); connect(ui.leftStartPos, &QLineEdit::textChanged, this, &HexCmpRangeWin::slot_asyncStartPos); connect(ui.leftCmpLens, &QLineEdit::textChanged, this, &HexCmpRangeWin::slot_asyncLenPos); } HexCmpRangeWin::~HexCmpRangeWin() { } void HexCmpRangeWin::slot_ok() { m_isCancel = false; close(); } //通过左边的值同步右边。右边不同步左边,加速用户输入 void HexCmpRangeWin::slot_asyncStartPos(const QString& text) { ui.rightStartPos->setText(text); } void HexCmpRangeWin::slot_asyncLenPos(const QString& text) { ui.rightCmpLens->setText(text); } //如果取消,则不返回任何有效范围值;错误值也是 const int MAX_CMP_LENS = 1024 * 1024 * 10; void HexCmpRangeWin::getRange(bool & isCancel, qint64 & leftStartPos, int & leftCmpLen, qint64 & rightStartPos, int & rightCmpLen) { isCancel = m_isCancel; if (isCancel) { return; } bool ok = false; bool ok1 = false; bool ok2 = false; bool ok3 = false; leftStartPos = ui.leftStartPos->text().toULongLong(&ok); leftCmpLen = ui.leftCmpLens->text().toInt(&ok1); rightStartPos = ui.rightStartPos->text().toULongLong(&ok2); rightCmpLen = ui.rightCmpLens->text().toInt(&ok3); if (!ok || !ok1 || !ok2 || !ok3) { isCancel = true; leftStartPos = -1; rightStartPos = -1; leftCmpLen = 0; rightCmpLen = 0; QMessageBox::warning(this, tr("Error"), tr("StartPos or cmpare lens value error.")); return; } if (leftCmpLen > MAX_CMP_LENS) { leftCmpLen = MAX_CMP_LENS; } if (rightCmpLen > MAX_CMP_LENS) { rightCmpLen = MAX_CMP_LENS; } }
1,767
C++
.cpp
63
23.936508
131
0.709259
cxasm/notepad--
5,942
234
284
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
25,177
QTreeWidgetSortItem.cpp
cxasm_notepad--/src/QTreeWidgetSortItem.cpp
#include "QTreeWidgetSortItem.h" #include "rcglobal.h" /* 自己重新实现一个QTreeWidgetSortItem,主要是为了重载函数的排序功能,不适应默认的名字排序,而是使用 * 每个项自带的tip字符串排序。这样做是因为对齐的时候,有些空白对齐项目,并没有名称,就会导致无法排序 */ int QTreeWidgetSortItem::s_sortType = 0; bool QTreeWidgetSortItem::s_syncOrder = false; QTreeWidgetSortItem::QTreeWidgetSortItem(int type):QTreeWidgetItem(type) { } QTreeWidgetSortItem::QTreeWidgetSortItem(const QStringList &strings, int type):QTreeWidgetItem(strings, type) { } QTreeWidgetSortItem::~QTreeWidgetSortItem() { } bool QTreeWidgetSortItem::operator<(const QTreeWidgetItem & other) const { if (s_sortType == 0) { if (!s_syncOrder) //按名称排序 { //目录最大,放在文件前面。都是目录则按照名称排序 if ((type() == RC_DIR) && (other.type() == RC_DIR)) { goto cmp_name; } else if ((type() == RC_DIR) && (other.type() != RC_DIR)) { return false; } else if ((type() != RC_DIR) && (other.type() == RC_DIR)) { return true; } cmp_name: QString a = this->data(0, Item_RelativePath).toString(); QString b = other.data(0, Item_RelativePath).toString(); return (a.compare(b, Qt::CaseInsensitive) > 0); } else { //同步序号,按序号进行排序 #if 0 if ((type() == RC_DIR) && (other.type() == RC_DIR)) { QString a = this->data(0, Item_RelativePath).toString(); QString b = other.data(0, Item_RelativePath).toString(); return !(a.compare(b, Qt::CaseInsensitive) > 0); } else if ((type() == RC_DIR) && (other.type() != RC_DIR)) { return true; } else if ((type() != RC_DIR) && (other.type() == RC_DIR)) { return false; } cmp_index: #endif //同步对方的操作。 int a = this->data(0, Item_Index).toInt(); int b = other.data(0, Item_Index).toInt(); return(a > b); } } else if (s_sortType == 1) //按大小排序 { //目录最大,放在文件前面。都是目录则按照名称排序 if ((type() == RC_DIR) && (other.type() == RC_DIR)) { qint64 a = this->data(0, DIR_ITEM_MAXSIZE_FILE).toULongLong(); qint64 b = other.data(0, DIR_ITEM_MAXSIZE_FILE).toULongLong(); return(a > b); #if 0 QString a = this->data(0, Item_RelativePath).toString(); QString b = other.data(0, Item_RelativePath).toString(); return (a.compare(b, Qt::CaseInsensitive) > 0); #endif } else if ((type() == RC_DIR) && (other.type() != RC_DIR)) { return false; } else if ((type() != RC_DIR) && (other.type() == RC_DIR)) { return true; } int leftSize = this->text(1).toInt(); int rightSize = other.text(1).toInt(); return(leftSize > rightSize); } else if (s_sortType == 2) //by 修改日期 { //目录最大,放在文件前面。都是目录则按照名称排序 if ((type() == RC_DIR) && (other.type() == RC_DIR)) { QString a = this->data(0, Item_RelativePath).toString(); QString b = other.data(0, Item_RelativePath).toString(); return (a.compare(b, Qt::CaseInsensitive) > 0); } else if ((type() == RC_DIR) && (other.type() != RC_DIR)) { return false; } else if ((type() != RC_DIR) && (other.type() == RC_DIR)) { return true; } QString a = this->text(2); QString b = other.text(2); return(a.compare(b, Qt::CaseInsensitive) > 0); } return false; }
3,557
C++
.cpp
115
23.504348
110
0.618905
cxasm/notepad--
5,942
234
284
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
25,178
pluginmgr.cpp
cxasm_notepad--/src/pluginmgr.cpp
#include "pluginmgr.h" #include "rcglobal.h" PluginMgr::PluginMgr(QWidget *parent, QList<NDD_PROC_DATA>& pluginList) : QMainWindow(parent) { ui.setupUi(this); ui.pluginTable->horizontalHeader()->setStretchLastSection(true); ui.pluginTable->horizontalHeader()->setSectionResizeMode(0, QHeaderView::ResizeToContents); ui.pluginTable->horizontalHeader()->setSectionResizeMode(3, QHeaderView::ResizeToContents); //ui.pluginTable->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch); init(pluginList); } PluginMgr::~PluginMgr() {} void PluginMgr::init(QList<NDD_PROC_DATA>& pluginList) { ui.pluginTable->clearContents(); ui.pluginTable->setRowCount(0); for (int i = 0; i < pluginList.size(); ++i) { ui.pluginTable->insertRow(i); NDD_PROC_DATA v = pluginList.at(i); ui.pluginTable->setItem(i, 0, new QTableWidgetItem(v.m_strPlugName)); ui.pluginTable->setItem(i, 1, new QTableWidgetItem(v.m_version)); ui.pluginTable->setItem(i, 2, new QTableWidgetItem(v.m_auther)); ui.pluginTable->setItem(i, 3, new QTableWidgetItem(v.m_strComment)); ui.pluginTable->setItem(i, 4, new QTableWidgetItem(v.m_strFilePath)); } } void PluginMgr::slot_openPluginDir() { QString strDir = qApp->applicationDirPath(); QString path = QString("%1/plugin").arg(strDir); showFileInExplorer(path); }
1,364
C++
.cpp
35
35.457143
93
0.745789
cxasm/notepad--
5,942
234
284
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
25,179
columnedit.cpp
cxasm_notepad--/src/columnedit.cpp
#include "columnedit.h" #include "scintillaeditview.h" ColumnEdit::ColumnEdit(QWidget *parent) : QWidget(parent), m_curEditWin(nullptr), m_editTabWidget(nullptr) { ui.setupUi(this); connect(ui.addPrefix, &QCheckBox::stateChanged, this, &ColumnEdit::slot_addPrefix); connect(ui.is16, &QRadioButton::clicked, this, &ColumnEdit::slot_bigChar); } ColumnEdit::~ColumnEdit() { } void ColumnEdit::slot_insertTextEnable(bool check) { if (check) { if (ui.numGroupBox->isChecked()) { ui.numGroupBox->setChecked(!check); } } } void ColumnEdit::slot_insertNumEnable(bool check) { if (check) { if (ui.textGroupBox->isChecked()) { ui.textGroupBox->setChecked(!check); } } } void ColumnEdit::slot_addPrefix(int s) { if (s == Qt::Checked) { ui.prefix->setEnabled(true); } else { ui.prefix->setEnabled(false); } } void ColumnEdit::slot_bigChar(bool isCheck) { ui.capital->setEnabled(isCheck); } //自动调整当前窗口的状态 QWidget* ColumnEdit::autoAdjustCurrentEditWin() { QWidget* pw = m_editTabWidget->currentWidget(); if (m_curEditWin != pw) { m_curEditWin = pw; } return pw; } void ColumnEdit::setTabWidget(QTabWidget *editTabWidget) { m_editTabWidget = editTabWidget; } void ColumnEdit::slot_ok() { autoAdjustCurrentEditWin(); ScintillaEditView* pEdit = dynamic_cast<ScintillaEditView*>(m_curEditWin); if (pEdit == nullptr || pEdit->isReadOnly()) { QApplication::beep(); return; } QString text; bool isNum = false; int numType = 10; int initNum = 0; int inc = ui.incNum->value(); int repeNum = ui.repeNum->value(); bool isAddPrefix = ui.addPrefix->isChecked(); QString prefix = ui.prefix->text(); bool isCapital = ui.capital->isChecked(); //是插入文本模式 if (ui.textGroupBox->isChecked()) { text = ui.inputText->text(); } else { isNum = true; text = ui.initNum->text(); bool ok = false; if (ui.is10->isChecked()) { numType = 10; } else if (ui.is16->isChecked()) { numType = 16; } else if (ui.is8->isChecked()) { numType = 8; } else if (ui.is2->isChecked()) { numType = 2; } int num = text.toInt(&ok, 10); initNum = num; if (ok) { text = QString::number(num, numType); if (isAddPrefix) { text = prefix + text; } } else { //这里要加个提示 QApplication::beep(); return; } } pEdit->execute(SCI_BEGINUNDOACTION); if (ui.textGroupBox->isChecked()) { if (pEdit->execute(SCI_SELECTIONISRECTANGLE) || pEdit->execute(SCI_GETSELECTIONS) > 1) { ColumnModeInfos colInfos = pEdit->getColumnModeSelectInfo(); std::sort(colInfos.begin(), colInfos.end(), SortInPositionOrder()); QByteArray bytes = text.toUtf8(); pEdit->columnReplace(colInfos, bytes); std::sort(colInfos.begin(), colInfos.end(), SortInSelectOrder()); pEdit->setMultiSelections(colInfos); return; } } else { if (pEdit->execute(SCI_SELECTIONISRECTANGLE) || pEdit->execute(SCI_GETSELECTIONS) > 1) { ColumnModeInfos colInfos = pEdit->getColumnModeSelectInfo(); // If there is no column mode info available, no need to do anything // If required a message can be shown to user, that select column properly or something similar if (colInfos.size() > 0) { std::sort(colInfos.begin(), colInfos.end(), SortInPositionOrder()); QByteArray bytes; if (isAddPrefix) { bytes = prefix.toUtf8(); } pEdit->columnReplace(colInfos, initNum, inc, repeNum, numType, isCapital, bytes); std::sort(colInfos.begin(), colInfos.end(), SortInSelectOrder()); pEdit->setMultiSelections(colInfos); } return; } } auto cursorPos = pEdit->execute(SCI_GETCURRENTPOS); auto cursorCol = pEdit->execute(SCI_GETCOLUMN, cursorPos); auto cursorLine = pEdit->execute(SCI_LINEFROMPOSITION, cursorPos); auto endPos = pEdit->execute(SCI_GETLENGTH); auto endLine = pEdit->execute(SCI_LINEFROMPOSITION, endPos); QByteArray lineData; int rn = repeNum; for (size_t i = cursorLine; i <= static_cast<size_t>(endLine); ++i) { auto lineBegin = pEdit->execute(SCI_POSITIONFROMLINE, i); auto lineEnd = pEdit->execute(SCI_GETLINEENDPOSITION, i); auto lineEndCol = pEdit->execute(SCI_GETCOLUMN, lineEnd); auto lineLen = lineEnd - lineBegin; lineData.resize(lineLen); Sci_TextRange lineText; lineText.chrg.cpMin = static_cast<Sci_Position>(lineBegin); lineText.chrg.cpMax = static_cast<Sci_Position>(lineEnd); lineText.lpstrText = lineData.data(); //获取原始行的内容 pEdit->SendScintilla(SCI_GETTEXTRANGE, 0, &lineText); if (lineEndCol < cursorCol) { QByteArray s_space(cursorCol - lineEndCol, ' '); lineData.append(s_space); lineData.append(text.toUtf8()); } else { int posAbs2Start = pEdit->execute(SCI_FINDCOLUMN, i, cursorCol); int posRelative2Start = posAbs2Start - lineBegin; lineData.insert(posRelative2Start, text.toUtf8()); } pEdit->SendScintilla(SCI_SETTARGETRANGE, lineBegin, lineEnd); pEdit->SendScintilla(SCI_REPLACETARGET, lineData.size(), lineData.data()); if (isNum) { --rn; if (rn > 0) { } else { rn = repeNum; initNum += inc; } if (numType != 16) { text = QString::number(initNum, numType); } else { if (isCapital) { text = QString::number(initNum, numType).toUpper(); } else { text = QString::number(initNum, numType); } } if (isAddPrefix) { text = prefix + text; } } } pEdit->execute(SCI_ENDUNDOACTION); }
5,754
C++
.cpp
226
20.995575
99
0.66957
cxasm/notepad--
5,942
234
284
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
25,180
hexrulewin.cpp
cxasm_notepad--/src/hexrulewin.cpp
#include "hexrulewin.h" HexRuleWin::HexRuleWin(int mode, int highlight, QWidget *parent): QWidget(parent), m_mode(mode), m_isHighlightBackgroud(highlight) { ui.setupUi(this); if (mode == 0) { ui.maxLcsMode->setChecked(true); } else { ui.byteCmpMode->setChecked(true); } ui.hightlightBack->setChecked((highlight == 0) ? false : true); } HexRuleWin::~HexRuleWin() { } void HexRuleWin::slot_okBt() { int nowMode = (ui.maxLcsMode->isChecked() ? 0 : 1); int highLight = (ui.hightlightBack->isChecked() ? 1 : 0); if ((nowMode != m_mode) || (highLight != m_isHighlightBackgroud)) { m_mode = nowMode; m_isHighlightBackgroud = highLight; emit modeChange(m_mode, m_isHighlightBackgroud); } close(); }
760
C++
.cpp
29
22.827586
131
0.683916
cxasm/notepad--
5,942
234
284
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
25,181
langextset.cpp
cxasm_notepad--/src/langextset.cpp
#include "langextset.h" #include "scintillaeditview.h" #include "extlexermanager.h" #include "ccnotepad.h" #include <qtablewidget.h> #include <QHeaderView> #include <QSettings> #include <QMessageBox> int ITEM_CHANGED = Qt::UserRole; int ITEM_LEX_ID = Qt::UserRole + 1; //对应的语法lexer的 ID int ITEM_LEX_EXT_OLD_VALUE = Qt::UserRole + 2; //对应的语法关联EXT文件的旧值 LangExtSet::LangExtSet(QWidget *parent) : QMainWindow(parent), m_isChanged(false) { ui.setupUi(this); ui.langTableWidget->horizontalHeader()->setSectionResizeMode(1, QHeaderView::ResizeToContents); initLangName(); connect(ui.langTableWidget, &QTableWidget::itemChanged, this, &LangExtSet::slot_itemChanged); connect(ui.langTableWidget, &QTableWidget::currentItemChanged, this, &LangExtSet::slot_currentItemChanged); } LangExtSet::~LangExtSet() {} void LangExtSet::initLangName() { int langId = 0; QMap<QString, QStringList> extLangMap; ExtLexerManager::getInstance()->getExtlistByLangTag(extLangMap); for (int i = 0; i <= L_TXT; ++i) { if (i == L_GLOBAL) { continue; } QsciLexer* pLexer = ScintillaEditView::createLexer(i); if (nullptr != pLexer) { QString langName = pLexer->lexerTag(); QTableWidgetItem* item = new QTableWidgetItem(langName); item->setFlags(item->flags() & ~Qt::ItemIsEditable); item->setData(ITEM_LEX_ID, QVariant(i)); ui.langTableWidget->insertRow(langId); ui.langTableWidget->setItem(langId, 0, item); QStringList extList; if (extLangMap.contains(langName)) { extList = extLangMap.value(langName); } QTableWidgetItem* item1 = new QTableWidgetItem(extList.join(',')); item1->setData(ITEM_CHANGED, QVariant(false)); //把旧值记起来,后面修改后对比实时修改内存中的改动 item1->setData(ITEM_LEX_EXT_OLD_VALUE, QVariant(extList)); ui.langTableWidget->setItem(langId, 1, item1); delete pLexer; ++langId; } } ui.langTableWidget->sortItems(0, Qt::AscendingOrder); } void LangExtSet::slot_itemChanged(QTableWidgetItem* item) { item->setData(ITEM_CHANGED, QVariant(true)); slot_currentItemChanged(item, nullptr); if (!m_isChanged) { m_isChanged = true; } } void LangExtSet::slot_currentItemChanged(QTableWidgetItem* current, QTableWidgetItem* previous) { if (current != nullptr) { int row = current->row(); QTableWidgetItem* tagItem = ui.langTableWidget->item(row, 0); QTableWidgetItem* extItem = ui.langTableWidget->item(row, 1); if (tagItem != nullptr && extItem != nullptr) { ui.plainTextEdit->setPlainText(tr("current lang: %1 \next file suffix is : %2\nDouble-click a column item to modify the syntax association file.").arg(tagItem->text()).arg(extItem->text())); } } } void LangExtSet::slot_save() { if (!m_isChanged) { ui.statusBar->showMessage(tr("Not change, no need save !"), 10000); return; } int rowNums = ui.langTableWidget->rowCount(); QString userLangFile = QString("notepad/tag_ext"); QSettings qs(QSettings::IniFormat, QSettings::UserScope, userLangFile); qs.setIniCodec("UTF-8"); for (int i = 0; i < rowNums; ++i) { QTableWidgetItem* item = ui.langTableWidget->item(i, 1); if (item != nullptr && item->data(ITEM_CHANGED).toBool()) { QTableWidgetItem* langItem = ui.langTableWidget->item(i, 0); if (langItem != nullptr) { QString langTag = langItem->text(); int lexId = langItem->data(ITEM_LEX_ID).toInt(); QStringList extList = item->text().split(','); for (int i = extList.size() - 1; i >= 0; --i) { if (extList.at(i).isEmpty()) { extList.removeAt(i); } } qs.setValue(langTag, extList); QString langLexerTag = QString("%1_lexId").arg(langTag); qs.setValue(langLexerTag, lexId); //上面是更新文件,下面是更新内存,让实时生效 QStringList oldExtList = item->data(ITEM_LEX_EXT_OLD_VALUE).toStringList(); updataExtLexerManager(langTag, lexId, oldExtList, extList); //更新新值。因为可能不关闭时再次修改 item->setData(ITEM_LEX_EXT_OLD_VALUE, QVariant(extList)); } } } qs.sync(); m_isChanged = false; ui.statusBar->showMessage(tr("Save Finished !"), 10000); } //更新ExtLexerManager中tag关联的值 void LangExtSet::updataExtLexerManager(QString tag, int lexId, QStringList & oldExtList, QStringList & newExtList) { //把旧的直接删除 for (int i = 0; i < oldExtList.size(); ++i) { ExtLexerManager::getInstance()->remove(oldExtList.at(i)); } //把新的重新加入一遍 for (int i = 0; i < newExtList.size(); ++i) { FileExtLexer v; v.ext = newExtList.at(i); v.id = (LangType)lexId; ExtLexerManager::getInstance()->addNewExtType(v.ext, v.id, tag); } } //加载文件的关联后缀到语法中 void LangExtSet::loadExtRelevanceToMagr() { QString userLangFile = QString("notepad/tag_ext");//自定义语言中不能有.字符,否则可能有错,后续要检查 QSettings qs(QSettings::IniFormat, QSettings::UserScope, userLangFile); qs.setIniCodec("UTF-8"); if (!QFile::exists(qs.fileName())) { return; } QStringList keylist = qs.allKeys(); QString langTag; QStringList extList; QString key_id; int lexid = 0; for (int i = 0; i < keylist.size(); ++i) { langTag = keylist.at(i); if (langTag.endsWith("_lexId")) { continue; } key_id = QString("%1_lexId").arg(langTag); extList = qs.value(langTag).toStringList(); lexid = qs.value(key_id).toInt(); for (int j = 0; j < extList.size(); ++j) { FileExtLexer v; v.ext = extList.at(j); v.id = (LangType)lexid; ExtLexerManager::getInstance()->addNewExtType(v.ext, v.id, langTag); } } } void LangExtSet::closeEvent(QCloseEvent* e) { if (m_isChanged) { if (QMessageBox::Yes == QMessageBox::question(this, tr("Save Change"), tr("Configuration has been modified. Do you want to save it?"))) { slot_save(); } } }
5,972
C++
.cpp
185
27.372973
194
0.688749
cxasm/notepad--
5,942
234
284
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
25,182
extLexermanager.cpp
cxasm_notepad--/src/extLexermanager.cpp
#include "extlexermanager.h" //专门用来管理用户自定义的Ext 和 词法Lexer关联的类。 //给出一个文件的ext后缀,快速告知该使用什么lexer进行语法高亮 ExtLexerManager* ExtLexerManager::s_instance = nullptr; ExtLexerManager::ExtLexerManager() { } ExtLexerManager * ExtLexerManager::getInstance() { if (s_instance == nullptr) { s_instance = new ExtLexerManager(); } return s_instance; } ExtLexerManager::~ExtLexerManager() { m_extToLexerIdMap.clear(); } int ExtLexerManager::size() { return m_extToLexerIdMap.size(); } bool ExtLexerManager::contains(QString ext) { return m_extToLexerIdMap.contains(ext); } void ExtLexerManager::remove(QString ext) { if (m_extToLexerIdMap.contains(ext)) { m_extToLexerIdMap.remove(ext); } } //ext:文件的后缀名 langTagName:语言的tag名称 //lexerId 语法的id,如果是用户自定义,则必然是L_USER_TXT,L_USER_CPP,L_USER_HTML,L_USER_JS,L_USER_XML, L_USER_INI 中的一个。 //langTagName:只有在用户定义语言下,才需要tagName。因为非用户定义的lexer,其tagname是固定的。 void ExtLexerManager::addNewExtType(QString ext, LangType lexerId, QString langTagName) { LexerInfo value(lexerId, langTagName); m_extToLexerIdMap.insert(ext,value); } bool ExtLexerManager::getLexerTypeByExt(QString ext, LexerInfo& lexer) { if (m_extToLexerIdMap.contains(ext)) { lexer = m_extToLexerIdMap[ext]; return true; } return false; } //列出tag语言下面的所有关联的文件后缀列表 void ExtLexerManager::getExtlistByLangTag(QString tag, QStringList& extList) { for (QMap<QString, LexerInfo>::iterator it = m_extToLexerIdMap.begin(); it != m_extToLexerIdMap.end(); ++it) { LexerInfo& v = it.value(); if (v.tagName == tag) { extList.append(it.key()); } } } //列出tag语言下面的所有关联的文件后缀列表 void ExtLexerManager::getExtlistByLangTag(QMap<QString,QStringList>& extLangMap) { for (QMap<QString, LexerInfo>::iterator it = m_extToLexerIdMap.begin(); it != m_extToLexerIdMap.end(); ++it) { LexerInfo& v = it.value(); if (extLangMap.contains(v.tagName)) { extLangMap[v.tagName].append(it.key()); } else { extLangMap[v.tagName] = QStringList(it.key()); } } }
2,210
C++
.cpp
79
22.987342
110
0.73582
cxasm/notepad--
5,942
234
284
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
25,183
Encode.cpp
cxasm_notepad--/src/Encode.cpp
#include "Encode.h" #include <QTextCodec> #include <QtDebug> /* 检查字符串编码的类。看了大量文献,结论如下: *如果是UTF BOM格式,或者UNICODE格式,其文件头部前几个字节(2-3)有一定的标识。由此标识直接按对应编码处理。 *如果没有标识,默认就是UTF8(NO BOM) 与 ANSI(现在只考虑GBK)进行对比。 *此时需要做统计分析。对所有行进行UTF8解析,如果按照UTF8解析错位再按照GBK解析。如果解析出GBK那么大概率认为文件是GBK编码的。 */ Encode::Encode() { } Encode::~Encode() { } CODE_ID Encode::getCodeByName(QString name) { CODE_ID id; if (name == "unknown") { id = CODE_ID::UNKOWN; } else if (name == "UTF16-LE") { id = CODE_ID::UNICODE_LE; } else if (name == "UTF16-BE") { id = CODE_ID::UNICODE_BE; } else if (name == "UTF8") { id = CODE_ID::UTF8_NOBOM; } else if (name == "UTF8-BOM") { id = CODE_ID::UTF8_BOM; } else if (name == "GBK") { id = CODE_ID::GBK; } else if (name == "EUC-JP") { id = CODE_ID::EUC_JP; } else if (name == "Shift-JIS") { id = CODE_ID::Shift_JIS; } else if (name == "EUC-KR") { id = CODE_ID::EUC_KR; } else if (name == "KOI8-R") { id = CODE_ID::KOI8_R; } else if (name == "TSCII") { id = CODE_ID::TSCII; } else if (name == "TIS-620") { id = CODE_ID::TIS_620; } else { id = CODE_ID::UNKOWN; } return id; } QString Encode::getLineEndById(RC_LINE_FORM id) { QString ret; switch (id) { case PAD_LINE: case UNKNOWN_LINE: #ifdef WIN32 ret = "Windows(CR LF)"; #else ret = "Unix(LF)"; #endif ret = "NULL"; break; case UNIX_LINE: ret = "Unix(LF)"; break; case DOS_LINE: ret = "Windows(CR LF)"; break; case MAC_LINE: ret = "Mac(CR)"; break; default: break; } return ret; } QString Encode::getCodeNameById(CODE_ID id) { QString ret; switch (id) { case UNKOWN: ret = "unknown"; break; case ANSI: ret = "unknown"; break; case UNICODE_LE: ret = "UTF16-LE"; break; case UNICODE_BE: ret = "UTF16-BE"; break; case UTF8_NOBOM: ret = "UTF8"; break; case UTF8_BOM: ret = "UTF8-BOM"; break; case GBK: ret = "GBK"; break; case EUC_JP: ret = "EUC-JP"; break; case Shift_JIS: ret = "Shift-JIS"; break; case EUC_KR: ret = "EUC-KR"; break; case KOI8_R: ret = "KOI8-R"; break; case TSCII: ret = "TSCII"; break; case TIS_620: ret = "TIS-620"; break; case BIG5: ret = "BIG5-HKSCS"; break; default: ret = "unknown"; break; } return ret; } QByteArray Encode::getEncodeStartFlagByte(CODE_ID code) { QByteArray ret; switch (code) { case UNICODE_LE: { ret.append((char)0xFF); ret.append((char)0xFE); } break; case UNICODE_BE: { ret.append((char)0xFE); ret.append((char)0xFF); } break; case UTF8_BOM: { ret.append((char)0xEF); ret.append((char)0xBB); ret.append((char)0xBF); } break; default: break; } return ret; } CODE_ID Encode::DetectEncode(const uchar* pBuffer, int length, int &skip) { if (pBuffer[0] == 0xFF && pBuffer[1] == 0xFE) { skip = 2; return CODE_ID::UNICODE_LE; //skip 2 } if (pBuffer[0] == 0xFE && pBuffer[1] == 0xFF) { skip = 2; return CODE_ID::UNICODE_BE; //skip 2 } if (pBuffer[0] == 0xEF && pBuffer[1] == 0xBB && pBuffer[2] == 0xBF) { skip = 3; return CODE_ID::UTF8_BOM; //skip 3 with BOM } // 不能知道是不是UTF8 CODE_ID code = CheckUnicodeWithoutBOM(pBuffer, length); skip = 0; return code; //skip 0 } bool Encode::tranGbkToUNICODE(const char* pText, int length, QString &out) { QTextCodec::ConverterState state; QTextCodec *codec = QTextCodec::codecForName("GBK"); out = codec->toUnicode((const char *)pText, length, &state); if (state.invalidChars > 0) { return false; } return true; } bool Encode::tranUtf8ToUNICODE(const char* pText, int length, QString &out) { QTextCodec::ConverterState state; QTextCodec *codec = QTextCodec::codecForName("UTF-8"); out = codec->toUnicode((const char *)pText, length, &state); if (state.invalidChars > 0) { return false; } return true; } //与getCodeNameById类似,但是返回的是QT系统支持的编码的字符串名称 QString Encode::getQtCodecNameById(CODE_ID id) { QString ret; switch (id) { case UNKOWN: case ANSI: ret = "unknown"; break; case UNICODE_LE: ret = "UTF16-LE"; break; case UNICODE_BE: ret = "UTF16-BE"; break; case UTF8_NOBOM://qt没有这种 case UTF8_BOM: ret = "UTF8"; break; case GBK: ret = "GBK"; break; case EUC_JP: ret = "EUC-JP"; break; case Shift_JIS: ret = "Shift-JIS"; break; case EUC_KR: ret = "EUC-KR"; break; case KOI8_R: ret = "KOI8-R"; break; case TSCII: ret = "TSCII"; break; case TIS_620: ret = "TIS-620"; break; case BIG5: ret = "Big5-HKSCS"; break; default: ret = "unknown"; break; } return ret; } //将指定编码的字符串转换到unicode bool Encode::tranStrToUNICODE(CODE_ID code, const char* pText, int length, QString &out) { if (length < 0) { return false; } QTextCodec::ConverterState state; QTextCodec *codec = nullptr; QString textCodeName = getQtCodecNameById(code); if (textCodeName.isEmpty() || textCodeName == "unknown") { //对于其它非识别编码,统一转换为utf8。减去让用户选择的麻烦 //这里其实是有问题的。先这样简单处理 codec = QTextCodec::codecForName("UTF-8"); } else { codec = QTextCodec::codecForName(textCodeName.toStdString().c_str()); } if (codec == nullptr) { return false; } out = codec->toUnicode((const char *)pText, length, &state); if (state.invalidChars > 0) { return false; } return true; } /* 这里其实是穷举字符串的字符编码;ASNI utf8。目前只检测GBK和utf8;其它语种没有穷举 *GB2312 GBK GB18030 三种差别见https://cloud.tencent.com/developer/article/1343240 *关于编码的详细说明,见https://blog.csdn.net/libaineu2004/article/details/19245205 */ //这里是有限检查utf8的,如果出现gbk,说明一定不是utf8,因为utf8检查到错误码。 CODE_ID Encode::CheckUnicodeWithoutBOM(const uchar* pText, int length) { QTextCodec::ConverterState state; QTextCodec *codec = QTextCodec::codecForName("UTF-8"); const QString text = codec->toUnicode((const char *)pText, length, &state); if (state.invalidChars > 0) { /*不是UTF-8格式的文件,这里优先判断是不是UTF8,再判断是不是GBK;我们先做中文版;如果后续要做 *国际版,其实不应该只检查GBK,而是应该检查本地ASCI码,包括ascii码*/ QTextCodec::ConverterState state1; QTextCodec *codec1 = QTextCodec::codecForName("GBK"); codec1->toUnicode((const char *)pText, length, &state1); if (state1.invalidChars > 0) { return CODE_ID::ANSI; } else { return CODE_ID::GBK; } } return CODE_ID::UTF8_NOBOM; } CODE_ID Encode::CheckUnicodeWithoutBOM(const uchar* pText, int length, QString &outUnicodeText) { QTextCodec::ConverterState state; QTextCodec *codec = QTextCodec::codecForName("UTF-8"); outUnicodeText = codec->toUnicode((const char *)pText, length, &state); if (state.invalidChars > 0) { /*不是UTF-8格式的文件,这里优先判断是不是UTF8,再判断是不是GBK;我们先做中文版;如果后续要做 *国际版,其实不应该只检查GBK,而是因为检查本地ASCI码,包括ascii码*/ QTextCodec::ConverterState state1; QTextCodec *codec1 = QTextCodec::codecForName("GBK"); QString gbkStr = codec1->toUnicode((const char *)pText, length, &state1); if (state1.invalidChars > 0) { //如果也不是gbk,姑且按照utf8直接返回 return CODE_ID::ANSI; } else { outUnicodeText = gbkStr; return CODE_ID::GBK; } } return CODE_ID::UTF8_NOBOM; } //检查是否全是ascii字符码 bool Encode::CheckTextIsAllAscii(const uchar* pText, int length) { for (int i = 0; i < length; ++i) { if (*(pText + i) < 0 || *(pText + i) > 0x7F) { return false; } } return true; }
8,452
C++
.cpp
364
17.184066
96
0.651179
cxasm/notepad--
5,942
234
284
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
25,184
findcmpwin.cpp
cxasm_notepad--/src/findcmpwin.cpp
#include "findcmpwin.h" #include "qscidisplaywindow.h" #include <QRadioButton> #include <QMessageBox> FindCmpWin::FindCmpWin(RC_DIRECTION dir, QWidget *parent):QMainWindow(parent), m_editWidget(nullptr), m_isFindFirst(true), m_findHistory(nullptr) { ui.setupUi(this); m_BackwardDir = false; m_matchWhole = false; m_matchCase = false; m_matchWrap = true; m_searchMode = 1; if (dir == RC_LEFT) { ui.leftSearch->setChecked(true); } else { ui.rightSearch->setChecked(true); } connect(ui.leftSearch, &QRadioButton::toggled, this, &FindCmpWin::slot_isSearchLeft); connect(ui.findModeRegularBt, &QRadioButton::toggled, this, &FindCmpWin::slot_findModeRegularBtChange); } FindCmpWin::~FindCmpWin() { } void FindCmpWin::slot_isSearchLeft(bool checked) { emit sgin_searchDirectionChange(checked ? RC_LEFT : RC_RIGHT); } void FindCmpWin::setCurrentTab(FindTabIndex index) { ui.findinfilesTab->setCurrentIndex(index); if (FIND_TAB == index) { ui.findComboBox->setFocus(); } } void FindCmpWin::setWorkEdit(QsciDisplayWindow *editWidget) { m_editWidget = editWidget; m_isFindFirst = true; } void FindCmpWin::setFindText(QString &text) { ui.findComboBox->setEditText(text); } void FindCmpWin::setFindHistory(QList<QString>* findHistory) { m_findHistory = findHistory; if ((m_findHistory != nullptr) && !m_findHistory->isEmpty()) { ui.findComboBox->addItems(*m_findHistory); ui.findComboBox->clearEditText(); } } //从ui读取参数配置到成员变量 void FindCmpWin::updateParameterFromUI() { if (ui.findinfilesTab->currentIndex() == 0) { int searchMode = 0; if (ui.findModeNormalBt->isChecked()) { searchMode = 1; } else if (ui.findModeRegularBt->isChecked()) { searchMode = 2; } if (m_searchMode != searchMode) { m_searchMode = searchMode; m_isFindFirst = true; } if (m_expr != ui.findComboBox->currentText()) { m_expr = ui.findComboBox->currentText(); m_isFindFirst = true; } if (m_BackwardDir != ui.findBackwardBox->isChecked()) { m_BackwardDir = ui.findBackwardBox->isChecked(); m_isFindFirst = true; } if (m_matchWhole != ui.findMatchWholeBox->isChecked()) { m_matchWhole = ui.findMatchWholeBox->isChecked(); m_isFindFirst = true; } if (m_matchCase != ui.findMatchCaseBox->isChecked()) { m_matchCase = ui.findMatchCaseBox->isChecked(); m_isFindFirst = true; } if (m_matchWrap != ui.findWrapBox->isChecked()) { m_matchWrap = ui.findWrapBox->isChecked(); m_isFindFirst = true; } } m_re = ((m_searchMode == 2) ? true : false); if (m_cs != m_matchCase) { m_cs = m_matchCase; } if (m_wo != m_matchWhole) { m_wo = m_matchWhole; } if (m_wrap != m_matchWrap) { m_wrap = m_matchWrap; } m_forward = !m_BackwardDir; } void FindCmpWin::addFindHistory(QString &text) { if ((m_findHistory != nullptr) && (-1 == m_findHistory->indexOf(text))) { m_findHistory->push_front(text); ui.findComboBox->insertItem(0, text); } } //检查是否是第一次查找,凡是参数变化了,则认定为是第一次查找。 //因为查找分firstFirst和firstNext,则是qscint特性决定的。所以正确识别第一次查找是必要的 bool FindCmpWin::isFirstFind() { return m_isFindFirst; } //一旦修改条件发生变化,则认定为第一次查找 void FindCmpWin::slot_findNext() { if (ui.findComboBox->currentText().isEmpty()) { ui.statusbar->showMessage(tr("what find is null !"), 3000); return; } updateParameterFromUI(); QsciDisplayWindow* pEdit = m_editWidget; //第一次查找 if (isFirstFind()) { if (pEdit != nullptr) { QString whatFind = ui.findComboBox->currentText(); if (!pEdit->findFirst(whatFind, m_re, m_cs, m_wo, m_wrap, m_forward)) { ui.statusbar->showMessage(tr("cant't find text \'%1\'").arg(m_expr),3000); } m_isFindFirst = false; //加入历史列表 addFindHistory(whatFind); } } else { //查找下一个 if (pEdit != nullptr) { if (!pEdit->findNext()) { ui.statusbar->showMessage(tr("no more find text \'%1\'").arg(m_expr),3000); } } } } // //void FindCmpWin::addCurFindRecord(QsciDisplayWindow* pEdit, FindCmpRecords& recordRet) //{ // int pos = pEdit->execute(SCI_GETCURRENTPOS); // int lineNum = pEdit->execute(SCI_LINEFROMPOSITION, pos); // int lineLens = pEdit->execute(SCI_LINELENGTH, lineNum); // // char* lineText = new char[lineLens + 1]; // memset(lineText, 0, lineLens + 1); // pEdit->execute(SCI_GETCURLINE, lineLens, reinterpret_cast<sptr_t>(lineText)); // // FindCmpRecord aRecord; // aRecord.lineNum = lineNum; // aRecord.pos = pos; // aRecord.lineContents = QString(lineText); // // delete[]lineText; // // recordRet.records.append(aRecord); //} void FindCmpWin::slot_findModeRegularBtChange(bool checked) { if (checked) { ui.findBackwardBox->setEnabled(false); ui.findBackwardBox->setChecked(false); ui.findMatchWholeBox->setEnabled(false); ui.findMatchWholeBox->setChecked(false); } else { ui.findBackwardBox->setEnabled(true); ui.findMatchWholeBox->setEnabled(true); } m_isFindFirst = true; }
5,348
C++
.cpp
203
21.674877
146
0.688467
cxasm/notepad--
5,942
234
284
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
25,185
filelistview.cpp
cxasm_notepad--/src/filelistview.cpp
#include "filelistview.h" #include "rcglobal.h" #include "ccnotepad.h" #include <QListWidgetItem> #include <QMenu> //当显示文件多了以后,把所有文件列在该列表中 FileListView::FileListView(QWidget *parent) : QWidget(parent), m_pNotepad(nullptr) { ui.setupUi(this); connect(ui.filelistWidget, &QListWidget::itemDoubleClicked, this, &FileListView::itemDoubleClicked); setContextMenuPolicy(Qt::CustomContextMenu); //设置枚举值 connect(this, &QListWidget::customContextMenuRequested, this, &FileListView::slot_ShowPopMenu); } FileListView::~FileListView() { m_fileEditMap.clear(); } void FileListView::setNotepadWin(QWidget* pNotepad) { m_pNotepad = pNotepad; } //右键菜单 void FileListView::slot_ShowPopMenu(const QPoint& pos) { QListWidgetItem* curItem = ui.filelistWidget->itemAt(pos); if (curItem != nullptr) { QMenu* menu = new QMenu(this); QAction* actionAdd = menu->addAction(tr("Show File in Explorer"), this, [&]() { showFileInExplorer(curItem->text()); }); menu->addAction(tr("Close File"), this, [&]() { QString filePath = curItem->text(); if (m_fileEditMap.contains(filePath)) { CCNotePad* pNotePad = dynamic_cast<CCNotePad*>(m_pNotepad); if (m_pNotepad != nullptr) { pNotePad->closeFileByEditWidget(m_fileEditMap.value(curItem->text()).pEditWidget); } //注意这里不需要在删除m_fileEditMap元素,因为closeFileByEditWidget里面会调用。 } }); //没有名称表示是对齐的item,不存在对应的文件,只是占位 if (curItem->text().isEmpty()) { actionAdd->setEnabled(false); } if (menu) { menu->setAttribute(Qt::WA_DeleteOnClose); menu->exec(QCursor::pos()); } } } void FileListView::delFileItem(QString & filePath) { if (m_fileEditMap.contains(filePath)) { m_fileEditMap.remove(filePath); QList<QListWidgetItem*> items = ui.filelistWidget->findItems(filePath, Qt::MatchFixedString); if (!items.isEmpty()) { delete items.at(0); } } } QWidget* FileListView::getWidgetByFilePath(QString filePath) { if (m_fileEditMap.contains(filePath)) { return m_fileEditMap.value(filePath).pEditWidget; } return nullptr; } void FileListView::setCurItem(QString filePath) { if (m_fileEditMap.contains(filePath)) { ui.filelistWidget->setCurrentItem(m_fileEditMap.value(filePath).pListItem); } } void FileListView::addFileItem(QString& filePath, QWidget* edit) { if (!m_fileEditMap.contains(filePath)) { QListWidgetItem* newItem = new QListWidgetItem(filePath); ui.filelistWidget->addItem(newItem); m_fileEditMap.insert(filePath, FileListItemData(edit, newItem)); } }
2,697
C++
.cpp
92
24.673913
102
0.722804
cxasm/notepad--
5,942
234
284
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
25,186
batchfindreplace.cpp
cxasm_notepad--/src/batchfindreplace.cpp
#include "batchfindreplace.h" #include "scintillaeditview.h" #include "ccnotepad.h" #include "progresswin.h" #include "nddsetting.h" #include "ctipwin.h" #include <QTableWidgetItem> #include <QFileDialog> BatchFindReplace::BatchFindReplace(QWidget *parent) : QMainWindow(parent), m_curEditWin(nullptr), m_editTabWidget(nullptr) { ui.setupUi(this); m_mainNotepad = dynamic_cast<CCNotePad*>(parent); } BatchFindReplace::~BatchFindReplace() { } void BatchFindReplace::closeEvent(QCloseEvent* event) { QByteArray curGeo = this->saveGeometry(); NddSetting::updataWinPos(BATCH_FIND_REPLACE_POS, curGeo); } void BatchFindReplace::setTabWidget(QTabWidget* editTabWidget) { m_editTabWidget = editTabWidget; } //自动调整当前窗口的状态,如果发生了变化,则需要认定为是首次查找 QWidget* BatchFindReplace::autoAdjustCurrentEditWin() { QWidget* pw = m_editTabWidget->currentWidget(); if (m_curEditWin != pw) { m_curEditWin = pw; } return pw; } void BatchFindReplace::appendToFindTable(QString findKeyword) { int rNum = ui.findReplaceTable->rowCount(); ui.findReplaceTable->insertRow(rNum); QTableWidgetItem* itemFind = new QTableWidgetItem(findKeyword); ui.findReplaceTable->setItem(rNum, 0, itemFind); ui.findReplaceTable->setItem(rNum, 1, new QTableWidgetItem()); } //这里不能追加,而是插入,即对应的Item必须已经存在。否则不插入 void BatchFindReplace::insertToReplaceTable(int row, QString replaceKeyword) { QTableWidgetItem* item = ui.findReplaceTable->item(row, 1); if (item == nullptr) { ui.statusBar->showMessage(tr("$1 has no find match work item").arg(replaceKeyword)); return; } item->setText(replaceKeyword); } void BatchFindReplace::insertToFindReplaceTable(QStringList& replaceKeyword) { for (int i = 0; i < replaceKeyword.size(); ++i) { insertToReplaceTable(i, replaceKeyword.at(i)); } } void BatchFindReplace::appendToFindReplaceTable(QStringList& findKeyword) { if (findKeyword.isEmpty()) { return; } int rNum = ui.findReplaceTable->rowCount(); for (int i = 0; i < findKeyword.size(); ++i) { int curRow = rNum + i; ui.findReplaceTable->insertRow(curRow); QTableWidgetItem* itemFind = new QTableWidgetItem(findKeyword.at(i)); ui.findReplaceTable->setItem(curRow, 0, itemFind); ui.findReplaceTable->setItem(curRow, 1, new QTableWidgetItem()); } } bool BatchFindReplace::tranInputKeyword(QString& findKeyWord, QStringList& outputKeyWordList) { //把空白字符,空格或者\t \r\n 等字符进行替换为空格 QRegExp re("\\s"); findKeyWord.replace(re, QString(" ")); //再进行空格分隔处理 outputKeyWordList = findKeyWord.split(" "); if (outputKeyWordList.size() > 20000) { ui.statusBar->showMessage(tr("Max find key word 20000 !"), 10000); return false; } //删除每一个空的元素 for (int i = outputKeyWordList.size() - 1; i >= 0; --i) { if (outputKeyWordList[i].trimmed().isEmpty()) { outputKeyWordList.removeAt(i); } } if (outputKeyWordList.isEmpty()) { return false; } return true; } void BatchFindReplace::on_freshBtClick() { QStringList findWordList; QString findKeyWord = ui.findKeywordEdit->toPlainText(); if (findKeyWord.isEmpty()) { ui.statusBar->showMessage(tr("Please input find keyword !"),10000); if (ui.findReplaceTable->rowCount() > 0) { ui.findReplaceTable->clearContents(); ui.findReplaceTable->setRowCount(0); } return; } if (!tranInputKeyword(findKeyWord, findWordList)) { return; } else { ui.findReplaceTable->clearContents(); ui.findReplaceTable->setRowCount(0); appendToFindReplaceTable(findWordList); } QStringList replaceWordList; QString replaceKeyWord = ui.replaceKeywordEdit->toPlainText(); if (!tranInputKeyword(replaceKeyWord, replaceWordList)) { return; } else { insertToFindReplaceTable(replaceWordList); } } //进行批量查找工作 void BatchFindReplace::on_findBtClick() { if (m_mainNotepad != nullptr && m_mainNotepad) { int rowNums = ui.findReplaceTable->rowCount(); if (rowNums == 0) { CTipWin::showTips(this, tr("Please fresh first !"), 1200); return; } int foundTimes = 0; QStringList findKeyList; for (int i = 0; i < rowNums; ++i) { QTableWidgetItem* item = ui.findReplaceTable->item(i, 0); if (item != nullptr && !item->text().isEmpty()) { findKeyList.append(item->text()); } } foundTimes = m_mainNotepad->findAtBack(findKeyList); ui.statusBar->showMessage(tr("Batch Find Finished! total %1 found.").arg(foundTimes),10000); } } //进行批量替换工作 void BatchFindReplace::on_replaceBtClick() { if (m_mainNotepad != nullptr) { int rowNums = ui.findReplaceTable->rowCount(); if (rowNums == 0) { CTipWin::showTips(this, tr("Please fresh first !"), 1200); return; } QStringList findKeyList; QStringList replaceKeyList; for (int i = 0; i < rowNums; ++i) { QTableWidgetItem* item = ui.findReplaceTable->item(i, 0); if (item != nullptr && !item->text().isEmpty()) { QTableWidgetItem* replaceItem = ui.findReplaceTable->item(i, 1); if (replaceItem != nullptr) { if (item->text() != replaceItem->text()) { findKeyList.append(item->text()); replaceKeyList.append(replaceItem->text()); } } } } m_mainNotepad->replaceAtBack(findKeyList, replaceKeyList); ui.statusBar->showMessage(tr("Batch Replace Finished, total Replace %1 times !").arg(findKeyList.size()), 10000); } } void BatchFindReplace::on_swapFindReplace() { QString findText = ui.findKeywordEdit->toPlainText(); QString replaceText = ui.replaceKeywordEdit->toPlainText(); ui.findKeywordEdit->setPlainText(replaceText); ui.replaceKeywordEdit->setPlainText(findText); on_freshBtClick(); } void BatchFindReplace::on_export() { QString filter("Text files (*.txt);;All types(*.*)"); QString fileName = QFileDialog::getSaveFileName(this, tr("Save File As ..."), QString(), filter); if (!fileName.isEmpty()) { QSettings setting(fileName, QSettings::IniFormat); setting.setIniCodec("UTF-8"); int rowNums = ui.findReplaceTable->rowCount(); QStringList findList; QStringList replaceList; for (int i = 0; i < rowNums; ++i) { QTableWidgetItem* item = ui.findReplaceTable->item(i, 0); if (item != nullptr && !item->text().isEmpty()) { QTableWidgetItem* replaceItem = ui.findReplaceTable->item(i, 1); if (replaceItem != nullptr) { findList.append(item->text()); replaceList.append(replaceItem->text()); } } } if (!findList.isEmpty()) { setting.setValue("find", findList); setting.setValue("replace", replaceList); ui.statusBar->showMessage(tr("Export File finished !"), 10000); } else { ui.statusBar->showMessage(tr("No Content to Export !"), 10000); } } } void BatchFindReplace::on_import() { QFileDialog fd(this, QString(), CCNotePad::s_lastOpenDirPath); fd.setFileMode(QFileDialog::ExistingFile); if (fd.exec() == QDialog::Accepted) //如果成功的执行 { QStringList fileNameList = fd.selectedFiles(); //返回文件列表的名称 QFileInfo fi(fileNameList[0]); QSettings setting(fi.filePath(), QSettings::IniFormat); setting.setIniCodec("UTF-8"); ui.findKeywordEdit->setPlainText(setting.value("find").toStringList().join(" ")); ui.replaceKeywordEdit->setPlainText(setting.value("replace").toStringList().join(" ")); on_freshBtClick(); } else { fd.close(); } } void BatchFindReplace::on_mark() { if (m_mainNotepad != nullptr) { int rowNums = ui.findReplaceTable->rowCount(); if (rowNums == 0) { CTipWin::showTips(this, tr("Please fresh first !"), 1200); return; } int markTimes = 0; QStringList findKeyList; for (int i = 0; i < rowNums; ++i) { QTableWidgetItem* item = ui.findReplaceTable->item(i, 0); if (item != nullptr && !item->text().isEmpty()) { findKeyList.append(item->text()); } } markTimes = m_mainNotepad->markAtBack(findKeyList); ui.statusBar->showMessage(tr("Batch Mark Finished, total Mark %1 times !").arg(markTimes), 10000); } } void BatchFindReplace::on_clearMark() { if (m_mainNotepad != nullptr) { m_mainNotepad->slot_clearMark(); } }
8,439
C++
.cpp
291
24.676976
116
0.699797
cxasm/notepad--
5,942
234
284
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
25,187
mytreeview.cpp
cxasm_notepad--/src/mytreeview.cpp
#include "mytreeview.h" MyTreeView::MyTreeView(QWidget *parent) : QTreeView(parent) {} MyTreeView::~MyTreeView() {} void MyTreeView::getSelectedIndexes(QModelIndexList & selectList) { selectList = this->selectedIndexes(); }
242
C++
.cpp
10
21.4
66
0.761062
cxasm/notepad--
5,942
234
284
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
25,188
donate.cpp
cxasm_notepad--/src/donate.cpp
#include "donate.h" Donate::Donate(QWidget *parent): QWidget(parent) { ui.setupUi(this); } Donate::~Donate() { }
131
C++
.cpp
8
13.125
49
0.675439
cxasm/notepad--
5,942
234
284
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
25,189
ctipwin.cpp
cxasm_notepad--/src/ctipwin.cpp
#include "ctipwin.h" #include <QTimer> CTipWin::CTipWin(QWidget *parent) : QWidget(parent) { ui.setupUi(this); this->setWindowFlags(Qt::ToolTip); QPalette palette(this->palette()); palette.setColor(QPalette::Window, QColor(0xfff29d)); this->setPalette(palette); } CTipWin::~CTipWin() { } void CTipWin::setTipText(QString text) { ui.labelInfo->setText(text); } void CTipWin::showMsg(int sec) { show(); QTimer::singleShot(sec, this, SLOT(slot_delayClose())); } void CTipWin::slot_delayClose() { close(); } void CTipWin::showTips(QWidget* parent, QString text, int sec, bool isMousePos) { if (parent != nullptr) { CTipWin* pWin = new CTipWin(); pWin->setTipText(text); pWin->setAttribute(Qt::WA_DeleteOnClose); pWin->showMsg(sec); if (!isMousePos) { QPoint pos = parent->pos(); QSize size = parent->size(); QPoint newPos(pos.x() + 10, pos.y() + size.height() - 20); pWin->move(newPos); } else { pWin->move(parent->cursor().pos()); } } }
1,052
C++
.cpp
48
18.479167
80
0.669057
cxasm/notepad--
5,942
234
284
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
25,190
plugin.cpp
cxasm_notepad--/src/plugin.cpp
#include "plugin.h" #include <QLibrary> #include <QDir> #include <QMenu> #include <QAction> bool loadApplication(const QString& strFileName, NDD_PROC_DATA* pProcData) { QLibrary lib(strFileName); NDD_PROC_IDENTIFY_CALLBACK procCallBack; procCallBack = (NDD_PROC_IDENTIFY_CALLBACK)lib.resolve("NDD_PROC_IDENTIFY"); if (procCallBack == NULL) { return false; } if (!procCallBack(pProcData)) { return false; } pProcData->m_strFilePath = strFileName; return true; } int loadProc(const QString& strDirOut, std::function<void(NDD_PROC_DATA&, QMenu*)> funcallback, QMenu* pUserData) { int nReturn = 0; QStringList list; QDir dir; dir.setPath(strDirOut); QString strDir, strName; QStringList strFilter; strDir = dir.absolutePath(); strDir += QDir::separator(); #if defined(Q_OS_WIN) strFilter << "*.dll"; #else strFilter << "lib*.so"; #endif list = dir.entryList(strFilter, QDir::Files | QDir::Readable, QDir::Name); QStringList::Iterator it = list.begin(); for (; it != list.end(); ++it) { NDD_PROC_DATA procData; strName = *it; strName = strDir + strName; if (!loadApplication(strName, &procData)) { continue; } funcallback(procData, pUserData); nReturn++; } return nReturn; }
1,311
C++
.cpp
52
21.519231
114
0.699427
cxasm/notepad--
5,942
234
284
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
25,191
bigfilemessage.cpp
cxasm_notepad--/src/bigfilemessage.cpp
#include "bigfilemessage.h" #include "nddsetting.h" BigFileMessage::BigFileMessage(QWidget *parent) : QDialog(parent), m_result(-1) { ui.setupUi(this); } BigFileMessage::~BigFileMessage() {} void BigFileMessage::setDefOpenMode(NddDocType defMode) { switch (defMode) { case TXT_TYPE: ui.textMode->setChecked(true); break; case BIG_TEXT_RO_TYPE: ui.bigTextMode->setChecked(true); break; case BIG_EDIT_RW_TYPE: break; case SUPER_BIG_TEXT_RO_TYPE: ui.superBigTextMode->setChecked(true); break; case HEX_TYPE: ui.hexMode->setChecked(true); break; default: break; } } void BigFileMessage::setTip(QString msg) { ui.label->setText(msg); } void BigFileMessage::slot_okBt() { if (ui.textMode->isChecked()) { m_result = TXT_TYPE;//普通文本 } else if(ui.bigTextMode->isChecked()) { m_result = BIG_TEXT_RO_TYPE; //小于8G的大文本 } else if (ui.superBigTextMode->isChecked()) { m_result = SUPER_BIG_TEXT_RO_TYPE;//8G以上的大文本 } else if (ui.hexMode->isChecked()) { m_result = HEX_TYPE;//二进制 } done(m_result); } void BigFileMessage::slot_cancelBt() { m_result = -1; done(m_result); }
1,198
C++
.cpp
60
16.566667
56
0.690433
cxasm/notepad--
5,942
234
284
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
25,192
filecmprulewin.cpp
cxasm_notepad--/src/filecmprulewin.cpp
#include "filecmprulewin.h" FileCmpRuleWin::FileCmpRuleWin(int mode, bool blankMath, int equalRato,QWidget *parent) : QWidget(parent) { ui.setupUi(this); if (mode == 0) { ui.radioButtonDefault->setChecked(true); } else if(mode == 1) { ui.radioButtonIgnoreBackWhite->setChecked(true); } else if (mode == 2) { ui.radioButtonIgnoreAllWhite->setChecked(true); } ui.checkBoxBlankMatch->setChecked(blankMath); int index = 0; if (equalRato == 70) { index = 1; } else if (equalRato == 90) { index = 2; } ui.comboBoxEqualRato->setCurrentIndex(index); } FileCmpRuleWin::~FileCmpRuleWin() { } void FileCmpRuleWin::slot_apply() { int status = 0; if (ui.radioButtonDefault->isChecked()) { status = 0; } else if (ui.radioButtonIgnoreBackWhite->isChecked()) { status = 1; } else if (ui.radioButtonIgnoreAllWhite->isChecked()) { status = 2; } bool blankMatch = (ui.checkBoxBlankMatch->isChecked() ? true : false); int equalRato = 50; if (ui.comboBoxEqualRato->currentIndex() == 1) { equalRato = 70; } else if (ui.comboBoxEqualRato->currentIndex() == 2) { equalRato = 90; } emit sign_cmpModeChange(status, blankMatch, equalRato); close(); }
1,270
C++
.cpp
60
17.733333
88
0.683277
cxasm/notepad--
5,942
234
284
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
25,193
shortcutkeyeditwin.cpp
cxasm_notepad--/src/shortcutkeyeditwin.cpp
#include "shortcutkeyeditwin.h" #include <QMessageBox> ShortcutKeyEditWin::ShortcutKeyEditWin(QWidget *parent) : QDialog(parent) { ui.setupUi(this); ui.keySequenceEdit->setFocus(); } ShortcutKeyEditWin::~ShortcutKeyEditWin() {} void ShortcutKeyEditWin::setCurKeyDesc(QString desc) { ui.curKeylineEdit->setText(desc); } void ShortcutKeyEditWin::setTitle(QString title) { this->setWindowTitle(title); } QKeySequence ShortcutKeyEditWin::getNewKeySeq() { return m_newKeys; } //确认修改,先检查一下。最多四个键 void ShortcutKeyEditWin::slot_ok() { QKeySequence keys = ui.keySequenceEdit->keySequence(); if (keys.isEmpty()) { QMessageBox::warning(this, tr("Error"), tr("input right key !")); return; } m_newKeys = keys; done(1); } //删除为空 void ShortcutKeyEditWin::on_delete() { done(2); }
863
C++
.cpp
39
18.692308
68
0.736641
cxasm/notepad--
5,942
234
284
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
25,194
qtlangset.cpp
cxasm_notepad--/src/qtlangset.cpp
#include "qtlangset.h" #include "scintillaeditview.h" #include "nddsetting.h" #include "rcglobal.h" #include "ccnotepad.h" #include "styleset.h" #include "extlexermanager.h" #include <SciLexer.h> #include <qscilexer.h> #include <QSettings> #include <QColorDialog> #include <QMessageBox> #include <QSpinBox> #include <Qsci/qscilexerglobal.h> #include <QDebug> #include <QDir> QtLangSet::QtLangSet(QString initTag, QWidget *parent) : QMainWindow(parent), m_selectLexer(nullptr), m_selectStyleId(0), m_isStyleChange(false),m_isStyleChildChange(false), m_initShowLexerTag(initTag), m_previousSysLangItem(nullptr),m_isGlobelItem(false) { ui.setupUi(this); initLangList(); initUserDefineLangList(); startSignSlot(); m_themesId = StyleSet::getCurrentSytleId(); m_lastThemesId = -1; ui.mainThemesCbox->setCurrentIndex(m_themesId); } QtLangSet::~QtLangSet() { if (nullptr != m_selectLexer) { delete m_selectLexer; m_selectLexer = nullptr; } } //在同步字体时,务必先关闭关联槽函数,避免循环触发。务必配对使用 void QtLangSet::enableFontChangeSensitive(bool isSensitive) { if (isSensitive) { connect(ui.boldCheckBox, &QCheckBox::stateChanged, this, &QtLangSet::slot_fontBoldChange); connect(ui.italicCheckBox, &QCheckBox::stateChanged, this, &QtLangSet::slot_fontItalicChange); connect(ui.underlineCheckBox, &QCheckBox::stateChanged, this, &QtLangSet::slot_fontUnderlineChange); connect(ui.fontSpinBox, SIGNAL(valueChanged(int)), this, SLOT(slot_fontSizeChange(int))); connect(ui.fontComboBox, &QFontComboBox::currentFontChanged, this, &QtLangSet::slot_fontChange); } else { disconnect(ui.boldCheckBox, &QCheckBox::stateChanged, this, &QtLangSet::slot_fontBoldChange); disconnect(ui.italicCheckBox, &QCheckBox::stateChanged, this, &QtLangSet::slot_fontItalicChange); disconnect(ui.underlineCheckBox, &QCheckBox::stateChanged, this, &QtLangSet::slot_fontUnderlineChange); disconnect(ui.fontSpinBox, SIGNAL(valueChanged(int)), this, SLOT(slot_fontSizeChange(int))); disconnect(ui.fontComboBox, &QFontComboBox::currentFontChanged, this, &QtLangSet::slot_fontChange); } } void QtLangSet::startSignSlot() { //开始本来使用的是QListWidget::currentItemChanged信号,但是发现该信号存在莫名其妙的触发机制。 //估计是QT5.12的bug。所以换成itemClicked信号 connect(ui.langListWidget, &QListWidget::itemClicked, this, &QtLangSet::slot_itemSelect); connect(ui.langListWidget, &QListWidget::currentRowChanged, this, &QtLangSet::slot_langListCurRowChanged); connect(ui.userLangListWidget, &QListWidget::itemClicked, this, &QtLangSet::slot_userLangItemSelect); connect(ui.styleListWidget, &QListWidget::itemClicked, this, &QtLangSet::slot_styleItemSelect); connect(ui.styleListWidget, &QListWidget::currentRowChanged, this, &QtLangSet::slot_styleListCurRowChanged); connect(ui.boldCheckBox, &QCheckBox::stateChanged, this, &QtLangSet::slot_fontBoldChange); connect(ui.italicCheckBox, &QCheckBox::stateChanged, this, &QtLangSet::slot_fontItalicChange); connect(ui.underlineCheckBox, &QCheckBox::stateChanged, this, &QtLangSet::slot_fontUnderlineChange); connect(ui.fontSpinBox, SIGNAL(valueChanged(int)), this, SLOT(slot_fontSizeChange(int))); connect(ui.fontComboBox, &QFontComboBox::currentFontChanged, this, &QtLangSet::slot_fontChange); } //让初始化时选择当前编辑器的语言 void QtLangSet::selectInitLangTag(QString initLangTag) { //第一次必须以初始化lexid显示。这样做实在是因为初始化list启动后,会自动把第一个设置为当前。 //这里还是有问题,是qt5.12.4的bug机制导致:如果没有选择QListWidget,会总是自动选择第一个 if (!initLangTag.isEmpty()) { QList<QListWidgetItem*> destItems = ui.langListWidget->findItems(initLangTag,Qt::MatchExactly); if (!destItems.isEmpty()) { QListWidgetItem* newItem = destItems.first(); ui.langListWidget->scrollToItem(newItem); ui.langListWidget->setCurrentItem(newItem); ui.userLangListWidget->setCurrentItem(nullptr); slot_itemSelect(newItem); } else { destItems = ui.userLangListWidget->findItems(initLangTag, Qt::MatchExactly); if (!destItems.isEmpty()) { QListWidgetItem* userItem = destItems.first(); ui.userLangListWidget->scrollToItem(userItem); ui.userLangListWidget->setCurrentItem(userItem); ui.langListWidget->setCurrentItem(nullptr); slot_userLangItemSelect(userItem); } } } } void QtLangSet::slot_fontBoldChange(int state) { //即时设置风格 if (m_selectLexer != nullptr) { if (m_curStyleData.font.bold() != ((state == Qt::Unchecked) ? false : true)) { m_curStyleData.font.setBold((state == Qt::Unchecked) ? false : true); m_selectLexer->setFont(m_curStyleData.font, m_selectStyleId); m_isStyleChange = true; if (m_isGlobelItem) { if (ui.useGlobalFont->isVisible() && ui.useGbFontBold->isChecked()) { slot_useAlobalFontBold(true); saveLangeSet(m_selectLexer); } else if (ui.useGlobalFont->isVisible() && !ui.useGbFontBold->isChecked()) { //保存全局样式第一条样式本身 saveLangeSet(m_selectLexer); } else if (!ui.useGlobalFont->isVisible()) { //全局非第一个样式,修改当前全局字体大小 //全局样式的非第一个 StyleSet::setGlobalFont(m_selectStyleId, m_curStyleData.font); //保存全局样式第一条样式本身 saveLangeSet(m_selectLexer); //这里就是全局的样式。通知当前所有的编辑框,去修改他们本身的全局样式 CCNotePad* pMainNote = dynamic_cast<CCNotePad*>(parent()); if (pMainNote != nullptr) { pMainNote->setGlobalFont(m_selectStyleId); } } } else { emit viewStyleChange(m_selectLexer->lexerTag(), m_selectStyleId, m_curStyleData.color, m_curStyleData.paper, m_curStyleData.font, true); } } } } void QtLangSet::slot_fontItalicChange(int state) { //即时设置风格 if (m_selectLexer != nullptr) { if (m_curStyleData.font.italic() != ((state == Qt::Unchecked) ? false : true)) { m_curStyleData.font.setItalic((state == Qt::Unchecked) ? false : true); m_selectLexer->setFont(m_curStyleData.font, m_selectStyleId); m_isStyleChange = true; if (m_isGlobelItem) { if (ui.useGlobalFont->isVisible() && ui.useGbFontItalic->isChecked()) { slot_useAlobalFontItalic(true); saveLangeSet(m_selectLexer); } else if (ui.useGlobalFont->isVisible() && !ui.useGbFontItalic->isChecked()) { //保存全局样式第一条样式本身 saveLangeSet(m_selectLexer); } else if (!ui.useGlobalFont->isVisible()) { //全局非第一个样式,修改当前全局字体大小 //全局样式的非第一个 StyleSet::setGlobalFont(m_selectStyleId, m_curStyleData.font); saveLangeSet(m_selectLexer); //这里就是全局的样式。通知当前所有的编辑框,去修改他们本身的全局样式 CCNotePad* pMainNote = dynamic_cast<CCNotePad*>(parent()); if (pMainNote != nullptr) { pMainNote->setGlobalFont(m_selectStyleId); } } } else { emit viewStyleChange(m_selectLexer->lexerTag(), m_selectStyleId, m_curStyleData.color, m_curStyleData.paper, m_curStyleData.font, true); } } } } void QtLangSet::slot_fontUnderlineChange(int state) { //即时设置风格 if (m_selectLexer != nullptr) { if (m_curStyleData.font.underline() != ((state == Qt::Unchecked) ? false : true)) { m_curStyleData.font.setUnderline((state == Qt::Unchecked) ? false : true); m_selectLexer->setFont(m_curStyleData.font, m_selectStyleId); m_isStyleChange = true; if (m_isGlobelItem) { if (ui.useGlobalFont->isVisible() && ui.useGbFontUnderline->isChecked()) { slot_useAlobalFontUnderline(true); saveLangeSet(m_selectLexer); } else if (ui.useGlobalFont->isVisible() && !ui.useGbFontUnderline->isChecked()) { //保存全局样式第一条样式本身 saveLangeSet(m_selectLexer); } else if (!ui.useGlobalFont->isVisible()) { //全局非第一个样式,修改当前全局字体大小 //全局样式的非第一个 StyleSet::setGlobalFont(m_selectStyleId, m_curStyleData.font); saveLangeSet(m_selectLexer); //这里就是全局的样式。通知当前所有的编辑框,去修改他们本身的全局样式 CCNotePad* pMainNote = dynamic_cast<CCNotePad*>(parent()); if (pMainNote != nullptr) { pMainNote->setGlobalFont(m_selectStyleId); } } } else { emit viewStyleChange(m_selectLexer->lexerTag(), m_selectStyleId, m_curStyleData.color, m_curStyleData.paper, m_curStyleData.font, true); } } } } //发现一个qt现象:在debug断住该slot_fontSizeChange函数,会导致槽触发2次;不断住或者release模式直接跑,不会触发2次 void QtLangSet::slot_fontSizeChange(int v) { //即时设置风格 if (m_selectLexer != nullptr) { //全局修改,把所有语言的所有风格都设置 if (m_isGlobelItem) { if (m_curStyleData.font.pointSize() != v) { m_curStyleData.font.setPointSize(v); //qDebug() << m_curStyleData.font.family(); m_isStyleChange = true; m_selectLexer->setFont(m_curStyleData.font, m_selectStyleId); //全局第一个样式,修改所有语法样式 if (ui.useGlobalFont->isVisible() && ui.useGbFontSize->isChecked()) { slot_useAlobalFontSize(true); saveLangeSet(m_selectLexer); } else if (ui.useGlobalFont->isVisible() && !ui.useGbFontSize->isChecked()) { //保存全局样式第一条样式本身 saveLangeSet(m_selectLexer); } else if (!ui.useGlobalFont->isVisible()) { //全局非第一个样式,修改当前全局字体大小 //全局样式的非第一个 StyleSet::setGlobalFont(m_selectStyleId, m_curStyleData.font); saveLangeSet(m_selectLexer); //这里就是全局的样式。通知当前所有的编辑框,去修改他们本身的全局样式 CCNotePad* pMainNote = dynamic_cast<CCNotePad*>(parent()); if (pMainNote != nullptr) { pMainNote->setGlobalFont(m_selectStyleId); } } } } else { if (m_curStyleData.font.pointSize() != v) { m_curStyleData.font.setPointSize(v); m_selectLexer->setFont(m_curStyleData.font, m_selectStyleId); m_isStyleChange = true; emit viewStyleChange(m_selectLexer->lexerTag(), m_selectStyleId, m_curStyleData.color, m_curStyleData.paper, m_curStyleData.font, true); } } /*else if (!ui.modifyAllFont->isChecked()) { if (m_curStyleData.font.pointSize() != v) { m_curStyleData.font.setPointSize(v); m_selectLexer->setFont(m_curStyleData.font, m_selectStyleId); m_isStyleChange = true; emit viewStyleChange(m_selectLexer->lexerTag(), m_selectStyleId, m_curStyleData.color, m_curStyleData.paper, m_curStyleData.font, true); } } else { m_curStyleData.font.setPointSize(v); m_selectLexer->setFont(m_curStyleData.font, m_selectStyleId); m_isStyleChange = true; //即时设置风格 if (m_selectLexer != nullptr) { int row = ui.styleListWidget->count(); QListWidgetItem* item = nullptr; for (int i = 0; i < row; ++i) { item = ui.styleListWidget->item(i); int styleId = item->data(Qt::UserRole).toInt(); //所有字体大小修改为一致 QFont f = m_selectLexer->font(styleId); f.setPointSize(v); m_selectLexer->setFont(f, styleId); } saveCurLangSettings(); emit viewLexerChange(m_selectLexer->lexerTag()); } }*/ } } void QtLangSet::getCurUseLexerTags(QVector<QString>& tag) { CCNotePad* pMainNote = dynamic_cast<CCNotePad*>(parent()); if (pMainNote != nullptr) { pMainNote->getCurUseLexerTags(tag); } } //使用全局设置设定所有语言风格 void QtLangSet::updateAllLangeStyleWithGlobal(GLOBAL_STYLE_SET flag) { QFont oldfont; bool isGlobalChange = false; for (int index = 0; index <= L_TXT; ++index) { //GLOBAL本身不保存,因为GLOBAL不是语法样式,而是全局的属性风格 //如果全局修改的是全局字体或字体大小,全局也修改一下。避免括弧等大小和全局字体不一样大。 //全局颜色前景和背景时,也要特殊对待,要单独修改全局default的修改;否则编辑界面看起来颜色杂乱 if (index == L_GLOBAL) { if (flag != GLOBAL_FONT_SIZE && flag != GLOBAL_FONT && flag != GLOBAL_FG_COLOR && flag != GLOBAL_BK_COLOR) { continue; } } QsciLexer *pLexer = ScintillaEditView::createLexer(index); if (nullptr != pLexer) { switch (flag) { case GLOBAL_FONT: { //非全局修改所有的语法对应样式 if (index != L_GLOBAL) { for (int i = 0; i <= 255; ++i) { if (!pLexer->description(i).isEmpty()) { oldfont = pLexer->font(i); oldfont.setFamily(m_curStyleData.font.family()); pLexer->setFont(oldfont, i); } } } else { //是全局属性修改字体 QsciLexerGlobal* pGlobalLexer = dynamic_cast<QsciLexerGlobal*>(pLexer); if (pGlobalLexer != nullptr) { for (int i = 0; i <= GLOBAL_STYLES::URL_HOVERRED; ++i) { oldfont = pLexer->font(i); oldfont.setFamily(m_curStyleData.font.family()); pLexer->setFont(oldfont, i); } isGlobalChange = true; } } } break; case GLOBAL_FONT_SIZE: { //非全局修改所有的语法对应样式 if (index != L_GLOBAL) { for (int i = 0; i <= 255; ++i) { if (!pLexer->description(i).isEmpty()) { oldfont = pLexer->font(i); oldfont.setPointSize(m_curStyleData.font.pointSize()); pLexer->setFont(oldfont, i); } } } else { //是全局 QsciLexerGlobal* pGlobalLexer = dynamic_cast<QsciLexerGlobal*>(pLexer); if (pGlobalLexer != nullptr) { for (int i = 0; i <= GLOBAL_STYLES::URL_HOVERRED; ++i) { oldfont = pLexer->font(i); oldfont.setPointSize(m_curStyleData.font.pointSize()); pLexer->setFont(oldfont, i); } isGlobalChange = true; } } } break; case GLOBAL_FONT_BOLD: { for (int i = 0; i <= 255; ++i) { if (!pLexer->description(i).isEmpty()) { oldfont = pLexer->font(i); oldfont.setBold(m_curStyleData.font.bold()); pLexer->setFont(oldfont, i); } } } break; case GLOBAL_FONT_UNDERLINE: { for (int i = 0; i <= 255; ++i) { if (!pLexer->description(i).isEmpty()) { oldfont = pLexer->font(i); oldfont.setUnderline(m_curStyleData.font.underline()); pLexer->setFont(oldfont, i); } } } break; case GLOBAL_FONT_ITALIC: { for (int i = 0; i <= 255; ++i) { if (!pLexer->description(i).isEmpty()) { oldfont = pLexer->font(i); oldfont.setItalic(m_curStyleData.font.italic()); pLexer->setFont(oldfont, i); } } } break; case GLOBAL_FG_COLOR: { //非全局修改所有的语法对应样式 if (index != L_GLOBAL) { pLexer->setColor(m_curStyleData.color, -1); pLexer->setDefaultColor(m_curStyleData.color); } else { //全局时,只修改default的颜色 pLexer->setColor(m_curStyleData.color, GLOBAL_STYLES::GLOBAL_OVERRIDE); pLexer->setColor(m_curStyleData.color, GLOBAL_STYLES::DEFAULT_STYLE); isGlobalChange = true; } } break; case GLOBAL_BK_COLOR: { //非全局修改所有的语法对应样式 if (index != L_GLOBAL) { pLexer->setPaper(m_curStyleData.paper, -1); //默认纸背景色会和QPalette保持一致。单独需要单独设置一下 pLexer->setDefaultPaper(m_curStyleData.paper); } else { //全局时,只修改default的颜色 pLexer->setPaper(m_curStyleData.paper, GLOBAL_STYLES::GLOBAL_OVERRIDE); pLexer->setPaper(m_curStyleData.paper, GLOBAL_STYLES::DEFAULT_STYLE); isGlobalChange = true; } } break; default: break; } saveLangeSet(pLexer); } delete pLexer; } //如果全局变化了,把当前全局界面刷新一下 //还有,还需要把当前打开文档的全局风格设置一下,否则全局不生效 if (isGlobalChange) { refreshGlobalSet(); } } void QtLangSet::refreshGlobalSet() { m_previousSysLangItem = nullptr; slot_langListCurRowChanged(0); StyleSet::reloadGolbalStyleFromSetFile(); //这里就是全局的样式。通知当前所有的编辑框,去修改他们本身的全局样式 CCNotePad* pMainNote = dynamic_cast<CCNotePad*>(parent()); if (pMainNote != nullptr) { for (int i = 0; i <= GLOBAL_STYLES::URL_HOVERRED; ++i) { pMainNote->setGlobalFont(i); } } } //恢复所有语言的初始配置。与restoreOriginLangOneStyle类似,但是粒度更大 void QtLangSet::restoreOriginLangAllStyle() { QsciLexer *pLexer = nullptr; //一旦重置,当前修改无条件不保存。否则避免当前的刚刚重置,又被保存 m_isStyleChange = false; for (int index = 0; index <= L_TXT; ++index) { pLexer = ScintillaEditView::createLexer(index); if (pLexer == nullptr) { continue; } //如果存在自定义的配置,直接全部删除掉 QString cfgPath = QString("notepad/userstyle/%1/%2").arg(StyleSet::getCurrentStyle()).arg(pLexer->lexerTag()); QSettings qs(QSettings::IniFormat, QSettings::UserScope, cfgPath); if (QFile::exists(qs.fileName())) { QFile::remove(qs.fileName()); } delete pLexer; pLexer = nullptr; //如果是全局的,把当前内存中的全局风格也更新一下 if (index == L_GLOBAL) { StyleSet::loadGolbalStyle(); } } } //只在restoreOriginLangOneStyle中调用 static void restoreLangFontFgColorToDarkStyle(QsciLexer *pLexer, int i) { //if (QtLangSet::s_darkColorMap.contains(pLexer->color(i).name())) //{ // pLexer->setColor(QtLangSet::s_darkColorMap.value(pLexer->color(i).name()), i); //} } //只在restoreOriginLangOneStyle中调用 static void restoreLangPaperColorToDarkStyle(QsciLexer *pLexer, int i) { //注意下面这个颜色和void StyleSet::setBlackStyle()中保持一致 //背景也变成暗黑色 if (StyleSet::foldbgColor != pLexer->paper(i)) { pLexer->setPaper(StyleSet::foldbgColor, i); pLexer->setDefaultPaper(StyleSet::foldbgColor); } } //恢复所有语言的初始配置,只恢复GLOBAL_STYLE_SET指定的风格 void QtLangSet::restoreOriginLangOneStyle(GLOBAL_STYLE_SET flag) { QFont oldfont; QFont curfont; QColor oldClor; for (int index = 0; index <= L_TXT; ++index) { QsciLexer *pLexer = ScintillaEditView::createLexer(index); QsciLexer *pOriginLexer = ScintillaEditView::createLexer(index,"",true); if (nullptr != pLexer) { for (int i = 0; i <= 255; ++i) { if (!pLexer->description(i).isEmpty()) { switch (flag) { case GLOBAL_FONT: { oldfont = pOriginLexer->font(i); pLexer->setFont(oldfont, i); } break; case GLOBAL_FONT_SIZE: { oldfont = pOriginLexer->font(i); curfont = pLexer->font(i); curfont.setPointSize(oldfont.pointSize()); pLexer->setFont(curfont, i); } break; case GLOBAL_FONT_BOLD: { oldfont = pOriginLexer->font(i); curfont = pLexer->font(i); curfont.setBold(oldfont.bold()); pLexer->setFont(curfont, i); } break; case GLOBAL_FONT_UNDERLINE: { oldfont = pOriginLexer->font(i); curfont = pLexer->font(i); curfont.setUnderline(oldfont.underline()); pLexer->setFont(curfont, i); } break; case GLOBAL_FONT_ITALIC: { oldfont = pOriginLexer->font(i); curfont = pLexer->font(i); curfont.setItalic(oldfont.italic()); pLexer->setFont(curfont, i); } break; case GLOBAL_FG_COLOR: { oldClor = pOriginLexer->color(i); pLexer->setColor(oldClor, i); } break; case GLOBAL_BK_COLOR: { oldClor = pOriginLexer->paper(i); pLexer->setPaper(oldClor, i); } break; default: break; } } } switch (flag) { case GLOBAL_FG_COLOR: //把默认颜色修改一下 oldClor = pOriginLexer->defaultColor(); pLexer->setDefaultColor(oldClor); break; case GLOBAL_BK_COLOR: //把默认颜色修改一下 oldClor = pOriginLexer->defaultPaper(); pLexer->setDefaultPaper(oldClor); break; } saveLangeSet(pLexer); } delete pLexer; delete pOriginLexer; } //全局变化了,把当前全局界面刷新一下 //还有,还需要把当前打开文档的全局风格设置一下,否则全局不生效 refreshGlobalSet(); } //预览全局修改字体效果。把当前所有的语法,风格字体都修改一遍 void QtLangSet::previewAllGoblalChange() { QVector<QString> tags; getCurUseLexerTags(tags); for (int i = 0, s = tags.size(); i < s; ++i) { emit viewLexerChange(tags.at(i)); } //这里还差一步 //这里还有问题,还需要把当前打开文档的全局风格设置一下,否则全局不生效 //这里就是全局的样式。通知当前所有的编辑框,去修改他们本身的全局样式 CCNotePad* pMainNote = dynamic_cast<CCNotePad*>(parent()); if (pMainNote != nullptr) { for (int i = 0; i <= GLOBAL_STYLES::URL_HOVERRED; ++i) { pMainNote->setGlobalFont(i); } } } void QtLangSet::slot_fontChange(const QFont &font) { //即时设置风格 if (m_selectLexer != nullptr) { //全局修改 if (m_isGlobelItem) { if (m_curStyleData.font != font) { m_curStyleData.font.setFamily(font.family()); m_selectLexer->setFont(m_curStyleData.font, m_selectStyleId); m_isStyleChange = true; //修改所有字体 if (ui.useGlobalFont->isVisible() && ui.useGbFont->isChecked()) { slot_useAlobalFont(true); saveLangeSet(m_selectLexer); } else if (ui.useGlobalFont->isVisible() && !ui.useGbFont->isChecked()) { //保存全局样式第一条样式本身 saveLangeSet(m_selectLexer); } else if(!ui.useGlobalFont->isVisible()) { //全局样式的非第一个 StyleSet::setGlobalFont(m_selectStyleId, m_curStyleData.font); //保存全局样式第一条样式本身 saveLangeSet(m_selectLexer); //这里就是全局的样式。通知当前所有的编辑框,去修改他们本身的全局样式 CCNotePad* pMainNote = dynamic_cast<CCNotePad*>(parent()); if (pMainNote != nullptr) { pMainNote->setGlobalFont(m_selectStyleId); } } } } else { #if 0 //统一修改字体,大小和风格保存不变 QFont oldf = m_curStyleData.font; m_curStyleData.font = font; m_curStyleData.font.setBold(oldf.bold()); m_curStyleData.font.setItalic(oldf.italic()); m_curStyleData.font.setUnderline(oldf.underline()); m_isStyleChange = true; //即时设置风格 if (m_selectLexer != nullptr) { int row = ui.styleListWidget->count(); QListWidgetItem* item = nullptr; for (int i = 0; i < row; ++i) { item = ui.styleListWidget->item(i); int styleId = item->data(Qt::UserRole).toInt(); QFont f = m_selectLexer->font(styleId); //新字体的名统一设置,但是风格字体大小保存老的一致 QFont newFont = m_curStyleData.font; newFont.setBold(f.bold()); newFont.setItalic(f.italic()); newFont.setUnderline(f.underline()); newFont.setPointSize(f.pointSize()); m_selectLexer->setFont(newFont, styleId); } saveCurLangSettings(); emit viewLexerChange(m_selectLexer->lexerTag()); } #endif if (m_curStyleData.font != font) { m_curStyleData.font.setFamily(font.family()); m_selectLexer->setFont(m_curStyleData.font, m_selectStyleId); m_isStyleChange = true; emit viewStyleChange(m_selectLexer->lexerTag(), m_selectStyleId, m_curStyleData.color, m_curStyleData.paper, m_curStyleData.font, true); } } } } void QtLangSet::initLangList() { for (int i = 0; i <= L_TXT; ++i) { QsciLexer *pLexer = ScintillaEditView::createLexer(i); if (nullptr != pLexer) { QString langName = pLexer->lexerTag(); QListWidgetItem *item = new QListWidgetItem(langName); item->setData(Qt::UserRole,i); ui.langListWidget->addItem(item); delete pLexer; } } //怀疑这个是队列链接的,会延迟执行。故总是导致选择的选不中,而是第一个语言asp。 ui.langListWidget->sortItems(Qt::AscendingOrder); //手动修改第一个名称为中文。 if (ui.langListWidget->item(0)->text() == QString("AllGlobal")) { ui.langListWidget->item(0)->setText(tr("AllGlobal")); } } //isLoadToUI是否加载显示到当前UI界面 bool QtLangSet::readLangSetFile(QString langName,QString &keyword, QString &motherLang, QString & extTypes) { QString userLangFile = QString("notepad/userlang/%1").arg(langName);//自定义语言中不能有.字符,否则可能有错,后续要检查 QSettings qs(QSettings::IniFormat, QSettings::UserScope, userLangFile); qs.setIniCodec("UTF-8"); //qDebug() << qs.fileName(); if (!qs.contains("mz")) { return false; } //自定义语言格式。 //mz:ndd //name:xxx //mother:xxx none/cpp/html 就三种 //ext:xx xx xx 文件关联后缀名 //keword:xxx keyword = qs.value("keyword").toString(); extTypes = qs.value("ext").toString(); motherLang = qs.value("mother").toString(); return true; } //初始化用户自定义的语言配置 void QtLangSet::initUserDefineLangList() { QString userLangDirPath = getUserLangDirPath(); //遍历文件夹 QDir dir_file(userLangDirPath); QFileInfoList list_file = dir_file.entryInfoList(QDir::Files | QDir::NoDotAndDotDot | QDir::NoSymLinks, QDir::Name); for (int i = 0; i < list_file.size(); ++i) { //将当前目录中所有文件添加到treewidget中 QFileInfo fileInfo = list_file.at(i); //这个文件是ext和tag的映射文件,不做配置解析 if (fileInfo.baseName() == "ext_tag") { continue; } ui.userLangListWidget->addItem(fileInfo.baseName()); } ui.userLangListWidget->sortItems(Qt::AscendingOrder); } //切换当前语言。 //QListWidget::currentItemChanged这个信号qt5.12.10中应该是存在bug,总是莫名其妙的要发一次currentItemChanged信号出来。导致第一次该选的项被覆盖。 //换成itemClicked信号 void QtLangSet::slot_itemSelect(QListWidgetItem *item) { if (item == nullptr) { return; } //qDebug() << item->text() << (previous ? previous->text() : 0); //如果前后主题发生了变化,则依旧要走更新,防止主题切换后没及时更新 if (m_previousSysLangItem == item && (m_lastThemesId == m_themesId)) { return; } ui.curThemes->setText(tr("Current themes : %1, language : %2").arg(StyleSet::getCurrentStyle()).arg(item->text())); ui.langListWidget->scrollToItem(item); ui.userLangListWidget->setCurrentItem(nullptr); //保存前一个已经修改的。询问用户是否保存 if (m_isStyleChange && m_previousSysLangItem != nullptr && m_selectLexer !=nullptr) { //只有当前是非全局,才需要提示用户是否要保持。 //全局的不需要提示,因为已经无条件全部保存过了。 if (!m_isGlobelItem) { if (QMessageBox::Yes == QMessageBox::question(this, tr("Save Change"), tr("%1 style configuration has been modified. Do you want to save it?").arg(m_previousSysLangItem->text()))) { saveCurLangSettings(); } } } if (!item->isSelected()) { item->setSelected(true); } ui.styleListWidget->clear(); if (m_selectLexer != nullptr) { delete m_selectLexer; m_selectLexer = nullptr; } int lexId = item->data(Qt::UserRole).toInt(); //全局的这个要单独对待,暂时没有任何风格。 if (lexId == L_GLOBAL) { m_isGlobelItem = true; ui.stackedWidget->setCurrentIndex(1); } else { m_isGlobelItem = false; ui.stackedWidget->setCurrentIndex(0); } QsciLexer *pLexer = ScintillaEditView::createLexer(lexId); if (nullptr != pLexer) { m_selectLexer = pLexer; QString keyword(m_selectLexer->keywords(1)); ui.keywordTe->setPlainText(keyword); ui.motherLangCb->setCurrentIndex(0); //设置关联文件项 QString langName = item->text(); QStringList extList; ExtLexerManager::getInstance()->getExtlistByLangTag(langName, extList); ui.extFileType->setText(extList.join(',')); for (int i = 0; i <= 255; ++i) { QString desc = pLexer->description(i); if (!desc.isEmpty()) { QListWidgetItem *itemtemp = new QListWidgetItem(desc); itemtemp->setData(Qt::UserRole, i); ui.styleListWidget->addItem(itemtemp); } } } m_previousSysLangItem = item; //自动显示第一条的结果 QListWidgetItem *itemtemp = ui.styleListWidget->item(0); if (itemtemp != nullptr) { itemtemp->setSelected(true); slot_styleItemSelect(itemtemp); } m_isStyleChange = false; //ui.extFileType->clear(); ui.motherLangCb->setCurrentIndex(0); } void QtLangSet::slot_langListCurRowChanged(int row) { QListWidgetItem* current = ui.langListWidget->item(row); slot_itemSelect(current); } //根据母亲模块语言,把属性风格显示出来 void QtLangSet::displayUserMotherLangsStyle(QString langTagName, UserLangMother motherLang) { QsciLexer *pLexer = nullptr; ui.styleListWidget->clear(); switch (motherLang) { case MOTHER_NONE: pLexer = ScintillaEditView::createLexer(L_USER_TXT, langTagName); break; case MOTHER_CPP: pLexer = ScintillaEditView::createLexer(L_USER_CPP, langTagName); break; default: pLexer = ScintillaEditView::createLexer(L_USER_TXT, langTagName); break; } if (nullptr != pLexer) { //这里一定要以新语言的名称作为lexer的tag。 //pLexer->setLexerTag(langTagName); pLexer->setIsUserDefineKeywords(true); if (m_selectLexer != nullptr) { delete m_selectLexer; } m_selectLexer = pLexer; for (int i = 0; i <= 255; ++i) { QString desc = pLexer->description(i); if (!desc.isEmpty()) { QListWidgetItem *itemtemp = new QListWidgetItem(desc); itemtemp->setData(Qt::UserRole, i); ui.styleListWidget->addItem(itemtemp); } } } //自动显示第一条的结果 QListWidgetItem *itemtemp = ui.styleListWidget->item(0); if (itemtemp != nullptr) { itemtemp->setSelected(true); slot_styleItemSelect(itemtemp); } m_isStyleChange = false; } //点击当前用户自定义语言的语言item。todo:暂时没有做前一个的修改保存,需要用户每次修改后自己点击save,否则可能不会保存 void QtLangSet::slot_userLangItemSelect(QListWidgetItem *item) { if (item == nullptr) { return; } //肯定不能是全局设置了 if(m_isGlobelItem || (ui.stackedWidget->currentIndex() == 1)) { m_isGlobelItem = false; ui.stackedWidget->setCurrentIndex(0); /*if (!ui.modiryAllColor->isEnabled()) { ui.modiryAllColor->setEnabled(true); } if (!ui.modifyAllFont->isEnabled()) { ui.modifyAllFont->setEnabled(true); }*/ } m_previousSysLangItem = nullptr; ui.langListWidget->setCurrentItem(nullptr); QString langName = item->text(); QString keyword; QString motherLang; QString extTypes; if (readLangSetFile(langName, keyword, motherLang, extTypes)) { ui.keywordTe->setPlainText(keyword); ui.motherLangCb->setCurrentText(motherLang); ui.extFileType->setText(extTypes); //根据母亲模块语言,把属性风格显示出来 displayUserMotherLangsStyle(langName, (UserLangMother)(LangType::L_USER_TXT + ui.motherLangCb->currentIndex())); } else { ui.statusBar->showMessage(tr("Read %1 language user define format error.").arg(langName), 10000); } } //获取当前ui上的字体 void QtLangSet::getCurUiFont(QFont& font) { font = ui.fontComboBox->currentFont(); font.setBold(ui.boldCheckBox->isChecked()); font.setItalic(ui.italicCheckBox->isChecked()); font.setUnderline(ui.underlineCheckBox->isChecked()); font.setPointSize(ui.fontSpinBox->value()); } void QtLangSet::closeEvent(QCloseEvent * e) { saveCurLangSettings(); } //把item的对应风格显示在界面上 void QtLangSet::syncShowStyleItemToUI(QListWidgetItem *item) { if (item != nullptr && m_selectLexer != nullptr) { int styleId = item->data(Qt::UserRole).toInt(); if (m_selectStyleId == styleId && (m_lastThemesId == m_themesId)) { return; } if (!item->isSelected()) { item->setSelected(true); } if (!ui.label_fc->isEnabled()) { ui.label_fc->setEnabled(true); ui.toolButton->setEnabled(true); } if (!ui.label_bc->isEnabled()) { ui.label_bc->setEnabled(true); ui.toolButton1->setEnabled(true); } if (!ui.fontComboBox->isEnabled()) { ui.fontComboBox->setEnabled(true); ui.boldCheckBox->setEnabled(true); ui.italicCheckBox->setEnabled(true); ui.underlineCheckBox->setEnabled(true); } if (!ui.fontSpinBox->isEnabled()) { ui.fontSpinBox->setEnabled(true); } m_selectStyleId = styleId; QsciLexer::StyleData & sd = m_selectLexer->styleData(styleId); m_curStyleData = sd; setStyleShow(sd.font, sd.color, sd.paper); //这里不能直接设置为非修改,如果之前已经修改过,则还是要认定为修改。 //m_isStyleChange = false; //如果是全局,则把不能修改的全局样式灰掉,避免干扰用户的选择 if (m_isGlobelItem) { QsciLexerGlobal* pGlobalLexer = dynamic_cast<QsciLexerGlobal*>(m_selectLexer); if (pGlobalLexer != nullptr) { int enableMask = pGlobalLexer->changeOperBit(styleId); if (!(enableMask & FG_BIT)) { ui.label_fc->setEnabled(false); ui.toolButton->setEnabled(false); } if (!(enableMask & BG_BIT)) { ui.label_bc->setEnabled(false); ui.toolButton1->setEnabled(false); } if (!(enableMask & FONT_BIT)) { ui.fontComboBox->setEnabled(false); ui.boldCheckBox->setEnabled(false); ui.italicCheckBox->setEnabled(false); ui.underlineCheckBox->setEnabled(false); } if (!(enableMask & SIZE_BIT)) { ui.fontSpinBox->setEnabled(false); } } } } } //点击当前的风格item void QtLangSet::slot_styleItemSelect(QListWidgetItem *current) { //qDebug() << "slot_styleItemSelect"; syncShowStyleItemToUI(current); if (m_isGlobelItem && ui.styleListWidget->item(0) == current) { ui.useGlobalColor->setVisible(true); ui.useGlobalFont->setVisible(true); } else { if (ui.useGlobalColor->isVisible()) { ui.useGlobalColor->setVisible(false); } if (ui.useGlobalFont->isVisible()) { ui.useGlobalFont->setVisible(false); } } } //使用键盘上下切换 void QtLangSet::slot_styleListCurRowChanged(int row) { //qDebug() << "slot_curRowChanged"; QListWidgetItem* current = ui.styleListWidget->item(row); slot_styleItemSelect(current); } void QtLangSet::fillForegroundColor(QColor& fcColor) { QPixmap f(32, 32); f.fill(fcColor); ui.label_fc->setPixmap(f); } void QtLangSet::fillBackgroundColor(QColor &bkColor) { QPixmap b(32, 32); b.fill(bkColor); ui.label_bc->setPixmap(b); } void QtLangSet::setStyleShow(QFont& font, QColor& fcColor, QColor &bkColor) { //修改字体会触发槽函数执行,务必先关闭一下信号 enableFontChangeSensitive(false); ui.fontComboBox->setCurrentFont(font); ui.fontSpinBox->setValue(font.pointSize()); ui.boldCheckBox->setChecked(font.bold()); ui.italicCheckBox->setChecked(font.italic()); ui.underlineCheckBox->setChecked(font.underline()); fillForegroundColor(fcColor); fillBackgroundColor(bkColor); enableFontChangeSensitive(true); } //读取特定语言的设置;StyleId-1则读取当前主题,否则指定的StyleId主题 bool QtLangSet::readLangSettings(QsciLexer *lexer, QString tag, int StyleId) { QString cfgPath = QString("notepad/userstyle/%1/%2").arg((StyleId == -1) ? StyleSet::getCurrentStyle() : StyleSet::getStyleName(StyleId)).arg(tag); QSettings qs(QSettings::IniFormat, QSettings::UserScope, cfgPath); if (QFile::exists(qs.fileName())) { return lexer->readSettings(qs); } else//这里应该加个逻辑完备的保护。如果没有读取到用户配置,则应该从标准目标去读原始配置 { return readLangOriginSettings(lexer, tag, StyleId, true); } return false; } //读取特定语言的原始样式设置;StyleId-1则读取当前主题,否则指定的StyleId主题 //force:无条件读取 bool QtLangSet::readLangOriginSettings(QsciLexer* lexer, QString tag, int StyleId, bool force) { //默认主题不需要读取,内存中已经存在 if (StyleId == 0 && !force) { return true; } //默认皮肤路径放在软件的同级目录下面的themes目录 QString cfgPath = QString("%1/themes/%2/%3.ini").arg(QCoreApplication::applicationDirPath()).arg((StyleId == -1)?StyleSet::getCurrentStyle(): StyleSet::getStyleName(StyleId)).arg(tag); QSettings qs(cfgPath, QSettings::IniFormat); if (QFile::exists(qs.fileName())) { return lexer->readSettings(qs); } return false; } //保存一种语言的配置。 void QtLangSet::saveLangeSet(QsciLexer *lexer, int StyleId) { if (lexer != nullptr) { QString tag = lexer->lexerTag(); QString cfgPath = QString("notepad/userstyle/%1/%2").arg(((StyleId == -1) ? StyleSet::getCurrentStyle() : StyleSet::getStyleName(StyleId))).arg(tag); QSettings qs(QSettings::IniFormat, QSettings::UserScope, cfgPath); lexer->writeSettings(qs); qs.sync(); } } //保存当前选定语言的配置 bool QtLangSet::saveCurLangSettings() { if (m_isStyleChange && m_selectLexer != nullptr) { saveLangeSet(m_selectLexer); m_isStyleChange = false; ui.statusBar->showMessage(tr("Save Finished !"),10000); return true; } ui.statusBar->showMessage(tr("Not change, no need save !"),10000); return false; } bool QtLangSet::isUseGlobalFgColor() { return ui.useGlobalColor->isVisible() && ui.useGbFc->isChecked(); } bool QtLangSet::isUseGlobalBgColor() { return ui.useGlobalColor->isVisible() && ui.useGbBc->isChecked(); } //修改前景色 void QtLangSet::slot_changeFgColor() { QColor color = QColorDialog::getColor(m_curStyleData.color, this, tr("Style Foreground Color")); if (color.isValid()) { //全局修改 if (m_isGlobelItem) { if (m_curStyleData.color != color) { m_curStyleData.color = color; fillForegroundColor(color); m_isStyleChange = true; //即时设置风格 if (m_selectLexer != nullptr) { //此时一定是QsciLexerGlobal m_selectLexer->setColor(color, m_selectStyleId); } //只有在第一个全局样式时,isUseGlobalFgColor下面才为true。把所有语言的所有风格都设置 if (isUseGlobalFgColor()) { slot_useAlobalFgColor(true); } else if(!ui.useGlobalColor->isVisible()) { //全局样式的非第一个 StyleSet::setGlobalFgColor(m_selectStyleId, color); //这里就是全局的样式。通知当前所有的编辑框,去修改他们本身的全局样式 CCNotePad* pMainNote = dynamic_cast<CCNotePad*>(parent()); if (pMainNote != nullptr) { pMainNote->setGlobalFgColor(m_selectStyleId); } } } } else { //当前前景色是否变化 if (m_curStyleData.color != color) { m_curStyleData.color = color; fillForegroundColor(color); m_isStyleChange = true; //即时设置风格 if (m_selectLexer != nullptr) { m_selectLexer->setColor(color, m_selectStyleId); emit viewStyleChange(m_selectLexer->lexerTag(), m_selectStyleId, color, m_curStyleData.paper, m_curStyleData.font, false); } } } /*else if (!ui.modiryAllColor->isChecked()) { 当前前景色是否变化 if (m_curStyleData.color != color) { m_curStyleData.color = color; fillForegroundColor(color); m_isStyleChange = true; 即时设置风格 if (m_selectLexer != nullptr) { m_selectLexer->setColor(color, m_selectStyleId); emit viewStyleChange(m_selectLexer->lexerTag(), m_selectStyleId, color, m_curStyleData.paper, m_curStyleData.font, false); } } }*/ /*else { 全部风格颜色修改 当前前景色是否变化 m_curStyleData.color = color; fillForegroundColor(color); m_isStyleChange = true; 即时设置风格 if (m_selectLexer != nullptr) { m_selectLexer->setColor(color, -1); saveCurLangSettings(); emit viewLexerChange(m_selectLexer->lexerTag()); } */ // } } } //修改背景色 void QtLangSet::slot_changeBkColor() { QColor color = QColorDialog::getColor(m_curStyleData.paper, this, tr("Style Background Color")); if (color.isValid()) { //全局修改,把所有语言的所有风格都设置 if (m_isGlobelItem) { if (m_curStyleData.paper != color) { m_curStyleData.paper = color; fillBackgroundColor(color); m_isStyleChange = true; //即时设置风格 if (m_selectLexer != nullptr) { m_selectLexer->setPaper(color, m_selectStyleId); } if (isUseGlobalBgColor()) { slot_useAlobalBkColor(true); } else if (!ui.useGlobalColor->isVisible()) { StyleSet::setGlobalBgColor(m_selectStyleId, color); //这里就是全局的样式。通知当前所有的编辑框,去修改他们本身的全局样式 CCNotePad* pMainNote = dynamic_cast<CCNotePad*>(parent()); if (pMainNote != nullptr) { pMainNote->setGlobalBgColor(m_selectStyleId); } } } } else { //当前背景色是否变化 if (m_curStyleData.paper != color) { m_curStyleData.paper = color; fillBackgroundColor(color); m_isStyleChange = true; //即时设置风格 if (m_selectLexer != nullptr) { m_selectLexer->setPaper(color, m_selectStyleId); emit viewStyleChange(m_selectLexer->lexerTag(), m_selectStyleId, m_curStyleData.color, m_curStyleData.paper, m_curStyleData.font, false); } } } // else if (!ui.modiryAllColor->isChecked()) // { // //当前前景色是否变化 // if (m_curStyleData.paper != color) // { // m_curStyleData.paper = color; // fillBackgroundColor(color); // m_isStyleChange = true; // //即时设置风格 // if (m_selectLexer != nullptr) // { // m_selectLexer->setPaper(color, m_selectStyleId); // emit viewStyleChange(m_selectLexer->lexerTag(), m_selectStyleId, color, m_curStyleData.paper, m_curStyleData.font, false); // } // } //} } } void QtLangSet::slot_saveClick() { saveCurLangSettings(); } //恢复初始化设置 void QtLangSet::slot_reset() { if (m_selectLexer != nullptr) { if (!m_isGlobelItem) { if (QMessageBox::Yes != QMessageBox::question(this, tr("Reset Style"), tr("Are you sure to reset language %1 sytle").arg(m_selectLexer->lexerTag()))) { return; } //一旦重置,当前修改无条件不保存。否则避免当前的刚刚重置,又被保存 m_isStyleChange = false; //如果存在自定义的配置,也删除掉 QString cfgPath = QString("notepad/userstyle/%1/%2").arg(StyleSet::getCurrentStyle()).arg(m_selectLexer->lexerTag()); QSettings qs(QSettings::IniFormat, QSettings::UserScope, cfgPath); if (QFile::exists(qs.fileName())) { QFile::remove(qs.fileName()); } //一定要先保存,因为selectInitLangTag后可能会变化 int row = ui.styleListWidget->currentRow(); //强行让slot_itemSelect里面的进行切换 m_previousSysLangItem = nullptr; selectInitLangTag(m_selectLexer->lexerTag()); //手动刷新UI QListWidgetItem* styleItem = ui.styleListWidget->item(row); m_selectStyleId = -1; syncShowStyleItemToUI(styleItem); emit viewLexerChange(m_selectLexer->lexerTag()); } else { if (ui.useGlobalFont->isVisible()) { //如果是全局重置,则把所有语言都重置 if (QMessageBox::Yes != QMessageBox::question(this, tr("Reset All Style"), tr("Are you sure to reset All language sytle"))) { return; } restoreOriginLangAllStyle(); previewAllGoblalChange(); //手动刷新UI。全局目前只有一行全局设置 if (m_selectLexer != nullptr) { delete m_selectLexer; } m_selectLexer = ScintillaEditView::createLexer(L_GLOBAL); QListWidgetItem* styleItem = ui.styleListWidget->item(0); m_selectStyleId = -1; syncShowStyleItemToUI(styleItem); } else { //重置所有全局样式 //一旦重置,当前修改无条件不保存。否则避免当前的刚刚重置,又被保存 m_isStyleChange = false; //如果存在自定义的配置,也删除掉 QString cfgPath = QString("notepad/userstyle/%1/%2").arg(StyleSet::getCurrentStyle()).arg(m_selectLexer->lexerTag()); QSettings qs(QSettings::IniFormat, QSettings::UserScope, cfgPath); if (QFile::exists(qs.fileName())) { QFile::remove(qs.fileName()); } //一定要先保存,因为selectInitLangTag后可能会变化 int row = ui.styleListWidget->currentRow(); //强行让slot_itemSelect里面的进行切换 m_previousSysLangItem = nullptr; //这里必须写ALLglobal,否则中文查找不到 selectInitLangTag(tr("AllGlobal")); //手动刷新UI QListWidgetItem* styleItem = ui.styleListWidget->item(row); m_selectStyleId = -1; syncShowStyleItemToUI(styleItem); //重新从加载一次纯净的全局样式。因为前面保存的已经删了,所以加载的是纯净的。 StyleSet::loadGolbalStyle(); updateThemes(); } } } } void QtLangSet::slot_useAlobalFgColor(bool check) { if (check) { updateAllLangeStyleWithGlobal(GLOBAL_FG_COLOR); previewAllGoblalChange(); } else { restoreOriginLangOneStyle(GLOBAL_FG_COLOR); previewAllGoblalChange(); } } void QtLangSet::slot_useAlobalBkColor(bool check) { if (check) { updateAllLangeStyleWithGlobal(GLOBAL_BK_COLOR); previewAllGoblalChange(); } else { restoreOriginLangOneStyle(GLOBAL_BK_COLOR); previewAllGoblalChange(); } } void QtLangSet::slot_useAlobalFont(bool check) { if (check) { updateAllLangeStyleWithGlobal(GLOBAL_FONT); previewAllGoblalChange(); } else { restoreOriginLangOneStyle(GLOBAL_FONT); previewAllGoblalChange(); } } void QtLangSet::slot_useAlobalFontSize(bool check) { if (check) { updateAllLangeStyleWithGlobal(GLOBAL_FONT_SIZE); previewAllGoblalChange(); } else { restoreOriginLangOneStyle(GLOBAL_FONT_SIZE); previewAllGoblalChange(); } } void QtLangSet::slot_useAlobalFontBold(bool check) { if (check) { updateAllLangeStyleWithGlobal(GLOBAL_FONT_BOLD); previewAllGoblalChange(); } else { restoreOriginLangOneStyle(GLOBAL_FONT_BOLD); previewAllGoblalChange(); } } void QtLangSet::slot_useAlobalFontUnderline(bool check) { if (check) { updateAllLangeStyleWithGlobal(GLOBAL_FONT_UNDERLINE); previewAllGoblalChange(); } else { restoreOriginLangOneStyle(GLOBAL_FONT_UNDERLINE); previewAllGoblalChange(); } } void QtLangSet::slot_useAlobalFontItalic(bool check) { if (check) { updateAllLangeStyleWithGlobal(GLOBAL_FONT_ITALIC); previewAllGoblalChange(); } else { restoreOriginLangOneStyle(GLOBAL_FONT_ITALIC); previewAllGoblalChange(); } } //把默认语言风格的部分颜色,替换为暗色下显眼的颜色 //这个函数是可以处理自定义语言的。 //void QtLangSet::setLangFontFgColorToDarkStyle(LangType langId, QString tag) //{ // QColor blackColor(Qt::black); // QColor lightColor(0xdedede); // // QColor blackColor1(0x0000ff); // QColor lightColor1(0xffaa00); // // // //C++注释的默认颜色,不显眼 // QColor blackColor2(0x007f00); // QColor lightColor2(0x009000); // // QColor blackColor3(0x7f7f00); // QColor lightColor3(0xfca287); // // // QColor blackColor4(0x8000ff); // QColor lightColor4(0xffaa00); // // 注意下面这个颜色和void StyleSet::setBlackStyle()中保持一致 // QColor bkPaperColor(0, 0, 0); // // QsciLexer *pLexer = ScintillaEditView::createLexer(langId, tag); // if (nullptr != pLexer) // { // for (int i = 0; i <= 255; ++i) // { // if (!pLexer->description(i).isEmpty()) // { // /*if (blackColor == pLexer->color(i)) // { // pLexer->setColor(lightColor, i); // } // else if (blackColor1 == pLexer->color(i)) // { // pLexer->setColor(lightColor1, i); // } // else if (blackColor2 == pLexer->color(i)) // { // pLexer->setColor(lightColor2, i); // } // else if (blackColor3 == pLexer->color(i)) // { // pLexer->setColor(lightColor3, i); // } // else if (blackColor4 == pLexer->color(i)) // { // pLexer->setColor(lightColor4, i); // }*/ // // if (QtLangSet::s_darkColorMap.contains(pLexer->color(i).name())) // { // pLexer->setColor(QtLangSet::s_darkColorMap.value(pLexer->color(i).name()), i); // } // // 背景也变成暗黑色 // if (StyleSet::foldbgColor != pLexer->paper(i)) // { // pLexer->setPaper(StyleSet::foldbgColor, i); // } // } // } // 默认纸背景色会和QPalette保持一致。但是因为黑色特色,其背景和QPalette不一样,所有需要单独设置一下 // pLexer->setDefaultPaper(StyleSet::foldbgColor); // saveLangeSet(pLexer); // delete pLexer; // } // } //把暗色系下面不容易看清的颜色给替换一下。默认是有风格的,但是默认风格是亮色系的。 //把凡是0x000000的字体,变成0xdedede //凡是0x0000ff的颜色,变成0xffff00 //这个函数没有处理自定义语言。 //void QtLangSet::setAllLangFontFgColorToDarkStyle() //{ // initDarkColorMap(); // // for (int index = 0; index <= L_TXT; ++index) // { // setLangFontFgColorToDarkStyle((LangType)index); // } //} //从默认主题模板创建一份用户的语言风格文件 void QtLangSet::createOneLangStyleFromThemes(int styleId, LangType langId, QString tag) { if (langId == L_GLOBAL) { qDebug("global call"); } //指定从原始模板的主题中读取一份数据 QsciLexer* pLexer = ScintillaEditView::createLexer(langId, tag, true, styleId); if (nullptr != pLexer) { saveLangeSet(pLexer, styleId); delete pLexer; } } //从原始主题模板中,创建一份用户主题文件 void QtLangSet::createUserStyleFormThemes(int styleId) { for (int index = 0; index <= L_TXT; ++index) { createOneLangStyleFromThemes(styleId, (LangType)index); } } //检查当前是否已经存在暗黑色语言配置 //bool QtLangSet::isExistDarkLangSetings() //{ // QString cfgPath = QString("notepad/userstyle/black/AllGlobal"); // QSettings qs(QSettings::IniFormat, QSettings::UserScope, cfgPath); // return QFile::exists(qs.fileName()); //} //检查当前是否已经存在主题配置 bool QtLangSet::isExistThemesSetings(int styleId) { QString cfgPath = QString("notepad/userstyle/%1/AllGlobal").arg(StyleSet::getStyleName(styleId)); QSettings qs(QSettings::IniFormat, QSettings::UserScope, cfgPath); return QFile::exists(qs.fileName()); } //当前主题发生变化 void QtLangSet::on_themesChange(int styleIndex) { //第一次启动时,防止初始情况没有初始化主题,故检测一下isExistThemesSetings if (m_themesId == styleIndex && isExistThemesSetings(styleIndex)) { return; } ui.statusBar->showMessage(tr("themes changing, please waiting ..."), 5000); m_themesId = styleIndex; //这个有个耦合:先要设置QsciLexer的当前主题。只有默认主题才有详细独立的风格。 //非默认主题,其初始风格全是默认样式。 QsciLexer::setCurThemes(m_themesId); //如果不存在主题设置,则从模板里面拷贝一份出来 if (!isExistThemesSetings(styleIndex)) { createUserStyleFormThemes(styleIndex); } StyleSet::setCurrentStyle(styleIndex); NddSetting::updataKeyValueFromNumSets(SKIN_KEY, m_themesId); //这里就要及时切换当前主题,预览颜色 updateThemes(); //下一步就是要更好当前编辑器的语法设置 previewAllGoblalChange(); int row = ui.langListWidget->currentRow(); //手动刷新UI QListWidgetItem* styleItem = ui.langListWidget->item(row); slot_itemSelect(styleItem); m_lastThemesId = m_themesId; ui.statusBar->showMessage(tr("themes changed finished ..."), 5000); } //更新当前编辑框中主题的样式 void QtLangSet::updateThemes() { CCNotePad* pMainNote = dynamic_cast<CCNotePad*>(parent()); if (pMainNote != nullptr) { pMainNote->updateThemes(); } } //增加一个快捷显示全局的按钮,避免用户经常找不到 void QtLangSet::on_showGlobalItem() { if (ui.langListWidget->currentRow() != 0) { ui.langListWidget->setCurrentRow(0); } }
54,603
C++
.cpp
1,709
23.844939
202
0.68366
cxasm/notepad--
5,942
234
284
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
25,195
MediatorDisplay.cpp
cxasm_notepad--/src/MediatorDisplay.cpp
#include "MediatorDisplay.h" //这里如果直接让左右互相同步,互相影响,可能导致混乱。需要一个中间调停者模式,作为中间人去控制同步消息 //中介者模式意图:用一个中介对象来封装一系列的对象交互,中介者使各对象不需要显式地相互引用,从而使其耦合松散,而且可以独立地改变它们之间的交互。 //主要解决:对象与对象之间存在大量的关联关系,这样势必会导致系统的结构变得很复杂,同时若一个对象发生改变,我们也需要跟踪与之相关联的对象,同时做出相应的处理。 //之前不使用该模式时,左右显示同步互相交互,时而发生消息混乱 MediatorDisplay::MediatorDisplay():QObject(nullptr) { m_leftLineNum = 0; m_rightLineNum = 0; m_leftScrollValue = 0; m_rightScrollValue = 0; } MediatorDisplay::~MediatorDisplay() { } void MediatorDisplay::setLeftNum(int value) { m_leftLineNum = value; if (m_leftLineNum != m_rightLineNum) { emit syncCurLineNum(0); } } void MediatorDisplay::setRightNum(int value) { m_rightLineNum = value; if (m_leftLineNum != m_rightLineNum) { emit syncCurLineNum(1); } } int MediatorDisplay::getLeftNum() { return m_leftLineNum; } int MediatorDisplay::getRightNum() { return m_rightLineNum; } void MediatorDisplay::setLeftScrollValue(int value) { if (m_leftScrollValue != value) { m_leftScrollValue = value; } //如果左右不相等,则推动对方去同步 if (m_leftScrollValue != m_rightScrollValue) { emit syncCurScrollValue(0); } } void MediatorDisplay::setRightScrollValue(int value) { if (m_rightScrollValue != value) { m_rightScrollValue = value; } if (m_leftScrollValue != m_rightScrollValue) { emit syncCurScrollValue(1); } } int MediatorDisplay::getLeftScrollValue() { return m_leftScrollValue; } int MediatorDisplay::getRightScrollValue() { return m_rightScrollValue; } void MediatorDisplay::setLeftScrollXValue(int value) { if (m_leftScrollXValue != value) { m_leftScrollXValue = value; } //如果左右不相等,则推动对方去同步 if (m_leftScrollXValue != m_rightScrollXValue) { emit syncCurScrollXValue(0); } } void MediatorDisplay::setRightScrollXValue(int value) { if (m_rightScrollXValue != value) { m_rightScrollXValue = value; } if (m_leftScrollXValue != m_rightScrollXValue) { emit syncCurScrollXValue(1); } } int MediatorDisplay::getLeftScrollXValue() { return m_leftScrollXValue; } int MediatorDisplay::getRightScrollXValue() { return m_rightScrollXValue; }
2,737
C++
.cpp
101
18.633663
81
0.751462
cxasm/notepad--
5,942
234
284
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
25,196
doctypelistview.cpp
cxasm_notepad--/src/doctypelistview.cpp
#include "doctypelistview.h" #include <QInputDialog> #include <QLineEdit> #include <QtDebug> #include <QThread> #include "nddsetting.h" //已知的文档类型 QMap<QString, bool>* DocTypeListView::s_supportFileExts = nullptr; QStringList DocTypeListView::s_supportFileExt = (QStringList ()<< "common" << "ms int/inf" << "c,c++,objc,go" << "java,c#,pascal" \ << "web script" << "public script" << "property script" << "fortran,Tex,SQL" << "misc" \ << "Qt" << "customize"); QMap<QString, bool>* DocTypeListView::s_binFileExts = nullptr; QStringList DocTypeListView::s_extBindFileType; QStringList HEX_FILE_EXTS_LIST = (QStringList() << "exe" << "dll" << "png" << "jpg" << "doc" << "docx" << "ppt" << "pptx" \ << "zip" << "gz" << "rar" << "pdf" << "7z" << "lib" << "so" << "db" << "obj" << "bmp" << "ico" << "qm" << "icns" << "jpeg" << "res" << "exp" << "ilk" << "deb"); QStringList INIT_EXTS_TYPES = (QStringList() << ".txt:.log" << ".ini:.inf" << ".h:.hh:.hpp:.hxx:.c:.cpp:.cxx:.cc:.m:.mm:.vcxproj:.vcproj:.props:vsprops:mainfest:.go:.mod" \ << ".java:.cs:.pas:.pp:.inc" << ".html:.htm:.shtml:.shtm:.hta:.asp:.aspx:.css:.js:.json:.jsm:.jsp:.php:.php3:.php4:.php5:.phps:.phpt:.phtml:.xml:.xhtml:.xht:.xul:.kml:.xaml:.xsml" \ << ".sh:.bsh:.bash:.bat:.cmd:.nsi:.nsh:.lua:.pl:.pm:.py" << ".rc:.as:.mx:.vb:.vbs" << ".f:.for:.f90:.f95:.f2k:.tex:.sql" \ << "nfo:.mak" << ".ui:.pro:.pri:.qrc:.qss"); //20220402发现bug:在1.11中引入深入对比后,会在子线程中调用这个初始化函数。引发了后续的sqlite错误。 //务必要保证这些实例和数据库对象,是在主线程中创建的。 void DocTypeListView::initSupportFileTypes() { assert(QThread::currentThread() == qApp->thread()); if (s_supportFileExts == nullptr) { s_supportFileExts = new QMap<QString, bool>; s_binFileExts = new QMap<QString, bool>; for (int i = 0; i < HEX_FILE_EXTS_LIST.size(); ++i) { s_binFileExts->insert(HEX_FILE_EXTS_LIST.at(i),true); } } else { //已经初始化过了。避免多次 return; } //如果数据库不存在,则使用默认值来进行初始化 if (!NddSetting::isDbExist()) { QStringList types = INIT_EXTS_TYPES; #if 0 types << ".txt:.log" << ".ini:.inf" << ".h:.hh:.hpp:.hxx:.c:.cpp:.cxx:.cc:.m:.mm:.vcxproj:.vcproj:.props:vsprops:mainfest:.go:.mod" \ << ".java:.cs:.pas:.pp:.inc" << ".html:.htm:.shtml:.shtm:.hta:.asp:.aspx:.css:.js:.json:.jsm:.jsp:.php:.php3:.php4:.php5:.phps:.phpt:.phtml:.xml:.xhtml:.xht:.xul:.kml:.xaml:.xsml" \ << ".sh:.bsh:.bash:.bat:.cmd:.nsi:.nsh:.lua:.pl:.pm:.py" << ".rc:.as:.mx:.vb:.vbs" << ".f:.for:.f90:.f95:.f2k:.tex:.sql" \ << "nfo:.mak" << ".ui:.pro:.pri:.qrc"; #endif QString typeStr = types.join(":"); QStringList typeList = typeStr.split(":"); for (QString var : typeList) { if (!var.isEmpty()) { s_supportFileExts->insert(var.mid(1), true); } } s_extBindFileType << types << ""; #if 0 s_extBindFileType << ".txt:.log" << ".ini:.inf" << ".h:.hh:.hpp:.hxx:.c:.cpp:.cxx:.cc:.m:.mm:.vcxproj:.vcproj:.props:vsprops:mainfest:.go:.mod" \ << ".java:.cs:.pas:.pp:.inc" << ".html:.htm:.shtml:.shtm:.hta:.asp:.aspx:.css:.js:.json:.jsm:.jsp:.php:.php3:.php4:.php5:.phps:.phpt:.phtml:.xml:.xhtml:.xht:.xul:.kml:.xaml:.xsml" \ << ".sh:.bsh:.bash:.bat:.cmd:.nsi:.nsh:.lua:.pl:.pm:.py" << ".rc:.as:.mx:.vb:.vbs" << ".f:.for:.f90:.f95:.f2k:.tex:.sql" \ << ".nfo:.mak" << ".ui:.pro:.pri:.qrc" << ""; #endif } else { //从数据库动态读取配置 QString key("typelist"); QString typeList = NddSetting::getKeyValueFromSets(key); if (typeList.isEmpty()) { //没有读取到,这是第一次启动软件,没有写入导致。在这里进行第一次的写入 QStringList types = INIT_EXTS_TYPES; types << ""; #if 0 types << ".txt:.log" << ".ini:.inf" << ".h:.hh:.hpp:.hxx:.c:.cpp:.cxx:.cc:.m:.mm:.vcxproj:.vcproj:.props:vsprops:mainfest:.go:.mod" \ << ".java:.cs:.pas:.pp:.inc" << ".html:.htm:.shtml:.shtm:.hta:.asp:.aspx:.css:.js:.json:.jsm:.jsp:.php:.php3:.php4:.php5:.phps:.phpt:.phtml:.xml:.xhtml:.xht:.xul:.kml:.xaml:.xsml" \ << ".sh:.bsh:.bash:.bat:.cmd:.nsi:.nsh:.lua:.pl:.pm:.py" << ".rc:.as:.mx:.vb:.vbs" << ".f:.for:.f90:.f95:.f2k:.tex:.sql" \ << ".nfo:.mak" << ".ui:.pro:.pri:.qrc" << ""; #endif s_extBindFileType = types; QString typeStr = types.join("|"); NddSetting::addKeyValueToSets(key, typeStr); typeStr.replace('|',':'); QStringList list = typeStr.split(":"); for (QString var : list) { if (!var.isEmpty()) { s_supportFileExts->insert(var.mid(1), true); } } } else { //从数据库中读取的内容进行动态配置 s_extBindFileType = typeList.split("|"); typeList.replace('|', ':'); QStringList list = typeList.split(":"); for (QString var : list) { if (!var.isEmpty()) { s_supportFileExts->insert(var.mid(1), true); } } } } } //是否支持文件后缀名,注意ext必须要带.xxx格式 bool DocTypeListView::isSupportExt(QString ext) { if (s_supportFileExts == nullptr) { initSupportFileTypes(); } return s_supportFileExts->contains(ext); } //是否是二进制格式的后缀文件 bool DocTypeListView::isHexExt(QString ext) { if (s_binFileExts == nullptr) { initSupportFileTypes(); } return s_binFileExts->contains(ext); } DocTypeListView::DocTypeListView(QWidget *parent) : QWidget(parent),m_isDirty(false) { ui.setupUi(this); if (s_supportFileExt.isEmpty()) { s_supportFileExt << "common" << "ms int/inf" << "c,c++,objc,go" << "java,c#,pascal" \ << "web script" << "public script" << "property script" << "fortran,Tex,SQL" << "misc" \ << "Qt" << "customize"; } initSupportFileTypes(); #if 0 if (s_extBindFileType.isEmpty()) { s_extBindFileType << ".txt:.log" << ".ini:.inf" << ".h:.hh:.hpp:.hxx:.c:.cpp:.cxx:.cc:.m:.mm:.vcxproj:.vcproj:.props:vsprops:mainfest:.go:.mod" \ << ".java:.cs:.pas:.pp:.inc" << ".html:.htm:.shtml:.shtm:.hta:.asp:.aspx:.css:js:.json:.jsm:.jsp:.php:.php3:.php4:.php5:.phps:.phpt:.phtml:.xml:.xhtml:.xht:.xul:.kml:.xaml:.xsml" \ << ".sh:.bsh:.bash:.bat:.cmd:.nsi:.nsh:.lua:.pl:.pm:.py" << ".rc:.as:.mx:.vb:.vbs" << ".f:.for:.f90:.f95:.f2k:.tex:.sql" \ << ".nfo:.mak" << ".ui:.pro:.pri:.qrc" << ""; } #endif ui.extListWidget->addItems(s_supportFileExt); connect(ui.extListWidget, &QListWidget::currentRowChanged, this, &DocTypeListView::slot_curRowChanged); setContextMenuPolicy(Qt::CustomContextMenu); m_menu = new QMenu(this); connect(this, &QWidget::customContextMenuRequested, this, &DocTypeListView::slot_customContextMenuRequested); m_menu->addAction("add Custom extension", this, &DocTypeListView::slot_addCustomType); connect(ui.customListWidget, &QListWidget::itemClicked, this, &DocTypeListView::slot_customListItemClicked); connect(ui.typListWidget, &QListWidget::itemClicked, this, &DocTypeListView::slot_typListItemClicked); } DocTypeListView::~DocTypeListView() { save(); } void DocTypeListView::save() { if (m_isDirty) { QString key("typelist"); QString typeStr = s_extBindFileType.join("|"); NddSetting::updataKeyValueFromSets(key, typeStr); m_isDirty = false; } } void DocTypeListView::slot_curRowChanged(int row) { ui.typListWidget->clear(); if (row < s_extBindFileType.count()) { QString typeStr = s_extBindFileType.at(row); if (typeStr.isEmpty()) { return; } QStringList typeList = typeStr.split(":"); if (typeList.size() > 0) { ui.typListWidget->addItems(typeList); } } } void DocTypeListView::slot_customContextMenuRequested(const QPoint& /*pos*/) { m_menu->exec(QCursor::pos()); } void DocTypeListView::slot_addCustomType() { bool ok = false; QString text = QInputDialog::getText(this, tr("input file ext()"), tr("ext (Split With :)"), QLineEdit::Normal, QString(".h:.cpp"), &ok); if (ok && !text.isEmpty()) { text = text.trimmed(); QStringList extList = text.split(":"); ui.customListWidget->addItems(extList); } } void DocTypeListView::slot_add() { int row = ui.customListWidget->currentRow(); if (row < 0) { return; } QListWidgetItem* item = ui.customListWidget->takeItem(row); ui.typListWidget->addItem(item); int index = ui.extListWidget->currentRow(); if (index < s_extBindFileType.size()) { if (!s_extBindFileType[index].isEmpty()) { QString curText = QString(":%1").arg(item->text()); s_extBindFileType[index].append(curText); } else { s_extBindFileType[index].append(item->text()); } QString var = item->text(); if (!var.isEmpty()) { s_supportFileExts->insert(var.mid(1), true); m_isDirty = true; } } } void DocTypeListView::slot_sub() { int row = ui.typListWidget->currentRow(); if (row < 0) { return; } QListWidgetItem* item = ui.typListWidget->takeItem(row); ui.customListWidget->addItem(item); int index = ui.extListWidget->currentRow(); if (index < s_extBindFileType.size()) { QString curText = QString("%1:").arg(item->text()); if (s_extBindFileType[index].contains(curText)) { s_extBindFileType[index].remove(curText); } else if (s_extBindFileType[index].endsWith(item->text())) { int lens = s_extBindFileType[index].size(); int delLens = item->text().size(); if (lens > delLens) { //删除:xxx s_extBindFileType[index].remove(lens - delLens -1, delLens + 1); } else { s_extBindFileType[index].clear(); } } QString var = item->text(); if (!var.isEmpty()) { s_supportFileExts->remove(var.mid(1)); m_isDirty = true; } } } void DocTypeListView::slot_customListItemClicked(QListWidgetItem* /*item*/) { //qDebug() << "custom list item click"; ui.subToolButton->setEnabled(false); ui.addToolButton->setEnabled(true); } void DocTypeListView::slot_typListItemClicked(QListWidgetItem* /*item*/) { //qDebug() << "type list item click"; ui.subToolButton->setEnabled(true); ui.addToolButton->setEnabled(false); }
10,317
C++
.cpp
283
30.971731
186
0.630235
cxasm/notepad--
5,942
234
284
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
25,197
scintillaeditview.cpp
cxasm_notepad--/src/scintillaeditview.cpp
#include "scintillaeditview.h" #include "common.h" #include "rgba_icons.h" #include "ccnotepad.h" #include "styleset.h" #include "qtlangset.h" #include "findwin.h" #include "filemanager.h" #include "shortcutkeymgr.h" #include "markdownview.h" #include <Scintilla.h> #include <SciLexer.h> #include <QImage> #include <Qsci/qscilexerpython.h> #include <Qsci/qscilexerasm.h> #include <Qsci/qscilexerbash.h> #include <Qsci/qscilexerbatch.h> #include <Qsci/qscilexercmake.h> #include <Qsci/qscilexercoffeescript.h> #include <Qsci/qscilexercpp.h> #include <Qsci/qscilexercsharp.h> #include <Qsci/qscilexercss.h> #include <Qsci/qscilexercustom.h> #include <Qsci/qscilexerd.h> #include <Qsci/qscilexerdiff.h> #include <Qsci/qscilexeredifact.h> #include <Qsci/qscilexerfortran.h> #include <Qsci/qscilexerfortran77.h> #include <Qsci/qscilexerhtml.h> #include <Qsci/qscilexeridl.h> #include <Qsci/qscilexerjava.h> #include <Qsci/qscilexerjavascript.h> #include <Qsci/qscilexerjson.h> #include <Qsci/qscilexerlua.h> #include <Qsci/qscilexermakefile.h> #include <Qsci/qscilexermarkdown.h> #include <Qsci/qscilexermatlab.h> #include <Qsci/qscilexeroctave.h> #include <Qsci/qscilexerpascal.h> #include <Qsci/qscilexerperl.h> #include <Qsci/qscilexerpo.h> #include <Qsci/qscilexerpostscript.h> #include <Qsci/qscilexerpov.h> #include <Qsci/qscilexerproperties.h> #include <Qsci/qscilexerpython.h> #include <Qsci/qscilexerr.h> #include <Qsci/qscilexerruby.h> #include <Qsci/qscilexerspice.h> #include <Qsci/qscilexersql.h> #include <Qsci/qscilexertcl.h> #include <Qsci/qscilexertex.h> #include <Qsci/qscilexerverilog.h> #include <Qsci/qscilexervhdl.h> #include <Qsci/qscilexerxml.h> #include <Qsci/qscilexeryaml.h> #include <Qsci/qscilexergo.h> #include <Qsci/qscilexertext.h> #include <Qsci/qscilexernsis.h> #include <Qsci/qscilexerglobal.h> #include <Qsci/qscilexerrust.h> #include <Qsci/qscilexervb.h> #include <QScrollBar> #include <unordered_set> #include <QClipboard> #include <QDesktopServices> #include <QDebug> #include <QMessageBox> #include <stdexcept> #include <mutex> // initialize the static variable #define DEFAULT_FONT_NAME "Courier New" //"Microsoft YaHei" int ScintillaEditView::s_tabLens = 4; //默认不使用tab,使用space替换 bool ScintillaEditView::s_noUseTab = true; int ScintillaEditView::s_bigTextSize = 100; const int ScintillaEditView::_SC_MARGE_LINENUMBER = 0; const int ScintillaEditView::_SC_MARGE_SYBOLE = 1; const int ScintillaEditView::_SC_MARGE_FOLDER = 2; //大文本是分块显示,务必要把真实的偏移行号给显示出来 const int SC_BIGTEXT_LINES = 0; const int MAX_PRE_NEXT_TIMES = 30; const int INIT_BIG_RO_TEXT_LINE_WIDTH = 8; #ifdef Q_OS_WIN LanguageName ScintillaEditView::langNames[L_EXTERNAL + 1] = { {QString("normal"), QString("Normal QString"), QString("Normal text file"), L_TXT, SCLEX_NULL}, {QString("php"), QString("PHP"), QString("PHP Hypertext Preprocessor file"), L_PHP, SCLEX_HTML}, {QString("c"), QString("C"), QString("C source file"), L_C, SCLEX_CPP}, {QString("cpp"), QString("C++"), QString("C++ source file"), L_CPP, SCLEX_CPP}, {QString("cs"), QString("C#"), QString("C# source file"), L_CS, SCLEX_CPP}, {QString("objc"), QString("Objective-C"), QString("Objective-C source file"), L_OBJC, SCLEX_CPP}, {QString("java"), QString("Java"), QString("Java source file"), L_JAVA, SCLEX_CPP}, {QString("rc"), QString("RC"), QString("Windows Resource file"), L_RC, SCLEX_CPP}, {QString("html"), QString("HTML"), QString("Hyper Text Markup Language file"), L_HTML, SCLEX_HTML}, {QString("xml"), QString("XML"), QString("eXtensible Markup Language file"), L_XML, SCLEX_XML}, {QString("makefile"), QString("Makefile"), QString("Makefile"), L_MAKEFILE, SCLEX_MAKEFILE}, {QString("pascal"), QString("Pascal"), QString("Pascal source file"), L_PASCAL, SCLEX_PASCAL}, {QString("batch"), QString("Batch"), QString("Batch file"), L_BATCH, SCLEX_BATCH}, {QString("ini"), QString("ini"), QString("MS ini file"), L_INI, SCLEX_PROPERTIES}, {QString("nfo"), QString("NFO"), QString("MSDOS Style/ASCII Art"), L_ASCII, SCLEX_NULL}, {QString("udf"), QString("udf"), QString("User Defined language file"), L_USER, SCLEX_USER}, {QString("asp"), QString("ASP"), QString("Active Server Pages script file"), L_ASP, SCLEX_HTML}, {QString("sql"), QString("SQL"), QString("Structured Query Language file"), L_SQL, SCLEX_SQL}, {QString("vb"), QString("Visual Basic"), QString("Visual Basic file"), L_VB, SCLEX_VB}, {QString("javascript"), QString("JavaScript"), QString("JavaScript file"), L_JS, L_JAVASCRIPT}, {QString("css"), QString("CSS"), QString("Cascade Style Sheets File"), L_CSS, SCLEX_CSS}, {QString("perl"), QString("Perl"), QString("Perl source file"), L_PERL, SCLEX_PERL}, {QString("python"), QString("Python"), QString("Python file"), L_PYTHON, SCLEX_PYTHON}, {QString("lua"), QString("Lua"), QString("Lua source File"), L_LUA, SCLEX_LUA}, {QString("tex"), QString("TeX"), QString("TeX file"), L_TEX, SCLEX_TEX}, {QString("fortran"), QString("Fortran free form"), QString("Fortran free form source file"), L_FORTRAN, SCLEX_FORTRAN}, {QString("bash"), QString("Shell"), QString("Unix script file"), L_BASH, SCLEX_BASH}, {QString("actionscript"), QString("ActionScript"), QString("Flash ActionScript file"), L_FLASH, SCLEX_CPP}, {QString("nsis"), QString("NSIS"), QString("Nullsoft Scriptable Install System script file"), L_NSIS, SCLEX_NSIS}, {QString("tcl"), QString("TCL"), QString("Tool Command Language file"), L_TCL, SCLEX_TCL}, {QString("lisp"), QString("Lisp"), QString("List Processing language file"), L_LISP, SCLEX_LISP}, {QString("scheme"), QString("Scheme"), QString("Scheme file"), L_SCHEME, SCLEX_LISP}, {QString("asm"), QString("Assembly"), QString("Assembly language source file"), L_ASM, SCLEX_ASM}, {QString("diff"), QString("Diff"), QString("Diff file"), L_DIFF, SCLEX_DIFF}, {QString("props"), QString("Properties file"), QString("Properties file"), L_PROPS, SCLEX_PROPERTIES}, {QString("postscript"), QString("PostScript"), QString("PostScript file"), L_PS, SCLEX_PS}, {QString("ruby"), QString("Ruby"), QString("Ruby file"), L_RUBY, SCLEX_RUBY}, {QString("smalltalk"), QString("Smalltalk"), QString("Smalltalk file"), L_SMALLTALK, SCLEX_SMALLTALK}, {QString("vhdl"), QString("VHDL"), QString("VHSIC Hardware Description Language file"), L_VHDL, SCLEX_VHDL}, {QString("kix"), QString("KiXtart"), QString("KiXtart file"), L_KIX, SCLEX_KIX}, {QString("autoit"), QString("AutoIt"), QString("AutoIt"), L_AU3, SCLEX_AU3}, {QString("caml"), QString("CAML"), QString("Categorical Abstract Machine Language"), L_CAML, SCLEX_CAML}, {QString("ada"), QString("Ada"), QString("Ada file"), L_ADA, SCLEX_ADA}, {QString("verilog"), QString("Verilog"), QString("Verilog file"), L_VERILOG, SCLEX_VERILOG}, {QString("matlab"), QString("MATLAB"), QString("MATrix LABoratory"), L_MATLAB, SCLEX_MATLAB}, {QString("haskell"), QString("Haskell"), QString("Haskell"), L_HASKELL, SCLEX_HASKELL}, {QString("inno"), QString("Inno Setup"), QString("Inno Setup script"), L_INNO, SCLEX_INNOSETUP}, {QString("searchResult"), QString("Internal Search"), QString("Internal Search"), L_SEARCHRESULT, SCLEX_SEARCHRESULT}, {QString("cmake"), QString("CMake"), QString("CMake file"), L_CMAKE, SCLEX_CMAKE}, {QString("yaml"), QString("YAML"), QString("YAML Ain't Markup Language"), L_YAML, SCLEX_YAML}, {QString("cobol"), QString("COBOL"), QString("COmmon Business Oriented Language"), L_COBOL, SCLEX_COBOL}, {QString("gui4cli"), QString("Gui4Cli"), QString("Gui4Cli file"), L_GUI4CLI, SCLEX_GUI4CLI}, {QString("d"), QString("D"), QString("D programming language"), L_D, SCLEX_D}, {QString("powershell"), QString("PowerShell"), QString("Windows PowerShell"), L_POWERSHELL, SCLEX_POWERSHELL}, {QString("r"), QString("R"), QString("R programming language"), L_R, SCLEX_R}, {QString("jsp"), QString("JSP"), QString("JavaServer Pages script file"), L_JSP, SCLEX_HTML}, {QString("coffeescript"), QString("CoffeeScript"), QString("CoffeeScript file"), L_COFFEESCRIPT, SCLEX_COFFEESCRIPT}, {QString("json"), QString("json"), QString("JSON file"), L_JSON, SCLEX_JSON }, {QString("javascript.js"), QString("JavaScript"), QString("JavaScript file"), L_JAVASCRIPT, SCLEX_CPP }, {QString("fortran77"), QString("Fortran fixed form"), QString("Fortran fixed form source file"), L_FORTRAN_77, SCLEX_F77}, {QString("baanc"), QString("BaanC"), QString("BaanC File"), L_BAANC, SCLEX_BAAN }, {QString("srec"), QString("S-Record"), QString("Motorola S-Record binary data"), L_SREC, SCLEX_SREC}, {QString("ihex"), QString("Intel HEX"), QString("Intel HEX binary data"), L_IHEX, SCLEX_IHEX}, {QString("tehex"), QString("Tektronix extended HEX"), QString("Tektronix extended HEX binary data"), L_TEHEX, SCLEX_TEHEX}, {QString("swift"), QString("Swift"), QString("Swift file"), L_SWIFT, SCLEX_CPP}, {QString("asn1"), QString("ASN.1"), QString("Abstract Syntax Notation One file"), L_ASN1, SCLEX_ASN1}, {QString("avs"), QString("AviSynth"), QString("AviSynth scripts files"), L_AVS, SCLEX_AVS}, {QString("blitzbasic"), QString("BlitzBasic"), QString("BlitzBasic file"), L_BLITZBASIC, SCLEX_BLITZBASIC}, {QString("purebasic"), QString("PureBasic"), QString("PureBasic file"), L_PUREBASIC, SCLEX_PUREBASIC}, {QString("freebasic"), QString("FreeBasic"), QString("FreeBasic file"), L_FREEBASIC, SCLEX_FREEBASIC}, {QString("csound"), QString("Csound"), QString("Csound file"), L_CSOUND, SCLEX_CSOUND}, {QString("erlang"), QString("Erlang"), QString("Erlang file"), L_ERLANG, SCLEX_ERLANG}, {QString("escript"), QString("ESCRIPT"), QString("ESCRIPT file"), L_ESCRIPT, SCLEX_ESCRIPT}, {QString("forth"), QString("Forth"), QString("Forth file"), L_FORTH, SCLEX_FORTH}, {QString("latex"), QString("LaTeX"), QString("LaTeX file"), L_LATEX, SCLEX_LATEX}, {QString("mmixal"), QString("MMIXAL"), QString("MMIXAL file"), L_MMIXAL, SCLEX_MMIXAL}, {QString("nim"), QString("Nim"), QString("Nim file"), L_NIM, SCLEX_NIMROD}, {QString("nncrontab"), QString("Nncrontab"), QString("extended crontab file"), L_NNCRONTAB, SCLEX_NNCRONTAB}, {QString("oscript"), QString("OScript"), QString("OScript source file"), L_OSCRIPT, SCLEX_OSCRIPT}, {QString("rebol"), QString("REBOL"), QString("REBOL file"), L_REBOL, SCLEX_REBOL}, {QString("registry"), QString("registry"), QString("registry file"), L_REGISTRY, SCLEX_REGISTRY}, {QString("rust"), QString("Rust"), QString("Rust file"), L_RUST, SCLEX_RUST}, {QString("spice"), QString("Spice"), QString("spice file"), L_SPICE, SCLEX_SPICE}, {QString("txt2tags"), QString("txt2tags"), QString("txt2tags file"), L_TXT2TAGS, SCLEX_TXT2TAGS}, {QString("visualprolog"), QString("Visual Prolog"), QString("Visual Prolog file"), L_VISUALPROLOG, SCLEX_VISUALPROLOG}, {QString("typescript"), QString("TypeScript"), QString("TypeScript file"), L_TYPESCRIPT, SCLEX_CPP}, {QString("edifact"), QString("Edifact"), QString("Edifact file"), L_EDIFACT, SCLEX_EDIFACT}, {QString("markdown"), QString("Markdown"), QString("Markdown file"), L_MARKDOWN, SCLEX_MARKDOWN}, {QString("octave"), QString("Octave"), QString("Octave file"), L_OCTAVE, SCLEX_OCTAVE}, {QString("po"), QString("PO"), QString("PO file"), L_PO, SCLEX_PO}, {QString("pov"), QString("POV"), QString("POV file"), L_POV, SCLEX_POV}, {QString("avs"), QString("AVS"), QString("AVS file"), L_AVS, SCLEX_AVS}, {QString("idl"), QString("IDL"), QString("IDL file"), L_IDL, SCLEX_IDL}, {QString("go"), QString("GO"), QString("GO file"), L_GO, SCLEX_GO}, {QString("txt"), QString("TEXT"), QString("TXT file"), L_TXT, SCLEX_TXT}, {QString("ext"), QString("External"), QString("External"), L_EXTERNAL, SCLEX_NULL} }; #endif ScintillaEditView::ScintillaEditView(QWidget *parent,bool isBigText) : QsciScintilla(parent), m_NoteWin(nullptr), m_preFirstLineNum(0), m_curPos(0), m_hasHighlight(false), m_bookmarkPng(nullptr), m_styleColorMenu(nullptr), m_isBigText(isBigText), m_curBlockLineStartNum(0) #ifdef Q_OS_WIN ,m_isInTailStatus(false) #endif { init(); } ScintillaEditView::~ScintillaEditView() { releaseAllMark(); if (m_bookmarkPng != nullptr) { delete m_bookmarkPng; } #ifdef Q_OS_WIN deleteTailFileThread(); #endif } ScintillaEditView::ScintillaEditView():QsciScintilla(nullptr),m_NoteWin(nullptr), m_preFirstLineNum(0), m_curPos(0), m_hasHighlight(false), m_bookmarkPng(nullptr), m_styleColorMenu(nullptr), m_isBigText(false), m_curBlockLineStartNum(0) #ifdef Q_OS_WIN , m_isInTailStatus(false) #endif { m_pScintillaFunc = (SCINTILLA_FUNC)this->SendScintillaPtrResult(SCI_GETDIRECTFUNCTION); m_pScintillaPtr = (SCINTILLA_PTR)this->SendScintillaPtrResult(SCI_GETDIRECTPOINTER); if (!m_pScintillaFunc) { throw std::runtime_error("ScintillaEditView::init : SCI_GETDIRECTFUNCTION message failed"); } if (!m_pScintillaPtr) { throw std::runtime_error("ScintillaEditView::init : SCI_GETDIRECTPOINTER message failed"); } } ScintillaEditView* ScintillaEditView::createEditForSearch() { return new ScintillaEditView(); } //截获ESC键盘,让界面去退出当前的子界面 void ScintillaEditView::keyPressEvent(QKeyEvent* event) { switch (event->key()) { case Qt::Key_Escape: if (m_NoteWin != nullptr) { m_NoteWin->on_quitActiveWindow(); } break; default: break; } return QsciScintilla::keyPressEvent(event); } void ScintillaEditView::mouseReleaseEvent(QMouseEvent* ev) { QsciScintilla::mouseReleaseEvent(ev); if (ev->button() == Qt::LeftButton) { if (hasSelectedText()) { emit delayWork(); } } } void ScintillaEditView::setBigTextMode(bool isBigText) { m_isBigText = isBigText; } void ScintillaEditView::setLexer(QsciLexer * lexer) { QsciScintilla::setLexer(lexer); if (lexer != nullptr && lexer->lexerId() == L_TXT) { showMargin(_SC_MARGE_FOLDER,false); updateThemes(); } else if(lexer != nullptr && lexer->lexerId() != L_TXT) { showMargin(_SC_MARGE_FOLDER, true); updateThemes(); } } void ScintillaEditView::setNoteWidget(QWidget * win) { CCNotePad* pv = dynamic_cast<CCNotePad*>(win); if (pv != nullptr) { m_NoteWin = pv; if (m_styleColorMenu != nullptr) { m_styleColorMenu->addAction(tr("Clear Select"), m_NoteWin, &CCNotePad::slot_clearWordHighlight); m_styleColorMenu->addAction(tr("Clear All"), m_NoteWin, &CCNotePad::slot_clearMark); } } } void ScintillaEditView::updateLineNumbersMargin(bool forcedToHide) { if (forcedToHide) { execute(SCI_SETMARGINWIDTHN, _SC_MARGE_LINENUMBER, (sptr_t)0); } else { updateLineNumberWidth(0); } } //根据现有滚动条来决定是否更新屏幕线宽长度。每滚动200个单位必须调整line宽 void ScintillaEditView::autoAdjustLineWidth(int xScrollValue) { //如果是大文本模式,行号长度目前是固定不变的,不需要动态调整。 if (m_isBigText) { return; } if (std::abs(xScrollValue - m_preFirstLineNum) > 200) { m_preFirstLineNum = xScrollValue; updateLineNumberWidth(1); } } void ScintillaEditView::updateLineNumberWidth(int lineNumberMarginDynamicWidth) { if (!m_isBigText) { auto linesVisible = execute(SCI_LINESONSCREEN); if (linesVisible) { int nbDigits = 0; if (lineNumberMarginDynamicWidth != 0) { int firstVisibleLineVis = execute(SCI_GETFIRSTVISIBLELINE); int lastVisibleLineVis = linesVisible + firstVisibleLineVis + 1; int lastVisibleLineDoc = execute(SCI_DOCLINEFROMVISIBLE, (long)lastVisibleLineVis); nbDigits = nbDigitsFromNbLines(lastVisibleLineDoc); nbDigits = nbDigits < 4 ? 4 : nbDigits; } else { int nbLines = execute(SCI_GETLINECOUNT); nbDigits = nbDigitsFromNbLines(nbLines); nbDigits = nbDigits < 4 ? 4 : nbDigits; } auto pixelWidth = 6 + nbDigits * execute(SCI_TEXTWIDTH, STYLE_LINENUMBER, reinterpret_cast<sptr_t>("8")); execute(SCI_SETMARGINWIDTHN, _SC_MARGE_LINENUMBER, pixelWidth); } } else { int pixelWidth = 6 + INIT_BIG_RO_TEXT_LINE_WIDTH * execute(SCI_TEXTWIDTH, STYLE_LINENUMBER, reinterpret_cast<sptr_t>("8")); execute(SCI_SETMARGINWIDTHN, SC_BIGTEXT_LINES, pixelWidth); } } void ScintillaEditView::showMargin(int whichMarge, bool willBeShowed) { if (whichMarge == _SC_MARGE_LINENUMBER) { bool forcedToHide = !willBeShowed; updateLineNumbersMargin(forcedToHide); } else { //后面再来解决像素的问题 //DPIManager& dpiManager = NppParameters::getInstance()._dpiManager; int width = 3; if (whichMarge == _SC_MARGE_SYBOLE) width = 14; else if (whichMarge == _SC_MARGE_FOLDER) width = 14; execute(SCI_SETMARGINWIDTHN, whichMarge, willBeShowed ? width : 0); } } sptr_t ScintillaEditView::execute(quint32 Msg, uptr_t wParam, sptr_t lParam) const { try { return (m_pScintillaFunc) ? m_pScintillaFunc(m_pScintillaPtr, Msg, wParam, lParam) : -1; } catch (...) { return -1; } }; QString ScintillaEditView::getTagByLexerId(int lexerId) { switch (lexerId) { case L_PHP: return "php"; case L_HTML: return ("html"); case L_ASP: return ("asp"); case L_JSP: return("jsp"); case L_C: return("c"); case L_RC: return("rc"); case L_CPP: return "cpp"; case L_OBJC: return ("objc"); case L_CS: return ("csharp"); case L_JAVA: return ("java"); case L_XML: return "xml"; case L_MAKEFILE: return "makefile"; case L_PASCAL: return "pascal"; case L_BATCH: return "batch"; case L_INI: return("ini"); case L_ASCII: break; case L_USER: break; case L_SQL: return "sql"; case L_VB: return "vb"; case L_CSS: return "css"; case L_PERL: return "perl"; case L_PYTHON: return "python"; case L_LUA: return "lua"; case L_TEX: break; case L_FORTRAN: return "fortran"; case L_BASH: return "bash"; case L_FLASH: return("flash"); case L_MATLAB: return ("matlab"); case L_MARKDOWN: return("markdown"); case L_NSIS: return "nsis"; case L_TCL: return "tcl"; case L_LISP: break; case L_SCHEME: break; case L_ASM: break; case L_DIFF: return "diff"; case L_PROPS: return "props"; case L_PS: break; case L_R: return "r"; case L_RUBY: return "ruby"; case L_SMALLTALK: break; case L_VHDL: return "vhdl"; case L_KIX: break; case L_AU3: break; case L_CAML: break; case L_ADA: break; case L_VERILOG: return "verilog"; case L_HASKELL: break; case L_INNO: break; case L_SEARCHRESULT: break; case L_CMAKE: return "cmake"; case L_YAML: return "yaml"; case L_COBOL: break; case L_GUI4CLI: break; case L_D: break; case L_POWERSHELL: break; case L_COFFEESCRIPT: return "coffeescript"; case L_JSON: return "json"; case L_JAVASCRIPT: return ("javascript"); case L_FORTRAN_77: return "fortran77"; case L_BAANC: break; case L_SREC: break; case L_IHEX: break; case L_TEHEX: break; case L_SWIFT: break; case L_ASN1: break; //case L_AVS: // return "avs"; case L_BLITZBASIC: break; case L_PUREBASIC: break; case L_FREEBASIC: break; case L_CSOUND: break; case L_ERLANG: break; case L_ESCRIPT: break; case L_FORTH: break; case L_LATEX: break; case L_MMIXAL: break; case L_NIM: break; case L_NNCRONTAB: break; case L_OSCRIPT: break; case L_REBOL: break; case L_REGISTRY: break; case L_RUST: return "rust"; case L_SPICE: return "spice"; case L_TXT2TAGS: break; case L_VISUALPROLOG: break; case L_TYPESCRIPT: return("typescript"); case L_EXTERNAL: break; case L_IDL: return("idl"); case L_GO: return("go"); case L_GLOBAL: return("AllGlobal"); case L_TXT: return("txt"); case L_USER_TXT: break; case L_USER_CPP: break; default: break; } return ""; } //status : true 表示存在, false 表示不存在 //tag,只有在用户自定义语法是,才需要给出。内部自带的语法不需要给出 //isOrigin:是否原生lexer,即不读取用户修改过的配置风格 QsciLexer* ScintillaEditView::createLexer(int lexerId, QString tag, bool isOrigin, int styleId) { QsciLexer* ret = nullptr; switch (lexerId) { case L_PHP: ret = new QsciLexerHTML(); ret->setLexerTag("php"); ret->setCommentLineSymbol("//"); ret->setCommentStart("/*"); ret->setCommentEnd("*/"); break; case L_HTML: ret = new QsciLexerHTML(); ret->setLexerTag("html"); break; case L_ASP: ret = new QsciLexerHTML(); ret->setLexerTag("asp"); break; case L_JSP: ret = new QsciLexerHTML(); ret->setLexerTag("jsp"); break; case L_C: ret = new QsciLexerCPP(); ret->setLexerTag("c"); break; case L_RC: ret = new QsciLexerCPP(); ret->setLexerTag("rc"); break; case L_CPP: ret = new QsciLexerCPP(); break; case L_OBJC: ret = new QsciLexerCPP(); ret->setLexerTag("objc"); break; case L_CS: ret = new QsciLexerCSharp(); ret->setLexerTag("csharp"); break; case L_JAVA: ret = new QsciLexerJava(); ret->setLexerTag("java"); break; case L_XML: ret = new QsciLexerXML(); break; case L_MAKEFILE: ret = new QsciLexerMakefile(); break; case L_PASCAL: ret = new QsciLexerPascal(); break; case L_BATCH: ret = new QsciLexerBatch(); break; case L_INI: ret = new QsciLexerProperties(); ret->setLexerTag("ini"); break; case L_ASCII: break; case L_USER: break; case L_SQL: ret = new QsciLexerSQL(); break; case L_VB: ret = new QsciLexerVB(); break; case L_CSS: ret = new QsciLexerCSS(); break; case L_PERL: ret = new QsciLexerPerl(); break; case L_PYTHON: ret = new QsciLexerPython(); break; case L_LUA: ret = new QsciLexerLua(); break; case L_TEX: break; case L_FORTRAN: ret = new QsciLexerFortran(); break; case L_BASH: ret = new QsciLexerBash(); break; case L_FLASH: ret = new QsciLexerCPP(); ret->setLexerTag("flash"); break; case L_MATLAB: ret = new QsciLexerMatlab(); break; case L_MARKDOWN: ret = new QsciLexerMarkdown(); break; case L_NSIS: ret = new QsciLexerNsis(); break; case L_TCL: ret = new QsciLexerTCL(); break; case L_LISP: break; case L_SCHEME: break; case L_ASM: ret = new QsciLexerAsm(); break; case L_DIFF: ret = new QsciLexerDiff(); break; case L_PROPS: ret = new QsciLexerProperties(); break; case L_PS: break; case L_R: ret = new QsciLexerR(); break; case L_RUBY: ret = new QsciLexerRuby(); break; case L_SMALLTALK: break; case L_VHDL: ret = new QsciLexerVHDL(); break; case L_KIX: break; case L_AU3: break; case L_CAML: break; case L_ADA: break; case L_VERILOG: ret = new QsciLexerVerilog(); break; case L_HASKELL: break; case L_INNO: break; case L_SEARCHRESULT: break; case L_CMAKE: ret = new QsciLexerCMake(); break; case L_YAML: ret = new QsciLexerYAML(); break; case L_COBOL: break; case L_GUI4CLI: break; case L_D: break; case L_POWERSHELL: break; case L_COFFEESCRIPT: ret = new QsciLexerCoffeeScript(); break; case L_JSON: ret = new QsciLexerJSON(); break; case L_JAVASCRIPT: ret = new QsciLexerJavaScript(); ret->setLexerTag("javascript"); break; case L_FORTRAN_77: ret = new QsciLexerFortran77(); break; case L_BAANC: break; case L_SREC: break; case L_IHEX: break; case L_TEHEX: break; case L_SWIFT: break; case L_ASN1: break; case L_AVS: //ret = new QsciLexerAVS(); break; case L_BLITZBASIC: break; case L_PUREBASIC: break; case L_FREEBASIC: break; case L_CSOUND: break; case L_ERLANG: break; case L_ESCRIPT: break; case L_FORTH: break; case L_LATEX: break; case L_MMIXAL: break; case L_NIM: break; case L_NNCRONTAB: break; case L_OSCRIPT: break; case L_REBOL: break; case L_REGISTRY: break; case L_RUST: ret = new QsciLexerRust(); break; case L_SPICE: ret = new QsciLexerSpice(); break; case L_TXT2TAGS: break; case L_VISUALPROLOG: break; case L_TYPESCRIPT: ret = new QsciLexerCPP(); ret->setLexerTag("typescript"); break; case L_EXTERNAL: break; case L_IDL: ret = new QsciLexerIDL(); ret->setLexerTag("idl"); break; case L_GO: ret = new QsciLexerGO(); ret->setLexerTag("go"); break; case L_GLOBAL: ret = new QsciLexerGlobal(); ret->setLexerTag("AllGlobal"); break; case L_TXT: ret = new QsciLexerText(); ret->setLexerTag("txt"); break; case L_USER_TXT: //使用txt的语法解析器,但是自定义关键字,自定义tag语言标签。下同 ret = new QsciLexerText(); ret->setLexerTag(tag); ret->setIsUserDefineKeywords(true); break; case L_USER_CPP: ret = new QsciLexerCPP(); ret->setLexerTag(tag); ret->setIsUserDefineKeywords(true); break; default: break; } if (ret != nullptr) { ret->setLexerId(lexerId); if (!isOrigin) { QtLangSet::readLangSettings(ret, ret->lexerTag(), styleId); } else { //如果是读取原生风格,则只有默认主题具备,其余主题要从模板中加载 QtLangSet::readLangOriginSettings(ret, ret->lexerTag(), styleId); } } return ret; } void ScintillaEditView::appendMarkRecord(FindRecords * r) { m_curMarkList.append(r); } void ScintillaEditView::releaseAllMark() { for (int i = 0; i < m_curMarkList.size(); ++i) { delete m_curMarkList.at(i); } m_curMarkList.clear(); } QList<FindRecords *>& ScintillaEditView::getCurMarkRecord() { return m_curMarkList; } ////调整颜色 //void ScintillaEditView::adjuctSkinStyle() //{ // if (StyleSet::m_curStyleId != BLACK_SE) // { // setMarginsForegroundColor(QColor(0x80, 0x80, 0x80)); //默认0x80, 0x80, 0x80 // } // else // { // setMarginsForegroundColor(QColor(0xde, 0xde, 0xde)); //默认0x80, 0x80, 0x80 // } // setMarginsBackgroundColor(StyleSet::marginsBackgroundColor); // // setMarginBackgroundColor(_SC_MARGE_SYBOLE, StyleSet::bookmarkBkColor); // setFoldMarginColors(StyleSet::marginsBackgroundColor, StyleSet::marginsBackgroundColor); // setStyleOptions(); //} void ScintillaEditView::setIndentGuide(bool willBeShowed) { QsciLexer* pLexer = this->lexer(); if (nullptr == pLexer) { return; } const int docIndentMode = (pLexer->lexerId() == L_PYTHON) ? SC_IV_LOOKFORWARD : SC_IV_LOOKBOTH; execute(SCI_SETINDENTATIONGUIDES, willBeShowed ? docIndentMode : SC_IV_NONE); QsciScintilla::setIndentGuide(willBeShowed); } void ScintillaEditView::init() { m_pScintillaFunc = (SCINTILLA_FUNC)this->SendScintillaPtrResult(SCI_GETDIRECTFUNCTION); m_pScintillaPtr = (SCINTILLA_PTR)this->SendScintillaPtrResult(SCI_GETDIRECTPOINTER); if (!m_pScintillaFunc) { throw std::runtime_error("ScintillaEditView::init : SCI_GETDIRECTFUNCTION message failed"); } if (!m_pScintillaPtr) { throw std::runtime_error("ScintillaEditView::init : SCI_GETDIRECTPOINTER message failed"); } if (m_isBigText) { this->setMarginType(SC_BIGTEXT_LINES, TextMargin); } else { //开启行号marge setMarginLineNumbers(_SC_MARGE_LINENUMBER, true); showMargin(_SC_MARGE_LINENUMBER, true); //通过fold发现,尽量使用qscint的功能,因为他做了大量封装和简化 setFolding(BoxedTreeFoldStyle, _SC_MARGE_FOLDER); } //行号、符号、折叠。中间符号留一个很小的间隔。用于圆形的标记符号 showMargin(_SC_MARGE_SYBOLE, true); setMarginType(_SC_MARGE_SYBOLE, QsciScintilla::SymbolMarginColor); m_bookmarkPng = new QPixmap(QString(":/Resources/img/bookmark.png")); markerDefine(*m_bookmarkPng, _SC_MARGE_SYBOLE); setMarginSensitivity(_SC_MARGE_SYBOLE, true); connect(this, &QsciScintilla::marginClicked, this, &ScintillaEditView::slot_bookMarkClicked); //开始括号匹配,比如html的<>,开启前后这类字段的匹配 setBraceMatching(SloppyBraceMatch); //自动补全效果不好,不开启20211017 //setAutoCompletionSource(QsciScintilla::AcsAPIs); //设置源,自动补全所有地方出现的 //setAutoCompletionCaseSensitivity(true); //设置自动补全大小写敏感 //setAutoCompletionThreshold(1); //设置每输入一个字符就会出现自动补全的提示 //设置字体 QFont font(DEFAULT_FONT_NAME, 11, QFont::Normal); setFont(font); setMarginsFont(font); execute(SCI_SETTABWIDTH, ScintillaEditView::s_tabLens); //使用空格替换tab setIndentationsUseTabs(!ScintillaEditView::s_noUseTab); //这个无比要设置false,否则双击后高亮单词,拷贝时会拷贝多个选择。 execute(SCI_SETMULTIPLESELECTION, true); execute(SCI_SETADDITIONALSELECTIONTYPING, true); execute(SCI_SETMULTIPASTE, SC_MULTIPASTE_EACH); execute(SCI_SETADDITIONALCARETSVISIBLE, true); execute(SCI_SETVIRTUALSPACEOPTIONS, SCVS_RECTANGULARSELECTION); //execute(SCI_SETSELFORE, true, 0x0); //execute(SCI_SETSELBACK, true, 0x9bff9b); //0x00ffff原来的黄色 //设置查找到Mark的风格。定义其前景颜色和形状 execute(SCI_INDICSETSTYLE, SCE_UNIVERSAL_FOUND_STYLE_EXT5, INDIC_ROUNDBOX); execute(SCI_INDICSETALPHA, SCE_UNIVERSAL_FOUND_STYLE_EXT5, 130); execute(SCI_INDICSETUNDER, SCE_UNIVERSAL_FOUND_STYLE_EXT5, false); //execute(SCI_INDICSETFORE, SCE_UNIVERSAL_FOUND_STYLE_EXT5, 0x00ffff); //设置查找到Mark的风格。定义其前景颜色和形状 execute(SCI_INDICSETSTYLE, SCE_UNIVERSAL_FOUND_STYLE_EXT4, INDIC_ROUNDBOX); execute(SCI_INDICSETALPHA, SCE_UNIVERSAL_FOUND_STYLE_EXT4, 130); execute(SCI_INDICSETUNDER, SCE_UNIVERSAL_FOUND_STYLE_EXT4, false); //execute(SCI_INDICSETFORE, SCE_UNIVERSAL_FOUND_STYLE_EXT4, 0xffff00); //设置查找到Mark的风格。定义其前景颜色和形状 execute(SCI_INDICSETSTYLE, SCE_UNIVERSAL_FOUND_STYLE_EXT3, INDIC_ROUNDBOX); execute(SCI_INDICSETALPHA, SCE_UNIVERSAL_FOUND_STYLE_EXT3, 130); execute(SCI_INDICSETUNDER, SCE_UNIVERSAL_FOUND_STYLE_EXT3, false); //execute(SCI_INDICSETFORE, SCE_UNIVERSAL_FOUND_STYLE_EXT3, 0x0080ff); //设置查找到Mark的风格。定义其前景颜色和形状 execute(SCI_INDICSETSTYLE, SCE_UNIVERSAL_FOUND_STYLE_EXT2, INDIC_ROUNDBOX); execute(SCI_INDICSETALPHA, SCE_UNIVERSAL_FOUND_STYLE_EXT2, 130); execute(SCI_INDICSETUNDER, SCE_UNIVERSAL_FOUND_STYLE_EXT2, false); //execute(SCI_INDICSETFORE, SCE_UNIVERSAL_FOUND_STYLE_EXT2, 0xff0080); //设置查找到Mark的风格。定义其前景颜色和形状 execute(SCI_INDICSETSTYLE, SCE_UNIVERSAL_FOUND_STYLE_EXT1, INDIC_ROUNDBOX); execute(SCI_INDICSETALPHA, SCE_UNIVERSAL_FOUND_STYLE_EXT1, 130); execute(SCI_INDICSETUNDER, SCE_UNIVERSAL_FOUND_STYLE_EXT1, false); //execute(SCI_INDICSETFORE, SCE_UNIVERSAL_FOUND_STYLE_EXT1, 0xff8000); //下面这两个是HTML文件的tag高亮的表示。 execute(SCI_INDICSETSTYLE, SCE_UNIVERSAL_TAGMATCH, INDIC_STRAIGHTBOX); execute(SCI_INDICSETALPHA, SCE_UNIVERSAL_TAGMATCH, 100); execute(SCI_INDICSETUNDER, SCE_UNIVERSAL_TAGMATCH, false); //execute(SCI_INDICSETFORE, SCE_UNIVERSAL_TAGMATCH, 0xff0080); execute(SCI_INDICSETSTYLE, SCE_UNIVERSAL_TAGATTR, INDIC_STRAIGHTBOX); execute(SCI_INDICSETALPHA, SCE_UNIVERSAL_TAGATTR, 100); execute(SCI_INDICSETUNDER, SCE_UNIVERSAL_TAGATTR, false); //execute(SCI_INDICSETFORE, SCE_UNIVERSAL_TAGATTR, 0x00ffff); //双击后同样的字段进行高亮 execute(SCI_INDICSETSTYLE, SCE_UNIVERSAL_FOUND_STYLE_SMART, INDIC_ROUNDBOX); execute(SCI_INDICSETALPHA, SCE_UNIVERSAL_FOUND_STYLE_SMART, 100); execute(SCI_INDICSETUNDER, SCE_UNIVERSAL_FOUND_STYLE_SMART, false); //execute(SCI_INDICSETFORE, SCE_UNIVERSAL_FOUND_STYLE_SMART, 0x00ff00); //设置空白字符的默认前景色 //execute(SCI_SETWHITESPACEFORE, true, 0x6ab5ff); execute(SCI_SETWHITESPACESIZE,3); setCaretLineVisible(true); //统一设置全局前景、背景、字体大小三个要素 updateThemes(); //记住position变化。不能使用cursorPositionChanged,因为他的列考虑uft8字符,中文一个也算1个,每次列不一定相等。 //要使用自定义的cursorPosChange,跟踪的是SCI_GETCURRENTPOS 的值。换行才会触发这个cursorPosChange。自定义的信号 connect(this,&QsciScintilla::cursorPosChange,this,&ScintillaEditView::slot_linePosChanged, Qt::QueuedConnection); connect(this, &QsciScintilla::selectionChanged, this, &ScintillaEditView::slot_clearHightWord, Qt::QueuedConnection); execute(SCI_SETSCROLLWIDTH, 1); connect(this->verticalScrollBar(), &QScrollBar::valueChanged, this, &ScintillaEditView::slot_scrollYValueChange); connect(this, &ScintillaEditView::delayWork, this,&ScintillaEditView::slot_delayWork, Qt::QueuedConnection); //设置换行符号的格式 #if defined(Q_OS_WIN) execute(SCI_SETEOLMODE, SC_EOL_CRLF); #elif !defined(Q_OS_MAC) execute(SCI_SETEOLMODE, SC_EOL_CR); #elif !defined(Q_OS_UNIX) execute(SCI_SETEOLMODE, SC_EOL_LF); #endif //开启新行自动缩进 setAutoIndent(true); //开启后可以保证长行在滚动条下完整显示 execute(SCI_SETSCROLLWIDTHTRACKING, true); } //大文本不能显示行号,其实显示的是每一行的地址。 //因为要跳转,所以没法实时计算当前位置所在的行号 void ScintillaEditView::showBigTextLineAddr(qint64 fileOffset) { int nbDigits = 0; if (fileOffset < 0xffffffff) { nbDigits = 9; } else { nbDigits = 13; } char* lineString = new char[17]; memset(lineString, 0, 17); auto pixelWidth = 6 + nbDigits * execute(SCI_TEXTWIDTH, STYLE_LINENUMBER, reinterpret_cast<sptr_t>("8")); this->execute(SCI_SETMARGINWIDTHN, SC_BIGTEXT_LINES, pixelWidth); int lineNums = this->lines(); int lineLength = 0; int style = STYLE_LINENUMBER; for (int i = 0; i < lineNums; ++i) { memset(lineString, 0, 17); lineLength = this->lineLength(i); if (fileOffset < 0xffffffff) { sprintf(lineString, "%08llX ", fileOffset); } else { sprintf(lineString, "%012llX ", fileOffset); } QString num(lineString); fileOffset += lineLength; this->setMarginText(i, num, style); } delete[]lineString; } void ScintillaEditView::clearSuperBitLineCache() { m_addrLineNumMap.clear(); } //20230116新增,尽可能的还是显示行号。如果发生了跳转,则没有办法计算前面的行号, //则只能显示地址。如果没跳转,而是动态顺序翻页,则可以显示行号 //20230201发现一个问题。底层qscint是按照utf8字节流来计算字符大小的。如果原始文件的编码 //不是utf8,比如GBK LE等,则大小是不能统一的。这是一个显示问题,但是不影响什么。 //通过this->lineLength(i);来计算是以utf8计算。 void ScintillaEditView::showBigTextLineAddr(qint64 fileOffset, qint64 fileEndOffset) { int nbDigits = 0; if (fileOffset < 0xffffffff) { nbDigits = INIT_BIG_RO_TEXT_LINE_WIDTH; } else { nbDigits = 12; } char* lineString = new char[17]; memset(lineString, 0, 17); auto pixelWidth = 6 + nbDigits * execute(SCI_TEXTWIDTH, STYLE_LINENUMBER, reinterpret_cast<sptr_t>("8")); this->execute(SCI_SETMARGINWIDTHN, SC_BIGTEXT_LINES, pixelWidth); int lineNums = this->lines(); int lineLength = 0; int style = STYLE_LINENUMBER; quint32 startLineNumOffset = 0; quint32 endLineNumOffset = 0; bool isShowLineNum = false; //显示行号还是地址 bool startLineExist = false; bool endLineExist = false; if (fileOffset == 0) { isShowLineNum = true; startLineExist = true; m_addrLineNumMap.insert(0, 1); //0地址对应第1行 m_addrLineNumMap.insert(fileEndOffset, lineNums+1); //fileEndOffset地址对应最后一行 } if (lineNums >= 1) { if (m_addrLineNumMap.contains(fileOffset)) { isShowLineNum = true; startLineExist = true; startLineNumOffset = m_addrLineNumMap.value(fileOffset); } else if (m_addrLineNumMap.contains(fileEndOffset)) { isShowLineNum = true; endLineExist = true; endLineNumOffset = m_addrLineNumMap.value(fileEndOffset); } } //不存在行号,只能显示地址 if (!isShowLineNum) { for (int i = 0; i < lineNums; ++i) { memset(lineString, 0, 17); lineLength = this->lineLength(i); if (fileOffset < 0xffffffff) { sprintf(lineString, "%08llX ", fileOffset); } else { sprintf(lineString, "%012llX ", fileOffset); } QString num(lineString); fileOffset += lineLength; this->setMarginText(i, num, style); } } else { //首行地址存在,从头到尾增加行号 if (startLineExist) { for (int i = 0; i < lineNums; ++i) { if (i == (lineNums - 1)) { //m_addrLineNumMap.insert(fileOffset, startLineNumOffset + i); m_addrLineNumMap.insert(fileEndOffset, startLineNumOffset + i); } memset(lineString, 0, 17); //lineLength = this->lineLength(i); sprintf(lineString, "%08lld ", startLineNumOffset + i); QString num(lineString); //fileOffset += lineLength; this->setMarginText(i, num, style); } } else if (endLineExist) { startLineNumOffset = endLineNumOffset - lineNums; for (int i = 0; i < lineNums; ++i) { if (i == 0) { //m_addrLineNumMap.insert(fileOffset, startLineNumOffset + i); m_addrLineNumMap.insert(fileOffset, startLineNumOffset + i); } memset(lineString, 0, 17); //lineLength = this->lineLength(i); sprintf(lineString, "%08lld ", startLineNumOffset + i); QString num(lineString); //fileOffset += lineLength; this->setMarginText(i, num, style); } } } delete[]lineString; } //大文本只读模式下,显示其文本 void ScintillaEditView::showBigTextRoLineNum(BigTextEditFileMgr* txtFile, int blockIndex) { BlockIndex bi = txtFile->blocks.at(blockIndex); int nbDigits = 0; if (bi.fileOffset < 0xffffffff) { nbDigits = INIT_BIG_RO_TEXT_LINE_WIDTH; } else { nbDigits = 12; } char* lineString = new char[17]; memset(lineString, 0, 17); auto pixelWidth = 6 + nbDigits * execute(SCI_TEXTWIDTH, STYLE_LINENUMBER, reinterpret_cast<sptr_t>("8")); this->execute(SCI_SETMARGINWIDTHN, SC_BIGTEXT_LINES, pixelWidth); int lineNums = this->lines(); qint64 curLineNum = bi.lineNumStart + 1;//行号从1开始 int style = STYLE_LINENUMBER; for (int i = 0; i < lineNums; ++i) { memset(lineString, 0, 17); if (bi.fileOffset < 0xffffffff) { sprintf(lineString, "%08lld ", curLineNum+i); } else { sprintf(lineString, "%012lld ", curLineNum + i); } QString num(lineString); this->setMarginText(i, num, style); } delete[]lineString; } void ScintillaEditView::bookmarkNext(bool forwardScan) { size_t lineno = this->getCurrentLineNumber(); int sci_marker = SCI_MARKERNEXT; size_t lineStart = lineno + 1; //Scan starting from next line int lineRetry = 0; //If not found, try from the beginning if (!forwardScan) { lineStart = lineno - 1; //Scan starting from previous line lineRetry = int(this->execute(SCI_GETLINECOUNT)); //If not found, try from the end sci_marker = SCI_MARKERPREVIOUS; } int nextLine = int(this->execute(sci_marker, lineStart, 1 << _SC_MARGE_SYBOLE)); if (nextLine < 0) nextLine = int(this->execute(sci_marker, lineRetry, 1 << _SC_MARGE_SYBOLE)); if (nextLine < 0) return; this->execute(SCI_ENSUREVISIBLEENFORCEPOLICY, nextLine); this->execute(SCI_GOTOLINE, nextLine); } void ScintillaEditView::bookmarkAdd(intptr_t lineno) const { if (lineno == -1) lineno = getCurrentLineNumber(); if (!bookmarkPresent(lineno)) this->execute(SCI_MARKERADD, lineno, _SC_MARGE_SYBOLE); } void ScintillaEditView::bookmarkDelete(size_t lineno) const { if (lineno == -1) lineno = this->getCurrentLineNumber(); while (bookmarkPresent(lineno)) this->execute(SCI_MARKERDELETE, lineno, _SC_MARGE_SYBOLE); } bool ScintillaEditView::bookmarkPresent(intptr_t lineno) const { if (lineno == -1) lineno = this->getCurrentLineNumber(); int state = this->execute(SCI_MARKERGET, lineno); return ((state & (1 << _SC_MARGE_SYBOLE)) != 0); } void ScintillaEditView::bookmarkToggle(intptr_t lineno) const { if (lineno == -1) lineno = this->getCurrentLineNumber(); if (bookmarkPresent(lineno)) bookmarkDelete(lineno); else bookmarkAdd(lineno); } void ScintillaEditView::bookmarkAdd(QSet<int>& lineSet) { QSet<int>::const_iterator i = lineSet.constBegin(); while (i != lineSet.constEnd()) { bookmarkAdd(*i); ++i; } } void ScintillaEditView::bookmarkClearAll() const { this->execute(SCI_MARKERDELETEALL, _SC_MARGE_SYBOLE); } void ScintillaEditView::slot_bookMarkClicked(int margin, int line, Qt::KeyboardModifiers state) { if (margin == _SC_MARGE_SYBOLE) { bookmarkToggle(line); } } std::mutex mark_mutex; QString ScintillaEditView::getMarkedLine(int ln) { auto lineLen = this->execute(SCI_LINELENGTH, ln); auto lineBegin = this->execute(SCI_POSITIONFROMLINE, ln); return this->getGenericTextAsQString(lineBegin, lineBegin + lineLen); } void ScintillaEditView::deleteMarkedline(int ln) { int lineLen = static_cast<int32_t>(this->execute(SCI_LINELENGTH, ln)); int lineBegin = static_cast<int32_t>(this->execute(SCI_POSITIONFROMLINE, ln)); bookmarkDelete(ln); QByteArray str2replace; this->replaceTarget(str2replace, lineBegin, lineBegin + lineLen); } void str2Cliboard(QString& text) { QClipboard* clip = QApplication::clipboard(); clip->setText(text); } void ScintillaEditView::cutMarkedLines() { std::lock_guard<std::mutex> lock(mark_mutex); int lastLine = this->lastZeroBasedLineNumber(); QString globalStr; this->execute(SCI_BEGINUNDOACTION); for (int i = lastLine; i >= 0; i--) { if (bookmarkPresent(i)) { QString currentStr = getMarkedLine(i) + globalStr; globalStr = currentStr; deleteMarkedline(i); } } this->execute(SCI_ENDUNDOACTION); str2Cliboard(globalStr); } void ScintillaEditView::copyMarkedLines() { int lastLine = this->lastZeroBasedLineNumber(); QString globalStr; for (int i = lastLine; i >= 0; i--) { if (bookmarkPresent(i)) { QString currentStr = getMarkedLine(i) + globalStr; globalStr = currentStr; } } str2Cliboard(globalStr); } void ScintillaEditView::replaceMarkedline(int ln, QByteArray& str) { int lineBegin = static_cast<int32_t>(this->execute(SCI_POSITIONFROMLINE, ln)); int lineEnd = static_cast<int32_t>(this->execute(SCI_GETLINEENDPOSITION, ln)); this->replaceTarget(str, lineBegin, lineEnd); } void ScintillaEditView::pasteToMarkedLines() { std::lock_guard<std::mutex> lock(mark_mutex); QClipboard* clip = QApplication::clipboard(); const QMimeData *mimeData = clip->mimeData(); if (!mimeData->hasText()) { return; } int lastLine = this->lastZeroBasedLineNumber(); QString clipboardStr = clip->text(); this->execute(SCI_BEGINUNDOACTION); for (int i = lastLine; i >= 0; i--) { if (bookmarkPresent(i)) { QByteArray text = clipboardStr.toUtf8(); replaceMarkedline(i, text); } } this->execute(SCI_ENDUNDOACTION); } //Y方向滚动条值变化后的槽函数 void ScintillaEditView::slot_scrollYValueChange(int value) { //使用滚动条翻页的效果并不好。暂时不放开 /*bool changePage = false; qDebug() << value << verticalScrollBar()->maximum() << verticalScrollBar()->minimum(); if (value >= this->verticalScrollBar()->maximum()) { if (m_NoteWin != nullptr) { changePage = m_NoteWin->nextPage(this); } } else if (value == this->verticalScrollBar()->minimum()) { if (m_NoteWin != nullptr) { changePage = m_NoteWin->prePage(this); } }*/ if (value >= this->verticalScrollBar()->maximum()) { if (m_NoteWin != nullptr) { m_NoteWin->showChangePageTips(this); } } else if (value == this->verticalScrollBar()->minimum()) { if (m_NoteWin != nullptr) { m_NoteWin->showChangePageTips(this); } } slot_delayWork(); autoAdjustLineWidth(value); } void ScintillaEditView::deleteMarkedLines(bool isMarked) { std::lock_guard<std::mutex> lock(mark_mutex); int lastLine = this->lastZeroBasedLineNumber(); this->execute(SCI_BEGINUNDOACTION); for (int i = lastLine; i >= 0; i--) { if (bookmarkPresent(i) == isMarked) deleteMarkedline(i); } this->execute(SCI_ENDUNDOACTION); } void ScintillaEditView::inverseMarks() { int lastLine = this->lastZeroBasedLineNumber(); for (int i = 0; i <= lastLine; ++i) { if (bookmarkPresent(i)) { bookmarkDelete(i); } else { bookmarkAdd(i); } } } void ScintillaEditView::slot_linePosChanged(int /*line*/, int pos) { //避免循环触发的slot_positionChanged if (m_curPos == pos) { return; } m_prePosRecord.append(pos); if (m_prePosRecord.size() >= MAX_PRE_NEXT_TIMES) { m_prePosRecord.takeFirst(); } } //回退一个位置 bool ScintillaEditView::gotoPrePos() { if (m_prePosRecord.size() > 1) { int v = m_prePosRecord.takeLast(); m_nextPosRecord.push_front(v); if (m_nextPosRecord.size() >= MAX_PRE_NEXT_TIMES) { m_nextPosRecord.takeLast(); } int pos = m_prePosRecord.last(); //下面这个函数比较坑,里面要循环Index次,每次返回的index值是不一样的。只能使用SCI_GOTOPOS可自定义的信号 //setCursorPosition(pos.line, pos.index); //会循环触发slot_positionChanged this->execute(SCI_GOTOPOS, pos); m_curPos = pos; return true; } return false; } bool ScintillaEditView::gotoNextPos() { if (m_nextPosRecord.size() > 0) { int pos = m_nextPosRecord.takeFirst(); m_prePosRecord.append(pos); this->execute(SCI_GOTOPOS, pos); m_curPos = pos; return true; } return false; } const int MAXLINEHIGHLIGHT = 400; void ScintillaEditView::clearIndicator(int indicatorNumber) { size_t docStart = 0; size_t docEnd = length(); execute(SCI_SETINDICATORCURRENT, indicatorNumber); execute(SCI_INDICATORCLEARRANGE, docStart, docEnd - docStart); }; void ScintillaEditView::slot_clearHightWord() { if (m_hasHighlight) { m_hasHighlight = false; clearIndicator(SCE_UNIVERSAL_FOUND_STYLE_SMART); } } intptr_t ScintillaEditView::searchInTarget(QByteArray& text2Find,size_t fromPos, size_t toPos) const { execute(SCI_SETTARGETRANGE, fromPos, toPos); return execute(SCI_SEARCHINTARGET, text2Find.size(), reinterpret_cast<sptr_t>(text2Find.data())); } intptr_t ScintillaEditView::replaceTargetRegExMode(QByteArray& re, intptr_t fromTargetPos, intptr_t toTargetPos) const { if (fromTargetPos != -1 || toTargetPos != -1) { execute(SCI_SETTARGETRANGE, fromTargetPos, toTargetPos); } return execute(SCI_REPLACETARGETRE, re.size(), reinterpret_cast<sptr_t>(re.data())); } //替换fromTargetPos 到 toTargetPos的内容为str2replace。 intptr_t ScintillaEditView::replaceTarget(QByteArray& str2replace, intptr_t fromTargetPos, intptr_t toTargetPos) const { if (fromTargetPos != -1 || toTargetPos != -1) { execute(SCI_SETTARGETRANGE, fromTargetPos, toTargetPos); } return execute(SCI_REPLACETARGET, str2replace.size(), reinterpret_cast<sptr_t>(str2replace.data())); } void ScintillaEditView::highlightViewWithWord(QString & word2Hilite) { int originalStartPos = execute(SCI_GETTARGETSTART); int originalEndPos = execute(SCI_GETTARGETEND); int firstLine = static_cast<int>(this->execute(SCI_GETFIRSTVISIBLELINE)); int nbLineOnScreen = this->execute(SCI_LINESONSCREEN); int nbLines = std::min(nbLineOnScreen, MAXLINEHIGHLIGHT) + 1; int lastLine = firstLine + nbLines; int startPos = 0; int endPos = 0; auto currentLine = firstLine; int prevDocLineChecked = -1; //invalid start auto searchMark = [this](int &startPos, int &endPos, QByteArray &word2Mark){ int targetStart = 0; int targetEnd = 0; long lens = word2Mark.length(); while (targetStart >= 0) { execute(SCI_SETTARGETRANGE, startPos, endPos); targetStart = SendScintilla(SCI_SEARCHINTARGET, lens, word2Mark.data()); if (targetStart == -1 || targetStart == -2) break; targetEnd = int(this->execute(SCI_GETTARGETEND)); if (targetEnd > endPos) { //we found a result but outside our range, therefore do not process it break; } int foundTextLen = targetEnd - targetStart; if (foundTextLen > 0) { this->execute(SCI_SETINDICATORCURRENT, SCE_UNIVERSAL_FOUND_STYLE_SMART); this->execute(SCI_INDICATORFILLRANGE, targetStart, foundTextLen); } if (targetStart + foundTextLen == endPos) break; startPos = targetStart + foundTextLen; } }; QByteArray whatMark = word2Hilite.toUtf8(); SendScintilla(SCI_SETSEARCHFLAGS, SCFIND_MATCHCASE /*| SCFIND_WHOLEWORD*/ | SCFIND_REGEXP_SKIPCRLFASONE); for (; currentLine < lastLine; ++currentLine) { int docLine = static_cast<int>(this->execute(SCI_DOCLINEFROMVISIBLE, currentLine)); if (docLine == prevDocLineChecked) continue; //still on same line (wordwrap) prevDocLineChecked = docLine; startPos = static_cast<int>(this->execute(SCI_POSITIONFROMLINE, docLine)); endPos = static_cast<int>(this->execute(SCI_POSITIONFROMLINE, docLine + 1)); if (endPos == -1) { //past EOF endPos = this->length() - 1; searchMark(startPos, endPos, whatMark); break; } else { searchMark(startPos, endPos, whatMark); } } m_hasHighlight = true; // restore the original targets to avoid conflicts with the search/replace functions this->execute(SCI_SETTARGETRANGE, originalStartPos, originalEndPos); } void ScintillaEditView::slot_markColorGroup(QAction *action) { CCNotePad::s_curMarkColorId = action->data().toInt(); if (m_NoteWin != nullptr) { m_NoteWin->slot_wordHighlight(); } } //修改标记样式的颜色 void ScintillaEditView::changeStyleColor(int sytleId) { if (m_styleColorMenu == nullptr) { initStyleColorMenu(); } if( sytleId < 5) { QPixmap colorBar(36, 36); colorBar.fill((&StyleSet::s_global_style->mark_style_1)[sytleId].bgColor); m_styleMarkActList.at(sytleId)->setIcon(colorBar); if (m_NoteWin != nullptr) { m_NoteWin->changeMarkColor(sytleId); } } } void ScintillaEditView::initStyleColorMenu() { if (m_styleColorMenu == nullptr) { m_styleColorMenu = new QMenu(tr("mark with color"), this); QPixmap colorBar(36, 36); QActionGroup* markColorGroup = new QActionGroup(this); connect(markColorGroup, &QActionGroup::triggered, this, &ScintillaEditView::slot_markColorGroup, Qt::QueuedConnection); int index = 1; auto initColorBar = [this, markColorGroup, &index](QPixmap& colorBar)->QAction* { QAction* action = new QAction(m_styleColorMenu); action->setIcon(colorBar); action->setCheckable(true); action->setText(tr("Color %1").arg(index)); action->setData(index + SCE_UNIVERSAL_FOUND_STYLE_EXT5 - 1); ++index; m_styleColorMenu->addAction(action); markColorGroup->addAction(action); return action; }; colorBar.fill(StyleSet::s_global_style->mark_style_1.bgColor); m_styleMarkActList.append(initColorBar(colorBar)); colorBar.fill(StyleSet::s_global_style->mark_style_2.bgColor); m_styleMarkActList.append(initColorBar(colorBar)); colorBar.fill(StyleSet::s_global_style->mark_style_3.bgColor); m_styleMarkActList.append(initColorBar(colorBar)); colorBar.fill(StyleSet::s_global_style->mark_style_4.bgColor); m_styleMarkActList.append(initColorBar(colorBar)); colorBar.fill(StyleSet::s_global_style->mark_style_5.bgColor); m_styleMarkActList.append(initColorBar(colorBar)); m_styleColorMenu->addSeparator(); if (m_NoteWin != nullptr) { m_styleColorMenu->addAction(tr("Clear Select"), m_NoteWin, &CCNotePad::slot_clearWordHighlight); m_styleColorMenu->addAction(tr("Clear All"), m_NoteWin, &CCNotePad::slot_clearMark); } } } void ScintillaEditView::contextUserDefineMenuEvent(QMenu* menu) { //QAction* action; if (menu != nullptr && (m_NoteWin !=nullptr)) { menu->addAction(tr("Show File in Explorer"), m_NoteWin, &CCNotePad::slot_showFileInExplorer); if (m_styleColorMenu == nullptr) { m_styleColorMenu = new QMenu(tr("mark with color"),this); QPixmap colorBar(36, 36); QActionGroup* markColorGroup = new QActionGroup(this); connect(markColorGroup, &QActionGroup::triggered, this, &ScintillaEditView::slot_markColorGroup, Qt::QueuedConnection); int index = 1; auto initColorBar = [this, markColorGroup, &index](QPixmap& colorBar)->QAction* { QAction* action = new QAction(m_styleColorMenu); action->setIcon(colorBar); action->setCheckable(true); action->setText(tr("Color %1").arg(index)); action->setData(index + SCE_UNIVERSAL_FOUND_STYLE_EXT5-1); ++index; m_styleColorMenu->addAction(action); markColorGroup->addAction(action); return action; }; colorBar.fill(StyleSet::s_global_style->mark_style_1.fgColor); m_styleMarkActList.append(initColorBar(colorBar)); colorBar.fill(StyleSet::s_global_style->mark_style_2.fgColor); m_styleMarkActList.append(initColorBar(colorBar)); colorBar.fill(StyleSet::s_global_style->mark_style_3.fgColor); m_styleMarkActList.append(initColorBar(colorBar)); colorBar.fill(StyleSet::s_global_style->mark_style_4.fgColor); m_styleMarkActList.append(initColorBar(colorBar)); colorBar.fill(StyleSet::s_global_style->mark_style_5.fgColor); m_styleMarkActList.append(initColorBar(colorBar)); m_styleColorMenu->addSeparator(); m_styleColorMenu->addAction(tr("Clear Select"), m_NoteWin, &CCNotePad::slot_clearWordHighlight); m_styleColorMenu->addAction(tr("Clear All"), m_NoteWin, &CCNotePad::slot_clearMark); } menu->addMenu(m_styleColorMenu); menu->addSeparator(); menu->addAction(tr("Add/Del line comment"), [this]() { doBlockComment(cm_toggle); }); menu->addAction(tr("Add Block comment"), [this]() { doStreamComment(); }); menu->addAction(tr("Del Block comment"), [this]() { undoStreamComment(); }); menu->addSeparator(); menu->addAction(tr("Markdown View"), this, &ScintillaEditView::on_viewMarkdown); menu->addAction(tr("Word Count"), [this]() { showWordNums(); }); } menu->show(); } void ScintillaEditView::replaceSelWith(const char* replaceText) { execute(SCI_REPLACESEL, 0, reinterpret_cast<sptr_t>(replaceText)); } bool ScintillaEditView::doBlockComment(Comment_Mode currCommentMode) { if (this->isReadOnly()) { return false; } //-- BlockToStreamComment: QByteArray commentStart; QByteArray commentEnd; QByteArray symbolStart; QByteArray symbolEnd; QByteArray commentLineSymbol; QByteArray symbol; bool isSingleLineAdvancedMode = false; QsciLexer* pLexer = this->lexer(); if (pLexer == nullptr) { return false; } else { commentLineSymbol = pLexer->getCommentLineSymbol(); commentStart = pLexer->getCommentStart(); commentEnd = pLexer->getCommentEnd(); } if ((commentLineSymbol.isEmpty()) || commentLineSymbol.isEmpty()) { // BlockToStreamComment: If there is no block-comment symbol, try the stream comment: if (!(commentStart.isEmpty() || commentEnd.isEmpty())) { if (currCommentMode == cm_comment) { isSingleLineAdvancedMode = true; } else if (currCommentMode == cm_uncomment) { return undoStreamComment(false); } else if (currCommentMode == cm_toggle) { isSingleLineAdvancedMode = true; } else { return false; } } else { return false; } } //For Single Line NORMAL MODE QByteArray comment; size_t comment_length = 0; //For Single Line ADVANCED MODE QByteArray advCommentStart; QByteArray advCommentEnd; size_t advCommentStart_length = 0; size_t advCommentEnd_length = 0; QByteArray aSpace(" "); //Only values that have passed through will be assigned, to be sure they are valid! if (!isSingleLineAdvancedMode) { comment = commentLineSymbol; if (!(pLexer->lexerId() == L_BAANC)) // BaanC standardization - no space. { comment += aSpace; } comment_length = comment.length(); } else // isSingleLineAdvancedMode { advCommentStart = commentStart; advCommentStart += aSpace; advCommentEnd = aSpace; advCommentEnd += commentEnd; advCommentStart_length = advCommentStart.length(); advCommentEnd_length = advCommentEnd.length(); } size_t selectionStart = this->execute(SCI_GETSELECTIONSTART); size_t selectionEnd = this->execute(SCI_GETSELECTIONEND); size_t caretPosition = this->execute(SCI_GETCURRENTPOS); bool move_caret = caretPosition < selectionEnd; intptr_t selStartLine = this->execute(SCI_LINEFROMPOSITION, selectionStart); intptr_t selEndLine = this->execute(SCI_LINEFROMPOSITION, selectionEnd); intptr_t lines = selEndLine - selStartLine; if ((lines > 0) && (selectionEnd == static_cast<size_t>(this->execute(SCI_POSITIONFROMLINE, selEndLine)))) { selEndLine--; } // count lines which were un-commented to decide if undoStreamComment() shall be called. int nUncomments = 0; //Some Lexers need line-comments at the beginning of a line. const bool avoidIndent = (pLexer->lexerId() == L_FORTRAN_77 || pLexer->lexerId() == L_BAANC); //Some Lexers comment blank lines, per their standards. const bool commentEmptyLines = (pLexer->lexerId() == L_BAANC); this->execute(SCI_BEGINUNDOACTION); for (intptr_t i = selStartLine; i <= selEndLine; ++i) { size_t lineStart = this->execute(SCI_POSITIONFROMLINE, i); size_t lineIndent = this->execute(SCI_GETLINEINDENTPOSITION, i); size_t lineEnd = this->execute(SCI_GETLINEENDPOSITION, i); // empty lines are not commented, unless required by the language. if (lineIndent == lineEnd && !commentEmptyLines) continue; if (avoidIndent) lineIndent = lineStart; //这里linebufferSize不需要包含字符串后面的\0,所以不需要预留1个\0符号 size_t linebufferSize = lineEnd - lineIndent; QByteArray linebuf; linebuf.resize(linebufferSize); this->getText(linebuf.data(), lineIndent, lineEnd); QByteArray linebufStr = linebuf; if (currCommentMode != cm_comment) // uncomment/toggle { if (!isSingleLineAdvancedMode) { if (qstrncmp(linebufStr.data(), comment.data(), !(pLexer->lexerId() == L_BAANC) ? comment_length - 1 : comment_length) == 0) { size_t len = (linebufStr[(int)comment_length - 1] == aSpace[0]) ? comment_length : (!(pLexer->lexerId() == L_BAANC) ? comment_length - 1 : comment_length); this->execute(SCI_SETSEL, lineIndent, lineIndent + len); this->replaceSelWith(""); // SELECTION RANGE ADJUSTMENT ....................... if (i == selStartLine) // first selected line { if (selectionStart > lineIndent + len) selectionStart -= len; else if (selectionStart > lineIndent) selectionStart = lineIndent; } // ................................................ if (i == selEndLine) // last selected line { if (selectionEnd > lineIndent + len) selectionEnd -= len; else if (selectionEnd > lineIndent) { selectionEnd = lineIndent; if (lineIndent == lineStart && i != selStartLine) ++selectionEnd; // avoid caret return in this case } } // ................................................ else // every iteration except the last selected line selectionEnd -= len; // .................................................. ++nUncomments; continue; } } else { if ((qstrncmp(linebufStr.data(), advCommentStart.data(), advCommentStart_length - 1) == 0) && (qstrncmp(linebufStr.mid(linebufStr.length() - advCommentEnd_length + 1, advCommentEnd_length - 1).data(), advCommentEnd.mid(1, advCommentEnd_length - 1).data(), advCommentEnd_length - 1) == 0)) { size_t startLen = linebufStr[(int)advCommentStart_length - 1] == aSpace[0] ? advCommentStart_length : advCommentStart_length - 1; size_t endLen = linebufStr[int(linebufStr.length() - advCommentEnd_length)] == aSpace[0] ? advCommentEnd_length : advCommentEnd_length - 1; this->execute(SCI_SETSEL, lineIndent, lineIndent + startLen); this->replaceSelWith(""); this->execute(SCI_SETSEL, lineEnd - startLen - endLen, lineEnd - startLen); this->replaceSelWith(""); // SELECTION RANGE ADJUSTMENT ....................... if (i == selStartLine) // first selected line { if (selectionStart > lineEnd - endLen) selectionStart = lineEnd - startLen - endLen; else if (selectionStart > lineIndent + startLen) selectionStart -= startLen; else if (selectionStart > lineIndent) selectionStart = lineIndent; } // ................................................ if (i == selEndLine) // last selected line { if (selectionEnd > lineEnd) selectionEnd -= (startLen + endLen); else if (selectionEnd > lineEnd - endLen) selectionEnd = lineEnd - startLen - endLen; else if (selectionEnd > lineIndent + startLen) selectionEnd -= startLen; else if (selectionEnd > lineIndent) { selectionEnd = lineIndent; if (lineIndent == lineStart && i != selStartLine) ++selectionEnd; // avoid caret return in this case } } // ................................................ else // every iteration except the last selected line selectionEnd -= (startLen + endLen); // .................................................. ++nUncomments; continue; } } } // uncomment/toggle if (currCommentMode != cm_uncomment) // comment/toggle { if (!isSingleLineAdvancedMode) { this->insertCharsFrom(lineIndent, comment); // SELECTION RANGE ADJUSTMENT ....................... if (i == selStartLine) // first selected line { if (selectionStart >= lineIndent) selectionStart += comment_length; } // ................................................ if (i == selEndLine) // last selected line { if (selectionEnd >= lineIndent) selectionEnd += comment_length; } // ................................................ else // every iteration except the last selected line selectionEnd += comment_length; // .................................................. } else // isSingleLineAdvancedMode { this->insertCharsFrom(lineIndent, advCommentStart); this->insertCharsFrom(lineEnd + advCommentStart_length, advCommentEnd); // SELECTION RANGE ADJUSTMENT ....................... if (i == selStartLine) // first selected line { if (selectionStart >= lineIndent) selectionStart += advCommentStart_length; } // ................................................ if (i == selEndLine) // last selected line { if (selectionEnd > lineEnd) selectionEnd += (advCommentStart_length + advCommentEnd_length); else if (selectionEnd >= lineIndent) selectionEnd += advCommentStart_length; } // ................................................ else // every iteration except the last selected line selectionEnd += (advCommentStart_length + advCommentEnd_length); // .................................................. } } // comment/toggle } // for (...) if (move_caret) { // moving caret to the beginning of selected block this->execute(SCI_GOTOPOS, selectionEnd); this->execute(SCI_SETCURRENTPOS, selectionStart); } else { this->execute(SCI_SETSEL, selectionStart, selectionEnd); } this->execute(SCI_ENDUNDOACTION); // undoStreamComment: If there were no block-comments to un-comment try uncommenting of stream-comment. if ((currCommentMode == cm_uncomment) && (nUncomments == 0)) { return undoStreamComment(false); } return true; } //显示文字的字数 void ScintillaEditView::showWordNums() { if (hasSelectedText()) { QString word = selectedText(); if (!word.isEmpty()) { int lineNum = word.count("\n"); if (!word.endsWith("\n")) { ++lineNum; } //\s是包含了换行符的,所有要单独统计\r\n换换行符,排除一下 QRegExp warpRe("[\r\n]"); int wrapNums = word.count(warpRe); QRegExp bkRe("\\s"); int blank = word.count(bkRe); QMessageBox::about(this, tr("Word Nums"), tr("Current Select Word Nums is %1 . \nLine nums is %2 . \nSpace nums is %3, Non-space is %4 .").\ arg(word.size()-wrapNums).arg(lineNum).arg(blank-wrapNums).arg(word.size()-blank)); } } else { int lineNum = this->lines(); QString text = this->text(); //\s是包含了换行符的,所有要单独统计\r\n换换行符,排除一下 QRegExp warpRe("[\r\n]"); int wrapNums = text.count(warpRe); QRegExp bkRe("\\s"); int blank = text.count(bkRe); QMessageBox::about(this, tr("Word Nums"), tr("Current Doc Word Nums is %1 . \nLine nums is %2 . \nSpace nums is %3, Non-space is %4 .").\ arg(text.size() - wrapNums).arg(lineNum).arg(blank - wrapNums).arg(text.size() - blank)); } } bool ScintillaEditView::undoStreamComment(bool tryBlockComment) { QByteArray commentStart; QByteArray commentEnd; QByteArray commentLineSymbol; QByteArray symbolStart; QByteArray symbolEnd; QByteArray symbol; const int charbufLen = 10; QByteArray charbuf; charbuf.reserve(charbufLen); bool retVal = false; QsciLexer* pLexer = this->lexer(); //-- Avoid side-effects (e.g. cursor moves number of comment-characters) when file is read-only. if (this->isReadOnly()) return false; if (pLexer->lexer() == nullptr) { return false; } else { commentLineSymbol = pLexer->getCommentLineSymbol(); commentStart = pLexer->getCommentStart(); commentEnd = pLexer->getCommentEnd(); } // BlockToStreamComment: If there is no stream-comment symbol and we came not from doBlockComment, try the block comment: if (commentStart.isEmpty() || commentEnd.isEmpty()) { if (!commentLineSymbol.isEmpty() && tryBlockComment) return doBlockComment(cm_uncomment); else return false; } QByteArray start_comment(commentStart); QByteArray end_comment(commentEnd); QByteArray white_space(" "); size_t start_comment_length = start_comment.length(); size_t end_comment_length = end_comment.length(); // do as long as stream-comments are within selection do { auto selectionStart = this->execute(SCI_GETSELECTIONSTART); auto selectionEnd = this->execute(SCI_GETSELECTIONEND); auto caretPosition = this->execute(SCI_GETCURRENTPOS); auto docLength = this->execute(SCI_GETLENGTH); // checking if caret is located in _beginning_ of selected block bool move_caret = caretPosition < selectionEnd; //-- Note: The caretPosition is either at selectionEnd or at selectionStart!! selectionStart is always before (smaller) than selectionEnd!! //-- First, search all start_comment and end_comment before and after the selectionStart and selectionEnd position. const int iSelStart = 0, iSelEnd = 1; const size_t N_CMNT = 2; intptr_t posStartCommentBefore[N_CMNT], posEndCommentBefore[N_CMNT], posStartCommentAfter[N_CMNT], posEndCommentAfter[N_CMNT]; bool blnStartCommentBefore[N_CMNT], blnEndCommentBefore[N_CMNT], blnStartCommentAfter[N_CMNT], blnEndCommentAfter[N_CMNT]; intptr_t posStartComment, posEndComment; intptr_t selectionStartMove, selectionEndMove; int flags; //-- Directly use Scintilla-Functions // rather than _findReplaceDlg.processFindNext()which does not return the find-position and is not quiet! flags = SCFIND_WORDSTART; this->execute(SCI_SETSEARCHFLAGS, flags); //-- Find all start- and end-comments before and after the selectionStart position. //-- When searching upwards the start-position for searching must be moved one after the current position // to find a search-string just starting before the current position! //-- Direction DIR_UP --- posStartCommentBefore[iSelStart] = this->searchInTarget(start_comment, selectionStart, 0); (posStartCommentBefore[iSelStart] == -1 ? blnStartCommentBefore[iSelStart] = false : blnStartCommentBefore[iSelStart] = true); posEndCommentBefore[iSelStart] = this->searchInTarget(end_comment, selectionStart, 0); (posEndCommentBefore[iSelStart] == -1 ? blnEndCommentBefore[iSelStart] = false : blnEndCommentBefore[iSelStart] = true); //-- Direction DIR_DOWN --- posStartCommentAfter[iSelStart] = this->searchInTarget(start_comment, selectionStart, docLength); (posStartCommentAfter[iSelStart] == -1 ? blnStartCommentAfter[iSelStart] = false : blnStartCommentAfter[iSelStart] = true); posEndCommentAfter[iSelStart] = this->searchInTarget(end_comment, selectionStart, docLength); (posEndCommentAfter[iSelStart] == -1 ? blnEndCommentAfter[iSelStart] = false : blnEndCommentAfter[iSelStart] = true); //-- Check, if selectionStart or selectionEnd is within a stream comment ----- // or if the selection includes a complete stream-comment!! ---------------- //-- First, check if there is a stream-comment around the selectionStart position: if ((blnStartCommentBefore[iSelStart] && blnEndCommentAfter[iSelStart]) && (!blnEndCommentBefore[iSelStart] || (posStartCommentBefore[iSelStart] >= posEndCommentBefore[iSelStart])) && (!blnStartCommentAfter[iSelStart] || (posEndCommentAfter[iSelStart] <= posStartCommentAfter[iSelStart]))) { posStartComment = posStartCommentBefore[iSelStart]; posEndComment = posEndCommentAfter[iSelStart]; } else //-- Second, check if there is a stream-comment around the selectionEnd position: { //-- Find all start- and end-comments before and after the selectionEnd position. //-- Direction DIR_UP --- posStartCommentBefore[iSelEnd] = this->searchInTarget(start_comment, selectionEnd, 0); (posStartCommentBefore[iSelEnd] == -1 ? blnStartCommentBefore[iSelEnd] = false : blnStartCommentBefore[iSelEnd] = true); posEndCommentBefore[iSelEnd] = this->searchInTarget(end_comment, selectionEnd, 0); (posEndCommentBefore[iSelEnd] == -1 ? blnEndCommentBefore[iSelEnd] = false : blnEndCommentBefore[iSelEnd] = true); //-- Direction DIR_DOWN --- posStartCommentAfter[iSelEnd] = this->searchInTarget(start_comment, selectionEnd, docLength); (posStartCommentAfter[iSelEnd] == -1 ? blnStartCommentAfter[iSelEnd] = false : blnStartCommentAfter[iSelEnd] = true); posEndCommentAfter[iSelEnd] = this->searchInTarget(end_comment, selectionEnd, docLength); (posEndCommentAfter[iSelEnd] == -1 ? blnEndCommentAfter[iSelEnd] = false : blnEndCommentAfter[iSelEnd] = true); if ((blnStartCommentBefore[iSelEnd] && blnEndCommentAfter[iSelEnd]) && (!blnEndCommentBefore[iSelEnd] || (posStartCommentBefore[iSelEnd] >= posEndCommentBefore[iSelEnd])) && (!blnStartCommentAfter[iSelEnd] || (posEndCommentAfter[iSelEnd] <= posStartCommentAfter[iSelEnd]))) { posStartComment = posStartCommentBefore[iSelEnd]; posEndComment = posEndCommentAfter[iSelEnd]; } //-- Third, check if there is a stream-comment within the selected area: else if ((blnStartCommentAfter[iSelStart] && (posStartCommentAfter[iSelStart] < selectionEnd)) && (blnEndCommentBefore[iSelEnd] && (posEndCommentBefore[iSelEnd] > selectionStart))) { //-- If there are more than one stream-comment within the selection, take the first one after selectionStart!! posStartComment = posStartCommentAfter[iSelStart]; posEndComment = posEndCommentAfter[iSelStart]; } //-- Finally, if there is no stream-comment, return else return retVal; } //-- Ok, there are valid start-comment and valid end-comment around the caret-position. // Now, un-comment stream-comment: retVal = true; intptr_t startCommentLength = start_comment_length; intptr_t endCommentLength = end_comment_length; //-- First delete end-comment, so that posStartCommentBefore does not change! //-- Get character before end-comment to decide, if there is a white character before the end-comment, which will be removed too! this->getText(charbuf.data(), posEndComment - 1, posEndComment); if (qstrncmp(charbuf, white_space, white_space.length()) == 0) { endCommentLength += 1; posEndComment -= 1; } //-- Delete end stream-comment string --------- this->execute(SCI_BEGINUNDOACTION); this->execute(SCI_SETSEL, posEndComment, posEndComment + endCommentLength); this->execute(SCI_REPLACESEL, 0, reinterpret_cast<sptr_t>("")); //-- Get character after start-comment to decide, if there is a white character after the start-comment, which will be removed too! this->getText(charbuf.data(), posStartComment + startCommentLength, posStartComment + startCommentLength + 1); if (qstrncmp(charbuf, white_space, white_space.length()) == 0) startCommentLength += 1; //-- Delete starting stream-comment string --------- this->execute(SCI_SETSEL, posStartComment, posStartComment + startCommentLength); this->execute(SCI_REPLACESEL, 0, reinterpret_cast<sptr_t>("")); this->execute(SCI_ENDUNDOACTION); //-- Reset selection before calling the routine //-- Determine selection movement // selectionStart if (selectionStart > posStartComment) { if (selectionStart >= posStartComment + startCommentLength) selectionStartMove = -startCommentLength; else selectionStartMove = -selectionStart - posStartComment; } else selectionStartMove = 0; // selectionEnd if (selectionEnd >= posEndComment + endCommentLength) selectionEndMove = -startCommentLength + endCommentLength; else if (selectionEnd <= posEndComment) selectionEndMove = -startCommentLength; else selectionEndMove = -startCommentLength + (selectionEnd - posEndComment); //-- Reset selection of text without deleted stream-comment-string if (move_caret) { // moving caret to the beginning of selected block this->execute(SCI_GOTOPOS, selectionEnd + selectionEndMove); this->execute(SCI_SETCURRENTPOS, selectionStart + selectionStartMove); } else { this->execute(SCI_SETSEL, selectionStart + selectionStartMove, selectionEnd + selectionEndMove); } } while (1); //do as long as stream-comments are within selection } bool ScintillaEditView::doStreamComment() { QByteArray commentStart; QByteArray commentEnd; QByteArray symbolStart; QByteArray symbolEnd; // BlockToStreamComment: QByteArray commentLineSymbol; QByteArray symbol; if (this->isReadOnly()) return false; QsciLexer* pLexer = this->lexer(); if (pLexer == nullptr) { return false; } else { // BlockToStreamComment: Next line needed to decide, if block-comment can be called below! commentLineSymbol = pLexer->getCommentLineSymbol(); commentStart = pLexer->getCommentStart(); commentEnd = pLexer->getCommentEnd(); } // BlockToStreamComment: If there is no stream-comment symbol, try the block comment: if (commentStart.isEmpty()||commentEnd.isEmpty()) { if (!commentLineSymbol.isEmpty()) return doBlockComment(cm_comment); else { return false; } } QByteArray start_comment(commentStart); QByteArray end_comment(commentEnd); QByteArray white_space(" "); start_comment += white_space; white_space += end_comment; end_comment = white_space; size_t start_comment_length = start_comment.length(); size_t selectionStart = this->execute(SCI_GETSELECTIONSTART); size_t selectionEnd = this->execute(SCI_GETSELECTIONEND); size_t caretPosition = this->execute(SCI_GETCURRENTPOS); // checking if caret is located in _beginning_ of selected block bool move_caret = caretPosition < selectionEnd; // if there is no selection? if (selectionEnd - selectionStart <= 0) { auto selLine = this->execute(SCI_LINEFROMPOSITION, selectionStart); selectionStart = this->execute(SCI_GETLINEINDENTPOSITION, selLine); selectionEnd = this->execute(SCI_GETLINEENDPOSITION, selLine); } this->execute(SCI_BEGINUNDOACTION); this->insertCharsFrom(selectionStart, start_comment); selectionEnd += start_comment_length; selectionStart += start_comment_length; this->insertCharsFrom(selectionEnd, end_comment); if (move_caret) { // moving caret to the beginning of selected block this->execute(SCI_GOTOPOS, selectionEnd); this->execute(SCI_SETCURRENTPOS, selectionStart); } else { this->execute(SCI_SETSEL, selectionStart, selectionEnd); } this->execute(SCI_ENDUNDOACTION); return true; } void ScintillaEditView::slot_delayWork() { if (!hasSelectedText()) { return; } QString word = selectedText(); if (!word.isEmpty()) { highlightViewWithWord(word); } } void ScintillaEditView::dragEnterEvent(QDragEnterEvent* event) { event->accept(); } void ScintillaEditView::dropEvent(QDropEvent* e) { QList<QUrl> urls = e->mimeData()->urls(); if (!urls.isEmpty()) { CCNotePad* pv = dynamic_cast<CCNotePad*>(m_NoteWin); if (pv != nullptr) { pv->receiveEditDrop(e); } return; } QsciScintilla::dropEvent(e); } void ScintillaEditView::mouseDoubleClickEvent(QMouseEvent * e) { if (CCNotePad::s_hightWebAddr == 1) { do { int position = this->execute(SCI_GETCURRENTPOS); auto indicMsk = this->execute(SCI_INDICATORALLONFOR, position); if (!(indicMsk & (1 << URL_INDIC))) break; auto startPos = this->execute(SCI_INDICATORSTART, URL_INDIC, position); auto endPos = this->execute(SCI_INDICATOREND, URL_INDIC, position); if ((position < startPos) || (position > endPos)) break; // WM_LBUTTONUP goes to opening browser instead of Scintilla here, because the mouse is not captured. // The missing message causes mouse cursor flicker as soon as the mouse cursor is moved to a position outside the text editing area. //::PostMessage(this->getHSelf(), WM_LBUTTONUP, 0, 0); // Revert selection of current word. Best to this early, otherwise the // selected word is visible all the time while the browser is starting execute(SCI_SETSEL, position, position); // Open URL QByteArray url; url.resize(endPos - startPos); this->getText(url.data(), static_cast<size_t>(startPos), static_cast<size_t>(endPos)); QUrl urlweb(url); if (urlweb.isValid()) { QDesktopServices::openUrl(urlweb); return; } } while (0); } //20230219先双击选中,再按住ctrl,再双击别的地方选中。此时是进入多选状态。 //这里必须要直接返回,不能做delayWork。否则因为delaywork里面不能判断多选,而数据越界崩溃 if (hasSelectedText()) { QsciScintilla::mouseDoubleClickEvent(e); return; } //执行下面mouseDoubleClickEvent后,又会选中。此时如果上面已经有选中,则会多选 QsciScintilla::mouseDoubleClickEvent(e); if (hasSelectedText()) { emit delayWork(); } } void ScintillaEditView::changeCase(const TextCaseType & caseToConvert, QString& strToConvert) const { if (strToConvert.isEmpty()) return; int nbChars = strToConvert.size(); switch (caseToConvert) { case UPPERCASE: { strToConvert = strToConvert.toUpper(); break; } case LOWERCASE: { strToConvert = strToConvert.toLower(); break; } case TITLECASE_FORCE: case TITLECASE_BLEND: { for (int i = 0; i < nbChars; ++i) { if (strToConvert[i].isLetter()) { if ((i < 1) ? true : !strToConvert[i - 1].isLetterOrNumber()) strToConvert[i] = strToConvert[i].toUpper(); else if (caseToConvert == TITLECASE_FORCE) strToConvert[i] = strToConvert[i].toLower(); //An exception if ((i < 2) ? false : (strToConvert[i - 1] == L'\'' && (strToConvert[i - 2].isLetter()))) strToConvert[i] = strToConvert[i].toLower(); } } break; } //case TITLECASE case SENTENCECASE_FORCE: case SENTENCECASE_BLEND: { bool isNewSentence = true; bool wasEolR = false; bool wasEolN = false; for (int i = 0; i < nbChars; ++i) { if (strToConvert[i].isLetter()) { if (isNewSentence) { strToConvert[i] = strToConvert[i].toUpper(); isNewSentence = false; } else if (caseToConvert == SENTENCECASE_FORCE) { strToConvert[i] = strToConvert[i].toLower(); } wasEolR = false; wasEolN = false; //An exception if (strToConvert[i] == L'i' && ((i < 1) ? false : (strToConvert[i - 1].isSpace() || strToConvert[i - 1] == '(' || strToConvert[i - 1] == '"')) && \ ((i + 1 == nbChars) ? false : (strToConvert[i + 1].isSpace() || strToConvert[i + 1] == '\''))) { strToConvert[i] = L'I'; } } else if (strToConvert[i] == '.' || strToConvert[i] == '!' || strToConvert[i] == '?') { if ((i + 1 == nbChars) ? true : strToConvert[i + 1].isLetterOrNumber()) isNewSentence = false; else isNewSentence = true; } else if (strToConvert[i] == '\r') { if (wasEolR) isNewSentence = true; else wasEolR = true; } else if (strToConvert[i] == '\n') { if (wasEolN) isNewSentence = true; else wasEolN = true; } } break; } //case SENTENCECASE case INVERTCASE: { for (int i = 0; i < nbChars; ++i) { if (strToConvert[i].isLower()) strToConvert[i] = strToConvert[i].toUpper(); else strToConvert[i] = strToConvert[i].toLower(); } break; } //case INVERTCASE case RANDOMCASE: { for (int i = 0; i < nbChars; ++i) { if (strToConvert[i].isLetter()) { if (std::rand() & true) strToConvert[i] = strToConvert[i].toUpper(); else strToConvert[i] = strToConvert[i].toLower(); } } break; } } //switch (caseToConvert) } void ScintillaEditView::convertSelectedTextTo(const TextCaseType & caseToConvert) { int selectionStart = execute(SCI_GETSELECTIONSTART); int selectionEnd = execute(SCI_GETSELECTIONEND); int strLen = (selectionEnd - selectionStart); if (strLen != 0) { int strSize = strLen + 1; char *selectedStr = new char[strSize]; execute(SCI_GETSELTEXT, 0, reinterpret_cast<sptr_t>(selectedStr)); QString utf8Str(selectedStr); changeCase(caseToConvert, utf8Str); QByteArray bytes = utf8Str.toUtf8(); execute(SCI_SETTARGETRANGE, selectionStart, selectionEnd); execute(SCI_BEGINUNDOACTION); execute(SCI_REPLACETARGET, strLen, reinterpret_cast<sptr_t>(bytes.data())); execute(SCI_ENDUNDOACTION); execute(SCI_SETSEL, selectionStart, selectionEnd); delete[] selectedStr; } } //获取当前选择的行范围 std::pair<size_t, size_t> ScintillaEditView::getSelectionLinesRange(intptr_t selectionNumber /* = -1 */) const { size_t numSelections = execute(SCI_GETSELECTIONS); size_t start_pos, end_pos; if ((selectionNumber < 0) || (static_cast<size_t>(selectionNumber) >= numSelections)) { start_pos = execute(SCI_GETSELECTIONSTART); end_pos = execute(SCI_GETSELECTIONEND); } else { start_pos = execute(SCI_GETSELECTIONNSTART, selectionNumber); end_pos = execute(SCI_GETSELECTIONNEND, selectionNumber); } size_t line1 = execute(SCI_LINEFROMPOSITION, start_pos); size_t line2 = execute(SCI_LINEFROMPOSITION, end_pos); if ((line1 != line2) && (static_cast<size_t>(execute(SCI_POSITIONFROMLINE, line2)) == end_pos)) { // if the end of the selection includes the line-ending, // then don't include the following line in the range --line2; } return std::pair<size_t, size_t>(line1, line2); } //获取内容。是uft8格式的。所有字符都以utf8编码 void ScintillaEditView::getText(char *dest, size_t start, size_t end) const { Sci_TextRange tr; tr.chrg.cpMin = static_cast<Sci_PositionCR>(start); tr.chrg.cpMax = static_cast<Sci_PositionCR>(end); tr.lpstrText = dest; this->SendScintilla(SCI_GETTEXTRANGE, 0, &tr); } QString ScintillaEditView::getGenericTextAsQString(size_t start, size_t end) const { assert(end > start); const size_t bufSize = end - start + 1; QByteArray bytes; bytes.resize(bufSize); getText(bytes.data(), start, end); return QString(bytes); } QString ScintillaEditView::getEOLString() { intptr_t eol_mode = execute(SCI_GETEOLMODE); if (eol_mode == SC_EOL_CRLF) { return QString("\r\n"); } else if (eol_mode == SC_EOL_LF) { return QString("\n"); } else { return QString("\r"); } } size_t vecRemoveDuplicates(QList<QString>& vec) { std::unordered_set<std::string> seen; auto newEnd = std::remove_if(vec.begin(), vec.end(), [&seen](const QString& value) { return !seen.insert(value.toStdString()).second; }); vec.erase(newEnd, vec.end()); return vec.size(); } void ScintillaEditView::removeAnyDuplicateLines() { size_t fromLine = 0, toLine = 0; bool hasLineSelection = false; auto selStart = execute(SCI_GETSELECTIONSTART); auto selEnd = execute(SCI_GETSELECTIONEND); hasLineSelection = selStart != selEnd; if (hasLineSelection) { const std::pair<size_t, size_t> lineRange = getSelectionLinesRange(); // One single line selection is not allowed. if (lineRange.first == lineRange.second) { return; } fromLine = lineRange.first; toLine = lineRange.second; } else { // No selection. fromLine = 0; toLine = execute(SCI_GETLINECOUNT) - 1; } if (fromLine >= toLine) { return; } const auto startPos = execute(SCI_POSITIONFROMLINE, fromLine); const auto endPos = execute(SCI_POSITIONFROMLINE, toLine) + execute(SCI_LINELENGTH, toLine); const QString text = getGenericTextAsQString(startPos, endPos); QStringList linesVect = text.split(getEOLString()); const size_t lineCount = execute(SCI_GETLINECOUNT); const bool doingEntireDocument = (toLine == (lineCount - 1)); if (!doingEntireDocument) { if (linesVect.rbegin()->isEmpty()) { linesVect.pop_back(); } } size_t origSize = linesVect.size(); size_t newSize = vecRemoveDuplicates(linesVect); if (origSize != newSize) { QString joined = linesVect.join(getEOLString()); if (!doingEntireDocument) { joined += getEOLString(); } if (text != joined) { QByteArray str2replace; str2replace = joined.toUtf8(); replaceTarget(str2replace, startPos, endPos); } } } void ScintillaEditView::insertCharsFrom(size_t position, const QByteArray & text2insert) const { this->SendScintilla(SCI_INSERTTEXT, position, text2insert.data()); } void ScintillaEditView::appandGenericText(const QByteArray &text2Append) const { this->SendScintilla(SCI_APPENDTEXT, text2Append.size(), text2Append.data()); } void ScintillaEditView::insertNewLineAboveCurrentLine(bool) { QString newline = getEOLString(); const auto current_line = getCurrentLineNumber(); if (current_line == 0) { // Special handling if caret is at first line. insertCharsFrom(0, newline.toUtf8()); } else { const auto eol_length = newline.length(); const auto position = execute(SCI_POSITIONFROMLINE, current_line) - eol_length; insertCharsFrom(position, newline.toUtf8()); } execute(SCI_SETEMPTYSELECTION, execute(SCI_POSITIONFROMLINE, current_line)); } void ScintillaEditView::insertNewLineBelowCurrentLine(bool) { QString newline = getEOLString(); const auto line_count = execute(SCI_GETLINECOUNT); const auto current_line = getCurrentLineNumber(); if (current_line == line_count - 1) { // Special handling if caret is at last line. appandGenericText(newline.toUtf8()); } else { const auto eol_length = newline.length(); const auto position = eol_length + execute(SCI_GETLINEENDPOSITION, current_line); insertCharsFrom(position, newline.toUtf8()); } execute(SCI_SETEMPTYSELECTION, execute(SCI_POSITIONFROMLINE, current_line + 1)); } void ScintillaEditView::sortLines(size_t fromLine, size_t toLine, ISorter* pSort) { if (fromLine >= toLine) { return; } const auto startPos = execute(SCI_POSITIONFROMLINE, fromLine); const auto endPos = execute(SCI_POSITIONFROMLINE, toLine) + execute(SCI_LINELENGTH, toLine); const QString text = getGenericTextAsQString(startPos, endPos); QStringList splitText = text.split(getEOLString()); const size_t lineCount = execute(SCI_GETLINECOUNT); const bool sortEntireDocument = toLine == lineCount - 1; if (!sortEntireDocument) { if (splitText.rbegin()->isEmpty()) { splitText.pop_back(); } } assert(toLine - fromLine + 1 == splitText.size()); const QList<QString> sortedText = pSort->sort(splitText); QString joined = sortedText.join(getEOLString()); if (sortEntireDocument) { assert(joined.length() == text.length()); } else { assert(joined.length() + getEOLString().length() == text.length()); joined += getEOLString(); } if (text != joined) { QByteArray bytes = joined.toUtf8(); replaceTarget(bytes, startPos, endPos); } } void ScintillaEditView::setFoldColor(int margin, QColor fgClack, QColor bkColor, QColor foreActive) { SendScintilla(SCI_MARKERSETFORE, margin, fgClack); SendScintilla(SCI_MARKERSETBACK, margin, bkColor); SendScintilla(SCI_MARKERSETBACKSELECTED, margin, foreActive); } ColumnModeInfos ScintillaEditView::getColumnModeSelectInfo() { ColumnModeInfos columnModeInfos; if (execute(SCI_GETSELECTIONS) > 1) // Multi-Selection || Column mode { intptr_t nbSel = execute(SCI_GETSELECTIONS); for (int i = 0; i < nbSel; ++i) { intptr_t absPosSelStartPerLine = execute(SCI_GETSELECTIONNANCHOR, i); intptr_t absPosSelEndPerLine = execute(SCI_GETSELECTIONNCARET, i); intptr_t nbVirtualAnchorSpc = execute(SCI_GETSELECTIONNANCHORVIRTUALSPACE, i); intptr_t nbVirtualCaretSpc = execute(SCI_GETSELECTIONNCARETVIRTUALSPACE, i); if (absPosSelStartPerLine == absPosSelEndPerLine && execute(SCI_SELECTIONISRECTANGLE)) { bool dir = nbVirtualAnchorSpc < nbVirtualCaretSpc ? L2R : R2L; columnModeInfos.push_back(ColumnModeInfo(absPosSelStartPerLine, absPosSelEndPerLine, i, dir, nbVirtualAnchorSpc, nbVirtualCaretSpc)); } else if (absPosSelStartPerLine > absPosSelEndPerLine) columnModeInfos.push_back(ColumnModeInfo(absPosSelEndPerLine, absPosSelStartPerLine, i, R2L, nbVirtualAnchorSpc, nbVirtualCaretSpc)); else columnModeInfos.push_back(ColumnModeInfo(absPosSelStartPerLine, absPosSelEndPerLine, i, L2R, nbVirtualAnchorSpc, nbVirtualCaretSpc)); } } return columnModeInfos; } void ScintillaEditView::columnReplace(ColumnModeInfos& cmi, QByteArray& str) { intptr_t totalDiff = 0; for (size_t i = 0, len = cmi.size(); i < len; ++i) { if (cmi[i].isValid()) { intptr_t len2beReplace = cmi[i]._selRpos - cmi[i]._selLpos; intptr_t diff = str.size() - len2beReplace; cmi[i]._selLpos += totalDiff; cmi[i]._selRpos += totalDiff; bool hasVirtualSpc = cmi[i]._nbVirtualAnchorSpc > 0; if (hasVirtualSpc) // if virtual space is present, then insert space { for (intptr_t j = 0, k = cmi[i]._selLpos; j < cmi[i]._nbVirtualCaretSpc; ++j, ++k) { execute(SCI_INSERTTEXT, k, reinterpret_cast<sptr_t>(" ")); } cmi[i]._selLpos += cmi[i]._nbVirtualAnchorSpc; cmi[i]._selRpos += cmi[i]._nbVirtualCaretSpc; } execute(SCI_SETTARGETRANGE, cmi[i]._selLpos, cmi[i]._selRpos); execute(SCI_REPLACETARGET, static_cast<int>(-1), reinterpret_cast<sptr_t>(str.data())); if (hasVirtualSpc) { totalDiff += cmi[i]._nbVirtualAnchorSpc + str.size(); // Now there's no more virtual space cmi[i]._nbVirtualAnchorSpc = 0; cmi[i]._nbVirtualCaretSpc = 0; } else { totalDiff += diff; } cmi[i]._selRpos += diff; } } } void ScintillaEditView::setMultiSelections(const ColumnModeInfos& cmi) { for (size_t i = 0, len = cmi.size(); i < len; ++i) { if (cmi[i].isValid()) { intptr_t selStart = cmi[i]._direction == L2R ? cmi[i]._selLpos : cmi[i]._selRpos; intptr_t selEnd = cmi[i]._direction == L2R ? cmi[i]._selRpos : cmi[i]._selLpos; execute(SCI_SETSELECTIONNSTART, i, selStart); execute(SCI_SETSELECTIONNEND, i, selEnd); } if (cmi[i]._nbVirtualAnchorSpc) execute(SCI_SETSELECTIONNANCHORVIRTUALSPACE, i, cmi[i]._nbVirtualAnchorSpc); if (cmi[i]._nbVirtualCaretSpc) execute(SCI_SETSELECTIONNCARETVIRTUALSPACE, i, cmi[i]._nbVirtualCaretSpc); } } int getNbDigits(int aNum, int base) { int nbChiffre = 1; int diviseur = base; for (;;) { int result = aNum / diviseur; if (!result) break; else { diviseur *= base; ++nbChiffre; } } if ((base == 16) && (nbChiffre % 2 != 0)) nbChiffre += 1; return nbChiffre; } void ScintillaEditView::columnReplace(ColumnModeInfos& cmi, int initial, int incr, int repeat, int format, bool isCapital, QByteArray& prefix) { assert(repeat > 0); // If there is no column mode info available, no need to do anything // If required a message can be shown to user, that select column properly or something similar // It is just a double check as taken in callee method (in case this method is called from multiple places) if (cmi.size() <= 0) return; // 0000 00 00 : Dec BASE_10 // 0000 00 01 : Hex BASE_16 // 0000 00 10 : Oct BASE_08 // 0000 00 11 : Bin BASE_02 // 0000 01 00 : 0 leading //Defined in ScintillaEditView.h : //const UCHAR MASK_FORMAT = 0x03; //const UCHAR MASK_ZERO_LEADING = 0x04; int base = format; const int stringSize = 512; QByteArray str; str.reserve(stringSize) ; // Compute the numbers to be placed at each column. std::vector<int> numbers; { int curNumber = initial; const size_t kiMaxSize = cmi.size(); while (numbers.size() < kiMaxSize) { for (int i = 0; i < repeat; i++) { numbers.push_back(curNumber); if (numbers.size() >= kiMaxSize) { break; } } curNumber += incr; } } assert(numbers.size() > 0); /*const int kibEnd = getNbDigits(*numbers.rbegin(), base); const int kibInit = getNbDigits(initial, base); const int kib = std::max<int>(kibInit, kibEnd);*/ intptr_t totalDiff = 0; const size_t len = cmi.size(); for (size_t i = 0; i < len; i++) { if (cmi[i].isValid()) { const intptr_t len2beReplaced = cmi[i]._selRpos - cmi[i]._selLpos; if (base != 16) { str = prefix + QString::number(numbers.at(i), base).toUtf8(); } else { //16进制,判断大小写 if (isCapital) { str = prefix + QString::number(numbers.at(i), base).toUpper().toUtf8(); } else { str = prefix + QString::number(numbers.at(i), base).toUtf8(); } } const intptr_t diff = str.size() - len2beReplaced; cmi[i]._selLpos += totalDiff; cmi[i]._selRpos += totalDiff; const bool hasVirtualSpc = cmi[i]._nbVirtualAnchorSpc > 0; if (hasVirtualSpc) // if virtual space is present, then insert space { for (intptr_t j = 0, k = cmi[i]._selLpos; j < cmi[i]._nbVirtualCaretSpc; ++j, ++k) { execute(SCI_INSERTTEXT, k, reinterpret_cast<sptr_t>(" ")); } cmi[i]._selLpos += cmi[i]._nbVirtualAnchorSpc; cmi[i]._selRpos += cmi[i]._nbVirtualCaretSpc; } execute(SCI_SETTARGETRANGE, cmi[i]._selLpos, cmi[i]._selRpos); execute(SCI_REPLACETARGET, static_cast<int>(-1), reinterpret_cast<sptr_t>(str.data())); if (hasVirtualSpc) { totalDiff += cmi[i]._nbVirtualAnchorSpc + str.size(); // Now there's no more virtual space cmi[i]._nbVirtualAnchorSpc = 0; cmi[i]._nbVirtualCaretSpc = 0; } else { totalDiff += diff; } cmi[i]._selRpos += diff; } } } void ScintillaEditView::getVisibleStartAndEndPosition(int * startPos, int * endPos) { assert(startPos != NULL && endPos != NULL); // Get the position of the 1st and last showing chars from the edit view QRect rcEditView; rcEditView = this->rect(); int pos = execute(SCI_POSITIONFROMPOINT, 0, 0); int line = execute(SCI_LINEFROMPOSITION, pos); *startPos = static_cast<int32_t>(execute(SCI_POSITIONFROMLINE, line)); pos = execute(SCI_POSITIONFROMPOINT, rcEditView.right() - rcEditView.left(), rcEditView.bottom() - rcEditView.top()); line = execute(SCI_LINEFROMPOSITION, pos); *endPos = static_cast<int32_t>(execute(SCI_GETLINEENDPOSITION, line)); } bool isUrlSchemeStartChar(QChar const c) { return ((c >= 'A') && (c <= 'Z')) || ((c >= 'a') && (c <= 'z')); } bool isUrlSchemeDelimiter(QChar const c) { return !(((c >= '0') && (c <= '9')) || ((c >= 'A') && (c <= 'Z')) || ((c >= 'a') && (c <= 'z')) || (c == '_')); } bool scanToUrlStart(QString &text, int textLen, int start, int* distance, int* schemeLength) { int p = start; int p0 = 0; enum { sUnknown, sScheme } s = sUnknown; while (p < textLen) { switch (s) { case sUnknown: if (isUrlSchemeStartChar(text[p]) && ((p == 0) || isUrlSchemeDelimiter(text[p - 1]))) { p0 = p; s = sScheme; } break; case sScheme: if (text[p] == ':') { *distance = p0 - start; *schemeLength = p - p0 + 1; return true; } if (!isUrlSchemeStartChar(text[p])) s = sUnknown; break; } p++; } *schemeLength = 0; *distance = p - start; return false; } bool isUrlTextChar(QChar const c) { if (c <= ' ') return false; switch (c.digitValue()) { case ('"'): case ('#'): case ('<'): case ('>'): case ('{'): case ('}'): case ('?'): case ('\u007F'): return false; } return true; } bool isUrlQueryDelimiter(QChar const c) { switch (c.digitValue()) { case '&': case '+': case '=': case ';': return true; } return false; } void scanToUrlEnd(QString & text, int textLen, int start, int* distance) { int p = start; QChar q = 0; enum { sHostAndPath, sQuery, sQueryAfterDelimiter, sQueryQuotes, sQueryAfterQuotes, sFragment } s = sHostAndPath; while (p < textLen) { switch (s) { case sHostAndPath: if (text[p] == QChar('?')) s = sQuery; else if (text[p] == '#') s = sFragment; else if (!isUrlTextChar(text[p])) { *distance = p - start; return; } break; case sQuery: if (text[p] == '#') s = sFragment; else if (isUrlQueryDelimiter(text[p])) s = sQueryAfterDelimiter; else if (!isUrlTextChar(text[p])) { *distance = p - start; return; } break; case sQueryAfterDelimiter: if ((text[p] == '\'') || (text[p] == '"') || (text[p] == '`')) { q = text[p]; s = sQueryQuotes; } else if (text[p] == '(') { q = ')'; s = sQueryQuotes; } else if (text[p] == '[') { q = ']'; s = sQueryQuotes; } else if (text[p] == '{') { q = '}'; s = sQueryQuotes; } else if (isUrlTextChar(text[p])) s = sQuery; else { *distance = p - start; return; } break; case sQueryQuotes: if (text[p] < ' ') { *distance = p - start; return; } if (text[p] == q) s = sQueryAfterQuotes; break; case sQueryAfterQuotes: if (isUrlQueryDelimiter(text[p])) s = sQueryAfterDelimiter; else { *distance = p - start; return; } break; case sFragment: if (!isUrlTextChar(text[p])) { *distance = p - start; return; } break; } p++; } *distance = p - start; } // removeUnwantedTrailingCharFromUrl removes a single unwanted trailing character from an URL. // It has to be called repeatedly, until it returns false, meaning that all unwanted characters are gone. bool removeUnwantedTrailingCharFromUrl(QChar const *text, int* length) { int l = *length - 1; if (l <= 0) return false; { // remove unwanted single characters const char *singleChars = ".,:;?!#"; for (int i = 0; singleChars[i]; i++) if (text[l] == singleChars[i]) { *length = l; return true; } } { // remove unwanted closing parenthesis const char *closingParenthesis = ")]"; const char *openingParenthesis = "(["; for (int i = 0; closingParenthesis[i]; i++) if (text[l] == closingParenthesis[i]) { int count = 0; for (int j = l - 1; j >= 0; j--) { if (text[j] == closingParenthesis[i]) count++; if (text[j] == openingParenthesis[i]) if (count > 0) count--; else return false; } if (count != 0) return false; *length = l; return true; } } return false; } bool isUrl(QString& text, int textLen, int start, int* segmentLen) { int dist = 0, schemeLen = 0; if (scanToUrlStart(text, textLen, start, &dist, &schemeLen)) { if (dist) { *segmentLen = dist; return false; } int len = 0; scanToUrlEnd(text, textLen, start + schemeLen, &len); if (len) { len += schemeLen; QString urlStr = text.mid(start, len); if (urlStr.startsWith("http://") || urlStr.startsWith("https://")) { QUrl url(urlStr); bool r = url.isValid(); if (r) { while (removeUnwantedTrailingCharFromUrl(text.data() + start, &len)); *segmentLen = len; return true; } } } len = 1; int lMax = textLen - start; while (isUrlSchemeStartChar(text[start + len]) && (len < lMax)) len++; *segmentLen = len; return false; } *segmentLen = dist; return false; } quint32 ScintillaEditView::getBigTextBlockStartLine() { return m_curBlockLineStartNum; } void ScintillaEditView::setBigTextBlockStartLine(quint32 line) { m_curBlockLineStartNum = line; } void ScintillaEditView::addHotSpot() { if (CCNotePad::s_hightWebAddr == 1) { int urlAction = urlNoUnderLineFg; int indicStyle = INDIC_PLAIN; int indicHoverStyle = INDIC_EXPLORERLINK; int indicStyleCur = this->execute(SCI_INDICGETSTYLE, URL_INDIC); int indicHoverStyleCur = this->execute(SCI_INDICGETHOVERSTYLE, URL_INDIC); if ((indicStyleCur != indicStyle) || (indicHoverStyleCur != indicHoverStyle)) { this->execute(SCI_INDICSETSTYLE, URL_INDIC, indicStyle); this->execute(SCI_INDICSETHOVERSTYLE, URL_INDIC, indicHoverStyle); this->execute(SCI_INDICSETALPHA, URL_INDIC, 70); this->execute(SCI_INDICSETFLAGS, URL_INDIC, SC_INDICFLAG_VALUEFORE); } int startPos = 0; int endPos = -1; this->getVisibleStartAndEndPosition(&startPos, &endPos); if (startPos >= endPos) { return; } this->execute(SCI_SETINDICATORCURRENT, URL_INDIC); if (urlAction == urlDisable) { this->execute(SCI_INDICATORCLEARRANGE, startPos, endPos - startPos); return; } int indicFore = this->execute(SCI_STYLEGETFORE, STYLE_DEFAULT); this->execute(SCI_SETINDICATORVALUE, indicFore); QByteArray encodedText; encodedText.resize(endPos - startPos); this->getText(encodedText.data(), startPos, endPos); QString encodedTextStr(encodedText); int wideTextLen = encodedTextStr.size(); if (wideTextLen > 0) { int startWide = 0; int lenWide = 0; int startEncoded = 0; int lenEncoded = 0; while (true) { bool r = isUrl(encodedTextStr, encodedTextStr.size(), startWide, &lenWide); if (lenWide <= 0) break; lenEncoded = encodedTextStr.mid(startWide, lenWide).toUtf8().size(); if (r) this->execute(SCI_INDICATORFILLRANGE, startEncoded + startPos, lenEncoded); else this->execute(SCI_INDICATORCLEARRANGE, startEncoded + startPos, lenEncoded); startWide += lenWide; startEncoded += lenEncoded; if ((startWide >= wideTextLen) || ((startEncoded + startPos) >= endPos)) break; } assert((startEncoded + startPos) == endPos); assert(startWide == wideTextLen); } } } void ScintillaEditView::setStyleOptions() { #if 0 //如果是黑色主题,则单独做一些风格设置 if (StyleSet::m_curStyleId == BLACK_SE) { setCaretLineBackgroundColor(QColor(0x333333)); setMatchedBraceForegroundColor(QColor(246, 81, 246)); setMatchedBraceBackgroundColor(QColor(18, 90, 36)); setCaretForegroundColor(QColor(255, 255, 255)); setFoldColor(SC_MARKNUM_FOLDEROPEN, QColor(45, 130, 45), QColor(222, 222, 222)); setFoldColor(SC_MARKNUM_FOLDER, QColor(45, 130, 45), QColor(222, 222, 222)); setFoldColor(SC_MARKNUM_FOLDERSUB, QColor(45, 130, 45), QColor(222, 222, 222)); setFoldColor(SC_MARKNUM_FOLDERTAIL, QColor(45, 130, 45), QColor(222, 222, 222)); setFoldColor(SC_MARKNUM_FOLDEREND, QColor(45, 130, 45), QColor(222, 222, 222)); setFoldColor(SC_MARKNUM_FOLDEROPENMID, QColor(45, 130, 45), QColor(222, 222, 222)); setFoldColor(SC_MARKNUM_FOLDERMIDTAIL, QColor(45, 130, 45), QColor(222, 222, 222)); } else { setCaretLineBackgroundColor(QColor(0xe8e8ff)); setMatchedBraceForegroundColor(QColor(191, 141, 255)); setMatchedBraceBackgroundColor(QColor(222, 222, 222)); setCaretForegroundColor(QColor(0, 0, 0)); setFoldColor(SC_MARKNUM_FOLDEROPEN, QColor(Qt::white), QColor(128, 128, 128)); setFoldColor(SC_MARKNUM_FOLDER, QColor(Qt::white), QColor(128, 128, 128)); setFoldColor(SC_MARKNUM_FOLDERSUB, QColor(Qt::white), QColor(128, 128, 128)); setFoldColor(SC_MARKNUM_FOLDERTAIL, QColor(Qt::white), QColor(128, 128, 128)); setFoldColor(SC_MARKNUM_FOLDEREND, QColor(Qt::white), QColor(128, 128, 128)); setFoldColor(SC_MARKNUM_FOLDEROPENMID, QColor(Qt::white), QColor(128, 128, 128)); setFoldColor(SC_MARKNUM_FOLDERMIDTAIL, QColor(Qt::white), QColor(128, 128, 128)); } #endif } //在ScintillaEditView中直接设置这些One_Stype_Info的属性值 //这里的style不一定是在lexer中的,而是默认的STYLE_*自定义的那些全局内部风格。 void ScintillaEditView::updateThemes() { //第0个是GLOBAL_OVERRIDE,是Lexer的样式,不属于全局 for (int i = 1; i <= URL_HOVERRED; ++i) { setGlobalFgColor(i); setGlobalBgColor(i); setGlobalFont(i); } } static void getFoldColor(QColor& fgColor, QColor& bgColor, QColor& activeFgColor) { //这里看起来反了,但是实际代码就是如此 fgColor = StyleSet::s_global_style->fold.bgColor; bgColor = StyleSet::s_global_style->fold.fgColor; activeFgColor = StyleSet::s_global_style->fold_active.fgColor; } void ScintillaEditView::setGlobalFgColor(int style) { switch (style) { case GLOBAL_OVERRIDE: { //全局前景色修改,是针对语法的lexer属性进行的修改,而非其余全局属性的修改。这点要区分开来 } break; case DEFAULT_STYLE: { //修改默认前景色 SendScintilla(SCI_STYLESETFORE, StyleSet::s_global_style->default_style.styleId, StyleSet::s_global_style->default_style.fgColor); } break; case INDENT_GUIDELINE: { //修改默认前景色 SendScintilla(SCI_STYLESETFORE, StyleSet::s_global_style->indent_guideline.styleId, StyleSet::s_global_style->indent_guideline.fgColor); } break; case BRACE_HIGHIGHT: { //修改默认前景色 SendScintilla(SCI_STYLESETFORE, StyleSet::s_global_style->brace_highight.styleId, StyleSet::s_global_style->brace_highight.fgColor); } break; case BAD_BRACE_COLOUR: { //修改默认前景色 SendScintilla(SCI_STYLESETFORE, StyleSet::s_global_style->bad_brace_color.styleId, StyleSet::s_global_style->bad_brace_color.fgColor); } break; case CURRENT_LINE_BACKGROUND_COLOR: //不能设置前景色,只能设置背景 break; case SELECT_TEXT_COLOR: SendScintilla(SCI_SETSELFORE, true, StyleSet::s_global_style->select_text_color.fgColor); break; case CARET_COLOUR: SendScintilla(SCI_SETCARETFORE, StyleSet::s_global_style->caret_colour.fgColor); break; case EDGE_COLOUR: SendScintilla(SCI_SETEDGECOLOUR, StyleSet::s_global_style->edge_colour.fgColor); break; case LINE_NUMBER_MARGIN: { //修改默认前景色 SendScintilla(SCI_STYLESETFORE, StyleSet::s_global_style->line_number_margin.styleId, StyleSet::s_global_style->line_number_margin.fgColor); } break; case BOOKMARK_MARGIN: //不能设置 break; case FOLD: case FOLD_ACTIVE: { QColor foldfgColor = Qt::white, foldbgColor = Qt::gray, activeFoldFgColor = Qt::red; getFoldColor(foldfgColor, foldbgColor, activeFoldFgColor); setFoldColor(SC_MARKNUM_FOLDEROPEN, foldfgColor, foldbgColor, activeFoldFgColor); setFoldColor(SC_MARKNUM_FOLDER, foldfgColor, foldbgColor, activeFoldFgColor); setFoldColor(SC_MARKNUM_FOLDERSUB, foldfgColor, foldbgColor, activeFoldFgColor); setFoldColor(SC_MARKNUM_FOLDERTAIL, foldfgColor, foldbgColor, activeFoldFgColor); setFoldColor(SC_MARKNUM_FOLDEREND, foldfgColor, foldbgColor, activeFoldFgColor); setFoldColor(SC_MARKNUM_FOLDEROPENMID, foldfgColor, foldbgColor, activeFoldFgColor); setFoldColor(SC_MARKNUM_FOLDERMIDTAIL, foldfgColor, foldbgColor, activeFoldFgColor); //暂时开启,看看后面是否有错误 //execute(SCI_MARKERENABLEHIGHLIGHT, true); } break; case FOLD_MARGIN: //前景背景一起设置,不分开 { setFoldMarginColors(StyleSet::s_global_style->fold_margin.fgColor, StyleSet::s_global_style->fold_margin.bgColor); } break; case WHITE_SPACE_SYMBOL: SendScintilla(SCI_SETWHITESPACEFORE, true, StyleSet::s_global_style->white_space_stybol.fgColor); break; case SMART_HIGHLIGHTING: //只能设置前景,不能设置背景 SendScintilla(SCI_INDICSETFORE, SCE_UNIVERSAL_FOUND_STYLE_SMART, StyleSet::s_global_style->smart_highlighting.fgColor); break; case FIND_MARK_STYLE: //只能设置前景,不能设置背景。目前这条是空的,暂时没有使用 SendScintilla(SCI_INDICSETFORE, SCE_UNIVERSAL_FOUND_STYLE, StyleSet::s_global_style->find_mark_style.fgColor); break; case MARK_STYLE_1: case MARK_STYLE_2: case MARK_STYLE_3: case MARK_STYLE_4: case MARK_STYLE_5: case INCREMENTAL_HIGHLIGHT: //暂时没有使用 break; case TAGS_MATCH_HIGHLIGHT: SendScintilla(SCI_INDICSETFORE, SCE_UNIVERSAL_TAGMATCH, StyleSet::s_global_style->tags_match_highlight.fgColor); break; case TAGS_ATTRIBUTE: SendScintilla(SCI_INDICSETFORE, SCE_UNIVERSAL_TAGATTR, StyleSet::s_global_style->tags_attribute.fgColor); break; //case ACTIVE_TAB_FOCUSED: //case ACTIVE_TAB_UNFOCUSED: //case ACTIVE_TAB_TEXT: //case INACTIVE_TABS: // break; case URL_HOVERRED: SendScintilla(SCI_INDICSETHOVERFORE, URL_INDIC, StyleSet::s_global_style->url_hoverred.fgColor); break; default: break; } }; void ScintillaEditView::setGlobalBgColor(int style) { switch (style) { case GLOBAL_OVERRIDE: { } break; case DEFAULT_STYLE: { //修改默认前景色 SendScintilla(SCI_STYLESETBACK, StyleSet::s_global_style->default_style.styleId, StyleSet::s_global_style->default_style.bgColor); } break; case INDENT_GUIDELINE: { //修改默认前景色 SendScintilla(SCI_STYLESETBACK, StyleSet::s_global_style->indent_guideline.styleId, StyleSet::s_global_style->indent_guideline.bgColor); } break; case BRACE_HIGHIGHT: { //修改默认前景色 SendScintilla(SCI_STYLESETBACK, StyleSet::s_global_style->brace_highight.styleId, StyleSet::s_global_style->brace_highight.bgColor); } break; case BAD_BRACE_COLOUR: { //修改默认前景色 SendScintilla(SCI_STYLESETBACK, StyleSet::s_global_style->bad_brace_color.styleId, StyleSet::s_global_style->bad_brace_color.bgColor); } break; case CURRENT_LINE_BACKGROUND_COLOR: //不能设置前景色,只能设置背景 SendScintilla(SCI_SETCARETLINEBACK, StyleSet::s_global_style->current_line_background_color.bgColor); break; case SELECT_TEXT_COLOR: SendScintilla(SCI_SETSELBACK, true, StyleSet::s_global_style->select_text_color.bgColor); break; case CARET_COLOUR: //不能设置 break; case EDGE_COLOUR: //不能设置 break; case LINE_NUMBER_MARGIN: { //修改默认背景色 SendScintilla(SCI_STYLESETBACK, StyleSet::s_global_style->line_number_margin.styleId, StyleSet::s_global_style->line_number_margin.bgColor); } break; case BOOKMARK_MARGIN: { if (StyleSet::s_global_style->bookmark_margin.bgColor.isValid()) { SendScintilla(SCI_SETMARGINBACKN, _SC_MARGE_SYBOLE, StyleSet::s_global_style->bookmark_margin.bgColor); } else { SendScintilla(SCI_SETMARGINBACKN, _SC_MARGE_SYBOLE, StyleSet::s_global_style->line_number_margin.bgColor); } } break; case FOLD: case FOLD_ACTIVE: { QColor foldfgColor = Qt::white, foldbgColor = Qt::gray, activeFoldFgColor = Qt::red; getFoldColor(foldfgColor, foldbgColor, activeFoldFgColor); setFoldColor(SC_MARKNUM_FOLDEROPEN, foldfgColor, foldbgColor, activeFoldFgColor); setFoldColor(SC_MARKNUM_FOLDER, foldfgColor, foldbgColor, activeFoldFgColor); setFoldColor(SC_MARKNUM_FOLDERSUB, foldfgColor, foldbgColor, activeFoldFgColor); setFoldColor(SC_MARKNUM_FOLDERTAIL, foldfgColor, foldbgColor, activeFoldFgColor); setFoldColor(SC_MARKNUM_FOLDEREND, foldfgColor, foldbgColor, activeFoldFgColor); setFoldColor(SC_MARKNUM_FOLDEROPENMID, foldfgColor, foldbgColor, activeFoldFgColor); setFoldColor(SC_MARKNUM_FOLDERMIDTAIL, foldfgColor, foldbgColor, activeFoldFgColor); //暂时不能开启。因为QT下面有一个1Pix的差异,如果开启,当前fold的变化会缺失1pix的宽度,看起来难看。 // 这是QT的bug,暂时解决不了。 //execute(SCI_MARKERENABLEHIGHLIGHT, true); } break; case FOLD_MARGIN: //前景背景一起设置,不分开 { setFoldMarginColors(StyleSet::s_global_style->fold_margin.fgColor, StyleSet::s_global_style->fold_margin.bgColor); } break; case WHITE_SPACE_SYMBOL: //不能设置 break; case SMART_HIGHLIGHTING: //不能设置 break; case FIND_MARK_STYLE: //不能设置 break; //下面五个比较特殊,选择改动的是背景。单本质改动的样式却是前景 case MARK_STYLE_1: //只能设置前景,不能设置背景 SendScintilla(SCI_INDICSETFORE, SCE_UNIVERSAL_FOUND_STYLE_EXT5, StyleSet::s_global_style->mark_style_1.bgColor); changeStyleColor(0); break; case MARK_STYLE_2: //只能设置前景,不能设置背景 SendScintilla(SCI_INDICSETFORE, SCE_UNIVERSAL_FOUND_STYLE_EXT4, StyleSet::s_global_style->mark_style_2.bgColor); changeStyleColor(1); break; case MARK_STYLE_3: //只能设置前景,不能设置背景 SendScintilla(SCI_INDICSETFORE, SCE_UNIVERSAL_FOUND_STYLE_EXT3, StyleSet::s_global_style->mark_style_3.bgColor); changeStyleColor(2); break; case MARK_STYLE_4: //只能设置前景,不能设置背景 SendScintilla(SCI_INDICSETFORE, SCE_UNIVERSAL_FOUND_STYLE_EXT2, StyleSet::s_global_style->mark_style_4.bgColor); changeStyleColor(3); break; case MARK_STYLE_5: //只能设置前景,不能设置背景 SendScintilla(SCI_INDICSETFORE, SCE_UNIVERSAL_FOUND_STYLE_EXT1, StyleSet::s_global_style->mark_style_5.bgColor); changeStyleColor(4); break; case INCREMENTAL_HIGHLIGHT: case TAGS_MATCH_HIGHLIGHT: case TAGS_ATTRIBUTE: break; //case ACTIVE_TAB_FOCUSED: //case ACTIVE_TAB_UNFOCUSED: //case ACTIVE_TAB_TEXT: //case INACTIVE_TABS: // break; case URL_HOVERRED: break; default: break; } }; // Set the font for a style. //enum Font_Set_Bit { // Bold_Bit = 0x1, // Italic_Bit = 0x2, // Underline_Bit = 0x4, // Font_Name_Bit = 0x8, // Font_Size_Bit = 0x10, //}; void ScintillaEditView::setStylesFont(const QFont& f, int style, int setBitMask) { if (setBitMask & Font_Name_Bit) { SendScintilla(SCI_STYLESETFONT, style, f.family().toUtf8().data()); } if (setBitMask & Bold_Bit) { SendScintilla(SCI_STYLESETBOLD, style, f.bold()); } if (setBitMask & Italic_Bit) { SendScintilla(SCI_STYLESETITALIC, style, f.italic()); } if (setBitMask & Underline_Bit) { SendScintilla(SCI_STYLESETUNDERLINE, style, f.underline()); } if (setBitMask & Font_Size_Bit && f.pointSize() > 2) { SendScintilla(SCI_STYLESETSIZE, style, f.pointSize()); } //如果是行号大小变化,则必须动态计算行宽度 if (style == STYLE_LINENUMBER) { updateLineNumberWidth(1); } } void ScintillaEditView::setGlobalFont(int style) { switch (style) { case GLOBAL_OVERRIDE: case INDENT_GUIDELINE: case CURRENT_LINE_BACKGROUND_COLOR: case SELECT_TEXT_COLOR: case CARET_COLOUR: case EDGE_COLOUR: case BOOKMARK_MARGIN: case FOLD: case FOLD_ACTIVE: case FOLD_MARGIN: case WHITE_SPACE_SYMBOL: case SMART_HIGHLIGHTING: case FIND_MARK_STYLE: case MARK_STYLE_1: case MARK_STYLE_2: case MARK_STYLE_3: case MARK_STYLE_4: case MARK_STYLE_5: case INCREMENTAL_HIGHLIGHT: case TAGS_MATCH_HIGHLIGHT: case TAGS_ATTRIBUTE: //case ACTIVE_TAB_FOCUSED: //case ACTIVE_TAB_UNFOCUSED: //case ACTIVE_TAB_TEXT: //case INACTIVE_TABS: case URL_HOVERRED: break; case DEFAULT_STYLE: { setStylesFont(StyleSet::s_global_style->default_style.font, STYLE_DEFAULT, 0x1f); } break; case BRACE_HIGHIGHT: { setStylesFont(StyleSet::s_global_style->brace_highight.font, STYLE_BRACELIGHT, 0x1f); } break; case BAD_BRACE_COLOUR: { setStylesFont(StyleSet::s_global_style->bad_brace_color.font, STYLE_BRACEBAD, 0x1f); } break; case LINE_NUMBER_MARGIN: { //除了下划线不加,其余的都需要设置 setStylesFont(StyleSet::s_global_style->line_number_margin.font, STYLE_LINENUMBER, 0x1b); } break; default: break; } } bool ScintillaEditView::isFoldIndentBased() const { QsciLexer* lexer = this->lexer(); if (lexer != nullptr) { int lexerId = lexer->lexerId(); return lexerId == L_PYTHON || lexerId == L_COFFEESCRIPT || lexerId == L_HASKELL || lexerId == L_VB || lexerId == L_YAML; } return false; } const int MAX_FOLD_COLLAPSE_LEVEL = 8; struct FoldLevelStack { int levelCount = 0; intptr_t levelStack[MAX_FOLD_COLLAPSE_LEVEL]{}; void push(intptr_t level) { while (levelCount != 0 && level <= levelStack[levelCount - 1]) { --levelCount; } levelStack[levelCount++] = level; } }; bool ScintillaEditView::isFolded(size_t line) { return (0 != execute(SCI_GETFOLDEXPANDED, line)); }; void ScintillaEditView::fold(size_t line, bool mode) { auto endStyled = execute(SCI_GETENDSTYLED); auto len = execute(SCI_GETTEXTLENGTH); if (endStyled < len) execute(SCI_COLOURISE, 0, -1); intptr_t headerLine; auto level = execute(SCI_GETFOLDLEVEL, line); if (level & SC_FOLDLEVELHEADERFLAG) headerLine = line; else { headerLine = execute(SCI_GETFOLDPARENT, line); if (headerLine == -1) return; } if (isFolded(headerLine) != mode) { execute(SCI_TOGGLEFOLD, headerLine); //SCNotification scnN; //scnN.nmhdr.code = SCN_FOLDINGSTATECHANGED; //scnN.nmhdr.hwndFrom = _hSelf; //scnN.nmhdr.idFrom = 0; //scnN.line = headerLine; //scnN.foldLevelNow = isFolded(headerLine) ? 1 : 0; //folded:1, unfolded:0 //::SendMessage(_hParent, WM_NOTIFY, 0, reinterpret_cast<LPARAM>(&scnN)); } } void ScintillaEditView::collapseFoldIndentBased(int level, bool mode) { execute(SCI_COLOURISE, 0, -1); FoldLevelStack levelStack; ++level; const intptr_t maxLine = execute(SCI_GETLINECOUNT); intptr_t line = 0; while (line < maxLine) { intptr_t level = execute(SCI_GETFOLDLEVEL, line); if (level & SC_FOLDLEVELHEADERFLAG) { level &= SC_FOLDLEVELNUMBERMASK; levelStack.push(level); if (level == levelStack.levelCount) { if (isFolded(line) != mode) { fold(line, mode); } line = execute(SCI_GETLASTCHILD, line, -1); } } ++line; } } void ScintillaEditView::collapse(int level, bool mode) { if (isFoldIndentBased()) { return collapseFoldIndentBased(level, mode); } execute(SCI_COLOURISE, 0, -1); intptr_t maxLine = execute(SCI_GETLINECOUNT); for (int line = 0; line < maxLine; ++line) { intptr_t lineLevel = execute(SCI_GETFOLDLEVEL, line); if (lineLevel & SC_FOLDLEVELHEADERFLAG) { lineLevel -= SC_FOLDLEVELBASE; if (level == (lineLevel & SC_FOLDLEVELNUMBERMASK)) if (isFolded(line) != mode) { fold(line, mode); } } } } void ScintillaEditView::comment(int type) { switch (type) { case ADD_DEL_LINE_COM: doBlockComment(cm_toggle); break; case ADD_BK_COM: doStreamComment(); break; case DEL_BK_COM: undoStreamComment(); break; default: break; } } #ifdef Q_OS_WIN void ScintillaEditView::deleteTailFileThread() { if (m_isInTailStatus) { m_isInTailStatus = false; qlonglong threadAddr = this->property(Tail_Thread).toLongLong(); std::thread* pListenThread = (std::thread*)(threadAddr); if (pListenThread->joinable()) { pListenThread->join(); } delete pListenThread; } } #endif //显示markdown编辑器 void ScintillaEditView::on_viewMarkdown() { if (m_markdownWin.isNull()) { m_markdownWin = new MarkdownView(this); m_markdownWin->setAttribute(Qt::WA_DeleteOnClose); connect(this, &ScintillaEditView::textChanged, this, &ScintillaEditView::on_updataMarkdown); } QString text = this->text(); m_markdownWin->viewMarkdown(text); m_markdownWin->show(); } void ScintillaEditView::on_updataMarkdown() { if (!m_markdownWin.isNull()) { QString text = this->text(); m_markdownWin->viewMarkdown(text); m_markdownWin->show(); } }
124,365
C++
.cpp
3,703
28.608966
237
0.690434
cxasm/notepad--
5,942
234
284
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
25,198
langstyledefine.cpp
cxasm_notepad--/src/langstyledefine.cpp
#include "langstyledefine.h" #include "userlexdef.h" #include "extlexermanager.h" #include <QInputDialog> #include <QMessageBox> #include <QSettings> #include <QFileInfo> #include <QDir> #include <QDebug> QString LangStyleDefine::s_userLangDirPath = ""; LangStyleDefine::LangStyleDefine(QWidget *parent): QMainWindow(parent) { ui.setupUi(this); loadUserLangs(); connect(ui.curDefineLangCb, QOverload<int>::of(&QComboBox::currentIndexChanged), this, &LangStyleDefine::slot_langsChange); } LangStyleDefine::~LangStyleDefine() {} //isLoadToUI是否加载显示到当前UI界面 bool LangStyleDefine::readLangSetFile(QString langName, bool isLoadToUI) { QString userLangFile = QString("notepad/userlang/%1").arg(langName);//自定义语言中不能有.字符,否则可能有错,后续要检查 QSettings qs(QSettings::IniFormat, QSettings::UserScope, userLangFile); qs.setIniCodec("UTF-8"); qDebug() << qs.fileName(); if (!qs.contains("mz")) { return false; } if (isLoadToUI) { //自定义语言格式。 //mz:ndd //name:xxx //mother:xxx none/cpp/html 就三种 //ext:xx xx xx 文件关联后缀名 //keword:xxx ui.keyWordEdit->setPlainText(qs.value("keyword").toString()); qDebug() << qs.value("keyword").toString(); ui.extNameLe->setText(qs.value("ext").toString()); qDebug() << qs.value("ext").toString(); ui.motherLangCb->setCurrentText(qs.value("mother").toString()); } return true; } //查找既有的用户自定义语言配置 void LangStyleDefine::loadUserLangs() { s_userLangDirPath = getUserLangDirPath(); //遍历文件夹 QDir dir_file(s_userLangDirPath); //dir_file.setFilter(QDir::Files | QDir::NoDotAndDotDot | QDir::NoSymLinks);//获取当前所有文件 QFileInfoList list_file = dir_file.entryInfoList(QDir::Files | QDir::NoDotAndDotDot | QDir::NoSymLinks, QDir::Name); bool isFirst = true; bool readOk = true; for (int i = 0; i < list_file.size(); ++i) { //将当前目录中所有文件添加到treewidget中 QFileInfo fileInfo = list_file.at(i); //这个文件是ext和tag的映射文件,不做配置解析 if (fileInfo.baseName() == "ext_tag") { continue; } if (isFirst) { readOk = readLangSetFile(fileInfo.baseName(), true); if (readOk) { isFirst = false; } } else { readOk = readLangSetFile(fileInfo.baseName(), false); } if (readOk) { ui.curDefineLangCb->addItem(fileInfo.baseName()); } } } void LangStyleDefine::slot_new() { QString name = QInputDialog::getText(this, tr("Create New Languages"), tr("Please Input Languages Name")); if (!name.isEmpty()) { if (-1 != name.indexOf(".")) { QMessageBox::warning(this, tr("Name Error"), tr("Name can not contains char '.' ")); return; } disconnect(ui.curDefineLangCb, QOverload<int>::of(&QComboBox::currentIndexChanged), this, &LangStyleDefine::slot_langsChange); ui.curDefineLangCb->addItem(name); ui.curDefineLangCb->setCurrentIndex(ui.curDefineLangCb->count()-1); ui.extNameLe->clear(); ui.motherLangCb->setCurrentIndex(0); ui.keyWordEdit->clear(); connect(ui.curDefineLangCb, QOverload<int>::of(&QComboBox::currentIndexChanged), this, &LangStyleDefine::slot_langsChange); } } void LangStyleDefine::slot_save() { if (ui.extNameLe->text().trimmed().isEmpty()) { QMessageBox::warning(this, tr("Ext is empty"), tr("input ext file tyle. Split with space char")); return; } if (ui.keyWordEdit->toPlainText().trimmed().isEmpty()) { QMessageBox::warning(this, tr("Keyword is empty"), tr("input Keyword. Split with space char")); return; } QString newLangName = ui.curDefineLangCb->currentText().trimmed(); if (newLangName.isEmpty()) { QMessageBox::warning(this, tr("Language name is empty"), tr("Select Definition Language Text")); return; } QString keywords = ui.keyWordEdit->toPlainText().trimmed(); int motherLangs = ui.motherLangCb->currentIndex(); motherLangs += LangType::L_USER_TXT; UserLexDef *pCppLexer = new UserLexDef(this); pCppLexer->setMotherLang(UserLangMother(motherLangs)); pCppLexer->setExtFileTypes(ui.extNameLe->text().trimmed()); pCppLexer->setKeyword(keywords); pCppLexer->writeUserSettings(newLangName); //把新语言tagName,和关联ext单独存放起来。后面只读取一个文件就能获取所有,避免遍历慢 QString extsFile = QString("notepad/userlang/ext_tag");//ext_tag是存在所有tag ext的文件 QSettings qs(QSettings::IniFormat, QSettings::UserScope, extsFile); qs.setIniCodec("UTF-8"); QStringList extList = ui.extNameLe->text().trimmed().split(" "); extList.append(QString::number(motherLangs)); //最后一个是mother lexer qs.setValue(newLangName, extList); //更新当前ExtLexerManager::getInstance()。如果不更新,就要重启软件才能生效 for (int i = 0, s = extList.size(); i < s; ++i) { ExtLexerManager::getInstance()->addNewExtType(extList.at(i), LangType(motherLangs), newLangName); } ui.statusBar->showMessage(tr("Save %1 language finished !").arg(newLangName), 10000); } void LangStyleDefine::slot_langsChange(int index) { QString name = ui.curDefineLangCb->currentText(); ui.keyWordEdit->clear(); ui.extNameLe->clear(); ui.motherLangCb->setCurrentIndex(0); readLangSetFile(name,true); } //删除当前的语言 void LangStyleDefine::slot_delete() { QString name = ui.curDefineLangCb->currentText(); //删除该语言 if (QMessageBox::Yes != QMessageBox::question(this, tr("Delete Language"), tr("Are you sure delete user define lanuage %1").arg(name))) { return; } { QString userLangFile = QString("notepad/userlang/%1").arg(name);//自定义语言中不能有.字符,否则可能有错,后续要检查 QSettings qs(QSettings::IniFormat, QSettings::UserScope, userLangFile); qs.setIniCodec("UTF-8"); //删除userlang下面的tag.ini QFile::remove(qs.fileName()); } { //把新语言在ext_tag中的关联文件记录也删除 QString extsFile = QString("notepad/userlang/ext_tag");//ext_tag是存在所有tag ext的文件 QSettings qs(QSettings::IniFormat, QSettings::UserScope, extsFile); qs.setIniCodec("UTF-8"); QStringList extList = qs.value(name).toStringList(); //更新当前ExtLexerManager::getInstance()。如果不更新,就要重启软件才能生效 for (int i = 0, s = extList.size(); i < s; ++i) { ExtLexerManager::getInstance()->remove(extList.at(i)); } qs.remove(name); } { //如果存在自定义的配置,也删除掉 QString cfgPath = QString("notepad/%1").arg(name); QSettings qs(QSettings::IniFormat, QSettings::UserScope, cfgPath); if (QFile::exists(qs.fileName())) { QFile::remove(qs.fileName()); } } ui.curDefineLangCb->removeItem(ui.curDefineLangCb->currentIndex()); ui.statusBar->showMessage(tr("Delete %1 language finished !").arg(name), 10000); }
7,055
C++
.cpp
189
30.550265
137
0.716336
cxasm/notepad--
5,942
234
284
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
25,199
encodeconvert.cpp
cxasm_notepad--/src/encodeconvert.cpp
#include "encodeconvert.h" #include "rcglobal.h" #include "CmpareMode.h" #include "doctypelistview.h" #include <QFileDialog> #include <QTreeWidgetItem> #include <QDateTime> #include <QFutureWatcher> #include <QString> #include <QtConcurrent> #include <QInputDialog> #include <QDragEnterEvent> const int ITEM_CODE = Qt::UserRole + 1; static QString fileSuffix(const QString& filePath) { QFileInfo fi(filePath); return fi.suffix(); } static QString getFileSizeFormat(qint64 size) { #if 0 if (size <= 1000) { return QString("%1").arg(size); } QString fileSize = QString("%1").arg(size); return QString("%1,%2").arg(fileSize.left(fileSize.count() - 3)).arg(fileSize.right(3)); #endif return QString::number(size); } EncodeConvert::EncodeConvert(QWidget *parent): QWidget(parent), m_commitCmpFileNums(0), m_finishCmpFileNums(0), m_menu(nullptr) { ui.setupUi(this); m_extComBoxNum = 0; connect(ui.treeWidget, &QTreeWidget::itemPressed, this, &EncodeConvert::slot_itemClicked); setAcceptDrops(true); } EncodeConvert::~EncodeConvert() { for (auto var : m_supportFileExt) { delete var; } m_supportFileExt.clear(); } bool EncodeConvert::isSupportExt(int index, QString ext) { bool ret = false; if (0 == index) { ret = DocTypeListView::isSupportExt(ext); } else if (index >= 1) { int i = index - 1; if (i < m_supportFileExt.count()) { ret = m_supportFileExt[i]->contains(ext); } } return ret; } //右键菜单 void EncodeConvert::slot_itemClicked(QTreeWidgetItem* item, int /*column*/) { if ((item != nullptr) && (Qt::RightButton == QGuiApplication::mouseButtons())) { if (m_menu == nullptr) { m_menu = new QMenu(this); m_menu->addAction(tr("&Show File in Explorer..."), this, [&]() { QString path, cmd; QTreeWidgetItem* it = ui.treeWidget->currentItem(); if (it == nullptr) { return; } path = QString("%1").arg(it->data(0, Qt::ToolTipRole).toString()); showFileInExplorer(path); }); } m_menu->move(QCursor::pos()); m_menu->show(); } } //用户自定义类型 void EncodeConvert::slot_userDefineExt() { bool ok = false; QString text = QInputDialog::getText(this, tr("input file ext()"),tr("ext (Split With :)"), QLineEdit::Normal, QString(".h:.cpp"), &ok); if (ok && !text.isEmpty()) { text = text.trimmed(); ui.extComboBox->addItem(text); QStringList extList = text.split(":"); QMap<QString, bool>* p = new QMap<QString, bool>; for (QString var : extList) { if (var.startsWith(".")) { p->insert(var.mid(1), true); } } m_supportFileExt.append(p); ++m_extComBoxNum; ui.extComboBox->setCurrentIndex(m_extComBoxNum); } } //打开文件目录 void EncodeConvert::slot_selectFile() { //加载左边的文件树 QString rootpath = QFileDialog::getExistingDirectory(this, tr("Open Directory"), QString(), QFileDialog::DontResolveSymlinks); if (!rootpath.isEmpty()) { ui.treeWidget->clear(); m_fileAttris.clear(); loadDir(rootpath); setItemIntervalBackground(); scanFileCode(); } } int EncodeConvert::allfile(QTreeWidgetItem* root_, QString path_) { QList<WalkFileInfo> dirsList; WalkFileInfo oneDir(0, root_, path_); dirsList.append(oneDir); int fileNums = 0; m_fileDirPath = path_; while (!dirsList.isEmpty()) { WalkFileInfo curDir = dirsList.first(); dirsList.pop_front(); QTreeWidgetItem* root = curDir.root; QString path = curDir.path; int direction = curDir.direction; /*添加path路径文件*/ QDir dir(path); //遍历各级子目录 //先获取文件到列表 //再获取文件夹到列表 QFileInfoList folder_list = dir.entryInfoList(QDir::Dirs | QDir::NoDotAndDotDot); //获取当前所有目录 for (int i = 0; i != folder_list.size(); ++i) //自动递归添加各目录到上一级目录 { QString namepath = folder_list.at(i).absoluteFilePath(); //获取路径 QFileInfo folderinfo = folder_list.at(i); QString name = folderinfo.fileName(); //获取目录名 QTreeWidgetItem* childroot = new QTreeWidgetItem(QStringList() << name); childroot->setIcon(0, QIcon(":/Resources/img/dir.png")); root->addChild(childroot); //将当前目录添加成path的子项 fileAttriNode node; node.type = RC_DIR;//是目录 node.selfItem = childroot; node.parent = root; node.relativePath = folderinfo.absoluteFilePath(); //把路径名称保存到tips中,后续需要这个来排序,下同 childroot->setData(0, Qt::ToolTipRole, node.relativePath); m_fileAttris.append(node); WalkFileInfo oneDir(direction, childroot, namepath); dirsList.push_front(oneDir); } QDir dir_file(path); dir_file.setFilter(QDir::Files | QDir::NoDotAndDotDot | QDir::NoSymLinks);//获取当前所有文件 QFileInfoList list_file = dir_file.entryInfoList(); for (int i = 0; i < list_file.size(); ++i) { //将当前目录中所有文件添加到treewidget中 QFileInfo fileInfo = list_file.at(i); QString name2 = fileInfo.fileName(); QTreeWidgetItem* child = new QTreeWidgetItem(QStringList() << name2); child->setIcon(0, QIcon(":/Resources/img/point.png")); child->setText(1, getFileSizeFormat(fileInfo.size())); /*QString lastModifyTime = fileInfo.lastModified().toString("yy/MM/dd hh:mm:ss"); child->setText(2, lastModifyTime);*/ root->addChild(child); fileAttriNode node; node.type = RC_FILE;//是文件 node.selfItem = child; node.parent = root; node.relativePath = fileInfo.absoluteFilePath(); //把路径名称保存到tips中,后续需要这个来排序,下同 child->setData(0, Qt::ToolTipRole, node.relativePath); m_fileAttris.append(node); } fileNums += list_file.size(); } return fileNums; } int EncodeConvert::loadDir(QString rootDirPath) { QString rootpath = rootDirPath; QTreeWidgetItem* root = nullptr; int fileNums = 0; ui.treeWidget->setColumnWidth(0, 400); ui.treeWidget->clear(); root = new QTreeWidgetItem(ui.treeWidget); root->setText(0, rootpath); root->setExpanded(true); //第一个节点是目录根节点 fileAttriNode node; node.type = RC_DIR;//是目录 node.selfItem = root; node.parent = nullptr; node.relativePath = "."; m_fileAttris.append(node); fileNums = allfile(root, rootpath); return fileNums; } QFuture<EncodeThreadParameter*> EncodeConvert::commitTask(std::function<EncodeThreadParameter* (EncodeThreadParameter*)> fun, EncodeThreadParameter* parameter) { /* 这里最开始准备使用信号提交多线程,但是发现std:;function无法使用槽函数机制,需要自己是实现元对象 * 直接使用QtConcurrent::run机制,不仅简单许多,而且在网上看了资料 */ return QtConcurrent::run(fun, parameter); } //识别文件编码 QFuture<EncodeThreadParameter_*> EncodeConvert::checkFileCode(QString filePath, QTreeWidgetItem* item) { EncodeThreadParameter_* p = new EncodeThreadParameter_(filePath); p->item = item; //int 0相等 1 不等 return commitTask([](EncodeThreadParameter_* parameter)->EncodeThreadParameter_* { //整个文件都要扫描完毕。还是怕太慢,最多1000行吧 parameter->code = CmpareMode::scanFileRealCode(parameter->filepath,1000); return parameter; } , p); } CODE_ID EncodeConvert::convertFileToCode(QString& filePath, CODE_ID srcCode, CODE_ID dstCode) { if (srcCode == CODE_ID::UNKOWN) { return CODE_ID::UNKOWN; } QFile file(filePath); if (!file.open(QIODevice::ReadOnly | QIODevice::ExistingOnly)) { return CODE_ID::UNKOWN; } QByteArray content = file.readAll(); file.close(); int skip = 0; switch (srcCode) { case UNKOWN: break; case ANSI: break; case UNICODE_LE: skip = 2; break; case UNICODE_BE: skip = 2; break; case UTF8_NOBOM: break; case UTF8_BOM: skip = 3; break; case GBK: break; default: break; } if (!file.open(QIODevice::WriteOnly | QIODevice::ExistingOnly | QIODevice::Truncate)) { return CODE_ID::UNKOWN; } QByteArray text2Save; if (skip == 2 && content.size() >= 2) { text2Save = QByteArray(content.mid(2)); } else if (skip == 3 && content.size() >= 3) { text2Save = QByteArray(content.mid(3)); } else { text2Save = QByteArray(content); } QString textOut; Encode::tranStrToUNICODE(srcCode, text2Save.data(), text2Save.size(), textOut); if (dstCode != UNKOWN) { //QByteArray codeFlag = Encode::getEncodeStartFlagByte(dstCode); //20210822 发现大坑,转换到一定格式后,字符串前面自动带了标识,不需要再来检查一次 //if (!codeFlag.isEmpty()) //{ // //先写入标识头 // file.write(codeFlag); //} //如果编码是已知如下类型,则后续保存其它行时,不修改编码格式,继续按照原编码进行保存 //前面已经设置过编码了,这里不需要再设置 if (dstCode == CODE_ID::UTF8_BOM) { //自动转换不会带UTF-8 BOM,所以自己要在前面写个BOM头。这是一个例外。需要手动写入头 //其他必然BL LE则不需要。 QByteArray codeFlag = Encode::getEncodeStartFlagByte(dstCode); if (!codeFlag.isEmpty()) { //先写入标识头 file.write(codeFlag); } } if (textOut.length() > 0) { //保存时注意编码问题。这个tolocal已经带了字符BOM头了。只要UTF8_BOM不会带 QByteArray t = textOut.toLocal8Bit(); file.write(textOut.toLocal8Bit()); } } file.close(); return dstCode; } CODE_ID EncodeConvert::getComboBoxCode(int index){ CODE_ID ret = CODE_ID::UNKOWN; if (index < CODE_END) { ret = (CODE_ID)index; } return ret; }; QFuture<EncodeThreadParameter_*> EncodeConvert::convertFileCode(QString filePath, QTreeWidgetItem* item) { EncodeThreadParameter_* p = new EncodeThreadParameter_(filePath); p->item = item; CODE_ID srcCode = static_cast<CODE_ID>(item->data(0, ITEM_CODE).toInt()); CODE_ID dstCode = getComboBoxCode(ui.codeToComboBox->currentIndex()); //int 0相等 1 不等 return commitTask([=](EncodeThreadParameter_* parameter)->EncodeThreadParameter_* { if (dstCode != CODE_ID::UNKOWN) { parameter->code = convertFileToCode(parameter->filepath, srcCode, dstCode); } else { parameter->code = UNKOWN; } return parameter; } , p); } //20220114 仅仅使用第一行失败编码还是不行,因为utf8和gbk其实有相同的编码范围。 //如果识别第一行为gbk的,则直接使用gbk。但是如果识别为utf8的,则需要识别更多的文本内容,这样会更慢 void EncodeConvert::scanFileCode() { m_finishCmpFileNums = 0; m_commitCmpFileNums = 0; ui.selectFileBt->setEnabled(false); ui.startBt->setEnabled(false); ui.closeBt->setEnabled(false); ui.logTextBrowser->clear(); ui.logTextBrowser->append(tr("start scan file text code, please wait...")); for (QList<fileAttriNode>::iterator iter = m_fileAttris.begin(); iter != m_fileAttris.end(); ++iter) { if (iter->type == RC_DIR) { iter->selfItem->setText(2, QString("--")); } //20230304 编码转换这里,不能仅仅只识别已知后缀文件,要失败所有文件 else if ((iter->type == RC_FILE) && DocTypeListView::isSupportExt(fileSuffix(iter->relativePath))) { QFutureWatcher<EncodeThreadParameter_*>* futureWatcher = new QFutureWatcher<EncodeThreadParameter_*>(); QObject::connect(futureWatcher, &QFutureWatcher<EncodeThreadParameter_>::finished, this, &EncodeConvert::slot_scanFileCode); futureWatcher->setFuture(this->checkFileCode(iter->relativePath,iter->selfItem)); ++m_commitCmpFileNums; } else { iter->selfItem->setText(2, tr("ignore")); } } int finishProcessRatio = 0; while (m_finishCmpFileNums < m_commitCmpFileNums) { int curProcessRatio = m_finishCmpFileNums * 100 / m_commitCmpFileNums; //没%5更新一下 if (curProcessRatio - finishProcessRatio >= 5) { finishProcessRatio = curProcessRatio; ui.logTextBrowser->append(tr("please wait, total file %1,cur scan index %2, scan finish %3%").arg(m_commitCmpFileNums).arg(m_finishCmpFileNums).arg(curProcessRatio)); } QCoreApplication::processEvents(); } ui.logTextBrowser->append(tr("scan finished, total file %1").arg(m_commitCmpFileNums)); ui.selectFileBt->setEnabled(true); ui.startBt->setEnabled(true); ui.closeBt->setEnabled(true); } //文件对比完毕,显示出文件是否意义,不一样则红色字符标识 void EncodeConvert::slot_scanFileCode() { QFutureWatcher<EncodeThreadParameter_*>* s = dynamic_cast<QFutureWatcher<EncodeThreadParameter_*> *>(sender()); EncodeThreadParameter_* result = s->result(); //这里释放的内容,其实是在mode里面new出来的 if (result != nullptr) { result->item->setText(2, Encode::getCodeNameById(result->code)); result->item->setData(0, ITEM_CODE, result->code); delete result; result = nullptr; } delete s; s = nullptr; ++m_finishCmpFileNums; } void EncodeConvert::slot_startConvert() { int extComboBoxIndex = ui.extComboBox->currentIndex(); CODE_ID dstCode = getComboBoxCode(ui.codeToComboBox->currentIndex()); m_finishCmpFileNums = 0; m_commitCmpFileNums = 0; ui.logTextBrowser->clear(); //如果编码是已知如下类型,则后续保存其它行时,不修改编码格式,继续按照原编码进行保存 QString destCodeName = Encode::getQtCodecNameById(dstCode); if (destCodeName.isEmpty() || destCodeName == "unknown") { //这里永远不会走。因为界面上不会有未知选项 assert(false); return; } else { QTextCodec::setCodecForLocale(QTextCodec::codecForName(destCodeName.toStdString().c_str())); } ui.selectFileBt->setEnabled(false); ui.codeToComboBox->setEditable(false); ui.closeBt->setEnabled(false); for (QList<fileAttriNode>::iterator iter = m_fileAttris.begin(); iter != m_fileAttris.end(); ++iter) { if ((iter->type == RC_FILE) && isSupportExt(extComboBoxIndex, fileSuffix(iter->relativePath))) { qDebug() << iter->relativePath; CODE_ID srcCode = static_cast<CODE_ID>(iter->selfItem->data(0, ITEM_CODE).toInt()); CODE_ID dstCode = getComboBoxCode(ui.codeToComboBox->currentIndex()); if (srcCode != dstCode) { QFutureWatcher<EncodeThreadParameter_*>* futureWatcher = new QFutureWatcher<EncodeThreadParameter_*>(); QObject::connect(futureWatcher, &QFutureWatcher<EncodeThreadParameter_>::finished, this, &EncodeConvert::slot_convertFileFinish); futureWatcher->setFuture(this->convertFileCode(iter->relativePath, iter->selfItem)); ++m_commitCmpFileNums; } else { iter->selfItem->setText(4, tr("already %1 ignore").arg(Encode::getCodeNameById(srcCode))); } } else { iter->selfItem->setText(4, tr("ignore")); } } int finishProcessRatio = 0; while (m_finishCmpFileNums < m_commitCmpFileNums) { int curProcessRatio = m_finishCmpFileNums * 100 / m_commitCmpFileNums; //没%5更新一下 if (curProcessRatio - finishProcessRatio >= 5) { finishProcessRatio = curProcessRatio; ui.logTextBrowser->append(tr("total file %1,cur deal index %2,finish %3%").arg(m_commitCmpFileNums).arg(m_finishCmpFileNums).arg(curProcessRatio)); } QCoreApplication::processEvents(); } ui.logTextBrowser->append(tr("total file %1,cur deal index %2,finish 100%").arg(m_commitCmpFileNums).arg(m_finishCmpFileNums)); ui.logTextBrowser->append(tr("convert finished !")); ui.selectFileBt->setEnabled(true); ui.codeToComboBox->setEditable(true); ui.closeBt->setEnabled(true); } //转换完成,设置当前表格上的显示状态 void EncodeConvert::slot_convertFileFinish() { QFutureWatcher<EncodeThreadParameter_*>* s = dynamic_cast<QFutureWatcher<EncodeThreadParameter_*> *>(sender()); EncodeThreadParameter_* result = s->result(); //这里释放的内容,其实是在mode里面new出来的 if (result != nullptr) { if (result->code != UNKOWN) { result->item->setText(3, Encode::getCodeNameById(result->code)); result->item->setText(4, tr("convert finish")); } else { result->item->setText(4, tr("convert fail")); ui.logTextBrowser->append(tr("file %1 convert failed,pleas check...").arg(result->item->data(0, Qt::ToolTipRole).toString())); } result->item->setData(0, ITEM_CODE, result->code); delete result; result = nullptr; } delete s; s = nullptr; ++m_finishCmpFileNums; } //对item进行间隔着色 void EncodeConvert::setItemIntervalBackground() { int curItemIndex = 0; QTreeWidgetItemIterator it(ui.treeWidget); while (*it) { if (curItemIndex % 2 == 1) { setItemBackground(*it, QColor(0xf8faf9)); } ++it; ++curItemIndex; } } void EncodeConvert::setItemBackground(QTreeWidgetItem* item, const QColor& color) { QBrush b(color); item->setBackground(0, b); item->setBackground(1, b); item->setBackground(2, b); item->setBackground(3, b); item->setBackground(4, b); } void EncodeConvert::dragEnterEvent(QDragEnterEvent* event) { if (event->mimeData()->hasFormat("text/uri-list")) //只能打开文本文件 { event->accept(); //可以在这个窗口部件上拖放对象 } else { event->ignore(); } } void EncodeConvert::dropEvent(QDropEvent* e) { QList<QUrl> urls = e->mimeData()->urls(); if (urls.isEmpty()) return; QString dirName = urls.first().toLocalFile(); if (dirName.isEmpty()) { return; } QDir dir(dirName); if (!dir.exists()) { ui.logTextBrowser->append(tr("please drop a file dir ...")); return; } ui.treeWidget->clear(); m_fileAttris.clear(); loadDir(dirName); setItemIntervalBackground(); scanFileCode(); e->accept(); }
18,308
C++
.cpp
554
26.243682
170
0.701011
cxasm/notepad--
5,942
234
284
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
25,200
nddpluginapi.cpp
cxasm_notepad--/src/nddpluginapi.cpp
#include "nddpluginapi.h" #include "ccnotepad.h" NddPluginApi::NddPluginApi(QObject *parent) : QObject(parent) {} NddPluginApi::~NddPluginApi() {} void NddPluginApi::setMainNotePad(QWidget * pWidget) { m_mainNotePad = pWidget; } //注意这里实际返回的是ScintillaEditView QsciScintilla* NddPluginApi::getCurrentEidtHandle() { CCNotePad* pNotepad = dynamic_cast<CCNotePad*>(m_mainNotePad); if (pNotepad != nullptr) { return pNotepad->getCurEditView(); } return nullptr; }
506
C++
.cpp
21
20.809524
64
0.755889
cxasm/notepad--
5,942
234
284
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
25,201
texteditsetwin.cpp
cxasm_notepad--/src/texteditsetwin.cpp
#include "texteditsetwin.h" #include "scintillaeditview.h" #include "ccnotepad.h" #include "qtlangset.h" #include "nddsetting.h" #include <QFontDialog> #include <QColorDialog> TextEditSetWin::TextEditSetWin(QWidget *parent) : QWidget(parent), m_notepadWin(nullptr) { ui.setupUi(this); if (ScintillaEditView::s_tabLens >= 0 && ScintillaEditView::s_tabLens <= 16) { ui.spinBoxTabLens->setValue(ScintillaEditView::s_tabLens); } ui.checkBoxReplaceTabToSpace->setChecked(ScintillaEditView::s_noUseTab); ui.BigTextSizeLimit->setValue(ScintillaEditView::s_bigTextSize); ui.restoreFile->setChecked((CCNotePad::s_restoreLastFile == 1)); int clearOpenfilelist = NddSetting::getKeyValueFromDelayNumSets(CLEAR_OPENFILE_ON_CLOSE); ui.openfileRecord->setChecked((clearOpenfilelist ==1)); QPalette pal = QApplication::palette(); QPixmap f(32, 32); f.fill(pal.text().color()); ui.appFontColorLabel->setPixmap(f); } TextEditSetWin::~TextEditSetWin() { save(); } void TextEditSetWin::setNotePadWin(QWidget *w) { m_notepadWin = w; } #if 0 //弹出对话框时,默认初始化该值 void TextEditSetWin::setProgramLangFont(QFont &font) { if (m_curProLangFont != font) { m_curProLangFont = font; } ui.curProLangFontEdit->setText(font.toString()); } #endif void TextEditSetWin::save() { bool lenChange = false; if (ui.spinBoxTabLens->value() != ScintillaEditView::s_tabLens) { ScintillaEditView::s_tabLens = ui.spinBoxTabLens->value(); lenChange = true; } bool useChange = false; if (ui.checkBoxReplaceTabToSpace->isChecked() != ScintillaEditView::s_noUseTab) { ScintillaEditView::s_noUseTab = ui.checkBoxReplaceTabToSpace->isChecked(); useChange = true; } if (lenChange || useChange) { emit sendTabFormatChange(lenChange, useChange); } if (ui.BigTextSizeLimit->value() != ScintillaEditView::s_bigTextSize) { ScintillaEditView::s_bigTextSize = ui.BigTextSizeLimit->value(); } int restoreFile = ui.restoreFile->isChecked() ? 1 : 0; if (restoreFile != CCNotePad::s_restoreLastFile) { CCNotePad::s_restoreLastFile = restoreFile; } //注意这里是禁用,和启用是相反的意思 int clearOpenfilelist = (ui.openfileRecord->isChecked() ? 1 : 0); NddSetting::updataKeyValueFromDelayNumSets(CLEAR_OPENFILE_ON_CLOSE, clearOpenfilelist); } void TextEditSetWin::slot_txtFontSet() { CCNotePad* pMainWin = dynamic_cast<CCNotePad*>(m_notepadWin); if (pMainWin == nullptr) { //是从对比规则里面弹出来的,不进行文本的设置 return; } QtLangSet* pWin = pMainWin->getLangSet(); #if 0 QtLangSet* pWin = new QtLangSet(QString("txt"), this); pWin->setAttribute(Qt::WA_DeleteOnClose); connect(pWin, &QtLangSet::viewStyleChange, pMainWin, &CCNotePad::slot_viewStyleChange); connect(pWin, &QtLangSet::viewLexerChange, pMainWin, &CCNotePad::slot_viewLexerChange); pWin->show(); #endif if (pWin != nullptr) { pWin->selectInitLangTag("txt"); } } #if 0 //app字体颜色设置 void TextEditSetWin::slot_appFontColor() { QPalette pal = qApp->palette(); QColor oldColor = pal.text().color(); QColor color = QColorDialog::getColor(pal.text().color(), this, tr("App Font Foreground Color")); if (color.isValid() && color != oldColor) { pal.setColor(QPalette::WindowText, color);//设置颜色 pal.setColor(QPalette::Text, color);//设置颜色 pal.setColor(QPalette::ButtonText, color);//设置颜色 pal.setColor(QPalette::ToolTipText, color); qApp->setPalette(pal); QPixmap f(32, 32); f.fill(pal.text().color()); ui.appFontColorLabel->setPixmap(f); //发现如果修改APP字体颜色后,必须要把存在的窗口关闭一下,否则存在的窗口的字体颜色无法生效。 CCNotePad* pMainWin = dynamic_cast<CCNotePad*>(m_notepadWin); if (pMainWin != nullptr) { //是从主界面调用的,执行一下颜色的更新 pMainWin->changeAppFontColor(color); return; } } } #endif #if 0 //不能整体修改QApplication::font(),会引发语法里面的文字重叠破坏。 //只针对菜单和状态栏,查找框字体进行修改。 void TextEditSetWin::slot_selectAppFont() { QFont ft; QFont curAppFont = QApplication::font(); bool ok = false;//定义bool型输出变量 ft = QFontDialog::getFont(&ok, curAppFont, this,tr("The App Font")); if (ok) { ui.appFontEdit->setText(ft.toString()); if (curAppFont != ft) { //emit signAppFontChange(ft); QApplication::setFont(ft,"FindResultWin"); } } } #endif #if 0 void TextEditSetWin::slot_selectProLangFont() { #if defined(Q_OS_WIN) QFont ft("Courier New", QsciLexer::s_defaultFontSize); #elif defined(Q_OS_MAC) QFont ft("Menlo", s_defaultFontSize); #else QFont ft("Bitstream Vera Sans", 9); #endif bool ok = false;//定义bool型输出变量 ft = QFontDialog::getFont(&ok, m_curProLangFont, this, tr("User define Txt Font")); if (ok) { ui.curProLangFontEdit->setText(ft.toString()); if (m_curProLangFont != ft) { m_curProLangFont = ft; emit signProLangFontChange(ft); } } else { ui.curProLangFontEdit->setText(ft.toString()); m_curProLangFont = ft; } } #endif
5,315
C++
.cpp
172
25.27907
99
0.722791
cxasm/notepad--
5,942
234
284
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
25,202
ccnotepad.cpp
cxasm_notepad--/src/cceditor/ccnotepad.cpp
#include <memory> #include "ccnotepad.h" #include "filemanager.h" #include "Encode.h" #include "findwin.h" #include "nddsetting.h" #include "findresultwin.h" #include "scintillaeditview.h" #include "scintillahexeditview.h" #include "encodeconvert.h" #include "optionsview.h" #include "donate.h" #include "renamewin.h" #include "doctypelistview.h" #include "hexfilegoto.h" #include "qscilexertext.h" #include "styleset.h" #include "qtlangset.h" #include "columnedit.h" #include "langstyledefine.h" #include "extlexermanager.h" #include "aboutndd.h" #include "filelistview.h" #include "bigfilemessage.h" #include "batchfindreplace.h" #include "langextset.h" #include "shortcutkeymgr.h" #include "md5hash.h" #include "CmpareMode.h" #ifdef NO_PLUGIN #include "pluginmgr.h" #include "plugin.h" #include "pluginGl.h" #endif #ifdef Q_OS_WIN #include "dectfilechanges.h" #endif #include <QFileDialog> #include <QDebug> #include <QTabBar> #include <QVariant> #include <QTextCodec> #include <QMessageBox> #include <QToolButton> #include <qsciscintilla.h> #include <QDockWidget> #include <QInputDialog> #include <QPair> #include <QMenu> #include <QProcess> #include <QSettings> #include <QSharedMemory> #include <QMimeDatabase> #include <QDateTime> #include <QShortcut> #ifdef Q_OS_WIN #include <QXmlQuery> #include <QXmlFormatter> #endif #include <QBuffer> #include <QXmlStreamReader> #include <QJsonObject> #include <QJsonDocument> #include <QWidgetAction> #include <QListWidgetItem> #include <QLibrary> #include "Sorters.h" #ifdef Q_OS_WIN #include <qt_windows.h> #include <Windows.h> #endif #include <memory> #ifdef Q_OS_WIN extern bool s_isAdminAuth; inline std::wstring StringToWString(const std::string& str) { #if 0 int len = MultiByteToWideChar(CP_UTF8, 0, str.c_str(), -1, NULL, 0); wchar_t* wide = new wchar_t[len + 1]; memset(wide, '\0', sizeof(wchar_t) * (len + 1)); MultiByteToWideChar(CP_UTF8, 0, str.c_str(), -1, wide, len); std::wstring w_str(wide); delete[] wide; return w_str; #endif QString temp = QString::fromStdString(str); return temp.toStdWString(); } #endif int CCNotePad::s_padTimes = 0; int CCNotePad::s_zoomValue = 0; QString CCNotePad::s_lastOpenDirPath = ""; QList<CCNotePad*> *CCNotePad::s_padInstances = nullptr; //文件保存的路径,qstring static const char* Edit_View_FilePath = "filePath"; //int 新文件的id序号。非新建文件为-1 static const char* Edit_File_New = "newfile"; //是否修改 true false static const char* Edit_Text_Change = "change"; //line行尾符号 static const char* Edit_Text_End = "lineend"; //外部修改 static const char* Modify_Outside = "modify"; //文档类型 1:text 2 hex static const char* Doc_Type = "type"; //tail状态 0 关闭 1开启 static const char* Tail_Status = "tail"; static const int MSG_EXIST_TIME = 8000; void setFileOpenAttrProperty(QWidget* pwidget, OpenAttr attr) { QVariant v(attr); pwidget->setProperty(Open_Attr, v); } const QString OpenAttrToString(OpenAttr openType) { QString ret; switch (openType) { case Text: ret = QObject::tr("Text Mode"); break; case HexReadOnly: ret = QObject::tr("Hex ReadOnly Mode"); break; case BigTextReadOnly: ret = QObject::tr("Big Text ReadOnly Mode"); break; case BigTextReadWrite: ret = QObject::tr("Big Text ReadWrite Mode"); break; case SuperBigTextReadOnly: ret = QObject::tr("Super Big Text ReadOnly Mode"); break; case TextReadOnly: ret = QObject::tr("Text ReadOnly Mode"); break; default: ret = QObject::tr("File Mode"); break; } return ret; } QString getFileOpenAttrProperty(QWidget* pwidget) { OpenAttr openType = (OpenAttr)pwidget->property(Open_Attr).toInt(); return OpenAttrToString(openType); } void setFilePathProperty(QWidget* pwidget, QString filePath) { QVariant v(filePath); pwidget->setProperty(Edit_View_FilePath, v); } QString getFilePathProperty(QWidget* pwidget) { return pwidget->property(Edit_View_FilePath).toString(); } void setFileNewIndexProperty(QWidget* pwidget, int index) { QVariant v(index); pwidget->setProperty(Edit_File_New, v); } //新文件的id,非新文件为-1 int getFileNewIndexProperty(QWidget* pwidget) { return pwidget->property(Edit_File_New).toInt(); } inline void setTextChangeProperty(QWidget* pwidget, bool status) { QVariant v(status); pwidget->setProperty(Edit_Text_Change, v); } bool getTextChangeProperty(QWidget* pwidget) { return pwidget->property(Edit_Text_Change).toBool(); } void setCodeTypeProperty(QWidget* pwidget, int type) { QVariant v(type); pwidget->setProperty(Edit_Text_Code, v); } int getCodeTypeProperty(QWidget* pwidget) { return pwidget->property(Edit_Text_Code).toInt(); } void setEndTypeProperty(QWidget* pwidget, int type) { QVariant v(type); pwidget->setProperty(Edit_Text_End, v); } int getEndTypeProperty(QWidget* pwidget) { return pwidget->property(Edit_Text_End).toInt(); } void setFileTailProperty(QWidget* pwidget, int type) { QVariant v(type); pwidget->setProperty(Tail_Status, v); } int getFileTailProperty(QWidget* pwidget) { return pwidget->property(Tail_Status).toInt(); } //根据当前路径,得到交互文件的名称 QString getSwapFilePath(QString filePath) { QFileInfo fi(filePath); #ifdef _WIN32 return QString("%1\\.%2.swp").arg(fi.absolutePath()).arg(fi.fileName()); #else return QString("%1/.%2.swp").arg(fi.absolutePath()).arg(fi.fileName()); #endif } void setDocTypeProperty(QWidget* pwidget, NddDocType type) { QVariant v(type); pwidget->setProperty(Doc_Type, v); } int getDocTypeProperty(QWidget* pwidget) { return pwidget->property(Doc_Type).toInt(); } //#define STYLE_DEEPBLUE #define STYLE_NOTEPAD #ifdef STYLE_BLACK const char *NewFileIcon = ":/Resources/edit/styleblack/newfile.png"; const char *OpenFileIcon = ":/Resources/edit/styleblack/openfile.png"; const char *NeedSaveBarIcon = ":/Resources/edit/styleblack/needsavebar.png"; const char *NoNeedSaveBarIcon = ":/Resources/edit/styleblack/noneedsavebar.png"; const char *NeedSaveAllBarIcon = ":/Resources/edit/styleblack/needsaveallbar.png"; const char *NoNeedSaveAllBarIcon = ":/Resources/edit/styleblack/noneedsaveallbar.png"; const char *CloseFileIcon = ":/Resources/edit/styleblack/closefile.png"; const char *CloseAllFileIcon = ":/Resources/edit/styleblack/closeall.png"; const char *CutIcon = ":/Resources/edit/styleblack/cut.png"; const char *CopyFileIcon = ":/Resources/edit/styleblack/copy.png"; const char *PasteIcon = ":/Resources/edit/styleblack/paste.png"; const char *UndoIcon = ":/Resources/edit/styleblack/undo.png"; const char *RedoIcon = ":/Resources/edit/styleblack/redo.png"; const char *FindIcon = ":/Resources/edit/styleblack/find.png"; const char *ReplaceIcon = ":/Resources/edit/styleblack/replace.png"; const char *ZoominIcon = ":/Resources/edit/styleblack/zoomin.png"; const char *ZoomoutIcon = ":/Resources/edit/styleblack/zoomout.png"; const char *CrlfIcon = ":/Resources/edit/styleblack/crlf.png"; const char *WhiteIcon = ":/Resources/edit/styleblack/white.png"; const char *FileCompareIcon = ":/Resources/edit/styleblack/filecompare.png"; const char *DirCompareIcon = ":/Resources/edit/styleblack/dircompare.png"; const char *TransCodeIcon = ":/Resources/edit/styleblack/transcode.png"; const char *RenameIcon = ":/Resources/edit/styleblack/rename.png"; #endif #ifdef STYLE_BLUDE const char *NewFileIcon32 = ":/Resources/edit/styleblue/newfile.png"; const char *OpenFileIcon32 = ":/Resources/edit/styleblue/openfile.png"; const char *NeedSaveBarIcon32 = ":/Resources/edit/styleblue/needsavebar.png"; const char *NoNeedSaveBarIcon32 = ":/Resources/edit/styleblue/needsavebar.png"; const char *NeedSaveAllBarIcon32 = ":/Resources/edit/styleblue/needsaveall.png"; const char *NoNeedSaveAllBarIcon32 = ":/Resources/edit/styleblue/needsaveall.png"; const char* AutoTimeSaveBarIcon32 = ":/Resources/edit/styleblue/autosave.png"; const char *CloseFileIcon32 = ":/Resources/edit/styleblue/closefile.png"; const char *CloseAllFileIcon32 = ":/Resources/edit/styleblue/closeall.png"; const char *CutIcon32 = ":/Resources/edit/styleblue/cut.png"; const char *CopyFileIcon32 = ":/Resources/edit/styleblue/copy.png"; const char *PasteIcon32 = ":/Resources/edit/styleblue/paste.png"; const char *UndoIcon32 = ":/Resources/edit/styleblue/undo.png"; const char *RedoIcon32 = ":/Resources/edit/styleblue/redo.png"; const char *FindIcon32 = ":/Resources/edit/styleblue/find.png"; const char *ReplaceIcon32 = ":/Resources/edit/styleblue/replace.png"; const char* MarkIcon32 = ":/Resources/edit/styleblue/mark.png"; const char* SignIcon32 = ":/Resources/edit/styleblue/sign.png"; const char* ClearSignIcon32 = ":/Resources/edit/styleblue/clearsign.png"; const char *ZoominIcon32 = ":/Resources/edit/styleblue/zoomin.png"; const char *ZoomoutIcon32 = ":/Resources/edit/styleblue/zoomout.png"; const char *CrlfIcon32 = ":/Resources/edit/styleblue/crlf.png"; const char *WhiteIcon32 = ":/Resources/edit/styleblue/white.png"; const char *IndentIcon32 = ":/Resources/edit/styleblue/indentGuide.png"; const char *FileCompareIcon32 = ":/Resources/edit/styleblue/filecompare.png"; const char *DirCompareIcon32 = ":/Resources/edit/styleblue/dircompare.png"; const char *BinCmpIcon32 = ":/Resources/edit/styleblue/bincmp.png"; const char *TransCodeIcon32 = ":/Resources/edit/styleblue/transcode.png"; const char *RenameIcon32 = ":/Resources/edit/styleblue/rename.png"; const char *PreHexIcon32 = ":/Resources/edit/styleblue/pre.png"; const char *NextHexIcon32 = ":/Resources/edit/styleblue/next.png"; const char *GotoHexIcon32 = ":/Resources/edit/styleblue/goto.png"; const char *TabNeedSave32 = ":/Resources/edit/global/needsave.png"; const char *TabNoNeedSave32 = ":/Resources/edit/global/noneedsave.png"; #endif const char *NewFileIcon32 = ":/Resources/edit/styledeepblue/newfile.png"; const char *OpenFileIcon32 = ":/Resources/edit/styledeepblue/openfile.png"; const char *NeedSaveBarIcon32 = ":/Resources/edit/styledeepblue/needsavebar.png"; const char *NoNeedSaveBarIcon32 = ":/Resources/edit/styledeepblue/needsavebar.png"; const char *NeedSaveAllBarIcon32 = ":/Resources/edit/styledeepblue/needsaveall.png"; const char *NoNeedSaveAllBarIcon32 = ":/Resources/edit/styledeepblue/needsaveall.png"; const char* AutoTimeSaveBarIcon32 = ":/Resources/edit/styledeepblue/autosave.png"; const char *CloseFileIcon32 = ":/Resources/edit/styledeepblue/closefile.png"; const char *CloseAllFileIcon32 = ":/Resources/edit/styledeepblue/closeall.png"; const char *CutIcon32 = ":/Resources/edit/styledeepblue/cut.png"; const char *CopyFileIcon32 = ":/Resources/edit/styledeepblue/copy.png"; const char *PasteIcon32 = ":/Resources/edit/styledeepblue/paste.png"; const char *UndoIcon32 = ":/Resources/edit/styledeepblue/undo.png"; const char *RedoIcon32 = ":/Resources/edit/styledeepblue/redo.png"; const char *FindIcon32 = ":/Resources/edit/styledeepblue/find.png"; const char *ReplaceIcon32 = ":/Resources/edit/styledeepblue/replace.png"; const char* MarkIcon32 = ":/Resources/edit/styledeepblue/mark.png"; const char* SignIcon32 = ":/Resources/edit/styledeepblue/sign.png"; const char* ClearSignIcon32 = ":/Resources/edit/styledeepblue/clearsign.png"; const char *ZoominIcon32 = ":/Resources/edit/styledeepblue/zoomin.png"; const char *ZoomoutIcon32 = ":/Resources/edit/styledeepblue/zoomout.png"; const char *CrlfIcon32 = ":/Resources/edit/styledeepblue/crlf.png"; const char *WhiteIcon32 = ":/Resources/edit/styledeepblue/white.png"; const char *IndentIcon32 = ":/Resources/edit/styledeepblue/indentGuide.png"; const char* TailfIcon32 = ":/Resources/edit/styledeepblue/tailf.png"; const char *FileCompareIcon32 = ":/Resources/edit/styledeepblue/filecompare.png"; const char *DirCompareIcon32 = ":/Resources/edit/styledeepblue/dircompare.png"; const char *BinCmpIcon32 = ":/Resources/edit/styledeepblue/bincmp.png"; const char *TransCodeIcon32 = ":/Resources/edit/styledeepblue/transcode.png"; const char *RenameIcon32 = ":/Resources/edit/styledeepblue/rename.png"; const char *PreHexIcon32 = ":/Resources/edit/styledeepblue/pre.png"; const char *NextHexIcon32 = ":/Resources/edit/styledeepblue/next.png"; const char *GotoHexIcon32 = ":/Resources/edit/styledeepblue/goto.png"; //const char *TabNeedSave32 = ":/Resources/edit/global/needsave.png"; //const char *TabNoNeedSave32 = ":/Resources/edit/global/noneedsave.png"; #if 0 const char *NewFileIconDark32 = ":/Resources/edit/styledark/newfile.png"; const char *OpenFileIconDark32 = ":/Resources/edit/styledark/openfile.png"; const char *NeedSaveBarIconDark32 = ":/Resources/edit/styledark/needsavebar.png"; const char *NoNeedSaveBarIconDark32 = ":/Resources/edit/styledark/needsavebar.png"; const char *NeedSaveAllBarIconDark32 = ":/Resources/edit/styledark/needsaveall.png"; const char *NoNeedSaveAllBarIconDark32 = ":/Resources/edit/styledark/needsaveall.png"; const char* AutoTimeSaveBarIconDark32 = ":/Resources/edit/styledark/autosave.png"; const char *CloseFileIconDark32 = ":/Resources/edit/styledark/closefile.png"; const char *CloseAllFileIconDark32 = ":/Resources/edit/styledark/closeall.png"; const char *CutIconDark32 = ":/Resources/edit/styledark/cut.png"; const char *CopyFileIconDark32 = ":/Resources/edit/styledark/copy.png"; const char *PasteIconDark32 = ":/Resources/edit/styledark/paste.png"; const char *UndoIconDark32 = ":/Resources/edit/styledark/undo.png"; const char *RedoIconDark32 = ":/Resources/edit/styledark/redo.png"; const char *FindIconDark32 = ":/Resources/edit/styledark/find.png"; const char *ReplaceIconDark32 = ":/Resources/edit/styledark/replace.png"; const char* MarkIconDark32 = ":/Resources/edit/styledark/mark.png"; const char* SignIconDark32 = ":/Resources/edit/styledark/sign.png"; const char* ClearSignIconDark32 = ":/Resources/edit/styledark/clearsign.png"; const char *ZoominIconDark32 = ":/Resources/edit/styledark/zoomin.png"; const char *ZoomoutIconDark32 = ":/Resources/edit/styledark/zoomout.png"; const char *CrlfIconDark32 = ":/Resources/edit/styledark/crlf.png"; const char *WhiteIconDark32 = ":/Resources/edit/styledark/white.png"; const char *IndentIconDark32 = ":/Resources/edit/styledark/indentGuide.png"; const char *FileCompareIconDark32 = ":/Resources/edit/styledark/filecompare.png"; const char *DirCompareIconDark32 = ":/Resources/edit/styledark/dircompare.png"; const char *BinCmpIconDark32 = ":/Resources/edit/styledark/bincmp.png"; const char *TransCodeIconDark32 = ":/Resources/edit/styledark/transcode.png"; const char *RenameIconDark32 = ":/Resources/edit/styledark/rename.png"; const char *PreHexIconDark32 = ":/Resources/edit/styledark/pre.png"; const char *NextHexIconDark32 = ":/Resources/edit/styledark/next.png"; const char *GotoHexIconDark32 = ":/Resources/edit/styledark/goto.png"; const char *TabNeedSaveDark32 = ":/Resources/edit/global/needsave.png"; const char *TabNoNeedSaveDark32 = ":/Resources/edit/global/noneedsavedark.png"; #endif const char *TabNeedSaveDark32 = ":/notepad/needsave.png"; const char *TabNoNeedSaveDark32 = ":/notepad/noneedsave.png"; #ifdef STYLE_NOTEPAD const char* NewFileIcon = ":/notepad/newFile.png"; const char* OpenFileIcon = ":/notepad/openFile.png"; const char* NeedSaveBarIcon = ":/notepad/saveFile.png"; const char* NoNeedSaveBarIcon = ":/notepad/saveFile.png"; const char* NeedSaveAllBarIcon = ":/notepad/saveAll.png"; const char* NoNeedSaveAllBarIcon = ":/notepad/saveAll.png"; const char* AutoTimeSaveBarIcon = ":/notepad/autosave.png"; const char* CloseFileIcon = ":/notepad/closeFile.png"; const char* CloseAllFileIcon = ":/notepad/closeAll.png"; const char* CutIcon = ":/notepad/cut.png"; const char* CopyFileIcon = ":/notepad/copy.png"; const char* PasteIcon = ":/notepad/paste.png"; const char* UndoIcon = ":/notepad/undo.png"; const char* RedoIcon = ":/notepad/redo.png"; const char* FindIcon = ":/notepad/find.png"; const char* ReplaceIcon = ":/notepad/findReplace.png"; const char* MarkIcon = ":/notepad/mark.png"; const char* SignIcon = ":/notepad/sign.png"; const char* ClearSignIcon = ":/notepad/clearsign.png"; const char* ZoominIcon = ":/notepad/zoomIn.png"; const char* ZoomoutIcon = ":/notepad/zoomOut.png"; const char* CrlfIcon = ":/notepad/wrap.png"; const char* WhiteIcon = ":/notepad/invisibleChar.png"; const char* IndentIcon = ":/notepad/indentGuide.png"; const char* TailfIcon = ":/notepad/tailf.png"; const char* FileCompareIcon = ":/notepad/cmpfile.png"; const char* DirCompareIcon = ":/notepad/cmpdir.png"; const char* BinCmpIcon = ":/notepad/cmpbin.png"; const char* TransCodeIcon = ":/notepad/ecg.png"; const char* RenameIcon = ":/notepad/rename.png"; const char* PreHexIcon = ":/notepad/pre.png"; const char* NextHexIcon = ":/notepad/next.png"; const char* GotoHexIcon = ":/notepad/go.png"; const char* RightCloseIcon = ":/notepad/rightClose.png"; const char *TabNeedSave = ":/notepad/needsave.png"; const char *TabNoNeedSave = ":/notepad/noneedsave.png"; #endif QString watchFilePath; //文件后缀与语言关联,与在ScintillaEditView::langNames中的序号为关联 //static QMap<QString, int> s_fileTypeToLangMap; //使用ExtLexerManager进行了替换 QStringList CCNotePad::s_findHistroy; QStringList CCNotePad::s_replaceHistroy; int CCNotePad::s_autoWarp = 0; //自动换行 int CCNotePad::s_indent = 0; //自动缩进 int CCNotePad::s_showblank = 0; //显示空白 int CCNotePad::s_restoreLastFile = 1;//自动恢复上次打开的文件 int CCNotePad::s_curStyleId = 0; int CCNotePad::s_curMarkColorId = SCE_UNIVERSAL_FOUND_STYLE_EXT5; int CCNotePad::s_hightWebAddr = 0; //lexerName to index //这里是静态的默认文件后缀类型与词法类型。还有一个动态的,用来管理用户新增语言的部分 FileExtLexer s_fileExtMapLexerId[FileExtMapLexerIdLen] = { {QString("h"), L_C}, {QString("c"), L_C}, {QString("cs"), L_CS}, {QString("cpp"), L_CPP}, {QString("cxx"), L_CPP}, {QString("rc"), L_RC}, {QString("html"), L_HTML}, {QString("htm"), L_HTML}, {QString("htmls"), L_HTML}, {QString("ini"), L_INI}, {QString("js"), L_JAVASCRIPT}, {QString("ts"), L_TYPESCRIPT}, {QString("css"), L_CSS}, {QString("java"), L_JAVA}, {QString("xml"), L_XML}, {QString("py"), L_PYTHON}, {QString("pas"), L_PASCAL}, {QString("php"), L_PHP}, {QString("sh"), L_BASH}, {QString("pl"), L_PERL}, {QString("rb"), L_RUBY}, {QString("bat"), L_BATCH}, {QString("go"), L_GO}, {QString("txt"), L_TXT}, {QString("pro"), L_INI}, {QString("pri"), L_INI}, {QString("json"), L_JSON}, {QString("lua"), L_LUA}, {QString("sql"), L_SQL}, {QString("yml"), L_YAML}, {QString("m"), L_MATLAB}, {QString("md"), L_MARKDOWN}, {QString("nsi"), L_NSIS}, {QString("nsh"), L_NSIS}, {QString("v"), L_VERILOG}, {QString("rs"), L_RUST}, {QString("frm"), L_VB}, {QString("NULL"), L_EXTERNAL}, }; RC_LINE_FORM getLineEndTypeFromBigText(QString& text) { for (int i = 0, s = text.size(); i < s; ++i) { if (text.at(i) == '\n' && ((i > 1) && text.at(i - 1) == '\r')) { return DOS_LINE; } else if (text.at(i) == '\n' && ((i > 1) && text.at(i - 1) != '\r')) { return UNIX_LINE; } else if (text.at(i) == '\r' && ((i != (s - 1)) && text.at(i + 1) != '\n')) { return MAC_LINE; } } //默认windws return DOS_LINE; } //根据文件的后缀来确定文件的编程语言,进而设置默认的LEXER void initFileTypeLangMap() { if (0 == ExtLexerManager::getInstance()->size()) { //先加载静态的关联文件后缀 for (int i = 0; i < FileExtMapLexerIdLen; ++i) { if (s_fileExtMapLexerId[i].id == L_EXTERNAL) { break; } else { FileExtLexer& v = s_fileExtMapLexerId[i]; //标准的定义可以忽略后面的tag,因为标准lexer的tag都是存在的。 ExtLexerManager::getInstance()->addNewExtType(v.ext, v.id, ScintillaEditView::getTagByLexerId(v.id)); } } //在加载动态的关联部分,这部分是用户自定义的类型。这里最好不要放在多个文件,否则会慢,单独放一个文件即可。 //把新语言tagName,和关联ext单独存放起来ext_tag.ini。只读取一个文件就能获取所有,避免遍历慢 QString extsFile = QString("notepad/userlang/ext_tag");//ext_tag是存在所有tag ext的文件 QSettings qs(QSettings::IniFormat, QSettings::UserScope, extsFile); qs.setIniCodec("UTF-8"); QStringList keys = qs.allKeys(); //LangType lexId = L_USER_TXT; bool ok = true; QString tagName; LangType lexerId; for (int i = 0, s = keys.size(); i < s; ++i) { const QString& tagName = keys.at(i); QStringList exts = qs.value(tagName).toStringList(); lexerId = (LangType)exts.takeLast().toInt(&ok); QString ext; if (ok) { foreach(ext, exts) { ExtLexerManager::getInstance()->addNewExtType(ext, lexerId, tagName); } } } //最后加载用户自定义的文件后缀名和语法关联文件 LangExtSet::loadExtRelevanceToMagr(); } } void CCNotePad::initLexerNameToIndex() { if (m_lexerNameToIndex.isEmpty()) { LexerNode* pNodes = new LexerNode[100]; int i = 0; //pNodes[i].pAct = ui.actionAVS; //pNodes[i].index = L_AVS; QVariant data((int)L_AVS); //ui.actionAVS->setData(data); //m_lexerNameToIndex.insert("avs", pNodes[i]); // ++i; pNodes[i].pAct = ui.actionAssembly; pNodes[i].index = L_ASM; data.setValue(int(L_ASM)); ui.actionAssembly->setData(data); m_lexerNameToIndex.insert("asm", pNodes[i]); ++i; pNodes[i].pAct = ui.actionbash; pNodes[i].index = L_BASH; data.setValue(int(L_BASH)); ui.actionbash->setData(data); m_lexerNameToIndex.insert("bash", pNodes[i]); ++i; pNodes[i].pAct = ui.actionBatch; pNodes[i].index = L_BATCH; data.setValue(int(L_BATCH)); ui.actionBatch->setData(data); m_lexerNameToIndex.insert("batch", pNodes[i]); ++i; pNodes[i].pAct = ui.actionCMake; pNodes[i].index = L_CMAKE; data.setValue(int(L_CMAKE)); ui.actionCMake->setData(data); m_lexerNameToIndex.insert("cmake", pNodes[i]); ++i; pNodes[i].pAct = ui.actionCoffeeScript; pNodes[i].index = L_COFFEESCRIPT; data.setValue(int(L_COFFEESCRIPT)); ui.actionCoffeeScript->setData(data); m_lexerNameToIndex.insert("coffeescript", pNodes[i]); ++i; pNodes[i].pAct = ui.actionCPP; pNodes[i].index = L_CPP; data.setValue(int(L_CPP)); ui.actionCPP->setData(data); m_lexerNameToIndex.insert("cpp", pNodes[i]); ++i; pNodes[i].pAct = ui.actionCShape; pNodes[i].index = L_CS; data.setValue(int(L_CS)); ui.actionCShape->setData(data); m_lexerNameToIndex.insert("csharp", pNodes[i]); ++i; pNodes[i].pAct = ui.actionCss; pNodes[i].index = L_CSS; data.setValue(int(L_CSS)); ui.actionCss->setData(data); m_lexerNameToIndex.insert("css", pNodes[i]); ++i; pNodes[i].pAct = ui.actionD_2; pNodes[i].index = L_D; data.setValue(int(L_D)); ui.actionD_2->setData(data); m_lexerNameToIndex.insert("d", pNodes[i]); ++i; pNodes[i].pAct = ui.actionDiff; pNodes[i].index = L_DIFF; data.setValue(int(L_DIFF)); ui.actionDiff->setData(data); m_lexerNameToIndex.insert("diff", pNodes[i]); ++i; pNodes[i].pAct = ui.actionEdifact; pNodes[i].index = L_EDIFACT; data.setValue(int(L_EDIFACT)); ui.actionEdifact->setData(data); m_lexerNameToIndex.insert("edifact", pNodes[i]); ++i; pNodes[i].pAct = ui.actionFortran; pNodes[i].index = L_FORTRAN; data.setValue(int(L_FORTRAN)); ui.actionFortran->setData(data); m_lexerNameToIndex.insert("fortran", pNodes[i]); ++i; pNodes[i].pAct = ui.actionFortran77; pNodes[i].index = L_FORTRAN_77; data.setValue(int(L_FORTRAN_77)); ui.actionFortran77->setData(data); m_lexerNameToIndex.insert("fortran77", pNodes[i]); ++i; pNodes[i].pAct = ui.actionHTML; pNodes[i].index = L_HTML; data.setValue(int(L_HTML)); ui.actionHTML->setData(data); m_lexerNameToIndex.insert("html", pNodes[i]); ++i; pNodes[i].pAct = ui.actionIDL; pNodes[i].index = L_IDL; data.setValue(int(L_IDL)); ui.actionIDL->setData(data); m_lexerNameToIndex.insert("idl", pNodes[i]); ++i; pNodes[i].pAct = ui.actionJava; pNodes[i].index = L_JAVA; data.setValue(int(L_JAVA)); ui.actionJava->setData(data); m_lexerNameToIndex.insert("java", pNodes[i]); ++i; pNodes[i].pAct = ui.actionJavaScript; pNodes[i].index = L_JAVASCRIPT; data.setValue(int(L_JAVASCRIPT)); ui.actionJavaScript->setData(data); m_lexerNameToIndex.insert("javascript", pNodes[i]); ++i; pNodes[i].pAct = ui.actionjson; pNodes[i].index = L_JSON; data.setValue(int(L_JSON)); ui.actionjson->setData(data); m_lexerNameToIndex.insert("json", pNodes[i]); ++i; pNodes[i].pAct = ui.actionLua; pNodes[i].index = L_LUA; data.setValue(int(L_LUA)); ui.actionLua->setData(data); m_lexerNameToIndex.insert("lua", pNodes[i]); ++i; pNodes[i].pAct = ui.actionMakefile; pNodes[i].index = L_MAKEFILE; data.setValue(int(L_MAKEFILE)); ui.actionMakefile->setData(data); m_lexerNameToIndex.insert("makefile", pNodes[i]); ++i; pNodes[i].pAct = ui.actionMarkDown_2; pNodes[i].index = L_MARKDOWN; data.setValue(int(L_MARKDOWN)); ui.actionMarkDown_2->setData(data); m_lexerNameToIndex.insert("markdown", pNodes[i]); ++i; pNodes[i].pAct = ui.actionMatlab; pNodes[i].index = L_MATLAB; data.setValue(int(L_MATLAB)); ui.actionMatlab->setData(data); m_lexerNameToIndex.insert("matlab", pNodes[i]); ++i; pNodes[i].pAct = ui.actionNSIS; pNodes[i].index = L_NSIS; data.setValue(int(L_NSIS)); ui.actionNSIS->setData(data); m_lexerNameToIndex.insert("nsis", pNodes[i]); ++i; pNodes[i].pAct = ui.actionOctave; pNodes[i].index = L_OCTAVE; data.setValue(int(L_OCTAVE)); ui.actionOctave->setData(data); m_lexerNameToIndex.insert("octave", pNodes[i]); ++i; pNodes[i].pAct = ui.actionPascal; pNodes[i].index = L_PASCAL; data.setValue(int(L_PASCAL)); ui.actionPascal->setData(data); m_lexerNameToIndex.insert("pascal", pNodes[i]); ++i; pNodes[i].pAct = ui.actionPerl; pNodes[i].index = L_PERL; data.setValue(int(L_PERL)); ui.actionPerl->setData(data); m_lexerNameToIndex.insert("perl", pNodes[i]); ++i; pNodes[i].pAct = ui.actionPo; pNodes[i].index = L_PO; data.setValue(int(L_PO)); ui.actionPo->setData(data); m_lexerNameToIndex.insert("po", pNodes[i]); ++i; pNodes[i].pAct = ui.actionPostScript; pNodes[i].index = L_PS; data.setValue(int(L_PS)); ui.actionPostScript->setData(data); m_lexerNameToIndex.insert("postscript", pNodes[i]); ++i; pNodes[i].pAct = ui.actionPov; pNodes[i].index = L_POV; data.setValue(int(L_POV)); ui.actionPov->setData(data); m_lexerNameToIndex.insert("pov", pNodes[i]); ++i; pNodes[i].pAct = ui.actionProperties_file; pNodes[i].index = L_INI; data.setValue(int(L_INI)); ui.actionProperties_file->setData(data); m_lexerNameToIndex.insert("props", pNodes[i]); ++i; pNodes[i].pAct = ui.actionPython; pNodes[i].index = L_PYTHON; data.setValue(int(L_PYTHON)); ui.actionPython->setData(data); m_lexerNameToIndex.insert("python", pNodes[i]); ++i; pNodes[i].pAct = ui.actionR_2; pNodes[i].index = L_R; data.setValue(int(L_R)); ui.actionR_2->setData(data); m_lexerNameToIndex.insert("r", pNodes[i]); ++i; pNodes[i].pAct = ui.actionRuby; pNodes[i].index = L_RUBY; data.setValue(int(L_RUBY)); ui.actionRuby->setData(data); m_lexerNameToIndex.insert("ruby", pNodes[i]); ++i; pNodes[i].pAct = ui.actionRust; pNodes[i].index = L_RUST; data.setValue(int(L_RUST)); ui.actionRust->setData(data); m_lexerNameToIndex.insert("rust", pNodes[i]); ++i; pNodes[i].pAct = ui.actionShell; pNodes[i].index = L_BASH; data.setValue(int(L_BASH)); ui.actionShell->setData(data); m_lexerNameToIndex.insert("shell", pNodes[i]); ++i; pNodes[i].pAct = ui.actionSpice; pNodes[i].index = L_SPICE; data.setValue(int(L_SPICE)); ui.actionSpice->setData(data); m_lexerNameToIndex.insert("spice", pNodes[i]); ++i; pNodes[i].pAct = ui.actionSql; pNodes[i].index = L_SQL; data.setValue(int(L_SQL)); ui.actionSql->setData(data); m_lexerNameToIndex.insert("sql", pNodes[i]); ++i; pNodes[i].pAct = ui.actionTcl; pNodes[i].index = L_TCL; data.setValue(int(L_TCL)); ui.actionTcl->setData(data); m_lexerNameToIndex.insert("tcl", pNodes[i]); ++i; pNodes[i].pAct = ui.actionTex; pNodes[i].index = L_TEX; data.setValue(int(L_TEX)); ui.actionTex->setData(data); m_lexerNameToIndex.insert("tex", pNodes[i]); ++i; pNodes[i].pAct = ui.actionVb; pNodes[i].index = L_VB; data.setValue(int(L_VB)); ui.actionVb->setData(data); m_lexerNameToIndex.insert("vb", pNodes[i]); ++i; pNodes[i].pAct = ui.actionVerilog; pNodes[i].index = L_VERILOG; data.setValue(int(L_VERILOG)); ui.actionVerilog->setData(data); m_lexerNameToIndex.insert("verilog", pNodes[i]); ++i; pNodes[i].pAct = ui.actionVHDL; pNodes[i].index = L_VHDL; data.setValue(int(L_VHDL)); ui.actionVHDL->setData(data); m_lexerNameToIndex.insert("vhdl", pNodes[i]); ++i; pNodes[i].pAct = ui.actionXML; pNodes[i].index = L_XML; data.setValue(int(L_XML)); ui.actionXML->setData(data); m_lexerNameToIndex.insert("xml", pNodes[i]); ++i; pNodes[i].pAct = ui.actionYAML; pNodes[i].index = L_YAML; data.setValue(int(L_YAML)); ui.actionYAML->setData(data); m_lexerNameToIndex.insert("yaml", pNodes[i]); ++i; //共用C++ pNodes[i].pAct = ui.actionC; pNodes[i].index = L_C; data.setValue(int(L_C)); ui.actionC->setData(data); m_lexerNameToIndex.insert("c", pNodes[i]); ++i; pNodes[i].pAct = ui.actionObjective_C; pNodes[i].index = L_OBJC; data.setValue(int(L_OBJC)); ui.actionObjective_C->setData(data); m_lexerNameToIndex.insert("objc", pNodes[i]); ++i; pNodes[i].pAct = ui.actionRC; pNodes[i].index = L_RC; data.setValue(int(L_RC)); ui.actionRC->setData(data); m_lexerNameToIndex.insert("rc", pNodes[i]); ++i; pNodes[i].pAct = ui.actionASP; pNodes[i].index = L_ASP; data.setValue(int(L_ASP)); ui.actionASP->setData(data); m_lexerNameToIndex.insert("asp", pNodes[i]); ++i; pNodes[i].pAct = ui.actionJsp; pNodes[i].index = L_JSP; data.setValue(int(L_JSP)); ui.actionJsp->setData(data); m_lexerNameToIndex.insert("jsp", pNodes[i]); ++i; pNodes[i].pAct = ui.actionPhp; pNodes[i].index = L_PHP; data.setValue(int(L_PHP)); ui.actionPhp->setData(data); m_lexerNameToIndex.insert("php", pNodes[i]); ++i; pNodes[i].pAct = ui.actionini; pNodes[i].index = L_INI; data.setValue(int(L_INI)); ui.actionini->setData(data); m_lexerNameToIndex.insert("ini", pNodes[i]); ++i; pNodes[i].pAct = ui.actionTypeScript; pNodes[i].index = L_TYPESCRIPT; data.setValue(int(L_TYPESCRIPT)); ui.actionTypeScript->setData(data); m_lexerNameToIndex.insert("typescript", pNodes[i]); ++i; pNodes[i].pAct = ui.actionGo; pNodes[i].index = L_GO; data.setValue(int(L_GO)); ui.actionGo->setData(data); m_lexerNameToIndex.insert("go", pNodes[i]); ++i; pNodes[i].pAct = ui.actionTxt; pNodes[i].index = L_TXT; data.setValue(int(L_TXT)); ui.actionTxt->setData(data); m_lexerNameToIndex.insert("txt", pNodes[i]); ++i; pNodes[i].pAct = ui.actionUserDefine; pNodes[i].index = L_USER_DEFINE; data.setValue(int(L_USER_DEFINE)); ui.actionUserDefine->setData(data); m_lexerNameToIndex.insert("UserDefine", pNodes[i]); ++i; delete[]pNodes; } } #ifdef Q_OS_WIN int CCNotePad::runAsAdmin(const QString& filePath) { //已经是管理员了,直接返回错误 if (s_isAdminAuth) { ui.statusBar->showMessage(tr("Run As Admin Failed to save the file. Please check the file permissions.")); return 1; } TCHAR nddFullPath[MAX_PATH]; ::GetModuleFileName(NULL, nddFullPath, MAX_PATH); ////先释放掉单一占位的内存 //if (m_shareMem->isAttached()) //{ // m_shareMem->detach(); //} QString argStr = QString("-muti %1").arg(filePath); std::basic_string<TCHAR> args = StringToWString(argStr.toStdString()); size_t shellExecRes = (size_t)::ShellExecute(NULL, TEXT("runas"), nddFullPath, args.c_str(), TEXT("."), SW_SHOW); // If the function succeeds, it returns a value greater than 32. If the function fails, // it returns an error value that indicates the cause of the failure. // https://msdn.microsoft.com/en-us/library/windows/desktop/bb762153%28v=vs.85%29.aspx if (shellExecRes < 32) { //失败后弹框。 QMessageBox::warning(nullptr, tr("Error"), tr("Can't Get Admin Auth, Open File %1 failed").arg(filePath)); return 1; } else { //成功后暂时不退出,因为amin存在的还有存在一些问题,比如后续文件不能右键菜单打开 //所以还需要维持当前这个界面存在 //成功获取权限后当前退出。这里其实还需要做一些释放操作 /*if (m_shareMem->isAttached()) { m_shareMem->detach(); } exit(0);*/ return 1; } } #endif //需要临时写一些文件,保存在该目录中。目前就是管理员提权时,保存之前的文件。 QString getGlboalTempSaveDir() { //就是app/notepad/temp的目录 QString tempFileList = QString("notepad/temp/list"); QSettings qs(QSettings::IniFormat, QSettings::UserScope, tempFileList); QString qsSavePath = qs.fileName(); QFileInfo fi(qsSavePath); return fi.dir().absolutePath(); } void setEditShowBlankStatus(ScintillaEditView* pEdit, int blankSet) { if (blankSet == 1) { pEdit->setWhitespaceVisibility(QsciScintilla::WsVisible); pEdit->setEolVisibility(false); } else if(blankSet == 2) { pEdit->setWhitespaceVisibility(QsciScintilla::WsInvisible); pEdit->setEolVisibility(true); } else if (blankSet == 3) { pEdit->setWhitespaceVisibility(QsciScintilla::WsVisible); pEdit->setEolVisibility(true); } else if (blankSet == 0) { pEdit->setWhitespaceVisibility(QsciScintilla::WsInvisible); pEdit->setEolVisibility(false); } } //根据文件类型给出语言id LexerInfo CCNotePad::getLangLexerIdByFileExt(QString filePath) { QFileInfo fi(filePath); QString ext = fi.suffix(); LexerInfo lexer(L_TXT,"txt"); if(ExtLexerManager::getInstance()->getLexerTypeByExt(ext, lexer)) { return lexer; } return lexer; } CCNotePad::CCNotePad(bool isMainWindows, QWidget *parent) : QMainWindow(parent), m_cutFile(nullptr),m_copyFile(nullptr), m_dockSelectTreeWin(nullptr), \ m_pResultWin(nullptr),m_isQuitCancel(false), m_tabRightClickMenu(nullptr), m_shareMem(nullptr),m_isMainWindows(isMainWindows),\ m_openInNewWinAct(nullptr), m_showFileDirAct(nullptr), m_showCmdAct(nullptr), m_timerAutoSave(nullptr), m_curColorIndex(-1), \ m_fileListView(nullptr), m_isInReloadFile(false), m_isToolMenuLoaded(false), m_isRecentFileLoaded(false) { ui.setupUi(this); #ifdef Q_OS_MAC setWindowIcon(QIcon(":/mac.icns")); #endif NddSetting::init(); m_translator = new QTranslator(this); m_curSoftLangs = NddSetting::getKeyValueFromNumSets(LANGS_KEY); switch (m_curSoftLangs) { case 0: //自动选择 { QLocale local; if (local.language() == QLocale::Chinese) { slot_changeChinese(); } break; } case 1: slot_changeChinese(); break; case 2: slot_changeEnglish(); break; default: break; } #if 0 if (s_padInstances == nullptr) { s_padInstances = new QList<CCNotePad*>(); s_padInstances->append(this); } //启用拖动 setAcceptDrops(true); initFileTypeLangMap(); initLexerNameToIndex(); //这里在主线程里面调用一下,避免后续因为没有创建,而可能在子线程中初始化里面的值,而且多个子线程引发重入竞争问题 //20220402在1.11中发现这个问题。所以加上这里的手动调用 DocTypeListView::initSupportFileTypes(); ui.editTabWidget->setTabsClosable(true); QTabBar* pBar = ui.editTabWidget->tabBar(); connect(pBar,&QTabBar::tabCloseRequested,this,&CCNotePad::slot_tabClose); m_codeStatusLabel = new QLabel("UTF8", ui.statusBar); #ifdef Q_OS_WIN m_lineEndLabel = new QLabel("Windows(CR LF)", ui.statusBar); #endif #ifdef Q_OS_UNIX m_lineEndLabel = new QLabel("Windows(LF)", ui.statusBar); #endif m_lineNumLabel = new QLabel(tr("Ln:0 Col:0"), ui.statusBar); m_langDescLabel = new QLabel("Txt", ui.statusBar); m_codeStatusLabel->setMinimumWidth(120); m_lineEndLabel->setMinimumWidth(100); m_lineNumLabel->setMinimumWidth(120); m_langDescLabel->setMinimumWidth(100); //0在前面,越小越在左边 ui.statusBar->insertPermanentWidget(0, m_langDescLabel); ui.statusBar->insertPermanentWidget(1, m_lineNumLabel); ui.statusBar->insertPermanentWidget(2, m_lineEndLabel); ui.statusBar->insertPermanentWidget(3, m_codeStatusLabel); initToolBar(); m_saveFile->setEnabled(false); m_saveAllFile->setEnabled(false); initReceneOpenFileMenu(); //最后加入退出菜单 ui.menuFile->addSeparator(); m_quitAction = ui.menuFile->addAction(tr("Quit"), this, &CCNotePad::slot_quit); m_quitAction->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_Q)); connect(ui.editTabWidget,&QTabWidget::currentChanged,this,&CCNotePad::slot_tabCurrentChanged); connect(ui.editTabWidget, &QTabWidget::tabBarClicked, this, &CCNotePad::slot_tabBarClicked); ui.editTabWidget->installEventFilter(this); m_fileWatch = new QFileSystemWatcher(this); connect(m_fileWatch,&QFileSystemWatcher::fileChanged,this, &CCNotePad::slot_fileChange); //只有主窗口才监控openwith的文件 if (isMainWindows) { initNotePadSqlOptions(); } slot_loadBookMarkMenu(); QByteArray lastGeo = NddSetting::getKeyByteArrayValue(WIN_POS); if (!lastGeo.isEmpty()) { restoreGeometry(lastGeo); } #endif } CCNotePad::~CCNotePad() { //只有主窗口,才有保存最近打开列表的权力 if (m_isMainWindows) { saveReceneOpenFile(); saveNotePadSqlOptions(); savePadUseTimes(); } NddSetting::close(); } //先快速让窗口展示处理,后续再去做复杂的初始化 void CCNotePad::quickshow() { QByteArray lastGeo = NddSetting::getKeyByteArrayValue(WIN_POS); if (!lastGeo.isEmpty()) { restoreGeometry(lastGeo); } show(); QCoreApplication::processEvents(); if (s_padInstances == nullptr) { s_padInstances = new QList<CCNotePad*>(); s_padInstances->append(this); } //启用拖动 setAcceptDrops(true); initFileTypeLangMap(); initLexerNameToIndex(); //这里在主线程里面调用一下,避免后续因为没有创建,而可能在子线程中初始化里面的值,而且多个子线程引发重入竞争问题 //20220402在1.11中发现这个问题。所以加上这里的手动调用 DocTypeListView::initSupportFileTypes(); ui.editTabWidget->setTabsClosable(true); QTabBar* pBar = ui.editTabWidget->tabBar(); connect(pBar, &QTabBar::tabCloseRequested, this, &CCNotePad::slot_tabClose); m_codeStatusLabel = new QLabel("UTF8", ui.statusBar); m_lineEndLabel = new QComboBox(ui.statusBar); m_lineEndLabel->addItems(QStringList() << "Windows(CR LF)" << "Unix(LF)" << "Mac(CR)"); #ifdef Q_OS_WIN m_lineEndLabel->setCurrentIndex(0); #else m_lineEndLabel->setCurrentIndex(1); #endif connect(m_lineEndLabel, QOverload<int>::of(&QComboBox::currentIndexChanged), this, &CCNotePad::on_lineEndChange); m_lineNumLabel = new QLabel(tr("Ln:0 Col:0"), ui.statusBar); m_langDescLabel = new QLabel("Txt", ui.statusBar); m_zoomLabel = new QLabel("Zoom", ui.statusBar); m_codeStatusLabel->setMinimumWidth(120); m_lineEndLabel->setMinimumWidth(100); m_lineNumLabel->setMinimumWidth(120); m_langDescLabel->setMinimumWidth(100); m_zoomLabel->setMinimumWidth(100); //0在前面,越小越在左边 ui.statusBar->insertPermanentWidget(0, m_zoomLabel); ui.statusBar->insertPermanentWidget(1, m_langDescLabel); ui.statusBar->insertPermanentWidget(2, m_lineNumLabel); ui.statusBar->insertPermanentWidget(3, m_lineEndLabel); ui.statusBar->insertPermanentWidget(4, m_codeStatusLabel); initToolBar(); m_saveFile->setEnabled(false); m_saveAllFile->setEnabled(false); //initReceneOpenFileMenu(); //延迟加载最近菜单列表 connect(ui.menuRecene_File, &QMenu::aboutToShow, this, &CCNotePad::on_loadReceneFile); //最后加入退出菜单 ui.menuFile->addSeparator(); #if 0 m_quitAction = ui.menuFile->addAction(tr("Quit"), this, &CCNotePad::slot_quit); m_quitAction->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_Q)); #endif connect(ui.editTabWidget, &QTabWidget::currentChanged, this, &CCNotePad::slot_tabCurrentChanged, Qt::UniqueConnection); connect(ui.editTabWidget, &QTabWidget::tabBarClicked, this, &CCNotePad::slot_tabBarClicked, Qt::QueuedConnection); //双击在新窗口中打开 connect(ui.editTabWidget, &QTabWidget::tabBarDoubleClicked, this, &CCNotePad::on_tabBarDoubleClicked, Qt::QueuedConnection); ui.editTabWidget->installEventFilter(this); m_fileWatch = new QFileSystemWatcher(this); connect(m_fileWatch, &QFileSystemWatcher::fileChanged, this, &CCNotePad::slot_fileChange); //只有主窗口才监控openwith的文件 if (m_isMainWindows) { initNotePadSqlOptions(); } m_isInitBookMarkAct = false; slot_loadBookMarkMenu(); slot_loadMarkColor(); m_isToolMenuLoaded = false; init_toolsMenu(); this->setContextMenuPolicy(Qt::NoContextMenu); //恢复文件列表 if (1 == NddSetting::getKeyValueFromNumSets(FILELISTSHOW)) { initFileListDockWin(); } //隐藏工具栏 if (0 == NddSetting::getKeyValueFromNumSets(TOOLBARSHOW)) { ui.mainToolBar->setVisible(false); ui.actionShow_ToolBar->setChecked(false); } //高亮web地址。默认为0不高亮 if (1 == NddSetting::getKeyValueFromNumSets(SHOWWEBADDR)) { s_hightWebAddr = 1; ui.actionShow_Web_Addr->setChecked(true); } //恢复用户自定义快捷键 setUserDefShortcutKey(); } void CCNotePad::on_lineEndChange(int index) { if (index == 0) { if (convertDocLineEnd(DOS_LINE)) { ui.actionconver_windows_CR_LF->setChecked(true); } } else if (index == 1) { if (convertDocLineEnd(UNIX_LINE)) { ui.actionconvert_Unix_LF->setChecked(true); } } else if (index == 2) { if (convertDocLineEnd(MAC_LINE)) { ui.actionconvert_Mac_CR->setChecked(true); } } } void CCNotePad::setUserDefShortcutKey(int shortcutId) { QKeySequence keySeq; switch (shortcutId) { case New_File_ID: keySeq = ShortcutKeyMgr::getUserDefShortcutKey(New_File); ui.actionNewFile->setShortcut(keySeq); break; case Open_File_ID: keySeq = ShortcutKeyMgr::getUserDefShortcutKey(Open_File); ui.actionOpenFile->setShortcut(keySeq); break; case Save_File_ID: break; case Save_All_File_ID: keySeq = ShortcutKeyMgr::getUserDefShortcutKey(Save_All_File); ui.actionSave_as->setShortcut(keySeq); break; case Close_ID: keySeq = ShortcutKeyMgr::getUserDefShortcutKey(Close); ui.actionClose->setShortcut(keySeq); break; case Close_All_ID: keySeq = ShortcutKeyMgr::getUserDefShortcutKey(Close_All); ui.actionClose_All->setShortcut(keySeq); break; case Cut_ID: break; case Copy_ID: break; case Paste_ID: break; case Undo_ID: break; case Redo_ID: break; case Find_ID: keySeq = ShortcutKeyMgr::getUserDefShortcutKey(Find); ui.actionFind->setShortcut(keySeq); break; case Replace_ID: keySeq = ShortcutKeyMgr::getUserDefShortcutKey(Replace); ui.actionReplace->setShortcut(keySeq); break; case Dir_Find_ID: keySeq = ShortcutKeyMgr::getUserDefShortcutKey(DirFind); ui.actionFind_In_Dir->setShortcut(keySeq); break; case Mark_ID: break; case Word_highlight_ID: keySeq = ShortcutKeyMgr::getUserDefShortcutKey(Word_highlight); m_signText->setShortcut(keySeq); break; case Clear_all_highlight_ID: keySeq = ShortcutKeyMgr::getUserDefShortcutKey(Clear_all_highlight); m_clearMark->setShortcut(keySeq); break; case Zoom_In_ID: keySeq = ShortcutKeyMgr::getUserDefShortcutKey(Zoom_In); m_zoomin->setShortcut(keySeq); break; case Zoom_Out_ID: keySeq = ShortcutKeyMgr::getUserDefShortcutKey(Zoom_Out); m_zoomout->setShortcut(keySeq); break; case Word_Wrap_ID: keySeq = ShortcutKeyMgr::getUserDefShortcutKey(Word_Wrap); ui.actionWrap->setShortcut(keySeq); break; case Show_Blank_ID: keySeq = ShortcutKeyMgr::getUserDefShortcutKey(Show_Blank); ui.actionShowAll->setShortcut(keySeq); break; case Indent_Guide_ID: keySeq = ShortcutKeyMgr::getUserDefShortcutKey(Indent_Guide); m_indentGuide->setShortcut(keySeq); break; case Pre_Page_ID: keySeq = ShortcutKeyMgr::getUserDefShortcutKey(Pre_Page); m_preHexPage->setShortcut(keySeq); break; case Next_Page_ID: keySeq = ShortcutKeyMgr::getUserDefShortcutKey(Next_Page); m_nextHexPage->setShortcut(keySeq); break; case Goto_Page_ID: keySeq = ShortcutKeyMgr::getUserDefShortcutKey(Goto_Page); ui.actionGoline->setShortcut(keySeq); break; case Trans_code_ID: keySeq = ShortcutKeyMgr::getUserDefShortcutKey(Trans_code); m_transcode->setShortcut(keySeq); break; case Batch_rename_ID: keySeq = ShortcutKeyMgr::getUserDefShortcutKey(Batch_rename); m_rename->setShortcut(keySeq); break; case Format_Xml_ID: keySeq = ShortcutKeyMgr::getUserDefShortcutKey(Format_Xml); m_formatXml->setShortcut(keySeq); break; case Format_Json_ID: keySeq = ShortcutKeyMgr::getUserDefShortcutKey(Format_Json); m_formatJson->setShortcut(keySeq); break; case ADD_DEL_LINE_COM: keySeq = ShortcutKeyMgr::getUserDefShortcutKey(ADD_DELETE_LINE_COMMENT); registerCommentShortKey(ADD_DEL_LINE_COM, keySeq); break; case ADD_BK_COM: keySeq = ShortcutKeyMgr::getUserDefShortcutKey(ADD_BLOCK_COMMENT); registerCommentShortKey(ADD_BK_COM, keySeq); break; case DEL_BK_COM: keySeq = ShortcutKeyMgr::getUserDefShortcutKey(CANCEL_BLOCK_COMMENT); registerCommentShortKey(DEL_BK_COM, keySeq); break; case S_K_FOLD_1: keySeq = ShortcutKeyMgr::getUserDefShortcutKey(FOLD_1); registerFoldShortKey(S_K_FOLD_1, keySeq, false); break; case S_K_FOLD_2: keySeq = ShortcutKeyMgr::getUserDefShortcutKey(FOLD_2); registerFoldShortKey(S_K_FOLD_2, keySeq, false); break; case S_K_FOLD_3: keySeq = ShortcutKeyMgr::getUserDefShortcutKey(FOLD_3); registerFoldShortKey(S_K_FOLD_3, keySeq, false); break; case S_K_FOLD_4: keySeq = ShortcutKeyMgr::getUserDefShortcutKey(FOLD_4); registerFoldShortKey(S_K_FOLD_4, keySeq, false); break; case S_K_FOLD_5: keySeq = ShortcutKeyMgr::getUserDefShortcutKey(FOLD_5); registerFoldShortKey(S_K_FOLD_5, keySeq, false); break; case S_K_FOLD_6: keySeq = ShortcutKeyMgr::getUserDefShortcutKey(FOLD_6); registerFoldShortKey(S_K_FOLD_6, keySeq, false); break; case S_K_FOLD_7: keySeq = ShortcutKeyMgr::getUserDefShortcutKey(FOLD_7); registerFoldShortKey(S_K_FOLD_7, keySeq, false); break; case S_K_FOLD_8: keySeq = ShortcutKeyMgr::getUserDefShortcutKey(FOLD_8); registerFoldShortKey(S_K_FOLD_8, keySeq, false); break; case S_K_UNFOLD_1: keySeq = ShortcutKeyMgr::getUserDefShortcutKey(UNFOLD_1); registerFoldShortKey(S_K_UNFOLD_1, keySeq, true); break; case S_K_UNFOLD_2: keySeq = ShortcutKeyMgr::getUserDefShortcutKey(UNFOLD_2); registerFoldShortKey(S_K_UNFOLD_2, keySeq, true); break; case S_K_UNFOLD_3: keySeq = ShortcutKeyMgr::getUserDefShortcutKey(UNFOLD_3); registerFoldShortKey(S_K_UNFOLD_3, keySeq, true); break; case S_K_UNFOLD_4: keySeq = ShortcutKeyMgr::getUserDefShortcutKey(UNFOLD_4); registerFoldShortKey(S_K_UNFOLD_4, keySeq, true); break; case S_K_UNFOLD_5: keySeq = ShortcutKeyMgr::getUserDefShortcutKey(UNFOLD_5); registerFoldShortKey(S_K_UNFOLD_5, keySeq, true); break; case S_K_UNFOLD_6: keySeq = ShortcutKeyMgr::getUserDefShortcutKey(UNFOLD_6); registerFoldShortKey(S_K_UNFOLD_6, keySeq, true); break; case S_K_UNFOLD_7: keySeq = ShortcutKeyMgr::getUserDefShortcutKey(UNFOLD_7); registerFoldShortKey(S_K_UNFOLD_7, keySeq, true); break; case S_K_UNFOLD_8: keySeq = ShortcutKeyMgr::getUserDefShortcutKey(UNFOLD_8); registerFoldShortKey(S_K_UNFOLD_8, keySeq, true); break; default: break; } } void CCNotePad::registerFoldShortKey(int type, QKeySequence& keySeq, bool isFold) { QShortcut* pStc = new QShortcut(this); pStc->setKey(keySeq); pStc->setContext(Qt::WidgetWithChildrenShortcut); connect(pStc, &QShortcut::activated, this, [=]() { doFold(type, isFold); }); } //注册注释快捷键 void CCNotePad::registerCommentShortKey(int type, QKeySequence& keySeq) { QShortcut* pStc = new QShortcut(this); pStc->setKey(keySeq); pStc->setContext(Qt::WidgetWithChildrenShortcut); connect(pStc, &QShortcut::activated, this, [=]() { doComment(type); }); } //注释问题。 void CCNotePad::doComment(int type) { QWidget* pw = ui.editTabWidget->currentWidget(); ScintillaEditView* pEdit = dynamic_cast<ScintillaEditView*>(pw); if (pEdit != nullptr && !pEdit->isReadOnly()) { pEdit->comment(type); } } void CCNotePad::doFold(int type, bool mode) { QWidget* pw = ui.editTabWidget->currentWidget(); ScintillaEditView* pEdit = dynamic_cast<ScintillaEditView*>(pw); if (pEdit != nullptr) { pEdit->collapse((mode?(type - S_K_UNFOLD_1): (type - S_K_FOLD_1)), mode); } } //设置用户自定义快捷键 void CCNotePad::setUserDefShortcutKey() { ShortcutKeyMgr::initShortcutKeysMap(); for (int i = New_File_ID; i < Shortcut_End_ID; ++i) { setUserDefShortcutKey(i); } } void CCNotePad::init_toolsMenu() { slot_dynamicLoadToolMenu(); //connect(ui.menuTools,&QMenu::aboutToShow,this,&CCNotePad::slot_dynamicLoadToolMenu); } enum ToolMenuAct { BATCH_FIND = 1, }; //动态加载工具菜单项 void CCNotePad::slot_dynamicLoadToolMenu() { if (!m_isToolMenuLoaded) { m_isToolMenuLoaded = true; connect(ui.actionPlugin_Manager, &QAction::triggered, this, &CCNotePad::slot_pluginMgr, Qt::UniqueConnection); QMenu* formatMenu = new QMenu(tr("Format Language"), this); m_formatXml = formatMenu->addAction(tr("Format Xml"), this, &CCNotePad::slot_formatXml); m_formatJson = formatMenu->addAction(tr("Format Json"), this, &CCNotePad::slot_formatJson); ui.menuTools->addMenu(formatMenu); QAction* pAct = nullptr; pAct = ui.menuTools->addAction(tr("Batch Find"), this, &CCNotePad::slot_batchFind); pAct->setData(BATCH_FIND); #ifdef NO_PLUGIN //动态加载插件 m_pluginList.clear(); loadPluginLib(); #endif } } void CCNotePad::slot_pluginMgr() { #ifdef NO_PLUGIN PluginMgr* pWin = new PluginMgr(this, m_pluginList); pWin->setAttribute(Qt::WA_DeleteOnClose); pWin->show(); #else QMessageBox::warning(this, "info", u8"便携版本不支持插件,请下载插件版!"); #endif } #ifdef NO_PLUGIN void CCNotePad::loadPluginLib() { QString strDir = qApp->applicationDirPath(); QDir dir(strDir); if (dir.cd("./plugin")) { strDir = dir.absolutePath(); loadPluginProcs(strDir,ui.menuPlugin); } } void CCNotePad::onPlugFound(NDD_PROC_DATA& procData, QMenu* pUserData) { QMenu* pMenu = pUserData; if (pMenu == NULL) { return; } //创建action if (procData.m_menuType == 0) { QAction* pAction = new QAction(procData.m_strPlugName, pMenu); pMenu->addAction(pAction); pAction->setText(procData.m_strPlugName); pAction->setData(procData.m_strFilePath); connect(pAction, &QAction::triggered, this, &CCNotePad::onPlugWork); } else if (procData.m_menuType == 1) { //创建二级菜单 QMenu* pluginMenu = new QMenu(procData.m_strPlugName, pMenu); pMenu->addMenu(pluginMenu); //菜单句柄通过procData传递到插件中 procData.m_rootMenu = pluginMenu; sendParaToPlugin(procData); } else { return; } m_pluginList.append(procData); } //真正执行插件的工作 void CCNotePad::onPlugWork(bool check) { QAction* pAct = dynamic_cast<QAction*>(sender()); if (pAct != nullptr) { QString plugPath = pAct->data().toString(); QLibrary* pLib = new QLibrary(plugPath); NDD_PROC_MAIN_CALLBACK pMainCallBack; pMainCallBack = (NDD_PROC_MAIN_CALLBACK)pLib->resolve("NDD_PROC_MAIN"); if (pMainCallBack != NULL) { std::function<QsciScintilla* ()> foundCallBack = std::bind(&CCNotePad::getCurEditView, this); std::function<bool(int, void*)> pluginCallBack = std::bind(&CCNotePad::pluginInvoke, this, std::placeholders::_1, std::placeholders::_2); pMainCallBack(this, plugPath, foundCallBack, pluginCallBack, nullptr); } else { ui.statusBar->showMessage(tr("plugin %1 load failed !").arg(plugPath), 10000); } } } //把插件需要的参数,传递到插件中去 void CCNotePad::sendParaToPlugin(NDD_PROC_DATA& procData) { QString plugPath = procData.m_strFilePath; QLibrary* pLib = new QLibrary(plugPath); NDD_PROC_MAIN_CALLBACK pMainCallBack; pMainCallBack = (NDD_PROC_MAIN_CALLBACK)pLib->resolve("NDD_PROC_MAIN"); if (pMainCallBack != NULL) { std::function<QsciScintilla* ()> foundCallBack = std::bind(&CCNotePad::getCurEditView, this); std::function<bool(int, void*)> pluginCallBack = std::bind(&CCNotePad::pluginInvoke, this, std::placeholders::_1, std::placeholders::_2); pMainCallBack(this, plugPath, foundCallBack, pluginCallBack, &procData); } else { ui.statusBar->showMessage(tr("plugin %1 load failed !").arg(plugPath), 10000); } } void CCNotePad::loadPluginProcs(QString strLibDir, QMenu* pMenu) { std::function<void(NDD_PROC_DATA&, QMenu*)> foundCallBack = std::bind(&CCNotePad::onPlugFound, this, std::placeholders::_1, std::placeholders::_2); int nRet = loadProc(strLibDir, foundCallBack, pMenu); if (nRet > 0) { ui.statusBar->showMessage(tr("load plugin in dir %1 success, plugin num %2").arg(strLibDir).arg(nRet)); } } #endif //批量查找替换 void CCNotePad::slot_batchFind() { #ifdef uos bool isPosAdjust = false; #endif if (m_batchFindWin.isNull()) { m_batchFindWin = new BatchFindReplace(this); m_batchFindWin->setAttribute(Qt::WA_DeleteOnClose); BatchFindReplace* pWin = dynamic_cast<BatchFindReplace*>(m_batchFindWin.data()); pWin->setTabWidget(ui.editTabWidget); QByteArray lastGeo = NddSetting::getWinPos(BATCH_FIND_REPLACE_POS); if (!lastGeo.isEmpty()) { m_batchFindWin->restoreGeometry(lastGeo); #ifdef uos isPosAdjust = true; #endif } } m_batchFindWin->show(); #ifdef uos if (!isPosAdjust) { adjustWInPos(m_batchFindWin); } #endif } #ifdef Q_OS_WIN void CCNotePad::checkAppFont() { //检查win下面的字体,win11有时默认字体是楷体 QFont srcFont = QApplication::font(); //win11发现字体是楷体。检测并设置一下 if (QString("SimSun") != srcFont.family()) { QFont font(QString("Courier"), 9); QApplication::setFont(font); ui.statusBar->showMessage(tr("If display exceptions,Please Install System Font Courier")); } } #endif enum BookMarkActId { SET_REMOVE=1, NEXT_MARK, PREV_MARK, CLEAR_MARK, CUT_MARK_LINE, COPY_MARK_LINE, PASTE_MARK_LINE, DELETE_MARK_LINE, DELETE_UNMARK, CLIP_MARK, }; void CCNotePad::slot_bookMarkAction() { QAction* pAct = dynamic_cast<QAction*>(sender()); if (pAct != nullptr) { QWidget* pw = ui.editTabWidget->currentWidget(); ScintillaEditView* pEdit = dynamic_cast<ScintillaEditView*>(pw); if (pEdit == nullptr) { return; } BookMarkActId id = (BookMarkActId)pAct->data().toInt(); switch (id) { case SET_REMOVE: pEdit->bookmarkToggle(-1); break; case NEXT_MARK: pEdit->bookmarkNext(true); break; case PREV_MARK: pEdit->bookmarkNext(false); break; case CLEAR_MARK: pEdit->bookmarkClearAll(); break; case CUT_MARK_LINE: pEdit->cutMarkedLines(); break; case COPY_MARK_LINE: pEdit->copyMarkedLines(); break; case PASTE_MARK_LINE: pEdit->pasteToMarkedLines(); break; case DELETE_MARK_LINE: pEdit->deleteMarkedLines(true); break; case DELETE_UNMARK: pEdit->deleteMarkedLines(false); break; case CLIP_MARK: pEdit->inverseMarks(); break; default: break; } } } //动态加载书签的菜单项 void CCNotePad::slot_loadBookMarkMenu() { if (!m_isInitBookMarkAct) { m_isInitBookMarkAct = true; QAction* pAct = nullptr; pAct = ui.menuBook_Mark->addAction(tr("Set/Remove BookMark"), this, &CCNotePad::slot_bookMarkAction, QKeySequence("Ctrl+F2")); pAct->setData(SET_REMOVE); pAct = ui.menuBook_Mark->addAction(tr("Next BookMark"), this, &CCNotePad::slot_bookMarkAction, QKeySequence("F2")); pAct->setData(NEXT_MARK); pAct = ui.menuBook_Mark->addAction(tr("Prev BookMark"), this, &CCNotePad::slot_bookMarkAction, QKeySequence("Shift+F2")); pAct->setData(PREV_MARK); pAct = ui.menuBook_Mark->addAction(tr("ClearAll BookMark"), this, &CCNotePad::slot_bookMarkAction); pAct->setData(CLEAR_MARK); pAct = ui.menuBook_Mark->addAction(tr("Cut BookMark Lines"), this, &CCNotePad::slot_bookMarkAction); pAct->setData(CUT_MARK_LINE); pAct = ui.menuBook_Mark->addAction(tr("Copy BookMark Lines"), this, &CCNotePad::slot_bookMarkAction); pAct->setData(COPY_MARK_LINE); pAct = ui.menuBook_Mark->addAction(tr("Paste BookMark Lines"), this, &CCNotePad::slot_bookMarkAction); pAct->setData(PASTE_MARK_LINE); pAct = ui.menuBook_Mark->addAction(tr("Delete BookMark Lines"), this, &CCNotePad::slot_bookMarkAction); pAct->setData(DELETE_MARK_LINE); pAct = ui.menuBook_Mark->addAction(tr("Delete UnBookMark Lines"), this, &CCNotePad::slot_bookMarkAction); pAct->setData(DELETE_UNMARK); pAct = ui.menuBook_Mark->addAction(tr("Clip BookMark"), this, &CCNotePad::slot_bookMarkAction); pAct->setData(CLIP_MARK); } } void CCNotePad::slot_markColorGroup(QAction *action) { CCNotePad::s_curMarkColorId = action->data().toInt(); slot_wordHighlight(); } #define SCE_UNIVERSAL_FOUND_STYLE_START 20 //修改标记样式的颜色 void CCNotePad::changeMarkColor(int sytleId) { if (sytleId < 5) { QPixmap colorBar(36, 36); colorBar.fill((&StyleSet::s_global_style->mark_style_1)[sytleId].bgColor); m_styleMarkActList.at(sytleId)->setIcon(colorBar); } } void CCNotePad::slot_loadMarkColor() { if (m_curColorIndex == -1) { m_curColorIndex = 0; QPixmap colorBar(36, 36); QActionGroup* markColorGroup = new QActionGroup(this); connect(markColorGroup, &QActionGroup::triggered, this, &CCNotePad::slot_markColorGroup, Qt::QueuedConnection); int index = 1; auto initColorBar = [this, markColorGroup,&index](QPixmap& colorBar)->QAction* { QAction* action = new QAction(ui.menuMark_Color); action->setIcon(colorBar); action->setText(tr("Color %1").arg(index)); action->setData(index+ SCE_UNIVERSAL_FOUND_STYLE_START); ++index; ui.menuMark_Color->addAction(action); markColorGroup->addAction(action); return action; }; m_styleMarkActList.clear(); colorBar.fill(StyleSet::s_global_style->mark_style_1.bgColor); m_styleMarkActList.append(initColorBar(colorBar)); colorBar.fill(StyleSet::s_global_style->mark_style_2.bgColor); m_styleMarkActList.append(initColorBar(colorBar)); colorBar.fill(StyleSet::s_global_style->mark_style_3.bgColor); m_styleMarkActList.append(initColorBar(colorBar)); colorBar.fill(StyleSet::s_global_style->mark_style_4.bgColor); m_styleMarkActList.append(initColorBar(colorBar)); colorBar.fill(StyleSet::s_global_style->mark_style_5.bgColor); m_styleMarkActList.append(initColorBar(colorBar)); } } void CCNotePad::syncCurSkinToMenu(int id) { s_curStyleId = id; } void CCNotePad::slot_changeChinese() { if (m_translator->load(":/realcompare_zh.qm")) { qApp->installTranslator(m_translator); ui.retranslateUi(this); if (m_curSoftLangs != 1) { m_curSoftLangs = 1; NddSetting::updataKeyValueFromNumSets(LANGS_KEY, m_curSoftLangs); } //如果已经加载了,则冲加载,否则中英文切换不生效 if (m_isToolMenuLoaded) { #ifdef NO_PLUGIN ui.menuPlugin->clear(); ui.menuPlugin->addAction(ui.actionPlugin_Manager); #endif ui.menuTools->clear(); m_isToolMenuLoaded = false; slot_dynamicLoadToolMenu(); } } } #ifdef uos void CCNotePad::adjustWInPos(QWidget* pWin) { QPoint globalPos = this->mapToGlobal(QPoint(0,0));//父窗口绝对坐标 int x = globalPos.x() + 300;//x坐标 int y = globalPos.y() + 100;//y坐标 pWin->move(x, y); } #endif void CCNotePad::slot_changeEnglish() { m_translator->load(""); qApp->installTranslator(m_translator); ui.retranslateUi(this); if (m_curSoftLangs != 2) { m_curSoftLangs = 2; NddSetting::updataKeyValueFromNumSets(LANGS_KEY, m_curSoftLangs); } //如果已经加载了,则冲加载,否则中英文切换不生效 if (m_isToolMenuLoaded) { #ifdef NO_PLUGIN ui.menuPlugin->clear(); ui.menuPlugin->addAction(ui.actionPlugin_Manager); #endif ui.menuTools->clear(); m_isToolMenuLoaded = false; slot_dynamicLoadToolMenu(); } } #if 0 void CCNotePad::saveDefFont() { if (s_txtFont.toString() != m_txtFontStr) { QString newFont = s_txtFont.toString(); NddSetting::updataKeyValueFromSets(TXT_FONT, newFont); } if (s_proLangFont.toString() != m_proLangFontStr) { QString newFont = s_proLangFont.toString(); NddSetting::updataKeyValueFromSets(PRO_LANG_FONT, newFont); } } #endif void CCNotePad::savePadUseTimes() { QString key("padtimes"); int times = NddSetting::getKeyValueFromNumSets(key); NddSetting::updataKeyValueFromNumSets(key, s_padTimes + times); } void CCNotePad::slot_searchResultShow() { initFindResultDockWin(); m_dockSelectTreeWin->show(); } //读取Sql的全局配置 void CCNotePad::initNotePadSqlOptions() { //tab的长度,默认为4 QString key("tablens"); ScintillaEditView::s_tabLens = NddSetting::getKeyValueFromNumSets(key); //space replace tab空格替换tab,默认1 QString key1("tabnouse"); ScintillaEditView::s_noUseTab = (1 == NddSetting::getKeyValueFromNumSets(key1)) ? true : false; ScintillaEditView::s_bigTextSize = NddSetting::getKeyValueFromNumSets(MAX_BIG_TEXT); if (ScintillaEditView::s_bigTextSize < 50 || ScintillaEditView::s_bigTextSize > 600) { ScintillaEditView::s_bigTextSize = 100; } s_restoreLastFile = NddSetting::getKeyValueFromNumSets(RESTORE_CLOSE_FILE); } //保存Sql的全局配置 void CCNotePad::saveNotePadSqlOptions() { QString key("tablens"); NddSetting::updataKeyValueFromNumSets(key, ScintillaEditView::s_tabLens); QString key1("tabnouse"); NddSetting::updataKeyValueFromNumSets(key1, ScintillaEditView::s_noUseTab?1:0); NddSetting::updataKeyValueFromNumSets(MAX_BIG_TEXT, ScintillaEditView::s_bigTextSize); NddSetting::updataKeyValueFromNumSets(RESTORE_CLOSE_FILE, CCNotePad::s_restoreLastFile); } //设置程序为文件右键的关联项目 void CCNotePad::setToFileRightMenu() { #if 0 #ifdef _WIN32 #ifdef _DEBUG return; #endif QString exepath = QCoreApplication::applicationFilePath(); exepath = exepath.replace("/", "\\"); QString iconTxt = exepath; exepath += " \"%1\""; QString menuDisplayName(tr("Edit with Notepad--")); QString keyPath = "HKEY_CLASSES_ROOT\\*\\shell\\" + menuDisplayName + "\\command"; QString iconPath = "HKEY_CLASSES_ROOT\\*\\shell\\" + menuDisplayName; QSettings settings(keyPath, QSettings::NativeFormat); QSettings iconSettings(iconPath, QSettings::NativeFormat); if (settings.value(".").toString() != exepath) { settings.setValue(".", exepath); iconSettings.setValue("Icon", iconTxt); //在读一次 if (settings.value(".").toString() != exepath) { //QMessageBox::warning(nullptr, tr("Notice"), tr("Please run in admin auth")); ui.statusBar->showMessage(tr("Please run in admin auth")); } } #endif #endif } void CCNotePad::slot_fileChange(QString filePath) { QWidget *pw = nullptr; int changeIndex = -1; for (int i = 0; i < ui.editTabWidget->count(); ++i) { pw = ui.editTabWidget->widget(i); if (pw != nullptr && (pw->property(Edit_View_FilePath) == filePath)) { //这里只设置1个标志,下次获取焦点时,才判定询问是否需要重新加载 pw->setProperty(Modify_Outside, QVariant(true)); changeIndex = i; break; } } //如果就是当前文件,则直接弹窗提示 if (ui.editTabWidget->currentIndex() == changeIndex) { checkRoladFile(dynamic_cast<ScintillaEditView*>(pw)); } } void CCNotePad::slot_tabBarDoubleClicked(int index) { if (-1 == index) { initTabNewOne(); } } //tab的双击行为 void CCNotePad::on_tabBarDoubleClicked(int index) { //如果是主窗口,则分出去;反之则回到主窗口 QWidget* pw = ui.editTabWidget->widget(index); if (pw == nullptr || (-1 != getFileNewIndexProperty(pw))) { return; } if (m_isMainWindows) { openFileInNewWin(index); } else { //一个窗口时,分出去后,当前直接关闭 bool isQuit = (ui.editTabWidget->count() == 1); if (pw != nullptr) { QString filePath = getFilePathProperty(pw); tabClose(index, true); if (s_padInstances != nullptr) { for (int i = 0; i < s_padInstances->size(); ++i) { CCNotePad* c = s_padInstances->at(i); if (c->m_isMainWindows) { c->openFile(filePath); } } } if(isQuit) { close(); } } } } void CCNotePad::slot_tabBarClicked(int index) { QWidget* pw = ui.editTabWidget->widget(index); if (pw == nullptr) { return; } int docType = getDocTypeProperty(pw); if (TXT_TYPE == docType) { ScintillaEditView* pEdit = dynamic_cast<ScintillaEditView*>(pw); if (checkRoladFile(pEdit)) { return; } } //右键菜单 if (Qt::RightButton == QGuiApplication::mouseButtons()) { if (m_tabRightClickMenu == nullptr) { m_tabRightClickMenu = new QMenu(this); m_tabRightClickMenu->addAction(tr("Close Current Document"),this,&CCNotePad::slot_actionClose); m_tabRightClickMenu->addAction(tr("Close Non-Current documents"),this, &CCNotePad::slot_actionCloseNonCurDoc); m_tabRightClickMenu->addAction(tr("Close Left All"),this, &CCNotePad::slot_actionCloseLeftAll); m_tabRightClickMenu->addAction(tr("Close Right All"),this, &CCNotePad::slot_actionCloseRightAll); m_tabRightClickMenu->addSeparator(); m_tabRightClickMenu->addAction(tr("Rename Current Document "), this, &CCNotePad::slot_actionRenameFile_toggle); m_tabRightClickMenu->addAction(tr("Current Document Sava as..."), this, &CCNotePad::slot_actionSaveAsFile_toggle); m_openInNewWinAct = m_tabRightClickMenu->addAction(tr("Open in New Window"),this, &CCNotePad::slot_openFileInNewWin); m_showFileDirAct = m_tabRightClickMenu->addAction(tr("Show File in Explorer..."), this, &CCNotePad::slot_showFileInExplorer); #ifdef Q_OS_WIN //每种linux mac系统的打开cmd终端方式均不一样,暂时只支持windows m_showCmdAct = m_tabRightClickMenu->addAction(tr("Cmd in Explorer..."), this, &CCNotePad::slot_showCmdInExplorer); #endif m_tabRightClickMenu->addSeparator(); m_openWithText = m_tabRightClickMenu->addAction(tr("Reload With Text Mode"), this, &CCNotePad::slot_reOpenTextMode); m_openWithHex = m_tabRightClickMenu->addAction(tr("Reload With Hex Mode"), this, &CCNotePad::slot_reOpenHexMode); m_tabRightClickMenu->addSeparator(); m_selectLeftCmp = m_tabRightClickMenu->addAction(tr("Select Left Cmp File"), this, &CCNotePad::slot_selectLeftFile); m_selectRightCmp = m_tabRightClickMenu->addAction(tr("Select Right Cmp File"), this, &CCNotePad::slot_selectRightFile); } //非new文件才能重新打开和定位到文件 if (getFileNewIndexProperty(pw) == -1) { m_openInNewWinAct->setEnabled(true); m_showFileDirAct->setEnabled(true); #ifdef Q_OS_WIN m_showCmdAct->setEnabled(true); #endif } else { m_openInNewWinAct->setEnabled(false); m_showFileDirAct->setEnabled(false); #ifdef Q_OS_WIN m_showCmdAct->setEnabled(false); #endif } if ((TXT_TYPE == docType) && (getFileNewIndexProperty(pw) == -1)) { m_openWithText->setEnabled(false); m_openWithHex->setEnabled(true); m_selectLeftCmp->setEnabled(true); m_selectRightCmp->setEnabled(true); } else if (HEX_TYPE == docType) { m_openWithText->setEnabled(true); m_openWithHex->setEnabled(false); m_selectLeftCmp->setEnabled(false); m_selectRightCmp->setEnabled(false); } else if ((TXT_TYPE == docType) && (getFileNewIndexProperty(pw) != -1)) { //新的文本,都不能 m_openWithText->setEnabled(false); m_openWithHex->setEnabled(false); m_selectLeftCmp->setEnabled(false); m_selectRightCmp->setEnabled(false); } else if(BIG_TEXT_RO_TYPE == docType || SUPER_BIG_TEXT_RO_TYPE == docType) { m_openWithText->setEnabled(false); m_openWithHex->setEnabled(true); m_selectLeftCmp->setEnabled(false); m_selectRightCmp->setEnabled(false); } ui.editTabWidget->setCurrentIndex(index); m_tabRightClickMenu->move(cursor().pos()); m_tabRightClickMenu->show(); } else if (Qt::MiddleButton == QGuiApplication::mouseButtons()) { //关闭当前文件 slot_tabClose(index); } } void CCNotePad::slot_reOpenTextMode() { QWidget* pw = ui.editTabWidget->currentWidget(); QString filePath = getFilePathProperty(pw); if (HEX_TYPE != getDocTypeProperty(pw)) { ui.statusBar->showMessage(tr("The currently file %1 is already in text mode").arg(filePath),5000); return; } slot_actionClose(true); openTextFile(filePath,false); } void CCNotePad::slot_reOpenHexMode() { QWidget* pw = ui.editTabWidget->currentWidget(); QString filePath = getFilePathProperty(pw); if (HEX_TYPE == getDocTypeProperty(pw)) { ui.statusBar->showMessage(tr("The currently file %1 is already in bin mode").arg(filePath),5000); return; } slot_actionClose(true); openHexFile(filePath); } void CCNotePad::slot_selectLeftFile() { QWidget* pw = ui.editTabWidget->currentWidget(); if (pw != nullptr) { m_cmpLeftFilePath = pw->property(Edit_View_FilePath).toString(); if (!m_cmpLeftFilePath.isEmpty() && !m_cmpRightFilePath.isEmpty()) { cmpSelectFile(); m_cmpLeftFilePath.clear(); m_cmpRightFilePath.clear(); } } } void CCNotePad::slot_selectRightFile() { QWidget* pw = ui.editTabWidget->currentWidget(); if (pw != nullptr) { m_cmpRightFilePath = pw->property(Edit_View_FilePath).toString(); if (!m_cmpLeftFilePath.isEmpty() && !m_cmpRightFilePath.isEmpty()) { cmpSelectFile(); m_cmpLeftFilePath.clear(); m_cmpRightFilePath.clear(); } } } //为了避免路径中\\不一样导致的查找不到问题,进行统一替换 QString getRegularFilePath(QString& path) { #ifdef _WIN32 path = path.replace("/", "\\"); #else path = path.replace("\\", "/"); #endif return path; } void CCNotePad::slot_showFileInExplorer() { QString path; QWidget* pw = ui.editTabWidget->currentWidget(); if (pw != nullptr) { path = pw->property(Edit_View_FilePath).toString(); } showFileInExplorer(path); } //打开cmd窗口 #ifdef Q_OS_WIN void CCNotePad::slot_showCmdInExplorer() { QString path; QWidget* pw = ui.editTabWidget->currentWidget(); if (pw != nullptr) { path = pw->property(Edit_View_FilePath).toString(); } QFileInfo fi(path); QString dirEment = fi.absolutePath(); HWND hWnd = (HWND)this->effectiveWinId(); HINSTANCE res = ::ShellExecute(hWnd, TEXT("open"), TEXT("cmd"), TEXT(""), dirEment.toStdWString().data(), SW_SHOW); //参考 https://msdn.microsoft.com/en-us/library/windows/desktop/bb762153(v=vs.85).aspx int retResult = static_cast<int>(reinterpret_cast<INT_PTR>(res)); if (retResult <= 32) { ui.statusBar->showMessage(tr("open cmd in file dir %1 failed.").arg(dirEment)); } #if 0 //下面方法不能分离式,主界面关闭后,cmd也消失了 QStringList arguments; arguments << "/K"; arguments << "title"; arguments << "child process"; QProcess* myProcess = new QProcess(this); QString program = "C:/Windows/System32/cmd.exe"; myProcess->setCreateProcessArgumentsModifier([](QProcess::CreateProcessArguments* args) { //args->startupInfo->wShowWindow = SW_SHOWMAXIMIZED;//此成员变量设置此有效,QT5.12 args->flags |= CREATE_NEW_CONSOLE; args->startupInfo->dwFlags &= ~STARTF_USESTDHANDLES; args->startupInfo->dwFlags |= STARTF_USEFILLATTRIBUTE; args->startupInfo->dwFillAttribute = FOREGROUND_INTENSITY; //args->startupInfo->dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES; }); myProcess->start(program, arguments); #endif } #endif //把文件在新窗口中打开。如果是新文件,则不行 void CCNotePad::openFileInNewWin(int index) { QString path; QWidget* pw = ui.editTabWidget->widget(index); if (pw != nullptr) { if (-1 != getFileNewIndexProperty(pw)) { return; } path = getFilePathProperty(pw); slot_tabClose(index); CCNotePad* pNewWin = new CCNotePad(false, nullptr); pNewWin->quickshow(); pNewWin->setShareMem(this->getShareMem()); pNewWin->setAttribute(Qt::WA_DeleteOnClose); pNewWin->openFile(path); #ifdef uos adjustWInPos(pNewWin); #endif s_padInstances->append(pNewWin); } } void CCNotePad::slot_openFileInNewWin() { int curIndex = ui.editTabWidget->currentIndex(); openFileInNewWin(curIndex); } //int defLexerId:如果失败,则按照该语法类型的id赋值;如果-1则不给与默认值。 //因为发现如果是新建的文件,而且手动设置了语法,其文件名还是*.txt,此时如果根据 //后缀名自动赋值与否,会导致手动设置的语法失效。 void CCNotePad::autoSetDocLexer(ScintillaEditView* pEdit, int defLexerId) { QString filePath = pEdit->property(Edit_View_FilePath).toString(); //OpenAttr openType = (OpenAttr)pEdit->property(Open_Attr).toInt(); //if (OpenAttr::Text != openType && OpenAttr::BigTextReadOnly != openType) //{ // return; //} LexerInfo lxdata = getLangLexerIdByFileExt(filePath); QsciLexer* lexer = nullptr; //如果没有特殊语法,而且默认给与语法不是-1,则按照默认语法设置 if (lxdata.lexerId == L_TXT && defLexerId != -1) { lexer = ScintillaEditView::createLexer(defLexerId); } else { lexer = ScintillaEditView::createLexer(lxdata.lexerId, lxdata.tagName); } if (lexer != nullptr) { if (nullptr != pEdit->lexer()) { delete pEdit->lexer(); } pEdit->setLexer(lexer); syncCurDocLexerToMenu(pEdit); } else { setTxtLexer(pEdit); syncCurDocLexerToMenu(pEdit); } } void CCNotePad::updateTitleToCurDocFilePath() { QWidget* pw = ui.editTabWidget->currentWidget(); if (pw != nullptr) { setWindowTitle(pw->property(Edit_View_FilePath).toString()); } } //切换tab后 void CCNotePad::slot_tabCurrentChanged(int index) { QWidget* pw = ui.editTabWidget->widget(index); if (pw != nullptr) { QString filePath = getFilePathProperty(pw); //16进制的处理逻辑 int docType = getDocTypeProperty(pw); if (HEX_TYPE == docType) { setWindowTitleMode(filePath, OpenAttr::HexReadOnly); fileListSetCurItem(filePath); return; } else if ((TXT_TYPE == docType)||(BIG_TEXT_RO_TYPE == docType)||(SUPER_BIG_TEXT_RO_TYPE == docType)) { int code = pw->property(Edit_Text_Code).toInt(); setCodeBarLabel(static_cast<CODE_ID>(code)); int lineEnd = pw->property(Edit_Text_End).toInt(); setLineEndBarLabel(static_cast<RC_LINE_FORM>(lineEnd)); if (pw->property(Edit_Text_Change).toBool()) { m_saveFile->setEnabled(true); } else { m_saveFile->setEnabled(false); } if (TXT_TYPE == docType) { setWindowTitleMode(filePath, (OpenAttr)pw->property(Open_Attr).toInt()); } else if (BIG_TEXT_RO_TYPE == docType) { //setWindowTitle(QString("%1 (%2)").arg(pw->property(Edit_View_FilePath).toString()).arg(tr("Big Text File ReadOnly"))); setWindowTitleMode(filePath, OpenAttr::BigTextReadOnly); } else if (SUPER_BIG_TEXT_RO_TYPE == docType) { //setWindowTitle(QString("%1 (%2)").arg(pw->property(Edit_View_FilePath).toString()).arg(tr("Big Text File ReadOnly"))); setWindowTitleMode(filePath, OpenAttr::SuperBigTextReadOnly); } syncCurDocEncodeToMenu(pw); syncCurDocLineEndStatusToMenu(pw); syncCurDocLexerToMenu(pw); syncCurDocTailfToMenu(pw); ScintillaEditView* pEdit = dynamic_cast<ScintillaEditView*>(pw); //目前只用了0 2 两种换行模式。 if (s_autoWarp != pEdit->wrapMode()) { pEdit->setWrapMode((s_autoWarp == 0 ? QsciScintilla::WrapNone: QsciScintilla::WrapCharacter)); } pEdit->viewport()->setFocus(); fileListSetCurItem(filePath); } } } //快捷按钮的初始化 void CCNotePad::setShoctIcon(int iconSize) { #if 0 auto setDark32Icon = [this]() { //黑色图标 m_newFile->setIcon(QIcon(NewFileIconDark32)); m_openFile->setIcon(QIcon(OpenFileIconDark32)); m_saveFile->setIcon(QIcon(NoNeedSaveBarIconDark32)); m_saveAllFile->setIcon(QIcon(NoNeedSaveAllBarIconDark32)); m_autoSaveAFile->setIcon(QIcon(AutoTimeSaveBarIconDark32)); m_closeFile->setIcon(QIcon(CloseFileIconDark32)); m_closeAllFile->setIcon(QIcon(CloseAllFileIconDark32)); m_cutFile->setIcon(QIcon(CutIconDark32)); m_copyFile->setIcon(QIcon(CopyFileIconDark32)); m_pasteFile->setIcon(QIcon(PasteIconDark32)); m_undo->setIcon(QIcon(UndoIconDark32)); m_redo->setIcon(QIcon(RedoIconDark32)); m_findText->setIcon(QIcon(FindIconDark32)); m_replaceText->setIcon(QIcon(ReplaceIconDark32)); m_markText->setIcon(QIcon(MarkIconDark32)); m_signText->setIcon(QIcon(SignIconDark32)); m_clearMark->setIcon(QIcon(ClearSignIconDark32)); m_zoomin->setIcon(QIcon(ZoominIconDark32)); m_zoomout->setIcon(QIcon(ZoomoutIconDark32)); m_wordwrap->setIcon(QIcon(CrlfIconDark32)); m_allWhite->setIcon(QIcon(WhiteIconDark32)); m_indentGuide->setIcon(QIcon(IndentIconDark32)); m_preHexPage->setIcon(QIcon(PreHexIconDark32)); m_nextHexPage->setIcon(QIcon(NextHexIconDark32)); m_gotoHexPage->setIcon(QIcon(GotoHexIconDark32)); m_fileCompare->setIcon(QIcon(FileCompareIconDark32)); m_dirCompare->setIcon(QIcon(DirCompareIconDark32)); m_binCompare->setIcon(QIcon(BinCmpIconDark32)); m_transcode->setIcon(QIcon(TransCodeIconDark32)); m_rename->setIcon(QIcon(RenameIconDark32)); }; if (iconSize < 48) { if (iconSize == 36 && StyleSet::getCurrentSytleId() == DEEP_BLACK) { setDark32Icon(); } else { m_newFile->setIcon(QIcon(NewFileIcon)); m_openFile->setIcon(QIcon(OpenFileIcon)); m_saveFile->setIcon(QIcon(NoNeedSaveBarIcon)); m_saveAllFile->setIcon(QIcon(NoNeedSaveAllBarIcon)); m_autoSaveAFile->setIcon(QIcon(AutoTimeSaveBarIcon)); m_closeFile->setIcon(QIcon(CloseFileIcon)); m_closeAllFile->setIcon(QIcon(CloseAllFileIcon)); m_cutFile->setIcon(QIcon(CutIcon)); m_copyFile->setIcon(QIcon(CopyFileIcon)); m_pasteFile->setIcon(QIcon(PasteIcon)); m_undo->setIcon(QIcon(UndoIcon)); m_redo->setIcon(QIcon(RedoIcon)); m_findText->setIcon(QIcon(FindIcon)); m_replaceText->setIcon(QIcon(ReplaceIcon)); m_markText->setIcon(QIcon(MarkIcon)); m_signText->setIcon(QIcon(SignIcon)); m_clearMark->setIcon(QIcon(ClearSignIcon)); m_zoomin->setIcon(QIcon(ZoominIcon)); m_zoomout->setIcon(QIcon(ZoomoutIcon)); m_wordwrap->setIcon(QIcon(CrlfIcon)); m_allWhite->setIcon(QIcon(WhiteIcon)); m_indentGuide->setIcon(QIcon(IndentIcon)); m_preHexPage->setIcon(QIcon(PreHexIcon)); m_nextHexPage->setIcon(QIcon(NextHexIcon)); m_gotoHexPage->setIcon(QIcon(GotoHexIcon)); m_fileCompare->setIcon(QIcon(FileCompareIcon)); m_dirCompare->setIcon(QIcon(DirCompareIcon)); m_binCompare->setIcon(QIcon(BinCmpIcon)); m_transcode->setIcon(QIcon(TransCodeIcon)); m_rename->setIcon(QIcon(RenameIcon)); } } else { if (StyleSet::getCurrentSytleId() != DEEP_BLACK) { m_newFile->setIcon(QIcon(NewFileIcon32)); m_openFile->setIcon(QIcon(OpenFileIcon32)); m_saveFile->setIcon(QIcon(NoNeedSaveBarIcon32)); m_saveAllFile->setIcon(QIcon(NoNeedSaveAllBarIcon32)); m_autoSaveAFile->setIcon(QIcon(AutoTimeSaveBarIcon32)); m_closeFile->setIcon(QIcon(CloseFileIcon32)); m_closeAllFile->setIcon(QIcon(CloseAllFileIcon32)); m_cutFile->setIcon(QIcon(CutIcon32)); m_copyFile->setIcon(QIcon(CopyFileIcon32)); m_pasteFile->setIcon(QIcon(PasteIcon32)); m_undo->setIcon(QIcon(UndoIcon32)); m_redo->setIcon(QIcon(RedoIcon32)); m_findText->setIcon(QIcon(FindIcon32)); m_replaceText->setIcon(QIcon(ReplaceIcon32)); m_markText->setIcon(QIcon(MarkIcon32)); m_signText->setIcon(QIcon(SignIcon32)); m_clearMark->setIcon(QIcon(ClearSignIcon32)); m_zoomin->setIcon(QIcon(ZoominIcon32)); m_zoomout->setIcon(QIcon(ZoomoutIcon32)); m_wordwrap->setIcon(QIcon(CrlfIcon32)); m_allWhite->setIcon(QIcon(WhiteIcon32)); m_indentGuide->setIcon(QIcon(IndentIcon32)); m_preHexPage->setIcon(QIcon(PreHexIcon32)); m_nextHexPage->setIcon(QIcon(NextHexIcon32)); m_gotoHexPage->setIcon(QIcon(GotoHexIcon32)); m_fileCompare->setIcon(QIcon(FileCompareIcon32)); m_dirCompare->setIcon(QIcon(DirCompareIcon32)); m_binCompare->setIcon(QIcon(BinCmpIcon32)); m_transcode->setIcon(QIcon(TransCodeIcon32)); m_rename->setIcon(QIcon(RenameIcon32)); } else { setDark32Icon(); } } #endif if (iconSize < 48) { m_newFile->setIcon(QIcon(NewFileIcon)); m_openFile->setIcon(QIcon(OpenFileIcon)); m_saveFile->setIcon(QIcon(NoNeedSaveBarIcon)); m_saveAllFile->setIcon(QIcon(NoNeedSaveAllBarIcon)); m_autoSaveAFile->setIcon(QIcon(AutoTimeSaveBarIcon)); m_closeFile->setIcon(QIcon(CloseFileIcon)); m_closeAllFile->setIcon(QIcon(CloseAllFileIcon)); m_cutFile->setIcon(QIcon(CutIcon)); m_copyFile->setIcon(QIcon(CopyFileIcon)); m_pasteFile->setIcon(QIcon(PasteIcon)); m_undo->setIcon(QIcon(UndoIcon)); m_redo->setIcon(QIcon(RedoIcon)); m_findText->setIcon(QIcon(FindIcon)); m_replaceText->setIcon(QIcon(ReplaceIcon)); m_markText->setIcon(QIcon(MarkIcon)); m_signText->setIcon(QIcon(SignIcon)); m_clearMark->setIcon(QIcon(ClearSignIcon)); m_zoomin->setIcon(QIcon(ZoominIcon)); m_zoomout->setIcon(QIcon(ZoomoutIcon)); m_wordwrap->setIcon(QIcon(CrlfIcon)); m_allWhite->setIcon(QIcon(WhiteIcon)); m_indentGuide->setIcon(QIcon(IndentIcon)); m_tailf->setIcon(QIcon(TailfIcon)); m_preHexPage->setIcon(QIcon(PreHexIcon)); m_nextHexPage->setIcon(QIcon(NextHexIcon)); m_gotoHexPage->setIcon(QIcon(GotoHexIcon)); m_transcode->setIcon(QIcon(TransCodeIcon)); m_rename->setIcon(QIcon(RenameIcon)); } else { m_newFile->setIcon(QIcon(NewFileIcon32)); m_openFile->setIcon(QIcon(OpenFileIcon32)); m_saveFile->setIcon(QIcon(NoNeedSaveBarIcon32)); m_saveAllFile->setIcon(QIcon(NoNeedSaveAllBarIcon32)); m_autoSaveAFile->setIcon(QIcon(AutoTimeSaveBarIcon32)); m_closeFile->setIcon(QIcon(CloseFileIcon32)); m_closeAllFile->setIcon(QIcon(CloseAllFileIcon32)); m_cutFile->setIcon(QIcon(CutIcon32)); m_copyFile->setIcon(QIcon(CopyFileIcon32)); m_pasteFile->setIcon(QIcon(PasteIcon32)); m_undo->setIcon(QIcon(UndoIcon32)); m_redo->setIcon(QIcon(RedoIcon32)); m_findText->setIcon(QIcon(FindIcon32)); m_replaceText->setIcon(QIcon(ReplaceIcon32)); m_markText->setIcon(QIcon(MarkIcon32)); m_signText->setIcon(QIcon(SignIcon32)); m_clearMark->setIcon(QIcon(ClearSignIcon32)); m_zoomin->setIcon(QIcon(ZoominIcon32)); m_zoomout->setIcon(QIcon(ZoomoutIcon32)); m_wordwrap->setIcon(QIcon(CrlfIcon32)); m_allWhite->setIcon(QIcon(WhiteIcon32)); m_indentGuide->setIcon(QIcon(IndentIcon32)); m_tailf->setIcon(QIcon(TailfIcon32)); m_preHexPage->setIcon(QIcon(PreHexIcon32)); m_nextHexPage->setIcon(QIcon(NextHexIcon32)); m_gotoHexPage->setIcon(QIcon(GotoHexIcon32)); m_transcode->setIcon(QIcon(TransCodeIcon32)); m_rename->setIcon(QIcon(RenameIcon32)); } } void CCNotePad::initToolBar() { int iconIndex = NddSetting::getKeyValueFromNumSets(ICON_SIZE); int ICON_SIZE = 24; if (iconIndex == 0) { ui.action24->setChecked(true); } else if (iconIndex == 1) { ICON_SIZE = 36; ui.action36->setChecked(true); } else if (iconIndex == 2) { ICON_SIZE = 48; ui.action48->setChecked(true); } m_curIconSize = ICON_SIZE; s_autoWarp = NddSetting::getKeyValueFromNumSets(AUTOWARP_KEY); s_zoomValue = NddSetting::getKeyValueFromNumSets(ZOOMVALUE); if (s_zoomValue > 10 || s_zoomValue < -5) { s_zoomValue = 0; NddSetting::updataKeyValueFromNumSets(ZOOMVALUE, s_zoomValue); } s_indent = NddSetting::getKeyValueFromNumSets(INDENT_KEY); s_showblank = NddSetting::getKeyValueFromNumSets(SHOWSPACE_KEY); m_newFile = new QToolButton(ui.mainToolBar); connect(m_newFile, &QAbstractButton::clicked, this, &CCNotePad::slot_actionNewFile_toggle); m_newFile->setFixedSize(ICON_SIZE, ICON_SIZE); m_newFile->setToolTip(tr("New File")); ui.mainToolBar->addWidget(m_newFile); m_openFile = new QToolButton(ui.mainToolBar); connect(m_openFile, &QAbstractButton::clicked, this, &CCNotePad::slot_actionOpenFile_toggle); m_openFile->setFixedSize(ICON_SIZE, ICON_SIZE); m_openFile->setToolTip(tr("Open File")); ui.mainToolBar->addWidget(m_openFile); m_saveFile = new QToolButton(ui.mainToolBar); connect(m_saveFile, &QAbstractButton::clicked, this, &CCNotePad::slot_actionSaveFile_toggle); m_saveFile->setFixedSize(ICON_SIZE, ICON_SIZE); m_saveFile->setToolTip(tr("Save File")); ui.mainToolBar->addWidget(m_saveFile); m_saveAllFile = new QToolButton(ui.mainToolBar); connect(m_saveAllFile, &QAbstractButton::clicked, this, &CCNotePad::slot_saveAllFile); m_saveAllFile->setFixedSize(ICON_SIZE, ICON_SIZE); m_saveAllFile->setToolTip(tr("Save All File")); ui.mainToolBar->addWidget(m_saveAllFile); m_autoSaveAFile = new QToolButton(ui.mainToolBar); m_autoSaveAFile->setCheckable(true); connect(m_autoSaveAFile, &QAbstractButton::clicked, this, &CCNotePad::slot_autoSaveFile); m_autoSaveAFile->setFixedSize(ICON_SIZE, ICON_SIZE); m_autoSaveAFile->setToolTip(tr("Cycle Auto Save")); ui.mainToolBar->addWidget(m_autoSaveAFile); m_closeFile = new QToolButton(ui.mainToolBar); connect(m_closeFile, &QAbstractButton::clicked, this, &CCNotePad::slot_actionClose); m_closeFile->setFixedSize(ICON_SIZE, ICON_SIZE); m_closeFile->setToolTip(tr("Close")); ui.mainToolBar->addWidget(m_closeFile); m_closeAllFile = new QToolButton(ui.mainToolBar); connect(m_closeAllFile, &QAbstractButton::clicked, this, &CCNotePad::slot_closeAllFile); m_closeAllFile->setFixedSize(ICON_SIZE, ICON_SIZE); m_closeAllFile->setToolTip(tr("Close All")); ui.mainToolBar->addWidget(m_closeAllFile); ui.mainToolBar->addSeparator(); m_cutFile = new QToolButton(ui.mainToolBar); connect(m_cutFile, &QAbstractButton::clicked, this, &CCNotePad::slot_cut); m_cutFile->setFixedSize(ICON_SIZE, ICON_SIZE); m_cutFile->setToolTip(tr("Cut")); ui.mainToolBar->addWidget(m_cutFile); m_copyFile = new QToolButton(ui.mainToolBar); connect(m_copyFile, &QAbstractButton::clicked, this, &CCNotePad::slot_copy); m_copyFile->setFixedSize(ICON_SIZE, ICON_SIZE); m_copyFile->setIcon(QIcon(CopyFileIcon)); m_copyFile->setToolTip(tr("Copy")); ui.mainToolBar->addWidget(m_copyFile); m_pasteFile = new QToolButton(ui.mainToolBar); connect(m_pasteFile, &QAbstractButton::clicked, this, &CCNotePad::slot_paste); m_pasteFile->setFixedSize(ICON_SIZE, ICON_SIZE); m_pasteFile->setToolTip(tr("Paste")); ui.mainToolBar->addWidget(m_pasteFile); ui.mainToolBar->addSeparator(); m_undo = new QToolButton(ui.mainToolBar); connect(m_undo, &QAbstractButton::clicked, this, &CCNotePad::slot_undo); m_undo->setFixedSize(ICON_SIZE, ICON_SIZE); m_undo->setToolTip(tr("Undo")); ui.mainToolBar->addWidget(m_undo); m_redo = new QToolButton(ui.mainToolBar); connect(m_redo, &QAbstractButton::clicked, this, &CCNotePad::slot_redo); m_redo->setFixedSize(ICON_SIZE, ICON_SIZE); m_redo->setToolTip(tr("Redo")); ui.mainToolBar->addWidget(m_redo); ui.mainToolBar->addSeparator(); m_findText = new QToolButton(ui.mainToolBar); connect(m_findText, &QAbstractButton::clicked, this, &CCNotePad::slot_find); m_findText->setFixedSize(ICON_SIZE, ICON_SIZE); m_findText->setToolTip(tr("Find")); ui.mainToolBar->addWidget(m_findText); m_replaceText = new QToolButton(ui.mainToolBar); connect(m_replaceText, &QAbstractButton::clicked, this, &CCNotePad::slot_replace); m_replaceText->setFixedSize(ICON_SIZE, ICON_SIZE); m_replaceText->setToolTip(tr("Replace")); ui.mainToolBar->addWidget(m_replaceText); m_markText = new QToolButton(ui.mainToolBar); connect(m_markText, &QAbstractButton::clicked, this, &CCNotePad::slot_markHighlight); m_markText->setFixedSize(ICON_SIZE, ICON_SIZE); m_markText->setToolTip(tr("Mark")); ui.mainToolBar->addWidget(m_markText); ui.mainToolBar->addSeparator(); //选择单词高亮 m_signText = new QToolButton(ui.mainToolBar); connect(m_signText, &QAbstractButton::clicked, this, &CCNotePad::slot_wordHighlight); m_signText->setFixedSize(ICON_SIZE, ICON_SIZE); m_signText->setToolTip(tr("word highlight(F8)")); m_signText->setShortcut(QKeySequence(Qt::Key_F8)); ui.mainToolBar->addWidget(m_signText); //选择单词高亮 m_clearMark = new QToolButton(ui.mainToolBar); connect(m_clearMark, &QAbstractButton::clicked, this, &CCNotePad::slot_clearMark); m_clearMark->setFixedSize(ICON_SIZE, ICON_SIZE); m_clearMark->setToolTip(tr("clear all highlight(F7)")); m_clearMark->setShortcut(QKeySequence(Qt::Key_F7)); ui.mainToolBar->addWidget(m_clearMark); ui.mainToolBar->addSeparator(); m_zoomin = new QToolButton(ui.mainToolBar); connect(m_zoomin, &QAbstractButton::clicked, this, &CCNotePad::slot_zoomin); m_zoomin->setFixedSize(ICON_SIZE, ICON_SIZE); m_zoomin->setToolTip(tr("Zoom In")); ui.mainToolBar->addWidget(m_zoomin); m_zoomout = new QToolButton(ui.mainToolBar); connect(m_zoomout, &QAbstractButton::clicked, this, &CCNotePad::slot_zoomout); m_zoomout->setFixedSize(ICON_SIZE, ICON_SIZE); m_zoomout->setToolTip(tr("Zoom Out")); ui.mainToolBar->addWidget(m_zoomout); ui.mainToolBar->addSeparator(); m_wordwrap = new QToolButton(ui.mainToolBar); m_wordwrap->setCheckable(true); m_wordwrap->setChecked((s_autoWarp != QsciScintilla::WrapNone)); connect(m_wordwrap, &QAbstractButton::clicked, this, &CCNotePad::slot_wordwrap); m_wordwrap->setFixedSize(ICON_SIZE, ICON_SIZE); m_wordwrap->setToolTip(tr("Word Wrap")); ui.mainToolBar->addWidget(m_wordwrap); ui.actionWrap->setChecked((s_autoWarp != QsciScintilla::WrapNone)); m_allWhite = new QToolButton(ui.mainToolBar); m_allWhite->setCheckable(true); m_allWhite->setChecked((s_showblank == 3)); //这里使用clicked信号。修改setChecked时,不会触发该信号,避免循环触发。 //注意统一:凡是需要两个地方控制一个状态,同步的地方。按钮使用clicked信号,action使用triggered。 //因为这两个信号,不会被setchecked修改,这样其他地方调用setchecked时,避免信号循环冲突 connect(m_allWhite, &QAbstractButton::clicked, this, &CCNotePad::slot_allWhite); m_allWhite->setFixedSize(ICON_SIZE, ICON_SIZE); m_allWhite->setToolTip(tr("Show Blank")); ui.mainToolBar->addWidget(m_allWhite); ui.actionShowAll->setChecked((s_showblank == 3)); m_indentGuide = new QToolButton(ui.mainToolBar); m_indentGuide->setCheckable(true); m_indentGuide->setChecked((s_indent == 1)); connect(m_indentGuide, &QAbstractButton::toggled, this, &CCNotePad::slot_indentGuide); m_indentGuide->setFixedSize(ICON_SIZE, ICON_SIZE); m_indentGuide->setToolTip(tr("Indent Guide")); ui.mainToolBar->addWidget(m_indentGuide); m_tailf = new QToolButton(ui.mainToolBar); m_tailf->setCheckable(true); m_tailf->setChecked(false); connect(m_tailf, &QAbstractButton::clicked, this, &CCNotePad::on_tailfile); m_tailf->setFixedSize(ICON_SIZE, ICON_SIZE); m_tailf->setToolTip(tr("tailf file")); ui.mainToolBar->addWidget(m_tailf); ui.mainToolBar->addSeparator(); m_preHexPage = new QToolButton(ui.mainToolBar); connect(m_preHexPage, &QAbstractButton::clicked, this, &CCNotePad::slot_preHexPage); m_preHexPage->setFixedSize(ICON_SIZE, ICON_SIZE); m_preHexPage->setToolTip(tr("Pre Hex Page")); ui.mainToolBar->addWidget(m_preHexPage); m_nextHexPage = new QToolButton(ui.mainToolBar); connect(m_nextHexPage, &QAbstractButton::clicked, this, &CCNotePad::slot_nextHexPage); m_nextHexPage->setFixedSize(ICON_SIZE, ICON_SIZE); m_nextHexPage->setToolTip(tr("Next Hex Page")); ui.mainToolBar->addWidget(m_nextHexPage); m_gotoHexPage = new QToolButton(ui.mainToolBar); connect(m_gotoHexPage, &QAbstractButton::clicked, this, &CCNotePad::slot_gotoHexPage); m_gotoHexPage->setFixedSize(ICON_SIZE, ICON_SIZE); m_gotoHexPage->setToolTip(tr("Goto Hex Page")); ui.mainToolBar->addWidget(m_gotoHexPage); ui.mainToolBar->addSeparator(); m_transcode = new QToolButton(ui.mainToolBar); connect(m_transcode, &QAbstractButton::clicked, this, &CCNotePad::slot_batch_convert); m_transcode->setFixedSize(ICON_SIZE, ICON_SIZE); m_transcode->setToolTip(tr("transform encoding")); ui.mainToolBar->addWidget(m_transcode); m_rename = new QToolButton(ui.mainToolBar); connect(m_rename, &QAbstractButton::clicked, this, &CCNotePad::slot_batch_rename); m_rename->setFixedSize(ICON_SIZE, ICON_SIZE); m_rename->setToolTip(tr("batch rename file")); ui.mainToolBar->addWidget(m_rename); setShoctIcon(ICON_SIZE); //编码里面只能有一个当前被选中 m_pEncodeActGroup = new QActionGroup(this); m_pEncodeActGroup->addAction(ui.actionencode_in_GBK); m_pEncodeActGroup->addAction(ui.actionencode_in_uft8); m_pEncodeActGroup->addAction(ui.actionencode_in_UTF8_BOM); m_pEncodeActGroup->addAction(ui.actionencode_in_UCS_BE_BOM); m_pEncodeActGroup->addAction(ui.actionencode_in_UCS_2_LE_BOM); m_pEncodeActGroup->addAction(ui.actionBig5); m_pEncodeActGroup->setExclusive(true); m_pLineEndActGroup = new QActionGroup(this); m_pLineEndActGroup->addAction(ui.actionconver_windows_CR_LF); m_pLineEndActGroup->addAction(ui.actionconvert_Unix_LF); m_pLineEndActGroup->addAction(ui.actionconvert_Mac_CR); m_pEncodeActGroup->setExclusive(true); m_pIconSize = new QActionGroup(this); m_pIconSize->addAction(ui.action24); m_pIconSize->addAction(ui.action36); m_pIconSize->addAction(ui.action48); m_pIconSize->setExclusive(true); connect(m_pIconSize, &QActionGroup::triggered, this, &CCNotePad::slot_changeIconSize, Qt::QueuedConnection); m_pLexerActGroup = new QActionGroup(this); /*m_pLexerActGroup->addAction(ui.actionAVS);*/ m_pLexerActGroup->addAction(ui.actionAssembly); m_pLexerActGroup->addAction(ui.actionbash); m_pLexerActGroup->addAction(ui.actionBatch); m_pLexerActGroup->addAction(ui.actionCMake); m_pLexerActGroup->addAction(ui.actionCoffeeScript); m_pLexerActGroup->addAction(ui.actionCPP); m_pLexerActGroup->addAction(ui.actionCShape); m_pLexerActGroup->addAction(ui.actionCss); m_pLexerActGroup->addAction(ui.actionD_2); m_pLexerActGroup->addAction(ui.actionDiff); m_pLexerActGroup->addAction(ui.actionEdifact); m_pLexerActGroup->addAction(ui.actionFortran); m_pLexerActGroup->addAction(ui.actionFortran77); m_pLexerActGroup->addAction(ui.actionHTML); m_pLexerActGroup->addAction(ui.actionIDL); m_pLexerActGroup->addAction(ui.actionJava); m_pLexerActGroup->addAction(ui.actionJavaScript); m_pLexerActGroup->addAction(ui.actionjson); m_pLexerActGroup->addAction(ui.actionLua); m_pLexerActGroup->addAction(ui.actionMakefile); m_pLexerActGroup->addAction(ui.actionMarkDown_2); m_pLexerActGroup->addAction(ui.actionMatlab); m_pLexerActGroup->addAction(ui.actionOctave); m_pLexerActGroup->addAction(ui.actionPascal); m_pLexerActGroup->addAction(ui.actionPerl); m_pLexerActGroup->addAction(ui.actionPo); m_pLexerActGroup->addAction(ui.actionPostScript); m_pLexerActGroup->addAction(ui.actionPov); m_pLexerActGroup->addAction(ui.actionProperties_file); m_pLexerActGroup->addAction(ui.actionPython); m_pLexerActGroup->addAction(ui.actionR_2); m_pLexerActGroup->addAction(ui.actionRuby); m_pLexerActGroup->addAction(ui.actionRust); m_pLexerActGroup->addAction(ui.actionSpice); m_pLexerActGroup->addAction(ui.actionSql); m_pLexerActGroup->addAction(ui.actionTcl); m_pLexerActGroup->addAction(ui.actionTex); m_pLexerActGroup->addAction(ui.actionVb); m_pLexerActGroup->addAction(ui.actionVerilog); m_pLexerActGroup->addAction(ui.actionVHDL); m_pLexerActGroup->addAction(ui.actionXML); m_pLexerActGroup->addAction(ui.actionYAML); m_pLexerActGroup->addAction(ui.actionPhp); m_pLexerActGroup->addAction(ui.actionC); m_pLexerActGroup->addAction(ui.actionObjective_C); m_pLexerActGroup->addAction(ui.actionRC); m_pLexerActGroup->addAction(ui.actionini); m_pLexerActGroup->addAction(ui.actionNfo); m_pLexerActGroup->addAction(ui.actionASP); m_pLexerActGroup->addAction(ui.actionVirsual_Basic); m_pLexerActGroup->addAction(ui.actionShell); m_pLexerActGroup->addAction(ui.actionActionScript); m_pLexerActGroup->addAction(ui.actionNSIS); m_pLexerActGroup->addAction(ui.actionLisp); m_pLexerActGroup->addAction(ui.actionScheme); m_pLexerActGroup->addAction(ui.actionAssembly); m_pLexerActGroup->addAction(ui.actionSmalltalk); m_pLexerActGroup->addAction(ui.actionAutoIt); m_pLexerActGroup->addAction(ui.actionPowerShell); m_pLexerActGroup->addAction(ui.actionJsp); m_pLexerActGroup->addAction(ui.actionBaanC); m_pLexerActGroup->addAction(ui.actionS_Record); m_pLexerActGroup->addAction(ui.actionTypeScript); m_pLexerActGroup->addAction(ui.actionVisual_Prolog); m_pLexerActGroup->addAction(ui.actionTxt2tags); m_pLexerActGroup->addAction(ui.actionRegistry); m_pLexerActGroup->addAction(ui.actionREBOL); m_pLexerActGroup->addAction(ui.actionOScript); m_pLexerActGroup->addAction(ui.actionNncrontab); m_pLexerActGroup->addAction(ui.actionNim); m_pLexerActGroup->addAction(ui.actionMMIXAL); m_pLexerActGroup->addAction(ui.actionLaTex); m_pLexerActGroup->addAction(ui.actionForth); m_pLexerActGroup->addAction(ui.actionESCRIPT); m_pLexerActGroup->addAction(ui.actionErlang); m_pLexerActGroup->addAction(ui.actionCsound); m_pLexerActGroup->addAction(ui.actionFreeBasic); m_pLexerActGroup->addAction(ui.actionBlitzBasic); m_pLexerActGroup->addAction(ui.actionPureBasic); m_pLexerActGroup->addAction(ui.actionAviSynth); m_pLexerActGroup->addAction(ui.actionASN1); m_pLexerActGroup->addAction(ui.actionSwift); m_pLexerActGroup->addAction(ui.actionIntel_HEX); m_pLexerActGroup->addAction(ui.actionGo); m_pLexerActGroup->addAction(ui.actionTxt); m_pLexerActGroup->addAction(ui.actionUserDefine); QActionGroup* langsGroup = new QActionGroup(this); langsGroup->addAction(ui.actionChinese); langsGroup->addAction(ui.actionEnglish); connect(ui.menuLanguage, &QMenu::triggered, this, &CCNotePad::slot_lexerActTrig); //这是在网上看到的一个方法,使用一个widget把位置占住,让后面的action跑到最后面 去 QWidget* space = new QWidget(); space->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); ui.mainToolBar->addWidget(space); QToolButton* closeX = new QToolButton(ui.mainToolBar); connect(closeX, &QAbstractButton::clicked, this, &CCNotePad::slot_actionClose); closeX->setFixedSize(ICON_SIZE, ICON_SIZE); closeX->setIcon(QIcon(RightCloseIcon)); closeX->setToolTip(tr("Close")); ui.mainToolBar->addWidget(closeX); syncBlankShowStatus(); } void CCNotePad::setZoomLabelValue(int zoomValue) { m_zoomLabel->setText(tr("Zoom: %1%").arg(zoomValue)); } void CCNotePad::slot_changeIconSize(QAction *action) { int size = 24; if (action == ui.action24) { size = 24; NddSetting::updataKeyValueFromNumSets(ICON_SIZE,0); ui.action24->setChecked(true); } else if (action == ui.action36) { size = 36; NddSetting::updataKeyValueFromNumSets(ICON_SIZE, 1); ui.action36->setChecked(true); } else if (action == ui.action48) { size = 48; NddSetting::updataKeyValueFromNumSets(ICON_SIZE, 2); ui.action48->setChecked(true); } m_curIconSize = size; const QObjectList & childs = ui.mainToolBar->children(); QToolButton* toolBt = nullptr; for (int i = 0; i < childs.size(); ++i) { toolBt = dynamic_cast<QToolButton*>(childs.at(i)); if (toolBt != nullptr) { toolBt->setFixedSize(size, size); } } setShoctIcon(size); } void CCNotePad::setTxtLexer(ScintillaEditView* pEdit) { QsciLexer* lexer = ScintillaEditView::createLexer(L_TXT, ""); pEdit->setLexer(lexer); } //点击语言lexer的槽函数 void CCNotePad::slot_lexerActTrig(QAction *action) { QWidget* pw = ui.editTabWidget->currentWidget(); ScintillaEditView* pEdit = dynamic_cast<ScintillaEditView*>(pw); if (pEdit != nullptr) { QVariant data = action->data(); if (data.isNull()) { QsciLexer * curLexer = pEdit->lexer(); if (curLexer != nullptr) { pEdit->setLexer(nullptr); delete curLexer; setTxtLexer(pEdit); } return; } int lexerId = data.toInt(); QsciLexer * curLexer = pEdit->lexer(); if (curLexer != nullptr) { QString tag = curLexer->lexerTag(); if (m_lexerNameToIndex.contains(tag)) { //当前已经相等了,则不需要重新设置lexer if (m_lexerNameToIndex.value(tag).index == lexerId) { return; } } else { //用户自定义的不在其中。不能设置为用户自定义的语法,不明确。 return; } delete curLexer; } QsciLexer * lexer = ScintillaEditView::createLexer(lexerId,""); if (lexer != nullptr) { pEdit->setLexer(lexer); QString tag = lexer->lexerTag(); setLangsDescLable(tag); } else { //默认按txt处理 setTxtLexer(pEdit); } } } //保存最近打开文件到数据库。文件只有在关闭时,才写入最近列表。不关闭的下次自动恢复打开 void CCNotePad::saveReceneOpenFile() { int clearOpenfilelist = NddSetting::getKeyValueFromDelayNumSets(CLEAR_OPENFILE_ON_CLOSE); //开启了关闭时清空打开历史列表 if (clearOpenfilelist == 1) { NddSetting::updataKeyValueFromDelaySets(RECENT_OPEN_FILE, ""); return; } QString rFile(RECENT_OPEN_FILE); const int maxRecord = 15; if (NddSetting::isDbExist()) { QStringList fileText; int count = 0; for (QList<QString>::iterator it = m_receneOpenFileList.begin(); it != m_receneOpenFileList.end(); ++it) { fileText.append(*it); if (count++ >= maxRecord) { break; } } if (!fileText.isEmpty()) { QString fileSaveText = fileText.join('|'); NddSetting::updataKeyValueFromDelaySets(rFile, fileSaveText); } } } //从最近列表中加载最近打开历史文件,到菜单中 void CCNotePad::on_loadReceneFile() { if (!m_isRecentFileLoaded) { m_isRecentFileLoaded = true; initReceneOpenFileMenu(); } } //从数据库读取最近对比的文件列表 void CCNotePad::initReceneOpenFileMenu() { QString rFile(RECENT_OPEN_FILE); if (NddSetting::isDbExist()) { QString fileStr = NddSetting::getKeyValueFromDelaySets(rFile); QStringList fileList = fileStr.split('|'); for (QString var : fileList) { if (!var.isEmpty() && (-1 == m_receneOpenFileList.indexOf(var))) { QAction* act = ui.menuRecene_File->addAction(var, this, &CCNotePad::slot_openReceneFile); act->setObjectName(var); m_receneOpenFileList.append(var); } } } } //判断文件是否已经打开中,是则返回其tabindex,否则-1 int CCNotePad::findFileIsOpenAtPad(QString filePath) { int ret = -1; getRegularFilePath(filePath); for (int i = 0; i < ui.editTabWidget->count(); ++i) { QWidget* pw = ui.editTabWidget->widget(i); if (pw != nullptr) { QString curPath = pw->property(Edit_View_FilePath).toString(); getRegularFilePath(curPath); if (curPath == filePath) { ret = i; break; } } } return ret; } //判断新建名称是否已经存在,是 true bool CCNotePad::isNewFileNameExist(QString& fileName) { for (int i = ui.editTabWidget->count() -1; i >=0 ; --i) { QWidget* pw = ui.editTabWidget->widget(i); if (pw != nullptr && (-1 != getFileNewIndexProperty(pw))) { if (getFilePathProperty(pw) == fileName) { return true; } } } return false; } //通过菜单打开最近文档 void CCNotePad::slot_openReceneFile() { QAction* pA = dynamic_cast<QAction*>(sender()); if (pA != nullptr) { //失败则删除对应的记录 if (!openFile(pA->text())) { pA->deleteLater(); } } } void CCNotePad::setCodeBarLabel(CODE_ID code) { QString codeStr = Encode::getCodeNameById(code); if (codeStr == "unknown") { codeStr = "UTF8"; } else if (codeStr == "GBK") { codeStr = tr("GB18030(Simplified Chinese)"); } else if(codeStr == "BIG5-HKSCS") { codeStr = tr("Big5(Traditional Chinese)"); } m_codeStatusLabel->setText(codeStr); } void CCNotePad::setLineEndBarLabel(RC_LINE_FORM lineEnd) { QString endStr = Encode::getLineEndById(lineEnd); if (m_lineEndLabel->currentText() != endStr) { //这里要禁止currentIndexChanged,避免循环触发 disconnect(m_lineEndLabel, QOverload<int>::of(&QComboBox::currentIndexChanged), this, &CCNotePad::on_lineEndChange); m_lineEndLabel->setCurrentText(endStr); connect(m_lineEndLabel, QOverload<int>::of(&QComboBox::currentIndexChanged), this, &CCNotePad::on_lineEndChange); } } void CCNotePad::setLangsDescLable(QString &langDesc) { m_langDescLabel->setText(tr("Language: %1").arg(langDesc)); } //重新加载文件。这里有个问题,文件的序号会跳动,要解决跳动问题。 //这里不能销毁当前pedit,加载编码也要保持不变。而且加载的文件一定是普通文本模式 //目前只在文本文件被修改后,外部自动加载的场景 //如果isTailfOn == true, 则从startReadSize开始读取文件,不从头读取。startReadSize=-1则还是从头,否则从startReadSize开始 void CCNotePad::reloadEditFile(ScintillaEditView* pEdit, bool isTailfOn, qint64 startReadSize) { QString filePath = pEdit->property(Edit_View_FilePath).toString(); CODE_ID code = (CODE_ID)getCodeTypeProperty(pEdit); RC_LINE_FORM lineEnd; int lineNum = 0; if (!isTailfOn) { lineNum = pEdit->getCurrentLineNumber(); } //下面这个clear会触发文本修改,要避免不必要的消息循环。先屏蔽一些信号 disEnableEditTextChangeSign(pEdit); if (isTailfOn && startReadSize != -1) { //如果是tail模式,则不要直接把文档清空 } else { pEdit->clear(); } pEdit->setProperty(Edit_Text_Change, QVariant(false)); setSaveButtonStatus(false); int errCode = 0; if (isTailfOn && startReadSize != -1) { //使用tailf读取尾部一部分数据;而不是全部读取 errCode = FileManager::getInstance().loadFileDataInTextFromOffset(pEdit, filePath, code, this, startReadSize); } else { errCode = FileManager::getInstance().loadFileDataInText(pEdit, filePath, code, lineEnd, nullptr, false, this); } enableEditTextChangeSign(pEdit); if (6 == errCode) { //可能存在乱码,给出警告。还是以编辑模式打开 ui.statusBar->showMessage(tr("File %1 open success. But Exist Garbled code !")); } else if (errCode != 0) { ui.statusBar->showMessage(tr("reload file %1 failed").arg(filePath)); return; } if (isTailfOn) { lineNum = pEdit->lines(); } pEdit->execute(SCI_GOTOLINE, lineNum - 1); } #ifdef Q_OS_WIN void CCNotePad::on_roladFile(ScintillaEditView* pEdit,quint64 lastSize, qint64 curSize) { pEdit->setProperty(Modify_Outside, QVariant(true)); checkRoladFile(pEdit, lastSize); } #endif void CCNotePad::doReloadTxtFile(ScintillaEditView* pEdit, bool isOnTail, qint64 startReadSize) { //reloadEditFile 里面会关闭和新增tab,触发一系列的currentChanged disconnect(ui.editTabWidget, &QTabWidget::currentChanged, this, &CCNotePad::slot_tabCurrentChanged); reloadEditFile(pEdit, isOnTail, startReadSize); pEdit->setProperty(Modify_Outside, QVariant(false)); connect(ui.editTabWidget, &QTabWidget::currentChanged, this, &CCNotePad::slot_tabCurrentChanged, Qt::UniqueConnection); }; //初次进入文件tailf模式。把文件清空,而且只留100行文件 void CCNotePad::firstTimeIntoTail(ScintillaEditView* pEdit, int remainLineNums) { int lineCount = pEdit->lines(); int startLineNum = 0; if (lineCount >= remainLineNums) { startLineNum = lineCount - remainLineNums; } int pos = pEdit->execute(SCI_POSITIONFROMLINE, startLineNum); disEnableEditTextChangeSign(pEdit); pEdit->clear(); enableEditTextChangeSign(pEdit); doReloadTxtFile(pEdit, true, pos); } //startReadSize == -1 则从头开始读取。否则从startReadSize开始 bool CCNotePad::checkRoladFile(ScintillaEditView* pEdit, qint64 startReadSize) { if (pEdit != nullptr && pEdit->property(Modify_Outside).toBool()) { //防止该函数重入,导致时序错误 if (m_isInReloadFile) { return false; } m_isInReloadFile = true; int tailStatus = getFileTailProperty(pEdit); if (tailStatus != 1) { QApplication::beep(); } //如果是开启了taif,则不提示,直接重新加载文件 if (tailStatus == 1) { //如果是进入tailf模式,但是startReadSize == -1.则什么也不干。 //等监控超时后,后续走tailf差异读取模式。 if (startReadSize == -1) { //这里什么也不做。坐等超时后,走下面的逻辑 } else { //如果文件大于3000行,则删除内容,只保留当前100行,继续tailf if (pEdit->lines() < 3000) { doReloadTxtFile(pEdit, true, startReadSize); } else { firstTimeIntoTail(pEdit,100); } } } else { QString filePath = pEdit->property(Edit_View_FilePath).toString(); int ret = QMessageBox::question(this, tr("Reload"), tr("\"%1\" This file has been modified by another program. Do you want to reload it?").arg(filePath), tr("Yes[Reload]"), tr("No[Drop]"), tr("On Tailf")); if(ret == 0) { doReloadTxtFile(pEdit, false, startReadSize); } else if (ret == 1) { //放弃 pEdit->setProperty(Modify_Outside, QVariant(false)); } else if (ret == 2) { m_tailf->setChecked(true); //这里也是首次开启tailf //读取最后3000行的内容。进入tailf模式 firstTimeIntoTail(pEdit,3000); //开启监控 tailfile(true,pEdit); } } m_isInReloadFile = false; return true; } return false; } //这个函数是在paint中调用,所以不要直连,否则调用QMessagebox后崩溃 void CCNotePad::slot_LineNumIndexChange(int line, int index) { ScintillaEditView* pEdit = dynamic_cast<ScintillaEditView*>(sender()); if (pEdit == nullptr) { return; } QString lineNums; int type = getDocTypeProperty(pEdit); switch (type) { case TXT_TYPE: //文本文件可能被修改。 checkRoladFile(pEdit); lineNums = tr("Ln: %1 Col: %2").arg(line + 1).arg(index); break; case BIG_TEXT_RO_TYPE: //大文本分块加载,只读格式 { quint32 bLineStart = pEdit->getBigTextBlockStartLine(); lineNums = tr("Ln: %1 Col: %2").arg(bLineStart + line + 1).arg(index); } break; case BIG_EDIT_RW_TYPE: break;//暂时没有 case SUPER_BIG_TEXT_RO_TYPE: case HEX_TYPE: //这两种是没有行号的,只有列号 lineNums = tr("Ln: %1 Col: %2").arg("unknown").arg(index); break; default: break; } m_lineNumLabel->setText(lineNums); } //打开监控文件修改的信号 void CCNotePad::enableEditTextChangeSign(ScintillaEditView* pEdit) { connect(pEdit, &ScintillaEditView::textChanged,this, &CCNotePad::slot_editViewMofidyChange); } //关闭监控文件修改的信号。这样是为了高效,一旦文字修改后,后续不需要在监控该信号。 //直到保存后,再放开 void CCNotePad::disEnableEditTextChangeSign(ScintillaEditView* pEdit) { //pEdit->disconnect(SIGNAL(textChanged())); disconnect(pEdit, &ScintillaEditView::textChanged, this, &CCNotePad::slot_editViewMofidyChange); } //编辑框文本变化后,设置对应的变化状态 void CCNotePad::slot_editViewMofidyChange() { ScintillaEditView* pEditView = dynamic_cast<ScintillaEditView*>(sender()); if (pEditView != nullptr) { //如果是未设置脏状态,则设置脏为true QVariant v = pEditView->property(Edit_Text_Change); bool isDirty = v.toBool(); if (!isDirty) { v.setValue(true); pEditView->setProperty(Edit_Text_Change,v); } //一旦变化后,设置tab为红色 int index = ui.editTabWidget->indexOf(pEditView); if (index != -1) { ui.editTabWidget->setTabIcon(index, QIcon(TabNeedSave)); } //设置状态栏也是红色 /*m_saveFile->setIcon(QIcon(NeedSaveBarIcon)); m_saveAllFile->setIcon(QIcon(NeedSaveAllBarIcon));*/ m_saveFile->setEnabled(true); m_saveAllFile->setEnabled(true); //断开监控。只有保存后再打开 disEnableEditTextChangeSign(pEditView); } } //更新当前文件的保存状态 void CCNotePad::updateCurTabSaveStatus() { QWidget* pw = ui.editTabWidget->currentWidget(); if (pw != nullptr) { if (pw->property(Edit_Text_Change).toBool()) { m_saveFile->setEnabled(true); } else { m_saveFile->setEnabled(false); } } } //只设置保存按钮的状态 void CCNotePad::setSaveButtonStatus(bool needSave) { m_saveFile->setEnabled(needSave); } void CCNotePad::setSaveAllButtonStatus(bool needSave) { m_saveAllFile->setEnabled(needSave); /*if (needSave) { m_saveAllFile->setIcon(QIcon(NeedSaveAllBarIcon)); } else { m_saveAllFile->setIcon(QIcon(NoNeedSaveAllBarIcon)); }*/ } QAction* findItemInMenuByName(QMenu* menu, QString name) { return menu->findChild<QAction*>(name); } void CCNotePad::dealRecentFileMenuWhenColseFile(QString closeFilePath) { //无条件加载一次,避免没有初始化 on_loadReceneFile(); QAction* act = nullptr; getRegularFilePath(closeFilePath); //如果关闭的文件,已经在最近列表中,则移动到最前面即可 int index = m_receneOpenFileList.indexOf(closeFilePath); if (-1 != index) { QString filePath = m_receneOpenFileList.takeAt(index); act = findItemInMenuByName(ui.menuRecene_File, filePath); if (act != nullptr) { ui.menuRecene_File->removeAction(act); } } else { act = new QAction(closeFilePath, ui.menuRecene_File); act->setObjectName(closeFilePath); connect(act, &QAction::triggered, this, &CCNotePad::slot_openReceneFile); } //在菜单最近列表上面添加。如果最近列表是空的,则放在退出菜单之上 if (m_receneOpenFileList.isEmpty()) { ui.menuRecene_File->insertAction(nullptr, act); } else { //放在列表最上面 QString curTopActionPath = m_receneOpenFileList.first(); QAction* topAct = findItemInMenuByName(ui.menuRecene_File, curTopActionPath); ui.menuRecene_File->insertAction(topAct, act); } m_receneOpenFileList.push_front(closeFilePath); //不能无限制变大,及时删除一部分 if (m_receneOpenFileList.size() > 15) { QString k = m_receneOpenFileList.takeLast(); QAction* lastAct = findItemInMenuByName(ui.menuRecene_File, k); if (lastAct != nullptr) { ui.menuRecene_File->removeAction(lastAct); lastAct->deleteLater(); } } } //isInQuit::是否在主程序退出状态 void CCNotePad::tabClose(int index, bool isInQuit) { QWidget* pw = ui.editTabWidget->widget(index); QString filePath = pw->property(Edit_View_FilePath).toString(); //16进制的处理逻辑 int type = getDocTypeProperty(pw); if (HEX_TYPE == type) { ui.editTabWidget->removeTab(index); pw->deleteLater(); FileManager::getInstance().closeHexFileHand(filePath); //关闭文件后,打开一个新的页面 if (!isInQuit) { initTabNewOne(); } delFileListView(filePath); return; } else if (BIG_TEXT_RO_TYPE == type) { ui.editTabWidget->removeTab(index); pw->deleteLater(); FileManager::getInstance().closeBigTextRoFileHand(filePath); if (!isInQuit) { initTabNewOne(); } delFileListView(filePath); return; } else if (SUPER_BIG_TEXT_RO_TYPE == type) { ui.editTabWidget->removeTab(index); pw->deleteLater(); FileManager::getInstance().closeSuperBigTextFileHand(filePath); if (!isInQuit) { initTabNewOne(); } delFileListView(filePath); return; } //关闭之前,检查是否要保存。如果文档为脏,则询问是否要保存 ScintillaEditView* pEdit = dynamic_cast<ScintillaEditView*>(pw); //关闭之前先检测是否在tailf模式,否则要回收tailf线程,不然可能崩溃 #ifdef Q_OS_WIN if (pEdit != nullptr) { pEdit->deleteTailFileThread(); } #endif if ((pEdit != nullptr) && (pEdit->property(Edit_Text_Change).toBool())) { QApplication::beep(); QMessageBox askSave(QMessageBox::Question, tr("Do you want to save changes to before closing?"), \ tr("If you don't save the changes you made in file %1, you'll lose them forever.").arg(filePath), \ QMessageBox::Yes | QMessageBox::No | QMessageBox::Cancel, this); QPushButton* okButton = (QPushButton *) askSave.button(QMessageBox::Yes); okButton->setText(tr("&Yes")); okButton = (QPushButton*)askSave.button(QMessageBox::No); okButton->setText(tr("&No")); okButton = (QPushButton*)askSave.button(QMessageBox::Cancel); okButton->setText(tr("&Cancel")); int ret = askSave.exec(); //保存 if (ret == QMessageBox::Yes) { saveTabEdit(index); //如果还是取消,即没有保存,则不能关闭 if (pEdit->property(Edit_Text_Change).toBool()) { return; } } else if (ret == QMessageBox::Cancel) { m_isQuitCancel = true; return; } } ui.editTabWidget->removeTab(index); QVariant v = pw->property(Edit_File_New); int newFileIndex = v.toInt(); if (newFileIndex >= 0) { //如果是新建文件,则删除对应的记录 FileManager::getInstance().delNewFileNode(newFileIndex); } //如果关闭的是没有保存的新建文件,则不需要保存在最近打开列表中。新建文件需要保存 if (-1 == pEdit->property(Edit_File_New).toInt()) { dealRecentFileMenuWhenColseFile(filePath); } //取消监控文件 removeWatchFilePath(filePath); pw->deleteLater(); //删除交换文件 QString swapfile = getSwapFilePath(filePath); if (QFile::exists(swapfile)) { QFile::remove(swapfile); } //当前关闭后,更新下tab的是否全部需要关闭状态 updateSaveAllToolBarStatus(); updateCurTabSaveStatus(); delFileListView(filePath); if (!isInQuit) { initTabNewOne(); } } //点击tab上的关闭事件执行槽函数。注意这个index是其在tab中的序号。 //当中间有删除时,是会动态变化的。所以不能以这个id为一直的固定索引 void CCNotePad::slot_tabClose(int index) { tabClose(index); } void CCNotePad::tabClose(QWidget* pEdit) { for (int i = 0; i < ui.editTabWidget->count(); ++i) { if (pEdit == ui.editTabWidget->widget(i)) { tabClose(i); break; } } } //输入参数:名称和文件新建文件序号。一定是文本文件。contentPath:从这个路径加载文件内容,目前在恢复文件中使用。 ScintillaEditView* CCNotePad::newTxtFile(QString name, int index, QString contentPath) { ScintillaEditView* pEdit = FileManager::getInstance().newEmptyDocument(); pEdit->setNoteWidget(this); CODE_ID code(UTF8_NOBOM); #ifdef _WIN32 RC_LINE_FORM lineEnd(DOS_LINE); #else RC_LINE_FORM lineEnd(UNIX_LINE); #endif bool isChange = false; //如果非空,则从contentPath中加载文件内容。做恢复文件使用 if (!contentPath.isEmpty()) { int ret = FileManager::getInstance().loadFileDataInText(pEdit, contentPath, code, lineEnd, nullptr, false, this); if (6 == ret) { //可能存在乱码,给出警告。还是以编辑模式打开 ui.statusBar->showMessage(tr("File %1 open success. But Exist Garbled code !")); } else if (ret != 0) { ui.statusBar->showMessage(tr("Restore Last Temp File %1 Failed").arg(contentPath)); } isChange = true; } connect(pEdit, &ScintillaEditView::cursorPositionChanged, this, &CCNotePad::slot_LineNumIndexChange, Qt::QueuedConnection); connect(pEdit, &ScintillaEditView::copyAvailable, this, &CCNotePad::slot_copyAvailable); connect(pEdit, SIGNAL(SCN_ZOOM()), this, SLOT(slot_zoomValueChange())); enableEditTextChangeSign(pEdit); QString label = name; disconnect(ui.editTabWidget, &QTabWidget::currentChanged, this, &CCNotePad::slot_tabCurrentChanged); int curIndex = ui.editTabWidget->addTab(pEdit, QIcon((StyleSet::getCurrentSytleId() != DEEP_BLACK)? TabNoNeedSave:TabNoNeedSaveDark32), label); QVariant editViewFilePath(label); pEdit->setProperty(Edit_View_FilePath, editViewFilePath); ui.editTabWidget->setTabToolTip(curIndex, label); setFileOpenAttrProperty(pEdit, OpenAttr::Text); setWindowTitleMode(label, OpenAttr::Text); QVariant editViewNewFile(index); pEdit->setProperty(Edit_File_New, editViewNewFile); QVariant editTextChange(isChange); pEdit->setProperty(Edit_Text_Change, editTextChange); QVariant editTextCode((int)code); pEdit->setProperty(Edit_Text_Code, editTextCode); syncCurDocEncodeToMenu(pEdit); syncCurDocTailfToMenu(pEdit); setDocTypeProperty(pEdit, TXT_TYPE); #ifdef _WIN32 QVariant editTextEnd((int)lineEnd); pEdit->setProperty(Edit_Text_End, editTextEnd); setLineEndBarLabel(DOS_LINE); #else QVariant editTextEnd((int)lineEnd); pEdit->setProperty(Edit_Text_End, editTextEnd); setLineEndBarLabel(UNIX_LINE); #endif syncCurDocLineEndStatusToMenu(pEdit); NewFileIdMgr fileId(index, pEdit); FileManager::getInstance().insertNewFileNode(fileId); ui.editTabWidget->setCurrentIndex(curIndex); connect(ui.editTabWidget, &QTabWidget::currentChanged, this, &CCNotePad::slot_tabCurrentChanged, Qt::UniqueConnection); //设置自动转换和缩进参考线 if (s_autoWarp != QsciScintilla::WrapNone) { pEdit->setWrapMode(QsciScintilla::WrapCharacter); } setEditShowBlankStatus(pEdit, s_showblank); if (s_zoomValue != 0) { pEdit->zoomTo(s_zoomValue); } autoSetDocLexer(pEdit); int zoomValue = 100 + 10 * s_zoomValue; ui.statusBar->showMessage(tr("New File Finished [Text Mode] Zoom %1%").arg(zoomValue), MSG_EXIST_TIME); setZoomLabelValue(zoomValue); //缩进线要在autoSetDocLexer之后,发现lexer会修改缩进参考线 if (s_indent == 1) { pEdit->setIndentGuide(true); } addFileListView(name, pEdit); pEdit->viewport()->setFocus(); return pEdit; } void CCNotePad::slot_actionNewFile_toggle(bool /*checked*/) { int index = FileManager::getInstance().getNextNewFileId(); int nameId = index; QString name; while (true) { name = QString("New %1").arg(nameId); //检测一下是否重名New 文件,如果存在,则重新命名。注意id肯定是唯一的,但是名称其实可以重复 if (!isNewFileNameExist(name)) { break; } ++nameId; } newTxtFile(name,index); } //适当做剪裁 QString CCNotePad::getShortName(const QString& name) { if (name.size() > 20) { return QString("%1...").arg(name.left(16)); } return name; } //重新加载文件以指定的编码方式。单纯的修改编码,不视作文件做了修改。 bool CCNotePad::reloadTextFileWithCode(CODE_ID code) { QWidget* pw = ui.editTabWidget->currentWidget(); //16进制的处理逻辑 int docType = getDocTypeProperty(pw); if (HEX_TYPE == docType) { ui.statusBar->showMessage(tr("Only Text File Can Use it, Current Doc is a Hex File !"), 10000); QApplication::beep(); return false; } ScintillaEditView* pEdit = dynamic_cast<ScintillaEditView*>(pw); //新建文件不需要重新打开文件,只修改编码显示 if (-1 == getFileNewIndexProperty(pw)) { QString filePath = pw->property(Edit_View_FilePath).toString(); RC_LINE_FORM lineEnd; disEnableEditTextChangeSign(pEdit); pEdit->clear(); if (docType == TXT_TYPE) { int errCode = FileManager::getInstance().loadFileDataInText(pEdit, filePath, code, lineEnd, this, false,this); if (errCode == 6) { //有乱码 } else if (errCode != 0) { delete pEdit; return false; } } else if (BIG_TEXT_RO_TYPE == docType) { //大文本索引加载模式,不需要再读取文本。只需要进行编码的转换即可 BigTextEditFileMgr* fileMgr = FileManager::getInstance().getBigFileEditMgr(filePath); if (fileMgr != nullptr) { fileMgr->loadWithCode = code; showBigTextFile(pEdit, fileMgr, fileMgr->m_curBlockIndex); } else { return false; } } else if (SUPER_BIG_TEXT_RO_TYPE == docType) { TextFileMgr* fileMgr = FileManager::getInstance().getSuperBigFileMgr(filePath); if (fileMgr != nullptr) { fileMgr->loadWithCode = code; showBigTextFile(pEdit, fileMgr); //如果切换了编码,可能乱码,把当前的行号缓存清空一下,因为旧行号已经没有意义了。 pEdit->clearSuperBitLineCache(); pEdit->showBigTextLineAddr(fileMgr->fileOffset - fileMgr->contentRealSize, fileMgr->fileOffset); } else { return false; } } if (pEdit->lexer() == nullptr) { autoSetDocLexer(pEdit); } enableEditTextChangeSign(pEdit); } setCodeBarLabel(code); QVariant editTextCode((int)code); pEdit->setProperty(Edit_Text_Code, editTextCode); return true; } const int MAX_TEXT_FILE_SIZE = 100 * 1024 * 1024; //大文本打开只读模式。20230126新增,这种模式打开时建立索引;todo:后续可多线程在后台建立索引 bool CCNotePad::openBigTextRoFile(QString filePath) { QFileInfo fi(filePath); QString fileLabel(fi.fileName()); //如果4M一个分块,则1024则是4G文件,2048则是8G文件。目前暂时最大支持8G的文件,进行文本编辑。 BigTextEditFileMgr* txtFile = nullptr; RC_LINE_FORM lineEnd(UNKNOWN_LINE); if (!FileManager::getInstance().loadFileDataWithIndex(filePath, txtFile)) { return false; } ScintillaEditView* pEdit = FileManager::getInstance().newEmptyDocument(true); pEdit->setReadOnly(true); pEdit->setNoteWidget(this); //必须要在editTabWidget->addTab之前,因为一旦add时会出发tabchange,其中没有doctype会导致错误 pEdit->execute(SCI_SETSCROLLWIDTH, 80 * 10); setDocTypeProperty(pEdit, BIG_TEXT_RO_TYPE); showBigTextFile(pEdit, txtFile,0); lineEnd = (RC_LINE_FORM)txtFile->lineEndType; disconnect(ui.editTabWidget, &QTabWidget::currentChanged, this, &CCNotePad::slot_tabCurrentChanged); int curIndex = ui.editTabWidget->addTab(pEdit, QIcon((StyleSet::getCurrentSytleId() != DEEP_BLACK) ? TabNoNeedSave : TabNoNeedSaveDark32), getShortName(fileLabel)); ui.editTabWidget->setCurrentIndex(curIndex); connect(ui.editTabWidget, &QTabWidget::currentChanged, this, &CCNotePad::slot_tabCurrentChanged, Qt::UniqueConnection); connect(pEdit, &ScintillaEditView::cursorPositionChanged, this, &CCNotePad::slot_LineNumIndexChange, Qt::QueuedConnection); autoSetDocLexer(pEdit); //pEdit->showBigEidTextLineNum(txtFile); QVariant editViewFilePath(filePath); pEdit->setProperty(Edit_View_FilePath, editViewFilePath); //setWindowTitle(QString("%1 (%2)").arg(filePath).arg(tr("Big Text File ReadOnly"))); ui.editTabWidget->setTabToolTip(curIndex, filePath); QVariant editViewNewFile(-1); pEdit->setProperty(Edit_File_New, editViewNewFile); QVariant editTextChange(false); pEdit->setProperty(Edit_Text_Change, editTextChange); setCodeTypeProperty(pEdit, txtFile->loadWithCode); setCodeBarLabel((CODE_ID)txtFile->loadWithCode); setLineEndBarLabel(lineEnd); setEndTypeProperty(pEdit, lineEnd); setDocEolMode(pEdit, lineEnd); syncCurDocEncodeToMenu(pEdit); syncCurDocTailfToMenu(pEdit); setFileOpenAttrProperty(pEdit, OpenAttr::BigTextReadOnly); setWindowTitleMode(filePath, OpenAttr::BigTextReadOnly); //设置自动转换和缩进参考线 if (s_autoWarp != QsciScintilla::WrapNone) { pEdit->setWrapMode(QsciScintilla::WrapCharacter); } setEditShowBlankStatus(pEdit, s_showblank); if (s_indent == 1) { pEdit->setIndentGuide(true); } if (s_zoomValue != 0) { pEdit->zoomTo(s_zoomValue); } addFileListView(filePath, pEdit); return true; } //按照超大文本文件进行只读打开 bool CCNotePad::openSuperBigTextFile(QString filePath) { QFileInfo fi(filePath); QString fileLabel(fi.fileName()); TextFileMgr* txtFile = nullptr; RC_LINE_FORM lineEnd(UNKNOWN_LINE); if (!FileManager::getInstance().loadFileData(filePath, txtFile, lineEnd)) { return false; } ScintillaEditView* pEdit = FileManager::getInstance().newEmptyDocument(true); pEdit->setReadOnly(true); pEdit->setNoteWidget(this); //必须要在editTabWidget->addTab之前,因为一旦add时会出发tabchange,其中没有doctype会导致错误 pEdit->execute(SCI_SETSCROLLWIDTH, 80 * 10); setDocTypeProperty(pEdit, SUPER_BIG_TEXT_RO_TYPE); showBigTextFile(pEdit, txtFile); lineEnd = (RC_LINE_FORM)txtFile->lineEndType; disconnect(ui.editTabWidget, &QTabWidget::currentChanged, this, &CCNotePad::slot_tabCurrentChanged); int curIndex = ui.editTabWidget->addTab(pEdit, QIcon((StyleSet::getCurrentSytleId() != DEEP_BLACK) ? TabNoNeedSave : TabNoNeedSaveDark32), getShortName(fileLabel)); ui.editTabWidget->setCurrentIndex(curIndex); connect(ui.editTabWidget, &QTabWidget::currentChanged, this, &CCNotePad::slot_tabCurrentChanged, Qt::UniqueConnection); connect(pEdit, &ScintillaEditView::cursorPositionChanged, this, &CCNotePad::slot_LineNumIndexChange, Qt::QueuedConnection); autoSetDocLexer(pEdit); pEdit->showBigTextLineAddr(txtFile->fileOffset - txtFile->contentRealSize, txtFile->fileOffset); QVariant editViewFilePath(filePath); pEdit->setProperty(Edit_View_FilePath, editViewFilePath); //setWindowTitle(QString("%1 (%2)").arg(filePath).arg(tr("Big Text File ReadOnly"))); ui.editTabWidget->setTabToolTip(curIndex, filePath); QVariant editViewNewFile(-1); pEdit->setProperty(Edit_File_New, editViewNewFile); QVariant editTextChange(false); pEdit->setProperty(Edit_Text_Change, editTextChange); setCodeTypeProperty(pEdit, txtFile->loadWithCode); setCodeBarLabel((CODE_ID)txtFile->loadWithCode); setLineEndBarLabel(lineEnd); setEndTypeProperty(pEdit, lineEnd); setDocEolMode(pEdit, lineEnd); syncCurDocEncodeToMenu(pEdit); syncCurDocTailfToMenu(pEdit); setFileOpenAttrProperty(pEdit, OpenAttr::SuperBigTextReadOnly); setWindowTitleMode(filePath, OpenAttr::SuperBigTextReadOnly); //设置自动转换和缩进参考线 if (s_autoWarp != QsciScintilla::WrapNone) { pEdit->setWrapMode(QsciScintilla::WrapCharacter); } setEditShowBlankStatus(pEdit, s_showblank); if (s_indent == 1) { pEdit->setIndentGuide(true); } if (s_zoomValue != 0) { pEdit->zoomTo(s_zoomValue); } addFileListView(filePath, pEdit); return true; } void CCNotePad::showChangePageTips(QWidget* pEdit) { int type = getDocTypeProperty(pEdit); if ((BIG_TEXT_RO_TYPE == type) || (SUPER_BIG_TEXT_RO_TYPE == type) || (HEX_TYPE == type)) { ui.statusBar->showMessage(tr("Use < (Prev) or > (Next) and Goto Buttons to Change Page Num ."), 10000); } } void CCNotePad::setWindowTitleMode(QString filePath, OpenAttr attr) { QString title = QString("%1 [%2]").arg(filePath).arg(OpenAttrToString(attr)); setWindowTitle(title); } const quint64 MAX_TRY_OPEN_FILE_SIZE = 1024 * 1024 * 1024; //打开普通文本文件。 bool CCNotePad::openTextFile(QString filePath, bool isCheckHex, CODE_ID code) { getRegularFilePath(filePath); //先检测交换文件是否存在,如果存在,说明上次崩溃了,提示用户恢复 QString swapfile = getSwapFilePath(filePath); bool isNeedRestoreFile = false; QFileInfo fi(filePath); //如果文件大于设定最大值,询问是否只读文件打开 if (ScintillaEditView::s_bigTextSize <= 0 || ScintillaEditView::s_bigTextSize > 300) { ScintillaEditView::s_bigTextSize = 100; } if (fi.size() > ScintillaEditView::s_bigTextSize*1024*1024) { //文件如果小于1G,询问用户如何打开。如果大于1G,无条件分块加载 if (fi.size() < MAX_TRY_OPEN_FILE_SIZE) { BigFileMessage askMsgBox(this); askMsgBox.setTip(tr("File %1 \nFile Size %2 > %3M, How to Open it ?").arg(filePath).arg(tranFileSize(fi.size())).arg(ScintillaEditView::s_bigTextSize)); int openMode = askMsgBox.exec(); //放弃打开 if (openMode == -1) { return false; } else if (openMode == TXT_TYPE) { //正常普通文本打开,不做什么,继续往下走 } else if (openMode == BIG_TEXT_RO_TYPE) { //大文本只读打开。20230125新增,做了内部索引,适合4G-8G左右的文件。 return openBigTextRoFile(filePath); } else if (openMode == SUPER_BIG_TEXT_RO_TYPE) { //超大文本编辑模式。8G以上 return openSuperBigTextFile(filePath); } else { //二进制打开 return openHexFile(filePath); } } else { //如果小于8G,则大文本只读打开;反之则超大文本只读打开 if (fi.size() <= 8 * MAX_TRY_OPEN_FILE_SIZE) { return openBigTextRoFile(filePath); } else { return openSuperBigTextFile(filePath); } } } if (QFile::exists(swapfile)) { QFileInfo spfi(swapfile); //如果存在交换文件,而且修改时间更晚,询问用户是否需要恢复 if ((spfi.size() > 0) /*&& (spfi.lastModified() >= fi.lastModified())*/) { //无条件备份一下文件,swap/原始文件都备份。避免用户文件丢失!!! QString srcBakFile = QString("%1_bak").arg(filePath); QString swapBakFile = QString("%1_bak").arg(swapfile); QFile::copy(filePath, srcBakFile); QFile::copy(swapfile, swapBakFile); int ret = QMessageBox::question(this, tr("Recover File?"), tr("File %1 abnormally closed last time , Restore it ?").arg(filePath), tr("Restore"), tr("No")); //使用历史存档恢复文件 if (ret == 0) { isNeedRestoreFile = true; } } } ScintillaEditView* pEdit = FileManager::getInstance().newEmptyDocument(); pEdit->setNoteWidget(this); //必须要在editTabWidget->addTab之前,因为一旦add时会出发tabchange,其中没有doctype会导致错误 setDocTypeProperty(pEdit, TXT_TYPE); RC_LINE_FORM lineEnd; bool isReadOnly = false; //如果需要恢复,则加载交换文件的内容。 if (!isNeedRestoreFile) { int ret = FileManager::getInstance().loadFileDataInText(pEdit, filePath, code, lineEnd, this, isCheckHex,this); if (4 == ret) { delete pEdit; //用户同意以二进制格式打开文件 return openHexFile(filePath); } //else if (5 == ret) //{ // isReadOnly = true; // //只读模式 //} else if (6 == ret) { //可能存在乱码,给出警告。还是以编辑模式打开 ui.statusBar->showMessage(tr("File %1 open success. But Exist Garbled code !")); } else if (0 != ret) { delete pEdit; return false; } } else { //使用上次的swap文件恢复当前文件 if (0 != FileManager::getInstance().loadFileDataInText(pEdit, swapfile, code, lineEnd,this,false,this)) { ui.statusBar->showMessage(tr("File %1 Open Failed").arg(swapfile)); delete pEdit; return false; } //恢复时直接使用新内容保存到原始文件中 saveFile(filePath, pEdit, false); } //下面函数太长,进行一个重构到setNormalTextEditInitPro,后面其他地方也需要使用 setNormalTextEditInitPro(pEdit, filePath, code, lineEnd, isReadOnly,false); return true; } //初始化普通可编辑文件的基本属性 //fileLabel:label显示名称 //filePath:对应的文件路径名 //code 文件编码 //lineEnd 文件换行符 //isReadOnly 是否只读 //isModifyed 是否修改过的脏状态 void CCNotePad::setNormalTextEditInitPro(ScintillaEditView* pEdit, QString filePath, CODE_ID code, RC_LINE_FORM lineEnd, bool isReadOnly, bool isModifyed) { //防止addTab触发currentChanged信号,应发不必要的连锁反应 disconnect(ui.editTabWidget, &QTabWidget::currentChanged, this, &CCNotePad::slot_tabCurrentChanged); QFileInfo fi(filePath); QString fileLabel(fi.fileName()); int curIndex = ui.editTabWidget->addTab(pEdit, QIcon(TabNoNeedSave), getShortName(fileLabel)); ui.editTabWidget->setCurrentWidget(pEdit); connect(ui.editTabWidget, &QTabWidget::currentChanged, this, &CCNotePad::slot_tabCurrentChanged, Qt::UniqueConnection); connect(pEdit, &ScintillaEditView::cursorPositionChanged, this, &CCNotePad::slot_LineNumIndexChange, Qt::QueuedConnection); enableEditTextChangeSign(pEdit); connect(pEdit, &ScintillaEditView::copyAvailable, this, &CCNotePad::slot_copyAvailable); connect(pEdit, SIGNAL(SCN_ZOOM()), this, SLOT(slot_zoomValueChange())); //监控文件 addWatchFilePath(filePath); setCodeBarLabel(code); setLineEndBarLabel(lineEnd); //注意顺序 QVariant editTextEnd((int)lineEnd); pEdit->setProperty(Edit_Text_End, editTextEnd); setDocEolMode(pEdit, lineEnd); QVariant editViewFilePath(filePath); pEdit->setProperty(Edit_View_FilePath, editViewFilePath); ui.editTabWidget->setTabToolTip(curIndex, filePath); QVariant editViewNewFile(-1); pEdit->setProperty(Edit_File_New, editViewNewFile); setTextChangeProperty(pEdit, isModifyed); //如果是脏,还需要设置保存等按钮 m_saveFile->setEnabled(isModifyed); if (isModifyed) { m_saveAllFile->setEnabled(true); ui.editTabWidget->setTabIcon(curIndex, QIcon(TabNeedSave)); } else { ui.editTabWidget->setTabIcon(curIndex, QIcon(TabNoNeedSave)); } QVariant editTextCode((int)code); pEdit->setProperty(Edit_Text_Code, editTextCode); syncCurDocEncodeToMenu(pEdit); syncCurDocLineEndStatusToMenu(pEdit); syncCurDocLexerToMenu(pEdit); //设置自动转换和缩进参考线 if (s_autoWarp != QsciScintilla::WrapNone) { pEdit->setWrapMode(QsciScintilla::WrapCharacter); } setEditShowBlankStatus(pEdit, s_showblank); if (s_zoomValue != 0) { pEdit->zoomTo(s_zoomValue); } if (!isReadOnly) { setFileOpenAttrProperty(pEdit, OpenAttr::Text); setWindowTitleMode(filePath, OpenAttr::Text); int zoomValue = 100 + 10 * s_zoomValue; ui.statusBar->showMessage(tr("File %1 Open Finished [Text Mode] Zoom %2%").arg(filePath).arg(zoomValue), MSG_EXIST_TIME); setZoomLabelValue(zoomValue); } else { setFileOpenAttrProperty(pEdit, OpenAttr::TextReadOnly); setWindowTitleMode(filePath, OpenAttr::TextReadOnly); ui.statusBar->showMessage(tr("File %1 Open Finished [Text ReadOnly Mode] (Note: display up to 50K bytes ...)").arg(fi.fileName()), MSG_EXIST_TIME); } if (pEdit->lexer() == nullptr) { autoSetDocLexer(pEdit); } //缩进线要在autoSetDocLexer之后,发现lexer会修改缩进参考线 if (s_indent == 1) { pEdit->setIndentGuide(true); } addFileListView(filePath, pEdit); } //显示二进制文件 bool CCNotePad::showHexFile(ScintillaHexEditView* pEdit, HexFileMgr* hexFile) { //二进制.预留4倍空间,双字节+空格+字符显示就是4倍,还要前面的地址12+空格+换行2=15。预留16个 //最后一行不慢16个字符的,也要把文字显示在对齐的16个字符的尾巴上。后面加的那个16*4就是多预留1行的空间 //最后一行不足16,字符显示对齐到尾巴的16的位置上 const int BUF_SIZE = hexFile->contentRealSize * 4 + 16 * (hexFile->contentRealSize / 16 + 1) + 16*4; char* textOut = new char[BUF_SIZE]; memset(textOut, 0, BUF_SIZE); int lineMax = 0; int offset = 0; uchar* pchar = (uchar*)hexFile->contentBuf; qint64 addr = hexFile->fileOffset - hexFile->contentRealSize; ui.statusBar->showMessage(tr("Current offset is %1 , load Contens Size is %2, File Total Size is %3").arg(addr).arg(hexFile->contentRealSize).arg(hexFile->fileSize)); char* lineString = new char[17]; memset(lineString,0,17); for (int pos = 0; pos < hexFile->contentRealSize; ++pos) { if (lineMax == 0) { if (addr < 0xffffffff) { sprintf(textOut + offset, "%08llX ", addr); offset += 9; } else { sprintf(textOut + offset, "%012llX ", addr); offset += 13; } } sprintf(textOut + offset, "%02X ", *(pchar+pos)); //如果在可显示字符内 if (*(pchar + pos) >= 32 && *(pchar + pos) <= 126) { lineString[lineMax] = *(pchar + pos); } else { lineString[lineMax] = '.'; } offset += 3; lineMax++; if (lineMax == 16) { memcpy(textOut + offset, lineString,16); offset += 16; sprintf(textOut + offset, "\r\n"); offset += 2; lineMax = 0; addr += 16; memset(lineString, 0, 17); } } if (lineMax > 0) { //对于尾巴不慢16字符的,对齐一下,让文本总是显示在最后的16个空间上 for (int i = 0; i < (16 - lineMax); ++i) { sprintf(textOut + offset, "-- "); offset += 3; } memcpy(textOut + offset, lineString, lineMax); offset += lineMax; sprintf(textOut + offset, "\r\n"); } QString text(textOut); pEdit->setUtf8(false); pEdit->setText(text); delete[]lineString; delete[]textOut; return true; } //显示超大文本文件只读 bool CCNotePad::showBigTextFile(ScintillaEditView* pEdit, TextFileMgr* txtFile) { qint64 addr = txtFile->fileOffset - txtFile->contentRealSize; CODE_ID code = (CODE_ID)txtFile->loadWithCode; //不知道编码,则需要自动判断编码 if (txtFile->loadWithCode == UNKOWN) { //自动从头部或文件中判断编码 code = CmpareMode::getTextFileEncodeType((uchar *)txtFile->contentBuf, txtFile->contentRealSize, txtFile->filePath); } QString outUtf8Text; bool tranSucess = true; //UNICODE_LE格式需要单独处理 if (code == UNICODE_LE) { tranSucess = CmpareMode::tranUnicodeLeToUtf8Bytes((uchar*)txtFile->contentBuf, txtFile->contentRealSize, outUtf8Text); } else { //如果还是unknown,则没法了,默认按照Utf8解析。 if (code == UNKOWN) { code = UTF8_NOBOM; } tranSucess = Encode::tranStrToUNICODE(code, (const char*)txtFile->contentBuf, txtFile->contentRealSize, outUtf8Text); } if (txtFile->loadWithCode != code) { txtFile->loadWithCode = code; } //获取行结尾信息 if (txtFile->lineEndType == RC_LINE_FORM::UNKNOWN_LINE) { txtFile->lineEndType = getLineEndTypeFromBigText(outUtf8Text); } pEdit->setText(outUtf8Text); if (tranSucess) { ui.statusBar->showMessage(tr("Current offset is %1 , load Contens Size is %2, File Total Size is %3").arg(addr).arg(txtFile->contentRealSize).arg(txtFile->fileSize)); } else { //文件乱码 if (txtFile->contentBuf == 0) { QMessageBox::warning(this, tr("Format Error"), tr("Not a txt format file , load with big txt is garbled code!")); } else { ui.statusBar->showMessage(tr("Not a txt format file , load with big txt is garbled code!")); } } //pEdit->setUtf8Text(txtFile->contentBuf, txtFile->contentRealSize); return true; } //显示大文本文件,可编辑。, int blockIndex显示第几块。txtFile->loadWithCode 如果是UNKONW,则自动判断编码;反之以code指定的加载 bool CCNotePad::showBigTextFile(ScintillaEditView* pEdit, BigTextEditFileMgr* txtFile, int blockIndex) { if (blockIndex >= 0 && blockIndex < txtFile->blocks.size()) { BlockIndex bi = txtFile->blocks.at(blockIndex); CODE_ID code = (CODE_ID)txtFile->loadWithCode; //不知道编码,则需要自动判断编码 if (txtFile->loadWithCode == UNKOWN) { //自动从头部或文件中判断编码。如果是第0块即文件开头,才能从头部检测 code = CmpareMode::getTextFileEncodeType(txtFile->filePtr + bi.fileOffset, bi.fileSize, txtFile->filePath, (blockIndex == 0)); } QString outUtf8Text; bool tranSucess = true; //UNICODE_LE格式需要单独处理 if (code == UNICODE_LE) { tranSucess = CmpareMode::tranUnicodeLeToUtf8Bytes(txtFile->filePtr + bi.fileOffset, bi.fileSize, outUtf8Text, (blockIndex == 0)); } else { //如果还是unknown,则没法了,默认按照Utf8解析。 if (code == UNKOWN) { code = UTF8_NOBOM; } tranSucess = Encode::tranStrToUNICODE(code, (const char*)txtFile->filePtr + bi.fileOffset, bi.fileSize, outUtf8Text); } if (txtFile->loadWithCode != code) { txtFile->loadWithCode = code; } //获取行结尾信息 if (txtFile->lineEndType == RC_LINE_FORM::UNKNOWN_LINE) { txtFile->lineEndType = getLineEndTypeFromBigText(outUtf8Text); } //int ret = pEdit->setUtf8Text((char*)txtFile->filePtr + bi.fileOffset, bi.fileSize); pEdit->setText(outUtf8Text); pEdit->showBigTextRoLineNum(txtFile, blockIndex); pEdit->setBigTextBlockStartLine(bi.lineNumStart); txtFile->m_curBlockIndex = blockIndex; if (tranSucess) { ui.statusBar->showMessage(tr("Current offset is %1 , line nums is %2 - %3 load Contens Size is %4, File Total Size is %5").arg(bi.fileOffset).arg(bi.lineNumStart + 1).arg(bi.lineNumStart + bi.lineNum + 1).arg(bi.fileSize).arg(txtFile->file->size())); } else { //文件乱码 if (blockIndex == 0) { QMessageBox::warning(this, tr("Format Error"), tr("Not a txt format file , load with big txt is garbled code!")); } else { ui.statusBar->showMessage(tr("Not a txt format file , load with big txt is garbled code!")); } } return true; } BlockIndex bi = txtFile->blocks.at(txtFile->m_curBlockIndex); ui.statusBar->showMessage(tr("Current offset is %1 , line nums is %2 - %3 load Contens Size is %4, File Total Size is %5").arg(bi.fileOffset).arg(bi.lineNumStart + 1).arg(bi.lineNumStart + bi.lineNum + 1).arg(bi.fileSize).arg(txtFile->file->size())); QApplication::beep(); return false; } //打开并显示二进制文件 bool CCNotePad::openHexFile(QString filePath) { getRegularFilePath(filePath); QFileInfo fi(filePath); QString fileLabel(fi.fileName()); HexFileMgr* hexFile = nullptr; if (!FileManager::getInstance().loadFileData(filePath, hexFile)) { return false; } ScintillaHexEditView* pEdit = FileManager::getInstance().newEmptyHexDocument(); pEdit->setReadOnly(true); pEdit->setNoteWidget(this); pEdit->execute(SCI_SETSCROLLWIDTH, 80 * 10); setDocTypeProperty(pEdit, HEX_TYPE); showHexFile(pEdit,hexFile); disconnect(ui.editTabWidget, &QTabWidget::currentChanged, this, &CCNotePad::slot_tabCurrentChanged); int curIndex = ui.editTabWidget->addTab(pEdit, QIcon((StyleSet::getCurrentSytleId() != DEEP_BLACK) ? TabNoNeedSave : TabNoNeedSaveDark32), getShortName(fileLabel)); ui.editTabWidget->setCurrentIndex(curIndex); connect(ui.editTabWidget, &QTabWidget::currentChanged, this, &CCNotePad::slot_tabCurrentChanged, Qt::UniqueConnection); QVariant editViewFilePath(filePath); pEdit->setProperty(Edit_View_FilePath, editViewFilePath); //setWindowTitle(filePath); ui.editTabWidget->setTabToolTip(curIndex, filePath); QVariant editViewNewFile(-1); pEdit->setProperty(Edit_File_New, editViewNewFile); QVariant editTextChange(false); pEdit->setProperty(Edit_Text_Change, editTextChange); syncCurDocEncodeToMenu(pEdit); syncCurDocTailfToMenu(pEdit); setFileOpenAttrProperty(pEdit, OpenAttr::HexReadOnly); setWindowTitleMode(filePath, OpenAttr::HexReadOnly); ui.statusBar->showMessage(tr("File %1 Open Finished [Hex ReayOnly Mode]").arg(filePath),MSG_EXIST_TIME); addFileListView(filePath, pEdit); return true; } void CCNotePad::slot_fileListView(bool check) { if (check) { initFileListDockWin(); syncFileTabToListView(); } else { if (!m_dockFileListWin.isNull()) { m_dockFileListWin->close(); } } } void CCNotePad::addFileListView(QString file, QWidget* pw) { if (!m_dockFileListWin.isNull()) { m_fileListView->addFileItem(file, pw); } } void CCNotePad::delFileListView(QString file) { if (!m_dockFileListWin.isNull()) { m_fileListView->delFileItem(file); } } void CCNotePad::syncFileTabToListView() { if (m_dockFileListWin.isNull()) { return; } for (int i = 0; i < ui.editTabWidget->count(); ++i) { QWidget* pw = ui.editTabWidget->widget(i); QString filePath = getFilePathProperty(pw); m_fileListView->addFileItem(filePath,pw); } } void CCNotePad::fileListSetCurItem(QString filePath) { if (!m_dockFileListWin.isNull()) { m_fileListView->setCurItem(filePath); } } //双击文件列表,定位到对应的文件 void CCNotePad::slot_fileListItemDoubleClick(QListWidgetItem* item) { if (!m_dockFileListWin.isNull()) { QWidget *pWid = m_fileListView->getWidgetByFilePath(item->text()); if (pWid != nullptr) { ui.editTabWidget->setCurrentWidget(pWid); } } } //在文件列表类中使用,关闭pEdit所在的编辑器 bool CCNotePad::closeFileByEditWidget(QWidget* pEdit) { int index = ui.editTabWidget->indexOf(pEdit); if (index != -1) { slot_tabClose(index); return true; } return false; } void CCNotePad::initFileListDockWin() { //停靠窗口1 if (m_dockFileListWin.isNull()) { m_dockFileListWin = new QDockWidget(tr("File List"), this); connect(m_dockFileListWin, &QDockWidget::dockLocationChanged, this, [](Qt::DockWidgetArea area) { NddSetting::updataKeyValueFromNumSets(FILELISTPOS, area); }); connect(m_dockFileListWin, &QObject::destroyed, this, [this] { if (ui.actionFileListView->isChecked()) { ui.actionFileListView->setChecked(false); } }); m_dockFileListWin->setAttribute(Qt::WA_DeleteOnClose); m_dockFileListWin->layout()->setMargin(0); m_dockFileListWin->layout()->setSpacing(0); //暂时不提供关闭,因为关闭后需要同步菜单的check状态 m_dockFileListWin->setFeatures(QDockWidget::DockWidgetFloatable | QDockWidget::DockWidgetClosable | QDockWidget::DockWidgetMovable); m_dockFileListWin->setAllowedAreas(Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea); m_fileListView = new FileListView(m_dockFileListWin); m_fileListView->setNotepadWin(this); connect(m_fileListView, &FileListView::itemDoubleClicked, this, &CCNotePad::slot_fileListItemDoubleClick); m_dockFileListWin->setWidget(m_fileListView); int lastArea = NddSetting::getKeyValueFromNumSets(FILELISTPOS); if (lastArea == 0) { lastArea = Qt::LeftDockWidgetArea; } addDockWidget((Qt::DockWidgetArea)lastArea, m_dockFileListWin); if (!ui.actionFileListView->isChecked()) { ui.actionFileListView->setChecked(true); } } m_dockFileListWin->show(); } static QString fileSuffix(const QString& filePath) { QFileInfo fi(filePath); return fi.suffix(); } //打开之前保存的恢复文件 bool CCNotePad::tryRestoreFile(QString filePath) { getRegularFilePath(filePath); QFileInfo fi(filePath); QString fileName = fi.fileName(); QString tempDir = getGlboalTempSaveDir(); QString restoreTempFile = QString("%1\\%2").arg(tempDir).arg(fi.fileName()); QFileInfo restoreFi(restoreTempFile); //存在恢复文件,则加载打开 if (restoreFi.exists()) { ScintillaEditView* pEdit = FileManager::getInstance().newEmptyDocument(); pEdit->setNoteWidget(this); //使用上次的swap文件恢复当前文件 CODE_ID code; RC_LINE_FORM lineEnd; if (0 != FileManager::getInstance().loadFileDataInText(pEdit, restoreTempFile, code, lineEnd, nullptr,false)) { ui.statusBar->showMessage(tr("File %1 Open Failed").arg(restoreTempFile)); delete pEdit; QFile::remove(restoreTempFile); return openFile(filePath); } else { //打开成功 setNormalTextEditInitPro(pEdit, filePath, code, lineEnd, false,true); //删除临时备份文件 QFile::remove(restoreTempFile); return true; } } return openFile(filePath); } bool CCNotePad::openFile(QString filePath, int lineNum) { s_padTimes++; //如果是相对路径 getRegularFilePath(filePath); QFileInfo fi(filePath); if (!fi.exists()) { QApplication::beep(); QMessageBox::warning(this, tr("Error"), tr("file %1 not exist.").arg(filePath)); return false; } s_lastOpenDirPath = fi.absoluteDir().absolutePath(); //如果已经打开过,则直接返回到当前文档 int retIndex = findFileIsOpenAtPad(filePath); if (-1 != retIndex) { ui.editTabWidget->setCurrentIndex(retIndex); QWidget* pw = ui.editTabWidget->currentWidget(); ScintillaEditView* pEdit = dynamic_cast<ScintillaEditView*>(pw); if (pEdit != nullptr) { //必须要先获得焦点,否则无法执行行跳转 pEdit->viewport()->setFocus(); if (lineNum != -1) { pEdit->execute(SCI_GOTOLINE, lineNum - 1); } } ui.statusBar->showMessage(tr("file %1 already open at tab %2").arg(filePath).arg(retIndex),MSG_EXIST_TIME); return true; } //如果是已知的二进制文件,以二进制打开 if (DocTypeListView::isHexExt(fileSuffix(filePath))) { return openHexFile(filePath); } //非已知的后缀文件,暂时无条件以文本模式打开 int ret = openTextFile(filePath); if (ret && lineNum != -1) { QWidget* pw = ui.editTabWidget->currentWidget(); ScintillaEditView* pEdit = dynamic_cast<ScintillaEditView*>(pw); if (pEdit != nullptr) { pEdit->execute(SCI_GOTOLINE, lineNum-1); } } return ret; } void CCNotePad::slot_slectionChanged() { ScintillaEditView* pEdit = dynamic_cast<ScintillaEditView*>(sender()); if (pEdit != nullptr) { if (pEdit->hasSelectedText()) { QString selectText = pEdit->selectedText(); } } } void CCNotePad::slot_actionOpenFile_toggle(bool /*checked*/) { if (s_lastOpenDirPath.isEmpty()) { s_lastOpenDirPath = NddSetting::getKeyValueFromDelaySets(LAST_OPEN_DIR); } QFileDialog fd(this,QString(), s_lastOpenDirPath); fd.setFileMode(QFileDialog::ExistingFile); if (fd.exec() == QDialog::Accepted) //如果成功的执行 { QStringList fileNameList = fd.selectedFiles(); //返回文件列表的名称 QFileInfo fi(fileNameList[0]); openFile(fi.filePath()); } else { fd.close(); } } #if 0 #ifdef _WIN32 void hide_file(const QString& szFile) { #ifdef UNICODE std::wstring wstr = szFile.toStdWString(); ::SetFileAttributes(wstr.c_str(), FILE_ATTRIBUTE_HIDDEN); #else ::SetFileAttributes(szFile.toStdString()c_str(), FILE_ATTRIBUTE_HIDDEN); #endif // !UNICODE } #endif // _WIN32 #endif //bool isBakWrite:是否进行保护写,即先写swap文件,再写源文件。这样可以避免突然断电导致源文件被清空 //isBakWrite 是否写保护swp文件,默认true。只有新文件时不需要,因为新文件不存在覆盖写的问题 //isStatic 是否静默:不弹出对话框,在外部批量查找替换文件夹时使用,避免弹窗中断。默认false //isClearSwpFile:是否回收swp交换文件,在外部批量查找替换文件夹时使用,替换后直接删除swp文件。默认false bool CCNotePad::saveFile(QString fileName, ScintillaEditView* pEdit, bool isBakWrite, bool isStatic, bool isClearSwpFile) { QFile srcfile(fileName); //如果文件存在,说明是旧文件,检测是否能写,不能写则失败。 //反之文件不存,是保存为新文件 bool isNewFile = false; if (srcfile.exists()) { //linux也不是拥有者,可写权限就行 QFlags<QFileDevice::Permission> power = QFile::permissions(fileName); if (!power.testFlag(QFile::WriteUser)) { //文件不能写 QApplication::beep(); if (!isStatic) { QMessageBox::warning(this, tr("Error"), tr("Save File %1 failed. Can not write auth, Please save as new file").arg(fileName)); } ui.statusBar->showMessage(tr("Save File %1 failed. Can not write auth, Please save as new file").arg(fileName)); return false; } } else { isNewFile = true; } auto saveWork = [this, &pEdit,isStatic](QFile& file, QString &fileName, bool isSwapFile=false)->bool{ if (!file.open(QIODevice::ReadWrite | QIODevice::Truncate)) { QApplication::beep(); if (!isStatic) { #ifdef Q_OS_WIN //打开失败,这里一般是权限问题导致。如果是windows,在外面申请权限后继续处理 if (QFileDevice::OpenError == file.error()) { //先把当前文件的内容,保存到临时的目录中。 QString tempDir = getGlboalTempSaveDir(); QFileInfo fi(fileName); QString saveTempFile = QString("%1\\%2").arg(tempDir).arg(fi.fileName()); saveFile(saveTempFile, pEdit, false, true, false); //后面新打开的文件,再去读取该文件。 this->runAsAdmin(fileName); return false; } #endif if (isSwapFile) { //如果是交换文件写失败,询问是否继续直接写文件 return (QMessageBox::Yes == QMessageBox::question(this, tr("Error"), tr("Save Swap File %1 failed. Write the target file directly ?").arg(fileName))); } else { QMessageBox::warning(this, tr("Error"), tr("Save File %1 failed. You may not have write privileges \nPlease save as a new file!").arg(fileName)); } } return false; } QString textOut = pEdit->text(); CODE_ID dstCode = static_cast<CODE_ID>(pEdit->property(Edit_Text_Code).toInt()); //如果编码是已知如下类型,则后续保存其它行时,不修改编码格式,继续按照原编码进行保存 if (dstCode == CODE_ID::UNICODE_BE) { QTextCodec::setCodecForLocale(QTextCodec::codecForName("UTF-16BE")); } else if (dstCode == CODE_ID::UNICODE_LE) { QTextCodec::setCodecForLocale(QTextCodec::codecForName("UTF-16LE")); } else if (dstCode == CODE_ID::UTF8_BOM) { QTextCodec::setCodecForLocale(QTextCodec::codecForName("UTF-8")); //自动转换不会带UTF-8 BOM,所以自己要在前面写个BOM头。这是一个例外。需要手动写入头 //其他编码BL LE则不需要。 QByteArray codeFlag = Encode::getEncodeStartFlagByte(dstCode); if (!codeFlag.isEmpty()) { //先写入标识头 file.write(codeFlag); } } else if (dstCode == CODE_ID::GBK) { QTextCodec::setCodecForLocale(QTextCodec::codecForName("GBK")); } else if (dstCode == CODE_ID::BIG5) { QTextCodec::setCodecForLocale(QTextCodec::codecForName("BIG5-HKSCS")); } else { //对于其它非识别编码,统一转换为utf8。减去让用户选择的麻烦 QTextCodec::setCodecForLocale(QTextCodec::codecForName("UTF-8")); } if (textOut.length() > 0) { //保存时注意编码问题。这个tolocal已经带了字符BOM头了。只有UTF8_BOM不会带,其他BE LE都会带 QByteArray t = textOut.toLocal8Bit(); file.write(textOut.toLocal8Bit()); } file.close(); return true; }; //如果是新文件,第一次保存,直接保存 //或者非保护写,直接写源文件即可 if (isNewFile || !isBakWrite) { saveWork(srcfile, fileName); } else { QString swapFilePath = getSwapFilePath(fileName); QFile swapfile(swapFilePath); //老文件则先写入交换文件,避免断电后破坏文件不能恢复 //再写入原本文件 bool success = saveWork(swapfile, fileName, true); if (success) { #if 0 //不要这个了,windows下无条件删除 if (!isClearSwpFile) { hide_file(swapFilePath); } #endif success = saveWork(srcfile, fileName); if (!success) { return false; } } #ifdef _WIN32 //windows下面如果保存成功,则无条件删除swap文件,许多用户反感这个.swap文件存在 if (success) { QFile::remove(swapFilePath); } #else if (success && isClearSwpFile) { QFile::remove(swapFilePath); } #endif } return true; } //bool isBakWrite:是否进行保护写,即先写swap文件,再写源文件。这样可以避免突然断电导致源文件被清空 //外部替换后保存文件时调用的函数,主要不弹出messagebox void CCNotePad::slot_saveFile(QString fileName, ScintillaEditView* pEdit) { //写保护文件、静默安装、删除保护文件 saveFile(fileName, pEdit,true,true,true); } //保存一个新建的文件后,更新相关配置 void CCNotePad::updateProAfterSaveNewFile(int curTabIndex, QString fileName, ScintillaEditView* pEdit) { getRegularFilePath(fileName); //保存成功后,更新文件的路径和tab标签 QFileInfo fi(fileName); QString fileLabel(fi.fileName()); ui.editTabWidget->setTabText(curTabIndex, fileLabel); //删除新文件的索引 QVariant v = pEdit->property(Edit_File_New); int newFileIndex = v.toInt(); if (newFileIndex >= 0) { //如果是新建文件,则删除对于的记录 FileManager::getInstance().delNewFileNode(newFileIndex); } v.setValue(-1); pEdit->setProperty(Edit_File_New, v); //更新路径名称 QVariant fp(fileName); pEdit->setProperty(Edit_View_FilePath, fp); //setWindowTitle(fileName); setFileOpenAttrProperty(pEdit, OpenAttr::Text); setWindowTitleMode(fileName, OpenAttr::Text); ui.editTabWidget->setTabToolTip(curTabIndex, fileName); autoSetDocLexer(pEdit); addWatchFilePath(fileName); } // void CCNotePad::saveTabEdit(int tabIndex) { QWidget* pw = ui.editTabWidget->widget(tabIndex); //16进制的处理逻辑 if (HEX_TYPE == getDocTypeProperty(pw)) { ui.statusBar->showMessage(tr("Only Text File Can Use it, Current Doc is a Hex File !"), 10000); QApplication::beep(); return; } ScintillaEditView* pEdit = dynamic_cast<ScintillaEditView*>(pw); //保存成功后,开启修改监控 //如果是未设置脏状态,则设置脏为true QVariant v = pEdit->property(Edit_Text_Change); bool isDirty = v.toBool(); //不脏则不需要保存,直接跳过 if (!isDirty) { return; } if (pEdit != nullptr) { //如果是新建的文件,则弹出保存对话框,进行保存 if (pEdit->property(Edit_File_New) >= 0) { QString filter("Text files (*.txt);;XML files (*.xml);;h files (*.h);;cpp file(*.cpp);;All types(*.*)"); QString fileName = QFileDialog::getSaveFileName(this, tr("Save File"), QString(), filter); if (!fileName.isEmpty()) { //如果已经打开过,则直接返回到当前文档 int retIndex = findFileIsOpenAtPad(fileName); if (-1 != retIndex) { QMessageBox::warning(this, tr("Error"), tr("file %1 already open at tab %2, please select other file name.").arg(fileName).arg(retIndex)); return; } if (!saveFile(fileName, pEdit)) { return; } updateProAfterSaveNewFile(tabIndex, fileName, pEdit); } else { //这里点击了取消,不进行保存 return; } } else { //如果是打开的文件了,则保存 QString fileName = pEdit->property(Edit_View_FilePath).toString(); if (!fileName.isEmpty()) { //保存前取消文件的修改检测,避免自己修改触发自己 removeWatchFilePath(fileName); if (!saveFile(fileName, pEdit)) { addWatchFilePath(fileName); return; } addWatchFilePath(fileName); } } //保存成功后,开启修改监控 //如果是未设置脏状态,则设置脏为true if (isDirty) { v.setValue(false); pEdit->setProperty(Edit_Text_Change, v); } //一旦保存后,设置tab为不需要保存状态 ui.editTabWidget->setTabIcon(tabIndex, QIcon((StyleSet::getCurrentSytleId() != DEEP_BLACK) ? TabNoNeedSave : TabNoNeedSaveDark32)); //m_saveFile->setIcon(QIcon(NoNeedSaveBarIcon)); m_saveFile->setEnabled(false); updateSaveAllToolBarStatus(); //只有保存后再打开文本变化监控 enableEditTextChangeSign(pEdit); } } //保存文件的执行 void CCNotePad::slot_actionSaveFile_toggle(bool /*checked*/) { int index = ui.editTabWidget->currentIndex(); saveTabEdit(index); } //文件重命名 void CCNotePad::slot_actionRenameFile_toggle(bool checked) { QWidget* pw = ui.editTabWidget->currentWidget(); int index = ui.editTabWidget->currentIndex(); //非新建文件走改名逻辑 if (-1 == getFileNewIndexProperty(pw)) { //取消旧的文件监控 QString oldName = pw->property(Edit_View_FilePath).toString(); getRegularFilePath(oldName); QFileInfo oldfi(oldName); //如果是打开的本来就存在的文件,也弹出保存进行 QString filter("Text files (*.txt);;XML files (*.xml);;h files (*.h);;cpp file(*.cpp);;All types(*.*)"); QString fileName = QFileDialog::getSaveFileName(this, tr("Rename File As ..."), oldfi.absoluteDir().absolutePath(), filter); if (!fileName.isEmpty()) { getRegularFilePath(fileName); if (oldName == fileName) { return; } QFileInfo newfi(fileName); if (oldfi.absoluteDir().absolutePath() != newfi.absoluteDir().absolutePath()) { return; } if (QFile::rename(oldName, fileName)) { removeWatchFilePath(oldName); //保存成功后,更新文件的路径和tab标签 QFileInfo fi(fileName); QString fileLabel(fi.fileName()); ui.editTabWidget->setTabText(index, fileLabel); //更新路径名称 QVariant fp(fileName); pw->setProperty(Edit_View_FilePath, fp); ui.editTabWidget->setTabToolTip(index, fileName); addWatchFilePath(fileName); } else { QApplication::beep(); QMessageBox::warning(this, tr("Error"), tr("file %1 reanme failed!").arg(fileName)); return; } } else { //这里点击了取消,不进行操作 return; } } else { //新建文件直接走另外保存逻辑 slot_actionSaveAsFile_toggle(checked); } } //保存文件的另存为槽函数。1)先执行保存。2)用保存后的新文件路径,替换当前的路径 void CCNotePad::slot_actionSaveAsFile_toggle(bool /*checked*/) { QWidget* pw = ui.editTabWidget->currentWidget(); //16进制的处理逻辑 if (HEX_TYPE == getDocTypeProperty(pw)) { ui.statusBar->showMessage(tr("Only Text File Can Use it, Current Doc is a Hex File !"), 10000); QApplication::beep(); return; } int index = ui.editTabWidget->currentIndex(); ScintillaEditView* pEdit = dynamic_cast<ScintillaEditView*>(pw); if (pEdit != nullptr) { //如果是新建的文件,则弹出保存对话框,进行保存 if (pEdit->property(Edit_File_New) >= 0) { QString filter("Text files (*.txt);;XML files (*.xml);;h files (*.h);;cpp file(*.cpp);;All types(*.*)"); QString fileName = QFileDialog::getSaveFileName(this, tr("Save File As ..."),QString(), filter); if (!fileName.isEmpty()) { getRegularFilePath(fileName); //如果已经打开过,则直接返回到当前文档 int retIndex = findFileIsOpenAtPad(fileName); if (-1 != retIndex) { QMessageBox::warning(this, tr("Error"), tr("file %1 already open at tab %2, please select other file name.").arg(fileName).arg(retIndex)); return; } if (!saveFile(fileName, pEdit)) { return; } updateProAfterSaveNewFile(index, fileName, pEdit); addWatchFilePath(fileName); } else { //这里点击了取消,不进行保存 return; } } else { //取消旧的文件监控 removeWatchFilePath(pEdit->property(Edit_View_FilePath).toString()); //如果是打开的本来就存在的文件,也弹出保存进行 QString filter("Text files (*.txt);;XML files (*.xml);;h files (*.h);;cpp file(*.cpp);;All types(*.*)"); QString curFilePath = getFilePathProperty(pEdit); QString fileName = QFileDialog::getSaveFileName(this, tr("Save File As ..."), curFilePath, filter); if (!fileName.isEmpty()) { if (!saveFile(fileName, pEdit)) { return; } //保存成功后,更新文件的路径和tab标签 QFileInfo fi(fileName); QString fileLabel(fi.fileName()); ui.editTabWidget->setTabText(index, fileLabel); //更新路径名称 QVariant fp(fileName); pEdit->setProperty(Edit_View_FilePath, fp); ui.editTabWidget->setTabToolTip(index, fileName); addWatchFilePath(fileName); setWindowTitleMode(fileName, OpenAttr::Text); } else { //这里点击了取消,不进行保存 return; } } //保存成功后,开启修改监控 //如果是未设置脏状态,则设置脏为true QVariant v = pEdit->property(Edit_Text_Change); bool isDirty = v.toBool(); if (isDirty) { v.setValue(false); pEdit->setProperty(Edit_Text_Change, v); } //保持完毕后,设置tab为蓝色,显示为不需要保持状态 ui.editTabWidget->setTabIcon(index, QIcon((StyleSet::getCurrentSytleId() != DEEP_BLACK) ? TabNoNeedSave : TabNoNeedSaveDark32)); //m_saveFile->setIcon(QIcon(NoNeedSaveBarIcon)); m_saveFile->setEnabled(false); updateSaveAllToolBarStatus(); //只有保存后再打开文本变化监控 enableEditTextChangeSign(pEdit); //updateTitleToCurDocFilePath(); } } //关闭当前文件 void CCNotePad::slot_actionClose(bool) { int index = ui.editTabWidget->currentIndex(); if (index >= 0) { slot_tabClose(index); } } //关闭非当前文档 void CCNotePad::slot_actionCloseNonCurDoc() { int index = ui.editTabWidget->currentIndex(); for (int i = ui.editTabWidget->count()-1; i >=0; --i) { if (i != index) { slot_tabClose(i); } } } void CCNotePad::slot_actionCloseLeftAll() { int index = ui.editTabWidget->currentIndex(); for (int i = index - 1; i >= 0; --i) { slot_tabClose(i); } } void CCNotePad::slot_actionCloseRightAll() { int index = ui.editTabWidget->currentIndex(); for (int i = ui.editTabWidget->count() - 1; i > index; --i) { slot_tabClose(i); } } //不管如何关闭,最终显示一个new1的新建在最上面 void CCNotePad::initTabNewOne() { if (0 == ui.editTabWidget->count()) { slot_actionNewFile_toggle(true); m_saveFile->setEnabled(false); m_saveAllFile->setEnabled(false); } } //退出所有。暂时不要了,默认alt+f4. void CCNotePad::slot_quit(bool) { close(); } void CCNotePad::slot_saveAllFile() { int index = ui.editTabWidget->currentIndex(); if (index == -1) { return; } //从尾部开始依次调用保存所有文件。没修改的不需要保存 for (int i = ui.editTabWidget->count()-1; i >= 0; --i) { saveTabEdit(i); } //最后恢复之前的current ui.editTabWidget->setCurrentIndex(index); } //定时自动保存 void CCNotePad::slot_autoSaveFile(bool status) { if (m_timerAutoSave == nullptr) { m_timerAutoSave = new QTimer(this); connect(m_timerAutoSave, &QTimer::timeout, this, &CCNotePad::slot_timerAutoSave); slot_timerAutoSave(); } if (status) { if (!m_timerAutoSave->isActive()) { //3分钟自动保存一次 m_timerAutoSave->start(1000 * 60 * 3); ui.statusBar->showMessage(tr("Cycle autosave on ..."),5000); } } else { if (m_timerAutoSave->isActive()) { m_timerAutoSave->stop(); ui.statusBar->showMessage(tr("Cycle autosave off ..."), 5000); } } } //定时器周期触发的自动保存 void CCNotePad::slot_timerAutoSave() { int curTabIndex = ui.editTabWidget->currentIndex(); for (int i = ui.editTabWidget->count() - 1; i >= 0; --i) { QWidget* pw = ui.editTabWidget->widget(i); //如果是未修改,不执行保存 if (!getTextChangeProperty(pw)) { continue; } //16进制文件不执行保存 if (HEX_TYPE == getDocTypeProperty(pw)) { continue; } //新建文件不需要保存 if (getFileNewIndexProperty(pw) >= 0) { continue; } ScintillaEditView* pEdit = dynamic_cast<ScintillaEditView*>(pw); if (pEdit != nullptr) { //如果是打开的文件了,则保存 QString fileName = getFilePathProperty(pw); if (!fileName.isEmpty()) { //保存前取消文件的修改检测,避免自己修改触发自己 removeWatchFilePath(fileName); if (!saveFile(fileName, pEdit)) { continue; } addWatchFilePath(fileName); } } //如果是未设置脏状态,则设置脏为false setTextChangeProperty(pw, false); if (curTabIndex == i) { m_saveFile->setEnabled(false); ui.statusBar->showMessage(tr("The current document has been automatically saved"), 5000); } //只有保存后再打开文本变化监控 enableEditTextChangeSign(pEdit); } } //保存文件为临时文件。一定是文本格式,可读写的。只在关闭时才需要调用该函数。 //凡是存在临时文件的,一定是脏文件,即关闭时没有保存的文件。 //而不存在临时文件,只有一个记录在list中的文件,表示不脏的文件,直接打开原始文件即可。 //1:非脏新建文件 2 非脏的已存在文件 3 脏的新建文件 4 脏的老文件。 //5和3一样,但是多了一个语法设置保存。 //20230119 对于1非脏的新建文件,不再保存。 void CCNotePad::saveTempFile(ScintillaEditView* pEdit,int index, QSettings& qs) { //16进制的处理逻辑 if (TXT_TYPE != getDocTypeProperty(pEdit)) { return; } QVariant v = pEdit->property(Edit_Text_Change); bool isDirty = v.toBool(); //不脏则不需要保存,直接跳过。不脏的文件,只记录1个名称,下次打开时恢复 if (!isDirty) { QString fileName = pEdit->property(Edit_View_FilePath).toString(); //把文件记录到qs中去 //index一定不能重复。n表示新建 //如果是新建的文件 if (pEdit->property(Edit_File_New) >= 0) { //不再保存新建的非脏文件。因为一定是空的,意义不大 //qs.setValue(QString("%1").arg(index), QString("%1|1").arg(fileName)); } else { qs.setValue(QString("%1").arg(index), QString("%1|2").arg(fileName)); //非新建文件,清空交换文件 QString swapfile = getSwapFilePath(fileName); if (QFile::exists(swapfile)) { QFile::remove(swapfile); } } return; } //如果是新建的文件 if (pEdit->property(Edit_File_New) >= 0) { QString qsSavePath = qs.fileName(); QFileInfo fi(qsSavePath); QString saveDir = fi.dir().absolutePath(); QString tempFileName = QString("%1/%2").arg(saveDir).arg(index); if (!saveFile(tempFileName, pEdit,false,true)) { return; } else { QString fileName = pEdit->property(Edit_View_FilePath).toString(); //把文件记录到qs中去 //index一定不能重复。2表示新建 int lexId = L_TXT; if (pEdit->lexer() != nullptr) { lexId = pEdit->lexer()->lexerId(); if (lexId > L_TXT) { lexId = L_TXT; } } if (lexId == L_TXT) { qs.setValue(QString("%1").arg(index), QString("%1|3").arg(fileName)); } else { qs.setValue(QString("%1").arg(index), QString("%1|%2|5").arg(fileName).arg(lexId)); } } } else { //如果是打开的文件了,则保存。脏的已经存在文件 QString fileName = pEdit->property(Edit_View_FilePath).toString(); if (!fileName.isEmpty()) { //保存前取消文件的修改检测,避免自己修改触发自己 removeWatchFilePath(fileName); QString qsSavePath = qs.fileName(); QFileInfo fi(qsSavePath); QString saveDir = fi.dir().absolutePath(); QString tempFileName = QString("%1/%2").arg(saveDir).arg(index); if (saveFile(tempFileName, pEdit, false, true)) { //把文件记录到qs中去 //index一定不能重复。2表示存在 qs.setValue(QString("%1").arg(index), QString("%1|4").arg(fileName)); } //要注意清空一下交换文件。因为这里的文件其实已经保存完毕了,直接把交换文件删除。 //否则下次恢复时,会检测到存在交换文件,会提示用户。 QString swapfile = getSwapFilePath(fileName); if (QFile::exists(swapfile)) { QFile::remove(swapfile); } } } } void CCNotePad::closeFileStatic(int index, QSettings& qs) { QWidget* pw = ui.editTabWidget->widget(index); QString filePath = pw->property(Edit_View_FilePath).toString(); //16进制的处理逻辑 int type = getDocTypeProperty(pw); if (HEX_TYPE == type) { ui.editTabWidget->removeTab(index); pw->deleteLater(); FileManager::getInstance().closeHexFileHand(filePath); return; } else if (BIG_TEXT_RO_TYPE == type) { ui.editTabWidget->removeTab(index); pw->deleteLater(); FileManager::getInstance().closeBigTextRoFileHand(filePath); return; } else if (SUPER_BIG_TEXT_RO_TYPE == type) { ui.editTabWidget->removeTab(index); pw->deleteLater(); FileManager::getInstance().closeSuperBigTextFileHand(filePath); return; } //关闭之前,检查是否要保存。如果文档为脏,则静默保存为temp文件 ScintillaEditView* pEdit = dynamic_cast<ScintillaEditView*>(pw); if ((pEdit != nullptr)) { saveTempFile(pEdit,index,qs); } ui.editTabWidget->removeTab(index); QVariant v = pw->property(Edit_File_New); int newFileIndex = v.toInt(); if (newFileIndex >= 0) { //如果是新建文件,则删除对应的记录 FileManager::getInstance().delNewFileNode(newFileIndex); } //这里是在退出程序的过程中,不需要更新最近打开文件菜单列表 //取消监控文件 removeWatchFilePath(filePath); pw->deleteLater(); } void CCNotePad::closeAllFileStatic() { QString tempFileList = QString("notepad/temp/list"); QSettings qs(QSettings::IniFormat, QSettings::UserScope, tempFileList); qs.setIniCodec("UTF-8"); QString qsSavePath = qs.fileName(); QFileInfo fi(qsSavePath); QDir saveDir = fi.dir(); //检查文件夹temp是否存在,不然就创建。发现第一次时,没有该文件夹,文件保存时失败。 if (!saveDir.exists()) { saveDir.mkdir(saveDir.absolutePath()); } qs.clear(); int curIndexWhenQuit = ui.editTabWidget->currentIndex(); NddSetting::updataKeyValueFromNumSets(LAST_ACTION_TAB_INDEX, curIndexWhenQuit); //这里是静默退出,反正要退出了,把槽函数取消一下,避免下面setCurrentIndex再触发做无用功 disconnect(ui.editTabWidget, &QTabWidget::currentChanged, this, &CCNotePad::slot_tabCurrentChanged); //从尾部开始依次调用保存所有文件。没修改的不需要保存 for (int i = ui.editTabWidget->count() - 1; i >= 0; --i) { ui.editTabWidget->setCurrentIndex(i); closeFileStatic(i,qs); } } //退出时关闭所有文件 void CCNotePad::closeAllFileWhenQuit(bool isQuit) { m_isQuitCancel = false; //从尾部开始依次调用保存所有文件。没修改的不需要保存 for (int i = ui.editTabWidget->count() - 1; i >= 0; --i) { ui.editTabWidget->setCurrentIndex(i); tabClose(i, isQuit); if (m_isQuitCancel) { break; } } } //关闭所有文件的槽函数 void CCNotePad::slot_closeAllFile(bool) { closeAllFileWhenQuit(false); } void CCNotePad::closeEvent(QCloseEvent * event) { if (!m_pFindWin.isNull()) { QByteArray curGeo = m_pFindWin->saveGeometry(); NddSetting::updataKeyByteArrayValue(FINDWINSIZE, curGeo); m_pFindWin.data()->close(); } if (!m_pHexGotoWin.isNull()) { m_pHexGotoWin.data()->close(); } if (!m_columnEditWin.isNull()) { m_columnEditWin.data()->close(); } //关闭的时候,filelistwin还存在 if (!m_dockFileListWin.isNull()) { NddSetting::updataKeyValueFromNumSets(FILELISTSHOW, 1); m_dockFileListWin.data()->close(); } else { NddSetting::updataKeyValueFromNumSets(FILELISTSHOW, 0); } #ifdef Q_OS_WIN if ((s_restoreLastFile==1) && m_isMainWindows && !s_isAdminAuth) { //走静默安装的函数。对于没有保存的文件,一律保存为临时文件 //主窗口才需要保存。非主的还是提示 closeAllFileStatic(); m_isQuitCancel = false; } else { closeAllFileWhenQuit(true); } #else if ((s_restoreLastFile == 1) && m_isMainWindows) { closeAllFileStatic(); m_isQuitCancel = false; } else { closeAllFileWhenQuit(true); } #endif if (m_isQuitCancel) { m_isQuitCancel = false; event->ignore(); return; } s_padInstances->removeOne(this); //把hwnd切换到当前还在的notepad,否则右键打开失效。因为窗口隐藏了 //退位让贤给当前还在的窗口 if (!s_padInstances->isEmpty()) { CCNotePad* c = s_padInstances->first(); //主窗口还在,没有删除,不用切换 //管理员窗口任何时候不做住窗口 #ifdef Q_OS_WIN if (c->m_isMainWindows || s_isAdminAuth) #else if (c->m_isMainWindows) #endif { //主窗口还在,则当前窗口直接退出。但是把主窗口呼出来一下 if (c->isHidden() || c->isMinimized()) { c->showNormal(); } event->accept(); return; } else { //把接位的窗口设置为主窗口,显示出来。隐藏的窗口时没有winid的,避免该错误。 if (c->isHidden() || c->isMinimized()) { c->showNormal(); } qlonglong winId = (qlonglong)c->effectiveWinId(); m_shareMem->lock(); memcpy(m_shareMem->data(), &winId, sizeof(qlonglong)); m_shareMem->unlock(); c->m_isMainWindows = true; } } //保存上次打开目录 if (!CCNotePad::s_lastOpenDirPath.isEmpty()) { NddSetting::updataKeyValueFromDelaySets(LAST_OPEN_DIR, CCNotePad::s_lastOpenDirPath); } //保存大小 QByteArray curGeo = saveGeometry(); NddSetting::updataKeyByteArrayValue(WIN_POS, curGeo); event->accept(); } void CCNotePad::updateSaveAllToolBarStatus() { bool isNeedSaveAll = false; //从尾部开始依次调用保存所有文件。没修改的不需要保存 for (int i = ui.editTabWidget->count() - 1; i >= 0; --i) { QWidget *pw = ui.editTabWidget->widget(i); if (pw->property(Edit_Text_Change).toBool()) { isNeedSaveAll = true; break; } } setSaveAllButtonStatus(isNeedSaveAll); } void CCNotePad::slot_copyAvailable(bool select) { if (m_cutFile != nullptr && m_copyFile != nullptr) { m_cutFile->setEnabled(select); m_copyFile->setEnabled(select); } } void CCNotePad::slot_cut() { QWidget* pw = ui.editTabWidget->currentWidget(); ScintillaEditView* pEdit = dynamic_cast<ScintillaEditView*>(pw); if (pEdit != nullptr) { pEdit->cut(); } } void CCNotePad::slot_copy() { QWidget* pw = ui.editTabWidget->currentWidget(); ScintillaEditView* pEdit = dynamic_cast<ScintillaEditView*>(pw); if (pEdit != nullptr) { pEdit->copy(); } } void CCNotePad::slot_paste() { QWidget* pw = ui.editTabWidget->currentWidget(); ScintillaEditView* pEdit = dynamic_cast<ScintillaEditView*>(pw); if (pEdit != nullptr) { pEdit->paste(); } } void CCNotePad::slot_selectAll() { QWidget* pw = ui.editTabWidget->currentWidget(); ScintillaEditView* pEdit = dynamic_cast<ScintillaEditView*>(pw); if (pEdit != nullptr) { pEdit->execute(SCI_SELECTALL); } } void CCNotePad::slot_undo() { QWidget* pw = ui.editTabWidget->currentWidget(); ScintillaEditView* pEdit = dynamic_cast<ScintillaEditView*>(pw); if (pEdit != nullptr) { pEdit->undo(); } } void CCNotePad::slot_redo() { QWidget* pw = ui.editTabWidget->currentWidget(); ScintillaEditView* pEdit = dynamic_cast<ScintillaEditView*>(pw); if (pEdit != nullptr) { pEdit->redo(); } } void CCNotePad::slot_zoomin() { ++s_zoomValue; if (s_zoomValue < -10) s_zoomValue = -10; else if (s_zoomValue > 20) s_zoomValue = 20; zoomto(s_zoomValue); } //ctrl+鼠标放大缩小zoom,由pedit发送的消息 //任何一个编辑框修改,其余的编辑框也需要同步修改 void CCNotePad::slot_zoomValueChange() { ScintillaEditView* pSrcEdit = dynamic_cast<ScintillaEditView*>(sender()); if (pSrcEdit != nullptr) { pSrcEdit->updateLineNumberWidth(); int curZoomValue = pSrcEdit->execute(SCI_GETZOOM); if (s_zoomValue != curZoomValue) { s_zoomValue = curZoomValue; NddSetting::updataKeyValueFromNumSets(ZOOMVALUE, s_zoomValue); int zoomValue = 100 + 10 * curZoomValue; ui.statusBar->showMessage(tr("Current Zoom Value is %1%").arg(zoomValue)); setZoomLabelValue(zoomValue); } //修改其余的pedit for (int i = ui.editTabWidget->count() - 1; i >= 0; --i) { QWidget* pw = ui.editTabWidget->widget(i); ScintillaEditView* pEdit = dynamic_cast<ScintillaEditView*>(pw); if ((pEdit != nullptr) && (pEdit != pSrcEdit)) { //zoomTo 会触发SCN_ZOOM,而zoomTo会触发slot_zoomValueChange,避免循环触发 disconnect(pEdit, SIGNAL(SCN_ZOOM()), this, SLOT(slot_zoomValueChange())); pEdit->zoomTo(s_zoomValue); pEdit->updateLineNumberWidth(); connect(pEdit, SIGNAL(SCN_ZOOM()), this, SLOT(slot_zoomValueChange())); } } } } void CCNotePad::zoomto(int zoomValue) { NddSetting::updataKeyValueFromNumSets(ZOOMVALUE, zoomValue); int value = 100 + 10 * zoomValue; ui.statusBar->showMessage(tr("Current Zoom Value is %1%").arg(value)); setZoomLabelValue(value); for (int i = ui.editTabWidget->count() - 1; i >= 0; --i) { QWidget* pw = ui.editTabWidget->widget(i); ScintillaEditView* pEdit = dynamic_cast<ScintillaEditView*>(pw); if (pEdit != nullptr) { //zoomTo 会触发SCN_ZOOM,而zoomTo会触发slot_zoomValueChange,避免循环触发 disconnect(pEdit, SIGNAL(SCN_ZOOM()), this, SLOT(slot_zoomValueChange())); pEdit->zoomTo(zoomValue); pEdit->updateLineNumberWidth(); connect(pEdit, SIGNAL(SCN_ZOOM()), this, SLOT(slot_zoomValueChange())); } } } void CCNotePad::slot_zoomout() { --s_zoomValue; if (s_zoomValue < -10) s_zoomValue = -10; else if (s_zoomValue > 20) s_zoomValue = 20; zoomto(s_zoomValue); } //只切换了当前文档。换行大批量切换,可能会非常耗时,所以不全部换行。在文档切换的时候,需要检查下当前文档的自动换行状态。 void CCNotePad::slot_wordwrap(bool checked) { QWidget* pw = ui.editTabWidget->currentWidget(); ScintillaEditView* pEdit = dynamic_cast<ScintillaEditView*>(pw); if (pEdit != nullptr) { if (checked) { pEdit->setWrapMode(QsciScintilla::WrapCharacter); } else { pEdit->setWrapMode(QsciScintilla::WrapNone); } } s_autoWarp = (checked) ? QsciScintilla::WrapCharacter : QsciScintilla::WrapNone; NddSetting::updataKeyValueFromNumSets(AUTOWARP_KEY, s_autoWarp); //同步两个按钮的状态 if (ui.actionWrap->isChecked() != checked) { ui.actionWrap->setChecked(checked); } if (m_wordwrap != nullptr && m_wordwrap->isChecked() != checked) { m_wordwrap->setChecked(checked); } } void CCNotePad::syncBlankShowStatus() { //检查3个地方按钮的状态。这里务必注意,action使用trigged信号,setcheck修改不会触发该信号。避免循环 //同样道理,button使用click信号,也是避免setcheck触发click信号,避免信号循环处理。 ui.actionShowSpaces->setChecked((0 != (s_showblank & 0x1))); ui.actionshow_end_of_line->setChecked((0 != (s_showblank & 0x2))); ui.actionShowAll->setChecked((3 == s_showblank)); m_allWhite->setChecked((3 == s_showblank)); } //这里是对所有文档进行了空白的开启等。后续如果发现有效率问题,要学自动换行那样,可以只修当前文档;其余文档在切换是更新 void CCNotePad::changeBlankShowStatus(int showBlank) { //对比判断防止循环触发,这个是有必要的。 if (s_showblank == showBlank) { return; } //0 全部不开启。1开始空白 2 开启行尾 3 全部开启 s_showblank = showBlank; for (int i = ui.editTabWidget->count() - 1; i >= 0; --i) { QWidget* pw = ui.editTabWidget->widget(i); ScintillaEditView* pEdit = dynamic_cast<ScintillaEditView*>(pw); if (pEdit != nullptr) { setEditShowBlankStatus(pEdit, s_showblank); } } NddSetting::updataKeyValueFromNumSets(SHOWSPACE_KEY, s_showblank); syncBlankShowStatus(); } //有2个函数,都触发该函数。一个是ui.actionShowAll,一个是按钮m_allWhite。 //状态以ui.actionShowAll为主。m_allWhite为辅助同步按钮状态。避免二者的信号互相干扰。 void CCNotePad::slot_allWhite(bool checked) { //0 全部不开启。1开始空白 2 开启行尾 3 全部开启 changeBlankShowStatus((checked ? 3 : 0)); } //只控制空格和TAB,不控制行尾 void CCNotePad::slot_show_spaces(bool checked) { int showblank = s_showblank; if (checked) { showblank |= 0x1; } else { showblank &= 0xe; } changeBlankShowStatus(showblank); } //全部都会生效,和自动换行不一样,会全部设置 void CCNotePad::slot_indentGuide(bool willBeShowed) { for (int i = ui.editTabWidget->count() - 1; i >= 0; --i) { QWidget* pw = ui.editTabWidget->widget(i); //文本的处理逻辑 if (TXT_TYPE == getDocTypeProperty(pw)) { //关闭之前,检查是否要保存。如果文档为脏,则询问是否要保存 ScintillaEditView* pEdit = dynamic_cast<ScintillaEditView*>(pw); pEdit->setIndentGuide(willBeShowed); } } s_indent = (willBeShowed) ? 1 : 0; NddSetting::updataKeyValueFromNumSets(INDENT_KEY, s_indent); } #ifdef Q_OS_WIN TCHAR* CharToWchar(const QString& str) { QByteArray ba = str.toUtf8(); char* data = ba.data(); //以上两步不能直接简化为“char *data = str.toUtf8().data();” int charLen = strlen(data); int len = MultiByteToWideChar(CP_ACP, 0, data, charLen, NULL, 0); TCHAR* buf = new TCHAR[len + 1]; MultiByteToWideChar(CP_ACP, 0, data, charLen, buf, len); buf[len] = '\0'; return buf; } #endif void CCNotePad::tailfile(bool isOn, ScintillaEditView* pEdit) { if (pEdit == nullptr || (TXT_TYPE != getDocTypeProperty(pEdit) || (-1 != getFileNewIndexProperty(pEdit)))) { m_tailf->setChecked(false); ui.statusBar->showMessage(tr("Only Text File Can Use it !"), MSG_EXIST_TIME); return; } if (isOn) { if (1 == getFileTailProperty(pEdit)) { return; } pEdit->setReadOnly(true); setFileTailProperty(pEdit, 1); ui.statusBar->showMessage(tr("File %1 into tailf mode, readonly !").arg(getFilePathProperty(pEdit)), MSG_EXIST_TIME); #ifdef Q_OS_WIN auto checkFileChange = [this](ScintillaEditView* pEdit) { QString filePath = getFilePathProperty(pEdit); TCHAR* fullFileName = CharToWchar(filePath); DectFileChanges fileChanges; fileChanges.AddFile(fullFileName, FILE_NOTIFY_CHANGE_LAST_WRITE | FILE_NOTIFY_CHANGE_SIZE); //单独开启一个线程,去监控文件大小的变化 HANDLE eventHandle = ::CreateEvent(nullptr, TRUE, FALSE, nullptr); HANDLE changeHandles[] = { eventHandle }; bool toBeGoon = true; while (toBeGoon) { DWORD waitStatus = ::WaitForMultipleObjects(_countof(changeHandles), changeHandles, FALSE, 1000); switch (waitStatus) { case WAIT_OBJECT_0 + 0: // User removes this folder or file browser is closed { toBeGoon = false; } break; case WAIT_TIMEOUT: { if (fileChanges.DetectChanges()) { //这里不能直接更新,而是要发生信号出去。否则跨线程访问,可能发生错误或告警 //pEdit->setProperty(Modify_Outside, QVariant(true)); //checkRoladFile(pEdit); quint64 lastSize = 0; quint64 curSize = 0; fileChanges.getDiffFileSize(lastSize,curSize); emit this->tailFileChange(pEdit, lastSize, curSize); } //如果退出监控。这里要注意,一定要是volidate的,否则多线程获取不到该变化 //使用了原子变量,效果是一样的,多个线程均可见 if (!(pEdit->m_isInTailStatus)) { toBeGoon = false; } } break; case WAIT_IO_COMPLETION: // Nothing to do. break; } } qDebug() << "listen file quit ..."; fileChanges.Terminate(); }; connect(this, &CCNotePad::tailFileChange, this, &CCNotePad::on_roladFile, Qt::QueuedConnection); pEdit->m_isInTailStatus = true; std::thread* pListenThread = new std::thread(checkFileChange, pEdit); QVariant t((qlonglong)pListenThread); pEdit->setProperty(Tail_Thread, t); #endif // Q_OS_WIN } else { #ifdef Q_OS_WIN if (!pEdit->m_isInTailStatus) { return; } #endif setFileTailProperty(pEdit, 0); #ifdef Q_OS_WIN pEdit->deleteTailFileThread(); #endif pEdit->setReadOnly(false); #ifdef Q_OS_WIN disconnect(this, &CCNotePad::tailFileChange, this, &CCNotePad::on_roladFile); #endif } } //实时开启文件变化tailf。20230218发现一个问题。 //文件没有关闭,只是flush时,无法实时刷新。所有要在windows上单独监控文件大小改变 void CCNotePad::on_tailfile(bool isOn) { QWidget* pw = ui.editTabWidget->currentWidget(); ScintillaEditView* pEdit = dynamic_cast<ScintillaEditView*>(pw); tailfile(isOn, pEdit); } void CCNotePad::find(FindTabIndex findType) { initFindWindow(findType); FindWin* pFind = dynamic_cast<FindWin*>(m_pFindWin.data()); #ifdef uos pFind->activateWindow(); #endif pFind->showNormal(); #ifdef uos adjustWInPos(pFind); #endif pFind->setFocus(); pFind->setCurrentTab(findType); } void CCNotePad::slot_findInDir() { find(DIR_FIND_TAB); } void CCNotePad::slot_find() { initFindWindow(FIND_TAB); FindWin* pFind = dynamic_cast<FindWin*>(m_pFindWin.data()); //必须要激活一下,所谓激活就是让当前这个查找窗口,获取焦点,是所有窗口中的当前活动窗口 pFind->activateWindow(); pFind->showNormal(); #ifdef uos adjustWInPos(pFind); #endif } //在后台查找关键字 int CCNotePad::findAtBack(QStringList& keyword) { initFindWindow(); FindWin* pFind = dynamic_cast<FindWin*>(m_pFindWin.data()); return pFind->findAtBack(keyword); } //在后台替换关键字 //在后台批量替换关键字 int CCNotePad::replaceAtBack(QStringList& keyword, QStringList& replace) { initFindWindow(); FindWin* pFind = dynamic_cast<FindWin*>(m_pFindWin.data()); return pFind->replaceAtBack(keyword, replace); } //在后台高亮关键字 int CCNotePad::markAtBack(QStringList& keyword) { initFindWindow(); FindWin* pFind = dynamic_cast<FindWin*>(m_pFindWin.data()); return pFind->markAtBack(keyword); } //返回值:0 正常 1 选择自动为空 int CCNotePad::initFindWindow(FindTabIndex type) { int ret = 0; FindWin* pFind = nullptr; QWidget* pw = ui.editTabWidget->currentWidget(); int docType = getDocTypeProperty(pw); if (m_pFindWin.isNull()) { m_pFindWin = new FindWin(this); connect(m_pFindWin,&QObject::destroyed,this,&CCNotePad::slot_saveSearchHistory); QByteArray lastGeo = NddSetting::getKeyByteArrayValue(FINDWINSIZE); if (!lastGeo.isEmpty()) { m_pFindWin->restoreGeometry(lastGeo); } pFind = dynamic_cast<FindWin*>(m_pFindWin.data()); if (s_findHistroy.isEmpty()) { //从历史查找记录文件中加载 QString searchHistory = QString("notepad/searchHistory");//历史查找记录 QSettings qs(QSettings::IniFormat, QSettings::UserScope, searchHistory); qs.setIniCodec("UTF-8"); if (qs.contains("keys")) { QVariant history = qs.value("keys", ""); s_findHistroy = history.toStringList(); } if (qs.contains("replace")) { QVariant replaceHistory = qs.value("replace", ""); s_replaceHistroy = replaceHistory.toStringList(); } } pFind->setFindHistory(&s_findHistroy); pFind->setReplaceHistory(&s_replaceHistroy); pFind->setTabWidget(ui.editTabWidget); if((TXT_TYPE == docType) || (BIG_TEXT_RO_TYPE == docType) || (SUPER_BIG_TEXT_RO_TYPE == docType)) { //connect(pFind, &FindWin::sign_findAllInCurDoc, this, &CCNotePad::slot_showFindAllInCurDocResult); connect(pFind, &FindWin::sign_findAllInOpenDoc, this, &CCNotePad::slot_showfindAllInOpenDocResult); connect(pFind, &FindWin::sign_replaceSaveFile, this, &CCNotePad::slot_saveFile); connect(pFind, &FindWin::sign_clearResult, this, &CCNotePad::slot_clearFindResult); } else { //二进制DOC只读,不许替换编辑。不在这里做,会导致编辑框回调。在FindWin里面去判断 //pFind->disableReplace(); } //注册一个ESC的退出按钮事件 //设置查找的快捷键 QShortcut *escSc = new QShortcut(m_pFindWin); escSc->setKey(QKeySequence(Qt::Key_Escape)); escSc->setContext(Qt::WidgetWithChildrenShortcut); connect(escSc, &QShortcut::activated, this, [this]() {m_pFindWin->close(); }); } else { pFind = dynamic_cast<FindWin*>(m_pFindWin.data()); } pFind->setCurrentTab(type); if ((TXT_TYPE == docType) || (BIG_TEXT_RO_TYPE == docType) || (SUPER_BIG_TEXT_RO_TYPE == docType)) { ScintillaEditView* pEdit = dynamic_cast<ScintillaEditView*>(pw); if (pEdit != nullptr && pEdit->hasSelectedText()) { QString text = pEdit->selectedText(); if (FIND_TAB == type) { pFind->setFindText(text); pFind->keywordWinGetFouse(FIND_TAB); //如果字段比较短,则字段填充到替换中 if (text.size() <= 60) { pFind->setReplaceFindText(text); } } else if (REPLACE_TAB == type) { pFind->setReplaceFindText(text); pFind->keywordWinGetFouse(REPLACE_TAB); //如果字段比较短,则字段填充到替换中 if (text.size() <= 60) { pFind->setFindText(text); } } else if (DIR_FIND_TAB == type) { pFind->setDirFindText(text); pFind->keywordWinGetFouse(DIR_FIND_TAB); } else if (MARK_TAB == type) { pFind->setMarkFindText(text); pFind->keywordWinGetFouse(MARK_TAB); } } else { QString text; pFind->setFindText(text); pFind->setReplaceFindText(text); pFind->setDirFindText(text); ret = 1; } } else if (HEX_TYPE == docType) { ScintillaHexEditView* pEdit = dynamic_cast<ScintillaHexEditView*>(pw); if (pEdit != nullptr && pEdit->hasSelectedText()) { QString text = pEdit->selectedText(); pFind->setFindText(text); } else { QString text; pFind->setFindText(text); ret = 1; } } return ret; } //保存历史查找记录 void CCNotePad::slot_saveSearchHistory() { //从历史查找记录文件中加载 QString searchHistory = QString("notepad/searchHistory");//历史查找记录 QSettings qs(QSettings::IniFormat, QSettings::UserScope, searchHistory); qs.setIniCodec("UTF-8"); if (s_findHistroy.count() > 15) { s_findHistroy = s_findHistroy.mid(0, 15); } qs.setValue("keys", s_findHistroy); if (s_replaceHistroy.count() > 15) { s_replaceHistroy = s_replaceHistroy.mid(0, 15); } qs.setValue("replace", s_replaceHistroy); qs.sync(); } void CCNotePad::slot_replace() { initFindWindow(REPLACE_TAB); FindWin* pFind = dynamic_cast<FindWin*>(m_pFindWin.data()); pFind->activateWindow(); pFind->showNormal(); #ifdef uos adjustWInPos(pFind); #endif } //标记高亮 void CCNotePad::slot_markHighlight() { initFindWindow(); FindWin* pFind = dynamic_cast<FindWin*>(m_pFindWin.data()); pFind->setCurrentTab(MARK_TAB); pFind->activateWindow(); pFind->showNormal(); #ifdef uos adjustWInPos(pFind); #endif } //取消所有标记高亮 void CCNotePad::slot_clearMark() { QWidget* pw = ui.editTabWidget->currentWidget(); int docType = getDocTypeProperty(pw); if ((TXT_TYPE == docType) || (BIG_TEXT_RO_TYPE == docType) || (SUPER_BIG_TEXT_RO_TYPE == docType)) { ScintillaEditView* pEdit = dynamic_cast<ScintillaEditView*>(pw); int docEnd = pEdit->length(); for (int i = 0; i < 5; ++i) { pEdit->execute(SCI_SETINDICATORCURRENT, SCE_UNIVERSAL_FOUND_STYLE_EXT5+i); pEdit->execute(SCI_INDICATORCLEARRANGE, 0, docEnd); } pEdit->releaseAllMark(); } } void CCNotePad::clearHighlightWord(QString signWord, ScintillaEditView* pEdit) { if (pEdit == nullptr) { QWidget* pw = ui.editTabWidget->currentWidget(); pEdit = dynamic_cast<ScintillaEditView*>(pw); if (HEX_TYPE == getDocTypeProperty(pw) || (pEdit == nullptr)) { return; } } //如果当前已经高亮,则取消高亮 QList<FindRecords*>& curMarkRecord = pEdit->getCurMarkRecord(); bool isClearMark = false; int i = 0; for (; i < curMarkRecord.size(); ++i) { if (signWord == curMarkRecord.at(i)->findText) { isClearMark = true; break; } } if (isClearMark) { //取消高亮 FindRecords* r = curMarkRecord.at(i); pEdit->execute(SCI_SETINDICATORCURRENT, r->hightLightColor); for (int j = 0; j < r->records.size(); ++j) { const FindRecord& oneRecord = r->records.at(j); pEdit->execute(SCI_INDICATORCLEARRANGE, oneRecord.pos, oneRecord.end - oneRecord.pos); } //必须删除释放,否则内存泄露 delete r; curMarkRecord.removeAt(i); } } void CCNotePad::slot_clearWordHighlight() { QWidget* pw = ui.editTabWidget->currentWidget(); int docType = getDocTypeProperty(pw); QString signWord; ScintillaEditView* pEdit; int srcPostion = -1; if ((TXT_TYPE == docType) || (BIG_TEXT_RO_TYPE == docType) || (SUPER_BIG_TEXT_RO_TYPE == docType)) { pEdit = dynamic_cast<ScintillaEditView*>(pw); if (pEdit != nullptr && pEdit->hasSelectedText()) { signWord = pEdit->selectedText(); } } else if (HEX_TYPE == docType) { return; } if (signWord.isEmpty()) { //如果没有选择内容,则自动获取当前的单词,进行1个匹配。注意中文也是一样,检测到前后的空格,看做1个单词 srcPostion = pEdit->execute(SCI_GETCURRENTPOS); signWord = pEdit->wordAtPosition(srcPostion); } if (!signWord.isEmpty()) { clearHighlightWord(signWord, pEdit); } } void CCNotePad::slot_wordHighlight() { QWidget* pw = ui.editTabWidget->currentWidget(); int docType = getDocTypeProperty(pw); QString signWord; ScintillaEditView* pEdit; int srcPostion = -1; if ((TXT_TYPE == docType) || (BIG_TEXT_RO_TYPE == docType) || (SUPER_BIG_TEXT_RO_TYPE == docType)) { pEdit = dynamic_cast<ScintillaEditView*>(pw); if (pEdit != nullptr && pEdit->hasSelectedText()) { signWord = pEdit->selectedText(); } } else if (HEX_TYPE == docType) { return; } if (signWord.isEmpty()) { //如果没有选择内容,则自动获取当前的单词,进行1个匹配。注意中文也是一样,检测到前后的空格,看做1个单词 srcPostion = pEdit->execute(SCI_GETCURRENTPOS); signWord = pEdit->wordAtPosition(srcPostion); } if (!signWord.isEmpty()) { //如果当前已经高亮,则取消高亮 QList<FindRecords*>& curMarkRecord = pEdit->getCurMarkRecord(); bool isClearMark = false; int i = 0; for (; i < curMarkRecord.size(); ++i) { if (signWord == curMarkRecord.at(i)->findText) { isClearMark = true; break; } } bool isNeedReColor = false; //取消高亮 if (isClearMark) { FindRecords* r = curMarkRecord.at(i); isNeedReColor = (r->hightLightColor != CCNotePad::s_curMarkColorId); pEdit->execute(SCI_SETINDICATORCURRENT, r->hightLightColor); for (int j = 0; j < r->records.size(); ++j) { const FindRecord& oneRecord = r->records.at(j); pEdit->execute(SCI_INDICATORCLEARRANGE, oneRecord.pos, oneRecord.end - oneRecord.pos); } //必须删除释放,否则内存泄露 delete r; curMarkRecord.removeAt(i); } //如果就颜色和当前颜色不一样,则还需要重新高亮 if(!isClearMark || isNeedReColor) { //反之高亮 initFindWindow(); FindWin* pFind = dynamic_cast<FindWin*>(m_pFindWin.data()); //静默调用 pFind->markAllWord(signWord); } } } void CCNotePad::slot_findResultPosChangeed(Qt::DockWidgetArea area) { NddSetting::updataKeyValueFromNumSets(FINDRESULTPOS,area); } void CCNotePad::initFindResultDockWin() { //停靠窗口1 if (m_dockSelectTreeWin == nullptr) { m_dockSelectTreeWin = new QDockWidget(tr("Find result"), this); connect(m_dockSelectTreeWin, &QDockWidget::dockLocationChanged, this, &CCNotePad::slot_findResultPosChangeed); m_dockSelectTreeWin->layout()->setMargin(0); m_dockSelectTreeWin->layout()->setSpacing(0); //暂时不提供关闭,因为关闭后需要同步菜单的check状态 m_dockSelectTreeWin->setFeatures(QDockWidget::DockWidgetFloatable | QDockWidget::DockWidgetClosable | QDockWidget::DockWidgetMovable); m_dockSelectTreeWin->setAllowedAreas(Qt::LeftDockWidgetArea| Qt::RightDockWidgetArea |Qt::BottomDockWidgetArea); m_pResultWin = new FindResultWin(m_dockSelectTreeWin); //connect(m_pResultWin, &FindResultWin::itemDoubleClicked, this, &CCNotePad::slot_findResultItemDoubleClick); connect(m_pResultWin, &FindResultWin::lineDoubleClicked, this, &CCNotePad::on_findResultlineDoubleClick); connect(m_pResultWin, &FindResultWin::showMsg, this, [this](QString& msg) { ui.statusBar->showMessage(msg,5000); }); m_dockSelectTreeWin->setWidget(m_pResultWin); int lastArea = NddSetting::getKeyValueFromNumSets(FINDRESULTPOS); if (lastArea == 0) { lastArea = Qt::BottomDockWidgetArea; } addDockWidget((Qt::DockWidgetArea)lastArea, m_dockSelectTreeWin); } } //双击查找结果,定位到对应的地方 void CCNotePad::slot_findResultItemDoubleClick(const QModelIndex &index) { //如果点击的是父节点,父节点有ResultItemEditor,则跳转到对应的编辑框 const QModelIndex* item = &index; auto locationCurrentEdit = [this](const QModelIndex *rootItem)->ScintillaEditView* { QString filePath = rootItem->data(ResultItemEditorFilePath).toString(); getRegularFilePath(filePath); if (!rootItem->data(ResultItemEditor).isNull()) { ScintillaEditView* pEdit = reinterpret_cast<ScintillaEditView*>(rootItem->data(ResultItemEditor).toLongLong()); //这里如果是目录查找过来的,是没有pEdit的 if (pEdit == nullptr) { goto foundInDir; } //当前已经在结果窗口上 if (dynamic_cast<ScintillaEditView*>(ui.editTabWidget->currentWidget()) == pEdit) { return pEdit; } //不在则遍历插值定位到 for (int i = 0; i < ui.editTabWidget->count(); ++i) { ScintillaEditView* pe = dynamic_cast<ScintillaEditView*>(ui.editTabWidget->widget(i)); if (pEdit == pe) { ui.editTabWidget->setCurrentIndex(i); return pe; } } foundInDir: //遍历文件路径查找 //不在则遍历插值定位到 for (int i = 0; i < ui.editTabWidget->count(); ++i) { ScintillaEditView* pe = dynamic_cast<ScintillaEditView*>(ui.editTabWidget->widget(i)); if (filePath == getFilePathProperty(pe)) { ui.editTabWidget->setCurrentIndex(i); return pe; } } //还是没有找到,则新建打开文件 if (openFile(filePath)) { ScintillaEditView*pEdit = dynamic_cast<ScintillaEditView*>(ui.editTabWidget->currentWidget()); return pEdit; } } ui.statusBar->showMessage(tr("file %1 was not exists !").arg(filePath), 5000); QApplication::beep(); return nullptr; }; if (!item->data(ResultItemDesc).isNull()) { //点击的是描述行 return; } //点击的是查找的根节点 if (!item->data(ResultItemEditor).isNull()) { locationCurrentEdit(item); } else if (!item->data(ResultItemPos).isNull()) { //点击的是查找的结果项目 QModelIndex rootItem = item->parent(); ScintillaEditView* pCurEdit = locationCurrentEdit(&rootItem); if(pCurEdit != nullptr) { //int findLens = rootItem.data(ResultWhatFind).toString().length(); //发现是中文必须下面这样,不能直接取qstring长度 //int findLens = rootItem.data(ResultWhatFind).toString().toUtf8().size(); int pos = item->data(ResultItemPos).toInt(); int len = item->data(ResultItemLen).toInt(); pCurEdit->execute(SCI_SETSEL, pos, pos + len); } } } //双击文件leve=2的节点后,显示文件并定位到文件位置中去高亮 void CCNotePad::on_findResultlineDoubleClick(QString* pFilePath, int pos, int end) { auto locationCurrentEdit = [this](QString filePath)->ScintillaEditView* { getRegularFilePath(filePath); ScintillaEditView* pEdit = dynamic_cast<ScintillaEditView*>(ui.editTabWidget->currentWidget()); if (pEdit != nullptr && (filePath == getFilePathProperty(pEdit))) { return pEdit; } //不在则遍历插值定位到 for (int i = 0; i < ui.editTabWidget->count(); ++i) { pEdit = dynamic_cast<ScintillaEditView*>(ui.editTabWidget->widget(i)); if (pEdit != nullptr && (filePath == getFilePathProperty(pEdit))) { ui.editTabWidget->setCurrentIndex(i); return pEdit; } } //走到这里,说明文档已经关闭,不在当前打开框中 //还是没有找到,则新建打开文件 if (openFile(filePath)) { ScintillaEditView* pEdit = dynamic_cast<ScintillaEditView*>(ui.editTabWidget->currentWidget()); return pEdit; } ui.statusBar->showMessage(tr("file %1 was not exists !").arg(filePath), 5000); QApplication::beep(); return nullptr; }; ScintillaEditView* pCurEdit = locationCurrentEdit(*pFilePath); if (pCurEdit != nullptr) { pCurEdit->execute(SCI_SETSEL, pos, end); } } #if 0 void CCNotePad::slot_showFindAllInCurDocResult(FindRecords* record) { initFindResultDockWin(); m_dockSelectTreeWin->setWindowTitle(tr("Find result - %1 hit").arg(record->records.size())); //m_pResultWin->appendResultsToShow(record); m_dockSelectTreeWin->show(); } #endif void CCNotePad::slot_showfindAllInOpenDocResult(QVector<FindRecords*>* record, int hits, QString whatFind) { initFindResultDockWin(); m_dockSelectTreeWin->setWindowTitle(tr("Find result - %1 hit").arg(hits)); m_pResultWin->appendResultsToShow(record, hits, whatFind); m_dockSelectTreeWin->show(); } //清空查找结果 void CCNotePad::slot_clearFindResult() { initFindResultDockWin(); m_pResultWin->slot_clearAllContents(); } void CCNotePad::slot_convertWinLineEnd(bool) { convertDocLineEnd(DOS_LINE); } void CCNotePad::slot_convertUnixLineEnd(bool) { convertDocLineEnd(UNIX_LINE); } void CCNotePad::slot_convertMacLineEnd(bool) { convertDocLineEnd(MAC_LINE); } void CCNotePad::setDocEolMode(ScintillaEditView* pEdit, RC_LINE_FORM endStatus) { int eolMode = 0; switch (endStatus) { case UNIX_LINE: eolMode = SC_EOL_LF; break; case DOS_LINE: eolMode = SC_EOL_CRLF; break; case MAC_LINE: eolMode = SC_EOL_CR; break; case PAD_LINE: case UNKNOWN_LINE: default: return; } if (pEdit != nullptr) { int curCode = pEdit->execute(SCI_GETEOLMODE); if (curCode != eolMode) { pEdit->execute(SCI_SETEOLMODE, eolMode); } } } bool CCNotePad::convertDocLineEnd(RC_LINE_FORM endStatus) { QWidget* pw = ui.editTabWidget->currentWidget(); if (HEX_TYPE == getDocTypeProperty(pw)) { ui.statusBar->showMessage(tr("Only Text File Can Use it, Current Doc is a Hex File !"), 10000); QApplication::beep(); return false; } ScintillaEditView* pEdit = dynamic_cast<ScintillaEditView*>(pw); if (pEdit != nullptr && pEdit->isReadOnly()) { ui.statusBar->showMessage(tr("The ReadOnly document does not allow this operation."), MSG_EXIST_TIME); QApplication::beep(); return false; } int eolMode = 0; switch (endStatus) { case UNIX_LINE: eolMode = SC_EOL_LF; break; case DOS_LINE: eolMode = SC_EOL_CRLF; break; case MAC_LINE: eolMode = SC_EOL_CR; break; case PAD_LINE: case UNKNOWN_LINE: default: return false; } if (pEdit != nullptr) { int curCode = pEdit->execute(SCI_GETEOLMODE); if (curCode != eolMode) { ui.statusBar->showMessage(tr("Convert end of line In progress, please wait ...")); pEdit->execute(SCI_SETEOLMODE, eolMode); pEdit->execute(SCI_CONVERTEOLS, eolMode); ui.statusBar->showMessage(tr("Convert end of line finish."),5000); QVariant editTextEnd((int)endStatus); pEdit->setProperty(Edit_Text_End, editTextEnd); QVariant textChanged(true); pEdit->setProperty(Edit_Text_Change, textChanged); setLineEndBarLabel(endStatus); } } return true; } void CCNotePad::slot_gotoline() { QWidget* pw = ui.editTabWidget->currentWidget(); ScintillaEditView* pEdit = dynamic_cast<ScintillaEditView*>(pw); if (pEdit != nullptr) { int lineCounts = 2147483647; bool ok; int num = QInputDialog::getInt(this, tr("Go to line"), tr("Line Num:"), 1, 1, lineCounts, 1, &ok); if (ok) { if (TXT_TYPE == getDocTypeProperty(pw)) { pEdit->execute(SCI_GOTOLINE, num - 1); } else if (BIG_TEXT_RO_TYPE == getDocTypeProperty(pw)) { //如果是大文本只读加载的,则逻辑不一样,需要根据行号定位到块,再定位到行 int blockid = FileManager::getInstance().getBigFileBlockId(getFilePathProperty(pw), num - 1); if (blockid != -1) { BigTextEditFileMgr* mgr = FileManager::getInstance().getBigFileEditMgr(getFilePathProperty(pw)); const BlockIndex& v = mgr->blocks.at(blockid); showBigTextFile(pEdit, mgr, blockid); int offsetLineNum = (num - v.lineNumStart); pEdit->execute(SCI_SETFIRSTVISIBLELINE, (long)offsetLineNum); pEdit->execute(SCI_GOTOLINE, offsetLineNum - 1); } else { BigTextEditFileMgr* mgr = FileManager::getInstance().getBigFileEditMgr(getFilePathProperty(pw)); const BlockIndex& v = mgr->blocks.last(); QApplication::beep(); ui.statusBar->showMessage(tr("out of file line range,mar line num is %1 !").arg(v.lineNum + v.lineNumStart -1)); } } else { //超大文本不支持跳转行号,只支持跳转地址。先留着 } } } } void CCNotePad::slot_show_line_end(bool checked) { int showblank = s_showblank; if (checked) { showblank |= 0x2; } else { showblank &= 0xd; } changeBlankShowStatus(showblank); } void CCNotePad::slot_load_with_gbk() { reloadTextFileWithCode(CODE_ID::GBK); } void CCNotePad::slot_load_with_utf8() { reloadTextFileWithCode(CODE_ID::UTF8_NOBOM); } void CCNotePad::slot_load_with_utf8_bom() { reloadTextFileWithCode(CODE_ID::UTF8_BOM); } void CCNotePad::slot_load_with_utf16_be() { reloadTextFileWithCode(CODE_ID::UNICODE_BE); } void CCNotePad::slot_load_with_utf16_le() { reloadTextFileWithCode(CODE_ID::UNICODE_LE); } void CCNotePad::slot_encode_gbk() { transDocToEncord(GBK); } void CCNotePad::slot_encode_utf8() { transDocToEncord(UTF8_NOBOM); } void CCNotePad::slot_encode_utf8_bom() { transDocToEncord(UTF8_BOM); } void CCNotePad::slot_encode_utf16_be() { transDocToEncord(UNICODE_BE); } void CCNotePad::slot_encode_utf16_le() { transDocToEncord(UNICODE_LE); } //执行转换文档编码到指定编码 void CCNotePad::transDocToEncord(CODE_ID destCode) { QWidget* pw = ui.editTabWidget->currentWidget(); ScintillaEditView* pEdit = dynamic_cast<ScintillaEditView*>(pw); if (pEdit != nullptr) { int srcCode = pEdit->property(Edit_Text_Code).toInt(); int newCode = static_cast<int>(destCode); //这里只是做了编码状态的修改,并没有及时落盘,修改为已修改状态。 //等到文件保存时才执行 if (srcCode != newCode) { setCodeTypeProperty(pEdit, (int)newCode); setTextChangeProperty(pEdit, true); ui.editTabWidget->setTabIcon(ui.editTabWidget->currentIndex(), QIcon(TabNeedSave)); setSaveButtonStatus(true); setSaveAllButtonStatus(true); syncCurDocEncodeToMenu(pw); setCodeBarLabel(static_cast<CODE_ID>(newCode)); } } } //同步当前文档的编码状态到菜单的Encode中。即每次切换当前编辑后,菜单上面的编码状态要同步 void CCNotePad::syncCurDocEncodeToMenu(QWidget* curEdit) { if (curEdit != nullptr) { int srcCode = curEdit->property(Edit_Text_Code).toInt(); switch (srcCode) { case GBK: ui.actionencode_in_GBK->setChecked(true); break; case UTF8_NOBOM: ui.actionencode_in_uft8->setChecked(true); break; case UTF8_BOM: ui.actionencode_in_UTF8_BOM->setChecked(true); break; case UNICODE_BE: ui.actionencode_in_UCS_BE_BOM->setChecked(true); break; case UNICODE_LE: ui.actionencode_in_UCS_2_LE_BOM->setChecked(true); break; case BIG5: ui.actionBig5->setChecked(true); break; default: break; } } } //同步当前的tailf状态 void CCNotePad::syncCurDocTailfToMenu(QWidget* curEdit) { m_tailf->setChecked(1 == getFileTailProperty(curEdit)); } //同步当前文档的编码状态到菜单的Encode中。即每次切换当前编辑后,菜单上面的编码状态要同步 void CCNotePad::syncCurDocLineEndStatusToMenu(QWidget* curEdit) { ScintillaEditView* pEdit = dynamic_cast<ScintillaEditView*>(curEdit); if (pEdit != nullptr) { int curCode = pEdit->execute(SCI_GETEOLMODE); switch (curCode) { case SC_EOL_CRLF: ui.actionconver_windows_CR_LF->setChecked(true); break; case SC_EOL_LF: ui.actionconvert_Unix_LF->setChecked(true); break; case SC_EOL_CR: ui.actionconvert_Mac_CR->setChecked(true); break; default: break; } } } //同步当前的编程语言到menu中 void CCNotePad::syncCurDocLexerToMenu(QWidget* pw) { ScintillaEditView* pEdit = dynamic_cast<ScintillaEditView*>(pw); if (pEdit == nullptr) { return; } QsciLexer * lexer = pEdit->lexer(); if (lexer != nullptr) { QString lexerName(lexer->lexerTag()); if (m_lexerNameToIndex.contains(lexerName)) { m_lexerNameToIndex.value(lexerName).pAct->setChecked(true); } else { m_lexerNameToIndex.value("UserDefine").pAct->setChecked(true); } setLangsDescLable(lexerName); } else { ui.actionTxt->setChecked(true); } } void CCNotePad::cmpSelectFile() { //此部分是对比软件的商业代码,开源版本不包含对比功能。 } void CCNotePad::slot_compareFile() { //此部分是对比软件的商业插件代码,开源版本不包含对比功能。 } void CCNotePad::slot_compareDir() { //此部分是对比软件的商业插件代码,开源版本不包含对比功能。 } void CCNotePad::slot_binCompare() { //此部分是对比软件的商业插件代码,开源版本不包含对比功能。 } void CCNotePad::slot_preHexPage() { QWidget* pw = ui.editTabWidget->currentWidget(); if (pw != nullptr && (TXT_TYPE == getDocTypeProperty(pw))) { ScintillaEditView* pEdit = dynamic_cast<ScintillaEditView*>(pw); if (!pEdit->gotoPrePos()) { QApplication::beep(); ui.statusBar->showMessage(tr("no more pre pos")); } } else if (pw != nullptr && (HEX_TYPE == getDocTypeProperty(pw))) { QString filePath = getFilePathProperty(pw); HexFileMgr *fileMgr = nullptr; //只有0才是成功 if (0 == FileManager::getInstance().loadFilePreNextPage(1, filePath, fileMgr)) { ScintillaHexEditView* pEdit = dynamic_cast<ScintillaHexEditView*>(pw); showHexFile(pEdit, fileMgr); } else { QApplication::beep(); } } else if (pw != nullptr && (SUPER_BIG_TEXT_RO_TYPE == getDocTypeProperty(pw))) { QString filePath = getFilePathProperty(pw); TextFileMgr *fileMgr = nullptr; //只有0才是成功 if (0 == FileManager::getInstance().loadFilePreNextPage(1, filePath, fileMgr)) { ScintillaEditView* pEdit = dynamic_cast<ScintillaEditView*>(pw); showBigTextFile(pEdit, fileMgr); pEdit->showBigTextLineAddr(fileMgr->fileOffset - fileMgr->contentRealSize, fileMgr->fileOffset); } } else if (pw != nullptr && (BIG_TEXT_RO_TYPE == getDocTypeProperty(pw))) { QString filePath = getFilePathProperty(pw); BigTextEditFileMgr* fileMgr = FileManager::getInstance().getBigFileEditMgr(filePath); if(fileMgr != nullptr) { ScintillaEditView* pEdit = dynamic_cast<ScintillaEditView*>(pw); int id = fileMgr->m_curBlockIndex - 1; showBigTextFile(pEdit, fileMgr, id); } } } void CCNotePad::slot_nextHexPage() { QWidget* pw = ui.editTabWidget->currentWidget(); if (pw != nullptr && (TXT_TYPE == getDocTypeProperty(pw))) { ScintillaEditView* pEdit = dynamic_cast<ScintillaEditView*>(pw); if (!pEdit->gotoNextPos()) { QApplication::beep(); ui.statusBar->showMessage(tr("no more next pos")); } } else if (pw != nullptr && (HEX_TYPE == getDocTypeProperty(pw))) { QString filePath = getFilePathProperty(pw); HexFileMgr *fileMgr = nullptr; //只有0才是成功 int ret = FileManager::getInstance().loadFilePreNextPage(2, filePath, fileMgr); if (0 == ret) { ScintillaHexEditView* pEdit = dynamic_cast<ScintillaHexEditView*>(pw); showHexFile(pEdit, fileMgr); //ui.statusBar->showMessage(tr("Current offset is %1 , File Size is %2").arg(fileMgr->fileOffset).arg(fileMgr->fileSize)); } else if (1 == ret) { ui.statusBar->showMessage(tr("The Last Page ! Current offset is %1 , load Contens Size is %2, File Total Size is %3").arg(fileMgr->fileOffset - fileMgr->contentRealSize).arg(fileMgr->contentRealSize).arg(fileMgr->fileSize)); QApplication::beep(); } } else if (pw != nullptr && (SUPER_BIG_TEXT_RO_TYPE == getDocTypeProperty(pw))) { QString filePath = getFilePathProperty(pw); TextFileMgr *fileMgr = nullptr; //只有0才是成功 int ret = FileManager::getInstance().loadFilePreNextPage(2, filePath, fileMgr); if (0 == ret) { ScintillaEditView* pEdit = dynamic_cast<ScintillaEditView*>(pw); showBigTextFile(pEdit, fileMgr); pEdit->showBigTextLineAddr(fileMgr->fileOffset - fileMgr->contentRealSize, fileMgr->fileOffset); } else if (1 == ret) { ui.statusBar->showMessage(tr("The Last Page ! Current offset is %1 , load Contens Size is %2, File Total Size is %3").arg(fileMgr->fileOffset - fileMgr->contentRealSize).arg(fileMgr->contentRealSize).arg(fileMgr->fileSize)); QApplication::beep(); } } else if (pw != nullptr && (BIG_TEXT_RO_TYPE == getDocTypeProperty(pw))) { QString filePath = getFilePathProperty(pw); BigTextEditFileMgr* fileMgr = FileManager::getInstance().getBigFileEditMgr(filePath); if (fileMgr != nullptr) { ScintillaEditView* pEdit = dynamic_cast<ScintillaEditView*>(pw); int id = fileMgr->m_curBlockIndex + 1; showBigTextFile(pEdit, fileMgr, id); } } } //菜单上面的GOTO按钮的执行槽函数 void CCNotePad::slot_gotoHexPage() { if (m_pHexGotoWin.isNull()) { m_pHexGotoWin = new HexFileGoto(this); m_pHexGotoWin->setWindowFlag(Qt::Window); HexFileGoto* pHexGoto = dynamic_cast<HexFileGoto*>(m_pHexGotoWin.data()); pHexGoto->setAttribute(Qt::WA_DeleteOnClose); connect(pHexGoto, &HexFileGoto::gotoClick, this, &CCNotePad::slot_hexGotoFile); registerEscKeyShort(m_pHexGotoWin); } QWidget* pw = ui.editTabWidget->currentWidget(); if (pw != nullptr && (HEX_TYPE == getDocTypeProperty(pw))) { m_pHexGotoWin.data()->activateWindow(); m_pHexGotoWin.data()->show(); #ifdef uos adjustWInPos(m_pHexGotoWin.data()); #endif } else if (pw != nullptr && (SUPER_BIG_TEXT_RO_TYPE == getDocTypeProperty(pw))) { m_pHexGotoWin.data()->activateWindow(); m_pHexGotoWin.data()->show(); #ifdef uos adjustWInPos(m_pHexGotoWin.data()); #endif } else if (pw != nullptr && (BIG_TEXT_RO_TYPE == getDocTypeProperty(pw))) { //这里直接按跳转到行号进行处理 slot_gotoline(); } else { ui.statusBar->showMessage(tr("Only Hex File Can Use it, Current Doc not a Hex File !"), 10000); QApplication::beep(); } } void CCNotePad::slot_hexGotoFile(qint64 addr) { QWidget* pw = ui.editTabWidget->currentWidget(); if (pw != nullptr && (HEX_TYPE == getDocTypeProperty(pw))) { QString filePath = getFilePathProperty(pw); HexFileMgr *fileMgr = nullptr; //只有0才是成功 if (addr < 0) { ui.statusBar->showMessage(tr("Error file offset addr , please check !"), MSG_EXIST_TIME); QApplication::beep(); return; } int ret = FileManager::getInstance().loadFileFromAddr(filePath, addr, fileMgr); if (0 == ret) { ScintillaHexEditView* pEdit = dynamic_cast<ScintillaHexEditView*>(pw); showHexFile(pEdit, fileMgr); } else if (-2 == ret) { ui.statusBar->showMessage(tr("File Size is %1, addr %2 is exceeds file size").arg(fileMgr->fileSize).arg(addr)); QApplication::beep(); } } else if (pw != nullptr && (SUPER_BIG_TEXT_RO_TYPE == getDocTypeProperty(pw))) { QString filePath = getFilePathProperty(pw); TextFileMgr *fileMgr = nullptr; //只有0才是成功 if (addr < 0) { ui.statusBar->showMessage(tr("Error file offset addr , please check !"), MSG_EXIST_TIME); QApplication::beep(); return; } int ret = FileManager::getInstance().loadFileFromAddr(filePath, addr, fileMgr); if (0 == ret) { ScintillaEditView* pEdit = dynamic_cast<ScintillaEditView*>(pw); showBigTextFile(pEdit, fileMgr); pEdit->showBigTextLineAddr(fileMgr->fileOffset - fileMgr->contentRealSize, fileMgr->fileOffset); } else if (-2 == ret) { ui.statusBar->showMessage(tr("File Size is %1, addr %2 is exceeds file size").arg(fileMgr->fileSize).arg(addr)); QApplication::beep(); } } else { ui.statusBar->showMessage(tr("Current Text Doc Can Not Use it !"), 10000); QApplication::beep(); } } void CCNotePad::slot_about() { QMessageBox msgBox(this); QString msg = tr(R"( <a href="https://gitee.com/cxasm/notepad--">https://gitee.com/cxasm/notepad--</a> <br/> <a href="https://github.com/cxasm/notepad--">https://github.com/cxasm/notepad--</a> )"); #if defined (Q_OS_MAC) msgBox.setText(msg); msgBox.setDetailedText(QString("Notepad-- %1").arg(VersionStr)); #else msgBox.setWindowTitle(QString("Notepad-- %1").arg(VersionStr)); msgBox.setText(msg); #endif msgBox.exec(); } void CCNotePad::slot_aboutNdd() { AboutNdd* pWin = new AboutNdd(this); pWin->setWindowFlag(Qt::Window); pWin->setAttribute(Qt::WA_DeleteOnClose); QString title = tr("Notepad-- Version %1").arg(VersionStr); pWin->setWindowTitle(title); pWin->appendText(title); int status = NddSetting::getKeyValueFromNumSets(SOFT_STATUS); if (1 == status) { pWin->appendText(tr("Registered Version")); } else { pWin->appendText(tr("Free Trial")); } pWin->show(); registerEscKeyShort(pWin); #ifdef uos adjustWInPos(pWin); #endif } void CCNotePad::addWatchFilePath(QString filePath) { getRegularFilePath(filePath); m_fileWatch->addPath(filePath); } void CCNotePad::removeWatchFilePath(QString filePath) { getRegularFilePath(filePath); m_fileWatch->removePath(filePath); } void CCNotePad::dragEnterEvent(QDragEnterEvent* event) { if (event->mimeData()->hasFormat("text/uri-list")) //只能打开文本文件 { event->accept(); //可以在这个窗口部件上拖放对象 } else { event->ignore(); } } void CCNotePad::receiveEditDrop(QDropEvent* e) { dropEvent(e); } void CCNotePad::dropEvent(QDropEvent* e) { QList<QUrl> urls = e->mimeData()->urls(); if (urls.isEmpty()) return; for (int i = 0; i < urls.size(); ++i) { QString fileName = urls.at(i).toLocalFile(); if (fileName.isEmpty()) { continue; } if (!QFile::exists(fileName)) { continue; } QFileInfo fi(fileName); if (!fi.isFile()) { ui.statusBar->showMessage(tr("%1 is not a file, skip open it...").arg(fileName)); continue; } openFile(fileName); } e->accept(); } void CCNotePad::dragLeaveEvent(QDragLeaveEvent* event) { qDebug() << "drag level"; } //目前只有一个Tabwidget的双击事件。 bool CCNotePad::eventFilter(QObject * watched, QEvent * event) { switch (event->type()) { case QEvent::MouseButtonDblClick: if (watched == ui.editTabWidget) { slot_actionNewFile_toggle(true); m_saveFile->setEnabled(false); return true; // 注意这里一定要返回true,表示你要过滤该事件原本的实现 } break; default: break; } return QObject::eventFilter(watched, event);; } #ifdef Q_OS_WIN static const ULONG_PTR CUSTOM_TYPE = 10000; static const ULONG_PTR OPEN_NOTEPAD_TYPE = 10001; static const ULONG_PTR CUSTOM_TYPE_FILE_LINENUM = 10002; bool CCNotePad::nativeOpenfile(QString openFilePath) { int retIndex = findFileIsOpenAtPad(openFilePath); if (-1 == retIndex) { openFile(openFilePath); } else { ui.statusBar->showMessage(tr("file %1 already open at tab %2").arg(openFilePath).arg(retIndex)); ui.editTabWidget->setCurrentIndex(retIndex); } //窗口如果最小化,则在任务栏下面闪动 QApplication::alert(this); //发现在release模式下,必须要先最小再最大,窗口才能跑到最前面。而调试时则没有该现象。可能是哪里有个问题。 if (!this->isMinimized()) { this->showMinimized(); } if (this->isMaximized()) { this->showMaximized(); } else { this->showNormal(); } this->activateWindow(); return true; } bool CCNotePad::nativeEvent(const QByteArray & eventType, void * message, long * result) { MSG *param = static_cast<MSG *>(message); switch (param->message) { case WM_COPYDATA: { COPYDATASTRUCT *cds = reinterpret_cast<COPYDATASTRUCT*>(param->lParam); if (cds->dwData == CUSTOM_TYPE) { QString openFilePath = QString::fromUtf8(reinterpret_cast<char*>(cds->lpData), cds->cbData); nativeOpenfile(openFilePath); *result = 1; return true; } else if (cds->dwData == OPEN_NOTEPAD_TYPE) { activateWindow(); QApplication::alert(this); *result = 1; return true; } else if (cds->dwData == CUSTOM_TYPE_FILE_LINENUM) { QString openFilePath = QString::fromUtf8(reinterpret_cast<char*>(cds->lpData), cds->cbData); QStringList paraList = openFilePath.split("|"); if (paraList.size() == 2) { nativeOpenfile(paraList.at(0)); bool ok = true; int lineNum = paraList.at(1).toInt(&ok); if (ok) { QWidget* pw = ui.editTabWidget->currentWidget(); ScintillaEditView* pEdit = dynamic_cast<ScintillaEditView*>(pw); if (pEdit != nullptr) { pEdit->execute(SCI_GOTOLINE, lineNum - 1); } } } *result = 1; return true; } } } return QWidget::nativeEvent(eventType, message, result); } #endif void CCNotePad::slot_batch_convert() { EncodeConvert* newWin = new EncodeConvert(nullptr); newWin->setAttribute(Qt::WA_DeleteOnClose); newWin->setWindowModality(Qt::ApplicationModal); newWin->show(); registerEscKeyShort(newWin); #ifdef uos adjustWInPos(newWin); #endif } //批量改名 void CCNotePad::slot_batch_rename() { ReNameWin* newWin = new ReNameWin(nullptr); newWin->setAttribute(Qt::WA_DeleteOnClose); newWin->setWindowModality(Qt::ApplicationModal); newWin->show(); registerEscKeyShort(newWin); #ifdef uos adjustWInPos(newWin); #endif } void CCNotePad::slot_options() { OptionsView* p = nullptr; if (m_optionsView.isNull()) { m_optionsView = new OptionsView(this, this); m_optionsView->setWindowFlag(Qt::Window); m_optionsView->setAttribute(Qt::WA_DeleteOnClose); p = dynamic_cast<OptionsView*>(m_optionsView.data()); connect(p, &OptionsView::sendTabFormatChange, this, &CCNotePad::slot_tabFormatChange); } else { p = dynamic_cast<OptionsView*>(m_optionsView.data()); } p->show(); registerEscKeyShort(p); #ifdef uos adjustWInPos(p); #endif } #if 0 //默认TXT文本的字体发生了变化 void CCNotePad::slot_txtFontChange(QFont &font) { QsciLexerText::setGlobalDefaultFont(font); s_txtFont = font; QWidget* pw = nullptr; QsciLexer* lexer = nullptr; for (int i = ui.editTabWidget->count() - 1; i >= 0; --i) { pw = ui.editTabWidget->widget(i); int docType = getDocTypeProperty(pw); if ((TXT_TYPE == docType) || (BIG_TEXT_RO_TYPE == docType)) { ScintillaEditView* pEdit = dynamic_cast<ScintillaEditView*>(pw); if (pEdit != nullptr ) { lexer = pEdit->lexer(); if (lexer != nullptr && (lexer->lexerId() == L_TXT)) { QsciLexerText* t = dynamic_cast<QsciLexerText*>(lexer); if (t != nullptr) { t->setFont(font, 0); } } } } } } #endif #if 0 //默认编程语言的文本的字体发生了变化 void CCNotePad::slot_proLangFontChange(QFont &font) { QsciLexer::setProLangeDefaultFont(font); s_proLangFont = font; QWidget* pw = nullptr; QsciLexer* lexer = nullptr; for (int i = ui.editTabWidget->count() - 1; i >= 0; --i) { pw = ui.editTabWidget->widget(i); int docType = getDocTypeProperty(pw); if ((TXT_TYPE == docType) || (BIG_TEXT_RO_TYPE == docType)) { ScintillaEditView* pEdit = dynamic_cast<ScintillaEditView*>(pw); if (pEdit != nullptr) { lexer = pEdit->lexer(); if (lexer != nullptr && (lexer->lexerId() != L_TXT)) { //这里还是有些问题,把所有的字体大小全部修改了。而没有只针对默认字体。 lexer->setFont(font, -1); } } } } } #endif //tab长度或者使用空格替换tab发生了变化 void CCNotePad::slot_tabFormatChange(bool tabLenChange, bool useTabChange) { QWidget* pw = nullptr; int docType = 0; for (int i = ui.editTabWidget->count() - 1; i >= 0; --i) { pw = ui.editTabWidget->widget(i); docType = getDocTypeProperty(pw); if ((TXT_TYPE == docType) || (BIG_TEXT_RO_TYPE == docType) || (SUPER_BIG_TEXT_RO_TYPE == docType)) { ScintillaEditView* pEdit = dynamic_cast<ScintillaEditView*>(pw); if (pEdit != nullptr) { if (tabLenChange) { pEdit->execute(SCI_SETTABWIDTH, ScintillaEditView::s_tabLens); } if (useTabChange) { pEdit->setIndentationsUseTabs(!ScintillaEditView::s_noUseTab); } } } } } void CCNotePad::slot_donate() { Donate* pWin = new Donate(this); pWin->setWindowFlag(Qt::Window); pWin->setAttribute(Qt::WA_DeleteOnClose); pWin->show(); registerEscKeyShort(pWin); #ifdef uos adjustWInPos(pWin); #endif } // void CCNotePad::slot_registerCmd(int cmd, int code) // { // if (cmd == 1) // { // //服务器返回注册码的消息。 //0 试用 1 正版 2 正版过期 3 错误key // int status = NddSetting::getKeyValueFromNumSets(SOFT_STATUS); // if (status != code) // { // NddSetting::updataKeyValueFromNumSets(SOFT_STATUS, code); // } // // emit signRegisterReplay(code); // } //} //获取注册码 //void CCNotePad::slot_register() //{ //} //当前正在使用的所有语言的tags void CCNotePad::getCurUseLexerTags(QVector<QString>& tags) { for (int i = ui.editTabWidget->count() - 1; i >= 0; --i) { QWidget* pw = ui.editTabWidget->widget(i); ScintillaEditView* pEdit = dynamic_cast<ScintillaEditView*>(pw); if (pEdit != nullptr && (pEdit->lexer() != nullptr)) { QString v = pEdit->lexer()->lexerTag(); if (-1 == tags.indexOf(v)) { tags.append(v); } } } } QtLangSet* CCNotePad::getLangSet() { slot_langFormat(); return dynamic_cast<QtLangSet*>(m_langSetWin.data()); } void CCNotePad::slot_langFormat() { QString initTag; QWidget* pw = ui.editTabWidget->currentWidget(); ScintillaEditView* pEdit = dynamic_cast<ScintillaEditView*>(pw); if (pEdit != nullptr && (pEdit->lexer() != nullptr)) { initTag = pEdit->lexer()->lexerTag(); } QtLangSet* pWin = nullptr; if (m_langSetWin.isNull()) { m_langSetWin = new QtLangSet(initTag, this); pWin = dynamic_cast<QtLangSet*>(m_langSetWin.data()); pWin->setAttribute(Qt::WA_DeleteOnClose); connect(pWin, &QtLangSet::viewStyleChange, this, &CCNotePad::slot_viewStyleChange); connect(pWin, &QtLangSet::viewLexerChange, this, &CCNotePad::slot_viewLexerChange); } else { pWin = dynamic_cast<QtLangSet*>(m_langSetWin.data()); } pWin->show(); registerEscKeyShort(pWin); #ifdef uos adjustWInPos(pWin); #endif pWin->selectInitLangTag(initTag); } void CCNotePad::slot_viewStyleChange(QString tag, int styleId, QColor& fgColor, QColor& bkColor, QFont& font, bool fontChange) { for (int i = ui.editTabWidget->count() - 1; i >= 0; --i) { QWidget* pw = ui.editTabWidget->widget(i); ScintillaEditView* pEdit = dynamic_cast<ScintillaEditView*>(pw); if (pEdit != nullptr && (pEdit->lexer() != nullptr)) { QsciLexer* lexer = pEdit->lexer(); if (lexer->lexerTag() == tag) { if (fgColor.isValid()) { lexer->setColor(fgColor, styleId); } if (bkColor.isValid()) { lexer->setPaper(bkColor, styleId); } if (fontChange) { lexer->setFont(font, styleId); } } } } } void CCNotePad::slot_viewLexerChange(QString tag) { int lexerId = -1; for (int i = ui.editTabWidget->count() - 1; i >= 0; --i) { QWidget* pw = ui.editTabWidget->widget(i); ScintillaEditView* pEdit = dynamic_cast<ScintillaEditView*>(pw); if (pEdit != nullptr && (pEdit->lexer() != nullptr)) { QsciLexer* lexer = pEdit->lexer(); if (lexer != nullptr && lexer->lexerTag() == tag) { lexerId = lexer->lexerId(); delete lexer; autoSetDocLexer(pEdit, lexerId); } } } } //1:非脏新建文件(干净新文件) void CCNotePad::restoreCleanNewFile(QString& fileName) { int index = FileManager::getInstance().getNextNewFileId(); newTxtFile(fileName, index); m_saveFile->setEnabled(false); } //2 非脏的老文件,直接打开 void CCNotePad::restoreCleanExistFile(QString& filePath) { openTextFile(filePath); m_saveFile->setEnabled(false); } //3 脏的新建文件。内容在tempFilePath中 void CCNotePad::restoreDirtyNewFile(QString& fileName, QString& tempFilePath, int lexid) { int index = FileManager::getInstance().getNextNewFileId(); ScintillaEditView* pEdit = newTxtFile(fileName, index, tempFilePath); if (lexid != L_TXT) { QsciLexer* lexer = pEdit->createLexer(lexid); if (lexer != nullptr) { if (nullptr != pEdit->lexer()) { delete pEdit->lexer(); } pEdit->setLexer(lexer); syncCurDocLexerToMenu(pEdit); } } setTextChangeProperty(pEdit,true); m_saveFile->setEnabled(true); m_saveAllFile->setEnabled(true); int tabIndex = ui.editTabWidget->indexOf(pEdit); if (tabIndex != -1) { ui.editTabWidget->setTabIcon(tabIndex, QIcon(TabNeedSave)); } } //4 脏的老文件。内容在tempFilePath中 bool CCNotePad::restoreDirtyExistFile(QString& filePath, QString& tempFilePath) { getRegularFilePath(filePath); #if 0 //这里不需要判断了,大文件压根不能编辑,没有保存临时文件的说法 QFileInfo fi(tempFilePath); //如果文件大于300M,按照只读文件打开 if (ScintillaEditView::s_bigTextSize <= 0 || ScintillaEditView::s_bigTextSize > 300) { ScintillaEditView::s_bigTextSize = 100; } if (fi.size() > ScintillaEditView::s_bigTextSize * 1024 * 1024) { return openBigTextFile(tempFilePath); } #endif QFileInfo fi(filePath); QString fileLabel(fi.fileName()); ScintillaEditView* pEdit = FileManager::getInstance().newEmptyDocument(); pEdit->setNoteWidget(this); //必须要在editTabWidget->addTab之前,因为一旦add时会出发tabchange,其中没有doctype会导致错误 setDocTypeProperty(pEdit, TXT_TYPE); CODE_ID code(UNKOWN); bool isReadOnly = false; #ifdef _WIN32 RC_LINE_FORM lineEnd(DOS_LINE); #else RC_LINE_FORM lineEnd(UNIX_LINE); #endif bool isChange = false; bool isLoadOrgin = false;//是否加载原始文件。只有临时文件被破坏或大小为空,才需要加载老的 //如果非空,则从contentPath中加载文件内容。做恢复文件使用 if (!tempFilePath.isEmpty()) { int ret = FileManager::getInstance().loadFileDataInText(pEdit, tempFilePath, code, lineEnd, nullptr, false,this); if ((ret != 6) && (ret != 0)) { isLoadOrgin = true; ui.statusBar->showMessage(tr("Restore Last Temp File %1 Failed").arg(tempFilePath), 5000); } else { //如果是空的临时文件,则直接打开原始文件,临时文件估计被破坏或是空的,则直接读取原始文件 if (ERROR_TYPE::OPEN_EMPTY_FILE == FileManager::getInstance().getLastErrorCode()) { isLoadOrgin = true; FileManager::getInstance().resetLastErrorCode(); } else { isChange = true; } } } if(isLoadOrgin) { int ret = FileManager::getInstance().loadFileDataInText(pEdit, filePath, code, lineEnd, this, true, this); if (4 == ret) { delete pEdit; //用户同意以二进制格式打开文件 return openHexFile(filePath); } //else if (5 == ret) //{ // isReadOnly = true; // //只读模式 //} else if (6 == ret) { //存在乱码,还是打开 } else if (0 != ret) { delete pEdit; return false; } } disconnect(ui.editTabWidget, &QTabWidget::currentChanged, this, &CCNotePad::slot_tabCurrentChanged); int curIndex = ui.editTabWidget->addTab(pEdit, QIcon((StyleSet::getCurrentSytleId() != DEEP_BLACK) ? TabNoNeedSave : TabNoNeedSaveDark32), getShortName(fileLabel)); ui.editTabWidget->setCurrentIndex(curIndex); connect(ui.editTabWidget, &QTabWidget::currentChanged, this, &CCNotePad::slot_tabCurrentChanged, Qt::UniqueConnection); connect(pEdit, &ScintillaEditView::cursorPositionChanged, this, &CCNotePad::slot_LineNumIndexChange, Qt::QueuedConnection); enableEditTextChangeSign(pEdit); connect(pEdit, &ScintillaEditView::copyAvailable, this, &CCNotePad::slot_copyAvailable); connect(pEdit, SIGNAL(SCN_ZOOM()), this, SLOT(slot_zoomValueChange())); //监控文件 addWatchFilePath(filePath); setCodeBarLabel(code); setLineEndBarLabel(lineEnd); //注意顺序 QVariant editTextEnd((int)lineEnd); pEdit->setProperty(Edit_Text_End, editTextEnd); setDocEolMode(pEdit, lineEnd); QVariant editViewFilePath(filePath); pEdit->setProperty(Edit_View_FilePath, editViewFilePath); ui.editTabWidget->setTabToolTip(curIndex, filePath); QVariant editViewNewFile(-1); pEdit->setProperty(Edit_File_New, editViewNewFile); setTextChangeProperty(pEdit, isChange); if (isChange) { ui.editTabWidget->setTabIcon(curIndex, QIcon(TabNeedSave)); } QVariant editTextCode((int)code); pEdit->setProperty(Edit_Text_Code, editTextCode); syncCurDocEncodeToMenu(pEdit); syncCurDocLineEndStatusToMenu(pEdit); syncCurDocLexerToMenu(pEdit); //设置自动转换和缩进参考线 if (s_autoWarp != QsciScintilla::WrapNone) { pEdit->setWrapMode(QsciScintilla::WrapCharacter); } setEditShowBlankStatus(pEdit, s_showblank); if (s_indent == 1) { pEdit->setIndentGuide(true); } if (s_zoomValue != 0) { pEdit->zoomTo(s_zoomValue); } if (!isReadOnly) { setFileOpenAttrProperty(pEdit, OpenAttr::Text); setWindowTitleMode(filePath, OpenAttr::Text); ui.statusBar->showMessage(tr("File %1 Open Finished [Text Mode]").arg(filePath)); } else { setFileOpenAttrProperty(pEdit, OpenAttr::TextReadOnly); setWindowTitleMode(filePath, OpenAttr::TextReadOnly); ui.statusBar->showMessage(tr("File %1 Open Finished [Text ReadOnly Mode] (Note: display up to 50K bytes ...)").arg(fi.fileName())); } if (pEdit->lexer() == nullptr) { autoSetDocLexer(pEdit); } if (isChange) { m_saveFile->setEnabled(true); m_saveAllFile->setEnabled(true); } return true; } //恢复上次打开的文件 //1:非脏新建文件 2 非脏的已存在文件 3 脏的新建文件 4 脏的老文件。 int CCNotePad::restoreLastFiles() { if (s_restoreLastFile == 0) { return 0; } QString tempFileList = QString("notepad/temp/list"); QSettings qs(QSettings::IniFormat, QSettings::UserScope, tempFileList); qs.setIniCodec("UTF-8"); QStringList fileList = qs.allKeys(); //从小到大排序一下。这里是按照ASCII排序,不得行。 // 需要转换为数字0-N进行排序,否则排序结果错误。 QList<int> fileIdList; for (int i = 0; i < fileList.size(); ++i) { fileIdList.append(fileList.at(i).toInt()); } std::sort(fileIdList.begin(), fileIdList.end(), [](int& a, int& b) { return a < b; }); int key; QString value; foreach(key, fileIdList) { value = qs.value(QString::number(key)).toString(); if (!value.isEmpty()) { bool ok = false; int type = value.right(1).toInt(&ok); if (!ok) { continue; } QString path = value.left(value.size()-2); switch (type) { case 1: restoreCleanNewFile(path); break; case 2: restoreCleanExistFile(path); break; case 3: { QString qsSavePath = qs.fileName(); QFileInfo fi(qsSavePath); QString saveDir = fi.dir().absolutePath(); QString tempFileName = QString("%1/%2").arg(saveDir).arg(key); restoreDirtyNewFile(path, tempFileName); } break; case 4: { QString qsSavePath = qs.fileName(); QFileInfo fi(qsSavePath); QString saveDir = fi.dir().absolutePath(); QString tempFileName = QString("%1/%2").arg(saveDir).arg(key); restoreDirtyExistFile(path, tempFileName); } break; case 5: { //与3一样,不过需要恢复语法 int pos = path.lastIndexOf("|"); QString filePath = path.mid(0,pos); int lexerId = path.mid(pos + 1).toInt(&ok); if (!ok) { continue; } QString qsSavePath = qs.fileName(); QFileInfo fi(qsSavePath); QString saveDir = fi.dir().absolutePath(); QString tempFileName = QString("%1/%2").arg(saveDir).arg(key); restoreDirtyNewFile(filePath, tempFileName, lexerId); } break; default: break; } } } //恢复完毕后,恢复上次的标签页 int curIndexWhenQuit = NddSetting::getKeyValueFromNumSets(LAST_ACTION_TAB_INDEX); ui.editTabWidget->setCurrentIndex(curIndexWhenQuit); return fileList.size(); } //删除行首空格 void CCNotePad::slot_removeHeadBlank() { initFindWindow(); FindWin* pFind = dynamic_cast<FindWin*>(m_pFindWin.data()); //静默调用 pFind->removeLineHeadEndBlank(1); } //删除行尾空格 void CCNotePad::slot_removeEndBlank() { initFindWindow(); FindWin* pFind = dynamic_cast<FindWin*>(m_pFindWin.data()); //静默调用 pFind->removeLineHeadEndBlank(2); } //删除两端空格 void CCNotePad::slot_removeHeadEndBlank() { initFindWindow(); FindWin* pFind = dynamic_cast<FindWin*>(m_pFindWin.data()); //静默调用 pFind->removeLineHeadEndBlank(1); pFind->removeLineHeadEndBlank(2); } void CCNotePad::slot_columnBlockEdit() { if (m_columnEditWin.isNull()) { m_columnEditWin = new ColumnEdit(this); m_columnEditWin->setWindowFlag(Qt::Window); m_columnEditWin->setAttribute(Qt::WA_DeleteOnClose); ColumnEdit* pWin = dynamic_cast<ColumnEdit*>(m_columnEditWin.data()); pWin->setTabWidget(ui.editTabWidget); } m_columnEditWin->show(); registerEscKeyShort(m_columnEditWin); #ifdef uos adjustWInPos(m_columnEditWin); #endif } void CCNotePad::slot_defineLangs() { LangStyleDefine* pWin = new LangStyleDefine(this); pWin->setAttribute(Qt::WA_DeleteOnClose); pWin->show(); registerEscKeyShort(pWin); #ifdef uos adjustWInPos(pWin); #endif } void CCNotePad::transCurUpperOrLower(TextCaseType type) { QWidget* pw = ui.editTabWidget->currentWidget(); ScintillaEditView* pEdit = dynamic_cast<ScintillaEditView*>(pw); if (pEdit != nullptr) { if (pEdit->isReadOnly()) { ui.statusBar->showMessage(tr("The ReadOnly document does not allow this operation."), MSG_EXIST_TIME); QApplication::beep(); return; } pEdit->convertSelectedTextTo(type); } } void CCNotePad::slot_uppercase() { transCurUpperOrLower(UPPERCASE); } void CCNotePad::slot_lowercase() { transCurUpperOrLower(LOWERCASE); } void CCNotePad::slot_properCase() { transCurUpperOrLower(TITLECASE_FORCE); } void CCNotePad::slot_properCaseBlend() { transCurUpperOrLower(TITLECASE_BLEND); } void CCNotePad::slot_sentenceCase() { transCurUpperOrLower(SENTENCECASE_FORCE); } void CCNotePad::slot_sentenceCaseBlend() { transCurUpperOrLower(SENTENCECASE_BLEND); } void CCNotePad::slot_invertCase() { transCurUpperOrLower(INVERTCASE); } void CCNotePad::slot_randomCase() { transCurUpperOrLower(RANDOMCASE); } void CCNotePad::slot_removeEmptyLine() { removeEmptyLine(false); } void CCNotePad::slot_removeEmptyLineCbc() { removeEmptyLine(true); } void CCNotePad::removeEmptyLine(bool isBlankContained) { initFindWindow(); FindWin* pFind = dynamic_cast<FindWin*>(m_pFindWin.data()); //静默调用 pFind->removeEmptyLine(isBlankContained); } void CCNotePad::slot_column_mode() { QMessageBox::about(this, tr("Column Edit Mode Tips"), tr("\"ALT+Mouse Click\" or \"Alt+Shift+Arrow keys\" Switch to mode!")); } void CCNotePad::slot_tabToSpace() { spaceTabConvert(Tab2Space); } void CCNotePad::slot_spaceToTabAll() { spaceTabConvert(Space2TabAll); } void CCNotePad::slot_spaceToTabLeading() { spaceTabConvert(Space2TabLeading); } ScintillaEditView* CCNotePad::getCurEditView() { QWidget* pw = ui.editTabWidget->currentWidget(); ScintillaEditView* _pEditView = dynamic_cast<ScintillaEditView*>(pw); if (_pEditView != nullptr) { if (_pEditView->isReadOnly()) { ui.statusBar->showMessage(tr("The ReadOnly document does not allow this operation."), MSG_EXIST_TIME); QApplication::beep(); return nullptr; } return _pEditView; } return nullptr; } //tab space 互转 void CCNotePad::spaceTabConvert(SpaceTab type) { QWidget* pw = ui.editTabWidget->currentWidget(); ScintillaEditView* _pEditView = dynamic_cast<ScintillaEditView*>(pw); if (_pEditView != nullptr) { if (_pEditView->isReadOnly()) { ui.statusBar->showMessage(tr("The ReadOnly document does not allow this operation."), MSG_EXIST_TIME); QApplication::beep(); return; } intptr_t tabWidth = _pEditView->execute(SCI_GETTABWIDTH); intptr_t currentPos = _pEditView->execute(SCI_GETCURRENTPOS); intptr_t docLength = _pEditView->execute(SCI_GETLENGTH) + 1; if (docLength < 2) return; intptr_t count = 0; intptr_t column = 0; intptr_t newCurrentPos = 0; intptr_t tabStop = tabWidth - 1; // remember, counting from zero ! bool onlyLeading = false; char * source = new char[docLength]; if (source == NULL) return; _pEditView->execute(SCI_GETTEXT, docLength, reinterpret_cast<sptr_t>(source)); if (type == Tab2Space) { // count how many tabs are there for (const char * ch = source; *ch; ++ch) { if (*ch == '\t') ++count; } if (count == 0) { delete[] source; return; } } // allocate tabwidth-1 chars extra per tab, just to be safe size_t newlen = docLength + count * (tabWidth - 1) + 1; char * destination = new char[newlen]; if (destination == NULL) { delete[] source; return; } char * dest = destination; switch (type) { case Tab2Space: { // rip through each line of the file for (int i = 0; source[i] != '\0'; ++i) { if (source[i] == '\t') { intptr_t insertTabs = tabWidth - (column % tabWidth); for (int j = 0; j < insertTabs; ++j) { *dest++ = ' '; if (i <= currentPos) ++newCurrentPos; } column += insertTabs; } else { *dest++ = source[i]; if (i <= currentPos) ++newCurrentPos; if ((source[i] == '\n') || (source[i] == '\r')) column = 0; else if ((source[i] & 0xC0) != 0x80) // UTF_8 support: count only bytes that don't start with 10...... ++column; } } *dest = '\0'; break; } case Space2TabLeading: { onlyLeading = true; } case Space2TabAll: { bool nextChar = false; int counter = 0; bool nonSpaceFound = false; for (int i = 0; source[i] != '\0'; ++i) { if (nonSpaceFound == false) { while (source[i + counter] == ' ') { if ((column + counter) == tabStop) { tabStop += tabWidth; if (counter >= 1) // counter is counted from 0, so counter >= max-1 { *dest++ = '\t'; i += counter; column += counter + 1; counter = 0; nextChar = true; if (i <= currentPos) ++newCurrentPos; break; } else if (source[i + 1] == ' ' || source[i + 1] == '\t') // if followed by space or TAB, convert even a single space to TAB { *dest++ = '\t'; i++; column += 1; counter = 0; if (i <= currentPos) ++newCurrentPos; } else // single space, don't convert it to TAB { *dest++ = source[i]; column += 1; counter = 0; nextChar = true; if (i <= currentPos) ++newCurrentPos; break; } } else ++counter; } if (nextChar == true) { nextChar = false; continue; } if (source[i] == ' ' && source[i + counter] == '\t') // spaces "absorbed" by a TAB on the right { *dest++ = '\t'; i += counter; column = tabStop + 1; tabStop += tabWidth; counter = 0; if (i <= currentPos) ++newCurrentPos; continue; } } if (onlyLeading == true && nonSpaceFound == false) nonSpaceFound = true; if (source[i] == '\n' || source[i] == '\r') { *dest++ = source[i]; column = 0; tabStop = tabWidth - 1; nonSpaceFound = false; } else if (source[i] == '\t') { *dest++ = source[i]; column = tabStop + 1; tabStop += tabWidth; counter = 0; } else { *dest++ = source[i]; counter = 0; if ((source[i] & 0xC0) != 0x80) // UTF_8 support: count only bytes that don't start with 10...... { ++column; if (column > 0 && column % tabWidth == 0) tabStop += tabWidth; } } if (i <= currentPos) ++newCurrentPos; } *dest = '\0'; break; } } _pEditView->execute(SCI_BEGINUNDOACTION); _pEditView->execute(SCI_SETTEXT, 0, reinterpret_cast<sptr_t>(destination)); _pEditView->execute(SCI_GOTOPOS, newCurrentPos); _pEditView->execute(SCI_ENDUNDOACTION); // clean up delete[] source; delete[] destination; } } void CCNotePad::slot_dupCurLine() { qDebug() << "dup atcion called"; ScintillaEditView* _pEditView = getCurEditView(); if (_pEditView != nullptr) { _pEditView->execute(SCI_LINEDUPLICATE); } } void CCNotePad::slot_removeDupLine() { ScintillaEditView* _pEditView = getCurEditView(); if (_pEditView != nullptr) { _pEditView->execute(SCI_BEGINUNDOACTION); _pEditView->removeAnyDuplicateLines(); _pEditView->execute(SCI_ENDUNDOACTION); } } void CCNotePad::slot_splitLines() { ScintillaEditView* _pEditView = getCurEditView(); if (_pEditView != nullptr) { if (_pEditView->execute(SCI_GETSELECTIONS) == 1) { std::pair<size_t, size_t> lineRange = _pEditView->getSelectionLinesRange(); auto anchorPos = _pEditView->execute(SCI_POSITIONFROMLINE, lineRange.first); auto caretPos = _pEditView->execute(SCI_GETLINEENDPOSITION, lineRange.second); _pEditView->execute(SCI_SETSELECTION, caretPos, anchorPos); _pEditView->execute(SCI_TARGETFROMSELECTION); size_t edgeMode = _pEditView->execute(SCI_GETEDGEMODE); if (edgeMode == EDGE_NONE) { _pEditView->execute(SCI_LINESSPLIT, 0); } else { auto textWidth = _pEditView->execute(SCI_TEXTWIDTH, STYLE_DEFAULT, reinterpret_cast<sptr_t>("P")); auto edgeCol = _pEditView->execute(SCI_GETEDGECOLUMN); // will work for edgeMode == EDGE_BACKGROUND if (edgeMode == EDGE_MULTILINE) { //暂时这样。后续有问题再说 } ++edgeCol; // compensate for zero-based column number _pEditView->execute(SCI_LINESSPLIT, textWidth * edgeCol); } } } } void CCNotePad::slot_joinLines() { ScintillaEditView* _pEditView = getCurEditView(); if (_pEditView != nullptr) { const std::pair<size_t, size_t> lineRange = _pEditView->getSelectionLinesRange(); if (lineRange.first != lineRange.second) { auto anchorPos = _pEditView->execute(SCI_POSITIONFROMLINE, lineRange.first); auto caretPos = _pEditView->execute(SCI_GETLINEENDPOSITION, lineRange.second); _pEditView->execute(SCI_SETSELECTION, caretPos, anchorPos); _pEditView->execute(SCI_TARGETFROMSELECTION); _pEditView->execute(SCI_LINESJOIN); } } } void CCNotePad::slot_moveUpCurLine() { ScintillaEditView* _pEditView = getCurEditView(); if (_pEditView != nullptr) { _pEditView->execute(SCI_MOVESELECTEDLINESUP); } } void CCNotePad::slot_moveDownCurLine() { ScintillaEditView* _pEditView = getCurEditView(); if (_pEditView != nullptr) { _pEditView->execute(SCI_MOVESELECTEDLINESDOWN); // Ensure the selection is within view _pEditView->execute(SCI_SCROLLRANGE, _pEditView->execute(SCI_GETSELECTIONEND), _pEditView->execute(SCI_GETSELECTIONSTART)); } } void CCNotePad::slot_insertBlankAbvCur() { ScintillaEditView* _pEditView = getCurEditView(); if (_pEditView != nullptr) { _pEditView->insertNewLineAboveCurrentLine(); } } void CCNotePad::slot_insertBlankBelCur() { ScintillaEditView* _pEditView = getCurEditView(); if (_pEditView != nullptr) { _pEditView->insertNewLineBelowCurrentLine(); } } void CCNotePad::dealLineSort(LINE_SORT_TYPE type) { ScintillaEditView* _pEditView = getCurEditView(); if (_pEditView == nullptr) { return; } size_t fromLine = 0, toLine = 0; size_t fromColumn = 0, toColumn = 0; bool hasLineSelection = false; if (_pEditView->execute(SCI_GETSELECTIONS) > 1) { if (_pEditView->execute(SCI_SELECTIONISRECTANGLE)) { size_t rectSelAnchor = _pEditView->execute(SCI_GETRECTANGULARSELECTIONANCHOR); size_t rectSelCaret = _pEditView->execute(SCI_GETRECTANGULARSELECTIONCARET); size_t anchorLine = _pEditView->execute(SCI_LINEFROMPOSITION, rectSelAnchor); size_t caretLine = _pEditView->execute(SCI_LINEFROMPOSITION, rectSelCaret); fromLine = std::min(anchorLine, caretLine); toLine = std::max(anchorLine, caretLine); size_t anchorLineOffset = rectSelAnchor - _pEditView->execute(SCI_POSITIONFROMLINE, anchorLine) + _pEditView->execute(SCI_GETRECTANGULARSELECTIONANCHORVIRTUALSPACE); size_t caretLineOffset = rectSelCaret - _pEditView->execute(SCI_POSITIONFROMLINE, caretLine) + _pEditView->execute(SCI_GETRECTANGULARSELECTIONCARETVIRTUALSPACE); fromColumn = std::min(anchorLineOffset, caretLineOffset); toColumn = std::max(anchorLineOffset, caretLineOffset); } else { return; } } else { auto selStart = _pEditView->execute(SCI_GETSELECTIONSTART); auto selEnd = _pEditView->execute(SCI_GETSELECTIONEND); hasLineSelection = selStart != selEnd; if (hasLineSelection) { const std::pair<size_t, size_t> lineRange = _pEditView->getSelectionLinesRange(); // One single line selection is not allowed. if (lineRange.first == lineRange.second) { return; } fromLine = lineRange.first; toLine = lineRange.second; } else { // No selection. fromLine = 0; toLine = _pEditView->execute(SCI_GETLINECOUNT) - 1; } } LINE_SORT_TYPE id = type; bool isDescending = ((id == SORTLINES_LEXICOGRAPHIC_DESCENDING) || (id == SORTLINES_LEXICO_CASE_INSENS_DESCENDING)); _pEditView->execute(SCI_BEGINUNDOACTION); std::unique_ptr<ISorter> pSorter; if (id == SORTLINES_LEXICOGRAPHIC_DESCENDING || id == SORTLINES_LEXICOGRAPHIC_ASCENDING) { pSorter = std::unique_ptr<ISorter>(new LexicographicSorter(isDescending, fromColumn, toColumn)); } else if (id == SORTLINES_LEXICO_CASE_INSENS_DESCENDING || id == SORTLINES_LEXICO_CASE_INSENS_ASCENDING) { pSorter = std::unique_ptr<ISorter>(new LexicographicCaseInsensitiveSorter(isDescending, fromColumn, toColumn)); } else if (id == SORTLINES_REVERSE_ORDER) { pSorter = std::unique_ptr<ISorter>(new ReverseSorter(isDescending, fromColumn, toColumn)); } try { _pEditView->sortLines(fromLine, toLine, pSorter.get()); } catch (size_t& failedLineIndex) { size_t lineNo = 1 + fromLine + failedLineIndex; QMessageBox::warning(this, tr("SortingError"), tr("Unable to perform numeric sorting due to line %1.").arg(lineNo)); } _pEditView->execute(SCI_ENDUNDOACTION); if (hasLineSelection) // there was 1 selection, so we restore it { auto posStart = _pEditView->execute(SCI_POSITIONFROMLINE, fromLine); auto posEnd = _pEditView->execute(SCI_GETLINEENDPOSITION, toLine); _pEditView->execute(SCI_SETSELECTIONSTART, posStart); _pEditView->execute(SCI_SETSELECTIONEND, posEnd); } } void CCNotePad::slot_reverseLineOrder() { dealLineSort(SORTLINES_REVERSE_ORDER); } void CCNotePad::slot_sortLexAsc() { dealLineSort(SORTLINES_LEXICOGRAPHIC_ASCENDING); } void CCNotePad::slot_sortLexAscIgnCase() { dealLineSort(SORTLINES_LEXICO_CASE_INSENS_ASCENDING); } void CCNotePad::slot_sortLexDesc() { dealLineSort(SORTLINES_LEXICOGRAPHIC_DESCENDING); } void CCNotePad::slot_sortLexDescIngCase() { dealLineSort(SORTLINES_LEXICO_CASE_INSENS_DESCENDING); } //这里是从F3 F4快捷按下时的查找槽函数。 void CCNotePad::slot_findNext() { //先检查一下,当前查找窗口是否存在而且显示。存在则直接调用查找框的功能。 //避免F3和查找框里面的干扰 if (!m_pFindWin.isNull() && m_pFindWin->isVisible()) { FindWin* pFind = dynamic_cast<FindWin*>(m_pFindWin.data()); pFind->setCurrentTab(FIND_TAB); pFind->findNext(); return; } int ret = initFindWindow(); if (ret == 0) { FindWin* pFind = dynamic_cast<FindWin*>(m_pFindWin.data()); pFind->setCurrentTab(FIND_TAB); pFind->findNext(); } else { ui.statusBar->showMessage(tr("what find is null !"), MSG_EXIST_TIME); } } void CCNotePad::slot_findPrev() { //先检查一下,当前查找窗口是否存在而且显示。存在则直接调用查找框的功能。 //避免F4和查找框里面的干扰 if (!m_pFindWin.isNull() && m_pFindWin->isVisible()) { FindWin* pFind = dynamic_cast<FindWin*>(m_pFindWin.data()); pFind->setCurrentTab(FIND_TAB); pFind->findPrev(); return; } int ret = initFindWindow(); if (ret == 0) { FindWin* pFind = dynamic_cast<FindWin*>(m_pFindWin.data()); pFind->setCurrentTab(FIND_TAB); pFind->findPrev(); } else { ui.statusBar->showMessage(tr("what find is null !"), MSG_EXIST_TIME); } } //繁体BIG5 void CCNotePad::slot_load_with_big5() { reloadTextFileWithCode(CODE_ID::BIG5); } //转成繁体BIG5 void CCNotePad::slot_encode_big5() { transDocToEncord(BIG5); } //为窗口注册ECS退出快捷键 void CCNotePad::registerEscKeyShort(QWidget *parent) { QShortcut *escSc = new QShortcut(parent); escSc->setKey(QKeySequence(Qt::Key_Escape)); escSc->setContext(Qt::WidgetWithChildrenShortcut); connect(escSc, &QShortcut::activated, this, &CCNotePad::slot_escQuit); } void CCNotePad::slot_escQuit() { QShortcut * escSc = dynamic_cast<QShortcut *>(sender()); if (escSc != nullptr && escSc->parentWidget() != nullptr) { escSc->parentWidget()->close(); } } //格式化xml语言 void CCNotePad::slot_formatXml() { ScintillaEditView* _pEditView = getCurEditView(); if (_pEditView == nullptr || _pEditView->isReadOnly()) { return; } QString text = _pEditView->text(); if (text.isEmpty()) { return; } QString xmlOut; QXmlStreamReader reader(text); QXmlStreamWriter writer(&xmlOut); writer.setAutoFormatting(true); while (!reader.atEnd()) { reader.readNext(); if (!reader.isWhitespace()) { writer.writeCurrentToken(reader); } } if (reader.hasError()) { ui.statusBar->showMessage(tr("XML format error, please check!"), MSG_EXIST_TIME); QApplication::beep(); return; } _pEditView->setText(xmlOut); } void CCNotePad::slot_formatJson() { ScintillaEditView* _pEditView = getCurEditView(); if (_pEditView == nullptr || _pEditView->isReadOnly()) { return; } QString text = _pEditView->text(); if (text.isEmpty()) { return; } QByteArray bytes = text.toUtf8(); QJsonParseError parseError; QJsonDocument doc = QJsonDocument::fromJson(bytes, &parseError); if (QJsonParseError::NoError != parseError.error) { ui.statusBar->showMessage(tr("JSON format error, please check!"),MSG_EXIST_TIME); QApplication::beep(); return; } QString content(doc.toJson(QJsonDocument::Indented)); _pEditView->setText(content); } //清空历史打开记录 void CCNotePad::slot_clearHistoryOpenList() { ui.menuRecene_File->clear(); m_receneOpenFileList.clear(); NddSetting::updataKeyValueFromDelaySets(RECENT_OPEN_FILE, ""); } void CCNotePad::slot_showToolBar(bool check) { ui.mainToolBar->setVisible(check); NddSetting::updataKeyValueFromNumSets(TOOLBARSHOW, check?1:0); } void CCNotePad::slot_showWebAddr(bool check) { CCNotePad::s_hightWebAddr = check ? 1 : 0; NddSetting::updataKeyValueFromNumSets(SHOWWEBADDR, s_hightWebAddr); } //更新当前主题的样式 void CCNotePad::updateThemes() { for (int i = ui.editTabWidget->count() - 1; i >= 0; --i) { QWidget* pw = ui.editTabWidget->widget(i); int docType = getDocTypeProperty(pw); if (docType != HEX_TYPE) { ScintillaEditView* pEdit = dynamic_cast<ScintillaEditView*>(pw); if (pEdit != nullptr) { pEdit->updateThemes(); } } else { ScintillaHexEditView* pEdit = dynamic_cast<ScintillaHexEditView*>(pw); if (pEdit != nullptr) { pEdit->updateThemes(); } } } //切换主题后,如果存在查找框,则暴力关闭一下,因为查找框的颜色实时生效还存在问题 if (m_dockSelectTreeWin != nullptr) { m_dockSelectTreeWin->deleteLater(); m_dockSelectTreeWin = nullptr; } } void CCNotePad::setGlobalFgColor(int style) { for (int i = ui.editTabWidget->count() - 1; i >= 0; --i) { QWidget* pw = ui.editTabWidget->widget(i); ScintillaEditView* pEdit = dynamic_cast<ScintillaEditView*>(pw); if (pEdit != nullptr) { pEdit->setGlobalFgColor(style); } } } void CCNotePad::setGlobalBgColor(int style) { for (int i = ui.editTabWidget->count() - 1; i >= 0; --i) { QWidget* pw = ui.editTabWidget->widget(i); ScintillaEditView* pEdit = dynamic_cast<ScintillaEditView*>(pw); if (pEdit != nullptr) { pEdit->setGlobalBgColor(style); } } } void CCNotePad::setGlobalFont(int style) { for (int i = ui.editTabWidget->count() - 1; i >= 0; --i) { QWidget* pw = ui.editTabWidget->widget(i); ScintillaEditView* pEdit = dynamic_cast<ScintillaEditView*>(pw); if (pEdit != nullptr) { pEdit->setGlobalFont(style); } } } //文件后缀的编程语法关联 void CCNotePad::slot_langFileSuffix() { LangExtSet* pWin = new LangExtSet(this); pWin->setAttribute(Qt::WA_DeleteOnClose); #ifdef uos adjustWInPos(pWin); #endif pWin->show(); } //快捷键管理 void CCNotePad::slot_shortcutManager() { ShortcutKeyMgr* pWin = new ShortcutKeyMgr(this); pWin->setAttribute(Qt::WA_DeleteOnClose); #ifdef uos adjustWInPos(pWin); #endif pWin->show(); } //处理当前按下ESC后,需要处理退出的事件 void CCNotePad::on_quitActiveWindow() { if (!m_pFindWin.isNull()&& m_pFindWin->isVisible()) { m_pFindWin->close(); } if (!m_columnEditWin.isNull() && m_columnEditWin->isVisible()) { m_columnEditWin->close(); } if (!m_langSetWin.isNull() && m_langSetWin->isVisible()) { m_langSetWin->close(); } if (!m_optionsView.isNull() && m_optionsView->isVisible()) { m_optionsView->close(); } } #if 0 //修改主题颜色//暂时不开始,发现MAC下有不开启深色的配置 void CCNotePad::changeAppFontColor(QColor color) { //把存在的界面都关闭。发现如果不关闭,颜色不会更新 if (!m_pFindWin.isNull()) { QByteArray curGeo = m_pFindWin->saveGeometry(); NddSetting::updataKeyByteArrayValue(FINDWINSIZE, curGeo); m_pFindWin.data()->deleteLater(); } if (!m_pHexGotoWin.isNull()) { m_pHexGotoWin.data()->close(); } if (!m_columnEditWin.isNull()) { m_columnEditWin.data()->close(); } //filelistwin还存在 if (!m_dockFileListWin.isNull()) { NddSetting::updataKeyValueFromNumSets(FILELISTSHOW, 1); m_dockFileListWin.data()->close(); } if (m_dockSelectTreeWin != nullptr) { m_dockSelectTreeWin->deleteLater(); m_dockSelectTreeWin = nullptr; } } #endif void CCNotePad::on_md5hash() { Md5hash* pWin = new Md5hash(this); pWin->setWindowFlag(Qt::Window); pWin->setAttribute(Qt::WA_DeleteOnClose); pWin->show(); } #ifdef NO_PLUGIN //插件中调用主程序的功能。 //cmdId 执行什么动作,一定固定后,主程序不能随便修改,否则会引发兼容性问题。 bool CCNotePad::pluginInvoke(int cmdId, void* data) { bool ret = false; switch (cmdId) { case 1: { //新建一个文件。 slot_actionNewFile_toggle(true); //默认不需要。 if (data != nullptr) { QVariant* pVar = (QVariant*)data; //回传回去新建文件的名称 ScintillaEditView* pw = getCurEditView(); if (pw != nullptr) { pVar->setValue(getFilePathProperty(pw)); } } ret = true; } break; case 2: { //设定当前编辑器的语言。0 js 1 json int lang = *((int*)data); LangType langs = ((lang == 0) ? L_JAVASCRIPT : L_JSON); ScintillaEditView* pEdit = getCurEditView(); if (pEdit != nullptr) { QsciLexer* curLexer = pEdit->lexer(); if (curLexer == nullptr) { //设定为目标语法 QsciLexer* lexer = ScintillaEditView::createLexer(langs); pEdit->setLexer(lexer); } else if (curLexer->lexerId() != langs) { pEdit->setLexer(nullptr); delete curLexer; curLexer = nullptr; QsciLexer* lexer = ScintillaEditView::createLexer(langs); pEdit->setLexer(lexer); } syncCurDocLexerToMenu(pEdit); } ret = true; } default: break; } return ret; } #endif
276,043
C++
.cpp
8,355
26.89228
254
0.708692
cxasm/notepad--
5,942
234
284
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
25,203
filemanager.cpp
cxasm_notepad--/src/cceditor/filemanager.cpp
#include "filemanager.h" #include "scintillaeditview.h" #include "scintillahexeditview.h" #include "CmpareMode.h" #include "ccnotepad.h" #include "progresswin.h" #include <QMessageBox> #include <QFile> #include <QtGlobal> #include <qscilexer.h> #include <QFileInfo> LangType detectLanguage(QString& headContent, QString& filepath); FileManager::FileManager():m_lastErrorCode(NONE_ERROR) { } FileManager::~FileManager() { } ScintillaEditView* FileManager::newEmptyDocument(bool isBigText) { ScintillaEditView* pEdit = new ScintillaEditView(nullptr, isBigText); return pEdit; } ScintillaHexEditView* FileManager::newEmptyHexDocument() { ScintillaHexEditView* pEdit = new ScintillaHexEditView(nullptr); return pEdit; } //从尾部找前面的换行符号。返回的是需要回溯的个数 //注意如果是LE编码,字节流是\n\0的格式。从尾部往前回溯,找到\n,要回退1个\0。\n\0是一个整体,不能分割开 //20230201发现一个bug,在LE模式下,不能单纯用\n做换行识别。因为发现其它字符也存在\n,必须要完整以\n\0才能确定是换行。 //同样发现BE模式下,是\0\n的格式,也不能单独使用\n做换行识别,因为发现其他字符也存在\n,必须要完整以\0\n才能确定是换行 int findLineEndPos(const char* buf, int size, CODE_ID code = UNKOWN) { int ret = 0; bool isfound = false; for (int i = size - 1; i >= 0; --i) { if (buf[i] == '\n') { ////如果是LE,还要确定\n的下一个是否是\0 if ((code == UNICODE_LE) && ((i != size -1) && (buf[i+1] != '\0'))) { ++ret; continue; } ////如果是BE,还要确定\n的前一个是否是\0 if ((code == UNICODE_BE) && ((i != 0) && (buf[i - 1] != '\0'))) { ++ret; continue; } isfound = true; break; } ++ret; } //如果没有找到,怀疑是mac格式,按照\r结尾解析 if (!isfound) { for (int i = size - 1; i >= 0; --i) { if (buf[i] == '\r') { ////如果是LE,还要确定\n的下一个是否是\0 if ((code == UNICODE_LE) && ((i != size - 1) && (buf[i + 1] != '\0'))) { continue; } ////如果是BE,还要确定\n的前一个是否是\0 if ((code == UNICODE_BE) && ((i != 0) && (buf[i - 1] != '\0'))) { continue; } isfound = true; break; } ++ret; } } if (isfound) { //注意好好想想,这里是--ret,而不是++ret。 if (code == UNICODE_LE) { --ret; } //UNICODE_BE不需要处理 return ret; } //说明是一个巨长的行,这种情况不是很好。直接读取了,不管是否进行了行截断 return 0; } //从行首找后面的换行符号。返回的是需要前进的个数,即把前面掐掉一节,让返回在一行的行首位置 int findLineStartPos(const char* buf, int size, CODE_ID code = UNKOWN) { int ret = 0; bool isfound = false; for (int i = 0; i < size; ++i) { ++ret; if (buf[i] == '\n') { ////如果是LE,还要确定\n的下一个是否是\0 if ((code == UNICODE_LE) && ((i != size - 1) && (buf[i + 1] != '\0'))) { continue; } ////如果是BE,还要确定\n的前一个是否是\0 if ((code == UNICODE_BE) && ((i != 0) && (buf[i - 1] != '\0'))) { continue; } isfound = true; break; } } //如果没有找到,怀疑是mac格式,按照\r结尾解析 if (!isfound) { for (int i = size - 1; i >= 0; --i) { ++ret; if (buf[i] == '\r') { ////如果是LE,还要确定\n的下一个是否是\0 if ((code == UNICODE_LE) && ((i != size - 1) && (buf[i + 1] != '\0'))) { continue; } ////如果是BE,还要确定\n的前一个是否是\0 if ((code == UNICODE_BE) && ((i != 0) && (buf[i - 1] != '\0'))) { continue; } isfound = true; break; } } } if (isfound) { //注意好好想想,这里是++ret,而不是--ret。 if (code == UNICODE_LE) { ++ret; } return ret; } //说明是一个巨长的行,这种情况不是很好。直接读取了,不管是否进行了行截断 return 0; } //返回第一个空闲的id,m_newFileIdList必须有序,从小到大,从0开始 //序号也从0开始,notepad++是从1开始 int FileManager::getNextNewFileId() { if (m_newFileIdList.isEmpty()) { return 0; } int index = 0; bool isFind = false; for (int i = 0; i < m_newFileIdList.size(); ++i) { if (m_newFileIdList.at(i).index > i) { index = i; isFind = true; break; } } if (!isFind) { index = m_newFileIdList.size(); } return index; } //务必要保证不能重复id,所以newnode后,必须接着调用insertNewFileNode,避免重复了 void FileManager::insertNewFileNode(NewFileIdMgr node) { m_newFileIdList.append(node); std::sort(m_newFileIdList.begin(), m_newFileIdList.end(), [](NewFileIdMgr& a, NewFileIdMgr& b) { return a.index < b.index; }); } //删除newfile id的节点 void FileManager::delNewFileNode(int fileIndex) { for (int i = 0; i < m_newFileIdList.size(); ++i) { if (m_newFileIdList.at(i).index == fileIndex) { m_newFileIdList.removeAt(i); break; } } } //和loadFileDataInText类似,但是不是从头开始读取文件,而是从startReadSize开始 //不检查编码,直接按照fileTextCode进行读取 int FileManager::loadFileDataInTextFromOffset(ScintillaEditView* editView, QString filePath, CODE_ID fileTextCode, QWidget* msgBoxParent, quint64 startReadSize) { QFile file(filePath); //如果文件不存在,直接返回 if (!file.exists()) { return -1; } QFlags<QFileDevice::Permission> power = QFile::permissions(filePath); //直接以只读的方式打开,至于能不能保存,是保存时需要考虑的问题。 //只需要在保存的时候获取admin权限即可 QIODevice::OpenMode mode; mode = QIODevice::ExistingOnly | QIODevice::ReadOnly; if (!file.open(mode)) { QMessageBox::warning(msgBoxParent, tr("Error"), tr("Open File %1 failed").arg(filePath)); return 2; } quint64 fileSize = file.size(); //如果文件是空的。检查一下,有可能在临时文件损坏情况下出现,外面需要使用 if (fileSize == 0) { file.close(); return 0; } //如果读取的内容,超过了当前文件大小,则直接返回。这里是返回0,视作成功,没有新内容要读 if (startReadSize >= fileSize) { file.close(); return 0; } QByteArray bytes; if (file.seek(startReadSize)) { //读取后面所有的内容 bytes = file.readAll(); } file.close(); QString text; Encode::tranStrToUNICODE(fileTextCode, bytes.data(), bytes.count(), text); editView->append(text); return 0; } #if 0 //这里是以文本方式加载文件。但是可能遇到的是二进制文件,里面会做判断 //二进制时hexAsk是否询问,当用户指定打开格式时,不需要询问 //MsgBoxParent::尽量把这个给一下,让MsgBox有图标,不那么难看。 int FileManager::loadFileDataInText(ScintillaEditView* editView, QString filePath, CODE_ID& fileTextCode, RC_LINE_FORM& lineEnd,CCNotePad * callbackObj, bool hexAsk, QWidget* msgBoxParent) { QFile file(filePath); //如果文件不存在,直接返回 if (!file.exists()) { return -1; } QFlags<QFileDevice::Permission> power = QFile::permissions(filePath); //直接以只读的方式打开,至于能不能保存,是保存时需要考虑的问题。 //只需要在保存的时候获取admin权限即可 QIODevice::OpenMode mode; mode = QIODevice::ExistingOnly | QIODevice::ReadOnly; if (!file.open(mode)) { qDebug() << file.error(); #ifdef Q_OS_WIN //打开失败,这里一般是权限问题导致。如果是windows,在外面申请权限后继续处理 if (QFileDevice::OpenError == file.error()) { if (callbackObj != nullptr) { return callbackObj->runAsAdmin(filePath); } return 1; } #endif #ifdef Q_OS_UNIX QMessageBox::warning(msgBoxParent, tr("Error"), tr("Open File %1 failed").arg(filePath)); #endif return 2; } qint64 fileSize = file.size(); //如果文件是空的。检查一下,有可能在临时文件损坏情况下出现,外面需要使用 if (fileSize == 0) { m_lastErrorCode = ERROR_TYPE::OPEN_EMPTY_FILE; file.close(); return 0; } qint64 bufferSizeRequested = fileSize + qMin((qint64)(1 << 20), (qint64)(fileSize / 6)); if (bufferSizeRequested > INT_MAX) { QMessageBox::warning(msgBoxParent, tr("Error"), tr("File is too big to be opened by Notepad--")); file.close(); return 3; } QList<LineFileInfo> outputLineInfoVec; int maxLineSize = 0; int charsNums = 0; bool isHexFile = false; fileTextCode = CmpareMode::scanFileOutPut(fileTextCode,filePath, outputLineInfoVec, maxLineSize, charsNums, isHexFile); //如果文件是空的。检查一下,有可能在临时文件损坏情况下出现,外面需要使用 if (charsNums == 0) { m_lastErrorCode = ERROR_TYPE::OPEN_EMPTY_FILE; file.close(); return 0; } if (isHexFile && hexAsk) { //检测到文件很可能是二进制文件,询问用户,是否以二进制加载 int ret = QMessageBox::question(msgBoxParent, tr("Open with Text or Hex? [Exist Garbled Code]"), tr("The file %1 is likely to be binary. Do you want to open it in binary?").arg(filePath), tr("Hex Open"), tr("Text Open"), tr("Cancel")); if (ret == 0) { //16进制打开 file.close(); return 4; } else if (ret == 1) { //继续以文本打开 } else { //取消,不打开 file.close(); return 2; } } if (maxLineSize > 0) { //int textWidth = editView->execute(SCI_TEXTWIDTH, STYLE_DEFAULT, reinterpret_cast<sptr_t>("P")); editView->execute(SCI_SETSCROLLWIDTH, maxLineSize*10); } //以第一行的换行为文本的换行符 lineEnd = UNKNOWN_LINE; if (!outputLineInfoVec.isEmpty()) { lineEnd = static_cast<RC_LINE_FORM>(outputLineInfoVec.at(0).lineEndFormat); } if (lineEnd == UNKNOWN_LINE) { #ifdef _WIN32 lineEnd = DOS_LINE; #else lineEnd = UNIX_LINE; #endif } QString text; text.reserve(charsNums + 1); for (QList<LineFileInfo>::iterator it = outputLineInfoVec.begin(); it != outputLineInfoVec.end(); ++it) { text.append(it->unicodeStr); } file.close(); //优先根据文件后缀来确定其语法风格 LexerInfo lxdata = CCNotePad::getLangLexerIdByFileExt(filePath); if (lxdata.lexerId != L_TXT) { QsciLexer* lexer = editView->createLexer(lxdata.lexerId, lxdata.tagName); editView->setLexer(lexer); } else { //利用前面5行,进行一个编程语言的判断 QString headContens; for (int i = 0; (i < outputLineInfoVec.size() && i < 5); ++i) { headContens.append(outputLineInfoVec.at(i).unicodeStr); } std::string headstr = headContens.toStdString(); LangType _language = detectLanguageFromTextBegining((const unsigned char *)headstr.data(), headstr.length()); if (_language >= 0 && _language < L_EXTERNAL) { QsciLexer* lexer = editView->createLexer(_language); editView->setLexer(lexer); } } //如果检测到时16进制文件,但是强行以二进制打开,则有限走setUtf8Text。 if (!isHexFile) { editView->setText(text); } else { //20230203有github用户反馈,说存在乱码的文件被截断,所以后续还是不走截断 editView->setText(text); return 6; #if 0 //这种情况,为了不编辑二进制模式,是可能只读的。 if (1 == editView->setUtf8Text(text)) { return 5;//只读模式 } #endif } return 0; } #endif //20230304新增加:不再一行一行读取文件,而是一次性读取到内存,加快文本文件打开时的处理速度 //这里是以文本方式加载文件。但是可能遇到的是二进制文件,里面会做判断 //二进制时hexAsk是否询问,当用户指定打开格式时,不需要询问 //MsgBoxParent::尽量把这个给一下,让MsgBox有图标,不那么难看。 int FileManager::loadFileDataInText(ScintillaEditView* editView, QString filePath, CODE_ID& fileTextCode, RC_LINE_FORM& lineEnd, CCNotePad* callbackObj, bool hexAsk, QWidget* msgBoxParent) { QFile file(filePath); //如果文件不存在,直接返回 if (!file.exists()) { return -1; } QFlags<QFileDevice::Permission> power = QFile::permissions(filePath); //直接以只读的方式打开,至于能不能保存,是保存时需要考虑的问题。 //只需要在保存的时候获取admin权限即可 QIODevice::OpenMode mode; mode = QIODevice::ExistingOnly | QIODevice::ReadOnly; if (!file.open(mode)) { qDebug() << file.error(); #ifdef Q_OS_WIN //打开失败,这里一般是权限问题导致。如果是windows,在外面申请权限后继续处理 if (QFileDevice::OpenError == file.error()) { if (callbackObj != nullptr) { return callbackObj->runAsAdmin(filePath); } return 1; } #endif #ifdef Q_OS_UNIX QMessageBox::warning(msgBoxParent, tr("Error"), tr("Open File %1 failed").arg(filePath)); #endif return 2; } qint64 fileSize = file.size(); //如果文件是空的。检查一下,有可能在临时文件损坏情况下出现,外面需要使用 if (fileSize == 0) { m_lastErrorCode = ERROR_TYPE::OPEN_EMPTY_FILE; file.close(); return 0; } qint64 bufferSizeRequested = fileSize + qMin((qint64)(1 << 20), (qint64)(fileSize / 6)); if (bufferSizeRequested > INT_MAX) { QMessageBox::warning(msgBoxParent, tr("Error"), tr("File is too big to be opened by Notepad--")); file.close(); return 3; } QString fileText; bool isErrorCode = false; fileTextCode = CmpareMode::scanFileOutPut(file, fileTextCode, filePath, fileText, isErrorCode); //如果文件是空的。检查一下,有可能在临时文件损坏情况下出现,外面需要使用 if (fileText.size() == 0) { m_lastErrorCode = ERROR_TYPE::OPEN_EMPTY_FILE; file.close(); return 0; } if (isErrorCode && hexAsk) { //检测到文件很可能是二进制文件,询问用户,是否以二进制加载 int ret = QMessageBox::question(msgBoxParent, tr("Open with Text or Hex? [Exist Garbled Code]"), tr("The file %1 is likely to be binary. Do you want to open it in binary?").arg(filePath), tr("Hex Open"), tr("Text Open"), tr("Cancel")); if (ret == 0) { //16进制打开 file.close(); return 4; } else if (ret == 1) { //继续以文本打开 } else { //取消,不打开 file.close(); return 2; } } //以第一行的换行为文本的换行符。暂时只考虑win unix 。mac \r 已经淘汰,暂时不管 lineEnd = RC_LINE_FORM::UNKNOWN_LINE; int pos = fileText.indexOf("\n"); if (pos >=1) { if (fileText[pos - 1] == QChar('\r')) { lineEnd = RC_LINE_FORM::DOS_LINE; } else { lineEnd = RC_LINE_FORM::UNIX_LINE; } } if (lineEnd == UNKNOWN_LINE) { #ifdef _WIN32 lineEnd = DOS_LINE; #else lineEnd = UNIX_LINE; #endif } file.close(); //优先根据文件后缀来确定其语法风格 LexerInfo lxdata = CCNotePad::getLangLexerIdByFileExt(filePath); if (lxdata.lexerId != L_TXT) { QsciLexer* lexer = editView->createLexer(lxdata.lexerId, lxdata.tagName); editView->setLexer(lexer); } else { //利用前面100个字符,进行一个编程语言的判断 QString headContens = fileText.mid(0, 100); LangType _language = detectLanguage(headContens, filePath); if (_language >= 0 && _language < L_EXTERNAL) { QsciLexer* lexer = editView->createLexer(_language); editView->setLexer(lexer); } } //如果检测到时16进制文件,但是强行以二进制打开,则有限走setUtf8Text。 if (!isErrorCode) { editView->setText(fileText); } else { //20230203有github用户反馈,说存在乱码的文件被截断,所以后续还是不走截断 editView->setText(fileText); return 6; } return 0; } //加载文件,只为查找使用 int FileManager::loadFileForSearch(ScintillaEditView* editView, QString filePath) { QFile file(filePath); QFlags<QFileDevice::Permission> power = QFile::permissions(filePath); QIODevice::OpenMode mode; if (!power.testFlag(QFile::WriteUser)) { //文件不能写 mode = QIODevice::ExistingOnly | QIODevice::ReadOnly; } else { mode = QIODevice::ExistingOnly | QIODevice::ReadWrite; } if (!file.open(mode)) { //qDebug() << file.error(); return 2; } qint64 fileSize = file.size(); qint64 bufferSizeRequested = fileSize + qMin((qint64)(1 << 20), (qint64)(fileSize / 6)); if (bufferSizeRequested > INT_MAX) { file.close(); return 3; } bool existGrbledCode = false; QString outText; CODE_ID fileTextCode = CODE_ID::UNKOWN; fileTextCode = CmpareMode::scanFileOutPut(file, fileTextCode, filePath, outText, existGrbledCode); //20230218 这里必须指明一下编码,否则后续会导致编码被修改 editView->setProperty(Edit_Text_Code, fileTextCode); if (existGrbledCode) { //qDebug() << filePath; file.close(); return 4; } file.close(); editView->setText(outText); return 0; } const int ONE_PAGE_BYTES = 4096; //加载下一页或者上一页。(二进制模式) int FileManager::loadFilePreNextPage(int dir, QString& filePath, HexFileMgr* & hexFileOut) { if (m_hexFileMgr.contains(filePath)) { hexFileOut = m_hexFileMgr.value(filePath); //小于LITTLE_FILE_MAX的已经一次性全部在内存,没有上下页可以翻到 if (hexFileOut->onetimeRead) { return 1; } qint64 pos = hexFileOut->fileOffset; if (dir == 1 && (pos >= 0)) { //上一页 pos = pos - hexFileOut->contentRealSize - ONE_PAGE_BYTES; if (pos < 0) { pos = 0; } } else if(dir == 2 && (pos < hexFileOut->fileSize)) { } else { return 1;//没有上下页,已经是最后一页或最前一页 } char* buf = new char[ONE_PAGE_BYTES+1]; hexFileOut->file->seek(pos); qint64 ret = hexFileOut->file->read(buf, ONE_PAGE_BYTES); if (ret <= 0) { return -1; } else { //读取成功 hexFileOut->fileOffset = hexFileOut->file->pos(); if (hexFileOut->contentBuf != nullptr) { delete[]hexFileOut->contentBuf; } hexFileOut->contentBuf = buf; hexFileOut->contentRealSize = ret; } return 0; } return -1; } const int ONE_PAGE_TEXT_SIZE = 1000 * 1024; //加载下一页或者上一页。(文本模式) //返回值:0表示成功 int FileManager::loadFilePreNextPage(int dir, QString& filePath, TextFileMgr* & textFileOut) { if (m_bigTxtFileMgr.contains(filePath)) { textFileOut = m_bigTxtFileMgr.value(filePath); qint64 pos = textFileOut->fileOffset; int canReadSize = 0; if (dir == 1 && (pos >= 0)) { //读取上一页 pos = pos - textFileOut->contentRealSize - ONE_PAGE_TEXT_SIZE; if (pos < 0) { //前面的内容不足以ONE_PAGE_TEXT_SIZE字节 canReadSize = textFileOut->fileOffset - textFileOut->contentRealSize; if (canReadSize <= 0) { return 1; } pos = 0; } else { canReadSize = ONE_PAGE_TEXT_SIZE; } } else if (dir == 2 && (pos < textFileOut->fileSize)) { canReadSize = ONE_PAGE_TEXT_SIZE; } else { return 1; } char* buf = new char[canReadSize + 1]; buf[canReadSize] = '\0'; textFileOut->file->seek(pos); qint64 ret = textFileOut->file->read(buf, canReadSize); if (ret <= 0) { return -1; } else { //读取成功 //如果是往后读取 if (dir == 2) { //读取了1M的内容,从内容尾部往前查找,找到第一个换行符号。如果没有怎么办?说明是一个巨长的行,不妙 //如果是巨长的行,一行超过ONE_PAGE_TEXT_SIZE(1M),则可能存在单个字符截断的可能。 buf[ret] = '\0'; int preLineEndPos = 0; if (textFileOut->file->pos() < textFileOut->fileSize)//反之已经到尾部了,不需要往前找行首了 { preLineEndPos = findLineEndPos(buf, ret, (CODE_ID)textFileOut->loadWithCode); if (preLineEndPos > 0) { //给后面的字符填\0,让字符串正常结尾\0 buf[ret - preLineEndPos] = '\0'; } } textFileOut->fileOffset = textFileOut->file->pos() -preLineEndPos; if (preLineEndPos > 0) { //文件seek到下一行的首位置。 textFileOut->file->seek(textFileOut->fileOffset); } if (textFileOut->contentBuf != nullptr) { delete[]textFileOut->contentBuf; } textFileOut->contentBuf = buf; textFileOut->contentRealSize = ret - preLineEndPos; } else if (dir == 1) { //如果是往前读取 //读取了1M的内容,从内容前面往后查找,找到第一个换行符号。如果没有怎么办?说明是一个巨长的行,不妙 buf[ret] = '\0'; int preLineStartPos = 0; if (textFileOut->file->pos() > canReadSize)//==canReadSize说明已经在文件最前面了。不在最前面,需要 { preLineStartPos = findLineStartPos(buf, ret, (CODE_ID)textFileOut->loadWithCode); if (preLineStartPos > 0) { //把\n前面的内容去掉,通过内存move的方式。 memmove(buf, buf+preLineStartPos,ret - preLineStartPos); buf[ret - preLineStartPos] = '\0'; } } textFileOut->fileOffset = textFileOut->file->pos(); if (textFileOut->contentBuf != nullptr) { delete[]textFileOut->contentBuf; } textFileOut->contentBuf = buf; textFileOut->contentRealSize = ret - preLineStartPos; } } return 0; } return -1; } //从指定地址开始加载文件 int FileManager::loadFileFromAddr(QString filePath, qint64 addr, HexFileMgr* & hexFileOut) { if (m_hexFileMgr.contains(filePath)) { hexFileOut = m_hexFileMgr.value(filePath); //超过文件大小 if (addr < 0 || addr >= hexFileOut->fileSize) { return -2; } //4K对齐 addr &= 0xfffffffffff0; char* buf = new char[ONE_PAGE_BYTES + 1]; hexFileOut->file->seek(addr); qint64 ret = hexFileOut->file->read(buf, ONE_PAGE_BYTES); if (ret <= 0) { return -1; } else { //读取成功 hexFileOut->fileOffset = hexFileOut->file->pos(); if (hexFileOut->contentBuf != nullptr) { delete[]hexFileOut->contentBuf; } hexFileOut->contentBuf = buf; hexFileOut->contentRealSize = ret; } return 0; } return -1; } //从指定地址开始加载文本文件 int FileManager::loadFileFromAddr(QString filePath, qint64 addr, TextFileMgr* & textFileOut) { if (m_bigTxtFileMgr.contains(filePath)) { textFileOut = m_bigTxtFileMgr.value(filePath); //超过文件大小 if (addr < 0 || addr >= textFileOut->fileSize) { return -2; } char* buf = new char[ONE_PAGE_TEXT_SIZE + 1]; buf[ONE_PAGE_TEXT_SIZE] = '\0'; textFileOut->file->seek(addr); qint64 ret = textFileOut->file->read(buf, ONE_PAGE_TEXT_SIZE); if (ret <= 0)//-1是出错。0也是没有读到 { return -1; } else { int preLineEndPos = 0; buf[ret] = '\0'; if (textFileOut->file->pos() < textFileOut->fileSize)//反之已经到尾部了,不需要往前找行了 { preLineEndPos = findLineEndPos(buf, ret, (CODE_ID)textFileOut->loadWithCode); if (preLineEndPos > 0) { //给后面的字符填\0,让字符串正常结尾\0 buf[ret - preLineEndPos] = '\0'; } } //如果本来就在开头开始,则不需要计算findLineStartPos int preLineStartPos = 0; if (addr == 0) { } else { preLineStartPos = findLineStartPos(buf, ret, (CODE_ID)textFileOut->loadWithCode); if (preLineStartPos > 0 && preLineStartPos < ret) //preLineStartPos如果大于ret,则全部都被跳过了,不会显示,是个特例 { memmove(buf, buf + preLineStartPos, ret - preLineStartPos); buf[ret - preLineStartPos] = '\0'; } else { //如果没做调整,则后续不需要偏移,这里必须preLineStartPos赋0值 preLineStartPos = 0; } } //只需要文件调到上一行的行位即可。 textFileOut->fileOffset = textFileOut->file->pos() - preLineEndPos; if (preLineEndPos > 0) { //文件seek到下一行的首位置。 textFileOut->file->seek(textFileOut->fileOffset); } if (textFileOut->contentBuf != nullptr) { delete[]textFileOut->contentBuf; } textFileOut->contentBuf = buf; textFileOut->contentRealSize = ret - preLineEndPos - preLineStartPos; } return 0; } return -1; } //加载二进制文件。从curPos开始,每行16个byte,每次读取64行,一共1024个byte bool FileManager::loadFileData(QString filePath, HexFileMgr* & hexFileOut) { QFile *file = new QFile(filePath); if (!file->open(QIODevice::ReadOnly | QIODevice::ExistingOnly)) { return false; } int readBytes = 0; if (file->size() <= LITTLE_FILE_MAX) { readBytes = LITTLE_FILE_MAX; } else { //对于大于10K的文件,每次只读4K readBytes = ONE_PAGE_BYTES; } char* buf = new char[readBytes]; qint64 ret = file->read(buf, readBytes); if (ret == -1) { //错误 file->close(); delete file; return false; } else { HexFileMgr* hexFile = nullptr; if (!m_hexFileMgr.contains(filePath)) { hexFile = new HexFileMgr(); hexFile->filePath = filePath; hexFile->file = file; hexFile->fileOffset = file->pos(); hexFile->fileSize = file->size(); hexFile->contentBuf = buf; hexFile->contentRealSize = ret; hexFile->onetimeRead = (file->size() <= LITTLE_FILE_MAX); m_hexFileMgr.insert(filePath, hexFile); } else { //理论上这里永远不走 hexFile = m_hexFileMgr.value(filePath); hexFile->fileOffset = file->pos(); hexFile->contentBuf = buf; hexFile->contentRealSize = ret; hexFile->onetimeRead = (file->size() <= LITTLE_FILE_MAX); } hexFileOut = hexFile; return true; } return false; } //加载大文本文件。从0开始读取ONE_PAGE_TEXT_SIZE 500K的内容 bool FileManager::loadFileData(QString filePath, TextFileMgr* & textFileOut, RC_LINE_FORM & lineEnd) { QFile *file = new QFile(filePath); if (!file->open(QIODevice::ReadOnly | QIODevice::ExistingOnly)) { return false; } int readBytes = ONE_PAGE_TEXT_SIZE; char* buf = new char[ONE_PAGE_TEXT_SIZE+1]; buf[ONE_PAGE_TEXT_SIZE] = '\0'; qint64 ret = file->read(buf, readBytes); if (ret <= 0) { //错误 file->close(); delete file; return false; } else { //读取了1M的内容,从尾部往找,找到第一个换行符号。如果没有怎么办?说明是一个巨长的行,不妙 buf[ret] = '\0'; //检测是否为unicode_le编码,要特殊对待。 //bool isUnLeCode = CmpareMode::isUnicodeLeBomFile((uchar*)buf, 2); CODE_ID code = CmpareMode::getTextFileEncodeType((uchar*)buf, ret, filePath, true); int preLineEndPos = findLineEndPos(buf,ret, code); if (preLineEndPos > 0) { //给后面的字符填\0,让字符串正常结尾\0 buf[ret - preLineEndPos] = '\0'; if (ret - preLineEndPos >= 2) { if (buf[ret - preLineEndPos - 1] == '\n' && buf[ret - preLineEndPos - 2] == '\r') { lineEnd = DOS_LINE; } else if (buf[ret - preLineEndPos - 1] == '\n') { lineEnd = UNIX_LINE; } else if (buf[ret - preLineEndPos - 1] == '\r') { lineEnd = MAC_LINE; } } } TextFileMgr* txtFile = nullptr; if (!m_bigTxtFileMgr.contains(filePath)) { txtFile = new TextFileMgr(); txtFile->loadWithCode = code; txtFile->filePath = filePath; txtFile->file = file; txtFile->fileOffset = file->pos() - preLineEndPos; if (preLineEndPos > 0) { //文件seek到下一行的首位置。下次读的时候,头部肯定是一行的行首啦 file->seek(txtFile->fileOffset); } txtFile->fileSize = file->size(); txtFile->contentBuf = buf; txtFile->contentRealSize = ret - preLineEndPos; m_bigTxtFileMgr.insert(filePath, txtFile); } else { //理论上这里永远不走 assert(false); txtFile = m_bigTxtFileMgr.value(filePath); txtFile->fileOffset = file->pos(); txtFile->contentBuf = buf; txtFile->contentRealSize = ret; } textFileOut = txtFile; return true; } return false; } //返回行的数量 int getLineNumInBuf(char* buf, int size, CODE_ID code = UNKOWN) { int lineNums = 0; for (int i = 0; i < size; ++i) { if (buf[i] == '\n') { ////如果是LE,还要确定\n的下一个是否是\0 if ((code == UNICODE_LE) && ((i != size - 1) && (buf[i + 1] != '\0'))) { continue; } //如果是BE,简单\0\n是否连续存在,不能单纯检查\n,还有确定\n的前一个是不是\0 if ((code == UNICODE_BE) && ((i != 0) && (buf[i - 1] != '\0'))) { continue; } ++lineNums; } } //如果没有找到,怀疑是mac格式,按照\r结尾解析 if (lineNums == 0) { for (int i = 0; i < size; ++i) { if (buf[i] == '\r') { ////如果是LE,还要确定\n的前面一个是否是\0 if ((code == UNICODE_LE) && ((i != size - 1) && (buf[i + 1] != '\0'))) { continue; } //如果是BE,简单\0\n是否连续存在,不能单纯检查\n,还有确定\n的前一个是不是\0 if ((code == UNICODE_BE) && ((i != 0) && (buf[i - 1] != '\0'))) { continue; } ++lineNums; } } } return lineNums; } //创建大文件编辑模式的索引文件。0 成功,-1取消 int FileManager::createBlockIndex(BigTextEditFileMgr* txtFile) { //每次filePtr 4M的速度进行建块 qint64 fileSize = txtFile->file->size(); qint64 curOffset = 0; uchar* curPtr = txtFile->filePtr; //检测是否为unicode_le编码,要特殊对待。 //bool isUnLeCode = CmpareMode::isUnicodeLeBomFile(curPtr, 2); CODE_ID code = CmpareMode::getTextFileEncodeType(curPtr, fileSize, txtFile->filePath, true); txtFile->loadWithCode = code; const int blockBytes = BigTextEditFileMgr::BLOCK_SIZE * 1024 * 1024; int lineEndPos = 0; int steps = fileSize / blockBytes; txtFile->blocks.reserve(steps + 10); ProgressWin* loadFileProcessWin = nullptr; if (steps > 200) { loadFileProcessWin = new ProgressWin(nullptr); loadFileProcessWin->setWindowModality(Qt::ApplicationModal); loadFileProcessWin->info(tr("load bit text file tree in progress\nfile size %1, please wait ...").arg(tranFileSize(fileSize))); loadFileProcessWin->setTotalSteps(steps); loadFileProcessWin->show(); } quint32 lineNumStart = 0; quint32 lineNum = 0; while ((curOffset + blockBytes) < fileSize) { BlockIndex bi; bi.fileOffset = curOffset; curOffset += blockBytes; lineEndPos = findLineEndPos((char*)curPtr+ bi.fileOffset, blockBytes, code); bi.fileSize = blockBytes - lineEndPos; lineNum = getLineNumInBuf((char*)curPtr + bi.fileOffset, bi.fileSize, code); curOffset -= lineEndPos; bi.lineNum = lineNum; bi.lineNumStart = lineNumStart; lineNumStart += lineNum; txtFile->blocks.append(bi); if (loadFileProcessWin != nullptr) { if (loadFileProcessWin->isCancel()) { delete loadFileProcessWin; txtFile->blocks.clear(); return -1; } loadFileProcessWin->moveStep(true); } } //最后一块 int lastBlockBytes = fileSize - curOffset; BlockIndex bi; bi.fileOffset = curOffset; curOffset += lastBlockBytes; bi.fileSize = lastBlockBytes; lineNum = getLineNumInBuf((char*)curPtr + bi.fileOffset, bi.fileSize); bi.lineNum = lineNum; bi.lineNumStart = lineNumStart; txtFile->blocks.append(bi); if (loadFileProcessWin != nullptr) { delete loadFileProcessWin; } return 0; } //加载大文件,以索引的方式打开大文件 bool FileManager::loadFileDataWithIndex(QString filePath, BigTextEditFileMgr*& textFileOut) { QFile* file = new QFile(filePath); file->open(QIODevice::ReadOnly); uchar* filePtr = file->map(0, file->size()); BigTextEditFileMgr* txtFile = nullptr; if (!m_bigTxtEditFileMgr.contains(filePath)) { txtFile = new BigTextEditFileMgr(); txtFile->filePath = filePath; txtFile->file = file; txtFile->filePtr = filePtr; textFileOut = txtFile; if (-1 == createBlockIndex(txtFile)) { //取消。 delete txtFile; txtFile = nullptr; return false; } m_bigTxtEditFileMgr.insert(filePath, txtFile); } else { //理论上这里永远不走 assert(false); } return true; } BigTextEditFileMgr* FileManager::getBigFileEditMgr(QString filepath) { if (m_bigTxtEditFileMgr.contains(filepath)) { return m_bigTxtEditFileMgr.value(filepath); } return nullptr; } TextFileMgr* FileManager::getSuperBigFileMgr(QString filepath) { if (m_bigTxtFileMgr.contains(filepath)) { return m_bigTxtFileMgr.value(filepath); } return nullptr; } int FileManager::getBigFileBlockId(QString filepath, quint32 lineNum) { BigTextEditFileMgr* v = m_bigTxtEditFileMgr.value(filepath); for (int i = 0, s = v->blocks.size(); i < s; ++i) { const BlockIndex& k = v->blocks.at(i); if (lineNum >= k.lineNumStart && lineNum < (k.lineNumStart + k.lineNum)) { return i; } } return -1; } HexFileMgr * FileManager::getHexFileHand(QString filepath) { if (m_hexFileMgr.contains(filepath)) { return m_hexFileMgr.value(filepath); } return nullptr; } void FileManager::closeHexFileHand(QString filepath) { if (m_hexFileMgr.contains(filepath)) { HexFileMgr* v = m_hexFileMgr.value(filepath); v->destory(); delete v; m_hexFileMgr.remove(filepath); } } void FileManager::closeSuperBigTextFileHand(QString filepath) { if (m_bigTxtFileMgr.contains(filepath)) { TextFileMgr* v = m_bigTxtFileMgr.value(filepath); v->destory(); delete v; m_bigTxtFileMgr.remove(filepath); } } void FileManager::closeBigTextRoFileHand(QString filepath) { if (m_bigTxtEditFileMgr.contains(filepath)) { BigTextEditFileMgr* v = m_bigTxtEditFileMgr.value(filepath); v->destory(); delete v; m_bigTxtEditFileMgr.remove(filepath); } } //初步检查文件的编程语言。两个标准: 1 文件头部标签 2 文件特定名称 LangType detectLanguage(QString& headContent, QString& filepath) { struct FirstLineLanguages { QString pattern; LangType lang; }; const size_t FIRST_LINE_LANGUAGES = 5; FirstLineLanguages languages[FIRST_LINE_LANGUAGES] = { { "<?xml", L_XML }, { "<?php", L_PHP }, { "<html", L_HTML }, { "<!DOCTYPE html", L_HTML }, { "<?", L_PHP } }; int foundPos = -1; for (int i = 0; i < FIRST_LINE_LANGUAGES; ++i) { foundPos = headContent.indexOf(languages[i].pattern); if (foundPos == 0) { return languages[i].lang; } } const size_t NAME_CHECK_LANGUAGES = 3; FirstLineLanguages NAME_LEXER[NAME_CHECK_LANGUAGES] = { { "make", L_MAKEFILE }, { "makefile", L_MAKEFILE }, { "CMakeLists", L_MAKEFILE }, }; QFileInfo fi(filepath); QString baseName = fi.baseName(); for (int i = 0; i < NAME_CHECK_LANGUAGES; ++i) { if (0 == NAME_LEXER[i].pattern.compare(baseName, Qt::CaseInsensitive)) { return NAME_LEXER[i].lang; } } // Unrecognized first line, we assume it is a text file for now return L_UNKNOWN; }
36,329
C++
.cpp
1,221
21.379197
238
0.658457
cxasm/notepad--
5,942
234
284
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
25,204
cfgtest_Qsci.cpp
cxasm_notepad--/src/qscint/Python/config-tests/cfgtest_Qsci.cpp
#include <QCoreApplication> #include <QFile> #include <QTextStream> #include <Qsci/qsciglobal.h> int main(int argc, char **argv) { QCoreApplication app(argc, argv); QFile outf(argv[1]); if (!outf.open(QIODevice::WriteOnly|QIODevice::Truncate|QIODevice::Text)) return 1; QTextStream out(&outf); out << QSCINTILLA_VERSION << '\n'; out << QSCINTILLA_VERSION_STR << '\n'; return 0; }
423
C++
.cpp
15
24.333333
77
0.680798
cxasm/notepad--
5,942
234
284
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
true
true
true
false
25,206
UTF8DocumentIterator.cpp
cxasm_notepad--/src/qscint/scintilla/boostregex/UTF8DocumentIterator.cpp
// This file is part of Notepad-- project // Copyright (C) 2023 Notepad-- authors. // This program is free software: you can 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 <https://www.gnu.org/licenses/>. #include "UTF8DocumentIterator.h" #include <stdexcept> #include "ILoader.h" #include "ILexer.h" #include "Scintilla.h" #include "Platform.h" #include "CharacterCategory.h" #include "Position.h" #include "SplitVector.h" #include "Partitioning.h" #include "RunStyles.h" #include "CellBuffer.h" #include "CharClassify.h" #include "Decoration.h" #include "CaseFolder.h" #include "Document.h" using namespace Scintilla; UTF8DocumentIterator::UTF8DocumentIterator(Document* doc, Sci::Position pos, Sci::Position end) : m_pos(pos), m_end(end), m_characterIndex(0), m_doc(doc) { // Check for debug builds PLATFORM_ASSERT(m_pos <= m_end); // Ensure for release. if (m_pos > m_end) { m_pos = m_end; } readCharacter(); } UTF8DocumentIterator::UTF8DocumentIterator(const UTF8DocumentIterator& copy) : m_pos(copy.m_pos), m_end(copy.m_end), m_characterIndex(copy.m_characterIndex), m_utf8Length(copy.m_utf8Length), m_utf16Length(copy.m_utf16Length), m_doc(copy.m_doc) { // Check for debug builds PLATFORM_ASSERT(m_pos <= m_end); m_character[0] = copy.m_character[0]; m_character[1] = copy.m_character[1]; // Ensure for release. if (m_pos > m_end) { m_pos = m_end; } } UTF8DocumentIterator& UTF8DocumentIterator::operator ++ () { PLATFORM_ASSERT(m_pos < m_end); if (m_utf16Length == 2 && m_characterIndex == 0) { m_characterIndex = 1; } else { m_pos += m_utf8Length; if (m_pos > m_end) { m_pos = m_end; } m_characterIndex = 0; readCharacter(); } return *this; } UTF8DocumentIterator& UTF8DocumentIterator::operator -- () { if (m_utf16Length == 2 && m_characterIndex == 1) { m_characterIndex = 0; } else { --m_pos; // Skip past the UTF-8 extension bytes while (0x80 == (m_doc->CharAt(m_pos) & 0xC0) && m_pos > 0) --m_pos; readCharacter(); if (m_utf16Length == 2) { m_characterIndex = 1; } } return *this; } void UTF8DocumentIterator::readCharacter() { unsigned char currentChar = m_doc->CharAt(m_pos); if (currentChar & 0x80) { int mask = 0x40; int nBytes = 1; do { mask >>= 1; ++nBytes; } while (currentChar & mask); int result = currentChar & m_firstByteMask[nBytes]; Sci::Position pos = m_pos; m_utf8Length = 1; // work out the unicode point, and count the actual bytes. // If a byte does not start with 10xxxxxx then it's not part of the // the code. Therefore invalid UTF-8 encodings are dealt with, simply by stopping when // the UTF8 extension bytes are no longer valid. while ((--nBytes) && (pos < m_end) && (0x80 == ((currentChar = m_doc->CharAt(++pos)) & 0xC0))) { result = (result << 6) | (currentChar & 0x3F); ++m_utf8Length; } if (result >= 0x10000) { result -= 0x10000; m_utf16Length = 2; // UTF-16 Pair m_character[0] = static_cast<wchar_t>(0xD800 + (result >> 10)); m_character[1] = static_cast<wchar_t>(0xDC00 + (result & 0x3FF)); } else { m_utf16Length = 1; m_character[0] = static_cast<wchar_t>(result); } } else { m_utf8Length = 1; m_utf16Length = 1; m_characterIndex = 0; m_character[0] = static_cast<wchar_t>(currentChar); } } const unsigned char UTF8DocumentIterator::m_firstByteMask[7] = { 0x7F, 0x3F, 0x1F, 0x0F, 0x07, 0x03, 0x01 };
4,172
C++
.cpp
150
24.126667
109
0.666248
cxasm/notepad--
5,942
234
284
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
true
false
25,229
LexTXT.cpp
cxasm_notepad--/src/qscint/scintilla/lexers/LexTXT.cpp
#include <stdlib.h> #include <string.h> #include <stdio.h> #include <stdarg.h> #include <assert.h> #include <ctype.h> #include <string> #include <vector> #include <map> #include <algorithm> #include "ILexer.h" #include "Scintilla.h" #include "SciLexer.h" #include "StringCopy.h" #include "WordList.h" #include "LexAccessor.h" #include "Accessor.h" #include "StyleContext.h" #include "CharacterSet.h" #include "CharacterCategory.h" #include "LexerModule.h" #include "OptionSet.h" #include "SubStyles.h" #include "DefaultLexer.h" #include "LexAccessor.h" #include "UniConversion.h" using namespace Scintilla; //const char styleSubable[] = { SCE_P_IDENTIFIER, 0 }; //Default = 0,//中文 //Ascii = 1,//英文 //Keyword = 2, //关键字,只有以TXT为母版的 LexicalClass lexicalClasses[] = { // Lexer Python SCLEX_PYTHON SCE_P_: 0, "SCE_TXT_DEFAULT", "default", "utf8 char", 1, "SCE_TXT_ASCII", "Ascii", "Ascii", 2, "SCE_TXT_KEYWORD", "keyword", "keyword", }; enum literalsAllowed { litNone = 0, litU = 1, litB = 2, litF = 4 }; // Options used for LexerPython struct OptionsTxt { bool ascii; bool utf8; OptionsTxt() { ascii = true; utf8 = true; } }; struct OptionSetTxt : public OptionSet<OptionsTxt> { OptionSetTxt() { DefineProperty("lexer.txt.utf8string", &OptionsTxt::utf8, "text Unicode string"); DefineProperty("lexer.txt.asciistring", &OptionsTxt::ascii, "text literals ascii string"); } }; class LexTXT :public DefaultLexer { WordList keywords; //SubStyles subStyles; OptionsTxt options; OptionSetTxt osTxt; public: explicit LexTXT() : DefaultLexer(lexicalClasses, ELEMENTS(lexicalClasses))/*, subStyles(styleSubable, 0x80, 0x40, 0)*/ { } virtual ~LexTXT() {} void SCI_METHOD Release() override { delete this; } int SCI_METHOD Version() const override { return lvSubStyles; } const char *SCI_METHOD PropertyNames() override { return osTxt.PropertyNames(); } int SCI_METHOD PropertyType(const char *name) override { return osTxt.PropertyType(name); } const char *SCI_METHOD DescribeProperty(const char *name) override { return osTxt.DescribeProperty(name); } Sci_Position SCI_METHOD PropertySet(const char *key, const char *val) override; const char *SCI_METHOD DescribeWordListSets() override { return ""; } Sci_Position SCI_METHOD WordListSet(int n, const char *wl) override; void SCI_METHOD Lex(Sci_PositionU startPos, Sci_Position length, int initStyle, IDocument *pAccess) override; void SCI_METHOD Fold(Sci_PositionU startPos, Sci_Position length, int initStyle, IDocument *pAccess) override; void *SCI_METHOD PrivateCall(int, void *) override { return 0; } int SCI_METHOD LineEndTypesSupported() override { return SC_LINE_END_TYPE_UNICODE; } //int SCI_METHOD AllocateSubStyles(int styleBase, int numberStyles) override { // return subStyles.Allocate(styleBase, numberStyles); //} //int SCI_METHOD SubStylesStart(int styleBase) override { // return subStyles.Start(styleBase); //} //int SCI_METHOD SubStylesLength(int styleBase) override { // return subStyles.Length(styleBase); //} //int SCI_METHOD StyleFromSubStyle(int subStyle) override { // const int styleBase = subStyles.BaseStyle(subStyle); // return styleBase; //} int SCI_METHOD PrimaryStyleFromStyle(int style) override { return style; } //void SCI_METHOD FreeSubStyles() override { // subStyles.Free(); //} //void SCI_METHOD SetIdentifiers(int style, const char *identifiers) override { // subStyles.SetIdentifiers(style, identifiers); //} int SCI_METHOD DistanceToSecondaryStyles() override { return 0; } //const char *SCI_METHOD GetSubStyleBases() override { // return styleSubable; //} static ILexer *LexerFactoryTxt() { return new LexTXT(); } }; Sci_Position SCI_METHOD LexTXT::PropertySet(const char *key, const char *val) { if (osTxt.PropertySet(&options, key, val)) { return 0; } return -1; } Sci_Position SCI_METHOD LexTXT::WordListSet(int n, const char *wl) { WordList *wordListN = 0; switch (n) { case 0: wordListN = &keywords; break; } Sci_Position firstModification = -1; if (wordListN) { WordList wlNew; wlNew.Set(wl); if (*wordListN != wlNew) { wordListN->Set(wl); firstModification = 0; } } return firstModification; } const int indicatorWhitespace = 1; //inline bool IsAWordChar(int ch, bool unicodeIdentifiers) { // if (ch < 0x80) // return (isalnum(ch) || ch == '.' || ch == '_'); // // if (!unicodeIdentifiers) // return false; // // // Python uses the XID_Continue set from unicode data // return IsXidContinue(ch); //} inline bool IsAAsciiChar(int ch) { return (ch < 0x80); } inline bool IsAWordStart(int ch, bool unicodeIdentifiers) { if (ch < 0x80) return (isalpha(ch) || ch == '_'); if (!unicodeIdentifiers) return false; // Python uses the XID_Start set from unicode data return IsXidStart(ch); } //只识别中文和英文两种单词的状态 void SCI_METHOD LexTXT::Lex(Sci_PositionU startPos, Sci_Position length, int initStyle, IDocument *pAccess) { Accessor styler(pAccess, NULL); const Sci_Position endPos = startPos + length; //// Backtrack to previous line in case need to fix its tab whinging //Sci_Position lineCurrent = styler.GetLine(startPos); //if (startPos > 0) { // if (lineCurrent > 0) { // lineCurrent--; // // Look for backslash-continued lines // while (lineCurrent > 0) { // Sci_Position eolPos = styler.LineStart(lineCurrent) - 1; // const int eolStyle = styler.StyleAt(eolPos); // if (eolStyle == SCE_P_STRING // || eolStyle == SCE_P_CHARACTER // || eolStyle == SCE_P_STRINGEOL) { // lineCurrent -= 1; // } // else { // break; // } // } // startPos = styler.LineStart(lineCurrent); // } // initStyle = (startPos == 0 ? SCE_P_DEFAULT : styler.StyleAt(startPos - 1)); //} //initStyle = initStyle & 31; //if (initStyle == SCE_P_STRINGEOL) { // initStyle = SCE_P_DEFAULT; //} StyleContext sc(startPos, endPos - startPos, initStyle, styler); Sci_Position startIndicator = sc.currentPos; for (; sc.More();) { // Check for a new state starting character if (sc.state == SCE_TXT_DEFAULT) { //遇到下一个ASCII字符的时候,进入识别状态 if (IsAAsciiChar(sc.ch)) { sc.SetState(SCE_TXT_IDENTIFIER); } } else if (sc.state == SCE_TXT_ASCII) { //遇到下一个非ASCII字符的时候,进入识别状态 if (!IsAAsciiChar(sc.ch)) { sc.SetState(SCE_TXT_IDENTIFIER); } } if (sc.state == SCE_TXT_IDENTIFIER) { //txt就三种状态、英文、中文、自定义关键字。默认是中文。 //遇到非字符和非数字,开始检测单词,是关键字则识别为关键字;若不是关键字,则肯定是英文字符 //如果遇到非ASCII字符,则开始检查 if (!IsAAsciiChar(sc.ch)) { char s[1000]; sc.GetCurrent(s, sizeof(s)); int style = SCE_TXT_IDENTIFIER; if (keywords.InList(s)) { style = SCE_TXT_KEYWORD; } else { //不是关键字,就是普通的英文单词 style = SCE_TXT_ASCII; } sc.ChangeState(style); //下面函数运行就已经把关键字或英文给单独设置风格了。此时默认进入中文风格状态 sc.SetState(SCE_TXT_DEFAULT); } } sc.Forward(); } //最后一段不能遗漏,也需要识别 if (sc.state == SCE_TXT_IDENTIFIER) { if (IsAAsciiChar(sc.chPrev)) { sc.ChangeState(SCE_TXT_ASCII); } else { sc.ChangeState(SCE_TXT_DEFAULT); } } sc.SetState(SCE_TXT_DEFAULT); styler.IndicatorFill(startIndicator, sc.currentPos, indicatorWhitespace, 0); sc.Complete(); } static bool IsCommentLine(Sci_Position line, Accessor &styler) { Sci_Position pos = styler.LineStart(line); const Sci_Position eol_pos = styler.LineStart(line + 1) - 1; for (Sci_Position i = pos; i < eol_pos; i++) { const char ch = styler[i]; if (ch == '#') return true; else if (ch != ' ' && ch != '\t') return false; } return false; } static bool IsQuoteLine(Sci_Position line, const Accessor &styler) { const int style = styler.StyleAt(styler.LineStart(line)) & 31; return false; } //不处理任何折叠 void SCI_METHOD LexTXT::Fold(Sci_PositionU startPos, Sci_Position length, int /*initStyle - unused*/, IDocument *pAccess) { return; } static const char *const txtWordListDesc[] = { 0 }; LexerModule lmTxt(SCLEX_TXT, LexTXT::LexerFactoryTxt, "txt", txtWordListDesc);
8,561
C++
.cpp
287
25.480836
124
0.704683
cxasm/notepad--
5,942
234
284
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
25,359
qscilexergo.cpp
cxasm_notepad--/src/qscint/src/qscilexergo.cpp
// This module implements the QsciLexerGO class. // // Copyright (c) 2023 Riverbank Computing Limited <info@riverbankcomputing.com> // // This file is part of QScintilla. // // This file may be used under the terms of the GNU General Public License // version 3.0 as published by the Free Software Foundation and appearing in // the file LICENSE included in the packaging of this file. Please review the // following information to ensure the GNU General Public License version 3.0 // requirements will be met: http://www.gnu.org/copyleft/gpl.html. // // If you do not wish to use this file under the terms of the GPL version 3.0 // then you may purchase a commercial license. For more information contact // info@riverbankcomputing.com. // // This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE // WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. #include "Qsci/qscilexergo.h" #include <qcolor.h> #include <qfont.h> #include <qsettings.h> // The ctor. QsciLexerGO::QsciLexerGO(QObject *parent) : QsciLexerCPP(parent) { m_commentSymbol = "//"; m_commentStart = "/*"; m_commentEnd = "*/"; } // The dtor. QsciLexerGO::~QsciLexerGO() { } // Returns the language name. const char *QsciLexerGO::language() const { return "GO"; } // Returns the foreground colour of the text for a style. QColor QsciLexerGO::defaultColor(int style) const { if (style == VerbatimString) return QColor(0x00, 0x7f, 0x00); return QsciLexerCPP::defaultColor(style); } // Returns the end-of-line fill for a style. bool QsciLexerGO::defaultEolFill(int style) const { if (style == VerbatimString) return true; return QsciLexerCPP::defaultEolFill(style); } // Returns the font of the text for a style. QFont QsciLexerGO::defaultFont(int style) const { if (style == VerbatimString) #if defined(Q_OS_WIN) return QFont("Courier New", QsciLexer::s_defaultFontSize); #elif defined(Q_OS_MAC) return QFont("Courier", 12); #else return QFont("Bitstream Vera Sans Mono", 9); #endif return QsciLexerCPP::defaultFont(style); } // Returns the set of keywords. const char *QsciLexerGO::keywords(int set) { if (set != 1) return 0; return "break case chan const continue default defer " "else fallthrough for func go goto if " "import interface map package range return " "select struct switch type var " "append copy int32 print bool false int64 println " "byte float32 iota real cap float64 len recover " "close imag make string complex int new " "true complex64 int8 nil uint complex128 int16 " "panic uint8 uint16 uint32 uint64 uintptr"; } // Returns the user name of a style. QString QsciLexerGO::description(int style) const { if (style == VerbatimString) return tr("Verbatim string"); return QsciLexerCPP::description(style); } // Returns the background colour of the text for a style. QColor QsciLexerGO::defaultPaper(int style) const { if (style == VerbatimString) return QColor(0xe0, 0xff, 0xe0); return QsciLexer::defaultPaper(style); }
3,101
C++
.cpp
95
30.042105
79
0.743702
cxasm/notepad--
5,942
234
284
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
25,363
qscilexerr.cpp
cxasm_notepad--/src/qscint/src/qscilexerr.cpp
#include "Qsci/qscilexerr.h" #include <qcolor.h> #include <qfont.h> #include <qsettings.h> // The ctor. QsciLexerR::QsciLexerR(QObject* parent) : QsciLexer(parent) { m_commentSymbol = "#"; m_commentStart = "\""; m_commentEnd = "\""; } // The dtor. QsciLexerR::~QsciLexerR() { } // Returns the language name. const char* QsciLexerR::language() const { return "R"; } // Returns the lexer name. const char* QsciLexerR::lexer() const { return "r"; } // Return the string of characters that comprise a word. const char* QsciLexerR::wordCharacters() const { return "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_$@%&"; } // Returns the foreground colour of the text for a style. QColor QsciLexerR::defaultColor(int style) const { switch (style) { case DEFAULT: return QColor(0x80, 0x80, 0x80); case KWORD: case BASEKWORD: case OTHERKWORD: return QColor(0x00, 0x00, 0xff); case COMMENT: return QColor(0x00, 0x7f, 0x00); case NUMBER: return QColor(0x00, 0x7f, 0x7f); case IDENTIFIER: return QColor(0x80, 0x00, 0xff); case STRING: case STRING2: return QColor(0x7f, 0x00, 0x7f); } return QsciLexer::defaultColor(style); } // Returns the end-of-line fill for a style. bool QsciLexerR::defaultEolFill(int style) const { return QsciLexer::defaultEolFill(style); } // Returns the font of the text for a style. QFont QsciLexerR::defaultFont(int style) const { QFont f; switch (style) { case COMMENT: #if defined(Q_OS_WIN) f = QFont("Courier New", 11); #elif defined(Q_OS_MAC) f = QFont("Comic Sans MS", 12); #else f = QFont("Bitstream Vera Serif", 9); #endif break; case KWORD: case BASEKWORD: case OTHERKWORD: f = QsciLexer::defaultFont(style); f.setBold(true); break; case STRING: case STRING2: #if defined(Q_OS_WIN) f = QFont("Courier New", QsciLexer::s_defaultFontSize); #elif defined(Q_OS_MAC) f = QFont("Courier", 12); #else f = QFont("Bitstream Vera Sans Mono", 9); #endif break; default: f = QsciLexer::defaultFont(style); } return f; } // Returns the set of keywords. const char* QsciLexerR::keywords(int set) { if (set == 1) { return "if else repeat while function for in next break TRUE FALSE NULL NA Inf NaN"; } else if (set == 2) { return "abbreviate abline abs acf acos acosh addmargins aggregate agrep alarm alias alist all anova any aov " "aperm append apply approx approxfun apropos ar args arima array arrows asin asinh assign assocplot atan " "atanh attach attr attributes autoload autoloader ave axis backsolve barplot basename beta bindtextdomain " "binomial biplot bitmap bmp body box boxplot bquote break browser builtins bxp by bzfile c call cancor " "capabilities casefold cat category cbind ccf ceiling character charmatch chartr chol choose chull citation " "class close cm cmdscale codes coef coefficients col colnames colors colorspaces colours comment complex confint " "conflicts contour contrasts contributors convolve cophenetic coplot cor cos cosh cov covratio cpgram crossprod " "cummax cummin cumprod cumsum curve cut cutree cycle data dataentry date dbeta dbinom dcauchy dchisq de debug " "debugger decompose delay deltat demo dendrapply density deparse deriv det detach determinant deviance dexp df " "dfbeta dfbetas dffits dgamma dgeom dget dhyper diag diff diffinv difftime digamma dim dimnames dir dirname dist " "dlnorm dlogis dmultinom dnbinom dnorm dotchart double dpois dput drop dsignrank dt dump dunif duplicated dweibull " "dwilcox eapply ecdf edit effects eigen emacs embed end environment eval evalq example exists exp expression factanal " "factor factorial family fft fifo file filter find fitted fivenum fix floor flush for force formals format formula " "forwardsolve fourfoldplot frame frequency ftable function gamma gaussian gc gcinfo gctorture get getenv geterrmessage " "gettext gettextf getwd gl glm globalenv gray grep grey grid gsub gzcon gzfile hat hatvalues hcl hclust head heatmap " "help hist history hsv httpclient iconv iconvlist identical identify if ifelse image influence inherits integer " "integrate interaction interactive intersect invisible isoreg jitter jpeg julian kappa kernapply kernel kmeans knots " "kronecker ksmooth labels lag lapply layout lbeta lchoose lcm legend length letters levels lfactorial lgamma library " "licence license line lines list lm load loadhistory loadings local locator loess log logb logical loglin lowess " "ls lsfit machine mad mahalanobis makepredictcall manova mapply match matlines matplot matpoints matrix max mean median " "medpolish menu merge message methods mget min missing mode monthplot months mosaicplot mtext mvfft names napredict " "naprint naresid nargs nchar ncol next nextn ngettext nlevels nlm nls noquote nrow numeric objects offset open optim " "optimise optimize options order ordered outer pacf page pairlist pairs palette par parse paste pbeta pbinom pbirthday " "pcauchy pchisq pdf pentagamma person persp pexp pf pgamma pgeom phyper pi pico pictex pie piechart pipe plclust plnorm " "plogis plot pmatch pmax pmin pnbinom png pnorm points poisson poly polygon polym polyroot postscript power ppoints " "ppois ppr prcomp predict preplot pretty princomp print prmatrix prod profile profiler proj promax prompt provide psigamma " "psignrank pt ptukey punif pweibull pwilcox q qbeta qbinom qbirthday qcauchy qchisq qexp qf qgamma qgeom qhyper qlnorm qlogis qnbinom " "qnorm qpois qqline qqnorm qqplot qr qsignrank qt qtukey quantile quarters quasi quasibinomial quasipoisson quit qunif quote qweibull " "qwilcox rainbow range rank raw rbeta rbind rbinom rcauchy rchisq readline real recover rect reformulate regexpr relevel remove reorder rep " "repeat replace replicate replications require reshape resid residuals restart return rev rexp rf rgamma rgb rgeom rhyper rle rlnorm rlogis rm " "rmultinom rnbinom rnorm round row rownames rowsum rpois rsignrank rstandard rstudent rt rug runif runmed rweibull rwilcox sample sapply save savehistory scale scan " "screen screeplot sd search searchpaths seek segments seq sequence serialize setdiff setequal setwd shell sign signif sin single sinh sink smooth solve sort " "source spectrum spline splinefun split sprintf sqrt stack stars start stderr stdin stdout stem step stepfun stl stop stopifnot str strftime strheight stripchart strptime " "strsplit strtrim structure strwidth strwrap sub subset substitute substr substring sum summary sunflowerplot supsmu svd sweep switch symbols symnum system t table tabulate " "tail tan tanh tapply tempdir tempfile termplot terms tetragamma text time title toeplitz tolower topenv toupper trace traceback transform trigamma trunc truncate try ts tsdiag " "tsp typeof unclass undebug union unique uniroot unix unlink unlist unname unserialize unsplit unstack untrace unz update upgrade url var varimax vcov vector version vi vignette " "warning warnings weekdays weights which while " "window windows with write wsbrowser xedit xemacs xfig xinch xor xtabs xyinch yinch zapsmall"; } else if (set == 3) { return "acme aids aircondit amis aml banking barchart barley beaver bigcity boot brambles breslow bs bwplot calcium cane " "capability cav censboot channing city claridge cloth cloud coal condense contourplot control corr darwin densityplot " "dogs dotplot ducks empinf envelope environmental ethanol fir frets gpar grav gravity grob hirose histogram islay knn " "larrows levelplot llines logit lpoints lsegments lset ltext lvqinit lvqtest manaus melanoma motor multiedit neuro " "nitrofen nodal ns nuclear oneway parallel paulsen poisons polar qq qqmath remission rfs saddle salinity shingle " "simplex singer somgrid splom stripplot survival tau tmd tsboot tuna unit urine viewport wireframe wool xyplot"; } } // Returns the user name of a style. QString QsciLexerR::description(int style) const { switch (style) { case DEFAULT: return tr("Default"); case COMMENT: return tr("Comment"); case KWORD: return tr("Kword"); case BASEKWORD: return tr("Basekword"); case OTHERKWORD: return tr("OtherKeyWord"); case NUMBER: return tr("Number"); case STRING: //key word return tr("String"); case STRING2: return tr("String2"); case OPERATOR: return tr("Operator"); case IDENTIFIER: return tr("Identifier"); case INFIX: return tr("Infix"); case INFIXEOL: return tr("Infix Eol"); } return QString(); } // Returns the background colour of the text for a style. QColor QsciLexerR::defaultPaper(int style) const { return QsciLexer::defaultPaper(style); }
9,406
C++
.cpp
190
43.021053
190
0.726579
cxasm/notepad--
5,942
234
284
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
25,364
qscilexerrust.cpp
cxasm_notepad--/src/qscint/src/qscilexerrust.cpp
#include "Qsci/qscilexerrust.h" #include "Qsci/qsciscintillabase.h" #include <qcolor.h> #include <qfont.h> #include <qsettings.h> QsciLexerRust::QsciLexerRust(QObject *parent) : QsciLexer(parent) { m_commentSymbol = "//"; m_commentStart = "/*"; m_commentEnd = "*/"; } QsciLexerRust::~QsciLexerRust() { } // Returns the language name. const char* QsciLexerRust::language() const { return "RUST"; } // Returns the lexer name. const char *QsciLexerRust::lexer() const { return "rust"; } // Returns the set of keywords. const char* QsciLexerRust::keywords(int set) { return "as break const continue crate dyn else enum extern " "false fn for if impl in let loop match mod move mut " "pub ref return Self self static struct super trait " "true type unsafe use where while"; } // Returns the foreground colour of the text for a style. QColor QsciLexerRust::defaultColor(int style) const { //if (style == VerbatimString) // return QColor(0x00, 0x7f, 0x00); switch (style) { case RUST_WORD: case RUST_WORD2: case RUST_WORD3: case RUST_WORD4: case RUST_WORD5: case RUST_WORD6: case RUST_WORD7: return QColor(0x00, 0x00, 0xff); default: break; } return QsciLexer::defaultColor(style); } // Returns the font of the text for a style. QFont QsciLexerRust::defaultFont(int style) const { return QsciLexer::defaultFont(style); } // Returns the user name of a style. QString QsciLexerRust::description(int style) const { switch (style) { case RUST_DEFAULT: return "Default"; case RUST_COMMENTBLOCK: return "comment"; case RUST_COMMENTLINE: return "commentline"; case RUST_COMMENTBLOCKDOC: return "commentblockdoc"; case RUST_COMMENTLINEDOC: return "commentlinedoc"; case RUST_NUMBER: return "number"; case RUST_WORD: return "word"; case RUST_WORD2: return "word2"; case RUST_WORD3: return "word3"; case RUST_WORD4: return "word4"; case RUST_WORD5: return "word5"; case RUST_WORD6: return "word6"; case RUST_WORD7: return "word7"; case RUST_STRING: return "string"; case RUST_STRINGR: return "stringr"; case RUST_CHARACTER: return "character"; case RUST_OPERATOR: return "operator"; case RUST_IDENTIFIER: return "identifier"; case RUST_LIFETIME: return "lifetime"; case RUST_MACRO: return "macro"; case RUST_LEXERROR: return "lexerror"; case RUST_BYTESTRING: return "bytestring"; case RUST_BYTESTRINGR: return "bytestringr"; case RUST_BYTECHARACTER: return "bytecharacter"; default: break; } return QString(); } // Returns the background colour of the text for a style. QColor QsciLexerRust::defaultPaper(int style) const { return QsciLexer::defaultPaper(style); } // Return the lexer identifier. int QsciLexerRust::lexerId() const { return L_RUST; }
2,897
C++
.cpp
126
19.904762
62
0.719752
cxasm/notepad--
5,942
234
284
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false