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
12,331
GtkUtil.cpp
xournalpp_xournalpp/src/util/GtkUtil.cpp
#include "util/GtkUtil.h" #include <string> #include <string_view> #include <gtk/gtk.h> #include "util/Assert.h" #include "util/raii/GVariantSPtr.h" namespace xoj::util::gtk { static GAction* findAction(GtkActionable* w) { const char* name = gtk_actionable_get_action_name(w); if (!name) { g_warning("xoj::util::gtk::findAction: No action name set"); return nullptr; } std::string_view namesv = name; size_t dotpos = namesv.find("."); if (dotpos == std::string_view::npos) { g_warning("xoj::util::gtk::findAction: Action name is not of the form \"namespace.name\": %s", name); return nullptr; } std::string groupname(namesv.substr(0, dotpos)); GActionGroup* win = gtk_widget_get_action_group(GTK_WIDGET(w), groupname.c_str()); if (!win) { // Most likely the widget just got removed from the toplevel g_debug("xoj::util::gtk::findAction: could not find action group \"%s\"", groupname.data()); return nullptr; } if (!G_IS_ACTION_MAP(win)) { g_warning("xoj::util::gtk::findAction: GActionGroup is not a GActionMap"); return nullptr; } auto shortname = namesv.substr(dotpos + 1); return g_action_map_lookup_action(G_ACTION_MAP(win), shortname.data()); } void setToggleButtonUnreleasable(GtkToggleButton* btn) { // "hierarchy-change" is emitted when the widget is added to/removed from a toplevel's descendance // We use this to connect to the suitable GAction signals once the widget has been added to the toolbar g_signal_connect(btn, "hierarchy-changed", G_CALLBACK(+[](GtkWidget* btn, GtkWidget*, gpointer) { GAction* action = findAction(GTK_ACTIONABLE(btn)); if (!action) { return; } g_signal_connect_object( btn, "toggled", G_CALLBACK(+[](GtkToggleButton* btn, gpointer a) { xoj::util::GVariantSPtr state(g_action_get_state(G_ACTION(a)), xoj::util::adopt); GVariant* target = gtk_actionable_get_action_target_value(GTK_ACTIONABLE(btn)); if (bool active = g_variant_equal(state.get(), target); active && !gtk_toggle_button_get_active(btn)) { gtk_toggle_button_set_active(btn, true); } }), action, GConnectFlags(0)); }), nullptr); } void setWidgetFollowActionEnabled(GtkWidget* w, GAction* a) { g_signal_connect_object(a, "notify::enabled", G_CALLBACK(+[](GObject* a, GParamSpec*, gpointer w) { bool b = g_action_get_enabled(G_ACTION(a)); gtk_widget_set_sensitive(GTK_WIDGET(w), b); }), w, GConnectFlags(0)); gtk_widget_set_sensitive(w, g_action_get_enabled(a)); } #if GTK_MAJOR_VERSION == 3 void setRadioButtonActionName(GtkRadioButton* btn, const char* actionNamespace, const char* actionName) { // "hierarchy-change" is emitted when the widget is added to/removed from a toplevel's descendance // We use this to connect to the suitable GAction signals once the widget has been added to the toolbar struct Data { std::string actionNamespace; std::string actionName; }; g_signal_connect_data( btn, "hierarchy-changed", G_CALLBACK(+[](GtkWidget* btn, GtkWidget*, gpointer d) { Data* data = static_cast<Data*>(d); GActionGroup* win = gtk_widget_get_action_group(btn, data->actionNamespace.c_str()); if (!win) { // Most likely the widget just got removed from the toplevel return; } xoj_assert(G_IS_ACTION_MAP(win)); auto* action = g_action_map_lookup_action(G_ACTION_MAP(win), data->actionName.c_str()); if (!action) { g_warning("Could not find action \"win.%s\"", data->actionName.c_str()); return; } { // btn owns the return GVariant of gtk_actionable_get_action_target_value() GVariant* target = gtk_actionable_get_action_target_value(GTK_ACTIONABLE(btn)); // action does not own the return GVariant and it is not floating either! xoj::util::GVariantSPtr state(g_action_get_state(G_ACTION(action)), xoj::util::adopt); gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(btn), g_variant_equal(target, state.get())); } static auto toggledCallback = +[](GtkToggleButton* btn, gpointer action) { xoj_assert(gtk_actionable_get_action_target_value(GTK_ACTIONABLE(btn))); if (gtk_toggle_button_get_active(btn)) { g_action_change_state(G_ACTION(action), gtk_actionable_get_action_target_value(GTK_ACTIONABLE(btn))); } }; g_signal_connect_object(btn, "toggled", G_CALLBACK(toggledCallback), action, GConnectFlags(0)); g_signal_connect_object( action, "notify::state", G_CALLBACK(+[](GObject* action, GParamSpec*, gpointer btn) { // btn owns the return GVariant of gtk_actionable_get_action_target_value() GVariant* target = gtk_actionable_get_action_target_value(GTK_ACTIONABLE(btn)); // action does not own the return GVariant and it is not floating either! xoj::util::GVariantSPtr state(g_action_get_state(G_ACTION(action)), xoj::util::adopt); xoj_assert(target); xoj_assert(state); if (g_variant_equal(target, state.get()) && !gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(btn))) { g_signal_handlers_block_by_func(btn, (gpointer)toggledCallback, action); gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(btn), true); g_signal_handlers_unblock_by_func(btn, (gpointer)toggledCallback, action); } }), btn, GConnectFlags(0)); setWidgetFollowActionEnabled(btn, action); }), new Data{actionNamespace, actionName}, +[](gpointer d, GClosure*) { delete static_cast<Data*>(d); }, GConnectFlags(0)); } void fixActionableInitialSensitivity(GtkActionable* w) { g_signal_connect(w, "hierarchy-changed", G_CALLBACK(+[](GtkWidget* w, GtkWidget*, gpointer) { GAction* action = findAction(GTK_ACTIONABLE(w)); if (!action) { return; } gtk_widget_set_sensitive(w, g_action_get_enabled(action)); }), nullptr); } #endif }; // namespace xoj::util::gtk
7,440
C++
.cpp
132
40.060606
118
0.544906
xournalpp/xournalpp
10,962
791
1,098
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
12,332
SaveNameUtils.cpp
xournalpp_xournalpp/src/util/SaveNameUtils.cpp
#include "util/SaveNameUtils.h" #include "util/PathUtil.h" // for clearExtensions auto SaveNameUtils::parseFilenameFromWildcardString(const std::string& wildcardString, const fs::path& defaultFilePath) -> std::string { std::string saveString = wildcardString; size_t pos = saveString.find(DEFAULT_WILDCARD_START); // parse all wildcards until none are left while (pos != std::string::npos) { size_t wildcardStartLength = std::strlen(DEFAULT_WILDCARD_START); size_t endPos = saveString.find(DEFAULT_WILDCARD_END, pos + wildcardStartLength); if (endPos == std::string::npos) { break; } std::string parsedWildcard = parseWildcard(saveString.substr(pos + wildcardStartLength, endPos - pos - wildcardStartLength), defaultFilePath); saveString.replace(pos, endPos + 1 - pos, parsedWildcard); pos += parsedWildcard.size(); pos = saveString.find(DEFAULT_WILDCARD_START, pos); } return saveString; } auto SaveNameUtils::parseWildcard(const std::string& wildcard, const fs::path& defaultFilePath) -> std::string { if (wildcard == WILDCARD_NAME) { fs::path path = defaultFilePath; Util::clearExtensions(path, ".pdf"); return path.u8string(); } if (wildcard == WILDCARD_DATE || wildcard == WILDCARD_TIME) { // Backwards compatibility: redirect to std::chrono placeholders return wildcard == WILDCARD_DATE ? "%F" : "%X"; } // not a valid wildcard return ""; }
1,520
C++
.cpp
32
41.1875
150
0.680837
xournalpp/xournalpp
10,962
791
1,098
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
12,333
Range.cpp
xournalpp_xournalpp/src/util/Range.cpp
#include "util/Range.h" #include <algorithm> // for max, min #include "util/Rectangle.h" Range::Range(const xoj::util::Rectangle<double>& r): minX(r.x), minY(r.y), maxX(r.x + r.width), maxY(r.y + r.height) {} void Range::addPoint(double x, double y) { this->minX = std::min(this->minX, x); this->maxX = std::max(this->maxX, x); this->minY = std::min(this->minY, y); this->maxY = std::max(this->maxY, y); } Range Range::unite(const Range& o) const { return Range(std::min(minX, o.minX), std::min(minY, o.minY), std::max(maxX, o.maxX), std::max(maxY, o.maxY)); } Range Range::intersect(const Range& o) const { Range rg(std::max(minX, o.minX), std::max(minY, o.minY), std::min(maxX, o.maxX), std::min(maxY, o.maxY)); return rg.isValid() ? rg : Range(); } auto Range::getX() const -> double { return this->minX; } auto Range::getY() const -> double { return this->minY; } auto Range::getWidth() const -> double { return this->maxX - this->minX; } auto Range::getHeight() const -> double { return this->maxY - this->minY; } void Range::addPadding(double padding) { this->minX -= padding; this->maxX += padding; this->minY -= padding; this->maxY += padding; } void Range::translate(double dx, double dy) { this->minX += dx; this->maxX += dx; this->minY += dy; this->maxY += dy; } auto Range::empty() const -> bool { Range empty; return this->minX == empty.minX && this->minY == empty.minY && this->maxX == empty.maxX && this->maxY == empty.maxY; } bool Range::isValid() const { return minX <= maxX && minY <= maxY; } bool Range::contains(double x, double y) const { return x >= minX && x <= maxX && y >= minY && y <= maxY; } bool Range::contains(const xoj::util::Rectangle<double>& r) const { return this->minX <= r.x && this->maxX >= r.x + r.width && this->minY <= r.y && this->maxY >= r.y + r.height; }
1,890
C++
.cpp
42
41.857143
120
0.628962
xournalpp/xournalpp
10,962
791
1,098
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
12,334
StringUtils.cpp
xournalpp_xournalpp/src/util/StringUtils.cpp
#include "util/StringUtils.h" #include <cstring> #include <sstream> // std::istringstream #include <utility> #include <glib.h> #include "util/safe_casts.h" // for as_signed using std::string; using std::vector; auto StringUtils::toLowerCase(const string& input) -> string { char* lower = g_utf8_strdown(input.c_str(), as_signed(input.size())); string lowerStr = lower; g_free(lower); return lowerStr; } void StringUtils::replaceAllChars(string& input, const std::vector<replace_pair>& replaces) { string out; bool found = false; for (char c: input) { for (const replace_pair& p: replaces) { if (c == p.first) { out += p.second; found = true; break; } } if (!found) { out += c; } found = false; } input = out; } auto StringUtils::split(const string& input, char delimiter) -> vector<string> { vector<string> tokens; string token; std::istringstream tokenStream(input); while (std::getline(tokenStream, token, delimiter)) { tokens.push_back(token); } return tokens; } auto StringUtils::startsWith(const string& str, const string& start) -> bool { return str.compare(0, start.length(), start) == 0; } auto StringUtils::endsWith(const string& str, const string& end) -> bool { if (end.size() > str.size()) { return false; } return str.compare(str.length() - end.length(), end.length(), end) == 0; } const std::string TRIM_CHARS = "\t\n\v\f\r "; auto StringUtils::ltrim(std::string str) -> std::string { str.erase(0, str.find_first_not_of(TRIM_CHARS)); return str; } auto StringUtils::rtrim(std::string str) -> std::string { str.erase(str.find_last_not_of(TRIM_CHARS) + 1); return str; } auto StringUtils::trim(std::string str) -> std::string { return ltrim(rtrim(std::move(str))); } auto StringUtils::iequals(const string& a, const string& b) -> bool { gchar* ca = g_utf8_casefold(a.c_str(), as_signed(a.size())); gchar* cb = g_utf8_casefold(b.c_str(), as_signed(b.size())); int result = strcmp(ca, cb); g_free(ca); g_free(cb); return result == 0; }
2,221
C++
.cpp
68
27.647059
95
0.627809
xournalpp/xournalpp
10,962
791
1,098
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
12,335
ElementRange.cpp
xournalpp_xournalpp/src/util/ElementRange.cpp
#include "util/ElementRange.h" #include <charconv> // for from_chars #include <cstddef> // for size_t #include <regex> // for regex_match, match_results<>::_Unchecked, regex #include <stdexcept> // for invalid_argument, logic_error #include <string> // for basic_string, string #include "util/i18n.h" // for _ /** * @brief Parse a string of page ranges. * * This function parses a string of page ranges into a vector of pairs of page * numbers. A page range is of the form n, n-, -m, n-m where n, m are positive * integers. The input - is also accepted. Page ranges are separated by `,`, `;` * and `:`. Whitespace is ignored. The parameter 'pageCount' is the largest page * number that may be refered to. The function silently corrects page numbers * equal to 0 or larger than pageCount by truncating to the nearest * acceptable integer. * * Example input and output: * * parse("1, 2-, -3, 4-5, -, 0-42", 10) * ===> * {0, 0}, {1, 9}, {0, 2}, {3, 4}, {0, 9}, {0, 9} * * Note that the page numbers are parsed in the format 1 - pageCount * (permissive) and the return values are in the range 0 - (pageCount-1). * * @param s The string containing page ranges to parse. * @param maxCount The largest element index that is possible to refer to. * @exception std::logic_error If `pageCount == 0`. * @exception std::invalid_argument If the input doesn't match any acceptable * page ranges. * @return A vector containing the page ranges. */ ElementRangeVector ElementRange::parse(const std::string& s, size_t maxCount) { // break the string into comma (or ;:) separated tokens. const std::regex separators("[,;:]"); auto begin = std::sregex_token_iterator(s.cbegin(), s.cend(), separators, -1); auto end = std::sregex_token_iterator(); ElementRangeVector entries; if (maxCount == 0) { throw std::logic_error("ElementRange::parse(): maxCount is zero."); } /* The following input cases are considered: * * 1) n, parsed by singlePage, * 2) n-, parsed by rightOpenRange, * 3) -m, parsed by leftOpenRange, * 4) n-m, parsed by pageRange, * 5) -, parsed by bothOpenRange, * 6) For everything else, an exception is thrown. */ const std::regex singlePage("\\s*(\\d+)\\s*"); const std::regex rightOpenRange("\\s*(\\d+)\\s*-\\s*"); const std::regex leftOpenRange("\\s*-\\s*(\\d+)\\s*"); const std::regex pageRange("\\s*(\\d+)\\s*-\\s*(\\d+)\\s*"); const std::regex bothOpenRange("\\s*-\\s*"); // for each token separated by `separators` for (auto it = begin; it != end; it++) { std::smatch match; ElementRangeEntry entry; const std::string str = it->str(); // This if-else block determines which case of 1) through 6) we deal with if (std::regex_match(str, match, singlePage)) { const auto token = match[1].str(); std::from_chars(token.data(), token.data() + token.size(), entry.first); entry.last = entry.first; } else if (std::regex_match(str, match, rightOpenRange)) { const auto token = match[1].str(); std::from_chars(token.data(), token.data() + token.size(), entry.first); entry.last = maxCount; } else if (std::regex_match(str, match, leftOpenRange)) { const auto token = match[1].str(); std::from_chars(token.data(), token.data() + token.size(), entry.last); entry.first = 1; } else if (std::regex_match(str, match, pageRange)) { const auto tokenFirst = match[1].str(); const auto tokenLast = match[2].str(); std::from_chars(tokenFirst.data(), tokenFirst.data() + tokenFirst.size(), entry.first); std::from_chars(tokenLast.data(), tokenLast.data() + tokenLast.size(), entry.last); } else if (std::regex_match(str, match, bothOpenRange)) { entry.first = 1; entry.last = maxCount; } else { throw std::invalid_argument(_("ElementRange::parse(): invalid element range.")); } if (entry.first > maxCount || entry.last > maxCount) { throw std::invalid_argument(_("ElementRange::parse(): given element index is larger than maximum count.")); } if (entry.last < entry.first) { throw std::invalid_argument(_("ElementRange::parse(): interval bounds must be in increasing order.")); } if (entry.first == 0) { // entry.last cannot be 0 unless entry.first is. throw std::invalid_argument(_("ElementRange::parse(): element indices start with 1")); } // decrease the ranges because they should start from 0 instead of 1 entry.first--; // Cannot already be 0 entry.last--; // Cannot already be 0 entries.push_back(entry); } return entries; }
4,910
C++
.cpp
102
41.784314
119
0.619375
xournalpp/xournalpp
10,962
791
1,098
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
12,336
OutputStream.cpp
xournalpp_xournalpp/src/util/OutputStream.cpp
#include "util/OutputStream.h" #include <cassert> #include <cerrno> #include <cstring> // for strlen #include <utility> // for move #include "util/GzUtil.h" // for GzUtil #include "util/i18n.h" // for FS, _F #include "util/safe_casts.h" OutputStream::OutputStream() = default; OutputStream::~OutputStream() = default; void OutputStream::write(const std::string& str) { write(str.c_str(), str.length()); } void OutputStream::write(const char* str) { write(str, std::strlen(str)); } //////////////////////////////////////////////////////// /// GzOutputStream ///////////////////////////////////// //////////////////////////////////////////////////////// GzOutputStream::GzOutputStream(fs::path file): file(std::move(file)) { this->fp = GzUtil::openPath(this->file, "w"); if (this->fp == nullptr) { this->error = FS(_F("Error opening file: \"{1}\"") % this->file.u8string()); this->error = this->error + "\n" + std::strerror(errno); } } GzOutputStream::~GzOutputStream() { if (this->fp) { close(); } this->fp = nullptr; } auto GzOutputStream::getLastError() const -> const std::string& { return this->error; } void GzOutputStream::write(const char* data, size_t len) { xoj_assert(len != 0 && this->fp); auto written = gzwrite(this->fp, data, strict_cast<unsigned int>(len)); if (as_unsigned(written) != len) { int errnum = 0; const char* error = gzerror(this->fp, &errnum); if (errnum != Z_OK) { this->error = FS(_F("Error writing data to file: \"{1}\"") % this->file.u8string()); this->error += "\n" + FS(_F("Error code {1}. Message:") % errnum) + "\n"; if (errnum == Z_ERRNO) { // fs error. Fetch the precise message this->error += std::strerror(errno); } else { this->error += error; } } } } void GzOutputStream::close() { if (!this->fp) { return; } auto errnum = gzclose(this->fp); this->fp = nullptr; if (errnum != Z_OK) { this->error = FS(_F("Error occurred while closing file: \"{1}\"") % this->file.u8string()); this->error += "\n" + FS(_F("Error code {1}") % errnum); if (errnum == Z_ERRNO) { // fs error. Fetch the precise message this->error = this->error + "\n" + std::strerror(errno); } } }
2,413
C++
.cpp
62
32.983871
99
0.540009
xournalpp/xournalpp
10,962
791
1,098
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
12,337
PathUtil.cpp
xournalpp_xournalpp/src/util/PathUtil.cpp
#include "util/PathUtil.h" #include <algorithm> #include <cstdlib> // for system #include <fstream> // for ifstream, char_traits, basic_ist... #include <iterator> // for begin #include <string_view> // for basic_string_view, operator""sv #include <type_traits> // for remove_reference<>::type #include <utility> // for move #include <config-paths.h> // for PACKAGE_DATA_DIR #include <glib.h> // for gchar, g_free, g_filename_to_uri #include "util/PlaceholderString.h" // for PlaceholderString #include "util/StringUtils.h" // for replace_pair, StringUtils #include "util/Util.h" // for getPid, execInUiThread #include "util/XojMsgBox.h" // for XojMsgBox #include "util/i18n.h" // for FS, _F, FORMAT_STR #include "util/safe_casts.h" // for as_signed #include "config.h" // for PROJECT_NAME #ifdef GHC_FILESYSTEM // Fix of ghc::filesystem bug (path::operator/=() won't support string_views) constexpr auto const* CONFIG_FOLDER_NAME = "xournalpp"; #else using namespace std::string_view_literals; constexpr auto CONFIG_FOLDER_NAME = "xournalpp"sv; #endif #ifdef _WIN32 #include <windows.h> auto Util::getLongPath(const fs::path& path) -> fs::path { DWORD wLongPathSz = GetLongPathNameW(path.c_str(), nullptr, 0); if (wLongPathSz == 0) { return path; } std::wstring wLongPath(wLongPathSz, L'\0'); GetLongPathNameW(path.c_str(), wLongPath.data(), static_cast<DWORD>(wLongPath.size())); wLongPath.pop_back(); return fs::path(std::move(wLongPath)); } #else auto Util::getLongPath(const fs::path& path) -> fs::path { return path; } #endif #ifdef __APPLE__ #include "util/Stacktrace.h" #endif /** * Read a file to a string * * @param path Path to read * @param showErrorToUser Show an error to the user, if the file could not be read * @param openmode Mode to open the file * * @return contents if the file was read, std::nullopt if not */ auto Util::readString(fs::path const& path, bool showErrorToUser, std::ios_base::openmode openmode) -> std::optional<std::string> { try { std::string s; std::ifstream ifs{path, openmode}; s.resize(fs::file_size(path)); ifs.read(s.data(), as_signed(s.size())); return {std::move(s)}; } catch (const fs::filesystem_error& e) { if (showErrorToUser) { XojMsgBox::showErrorToUser(nullptr, e.what()); } } return std::nullopt; } auto Util::getEscapedPath(const fs::path& path) -> std::string { std::string escaped = path.string(); StringUtils::replaceAllChars(escaped, {replace_pair('\\', "\\\\"), replace_pair('\"', "\\\"")}); return escaped; } auto Util::hasXournalFileExt(const fs::path& path) -> bool { auto extension = StringUtils::toLowerCase(path.extension().string()); return extension == ".xoj" || extension == ".xopp"; } auto Util::hasPdfFileExt(const fs::path& path) -> bool { return StringUtils::toLowerCase(path.extension().string()) == ".pdf"; } auto Util::clearExtensions(fs::path& path, const std::string& ext) -> void { auto rm_ext = [&path](const std::string ext) { if (StringUtils::toLowerCase(path.extension().string()) == StringUtils::toLowerCase(ext)) { path.replace_extension(""); } }; rm_ext(".xoj"); rm_ext(".xopp"); if (!ext.empty()) { rm_ext(ext); } } // Uri must be ASCII-encoded! auto Util::fromUri(const std::string& uri) -> std::optional<fs::path> { if (!StringUtils::startsWith(uri, "file://")) { return std::nullopt; } gchar* filename = g_filename_from_uri(uri.c_str(), nullptr, nullptr); if (filename == nullptr) { return std::nullopt; } auto p = fs::u8path(filename); g_free(filename); return {std::move(p)}; } auto Util::toUri(const fs::path& path) -> std::optional<std::string> { GError* error{}; char* uri = [&] { if (path.is_absolute()) { return g_filename_to_uri(path.u8string().c_str(), nullptr, &error); } return g_filename_to_uri(fs::absolute(path).u8string().c_str(), nullptr, &error); }(); if (error != nullptr) { g_warning("Util::toUri: could not parse path to URI, error: %s\n", error->message); g_error_free(error); return std::nullopt; } if (!uri) { g_warning("Util::toUri: path results in empty URI"); return std::nullopt; } std::string uriString(uri); g_free(uri); return {std::move(uriString)}; } auto Util::fromGFile(GFile* file) -> fs::path { char* p = g_file_get_path(file); auto ret = p ? fs::u8path(p) : fs::path{}; g_free(p); return ret; } auto Util::toGFile(fs::path const& path) -> xoj::util::GObjectSPtr<GFile> { return xoj::util::GObjectSPtr<GFile>(g_file_new_for_path(path.u8string().c_str()), xoj::util::adopt); } void Util::openFileWithDefaultApplication(const fs::path& filename) { #ifdef __APPLE__ constexpr auto const OPEN_PATTERN = "open \"{1}\""; #elif _WIN32 // note the underscore: without it, it's not msdn official! constexpr auto const OPEN_PATTERN = "start \"\" \"{1}\""; /** * start command requires a (possibly empty) title when there are quotes around the command * https://stackoverflow.com/questions/27261692/how-do-i-use-quotes-in-cmd-start */ #else // linux, unix, ... constexpr auto const OPEN_PATTERN = "xdg-open \"{1}\""; #endif std::string command = FS(FORMAT_STR(OPEN_PATTERN) % Util::getEscapedPath(filename)); if (system(command.c_str()) != 0) { std::string msg = FS(_F("File couldn't be opened. You have to do it manually:\n" "URL: {1}") % filename.u8string()); XojMsgBox::showErrorToUser(nullptr, msg); } } auto Util::getGettextFilepath(fs::path const& localeDir) -> fs::path { /// documentation of g_getenv is wrong, its UTF-8, see #5640 const char* gettextEnv = g_getenv("TEXTDOMAINDIR"); // Only consider first path in environment variable std::string_view directories; if (gettextEnv) { directories = gettextEnv; size_t firstDot = directories.find(G_SEARCHPATH_SEPARATOR); if (firstDot != std::string::npos) { directories = directories.substr(0, firstDot); } } auto dir = (gettextEnv) ? fs::u8path(directories) : localeDir; g_debug("TEXTDOMAINDIR = %s, Platform-specific locale dir = %s, chosen directory = %s", gettextEnv, localeDir.string().c_str(), dir.string().c_str()); return dir; } auto Util::getAutosaveFilepath() -> fs::path { fs::path p(getCacheSubfolder("autosaves")); p /= std::to_string(getPid()) + ".xopp"; return p; } auto Util::getConfigFolder() -> fs::path { auto p = fs::u8path(g_get_user_config_dir()); return (p /= CONFIG_FOLDER_NAME); } auto Util::getConfigSubfolder(const fs::path& subfolder) -> fs::path { fs::path p = getConfigFolder(); p /= subfolder; return Util::ensureFolderExists(p); } auto Util::getCacheSubfolder(const fs::path& subfolder) -> fs::path { auto p = fs::u8path(g_get_user_cache_dir()); p /= CONFIG_FOLDER_NAME; p /= subfolder; return Util::ensureFolderExists(p); } auto Util::getDataSubfolder(const fs::path& subfolder) -> fs::path { auto p = fs::u8path(g_get_user_data_dir()); p /= CONFIG_FOLDER_NAME; p /= subfolder; return Util::ensureFolderExists(p); } static auto buildUserStateDir() -> fs::path { #if _WIN32 // Windows: state directory is same as data directory return fs::u8path(g_get_user_data_dir()); #else // Unix: $XDG_STATE_HOME or ~/.local/state const char* xdgStateHome = std::getenv("XDG_STATE_HOME"); if (xdgStateHome && xdgStateHome[0]) { // environment variable exists and is non-empty return fs::u8path(xdgStateHome); } auto path = fs::u8path(g_get_home_dir()); return path / ".local/state"; #endif } static auto getUserStateDir() -> const fs::path& { // The GLib function g_get_user_state_dir is not supported on GLib < 2.72, // so we implement our version here. // Cache fs::path so it is only computed once. static std::optional<const fs::path> userStateDir; if (!userStateDir.has_value()) { userStateDir.emplace(buildUserStateDir()); } return *userStateDir; } auto Util::getStateSubfolder(const fs::path& subfolder) -> fs::path { auto p = getUserStateDir(); p /= CONFIG_FOLDER_NAME; p /= subfolder; return Util::ensureFolderExists(p); } auto Util::getConfigFile(const fs::path& relativeFileName) -> fs::path { fs::path p = getConfigSubfolder(relativeFileName.parent_path()); p /= relativeFileName.filename(); return p; } auto Util::getCacheFile(const fs::path& relativeFileName) -> fs::path { fs::path p = getCacheSubfolder(relativeFileName.parent_path()); p /= relativeFileName.filename(); return p; } auto Util::getTmpDirSubfolder(const fs::path& subfolder) -> fs::path { auto p = fs::u8path(g_get_tmp_dir()); p /= FS(_F("xournalpp-{1}") % Util::getPid()); p /= subfolder; return Util::ensureFolderExists(p); } auto Util::ensureFolderExists(const fs::path& p) -> fs::path { try { fs::create_directories(p); } catch (const fs::filesystem_error& fe) { Util::execInUiThread([=]() { std::string msg = FS(_F("Could not create folder: {1}\nFailed with error: {2}") % p.u8string() % fe.what()); XojMsgBox::showErrorToUser(nullptr, msg); }); } return p; } auto Util::isChildOrEquivalent(fs::path const& path, fs::path const& base) -> bool { auto safeCanonical = [](fs::path const& p) { try { return fs::weakly_canonical(p); } catch (const fs::filesystem_error& fe) { g_warning("Util::isChildOrEquivalent: Error resolving paths, failed with %s.\nFalling back to " "lexicographical path", fe.what()); return p; } }; auto relativePath = safeCanonical(path).lexically_relative(safeCanonical(base)); return !relativePath.empty() && *std::begin(relativePath) != ".."; } bool Util::safeRenameFile(fs::path const& from, fs::path const& to) { if (!fs::is_regular_file(from)) { return false; } // Due to https://github.com/xournalpp/xournalpp/issues/1122, // we first attempt to move the file with fs::rename. // If this fails, we then copy and delete the source, as // discussed in the issue // Use target default perms; the source partition may have different file // system attributes than the target, and we don't want anything bad in the // autosave directory // Attempt move try { fs::remove(to); fs::rename(from, to); } catch (const fs::filesystem_error& fe) { // Attempt copy and delete g_warning("Renaming file %s to %s failed with %s. This may happen when source and target are on different " "filesystems. Attempt to copy the file.", fe.path1().string().c_str(), fe.path2().string().c_str(), fe.what()); fs::copy_file(from, to, fs::copy_options::overwrite_existing); fs::remove(from); } return true; } auto Util::getDataPath() -> fs::path { #ifdef _WIN32 TCHAR szFileName[MAX_PATH]; GetModuleFileName(nullptr, szFileName, MAX_PATH); auto exePath = std::string(szFileName); std::string::size_type pos = exePath.find_last_of("\\/"); fs::path p = exePath.substr(0, pos); p = p / ".." / "share" / PROJECT_NAME; return p; #elif defined(__APPLE__) fs::path p = Stacktrace::getExePath().parent_path(); if (fs::exists(p / "Resources")) { p = p / "Resources"; } else { p = PACKAGE_DATA_DIR; p /= PROJECT_NAME; } return p; #else fs::path p = PACKAGE_DATA_DIR; p /= PROJECT_NAME; return p; #endif } auto Util::getLocalePath() -> fs::path { #ifdef __APPLE__ fs::path p = Stacktrace::getExePath().parent_path(); if (fs::exists(p / "Resources")) { return p / "Resources" / "share" / "locale"; } #endif return getDataPath() / ".." / "locale"; } auto Util::getBuiltInPaletteDirectoryPath() -> fs::path { return getDataPath() / "palettes"; } auto Util::getCustomPaletteDirectoryPath() -> fs::path { return getConfigSubfolder("palettes"); } auto Util::listFilesSorted(fs::path directory) -> std::vector<fs::path> { std::vector<fs::path> filePaths{}; if (!exists(directory)) { g_warning("Directory %s does not exist.", directory.u8string().c_str()); return filePaths; } for (const fs::directory_entry& p: fs::directory_iterator(directory)) { filePaths.push_back(p.path()); } std::sort(filePaths.begin(), filePaths.end()); return filePaths; }
12,969
C++
.cpp
340
33.114706
120
0.637817
xournalpp/xournalpp
10,962
791
1,098
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
12,338
gtk4_helper.cpp
xournalpp_xournalpp/src/util/gtk4_helper.cpp
#include "util/gtk4_helper.h" #include <gtk/gtk.h> #include "util/Assert.h" #include "util/raii/CStringWrapper.h" namespace { void set_child(GtkContainer* c, GtkWidget* child) { gtk_container_foreach( c, +[](GtkWidget* child, gpointer c) { gtk_container_remove(GTK_CONTAINER(c), child); }, c); gtk_container_add(c, child); } }; // namespace /**** GtkBox ****/ void gtk_box_append(GtkBox* box, GtkWidget* child) { constexpr auto default_expand = false; gtk_box_pack_start(GTK_BOX(box), child, default_expand, true, 0); } void gtk_box_prepend(GtkBox* box, GtkWidget* child) { gtk_box_append(box, child); gtk_box_reorder_child(box, child, 0); } void gtk_box_remove(GtkBox* box, GtkWidget* child) { gtk_container_remove(GTK_CONTAINER(box), child); } /**** GtkWindow ****/ void gtk_window_destroy(GtkWindow* win) { gtk_widget_destroy(GTK_WIDGET(win)); } /**** GtkWidget ****/ void gtk_widget_add_css_class(GtkWidget* widget, const char* css_class) { gtk_style_context_add_class(gtk_widget_get_style_context(widget), css_class); } void gtk_widget_remove_css_class(GtkWidget* widget, const char* css_class) { gtk_style_context_remove_class(gtk_widget_get_style_context(widget), css_class); } int gtk_widget_get_width(GtkWidget* widget) { GtkAllocation allocation; gtk_widget_get_allocation(widget, &allocation); if (allocation.width <= 1 && allocation.height <= 1) { return 0; } else { return allocation.width; } } GtkClipboard* gtk_widget_get_clipboard(GtkWidget* widget) { return gtk_widget_get_clipboard(widget, GDK_SELECTION_CLIPBOARD); } /*** GtkDrawingArea ****/ void gtk_drawing_area_set_draw_func(GtkDrawingArea* area, GtkDrawingAreaDrawFunc draw_func, gpointer user_data, GDestroyNotify destroy) { xoj_assert(draw_func != nullptr); struct Data { gpointer data; GtkDrawingAreaDrawFunc draw_func; GDestroyNotify destroy; }; Data* data = new Data{user_data, draw_func, destroy}; g_signal_connect_data(area, "draw", G_CALLBACK(+[](GtkDrawingArea* self, cairo_t* cr, Data* d) { GtkAllocation alloc; gtk_widget_get_allocation(GTK_WIDGET(self), &alloc); d->draw_func(self, cr, alloc.width, alloc.height, d->data); }), data, GClosureNotify(+[](gpointer d, GClosure*) { auto* data = static_cast<Data*>(d); if (data && data->destroy) { data->destroy(data->data); } delete data; }), GConnectFlags(0U)); // 0 = G_CONNECT_DEFAULT only introduced in GObject 2.74 } /**** GtkScale ****/ void gtk_scale_set_format_value_func(GtkScale* scale, GtkScaleFormatValueFunc func, gpointer user_data, GDestroyNotify destroy_notify) { xoj_assert(func != nullptr); struct Data { gpointer data; GtkScaleFormatValueFunc func; GDestroyNotify destroy; }; Data* data = new Data{user_data, func, destroy_notify}; g_signal_connect_data(scale, "format-value", G_CALLBACK(+[](GtkScale* self, gdouble value, gpointer user_data) { auto* data = static_cast<Data*>(user_data); return data->func(self, value, data->data); }), data, GClosureNotify(+[](gpointer d, GClosure*) { auto* data = static_cast<Data*>(d); if (data && data->destroy) { data->destroy(data->data); } delete data; }), GConnectFlags(0U)); // 0 = G_CONNECT_DEFAULT only introduced in GObject 2.74 } /**** GtkScrolledWindow ****/ GtkWidget* gtk_scrolled_window_new() { return gtk_scrolled_window_new(nullptr, nullptr); } void gtk_scrolled_window_set_child(GtkScrolledWindow* win, GtkWidget* child) { set_child(GTK_CONTAINER(win), child); } GtkWidget* gtk_scrolled_window_get_child(GtkScrolledWindow* win) { return gtk_bin_get_child(GTK_BIN(win)); } /**** GtkCheckButton ****/ void gtk_check_button_set_child(GtkCheckButton* button, GtkWidget* child) { set_child(GTK_CONTAINER(button), child); } void gtk_check_button_set_label(GtkCheckButton* button, const char* label) { gtk_check_button_set_child(GTK_CHECK_BUTTON(button), gtk_label_new(label)); } bool gtk_check_button_get_active(GtkCheckButton* bt) { return gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(bt)); } void gtk_check_button_set_active(GtkCheckButton* bt, bool state) { gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(bt), state); } /**** GtkButton ****/ void gtk_button_set_child(GtkButton* button, GtkWidget* child) { set_child(GTK_CONTAINER(button), child); } GtkWidget* gtk_button_get_child(GtkButton* button) { return gtk_bin_get_child(GTK_BIN(button)); } void gtk_button_set_icon_name(GtkButton* button, const char* iconName) { // Is GTK_ICON_SIZE_LARGE_TOOLBAR i the right size?? gtk_button_set_image(button, gtk_image_new_from_icon_name(iconName, GTK_ICON_SIZE_LARGE_TOOLBAR)); } /**** GtkPopover ****/ GtkWidget* gtk_popover_new() { return gtk_popover_new(nullptr); } void gtk_popover_set_child(GtkPopover* popover, GtkWidget* child) { set_child(GTK_CONTAINER(popover), child); } GtkWidget* gtk_popover_menu_new_from_model(GMenuModel* model) { return gtk_popover_new_from_model(nullptr, model); } /**** GtkLabel ****/ void gtk_label_set_wrap(GtkLabel* label, gboolean wrap) { gtk_label_set_line_wrap(label, wrap); } void gtk_label_set_wrap_mode(GtkLabel* label, PangoWrapMode wrap_mode) { gtk_label_set_line_wrap_mode(label, wrap_mode); } /**** GtkIMContext ****/ void gtk_im_context_set_client_widget(GtkIMContext* context, GtkWidget* widget) { gtk_im_context_set_client_window(context, widget ? gtk_widget_get_parent_window(widget) : nullptr); } /**** GtkFileChooserDialog ****/ gboolean gtk_file_chooser_add_shortcut_folder(GtkFileChooser* chooser, GFile* file, GError** error) { auto uri = xoj::util::OwnedCString::assumeOwnership(g_file_get_uri(file)); return gtk_file_chooser_add_shortcut_folder(chooser, uri.get(), error); } gboolean gtk_file_chooser_set_current_folder(GtkFileChooser* chooser, GFile* file, GError** error) { return gtk_file_chooser_set_current_folder_file(chooser, file, error); } /**** GtkFixed ****/ void gtk_fixed_remove(GtkFixed* fixed, GtkWidget* child) { gtk_container_remove(GTK_CONTAINER(fixed), child); } /**** GtkListBox ****/ void gtk_list_box_append(GtkListBox* box, GtkWidget* widget) { gtk_container_add(GTK_CONTAINER(box), widget); } void gtk_list_box_row_set_child(GtkListBoxRow* row, GtkWidget* w) { set_child(GTK_CONTAINER(row), w); } GtkWidget* gtk_list_box_row_get_child(GtkListBoxRow* row) { return gtk_bin_get_child(GTK_BIN(row)); } /**** GtkEventController ****/ GdkEvent* gtk_event_controller_get_current_event(GtkEventController*) { return gtk_get_current_event(); }
7,302
C++
.cpp
138
44.789855
118
0.646184
xournalpp/xournalpp
10,962
791
1,098
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
12,339
NamedColor.cpp
xournalpp_xournalpp/src/util/NamedColor.cpp
#include "util/NamedColor.h" #include <cstdint> // for uint16_t, uint8_t #include <sstream> // for istringstream, basic_istream, basic_i... #include <stdexcept> // for invalid_argument #include <utility> // for move #include "util/StringUtils.h" // for StringUtils #include "util/i18n.h" // for fetch_translation #include "util/serdesstream.h" // for serdes_stream NamedColor::NamedColor(): paletteIndex{0}, name{"Custom Color"}, colorU16{ColorU16{}}, color{Color(0u)}, isPaletteColor{false} {} NamedColor::NamedColor(size_t paletteIndex): paletteIndex{paletteIndex}, name{"Fallback Color"}, colorU16{ColorU16{}}, color{Color(0u)}, isPaletteColor{true} {} NamedColor::NamedColor(Color color): paletteIndex{0}, name{"Custom Color"}, colorU16(Util::argb_to_ColorU16(color)), color(color), isPaletteColor{false} {}; auto operator>>(std::istream& str, NamedColor& namedColor) -> std::istream& { std::string line; NamedColor tmp; if (std::getline(str, line)) { auto iss = serdes_stream<std::istringstream>(line); uint16_t r{}, g{}, b{}; if (iss >> r >> g >> b && std::getline(iss, tmp.name)) { if (r > 255 || g > 255 || b > 255) { throw std::invalid_argument("RGB values bigger than 255 are not supported."); } tmp.color = Color(uint8_t(r), uint8_t(g), uint8_t(b)); tmp.name = fetch_translation_context("Color", StringUtils::trim(tmp.name).c_str()); tmp.colorU16 = Util::argb_to_ColorU16(tmp.color); tmp.isPaletteColor = true; tmp.paletteIndex = namedColor.paletteIndex; // All read operations worked namedColor = std::move(tmp); } else { /* * One operation failed. * So set the state on the main stream * to indicate failure. */ str.setstate(std::ios::failbit); } } return str; } auto NamedColor::getColorU16() const -> ColorU16 { return colorU16; } auto NamedColor::getColor() const -> Color { return color; } auto NamedColor::getIndex() const -> size_t { return paletteIndex; }; auto NamedColor::getName() const -> std::string const& { return name; };
2,331
C++
.cpp
54
35.518519
111
0.609885
xournalpp/xournalpp
10,962
791
1,098
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
12,340
PlaceholderString.cpp
xournalpp_xournalpp/src/util/PlaceholderString.cpp
#include "util/PlaceholderString.h" #include <exception> // for exception #include <glib.h> // for g_error #include "util/safe_casts.h" // for as_unsigned /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// PlaceholderString::PlaceholderString(std::string text): text(std::move(text)) {} auto PlaceholderString::formatPart(std::string format) const -> std::string { std::string formatDef; std::size_t comma = format.find(','); if (comma != std::string::npos) { formatDef = format.substr(comma + 1); format = format.substr(0, comma); } int index = 0; try { index = std::stoi(format); } catch (const std::exception& e) { g_error("Could not parse \"%s\" as int, error: %s", format.c_str(), e.what()); } // Placeholder index starting at 1, vector at 0 index--; if (index < 0 || index >= static_cast<int>(data.size())) { std::string notFound = "{"; notFound += std::to_string(index + 1); notFound += "}"; return notFound; } auto const& pe = data[as_unsigned(index)]; return pe->format(formatDef); } void PlaceholderString::process() const { if (!processed.empty()) { return; } bool openBracket = false; bool closeBacket = false; std::string formatString; // Should work, also for UTF-8 for (char c: text) { if (c == '{') { closeBacket = false; if (openBracket) { openBracket = false; processed += '{'; continue; } openBracket = true; continue; } if (c == '}') { if (closeBacket) { processed += '}'; closeBacket = false; continue; } closeBacket = true; if (openBracket) { processed += formatPart(formatString); openBracket = false; formatString = ""; } continue; } if (openBracket) { formatString += c; continue; } closeBacket = false; processed += c; } } auto PlaceholderString::str() const -> std::string { process(); return processed; } auto PlaceholderString::c_str() const -> const char* { process(); return processed.c_str(); } auto operator<<(std::ostream& os, PlaceholderString& ps) -> std::ostream& { return os << ps.str(); }
2,683
C++
.cpp
82
24.853659
100
0.492242
xournalpp/xournalpp
10,962
791
1,098
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
12,341
Color.cpp
xournalpp_xournalpp/src/util/Color.cpp
#include "util/Color.h" #include <algorithm> // for max, min #include <iomanip> // for operator<<, setfill, setw #include <sstream> // for operator<<, stringstream, basic_ostream, char_t... #include "util/Assert.h" // for xoj_assert #include "util/serdesstream.h" // for serdes_stream float Util::as_grayscale_color(Color color) { GdkRGBA components = rgb_to_GdkRGBA(color); float componentAvg = static_cast<float>(components.red + components.green + components.blue) / 3.0f; return componentAvg; } float Util::get_color_contrast(Color color1, Color color2) { float grayscale1 = as_grayscale_color(color1); float grayscale2 = as_grayscale_color(color2); return std::max(grayscale1, grayscale2) - std::min(grayscale1, grayscale2); } auto Util::rgb_to_hex_string(Color rgb) -> std::string { auto s = serdes_stream<std::ostringstream>(); auto tmp_color = rgb; tmp_color.alpha = 0; s << "#" << std::hex << std::setfill('0') << std::setw(6) << std::right << tmp_color; return s.str(); }
1,043
C++
.cpp
23
42.086957
104
0.688735
xournalpp/xournalpp
10,962
791
1,098
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
12,342
XojPreviewExtractor.cpp
xournalpp_xournalpp/src/util/XojPreviewExtractor.cpp
#include "util/XojPreviewExtractor.h" #include <array> // for array #include <cstring> // for strlen, strncmp #include <string> // for allocator, string #include <glib.h> // for g_free, g_base64_decode, g_malloc, gsize #include <zip.h> // for zip_close, zip_fclose, zip_stat_t, zip_fopen #include <zipconf.h> // for zip_int64_t, zip_uint64_t #include <zlib.h> // for gzclose, gzread, gzFile #include "util/GzUtil.h" // for GzUtil #include "util/PathUtil.h" // for hasXournalFileExt #include "util/safe_casts.h" // for as_signed #include "filesystem.h" // for path const char* TAG_PREVIEW_NAME = "preview"; const size_t TAG_PREVIEW_NAME_LEN = strlen(TAG_PREVIEW_NAME); const char* TAG_PAGE_NAME = "page"; const size_t TAG_PAGE_NAME_LEN = strlen(TAG_PAGE_NAME); const char* TAG_PREVIEW_END_NAME = "/preview"; const size_t TAG_PREVIEW_END_NAME_LEN = strlen(TAG_PREVIEW_END_NAME); // max png size is: (1.02*(3*128+1)*128)+68 approx 50334 // see https://stackoverflow.com/a/22507715/2907484 // max base64-overhead is ceil(50334/3)*4 = 67112 // see https://stackoverflow.com/a/4715480/2907484 // round it up a bit constexpr auto BUF_SIZE = 68000; XojPreviewExtractor::XojPreviewExtractor() = default; XojPreviewExtractor::~XojPreviewExtractor() { g_free(data); data = nullptr; dataLen = 0; } /** * @return The preview data, should be a binary PNG */ auto XojPreviewExtractor::getData(gsize& dataLen) -> unsigned char* { dataLen = this->dataLen; return this->data; } /** * Try to read the preview from byte buffer * @param buffer Buffer * @param len Buffer len * @return If an image was read, or the error */ auto XojPreviewExtractor::readPreview(char* buffer, int len) -> PreviewExtractResult { bool inTag = false; int startTag = 0; int startPreview = -1; int endPreview = -1; int pageStart = -1; for (int i = 0; i < len; i++) { if (inTag) { if (buffer[i] == '>') { inTag = false; int tagLen = i - startTag; if (tagLen == as_signed(TAG_PREVIEW_NAME_LEN) && strncmp(TAG_PREVIEW_NAME, buffer + startTag, TAG_PREVIEW_NAME_LEN) == 0) { startPreview = i + 1; } if (tagLen == as_signed(TAG_PREVIEW_END_NAME_LEN) && strncmp(TAG_PREVIEW_END_NAME, buffer + startTag, TAG_PREVIEW_END_NAME_LEN) == 0) { endPreview = i - static_cast<int>(TAG_PREVIEW_END_NAME_LEN) - 1; break; } if (tagLen >= as_signed(TAG_PAGE_NAME_LEN) && strncmp(TAG_PAGE_NAME, buffer + startTag, TAG_PAGE_NAME_LEN) == 0) { pageStart = i; break; } } continue; } if (buffer[i] == '<') { inTag = true; startTag = i + 1; continue; } } if (startPreview != -1 && endPreview != -1) { buffer[endPreview] = 0; this->data = g_base64_decode(buffer + startPreview, &dataLen); return PREVIEW_RESULT_IMAGE_READ; } if (pageStart != -1) { return PREVIEW_RESULT_NO_PREVIEW; } return PREVIEW_RESULT_ERROR_READING_PREVIEW; } /** * Try to read the preview from file * @param file .xoj File * @return true if a preview was read, false if not */ auto XojPreviewExtractor::readFile(const fs::path& file) -> PreviewExtractResult { // check file extensions if (!Util::hasXournalFileExt(file)) { return PREVIEW_RESULT_BAD_FILE_EXTENSION; } // read the new file format int zipError = 0; zip_t* zipFp = zip_open(file.u8string().c_str(), ZIP_RDONLY, &zipError); if (!zipFp && zipError == ZIP_ER_NOZIP) { gzFile fp = GzUtil::openPath(file, "r"); if (!fp) { return PREVIEW_RESULT_COULD_NOT_OPEN_FILE; } // The <preview> Tag is within the first 179 Bytes std::array<char, BUF_SIZE> buffer{}; int readLen = gzread(fp, buffer.data(), BUF_SIZE); PreviewExtractResult result = readPreview(buffer.data(), readLen); gzclose(fp); return result; } if (!zipFp) { return PREVIEW_RESULT_COULD_NOT_OPEN_FILE; } zip_stat_t thumbStat; int statStatus = zip_stat(zipFp, "thumbnails/thumbnail.png", 0, &thumbStat); if (statStatus != 0) { zip_close(zipFp); return PREVIEW_RESULT_NO_PREVIEW; } if (thumbStat.valid & ZIP_STAT_SIZE) { dataLen = thumbStat.size; } else { zip_close(zipFp); return PREVIEW_RESULT_ERROR_READING_PREVIEW; } zip_file_t* thumb = zip_fopen(zipFp, "thumbnails/thumbnail.png", 0); if (!thumb) { zip_close(zipFp); return PREVIEW_RESULT_ERROR_READING_PREVIEW; } data = static_cast<unsigned char*>(g_malloc(thumbStat.size)); zip_uint64_t readBytes = 0; while (readBytes < dataLen) { zip_int64_t read = zip_fread(thumb, data, thumbStat.size); if (read == -1) { g_free(data); zip_fclose(thumb); zip_close(zipFp); return PREVIEW_RESULT_ERROR_READING_PREVIEW; } readBytes += static_cast<zip_uint64_t>(read); } zip_fclose(thumb); zip_close(zipFp); return PREVIEW_RESULT_IMAGE_READ; }
5,400
C++
.cpp
148
29.594595
102
0.606466
xournalpp/xournalpp
10,962
791
1,098
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
12,343
Util.cpp
xournalpp_xournalpp/src/util/Util.cpp
#include "util/Util.h" #include <array> // for array #include <cstdlib> // for system #include <string> // for allocator, string #include <utility> // for move #include <vector> // for vector #include <gdk/gdk.h> // for gdk_cairo_set_source_rgba, gdk_t... #include "util/Color.h" // for argb_to_GdkRGBA, rgb_to_GdkRGBA #include "util/OutputStream.h" // for OutputStream #include "util/PlaceholderString.h" // for PlaceholderString #include "util/XojMsgBox.h" // for XojMsgBox #include "util/i18n.h" // for FS, _F #if defined(_MSC_VER) #include <windows.h> #else #include <unistd.h> // for getpid, pid_t #endif void Util::cairo_set_source_rgbi(cairo_t* cr, Color color, double alpha) { auto rgba = argb_to_GdkRGBA(color, alpha); gdk_cairo_set_source_rgba(cr, &rgba); } void Util::cairo_set_source_argb(cairo_t* cr, Color color) { auto rgba = argb_to_GdkRGBA(color); gdk_cairo_set_source_rgba(cr, &rgba); } auto Util::getPid() -> PID { #if defined(_MSC_VER) return GetCurrentProcessId(); #else return ::getpid(); #endif } auto Util::paintBackgroundWhite(GtkWidget* widget, cairo_t* cr, void*) -> gboolean { GtkAllocation alloc; gtk_widget_get_allocation(widget, &alloc); cairo_set_source_rgb(cr, 1, 1, 1); cairo_rectangle(cr, 0, 0, alloc.width, alloc.height); cairo_fill(cr); return false; } xoj::util::Point<double> Util::toWidgetCoords(GtkWidget* widget, xoj::util::Point<double> absolute_coords) { int rx, ry; // X11 uses absolute screen coordinates while Wayland uses absolute window coordinates. // Converting them to widget-local coordinates will cancel out this difference. // `gtk_widget_get_window` doesn't return the actual window, but the local widget-window. // GTK4 renames `gdk_window_get_root_coords()` to `gdk_surface_get_root_coords()` gdk_window_get_root_coords(gtk_widget_get_window(widget), 0, 0, &rx, &ry); return xoj::util::Point<double>{absolute_coords.x - rx, absolute_coords.y - ry}; } void Util::cairo_set_dash_from_vector(cairo_t* cr, const std::vector<double>& dashes, double offset) { cairo_set_dash(cr, dashes.data(), static_cast<int>(dashes.size()), offset); } void Util::writeCoordinateString(OutputStream* out, double xVal, double yVal) { std::array<char, G_ASCII_DTOSTR_BUF_SIZE> coordString{}; g_ascii_formatd(coordString.data(), G_ASCII_DTOSTR_BUF_SIZE, Util::PRECISION_FORMAT_STRING, xVal); out->write(coordString.data()); out->write(" "); g_ascii_formatd(coordString.data(), G_ASCII_DTOSTR_BUF_SIZE, Util::PRECISION_FORMAT_STRING, yVal); out->write(coordString.data()); } void Util::systemWithMessage(const char* command) { if (auto errc = std::system(command); errc != 0) { std::string msg = FS(_F("Error {1} executing system command: {2}") % errc % command); XojMsgBox::showErrorToUser(nullptr, msg); } } bool Util::isFlatpakInstallation() { return fs::exists("/.flatpak-info"); }
3,015
C++
.cpp
67
41.880597
108
0.693252
xournalpp/xournalpp
10,962
791
1,098
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
12,344
GzUtil.cpp
xournalpp_xournalpp/src/util/GzUtil.cpp
#include "util/GzUtil.h" auto GzUtil::openPath(const fs::path& path, const std::string& flags) -> gzFile { #ifdef _WIN32 gzFile fp = gzopen_w(path.c_str(), flags.c_str()); return fp; #else return gzopen(path.c_str(), flags.c_str()); #endif }
256
C++
.cpp
9
25.888889
81
0.669388
xournalpp/xournalpp
10,962
791
1,098
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
12,345
gdk4_helper.cpp
xournalpp_xournalpp/src/util/gdk4_helper.cpp
#include "util/gdk4_helper.h" #include "util/Assert.h" /*** GdkEvent ***/ GdkModifierType gdk_event_get_modifier_state(GdkEvent* event) { GdkModifierType state; gdk_event_get_state(event, &state); return state; } /*** GdkKeyEvent ***/ GdkModifierType gdk_key_event_get_consumed_modifiers(GdkEvent* event) { auto keymap = gdk_keymap_get_for_display(gdk_display_get_default()); GdkModifierType consumed; /* According to https://docs.gtk.org/gdk3/method.Keymap.translate_keyboard_state.html * * consumed modifiers should be masked out. For instance, on a US keyboard, the plus symbol is shifted, so when comparing a key press to a <Control>plus accelerator <Shift> should be masked out. */ gdk_keymap_translate_keyboard_state(keymap, event->key.hardware_keycode, static_cast<GdkModifierType>(event->key.state), event->key.group, nullptr, nullptr, nullptr, &consumed); return consumed; } guint gdk_key_event_get_keyval(GdkEvent* event) { guint res = 0; gdk_event_get_keyval(event, &res); return res; }
1,151
C++
.cpp
27
36.111111
114
0.675603
xournalpp/xournalpp
10,962
791
1,098
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
12,346
Stacktrace.cpp
xournalpp_xournalpp/src/util/Stacktrace.cpp
#include "util/Stacktrace.h" #include <algorithm> // for max #include <array> // for array #include <cerrno> // for errno #include <cstdint> // for uintptr_t #include <cstdio> // for fgets, pclose, popen, snprintf, FILE #include <cstring> // for strerror #include <iostream> // for operator<<, basic_ostream, basic_ostream::... #include <string> // for string #include "util/safe_casts.h" // for bit_cast #ifdef _WIN32 #include <Windows.h> #else #include <dlfcn.h> // for dladdr #include <execinfo.h> // for backtrace, backtrace_symbols #include <unistd.h> // for readlink, ssize_t #ifdef __APPLE__ #include <glib.h> #include <mach-o/dyld.h> #else #include <climits> // for PATH_MAX #endif #endif using std::endl; /** * This code uses addr2line * * Another solution would be backtrace-symbols.c from cairo/util, but its really complicated */ Stacktrace::Stacktrace() = default; Stacktrace::~Stacktrace() = default; #ifdef _WIN32 fs::path Stacktrace::getExePath() { char szFileName[MAX_PATH + 1]; GetModuleFileNameA(nullptr, szFileName, MAX_PATH + 1); return fs::path{szFileName}; } void Stacktrace::printStacktrace(std::ostream& stream) { // Stacktrace is currently not implemented for Windows // Currently this is only needed for developing, so this is no issue } #else #ifdef __APPLE__ #include "filesystem.h" fs::path Stacktrace::getExePath() { char c; uint32_t size = 0; _NSGetExecutablePath(&c, &size); char* path = new char[size + 1]; if (_NSGetExecutablePath(path, &size) == 0) { fs::path p(path); delete[] path; return p.parent_path(); } g_error("Could not executable path!"); delete[] path; return ""; } #else auto Stacktrace::getExePath() -> fs::path { #ifndef PATH_MAX // This is because PATH_MAX is (per posix) not defined if there is // no limit, e.g., on GNU Hurd. The "right" workaround is to not use // PATH_MAX, instead stat the link and use stat.st_size for // allocating the buffer. #define PATH_MAX 4096 #endif std::array<char, PATH_MAX> result{}; ssize_t count = readlink("/proc/self/exe", result.data(), PATH_MAX); return fs::path{std::string(result.data(), as_unsigned(std::max(ssize_t{0}, count)))}; } #endif void Stacktrace::printStacktrace(std::ostream& stream) { std::array<void*, 32> trace{}; std::array<char, 2048> buff{}; int trace_size = backtrace(trace.data(), trace.size()); char** messages = backtrace_symbols(trace.data(), trace_size); // skip first stack frame (points here) for (unsigned int i = 1; as_signed(i) < trace_size; ++i) { stream << "[bt] #" << i - 1 << " " << messages[i] << endl; Dl_info info; // NOLINT(cppcoreguidelines-init-variables) dladdr(trace[i], &info); std::array<char, 1024> syscom{}; // Todo (cpp20): use std::format instead of snprintf snprintf(syscom.data(), syscom.size(), "addr2line %lx -fCpe \"%s\"", xoj::util::bit_cast<std::uintptr_t>(trace[i]) - xoj::util::bit_cast<std::uintptr_t>(info.dli_fbase), info.dli_fname); FILE* fProc = popen(syscom.data(), "r"); if (fProc != nullptr) { while (fgets(buff.data(), buff.size(), fProc) != nullptr) { stream << buff.data(); } pclose(fProc); } else { stream << "failed to invoke addr2line: " << std::strerror(errno); } } free(messages); } #endif void Stacktrace::printStacktrace() { printStacktrace(std::cerr); }
3,607
C++
.cpp
101
31.257426
117
0.640414
xournalpp/xournalpp
10,962
791
1,098
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
12,347
XojMsgBox.cpp
xournalpp_xournalpp/src/util/XojMsgBox.cpp
#include "util/XojMsgBox.h" #include <utility> // for move #include <glib-object.h> // for g_object_set_property, g_value_init, g_valu... #include <glib.h> // for g_free, g_markup_escape_text, g_error_free #include "util/PopupWindowWrapper.h" #include "util/Util.h" #include "util/gtk4_helper.h" #include "util/i18n.h" // for _, FS, _F #include "util/raii/CStringWrapper.h" #ifdef _WIN32 // Needed for help dialog workaround on Windows; see XojMsgBox::showHelp #include <windows.h> // <windows.h> must be included first #include <shellapi.h> // for ShellExecute #endif GtkWindow* defaultWindow = nullptr; XojMsgBox::XojMsgBox(GtkDialog* dialog, xoj::util::move_only_function<void(int)> callback, CallbackPolicy pol): window(reinterpret_cast<GtkWindow*>(dialog)), callback(std::move(callback)), policy(pol) { this->signalId = g_signal_connect(dialog, "response", G_CALLBACK(+[](GtkDialog* dialog, int response, gpointer data) { auto* self = static_cast<XojMsgBox*>(data); if (self->policy == IMMEDIATE) { self->callback(response); } else { // POSTPONED // We sometimes need to call gtk_window_close() before invoking the callback, // because if the callback pops up another dialog, the first one won't close... // But since gtk_window_close() triggers the destruction of *self, we first move // the callback Util::execInUiThread([cb = std::move(self->callback), r = response]() { cb(r); }); } // Closing the window causes another "response" signal, which we want to ignore g_signal_handler_disconnect(dialog, self->signalId); gtk_window_close(self->getWindow()); // Destroys *self. Beware! }), this); } /** * Set window for messages without window */ void XojMsgBox::setDefaultWindow(GtkWindow* win) { defaultWindow = win; } void XojMsgBox::showMarkupMessageToUser(GtkWindow* win, const std::string_view& markupTitle, const std::string& msg, GtkMessageType type) { if (win == nullptr) { win = defaultWindow; } GtkWidget* dialog = gtk_message_dialog_new_with_markup(win, GTK_DIALOG_MODAL, type, GTK_BUTTONS_OK, nullptr); gtk_message_dialog_set_markup(GTK_MESSAGE_DIALOG(dialog), markupTitle.data()); if (!msg.empty()) { gtk_message_dialog_format_secondary_text(GTK_MESSAGE_DIALOG(dialog), "%s", msg.c_str()); } xoj::popup::PopupWindowWrapper<XojMsgBox> popup(GTK_DIALOG(dialog)); popup.show(win); } void XojMsgBox::showMessageToUser(GtkWindow* win, const std::string& title, const std::string& msg, GtkMessageType type) { auto escapedTitle = xoj::util::OwnedCString::assumeOwnership(g_markup_escape_text(title.c_str(), -1)); showMarkupMessageToUser(win, escapedTitle.get(), msg, type); } void XojMsgBox::showMessageToUser(GtkWindow* win, const std::string& msg, GtkMessageType type) { showMessageToUser(win, msg, std::string(), type); } void XojMsgBox::showErrorToUser(GtkWindow* win, const std::string& msg) { showMessageToUser(win, msg, GTK_MESSAGE_ERROR); g_warning("%s", msg.c_str()); } void XojMsgBox::askQuestion(GtkWindow* win, const std::string& maintext, const std::string& secondarytext, const std::vector<Button>& buttons, xoj::util::move_only_function<void(int)> callback) { auto formattedMsg = xoj::util::OwnedCString::assumeOwnership(g_markup_escape_text(maintext.c_str(), -1)); askQuestionWithMarkup(win, std::string_view(formattedMsg), secondarytext, buttons, std::move(callback)); } void XojMsgBox::askQuestionWithMarkup(GtkWindow* win, std::string_view maintext, const std::string& secondarytext, const std::vector<Button>& buttons, xoj::util::move_only_function<void(int)> callback) { if (win == nullptr) { win = defaultWindow; } GtkWidget* dialog = gtk_message_dialog_new_with_markup(win, GTK_DIALOG_MODAL, GTK_MESSAGE_QUESTION, GTK_BUTTONS_NONE, nullptr); for (auto& b: buttons) { gtk_dialog_add_button(GTK_DIALOG(dialog), b.label.c_str(), b.response); } gtk_message_dialog_set_markup(GTK_MESSAGE_DIALOG(dialog), maintext.data()); gtk_message_dialog_format_secondary_text(GTK_MESSAGE_DIALOG(dialog), "%s", secondarytext.c_str()); xoj::popup::PopupWindowWrapper<XojMsgBox> popup(GTK_DIALOG(dialog), std::move(callback)); popup.show(win); } void XojMsgBox::showErrorAndQuit(std::string& msg, int exitCode) { GtkWidget* dialog = gtk_message_dialog_new_with_markup(defaultWindow, GTK_DIALOG_MODAL, GTK_MESSAGE_ERROR, GTK_BUTTONS_OK, nullptr); gtk_message_dialog_set_markup(GTK_MESSAGE_DIALOG(dialog), msg.c_str()); // We use a hack to ensure the app does not exit until the user has read the error message and closed the popup bool done = false; xoj::popup::PopupWindowWrapper<XojMsgBox> popup(GTK_DIALOG(dialog), [&done](int) { done = true; }); popup.show(defaultWindow); while (!done) { // Let the main loop run so the popup pops up and can be interacted with g_main_context_iteration(g_main_context_default(), true); } exit(exitCode); } void XojMsgBox::showPluginMessage(const std::string& pluginName, const std::string& msg, bool error) { auto header = std::string("Xournal++ Plugin «") + pluginName + "»"; auto escapedHeader = xoj::util::OwnedCString::assumeOwnership(g_markup_escape_text(header.c_str(), -1)); header = (error ? std::string("<b>Error in </b>") : "") + escapedHeader.get(); showMarkupMessageToUser(nullptr, header, msg, error ? GTK_MESSAGE_ERROR : GTK_MESSAGE_INFO); } auto XojMsgBox::askPluginQuestion(const std::string& pluginName, const std::string& msg, const std::vector<Button>& buttons, bool error) -> int { /* * Todo(gtk4): Remove this function entirely. */ std::string header = "<i>Warning: The plugin interface function msgbox() is deprecated and will soon be removed. " "Please adapt your plugin to use the function openDialog() instead</i>\n\n"; header += (error ? std::string("<b>Error in </b>") : "") + std::string("Xournal++ Plugin «") + pluginName + "»"; GtkWidget* dialog = gtk_message_dialog_new_with_markup(defaultWindow, GTK_DIALOG_MODAL, error ? GTK_MESSAGE_ERROR : GTK_MESSAGE_QUESTION, GTK_BUTTONS_NONE, nullptr); gtk_message_dialog_set_markup(GTK_MESSAGE_DIALOG(dialog), header.c_str()); if (defaultWindow != nullptr) { gtk_window_set_transient_for(GTK_WINDOW(dialog), defaultWindow); } GValue val = G_VALUE_INIT; g_value_init(&val, G_TYPE_STRING); g_value_set_string(&val, msg.c_str()); g_object_set_property(G_OBJECT(dialog), "secondary-text", &val); g_value_unset(&val); for (auto& b: buttons) { gtk_dialog_add_button(GTK_DIALOG(dialog), b.label.c_str(), b.response); } int res = gtk_dialog_run(GTK_DIALOG(dialog)); gtk_widget_destroy(dialog); return res; } void XojMsgBox::replaceFileQuestion(GtkWindow* win, fs::path file, xoj::util::move_only_function<void(const fs::path&)> writeTofile) { if (!fs::exists(file)) { writeTofile(file); return; } GtkWidget* dialog = gtk_message_dialog_new( win, GTK_DIALOG_MODAL, GTK_MESSAGE_QUESTION, GTK_BUTTONS_NONE, "%s", FS(FORMAT_STR("The file {1} already exists! Do you want to replace it?") % file.filename().u8string()) .c_str()); if (win != nullptr) { gtk_window_set_transient_for(GTK_WINDOW(dialog), win); } gtk_dialog_add_button(GTK_DIALOG(dialog), _("Select another name"), GTK_RESPONSE_CANCEL); gtk_dialog_add_button(GTK_DIALOG(dialog), _("Replace"), GTK_RESPONSE_OK); xoj::popup::PopupWindowWrapper<XojMsgBox> popup( GTK_DIALOG(dialog), [overwrite = std::move(writeTofile), file = std::move(file)](int response) mutable { if (response == GTK_RESPONSE_OK) { overwrite(file); } }); popup.show(win); } constexpr auto* XOJ_HELP = "https://xournalpp.github.io/community/help/"; void XojMsgBox::showHelp(GtkWindow* win) { #ifdef _WIN32 // gvfs is not in MSYS repositories, so we can't use gtk_show_uri. // Instead, we use the native API instead. ShellExecute(nullptr, "open", XOJ_HELP, nullptr, nullptr, SW_SHOW); #else GError* error = nullptr; gtk_show_uri(gtk_window_get_screen(win), XOJ_HELP, gtk_get_current_event_time(), &error); if (error) { std::string msg = FS(_F("There was an error displaying help: {1}") % error->message); XojMsgBox::showErrorToUser(win, msg); g_error_free(error); } #endif }
9,498
C++
.cpp
172
45.069767
119
0.623531
xournalpp/xournalpp
10,962
791
1,098
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
12,348
ObjectOutputStream.cpp
xournalpp_xournalpp/src/util/serializing/ObjectOutputStream.cpp
#include "util/serializing/ObjectOutputStream.h" #include <cairo.h> // for CAIRO_STATUS_SUCCESS #include "util/Assert.h" // for xoj_assert #include "util/serializing/ObjectEncoding.h" // for ObjectEncoding #include "util/serializing/Serializable.h" // for XML_VERSION_STR ObjectOutputStream::ObjectOutputStream(ObjectEncoding* encoder) { xoj_assert(encoder != nullptr); this->encoder = encoder; writeString(XML_VERSION_STR); } ObjectOutputStream::~ObjectOutputStream() { delete this->encoder; this->encoder = nullptr; } void ObjectOutputStream::writeObject(const char* name) { this->encoder->addStr("_{"); writeString(name); } void ObjectOutputStream::endObject() { this->encoder->addStr("_}"); } void ObjectOutputStream::writeInt(int i) { this->encoder->addStr("_i"); this->encoder->addData(&i, sizeof(int)); } void ObjectOutputStream::writeUInt(uint32_t u) { this->encoder->addStr("_u"); this->encoder->addData(&u, sizeof(uint32_t)); } void ObjectOutputStream::writeDouble(double d) { this->encoder->addStr("_d"); this->encoder->addData(&d, sizeof(double)); } void ObjectOutputStream::writeSizeT(size_t st) { this->encoder->addStr("_l"); this->encoder->addData(&st, sizeof(size_t)); } void ObjectOutputStream::writeString(const char* str) { writeString(std::string(str)); } void ObjectOutputStream::writeString(const std::string& s) { this->encoder->addStr("_s"); size_t len = s.length(); this->encoder->addData(&len, sizeof(size_t)); this->encoder->addData(s.c_str(), len); } void ObjectOutputStream::writeData(const void* data, size_t len, size_t width) { this->encoder->addStr("_b"); this->encoder->addData(&len, sizeof(size_t)); // size of one element this->encoder->addData(&width, sizeof(size_t)); if (data != nullptr) { this->encoder->addData(data, len * width); } } void ObjectOutputStream::writeImage(const std::string_view& imgData) { this->encoder->addStr("_m"); size_t len = imgData.length(); this->encoder->addData(&len, sizeof(size_t)); this->encoder->addData(imgData.data(), len); } auto ObjectOutputStream::getStr() -> GString* { return this->encoder->getData(); }
2,251
C++
.cpp
58
35.362069
88
0.692414
xournalpp/xournalpp
10,962
791
1,098
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
12,349
ObjectInputStream.cpp
xournalpp_xournalpp/src/util/serializing/ObjectInputStream.cpp
#include "util/serializing/ObjectInputStream.h" #include <cstdint> // for uint32_t #include <glib.h> // for g_free, g_strdup_... #include "util/PlaceholderString.h" // for PlaceholderString #include "util/i18n.h" // for FORMAT_STR, FS #include "util/safe_casts.h" // for as_signed #include "util/serializing/InputStreamException.h" // for InputStreamException #include "util/serializing/Serializable.h" // for XML_VERSION_STR template size_t ObjectInputStream::readType<size_t>(); // This function requires that T is read from its binary representation to work (e.g. integer type) template <typename T> T ObjectInputStream::readType() { if (istream.str().size() < sizeof(T)) { std::ostringstream oss; oss << "End reached: trying to read " << sizeof(T) << " bytes while only " << istream.str().size() << " bytes available"; throw InputStreamException(oss.str(), __FILE__, __LINE__); } T output; istream.read((char*)&output, as_signed(sizeof(T))); return output; } size_t ObjectInputStream::pos() { return static_cast<size_t>(istream.tellg()); } auto ObjectInputStream::read(const char* data, size_t data_len) -> bool { istream.clear(); len = data_len; std::string dataStr = std::string(data, len); istream.str(dataStr); try { std::string version = readString(); if (version != XML_VERSION_STR) { g_warning("ObjectInputStream version mismatch... two different Xournal versions running? (%s / %s)", version.c_str(), XML_VERSION_STR); return false; } } catch (const InputStreamException& e) { g_warning("InputStreamException: %s", e.what()); return false; } return true; } void ObjectInputStream::readObject(const char* name) { std::string type = readObject(); if (type != name) { throw InputStreamException(FS(FORMAT_STR("Try to read object type {1} but read object type {2}") % name % type), __FILE__, __LINE__); } } auto ObjectInputStream::readObject() -> std::string { checkType('{'); return readString(); } auto ObjectInputStream::getNextObjectName() -> std::string { auto position = istream.tellg(); checkType('{'); std::string name = readString(); istream.seekg(position); return name; } void ObjectInputStream::endObject() { checkType('}'); } auto ObjectInputStream::readInt() -> int { checkType('i'); return readType<int>(); } auto ObjectInputStream::readUInt() -> uint32_t { checkType('u'); return readType<uint32_t>(); } auto ObjectInputStream::readDouble() -> double { checkType('d'); return readType<double>(); } auto ObjectInputStream::readSizeT() -> size_t { checkType('l'); return readType<size_t>(); } auto ObjectInputStream::readString() -> std::string { checkType('s'); size_t lenString = readType<size_t>(); if (istream.str().size() < len) { throw InputStreamException("End reached, but try to read an string", __FILE__, __LINE__); } std::string output; output.resize(lenString); istream.read(&output[0], as_signed(lenString)); return output; } auto ObjectInputStream::readImage() -> std::string { checkType('m'); if (istream.str().size() < sizeof(size_t)) { throw InputStreamException("End reached, but try to read an image's data's length", __FILE__, __LINE__); } const size_t len = readType<size_t>(); if (istream.str().size() < len) { throw InputStreamException("End reached, but try to read an image", __FILE__, __LINE__); } std::string data; data.resize(len); istream.read(data.data(), as_signed(len)); return data; } void ObjectInputStream::checkType(char type) { if (istream.str().size() < 2) { throw InputStreamException( FS(FORMAT_STR("End reached, but try to read {1}, index {2} of {3}") % getType(type) % pos() % len), __FILE__, __LINE__); } char t = 0, underscore = 0; istream >> underscore >> t; if (underscore != '_') { throw InputStreamException(FS(FORMAT_STR("Expected type signature of {1}, index {2} of {3}, but read '{4}'") % getType(type) % (pos() + 1) % len % underscore), __FILE__, __LINE__); } if (t != type) { throw InputStreamException(FS(FORMAT_STR("Expected {1} but read {2}") % getType(type) % getType(t)), __FILE__, __LINE__); } } auto ObjectInputStream::getType(char type) -> std::string { std::string ret; if (type == '{') { ret = "Object begin"; } else if (type == '}') { ret = "Object end"; } else if (type == 'i') { ret = "Number"; } else if (type == 'u') { ret = "Unsigned Number"; } else if (type == 'd') { ret = "Floating point"; } else if (type == 'l') { ret = "Size"; } else if (type == 's') { ret = "String"; } else if (type == 'b') { ret = "Binary"; } else if (type == 'm') { ret = "Image"; } else { char* str = g_strdup_printf("Unknown type: %02hhx (%c)", type, type); ret = str; g_free(str); } return ret; }
5,412
C++
.cpp
146
30.835616
120
0.586121
xournalpp/xournalpp
10,962
791
1,098
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
12,350
HexObjectEncoding.cpp
xournalpp_xournalpp/src/util/serializing/HexObjectEncoding.cpp
#include "util/serializing/HexObjectEncoding.h" #include <cinttypes> // for PRIx8 #include <cstdint> // for uint8_t #include <cstdio> // for sprintf #include <glib.h> // for g_free, g_malloc, g_string_append_len #include "util/safe_casts.h" // for as_signed HexObjectEncoding::HexObjectEncoding() = default; HexObjectEncoding::~HexObjectEncoding() = default; void HexObjectEncoding::addData(const void* data, size_t len) { char* buffer = static_cast<char*>(g_malloc(len * 2)); for (size_t i = 0; i < len; i++) { uint8_t x = static_cast<uint8_t const*>(data)[i]; sprintf(&buffer[i * 2], "%02" PRIx8, x); } g_string_append_len(this->data, buffer, as_signed(len * 2)); g_free(buffer); }
739
C++
.cpp
17
39.823529
64
0.666199
xournalpp/xournalpp
10,962
791
1,098
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
12,351
InputStreamException.cpp
xournalpp_xournalpp/src/util/serializing/InputStreamException.cpp
#include "util/serializing/InputStreamException.h" InputStreamException::InputStreamException(const std::string& message, const std::string& filename, int line) { this->message = message + ", " + filename + ": " + std::to_string(line); } InputStreamException::~InputStreamException() = default; const char* InputStreamException::what() const noexcept { return this->message.c_str(); }
392
C++
.cpp
6
63.166667
111
0.751958
xournalpp/xournalpp
10,962
791
1,098
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
12,352
BinObjectEncoding.cpp
xournalpp_xournalpp/src/util/serializing/BinObjectEncoding.cpp
#include "util/serializing/BinObjectEncoding.h" #include <glib.h> // for g_string_append_len #include "util/safe_casts.h" // for as_signed BinObjectEncoding::BinObjectEncoding() = default; BinObjectEncoding::~BinObjectEncoding() = default; void BinObjectEncoding::addData(const void* data, size_t len) { g_string_append_len(this->data, static_cast<const char*>(data), as_signed(len)); }
398
C++
.cpp
8
47.625
84
0.758442
xournalpp/xournalpp
10,962
791
1,098
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
12,353
ObjectEncoding.cpp
xournalpp_xournalpp/src/util/serializing/ObjectEncoding.cpp
#include "util/serializing/ObjectEncoding.h" ObjectEncoding::ObjectEncoding() { this->data = g_string_new(""); } ObjectEncoding::~ObjectEncoding() = default; void ObjectEncoding::addStr(const char* str) const { g_string_append(this->data, str); } auto ObjectEncoding::getData() -> GString* { GString* str = this->data; this->data = nullptr; return str; }
371
C++
.cpp
9
38.444444
88
0.717877
xournalpp/xournalpp
10,962
791
1,098
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
12,354
Logger.cpp
xournalpp_xournalpp/src/util/logger/Logger.cpp
#include "util/logger/Logger.h" #include <ctime> // for localtime_r, strftime, tm #include "config-dev.h" // for DEV_CALL_LOG #ifdef DEV_CALL_LOG #include <cstdio> // for snprintf #include <fstream> // for operator<<, basic_ostream, ofstream, ostring... #include <sstream> // for stringstream #include <string> // for char_traits, operator<<, allocator, string #ifdef _WIN32 #include <windows.h> inline std::string NowTime() { const int MAX_LEN = 200; char buffer[MAX_LEN]; if (GetTimeFormatA(LOCALE_USER_DEFAULT, 0, 0, "HH':'mm':'ss", buffer, MAX_LEN) == 0) { return "Error in NowTime()"; } char result[100] = {0}; static DWORD first = GetTickCount(); sprintf_s(result, 100, "%s.%06ld", buffer, (long)(GetTickCount() - first)); return result; } #else #include <sys/time.h> // for gettimeofday, timeval inline std::string NowTime() { struct timeval tv; gettimeofday(&tv, 0); char buffer[100]; tm r; strftime(buffer, sizeof(buffer), "%X", localtime_r(&tv.tv_sec, &r)); char result[100]; snprintf(result, sizeof(result), "%s.%06ld", buffer, (long)tv.tv_usec); return result; } #endif //_WIN32 Log::Log() {} Log::~Log() {} std::ofstream logfile; void Log::trace(const char* callType, const char* clazz, const char* function, long obj) { std::ostringstream os; os << NowTime() << " - "; os << callType << " " << clazz << ":" << function << " (" << obj << ")" << std::endl; logfile << os.str(); } void Log::initlog() { logfile.open("xournalCalls.log"); } void Log::closelog() { logfile.close(); } #endif // DEV_CALL_LOG
1,636
C++
.cpp
46
32.173913
90
0.640306
xournalpp/xournalpp
10,962
791
1,098
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
12,355
CStringWrapper.cpp
xournalpp_xournalpp/src/util/raii/CStringWrapper.cpp
#include "util/raii/CStringWrapper.h" #include <utility> #include <glib.h> namespace xoj::util { inline namespace raii { OwnedCString::OwnedCString(OwnedCString&& s): data(std::exchange(s.data, nullptr)) {} OwnedCString& OwnedCString::operator=(OwnedCString&& s) { g_free(data); data = std::exchange(s.data, nullptr); return *this; } OwnedCString OwnedCString::assumeOwnership(char* s) { OwnedCString res; res.data = s; return res; } OwnedCString::~OwnedCString() { g_free(data); } const char* OwnedCString::get() const { return data; } OwnedCString::operator bool() const { return data && data[0]; } OwnedCString::operator std::string_view() const { return data ? data : std::string_view(); } const char& OwnedCString::operator[](size_t n) const { return data[n]; } char** OwnedCString::contentReplacer() { g_free(std::exchange(data, nullptr)); return &data; } }; // namespace raii }; // namespace xoj::util
951
C++
.cpp
27
32.740741
92
0.710699
xournalpp/xournalpp
10,962
791
1,098
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
12,356
Setsquare.cpp
xournalpp_xournalpp/src/core/model/Setsquare.cpp
#include "Setsquare.h" #include <cmath> // for sin, cos #include <initializer_list> // for initializer_list #include "gui/inputdevices/SetsquareInputHandler.h" #include "view/SetsquareView.h" Setsquare::Setsquare(): Setsquare(INITIAL_HEIGHT, .0, 0., 0.) {} Setsquare::Setsquare(double height, double rotation, double x, double y): GeometryTool(height, rotation, x, y) { this->lastRepaintRange = getToolRange(true); } Setsquare::~Setsquare() { viewPool->dispatchAndClear(xoj::view::SetsquareView::FINALIZATION_REQUEST, lastRepaintRange); } auto Setsquare::getToolRange(bool transformed) const -> Range { const auto h = height * CM; Range rg; if (transformed) { const auto cs = std::cos(rotation); const auto si = std::sin(rotation); rg.addPoint(translationX + cs * h, translationY - si * h); rg.addPoint(translationX - cs * h, translationY + si * h); rg.addPoint(translationX - si * h, translationY + cs * h); } else { rg.addPoint(h, 0); rg.addPoint(-h, 0); rg.addPoint(0, h); } // Padding required to fully render the boundary red lines constexpr double RENDER_PADDING = 1.0; rg.addPadding(RENDER_PADDING + .5 * xoj::view::SetsquareView::LINE_WIDTH_IN_CM * CM); // account for line width return rg; } void Setsquare::notify(bool resetMask) const { if (resetMask) { viewPool->dispatch(xoj::view::GeometryToolView::RESET_MASK); } viewPool->dispatch(xoj::view::SetsquareView::UPDATE_VALUES, this->getHeight(), this->getRotation(), this->getMatrix()); Range rg = this->getToolRange(true); viewPool->dispatch(xoj::view::SetsquareView::FLAG_DIRTY_REGION, this->computeRepaintRange(rg)); handlerPool->dispatch(SetsquareInputHandler::UPDATE_VALUES, this->getHeight(), this->getRotation(), this->getTranslationX(), this->getTranslationY()); }
1,946
C++
.cpp
42
40.619048
116
0.674406
xournalpp/xournalpp
10,962
791
1,098
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
12,357
AudioElement.cpp
xournalpp_xournalpp/src/core/model/AudioElement.cpp
#include "AudioElement.h" #include <utility> // for move #include "model/Element.h" // for Element, ElementType #include "util/serializing/ObjectInputStream.h" // for ObjectInputStream #include "util/serializing/ObjectOutputStream.h" // for ObjectOutputStream AudioElement::AudioElement(ElementType type): Element(type) {} AudioElement::~AudioElement() { this->timestamp = 0; } void AudioElement::setAudioFilename(fs::path fn) { this->audioFilename = std::move(fn); } auto AudioElement::getAudioFilename() const -> fs::path const& { return this->audioFilename; } void AudioElement::setTimestamp(size_t timestamp) { this->timestamp = timestamp; } auto AudioElement::getTimestamp() const -> size_t { return this->timestamp; } void AudioElement::serialize(ObjectOutputStream& out) const { out.writeObject("AudioElement"); this->Element::serialize(out); out.writeString(this->audioFilename.u8string()); out.writeSizeT(this->timestamp); out.endObject(); } void AudioElement::readSerialized(ObjectInputStream& in) { in.readObject("AudioElement"); this->Element::readSerialized(in); this->audioFilename = in.readString(); this->timestamp = in.readSizeT(); in.endObject(); } void AudioElement::cloneAudioData(const AudioElement* other) { setAudioFilename(other->getAudioFilename()); setTimestamp(other->getTimestamp()); }
1,406
C++
.cpp
29
45.241379
94
0.741912
xournalpp/xournalpp
10,962
791
1,098
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
12,358
TexImage.cpp
xournalpp_xournalpp/src/core/model/TexImage.cpp
#include "TexImage.h" #include <memory> #include <utility> // for move #include <poppler-document.h> // for poppler_document_ge... #include <poppler-page.h> // for poppler_page_get_size #include "model/Element.h" // for Element, ELEMENT_TE... #include "util/Rectangle.h" // for Rectangle #include "util/raii/GObjectSPtr.h" // for GObjectSPtr #include "util/serializing/ObjectInputStream.h" // for ObjectInputStream #include "util/serializing/ObjectOutputStream.h" // for ObjectOutputStream using xoj::util::Rectangle; TexImage::TexImage(): Element(ELEMENT_TEXIMAGE) { this->sizeCalculated = true; } TexImage::~TexImage() { freeImageAndPdf(); } void TexImage::freeImageAndPdf() { if (this->image) { cairo_surface_destroy(this->image); this->image = nullptr; } this->pdf.reset(); } auto TexImage::cloneTexImage() const -> std::unique_ptr<TexImage> { auto img = std::make_unique<TexImage>(); img->x = this->x; img->y = this->y; img->setColor(this->getColor()); img->width = this->width; img->height = this->height; img->text = this->text; img->snappedBounds = this->snappedBounds; img->sizeCalculated = this->sizeCalculated; // Clone has a copy of our PDF. img->pdf = this->pdf; // Load a copy of our data (must be called after // giving the clone a copy of our PDF -- it may change // the PDF we've given it). img->loadData(std::string(this->binaryData), nullptr); return img; } auto TexImage::clone() const -> ElementPtr { return cloneTexImage(); } void TexImage::setWidth(double width) { this->width = width; this->calcSize(); } void TexImage::setHeight(double height) { this->height = height; this->calcSize(); } auto TexImage::cairoReadFunction(TexImage* image, unsigned char* data, unsigned int length) -> cairo_status_t { for (unsigned int i = 0; i < length; i++, image->read++) { if (image->read >= image->binaryData.length()) { return CAIRO_STATUS_READ_ERROR; } data[i] = static_cast<unsigned char>(image->binaryData[image->read]); } return CAIRO_STATUS_SUCCESS; } /** * Gets the binary data, a .PNG image or a .PDF */ auto TexImage::getBinaryData() const -> std::string const& { return this->binaryData; } void TexImage::setText(std::string text) { this->text = std::move(text); } auto TexImage::getText() const -> std::string { return this->text; } auto TexImage::loadData(std::string&& bytes, GError** err) -> bool { this->freeImageAndPdf(); this->binaryData = bytes; if (this->binaryData.length() < 4) { return false; } const std::string type = binaryData.substr(1, 3); if (type == "PDF") { // Note: binaryData must not be modified while pdf is live. this->pdf.reset(poppler_document_new_from_data(this->binaryData.data(), this->binaryData.size(), nullptr, err), xoj::util::adopt); if (!pdf.get() || poppler_document_get_n_pages(this->pdf.get()) < 1) { return false; } if (std::abs(this->width * this->height) <= std::numeric_limits<double>::epsilon()) { xoj::util::GObjectSPtr<PopplerPage> page(poppler_document_get_page(this->pdf.get(), 0), xoj::util::adopt); poppler_page_get_size(page.get(), &this->width, &this->height); } } else if (type == "PNG") { this->image = cairo_image_surface_create_from_png_stream( reinterpret_cast<cairo_read_func_t>(&cairoReadFunction), this); } else { g_warning("Unknown Latex image type: \"%s\"", type.c_str()); } return true; } auto TexImage::getImage() const -> cairo_surface_t* { return this->image; } auto TexImage::getPdf() const -> PopplerDocument* { return this->pdf.get(); } void TexImage::scale(double x0, double y0, double fx, double fy, double rotation, bool) { // line width scaling option is not used this->x = (this->x - x0) * fx + x0; this->y = (this->y - y0) * fy + y0; this->width *= fx; this->height *= fy; this->calcSize(); } void TexImage::rotate(double x0, double y0, double th) { // Rotation for TexImages not yet implemented } void TexImage::serialize(ObjectOutputStream& out) const { out.writeObject("TexImage"); this->Element::serialize(out); out.writeDouble(this->width); out.writeDouble(this->height); out.writeString(this->text); out.writeString(this->binaryData); out.endObject(); } void TexImage::readSerialized(ObjectInputStream& in) { in.readObject("TexImage"); this->Element::readSerialized(in); this->width = in.readDouble(); this->height = in.readDouble(); this->text = in.readString(); freeImageAndPdf(); std::string data = in.readString(); this->loadData(std::move(data), nullptr); in.endObject(); this->calcSize(); } void TexImage::calcSize() const { this->snappedBounds = Rectangle<double>(this->x, this->y, this->width, this->height); this->sizeCalculated = true; }
5,132
C++
.cpp
126
35.690476
119
0.646052
xournalpp/xournalpp
10,962
791
1,098
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
12,359
Compass.cpp
xournalpp_xournalpp/src/core/model/Compass.cpp
#include "Compass.h" #include <cmath> // for sin, cos #include <initializer_list> // for initializer_list #include "gui/inputdevices/CompassInputHandler.h" #include "view/CompassView.h" Compass::Compass(): Compass(INITIAL_HEIGHT, .0, 0., 0.) {} Compass::Compass(double height, double rotation, double x, double y): GeometryTool(height, rotation, x, y) { this->lastRepaintRange = getToolRange(true); } Compass::~Compass() { viewPool->dispatchAndClear(xoj::view::CompassView::FINALIZATION_REQUEST, lastRepaintRange); } auto Compass::getToolRange(bool transformed) const -> Range { const auto h = height * CM; Range rg; if (transformed) { rg.addPoint(translationX - h, translationY - h); rg.addPoint(translationX + h, translationY + h); } else { rg.addPoint(-h, -h); rg.addPoint(h, h); } // Padding required to fully render the boundary red lines and last blue digit constexpr double RENDER_PADDING = 2.0; rg.addPadding(RENDER_PADDING + .5 * xoj::view::CompassView::LINE_WIDTH_IN_CM * CM); // account for line width return rg; } void Compass::notify(bool resetMask) const { if (resetMask) { viewPool->dispatch(xoj::view::GeometryToolView::RESET_MASK); } viewPool->dispatch(xoj::view::CompassView::UPDATE_VALUES, this->getHeight(), this->getRotation(), this->getMatrix()); Range rg = this->getToolRange(true); viewPool->dispatch(xoj::view::CompassView::FLAG_DIRTY_REGION, this->computeRepaintRange(rg)); handlerPool->dispatch(CompassInputHandler::UPDATE_VALUES, this->getHeight(), this->getRotation(), this->getTranslationX(), this->getTranslationY()); }
1,728
C++
.cpp
36
42.472222
115
0.68371
xournalpp/xournalpp
10,962
791
1,098
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
12,360
BackgroundConfig.cpp
xournalpp_xournalpp/src/core/model/BackgroundConfig.cpp
#include "BackgroundConfig.h" #include <cstddef> // for size_t #include <sstream> // for istringstream, basic_ios::imbue, basi... #include <utility> // for pair #include <vector> // for vector #include "util/StringUtils.h" // for StringUtils #include "util/serdesstream.h" // for serdes_stream using std::string; BackgroundConfig::BackgroundConfig(const string& config) { for (const string& s: StringUtils::split(config, ',')) { size_t dotPos = s.find_last_of('='); if (dotPos != string::npos) { string key = s.substr(0, dotPos); string value = s.substr(dotPos + 1); data[key] = value; } } } BackgroundConfig::~BackgroundConfig() = default; auto BackgroundConfig::loadValue(const string& key, string& value) const -> bool { auto it = data.find(key); if (it != this->data.end()) { value = it->second; return true; } return false; } auto BackgroundConfig::loadValue(const string& key, int& value) const -> bool { string str; if (loadValue(key, str)) { auto valueStream = serdes_stream<std::istringstream>(str); valueStream >> value; return true; } return false; } auto BackgroundConfig::loadValue(const string& key, double& value) const -> bool { string str; if (loadValue(key, str)) { auto valueStream = serdes_stream<std::istringstream>(str); valueStream >> value; return true; } return false; } auto BackgroundConfig::loadValueHex(const string& key, uint32_t& value) const -> bool { string str; if (loadValue(key, str)) { auto valueStream = serdes_stream<std::istringstream>(str); valueStream >> std::hex >> value; return true; } return false; }
1,788
C++
.cpp
54
27.796296
87
0.640906
xournalpp/xournalpp
10,962
791
1,098
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
12,361
GeometryTool.cpp
xournalpp_xournalpp/src/core/model/GeometryTool.cpp
#include "GeometryTool.h" #include <initializer_list> // for initializer_list GeometryTool::GeometryTool(double h, double r, double tx, double ty): height(h), rotation(r), translationX(tx), translationY(ty), viewPool(std::make_shared<xoj::util::DispatchPool<xoj::view::GeometryToolView>>()), handlerPool(std::make_shared<xoj::util::DispatchPool<GeometryToolInputHandler>>()) {} GeometryTool::~GeometryTool() {} void GeometryTool::setHeight(double height) { this->height = height; } auto GeometryTool::getHeight() const -> double { return this->height; } void GeometryTool::setRotation(double rotation) { this->rotation = rotation; } auto GeometryTool::getRotation() const -> double { return this->rotation; } void GeometryTool::setTranslationX(double x) { this->translationX = x; } auto GeometryTool::getTranslationX() const -> double { return this->translationX; } void GeometryTool::setTranslationY(double y) { this->translationY = y; } auto GeometryTool::getTranslationY() const -> double { return this->translationY; } auto GeometryTool::getMatrix() const -> cairo_matrix_t { cairo_matrix_t matrix; cairo_matrix_init_identity(&matrix); cairo_matrix_translate(&matrix, this->translationX, this->translationY); cairo_matrix_rotate(&matrix, this->rotation); cairo_matrix_scale(&matrix, CM, CM); return matrix; } auto GeometryTool::getViewPool() const -> const std::shared_ptr<xoj::util::DispatchPool<xoj::view::GeometryToolView>>& { return viewPool; } auto GeometryTool::getHandlerPool() const -> const std::shared_ptr<xoj::util::DispatchPool<GeometryToolInputHandler>>& { return handlerPool; } auto GeometryTool::getStroke() const -> Stroke* { return this->stroke; } void GeometryTool::setStroke(Stroke* s) { this->stroke = s; } auto GeometryTool::computeRepaintRange(Range rg) const -> Range { Range lastRange = this->lastRepaintRange; if (this->stroke) { rg.addPoint(this->stroke->getX(), this->stroke->getY()); rg.addPoint(this->stroke->getX() + this->stroke->getElementWidth(), this->stroke->getY() + this->stroke->getElementHeight()); } this->lastRepaintRange = rg; return rg.unite(lastRange); }
2,251
C++
.cpp
44
46.818182
120
0.716302
xournalpp/xournalpp
10,962
791
1,098
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
12,362
BackgroundImage.cpp
xournalpp_xournalpp/src/core/model/BackgroundImage.cpp
#include "BackgroundImage.h" #include <string> // for string #include <utility> // for move #include <glib-object.h> // for g_object_unref #include "util/Stacktrace.h" // for Stacktrace /* * The contents of a background image * * Internal impl object, dont move this to an external header/source file due this is the best way to reduce code * bloat and increase encapsulation. This object is only used in this source scope and is a RAII Container for the * GdkPixbuf* * No xournal memory leak tests necessary, because we use smart ptrs to ensure memory correctness */ struct BackgroundImage::Content { Content(fs::path path, GError** error): path(std::move(path)), pixbuf(gdk_pixbuf_new_from_file(this->path.u8string().c_str(), error)) {} Content(GInputStream* stream, fs::path path, GError** error): path(std::move(path)), pixbuf(gdk_pixbuf_new_from_stream(stream, nullptr, error)) {} ~Content() { g_object_unref(this->pixbuf); this->pixbuf = nullptr; }; Content(const Content&) = delete; Content(Content&&) = default; auto operator=(const Content&) -> Content& = delete; auto operator=(Content&&) -> Content& = default; fs::path path; GdkPixbuf* pixbuf = nullptr; int pageId = -1; bool attach = false; }; BackgroundImage::BackgroundImage() = default; BackgroundImage::BackgroundImage(const BackgroundImage& img) = default; BackgroundImage::BackgroundImage(BackgroundImage&& img) noexcept: img(std::move(img.img)) {} BackgroundImage::~BackgroundImage() = default; auto BackgroundImage::operator==(const BackgroundImage& img) -> bool { return this->img == img.img; } void BackgroundImage::free() { this->img.reset(); } void BackgroundImage::loadFile(fs::path const& path, GError** error) { this->img = std::make_shared<Content>(path, error); } void BackgroundImage::loadFile(GInputStream* stream, fs::path const& path, GError** error) { this->img = std::make_shared<Content>(stream, path, error); } auto BackgroundImage::getCloneId() -> int { return this->img ? this->img->pageId : -1; } void BackgroundImage::setCloneId(int id) { if (this->img) { this->img->pageId = id; } } void BackgroundImage::clearSaveState() { this->setCloneId(-1); } auto BackgroundImage::getFilepath() const -> fs::path { return this->img ? this->img->path : fs::path{}; } void BackgroundImage::setFilepath(fs::path path) { if (this->img) { this->img->path = std::move(path); } } auto BackgroundImage::isAttached() const -> bool { return this->img ? this->img->attach : false; } void BackgroundImage::setAttach(bool attach) { if (!this->img) { g_warning("BackgroundImage::setAttach: please load first an image before call setAttach!"); Stacktrace::printStacktrace(); return; } this->img->attach = attach; } auto BackgroundImage::getPixbuf() const -> GdkPixbuf* { return this->img ? this->img->pixbuf : nullptr; } auto BackgroundImage::isEmpty() const -> bool { return !this->img; }
3,059
C++
.cpp
67
41.716418
114
0.695887
xournalpp/xournalpp
10,962
791
1,098
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
12,363
LinkDestination.cpp
xournalpp_xournalpp/src/core/model/LinkDestination.cpp
#include "LinkDestination.h" #include <utility> // for move #include "util/Util.h" // for npos struct _LinkDestClass { GObjectClass base_class; }; G_DEFINE_TYPE(XojLinkDest, link_dest, G_TYPE_OBJECT) // @suppress("Unused static function") static void link_dest_init(XojLinkDest* linkAction) { linkAction->dest = nullptr; } static gpointer parent_class = nullptr; static void link_dest_finalize(GObject* object) { delete LINK_DEST(object)->dest; LINK_DEST(object)->dest = nullptr; G_OBJECT_CLASS(parent_class)->finalize(object); } static void link_dest_dispose(GObject* object) { G_OBJECT_CLASS(parent_class)->dispose(object); } static void link_dest_class_init(XojLinkDestClass* linkClass) { GObjectClass* g_object_class = nullptr; parent_class = g_type_class_peek_parent(linkClass); g_object_class = G_OBJECT_CLASS(linkClass); g_object_class->dispose = link_dest_dispose; g_object_class->finalize = link_dest_finalize; } auto link_dest_new() -> XojLinkDest* { return LINK_DEST(g_object_new(TYPE_LINK_DEST, nullptr)); } LinkDestination::LinkDestination(): page(npos), expand(false), left(0), top(0), zoom(0), changeLeft(false), changeZoom(false), changeTop(false), name(""), contents(UnknownType{}) {} LinkDestination::~LinkDestination() = default; auto LinkDestination::getPdfPage() const -> size_t { return this->page; } void LinkDestination::setPdfPage(size_t page) { this->page = page; } void LinkDestination::setExpand(bool expand) { this->expand = expand; } auto LinkDestination::getExpand() const -> bool { return this->expand; } auto LinkDestination::shouldChangeLeft() const -> bool { return changeLeft; } auto LinkDestination::shouldChangeTop() const -> bool { return changeTop; } auto LinkDestination::getZoom() const -> double { return zoom; } auto LinkDestination::getLeft() const -> double { return left; } auto LinkDestination::getTop() const -> double { return top; } void LinkDestination::setChangeLeft(double left) { this->left = left; this->changeLeft = true; } void LinkDestination::setChangeZoom(double zoom) { this->zoom = zoom; this->changeZoom = true; } void LinkDestination::setChangeTop(double top) { this->top = top; this->changeTop = true; } void LinkDestination::setName(std::string name) { this->name = std::move(name); } auto LinkDestination::getName() const -> const std::string& { return name; } void LinkDestination::setURI(std::string uri) { this->contents = LinkType{std::move(uri)}; } auto LinkDestination::isURI() const -> bool { return std::holds_alternative<LinkDestination::LinkType>(contents); } auto LinkDestination::getURI() const -> std::optional<std::string> { if (auto* t = std::get_if<LinkDestination::LinkType>(&contents)) { return t->uri; } else { return std::nullopt; } }
2,926
C++
.cpp
67
39.686567
115
0.709586
xournalpp/xournalpp
10,962
791
1,098
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
12,364
PageListener.cpp
xournalpp_xournalpp/src/core/model/PageListener.cpp
#include "PageListener.h" #include "PageHandler.h" PageListener::PageListener() = default; PageListener::~PageListener() { unregisterFromHandler(); } void PageListener::registerToHandler(std::shared_ptr<PageHandler> const& _handler) { this->handler = _handler; _handler->addListener(this); } void PageListener::unregisterFromHandler() { if (auto _handler = this->handler.lock(); _handler) { _handler->removeListener(this); this->handler.reset(); } }
487
C++
.cpp
14
31.142857
84
0.717949
xournalpp/xournalpp
10,962
791
1,098
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
12,365
Image.cpp
xournalpp_xournalpp/src/core/model/Image.cpp
#include "Image.h" #include <algorithm> // for min #include <array> // for array #include <memory> #include <utility> // for move, pair #include <cairo.h> // for cairo_surface_destroy #include <gdk/gdk.h> // for gdk_cairo_set_sourc... #include <glib.h> // for guchar #include "model/Element.h" // for Element, ELEMENT_IMAGE #include "util/Assert.h" // for xoj_assert #include "util/Rectangle.h" // for Rectangle #include "util/raii/GObjectSPtr.h" // for GObjectSPtr #include "util/serializing/ObjectInputStream.h" // for ObjectInputStream #include "util/serializing/ObjectOutputStream.h" // for ObjectOutputStream using xoj::util::Rectangle; Image::Image(): Element(ELEMENT_IMAGE) {} Image::~Image() { if (this->image) { cairo_surface_destroy(this->image); this->image = nullptr; } if (this->format) { gdk_pixbuf_format_free(this->format); this->format = nullptr; } } auto Image::clone() const -> ElementPtr { auto img = std::make_unique<Image>(); img->x = this->x; img->y = this->y; img->setColor(this->getColor()); img->width = this->width; img->height = this->height; img->data = this->data; img->image = cairo_surface_reference(this->image); img->snappedBounds = this->snappedBounds; img->sizeCalculated = this->sizeCalculated; return img; } void Image::setWidth(double width) { this->width = width; this->calcSize(); } void Image::setHeight(double height) { this->height = height; this->calcSize(); } void Image::setImage(std::string_view data) { setImage(std::string(data)); } void Image::setImage(std::string&& data) { if (this->image) { cairo_surface_destroy(this->image); this->image = nullptr; } this->data = std::move(data); if (this->format) { gdk_pixbuf_format_free(this->format); this->format = nullptr; } // FIXME: awful hack to try to parse the format std::array<char*, 4096> buffer{}; xoj::util::GObjectSPtr<GdkPixbufLoader> loader(gdk_pixbuf_loader_new(), xoj::util::adopt); size_t remaining = this->data.size(); while (remaining > 0) { size_t readLen = std::min(remaining, buffer.size()); if (!gdk_pixbuf_loader_write(loader.get(), reinterpret_cast<const guchar*>(this->data.c_str()), readLen, nullptr)) break; remaining -= readLen; // Try to determine the format early, if possible this->format = gdk_pixbuf_loader_get_format(loader.get()); if (this->format) { break; } } gdk_pixbuf_loader_close(loader.get(), nullptr); // if the format was not determined early, it can probably be determined now if (!this->format) { this->format = gdk_pixbuf_loader_get_format(loader.get()); } xoj_assert_message(this->format != nullptr, "could not parse the image format!"); // the format is owned by the pixbuf, so create a copy this->format = gdk_pixbuf_format_copy(this->format); } void Image::setImage(GdkPixbuf* img) { #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wdeprecated-declarations" setImage(gdk_cairo_surface_create_from_pixbuf(img, 0, nullptr)); #pragma GCC diagnostic pop } void Image::setImage(cairo_surface_t* image) { if (this->image) { cairo_surface_destroy(this->image); this->image = nullptr; } struct { std::string buffer; std::string readbuf; } closure_; const cairo_write_func_t writeFunc = [](void* closurePtr, const unsigned char* data, unsigned int length) -> cairo_status_t { auto& closure = *reinterpret_cast<decltype(&closure_)>(closurePtr); closure.buffer.append(reinterpret_cast<const char*>(data), length); return CAIRO_STATUS_SUCCESS; }; cairo_surface_write_to_png_stream(image, writeFunc, &closure_); data = std::move(closure_.buffer); } auto Image::getImage() const -> cairo_surface_t* { xoj_assert_message(data.length() > 0, "image has no data, cannot render it!"); if (this->image == nullptr) { xoj::util::GObjectSPtr<GdkPixbufLoader> loader(gdk_pixbuf_loader_new(), xoj::util::adopt); gdk_pixbuf_loader_write(loader.get(), reinterpret_cast<const guchar*>(this->data.c_str()), this->data.length(), nullptr); [[maybe_unused]] bool success = gdk_pixbuf_loader_close(loader.get(), nullptr); xoj_assert_message(success, "errors in loading image data!"); GdkPixbuf* tmp = gdk_pixbuf_loader_get_pixbuf(loader.get()); xoj_assert(tmp != nullptr); xoj::util::GObjectSPtr<GdkPixbuf> pixbuf(gdk_pixbuf_apply_embedded_orientation(tmp), xoj::util::adopt); this->imageSize = {gdk_pixbuf_get_width(pixbuf.get()), gdk_pixbuf_get_height(pixbuf.get())}; // TODO: pass in window once this code is refactored into ImageView this->image = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, this->imageSize.first, this->imageSize.second); xoj_assert(this->image != nullptr); // Paint the pixbuf on to the surface // NOTE: we do this manually instead of using gdk_cairo_surface_create_from_pixbuf // since this does not work in CLI mode. cairo_t* cr = cairo_create(this->image); gdk_cairo_set_source_pixbuf(cr, pixbuf.get(), 0, 0); cairo_paint(cr); cairo_destroy(cr); } return this->image; } void Image::scale(double x0, double y0, double fx, double fy, double rotation, bool) { // line width scaling option is not used this->x -= x0; this->x *= fx; this->x += x0; this->y -= y0; this->y *= fy; this->y += y0; this->width *= fx; this->height *= fy; this->calcSize(); } void Image::rotate(double x0, double y0, double th) {} void Image::serialize(ObjectOutputStream& out) const { out.writeObject("Image"); this->Element::serialize(out); out.writeDouble(this->width); out.writeDouble(this->height); out.writeImage(this->data); out.endObject(); } void Image::readSerialized(ObjectInputStream& in) { in.readObject("Image"); this->Element::readSerialized(in); this->width = in.readDouble(); this->height = in.readDouble(); if (this->image) { cairo_surface_destroy(this->image); this->image = nullptr; } this->data = in.readImage(); in.endObject(); this->calcSize(); } void Image::calcSize() const { this->snappedBounds = Rectangle<double>(this->x, this->y, this->width, this->height); this->sizeCalculated = true; } bool Image::hasData() const { return !this->data.empty(); } const unsigned char* Image::getRawData() const { return reinterpret_cast<const unsigned char*>(this->data.data()); } size_t Image::getRawDataLength() const { return this->data.size(); } std::pair<int, int> Image::getImageSize() const { return this->imageSize; } GdkPixbufFormat* Image::getImageFormat() const { return this->format; }
7,197
C++
.cpp
175
35.257143
119
0.641761
xournalpp/xournalpp
10,962
791
1,098
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
12,366
Layer.cpp
xournalpp_xournalpp/src/core/model/Layer.cpp
#include "Layer.h" #include <cstddef> #include <memory> #include <utility> #include <vector> #include <glib.h> // for g_warning #include "model/Element.h" // for Element, Element::Index, Element::Inval... #include "model/ElementInsertionPosition.h" #include "util/Assert.h" // for xoj_assert #include "util/Stacktrace.h" // for Stacktrace #include "util/safe_casts.h" Layer::Layer() = default; Layer::~Layer() = default; auto Layer::clone() const -> Layer* { auto* layer = new Layer(); if (hasName()) { layer->setName(getName()); } for (auto const& e: this->elements) { layer->addElement(e->clone()); } return layer; } void Layer::addElement(ElementPtr e) { if (e == nullptr) { g_warning("addElement(nullptr)!"); Stacktrace::printStacktrace(); return; } this->elements.emplace_back(std::move(e)); } void Layer::insertElement(ElementPtr e, Element::Index pos) { if (e == nullptr) { g_warning("insertElement(nullptr)!"); Stacktrace::printStacktrace(); return; } // prevent crash, even if this never should happen, // but there was a bug before which cause this error if (pos < 0) { pos = 0; } // If the element should be inserted at the top if (pos >= static_cast<int>(this->elements.size())) { this->elements.push_back(std::move(e)); } else { this->elements.insert(this->elements.begin() + pos, std::move(e)); } } auto Layer::indexOf(Element* e) const -> Element::Index { for (unsigned int i = 0; i < this->elements.size(); i++) { if (this->elements[i].get() == e) { return i; } } return Element::InvalidIndex; } auto Layer::removeElement(Element* e) -> InsertionPosition { for (unsigned int i = 0; i < this->elements.size(); i++) { if (e == this->elements[i].get()) { auto res = std::move(this->elements[i]); this->elements.erase(this->elements.begin() + i); return InsertionPosition{std::move(res), i}; } } g_warning("Could not remove element %p from layer %p, it's not on the layer!", e, this); Stacktrace::printStacktrace(); return InsertionPosition{nullptr, Element::InvalidIndex}; } auto Layer::removeElementAt(Element* e, Element::Index pos) -> InsertionPosition { if (pos >= 0 && as_unsigned(pos) < elements.size() && this->elements[as_unsigned(pos)].get() == e) { auto iter = std::next(this->elements.begin(), pos); auto res = std::move(*iter); this->elements.erase(iter); return InsertionPosition{std::move(res), pos}; } return removeElement(e); } auto Layer::removeElementsAt(InsertionOrderRef const& elts) -> InsertionOrder { InsertionOrder res; res.reserve(elts.size()); auto endIndex = static_cast<Element::Index>(elements.size()); for (auto&& [e, p]: elts) { xoj_assert(e); auto pos = p; if (pos < 0 || pos > endIndex || elements[static_cast<size_t>(pos)].get() != e) { pos = indexOf(e); if (pos == Element::InvalidIndex) { g_warning("Could not remove element from layer, it's not on the layer!"); Stacktrace::printStacktrace(); continue; } } res.emplace_back(std::move(elements[static_cast<size_t>(pos)]), pos); } this->elements.erase(std::remove(this->elements.begin(), this->elements.end(), nullptr), this->elements.end()); return res; } auto Layer::clearNoFree() -> std::vector<ElementPtr> { return std::move(this->elements); } auto Layer::isAnnotated() const -> bool { return !this->elements.empty(); } /** * @return true if the layer is visible */ auto Layer::isVisible() const -> bool { return visible; } /** * @return true if the layer is visible */ void Layer::setVisible(bool visible) { this->visible = visible; } auto Layer::getElements() const -> std::vector<ElementPtr> const& { return this->elements; } auto Layer::hasName() const -> bool { return name.has_value(); } auto Layer::getName() const -> std::string { return name.value_or(""); } void Layer::setName(const std::string& newName) { this->name = newName; }
4,255
C++
.cpp
112
32.491071
115
0.625759
xournalpp/xournalpp
10,962
791
1,098
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
12,367
FormatDefinitions.cpp
xournalpp_xournalpp/src/core/model/FormatDefinitions.cpp
#include "FormatDefinitions.h" #include "util/Util.h" // for DPI_NORMALIZATION_FACTOR const FormatUnits XOJ_UNITS[] = {{"cm", 28.346}, {"in", Util::DPI_NORMALIZATION_FACTOR}, {"points", 1.0}}; const int XOJ_UNIT_COUNT = sizeof(XOJ_UNITS) / sizeof(FormatUnits);
265
C++
.cpp
4
64.5
106
0.713178
xournalpp/xournalpp
10,962
791
1,098
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
12,368
Point.cpp
xournalpp_xournalpp/src/core/model/Point.cpp
#include "Point.h" #include <cmath> // for hypot #include "util/Rectangle.h" // for Rectangle Point::Point(double x, double y): x(x), y(y) {} Point::Point(double x, double y, double z): x(x), y(y), z(z) {} auto Point::lineLengthTo(const Point& p) const -> double { return std::hypot(this->x - p.x, this->y - p.y); } auto Point::lineTo(const Point& p, double length) const -> Point { return relativeLineTo(p, length / lineLengthTo(p)); } auto Point::relativeLineTo(const Point& p, const double ratio) const -> Point { return Point(x + ratio * (p.x - x), y + ratio * (p.y - y), z + ratio * (p.z - z)); } auto Point::equalsPos(const Point& p) const -> bool { return this->x == p.x && this->y == p.y; } auto Point::isInside(const xoj::util::Rectangle<double>& rect) const -> bool { return x >= rect.x && x <= rect.x + rect.width && y >= rect.y && y <= rect.y + rect.height; }
891
C++
.cpp
14
61.428571
120
0.635945
xournalpp/xournalpp
10,962
791
1,098
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
12,369
XojPage.cpp
xournalpp_xournalpp/src/core/model/XojPage.cpp
#include "XojPage.h" #include <algorithm> // for find, transform #include <iterator> // for back_insert_iterator, back_inserter, begin #include <utility> // for move #include "model/Layer.h" // for Layer, Layer::Index #include "model/PageType.h" // for PageType, PageTypeFormat, PageTypeForma... #include "util/Assert.h" // for xoj_assert #include "util/i18n.h" // for _ #include "BackgroundImage.h" // for BackgroundImage XojPage::XojPage(double width, double height, bool suppressLayerCreation): width(width), height(height), bgType(PageTypeFormat::Lined) { if (!suppressLayerCreation) { // ensure at least one valid layer exists this->addLayer(new Layer()); this->currentLayer = 1; } } XojPage::~XojPage() { for (Layer* l: this->layer) { delete l; } this->layer.clear(); } XojPage::XojPage(XojPage const& page): backgroundImage(page.backgroundImage), width(page.width), height(page.height), currentLayer(page.currentLayer), bgType(page.bgType), pdfBackgroundPage(page.pdfBackgroundPage), backgroundColor(page.backgroundColor) { this->layer.reserve(page.layer.size()); std::transform(begin(page.layer), end(page.layer), std::back_inserter(this->layer), [](auto* layer) { return layer->clone(); }); } auto XojPage::clone() -> XojPage* { return new XojPage(*this); } void XojPage::addLayer(Layer* layer) { this->layer.push_back(layer); this->currentLayer = npos; } void XojPage::insertLayer(Layer* layer, Layer::Index index) { if (index >= this->layer.size()) { addLayer(layer); return; } this->layer.insert(std::next(this->layer.begin(), static_cast<ptrdiff_t>(index)), layer); this->currentLayer = index + 1; } void XojPage::removeLayer(Layer* l) { if (auto it = std::find(layer.begin(), layer.end(), l); it != layer.end()) { this->layer.erase(it); } this->currentLayer = npos; // ensure at least one valid layer exists if (layer.empty()) { addLayer(new Layer()); } } void XojPage::setSelectedLayerId(Layer::Index id) { this->currentLayer = id; } auto XojPage::getLayers() -> std::vector<Layer*>* { return &this->layer; } auto XojPage::getLayerCount() const -> Layer::Index { return this->layer.size(); } /** * Layer ID 0 = Background, Layer ID 1 = Layer 1 */ auto XojPage::getSelectedLayerId() -> Layer::Index { if (this->currentLayer == npos) { this->currentLayer = this->layer.size(); } return this->currentLayer; } void XojPage::setLayerVisible(Layer::Index layerId, bool visible) { if (layerId == 0) { backgroundVisible = visible; return; } layerId--; if (layerId >= this->layer.size()) { return; } this->layer[layerId]->setVisible(visible); } auto XojPage::isLayerVisible(Layer::Index layerId) const -> bool { if (layerId == 0) { return backgroundVisible; } layerId--; if (layerId >= this->layer.size()) { return false; } return this->layer[layerId]->isVisible(); } void XojPage::setBackgroundPdfPageNr(size_t page) { this->pdfBackgroundPage = page; this->bgType.format = PageTypeFormat::Pdf; this->bgType.config = ""; } void XojPage::setBackgroundColor(Color color) { this->backgroundColor = color; } auto XojPage::getBackgroundColor() const -> Color { return this->backgroundColor; } void XojPage::setSize(double width, double height) { this->width = width; this->height = height; } auto XojPage::getWidth() const -> double { return this->width; } auto XojPage::getHeight() const -> double { return this->height; } auto XojPage::getPdfPageNr() const -> size_t { return this->pdfBackgroundPage; } auto XojPage::isAnnotated() const -> bool { for (Layer* l: this->layer) { if (l->isAnnotated()) { return true; } } return false; } void XojPage::setBackgroundType(const PageType& bgType) { this->bgType = bgType; if (!bgType.isPdfPage()) { this->pdfBackgroundPage = npos; } if (!bgType.isImagePage()) { this->backgroundImage.free(); } } auto XojPage::getBackgroundType() -> PageType { return this->bgType; } auto XojPage::getBackgroundImage() -> BackgroundImage& { return this->backgroundImage; } void XojPage::setBackgroundImage(BackgroundImage img) { this->backgroundImage = std::move(img); } auto XojPage::getSelectedLayer() -> Layer* { xoj_assert(!layer.empty()); size_t layer = getSelectedLayerId(); if (layer > 0) { layer--; } return this->layer[layer]; } auto XojPage::getBackgroundName() const -> std::string { return backgroundName.value_or(_("Background")); } auto XojPage::backgroundHasName() const -> bool { return backgroundName.has_value(); } void XojPage::setBackgroundName(const std::string& newName) { backgroundName = newName; }
4,952
C++
.cpp
133
32.639098
136
0.667015
xournalpp/xournalpp
10,962
791
1,098
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
12,370
DocumentHandler.cpp
xournalpp_xournalpp/src/core/model/DocumentHandler.cpp
#include "DocumentHandler.h" #include "model/DocumentChangeType.h" // for DocumentChangeType #include "DocumentListener.h" // for DocumentListener void DocumentHandler::addListener(DocumentListener* l) { this->listener.push_back(l); } void DocumentHandler::removeListener(DocumentListener* l) { this->listener.remove(l); } void DocumentHandler::fireDocumentChanged(DocumentChangeType type) { for (DocumentListener* dl: this->listener) { dl->documentChanged(type); } } void DocumentHandler::firePageSizeChanged(size_t page) { for (DocumentListener* dl: this->listener) { dl->pageSizeChanged(page); } } void DocumentHandler::firePageChanged(size_t page) { for (DocumentListener* dl: this->listener) { dl->pageChanged(page); } } void DocumentHandler::firePageInserted(size_t page) { for (DocumentListener* dl: this->listener) { dl->pageInserted(page); } } void DocumentHandler::firePageDeleted(size_t page) { for (DocumentListener* dl: this->listener) { dl->pageDeleted(page); } } void DocumentHandler::firePageSelected(size_t page) { for (DocumentListener* dl: this->listener) { dl->pageSelected(page); } }
1,141
C++
.cpp
23
47.130435
87
0.763538
xournalpp/xournalpp
10,962
791
1,098
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
12,371
Snapping.cpp
xournalpp_xournalpp/src/core/model/Snapping.cpp
#include "Snapping.h" #include <algorithm> // for min, max #include <cmath> // for pow, atan2, cos, hypot, remainder, sin, abs #include <cstdlib> // for abs #include "model/Point.h" // for Point namespace Snapping { [[nodiscard]] inline double roundToMultiple(double val, double multiple) { return val - std::remainder(val, multiple); } [[nodiscard]] inline double distance(Point const& a, Point const& b) { return std::hypot(b.x - a.x, b.y - a.y); } double snapVertically(double y, double gridSize, double tolerance) { double ySnapped = roundToMultiple(y, gridSize); return std::abs(ySnapped - y) < tolerance * gridSize / 2.0 ? ySnapped : y; } double snapHorizontally(double x, double gridSize, double tolerance) { double xSnapped = roundToMultiple(x, gridSize); return std::abs(xSnapped - x) < tolerance * gridSize / 2.0 ? xSnapped : x; } Point snapToGrid(Point const& pos, double gridSize, double tolerance) { double abs_tolerance = (gridSize / sqrt(2)) * tolerance; Point ret{roundToMultiple(pos.x, gridSize), roundToMultiple(pos.y, gridSize), pos.z}; return distance(ret, pos) < abs_tolerance ? ret : pos; } double snapAngle(double radian, double tolerance) { auto snapped = roundToMultiple(radian, M_PI_4 / 3.0); double abs_tolerance = (M_PI_4 / 6.0) * tolerance; return std::abs(snapped - radian) < abs_tolerance ? snapped : radian; } Point snapRotation(Point const& pos, Point const& center, double tolerance) { auto const dist = distance(pos, center); auto const angle = std::atan2(pos.y - center.y, pos.x - center.x); auto const snappedAngle = snapAngle(angle, tolerance); return {center.x + dist * std::cos(snappedAngle), // center.y + dist * std::sin(snappedAngle), pos.z}; } Point projToLine(Point const& pos, Point const& first, Point const& second) { const double scalar = ((first.x - pos.x) * (second.y - first.y) + (first.y - pos.y) * (first.x - second.x)) / (std::pow(second.y - first.y, 2) + std::pow(first.x - second.x, 2)); const double projX = pos.x + scalar * (second.y - first.y); const double projY = pos.y + scalar * (first.x - second.x); return Point(projX, projY, pos.z); } double distanceLine(Point const& pos, Point const& first, Point const& second) { const auto proj = projToLine(pos, first, second); if (std::min(first.x, second.x) <= proj.x && proj.x <= std::max(first.x, second.x) && std::min(first.y, second.y) <= proj.y && proj.y <= std::max(first.y, second.y)) { return distance(pos, proj); } else { const double dist1 = distance(pos, first); const double dist2 = distance(pos, second); return std::min(dist1, dist2); } } } // namespace Snapping
2,773
C++
.cpp
52
48.923077
120
0.665683
xournalpp/xournalpp
10,962
791
1,098
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
12,372
PageHandler.cpp
xournalpp_xournalpp/src/core/model/PageHandler.cpp
#include "PageHandler.h" #include "PageListener.h" // for PageListener namespace xoj::util { template <class T> class Rectangle; } // namespace xoj::util using xoj::util::Rectangle; PageHandler::PageHandler() = default; PageHandler::~PageHandler() = default; void PageHandler::addListener(PageListener* l) { this->listeners.push_back(l); } void PageHandler::removeListener(PageListener* l) { this->listeners.remove(l); } void PageHandler::fireRectChanged(Rectangle<double>& rect) { for (PageListener* pl: this->listeners) { pl->rectChanged(rect); } } void PageHandler::fireRangeChanged(Range& range) { for (PageListener* pl: this->listeners) { pl->rangeChanged(range); } } void PageHandler::fireElementChanged(Element* elem) { for (PageListener* pl: this->listeners) { pl->elementChanged(elem); } } void PageHandler::fireElementsChanged(const std::vector<Element*>& elements, Range range) { for (PageListener* pl: this->listeners) { pl->elementsChanged(elements, range); } } void PageHandler::firePageChanged() { for (PageListener* pl: this->listeners) { pl->pageChanged(); } }
1,124
C++
.cpp
28
37.571429
91
0.739852
xournalpp/xournalpp
10,962
791
1,098
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
12,373
Element.cpp
xournalpp_xournalpp/src/core/model/Element.cpp
#include "Element.h" #include <algorithm> // for max, min #include <cmath> // for ceil, floor, NAN #include <cstdint> // for uint32_t #include <glib.h> // for gint #include "util/safe_casts.h" // for as_unsigned #include "util/serializing/ObjectInputStream.h" // for ObjectInputStream #include "util/serializing/ObjectOutputStream.h" // for ObjectOutputStream using xoj::util::Rectangle; Element::Element(ElementType type): type(type) {} auto Element::getType() const -> ElementType { return this->type; } void Element::setX(double x) { this->x = x; this->sizeCalculated = false; } void Element::setY(double y) { this->y = y; this->sizeCalculated = false; } auto Element::getX() const -> double { if (!this->sizeCalculated) { this->sizeCalculated = true; calcSize(); } return x; } auto Element::getY() const -> double { if (!this->sizeCalculated) { this->sizeCalculated = true; calcSize(); } return y; } auto Element::getSnappedBounds() const -> Rectangle<double> { if (!this->sizeCalculated) { this->sizeCalculated = true; calcSize(); } return this->snappedBounds; } void Element::move(double dx, double dy) { this->x += dx; this->y += dy; this->snappedBounds = this->snappedBounds.translated(dx, dy); } auto Element::getElementWidth() const -> double { if (!this->sizeCalculated) { this->sizeCalculated = true; calcSize(); } return this->width; } auto Element::getElementHeight() const -> double { if (!this->sizeCalculated) { this->sizeCalculated = true; calcSize(); } return this->height; } auto Element::boundingRect() const -> Rectangle<double> { return Rectangle<double>(getX(), getY(), getElementWidth(), getElementHeight()); } void Element::setColor(Color color) { this->color = color; } auto Element::getColor() const -> Color { return this->color; } auto Element::intersectsArea(const GdkRectangle* src) const -> bool { // compute the smallest rectangle with integer coordinates containing the bounding box and having width, height > 0 auto x = getX(); auto y = getY(); auto x1 = gint(std::floor(getX())); auto y1 = gint(std::floor(getY())); auto x2 = gint(std::ceil(x + getElementWidth())); auto y2 = gint(std::ceil(y + getElementHeight())); GdkRectangle rect = {x1, y1, std::max(1, x2 - x1), std::max(1, y2 - y1)}; return gdk_rectangle_intersect(src, &rect, nullptr); } auto Element::intersectsArea(double x, double y, double width, double height) const -> bool { double dest_x = NAN, dest_y = NAN; double dest_w = NAN, dest_h = NAN; dest_x = std::max(getX(), x); dest_y = std::max(getY(), y); dest_w = std::min(getX() + getElementWidth(), x + width) - dest_x; dest_h = std::min(getY() + getElementHeight(), y + height) - dest_y; return (dest_w > 0 && dest_h > 0); } auto Element::isInSelection(ShapeContainer* container) const -> bool { if (!container->contains(getX(), getY())) { return false; } if (!container->contains(getX() + getElementWidth(), getY())) { return false; } if (!container->contains(getX(), getY() + getElementHeight())) { return false; } if (!container->contains(getX() + getElementWidth(), getY() + getElementHeight())) { return false; } return true; } auto Element::rescaleOnlyAspectRatio() -> bool { return false; } auto Element::rescaleWithMirror() -> bool { return false; } void Element::serialize(ObjectOutputStream& out) const { out.writeObject("Element"); out.writeDouble(this->x); out.writeDouble(this->y); out.writeUInt(uint32_t(this->color)); out.endObject(); } void Element::readSerialized(ObjectInputStream& in) { in.readObject("Element"); this->x = in.readDouble(); this->y = in.readDouble(); this->color = Color(in.readUInt()); in.endObject(); } namespace xoj { auto refElementContainer(const std::vector<ElementPtr>& elements) -> std::vector<Element*> { std::vector<Element*> result(elements.size()); std::transform(elements.begin(), elements.end(), result.begin(), [](auto const& e) { return e.get(); }); return result; } } // namespace xoj
4,316
C++
.cpp
122
31.188525
119
0.652247
xournalpp/xournalpp
10,962
791
1,098
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
12,374
Text.cpp
xournalpp_xournalpp/src/core/model/Text.cpp
#include "Text.h" #include <memory> #include <utility> // for move #include <glib.h> // for g_warning #include <pango/pangocairo.h> #include "model/AudioElement.h" // for AudioElement #include "model/Element.h" // for ELEMENT_TEXT, Eleme... #include "model/Font.h" // for XojFont #include "pdf/base/XojPdfPage.h" // for XojPdfRectangle #include "util/Rectangle.h" // for Rectangle #include "util/Stacktrace.h" // for Stacktrace #include "util/StringUtils.h" #include "util/raii/GObjectSPtr.h" #include "util/serializing/ObjectInputStream.h" // for ObjectInputStream #include "util/serializing/ObjectOutputStream.h" // for ObjectOutputStream using xoj::util::Rectangle; Text::Text(): AudioElement(ELEMENT_TEXT) { this->font.setName("Sans"); this->font.setSize(12); } Text::~Text() = default; auto Text::cloneText() const -> std::unique_ptr<Text> { auto text = std::make_unique<Text>(); text->font = this->font; text->text = this->text; text->setColor(this->getColor()); text->x = this->x; text->y = this->y; text->width = this->width; text->height = this->height; text->cloneAudioData(this); text->snappedBounds = this->snappedBounds; text->sizeCalculated = this->sizeCalculated; text->inEditing = this->inEditing; return text; } auto Text::clone() const -> ElementPtr { return cloneText(); } auto Text::getFont() -> XojFont& { return font; } void Text::setFont(const XojFont& font) { this->font = font; } auto Text::getFontSize() const -> double { return font.getSize(); } auto Text::getFontName() const -> std::string { return font.getName(); } auto Text::getText() const -> const std::string& { return this->text; } void Text::setText(std::string text) { this->text = std::move(text); sizeCalculated = false; } void Text::calcSize() const { auto layout = createPangoLayout(); pango_layout_set_text(layout.get(), this->text.c_str(), static_cast<int>(this->text.length())); int w = 0; int h = 0; pango_layout_get_size(layout.get(), &w, &h); this->width = (static_cast<double>(w)) / PANGO_SCALE; this->height = (static_cast<double>(h)) / PANGO_SCALE; this->updateSnapping(); } void Text::setWidth(double width) { this->width = width; this->updateSnapping(); } void Text::setHeight(double height) { this->height = height; this->updateSnapping(); } void Text::setInEditing(bool inEditing) { this->inEditing = inEditing; } auto Text::createPangoLayout() const -> xoj::util::GObjectSPtr<PangoLayout> { xoj::util::GObjectSPtr<PangoContext> c(pango_font_map_create_context(pango_cairo_font_map_get_default()), xoj::util::adopt); xoj::util::GObjectSPtr<PangoLayout> layout(pango_layout_new(c.get()), xoj::util::adopt); #if PANGO_VERSION_CHECK(1, 48, 5) // see https://gitlab.gnome.org/GNOME/pango/-/issues/499 pango_layout_set_line_spacing(layout.get(), 1.0); #endif updatePangoFont(layout.get()); return layout; } void Text::updatePangoFont(PangoLayout* layout) const { PangoFontDescription* desc = pango_font_description_from_string(this->getFontName().c_str()); pango_font_description_set_absolute_size(desc, this->getFontSize() * PANGO_SCALE); pango_layout_set_font_description(layout, desc); pango_font_description_free(desc); } void Text::scale(double x0, double y0, double fx, double fy, double rotation, bool) { // line width scaling option is not used // only proportional scale allowed... if (fx != fy) { g_warning("rescale font with fx != fy not supported: %lf / %lf", fx, fy); Stacktrace::printStacktrace(); } this->x -= x0; this->x *= fx; this->x += x0; this->y -= y0; this->y *= fy; this->y += y0; double size = this->font.getSize() * fx; this->font.setSize(size); sizeCalculated = false; } void Text::rotate(double x0, double y0, double th) {} auto Text::isInEditing() const -> bool { return this->inEditing; } auto Text::rescaleOnlyAspectRatio() -> bool { return true; } auto Text::intersects(double x, double y, double halfEraserSize) const -> bool { return intersects(x, y, halfEraserSize, nullptr); } auto Text::intersects(double x, double y, double halfEraserSize, double* gap) const -> bool { double x1 = this->x - halfEraserSize; double x2 = this->x + this->getElementWidth() + halfEraserSize; double y1 = this->y - halfEraserSize; double y2 = this->y + this->getElementHeight() + halfEraserSize; return x >= x1 && x <= x2 && y >= y1 && y <= y2; } void Text::serialize(ObjectOutputStream& out) const { out.writeObject("Text"); this->AudioElement::serialize(out); out.writeString(this->text); font.serialize(out); out.endObject(); } void Text::readSerialized(ObjectInputStream& in) { in.readObject("Text"); this->AudioElement::readSerialized(in); this->text = in.readString(); font.readSerialized(in); in.endObject(); } void Text::updateSnapping() const { this->snappedBounds = Rectangle<double>(this->x, this->y, this->width, this->height); } auto Text::findText(const std::string& search) const -> std::vector<XojPdfRectangle> { size_t patternLength = search.length(); if (patternLength == 0) { return {}; } auto layout = this->createPangoLayout(); pango_layout_set_text(layout.get(), this->text.c_str(), static_cast<int>(this->text.length())); std::string text = StringUtils::toLowerCase(this->text); std::string pattern = StringUtils::toLowerCase(search); std::vector<XojPdfRectangle> list; for (size_t pos = text.find(pattern); pos != std::string::npos; pos = text.find(pattern, pos + 1)) { XojPdfRectangle mark; PangoRectangle rect = {0}; pango_layout_index_to_pos(layout.get(), static_cast<int>(pos), &rect); mark.x1 = (static_cast<double>(rect.x)) / PANGO_SCALE + this->getX(); mark.y1 = (static_cast<double>(rect.y)) / PANGO_SCALE + this->getY(); pango_layout_index_to_pos(layout.get(), static_cast<int>(pos + patternLength - 1), &rect); mark.x2 = (static_cast<double>(rect.x) + rect.width) / PANGO_SCALE + this->getX(); mark.y2 = (static_cast<double>(rect.y) + rect.height) / PANGO_SCALE + this->getY(); list.push_back(mark); } return list; }
6,428
C++
.cpp
151
38.099338
109
0.66806
xournalpp/xournalpp
10,962
791
1,098
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
12,375
DocumentListener.cpp
xournalpp_xournalpp/src/core/model/DocumentListener.cpp
#include "DocumentListener.h" #include "model/DocumentChangeType.h" // for DocumentChangeType #include "DocumentHandler.h" // for DocumentHandler DocumentListener::DocumentListener() = default; DocumentListener::~DocumentListener() { unregisterListener(); } void DocumentListener::registerListener(DocumentHandler* handler) { this->handler = handler; handler->addListener(this); } void DocumentListener::unregisterListener() { if (this->handler) { this->handler->removeListener(this); } } void DocumentListener::documentChanged(DocumentChangeType type) {} void DocumentListener::pageSizeChanged(size_t page) {} void DocumentListener::pageChanged(size_t page) {} void DocumentListener::pageInserted(size_t page) {} void DocumentListener::pageDeleted(size_t page) {} void DocumentListener::pageSelected(size_t page) {}
855
C++
.cpp
20
39.95
67
0.786148
xournalpp/xournalpp
10,962
791
1,098
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
12,376
StrokeStyle.cpp
xournalpp_xournalpp/src/core/model/StrokeStyle.cpp
#include "StrokeStyle.h" #include <cstring> // for memcmp, strcmp, strncmp #include <iomanip> // for setprecision #include <iterator> // for ostream_iterator #include <map> // for map #include <sstream> // for istringstream #include <vector> // for vector #include "model/LineStyle.h" // for LineStyle namespace { constexpr auto CUSTOM_KEY = "cust: "; const std::map<std::string, std::vector<double>> predefinedPatterns = { {"dash", {6, 3}}, {"dashdot", {6, 3, 0.5, 3}}, {"dot", {0.5, 3}}}; auto formatStyle(const std::vector<double>& dashes) -> std::string { // Check if dashes match named predefined dashes. for (auto& pair: predefinedPatterns) { if (pair.second == dashes) { return pair.first; } } // Else generate custom dashes string std::ostringstream custom; custom << std::setprecision(2) << std::fixed; custom << CUSTOM_KEY; std::copy(dashes.begin(), dashes.end(), std::ostream_iterator<double>(custom, " ")); // Return dashes string with traling space removed. return custom.str().substr(0, custom.str().length() - 1); } } // namespace auto StrokeStyle::parseStyle(const std::string& style) -> LineStyle { auto it = predefinedPatterns.find(style); if (it != predefinedPatterns.end()) { LineStyle ls; std::vector<double> dashes = it->second; ls.setDashes(std::move(dashes)); return ls; } if (style.substr(0, strlen(CUSTOM_KEY)) != CUSTOM_KEY) { return LineStyle(); } std::stringstream dashStream(style); std::vector<double> dashes; dashStream.seekg(strlen(CUSTOM_KEY)); for (double value; dashStream >> value;) { dashes.push_back(value); } if (dashes.empty()) { return LineStyle(); } LineStyle ls; ls.setDashes(std::move(dashes)); return ls; } auto StrokeStyle::formatStyle(const LineStyle& style) -> std::string { const auto& dashes = style.getDashes(); if (!dashes.empty()) { return ::formatStyle(dashes); } // Should not be returned, in this case the attribute is not written return "plain"; }
2,162
C++
.cpp
60
31.066667
88
0.644434
xournalpp/xournalpp
10,962
791
1,098
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
12,377
PageType.cpp
xournalpp_xournalpp/src/core/model/PageType.cpp
#include "PageType.h" PageType::PageType(): format(PageTypeFormat::Lined) {} PageType::PageType(PageTypeFormat format): format(format) {} PageType::PageType(const PageType& other) { this->format = other.format; this->config = other.config; } PageType::~PageType() = default; /** * Compare Operator */ auto PageType::operator==(const PageType& other) const -> bool { return this->config == other.config && this->format == other.format; } auto PageType::operator!=(const PageType& other) const -> bool { return !(*this == other); } /** * PDF background */ auto PageType::isPdfPage() const -> bool { return this->format == PageTypeFormat::Pdf; } /** * Image Background */ auto PageType::isImagePage() const -> bool { return this->format == PageTypeFormat::Image; } /** * Special background */ auto PageType::isSpecial() const -> bool { return this->format == PageTypeFormat::Pdf || this->format == PageTypeFormat::Image; }
952
C++
.cpp
29
30.724138
92
0.702732
xournalpp/xournalpp
10,962
791
1,098
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
12,378
SplineSegment.cpp
xournalpp_xournalpp/src/core/model/SplineSegment.cpp
#include "SplineSegment.h" #include <cmath> // for abs #include <iterator> // for end SplineSegment::SplineSegment(const Point& p, const Point& q): firstKnot(p), secondKnot(q), firstControlPoint(p), secondControlPoint(q) {} SplineSegment::SplineSegment(const Point& p, const Point& fp, const Point& sp, const Point& q) { firstKnot = p; firstControlPoint = fp; secondControlPoint = sp; secondKnot = q; } void SplineSegment::draw(cairo_t* cr) const { cairo_move_to(cr, firstKnot.x, firstKnot.y); cairo_curve_to(cr, firstControlPoint.x, firstControlPoint.y, secondControlPoint.x, secondControlPoint.y, secondKnot.x, secondKnot.y); } auto SplineSegment::toPointSequence(bool usePressure) const -> std::list<Point> { if (isFlatEnough(usePressure)) { return {firstKnot}; } auto const& childSegments = subdivide(0.5, usePressure); auto left_points = childSegments.first.toPointSequence(usePressure); left_points.splice(end(left_points), childSegments.second.toPointSequence(usePressure)); return left_points; } auto SplineSegment::subdivide(float t, bool usePressure) const -> std::pair<SplineSegment, SplineSegment> { Point b0 = SplineSegment::linearInterpolate(firstKnot, firstControlPoint, t); // Same as evaluating a Bezier Point b1 = SplineSegment::linearInterpolate(firstControlPoint, secondControlPoint, t); Point b2 = SplineSegment::linearInterpolate(secondControlPoint, secondKnot, t); Point c0 = SplineSegment::linearInterpolate(b0, b1, t); Point c1 = SplineSegment::linearInterpolate(b1, b2, t); Point d0 = SplineSegment::linearInterpolate(c0, c1, t); // This would be the interpolated point if (usePressure) { /** * Beware: with this quite imperfect formula, the pressure does not change linearly with the lengths */ d0.z = t * firstKnot.z + (1 - t) * secondKnot.z; } SplineSegment firstPart = SplineSegment(firstKnot, b0, c0, d0); // first point of each step SplineSegment secondPart = SplineSegment(d0, c1, b2, secondKnot); // last point of each step return std::make_pair(firstPart, secondPart); } auto SplineSegment::linearInterpolate(const Point& p, const Point& q, float t) -> Point { return Point(p.x * (1 - t) + q.x * t, p.y * (1 - t) + q.y * t); } constexpr double FLATNESS_TOLERANCE = 1.0001; constexpr double MIN_KNOT_DISTANCE = 0.3; constexpr double MAX_WIDTH_VARIATION = 0.1; auto SplineSegment::isFlatEnough(bool usePressure) const -> bool { double l1 = firstKnot.lineLengthTo(firstControlPoint); double l2 = firstControlPoint.lineLengthTo(secondControlPoint); double l3 = secondControlPoint.lineLengthTo(secondKnot); double l = firstKnot.lineLengthTo(secondKnot); return l < MIN_KNOT_DISTANCE || (l1 + l2 + l3 < FLATNESS_TOLERANCE * l && ((!usePressure) || std::abs(firstKnot.z - secondKnot.z) <= MAX_WIDTH_VARIATION)); }
2,989
C++
.cpp
56
48.160714
118
0.710175
xournalpp/xournalpp
10,962
791
1,098
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
12,379
LineStyle.cpp
xournalpp_xournalpp/src/core/model/LineStyle.cpp
#include "LineStyle.h" #include <cstring> // for memcpy #include <vector> // for vector #include <glib.h> // for g_free, g_malloc #include "util/serializing/ObjectInputStream.h" // for ObjectInputStream #include "util/serializing/ObjectOutputStream.h" // for ObjectOutputStream LineStyle::LineStyle() = default; LineStyle::~LineStyle() = default; auto LineStyle::operator==(const LineStyle& rhs) const -> bool { return dashes == rhs.dashes; } void LineStyle::serialize(ObjectOutputStream& out) const { out.writeObject("LineStyle"); out.writeData(this->dashes); out.endObject(); } void LineStyle::readSerialized(ObjectInputStream& in) { in.readObject("LineStyle"); in.readData(dashes); in.endObject(); } auto LineStyle::getDashes() const -> const std::vector<double>& { return dashes; } void LineStyle::setDashes(std::vector<double>&& dashes) { this->dashes = std::move(dashes); } auto LineStyle::hasDashes() const -> bool { return !dashes.empty(); }
997
C++
.cpp
22
42.5
95
0.73097
xournalpp/xournalpp
10,962
791
1,098
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
12,380
Font.cpp
xournalpp_xournalpp/src/core/model/Font.cpp
#include "Font.h" #include <cstdlib> // for atof #include <regex> // for match_results, rege... #include <sstream> // for basic_ostream, oper... #include <utility> // for move #include "util/serdesstream.h" #include "util/serializing/ObjectInputStream.h" // for ObjectInputStream #include "util/serializing/ObjectOutputStream.h" // for ObjectOutputStream XojFont::XojFont(std::string name, double size) { setName(std::move(name)); setSize(size); } auto XojFont::getName() const -> const std::string& { return this->name; } void XojFont::setName(std::string name) { this->name = std::move(name); } auto XojFont::getSize() const -> double { return size; } void XojFont::setSize(double size) { this->size = size; } XojFont::XojFont(const char* description) { // See https://stackoverflow.com/questions/44949784/c-regex-which-group-matched for // a good overview of regular expressions in C++. std::regex pangoFontDescriptionRegex{"^(.*) (\\d+[.]?\\d*)$"}; std::match_results<const char*> results; std::regex_search(description, results, pangoFontDescriptionRegex); if (results.size() > 1) { this->name = results[1].str(); } else { this->name = ""; } if (results.size() > 2) { this->size = atof(results[2].str().c_str()); } else { this->size = 0; } } XojFont& XojFont::operator=(const std::string& description) { return *this = XojFont(description.c_str()); } auto XojFont::asString() const -> std::string { auto result = serdes_stream<std::stringstream>(); result << getName() << " " << getSize(); return result.str(); } void XojFont::serialize(ObjectOutputStream& out) const { out.writeObject("XojFont"); out.writeString(this->name); out.writeDouble(this->size); out.endObject(); } void XojFont::readSerialized(ObjectInputStream& in) { in.readObject("XojFont"); this->name = in.readString(); this->size = in.readDouble(); in.endObject(); }
1,995
C++
.cpp
51
35.215686
108
0.670478
xournalpp/xournalpp
10,962
791
1,098
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
12,381
Stroke.cpp
xournalpp_xournalpp/src/core/model/Stroke.cpp
#include "Stroke.h" #include <algorithm> // for min, max, copy #include <cmath> // for abs, hypot, sqrt #include <cstdint> // for uint64_t #include <iterator> // for back_insert_iterator #include <limits> // for numeric_limits #include <memory> #include <numeric> // for accumulate #include <optional> // for optional, nullopt #include <string> // for to_string, operator<< #include <cairo.h> // for cairo_matrix_translate #include <glib.h> // for g_free, g_message #include "eraser/PaddedBox.h" // for PaddedBox #include "model/AudioElement.h" // for AudioElement #include "model/Element.h" // for Element, ELEMENT_ST... #include "model/LineStyle.h" // for LineStyle #include "model/Point.h" // for Point, Point::NO_PR... #include "util/Assert.h" // for xoj_assert #include "util/BasePointerIterator.h" // for BasePointerIterator #include "util/Interval.h" // for Interval #include "util/PairView.h" // for PairView<>::BaseIte... #include "util/PlaceholderString.h" // for PlaceholderString #include "util/Rectangle.h" // for Rectangle #include "util/SmallVector.h" // for SmallVector #include "util/TinyVector.h" // for TinyVector #include "util/i18n.h" // for FC, FORMAT_STR #include "util/serdesstream.h" // for serdes_stream #include "util/serializing/ObjectInputStream.h" // for ObjectInputStream #include "util/serializing/ObjectOutputStream.h" // for ObjectOutputStream #include "PathParameter.h" // for PathParameter #include "config-debug.h" // for ENABLE_ERASER_DEBUG using xoj::util::Rectangle; #define COMMA , // #define ENABLE_ERASER_DEBUG // See config-debug.h.in #ifdef ENABLE_ERASER_DEBUG #include <iomanip> // for operator<<, setw #include <sstream> // for operator<<, basic_o... #define DEBUG_ERASER(f) f #else #define DEBUG_ERASER(f) #endif template <typename Float> constexpr void updateBoundingBox(Float& x, Float& y, Float& width, Float& height, Point const& p, double half_width) { { Float x2 = x + width; Float y2 = y + height; x = std::min(x, p.x - half_width); y = std::min(y, p.y - half_width); x2 = std::max(x2, p.x + half_width); y2 = std::max(y2, p.y + half_width); width = x2 - x; height = y2 - y; } } template <typename Float> constexpr void updateSnappedBounds(Rectangle<Float>& snap, Point const& p) { { Float snapx2 = snap.x + snap.width; Float snapy2 = snap.y + snap.height; snap.x = std::min(snap.x, p.x); snap.y = std::min(snap.y, p.y); snapx2 = std::max(snapx2, p.x); snapy2 = std::max(snapy2, p.y); snap.width = snapx2 - snap.x; snap.height = snapy2 - snap.y; } } Stroke::Stroke(): AudioElement(ELEMENT_STROKE) {} Stroke::~Stroke() = default; /** * Clone style attributes, but not the data (position, pressure etc.) */ void Stroke::applyStyleFrom(const Stroke* other) { setColor(other->getColor()); setToolType(other->getToolType()); setWidth(other->getWidth()); setFill(other->getFill()); setStrokeCapStyle(other->getStrokeCapStyle()); setLineStyle(other->getLineStyle()); cloneAudioData(other); } auto Stroke::cloneStroke() const -> std::unique_ptr<Stroke> { auto s = std::make_unique<Stroke>(); s->applyStyleFrom(this); s->points = this->points; s->x = this->x; s->y = this->y; s->Element::width = this->Element::width; s->Element::height = this->Element::height; s->snappedBounds = this->snappedBounds; s->sizeCalculated = this->sizeCalculated; return s; } auto Stroke::clone() const -> ElementPtr { return this->cloneStroke(); } std::unique_ptr<Stroke> Stroke::cloneSection(const PathParameter& lowerBound, const PathParameter& upperBound) const { xoj_assert(lowerBound.isValid() && upperBound.isValid()); xoj_assert(lowerBound <= upperBound); xoj_assert(upperBound.index < this->points.size() - 1); auto s = std::make_unique<Stroke>(); s->applyStyleFrom(this); s->points.reserve(upperBound.index - lowerBound.index + 2); s->points.emplace_back(this->getPoint(lowerBound)); auto beginIt = std::next(this->points.cbegin(), (std::ptrdiff_t)lowerBound.index + 1); auto endIt = std::next(this->points.cbegin(), (std::ptrdiff_t)upperBound.index + 1); std::copy(beginIt, endIt, std::back_inserter(s->points)); s->points.emplace_back(this->getPoint(upperBound)); // Remove unused pressure value s->points.back().z = Point::NO_PRESSURE; return s; } std::unique_ptr<Stroke> Stroke::cloneCircularSectionOfClosedStroke(const PathParameter& startParam, const PathParameter& endParam) const { xoj_assert(startParam.isValid() && endParam.isValid()); xoj_assert(endParam < startParam); xoj_assert(startParam.index < this->points.size() - 1); auto s = std::make_unique<Stroke>(); s->applyStyleFrom(this); s->points.reserve(this->points.size() - startParam.index + endParam.index + 1); s->points.emplace_back(this->getPoint(startParam)); auto startIt = std::next(this->points.cbegin(), (std::ptrdiff_t)startParam.index + 1); // Skip the last point: points.back().equalPos(points.front()) == true and we want this point only once xoj_assert(startIt != this->points.cend()); std::copy(startIt, std::prev(this->points.cend()), std::back_inserter(s->points)); auto endIt = std::next(this->points.cbegin(), (std::ptrdiff_t)endParam.index + 1); std::copy(this->points.cbegin(), endIt, std::back_inserter(s->points)); s->points.emplace_back(this->getPoint(endParam)); // Remove unused pressure value s->points.back().z = Point::NO_PRESSURE; return s; } void Stroke::serialize(ObjectOutputStream& out) const { out.writeObject("Stroke"); this->AudioElement::serialize(out); out.writeDouble(this->width); out.writeInt(this->toolType); out.writeInt(fill); out.writeInt(this->capStyle); out.writeData(this->points.data(), this->points.size(), sizeof(Point)); this->lineStyle.serialize(out); out.endObject(); } void Stroke::readSerialized(ObjectInputStream& in) { in.readObject("Stroke"); this->AudioElement::readSerialized(in); this->width = in.readDouble(); this->toolType = static_cast<StrokeTool::Value>(in.readInt()); this->fill = in.readInt(); this->capStyle = static_cast<StrokeCapStyle>(in.readInt()); in.readData(this->points); this->lineStyle.readSerialized(in); in.endObject(); } /** * Option to fill the shape: * -1: The shape is not filled * 255: The shape is fully opaque filled * ... * 1: The shape is nearly fully transparent filled */ auto Stroke::getFill() const -> int { return fill; } /** * Option to fill the shape: * -1: The shape is not filled * 255: The shape is fully opaque filled * ... * 1: The shape is nearly fully transparent filled */ void Stroke::setFill(int fill) { this->fill = fill; } void Stroke::setWidth(double width) { this->width = width; } auto Stroke::getWidth() const -> double { return this->width; } auto Stroke::rescaleWithMirror() -> bool { return true; } auto Stroke::isInSelection(ShapeContainer* container) const -> bool { for (auto&& p: this->points) { double px = p.x; double py = p.y; if (!container->contains(px, py)) { return false; } } return true; } void Stroke::addPoint(const Point& p) { this->points.emplace_back(p); if (!sizeCalculated) { return; } if (hasPressure()) { updateBoundsLastTwoPressures(); } else { updateBoundingBox(Element::x, Element::y, Element::width, Element::height, p, 0.5 * this->width); updateSnappedBounds(Element::snappedBounds, p); } } auto Stroke::getPointCount() const -> size_t { return this->points.size(); } auto Stroke::getPointVector() const -> std::vector<Point> const& { return points; } void Stroke::deletePointsFrom(size_t index) { points.resize(std::min(index, points.size())); this->sizeCalculated = false; } auto Stroke::getPoint(size_t index) const -> Point { if (index < 0 || index >= this->points.size()) { g_warning("Stroke::getPoint(%zu) out of bounds!", index); return Point(0., 0., Point::NO_PRESSURE); } return points.at(index); } Point Stroke::getPoint(PathParameter parameter) const { xoj_assert(parameter.isValid() && parameter.index < this->points.size() - 1); const Point& p = this->points[parameter.index]; Point res = p.relativeLineTo(this->points[parameter.index + 1], parameter.t); res.z = p.z; // The point's width should be that of the segment's first point return res; } auto Stroke::getPoints() const -> const Point* { return this->points.data(); } void Stroke::setPointVectorInternal(const Range* const snappingBox) { if (!snappingBox || this->points.empty() || this->points.front().z != Point::NO_PRESSURE) { // We cannot deduce the bounding box from the snapping box if the stroke has pressure values this->sizeCalculated = false; } else { xoj_assert(snappingBox->isValid()); this->snappedBounds = xoj::util::Rectangle<double>(*snappingBox); Element::x = snappingBox->minX - 0.5 * this->width; Element::y = snappingBox->minY - 0.5 * this->width; Element::width = snappingBox->getWidth() + this->width; Element::height = snappingBox->getHeight() + this->width; this->sizeCalculated = true; } } void Stroke::setPointVector(const std::vector<Point>& other, const Range* const snappingBox) { this->points = other; this->setPointVectorInternal(snappingBox); } void Stroke::setPointVector(std::vector<Point>&& other, const Range* const snappingBox) { this->points = std::move(other); this->setPointVectorInternal(snappingBox); } void Stroke::freeUnusedPointItems() { this->points = {begin(this->points), end(this->points)}; } void Stroke::setToolType(StrokeTool type) { this->toolType = type; } auto Stroke::getToolType() const -> StrokeTool { return this->toolType; } void Stroke::setLineStyle(const LineStyle& style) { this->lineStyle = style; } auto Stroke::getLineStyle() const -> const LineStyle& { return this->lineStyle; } void Stroke::move(double dx, double dy) { for (auto&& point: points) { point.x += dx; point.y += dy; } Element::x += dx; Element::y += dy; Element::snappedBounds = Element::snappedBounds.translated(dx, dy); } void Stroke::rotate(double x0, double y0, double th) { cairo_matrix_t rotMatrix; cairo_matrix_init_identity(&rotMatrix); cairo_matrix_translate(&rotMatrix, x0, y0); cairo_matrix_rotate(&rotMatrix, th); cairo_matrix_translate(&rotMatrix, -x0, -y0); for (auto&& p: points) { cairo_matrix_transform_point(&rotMatrix, &p.x, &p.y); } this->sizeCalculated = false; // Width and Height will likely be changed after this operation } void Stroke::scale(double x0, double y0, double fx, double fy, double rotation, bool restoreLineWidth) { double fz = (restoreLineWidth) ? 1 : sqrt(std::abs(fx * fy)); cairo_matrix_t scaleMatrix; cairo_matrix_init_identity(&scaleMatrix); cairo_matrix_translate(&scaleMatrix, x0, y0); cairo_matrix_rotate(&scaleMatrix, rotation); cairo_matrix_scale(&scaleMatrix, fx, fy); cairo_matrix_rotate(&scaleMatrix, -rotation); cairo_matrix_translate(&scaleMatrix, -x0, -y0); for (auto&& p: points) { cairo_matrix_transform_point(&scaleMatrix, &p.x, &p.y); if (p.z != Point::NO_PRESSURE) { p.z *= fz; } } this->width *= fz; this->sizeCalculated = false; } auto Stroke::hasPressure() const -> bool { if (!this->points.empty()) { return this->points[0].z != Point::NO_PRESSURE; } return false; } auto Stroke::getAvgPressure() const -> double { return std::accumulate(begin(this->points), end(this->points), 0.0, [](double l, Point const& p) { return l + p.z; }) / static_cast<double>(this->points.size()); } void Stroke::updateBoundsLastTwoPressures() { if (!sizeCalculated || this->points.empty()) { return; } auto const pointCount = this->getPointCount(); xoj_assert(pointCount >= 2); Point& p = this->points.back(); Point& p2 = this->points[pointCount - 2]; double pressure = p2.z; updateSnappedBounds(snappedBounds, p); updateBoundingBox(Element::x, Element::y, Element::width, Element::height, p, 0.5 * pressure); updateBoundingBox(Element::x, Element::y, Element::width, Element::height, p2, 0.5 * pressure); } void Stroke::scalePressure(double factor) { if (!hasPressure()) { return; } for (auto&& p: this->points) { p.z *= factor; } this->sizeCalculated = false; } void Stroke::setLastPressure(double pressure) { if (!this->points.empty()) { xoj_assert(pressure != Point::NO_PRESSURE); Point& back = this->points.back(); back.z = pressure; } } void Stroke::setSecondToLastPressure(double pressure) { auto const pointCount = this->getPointCount(); if (pointCount >= 2) { Point& p = this->points[pointCount - 2]; p.z = pressure; updateBoundsLastTwoPressures(); } } void Stroke::setPressure(const std::vector<double>& pressure) { // The last pressure is not used - as there is no line drawn from this point if (this->points.size() - 1 != pressure.size()) { g_warning("invalid pressure point count: %s, expected %s", std::to_string(pressure.size()).data(), std::to_string(this->points.size() - 1).data()); } auto max_size = std::min(pressure.size(), this->points.size() - 1); for (size_t i = 0U; i != max_size; ++i) { this->points[i].z = pressure[i]; } } /** * checks if the stroke is intersected by the eraser rectangle */ auto Stroke::intersects(double x, double y, double halfEraserSize) const -> bool { return intersects(x, y, halfEraserSize, nullptr); } /** * checks if the stroke is intersected by the eraser rectangle */ auto Stroke::intersects(double x, double y, double halfEraserSize, double* gap) const -> bool { if (this->points.empty()) { return false; } double x1 = x - halfEraserSize; double x2 = x + halfEraserSize; double y1 = y - halfEraserSize; double y2 = y + halfEraserSize; double lastX = points[0].x; double lastY = points[0].y; for (auto&& point: points) { double px = point.x; double py = point.y; if (px >= x1 && py >= y1 && px <= x2 && py <= y2) { if (gap) { *gap = 0; } return true; } double len = hypot(px - lastX, py - lastY); if (len >= halfEraserSize) { /** * The distance of the center of the eraser box to the line passing through (lastx, lasty) and (px, py) */ double p = std::abs((x - lastX) * (lastY - py) + (y - lastY) * (px - lastX)) / len; // If the distance p of the center of the eraser box to the (full) line is in the range, // we check whether the eraser box is not too far from the line segment through the two points. if (p <= halfEraserSize) { double centerX = (lastX + px) / 2; double centerY = (lastY + py) / 2; double distance = hypot(x - centerX, y - centerY); // For the above check we imagine a circle whose center is the mid point of the two points of the stroke // and whose radius is half the length of the line segment plus half the diameter of the eraser box // plus some small padding // If the center of the eraser box lies within that circle then we consider it to be close enough distance -= halfEraserSize * std::sqrt(2); constexpr double PADDING = 0.1; if (distance <= len / 2 + PADDING) { if (gap) { *gap = distance; } return true; } } } lastX = px; lastY = py; } return false; } /** * @brief Get the interval of length parameters where the line (pq) is in the rectangle. * @param p First point * @param q Second point * @param rectangle The rectangle * @return Optional interval res. * The line enters the rectangle at the point res.min * p + (1 - res.min) * q * The line leaves the rectangle at the point res.max * p + (1 - res.max) * q */ static std::optional<Interval<double>> intersectLineWithRectangle(const Point& p, const Point& q, const Rectangle<double>& rectangle) { auto intersectLineWithStrip = [](double a1, double a2, double stripAMin, double stripWidth) { // a1, a2 are coordinates along an axis orthogonal to the strip double norm = 1.0 / (a2 - a1); double t1 = (stripAMin - a1) * norm; double t2 = t1 + stripWidth * norm; return Interval<double>::getInterval(t1, t2); }; if (p.x == q.x) { if (p.y == q.y) { // Single dot return std::nullopt; } // Vertical segment if (rectangle.x < p.x && p.x < rectangle.x + rectangle.width) { return intersectLineWithStrip(p.y, q.y, rectangle.y, rectangle.height); } return std::nullopt; } if (p.y == q.y) { // Horizontal segment if (rectangle.y < p.y && p.y < rectangle.y + rectangle.height) { return intersectLineWithStrip(p.x, q.x, rectangle.x, rectangle.width); } return std::nullopt; } // Generic case Interval<double> verticalIntersections = intersectLineWithStrip(p.y, q.y, rectangle.y, rectangle.height); Interval<double> horizontalIntersections = intersectLineWithStrip(p.x, q.x, rectangle.x, rectangle.width); return verticalIntersections.intersect(horizontalIntersections); } /** * Same as intersectLineWithRectangle but only returns parameters between 0 and 1 * (corresponding to points between p and q) */ static TinyVector<double, 2> intersectLineSegmentWithRectangle(const Point& p, const Point& q, const Rectangle<double>& rectangle) { std::optional<Interval<double>> intersections = intersectLineWithRectangle(p, q, rectangle); if (intersections) { TinyVector<double, 2> result; if (intersections->min > 0.0 && intersections->min <= 1.0) { result.emplace_back(intersections->min); } if (intersections->max > 0.0 && intersections->max <= 1.0) { result.emplace_back(intersections->max); } return result; } return {}; } auto Stroke::intersectWithPaddedBox(const PaddedBox& box) const -> IntersectionParametersContainer { auto pointCount = this->points.size(); if (pointCount < 2) { if (pointCount == 1 && this->points.back().isInside(box.getInnerRectangle())) { IntersectionParametersContainer result; result.emplace_back(0U, 0.0); result.emplace_back(0U, 0.0); return result; } return IntersectionParametersContainer(); } return this->intersectWithPaddedBox(box, 0, pointCount - 2); } auto Stroke::intersectWithPaddedBox(const PaddedBox& box, size_t firstIndex, size_t lastIndex) const -> IntersectionParametersContainer { xoj_assert(firstIndex <= lastIndex && lastIndex < this->points.size() - 1); const auto innerBox = box.getInnerRectangle(); const auto outerBox = box.getOuterRectangle(); struct Flags { bool isInsideOuter; bool wentInsideInner; bool lastSegmentEndedOnBoundary; }; auto initializeFlagsFromHalfTangentAtFirstKnot = [&outerBox, &innerBox](const Point& firstKnot, const Point& halfTangentControlPoint) -> Flags { if (firstKnot.isInside(innerBox)) { return {true, true, false}; } else if (firstKnot.isInside(outerBox)) { std::optional<Interval<double>> innerLineIntersections = intersectLineWithRectangle(firstKnot, halfTangentControlPoint, innerBox); // If the half tangent goes towards to inner box, say we've been inside the inner box return {true, innerLineIntersections && innerLineIntersections.value().max <= 0.0, false}; } return {false, false, false}; }; size_t index = firstIndex; const PairView segments(this->points); auto segmentIt = std::next(segments.begin(), (std::ptrdiff_t)index); Flags flags = initializeFlagsFromHalfTangentAtFirstKnot(segmentIt.first(), segmentIt.second()); DEBUG_ERASER(auto debugstream = serdes_stream<std::stringstream>(); debugstream << "Stroke::intersectWithPaddedBox debug:\n"; debugstream << std::boolalpha; debugstream << "| * flags.isInsideOuter = " << flags.isInsideOuter << std::endl; debugstream << "| * flags.wentInsideInner = " << flags.wentInsideInner << std::endl; debugstream << "| * flags.lastSegmentEndedOnBoundary = " << flags.lastSegmentEndedOnBoundary << std::endl; debugstream << std::fixed;) IntersectionParametersContainer result; if (flags.isInsideOuter) { // We start inside the padded box. Add a fake intersection parameter result.emplace_back(firstIndex, 0.0); } auto processSegment = [&flags, &outerBox, &innerBox, &result DEBUG_ERASER(COMMA & debugstream)]( const Point& firstKnot, const Point& secondKnot, size_t index) { DEBUG_ERASER(debugstream << "| * Segment " << std::setw(3) << index << std::setprecision(5); debugstream << ": (" << std::setw(9) << firstKnot.x; debugstream << " ; " << std::setw(9) << firstKnot.y; debugstream << ") -- (" << std::setw(9) << secondKnot.x; debugstream << " ; " << std::setw(9) << secondKnot.y; debugstream << ")\n" << std::setprecision(17); // High precision to detect numerical inaccuracy ) auto outerIntersections = intersectLineSegmentWithRectangle(firstKnot, secondKnot, outerBox); if (!outerIntersections.empty() || firstKnot.isInside(outerBox) || secondKnot.isInside(outerBox)) { // Some part of the segment lies inside the padded box auto innerIntersections = intersectLineSegmentWithRectangle(firstKnot, secondKnot, innerBox); auto itInner = innerIntersections.begin(); auto itInnerEnd = innerIntersections.end(); auto skipInnerIntersectionsBelowValue = [&itInner, itInnerEnd](double upToValue) -> bool { bool skipSome = false; while (itInner != itInnerEnd && *itInner < upToValue) { skipSome = true; ++itInner; } return skipSome; }; if (flags.lastSegmentEndedOnBoundary) { flags.lastSegmentEndedOnBoundary = false; Point p = secondKnot; if (!outerIntersections.empty()) { double t = 0.5 * outerIntersections.front(); p = firstKnot.relativeLineTo(secondKnot, t); } if (p.isInside(outerBox) != (result.size() % 2 != 0)) { // The stroke bounced back on the box border and never got in or out // Remove the last intersection point xoj_assert(!result.empty()); result.pop_back(); } } for (auto outerIntersection: outerIntersections) { flags.wentInsideInner |= skipInnerIntersectionsBelowValue(outerIntersection); DEBUG_ERASER(debugstream << "| | ** " << "wentInsideInner = " << flags.wentInsideInner << std::endl;) if (!flags.isInsideOuter || flags.wentInsideInner) { result.emplace_back(index, outerIntersection); if (outerIntersection == 1.0) { flags.lastSegmentEndedOnBoundary = true; } DEBUG_ERASER( if (!flags.isInsideOuter) { debugstream << "| | ** going-in (" << std::setw(3) << index << "," << std::setw(20) << outerIntersection << ")" << std::endl; } if (flags.wentInsideInner) { debugstream << "| | ** going-out (" << std::setw(3) << index << "," << std::setw(20) << outerIntersection << ")" << std::endl; }) } else { xoj_assert(!result.empty()); DEBUG_ERASER(debugstream << "| | ** popping (" << std::setw(3) << result.back().index << "," << std::setw(20) << result.back().t << ")" << std::endl;) result.pop_back(); } flags.wentInsideInner = false; flags.isInsideOuter = !flags.isInsideOuter; } if (itInner != itInnerEnd) { flags.wentInsideInner = true; } } DEBUG_ERASER(debugstream << "| |__** result.size() = " << std::setw(3) << result.size() << std::endl;) }; auto endSegmentIt = std::next(segments.begin(), (std::ptrdiff_t)(lastIndex + 1)); for (; segmentIt != endSegmentIt; segmentIt++, index++) { processSegment(segmentIt.first(), segmentIt.second(), index); } auto isHalfTangentAtLastKnotGoingTowardInnerBox = [&innerBox, &outerBox](const Point& lastKnot, const Point& halfTangentControlPoint) -> bool { xoj_assert(lastKnot.isInside(outerBox)); std::optional<Interval<double>> innerLineIntersections = intersectLineWithRectangle(lastKnot, halfTangentControlPoint, innerBox); return innerLineIntersections && innerLineIntersections.value().max < 0.0; }; /** * Due to numerical imprecision, we could get inconsistent results * (typically when a stroke's point lies on outerBox' boundary). * We try and detect those cases, and simply drop them */ bool inconsistentResults = false; if (result.size() % 2) { // Not necessarily inconsistent: could be the stroke ends in outerBox --segmentIt; const Point& lastPoint = segmentIt.second(); DEBUG_ERASER(debugstream << "| | Odd number of intersection points" << std::endl;) if (lastPoint.isInside(outerBox)) { if (flags.wentInsideInner || isHalfTangentAtLastKnotGoingTowardInnerBox(lastPoint, segmentIt.first())) { result.emplace_back(index - 1, 1.0); DEBUG_ERASER(debugstream << "| | ** pushing (" << std::setw(3) << result.back().index << "," << std::setw(20) << result.back().t << ")" << std::endl;) } else { DEBUG_ERASER(debugstream << "| | ** popping (" << std::setw(3) << result.back().index << "," << std::setw(20) << result.back().t << ")" << std::endl;) result.pop_back(); } } else { inconsistentResults = true; } } // Returns true if the result is inconsistent auto checkSanity = [&outerBox, this DEBUG_ERASER(COMMA & debugstream)](const IntersectionParametersContainer& res) -> bool { for (auto it1 = res.begin(), it2 = std::next(it1), end = res.end(); it1 != end; it1 += 2, it2 += 2) { const auto& paramStart = *it1; const auto& paramLast = *it2; DEBUG_ERASER(debugstream << "| SanityCheck on parameters (" << paramStart.index << " ; " << paramStart.t << ") -- (" << paramLast.index << " ; " << paramLast.t << ")" << std::endl;) Point testPoint; // Get a point on the stroke within the interval of parameters if (paramStart.index == paramLast.index) { testPoint = this->getPoint(PathParameter(paramStart.index, 0.5 * (paramStart.t + paramLast.t))); DEBUG_ERASER(debugstream << "| -------- getting point (" << paramStart.index << " ; " << 0.5 * (paramStart.t + paramLast.t) << ")" << std::endl;) } else { testPoint = this->getPoint((paramStart.index + paramLast.index + 1) / 2); DEBUG_ERASER(debugstream << "| -------- getting point (" << (paramStart.index + paramLast.index + 1) / 2 << " ; 0.0)" << std::endl;) } if (!testPoint.isInside(outerBox)) { DEBUG_ERASER(debugstream << "| --------- It is not in !!" << std::endl;) return true; } DEBUG_ERASER(debugstream << "| --------- It is in." << std::endl;) } return false; }; inconsistentResults = inconsistentResults || checkSanity(result); if (inconsistentResults) { DEBUG_ERASER(debugstream << "| Inconsistent results!\n"; debugstream << "| * innerBox = ("; debugstream << std::setprecision(5); debugstream << std::setw(9) << innerBox.x << " ; "; debugstream << std::setw(9) << innerBox.x + innerBox.width << ") -- ("; debugstream << std::setw(9) << innerBox.y << " ; "; debugstream << std::setw(9) << innerBox.y + innerBox.height << ")\n"; debugstream << "| * outerBox = ("; debugstream << std::setw(9) << outerBox.x << " ; "; debugstream << std::setw(9) << outerBox.x + outerBox.width << ") -- ("; debugstream << std::setw(9) << outerBox.y << " ; "; debugstream << std::setw(9) << outerBox.y + outerBox.height << ")\n"; std::cout << debugstream.str();) return {}; } return result; } /** * Updates the size * The size is needed to only redraw the requested part instead of redrawing * the whole page (performance reason). * Also used for Selected Bounding box. */ void Stroke::calcSize() const { if (this->points.empty()) { Element::x = 0; Element::y = 0; // The size of the rectangle, not the size of the pen! Element::width = 0; Element::height = 0; // used for snapping Element::snappedBounds = Rectangle<double>{}; } double minSnapX = std::numeric_limits<double>::max(); double maxSnapX = std::numeric_limits<double>::min(); double minSnapY = std::numeric_limits<double>::max(); double maxSnapY = std::numeric_limits<double>::min(); auto halfThick = 0.0; // #pragma omp parralel for (auto&& p: points) { halfThick = std::max(halfThick, p.z); minSnapX = std::min(minSnapX, p.x); minSnapY = std::min(minSnapY, p.y); maxSnapX = std::max(maxSnapX, p.x); maxSnapY = std::max(maxSnapY, p.y); } halfThick = points[0].z != Point::NO_PRESSURE ? halfThick / 2.0 : this->width / 2.0; auto minX = minSnapX - halfThick; auto minY = minSnapY - halfThick; auto maxX = maxSnapX + halfThick; auto maxY = maxSnapY + halfThick; Element::x = minX; Element::y = minY; Element::width = maxX - minX; Element::height = maxY - minY; Element::snappedBounds = Rectangle<double>(minSnapX, minSnapY, maxSnapX - minSnapX, maxSnapY - minSnapY); } auto Stroke::getErasable() const -> ErasableStroke* { return this->erasable; } void Stroke::setErasable(ErasableStroke* erasable) { this->erasable = erasable; } auto Stroke::getStrokeCapStyle() const -> StrokeCapStyle { return this->capStyle; } void Stroke::setStrokeCapStyle(const StrokeCapStyle capStyle) { this->capStyle = capStyle; } void Stroke::debugPrint() const { g_message("%s", FC(FORMAT_STR("Stroke {1} / hasPressure() = {2}") % (int64_t)this % this->hasPressure())); for (auto&& p: points) { g_message("%lf / %lf / %lf", p.x, p.y, p.z); } g_message("\n"); }
33,227
C++
.cpp
709
38.445698
120
0.601558
xournalpp/xournalpp
10,962
791
1,098
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
12,382
Document.cpp
xournalpp_xournalpp/src/core/model/Document.cpp
#include "Document.h" #include <codecvt> // for codecvt_utf8_utf16 #include <ctime> // for size_t, localtime, strf... #include <iomanip> #include <memory> #include <sstream> #include <string> // for string #include <utility> // for move, pair #include <glib-object.h> // for g_object_unref, G_TYPE_... #include "model/DocumentChangeType.h" // for DOCUMENT_CHANGE_CLEARED #include "model/DocumentHandler.h" // for DocumentHandler #include "model/PageRef.h" // for PageRef #include "model/PageType.h" // for PageType #include "pdf/base/XojPdfAction.h" // for XojPdfAction #include "pdf/base/XojPdfBookmarkIterator.h" // for XojPdfBookmarkIterator #include "util/PathUtil.h" // for clearExtensions #include "util/PlaceholderString.h" // for PlaceholderString #include "util/SaveNameUtils.h" // for parseFilename #include "util/Util.h" // for npos #include "util/glib_casts.h" // for wrap_v #include "util/i18n.h" // for FS, _F #include "util/raii/GObjectSPtr.h" // for GObjectSPtr #include "util/safe_casts.h" // for as_signed #include "LinkDestination.h" // for XojLinkDest, DOCUMENT_L... #include "XojPage.h" // for XojPage #include "filesystem.h" // for path Document::Document(DocumentHandler* handler): handler(handler) {} Document::~Document() { clearDocument(true); freeTreeContentModel(); } void Document::freeTreeContentModel() { if (this->contentsModel) { gtk_tree_model_foreach(this->contentsModel.get(), xoj::util::wrap_v<freeTreeContentEntry>, this); this->contentsModel.reset(); } } auto Document::freeTreeContentEntry(GtkTreeModel* treeModel, GtkTreePath* path, GtkTreeIter* iter, Document* doc) -> bool { XojLinkDest* link = nullptr; gtk_tree_model_get(treeModel, iter, DOCUMENT_LINKS_COLUMN_LINK, &link, -1); if (link == nullptr) { return false; } // The dispose function of XojLinkDest is not called, this workaround fixes the Memory Leak delete link->dest; link->dest = nullptr; return false; } void Document::lock() { this->documentLock.lock(); // if(tryLock()) { // fprintf(stderr, "Locked by\n"); // Stacktrace::printStacktrace(); // fprintf(stderr, "\n\n\n\n"); // } else { // g_mutex_lock(&this->documentLock); // } } void Document::unlock() { this->documentLock.unlock(); // fprintf(stderr, "Unlocked by\n"); // Stacktrace::printStacktrace(); // fprintf(stderr, "\n\n\n\n"); } /* ** Returns true when successfully acquiring lock. */ auto Document::tryLock() -> bool { return this->documentLock.try_lock(); } void Document::clearDocument(bool destroy) { if (this->preview) { cairo_surface_destroy(this->preview); this->preview = nullptr; } if (!destroy) { // release lock bool lastLock = tryLock(); unlock(); this->handler->fireDocumentChanged(DOCUMENT_CHANGE_CLEARED); if (!lastLock) // document was locked before { lock(); } } this->pages.clear(); this->pageIndex.reset(); freeTreeContentModel(); this->filepath = fs::path{}; this->pdfFilepath = fs::path{}; } /** * Returns the pageCount, this call don't need to be synchronized (if it's not critical, you may get wrong data) */ auto Document::getPageCount() const -> size_t { return this->pages.size(); } auto Document::getPdfPageCount() const -> size_t { return pdfDocument.getPageCount(); } void Document::setFilepath(fs::path filepath) { this->filepath = std::move(filepath); } auto Document::getFilepath() const -> fs::path { return filepath; } auto Document::getPdfFilepath() const -> fs::path { return pdfFilepath; } auto Document::createSaveFolder(fs::path lastSavePath) -> fs::path { if (!filepath.empty()) { return filepath.parent_path(); } if (!pdfFilepath.empty()) { return pdfFilepath.parent_path(); } return lastSavePath; } auto Document::createSaveFilename(DocumentType type, const std::string& defaultSaveName, const std::string& defaultPdfName) -> fs::path { constexpr static std::wstring_view forbiddenChars = {L"\\/:*?\"<>|"}; std::string wildcardString; if (type != Document::PDF) { if (!filepath.empty()) { // This can be any extension fs::path p = filepath.filename(); Util::clearExtensions(p); return p; } if (!pdfFilepath.empty()) { fs::path p = pdfFilepath.filename(); Util::clearExtensions(p, ".pdf"); return p; } } else if (!pdfFilepath.empty()) { wildcardString = SaveNameUtils::parseFilenameFromWildcardString(defaultPdfName, this->pdfFilepath.filename()); } else if (!filepath.empty()) { wildcardString = SaveNameUtils::parseFilenameFromWildcardString(defaultPdfName, this->filepath.filename()); } std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> converter; auto format_str = wildcardString.empty() ? defaultSaveName : wildcardString; auto format = converter.from_bytes(format_str); // Todo (cpp20): use <format> std::wostringstream ss; ss.imbue(std::locale()); time_t curtime = time(nullptr); ss << std::put_time(localtime(&curtime), format.c_str()); auto filename = ss.str(); // Todo (cpp20): use <ranges> for (auto& c: filename) { if ((c < 32 && c > 0) || c == 127 || forbiddenChars.find(c) != std::string::npos) { c = '_'; } } fs::path p = filename; Util::clearExtensions(p); return p; } auto Document::getPreview() const -> cairo_surface_t* { return this->preview; } void Document::setPreview(cairo_surface_t* preview) { if (this->preview) { cairo_surface_destroy(this->preview); } if (preview) { this->preview = cairo_surface_reference(preview); } else { this->preview = nullptr; } } auto Document::getEvMetadataFilename() const -> fs::path { if (!this->filepath.empty()) { return this->filepath; } if (!this->pdfFilepath.empty()) { return this->pdfFilepath; } return fs::path{}; } auto Document::isAttachPdf() const -> bool { return this->attachPdf; } auto Document::findPdfPage(size_t pdfPage) -> size_t { // Create a page index if not already indexed. if (!this->pageIndex) indexPdfPages(); auto pos = this->pageIndex->find(pdfPage); if (pos == this->pageIndex->end()) { return npos; } else { return pos->second; } } void Document::buildTreeContentsModel(GtkTreeIter* parent, XojPdfBookmarkIterator* iter) { do { GtkTreeIter treeIter = {0}; XojPdfAction* action = iter->getAction(); LinkDestination* dest = new LinkDestination(*action->getDestination()); XojLinkDest* link = link_dest_new(); link->dest = dest; if (action->getTitle().empty()) { g_object_unref(link); delete action; continue; } link->dest->setExpand(iter->isOpen()); gtk_tree_store_append(GTK_TREE_STORE(contentsModel.get()), &treeIter, parent); char* titleMarkup = g_markup_escape_text(action->getTitle().c_str(), -1); gtk_tree_store_set(GTK_TREE_STORE(contentsModel.get()), &treeIter, DOCUMENT_LINKS_COLUMN_NAME, titleMarkup, DOCUMENT_LINKS_COLUMN_LINK, link, DOCUMENT_LINKS_COLUMN_PAGE_NUMBER, "", -1); g_free(titleMarkup); g_object_unref(link); XojPdfBookmarkIterator* child = iter->getChildIter(); if (child) { buildTreeContentsModel(&treeIter, child); delete child; } delete action; } while (iter->next()); } void Document::indexPdfPages() { auto index = std::make_unique<PageIndex>(); for (size_t i = 0; i < this->pages.size(); ++i) { const auto& p = this->pages[i]; if (p->getBackgroundType().isPdfPage()) { index->emplace(p->getPdfPageNr(), i); } } this->pageIndex.swap(index); } void Document::buildContentsModel() { freeTreeContentModel(); XojPdfBookmarkIterator* iter = pdfDocument.getContentsIter(); if (iter == nullptr) { // No Bookmarks return; } this->contentsModel.reset(reinterpret_cast<GtkTreeModel*>(gtk_tree_store_new(4, G_TYPE_STRING, G_TYPE_OBJECT, G_TYPE_BOOLEAN, G_TYPE_STRING)), xoj::util::adopt); buildTreeContentsModel(nullptr, iter); delete iter; } auto Document::getContentsModel() const -> GtkTreeModel* { return this->contentsModel.get(); } auto Document::fillPageLabels(GtkTreeModel* treeModel, GtkTreePath* path, GtkTreeIter* iter, Document* doc) -> bool { XojLinkDest* link = nullptr; gtk_tree_model_get(treeModel, iter, DOCUMENT_LINKS_COLUMN_LINK, &link, -1); if (link == nullptr) { return false; } auto page = doc->findPdfPage(link->dest->getPdfPage()); gchar* pageLabel = nullptr; if (page != npos) { pageLabel = g_strdup_printf("%zu", page + 1); } gtk_tree_store_set(GTK_TREE_STORE(treeModel), iter, DOCUMENT_LINKS_COLUMN_PAGE_NUMBER, pageLabel, -1); g_free(pageLabel); g_object_unref(link); return false; } void Document::updateIndexPageNumbers() { if (this->contentsModel) { gtk_tree_model_foreach(this->contentsModel.get(), xoj::util::wrap_v<fillPageLabels>, this); } } void Document::setPdfAttributes(const fs::path& filename, bool attachToDocument) { this->pdfFilepath = filename; this->attachPdf = attachToDocument; } auto Document::readPdf(const fs::path& filename, bool initPages, bool attachToDocument, std::unique_ptr<std::string> data) -> bool { GError* popplerError = nullptr; lock(); if (data != nullptr) { if (!pdfDocument.load(std::move(data), password, &popplerError)) { lastError = FS(_F("Document not loaded! ({1}), {2}") % filename.u8string() % popplerError->message); g_error_free(popplerError); unlock(); return false; } } else { if (!pdfDocument.load(filename, password, &popplerError)) { if (popplerError) { lastError = FS(_F("Document not loaded! ({1}), {2}") % filename.u8string() % popplerError->message); g_error_free(popplerError); } else { lastError = FS(_F("Document not loaded! ({1}), {2}") % filename.u8string() % ""); } unlock(); return false; } } this->pdfFilepath = filename; this->attachPdf = attachToDocument; lastError = ""; if (initPages) { this->pages.clear(); } if (initPages) { for (size_t i = 0; i < pdfDocument.getPageCount(); i++) { XojPdfPageSPtr page = pdfDocument.getPage(i); auto p = std::make_shared<XojPage>(page->getWidth(), page->getHeight()); p->setBackgroundPdfPageNr(i); this->pages.emplace_back(std::move(p)); } } indexPdfPages(); buildContentsModel(); updateIndexPageNumbers(); unlock(); this->handler->fireDocumentChanged(DOCUMENT_CHANGE_PDF_BOOKMARKS); return true; } void Document::resetPdf() { pdfDocument.reset(); } void Document::setPageSize(PageRef p, double width, double height) { p->setSize(width, height); } auto Document::getPageWidth(PageRef p) -> double { return p->getWidth(); } auto Document::getPageHeight(PageRef p) -> double { return p->getHeight(); } /** * @return The last error message to show to the user */ auto Document::getLastErrorMsg() const -> std::string { return lastError; } void Document::deletePage(size_t pNr) { auto it = this->pages.begin() + as_signed(pNr); this->pages.erase(it); // Reset the page index this->pageIndex.reset(); updateIndexPageNumbers(); } void Document::insertPage(const PageRef& p, size_t position) { this->pages.insert(this->pages.begin() + as_signed(position), p); // Reset the page index this->pageIndex.reset(); updateIndexPageNumbers(); } void Document::addPage(const PageRef& p) { this->pages.push_back(p); // Reset the page index this->pageIndex.reset(); updateIndexPageNumbers(); } auto Document::indexOf(const PageRef& page) -> size_t { for (size_t i = 0; i < this->pages.size(); i++) { PageRef pg = this->pages[i]; if (pg == page) { return i; } } return npos; } auto Document::getPage(size_t page) const -> PageRef { if (getPageCount() <= page) { return nullptr; } if (page == npos) { return nullptr; } return this->pages[page]; } auto Document::getPdfPage(size_t page) const -> XojPdfPageSPtr { return this->pdfDocument.getPage(page); } auto Document::getPdfDocument() const -> const XojPdfDocument& { return this->pdfDocument; } auto Document::operator=(const Document& doc) -> Document& { clearDocument(); // Copy PDF Document this->pdfDocument = doc.pdfDocument; this->password = doc.password; this->createBackupOnSave = doc.createBackupOnSave; this->pdfFilepath = doc.pdfFilepath; this->filepath = doc.filepath; this->pages = doc.pages; this->attachPdf = doc.attachPdf; indexPdfPages(); buildContentsModel(); updateIndexPageNumbers(); bool lastLock = tryLock(); unlock(); this->handler->fireDocumentChanged(DOCUMENT_CHANGE_COMPLETE); if (!lastLock) // document was locked before { lock(); } return *this; } void Document::setCreateBackupOnSave(bool backup) { this->createBackupOnSave = backup; } auto Document::shouldCreateBackupOnSave() const -> bool { return this->createBackupOnSave; }
14,165
C++
.cpp
370
32.172973
118
0.631214
xournalpp/xournalpp
10,962
791
1,098
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
12,383
ErasableStroke.cpp
xournalpp_xournalpp/src/core/model/eraser/ErasableStroke.cpp
#include "ErasableStroke.h" #include <algorithm> // for max, min, copy, lower_bound #include <cstddef> // for size_t, ptrdiff_t #include <iterator> // for next #include <optional> // for optional #include <tuple> // for forward_as_tuple #include <glib.h> // for g_warning #include "model/Point.h" // for Point #include "model/Stroke.h" // for Stroke, IntersectionParameter... #include "util/Assert.h" // for xoj_assert #include "util/Range.h" // for Range #include "util/SmallVector.h" // for SmallVector #include "util/UnionOfIntervals.h" // for UnionOfIntervals #include "ErasableStrokeOverlapTree.h" // for ErasableStroke::OverlapTree #include "PaddedBox.h" // for PaddedBox using xoj::util::Rectangle; ErasableStroke::ErasableStroke(const Stroke& stroke): stroke(stroke) { const auto& pts = this->stroke.getPointVector(); closedStroke = pts.size() >= 3 && pts.front().lineLengthTo(pts.back()) < CLOSED_STROKE_DISTANCE; } ErasableStroke::~ErasableStroke() = default; /** * Erasure works as follows: * * Two squares: * the visible eraser square * * the same square with a padding depending on the stroke's width (see #997) * * We erase every section of the stroke that comes in the box with its padding, provided it hits the box itself at * some point. * This means we erase a little outside the visible box, but only when the stroke enters or leaves the visible box. */ void ErasableStroke::beginErasure(const IntersectionParametersContainer& paddedIntersections, Range& range) { size_t n = this->stroke.getPointCount(); if (n < 2) { return; } xoj_assert(paddedIntersections.size() % 2 == 0); UnionOfIntervals<PathParameter> sections; // Contains the removed sections sections.appendData(paddedIntersections); // We will need to rerender everywhere a section was removed for (auto& s: sections.cloneToIntervalVector()) { range = range.unite(computeSubSectionBoundingBox(s)); } // Now contains remaining sections sections.complement({0, 0.0}, {n - 2, 1.0}); const bool highlighter = this->stroke.getToolType() == StrokeTool::HIGHLIGHTER; const bool filled = this->stroke.getFill() != -1; if (highlighter || filled) { auto subsections = sections.cloneToIntervalVector(); if (filled) { if (subsections.size() == 1) { // We erased the stroke from its ends. Simply add the end points to ensure the filling is rerendered const Point& p1 = this->stroke.getPointVector().front(); range.addPoint(p1.x, p1.y); const Point& p2 = this->stroke.getPointVector().back(); range.addPoint(p2.x, p2.y); } else { // The stroke was split in two or more (and possibly shrank). Need to rerender its entire box. range.addPoint(this->stroke.getX(), this->stroke.getY()); range.addPoint(this->stroke.getX() + this->stroke.getElementWidth(), this->stroke.getY() + this->stroke.getElementHeight()); } } else if (subsections.size() > 1) { /** * Highlighter and the stroke has been split in two or more subsections. * Rerender wherever those subsections overlap */ addOverlapsToRange(subsections, range); } } { // lock_guard range std::lock_guard<std::mutex> lock(this->sectionsMutex); this->remainingSections.swap(sections); } // release the mutex } void ErasableStroke::erase(const PaddedBox& box, Range& range) { size_t n = (size_t)this->stroke.getPointCount(); if (n < 2) { g_warning("Erasing empty stroke"); return; } std::vector<SubSection> sections = this->getRemainingSubSectionsVector(); if (sections.empty()) { /** Nothing left to erase! **/ std::lock_guard<std::mutex> lock(this->boxesMutex); boundingBoxes.clear(); return; } if (changesAtLastIteration) { // Remove the boxes of the cache corresponding to sections that no longer exist std::lock_guard<std::mutex> lock(this->boxesMutex); auto it = boundingBoxes.begin(); for (auto itSection = sections.cbegin(), itSectionEnd = sections.cend(); it != boundingBoxes.end() && itSection != itSectionEnd;) { if (*itSection < it->first) { ++itSection; } else if (*itSection > it->first) { it = boundingBoxes.erase(it); } else { ++it; } } boundingBoxes.erase(it, boundingBoxes.end()); } /** * Determine which (intervals of) segments are still (partially) visible and have their bounding box intersecting * the eraser square * * This avoids computing a segment's intersections with the eraser box twice */ std::vector<Interval<size_t>> indexIntervals; for (const SubSection& section: sections) { if (!getSubSectionBoundingBox(section).intersect(Range(box.getInnerRectangle())).empty()) { if (indexIntervals.empty()) { indexIntervals.emplace_back(section.min.index, section.max.index); } else { if (indexIntervals.back().max + 1 >= section.min.index) { // Merge together two sections if the first ends in the segment in which the second begins indexIntervals.back().envelop(section.max.index); } else { indexIntervals.emplace_back(section.min.index, section.max.index); } } } } UnionOfIntervals<PathParameter> newErasedSections; for (auto& i: indexIntervals) { newErasedSections.appendData(this->stroke.intersectWithPaddedBox(box, i.min, i.max)); } changesAtLastIteration = !newErasedSections.empty(); if (changesAtLastIteration) { // We will need to rerender everywhere a section was removed for (auto& s: newErasedSections.cloneToIntervalVector()) { range = range.unite(computeSubSectionBoundingBox(s)); } const bool highlighter = this->stroke.getToolType() == StrokeTool::HIGHLIGHTER; const bool filled = this->stroke.getFill() != -1; if (highlighter || filled) { /** * Detect if a section has been modified. If so, rerender whatever needs rerendering. */ std::vector<SubSection> newRemainingSections; // Update the remaining sections newErasedSections.complement({0, 0.0}, {n - 2, 1.0}); { // lock_guard scope std::lock_guard<std::mutex> lock(sectionsMutex); remainingSections.intersect(newErasedSections.getData()); newRemainingSections = remainingSections.cloneToIntervalVector(); } // Release the mutex auto itNewSection = newRemainingSections.begin(); auto itNewSectionEnd = newRemainingSections.end(); for (auto& section: sections) { // Find out which new sections belonged to the same section before std::vector<SubSection> subsections; while (itNewSection != itNewSectionEnd && itNewSection->max <= section.max) { subsections.emplace_back(*itNewSection); ++itNewSection; } if (subsections.empty()) { // The section was entirely erased. No need for special rerendering. continue; } if (filled) { if (subsections.size() == 1) { const auto& subsection = subsections.back(); if (subsection.min == section.min && subsection.max == section.max) { // No modification continue; } // The section shrank. Point p = this->stroke.getPoint(section.min); range.addPoint(p.x, p.y); p = this->stroke.getPoint(section.max); range.addPoint(p.x, p.y); p = this->stroke.getPoint(subsection.min); range.addPoint(p.x, p.y); p = this->stroke.getPoint(subsection.max); range.addPoint(p.x, p.y); continue; } // The section was split in two or more (and possibly shrank). Need to rerender its entire box. range = range.unite(this->getSubSectionBoundingBox(section)); break; } // Necessarily highlighter and not filled if (subsections.size() > 1) { /** * The section has been split in two (or more). * Rerender wherever those subsections overlap. */ addOverlapsToRange(subsections, range); } } } else { // Update the remaining sections newErasedSections.complement({0, 0.0}, {n - 2, 1.0}); { // lock_guard scope std::lock_guard<std::mutex> lock(sectionsMutex); remainingSections.intersect(newErasedSections.getData()); } // Release the mutex } } } auto ErasableStroke::getStrokes() const -> std::vector<std::unique_ptr<Stroke>> { std::vector<SubSection> sections = this->getRemainingSubSectionsVector(); std::vector<std::unique_ptr<Stroke>> strokes; strokes.reserve(sections.size()); bool mergeFirstAndLast = this->closedStroke && sections.size() >= 2 && sections.front().min == PathParameter(0, 0.0) && sections.back().max == PathParameter(this->stroke.getPointCount() - 2, 1.0); auto sectionIt = sections.cbegin(); auto sectionEndIt = sections.cend(); if (mergeFirstAndLast) { /** * Clone the first and last sections as a single stroke */ strokes.push_back(this->stroke.cloneCircularSectionOfClosedStroke(sections.back().min, sections.front().max)); // Avoid cloning those sections again ++sectionIt; --sectionEndIt; } for (; sectionIt != sectionEndIt; ++sectionIt) { strokes.push_back(this->stroke.cloneSection(sectionIt->min, sectionIt->max)); } return strokes; } std::vector<ErasableStroke::SubSection> ErasableStroke::getRemainingSubSectionsVector() const { std::lock_guard<std::mutex> lock(this->sectionsMutex); return this->remainingSections.cloneToIntervalVector(); } bool ErasableStroke::isClosedStroke() const { return this->closedStroke; } auto ErasableStroke::getSubSectionBoundingBox(const ErasableStroke::SubSection& section) const -> const Range& { std::lock_guard<std::mutex> lock(this->boxesMutex); // First look for the box in the cache auto it = std::lower_bound(boundingBoxes.begin(), boundingBoxes.end(), section, [](const std::pair<SubSection, Range>& cacheData, const SubSection& section) { return cacheData.first < section; }); if (it != boundingBoxes.end() && section == it->first) { // There was already a box computed for this section return it->second; } // Need to compute the bounding box // Assign the computed box to the cache it = boundingBoxes.emplace(it, std::piecewise_construct, std::forward_as_tuple(section), std::forward_as_tuple(computeSubSectionBoundingBox(section))); return it->second; } auto ErasableStroke::computeSubSectionBoundingBox(const SubSection& section) const -> Range { const bool hasPressure = this->stroke.hasPressure(); const double halfWidth = 0.5 * this->stroke.getWidth(); double lastPressure = 0; auto pointRange = [&](const Point& p) { const double padding = hasPressure ? 0.5 * std::max(lastPressure, p.z) : halfWidth; lastPressure = p.z; return Range(p.x - padding, p.y - padding, p.x + padding, p.y + padding); }; Range rg = pointRange(this->stroke.getPoint(section.min)); auto data = this->stroke.getPointVector(); auto endIt = std::next(data.cbegin(), (std::ptrdiff_t)section.max.index + 1); for (auto ptIt = std::next(data.cbegin(), (std::ptrdiff_t)section.min.index + 1); ptIt != endIt; ++ptIt) { rg = rg.unite(pointRange(*ptIt)); } return rg.unite(pointRange(this->stroke.getPoint(section.max))); } void ErasableStroke::addOverlapsToRange(const std::vector<SubSection>& subsections, Range& range) { // Will contain the intersection trees of the subsections std::vector<OverlapTree> overlapTrees(subsections.size()); /** * For each given subsection, we compute a binary tree whose leaves correspond to individual segments in the * subsection and contain the thin bounding box of the segments. * The nodes contain the union of the bounding boxes of their children, so that the root itself contains the * bounding box of the subsection. * * To compute the overlaps between two subsections, we intersect the bounding boxes in their trees, until we reach * intersecting leaves. * See ErasableStroke::OverlapTree for the details. */ const double halfWidth = 0.5 * this->stroke.getWidth(); size_t i = 0; size_t j = 0; for (auto it1 = subsections.cbegin(), itEnd = subsections.cend(); it1 != itEnd; ++it1, ++i) { j = i + 1; for (auto it2 = std::next(it1); it2 != itEnd; ++it2, ++j) { if (!getSubSectionBoundingBox(*it1).intersect(getSubSectionBoundingBox(*it2)).empty()) { // Compute the intersections trees if they have not yet been computed if (!overlapTrees[i].isPopulated()) { overlapTrees[i].populate(*it1, this->stroke); } if (!overlapTrees[j].isPopulated()) { overlapTrees[j].populate(*it2, this->stroke); } #ifdef DEBUG_ERASABLE_STROKE_BOXES overlapTrees[i].addOverlapsToRange(overlapTrees[j], halfWidth, range, debugMask.get()); #else overlapTrees[i].addOverlapsToRange(overlapTrees[j], halfWidth, range); #endif } } } } #ifdef DEBUG_ERASABLE_STROKE_BOXES void ErasableStroke::paintDebugRect(const Rectangle<double>& rect, char color, cairo_t* cr) { if (cr == nullptr) { return; } if (color == 'r') { cairo_set_source_rgba(cr, 1, 0, 0, 0.8); } else if (color == 'g') { cairo_set_source_rgba(cr, 0, 1, 0, 0.8); } else if (color == 'b') { cairo_set_source_rgba(cr, 0, 0, 1, 0.8); } else { cairo_set_source_rgba(cr, 0.5, 0.5, 0.5, 0.8); } cairo_move_to(cr, rect.x, rect.y); cairo_line_to(cr, rect.x + rect.width, rect.y); cairo_line_to(cr, rect.x + rect.width, rect.y + rect.height); cairo_line_to(cr, rect.x, rect.y + rect.height); cairo_line_to(cr, rect.x, rect.y); cairo_stroke(cr); } #endif
15,511
C++
.cpp
323
37.962848
118
0.606171
xournalpp/xournalpp
10,962
791
1,098
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
12,384
ErasableStrokeOverlapTree.cpp
xournalpp_xournalpp/src/core/model/eraser/ErasableStrokeOverlapTree.cpp
#include "ErasableStrokeOverlapTree.h" #include <algorithm> // for max, min, minmax #include <optional> // for optional #include <tuple> // for tie, tuple #include "model/PathParameter.h" // for PathParameter #include "model/Point.h" // for Point #include "model/Stroke.h" // for Stroke #include "model/eraser/ErasableStroke.h" // for ErasableStroke::SubSection #include "util/Assert.h" // for xoj_assert #include "util/Range.h" // for Range using xoj::util::Rectangle; void ErasableStroke::OverlapTree::populate(const SubSection& section, const Stroke& stroke) { Populator populator(this->data, stroke); populator.populate(section, this->root); populated = true; } bool ErasableStroke::OverlapTree::isPopulated() const { return populated; } #ifdef DEBUG_ERASABLE_STROKE_BOXES void ErasableStroke::OverlapTree::addOverlapsToRange(const ErasableStroke::OverlapTree& other, double halfWidth, Range& range, cairo_t* cr) const { #else void ErasableStroke::OverlapTree::addOverlapsToRange(const ErasableStroke::OverlapTree& other, double halfWidth, Range& range) const { #endif xoj_assert(this->isPopulated() && other.isPopulated()); #ifdef DEBUG_ERASABLE_STROKE_BOXES this->root.addOverlapsToRange(other.root, halfWidth, range, cr); #else this->root.addOverlapsToRange(other.root, halfWidth, range); #endif } void ErasableStroke::OverlapTree::Populator::populate(const SubSection& section, Node& root) { xoj_assert(section.min.index <= section.max.index && section.max.index < stroke.getPointCount()); size_t nbLeaves = section.max.index - section.min.index + 1; this->data.resize(nbLeaves - 1); this->nextFreeSlot = this->data.begin(); if (section.min.index == section.max.index) { // The section spans on a single segment root.initializeOnSegment(this->stroke.getPoint(section.min), this->stroke.getPoint(section.max)); return; } if (section.max.t == 0.0) { if (section.min.index + 1 == section.max.index) { // The section spans on a single segment root.initializeOnSegment(this->stroke.getPoint(section.min), this->stroke.getPoint(section.max.index)); return; } if (section.min.t == 0.0) { this->populateNode(root, section.min.index, section.max.index, this->stroke.getPointVector()); return; } this->populateNode(root, this->stroke.getPoint(section.min), section.min.index + 1, section.max.index, this->stroke.getPointVector()); return; } if (section.min.t == 0.0) { this->populateNode(root, section.min.index, section.max.index, this->stroke.getPoint(section.max), this->stroke.getPointVector()); return; } this->populateNode(root, this->stroke.getPoint(section.min), section.min.index + 1, section.max.index, this->stroke.getPoint(section.max), this->stroke.getPointVector()); } auto ErasableStroke::OverlapTree::Populator::getNextFreeSlot() -> std::pair<Node, Node>* { xoj_assert(nextFreeSlot < data.end()); return &*(nextFreeSlot++); } void ErasableStroke::OverlapTree::Populator::populateNode(Node& node, const Point& firstPoint, size_t min, size_t max, const Point& lastPoint, const std::vector<Point>& pts) { xoj_assert(min <= max && max < pts.size()); /** * Split in two in the middle */ size_t middle = (min + max) / 2; node.children = getNextFreeSlot(); this->populateNode(node.children->first, firstPoint, min, middle, pts); this->populateNode(node.children->second, middle, max, lastPoint, pts); node.computeBoxFromChildren(); } void ErasableStroke::OverlapTree::Populator::populateNode(Node& node, const Point& firstPoint, size_t min, size_t max, const std::vector<Point>& pts) { xoj_assert(min <= max && max < pts.size()); if (min == max) { // The node corresponds to a single segment node.initializeOnSegment(firstPoint, pts[min]); return; } /** * Split in two */ size_t middle = (min + max) / 2; xoj_assert(middle >= min && middle < max); node.children = getNextFreeSlot(); this->populateNode(node.children->first, firstPoint, min, middle, pts); this->populateNode(node.children->second, middle, max, pts); node.computeBoxFromChildren(); } void ErasableStroke::OverlapTree::Populator::populateNode(Node& node, size_t min, size_t max, const Point& lastPoint, const std::vector<Point>& pts) { xoj_assert(min <= max && max < pts.size()); if (min == max) { // The node corresponds to a single segment node.initializeOnSegment(pts[min], lastPoint); return; } /** * Split in two */ size_t middle = (min + max + 1) / 2; xoj_assert(middle > min && middle <= max); node.children = getNextFreeSlot(); this->populateNode(node.children->first, min, middle, pts); this->populateNode(node.children->second, middle, max, lastPoint, pts); node.computeBoxFromChildren(); } void ErasableStroke::OverlapTree::Populator::populateNode(Node& node, size_t min, size_t max, const std::vector<Point>& pts) { xoj_assert(max > min); if (min + 1 == max) { // The node corresponds to a single segment node.initializeOnSegment(pts[min], pts[max]); return; } /** * Split in two */ size_t middle = (min + max) / 2; xoj_assert(middle > min && middle < max); node.children = getNextFreeSlot(); this->populateNode(node.children->first, min, middle, pts); this->populateNode(node.children->second, middle, max, pts); node.computeBoxFromChildren(); } void ErasableStroke::OverlapTree::Node::initializeOnSegment(const Point& p1, const Point& p2) { std::tie(this->minX, this->maxX) = std::minmax(p1.x, p2.x); std::tie(this->minY, this->maxY) = std::minmax(p1.y, p2.y); } void ErasableStroke::OverlapTree::Node::computeBoxFromChildren() { xoj_assert(children != nullptr); minX = std::min(children->first.minX, children->second.minX); maxX = std::max(children->first.maxX, children->second.maxX); minY = std::min(children->first.minY, children->second.minY); maxY = std::max(children->first.maxY, children->second.maxY); } #ifdef DEBUG_ERASABLE_STROKE_BOXES void ErasableStroke::OverlapTree::Node::addOverlapsToRange(const Node& other, double halfWidth, Range& range, cairo_t* cr) const { #else void ErasableStroke::OverlapTree::Node::addOverlapsToRange(const Node& other, double halfWidth, Range& range) const { #endif bool intersect = this->maxX + halfWidth > other.minX - halfWidth && this->minX - halfWidth<other.maxX + halfWidth&& this->maxY + halfWidth> other.minY - halfWidth && this->minY - halfWidth < other.maxY + halfWidth; if (!intersect) { return; } if (other.children != nullptr) { #ifdef DEBUG_ERASABLE_STROKE_BOXES other.children->first.addOverlapsToRange(*this, halfWidth, range, cr); other.children->second.addOverlapsToRange(*this, halfWidth, range, cr); #else other.children->first.addOverlapsToRange(*this, halfWidth, range); other.children->second.addOverlapsToRange(*this, halfWidth, range); #endif return; } /** * other is a leaf corresponding to a single segment of the stroke * Split *this until it's just a leaf */ if (this->children != nullptr) { #ifdef DEBUG_ERASABLE_STROKE_BOXES this->children->first.addOverlapsToRange(other, halfWidth, range, cr); this->children->second.addOverlapsToRange(other, halfWidth, range, cr); #else this->children->first.addOverlapsToRange(other, halfWidth, range); this->children->second.addOverlapsToRange(other, halfWidth, range); #endif return; } /** * Both this and other are leaves corresponding to single segments * Repaint the intersection of their bounding boxes */ auto rectThis = this->toRectangle(halfWidth); auto rectOther = other.toRectangle(halfWidth); auto inter = rectThis.intersects(rectOther); xoj_assert(inter); const Rectangle<double>& rect = inter.value(); #ifdef DEBUG_ERASABLE_STROKE_BOXES paintDebugRect(rectThis, 'g', cr); paintDebugRect(rectOther, 'g', cr); paintDebugRect(rect, 'b', cr); #endif range.addPoint(rect.x, rect.y); range.addPoint(rect.x + rect.width, rect.y + rect.height); } auto ErasableStroke::OverlapTree::Node::toRectangle(double padding) const -> Rectangle<double> { return {minX - padding, minY - padding, maxX - minX + 2 * padding, maxY - minY + 2 * padding}; }
9,190
C++
.cpp
200
38.655
118
0.647315
xournalpp/xournalpp
10,962
791
1,098
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
12,385
MoveSelectionToLayerUndoAction.cpp
xournalpp_xournalpp/src/core/undo/MoveSelectionToLayerUndoAction.cpp
#include "MoveSelectionToLayerUndoAction.h" #include <memory> // for __shared_ptr_access, __shared_pt... #include <glib.h> // for g_warning #include "control/Control.h" #include "model/Document.h" #include "model/Element.h" // for Element, ELEMENT_IMAGE, ELEMENT_... #include "model/Layer.h" // for Layer #include "model/PageRef.h" // for PageRef #include "model/XojPage.h" // for XojPage #include "undo/PageLayerPosEntry.h" // for PageLayerPosEntry, operator< #include "undo/UndoAction.h" // for UndoAction #include "util/i18n.h" // for _ MoveSelectionToLayerUndoAction::MoveSelectionToLayerUndoAction(const PageRef& page, LayerController* layerController, Layer* oldLayer, size_t oldLayerNo, size_t newLayerNo): UndoAction("MoveSelectionToLayerUndoAction"), layerController(layerController), oldLayer(oldLayer), oldLayerNo(oldLayerNo), newLayerNo(newLayerNo) { this->page = page; } auto MoveSelectionToLayerUndoAction::getText() -> std::string { return "Move selection to layer"; } auto MoveSelectionToLayerUndoAction::undo(Control* control) -> bool { if (elements.empty()) { this->undone = false; return false; } Document* doc = control->getDocument(); doc->lock(); for (const auto& elem: elements) { this->oldLayer->addElement(elem.layer->removeElement(elem.element).e); } this->layerController->switchToLay(oldLayerNo + 1); doc->unlock(); this->undone = false; return true; } auto MoveSelectionToLayerUndoAction::redo(Control* control) -> bool { if (elements.empty()) { this->undone = true; return false; } Document* doc = control->getDocument(); doc->lock(); for (const auto& elem: elements) { elem.layer->insertElement(this->oldLayer->removeElement(elem.element).e, elem.pos); } this->layerController->switchToLay(newLayerNo + 1); doc->unlock(); this->undone = true; return true; } void MoveSelectionToLayerUndoAction::addElement(Layer* layer, Element* e, Element::Index pos) { elements.emplace(layer, e, pos); }
2,179
C++
.cpp
56
34.482143
173
0.68072
xournalpp/xournalpp
10,962
791
1,098
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
12,386
SwapUndoAction.cpp
xournalpp_xournalpp/src/core/undo/SwapUndoAction.cpp
#include "SwapUndoAction.h" #include <utility> // for swap #include <glib.h> // for gint #include "control/Control.h" // for Control #include "control/ScrollHandler.h" // for ScrollHandler #include "model/Document.h" // for Document #include "undo/UndoAction.h" // for UndoAction #include "util/i18n.h" // for _ SwapUndoAction::SwapUndoAction(size_t pageNr, bool moveUp, const PageRef& swappedPage, const PageRef& otherPage): UndoAction("SwapUndoAction") { this->pageNr = pageNr; this->moveUp = moveUp; this->swappedPage = swappedPage; this->otherPage = otherPage; } SwapUndoAction::~SwapUndoAction() = default; auto SwapUndoAction::undo(Control* control) -> bool { swap(control); this->undone = true; return true; } auto SwapUndoAction::redo(Control* control) -> bool { swap(control); this->undone = false; return true; } void SwapUndoAction::swap(Control* control) { Document* doc = control->getDocument(); doc->lock(); size_t insertPos = this->pageNr; size_t deletePos = this->pageNr + 1; if (moveUp != this->undone) { std::swap(insertPos, deletePos); } doc->deletePage(deletePos); doc->insertPage(this->swappedPage, insertPos); doc->unlock(); control->firePageDeleted(deletePos); control->firePageInserted(insertPos); control->firePageSelected(insertPos); control->getScrollHandler()->scrollToPage(insertPos); } auto SwapUndoAction::getPages() -> std::vector<PageRef> { std::vector<PageRef> pages; pages.push_back(this->swappedPage); pages.push_back(this->otherPage); return pages; } auto SwapUndoAction::getText() -> std::string { return moveUp ? _("Move page upwards") : _("Move page downwards"); }
1,785
C++
.cpp
49
32.530612
116
0.689173
xournalpp/xournalpp
10,962
791
1,098
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
12,387
InsertUndoAction.cpp
xournalpp_xournalpp/src/core/undo/InsertUndoAction.cpp
#include "InsertUndoAction.h" #include <memory> // for allocator, __shared_ptr_access, __share... #include <utility> // for move #include "control/Control.h" #include "model/Document.h" #include "model/Element.h" // for Element, ELEMENT_IMAGE, ELEMENT_STROKE #include "model/Layer.h" // for Layer #include "model/PageRef.h" // for PageRef #include "model/XojPage.h" // for XojPage #include "undo/UndoAction.h" // for UndoAction #include "util/i18n.h" // for _ InsertUndoAction::InsertUndoAction(const PageRef& page, Layer* layer, Element* element): UndoAction("InsertUndoAction"), layer(layer), element(element), elementOwn(nullptr) { this->page = page; } InsertUndoAction::~InsertUndoAction() = default; auto InsertUndoAction::getText() -> std::string { switch (element->getType()) { case ELEMENT_STROKE: return _("Draw stroke"); case ELEMENT_TEXT: return _("Write text"); case ELEMENT_IMAGE: return _("Insert image"); case ELEMENT_TEXIMAGE: return _("Insert latex"); default: return ""; } } auto InsertUndoAction::undo(Control* control) -> bool { Document* doc = control->getDocument(); doc->lock(); this->elementOwn = this->layer->removeElement(this->element).e; doc->unlock(); this->page->fireElementChanged(this->element); this->undone = true; return true; } auto InsertUndoAction::redo(Control* control) -> bool { Document* doc = control->getDocument(); doc->lock(); this->layer->addElement(std::move(this->elementOwn)); doc->unlock(); this->page->fireElementChanged(this->element); this->undone = false; return true; } InsertsUndoAction::InsertsUndoAction(const PageRef& page, Layer* layer, std::vector<Element*> elements): UndoAction("InsertsUndoAction"), layer(layer), elements(std::move(elements)), elementsOwn(0) { this->page = page; } InsertsUndoAction::~InsertsUndoAction() = default; auto InsertsUndoAction::getText() -> std::string { return _("Insert elements"); } auto InsertsUndoAction::undo(Control* control) -> bool { this->elementsOwn.reserve(this->elements.size()); Document* doc = control->getDocument(); doc->lock(); for (Element* elem: this->elements) { this->elementsOwn.emplace_back(this->layer->removeElement(elem).e); } doc->unlock(); for (Element* elem: this->elements) { this->page->fireElementChanged(elem); } this->undone = true; return true; } auto InsertsUndoAction::redo(Control* control) -> bool { Document* doc = control->getDocument(); doc->lock(); for (auto&& elem: this->elementsOwn) { this->layer->addElement(std::move(elem)); } doc->unlock(); this->elementsOwn = std::vector<ElementPtr>(0); for (auto&& elem: this->elements) { this->page->fireElementChanged(elem); } this->undone = false; return true; }
2,995
C++
.cpp
82
31.573171
104
0.661821
xournalpp/xournalpp
10,962
791
1,098
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
12,388
ColorUndoAction.cpp
xournalpp_xournalpp/src/core/undo/ColorUndoAction.cpp
#include "ColorUndoAction.h" #include <algorithm> // for max, min #include <memory> // for __shared_ptr_access, __shared_ptr_acces... #include "control/Control.h" #include "model/Document.h" #include "model/Element.h" // for Element #include "model/XojPage.h" // for XojPage #include "undo/UndoAction.h" // for UndoAction #include "util/Rectangle.h" // for Rectangle #include "util/i18n.h" // for _ using xoj::util::Rectangle; class ColorUndoActionEntry { public: ColorUndoActionEntry(Element* e, Color oldColor, Color newColor): e(e), oldColor(oldColor), newColor(newColor) {} Element* e; Color oldColor; Color newColor; }; ColorUndoAction::ColorUndoAction(const PageRef& page, Layer* layer): UndoAction("ColorUndoAction") { this->page = page; this->layer = layer; } ColorUndoAction::~ColorUndoAction() { for (ColorUndoActionEntry* e: this->data) { delete e; } } void ColorUndoAction::addStroke(Element* e, Color originalColor, Color newColor) { this->data.push_back(new ColorUndoActionEntry(e, originalColor, newColor)); } auto ColorUndoAction::undo(Control* control) -> bool { if (this->data.empty()) { return true; } Document* doc = control->getDocument(); doc->lock(); ColorUndoActionEntry* e = this->data.front(); double x1 = e->e->getX(); double x2 = e->e->getX() + e->e->getElementWidth(); double y1 = e->e->getY(); double y2 = e->e->getY() + e->e->getElementHeight(); for (ColorUndoActionEntry* e: this->data) { e->e->setColor(e->oldColor); x1 = std::min(x1, e->e->getX()); x2 = std::max(x2, e->e->getX() + e->e->getElementWidth()); y1 = std::min(y1, e->e->getY()); y2 = std::max(y2, e->e->getY() + e->e->getElementHeight()); } doc->unlock(); Rectangle rect(x1, y1, x2 - x1, y2 - y1); this->page->fireRectChanged(rect); return true; } auto ColorUndoAction::redo(Control* control) -> bool { if (this->data.empty()) { return true; } Document* doc = control->getDocument(); doc->lock(); ColorUndoActionEntry* e = this->data.front(); double x1 = e->e->getX(); double x2 = e->e->getX() + e->e->getElementWidth(); double y1 = e->e->getY(); double y2 = e->e->getY() + e->e->getElementHeight(); for (ColorUndoActionEntry* e: this->data) { e->e->setColor(e->newColor); x1 = std::min(x1, e->e->getX()); x2 = std::max(x2, e->e->getX() + e->e->getElementWidth()); y1 = std::min(y1, e->e->getY()); y2 = std::max(y2, e->e->getY() + e->e->getElementHeight()); } doc->unlock(); Rectangle rect(x1, y1, x2 - x1, y2 - y1); this->page->fireRectChanged(rect); return true; } auto ColorUndoAction::getText() -> std::string { return _("Change color"); }
2,831
C++
.cpp
75
33.146667
117
0.625091
xournalpp/xournalpp
10,962
791
1,098
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
12,389
InsertLayerUndoAction.cpp
xournalpp_xournalpp/src/core/undo/InsertLayerUndoAction.cpp
#include "InsertLayerUndoAction.h" #include "control/Control.h" // for Control #include "control/layer/LayerController.h" // for LayerController #include "gui/MainWindow.h" // for MainWindow #include "gui/XournalView.h" // for XournalView #include "model/Document.h" // for Document #include "model/Layer.h" // for Layer, Layer::Index #include "model/PageRef.h" // for PageRef #include "undo/UndoAction.h" // for UndoAction #include "util/i18n.h" // for _ InsertLayerUndoAction::InsertLayerUndoAction(LayerController* layerController, const PageRef& page, Layer* layer, Layer::Index layerPosition): UndoAction("InsertLayerUndoAction"), layerPosition(layerPosition), layerController(layerController), layer(layer) { this->page = page; } InsertLayerUndoAction::~InsertLayerUndoAction() { if (this->undone) { // The layer was undone, also deleted delete this->layer; } } auto InsertLayerUndoAction::getText() -> std::string { return _("Insert layer"); } auto InsertLayerUndoAction::undo(Control* control) -> bool { Document* doc = control->getDocument(); doc->lock(); layerController->removeLayer(this->page, this->layer); doc->unlock(); this->undone = true; return true; } auto InsertLayerUndoAction::redo(Control* control) -> bool { Document* doc = control->getDocument(); doc->lock(); layerController->insertLayer(this->page, this->layer, layerPosition); auto id = doc->indexOf(this->page); doc->unlock(); control->getWindow()->getXournal()->layerChanged(id); this->undone = false; return true; }
1,802
C++
.cpp
43
36.953488
113
0.638286
xournalpp/xournalpp
10,962
791
1,098
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
12,390
LayerRenameUndoAction.cpp
xournalpp_xournalpp/src/core/undo/LayerRenameUndoAction.cpp
#include "LayerRenameUndoAction.h" #include "control/Control.h" #include "control/layer/LayerController.h" // for LayerController #include "model/Document.h" #include "model/Layer.h" // for Layer #include "undo/UndoAction.h" // for UndoAction #include "util/i18n.h" // for _ LayerRenameUndoAction::LayerRenameUndoAction(LayerController* layerController, Layer* layer, const std::string& newName, const std::string& oldName): UndoAction("LayerUndoAction"), layer(layer), layerController(layerController), newName(newName), oldName(oldName) {} LayerRenameUndoAction::~LayerRenameUndoAction() = default; auto LayerRenameUndoAction::getText() -> std::string { return _("Rename layer"); }; auto LayerRenameUndoAction::undo(Control* control) -> bool { Document* doc = control->getDocument(); doc->lock(); layer->setName(oldName); doc->unlock(); layerController->fireRebuildLayerMenu(); return true; } auto LayerRenameUndoAction::redo(Control* control) -> bool { Document* doc = control->getDocument(); doc->lock(); layer->setName(newName); doc->unlock(); layerController->fireRebuildLayerMenu(); return true; }
1,300
C++
.cpp
32
35.28125
120
0.666403
xournalpp/xournalpp
10,962
791
1,098
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
12,391
LineStyleUndoAction.cpp
xournalpp_xournalpp/src/core/undo/LineStyleUndoAction.cpp
#include "LineStyleUndoAction.h" #include <algorithm> // for max, min #include <memory> // for __shared_ptr_access, __shared_ptr_acces... #include "control/Control.h" #include "model/Document.h" #include "model/PageRef.h" // for PageRef #include "model/Stroke.h" // for Stroke #include "model/XojPage.h" // for XojPage #include "undo/UndoAction.h" // for UndoAction #include "util/Rectangle.h" // for Rectangle #include "util/i18n.h" // for _ using xoj::util::Rectangle; LineStyleUndoAction::LineStyleUndoAction(const PageRef& page, Layer* layer): UndoAction("LineStyleUndoAction") { this->page = page; this->layer = layer; } void LineStyleUndoAction::addStroke(Stroke* s, LineStyle originalStyle, LineStyle newStyle) { this->data.emplace_back(s, originalStyle, newStyle); } auto LineStyleUndoAction::undo(Control* control) -> bool { if (this->data.empty()) { return true; } Document* doc = control->getDocument(); doc->lock(); LineStyleUndoActionEntry e = this->data.front(); double x1 = e.s->getX(); double x2 = e.s->getX() + e.s->getElementWidth(); double y1 = e.s->getY(); double y2 = e.s->getY() + e.s->getElementHeight(); for (LineStyleUndoActionEntry& e: this->data) { e.s->setLineStyle(e.oldStyle); x1 = std::min(x1, e.s->getX()); x2 = std::max(x2, e.s->getX() + e.s->getElementWidth()); y1 = std::min(y1, e.s->getY()); y2 = std::max(y2, e.s->getY() + e.s->getElementHeight()); } doc->unlock(); Rectangle rect(x1, y1, x2 - x1, y2 - y1); this->page->fireRectChanged(rect); return true; } auto LineStyleUndoAction::redo(Control* control) -> bool { if (this->data.empty()) { return true; } Document* doc = control->getDocument(); doc->lock(); LineStyleUndoActionEntry e = this->data.front(); double x1 = e.s->getX(); double x2 = e.s->getX() + e.s->getElementWidth(); double y1 = e.s->getY(); double y2 = e.s->getY() + e.s->getElementHeight(); for (LineStyleUndoActionEntry& e: this->data) { e.s->setLineStyle(e.newStyle); x1 = std::min(x1, e.s->getX()); x2 = std::max(x2, e.s->getX() + e.s->getElementWidth()); y1 = std::min(y1, e.s->getY()); y2 = std::max(y2, e.s->getY() + e.s->getElementHeight()); } doc->unlock(); Rectangle rect(x1, y1, x2 - x1, y2 - y1); this->page->fireRectChanged(rect); return true; } auto LineStyleUndoAction::getText() -> std::string { return _("Change line style"); }
2,574
C++
.cpp
66
34.242424
112
0.627814
xournalpp/xournalpp
10,962
791
1,098
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
12,392
RemoveLayerUndoAction.cpp
xournalpp_xournalpp/src/core/undo/RemoveLayerUndoAction.cpp
#include "RemoveLayerUndoAction.h" #include "control/Control.h" // for Control #include "control/layer/LayerController.h" // for LayerController #include "gui/MainWindow.h" // for MainWindow #include "gui/XournalView.h" // for XournalView #include "model/Document.h" // for Document #include "model/Layer.h" // for Layer, Layer::Index #include "model/PageRef.h" // for PageRef #include "undo/UndoAction.h" // for UndoAction #include "util/i18n.h" // for _ RemoveLayerUndoAction::RemoveLayerUndoAction(LayerController* layerController, const PageRef& page, Layer* layer, Layer::Index layerPos): UndoAction("RemoveLayerUndoAction"), layerController(layerController), layer(layer), layerPos(layerPos) { this->page = page; } RemoveLayerUndoAction::~RemoveLayerUndoAction() { if (!this->undone) { // The layer was NOT undone, also NOT restored delete this->layer; } this->layer = nullptr; } auto RemoveLayerUndoAction::getText() -> std::string { return _("Delete layer"); } auto RemoveLayerUndoAction::undo(Control* control) -> bool { Document* doc = control->getDocument(); doc->lock(); layerController->insertLayer(this->page, this->layer, this->layerPos); auto id = doc->indexOf(this->page); doc->unlock(); control->getWindow()->getXournal()->layerChanged(id); this->undone = true; return true; } auto RemoveLayerUndoAction::redo(Control* control) -> bool { Document* doc = control->getDocument(); doc->lock(); layerController->removeLayer(page, layer); auto id = doc->indexOf(this->page); doc->unlock(); control->getWindow()->getXournal()->layerChanged(id); this->undone = false; return true; }
1,887
C++
.cpp
43
39.209302
113
0.643052
xournalpp/xournalpp
10,962
791
1,098
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
12,393
PageBackgroundChangedUndoAction.cpp
xournalpp_xournalpp/src/core/undo/PageBackgroundChangedUndoAction.cpp
#include "PageBackgroundChangedUndoAction.h" #include <memory> // for __shared_ptr_access, allocator #include <utility> // for move #include "control/Control.h" // for Control #include "model/Document.h" // for Document #include "model/XojPage.h" // for XojPage #include "undo/UndoAction.h" // for UndoAction #include "util/Util.h" // for npos #include "util/i18n.h" // for _ PageBackgroundChangedUndoAction::PageBackgroundChangedUndoAction(const PageRef& page, const PageType& origType, size_t origPdfPage, BackgroundImage origBackgroundImage, double origW, double origH): UndoAction("PageBackgroundChangedUndoAction") { this->page = page; this->origType = origType; this->origPdfPage = origPdfPage; this->origBackgroundImage = std::move(origBackgroundImage); this->origW = origW; this->origH = origH; this->newType.format = PageTypeFormat::Plain; } PageBackgroundChangedUndoAction::~PageBackgroundChangedUndoAction() = default; auto PageBackgroundChangedUndoAction::undo(Control* control) -> bool { Document* doc = control->getDocument(); doc->lock(); this->newType = this->page->getBackgroundType(); this->newPdfPage = this->page->getPdfPageNr(); this->newBackgroundImage = this->page->getBackgroundImage(); this->newW = this->page->getWidth(); this->newH = this->page->getHeight(); auto pageNr = doc->indexOf(this->page); if (pageNr == npos) { doc->unlock(); return false; } bool pageSizeChanged = this->newW != this->origW || this->newH != this->origH; if (pageSizeChanged) { this->page->setSize(this->origW, this->origH); } this->page->setBackgroundType(this->origType); if (this->origType.isPdfPage()) { this->page->setBackgroundPdfPageNr(this->origPdfPage); } else if (this->origType.isImagePage()) { this->page->setBackgroundImage(this->origBackgroundImage); } doc->unlock(); if (pageSizeChanged) { control->firePageSizeChanged(pageNr); } control->firePageChanged(pageNr); return true; } auto PageBackgroundChangedUndoAction::redo(Control* control) -> bool { Document* doc = control->getDocument(); doc->lock(); auto pageNr = doc->indexOf(this->page); if (pageNr == npos) { doc->unlock(); return false; } bool pageSizeChanged = this->newW != this->origW || this->newH != this->origH; if (pageSizeChanged) { this->page->setSize(this->newW, this->newH); } this->page->setBackgroundType(this->newType); if (this->newType.isPdfPage()) { this->page->setBackgroundPdfPageNr(this->newPdfPage); } else if (this->newType.isImagePage()) { this->page->setBackgroundImage(this->newBackgroundImage); } doc->unlock(); if (pageSizeChanged) { control->firePageSizeChanged(pageNr); } control->firePageChanged(pageNr); return true; } auto PageBackgroundChangedUndoAction::getText() -> std::string { return _("Page background changed"); }
3,254
C++
.cpp
79
33.848101
115
0.643332
xournalpp/xournalpp
10,962
791
1,098
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
12,394
RotateUndoAction.cpp
xournalpp_xournalpp/src/core/undo/RotateUndoAction.cpp
#include "RotateUndoAction.h" #include <memory> // for allocator, __shared_ptr_access, __share... #include "control/Control.h" #include "model/Document.h" #include "model/Element.h" // for Element #include "model/PageRef.h" // for PageRef #include "model/XojPage.h" // for XojPage #include "undo/UndoAction.h" // for UndoAction #include "util/Range.h" // for Range #include "util/i18n.h" // for _ RotateUndoAction::RotateUndoAction(const PageRef& page, std::vector<Element*>* elements, double x0, double y0, double rotation): UndoAction("RotateUndoAction") { this->page = page; this->elements = *elements; this->x0 = x0; this->y0 = y0; this->rotation = rotation; } RotateUndoAction::~RotateUndoAction() { this->page = nullptr; } auto RotateUndoAction::undo(Control* control) -> bool { applyRotation(-this->rotation, control->getDocument()); this->undone = true; return true; } auto RotateUndoAction::redo(Control* control) -> bool { applyRotation(this->rotation, control->getDocument()); this->undone = false; return true; } void RotateUndoAction::applyRotation(double rotation, Document* doc) { if (this->elements.empty()) { return; } doc->lock(); Range r(elements.front()->getX(), elements.front()->getY()); for (Element* e: this->elements) { r.addPoint(e->getX(), e->getY()); r.addPoint(e->getX() + e->getElementWidth(), e->getY() + e->getElementHeight()); e->rotate(this->x0, this->y0, rotation); r.addPoint(e->getX(), e->getY()); r.addPoint(e->getX() + e->getElementWidth(), e->getY() + e->getElementHeight()); } doc->unlock(); this->page->fireRangeChanged(r); } auto RotateUndoAction::getText() -> std::string { return _("Rotation"); }
1,844
C++
.cpp
47
34.446809
110
0.643337
xournalpp/xournalpp
10,962
791
1,098
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
12,395
UndoRedoHandler.cpp
xournalpp_xournalpp/src/core/undo/UndoRedoHandler.cpp
#include "UndoRedoHandler.h" #include <algorithm> // for find_if #include <cinttypes> // for PRIu64 #include <cstdint> // for uint64_t #include <iterator> // for end, begin #include <memory> // for unique_ptr, allocator_traits<>::value_type #include <utility> // for move #include <glib.h> // for g_message #include "control/Control.h" // for Control #include "model/Document.h" // for Document #include "undo/UndoAction.h" // for UndoActionPtr, UndoAction #include "util/Assert.h" // for xoj_assert #include "util/XojMsgBox.h" // for XojMsgBox #include "util/i18n.h" // for _, FS, _F using std::string; template <typename T> T* GetPtr(T* ptr) { return ptr; } template <typename T> T* GetPtr(const std::unique_ptr<T>& ptr) { return ptr.get(); } template <typename PtrType> inline void printAction(PtrType& action, size_t n = 666) { if (action) { g_message("%3zu -- %p / %s", n, GetPtr(action), action->getClassName().c_str()); } else { g_message("%3zu -- (null)", n); } } template <typename PtrType> inline void printUndoList(const std::deque<PtrType>& list) { size_t n = 1; for (const auto& action: list) { printAction(action, n++); } } #ifdef UNDO_TRACE constexpr bool UNDO_TRACE_BOOL = true; #else constexpr bool UNDO_TRACE_BOOL = false; #endif void UndoRedoHandler::printContents() { if constexpr (UNDO_TRACE_BOOL) // NOLINT { g_message("redoList"); // NOLINT printUndoList(this->redoList); // NOLINT g_message("undoList"); // NOLINT printUndoList(this->undoList); // NOLINT g_message("savedUndo"); // NOLINT if (this->savedUndo) // NOLINT { // NOLINT printAction(this->savedUndo); // NOLINT } // NOLINT } } UndoRedoHandler::UndoRedoHandler(Control* control): control(control) {} UndoRedoHandler::~UndoRedoHandler() { clearContents(); } void UndoRedoHandler::clearContents() { #ifdef UNDO_TRACE for (auto const& undoAction: this->undoList) { g_message("clearContents()::Delete UndoAction: %p / %s", undoAction.get(), undoAction->getClassName().c_str()); } #endif // UNDO_TRACE undoList.clear(); clearRedo(); this->savedUndo = nullptr; this->autosavedUndo = nullptr; printContents(); } void UndoRedoHandler::clearRedo() { #ifdef UNDO_TRACE for (auto const& undoAction: this->redoList) { g_message("clearRedo()::Delete UndoAction: %p / %s", undoAction.get(), undoAction->getClassName().c_str()); } #endif redoList.clear(); printContents(); } void UndoRedoHandler::undo() { if (this->undoList.empty()) { return; } xoj_assert(this->undoList.back()); auto& undoAction = *this->undoList.back(); this->redoList.emplace_back(std::move(this->undoList.back())); this->undoList.pop_back(); bool undoResult = undoAction.undo(this->control); if (!undoResult) { string msg = FS(_F("Could not undo \"{1}\"\n" "Something went wrong… Please write a bug report…") % undoAction.getText()); XojMsgBox::showErrorToUser(control->getGtkWindow(), msg); } fireUpdateUndoRedoButtons(undoAction.getPages()); printContents(); } void UndoRedoHandler::redo() { if (this->redoList.empty()) { return; } xoj_assert(this->redoList.back()); UndoAction& redoAction = *this->redoList.back(); this->undoList.emplace_back(std::move(this->redoList.back())); this->redoList.pop_back(); bool redoResult = redoAction.redo(this->control); if (!redoResult) { string msg = FS(_F("Could not redo \"{1}\"\n" "Something went wrong… Please write a bug report…") % redoAction.getText()); XojMsgBox::showErrorToUser(control->getGtkWindow(), msg); } fireUpdateUndoRedoButtons(redoAction.getPages()); printContents(); } auto UndoRedoHandler::canUndo() -> bool { return !this->undoList.empty(); } auto UndoRedoHandler::canRedo() -> bool { return !this->redoList.empty(); } /** * Adds an undo Action to the list, or if nullptr does nothing */ void UndoRedoHandler::addUndoAction(UndoActionPtr action) { if (!action) { return; } this->undoList.emplace_back(std::move(action)); clearRedo(); fireUpdateUndoRedoButtons(this->undoList.back()->getPages()); printContents(); } auto UndoRedoHandler::undoDescription() -> string { if (!this->undoList.empty()) { UndoAction& a = *this->undoList.back(); if (!a.getText().empty()) { string txt = _("Undo: "); txt += a.getText(); return txt; } } return _("Undo"); } auto UndoRedoHandler::redoDescription() -> string { if (!this->redoList.empty()) { UndoAction& a = *this->redoList.back(); if (!a.getText().empty()) { string txt = _("Redo: "); txt += a.getText(); return txt; } } return _("Redo"); } void UndoRedoHandler::fireUpdateUndoRedoButtons(const std::vector<PageRef>& pages) { for (auto&& undoRedoListener: this->listener) { undoRedoListener->undoRedoChanged(); } for (PageRef page: pages) { if (!page) { continue; } for (auto&& undoRedoListener: this->listener) { undoRedoListener->undoRedoPageChanged(page); } } } void UndoRedoHandler::addUndoRedoListener(UndoRedoListener* listener) { this->listener.emplace_back(listener); } auto UndoRedoHandler::isChanged() -> bool { if (this->undoList.empty()) { return this->savedUndo; } return this->savedUndo != this->undoList.back().get(); } auto UndoRedoHandler::isChangedAutosave() -> bool { if (this->undoList.empty()) { return this->autosavedUndo; } return this->autosavedUndo != this->undoList.back().get(); } void UndoRedoHandler::documentAutosaved() { this->autosavedUndo = this->undoList.empty() ? nullptr : this->undoList.back().get(); } void UndoRedoHandler::documentSaved() { this->savedUndo = this->undoList.empty() ? nullptr : this->undoList.back().get(); }
6,339
C++
.cpp
180
29.922222
119
0.627335
xournalpp/xournalpp
10,962
791
1,098
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
12,396
EmergencySaveRestore.cpp
xournalpp_xournalpp/src/core/undo/EmergencySaveRestore.cpp
#include "EmergencySaveRestore.h" #include "undo/UndoAction.h" // for UndoAction #include "util/i18n.h" // for _ class Control; EmergencySaveRestore::EmergencySaveRestore(): UndoAction("EmergencySaveRestore") {} EmergencySaveRestore::~EmergencySaveRestore() = default; auto EmergencySaveRestore::redo(Control* control) -> bool { // Does nothing, only used to mark the document as changed return true; } auto EmergencySaveRestore::undo(Control* control) -> bool { // Does nothing, only used to mark the document as changed return true; } auto EmergencySaveRestore::getText() -> std::string { return _("Emergency saved document"); }
662
C++
.cpp
15
41.6
93
0.751563
xournalpp/xournalpp
10,962
791
1,098
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
12,397
MergeLayerDownUndoAction.cpp
xournalpp_xournalpp/src/core/undo/MergeLayerDownUndoAction.cpp
#include "MergeLayerDownUndoAction.h" #include <memory> // for __shared_ptr_access #include <utility> #include <vector> // for vector #include "control/Control.h" // for Control #include "control/layer/LayerController.h" // for LayerController #include "gui/MainWindow.h" // for MainWindow #include "gui/XournalView.h" // for XournalView #include "model/Document.h" #include "model/Layer.h" // for Layer, Layer::Index #include "model/PageRef.h" // for PageRef #include "model/XojPage.h" // for XojPage #include "undo/UndoAction.h" // for UndoAction #include "util/i18n.h" // for _ class Element; namespace xoj { auto refElementContainer(const std::vector<ElementPtr>& elements) -> std::vector<Element*>; } // namespace xoj MergeLayerDownUndoAction::MergeLayerDownUndoAction(LayerController* layerController, const PageRef& page, Layer* upperLayer, Layer::Index upperLayerPos, Layer* lowerLayer, size_t selectedPage): UndoAction("MergeLayerDownUndoAction"), layerController(layerController), upperLayer(upperLayer), upperLayerPos(upperLayerPos), upperLayerID(upperLayerPos + 1), lowerLayer(lowerLayer), lowerLayerID(upperLayerPos), selectedPage(selectedPage) { this->page = page; } auto MergeLayerDownUndoAction::getText() -> std::string { return _("Merge layer down"); } auto MergeLayerDownUndoAction::undo(Control* control) -> bool { Document* doc = control->getDocument(); doc->lock(); // remove all elements present in the upper layer from the lower layer again for (Element* elem: upperLayerElements) { this->upperLayer->addElement(this->lowerLayer->removeElement(elem).e); } // add the upper layer back at its old pos layerController->insertLayer(this->page, this->upperLayer, upperLayerPos); // set the selected layer back to the ID of the upper layer this->page->setSelectedLayerId(this->upperLayerID); doc->unlock(); this->undone = true; this->triggerUIUpdate(control); return true; } auto MergeLayerDownUndoAction::redo(Control* control) -> bool { Document* doc = control->getDocument(); doc->lock(); // remove the upper layer layerController->removeLayer(this->page, this->upperLayer); this->upperLayerElements = xoj::refElementContainer(this->upperLayer->getElements()); auto elements = this->upperLayer->clearNoFree(); // add all elements back to the lower layer for (auto&& elem: elements) { this->lowerLayer->addElement(std::move(elem)); } // set the selected layer back to the ID of the lower layer this->page->setSelectedLayerId(this->lowerLayerID); doc->unlock(); this->undone = false; this->triggerUIUpdate(control); return true; } void MergeLayerDownUndoAction::triggerUIUpdate(Control* control) { /* * NOTE: (call order relevant to avoid deadlock) * When this implementation is called by the `UndoRedoHandler` the * document is locked. Calling `layerChanged` adds a render job which * can only be processed when the document is unlocked again, but might * have already claimed `Scheduler::jobRunningMutex`. * `fireRebuildLayerMenu` will wait for `jobRunningMutex` to be free, * so calling `fireRebuildLayerMenu` AFTER `layerChanged` will likely * result in a DEADLOCK. */ /* * Rebuild the layer menu, so that the correct new layer selection is * properly displayed in the sidebar. Without this, the visually displayed * selection defaults to the top layer while the actual selection is the * newly merged layer; there would be a mismatch without rebuilding the * menu this way. */ layerController->fireRebuildLayerMenu(); /* * Under some circumstance (e.g. the layer below is not set to visible) * merging might change the appearance of the page, so `layerChanged` is * employed to rerender the page. */ MainWindow* win = control->getWindow(); if (win) { win->getXournal()->layerChanged(this->selectedPage); } }
4,351
C++
.cpp
95
40.042105
116
0.673754
xournalpp/xournalpp
10,962
791
1,098
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
12,398
TextBoxUndoAction.cpp
xournalpp_xournalpp/src/core/undo/TextBoxUndoAction.cpp
#include "TextBoxUndoAction.h" #include <algorithm> // for max, min #include <memory> // for allocator, __shared_ptr_access, __share... #include <utility> #include "control/Control.h" #include "model/Document.h" #include "model/Element.h" // for Element #include "model/Layer.h" // for Layer #include "model/PageRef.h" // for PageRef #include "model/XojPage.h" // for XojPage #include "undo/UndoAction.h" // for UndoAction #include "util/Rectangle.h" // for Rectangle #include "util/i18n.h" // for _ using xoj::util::Rectangle; TextBoxUndoAction::TextBoxUndoAction(const PageRef& page, Layer* layer, Element* element, ElementPtr oldelement): UndoAction("TextBoxUndoAction"), layer(layer), element(element), oldelement(std::move(oldelement)) { this->page = page; } TextBoxUndoAction::~TextBoxUndoAction() = default; auto TextBoxUndoAction::getText() -> std::string { return _("Edit text"); } auto TextBoxUndoAction::undo(Control* control) -> bool { Document* doc = control->getDocument(); doc->lock(); auto rect = element->boundingRect(); rect.unite(oldelement->boundingRect()); // swap them to be memory safe auto elementPtr = this->layer->removeElement(std::exchange(this->element, this->oldelement.get())).e; this->layer->addElement(std::exchange(this->oldelement, std::move(elementPtr))); doc->unlock(); this->page->fireRectChanged(rect); this->undone = true; return true; } auto TextBoxUndoAction::redo(Control* control) -> bool { undo(control); this->undone = false; return true; }
1,594
C++
.cpp
38
38.894737
113
0.703105
xournalpp/xournalpp
10,962
791
1,098
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
12,399
UndoAction.cpp
xournalpp_xournalpp/src/core/undo/UndoAction.cpp
#include "UndoAction.h" #include <utility> // for move UndoAction::UndoAction(std::string className): className(std::move(className)) {} auto UndoAction::getPages() -> std::vector<PageRef> { std::vector<PageRef> pages; pages.push_back(this->page); return pages; } auto UndoAction::getClassName() const -> std::string const& { return this->className; }
369
C++
.cpp
9
38.222222
87
0.72191
xournalpp/xournalpp
10,962
791
1,098
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
12,400
MoveLayerUndoAction.cpp
xournalpp_xournalpp/src/core/undo/MoveLayerUndoAction.cpp
#include "MoveLayerUndoAction.h" #include "control/Control.h" #include "control/layer/LayerController.h" // for LayerController #include "model/Document.h" #include "model/Layer.h" // for Layer, Layer::Index #include "model/PageRef.h" // for PageRef #include "undo/UndoAction.h" // for UndoAction #include "util/i18n.h" // for _ class Control; MoveLayerUndoAction::MoveLayerUndoAction(LayerController* layerController, const PageRef& page, Layer* layer, Layer::Index oldLayerPos, Layer::Index newLayerPos): UndoAction("MoveLayerUndoAction"), oldLayerPos(oldLayerPos), newLayerPos(newLayerPos), layerController(layerController) { this->page = page; this->layer = layer; } MoveLayerUndoAction::~MoveLayerUndoAction() { this->layerController = nullptr; this->layer = nullptr; } auto MoveLayerUndoAction::getText() -> std::string { return _("Move layer"); } auto MoveLayerUndoAction::undo(Control* control) -> bool { Document* doc = control->getDocument(); doc->lock(); layerController->removeLayer(this->page, this->layer); layerController->insertLayer(this->page, this->layer, oldLayerPos); doc->unlock(); this->undone = true; return true; } auto MoveLayerUndoAction::redo(Control* control) -> bool { Document* doc = control->getDocument(); doc->lock(); layerController->removeLayer(this->page, this->layer); layerController->insertLayer(this->page, this->layer, newLayerPos); doc->unlock(); this->undone = false; return true; }
1,656
C++
.cpp
41
35.585366
109
0.671446
xournalpp/xournalpp
10,962
791
1,098
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
12,401
ArrangeUndoAction.cpp
xournalpp_xournalpp/src/core/undo/ArrangeUndoAction.cpp
#include "ArrangeUndoAction.h" #include <memory> // for allocator, __shared_ptr_access, __share... #include <unordered_map> #include "control/Control.h" #include "model/Document.h" #include "model/Element.h" #include "model/Layer.h" // for Layer #include "model/XojPage.h" // for XojPage #include "undo/UndoAction.h" // for UndoAction ArrangeUndoAction::ArrangeUndoAction(const PageRef& page, Layer* layer, std::string desc, InsertionOrderRef oldOrder, InsertionOrderRef newOrder): UndoAction("ArrangeUndoAction"), layer(layer), description(std::move(desc)), oldOrder(std::move(oldOrder)), newOrder(std::move(newOrder)) { this->page = page; } ArrangeUndoAction::~ArrangeUndoAction() { this->page = nullptr; } bool ArrangeUndoAction::undo(Control* control) { this->undone = true; applyRearrange(control); return true; } bool ArrangeUndoAction::redo(Control* control) { this->undone = false; applyRearrange(control); return true; } void ArrangeUndoAction::applyRearrange(Control* control) { // Convert source order into target order const auto& srcOrder = this->undone ? this->newOrder : this->oldOrder; const auto& tgtOrder = this->undone ? this->oldOrder : this->newOrder; std::unordered_map<Element*, ElementPtr> removedElements; removedElements.reserve(srcOrder.size()); Document* doc = control->getDocument(); doc->lock(); for (const auto& [e, _]: srcOrder) { removedElements.emplace(e, layer->removeElement(e).e); } for (const auto& [e, i]: tgtOrder) { layer->insertElement(std::move(removedElements[e]), i); } doc->unlock(); this->page->firePageChanged(); } std::string ArrangeUndoAction::getText() { return this->description; }
1,829
C++
.cpp
47
33.978723
117
0.687006
xournalpp/xournalpp
10,962
791
1,098
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
12,402
AddUndoAction.cpp
xournalpp_xournalpp/src/core/undo/AddUndoAction.cpp
#include "AddUndoAction.h" #include <memory> // for __shared_ptr_access, __shared_pt... #include <glib.h> // for g_warning #include "control/Control.h" #include "model/Document.h" #include "model/Element.h" // for Element, ELEMENT_IMAGE, ELEMENT_... #include "model/Layer.h" // for Layer #include "model/XojPage.h" // for XojPage #include "undo/UndoAction.h" // for UndoAction #include "util/i18n.h" // for _ AddUndoAction::AddUndoAction(const PageRef& page, bool eraser): UndoAction("AddUndoAction") { this->page = page; this->eraser = eraser; } void AddUndoAction::addElement(Layer* layer, Element* e, Element::Index pos) { elements.emplace(layer, e, pos); } auto AddUndoAction::redo(Control* control) -> bool { if (elements.empty()) { g_warning("Could not undo AddUndoAction, there is nothing to undo"); this->undone = true; return false; } Document* doc = control->getDocument(); doc->lock(); for (const auto& elem: elements) { elem.layer->insertElement(std::move(elem.elementOwn), elem.pos); } doc->unlock(); for (const auto& elem: elements) { this->page->fireElementChanged(elem.element); } this->undone = true; return true; } auto AddUndoAction::undo(Control* control) -> bool { if (elements.empty()) { g_warning("Could not redo AddUndoAction, there is nothing to redo"); this->undone = false; return false; } Document* doc = control->getDocument(); doc->lock(); for (const auto& elem: elements) { elem.elementOwn = elem.layer->removeElement(elem.element).e; } doc->unlock(); for (const auto& elem: elements) { this->page->fireElementChanged(elem.element); } this->undone = false; return true; } auto AddUndoAction::getText() -> std::string { std::string text; if (eraser) { text = _("Erase stroke"); } else { text = _("Paste"); if (!elements.empty()) { ElementType type = elements.begin()->element->getType(); for (auto elemIter = ++elements.begin(); elemIter != elements.end(); ++elemIter) { if (type != elemIter->element->getType()) { text += " "; text += _("elements"); return text; } } text += " "; switch (type) { case ELEMENT_STROKE: text += _("stroke"); break; case ELEMENT_IMAGE: text += _("image"); break; case ELEMENT_TEXIMAGE: text += _("latex"); break; case ELEMENT_TEXT: text += _("text"); break; } } } return text; }
2,929
C++
.cpp
85
26
113
0.544586
xournalpp/xournalpp
10,962
791
1,098
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
12,403
MoveUndoAction.cpp
xournalpp_xournalpp/src/core/undo/MoveUndoAction.cpp
#include "MoveUndoAction.h" #include <memory> // for allocator, operator!=, __shared_ptr_access #include <utility> #include "control/Control.h" #include "model/Document.h" #include "model/Element.h" // for Element #include "model/Layer.h" // for Layer #include "model/PageRef.h" // for PageRef #include "model/XojPage.h" // for XojPage #include "undo/UndoAction.h" // for UndoAction #include "util/i18n.h" // for _ MoveUndoAction::MoveUndoAction(Layer* sourceLayer, const PageRef& sourcePage, std::vector<Element*> selected, double mx, double my, Layer* targetLayer, PageRef targetPage): UndoAction("MoveUndoAction"), elements(std::move(selected)), sourceLayer(sourceLayer), text(_("Move")), dx(mx), dy(my) { this->page = sourcePage; if (this->page != targetPage) { this->targetPage = std::move(targetPage); this->targetLayer = targetLayer; } } MoveUndoAction::~MoveUndoAction() = default; void MoveUndoAction::move() { if (this->undone) { for (Element* e: this->elements) { e->move(dx, dy); } } else { for (Element* e: this->elements) { e->move(-dx, -dy); } } } auto MoveUndoAction::undo(Control* control) -> bool { Document* doc = control->getDocument(); doc->lock(); if (this->sourceLayer != this->targetLayer && this->targetLayer != nullptr) { switchLayer(&this->elements, this->targetLayer, this->sourceLayer); } move(); doc->unlock(); repaint(); this->undone = true; return true; } auto MoveUndoAction::redo(Control* control) -> bool { Document* doc = control->getDocument(); doc->lock(); if (this->sourceLayer != this->targetLayer && this->targetLayer != nullptr) { switchLayer(&this->elements, this->sourceLayer, this->targetLayer); } move(); doc->unlock(); repaint(); this->undone = false; return true; } void MoveUndoAction::switchLayer(std::vector<Element*>* entries, Layer* oldLayer, Layer* newLayer) { for (Element* e: this->elements) { newLayer->addElement(oldLayer->removeElement(e).e); } } void MoveUndoAction::repaint() { if (this->elements.empty()) { return; } this->page->firePageChanged(); if (this->targetPage) { this->targetPage->firePageChanged(); } } auto MoveUndoAction::getPages() -> std::vector<PageRef> { std::vector<PageRef> pages; pages.push_back(this->page); pages.push_back(this->targetPage); return pages; } auto MoveUndoAction::getText() -> std::string { return text; }
2,636
C++
.cpp
78
28.833333
120
0.643307
xournalpp/xournalpp
10,962
791
1,098
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
12,404
ScaleUndoAction.cpp
xournalpp_xournalpp/src/core/undo/ScaleUndoAction.cpp
#include "ScaleUndoAction.h" #include <cmath> // for isfinite #include <memory> // for allocator, __shared_ptr_access, __share... #include "control/Control.h" #include "model/Document.h" #include "model/Element.h" // for Element #include "model/PageRef.h" // for PageRef #include "model/XojPage.h" // for XojPage #include "undo/UndoAction.h" // for UndoAction #include "util/Range.h" // for Range #include "util/i18n.h" // for _ ScaleUndoAction::ScaleUndoAction(const PageRef& page, std::vector<Element*>* elements, double x0, double y0, double fx, double fy, double rotation, bool restoreLineWidth): UndoAction("ScaleUndoAction") { this->page = page; this->elements = *elements; this->x0 = x0; this->y0 = y0; this->fx = std::isfinite(fx) ? fx : 1.0; this->fy = std::isfinite(fy) ? fy : 1.0; this->rotation = rotation; this->restoreLineWidth = restoreLineWidth; } ScaleUndoAction::~ScaleUndoAction() { this->page = nullptr; } auto ScaleUndoAction::undo(Control* control) -> bool { applyScale(1 / this->fx, 1 / this->fy, restoreLineWidth, control->getDocument()); this->undone = true; return true; } auto ScaleUndoAction::redo(Control* control) -> bool { applyScale(this->fx, this->fy, restoreLineWidth, control->getDocument()); this->undone = false; return true; } void ScaleUndoAction::applyScale(double fx, double fy, bool restoreLineWidth, Document* doc) { if (this->elements.empty()) { return; } doc->lock(); Range r(elements.front()->getX(), elements.front()->getY()); for (Element* e: this->elements) { r.addPoint(e->getX(), e->getY()); r.addPoint(e->getX() + e->getElementWidth(), e->getY() + e->getElementHeight()); e->scale(this->x0, this->y0, fx, fy, this->rotation, restoreLineWidth); r.addPoint(e->getX(), e->getY()); r.addPoint(e->getX() + e->getElementWidth(), e->getY() + e->getElementHeight()); } doc->unlock(); this->page->fireRangeChanged(r); } auto ScaleUndoAction::getText() -> std::string { return _("Scale"); }
2,147
C++
.cpp
51
37.411765
119
0.646043
xournalpp/xournalpp
10,962
791
1,098
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
12,405
MissingPdfUndoAction.cpp
xournalpp_xournalpp/src/core/undo/MissingPdfUndoAction.cpp
#include "MissingPdfUndoAction.h" #include "control/Control.h" // for Control #include "control/PageBackgroundChangeController.h" // for PageBackGroundChangeController #include "gui/MainWindow.h" // for MainWindow #include "gui/XournalView.h" // for XournalView #include "model/Document.h" // for Document #include "model/PageType.h" // for PageTypeFormat #include "model/XojPage.h" // for XojPage #include "undo/UndoAction.h" // for UndoAction #include "util/i18n.h" // for _ MissingPdfUndoAction::MissingPdfUndoAction(const fs::path& oldFilepath, bool oldAttachPdf): UndoAction("MissingPdfUndoAction"), filepath(oldFilepath), attachPdf(oldAttachPdf) {} MissingPdfUndoAction::~MissingPdfUndoAction() = default; auto MissingPdfUndoAction::undo(Control* control) -> bool { Document* doc = control->getDocument(); fs::path redoFilepath = doc->getPdfFilepath(); bool redoAttachPdf = doc->isAttachPdf(); doc->lock(); doc->resetPdf(); doc->setPdfAttributes(this->filepath, this->attachPdf); doc->unlock(); control->getWindow()->getXournal()->recreatePdfCache(); for (size_t p = 0; p < doc->getPageCount(); p++) { if (doc->getPage(p)->getBackgroundType().format == PageTypeFormat::Pdf) { control->firePageChanged(p); } } this->filepath = std::move(redoFilepath); this->attachPdf = redoAttachPdf; return true; } auto MissingPdfUndoAction::redo(Control* control) -> bool { Document* doc = control->getDocument(); doc->lock(); fs::path undoFilepath = doc->getPdfFilepath(); bool undoAttachPdf = doc->isAttachPdf(); doc->unlock(); doc->readPdf(this->filepath, false, this->attachPdf); control->getWindow()->getXournal()->recreatePdfCache(); for (size_t p = 0; p < doc->getPageCount(); p++) { if (doc->getPage(p)->getBackgroundType().format == PageTypeFormat::Pdf) { control->firePageChanged(p); } } this->filepath = std::move(undoFilepath); this->attachPdf = undoAttachPdf; return true; } auto MissingPdfUndoAction::getText() -> std::string { return _("Replace missing PDF"); }
2,353
C++
.cpp
49
43.326531
93
0.63533
xournalpp/xournalpp
10,962
791
1,098
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
12,406
RecognizerUndoAction.cpp
xournalpp_xournalpp/src/core/undo/RecognizerUndoAction.cpp
#include "RecognizerUndoAction.h" #include <memory> // for __shared_ptr_access, __shared_ptr_acces... #include <utility> #include <glib.h> // for g_warning #include "control/Control.h" #include "model/Document.h" #include "model/Element.h" #include "model/Layer.h" // for Layer #include "model/Stroke.h" // for Stroke #include "model/XojPage.h" // for XojPage #include "undo/UndoAction.h" // for UndoAction #include "util/i18n.h" // for _ RecognizerUndoAction::RecognizerUndoAction(const PageRef& page, Layer* layer, ElementPtr original, Element* recognized): UndoAction("RecognizerUndoAction"), layer(layer), original(original.get()), originalOwned(std::move(original)), recognized(recognized) { this->page = page; } RecognizerUndoAction::~RecognizerUndoAction() = default; auto RecognizerUndoAction::undo(Control* control) -> bool { Document* doc = control->getDocument(); doc->lock(); auto [owned, pos] = this->layer->removeElement(this->recognized); this->recognizedOwned = std::move(owned); this->layer->insertElement(std::move(this->originalOwned), pos); doc->unlock(); this->page->fireElementChanged(this->recognized); this->page->fireElementChanged(original); this->undone = true; return true; } auto RecognizerUndoAction::redo(Control* control) -> bool { Element::Index pos = 0; Document* doc = control->getDocument(); doc->lock(); auto [owned, posi] = this->layer->removeElement(original); this->originalOwned = std::move(owned); this->layer->insertElement(std::move(this->recognizedOwned), pos); doc->unlock(); this->page->fireElementChanged(original); this->page->fireElementChanged(this->recognized); this->undone = false; return true; } auto RecognizerUndoAction::getText() -> std::string { return _("Shape Recognizer"); }
1,901
C++
.cpp
47
36.425532
120
0.69837
xournalpp/xournalpp
10,962
791
1,098
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
12,407
GroupUndoAction.cpp
xournalpp_xournalpp/src/core/undo/GroupUndoAction.cpp
#include "GroupUndoAction.h" #include <algorithm> // for none_of #include <utility> // for move #include "undo/UndoAction.h" // for UndoAction class Control; GroupUndoAction::GroupUndoAction(): UndoAction("GroupUndoAction") {} void GroupUndoAction::addAction(std::unique_ptr<UndoAction> action) { actions.push_back(std::move(action)); } auto GroupUndoAction::getPages() -> std::vector<PageRef> { std::vector<PageRef> pages; for (std::unique_ptr<UndoAction>& a: actions) { for (PageRef addPage: a->getPages()) { if (!addPage) { continue; } if (std::none_of(pages.begin(), pages.end(), [&](const PageRef& p) { return addPage == p; })) { pages.push_back(addPage); } } } return pages; } auto GroupUndoAction::redo(Control* control) -> bool { bool result = true; for (auto& action: actions) { result = result && action->redo(control); } return result; } auto GroupUndoAction::undo(Control* control) -> bool { bool result = true; for (auto& action: actions) { result = result && action->undo(control); } return result; } auto GroupUndoAction::getText() -> std::string { if (actions.empty()) { return "!! NOTHING !!"; } return actions[0]->getText(); }
1,321
C++
.cpp
37
30.081081
109
0.628054
xournalpp/xournalpp
10,962
791
1,098
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
12,408
SizeUndoAction.cpp
xournalpp_xournalpp/src/core/undo/SizeUndoAction.cpp
#include "SizeUndoAction.h" #include <memory> // for allocator, __shared_ptr_access, __share... #include <utility> // for move #include "control/Control.h" #include "model/Document.h" #include "model/Point.h" // for Point #include "model/Stroke.h" // for Stroke #include "model/XojPage.h" // for XojPage #include "undo/UndoAction.h" // for UndoAction #include "util/Range.h" // for Range #include "util/i18n.h" // for _ using std::vector; class SizeUndoActionEntry { public: SizeUndoActionEntry(Stroke* s, double originalWidth, double newWidth, vector<double> originalPressure, vector<double> newPressure, size_t pressureCount) { this->s = s; this->originalWidth = originalWidth; this->newWidth = newWidth; this->originalPressure = std::move(originalPressure); this->newPressure = std::move(newPressure); this->pressureCount = pressureCount; } ~SizeUndoActionEntry() = default; Stroke* s; double originalWidth; double newWidth; vector<double> originalPressure; vector<double> newPressure; size_t pressureCount; }; SizeUndoAction::SizeUndoAction(const PageRef& page, Layer* layer): UndoAction("SizeUndoAction") { this->page = page; this->layer = layer; } SizeUndoAction::~SizeUndoAction() { for (SizeUndoActionEntry* e: this->data) { delete e; } this->data.clear(); } auto SizeUndoAction::getPressure(Stroke* s) -> vector<double> { size_t count = s->getPointCount(); vector<double> data; data.reserve(count); for (size_t i = 0; i < count; i++) { data.push_back(s->getPoint(i).z); } return data; } void SizeUndoAction::addStroke(Stroke* s, double originalWidth, double newWidth, vector<double> originalPressure, vector<double> newPressure, size_t pressureCount) { this->data.push_back(new SizeUndoActionEntry(s, originalWidth, newWidth, std::move(originalPressure), std::move(newPressure), pressureCount)); } auto SizeUndoAction::undo(Control* control) -> bool { if (this->data.empty()) { return true; } Document* doc = control->getDocument(); doc->lock(); SizeUndoActionEntry* e = this->data.front(); Range range(e->s->getX(), e->s->getY()); for (SizeUndoActionEntry* e: this->data) { e->s->setWidth(e->originalWidth); e->s->setPressure(e->originalPressure); range.addPoint(e->s->getX(), e->s->getY()); range.addPoint(e->s->getX() + e->s->getElementWidth(), e->s->getY() + e->s->getElementHeight()); } doc->unlock(); this->page->fireRangeChanged(range); return true; } auto SizeUndoAction::redo(Control* control) -> bool { if (this->data.empty()) { return true; } Document* doc = control->getDocument(); doc->lock(); SizeUndoActionEntry* e = this->data.front(); Range range(e->s->getX(), e->s->getY()); for (SizeUndoActionEntry* e: this->data) { e->s->setWidth(e->newWidth); e->s->setPressure(e->newPressure); range.addPoint(e->s->getX(), e->s->getY()); range.addPoint(e->s->getX() + e->s->getElementWidth(), e->s->getY() + e->s->getElementHeight()); } doc->unlock(); this->page->fireRangeChanged(range); return true; } auto SizeUndoAction::getText() -> std::string { return _("Change stroke width"); }
3,467
C++
.cpp
90
32.677778
113
0.64049
xournalpp/xournalpp
10,962
791
1,098
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
12,409
DeleteUndoAction.cpp
xournalpp_xournalpp/src/core/undo/DeleteUndoAction.cpp
#include "DeleteUndoAction.h" #include <memory> // for __shared_ptr_access, __shared_pt... #include <glib.h> // for g_warning #include "control/Control.h" #include "model/Document.h" #include "model/Element.h" // for Element, ELEMENT_IMAGE, ELEMENT_... #include "model/Layer.h" // for Layer #include "model/XojPage.h" // for XojPage #include "undo/UndoAction.h" // for UndoAction #include "util/i18n.h" // for _ DeleteUndoAction::DeleteUndoAction(const PageRef& page, bool eraser): UndoAction("DeleteUndoAction"), eraser(eraser) { this->page = page; } void DeleteUndoAction::addElement(Layer* layer, ElementPtr e, Element::Index pos) { elements.emplace(layer, std::move(e), pos); } auto DeleteUndoAction::undo(Control* control) -> bool { if (elements.empty()) { g_warning("Could not undo DeleteUndoAction, there is nothing to undo"); this->undone = true; return false; } Document* doc = control->getDocument(); doc->lock(); for (auto& elem: elements) { elem.layer->insertElement(std::move(elem.elementOwn), elem.pos); } doc->unlock(); for (const auto& elem: elements) { this->page->fireElementChanged(elem.element); } this->undone = true; return true; } auto DeleteUndoAction::redo(Control* control) -> bool { if (elements.empty()) { g_warning("Could not redo DeleteUndoAction, there is nothing to redo"); this->undone = false; return false; } Document* doc = control->getDocument(); doc->lock(); for (auto& elem: elements) { elem.elementOwn = elem.layer->removeElement(elem.element).e; } doc->unlock(); for (auto& elem: elements) { this->page->fireElementChanged(elem.element); } this->undone = false; return true; } auto DeleteUndoAction::getText() -> std::string { if (eraser) { return _("Erase stroke"); } std::string text = _("Delete"); if (!elements.empty()) { ElementType type = elements.begin()->element->getType(); for (auto elemIter = ++elements.begin(); elemIter != elements.end(); ++elemIter) { if (type != elemIter->element->getType()) { text += " "; text += _("elements"); return text; } } text += " "; switch (type) { case ELEMENT_STROKE: text += _("stroke"); break; case ELEMENT_IMAGE: text += _("image"); break; case ELEMENT_TEXIMAGE: text += _("latex"); break; case ELEMENT_TEXT: text += _("text"); break; } } return text; }
2,824
C++
.cpp
84
26.369048
118
0.571901
xournalpp/xournalpp
10,962
791
1,098
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
12,410
EraseUndoAction.cpp
xournalpp_xournalpp/src/core/undo/EraseUndoAction.cpp
#include "EraseUndoAction.h" #include <memory> // for __shared_ptr_access, __shar... #include <vector> // for vector #include "control/Control.h" #include "model/Document.h" #include "model/Layer.h" // for Layer #include "model/Stroke.h" // for Stroke #include "model/XojPage.h" // for XojPage #include "model/eraser/ErasableStroke.h" // for ErasableStroke #include "undo/UndoAction.h" // for UndoAction #include "util/i18n.h" // for _ EraseUndoAction::EraseUndoAction(const PageRef& page): UndoAction("EraseUndoAction") { this->page = page; } void EraseUndoAction::addOriginal(Layer* layer, Stroke* element, Element::Index pos) { original.emplace(layer, element, pos); } void EraseUndoAction::addEdited(Layer* layer, Stroke* element, Element::Index pos) { edited.emplace(layer, element, pos); } void EraseUndoAction::removeEdited(Stroke* element) { for (auto entryIter = edited.begin(); entryIter != edited.end(); ++entryIter) { if (entryIter->element == element) { edited.erase(entryIter); return; } } } void EraseUndoAction::finalize() { for (auto const& entry: original) { if (entry.element->getPointCount() == 0) { // TODO (Marmare314): is this really expected behaviour? continue; } else { // Remove the original and add the copy auto [own, pos] = entry.layer->removeElement(entry.element); entry.elementOwn = std::move(own); ErasableStroke* e = entry.element->getErasable(); std::vector<std::unique_ptr<Stroke>> strokeList = e->getStrokes(); for (auto& stroke: strokeList) { // TODO (Marmare314): should use unique_ptr in layer auto copy = std::move(stroke); this->addEdited(entry.layer, copy.get(), pos); entry.layer->insertElement(std::move(copy), pos); pos++; } delete e; e = nullptr; entry.element->setErasable(nullptr); } } this->page->firePageChanged(); } auto EraseUndoAction::getText() -> std::string { return _("Erase stroke"); } auto EraseUndoAction::undo(Control* control) -> bool { Document* doc = control->getDocument(); doc->lock(); for (auto const& entry: edited) { entry.elementOwn = entry.layer->removeElement(entry.element).e; } for (auto const& entry: original) { entry.layer->insertElement(std::move(entry.elementOwn), entry.pos); } doc->unlock(); for (auto const& entry: edited) { this->page->fireElementChanged(entry.element); } for (auto const& entry: original) { this->page->fireElementChanged(entry.element); } this->undone = true; return true; } auto EraseUndoAction::redo(Control* control) -> bool { Document* doc = control->getDocument(); doc->lock(); for (auto const& entry: original) { entry.elementOwn = entry.layer->removeElement(entry.element).e; } for (auto const& entry: edited) { entry.layer->insertElement(std::move(entry.elementOwn), entry.pos); } doc->unlock(); for (auto const& entry: original) { this->page->fireElementChanged(entry.element); } for (auto const& entry: edited) { this->page->fireElementChanged(entry.element); } this->undone = false; return true; }
3,496
C++
.cpp
90
32.288889
107
0.620944
xournalpp/xournalpp
10,962
791
1,098
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
12,411
FontUndoAction.cpp
xournalpp_xournalpp/src/core/undo/FontUndoAction.cpp
#include "FontUndoAction.h" #include <algorithm> // for max, min #include <memory> // for __shared_ptr_access, __shared_ptr_acces... #include "control/Control.h" #include "model/Document.h" #include "model/Font.h" // for XojFont #include "model/Text.h" // for Text #include "model/XojPage.h" // for XojPage #include "undo/UndoAction.h" // for UndoAction #include "util/Rectangle.h" // for Rectangle #include "util/i18n.h" // for _ using xoj::util::Rectangle; class FontUndoActionEntry { public: FontUndoActionEntry(Text* e, const XojFont& oldFont, const XojFont& newFont) { this->e = e; this->oldFont = oldFont; this->newFont = newFont; } Text* e; XojFont oldFont; XojFont newFont; }; FontUndoAction::FontUndoAction(const PageRef& page, Layer* layer): UndoAction("FontUndoAction") { this->page = page; this->layer = layer; } FontUndoAction::~FontUndoAction() { for (FontUndoActionEntry* e: this->data) { delete e; } this->data.clear(); } void FontUndoAction::addStroke(Text* e, const XojFont& oldFont, const XojFont& newFont) { this->data.push_back(new FontUndoActionEntry(e, oldFont, newFont)); } auto FontUndoAction::undo(Control* control) -> bool { if (this->data.empty()) { return true; } Document* doc = control->getDocument(); doc->lock(); FontUndoActionEntry* e = this->data.front(); double x1 = e->e->getX(); double x2 = e->e->getX() + e->e->getElementWidth(); double y1 = e->e->getY(); double y2 = e->e->getY() + e->e->getElementHeight(); for (FontUndoActionEntry* e: this->data) { // size with old font x1 = std::min(x1, e->e->getX()); x2 = std::max(x2, e->e->getX() + e->e->getElementWidth()); y1 = std::min(y1, e->e->getY()); y2 = std::max(y2, e->e->getY() + e->e->getElementHeight()); e->e->setFont(e->oldFont); // size with new font x1 = std::min(x1, e->e->getX()); x2 = std::max(x2, e->e->getX() + e->e->getElementWidth()); y1 = std::min(y1, e->e->getY()); y2 = std::max(y2, e->e->getY() + e->e->getElementHeight()); } doc->unlock(); Rectangle<double> rect(x1, y1, x2 - x1, y2 - y1); this->page->fireRectChanged(rect); return true; } auto FontUndoAction::redo(Control* control) -> bool { if (this->data.empty()) { return true; } Document* doc = control->getDocument(); doc->lock(); FontUndoActionEntry* e = this->data.front(); double x1 = e->e->getX(); double x2 = e->e->getX() + e->e->getElementWidth(); double y1 = e->e->getY(); double y2 = e->e->getY() + e->e->getElementHeight(); for (FontUndoActionEntry* e: this->data) { // size with old font x1 = std::min(x1, e->e->getX()); x2 = std::max(x2, e->e->getX() + e->e->getElementWidth()); y1 = std::min(y1, e->e->getY()); y2 = std::max(y2, e->e->getY() + e->e->getElementHeight()); e->e->setFont(e->newFont); // size with new font x1 = std::min(x1, e->e->getX()); x2 = std::max(x2, e->e->getX() + e->e->getElementWidth()); y1 = std::min(y1, e->e->getY()); y2 = std::max(y2, e->e->getY() + e->e->getElementHeight()); } doc->unlock(); Rectangle<double> rect(x1, y1, x2 - x1, y2 - y1); this->page->fireRectChanged(rect); return true; } auto FontUndoAction::getText() -> std::string { return _("Change font"); }
3,506
C++
.cpp
93
32.387097
97
0.591204
xournalpp/xournalpp
10,962
791
1,098
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
12,412
InsertDeletePageUndoAction.cpp
xournalpp_xournalpp/src/core/undo/InsertDeletePageUndoAction.cpp
#include "InsertDeletePageUndoAction.h" #include "control/Control.h" // for Control #include "control/ScrollHandler.h" // for ScrollHandler #include "gui/XournalppCursor.h" // for XournalppCursor #include "model/Document.h" // for Document #include "model/PageRef.h" // for PageRef #include "undo/UndoAction.h" // for UndoAction #include "util/Util.h" // for npos #include "util/i18n.h" // for _ InsertDeletePageUndoAction::InsertDeletePageUndoAction(const PageRef& page, size_t pagePos, bool inserted): UndoAction("InsertDeletePageUndoAction") { this->inserted = inserted; this->page = page; this->pagePos = pagePos; } InsertDeletePageUndoAction::~InsertDeletePageUndoAction() { this->page = nullptr; } auto InsertDeletePageUndoAction::undo(Control* control) -> bool { if (this->inserted) { return deletePage(control); } return insertPage(control); } auto InsertDeletePageUndoAction::redo(Control* control) -> bool { if (this->inserted) { return insertPage(control); } return deletePage(control); } auto InsertDeletePageUndoAction::insertPage(Control* control) -> bool { Document* doc = control->getDocument(); // just in case there would be a hang here, // we'll clear the selection in redo as well control->clearSelectionEndText(); doc->lock(); doc->insertPage(this->page, this->pagePos); doc->unlock(); control->firePageInserted(this->pagePos); control->getCursor()->updateCursor(); control->getScrollHandler()->scrollToPage(this->pagePos); return true; } auto InsertDeletePageUndoAction::deletePage(Control* control) -> bool { Document* doc = control->getDocument(); // in order to fix the hang, we need to get out // of text mode //***This might kill whatever we've got selected control->clearSelectionEndText(); doc->lock(); auto pNr = doc->indexOf(page); doc->unlock(); if (pNr == npos) { // this should not happen return false; } // first send event, then delete page... control->firePageDeleted(pNr); doc->lock(); doc->deletePage(pNr); doc->unlock(); return true; } auto InsertDeletePageUndoAction::getText() -> std::string { if (this->inserted) { return _("Page inserted"); } return _("Page deleted"); }
2,401
C++
.cpp
67
31.477612
107
0.677475
xournalpp/xournalpp
10,962
791
1,098
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
12,413
FillUndoAction.cpp
xournalpp_xournalpp/src/core/undo/FillUndoAction.cpp
#include "FillUndoAction.h" #include <memory> // for allocator, __shared_ptr_access, __share... #include "control/Control.h" #include "model/Document.h" #include "model/Stroke.h" // for Stroke #include "model/XojPage.h" // for XojPage #include "undo/UndoAction.h" // for UndoAction #include "util/Range.h" // for Range #include "util/i18n.h" // for _ class FillUndoActionEntry { public: FillUndoActionEntry(Stroke* s, int originalFill, int newFill) { this->s = s; this->originalFill = originalFill; this->newFill = newFill; } ~FillUndoActionEntry() = default; Stroke* s; int originalFill; int newFill; }; FillUndoAction::FillUndoAction(const PageRef& page, Layer* layer): UndoAction("FillUndoAction") { this->page = page; this->layer = layer; } FillUndoAction::~FillUndoAction() { for (FillUndoActionEntry* e: this->data) { delete e; } this->data.clear(); } void FillUndoAction::addStroke(Stroke* s, int originalFill, int newFill) { this->data.push_back(new FillUndoActionEntry(s, originalFill, newFill)); } auto FillUndoAction::undo(Control* control) -> bool { if (this->data.empty()) { return true; } Document* doc = control->getDocument(); doc->lock(); FillUndoActionEntry* e = this->data.front(); Range range(e->s->getX(), e->s->getY()); for (FillUndoActionEntry* e: this->data) { e->s->setFill(e->originalFill); range.addPoint(e->s->getX(), e->s->getY()); range.addPoint(e->s->getX() + e->s->getElementWidth(), e->s->getY() + e->s->getElementHeight()); } doc->unlock(); this->page->fireRangeChanged(range); return true; } auto FillUndoAction::redo(Control* control) -> bool { if (this->data.empty()) { return true; } Document* doc = control->getDocument(); doc->lock(); FillUndoActionEntry* e = this->data.front(); Range range(e->s->getX(), e->s->getY()); for (FillUndoActionEntry* e: this->data) { e->s->setFill(e->newFill); range.addPoint(e->s->getX(), e->s->getY()); range.addPoint(e->s->getX() + e->s->getElementWidth(), e->s->getY() + e->s->getElementHeight()); } doc->unlock(); this->page->fireRangeChanged(range); return true; } auto FillUndoAction::getText() -> std::string { return _("Change stroke fill"); }
2,386
C++
.cpp
67
31.014925
104
0.640992
xournalpp/xournalpp
10,962
791
1,098
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
12,414
PortAudioConsumer.cpp
xournalpp_xournalpp/src/core/audio/PortAudioConsumer.cpp
#include "PortAudioConsumer.h" #include <algorithm> // for for_each, transform, max #include <deque> // for _Deque_iterator #include <iterator> // for next, prev #include <string> // for to_string, string #include <glib.h> // for g_warning #include "audio/AudioQueue.h" // for AudioQueue #include "audio/DeviceInfo.h" // for DeviceInfo #include "control/settings/Settings.h" // for Settings #include "util/safe_casts.h" // for as_unsigned #include "AudioPlayer.h" // for AudioPlayer constexpr auto FRAMES_PER_BUFFER{64U}; auto PortAudioConsumer::getOutputDevices() const -> std::vector<DeviceInfo> { std::vector<DeviceInfo> deviceList; deviceList.reserve(as_unsigned(this->sys.deviceCount())); for (auto i = this->sys.devicesBegin(); i != sys.devicesEnd(); ++i) { if (i->isFullDuplexDevice() || i->isOutputOnlyDevice()) { DeviceInfo deviceInfo(&(*i), this->audioPlayer.getSettings().getAudioOutputDevice() == i->index()); deviceList.push_back(deviceInfo); } } return deviceList; } auto PortAudioConsumer::getSelectedOutputDevice() const -> DeviceInfo { try { return DeviceInfo(&sys.deviceByIndex(this->audioPlayer.getSettings().getAudioOutputDevice()), true); } catch (const portaudio::PaException& e) { g_warning("PortAudioConsumer: Selected output device was not found - fallback to default output device\nCaused " "by: %s", e.what()); return DeviceInfo(&sys.defaultOutputDevice(), true); } } auto PortAudioConsumer::isPlaying() const -> bool { return this->outputStream && this->outputStream->isActive(); } auto PortAudioConsumer::startPlaying() -> bool { // Abort a playback stream if one is currently active if (isPlaying()) { this->outputStream->abort(); } auto [sampleRate, channels] = this->audioQueue.getAudioAttributes(); if (sampleRate == -1) { g_warning("PortAudioConsumer: Timing issue - Sample rate requested before known"); return false; } // Get the device information of our output device portaudio::Device* device = nullptr; try { device = &sys.deviceByIndex(getSelectedOutputDevice().getIndex()); } catch (const portaudio::PaException&) { g_warning("PortAudioConsumer: Unable to find selected output device"); return false; } if (device->maxOutputChannels() < channels) { this->audioQueue.signalEndOfStream(); g_warning("Output device has not enough channels to play audio file. (Requires at least 2 channels)"); return false; } this->outputChannels = channels; portaudio::DirectionSpecificStreamParameters outParams(*device, channels, portaudio::FLOAT32, true, device->defaultLowOutputLatency(), nullptr); portaudio::StreamParameters params(portaudio::DirectionSpecificStreamParameters::null(), outParams, sampleRate, FRAMES_PER_BUFFER, paNoFlag); try { this->outputStream = std::make_unique<portaudio::MemFunCallbackStream<PortAudioConsumer>>( params, *this, &PortAudioConsumer::playCallback); } catch (const portaudio::PaException& e) { this->audioQueue.signalEndOfStream(); g_warning("PortAudioConsumer: Unable to open stream to device\nCaused by: %s", e.what()); return false; } // Start the recording try { this->outputStream->start(); } catch (const portaudio::PaException& e) { this->audioQueue.signalEndOfStream(); g_warning("PortAudioConsumer: Unable to start stream\nCaused by: %s", e.what()); this->outputStream.reset(); return false; } return true; } auto PortAudioConsumer::playCallback(const void* /*inputBuffer*/, void* outputBuffer, unsigned long framesPerBuffer, const PaStreamCallbackTimeInfo*, PaStreamCallbackFlags statusFlags) -> int { if (statusFlags) { g_warning("PortAudioConsumer: PortAudio reported a stream warning: %s", std::to_string(statusFlags).c_str()); } if (outputBuffer != nullptr) { auto begI = static_cast<float*>(outputBuffer); auto midI = this->audioQueue.pop(begI, framesPerBuffer * as_unsigned(this->outputChannels)); auto endI = std::next(begI, as_signed(framesPerBuffer) * this->outputChannels); // Fill buffer to requested length if necessary if (midI != endI) { // Show underflow warning if there are not enough samples and the stream is not yet finished if (!this->audioQueue.hasStreamEnded()) { g_warning("PortAudioConsumer: Not enough audio samples available to fill requested frame"); } if (midI > std::next(begI, this->outputChannels)) { // If there is previous audio data use this data to ramp down the audio samples std::transform(std::prev(midI, this->outputChannels), std::prev(endI, this->outputChannels), midI, [](auto&& ampl) { return ampl / 2.0; }); } else { // If there is no data that could be used to ramp down just output silence std::for_each(midI, endI, [](auto& ampl) { ampl = 0; }); } } // Continue playback if there is still data available if (this->audioQueue.hasStreamEnded() && this->audioQueue.empty()) { this->audioPlayer.disableAudioPlaybackButtons(); return paComplete; } return paContinue; } // The output buffer is no longer available - Abort! this->audioQueue.signalEndOfStream(); this->audioPlayer.disableAudioPlaybackButtons(); return paAbort; } void PortAudioConsumer::stopPlaying() { // Stop the playback if (this->outputStream) { try { if (this->outputStream->isActive()) { this->outputStream->stop(); } } catch (const portaudio::PaException&) { /* * We try closing the stream but this->outputStream might be an invalid object at this time if the stream * was previously closed by the backend. Just ignore this as the stream is closed either way. */ } } this->outputStream.reset(); }
6,438
C++
.cpp
133
39.842105
120
0.643471
xournalpp/xournalpp
10,962
791
1,098
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
12,415
PortAudioProducer.cpp
xournalpp_xournalpp/src/core/audio/PortAudioProducer.cpp
#include "PortAudioProducer.h" #include <algorithm> // for min, max #include <cstddef> // for size_t #include <iterator> // for next #include <string> // for to_string, string #include <glib.h> // for g_message #include "audio/AudioQueue.h" // for AudioQueue #include "audio/DeviceInfo.h" // for DeviceInfo #include "control/settings/Settings.h" // for Settings #include "util/safe_casts.h" // for as_unsigned constexpr auto FRAMES_PER_BUFFER{64U}; auto PortAudioProducer::getInputDevices() const -> std::vector<DeviceInfo> { auto devCount = as_unsigned(this->sys.deviceCount()); std::vector<DeviceInfo> deviceList; deviceList.reserve(devCount); for (auto i = this->sys.devicesBegin(); i != sys.devicesEnd(); ++i) { if (i->isFullDuplexDevice() || i->isInputOnlyDevice()) { DeviceInfo deviceInfo(&(*i), this->settings.getAudioInputDevice() == i->index()); deviceList.push_back(deviceInfo); } } return deviceList; } auto PortAudioProducer::getSelectedInputDevice() const -> DeviceInfo { try { return DeviceInfo(&sys.deviceByIndex(this->settings.getAudioInputDevice()), true); } catch (const portaudio::PaException& e) { g_message( "PortAudioProducer: Selected input device not found - fallback to default input device\nCaused by: %s", e.what()); return DeviceInfo(&sys.defaultInputDevice(), true); } } auto PortAudioProducer::isRecording() const -> bool { return this->inputStream && this->inputStream->isActive(); } auto PortAudioProducer::startRecording() -> bool { // Check if there already is a recording if (this->inputStream) { return false; } // Get the device information of our input device portaudio::Device* device = nullptr; try { device = &sys.deviceByIndex(getSelectedInputDevice().getIndex()); } catch (const portaudio::PaException&) { g_message("PortAudioProducer: Unable to find selected input device"); return false; } // Restrict recording channels to 2 as playback devices should have 2 channels at least this->inputChannels = std::min(2, device->maxInputChannels()); portaudio::DirectionSpecificStreamParameters inParams(*device, this->inputChannels, portaudio::FLOAT32, true, device->defaultLowInputLatency(), nullptr); portaudio::StreamParameters params(inParams, portaudio::DirectionSpecificStreamParameters::null(), this->settings.getAudioSampleRate(), FRAMES_PER_BUFFER, paNoFlag); this->audioQueue.setAudioAttributes(this->settings.getAudioSampleRate(), static_cast<unsigned int>(this->inputChannels)); // Specify the callback used for buffering the recorded data try { this->inputStream = std::make_unique<portaudio::MemFunCallbackStream<PortAudioProducer>>( params, *this, &PortAudioProducer::recordCallback); } catch (const portaudio::PaException&) { g_message("PortAudioProducer: Unable to open stream"); return false; } // Start the recording try { this->inputStream->start(); } catch (const portaudio::PaException&) { g_message("PortAudioProducer: Unable to start stream"); this->inputStream.reset(); return false; } return true; } auto PortAudioProducer::recordCallback(const void* inputBuffer, void* /*outputBuffer*/, unsigned long framesPerBuffer, const PaStreamCallbackTimeInfo*, PaStreamCallbackFlags statusFlags) -> int { if (statusFlags) { g_message("PortAudioProducer: statusFlag: %s", std::to_string(statusFlags).c_str()); } if (inputBuffer != nullptr) { size_t providedFrames = framesPerBuffer * as_unsigned(this->inputChannels); auto begI = static_cast<float const*>(inputBuffer); this->audioQueue.emplace(begI, std::next(begI, as_signed(providedFrames))); } return paContinue; } void PortAudioProducer::stopRecording() { // Stop the recording if (this->inputStream) { try { if (this->inputStream->isActive()) { this->inputStream->stop(); } } catch (const portaudio::PaException&) { g_message("PortAudioProducer: Closing stream failed"); } } // Notify the consumer at the other side that there will be no more data this->audioQueue.signalEndOfStream(); // Allow new recording by removing the old one this->inputStream.reset(); }
4,692
C++
.cpp
101
38.742574
119
0.659006
xournalpp/xournalpp
10,962
791
1,098
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
12,416
DeviceInfo.cpp
xournalpp_xournalpp/src/core/audio/DeviceInfo.cpp
#include "DeviceInfo.h" DeviceInfo::DeviceInfo(portaudio::Device* device, bool selected): deviceName(device->name()), index(device->index()), selected(selected), inputChannels((device->isFullDuplexDevice() || device->isInputOnlyDevice()) ? device->maxInputChannels() : 0), outputChannels((device->isFullDuplexDevice() || device->isOutputOnlyDevice()) ? device->maxOutputChannels() : 0) {} auto DeviceInfo::getDeviceName() const -> const std::string& { return deviceName; } auto DeviceInfo::getIndex() const -> PaDeviceIndex { return index; } auto DeviceInfo::getSelected() const -> bool { return selected; }
740
C++
.cpp
11
54.272727
118
0.624828
xournalpp/xournalpp
10,962
791
1,098
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
12,417
AudioRecorder.cpp
xournalpp_xournalpp/src/core/audio/AudioRecorder.cpp
#include "AudioRecorder.h" #include "audio/AudioQueue.h" // for AudioQueue #include "audio/DeviceInfo.h" // for DeviceInfo #include "audio/PortAudioProducer.h" // for PortAudioProducer #include "audio/VorbisConsumer.h" // for VorbisConsumer AudioRecorder::AudioRecorder(Settings& settings): audioQueue(std::make_unique<AudioQueue<float>>()), portAudioProducer(std::make_unique<PortAudioProducer>(settings, *audioQueue)), vorbisConsumer(std::make_unique<VorbisConsumer>(settings, *audioQueue)) {} AudioRecorder::~AudioRecorder() { this->stop(); } auto AudioRecorder::start(fs::path const& file) -> bool { bool status = this->portAudioProducer->startRecording(); // Start the consumer for writing the data status = status && this->vorbisConsumer->start(file); return status; } void AudioRecorder::stop() { this->portAudioProducer->stopRecording(); this->vorbisConsumer->join(); // libsox must write all the data before we can continue this->audioQueue->reset(); // next recording requires empty queue } auto AudioRecorder::isRecording() const -> bool { return this->portAudioProducer->isRecording(); } auto AudioRecorder::getInputDevices() const -> std::vector<DeviceInfo> { return this->portAudioProducer->getInputDevices(); }
1,315
C++
.cpp
25
49.08
98
0.731878
xournalpp/xournalpp
10,962
791
1,098
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
12,418
VorbisConsumer.cpp
xournalpp_xournalpp/src/core/audio/VorbisConsumer.cpp
#include "VorbisConsumer.h" #include <algorithm> // for for_each, min, max #include <cstddef> // for size_t #include <deque> // for _Deque_iterator #include <iterator> // for back_insert_iterator, back_in... #include <memory> // for unique_ptr #include <string> // for string #include <utility> // for move #include <vector> // for vector #include <glib.h> // for g_warning #include <sndfile.h> // for SF_INFO, sf_strerror, sf_writ... #include "audio/AudioQueue.h" // for AudioQueue #include "control/settings/Settings.h" // for Settings #include "SNDFileCpp.h" // for make_snd_file, xoj using namespace xoj; auto VorbisConsumer::start(fs::path const& file) -> bool { auto [sampleRate, channels] = this->audioQueue.getAudioAttributes(); if (sampleRate == -1) { g_warning("VorbisConsumer: Timing issue - Sample rate requested before known"); return false; } SF_INFO sfInfo; sfInfo.channels = channels; sfInfo.format = SF_FORMAT_OGG | SF_FORMAT_VORBIS; sfInfo.samplerate = static_cast<int>(this->settings.getAudioSampleRate()); auto sfFile = audio::make_snd_file(file.native(), SFM_WRITE, &sfInfo); if (!sfFile) { g_warning("VorbisConsumer: output file \"%s\" could not be opened\ncaused by:%s", file.u8string().c_str(), sf_strerror(sfFile.get())); return false; } this->consumerThread = std::thread([this, sfFile = std::move(sfFile), channels = channels] { auto lock{audioQueue.acquire_lock()}; auto buffer_size{size_t(64 * channels)}; std::vector<float> buffer; buffer.reserve(buffer_size); // efficiency float audioGain = static_cast<float>(this->settings.getAudioGain()); while (!(this->stopConsumer || (audioQueue.hasStreamEnded() && audioQueue.empty()))) { audioQueue.waitForProducer(lock); while (audioQueue.size() > buffer_size || (audioQueue.hasStreamEnded() && !audioQueue.empty())) { buffer.resize(0); this->audioQueue.pop(std::back_inserter(buffer), buffer_size); // apply gain if (audioGain != 1.0f) { std::for_each(begin(buffer), end(buffer), [audioGain](auto& val) { val *= audioGain; }); } sf_writef_float(sfFile.get(), buffer.data(), std::min<sf_count_t>(sf_count_t(buffer.size()) / channels, 64)); } } }); return true; } void VorbisConsumer::join() { // Join the consumer thread to wait for completion if (this->consumerThread.joinable()) { this->consumerThread.join(); } } void VorbisConsumer::stop() { // Stop consumer this->audioQueue.signalEndOfStream(); // Wait for consumer to finish join(); }
2,852
C++
.cpp
65
36.846154
114
0.620988
xournalpp/xournalpp
10,962
791
1,098
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
12,419
VorbisProducer.cpp
xournalpp_xournalpp/src/core/audio/VorbisProducer.cpp
#include "VorbisProducer.h" #include <algorithm> // for fill_n, max #include <cstdio> // for size_t, SEEK_CUR, SEEK_SET #include <iterator> // for begin, end #include <memory> // for unique_ptr #include <string> // for string #include <utility> // for move #include <vector> // for vector #include <glib.h> // for g_warning #include <sndfile.h> // for SF_INFO, sf_seek, sf_count_t, sf_readf... #include "audio/AudioQueue.h" // for AudioQueue #include "audio/SNDFileCpp.h" // for make_snd_file, xoj using namespace xoj; constexpr auto sample_buffer_size = size_t{16384U}; auto VorbisProducer::start(fs::path const& file, unsigned int timestamp) -> bool { SF_INFO sfInfo{}; auto sfFile = audio::make_snd_file(file, SFM_READ, &sfInfo); if (!sfFile) { g_warning("VorbisProducer: input file \"%s\" could not be opened\ncaused by:%s", file.u8string().c_str(), sf_strerror(sfFile.get())); return false; } sf_count_t seekPosition = sfInfo.samplerate / 1000 * sf_count_t(timestamp); if (seekPosition < sfInfo.frames) { sf_seek(sfFile.get(), seekPosition, SEEK_SET); } else { g_warning("VorbisProducer: Seeking outside of audio file extent"); } this->audioQueue.setAudioAttributes(sfInfo.samplerate, static_cast<unsigned int>(sfInfo.channels)); this->producerThread = std::thread([this, sfInfo, sfFile = std::move(sfFile)] { sf_count_t numFrames{1}; size_t const bufferSize{size_t(1024U) * size_t(sfInfo.channels)}; std::vector<float> sampleBuffer(bufferSize); auto lock = audioQueue.acquire_lock(); while (!this->stopProducer && numFrames > 0 && !this->audioQueue.hasStreamEnded()) { sampleBuffer.resize(bufferSize); numFrames = sf_readf_float(sfFile.get(), sampleBuffer.data(), 1024); sampleBuffer.resize(size_t(numFrames * sfInfo.channels)); while (this->audioQueue.size() >= sample_buffer_size && !this->audioQueue.hasStreamEnded() && !this->stopProducer) { audioQueue.waitForConsumer(lock); } if (auto tmpSeekSeconds = this->seekSeconds.load(); tmpSeekSeconds != 0) { sf_seek(sfFile.get(), tmpSeekSeconds * sfInfo.samplerate, SEEK_CUR); this->seekSeconds -= tmpSeekSeconds; } this->audioQueue.emplace(begin(sampleBuffer), end(sampleBuffer)); } this->audioQueue.signalEndOfStream(); }); return true; } void VorbisProducer::abort() { this->stopProducer = true; // Wait for producer to finish stop(); this->stopProducer = false; } void VorbisProducer::stop() { // Wait for producer to finish if (this->producerThread.joinable()) { this->producerThread.join(); } } void VorbisProducer::seek(int seconds) { this->seekSeconds = seconds; }
2,928
C++
.cpp
65
38.338462
113
0.646397
xournalpp/xournalpp
10,962
791
1,098
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
12,420
AudioPlayer.cpp
xournalpp_xournalpp/src/core/audio/AudioPlayer.cpp
#include "AudioPlayer.h" #include "audio/AudioQueue.h" // for AudioQueue #include "audio/DeviceInfo.h" // for DeviceInfo #include "audio/PortAudioConsumer.h" // for PortAudioConsumer #include "audio/VorbisProducer.h" // for VorbisProducer #include "control/Control.h" // for Control #include "control/actions/ActionDatabase.h" // for ActionDatabase #include "gui/MainWindow.h" // for MainWindow class Settings; AudioPlayer::AudioPlayer(Control& control, Settings& settings): control(control), settings(settings), audioQueue(std::make_unique<AudioQueue<float>>()), portAudioConsumer(std::make_unique<PortAudioConsumer>(*this, *audioQueue)), vorbisProducer(std::make_unique<VorbisProducer>(*audioQueue)) {} AudioPlayer::~AudioPlayer() { this->stop(); } auto AudioPlayer::start(fs::path const& file, unsigned int timestamp) -> bool { // Start the producer for reading the data bool status = this->vorbisProducer->start(file, timestamp); // Start playing if (status) { status = status && this->play(); } return status; } auto AudioPlayer::isPlaying() -> bool { return this->portAudioConsumer->isPlaying(); } void AudioPlayer::pause() { if (!this->portAudioConsumer->isPlaying()) { return; } // Stop playing audio this->portAudioConsumer->stopPlaying(); } auto AudioPlayer::play() -> bool { if (this->portAudioConsumer->isPlaying()) { return false; } return this->portAudioConsumer->startPlaying(); } void AudioPlayer::disableAudioPlaybackButtons() { if (this->audioQueue->hasStreamEnded()) { auto* actionDB = this->control.getActionDatabase(); actionDB->enableAction(Action::AUDIO_PAUSE_PLAYBACK, false); actionDB->enableAction(Action::AUDIO_STOP_PLAYBACK, false); actionDB->enableAction(Action::AUDIO_SEEK_FORWARDS, false); actionDB->enableAction(Action::AUDIO_SEEK_BACKWARDS, false); actionDB->setActionState(Action::AUDIO_PAUSE_PLAYBACK, false); } } void AudioPlayer::stop() { disableAudioPlaybackButtons(); // Stop playing audio this->portAudioConsumer->stopPlaying(); this->audioQueue->signalEndOfStream(); // Abort libsox this->vorbisProducer->abort(); // Reset the queue for the next playback this->audioQueue->reset(); } void AudioPlayer::seek(int seconds) { // set seek flag here in vorbisProducer this->vorbisProducer->seek(seconds); } auto AudioPlayer::getOutputDevices() -> std::vector<DeviceInfo> { return this->portAudioConsumer->getOutputDevices(); } auto AudioPlayer::getSettings() -> Settings& { return this->settings; }
2,749
C++
.cpp
65
37.723077
119
0.692192
xournalpp/xournalpp
10,962
791
1,098
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
12,421
PopplerGlibDocument.cpp
xournalpp_xournalpp/src/core/pdf/popplerapi/PopplerGlibDocument.cpp
#include "PopplerGlibDocument.h" #include <memory> // for make_shared, unique_ptr #include <optional> // for optional #include <poppler-document.h> // for poppler_document_get_n_... #include "util/PathUtil.h" // for toUri #include "PopplerGlibPage.h" // for PopplerGlibPage #include "PopplerGlibPageBookmarkIterator.h" // for PopplerGlibPageBookmark... #include "filesystem.h" // for path class XojPdfBookmarkIterator; using std::string; PopplerGlibDocument::PopplerGlibDocument() = default; PopplerGlibDocument::PopplerGlibDocument(const PopplerGlibDocument& doc): document(doc.document) { if (document) { g_object_ref(document); } } PopplerGlibDocument::~PopplerGlibDocument() { if (document) { g_object_unref(document); document = nullptr; } } void PopplerGlibDocument::assign(XojPdfDocumentInterface* doc) { if (document) { g_object_unref(document); } document = (dynamic_cast<PopplerGlibDocument*>(doc))->document; if (document) { g_object_ref(document); } } auto PopplerGlibDocument::equals(XojPdfDocumentInterface* doc) const -> bool { return document == (dynamic_cast<PopplerGlibDocument*>(doc))->document; } auto PopplerGlibDocument::save(fs::path const& file, GError** error) const -> bool { if (document == nullptr) { return false; } auto uri = Util::toUri(file); if (!uri) { return false; } return poppler_document_save(document, uri->c_str(), error); } auto PopplerGlibDocument::load(fs::path const& file, string password, GError** error) -> bool { auto uri = Util::toUri(file); if (!uri) { return false; } if (document) { g_object_unref(document); document = nullptr; } this->document = poppler_document_new_from_file(uri->c_str(), password.c_str(), error); return this->document != nullptr; } auto PopplerGlibDocument::load(std::unique_ptr<std::string> data, string password, GError** error) -> bool { if (document) { g_object_unref(document); } GBytes* bytes = g_bytes_new_with_free_func( data->data(), data->size(), [](gpointer d) { delete reinterpret_cast<std::string*>(d); }, data.get()); data.release(); // the string will be deleted with the bytes object this->document = poppler_document_new_from_bytes(bytes, password.c_str(), error); g_bytes_unref(bytes); // a reference is now held by the document return this->document != nullptr; } auto PopplerGlibDocument::isLoaded() const -> bool { return this->document != nullptr; } void PopplerGlibDocument::reset() { if (document) { g_object_unref(document); document = nullptr; } } auto PopplerGlibDocument::getPage(size_t page) const -> XojPdfPageSPtr { if (document == nullptr) { return nullptr; } PopplerPage* pg = poppler_document_get_page(document, int(page)); XojPdfPageSPtr pageptr = std::make_shared<PopplerGlibPage>(pg, document); g_object_unref(pg); return pageptr; } auto PopplerGlibDocument::getPageCount() const -> size_t { if (document == nullptr) { return 0; } return size_t(poppler_document_get_n_pages(document)); } auto PopplerGlibDocument::getContentsIter() const -> XojPdfBookmarkIterator* { if (document == nullptr) { return nullptr; } PopplerIndexIter* iter = poppler_index_iter_new(document); if (iter == nullptr) { return nullptr; } return new PopplerGlibPageBookmarkIterator(iter, document); }
3,602
C++
.cpp
99
31.676768
114
0.676555
xournalpp/xournalpp
10,962
791
1,098
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
12,422
PopplerGlibPageBookmarkIterator.cpp
xournalpp_xournalpp/src/core/pdf/popplerapi/PopplerGlibPageBookmarkIterator.cpp
#include "PopplerGlibPageBookmarkIterator.h" #include <poppler-action.h> // for poppler_action_free #include <poppler-document.h> // for poppler_index_iter_free #include "pdf/popplerapi/PopplerGlibAction.h" // for PopplerGlibAction class XojPdfAction; PopplerGlibPageBookmarkIterator::PopplerGlibPageBookmarkIterator(PopplerIndexIter* iter, PopplerDocument* document): iter(iter), document(document) { g_object_ref(document); } PopplerGlibPageBookmarkIterator::~PopplerGlibPageBookmarkIterator() { poppler_index_iter_free(iter); iter = nullptr; if (document) { g_object_unref(document); document = nullptr; } } auto PopplerGlibPageBookmarkIterator::next() -> bool { return poppler_index_iter_next(iter); } auto PopplerGlibPageBookmarkIterator::isOpen() -> bool { return poppler_index_iter_is_open(iter); } auto PopplerGlibPageBookmarkIterator::getChildIter() -> XojPdfBookmarkIterator* { PopplerIndexIter* child = poppler_index_iter_get_child(iter); if (child == nullptr) { return nullptr; } return new PopplerGlibPageBookmarkIterator(child, document); } auto PopplerGlibPageBookmarkIterator::getAction() -> XojPdfAction* { PopplerAction* action = poppler_index_iter_get_action(iter); if (action == nullptr) { return nullptr; } XojPdfAction* result = new PopplerGlibAction(action, document); poppler_action_free(action); // XojPdfAction does not own action. return result; }
1,495
C++
.cpp
35
38.457143
116
0.750346
xournalpp/xournalpp
10,962
791
1,098
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
12,423
PopplerGlibPage.cpp
xournalpp_xournalpp/src/core/pdf/popplerapi/PopplerGlibPage.cpp
#include "PopplerGlibPage.h" #include <algorithm> // for max, min #include <cstdlib> // for abs, NULL, ptrdiff_t #include <memory> // for make_unique #include <sstream> // for operator<<, ostringstream, bas... #include <glib.h> // for g_free, g_utf8_offset_to_pointer #include <poppler-page.h> // for _PopplerRectangle, _PopplerLin... #include <poppler.h> // for PopplerRectangle, g_object_ref #include "pdf/base/XojPdfAction.h" // for XojPdfAction #include "pdf/base/XojPdfPage.h" // for XojPdfRectangle, XojPdfPage::Link #include "util/Assert.h" // for xoj_assert #include "util/GListView.h" // for GListView, GListView<>::GListV... #include "util/raii/CLibrariesSPtr.h" // for adopt #include "util/raii/CairoWrappers.h" // for CairoRegionSPtr #include "PopplerGlibAction.h" // for PopplerGlibAction #include "cairo.h" // for cairo_region_create, cairo_reg... PopplerGlibPage::PopplerGlibPage(PopplerPage* page, PopplerDocument* parentDoc): page(page), document(parentDoc) { if (page != nullptr) { g_object_ref(page); } } PopplerGlibPage::PopplerGlibPage(const PopplerGlibPage& other): page(other.page), document(other.document) { if (page != nullptr) { g_object_ref(page); } document = nullptr; } PopplerGlibPage::~PopplerGlibPage() { if (page) { g_object_unref(page); page = nullptr; } } PopplerGlibPage& PopplerGlibPage::operator=(const PopplerGlibPage& other) { if (&other == this) { return *this; } if (page) { g_object_unref(page); page = nullptr; } page = other.page; if (page != nullptr) { g_object_ref(page); } document = other.document; return *this; } auto PopplerGlibPage::getWidth() const -> double { double width = 0; poppler_page_get_size(const_cast<PopplerPage*>(page), &width, nullptr); return width; } auto PopplerGlibPage::getHeight() const -> double { double height = 0; poppler_page_get_size(const_cast<PopplerPage*>(page), nullptr, &height); return height; } void PopplerGlibPage::render(cairo_t* cr) const { cairo_save(cr); cairo_set_source_rgb(cr, 1., 1., 1.); cairo_paint(cr); poppler_page_render(page, cr); cairo_restore(cr); } void PopplerGlibPage::renderForPrinting(cairo_t* cr) const { poppler_page_render_for_printing(page, cr); } auto PopplerGlibPage::getPageId() const -> int { return poppler_page_get_index(page); } auto PopplerGlibPage::getPageLabel() const -> std::string { gchar* label{poppler_page_get_label(page)}; std::string cpp_label{label}; g_free(label); return cpp_label; } auto PopplerGlibPage::findText(const std::string& text) -> std::vector<XojPdfRectangle> { std::vector<XojPdfRectangle> findings; double height = getHeight(); GList* matches = poppler_page_find_text(page, text.c_str()); for (auto& rect: GListView<PopplerRectangle>(matches)) { findings.emplace_back(rect.x1, height - rect.y2, rect.x2, height - rect.y1); poppler_rectangle_free(&rect); } g_list_free(matches); return findings; } auto getPopplerSelectionStyle(XojPdfPageSelectionStyle style) -> PopplerSelectionStyle { switch (style) { case XojPdfPageSelectionStyle::Word: return POPPLER_SELECTION_WORD; case XojPdfPageSelectionStyle::Line: return POPPLER_SELECTION_LINE; case XojPdfPageSelectionStyle::Linear: case XojPdfPageSelectionStyle::Area: return POPPLER_SELECTION_GLYPH; default: xoj_assert_message(false, "unimplemented"); } } auto PopplerGlibPage::selectText(const XojPdfRectangle& rect, XojPdfPageSelectionStyle style) -> std::string { PopplerRectangle pRect = {rect.x1, rect.y1, rect.x2, rect.y2}; const auto pStyle = getPopplerSelectionStyle(style); if (style == XojPdfPageSelectionStyle::Area) { PopplerRectangle* rectArray = nullptr; guint numRects = 0; if (!poppler_page_get_text_layout_for_area(this->page, &pRect, &rectArray, &numRects)) { return ""; } char* textBytes = poppler_page_get_text_for_area(page, &pRect); xoj_assert(textBytes); double y = rectArray[0].y2; std::ostringstream ss; for (guint i = 0; i < numRects; i++) { // do not copy characters whose bounding box has a non-empty intersection with rect const auto& r = rectArray[i]; { auto x1 = std::max(rect.x1, r.x1); auto y1 = std::max(rect.y1, r.y1); auto x2 = std::min(rect.x2, r.x2); auto y2 = std::min(rect.y2, r.y2); bool inBounds = x2 > x1 && y2 > y1; if (!inBounds) continue; } const auto eps = 1e-5; if (std::abs(y - r.y2) > eps) { // new line ss << '\n'; y = rectArray[i].y2; } char* const startPos = g_utf8_offset_to_pointer(textBytes, i); char* const endPos = g_utf8_offset_to_pointer(textBytes, i + 1); for (long j = 0; j < static_cast<ptrdiff_t>(endPos - startPos); ++j) { ss << startPos[j]; } } g_free(textBytes); return ss.str(); } else { char* text = poppler_page_get_selected_text(page, pStyle, &pRect); if (text) { std::string ret(text); g_free(text); return ret; } else { return ""; } } } auto PopplerGlibPage::selectTextRegion(const XojPdfRectangle& rect, XojPdfPageSelectionStyle style) -> cairo_region_t* { PopplerRectangle pRect = {rect.x1, rect.y1, rect.x2, rect.y2}; const auto pStyle = getPopplerSelectionStyle(style); // The computed region is technically wrong for // XojPdfPageSelectionStyle::Area, but there is no selection preview with // area select. cairo_region_t* region = poppler_page_get_selected_region(page, 1.0, pStyle, &pRect); return region; } namespace { cairo_rectangle_int_t cairoRectFromDouble(double x1, double y1, double width, double height) { return {static_cast<int>(x1), static_cast<int>(y1), static_cast<int>(width), static_cast<int>(height)}; } } // namespace auto PopplerGlibPage::selectTextLines(const XojPdfRectangle& selectRect, XojPdfPageSelectionStyle style) -> TextSelection { std::vector<XojPdfRectangle> textRects; // The selection rectangle may be "improper" by having x2 <= x1 or y1 <= y2 (e.g., if user // selects from right to left or from bottom to top). This is incompatible with cairo, so // construct a proper rectangle satisfying x1 <= x2 and y1 <= y2. PopplerRectangle rect{std::min(selectRect.x1, selectRect.x2), std::min(selectRect.y1, selectRect.y2), std::max(selectRect.x1, selectRect.x2), std::max(selectRect.y1, selectRect.y2)}; PopplerRectangle* rectArray = nullptr; guint numRects = 0; if (style == XojPdfPageSelectionStyle::Area) { // We always want to select in the "proper" rectangle. PopplerRectangle area{rect.x1, rect.y1, rect.x2, rect.y2}; if (!poppler_page_get_text_layout_for_area(this->page, &area, &rectArray, &numRects)) { return {xoj::util::CairoRegionSPtr(cairo_region_create(), xoj::util::adopt), textRects}; } } else { if (!poppler_page_get_text_layout(this->page, &rectArray, &numRects)) { return {xoj::util::CairoRegionSPtr(cairo_region_create(), xoj::util::adopt), textRects}; } } // construct the region later for area selection, but use poppler's region // for other selection styles cairo_region_t* region = nullptr; if (style != XojPdfPageSelectionStyle::Area) { // do not use the "proper" rectangle here as it may be different from the actual selection. region = selectTextRegion(selectRect, style); } const auto isSameLine = [&](const auto& r1, const auto& r2) { const auto eps = 1e-5; return std::abs(r1.y1 - r2.y1) < eps && std::abs(r1.y2 - r2.y2) < eps; }; PopplerRectangle prevRect = rectArray[0]; if (style == XojPdfPageSelectionStyle::Area) { // helper to add only those rectangles that have nonempty intersection with the selected area const auto addTextRectsInArea = [&](const PopplerRectangle& r) { auto x1 = std::max(rect.x1, r.x1); auto y1 = std::max(rect.y1, r.y1); auto x2 = std::min(rect.x2, r.x2); auto y2 = std::min(rect.y2, r.y2); bool inBounds = x2 > x1 && y2 > y1; if (inBounds) { textRects.emplace_back(r.x1, r.y1, r.x2, r.y2); } }; // construct the text rectangles for (guint i = 1; i < numRects; i++) { PopplerRectangle nextRect = rectArray[i]; if (isSameLine(prevRect, nextRect)) { // Merge if both prev & next rectangles are in bounds. Note that // only x is checked since rectArray was constructed for the // selected area. bool shouldMerge = (rect.x1 <= prevRect.x1 && prevRect.x2 <= rect.x2 && rect.x1 <= nextRect.x1 && nextRect.x2 <= rect.x2); if (shouldMerge) { prevRect.x1 = std::min(prevRect.x1, nextRect.x2); prevRect.x2 = std::max(prevRect.x2, nextRect.x2); continue; } } addTextRectsInArea(prevRect); prevRect = nextRect; } addTextRectsInArea(prevRect); region = cairo_region_create(); for (const XojPdfRectangle& r: textRects) { const auto x1 = std::min(r.x1, r.x2); const auto x2 = std::max(r.x1, r.x2); const auto y1 = std::min(r.y1, r.y2); const auto y2 = std::max(r.y1, r.y2); cairo_rectangle_int_t crect = cairoRectFromDouble(x1, y1, x2 - x1, y2 - y1); cairo_region_union_rectangle(region, &crect); } } else { // this is for all other styles (e.g., linear) // helper to add only those rectangles that are contained in the selection region const auto addTextRectsInRegion = [&](const PopplerRectangle& r) { auto crect = cairoRectFromDouble(r.x1, r.y1, r.x2 - r.x1, r.y2 - r.y1); if (cairo_region_contains_rectangle(region, &crect) == CAIRO_REGION_OVERLAP_IN) { textRects.emplace_back(r.x1, r.y1, r.x2, r.y2); } }; // construct the text rectangles for (guint i = 1; i < numRects; i++) { PopplerRectangle nextRect = rectArray[i]; if (isSameLine(prevRect, nextRect)) { // merge the rectangles if they, when combined, are contained in the selection region auto x1 = std::min(prevRect.x1, nextRect.x2); auto x2 = std::max(prevRect.x2, nextRect.x2); auto crect = cairoRectFromDouble(x1, prevRect.y1, x2 - x1, prevRect.y2 - prevRect.y1); if (cairo_region_contains_rectangle(region, &crect) == CAIRO_REGION_OVERLAP_IN) { prevRect.x1 = x1; prevRect.x2 = x2; continue; } } addTextRectsInRegion(prevRect); prevRect = nextRect; } addTextRectsInRegion(prevRect); } xoj_assert(region); return {xoj::util::CairoRegionSPtr(region, xoj::util::adopt), textRects}; } auto PopplerGlibPage::getLinks() -> std::vector<Link> { std::vector<Link> results; const double height = getHeight(); GList* links = poppler_page_get_link_mapping(this->page); for (GList* l = links; l != NULL; l = g_list_next(l)) { const auto& link = *static_cast<PopplerLinkMapping*>(l->data); if (link.action) { XojPdfRectangle rect{link.area.x1, height - link.area.y2, link.area.x2, height - link.area.y1}; results.emplace_back(Link{rect, std::make_unique<PopplerGlibAction>(link.action, document)}); } } poppler_page_free_link_mapping(links); return results; }
12,380
C++
.cpp
277
36.3213
120
0.615761
xournalpp/xournalpp
10,962
791
1,098
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
12,424
PopplerGlibAction.cpp
xournalpp_xournalpp/src/core/pdf/popplerapi/PopplerGlibAction.cpp
#include "PopplerGlibAction.h" #include <algorithm> // for min #include <cstddef> // for size_t #include <glib.h> // for g_warning, gchar #include <poppler-action.h> // for poppler_dest_free, PopplerActi... #include <poppler-document.h> // for poppler_document_find_dest #include <poppler-page.h> // for poppler_page_get_size #include "model/LinkDestination.h" // for LinkDestination #include "util/Util.h" // for npos #include "util/raii/CLibrariesSPtr.h" // for ref using std::string; PopplerGlibAction::PopplerGlibAction(PopplerAction* action, PopplerDocument* document): document(document, xoj::util::ref) { if (gchar* title_cstr = reinterpret_cast<PopplerActionAny*>(action)->title) { title = std::string{title_cstr}; } destination = getDestination(action); } PopplerGlibAction::~PopplerGlibAction() = default; auto PopplerGlibAction::getDestination(PopplerAction* action) -> std::shared_ptr<const LinkDestination> { auto dest = std::make_shared<LinkDestination>(); dest->setName(getTitle()); if (action->type == POPPLER_ACTION_URI && action->uri.uri) { dest->setURI(std::string{action->uri.uri}); } else if (action->type == POPPLER_ACTION_GOTO_DEST) { auto* actionDest = reinterpret_cast<PopplerActionGotoDest*>(action); PopplerDest* pDest = actionDest->dest; if (pDest == nullptr) { return dest; } linkFromDest(*dest, pDest); } else { // Every other action is currently unsupported. } return dest; } auto PopplerGlibAction::getDestination() -> std::shared_ptr<const LinkDestination> { return destination; } void PopplerGlibAction::linkFromDest(LinkDestination& link, PopplerDest* pDest) { switch (pDest->type) { case POPPLER_DEST_UNKNOWN: g_warning("PDF Contains unknown link destination"); break; case POPPLER_DEST_XYZ: { PopplerPage* page = poppler_document_get_page(document.get(), pDest->page_num - 1); if (page == nullptr) { return; } double pageWidth = 0; double pageHeight = 0; poppler_page_get_size(page, &pageWidth, &pageHeight); if (pDest->left != 0) { link.setChangeLeft(pDest->left); } else if (pDest->right != 0) { link.setChangeLeft(pageWidth - pDest->right); } if (pDest->top != 0) { link.setChangeTop(pageHeight - std::min(pageHeight, pDest->top)); } else if (pDest->bottom != 0) { link.setChangeTop(pageHeight - std::min(pageHeight, pageHeight - pDest->bottom)); } if (pDest->zoom != 0) { link.setChangeZoom(pDest->zoom); } g_object_unref(page); } break; case POPPLER_DEST_NAMED: { PopplerDest* pDest2 = poppler_document_find_dest(document.get(), pDest->named_dest); if (pDest2 != nullptr) { linkFromDest(link, pDest2); poppler_dest_free(pDest2); return; } } break; default: break; } link.setPdfPage(pDest->page_num > 0 ? static_cast<size_t>(pDest->page_num - 1) : npos); } auto PopplerGlibAction::getTitle() -> std::string { return title; }
3,414
C++
.cpp
79
34.607595
106
0.608027
xournalpp/xournalpp
10,962
791
1,098
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
12,425
XojPdfPage.cpp
xournalpp_xournalpp/src/core/pdf/base/XojPdfPage.cpp
#include "XojPdfPage.h" XojPdfRectangle::XojPdfRectangle(double x1, double y1, double x2, double y2): x1(x1), y1(y1), x2(x2), y2(y2) {}
137
C++
.cpp
2
67
111
0.716418
xournalpp/xournalpp
10,962
791
1,098
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
12,426
XojPdfDocument.cpp
xournalpp_xournalpp/src/core/pdf/base/XojPdfDocument.cpp
#include "XojPdfDocument.h" #include "pdf/base/XojPdfDocumentInterface.h" // for XojPdfDocumentInterface #include "pdf/base/XojPdfPage.h" // for XojPdfPageSPtr #include "pdf/popplerapi/PopplerGlibDocument.h" // for PopplerGlibDocument #include "filesystem.h" // for path class XojPdfBookmarkIterator; XojPdfDocument::XojPdfDocument(): doc(new PopplerGlibDocument()) {} XojPdfDocument::XojPdfDocument(const XojPdfDocument& doc): doc(new PopplerGlibDocument()) { this->doc->assign(doc.doc); } XojPdfDocument::~XojPdfDocument() { delete doc; doc = nullptr; } auto XojPdfDocument::operator=(const XojPdfDocument& doc) -> XojPdfDocument& { this->doc->assign(doc.doc); return *this; } auto XojPdfDocument::operator==(XojPdfDocument& doc) const -> bool { return this->doc->equals(doc.doc); } void XojPdfDocument::assign(XojPdfDocumentInterface* doc) { this->doc->assign(doc); } auto XojPdfDocument::equals(XojPdfDocumentInterface* doc) const -> bool { return this->doc->equals(doc); } auto XojPdfDocument::save(fs::path const& file, GError** error) const -> bool { return doc->save(file, error); } auto XojPdfDocument::load(fs::path const& file, std::string password, GError** error) -> bool { return doc->load(file, password, error); } auto XojPdfDocument::load(std::unique_ptr<std::string> data, std::string password, GError** error) -> bool { return doc->load(std::move(data), password, error); } auto XojPdfDocument::isLoaded() const -> bool { return doc->isLoaded(); } void XojPdfDocument::reset() { doc->reset(); } auto XojPdfDocument::getPage(size_t page) const -> XojPdfPageSPtr { return doc->getPage(page); } auto XojPdfDocument::getPageCount() const -> size_t { return doc->getPageCount(); } auto XojPdfDocument::getContentsIter() const -> XojPdfBookmarkIterator* { return doc->getContentsIter(); }
1,869
C++
.cpp
33
54.242424
112
0.740374
xournalpp/xournalpp
10,962
791
1,098
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
12,427
XojPdfExport.cpp
xournalpp_xournalpp/src/core/pdf/base/XojPdfExport.cpp
#include "XojPdfExport.h" XojPdfExport::XojPdfExport() = default; XojPdfExport::~XojPdfExport() = default; /** * Export without background */ void XojPdfExport::setExportBackground(ExportBackgroundType exportBackground) { // Does nothing in the base class }
267
C++
.cpp
9
27.666667
79
0.788235
xournalpp/xournalpp
10,962
791
1,098
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
12,428
XojPdfExportFactory.cpp
xournalpp_xournalpp/src/core/pdf/base/XojPdfExportFactory.cpp
#include "XojPdfExportFactory.h" #include "XojCairoPdfExport.h" // for XojCairoPdfExport class XojPdfExport; XojPdfExportFactory::XojPdfExportFactory() = default; XojPdfExportFactory::~XojPdfExportFactory() = default; auto XojPdfExportFactory::createExport(Document* doc, ProgressListener* listener) -> std::unique_ptr<XojPdfExport> { return std::make_unique<XojCairoPdfExport>(doc, listener); }
406
C++
.cpp
8
48.625
116
0.814249
xournalpp/xournalpp
10,962
791
1,098
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
12,429
XojCairoPdfExport.cpp
xournalpp_xournalpp/src/core/pdf/base/XojCairoPdfExport.cpp
#include "XojCairoPdfExport.h" #include <algorithm> // for copy, min #include <map> // for map #include <memory> // for __shared_ptr_access #include <sstream> // for ostringstream, operator<< #include <stack> // for stack #include <utility> // for pair, make_pair #include <vector> // for vector #include <cairo-pdf.h> // for cairo_pdf_surface_set_met... #include <glib-object.h> // for g_object_unref #include "control/jobs/ProgressListener.h" // for ProgressListener #include "model/Document.h" // for Document #include "model/Layer.h" // for Layer #include "model/LinkDestination.h" // for LinkDestination, XojLinkDest #include "model/PageRef.h" // for PageRef #include "model/PageType.h" // for PageType #include "model/XojPage.h" // for XojPage #include "pdf/base/XojPdfPage.h" // for XojPdfPageSPtr, XojPdfPage #include "util/Assert.h" // for xoj_assert #include "util/Util.h" // for npos #include "util/i18n.h" // for _ #include "util/serdesstream.h" // for serdes_stream #include "view/DocumentView.h" // for DocumentView #include "config.h" // for PROJECT_STRING #include "filesystem.h" // for path XojCairoPdfExport::XojCairoPdfExport(Document* doc, ProgressListener* progressListener): doc(doc), progressListener(progressListener) {} XojCairoPdfExport::~XojCairoPdfExport() { if (this->surface != nullptr) { endPdf(); } } /** * Export without background */ void XojCairoPdfExport::setExportBackground(ExportBackgroundType exportBackground) { this->exportBackground = exportBackground; } auto XojCairoPdfExport::startPdf(const fs::path& file, bool exportOutline) -> bool { this->surface = cairo_pdf_surface_create(file.u8string().c_str(), 0, 0); this->cr = cairo_create(surface); #if CAIRO_VERSION >= CAIRO_VERSION_ENCODE(1, 16, 0) cairo_pdf_surface_set_metadata(surface, CAIRO_PDF_METADATA_TITLE, doc->getFilepath().filename().u8string().c_str()); cairo_pdf_surface_set_metadata(surface, CAIRO_PDF_METADATA_CREATOR, PROJECT_STRING); if (exportOutline) { this->populatePdfOutline(); } #endif // Turn on font hint metrics, for consistency with text display in the app cairo_font_options_t* fontOptions = cairo_font_options_create(); cairo_font_options_set_hint_metrics(fontOptions, CAIRO_HINT_METRICS_ON); cairo_set_font_options(cr, fontOptions); cairo_font_options_destroy(fontOptions); return cairo_surface_status(this->surface) == CAIRO_STATUS_SUCCESS; } #if CAIRO_VERSION >= CAIRO_VERSION_ENCODE(1, 16, 0) void XojCairoPdfExport::populatePdfOutline() { auto tocModel = doc->getContentsModel(); if (tocModel == nullptr) return; int idCounter = CAIRO_PDF_OUTLINE_ROOT; std::stack<std::pair<GtkTreeIter, int>> nodeStack; GtkTreeIter firstIter = {0}; if (!gtk_tree_model_get_iter_first(tocModel, &firstIter)) { // Outline is empty, so do nothing. return; } nodeStack.push(std::make_pair(firstIter, idCounter)); while (!nodeStack.empty()) { auto [iter, parentId] = nodeStack.top(); nodeStack.pop(); const int currentId = ++idCounter; XojLinkDest* link = nullptr; gtk_tree_model_get(tocModel, &iter, DOCUMENT_LINKS_COLUMN_LINK, &link, -1); auto dest = link->dest; auto pdfBgPage = dest->getPdfPage(); // Link destination in original background PDF auto pageDest = pdfBgPage == npos ? npos : doc->findPdfPage(pdfBgPage); // Destination in document if (pageDest != npos) { auto linkAttrBuf = serdes_stream<std::ostringstream>(); linkAttrBuf << "page=" << pageDest + 1; if (dest->shouldChangeLeft() && dest->shouldChangeTop()) { linkAttrBuf << " pos=[" << dest->getLeft() << " " << dest->getTop() << "]"; } const auto linkAttr = linkAttrBuf.str(); auto outlineFlags = dest->getExpand() ? CAIRO_PDF_OUTLINE_FLAG_OPEN : 0; cairo_pdf_surface_add_outline(this->surface, parentId, link->dest->getName().data(), linkAttr.data(), static_cast<cairo_pdf_outline_flags_t>(outlineFlags)); } g_object_unref(link); GtkTreeIter childIter; if (gtk_tree_model_iter_children(tocModel, &childIter, &iter)) { nodeStack.push(std::make_pair(childIter, currentId)); } if (gtk_tree_model_iter_next(tocModel, &iter)) { nodeStack.push(std::make_pair(iter, parentId)); } } } #endif bool XojCairoPdfExport::endPdf() { cairo_surface_finish(this->surface); bool success = cairo_surface_status(this->surface) == CAIRO_STATUS_SUCCESS; if (!success) { this->lastError = _("Error while finalizing the PDF Cairo surface"); this->lastError += "\nCairo error: "; this->lastError += cairo_status_to_string(cairo_surface_status(this->surface)); } cairo_destroy(this->cr); this->cr = nullptr; cairo_surface_destroy(this->surface); this->surface = nullptr; return success; } void XojCairoPdfExport::exportPage(size_t page) { PageRef p = doc->getPage(page); cairo_pdf_surface_set_size(this->surface, p->getWidth(), p->getHeight()); DocumentView view; cairo_save(this->cr); // For a better pdf quality, we use a dedicated pdf rendering if (p->getBackgroundType().isPdfPage() && (exportBackground != EXPORT_BACKGROUND_NONE)) { auto pgNo = p->getPdfPageNr(); XojPdfPageSPtr popplerPage = doc->getPdfPage(pgNo); popplerPage->renderForPrinting(cr); } xoj::view::BackgroundFlags flags; flags.showPDF = xoj::view::HIDE_PDF_BACKGROUND; // Already exported (if any) flags.showImage = exportBackground == EXPORT_BACKGROUND_NONE ? xoj::view::HIDE_IMAGE_BACKGROUND : xoj::view::SHOW_IMAGE_BACKGROUND; flags.showRuling = exportBackground <= EXPORT_BACKGROUND_UNRULED ? xoj::view::HIDE_RULING_BACKGROUND : xoj::view::SHOW_RULING_BACKGROUND; if (layerRange) { view.drawLayersOfPage(*layerRange, p, this->cr, true /* dont render eraseable */, flags); } else { view.drawPage(p, this->cr, true /* dont render eraseable */, flags); } // next page cairo_show_page(this->cr); cairo_restore(this->cr); } // export layers one by one to produce as many PDF pages as there are layers. void XojCairoPdfExport::exportPageLayers(size_t page) { PageRef p = doc->getPage(page); // We keep a copy of the layers initial Visible state std::map<Layer*, bool> initialVisibility; for (const auto& layer: *p->getLayers()) { initialVisibility[layer] = layer->isVisible(); layer->setVisible(false); } // We draw as many pages as there are layers. The first page has // only Layer 1 visible, the last has all layers visible. for (const auto& layer: *p->getLayers()) { layer->setVisible(true); exportPage(page); } // We restore the initial visibilities for (const auto& layer: *p->getLayers()) layer->setVisible(initialVisibility[layer]); } auto XojCairoPdfExport::createPdf(fs::path const& file, const PageRangeVector& range, bool progressiveMode) -> bool { if (range.empty()) { this->lastError = _("No pages to export!"); return false; } // Only export the outline if we are exporting the entire document. otherwise, links may point to page numbers // greater than the total number of pages, leading to corrupt pdf files bool outline = range.size() == 1 && range.front().first == 0 && range.front().last >= doc->getPageCount() - 1; if (!startPdf(file, outline)) { this->lastError = _("Failed to initialize PDF Cairo surface"); this->lastError += "\nCairo error: "; this->lastError += cairo_status_to_string(cairo_surface_status(this->surface)); return false; } size_t count = 0; for (const auto& e: range) { xoj_assert(e.last >= e.first); // Ok, when the PageRangeVector was the result of parsing count += e.last - e.first + 1; // Not accurate, if e.last is > doc->getPageCount() } if (this->progressListener) { this->progressListener->setMaximumState(count); } size_t c = 0; for (const auto& e: range) { auto max = std::min(e.last, doc->getPageCount()); // Should be e.last for parsed PageRangeVector for (size_t i = e.first; i <= max; i++) { if (progressiveMode) { exportPageLayers(i); } else { exportPage(i); } if (this->progressListener) { this->progressListener->setCurrentState(++c); } } } return endPdf(); } auto XojCairoPdfExport::createPdf(fs::path const& file, bool progressiveMode) -> bool { if (doc->getPageCount() < 1) { lastError = _("No pages to export!"); return false; } if (!startPdf(file, /* exportOutline */ true)) { this->lastError = _("Failed to initialize PDF Cairo surface"); this->lastError += "\nCairo error: "; this->lastError += cairo_status_to_string(cairo_surface_status(this->surface)); return false; } auto count = doc->getPageCount(); if (this->progressListener) { this->progressListener->setMaximumState(count); } for (decltype(count) i = 0; i < count; i++) { if (progressiveMode) { exportPageLayers(i); } else { exportPage(i); } if (this->progressListener) { this->progressListener->setCurrentState(i + 1); } } return endPdf(); } auto XojCairoPdfExport::getLastError() -> std::string { return lastError; } void XojCairoPdfExport::setLayerRange(const char* rangeStr) { if (rangeStr) { // Use no upper bound for layer indices, as the maximal value can vary between pages layerRange = std::make_unique<LayerRangeVector>(ElementRange::parse(rangeStr, std::numeric_limits<size_t>::max())); } }
10,438
C++
.cpp
230
38.495652
120
0.632972
xournalpp/xournalpp
10,962
791
1,098
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
12,430
Plugin.cpp
xournalpp_xournalpp/src/core/plugin/Plugin.cpp
#include "Plugin.h" #include <algorithm> // for max #include <array> // for array #include <gdk/gdk.h> // for GdkModifierType #include <glib-object.h> // for G_CALLBACK, g_signal_connect #include <glib.h> // for g_key_file_free, g_warning, g_free #include "util/Assert.h" // for xoj_assert #include "util/PathUtil.h" // for toGFilename #include "util/XojMsgBox.h" // for XojMsgBox #include "config-features.h" // for ENABLE_PLUGINS #ifdef ENABLE_PLUGINS #include <utility> // for move, pair #include "gui/toolbarMenubar/ToolMenuHandler.h" // for ToolMenuHandler #include "util/i18n.h" // for _ #include "util/raii/GObjectSPtr.h" #include "config.h" // for PROJECT_VERSION extern "C" { #include <lauxlib.h> // for luaL_Reg, luaL_newstate, luaL_requiref #include <lua.h> // for lua_getglobal, lua_getfield, lua_setf... #include <lualib.h> // for luaL_openlibs } #include "luapi_application.h" // for luaopen_app /* ** these libs are loaded by lua.c and are readily available to any Lua ** program */ constexpr std::array loadedlibs{luaL_Reg{"app", luaopen_app}}; Plugin::Plugin(Control* control, std::string name, fs::path path): control(control), name(std::move(name)), path(std::move(path)) { loadIni(); } auto Plugin::getPluginFromLua(lua_State* lua) -> Plugin* { lua_getfield(lua, LUA_REGISTRYINDEX, "Xournalpp_Plugin"); if (lua_islightuserdata(lua, -1)) { auto* data = static_cast<Plugin*>(lua_touserdata(lua, -1)); lua_pop(lua, 1); return data; } return nullptr; } void Plugin::registerToolbar() { if (!this->valid || !this->enabled) { return; } inInitUi = true; lua_getglobal(lua.get(), "initUi"); if (lua_isfunction(lua.get(), -1) == 1) { if (callFunction("initUi")) { g_message("Plugin \"%s\" UI initialized", name.c_str()); } else { g_warning("Plugin \"%s\" init failed!", name.c_str()); } } else { g_message("Plugin \"%s\" has no UI init", name.c_str()); } inInitUi = false; } size_t Plugin::populateMenuSection(GtkApplicationWindow* win, size_t startId) { if (menuEntries.empty() || !this->enabled) { // No entries - nothing to do return startId; } // The menu should never be populated twice. // If this assert ever fails, do not recreate the GSimpleAction's below xoj_assert(!menuSection); this->menuSection.reset(g_menu_new(), xoj::util::adopt); for (auto& m: menuEntries) { std::string actionName = G_ACTION_NAME_PREFIX; actionName += std::to_string(startId++); m.action.reset(g_simple_action_new(actionName.c_str(), nullptr), xoj::util::adopt); actionName = "win." + actionName; xoj::util::GObjectSPtr<GMenuItem> entry(g_menu_item_new(m.label.c_str(), actionName.c_str()), xoj::util::adopt); g_menu_append_item(menuSection.get(), entry.get()); // This might fail, when the vector reallocates, but then the order of initialisation is violated g_signal_connect( m.action.get(), "activate", G_CALLBACK(+[](GSimpleAction*, GVariant*, MenuEntry* me) { me->plugin->executeMenuEntry(me); }), &m); g_action_map_add_action(G_ACTION_MAP(win), G_ACTION(m.action.get())); if (!m.accelerator.empty()) { const char* accels[2] = {m.accelerator.c_str(), nullptr}; gtk_application_set_accels_for_action(gtk_window_get_application(GTK_WINDOW(win)), actionName.c_str(), accels); } } return startId; } void Plugin::executeMenuEntry(MenuEntry* entry) { callFunction(entry->callback, entry->mode); } auto Plugin::registerMenu(std::string menu, std::string callback, ptrdiff_t mode, std::string accelerator) -> size_t { menuEntries.emplace_back(this, std::move(menu), std::move(callback), mode, std::move(accelerator)); return menuEntries.size() - 1; } void Plugin::registerToolButton(ToolMenuHandler* toolMenuHandler) { if (toolbarButtonEntries.empty() || !this->enabled) { // No entries - nothing to do return; } for (auto&& t: toolbarButtonEntries) { g_message("Add toolbar button with id: %s and icon: %s", t.toolbarId.c_str(), t.iconName.c_str()); toolMenuHandler->addPluginItem(&t); } } void Plugin::executeToolbarButton(ToolbarButtonEntry* entry) { callFunction(entry->callback, entry->mode); } void Plugin::registerToolButton(std::string description, std::string toolbarId, std::string iconName, std::string callback, ptrdiff_t mode) { if (toolbarId == "") { return; } toolbarId = "Plugin::" + toolbarId; // In order to avoid name collisions with built in toolbar id's. toolbarButtonEntries.emplace_back(this, std::move(description), std::move(toolbarId), std::move(iconName), std::move(callback), mode); } auto Plugin::getControl() const -> Control* { return control; } void Plugin::loadIni() { GKeyFile* config = g_key_file_new(); g_key_file_set_list_separator(config, ','); auto filename = path / "plugin.ini"; if (!g_key_file_load_from_file(config, Util::toGFilename(filename).c_str(), G_KEY_FILE_NONE, nullptr)) { g_key_file_free(config); return; } auto LOAD_FROM_INI = [config](auto& target, char const* group, char const* key) { char* value = g_key_file_get_string(config, group, key, nullptr); if (value != nullptr) { target = value; g_free(value); } }; LOAD_FROM_INI(author, "about", "author"); LOAD_FROM_INI(version, "about", "version"); LOAD_FROM_INI(description, "about", "description"); if (version == "<xournalpp>") { version = PROJECT_VERSION; } LOAD_FROM_INI(mainfile, "plugin", "mainfile"); std::string defaultEnabledStr; LOAD_FROM_INI(defaultEnabledStr, "default", "enabled"); defaultEnabled = defaultEnabledStr == "true"; enabled = defaultEnabled; g_key_file_free(config); this->valid = true; } void Plugin::registerXournalppLibs(lua_State* luaPtr) { for (auto const& lib: loadedlibs) { luaL_requiref(luaPtr, lib.name, lib.func, 1); // remove lib lua_pop(luaPtr, 1); } } void Plugin::addPluginToLuaPath() { lua_getglobal(lua.get(), "package"); // get field "path" from table at top of stack (-1) lua_getfield(lua.get(), -1, "path"); // grab path string from top of stack std::string luaPath = lua_tostring(lua.get(), -1); // prepend the path of the current plugin auto curPath = this->path / "?.lua"; std::string combinedPath = curPath.string() + ";" + luaPath; // get rid of the std::string on the stack we just pushed lua_pop(lua.get(), 1); // push the new one lua_pushstring(lua.get(), combinedPath.c_str()); // set the field "path" in table at -2 with value at top of stack lua_setfield(lua.get(), -2, "path"); // get rid of package table from top of stack lua_pop(lua.get(), 1); } void Plugin::loadScript() { if (mainfile.empty()) { this->valid = false; return; } if (mainfile.find("..") != std::string::npos) { g_warning("Plugin \"%s\" contains unsupported path \"%s\"", name.c_str(), mainfile.c_str()); this->valid = false; return; } if (!this->enabled) { return; } // Create Lua state variable lua.reset(luaL_newstate()); // Load Lua libraries luaL_openlibs(lua.get()); // Load but don't run the Lua script auto luafile = path / mainfile; int status = luaL_loadfile(lua.get(), luafile.string().c_str()); if (status != LUA_OK) { const char* errMsg = lua_tostring(lua.get(), -1); XojMsgBox::showPluginMessage(name, errMsg, true); // Error out if file can't be read g_warning("Could not load plugin Lua file. Error: \"%s\", error code: %d (syntax error: %s)", errMsg, status, status == LUA_ERRSYNTAX ? "true" : "false"); this->valid = false; return; } // Register Plugin object to Lua instance lua_pushlightuserdata(lua.get(), this); lua_setfield(lua.get(), LUA_REGISTRYINDEX, "Xournalpp_Plugin"); registerXournalppLibs(lua.get()); addPluginToLuaPath(); // Run the loaded Lua script if (lua_pcall(lua.get(), 0, 0, 0) != LUA_OK) { const char* errMsg = lua_tostring(lua.get(), -1); XojMsgBox::showPluginMessage(name, errMsg, true); g_warning("Could not run plugin Lua file: \"%s\", error: \"%s\"", luafile.string().c_str(), errMsg); this->valid = false; return; } } auto Plugin::callFunction(const std::string& fnc, ptrdiff_t mode) -> bool { lua_getglobal(lua.get(), fnc.c_str()); int numArgs = 0; if (mode != std::numeric_limits<ptrdiff_t>::max()) { lua_pushinteger(lua.get(), mode); numArgs = 1; } // Run the function if (lua_pcall(lua.get(), numArgs, 0, 0)) { const char* errMsg = lua_tostring(lua.get(), -1); XojMsgBox::showPluginMessage(name, errMsg, true); g_warning("Error in Plugin: \"%s\", error: \"%s\"", name.c_str(), errMsg); return false; } return true; } auto Plugin::callFunction(const std::string& fnc, const char* s) -> bool { lua_getglobal(lua.get(), fnc.c_str()); lua_pushstring(lua.get(), s); // Run the function if (lua_pcall(lua.get(), 1, 0, 0)) { const char* errMsg = lua_tostring(lua.get(), -1); XojMsgBox::showPluginMessage(name, errMsg, true); g_warning("Error in Plugin: \"%s\", error: \"%s\"", name.c_str(), errMsg); return false; } return true; } auto Plugin::getName() const -> std::string const& { return name; } auto Plugin::getDescription() const -> std::string const& { return description; } auto Plugin::getAuthor() const -> std::string const& { return author; } auto Plugin::getVersion() const -> std::string const& { return version; } auto Plugin::getPath() const -> fs::path const& { return path; } auto Plugin::isEnabled() const -> bool { return enabled; } void Plugin::setEnabled(bool lEnabled) { this->enabled = lEnabled; } auto Plugin::isDefaultEnabled() const -> bool { return defaultEnabled; } auto Plugin::isInInitUi() const -> bool { return inInitUi; } auto Plugin::isValid() const -> bool { return valid; } #endif
10,587
C++
.cpp
247
36.854251
162
0.630727
xournalpp/xournalpp
10,962
791
1,098
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false