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,734
GVariantSPtr.h
xournalpp_xournalpp/src/util/include/util/raii/GVariantSPtr.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 "util/GVariantTemplate.h" #include "CLibrariesSPtr.h" namespace xoj::util { inline namespace raii { namespace specialization { class GVariantHandler { public: constexpr static auto ref = [](GVariant* v) { return g_variant_ref(v); }; constexpr static auto unref = [](GVariant* v) { g_variant_unref(v); }; constexpr static auto ref_sink = [](GVariant* v) { return g_variant_ref_sink(v); }; constexpr static auto adopt = [](GVariant* v) { return g_variant_take_ref(v); }; }; }; // namespace specialization using GVariantSPtr = CLibrariesSPtr<GVariant, raii::specialization::GVariantHandler>; template <typename T> GVariantSPtr makeGVariantSPtr(T t) { return GVariantSPtr(makeGVariant(t), adopt); } }; // namespace raii }; // namespace xoj::util
1,009
C++
.h
33
28.363636
87
0.724352
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,735
CStringWrapper.h
xournalpp_xournalpp/src/util/include/util/raii/CStringWrapper.h
/* * Xournal++ * * C-type strings wrapper, taking ownership of the data. * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #include <cstddef> // for size_t #include <string_view> namespace xoj::util { inline namespace raii { class OwnedCString final { public: OwnedCString() = default; OwnedCString(const OwnedCString&) = delete; OwnedCString(OwnedCString&& s); OwnedCString& operator=(const OwnedCString&) = delete; OwnedCString& operator=(OwnedCString&& s); ~OwnedCString(); /** * @brief Assume ownership */ static OwnedCString assumeOwnership(char* s); const char* get() const; operator bool() const; explicit operator std::string_view() const; /* * Why is this class implicitly convertible to const char& without this line? * In any case: this is dangerous, as it makes * CString bar = "blob"; * std::string foo = bar; * compile without having the expected behaviour */ operator const char&() const = delete; const char& operator[](size_t n) const; /** * @brief Safely delete the content and return a pointer to the private data pointer * Use to set the data with some C-libraries functions taking a char** as argument */ char** contentReplacer(); private: char* data = nullptr; }; }; // namespace raii }; // namespace xoj::util
1,452
C++
.h
49
25.755102
91
0.677905
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,736
PangoSPtr.h
xournalpp_xournalpp/src/util/include/util/raii/PangoSPtr.h
/* * Xournal++ * * RAII wrappers for C library classes * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #include <pango/pango-attributes.h> // for PangoAttrList, pango_attr_list_ref, pango_attr_list_unref #include "CLibrariesSPtr.h" #include "IdentityFunction.h" namespace xoj::util { inline namespace raii { namespace specialization { class PangoAttrListHandler { public: constexpr static auto ref = pango_attr_list_ref; constexpr static auto unref = pango_attr_list_unref; constexpr static auto adopt = identity<PangoAttrList>; }; }; // namespace specialization using PangoAttrListSPtr = CLibrariesSPtr<PangoAttrList, raii::specialization::PangoAttrListHandler>; }; // namespace raii }; // namespace xoj::util
810
C++
.h
27
28
101
0.765766
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,737
CLibrariesSPtr.h
xournalpp_xournalpp/src/util/include/util/raii/CLibrariesSPtr.h
/* * Xournal++ * * RAII smart pointers for C library classes * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #include <utility> namespace xoj::util { /** * @brief Placeholder type for C-lib smart pointer wrappers' contructors and reset methods: adopt the element */ constexpr static struct Adopt { } adopt = Adopt(); /** * @brief Placeholder type for C-lib smart pointer wrappers' contructors and reset methods: add a ref to the element */ constexpr static struct Ref { } ref = Ref(); /** * @brief Placeholder type for C-lib smart pointer wrappers' contructors and reset methods: ref_sink the element */ constexpr static struct RefSink { } refsink = RefSink(); /** * @brief Simple template class for RAII smart pointer (aimed at Cairo/GTK/Poppler ref-counting classes) * @param T The wrapper will store a pointer of type T * @param H Handler class containing at least * static T* ref(T*): * static void unref(T*); * static T* adopt(T*); // What to do to a pointer when we adopt an instance (typically the identity) * and optionally (for floating refs) * static T* ref_sink(T*); */ template <typename T, class H> class CLibrariesSPtr { public: CLibrariesSPtr() = default; CLibrariesSPtr(std::nullptr_t) {} using handler_type = H; private: static auto safeAdopt(T* ptr) -> T* { return ptr ? H::adopt(ptr) : nullptr; } static auto safeRef(T* ptr) -> T* { return ptr ? H::ref(ptr) : nullptr; } static auto safeUnref(T* ptr) -> void { if (ptr) { H::unref(ptr); } } static auto safeRefSink(T* ptr) -> T* { return ptr ? H::ref_sink(ptr) : nullptr; } static auto safeReset(T*& ptr, T* val) -> void { safeUnref(std::exchange(ptr, val)); } public: ~CLibrariesSPtr() { safeUnref(p); } CLibrariesSPtr(const CLibrariesSPtr& other) { p = safeRef(other.p); } CLibrariesSPtr(CLibrariesSPtr&& other) { p = std::exchange(other.p, nullptr); } CLibrariesSPtr& operator=(const CLibrariesSPtr& other) { if (this != &other) { safeReset(p, safeRef(other.p)); } return *this; } CLibrariesSPtr& operator=(CLibrariesSPtr&& other) { if (this != &other) { safeReset(p, std::exchange(other.p, nullptr)); } return *this; } bool operator==(std::nullptr_t) { return p == nullptr; } bool operator!=(std::nullptr_t) { return p != nullptr; } explicit CLibrariesSPtr(T* p, Adopt): p(safeAdopt(p)) {} explicit CLibrariesSPtr(T* p, Ref): p(safeRef(p)) {} explicit CLibrariesSPtr(T* p, RefSink): p(safeRefSink(p)) {} void reset() { safeReset(p, nullptr); } void reset(T* other, Adopt) { safeReset(p, safeAdopt(other)); } void reset(T* other, Ref) { safeReset(p, safeRef(other)); } void reset(T* other, RefSink) { safeReset(p, safeRefSink(other)); } operator bool() const { return p != nullptr; } T* get() const { return p; } T* release() { return std::exchange(p, nullptr); } T* operator->() const { return p; } void swap(CLibrariesSPtr& other) { std::swap(p, other.p); } private: T* p = nullptr; }; }; // namespace xoj::util namespace std { template <typename T, class H> void swap(xoj::util::CLibrariesSPtr<T, H>& first, xoj::util::CLibrariesSPtr<T, H>& second) { first.swap(second); } }; // namespace std
3,473
C++
.h
94
33.042553
116
0.647111
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,738
Font.h
xournalpp_xournalpp/src/core/model/Font.h
/* * Xournal++ * * A font with a name and a size * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #include <string> // for string #include "util/serializing/Serializable.h" // for Serializable class ObjectInputStream; class ObjectOutputStream; class XojFont: public Serializable { public: XojFont() = default; XojFont(std::string name, double size); XojFont(const XojFont&) = default; XojFont(XojFont&&) = default; ~XojFont() override = default; XojFont& operator=(const XojFont&) = default; XojFont& operator=(XojFont&&) = default; /** * Set this from a Pango-style font description. * E.g. * Serif 12 * sets this' size to 12 and this font's name to Serif. * * @param description Pango-style font description. */ explicit XojFont(const char* description); XojFont& operator=(const std::string& description); public: const std::string& getName() const; void setName(std::string name); double getSize() const; void setSize(double size); /** * @return The Pango-style string that represents this * font. */ std::string asString() const; public: // Serialize interface void serialize(ObjectOutputStream& out) const override; void readSerialized(ObjectInputStream& in) override; private: void updateFontDesc(); private: std::string name; double size = 0; };
1,486
C++
.h
54
23.537037
63
0.688293
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,739
StrokeStyle.h
xournalpp_xournalpp/src/core/model/StrokeStyle.h
/* * Xournal++ * * Definition for StrokeStyles * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #include <string> // for string #include "LineStyle.h" // for LineStyle namespace StrokeStyle { /** Parse LineStyle from string. * * @return LineStyle deserialized from string */ LineStyle parseStyle(const std::string& style); /** Convert a LineStyle to a string. * * @param style to be serialized * @return string containing serialized version of LineStyle */ std::string formatStyle(const LineStyle& style); } // namespace StrokeStyle
623
C++
.h
26
22.192308
60
0.745363
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,740
Point.h
xournalpp_xournalpp/src/core/model/Point.h
/* * Xournal++ * * A point of a stroke * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once namespace xoj::util { template <class T> class Rectangle; } // namespace xoj::util /** * @class Point * @brief Representation of a point. */ class Point { public: Point() = default; ~Point() = default; Point(const Point& p) = default; Point& operator=(Point const&) = default; /** * @brief Point from two values. * @param x X value of the point. * @param y Y value of the point. */ Point(double x, double y); /** * @brief Point from three values. * @param x X value of the point. * @param y Y value of the point. * @param z Z value of the point. This denotes the pressure sensitivity. */ Point(double x, double y, double z); public: /** * @brief Compute the distance to another point. * @param p The other point. * @return The Euclidean distance to the other point. */ double lineLengthTo(const Point& p) const; /** * @brief Compute new Point in the direction from this to another Point. * @param p The other Point. * @param length The line length or vector length. * @return The new Point. */ Point lineTo(const Point& p, double length) const; /** * @brief Compute new Point in the direction from this to another Point. * @param p The other Point. * @param ratio The line length over the distance between this and the other Point p * @return The new Point. */ Point relativeLineTo(const Point& p, double ratio) const; /** * @brief Compare if this Point has the same position as another Point. * @param p The other Point. * @return True if the coordinates are equal. False otherwise. */ bool equalsPos(const Point& p) const; /** * @brief Test if the point lies (strictly) inside a given rectangle * @param rect The rectangle * @return True if the point is in rectangle, false otherwise */ bool isInside(const xoj::util::Rectangle<double>& rect) const; public: /** * @brief Private storage for x coordinate. */ double x = 0; /** * @brief Private storage for y coordinate. */ double y = 0; /** * @brief Private storage for pressure. */ double z = NO_PRESSURE; static constexpr double NO_PRESSURE = -1; };
2,472
C++
.h
86
24.104651
88
0.64346
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,741
ElementContainer.h
xournalpp_xournalpp/src/core/model/ElementContainer.h
/* * Xournal++ * * Interface for element containers like selection * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #include <functional> class Element; class ElementContainer { public: virtual void forEachElement(std::function<void(Element*)> f) const = 0; protected: // interface -> protected, non virtual ~ElementContainer() = default; };
435
C++
.h
20
19.45
75
0.731707
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,742
LineStyle.h
xournalpp_xournalpp/src/core/model/LineStyle.h
/* * Xournal++ * * Dash definition of a stroke * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #include <vector> #include "util/serializing/Serializable.h" // for Serializable class ObjectInputStream; class ObjectOutputStream; class LineStyle: public Serializable { public: LineStyle(); ~LineStyle() override; bool operator==(const LineStyle& other) const; public: // Serialize interface void serialize(ObjectOutputStream& out) const override; void readSerialized(ObjectInputStream& in) override; /** * Get dash vector * * @return dashes */ const std::vector<double>& getDashes() const; /** * @return true if dashed */ bool hasDashes() const; /** * Set the dash vector and count * * @param dashes Dash data, will be moved, and continuous use from caller invalid */ void setDashes(std::vector<double>&& dashes); private: std::vector<double> dashes; };
1,043
C++
.h
43
20.395349
85
0.687247
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,743
BackgroundConfig.h
xournalpp_xournalpp/src/core/model/BackgroundConfig.h
/* * Xournal++ * * Configuration data for generated backgrounds * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #include <cstdint> // for uint32_t #include <map> // for map #include <string> // for string // This class corresponds to the config line of entries in pagetemplate.ini class BackgroundConfig { public: BackgroundConfig(const std::string& config); virtual ~BackgroundConfig(); public: bool loadValue(const std::string& key, std::string& value) const; bool loadValue(const std::string& key, int& value) const; bool loadValue(const std::string& key, double& value) const; bool loadValueHex(const std::string& key, uint32_t& value) const; private: std::map<std::string, std::string> data; }; namespace background_config_strings { // Those strings are used in the pagetemplate.ini configuration file constexpr static char CFG_FOREGROUND_COLOR_1[] = "f1"; constexpr static char CFG_ALT_FOREGROUND_COLOR_1[] = "af1"; constexpr static char CFG_FOREGROUND_COLOR_2[] = "f2"; constexpr static char CFG_ALT_FOREGROUND_COLOR_2[] = "af2"; constexpr static char CFG_LINE_WIDTH[] = "lw"; constexpr static char CFG_MARGIN[] = "m1"; constexpr static char CFG_ROUND_MARGIN[] = "rm"; constexpr static char CFG_RASTER[] = "r1"; } // namespace background_config_strings
1,387
C++
.h
38
34.342105
75
0.731744
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,744
PageListener.h
xournalpp_xournalpp/src/core/model/PageListener.h
/* * Xournal++ * * Page listener * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #include <memory> // for shared_ptr, weak_ptr #include <vector> class Element; class PageHandler; class Range; namespace xoj::util { template <class T> class Rectangle; } // namespace xoj::util class PageListener { public: PageListener(); virtual ~PageListener(); public: void registerToHandler(std::shared_ptr<PageHandler> const& handler); void unregisterFromHandler(); virtual void rectChanged(xoj::util::Rectangle<double>& rect) {} virtual void rangeChanged(Range& range) {} virtual void elementChanged(Element* elem) {} virtual void elementsChanged(const std::vector<Element*>& elements, const Range& range) {} virtual void pageChanged() {} private: std::weak_ptr<PageHandler> handler; };
900
C++
.h
35
23.114286
94
0.731935
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,745
Text.h
xournalpp_xournalpp/src/core/model/Text.h
/* * Xournal++ * * A text element * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #include <string> // for string #include <vector> #include <pango/pango.h> #include "model/Element.h" #include "util/raii/GObjectSPtr.h" #include "AudioElement.h" // for AudioElement #include "Font.h" // for XojFont class Element; class ObjectInputStream; class ObjectOutputStream; class XojPdfRectangle; class Text: public AudioElement { public: Text(); ~Text() override; public: void setFont(const XojFont& font); XojFont& getFont(); double getFontSize() const; // same result as getFont()->getSize(), but const std::string getFontName() const; // same result as getFont()->getName(), but const const std::string& getText() const; void setText(std::string text); void setWidth(double width); void setHeight(double height); void setInEditing(bool inEditing); bool isInEditing() const; xoj::util::GObjectSPtr<PangoLayout> createPangoLayout() const; void updatePangoFont(PangoLayout* layout) const; void scale(double x0, double y0, double fx, double fy, double rotation, bool restoreLineWidth) override; void rotate(double x0, double y0, double th) override; bool rescaleOnlyAspectRatio() override; auto cloneText() const -> std::unique_ptr<Text>; auto clone() const -> ElementPtr override; bool intersects(double x, double y, double halfEraserSize) const override; bool intersects(double x, double y, double halfEraserSize, double* gap) const override; public: // Serialize interface void serialize(ObjectOutputStream& out) const override; void readSerialized(ObjectInputStream& in) override; protected: void calcSize() const override; void updateSnapping() const; public: std::vector<XojPdfRectangle> findText(const std::string& search) const; private: XojFont font; std::string text; bool inEditing = false; };
2,032
C++
.h
60
30.35
108
0.730769
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,746
DocumentHandler.h
xournalpp_xournalpp/src/core/model/DocumentHandler.h
/* * Xournal++ * * Document handler * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #include <cstddef> // for size_t #include <list> // for list #include "DocumentChangeType.h" // for DocumentChangeType class DocumentListener; class DocumentHandler { public: DocumentHandler() = default; ~DocumentHandler() = default; public: void fireDocumentChanged(DocumentChangeType type); void firePageSizeChanged(size_t page); void firePageChanged(size_t page); void firePageInserted(size_t page); void firePageDeleted(size_t page); // void firePageLoaded(PageRef page); void firePageSelected(size_t page); private: void addListener(DocumentListener* l); void removeListener(DocumentListener* l); private: std::list<DocumentListener*> listener; friend class DocumentListener; };
913
C++
.h
34
23.764706
58
0.743383
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,747
FormatDefinitions.h
xournalpp_xournalpp/src/core/model/FormatDefinitions.h
/* * Xournal++ * * Abstract gui class, which loads the glade objcts * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once typedef struct { const char* name; const double scale; } FormatUnits; extern const FormatUnits XOJ_UNITS[]; extern const int XOJ_UNIT_COUNT;
345
C++
.h
17
18.117647
51
0.729231
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,748
AudioElement.h
xournalpp_xournalpp/src/core/model/AudioElement.h
/* * Xournal++ * * Element that is audio enabled * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #include <cstddef> // for size_t #include "Element.h" // for Element, ElementType #include "filesystem.h" // for path class ObjectInputStream; class ObjectOutputStream; class AudioElement: public Element { protected: AudioElement(ElementType type); public: ~AudioElement() override; void setTimestamp(size_t timestamp); size_t getTimestamp() const; void setAudioFilename(fs::path fn); auto getAudioFilename() const -> fs::path const&; virtual bool intersects(double x, double y, double halfSize) const = 0; virtual bool intersects(double x, double y, double halfSize, double* gap) const = 0; protected: void serialize(ObjectOutputStream& out) const override; void readSerialized(ObjectInputStream& in) override; void cloneAudioData(const AudioElement* other); private: // Stroke timestamp, to match it to the audio stream size_t timestamp = 0; fs::path audioFilename{}; };
1,122
C++
.h
36
28
88
0.736253
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,749
Image.h
xournalpp_xournalpp/src/core/model/Image.h
/* * Xournal++ * * An Image on the document * * @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 <string_view> // for string_view #include <utility> // for pair, make_pair #include <cairo.h> // for cairo_surface_t, cairo_status_t #include <gdk-pixbuf/gdk-pixbuf.h> // for GdkPixbufFormat, GdkPixbuf #include "Element.h" // for Element class ObjectInputStream; class ObjectOutputStream; class Image: public Element { public: Image(); Image(const Image&) = delete; Image& operator=(const Image&) = delete; Image(Image&&) = delete; Image& operator=(Image&&) = delete; virtual ~Image(); public: void setWidth(double width); void setHeight(double height); /// Set the image data by copying the data from the provided string_view. void setImage(std::string_view data); /// Set the image data by moving the data. void setImage(std::string&& data); /// Set the image data by copying the data from the provided pixbuf. /// /// \deprecated Pass the raw image data instead. /// /// FIXME: remove this method. Currently, it is used by Control::clipboardPasteImage. [[deprecated]] void setImage(GdkPixbuf* img); /// Returns the internal surface that contains the rendered image data. /// /// Note that the image is rendered lazily by default; call this method to render it. cairo_surface_t* getImage() const; void scale(double x0, double y0, double fx, double fy, double rotation, bool restoreLineWidth) override; void rotate(double x0, double y0, double th) override; auto clone() const -> ElementPtr override; bool hasData() const; /// Return a pointer to the raw data. Note that the pointer will be invalidated if the data is changed. const unsigned char* getRawData() const; /// Return the length of the raw data. size_t getRawDataLength() const; /// Return the size of the raw image, or (-1, -1) if the image has not been rendered yet. std::pair<int, int> getImageSize() const; [[maybe_unused]] GdkPixbufFormat* getImageFormat() const; static constexpr std::pair<int, int> NOSIZE = std::make_pair(-1, -1); public: // Serialize interface void serialize(ObjectOutputStream& out) const override; void readSerialized(ObjectInputStream& in) override; private: void calcSize() const override; static cairo_status_t cairoReadFunction(const Image* image, unsigned char* data, unsigned int length); private: /// Set the image data by rendering the surface to PNG and copying the PNG data. /// /// \deprecated Pass the raw image data instead. /// /// FIXME: remove this when setImage(GdkPixbuf*) is removed. [[deprecated]] void setImage(cairo_surface_t* image); /// Temporary surface used as a render buffer. mutable cairo_surface_t* image = nullptr; /// Image format information. mutable GdkPixbufFormat* format = nullptr; mutable std::pair<int, int> imageSize = {-1, -1}; std::string data; };
3,190
C++
.h
78
36.820513
108
0.696596
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,750
Compass.h
xournalpp_xournalpp/src/core/model/Compass.h
/* * Xournal++ * * A compass model * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #include "model/GeometryTool.h" /** * @brief A class that models a compass * * The compass has the shape of a circle and has a certain height (radius), may be rotated and * translated. User coordinates are specified in cm. */ namespace xoj::view { class CompassView; }; class CompassInputHandler; class Compass: public GeometryTool { public: Compass(); /** * @brief A compass specified by its radius, rotation angle and translations in x- and y-directions * @param height the radius of the compass * @param rotation the angle (in radian) around which the compass is rotated with respect to the x-axis * @param x the x-coordinate (in pt) of the center of the compass * @param y the y-coordinate (in pt) of the center of the compass */ Compass(double height, double rotation, double x, double y); virtual ~Compass(); void notify(bool resetMask) const override; // calls the update method of all observers Range getToolRange(bool transformed) const override; // parameters used when initially displaying the compass on a page static constexpr double INITIAL_HEIGHT = 3.0; };
1,310
C++
.h
39
30.384615
107
0.726408
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,751
OverlayBase.h
xournalpp_xournalpp/src/core/model/OverlayBase.h
/* * Xournal++ * * * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once /** * Empty base class for overlays: anything that is drawn over a document, but not in the document * (e.g. active tools, selections, search results highlighting...). * * This class is only used for pointer comparison. */ class OverlayBase { public: virtual ~OverlayBase() = default; };
444
C++
.h
21
19.190476
97
0.707838
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,752
LinkDestination.h
xournalpp_xournalpp/src/core/model/LinkDestination.h
/* * Xournal++ * * A link destination in a PDF Document * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #include <cstddef> // for size_t #include <optional> // for optional #include <string> // for string #include <variant> // for variant #include <glib-object.h> // for G_TYPE_CHECK_INSTANCE_CAST, GObject, GType #include <glib.h> // for G_GNUC_CONST struct _LinkDest; typedef struct _LinkDest XojLinkDest; typedef struct _LinkDestClass XojLinkDestClass; class LinkDestination { public: LinkDestination(); virtual ~LinkDestination(); /// A link to a URI. struct LinkType { std::string uri; }; /// A link to some unknown PDF action. struct UnknownType {}; /// Represents a possible PDF link action. using Type = std::variant<UnknownType, LinkType>; public: size_t getPdfPage() const; void setPdfPage(size_t page); void setExpand(bool expand); bool getExpand() const; bool shouldChangeLeft() const; bool shouldChangeTop() const; double getZoom() const; [[maybe_unused]] double getLeft() const; double getTop() const; void setChangeLeft(double left); void setChangeZoom(double zoom); void setChangeTop(double top); void setName(std::string name); const std::string& getName() const; /// \return Whether this link refers to a URI. bool isURI() const; std::optional<std::string> getURI() const; /// \return Changes this link to refer to the given URI. void setURI(std::string uri); private: size_t page; bool expand; double left; double top; double zoom; bool changeLeft; bool changeZoom; bool changeTop; std::string name; Type contents; }; struct _LinkDest { GObject base_instance; LinkDestination* dest; }; enum { DOCUMENT_LINKS_COLUMN_NAME, DOCUMENT_LINKS_COLUMN_LINK, DOCUMENT_LINKS_COLUMN_EXPAND, DOCUMENT_LINKS_COLUMN_PAGE_NUMBER }; #define TYPE_LINK_DEST (link_dest_get_type()) #define LINK_DEST(object) (G_TYPE_CHECK_INSTANCE_CAST((object), TYPE_LINK_DEST, XojLinkDest)) #define LINK_DEST_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST((klass), TYPE_LINK_DEST, XojLinkDestClass)) #define IS_LINK_DEST(object) (G_TYPE_CHECK_INSTANCE_TYPE((object), TYPE_LINK_DEST)) #define IS_LINK_DEST_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE((klass), TYPE_LINK_DEST)) #define LINK_DEST_GET_CLASS(object) (G_TYPE_INSTANCE_GET_CLASS((object), TYPE_LINK_DEST, XojLinkDestClass)) GType link_dest_get_type(void) G_GNUC_CONST; XojLinkDest* link_dest_new();
2,631
C++
.h
82
28.414634
107
0.708284
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,753
Element.h
xournalpp_xournalpp/src/core/model/Element.h
/* * Xournal++ * * An element on the Document * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #include <cstddef> // for ptrdiff_t #include <memory> // for unique_ptr #include <vector> // for vector #include <gdk/gdk.h> // for GdkRectangle #include "util/Color.h" // for Color #include "util/Rectangle.h" // for Rectangle #include "util/serializing/Serializable.h" // for Serializable class ObjectInputStream; class ObjectOutputStream; enum ElementType { ELEMENT_STROKE = 1, ELEMENT_IMAGE, ELEMENT_TEXIMAGE, ELEMENT_TEXT }; class ShapeContainer { public: virtual bool contains(double x, double y) const = 0; virtual ~ShapeContainer() = default; }; class Element; using ElementPtr = std::unique_ptr<Element>; class Element: public Serializable { protected: Element(ElementType type); public: ~Element() override = default; using Index = std::ptrdiff_t; static constexpr auto InvalidIndex = static_cast<Index>(-1); public: ElementType getType() const; void setX(double x); void setY(double y); double getX() const; double getY() const; virtual void move(double dx, double dy); virtual void scale(double x0, double y0, double fx, double fy, double rotation, bool restoreLineWidth) = 0; virtual void rotate(double x0, double y0, double th) = 0; void setColor(Color color); Color getColor() const; double getElementWidth() const; double getElementHeight() const; xoj::util::Rectangle<double> getSnappedBounds() const; xoj::util::Rectangle<double> boundingRect() const; virtual bool intersectsArea(const GdkRectangle* src) const; virtual bool intersectsArea(double x, double y, double width, double height) const; virtual bool isInSelection(ShapeContainer* container) const; virtual bool rescaleOnlyAspectRatio(); virtual bool rescaleWithMirror(); /** * Take 1:1 copy of this element */ virtual auto clone() const -> ElementPtr = 0; void serialize(ObjectOutputStream& out) const override; void readSerialized(ObjectInputStream& in) override; private: protected: virtual void calcSize() const = 0; protected: // If the size has been calculated mutable bool sizeCalculated = false; mutable double width = 0; mutable double height = 0; // The position on the screen mutable double x = 0; mutable double y = 0; // The position and dimensions on the screen used for snapping mutable xoj::util::Rectangle<double> snappedBounds{}; private: /** * Type of this element */ ElementType type; /** * The color in RGB format */ Color color{0U}; }; namespace xoj { auto refElementContainer(const std::vector<ElementPtr>& elements) -> std::vector<Element*>; } // namespace xoj
2,911
C++
.h
87
29.643678
111
0.708602
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,754
PageHandler.h
xournalpp_xournalpp/src/core/model/PageHandler.h
/* * Xournal++ * * Page handler * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #include <list> // for list #include <vector> #include "util/Range.h" // for Range class Element; class PageListener; class Range; namespace xoj::util { template <class T> class Rectangle; } // namespace xoj::util class PageHandler { public: PageHandler(); virtual ~PageHandler(); public: void fireRectChanged(xoj::util::Rectangle<double>& rect); void fireRangeChanged(Range& range); void fireElementChanged(Element* elem); /** * @brief The listed elements have been changed * @param range (optional) if provided, the Range must contain the bounding boxes of the changed elements, both * before and after they were changed */ void fireElementsChanged(const std::vector<Element*>& elements, Range range = Range()); void firePageChanged(); private: void addListener(PageListener* l); void removeListener(PageListener* l); private: std::list<PageListener*> listeners; friend class PageListener; };
1,132
C++
.h
43
23.325581
115
0.724074
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,755
Layer.h
xournalpp_xournalpp/src/core/model/Layer.h
/* * Xournal++ * * A layer on a page * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #include <cstddef> // for size_t #include <memory> // for unique_ptr #include <optional> // for optional #include <string> // for string #include <vector> // for vector #include "Element.h" // for Element, Element::Index #include "ElementInsertionPosition.h" // for InsertionOrder template <class T> using optional = std::optional<T>; class Layer { public: Layer(); virtual ~Layer(); using Index = size_t; public: /** * Appends an Element to this Layer * * @note Performs a check to determine whether the element is already contained in the Layer */ void addElement(ElementPtr e); /** * Inserts an Element in the specified position of the Layer%s internal list * * @note Performs a check to determine whether the element is already contained in the Layer */ void insertElement(ElementPtr e, Element::Index pos); /** * Returns the index of the given Element with respect to the internal list */ auto indexOf(Element* e) const -> Element::Index; /** * Removes an Element from the Layer and optionally deletes it * @return the position the element occupied */ auto removeElement(Element* e) -> InsertionPosition; /** * Removes the Element. If e is not at index pos, tries to find it elsewhere (this could happen is the layer was * modified between now and when pos was computed) * @return The actual position of the removed element */ auto removeElementAt(Element* e, Element::Index pos) -> InsertionPosition; /** * Removes the Elements. If an element cannot be found at its designated position, it is search through the layer */ auto removeElementsAt(InsertionOrderRef const& elts) -> InsertionOrder; /** * Removes all Elements from the Layer *without freeing them*. Returns the elements. */ auto clearNoFree() -> std::vector<ElementPtr>; /** * Returns an iterator over the Element%s contained in this Layer */ auto getElements() const -> std::vector<ElementPtr> const&; /** * Returns whether or not the Layer is empty */ auto isAnnotated() const -> bool; /** * @return true if the layer is visible */ auto isVisible() const -> bool; /** * @param visible true if the layer is visible */ void setVisible(bool visible); /** * Creates a deep copy of this Layer by copying all of the Element%s contained in it */ auto clone() const -> Layer*; /** * @return true if layer has a name */ auto hasName() const -> bool; /** * @return layer custom name or empty string if custom name is not set */ auto getName() const -> std::string; /** * Sets custom name for the layer */ void setName(const std::string& newName); private: std::vector<ElementPtr> elements; bool visible = true; std::optional<std::string> name; };
3,134
C++
.h
98
27.285714
117
0.664675
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,756
XojPage.h
xournalpp_xournalpp/src/core/model/XojPage.h
/* * Xournal++ * * A page (PDF or drawings or both) * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #include <cstddef> // for size_t #include <optional> // for optional #include <string> // for string #include <vector> // for vector #include "util/Color.h" // for Color #include "util/Util.h" // for npos #include "BackgroundImage.h" // for BackgroundImage #include "Layer.h" // for Layer, Layer::Index #include "PageHandler.h" // for PageHandler #include "PageType.h" // for PageType class XojPage: public PageHandler { public: XojPage(double width, double height, bool suppressLayerCreation = false); ~XojPage() override; XojPage(const XojPage& page); void operator=(const XojPage& p) = delete; // Do not modify layers directly, use LayerController // So notification can be sent on change protected: void addLayer(Layer* layer); void insertLayer(Layer* layer, Layer::Index index); void removeLayer(Layer* layer); void setLayerVisible(Layer::Index layerId, bool visible); public: // Also set the size over doc->setPageSize! void setBackgroundPdfPageNr(size_t page); void setBackgroundType(const PageType& bgType); PageType getBackgroundType(); /** * Do not call this, cal doc->setPageSize(Page * p, double width, double height); */ void setSize(double width, double height); double getWidth() const; double getHeight() const; size_t getPdfPageNr() const; bool isAnnotated() const; void setBackgroundColor(Color color); Color getBackgroundColor() const; std::vector<Layer*>* getLayers(); Layer::Index getLayerCount() const; Layer::Index getSelectedLayerId(); void setSelectedLayerId(Layer::Index id); bool isLayerVisible(Layer::Index layerId) const; Layer* getSelectedLayer(); BackgroundImage& getBackgroundImage(); void setBackgroundImage(BackgroundImage img); std::string getBackgroundName() const; bool backgroundHasName() const; void setBackgroundName(const std::string& newName); /** * Copies this page an all it's contents to a new page */ XojPage* clone(); private: /** * The Background image if any */ BackgroundImage backgroundImage; /** * The size of the page */ double width = 0; double height = 0; /** * The layer list */ std::vector<Layer*> layer; /** * The current selected layer ID */ Layer::Index currentLayer = npos; /** * The Background Type of the page */ PageType bgType; /** * If the page has a PDF background, the page number of the PDF Page */ size_t pdfBackgroundPage = npos; /** * The background color if the background type is plain */ Color backgroundColor{Colors::white}; /** * Background visible */ bool backgroundVisible = true; /** * Background name */ std::optional<std::string> backgroundName; // Allow LoadHandler to add layers directly friend class LoadHandler; // Allow LayerController to modify layers of a page // Notifications were be sent friend class LayerController; };
3,302
C++
.h
108
26.018519
85
0.678041
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,757
Snapping.h
xournalpp_xournalpp/src/core/model/Snapping.h
/* * Xournal++ * * Snapping methods * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #include "Point.h" namespace Snapping { /** * @brief If a value is near enough to the y-coordinate of a grid point, it returns the nearest y-coordinate of the * grid point. Otherwise the original value itself. * @param y the value * @param gridSize the distance to each snapping point * @param tolerance the tolerance as a fraction of a half grid diagonal (assumed to be between 0 and 1) */ [[nodiscard]] double snapVertically(double y, double gridSize, double tolerance); /** * @brief If a value is near enough to the x-coordinate of a grid point, it returns the nearest x-coordinate of the * grid point. Otherwise the original value itself. * @param x the value * @param gridSize the distance to each snapping point * @param tolerance the tolerance as a fraction of a half grid diagonal (assumed to be between 0 and 1) */ [[nodiscard]] double snapHorizontally(double x, double gridSize, double tolerance); /** * @brief If a points distance to the nearest grid point is under a certain tolerance, it returns the nearest * grid point. Otherwise the original Point itself. * @param pos the position * @param gridSize the distance to each snapping point * @param tolerance the tolerance as a fraction of a half grid diagonal (assumed to be between 0 and 1) */ [[nodiscard]] Point snapToGrid(Point const& pos, double gridSize, double tolerance); /** * @brief if the angles distance to a multiple quarter of PI is under a certain tolerance, it returns the latter. * Otherwise the original angle. * @param radian the angle (in radian) * @param tolerance the tolerance as a fraction of M_PI/8 (assumed to be between 0 and 1) */ [[nodiscard]] double snapAngle(double radian, double tolerance); /** * @brief Snaps the angle between the horizontal axis and the line between the given point and center * and returns the point rotated accordingly * @param pos the coordinate of the point * @param center the center of rotation * @param tolerance the tolerance as a fraction of M_PI/8 (assumed to be between 0 and 1) */ [[nodiscard]] Point snapRotation(Point const& pos, Point const& center, double tolerance); /** * @brief For a given point computes the nearest point on a straight line specified by two points lying on it * @param pos the given point * @param first the first point of the straight line * @param second the second point of the straight line */ [[nodiscard]] Point projToLine(Point const& pos, Point const& first, Point const& second); /** * @brief Computes the distance from a given point to a line sgement specified by its end points * @param pos the given point * @param first the first end point of the line segment * @param second the second end point of the line segment */ [[nodiscard]] double distanceLine(Point const& pos, Point const& first, Point const& second); } // namespace Snapping
3,014
C++
.h
67
43.119403
115
0.757576
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,758
DocumentChangeType.h
xournalpp_xournalpp/src/core/model/DocumentChangeType.h
/* * Xournal++ * * Enum which type of change is occurred * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once enum DocumentChangeType { DOCUMENT_CHANGE_CLEARED, DOCUMENT_CHANGE_COMPLETE, DOCUMENT_CHANGE_PDF_BOOKMARKS };
294
C++
.h
12
22.583333
109
0.75
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,759
GeometryTool.h
xournalpp_xournalpp/src/core/model/GeometryTool.h
/* * Xournal++ * * A geometry tool * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #include <cairo.h> // for cairo_matrix_t #include "model/OverlayBase.h" #include "model/Stroke.h" #include "util/DispatchPool.h" constexpr static double HALF_CM = 14.17; constexpr static double CM = 2. * HALF_CM; enum GeometryToolType { SETSQUARE, COMPASS }; /** * @brief A class that models a geometry tool * * The geometry tool has a certain height/size, may be rotated and * translated. User coordinates are specified in cm. */ namespace xoj::util { template <class T> class DispatchPool; } namespace xoj::view { class GeometryToolView; }; class GeometryToolInputHandler; class GeometryTool: public OverlayBase { public: /** * @brief A geometry tool specified by its height, rotation angle and translations in x- and y-directions * @param height the height (size parameter) of the geometry tool * @param rotation the angle (in radian) around which the geometry tool is rotated with respect to the x-axis * @param x the x-coordinate (in pt) of the rotation center * @param y the y-coordinate (in pt) of the rotation center */ GeometryTool(double height, double rotation, double x, double y); virtual ~GeometryTool(); void setHeight(double height); double getHeight() const; void setRotation(double rotation); double getRotation() const; void setTranslationX(double x); double getTranslationX() const; void setTranslationY(double y); double getTranslationY() const; cairo_matrix_t getMatrix() const; Stroke* getStroke() const; void setStroke(Stroke* s); const std::shared_ptr<xoj::util::DispatchPool<xoj::view::GeometryToolView>>& getViewPool() const; const std::shared_ptr<xoj::util::DispatchPool<GeometryToolInputHandler>>& getHandlerPool() const; virtual void notify(bool resetMask = false) const = 0; // calls the update method of all observers /** * @brief Returns the range for the tool alone (without stroke) * * @param transformed whether the range should be rotated and translated */ virtual Range getToolRange(bool transformed) const = 0; protected: /** * @brief the height of the geometry tool */ double height; /** * @brief the angle (in radian) around which the geometry tool is rotated with respect to the x-axis */ double rotation; /** * @brief the x-coordinate (in pt) of the rotation center */ double translationX; /** * @brief the y-coordinate (in pt) of the rotation center */ double translationY; Stroke* stroke = nullptr; std::shared_ptr<xoj::util::DispatchPool<xoj::view::GeometryToolView>> viewPool; std::shared_ptr<xoj::util::DispatchPool<GeometryToolInputHandler>> handlerPool; /** * @brief Bounding box of the geometry tool and stroke after its last update */ mutable Range lastRepaintRange; protected: /** * @brief computes the repaint range by uniting the stroke's repaint range with the geometry tool repaint range * @param rg the geometry tool repaint range */ Range computeRepaintRange(Range rg) const; };
3,281
C++
.h
94
30.819149
115
0.715054
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,760
PathParameter.h
xournalpp_xournalpp/src/core/model/PathParameter.h
/** * Xournal++ * * @brief Type for parameters of points on a path. * Similar to std::pair<size_t, double>, but with named variables * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once struct PathParameter { PathParameter() = default; PathParameter(size_t index, double t): index(index), t(t) {} ~PathParameter() = default; bool operator==(const PathParameter& p) const { return index == p.index && t == p.t; }; bool operator!=(const PathParameter& p) const { return !(*this == p); }; bool operator<(const PathParameter& p) const { return index < p.index || (index == p.index && t < p.t); }; bool operator>(const PathParameter& p) const { return index > p.index || (index == p.index && t > p.t); }; bool operator<=(const PathParameter& p) const { return index < p.index || (index == p.index && t <= p.t); }; bool operator>=(const PathParameter& p) const { return index > p.index || (index == p.index && t >= p.t); }; bool isValid() const { return t <= 1.0 && t >= 0.0; } size_t index; double t; };
1,124
C++
.h
26
39.846154
112
0.630713
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,761
TexImage.h
xournalpp_xournalpp/src/core/model/TexImage.h
/* * Xournal++ * * A TexImage on the document * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #include <memory> #include <string> // for string #include <cairo.h> // for cairo_surface_t, cairo_status_t #include <glib.h> // for GError #include <poppler.h> // for PopplerDocument #include "util/raii/GObjectSPtr.h" // for GObjectSPtr #include "Element.h" // for Element class ObjectInputStream; class ObjectOutputStream; class TexImage: public Element { public: TexImage(); TexImage(const TexImage&) = delete; TexImage& operator=(const TexImage&) = delete; TexImage(const TexImage&&) = delete; TexImage&& operator=(const TexImage&&) = delete; ~TexImage() override; public: void setWidth(double width); void setHeight(double height); /** * Returns the binary data (PDF or PNG (deprecated)). */ const std::string& getBinaryData() const; /** * @return The image, if render source is PNG. Note: this is deprecated. */ cairo_surface_t* getImage() const; /** * @return The PDF Document, if rendered as a PDF. * * The document needs to be referenced, if it will be hold somewhere */ PopplerDocument* getPdf() const; void scale(double x0, double y0, double fx, double fy, double rotation, bool restoreLineWidth) override; void rotate(double x0, double y0, double th) override; // text tag to alow latex void setText(std::string text); std::string getText() const; auto cloneTexImage() const -> std::unique_ptr<TexImage>; auto clone() const -> ElementPtr override; /** * @return true if the binary data (PNG or PDF) was loaded successfully. */ bool loadData(std::string&& bytes, GError** err = nullptr); public: // Serialize interface void serialize(ObjectOutputStream& out) const override; void readSerialized(ObjectInputStream& in) override; private: void calcSize() const override; static cairo_status_t cairoReadFunction(TexImage* image, unsigned char* data, unsigned int length); /** * Free image and PDF */ void freeImageAndPdf(); private: /** * Tex PDF Document, if rendered as PDF */ xoj::util::GObjectSPtr<PopplerDocument> pdf; /** * Tex image, if rendered as image. Note: this is deprecated and subject to removal in a later version. */ cairo_surface_t* image = nullptr; /** * PNG Image / PDF Document */ std::string binaryData; /** * Read position for PNG binaryData (deprecated). */ std::string::size_type read = 0; /** * Tex String */ std::string text; };
2,741
C++
.h
89
26.382022
108
0.67225
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,762
Stroke.h
xournalpp_xournalpp/src/core/model/Stroke.h
/* * Xournal++ * * A stroke on the document * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #include <cstddef> // for size_t #include <memory> // for unique_ptr #include <vector> // for vector #include "model/Element.h" #include "AudioElement.h" // for AudioElement #include "LineStyle.h" // for LineStyle #include "Point.h" // for Point class Element; class ObjectInputStream; class ObjectOutputStream; class ShapeContainer; class StrokeTool { public: enum Value { PEN, ERASER, HIGHLIGHTER }; StrokeTool(Value v): value(v) {} [[nodiscard]] bool isPressureSensitive() const { return value == PEN; } [[nodiscard]] bool hasLineStyle() const { return value == PEN; } operator const Value&() const { return value; } operator Value&() { return value; } private: Value value = PEN; }; enum StrokeCapStyle { ROUND = 0, BUTT = 1, SQUARE = 2 }; // Must match the indices in StrokeView::CAIRO_LINE_CAP // and in EraserHandler::PADDING_COEFFICIENT_CAP class ErasableStroke; struct PaddedBox; struct PathParameter; template <class T, size_t N> class SmallVector; using IntersectionParametersContainer = SmallVector<PathParameter, 4>; class Stroke: public AudioElement { public: Stroke(); Stroke(Stroke const&) = default; Stroke(Stroke&&) = default; Stroke& operator=(Stroke const&) = default; Stroke& operator=(Stroke&&) = default; ~Stroke() override; public: auto cloneStroke() const -> std::unique_ptr<Stroke>; auto clone() const -> ElementPtr override; /** * @brief Create a partial clone whose points are those of parameters between lowerBound and upperBound * Assumes both lowerBound and upperBound are valid parameters of the stroke, and lowerBound <= upperBound */ std::unique_ptr<Stroke> cloneSection(const PathParameter& lowerBound, const PathParameter& upperBound) const; /** * @brief Create a partial clone of a closed stroke (i.e. points.front() == points.back()) with points * getPoint(startParam) -- ... -- points.back() == points.front() -- ... -- getPoint(endParam) * Assumes both startParam and endParam are valid parameters of the stroke, and endParam.index < startParam.index */ std::unique_ptr<Stroke> cloneCircularSectionOfClosedStroke(const PathParameter& startParam, const PathParameter& endParam) const; /** * Clone style attributes, but not the data (position, width etc.) */ void applyStyleFrom(const Stroke* other); void setWidth(double width); double getWidth() const; /** * Option to fill the shape: * -1: The shape is not filled * 255: The shape is fully opaque filled * ... * 1: The shape is nearly fully transparent filled */ int getFill() const; /** * Option to fill the shape: * -1: The shape is not filled * 255: The shape is fully opaque filled * ... * 1: The shape is nearly fully transparent filled */ void setFill(int fill); void addPoint(const Point& p); size_t getPointCount() const; void freeUnusedPointItems(); std::vector<Point> const& getPointVector() const; Point getPoint(size_t index) const; Point getPoint(PathParameter parameter) const; const Point* getPoints() const; /** * @brief Replace the stroke's points by the ones in the provided vector (they will be copied). * @param other New vector of points for the stroke * @param snappingBox (optional) Precomputed snapping box of the new points (i.e. the smallest Range containing all * the points, stroke width or pressure values not being considered). The snappingBox parameter avoids a * recomputation of the bounding boxes if the new points have no pressure values. */ void setPointVector(const std::vector<Point>& other, const Range* const snappingBox = nullptr); void setPointVector(std::vector<Point>&& other, const Range* const snappingBox = nullptr); private: void setPointVectorInternal(const Range* const snappingBox); public: void deletePointsFrom(size_t index); void setToolType(StrokeTool type); StrokeTool getToolType() const; const LineStyle& getLineStyle() const; void setLineStyle(const LineStyle& style); bool intersects(double x, double y, double halfEraserSize) const override; bool intersects(double x, double y, double halfEraserSize, double* gap) const override; /** * @brief Find the parameters within a certain interval corresponding to the points where the stroke crosses in * or out of the given box with its padding. Intersections are ignored if the stroke does not hit the small box * itself. * @param box The padded box * @param firstIndex The lower bound of the interval * @param lastIndex The upper bound of the interval * @return The parameters (sorted). The size of the returned vector is always even. * * Warning: this function does not test if the box intersects the stroke's bounding box. * For optimization purposes, this test should be performed beforehand by the caller. */ IntersectionParametersContainer intersectWithPaddedBox(const PaddedBox& box, size_t firstIndex, size_t lastIndex) const; IntersectionParametersContainer intersectWithPaddedBox(const PaddedBox& box) const; void setPressure(const std::vector<double>& pressure); void setLastPressure(double pressure); void setSecondToLastPressure(double pressure); void clearPressure(); void scalePressure(double factor); /** * @brief Update the stroke's bounding box using the second-to-last point's pressure value and the last two points. */ void updateBoundsLastTwoPressures(); bool hasPressure() const; double getAvgPressure() const; void move(double dx, double dy) override; void scale(double x0, double y0, double fx, double fy, double rotation, bool restoreLineWidth) override; void rotate(double x0, double y0, double th) override; bool isInSelection(ShapeContainer* container) const override; ErasableStroke* getErasable() const; void setErasable(ErasableStroke* erasable); StrokeCapStyle getStrokeCapStyle() const; void setStrokeCapStyle(const StrokeCapStyle capStyle); [[maybe_unused]] void debugPrint() const; public: // Serialize interface void serialize(ObjectOutputStream& out) const override; void readSerialized(ObjectInputStream& in) override; bool rescaleWithMirror() override; protected: void calcSize() const override; private: // The stroke width cannot be inherited from Element double width = 0; StrokeTool toolType = StrokeTool::PEN; // The array with the points std::vector<Point> points{}; /** * Dashed line */ LineStyle lineStyle; ErasableStroke* erasable = nullptr; /** * Option to fill the shape: * -1: The shape is not filled * 255: The shape is fully opaque filled * ... * 1: The shape is nearly fully transparent filled */ int fill = -1; StrokeCapStyle capStyle = StrokeCapStyle::ROUND; };
7,367
C++
.h
179
35.905028
119
0.704004
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,763
SplineSegment.h
xournalpp_xournalpp/src/core/model/SplineSegment.h
/* * Xournal++ * * A spline segment * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #include <list> // for list #include <utility> // for pair #include <cairo.h> // for cairo_t #include "model/Point.h" // for Point /** * @brief A class to handle splines segments * * Every spline segment is defined by two knot points and two control points. * This contrasts to the cairo-draw command cairo_curve_to, where everything is relative to the current position of * another knot, */ class SplineSegment { public: SplineSegment() = default; /** * @brief A linear spline segment from two points * @param p the first knot * @param q the second knot */ SplineSegment(const Point& p, const Point& q); /** * @brief A spline segment from four points * @param p the first knot * @param fp the first control point * @param sp the second control point * @param q the second knot */ SplineSegment(const Point& p, const Point& fp, const Point& sp, const Point& q); /** * @brief draw the spline segment via the cairo_curve_to command * @param cr the cairo context on which the spline segment ought to be drawn */ void draw(cairo_t* cr) const; /** * @brief Convert the spline segment to a list of points. * @param usePressure If true, interpolate the pressure along the spline. Default: false * @return A point list which represents the spline segment without the end point. */ std::list<Point> toPointSequence(bool usePressure = false) const; /** * @brief Subdivide the spline into two parts with respect to parameter t. * @param t the parameter between 0 and 1, which corresponds to the point where the spline is split * @param usePressure If true, infer pressure values for the resulting SplineSegments' endpoints. Default: false. * @return A pair of two spline segments corresponding to the two parts of the spline */ std::pair<SplineSegment, SplineSegment> subdivide(float t, bool usePressure = false) const; /** * @brief Interpolate a line segment with respect to parameter t * @param t the parameter between 0 and 1, which corresponds to the point on the line segment * @param p the starting point of the line segment * @param q the end point of the line segment * @return A point on the line segment which corresponds to the parameter value t */ static Point linearInterpolate(const Point& p, const Point& q, float t); /** * @brief checks if the spline segment is flat enough so that it can be drawn as a straight line * @param usePressure If true, return false if the endpoints' pressure values are to far appart. Default: false. * @return true, if the spline segment is flat enough; false otherwise */ bool isFlatEnough(bool usePressure = false) const; public: /** * @brief The first knot of the spline segment. */ Point firstKnot; /** * @brief The second knot of the spline segment. */ Point secondKnot; /** * @brief The first control point of the spline segment. */ Point firstControlPoint; /** * @brief The second control point of the spline segment. */ Point secondControlPoint; };
3,377
C++
.h
89
33.269663
117
0.691554
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,764
PageType.h
xournalpp_xournalpp/src/core/model/PageType.h
/* * Xournal++ * * Paper background type * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #include <string> // for string enum class PageTypeFormat { Plain, Ruled, Lined, Staves, Graph, Dotted, IsoDotted, IsoGraph, Pdf, Image }; class PageType { public: PageType(); explicit PageType(PageTypeFormat format); PageType(const PageType& other); ~PageType(); private: public: /** * Compare Operator */ bool operator==(const PageType& other) const; bool operator!=(const PageType& other) const; /** * PDF background */ bool isPdfPage() const; /** * Image Background */ bool isImagePage() const; /** * Special background */ bool isSpecial() const; public: /** * Base format */ PageTypeFormat format; /** * Arguments for the format */ std::string config; };
966
C++
.h
48
16.041667
106
0.636163
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,765
BackgroundImage.h
xournalpp_xournalpp/src/core/model/BackgroundImage.h
/* * Xournal++ * * A background image of a page * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #include <memory> // for shared_ptr #include <gdk-pixbuf/gdk-pixbuf.h> // for GdkPixbuf #include <gio/gio.h> // for GInputStream #include <glib.h> // for GError #include "filesystem.h" // for path struct BackgroundImage { BackgroundImage(); BackgroundImage(const BackgroundImage& img); BackgroundImage(BackgroundImage&& img) noexcept; ~BackgroundImage(); BackgroundImage& operator=(const BackgroundImage& img) = default; BackgroundImage& operator=(BackgroundImage&& img) = default; bool operator==(const BackgroundImage& img); void free(); void loadFile(fs::path const& filepath, GError** error); void loadFile(GInputStream* stream, fs::path const& filepath, GError** error); int getCloneId(); void setCloneId(int id); void clearSaveState(); fs::path getFilepath() const; void setFilepath(fs::path filepath); bool isAttached() const; void setAttach(bool attach); GdkPixbuf* getPixbuf() const; bool isEmpty() const; private: struct Content; std::shared_ptr<Content> img; };
1,283
C++
.h
40
28.325
82
0.692496
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,766
DocumentListener.h
xournalpp_xournalpp/src/core/model/DocumentListener.h
/* * Xournal++ * * Document listener * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #include <cstddef> // for size_t #include "DocumentChangeType.h" // for DocumentChangeType class DocumentHandler; class DocumentListener { public: DocumentListener(); virtual ~DocumentListener(); public: void registerListener(DocumentHandler* handler); void unregisterListener(); virtual void documentChanged(DocumentChangeType type); virtual void pageSizeChanged(size_t page); virtual void pageChanged(size_t page); virtual void pageInserted(size_t page); virtual void pageDeleted(size_t page); virtual void pageSelected(size_t page); private: DocumentHandler* handler = nullptr; };
800
C++
.h
30
23.633333
58
0.753281
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,767
ElementInsertionPosition.h
xournalpp_xournalpp/src/core/model/ElementInsertionPosition.h
/* * Xournal++ * * The position (depth) of an element * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #include <limits> #include <vector> #include "Element.h" struct InsertionPositionRef { constexpr InsertionPositionRef() = default; constexpr explicit InsertionPositionRef(Element* e, Element::Index pos = std::numeric_limits<Element::Index>::max()): e(e), pos(pos) {} Element* e{}; Element::Index pos{}; constexpr friend auto operator<(const InsertionPositionRef& p1, const InsertionPositionRef& p2) -> bool { return p1.pos < p2.pos; } }; struct InsertionPosition { constexpr InsertionPosition() = default; explicit InsertionPosition(ElementPtr e, Element::Index pos = std::numeric_limits<Element::Index>::max()): e(std::move(e)), pos(pos) {} auto ref() const -> InsertionPositionRef { return InsertionPositionRef{e.get(), pos}; } ElementPtr e; Element::Index pos{}; constexpr friend auto operator<(const InsertionPosition& p1, const InsertionPosition& p2) -> bool { return p1.pos < p2.pos; } constexpr friend auto operator<(Element::Index pos, const InsertionPosition& p2) -> bool { return pos < p2.pos; } constexpr friend auto operator<(const InsertionPosition& p2, Element::Index pos) -> bool { return p2.pos < pos; } }; using InsertionOrder = std::vector<InsertionPosition>; // using InsertionOrderRef = std::span<InsertionPositionRef const>; (cpp20, optional cpp26 (implicit conversion from // vector)) using InsertionOrderRef = std::vector<InsertionPositionRef>; inline auto refInsertionOrder(InsertionOrder const& order) -> InsertionOrderRef { InsertionOrderRef ref(order.size()); std::transform(order.begin(), order.end(), ref.begin(), [](auto const& pos) { return pos.ref(); }); return ref; }
1,948
C++
.h
47
36.680851
117
0.694547
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,768
Document.h
xournalpp_xournalpp/src/core/model/Document.h
/* * Xournal++ * * The document * * All methods are unlocked, you need to lock the document before you change something and unlock after. * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #include <cstddef> // for size_t #include <memory> // for unique_ptr #include <mutex> // for mutex #include <string> // for string #include <unordered_map> // for unordered_map #include <vector> // for vector #include <cairo.h> // for cairo_surface_t #include <glib.h> // for gpointer, gsize #include <gtk/gtk.h> // for GtkTreeModel, GtkTreeIter, GtkT... #include "pdf/base/XojPdfDocument.h" // for XojPdfDocument #include "pdf/base/XojPdfPage.h" // for XojPdfPageSPtr #include "util/raii/GObjectSPtr.h" // for GObjectSptr #include "PageRef.h" // for PageRef #include "filesystem.h" // for path class DocumentHandler; class XojPdfBookmarkIterator; class Document { public: Document(DocumentHandler* handler); virtual ~Document(); public: enum DocumentType { XOPP, XOJ, PDF }; void setPdfAttributes(const fs::path& filename, bool attachToDocument); bool readPdf(const fs::path& filename, bool initPages, bool attachToDocument, std::unique_ptr<std::string> data = {}); void resetPdf(); size_t getPageCount() const; size_t getPdfPageCount() const; XojPdfPageSPtr getPdfPage(size_t page) const; const XojPdfDocument& getPdfDocument() const; void insertPage(const PageRef& p, size_t position); void addPage(const PageRef& p); template <class InputIter> void addPages(InputIter first, InputIter last); PageRef getPage(size_t page) const; void deletePage(size_t pNr); static void setPageSize(PageRef p, double width, double height); static double getPageWidth(PageRef p); static double getPageHeight(PageRef p); size_t indexOf(const PageRef& page); /** * @return The last error message to show to the user */ std::string getLastErrorMsg() const; size_t findPdfPage(size_t pdfPage); Document& operator=(const Document& doc); void setFilepath(fs::path filepath); fs::path getFilepath() const; fs::path getPdfFilepath() const; fs::path createSaveFolder(fs::path lastSavePath); fs::path createSaveFilename(DocumentType type, const std::string& defaultSaveName, const std::string& defaultPfdName = ""); fs::path getEvMetadataFilename() const; GtkTreeModel* getContentsModel() const; void setCreateBackupOnSave(bool backup); bool shouldCreateBackupOnSave() const; void clearDocument(bool destroy = false); bool isAttachPdf() const; cairo_surface_t* getPreview() const; void setPreview(cairo_surface_t* preview); void lock(); void unlock(); bool tryLock(); private: void buildContentsModel(); void freeTreeContentModel(); static bool freeTreeContentEntry(GtkTreeModel* treeModel, GtkTreePath* path, GtkTreeIter* iter, Document* doc); void buildTreeContentsModel(GtkTreeIter* parent, XojPdfBookmarkIterator* iter); void updateIndexPageNumbers(); static bool fillPageLabels(GtkTreeModel* treeModel, GtkTreePath* path, GtkTreeIter* iter, Document* doc); private: DocumentHandler* handler = nullptr; XojPdfDocument pdfDocument; fs::path filepath; fs::path pdfFilepath; bool attachPdf = false; /** * Password: not handled yet */ std::string password; std::string lastError; /** * The pages in the document */ std::vector<PageRef> pages; /** * Index from pdf page number to document page number */ using PageIndex = std::unordered_map<size_t, size_t>; /** * The cached page index */ std::unique_ptr<PageIndex> pageIndex; /** * Creates an index from pdf page number to document page number * * Clears the index first in case it is already exists. */ void indexPdfPages(); /** * The bookmark contents model */ xoj::util::GObjectSPtr<GtkTreeModel> contentsModel; /** * create a backup before save */ bool createBackupOnSave = false; /** * The preview for the file */ cairo_surface_t* preview = nullptr; /** * The lock of the document */ std::mutex documentLock; }; template <class InputIter> void Document::addPages(InputIter first, InputIter last) { this->pages.insert(this->pages.end(), first, last); this->pageIndex.reset(); updateIndexPageNumbers(); }
4,622
C++
.h
134
29.985075
127
0.695369
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,770
Setsquare.h
xournalpp_xournalpp/src/core/model/Setsquare.h
/* * Xournal++ * * A setsquare model * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #include <cmath> #include "model/GeometryTool.h" /** * @brief A class that models a setsquare * * The setsquare has the shape of a right-angled isosceles triangle and has a certain height, may be rotated and * translated. User coordinates are specified in cm. */ class SetsquareInputHandler; namespace xoj::view { class SetsquareView; }; class Setsquare: public GeometryTool { public: Setsquare(); /** * @brief A setsquare specified by its height, rotation angle and translations in x- and y-directions * @param height the height of the setsquare * @param rotation the angle (in radian) around which the setsquare is rotated with respect to the x-axis * @param x the x-coordinate o(in pt) f the mid point of the longest side of the setsquare * @param y the y-coordinate (in pt) of the mid point of the longest side of the setsquare */ Setsquare(double height, double rotation, double x, double y); virtual ~Setsquare(); void notify(bool resetMask) const override; // calls the update method of all observers Range getToolRange(bool transformed) const override; // parameters used when initially displaying setsquare on a page static constexpr double INITIAL_HEIGHT = 8.0; // relation between setsquare height and radius static constexpr double DISTANCE_SEMICIRCLE_FROM_LEGS = 1.15; static inline double radiusFromHeight(double height) { return height / std::sqrt(2.) - DISTANCE_SEMICIRCLE_FROM_LEGS; } };
1,671
C++
.h
45
33.644444
112
0.736059
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,771
PaddedBox.h
xournalpp_xournalpp/src/core/model/eraser/PaddedBox.h
/** * Xournal++ * * @brief Small structure for a square with a padding * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #include "model/Point.h" #include "util/Rectangle.h" struct PaddedBox { Point center; double halfSize; double halfSizeWithPadding; xoj::util::Rectangle<double> getInnerRectangle() const { return {center.x - halfSize, center.y - halfSize, 2 * halfSize, 2 * halfSize}; } xoj::util::Rectangle<double> getOuterRectangle() const { return {center.x - halfSizeWithPadding, center.y - halfSizeWithPadding, 2 * halfSizeWithPadding, 2 * halfSizeWithPadding}; } void addToRange(Range& range) const { range.addPoint(center.x - halfSizeWithPadding, center.y - halfSizeWithPadding); range.addPoint(center.x + halfSizeWithPadding, center.y + halfSizeWithPadding); } };
939
C++
.h
29
28
104
0.698343
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,772
ErasableStroke.h
xournalpp_xournalpp/src/core/model/eraser/ErasableStroke.h
/* * Xournal++ * * A stroke which is temporary used if you erase a part * This class remembers which sections of a stroke have not yet been erased, until the eraser sequence is concluded * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #include <memory> // for unique_ptr #include <mutex> // for mutex #include <utility> // for pair #include <vector> // for vector #include "model/PathParameter.h" // for PathParameter #include "model/Stroke.h" // for Stroke (ptr only), IntersectionPa... #include "util/Interval.h" // for Interval #include "util/Rectangle.h" // for Rectangle #include "util/UnionOfIntervals.h" // for UnionOfIntervals #include "config-debug.h" // for DEBUG_ERASABLE_STROKE_BOXES #ifdef DEBUG_ERASABLE_STROKE_BOXES #include <cairo.h> // for cairo_t #include "view/Mask.h" #endif class Range; struct PaddedBox; class ErasableStroke { public: ErasableStroke(const Stroke& stroke); ~ErasableStroke(); /** * @brief Type for subsections of a stroke */ using SubSection = Interval<PathParameter>; public: /** * @brief Starts erasing the stroke, with the already computed intersection parameters * @param intersectionParameters Vector of even length containing the parameters of the sections to be erased * @param range Range (destined to rerendering) that will be widened around the eraser box * @param view Redrawable to which we pass areas that need rerendering * view is only used when the stroke is from the highlighter tool. * The rerendered areas correspond to where the stroke overlaps itself after being split in two (or more) */ void beginErasure(const IntersectionParametersContainer& intersectionParameters, Range& range); /** * @brief Erase the stroke * @param box PaddedBox of the eraser * @param range Range (destined to rerendering) that will be widened around the eraser box * @param view Redrawable to which we pass areas that need rerendering * view is only used when the stroke is from the highlighter tool. * The rerendered areas correspond to where the stroke overlaps itself after being split in two (or more) */ void erase(const PaddedBox& box, Range& range); /** * @brief Get the resulting strokes (if any) once the erasing is finished * @return A vector of pointers to newly created strokes (owned by the caller). * The resulting strokes correspond to what's left of the original stroke */ std::vector<std::unique_ptr<Stroke>> getStrokes() const; /** * @brief Get a clone of the data, in the form of a vector of sections * @return The clone */ std::vector<ErasableStroke::SubSection> getRemainingSubSectionsVector() const; /** * @return true if the stroke is closed (i.e. the first and last knots are very close), false otherwise. */ bool isClosedStroke() const; /** * @brief Get the bounding box of a subsection. * The bounding box is either pulled from cache or computed and added to cache * @return The bounding box. */ const Range& getSubSectionBoundingBox(const SubSection& section) const; protected: /** * @brief Compute the bounding box of a subsection. * @return The bounding box. */ Range computeSubSectionBoundingBox(const SubSection& section) const; /** * @brief Given a vector of subsections, compute (coarsely) where those subsections overlap. * @param subsections The input subsections * @return Vector of disjoint rectangles. Altogether, those rectangles contains all the overlaps of the subsections */ void addOverlapsToRange(const std::vector<SubSection>& subsections, Range& range); public: /** * @brief Reference to the stroke being erased */ const Stroke& stroke; protected: /** * @brief Parameters for the subsections that have not (yet) been erased * Protected by the associated mutex */ UnionOfIntervals<PathParameter> remainingSections{}; mutable std::mutex sectionsMutex; /** * @brief Cache for the bounding boxes of the remaining subsections * Usually pretty small (< 10): std::vector is faster than std::map * Protected by the associated mutex */ mutable std::vector<std::pair<SubSection, Range>> boundingBoxes; mutable std::mutex boxesMutex; /** * @brief Whether or not the last iteration erased anything */ bool changesAtLastIteration = false; /** * @brief Whether the stroke is closed (i.e. the first and last knots are very close) */ bool closedStroke; static constexpr double CLOSED_STROKE_DISTANCE = 0.3; #ifdef DEBUG_ERASABLE_STROKE_BOXES public: mutable xoj::view::Mask debugMask; static void paintDebugRect(const xoj::util::Rectangle<double>& rect, char color, cairo_t* cr); #endif public: /** * Binary tree used for searching for overlaps between subsections */ class OverlapTree; };
5,103
C++
.h
127
35.732283
119
0.712381
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,773
ErasableStrokeOverlapTree.h
xournalpp_xournalpp/src/core/model/eraser/ErasableStrokeOverlapTree.h
/* * Xournal++ * * A stroke which is temporary used if you erase a part * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #include <cstddef> // for size_t #include <utility> // for pair #include <vector> // for vector, vector<>::iterator #include <cairo.h> // for cairo_t #include "util/Rectangle.h" // for Rectangle #include "ErasableStroke.h" // for ErasableStroke::SubSection, ErasableStroke #include "config-debug.h" // for DEBUG_ERASABLE_STROKE_BOXES class Point; class Range; class Stroke; class ErasableStroke::OverlapTree { public: OverlapTree() = default; /** * @brief Populate the tree, so that it corresponds to the given section of the given stroke. */ void populate(const SubSection& section, const Stroke& stroke); bool isPopulated() const; #ifdef DEBUG_ERASABLE_STROKE_BOXES /** * @brief Add to a vector rectangles which altogether contain every overlap between the subsection corresponding * to this tree and the subsection corresponding to another tree. * @param other The other tree * @param halfWidth half the width of the stroke * @param overlapBoxes the Rectangle vector to which we push * @param cr A cairo context in which we paint the rectangles, for debug purposes */ void addOverlapsToRange(const OverlapTree& other, double halfWidth, Range& range, cairo_t* cr = nullptr) const; #else /** * @brief Add to a vector rectangles which altogether contain every overlap between the subsection corresponding * to this tree and the subsection corresponding to another tree. * @param other The other tree * @param halfWidth half the width of the stroke * @param overlapBoxes the Rectangle vector to which we push */ void addOverlapsToRange(const OverlapTree& other, double halfWidth, Range& range) const; #endif private: /** * Root, node or leaf of a binary tree used for searching for overlaps between subsections */ class Node { public: Node() = default; #ifdef DEBUG_ERASABLE_STROKE_BOXES /** * @brief Add to a vector rectangles which altogether contain every overlap between the subsection corresponding * to this node and the subsection corresponding to another node. * @param other The other node * @param halfWidth half the width of the stroke * @param overlapBoxes the Rectangle vector to which we push * @param cr A cairo context in which we paint the rectangles, for debug purposes */ void addOverlapsToRange(const Node& other, double halfWidth, Range& range, cairo_t* cr) const; #else /** * @brief Add to a vector rectangles which altogether contain every overlap between the subsection corresponding * to this node and the subsection corresponding to another node. * @param other The other node * @param halfWidth half the width of the stroke * @param overlapBoxes the Rectangle vector to which we push */ void addOverlapsToRange(const Node& other, double halfWidth, Range& range) const; #endif /** * Bounding box of the subsection represented by the node. * WARNING: The bounding box does not take the stroke thickness into account */ double minX; double maxX; double minY; double maxY; /** * Descendants, corresponding to the two halves of the subsection represented by the node */ std::pair<Node, Node>* children = nullptr; /** * @brief Initialize the bounding box (minX, maxX, minY, maxY) when the node corresponds to a single segment * @param p1 The first endpoint of the segment * @param p2 The second endpoint of the segment */ void initializeOnSegment(const Point& p1, const Point& p2); /** * @brief Compute the node's bounding box by taking the union of the children's boxes */ void computeBoxFromChildren(); /** * @brief Get a rectangle from the box (minX, maxX, minY, maxY), with an additional padding * @param padding Padding added to the box (typically, half the stroke's width) */ xoj::util::Rectangle<double> toRectangle(double padding) const; }; Node root; std::vector<std::pair<Node, Node>> data; bool populated = false; class Populator { public: Populator(std::vector<std::pair<Node, Node>>& data, const Stroke& stroke): data(data), stroke(stroke) {} void populate(const SubSection& section, Node& root); private: std::vector<std::pair<Node, Node>>& data; const Stroke& stroke; std::vector<std::pair<Node, Node>>::iterator nextFreeSlot; std::pair<Node, Node>* getNextFreeSlot(); /** * @brief Create a root corresponding to the subsection: * firstPoint -- pts[min] -- ... -- pts[max] -- lastPoint */ void populateNode(Node& node, const Point& firstPoint, size_t min, size_t max, const Point& lastPoint, const std::vector<Point>& pts); /** * @brief Create a subtree corresponding to the subsection: * firstPoint -- pts[min] -- ... -- pts[max] */ void populateNode(Node& node, const Point& firstPoint, size_t min, size_t max, const std::vector<Point>& pts); /** * @brief Create a subtree corresponding to the subsection: * pts[min] -- ... -- pts[max] -- lastPoint */ void populateNode(Node& node, size_t min, size_t max, const Point& lastPoint, const std::vector<Point>& pts); /** * @brief Create a subtree corresponding to the subsection: * pts[min] -- ... -- pts[max] */ void populateNode(Node& node, size_t min, size_t max, const std::vector<Point>& pts); }; };
6,032
C++
.h
139
36.446043
120
0.656841
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,774
FillUndoAction.h
xournalpp_xournalpp/src/core/undo/FillUndoAction.h
/* * Xournal++ * * Undo action resize * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #include <string> // for string #include <vector> // for vector #include "model/PageRef.h" // for PageRef #include "UndoAction.h" // for UndoAction class Layer; class FillUndoActionEntry; class Stroke; class Control; class FillUndoAction: public UndoAction { public: FillUndoAction(const PageRef& page, Layer* layer); ~FillUndoAction() override; public: bool undo(Control* control) override; bool redo(Control* control) override; std::string getText() override; void addStroke(Stroke* s, int originalFill, int newFill); private: std::vector<FillUndoActionEntry*> data; Layer* layer; };
795
C++
.h
32
22.25
61
0.734396
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,775
TextBoxUndoAction.h
xournalpp_xournalpp/src/core/undo/TextBoxUndoAction.h
/* * Xournal++ * * Undo action for insert (write text, draw stroke...) * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #include <string> // for string #include "model/PageRef.h" // for PageRef #include "UndoAction.h" // for UndoAction class Element; class Layer; class Control; using ElementPtr = std::unique_ptr<Element>; class TextBoxUndoAction: public UndoAction { public: TextBoxUndoAction(const PageRef& page, Layer* layer, Element* element, ElementPtr oldelement); ~TextBoxUndoAction() override; public: auto undo(Control* control) -> bool override; auto redo(Control* control) -> bool override; auto getText() -> std::string override; private: Layer* layer; Element* element; ElementPtr oldelement; };
831
C++
.h
31
24.16129
98
0.729114
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,776
MoveSelectionToLayerUndoAction.h
xournalpp_xournalpp/src/core/undo/MoveSelectionToLayerUndoAction.h
/* * Xournal++ * * Undo action for moving selection between layers * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #include <set> // for multiset #include <string> // for string #include "model/Element.h" // for Element #include "model/PageRef.h" // for PageRef #include "control/layer/LayerController.h" // for LayerController #include "PageLayerPosEntry.h" // for PageLayerPosEntry #include "UndoAction.h" // for UndoAction class Control; class Layer; class MoveSelectionToLayerUndoAction: public UndoAction { public: MoveSelectionToLayerUndoAction(const PageRef& page, LayerController* layerController, Layer* oldLayer, size_t oldLayerNo, size_t newLayerNo); public: bool undo(Control* control) override; bool redo(Control* control) override; void addElement(Layer* layer, Element* e, Element::Index pos); std::string getText() override; private: std::multiset<PageLayerPosEntry<Element>> elements{}; LayerController* layerController; Layer* oldLayer; size_t oldLayerNo; size_t newLayerNo; };
1,133
C++
.h
35
29.685714
145
0.752757
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,777
MoveUndoAction.h
xournalpp_xournalpp/src/core/undo/MoveUndoAction.h
/* * Xournal++ * * Undo move action (EditSelection) * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #include <string> // for string #include <vector> // for vector #include "model/PageRef.h" // for PageRef #include "UndoAction.h" // for UndoAction class Layer; class Control; class Element; class MoveUndoAction: public UndoAction { public: MoveUndoAction(Layer* sourceLayer, const PageRef& sourcePage, std::vector<Element*> selected, double mx, double my, Layer* targetLayer, PageRef targetPage); ~MoveUndoAction() override; public: bool undo(Control* control) override; bool redo(Control* control) override; std::vector<PageRef> getPages() override; std::string getText() override; private: void switchLayer(std::vector<Element*>* entries, Layer* oldLayer, Layer* newLayer); void repaint(); void move(); private: std::vector<Element*> elements; PageRef targetPage; Layer* sourceLayer = nullptr; Layer* targetLayer = nullptr; std::string text; double dx = 0; double dy = 0; };
1,154
C++
.h
41
24.609756
119
0.707539
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,778
EmergencySaveRestore.h
xournalpp_xournalpp/src/core/undo/EmergencySaveRestore.h
/* * Xournal++ * * Element used to mark the document as changed, so it is changed after restore. * Without this, it's unchanged and does not ask for save * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #include <string> // for string #include "UndoAction.h" // for UndoAction class Control; class EmergencySaveRestore: public UndoAction { public: EmergencySaveRestore(); ~EmergencySaveRestore() override; public: bool undo(Control* control) override; bool redo(Control* control) override; std::string getText() override; private: };
642
C++
.h
25
23.12
80
0.740132
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,779
GroupUndoAction.h
xournalpp_xournalpp/src/core/undo/GroupUndoAction.h
/* * Xournal++ * * Undo action to group a list of undo actions of the same type * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #include <memory> // for unique_ptr #include <string> // for string #include <vector> // for vector #include "model/PageRef.h" // for PageRef #include "UndoAction.h" // for UndoAction class Control; class GroupUndoAction: public UndoAction { public: GroupUndoAction(); public: void addAction(std::unique_ptr<UndoAction> action); /** * Get the affected pages */ std::vector<PageRef> getPages() override; bool undo(Control* control) override; bool redo(Control* control) override; std::string getText() override; private: std::vector<std::unique_ptr<UndoAction>> actions; };
837
C++
.h
32
23.1875
63
0.708701
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,780
SwapUndoAction.h
xournalpp_xournalpp/src/core/undo/SwapUndoAction.h
/* * Xournal++ * * Undo page swap action * * @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 #include "model/PageRef.h" // for PageRef #include "UndoAction.h" // for UndoAction class Control; class SwapUndoAction: public UndoAction { public: SwapUndoAction(size_t pageNr, bool moveUp, const PageRef& swappedPage, const PageRef& otherPage); ~SwapUndoAction() override; public: bool undo(Control* control) override; bool redo(Control* control) override; std::vector<PageRef> getPages() override; std::string getText() override; private: void swap(Control* control); private: size_t pageNr; PageRef swappedPage; PageRef otherPage; bool moveUp; };
875
C++
.h
34
22.882353
101
0.722022
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,781
LineStyleUndoAction.h
xournalpp_xournalpp/src/core/undo/LineStyleUndoAction.h
/* * Xournal++ * * Undo action for line style changes (Edit selection) * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #include <string> // for string #include <vector> // for vector #include "model/LineStyle.h" // for LineStyle #include "model/PageRef.h" // for PageRef #include "UndoAction.h" // for UndoAction class Stroke; class Layer; class Control; struct LineStyleUndoActionEntry { LineStyleUndoActionEntry(Stroke* s, LineStyle oldStyle, LineStyle newStyle): s(s), oldStyle(oldStyle), newStyle(newStyle) {} Stroke* s; LineStyle oldStyle; LineStyle newStyle; }; class LineStyleUndoAction: public UndoAction { public: LineStyleUndoAction(const PageRef& page, Layer* layer); LineStyleUndoAction(LineStyleUndoAction const&) = delete; LineStyleUndoAction(LineStyleUndoAction&&) = delete; LineStyleUndoAction& operator=(LineStyleUndoAction const&) = delete; LineStyleUndoAction& operator=(LineStyleUndoAction&&) = delete; ~LineStyleUndoAction() override = default; public: bool undo(Control* control) override; bool redo(Control* control) override; std::string getText() override; void addStroke(Stroke* s, LineStyle originalStyle, LineStyle newStyle); private: std::vector<LineStyleUndoActionEntry> data; Layer* layer; };
1,394
C++
.h
43
29.209302
80
0.747204
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,782
PageBackgroundChangedUndoAction.h
xournalpp_xournalpp/src/core/undo/PageBackgroundChangedUndoAction.h
/* * Xournal++ * * Undo action for background change * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #include <string> // for string #include "model/BackgroundImage.h" // for BackgroundImage #include "model/PageRef.h" // for PageRef #include "model/PageType.h" // for PageType #include "util/Util.h" // for npos #include "UndoAction.h" // for UndoAction class Control; class PageBackgroundChangedUndoAction: public UndoAction { public: PageBackgroundChangedUndoAction(const PageRef& page, const PageType& origType, size_t origPdfPage, BackgroundImage origBackgroundImage, double origW, double origH); ~PageBackgroundChangedUndoAction() override; public: bool undo(Control* control) override; bool redo(Control* control) override; std::string getText() override; private: PageType origType; size_t origPdfPage; BackgroundImage origBackgroundImage; double origW; double origH; PageType newType; size_t newPdfPage = npos; BackgroundImage newBackgroundImage; double newW = 0; double newH = 0; };
1,209
C++
.h
39
27.025641
102
0.710958
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,783
InsertUndoAction.h
xournalpp_xournalpp/src/core/undo/InsertUndoAction.h
/* * Xournal++ * * Undo action for insert (write text, draw stroke...) * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #include <string> // for string #include <vector> // for vector #include "model/Element.h" #include "model/PageRef.h" // for PageRef #include "UndoAction.h" // for UndoAction class Element; class Layer; class Control; using ElementPtr = std::unique_ptr<Element>; class InsertUndoAction: public UndoAction { public: InsertUndoAction(const PageRef& page, Layer* layer, Element* element); ~InsertUndoAction() override; public: bool undo(Control* control) override; bool redo(Control* control) override; std::string getText() override; private: Layer* layer; Element* element; ElementPtr elementOwn; }; class InsertsUndoAction: public UndoAction { public: InsertsUndoAction(const PageRef& page, Layer* layer, std::vector<Element*> elements); ~InsertsUndoAction() override; public: bool undo(Control* control) override; bool redo(Control* control) override; std::string getText() override; private: Layer* layer; std::vector<Element*> elements; std::vector<ElementPtr> elementsOwn; };
1,258
C++
.h
46
24.456522
89
0.734558
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,784
DeleteUndoAction.h
xournalpp_xournalpp/src/core/undo/DeleteUndoAction.h
/* * Xournal++ * * Undo action for delete (eraser, delete) * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #include <set> // for multiset #include <string> // for string #include "model/Element.h" // for Element, Element::Index #include "model/PageRef.h" // for PageRef #include "PageLayerPosEntry.h" // for PageLayerPosEntry #include "UndoAction.h" // for UndoAction class Control; class Layer; class DeleteUndoAction: public UndoAction { public: DeleteUndoAction(const PageRef& page, bool eraser); public: bool undo(Control* control) override; bool redo(Control* control) override; void addElement(Layer* layer, ElementPtr e, Element::Index pos); std::string getText() override; private: // Todo (performance): replace by flat_multi_set / sorted_vector std::multiset<PageLayerPosEntry<Element>> elements{}; bool eraser = true; };
967
C++
.h
32
27.625
68
0.723243
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,785
MoveLayerUndoAction.h
xournalpp_xournalpp/src/core/undo/MoveLayerUndoAction.h
/* * Xournal++ * * Undo action for insert layer * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #include <string> // for string #include "model/Layer.h" // for Layer, Layer::Index #include "model/PageRef.h" // for PageRef #include "UndoAction.h" // for UndoAction class LayerController; class Control; class MoveLayerUndoAction: public UndoAction { public: MoveLayerUndoAction(LayerController* layerController, const PageRef& page, Layer* layer, Layer::Index oldLayerPos, Layer::Index newLayerPos); ~MoveLayerUndoAction() override; public: bool undo(Control* control) override; bool redo(Control* control) override; std::string getText() override; private: Layer::Index oldLayerPos; Layer::Index newLayerPos; LayerController* layerController; Layer* layer; };
913
C++
.h
32
25.09375
118
0.724771
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,786
EraseUndoAction.h
xournalpp_xournalpp/src/core/undo/EraseUndoAction.h
/* * Xournal++ * * Undo action for eraser * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #include <set> // for multiset #include <string> // for string #include "model/PageRef.h" // for PageRef #include "model/Stroke.h" // for Stroke #include "PageLayerPosEntry.h" // for PageLayerPosEntry #include "UndoAction.h" // for UndoAction class Control; class Layer; class EraseUndoAction: public UndoAction { public: EraseUndoAction(const PageRef& page); public: bool undo(Control* control) override; bool redo(Control* control) override; void addOriginal(Layer* layer, Stroke* element, Element::Index pos); void addEdited(Layer* layer, Stroke* element, Element::Index pos); [[maybe_unused]] void removeEdited(Stroke* element); void finalize(); std::string getText() override; private: std::multiset<PageLayerPosEntry<Stroke>> edited{}; std::multiset<PageLayerPosEntry<Stroke>> original{}; };
1,033
C++
.h
34
27.617647
72
0.722672
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,787
RemoveLayerUndoAction.h
xournalpp_xournalpp/src/core/undo/RemoveLayerUndoAction.h
/* * Xournal++ * * Undo action for remove layer * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #include <string> // for string #include "model/Layer.h" // for Layer, Layer::Index #include "model/PageRef.h" // for PageRef #include "UndoAction.h" // for UndoAction class LayerController; class Control; class RemoveLayerUndoAction: public UndoAction { public: RemoveLayerUndoAction(LayerController* layerController, const PageRef& page, Layer* layer, Layer::Index layerPos); ~RemoveLayerUndoAction() override; public: bool undo(Control* control) override; bool redo(Control* control) override; std::string getText() override; private: LayerController* layerController; Layer* layer; Layer::Index layerPos; };
832
C++
.h
30
25.066667
118
0.74401
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,788
AddUndoAction.h
xournalpp_xournalpp/src/core/undo/AddUndoAction.h
/* * Xournal++ * * Undo action for delete (eraser, delete) * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #include <set> // for multiset #include <string> // for string #include "model/Element.h" // for Element #include "model/PageRef.h" // for PageRef #include "PageLayerPosEntry.h" // for PageLayerPosEntry #include "UndoAction.h" // for UndoAction class Control; class Layer; class AddUndoAction: public UndoAction { public: AddUndoAction(const PageRef& page, bool eraser); public: bool undo(Control* control) override; bool redo(Control* control) override; void addElement(Layer* layer, Element* e, Element::Index pos); std::string getText() override; private: std::multiset<PageLayerPosEntry<Element>> elements{}; bool eraser = false; };
875
C++
.h
31
25.709677
66
0.720624
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,789
InsertLayerUndoAction.h
xournalpp_xournalpp/src/core/undo/InsertLayerUndoAction.h
/* * Xournal++ * * Undo action for insert layer * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #include <string> // for string #include "model/Layer.h" // for Layer, Layer::Index #include "model/PageRef.h" // for PageRef #include "UndoAction.h" // for UndoAction class LayerController; class Control; class InsertLayerUndoAction: public UndoAction { public: InsertLayerUndoAction(LayerController* layerController, const PageRef& page, Layer* layer, Layer::Index layerPosition); ~InsertLayerUndoAction() override; public: bool undo(Control* control) override; bool redo(Control* control) override; std::string getText() override; private: Layer::Index layerPosition; LayerController* layerController; Layer* layer; };
869
C++
.h
31
24.580645
94
0.723764
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,790
SizeUndoAction.h
xournalpp_xournalpp/src/core/undo/SizeUndoAction.h
/* * Xournal++ * * Undo action resize * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #include <string> // for string #include <vector> // for vector #include "model/PageRef.h" // for PageRef #include "UndoAction.h" // for UndoAction class Layer; class SizeUndoActionEntry; class Stroke; class Control; class SizeUndoAction: public UndoAction { public: SizeUndoAction(const PageRef& page, Layer* layer); ~SizeUndoAction() override; public: bool undo(Control* control) override; bool redo(Control* control) override; std::string getText() override; void addStroke(Stroke* s, double originalWidth, double newWidth, std::vector<double> originalPressure, std::vector<double> newPressure, size_t pressureCount); public: static std::vector<double> getPressure(Stroke* s); private: std::vector<SizeUndoActionEntry*> data; Layer* layer; };
979
C++
.h
35
24.828571
106
0.729904
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,791
UndoRedoHandler.h
xournalpp_xournalpp/src/core/undo/UndoRedoHandler.h
/* * Xournal++ * * Handles Undo and Redo * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #include <deque> // for deque #include <string> // for string #include <vector> // for vector #include "model/PageRef.h" // for PageRef #include "UndoAction.h" // for UndoActionPtr class Control; class UndoRedoListener { public: virtual void undoRedoChanged() = 0; virtual void undoRedoPageChanged(PageRef page) = 0; virtual ~UndoRedoListener() = default; }; class UndoRedoHandler { public: explicit UndoRedoHandler(Control* control); virtual ~UndoRedoHandler(); void undo(); void redo(); bool canUndo(); bool canRedo(); void addUndoAction(UndoActionPtr action); std::string undoDescription(); std::string redoDescription(); void clearContents(); void fireUpdateUndoRedoButtons(const std::vector<PageRef>& pages); void addUndoRedoListener(UndoRedoListener* listener); bool isChanged(); bool isChangedAutosave(); void documentAutosaved(); void documentSaved(); private: void clearRedo(); void printContents(); private: std::deque<UndoActionPtr> undoList; std::deque<UndoActionPtr> redoList; UndoAction* savedUndo = nullptr; UndoAction* autosavedUndo = nullptr; std::vector<UndoRedoListener*> listener; Control* control = nullptr; };
1,432
C++
.h
52
23.903846
70
0.722059
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,792
PageLayerPosEntry.h
xournalpp_xournalpp/src/core/undo/PageLayerPosEntry.h
/* * Xournal++ * * Position entry for undo / redo handling * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #include <memory> #include <utility> #include "model/Element.h" class Layer; template <class T> struct PageLayerPosEntry { // TODO (cpp20): constructor could be removed with C++20 explicit PageLayerPosEntry(Layer* layer, std::unique_ptr<T> element, typename T::Index pos): pos(pos), layer(layer), // element(element.get()), elementOwn(std::move(element)) {} explicit PageLayerPosEntry(Layer* layer, T* element, typename T::Index pos): pos(pos), layer(layer), // element(element) {} typename T::Index pos{}; Layer* layer{}; T* element{}; mutable std::unique_ptr<Element> elementOwn{}; }; template <typename T> constexpr auto operator<(const PageLayerPosEntry<T>& lhs, const PageLayerPosEntry<T>& rhs) -> bool { return lhs.pos < rhs.pos; }
1,047
C++
.h
36
24.416667
100
0.654382
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,793
MissingPdfUndoAction.h
xournalpp_xournalpp/src/core/undo/MissingPdfUndoAction.h
/* * Xournal++ * * Undo action for replacing a missing PDF file * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #include "UndoAction.h" // for UndoAction #include "filesystem.h" // for path class Control; class MissingPdfUndoAction: public UndoAction { public: MissingPdfUndoAction(const fs::path& oldFilepath, bool oldAttachPdf); ~MissingPdfUndoAction() override; public: bool undo(Control* control) override; bool redo(Control* control) override; std::string getText() override; private: fs::path filepath; bool attachPdf; };
642
C++
.h
26
22
73
0.738916
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,794
RotateUndoAction.h
xournalpp_xournalpp/src/core/undo/RotateUndoAction.h
/* * Xournal++ * * Undo action for rotate (EditSelection) * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #include <string> // for string #include <vector> // for vector #include "model/PageRef.h" // for PageRef #include "UndoAction.h" // for UndoAction class Control; class Document; class Element; class RotateUndoAction: public UndoAction { public: RotateUndoAction(const PageRef& page, std::vector<Element*>* elements, double x0, double y0, double rotation); ~RotateUndoAction() override; public: bool undo(Control* control) override; bool redo(Control* control) override; std::string getText() override; private: void applyRotation(double rotation, Document* doc); private: std::vector<Element*> elements; double x0; double y0; double rotation = 0; };
888
C++
.h
34
23.382353
114
0.729858
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,795
InsertDeletePageUndoAction.h
xournalpp_xournalpp/src/core/undo/InsertDeletePageUndoAction.h
/* * Xournal++ * * Undo action for insert page / delete page * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #include <string> // for string #include "model/PageRef.h" // for PageRef #include "UndoAction.h" // for UndoAction class Control; class InsertDeletePageUndoAction: public UndoAction { public: InsertDeletePageUndoAction(const PageRef& page, size_t pagePos, bool inserted); ~InsertDeletePageUndoAction() override; public: bool undo(Control* control) override; bool redo(Control* control) override; std::string getText() override; private: bool insertPage(Control* control); bool deletePage(Control* control); private: bool inserted; size_t pagePos; };
787
C++
.h
30
23.366667
83
0.741287
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,796
FontUndoAction.h
xournalpp_xournalpp/src/core/undo/FontUndoAction.h
/* * Xournal++ * * Undo action for font changes * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #include <string> // for string #include <vector> // for vector #include "model/PageRef.h" // for PageRef #include "UndoAction.h" // for UndoAction class FontUndoActionEntry; class Layer; class Text; class XojFont; class Control; class FontUndoAction: public UndoAction { public: FontUndoAction(const PageRef& page, Layer* layer); ~FontUndoAction() override; public: bool undo(Control* control) override; bool redo(Control* control) override; std::string getText() override; void addStroke(Text* e, const XojFont& oldFont, const XojFont& newFont); private: std::vector<FontUndoActionEntry*> data; Layer* layer; };
833
C++
.h
33
22.69697
76
0.736709
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,797
ArrangeUndoAction.h
xournalpp_xournalpp/src/core/undo/ArrangeUndoAction.h
/* * Xournal++ * * Undo move action (EditSelection) * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #include <deque> // for deque #include <string> // for string #include <utility> // for pair #include <vector> // for vector #include "model/Element.h" // for Element::Index, Element #include "model/ElementInsertionPosition.h" // for InsertionOrder #include "model/PageRef.h" // for PageRef #include "UndoAction.h" // for UndoAction class Control; class Layer; class ArrangeUndoAction: public UndoAction { public: ArrangeUndoAction(const PageRef& page, Layer* layer, std::string desc, InsertionOrderRef oldOrder, InsertionOrderRef newOrder); ~ArrangeUndoAction() override; public: bool undo(Control* control) override; bool redo(Control* control) override; std::string getText() override; private: void applyRearrange(Control* control); private: Layer* layer; /** Description of the ordering action. */ std::string description; // These track the ordering of elements InsertionOrderRef oldOrder; InsertionOrderRef newOrder; };
1,197
C++
.h
40
26.675
102
0.725131
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,798
LayerRenameUndoAction.h
xournalpp_xournalpp/src/core/undo/LayerRenameUndoAction.h
/* * Xournal++ * * Rename undo action for layer * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #include <string> // for string #include "UndoAction.h" // for UndoAction class Layer; class Control; class LayerController; class LayerRenameUndoAction: public UndoAction { public: LayerRenameUndoAction(LayerController* layerController, Layer* layer, const std::string& newName, const std::string& oldName); ~LayerRenameUndoAction() override; public: std::string getText() override; bool undo(Control* control) override; bool redo(Control* control) override; private: Layer* layer; LayerController* layerController; std::string newName; std::string oldName; };
806
C++
.h
31
22.483871
101
0.723958
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,799
UndoAction.h
xournalpp_xournalpp/src/core/undo/UndoAction.h
/* * Xournal++ * * Abstract undo action * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #include <memory> // for unique_ptr #include <string> // for string #include <vector> // for vector #include "model/PageRef.h" // for PageRef class Control; class UndoAction { public: UndoAction(std::string className); // NOLINT virtual ~UndoAction() = default; public: virtual bool undo(Control* control) = 0; virtual bool redo(Control* control) = 0; virtual std::string getText() = 0; /** * Get the affected pages */ virtual std::vector<PageRef> getPages(); auto getClassName() const -> std::string const&; protected: // This is only for debugging / Testing purpose std::string className; PageRef page; bool undone = false; }; using UndoActionPtr = std::unique_ptr<UndoAction>;
919
C++
.h
36
22.361111
52
0.688073
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,800
ScaleUndoAction.h
xournalpp_xournalpp/src/core/undo/ScaleUndoAction.h
/* * Xournal++ * * Undo action for rescale (EditSelection) * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #include <string> // for string #include <vector> // for vector #include "model/PageRef.h" // for PageRef #include "UndoAction.h" // for UndoAction class Control; class Document; class Element; class ScaleUndoAction: public UndoAction { public: ScaleUndoAction(const PageRef& page, std::vector<Element*>* elements, double x0, double y0, double fx, double fy, double rotation, bool restoreLineWidth); ~ScaleUndoAction() override; public: bool undo(Control* control) override; bool redo(Control* control) override; std::string getText() override; private: void applyScale(double fx, double fy, bool restoreLineWidth, Document* doc); private: std::vector<Element*> elements; double x0; double y0; double fx; double fy; double rotation; bool restoreLineWidth; };
1,029
C++
.h
38
23.684211
117
0.717635
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,801
RecognizerUndoAction.h
xournalpp_xournalpp/src/core/undo/RecognizerUndoAction.h
/* * Xournal++ * * Undo action for stroke recognizer * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #include <memory> // for unique_ptr #include <string> // for string #include <vector> // for vector #include "model/PageRef.h" // for PageRef #include "UndoAction.h" // for UndoAction class Layer; class Stroke; class Control; class Element; class RecognizerUndoAction: public UndoAction { public: RecognizerUndoAction(const PageRef& page, Layer* layer, std::unique_ptr<Element> original, Element* recognized); ~RecognizerUndoAction() override; public: bool undo(Control* control) override; bool redo(Control* control) override; std::string getText() override; private: Layer* layer; Element* original; std::unique_ptr<Element> originalOwned; Element* recognized; std::unique_ptr<Element> recognizedOwned; };
940
C++
.h
35
24.2
116
0.738839
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,802
MergeLayerDownUndoAction.h
xournalpp_xournalpp/src/core/undo/MergeLayerDownUndoAction.h
/* * Xournal++ * * Undo action for merging layer down * * @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 "model/Layer.h" // for Layer, Layer::Index #include "model/PageRef.h" // for PageRef #include "UndoAction.h" // for UndoAction class LayerController; class Control; class MergeLayerDownUndoAction: public UndoAction { public: MergeLayerDownUndoAction(LayerController* layerController, const PageRef& page, Layer* upperLayer, Layer::Index upperLayerPos, Layer* lowerLayer, size_t selectedPage); public: bool undo(Control* control) override; bool redo(Control* control) override; std::string getText() override; private: void triggerUIUpdate(Control* control); LayerController* layerController; Layer* upperLayer; std::vector<Element*> upperLayerElements; Layer::Index upperLayerPos; Layer::Index upperLayerID; Layer* lowerLayer; Layer::Index lowerLayerID; size_t selectedPage; };
1,133
C++
.h
37
26.837838
102
0.728532
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,803
ColorUndoAction.h
xournalpp_xournalpp/src/core/undo/ColorUndoAction.h
/* * Xournal++ * * Undo action for color changes (Edit selection) * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #include <string> // for string #include <vector> // for vector #include "model/PageRef.h" // for PageRef #include "util/Color.h" // for Color #include "UndoAction.h" // for UndoAction class ColorUndoActionEntry; class Element; class Layer; class Control; class ColorUndoAction: public UndoAction { public: ColorUndoAction(const PageRef& page, Layer* layer); ~ColorUndoAction() override; public: bool undo(Control* control) override; bool redo(Control* control) override; std::string getText() override; void addStroke(Element* e, Color originalColor, Color newColor); private: std::vector<ColorUndoActionEntry*> data; Layer* layer; };
876
C++
.h
33
24.030303
68
0.735012
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,804
AudioRecorder.h
xournalpp_xournalpp/src/core/audio/AudioRecorder.h
/* * Xournal++ * * Class to record audio and store it as MP3-file * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #include <memory> // for make_unique, unique_ptr #include <vector> // for vector #include "filesystem.h" // for path template <typename T> class AudioQueue; class DeviceInfo; class PortAudioProducer; class Settings; class VorbisConsumer; class AudioRecorder final { public: explicit AudioRecorder(Settings& settings); AudioRecorder(AudioRecorder const&) = delete; AudioRecorder(AudioRecorder&&) = delete; auto operator=(AudioRecorder const&) -> AudioRecorder& = delete; auto operator=(AudioRecorder&&) -> AudioRecorder& = delete; ~AudioRecorder(); bool start(fs::path const& file); void stop(); [[nodiscard]] bool isRecording() const; std::vector<DeviceInfo> getInputDevices() const; private: std::unique_ptr<AudioQueue<float>> audioQueue; std::unique_ptr<PortAudioProducer> portAudioProducer; std::unique_ptr<VorbisConsumer> vorbisConsumer; };
1,098
C++
.h
37
26.837838
68
0.739089
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,805
VorbisProducer.h
xournalpp_xournalpp/src/core/audio/VorbisProducer.h
/* * Xournal++ * * Class to read audio data from an mp3 file * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #include <atomic> // for atomic #include <thread> // for thread #include "filesystem.h" // for path template <typename T> class AudioQueue; class VorbisProducer final { public: explicit VorbisProducer(AudioQueue<float>& audioQueue): audioQueue(audioQueue) {} bool start(fs::path const& file, unsigned int timestamp); void abort(); void stop(); void seek(int seconds); private: AudioQueue<float>& audioQueue; std::thread producerThread{}; std::atomic<bool> stopProducer{false}; std::atomic<int> seekSeconds{0}; };
746
C++
.h
29
22.896552
85
0.715092
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,806
VorbisConsumer.h
xournalpp_xournalpp/src/core/audio/VorbisConsumer.h
/* * Xournal++ * * Class to save audio data in an opus file * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #include <atomic> // for atomic #include <thread> // for thread #include "filesystem.h" // for path class Settings; template <typename T> class AudioQueue; class VorbisConsumer final { public: explicit VorbisConsumer(Settings& settings, AudioQueue<float>& audioQueue): settings(settings), audioQueue(audioQueue) {} public: bool start(fs::path const& file); void join(); void stop(); private: Settings& settings; AudioQueue<float>& audioQueue; std::thread consumerThread{}; std::atomic<bool> stopConsumer{false}; };
755
C++
.h
31
21.387097
79
0.712291
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,807
PortAudioProducer.h
xournalpp_xournalpp/src/core/audio/PortAudioProducer.h
/* * Xournal++ * * Class to record audio using libportaudio * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #include <memory> // for unique_ptr #include <vector> // for vector #include <portaudiocpp/PortAudioCpp.hxx> // for MemFunCallbackStream, System #include "DeviceInfo.h" // for DeviceInfo class Settings; template <typename T> class AudioQueue; class PortAudioProducer { public: PortAudioProducer(Settings& settings, AudioQueue<float>& audioQueue): settings(settings), audioQueue(audioQueue){}; std::vector<DeviceInfo> getInputDevices() const; DeviceInfo getSelectedInputDevice() const; bool isRecording() const; bool startRecording(); int recordCallback(const void* inputBuffer, void* outputBuffer, unsigned long framesPerBuffer, const PaStreamCallbackTimeInfo* timeInfo, PaStreamCallbackFlags statusFlags); void stopRecording(); private: portaudio::System& sys{portaudio::System::instance()}; Settings& settings; AudioQueue<float>& audioQueue; std::unique_ptr<portaudio::MemFunCallbackStream<PortAudioProducer>> inputStream; int inputChannels = 0; };
1,228
C++
.h
35
31.314286
119
0.753401
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,808
DeviceInfo.h
xournalpp_xournalpp/src/core/audio/DeviceInfo.h
/* * Xournal++ * * Class storing information about an audio device * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #include <string> // for string #include <portaudiocpp/PortAudioCpp.hxx> // for PaDeviceIndex class DeviceInfo { public: DeviceInfo(portaudio::Device* device, bool selected); public: const std::string& getDeviceName() const; PaDeviceIndex getIndex() const; bool getSelected() const; private: const std::string deviceName; const PaDeviceIndex index{}; const bool selected{}; const int inputChannels{}; const int outputChannels{}; };
668
C++
.h
27
21.851852
62
0.729134
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,809
AudioPlayer.h
xournalpp_xournalpp/src/core/audio/AudioPlayer.h
/* * Xournal++ * * Class to play audio from a MP3-file * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #include <memory> // for make_unique, unique_ptr #include <vector> // for vector #include "filesystem.h" // for path template <typename T> class AudioQueue; class Control; class DeviceInfo; class PortAudioConsumer; class Settings; class VorbisProducer; class AudioPlayer final { public: explicit AudioPlayer(Control& control, Settings& settings); AudioPlayer(AudioPlayer const&) = delete; AudioPlayer(AudioPlayer&&) = delete; auto operator=(AudioPlayer const&) -> AudioPlayer& = delete; auto operator=(AudioPlayer&&) -> AudioPlayer& = delete; ~AudioPlayer(); bool start(fs::path const& file, unsigned int timestamp = 0); bool isPlaying(); void stop(); bool play(); void pause(); void seek(int seconds); std::vector<DeviceInfo> getOutputDevices(); Settings& getSettings(); void disableAudioPlaybackButtons(); private: Control& control; Settings& settings; std::unique_ptr<AudioQueue<float>> audioQueue; std::unique_ptr<PortAudioConsumer> portAudioConsumer; std::unique_ptr<VorbisProducer> vorbisProducer; };
1,281
C++
.h
45
25.244444
65
0.726531
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,810
PortAudioConsumer.h
xournalpp_xournalpp/src/core/audio/PortAudioConsumer.h
/* * Xournal++ * * Class to play audio using libportaudio * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #include <memory> // for unique_ptr #include <vector> // for vector #include <portaudiocpp/PortAudioCpp.hxx> // for MemFunCallbackStream, System #include "DeviceInfo.h" // for DeviceInfo class AudioPlayer; template <typename T> class AudioQueue; class PortAudioConsumer final { public: explicit PortAudioConsumer(AudioPlayer& audioPlayer, AudioQueue<float>& audioQueue): audioPlayer(audioPlayer), audioQueue(audioQueue) {} std::vector<DeviceInfo> getOutputDevices() const; DeviceInfo getSelectedOutputDevice() const; bool isPlaying() const; bool startPlaying(); int playCallback(const void* inputBuffer, void* outputBuffer, unsigned long framesPerBuffer, const PaStreamCallbackTimeInfo* timeInfo, PaStreamCallbackFlags statusFlags); void stopPlaying(); private: portaudio::System& sys{portaudio::System::instance()}; AudioPlayer& audioPlayer; AudioQueue<float>& audioQueue; std::unique_ptr<portaudio::MemFunCallbackStream<PortAudioConsumer>> outputStream; int outputChannels = 0; };
1,261
C++
.h
36
31.25
98
0.752263
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,811
SNDFileCpp.h
xournalpp_xournalpp/src/core/audio/SNDFileCpp.h
/* * Xournal++ * * Helper functions for libsndfile * platform dependent code to open std::filesystem::paths * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #ifdef _WIN32 #include <windows.h> #define ENABLE_SNDFILE_WINDOWS_PROTOTYPES 1 #endif #include <memory> #include <sndfile.h> #include "filesystem.h" namespace xoj::audio { struct SNDFILE_Deleter { void operator()(SNDFILE* file) { sf_close(file); } }; using SNDFileGuard = std::unique_ptr<SNDFILE, SNDFILE_Deleter>; /** * Open a file with libsndfile * * @param path std::string const& path to ensure system single byte encoding * @return The resource pointer to the sound file */ inline SNDFILE* sf_open_pp(std::string const& path, int mode, SF_INFO* info) { return sf_open(path.c_str(), mode, info); } #if (defined(ENABLE_SNDFILE_WINDOWS_PROTOTYPES) && ENABLE_SNDFILE_WINDOWS_PROTOTYPES) /** * Open a file with libsndfile * * @param path std::wstring const& path to ensure system double byte encoding * @return The resource pointer to the sound file */ inline SNDFILE* sf_open_pp(std::wstring const& path, int mode, SF_INFO* info) { return sf_wchar_open(path.c_str(), mode, info); } #endif // naming similar to std::make_unique inline auto make_snd_file(fs::path const& file, int mode, SF_INFO* info) { return SNDFileGuard{sf_open_pp(file, mode, info)}; } } // namespace xoj::audio
1,454
C++
.h
49
27.714286
85
0.731707
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,812
AudioQueue.h
xournalpp_xournalpp/src/core/audio/AudioQueue.h
/* * Xournal++ * * Queue to connect an audio producer and an audio consumer * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #include <algorithm> #include <condition_variable> #include <deque> #include <limits> #include <mutex> #include "util/Assert.h" #include "util/safe_casts.h" // for as_signed template <typename T> class AudioQueue { public: void reset() { std::lock_guard<std::mutex> lock(internalLock); this->popNotified = false; this->pushNotified = false; this->streamEnd = false; internalQueue.clear(); this->sampleRate = -1; this->channels = 0; } bool empty() { std::lock_guard<std::mutex> lock(internalLock); return internalQueue.empty(); } size_t size() { std::lock_guard<std::mutex> lock(internalLock); return internalQueue.size(); } template <typename Iter> void emplace(Iter begI, Iter endI) { std::lock_guard<std::mutex> lock(internalLock); std::move(begI, endI, std::front_inserter(internalQueue)); this->pushNotified = true; this->pushLockCondition.notify_one(); } template <typename InsertIter> InsertIter pop(InsertIter insertIter, size_t nSamples) { std::lock_guard<std::mutex> lock(internalLock); if (this->channels == 0) { this->popNotified = true; this->popLockCondition.notify_one(); return insertIter; } auto queueSize = internalQueue.size(); auto returnBufferLength = std::min<size_t>(nSamples, queueSize - queueSize % this->channels); auto begI = rbegin(internalQueue); auto endI = std::next(begI, as_signed(returnBufferLength)); auto ret = std::move(begI, endI, insertIter); internalQueue.erase(endI.base(), begI.base()); this->popNotified = true; this->popLockCondition.notify_one(); return ret; } void signalEndOfStream() { std::lock_guard<std::mutex> lock(internalLock); this->streamEnd = true; this->pushNotified = true; this->popNotified = true; this->pushLockCondition.notify_one(); this->popLockCondition.notify_one(); } void waitForProducer(std::unique_lock<std::mutex>& lock) { // static_assert(lock.mutex() == &this->queueLock); xoj_assert(lock.mutex() == &this->queueLock); while (!this->pushNotified && !hasStreamEnded()) { this->pushLockCondition.wait(lock); } this->pushNotified = false; } void waitForConsumer(std::unique_lock<std::mutex>& lock) { // static_assert(lock.mutex() == &this->queueLock); xoj_assert(lock.mutex() == &this->queueLock); while (!this->popNotified && !hasStreamEnded()) { this->popLockCondition.wait(lock); } this->popNotified = false; } bool hasStreamEnded() { std::lock_guard<std::mutex> lock(internalLock); return this->streamEnd; } [[nodiscard]] std::unique_lock<std::mutex> acquire_lock() { std::unique_lock retLock{this->queueLock, std::defer_lock}; std::lock(retLock, this->internalLock); std::lock_guard lock{this->internalLock, std::adopt_lock}; return retLock; } void setAudioAttributes(double lSampleRate, unsigned int lChannels) { std::lock_guard<std::mutex> lock(internalLock); this->sampleRate = lSampleRate; this->channels = lChannels; } /** * @return a pair of the sample rate and the channel count, * std::pair<>::first is the sample rate and std::pair<>::second the channel count. * Todo (readability, type-safety): create a struct AudioAttributes; remove this comment */ [[nodiscard]] std::pair<double, int> getAudioAttributes() { std::lock_guard<std::mutex> lock(internalLock); return {this->sampleRate, this->channels}; } private: std::mutex queueLock; std::mutex internalLock; std::deque<T> internalQueue; std::condition_variable pushLockCondition; std::condition_variable popLockCondition; double sampleRate{std::numeric_limits<double>::quiet_NaN()}; uint32_t channels{0}; bool streamEnd{false}; bool pushNotified{false}; bool popNotified{false}; };
4,368
C++
.h
119
30.184874
101
0.647714
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,813
PopplerGlibDocument.h
xournalpp_xournalpp/src/core/pdf/popplerapi/PopplerGlibDocument.h
/* * Xournal++ * * Poppler GLib Implementation * * @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 <glib.h> // for GError, gpointer, gsize #include <poppler.h> // for PopplerDocument #include "pdf/base/XojPdfDocumentInterface.h" // for XojPdfDocumentInterface #include "pdf/base/XojPdfPage.h" // for XojPdfPageSPtr #include "filesystem.h" // for path class XojPdfBookmarkIterator; class PopplerGlibDocument: public XojPdfDocumentInterface { public: PopplerGlibDocument(); PopplerGlibDocument(const PopplerGlibDocument& doc); ~PopplerGlibDocument() override; public: void assign(XojPdfDocumentInterface* doc) override; bool equals(XojPdfDocumentInterface* doc) const override; public: bool save(fs::path const& filepath, GError** error) const override; bool load(fs::path const& filepath, std::string password, GError** error) override; bool load(std::unique_ptr<std::string> data, std::string password, GError** error) override; bool isLoaded() const override; void reset() override; XojPdfPageSPtr getPage(size_t page) const override; size_t getPageCount() const override; XojPdfBookmarkIterator* getContentsIter() const override; private: PopplerDocument* document = nullptr; };
1,419
C++
.h
39
33.435897
96
0.747261
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,814
PopplerGlibAction.h
xournalpp_xournalpp/src/core/pdf/popplerapi/PopplerGlibAction.h
/* * Xournal++ * * PDF Action Abstraction Interface * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #include <memory> // for shared_ptr #include <string> // for string #include <poppler.h> // for PopplerAction, PopplerDocument #include "pdf/base/XojPdfAction.h" // for XojPdfAction #include "util/raii/GObjectSPtr.h" // for GObjectSPtr class LinkDestination; class PopplerGlibAction: public XojPdfAction { public: PopplerGlibAction(PopplerAction* action, PopplerDocument* document); ~PopplerGlibAction() override; public: virtual std::shared_ptr<const LinkDestination> getDestination() override; virtual std::string getTitle() override; private: virtual std::shared_ptr<const LinkDestination> getDestination(PopplerAction* action); void linkFromDest(LinkDestination& link, PopplerDest* pDest); private: xoj::util::raii::GObjectSPtr<PopplerDocument> document; std::shared_ptr<const LinkDestination> destination; std::string title; };
1,061
C++
.h
32
30.4375
89
0.766438
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,815
PopplerGlibPage.h
xournalpp_xournalpp/src/core/pdf/popplerapi/PopplerGlibPage.h
/* * Xournal++ * * PDF Page GLib Implementation * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #include <string> // for string #include <vector> // for vector #include <cairo.h> // for cairo_t, cairo_region_t #include <poppler.h> // for PopplerPage #include "pdf/base/XojPdfPage.h" // for XojPdfRectangle (ptr only), XojPdfP... class PopplerGlibPage: public XojPdfPage { public: PopplerGlibPage(PopplerPage* page, PopplerDocument* doc); PopplerGlibPage(const PopplerGlibPage& other); virtual ~PopplerGlibPage(); PopplerGlibPage& operator=(const PopplerGlibPage& other); public: double getWidth() const override; double getHeight() const override; void render(cairo_t* cr) const override; void renderForPrinting(cairo_t* cr) const override; std::vector<XojPdfRectangle> findText(const std::string& text) override; std::string selectText(const XojPdfRectangle& rect, XojPdfPageSelectionStyle style) override; cairo_region_t* selectTextRegion(const XojPdfRectangle& rect, XojPdfPageSelectionStyle style) override; TextSelection selectTextLines(const XojPdfRectangle& rect, XojPdfPageSelectionStyle style) override; auto getLinks() -> std::vector<Link> override; int getPageId() const override; std::string getPageLabel() const override; private: PopplerPage* page; PopplerDocument* document; };
1,461
C++
.h
38
35
107
0.756219
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,816
PopplerGlibPageBookmarkIterator.h
xournalpp_xournalpp/src/core/pdf/popplerapi/PopplerGlibPageBookmarkIterator.h
/* * Xournal++ * * PDF Bookmark iterator interface * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #include <poppler.h> // for PopplerDocument, Popple... #include "pdf/base/XojPdfBookmarkIterator.h" // for XojPdfBookmarkIterator class XojPdfAction; class PopplerGlibPageBookmarkIterator: public XojPdfBookmarkIterator { public: PopplerGlibPageBookmarkIterator(PopplerIndexIter* iter, PopplerDocument* document); ~PopplerGlibPageBookmarkIterator() override; public: bool next() override; bool isOpen() override; XojPdfBookmarkIterator* getChildIter() override; XojPdfAction* getAction() override; private: PopplerIndexIter* iter; PopplerDocument* document; };
778
C++
.h
27
26
87
0.777927
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,817
XojPdfDocumentInterface.h
xournalpp_xournalpp/src/core/pdf/base/XojPdfDocumentInterface.h
/* * Xournal++ * * PDF Document Container Interface * * @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 <glib.h> // for GError, gpointer, gsize #include "XojPdfPage.h" // for XojPdfPageSPtr #include "filesystem.h" // for path class XojPdfBookmarkIterator; class XojPdfDocumentInterface { public: XojPdfDocumentInterface(); virtual ~XojPdfDocumentInterface(); public: virtual void assign(XojPdfDocumentInterface* doc) = 0; virtual bool equals(XojPdfDocumentInterface* doc) const = 0; public: virtual bool save(fs::path const& file, GError** error) const = 0; virtual bool load(fs::path const& file, std::string password, GError** error) = 0; virtual bool load(std::unique_ptr<std::string> data, std::string password, GError** error) = 0; virtual bool isLoaded() const = 0; virtual void reset() = 0; virtual XojPdfPageSPtr getPage(size_t page) const = 0; virtual size_t getPageCount() const = 0; virtual XojPdfBookmarkIterator* getContentsIter() const = 0; private: };
1,178
C++
.h
35
30.742857
99
0.724625
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,818
XojPdfExport.h
xournalpp_xournalpp/src/core/pdf/base/XojPdfExport.h
/* * Xournal++ * * PDF Document Export Abstraction Interface * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #include <string> #include "control/jobs/BaseExportJob.h" #include "util/ElementRange.h" #include "filesystem.h" class XojPdfExport { public: XojPdfExport(); virtual ~XojPdfExport(); public: virtual bool createPdf(fs::path const& file, bool progressiveMode) = 0; virtual bool createPdf(fs::path const& file, const PageRangeVector& range, bool progressiveMode) = 0; virtual std::string getLastError() = 0; /** * Export without background */ virtual void setExportBackground(ExportBackgroundType exportBackground); /** * @brief Select layers to export by parsing str * @param rangeStr A string parsed to get a list of layers */ virtual void setLayerRange(const char* rangeStr) = 0; private: };
948
C++
.h
34
24.558824
105
0.723757
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,819
XojPdfPage.h
xournalpp_xournalpp/src/core/pdf/base/XojPdfPage.h
/* * Xournal++ * * PDF Page Abstraction Interface * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #include <cstdint> // for uint8_t #include <memory> // for shared_ptr #include <string> // for string #include <vector> // for vector #include <cairo.h> // for cairo_region_t, cairo_t #include <glib.h> // for GURI #include "util/raii/CairoWrappers.h" #include "XojPdfAction.h" class XojPdfLink; /// Determines how text is selected on a user action. enum class XojPdfPageSelectionStyle : uint8_t { /// Standard selection, where all text between start and end positions is selected. Linear, /// Select a single word. Word, /// Select a single line. Line, /// Select an area. Area, }; class XojPdfRectangle { public: XojPdfRectangle() = default; XojPdfRectangle(double x1, double y1, double x2, double y2); public: double x1 = -1; double y1 = -1; double x2 = -1; double y2 = -1; }; class XojPdfPage { public: struct TextSelection { xoj::util::CairoRegionSPtr region; std::vector<XojPdfRectangle> rects; }; struct Link { XojPdfRectangle bounds; std::unique_ptr<XojPdfAction> action; }; virtual double getWidth() const = 0; virtual double getHeight() const = 0; /** * Renders the page to the given cairo context. * Use render() for rendering to a screen (or a raster image format), * Use renderForPrinting() for exports to vector formats (not sure it will be vectorial, but the quality is better) * * See https://poppler.freedesktop.org/api/glib/poppler-Poppler-Page.html#poppler-page-render-for-printing * for actual differences between the two functions in the poppler based implementation. */ virtual void render(cairo_t* cr) const = 0; virtual void renderForPrinting(cairo_t* cr) const = 0; virtual std::vector<XojPdfRectangle> findText(const std::string& text) = 0; /// Retrieve the text contained in the provided rectangle using the given /// selection style. /// @param rect start and end points /// @param style The text selection style /// @return The selected text. virtual std::string selectText(const XojPdfRectangle& rect, XojPdfPageSelectionStyle style) = 0; /// Retrieve the cairo_region_t that encompasses the text that would be /// selected in the given rectangle with the given text selection style. /// @param rect start and end points /// @param style The text selection style /// @return A region that contains the text that would be selected. virtual cairo_region_t* selectTextRegion(const XojPdfRectangle& rect, XojPdfPageSelectionStyle style) = 0; /// Retrieve the set of rectangles that represent each line of text selected /// in the given rectangle with the given text selection style. /// @param rect start and end points /// @param style The text selection style /// @return The rectangles that cover the text that would be selected. virtual TextSelection selectTextLines(const XojPdfRectangle& rect, XojPdfPageSelectionStyle style) = 0; /** * @return A list of Links in the current page. */ virtual auto getLinks() -> std::vector<Link> = 0; virtual int getPageId() const = 0; virtual std::string getPageLabel() const = 0; private: }; typedef std::shared_ptr<XojPdfPage> XojPdfPageSPtr;
3,479
C++
.h
91
34.021978
119
0.705882
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,820
XojPdfExportFactory.h
xournalpp_xournalpp/src/core/pdf/base/XojPdfExportFactory.h
/* * Xournal++ * * PDF Document Export Abstraction Interface * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #include <memory> // for unique_ptr class Document; class ProgressListener; class XojPdfExport; class XojPdfExportFactory { private: XojPdfExportFactory(); virtual ~XojPdfExportFactory(); public: static std::unique_ptr<XojPdfExport> createExport(Document* doc, ProgressListener* listener); private: };
507
C++
.h
23
19.869565
97
0.767782
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,821
XojCairoPdfExport.h
xournalpp_xournalpp/src/core/pdf/base/XojCairoPdfExport.h
/* * Xournal++ * * PDF Document Export Abstraction Interface * * @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 <cairo.h> // for CAIRO_VERSION, CAIRO_VERSION... #include <gtk/gtk.h> // for GtkTreeModel #include "control/jobs/BaseExportJob.h" // for ExportBackgroundType, EXPORT... #include "util/ElementRange.h" // for PageRangeVector #include "XojPdfExport.h" // for XojPdfExport #include "filesystem.h" // for path class Document; class ProgressListener; class XojCairoPdfExport: public XojPdfExport { public: XojCairoPdfExport(Document* doc, ProgressListener* progressListener); ~XojCairoPdfExport() override; public: bool createPdf(fs::path const& file, bool progressiveMode) override; bool createPdf(fs::path const& file, const PageRangeVector& range, bool progressiveMode) override; std::string getLastError() override; /** * Export without background */ void setExportBackground(ExportBackgroundType exportBackground) override; private: bool startPdf(const fs::path& file, bool exportOutline); #if CAIRO_VERSION >= CAIRO_VERSION_ENCODE(1, 16, 0) /** * Populate the outline of the generated PDF using the outline of the * background PDF. * * This requires features available only in cairo 1.16 or newer. */ void populatePdfOutline(); #endif bool endPdf(); void exportPage(size_t page); /** * Export as a PDF document where each additional layer creates a * new page */ void exportPageLayers(size_t page); /** * @brief Select layers to export by parsing str * @param rangeStr A string parsed to get a list of layers */ void setLayerRange(const char* rangeStr) override; private: Document* doc = nullptr; ProgressListener* progressListener = nullptr; cairo_surface_t* surface = nullptr; cairo_t* cr = nullptr; ExportBackgroundType exportBackground = EXPORT_BACKGROUND_ALL; std::string lastError; std::unique_ptr<LayerRangeVector> layerRange; };
2,187
C++
.h
64
30.40625
102
0.72093
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,822
XojPdfDocument.h
xournalpp_xournalpp/src/core/pdf/base/XojPdfDocument.h
/* * Xournal++ * * PDF Document Container * * @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 <optional> #include <string> #include <vector> #include <glib.h> // for GError, gpointer, gsize #include "XojPdfDocumentInterface.h" // for XojPdfDocumentInterface #include "XojPdfPage.h" // for XojPdfPageSPtr #include "filesystem.h" // for path class XojPdfBookmarkIterator; class XojPdfDocument: XojPdfDocumentInterface { public: XojPdfDocument(); XojPdfDocument(const XojPdfDocument& doc); ~XojPdfDocument() override; public: XojPdfDocument& operator=(const XojPdfDocument& doc); bool operator==(XojPdfDocument& doc) const; void assign(XojPdfDocumentInterface* doc) override; bool equals(XojPdfDocumentInterface* doc) const override; public: bool save(fs::path const& file, GError** error) const override; bool load(fs::path const& file, std::string password, GError** error) override; bool load(std::unique_ptr<std::string> data, std::string password, GError** error) override; bool isLoaded() const override; void reset() override; XojPdfPageSPtr getPage(size_t page) const override; size_t getPageCount() const override; XojPdfBookmarkIterator* getContentsIter() const override; private: XojPdfDocumentInterface* doc; };
1,476
C++
.h
43
31.372093
96
0.736287
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,823
XojPdfBookmarkIterator.h
xournalpp_xournalpp/src/core/pdf/base/XojPdfBookmarkIterator.h
/* * Xournal++ * * PDF Bookmark iterator interface * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once class XojPdfAction; class XojPdfBookmarkIterator { public: XojPdfBookmarkIterator(); virtual ~XojPdfBookmarkIterator(); public: virtual bool next() = 0; virtual bool isOpen() = 0; virtual XojPdfBookmarkIterator* getChildIter() = 0; virtual XojPdfAction* getAction() = 0; private: };
489
C++
.h
23
18.565217
55
0.728261
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,824
XojPdfAction.h
xournalpp_xournalpp/src/core/pdf/base/XojPdfAction.h
/* * Xournal++ * * PDF Action Abstraction Interface * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #include <string> // for string #include <memory> #include <vector> #include "model/LinkDestination.h" // for XojLinkDest class XojPdfAction { public: XojPdfAction(); virtual ~XojPdfAction(); public: virtual std::shared_ptr<const LinkDestination> getDestination() = 0; virtual std::string getTitle() = 0; private: };
519
C++
.h
24
19.291667
72
0.723361
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,825
luapi_application.h
xournalpp_xournalpp/src/core/plugin/luapi_application.h
/* * Xournal++ * * Lua API, application library * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #include <cstring> #include <limits> // for numeric_limits #include <memory> #include <sstream> #include <gtk/gtk.h> #include <stdint.h> #include "control/Control.h" #include "control/ExportHelper.h" #include "control/PageBackgroundChangeController.h" #include "control/ScrollHandler.h" #include "control/Tool.h" #include "control/actions/ActionDatabase.h" // for ActionDatabase #include "control/layer/LayerController.h" #include "control/pagetype/PageTypeHandler.h" #include "control/settings/Settings.h" #include "control/tools/EditSelection.h" #include "control/tools/ImageHandler.h" #include "control/zoom/ZoomControl.h" #include "enums/Action.enum.h" #include "gui/Layout.h" #include "gui/MainWindow.h" #include "gui/XournalView.h" #include "gui/dialog/FileChooserFiltersHelper.h" #include "gui/dialog/XojOpenDlg.h" // for XojO... #include "gui/dialog/XojSaveDlg.h" // for XojS... #include "gui/sidebar/Sidebar.h" #include "gui/toolbarMenubar/model/ColorPalette.h" // for Palette #include "gui/widgets/XournalWidget.h" #include "model/Document.h" #include "model/Element.h" #include "model/Font.h" #include "model/Image.h" #include "model/SplineSegment.h" #include "model/Stroke.h" #include "model/StrokeStyle.h" #include "model/Text.h" #include "model/XojPage.h" // IWYU pragma: keep for XojPage #include "plugin/Plugin.h" #include "undo/InsertUndoAction.h" #include "util/PopupWindowWrapper.h" // for PopupWindowWrapper #include "util/StringUtils.h" #include "util/i18n.h" // for _ #include "util/safe_casts.h" // for round_cast, as_signed, as_unsigned #include "ActionBackwardCompatibilityLayer.h" extern "C" { #include <lauxlib.h> // for luaL_Reg, luaL_newstate, luaL_requiref #include <lua.h> // for lua_getglobal, lua_getfield, lua_setf... #include <lualib.h> // for luaL_openlibs } static std::tuple<std::optional<std::string>, std::vector<Element*>> getElementsFromHelper(Control* control, const std::string& type) { std::vector<Element*> elements = {}; if (type == "layer") { auto sel = control->getWindow()->getXournal()->getSelection(); if (sel) { control->clearSelection(); // otherwise texts in the selection won't be recognized } elements = xoj::refElementContainer(control->getCurrentPage()->getSelectedLayer()->getElements()); } else if (type == "selection") { auto sel = control->getWindow()->getXournal()->getSelection(); if (sel) { elements = sel->getElements(); } else { return std::make_tuple(std::make_optional("There is no selection"), elements); } } else { std::stringstream err_msg; err_msg << "Unknown argument (" << type << ") for getting selection"; return std::make_tuple(std::make_optional(err_msg.str()), elements); } return std::make_tuple(std::nullopt, elements); } /* * Code conventions: * Error handling: * luapi functions should call `return luaL_error(L, fmt, ...)` if * something *unexpected happens* (e.g. wrong arguments). This throws a * real lua error. * They may also `return nil, errorMessage`. This behavior is reserved for * things that are *expected to happen* (e.g. ressource is not * available). */ /** * Renames file 'from' to file 'to' in the file system. * Overwrites 'to' if it already exists. * * @param from string * @param to string * @return number|nil Returns 1 on success, and (nil, message) on failure. * @return string * * Example: * assert(app.glib_rename("path/to/foo", "other/bar")) * * Preferred to os.rename() because it works across * partitions. Uses glib's rename function. * * Returns 1 on success, and (nil, message) on failure. */ static int applib_glib_rename(lua_State* L) { GError* err = nullptr; xoj::util::GObjectSPtr<GFile> to(g_file_new_for_path(lua_tostring(L, -1)), xoj::util::adopt); xoj::util::GObjectSPtr<GFile> from(g_file_new_for_path(lua_tostring(L, -2)), xoj::util::adopt); g_file_move(from.get(), to.get(), G_FILE_COPY_OVERWRITE, nullptr, nullptr, nullptr, &err); if (err) { // return nil, error message lua_pushnil(L); lua_pushfstring(L, "%s (error code: %d)", err->message, err->code); g_error_free(err); return 2; } else { // return 1 lua_pushinteger(L, 1); return 1; } } /** * THIS FUNCTION IS DEPRECATED AND WILL BE REMOVED SOON. Use applib_fileDialogSave() instead. * * @deprecated * Create a 'Save As' native dialog and return as a string * the filepath of the location the user chose to save. * * @param filename string suggestion for a filename, defaults to "Untitled" * @return string path of the selected location * * Examples: * local filename = app.saveAs() -- defaults to suggestion "Untitled" * local filename = app.saveAs("foo") -- suggests "foo" as filename */ static int applib_saveAs(lua_State* L) { gint res; int args_returned = 0; // change to 1 if user chooses file const char* filename = luaL_checkstring(L, -1); // Create a 'Save As' native dialog xoj::util::GObjectSPtr<GtkFileChooserNative> native( gtk_file_chooser_native_new(_("Save file"), nullptr, GTK_FILE_CHOOSER_ACTION_SAVE, nullptr, nullptr), xoj::util::adopt); // If user tries to overwrite a file, ask if it's OK gtk_file_chooser_set_do_overwrite_confirmation(GTK_FILE_CHOOSER(native.get()), TRUE); // Offer a suggestion for the filename if filename absent gtk_file_chooser_set_current_name(GTK_FILE_CHOOSER(native.get()), filename ? filename : (std::string{_("Untitled")}).c_str()); // Wait until user responds to dialog res = gtk_native_dialog_run(GTK_NATIVE_DIALOG(native.get())); // Return the filename chosen to lua if (res == GTK_RESPONSE_ACCEPT) { char* filename = static_cast<char*>(gtk_file_chooser_get_filename(GTK_FILE_CHOOSER(native.get()))); lua_pushlstring(L, filename, strlen(filename)); g_free(static_cast<gchar*>(filename)); args_returned = 1; } return args_returned; } /** * Create a 'Save As' dialog and once the user has chosen the filepath of the location to save * calls the specified callback function to which it passes the filepath or the empty string, if the * operation was cancelled. * * @param cb string name of the callback function(path:string) to call when a file has been chosen * @param filename string suggestion for a filename, defaults to "Untitled" * * Examples: * app.fileDialogSave("cb") -- defaults to suggestion "Untitled" in current working directory * app.fileDialogSave("cb", "foo") -- suggests "foo" as filename in current working directory * app.fileDialogSave("cb", "/path/to/folder/bar.png") -- suggestes the given absolute path */ static int applib_fileDialogSave(lua_State* L) { lua_settop(L, 2); // discard extra arguments const char* luaCallback = luaL_checkstring(L, 1); const char* filename = luaL_optstring(L, 2, _("Untitled")); if (auto s = std::string(filename); s.find("/") == std::string::npos && s.find("\\") == std::string::npos) { // relative path (contains no slashes and backslashes) filename = ("./" + s).c_str(); } fs::path suggestedPath{filename}; auto pathValidation = [](fs::path& p, const char* filterName) { return true; }; Plugin* plugin = Plugin::getPluginFromLua(L); Control* ctrl = plugin->getControl(); auto callback = [plugin, luaCallback = std::string(luaCallback)](std::optional<fs::path> p) { if (p && !p->empty()) { plugin->callFunction(luaCallback, p.value().string().c_str()); } else { plugin->callFunction(luaCallback, ""); } }; auto popup = xoj::popup::PopupWindowWrapper<xoj::SaveExportDialog>(ctrl->getSettings(), std::move(suggestedPath), _("Save File"), _("Save"), std::move(pathValidation), std::move(callback)); auto* fc = GTK_FILE_CHOOSER(popup.getPopup()->getWindow()); xoj::addFilterAllFiles(fc); popup.show(GTK_WINDOW(ctrl->getWindow()->getWindow())); return 0; } /** * THIS FUNCTION IS DEPRECATED AND WILL BE REMOVED SOON. Use applib_fileDialogOpen() instead. * * @deprecated * Create a 'Open File' native dialog and return as a string * the filepath the user chose to open. * * @param types string[] array of the different allowed extensions e.g. {'\*.bmp', '\*.png'} * @returns string path of the selected location * * Examples: * path = app.getFilePath({}) * path = app.getFilePath({'*.bmp', '*.png'}) */ static int applib_getFilePath(lua_State* L) { xoj::util::GObjectSPtr<GtkFileChooserNative> native( gtk_file_chooser_native_new(_("Open file"), nullptr, GTK_FILE_CHOOSER_ACTION_OPEN, nullptr, nullptr), xoj::util::adopt); gint res; int args_returned = 0; // change to 1 if user chooses file char* filename; // Get vector of supported formats from Lua stack std::vector<std::string> formats; // stack now contains: -1 => table lua_pushnil(L); // stack now contains: -1 => nil; -2 => table while (lua_next(L, -2)) { // stack now contains: -1 => value; -2 => key; -3 => table const char* value = lua_tostring(L, -1); formats.push_back(value); lua_pop(L, 1); // stack now contains: -1 => key; -2 => table } // stack now contains: -1 => table lua_pop(L, 1); // Stack is now the same as it was on entry to this function if (formats.size() > 0) { GtkFileFilter* filterSupported = gtk_file_filter_new(); gtk_file_filter_set_name(filterSupported, _("Supported files")); for (std::string format: formats) { gtk_file_filter_add_pattern(filterSupported, format.c_str()); } gtk_file_chooser_add_filter(GTK_FILE_CHOOSER(native.get()), filterSupported); } // Wait until user responds to dialog res = gtk_native_dialog_run(GTK_NATIVE_DIALOG(native.get())); // Return the filename chosen to lua if (res == GTK_RESPONSE_ACCEPT) { filename = static_cast<char*>(gtk_file_chooser_get_filename(GTK_FILE_CHOOSER(native.get()))); lua_pushlstring(L, filename, strlen(filename)); g_free(static_cast<gchar*>(filename)); args_returned = 1; } // Destroy the dialog and free memory return args_returned; } /** * Create an 'Open File' dialog and when the user has chosen a filepath * call a callback function whose sole argument is the filepath. * * @param cb string name of the callback function(path:string) to call when a file was chosen * @param types string[] array of the different allowed extensions e.g. {'\*.bmp', '\*.png'} * * Examples: * app.fileDialogOpen("cb", {}) * app.fileDialogOpen("cb", {'*.bmp', '*.png'}) */ static int applib_fileDialogOpen(lua_State* L) { // discard any extra arguments passed in lua_settop(L, 2); const char* callback = luaL_checkstring(L, 1); // Get vector of supported formats from Lua stack std::vector<std::string> formats; // stack now contains: -1 => table lua_pushnil(L); // stack now contains: -1 => nil; 2 => table, 1 => string while (lua_next(L, 2)) { // stack now contains: -1 => value; -2 => key; 2 => table, 1 => string const char* value = lua_tostring(L, -1); formats.push_back(value); lua_pop(L, 1); // stack now contains: -1 => key; 2 => table, 1 => string } lua_pop(L, 1); // Stack is now the same as it was on entry to this function Plugin* plugin = Plugin::getPluginFromLua(L); Control* ctrl = plugin->getControl(); xoj::OpenDlg::showMultiFormatDialog(ctrl->getGtkWindow(), formats, [plugin, callback = std::string(callback)](fs::path path) { g_message("%s", (_F("file: {1}") % path.string()).c_str()); plugin->callFunction(callback, path.string().c_str()); }); return 0; } /** * THIS FUNCTION IS DEPRECATED AND WILL BE REMOVED SOON. Use applib_openDialog() instead. * * @deprecated * Example: local result = app.msgbox("Test123", {[1] = "Yes", [2] = "No"}) * Pops up a message box with two buttons "Yes" and "No" and returns 1 for yes, 2 for no */ static int applib_msgbox(lua_State* L) { const char* msg = luaL_checkstring(L, 1); // discard any extra arguments passed in lua_settop(L, 2); luaL_checktype(L, 2, LUA_TTABLE); lua_pushnil(L); // initial key for table traversal with `next` std::vector<XojMsgBox::Button> buttons; while (lua_next(L, 2) != 0) { int index = static_cast<int>(lua_tointeger(L, -2)); const char* buttonText = luaL_checkstring(L, -1); lua_pop(L, 1); buttons.emplace_back(buttonText, index); } Plugin* plugin = Plugin::getPluginFromLua(L); int result = XojMsgBox::askPluginQuestion(plugin->getName(), msg, buttons); lua_pushinteger(L, result); return 1; } /** * Open a dialog with arbitrary text and buttons (with callbacks) * * @param message string * @param options table<integer, string> integer to button texts * @param cb string name of the callback function(button:integer) to call on user interaction * @param error boolean is this message an error (optional) * * Example 1: app.openDialog("Test123", {[1] = "Yes", [2] = "No"}, "cb", false) * or app.openDialog("Test123", {"Yes", "No"}, "cb") * Pops up a message box with two buttons "Yes" and "No" and executed function "cb" whose single parameter is the number * corresponding to the button the user clicked. * * If the optional boolean parameter is true, the dialog is treated as an error message * Example 2: app.openDialog("Invalid parameter", {"Ok"}, "", true) * * Warning: the callback function is never called if the dialog is closed without pressing one of the custom buttons. */ static int applib_openDialog(lua_State* L) { const char* msg = luaL_checkstring(L, 1); // discard any extra arguments passed in lua_settop(L, 4); luaL_checktype(L, 2, LUA_TTABLE); lua_pushnil(L); // initial key for table traversal with `next` std::vector<XojMsgBox::Button> buttons; while (lua_next(L, 2) != 0) { int index = static_cast<int>(lua_tointeger(L, -2)); const char* buttonText = luaL_checkstring(L, -1); lua_pop(L, 1); buttons.emplace_back(buttonText, index); } std::string cb = luaL_optstring(L, 3, ""); bool error = lua_toboolean(L, 4); Plugin* plugin = Plugin::getPluginFromLua(L); const std::string& pluginName = plugin->getName(); auto header = (error ? std::string("<b>Error in </b>") : "") + std::string("Xournal++ Plugin «") + pluginName + "»"; XojMsgBox::askQuestionWithMarkup(nullptr, header, msg, buttons, [cb, plugin](int response) { if (cb != "" && response >= 1) { plugin->callFunction(cb, static_cast<ptrdiff_t>(response)); } }); return 0; } /** * Allow to register menupoints and toolbar buttons. This needs to be called from initUi * * @param opts {menu: string, callback: string, toolbarID: string, mode:integer, accelerator:string} options (`mode`, `toolbarID` and `accelerator` are optional) * @return {menuId:integer} * * Example 1: app.registerUi({["menu"] = "HelloWorld", callback="printMessage", mode=1, accelerator="<Control>a"}) * registers a menupoint with name "HelloWorld" executing a function named "printMessage", in mode 1, * which can be triggered via the "<Control>a" keyboard accelerator * * Example 2: app.registerUi({callback ="blueDashedPen", toolbarId="CUSTOM_PEN_1", iconName="bluePenIcon"}) * registers a toolbar icon named "bluePenIcon" executing a function named "blueDashedPen", which can be added * to a toolbar via toolbar customization or by editing the toolbar.ini file using the name "Plugin::CUSTOM_PEN_1" * Note that in toolbar.ini the string "Plugin::" must always be prepended to the toolbarId specified in the plugin * * The mode and accelerator are optional. When specifying the mode, the callback function should have one parameter that receives the mode. This is useful for callback functions that are shared among multiple menu entries. */ static int applib_registerUi(lua_State* L) { Plugin* plugin = Plugin::getPluginFromLua(L); if (!plugin->isInInitUi()) { return luaL_error(L, "registerUi needs to be called within initUi()"); } // discard any extra arguments passed in lua_settop(L, 1); luaL_checktype(L, 1, LUA_TTABLE); // Now to get the data out of the table // 'unpack' the table by putting the values onto // the stack first. Then convert those stack values // into an appropriate C type. lua_getfield(L, 1, "accelerator"); lua_getfield(L, 1, "menu"); lua_getfield(L, 1, "callback"); lua_getfield(L, 1, "mode"); lua_getfield(L, 1, "toolbarId"); lua_getfield(L, 1, "iconName"); // In Example 1 stack now has following: // 1 = {"menu"="MenuName", callback="functionName", mode=1, accelerator="<Control>a"} // -6 = "<Control>a" // -5 = "MenuName" // -4 = "functionName" // -3 = mode // -2 = nil // -1 = nil const char* accelerator = luaL_optstring(L, -6, ""); const char* menu = luaL_optstring(L, -5, ""); const char* callback = luaL_optstring(L, -4, nullptr); const ptrdiff_t mode = luaL_optinteger(L, -3, std::numeric_limits<ptrdiff_t>::max()); const char* toolbarId = luaL_optstring(L, -2, ""); const char* iconName = luaL_optstring(L, -1, ""); if (callback == nullptr) { return luaL_error(L, "Missing callback function!"); } size_t menuId = plugin->registerMenu(menu, callback, mode, accelerator); plugin->registerToolButton(menu, toolbarId, iconName, callback, mode); // Make sure to remove all vars which are put to the stack before! lua_pop(L, 6); // Add return value to the Stack lua_createtable(L, 0, 2); lua_pushstring(L, "menuId"); lua_pushinteger(L, as_signed(menuId)); lua_settable(L, -3); /* 3rd element from the stack top */ return 1; } /** * Execute an UI action (usually internally called from Toolbar / Menu) * The argument consists of a Lua table with 3 keys: "action", "group" and "enabled" * The key "group" is currently only used for debugging purpose and can safely be omitted. * The key "enabled" is true by default. * * @param opts {action: string, enabled:boolean} options (`enabled` is `true` by default) * * Example 1: app.uiAction({["action"] = "ACTION_PASTE"}) * pastes the clipboard content into the document * * Example 2: app.uiAction({["action"] = "ACTION_TOOL_DRAW_ELLIPSE", ["enabled"] = false}) * turns off the Ellipse drawing type */ static int applib_uiAction(lua_State* L) { Plugin* plugin = Plugin::getPluginFromLua(L); // discard any extra arguments passed in lua_settop(L, 1); luaL_checktype(L, 1, LUA_TTABLE); lua_getfield(L, 1, "enabled"); lua_getfield(L, 1, "action"); // stack now has following: // 1 = {["action"] = "ACTION_GRID_SNAPPING", ["group"] = "GROUP_GRID_SNAPPING", ["enabled"] = true} // -2 = true // -1 = "ACTION_GRID_SNAPPING" bool enabled = lua_isboolean(L, -2) ? lua_toboolean(L, -2) : true; const char* actionStr = luaL_optstring(L, -1, nullptr); if (actionStr == nullptr) { return luaL_error(L, "Missing action!"); } ActionBackwardCompatibilityLayer::actionPerformed(plugin->getControl(), actionStr, enabled); return 0; } /** * Execute action from sidebar menu * * @param action string the desired action * * Example: app.sidebarAction("MOVE_DOWN") * moves down the current page or layer, depending on which sidebar tab is selected */ static int applib_sidebarAction(lua_State* L) { // Connect the context menu actions const std::map<std::string, Action> actionMapPage = { {"COPY", Action::DUPLICATE_PAGE}, {"DELETE", Action::DELETE_PAGE}, {"MOVE_UP", Action::MOVE_PAGE_TOWARDS_BEGINNING}, {"MOVE_DOWN", Action::MOVE_PAGE_TOWARDS_END}, {"NEW_BEFORE", Action::NEW_PAGE_BEFORE}, {"NEW_AFTER", Action::NEW_PAGE_AFTER}, }; const std::map<std::string, Action> actionMapLayer = { {"COPY", Action::LAYER_COPY}, {"DELETE", Action::LAYER_DELETE}, {"MOVE_UP", Action::LAYER_MOVE_UP}, {"MOVE_DOWN", Action::LAYER_MOVE_DOWN}, {"MERGE_DOWN", Action::LAYER_MERGE_DOWN}, }; const char* actionStr = luaL_checkstring(L, 1); if (actionStr == nullptr) { return luaL_error(L, "Missing action!"); } Plugin* plugin = Plugin::getPluginFromLua(L); Control* control = plugin->getControl(); size_t tab = control->getSidebar()->getSelectedTab(); if (tab == 0) { return luaL_error(L, "Currently selected sidebar tab does not have any actions"); } const auto actionMap = (tab == 1) ? actionMapPage : actionMapLayer; auto pos = actionMap.find(actionStr); if (pos == actionMap.end()) { return luaL_error(L, "Unknown action: %s", actionStr); } auto* actionDB = control->getActionDatabase(); actionDB->fireActivateAction(pos->second); return 0; } /** * Get the index of the currently active sidebar-page. * * @return integer pageNr pageNr of the sidebar page * * Example: app.getSidebarPageNo() -- returns e.g. 1 */ static int applib_getSidebarPageNo(lua_State* L) { Plugin* plugin = Plugin::getPluginFromLua(L); Sidebar* sidebar = plugin->getControl()->getSidebar(); lua_pushinteger(L, as_signed(sidebar->getSelectedTab()) + 1); return 1; } /** * Set the currently active sidebar-page by its index. * * @param pageNr integer pageNr of the sidebar page * * Look at src/core/gui/sidebar/Sidebar.cpp to find out which index corresponds to which page (e.g. currently 1 is the * page with the TOC/index if available). Note that indexing the sidebar-pages starts at 1 (as usual in lua). * * Example: app.setSidebarPageNo(3) -- sets the sidebar-page to preview Layer */ static int applib_setSidebarPageNo(lua_State* L) { Plugin* plugin = Plugin::getPluginFromLua(L); Sidebar* sidebar = plugin->getControl()->getSidebar(); // Discard any extra arguments passed in lua_settop(L, 1); if (!lua_isinteger(L, 1)) { return luaL_error(L, "Missing pageNo for setSidebarPageNo!"); } auto page = static_cast<int>(lua_tointeger(L, 1)); if (page <= 0) { lua_pushnil(L); lua_pushfstring(L, "Invalid pageNo (%d) provided!", page); return 2; } if (as_unsigned(page) > sidebar->getNumberOfTabs()) { lua_pushnil(L); lua_pushfstring(L, "Invalid pageNo (%d >= %d) provided!", page, sidebar->getNumberOfTabs()); return 2; } sidebar->setSelectedTab(as_unsigned(page) - 1); return 0; } /** * Execute action from layer controller * * @param action string the desired action * * Example: app.layerAction("ACTION_DELETE_LAYER") * deletes the current layer */ static int applib_layerAction(lua_State* L) { Plugin* plugin = Plugin::getPluginFromLua(L); const char* actionStr = luaL_checkstring(L, 1); if (actionStr == nullptr) { return luaL_error(L, "Missing action!"); } ActionBackwardCompatibilityLayer::actionPerformed(plugin->getControl(), actionStr, true); return 0; } /** * Helper function to handle a allowUndoRedoAction string parameter. allowUndoRedoAction can take the following values: * - "grouped": the elements get a single undo-redo-action * - "individual" each of the elements get an own undo-redo-action * - "none": no undo-redo-action will be inserted * if an invalid value is being passed as allowUndoRedoAction this function errors */ static int handleUndoRedoActionHelper(lua_State* L, Control* control, const char* allowUndoRedoAction, const std::vector<Element*>& elements) { if (strcmp("grouped", allowUndoRedoAction) == 0) { PageRef const& page = control->getCurrentPage(); Layer* layer = page->getSelectedLayer(); UndoRedoHandler* undo = control->getUndoRedoHandler(); undo->addUndoAction(std::make_unique<InsertsUndoAction>(page, layer, elements)); } else if (strcmp("individual", allowUndoRedoAction) == 0) { PageRef const& page = control->getCurrentPage(); Layer* layer = page->getSelectedLayer(); UndoRedoHandler* undo = control->getUndoRedoHandler(); for (Element* element: elements) { undo->addUndoAction(std::make_unique<InsertUndoAction>(page, layer, element)); } } else if (strcmp("none", allowUndoRedoAction) == 0) { g_warning("Not allowing undo/redo action."); } else { return luaL_error(L, "Unrecognized undo/redo option: %s", allowUndoRedoAction); } return 0; } /** * Helper function for addStroke API. Parses pen settings from API call, taking * in a Stroke and a chosen Layer, sets the pen settings, and applies the stroke. */ static void addStrokeHelper(lua_State* L, std::unique_ptr<Stroke> stroke) { Plugin* plugin = Plugin::getPluginFromLua(L); Control* ctrl = plugin->getControl(); PageRef const& page = ctrl->getCurrentPage(); Layer* layer = page->getSelectedLayer(); std::string size; double thickness; int fillOpacity; bool filled; Color color; std::string lineStyle; ToolHandler* toolHandler; const char* tool; std::string allowUndoRedoAction; // Get attributes. lua_getfield(L, -1, "tool"); lua_getfield(L, -2, "width"); lua_getfield(L, -3, "color"); lua_getfield(L, -4, "fill"); lua_getfield(L, -5, "lineStyle"); // stack now has following: // -6 = table // -5 = tool // -4 = width // -3 = color // -2 = fill // -1 = lineStyle tool = luaL_optstring(L, -5, ""); // We're gonna need the tool type. toolHandler = ctrl->getToolHandler(); // TODO: (willnilges) Handle DrawingType? // TODO: (willnilges) Break out Eraser functionality into a new API call. // Set tool type if (strcmp("highlighter", tool) == 0) { stroke->setToolType(StrokeTool::HIGHLIGHTER); size = toolSizeToString(toolHandler->getHighlighterSize()); thickness = toolHandler->getToolThickness(TOOL_HIGHLIGHTER)[toolSizeFromString(size)]; fillOpacity = toolHandler->getHighlighterFill(); filled = toolHandler->getHighlighterFillEnabled(); Tool& tool = toolHandler->getTool(TOOL_HIGHLIGHTER); color = tool.getColor(); } else { if (!(strcmp("pen", tool) == 0)) { g_warning("%s", FC(_F("Unknown stroke type: \"{1}\", defaulting to pen") % tool)); } stroke->setToolType(StrokeTool::PEN); size = toolSizeToString(toolHandler->getPenSize()); thickness = toolHandler->getToolThickness(TOOL_PEN)[toolSizeFromString(size)]; fillOpacity = toolHandler->getPenFill(); filled = toolHandler->getPenFillEnabled(); Tool& tool = toolHandler->getTool(TOOL_PEN); color = tool.getColor(); lineStyle = StrokeStyle::formatStyle(tool.getLineStyle()); } // Set width if (lua_isnumber(L, -4)) { // Check if the width was provided stroke->setWidth(lua_tonumber(L, -4)); } else { stroke->setWidth(thickness); } // Set color if (lua_isinteger(L, -3)) { // Check if the color was provided stroke->setColor(static_cast<Color>(static_cast<uint32_t>(as_unsigned(lua_tointeger(L, -3))))); } else { stroke->setColor(color); } // Set fill if (lua_isinteger(L, -2)) { // Check if fill settings were provided stroke->setFill(static_cast<int>(lua_tointeger(L, -2))); } else if (filled) { stroke->setFill(fillOpacity); } else { stroke->setFill(-1); // No fill } // Set line style if (lua_isstring(L, -1)) { // Check if line style settings were provided stroke->setLineStyle(StrokeStyle::parseStyle(lua_tostring(L, -1))); } else { stroke->setLineStyle(StrokeStyle::parseStyle(lineStyle.data())); } // stack cleanup is needed as this is a helper function lua_pop(L, 5); // Finally done with all that Lua data. // Add the stroke layer->addElement(std::move(stroke)); return; } /** * Given a table containing a series of splines, draws a batch of strokes on the canvas. * Expects a table of tables containing eight coordinate pairs, along with attributes of the stroke. * * @param opts {splines:{coordinates:number[], tool:string, width:number, color:integer, fill:number, * linestyle:string}[], allowUndoRedoAction:string} * * Required Arguments: splines * Optional Arguments: pressure, tool, width, color, fill, lineStyle * * If optional arguments are not provided, the specified tool settings are used. * If the tool is not provided, the current pen settings are used. * The only tools supported are Pen and Highlighter. * * The function expects 8 points per spline segment. Due to the nature of cubic * splines, you must pass your points in a repeating pattern: * startX, startY, ctrl1X, ctrl1Y, ctrl2X, ctrl2Y, endX, endY, startX, startY, ... * * The function checks that the length of the coordinate table is divisible by eight, and will throw * an error if it is not. * * Example: app.addSplines({ * ["splines"] = { -- The outer table is a table of strokes * ["coordinates"] = { -- Each inner table is a coord stream that represents SplineSegments that can be * assembled into a stroke * [1] = 880.0, // Every eight coordinates (4 pairs) is a SplineSegment * [2] = 874.0, * [3] = 881.3295, * [4] = 851.5736, * [5] = 877.2915, * [6] = 828.2946, * [7] = 875.1697, * [8] = 806.0, * ... -- A spline can be made up of as many SplineSegments as is necessary. * }, * -- Tool options are also specified per-stroke * ["width"] = 1.4, * ["color"] = 0xff0000, * ["fill"] = 0, * ["tool"] = "pen", * ["lineStyle"] = "plain" * }, * ["allowUndoRedoAction"] = "grouped", -- Each batch of splines can be grouped into one undo/redo action (or * "individual" or "none") * }) */ static int applib_addSplines(lua_State* L) { Plugin* plugin = Plugin::getPluginFromLua(L); Control* ctrl = plugin->getControl(); std::vector<Element*> strokes; const char* allowUndoRedoAction; // Discard any extra arguments passed in lua_settop(L, 1); luaL_checktype(L, 1, LUA_TTABLE); lua_getfield(L, 1, "splines"); if (!lua_istable(L, -1)) { return luaL_error(L, "Missing spline table!"); } // stack now has following: // 1 = table arg // -1 = splines size_t numSplines = lua_rawlen(L, -1); for (size_t a = 1; a <= numSplines; a++) { std::vector<double> coordStream; auto stroke = std::make_unique<Stroke>(); // Get coordinates lua_pushinteger(L, as_signed(a)); lua_gettable(L, -2); // get current spline from splines table lua_getfield(L, -1, "coordinates"); // get coordinates of the current spline if (!lua_istable(L, -1)) { return luaL_error(L, "Missing coordinate table!"); } size_t numCoords = lua_rawlen(L, -1); for (size_t b = 1; b <= numCoords; b++) { lua_pushinteger(L, as_signed(b)); lua_gettable(L, -2); // get current coordinate from coordinates double point = lua_tonumber(L, -1); coordStream.push_back(point); // Each segment is going to have multiples of 8 points. lua_pop(L, 1); // cleanup fetched coordinate } // pop value + copy of key, leaving original key lua_pop(L, 1); // cleanup coordinates table // Handle those points // Check if the list is divisible by 8. if (coordStream.size() % 8 != 0) { return luaL_error(L, "Point table incomplete!"); } // Now take that gigantic list of splines and create SplineSegments out of them. long unsigned int i = 0; while (i < coordStream.size()) { // start, ctrl1, ctrl2, end Point start = Point(coordStream.at(i), coordStream.at(i + 1), Point::NO_PRESSURE); Point ctrl1 = Point(coordStream.at(i + 2), coordStream.at(i + 3), Point::NO_PRESSURE); Point ctrl2 = Point(coordStream.at(i + 4), coordStream.at(i + 5), Point::NO_PRESSURE); Point end = Point(coordStream.at(i + 6), coordStream.at(i + 7), Point::NO_PRESSURE); i += 8; SplineSegment segment = SplineSegment(start, ctrl1, ctrl2, end); std::list<Point> raster = segment.toPointSequence(); for (Point point: raster) { stroke->addPoint(point); } // TODO: (willnilges) Is there a way we can get Pressure with Splines? } if (stroke->getPointCount() >= 2) { // Finish building the Stroke and apply it to the layer. strokes.push_back(stroke.get()); addStrokeHelper(L, std::move(stroke)); } else { g_warning("Stroke shorter than two points. Discarding. (Has %zu)", stroke->getPointCount()); } // Onto the next stroke lua_pop(L, 1); // cleanup current spline } // Stack is now the same as it was on entry to this function lua_pop(L, 1); // cleanup splines table // stack now has following: // 1 = table arg // Check how the user wants to handle undoing lua_getfield(L, 1, "allowUndoRedoAction"); allowUndoRedoAction = luaL_optstring(L, -1, "grouped"); lua_pop(L, 1); handleUndoRedoActionHelper(L, ctrl, allowUndoRedoAction, strokes); return 0; } /** * Given a table of sets of points, draws a batch of strokes on the canvas. * Expects three tables of equal length: one for X, one for Y, and one for * stroke pressure, along with attributes of the stroke. Each stroke has * attributes handled individually. * * @param opts {strokes:{X:number[], Y:number[], pressure:number[], tool:string, width:number, color:integer, * fill:number, linestyle:string}[], allowUndoRedoAction:string} * * Required Arguments: X, Y * Optional Arguments: pressure, tool, width, color, fill, lineStyle * * If optional arguments are not provided, the specified tool settings are used. * If the tool is not provided, the current pen settings are used. * The only tools supported are Pen and Highlighter. * * The function checks for consistency among table lengths, and throws an * error if there is a discrepancy * * Example: * * app.addStrokes({ * ["strokes"] = { -- The outer table is a table of strokes * { -- Inside a stroke are three tables of equivalent length that represent a series of points * ["x"] = { [1] = 110.0, [2] = 120.0, [3] = 130.0, ... }, * ["y"] = { [1] = 200.0, [2] = 205.0, [3] = 210.0, ... }, * ["pressure"] = { [1] = 0.8, [2] = 0.9, [3] = 1.1, ... }, * -- Each stroke has individually handled options * ["tool"] = "pen", * ["width"] = 3.8, * ["color"] = 0xa000f0, * ["fill"] = 0, * ["lineStyle"] = "solid", * }, * { * ["x"] = { [1] = 310.0, [2] = 320.0, [3] = 330.0, ... }, * ["y"] = { [1] = 300.0, [2] = 305.0, [3] = 310.0, ... }, * ["pressure"] = { [1] = 3.0, [2] = 3.0, [3] = 3.0, ... }, * ["tool"] = "pen", * ["width"] = 1.21, * ["color"] = 0x808000, * ["fill"] = 0, * ["lineStyle"] = "solid", * }, * { * ["x"] = { [1] = 27.0, [2] = 28.0, [3] = 30.0, ... }, * ["y"] = { [1] = 100.0, [2] = 102.3, [3] = 102.5, ... }, * ["pressure"] = { [1] = 1.0, [2] = 1.0, [3] = 1.0, ... }, * ["tool"] = "pen", * ["width"] = 1.0, * ["color"] = 0x00aaaa, * ["fill"] = 0, * ["lineStyle"] = "dashdot", * }, * }, * ["allowUndoRedoAction"] = "grouped", -- Each batch of strokes can be grouped into one undo/redo action (or * "individual" or "none") * }) */ static int applib_addStrokes(lua_State* L) { Plugin* plugin = Plugin::getPluginFromLua(L); Control* ctrl = plugin->getControl(); std::vector<Element*> strokes; const char* allowUndoRedoAction; // Discard any extra arguments passed in lua_settop(L, 1); luaL_checktype(L, 1, LUA_TTABLE); lua_getfield(L, 1, "strokes"); if (!lua_istable(L, -1)) { return luaL_error(L, "Missing stroke table!"); } // stack now has following: // 1 = table arg // -1 = strokes size_t numStrokes = lua_rawlen(L, -1); for (size_t a = 1; a <= numStrokes; a++) { std::vector<double> xStream; std::vector<double> yStream; std::vector<double> pressureStream; auto stroke = std::make_unique<Stroke>(); // Fetch table of X values from the Lua stack lua_pushinteger(L, as_signed(a)); lua_gettable(L, -2); // get current stroke lua_getfield(L, -1, "x"); // get x array of current stroke if (!lua_istable(L, -1)) { return luaL_error(L, "Missing X-Coordinate table!"); } size_t xPoints = lua_rawlen(L, -1); for (size_t b = 1; b <= xPoints; b++) { lua_pushinteger(L, as_signed(b)); lua_gettable(L, -2); // get current x-Coordinate double value = lua_tonumber(L, -1); xStream.push_back(value); lua_pop(L, 1); // cleanup x-Coordinate } lua_pop(L, 1); // cleanup x array // Fetch table of Y values form the Lua stack lua_getfield(L, -1, "y"); // get y array of current stroke if (!lua_istable(L, -1)) { return luaL_error(L, "Missing Y-Coordinate table!"); } size_t yPoints = lua_rawlen(L, -1); for (size_t b = 1; b <= yPoints; b++) { lua_pushinteger(L, as_signed(b)); lua_gettable(L, -2); // get current y-Coordinate double value = lua_tonumber(L, -1); yStream.push_back(value); lua_pop(L, 1); // cleanup y-Coordinate } lua_pop(L, 1); // cleanup y array // Fetch table of pressure values from the Lua stack lua_getfield(L, -1, "pressure"); if (lua_istable(L, -1)) { size_t pressurePoints = lua_rawlen(L, -1); for (size_t b = 1; b <= pressurePoints; b++) { lua_pushinteger(L, as_signed(b)); lua_gettable(L, -2); // get current pressure double value = lua_tonumber(L, -1); pressureStream.push_back(value); lua_pop(L, 1); // cleanup pressure } } lua_pop(L, 1); // cleanup pressure array // Handle those points // Make sure all vectors are the same length. if (xStream.size() != yStream.size()) { return luaL_error(L, "X and Y vectors are not equal length!"); } if (xStream.size() != pressureStream.size() && pressureStream.size() > 0) { return luaL_error(L, "Pressure vector is not equal length!"); } // Check and make sure there's enough points (need at least 2) if (xStream.size() < 2) { g_warning("Stroke shorter than two points. Discarding. (Has %zu/2)", xStream.size()); return 1; } // Add points to the stroke. Include pressure, if it exists. if (pressureStream.size() > 0) { for (long unsigned int i = 0; i < xStream.size(); i++) { Point myPoint = Point(xStream.at(i), yStream.at(i), pressureStream.at(i)); stroke->addPoint(myPoint); } } else { for (long unsigned int i = 0; i < xStream.size(); i++) { Point myPoint = Point(xStream.at(i), yStream.at(i), Point::NO_PRESSURE); stroke->addPoint(myPoint); } } // Finish building the Stroke and apply it to the layer. strokes.push_back(stroke.get()); addStrokeHelper(L, std::move(stroke)); // Onto the next stroke lua_pop(L, 1); // cleanup stroke table } // stack now has following: // 1 = table arg // -1 = strokes // Check how the user wants to handle undoing lua_getfield(L, 1, "allowUndoRedoAction"); allowUndoRedoAction = luaL_optstring(L, -1, "grouped"); if (strcmp("grouped", allowUndoRedoAction) == 0) { PageRef const& page = ctrl->getCurrentPage(); Layer* layer = page->getSelectedLayer(); UndoRedoHandler* undo = ctrl->getUndoRedoHandler(); undo->addUndoAction(std::make_unique<InsertsUndoAction>(page, layer, strokes)); } else if (strcmp("individual", allowUndoRedoAction) == 0) { PageRef const& page = ctrl->getCurrentPage(); Layer* layer = page->getSelectedLayer(); UndoRedoHandler* undo = ctrl->getUndoRedoHandler(); for (Element* element: strokes) { undo->addUndoAction(std::make_unique<InsertUndoAction>(page, layer, element)); } } else if (strcmp("none", allowUndoRedoAction) == 0) g_warning("Not allowing undo/redo action."); else { return luaL_error(L, "Unrecognized undo/redo option: %s", allowUndoRedoAction); } return 0; } /** * Adds textboxes as specified to the current layer. * * Global parameters: * - texts table: array of text-parameter-tables * - allowUndoRedoAction string: Decides how the change gets introduced into the undoRedo action list "individual", * "grouped" or "none" * * @param opts {texts:{text:string, font:{name:string, size:number}, color:integer, x:number, y:number}[], * allowUndoRedoAction:string} * * Parameters per textbox: * - text string: content of the textbox (required) * - font table {name string, size number} (default: currently configured font/size from the settings) * - color integer: RGB hex code for the text-color (default: color of text tool) * - x number: x-position of the box (upper left corner) (required) * - y number: y-position of the box (upper left corner) (required) * * Example: * * app.addTexts{texts={ * { * text="Hello World", * font={name="Noto Sans Mono Medium", size=8.0}, * color=0x1259b9, * x = 50.0, * y = 50.0, * }, * { * text="Testing", * font={name="Noto Sans Mono Medium", size=8.0}, * color=0x0, * x = 150.0, * y = 50.0, * }, * } */ static int applib_addTexts(lua_State* L) { Plugin* plugin = Plugin::getPluginFromLua(L); Control* control = plugin->getControl(); PageRef const& page = control->getCurrentPage(); Layer* layer = page->getSelectedLayer(); Settings* settings = control->getSettings(); std::vector<Element*> texts; // Discard any extra arguments passed in lua_settop(L, 1); luaL_checktype(L, 1, LUA_TTABLE); lua_getfield(L, 1, "texts"); if (!lua_istable(L, -1)) { return luaL_error(L, "Missing text table!"); } // stack now has following: // 1 = table arg // -1 = texts array // get default color ToolHandler* toolHandler = control->getToolHandler(); Tool& tool = toolHandler->getTool(TOOL_TEXT); Color default_color = tool.getColor(); // default font XojFont& default_font = settings->getFont(); size_t numTexts = lua_rawlen(L, -1); for (size_t a = 1; a <= numTexts; a++) { auto text = std::make_unique<Text>(); // Fetch table of X values from the Lua stack lua_pushinteger(L, as_signed(a)); lua_gettable(L, -2); // get current text luaL_checktype(L, -1, LUA_TTABLE); lua_getfield(L, -1, "text"); // handle font table lua_getfield(L, -2, "font"); // {name="", size=0} if (lua_istable(L, -1)) { lua_getfield(L, -1, "name"); lua_getfield(L, -2, "size"); } else if (lua_isnil(L, -1)) { // push two dummy values if font is unset/no table lua_pushnil(L); lua_pushnil(L); } else { return luaL_error(L, "'font' value must be a table!"); } lua_getfield(L, -5, "color"); lua_getfield(L, -6, "x"); lua_getfield(L, -7, "y"); // stack now has following: // 1 = global params table // -9 = texts array // -8 = current text-params table // -7 = text // -6 = font-table // -5 = fontname // -4 = fontsize // -3 = color // -2 = x // -1 = y if (!lua_isstring(L, -7)) { return luaL_error(L, "Missing text!/'text' must be a string"); } text->setText(lua_tostring(L, -7)); XojFont font{}; font.setName(luaL_optstring(L, -5, default_font.getName().c_str())); font.setSize(luaL_optnumber(L, -4, default_font.getSize())); text->setFont(font); if (lua_isinteger(L, -3)) { // Check if the color was provided uint32_t color = static_cast<uint32_t>(as_unsigned(lua_tointeger(L, -3))); if (color > 0xffffff) { std::stringstream msg; msg << "Color 0x" << std::hex << color << " is no valid RGB color."; return luaL_error(L, msg.str().c_str()); // luaL_error does not support %x for hex numbers } text->setColor(Color(color | 0xff000000U)); } else if (lua_isnil(L, -3)) { text->setColor(default_color); } else { return luaL_error(L, "'color' must be an integer/hex-code or unset"); } if (!lua_isnumber(L, -2)) { // Check if x was provided return luaL_error(L, "Missing X-Coordinate!/must be a number"); } text->setX(lua_tonumber(L, -2)); if (!lua_isnumber(L, -1)) { // Check if y was provided return luaL_error(L, "Missing Y-Coordinate!/must be a number"); } text->setY(lua_tonumber(L, -1)); lua_pop(L, 8); // remove values read out from the text table + text-table itself // Finish building the Text and apply it to the layer. texts.push_back(text.get()); layer->addElement(std::move(text)); // Onto the next text } // stack now has following: // 1 = table arg // -1 = texts array lua_getfield(L, 1, "allowUndoRedoAction"); const char* allowUndoRedoAction = luaL_optstring(L, -1, "grouped"); lua_pop(L, 1); handleUndoRedoActionHelper(L, control, allowUndoRedoAction, texts); return 0; } /** * Returns a list of lua table of the texts (from current selection / current layer). * Is mostly inverse to app.addTexts (except getTexts will also retrieve the width/height of the textbox) * * @param type string "selection" or "layer" * @return {text:string, font:{name:string, size:number}, color:integer, x:number, y:number, width:number, * height:number}[] texts * * Required argument: type ("selection" or "layer") * * Example: local texts = app.getTexts("layer") * * possible return value: * { * { * text = "Hello World", * font = { * name = "Noto Sans Mono Medium", * size = 8.0, * }, * color = 0x1259b9, * x = 127.0, * y = 70.0, * width = 55.0, * height = 23.0, * }, * { * text = "Testing", * font = { * name = "Noto Sans Mono Medium", * size = 8.0, * }, * color = 0x0, * x = 150.0,, * y = 70.0, * width = 55.0, * height = 23.0, * }, * } * */ static int applib_getTexts(lua_State* L) { Plugin* plugin = Plugin::getPluginFromLua(L); std::string type = luaL_checkstring(L, 1); Control* control = plugin->getControl(); // Discard any extra arguments passed in lua_settop(L, 1); luaL_checktype(L, 1, LUA_TSTRING); const auto& [err, elements] = getElementsFromHelper(control, type); if (err.has_value()) { return luaL_error(L, err.value().c_str()); } lua_newtable(L); // create table of the elements int currTextNo = 0; // stack now has following: // 1 = type (string) // -1 = table of texts (to be returned) for (Element* e: elements) { if (e->getType() == ELEMENT_TEXT) { auto* t = static_cast<Text*>(e); lua_pushinteger(L, ++currTextNo); // index for later (settable) lua_newtable(L); // create text table // stack now has following: // 1 = type (string) // -3 = table of texts (to be returned) // -2 = index of the current text // -1 = current text table lua_pushstring(L, t->getText().c_str()); lua_setfield(L, -2, "text"); // add text to text element lua_newtable(L); // font table to stack lua_pushstring(L, t->getFontName().c_str()); lua_setfield(L, -2, "name"); // add font to text lua_pushnumber(L, t->getFontSize()); lua_setfield(L, -2, "size"); // add size to text lua_setfield(L, -2, "font"); // insert font-table to text element lua_pushinteger(L, as_signed(uint32_t(t->getColor()) & 0xffffffU)); lua_setfield(L, -2, "color"); // add color to text lua_pushnumber(L, t->getX()); lua_setfield(L, -2, "x"); // add x coordindate to text lua_pushnumber(L, t->getY()); lua_setfield(L, -2, "y"); // add y coordinate to text lua_pushnumber(L, t->getElementWidth()); lua_setfield(L, -2, "width"); // add width to text lua_pushnumber(L, t->getElementHeight()); lua_setfield(L, -2, "height"); // add height to text lua_settable(L, -3); // add text to elements } } return 1; } /** * Puts a Lua Table of the Strokes (from the selection tool / selected layer) onto the stack. * Is inverse to app.addStrokes * * @param type string "selection" or "layer" * @return {x:number[], y:number[], pressure:number[], tool:string, width:number, color:integer, fill:number, * linestyle:string}[] strokes * * Required argument: type ("selection" or "layer") * * Example: local strokes = app.getStrokes("selection") * * possible return value: * { * { -- Inside a stroke are three tables of equivalent length that represent a series of points * ["x"] = { [1] = 110.0, [2] = 120.0, [3] = 130.0, ... }, * ["y"] = { [1] = 200.0, [2] = 205.0, [3] = 210.0, ... }, * -- pressure is only present if pressure is set -> pressure member might be nil * ["pressure"] = { [1] = 0.8, [2] = 0.9, [3] = 1.1, ... }, * -- Each stroke has individually handled options * ["tool"] = "pen", * ["width"] = 3.8, * ["color"] = 0xa000f0, * ["fill"] = 0, * ["lineStyle"] = "plain", * }, * { * ["x"] = {207, 207.5, 315.2, 315.29, 207.5844}, * ["y"] = {108, 167.4, 167.4, 108.70, 108.7094}, * ["tool"] = "pen", * ["width"] = 0.85, * ["color"] = 16744448, * ["fill"] = -1, * ["lineStyle"] = "plain", * }, * { * ["x"] = {387.60, 387.6042, 500.879, 500.87, 387.604}, * ["y"] = {153.14, 215.8661, 215.866, 153.14, 153.148}, * ["tool"] = "pen", * ["width"] = 0.85, * ["color"] = 16744448, * ["fill"] = -1, * ["lineStyle"] = "plain", * }, * } */ static int applib_getStrokes(lua_State* L) { Plugin* plugin = Plugin::getPluginFromLua(L); std::string type = luaL_checkstring(L, 1); Control* control = plugin->getControl(); // Discard any extra arguments passed in lua_settop(L, 1); luaL_checktype(L, 1, LUA_TSTRING); const auto& [err, elements] = getElementsFromHelper(control, type); if (err.has_value()) { return luaL_error(L, err.value().c_str()); } lua_newtable(L); // create table of the elements int currStrokeNo = 0; int currPointNo = 0; // stack now has following: // 1 = type (string) // -1 = table of strokes (to be returned) for (Element* e: elements) { if (e->getType() == ELEMENT_STROKE) { auto* s = static_cast<Stroke*>(e); lua_pushinteger(L, ++currStrokeNo); // index for later (settable) lua_newtable(L); // create stroke table // stack now has following: // 1 = type (string) // -3 = table of strokes (to be returned) // -2 = index of the current stroke // -1 = current stroke lua_newtable(L); // create table of x-coordinates for (auto p: s->getPointVector()) { lua_pushinteger(L, ++currPointNo); // key lua_pushnumber(L, p.x); // value lua_settable(L, -3); // insert } lua_setfield(L, -2, "x"); // add x-coordinates to stroke currPointNo = 0; lua_newtable(L); // create table for y-coordinates for (auto p: s->getPointVector()) { lua_pushinteger(L, ++currPointNo); // key lua_pushnumber(L, p.y); // value lua_settable(L, -3); // insert } lua_setfield(L, -2, "y"); // add y-coordinates to stroke currPointNo = 0; if (s->hasPressure()) { lua_newtable(L); // create table for pressures for (auto p: s->getPointVector()) { lua_pushinteger(L, ++currPointNo); // key lua_pushnumber(L, p.z); // value lua_settable(L, -3); // insert } lua_setfield(L, -2, "pressure"); // add pressures to stroke currPointNo = 0; } // stack now has following: // 1 = type (string) // -3 = table of strokes (to be returned) // -2 = index of the current stroke // -1 = current stroke StrokeTool tool = s->getToolType(); if (tool == StrokeTool::PEN) { lua_pushstring(L, "pen"); } else if (tool == StrokeTool::ERASER) { lua_pushstring(L, "eraser"); } else if (tool == StrokeTool::HIGHLIGHTER) { lua_pushstring(L, "highlighter"); } else { return luaL_error(L, "Unknown StrokeTool::Value."); } lua_setfield(L, -2, "tool"); // add tool to stroke lua_pushnumber(L, s->getWidth()); lua_setfield(L, -2, "width"); // add width to stroke lua_pushinteger(L, as_signed(uint32_t(s->getColor()) & 0xffffffU)); lua_setfield(L, -2, "color"); // add color to stroke lua_pushinteger(L, s->getFill()); lua_setfield(L, -2, "fill"); // add fill to stroke lua_pushstring(L, StrokeStyle::formatStyle(s->getLineStyle()).c_str()); lua_setfield(L, -2, "lineStyle"); // add linestyle to stroke lua_settable(L, -3); // add stroke to returned table } } return 1; } /** * Notifies program of any updates to the working document caused * by the API. * * Example: app.refreshPage() */ static int applib_refreshPage(lua_State* L) { Plugin* plugin = Plugin::getPluginFromLua(L); Control* ctrl = plugin->getControl(); PageRef const& page = ctrl->getCurrentPage(); if (page) { page->firePageChanged(); } else { return luaL_error(L, "Called applib_refreshPage, but there is no current page."); } return 0; } /** * Change page background of current page * * @param background string backgroundType (e.g. "graph") * * Example: app.changeCurrentPageBackground("graph") * changes the page background of the current page to graph paper */ static int applib_changeCurrentPageBackground(lua_State* L) { PageType pt; pt.format = PageTypeHandler::getPageTypeFormatForString(luaL_checkstring(L, 1)); pt.config = luaL_optstring(L, 2, ""); Plugin* plugin = Plugin::getPluginFromLua(L); Control* ctrl = plugin->getControl(); PageBackgroundChangeController* pageBgCtrl = ctrl->getPageBackgroundChangeController(); pageBgCtrl->changeCurrentPageBackground(pt); return 0; } /** * Query all colors of the current palette. * * @return {color: integer, name: string}[] options * * Example: palette = app.getColorPalette() * possible return value: * { * [1] = {color = 0xffffff, name = "white" }, * [2] = {color = 0x000000, name = "black" }, * [3] = {color = 0xdc8a78, name = "Rosewater" }, * } * */ static int applib_getColorPalette(lua_State* L) { // discard any extra arguments passed in lua_settop(L, 0); Plugin* plugin = Plugin::getPluginFromLua(L); Settings* settings = plugin->getControl()->getSettings(); const Palette& palette = plugin->getControl()->getPalette(); lua_newtable(L); // return table for (size_t i = 0; i < palette.size(); i++) { lua_pushinteger(L, as_signed(i) + 1); // index in return table lua_newtable(L); // item table const auto& col = palette.getColorAt(i); lua_pushstring(L, col.getName().c_str()); lua_setfield(L, -2, "name"); lua_pushinteger(L, as_signed(uint32_t(col.getColor()) & 0xffffffU)); lua_setfield(L, -2, "color"); lua_settable(L, -3); } return 1; } /** * Change color of a specified tool or of the current tool * * @param opts {color: integer, tool: string, selection: boolean} options (`selection=true` -> new color applies to * active selection as well, `tool=nil` (unset) -> currently active tool is being used) * * Example 1: app.changeToolColor({["color"] = 0xff00ff, ["tool"] = "PEN"}) * changes the color of the pen tool to violet without applying this change to the current selection * * Example 2: app.changeToolColor({["color"] = 0xff0000, ["selection"] = true }) * changes the color of the current tool to red and also applies it to the current selection if there is one */ static int applib_changeToolColor(lua_State* L) { // discard any extra arguments passed in lua_settop(L, 1); luaL_checktype(L, 1, LUA_TTABLE); lua_getfield(L, 1, "selection"); /* either true or false, for changing selection color defaults to false*/ lua_getfield(L, 1, "tool"); /* "pen", "highlighter", "text" "select_rect", "select_object", "select_region" if omitted, current Tool is used */ lua_getfield(L, 1, "color"); // an RGB hex code defining the color // stack now has following: // 1 = {["color"] = 0xff00ff, ["tool"] = "PEN", ["selection"] = true} // -3 = true // -2 = "pen" // -1 = 0xff0077 Plugin* plugin = Plugin::getPluginFromLua(L); Control* ctrl = plugin->getControl(); ToolHandler* toolHandler = ctrl->getToolHandler(); bool selection = false; if (lua_isboolean(L, -3)) { selection = lua_toboolean(L, -3); } else if (!lua_isnil(L, -3)) { return luaL_error(L, "" "selection" " key should be a boolean value (or nil)"); } ToolType toolType = toolHandler->getToolType(); const char* toolStr = luaL_optstring(L, -2, nullptr); if (toolStr != nullptr) { toolType = toolTypeFromString(StringUtils::toLowerCase(toolStr)); } if (toolType == TOOL_NONE) { lua_pop(L, 3); return luaL_error(L, "tool \"%s\" is not valid or no tool has been selected", toolTypeToString(toolType).c_str()); } uint32_t color = 0x000000; if (lua_isinteger(L, -1)) { color = static_cast<uint32_t>(as_unsigned(lua_tointeger(L, -1))); if (color > 0xffffff) { std::stringstream msg; msg << "Color 0x" << std::hex << color << " is no valid RGB color."; return luaL_error(L, msg.str().c_str()); // luaL_error does not support %x for hex numbers } } else if (!lua_isnil(L, -1)) { return luaL_error(L, " " "color" " key should be an RGB hex code in the form 0xRRGGBB (or nil)"); } Tool& tool = toolHandler->getTool(toolType); if (tool.hasCapability(TOOL_CAP_COLOR)) { tool.setColor(Color(color | 0xff000000U)); ctrl->toolColorChanged(); if (selection) { ctrl->changeColorOfSelection(); } } else { return luaL_error(L, "tool \"%s\" has no color capability", toolTypeToString(toolType).c_str()); } return 0; } /** * Select Background Pdf Page for Current Page * First argument is an integer (page number) and the second argument is a boolean (isRelative) * specifying whether the page number is relative to the current pdf page or absolute * * @param pageNr integer page-nunmber * @param relative boolean should `pageNr` be interpreted relative? * * Example 1: app.changeBackgroundPdfPageNr(1, true) * changes the pdf page to the next one (relative mode) * * Example 2: app.changeBackgroundPdfPageNr(7, false) * changes the page background to the 7th pdf page (absolute mode) */ static int applib_changeBackgroundPdfPageNr(lua_State* L) { Plugin* plugin = Plugin::getPluginFromLua(L); size_t nr = as_unsigned(luaL_checkinteger(L, 1)); bool relative = true; if (lua_isboolean(L, 2)) { relative = lua_toboolean(L, 2); } Control* control = plugin->getControl(); Document* doc = control->getDocument(); PageRef const& page = control->getCurrentPage(); if (!page) { return luaL_error(L, "No page!"); } size_t selected = nr - 1; if (relative) { bool isPdf = page->getBackgroundType().isPdfPage(); if (isPdf) { selected = page->getPdfPageNr() + nr; } else { return luaL_error(L, "Current page has no pdf background, cannot use relative mode!"); } } if (selected < doc->getPdfPageCount()) { // no need to set a type, if we set the page number the type is also set page->setBackgroundPdfPageNr(selected); XojPdfPageSPtr p = doc->getPdfPage(selected); page->setSize(p->getWidth(), p->getHeight()); } else { return luaL_error(L, "Pdf page number %d does not exist!", selected + 1); } return 0; } /* * pushes an rectangle (width, height, x, y) to the lua stack as a new table * in most cases you'll want to do a * lua_newtable(L); // create rectangle table * before and a * lua_setfield(L, -2, "rectangleTable"); // add rectangle table to other table * after this function */ static void pushRectangleHelper(lua_State* L, xoj::util::Rectangle<double> rect) { lua_pushnumber(L, rect.width); lua_setfield(L, -2, "width"); lua_pushnumber(L, rect.height); lua_setfield(L, -2, "height"); lua_pushnumber(L, rect.x); lua_setfield(L, -2, "x"); lua_pushnumber(L, rect.y); lua_setfield(L, -2, "y"); } /** * Returns a table encoding all info on the chosen tool (active, pen, highlighter, eraser or text) in a Lua table. * * @param tool string tool to get the information for * @return {} info varies a lot depending on the tool * * The Lua table will be of one of the following shapes * * for pen: * { * "size" = string * "color" = integer * "filled" = bool * "fillOpacity" = integer (0 to 255) * "drawingType" = string * "lineStyle" = string * } * * See /src/control/ToolEnums.cpp for possible values of "size". * * for text: * { * "font" = { * name = string. * size = number * } * "color" = integer * } * * for active tool: * { * "type" = string * "size" = { * name = string. * value = number * } * "color" = integer * "fillOpacity" = integer (0 to 255) * "drawingType" = string * "lineStyle" = string * "thickness" = number * } * * See /src/control/ToolEnums.cpp for possible values of "type", "size", "drawingType" and "lineStyle". * * for eraser: * { * "type" = string * "size" = string * } * * See /src/control/ToolEnums.cpp for possible values of "type" and "size". * * for highlighter: * { * "size" = string * "color" = integer * "filled" = bool * "fillOpacity" = integer (0 to 255) * "drawingType" = string * } * * See /src/control/ToolEnums.cpp for possible values of "size". * * for seiection: * { * -- bounding box as drawn in the UI (includes padding on all sides) * "boundingBox" = { * "width" = number * "height" = number * "x" = number * "y" = number * } * -- same as "boundingBox" but the state before any transformation was applied * "originalBounds" = { * "width" = number * "height" = number * "x" = number * "y" = number * } * -- bounds used for snapping (doesn't include padding and doesn't account to line width) * -- for more information see https://github.com/xournalpp/xournalpp/pull/4359#issuecomment-1304395011 * "snappedBounds" = { * "width" = number * "height" = number * "x" = number * "y" = number * } * "rotation" = number * "isRotationSupported" = bool * } * * Example 1: local penInfo = app.getToolInfo("pen") * local size = penInfo["size"] * local opacity = penInfo["fillOpacity"] * * * Example 2: local font = app.getToolInfo("text")["font"] * local fontname = font["name"] * local fontsize = font["size"] * * Example 3: local color = app.getToolInfo("text")["color"] * local red = color >> 16 & 0xff * local green = color >> 8 & 0xff * local blue = color & 0xff * * Example 4: local activeToolInfo = app.getToolInfo("active") * local thickness = activeToolInfo["thickness"] * local drawingType = activeToolInfo["drawingType"] * * Example 5: local eraserInfo = app.getToolInfo("eraser") * local type = eraserInfo["type"] * local size = eraserInfo["size"] * local sizeName = size["name"] * local thickness = size["value"] * * Example 6: local highlighterInfo = app.getToolInfo("highlighter") * local sizeName = highlighterInfo["size"]["name"] * local opacity = highlighterInfo["fillOpacity"] * * Example 7: local selectionInfo = app.getToolInfo("selection") * local rotation = selectionInfo["rotation"] * local boundingX = selectionInfo["boundingBox"]["x"] * local snappedBoundsWidth = selectionInfo["snappedBounds"]["width"] */ static int applib_getToolInfo(lua_State* L) { Plugin* plugin = Plugin::getPluginFromLua(L); Control* control = plugin->getControl(); ToolHandler* toolHandler = control->getToolHandler(); // discard any extra arguments passed in lua_settop(L, 1); luaL_checktype(L, 1, LUA_TSTRING); const char* mode = luaL_checkstring(L, -1); lua_newtable(L); // return table // stack now has following: // 1 = mode // -1 = table to be returned if (strcmp(mode, "active") == 0) { std::string toolType = toolTypeToString(toolHandler->getToolType()); std::string toolSize = toolSizeToString(toolHandler->getSize()); double thickness = toolHandler->getThickness(); Color color = toolHandler->getColor(); int fillOpacity = toolHandler->getFill(); std::string drawingType = drawingTypeToString(toolHandler->getDrawingType()); std::string lineStyle = StrokeStyle::formatStyle(toolHandler->getLineStyle()); lua_pushstring(L, toolType.c_str()); // value lua_setfield(L, -2, "type"); // insert lua_newtable(L); // beginning of "size" table lua_pushstring(L, toolSize.c_str()); // value lua_setfield(L, -2, "name"); // insert lua_pushnumber(L, thickness); // value lua_setfield(L, -2, "value"); // insert lua_setfield(L, -2, "size"); // end of "size" table lua_pushinteger(L, as_signed(uint32_t(color) & 0xffffffU)); // value lua_setfield(L, -2, "color"); // insert lua_pushinteger(L, fillOpacity); // value lua_setfield(L, -2, "fillOpacity"); // insert lua_pushstring(L, drawingType.c_str()); // value lua_setfield(L, -2, "drawingType"); // insert lua_pushstring(L, lineStyle.c_str()); // value lua_setfield(L, -2, "lineStyle"); // insert } else if (strcmp(mode, "pen") == 0) { std::string size = toolSizeToString(toolHandler->getPenSize()); double thickness = toolHandler->getToolThickness(TOOL_PEN)[toolSizeFromString(size)]; int fillOpacity = toolHandler->getPenFill(); bool filled = toolHandler->getPenFillEnabled(); Tool& tool = toolHandler->getTool(TOOL_PEN); Color color = tool.getColor(); std::string drawingType = drawingTypeToString(tool.getDrawingType()); std::string lineStyle = StrokeStyle::formatStyle(tool.getLineStyle()); lua_newtable(L); // beginning of "size" table lua_pushstring(L, size.c_str()); // value lua_setfield(L, -2, "name"); // insert lua_pushnumber(L, thickness); // value lua_setfield(L, -2, "value"); // insert lua_setfield(L, -2, "size"); // end of "size" table lua_pushinteger(L, as_signed(uint32_t(color) & 0xffffffU)); // value lua_setfield(L, -2, "color"); // insert lua_pushstring(L, drawingType.c_str()); // value lua_setfield(L, -2, "drawingType"); // insert lua_pushstring(L, lineStyle.c_str()); // value lua_setfield(L, -2, "lineStyle"); // insert lua_pushboolean(L, filled); // value lua_setfield(L, -2, "filled"); // insert lua_pushinteger(L, fillOpacity); // value lua_setfield(L, -2, "fillOpacity"); // insert } else if (strcmp(mode, "highlighter") == 0) { std::string size = toolSizeToString(toolHandler->getHighlighterSize()); double thickness = toolHandler->getToolThickness(TOOL_HIGHLIGHTER)[toolSizeFromString(size)]; int fillOpacity = toolHandler->getHighlighterFill(); bool filled = toolHandler->getHighlighterFillEnabled(); Tool& tool = toolHandler->getTool(TOOL_HIGHLIGHTER); Color color = tool.getColor(); std::string drawingType = drawingTypeToString(tool.getDrawingType()); lua_newtable(L); // beginning of "size" table lua_pushstring(L, size.c_str()); // value lua_setfield(L, -2, "name"); // insert lua_pushnumber(L, thickness); // value lua_setfield(L, -2, "value"); // insert lua_setfield(L, -2, "size"); // end of "size" table lua_pushinteger(L, as_signed(uint32_t(color) & 0xffffffU)); // value lua_setfield(L, -2, "color"); // insert lua_pushstring(L, drawingType.c_str()); // value lua_setfield(L, -2, "drawingType"); // insert lua_pushboolean(L, filled); // value lua_setfield(L, -2, "filled"); // insert lua_pushinteger(L, fillOpacity); // value lua_setfield(L, -2, "fillOpacity"); // insert } else if (strcmp(mode, "eraser") == 0) { std::string type = eraserTypeToString(toolHandler->getEraserType()); std::string size = toolSizeToString(toolHandler->getEraserSize()); double thickness = toolHandler->getToolThickness(ToolType::TOOL_ERASER)[toolSizeFromString(size)]; lua_pushstring(L, type.c_str()); // value lua_setfield(L, -2, "type"); // insert lua_newtable(L); // beginning of "size" table lua_pushstring(L, size.c_str()); // value lua_setfield(L, -2, "name"); // insert lua_pushnumber(L, thickness); // value lua_setfield(L, -2, "value"); // insert lua_setfield(L, -2, "size"); // end of "size" table } else if (strcmp(mode, "text") == 0) { Settings* settings = control->getSettings(); XojFont& font = settings->getFont(); std::string fontname = font.getName(); double size = font.getSize(); Tool& tool = toolHandler->getTool(TOOL_TEXT); Color color = tool.getColor(); lua_newtable(L); // font table lua_pushstring(L, fontname.c_str()); // value lua_setfield(L, -2, "name"); // insert lua_pushnumber(L, size); // value lua_setfield(L, -2, "size"); // insert lua_setfield(L, -2, "font"); // insert font table lua_pushinteger(L, as_signed(uint32_t(color) & 0xffffffU)); // value lua_setfield(L, -2, "color"); // insert // results in {font={name="fontname", size=0}, color=0x0} } else if (strcmp(mode, "selection") == 0) { auto sel = control->getWindow()->getXournal()->getSelection(); if (!sel) { return luaL_error(L, "There is no selection! "); } auto rect = sel->getRect(); lua_pushnumber(L, sel->getRotation()); lua_setfield(L, -2, "rotation"); lua_pushboolean(L, sel->isRotationSupported()); lua_setfield(L, -2, "isRotationSupported"); lua_newtable(L); // create originalBounds table pushRectangleHelper(L, sel->getOriginalBounds()); lua_setfield(L, -2, "originalBounds"); // add originalBounds table to return table lua_newtable(L); // create snappedBounds table pushRectangleHelper(L, sel->getSnappedBounds()); lua_setfield(L, -2, "snappedBounds"); // add snappedBounds table to return table lua_newtable(L); // create boundingBox table pushRectangleHelper(L, rect); lua_setfield(L, -2, "boundingBox"); // add boundingBox table to return table } return 1; } /** * Returns a table encoding the document structure in a Lua table. * * @return {pages:{pageWidth:number, pageHeight:number, isAnnotated:boolean, pageTypeFormat:string, * pageTypeConfig:string, backgroundColor:integer, pdfBackgroundPageNo:integer, layers:{isVisible:boolean, * isAnnotated:boolean}[], currentLayer:integer}[], currentPage:integer, pdfBackgroundFilename:string, * xoppFilename:string} * * The shape of the returned Lua table will be: * { * "pages" = { * { * "pageWidth" = number, * "pageHeight" = number, * "isAnnotated" = bool, * "pageTypeFormat" = string, * "pageTypeConfig" = string, * "backgroundColor" = integer, * "pdfBackgroundPageNo" = integer (0, if there is no pdf background page), * "layers" = { * [0] = { * "isVisible" = bool * }, * [1] = { * "isVisible" = bool, * "isAnnotated" = bool * }, * ... * }, * "currentLayer" = integer * }, * ... * } * "currentPage" = integer, * "pdfBackgroundFilename" = string (empty if there is none) * "xoppFilename" = string (empty if there is none) * } * * Example: local docStructure = app.getDocumentStructure() */ static int applib_getDocumentStructure(lua_State* L) { Plugin* plugin = Plugin::getPluginFromLua(L); Control* control = plugin->getControl(); Document* doc = control->getDocument(); lua_newtable(L); lua_pushliteral(L, "pages"); lua_newtable(L); // beginning of pages table // stack now has following: // -2 = table to be returned // -1 = pages table/array // add pages for (size_t p = 1; p <= doc->getPageCount(); ++p) { auto page = doc->getPage(p - 1); lua_pushinteger(L, as_signed(p)); // key of the page lua_newtable(L); // beginning of table for page p lua_pushnumber(L, page->getWidth()); // value lua_setfield(L, -2, "pageWidth"); // insert lua_pushnumber(L, page->getHeight()); // value lua_setfield(L, -2, "pageHeight"); // insert lua_pushboolean(L, page->isAnnotated()); // value lua_setfield(L, -2, "isAnnotated"); // insert PageType pt = page->getBackgroundType(); std::string pageTypeFormat = PageTypeHandler::getStringForPageTypeFormat(pt.format); lua_pushstring(L, pageTypeFormat.c_str()); // value lua_setfield(L, -2, "pageTypeFormat"); // insert lua_pushstring(L, pt.config.c_str()); // value lua_setfield(L, -2, "pageTypeConfig"); // insert lua_pushinteger(L, as_signed(uint32_t(page->getBackgroundColor()) & 0xffffffU)); // value lua_setfield(L, -2, "backgroundColor"); // insert lua_pushinteger(L, as_signed(page->getPdfPageNr()) + 1); // value lua_setfield(L, -2, "pdfBackgroundPageNo"); // insert lua_newtable(L); // beginning of layers table // add background layer lua_pushinteger(L, 0); // key of the layer lua_newtable(L); // beginning of table for background layer lua_pushboolean(L, page->isLayerVisible(0U)); // value lua_setfield(L, -2, "isVisible"); // insert lua_pushstring(L, page->getBackgroundName().c_str()); // value lua_setfield(L, -2, "name"); // insert lua_settable(L, -3); // end of table for background layer // add (non-background) layers int currLayer = 0; for (auto l: *page->getLayers()) { lua_pushinteger(L, ++currLayer); // key of the layer lua_newtable(L); // beginning of table for layer l lua_pushstring(L, l->getName().c_str()); // value lua_setfield(L, -2, "name"); // insert lua_pushboolean(L, l->isVisible()); // value lua_setfield(L, -2, "isVisible"); // insert lua_pushboolean(L, l->isAnnotated()); // value lua_setfield(L, -2, "isAnnotated"); // insert lua_settable(L, -3); // end of table for layer l } lua_setfield(L, -2, "layers"); // end of layers table lua_pushinteger(L, as_signed(page->getSelectedLayerId())); // value lua_setfield(L, -2, "currentLayer"); // insert lua_settable(L, -3); // end of table for page p } lua_settable(L, -3); // end of pages table lua_pushinteger(L, as_signed(control->getCurrentPageNo()) + 1); // value lua_setfield(L, -2, "currentPage"); // insert lua_pushstring(L, doc->getPdfFilepath().string().c_str()); // value lua_setfield(L, -2, "pdfBackgroundFilename"); // insert lua_pushstring(L, doc->getFilepath().string().c_str()); // value lua_setfield(L, -2, "xoppFilename"); // insert return 1; } /** * Scrolls to the page specified relatively or absolutely (by default) * The page number is clamped to the range between the first and last page * * @param page integer (automatically clamped) * @param relative boolean * * Example 1: app.scrollToPage(1, true) * scrolls to the next page (relative mode) * * Example 2: app.scrollToPage(10) * scrolls to page 10 (absolute mode) **/ static int applib_scrollToPage(lua_State* L) { Plugin* plugin = Plugin::getPluginFromLua(L); Control* control = plugin->getControl(); int val = static_cast<int>(luaL_checkinteger(L, 1)); bool relative = false; if (lua_isboolean(L, 2)) { relative = lua_toboolean(L, 2); } int page = (relative) ? static_cast<int>(control->getCurrentPageNo()) + val : val - 1; const int first = 0; const int last = static_cast<int>(control->getDocument()->getPageCount()) - 1; control->getScrollHandler()->scrollToPage(static_cast<size_t>(std::clamp(page, first, last))); return 0; } /** * Scrolls to the position on the selected page specified relatively (by default) or absolutely * * @param x number * @param y number * @param relative boolean * * Example 1: app.scrollToPos(20,10) * scrolls 20pt right and 10pt down (relative mode) * * Example 2: app.scrollToPos(200, 50, false) * scrolls to page position 200pt right and 50pt down from the left page corner (absolute mode) **/ static int applib_scrollToPos(lua_State* L) { Plugin* plugin = Plugin::getPluginFromLua(L); Control* control = plugin->getControl(); Layout* layout = control->getWindow()->getLayout(); double dx = luaL_checknumber(L, 1); double dy = luaL_checknumber(L, 2); bool relative = true; if (lua_isboolean(L, 3)) { relative = lua_toboolean(L, 3); } if (relative) { layout->scrollRelative(dx, dy); } else { layout->scrollAbs(dx, dy); } return 0; } /** * Obtains the label of the specified page in the pdf background. * * @param page integer * @return string|nil Returns the label on success and (nil, message) if page number is out of range. * @return string * * Example 1: local label = app.getPageLabel(10) ' obtains the page label of page 10 in the background pdf **/ static int applib_getPageLabel(lua_State* L) { const Plugin* plugin = Plugin::getPluginFromLua(L); const Control* control = plugin->getControl(); const XojPdfDocument& doc = control->getDocument()->getPdfDocument(); const size_t pagenr = static_cast<size_t>(luaL_checkinteger(L, 1)) - 1; if (pagenr >= doc.getPageCount()) { lua_pushnil(L); lua_pushfstring(L, "page nr %zu is out of range", pagenr); return 2; } std::string label = doc.getPage(pagenr)->getPageLabel(); lua_pushlstring(L, label.c_str(), label.length()); return 1; } /** * Sets the current page as indicated (without scrolling) * The page number passed is clamped to the range between first page and last page * * @param pageNr integer (automatically clamped) * * Example: app.setCurrentPage(1) * makes the first page the new current page **/ static int applib_setCurrentPage(lua_State* L) { Plugin* plugin = Plugin::getPluginFromLua(L); Control* control = plugin->getControl(); size_t pageId = as_unsigned(luaL_checkinteger(L, 1)); const size_t first = 1; const size_t last = control->getDocument()->getPageCount(); control->firePageSelected(std::clamp(pageId, first, last) - 1); return 0; } /** * Sets the width and height of the current page in pt = 1/72 inch either relatively or absolutely (by default) * * @param width number * @param height number * @param relative boolean * * Example 1: app.setPageSize(595.275591, 841.889764) * makes the current page have standard (A4 paper) width and height (absolute mode) * * Example 2: app.setPageSize(0, 14.17*6, true) * adds 14.17*6 pt = 3cm to the height of the page (relative mode) **/ static int applib_setPageSize(lua_State* L) { Plugin* plugin = Plugin::getPluginFromLua(L); Control* control = plugin->getControl(); Document* doc = control->getDocument(); PageRef const& page = control->getCurrentPage(); if (!page) { return luaL_error(L, "No page!"); } double width = luaL_checknumber(L, 1); double height = luaL_checknumber(L, 2); bool relative = false; if (lua_isboolean(L, 3)) { relative = lua_toboolean(L, 3); } if (relative) { width += page->getWidth(); height += page->getHeight(); } if (width > 0 && height > 0) { doc->lock(); Document::setPageSize(page, width, height); doc->unlock(); } size_t pageNo = doc->indexOf(page); if (pageNo != npos && pageNo < doc->getPageCount()) { control->firePageSizeChanged(pageNo); } return 0; } /** * Sets the current layer of the current page as indicated and updates visibility if specified (by default it does not) * Displays an error message, if the selected layer does not exist * * @param layerNr integer number of the (non-background) layer * @param change_visibility boolean true -> makes all layers up to the selected one visible, all others invisible * * Example 1: app.setCurrentLayer(2, true) * makes the second (non-background) layer the current layer and makes layers 1, 2 and the background layer visible, the *others hidden * * Example 2: app.setCurrentLayer(2, false) * makes the second (non-background) layer the current layer and does not change visibility **/ static int applib_setCurrentLayer(lua_State* L) { Plugin* plugin = Plugin::getPluginFromLua(L); Control* control = plugin->getControl(); PageRef const& page = control->getCurrentPage(); if (!page) { return luaL_error(L, "No page!"); } size_t layerCount = page->getLayerCount(); size_t layerId = as_unsigned(luaL_checkinteger(L, 1)); if (layerId > layerCount) { return luaL_error(L, "No layer with layer ID %d", layerId); } bool update = false; if (lua_isboolean(L, 2)) { update = lua_toboolean(L, 2); } control->getLayerController()->switchToLay(layerId, update); return 0; } /** * Sets the visibility of the current layer * * @param visible boolean * * Example: app.setLayerVisibility(true) * makes the current layer visible */ static int applib_setLayerVisibility(lua_State* L) { Plugin* plugin = Plugin::getPluginFromLua(L); Control* control = plugin->getControl(); bool enabled = true; if (lua_isboolean(L, 1)) { enabled = lua_toboolean(L, 1); } auto layerId = control->getCurrentPage()->getSelectedLayerId(); control->getLayerController()->setLayerVisible(layerId, enabled); return 0; } /** * Sets currently selected layer's name. * * @param name string * * Example: app.setCurrentLayerName("Custom name 1") * Changes current layer name to "Custom name 1" **/ static int applib_setCurrentLayerName(lua_State* L) { Plugin* plugin = Plugin::getPluginFromLua(L); Control* control = plugin->getControl(); if (lua_isstring(L, 1)) { auto name = lua_tostring(L, 1); control->getLayerController()->setCurrentLayerName(name); } return 0; } /** * Sets background name. * * @param name string * * Example: app.setBackgroundName("Custom name 1") * Changes background name to "Custom name 1" **/ static int applib_setBackgroundName(lua_State* L) { Plugin* plugin = Plugin::getPluginFromLua(L); Control* control = plugin->getControl(); PageRef const& page = control->getCurrentPage(); if (!page) { return luaL_error(L, "No page!"); } if (lua_isstring(L, 1)) { auto name = lua_tostring(L, 1); page->setBackgroundName(name); } return 0; } /** * Scales all text elements of the current layer by the given scale factor. * This means the font sizes get scaled, wheras the position of the left upper corner * of the bounding box remains unchanged * * @param factor number * * Example: app.scaleTextElements(2.3) * scales all text elements on the current layer with factor 2.3 **/ static int applib_scaleTextElements(lua_State* L) { Plugin* plugin = Plugin::getPluginFromLua(L); Control* control = plugin->getControl(); double f = luaL_checknumber(L, 1); control->clearSelectionEndText(); const auto& elements = control->getCurrentPage()->getSelectedLayer()->getElements(); for (auto const& e: elements) { if (e->getType() == ELEMENT_TEXT) { Text* t = static_cast<Text*>(e.get()); t->scale(t->getX(), t->getY(), f, f, 0.0, false); } } return 0; } /** * Gets the display DPI. * * @return integer displayDpi dpi of the display * * Example: app.getDisplayDpi() **/ static int applib_getDisplayDpi(lua_State* L) { Plugin* plugin = Plugin::getPluginFromLua(L); Control* control = plugin->getControl(); int dpi = control->getSettings()->getDisplayDpi(); lua_pushinteger(L, dpi); return 1; } /** * Gets the current zoom. * * @return double current zoom level * * Example: app.getZoom() **/ static int applib_getZoom(lua_State* L) { Plugin* plugin = Plugin::getPluginFromLua(L); Control* control = plugin->getControl(); double zoom = control->getZoomControl()->getZoomReal(); lua_pushnumber(L, zoom); return 1; } /** * Sets the current zoom. * * @param zoom number * * Example: app.setZoom(2.5) * Changes zoom level to 2.5 **/ static int applib_setZoom(lua_State* L) { Plugin* plugin = Plugin::getPluginFromLua(L); Control* control = plugin->getControl(); ZoomControl* zoomControl = control->getZoomControl(); double newZoom = luaL_checknumber(L, 1) * zoomControl->getZoom100Value(); zoomControl->setZoomFitMode(false); zoomControl->startZoomSequence(); zoomControl->zoomSequenceChange(newZoom, false); zoomControl->endZoomSequence(); return 0; } /** * Exports the current document as a pdf or as a svg or png image * * @param opts {outputFile:string, range:string, background:string, progressiveMode: boolean} * * Example 1: * app.export({["outputFile"] = "Test.pdf", ["range"] = "2-5; 7", ["background"] = "none", ["progressiveMode"] = true}) * uses progressiveMode, so for each page of the document, instead of rendering one PDF page, the page layers are * rendered one by one to produce as many pages as there are layers. * * Example 2: * app.export({["outputFile"] = "Test.svg", ["range"] = "3-", ["background"] = "unruled"}) * * Example 3: * app.export({["outputFile"] = "Test.png", ["layerRange"] = "1-2", ["background"] = "all", ["pngWidth"] = 800}) **/ static int applib_export(lua_State* L) { Plugin* plugin = Plugin::getPluginFromLua(L); Control* control = plugin->getControl(); Document* doc = control->getDocument(); // discard any extra arguments passed in lua_settop(L, 1); luaL_checktype(L, 1, LUA_TTABLE); lua_getfield(L, 1, "outputFile"); lua_getfield(L, 1, "range"); lua_getfield(L, 1, "layerRange"); lua_getfield(L, 1, "background"); lua_getfield(L, 1, "progressiveMode"); lua_getfield(L, 1, "pngDpi"); lua_getfield(L, 1, "pngWidth"); lua_getfield(L, 1, "dpiHeight"); // stack now has following: // 1 = param table // -8 = outputFile // -7 = range // -6 = layerRange // -5 = background // -4 = progressiveMode // -3 = pngDpi // -2 = pngWidth // -1 = dpiHeight const char* outputFile = luaL_optstring(L, -8, nullptr); const char* range = luaL_optstring(L, -7, nullptr); const char* layerRange = luaL_optstring(L, -6, nullptr); const char* background = luaL_optstring(L, -5, "all"); bool progressiveMode = lua_toboolean(L, -4); // true unless nil or false int pngDpi = static_cast<int>(luaL_optinteger(L, -3, -1)); int pngWidth = static_cast<int>(luaL_optinteger(L, -2, -1)); int pngHeight = static_cast<int>(luaL_optinteger(L, -1, -1)); ExportBackgroundType bgType = EXPORT_BACKGROUND_ALL; if (strcmp(background, "unruled") == 0) { bgType = EXPORT_BACKGROUND_UNRULED; } else if (strcmp(background, "none") == 0) { bgType = EXPORT_BACKGROUND_NONE; } if (outputFile == nullptr) { return luaL_error(L, "Missing output file!"); } fs::path file = fs::path(outputFile); auto extension = file.extension(); if (extension == ".pdf") { ExportHelper::exportPdf(doc, outputFile, range, layerRange, bgType, progressiveMode); } else if (extension == ".svg" || extension == ".png") { ExportHelper::exportImg(doc, outputFile, range, layerRange, pngDpi, pngWidth, pngHeight, bgType); } return 0; } /** * Opens a file and by default asks the user what to do with the old document. * Returns true when successful, false otherwise. * * @param path string * @param pageNr integer scroll to this page (defaults to 1) * @param oldDocument boolean don't ask weather to save the old document? (defaults to false) * @return boolean success * * Example 1: local success = app.openFile("home/username/bg.pdf") * asks what to do with the old document and loads the file afterwards, scrolls to top * * Example 2: local sucess = app.openFile("home/username/paintings.xopp", 3, true) * opens the file, scrolls to the 3rd page and does not ask to save the old document */ static int applib_openFile(lua_State* L) { Plugin* plugin = Plugin::getPluginFromLua(L); Control* control = plugin->getControl(); const char* filename = luaL_checkstring(L, 1); int scrollToPage = 0; // by default scroll to the same page like last time if (lua_isinteger(L, 2)) { scrollToPage = static_cast<int>(lua_tointeger(L, 2)); } bool forceOpen = false; // by default asks the user if (lua_isboolean(L, 3)) { forceOpen = lua_toboolean(L, 3); } control->openFile(fs::path(filename), [](bool) {}, scrollToPage - 1, forceOpen); lua_pushboolean(L, true); // Todo replace with callback return 1; } /** * Adds images from the provided paths or the provided image data on the current page on the current layer. * * @param opts {images:{path:string, data:string, x:number, y:number, maxHeight:number, maxWidth:number, * aspectRatio:boolean}[], allowUndoRedoAction:string} * * Global parameters: * - images table: array of image-parameter-tables * - allowUndoRedoAction string: Decides how the change gets introduced into the undoRedo action list "individual", * "grouped" or "none" * * Parameters per image: * - path string: filepath to the image * or * - data string: (file) content of the image (exactly one of path and data should be specified) * - x number: x-Coordinate where to place the left upper corner of the image (default: 0) * - y number: y-Coordinate where to place the left upper corner of the image (default: 0) * scaling options: * - maxWidth integer: sets the width of the image in pixels. If that is too large for the page the image gets scaled * down keeping the aspect-ratio provided by maxWidth/maxHeight (default: -1) * - maxHeight integer: sets the height of the image in pixels. If that is too large for the page the image gets scaled * down keeping the aspect-ratio provided by maxWidth/maxHeight (default: -1) * - aspectRatio boolean: should the image be scaled in the other dimension to preserve the aspect ratio? Is only set * to false if the parameter is false, nil leads to the default value of true (default: true) * - scale number: factor to apply to the both dimensions in the end after setting width/height (with/without * keeping aspect ratio) (default: 1) * * Note about scaling: * If the maxHeight-, the maxWidth- as well as the aspectRatio-parameter are given, the image will fit into the * rectangle specified with maxHeight/maxWidth. To preserve the aspect ratio, one dimension will be smaller than * specified. Still, the scale parameter is applied after this width/height scaling and if after that the dimensions are * too large for the page, the image still gets scaled down afterwards. * * Returns as many values as images were passed. A nil value represents success, while * on error the value corresponding to the image will be a string with the error message. * If the parameters don't fit at all, a real lua error might be thrown immediately. * * Example 1: app.addImages{images={{path="/media/data/myImg.png", x=10, y=20, scale=2}, * {path="/media/data/myImg2.png", maxHeight=300, aspectRatio=true}}, * allowUndoRedoAction="grouped", * } * Example 2: app.addImages{images={{data="<binary image data>", x=100, y=200, maxHeight=300, maxWidth=400}}} */ static int applib_addImages(lua_State* L) { Plugin* plugin = Plugin::getPluginFromLua(L); Control* control = plugin->getControl(); // Discard any extra arguments passed in lua_settop(L, 1); luaL_checktype(L, 1, LUA_TTABLE); lua_getfield(L, 1, "images"); if (!lua_istable(L, 2)) { return luaL_error(L, "Missing image table!"); } auto cntParams = static_cast<int>(lua_rawlen(L, 2)); std::vector<Element*> images{}; for (int imgParam{1}; imgParam <= cntParams; imgParam++) { lua_pushinteger(L, imgParam); lua_gettable(L, 2); luaL_checktype(L, -1, LUA_TTABLE); lua_getfield(L, -1, "path"); lua_getfield(L, -2, "data"); lua_getfield(L, -3, "x"); lua_getfield(L, -4, "y"); lua_getfield(L, -5, "maxWidth"); lua_getfield(L, -6, "maxHeight"); lua_getfield(L, -7, "scale"); lua_getfield(L, -8, "aspectRatio"); // stack now has the following: // 1 = global params table // -9 = current img-params table // -8 = filepath // -7 = image data // -6 = x coordinate // -5 = y coordinate // -4 = maxWidth (in pixel) // -3 = maxHeight (in pixel) // -2 = scale // -1 = aspectRatio // fetch the parameters and check for validity. If parameter is invalid -> hard error double x = luaL_optnumber(L, -6, 0); double y = luaL_optnumber(L, -5, 0); int maxHeightParam = static_cast<int>(luaL_optinteger(L, -3, -1)); if (maxHeightParam <= 0 && maxHeightParam != -1) { return luaL_error(L, "Invalid height given, must be positive integer or -1 to deactivate manual setting."); } int maxWidthParam = static_cast<int>(luaL_optinteger(L, -4, -1)); if (maxWidthParam <= 0 && maxWidthParam != -1) { return luaL_error(L, "Invalid width given, must be positive integer or -1 to deactivate manual setting."); } double scale = luaL_optnumber(L, -2, 1); if (scale <= 0) { return luaL_error(L, "Invalid scale given, must be a positive number."); } bool aspectRatio{true}; if (!lua_isnil(L, -1)) { // use the typical lua version of booleans (everything different than false (any set value) is true) aspectRatio = lua_toboolean(L, -1); } const char* path = luaL_optstring(L, -8, nullptr); size_t dataLen = 0; const char* data = luaL_optlstring(L, -7, nullptr, &dataLen); if (!path && !data) { return luaL_error(L, "no 'path' parameter and no image 'data' was provided."); } if (path && data) { return luaL_error(L, "both 'path' parameter and image 'data' were provided. Only one should be specified. "); } std::unique_ptr<Image> img; if (path) { fs::path p(path); if (p.empty() || !fs::exists(p)) { lua_pop(L, 8); // pop the params we fetched from the global param-table from the stack lua_pushfstring(L, "Error: file '%s' does not exist.", path); // soft error continue; } img = ImageHandler::createImageFromFile(p); if (!img) { lua_pop(L, 8); // pop the params we fetched from the global param-table from the stack lua_pushfstring(L, "Error: creating the image (%s) failed.", path); // soft error continue; } } else { // data was provided instead img = std::make_unique<Image>(); img->setImage(std::string(data, dataLen)); img->getImage(); // render image first to get the proper width and height } auto [width, height] = img->getImageSize(); img->setX(x); img->setY(y); // apply width/height parameter if (maxWidthParam != -1 && maxHeightParam != -1) { // both width and height are set if (aspectRatio) { double scale_y{static_cast<double>(maxHeightParam) / static_cast<double>(height)}; double scale_x{static_cast<double>(maxWidthParam) / static_cast<double>(width)}; double scale{std::min(scale_y, scale_x)}; height = round_cast<int>(height * scale); width = round_cast<int>(width * scale); } else { width = maxWidthParam; height = maxHeightParam; } } else if (maxWidthParam != -1 && maxHeightParam == -1) { // maxHeight is set if (aspectRatio) { height = round_cast<int>(static_cast<double>(height) / static_cast<double>(width) * maxWidthParam); } width = maxWidthParam; } else if (maxHeightParam != -1 && maxWidthParam == -1) { // maxWidth is set if (aspectRatio) { width = round_cast<int>(static_cast<double>(width) / static_cast<double>(height) * maxHeightParam); } height = maxHeightParam; } // apply scale option width = round_cast<int>(width * scale); height = round_cast<int>(height * scale); PageRef page = control->getCurrentPage(); // scale down keeping the current aspect ratio after the manual scaling to fit the image on the page // if the image already fits on the screen, no other scaling is applied here // already sets width/height in the image ImageHandler::automaticScaling(*img, page); // store the image to later build the undo/redo action chain images.push_back(img.get()); lua_pop(L, 8); // pop the params we fetched from the global param-table from the stack bool succ = ImageHandler::addImageToDocument(std::move(img), page, control, false); if (!succ) { lua_pushfstring(L, "Error: Inserting the image (%s) failed.", path); // soft error } lua_pushnil(L); } // Check how the user wants to handle undoing lua_getfield(L, 1, "allowUndoRedoAction"); const char* allowUndoRedoAction = luaL_optstring(L, -1, "grouped"); lua_pop(L, 1); handleUndoRedoActionHelper(L, control, allowUndoRedoAction, images); return cntParams; } /** * Puts a Lua Table of the Images (from the selection tool / selected layer) onto the stack. * Is inverse to app.addImages * * @param type string "selection" or "layer" * @return {x:number, y:number, width:number, height:number, data:string, format:string, imageWidth:number, * imageHeight:number}[] images * * Required argument: type ("selection" or "layer") * * Example: local images = app.getImages("selection") * * return value: * { * { * ["x"] = number, * ["y"] = number, * ["width"] = number, (width when inserted into Xournal++) * ["height"] = number, (height when inserted into Xournal++) * ["data"] = string, * ["format"] = string, * ["imageWidth"] = integer, * ["imageHeight"] = integer, * }, * { * ... * }, * ... * } */ static int applib_getImages(lua_State* L) { Plugin* plugin = Plugin::getPluginFromLua(L); std::string type = luaL_checkstring(L, 1); Control* control = plugin->getControl(); // Discard any extra arguments passed in lua_settop(L, 1); const auto& [err, elements] = getElementsFromHelper(control, type); if (err.has_value()) { return luaL_error(L, err.value().c_str()); } lua_newtable(L); // create table of all images int currImageNo = 0; for (Element* e: elements) { if (e->getType() == ELEMENT_IMAGE) { auto* im = static_cast<Image*>(e); lua_pushinteger(L, ++currImageNo); // index for later (settable) lua_newtable(L); // create table for current image // "x": number lua_pushnumber(L, im->getX()); lua_setfield(L, -2, "x"); // "y": number lua_pushnumber(L, im->getY()); lua_setfield(L, -2, "y"); // "width": number lua_pushnumber(L, im->getElementWidth()); lua_setfield(L, -2, "width"); // "height": number lua_pushnumber(L, im->getElementHeight()); lua_setfield(L, -2, "height"); // data: string (can be optimized via lual_Buffer) lua_pushlstring(L, reinterpret_cast<const char*>(im->getRawData()), im->getRawDataLength()); lua_setfield(L, -2, "data"); // format: string lua_pushstring(L, gdk_pixbuf_format_get_name(im->getImageFormat())); lua_setfield(L, -2, "format"); std::pair<int, int> imageSize = im->getImageSize(); // image width: integer lua_pushinteger(L, imageSize.first); lua_setfield(L, -2, "imageWidth"); // image height: integer lua_pushinteger(L, imageSize.second); lua_setfield(L, -2, "imageHeight"); lua_settable(L, -3); // add image to table } } return 1; } /* * The full Lua Plugin API. * See above for example usage of each function. */ static const luaL_Reg applib[] = {{"msgbox", applib_msgbox}, // Todo(gtk4) remove this deprecated function {"openDialog", applib_openDialog}, {"getPageLabel", applib_getPageLabel}, {"glib_rename", applib_glib_rename}, {"saveAs", applib_saveAs}, // Todo(gtk4) remove this deprecated function {"fileDialogSave", applib_fileDialogSave}, {"registerUi", applib_registerUi}, {"uiAction", applib_uiAction}, {"sidebarAction", applib_sidebarAction}, {"layerAction", applib_layerAction}, {"changeToolColor", applib_changeToolColor}, {"getColorPalette", applib_getColorPalette}, {"changeCurrentPageBackground", applib_changeCurrentPageBackground}, {"changeBackgroundPdfPageNr", applib_changeBackgroundPdfPageNr}, {"getToolInfo", applib_getToolInfo}, {"getSidebarPageNo", applib_getSidebarPageNo}, {"setSidebarPageNo", applib_setSidebarPageNo}, {"getDocumentStructure", applib_getDocumentStructure}, {"scrollToPage", applib_scrollToPage}, {"scrollToPos", applib_scrollToPos}, {"setCurrentPage", applib_setCurrentPage}, {"setPageSize", applib_setPageSize}, {"setCurrentLayer", applib_setCurrentLayer}, {"setLayerVisibility", applib_setLayerVisibility}, {"setCurrentLayerName", applib_setCurrentLayerName}, {"setBackgroundName", applib_setBackgroundName}, {"scaleTextElements", applib_scaleTextElements}, {"getDisplayDpi", applib_getDisplayDpi}, {"getZoom", applib_getZoom}, {"setZoom", applib_setZoom}, {"export", applib_export}, {"addStrokes", applib_addStrokes}, {"addSplines", applib_addSplines}, {"addImages", applib_addImages}, {"addTexts", applib_addTexts}, {"getFilePath", applib_getFilePath}, // Todo(gtk4) remove this deprecated function {"fileDialogOpen", applib_fileDialogOpen}, {"refreshPage", applib_refreshPage}, {"getStrokes", applib_getStrokes}, {"getImages", applib_getImages}, {"getTexts", applib_getTexts}, {"openFile", applib_openFile}, // Placeholder // {"MSG_BT_OK", nullptr}, {nullptr, nullptr}}; /** * Open application Library */ inline int luaopen_app(lua_State* L) { luaL_newlib(L, applib); // lua_pushnumber(L, MSG_BT_OK); // lua_setfield(L, -2, "MSG_BT_OK"); return 1; }
111,419
C++
.h
2,630
35.957414
120
0.604156
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,826
ActionBackwardCompatibilityLayer.h
xournalpp_xournalpp/src/core/plugin/ActionBackwardCompatibilityLayer.h
/* * Xournal++ * * Compat. layer for mapping old plugin action triggers to new actions * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #include "config-features.h" // for ENABLE_PLUGINS #ifdef ENABLE_PLUGINS #include <string_view> class Control; namespace ActionBackwardCompatibilityLayer { /** * @brief Translates the old ActionType type to a new Action and fires it. * @param enabled Used for boolean actions only */ void actionPerformed(Control* ctrl, std::string_view type, bool enabled); }; // namespace ActionBackwardCompatibilityLayer #endif
637
C++
.h
23
25.913043
74
0.769737
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,827
Plugin.h
xournalpp_xournalpp/src/core/plugin/Plugin.h
/* * Xournal++ * * A single Xournal++ Plugin * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #include <cstddef> // for size_t #include <limits> // for numeric_limits #include <memory> // for unique_ptr #include "config-features.h" // for ENABLE_PLUGINS #ifdef ENABLE_PLUGINS #include <string> // for string #include <utility> // for move #include <vector> // for vector #include <gtk/gtk.h> // for GtkWidget, GtkWindow #include "util/raii/GObjectSPtr.h" #include "filesystem.h" // for path extern "C" { #include <lua.h> // for lua_State, lua_close } class Plugin; class Control; class ToolMenuHandler; struct MenuEntry final { MenuEntry() = default; MenuEntry(Plugin* plugin, std::string label, std::string callback, ptrdiff_t mode, std::string accelerator): plugin(plugin), label(std::move(label)), callback(std::move(callback)), mode(mode), accelerator(std::move(accelerator)) {} Plugin* plugin = nullptr; ///< The Plugin std::string label{}; ///< Menu display name std::string callback{}; ///< Callback function name ptrdiff_t mode{std::numeric_limits<ptrdiff_t>::max()}; ///< mode in which the callback function is run /** * @brief Accelerator key, see * https://developer.gnome.org/gtk3/stable/gtk3-Keyboard-Accelerators.html#gtk-accelerator-parse */ std::string accelerator{}; /// Action activated when using the menu entry xoj::util::GObjectSPtr<GSimpleAction> action; }; struct ToolbarButtonEntry final { ToolbarButtonEntry() = default; ToolbarButtonEntry(Plugin* plugin, std::string description, std::string toolbarId, std::string iconName, std::string callback, ptrdiff_t mode): plugin(plugin), description(std::move(description)), toolbarId(std::move(toolbarId)), iconName(std::move(iconName)), callback(std::move(callback)), mode(mode) {} Plugin* plugin = nullptr; std::string description{}; ///< description displayed on hovering over the toolbar button std::string toolbarId{}; ///< toolbar ID to be used in toolbar.ini std::string iconName{}; ///< name of the icon which should be stored as iconName + ".svg" std::string callback{}; ///< Callback function name ptrdiff_t mode{std::numeric_limits<ptrdiff_t>::max()}; ///< mode in which the callback function is run }; struct LuaDeleter { void operator()(lua_State* ptr) const { lua_close(ptr); } }; class Plugin final { public: Plugin(Control* control, std::string name, fs::path path); public: /// Load the plugin script void loadScript(); /// Check if this plugin is valid auto isValid() const -> bool; /// Register toolbar item and all other UI stuff void registerToolbar(); /** * @brief Create a GMenu section for the plugin * @param startId next available id * @return next available id after this menu is populated */ size_t populateMenuSection(GtkApplicationWindow* win, size_t startId); /// Get a model for the GMenu section for the plugin inline GMenuModel* getMenuSection() const { return G_MENU_MODEL(menuSection.get()); } // Register toolbar button void registerToolButton(std::string description, std::string toolbarId, std::string iconName, std::string callback, ptrdiff_t mode); // Register all toolbar buttons void registerToolButton(ToolMenuHandler* toolMenuHandler); /// Execute menu entry void executeMenuEntry(MenuEntry* entry); // Execute toolbar button void executeToolbarButton(ToolbarButtonEntry* entry); /// @return the Plugin name auto getName() const -> std::string const&; /// @return Description of the plugin auto getDescription() const -> std::string const&; /// Author of the plugin auto getAuthor() const -> std::string const&; /// Plugin version auto getVersion() const -> std::string const&; /// @return the path to the plugin folder. Each plugin should have a unique path. auto getPath() const -> fs::path const&; /// The plugin is enabled auto isEnabled() const -> bool; /// The plugin is enabled void setEnabled(bool lEnabled); /// The plugin is default enabled auto isDefaultEnabled() const -> bool; ///@return Flag to check if init ui is currently running auto isInInitUi() const -> bool; /// Register a menu item /// @return Internal ID, can e.g. be used to disable the menu auto registerMenu(std::string menu, std::string callback, ptrdiff_t mode, std::string accelerator) -> size_t; ///@return The main controller auto getControl() const -> Control*; private: /// Load ini file void loadIni(); /// Load custom Lua Libraries static void registerXournalppLibs(lua_State* luaPtr); /// Add the plugin folder to the lua path void addPluginToLuaPath(); public: /// Get Plugin from lua engine static auto getPluginFromLua(lua_State* lua) -> Plugin*; /// Execute lua function auto callFunction(const std::string& fnc, ptrdiff_t mode = std::numeric_limits<ptrdiff_t>::max()) -> bool; auto callFunction(const std::string& fnc, const char* s) -> bool; private: Control* control; ///< The main controller std::unique_ptr<lua_State, LuaDeleter> lua{}; ///< Lua engine std::vector<MenuEntry> menuEntries; ///< All registered menu entries xoj::util::GObjectSPtr<GMenu> menuSection; ///< Menu section containing the menu entries std::vector<ToolbarButtonEntry> toolbarButtonEntries; ///< All registered toolbar button entries std::string name; ///< Plugin name std::string description; ///< Description of the plugin std::string author; ///< Author of the plugin std::string version; ///< Plugin version std::string mainfile; ///< Main plugin script fs::path path; ///< Plugin root path bool enabled = false; ///< The plugin is enabled bool defaultEnabled = false; ///< The plugin is default enabled bool inInitUi = false; ///< Flag to check if init ui is currently running bool valid = false; ///< Flag if the plugin is valid / correct loaded static constexpr auto G_ACTION_NAME_PREFIX = "plugins.action-"; }; #else struct Plugin final {}; ///< empty struct, since Plugins are not available #endif
6,774
C++
.h
152
39.467105
119
0.654758
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,828
PluginController.h
xournalpp_xournalpp/src/core/plugin/PluginController.h
/* * Xournal++ * * Plugin main controller * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #include <memory> #include <string> #include <vector> #include <gtk/gtk.h> // for GtkApplicationWindow #include "Plugin.h" #include "filesystem.h" class Control; class ToolMenuHandler; class PluginController final { public: explicit PluginController(Control* control); public: /** * Register toolbar item and all other UI stuff */ void registerToolbar(); /** * @brief Create menu sections (one per enabled plugin with menu entries) * The data is owned by the Plugin's themselves - do not unref */ std::vector<GMenuModel*> createMenuSections(GtkApplicationWindow* win); /** * Add toolbar buttons */ void registerToolButtons(ToolMenuHandler* toolMenuHandler); /** * Show Plugin manager Dialog */ void showPluginManager() const; private: /** * The main controller */ Control* control; /** * All loaded Plugins, sorted by name and path * Todo: replace with boost::flat_map */ std::vector<std::unique_ptr<Plugin>> plugins; };
1,223
C++
.h
51
20.176471
77
0.686207
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,829
Control.h
xournalpp_xournalpp/src/core/control/Control.h
/* * Xournal++ * * The main Control * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #include <cstddef> // for size_t #include <memory> // for unique_ptr #include <optional> // for optional #include <string> // for string, allocator #include <vector> // for vector #include <gdk-pixbuf/gdk-pixbuf.h> // for GdkPixbuf #include <gio/gio.h> // for GApplication #include <glib.h> // for guint #include <gtk/gtk.h> // for GtkLabel #include "control/ToolEnums.h" // for ToolSize, ToolType #include "control/jobs/ProgressListener.h" // for ProgressListener #include "control/settings/ViewModes.h" // for ViewModeId #include "control/tools/EditSelection.h" // for OrderChange #include "enums/Action.enum.h" // for Action #include "gui/toolbarMenubar/model/ColorPalette.h" // for ColorPalette #include "model/DocumentHandler.h" // for DocumentHandler #include "model/DocumentListener.h" // for DocumentListener #include "model/GeometryTool.h" // for GeometryTool #include "model/PageRef.h" // for PageRef #include "undo/UndoRedoHandler.h" // for UndoRedoHandler (ptr only) #include "ClipboardHandler.h" // for ClipboardListener #include "ToolHandler.h" // for ToolListener #include "filesystem.h" // for path class LoadHandler; class GeometryToolController; class AudioController; class FullscreenHandler; class Sidebar; class GladeSearchpath; class MetadataManager; class XournalppCursor; class ToolbarDragDropHandler; class MetadataEntry; class MetadataCallbackData; class PageBackgroundChangeController; class PageTypeHandler; class BaseExportJob; class LayerController; class PluginController; class Document; class EditSelection; class Element; class MainWindow; class ObjectInputStream; class ScrollHandler; class SearchBar; class Settings; class TextEditor; class XournalScheduler; class ZoomControl; class ToolMenuHandler; class XojFont; class XojPdfRectangle; class Callback; class ActionDatabase; class Control: public ToolListener, public DocumentHandler, public UndoRedoListener, public ClipboardListener, public ProgressListener { public: Control(GApplication* gtkApp, GladeSearchpath* gladeSearchPath, bool disableAudio); Control(Control const&) = delete; Control(Control&&) = delete; auto operator=(Control const&) -> Control& = delete; auto operator=(Control&&) -> Control& = delete; ~Control() override; void initWindow(MainWindow* win); public: /// Asymchronously closes the current document and replaces it by a new file void newFile(fs::path filepath = {}); /// @brief Shows an open file dialog and opens the selected file after closing the previously opened file void askToOpenFile(); /** * @brief Asynchronously opens the provided path, safely closes the current opened document and replaces it with the * newly parsed file. Calls callback afterwards, with boolean parameter true on success. Does nothing to this->doc * in case of failure at any point. */ void openFile( fs::path filepath, std::function<void(bool)> callback = [](bool) {}, int scrollToPage = -1, bool forceOpen = false); /// Shows an open file dialog and opens the selected file void askToAnnotatePdf(); /** * (Potentially asynchronously) Opens the given file without saving any previously opened Document. Calls callback * afterwards, with boolean parameter true if success. WARNING: may lead to data loss if the current Document has * not been saved yet. */ void openFileWithoutSavingTheCurrentDocument(fs::path filepath, bool attachToDocument, int scrollToPage, std::function<void(bool)> callback); void print(); void exportAsPdf(); void exportAs(); void quit(bool allowCancel = true); /** * @brief Asynchronously saves the document and calls callback afterwards with boolean parameter true on success. * May ask the user for a place to save if necessary. */ void save(std::function<void(bool)> callback = [](bool) {}); /** * @brief Asks the user for a new location, asynchronously saves the document there and calls callback afterwards. */ void saveAs(std::function<void(bool)> callback = [](bool) {}); /** * Marks the current document as saved if it is currently marked as unsaved. */ void resetSavedStatus(); /** * Close the current document, prompting to save unsaved changes. * * @param callback Called after trying to close the document, with param true in case of success, false otherwise. * @param allowDestroy Whether clicking "Discard" should destroy the current document. * @param allowCancel Whether the user should be able to cancel closing the document. * @return true if the user closed the document, otherwise false. */ void close(std::function<void(bool)> callback, bool allowDestroy = false, bool allowCancel = true); // Menu edit void showSettings(); // The core handler for inserting latex void runLatex(); // Menu Help void showAbout(); /** * @brief Update the Cursor and the Toolbar based on the active color * */ void toolColorChanged() override; /** * @brief Change the color of the current selection based on the active Tool * */ void changeColorOfSelection() override; void toolChanged() override; void toolSizeChanged() override; void toolFillChanged() override; void toolLineStyleChanged() override; void selectTool(ToolType type); void selectDefaultTool(); void setFontSelected(const XojFont& font); ///< Modifies the Action state without triggering callbacks void fontChanged(const XojFont& font); ///< Set the font after the user selected a font void updatePageNumbers(size_t page, size_t pdfPage); /** * Save current state (selected tool etc.) */ void saveSettings(); void updateWindowTitle(); void setViewPairedPages(bool enabled); void setViewFullscreenMode(bool enabled); void setViewPresentationMode(bool enabled); void setPairsOffset(int numOffset); void setViewColumns(int numColumns); void setViewRows(int numRows); void setViewLayoutVert(bool vert); void setViewLayoutR2L(bool r2l); void setViewLayoutB2T(bool b2t); void manageToolbars(); void customizeToolbars(); void setFullscreen(bool enabled); void setShowSidebar(bool enabled); void setShowToolbar(bool enabled); void setShowMenubar(bool enabled); void gotoPage(); void setToolDrawingType(DrawingType type); void paperTemplate(); void paperFormat(); void changePageBackgroundColor(); void updateBackgroundSizeButton(); /** * Loads the view mode (hide/show menu-,tool-&sidebar) */ bool loadViewMode(ViewModeId mode); /** * @brief Search text on the given page. The matches (if any) are stored in the XojPageView::SearchControl instance. * @param occurrences If not nullptr, the pointed variable will contain the number of matches on the page * @param matchRect If not nullptr, will contain the topleft point of the first match on the page * (Used for scrolling to the first match) * @return true if at least one match was found */ bool searchTextOnPage(const std::string& text, size_t pageNumber, size_t index, size_t* occurrences, XojPdfRectangle* matchRect); /** * Fire page selected, but first check if the page Number is valid * * @return the page ID or size_t_npos if the page is not found */ size_t firePageSelected(const PageRef& page); void firePageSelected(size_t page); void addDefaultPage(const std::optional<std::string>& pageTemplate, Document* doc = nullptr); void duplicatePage(); void insertNewPage(size_t position, bool shouldScrollToPage = true); void appendNewPdfPages(); void insertPage(const PageRef& page, size_t position, bool shouldScrollToPage = true); void deletePage(); void movePageTowardsBeginning(); void movePageTowardsEnd(); /** * Ask the user whether a page with the given id * should be added to the document. */ void askInsertPdfPage(size_t pdfPage); /** * Disable / enable page action buttons */ void updatePageActions(); // selection handling void clearSelection(); void moveSelectionToLayer(size_t layerNo); void setCopyCutEnabled(bool enabled); void enableAutosave(bool enable); void clearSelectionEndText(); void selectAllOnPage(); void reorderSelection(EditSelection::OrderChange change); void setToolSize(ToolSize size); /** * Change the line style of the PEN if select, or of selected elements if any * Otherwise, select the PEN tool and set its linestyle */ void setLineStyle(const std::string& style); /** * Change the eraser type. If the eraser is not selected, select it as well. */ void setEraserType(EraserType type); void setFill(bool fill); TextEditor* getTextEditor(); GladeSearchpath* getGladeSearchPath() const; void disableSidebarTmp(bool disabled); XournalScheduler* getScheduler() const; void block(const std::string& name); void unblock(); void setLastAutosaveFile(fs::path newAutosaveFile); void deleteLastAutosaveFile(); void setClipboardHandlerSelection(EditSelection* selection); void addChangedDocumentListener(DocumentListener* dl); void removeChangedDocumentListener(DocumentListener* dl); MetadataManager* getMetadataManager() const; Settings* getSettings() const; ToolHandler* getToolHandler() const; ZoomControl* getZoomControl() const; Document* getDocument() const; UndoRedoHandler* getUndoRedoHandler() const; MainWindow* getWindow() const; GtkWindow* getGtkWindow() const; ScrollHandler* getScrollHandler() const; PageRef getCurrentPage(); size_t getCurrentPageNo() const; XournalppCursor* getCursor() const; Sidebar* getSidebar() const; SearchBar* getSearchBar() const; AudioController* getAudioController() const; PageTypeHandler* getPageTypes() const; PageBackgroundChangeController* getPageBackgroundChangeController() const; LayerController* getLayerController() const; PluginController* getPluginController() const; const Palette& getPalette() const; bool copy(); bool cut(); bool paste(); void help(); void selectAlpha(OpacityFeature feature); /** * @brief Initialize the all button tools based on the respective ButtonConfigs * */ void initButtonTool(); public: // UndoRedoListener interface void undoRedoChanged() override; void undoRedoPageChanged(PageRef page) override; public: // ProgressListener interface void setMaximumState(size_t max) override; void setCurrentState(size_t state) override; public: // ClipboardListener interface void clipboardCutCopyEnabled(bool enabled) override; void clipboardPasteEnabled(bool enabled) override; void clipboardPasteText(std::string text) override; void clipboardPasteImage(GdkPixbuf* img) override; void clipboardPasteXournal(ObjectInputStream& in) override; void deleteSelection() override; void clipboardPaste(ElementPtr e); public: void registerPluginToolButtons(ToolMenuHandler* toolMenuHandler); inline ActionDatabase* getActionDatabase() const { return actionDB.get(); } void loadPaletteFromSettings(); protected: void setRotationSnapping(bool enable); void setGridSnapping(bool enable); bool showSaveDialog(); void showFontDialog(); void showColorChooserDialog(); void fileLoaded(int scrollToPage = -1); void eraserSizeChanged(); void penSizeChanged(); void highlighterSizeChanged(); static bool checkChangedDocument(Control* control); static bool autosaveCallback(Control* control); /** * Load metadata later, md will be deleted */ void loadMetadata(MetadataEntry md); static bool loadMetadataCallback(MetadataCallbackData* data); void saveImpl(bool saveAs, std::function<void(bool)> callback); private: /** * @brief Creates the specified geometric tool if it's not on the current page yet. Deletes it if it already exists. * @return true if a geometric tool was created */ template <class ToolClass, class ViewClass, class ControllerClass, class InputHandlerClass, GeometryToolType toolType> bool toggleGeometryTool(); void resetGeometryTool(); /** * @brief Creates a compass if it's not on the current page yet. Deletes it if it already exists. * @return true if a compass was created */ bool toggleCompass(); /** * @brief Creates a setsquare if it's not on the current page yet. Deletes it if it already exists. * @return true if a setsquare was created */ bool toggleSetsquare(); struct MissingPdfData; /** * Prompt the user that the PDF background is missing and offer solution options */ void promptMissingPdf(MissingPdfData& missingPdf, const fs::path& filepath); /** * Handle the response from the missing PDF dialog */ void missingPdfDialogResponseHandler(fs::path proposedPdfFilepath, int responseId); /** * "Closes" the document, preparing the editor for a new document. */ void closeDocument(); /** * Forcibly replaces the opened document. * WARNING: Be sure the active document has been saved (or discarded) before calling replaceDocument() */ void replaceDocument(std::unique_ptr<Document> doc, int scrollToPage); /** * Asynchronously opens the provided path and parse it as a .xopp or .xoj file. Then forcibly replaces the currently * opened document with the new one. Asks the user in case of doubts (e.g. wrong file version) and aborts if the * document was not correctly and entirely parsed. Calls callback afterwards, with boolean parameter true on * success. WARNING: Be sure the active document has been saved (or discarded) before calling openXoppFile() */ void openXoppFile(fs::path filepath, int scrollToPage, std::function<void(bool)> callback); /** * Opens the provided path and parse it as a PDF file. Then forcibly replaces the currently opened document with a * new one based on the PDF. WARNING: Be sure the active document has been saved (or discarded) before calling * openPdfFile() * * @return true on success */ bool openPdfFile(fs::path filepath, bool attachToDocument, int scrollToPage); /** * Opens the provided path and parse it as a .xopt template file. Then forcibly replaces the currently opened * document with a new one based on the template. WARNING: Be sure the active document has been saved (or discarded) * before calling openXoptFile() * * @return true on success */ bool openXoptFile(fs::path filepath); /** * @brief Get the pen line style to select in the toolbar * * @return style to select, empty if no style should be selected (active * selection with differing line styles) */ auto getLineStyleToSelect() -> std::optional<std::string> const; UndoRedoHandler* undoRedo = nullptr; ZoomControl* zoom = nullptr; Settings* settings = nullptr; std::unique_ptr<Palette> palette; MainWindow* win = nullptr; Document* doc = nullptr; Sidebar* sidebar = nullptr; SearchBar* searchBar = nullptr; ToolHandler* toolHandler; ScrollHandler* scrollHandler; AudioController* audioController; ToolbarDragDropHandler* dragDropHandler = nullptr; GApplication* gtkApp = nullptr; /** * The cursor handler */ XournalppCursor* cursor; /** * Timeout id: the timeout watches the changes and actualizes the previews from time to time */ guint changeTimout; /** * The pages wihch has changed since the last update (for preview update) */ std::vector<PageRef> changedPages; /** * DocumentListener instances that are to be updated by checkChangedDocument. */ std::list<DocumentListener*> changedDocumentListeners; /** * Our clipboard abstraction */ ClipboardHandler* clipboardHandler = nullptr; /** * The autosave handler ID */ guint autosaveTimeout = 0; fs::path lastAutosaveFilename; XournalScheduler* scheduler; /** * State / Blocking attributes */ GtkWidget* statusbar = nullptr; GtkLabel* lbState = nullptr; GtkProgressBar* pgState = nullptr; size_t maxState = 0; bool isBlocking; GladeSearchpath* gladeSearchPath; MetadataManager* metadata; PageTypeHandler* pageTypes; std::unique_ptr<PageBackgroundChangeController> pageBackgroundChangeController; LayerController* layerController; std::unique_ptr<GeometryTool> geometryTool; std::unique_ptr<GeometryToolController> geometryToolController; /** * Manage all Xournal++ plugins */ PluginController* pluginController; std::unique_ptr<ActionDatabase> actionDB; template <Action a> friend struct ActionProperties; };
17,764
C++
.h
444
34.923423
120
0.712775
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,830
Tool.h
xournalpp_xournalpp/src/core/control/Tool.h
/* * Xournal++ * * A tool * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #include <array> // for array #include <optional> // for optional #include <string> // for string #include "control/ToolEnums.h" // for ToolType, ToolCapabilities, ToolSize #include "util/Color.h" // for Color #include "ToolBase.h" // for ToolBase class Tool: public ToolBase { public: /** * @brief number of different sizes defined for tools with Size capability * */ static constexpr int toolSizes = 5; Tool(std::string name, ToolType type, Color color, unsigned int capabilities, std::optional<std::array<double, Tool::toolSizes>> thickness); /** * @brief Construct a new Tool object based on another tool. * @param t tool to use as basis for new copy. */ Tool(const Tool& t); ~Tool() override; public: std::string getName() const; ToolType getToolType() const; bool hasCapability(ToolCapabilities cap) const; double getThickness(ToolSize size) const; /** * @brief Check whether the tool is a Drawing tool. * Drawing tools are considered all tools that directly change the canvas. * Right now these are: * - Highlighter * - Pen * - Eraser * * @return true if tool is a drawing tool * @return false if tool is no drawing tool */ bool isDrawingTool() const; protected: void setCapability(unsigned int capability, bool enabled); private: void operator=(const Tool& t); private: std::string name; ToolType type; std::optional<std::array<double, toolSizes>> thickness; unsigned int capabilities; friend class ToolHandler; };
1,778
C++
.h
60
25.433333
81
0.678824
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,831
PrintHandler.h
xournalpp_xournalpp/src/core/control/PrintHandler.h
/* * Xournal++ * * Prints a document * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #include <cstddef> // for size_t #include <gtk/gtk.h> // for GtkWindow class Document; namespace PrintHandler { void print(Document* doc, size_t currentPage, GtkWindow* parent); }
349
C++
.h
17
18.705882
65
0.721713
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,832
RecentManager.h
xournalpp_xournalpp/src/core/control/RecentManager.h
/* * Xournal++ * * The recent opened files * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #include <gtk/gtk.h> // for GtkRecentInfo #include "util/TinyVector.h" #include "util/raii/CLibrariesSPtr.h" #include "filesystem.h" // for path class Control; /** * @brief Handles the GtkMenu displaying the recent files */ namespace RecentManager { constexpr auto const* MIME = "application/x-xoj"; constexpr auto const* MIME_PDF = "application/x-pdf"; constexpr auto const* GROUP = "xournal++"; constexpr int MAX_RECENT = 10; /** * Adds a file to the underlying GtkRecentManager */ void addRecentFileFilename(const fs::path& filename); /** * Removes a file from the underlying GtkRecentManager */ void removeRecentFileFilename(const fs::path& filename); /** * Remove all supported files from the recent file list */ void clearRecentFiles(); class GtkRecentInfoHandler { public: constexpr static auto ref = gtk_recent_info_ref; constexpr static auto unref = gtk_recent_info_unref; // Todo(cpp20): replace with std:identity() constexpr static auto adopt = [](GtkRecentInfo* p) { return p; }; }; using GtkRecentInfoSPtr = xoj::util::CLibrariesSPtr<GtkRecentInfo, GtkRecentInfoHandler>; /** * Returns the most recent xoj item from the underlying GtkRecentManager * or nullptr, if no recent files exist */ GtkRecentInfoSPtr getMostRecent(); /** * */ struct RecentFiles { TinyVector<GtkRecentInfoSPtr, MAX_RECENT> recentXoppFiles; TinyVector<GtkRecentInfoSPtr, MAX_RECENT> recentPdfFiles; }; RecentFiles getRecentFiles(); }; // namespace RecentManager
1,668
C++
.h
58
26.758621
89
0.758448
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,833
LatexController.h
xournalpp_xournalpp/src/core/control/LatexController.h
/* * Xournal++ * * Controller for Latex stuff * * @author W Brenna * http://wbrenna.ca * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #include <memory> // for unique_ptr #include <string> // for string #include <gio/gio.h> // for GAsyncResult, GCancellable #include <gtk/gtk.h> // for GtkTextBuffer #include <poppler.h> // for GObject #include "control/latex/LatexGenerator.h" // for LatexGenerator #include "model/PageRef.h" // for PageRef #include "filesystem.h" // for path class Control; class TexImage; class Document; class XojPageView; class Layer; class Element; class LatexSettings; class LatexDialog; class LatexController final { public: LatexController() = delete; LatexController(const LatexController& other) = delete; LatexController& operator=(const LatexController& other) = delete; LatexController(Control* control); ~LatexController(); public: /** * Open a LatexDialog, wait for the user to provide the LaTeX formula, and * insert the rendered formula into the document if the supplied LaTeX is * valid. */ static void run(Control* ctrl); private: /** * Provides information about whether a particular dependency was found or not. */ class FindDependencyStatus { public: FindDependencyStatus(bool success, std::string errorMsg): success(success), errorMsg(std::move(errorMsg)){}; bool success; std::string errorMsg; }; /** * Set the required LaTeX files, returning false if at least one of them is not found. */ LatexController::FindDependencyStatus findTexDependencies(); /** * Find a selected tex element, and load it */ void findSelectedTexElement(); /** * If a previous image/text is selected, delete it */ void deleteOldImage(); /** * Asynchronously runs the LaTeX command and then updates the TeX image with * the given LaTeX string. If the preview is already being updated, then * this method will be a no-op. */ void triggerImageUpdate(const std::string& texString); /** * Show the LaTex Editor dialog and process its output */ static void showTexEditDialog(std::unique_ptr<LatexController> texCtrl); /** * Signal handler, updates the rendered image when the text in the editor * changes. */ static void handleTexChanged(LatexController* self); /** * Updates the display once the PDF file is generated. * * If the Latex text has changed since the last update, triggerPreviewUpdate * will be called again. */ static void onPdfRenderComplete(GObject* procObj, GAsyncResult* res, LatexController* self); void updateStatus(); bool isUpdating(); /** * Load the preview PDF from disk and create a TexImage object. */ std::unique_ptr<TexImage> loadRendered(std::string renderedTex); /** * Insert the generated preview TexImage into the current page. */ void insertTexImage(); /// Cancels the current edition: puts the original Tex element back in place (does nothing if there was none) void cancelEditing(); private: Control* control = nullptr; LatexSettings const& settings; /** * The contents of the latex template, loaded from disk. */ std::string latexTemplate; /** * LaTex editor dialog */ LatexDialog* dlg = nullptr; friend class LatexDialog; /** * Tex binary full path */ fs::path pdflatexPath; /** * The original TeX string when the dialog was opened, or the empty string * if creating a new LaTeX element. */ std::string initialTex; /** * The last TeX string shown in the preview. */ std::string lastPreviewedTex; /** * Whether a preview is currently being generated. */ GCancellable* updating_cancellable = nullptr; /** * The output of the last run of the * TeX command. */ std::string texProcessOutput; /** * Whether the current TeX string is valid. */ bool isValidTex = false; /** * X-Position */ double posx = 0; /** * Y-Position */ double posy = 0; /** * Image width */ double imgwidth = 0; /** * Image height */ double imgheight = 0; /** * Document */ Document* doc = nullptr; /** * Page View */ XojPageView* view = nullptr; /** * Selected Page */ PageRef page; /** * Selected layer */ Layer* layer = nullptr; /** * The directory in which the LaTeX files will be generated. Note that this * should be within a system temporary directory. */ fs::path texTmpDir; /** * The element that is currently being edited. */ Element* selectedElem = nullptr; /** * The controller owns the rendered preview in order to be able to delete it * when a new render is created */ std::unique_ptr<TexImage> temporaryRender; LatexGenerator generator; };
5,197
C++
.h
186
22.978495
116
0.658753
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,834
PageBackgroundChangeController.h
xournalpp_xournalpp/src/core/control/PageBackgroundChangeController.h
/* * Xournal++ * * Handle page background change and all other PageBackground stuff * * @author Xournal++ Team * https://github.com/xournalpp/xournalpp * * @license GNU GPLv2 or later */ #pragma once #include <cstddef> // for size_t #include <functional> #include <memory> // for unique_ptr #include <optional> #include <variant> #include "model/BackgroundImage.h" #include "model/DocumentChangeType.h" // for DocumentChangeType #include "model/DocumentListener.h" // for DocumentListener #include "model/PageRef.h" // for PageRef #include "model/PageType.h" // for PageType #include "filesystem.h" // for path class Control; class UndoAction; class PageBackgroundChangeController: public DocumentListener { public: PageBackgroundChangeController(Control* control); ~PageBackgroundChangeController() override = default; public: void changeCurrentPageBackground(const PageType& pageType); /** * @brief (Un)set the page type for newly created pages * @param pageType The new page type. * Passing std::nullopt will unset the page type. * If the page type is not set, newly created pages will have the same type as the current page. */ void setPageTypeForNewPages(const std::optional<PageType>& pageType); void applyCurrentPageBackgroundToAll(); void applyBackgroundToAllPages(const PageType& pt); void changePdfPagesBackground(const fs::path& filepath, bool attachPdf); void insertNewPage(size_t position, bool shouldScrollToPage = true); // DocumentListener public: void documentChanged(DocumentChangeType type) override; void pageSizeChanged(size_t page) override; void pageChanged(size_t page) override; void pageInserted(size_t page) override; void pageDeleted(size_t page) override; void pageSelected(size_t page) override; private: /** * Copy the background from source to target */ static void copyBackgroundFromOtherPage(PageRef target, PageRef source); /// Asks the user to choose a pdf page, and calls callback void askForPdfBackground(std::function<void(size_t)> callback); /// Asks the user to choose an image background, and calls callback void askForImageBackground(std::function<void(BackgroundImage)> callback); /// Nothing, a BackgroundImage or the number of a pdf page using CommitParameter = std::variant<std::nullopt_t, BackgroundImage, size_t>; /** * Applies pageType to page number pageNum. * If pageType.isImage(), a BackgroundImage must be provided * If pageType.isPdf(), a pdf page number must be provided in the std::variant */ auto commitPageTypeChange(size_t pageNum, const PageType& pageType, CommitParameter param = std::nullopt) -> std::unique_ptr<UndoAction>; private: Control* control = nullptr; std::optional<PageType> pageTypeForNewPages; };
2,925
C++
.h
71
37.366197
109
0.735656
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