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,633
TouchDisableX11.cpp
xournalpp_xournalpp/src/core/gui/inputdevices/touchdisable/TouchDisableX11.cpp
#include "TouchDisableX11.h" #ifdef X11_ENABLED #include <X11/Xatom.h> // for XA_INTEGER #include <X11/extensions/XI.h> // for XI_TOUCHSCREEN #include <gdk/gdk.h> // for gdk_display_get_default #include <gdk/gdkx.h> // for gdk_x11_display_get_xdisplay #include <glib.h> // for g_message, g_warning, g_error TouchDisableX11::TouchDisableX11() = default; TouchDisableX11::~TouchDisableX11() { if (touchdev) { XCloseDevice(display, touchdev); touchdev = nullptr; } display = nullptr; } void TouchDisableX11::init() { // Get display from GTK display = gdk_x11_display_get_xdisplay(gdk_display_get_default()); if (display == nullptr) { g_error("Could not open X11 display"); return; } touchAtom = XInternAtom(display, "TOUCHSCREEN", true); if (touchAtom == None) { touchAtom = XInternAtom(display, XI_TOUCHSCREEN, false); } int inputDeviceCount = 0; XID touchId = 0; XDeviceInfo* devices = XListInputDevices(display, &inputDeviceCount); for (int i = 0; i < inputDeviceCount; i++) { if (touchId == 0 && devices[i].type == touchAtom) { touchId = devices[i].id; } if (devices[i].id == touchId) { touch = devices + i; } } if (touch == nullptr) { g_warning("Could not find touchscreen device for disabling"); return; } touchdev = XOpenDevice(display, touch->id); if (!touchdev) { g_warning("Failed to open touch device \"%s\"", touch->name); return; } g_message("X11 Touch disabler active for device \"%s\"", touch->name); enabledAtom = XInternAtom(display, "Device Enabled", false); } void TouchDisableX11::enableTouch() { if (!touchdev) { return; } unsigned char value = 1; XChangeDeviceProperty(display, touchdev, enabledAtom, XA_INTEGER, 8, PropModeReplace, &value, 1); g_message("X11 Touch enabled"); } void TouchDisableX11::disableTouch() { if (!touchdev) { return; } unsigned char value = 0; XChangeDeviceProperty(display, touchdev, enabledAtom, XA_INTEGER, 8, PropModeReplace, &value, 1); g_message("X11 Touch disabled"); } #endif
2,264
C++
.cpp
66
28.909091
101
0.634862
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,634
TouchDisableInterface.cpp
xournalpp_xournalpp/src/core/gui/inputdevices/touchdisable/TouchDisableInterface.cpp
#include "TouchDisableInterface.h" TouchDisableInterface::TouchDisableInterface() = default; TouchDisableInterface::~TouchDisableInterface() = default; void TouchDisableInterface::init() {}
193
C++
.cpp
4
46.5
58
0.83871
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,635
Mask.cpp
xournalpp_xournalpp/src/core/view/Mask.cpp
#include "Mask.h" #include <iostream> #include <cairo.h> #include "util/Assert.h" #include "util/Range.h" #include "util/safe_casts.h" // for ceil_cast, floor_cast #include "config-debug.h" using namespace xoj::view; #ifdef DEBUG_MASKS #include <string> namespace { // cairo helper functions, for handling various surface types std::string getSurfaceTypeName(cairo_surface_t*); }; #define IF_DBG_MASKS(f) f #else #define IF_DBG_MASKS(f) #endif Mask::Mask(cairo_surface_t* target, const Range& extent, double zoom, cairo_content_t contentType): xOffset(floor_cast<int>(extent.minX * zoom)), yOffset(floor_cast<int>(extent.minY * zoom)), zoom(zoom) { constructorImpl(target, extent, zoom, contentType); } Mask::Mask(int DPIScaling, const Range& extent, double zoom, cairo_content_t contentType): xOffset(floor_cast<int>(extent.minX * zoom)), yOffset(floor_cast<int>(extent.minY * zoom)), zoom(zoom) { constructorImpl(DPIScaling, extent, zoom, contentType); } template <typename DPIInfoType> class SurfaceCreator {}; template <> class SurfaceCreator<cairo_surface_t*> { public: static constexpr auto create = [](cairo_surface_t* other, cairo_content_t content, int width, int height) -> cairo_surface_t* { return cairo_surface_create_similar(other, content, width, height); }; }; template <> class SurfaceCreator<int> { public: static cairo_surface_t* create(int DPIScaling, cairo_content_t contentType, int width, int height) { cairo_surface_t* surf = cairo_image_surface_create(contentType == CAIRO_CONTENT_ALPHA ? CAIRO_FORMAT_A8 : CAIRO_FORMAT_ARGB32, width * DPIScaling, height * DPIScaling); cairo_surface_set_device_scale(surf, DPIScaling, DPIScaling); return surf; } }; template <typename DPIInfoType> void Mask::constructorImpl(DPIInfoType dpiInfo, const Range& extent, double zoom, cairo_content_t contentType) { xoj_assert(dpiInfo); xoj_assert_message(extent.isValid(), std::string("Invalid range in Mask(): X ") + std::to_string(extent.minX) + " -- " + std::to_string(extent.maxX) + "\n Y " + std::to_string(extent.minY) + " -- " + std::to_string(extent.maxY)); xoj_assert(zoom > 0.0); const int width = ceil_cast<int>(extent.maxX * zoom) - xOffset; const int height = ceil_cast<int>(extent.maxY * zoom) - yOffset; /* * Create the most suitable kind of surface. * * Note that width and height are in device space coordinates (i.e. before DPI scaling). * If `dpiInfo` asks for a device scaling, then the number of pixels in the resulting surface will be multiplied * accordingly, and the scaling is applied to the new surface. */ cairo_surface_t* surf = SurfaceCreator<DPIInfoType>::create(dpiInfo, contentType, width, height); IF_DBG_MASKS({ std::cout << "Creating mask of type: " << getSurfaceTypeName(surf) << std::endl; std::cout << " Its size: " << width << " x " << height << " (in device space)" << std::endl; double x; double y; cairo_surface_get_device_scale(surf, &x, &y); std::cout << " Its DPI scaling: " << x << " x " << y << std::endl; }); this->cr.reset(cairo_create(surf), xoj::util::adopt); cairo_surface_destroy(surf); // surf is now owned by this->cr cairo_translate(this->cr.get(), -xOffset, -yOffset); cairo_scale(this->cr.get(), zoom, zoom); IF_DBG_MASKS({ xoj::util::CairoSaveGuard saveGuard(cr.get()); cairo_set_operator(cr.get(), CAIRO_OPERATOR_OVER); cairo_set_source_rgba(cr.get(), 1.0, 0.0, 0.0, 0.3); cairo_paint(cr.get()); }); } auto Mask::get() -> cairo_t* { return cr.get(); } bool Mask::isInitialized() const { return cr; } void Mask::blitTo(cairo_t* targetCr) const { xoj_assert(isInitialized()); xoj::util::CairoSaveGuard guard(targetCr); cairo_scale(targetCr, 1. / zoom, 1. / zoom); cairo_mask_surface(targetCr, cairo_get_target(const_cast<cairo_t*>(cr.get())), xOffset, yOffset); } void Mask::paintTo(cairo_t* targetCr) const { xoj_assert(isInitialized()); xoj::util::CairoSaveGuard guard(targetCr); cairo_scale(targetCr, 1. / zoom, 1. / zoom); cairo_set_source_surface(targetCr, cairo_get_target(const_cast<cairo_t*>(cr.get())), xOffset, yOffset); cairo_paint(targetCr); } void Mask::wipe() { xoj_assert(isInitialized()); xoj::util::CairoSaveGuard saveGuard(cr.get()); cairo_set_operator(cr.get(), CAIRO_OPERATOR_CLEAR); cairo_paint(cr.get()); IF_DBG_MASKS({ cairo_set_operator(cr.get(), CAIRO_OPERATOR_OVER); cairo_set_source_rgba(cr.get(), 1.0, 0.0, 0.0, 0.3); cairo_paint(cr.get()); }); } void Mask::wipeRange(const Range& rg) { xoj_assert(isInitialized()); xoj::util::CairoSaveGuard saveGuard(cr.get()); cairo_rectangle(cr.get(), rg.minX, rg.minY, rg.getWidth(), rg.getHeight()); cairo_clip(cr.get()); wipe(); } void Mask::reset() { cr.reset(); } #ifdef DEBUG_MASKS namespace { auto getSurfaceTypeName(cairo_surface_t* surf) -> std::string { auto surftype = cairo_surface_get_type(surf); switch (surftype) { // Strings from https://cairographics.org/manual/cairo-cairo-surface-t.html#cairo-surface-type-t case CAIRO_SURFACE_TYPE_IMAGE: return "image"; case CAIRO_SURFACE_TYPE_PDF: return "pdf"; case CAIRO_SURFACE_TYPE_PS: return "ps"; case CAIRO_SURFACE_TYPE_XLIB: return "xlib"; case CAIRO_SURFACE_TYPE_XCB: return "xcb"; case CAIRO_SURFACE_TYPE_GLITZ: return "glitz"; case CAIRO_SURFACE_TYPE_QUARTZ: return "quartz"; case CAIRO_SURFACE_TYPE_WIN32: return "win32"; case CAIRO_SURFACE_TYPE_BEOS: return "beos"; case CAIRO_SURFACE_TYPE_DIRECTFB: return "directfb"; case CAIRO_SURFACE_TYPE_SVG: return "svg"; case CAIRO_SURFACE_TYPE_OS2: return "os2"; case CAIRO_SURFACE_TYPE_WIN32_PRINTING: return "win32 printing surface"; case CAIRO_SURFACE_TYPE_QUARTZ_IMAGE: return "quartz_image"; case CAIRO_SURFACE_TYPE_SCRIPT: return "script"; case CAIRO_SURFACE_TYPE_QT: return "Qt"; case CAIRO_SURFACE_TYPE_RECORDING: return "recording"; case CAIRO_SURFACE_TYPE_VG: return "OpenVG surface"; case CAIRO_SURFACE_TYPE_GL: return "OpenGL"; case CAIRO_SURFACE_TYPE_DRM: return "Direct Render Manager"; case CAIRO_SURFACE_TYPE_TEE: return "'tee' (a multiplexing surface)"; case CAIRO_SURFACE_TYPE_XML: return "XML (for debugging)"; case CAIRO_SURFACE_TYPE_SKIA: return "CAIRO_SURFACE_TYPE_SKIA"; case CAIRO_SURFACE_TYPE_SUBSURFACE: return "subsurface created with cairo_surface_create_for_rectangle()"; case CAIRO_SURFACE_TYPE_COGL: return "Cogl"; default: return "Unknown surface type"; } } }; // namespace #endif
7,441
C++
.cpp
179
34.122905
118
0.626692
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,636
StrokeView.cpp
xournalpp_xournalpp/src/core/view/StrokeView.cpp
#include "StrokeView.h" #include <algorithm> // for max #include <cmath> // for ceil #include <glib.h> // for g_warning #include "model/Stroke.h" // for Stroke, StrokeTool::HIGHLIGHTER #include "util/Assert.h" // for xoj_assert #include "util/Color.h" // for cairo_set_source_rgbi #include "util/Rectangle.h" // for Rectangle #include "view/Mask.h" // for Mask #include "view/View.h" // for Context, OPACITY_NO_AUDIO, view #include "ErasableStrokeView.h" // for ErasableStrokeView #include "StrokeViewHelper.h" #include "filesystem.h" // for path class ErasableStroke; using xoj::util::Rectangle; using namespace xoj::view; StrokeView::StrokeView(const Stroke* s): s(s) {} void StrokeView::draw(const Context& ctx) const { if (s->getPointCount() < 2) { // Should not happen g_warning("View::StrokeView::draw empty stroke..."); return; } const bool highlighter = s->getToolType() == StrokeTool::HIGHLIGHTER; const bool filledHighlighter = highlighter && s->getFill() != -1; const bool drawTranslucent = ctx.fadeOutNonAudio && s->getAudioFilename().empty(); const bool useMask = (!ctx.noColor && filledHighlighter) || drawTranslucent; if (ctx.showCurrentEdition && filledHighlighter && s->getErasable() != nullptr) { // Currently being erased filled highlighter strokes need a special treatment ErasableStrokeView erasableStrokeView(*s->getErasable()); erasableStrokeView.paintFilledHighlighter(ctx.cr); return; } // The mask will be colorblind const bool noColor = ctx.noColor || useMask; xoj::util::CairoSaveGuard saveGuard(ctx.cr); Mask mask; // If not using a mask, draw directly onto the given cairo context cairo_t* cr = ctx.cr; if (useMask) { /** * To avoid visual glitches when different translucent cairo_stroke are painted, * they are painted without colors to a mask which will in turn be blitted (see below) */ /** * Infer the zoom level from context. */ cairo_matrix_t matrix; cairo_get_matrix(ctx.cr, &matrix); // We assume the matrix is diagonal (i.e. only scaling, no rotation) xoj_assert(matrix.xy == 0 && matrix.yx == 0); const double zoom = std::max(matrix.xx, matrix.yy); /** * Create a mask tailored to the stroke's bounding box */ mask = Mask(cairo_get_target(ctx.cr), Range(s->boundingRect()), zoom); cr = mask.get(); } cairo_set_line_join(cr, CAIRO_LINE_JOIN_ROUND); cairo_set_line_cap(cr, CAIRO_LINE_CAP[s->getStrokeCapStyle()]); if (auto fill = s->getFill(); fill != -1) { /** * Paint the filling */ if (noColor) { // Painting on an Alpha-only mask. No need for colors. if (filledHighlighter) { cairo_set_source_rgba(cr, 1, 1, 1, 1); } else { cairo_set_source_rgba(cr, 1, 1, 1, static_cast<double>(fill) / 255.0); } } else { Util::cairo_set_source_rgbi(cr, s->getColor(), static_cast<double>(fill) / 255.0); } cairo_set_operator(cr, useMask ? CAIRO_OPERATOR_SOURCE : CAIRO_OPERATOR_OVER); if (ErasableStroke* erasable = s->getErasable(); erasable != nullptr && ctx.showCurrentEdition) { // don't render erasable for previews ErasableStrokeView erasableStrokeView(*erasable); erasableStrokeView.drawFilling(cr); } else { StrokeViewHelper::pathToCairo(cr, s->getPointVector()); cairo_fill(cr); } } /** * Picking the colors and alpha values, and the operator */ if (noColor) { /** * No color: painting onto an alpha mask. Colors will be applied upon blitting. */ cairo_set_source_rgba(cr, 1, 1, 1, 1); cairo_set_operator(cr, CAIRO_OPERATOR_SOURCE); } else if (highlighter) { /** * Highlighter without filling. */ Util::cairo_set_source_rgbi(cr, s->getColor(), OPACITY_HIGHLIGHTER); cairo_set_operator(cr, CAIRO_OPERATOR_MULTIPLY); } else { /** * Normal pen */ Util::cairo_set_source_rgbi(cr, s->getColor()); cairo_set_operator(cr, CAIRO_OPERATOR_SOURCE); } if (ErasableStroke* erasable = s->getErasable(); erasable != nullptr && ctx.showCurrentEdition) { // don't render erasable for previews ErasableStrokeView erasableStrokeView(*erasable); erasableStrokeView.draw(cr); } else if (s->hasPressure() && !highlighter) { StrokeViewHelper::drawWithPressure(cr, s->getPointVector(), s->getLineStyle()); } else { StrokeViewHelper::drawNoPressure(cr, s->getPointVector(), s->getWidth(), s->getLineStyle()); } if (useMask) { /** * Blit the mask onto the target cairo context. */ /** * Opacity for the mask's content: the base value depends on the tool: * Pen : 1 * Highlighter (no filling): OPACITY_HIGHLIGHTER * Highlighter (filled) : s->getFill() / 255 */ double groupAlpha = highlighter ? (filledHighlighter ? static_cast<double>(s->getFill()) / 255.0 : OPACITY_HIGHLIGHTER) : 1.0; // If the stroke has no audio attached, we draw it (even more) translucent if (drawTranslucent) { groupAlpha *= OPACITY_NO_AUDIO; groupAlpha = std::max(MINIMAL_ALPHA, groupAlpha); } // Blit the mask onto the given cairo context cairo_set_operator(ctx.cr, highlighter ? CAIRO_OPERATOR_MULTIPLY : CAIRO_OPERATOR_OVER); Util::cairo_set_source_rgbi(ctx.cr, s->getColor(), groupAlpha); mask.blitTo(ctx.cr); } }
5,938
C++
.cpp
139
34.697842
117
0.613798
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,637
ElementContainerView.cpp
xournalpp_xournalpp/src/core/view/ElementContainerView.cpp
#include "ElementContainerView.h" #include <memory> // for unique_ptr #include "model/ElementContainer.h" // for ElementContainer #include "View.h" // for ElementView class Element; using namespace xoj::view; ElementContainerView::ElementContainerView(const ElementContainer* container): container(container) {} void ElementContainerView::draw(const Context& ctx) const { container->forEachElement([&ctx](Element* e) { auto elementView = ElementView::createFromElement(e); elementView->draw(ctx); }); }
537
C++
.cpp
13
37.923077
102
0.758221
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,638
ImageView.cpp
xournalpp_xournalpp/src/core/view/ImageView.cpp
#include "ImageView.h" #include <cairo.h> // for cairo_image_surface_get_height, cairo_image... #include "model/Image.h" // for Image #include "view/View.h" // for Context, OPACITY_NO_AUDIO, view using namespace xoj::view; ImageView::ImageView(const Image* image): image(image) {} ImageView::~ImageView() = default; void ImageView::draw(const Context& ctx) const { cairo_t* cr = ctx.cr; cairo_save(cr); cairo_surface_t* img = image->getImage(); int width = cairo_image_surface_get_width(img); int height = cairo_image_surface_get_height(img); cairo_set_operator(cr, CAIRO_OPERATOR_OVER); double xFactor = image->getElementWidth() / width; double yFactor = image->getElementHeight() / height; cairo_scale(cr, xFactor, yFactor); cairo_set_source_surface(cr, img, image->getX() / xFactor, image->getY() / yFactor); // make images translucent when highlighting elements with audio, as they can not have audio if (ctx.fadeOutNonAudio) { cairo_paint_with_alpha(cr, OPACITY_NO_AUDIO); } else { cairo_paint(cr); } cairo_restore(cr); }
1,121
C++
.cpp
26
38.692308
96
0.692237
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,639
SetsquareView.cpp
xournalpp_xournalpp/src/core/view/SetsquareView.cpp
#include "SetsquareView.h" #include <algorithm> // for max, min #include <cmath> // for isnan, sqrt, cos, sin, atan2 #include <iomanip> #include <sstream> #include <utility> // for move #include <glib.h> // for g_error, g_warning #include "model/Setsquare.h" // for Setsquare #include "model/Stroke.h" // for Stroke #include "util/Assert.h" // for xoj_assert #include "util/raii/CairoWrappers.h" // for CairoSaveGuard #include "util/safe_casts.h" // for floor_cast #include "view/Repaintable.h" // for Repaintable #include "view/View.h" // for Context #include "StrokeView.h" // for StrokeView using namespace xoj::view; // all lengths are in centimeter constexpr double FONT_SIZE = .2; constexpr double CIRCLE_RAD = .3; constexpr double TICK_SMALL = .1; constexpr double TICK_LARGE = .2; constexpr double MAX_HOR_POS_VMARKS = 2.5; constexpr int MIN_OFFSET_ANG_MARKS = 2; constexpr double RELATIVE_CIRCLE_POS = .75; constexpr double RELATIVE_MAX_HOR_POS_VMARKS = .6; constexpr double HMARK_POS = 2.; constexpr double MIN_DIST_FROM_HMARK = .2; constexpr int MIN_VMARK_SMALL = 3; constexpr int MIN_VMARK_LARGE = 5; constexpr int OFFSET_FROM_SEMICIRCLE = 2.; constexpr double ZERO_MARK_TICK = .5; constexpr int SKIPPED_HMARKS = 8; constexpr const char* FONT_FAMILY = "Arial"; SetsquareView::SetsquareView(const Setsquare* setsquare, Repaintable* parent, ZoomControl* zoomControl): GeometryToolView(setsquare, parent, zoomControl) { this->registerToPool(setsquare->getViewPool()); } SetsquareView::~SetsquareView() noexcept { this->unregisterFromPool(); }; void SetsquareView::on(FlagDirtyRegionRequest, const Range& rg) { this->parent->flagDirtyRegion(rg); } void SetsquareView::on(UpdateValuesRequest, double h, double rot, cairo_matrix_t m) { xoj_assert_message(h > 0, "Non-positive setsquare height"); height = h; rotation = rot; matrix = m; radius = Setsquare::radiusFromHeight(height); circlePos = height * RELATIVE_CIRCLE_POS; horPosVmarks = std::min(MAX_HOR_POS_VMARKS, radius * RELATIVE_MAX_HOR_POS_VMARKS); minVmark = (std::abs(horPosVmarks - HMARK_POS - TICK_SMALL / 2.) < MIN_DIST_FROM_HMARK - TICK_SMALL / 2.) ? MIN_VMARK_LARGE : MIN_VMARK_SMALL; maxVmark = floor_cast<int>(cathete(radius, horPosVmarks) * 10.0) - OFFSET_FROM_SEMICIRCLE; // The following computation of the angular marks offset is based on experimentation. offset = std::max(MIN_OFFSET_ANG_MARKS, static_cast<int>(256.0 / std::pow(height, 2))); // larger offset for small height if (std ::abs(radius - std::round(radius)) < .2) { // larger offset when semicircle comes close to big hmarks offset = std::max(offset, static_cast<int>(24.0 / radius)); } maxHmark = floor_cast<int>(height * 10.0) - SKIPPED_HMARKS; } void SetsquareView::deleteOn(SetsquareView::FinalizationRequest, const Range& rg) { this->parent->drawAndDeleteToolView(this, rg); } void SetsquareView::drawGeometryTool(cairo_t* cr) const { xoj::util::CairoSaveGuard saveGuard(cr); cairo_scale(cr, CM, CM); cairo_set_line_width(cr, LINE_WIDTH_IN_CM); cairo_set_fill_rule(cr, CAIRO_FILL_RULE_EVEN_ODD); cairo_select_font_face(cr, FONT_FAMILY, CAIRO_FONT_SLANT_NORMAL, CAIRO_FONT_WEIGHT_NORMAL); cairo_set_font_size(cr, FONT_SIZE); // clip to slightly enlarged setsquare for performance reasons const double enlargedHeight = this->height + LINE_WIDTH_IN_CM; cairo_move_to(cr, enlargedHeight, -LINE_WIDTH_IN_CM); cairo_line_to(cr, -enlargedHeight, -LINE_WIDTH_IN_CM); cairo_line_to(cr, .0, enlargedHeight); cairo_close_path(cr); cairo_clip(cr); cairo_set_source_rgb(cr, 1., .0, .0); // red drawOutline(cr); cairo_set_source_rgb(cr, .0, .0, 1.); // blue drawHorizontalMarks(cr); cairo_set_source_rgb(cr, .0, .5, .0); // green drawVerticalMarks(cr); cairo_set_source_rgb(cr, .5, .0, .5); // violet drawAngularMarks(cr); } void SetsquareView::drawDisplays(cairo_t* cr) const { xoj::util::CairoSaveGuard saveGuard(cr); cairo_transform(cr, &matrix); cairo_set_line_width(cr, LINE_WIDTH_IN_CM); cairo_select_font_face(cr, FONT_FAMILY, CAIRO_FONT_SLANT_NORMAL, CAIRO_FONT_WEIGHT_NORMAL); cairo_set_font_size(cr, FONT_SIZE); cairo_set_source_rgb(cr, .0, .5, .5); // turquoise drawRotation(cr); } void SetsquareView::drawOutline(cairo_t* cr) const { xoj::util::CairoSaveGuard saveGuard(cr); cairo_move_to(cr, this->height, .0); cairo_line_to(cr, -this->height, .0); cairo_line_to(cr, .0, this->height); cairo_close_path(cr); cairo_stroke_preserve(cr); cairo_set_source_rgba(cr, .2, .2, .2, .1); // transparent gray cairo_fill(cr); } void SetsquareView::drawRotation(cairo_t* cr) const { xoj::util::CairoSaveGuard saveGuard(cr); // write the angle between hypotenuse and horizontal axis within a small circle std::stringstream ss; ss << std::fixed << std::setprecision(1) << std::abs(std::remainder(deg(this->rotation), 180.)); cairo_move_to(cr, .0, this->circlePos); showTextCenteredAndRotated(cr, ss.str(), -deg(this->rotation)); cairo_move_to(cr, .0, this->circlePos); cairo_new_sub_path(cr); cairo_arc(cr, .0, this->circlePos, CIRCLE_RAD, .0, 2. * M_PI); cairo_stroke(cr); } void SetsquareView::drawAngularMarks(cairo_t* cr) const { xoj::util::CairoSaveGuard saveGuard(cr); // BEGIN: 45 degree marks clipHorizontalStripes(cr); clipVerticalStripes(cr); for (int i: {45, 135}) { const double cs = std::cos(rad(i)); const double si = std::sin(rad(i)); // inside semicircle const double radInsideUpper = this->radius - .3; // 4.2 cairo_move_to(cr, cs, si); cairo_line_to(cr, radInsideUpper * cs, radInsideUpper * si); // outside semicircle const double radOutsideLower = this->radius + .3; // 4.8 const double radOutsideUpper = this->height / std::sqrt(2.) - .3; // 5.4 cairo_move_to(cr, radOutsideLower * cs, radOutsideLower * si); cairo_line_to(cr, radOutsideUpper * cs, radOutsideUpper * si); } cairo_stroke(cr); cairo_reset_clip(cr); // END: 45 degree marks // BEGIN: marks and numbers around semicircle for (int i = 1; i < 180; i++) { // the radius corresponding to the point with angle i on one of the short sides of the setsquare // it is computed using the law of sines const double radCath = this->height * std::sin(rad(45)) / std::sin(rad(i > 90 ? i - 45 : 135 - i)); const double cs = std::cos(rad(i)); const double si = std::sin(rad(i)); const double tick = (i % 5 == 0) ? TICK_LARGE : TICK_SMALL; cairo_move_to(cr, radCath * cs, radCath * si); // move to one of the short sides of the set square if (i % 10 == 0 && i > this->offset && i < 180 - this->offset) { // large tick near short side of set square const double radTickEnd = (i == 90) ? (this->circlePos + .5) : (this->radius + .8); cairo_line_to(cr, radTickEnd * cs, radTickEnd * si); // show increasing numbers near semi-circle const double radInc = this->radius + 0.3; cairo_move_to(cr, radInc * cs, radInc * si); showTextCenteredAndRotated(cr, std::to_string(i), i + 270); // show decreasing numbers a bit further from semi-circle if (i != 90) { const double radDec = this->radius + 0.6; cairo_move_to(cr, radDec * cs, radDec * si); showTextCenteredAndRotated(cr, std::to_string(180 - i), i + 270); } } else { cairo_rel_line_to(cr, -tick * cs, -tick * si); // just a tick near short side of set square } if (i > this->offset && i < 180 - this->offset) { // tick near semi-circle cairo_move_to(cr, this->radius * cs, this->radius * si); cairo_rel_line_to(cr, tick * cs, tick * si); } } cairo_stroke(cr); // END: marks and numbers around semicircle } void SetsquareView::drawVerticalMarks(cairo_t* cr) const { xoj::util::CairoSaveGuard saveGuard(cr); const auto max = this->maxVmark / 10; // number of full centimeters // BEGIN: VERTICAL marks within semicircle clipVerticalStripes(cr); // draw vertical marks for (double i = .5; i <= max; i += .5) { const double x = cathete(this->radius - .25, i); cairo_move_to(cr, -x, i); cairo_line_to(cr, x, i); cairo_stroke(cr); } cairo_reset_clip(cr); // END: VERTICAL marks within circle // BEGIN: vertical measuring marks with numbers for (int i = this->minVmark; i <= this->maxVmark; i++) { const double y = static_cast<double>(i) / 10.; const double tick = (i % 5 == 0) ? TICK_LARGE : TICK_SMALL; // marks and numbers (left and right) for (const double sign: {-1., 1.}) { cairo_move_to(cr, sign * this->horPosVmarks, y); cairo_rel_line_to(cr, -sign * tick, .0); if (i % 10 == 0) { const auto text = std::to_string(i / 10); cairo_rel_move_to(cr, -sign * TICK_SMALL, .0); showTextCenteredAndRotated(cr, text, .0); }; } } cairo_stroke(cr); // END: vertical measuring marks with numbers } void SetsquareView::drawHorizontalMarks(cairo_t* cr) const { xoj::util::CairoSaveGuard saveGuard(cr); const auto max = this->maxVmark / 10; // number of full centimeters // BEGIN: line indicating horizontal 0 for (auto i = 1; i <= max; i++) { cairo_move_to(cr, .0, static_cast<double>(i) - ZERO_MARK_TICK / 2.); cairo_rel_line_to(cr, .0, ZERO_MARK_TICK); } cairo_stroke(cr); // END: line indicating horizontal 0 // BEGIN: measuring marks on top for (int i = -this->maxHmark; i <= this->maxHmark; i++) { const double tick = (i % 5 == 0) ? TICK_LARGE : TICK_SMALL; // draw marks cairo_move_to(cr, static_cast<double>(i) / 10., .0); cairo_rel_line_to(cr, .0, tick); if (i % 10 == 0) { // draw numbers cairo_rel_move_to(cr, .0, FONT_SIZE / 2.); const auto text = std::to_string(std::abs(i / 10)); showTextCenteredAndRotated(cr, text.c_str(), .0); } } cairo_stroke(cr); // END: measuring marks on top } void SetsquareView::clipVerticalStripes(cairo_t* cr) const { // y-coordinate of the highest vertical mark const auto y = static_cast<double>(this->maxVmark) / 10.; cairo_rectangle(cr, -this->horPosVmarks - .25, .0, .75, y + .5); // left stripe cairo_rectangle(cr, this->horPosVmarks - .5, .0, .75, y + .5); // right stripe cairo_rectangle(cr, -.25, .0, .5, y + .5); // middle stripe cairo_rectangle(cr, -this->height, .0, 2. * this->height, this->height); // clip to the outside cairo_clip(cr); } void SetsquareView::clipHorizontalStripes(cairo_t* cr) const { for (auto i = .5; i <= static_cast<double>(this->maxVmark) / 10.0; i += .5) { double x = cathete(this->radius - .25, i); cairo_rectangle(cr, -x, i - .15, 2. * x, .3); } cairo_rectangle(cr, -this->height, .0, 2. * this->height, this->height); // clip to the outside cairo_clip(cr); }
11,606
C++
.cpp
247
40.813765
114
0.627862
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,640
CompassView.cpp
xournalpp_xournalpp/src/core/view/CompassView.cpp
#include "CompassView.h" #include <algorithm> // for max, min #include <cmath> // for isnan, sqrt, cos, sin, atan2 #include <iomanip> #include <sstream> #include <utility> // for move #include <glib.h> // for g_error, g_warning #include "model/Compass.h" // for Compass #include "model/Stroke.h" // for Stroke #include "util/Assert.h" // for xoj_assert #include "util/raii/CairoWrappers.h" // for CairoSaveGuard #include "util/safe_casts.h" // for round_cast #include "view/Repaintable.h" // for Repaintable #include "view/View.h" // for Context #include "StrokeView.h" // for StrokeView using namespace xoj::view; // all lengths are in centimeter constexpr double FONT_SIZE = .2; constexpr double CIRCLE_RAD = .3; constexpr double TICK_SMALL = .1; constexpr double TICK_LARGE = .2; constexpr double RELATIVE_CIRCLE_POS = .8; constexpr double RELATIVE_ANGULAR_CAPTION_POS = .3; constexpr double OFFSET_CIRCLE_POS = .4; constexpr const char* FONT_FAMILY = "Arial"; CompassView::CompassView(const Compass* compass, Repaintable* parent, ZoomControl* zoomControl): GeometryToolView(compass, parent, zoomControl) { this->registerToPool(compass->getViewPool()); } CompassView::~CompassView() noexcept { this->unregisterFromPool(); }; void CompassView::on(FlagDirtyRegionRequest, const Range& rg) { this->parent->flagDirtyRegion(rg); } void CompassView::on(UpdateValuesRequest, double h, double rot, cairo_matrix_t m) { xoj_assert_message(h > 0, "Non-positive compass height"); height = h; rotation = rot; matrix = m; circlePos = height * RELATIVE_CIRCLE_POS - OFFSET_CIRCLE_POS; angularCaptionPos = height * RELATIVE_ANGULAR_CAPTION_POS; maxHmark = round_cast<int>(height * 10.0); drawRotationDisplay = height >= 2.; drawRadialCaption = height >= 1.5; angularOffset = (height >= 2.) ? 1 : (height >= 1.2) ? 2 : (height >= 0.8) ? 5 : 10; angularCaptionOffset = (height >= 3.) ? 30 : (height >= 1.5) ? 45 : (height >= 1.) ? 90 : 360; } void CompassView::deleteOn(CompassView::FinalizationRequest, const Range& rg) { this->parent->drawAndDeleteToolView(this, rg); } void CompassView::drawGeometryTool(cairo_t* cr) const { xoj::util::CairoSaveGuard saveGuard(cr); cairo_scale(cr, CM, CM); cairo_set_line_width(cr, LINE_WIDTH_IN_CM); cairo_set_fill_rule(cr, CAIRO_FILL_RULE_EVEN_ODD); cairo_select_font_face(cr, FONT_FAMILY, CAIRO_FONT_SLANT_NORMAL, CAIRO_FONT_WEIGHT_NORMAL); cairo_set_font_size(cr, FONT_SIZE); cairo_set_source_rgb(cr, 1, 0, 0); // red drawOutline(cr); cairo_set_source_rgb(cr, .0, .0, 1.); // blue drawHorizontalMarks(cr); cairo_set_source_rgb(cr, .5, 0, .5); // violet drawAngularMarks(cr); } void CompassView::drawDisplays(cairo_t* cr) const { xoj::util::CairoSaveGuard saveGuard(cr); cairo_transform(cr, &matrix); cairo_set_line_width(cr, LINE_WIDTH_IN_CM); cairo_select_font_face(cr, FONT_FAMILY, CAIRO_FONT_SLANT_NORMAL, CAIRO_FONT_WEIGHT_NORMAL); cairo_set_font_size(cr, FONT_SIZE); cairo_set_source_rgb(cr, 0, .5, .5); // turquoise drawRotation(cr); } void CompassView::drawOutline(cairo_t* cr) const { xoj::util::CairoSaveGuard saveGuard(cr); cairo_move_to(cr, .0, .0); cairo_arc(cr, .0, .0, this->height, .0, 2. * M_PI); cairo_stroke_preserve(cr); cairo_set_source_rgba(cr, .2, .2, .2, .1); // transparent gray cairo_fill(cr); } void CompassView::drawRotation(cairo_t* cr) const { if (!drawRotationDisplay) { return; } xoj::util::CairoSaveGuard saveGuard(cr); // write the angle within a small circle std::stringstream ss; ss << std::fixed << std::setprecision(1) << std::abs(std::remainder(deg(this->rotation), 180.)); cairo_move_to(cr, .0, -this->circlePos); showTextCenteredAndRotated(cr, ss.str(), -deg(this->rotation)); cairo_move_to(cr, .0, -this->circlePos); cairo_new_sub_path(cr); cairo_arc(cr, .0, -this->circlePos, CIRCLE_RAD, .0, 2. * M_PI); cairo_stroke(cr); } void CompassView::drawAngularMarks(cairo_t* cr) const { xoj::util::CairoSaveGuard saveGuard(cr); for (int i = angularOffset; i < 360; i += angularOffset) { const double cs = std::cos(rad(i)); const double si = std::sin(rad(i)); const double tick = (i % 5 == 0) ? TICK_LARGE : TICK_SMALL; cairo_move_to(cr, this->height * cs, this->height * si); if (i % angularCaptionOffset == 0) { const double radTickEnd = (i == 270) ? (this->circlePos + 1.5 * CIRCLE_RAD) : (angularCaptionPos + 0.3); cairo_line_to(cr, radTickEnd * cs, radTickEnd * si); cairo_move_to(cr, angularCaptionPos * cs, angularCaptionPos * si); showTextCenteredAndRotated(cr, std::to_string(360 - i), i + 90); } else { cairo_rel_line_to(cr, -tick * cs, -tick * si); } } cairo_stroke(cr); } void CompassView::drawHorizontalMarks(cairo_t* cr) const { xoj::util::CairoSaveGuard saveGuard(cr); // BEGIN: radial measuring marks for (int i = 0; i <= this->maxHmark; i++) { const double tick = (i % 5 == 0) ? TICK_LARGE : TICK_SMALL; // draw marks cairo_move_to(cr, static_cast<double>(i) / 10.0, .0); cairo_rel_line_to(cr, .0, tick); if (i % 10 == 0 && drawRadialCaption) { // draw numbers cairo_rel_move_to(cr, .0, FONT_SIZE / 2.); const auto text = std::to_string(std::abs(i / 10)); showTextCenteredAndRotated(cr, text.c_str(), .0); } } cairo_stroke(cr); // END: radial measuring marks }
5,716
C++
.cpp
129
39.472868
116
0.648741
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,641
GeometryToolView.cpp
xournalpp_xournalpp/src/core/view/GeometryToolView.cpp
#include "GeometryToolView.h" #include "control/zoom/ZoomControl.h" #include "model/GeometryTool.h" // for GeometryTool #include "model/Stroke.h" // for Stroke #include "util/raii/CairoWrappers.h" // for CairoSaveGuard #include "view/Repaintable.h" // for Repaintable #include "view/View.h" // for Context #include "StrokeView.h" // for StrokeView using namespace xoj::view; GeometryToolView::GeometryToolView(const GeometryTool* geometryTool, Repaintable* parent, ZoomControl* zoomControl): ToolView(parent), geometryTool(geometryTool), zoomControl(zoomControl) { zoomControl->addZoomListener(this); } GeometryToolView::~GeometryToolView() { zoomControl->removeZoomListener(this); } void GeometryToolView::draw(cairo_t* cr) const { xoj::util::CairoSaveGuard saveGuard(cr); cairo_save(cr); if (!mask.isInitialized()) { // Initialize the mask on first call, when the geometry tool changes size and when zooming mask = createMask(cr); this->drawGeometryTool(mask.get()); } cairo_translate(cr, geometryTool->getTranslationX(), geometryTool->getTranslationY()); cairo_rotate(cr, geometryTool->getRotation()); mask.paintTo(cr); cairo_restore(cr); this->drawDisplays(cr); this->drawTemporaryStroke(cr); } bool GeometryToolView::isViewOf(const OverlayBase* overlay) const { return overlay == this->geometryTool; } void GeometryToolView::drawTemporaryStroke(cairo_t* cr) const { if (geometryTool->getStroke()) { auto context = xoj::view::Context::createDefault(cr); xoj::view::StrokeView strokeView(geometryTool->getStroke()); strokeView.draw(context); } } auto GeometryToolView::createMask(cairo_t* targetCr) const -> Mask { const double zoom = this->parent->getZoom(); Range rg = geometryTool->getToolRange(false); return Mask(cairo_get_target(targetCr), rg, zoom, CAIRO_CONTENT_COLOR_ALPHA); } void GeometryToolView::on(ResetMaskRequest) { mask.reset(); } void GeometryToolView::showTextCenteredAndRotated(cairo_t* cr, const std::string& text, double angle) const { xoj::util::CairoSaveGuard saveGuard(cr); cairo_text_extents_t te; cairo_text_extents(cr, text.c_str(), &te); const double dx = te.x_bearing + te.width / 2.0; const double dy = te.y_bearing + te.height / 2.0; cairo_rotate(cr, rad(angle)); cairo_rel_move_to(cr, -dx, -dy); cairo_text_path(cr, text.c_str()); } void GeometryToolView::zoomChanged() { // If zooming in, the mask needs redrawing. Otherwise it gets blurry. mask.reset(); }
2,611
C++
.cpp
57
41.754386
116
0.714173
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,642
ElementView.cpp
xournalpp_xournalpp/src/core/view/ElementView.cpp
#include <memory> // for make_unique, unique_ptr #include "model/Element.h" // for Element, ELEMENT_IMAGE, ELEMENT_STROKE #include "model/Image.h" // for Image #include "model/Stroke.h" // for Stroke #include "model/TexImage.h" // for TexImage #include "model/Text.h" // for Text #include "util/Assert.h" // for xoj_assert #include "ImageView.h" // for ImageView #include "StrokeView.h" // for StrokeView #include "TexImageView.h" // for TexImageView #include "TextView.h" // for TextView #include "View.h" // for ElementView, view using namespace xoj::view; auto ElementView::createFromElement(const Element* e) -> std::unique_ptr<ElementView> { switch (e->getType()) { case ELEMENT_STROKE: return std::make_unique<StrokeView>(dynamic_cast<const Stroke*>(e)); case ELEMENT_TEXT: return std::make_unique<TextView>(dynamic_cast<const Text*>(e)); case ELEMENT_IMAGE: return std::make_unique<ImageView>(dynamic_cast<const Image*>(e)); case ELEMENT_TEXIMAGE: return std::make_unique<TexImageView>(dynamic_cast<const TexImage*>(e)); default: xoj_assert_message(false, "ElementView::getFromElement: Unknown element type!"); return nullptr; } }
1,304
C++
.cpp
28
41.142857
92
0.66195
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,643
TextView.cpp
xournalpp_xournalpp/src/core/view/TextView.cpp
#include "TextView.h" #include <algorithm> // for max #include <cstddef> // for size_t #include "model/Text.h" // for Text #include "util/Color.h" // for cairo_set_source_rgbi #include "util/StringUtils.h" // for StringUtils #include "util/raii/CairoWrappers.h" #include "util/raii/GObjectSPtr.h" #include "view/View.h" // for Context, OPACITY_NO_AUDIO, view #include "filesystem.h" // for path using namespace xoj::view; TextView::TextView(const Text* text): text(text) {} TextView::~TextView() = default; auto TextView::initPango(cairo_t* cr, const Text* t) -> xoj::util::GObjectSPtr<PangoLayout> { auto layout = t->createPangoLayout(); pango_cairo_update_layout(cr, layout.get()); pango_context_set_matrix(pango_layout_get_context(layout.get()), nullptr); return layout; } void TextView::draw(const Context& ctx) const { if (text->isInEditing()) { // The drawing is handled by gui/TextEditor return; } xoj::util::CairoSaveGuard saveGuard(ctx.cr); // make elements without audio translucent when highlighting elements with audio if (ctx.fadeOutNonAudio && text->getAudioFilename().empty()) { cairo_set_operator(ctx.cr, CAIRO_OPERATOR_OVER); Util::cairo_set_source_rgbi(ctx.cr, text->getColor(), OPACITY_NO_AUDIO); } else { cairo_set_operator(ctx.cr, CAIRO_OPERATOR_SOURCE); Util::cairo_set_source_rgbi(ctx.cr, text->getColor()); } cairo_translate(ctx.cr, text->getX(), text->getY()); auto layout = initPango(ctx.cr, text); const std::string& content = text->getText(); pango_layout_set_text(layout.get(), content.c_str(), static_cast<int>(content.length())); pango_cairo_show_layout(ctx.cr, layout.get()); }
1,776
C++
.cpp
39
41.307692
93
0.680209
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,644
DocumentView.cpp
xournalpp_xournalpp/src/core/view/DocumentView.cpp
#include "DocumentView.h" #include <memory> // for __shared_ptr_access, uni... #include <vector> // for vector #include <glib.h> // for g_message #include "model/Layer.h" // for Layer #include "model/XojPage.h" // for XojPage #include "view/DebugShowRepaintBounds.h" // for IF_DEBUG_REPAINT #include "view/View.h" // for EditionTreatment, NORMAL... #include "view/background/BackgroundView.h" // for BackgroundFlags, Backgro... #include "LayerView.h" // for LayerView /** * Mark stroke with Audio */ void DocumentView::setMarkAudioStroke(bool markAudioStroke) { this->markAudioStroke = markAudioStroke; } void DocumentView::setPdfCache(PdfCache* cache) { pdfCache = cache; } /** * Drawing first step * @param page The page to draw * @param cr Draw to this context * @param dontRenderEditingStroke false to draw currently drawing stroke */ void DocumentView::initDrawing(PageRef page, cairo_t* cr, bool dontRenderEditingStroke) { this->cr = cr; this->page = page; this->dontRenderEditingStroke = dontRenderEditingStroke; } /** * Last step in drawing */ void DocumentView::finializeDrawing() { IF_DEBUG_REPAINT({ double minX; double maxX; double minY; double maxY; cairo_clip_extents(cr, &minX, &minY, &maxX, &maxY); if (minX > 1 || minY > 1 || maxX < page->getWidth() - 1 || maxY < page->getHeight() - 1) { g_message("DBG:rerender area: %6.2f < x < %6.2f ; %6.2f < y < %6.2f", minX, maxX, minY, maxY); cairo_set_source_rgb(cr, 1, 0, 0); cairo_set_line_width(cr, 1); cairo_rectangle(cr, minX + 3, minY + 3, maxX - minX - 6, maxY - minY - 6); cairo_stroke(cr); } else { g_message("DBG:rerender complete"); } }); this->page = nullptr; this->cr = nullptr; } /** * Draw the background */ void DocumentView::drawBackground(xoj::view::BackgroundFlags bgFlags) const { auto bgView = xoj::view::BackgroundView::createForPage(page, bgFlags, pdfCache); bgView->draw(cr); } void DocumentView::drawPage(PageRef page, cairo_t* cr, bool dontRenderEditingStroke, xoj::view::BackgroundFlags flags) { initDrawing(page, cr, dontRenderEditingStroke); drawBackground(flags); xoj::view::Context context{cr, (xoj::view::NonAudioTreatment)this->markAudioStroke, (xoj::view::EditionTreatment) !this->dontRenderEditingStroke, xoj::view::NORMAL_COLOR}; for (Layer* layer: *page->getLayers()) { if (layer->isVisible()) { xoj::view::LayerView layerView(layer); layerView.draw(context); } } finializeDrawing(); } void DocumentView::drawLayersOfPage(const LayerRangeVector& layerRange, PageRef page, cairo_t* cr, bool dontRenderEditingStroke, xoj::view::BackgroundFlags flags) { initDrawing(page, cr, dontRenderEditingStroke); drawBackground(flags); size_t layerCount = page->getLayerCount(); std::vector<bool> visible(layerCount, false); for (LayerRangeEntry e: layerRange) { auto last = e.last; if (last >= layerCount) { last = layerCount - 1; } for (auto x = e.first; x <= last; x++) { visible[x] = true; } } xoj::view::Context context{cr, (xoj::view::NonAudioTreatment)this->markAudioStroke, (xoj::view::EditionTreatment) !this->dontRenderEditingStroke, xoj::view::NORMAL_COLOR}; auto visibilityIt = visible.begin(); for (Layer* l: *page->getLayers()) { if (!*(visibilityIt++)) { continue; } xoj::view::LayerView layerView(l); layerView.draw(context); } finializeDrawing(); }
3,835
C++
.cpp
96
33.552083
120
0.630984
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,645
StrokeViewHelper.cpp
xournalpp_xournalpp/src/core/view/StrokeViewHelper.cpp
#include "StrokeViewHelper.h" #include "model/LineStyle.h" #include "model/Point.h" #include "util/Assert.h" #include "util/LoopUtil.h" #include "util/PairView.h" #include "util/Util.h" // for cairo_set_dash_from_vector void xoj::view::StrokeViewHelper::pathToCairo(cairo_t* cr, const std::vector<Point>& pts) { for_first_then_each( pts, [cr](auto const& first) { cairo_move_to(cr, first.x, first.y); }, [cr](auto const& other) { cairo_line_to(cr, other.x, other.y); }); } /** * No pressure sensitivity, one line is drawn */ void xoj::view::StrokeViewHelper::drawNoPressure(cairo_t* cr, const std::vector<Point>& pts, const double strokeWidth, const LineStyle& lineStyle, double dashOffset) { cairo_set_line_width(cr, strokeWidth); const auto& dashes = lineStyle.getDashes(); Util::cairo_set_dash_from_vector(cr, dashes, dashOffset); pathToCairo(cr, pts); cairo_stroke(cr); } /** * Draw a stroke with pressure, for this multiple lines with different widths needs to be drawn */ double xoj::view::StrokeViewHelper::drawWithPressure(cairo_t* cr, const std::vector<Point>& pts, const LineStyle& lineStyle, double dashOffset) { const auto& dashes = lineStyle.getDashes(); /* * Because the width varies, we need to call cairo_stroke() once per segment */ auto drawSegment = [cr](const Point& p, const Point& q) { xoj_assert(p.z > 0.0); cairo_set_line_width(cr, p.z); cairo_move_to(cr, p.x, p.y); cairo_line_to(cr, q.x, q.y); cairo_stroke(cr); }; if (!dashes.empty()) { for (const auto& [p, q]: PairView(pts)) { Util::cairo_set_dash_from_vector(cr, dashes, dashOffset); dashOffset += p.lineLengthTo(q); drawSegment(p, q); } } else { cairo_set_dash(cr, nullptr, 0, 0.0); for (const auto& [p, q]: PairView(pts)) { drawSegment(p, q); } } return dashOffset; }
2,083
C++
.cpp
53
32.037736
118
0.611771
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,646
TexImageView.cpp
xournalpp_xournalpp/src/core/view/TexImageView.cpp
#include "TexImageView.h" #include <string> // for string #include <cairo.h> // for cairo_paint_with_alpha, cairo_scale #include <glib.h> // for g_warning #include <poppler.h> // for PopplerPage, PopplerDocument, g_clear_... #include "model/TexImage.h" // for TexImage #include "view/View.h" // for Context, OPACITY_NO_AUDIO, view using namespace xoj::view; TexImageView::TexImageView(const TexImage* texImage): texImage(texImage) {} TexImageView::~TexImageView() = default; void TexImageView::draw(const Context& ctx) const { cairo_t* cr = ctx.cr; cairo_save(cr); PopplerDocument* pdf = texImage->getPdf(); cairo_surface_t* img = texImage->getImage(); if (pdf != nullptr) { if (poppler_document_get_n_pages(pdf) < 1) { g_warning("Got latex PDF without pages!: %s", texImage->getText().c_str()); return; } PopplerPage* page = poppler_document_get_page(pdf, 0); double pageWidth = 0; double pageHeight = 0; poppler_page_get_size(page, &pageWidth, &pageHeight); double xFactor = texImage->getElementWidth() / pageWidth; double yFactor = texImage->getElementHeight() / pageHeight; cairo_set_operator(cr, CAIRO_OPERATOR_OVER); cairo_translate(cr, texImage->getX(), texImage->getY()); cairo_scale(cr, xFactor, yFactor); // Make TeX images translucent when highlighting audio strokes as they can not have audio if (ctx.fadeOutNonAudio) { /** * Switch to a temporary surface, render the page, then switch back. * This sets the current pattern to the temporary surface. */ cairo_push_group(cr); poppler_page_render(page, cr); cairo_pop_group_to_source(cr); // paint the temporary surface with opacity level cairo_paint_with_alpha(cr, OPACITY_NO_AUDIO); } else { poppler_page_render(page, cr); } g_clear_object(&page); } else if (img != nullptr) { int width = cairo_image_surface_get_width(img); int height = cairo_image_surface_get_height(img); cairo_set_operator(cr, CAIRO_OPERATOR_OVER); double xFactor = texImage->getElementWidth() / width; double yFactor = texImage->getElementHeight() / height; cairo_scale(cr, xFactor, yFactor); cairo_set_source_surface(cr, img, texImage->getX() / xFactor, texImage->getY() / yFactor); // Make TeX images translucent when highlighting audio strokes as they can not have audio if (ctx.fadeOutNonAudio) { cairo_paint_with_alpha(cr, OPACITY_NO_AUDIO); } else { cairo_paint(cr); } } cairo_restore(cr); }
2,816
C++
.cpp
61
37.934426
98
0.626418
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,647
LayerView.cpp
xournalpp_xournalpp/src/core/view/LayerView.cpp
#include "LayerView.h" #include <memory> // for unique_ptr #include <cairo.h> // for cairo_clip_extents, cairo_rectangle #include <glib.h> // for g_message #include "model/Element.h" // for Element #include "model/Layer.h" // for Layer #include "DebugShowRepaintBounds.h" // for IF_DEBUG_REPAINT #include "View.h" // for Context, ElementView using namespace xoj::view; LayerView::LayerView(const Layer* layer): layer(layer) {} const Layer* LayerView::getLayer() const { return layer; } void LayerView::draw(const Context& ctx) const { IF_DEBUG_REPAINT(int drawn = 0; int notDrawn = 0;); // Get the bounds of the mask, in page coordinates double minX; double maxX; double minY; double maxY; cairo_clip_extents(ctx.cr, &minX, &minY, &maxX, &maxY); for (auto const& e: layer->getElements()) { IF_DEBUG_REPAINT({ auto cr = ctx.cr; cairo_set_operator(cr, CAIRO_OPERATOR_SOURCE); cairo_set_source_rgb(cr, 0, 1, 0); cairo_set_line_width(cr, 1); cairo_rectangle(cr, e->getX(), e->getY(), e->getElementWidth(), e->getElementHeight()); cairo_stroke(cr); }); if (e->intersectsArea(minX, minY, maxX - minX, maxY - minY)) { ElementView::createFromElement(e.get())->draw(ctx); IF_DEBUG_REPAINT(drawn++;); } IF_DEBUG_REPAINT(else { notDrawn++; }); } IF_DEBUG_REPAINT(g_message("DBG:LayerView::draw: draw %i / not draw %i", drawn, notDrawn);); }
1,546
C++
.cpp
36
36.722222
99
0.624166
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,648
ErasableStrokeView.cpp
xournalpp_xournalpp/src/core/view/ErasableStrokeView.cpp
#include "ErasableStrokeView.h" #include <cmath> // for ceil #include <iosfwd> // for ptrdiff_t #include <iterator> // for next #include <memory> // for allocator_traits<>::value_type #include <vector> // for vector #include "model/LineStyle.h" // for LineStyle #include "model/PathParameter.h" // for PathParameter #include "model/Point.h" // for Point #include "model/Stroke.h" // for Stroke, StrokeTool::HIGHLIG... #include "model/eraser/ErasableStroke.h" // for ErasableStroke, ErasableStr... #include "util/Assert.h" // for xoj_assert #include "util/Color.h" // for cairo_set_source_rgbi #include "util/Interval.h" // for Interval #include "util/Rectangle.h" // for Rectangle #include "util/Util.h" // for cairo_set_dash_from_vector #include "Mask.h" // for Mask #include "StrokeView.h" // for StrokeView, StrokeView::CAI... #include "config-debug.h" // for DEBUG_ERASABLE_STROKE_BOXES using xoj::util::Rectangle; using namespace xoj::view; ErasableStrokeView::ErasableStrokeView(const ErasableStroke& erasableStroke): erasableStroke(erasableStroke) {} void ErasableStrokeView::draw(cairo_t* cr) const { std::vector<ErasableStroke::SubSection> sections = erasableStroke.getRemainingSubSectionsVector(); if (sections.empty()) { return; } const Stroke& stroke = this->erasableStroke.stroke; const auto& dashes = stroke.getLineStyle().getDashes(); const std::vector<Point>& data = stroke.getPointVector(); xoj::util::CairoSaveGuard guard(cr); if (stroke.hasPressure()) { double dashOffset = 0; for (const auto& interval: sections) { Point p = stroke.getPoint(interval.min); cairo_set_line_width(cr, p.z); cairo_move_to(cr, p.x, p.y); const Point* lastPoint = &p; auto endIt = std::next(data.cbegin(), (std::ptrdiff_t)interval.max.index + 1); for (auto it = std::next(data.cbegin(), (std::ptrdiff_t)interval.min.index + 1); it != endIt; ++it) { if (!dashes.empty()) { Util::cairo_set_dash_from_vector(cr, dashes, dashOffset); dashOffset += lastPoint->lineLengthTo(*it); lastPoint = &(*it); } cairo_line_to(cr, it->x, it->y); cairo_stroke(cr); cairo_set_line_width(cr, it->z); cairo_move_to(cr, it->x, it->y); } if (!dashes.empty()) { Util::cairo_set_dash_from_vector(cr, dashes, dashOffset); } Point q = stroke.getPoint(interval.max); cairo_line_to(cr, q.x, q.y); cairo_stroke(cr); } } else { cairo_set_line_width(cr, stroke.getWidth()); Util::cairo_set_dash_from_vector(cr, dashes, 0); bool mergeFirstAndLast = this->erasableStroke.isClosedStroke() && stroke.getToolType() == StrokeTool::HIGHLIGHTER && sections.size() >= 2 && sections.front().min == PathParameter(0, 0.0) && sections.back().max == PathParameter(data.size() - 2, 1.0); auto sectionIt = sections.cbegin(); auto sectionEndIt = sections.cend(); if (mergeFirstAndLast) { /** * Draw the first and last section as one */ const ErasableStroke::SubSection& first = sections.front(); const ErasableStroke::SubSection& last = sections.back(); Point p = stroke.getPoint(last.min); cairo_move_to(cr, p.x, p.y); auto endIt = data.cend(); for (auto it = std::next(data.cbegin(), (std::ptrdiff_t)last.min.index + 1); it != endIt; ++it) { cairo_line_to(cr, it->x, it->y); } endIt = std::next(data.cbegin(), (std::ptrdiff_t)first.max.index + 1); for (auto it = data.cbegin(); it != endIt; ++it) { cairo_line_to(cr, it->x, it->y); } Point q = stroke.getPoint(first.max); cairo_line_to(cr, q.x, q.y); cairo_stroke(cr); // Avoid drawing those sections again ++sectionIt; --sectionEndIt; } for (; sectionIt != sectionEndIt; ++sectionIt) { Point p = stroke.getPoint(sectionIt->min); cairo_move_to(cr, p.x, p.y); auto endIt = std::next(data.cbegin(), (std::ptrdiff_t)sectionIt->max.index + 1); for (auto it = std::next(data.cbegin(), (std::ptrdiff_t)sectionIt->min.index + 1); it != endIt; ++it) { cairo_line_to(cr, it->x, it->y); } Point q = stroke.getPoint(sectionIt->max); cairo_line_to(cr, q.x, q.y); cairo_stroke(cr); } } #ifdef DEBUG_ERASABLE_STROKE_BOXES if (!this->erasableStroke.debugMask.isInitialized()) { cairo_matrix_t matrix; cairo_get_matrix(cr, &matrix); Range extents(0, 0, stroke.getElementWidth(), stroke.getElementHeight()); extents.addPadding(5 * stroke.getWidth()); erasableStroke.debugMask = Mask(cairo_get_target(cr), extents, matrix.xx, CAIRO_CONTENT_COLOR_ALPHA); cairo_set_line_width(this->erasableStroke.debugMask.get(), 2); } else { cairo_set_operator(cr, CAIRO_OPERATOR_OVER); this->erasableStroke.debugMask.paintTo(cr); } #endif } void ErasableStrokeView::drawFilling(cairo_t* cr) const { std::vector<ErasableStroke::SubSection> sections = erasableStroke.getRemainingSubSectionsVector(); if (sections.empty()) { return; } const Stroke& stroke = this->erasableStroke.stroke; const std::vector<Point>& data = stroke.getPointVector(); bool mergeFirstAndLast = this->erasableStroke.isClosedStroke() && sections.size() >= 2 && sections.front().min == PathParameter(0, 0.0) && sections.back().max == PathParameter(data.size() - 2, 1.0); auto sectionIt = sections.cbegin(); auto sectionEndIt = sections.cend(); if (mergeFirstAndLast) { /** * Draw the first and last sections as one */ const ErasableStroke::SubSection& first = sections.front(); const ErasableStroke::SubSection& last = sections.back(); Point p = stroke.getPoint(last.min); cairo_move_to(cr, p.x, p.y); auto endIt = data.cend(); for (auto it = std::next(data.cbegin(), (std::ptrdiff_t)last.min.index + 1); it != endIt; ++it) { cairo_line_to(cr, it->x, it->y); } endIt = std::next(data.cbegin(), (std::ptrdiff_t)first.max.index + 1); for (auto it = data.cbegin(); it != endIt; ++it) { cairo_line_to(cr, it->x, it->y); } Point q = stroke.getPoint(first.max); cairo_line_to(cr, q.x, q.y); cairo_fill(cr); // Avoid drawing those sections again ++sectionIt; --sectionEndIt; } for (; sectionIt != sectionEndIt; ++sectionIt) { Point p = stroke.getPoint(sectionIt->min); cairo_move_to(cr, p.x, p.y); auto endIt = std::next(data.cbegin(), (std::ptrdiff_t)sectionIt->max.index + 1); for (auto it = std::next(data.cbegin(), (std::ptrdiff_t)sectionIt->min.index + 1); it != endIt; ++it) { cairo_line_to(cr, it->x, it->y); } Point q = stroke.getPoint(sectionIt->max); cairo_line_to(cr, q.x, q.y); cairo_fill(cr); } } void ErasableStrokeView::paintFilledHighlighter(cairo_t* cr) const { const Stroke& stroke = erasableStroke.stroke; std::vector<ErasableStroke::SubSection> sections = erasableStroke.getRemainingSubSectionsVector(); if (sections.empty()) { return; } xoj::util::CairoSaveGuard guard(cr); const auto linecap = StrokeView::CAIRO_LINE_CAP[stroke.getStrokeCapStyle()]; /** * We create a mask for each subsection, paint on it and blit them all. * We need to rescale the mask according to the scaling of the target cairo context. * We find out this scaling by looking at the transformation matrix */ cairo_matrix_t matrix; cairo_get_matrix(cr, &matrix); // We assume the matrix is an homothety xoj_assert(matrix.xx == matrix.yy && matrix.xy == 0 && matrix.yx == 0); // Initialise the cairo context cairo_set_operator(cr, CAIRO_OPERATOR_MULTIPLY); Util::cairo_set_source_rgbi(cr, stroke.getColor(), static_cast<double>(stroke.getFill()) / 255.0); const std::vector<Point>& data = stroke.getPointVector(); bool mergeFirstAndLast = erasableStroke.isClosedStroke() && sections.size() >= 2 && sections.front().min == PathParameter(0, 0.0) && sections.back().max == PathParameter(data.size() - 2, 1.0); auto sectionIt = sections.cbegin(); auto sectionEndIt = sections.cend(); if (mergeFirstAndLast) { /** * Draw the first and last sections as one */ const ErasableStroke::SubSection& first = sections.front(); const ErasableStroke::SubSection& last = sections.back(); /** * Create a mask tailored to the union of the sections' bounding boxes */ Range box = erasableStroke.getSubSectionBoundingBox(first).unite(erasableStroke.getSubSectionBoundingBox(last)); Mask mask = createMask(cr, box, matrix.xx); cairo_t* crMask = mask.get(); cairo_set_line_cap(crMask, linecap); // Paint to the mask Point p = stroke.getPoint(last.min); cairo_move_to(crMask, p.x, p.y); auto endIt = data.cend(); for (auto it = std::next(data.cbegin(), (std::ptrdiff_t)last.min.index + 1); it != endIt; ++it) { cairo_line_to(crMask, it->x, it->y); } endIt = std::next(data.cbegin(), (std::ptrdiff_t)first.max.index + 1); for (auto it = data.cbegin(); it != endIt; ++it) { cairo_line_to(crMask, it->x, it->y); } Point q = stroke.getPoint(first.max); cairo_line_to(crMask, q.x, q.y); cairo_fill_preserve(crMask); cairo_stroke(crMask); mask.blitTo(cr); // Avoid drawing those sections again ++sectionIt; --sectionEndIt; } for (; sectionIt != sectionEndIt; ++sectionIt) { // Create a mask Mask mask = createMask(cr, erasableStroke.getSubSectionBoundingBox(*sectionIt), matrix.xx); cairo_t* crMask = mask.get(); cairo_set_line_cap(crMask, linecap); // Paint to the mask Point p = stroke.getPoint(sectionIt->min); cairo_move_to(crMask, p.x, p.y); auto endIt = std::next(data.cbegin(), (std::ptrdiff_t)sectionIt->max.index + 1); for (auto it = std::next(data.cbegin(), (std::ptrdiff_t)sectionIt->min.index + 1); it != endIt; ++it) { cairo_line_to(crMask, it->x, it->y); } Point q = stroke.getPoint(sectionIt->max); cairo_line_to(crMask, q.x, q.y); cairo_fill_preserve(crMask); cairo_stroke(crMask); mask.blitTo(cr); } } auto ErasableStrokeView::createMask(cairo_t* target, const Range& box, double zoom) const -> Mask { Mask mask(cairo_get_target(target), box, zoom); cairo_t* crMask = mask.get(); cairo_set_line_join(crMask, CAIRO_LINE_JOIN_ROUND); cairo_set_source_rgba(crMask, 1, 1, 1, 1); cairo_set_operator(crMask, CAIRO_OPERATOR_SOURCE); cairo_set_line_width(crMask, this->erasableStroke.stroke.getWidth()); return mask; }
11,755
C++
.cpp
243
39.271605
120
0.595579
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,649
StavesBackgroundView.cpp
xournalpp_xournalpp/src/core/view/background/StavesBackgroundView.cpp
#include "StavesBackgroundView.h" #include "model/BackgroundConfig.h" // for BackgroundConfig #include "view/background/BackgroundView.h" // for view #include "view/background/OneColorBackgroundView.h" // for OneColorBackgrou... #include "view/background/PlainBackgroundView.h" // for PlainBackgroundView using namespace background_config_strings; using namespace xoj::view; StavesBackgroundView::StavesBackgroundView(double pageWidth, double pageHeight, Color backgroundColor, const BackgroundConfig& config): OneColorBackgroundView(pageWidth, pageHeight, backgroundColor, config, DEFAULT_LINE_WIDTH, DEFAULT_LINE_COLOR, ALT_DEFAULT_LINE_COLOR) {} void StavesBackgroundView::draw(cairo_t* cr) const { // Paint the background color PlainBackgroundView::draw(cr); // Get the bounds of the mask, in page coordinates double minX; double maxX; double minY; double maxY; cairo_clip_extents(cr, &minX, &minY, &maxX, &maxY); const double staffHeight = lineWidth + 4 * LINES_SPACING; // The `+ 4 * lineWidth` is here as a legacy and it does not make a lot of sense. // Still, we must keep it so that we do not alter how staves are displayed in pre-existing documents const double vOffsetBetweenStaves = STAVES_SPACING + staffHeight + 4 * lineWidth; auto [indexMinY, indexMaxY] = getIndexBounds(minY - HEADER_SIZE - staffHeight, maxY + 0.5 * lineWidth - HEADER_SIZE, vOffsetBetweenStaves, 0.0, pageHeight - HEADER_SIZE - FOOTER_SIZE); auto drawStaff = [cr, w = this->pageWidth](double offset) { for (int i = 0; i < 5; ++i) { double y = offset + i * LINES_SPACING; cairo_move_to(cr, MARGIN, y); cairo_line_to(cr, w - MARGIN, y); } cairo_line_to(cr, w - MARGIN, offset); cairo_move_to(cr, MARGIN, offset); cairo_line_to(cr, MARGIN, offset + 4 * LINES_SPACING); }; for (int i = indexMinY; i <= indexMaxY; ++i) { drawStaff(HEADER_SIZE + i * vOffsetBetweenStaves); } cairo_save(cr); Util::cairo_set_source_rgbi(cr, foregroundColor); cairo_set_line_width(cr, lineWidth); cairo_set_line_cap(cr, CAIRO_LINE_CAP_SQUARE); cairo_stroke(cr); cairo_restore(cr); }
2,379
C++
.cpp
44
46.113636
120
0.658348
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,650
BackgroundView.cpp
xournalpp_xournalpp/src/core/view/background/BackgroundView.cpp
#include "BackgroundView.h" #include <glib.h> // for g_warning #include "model/PageType.h" // for PageType, PageTy... #include "model/XojPage.h" // for XojPage #include "view/background/OneColorBackgroundView.h" // for OneColorBackgrou... #include "DottedBackgroundView.h" // for DottedBackground... #include "GraphBackgroundView.h" // for GraphBackgroundView #include "ImageBackgroundView.h" // for ImageBackgroundView #include "IsoDottedBackgroundView.h" // for IsoDottedBackgro... #include "IsoGraphBackgroundView.h" // for IsoGraphBackgrou... #include "LinedBackgroundView.h" // for LinedBackgroundView #include "PdfBackgroundView.h" // for PdfBackgroundView #include "PlainBackgroundView.h" // for PlainBackgroundView #include "RuledBackgroundView.h" // for RuledBackgroundView #include "StavesBackgroundView.h" // for StavesBackground... #include "TransparentCheckerboardBackgroundView.h" // for TransparentCheck... using namespace xoj::view; auto BackgroundView::createRuled(double width, double height, Color backgroundColor, const PageType& pt, double lineWidthFactor) -> std::unique_ptr<BackgroundView> { std::unique_ptr<OneColorBackgroundView> res; switch (pt.format) { case PageTypeFormat::Plain: return std::make_unique<PlainBackgroundView>(width, height, backgroundColor); case PageTypeFormat::Ruled: res = std::make_unique<RuledBackgroundView>(width, height, backgroundColor, pt.config); break; case PageTypeFormat::Lined: res = std::make_unique<LinedBackgroundView>(width, height, backgroundColor, pt.config); break; case PageTypeFormat::Graph: res = std::make_unique<GraphBackgroundView>(width, height, backgroundColor, pt.config); break; case PageTypeFormat::Staves: res = std::make_unique<StavesBackgroundView>(width, height, backgroundColor, pt.config); break; case PageTypeFormat::Dotted: res = std::make_unique<DottedBackgroundView>(width, height, backgroundColor, pt.config); break; case PageTypeFormat::IsoGraph: res = std::make_unique<IsoGraphBackgroundView>(width, height, backgroundColor, pt.config); break; case PageTypeFormat::IsoDotted: res = std::make_unique<IsoDottedBackgroundView>(width, height, backgroundColor, pt.config); break; default: g_warning("BackgroundView::createForPage unknowntype: %d", static_cast<int>(pt.format)); return nullptr; } // In page template previews, the line width is multiplied to make the lines actually visible. res->multiplyLineWidth(lineWidthFactor); return res; } auto BackgroundView::createForPage(PageRef page, BackgroundFlags bgFlags, PdfCache* pdfCache) -> std::unique_ptr<BackgroundView> { const double width = page->getWidth(); const double height = page->getHeight(); if (!bgFlags.forceVisible && !page->isLayerVisible(0)) { return std::make_unique<TransparentCheckerboardBackgroundView>(width, height); } const auto pt = page->getBackgroundType(); if (pt.isSpecial()) { switch (pt.format) { case PageTypeFormat::Image: if (bgFlags.showImage) { return std::make_unique<ImageBackgroundView>(width, height, page->getBackgroundImage()); } break; case PageTypeFormat::Pdf: if (bgFlags.showPDF) { return std::make_unique<PdfBackgroundView>(width, height, page->getPdfPageNr(), pdfCache); } break; default: g_warning("BackgroundView::createForPage unknown type: %d\n", static_cast<int>(pt.format)); return nullptr; } } else { if (bgFlags.showRuling) { return createRuled(width, height, page->getBackgroundColor(), pt); } } if (bgFlags.forceBackgroundColor) { return std::make_unique<PlainBackgroundView>(width, height, page->getBackgroundColor()); } else { return std::make_unique<BackgroundView>(width, height); // Dummy no-op view } }
4,509
C++
.cpp
87
43.183908
110
0.635478
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,651
OneColorBackgroundView.cpp
xournalpp_xournalpp/src/core/view/background/OneColorBackgroundView.cpp
#include "OneColorBackgroundView.h" #include <cstdint> // for uint32_t #include "model/BackgroundConfig.h" // for BackgroundConfig #include "view/background/BackgroundView.h" // for view #include "view/background/PlainBackgroundView.h" // for PlainBackgroundView using namespace background_config_strings; using namespace xoj::view; OneColorBackgroundView::OneColorBackgroundView(double pageWidth, double pageHeight, Color backgroundColor, const BackgroundConfig& config, double defaultLineWidth, Color defaultLineColor, Color altDefaultLineColor): PlainBackgroundView(pageWidth, pageHeight, backgroundColor), lineWidth(defaultLineWidth) { config.loadValue(CFG_LINE_WIDTH, lineWidth); if (backgroundColor.isLight()) { foregroundColor = getColorOr(config, CFG_FOREGROUND_COLOR_1, defaultLineColor); } else { foregroundColor = getColorOr(config, CFG_ALT_FOREGROUND_COLOR_1, altDefaultLineColor); } } void xoj::view::OneColorBackgroundView::multiplyLineWidth(double factor) { lineWidth *= factor; } Color OneColorBackgroundView::getColorOr(const BackgroundConfig& config, const std::string& str, const Color& defaultColor) { if (uint32_t hexColor; config.loadValueHex(str, hexColor)) { return Color(hexColor); } return defaultColor; }
1,457
C++
.cpp
26
47.230769
106
0.701335
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,652
IsoDottedBackgroundView.cpp
xournalpp_xournalpp/src/core/view/background/IsoDottedBackgroundView.cpp
#include "IsoDottedBackgroundView.h" #include "model/BackgroundConfig.h" // for BackgroundC... #include "view/background/BackgroundView.h" // for view #include "view/background/BaseIsometricBackgroundView.h" // for BaseIsometr... using namespace xoj::view; IsoDottedBackgroundView::IsoDottedBackgroundView(double pageWidth, double pageHeight, Color backgroundColor, const BackgroundConfig& config): BaseIsometricBackgroundView(pageWidth, pageHeight, backgroundColor, config, DEFAULT_LINE_WIDTH) {} void IsoDottedBackgroundView::paintGrid(cairo_t* cr, int cols, int rows, double xstep, double ystep, double xOffset, double yOffset) const { auto drawDot = [&](double x, double y) { cairo_move_to(cr, xOffset + x, yOffset + y); cairo_line_to(cr, xOffset + x, yOffset + y); }; for (int col = 0; col <= cols; ++col) { const auto x = col * xstep; const auto evenCol = col % 2 == 0; const auto yoffset = evenCol ? ystep : 0.0; const auto rowsInCol = evenCol ? rows - 2 : rows; for (int row = 0; row <= rowsInCol; row += 2) { const auto y = yoffset + row * ystep; drawDot(x, y); } } }
1,324
C++
.cpp
25
43.56
116
0.608527
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,653
RuledBackgroundView.cpp
xournalpp_xournalpp/src/core/view/background/RuledBackgroundView.cpp
#include "RuledBackgroundView.h" #include <memory> // for allocator #include "model/BackgroundConfig.h" // for BackgroundConfig #include "view/background/BackgroundView.h" // for view #include "view/background/OneColorBackgroundView.h" // for OneColorBackgrou... #include "view/background/PlainBackgroundView.h" // for PlainBackgroundView using namespace background_config_strings; using namespace xoj::view; RuledBackgroundView::RuledBackgroundView(double pageWidth, double pageHeight, Color backgroundColor, const BackgroundConfig& config): OneColorBackgroundView(pageWidth, pageHeight, backgroundColor, config, DEFAULT_LINE_WIDTH, DEFAULT_H_LINE_COLOR, ALT_DEFAULT_H_LINE_COLOR) { config.loadValue(CFG_RASTER, lineSpacing); } void RuledBackgroundView::draw(cairo_t* cr) const { // Paint the background color PlainBackgroundView::draw(cr); // Get the bounds of the mask, in page coordinates double minX; double maxX; double minY; double maxY; cairo_clip_extents(cr, &minX, &minY, &maxX, &maxY); // Add a 0.5 * lineWidth padding in case the line is just outside the mask but its thickness still makes it // (partially) visible auto [indexMinY, indexMaxY] = getIndexBounds(minY - HEADER_SIZE - 0.5 * lineWidth, maxY - HEADER_SIZE + 0.5 * lineWidth, lineSpacing, 0.0, pageHeight - HEADER_SIZE - FOOTER_SIZE); for (int i = indexMinY; i <= indexMaxY; ++i) { cairo_move_to(cr, minX, HEADER_SIZE + i * lineSpacing); cairo_line_to(cr, maxX, HEADER_SIZE + i * lineSpacing); } cairo_save(cr); Util::cairo_set_source_rgbi(cr, foregroundColor); cairo_set_line_width(cr, lineWidth); cairo_set_line_cap(cr, CAIRO_LINE_CAP_BUTT); cairo_stroke(cr); cairo_restore(cr); }
1,914
C++
.cpp
39
42.333333
120
0.676849
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,654
BaseIsometricBackgroundView.cpp
xournalpp_xournalpp/src/core/view/background/BaseIsometricBackgroundView.cpp
#include "BaseIsometricBackgroundView.h" #include <cmath> // for floor, sqrt #include <memory> // for allocator #include "model/BackgroundConfig.h" // for BackgroundConfig #include "util/safe_casts.h" // for floor_cast #include "view/background/BackgroundView.h" // for view #include "view/background/OneColorBackgroundView.h" // for OneColorBackgrou... #include "view/background/PlainBackgroundView.h" // for PlainBackgroundView using namespace background_config_strings; using namespace xoj::view; BaseIsometricBackgroundView::BaseIsometricBackgroundView(double pageWidth, double pageHeight, Color backgroundColor, const BackgroundConfig& config, double defaultLineWidth): OneColorBackgroundView(pageWidth, pageHeight, backgroundColor, config, defaultLineWidth, DEFAULT_LINE_COLOR, ALT_DEFAULT_LINE_COLOR) { config.loadValue(CFG_RASTER, triangleSize); } void BaseIsometricBackgroundView::draw(cairo_t* cr) const { // Paint the background color PlainBackgroundView::draw(cr); const double xstep = std::sqrt(3.0) / 2.0 * triangleSize; const double ystep = triangleSize / 2.0; // Deduce the maximum grid size const double margin = triangleSize; int cols = floor_cast<int>((pageWidth - 2 * margin) / xstep); int rows = floor_cast<int>((pageHeight - 2 * margin) / ystep); // Center the grid on the page const double contentWidth = cols * xstep; const double contentHeight = rows * ystep; double contentXOffset = (pageWidth - contentWidth) / 2; double contentYOffset = (pageHeight - contentHeight) / 2; // Get the bounds of the mask, in page coordinates double minX; double maxX; double minY; double maxY; cairo_clip_extents(cr, &minX, &minY, &maxX, &maxY); // Get the indices we need to paint (= on or near the mask) const double halfLineWidth = 0.5 * lineWidth; auto [indexMinX, indexMaxX] = getIndexBounds(minX - halfLineWidth - xstep - contentXOffset, maxX + halfLineWidth + xstep - contentXOffset, xstep, 0.0, contentWidth); auto [indexMinY, indexMaxY] = getIndexBounds(minY - halfLineWidth - ystep - contentYOffset, maxY + halfLineWidth + ystep - contentYOffset, ystep, 0.0, contentHeight); if ((indexMinY + indexMinX) % 2) { /** The painted area should start with \/\/\/... * /\/\/\/.. * * Enlarge by 1 so that it starts with /\/\/... * \/\/\/.. */ if (indexMinX) { --indexMinX; } else { --indexMinY; } } // Compute the offset and the number of steps within the mask contentXOffset += indexMinX * xstep; contentYOffset += indexMinY * ystep; cols = indexMaxX - indexMinX; rows = indexMaxY - indexMinY; paintGrid(cr, cols, rows, xstep, ystep, contentXOffset, contentYOffset); cairo_save(cr); Util::cairo_set_source_rgbi(cr, foregroundColor); cairo_set_line_width(cr, lineWidth); cairo_set_line_cap(cr, CAIRO_LINE_CAP_ROUND); cairo_stroke(cr); cairo_restore(cr); }
3,338
C++
.cpp
70
40.357143
120
0.634994
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,655
LinedBackgroundView.cpp
xournalpp_xournalpp/src/core/view/background/LinedBackgroundView.cpp
#include "LinedBackgroundView.h" #include <memory> // for allocator #include "model/BackgroundConfig.h" // for BackgroundConfig #include "view/background/BackgroundView.h" // for view #include "view/background/RuledBackgroundView.h" // for RuledBackgroundView using namespace background_config_strings; using namespace xoj::view; LinedBackgroundView::LinedBackgroundView(double pageWidth, double pageHeight, Color backgroundColor, const BackgroundConfig& config): RuledBackgroundView(pageWidth, pageHeight, backgroundColor, config) { if (backgroundColor.isLight()) { vLineColor = getColorOr(config, CFG_FOREGROUND_COLOR_2, DEFAULT_V_LINE_COLOR); } else { vLineColor = getColorOr(config, CFG_ALT_FOREGROUND_COLOR_2, ALT_DEFAULT_V_LINE_COLOR); } config.loadValue(CFG_MARGIN, margin); if (margin < 0) { // A negative value puts the margin line on the right hand side margin += pageWidth; } } void LinedBackgroundView::draw(cairo_t* cr) const { // Paint the horizontal lines RuledBackgroundView::draw(cr); // Add the vertical line cairo_save(cr); Util::cairo_set_source_rgbi(cr, vLineColor); cairo_set_line_width(cr, lineWidth); cairo_set_line_cap(cr, CAIRO_LINE_CAP_BUTT); cairo_move_to(cr, margin, 0); cairo_line_to(cr, margin, pageHeight); cairo_stroke(cr); cairo_restore(cr); }
1,457
C++
.cpp
34
37.235294
100
0.698233
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,656
ImageBackgroundView.cpp
xournalpp_xournalpp/src/core/view/background/ImageBackgroundView.cpp
#include "ImageBackgroundView.h" #include <gdk-pixbuf/gdk-pixbuf.h> // for gdk_pixbuf_get_height #include <gdk/gdk.h> // for gdk_cairo_set_source_pixbuf #include "model/BackgroundImage.h" // for BackgroundImage #include "view/background/BackgroundView.h" // for BackgroundView, view using namespace xoj::view; ImageBackgroundView::ImageBackgroundView(double pageWidth, double pageHeight, const BackgroundImage& image): BackgroundView(pageWidth, pageHeight), image(image) {} void ImageBackgroundView::draw(cairo_t* cr) const { GdkPixbuf* pixbuff = this->image.getPixbuf(); if (pixbuff) { cairo_matrix_t matrix = {0}; cairo_get_matrix(cr, &matrix); int width = gdk_pixbuf_get_width(pixbuff); int height = gdk_pixbuf_get_height(pixbuff); double sx = this->pageWidth / width; double sy = this->pageHeight / height; cairo_scale(cr, sx, sy); gdk_cairo_set_source_pixbuf(cr, pixbuff, 0, 0); cairo_paint(cr); cairo_set_matrix(cr, &matrix); } }
1,073
C++
.cpp
23
40.869565
108
0.675962
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,657
IsoGraphBackgroundView.cpp
xournalpp_xournalpp/src/core/view/background/IsoGraphBackgroundView.cpp
#include "IsoGraphBackgroundView.h" #include "model/BackgroundConfig.h" // for BackgroundC... #include "util/safe_casts.h" // for floor_cast #include "view/background/BackgroundView.h" // for view #include "view/background/BaseIsometricBackgroundView.h" // for BaseIsometr... using namespace xoj::view; IsoGraphBackgroundView::IsoGraphBackgroundView(double pageWidth, double pageHeight, Color backgroundColor, const BackgroundConfig& config): BaseIsometricBackgroundView(pageWidth, pageHeight, backgroundColor, config, DEFAULT_LINE_WIDTH) {} void IsoGraphBackgroundView::paintGrid(cairo_t* cr, int cols, int rows, double xstep, double ystep, double xOffset, double yOffset) const { auto drawLine = [&](double x1, double y1, double x2, double y2) { cairo_move_to(cr, xOffset + x1, yOffset + y1); cairo_line_to(cr, xOffset + x2, yOffset + y2); }; const auto contentWidth = cols * xstep; const auto contentHeight = rows * ystep; // Draw Horizontal line on top and bottom // NB: if we're drawing only a portion of the page that does not touch the upper or lower edge, those lines are not // at their rightful place. They are also out of the cairo mask's clip, so the following is a no-op. drawLine(0.0, 0.0, contentWidth, 0.0); drawLine(0.0, contentHeight, contentWidth, contentHeight); for (int col = 0; col <= cols; ++col) { const auto x = col * xstep; drawLine(x, 0.0, x, contentHeight); } // Determine the number of diagonals to draw auto hdiags = floor_cast<int>(cols / 2); auto vdiags = floor_cast<int>(rows / 2); auto diags = hdiags + vdiags; auto hcorr = cols - 2 * hdiags; auto vcorr = rows - 2 * vdiags; // Draw diagonals starting in the top left corner (left-down) for (int d = 0; d < diags + hcorr * vcorr; ++d) { // Point 1 travels horizontally from top left to top right, // then from top right to bottom right. double x1 = contentWidth, y1 = 0.0; if (d < hdiags) { x1 = xstep + d * 2 * xstep; } else { y1 = ystep + (d - hdiags) * 2 * ystep - hcorr * ystep; } // Point 2 travels vertically from top left to bottom left, // then from bottom left to bottom right. double x2 = 0.0, y2 = contentHeight; if (d < vdiags) { y2 = ystep + d * 2 * ystep; } else { x2 = xstep + (d - vdiags) * 2 * xstep - vcorr * xstep; } drawLine(x1, y1, x2, y2); } // Draw diagonals starting in the top right corner (right-down) for (int d = 0; d < diags; ++d) { // Point 1 travels horizontally from top right to top left, // then from top left to bottom left. double x1 = 0.0, y1 = 0.0; if (d < hdiags) { x1 = contentWidth - (xstep + d * 2 * xstep) - hcorr * xstep; } else { y1 = ystep + (d - hdiags) * 2 * ystep; } // Point 2 travels vertically from top right to bottom right, // then from top bottom right to bottom left. double x2 = contentWidth, y2 = contentHeight; if (d < vdiags) { y2 = ystep + d * 2 * ystep + hcorr * ystep; } else { x2 = contentWidth - (xstep + (d - vdiags) * 2 * xstep) + (vcorr - hcorr) * xstep; } drawLine(x1, y1, x2, y2); } }
3,544
C++
.cpp
73
40.178082
119
0.589001
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,658
DottedBackgroundView.cpp
xournalpp_xournalpp/src/core/view/background/DottedBackgroundView.cpp
#include "DottedBackgroundView.h" #include <memory> // for allocator #include "model/BackgroundConfig.h" // for BackgroundConfig #include "view/background/BackgroundView.h" // for view #include "view/background/OneColorBackgroundView.h" // for OneColorBackgrou... #include "view/background/PlainBackgroundView.h" // for PlainBackgroundView using namespace background_config_strings; using namespace xoj::view; DottedBackgroundView::DottedBackgroundView(double pageWidth, double pageHeight, Color backgroundColor, const BackgroundConfig& config): OneColorBackgroundView(pageWidth, pageHeight, backgroundColor, config, DEFAULT_LINE_WIDTH, DEFAULT_LINE_COLOR, ALT_DEFAULT_LINE_COLOR) { config.loadValue(CFG_RASTER, squareSize); } void DottedBackgroundView::draw(cairo_t* cr) const { // Paint the background color PlainBackgroundView::draw(cr); // Get the bounds of the mask, in page coordinates double minX; double maxX; double minY; double maxY; cairo_clip_extents(cr, &minX, &minY, &maxX, &maxY); // Add a 0.5 * lineWidth padding in case the line is just outside the mask but its thickness still makes it // (partially) visible const double halfLineWidth = 0.5 * lineWidth; auto [indexMinX, indexMaxX] = getIndexBounds(minX - halfLineWidth, maxX + halfLineWidth, squareSize, squareSize, pageWidth); auto [indexMinY, indexMaxY] = getIndexBounds(minY - halfLineWidth, maxY + halfLineWidth, squareSize, squareSize, pageHeight); for (int i = indexMinX; i <= indexMaxX; ++i) { double x = i * squareSize; for (int j = indexMinY; j <= indexMaxY; ++j) { double y = j * squareSize; cairo_move_to(cr, x, y); cairo_line_to(cr, x, y); } } cairo_save(cr); Util::cairo_set_source_rgbi(cr, foregroundColor); cairo_set_line_width(cr, lineWidth); cairo_set_line_cap(cr, CAIRO_LINE_CAP_ROUND); cairo_stroke(cr); cairo_restore(cr); }
2,112
C++
.cpp
45
40.066667
118
0.673311
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,659
PlainBackgroundView.cpp
xournalpp_xournalpp/src/core/view/background/PlainBackgroundView.cpp
#include "PlainBackgroundView.h" #include <algorithm> // for max, min #include "util/safe_casts.h" // for ceil_cast, floor_cast #include "view/background/BackgroundView.h" // for BackgroundView, view using namespace xoj::view; PlainBackgroundView::PlainBackgroundView(double pageWidth, double pageHeight, Color backgroundColor): BackgroundView(pageWidth, pageHeight), backgroundColor(backgroundColor) {} void PlainBackgroundView::draw(cairo_t* cr) const { Util::cairo_set_source_rgbi(cr, this->backgroundColor); cairo_paint(cr); } std::pair<int, int> PlainBackgroundView::getIndexBounds(double min, double max, double step, double margin, double length) { return {ceil_cast<int>(std::max(min, margin) / step), floor_cast<int>(std::min(max, margin + length) / step)}; }
869
C++
.cpp
15
51.466667
114
0.694575
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,660
TransparentCheckerboardBackgroundView.cpp
xournalpp_xournalpp/src/core/view/background/TransparentCheckerboardBackgroundView.cpp
#include "TransparentCheckerboardBackgroundView.h" #include "view/background/BackgroundView.h" // for BackgroundView, view using namespace xoj::view; TransparentCheckerboardBackgroundView::TransparentCheckerboardBackgroundView(double pageWidth, double pageHeight): BackgroundView(pageWidth, pageHeight), pattern(createPattern()) {} TransparentCheckerboardBackgroundView::~TransparentCheckerboardBackgroundView() noexcept { cairo_pattern_destroy(pattern); } auto TransparentCheckerboardBackgroundView::createPattern() -> cairo_pattern_t* { cairo_surface_t* surf = cairo_image_surface_create(CAIRO_FORMAT_RGB24, 2 * CHECKER_SIZE, 2 * CHECKER_SIZE); cairo_t* cr = cairo_create(surf); Util::cairo_set_source_rgbi(cr, LIGHT_GREY); cairo_paint(cr); Util::cairo_set_source_rgbi(cr, DARK_GREY); cairo_rectangle(cr, CHECKER_SIZE, 0, CHECKER_SIZE, CHECKER_SIZE); cairo_rectangle(cr, 0, CHECKER_SIZE, CHECKER_SIZE, CHECKER_SIZE); cairo_fill(cr); cairo_destroy(cr); cairo_pattern_t* pattern = cairo_pattern_create_for_surface(surf); cairo_surface_destroy(surf); // The surface is now owned by the pattern cairo_pattern_set_filter(pattern, CAIRO_FILTER_NEAREST); cairo_pattern_set_extend(pattern, CAIRO_EXTEND_REPEAT); return pattern; } void TransparentCheckerboardBackgroundView::draw(cairo_t* cr) const { cairo_save(cr); cairo_set_source(cr, this->pattern); cairo_paint(cr); cairo_restore(cr); }
1,484
C++
.cpp
30
45.233333
114
0.759195
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,661
PdfBackgroundView.cpp
xournalpp_xournalpp/src/core/view/background/PdfBackgroundView.cpp
#include "PdfBackgroundView.h" #include <glib.h> // for g_warning #include "control/PdfCache.h" // for PdfCache #include "util/Assert.h" // for xoj_assert #include "view/background/BackgroundView.h" // for BackgroundView, view using namespace xoj::view; PdfBackgroundView::PdfBackgroundView(double pageWidth, double pageHeight, size_t pageNo, PdfCache* pdfCache): BackgroundView(pageWidth, pageHeight), pageNo(pageNo), pdfCache(pdfCache) {} void PdfBackgroundView::draw(cairo_t* cr) const { if (pdfCache) { // get zoom from cairo cairo_matrix_t matrix = {0}; cairo_get_matrix(cr, &matrix); xoj_assert(matrix.xx == matrix.yy && matrix.xy == 0.0 && matrix.yx == 0.0); // Homothety matrix double scaleX; double scaleY; cairo_surface_get_device_scale(cairo_get_target(cr), &scaleX, &scaleY); xoj_assert(scaleX == scaleY); double pixelsPerPageUnit = matrix.xx * scaleX; pdfCache->render(cr, pageNo, pixelsPerPageUnit, pageWidth, pageHeight); } else { g_warning("PdfBackgroundView::draw Missing pdf cache: cannot render the pdf page"); PdfCache::renderMissingPdfPage(cr, pageWidth, pageHeight); } }
1,252
C++
.cpp
25
44.24
109
0.671849
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,662
GraphBackgroundView.cpp
xournalpp_xournalpp/src/core/view/background/GraphBackgroundView.cpp
#include "GraphBackgroundView.h" #include <algorithm> // for max, min #include <memory> // for allocator #include "model/BackgroundConfig.h" // for BackgroundConfig #include "view/background/BackgroundView.h" // for view #include "view/background/OneColorBackgroundView.h" // for OneColorBackgrou... #include "view/background/PlainBackgroundView.h" // for PlainBackgroundView using namespace background_config_strings; using namespace xoj::view; GraphBackgroundView::GraphBackgroundView(double pageWidth, double pageHeight, Color backgroundColor, const BackgroundConfig& config): OneColorBackgroundView(pageWidth, pageHeight, backgroundColor, config, DEFAULT_LINE_WIDTH, DEFAULT_LINE_COLOR, ALT_DEFAULT_LINE_COLOR) { config.loadValue(CFG_RASTER, squareSize); config.loadValue(CFG_MARGIN, margin); if (int roundToGrid = 0; margin > 0.0 && config.loadValue(CFG_ROUND_MARGIN, roundToGrid) && roundToGrid) { roundUpMargin = true; } } void GraphBackgroundView::draw(cairo_t* cr) const { // Paint the background color PlainBackgroundView::draw(cr); // Get the bounds of the mask, in page coordinates double minX; double maxX; double minY; double maxY; cairo_clip_extents(cr, &minX, &minY, &maxX, &maxY); if (margin > 0.0) { minX = std::max(minX, margin); maxX = std::min(maxX, pageWidth - margin); minY = std::max(minY, margin); maxY = std::min(maxY, pageHeight - margin); } // Add a 0.5 * lineWidth padding in case the line is just outside the mask but its thickness still makes it // (partially) visible const double halfLineWidth = 0.5 * lineWidth; auto [indexMinX, indexMaxX] = getIndexBounds(minX - halfLineWidth, maxX + halfLineWidth, squareSize, squareSize, pageWidth); auto [indexMinY, indexMaxY] = getIndexBounds(minY - halfLineWidth, maxY + halfLineWidth, squareSize, squareSize, pageHeight); if (roundUpMargin) { auto [pageIndexMinX, pageIndexMaxX] = getIndexBounds(margin - halfLineWidth, pageWidth - margin + halfLineWidth, squareSize, squareSize, pageWidth); auto [pageIndexMinY, pageIndexMaxY] = getIndexBounds( margin - halfLineWidth, pageHeight - margin + halfLineWidth, squareSize, squareSize, pageHeight); minX = std::max(minX, squareSize * pageIndexMinX); maxX = std::min(maxX, squareSize * pageIndexMaxX); minY = std::max(minY, squareSize * pageIndexMinY); maxY = std::min(maxY, squareSize * pageIndexMaxY); } for (int i = indexMinX; i <= indexMaxX; ++i) { cairo_move_to(cr, i * squareSize, minY); cairo_line_to(cr, i * squareSize, maxY); } for (int i = indexMinY; i <= indexMaxY; ++i) { cairo_move_to(cr, minX, i * squareSize); cairo_line_to(cr, maxX, i * squareSize); } cairo_save(cr); Util::cairo_set_source_rgbi(cr, foregroundColor); cairo_set_line_width(cr, lineWidth); cairo_set_line_cap(cr, CAIRO_LINE_CAP_SQUARE); cairo_stroke(cr); cairo_restore(cr); }
3,252
C++
.cpp
66
41.636364
120
0.658683
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,663
StrokeToolView.cpp
xournalpp_xournalpp/src/core/view/overlays/StrokeToolView.cpp
#include "StrokeToolView.h" #include <functional> #include <memory> #include <numeric> #include "control/tools/StrokeHandler.h" #include "model/LineStyle.h" #include "model/Stroke.h" #include "util/Assert.h" #include "util/Color.h" #include "util/PairView.h" #include "util/Range.h" #include "util/raii/CairoWrappers.h" // for CairoSaveGuard #include "view/Repaintable.h" #include "view/StrokeViewHelper.h" using namespace xoj::view; StrokeToolView::StrokeToolView(const StrokeHandler* strokeHandler, const Stroke& stroke, Repaintable* parent): BaseStrokeToolView(parent, stroke), strokeHandler(strokeHandler), pointBuffer(stroke.getPointVector()) { this->registerToPool(strokeHandler->getViewPool()); parent->flagDirtyRegion(Range(stroke.boundingRect())); } StrokeToolView::~StrokeToolView() noexcept { this->unregisterFromPool(); } bool StrokeToolView::isViewOf(const OverlayBase* overlay) const { return overlay == this->strokeHandler; } void StrokeToolView::draw(cairo_t* cr) const { std::vector<Point> pts = this->flushBuffer(); if (pts.empty()) { // The input sequence has probably been cancelled. This view should soon be deleted return; } // pts.front() is the last point we painted on the mask during the last iteration (see flushBuffer()) if (!mask.isInitialized()) { // Initialize the mask on first call mask = createMask(cr); if (!mask.isInitialized()) { /* * The user might be drawing on a page that is not visible at all: * e.g. https://github.com/xournalpp/xournalpp/pull/4158#issuecomment-1385954494 */ return; } } xoj::util::CairoSaveGuard saveGuard(cr); cairo_set_operator(cr, this->cairoOp); this->drawFilling(cr, pts); // Noop in the base class. Util::cairo_set_source_argb(cr, strokeColor); if (pts.size() > 1) { // Draw the new segments on the mask if (pts.front().z == Point::NO_PRESSURE) { StrokeViewHelper::drawNoPressure(this->mask.get(), pts, this->strokeWidth, this->lineStyle, this->dashOffset); if (this->lineStyle.hasDashes()) { // Keep the offset up to date, so we do not have to redraw the entire stroke every time. PairView segments(pts); this->dashOffset = std::transform_reduce(segments.begin(), segments.end(), this->dashOffset, std::plus<>(), [](auto& seg) { return seg.front().lineLengthTo(seg.back()); }); } } else { this->dashOffset = StrokeViewHelper::drawWithPressure(this->mask.get(), pts, this->lineStyle, this->dashOffset); } } else if (this->singleDot) { this->drawDot(this->mask.get(), pts.back()); } this->mask.blitTo(cr); } void StrokeToolView::on(StrokeToolView::AddPointRequest, const Point& p) { this->singleDot = false; xoj_assert(!this->pointBuffer.empty()); // front() is the last point we painted on the mask (see flushBuffer()) Point lastPoint = this->pointBuffer.back(); this->pointBuffer.emplace_back(p); this->parent->flagDirtyRegion(this->getRepaintRange(lastPoint, p)); } void StrokeToolView::on(StrokeToolView::ThickenFirstPointRequest, double newWidth) { xoj_assert(newWidth > 0.0); xoj_assert(this->pointBuffer.size() == 1); Point& p = this->pointBuffer.back(); xoj_assert(p.z <= newWidth); // Thicken means thicken p.z = newWidth; Range rg = Range(p.x, p.y); rg.addPadding(0.5 * newWidth); this->parent->flagDirtyRegion(rg); } void StrokeToolView::deleteOn(StrokeToolView::CancellationRequest, const Range& rg) { this->pointBuffer.clear(); this->parent->drawAndDeleteToolView(this, rg); } void StrokeToolView::on(StrokeToolView::StrokeReplacementRequest, const Stroke& newStroke) { if (this->mask.isInitialized()) { // only wipe mask it actually exists (the view has already been drawn at least once) this->mask.wipe(); } this->pointBuffer = newStroke.getPointVector(); this->dashOffset = 0; this->strokeWidth = newStroke.getWidth(); xoj_assert(this->strokeColor == strokeColorWithAlpha(newStroke)); xoj_assert(this->lineStyle == newStroke.getLineStyle()); xoj_assert(this->cairoOp == (newStroke.getToolType() == StrokeTool::HIGHLIGHTER ? CAIRO_OPERATOR_MULTIPLY : CAIRO_OPERATOR_OVER)); } void StrokeToolView::deleteOn(StrokeToolView::FinalizationRequest, const Range& rg) { this->parent->drawAndDeleteToolView(this, rg); } auto StrokeToolView::getRepaintRange(const Point& lastPoint, const Point& addedPoint) const -> Range { const double width = lastPoint.z == Point::NO_PRESSURE ? this->strokeWidth : lastPoint.z; Range rg(lastPoint.x, lastPoint.y); rg.addPoint(addedPoint.x, addedPoint.y); rg.addPadding(0.5 * width); return rg; } void StrokeToolView::drawDot(cairo_t* cr, const Point& p) const { cairo_set_line_width(cr, p.z == Point::NO_PRESSURE ? this->strokeWidth : p.z); cairo_set_line_cap(cr, CAIRO_LINE_CAP_ROUND); cairo_move_to(cr, p.x, p.y); cairo_line_to(cr, p.x, p.y); cairo_stroke(cr); } std::vector<Point> StrokeToolView::flushBuffer() const { std::vector<Point> pts; std::swap(this->pointBuffer, pts); if (!pts.empty()) { // Keep the last point in the buffer - to be used in the next iteration this->pointBuffer.emplace_back(pts.back()); } return pts; }
5,623
C++
.cpp
125
38.552
117
0.668554
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,664
BaseStrokeToolView.cpp
xournalpp_xournalpp/src/core/view/overlays/BaseStrokeToolView.cpp
#include "BaseStrokeToolView.h" #include <cmath> #include <cairo.h> #include "model/Stroke.h" #include "util/Range.h" #include "view/Mask.h" #include "view/Repaintable.h" #include "view/overlays/OverlayView.h" using namespace xoj::view; BaseStrokeToolView::BaseStrokeToolView(Repaintable* parent, const Stroke& stroke): ToolView(parent), cairoOp(stroke.getToolType() == StrokeTool::HIGHLIGHTER ? CAIRO_OPERATOR_MULTIPLY : CAIRO_OPERATOR_OVER), strokeColor(strokeColorWithAlpha(stroke)), lineStyle(stroke.getLineStyle()), strokeWidth(stroke.getWidth()) {} BaseStrokeToolView::~BaseStrokeToolView() noexcept = default; Color BaseStrokeToolView::strokeColorWithAlpha(const Stroke& s) { Color c = s.getColor(); if (s.getToolType() == StrokeTool::HIGHLIGHTER) { c.alpha = s.getFill() == -1 ? 120U : static_cast<uint8_t>(s.getFill()); } else { c.alpha = 255U; } return c; } auto BaseStrokeToolView::createMask(cairo_t* tgtcr) const -> Mask { const double zoom = this->parent->getZoom(); Range visibleRange = this->parent->getVisiblePart(); if (!visibleRange.isValid()) { /* * The user might be drawing on a page that is not visible at all: * e.g. https://github.com/xournalpp/xournalpp/pull/4158#issuecomment-1385954494 */ return Mask(); } // Add a small padding, to avoid visual artefacts if scrolling right after finishing a stroke touching the visible // area's border visibleRange.addPadding(0.5 * this->strokeWidth); Mask mask(cairo_get_target(tgtcr), visibleRange, zoom); cairo_t* cr = mask.get(); cairo_set_source_rgba(cr, 1, 1, 1, 1); cairo_set_operator(cr, CAIRO_OPERATOR_OVER); cairo_set_line_cap(cr, CAIRO_LINE_CAP_ROUND); cairo_set_line_join(cr, CAIRO_LINE_JOIN_ROUND); return mask; }
1,878
C++
.cpp
46
35.76087
118
0.693956
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,665
SplineToolView.cpp
xournalpp_xournalpp/src/core/view/overlays/SplineToolView.cpp
#include "SplineToolView.h" #include <algorithm> // for for_each #include <cmath> #include <cstdio> #include <optional> #include <vector> #include "control/tools/SplineHandler.h" #include "control/zoom/ZoomControl.h" #include "model/Point.h" #include "model/SplineSegment.h" #include "util/Assert.h" #include "util/raii/CairoWrappers.h" #include "view/Repaintable.h" class OverlayBase; using namespace xoj::view; SplineToolView::SplineToolView(const SplineHandler* splineHandler, Repaintable* parent): BaseShapeOrSplineToolView(splineHandler, parent), splineHandler(splineHandler) { this->registerToPool(splineHandler->getViewPool()); this->parent->getZoomControl()->addZoomListener(this); } SplineToolView::~SplineToolView() noexcept { this->unregisterFromPool(); this->parent->getZoomControl()->removeZoomListener(this); } void SplineToolView::draw(cairo_t* cr) const { auto data = this->splineHandler->getData(); if (!data) { return; } xoj_assert(!data->knots.empty() && data->knots.size() == data->tangents.size()); const double lineWidth = LINE_WIDTH_WITHOUT_ZOOM / this->parent->getZoom(); xoj::util::CairoSaveGuard saveGuard(cr); cairo_set_line_width(cr, lineWidth); const Point& firstKnot = data->knots.front(); const Point& lastKnot = data->knots.back(); const Point& firstTangent = data->tangents.front(); const Point& lastTangent = data->tangents.back(); auto drawCircle = [cr, radius = data->knotsAttractionRadius](const Point& center) { cairo_new_sub_path(cr); cairo_arc(cr, center.x, center.y, radius, 0, 2 * M_PI); }; // draw circles around knot points Util::cairo_set_source_argb(cr, NODE_CIRCLE_COLOR); std::for_each(std::next(data->knots.begin()), data->knots.end(), drawCircle); cairo_stroke(cr); Util::cairo_set_source_argb(cr, FIRST_NODE_CIRCLE_COLOR); drawCircle(firstKnot); if (data->closedSpline) { // current point lies within the circle around the first knot cairo_fill_preserve(cr); } cairo_stroke(cr); // draw dynamically changing segment Util::cairo_set_source_argb(cr, DYNAMIC_OBJECTS_COLOR); const Point& cp1 = Point(lastKnot.x + lastTangent.x, lastKnot.y + lastTangent.y); const Point& cp2 = data->closedSpline ? Point(firstKnot.x - firstTangent.x, firstKnot.y - firstTangent.y) : data->currPoint; const Point& otherKnot = data->closedSpline ? firstKnot : data->currPoint; SplineSegment(lastKnot, cp1, cp2, otherKnot).draw(cr); cairo_stroke(cr); Util::cairo_set_source_argb(cr, TANGENT_VECTOR_COLOR); // draw dynamically changing tangent vector cairo_move_to(cr, lastKnot.x - lastTangent.x, lastKnot.y - lastTangent.y); cairo_line_to(cr, lastKnot.x + lastTangent.x, lastKnot.y + lastTangent.y); // draw other tangent vectors for (size_t i = 0; i < data->knots.size() - 1; i++) { cairo_move_to(cr, data->knots[i].x - data->tangents[i].x, data->knots[i].y - data->tangents[i].y); cairo_line_to(cr, data->knots[i].x + data->tangents[i].x, data->knots[i].y + data->tangents[i].y); } cairo_stroke(cr); this->drawSpline(cr, data.value()); } void SplineToolView::drawWithoutDrawingAids(cairo_t* cr) const { auto data = this->splineHandler->getData(); if (!data) { return; } xoj_assert(!data->knots.empty() && data->knots.size() == data->tangents.size()); xoj::util::CairoSaveGuard saveGuard(cr); this->drawSpline(cr, data.value()); } void SplineToolView::drawSpline(cairo_t* cr, const SplineHandlerData& data) const { if (data.knots.size() > 1) { cairo_t* effCr = this->prepareContext(cr); const Point& firstKnot = data.knots.front(); cairo_move_to(effCr, firstKnot.x, firstKnot.y); auto itKnot1 = data.knots.begin(); auto itKnot2 = std::next(itKnot1); auto itTgt1 = data.tangents.begin(); auto itTgt2 = std::next(itTgt1); for (; itKnot2 != data.knots.end(); ++itKnot1, ++itKnot2, ++itTgt1, ++itTgt2) { cairo_curve_to(effCr, itKnot1->x + itTgt1->x, itKnot1->y + itTgt1->y, itKnot2->x - itTgt2->x, itKnot2->y - itTgt2->y, itKnot2->x, itKnot2->y); } this->commitDrawing(cr); } } bool SplineToolView::isViewOf(const OverlayBase* overlay) const { return overlay == this->splineHandler; } void SplineToolView::zoomChanged() { this->mask.reset(); } void SplineToolView::on(FlagDirtyRegionRequest, Range rg) { maskWipeExtent = maskWipeExtent.unite(rg); rg.addPadding(LINE_WIDTH_WITHOUT_ZOOM / (2.0 * this->parent->getZoom())); this->parent->flagDirtyRegion(rg); } void SplineToolView::deleteOn(SplineToolView::FinalizationRequest, Range rg) { rg.addPadding(LINE_WIDTH_WITHOUT_ZOOM / (2.0 * this->parent->getZoom())); this->parent->drawAndDeleteToolView(this, rg); }
4,929
C++
.cpp
107
40.925234
117
0.683563
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,666
ShapeToolView.cpp
xournalpp_xournalpp/src/core/view/overlays/ShapeToolView.cpp
#include "ShapeToolView.h" #include <vector> #include "control/tools/BaseShapeHandler.h" #include "util/raii/CairoWrappers.h" #include "view/Repaintable.h" #include "view/StrokeViewHelper.h" using namespace xoj::view; ShapeToolView::ShapeToolView(const BaseShapeHandler* toolHandler, Repaintable* parent): BaseShapeOrSplineToolView(toolHandler, parent), toolHandler(toolHandler) { this->registerToPool(toolHandler->getViewPool()); } ShapeToolView::~ShapeToolView() noexcept { this->unregisterFromPool(); } void ShapeToolView::draw(cairo_t* cr) const { const auto& pts = this->toolHandler->getShape(); if (pts.empty()) { // The input sequence has been cancelled. This view should soon be deleted return; } xoj::util::CairoSaveGuard saveGuard(cr); // cairo_save cairo_t* effCr = this->prepareContext(cr); StrokeViewHelper::pathToCairo(effCr, pts); this->commitDrawing(cr); } bool ShapeToolView::isViewOf(const OverlayBase* overlay) const { return overlay == this->toolHandler; } void ShapeToolView::on(ShapeToolView::FlagDirtyRegionRequest, const Range& rg) { maskWipeExtent = maskWipeExtent.unite(rg); this->parent->flagDirtyRegion(rg); } void ShapeToolView::deleteOn(ShapeToolView::FinalizationRequest, const Range& rg) { this->parent->drawAndDeleteToolView(this, rg); }
1,354
C++
.cpp
31
40.032258
103
0.757066
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,667
BaseShapeOrSplineToolView.cpp
xournalpp_xournalpp/src/core/view/overlays/BaseShapeOrSplineToolView.cpp
#include "BaseShapeOrSplineToolView.h" #include "control/tools/InputHandler.h" #include "model/LineStyle.h" #include "model/Stroke.h" #include "util/Assert.h" #include "util/Color.h" #include "util/Util.h" // for cairo_set_dash_from_vector using namespace xoj::view; /** * @brief To avoid rendering artefact (due to antialiasing?) we add a padding when clearing out the mask (for filled * highlighter only) */ constexpr double MASK_CLEARANCE_PADDING = 1; static const Stroke& safeGetStroke(const InputHandler* h) { xoj_assert(h); xoj_assert(h->getStroke()); return *h->getStroke(); } static double getFillingAlpha(const InputHandler* h) { auto f = safeGetStroke(h).getFill(); return f == -1 ? 0.0 : f / 255.0; } BaseShapeOrSplineToolView::BaseShapeOrSplineToolView(const InputHandler* toolHandler, Repaintable* parent): BaseStrokeToolView(parent, safeGetStroke(toolHandler)), fillingAlpha(getFillingAlpha(toolHandler)), needMask(this->fillingAlpha != 0.0 && safeGetStroke(toolHandler).getToolType() == StrokeTool::HIGHLIGHTER) {} BaseShapeOrSplineToolView::~BaseShapeOrSplineToolView() noexcept = default; cairo_t* BaseShapeOrSplineToolView::prepareContext(cairo_t* cr) const { cairo_set_operator(cr, this->cairoOp); if (needMask) { // The mask is only for filled highlighter strokes, to avoid artefacts as in // https://github.com/xournalpp/xournalpp/issues/3709 if (!mask.isInitialized()) { mask = createMask(cr); const auto& dashes = this->lineStyle.getDashes(); Util::cairo_set_dash_from_vector(mask.get(), dashes, 0); cairo_set_line_width(mask.get(), this->strokeWidth); // operator is already set by createMask(). } else { // Clear the mask maskWipeExtent.addPadding(MASK_CLEARANCE_PADDING); mask.wipeRange(maskWipeExtent); maskWipeExtent = Range(); } return mask.get(); } else { cairo_set_line_cap(cr, CAIRO_LINE_CAP_ROUND); cairo_set_line_join(cr, CAIRO_LINE_JOIN_ROUND); cairo_set_line_width(cr, this->strokeWidth); const auto& dashes = this->lineStyle.getDashes(); Util::cairo_set_dash_from_vector(cr, dashes, 0.0); return cr; } } void BaseShapeOrSplineToolView::commitDrawing(cairo_t* cr) const { if (fillingAlpha != 0.0) { if (mask.isInitialized()) { cairo_fill_preserve(mask.get()); } else { // Not need when using a mask: transparency will be applied upon blitting. Util::cairo_set_source_rgbi(cr, strokeColor, fillingAlpha); cairo_fill_preserve(cr); } } Util::cairo_set_source_argb(cr, this->strokeColor); if (mask.isInitialized()) { cairo_stroke(mask.get()); mask.blitTo(cr); } else { cairo_stroke(cr); } }
2,924
C++
.cpp
72
34.055556
117
0.665023
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,668
PdfElementSelectionView.cpp
xournalpp_xournalpp/src/core/view/overlays/PdfElementSelectionView.cpp
#include "PdfElementSelectionView.h" #include "control/tools/PdfElemSelection.h" #include "util/raii/CairoWrappers.h" #include "view/Repaintable.h" class Range; using namespace xoj::view; PdfElementSelectionView::PdfElementSelectionView(const PdfElemSelection* selection, Repaintable* parent, Color selectionColor): OverlayView(parent), selection(selection), selectionColor(selectionColor) { this->registerToPool(selection->getViewPool()); } PdfElementSelectionView::~PdfElementSelectionView() noexcept { this->unregisterFromPool(); } void PdfElementSelectionView::draw(cairo_t* cr) const { xoj::util::CairoSaveGuard saveGuard(cr); if (auto reg = selection->getSelectedRegion(); reg && !cairo_region_is_empty(reg)) { gdk_cairo_region(cr, reg); Util::cairo_set_source_rgbi(cr, selectionColor, SELECTION_OPACITY); cairo_fill(cr); } } bool PdfElementSelectionView::isViewOf(const OverlayBase* overlay) const { return overlay == this->selection; } void PdfElementSelectionView::on(PdfElementSelectionView::FlagDirtyRegionRequest, const Range& rg) const { this->parent->flagDirtyRegion(rg); } void PdfElementSelectionView::deleteOn(PdfElementSelectionView::CancelSelectionRequest, const Range& rg) { this->parent->deleteOverlayView(this, rg); }
1,355
C++
.cpp
27
44.925926
111
0.751138
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,669
VerticalToolView.cpp
xournalpp_xournalpp/src/core/view/overlays/VerticalToolView.cpp
#include "VerticalToolView.h" #include "control/settings/Settings.h" #include "control/zoom/ZoomControl.h" #include "util/raii/CairoWrappers.h" #include "view/ElementContainerView.h" #include "view/Repaintable.h" #include "view/View.h" using namespace xoj::view; VerticalToolView::VerticalToolView(const VerticalToolHandler* handler, Repaintable* parent, ZoomControl* zoomControl, const Settings* settings): ToolView(parent), toolHandler(handler), zoomControl(zoomControl), aidColor(settings->getSelectionColor()) { this->registerToPool(handler->getViewPool()); zoomControl->addZoomListener(this); } VerticalToolView::~VerticalToolView() noexcept { zoomControl->removeZoomListener(this); this->unregisterFromPool(); } void VerticalToolView::draw(cairo_t* cr) const { xoj::util::CairoSaveGuard saveGuard(cr); const double startY = toolHandler->getStartY(); const double endY = toolHandler->getEndY(); cairo_rectangle(cr, 0, startY, toolHandler->getPageWidth(), endY - startY); cairo_set_line_width(cr, BORDER_WIDTH_IN_PIXELS / this->parent->getZoom()); Util::cairo_set_source_rgbi(cr, this->aidColor); cairo_stroke_preserve(cr); Util::cairo_set_source_rgbi(cr, this->aidColor, BACKGROUND_OPACITY); cairo_fill(cr); this->drawWithoutDrawingAids(cr); } void VerticalToolView::drawWithoutDrawingAids(cairo_t* cr) const { xoj::util::CairoSaveGuard saveGuard(cr); if (!mask.isInitialized()) { // Initialize the mask on first call, when changing sides or upon zoom change mask = createMask(cr); xoj::view::ElementContainerView v(this->toolHandler); v.draw(xoj::view::Context::createDefault(mask.get())); } cairo_translate(cr, 0, toolHandler->getEndY() - toolHandler->getStartY()); mask.paintTo(cr); } bool VerticalToolView::isViewOf(const OverlayBase* overlay) const { return overlay == this->toolHandler; } void VerticalToolView::on(VerticalToolView::SetVerticalShiftRequest, double shift) { Range rg = this->parent->getVisiblePart(); auto side = this->toolHandler->getSide(); // Padding for taking into account the drawing aid line width const double padding = 0.5 * BORDER_WIDTH_IN_PIXELS / this->parent->getZoom(); if (side == VerticalToolHandler::Side::Above) { rg.maxY = std::clamp(std::max(shift, this->lastShift) + padding, rg.minY, rg.maxY); } else { rg.minY = std::clamp(std::min(shift, this->lastShift) - padding, rg.minY, rg.maxY); } this->parent->flagDirtyRegion(rg); this->lastShift = shift; } void VerticalToolView::on(VerticalToolView::SwitchDirectionRequest) { mask.reset(); this->parent->flagDirtyRegion(this->parent->getVisiblePart()); } void VerticalToolView::deleteOn(VerticalToolView::FinalizationRequest) { double startY = toolHandler->getStartY(); double endY = toolHandler->getEndY(); auto [minY, maxY] = std::minmax(startY, endY); // Padding for taking into account the drawing aid line width const double padding = 0.5 * BORDER_WIDTH_IN_PIXELS / this->parent->getZoom(); // Get a range containing exactly the drawing aid blue rectangle Range rg(std::numeric_limits<double>::lowest(), minY - padding, std::numeric_limits<double>::max(), maxY + padding); rg = rg.intersect(this->parent->getVisiblePart()); this->parent->drawAndDeleteToolView(this, rg); } Mask VerticalToolView::createMask(cairo_t* tgtcr) const { auto side = toolHandler->getSide(); auto startY = toolHandler->getStartY(); /* * Create a mask that * * starts at startY if side == Side::Below * * ends at startY if side == Side::Above * * has height and width those of the visible area * This mask is as small as possible, and still allows the user to see all elements go up or down, as long as the * cursor remains in the affected page. * TODO find a way to have the mask big enough for all situations: * * If the previous page is partially visible, the mask is to short * * If the cursor goes into the toolbar, the mask is to short * * If several views are implemented, the mask size should depend on the possible cursor positions * within the acted upon view, not the current view * (the entire page is not an option for infinite pages...) */ const double zoom = this->parent->getZoom(); Range range = this->parent->getVisiblePart(); if (side == VerticalToolHandler::Side::Above) { range.translate(0, startY - range.maxY); } else { range.translate(0, startY - range.minY); } return Mask(cairo_get_target(tgtcr), range, zoom, CAIRO_CONTENT_COLOR_ALPHA); } void VerticalToolView::zoomChanged() { // If zooming in, the mask needs redrawing to get a suitable definition // If zooming out, the mask needs redrawing to cover a bigger part of the page mask.reset(); }
5,037
C++
.cpp
101
44.891089
120
0.697556
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,670
ImageSizeSelectionView.cpp
xournalpp_xournalpp/src/core/view/overlays/ImageSizeSelectionView.cpp
#include "ImageSizeSelectionView.h" #include "control/tools/ImageSizeSelection.h" // for ImageSizeSelection #include "util/Rectangle.h" // for Rectangle #include "util/raii/CairoWrappers.h" // for cairo_save #include "view/Repaintable.h" // for Repaintable using namespace xoj::view; ImageSizeSelectionView::ImageSizeSelectionView(const ImageSizeSelection* imageSizeSelection, Repaintable* parent, Color selectionColor): OverlayView(parent), imageSizeSelection(imageSizeSelection), selectionColor(selectionColor) { this->registerToPool(imageSizeSelection->getViewPool()); } ImageSizeSelectionView::~ImageSizeSelectionView() noexcept = default; void ImageSizeSelectionView::draw(cairo_t* cr) const { const xoj::util::Rectangle space = this->imageSizeSelection->getSelectedSpace(); xoj::util::CairoSaveGuard const saveGuard(cr); // cairo_save cairo_set_line_width(cr, BORDER_WIDTH_IN_PIXELS / this->parent->getZoom()); cairo_set_dash(cr, DASH_PATTERN.data(), DASH_PATTERN.size(), 0); Util::cairo_set_source_rgbi(cr, selectionColor); cairo_new_path(cr); // these lines form the outline of the space rectangle cairo_line_to(cr, space.x, space.y); cairo_line_to(cr, space.x, space.y + space.height); cairo_line_to(cr, space.x + space.width, space.y + space.height); cairo_line_to(cr, space.x + space.width, space.y); cairo_close_path(cr); cairo_stroke_preserve(cr); Util::cairo_set_source_rgbi(cr, selectionColor, OPACITY_FOR_FILL); cairo_fill(cr); } auto ImageSizeSelectionView::isViewOf(const OverlayBase* overlay) const -> bool { return overlay == this->imageSizeSelection; } void ImageSizeSelectionView::on(ImageSizeSelectionView::FlagDirtyRegionRequest, Range rg) { rg.addPadding(BORDER_WIDTH_IN_PIXELS / this->parent->getZoom()); this->parent->flagDirtyRegion(rg); } void ImageSizeSelectionView::deleteOn(ImageSizeSelectionView::FinalizationRequest, Range rg) { rg.addPadding(BORDER_WIDTH_IN_PIXELS / this->parent->getZoom()); this->parent->deleteOverlayView(this, rg); }
2,177
C++
.cpp
40
49.525
113
0.725
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,671
SearchResultView.cpp
xournalpp_xournalpp/src/core/view/overlays/SearchResultView.cpp
#include "SearchResultView.h" #include "control/SearchControl.h" #include "util/Range.h" #include "util/raii/CairoWrappers.h" #include "view/Repaintable.h" using namespace xoj::view; SearchResultView::SearchResultView(const SearchControl* searchControl, Repaintable* parent, Color frameColor, Color frameHighlightColor): OverlayView(parent), searchControl(searchControl), frameColor(frameColor), frameHighlightColor(frameHighlightColor) { this->registerToPool(searchControl->getViewPool()); } SearchResultView::~SearchResultView() noexcept { this->unregisterFromPool(); } void SearchResultView::draw(cairo_t* cr) const { const XojPdfRectangle* highlightRect = this->searchControl->getHighlightRect(); xoj::util::CairoSaveGuard saveGuard(cr); cairo_set_line_width(cr, BORDER_WIDTH_IN_PIXELS / this->parent->getZoom()); for (const XojPdfRectangle& rect: this->searchControl->getResults()) { cairo_rectangle(cr, rect.x1, rect.y1, rect.x2 - rect.x1, rect.y2 - rect.y1); Color color = frameColor; if (&rect == highlightRect) { color = frameHighlightColor; } Util::cairo_set_source_rgbi(cr, color); cairo_stroke_preserve(cr); Util::cairo_set_source_rgbi(cr, color, BACKGROUND_OPACITY); cairo_fill(cr); } } bool SearchResultView::isViewOf(const OverlayBase* overlay) const { return overlay == this->searchControl; } void SearchResultView::on(SearchResultView::SearchChangedNotification) { Range rg = this->parent->getVisiblePart(); if (!rg.empty()) { this->parent->flagDirtyRegion(this->parent->getVisiblePart()); } }
1,707
C++
.cpp
38
38.763158
109
0.704819
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,672
StrokeToolFilledHighlighterView.cpp
xournalpp_xournalpp/src/core/view/overlays/StrokeToolFilledHighlighterView.cpp
#include "StrokeToolFilledHighlighterView.h" #include <vector> #include "model/Point.h" #include "util/Color.h" #include "util/Range.h" #include "util/raii/CairoWrappers.h" #include "view/StrokeViewHelper.h" using namespace xoj::view; StrokeToolFilledHighlighterView::StrokeToolFilledHighlighterView(const StrokeHandler* strokeHandler, const Stroke& stroke, Repaintable* parent): StrokeToolFilledView(strokeHandler, stroke, parent) {} StrokeToolFilledHighlighterView::~StrokeToolFilledHighlighterView() noexcept = default; void StrokeToolFilledHighlighterView::draw(cairo_t* cr) const { std::vector<Point> pts = this->flushBuffer(); if (pts.empty()) { // The input sequence has probably been cancelled. This view should soon be deleted return; } this->filling.appendSegments(pts); if (!this->mask.isInitialized()) { // Initialize mask on first call this->mask = this->createMask(cr); if (!mask.isInitialized()) { /* * The user might be drawing on a page that is not visible at all: * e.g. https://github.com/xournalpp/xournalpp/pull/4158#issuecomment-1385954494 */ return; } } if (this->singleDot) { this->drawDot(this->mask.get(), pts.back()); } else { /* * Upon adding a segment, the filling can actually shrink. * We wipe the portion of the mask that can change: the convex hull of the added points + the first point */ Range wipe(filling.firstPoint.x, filling.firstPoint.y); for (auto& p: pts) { wipe.addPoint(p.x, p.y); } if (wipe.isValid()) { this->mask.wipeRange(wipe); } /* * Draw both the filling and the stroke alike on the mask */ cairo_set_line_width(this->mask.get(), this->strokeWidth); StrokeViewHelper::pathToCairo(this->mask.get(), this->filling.contour); cairo_fill_preserve(this->mask.get()); cairo_stroke(this->mask.get()); } xoj::util::CairoSaveGuard saveGuard(cr); Util::cairo_set_source_argb(cr, this->strokeColor); cairo_set_operator(cr, this->cairoOp); this->mask.blitTo(cr); }
2,320
C++
.cpp
57
32.385965
113
0.633734
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,673
TextEditionView.cpp
xournalpp_xournalpp/src/core/view/overlays/TextEditionView.cpp
#include "TextEditionView.h" #include "control/tools/TextEditor.h" #include "model/Text.h" #include "util/Color.h" #include "util/raii/CairoWrappers.h" #include "view/Repaintable.h" using namespace xoj::view; TextEditionView::TextEditionView(const TextEditor* textEditor, Repaintable* parent): ToolView(parent), textEditor(textEditor) { this->registerToPool(textEditor->getViewPool()); this->on(FLAG_DIRTY_REGION, textEditor->getContentBoundingBox()); } TextEditionView::~TextEditionView() noexcept { this->unregisterFromPool(); } void TextEditionView::draw(cairo_t* cr) const { xoj::util::CairoSaveGuard saveGuard(cr); // Draw the frame double zoom = parent->getZoom(); cairo_set_line_width(cr, BORDER_WIDTH_IN_PIXELS / zoom); Util::cairo_set_source_argb(cr, this->textEditor->getSelectionColor()); Range frame = textEditor->getContentBoundingBox(); frame.addPadding(PADDING_IN_PIXELS / zoom); cairo_rectangle(cr, frame.getX(), frame.getY(), frame.getWidth(), frame.getHeight()); cairo_stroke(cr); // Draw the text itself this->drawWithoutDrawingAids(cr); // Draw the cursor if (this->textEditor->isCursorVisible()) { auto cursorBox = this->textEditor->getCursorBox(); if (cursorBox.getWidth() == 0.0) { const double shift = 0.5 * INSERTION_CURSOR_WIDTH_IN_PIXELS / zoom; cursorBox.minX -= shift; cursorBox.maxX += shift; } cairo_set_operator(cr, CAIRO_OPERATOR_DIFFERENCE); cairo_set_source_rgb(cr, 1, 1, 1); const Text* textElement = this->textEditor->getTextElement(); cairo_rectangle(cr, cursorBox.minX + textElement->getX(), cursorBox.minY + textElement->getY(), cursorBox.getWidth(), cursorBox.getHeight()); cairo_fill(cr); } } void TextEditionView::drawWithoutDrawingAids(cairo_t* cr) const { xoj::util::CairoSaveGuard saveGuard(cr); const Text* textElement = this->textEditor->getTextElement(); Util::cairo_set_source_rgbi(cr, textElement->getColor()); // From now on, coordinates are in textElement coordinates cairo_translate(cr, textElement->getX(), textElement->getY()); // The data is owned by textEditor PangoLayout* layout = this->textEditor->getUpToDateLayout(); // The cairo context might have changed. Update the pango layout pango_cairo_update_layout(cr, layout); pango_context_set_matrix(pango_layout_get_context(layout), nullptr); pango_cairo_show_layout(cr, layout); } bool TextEditionView::isViewOf(const OverlayBase* overlay) const { return overlay == this->textEditor; } auto TextEditionView::toWindowCoordinates(const xoj::util::Rectangle<double>& r) const -> xoj::util::Rectangle<double> { auto* textElement = this->textEditor->getTextElement(); return parent->toWindowCoordinates(r.translated(textElement->getX(), textElement->getY())); } void TextEditionView::on(TextEditionView::FlagDirtyRegionRequest, Range rg) { const double padding = std::max(BORDER_WIDTH_IN_PIXELS + PADDING_IN_PIXELS, INSERTION_CURSOR_WIDTH_IN_PIXELS) / this->parent->getZoom(); rg.addPadding(padding); this->parent->flagDirtyRegion(rg); } void TextEditionView::deleteOn(TextEditionView::FinalizationRequest, Range rg) { const double padding = std::max(BORDER_WIDTH_IN_PIXELS + PADDING_IN_PIXELS, INSERTION_CURSOR_WIDTH_IN_PIXELS) / this->parent->getZoom(); rg.addPadding(padding); this->parent->drawAndDeleteToolView(this, rg); }
3,580
C++
.cpp
71
44.56338
120
0.70745
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,674
StrokeToolFilledView.cpp
xournalpp_xournalpp/src/core/view/overlays/StrokeToolFilledView.cpp
#include "StrokeToolFilledView.h" #include <algorithm> #include "model/Stroke.h" #include "util/Assert.h" #include "util/Color.h" #include "util/Range.h" #include "view/Repaintable.h" #include "view/StrokeViewHelper.h" using namespace xoj::view; static const Point& setupFirstPoint(const Stroke& s) { const auto& pts = s.getPointVector(); xoj_assert(!pts.empty()); return pts.front(); } StrokeToolFilledView::StrokeToolFilledView(const StrokeHandler* strokeHandler, const Stroke& stroke, Repaintable* parent): StrokeToolView(strokeHandler, stroke, parent), filling(stroke.getFill() / 255.0, setupFirstPoint(stroke)) {} StrokeToolFilledView::~StrokeToolFilledView() noexcept = default; void StrokeToolFilledView::drawFilling(cairo_t* cr, const std::vector<Point>& pts) const { this->filling.appendSegments(pts); /* * Draw the filling directly (not through the mask) * Upon adding a segment, the filling can actually shrink, making it easier to redraw the filling every time. */ StrokeViewHelper::pathToCairo(cr, this->filling.contour); Util::cairo_set_source_rgbi(cr, strokeColor, this->filling.alpha); cairo_fill(cr); } void StrokeToolFilledView::on(StrokeToolView::AddPointRequest, const Point& p) { this->singleDot = false; xoj_assert(!this->pointBuffer.empty()); Point lastPoint = this->pointBuffer.back(); this->pointBuffer.emplace_back(p); auto rg = this->getRepaintRange(lastPoint, p); // Add the first point, so that the range covers all the filling changes rg.addPoint(this->filling.firstPoint.x, this->filling.firstPoint.y); this->parent->flagDirtyRegion(rg); } void StrokeToolFilledView::on(StrokeToolView::StrokeReplacementRequest, const Stroke& newStroke) { StrokeToolView::on(STROKE_REPLACEMENT_REQUEST, newStroke); this->filling.contour = this->pointBuffer; if (!this->pointBuffer.empty()) { const Point& fp = this->pointBuffer.front(); this->filling.firstPoint = xoj::util::Point<double>(fp.x, fp.y); } } void StrokeToolFilledView::FillingData::appendSegments(const std::vector<Point>& pts) { xoj_assert(!pts.empty()); // Add new points to the contour // contour.back() == pts.front(), so we skip it. std::copy(std::next(pts.begin()), pts.end(), std::back_inserter(contour)); }
2,383
C++
.cpp
52
41.211538
116
0.717363
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,675
SelectionView.cpp
xournalpp_xournalpp/src/core/view/overlays/SelectionView.cpp
#include "SelectionView.h" #include <vector> #include "control/tools/Selection.h" #include "util/Color.h" #include "util/LoopUtil.h" #include "util/Range.h" #include "util/raii/CairoWrappers.h" #include "view/Repaintable.h" using namespace xoj::view; SelectionView::SelectionView(const Selection* selection, Repaintable* parent, Color selectionColor): OverlayView(parent), selection(selection), selectionColor(selectionColor) { this->registerToPool(selection->getViewPool()); } SelectionView::~SelectionView() noexcept { this->unregisterFromPool(); } void SelectionView::draw(cairo_t* cr) const { auto pts = this->selection->getBoundary(); if (pts.size() < 3) { // To few points to draw return; } xoj::util::CairoSaveGuard saveGuard(cr); // cairo_save // set the line always the same size on display cairo_set_line_width(cr, BORDER_WIDTH_IN_PIXELS / this->parent->getZoom()); Util::cairo_set_source_rgbi(cr, selectionColor); cairo_new_path(cr); for (auto& p: pts) { cairo_line_to(cr, p.x, p.y); } cairo_close_path(cr); cairo_stroke_preserve(cr); Util::cairo_set_source_rgbi(cr, selectionColor, FILLING_OPACITY); cairo_fill(cr); } bool SelectionView::isViewOf(const OverlayBase* overlay) const { return overlay == this->selection; } void SelectionView::on(SelectionView::FlagDirtyRegionRequest, Range rg) { rg.addPadding(BORDER_WIDTH_IN_PIXELS / this->parent->getZoom()); this->parent->flagDirtyRegion(rg); } void xoj::view::SelectionView::deleteOn(xoj::view::SelectionView::DeleteViewsRequest, Range rg) { rg.addPadding(BORDER_WIDTH_IN_PIXELS / this->parent->getZoom()); this->parent->deleteOverlayView(this, rg); }
1,739
C++
.cpp
42
37.5
101
0.721925
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,676
xournalpp-thumbnailer.cpp
xournalpp_xournalpp/src/xoj-preview-extractor/xournalpp-thumbnailer.cpp
/* * Xournal++ * * This small program extracts a preview out of a xoj file * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GPL */ // Set to true to write a log with errors and debug logs to /tmp/xojtmb.log #define DEBUG_THUMBNAILER false #include <algorithm> // for max, min #include <cstdio> // for fclose, fopen, fwrite, FILE #include <iostream> // for endl, ostream, basic_ostream #include <locale> // for locale #include <string> // for string, basic_string, allocator #include <vector> // for vector #include <cairo.h> // for cairo_create, cairo_image_surf... #include <glib.h> // for gchar, g_get_home_dir, g_getenv #include <libintl.h> // for bindtextdomain, textdomain #include <librsvg/rsvg.h> // for RsvgDimensionData, rsvg_handle... #include "util/PathUtil.h" // for getLocalePath #include "util/PlaceholderString.h" // for PlaceholderString #include "util/XojPreviewExtractor.h" // for XojPreviewExtractor, PREVIEW_R... #include "util/i18n.h" // for _F, _ #include "config.h" // for GETTEXT_PACKAGE, ENABLE_NLS #include "filesystem.h" // for path, operator/, u8path, exists #ifdef DEBUG_THUMBERNAILER #include <fstream> #endif using std::cerr; using std::cout; using std::endl; using std::string; void initLocalisation() { #ifdef ENABLE_NLS bindtextdomain(GETTEXT_PACKAGE, Util::getLocalePath().u8string().c_str()); textdomain(GETTEXT_PACKAGE); #endif // ENABLE_NLS std::locale::global(std::locale("")); //"" - system default locale std::cout.imbue(std::locale()); } void logMessage(string msg, bool error) { if (error) { cerr << msg << endl; } else { cout << msg << endl; } #if DEBUG_THUMBNAILER std::ofstream ofs; ofs.open("/tmp/xojtmb.log", std::ofstream::out | std::ofstream::app); if (error) { ofs << "E: "; } else { ofs << "I: "; } ofs << msg << endl; ofs.close(); #endif } static const std::string iconName = "com.github.xournalpp.xournalpp"; /** * Search for Xournal++ icon based on the freedesktop icon theme specification */ fs::path findAppIcon() { std::vector<fs::path> basedirs; #if DEBUG_THUMBNAILER basedirs.emplace_back(fs::u8path("../ui/pixmaps")); #endif // $HOME/.icons basedirs.emplace_back(fs::u8path(g_get_home_dir()) / ".icons"); // $XDG_DATA_DIRS/icons if (const char* datadirs = g_getenv("XDG_DATA_DIRS")) { std::string dds = datadirs; std::string::size_type lastp = 0; std::string::size_type p; while ((p = dds.find(":", lastp)) != std::string::npos) { std::string path = dds.substr(lastp, p - lastp); basedirs.emplace_back(fs::u8path(path) / "icons"); lastp = p + 1; } } basedirs.emplace_back(fs::u8path("/usr/share/pixmaps")); const auto iconFile = iconName + ".svg"; // Search through base directories for (auto&& d: basedirs) { fs::path svgPath; if (fs::exists((svgPath = d / "hicolor/scalable/apps" / iconFile))) { return svgPath; } else if (fs::exists((svgPath = d / iconFile))) { return svgPath; } } return ""; } int main(int argc, char* argv[]) { initLocalisation(); // check args count if (argc != 3) { logMessage(_("xoj-preview-extractor: call with INPUT.xoj OUTPUT.png"), true); return 1; } XojPreviewExtractor extractor; PreviewExtractResult result = extractor.readFile(argv[1]); switch (result) { case PREVIEW_RESULT_IMAGE_READ: // continue to write preview break; case PREVIEW_RESULT_BAD_FILE_EXTENSION: logMessage((_F("xoj-preview-extractor: file \"{1}\" is not .xoj file") % argv[1]).str(), true); return 2; case PREVIEW_RESULT_COULD_NOT_OPEN_FILE: logMessage((_F("xoj-preview-extractor: opening input file \"{1}\" failed") % argv[1]).str(), true); return 3; case PREVIEW_RESULT_NO_PREVIEW: logMessage((_F("xoj-preview-extractor: file \"{1}\" contains no preview") % argv[1]).str(), true); return 4; case PREVIEW_RESULT_ERROR_READING_PREVIEW: default: logMessage(_("xoj-preview-extractor: no preview and page found, maybe an invalid file?"), true); return 5; } gsize dataLen = 0; unsigned char* imageData = extractor.getData(dataLen); // The following code is for rendering the Xournal++ icon on top of thumbnails. // Struct for reading imageData into a cairo surface struct ReadClosure { unsigned int pos; unsigned char* data; gsize maxLen; }; cairo_read_func_t processRead = (cairo_read_func_t) + [](ReadClosure* closure, unsigned char* data, unsigned int length) { if (closure->pos + length > closure->maxLen) { return CAIRO_STATUS_READ_ERROR; } for (auto i = 0U; i < length; i++) { data[i] = closure->data[closure->pos + i]; } closure->pos += length; return CAIRO_STATUS_SUCCESS; }; ReadClosure closure{0, imageData, dataLen}; cairo_surface_t* thumbnail = cairo_image_surface_create_from_png_stream(processRead, &closure); // This application is short-lived, so we'll purposefully be sloppy and let the OS free memory. if (cairo_surface_status(thumbnail) == CAIRO_STATUS_SUCCESS) { GError* err = nullptr; const auto width = cairo_image_surface_get_width(thumbnail); const auto height = cairo_image_surface_get_height(thumbnail); const auto iconSize = 0.5 * std::min(width, height); const auto svgPath = findAppIcon(); RsvgHandle* handle = rsvg_handle_new_from_file(svgPath.c_str(), &err); if (err) { logMessage((_F("xoj-preview-extractor: could not find icon \"{1}\"") % iconName).str(), true); } else { rsvg_handle_set_dpi(handle, 90); // does the dpi matter for an icon overlay? // Render at bottom right cairo_t* cr = cairo_create(thumbnail); const RsvgRectangle viewport{width - iconSize, height - iconSize, iconSize, iconSize}; GError* error = nullptr; rsvg_handle_render_document(handle, cr, &viewport, &error); if (error != nullptr) { g_warning("Could not render the icon"); g_clear_error(&error); } } cairo_surface_write_to_png(thumbnail, argv[2]); } else { // Cairo was unable to load the image, so fallback to writing the PNG data to disk. FILE* fp = fopen(argv[2], "wb"); if (!fp) { logMessage((_F("xoj-preview-extractor: opening output file \"{1}\" failed") % argv[2]).str(), true); return 6; } fwrite(imageData, dataLen, 1, fp); fclose(fp); } logMessage(_("xoj-preview-extractor: successfully extracted"), false); return 0; }
7,182
C++
.cpp
181
32.779006
112
0.610649
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,677
Xournalpp.cpp
xournalpp_xournalpp/src/exe/Xournalpp.cpp
/* * Xournal++ * * The main application * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 */ #include "control/CrashHandler.h" // for installCrashHandlers #include "control/XournalMain.h" // for run #ifdef __APPLE__ #include "osx/setup-env.h" #endif #ifdef _WIN32 #include <cstdlib> #include "win32/console.h" #endif auto main(int argc, char* argv[]) -> int { #ifdef _WIN32 // Attach to the console here. Otherwise, gspawn-win32-helper will create annoying console popups. attachConsole(); #endif // init crash handler installCrashHandlers(); #ifdef DEV_CALL_LOG Log::initlog(); #endif #ifdef _WIN32 // Switch to the FontConfig backend for Pango - See #3371 _putenv_s("PANGOCAIRO_BACKEND", "fc"); #endif #ifdef __APPLE__ // Setup the environment variables, in particular so that the pixbuf loaders are found setupEnvironment(); #endif // Use this two line to test the crash handler... // int* crash = nullptr; // *crash = 0; int result = XournalMain::run(argc, argv); #ifdef DEV_CALL_LOG Log::closelog(); #endif return result; }
1,155
C++
.cpp
46
22.326087
102
0.70073
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,678
setup-env.cpp
xournalpp_xournalpp/src/exe/osx/setup-env.cpp
#include "setup-env.h" #include <string> #include <CoreFoundation/CoreFoundation.h> #include <glib.h> #include "util/Stacktrace.h" #include "filesystem.h" void setupEnvironment() { /** * see https://gitlab.gnome.org/GNOME/gtk-mac-bundler/-/blob/master/examples/gtk3-launcher.sh * and https://gitlab.gnome.org/GNOME/gtk-mac-bundler/-/issues/12 */ auto base = Stacktrace::getExePath().parent_path(); // Xournal++.app/Contents or $HOME/gtk/inst if (fs::exists(base / "Resources")) { // app-bundle base = base / "Resources"; } // Now base is Xournal++.app/Contents/Resources or $HOME/gtk/inst auto libPath = base / "lib"; auto dataPath = base / "share"; auto xdgPath = base / "etc" / "xdg"; auto imModuleFile = libPath / "gtk-3.0" / "3.0.0" / "immodules.cache"; auto pixbufModuleFile = libPath / "gdk-pixbuf-2.0" / "2.10.0" / "loaders.cache"; setenv("XDG_CONFIG_DIRS", xdgPath.string().c_str(), 1); setenv("XDG_DATA_DIRS", dataPath.string().c_str(), 1); setenv("GTK_DATA_PREFIX", base.string().c_str(), 1); setenv("GTK_EXE_PREFIX", base.string().c_str(), 1); setenv("GTK_PATH", base.string().c_str(), 1); setenv("GTK_IM_MODULE_FILE", imModuleFile.string().c_str(), 0); setenv("GDK_PIXBUF_MODULE_FILE", pixbufModuleFile.string().c_str(), 0); auto environ = g_get_environ(); const char* usedPixbufModuleFile = g_environ_getenv(environ, "GDK_PIXBUF_MODULE_FILE"); g_message("Continue with GDK_PIXBUF_MODULE_FILE = %s", usedPixbufModuleFile); /** * set LANG and LC_MESSAGES in order to detect the default language * Use the equivalent of 'defaults read -g "AppleLanguages"' executed in the terminal, also visible in System * settings -> Language and Region */ CFArrayRef languages = (CFArrayRef)CFPreferencesCopyAppValue(CFSTR("AppleLanguages"), kCFPreferencesCurrentApplication); if (languages && CFArrayGetCount(languages)) { CFStringRef langCode = (CFStringRef)CFArrayGetValueAtIndex(languages, 0); if (langCode) { char buffer[128]; if (CFStringGetCString(langCode, buffer, sizeof(buffer), kCFStringEncodingUTF8)) { std::string lang = buffer; // e.g. "de-DE" if (auto pos = lang.find("-"); pos != std::string::npos) { lang.replace(pos, 1, "_"); // e.g. "de_DE" } lang += ".UTF-8"; // e.g. "de_DE.UTF-8" g_message("Setting LANG and LC_MESSAGES to %s", lang.c_str()); setenv("LANG", lang.c_str(), 0); setenv("LC_MESSAGES", lang.c_str(), 0); } } } }
2,731
C++
.cpp
54
43.055556
113
0.614489
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,679
console.cpp
xournalpp_xournalpp/src/exe/win32/console.cpp
#include "console.h" #include <windows.h> void attachConsole() { if (GetConsoleWindow() != NULL) { // Console is already attached. return; } // Make sure the console starts hidden. STARTUPINFOW startupInfo = {0}; startupInfo.dwFlags = STARTF_USESHOWWINDOW; startupInfo.wShowWindow = SW_HIDE; startupInfo.cb = sizeof(startupInfo); PROCESS_INFORMATION processInformation = {0}; bool consoleAttached = false; if (CreateProcessW(L"C:\\Windows\\System32\\cmd.exe", NULL, NULL, NULL, FALSE, 0, NULL, NULL, &startupInfo, &processInformation)) { HANDLE job = CreateJobObject(NULL, NULL); if (job != NULL) { // Terminate the console process automatically when Xournal++ exits. JOBOBJECT_EXTENDED_LIMIT_INFORMATION jobInformation = {0}; jobInformation.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE; if (!SetInformationJobObject(job, JobObjectExtendedLimitInformation, &jobInformation, sizeof(jobInformation)) || !AssignProcessToJobObject(job, processInformation.hProcess)) { TerminateProcess(processInformation.hProcess, 0); CloseHandle(processInformation.hProcess); CloseHandle(processInformation.hThread); CloseHandle(job); processInformation.hProcess = processInformation.hThread = job = NULL; } else { // It takes a short time before the console becomes ready to be attached, unfortunately // there is no API that would let us wait for it. for (unsigned short i = 0; i < 20; i++) { if (AttachConsole(processInformation.dwProcessId)) { consoleAttached = true; break; } Sleep(50); } } } else { TerminateProcess(processInformation.hProcess, 0); CloseHandle(processInformation.hProcess); CloseHandle(processInformation.hThread); processInformation.hProcess = processInformation.hThread = NULL; } if (processInformation.hProcess != NULL) { if (!consoleAttached) { TerminateProcess(processInformation.hProcess, 0); CloseHandle(job); } CloseHandle(processInformation.hProcess); CloseHandle(processInformation.hThread); } } if (!consoleAttached) { // Could not attach to the manually created console process, request one from the system instead. // This will make the console window flash briefly before we hide it. AllocConsole(); ShowWindow(GetConsoleWindow(), SW_HIDE); } }
2,878
C++
.cpp
62
34.274194
111
0.609269
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,680
gui_main.cpp
xournalpp_xournalpp/src/exe/win32/gui_main.cpp
// Only for Windows GUI applications, compiled with MSVC. #ifdef _MSC_VER #include <cstdlib> #include <combaseapi.h> #include <windows.h> auto main(int argc, char* argv[]) -> int; int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PSTR lpCmdLine, int nCmdShow) { // Call main: return main(__argc, __argv); } #endif
342
C++
.cpp
11
28.909091
96
0.736196
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,681
GtkTest.h
xournalpp_xournalpp/test/gtk_tests/dialog/GtkTest.h
// // Created by hermannt on 11.06.23. // #ifndef XOURNALPP_GTKTEST_H #define XOURNALPP_GTKTEST_H #include <gtest/gtest.h> #include <gtk/gtk.h> class GtkTest: public ::testing::Test { protected: GtkApplication* app; int argn; char** argv; virtual void runTest(GtkApplication* app) = 0; // Setting up the testing environment void SetUp() override; // This the callback in which the actual test is run // It needs to be a callback because it requires the GtkApplication to be running already. static void applicationCallback(GtkApplication* app, gpointer userData); }; #endif // XOURNALPP_GTKTEST_H
641
C++
.h
20
28.9
94
0.736156
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,682
gdk4_helper.h
xournalpp_xournalpp/src/util/include/util/gdk4_helper.h
/* * Xournal++ * * header for missing gdk4 functions (part of the gtk4 port) * will be removed later * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #include <gdk/gdk.h> /*** GdkEvent ***/ GdkModifierType gdk_event_get_modifier_state(GdkEvent* event); /*** GdkKeyEvent ***/ GdkModifierType gdk_key_event_get_consumed_modifiers(GdkEvent* event); guint gdk_key_event_get_keyval(GdkEvent* event);
476
C++
.h
18
24.666667
70
0.735683
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,683
Point.h
xournalpp_xournalpp/src/util/include/util/Point.h
/* * Xournal++ * * Range * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #include <cmath> #include <tuple> namespace xoj::util { template <typename T> struct Point { // Todo (c++20): remove constructors constexpr Point() = default; constexpr Point(T x, T y): x(x), y(y) {} [[maybe_unused]] constexpr auto distance(Point p) const -> double { return std::hypot(p.x - this->x, p.y - this->y); } [[maybe_unused]] constexpr auto operator-(Point p) const -> Point { return {this->x - p.x, this->y - p.y}; } [[maybe_unused]] constexpr auto operator-=(Point p) -> Point& { return *this = *this - p; } [[maybe_unused]] constexpr auto operator+(Point p) const -> Point { return {this->x + p.x, this->y + p.y}; } [[maybe_unused]] constexpr auto operator+=(Point p) -> Point& { return *this = *this + p; } [[maybe_unused]] constexpr auto operator/(T k) const -> Point { return {this->x / k, this->y / k}; } [[maybe_unused]] constexpr auto operator/=(T k) -> Point& { return *this = *this / k; } [[maybe_unused]] constexpr auto operator*(T k) const -> Point { return {this->x * k, this->y * k}; } [[maybe_unused]] constexpr auto operator*=(T k) -> Point& { return *this = *this * k; } [[maybe_unused]] constexpr friend auto operator==(Point const& lhs, Point const& rhs) -> bool { return std::tie(lhs.x, lhs.y) == std::tie(rhs.x, rhs.y); } [[maybe_unused]] constexpr friend auto operator!=(Point const& lhs, Point const& rhs) -> bool { return !(lhs == rhs); } T x{}; T y{}; }; } // namespace xoj::util
1,680
C++
.h
40
37.95
112
0.609711
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,684
GListView.h
xournalpp_xournalpp/src/util/include/util/GListView.h
/* * Xournal++ * * GListView, a c++ wrapper around GList * Provides a begin iterator and a Sentinel * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #include <tuple> #include <glib.h> template <class ListType, typename T> struct ListView { struct GListViewIter { using iterator_category = std::forward_iterator_tag; using value_type = T; using pointer = T*; using reference = T&; using difference_type = std::ptrdiff_t; constexpr auto operator++() -> GListViewIter& { this->list = list->next; return *this; } constexpr auto operator++(int) -> GListViewIter { GListViewIter ret = *this; ++(*this); return ret; } constexpr friend auto operator==(GListViewIter const& lhs, GListViewIter const& rhs) -> bool { return lhs.list == rhs.list; } constexpr friend auto operator!=(GListViewIter const& lhs, GListViewIter const& rhs) -> bool { return !(lhs == rhs); } constexpr T& operator*() { return *static_cast<T*>(list->data); } constexpr T* operator->() { return static_cast<T*>(list->data); } ListType* list{}; }; struct GListViewSentinel { constexpr friend bool operator==(GListViewIter const& iter, GListViewSentinel const&) { return iter.list == nullptr; } constexpr friend bool operator==(GListViewSentinel const&, GListViewIter const& iter) { return iter.list == nullptr; } constexpr friend bool operator!=(GListViewIter const& iter, GListViewSentinel const&) { return iter.list != nullptr; } constexpr friend bool operator!=(GListViewSentinel const&, GListViewIter const& iter) { return iter.list != nullptr; } }; constexpr ListView(ListType* list): list(list) {} constexpr auto begin() -> GListViewIter { return {list}; } // /// Slow, iterates over all elements to find the end // Todo(if required): constexpr auto rbegin() -> GListViewRevIter { return {g_list_last(list)}; } constexpr auto end() -> GListViewSentinel { return {}; } // Todo(if required): constexpr auto rend() -> GListViewSentinel { return {}; } /// Convenient way to iterate over a GListView, DO NOT REVERSE IT constexpr auto end_iter() -> GListViewIter { return {nullptr}; } private: ListType* list; }; template <typename T> using GListView = ListView<GList, T>; template <typename T> using GSListView = ListView<GSList, T>;
2,667
C++
.h
70
31.328571
102
0.633967
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,685
BasePointerIterator.h
xournalpp_xournalpp/src/util/include/util/BasePointerIterator.h
/* * Xournal++ * * Basic iterator based on pointer arithmetics * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #include <cstddef> #include <iterator> #include "TypeIfThenElse.h" template <typename T, bool is_const> class BasePointerIterator { public: using iterator_category = std::random_access_iterator_tag; using value_type = T; using qualified_value_type = typename const_if<T, is_const>::type; using pointer = qualified_value_type*; using reference = qualified_value_type&; using difference_type = std::ptrdiff_t; BasePointerIterator() = default; ~BasePointerIterator() = default; BasePointerIterator(const BasePointerIterator&) = default; BasePointerIterator(pointer p): p(p) {} reference operator*() const { return *p; } pointer operator->() const { return p; } BasePointerIterator& operator++() { ++p; return *this; } BasePointerIterator operator++(int) { auto tmp = *this; ++p; return tmp; } BasePointerIterator& operator--() { --p; return *this; } BasePointerIterator operator--(int) { auto tmp = *this; --p; return tmp; } BasePointerIterator& operator+=(difference_type n) { p += n; return *this; } BasePointerIterator& operator-=(difference_type n) { p -= n; return *this; } BasePointerIterator operator+(difference_type n) const { return BasePointerIterator(p + n); } BasePointerIterator operator-(difference_type n) const { return BasePointerIterator(p - n); } difference_type operator-(const BasePointerIterator& other) const { return p - other.p; } reference operator[](difference_type n) { return *(p + n); } bool operator==(const BasePointerIterator& other) const { return p == other.p; } bool operator!=(const BasePointerIterator& other) const { return p != other.p; } bool operator<(const BasePointerIterator& other) const { return p < other.p; } bool operator>(const BasePointerIterator& other) const { return other < *this; } bool operator<=(const BasePointerIterator& other) const { return !(other < *this); } bool operator>=(const BasePointerIterator& other) const { return !(*this < other); } friend BasePointerIterator operator+(difference_type n, BasePointerIterator& it) { return it + n; } private: pointer p = nullptr; };
2,496
C++
.h
69
31.15942
103
0.674534
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,686
Range.h
xournalpp_xournalpp/src/util/include/util/Range.h
/* * Xournal++ * * Range * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #include <limits> namespace xoj::util { template <typename Float> class Rectangle; }; class Range final { public: Range() = default; // Empty range Range(double x, double y): minX(x), minY(y), maxX(x), maxY(y) {} Range(double minX, double minY, double maxX, double maxY): minX(minX), minY(minY), maxX(maxX), maxY(maxY) {} explicit Range(const xoj::util::Rectangle<double>& r); void addPoint(double x, double y); [[nodiscard]] Range unite(const Range& other) const; [[nodiscard]] Range intersect(const Range& other) const; [[nodiscard]] double getX() const; [[nodiscard]] double getY() const; [[nodiscard]] double getWidth() const; [[nodiscard]] double getHeight() const; void addPadding(double padding); void translate(double dx, double dy); [[nodiscard]] bool empty() const; [[nodiscard]] bool isValid() const; [[nodiscard]] bool contains(double x, double y) const; [[nodiscard]] bool contains(const xoj::util::Rectangle<double>& r) const; double minX = std::numeric_limits<double>::max(); double minY = std::numeric_limits<double>::max(); double maxX = std::numeric_limits<double>::lowest(); double maxY = std::numeric_limits<double>::lowest(); };
1,395
C++
.h
40
31.3
112
0.679554
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,687
XojPreviewExtractor.h
xournalpp_xournalpp/src/util/include/util/XojPreviewExtractor.h
/* * Xournal++ * * Extracts a preview of an .xoj file, used by xournalpp-thumbnailer and xournalpp * Because of this xournal type checks cannot be used * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #include <glib.h> // for gsize #include "filesystem.h" // for path enum PreviewExtractResult { /** * Successfully read an image from file */ PREVIEW_RESULT_IMAGE_READ = 0, /** * File extension is wrong */ PREVIEW_RESULT_BAD_FILE_EXTENSION, /** * The file could not be openend / found */ PREVIEW_RESULT_COULD_NOT_OPEN_FILE, /** * The preview could not be extracted */ PREVIEW_RESULT_ERROR_READING_PREVIEW, /** * The file contains no preview */ PREVIEW_RESULT_NO_PREVIEW, }; class XojPreviewExtractor { public: XojPreviewExtractor(); ~XojPreviewExtractor(); public: /** * Try to read the preview from file * @param file .xoj File * @return If an image was read, or the error */ PreviewExtractResult readFile(const fs::path& file); /** * Try to read the preview from byte buffer * @param buffer Buffer * @param len Buffer len * @return If an image was read, or the error */ PreviewExtractResult readPreview(char* buffer, int len); /** * @return The preview data, should be a binary PNG */ unsigned char* getData(gsize& dataLen); // Member private: /** * Preview data */ unsigned char* data = nullptr; gsize dataLen = 0; };
1,617
C++
.h
66
20.060606
82
0.649967
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,688
PathUtil.h
xournalpp_xournalpp/src/util/include/util/PathUtil.h
/* * Xournal++ * * Helper for reading / writing files * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #include <cstring> // for strlen, size_t #include <optional> // for optional #include <string> // for string, allocator, basic_string #include <vector> // for vector #include <gio/gio.h> // for GFile #include <glib.h> // for g_free, GError, g_error_free, g_filename_fro... #include "util/raii/GObjectSPtr.h" #include "util/safe_casts.h" // for as_signed #include "filesystem.h" // for path, u8path namespace Util { /** * 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 */ [[maybe_unused]] [[nodiscard]] std::optional<std::string> readString(fs::path const& path, bool showErrorToUser = true, std::ios_base::openmode openmode = std::ios::in); /** * Get escaped path, all " and \ are escaped */ [[maybe_unused]] [[nodiscard]] std::string getEscapedPath(const fs::path& path); /** * @return true if this file has .xopp or .xoj extension */ [[maybe_unused]] [[nodiscard]] bool hasXournalFileExt(const fs::path& path); /** * @return true if this file has a pdf extension */ bool hasPdfFileExt(const fs::path& path); /** * Clear the xournal extensions ignoring case (.xoj, .xopp) * * @param ext An extension to clear additionally, eg .pdf (would also clear * .PDF.xopp etc.) */ void clearExtensions(fs::path& path, const std::string& ext = ""); // Uri must be ASCII-encoded! [[maybe_unused]] [[nodiscard]] std::optional<fs::path> fromUri(const std::string& uri); [[maybe_unused]] [[nodiscard]] std::optional<std::string> toUri(const fs::path& path); [[maybe_unused]] [[nodiscard]] fs::path fromGFile(GFile* file); [[maybe_unused]] [[nodiscard]] xoj::util::GObjectSPtr<GFile> toGFile(fs::path const& path); [[maybe_unused]] [[nodiscard]] inline fs::path fromGFilename(char* path, bool owned = true) { auto deleter = [path, owned]() { if (owned) { g_free(path); } }; if (path == nullptr) { return {}; } gsize pSize{0}; GError* err{}; auto* u8Path = g_filename_to_utf8(path, as_signed(std::strlen(path)), nullptr, &pSize, &err); if (err) { g_message("Failed to convert g_filename to utf8 with error code: %d\n%s", err->code, err->message); g_error_free(err); deleter(); return {}; } auto ret = fs::u8path(u8Path, u8Path + pSize); g_free(u8Path); deleter(); return ret; } [[maybe_unused]] [[nodiscard]] inline std::string toGFilename(fs::path const& path) { auto u8path = path.u8string(); gsize pSize{0}; GError* err{}; auto* local = g_filename_from_utf8(u8path.c_str(), as_signed(u8path.size()), nullptr, &pSize, &err); if (err) { g_message("Failed to convert g_filename from utf8 with error code: %d\n%s", err->code, err->message); g_error_free(err); return {}; } auto ret = std::string{local, pSize}; g_free(local); return ret; } void openFileWithDefaultApplication(const fs::path& filename); [[maybe_unused]] [[nodiscard]] bool isChildOrEquivalent(fs::path const& path, fs::path const& base); [[maybe_unused]] bool safeRenameFile(fs::path const& from, fs::path const& to); [[maybe_unused]] fs::path ensureFolderExists(const fs::path& p); /** * Convert to platform compatible path. Call this before * passing a path to another program. */ fs::path getLongPath(const fs::path& path); [[deprecated("can produce invalid strings on windows, use fs::path::native()")]] [[nodiscard]] // auto system_single_byte_filename(const fs::path& path) -> std::string; /** * Return the configuration folder path (may not be guaranteed to exist). */ [[maybe_unused]] [[nodiscard]] fs::path getConfigFolder(); [[maybe_unused]] [[nodiscard]] fs::path getConfigSubfolder(const fs::path& subfolder = ""); [[maybe_unused]] [[nodiscard]] fs::path getCacheSubfolder(const fs::path& subfolder = ""); [[maybe_unused]] [[nodiscard]] fs::path getDataSubfolder(const fs::path& subfolder = ""); [[maybe_unused]] [[nodiscard]] fs::path getStateSubfolder(const fs::path& subfolder = ""); [[maybe_unused]] [[nodiscard]] fs::path getConfigFile(const fs::path& relativeFileName = ""); [[maybe_unused]] [[nodiscard]] fs::path getCacheFile(const fs::path& relativeFileName = ""); [[maybe_unused]] [[nodiscard]] fs::path getTmpDirSubfolder(const fs::path& subfolder = ""); [[maybe_unused]] [[nodiscard]] fs::path getAutosaveFilepath(); [[maybe_unused]] [[nodiscard]] fs::path getGettextFilepath(fs::path const& localeDir); [[maybe_unused]] [[nodiscard]] fs::path getDataPath(); [[maybe_unused]] [[nodiscard]] fs::path getLocalePath(); fs::path getBuiltInPaletteDirectoryPath(); fs::path getCustomPaletteDirectoryPath(); /** * List all files in a directory sorted alphabetically * * If the directory does not exist it returns an empty list. * @param directory to search * @return files in directory */ std::vector<fs::path> listFilesSorted(fs::path directory); } // namespace Util
5,328
C++
.h
130
37.561538
119
0.675498
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,689
GVariantTemplate.h
xournalpp_xournalpp/src/util/include/util/GVariantTemplate.h
/* * Xournal++ * * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #include <bitset> #include <string> #include <type_traits> #include <glib.h> #include "util/Color.h" namespace detail { template <class T> constexpr inline bool match_guint32() { return std::is_integral_v<T> && std::is_unsigned_v<T> && sizeof(T) == sizeof(guint32); } template <class T> constexpr inline bool match_gint32() { return std::is_integral_v<T> && std::is_signed_v<T> && sizeof(T) == sizeof(gint32); } template <class T> constexpr inline bool match_guint64() { return std::is_integral_v<T> && std::is_unsigned_v<T> && sizeof(T) == sizeof(guint64); } template <class T> constexpr inline bool match_gint64() { return std::is_integral_v<T> && std::is_signed_v<T> && sizeof(T) == sizeof(gint64); } template <class T, class U = void> struct GVariantWrapperImpl {}; template <> struct GVariantWrapperImpl<bool> { static inline bool getValue(GVariant* v) { return g_variant_get_boolean(v); } static inline const GVariantType* getType() { return G_VARIANT_TYPE_BOOLEAN; } static inline GVariant* make(bool v) { return g_variant_new_boolean(v); } }; template <> struct GVariantWrapperImpl<const char*> { static inline const char* getValue(GVariant* v) { return g_variant_get_string(v, nullptr); } static inline const GVariantType* getType() { return G_VARIANT_TYPE_STRING; } static inline GVariant* make(const char* v) { return g_variant_new_string(v); } }; template <> struct GVariantWrapperImpl<double> { static inline double getValue(GVariant* v) { return g_variant_get_double(v); } static inline const GVariantType* getType() { return G_VARIANT_TYPE_DOUBLE; } static inline GVariant* make(double v) { return g_variant_new_double(v); } }; template <class T> struct GVariantWrapperImpl<T, std::enable_if_t<match_gint32<T>(), void>> { static inline T getValue(GVariant* v) { return g_variant_get_int32(v); } static inline const GVariantType* getType() { return G_VARIANT_TYPE_INT32; } static inline GVariant* make(T v) { return g_variant_new_int32(v); } }; template <class T> struct GVariantWrapperImpl<T, std::enable_if_t<match_guint32<T>(), void>> { static inline T getValue(GVariant* v) { return g_variant_get_uint32(v); } static inline const GVariantType* getType() { return G_VARIANT_TYPE_UINT32; } static inline GVariant* make(T v) { return g_variant_new_uint32(v); } }; template <class T> struct GVariantWrapperImpl<T, std::enable_if_t<match_gint64<T>(), void>> { static inline T getValue(GVariant* v) { return g_variant_get_int64(v); } static inline const GVariantType* getType() { return G_VARIANT_TYPE_INT64; } static inline GVariant* make(T v) { return g_variant_new_int64(v); } }; template <class T> struct GVariantWrapperImpl<T, std::enable_if_t<match_guint64<T>(), void>> { static inline T getValue(GVariant* v) { return g_variant_get_uint64(v); } static inline const GVariantType* getType() { return G_VARIANT_TYPE_UINT64; } static inline GVariant* make(T v) { return g_variant_new_uint64(v); } }; template <class T> struct GVariantWrapperImpl<T, std::enable_if_t<std::is_enum_v<T>, void>> { // enum types are stored as guint64 static inline T getValue(GVariant* v) { return static_cast<T>(g_variant_get_uint64(v)); } static inline const GVariantType* getType() { return G_VARIANT_TYPE_UINT64; } static inline GVariant* make(T v) { return g_variant_new_uint64(static_cast<guint64>(v)); } }; template <> struct GVariantWrapperImpl<Color> { static_assert(sizeof(guint32) == sizeof(Color)); static inline Color getValue(GVariant* v) { return static_cast<Color>(g_variant_get_uint32(v)); } static inline const GVariantType* getType() { return G_VARIANT_TYPE_UINT32; } static inline GVariant* make(Color v) { return g_variant_new_uint32(static_cast<guint32>(v)); } }; }; // namespace detail template <class T> inline T getGVariantValue(GVariant* v) { return detail::GVariantWrapperImpl<T>::getValue(v); } template <class T> inline const GVariantType* gVariantType() { return detail::GVariantWrapperImpl<T>::getType(); } template <class T> inline GVariant* makeGVariant(T v) { return detail::GVariantWrapperImpl<T>::make(v); } template <> inline GVariant* makeGVariant(const std::string& v) { return g_variant_new_string(v.c_str()); } template <> inline const GVariantType* gVariantType<const std::string&>() { return G_VARIANT_TYPE_STRING; }
4,557
C++
.h
110
38.9
111
0.718602
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,690
XojMsgBox.h
xournalpp_xournalpp/src/util/include/util/XojMsgBox.h
/* * Xournal++ * * Xournal util functions * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #include <string> #include <vector> #include <gtk/gtk.h> #include "util/move_only_function.h" #include "util/raii/GtkWindowUPtr.h" #include "filesystem.h" class XojMsgBox final { public: enum CallbackPolicy { IMMEDIATE, POSTPONED }; XojMsgBox( GtkDialog* dialog, xoj::util::move_only_function<void(int)> callback = [](int) {}, CallbackPolicy pol = POSTPONED); ~XojMsgBox() = default; inline GtkWindow* getWindow() const { return window.get(); } private: xoj::util::GtkWindowUPtr window; xoj::util::move_only_function<void(int)> callback; ///< The parameter is the dialog's response ID gulong signalId; /** * If POSTPONED, the callback is called after the dialog has been closed. This is necessary when the callback can * pop up another dialog. * However, if POSTPONED, the dialog instance will have been destroyed by the time the callback is called, so any * pointer to the GtkDialog instance will be dangling */ CallbackPolicy policy; public: struct Button { Button(std::string l, int r): label(std::move(l)), response(r) {} std::string label; int response; }; /** * Set window for messages without window */ static void setDefaultWindow(GtkWindow* win); static void askQuestion(GtkWindow* win, const std::string& maintext, const std::string& secondarytext, const std::vector<Button>& buttons, xoj::util::move_only_function<void(int)> callback); /** * @brief same as askQuestion() but the string maintext is not escaped for Pango markups */ static void askQuestionWithMarkup(GtkWindow* win, std::string_view maintext, const std::string& secondarytext, const std::vector<Button>& buttons, xoj::util::move_only_function<void(int)> callback); /** * @brief Shows a message with title markupTitle and message content msg. * The title is formatted according to any Pango markups it contains. */ static void showMarkupMessageToUser(GtkWindow* win, const std::string_view& markupTitle, const std::string& msg, GtkMessageType type); static void showMessageToUser(GtkWindow* win, const std::string& msg, GtkMessageType type); static void showMessageToUser(GtkWindow* win, const std::string& title, const std::string& msg, GtkMessageType type); static void showErrorToUser(GtkWindow* win, const std::string& msg); /// @brief This should be used for fatal errors, typically in early GUI startup (missing UI main file or so). [[noreturn]] static void showErrorAndQuit(std::string& msg, int exitCode); static void showPluginMessage(const std::string& pluginName, const std::string& msg, bool error = false); [[deprecated("Will be removed when porting to gtk4")]] static int askPluginQuestion( const std::string& pluginName, const std::string& msg, const std::vector<Button>& buttons, bool error = false); static void showHelp(GtkWindow* win); /** * @brief Calls writeToFile(file) if either file is not already present in the filesystem, or is the user answers * "Overwrite" to a popup dialog. */ static void replaceFileQuestion(GtkWindow* win, fs::path file, xoj::util::move_only_function<void(const fs::path&)> writeToFile); };
3,672
C++
.h
78
39.705128
117
0.669461
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,691
PopupWindowWrapper.h
xournalpp_xournalpp/src/util/include/util/PopupWindowWrapper.h
/* * Xournal++ * * PopupWindow base class * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #include <memory> #include <gtk/gtk.h> #include "util/Assert.h" #include "util/gtk4_helper.h" namespace xoj::popup { /** * @brief The class PopupWindowWrapper allows a safe non-blocking creation and display of a popup window. * It shows the popup (upon a call to show()) and tasks a callback function to actually delete the popup once it has * been closed by the user. */ template <class PopupType> class PopupWindowWrapper { public: PopupWindowWrapper() = delete; PopupWindowWrapper(const PopupWindowWrapper&) = delete; PopupWindowWrapper(PopupWindowWrapper&&) = delete; template <class... Args> PopupWindowWrapper(Args&&... args) { popup = new PopupType(std::forward<Args>(args)...); } ~PopupWindowWrapper() { delete popup; } void show(GtkWindow* parent) { gtk_window_set_transient_for(popup->getWindow(), parent); gtk_window_set_modal(popup->getWindow(), true); #if GTK_MAJOR_VERSION == 3 gtk_window_set_position(popup->getWindow(), GTK_WIN_POS_CENTER_ON_PARENT); gtk_widget_show(GTK_WIDGET(popup->getWindow())); g_signal_connect(popup->getWindow(), "delete-event", G_CALLBACK(+[](GtkWidget*, GdkEvent*, gpointer popup) -> gboolean { delete reinterpret_cast<PopupType*>(popup); return true; // Block the default callback: we destroy the window via ~GtkWindowUPtr() }), popup); #else gtk_widget_show(GTK_WIDGET(popup->getWindow())); g_signal_connect(popup->getWindow(), "close-request", G_CALLBACK(+[](GtkWindow*, gpointer popup) -> gboolean { delete reinterpret_cast<PopupType*>(popup); return true; // Block the default callback: we destroy the window via ~GtkWindowUPtr() }), popup); #endif /* * The actual popup must outlive this wrapper (so the main loop can go on). * As a consequence, once the popup is shown, this wrapper does not own the popup anymore. * The popup will get destroy by the signal connected above. */ popup = nullptr; } PopupType* getPopup() const { xoj_assert_message(popup, "Do not call getPopup() after show()!"); return popup; } private: PopupType* popup = nullptr; }; }; // namespace xoj::popup
2,633
C++
.h
67
31.641791
118
0.62686
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,692
LoopUtil.h
xournalpp_xournalpp/src/util/include/util/LoopUtil.h
/* * Xournal++ * * Utility for loops * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #include <algorithm> #include <iterator> #include <utility> /** * for_first_then_each * loop over the container from begin to end but handles the first element * differently. */ template <typename Container, typename Fun1, typename Fun2> void for_first_then_each(Container&& c, Fun1 f1, Fun2&& f2) { auto begi = begin(c); auto endi = end(c); if (begi == endi) return; f1(*begi); std::for_each(std::next(begi), endi, std::forward<Fun2&&>(f2)); };
643
C++
.h
28
20.392857
74
0.676471
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,693
Interval.h
xournalpp_xournalpp/src/util/include/util/Interval.h
/* * Xournal++ * * A interval data structure over a numeric data type. * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #include <algorithm> #include <optional> /** * @brief A templated class for (half open) intervals (a,b] */ template <class T> class Interval { public: /** * The interval bounds. * * Do not change the order: the class IntervalIteratable below relies on it. */ T min{}; T max{}; Interval() = default; /** * @brief Initialize the interval to (min,max] * @param min the lower bound * @param max the upper bound */ Interval(const T& min, const T& max): min(min), max(max) {} /** * @brief Get the interval (a,b] or (b,a], depending on which is greater * @param a One bound * @param b The other bound * @return The interval */ static inline Interval getInterval(const T& a, const T& b) { return a < b ? Interval(a, b) : Interval(b, a); } /** * @brief Computes the convex envelop of this and the other interval * @param other The other interval */ [[maybe_unused]] void envelop(const Interval& other) { min = std::min(min, other.min); max = std::max(max, other.max); } /** * @brief Computes the convex envelop of this and another value * @param t The other value */ [[maybe_unused]] void envelop(const T& t) { max = std::max(max, t); min = std::min(min, t); } /** * @brief Test if this interval contains a value * @param t The value * @return true if t lies in *this, false otherwise */ [[maybe_unused]] bool contains(const T& t) const { return t > min && t <= max; } /** * @brief Test if this interval is contained in another * @param other The other interval * @return true if *this lies inside other, false otherwise */ [[maybe_unused]] bool isContainedIn(const Interval& other) const { return min >= other.min && max <= other.max; } /** * @brief Test if this interval intersects another * @param other The other interval * @return true if *this and other intersect, false otherwise */ [[maybe_unused]] std::optional<Interval<T>> intersect(const Interval& other) const { double newMin = std::max(min, other.min); double newMax = std::min(max, other.max); return (newMin < newMax) ? std::optional(Interval(newMin, newMax)) : std::nullopt; } /** * @brief Compute the length of the interval * @return The length */ [[maybe_unused]] T length() const { return max - min; } bool operator==(const Interval<T>& other) const { return min == other.min && max == other.max; } bool operator!=(const Interval<T>& other) const { return min != other.min || max != other.max; } /** * Lexicographic order for intervals */ bool operator<=(const Interval<T>& other) const { return min < other.min || (min == other.min && max <= other.max); } bool operator>=(const Interval<T>& other) const { return other <= *this; } bool operator<(const Interval<T>& other) const { return !(other <= *this); } bool operator>(const Interval<T>& other) const { return !(*this <= other); } };
3,329
C++
.h
95
29.915789
117
0.620925
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,694
move_only_function.h
xournalpp_xournalpp/src/util/include/util/move_only_function.h
/* * Xournal++ * * Rudimentary port of C++23's std::move_only_function * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #include <functional> #include <memory> #include <type_traits> #include <utility> namespace xoj::util { template <class T> class move_only_function final {}; /** * Rudimentary implementation of C++23's std::move_only_function * * Specialization of std::swap and bool operator==(const move_only_function&, std::nullptr_t) are not implemented. * Add them if required. */ template <class R, class... Args> class move_only_function<R(Args...)> final { public: move_only_function() = default; move_only_function(move_only_function&& f) = default; move_only_function& operator=(move_only_function&& f) = default; move_only_function(const move_only_function&) = delete; move_only_function& operator=(const move_only_function&) = delete; move_only_function& operator=(std::nullptr_t) { invoke = nullptr; callable.reset(); } operator bool() const { return static_cast<bool>(invoke) && static_cast<bool>(callable); } R operator()(Args... args) const { if (!invoke || !callable) { throw std::bad_function_call(); } return invoke(callable.get(), std::forward<Args>(args)...); } private: template <class F, class... FArgs> void bind(FArgs&&... fargs) { invoke = +[](void* p, Args... args) -> R { return (*static_cast<F*>(p))(std::forward<Args>(args)...); }; callable = {new F(std::forward<FArgs>(fargs)...), [](void* pf) { delete static_cast<F*>(pf); }}; }; public: template <class F, std::enable_if_t<!std::is_same_v<std::decay_t<F>, move_only_function>, bool> = true, std::enable_if_t<std::is_same_v<R, void> || std::is_convertible_v<std::invoke_result_t<F, Args...>, R>, bool> = true> move_only_function(F&& f) { bind<std::decay_t<F>>(std::forward<F>(f)); } private: std::unique_ptr<void, void (*)(void*)> callable{nullptr, +[](void*) {}}; void (*invoke)(void*, Args...) = nullptr; }; } // namespace xoj::util
2,203
C++
.h
61
31.590164
117
0.62746
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,695
DispatchPool.h
xournalpp_xournalpp/src/util/include/util/DispatchPool.h
/* * Xournal++ * * Template class for a dispatch pool and listeners * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #include <algorithm> #include <memory> #include <utility> #include <vector> #include "util/Assert.h" namespace xoj::util { /** * @brief Utility class for dispatching a method call to multiple "listeners". * * The listeners must implement functions * void on(Arg&&...); * that the dispatcher will call through dispatch() and/or functions * void deleteOn(Arg&&...); * that the dispatcher will call through dispatchAndClear(); * * The `on()`s must not delete the listener, or even remove it from the pool. * The `deleteOn()`s must make sure the listener no longer references the pool (for instance by deleting the listener) */ template <class ListenerT> class DispatchPool final { public: using listener_type = ListenerT; /** * @brief Invokes the `on()` method of all registered `ListenerT`s. */ template <typename... Args> void dispatch(Args&&... args) const { for (auto* v: this->pool) { v->on(std::forward<Args>(args)...); } } /** * @brief Invokes the `deleteOn()` method of all registered `ListenerT`s and clears the pool. * A call to v->deleteOn() is supposed to delete the listener v * (or at the very least remove any reference to the dispatcher in the listener v) */ template <typename... Args> void dispatchAndClear(Args&&... args) const { // We cannot iterate on the this->pool: the listener's deletion would trigger calls to DispatchPool::remove() // leading to possible segfaults. auto p = std::move(this->pool); for (auto* v: p) { v->deleteOn(std::forward<Args>(args)...); } } /** * @brief Adds a new listener to the pool. * The listener must not already be registered. */ void add(listener_type* v) { xoj_assert_message(v != nullptr, "Adding nullptr listener"); xoj_assert_message(std::find(this->pool.begin(), this->pool.end(), v) == this->pool.end(), "Listener is already listed"); this->pool.emplace_back(v); } void remove(listener_type* v) { xoj_assert_message(v != nullptr, "Removing nullptr listener"); auto it = std::find(this->pool.begin(), this->pool.end(), v); if (it != this->pool.end()) { this->pool.erase(it); } } [[nodiscard]] bool empty() const { return pool.empty(); } [[nodiscard]] const listener_type& front() const { return *pool.front(); } private: std::vector<listener_type*> pool; }; /** * @brief CRTP-style class for listener * Usage: * class A: Listener<A> { * (virtual) ~A() { unregisterFromPool(); } * void on(...); // Signal receiver * }; * * WARNING: Always unregisterFromPool() in derived class destructor. * * For listening to several type of dispatchers do: * class A : public Listener<A> {...}; // virtual void on(...); in here * class B : public Listener<B> {...}; // virtual void on(...); in here - types must differ from the ones in A * class C : public A, public B {...}; // overload everything here */ template <class T> class Listener { private: // Keep the constructor private: only T can inherit Listener<T> (for the static_cast<T*>(this) below). Listener() = default; friend T; using pool_type = xoj::util::DispatchPool<T>; public: /** * @brief Register to a new dispatch pool. Unregisters from any pool the listener was previously registered to. */ void registerToPool(const std::shared_ptr<pool_type>& newpool) { if (auto p = this->pool.lock()) { p->remove(static_cast<T*>(this)); } newpool->add(static_cast<T*>(this)); this->pool = newpool; } /** * @brief Unregisters from the current pool (if any). */ void unregisterFromPool() { if (auto p = this->pool.lock()) { p->remove(static_cast<T*>(this)); } this->pool.reset(); } [[nodiscard]] auto getPool() const -> std::shared_ptr<pool_type> { return this->pool.lock(); } private: std::weak_ptr<pool_type> pool; }; }; // namespace xoj::util
4,352
C++
.h
125
29.92
118
0.627078
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,696
i18n.h
xournalpp_xournalpp/src/util/include/util/i18n.h
/* * Xournal++ * * Internationalization module * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #include <libintl.h> #include "PlaceholderString.h" #undef snprintf #define _(msg) gettext(msg) #define C_(context, msg) g_dpgettext2(nullptr, context, msg) /// The string is not looked for by xgettext and should be added to the .po files another way (e.g. with N_ below) #define fetch_translation(msg) gettext(msg) #define fetch_translation_context(context, msg) g_dpgettext2(nullptr, context, msg) // Formatted Translation #define _F(msg) PlaceholderString(_(msg)) #define C_F(context, msg) PlaceholderString(C_(context, msg)) // Formatted, not translated text #define FORMAT_STR(msg) PlaceholderString(msg) // No translation performed, but in the Translation string // So translation can be loaded dynamically at other place // in the code #define N_(msg) (msg) #define NC_(context, msg) (msg) /* Some helper macros */ // PlaceholderString → std::string #define FS(format) (format).str() // PlaceholderString → const char* #define FC(format) FS(format).c_str()
1,151
C++
.h
34
32.147059
114
0.753176
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,697
EnumIndexedArray.h
xournalpp_xournalpp/src/util/include/util/EnumIndexedArray.h
/* * Xournal++ * * An array indexed by a CONTIGUOUS scoped enum from 0 to ENUMERATOR_COUNT-1 * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #include <array> #include <type_traits> #include "util/Assert.h" #include "util/safe_casts.h" // for to_underlying Todo(cpp20) use <utility> template <class T, typename enum_class, std::enable_if_t<std::is_enum_v<enum_class> && std::is_unsigned_v<std::underlying_type_t<enum_class>> && !std::is_convertible_v<enum_class, std::underlying_type_t<enum_class>>, bool> = true> class EnumIndexedArray: private std::array<T, xoj::to_underlying(enum_class::ENUMERATOR_COUNT)> { public: using underlying_array_type = std::array<T, xoj::to_underlying(enum_class::ENUMERATOR_COUNT)>; T& operator[](enum_class value) { xoj_assert(value < enum_class::ENUMERATOR_COUNT); return underlying_array_type::operator[](xoj::to_underlying(value)); } const T& operator[](enum_class value) const { xoj_assert(value < enum_class::ENUMERATOR_COUNT); return underlying_array_type::operator[](xoj::to_underlying(value)); } using underlying_array_type::begin; using underlying_array_type::end; };
1,325
C++
.h
33
34.69697
114
0.670295
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,698
ElementRange.h
xournalpp_xournalpp/src/util/include/util/ElementRange.h
/* * Xournal++ * * A page range for PDF export etc. (e.g. 1-2,5,7) * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #include <cstddef> // for size_t #include <string> // for string #include <vector> // for vector struct ElementRangeEntry { ElementRangeEntry() = default; // pre c++20 requirement ElementRangeEntry(size_t first, size_t last): first(first), last(last) {} // pre c++20 requirement size_t first{}; size_t last{}; }; using ElementRangeVector = std::vector<ElementRangeEntry>; namespace ElementRange { ElementRangeVector parse(const std::string& str, size_t maxCount); }; // namespace ElementRange /** * Aliases for page and layer ranges */ using PageRangeEntry = ElementRangeEntry; using PageRangeVector = ElementRangeVector; using LayerRangeEntry = ElementRangeEntry; using LayerRangeVector = ElementRangeVector;
977
C++
.h
31
29.451613
103
0.703191
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,699
SmallVector.h
xournalpp_xournalpp/src/util/include/util/SmallVector.h
/* * Xournal++ * * A small-vector-optimized data structure, with data in the stack when it's small enough, in the heap otherwise * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #include <algorithm> #include <cstddef> #include <initializer_list> #include <iterator> #include <memory> #include <utility> #include <vector> #include "util/Assert.h" #include "BasePointerIterator.h" #include "TinyVector.h" /** * @brief A small-vector-optimized data structure, with data in the stack when it's small enough, in the heap otherwise * If the size of the container often passes from > N to <= N and vice-versa, don't use this class (or pick a better N) * This would result in a lot of unnecessary data moves between stack and heap, thus poorer performance. */ template <class T, size_t N> class SmallVector { public: using size_type = size_t; using value_type = T; using reference = T&; using iterator = BasePointerIterator<T, false>; using const_iterator = BasePointerIterator<T, true>; using difference_type = ptrdiff_t; SmallVector() = default; ~SmallVector() { if (nb <= N) { dataArrayClear(); } } SmallVector(const SmallVector& other) { if (other.size() > N) { // Avoid moving from stack to heap dataVector = other.dataVector; } else { std::uninitialized_copy(other.begin(), other.end(), dataArray.data()); } nb = other.size(); } SmallVector(SmallVector&& other) { if (other.size() > N) { dataVector = std::move(other.dataVector); nb = other.size(); other.nb = 0; } else { std::uninitialized_move(other.begin(), other.end(), dataArray.data()); nb = other.size(); other.clear(); } } SmallVector& operator=(const SmallVector& other) { if (this == &other) { return *this; } clear(); if (other.size() > N) { // Avoid moving from stack to heap dataVector = other.dataVector; } else { std::uninitialized_copy(other.begin(), other.end(), dataArray.data()); } nb = other.size(); return *this; } SmallVector& operator=(SmallVector&& other) { if (this == &other) { return *this; } clear(); if (other.size() > N) { dataVector = std::move(other.dataVector); nb = other.size(); other.nb = 0; } else { std::uninitialized_move(other.begin(), other.end(), dataArray.data()); nb = other.size(); other.clear(); } return *this; } SmallVector(std::initializer_list<T> list) { nb = static_cast<size_type>(list.size()); if (nb <= N) { std::uninitialized_move(list.begin(), list.end(), dataArray.data()); } else { dataVector = list; //{list.begin(), list.end()}; } } SmallVector& operator=(std::initializer_list<T> list) { clear(); nb = static_cast<size_type>(list.size()); if (nb <= N) { std::uninitialized_move(list.begin(), list.end(), dataArray.data()); } else { dataVector = list; //{list.begin(), list.end()}; } return *this; } size_type size() const { return nb; } bool empty() const { return nb == 0; } T& operator[](size_type pos) { return nb <= N ? dataArray[pos] : dataVector[pos]; } const T& operator[](size_type pos) const { return nb <= N ? dataArray[pos] : dataVector[pos]; } T& front() { return nb <= N ? *dataArray.data() : dataVector.front(); } const T& front() const { return nb <= N ? *dataArray.data() : dataVector.front(); } T& back() { return nb <= N ? *(dataArray.data() + nb - 1) : dataVector.back(); } const T& back() const { return nb <= N ? *(dataArray.data() + nb - 1) : dataVector.back(); } T* data() { return nb <= N ? dataArray.data() : dataVector.data(); } const T* data() const { return nb <= N ? dataArray.data() : dataVector.data(); } iterator begin() { return nb <= N ? dataArray.data() : dataVector.data(); } const_iterator begin() const { return nb <= N ? dataArray.data() : dataVector.data(); } iterator end() { return nb <= N ? dataArray.data() + nb : dataVector.data() + nb; } const_iterator end() const { return nb <= N ? dataArray.data() + nb : dataVector.data() + nb; } template <class... Args> void emplace_back(Args&&... args) { if (nb < N) { ::new (&dataArray[nb]) T(std::forward<Args>(args)...); } else if (nb == N) { xoj_assert(end() == begin() + N); dataVector.reserve(N + 1); std::move(dataArrayBegin(), dataArrayEnd(), std::back_inserter(dataVector)); dataArrayClear(); dataVector.emplace_back(std::forward<Args>(args)...); } else { dataVector.emplace_back(std::forward<Args>(args)...); } ++nb; } void push_back(const T& value) { emplace_back(value); } void push_back(T&& value) { emplace_back(std::move(value)); } void pop_back() { if (nb > N) { if (nb == N + 1) { std::uninitialized_move(dataVector.begin(), std::prev(dataVector.end()), dataArray.data()); dataVector = std::vector<value_type>(0); } else { dataVector.pop_back(); } } else { xoj_assert(nb != 0); std::destroy_at(dataArray.data() + nb - 1); } --nb; } void clear() { if (nb > N) { dataVector = std::vector<value_type>(0); } else { dataArrayClear(); } nb = 0; } void swap(SmallVector& other) { if (nb > N) { dataVector.swap(other.dataVector); if (other.nb <= N) { // Handle stack data std::uninitialized_move(other.dataArrayBegin(), other.dataArrayEnd(), dataArray.data()); other.dataArrayClear(); } std::swap(nb, other.nb); return; } if (other.nb > N) { dataVector.swap(other.dataVector); std::uninitialized_move(dataArrayBegin(), dataArrayEnd(), other.dataArray.data()); dataArrayClear(); std::swap(nb, other.nb); return; } // Both in stack if (nb < other.nb) { iterator it = std::swap_ranges(dataArrayBegin(), dataArrayEnd(), other.dataArray.data()); std::uninitialized_move(it, other.dataArrayEnd(), dataArrayEnd()); std::destroy(it, other.dataArrayEnd()); } else { iterator it = std::swap_ranges(other.dataArrayBegin(), other.dataArrayEnd(), dataArray.data()); std::uninitialized_move(it, dataArrayEnd(), other.dataArrayEnd()); std::destroy(it, dataArrayEnd()); } std::swap(nb, other.nb); } private: iterator dataArrayBegin() { return dataArray.data(); } iterator dataArrayEnd() { xoj_assert(nb <= N); return dataArray.data() + nb; } void dataArrayClear() { std::destroy(dataArrayBegin(), dataArrayEnd()); } UninitializedStorage<T, N> dataArray{}; std::vector<T> dataVector{}; size_type nb = 0; }; namespace std { template <typename T, size_t N> void swap(SmallVector<T, N>& a, SmallVector<T, N>& b) { a.swap(b); } } // namespace std
7,653
C++
.h
208
28.8125
119
0.56181
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,700
TinyVector.h
xournalpp_xournalpp/src/util/include/util/TinyVector.h
/* * Xournal++ * * A tiny vector stored in the stack, with a small maximal size * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #include <algorithm> #include <array> #include <cstddef> #include <iterator> #include <memory> #include <type_traits> #include <utility> #include "util/Assert.h" #include "BasePointerIterator.h" template <class T, size_t N> class UninitializedStorage { public: using size_type = size_t; using value_type = T; using reference = T&; T& operator[](size_type pos) { return *std::launder(reinterpret_cast<T*>(&dataArray[pos])); } const T& operator[](size_type pos) const { return *std::launder(reinterpret_cast<const T*>(&dataArray[pos])); } T* data() { return std::launder(reinterpret_cast<T*>(dataArray.data())); } const T* data() const { return std::launder(reinterpret_cast<const T*>(dataArray.data())); } protected: std::array<typename std::aligned_storage<sizeof(T), alignof(T)>::type, N> dataArray; }; template <class T, size_t N> class TinyVector: public UninitializedStorage<T, N> { public: using size_type = size_t; using value_type = T; using reference = T&; using iterator = BasePointerIterator<T, false>; using const_iterator = BasePointerIterator<T, true>; using difference_type = ptrdiff_t; TinyVector() = default; ~TinyVector() { std::destroy(begin(), end()); } TinyVector(const TinyVector& other) { std::copy(other.begin(), other.end(), std::back_inserter(*this)); } TinyVector(TinyVector&& other) { std::move(other.begin(), other.end(), std::back_inserter(*this)); other.clear(); } TinyVector& operator=(const TinyVector& other) { if (this == &other) { return *this; } clear(); std::copy(other.begin(), other.end(), std::back_inserter(*this)); return *this; } TinyVector& operator=(TinyVector&& other) { if (this == &other) { return *this; } clear(); std::move(other.begin(), other.end(), std::back_inserter(*this)); other.clear(); return *this; } size_type size() const { return nb; } bool empty() const { return nb == 0; } T& front() { return *UninitializedStorage<T, N>::data(); } const T& front() const { return *UninitializedStorage<T, N>::data(); } T& back() { return *(UninitializedStorage<T, N>::data() + nb - 1); } const T& back() const { return *(UninitializedStorage<T, N>::data() + nb - 1); } template <class... Args> void emplace_back(Args&&... args) { xoj_assert(nb < N); ::new (&UninitializedStorage<T, N>::dataArray[nb++]) T(std::forward<Args>(args)...); } void push_back(const T& value) { emplace_back(value); } void push_back(T&& value) { emplace_back(std::move(value)); } void pop_back() { xoj_assert(nb != 0); std::destroy_at(&back()); nb--; } void clear() { std::destroy(begin(), end()); nb = 0; } void erase_from(const iterator& first) { std::destroy(first, end()); nb = static_cast<size_type>(std::distance(begin(), first)); } void swap(TinyVector& other) { if (nb < other.nb) { iterator it = std::swap_ranges(begin(), end(), other.begin()); std::move(it, other.end(), std::back_inserter(*this)); other.erase_from(it); } else { iterator it = std::swap_ranges(other.begin(), other.end(), begin()); std::move(it, end(), std::back_inserter(other)); erase_from(it); } } iterator begin() { return UninitializedStorage<T, N>::data(); } const_iterator begin() const { return UninitializedStorage<T, N>::data(); } iterator end() { return UninitializedStorage<T, N>::data() + nb; } const_iterator end() const { return UninitializedStorage<T, N>::data() + nb; } private: size_type nb = 0; }; namespace std { template <typename T, size_t N> void swap(TinyVector<T, N>& a, TinyVector<T, N>& b) { a.swap(b); } } // namespace std
4,164
C++
.h
116
30.456897
115
0.612903
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,701
PlaceholderString.h
xournalpp_xournalpp/src/util/include/util/PlaceholderString.h
/* * Xournal++ * * Internationalization module * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ // Todo(fabian): replace with cpp20 format library or https://github.com/fmtlib/fmt which are the same // also using python like format string syntax #pragma once #include <cstddef> // for size_t #include <cstdint> // for int64_t #include <memory> // for unique_ptr #include <ostream> // for ostream #include <string> // for string #include <utility> // for move #include <vector> // for vector #include <glib.h> // for g_error /** * Base class for Formatting */ class PlaceholderElement { public: virtual ~PlaceholderElement() = default; PlaceholderElement() = default; PlaceholderElement(PlaceholderElement const& p) = default; PlaceholderElement(PlaceholderElement&& p) = default; PlaceholderElement& operator=(PlaceholderElement const&) = default; PlaceholderElement& operator=(PlaceholderElement&&) = default; virtual auto format(std::string format) const -> std::string = 0; }; /** * Format String */ class PlaceholderElementString: public PlaceholderElement { public: explicit PlaceholderElementString(std::string_view text): text(text) {} auto format(std::string format) const -> std::string override { return text; } private: std::string text; }; /** * Format int */ template <typename T> class PlaceholderElementInt: public PlaceholderElement { public: explicit PlaceholderElementInt(T value): value(value) {} auto format(std::string format) const -> std::string override { return std::to_string(value); } private: T value; }; /** * Placeholder String, used for formatting. Support Placeholder like * {1}, {2} etc. Use {{ for { */ struct PlaceholderString { PlaceholderString(std::string text); // Placeholder methods template <typename T> auto operator%(T value) -> PlaceholderString& { if constexpr (std::is_integral_v<T>) { data.emplace_back(std::make_unique<PlaceholderElementInt<T>>(value)); } else { data.emplace_back(std::make_unique<PlaceholderElementString>(std::move(value))); } return *this; } // Process Method std::string str() const; const char* c_str() const; // NOLINT(readability-identifier-naming) private: std::string formatPart(std::string format) const; void process() const; /** * Values for Placeholder */ std::vector<std::unique_ptr<PlaceholderElement>> data; /** * Input text */ std::string text; /** * Processed String */ mutable std::string processed; }; std::ostream& operator<<(std::ostream& os, PlaceholderString& ps);
2,776
C++
.h
91
26.857143
102
0.692568
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,702
GtkUtil.h
xournalpp_xournalpp/src/util/include/util/GtkUtil.h
/* * Xournal++ * Helper function for setting up some GtkWidget * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #include <gtk/gtk.h> namespace xoj::util::gtk { /** * @brief if `btn` has the GtkActionable properties action-name and action-target set, and a corresponding action has * been added to any ascendent's GActionMap, then make the ToggleButton to never be unset when clicking on it. Only * changing the action state can unset the button (e.g. by clicking on another button with the same action but a * different state). */ void setToggleButtonUnreleasable(GtkToggleButton* btn); /** * @brief Make so a widget is automatically enabled/disabled whenever the given action is */ void setWidgetFollowActionEnabled(GtkWidget* w, GAction* a); #if GTK_MAJOR_VERSION == 3 /** * @brief RadioButton's and GAction don't work as expected in GTK3: * * Without setting the group, the RadioButtons are simply always ticked (all of them) * * With the group properly set, when a RadioButton is "un-selected" (because we selected another one), it still * changes the GAction's state (it should only do that when being selected). This leads to infinite callback loops * * To circumvent this, we make our own GAction/RadioButton interactions. Don't forget to group the buttons together. */ void setRadioButtonActionName(GtkRadioButton* btn, const char* actionNamespace, const char* actionName); /** * @brief some Gtk3 GtkActionable implementations (e.g. GtkMEnuItem) do not set their sensitivity properly on startup * Fixes that */ void fixActionableInitialSensitivity(GtkActionable* w); #endif }; // namespace xoj::util::gtk
1,714
C++
.h
40
41.075
117
0.770384
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,703
gtk4_helper.h
xournalpp_xournalpp/src/util/include/util/gtk4_helper.h
/* * Xournal++ * * header for missing gtk4 functions (part of the gtk4 port) * will be removed later * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #include <gtk/gtk.h> /**** GtkBox ****/ void gtk_box_append(GtkBox* box, GtkWidget* child); void gtk_box_prepend(GtkBox* box, GtkWidget* child); void gtk_box_remove(GtkBox* box, GtkWidget* child); /**** GtkWindow ****/ void gtk_window_destroy(GtkWindow* win); /**** GtkWidget ****/ void gtk_widget_add_css_class(GtkWidget* widget, const char* css_class); void gtk_widget_remove_css_class(GtkWidget* widget, const char* css_class); int gtk_widget_get_width(GtkWidget* widget); GtkClipboard* gtk_widget_get_clipboard(GtkWidget* widget); /*** GtkDrawingArea ****/ typedef void (*GtkDrawingAreaDrawFunc)(GtkDrawingArea* drawing_area, cairo_t* cr, int width, int height, gpointer user_data); /// WARNING: unsetting (via draw_func = nullptr) or replacing the function is not implemented here. void gtk_drawing_area_set_draw_func(GtkDrawingArea* area, GtkDrawingAreaDrawFunc draw_func, gpointer user_data, GDestroyNotify destroy); /**** GtkScale ****/ typedef char* (*GtkScaleFormatValueFunc)(GtkScale* scale, double value, gpointer user_data); /// WARNING: unsetting (via func = nullptr) or replacing the function is not implemented here. void gtk_scale_set_format_value_func(GtkScale* scale, GtkScaleFormatValueFunc func, gpointer user_data, GDestroyNotify destroy_notify); /**** GtkScrolledWindow ****/ GtkWidget* gtk_scrolled_window_new(); void gtk_scrolled_window_set_child(GtkScrolledWindow* win, GtkWidget* child); GtkWidget* gtk_scrolled_window_get_child(GtkScrolledWindow* win); /**** GtkCheckButton ****/ void gtk_check_button_set_child(GtkCheckButton* button, GtkWidget* child); void gtk_check_button_set_label(GtkCheckButton* button, const char* label); bool gtk_check_button_get_active(GtkCheckButton* bt); void gtk_check_button_set_active(GtkCheckButton* bt, bool state); /**** GtkButton ****/ void gtk_button_set_child(GtkButton* button, GtkWidget* child); GtkWidget* gtk_button_get_child(GtkButton* button); void gtk_button_set_icon_name(GtkButton* button, const char* iconName); /**** GtkPopover ****/ GtkWidget* gtk_popover_new(); void gtk_popover_set_child(GtkPopover* popover, GtkWidget* child); GtkWidget* gtk_popover_menu_new_from_model(GMenuModel* model); /**** GtkLabel ****/ void gtk_label_set_wrap(GtkLabel* label, gboolean wrap); void gtk_label_set_wrap_mode(GtkLabel* label, PangoWrapMode wrap_mode); /**** GtkIMContext ****/ void gtk_im_context_set_client_widget(GtkIMContext* context, GtkWidget* widget); /**** GtkFileChooserDialog ****/ gboolean gtk_file_chooser_add_shortcut_folder(GtkFileChooser* chooser, GFile* file, GError** error); gboolean gtk_file_chooser_set_current_folder(GtkFileChooser* chooser, GFile* file, GError** error); /**** GtkFixed ****/ void gtk_fixed_remove(GtkFixed* fixed, GtkWidget* child); /**** GtkListBox ****/ void gtk_list_box_append(GtkListBox* box, GtkWidget* widget); void gtk_list_box_row_set_child(GtkListBoxRow* row, GtkWidget* w); GtkWidget* gtk_list_box_row_get_child(GtkListBoxRow* row); /**** GtkEventController ****/ GdkEvent* gtk_event_controller_get_current_event(GtkEventController*);
3,420
C++
.h
68
47.102941
111
0.734135
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,704
Util.h
xournalpp_xournalpp/src/util/include/util/Util.h
/* * Xournal++ * * Xournal util functions * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #include <cstdlib> // size_t #include <functional> // for function #include <limits> // for numeric_limits #include <utility> #include <cairo.h> // for cairo_t #include <glib.h> // for G_PRIORITY_DEFAULT_IDLE, gboolean, gchar, gint #include <gtk/gtk.h> // for GtkWidget #include "util/glib_casts.h" #include "Point.h" class OutputStream; namespace Util { #if defined(_MSC_VER) using PID = uint32_t; // DWORD #else using PID = int32_t; // pid #endif auto getPid() -> PID; /** * Wrap the system call to redirect errors to a dialog */ void systemWithMessage(const char* command); /** * Check if currently running in a Flatpak sandbox */ bool isFlatpakInstallation(); /** * Execute the callback in the UI Thread. * * Make sure the container class is not deleted before the UI stuff is finished! */ template <typename Fun> void execInUiThread(Fun&& callback, gint priority = G_PRIORITY_DEFAULT_IDLE) { if constexpr (std::is_function_v<Fun>) { gdk_threads_add_idle_full(priority, std::forward<Fun>(callback), nullptr, nullptr); } else { constexpr auto fn = +[](gpointer functor) -> int { auto fun = static_cast<Fun*>(functor); (*fun)(); return G_SOURCE_REMOVE; }; gdk_threads_add_idle_full(priority, fn, new auto(std::forward<Fun>(callback)), &xoj::util::destroy_cb<Fun>); } } gboolean paintBackgroundWhite(GtkWidget* widget, cairo_t* cr, void* unused); void cairo_set_dash_from_vector(cairo_t* cr, const std::vector<double>& dashes, double offset); /** * Transform absolute coordinates into coordinates local to the specified widget. * The top left corner of `widget` will have coordinates (0, 0). */ xoj::util::Point<double> toWidgetCoords(GtkWidget* widget, xoj::util::Point<double> absolute_coords); /** * Format coordinates to use 8 digits of precision https://m.xkcd.com/2170/ * This function directly writes to the given OutputStream. */ extern void writeCoordinateString(OutputStream* out, double xVal, double yVal); constexpr const gchar* PRECISION_FORMAT_STRING = "%.8g"; constexpr const auto DPI_NORMALIZATION_FACTOR = 72.0; } // namespace Util constexpr auto npos = std::numeric_limits<size_t>::max();
2,410
C++
.h
70
31.671429
116
0.709052
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,705
PairView.h
xournalpp_xournalpp/src/util/include/util/PairView.h
/* * Xournal++ * * C++20-like view to iterate on pairs of consecutive elements * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #include <array> #include <iterator> #include <type_traits> #include "TypeIfThenElse.h" /** * @brief view to iterate on pairs of consecutive elements. The pairs overlap: * On an array x[N], you'll get the pairs (x[0],x[1]), (x[1],x[2]), ... , (x[n-2],x[n-1]) * @param contiguous_container_type Must be a contiguous container */ template <typename contiguous_container_type> class PairView { // C++ 20 // static_assert(is_same<typename std::iterator_traits<typename // contiguous_container_type::iterator>::iterator_category, contiguous_iterator_tag>::value, "">); public: using sub_value_type = typename contiguous_container_type::value_type; static_assert(!std::is_same<sub_value_type, bool>::value, "bool arrays are not contiguous"); using value_type = std::array<sub_value_type, 2>; PairView(contiguous_container_type& c): container(c){}; private: contiguous_container_type& container; template <bool is_const> class BaseIterator { public: using iterator_category = std::random_access_iterator_tag; using value_type = typename PairView::value_type; using qualified_value_type = typename const_if<value_type, is_const>::type; using qualified_sub_value_type = typename const_if<sub_value_type, is_const>::type; using pointer = qualified_value_type*; using reference = qualified_value_type&; using difference_type = std::ptrdiff_t; using container_iterator_type = typename type_or_type<typename contiguous_container_type::const_iterator, typename contiguous_container_type::iterator, is_const>::type; BaseIterator() = default; ~BaseIterator() = default; BaseIterator(const BaseIterator&) = default; BaseIterator(container_iterator_type it): it(it) {} reference operator*() const { return *reinterpret_cast<pointer>(&*it); } qualified_sub_value_type& first() const { return *it; } qualified_sub_value_type& second() const { return it[1]; } BaseIterator& operator++() { ++it; return *this; } BaseIterator operator++(int) { auto tmp = *this; ++it; return tmp; } BaseIterator& operator--() { --it; return *this; } BaseIterator operator--(int) { auto tmp = *this; --it; return tmp; } BaseIterator& operator+=(difference_type n) { it += n; return *this; } BaseIterator& operator-=(difference_type n) { it -= n; return *this; } BaseIterator operator+(difference_type n) const { return BaseIterator(std::next(it, n)); } BaseIterator operator-(difference_type n) const { return BaseIterator(std::prev(it, n)); } difference_type operator-(const BaseIterator& other) const { return std::distance(it, other.it); } reference operator[](difference_type n) const { return *(*this + n); } bool operator==(const BaseIterator& other) const { return it == other.it; } bool operator!=(const BaseIterator& other) const { return it != other.it; } bool operator<(const BaseIterator& other) const { return it < other.it; } bool operator>(const BaseIterator& other) const { return other < *this; } bool operator<=(const BaseIterator& other) const { return !(other < *this); } bool operator>=(const BaseIterator& other) const { return !(*this < other); } friend BaseIterator operator+(difference_type n, BaseIterator& it) { return it + n; } private: container_iterator_type it; }; using const_iterator = BaseIterator<true>; using iterator = BaseIterator<false>; public: const_iterator begin() const { return const_iterator(container.begin()); } template <class T = contiguous_container_type, std::enable_if_t<!std::is_const<T>::value, int> = 0> iterator begin() { return iterator(container.begin()); } const_iterator end() const { if (container.empty()) { return begin(); } return const_iterator(std::prev(container.end())); } template <class T = contiguous_container_type, std::enable_if_t<!std::is_const<T>::value, int> = 0> iterator end() { if (container.empty()) { return begin(); } return iterator(std::prev(container.end())); } };
4,748
C++
.h
114
34.140351
106
0.627952
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,706
TypeIfThenElse.h
xournalpp_xournalpp/src/util/include/util/TypeIfThenElse.h
/* * Xournal++ * * Helper structures to get various types depending on a boolean value * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once /** * @brief Get `const T` if the boolean is true, `T` otherwise */ template <typename T, bool> struct const_if { using type = T; }; template <typename T> struct const_if<T, true> { using type = const T; }; /** * @brief Get `T` if the boolean is true, `U` otherwise */ template <typename T, typename U, bool> struct type_or_type { using type = T; }; template <typename T, typename U> struct type_or_type<T, U, false> { using type = U; };
672
C++
.h
33
18.424242
70
0.679749
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,707
StringUtils.h
xournalpp_xournalpp/src/util/include/util/StringUtils.h
/* * Xournal++ * * String utilities * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #include <string> // for string, basic_string #include <utility> // for pair #include <vector> // for vector typedef std::pair<char, std::string> replace_pair; class StringUtils { public: static std::string toLowerCase(const std::string& input); static void replaceAllChars(std::string& input, const std::vector<replace_pair>& replaces); static std::vector<std::string> split(const std::string& input, char delimiter); static bool startsWith(const std::string& str, const std::string& start); static bool endsWith(const std::string& str, const std::string& end); static std::string ltrim(std::string str); static std::string rtrim(std::string str); static std::string trim(std::string str); static bool iequals(const std::string& a, const std::string& b); static bool isNumber(const std::string& input); };
1,017
C++
.h
28
33.428571
95
0.714721
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,708
glib_casts.h
xournalpp_xournalpp/src/util/include/util/glib_casts.h
/* * Xournal++ * * header for casting c++ callbacks into gtk callbacks * will be removed later * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #include <cstdint> #include <tuple> #include <type_traits> #include <glib-object.h> #include <glib.h> namespace xoj::util { namespace detail { template <typename F> struct FunctionTraits; template <typename R, typename... Args> struct FunctionTraits<R (&)(Args...)> { using Reference = R (&)(Args...); using RetType = R; using ArgTypes = std::tuple<Args...>; static constexpr std::size_t ArgCount = sizeof...(Args); template <std::size_t N> using NthArg = std::tuple_element_t<N, ArgTypes>; using FirstArg = NthArg<0>; using LastArg = NthArg<ArgCount - 1>; }; template <typename R, typename... Args> struct FunctionTraits<R (*)(Args...)> { using Pointer = R (*)(Args...); using RetType = R; using ArgTypes = std::tuple<Args...>; static constexpr std::size_t ArgCount = sizeof...(Args); template <std::size_t N> using NthArg = std::tuple_element_t<N, ArgTypes>; using FirstArg = NthArg<0>; using LastArg = NthArg<ArgCount - 1>; }; template <typename F, size_t... Is> constexpr auto indices_impl(F f, std::index_sequence<Is...>) { return f(std::integral_constant<size_t, Is>()...); } template <size_t N, typename F> constexpr auto indices(F f) { return indices_impl(f, std::make_index_sequence<N>()); } template <auto SrcFn, class ST, class... Args> constexpr auto callback_once_impl(Args... args, void* data) -> gboolean { SrcFn(args..., static_cast<ST>(data)); return G_SOURCE_REMOVE; } template <auto SrcFn, class R, class ST, class... Args> constexpr auto wrap_impl(Args... args, void* data) -> std::conditional_t<std::is_same_v<bool, R>, gboolean, R> { if constexpr (std::is_same_v<void, R>) { SrcFn(args..., static_cast<ST>(data)); return; } else if constexpr (std::is_same_v<bool, R>) { return SrcFn(args..., static_cast<ST>(data)) ? G_SOURCE_CONTINUE : G_SOURCE_REMOVE; } else { return SrcFn(args..., static_cast<ST>(data)); } } } // namespace detail /** * wrap a C++ function into a C / glib compatible callback function * for single execution. Usable for API's like g_timeout_add / g_idle_add */ template <auto SrcFn> constexpr auto wrap_for_once() -> auto { using namespace detail; using FTI = FunctionTraits<decltype(SrcFn)>; return indices<FTI::ArgCount - 1>([&](auto... Is) { return callback_once_impl<SrcFn, typename FTI::LastArg, std::tuple_element_t<Is, typename FTI::ArgTypes>...>; }); } template <auto SrcFn> constexpr inline auto wrap_for_once_v = wrap_for_once<SrcFn>(); /** * Generally wrap a C++ function into a C / glib compatible callback function. * Removes warnings for functionpointer casts due to UB without reinterpreting the functionpointer. * Preserves type checking behavior of the compiler. * Replaces bool return values with gboolean. * statically casts data pointer to the last argument type of the function. * Use this whenever you would cast a functionpointer to any callback function. */ template <auto SrcFn> constexpr auto wrap() -> auto { using namespace detail; using FTI = FunctionTraits<decltype(SrcFn)>; return indices<FTI::ArgCount - 1>([&](auto... Is) { return wrap_impl<SrcFn, typename FTI::RetType, typename FTI::LastArg, std::tuple_element_t<Is, typename FTI::ArgTypes>...>; }); } template <auto SrcFn> constexpr inline auto wrap_v = wrap<SrcFn>(); /** * wrap a C++ function into a C / glib compatible callback function, just like wrap, * but reinterpret casts the functionpointer to a GCallback, which can be used for dynamic callback dispatching. * For example all g_signal_connect*, functions. * This wrapper function must be used with caution, as the reinterpret cast removes all type checking capabilities of * the compiler. The signature of the wrapper, must match the signature of the callback function. * Possible improvements: add a template type parameter for the callback function signature, to check the signature of * the target callback. * Use this instead of G_CALLBACK */ template <auto SrcFn> inline auto const wrap_for_g_callback_v = G_CALLBACK(wrap_v<SrcFn>); template <typename T, std::enable_if_t<!std::is_same_v<T, void>, int> = 1> constexpr void destroy_cb(gpointer data) { delete static_cast<T*>(data); }; template <typename T, std::enable_if_t<!std::is_same_v<T, void>, int> = 1> constexpr void closure_notify_cb(gpointer data, GClosure*) { delete static_cast<T*>(data); }; #ifndef NDEBUG constexpr auto tester1(int*, double*, char*) -> bool { return true; } constexpr auto tester2(int*, double*, char*) -> uint64_t { return 1; } static_assert(std::is_same_v<decltype(wrap_for_once<tester1>()), gboolean (*)(int*, double*, void*)>); static_assert(std::is_same_v<decltype(wrap_for_once<tester2>()), gboolean (*)(int*, double*, void*)>); static_assert(std::is_same_v<decltype(wrap<tester1>()), gboolean (*)(int*, double*, void*)>); static_assert(std::is_same_v<decltype(wrap<tester2>()), uint64_t (*)(int*, double*, void*)>); #endif } // namespace xoj::util
5,304
C++
.h
130
37.792308
118
0.69637
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,709
OutputStream.h
xournalpp_xournalpp/src/util/include/util/OutputStream.h
/* * Xournal++ * * Output streams for writing * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #include <string> // for string #include <zlib.h> // for gzFile #include "filesystem.h" // for path class OutputStream { public: OutputStream(); virtual ~OutputStream(); public: void write(const char* str); void write(const std::string& str); virtual void write(const char* data, size_t len) = 0; virtual void close() = 0; }; class GzOutputStream: public OutputStream { public: GzOutputStream(fs::path file); ~GzOutputStream() override; public: void write(const char* data, size_t len) override; void close() override; const std::string& getLastError() const; private: gzFile fp = nullptr; std::string error; fs::path file; };
870
C++
.h
37
20.405405
57
0.692683
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,710
Stacktrace.h
xournalpp_xournalpp/src/util/include/util/Stacktrace.h
/* * Xournal++ * * Prints a Stacktrace * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #include <iostream> #include "filesystem.h" class Stacktrace { private: Stacktrace(); virtual ~Stacktrace(); public: static fs::path getExePath(); static void printStacktrace(); static void printStacktrace(std::ostream& stream); };
421
C++
.h
22
16.590909
54
0.713198
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,711
Color.h
xournalpp_xournalpp/src/util/include/util/Color.h
/* * Xournal++ * * Color utility, does color conversions * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #include <cstdint> // for uint32_t, uint8_t, uint16_t #include <cstring> // for size_t #include <functional> // for hash #include <iostream> // for istream, ostream, basic_istream<>::__istream_... #include <limits> // for numeric_limits #include <string> // for string #include <cairo.h> // for cairo_t #include <gdk/gdk.h> // for GdkRGBA struct ColorU8 { uint8_t red{}; uint8_t green{}; uint8_t blue{}; uint8_t alpha{}; constexpr ColorU8() = default; constexpr ColorU8(uint8_t r, uint8_t g, uint8_t b, uint8_t a = 0xffU): red(r), green(g), blue(b), alpha(a) {} constexpr explicit ColorU8(uint32_t val): // Legacy ordering for serdes: 0xAARRGGBB red(uint8_t((val >> 16U) & 0xffU)), green(uint8_t((val >> 8U) & 0xffU)), blue(uint8_t((val >> 0U) & 0xffU)), alpha(uint8_t((val >> 24U) & 0xffU)) {} constexpr explicit operator uint32_t() const { // Legacy ordering for serdes: 0xAARRGGBB uint32_t val = (uint32_t(red) << 16U) | (uint32_t(green) << 8U) | uint32_t(blue) | (uint32_t(alpha) << 24U); return val; } constexpr auto operator=(uint32_t rhs) -> ColorU8& { *this = ColorU8(rhs); return *this; } constexpr friend bool operator==(ColorU8 const& lhs, ColorU8 const& rhs) { return uint32_t(lhs) == uint32_t(rhs); } constexpr friend bool operator!=(ColorU8 const& lhs, ColorU8 const& rhs) { return uint32_t(lhs) != uint32_t(rhs); } constexpr friend bool operator<(ColorU8 const& lhs, ColorU8 const& rhs) { return uint32_t(lhs) < uint32_t(rhs); } constexpr friend bool operator==(ColorU8 const& lhs, uint32_t rhs) { return uint32_t(lhs) == rhs; } constexpr friend bool operator!=(ColorU8 const& lhs, uint32_t rhs) { return uint32_t(lhs) != rhs; } constexpr friend bool operator<(ColorU8 const& lhs, uint32_t rhs) { return uint32_t(lhs) < rhs; } inline friend std::ostream& operator<<(std::ostream& os, ColorU8 rhs) { return os << uint32_t(rhs); } inline friend std::istream& operator>>(std::istream& is, ColorU8& rhs) { uint32_t val{}; is >> val; rhs = val; return is; }; constexpr auto isLight() const -> bool { return uint32_t(red) + uint32_t(green) + uint32_t(blue) > 0x180U; } }; static_assert(sizeof(ColorU8) == sizeof(uint32_t), "Color is not 32 bit"); using Color = ColorU8; namespace std { template <> struct hash<Color> { size_t operator()(Color c) const noexcept { return uint32_t(c); } }; } // namespace std struct ColorU16 { uint16_t red{}; uint16_t green{}; uint16_t blue{}; uint16_t alpha{}; }; inline std::ostream& operator<<(std::ostream& os, ColorU16 rhs) { return os << rhs.red << rhs.green << rhs.blue << rhs.alpha; } inline std::istream& operator>>(std::istream& is, ColorU16& rhs) { return is >> rhs.red >> rhs.green >> rhs.blue >> rhs.alpha; } namespace Util { constexpr auto rgb_to_GdkRGBA(Color color) -> GdkRGBA; constexpr auto argb_to_GdkRGBA(Color color) -> GdkRGBA; constexpr auto argb_to_GdkRGBA(Color color, double alpha) -> GdkRGBA; constexpr auto GdkRGBA_to_argb(const GdkRGBA& color) -> Color; constexpr auto GdkRGBA_to_rgb(const GdkRGBA& color) -> Color; constexpr auto ColorU16_to_argb(const ColorU16& color) -> Color; constexpr auto argb_to_ColorU16(const Color& color) -> ColorU16; constexpr auto GdkRGBA_to_ColorU16(const GdkRGBA& color) -> ColorU16; /// Set the color of a cairo context -- uses alpha as alpha value void cairo_set_source_rgbi(cairo_t* cr, Color color, double alpha = 1.0); /// Set the color of a cairo context -- uses color.alpha as alpha value void cairo_set_source_argb(cairo_t* cr, Color color); // Use color.alpha constexpr auto floatToUIntColor(double color) -> uint8_t; /** * @param color Color to convert to grayscale. * @return Given color converted to grayscale 1.0 -> white, 0.0 -> black. */ float as_grayscale_color(Color color); /** * Get the fraction by which the grayscale value of color1 contrasts * with color2 (0.0 = no contrast, 1.0 = maximum contrast). * Does not take a color's alpha channel into account. * @return Scale factor by which the two given colors differ. Must be in * [0.0, 1.0]. */ float get_color_contrast(Color color1, Color color2); /** * @param rgb Color to get a representation for, while ignoring the alpha channel. * @return a CSS-style representation of the color, in hex. For example, * red might be #ff0000, green, #00ff00, and blue, #0000ff. */ std::string rgb_to_hex_string(Color rgb); } // namespace Util constexpr auto Util::rgb_to_GdkRGBA(Color color) -> GdkRGBA { // color.alpha = 0xFF; return Util::argb_to_GdkRGBA(color); } constexpr auto Util::argb_to_GdkRGBA(const Color color) -> GdkRGBA { return {color.red / 255.0, // color.green / 255.0, // color.blue / 255.0, // color.alpha / 255.0}; } constexpr auto Util::argb_to_GdkRGBA(Color color, double alpha) -> GdkRGBA { return {color.red / 255.0, // color.green / 255.0, // color.blue / 255.0, // alpha}; } constexpr auto Util::GdkRGBA_to_argb(const GdkRGBA& color) -> Color { auto ret = GdkRGBA_to_rgb(color); ret.alpha = floatToUIntColor(color.alpha); return ret; } constexpr auto Util::GdkRGBA_to_rgb(const GdkRGBA& color) -> Color { return Color{floatToUIntColor(color.red), // floatToUIntColor(color.green), // floatToUIntColor(color.blue)}; } constexpr auto Util::argb_to_ColorU16(const Color& color) -> ColorU16 { /* 0xff should map to 0xffff in 16 bit. Therefore multipliing by 257 instead of 256*/ return {static_cast<uint16_t>((color.red << 8U) + color.red), static_cast<uint16_t>((color.green << 8U) + color.green), static_cast<uint16_t>((color.blue << 8U) + color.blue), static_cast<uint16_t>((color.alpha << 8U) + color.alpha)}; } constexpr auto Util::ColorU16_to_argb(const ColorU16& color) -> Color { return Color{static_cast<uint8_t>(color.red >> 8U), static_cast<uint8_t>(color.green >> 8U), static_cast<uint8_t>(color.blue >> 8U), static_cast<uint8_t>(color.alpha >> 8U)}; } constexpr auto Util::floatToUIntColor(const double color) -> uint8_t { /* * Splits the double into a equal sized distribution between [0,256[ and rounding down * inspired by, which isn't completely correct: * https://stackoverflow.com/questions/1914115/converting-color-value-from-float-0-1-to-byte-0-255 */ constexpr double MAX_COLOR = 256.0 - std::numeric_limits<double>::epsilon() * 128; static_assert(MAX_COLOR < 256.0, "MAX_COLOR isn't smaller than 256"); return static_cast<uint8_t>(color * MAX_COLOR); } constexpr auto Util::GdkRGBA_to_ColorU16(const GdkRGBA& color) -> ColorU16 { auto floatToColorU16 = [](double color) { constexpr double MAX_COLOR = 65536.0 - std::numeric_limits<double>::epsilon() * (65536.0 / 2.0); static_assert(MAX_COLOR < 65536.0, "MAX_COLOR isn't smaller than 65536"); return static_cast<uint16_t>(color * MAX_COLOR); }; return {floatToColorU16(color.red), // floatToColorU16(color.green), // floatToColorU16(color.blue), // floatToColorU16(color.alpha)}; } namespace Colors { /* * A palette of predefined colors. The names are the relevant CSS4 named * color, if exists, else the name of the named color with the smallest * distance from it as an (r, g, b) vector with the prefix "xopp_", * see https://www.w3.org/TR/css-color-4/#named-colors */ constexpr Color black{0xff000000U}; constexpr Color gray{0xff808080U}; constexpr Color green{0xff008000U}; constexpr Color lawngreen(0xff7cfc00U); constexpr Color lime{0xff00ff00U}; constexpr Color magenta{0xffff00ffU}; constexpr Color red{0xffff0000U}; constexpr Color silver{0xffc0c0c0}; constexpr Color white{0xffffffffU}; constexpr Color yellow{0xffffff00U}; constexpr Color xopp_antiquewhite{0xfff8ead3U}; constexpr Color xopp_aquamarine{0xff80ffc0U}; constexpr Color xopp_bisque{0xfffee7c4U}; constexpr Color xopp_cornflowerblue{0xff729fcfU}; constexpr Color xopp_darkorange{0xffff8000U}; constexpr Color xopp_darkslategray{0xff434343U}; constexpr Color xopp_deeppink{0xffff0080U}; constexpr Color xopp_deepskyblue{0xff00c0ffU}; constexpr Color xopp_dodgerblue{0xff40a0ffU}; constexpr Color xopp_gainsboro{0xffdadcdaU}; constexpr Color xopp_gainsboro02{0xffdcdad5U}; constexpr Color xopp_gainsboro03{0xffe6d8e4U}; constexpr Color xopp_khaki{0xffffff80U}; constexpr Color xopp_lavender{0xffd4e2f0U}; constexpr Color xopp_lemonchifon{0xfffef8c9U}; constexpr Color xopp_lightpink{0xfffabebeU}; constexpr Color xopp_lightsalmon{0xffffc080U}; constexpr Color xopp_midnightblue{0xff220080U}; constexpr Color xopp_palegoldenrod{0xffdcf6c1U}; constexpr Color xopp_paleturqoise{0xffa0e8ffU}; constexpr Color xopp_pink{0xffffc0d4U}; constexpr Color xopp_royalblue{0xff3333ccU}; constexpr Color xopp_silver{0xffbdbdbdU}; constexpr Color xopp_snow{0xfffafaf9U}; } // namespace Colors
9,369
C++
.h
210
40.666667
119
0.693817
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,712
Rectangle.h
xournalpp_xournalpp/src/util/include/util/Rectangle.h
/* * Xournal++ * * A rectangle data structure over a numeric data type. * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #include <algorithm> #include <iosfwd> #include <optional> #include "util/Range.h" namespace xoj::util { // Rectangle is already defined in windows.h template <class T> class Rectangle final { public: constexpr Rectangle() = default; constexpr Rectangle(T x, T y, T width, T height): x(x), y(y), width(width), height(height) {} constexpr explicit Rectangle(const Range& rect): x(rect.getX()), y(rect.getY()), width(rect.getWidth()), height(rect.getHeight()) {} constexpr auto operator==(const Rectangle& other) const -> bool { return x == other.x && y == other.y && width == other.width && height == other.height; } /** * Returns whether this rectangle intersects another and the intersection * @param other the other rectangle * @return whether the rectangles intersect and if so, the intersection */ constexpr auto intersects(const Rectangle& other) const -> std::optional<Rectangle> { auto x1 = std::max(this->x, other.x); auto y1 = std::max(this->y, other.y); auto x2 = std::min(this->x + this->width, other.x + other.width); auto y2 = std::min(this->y + this->height, other.y + other.height); if (x2 > x1 && y2 > y1) { return {{x1, y1, x2 - x1, y2 - y1}}; } return std::nullopt; } /** * Returns a new Rectangle with an offset specified * by the function arguments */ constexpr auto translated(T dx, T dy) const -> Rectangle { return Rectangle(this->x + dx, this->y + dy, this->width, this->height); } /** * Computes the union of this and the other rectangle */ constexpr void unite(const Rectangle& other) { this->width = std::max(this->x + this->width, other.x + other.width); this->height = std::max(this->y + this->height, other.y + other.height); this->x = std::min(this->x, other.x); this->y = std::min(this->y, other.y); this->width -= this->x; this->height -= this->y; } /** * Applies a scalar to this rectangle */ constexpr auto operator*=(T factor) -> Rectangle& { x *= factor; y *= factor; width *= factor; height *= factor; return *this; } /** * Calculates the area */ constexpr auto area() const -> T { return width * height; } T x{}; T y{}; T width{}; T height{}; }; } // namespace xoj::util
2,663
C++
.h
79
28.113924
97
0.604434
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,713
serdesstream.h
xournalpp_xournalpp/src/util/include/util/serdesstream.h
#pragma once #include <locale> #include <utility> /** * @brief Serdes always requires the same locale. Independently of the local / C++ global locale. */ template <typename StdStream, typename... Args> StdStream serdes_stream(Args&&... args) { StdStream ret(std::forward<Args>(args)...); ret.imbue(std::locale::classic()); return ret; }
353
C++
.h
12
27.083333
97
0.707965
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,714
GzUtil.h
xournalpp_xournalpp/src/util/include/util/GzUtil.h
/* * Xournal++ * * Gzip Helper * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #include <string> // for string #include <zlib.h> // for gzFile #include "filesystem.h" // for path class GzUtil { private: GzUtil(); virtual ~GzUtil(); public: static gzFile openPath(const fs::path& path, const std::string& flags); };
413
C++
.h
21
17.380952
75
0.681347
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,715
Assert.h
xournalpp_xournalpp/src/util/include/util/Assert.h
/* * Xournal++ * * assert * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #include <string> #ifdef NDEBUG #define xoj_assert(expr) static_cast<void>(0) #define xoj_assert_message(expr, msg) static_cast<void>(0) #else namespace xoj::util { [[noreturn]] void assertFailure(const char* expr, const std::string& msg, const char* fileName, int line, const char* funcName); }; #define xoj_assert_message(expr, msg) \ (static_cast<bool>(expr) ? static_cast<void>(0) : \ xoj::util::assertFailure(#expr, msg, __FILE__, __LINE__, __func__)) #define xoj_assert(expr) xoj_assert_message(expr, "") #endif
755
C++
.h
25
26.04
105
0.628611
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,716
safe_casts.h
xournalpp_xournalpp/src/util/include/util/safe_casts.h
/* * This file is provided by Fabian Keßler <fabian_kessler@gmx.de> under the * Boost Software License - Version 1.0 - August 17th, 2003 to the Xournal++ * project. * * Boost Software License - Version 1.0 - August 17th, 2003 * * Permission is hereby granted, free of charge, to any person or organization * obtaining a copy of the software and accompanying documentation covered by * this license (the "Software") to use, reproduce, display, distribute, * execute, and transmit the Software, and to prepare derivative works of the * Software, and to permit third-parties to whom the Software is furnished to * do so, all subject to the following: * * The copyright notices in the Software and this entire statement, including * the above license grant, this restriction and the following disclaimer, * must be included in all copies of the Software, in whole or in part, and * all derivative works of the Software, unless such copies or derivative * works are solely in the form of machine-executable object code generated by * a source language processor. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT * SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE * FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ #pragma once #include <cmath> #include <type_traits> #include <utility> #include "util/Assert.h" template <typename To, typename From> [[maybe_unused]] [[nodiscard]] constexpr auto is_safely_castable(From from) -> bool { using Big = decltype(from * std::declval<To>()); auto to = static_cast<To>(from); return Big(to) == Big(from) && ((to < 0 && from < 0) || (to >= 0 && from >= 0)); } template <typename To, typename From> [[maybe_unused]] [[nodiscard]] constexpr auto strict_cast(From from) -> To { xoj_assert(is_safely_castable<To>(from)); return static_cast<To>(from); } template <typename Integral> [[maybe_unused]] [[nodiscard]] constexpr auto as_signed(Integral i) -> std::make_signed_t<std::remove_cv_t<std::remove_reference_t<Integral>>> { return static_cast<std::make_signed_t<std::remove_cv_t<std::remove_reference_t<Integral>>>>(i); } template <typename Integral> [[maybe_unused]] [[nodiscard]] constexpr auto as_unsigned(Integral i) -> std::make_unsigned_t<std::remove_cv_t<std::remove_reference_t<Integral>>> { return static_cast<std::make_unsigned_t<std::remove_cv_t<std::remove_reference_t<Integral>>>>(i); } template <typename Integral> [[maybe_unused]] [[nodiscard]] constexpr auto as_signed_strict(Integral i) -> std::make_signed_t<std::remove_cv_t<std::remove_reference_t<Integral>>> { auto rv = static_cast<std::make_signed_t<std::remove_cv_t<std::remove_reference_t<Integral>>>>(i); xoj_assert((i < 0 && rv < 0) || (i >= 0 && rv >= 0)); return rv; } template <typename Integral> [[maybe_unused]] [[nodiscard]] constexpr auto as_unsigned_strict(Integral i) -> std::make_unsigned_t<std::remove_cv_t<std::remove_reference_t<Integral>>> { xoj_assert(i > 0); return static_cast<std::make_unsigned_t<std::remove_cv_t<std::remove_reference_t<Integral>>>>(i); } template <typename Integral, typename Float> inline auto round_cast(Float f) -> Integral { auto rv0 = std::lround(f); auto rv1 = static_cast<Integral>(rv0); xoj_assert(rv0 == rv1); return rv1; } template <typename Integral, typename Float> inline auto ceil_cast(Float f) -> Integral { auto rv0 = std::ceil(f); auto rv1 = Integral(rv0); xoj_assert(rv0 == static_cast<Float>(rv1)); return rv1; } template <typename Integral, typename Float> inline auto floor_cast(Float f) -> Integral { auto rv0 = std::floor(f); auto rv1 = Integral(rv0); xoj_assert(rv0 == static_cast<Float>(rv1)); return rv1; } namespace xoj { template <class Enum> constexpr std::underlying_type_t<Enum> to_underlying(Enum e) noexcept { return static_cast<std::underlying_type_t<Enum>>(e); } } // namespace xoj #if defined __has_include && !defined(XOJ_USE_STD_BIT_CAST) #if __has_include(<bit>) #include <bit> #if defined(__cpp_lib_bit_cast) && __cpp_lib_bit_cast >= 201806L #define XOJ_USE_STD_BIT_CAST 1 #endif #endif #endif #if defined(XOJ_USE_STD_BIT_CAST) && XOJ_USE_STD_BIT_CAST == 1 namespace xoj::util { using std::bit_cast; } // namespace xoj::util #else #include <cstring> namespace xoj::util { /** * A backport from C++20 of std::bit_cast() */ template <class To, class From> inline std::enable_if_t< sizeof(To) == sizeof(From) && std::is_trivially_copyable_v<From> && std::is_trivially_copyable_v<To>, To> // constexpr support needs compiler magic bit_cast(const From& src) noexcept { static_assert(std::is_trivially_constructible_v<To>, "backport of bit_cast requires destination type to be trivially constructible"); To dst; std::memcpy(&dst, &src, sizeof(To)); return dst; } } // namespace xoj::util #endif // static_assert(is_safely_castable<int>(std::numeric_limits<size_t>::max()) == false); // static_assert(is_safely_castable<int>(std::numeric_limits<int64_t>::min()) == false); // static_assert(is_safely_castable<int>(std::numeric_limits<double>::min()) == false); // static_assert(is_safely_castable<int>(std::numeric_limits<float>::min()) == false); // static_assert(is_safely_castable<int>(size_t(std::numeric_limits<int>::max()))); // static_assert(is_safely_castable<int>(int64_t(std::numeric_limits<int>::min()))); // static_assert(is_safely_castable<int>(double(std::numeric_limits<int>::min())));
5,864
C++
.h
133
41.308271
113
0.70931
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,717
UnionOfIntervals.h
xournalpp_xournalpp/src/util/include/util/UnionOfIntervals.h
/* * Xournal++ * * A data structure for unions of intervals of a numeric data type. * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #include <algorithm> #include <iterator> #include <vector> #include "util/Assert.h" #include "Interval.h" /** * @brief A data structure for unions of intervals of a numeric data type * * The intervals are stored as a sorted list of their bounds. The list must be of even length. * This data structure makes the computation of the union/intersection/complement of those intervals very simple. * The downside is: it makes iterating through the structure a bit weird. See cloneToIntervalVector below for an example */ template <class T> class UnionOfIntervals final { public: UnionOfIntervals() = default; /** * @brief Reset the union of intervals to be the single interval [lowerBound, upperBound). * Assumes lowerBound < upperBound * @param lowerBound The lower bound * @param upperBound The upper bound */ [[maybe_unused]] void set(const T& lowerBound, const T& upperBound) { data = {lowerBound, upperBound}; } /** * @brief Add the intervals of other to this * @param other Any forward-iteratable sorted container of type T of **even length** * @return True if changes were made, false otherwise */ template <class C> [[maybe_unused]] bool unite(const C& other) { bool changesMade = false; bool insideThis = false; bool insideOther = false; auto itThis = this->data.begin(); auto itOther = other.cbegin(); while (itThis != this->data.end() && itOther != other.cend()) { if (*itOther == *itThis) { if (insideThis != insideOther) { // This bound is no longer needed // Remove and increment itThis = this->data.erase(itThis); changesMade = true; } else { ++itThis; } itOther++; insideThis = !insideThis; insideOther = !insideOther; } else if (*itOther < *itThis) { insideOther = !insideOther; if (!insideThis) { // Open or close an interval (depending on the value of insideOther) itThis = std::next(this->data.insert(itThis, *itOther)); changesMade = true; } ++itOther; } else { insideThis = !insideThis; if (insideOther) { // This bound is no longer needed // Remove and increment itThis = this->data.erase(itThis); changesMade = true; } else { ++itThis; } } } if (itOther == other.cend()) { return changesMade; } std::copy(itOther, other.cend(), std::back_inserter(this->data)); xoj_assert(this->data.size() % 2 == 0); return true; } /** * @brief Intersect the intervals of this with those of other * @param other Any forward-iteratable sorted container of type T of **even length** * @return True if changes were made, false otherwise */ template <class C> [[maybe_unused]] bool intersect(const C& other) { bool changesMade = false; bool insideThis = false; bool insideOther = false; auto itThis = this->data.begin(); auto itOther = other.cbegin(); while (itThis != this->data.end() && itOther != other.cend()) { if (*itOther == *itThis) { if (insideThis != insideOther) { // This bound is no longer needed // Remove and increment itThis = this->data.erase(itThis); changesMade = true; } else { ++itThis; } ++itOther; insideThis = !insideThis; insideOther = !insideOther; } else if (*itOther < *itThis) { insideOther = !insideOther; if (insideThis) { // Open or close an interval (depending on the value of insideOther) itThis = std::next(this->data.insert(itThis, *itOther)); changesMade = true; } itOther++; } else { insideThis = !insideThis; if (!insideOther) { // This bound is no longer needed // Remove and increment itThis = this->data.erase(itThis); changesMade = true; } else { ++itThis; } } } data.erase(itThis, data.end()); xoj_assert(this->data.size() % 2 == 0); return changesMade; } /** * @brief Replace the union of intervals by its complement inside [lowerBound, upperBound]. * Assumes all values lie in this interval. * @param lowerBound The lower bound * @param upperBound The upper bound */ void complement(const T& lowerBound, const T& upperBound) { if (data.empty()) { data = {lowerBound, upperBound}; return; } if (data.front() == lowerBound) { data.erase(data.begin()); } else { data.insert(data.begin(), lowerBound); } if (data.back() == upperBound) { data.pop_back(); } else { data.push_back(upperBound); } xoj_assert(this->data.size() % 2 == 0); } /** * @brief Copy the data into a vector of type Interval * @return The copied vector */ std::vector<Interval<T>> cloneToIntervalVector() const { std::vector<Interval<T>> result; xoj_assert(this->data.size() % 2 == 0); result.reserve(data.size() / 2); auto itLowerBound = data.cbegin(); auto itUpperBound = itLowerBound; auto itEnd = data.cend(); while (itLowerBound != itEnd) { itUpperBound = std::next(itLowerBound); result.emplace_back(*itLowerBound, *itUpperBound); itLowerBound = std::next(itUpperBound); } return result; } /** * @brief Determine if the union of intervals is empty or not * @return true if it is empty, false otherwise */ inline bool empty() const { return data.empty(); } /** * @brief Get a reference to the data */ const std::vector<T>& getData() const { return data; } /** * @brief Swap the content with that of other */ void swap(UnionOfIntervals<T>& other) { data.swap(other.data); } /** * @brief Append raw data to the union's data * @param container Container with the added data * * This assumes: * * container is a container of type T of even length * * container is sorted * * container.front() > data.back() */ template <typename container_type> void appendData(const container_type& container) { xoj_assert(container.size() % 2 == 0); std::copy(container.begin(), container.end(), std::back_inserter(data)); } private: std::vector<T> data; };
7,502
C++
.h
206
26.466019
120
0.5509
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,718
NamedColor.h
xournalpp_xournalpp/src/util/include/util/NamedColor.h
/** * Xournal++ * * Part of the customizable toolbars * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later * @brief Struct for NamedColor */ #pragma once #include <cstddef> // for size_t #include <iosfwd> // for istream #include <string> // for string, basic_string #include "util/Color.h" // for Color, ColorU16, ColorU8 /** * @brief NamedColor is an object for a color with name and an optional index which refers to the index of the color * inside a given palette. * If the NamedColor does not come from a Color palette isColorPalette is set to false and the palettIndex is 0. * */ struct NamedColor { /** * @brief Default Construct a new Named Color instance * This is only needed for the input operator implementation * */ NamedColor(); /** * @brief Construct a new NamedColor instance for a Color Palette * The paletteIndex should be the index which the color will have in the palette. * This is to be used as: * * NamedColor color{namedColors.size()}; * std::istringstream iss{line}; * if (iss >> color) { * ... * } * * @param paletteIndex */ explicit NamedColor(size_t paletteIndex); /** * @brief Construct a new NamedColor instance * This automatically sets the isPaletteColor to negative as NamedColors from a color palette can only be * constructed using the input operator. * As it is no paletteColor the Name of the Color will be set to "Custom Color" and the paletteIndex to 0. * * @param color color to set for the custom NamedColor instance */ explicit NamedColor(Color color); /** * @brief Input operator for parsing NamedColor from input string stream * * @param str input string stream * @param namedColor output for parsed NamedColor * @return std::istream& which is the rest of the input string stream after parsing */ friend auto operator>>(std::istream& str, NamedColor& namedColor) -> std::istream&; /** * @brief Get the color formatted as ColorU16 object * * @return ColorU16 */ auto getColorU16() const -> ColorU16; /** * @brief Get the color formatted as Color object * * @return Color */ auto getColor() const -> Color; /** * @brief Get the Index of the NamedColor inside the Palette * * @return size_t index */ auto getIndex() const -> size_t; /** * @brief Get the Name of the NamedColor * * @return std::string name */ auto getName() const -> std::string const&; private: /** * @brief Index of the Namedcolor inside the palette * This is useful for loading the toolbar from the toolbar.ini * */ size_t paletteIndex; std::string name; ColorU16 colorU16; Color color; /** * @brief Flag whether a color comes from a palette or is a custom color. * */ bool isPaletteColor; };
3,058
C++
.h
100
25.78
116
0.655008
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,719
SaveNameUtils.h
xournalpp_xournalpp/src/util/include/util/SaveNameUtils.h
/* * Xournal++ * * Save-name parsing utility, does wildcard-string to save-name conversions * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #include <string> // for string #include "filesystem.h" // for path constexpr auto DEFAULT_WILDCARD_START = "%{"; constexpr auto DEFAULT_WILDCARD_END = "}"; // wildcard options constexpr auto WILDCARD_NAME = "name"; ///< default store name, e.g. original pdf name constexpr auto WILDCARD_DATE = "date"; ///< current date - Deprecated: prefer using %F instead of %{date} constexpr auto WILDCARD_TIME = "time"; ///< current time - Deprecated: prefer using %X instead of %{time} class SaveNameUtils { public: static std::string parseFilenameFromWildcardString(const std::string& wildcardString, const fs::path& defaultFilePath); private: static std::string parseWildcard(const std::string& wildcard, const fs::path& defaultFilePath); };
981
C++
.h
25
37.28
123
0.731296
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,720
CircularBuffer.h
xournalpp_xournalpp/src/util/include/util/CircularBuffer.h
/* * Xournal++ * * A rudimentary circular buffer * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #include <cstddef> #include <vector> template <class T> class CircularBuffer: private std::vector<T> { public: CircularBuffer(size_t length): std::vector<T>(length > 1 ? length : 1), length(length > 1 ? length : 1) {} ~CircularBuffer() = default; T front() { return (*this)[head]; } T back() { if (head == 0) { return (*this)[length - 1]; } return (*this)[head - 1]; } void push_front(const T& ev) { head++; head %= length; (*this)[head] = ev; } void assign(const T& ev) { for (T& e: *this) { e = ev; } } size_t size() { return length; } /** * Beware: begin and end are not related to the position of the head */ using std::vector<T>::cbegin; using std::vector<T>::begin; using std::vector<T>::cend; using std::vector<T>::end; private: const size_t length; size_t head = length - 1; };
1,110
C++
.h
45
20.133333
110
0.580584
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,721
HexObjectEncoding.h
xournalpp_xournalpp/src/util/include/util/serializing/HexObjectEncoding.h
/* * Xournal++ * * Hex encoded serialized stream * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #include "ObjectEncoding.h" class HexObjectEncoding: public ObjectEncoding { public: HexObjectEncoding(); ~HexObjectEncoding() override; public: void addData(const void* data, size_t len) override; private: };
401
C++
.h
20
17.75
56
0.742021
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,723
ObjectOutputStream.h
xournalpp_xournalpp/src/util/include/util/serializing/ObjectOutputStream.h
/* * Xournal++ * * Serialized output stream * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #include <cstddef> // for size_t #include <cstdint> // for uint32_t #include <string> // for string #include <string_view> // for string_view #include <vector> // for vector #include <glib.h> // for GString class ObjectEncoding; class ObjectOutputStream { public: ObjectOutputStream(ObjectEncoding* encoder); virtual ~ObjectOutputStream(); public: void writeObject(const char* name); void endObject(); void writeInt(int i); void writeUInt(uint32_t u); void writeDouble(double d); void writeSizeT(size_t st); void writeString(const char* str); void writeString(const std::string& s); void writeData(const void* data, size_t len, size_t width); template <typename T> void writeData(const std::vector<T>& data); /// Writes the raw image data to the output stream. void writeImage(const std::string_view& imgData); GString* getStr(); private: ObjectEncoding* encoder = nullptr; }; template <typename T> void ObjectOutputStream::writeData(const std::vector<T>& data) { writeData(data.data(), data.size(), sizeof(T)); }
1,292
C++
.h
44
26.227273
64
0.700405
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,724
ObjectEncoding.h
xournalpp_xournalpp/src/util/include/util/serializing/ObjectEncoding.h
/* * Xournal++ * * Encoding for serialized streams * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #include <glib.h> // for GString class ObjectEncoding { public: ObjectEncoding(); virtual ~ObjectEncoding(); public: void addStr(const char* str) const; virtual void addData(const void* data, size_t len) = 0; GString* getData(); public: GString* data; };
463
C++
.h
23
17.391304
59
0.69746
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,725
Serializable.h
xournalpp_xournalpp/src/util/include/util/serializing/Serializable.h
/* * Xournal++ * * Serializable interface * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #include "InputStreamException.h" class ObjectInputStream; class ObjectOutputStream; const static char* const XML_VERSION_STR = "XojStrm1:"; class Serializable { public: virtual void serialize(ObjectOutputStream& out) const = 0; virtual void readSerialized(ObjectInputStream& in) = 0; virtual ~Serializable() = default; };
508
C++
.h
21
21.904762
62
0.756757
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,726
ObjectInputStream.h
xournalpp_xournalpp/src/util/include/util/serializing/ObjectInputStream.h
/* * Xournal++ * * Serialized input stream * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #include <cstddef> // for size_t #include <cstdint> // for uint32_t #include <sstream> // for istringstream #include <string> // for string #include <vector> // for vector #include "util/safe_casts.h" // for as_signed #include "InputStreamException.h" class ObjectInputStream { public: ObjectInputStream() = default; virtual ~ObjectInputStream() = default; public: bool read(const char* data, size_t len); void readObject(const char* name); std::string readObject(); std::string getNextObjectName(); void endObject(); int readInt(); uint32_t readUInt(); double readDouble(); size_t readSizeT(); std::string readString(); template <typename T> void readData(std::vector<T>& data); /// Reads raw image data from the stream. std::string readImage(); private: void checkType(char type); static std::string getType(char type); template <class T> T readType(); private: std::istringstream istream; size_t pos(); size_t len = 0; }; extern template size_t ObjectInputStream::readType<size_t>(); template <typename T> void ObjectInputStream::readData(std::vector<T>& data) { checkType('b'); if (istream.str().size() < 2 * sizeof(size_t)) { throw InputStreamException("End reached, but try to read data len and width", __FILE__, __LINE__); } size_t len = readType<size_t>(); size_t width = readType<size_t>(); if (width != sizeof(T)) { throw InputStreamException("Data width mismatch requested type width", __FILE__, __LINE__); } if (istream.str().size() < len * width) { throw InputStreamException("End reached, but try to read data", __FILE__, __LINE__); } if (len) { data.resize(len); istream.read((char*)data.data(), as_signed(len * width)); } }
2,013
C++
.h
67
25.970149
106
0.658701
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,727
BinObjectEncoding.h
xournalpp_xournalpp/src/util/include/util/serializing/BinObjectEncoding.h
/* * Xournal++ * * Binary encoded serialized stream * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #include "ObjectEncoding.h" class BinObjectEncoding: public ObjectEncoding { public: BinObjectEncoding(); ~BinObjectEncoding() override; public: void addData(const void* data, size_t len) override; private: };
404
C++
.h
20
17.9
56
0.744063
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,728
Logger.h
xournalpp_xournalpp/src/util/include/util/logger/Logger.h
/* * Xournal++ * * Logging class for debugging * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once class Log { private: Log(); virtual ~Log(); Log(const Log&); Log& operator=(const Log&); public: static void initlog(); static void closelog(); static void trace(const char* callType, const char* clazz, const char* function, long obj); };
443
C++
.h
22
17.272727
95
0.673861
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,729
CairoWrappers.h
xournalpp_xournalpp/src/util/include/util/raii/CairoWrappers.h
/* * Xournal++ * * RAII wrappers for C library classes * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #include <utility> #include <cairo.h> #include "CLibrariesSPtr.h" #include "IdentityFunction.h" namespace xoj::util { inline namespace raii { namespace specialization { class CairoHandler { public: constexpr static auto ref = [](cairo_t* cr) { return cairo_reference(cr); }; constexpr static auto unref = [](cairo_t* cr) { cairo_destroy(cr); }; constexpr static auto adopt = identity<cairo_t>; }; class CairoSurfaceHandler { public: constexpr static auto ref = [](cairo_surface_t* cs) { return cairo_surface_reference(cs); }; constexpr static auto unref = [](cairo_surface_t* cs) { cairo_surface_destroy(cs); }; constexpr static auto adopt = identity<cairo_surface_t>; }; class CairoRegionHandler { public: constexpr static auto ref = [](cairo_region_t* cr) { return cairo_region_reference(cr); }; constexpr static auto unref = [](cairo_region_t* cr) { cairo_region_destroy(cr); }; constexpr static auto adopt = identity<cairo_region_t>; }; }; // namespace specialization using CairoSPtr = CLibrariesSPtr<cairo_t, raii::specialization::CairoHandler>; using CairoSurfaceSPtr = CLibrariesSPtr<cairo_surface_t, raii::specialization::CairoSurfaceHandler>; using CairoRegionSPtr = CLibrariesSPtr<cairo_region_t, raii::specialization::CairoRegionHandler>; /** * @brief cairo_save(cr)/cairo_restore(cr) RAII implementation */ class CairoSaveGuard { public: CairoSaveGuard() = delete; [[nodiscard]] CairoSaveGuard(cairo_t* cr): cr(cr) { cairo_save(cr); } ~CairoSaveGuard() { cairo_restore(cr); } CairoSaveGuard(const CairoSaveGuard&) = delete; CairoSaveGuard(CairoSaveGuard&&) = delete; CairoSaveGuard& operator=(const CairoSaveGuard&) = delete; CairoSaveGuard& operator=(CairoSaveGuard&&) = delete; private: cairo_t* cr; }; }; // namespace raii }; // namespace xoj::util
2,030
C++
.h
57
33
100
0.730102
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,730
IdentityFunction.h
xournalpp_xournalpp/src/util/include/util/raii/IdentityFunction.h
/* * Xournal++ * * Identity function * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once namespace xoj::util { inline namespace raii { namespace specialization { template <typename T> // Todo(cpp20): use std:identity() and remove this header constexpr auto identity = [](T* p) { return p; }; }; }; // namespace raii }; // namespace xoj::util
421
C++
.h
19
20.526316
80
0.701754
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,731
GtkWindowUPtr.h
xournalpp_xournalpp/src/util/include/util/raii/GtkWindowUPtr.h
/* * Xournal++ * * RAII wrappers for C library classes * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #include <memory> #include <gtk/gtk.h> #include "util/gtk4_helper.h" namespace xoj::util { inline namespace raii { namespace specialization { struct GtkWindowDeleter { void operator()(GtkWindow* w) { if (w) { gtk_window_destroy(w); } } }; }; // namespace specialization using GtkWindowUPtr = std::unique_ptr<GtkWindow, specialization::GtkWindowDeleter>; }; // namespace raii }; // namespace xoj::util
628
C++
.h
28
19.535714
83
0.692568
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,732
GLibGuards.h
xournalpp_xournalpp/src/util/include/util/raii/GLibGuards.h
/* * Xournal++ * * Basic memory RAII Guards for GLib objects * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #include <memory> #include <type_traits> #include <gtk/gtk.h> namespace xoj::util { inline namespace raii { #define XOJ_GIO_GUARD_GENERATOR(class_name, type, deletion_func) \ namespace detail { \ struct class_name##GuardDelete { \ auto operator()(type* ptr) const -> void { \ if (ptr) { \ deletion_func(ptr); \ ptr = nullptr; \ } \ } \ }; \ } /* namespace detail */ \ using class_name##Guard = std::unique_ptr<type, detail::class_name##GuardDelete> #define XOJ_GIO_GUARD_GENERATOR_TYPE(type, deletion_func) XOJ_GIO_GUARD_GENERATOR(type, type, deletion_func) XOJ_GIO_GUARD_GENERATOR(GStrv, gchar*, g_strfreev); XOJ_GIO_GUARD_GENERATOR_TYPE(GError, g_error_free); template <typename Smart, typename Pointer /* , typename ... Tuple */> struct out_ptr_t { out_ptr_t(Smart& smart /* , Tuple tuple */): smart(smart) /* , tuple(tuple) */ {} ~out_ptr_t() noexcept { smart.reset(ptr /*, Todo: unpack tuble with indices trick if required*/); } out_ptr_t(out_ptr_t const&) = delete; auto operator=(out_ptr_t const&) -> out_ptr_t& = delete; operator Pointer*() noexcept { return &ptr; } private: Smart& smart; Pointer ptr{}; // Tuple tuple; }; template <typename Smart, typename... A> auto out_ptr(Smart& s /*, A&&... a */) noexcept -> out_ptr_t<Smart, typename Smart::pointer /* , std::tuple<A...> */> { return out_ptr_t<Smart, typename Smart::pointer /* , std::tuple<A...> */> // (s /* , std::tuple<A...>(std::forward<A>(a)...) */); } } // namespace raii } // namespace xoj::util
2,200
C++
.h
50
39.8
119
0.512856
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,733
GObjectSPtr.h
xournalpp_xournalpp/src/util/include/util/raii/GObjectSPtr.h
/* * Xournal++ * * RAII wrappers for C library classes * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #include <utility> #include <glib-object.h> #include <gtk/gtk.h> #include "CLibrariesSPtr.h" namespace xoj::util { inline namespace raii { namespace specialization { template <class object_type> class GObjectHandler { public: static object_type* ref(object_type* p) { return static_cast<object_type*>(g_object_ref(p)); } constexpr static auto unref = [](object_type* p) { g_object_unref(p); }; static object_type* ref_sink(object_type* p) { return static_cast<object_type*>(g_object_ref_sink(p)); } static object_type* adopt(object_type* p) { #if (GLIB_MAJOR_VERSION > 2 || (GLIB_MAJOR_VERSION == 2 && GLIB_MINOR_VERSION >= 70)) return static_cast<object_type*>(g_object_take_ref(p)); #else return g_object_is_floating(p) ? static_cast<object_type*>(g_object_ref_sink(p)) : p; #endif } }; }; // namespace specialization template <typename GlibClass> using GObjectSPtr = CLibrariesSPtr<GlibClass, raii::specialization::GObjectHandler<GlibClass>>; using WidgetSPtr = GObjectSPtr<GtkWidget>; }; // namespace raii }; // namespace xoj::util
1,265
C++
.h
38
30.842105
108
0.714873
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