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,533
|
Shadow.cpp
|
xournalpp_xournalpp/src/core/gui/Shadow.cpp
|
#include "Shadow.h"
#include <cmath>
#include "ShadowCode.c"
Shadow* Shadow::instance = new Shadow();
using u8ptr = const unsigned char*;
Shadow::Shadow() {
const int sBrSize = shadowBottomRightSize;
const int sTlSize = shadowTopLeftSize;
this->edgeTopLeft = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, sTlSize * 2, sTlSize * 2);
cairo_t* cr = cairo_create(this->edgeTopLeft);
drawShadowEdge(cr, 0, 0, sTlSize, sTlSize, reinterpret_cast<u8ptr>(shadowEdge1), 0, 0, 0);
cairo_destroy(cr);
this->edgeTopRight = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, sBrSize * 2, sTlSize * 2);
cr = cairo_create(this->edgeTopRight);
drawShadowEdge(cr, 0, 0, sBrSize, sTlSize, reinterpret_cast<u8ptr>(shadowEdge2), 0, 0, 0);
cairo_destroy(cr);
this->edgeBottomRight = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, sBrSize * 2, sBrSize * 2);
cr = cairo_create(this->edgeBottomRight);
drawShadowEdge(cr, 0, 0, sBrSize, sBrSize, reinterpret_cast<u8ptr>(shadowEdge3), 0, 0, 0);
cairo_destroy(cr);
this->edgeBottomLeft = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, sTlSize * 2, sBrSize * 2);
cr = cairo_create(this->edgeBottomLeft);
drawShadowEdge(cr, 0, 0, sTlSize, sBrSize, reinterpret_cast<u8ptr>(shadowEdge4), 0, 0, 0);
cairo_destroy(cr);
}
Shadow::~Shadow() {
cairo_surface_destroy(this->edgeBottomLeft);
cairo_surface_destroy(this->edgeBottomRight);
cairo_surface_destroy(this->edgeTopLeft);
cairo_surface_destroy(this->edgeTopRight);
this->edgeBottomLeft = nullptr;
this->edgeBottomRight = nullptr;
this->edgeTopLeft = nullptr;
this->edgeTopRight = nullptr;
if (this->left) {
cairo_surface_destroy(this->left);
}
if (this->top) {
cairo_surface_destroy(this->top);
}
if (this->right) {
cairo_surface_destroy(this->right);
}
if (this->bottom) {
cairo_surface_destroy(this->bottom);
}
this->left = nullptr;
this->top = nullptr;
this->right = nullptr;
this->bottom = nullptr;
}
auto Shadow::getShadowBottomRightSize() -> int { return shadowBottomRightSize; }
auto Shadow::getShadowTopLeftSize() -> int { return shadowTopLeftSize; }
void Shadow::drawShadowEdge(cairo_t* cr, int x, int y, int width, int height, const unsigned char* edge, double r,
double g, double b) {
int w = width * 2;
int h = height * 2;
for (int u = 0; u < h; u++) {
for (int i = 0; i < w; i++) {
double a = edge[u * w + i] / 255.0;
cairo_set_source_rgba(cr, r, g, b, a);
cairo_rectangle(cr, x + i, y + u, 1, 1);
cairo_fill(cr);
}
}
}
void Shadow::paintEdge(cairo_t* cr, cairo_surface_t* image, int x, int y, int width, int height) {
cairo_set_source_surface(cr, image, x - width, y - height);
cairo_rectangle(cr, x - width, y - height, width * 2, height * 2);
cairo_fill(cr);
}
void Shadow::drawShadowTop(cairo_t* cr, int x, int y, int width, double r, double g, double b) {
int w = this->top ? cairo_image_surface_get_width(this->top) : 0;
if (w < width) {
if (this->top) {
cairo_surface_destroy(this->top);
}
this->top = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, width, shadowTopLeftSize);
cairo_t* cr2 = cairo_create(this->top);
double a = NAN;
// draw shadow on top and left
for (int i = 0; i < shadowTopLeftSize; i++) {
a = shadowTopLeft[i] / 255.0;
cairo_set_source_rgba(cr2, r, g, b, a);
cairo_rectangle(cr2, 0, i, width, 1);
cairo_fill(cr2);
}
cairo_destroy(cr2);
}
cairo_set_source_surface(cr, this->top, x + shadowTopLeftSize, y - shadowTopLeftSize);
cairo_rectangle(cr, x + shadowTopLeftSize, y - shadowTopLeftSize, width - 2 * shadowTopLeftSize, shadowTopLeftSize);
cairo_fill(cr);
}
void Shadow::drawShadowLeft(cairo_t* cr, int x, int y, int height, double r, double g, double b) {
int h = this->left ? cairo_image_surface_get_height(this->left) : 0;
if (h < height) {
if (this->left) {
cairo_surface_destroy(this->left);
}
this->left = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, shadowTopLeftSize, height);
cairo_t* cr2 = cairo_create(this->left);
double a = NAN;
// draw shadow on top and left
for (int i = 0; i < shadowTopLeftSize; i++) {
a = shadowTopLeft[i] / 255.0;
cairo_set_source_rgba(cr2, r, g, b, a);
cairo_rectangle(cr2, i, 0, 1, height);
cairo_fill(cr2);
}
cairo_destroy(cr2);
}
cairo_set_source_surface(cr, this->left, x - shadowTopLeftSize, y + shadowTopLeftSize);
cairo_rectangle(cr, x - shadowTopLeftSize, y + shadowTopLeftSize, shadowTopLeftSize,
height - 2 * shadowTopLeftSize);
cairo_fill(cr);
}
void Shadow::drawShadowRight(cairo_t* cr, int x, int y, int height, double r, double g, double b) {
int h = this->right ? cairo_image_surface_get_height(this->right) : 0;
if (h < height) {
if (this->right) {
cairo_surface_destroy(this->right);
}
this->right = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, shadowBottomRightSize, height);
cairo_t* cr2 = cairo_create(this->right);
double a = NAN;
// draw shadow on top and left
for (int i = 0; i < shadowBottomRightSize; i++) {
a = shadowBottomRight[i] / 255.0;
cairo_set_source_rgba(cr2, r, g, b, a);
cairo_rectangle(cr2, i, 0, 1, height);
cairo_fill(cr2);
}
cairo_destroy(cr2);
}
cairo_set_source_surface(cr, this->right, x, y + shadowBottomRightSize);
cairo_rectangle(cr, x, y + shadowBottomRightSize, shadowBottomRightSize, height - 2 * shadowBottomRightSize);
cairo_fill(cr);
}
void Shadow::drawShadowBottom(cairo_t* cr, int x, int y, int width, double r, double g, double b) {
int w = this->bottom ? cairo_image_surface_get_width(this->bottom) : 0;
if (w < width) {
if (this->bottom) {
cairo_surface_destroy(this->bottom);
}
this->bottom = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, width, shadowBottomRightSize);
cairo_t* cr2 = cairo_create(this->bottom);
// draw shadow on top and left
for (int i = 0; i < shadowBottomRightSize; i++) {
auto a = shadowBottomRight[i] / 255.0;
cairo_set_source_rgba(cr2, r, g, b, a);
cairo_rectangle(cr2, 0, i, width, 1);
cairo_fill(cr2);
}
cairo_destroy(cr2);
}
cairo_set_source_surface(cr, this->bottom, x + shadowBottomRightSize, y);
cairo_rectangle(cr, x + shadowBottomRightSize, y, width - 2 * shadowBottomRightSize, shadowBottomRightSize);
cairo_fill(cr);
}
void Shadow::drawShadowImpl(cairo_t* cr, int x, int y, int width, int height) {
const int sBrSize = shadowBottomRightSize;
const int sTlSize = shadowTopLeftSize;
drawShadowTop(cr, x, y, width - 3, 0, 0, 0);
drawShadowLeft(cr, x, y, height - 3, 0, 0, 0);
drawShadowRight(cr, x + width, y - 4, height + 5, 0, 0, 0);
drawShadowBottom(cr, x - 4, y + height, width + 5, 0, 0, 0);
paintEdge(cr, this->edgeTopLeft, x, y, sTlSize, sTlSize);
paintEdge(cr, this->edgeTopRight, x + width + 1, y, sBrSize, sTlSize);
paintEdge(cr, this->edgeBottomLeft, x, y + height + 1, sTlSize, sBrSize);
paintEdge(cr, this->edgeBottomRight, x + width + 1, y + height + 1, sBrSize, sBrSize);
}
void Shadow::drawShadow(cairo_t* cr, int x, int y, int width, int height) {
Shadow::instance->drawShadowImpl(cr, x, y, width, height);
}
| 7,809
|
C++
|
.cpp
| 174
| 37.913793
| 120
| 0.629864
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
12,534
|
LayoutMapper.cpp
|
xournalpp_xournalpp/src/core/gui/LayoutMapper.cpp
|
#include "LayoutMapper.h"
#include <algorithm> // for max
#include <map> // for __alloc_traits<>::value_type
#include "control/settings/Settings.h" // for Settings
constexpr auto calc_default_grid_pos = [](size_t page_nr, GridPosition grid_size,
LayoutSettings::Orientation orientation) {
return orientation == LayoutSettings::Orientation::Vertical ?
GridPosition{page_nr / grid_size.row, page_nr % grid_size.row} :
GridPosition{page_nr % grid_size.col, page_nr / grid_size.col};
};
constexpr auto map1 = [](LayoutSettings const& data, size_t page_nr) {
GridPosition grid_pos{};
auto new_nr = page_nr + static_cast<size_t>(data.offset);
if (data.showPairedPages) {
auto grid_size = GridPosition{data.cols / 2, data.rows};
grid_pos = calc_default_grid_pos(new_nr / 2, grid_size, data.orientation);
(grid_pos.col *= 2) += (new_nr % 2);
} else {
grid_pos = calc_default_grid_pos(new_nr, {data.cols, data.rows}, data.orientation);
}
decltype(grid_pos) grid_pos2 = {
(data.horizontalDir == LayoutSettings::HorizontalDirection::RightToLeft ? data.cols - 1 - grid_pos.col :
grid_pos.col),
(data.verticalDir == LayoutSettings::VerticalDirection::BottomToTop ? data.rows - 1 - grid_pos.row :
grid_pos.row)};
return grid_pos2;
};
constexpr auto map2 = [](LayoutSettings const& data, GridPosition pos) -> std::optional<size_t> {
auto isRightToLeft = [&]() { return data.horizontalDir == LayoutSettings::RightToLeft; };
auto isBottomToTop = [&]() { return data.verticalDir == LayoutSettings::BottomToTop; };
auto isVertical = [&]() { return data.orientation == LayoutSettings::Vertical; };
if (isRightToLeft()) { // reverse x
pos.col = data.cols - 1 - pos.col;
}
if (isBottomToTop()) { // reverse y
pos.row = data.rows - 1 - pos.row;
}
size_t res{};
if (isVertical()) {
if (data.showPairedPages) {
res = ((pos.row + data.rows * (pos.col / 2)) * 2) + pos.col % 2;
} else {
res = pos.row + data.rows * pos.col;
}
} else { // Horizontal
res = pos.col + data.cols * pos.row;
}
res -= data.offset;
if (res >= data.actualPages) {
return {};
}
return res;
};
// Testers
constexpr LayoutSettings my_data0{1, 91, 92, 1};
constexpr LayoutSettings my_data1{91, 1, 90, 1};
constexpr LayoutSettings my_data2{
6, 6, 35, 1, true, LayoutSettings::Vertical, LayoutSettings::RightToLeft, LayoutSettings::BottomToTop};
constexpr GridPosition test_pos0{0, 3};
constexpr GridPosition test_pos1{3, 0};
constexpr GridPosition test_pos2{3, 3};
static_assert(map1(my_data0, *map2(my_data0, test_pos0)) == test_pos0);
static_assert(map1(my_data1, *map2(my_data1, test_pos1)) == test_pos1);
static_assert(map1(my_data2, *map2(my_data2, test_pos2)) == test_pos2);
template <typename T>
constexpr auto hash(T&& data_, GridPosition const& pos) {
return pos.col + pos.row * data_.cols;
}
/**
* calculate
*
* Set mapper to LayoutType with number of pages and of fixed rows or columns
* @param data the data to be configured
* @param numRows Number of rows ( used if useRows )
* @param numCols Number of columns ( used if !useRows )
* @param useRows use pages/rows to recalculate cols else recalculate rows
* @param firstPageOffset Pages to offset - usually one or zero in order to pair up properly
*/
void calculate(LayoutSettings& data, size_t numRows, size_t numCols, bool useRows, uint32_t firstPageOffset) {
if (useRows) {
data.rows = std::max<size_t>(1UL, numRows);
// using + ( rows-1) to round up (int)pages/rows
data.cols = std::max<size_t>(1UL, (data.actualPages + firstPageOffset + (data.rows - 1)) / data.rows);
if (data.showPairedPages) {
data.cols += data.cols % 2; // make even
}
} else {
data.cols = std::max<size_t>(1UL, numCols);
if (data.showPairedPages) {
data.cols += data.cols % 2; // make even
}
data.rows = std::max<size_t>(1UL, (data.actualPages + firstPageOffset + (data.cols - 1)) / data.cols);
}
if (data.orientation == LayoutSettings::Vertical) {
// Vertical Layout
if (data.showPairedPages) {
data.offset = firstPageOffset % static_cast<uint32_t>(2 * data.rows);
} else {
data.offset = firstPageOffset % static_cast<uint32_t>(data.rows);
}
} else {
// Horizontal Layout
data.offset = firstPageOffset % static_cast<uint32_t>(data.cols);
}
}
void LayoutMapper::configureFromSettings(size_t numPages, Settings* settings) {
LayoutSettings data;
// get from user settings:
data.actualPages = numPages;
data.showPairedPages = settings->isShowPairedPages();
auto const& pairsOffset = data.showPairedPages ? static_cast<uint32_t>(settings->getPairsOffset()) : 0U;
auto const& isPresentationMode = settings->isPresentationMode();
auto const& fixRows = !isPresentationMode && settings->isViewFixedRows();
auto const& numCols = size_t(isPresentationMode ? 1 : settings->getViewColumns());
auto const& numRows = size_t(isPresentationMode ? 1 : settings->getViewRows());
// assemble bitflags for LayoutType
data.orientation = (isPresentationMode || settings->getViewLayoutVert()) ? LayoutSettings::Vertical :
LayoutSettings::Horizontal;
data.horizontalDir = settings->getViewLayoutR2L() ? LayoutSettings::RightToLeft : LayoutSettings::LeftToRight;
data.verticalDir = settings->getViewLayoutB2T() ? LayoutSettings::BottomToTop : LayoutSettings::TopToBottom;
calculate(data, numRows, numCols, fixRows, pairsOffset);
if (data == data_) {
return;
}
data_ = data;
precalculateMappers();
}
void LayoutMapper::precalculateMappers() {
this->pageToRaster.clear();
this->rasterToPage.clear();
this->pageToRaster.resize(data_.actualPages);
this->rasterToPage.resize(data_.rows * data_.cols, size_t(-1));
for (size_t i = 0; i != data_.actualPages; ++i) {
auto&& val = map1(data_, i);
this->pageToRaster[i] = val;
this->rasterToPage[hash(data_, val)] = i;
}
}
auto LayoutMapper::getColumns() const -> size_t { return data_.cols; }
auto LayoutMapper::getRows() const -> size_t { return data_.rows; }
auto LayoutMapper::isPairedPages() const -> bool { return data_.showPairedPages; }
auto LayoutMapper::at(size_t page) const -> GridPosition { return pageToRaster.at(page); }
auto LayoutMapper::at(GridPosition const& rasterXY) const -> std::optional<size_t> {
auto index = hash(data_, rasterXY);
if (index >= rasterToPage.size()) {
return std::nullopt;
}
auto val = rasterToPage[index];
return val >= data_.actualPages ? std::nullopt : std::optional<size_t>(val); // Maybe optimize this
}
| 7,216
|
C++
|
.cpp
| 150
| 40.766667
| 116
| 0.637022
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,535
|
GladeSearchpath.cpp
|
xournalpp_xournalpp/src/core/gui/GladeSearchpath.cpp
|
/*
* Xournal++
*
* Search directory for icons and Glade files
*
* @author andreas
* https://github.com/xournalpp/xournalpp
*
* @license GNU GPLv2 or later
*/
#include "GladeSearchpath.h"
GladeSearchpath::GladeSearchpath() = default;
GladeSearchpath::~GladeSearchpath() { directories.clear(); }
auto GladeSearchpath::findFile(fs::path const& subdir, fs::path const& file) const -> fs::path {
fs::path filepath;
if (subdir.empty()) {
filepath = file;
} else {
filepath = subdir / file;
}
// We step through each directory to find it.
for (const auto& dir: directories) {
auto pathname = dir / filepath;
if (fs::exists(pathname)) {
return pathname;
}
}
return fs::path{};
}
/**
* @return The first search path
*/
auto GladeSearchpath::getFirstSearchPath() const -> fs::path {
if (this->directories.empty()) {
return {};
}
return this->directories[0];
}
/**
* Use this function to set the directory containing installed pixmaps and Glade XML files.
*/
void GladeSearchpath::addSearchDirectory(fs::path const& directory) { this->directories.push_back(directory); }
| 1,187
|
C++
|
.cpp
| 42
| 24.238095
| 111
| 0.668722
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,536
|
ToolitemDragDrop.cpp
|
xournalpp_xournalpp/src/core/gui/ToolitemDragDrop.cpp
|
#include "ToolitemDragDrop.h"
#include <glib-object.h> // for g_object_...
#include <glib.h> // for g_malloc
#include "gui/toolbarMenubar/AbstractToolItem.h" // for AbstractT...
#include "gui/toolbarMenubar/icon/ToolbarSeparatorImage.h" // for getNewToo...
struct NamedColor;
const char* ATTACH_DRAG_DROP_DATA = "XOJ_DRAG_DROP_DATA";
void ToolitemDragDrop::attachMetadata(GtkWidget* w, int id, AbstractToolItem* ait) {
ToolItemDragDropData* d = g_new(ToolItemDragDropData, 1);
d->identify = ToolItemDragDropData_Identify;
d->id = id;
d->item = ait;
d->type = TOOL_ITEM_ITEM;
d->paletteColorIndex = 0;
g_object_set_data_full(G_OBJECT(w), ATTACH_DRAG_DROP_DATA, d, static_cast<GDestroyNotify>(g_free));
}
auto ToolitemDragDrop::ToolItemDragDropData_new(AbstractToolItem* item) -> std::unique_ptr<ToolItemDragDropData> {
auto d = std::make_unique<ToolItemDragDropData>();
d->identify = ToolItemDragDropData_Identify;
d->id = -1;
d->item = item;
d->type = TOOL_ITEM_ITEM;
d->paletteColorIndex = 0;
return d;
}
void ToolitemDragDrop::attachMetadata(GtkWidget* w, int id, ToolItemType type) {
ToolItemDragDropData* d = g_new(ToolItemDragDropData, 1);
d->identify = ToolItemDragDropData_Identify;
d->id = id;
d->item = nullptr;
d->type = type;
d->paletteColorIndex = 0;
g_object_set_data_full(G_OBJECT(w), ATTACH_DRAG_DROP_DATA, d, static_cast<GDestroyNotify>(g_free));
}
void ToolitemDragDrop::attachMetadataColor(GtkWidget* w, int id, size_t paletteColorIndex, AbstractToolItem* item) {
ToolItemDragDropData* d = g_new(ToolItemDragDropData, 1);
d->identify = ToolItemDragDropData_Identify;
d->id = id;
d->item = item;
d->type = TOOL_ITEM_COLOR;
d->paletteColorIndex = paletteColorIndex;
g_object_set_data_full(G_OBJECT(w), ATTACH_DRAG_DROP_DATA, d, static_cast<GDestroyNotify>(g_free));
}
auto ToolitemDragDrop::getIcon(ToolItemDragDropData* data) -> GtkWidget* {
if (data->type == TOOL_ITEM_ITEM || data->type == TOOL_ITEM_COLOR) {
return data->item->getNewToolIcon();
}
if (data->type == TOOL_ITEM_SEPARATOR) {
return ToolbarSeparatorImage::newImage(SeparatorType::SEPARATOR);
}
if (data->type == TOOL_ITEM_SPACER) {
return ToolbarSeparatorImage::newImage(SeparatorType::SPACER);
}
g_warning("ToolitemDragDrop::getIcon unhandled type: %i\n", data->type);
return gtk_image_new();
}
auto ToolitemDragDrop::checkToolItemDragDropData(ToolItemDragDropData const* d) -> bool {
return d->identify == ToolItemDragDropData_Identify;
}
auto ToolitemDragDrop::metadataGetMetadata(GtkWidget* w) -> ToolItemDragDropData* {
void* ptr = g_object_get_data(G_OBJECT(w), ATTACH_DRAG_DROP_DATA);
if (ptr == nullptr) {
g_warning("ToolitemDragDrop::metadataGetMetadata Could not get Metadata %s from %s\n", ATTACH_DRAG_DROP_DATA,
g_type_name(G_TYPE_FROM_INSTANCE(w)));
return nullptr;
}
if (!checkToolItemDragDropData(static_cast<ToolItemDragDropData const*>(ptr))) {
g_warning("ToolitemDragDrop::metadataGetMetadata data is not an instance of ToolItemDragDropData!");
return nullptr;
}
return static_cast<ToolItemDragDropData*>(ptr);
}
| 3,296
|
C++
|
.cpp
| 72
| 41.138889
| 117
| 0.708229
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,537
|
CreatePreviewImage.cpp
|
xournalpp_xournalpp/src/core/gui/CreatePreviewImage.cpp
|
#include "CreatePreviewImage.h"
#include "model/PageType.h" // for PageType
#include "util/Color.h" // for Color
#include "util/raii/CairoWrappers.h"
#include "util/raii/GObjectSPtr.h"
#include "view/background/BackgroundView.h" // for BackgroundView
namespace xoj::helper {
auto createPreviewImage(const PageType& pt) -> GtkWidget* {
const double zoom = 0.5;
xoj::util::CairoSurfaceSPtr surface(cairo_image_surface_create(CAIRO_FORMAT_ARGB32, PREVIEW_WIDTH, PREVIEW_HEIGHT),
xoj::util::adopt);
xoj::util::CairoSPtr crSPtr(cairo_create(surface.get()), xoj::util::adopt);
auto cr = crSPtr.get();
cairo_scale(cr, zoom, zoom);
auto bgView = xoj::view::BackgroundView::createRuled(PREVIEW_WIDTH / zoom, PREVIEW_HEIGHT / zoom, Colors::white, pt,
1. / zoom);
bgView->draw(cr);
cairo_identity_matrix(cr);
cairo_set_line_width(cr, 2);
cairo_set_source_rgb(cr, 0.8, 0.8, 0.8);
cairo_move_to(cr, 0, 0);
cairo_line_to(cr, PREVIEW_WIDTH, 0);
cairo_line_to(cr, PREVIEW_WIDTH, PREVIEW_HEIGHT);
cairo_line_to(cr, 0, PREVIEW_HEIGHT);
cairo_line_to(cr, 0, 0);
cairo_stroke(cr);
xoj::util::GObjectSPtr<GdkPixbuf> pixbuf(
gdk_pixbuf_get_from_surface(surface.get(), 0, 0, PREVIEW_WIDTH, PREVIEW_HEIGHT), xoj::util::adopt);
return gtk_image_new_from_pixbuf(pixbuf.get());
}
}; // namespace xoj::helper
| 1,478
|
C++
|
.cpp
| 31
| 40.580645
| 120
| 0.649062
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,538
|
SpinPageAdapter.cpp
|
xournalpp_xournalpp/src/core/gui/widgets/SpinPageAdapter.cpp
|
#include "SpinPageAdapter.h"
#include <cstdint> // for uint64_t
#include <glib-object.h> // for g_signal_handler_disconnect, G_CALLBACK
#include "util/Assert.h" // for xoj_assert
#include "util/glib_casts.h" // for wrap_for_once_v
#include "util/safe_casts.h"
auto SpinPageAdapter::pageNrSpinChangedTimerCallback(SpinPageAdapter* adapter) -> bool {
adapter->lastTimeoutId = 0;
adapter->page = static_cast<size_t>(gtk_spin_button_get_value_as_int(GTK_SPIN_BUTTON(adapter->widget.get())));
adapter->firePageChanged();
return false;
}
void SpinPageAdapter::pageNrSpinChangedCallback(GtkSpinButton* spinbutton, SpinPageAdapter* adapter) {
// Nothing changed.
if (as_unsigned(gtk_spin_button_get_value_as_int(GTK_SPIN_BUTTON(spinbutton))) == adapter->page) {
return;
}
if (adapter->lastTimeoutId) {
g_source_remove(adapter->lastTimeoutId);
}
// Give the spin button some time to release, if we don't do he will send new events...
adapter->lastTimeoutId = g_timeout_add(100, xoj::util::wrap_for_once_v<pageNrSpinChangedTimerCallback>, adapter);
}
void SpinPageAdapter::setWidget(GtkWidget* widget) {
if (this->widget && this->pageNrSpinChangedHandlerId) {
g_signal_handler_disconnect(this->widget.get(), this->pageNrSpinChangedHandlerId);
}
xoj_assert(widget);
this->widget.reset(widget, xoj::util::refsink);
this->pageNrSpinChangedHandlerId =
g_signal_connect(widget, "value-changed", G_CALLBACK(pageNrSpinChangedCallback), this);
this->lastTimeoutId = 0;
gtk_spin_button_set_range(GTK_SPIN_BUTTON(widget), static_cast<double>(this->min), static_cast<double>(this->max));
gtk_spin_button_set_value(GTK_SPIN_BUTTON(widget), static_cast<double>(this->page));
}
auto SpinPageAdapter::getPage() const -> size_t { return this->page; }
void SpinPageAdapter::setPage(size_t page) {
this->page = page;
if (this->widget) {
gtk_spin_button_set_value(GTK_SPIN_BUTTON(this->widget.get()), static_cast<double>(page));
}
}
void SpinPageAdapter::setMinMaxPage(size_t min, size_t max) {
this->min = min;
this->max = max;
if (this->widget) {
gtk_spin_button_set_range(GTK_SPIN_BUTTON(this->widget.get()), static_cast<double>(min),
static_cast<double>(max));
}
}
void SpinPageAdapter::addListener(SpinPageListener* listener) { this->listener = listener; }
void SpinPageAdapter::removeListener(SpinPageListener* listener) {
xoj_assert(listener == this->listener);
this->listener = nullptr;
}
void SpinPageAdapter::firePageChanged() { this->listener->pageChanged(this->page); }
SpinPageListener::~SpinPageListener() = default;
| 2,725
|
C++
|
.cpp
| 57
| 43.035088
| 119
| 0.709544
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,539
|
XournalWidget.cpp
|
xournalpp_xournalpp/src/core/gui/widgets/XournalWidget.cpp
|
#include "XournalWidget.h"
#include <algorithm> // for max
#include <cmath> // for NAN
#include <optional> // for optional
#include <vector> // for vector
#include <cairo.h> // for cairo_restore, cairo_save
#include <gdk/gdk.h> // for GdkRectangle, GdkWindowAttr
#include "control/Control.h" // for Control
#include "control/settings/Settings.h" // for Settings
#include "control/tools/EditSelection.h" // for EditSelection
#include "gui/Layout.h" // for Layout
#include "gui/LegacyRedrawable.h" // for Redrawable
#include "gui/PageView.h" // for XojPageView
#include "gui/Shadow.h" // for Shadow
#include "gui/XournalView.h" // for XournalView
#include "gui/inputdevices/InputContext.h" // for InputContext
#include "gui/scroll/ScrollHandling.h" // for ScrollHandling
#include "util/Color.h" // for cairo_set_source_rgbi
#include "util/Rectangle.h" // for Rectangle
using xoj::util::Rectangle;
static void gtk_xournal_class_init(GtkXournalClass* klass);
static void gtk_xournal_init(GtkXournal* xournal);
static void gtk_xournal_get_preferred_width(GtkWidget* widget, gint* minimal_width, gint* natural_width);
static void gtk_xournal_get_preferred_height(GtkWidget* widget, gint* minimal_height, gint* natural_height);
static void gtk_xournal_size_allocate(GtkWidget* widget, GtkAllocation* allocation);
static void gtk_xournal_realize(GtkWidget* widget);
static auto gtk_xournal_draw(GtkWidget* widget, cairo_t* cr) -> gboolean;
static void gtk_xournal_dispose(GObject* object);
auto gtk_xournal_get_type(void) -> GType {
static GType gtk_xournal_type = 0;
if (!gtk_xournal_type) {
static const GTypeInfo gtk_xournal_info = {sizeof(GtkXournalClass),
// base initialize
nullptr,
// base finalize
nullptr,
// class initialize
reinterpret_cast<GClassInitFunc>(gtk_xournal_class_init),
// class finalize
nullptr,
// class data,
nullptr,
// instance size
sizeof(GtkXournal),
// n_preallocs
0,
// instance init
reinterpret_cast<GInstanceInitFunc>(gtk_xournal_init),
// value table
nullptr};
gtk_xournal_type =
g_type_register_static(GTK_TYPE_WIDGET, "GtkXournal", >k_xournal_info, static_cast<GTypeFlags>(0));
}
return gtk_xournal_type;
}
auto gtk_xournal_new(XournalView* view, InputContext* inputContext) -> GtkWidget* {
GtkXournal* xoj = GTK_XOURNAL(g_object_new(gtk_xournal_get_type(), nullptr));
xoj->view = view;
xoj->scrollHandling = inputContext->getScrollHandling();
xoj->layout = new Layout(view, inputContext->getScrollHandling());
xoj->selection = nullptr;
xoj->input = inputContext;
xoj->input->connect(GTK_WIDGET(xoj));
return GTK_WIDGET(xoj);
}
static void gtk_xournal_class_init(GtkXournalClass* cptr) {
auto* widget_class = reinterpret_cast<GtkWidgetClass*>(cptr);
widget_class->realize = gtk_xournal_realize;
widget_class->get_preferred_width = gtk_xournal_get_preferred_width;
widget_class->get_preferred_height = gtk_xournal_get_preferred_height;
widget_class->size_allocate = gtk_xournal_size_allocate;
widget_class->draw = gtk_xournal_draw;
reinterpret_cast<GObjectClass*>(widget_class)->dispose = gtk_xournal_dispose;
}
auto gtk_xournal_get_visible_area(GtkWidget* widget, const XojPageView* p) -> Rectangle<double>* {
g_return_val_if_fail(widget != nullptr, nullptr);
g_return_val_if_fail(GTK_IS_XOURNAL(widget), nullptr);
GtkXournal* xournal = GTK_XOURNAL(widget);
GtkAdjustment* vadj = xournal->scrollHandling->getVertical();
GtkAdjustment* hadj = xournal->scrollHandling->getHorizontal();
GdkRectangle r2;
r2.x = static_cast<int>(gtk_adjustment_get_value(hadj));
r2.y = static_cast<int>(gtk_adjustment_get_value(vadj));
r2.width = static_cast<int>(gtk_adjustment_get_page_size(hadj));
r2.height = static_cast<int>(gtk_adjustment_get_page_size(vadj));
GdkRectangle r1;
r1.x = p->getX();
r1.y = p->getY();
r1.width = p->getDisplayWidth();
r1.height = p->getDisplayHeight();
GdkRectangle r3 = {0, 0, 0, 0};
gdk_rectangle_intersect(&r1, &r2, &r3);
if (r3.width == 0 && r3.height == 0) {
return nullptr;
}
r3.x -= r1.x;
r3.y -= r1.y;
double zoom = xournal->view->getZoom();
if (r3.x < 0 || r3.y < 0) {
g_warning("XournalWidget:gtk_xournal_get_visible_area: intersection rectangle coordinates are negative which "
"should never happen");
}
return new Rectangle<double>(std::max(r3.x, 0) / zoom, std::max(r3.y, 0) / zoom, r3.width / zoom, r3.height / zoom);
}
auto gtk_xournal_get_layout(GtkWidget* widget) -> Layout* {
g_return_val_if_fail(widget != nullptr, nullptr);
g_return_val_if_fail(GTK_IS_XOURNAL(widget), nullptr);
GtkXournal* xournal = GTK_XOURNAL(widget);
return xournal->layout;
}
static void gtk_xournal_init(GtkXournal* xournal) {
GtkWidget* widget = GTK_WIDGET(xournal);
gtk_widget_set_can_focus(widget, true);
}
static void gtk_xournal_get_preferred_width(GtkWidget* widget, gint* minimal_width, gint* natural_width) {
GtkXournal* xournal = GTK_XOURNAL(widget);
*minimal_width = *natural_width = xournal->layout->getMinimalWidth();
}
static void gtk_xournal_get_preferred_height(GtkWidget* widget, gint* minimal_height, gint* natural_height) {
GtkXournal* xournal = GTK_XOURNAL(widget);
*minimal_height = *natural_height = xournal->layout->getMinimalHeight();
}
/**
* This method is called while scrolling or after the XournalWidget size has changed
*/
static void gtk_xournal_size_allocate(GtkWidget* widget, GtkAllocation* allocation) {
g_return_if_fail(widget != nullptr);
g_return_if_fail(GTK_IS_XOURNAL(widget));
g_return_if_fail(allocation != nullptr);
gtk_widget_set_allocation(widget, allocation);
if (gtk_widget_get_realized(widget)) {
gdk_window_move_resize(gtk_widget_get_window(widget), allocation->x, allocation->y, allocation->width,
allocation->height);
}
GtkXournal* xournal = GTK_XOURNAL(widget);
// layout the pages in the XournalWidget
xournal->layout->layoutPages(allocation->width, allocation->height);
}
static void gtk_xournal_realize(GtkWidget* widget) {
GdkWindowAttr attributes;
g_return_if_fail(widget != nullptr);
g_return_if_fail(GTK_IS_XOURNAL(widget));
gtk_widget_set_realized(widget, true);
gtk_widget_set_hexpand(widget, true);
gtk_widget_set_vexpand(widget, true);
GtkAllocation allocation;
gtk_widget_get_allocation(widget, &allocation);
attributes.window_type = GDK_WINDOW_CHILD;
attributes.x = allocation.x;
attributes.y = allocation.y;
attributes.width = allocation.width;
attributes.height = allocation.height;
attributes.wclass = GDK_INPUT_OUTPUT;
attributes.event_mask = gtk_widget_get_events(widget) | GDK_EXPOSURE_MASK;
gint attributes_mask = GDK_WA_X | GDK_WA_Y;
gtk_widget_set_window(widget, gdk_window_new(gtk_widget_get_parent_window(widget), &attributes, attributes_mask));
gdk_window_set_user_data(gtk_widget_get_window(widget), widget);
}
static void gtk_xournal_draw_shadow(GtkXournal* xournal, cairo_t* cr, int left, int top, int width, int height,
bool selected) {
if (selected) {
Shadow::drawShadow(cr, left - 2, top - 2, width + 4, height + 4);
Settings* settings = xournal->view->getControl()->getSettings();
// Draw border
Util::cairo_set_source_rgbi(cr, settings->getBorderColor());
cairo_set_line_width(cr, 4.0);
cairo_set_line_cap(cr, CAIRO_LINE_CAP_SQUARE);
cairo_set_line_join(cr, CAIRO_LINE_JOIN_MITER);
cairo_rectangle(cr, left, top, width, height);
cairo_stroke(cr);
} else {
Shadow::drawShadow(cr, left, top, width, height);
}
}
void gtk_xournal_repaint_area(GtkWidget* widget, int x1, int y1, int x2, int y2) {
g_return_if_fail(widget != nullptr);
g_return_if_fail(GTK_IS_XOURNAL(widget));
if (x2 < 0 || y2 < 0) {
return; // outside visible area
}
GtkAllocation alloc = {0};
gtk_widget_get_allocation(widget, &alloc);
if (x1 > alloc.width || y1 > alloc.height) {
return; // outside visible area
}
gtk_widget_queue_draw_area(widget, x1, y1, x2 - x1, y2 - y1);
}
static auto gtk_xournal_draw(GtkWidget* widget, cairo_t* cr) -> gboolean {
g_return_val_if_fail(widget != nullptr, false);
g_return_val_if_fail(GTK_IS_XOURNAL(widget), false);
GtkXournal* xournal = GTK_XOURNAL(widget);
double x1 = NAN, x2 = NAN, y1 = NAN, y2 = NAN;
cairo_clip_extents(cr, &x1, &y1, &x2, &y2);
// Draw background
Settings* settings = xournal->view->getControl()->getSettings();
Util::cairo_set_source_rgbi(cr, settings->getBackgroundColor());
cairo_paint(cr);
// Add a padding for the shadow of the pages
Rectangle clippingRect(x1 - 10, y1 - 10, x2 - x1 + 20, y2 - y1 + 20);
for (auto&& pv: xournal->view->getViewPages()) {
int px = pv->getX();
int py = pv->getY();
int pw = pv->getDisplayWidth();
int ph = pv->getDisplayHeight();
if (!clippingRect.intersects(pv->getRect())) {
continue;
}
gtk_xournal_draw_shadow(xournal, cr, px, py, pw, ph, pv->isSelected());
cairo_save(cr);
cairo_translate(cr, px, py);
pv->paintPage(cr, nullptr);
cairo_restore(cr);
}
if (xournal->selection) {
cairo_save(cr);
double zoom = xournal->view->getZoom();
LegacyRedrawable* red = xournal->selection->getView();
cairo_translate(cr, red->getX(), red->getY());
xournal->selection->paint(cr, zoom);
cairo_restore(cr);
}
return true;
}
static void gtk_xournal_dispose(GObject* object) {
g_return_if_fail(object != nullptr);
g_return_if_fail(GTK_IS_XOURNAL(object));
GtkXournal* xournal = GTK_XOURNAL(object);
delete xournal->selection;
xournal->selection = nullptr;
delete xournal->layout;
xournal->layout = nullptr;
delete xournal->input;
xournal->input = nullptr;
}
| 11,243
|
C++
|
.cpp
| 234
| 39.132479
| 120
| 0.621547
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,540
|
ZoomCallib.cpp
|
xournalpp_xournalpp/src/core/gui/widgets/ZoomCallib.cpp
|
/*
* Xournal++
*
* Control to callibrate the zoom to fit the display DPI
*
* @author Xournal Team
* http://xournal.sf.net
*
* @license GPL
*/
#include "ZoomCallib.h"
#include <cairo.h> // for cairo_set_source_rgb, cairo_fill, cairo_move_to
#include <gdk/gdk.h> // for GdkWindowAttr, gdk_window_move_resize, gdk_wind...
G_DEFINE_TYPE(ZoomCallib, zoomcallib, GTK_TYPE_WIDGET); // NOLINT // @suppress("Unused static function")
static void zoomcallib_get_preferred_width(GtkWidget* widget, gint* minimal_width, gint* natural_width);
static void zoomcallib_get_preferred_height(GtkWidget* widget, gint* minimal_height, gint* natural_height);
static void zoomcallib_size_allocate(GtkWidget* widget, GtkAllocation* allocation);
static void zoomcallib_realize(GtkWidget* widget);
static auto zoomcallib_draw(GtkWidget* widget, cairo_t* cr) -> gboolean;
// static void zoomcallib_destroy(GtkObject* object);
void zoomcallib_set_val(ZoomCallib* callib, gint val) {
callib->val = val;
if (gtk_widget_is_drawable(GTK_WIDGET(callib))) {
gtk_widget_queue_draw(GTK_WIDGET(callib));
}
}
auto zoomcallib_new() -> GtkWidget* { return GTK_WIDGET(g_object_new(zoomcallib_get_type(), nullptr)); }
static void zoomcallib_class_init(ZoomCallibClass* klass) {
GtkWidgetClass* widget_class = nullptr;
widget_class = reinterpret_cast<GtkWidgetClass*>(klass);
widget_class->realize = zoomcallib_realize;
widget_class->size_allocate = zoomcallib_size_allocate;
widget_class->draw = zoomcallib_draw;
widget_class->get_preferred_width = zoomcallib_get_preferred_width;
widget_class->get_preferred_height = zoomcallib_get_preferred_height;
}
static void zoomcallib_init(ZoomCallib* zc) { zc->val = 72; }
static void zoomcallib_get_preferred_width(GtkWidget* widget, gint* minimal_width, gint* natural_width) {
*minimal_width = *natural_width = 200;
}
static void zoomcallib_get_preferred_height(GtkWidget* widget, gint* minimal_height, gint* natural_height) {
*minimal_height = *natural_height = 75;
}
static void zoomcallib_size_allocate(GtkWidget* widget, GtkAllocation* allocation) {
g_return_if_fail(widget != nullptr);
g_return_if_fail(IS_ZOOM_CALLIB(widget));
g_return_if_fail(allocation != nullptr);
gtk_widget_set_allocation(widget, allocation);
if (gtk_widget_get_realized(widget)) {
gdk_window_move_resize(gtk_widget_get_window(widget), allocation->x, allocation->y, allocation->width,
allocation->height);
}
}
static void zoomcallib_realize(GtkWidget* widget) {
GdkWindowAttr attributes;
GtkAllocation allocation;
g_return_if_fail(widget != nullptr);
g_return_if_fail(IS_ZOOM_CALLIB(widget));
gtk_widget_set_realized(widget, true);
attributes.window_type = GDK_WINDOW_CHILD;
gtk_widget_get_allocation(widget, &allocation);
attributes.x = allocation.x;
attributes.y = allocation.y;
attributes.width = allocation.width;
attributes.height = allocation.height;
attributes.wclass = GDK_INPUT_OUTPUT;
attributes.event_mask = gtk_widget_get_events(widget) | GDK_EXPOSURE_MASK;
gint attributes_mask = GDK_WA_X | GDK_WA_Y;
gtk_widget_set_window(widget, gdk_window_new(gtk_widget_get_parent_window(widget), &attributes, attributes_mask));
gdk_window_set_user_data(gtk_widget_get_window(widget), widget);
}
static auto zoomcallib_draw(GtkWidget* widget, cairo_t* cr) -> gboolean {
if (!IS_ZOOM_CALLIB(widget)) {
g_message("zoomcallib_draw without a ZoomCallib");
}
cairo_text_extents_t extents;
GtkAllocation allocation;
cairo_set_source_rgb(cr, 1, 1, 1);
cairo_paint(cr);
gtk_widget_get_allocation(widget, &allocation);
gdouble hafCm = (ZOOM_CALLIB(widget)->val / 2.54) / 2;
int h = allocation.height;
int height = 50;
if (h < height) {
height = allocation.height - 10;
}
cairo_select_font_face(cr, "Serif", CAIRO_FONT_SLANT_NORMAL, CAIRO_FONT_WEIGHT_BOLD);
cairo_set_font_size(cr, 13);
auto cx = [x_base = 2, hafCm](int i) { return x_base + i * hafCm; };
for (int i = 0; cx(i) < allocation.width; ++i) {
gdouble x = cx(i);
int y = 0;
if (i % 2 == 0) {
cairo_set_source_rgb(cr, 0, 0, 0);
y = height - 3;
} else {
cairo_set_source_rgb(cr, 0.5, 0.5, 0.5);
y = height - 17;
}
cairo_rectangle(cr, x, 2 + h - y, 1, y);
cairo_fill(cr);
if (i % 2 == 0 && i != 0 && x < allocation.width - 20) {
cairo_set_source_rgb(cr, 0, 0, 0);
char* txt = g_strdup_printf("%i", i / 2);
cairo_text_extents(cr, txt, &extents);
cairo_move_to(cr, x - extents.width / 2, h - y - 3);
cairo_show_text(cr, txt);
g_free(txt);
}
}
return true;
}
| 4,905
|
C++
|
.cpp
| 112
| 38.1875
| 118
| 0.672352
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,541
|
PageTypeSelectionMenuBase.cpp
|
xournalpp_xournalpp/src/core/gui/menus/PageTypeSelectionMenuBase.cpp
|
#include "PageTypeSelectionMenuBase.h"
#include <algorithm> // for find_if
#include <iterator>
#include <memory>
#include <vector>
#include <glib-object.h> // for G_CALLBACK, g_sig...
#include "control/pagetype/PageTypeHandler.h" // for PageTypeInfo, Pag...
#include "control/settings/PageTemplateSettings.h" // for PageTemplateSettings
#include "control/settings/Settings.h" // for Settings
#include "util/raii/GVariantSPtr.h"
namespace {
std::optional<PageType> getInitiallySelectedPageType(const Settings* settings) {
if (settings) {
PageTemplateSettings model;
model.parse(settings->getPageTemplate());
return model.getPageInsertType();
}
return std::nullopt;
}
/**
* @brief Returns the action target value associated to the given page type.
*/
size_t findIndex(PageTypeHandler* types, const std::optional<PageType>& pt) {
auto find_index_of = [](const std::vector<std::unique_ptr<PageTypeInfo>>& types, const PageType& pt) {
auto it = std::find_if(types.begin(), types.end(), [&pt](const auto& info) { return info->page == pt; });
return it != types.end() ? static_cast<size_t>(std::distance(types.begin(), it)) :
PageTypeSelectionMenuBase::COPY_CURRENT_PLACEHOLDER;
};
return pt ? (pt->isSpecial() ?
find_index_of(types->getSpecialPageTypes(), pt.value()) + types->getPageTypes().size() :
find_index_of(types->getPageTypes(), pt.value())) :
PageTypeSelectionMenuBase::COPY_CURRENT_PLACEHOLDER;
}
GSimpleAction* createPageTypeSelectionAction(PageTypeHandler* types, const std::optional<PageType>& pt,
const std::string_view& actionName) {
size_t index = findIndex(types, pt);
return g_simple_action_new_stateful(actionName.data(), G_VARIANT_TYPE_UINT64, g_variant_new_uint64(index));
}
}; // namespace
PageTypeSelectionMenuBase::PageTypeSelectionMenuBase(PageTypeHandler* typesHandler, const Settings* settings,
const std::string_view& actionName):
selectedPT(getInitiallySelectedPageType(settings)),
typeSelectionAction(createPageTypeSelectionAction(typesHandler, selectedPT, actionName), xoj::util::adopt),
types(typesHandler) {
g_signal_connect(G_OBJECT(typeSelectionAction.get()), "change-state", G_CALLBACK(changeSelectionCallback), this);
// The GAction is not yet added to any GActionMap/GActionGroup - do it in derived classes
}
void PageTypeSelectionMenuBase::changeSelectionCallback(GSimpleAction* ga, GVariant* parameter,
PageTypeSelectionMenuBase* self) {
if (g_variant_equal(parameter, xoj::util::GVariantSPtr(g_action_get_state(G_ACTION(ga)), xoj::util::adopt).get())) {
return;
}
g_simple_action_set_state(ga, parameter);
auto id = g_variant_get_uint64(parameter);
const auto& types = self->types;
const auto& genTypes = types->getPageTypes();
const auto& specialTypes = types->getSpecialPageTypes();
PageTypeInfo* info = nullptr;
if (id < genTypes.size()) {
info = genTypes[id].get();
} else if (id < genTypes.size() + specialTypes.size()) {
info = specialTypes[id - genTypes.size()].get();
} // The "Copy current page" type has id == npos
self->selectedPT = info ? std::make_optional(info->page) : std::nullopt;
self->entrySelected(info);
}
void PageTypeSelectionMenuBase::setSelected(const std::optional<PageType>& selected) {
if (this->selectedPT != selected) {
size_t index = findIndex(types, selected);
g_simple_action_set_state(typeSelectionAction.get(), g_variant_new_uint64(index));
this->selectedPT = selected;
}
}
| 3,853
|
C++
|
.cpp
| 73
| 45.150685
| 120
| 0.669854
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,542
|
PageTypeSelectionPopover.cpp
|
xournalpp_xournalpp/src/core/gui/menus/popoverMenus/PageTypeSelectionPopover.cpp
|
#include "PageTypeSelectionPopover.h"
#include <memory> // for unique_ptr
#include <string> // for string
#include <glib.h>
#include <gtk/gtkactionable.h>
#include "control/PageBackgroundChangeController.h"
#include "control/pagetype/PageTypeHandler.h" // for PageTypeInfo
#include "gui/CreatePreviewImage.h"
#include "gui/menus/StaticAssertActionNamespace.h"
#include "model/PageType.h" // for PageType
#include "util/Assert.h"
#include "util/GListView.h"
#include "util/GtkUtil.h"
#include "util/Util.h"
#include "util/gtk4_helper.h" // for gtk_box_append
#include "util/i18n.h" // for _
#include "util/raii/GObjectSPtr.h"
#include "util/raii/GVariantSPtr.h"
namespace {
static constexpr auto PAGE_TYPES_PER_ROW = 4;
static constexpr auto G_ACTION_NAMESPACE = "win.";
static constexpr auto SELECTION_ACTION_NAME = "select-page-type-of-new-page";
GtkWidget* createEntryWithoutPreview(const char* label, size_t entryNb, const std::string_view& prefixedActionName) {
GtkWidget* button = gtk_toggle_button_new();
GtkWidget* labelWidget = gtk_label_new(label);
gtk_label_set_wrap_mode(GTK_LABEL(labelWidget), PANGO_WRAP_WORD);
gtk_label_set_wrap(GTK_LABEL(labelWidget), true);
gtk_label_set_justify(GTK_LABEL(labelWidget), GTK_JUSTIFY_CENTER);
gtk_label_set_max_width_chars(GTK_LABEL(labelWidget), 1);
gtk_widget_set_size_request(labelWidget, xoj::helper::PREVIEW_WIDTH, xoj::helper::PREVIEW_HEIGHT);
gtk_button_set_child(GTK_BUTTON(button), labelWidget);
gtk_actionable_set_action_name(GTK_ACTIONABLE(button), prefixedActionName.data());
gtk_actionable_set_action_target_value(GTK_ACTIONABLE(button), xoj::util::makeGVariantSPtr(entryNb).get());
xoj::util::gtk::setToggleButtonUnreleasable(GTK_TOGGLE_BUTTON(button));
return button;
}
GtkGrid* createEmptyGrid() {
GtkGrid* grid = GTK_GRID(gtk_grid_new());
gtk_grid_set_column_homogeneous(grid, true);
gtk_grid_set_row_homogeneous(grid, true);
gtk_grid_set_column_spacing(grid, 10);
gtk_grid_set_row_spacing(grid, 10);
gtk_widget_set_margin_start(GTK_WIDGET(grid), 10);
gtk_widget_set_margin_end(GTK_WIDGET(grid), 10);
return grid;
}
/**
* @brief Create a togglebutton containing a miniature of the given (standard) page type
* The toggle button is initialized to follow a GAction with the given action name and target value entryNb.
* The returned widget is a floating ref.
*/
GtkWidget* createEntryWithPreview(const PageTypeInfo* pti, size_t entryNb, const std::string_view& prefixedActionName) {
GtkWidget* button = gtk_toggle_button_new();
// // Use to restore labels in the menu
// GtkWidget* label = gtk_box_new(GTK_ORIENTATION_VERTICAL, 4);
// gtk_box_append(GTK_BOX(label), createPreviewImage(*pti));
// gtk_box_append(GTK_BOX(label), gtk_label_new(pti->name.c_str()));
// gtk_button_set_child(GTK_BUTTON(button), label);
GtkWidget* preview = xoj::helper::createPreviewImage(pti->page);
gtk_widget_set_tooltip_text(preview, pti->name.c_str());
gtk_button_set_child(GTK_BUTTON(button), preview); // takes ownership of preview
gtk_actionable_set_action_name(GTK_ACTIONABLE(button), prefixedActionName.data());
gtk_actionable_set_action_target_value(GTK_ACTIONABLE(button), xoj::util::makeGVariantSPtr(entryNb).get());
xoj::util::gtk::setToggleButtonUnreleasable(GTK_TOGGLE_BUTTON(button));
return button;
}
/**
* @brief Create a grid containing a miniature for each one the given (standard) page types
* The returned widget is a floating ref.
*/
GtkWidget* createPreviewGrid(const std::vector<std::unique_ptr<PageTypeInfo>>& pageTypes,
const std::string_view& prefixedActionName) {
GtkGrid* grid = createEmptyGrid();
gtk_widget_set_margin_top(GTK_WIDGET(grid), 10);
size_t n = 0;
int gridX = 0;
int gridY = 0;
for (const auto& pageInfo: pageTypes) {
// Special page types do not get a preview
xoj_assert(!pageInfo->page.isSpecial());
auto* entry = createEntryWithPreview(pageInfo.get(), n++, prefixedActionName);
if (gridX >= PAGE_TYPES_PER_ROW) {
gridX = 0;
gridY++;
}
gtk_grid_attach(grid, entry, gridX, gridY, 1, 1);
gridX++;
}
return GTK_WIDGET(grid);
}
}; // namespace
PageTypeSelectionPopover::PageTypeSelectionPopover(PageTypeHandler* typesHandler,
PageBackgroundChangeController* controller, const Settings* settings,
GtkApplicationWindow* win):
PageTypeSelectionMenuBase(typesHandler, settings, SELECTION_ACTION_NAME), controller(controller) {
static_assert(is_action_namespace_match<decltype(win)>(G_ACTION_NAMESPACE));
g_action_map_add_action(G_ACTION_MAP(win), G_ACTION(typeSelectionAction.get()));
controller->setPageTypeForNewPages(this->selectedPT);
}
GtkWidget* PageTypeSelectionPopover::createPopover() const {
GtkWidget* popover = gtk_popover_new();
// Todo(cpp20): constexpr this
std::string prefixedActionName = G_ACTION_NAMESPACE;
prefixedActionName += SELECTION_ACTION_NAME;
GtkBox* box = GTK_BOX(gtk_box_new(GTK_ORIENTATION_VERTICAL, 0));
gtk_popover_set_child(GTK_POPOVER(popover), GTK_WIDGET(box));
gtk_box_append(box, createPreviewGrid(types->getPageTypes(), prefixedActionName));
gtk_box_append(box, gtk_separator_new(GTK_ORIENTATION_HORIZONTAL));
GtkGrid* grid = createEmptyGrid();
int gridX = 0;
// Create a special entry for copying the current page's background
// It has index == npos
gtk_grid_attach(grid, createEntryWithoutPreview(_("Copy current background"), npos, prefixedActionName), gridX++, 0,
1, 1);
// The indices of special page types start after the normal page types'
size_t n = types->getPageTypes().size();
for (const auto& pageInfo: types->getSpecialPageTypes()) {
gtk_grid_attach(grid, createEntryWithoutPreview(pageInfo->name.c_str(), n++, prefixedActionName), gridX++, 0, 1,
1);
}
while (gridX < PAGE_TYPES_PER_ROW) {
// Add empty cells to the grid so the buttons don't get extended
gtk_grid_attach(grid, gtk_label_new(""), gridX++, 0, 1, 1);
}
gtk_box_append(box, GTK_WIDGET(grid));
gtk_box_append(box, gtk_separator_new(GTK_ORIENTATION_HORIZONTAL));
GtkWidget* applyToCurrentPageButton = gtk_button_new_with_label(_("Apply to current page"));
g_signal_connect(applyToCurrentPageButton, "clicked", G_CALLBACK(+[](GtkWidget*, gpointer d) {
auto self = static_cast<const PageTypeSelectionPopover*>(d);
if (self->selectedPT) {
self->controller->changeCurrentPageBackground(self->selectedPT.value());
}
}),
const_cast<PageTypeSelectionPopover*>(this));
gtk_box_append(box, applyToCurrentPageButton);
// We cannot "Apply to current page" if no page type is selected...
gtk_widget_set_sensitive(applyToCurrentPageButton, this->selectedPT.has_value());
g_signal_connect_object(this->typeSelectionAction.get(), "notify::state",
G_CALLBACK(+[](GObject* a, GParamSpec*, gpointer btn) {
xoj::util::GVariantSPtr state(g_action_get_state(G_ACTION(a)), xoj::util::adopt);
gtk_widget_set_sensitive(GTK_WIDGET(btn), getGVariantValue<size_t>(state.get()) !=
COPY_CURRENT_PLACEHOLDER);
}),
applyToCurrentPageButton, GConnectFlags(0));
GtkWidget* button = gtk_button_new_with_label(_("Apply to all pages"));
g_signal_connect(button, "clicked", G_CALLBACK(+[](GtkWidget*, gpointer d) {
auto self = static_cast<const PageTypeSelectionPopover*>(d);
if (self->selectedPT) {
self->controller->applyBackgroundToAllPages(self->selectedPT.value());
} else {
self->controller->applyCurrentPageBackgroundToAll();
}
}),
const_cast<PageTypeSelectionPopover*>(this));
gtk_box_append(box, button);
gtk_widget_show_all(GTK_WIDGET(box));
return popover;
}
void PageTypeSelectionPopover::entrySelected(const PageTypeInfo*) {
this->controller->setPageTypeForNewPages(this->selectedPT);
}
| 8,698
|
C++
|
.cpp
| 161
| 45.496894
| 120
| 0.666118
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,543
|
PageTypeSelectionPopoverGridOnly.cpp
|
xournalpp_xournalpp/src/core/gui/menus/popoverMenus/PageTypeSelectionPopoverGridOnly.cpp
|
#include "PageTypeSelectionPopoverGridOnly.h"
#include <memory> // for unique_ptr
#include <string> // for string
#include <glib.h>
#include <gtk/gtkactionable.h>
#include "control/pagetype/PageTypeHandler.h" // for PageTypeInfo
#include "gui/CreatePreviewImage.h"
#include "gui/dialog/PageTemplateDialog.h"
#include "model/PageType.h" // for PageType
#include "util/Assert.h"
#include "util/raii/GVariantSPtr.h"
namespace {
static constexpr auto PAGE_TYPES_PER_ROW = 4;
static constexpr auto G_ACTION_NAMESPACE = "popover";
static constexpr auto SELECTION_ACTION_NAME = "select-page-type-template";
GtkWidget* createPreviewGrid(const std::vector<std::unique_ptr<PageTypeInfo>>& pageTypes,
const std::string_view& prefixedActionName) {
/*
* Todo(gtk4): replace the GtkMenu with a GtkPopover, using PageTypeSelectionPopover::createPreviewGrid instead.
* Note that GtkPopover is no good with GTK 3, as the popover gets cropped to the dialog window (so part of it is
* not displayed). GtkMenus don't have this restriction but are removed in GTK 4. Popovers in GTK 4 do not have this
* restriction.
*/
GtkMenu* gtkMenu = GTK_MENU(gtk_menu_new());
size_t n = 0;
unsigned int gridX = 0;
unsigned int gridY = 0;
for (const auto& pageInfo: pageTypes) {
// Special page types do not get a preview
xoj_assert(!pageInfo->page.isSpecial());
auto* entry = gtk_check_menu_item_new();
gtk_check_menu_item_set_draw_as_radio(GTK_CHECK_MENU_ITEM(entry), true);
gtk_actionable_set_action_name(GTK_ACTIONABLE(entry), prefixedActionName.data());
gtk_actionable_set_action_target_value(GTK_ACTIONABLE(entry), xoj::util::makeGVariantSPtr(n++).get());
GtkWidget* preview = xoj::helper::createPreviewImage(pageInfo->page);
gtk_widget_set_tooltip_text(preview, pageInfo->name.c_str());
gtk_container_add(GTK_CONTAINER(entry), preview); // takes ownership of preview
if (gridX >= PAGE_TYPES_PER_ROW) {
gridX = 0;
gridY++;
}
gtk_menu_attach(gtkMenu, entry, gridX, gridX + 1, gridY, gridY + 1);
gridX++;
}
return GTK_WIDGET(gtkMenu);
}
}; // namespace
PageTypeSelectionPopoverGridOnly::PageTypeSelectionPopoverGridOnly(PageTypeHandler* typesHandler,
const Settings* settings,
xoj::popup::PageTemplateDialog* parent):
PageTypeSelectionMenuBase(typesHandler, settings, SELECTION_ACTION_NAME),
parent(parent),
popover(createPopover()) {
xoj::util::GObjectSPtr<GSimpleActionGroup> group(g_simple_action_group_new(), xoj::util::adopt);
g_action_map_add_action(G_ACTION_MAP(group.get()), G_ACTION(typeSelectionAction.get()));
gtk_widget_insert_action_group(GTK_WIDGET(parent->getWindow()), G_ACTION_NAMESPACE, G_ACTION_GROUP(group.get()));
}
xoj::util::WidgetSPtr PageTypeSelectionPopoverGridOnly::createPopover() {
// Todo(cpp20): constexpr this
std::string prefixedActionName = G_ACTION_NAMESPACE;
prefixedActionName += ".";
prefixedActionName += SELECTION_ACTION_NAME;
xoj::util::WidgetSPtr popover(createPreviewGrid(types->getPageTypes(), prefixedActionName), xoj::util::adopt);
gtk_widget_show_all(popover.get());
return popover;
}
void PageTypeSelectionPopoverGridOnly::entrySelected(const PageTypeInfo* info) {
xoj_assert(info);
parent->changeCurrentPageBackground(info);
}
| 3,585
|
C++
|
.cpp
| 70
| 44.028571
| 120
| 0.689891
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,544
|
ToolbarSelectionSubmenu.cpp
|
xournalpp_xournalpp/src/core/gui/menus/menubar/ToolbarSelectionSubmenu.cpp
|
#include "ToolbarSelectionSubmenu.h"
#include <algorithm>
#include <string> // for operator==, string
#include <glib-object.h> // for G_CALLBACK, g_sig...
#include "control/settings/Settings.h" // for Settings
#include "gui/MainWindow.h" // for MainWindow
#include "gui/menus/StaticAssertActionNamespace.h"
#include "gui/toolbarMenubar/ToolMenuHandler.h" // for ToolMenuHandler
#include "gui/toolbarMenubar/model/ToolbarData.h" // for ToolbarData
#include "gui/toolbarMenubar/model/ToolbarModel.h" // for ToolbarModel
#include "Menubar.h"
namespace {
constexpr auto G_ACTION_NAMESPACE = "win.";
constexpr auto G_ACTION_NAME = "select-toolbar";
/// id from ui/mainmenubar.xml
constexpr auto SUBMENU_ID = "menuViewToolbar";
auto createToolbarSelectionMenuItem(const ToolbarData* toolbarData) {
std::string action = G_ACTION_NAMESPACE;
action += G_ACTION_NAME;
action += "('";
action += toolbarData->getId();
action += "')";
return xoj::util::GObjectSPtr<GMenuItem>(g_menu_item_new(toolbarData->getName().c_str(), action.c_str()),
xoj::util::adopt);
}
void toolbarSelectionMenuChangeStateCallback(GSimpleAction* ga, GVariant* parameter, MainWindow* window) {
g_simple_action_set_state(ga, parameter);
gsize l = 0;
const char* p = g_variant_get_string(parameter, &l);
std::string toolbarId(p, l);
window->toolbarSelected(toolbarId);
}
}; // namespace
ToolbarSelectionSubmenu::ToolbarSelectionSubmenu(MainWindow* win, Settings* settings, ToolMenuHandler* toolbar):
gAction(g_simple_action_new_stateful(G_ACTION_NAME, G_VARIANT_TYPE_STRING,
g_variant_new_string(settings->getSelectedToolbar().c_str())),
xoj::util::adopt) {
const auto& toolbars = toolbar->getModel()->getToolbars();
auto it = toolbars.begin();
this->stockConfigurationsSection.reset(g_menu_new(), xoj::util::adopt);
for (; it != toolbars.end() && (*it)->isPredefined(); ++it) {
g_menu_append_item(this->stockConfigurationsSection.get(), createToolbarSelectionMenuItem(it->get()).get());
}
this->customConfigurationsSection.reset(g_menu_new(), xoj::util::adopt);
for (; it != toolbars.end(); ++it) {
g_menu_append_item(this->customConfigurationsSection.get(), createToolbarSelectionMenuItem(it->get()).get());
}
g_signal_connect(G_OBJECT(gAction.get()), "change-state", G_CALLBACK(toolbarSelectionMenuChangeStateCallback), win);
static_assert(is_action_namespace_match<decltype(win)>(G_ACTION_NAMESPACE));
g_action_map_add_action(G_ACTION_MAP(win->getWindow()), G_ACTION(gAction.get()));
}
ToolbarSelectionSubmenu::~ToolbarSelectionSubmenu() = default;
void ToolbarSelectionSubmenu::setDisabled(bool disabled) { g_simple_action_set_enabled(gAction.get(), !disabled); }
void ToolbarSelectionSubmenu::addToMenubar(Menubar& menubar) {
GMenu* submenu = menubar.get<GMenu>(SUBMENU_ID, [](auto* p) { return G_MENU(p); });
g_menu_prepend_section(submenu, nullptr, G_MENU_MODEL(customConfigurationsSection.get()));
g_menu_prepend_section(submenu, nullptr, G_MENU_MODEL(stockConfigurationsSection.get()));
}
void ToolbarSelectionSubmenu::update(ToolMenuHandler* toolbarHandler, const ToolbarData* tb) {
const auto& toolbars = toolbarHandler->getModel()->getToolbars();
// The first half stockConfigurationsSection of the menu has already been generated: fast forward to the first
// custom config
auto it = std::find_if_not(toolbars.begin(), toolbars.end(), [](const auto& d) { return d->isPredefined(); });
g_menu_remove_all(this->customConfigurationsSection.get());
for (; it != toolbars.end(); ++it) {
g_menu_append_item(this->customConfigurationsSection.get(), createToolbarSelectionMenuItem(it->get()).get());
}
// Does not fire a "change-state" signal
g_simple_action_set_state(gAction.get(), g_variant_new_string(tb ? tb->getId().c_str() : ""));
}
| 4,021
|
C++
|
.cpp
| 70
| 52.271429
| 120
| 0.705823
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,545
|
Menubar.cpp
|
xournalpp_xournalpp/src/core/gui/menus/menubar/Menubar.cpp
|
#include "Menubar.h"
#include "control/Control.h"
#include "gui/GladeSearchpath.h"
#include "gui/MainWindow.h"
#include "util/Assert.h"
#include "util/XojMsgBox.h"
#include "util/i18n.h"
#include "util/raii/GVariantSPtr.h"
#include "PageTypeSubmenu.h"
#include "PluginsSubmenu.h"
#include "RecentDocumentsSubmenu.h"
#include "ToolbarSelectionSubmenu.h"
#include "config-features.h" // for ENABLE_PLUGINS
constexpr auto MENU_XML_FILE = "mainmenubar.xml";
constexpr auto MENU_ID = "menubar";
constexpr auto UNDO_REDO_SECTION_ID = "sectionUndoRedo";
Menubar::Menubar() = default;
Menubar::~Menubar() noexcept = default;
/// @brief Recursively removes all items with attribute "class" with value classname
static void removeItemsWithClass(GMenu* menu, const char* classname) {
int N = g_menu_model_get_n_items(G_MENU_MODEL(menu));
for (int n = 0; n < N; ++n) {
xoj::util::GVariantSPtr c(
g_menu_model_get_item_attribute_value(G_MENU_MODEL(menu), n, "class", G_VARIANT_TYPE_STRING),
xoj::util::adopt);
if (c && std::string_view(g_variant_get_string(c.get(), nullptr)) == classname) {
g_menu_remove(menu, n--);
N--;
} else {
xoj::util::GObjectSPtr<GMenuLinkIter> it(g_menu_model_iterate_item_links(G_MENU_MODEL(menu), n),
xoj::util::adopt);
while (g_menu_link_iter_next(it.get())) {
xoj::util::GObjectSPtr<GMenuModel> sub(g_menu_link_iter_get_value(it.get()), xoj::util::adopt);
if (sub && G_IS_MENU(sub.get())) {
removeItemsWithClass(G_MENU(sub.get()), classname);
}
}
}
}
}
void Menubar::populate(const GladeSearchpath* gladeSearchPath, MainWindow* win) {
builder.reset(gtk_builder_new(), xoj::util::adopt);
auto filepath = gladeSearchPath->findFile("", MENU_XML_FILE);
GError* error = nullptr;
if (!gtk_builder_add_from_file(builder.get(), filepath.u8string().c_str(), &error)) {
std::string msg = FS(_F("Error loading menubar XML file (try to load \"{1}\")") % filepath.u8string());
if (error != nullptr) {
msg += "\n";
msg += error->message;
g_error_free(error);
}
XojMsgBox::showErrorToUser(nullptr, msg);
return;
}
menu = G_MENU_MODEL(gtk_builder_get_object(builder.get(), MENU_ID));
Control* ctrl = win->getControl();
recentDocumentsSubmenu = std::make_unique<RecentDocumentsSubmenu>(ctrl, GTK_APPLICATION_WINDOW(win->getWindow()));
toolbarSelectionSubmenu =
std::make_unique<ToolbarSelectionSubmenu>(win, ctrl->getSettings(), win->getToolMenuHandler());
pageTypeSubmenu = std::make_unique<PageTypeSubmenu>(ctrl->getPageTypes(), ctrl->getPageBackgroundChangeController(),
ctrl->getSettings(), GTK_APPLICATION_WINDOW(win->getWindow()));
#ifdef ENABLE_PLUGINS
pluginsSubmenu =
std::make_unique<PluginsSubmenu>(ctrl->getPluginController(), GTK_APPLICATION_WINDOW(win->getWindow()));
#endif
forEachSubmenu([&](auto& subm) { subm.addToMenubar(*this); });
if (!ctrl->getAudioController()) {
removeItemsWithClass(G_MENU(menu), "audio");
}
undoRedoSection = G_MENU(gtk_builder_get_object(builder.get(), UNDO_REDO_SECTION_ID));
}
void Menubar::setUndoDescription(const std::string& description) {
xoj_assert(undoRedoSection);
g_menu_remove(undoRedoSection, 0);
g_menu_prepend(undoRedoSection, description.c_str(), "win.undo");
}
void Menubar::setRedoDescription(const std::string& description) {
xoj_assert(undoRedoSection);
g_menu_remove(undoRedoSection, 1);
g_menu_append(undoRedoSection, description.c_str(), "win.redo");
}
void Menubar::setDisabled(bool disabled) {
forEachSubmenu([&](auto& subm) { subm.setDisabled(disabled); });
}
| 3,958
|
C++
|
.cpp
| 84
| 39.845238
| 120
| 0.65249
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,546
|
RecentDocumentsSubmenu.cpp
|
xournalpp_xournalpp/src/core/gui/menus/menubar/RecentDocumentsSubmenu.cpp
|
#include "RecentDocumentsSubmenu.h"
#include <string> // for string, allocator, operator+
#include <gio/gio.h> // for GMenu
#include "control/Control.h"
#include "control/RecentManager.h"
#include "gui/menus/StaticAssertActionNamespace.h"
#include "util/Assert.h"
#include "util/PathUtil.h" // for fromUri, toUri, hasPdfFileExt
#include "util/PlaceholderString.h" // for PlaceholderString
#include "util/StringUtils.h" // for replace_pair, StringUtils
#include "util/TinyVector.h" // for TinyVector
#include "util/i18n.h" // for FS, FORMAT_STR, C_F
#include "Menubar.h"
namespace {
constexpr auto SUBMENU_ID = "menuFileRecent";
constexpr auto G_ACTION_NAMESPACE = "win.";
constexpr auto OPEN_ACTION_NAME = "open-file-at";
constexpr auto REMOVE_ACTION_NAME = "remove-file-at";
/**
* @brief For a disable placeholder saying "No recent files"
* To disable a GMenu entry, give it an action name that does not correspond to any GAction
*/
constexpr auto DISABLED_ACTION_NAME = "always-disabled-action";
constexpr auto CLEAR_LIST_ACTION_NAME = "clear-recent-files";
void recentManagerChangedCallback(GtkRecentManager* /*manager*/, RecentDocumentsSubmenu* recentDocsSubmenu) {
recentDocsSubmenu->updateMenu();
}
void clearRecentFilesCallback(GSimpleAction*, GVariant*, gpointer) { RecentManager::clearRecentFiles(); }
auto createRecentMenuItem(const GtkRecentInfo* info, size_t i) {
std::string display_name = gtk_recent_info_get_display_name(const_cast<GtkRecentInfo*>(info));
// escape underscore
StringUtils::replaceAllChars(display_name, {replace_pair('_', "__")});
std::string label = FS(FORMAT_STR("{1}. {2}") % (i + 1) % display_name);
std::string action = G_ACTION_NAMESPACE;
action += OPEN_ACTION_NAME;
action += "(uint64 ";
action += std::to_string(i);
action += ")";
return xoj::util::GObjectSPtr<GMenuItem>(g_menu_item_new(label.c_str(), action.c_str()), xoj::util::adopt);
}
auto createRemoveMenuItem(const GtkRecentInfo* info, size_t i) {
std::string display_name = gtk_recent_info_get_display_name(const_cast<GtkRecentInfo*>(info));
// escape underscore
StringUtils::replaceAllChars(display_name, {replace_pair('_', "__")});
std::string label =
FS(FORMAT_STR("{1}. {2} {3}") % (i + 1) %
C_("The selected document will be removed from the recent files list", "Dismiss") % display_name);
std::string action = G_ACTION_NAMESPACE;
action += REMOVE_ACTION_NAME;
action += "(uint64 ";
action += std::to_string(i);
action += ")";
return xoj::util::GObjectSPtr<GMenuItem>(g_menu_item_new(label.c_str(), action.c_str()), xoj::util::adopt);
}
template <typename container>
auto createRecentMenu(const container& recentFiles, size_t start_index) -> xoj::util::GObjectSPtr<GMenu> {
if (recentFiles.empty()) {
return nullptr;
}
GMenu* menu = g_menu_new();
for (auto& recent: recentFiles) {
g_menu_append_item(menu, createRecentMenuItem(recent.get(), start_index++).get());
}
return xoj::util::GObjectSPtr<GMenu>(menu, xoj::util::adopt);
}
template <typename container>
auto createRemoveSubmenu(const container& recentFiles, size_t start_index) -> xoj::util::GObjectSPtr<GMenu> {
if (recentFiles.empty()) {
return nullptr;
}
GMenu* menu = g_menu_new();
for (auto& recent: recentFiles) {
g_menu_append_item(menu, createRemoveMenuItem(recent.get(), start_index++).get());
}
return xoj::util::GObjectSPtr<GMenu>(menu, xoj::util::adopt);
}
auto createEmptyListPlaceholder() {
return xoj::util::GObjectSPtr<GMenuItem>(g_menu_item_new(_("No recent files"), DISABLED_ACTION_NAME),
xoj::util::adopt);
}
auto createClearListSection() {
// Todo(cpp20): constexpr this concatenation
std::string action = G_ACTION_NAMESPACE;
action += CLEAR_LIST_ACTION_NAME;
GMenu* menu = g_menu_new();
g_menu_append(menu, _("Clear list"), action.c_str());
return xoj::util::GObjectSPtr<GMenu>(menu, xoj::util::adopt);
}
} // namespace
RecentDocumentsSubmenu::RecentDocumentsSubmenu(Control* control, GtkApplicationWindow* win): control(control) {
GtkRecentManager* recentManager = gtk_recent_manager_get_default();
this->recentHandlerId = g_signal_connect(recentManager, "changed", G_CALLBACK(recentManagerChangedCallback), this);
if (!win) {
g_warning("RecentDocumentsSubmenu::RecentDocumentsSubmenu: no GtkApplicationWindow provided. Cannot push the "
"appropriate GAction.");
} else {
static_assert(is_action_namespace_match<decltype(win)>(G_ACTION_NAMESPACE));
openFileAction.reset(g_simple_action_new(OPEN_ACTION_NAME, G_VARIANT_TYPE_UINT64), xoj::util::adopt);
g_signal_connect(G_OBJECT(openFileAction.get()), "activate", G_CALLBACK(openFileCallback), this);
g_action_map_add_action(G_ACTION_MAP(win), G_ACTION(openFileAction.get()));
clearListAction.reset(g_simple_action_new(CLEAR_LIST_ACTION_NAME, nullptr), xoj::util::adopt);
g_signal_connect(G_OBJECT(clearListAction.get()), "activate", G_CALLBACK(clearRecentFilesCallback), nullptr);
g_action_map_add_action(G_ACTION_MAP(win), G_ACTION(clearListAction.get()));
removeFileAction.reset(g_simple_action_new(REMOVE_ACTION_NAME, G_VARIANT_TYPE_UINT64), xoj::util::adopt);
g_signal_connect(G_OBJECT(removeFileAction.get()), "activate", G_CALLBACK(removeFileCallback), this);
g_action_map_add_action(G_ACTION_MAP(win), G_ACTION(removeFileAction.get()));
}
}
RecentDocumentsSubmenu::~RecentDocumentsSubmenu() {
if (this->recentHandlerId) {
GtkRecentManager* recentManager = gtk_recent_manager_get_default();
g_signal_handler_disconnect(recentManager, this->recentHandlerId);
this->recentHandlerId = 0;
}
}
void RecentDocumentsSubmenu::updateMenu() {
auto fileList = RecentManager::getRecentFiles();
xoppFiles.clear();
std::transform(fileList.recentXoppFiles.begin(), fileList.recentXoppFiles.end(), std::back_inserter(xoppFiles),
[](auto& info) { return Util::fromUri(gtk_recent_info_get_uri(info.get())).value(); });
pdfFiles.clear();
std::transform(fileList.recentPdfFiles.begin(), fileList.recentPdfFiles.end(), std::back_inserter(pdfFiles),
[](auto& info) { return Util::fromUri(gtk_recent_info_get_uri(info.get())).value(); });
this->menuXoppFiles = createRecentMenu(fileList.recentXoppFiles, 0);
this->menuPdfFiles = createRecentMenu(fileList.recentPdfFiles, fileList.recentXoppFiles.size());
xoj_assert(recentFilesSubmenu);
g_menu_remove_all(recentFilesSubmenu.get());
if (this->menuXoppFiles) {
g_menu_append_section(recentFilesSubmenu.get(), nullptr, G_MENU_MODEL(this->menuXoppFiles.get()));
}
if (this->menuPdfFiles) {
g_menu_append_section(recentFilesSubmenu.get(), nullptr, G_MENU_MODEL(this->menuPdfFiles.get()));
}
if (this->menuXoppFiles || this->menuPdfFiles) {
g_menu_append_section(recentFilesSubmenu.get(), nullptr, G_MENU_MODEL(createClearListSection().get()));
}
if (!fileList.recentXoppFiles.empty() || !fileList.recentPdfFiles.empty()) {
GMenu* removeSubmenu = g_menu_new();
if (!fileList.recentXoppFiles.empty()) {
auto removeXoppMenu = createRemoveSubmenu(fileList.recentXoppFiles, 0);
g_menu_append_section(removeSubmenu,
C_("In the submenu for removing recent documents, this will display on top of the "
"list xournal++ files to separate them from PDF files",
"Xournal++ Files"),
G_MENU_MODEL(removeXoppMenu.get()));
}
if (!fileList.recentPdfFiles.empty()) {
auto removePdfMenu = createRemoveSubmenu(fileList.recentPdfFiles, fileList.recentXoppFiles.size());
g_menu_append_section(removeSubmenu,
C_("In the submenu for removing recent documents, this will display on top of the "
"list PDF files to separate them from xournal++ files",
"PDF Files"),
G_MENU_MODEL(removePdfMenu.get()));
}
GMenuItem* removeSubmenuItem =
g_menu_item_new_submenu(C_("This opens a submenu of the recent files list, and clicking on individual "
"entries in this submenu will remove it from the recent files list",
"Dismiss a single document"),
G_MENU_MODEL(removeSubmenu));
g_menu_append_item(recentFilesSubmenu.get(), removeSubmenuItem);
g_object_unref(removeSubmenu);
} else {
g_menu_append_item(recentFilesSubmenu.get(), createEmptyListPlaceholder().get());
}
}
void RecentDocumentsSubmenu::addToMenubar(Menubar& menubar) {
recentFilesSubmenu.reset(menubar.get<GMenu>(SUBMENU_ID, [](auto* p) { return G_MENU(p); }), xoj::util::ref);
updateMenu();
}
void RecentDocumentsSubmenu::setDisabled(bool disabled) {
g_simple_action_set_enabled(openFileAction.get(), !disabled);
g_simple_action_set_enabled(clearListAction.get(), !disabled);
}
void RecentDocumentsSubmenu::openFileCallback(GSimpleAction* ga, GVariant* parameter, RecentDocumentsSubmenu* self) {
auto index = g_variant_get_uint64(parameter);
auto& path =
index < self->xoppFiles.size() ? self->xoppFiles[index] : self->pdfFiles[index - self->xoppFiles.size()];
self->control->openFile(path);
}
void RecentDocumentsSubmenu::removeFileCallback(GSimpleAction* ga, GVariant* parameter, RecentDocumentsSubmenu* self) {
auto index = g_variant_get_uint64(parameter);
auto& path =
index < self->xoppFiles.size() ? self->xoppFiles[index] : self->pdfFiles[index - self->xoppFiles.size()];
RecentManager::removeRecentFileFilename(path);
self->updateMenu();
}
| 10,197
|
C++
|
.cpp
| 186
| 47.274194
| 119
| 0.674293
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,547
|
PluginsSubmenu.cpp
|
xournalpp_xournalpp/src/core/gui/menus/menubar/PluginsSubmenu.cpp
|
#include "PluginsSubmenu.h"
#include "plugin/PluginController.h"
#include "util/Assert.h"
#include "util/i18n.h"
#include "Menubar.h"
/// position of the plugin submenu, from the end of the menu bar: 1 means just before the last one (About)
static constexpr int POSITION_IN_MENUBAR_FROM_END = 1;
PluginsSubmenu::PluginsSubmenu(PluginController* pluginController, GtkApplicationWindow* win):
submenu(g_menu_new(), xoj::util::adopt) {
xoj::util::GObjectSPtr<GMenu> firstSection(g_menu_new(), xoj::util::adopt);
g_menu_append(firstSection.get(), _("Plugin Manager"), "win.plugin-manager");
g_menu_append_section(submenu.get(), nullptr, G_MENU_MODEL(firstSection.get()));
for (auto* section: pluginController->createMenuSections(win)) {
g_menu_append_section(submenu.get(), nullptr, section);
}
}
void PluginsSubmenu::setDisabled(bool disabled) {
// TODO!!
}
void PluginsSubmenu::addToMenubar(Menubar& menubar) {
GMenuModel* mainmenu = menubar.getModel();
int insertionPlace = g_menu_model_get_n_items(mainmenu) - POSITION_IN_MENUBAR_FROM_END;
xoj_assert(insertionPlace >= 0);
g_menu_insert_submenu(G_MENU(mainmenu), insertionPlace, _("Plugin"), G_MENU_MODEL(submenu.get()));
}
| 1,238
|
C++
|
.cpp
| 25
| 45.96
| 106
| 0.73112
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,548
|
PageTypeSubmenu.cpp
|
xournalpp_xournalpp/src/core/gui/menus/menubar/PageTypeSubmenu.cpp
|
#include "PageTypeSubmenu.h"
#include <memory> // for unique_ptr
#include <optional>
#include <string> // for string
#include <vector>
#include <glib-object.h> // for G_CALLBACK, g_sig...
#include "control/PageBackgroundChangeController.h"
#include "control/pagetype/PageTypeHandler.h" // for PageTypeInfo, Pag...
#include "gui/menus/StaticAssertActionNamespace.h"
#include "util/i18n.h" // for _
#include "util/raii/GVariantSPtr.h"
#include "Menubar.h"
namespace {
static constexpr auto G_ACTION_NAMESPACE = "win.";
static constexpr auto SELECTION_ACTION_NAME = "menu.pick-page-type";
static constexpr auto APPLY_ALL_ACTION_NAME = "menu.apply-current-page-type-to-all-pages";
static constexpr auto SUBMENU_ID = "menuJournalPaperBackground";
auto createPageTypesSection(const std::vector<std::unique_ptr<PageTypeInfo>>& pageTypes, size_t index) {
GMenu* menu = g_menu_new();
// Todo(c++20) constexpr this
std::string actionName = G_ACTION_NAMESPACE;
actionName += SELECTION_ACTION_NAME;
for (auto& pageInfo: pageTypes) {
xoj::util::GObjectSPtr<GMenuItem> item(g_menu_item_new(pageInfo->name.c_str(), nullptr), xoj::util::adopt);
g_menu_item_set_action_and_target_value(item.get(), actionName.c_str(),
xoj::util::makeGVariantSPtr(index++).get());
g_menu_append_item(menu, item.get());
}
return xoj::util::GObjectSPtr<GMenu>(menu, xoj::util::adopt);
}
auto createApplyToAllPagesSection() {
GMenu* menu = g_menu_new();
// Todo(c++20) constexpr this
std::string actionName = G_ACTION_NAMESPACE;
actionName += APPLY_ALL_ACTION_NAME;
g_menu_append(menu, _("Apply to all pages"), actionName.c_str());
return xoj::util::GObjectSPtr<GMenu>(menu, xoj::util::adopt);
}
}; // namespace
PageTypeSubmenu::PageTypeSubmenu(PageTypeHandler* typesHandler, PageBackgroundChangeController* controller,
const Settings* settings, GtkApplicationWindow* win):
PageTypeSelectionMenuBase(typesHandler, settings, SELECTION_ACTION_NAME),
controller(controller),
generatedPageTypesSection(createPageTypesSection(typesHandler->getPageTypes(), 0)),
specialPageTypesSection(
createPageTypesSection(typesHandler->getSpecialPageTypes(), typesHandler->getPageTypes().size())),
applyToAllPagesSection(createApplyToAllPagesSection()),
applyToAllPagesAction(g_simple_action_new(APPLY_ALL_ACTION_NAME, nullptr), xoj::util::adopt) {
this->changeCurrentPageUponCallback = true;
static_assert(is_action_namespace_match<decltype(win)>(G_ACTION_NAMESPACE));
g_action_map_add_action(G_ACTION_MAP(win), G_ACTION(typeSelectionAction.get()));
g_action_map_add_action(G_ACTION_MAP(win), G_ACTION(applyToAllPagesAction.get()));
g_signal_connect(G_OBJECT(applyToAllPagesAction.get()), "activate",
G_CALLBACK(+[](GSimpleAction*, GVariant*, PageBackgroundChangeController* controller) {
controller->applyCurrentPageBackgroundToAll();
}),
this->controller);
}
void PageTypeSubmenu::setDisabled(bool disabled) {
g_simple_action_set_enabled(typeSelectionAction.get(), !disabled);
g_simple_action_set_enabled(applyToAllPagesAction.get(), !disabled);
}
void PageTypeSubmenu::addToMenubar(Menubar& menubar) {
GMenu* submenu = menubar.get<GMenu>(SUBMENU_ID, [](auto* p) { return G_MENU(p); });
g_menu_append_section(submenu, nullptr, G_MENU_MODEL(generatedPageTypesSection.get()));
g_menu_append_section(submenu, nullptr, G_MENU_MODEL(specialPageTypesSection.get()));
g_menu_append_section(submenu, nullptr, G_MENU_MODEL(applyToAllPagesSection.get()));
}
void PageTypeSubmenu::entrySelected(const PageTypeInfo*) {
if (this->selectedPT && this->controller) {
this->controller->changeCurrentPageBackground(this->selectedPT.value());
}
}
| 3,970
|
C++
|
.cpp
| 73
| 48.054795
| 115
| 0.709827
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,549
|
Sidebar.cpp
|
xournalpp_xournalpp/src/core/gui/sidebar/Sidebar.cpp
|
#include "Sidebar.h"
#include <cstdint> // for int64_t
#include <memory> // for std::make_unique and std::make_shared
#include <string> // for string
#include <config-features.h>
#include <gdk/gdk.h> // for gdk_display_get...
#include <glib-object.h> // for G_CALLBACK, g_s...
#include <gtk/gtk.h> // for gtk_toggle_tool_button_new...
#include "control/Control.h" // for Control
#include "control/settings/Settings.h" // for Settings
#include "gui/GladeGui.h" // for GladeGui
#include "gui/sidebar/AbstractSidebarPage.h" // for AbstractSidebar...
#include "gui/sidebar/indextree/SidebarIndexPage.h" // for SidebarIndexPage
#include "model/Document.h" // for Document
#include "model/XojPage.h" // for XojPage
#include "pdf/base/XojPdfPage.h" // for XojPdfPageSPtr
#include "previews/layer/SidebarPreviewLayers.h" // for SidebarPreviewL...
#include "previews/page/SidebarPreviewPages.h" // for SidebarPreviewP...
#include "util/Util.h" // for npos
#include "util/glib_casts.h" // for closure_notify_cb
#include "util/gtk4_helper.h" //
#include "util/i18n.h" // for _, FC, _F
Sidebar::Sidebar(GladeGui* gui, Control* control): control(control) {
this->tbSelectTab = GTK_BOX(gui->get("bxSidebarTopActions"));
this->buttonCloseSidebar = gui->get("buttonCloseSidebar");
this->sidebarContents = gui->get("sidebarContents");
this->initTabs(sidebarContents);
registerListener(control);
}
void Sidebar::initTabs(GtkWidget* sidebarContents) {
addTab(std::make_unique<SidebarIndexPage>(this->control));
addTab(std::make_unique<SidebarPreviewPages>(this->control));
addTab(std::make_unique<SidebarPreviewLayers>(this->control, false));
addTab(std::make_unique<SidebarPreviewLayers>(this->control, true));
// Init toolbar with icons
size_t i = 0;
for (auto&& p: this->tabs) {
GtkWidget* btn = gtk_toggle_button_new();
p->tabButton = btn;
gtk_button_set_icon_name(GTK_BUTTON(btn), p->getIconName().c_str());
g_signal_connect_data(btn, "clicked", G_CALLBACK(&buttonClicked), new SidebarTabButton(this, i, p.get()),
xoj::util::closure_notify_cb<SidebarTabButton>, GConnectFlags(0));
gtk_widget_set_tooltip_text(btn, p->getName().c_str());
gtk_box_append(tbSelectTab, btn);
// Add widget to sidebar
gtk_widget_set_vexpand(p->getWidget(), true);
gtk_box_append(GTK_BOX(sidebarContents), p->getWidget());
i++;
}
updateVisibleTabs();
}
void Sidebar::buttonClicked(GtkButton* button, SidebarTabButton* buttonData) {
if (gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(button))) {
if (buttonData->sidebar->visibleTab != buttonData->page->getWidget()) {
buttonData->sidebar->setSelectedTab(buttonData->index);
}
} else if (buttonData->sidebar->visibleTab == buttonData->page->getWidget()) {
gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(button), true);
}
}
void Sidebar::addTab(std::unique_ptr<AbstractSidebarPage> tab) { this->tabs.push_back(std::move(tab)); }
Sidebar::~Sidebar() = default;
void Sidebar::selectPageNr(size_t page, size_t pdfPage) {
for (auto&& p: this->tabs) {
p->selectPageNr(page, pdfPage);
}
}
void Sidebar::setSelectedTab(size_t tab) {
this->visibleTab = nullptr;
size_t i = 0;
for (auto&& t: this->tabs) {
if (tab == i) {
gtk_widget_show(t->getWidget());
gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(t->tabButton), true);
this->visibleTab = t->getWidget();
this->currentTabIdx = i;
t->enableSidebar();
} else {
t->disableSidebar();
gtk_widget_hide(t->getWidget());
gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(t->tabButton), false);
}
i++;
}
}
void Sidebar::updateVisibleTabs() {
size_t i = 0;
size_t selected = npos;
for (auto&& p: this->tabs) {
gtk_widget_set_visible(GTK_WIDGET(p->tabButton), p->hasData());
if (p->hasData() && selected == npos) {
selected = i;
}
i++;
}
setSelectedTab(selected);
}
void Sidebar::setTmpDisabled(bool disabled) {
gtk_widget_set_sensitive(this->buttonCloseSidebar, !disabled);
gtk_widget_set_sensitive(GTK_WIDGET(this->tbSelectTab), !disabled);
for (auto&& t: this->tabs) {
t->setTmpDisabled(disabled);
}
gdk_display_sync(gdk_display_get_default());
}
void Sidebar::saveSize() {
GtkAllocation alloc;
gtk_widget_get_allocation(this->sidebarContents, &alloc);
this->control->getSettings()->setSidebarWidth(alloc.width);
}
size_t Sidebar::getNumberOfTabs() const { return this->tabs.size(); }
size_t Sidebar::getSelectedTab() const { return this->currentTabIdx; }
auto Sidebar::getControl() -> Control* { return this->control; }
void Sidebar::documentChanged(DocumentChangeType type) {
if (type == DOCUMENT_CHANGE_CLEARED || type == DOCUMENT_CHANGE_COMPLETE || type == DOCUMENT_CHANGE_PDF_BOOKMARKS) {
updateVisibleTabs();
}
}
SidebarTabButton::SidebarTabButton(Sidebar* sidebar, size_t index, AbstractSidebarPage* page):
sidebar(sidebar), index(index), page(page) {}
void Sidebar::layout() {
for (auto&& tab: this->tabs) {
tab->layout();
}
}
| 5,612
|
C++
|
.cpp
| 125
| 39.456
| 119
| 0.636697
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,550
|
AbstractSidebarPage.cpp
|
xournalpp_xournalpp/src/core/gui/sidebar/AbstractSidebarPage.cpp
|
#include "AbstractSidebarPage.h"
#include <gdk/gdk.h> // for gdk_cursor_new_for_display, gdk_display_get...
#include <glib-object.h> // for g_object_unref
AbstractSidebarPage::AbstractSidebarPage(Control* control): control(control) {}
AbstractSidebarPage::~AbstractSidebarPage() = default;
void AbstractSidebarPage::selectPageNr(size_t page, size_t pdfPage) {}
auto AbstractSidebarPage::getControl() -> Control* { return this->control; }
void AbstractSidebarPage::setTmpDisabled(bool disabled) {
GdkCursor* cursor = nullptr;
if (disabled) {
cursor = gdk_cursor_new_for_display(gdk_display_get_default(), GDK_WATCH);
}
if (gtk_widget_get_window(this->getWidget())) {
gdk_window_set_cursor(gtk_widget_get_window(this->getWidget()), cursor);
}
gtk_widget_set_sensitive(this->getWidget(), !disabled);
if (cursor) {
g_object_unref(cursor);
}
}
| 911
|
C++
|
.cpp
| 20
| 41.25
| 82
| 0.713961
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,551
|
SidebarPreviewPageEntry.cpp
|
xournalpp_xournalpp/src/core/gui/sidebar/previews/page/SidebarPreviewPageEntry.cpp
|
#include "SidebarPreviewPageEntry.h"
#include "control/Control.h" // for Control
#include "control/ScrollHandler.h" // for ScrollHan...
#include "control/settings/Settings.h" // for Settings
#include "gui/PagePreviewDecoration.h" // for Drawing ...
#include "gui/sidebar/previews/page/SidebarPreviewPages.h" // for SidebarPr...
#include "util/gtk4_helper.h"
SidebarPreviewPageEntry::SidebarPreviewPageEntry(SidebarPreviewPages* sidebar, const PageRef& page, size_t index):
SidebarPreviewBaseEntry(sidebar, page), sidebar(sidebar), index(index) {
if (sidebar->getControl()->getSettings()->getSidebarNumberingStyle() ==
SidebarNumberingStyle::NUMBER_BELOW_PREVIEW) {
gtk_widget_set_size_request(this->button.get(), imageWidth, imageHeight + PagePreviewDecoration::MARGIN_BOTTOM);
}
}
SidebarPreviewPageEntry::~SidebarPreviewPageEntry() {
GtkWidget* w = this->getWidget();
gtk_fixed_remove(GTK_FIXED(gtk_widget_get_parent(w)), w);
}
auto SidebarPreviewPageEntry::getRenderType() const -> PreviewRenderType { return RENDER_TYPE_PAGE_PREVIEW; }
void SidebarPreviewPageEntry::mouseButtonPressCallback() {
sidebar->getControl()->getScrollHandler()->scrollToPage(page);
sidebar->getControl()->firePageSelected(page);
}
void SidebarPreviewPageEntry::paint(cairo_t* cr) {
SidebarPreviewBaseEntry::paint(cr);
if (sidebar->getControl()->getSettings()->getSidebarNumberingStyle() == SidebarNumberingStyle::NONE) {
return;
}
drawEntryNumber(cr);
}
void SidebarPreviewPageEntry::drawEntryNumber(cairo_t* cr) {
PagePreviewDecoration::drawDecoration(cr, this, this->sidebar->getControl());
}
auto SidebarPreviewPageEntry::getHeight() const -> int {
if (sidebar->getControl()->getSettings()->getSidebarNumberingStyle() ==
SidebarNumberingStyle::NUMBER_BELOW_PREVIEW) {
return imageHeight + PagePreviewDecoration::MARGIN_BOTTOM;
}
return imageHeight;
}
void SidebarPreviewPageEntry::setIndex(size_t index) { this->index = index; }
size_t SidebarPreviewPageEntry::getIndex() const { return this->index; }
bool SidebarPreviewPageEntry::isSelected() const { return this->selected; }
double SidebarPreviewPageEntry::getZoom() const { return this->sidebar->getZoom(); }
| 2,362
|
C++
|
.cpp
| 44
| 50.045455
| 120
| 0.725932
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,552
|
SidebarPreviewPages.cpp
|
xournalpp_xournalpp/src/core/gui/sidebar/previews/page/SidebarPreviewPages.cpp
|
#include "SidebarPreviewPages.h"
#include <algorithm> // for max
#include <map> // for map
#include <memory> // for uniqu...
#include <utility> // for pair
#include <glib-object.h> // for g_obj...
#include "control/Control.h" // for Control
#include "gui/sidebar/previews/base/SidebarPreviewBaseEntry.h" // for Sideb...
#include "model/Document.h" // for Document
#include "model/PageRef.h" // for PageRef
#include "util/Assert.h" // for xoj_assert
#include "util/Util.h" // for npos
#include "util/gtk4_helper.h"
#include "util/i18n.h" // for _
#include "util/safe_casts.h" // for as_signed
#include "SidebarPreviewPageEntry.h" // for Sideb...
constexpr auto MENU_ID = "PreviewPagesContextMenu";
constexpr auto TOOLBAR_ID = "PreviewPagesToolbar";
SidebarPreviewPages::SidebarPreviewPages(Control* control):
SidebarPreviewBase(control, MENU_ID, TOOLBAR_ID), iconNameHelper(control->getSettings()) {}
SidebarPreviewPages::~SidebarPreviewPages() = default;
void SidebarPreviewPages::enableSidebar() {
SidebarPreviewBase::enableSidebar();
pageSelected(this->selectedEntry);
}
auto SidebarPreviewPages::getName() -> std::string { return _("Page Preview"); }
auto SidebarPreviewPages::getIconName() -> std::string { return this->iconNameHelper.iconName("sidebar-page-preview"); }
void SidebarPreviewPages::updatePreviews() {
this->previews.clear();
Document* doc = this->getControl()->getDocument();
doc->lock();
size_t len = doc->getPageCount();
for (size_t i = 0; i < len; i++) {
auto p = std::make_unique<SidebarPreviewPageEntry>(this, doc->getPage(i), i);
gtk_fixed_put(this->miniaturesContainer.get(), p->getWidget(), 0, 0);
this->previews.emplace_back(std::move(p));
}
doc->unlock();
layout();
}
void SidebarPreviewPages::pageSizeChanged(size_t page) {
if (page == npos || page >= this->previews.size()) {
return;
}
auto& p = this->previews[page];
p->updateSize();
p->repaint();
layout();
}
void SidebarPreviewPages::pageChanged(size_t page) {
if (page == npos || page >= this->previews.size()) {
return;
}
auto& p = this->previews[page];
p->repaint();
}
void SidebarPreviewPages::pageDeleted(size_t page) {
if (page >= previews.size()) {
return;
}
previews.erase(previews.begin() + as_signed(page));
// Unselect page, to prevent double selection displaying
unselectPage();
updateIndices();
layout();
}
void SidebarPreviewPages::pageInserted(size_t page) {
Document* doc = control->getDocument();
doc->lock();
auto p = std::make_unique<SidebarPreviewPageEntry>(this, doc->getPage(page), page);
doc->unlock();
gtk_fixed_put(this->miniaturesContainer.get(), p->getWidget(), 0, 0);
this->previews.insert(this->previews.begin() + as_signed(page), std::move(p));
// Unselect page, to prevent double selection displaying
unselectPage();
updateIndices();
layout();
}
/**
* Unselect the last selected page, if any
*/
void SidebarPreviewPages::unselectPage() {
for (auto& p: this->previews) {
p->setSelected(false);
}
}
void SidebarPreviewPages::pageSelected(size_t page) {
if (this->selectedEntry != npos && this->selectedEntry < this->previews.size()) {
this->previews[this->selectedEntry]->setSelected(false);
}
this->selectedEntry = page;
if (!this->enabled) {
return;
}
if (this->selectedEntry != npos && this->selectedEntry < this->previews.size()) {
auto& p = this->previews[this->selectedEntry];
p->setSelected(true);
scrollToPreview(this);
}
}
void SidebarPreviewPages::updateIndices() {
size_t index = 0;
for (auto& preview: this->previews) {
dynamic_cast<SidebarPreviewPageEntry*>(preview.get())->setIndex(index++);
}
}
| 4,082
|
C++
|
.cpp
| 106
| 34.254717
| 120
| 0.642477
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,553
|
SidebarPreviewLayers.cpp
|
xournalpp_xournalpp/src/core/gui/sidebar/previews/layer/SidebarPreviewLayers.cpp
|
#include "SidebarPreviewLayers.h"
#include <algorithm> // for max
#include <vector> // for vector
#include <gtk/gtk.h> // for gtk...
#include "control/Control.h" // for Con...
#include "control/layer/LayerController.h" // for Lay...
#include "gui/sidebar/previews/base/SidebarPreviewBaseEntry.h" // for Sid...
#include "model/PageRef.h" // for Pag...
#include "model/XojPage.h" // for Xoj...
#include "util/Util.h" // for npos
#include "util/gtk4_helper.h"
#include "util/i18n.h" // for _
#include "SidebarPreviewLayerEntry.h" // for Sid...
constexpr auto MENU_ID = "PreviewLayersContextMenu";
constexpr auto TOOLBAR_ID = "PreviewLayersToolbar";
SidebarPreviewLayers::SidebarPreviewLayers(Control* control, bool stacked):
SidebarPreviewBase(control, MENU_ID, TOOLBAR_ID),
lc(control->getLayerController()),
stacked(stacked),
iconNameHelper(control->getSettings()) {
LayerCtrlListener::registerListener(lc);
}
SidebarPreviewLayers::~SidebarPreviewLayers() = default;
void SidebarPreviewLayers::enableSidebar() {
SidebarPreviewBase::enableSidebar();
rebuildLayerMenu();
}
auto SidebarPreviewLayers::getName() -> std::string { return stacked ? _("Layerstack Preview") : _("Layer Preview"); }
auto SidebarPreviewLayers::getIconName() -> std::string {
const char* icon = stacked ? "sidebar-layerstack" : "sidebar-layer";
return this->iconNameHelper.iconName(icon);
}
void SidebarPreviewLayers::pageSizeChanged(size_t page) {
if (page != this->lc->getCurrentPageId() || !enabled) {
return;
}
updatePreviews();
}
void SidebarPreviewLayers::pageChanged(size_t page) {
if (page != this->lc->getCurrentPageId() || !enabled) {
return;
}
// Repaint all layer
for (auto& p: this->previews) { p->repaint(); }
}
void SidebarPreviewLayers::updatePreviews() {
if (!enabled) {
return;
}
// clear old previews
this->previews.clear();
this->selectedEntry = npos;
PageRef page = lc->getCurrentPage();
if (!page) {
return;
}
auto layerCount = page->getLayerCount();
for (auto i = layerCount + 1; i != 0;) {
--i;
std::string name = lc->getLayerNameById(i);
auto p = std::make_unique<SidebarPreviewLayerEntry>(this, page, i, name, this->stacked);
gtk_fixed_put(this->miniaturesContainer.get(), p->getWidget(), 0, 0);
this->previews.emplace_back(std::move(p));
}
layout();
updateSelectedLayer();
layerVisibilityChanged();
}
void SidebarPreviewLayers::rebuildLayerMenu() {
if (!enabled) {
return;
}
updatePreviews();
}
void SidebarPreviewLayers::layerVisibilityChanged() {
PageRef p = lc->getCurrentPage();
if (!p) {
return;
}
Layer::Index i = p->getLayerCount();
for (auto& e: this->previews) {
dynamic_cast<SidebarPreviewLayerEntry*>(e.get())->setVisibleCheckbox(p->isLayerVisible(i--));
}
updateSelectedLayer();
}
void SidebarPreviewLayers::updateSelectedLayer() {
// Layers are in reverse order (top index: 0, but bottom preview is 0)
size_t entryIndex = this->previews.size() - lc->getCurrentLayerId() - 1;
if (this->selectedEntry == entryIndex) {
return;
}
if (this->selectedEntry != npos && this->selectedEntry < this->previews.size()) {
this->previews[this->selectedEntry]->setSelected(false);
}
this->selectedEntry = entryIndex;
if (this->selectedEntry != npos && this->selectedEntry < this->previews.size()) {
auto& p = this->previews[this->selectedEntry];
p->setSelected(true);
scrollToPreview(this);
}
}
void SidebarPreviewLayers::layerSelected(Layer::Index layerId) {
if (layerId != 0) { // We can't select the background
lc->switchToLay(layerId);
updateSelectedLayer();
}
}
/**
* A layer was hidden / showed
*/
void SidebarPreviewLayers::layerVisibilityChanged(Layer::Index layerIndex, bool enabled) {
lc->setLayerVisible(layerIndex, enabled);
}
| 4,223
|
C++
|
.cpp
| 113
| 32.761062
| 118
| 0.648775
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,554
|
SidebarPreviewLayerEntry.cpp
|
xournalpp_xournalpp/src/core/gui/sidebar/previews/layer/SidebarPreviewLayerEntry.cpp
|
#include "SidebarPreviewLayerEntry.h"
#include <gdk/gdk.h> // for GdkEvent, GDK_BUTTON_PRESS, GdkEve...
#include <glib-object.h> // for G_CALLBACK, g_signal_connect, g_si...
#include "gui/Shadow.h" // for Shadow
#include "util/gtk4_helper.h"
#include "SidebarPreviewLayers.h" // for SidebarPreviewLayers
SidebarPreviewLayerEntry::SidebarPreviewLayerEntry(SidebarPreviewLayers* sidebar, const PageRef& page,
Layer::Index layerId, const std::string& layerName, bool stacked):
SidebarPreviewBaseEntry(sidebar, page),
sidebar(sidebar),
layerId(layerId),
box(gtk_box_new(GTK_ORIENTATION_VERTICAL, 4), xoj::util::adopt),
stacked(stacked) {
#if GTK_CHECK_VERSION(4, 8, 0)
cbVisible = gtk_check_button_new();
GtkWidget* lbl = gtk_label_new(layerName.c_str());
gtk_label_set_ellipsize(GTK_LABEL(lbl), PANGO_ELLIPSIZE_END);
gtk_check_button_set_child(GTK_CHECK_BUTTON(cbVisible), lbl);
#else
cbVisible = gtk_check_button_new_with_label(layerName.c_str());
#endif
callbackId = g_signal_connect(
cbVisible, "toggled", G_CALLBACK(+[](GtkCheckButton* btn, gpointer d) {
auto* self = static_cast<SidebarPreviewLayerEntry*>(d);
bool check = gtk_check_button_get_active(btn);
(dynamic_cast<SidebarPreviewLayers*>(self->sidebar))->layerVisibilityChanged(self->layerId, check);
}),
this);
gtk_widget_set_margin_start(cbVisible, Shadow::getShadowTopLeftSize());
// This doesn't really do it. gtk_widget_get_allocated_height() always returns 1...
toolbarHeight = gtk_widget_get_allocated_height(cbVisible) + Shadow::getShadowTopLeftSize() + 20;
gtk_box_append(GTK_BOX(box.get()), this->button.get());
gtk_box_append(GTK_BOX(box.get()), cbVisible);
gtk_widget_show_all(box.get());
}
SidebarPreviewLayerEntry::~SidebarPreviewLayerEntry() {
GtkWidget* w = this->getWidget();
gtk_fixed_remove(GTK_FIXED(gtk_widget_get_parent(w)), w);
}
void SidebarPreviewLayerEntry::mouseButtonPressCallback() {
(dynamic_cast<SidebarPreviewLayers*>(sidebar))->layerSelected(layerId);
}
auto SidebarPreviewLayerEntry::getRenderType() const -> PreviewRenderType {
return stacked ? RENDER_TYPE_PAGE_LAYERSTACK : RENDER_TYPE_PAGE_LAYER;
}
auto SidebarPreviewLayerEntry::getHeight() const -> int { return imageHeight + toolbarHeight; }
auto SidebarPreviewLayerEntry::getLayer() const -> Layer::Index { return layerId; }
auto SidebarPreviewLayerEntry::getWidget() const -> GtkWidget* { return this->box.get(); }
/**
* Set the value of the visible checkbox
*/
void SidebarPreviewLayerEntry::setVisibleCheckbox(bool enabled) {
g_signal_handler_block(cbVisible, callbackId);
gtk_check_button_set_active(GTK_CHECK_BUTTON(cbVisible), enabled);
g_signal_handler_unblock(cbVisible, callbackId);
}
| 2,920
|
C++
|
.cpp
| 56
| 46.339286
| 117
| 0.707514
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,555
|
SidebarLayout.cpp
|
xournalpp_xournalpp/src/core/gui/sidebar/previews/base/SidebarLayout.cpp
|
#include "SidebarLayout.h"
#include <algorithm> // for max
#include <vector> // for vector
#include <gtk/gtk.h> // for GTK_FIXED, gtk_fixed_move
#include "util/gtk4_helper.h"
#include "util/safe_casts.h" // for as_unsigned
#include "SidebarPreviewBase.h" // for SidebarPreviewBase
#include "SidebarPreviewBaseEntry.h" // for SidebarPreviewBaseEntry
class SidebarRow {
public:
explicit SidebarRow(int width) {
this->width = width;
this->currentWidth = 0;
}
~SidebarRow() { clear(); }
auto isSpaceFor(SidebarPreviewBaseEntry* p) -> bool {
if (this->list.empty()) {
return true;
}
if (this->currentWidth + p->getWidth() < width) {
return true;
}
return false;
}
void add(SidebarPreviewBaseEntry* p) {
this->list.push_back(p);
this->currentWidth += p->getWidth();
}
void clear() {
this->list.clear();
this->currentWidth = 0;
}
auto getCount() -> size_t { return this->list.size(); }
auto getWidth() const -> int { return this->currentWidth; }
auto placeAt(int y, GtkFixed* layout) -> int {
int height = 0;
int x = 0;
for (SidebarPreviewBaseEntry* p: this->list) { height = std::max(height, p->getHeight()); }
for (SidebarPreviewBaseEntry* p: this->list) {
int currentY = (height - p->getHeight()) / 2;
gtk_fixed_move(layout, p->getWidget(), x, y + currentY);
x += p->getWidth();
}
return height;
}
private:
int width;
int currentWidth;
std::vector<SidebarPreviewBaseEntry*> list;
};
void SidebarLayout::layout(SidebarPreviewBase* sidebar) {
int y = 0;
int width = 0;
int sidebarWidth = gtk_widget_get_width(sidebar->scrollableBox.get());
SidebarRow row(sidebarWidth);
GtkFixed* w = sidebar->miniaturesContainer.get();
for (auto& p: sidebar->previews) {
if (row.isSpaceFor(p.get())) {
row.add(p.get());
} else {
y += row.placeAt(y, w);
width = std::max(width, row.getWidth());
row.clear();
row.add(p.get());
}
}
if (row.getCount() != 0) {
y += row.placeAt(y, w);
width = std::max(width, row.getWidth());
row.clear();
}
gtk_widget_set_size_request(GTK_WIDGET(w), width, y);
gtk_widget_show_all(GTK_WIDGET(w));
}
| 2,465
|
C++
|
.cpp
| 74
| 26.297297
| 99
| 0.586938
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,556
|
SidebarPreviewBase.cpp
|
xournalpp_xournalpp/src/core/gui/sidebar/previews/base/SidebarPreviewBase.cpp
|
#include "SidebarPreviewBase.h"
#include <cstdlib> // for abs, size_t
#include <glib-object.h> // for g_object_ref, G_CALLBACK, g_sig...
#include <glib.h> // for g_idle_add
#include "control/Control.h" // for Control
#include "control/PdfCache.h" // for PdfCache
#include "gui/Builder.h" // for Builder
#include "gui/MainWindow.h" // for MainWindow
#include "model/Document.h" // for Document
#include "util/Util.h" // for npos
#include "util/glib_casts.h" // for wrap_for_once_v
#include "util/gtk4_helper.h"
#include "SidebarLayout.h" // for SidebarLayout
#include "SidebarPreviewBaseEntry.h" // for SidebarPreviewBaseEntry
constexpr auto XML_FILE = "sidebar.ui";
SidebarPreviewBase::SidebarPreviewBase(Control* control, const char* menuId, const char* toolbarId):
AbstractSidebarPage(control),
scrollableBox(gtk_scrolled_window_new(), xoj::util::adopt),
mainBox(gtk_box_new(GTK_ORIENTATION_VERTICAL, 0), xoj::util::adopt),
miniaturesContainer(GTK_FIXED(gtk_fixed_new()), xoj::util::adopt) {
gtk_box_append(GTK_BOX(mainBox.get()), scrollableBox.get());
gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(scrollableBox.get()), GTK_POLICY_AUTOMATIC,
GTK_POLICY_AUTOMATIC);
gtk_scrolled_window_set_child(GTK_SCROLLED_WINDOW(scrollableBox.get()), GTK_WIDGET(miniaturesContainer.get()));
gtk_widget_set_vexpand(scrollableBox.get(), true);
Document* doc = this->control->getDocument();
doc->lock();
if (doc->getPdfPageCount() != 0) {
this->cache = std::make_unique<PdfCache>(doc->getPdfDocument(), control->getSettings());
}
doc->unlock();
registerListener(this->control);
this->control->addChangedDocumentListener(this);
auto* adj = gtk_scrolled_window_get_hadjustment(GTK_SCROLLED_WINDOW(scrollableBox.get()));
g_signal_connect(
adj, "notify::page-size", G_CALLBACK(+[](GObject* adj, GParamSpec*, gpointer d) {
static_cast<SidebarPreviewBase*>(d)->newWidth(gtk_adjustment_get_page_size(GTK_ADJUSTMENT(adj)));
}),
this);
Builder builder(control->getGladeSearchPath(), XML_FILE);
GMenuModel* menu = G_MENU_MODEL(builder.get<GObject>(menuId));
contextMenu.reset(GTK_MENU(gtk_menu_new_from_model(menu)), xoj::util::adopt);
gtk_menu_attach_to_widget(contextMenu.get(), mainBox.get(), nullptr);
gtk_box_append(GTK_BOX(mainBox.get()), builder.get(toolbarId));
gtk_widget_show_all(mainBox.get());
}
SidebarPreviewBase::~SidebarPreviewBase() { this->control->removeChangedDocumentListener(this); }
void SidebarPreviewBase::enableSidebar() { enabled = true; }
void SidebarPreviewBase::disableSidebar() { enabled = false; }
void SidebarPreviewBase::newWidth(double width) {
static constexpr double TRIGGER = 20.;
if (std::abs(lastWidth - width) > TRIGGER) {
this->layout();
lastWidth = width;
}
}
auto SidebarPreviewBase::getZoom() const -> double { return this->zoom; }
auto SidebarPreviewBase::getCache() -> PdfCache* { return this->cache.get(); }
void SidebarPreviewBase::layout() { SidebarLayout::layout(this); }
auto SidebarPreviewBase::hasData() -> bool { return true; }
auto SidebarPreviewBase::getWidget() -> GtkWidget* { return this->mainBox.get(); }
void SidebarPreviewBase::documentChanged(DocumentChangeType type) {
if (type == DOCUMENT_CHANGE_COMPLETE || type == DOCUMENT_CHANGE_CLEARED) {
this->cache.reset();
Document* doc = control->getDocument();
doc->lock();
if (doc->getPdfPageCount() != 0) {
this->cache = std::make_unique<PdfCache>(doc->getPdfDocument(), control->getSettings());
}
doc->unlock();
updatePreviews();
}
}
auto SidebarPreviewBase::scrollToPreview(SidebarPreviewBase* sidebar) -> bool {
if (!sidebar->enabled) {
return false;
}
MainWindow* win = sidebar->control->getWindow();
if (win == nullptr) {
return false;
}
GtkWidget* w = win->get("sidebar");
if (!gtk_widget_get_visible(w)) {
return false;
}
if (sidebar->selectedEntry != npos && sidebar->selectedEntry < sidebar->previews.size()) {
auto& p = sidebar->previews[sidebar->selectedEntry];
// scroll to preview
GtkAdjustment* vadj = gtk_scrolled_window_get_vadjustment(GTK_SCROLLED_WINDOW(sidebar->scrollableBox.get()));
GtkWidget* widget = p->getWidget();
GtkAllocation allocation;
gtk_widget_get_allocation(widget, &allocation);
int x = allocation.x;
int y = allocation.y;
if (x == -1) {
g_idle_add(xoj::util::wrap_for_once_v<scrollToPreview>, sidebar);
return false;
}
gtk_adjustment_clamp_page(vadj, y, y + allocation.height);
}
return false;
}
void SidebarPreviewBase::pageDeleted(size_t page) {}
void SidebarPreviewBase::pageInserted(size_t page) {}
void SidebarPreviewBase::openPreviewContextMenu(GdkEvent* currentEvent) {
gtk_menu_popup_at_pointer(contextMenu.get(), currentEvent);
}
| 5,141
|
C++
|
.cpp
| 107
| 42.121495
| 117
| 0.677071
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,557
|
SidebarPreviewBaseEntry.cpp
|
xournalpp_xournalpp/src/core/gui/sidebar/previews/base/SidebarPreviewBaseEntry.cpp
|
#include "SidebarPreviewBaseEntry.h"
#include <gdk/gdk.h> // for GdkEvent, GDK_BUTTON_PRESS
#include <glib-object.h> // for G_CALLBACK, g_object_ref
#include <gtk/gtk.h> //
#include "control/Control.h" // for Control
#include "control/jobs/XournalScheduler.h" // for XournalScheduler
#include "control/settings/Settings.h" // for Settings
#include "gui/Shadow.h" // for Shadow
#include "model/XojPage.h" // for XojPage
#include "util/Color.h" // for cairo_set_source_rgbi
#include "util/gtk4_helper.h" //
#include "util/i18n.h" // for _
#include "util/safe_casts.h" // for floor_cast
#include "SidebarPreviewBase.h" // for SidebarPreviewBase
SidebarPreviewBaseEntry::SidebarPreviewBaseEntry(SidebarPreviewBase* sidebar, const PageRef& page):
sidebar(sidebar), page(page), button(gtk_button_new(), xoj::util::adopt) {
updateSize();
gtk_widget_set_events(this->button.get(), GDK_EXPOSURE_MASK);
g_signal_connect(this->button.get(), "draw", G_CALLBACK(drawCallback), this);
g_signal_connect(this->button.get(), "clicked", G_CALLBACK(+[](GtkButton*, gpointer self) {
static_cast<SidebarPreviewBaseEntry*>(self)->mouseButtonPressCallback();
return true;
}),
this);
const auto clickCallback = G_CALLBACK(+[](GtkWidget*, GdkEvent* event, SidebarPreviewBaseEntry* self) {
// Open context menu on right mouse click
if (event->type == GDK_BUTTON_PRESS) {
auto mouseEvent = reinterpret_cast<GdkEventButton*>(event);
if (mouseEvent->button == 3) {
self->mouseButtonPressCallback();
self->sidebar->openPreviewContextMenu(event);
return true;
}
}
return false;
});
g_signal_connect_after(this->button.get(), "button-press-event", clickCallback, this);
}
SidebarPreviewBaseEntry::~SidebarPreviewBaseEntry() {
this->sidebar->getControl()->getScheduler()->removeSidebar(this);
}
auto SidebarPreviewBaseEntry::drawCallback(GtkWidget* widget, cairo_t* cr, SidebarPreviewBaseEntry* preview)
-> gboolean {
preview->paint(cr);
return true;
}
void SidebarPreviewBaseEntry::setSelected(bool selected) {
if (this->selected == selected) {
return;
}
this->selected = selected;
gtk_widget_queue_draw(this->button.get());
}
void SidebarPreviewBaseEntry::repaint() { sidebar->getControl()->getScheduler()->addRepaintSidebar(this); }
void SidebarPreviewBaseEntry::drawLoadingPage() {
this->buffer.reset(cairo_image_surface_create(CAIRO_FORMAT_ARGB32, imageWidth, imageHeight), xoj::util::adopt);
double zoom = sidebar->getZoom();
cairo_t* cr2 = cairo_create(this->buffer.get());
cairo_matrix_t defaultMatrix = {0};
cairo_get_matrix(cr2, &defaultMatrix);
cairo_translate(cr2, Shadow::getShadowTopLeftSize() + 2, Shadow::getShadowTopLeftSize() + 2);
cairo_scale(cr2, zoom, zoom);
const char* txtLoading = _("Loading...");
cairo_text_extents_t ex;
cairo_set_source_rgb(cr2, 0.5, 0.5, 0.5);
cairo_select_font_face(cr2, "Sans", CAIRO_FONT_SLANT_NORMAL, CAIRO_FONT_WEIGHT_BOLD);
cairo_set_font_size(cr2, 70.0);
cairo_text_extents(cr2, txtLoading, &ex);
cairo_move_to(cr2, (page->getWidth() - ex.width) / 2 - ex.x_bearing,
(page->getHeight() - ex.height) / 2 - ex.y_bearing);
cairo_show_text(cr2, txtLoading);
cairo_destroy(cr2);
}
void SidebarPreviewBaseEntry::paint(cairo_t* cr) {
bool doRepaint = false;
this->drawingMutex.lock();
if (!this->buffer) {
drawLoadingPage();
doRepaint = true;
}
cairo_set_source_surface(cr, this->buffer.get(), 0, 0);
cairo_paint(cr);
this->drawingMutex.unlock();
double height = page->getHeight() * sidebar->getZoom();
double width = page->getWidth() * sidebar->getZoom();
if (this->selected) {
// Draw border
Util::cairo_set_source_rgbi(cr, sidebar->getControl()->getSettings()->getBorderColor());
cairo_set_line_width(cr, 2);
cairo_set_line_cap(cr, CAIRO_LINE_CAP_BUTT);
cairo_set_line_join(cr, CAIRO_LINE_JOIN_BEVEL);
cairo_rectangle(cr, Shadow::getShadowTopLeftSize() + 0.5, Shadow::getShadowTopLeftSize() + 0.5, width + 3,
height + 3);
cairo_stroke(cr);
cairo_set_operator(cr, CAIRO_OPERATOR_ATOP);
Shadow::drawShadow(cr, Shadow::getShadowTopLeftSize(), Shadow::getShadowTopLeftSize(),
round_cast<int>(width) + 4, round_cast<int>(height) + 4);
} else {
cairo_set_operator(cr, CAIRO_OPERATOR_ATOP);
Shadow::drawShadow(cr, Shadow::getShadowTopLeftSize() + 2, Shadow::getShadowTopLeftSize() + 2,
round_cast<int>(width), round_cast<int>(height));
}
if (doRepaint) {
repaint();
}
}
void SidebarPreviewBaseEntry::updateSize() {
this->DPIscaling = gtk_widget_get_scale_factor(this->button.get());
const int shadowPadding = Shadow::getShadowBottomRightSize() + Shadow::getShadowTopLeftSize() + 4;
// To avoid having a black line, we use floor rather than ceil
this->imageWidth = floor_cast<int>(page->getWidth() * sidebar->getZoom()) + shadowPadding;
this->imageHeight = floor_cast<int>(page->getHeight() * sidebar->getZoom()) + shadowPadding;
gtk_widget_set_size_request(this->button.get(), imageWidth, imageHeight);
}
auto SidebarPreviewBaseEntry::getWidget() const -> GtkWidget* { return this->button.get(); }
auto SidebarPreviewBaseEntry::getWidth() const -> int { return imageWidth; }
auto SidebarPreviewBaseEntry::getHeight() const -> int { return imageHeight; }
| 5,878
|
C++
|
.cpp
| 117
| 43.452991
| 115
| 0.650943
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,558
|
SidebarIndexPage.cpp
|
xournalpp_xournalpp/src/core/gui/sidebar/indextree/SidebarIndexPage.cpp
|
#include "SidebarIndexPage.h"
#include <cstring> // for strlen
#include <glib-object.h> // for g_object_unref
#include <pango/pango.h> // for PangoLogAttr
#include "control/Control.h" // for Control
#include "control/ScrollHandler.h" // for ScrollHandler
#include "model/Document.h" // for Document
#include "model/LinkDestination.h" // for XojLinkDest
#include "util/Assert.h" // for xoj_assert
#include "util/glib_casts.h" // for wrap_v
#include "util/gtk4_helper.h" //
#include "util/i18n.h" // for _
#include "util/safe_casts.h" // for as_unsigned
SidebarIndexPage::SidebarIndexPage(Control* control):
AbstractSidebarPage(control), iconNameHelper(control->getSettings()) {
this->treeViewBookmarks = gtk_tree_view_new();
g_object_ref(this->treeViewBookmarks);
gtk_tree_view_set_enable_search(GTK_TREE_VIEW(treeViewBookmarks), true);
gtk_tree_view_set_search_column(GTK_TREE_VIEW(treeViewBookmarks), DOCUMENT_LINKS_COLUMN_NAME);
gtk_tree_view_set_search_equal_func(GTK_TREE_VIEW(treeViewBookmarks),
reinterpret_cast<GtkTreeViewSearchEqualFunc>(treeSearchFunction), this,
nullptr);
this->scrollBookmarks = gtk_scrolled_window_new();
g_object_ref(this->scrollBookmarks);
gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(scrollBookmarks), GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC);
GtkTreeSelection* selection = gtk_tree_view_get_selection(GTK_TREE_VIEW(treeViewBookmarks));
gtk_tree_selection_set_mode(selection, GTK_SELECTION_SINGLE);
gtk_tree_view_set_headers_visible(GTK_TREE_VIEW(treeViewBookmarks), false);
gtk_scrolled_window_set_child(GTK_SCROLLED_WINDOW(scrollBookmarks), treeViewBookmarks);
GtkTreeViewColumn* column = gtk_tree_view_column_new();
gtk_tree_view_column_set_expand(GTK_TREE_VIEW_COLUMN(column), true);
gtk_tree_view_append_column(GTK_TREE_VIEW(treeViewBookmarks), column);
auto* renderer = static_cast<GtkCellRenderer*>(
g_object_new(GTK_TYPE_CELL_RENDERER_TEXT, "ellipsize", PANGO_ELLIPSIZE_END, nullptr));
gtk_tree_view_column_pack_start(GTK_TREE_VIEW_COLUMN(column), renderer, true);
gtk_tree_view_column_set_attributes(GTK_TREE_VIEW_COLUMN(column), renderer, "markup", DOCUMENT_LINKS_COLUMN_NAME,
nullptr);
renderer = gtk_cell_renderer_text_new();
gtk_tree_view_column_pack_end(GTK_TREE_VIEW_COLUMN(column), renderer, false);
gtk_tree_view_column_set_attributes(GTK_TREE_VIEW_COLUMN(column), renderer, "text",
DOCUMENT_LINKS_COLUMN_PAGE_NUMBER, nullptr);
g_object_set(G_OBJECT(renderer), "style", PANGO_STYLE_ITALIC, nullptr);
this->selectHandler = g_signal_connect(treeViewBookmarks, "cursor-changed", G_CALLBACK(treeBookmarkSelected), this);
xoj_assert(this->selectHandler != 0);
gtk_widget_show(this->treeViewBookmarks);
registerListener(control);
}
SidebarIndexPage::~SidebarIndexPage() {
if (this->searchTimeout) {
g_source_remove(this->searchTimeout);
this->searchTimeout = 0;
}
g_object_unref(this->treeViewBookmarks);
g_object_unref(this->scrollBookmarks);
}
void SidebarIndexPage::enableSidebar() {}
void SidebarIndexPage::disableSidebar() {
// Nothing to do at the moment
}
auto SidebarIndexPage::treeBookmarkSelected(GtkWidget* treeview, SidebarIndexPage* sidebar) -> bool {
if (sidebar->searchTimeout) {
return false;
}
gtk_widget_grab_focus(GTK_WIDGET(treeview));
GtkTreeSelection* selection = gtk_tree_view_get_selection(GTK_TREE_VIEW(treeview));
if (selection) {
GtkTreeModel* model = nullptr;
GtkTreeIter iter = {0};
if (gtk_tree_selection_get_selected(selection, &model, &iter)) {
XojLinkDest* link = nullptr;
gtk_tree_model_get(model, &iter, DOCUMENT_LINKS_COLUMN_LINK, &link, -1);
if (link && link->dest) {
LinkDestination* dest = link->dest;
sidebar->control->getScrollHandler()->scrollToLinkDest(*dest);
}
g_object_unref(link);
return true;
}
}
return false;
}
auto SidebarIndexPage::searchTimeoutFunc(SidebarIndexPage* sidebar) -> bool {
sidebar->searchTimeout = 0;
treeBookmarkSelected(sidebar->treeViewBookmarks, sidebar);
return false;
}
auto SidebarIndexPage::treeSearchFunction(GtkTreeModel* model, gint column, const gchar* key, GtkTreeIter* iter,
SidebarIndexPage* sidebar) -> gboolean {
if (sidebar->searchTimeout) {
g_source_remove(sidebar->searchTimeout);
sidebar->searchTimeout = 0;
}
sidebar->searchTimeout = g_timeout_add_seconds_full(G_PRIORITY_DEFAULT_IDLE, 2,
xoj::util::wrap_v<searchTimeoutFunc>, sidebar, nullptr);
// Source: Pidgin
gchar* text = nullptr;
gtk_tree_model_get(model, iter, DOCUMENT_LINKS_COLUMN_NAME, &text, -1);
if (text == nullptr) {
return true;
}
gchar* tmp = g_utf8_normalize(key, -1, G_NORMALIZE_DEFAULT);
gchar* enteredstring = g_utf8_casefold(tmp, -1);
g_free(tmp);
tmp = g_utf8_normalize(text, -1, G_NORMALIZE_DEFAULT);
gchar* normalized = g_utf8_casefold(tmp, -1);
g_free(tmp);
if (g_str_has_prefix(normalized, enteredstring)) {
g_free(enteredstring);
g_free(normalized);
return false;
}
/* Use Pango to separate by words. */
size_t len = as_unsigned(g_utf8_strlen(normalized, -1));
PangoLogAttr* log_attrs = g_new(PangoLogAttr, len + 1);
pango_get_log_attrs(normalized, static_cast<int>(strlen(normalized)), -1, nullptr, log_attrs,
static_cast<int>(len + 1));
gchar* word = normalized;
gboolean result = true;
for (size_t i = 0; i < (len - 1); i++) {
if (log_attrs[i].is_word_start && g_str_has_prefix(word, enteredstring)) {
result = false;
break;
}
word = g_utf8_next_char(word);
}
g_free(log_attrs);
g_free(enteredstring);
g_free(normalized);
return result;
}
auto SidebarIndexPage::getName() -> std::string { return _("Contents"); }
auto SidebarIndexPage::getIconName() -> std::string { return this->iconNameHelper.iconName("sidebar-index"); }
auto SidebarIndexPage::hasData() -> bool { return this->hasContents; }
auto SidebarIndexPage::getWidget() -> GtkWidget* { return this->scrollBookmarks; }
auto SidebarIndexPage::expandOpenLinks(GtkTreeModel* model, GtkTreeIter* parent) -> int {
GtkTreeIter iter = {0};
XojLinkDest* link = nullptr;
if (model == nullptr) {
return 0;
}
int count = 0;
if (gtk_tree_model_iter_children(model, &iter, parent)) {
do {
gtk_tree_model_get(model, &iter, DOCUMENT_LINKS_COLUMN_LINK, &link, -1);
if (link->dest->getExpand()) {
GtkTreePath* path = gtk_tree_model_get_path(model, &iter);
gtk_tree_view_expand_row(GTK_TREE_VIEW(treeViewBookmarks), path, false);
gtk_tree_path_free(path);
}
g_object_unref(link);
count++;
count += expandOpenLinks(model, &iter);
} while (gtk_tree_model_iter_next(model, &iter));
}
return count;
}
void SidebarIndexPage::selectPageNr(size_t page, size_t pdfPage) { selectPageNr(page, pdfPage, nullptr); }
auto SidebarIndexPage::selectPageNr(size_t page, size_t pdfPage, GtkTreeIter* parent) -> bool {
GtkTreeIter iter;
Document* doc = control->getDocument();
doc->lock();
GtkTreeModel* model = doc->getContentsModel();
if (model == nullptr) {
doc->unlock();
return false;
}
g_object_ref(model);
doc->unlock();
if (parent == nullptr) {
// check if there is already the current page selected
GtkTreeSelection* selection = gtk_tree_view_get_selection(GTK_TREE_VIEW(treeViewBookmarks));
if (gtk_tree_selection_get_selected(selection, &model, &iter)) {
XojLinkDest* link = nullptr;
gtk_tree_model_get(model, &iter, DOCUMENT_LINKS_COLUMN_LINK, &link, -1);
if (link && link->dest) {
LinkDestination* dest = link->dest;
if (dest->getPdfPage() == pdfPage) {
g_object_unref(model);
g_object_unref(link);
// already a bookmark from this page selected
return true;
}
}
g_object_unref(link);
}
}
gboolean valid = gtk_tree_model_iter_children(model, &iter, parent);
while (valid) {
XojLinkDest* link = nullptr;
gtk_tree_model_get(model, &iter, DOCUMENT_LINKS_COLUMN_LINK, &link, -1);
if (link->dest->getPdfPage() == pdfPage) {
GtkTreeSelection* selection = gtk_tree_view_get_selection(GTK_TREE_VIEW(treeViewBookmarks));
gtk_tree_selection_select_iter(selection, &iter);
g_object_unref(link);
g_object_unref(model);
return true;
}
g_object_unref(link);
if (selectPageNr(page, pdfPage, &iter)) {
g_object_unref(model);
return true;
}
valid = gtk_tree_model_iter_next(model, &iter);
}
g_object_unref(model);
return false;
}
void SidebarIndexPage::documentChanged(DocumentChangeType type) {
if (type == DOCUMENT_CHANGE_CLEARED) {
gtk_tree_view_set_model(GTK_TREE_VIEW(this->treeViewBookmarks), nullptr);
} else if (type == DOCUMENT_CHANGE_PDF_BOOKMARKS || type == DOCUMENT_CHANGE_COMPLETE) {
Document* doc = this->control->getDocument();
// Block the cursor-change signal when the document changes, otherwise
// there will be a deadlock: both the selectHandler and this code will
// lock the document.
g_signal_handler_block(this->treeViewBookmarks, this->selectHandler);
doc->lock();
GtkTreeModel* model = doc->getContentsModel();
gtk_tree_view_set_model(GTK_TREE_VIEW(this->treeViewBookmarks), model);
int count = expandOpenLinks(model, nullptr);
doc->unlock();
g_signal_handler_unblock(this->treeViewBookmarks, this->selectHandler);
this->treeBookmarkSelected(this->treeViewBookmarks, this);
hasContents = (count != 0);
}
}
void SidebarIndexPage::layout() {}
| 10,631
|
C++
|
.cpp
| 227
| 38.524229
| 120
| 0.644968
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,559
|
FormatDialog.cpp
|
xournalpp_xournalpp/src/core/gui/dialog/FormatDialog.cpp
|
#include "FormatDialog.h"
#include <string> // for operator==, string, basic_string
#include <glib-object.h> // for G_CALLBACK, g_signal_connect
#include <glib.h> // for g_list_free, GList
#include "control/settings/Settings.h" // for Settings
#include "model/FormatDefinitions.h" // for FormatUnits, XOJ_UNITS, XOJ_U...
#include "util/GListView.h" // for GListView, GListView<>::GList...
#include "util/StringUtils.h" // for StringUtils
#include "util/i18n.h" // for _
class GladeSearchpath;
constexpr auto UI_FILE = "pageFormat.glade";
constexpr auto UI_DIALOG_NAME = "pageFormatDialog";
using namespace xoj::popup;
FormatDialog::FormatDialog(GladeSearchpath* gladeSearchPath, Settings* settings, double width, double height,
std::function<void(double, double)> callback):
settings(settings),
selectedScale(settings->getSizeUnitIndex()),
scale(XOJ_UNITS[selectedScale].scale),
origWidth(width),
origHeight(height),
callbackFun(callback) {
Builder builder(gladeSearchPath, UI_FILE);
window.reset(GTK_WINDOW(builder.get(UI_DIALOG_NAME)));
paperTemplatesCombo = GTK_COMBO_BOX(builder.get("cbTemplate"));
landscapeButton = GTK_TOGGLE_BUTTON(builder.get("btLandscape"));
portraitButton = GTK_TOGGLE_BUTTON(builder.get("btPortrait"));
widthSpin = GTK_SPIN_BUTTON(builder.get("spinWidth"));
heightSpin = GTK_SPIN_BUTTON(builder.get("spinHeight"));
GtkWidget* cbUnit = builder.get("cbUnit");
for (int i = 0; i < XOJ_UNIT_COUNT; i++) {
gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(cbUnit), XOJ_UNITS[i].name);
}
gtk_combo_box_set_active(GTK_COMBO_BOX(cbUnit), this->selectedScale);
GtkListStore* store = gtk_list_store_new(2, G_TYPE_STRING, G_TYPE_POINTER);
gtk_combo_box_set_model(paperTemplatesCombo, GTK_TREE_MODEL(store));
g_object_unref(store);
GtkCellRenderer* cell = gtk_cell_renderer_text_new();
gtk_cell_layout_pack_start(GTK_CELL_LAYOUT(paperTemplatesCombo), cell, true);
gtk_cell_layout_set_attributes(GTK_CELL_LAYOUT(paperTemplatesCombo), cell, "text", 0, nullptr);
loadPageFormats();
for (auto& size: paperSizes) {
std::string displayName = gtk_paper_size_get_display_name(size.get());
if (StringUtils::startsWith(displayName, "custom_")) {
displayName = displayName.substr(7);
}
GtkTreeIter iter;
gtk_list_store_append(store, &iter);
gtk_list_store_set(store, &iter, 0, displayName.c_str(), -1);
gtk_list_store_set(store, &iter, 1, size.get(), -1);
}
GtkTreeIter iter;
gtk_list_store_append(store, &iter);
gtk_list_store_set(store, &iter, 0, _("Custom"), -1);
gtk_list_store_set(store, &iter, 1, nullptr, -1);
reset(this);
g_signal_connect(landscapeButton, "toggled", G_CALLBACK(landscapeSelectedCb), this);
g_signal_connect(portraitButton, "toggled", G_CALLBACK(portraitSelectedCb), this);
g_signal_connect(paperTemplatesCombo, "changed", G_CALLBACK(cbFormatChangedCb), this);
g_signal_connect(cbUnit, "changed", G_CALLBACK(cbUnitChanged), this);
g_signal_connect_swapped(widthSpin, "value-changed", G_CALLBACK(spinValueChangedCb), this);
g_signal_connect_swapped(heightSpin, "value-changed", G_CALLBACK(spinValueChangedCb), this);
g_signal_connect_swapped(builder.get("btReset"), "clicked", G_CALLBACK(reset), this);
g_signal_connect_swapped(builder.get("btCancel"), "clicked", G_CALLBACK(gtk_window_close), this->window.get());
g_signal_connect_swapped(builder.get("btOk"), "clicked", G_CALLBACK(+[](FormatDialog* self) {
self->settings->setSizeUnitIndex(self->selectedScale);
self->callbackFun(gtk_spin_button_get_value(self->widthSpin) * self->scale,
gtk_spin_button_get_value(self->heightSpin) * self->scale);
gtk_window_close(self->window.get());
}),
this);
}
void FormatDialog::loadPageFormats() {
GList* default_sizes = gtk_paper_size_get_paper_sizes(false);
for (auto& s: GListView<GtkPaperSize>(default_sizes)) {
std::string name = gtk_paper_size_get_name(&s);
if (name == GTK_PAPER_NAME_A3 || name == GTK_PAPER_NAME_A4 || name == GTK_PAPER_NAME_A5 ||
name == GTK_PAPER_NAME_LETTER || name == GTK_PAPER_NAME_LEGAL) {
paperSizes.emplace_back(&s, gtk_paper_size_free);
continue;
}
gtk_paper_size_free(&s);
}
g_list_free(default_sizes);
// Name format: ftp://ftp.pwg.org/pub/pwg/candidates/cs-pwgmsn10-20020226-5101.1.pdf
paperSizes.emplace_back(gtk_paper_size_new("custom_16x9_320x180mm"), gtk_paper_size_free);
paperSizes.emplace_back(gtk_paper_size_new("custom_4x3_320x240mm"), gtk_paper_size_free);
}
void FormatDialog::setOrientation(Orientation orientation) {
if (this->orientation == orientation) {
return;
}
this->orientation = orientation;
gtk_toggle_button_set_active(portraitButton, orientation == ORIENTATION_PORTRAIT);
gtk_toggle_button_set_active(landscapeButton, orientation == ORIENTATION_LANDSCAPE);
}
void FormatDialog::spinValueChangedCb(FormatDialog* dlg) {
if (dlg->ignoreSpinChange) {
return;
}
double width = gtk_spin_button_get_value(dlg->widthSpin) * dlg->scale;
double height = gtk_spin_button_get_value(dlg->heightSpin) * dlg->scale;
if (width < height) {
dlg->setOrientation(ORIENTATION_PORTRAIT);
} else if (width > height) {
dlg->setOrientation(ORIENTATION_LANDSCAPE);
} else {
dlg->setOrientation(ORIENTATION_NOT_DEFINED);
}
int i = 0;
for (auto& size: dlg->paperSizes) {
double w = gtk_paper_size_get_width(size.get(), GTK_UNIT_POINTS);
double h = gtk_paper_size_get_height(size.get(), GTK_UNIT_POINTS);
if ((static_cast<int>(w - width) == 0 && static_cast<int>(h - height) == 0) ||
(static_cast<int>(h - width) == 0 && static_cast<int>(w - height) == 0)) {
break;
}
i++;
}
gtk_combo_box_set_active(dlg->paperTemplatesCombo, i);
}
void FormatDialog::cbUnitChanged(GtkComboBox* widget, FormatDialog* dlg) {
int selectd = gtk_combo_box_get_active(widget);
if (dlg->selectedScale == selectd) {
return;
}
double width = gtk_spin_button_get_value(dlg->widthSpin) * dlg->scale;
double height = gtk_spin_button_get_value(dlg->heightSpin) * dlg->scale;
dlg->selectedScale = selectd;
dlg->scale = XOJ_UNITS[dlg->selectedScale].scale;
dlg->setSpinValues(width / dlg->scale, height / dlg->scale);
}
void FormatDialog::cbFormatChangedCb(GtkComboBox* widget, FormatDialog* dlg) {
GtkTreeIter iter;
if (!gtk_combo_box_get_active_iter(widget, &iter)) {
return;
}
GtkTreeModel* model = gtk_combo_box_get_model(widget);
GValue value = {0};
gtk_tree_model_get_value(model, &iter, 1, &value);
if (!G_VALUE_HOLDS_POINTER(&value)) {
return;
}
auto* s = static_cast<GtkPaperSize*>(g_value_get_pointer(&value));
if (s == nullptr) {
return;
}
double width = gtk_paper_size_get_width(s, GTK_UNIT_POINTS) / dlg->scale;
double height = gtk_paper_size_get_height(s, GTK_UNIT_POINTS) / dlg->scale;
if (dlg->orientation == ORIENTATION_LANDSCAPE) {
if (width < height) {
std::swap(width, height);
}
} else {
if (width > height) {
std::swap(width, height);
}
dlg->setOrientation(ORIENTATION_PORTRAIT);
}
dlg->setSpinValues(width, height);
}
void FormatDialog::portraitSelectedCb(GtkToggleButton* bt, FormatDialog* dlg) {
bool activated = gtk_toggle_button_get_active(bt);
if (activated) {
gtk_toggle_button_set_active(dlg->landscapeButton, false);
dlg->orientation = ORIENTATION_PORTRAIT;
double width = gtk_spin_button_get_value(dlg->widthSpin);
double height = gtk_spin_button_get_value(dlg->heightSpin);
if (width > height) {
// Exchange width and height
dlg->setSpinValues(height, width);
}
}
}
void FormatDialog::landscapeSelectedCb(GtkToggleButton* bt, FormatDialog* dlg) {
bool activated = gtk_toggle_button_get_active(bt);
if (activated) {
gtk_toggle_button_set_active(dlg->portraitButton, false);
dlg->orientation = ORIENTATION_LANDSCAPE;
double width = gtk_spin_button_get_value(dlg->widthSpin);
double height = gtk_spin_button_get_value(dlg->heightSpin);
if (width < height) {
// Exchange width and height
dlg->setSpinValues(height, width);
}
}
}
void FormatDialog::reset(FormatDialog* self) {
self->setSpinValues(self->origWidth / self->scale, self->origHeight / self->scale);
spinValueChangedCb(self);
}
void FormatDialog::setSpinValues(double width, double height) {
ignoreSpinChange = true;
gtk_spin_button_set_value(widthSpin, width);
gtk_spin_button_set_value(heightSpin, height);
ignoreSpinChange = false;
}
| 9,304
|
C++
|
.cpp
| 196
| 40.321429
| 115
| 0.657389
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,560
|
SelectOpacityDialog.cpp
|
xournalpp_xournalpp/src/core/gui/dialog/SelectOpacityDialog.cpp
|
#include "SelectOpacityDialog.h"
#include <cairo.h> // for cairo_set_operator, cairo_rectangle, cairo_...
#include <glib-object.h> // for G_CALLBACK, g_signal_connect
#include <glib.h> // for gdouble
#include "gui/Builder.h"
#include "util/Stacktrace.h"
#include "util/i18n.h"
#include "util/raii/CairoWrappers.h"
#include "util/raii/GObjectSPtr.h"
#include "util/safe_casts.h" // for round_cast
class GladeSearchpath;
constexpr auto UI_FILE = "selectOpacity.glade";
constexpr auto UI_DIALOG_NAME = "selectOpacityDialog";
static int percentToByte(double percent) { return round_cast<int>(percent * 2.55); }
static double byteToPercent(int byte) { return byte / 2.55; }
static inline void buildLabel(Builder& builder, OpacityFeature opacityFeature) {
// Used to set the label of the dialog in the form of:
// <b>{toolOptionsDesc}</b>\n
// Select opacity for: {opacityFeatureDesc}
std::string toolOptionsDesc;
std::string selectOpacityFor = _("Select opacity for: ");
std::string opacityFeatureDesc;
switch (opacityFeature) {
case OPACITY_FILL_HIGHLIGHTER:
toolOptionsDesc = _("Highlighter Options");
opacityFeatureDesc = _("Fill color");
break;
case OPACITY_FILL_PEN:
toolOptionsDesc = _("Pen Options");
opacityFeatureDesc = _("Fill color");
break;
case OPACITY_SELECT_PDF_TEXT_MARKER:
toolOptionsDesc = _("PDF Text Options");
opacityFeatureDesc = _("PDF Text Marker");
break;
default:
g_warning("No opacityFeature description set for '%s'", opacityFeatureToString(opacityFeature).c_str());
Stacktrace::printStacktrace();
break;
}
gtk_label_set_label(GTK_LABEL(builder.get("label1")),
FC(_F("<b>{1}</b>\n{2}{3}") % toolOptionsDesc % selectOpacityFor % opacityFeatureDesc));
}
xoj::popup::SelectOpacityDialog::SelectOpacityDialog(GladeSearchpath* gladeSearchPath, int alpha,
OpacityFeature feature,
std::function<void(int, OpacityFeature)> callback):
opacityFeature(feature), callback(callback) {
Builder builder(gladeSearchPath, UI_FILE);
this->window.reset(GTK_WINDOW(builder.get(UI_DIALOG_NAME)));
buildLabel(builder, opacityFeature);
previewImage = GTK_IMAGE(builder.get("imgPreview"));
alphaRange = GTK_RANGE(builder.get("scaleAlpha"));
gtk_range_set_value(alphaRange, byteToPercent(alpha));
setPreviewImage(alpha);
g_signal_connect(alphaRange, "value-changed", G_CALLBACK(+[](GtkRange* range, gpointer self) {
static_cast<SelectOpacityDialog*>(self)->setPreviewImage(
percentToByte(round_cast<int>(gtk_range_get_value(range))));
}),
this);
g_signal_connect_swapped(builder.get("btCancel"), "clicked", G_CALLBACK(gtk_window_close), this->window.get());
g_signal_connect(builder.get("btOk"), "clicked", G_CALLBACK(+[](GtkButton*, SelectOpacityDialog* self) {
self->callback(percentToByte(gtk_range_get_value(self->alphaRange)), self->opacityFeature);
gtk_window_close(self->window.get());
}),
this);
#if GTK_MAJOR_VERSION == 3
// Widgets are visible by default in gtk4
gtk_widget_show_all(builder.get("dialog-main-box"));
#endif
}
xoj::popup::SelectOpacityDialog::~SelectOpacityDialog() = default;
const int PREVIEW_WIDTH = 70;
const int PREVIEW_HEIGTH = 50;
const int PREVIEW_BORDER = 10;
void xoj::popup::SelectOpacityDialog::setPreviewImage(int alpha) {
xoj::util::CairoSurfaceSPtr surface(cairo_image_surface_create(CAIRO_FORMAT_ARGB32, PREVIEW_WIDTH, PREVIEW_HEIGTH),
xoj::util::adopt);
xoj::util::CairoSPtr cairo(cairo_create(surface.get()), xoj::util::adopt);
cairo_t* cr = cairo.get();
cairo_set_operator(cr, CAIRO_OPERATOR_SOURCE);
cairo_set_source_rgb(cr, 255, 255, 255);
cairo_paint(cr);
cairo_set_operator(cr, CAIRO_OPERATOR_OVER);
cairo_set_source_rgba(cr, 0, 0x80 / 255.0, 0, alpha / 255.0);
cairo_rectangle(cr, PREVIEW_BORDER, PREVIEW_BORDER, PREVIEW_WIDTH - PREVIEW_BORDER * 2,
PREVIEW_HEIGTH - PREVIEW_BORDER * 2);
cairo_fill(cr);
if (opacityFeature == OPACITY_FILL_PEN) {
cairo_set_line_width(cr, 5);
cairo_set_operator(cr, CAIRO_OPERATOR_SOURCE);
cairo_set_source_rgb(cr, 0, 0x80 / 255.0, 0);
cairo_rectangle(cr, PREVIEW_BORDER, PREVIEW_BORDER, PREVIEW_WIDTH - PREVIEW_BORDER * 2,
PREVIEW_HEIGTH - PREVIEW_BORDER * 2);
cairo_stroke(cr);
}
xoj::util::GObjectSPtr<GdkPixbuf> pixbuf(
gdk_pixbuf_get_from_surface(surface.get(), 0, 0, PREVIEW_WIDTH, PREVIEW_HEIGTH), xoj::util::adopt);
gtk_image_set_from_pixbuf(previewImage, pixbuf.get());
}
| 5,080
|
C++
|
.cpp
| 99
| 42.191919
| 119
| 0.64267
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,561
|
DeviceClassConfigGui.cpp
|
xournalpp_xournalpp/src/core/gui/dialog/DeviceClassConfigGui.cpp
|
#include "DeviceClassConfigGui.h"
#include <string> // for allocator, char_traits
#include <glib.h> // for g_ascii_strtoll, g_strdu...
#include "control/DeviceListHelper.h" // for InputDevice
#include "control/settings/Settings.h" // for Settings
#include "control/settings/SettingsEnums.h" // for InputDeviceTypeOption
#include "gui/Builder.h" // for Builder
#include "util/Assert.h" // for xoj_assert
#include "util/gtk4_helper.h" // for gtk_box_append
class GladeSearchpath;
constexpr auto UI_FILE = "settingsDeviceClassConfig.glade";
constexpr auto UI_WIDGET_NAME = "deviceClassBox";
DeviceClassConfigGui::DeviceClassConfigGui(GladeSearchpath* gladeSearchPath, GtkBox* box, Settings* settings,
const InputDevice& device):
settings(settings), device(device) {
Builder builder(gladeSearchPath, UI_FILE);
gtk_box_append(box, builder.get(UI_WIDGET_NAME)); // box takes ownership of it all!
this->labelDevice = builder.get("labelDevice");
this->cbDeviceClass = builder.get("cbDeviceClass");
gtk_label_set_text(GTK_LABEL(this->labelDevice), (device.getName() + " (" + device.getType() + ")").c_str());
loadSettings();
}
void DeviceClassConfigGui::loadSettings() {
// Get device class of device if available or
InputDeviceTypeOption deviceType =
this->settings->getDeviceClassForDevice(this->device.getName(), this->device.getSource());
// Use the ID of each option in case the combo box options get rearranged in the future
gtk_combo_box_set_active_id(GTK_COMBO_BOX(this->cbDeviceClass),
g_strdup_printf("%i", static_cast<int>(deviceType)));
}
void DeviceClassConfigGui::saveSettings() {
const gchar* deviceClassId = gtk_combo_box_get_active_id(GTK_COMBO_BOX(this->cbDeviceClass));
xoj_assert(deviceClassId != nullptr);
auto deviceClass = static_cast<InputDeviceTypeOption>(g_ascii_strtoll(deviceClassId, nullptr, 10));
this->settings->setDeviceClassForDevice(this->device.getName(), this->device.getSource(), deviceClass);
}
| 2,157
|
C++
|
.cpp
| 36
| 54.444444
| 113
| 0.697774
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,562
|
AboutDialog.cpp
|
xournalpp_xournalpp/src/core/gui/dialog/AboutDialog.cpp
|
#include "AboutDialog.h"
#include <gtk/gtk.h>
#include "gui/Builder.h"
#include "util/PlaceholderString.h" // for PlaceholderString
#include "util/gtk4_helper.h" // for gtk_box_append
#include "util/i18n.h" // for _
#include "config-git.h" // for GIT_COMMIT_ID
#include "config.h" // for PROJECT_VERSION
class GladeSearchpath;
constexpr auto UI_FILE = "about.glade";
constexpr auto UI_DIALOG_NAME = "aboutDialog";
constexpr auto GIT_REPO = "https://github.com/xournalpp/xournalpp";
constexpr auto WEBSITE = "https://xournalpp.github.io";
constexpr auto AUTHORS_LINK = "https://raw.githubusercontent.com/xournalpp/xournalpp/master/AUTHORS";
constexpr auto LICENCE_LINK = "https://raw.githubusercontent.com/xournalpp/xournalpp/master/LICENSE";
static GtkWindow* constructWindow(GladeSearchpath* gladeSearchPath) {
Builder builder(gladeSearchPath, UI_FILE);
GtkWindow* window = GTK_WINDOW(builder.get(UI_DIALOG_NAME));
auto insertPropertyKey = [](GtkGrid* grid, std::string&& str, gint top) {
auto widget = gtk_label_new(nullptr);
gtk_label_set_markup(GTK_LABEL(widget), str.insert(0, "<b>").append("</b>").c_str());
gtk_widget_set_halign(widget, GtkAlign::GTK_ALIGN_START);
gtk_grid_attach(grid, widget, 0, top, 1, 1);
};
auto insertPropertyValue = [](GtkGrid* grid, std::string const& str, gint top) {
auto widget = gtk_label_new(str.c_str());
gtk_widget_set_halign(widget, GtkAlign::GTK_ALIGN_START);
gtk_grid_attach(grid, widget, 1, top, 1, 1);
};
auto infoGrid = GTK_GRID(builder.get("versionInfoGrid"));
insertPropertyKey(infoGrid, _("Version"), 0);
insertPropertyValue(infoGrid, PROJECT_VERSION, 0);
insertPropertyKey(infoGrid, _("Built on"), 1);
insertPropertyValue(infoGrid, __DATE__ ", " __TIME__, 1);
insertPropertyKey(infoGrid, _("GTK Version"), 2);
auto gtkVersion =
FS(FORMAT_STR("{1}.{2}.{3}") % gtk_get_major_version() % gtk_get_minor_version() % gtk_get_micro_version());
insertPropertyValue(infoGrid, gtkVersion, 2);
auto const gitCommitId = std::string{GIT_COMMIT_ID};
if (!gitCommitId.empty()) {
insertPropertyKey(infoGrid, _("Git commit"), 3);
insertPropertyValue(infoGrid, gitCommitId.c_str(), 3);
}
gtk_box_append(GTK_BOX(builder.get("vboxRepo")), gtk_link_button_new(GIT_REPO));
gtk_box_append(GTK_BOX(builder.get("vboxWebsite")), gtk_link_button_new(WEBSITE));
gtk_box_append(GTK_BOX(builder.get("vboxCommunity")),
gtk_link_button_new_with_label(AUTHORS_LINK, _("See the full list of contributors")));
gtk_box_append(GTK_BOX(builder.get("vboxLicense")),
gtk_link_button_new_with_label(LICENCE_LINK, _("GNU GPLv2 or later")));
g_signal_connect_swapped(GTK_BUTTON(builder.get("closebutton")), "clicked", G_CALLBACK(gtk_window_close), window);
#if GTK_MAJOR_VERSION == 3
// Widgets are visible by default in gtk4
gtk_widget_show_all(builder.get("dialog-main-box"));
#endif
return window;
}
xoj::popup::AboutDialog::AboutDialog(GladeSearchpath* gladeSearchPath): window(constructWindow(gladeSearchPath)) {}
xoj::popup::AboutDialog::~AboutDialog() = default;
| 3,244
|
C++
|
.cpp
| 58
| 50.793103
| 120
| 0.691919
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,563
|
XojSaveDlg.cpp
|
xournalpp_xournalpp/src/core/gui/dialog/XojSaveDlg.cpp
|
#include "XojSaveDlg.h"
#include <optional>
#include "control/settings/Settings.h"
#include "util/PathUtil.h" // for fromGFile, toGFile
#include "util/PopupWindowWrapper.h" // for PopupWindowWrapper
#include "util/Util.h"
#include "util/XojMsgBox.h"
#include "util/gtk4_helper.h" // for gtk_file_chooser_set_current_folder
#include "util/i18n.h" // for _
#include "util/raii/GObjectSPtr.h" // for GObjectSPtr
#include "util/raii/GtkWindowUPtr.h" // for GtkWindowUPtr
#include "FileChooserFiltersHelper.h"
static GtkWindow* makeWindow(Settings* settings, fs::path suggestedPath, const char* windowTitle,
const char* buttonLabel) {
GtkWidget* dialog = gtk_file_chooser_dialog_new(windowTitle, nullptr, GTK_FILE_CHOOSER_ACTION_SAVE, _("_Cancel"),
GTK_RESPONSE_CANCEL, buttonLabel, GTK_RESPONSE_OK, nullptr);
gtk_file_chooser_set_current_folder(GTK_FILE_CHOOSER(dialog), Util::toGFile(suggestedPath.parent_path()).get(),
nullptr);
gtk_file_chooser_set_current_name(GTK_FILE_CHOOSER(dialog), Util::toGFilename(suggestedPath.filename()).c_str());
gtk_file_chooser_add_shortcut_folder(GTK_FILE_CHOOSER(dialog), Util::toGFile(settings->getLastOpenPath()).get(),
nullptr);
return GTK_WINDOW(dialog);
}
xoj::SaveExportDialog::SaveExportDialog(Settings* settings, fs::path suggestedPath, const char* windowTitle,
const char* buttonLabel,
std::function<bool(fs::path&, const char* filterName)> pathValidation,
std::function<void(std::optional<fs::path>)> callback):
window(makeWindow(settings, std::move(suggestedPath), windowTitle, buttonLabel)),
callback(std::move(callback)),
pathValidation(std::move(pathValidation)) {
this->signalId = g_signal_connect(
window.get(), "response", G_CALLBACK(+[](GtkDialog* win, int response, gpointer data) {
auto* self = static_cast<SaveExportDialog*>(data);
auto* fc = GTK_FILE_CHOOSER(win);
if (response == GTK_RESPONSE_OK) {
auto file = Util::fromGFile(
xoj::util::GObjectSPtr<GFile>(gtk_file_chooser_get_file(fc), xoj::util::adopt).get());
if (self->pathValidation(file, gtk_file_filter_get_name(gtk_file_chooser_get_filter(fc)))) {
XojMsgBox::replaceFileQuestion(
GTK_WINDOW(win), std::move(file),
std::bind(&SaveExportDialog::close, self, std::placeholders::_1));
} // else the dialog stays on until a suitable destination is found or cancel is hit.
} else {
self->close(std::nullopt);
}
}),
this);
}
void xoj::SaveExportDialog::close(std::optional<fs::path> path) {
// We need to call gtk_window_close() before invoking the callback, because if the callback pops up another dialog,
// the first one won't close...
// But since gtk_window_close() triggers the destruction of *this, we first move the callback
auto cb = std::move(this->callback);
// Closing the window causes another "response" signal, which we want to ignore
g_signal_handler_disconnect(window.get(), signalId);
gtk_window_close(window.get()); // Destroys *this. Don't do anything after this call
cb(std::move(path));
}
static bool xoppPathValidation(fs::path& p, const char*) {
Util::clearExtensions(p);
p += ".xopp";
return true;
}
void xoj::SaveExportDialog::showSaveFileDialog(GtkWindow* parent, Settings* settings, fs::path suggestedPath,
std::function<void(std::optional<fs::path>)> callback) {
auto popup = xoj::popup::PopupWindowWrapper<SaveExportDialog>(settings, std::move(suggestedPath), _("Save File"),
_("Save"), xoppPathValidation, std::move(callback));
auto* fc = GTK_FILE_CHOOSER(popup.getPopup()->getWindow());
xoj::addFilterXopp(fc);
popup.show(parent);
}
| 4,344
|
C++
|
.cpp
| 71
| 48.492958
| 119
| 0.61038
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,564
|
XojOpenDlg.cpp
|
xournalpp_xournalpp/src/core/gui/dialog/XojOpenDlg.cpp
|
#include "XojOpenDlg.h"
#include "control/settings/Settings.h" // for Settings
#include "util/PathUtil.h" // for fromGFile, toGFile
#include "util/PopupWindowWrapper.h" // for PopupWindowWrapper
#include "util/Util.h"
#include "util/gtk4_helper.h" // for gtk_file_chooser_set_current_folder
#include "util/i18n.h" // for _
#include "util/raii/GObjectSPtr.h" // for GObjectSPtr
#include "util/raii/GtkWindowUPtr.h" // for GtkWindowUPtr
#include "FileChooserFiltersHelper.h"
static void addlastSavePathShortcut(GtkFileChooser* fc, Settings* settings) {
auto lastSavePath = settings->getLastSavePath();
if (!lastSavePath.empty()) {
#if GTK_MAJOR_VERSION == 3
gtk_file_chooser_add_shortcut_folder(fc, lastSavePath.u8string().c_str(), nullptr);
#else
gtk_file_chooser_add_shortcut_folder(fc, Util::toGFile(lastSavePath.u8string()).get(), nullptr);
#endif
}
}
static void setCurrentFolderToLastOpenPath(GtkFileChooser* fc, Settings* settings) {
fs::path currentFolder;
if (settings && !settings->getLastOpenPath().empty()) {
currentFolder = settings->getLastOpenPath();
} else {
currentFolder = g_get_home_dir();
}
gtk_file_chooser_set_current_folder(fc, Util::toGFile(currentFolder).get(), nullptr);
}
template <class... Args>
static std::function<void(fs::path, Args...)> addSetLastSavePathToCallback(
std::function<void(fs::path, Args...)> callback, Settings* settings) {
return [cb = std::move(callback), settings](fs::path path, Args... args) {
if (settings && !path.empty()) {
settings->setLastOpenPath(path.parent_path());
}
cb(std::move(path), std::forward<Args>(args)...);
};
}
constexpr auto ATTACH_CHOICE_ID = "attachPdfChoice";
static void addAttachChoice(GtkFileChooser* fc) {
gtk_file_chooser_add_choice(fc, ATTACH_CHOICE_ID, _("Attach file to the journal"), nullptr, nullptr);
gtk_file_chooser_set_choice(fc, ATTACH_CHOICE_ID, "false");
}
// Helper class, for a single open dialog
class FileDlg {
public:
/**
* Creates an open file dialog. The callback is only called if a file is actually chosen
* @param callback(path, attachPdf)
*/
FileDlg(const char* title, std::function<void(fs::path, bool)> callback);
/**
* Creates an open file dialog. The callback is only called if a file is actually chosen
* @param callback(path)
*/
FileDlg(const char* title, std::function<void(fs::path)> callback);
~FileDlg() = default;
inline GtkWindow* getWindow() const { return window.get(); }
private:
xoj::util::GtkWindowUPtr window;
std::function<void(fs::path, bool)> callback;
gulong signalId{};
};
static GtkWindow* makeWindow(const char* title) {
// Todo(maybe)
// Restore previews using https://discourse.gnome.org/t/file-chooser-gtk-4-image-preview/11510/2
auto* win = gtk_file_chooser_dialog_new(title, nullptr, GTK_FILE_CHOOSER_ACTION_OPEN, _("_Cancel"),
GTK_RESPONSE_CANCEL, _("_Open"), GTK_RESPONSE_OK, nullptr);
return GTK_WINDOW(win);
}
FileDlg::FileDlg(const char* title, std::function<void(fs::path, bool)> callback):
window(makeWindow(title)), callback(std::move(callback)) {
this->signalId = g_signal_connect(
window.get(), "response", G_CALLBACK(+[](GtkDialog* win, int response, gpointer data) {
auto* self = static_cast<FileDlg*>(data);
if (response == GTK_RESPONSE_OK) {
auto path =
Util::fromGFile(xoj::util::GObjectSPtr<GFile>(
gtk_file_chooser_get_file(GTK_FILE_CHOOSER(win)), xoj::util::adopt)
.get());
bool attach = false;
if (const char* choice = gtk_file_chooser_get_choice(GTK_FILE_CHOOSER(win), ATTACH_CHOICE_ID);
choice) {
attach = std::strcmp(choice, "true") == 0;
}
// We need to call gtk_window_close() before invoking the callback, because if the callback pops up
// another dialog, the first one won't close...
// So we postpone the callback
Util::execInUiThread([cb = std::move(self->callback), path = std::move(path), attach]() {
cb(std::move(path), attach);
});
}
// Closing the window causes another "response" signal, which we want to ignore
g_signal_handler_disconnect(win, self->signalId);
gtk_window_close(self->getWindow()); // Destroys *self. Beware!
}),
this);
}
FileDlg::FileDlg(const char* title, std::function<void(fs::path)> callback):
FileDlg(title, [cb = std::move(callback)](fs::path path, bool) { cb(std::move(path)); }) {}
void xoj::OpenDlg::showOpenTemplateDialog(GtkWindow* parent, Settings* settings,
std::function<void(fs::path)> callback) {
auto popup = xoj::popup::PopupWindowWrapper<FileDlg>(_("Open template file"),
addSetLastSavePathToCallback(std::move(callback), settings));
auto* fc = GTK_FILE_CHOOSER(popup.getPopup()->getWindow());
xoj::addFilterAllFiles(fc);
xoj::addFilterXopt(fc);
setCurrentFolderToLastOpenPath(fc, settings);
popup.show(parent);
}
void xoj::OpenDlg::showOpenFileDialog(GtkWindow* parent, Settings* settings, std::function<void(fs::path)> callback) {
auto popup = xoj::popup::PopupWindowWrapper<FileDlg>(_("Open file"),
addSetLastSavePathToCallback(std::move(callback), settings));
auto* fc = GTK_FILE_CHOOSER(popup.getPopup()->getWindow());
xoj::addFilterSupported(fc);
xoj::addFilterXoj(fc);
xoj::addFilterXopt(fc);
xoj::addFilterXopp(fc);
xoj::addFilterPdf(fc);
xoj::addFilterAllFiles(fc);
addlastSavePathShortcut(fc, settings);
setCurrentFolderToLastOpenPath(fc, settings);
popup.show(parent);
}
void xoj::OpenDlg::showAnnotatePdfDialog(GtkWindow* parent, Settings* settings,
std::function<void(fs::path, bool)> callback) {
auto popup = xoj::popup::PopupWindowWrapper<FileDlg>(_("Annotate Pdf file"),
addSetLastSavePathToCallback(std::move(callback), settings));
auto* fc = GTK_FILE_CHOOSER(popup.getPopup()->getWindow());
xoj::addFilterPdf(fc);
xoj::addFilterAllFiles(fc);
addlastSavePathShortcut(fc, settings);
setCurrentFolderToLastOpenPath(fc, settings);
addAttachChoice(fc);
popup.show(parent);
}
void xoj::OpenDlg::showOpenImageDialog(GtkWindow* parent, Settings* settings,
std::function<void(fs::path, bool)> callback) {
auto popup = xoj::popup::PopupWindowWrapper<FileDlg>(_("Choose image file"),
[cb = std::move(callback), settings](fs::path p, bool attach) {
if (auto folder = p.parent_path(); !folder.empty()) {
settings->setLastImagePath(folder);
}
cb(std::move(p), attach);
});
auto* fc = GTK_FILE_CHOOSER(popup.getPopup()->getWindow());
xoj::addFilterImages(fc);
xoj::addFilterAllFiles(fc);
if (!settings->getLastImagePath().empty()) {
gtk_file_chooser_set_current_folder(fc, Util::toGFile(settings->getLastImagePath()).get(), nullptr);
}
addAttachChoice(fc);
popup.show(parent);
}
void xoj::OpenDlg::showMultiFormatDialog(GtkWindow* parent, std::vector<std::string> formats,
std::function<void(fs::path)> callback) {
auto popup = xoj::popup::PopupWindowWrapper<FileDlg>(_("Open file"), std::move(callback));
auto* fc = GTK_FILE_CHOOSER(popup.getPopup()->getWindow());
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(fc, filterSupported);
}
popup.show(parent);
}
| 8,775
|
C++
|
.cpp
| 169
| 40.650888
| 120
| 0.601121
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,565
|
FileChooserFiltersHelper.cpp
|
xournalpp_xournalpp/src/core/gui/dialog/FileChooserFiltersHelper.cpp
|
#include "FileChooserFiltersHelper.h"
#include "util/i18n.h"
namespace xoj {
static void addMimeTypeFilter(GtkFileChooser* fc, const char* name, const char* mime) {
GtkFileFilter* filterPdf = gtk_file_filter_new();
gtk_file_filter_set_name(filterPdf, name);
gtk_file_filter_add_mime_type(filterPdf, mime);
gtk_file_chooser_add_filter(fc, filterPdf);
}
void addFilterAllFiles(GtkFileChooser* fc) {
GtkFileFilter* filterAll = gtk_file_filter_new();
gtk_file_filter_set_name(filterAll, _("All files"));
gtk_file_filter_add_pattern(filterAll, "*");
gtk_file_chooser_add_filter(fc, filterAll);
}
void addFilterSupported(GtkFileChooser* fc) {
GtkFileFilter* filterSupported = gtk_file_filter_new();
gtk_file_filter_set_name(filterSupported, _("Supported files"));
gtk_file_filter_add_mime_type(filterSupported, "application/x-xojpp");
gtk_file_filter_add_mime_type(filterSupported, "application/x-xopp");
gtk_file_filter_add_mime_type(filterSupported, "application/x-xopt");
gtk_file_filter_add_mime_type(filterSupported, "application/pdf");
gtk_file_filter_add_pattern(filterSupported, "*.moj"); // MrWriter
gtk_file_chooser_add_filter(fc, filterSupported);
}
void addFilterPdf(GtkFileChooser* fc) { addMimeTypeFilter(fc, _("PDF files"), "application/pdf"); }
void addFilterXoj(GtkFileChooser* fc) { addMimeTypeFilter(fc, _("Xournal files"), "application/x-xojpp"); }
void addFilterXopp(GtkFileChooser* fc) { addMimeTypeFilter(fc, _("Xournal++ files"), "application/x-xopp"); }
void addFilterXopt(GtkFileChooser* fc) { addMimeTypeFilter(fc, _("Xournal++ template"), "application/x-xopt"); }
void addFilterSvg(GtkFileChooser* fc) { addMimeTypeFilter(fc, _("SVG graphics"), "image/svg+xml"); }
void addFilterPng(GtkFileChooser* fc) { addMimeTypeFilter(fc, _("PNG graphics"), "image/png"); }
void addFilterImages(GtkFileChooser* fc) {
GtkFileFilter* filter = gtk_file_filter_new();
gtk_file_filter_set_name(filter, _("Image files"));
gtk_file_filter_add_pixbuf_formats(filter);
gtk_file_chooser_add_filter(fc, filter);
}
}; // namespace xoj
| 2,121
|
C++
|
.cpp
| 38
| 52.552632
| 112
| 0.737121
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,566
|
SettingsDialogPaletteTab.cpp
|
xournalpp_xournalpp/src/core/gui/dialog/SettingsDialogPaletteTab.cpp
|
#include "SettingsDialogPaletteTab.h"
#include "gui/toolbarMenubar/icon/ColorIcon.h"
#include "util/PathUtil.h"
#include "util/gtk4_helper.h"
#include "util/i18n.h"
static const char* const G_OBJECT_PALETTE_PATH = "xournalpp.palettePath";
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// HELPER
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
auto colorize(const std::string& text, const std::string& color) -> std::string {
return std::string{"<span foreground=\""} + color + std::string{"\">"} + text + std::string{"</span>"};
}
void setGObjectPalettePath(GObject* gObject, const fs::path& path) {
g_object_set_data(gObject, G_OBJECT_PALETTE_PATH, (gpointer)&path);
}
auto getGObjectPalettePath(GObject* gObject) -> fs::path {
auto* pathPointer = (fs::path*)g_object_get_data(gObject, G_OBJECT_PALETTE_PATH);
return *pathPointer;
}
auto getDisplayPalettePath(const fs::path& path) -> std::string {
if (path.parent_path() == Util::getBuiltInPaletteDirectoryPath()) {
return std::string{"└─ "} + "<i>" + FS(_F("Built-in palettes")) + "/</i> " + path.filename().u8string();
} else if (path.parent_path() == Util::getCustomPaletteDirectoryPath()) {
return std::string{"└─ "} + "<i>" + FS(_F("User palettes")) + "/</i> " + path.filename().u8string();
} else {
g_warning("Unexpected type of palette path encountered %s", path.parent_path().u8string().c_str());
return std::string{"└─ "} + path.u8string();
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Public Methods
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
constexpr auto UI_FILE = "paletteSettings.glade";
constexpr auto UI_PANEL_NAME = "paletteSettingsPanel";
SettingsDialogPaletteTab::SettingsDialogPaletteTab(GladeSearchpath* gladeSearchPath,
const std::vector<fs::path>& paletteDirectories):
builder(gladeSearchPath, UI_FILE) {
colorPaletteExplainLabel = GTK_LABEL(builder.get("colorPaletteExplainLabel"));
paletteListBox = GTK_LIST_BOX(builder.get("paletteListBox"));
panel = GTK_SCROLLED_WINDOW(builder.get(UI_PANEL_NAME));
renderColorPaletteExplainLabel();
setAllPaletteFilePaths(paletteDirectories);
}
void SettingsDialogPaletteTab::renderPaletteTab(const fs::path& currentlySetPalettePath) {
GtkListBox* lb = paletteListBox;
if (allPaletteFilePaths.empty()) {
renderNoPaletteFoundDisclaimer(lb);
return;
}
for (const fs::path& p: allPaletteFilePaths) {
GtkWidget* listBoxRow = renderPaletteListBoxRow(lb, p);
if (p == currentlySetPalettePath) {
gtk_list_box_select_row(GTK_LIST_BOX(lb), GTK_LIST_BOX_ROW(listBoxRow));
}
}
gtk_widget_show_all(GTK_WIDGET(lb));
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Private Methods
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
auto SettingsDialogPaletteTab::renderPaletteListBoxRow(GtkListBox* lb, const fs::path& p) -> GtkWidget* {
Palette palette{p};
GtkWidget* listBoxRow = nullptr;
try {
palette.load();
listBoxRow = newPaletteListBoxRow(palette);
} catch (const std::exception& e) {
listBoxRow = newErrorListBoxRow(p, e.what());
}
setGObjectPalettePath(G_OBJECT(listBoxRow), p);
gtk_list_box_prepend(lb, listBoxRow);
return listBoxRow;
}
void SettingsDialogPaletteTab::renderColorPaletteExplainLabel() const {
gtk_label_set_label(colorPaletteExplainLabel, FS(_F("<i>The palettes shown below are obtained from the "
"<a href=\"file://{1}\">Built-in palettes</a> and "
"<a href=\"file://{2}\">User palettes</a> directories:</i>\n") %
Util::getBuiltInPaletteDirectoryPath().u8string() %
Util::getCustomPaletteDirectoryPath().u8string())
.c_str());
gtk_label_set_wrap(colorPaletteExplainLabel, true);
gtk_label_set_use_markup(colorPaletteExplainLabel, true);
}
void SettingsDialogPaletteTab::renderNoPaletteFoundDisclaimer(GtkListBox* lb) {
GtkWidget* listBoxRow = gtk_list_box_row_new();
GtkWidget* label = gtk_label_new(("<span foreground=\"red\">" +
FS(_F("No palette files (i.e. with extension .gpl) could be found.\n"
"Using the default until another palette is configured.")) +
"</span>")
.c_str());
gtk_label_set_use_markup(GTK_LABEL(label), true);
gtk_list_box_row_set_child(GTK_LIST_BOX_ROW(listBoxRow), label);
gtk_list_box_row_set_activatable(GTK_LIST_BOX_ROW(listBoxRow), FALSE);
gtk_list_box_row_set_selectable(GTK_LIST_BOX_ROW(listBoxRow), FALSE);
gtk_list_box_prepend(lb, listBoxRow);
}
// use list of fs::path as input
void SettingsDialogPaletteTab::setAllPaletteFilePaths(const std::vector<fs::path>& paletteDirectories) {
for (const fs::path& paletteDirectory: paletteDirectories) {
std::vector<fs::path> const files = Util::listFilesSorted(paletteDirectory);
for (const fs::path& paletteFile: files) {
if (paletteFile.extension() == ".gpl") {
allPaletteFilePaths.push_back(paletteFile);
}
}
}
}
auto SettingsDialogPaletteTab::getSelectedPalette() const -> std::optional<fs::path> {
GtkListBoxRow* selected_listbox_row = gtk_list_box_get_selected_row(paletteListBox);
if (allPaletteFilePaths.empty()) {
return std::nullopt;
}
if (!G_IS_OBJECT(selected_listbox_row)) {
return std::nullopt;
}
return getGObjectPalettePath(G_OBJECT(selected_listbox_row));
}
auto SettingsDialogPaletteTab::newErrorListBoxRow(const fs::path& palettePath, const std::string& error) -> GtkWidget* {
GtkWidget* listBoxRow = gtk_list_box_row_new();
GtkWidget* rowContent = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 3);
gtk_list_box_row_set_child(GTK_LIST_BOX_ROW(listBoxRow), rowContent);
std::string const formattedError = colorize(FS(_F("Error")) + ": " + error, "red");
GtkWidget* text = newPaletteTextBox(formattedError, palettePath);
gtk_box_append(GTK_BOX(rowContent), text);
return listBoxRow;
}
auto SettingsDialogPaletteTab::newPaletteListBoxRow(Palette& palette) -> GtkWidget* {
GtkWidget* listBoxRow = gtk_list_box_row_new();
GtkWidget* rowContent = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 3);
gtk_list_box_row_set_child(GTK_LIST_BOX_ROW(listBoxRow), rowContent);
std::string const paletteName = palette.getHeader(std::string{FS(_F("Name"))});
GtkWidget* text = nullptr;
if (paletteName.empty()) {
text = newPaletteTextBox(std::string{"<i>" + FS(_F("Palette has no Name")) + "</i>"}, palette.getFilePath());
} else {
text = newPaletteTextBox(paletteName, palette.getFilePath().u8string());
}
gtk_box_append(GTK_BOX(rowContent), text);
GtkWidget* colorIcons = newPaletteColorIconsBox(palette);
gtk_widget_set_hexpand(colorIcons, true);
gtk_box_append(GTK_BOX(rowContent), colorIcons);
return listBoxRow;
}
auto SettingsDialogPaletteTab::newPaletteTextBox(const std::string& mainContent, const fs::path& path) -> GtkWidget* {
GtkWidget* textBox = gtk_box_new(GTK_ORIENTATION_VERTICAL, 3);
GtkWidget* mainLabel = gtk_label_new(mainContent.c_str());
gtk_widget_set_halign(mainLabel, GTK_ALIGN_START);
gtk_label_set_use_markup(GTK_LABEL(mainLabel), true);
gtk_box_append(GTK_BOX(textBox), mainLabel);
GtkWidget* secondaryLabel = gtk_label_new(getDisplayPalettePath(path).c_str());
gtk_widget_set_halign(secondaryLabel, GTK_ALIGN_START);
gtk_label_set_use_markup(GTK_LABEL(secondaryLabel), true);
gtk_box_append(GTK_BOX(textBox), secondaryLabel);
return textBox;
}
auto SettingsDialogPaletteTab::newPaletteColorIconsBox(const Palette& palette) -> GtkWidget* {
GtkWidget* colors = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 3);
for (unsigned long i = 0; i < palette.size(); i++) {
const NamedColor& namedColor = palette.getColorAt(i);
const Color c = namedColor.getColor();
GtkWidget* icon = ColorIcon::newGtkImage(c, 16, true);
gtk_box_append(GTK_BOX(colors), icon);
}
gtk_widget_set_halign(colors, GTK_ALIGN_END);
return colors;
}
| 8,995
|
C++
|
.cpp
| 166
| 46.518072
| 120
| 0.60982
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,567
|
PluginDialog.cpp
|
xournalpp_xournalpp/src/core/gui/dialog/PluginDialog.cpp
|
#include "PluginDialog.h"
#ifdef ENABLE_PLUGINS
#include <algorithm>
#include <string> // for string
#include "control/settings/Settings.h" // for Settings
#include "gui/Builder.h"
#include "gui/dialog/PluginDialogEntry.h" // for PluginDialogEntry
#include "plugin/PluginController.h" // for PluginController
class GladeSearchpath;
class Plugin;
constexpr auto UI_FILE = "plugin.glade";
constexpr auto UI_DIALOG_NAME = "pluginDialog";
PluginDialog::PluginDialog(GladeSearchpath* gladeSearchPath, Settings* settings,
const std::vector<std::unique_ptr<Plugin>>& pluginList):
settings(settings) {
Builder builder(gladeSearchPath, UI_FILE);
window.reset(GTK_WINDOW(builder.get(UI_DIALOG_NAME)));
GtkBox* pluginBox = GTK_BOX(builder.get("pluginBox"));
std::transform(pluginList.begin(), pluginList.end(), std::back_inserter(this->plugins),
[&](auto& p) { return std::make_unique<PluginDialogEntry>(p.get(), gladeSearchPath, pluginBox); });
g_signal_connect_swapped(builder.get("btCancel"), "clicked", G_CALLBACK(gtk_window_close), this->window.get());
g_signal_connect_swapped(builder.get("btOk"), "clicked", G_CALLBACK(+[](PluginDialog* self) {
self->saveSettings();
gtk_window_close(self->window.get());
}),
this);
}
void PluginDialog::saveSettings() {
std::string pluginEnabled;
std::string pluginDisabled;
// Save plugin settings
for (auto&& bcg: this->plugins) { bcg->saveSettings(pluginEnabled, pluginDisabled); }
settings->setPluginEnabled(pluginEnabled);
settings->setPluginDisabled(pluginDisabled);
}
#endif
| 1,762
|
C++
|
.cpp
| 36
| 41.333333
| 118
| 0.669778
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,568
|
SelectBackgroundColorDialog.cpp
|
xournalpp_xournalpp/src/core/gui/dialog/SelectBackgroundColorDialog.cpp
|
#include "SelectBackgroundColorDialog.h"
#include <cstdint> // for uint32_t
#include <string> // for allocator
#include <glib.h> // for g_free, g_strdup_printf
#include "control/Control.h" // for Control
#include "control/settings/Settings.h" // for SElement, Settings
#include "util/Color.h"
#include "util/i18n.h" // for _
#include "util/safe_casts.h" // for as_unsigned
static inline std::array<GdkRGBA, 9> background1 = {
Util::rgb_to_GdkRGBA(Colors::xopp_lightpink), //
Util::rgb_to_GdkRGBA(Colors::xopp_bisque), //
Util::rgb_to_GdkRGBA(Colors::xopp_lemonchifon), //
Util::rgb_to_GdkRGBA(Colors::xopp_palegoldenrod), //
Util::rgb_to_GdkRGBA(Colors::xopp_lavender), //
Util::rgb_to_GdkRGBA(Colors::xopp_gainsboro03), //
Util::rgb_to_GdkRGBA(Colors::xopp_antiquewhite), //
Util::rgb_to_GdkRGBA(Colors::xopp_gainsboro), //
Util::rgb_to_GdkRGBA(Colors::xopp_snow) //
};
static inline std::array<GdkRGBA, 6> backgroundXournal = {
Util::rgb_to_GdkRGBA(Colors::white), //
Util::rgb_to_GdkRGBA(Colors::xopp_paleturqoise), //
Util::rgb_to_GdkRGBA(Colors::xopp_aquamarine), //
Util::rgb_to_GdkRGBA(Colors::xopp_pink), //
Util::rgb_to_GdkRGBA(Colors::xopp_lightsalmon), //
Util::rgb_to_GdkRGBA(Colors::xopp_khaki) //
};
SelectBackgroundColorDialog::SelectBackgroundColorDialog(Control* control, std::function<void(Color)> callback):
control(control), callback(callback) {
lastBackgroundColors.fill(Util::rgb_to_GdkRGBA(Colors::white));
Settings* settings = control->getSettings();
SElement& el = settings->getCustomElement("lastUsedPageBgColor");
int count = 0;
el.getInt("count", count);
auto index = 0ULL;
for (int i = 0; i < count && index < LAST_BACKGROUND_COLOR_COUNT; i++) {
int iColor{};
char* settingName = g_strdup_printf("color%02i", i);
bool read = el.getInt(settingName, iColor);
g_free(settingName);
if (!read) {
continue;
}
lastBackgroundColors[index] = Util::rgb_to_GdkRGBA(Color(as_unsigned(iColor)));
++index;
}
window.reset(GTK_WINDOW(gtk_color_chooser_dialog_new(_("Select background color"), nullptr)));
GtkColorChooser* chooser = GTK_COLOR_CHOOSER(window.get());
gtk_color_chooser_set_use_alpha(chooser, false);
gtk_color_chooser_add_palette(chooser, GTK_ORIENTATION_HORIZONTAL, 9, background1.size(), background1.data());
gtk_color_chooser_add_palette(chooser, GTK_ORIENTATION_HORIZONTAL, 9, backgroundXournal.size(),
backgroundXournal.data());
// Last used colors (only by background, the general last used are shared with the
// pen and highlighter etc.)
gtk_color_chooser_add_palette(chooser, GTK_ORIENTATION_HORIZONTAL, 9, static_cast<int>(lastBackgroundColors.size()),
lastBackgroundColors.data());
g_signal_connect(window.get(), "response",
G_CALLBACK(+[](GtkColorChooser*, int response, SelectBackgroundColorDialog* self) {
if (response == GTK_RESPONSE_DELETE_EVENT) {
// Ignore DELETE_EVENT, as this is caught by the PopupWindowWrapper
return;
}
if (response == GTK_RESPONSE_OK) {
GdkRGBA color;
gtk_color_chooser_get_rgba(GTK_COLOR_CHOOSER(self->window.get()), &color);
self->storeLastUsedValuesInSettings(color);
self->callback(Util::GdkRGBA_to_argb(color));
}
gtk_window_close(self->window.get());
}),
this);
}
void SelectBackgroundColorDialog::storeLastUsedValuesInSettings(GdkRGBA color) {
for (auto& lastBackgroundColor: lastBackgroundColors) {
if (gdk_rgba_equal(&lastBackgroundColor, &color)) {
// The new color is already in the list, do not save
return;
}
}
Settings* settings = control->getSettings();
SElement& el = settings->getCustomElement("lastUsedPageBgColor");
// Move all colors one step back
for (size_t i = LAST_BACKGROUND_COLOR_COUNT - 1; i > 0; i--) {
lastBackgroundColors[i] = lastBackgroundColors[i - 1];
}
lastBackgroundColors[0] = color;
el.setInt("count", LAST_BACKGROUND_COLOR_COUNT);
for (size_t i = 0; i < LAST_BACKGROUND_COLOR_COUNT; i++) {
char* settingName = g_strdup_printf("color%02zu", i);
el.setIntHex(settingName, int(uint32_t(Util::GdkRGBA_to_argb(lastBackgroundColors[i]))));
g_free(settingName);
}
settings->customSettingsChanged();
}
| 4,912
|
C++
|
.cpp
| 95
| 41.8
| 120
| 0.617985
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,569
|
SettingsDialog.cpp
|
xournalpp_xournalpp/src/core/gui/dialog/SettingsDialog.cpp
|
#include "SettingsDialog.h"
#include <algorithm> // for max
#include <cstddef> // for NULL, size_t
#include <type_traits> // for __underlying_type_im...
#include <gdk/gdk.h> // for GdkRGBA, GdkRectangle
#include <glib-object.h> // for G_CALLBACK, g_signal...
#include "control/AudioController.h" // for AudioController
#include "control/Control.h" // for Control
#include "control/DeviceListHelper.h" // for getDeviceList, Input...
#include "control/settings/Settings.h" // for Settings, SElement
#include "control/settings/SettingsEnums.h" // for STYLUS_CURSOR_ARROW
#include "control/tools/StrokeStabilizerEnum.h" // for AveragingMethod, Pre...
#include "gui/CreatePreviewImage.h" // for createPreviewImage
#include "gui/MainWindow.h" // for MainWindow
#include "gui/XournalView.h" // for XournalView
#include "gui/toolbarMenubar/ToolMenuHandler.h" // for ToolMenuHandler
#include "gui/toolbarMenubar/icon/ColorIcon.h"
#include "gui/toolbarMenubar/model/ColorPalette.h" // for Palette
#include "gui/widgets/ZoomCallib.h" // for zoomcallib_new, zoom...
#include "model/PageType.h" // for PageType
#include "util/Color.h" // for GdkRGBA_to_argb, rgb...
#include "util/PathUtil.h" // for fromGFile, toGFilename
#include "util/Util.h" // for systemWithMessage
#include "util/gtk4_helper.h" //
#include "util/i18n.h" // for _
#include "util/raii/CairoWrappers.h" // for CairoSurfaceSPtr
#include "util/safe_casts.h" // for round_cast
#include "ButtonConfigGui.h" // for ButtonConfigGui
#include "DeviceClassConfigGui.h" // for DeviceClassConfigGui
#include "LanguageConfigGui.h" // for LanguageConfigGui
#include "LatexSettingsPanel.h" // for LatexSettingsPanel
#include "filesystem.h" // for is_directory
class GladeSearchpath;
using std::string;
using std::vector;
constexpr auto UI_FILE = "settings.glade";
constexpr auto UI_DIALOG_NAME = "settingsDialog";
SettingsDialog::SettingsDialog(GladeSearchpath* gladeSearchPath, Settings* settings, Control* control,
const std::vector<fs::path>& paletteDirectories, std::function<void()> callback):
settings(settings),
control(control),
callib(zoomcallib_new()),
builder(gladeSearchPath, UI_FILE),
window(GTK_WINDOW(builder.get(UI_DIALOG_NAME))),
languageConfig(gladeSearchPath, builder.get("hboxLanguageSelect"), settings),
latexPanel(gladeSearchPath),
paletteTab(gladeSearchPath, paletteDirectories),
callback(callback) {
gtk_box_append(GTK_BOX(builder.get("zoomVBox")), callib);
gtk_widget_show(callib);
GtkWidget* preview = xoj::helper::createPreviewImage(PageType{PageTypeFormat::Lined});
gtk_box_append(GTK_BOX(builder.get("pagePreviewImage")), preview);
gtk_widget_show(preview);
initMouseButtonEvents(gladeSearchPath);
vector<InputDevice> deviceList = DeviceListHelper::getDeviceList(this->settings);
GtkBox* container = GTK_BOX(builder.get("hboxInputDeviceClasses"));
for (const InputDevice& inputDevice: deviceList) {
// Only add real devices (core pointers have vendor and product id nullptr)
this->deviceClassConfigs.emplace_back(gladeSearchPath, container, settings, inputDevice);
}
if (deviceList.empty()) {
GtkWidget* label = gtk_label_new("");
gtk_label_set_markup(GTK_LABEL(label),
_("<b>No devices were found. This seems wrong - maybe file a bug report?</b>"));
gtk_box_append(GTK_BOX(container), label);
gtk_widget_show(label);
}
gtk_box_append(GTK_BOX(builder.get("latexTabBox")), this->latexPanel.getPanel());
gtk_box_append(GTK_BOX(builder.get("paletteTabBox")), this->paletteTab.getPanel());
g_signal_connect(GTK_RANGE(builder.get("zoomCallibSlider")), "value-changed",
G_CALLBACK(+[](GtkRange* range, gpointer self) {
static_cast<SettingsDialog*>(self)->setDpi(round_cast<int>(gtk_range_get_value(range)));
}),
this);
g_signal_connect_swapped(builder.get("cbEnablePressureInference"), "toggled",
G_CALLBACK(+[](SettingsDialog* self) { self->updatePressureSensitivityOptions(); }), this);
g_signal_connect_swapped(builder.get("cbSettingPresureSensitivity"), "toggled",
G_CALLBACK(+[](SettingsDialog* self) { self->updatePressureSensitivityOptions(); }), this);
g_signal_connect_swapped(
builder.get("cbAutosave"), "toggled",
G_CALLBACK(+[](SettingsDialog* self) { self->enableWithCheckbox("cbAutosave", "boxAutosave"); }), this);
g_signal_connect_swapped(builder.get("cbIgnoreFirstStylusEvents"), "toggled", G_CALLBACK(+[](SettingsDialog* self) {
self->enableWithCheckbox("cbIgnoreFirstStylusEvents", "spNumIgnoredStylusEvents");
}),
this);
g_signal_connect_swapped(
builder.get("btTestEnable"), "clicked", G_CALLBACK(+[](SettingsDialog* self) {
Util::systemWithMessage(gtk_entry_get_text(GTK_ENTRY(self->builder.get("txtEnableTouchCommand"))));
}),
this);
g_signal_connect_swapped(
builder.get("btTestDisable"), "clicked", G_CALLBACK(+[](SettingsDialog* self) {
Util::systemWithMessage(gtk_entry_get_text(GTK_ENTRY(self->builder.get("txtDisableTouchCommand"))));
}),
this);
g_signal_connect_swapped(builder.get("cbAddVerticalSpace"), "toggled", G_CALLBACK(+[](SettingsDialog* self) {
self->enableWithCheckbox("cbAddVerticalSpace", "spAddVerticalSpaceAbove");
self->enableWithCheckbox("cbAddVerticalSpace", "spAddVerticalSpaceBelow");
}),
this);
g_signal_connect_swapped(builder.get("cbAddHorizontalSpace"), "toggled", G_CALLBACK(+[](SettingsDialog* self) {
self->enableWithCheckbox("cbAddHorizontalSpace", "spAddHorizontalSpaceLeft");
self->enableWithCheckbox("cbAddHorizontalSpace", "spAddHorizontalSpaceRight");
}),
this);
g_signal_connect_swapped(builder.get("cbUnlimitedScrolling"), "toggled", G_CALLBACK(+[](SettingsDialog* self) {
self->disableWithCheckbox("cbUnlimitedScrolling", "cbAddHorizontalSpace");
self->disableWithCheckbox("cbUnlimitedScrolling", "cbAddVerticalSpace");
self->enableWithEnabledCheckbox("cbAddHorizontalSpace", "spAddHorizontalSpaceLeft");
self->enableWithEnabledCheckbox("cbAddVerticalSpace", "spAddVerticalSpaceAbove");
self->enableWithEnabledCheckbox("cbAddHorizontalSpace", "spAddHorizontalSpaceRight");
self->enableWithEnabledCheckbox("cbAddVerticalSpace", "spAddVerticalSpaceBelow");
}),
this);
g_signal_connect_swapped(builder.get("cbDrawDirModsEnabled"), "toggled", G_CALLBACK(+[](SettingsDialog* self) {
self->enableWithCheckbox("cbDrawDirModsEnabled", "spDrawDirModsRadius");
}),
this);
g_signal_connect_swapped(builder.get("cbStrokeFilterEnabled"), "toggled", G_CALLBACK(+[](SettingsDialog* self) {
self->enableWithCheckbox("cbStrokeFilterEnabled", "spStrokeIgnoreTime");
self->enableWithCheckbox("cbStrokeFilterEnabled", "spStrokeIgnoreLength");
self->enableWithCheckbox("cbStrokeFilterEnabled", "spStrokeSuccessiveTime");
self->enableWithCheckbox("cbStrokeFilterEnabled", "cbDoActionOnStrokeFiltered");
self->enableWithCheckbox("cbStrokeFilterEnabled", "cbTrySelectOnStrokeFiltered");
}),
this);
g_signal_connect_swapped(builder.get("cbDisableAudio"), "toggled", G_CALLBACK(+[](SettingsDialog* self) {
self->disableWithCheckbox("cbDisableAudio", "sidAudio1");
self->disableWithCheckbox("cbDisableAudio", "sidAudio2");
self->disableWithCheckbox("cbDisableAudio", "sidAudio3");
self->disableWithCheckbox("cbDisableAudio", "sidAudio4");
self->disableWithCheckbox("cbDisableAudio", "sidAudioLbl");
}),
this);
g_signal_connect_swapped(builder.get("cbDisableTouchOnPenNear"), "toggled", G_CALLBACK(+[](SettingsDialog* self) {
self->enableWithCheckbox("cbDisableTouchOnPenNear", "boxInternalHandRecognition");
}),
this);
g_signal_connect_swapped(builder.get("cbTouchDisableMethod"), "changed",
G_CALLBACK(+[](SettingsDialog* self) { self->customHandRecognitionToggled(); }), this);
g_signal_connect_swapped(builder.get("cbEnableZoomGestures"), "toggled", G_CALLBACK(+[](SettingsDialog* self) {
self->enableWithCheckbox("cbEnableZoomGestures", "gdStartZoomAtSetting");
}),
this);
g_signal_connect_swapped(builder.get("cbStylusCursorType"), "changed",
G_CALLBACK(+[](SettingsDialog* self) { self->customStylusIconTypeChanged(); }), this);
g_signal_connect(GTK_COMBO_BOX(builder.get("cbStabilizerAveragingMethods")), "changed",
G_CALLBACK(+[](GtkComboBox* comboBox, gpointer self) {
static_cast<SettingsDialog*>(self)->showStabilizerAvMethodOptions(
static_cast<StrokeStabilizer::AveragingMethod>(gtk_combo_box_get_active(comboBox)));
}),
this);
g_signal_connect(GTK_COMBO_BOX(builder.get("cbStabilizerPreprocessors")), "changed",
G_CALLBACK(+[](GtkComboBox* comboBox, gpointer self) {
static_cast<SettingsDialog*>(self)->showStabilizerPreprocessorOptions(
static_cast<StrokeStabilizer::Preprocessor>(gtk_combo_box_get_active(comboBox)));
}),
this);
g_signal_connect_swapped(builder.get("btOk"), "clicked", G_CALLBACK(+[](SettingsDialog* self) {
self->save();
self->callback();
gtk_window_close(self->window.get());
}),
this);
g_signal_connect_swapped(builder.get("btCancel"), "clicked", G_CALLBACK(gtk_window_close), window.get());
g_signal_connect(builder.get("cbUseSpacesAsTab"), "toggled",
G_CALLBACK(+[](GtkCheckButton* checkBox, SettingsDialog* self) {
self->enableWithCheckbox("cbUseSpacesAsTab", "numberOfSpacesContainer");
}),
this);
load();
}
void SettingsDialog::initMouseButtonEvents(GladeSearchpath* gladeSearchPath) {
auto emplaceButton = [gladeSearchPath, &btns = buttonConfigs, settings = settings, &bld = builder](
const char* hbox, Button button, bool withDevice = false) {
btns.emplace_back(std::make_unique<ButtonConfigGui>(gladeSearchPath, GTK_BOX(bld.get(hbox)), settings, button,
withDevice));
};
emplaceButton("hboxMiddleMouse", BUTTON_MOUSE_MIDDLE);
emplaceButton("hboxRightMouse", BUTTON_MOUSE_RIGHT);
emplaceButton("hboxEraser", BUTTON_ERASER);
emplaceButton("hboxTouch", BUTTON_TOUCH, true);
emplaceButton("hboxPenButton1", BUTTON_STYLUS_ONE);
emplaceButton("hboxPenButton2", BUTTON_STYLUS_TWO);
emplaceButton("hboxDefaultTool", BUTTON_DEFAULT);
}
void SettingsDialog::setDpi(int dpi) {
if (this->dpi == dpi) {
return;
}
this->dpi = dpi;
zoomcallib_set_val(ZOOM_CALLIB(callib), dpi);
}
void SettingsDialog::loadCheckbox(const char* name, bool value) {
gtk_check_button_set_active(GTK_CHECK_BUTTON(builder.get(name)), value);
}
auto SettingsDialog::getCheckbox(const char* name) -> bool {
return gtk_check_button_get_active(GTK_CHECK_BUTTON(builder.get(name)));
}
void SettingsDialog::loadSlider(const char* name, double value) {
GtkRange* range = GTK_RANGE(builder.get(name));
gtk_range_set_value(range, value);
}
auto SettingsDialog::getSlider(const char* name) -> double {
GtkRange* range = GTK_RANGE(builder.get(name));
return gtk_range_get_value(range);
}
/**
* Checkbox was toggled, enable / disable it
*/
void SettingsDialog::enableWithCheckbox(const string& checkboxId, const string& widgetId) {
bool enabled = gtk_check_button_get_active(GTK_CHECK_BUTTON(builder.get(checkboxId)));
gtk_widget_set_sensitive(builder.get(widgetId), enabled);
}
void SettingsDialog::disableWithCheckbox(const string& checkboxId, const string& widgetId) {
bool enabled = gtk_check_button_get_active(GTK_CHECK_BUTTON(builder.get(checkboxId)));
gtk_widget_set_sensitive(builder.get(widgetId), !enabled);
}
/**
* similar to enableWithCheckbox, but also disables widget if the checkbox is disabled
*/
void SettingsDialog::enableWithEnabledCheckbox(const string& checkboxId, const string& widgetId) {
GtkWidget* checkboxWidget = builder.get(checkboxId);
bool const enabled =
gtk_widget_get_sensitive(checkboxWidget) && gtk_check_button_get_active(GTK_CHECK_BUTTON(checkboxWidget));
gtk_widget_set_sensitive(builder.get(widgetId), enabled);
}
void SettingsDialog::updatePressureSensitivityOptions() {
GtkWidget* sensitivityOptionsFrame = builder.get("framePressureSensitivityScale");
bool havePressureInput = getCheckbox("cbSettingPresureSensitivity") || getCheckbox("cbEnablePressureInference");
if (!havePressureInput) {
gtk_widget_set_tooltip_text(sensitivityOptionsFrame,
_("Enable pressure sensitivity or pressure inference to change this setting!"));
} else {
gtk_widget_set_tooltip_text(sensitivityOptionsFrame,
_("Filter input pressure. Multiply the pressure by the pressure multiplier."
" If less than the minimum, use the minimum pressure."));
}
gtk_widget_set_sensitive(sensitivityOptionsFrame, havePressureInput);
}
void SettingsDialog::customHandRecognitionToggled() {
GtkWidget* cbTouchDisableMethod = builder.get("cbTouchDisableMethod");
int touchMethod = gtk_combo_box_get_active(GTK_COMBO_BOX(cbTouchDisableMethod));
gtk_widget_set_sensitive(builder.get("boxCustomTouchDisableSettings"), touchMethod == 2);
}
void SettingsDialog::customStylusIconTypeChanged() {
GtkWidget* cbStylusCursorType = builder.get("cbStylusCursorType");
int stylusCursorType = gtk_combo_box_get_active(GTK_COMBO_BOX(cbStylusCursorType));
bool showCursorHighlightOptions =
(stylusCursorType != STYLUS_CURSOR_NONE && stylusCursorType != STYLUS_CURSOR_ARROW);
gtk_widget_set_sensitive(builder.get("highlightCursorGrid"), showCursorHighlightOptions);
}
void SettingsDialog::showStabilizerAvMethodOptions(StrokeStabilizer::AveragingMethod method) {
bool showArithmetic = method == StrokeStabilizer::AveragingMethod::ARITHMETIC;
gtk_widget_set_visible(builder.get("lbStabilizerBuffersize"), showArithmetic);
gtk_widget_set_visible(builder.get("sbStabilizerBuffersize"), showArithmetic);
bool showSigma = method == StrokeStabilizer::AveragingMethod::VELOCITY_GAUSSIAN;
gtk_widget_set_visible(builder.get("lbStabilizerSigma"), showSigma);
gtk_widget_set_visible(builder.get("sbStabilizerSigma"), showSigma);
bool preprocessorOn = static_cast<StrokeStabilizer::Preprocessor>(gtk_combo_box_get_active(GTK_COMBO_BOX(
builder.get("cbStabilizerPreprocessors")))) != StrokeStabilizer::Preprocessor::NONE;
bool sensitive = showSigma || showArithmetic || preprocessorOn;
gtk_widget_set_sensitive(builder.get("cbStabilizerEnableFinalizeStroke"), sensitive);
}
void SettingsDialog::showStabilizerPreprocessorOptions(StrokeStabilizer::Preprocessor preprocessor) {
bool showDeadzone = preprocessor == StrokeStabilizer::Preprocessor::DEADZONE;
gtk_widget_set_visible(builder.get("lbStabilizerDeadzoneRadius"), showDeadzone);
gtk_widget_set_visible(builder.get("sbStabilizerDeadzoneRadius"), showDeadzone);
gtk_widget_set_visible(builder.get("cbStabilizerEnableCuspDetection"), showDeadzone);
bool showInertia = preprocessor == StrokeStabilizer::Preprocessor::INERTIA;
gtk_widget_set_visible(builder.get("lbStabilizerDrag"), showInertia);
gtk_widget_set_visible(builder.get("sbStabilizerDrag"), showInertia);
gtk_widget_set_visible(builder.get("lbStabilizerMass"), showInertia);
gtk_widget_set_visible(builder.get("sbStabilizerMass"), showInertia);
bool averagingOn = static_cast<StrokeStabilizer::AveragingMethod>(
gtk_combo_box_get_active(GTK_COMBO_BOX(builder.get("cbStabilizerAveragingMethods")))) !=
StrokeStabilizer::AveragingMethod::NONE;
bool sensitive = showDeadzone || showInertia || averagingOn;
gtk_widget_set_sensitive(builder.get("cbStabilizerEnableFinalizeStroke"), sensitive);
}
void SettingsDialog::load() {
loadCheckbox("cbSettingPresureSensitivity", settings->isPressureSensitivity());
loadCheckbox("cbEnableZoomGestures", settings->isZoomGesturesEnabled());
loadCheckbox("cbShowSidebarRight", settings->isSidebarOnRight());
loadCheckbox("cbShowScrollbarLeft", settings->isScrollbarOnLeft());
loadCheckbox("cbAutoloadMostRecent", settings->isAutoloadMostRecent());
loadCheckbox("cbAutoloadXoj", settings->isAutoloadPdfXoj());
loadCheckbox("cbAutosave", settings->isAutosaveEnabled());
loadCheckbox("cbAddVerticalSpace", settings->getAddVerticalSpace());
loadCheckbox("cbAddHorizontalSpace", settings->getAddHorizontalSpace());
loadCheckbox("cbUnlimitedScrolling", settings->getUnlimitedScrolling());
loadCheckbox("cbDrawDirModsEnabled", settings->getDrawDirModsEnabled());
loadCheckbox("cbStrokeFilterEnabled", settings->getStrokeFilterEnabled());
loadCheckbox("cbDoActionOnStrokeFiltered", settings->getDoActionOnStrokeFiltered());
loadCheckbox("cbTrySelectOnStrokeFiltered", settings->getTrySelectOnStrokeFiltered());
loadCheckbox("cbSnapRecognizedShapesEnabled", settings->getSnapRecognizedShapesEnabled());
loadCheckbox("cbRestoreLineWidthEnabled", settings->getRestoreLineWidthEnabled());
loadCheckbox("cbStockIcons", settings->areStockIconsUsed());
loadCheckbox("cbHideHorizontalScrollbar", settings->getScrollbarHideType() & SCROLLBAR_HIDE_HORIZONTAL);
loadCheckbox("cbHideVerticalScrollbar", settings->getScrollbarHideType() & SCROLLBAR_HIDE_VERTICAL);
loadCheckbox("cbDisableScrollbarFadeout", settings->isScrollbarFadeoutDisabled());
loadCheckbox("cbDisableAudio", settings->isAudioDisabled());
loadCheckbox("cbEnablePressureInference", settings->isPressureGuessingEnabled());
loadCheckbox("cbTouchDrawing", settings->getTouchDrawingEnabled());
loadCheckbox("cbDisableGtkInertialScroll", !settings->getGtkTouchInertialScrollingEnabled());
const bool ignoreStylusEventsEnabled = settings->getIgnoredStylusEvents() != 0; // 0 means disabled, >0 enabled
loadCheckbox("cbIgnoreFirstStylusEvents", ignoreStylusEventsEnabled);
loadCheckbox("cbInputSystemTPCButton", settings->getInputSystemTPCButtonEnabled());
loadCheckbox("cbInputSystemDrawOutsideWindow", settings->getInputSystemDrawOutsideWindowEnabled());
/**
* Tab size related settings
*/
loadCheckbox("cbUseSpacesAsTab", settings->getUseSpacesAsTab());
GtkSpinButton* sbNumberOfSpacesForTab = GTK_SPIN_BUTTON(builder.get("sbNumberOfSpacesForTab"));
gtk_spin_button_set_value(sbNumberOfSpacesForTab, settings->getNumberOfSpacesForTab());
gtk_widget_set_sensitive(GTK_WIDGET(builder.get("numberOfSpacesContainer")), settings->getUseSpacesAsTab());
/**
* Stabilizer related settings
*/
loadCheckbox("cbStabilizerEnableCuspDetection", settings->getStabilizerCuspDetection());
loadCheckbox("cbStabilizerEnableFinalizeStroke", settings->getStabilizerFinalizeStroke());
GtkWidget* sbStabilizerBuffersize = builder.get("sbStabilizerBuffersize");
gtk_spin_button_set_value(GTK_SPIN_BUTTON(sbStabilizerBuffersize),
static_cast<double>(settings->getStabilizerBuffersize()));
GtkWidget* sbStabilizerDeadzoneRadius = builder.get("sbStabilizerDeadzoneRadius");
gtk_spin_button_set_value(GTK_SPIN_BUTTON(sbStabilizerDeadzoneRadius), settings->getStabilizerDeadzoneRadius());
GtkWidget* sbStabilizerDrag = builder.get("sbStabilizerDrag");
gtk_spin_button_set_value(GTK_SPIN_BUTTON(sbStabilizerDrag), settings->getStabilizerDrag());
GtkWidget* sbStabilizerMass = builder.get("sbStabilizerMass");
gtk_spin_button_set_value(GTK_SPIN_BUTTON(sbStabilizerMass), settings->getStabilizerMass());
GtkWidget* sbStabilizerSigma = builder.get("sbStabilizerSigma");
gtk_spin_button_set_value(GTK_SPIN_BUTTON(sbStabilizerSigma), settings->getStabilizerSigma());
GtkComboBox* cbStabilizerAveragingMethods = GTK_COMBO_BOX(builder.get("cbStabilizerAveragingMethods"));
gtk_combo_box_set_active(cbStabilizerAveragingMethods, static_cast<int>(settings->getStabilizerAveragingMethod()));
showStabilizerAvMethodOptions(settings->getStabilizerAveragingMethod());
GtkComboBox* cbStabilizerPreprocessors = GTK_COMBO_BOX(builder.get("cbStabilizerPreprocessors"));
gtk_combo_box_set_active(cbStabilizerPreprocessors, static_cast<int>(settings->getStabilizerPreprocessor()));
showStabilizerPreprocessorOptions(settings->getStabilizerPreprocessor());
/***********/
GtkComboBox* cbSidebarNumberingStyle = GTK_COMBO_BOX(builder.get("cbSidebarPageNumberStyle"));
gtk_combo_box_set_active(cbSidebarNumberingStyle, static_cast<int>(settings->getSidebarNumberingStyle()));
GtkWidget* txtDefaultSaveName = builder.get("txtDefaultSaveName");
gtk_entry_set_text(GTK_ENTRY(txtDefaultSaveName), settings->getDefaultSaveName().c_str());
GtkWidget* txtDefaultPdfName = builder.get("txtDefaultPdfName");
gtk_entry_set_text(GTK_ENTRY(txtDefaultPdfName), settings->getDefaultPdfExportName().c_str());
gtk_file_chooser_set_current_folder(GTK_FILE_CHOOSER(builder.get("fcAudioPath")),
Util::toGFilename(settings->getAudioFolder()).c_str());
GtkWidget* spAutosaveTimeout = builder.get("spAutosaveTimeout");
gtk_spin_button_set_value(GTK_SPIN_BUTTON(spAutosaveTimeout), settings->getAutosaveTimeout());
GtkWidget* spNumIgnoredStylusEvents = builder.get("spNumIgnoredStylusEvents");
if (!ignoreStylusEventsEnabled) { // The spinButton's value should be >= 1
gtk_spin_button_set_value(GTK_SPIN_BUTTON(spNumIgnoredStylusEvents), 1);
} else {
gtk_spin_button_set_value(GTK_SPIN_BUTTON(spNumIgnoredStylusEvents), settings->getIgnoredStylusEvents());
}
GtkWidget* spPairsOffset = builder.get("spPairsOffset");
gtk_spin_button_set_value(GTK_SPIN_BUTTON(spPairsOffset), settings->getPairsOffset());
EmptyLastPageAppendType append = settings->getEmptyLastPageAppend();
loadCheckbox("rdLastPageAppendOnDrawOfLastPage", append == EmptyLastPageAppendType::OnDrawOfLastPage);
loadCheckbox("rdLastPageAppendOnScrollToEndOfLastPage", append == EmptyLastPageAppendType::OnScrollToEndOfLastPage);
loadCheckbox("rdLastPageAppendDisabled", append == EmptyLastPageAppendType::Disabled);
GtkWidget* spSnapRotationTolerance = builder.get("spSnapRotationTolerance");
gtk_spin_button_set_value(GTK_SPIN_BUTTON(spSnapRotationTolerance), settings->getSnapRotationTolerance());
GtkWidget* spSnapGridTolerance = builder.get("spSnapGridTolerance");
gtk_spin_button_set_value(GTK_SPIN_BUTTON(spSnapGridTolerance), settings->getSnapGridTolerance());
GtkWidget* spSnapGridSize = builder.get("spSnapGridSize");
gtk_spin_button_set_value(GTK_SPIN_BUTTON(spSnapGridSize), settings->getSnapGridSize() / DEFAULT_GRID_SIZE);
GtkWidget* spStrokeRecognizerMinSize = builder.get("spStrokeRecognizerMinSize");
gtk_spin_button_set_value(GTK_SPIN_BUTTON(spStrokeRecognizerMinSize), settings->getStrokeRecognizerMinSize());
gtk_spin_button_set_value(GTK_SPIN_BUTTON(builder.get("edgePanSpeed")), settings->getEdgePanSpeed());
gtk_spin_button_set_value(GTK_SPIN_BUTTON(builder.get("edgePanMaxMult")), settings->getEdgePanMaxMult());
GtkWidget* spZoomStep = builder.get("spZoomStep");
gtk_spin_button_set_value(GTK_SPIN_BUTTON(spZoomStep), settings->getZoomStep());
GtkWidget* spZoomStepScroll = builder.get("spZoomStepScroll");
gtk_spin_button_set_value(GTK_SPIN_BUTTON(spZoomStepScroll), settings->getZoomStepScroll());
GtkWidget* spAddHorizontalSpaceRight = builder.get("spAddHorizontalSpaceRight");
gtk_spin_button_set_value(GTK_SPIN_BUTTON(spAddHorizontalSpaceRight), settings->getAddHorizontalSpaceAmountRight());
GtkWidget* spAddVerticalSpaceAbove = builder.get("spAddVerticalSpaceAbove");
gtk_spin_button_set_value(GTK_SPIN_BUTTON(spAddVerticalSpaceAbove), settings->getAddVerticalSpaceAmountAbove());
GtkWidget* spAddHorizontalSpaceLeft = builder.get("spAddHorizontalSpaceLeft");
gtk_spin_button_set_value(GTK_SPIN_BUTTON(spAddHorizontalSpaceLeft), settings->getAddHorizontalSpaceAmountLeft());
GtkWidget* spAddVerticalSpaceBelow = builder.get("spAddVerticalSpaceBelow");
gtk_spin_button_set_value(GTK_SPIN_BUTTON(spAddVerticalSpaceBelow), settings->getAddVerticalSpaceAmountBelow());
GtkWidget* spDrawDirModsRadius = builder.get("spDrawDirModsRadius");
gtk_spin_button_set_value(GTK_SPIN_BUTTON(spDrawDirModsRadius), settings->getDrawDirModsRadius());
GtkWidget* spReRenderThreshold = builder.get("spReRenderThreshold");
gtk_spin_button_set_value(GTK_SPIN_BUTTON(spReRenderThreshold), settings->getPDFPageRerenderThreshold());
GtkWidget* spTouchZoomStartThreshold = builder.get("spTouchZoomStartThreshold");
gtk_spin_button_set_value(GTK_SPIN_BUTTON(spTouchZoomStartThreshold), settings->getTouchZoomStartThreshold());
{
int time = 0;
double length = 0;
int successive = 0;
settings->getStrokeFilter(&time, &length, &successive);
GtkWidget* spStrokeIgnoreTime = builder.get("spStrokeIgnoreTime");
gtk_spin_button_set_value(GTK_SPIN_BUTTON(spStrokeIgnoreTime), time);
GtkWidget* spStrokeIgnoreLength = builder.get("spStrokeIgnoreLength");
gtk_spin_button_set_value(GTK_SPIN_BUTTON(spStrokeIgnoreLength), length);
GtkWidget* spStrokeSuccessiveTime = builder.get("spStrokeSuccessiveTime");
gtk_spin_button_set_value(GTK_SPIN_BUTTON(spStrokeSuccessiveTime), successive);
}
this->setDpi(settings->getDisplayDpi());
loadSlider("zoomCallibSlider", dpi);
loadSlider("scaleMinimumPressure", settings->getMinimumPressure());
loadSlider("scalePressureMultiplier", settings->getPressureMultiplier());
GdkRGBA color = Util::rgb_to_GdkRGBA(settings->getBorderColor());
gtk_color_chooser_set_rgba(GTK_COLOR_CHOOSER(builder.get("colorBorder")), &color);
color = Util::rgb_to_GdkRGBA(settings->getBackgroundColor());
gtk_color_chooser_set_rgba(GTK_COLOR_CHOOSER(builder.get("colorBackground")), &color);
color = Util::rgb_to_GdkRGBA(settings->getSelectionColor());
gtk_color_chooser_set_rgba(GTK_COLOR_CHOOSER(builder.get("colorSelection")), &color);
color = Util::rgb_to_GdkRGBA(settings->getActiveSelectionColor());
gtk_color_chooser_set_rgba(GTK_COLOR_CHOOSER(builder.get("colorSelectionActive")), &color);
loadCheckbox("cbHighlightPosition", settings->isHighlightPosition());
color = Util::argb_to_GdkRGBA(settings->getCursorHighlightColor());
gtk_color_chooser_set_rgba(GTK_COLOR_CHOOSER(builder.get("cursorHighlightColor")), &color);
color = Util::argb_to_GdkRGBA(settings->getCursorHighlightBorderColor());
gtk_color_chooser_set_rgba(GTK_COLOR_CHOOSER(builder.get("cursorHighlightBorderColor")), &color);
gtk_spin_button_set_value(GTK_SPIN_BUTTON(builder.get("cursorHighlightRadius")),
settings->getCursorHighlightRadius());
gtk_spin_button_set_value(GTK_SPIN_BUTTON(builder.get("cursorHighlightBorderWidth")),
settings->getCursorHighlightBorderWidth());
switch (settings->getStylusCursorType()) {
case STYLUS_CURSOR_NONE:
gtk_combo_box_set_active(GTK_COMBO_BOX(builder.get("cbStylusCursorType")), 0);
break;
case STYLUS_CURSOR_BIG:
gtk_combo_box_set_active(GTK_COMBO_BOX(builder.get("cbStylusCursorType")), 2);
break;
case STYLUS_CURSOR_ARROW:
gtk_combo_box_set_active(GTK_COMBO_BOX(builder.get("cbStylusCursorType")), 3);
break;
case STYLUS_CURSOR_DOT:
default:
gtk_combo_box_set_active(GTK_COMBO_BOX(builder.get("cbStylusCursorType")), 1);
break;
}
switch (settings->getEraserVisibility()) {
case ERASER_VISIBILITY_NEVER:
gtk_combo_box_set_active(GTK_COMBO_BOX(builder.get("cbEraserVisibility")), 0);
break;
case ERASER_VISIBILITY_HOVER:
gtk_combo_box_set_active(GTK_COMBO_BOX(builder.get("cbEraserVisibility")), 2);
break;
case ERASER_VISIBILITY_TOUCH:
gtk_combo_box_set_active(GTK_COMBO_BOX(builder.get("cbEraserVisibility")), 3);
break;
case ERASER_VISIBILITY_ALWAYS:
default:
gtk_combo_box_set_active(GTK_COMBO_BOX(builder.get("cbEraserVisibility")), 1);
break;
}
switch (settings->getIconTheme()) {
case ICON_THEME_LUCIDE:
gtk_combo_box_set_active(GTK_COMBO_BOX(builder.get("cbIconTheme")), 1);
break;
case ICON_THEME_COLOR:
default:
gtk_combo_box_set_active(GTK_COMBO_BOX(builder.get("cbIconTheme")), 0);
break;
}
switch (settings->getThemeVariant()) {
case THEME_VARIANT_FORCE_LIGHT:
gtk_combo_box_set_active(GTK_COMBO_BOX(builder.get("cbThemeVariant")), 1);
break;
case THEME_VARIANT_FORCE_DARK:
gtk_combo_box_set_active(GTK_COMBO_BOX(builder.get("cbThemeVariant")), 2);
break;
case THEME_VARIANT_USE_SYSTEM:
default:
gtk_combo_box_set_active(GTK_COMBO_BOX(builder.get("cbThemeVariant")), 0);
break;
}
auto viewMode = settings->getViewModes().at(PresetViewModeIds::VIEW_MODE_FULLSCREEN);
bool showFullscreenMenubar = viewMode.showMenubar;
bool showFullscreenToolbar = viewMode.showToolbar;
bool showFullscreenSidebar = viewMode.showSidebar;
viewMode = settings->getViewModes().at(PresetViewModeIds::VIEW_MODE_PRESENTATION);
bool showPresentationMenubar = viewMode.showMenubar;
bool showPresentationToolbar = viewMode.showToolbar;
bool showPresentationSidebar = viewMode.showSidebar;
bool goPresentationFullscreen = viewMode.goFullscreen;
loadCheckbox("cbShowFullscreenMenubar", showFullscreenMenubar);
loadCheckbox("cbShowFullscreenToolbar", showFullscreenToolbar);
loadCheckbox("cbShowFullscreenSidebar", showFullscreenSidebar);
loadCheckbox("cbShowPresentationMenubar", showPresentationMenubar);
loadCheckbox("cbShowPresentationToolbar", showPresentationToolbar);
loadCheckbox("cbShowPresentationSidebar", showPresentationSidebar);
loadCheckbox("cbPresentationGoFullscreen", goPresentationFullscreen);
loadCheckbox("cbHideMenubarStartup", settings->isMenubarVisible());
loadCheckbox("cbShowFilepathInTitlebar", settings->isFilepathInTitlebarShown());
loadCheckbox("cbShowPageNumberInTitlebar", settings->isPageNumberInTitlebarShown());
gtk_spin_button_set_value(GTK_SPIN_BUTTON(builder.get("preloadPagesBefore")),
static_cast<double>(settings->getPreloadPagesBefore()));
gtk_spin_button_set_value(GTK_SPIN_BUTTON(builder.get("preloadPagesAfter")),
static_cast<double>(settings->getPreloadPagesAfter()));
loadCheckbox("cbEagerPageCleanup", settings->isEagerPageCleanup());
disableWithCheckbox("cbUnlimitedScrolling", "cbAddVerticalSpace");
disableWithCheckbox("cbUnlimitedScrolling", "cbAddHorizontalSpace");
enableWithCheckbox("cbAutosave", "boxAutosave");
enableWithCheckbox("cbIgnoreFirstStylusEvents", "spNumIgnoredStylusEvents");
enableWithEnabledCheckbox("cbAddVerticalSpace", "spAddVerticalSpaceAbove");
enableWithEnabledCheckbox("cbAddHorizontalSpace", "spAddHorizontalSpaceRight");
enableWithEnabledCheckbox("cbAddVerticalSpace", "spAddVerticalSpaceBelow");
enableWithEnabledCheckbox("cbAddHorizontalSpace", "spAddHorizontalSpaceLeft");
enableWithCheckbox("cbDrawDirModsEnabled", "spDrawDirModsRadius");
enableWithCheckbox("cbStrokeFilterEnabled", "spStrokeIgnoreTime");
enableWithCheckbox("cbStrokeFilterEnabled", "spStrokeIgnoreLength");
enableWithCheckbox("cbStrokeFilterEnabled", "spStrokeSuccessiveTime");
enableWithCheckbox("cbStrokeFilterEnabled", "cbDoActionOnStrokeFiltered");
enableWithCheckbox("cbStrokeFilterEnabled", "cbTrySelectOnStrokeFiltered");
enableWithCheckbox("cbEnableZoomGestures", "gdStartZoomAtSetting");
enableWithCheckbox("cbDisableTouchOnPenNear", "boxInternalHandRecognition");
customHandRecognitionToggled();
customStylusIconTypeChanged();
updatePressureSensitivityOptions();
SElement& touch = settings->getCustomElement("touch");
bool disablePen = false;
touch.getBool("disableTouch", disablePen);
loadCheckbox("cbDisableTouchOnPenNear", disablePen);
string disableMethod;
touch.getString("method", disableMethod);
int methodId = 0;
if (disableMethod == "X11") {
methodId = 1;
} else if (disableMethod == "custom") {
methodId = 2;
}
gtk_combo_box_set_active(GTK_COMBO_BOX(builder.get("cbTouchDisableMethod")), methodId);
string cmd;
touch.getString("cmdEnable", cmd);
gtk_entry_set_text(GTK_ENTRY(builder.get("txtEnableTouchCommand")), cmd.c_str());
cmd = "";
touch.getString("cmdDisable", cmd);
gtk_entry_set_text(GTK_ENTRY(builder.get("txtDisableTouchCommand")), cmd.c_str());
int timeoutMs = 1000;
touch.getInt("timeout", timeoutMs);
gtk_spin_button_set_value(GTK_SPIN_BUTTON(builder.get("spTouchDisableTimeout")), timeoutMs / 1000.0);
if (this->control->getAudioController()) {
this->audioInputDevices = this->control->getAudioController()->getInputDevices();
gtk_combo_box_text_append(GTK_COMBO_BOX_TEXT(builder.get("cbAudioInputDevice")), "", "System default");
gtk_combo_box_set_active(GTK_COMBO_BOX(builder.get("cbAudioInputDevice")), 0);
for (auto& audioInputDevice: this->audioInputDevices) {
gtk_combo_box_text_append(GTK_COMBO_BOX_TEXT(builder.get("cbAudioInputDevice")), "",
audioInputDevice.getDeviceName().c_str());
}
for (size_t i = 0; i < this->audioInputDevices.size(); i++) {
if (this->audioInputDevices[i].getSelected()) {
gtk_combo_box_set_active(GTK_COMBO_BOX(builder.get("cbAudioInputDevice")), static_cast<gint>(i + 1));
}
}
this->audioOutputDevices = this->control->getAudioController()->getOutputDevices();
gtk_combo_box_text_append(GTK_COMBO_BOX_TEXT(builder.get("cbAudioOutputDevice")), "", "System default");
gtk_combo_box_set_active(GTK_COMBO_BOX(builder.get("cbAudioOutputDevice")), 0);
for (auto& audioOutputDevice: this->audioOutputDevices) {
gtk_combo_box_text_append(GTK_COMBO_BOX_TEXT(builder.get("cbAudioOutputDevice")), "",
audioOutputDevice.getDeviceName().c_str());
}
for (size_t i = 0; i < this->audioOutputDevices.size(); i++) {
if (this->audioOutputDevices[i].getSelected()) {
gtk_combo_box_set_active(GTK_COMBO_BOX(builder.get("cbAudioOutputDevice")), static_cast<gint>(i + 1));
}
}
switch (static_cast<int>(settings->getAudioSampleRate())) {
case 16000:
gtk_combo_box_set_active(GTK_COMBO_BOX(builder.get("cbAudioSampleRate")), 0);
break;
case 96000:
gtk_combo_box_set_active(GTK_COMBO_BOX(builder.get("cbAudioSampleRate")), 2);
break;
case 192000:
gtk_combo_box_set_active(GTK_COMBO_BOX(builder.get("cbAudioSampleRate")), 3);
break;
case 44100:
default:
gtk_combo_box_set_active(GTK_COMBO_BOX(builder.get("cbAudioSampleRate")), 1);
break;
}
gtk_spin_button_set_value(GTK_SPIN_BUTTON(builder.get("spAudioGain")), settings->getAudioGain());
gtk_spin_button_set_value(GTK_SPIN_BUTTON(builder.get("spDefaultSeekTime")), settings->getDefaultSeekTime());
}
this->latexPanel.load(settings->latexSettings);
paletteTab.renderPaletteTab(this->control->getPalette().getFilePath());
}
void SettingsDialog::save() {
settings->transactionStart();
settings->setPressureSensitivity(getCheckbox("cbSettingPresureSensitivity"));
settings->setMinimumPressure(getSlider("scaleMinimumPressure"));
settings->setPressureMultiplier(getSlider("scalePressureMultiplier"));
settings->setZoomGesturesEnabled(getCheckbox("cbEnableZoomGestures"));
settings->setSidebarOnRight(getCheckbox("cbShowSidebarRight"));
settings->setScrollbarOnLeft(getCheckbox("cbShowScrollbarLeft"));
settings->setAutoloadMostRecent(getCheckbox("cbAutoloadMostRecent"));
settings->setAutoloadPdfXoj(getCheckbox("cbAutoloadXoj"));
settings->setAutosaveEnabled(getCheckbox("cbAutosave"));
settings->setAddVerticalSpace(getCheckbox("cbAddVerticalSpace"));
settings->setAddHorizontalSpace(getCheckbox("cbAddHorizontalSpace"));
settings->setUnlimitedScrolling(getCheckbox("cbUnlimitedScrolling"));
settings->setDrawDirModsEnabled(getCheckbox("cbDrawDirModsEnabled"));
settings->setStrokeFilterEnabled(getCheckbox("cbStrokeFilterEnabled"));
settings->setDoActionOnStrokeFiltered(getCheckbox("cbDoActionOnStrokeFiltered"));
settings->setTrySelectOnStrokeFiltered(getCheckbox("cbTrySelectOnStrokeFiltered"));
settings->setSnapRecognizedShapesEnabled(getCheckbox("cbSnapRecognizedShapesEnabled"));
settings->setRestoreLineWidthEnabled(getCheckbox("cbRestoreLineWidthEnabled"));
settings->setAreStockIconsUsed(getCheckbox("cbStockIcons"));
settings->setPressureGuessingEnabled(getCheckbox("cbEnablePressureInference"));
settings->setTouchDrawingEnabled(getCheckbox("cbTouchDrawing"));
settings->setGtkTouchInertialScrollingEnabled(!getCheckbox("cbDisableGtkInertialScroll"));
settings->setInputSystemTPCButtonEnabled(getCheckbox("cbInputSystemTPCButton"));
settings->setInputSystemDrawOutsideWindowEnabled(getCheckbox("cbInputSystemDrawOutsideWindow"));
settings->setScrollbarFadeoutDisabled(getCheckbox("cbDisableScrollbarFadeout"));
settings->setAudioDisabled(getCheckbox("cbDisableAudio"));
/**
* Tab size relate settings
*/
settings->setUseSpacesAsTab(getCheckbox("cbUseSpacesAsTab"));
settings->setNumberOfSpacesForTab(static_cast<unsigned int>(
gtk_spin_button_get_value_as_int(GTK_SPIN_BUTTON(builder.get("sbNumberOfSpacesForTab")))));
/**
* Stabilizer related settings
*/
settings->setStabilizerAveragingMethod(static_cast<StrokeStabilizer::AveragingMethod>(
gtk_combo_box_get_active(GTK_COMBO_BOX(builder.get("cbStabilizerAveragingMethods")))));
settings->setStabilizerPreprocessor(static_cast<StrokeStabilizer::Preprocessor>(
gtk_combo_box_get_active(GTK_COMBO_BOX(builder.get("cbStabilizerPreprocessors")))));
settings->setStabilizerBuffersize(static_cast<size_t>(
gtk_spin_button_get_value_as_int(GTK_SPIN_BUTTON(builder.get("sbStabilizerBuffersize")))));
settings->setStabilizerDeadzoneRadius(
gtk_spin_button_get_value(GTK_SPIN_BUTTON(builder.get("sbStabilizerDeadzoneRadius"))));
settings->setStabilizerDrag(gtk_spin_button_get_value(GTK_SPIN_BUTTON(builder.get("sbStabilizerDrag"))));
settings->setStabilizerMass(gtk_spin_button_get_value(GTK_SPIN_BUTTON(builder.get("sbStabilizerMass"))));
settings->setStabilizerSigma(gtk_spin_button_get_value(GTK_SPIN_BUTTON(builder.get("sbStabilizerSigma"))));
settings->setStabilizerCuspDetection(getCheckbox("cbStabilizerEnableCuspDetection"));
settings->setStabilizerFinalizeStroke(getCheckbox("cbStabilizerEnableFinalizeStroke"));
settings->setSidebarNumberingStyle(static_cast<SidebarNumberingStyle>(
gtk_combo_box_get_active(GTK_COMBO_BOX(builder.get("cbSidebarPageNumberStyle")))));
auto scrollbarHideType =
static_cast<std::make_unsigned<std::underlying_type<ScrollbarHideType>::type>::type>(SCROLLBAR_HIDE_NONE);
if (getCheckbox("cbHideHorizontalScrollbar")) {
scrollbarHideType |= SCROLLBAR_HIDE_HORIZONTAL;
}
if (getCheckbox("cbHideVerticalScrollbar")) {
scrollbarHideType |= SCROLLBAR_HIDE_VERTICAL;
}
settings->setScrollbarHideType(static_cast<ScrollbarHideType>(scrollbarHideType));
GdkRGBA color;
gtk_color_chooser_get_rgba(GTK_COLOR_CHOOSER(builder.get("colorBorder")), &color);
settings->setBorderColor(Util::GdkRGBA_to_argb(color));
gtk_color_chooser_get_rgba(GTK_COLOR_CHOOSER(builder.get("colorBackground")), &color);
settings->setBackgroundColor(Util::GdkRGBA_to_argb(color));
gtk_color_chooser_get_rgba(GTK_COLOR_CHOOSER(builder.get("colorSelection")), &color);
settings->setSelectionColor(Util::GdkRGBA_to_argb(color));
gtk_color_chooser_get_rgba(GTK_COLOR_CHOOSER(builder.get("colorSelectionActive")), &color);
settings->setActiveSelectionColor(Util::GdkRGBA_to_argb(color));
settings->setHighlightPosition(getCheckbox("cbHighlightPosition"));
gtk_color_chooser_get_rgba(GTK_COLOR_CHOOSER(builder.get("cursorHighlightColor")), &color);
settings->setCursorHighlightColor(Util::GdkRGBA_to_argb(color));
gtk_color_chooser_get_rgba(GTK_COLOR_CHOOSER(builder.get("cursorHighlightBorderColor")), &color);
settings->setCursorHighlightBorderColor(Util::GdkRGBA_to_argb(color));
GtkWidget* spCursorHighlightRadius = builder.get("cursorHighlightRadius");
settings->setCursorHighlightRadius(gtk_spin_button_get_value(GTK_SPIN_BUTTON(spCursorHighlightRadius)));
GtkWidget* spCursorHighlightBorderWidth = builder.get("cursorHighlightBorderWidth");
settings->setCursorHighlightBorderWidth(gtk_spin_button_get_value(GTK_SPIN_BUTTON(spCursorHighlightBorderWidth)));
switch (gtk_combo_box_get_active(GTK_COMBO_BOX(builder.get("cbStylusCursorType")))) {
case 0:
settings->setStylusCursorType(STYLUS_CURSOR_NONE);
break;
case 2:
settings->setStylusCursorType(STYLUS_CURSOR_BIG);
break;
case 3:
settings->setStylusCursorType(STYLUS_CURSOR_ARROW);
break;
case 1:
default:
settings->setStylusCursorType(STYLUS_CURSOR_DOT);
break;
}
switch (gtk_combo_box_get_active(GTK_COMBO_BOX(builder.get("cbEraserVisibility")))) {
case 0:
settings->setEraserVisibility(ERASER_VISIBILITY_NEVER);
break;
case 2:
settings->setEraserVisibility(ERASER_VISIBILITY_HOVER);
break;
case 3:
settings->setEraserVisibility(ERASER_VISIBILITY_TOUCH);
break;
case 1:
default:
settings->setEraserVisibility(ERASER_VISIBILITY_ALWAYS);
break;
}
switch (gtk_combo_box_get_active(GTK_COMBO_BOX(builder.get("cbIconTheme")))) {
case 1:
settings->setIconTheme(ICON_THEME_LUCIDE);
break;
case 0:
default:
settings->setIconTheme(ICON_THEME_COLOR);
break;
}
switch (gtk_combo_box_get_active(GTK_COMBO_BOX(builder.get("cbThemeVariant")))) {
case 1:
settings->setThemeVariant(THEME_VARIANT_FORCE_LIGHT);
break;
case 2:
settings->setThemeVariant(THEME_VARIANT_FORCE_DARK);
break;
case 0:
default:
settings->setThemeVariant(THEME_VARIANT_USE_SYSTEM);
break;
}
ViewMode viewModeFullscreen;
viewModeFullscreen.goFullscreen = true;
viewModeFullscreen.showMenubar = getCheckbox("cbShowFullscreenMenubar");
viewModeFullscreen.showToolbar = getCheckbox("cbShowFullscreenToolbar");
viewModeFullscreen.showSidebar = getCheckbox("cbShowFullscreenSidebar");
settings->setViewMode(PresetViewModeIds::VIEW_MODE_FULLSCREEN, viewModeFullscreen);
ViewMode viewModePresentation;
viewModePresentation.showMenubar = getCheckbox("cbShowPresentationMenubar");
viewModePresentation.showToolbar = getCheckbox("cbShowPresentationToolbar");
viewModePresentation.showSidebar = getCheckbox("cbShowPresentationSidebar");
viewModePresentation.goFullscreen = getCheckbox("cbPresentationGoFullscreen");
settings->setViewMode(PresetViewModeIds::VIEW_MODE_PRESENTATION, viewModePresentation);
settings->setMenubarVisible(getCheckbox("cbHideMenubarStartup"));
settings->setFilepathInTitlebarShown(getCheckbox("cbShowFilepathInTitlebar"));
settings->setPageNumberInTitlebarShown(getCheckbox("cbShowPageNumberInTitlebar"));
constexpr auto spinAsUint = [&](GtkSpinButton* btn) {
int v = gtk_spin_button_get_value_as_int(btn);
return v < 0 ? 0U : static_cast<unsigned int>(v);
};
unsigned int preloadPagesBefore = spinAsUint(GTK_SPIN_BUTTON(builder.get("preloadPagesBefore")));
unsigned int preloadPagesAfter = spinAsUint(GTK_SPIN_BUTTON(builder.get("preloadPagesAfter")));
settings->setPreloadPagesAfter(preloadPagesAfter);
settings->setPreloadPagesBefore(preloadPagesBefore);
settings->setEagerPageCleanup(getCheckbox("cbEagerPageCleanup"));
settings->setDefaultSaveName(gtk_entry_get_text(GTK_ENTRY(builder.get("txtDefaultSaveName"))));
settings->setDefaultPdfExportName(gtk_entry_get_text(GTK_ENTRY(builder.get("txtDefaultPdfName"))));
// Todo(fabian): use Util::fromGFilename!
auto file = gtk_file_chooser_get_file(GTK_FILE_CHOOSER(builder.get("fcAudioPath")));
auto path = Util::fromGFile(file);
g_object_unref(file);
if (fs::is_directory(path)) {
settings->setAudioFolder(path);
}
GtkWidget* spAutosaveTimeout = builder.get("spAutosaveTimeout");
int autosaveTimeout = static_cast<int>(gtk_spin_button_get_value(GTK_SPIN_BUTTON(spAutosaveTimeout)));
settings->setAutosaveTimeout(autosaveTimeout);
if (getCheckbox("cbIgnoreFirstStylusEvents")) {
GtkWidget* spNumIgnoredStylusEvents = builder.get("spNumIgnoredStylusEvents");
int numIgnoredStylusEvents =
static_cast<int>(gtk_spin_button_get_value(GTK_SPIN_BUTTON(spNumIgnoredStylusEvents)));
settings->setIgnoredStylusEvents(numIgnoredStylusEvents);
} else {
settings->setIgnoredStylusEvents(0); // This means nothing will be ignored
}
GtkWidget* spPairsOffset = builder.get("spPairsOffset");
int numPairsOffset = static_cast<int>(gtk_spin_button_get_value(GTK_SPIN_BUTTON(spPairsOffset)));
settings->setPairsOffset(numPairsOffset);
if (getCheckbox("rdLastPageAppendDisabled")) {
settings->setEmptyLastPageAppend(EmptyLastPageAppendType::Disabled);
} else if (getCheckbox("rdLastPageAppendOnDrawOfLastPage")) {
settings->setEmptyLastPageAppend(EmptyLastPageAppendType::OnDrawOfLastPage);
} else if (getCheckbox("rdLastPageAppendOnScrollToEndOfLastPage")) {
settings->setEmptyLastPageAppend(EmptyLastPageAppendType::OnScrollToEndOfLastPage);
} else {
settings->setEmptyLastPageAppend(EmptyLastPageAppendType::Disabled);
}
settings->setEdgePanSpeed(gtk_spin_button_get_value(GTK_SPIN_BUTTON(builder.get("edgePanSpeed"))));
settings->setEdgePanMaxMult(gtk_spin_button_get_value(GTK_SPIN_BUTTON(builder.get("edgePanMaxMult"))));
GtkWidget* spZoomStep = builder.get("spZoomStep");
double zoomStep = gtk_spin_button_get_value(GTK_SPIN_BUTTON(spZoomStep));
settings->setZoomStep(zoomStep);
GtkWidget* spZoomStepScroll = builder.get("spZoomStepScroll");
double zoomStepScroll = gtk_spin_button_get_value(GTK_SPIN_BUTTON(spZoomStepScroll));
settings->setZoomStepScroll(zoomStepScroll);
GtkWidget* spAddHorizontalSpaceRight = builder.get("spAddHorizontalSpaceRight");
const int addHorizontalSpaceAmountRight =
static_cast<int>(gtk_spin_button_get_value(GTK_SPIN_BUTTON(spAddHorizontalSpaceRight)));
settings->setAddHorizontalSpaceAmountRight(addHorizontalSpaceAmountRight);
GtkWidget* spAddVerticalSpaceAbove = builder.get("spAddVerticalSpaceAbove");
const int addVerticalSpaceAmountAbove =
static_cast<int>(gtk_spin_button_get_value(GTK_SPIN_BUTTON(spAddVerticalSpaceAbove)));
settings->setAddVerticalSpaceAmountAbove(addVerticalSpaceAmountAbove);
GtkWidget* spAddHorizontalSpaceLeft = builder.get("spAddHorizontalSpaceLeft");
const int addHorizontalSpaceAmountLeft =
static_cast<int>(gtk_spin_button_get_value(GTK_SPIN_BUTTON(spAddHorizontalSpaceLeft)));
settings->setAddHorizontalSpaceAmountLeft(addHorizontalSpaceAmountLeft);
GtkWidget* spAddVerticalSpaceBelow = builder.get("spAddVerticalSpaceBelow");
const int addVerticalSpaceAmountBelow =
static_cast<int>(gtk_spin_button_get_value(GTK_SPIN_BUTTON(spAddVerticalSpaceBelow)));
settings->setAddVerticalSpaceAmountBelow(addVerticalSpaceAmountBelow);
GtkWidget* spDrawDirModsRadius = builder.get("spDrawDirModsRadius");
int drawDirModsRadius = static_cast<int>(gtk_spin_button_get_value(GTK_SPIN_BUTTON(spDrawDirModsRadius)));
settings->setDrawDirModsRadius(drawDirModsRadius);
GtkWidget* spStrokeIgnoreTime = builder.get("spStrokeIgnoreTime");
int strokeIgnoreTime = static_cast<int>(gtk_spin_button_get_value(GTK_SPIN_BUTTON(spStrokeIgnoreTime)));
GtkWidget* spStrokeIgnoreLength = builder.get("spStrokeIgnoreLength");
double strokeIgnoreLength = gtk_spin_button_get_value(GTK_SPIN_BUTTON(spStrokeIgnoreLength));
GtkWidget* spStrokeSuccessiveTime = builder.get("spStrokeSuccessiveTime");
int strokeSuccessiveTime = static_cast<int>(gtk_spin_button_get_value(GTK_SPIN_BUTTON(spStrokeSuccessiveTime)));
settings->setStrokeFilter(strokeIgnoreTime, strokeIgnoreLength, strokeSuccessiveTime);
GtkWidget* spTouchZoomStartThreshold = builder.get("spTouchZoomStartThreshold");
double zoomStartThreshold = gtk_spin_button_get_value(GTK_SPIN_BUTTON(spTouchZoomStartThreshold));
settings->setTouchZoomStartThreshold(zoomStartThreshold);
GtkWidget* spReRenderThreshold = builder.get("spReRenderThreshold");
double rerenderThreshold = gtk_spin_button_get_value(GTK_SPIN_BUTTON(spReRenderThreshold));
settings->setPDFPageRerenderThreshold(rerenderThreshold);
settings->setDisplayDpi(dpi);
for (auto&& bcg: this->buttonConfigs) {
bcg->saveSettings();
}
languageConfig.saveSettings();
SElement& touch = settings->getCustomElement("touch");
touch.setBool("disableTouch", getCheckbox("cbDisableTouchOnPenNear"));
int touchMethod = gtk_combo_box_get_active(GTK_COMBO_BOX(builder.get("cbTouchDisableMethod")));
switch (touchMethod) {
case 1:
touch.setString("method", "X11");
break;
case 2:
touch.setString("method", "custom");
break;
case 0:
default:
touch.setString("method", "auto");
}
touch.setString("cmdEnable", gtk_entry_get_text(GTK_ENTRY(builder.get("txtEnableTouchCommand"))));
touch.setString("cmdDisable", gtk_entry_get_text(GTK_ENTRY(builder.get("txtDisableTouchCommand"))));
touch.setInt(
"timeout",
static_cast<int>(gtk_spin_button_get_value(GTK_SPIN_BUTTON(builder.get("spTouchDisableTimeout"))) * 1000));
settings->setSnapRotationTolerance(
static_cast<double>(gtk_spin_button_get_value(GTK_SPIN_BUTTON(builder.get("spSnapRotationTolerance")))));
settings->setSnapGridTolerance(
static_cast<double>(gtk_spin_button_get_value(GTK_SPIN_BUTTON(builder.get("spSnapGridTolerance")))));
settings->setSnapGridSize(static_cast<double>(
gtk_spin_button_get_value(GTK_SPIN_BUTTON(builder.get("spSnapGridSize"))) * DEFAULT_GRID_SIZE));
settings->setStrokeRecognizerMinSize(
static_cast<double>(gtk_spin_button_get_value(GTK_SPIN_BUTTON(builder.get("spStrokeRecognizerMinSize")))));
size_t selectedInputDeviceIndex =
static_cast<size_t>(gtk_combo_box_get_active(GTK_COMBO_BOX(builder.get("cbAudioInputDevice"))));
if (selectedInputDeviceIndex == 0) {
settings->setAudioInputDevice(Settings::AUDIO_INPUT_SYSTEM_DEFAULT);
} else if (selectedInputDeviceIndex - 1 < this->audioInputDevices.size()) {
settings->setAudioInputDevice(this->audioInputDevices[selectedInputDeviceIndex - 1].getIndex());
}
size_t selectedOutputDeviceIndex =
static_cast<size_t>(gtk_combo_box_get_active(GTK_COMBO_BOX(builder.get("cbAudioOutputDevice"))));
if (selectedOutputDeviceIndex == 0) {
settings->setAudioOutputDevice(Settings::AUDIO_OUTPUT_SYSTEM_DEFAULT);
} else if (selectedOutputDeviceIndex - 1 < this->audioOutputDevices.size()) {
settings->setAudioOutputDevice(this->audioOutputDevices[selectedOutputDeviceIndex - 1].getIndex());
}
switch (gtk_combo_box_get_active(GTK_COMBO_BOX(builder.get("cbAudioSampleRate")))) {
case 0:
settings->setAudioSampleRate(16000.0);
break;
case 2:
settings->setAudioSampleRate(96000.0);
break;
case 3:
settings->setAudioSampleRate(192000.0);
break;
case 1:
default:
settings->setAudioSampleRate(44100.0);
break;
}
settings->setAudioGain(static_cast<double>(gtk_spin_button_get_value(GTK_SPIN_BUTTON(builder.get("spAudioGain")))));
settings->setDefaultSeekTime(
static_cast<unsigned int>(gtk_spin_button_get_value(GTK_SPIN_BUTTON(builder.get("spDefaultSeekTime")))));
const std::optional<std::filesystem::path> selectedPalette = paletteTab.getSelectedPalette();
if (selectedPalette.has_value()) {
settings->setColorPaletteSetting(selectedPalette.value());
}
for (auto& deviceClassConfigGui: this->deviceClassConfigs) {
deviceClassConfigGui.saveSettings();
}
this->latexPanel.save(settings->latexSettings);
settings->transactionEnd();
this->control->getWindow()->setGtkTouchscreenScrollingForDeviceMapping();
this->control->initButtonTool();
this->control->getWindow()->getXournal()->onSettingsChanged();
}
| 56,489
|
C++
|
.cpp
| 887
| 54.621195
| 120
| 0.708505
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,570
|
PluginDialogEntry.cpp
|
xournalpp_xournalpp/src/core/gui/dialog/PluginDialogEntry.cpp
|
#include "PluginDialogEntry.h"
#ifdef ENABLE_PLUGINS
#include "gui/Builder.h"
#include "plugin/Plugin.h"
#include "util/gtk4_helper.h"
#include "util/i18n.h"
#include "filesystem.h" // for path
class GladeSearchpath;
constexpr auto UI_FILE = "pluginEntry.glade";
constexpr auto UI_WIDGET_NAME = "pluginMainBox";
PluginDialogEntry::PluginDialogEntry(Plugin* plugin, GladeSearchpath* gladeSearchPath, GtkBox* box): plugin(plugin) {
Builder builder(gladeSearchPath, UI_FILE);
gtk_box_append(box, builder.get(UI_WIDGET_NAME));
stateButton = GTK_CHECK_BUTTON(builder.get("cbEnabled"));
gtk_label_set_text(GTK_LABEL(builder.get("pluginName")), plugin->getName().c_str());
gtk_label_set_text(GTK_LABEL(builder.get("lbAuthor")), plugin->getAuthor().c_str());
gtk_label_set_text(GTK_LABEL(builder.get("lbVersion")), plugin->getVersion().c_str());
gtk_label_set_text(GTK_LABEL(builder.get("lbDescription")), plugin->getDescription().c_str());
gtk_label_set_text(GTK_LABEL(builder.get("lbPath")), plugin->getPath().u8string().c_str());
gtk_label_set_text(GTK_LABEL(builder.get("lbDefaultText")),
plugin->isDefaultEnabled() ? _("default enabled") : _("default disabled"));
gtk_check_button_set_active(stateButton, plugin->isEnabled());
}
void PluginDialogEntry::saveSettings(std::string& pluginEnabled, std::string& pluginDisabled) {
bool state = gtk_check_button_get_active(stateButton);
if (state == plugin->isDefaultEnabled()) {
return;
}
if (state) {
if (!pluginEnabled.empty()) {
pluginEnabled += ",";
}
pluginEnabled += plugin->getPath().u8string();
} else {
if (!pluginDisabled.empty()) {
pluginDisabled += ",";
}
pluginDisabled += plugin->getPath().u8string();
}
}
#endif
| 1,847
|
C++
|
.cpp
| 41
| 39.707317
| 117
| 0.680223
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,571
|
LanguageConfigGui.cpp
|
xournalpp_xournalpp/src/core/gui/dialog/LanguageConfigGui.cpp
|
#include "LanguageConfigGui.h"
#include <algorithm> // for find, lower_bound, sort
#include <cstdlib> // for setenv
#include <memory> // for allocator, __alloc_traits<>::...
#include <glib-object.h> // for G_TYPE_STRING
#include <glib.h> // for g_warning, gint
#include "control/settings/Settings.h" // for Settings
#include "util/PathUtil.h" // for getGettextFilepath, getLocale...
#include "util/StringUtils.h" // for StringUtils
#include "util/XojMsgBox.h" // for XojMsgBox
#include "util/i18n.h" // for _
#include "util/safe_casts.h" // for as_unsigned
#include "config.h" // for GETTEXT_PACKAGE
#include "filesystem.h" // for directory_iterator, operator/
class GladeSearchpath;
LanguageConfigGui::LanguageConfigGui(GladeSearchpath* gladeSearchPath, GtkWidget* w, Settings* settings):
GladeGui(gladeSearchPath, "settingsLanguageConfig.glade", "offscreenwindow"), settings(settings) {
auto dropdown = get("languageSettingsDropdown");
gtk_container_remove(GTK_CONTAINER(getWindow()), dropdown);
gtk_container_add(GTK_CONTAINER(w), dropdown);
gtk_widget_show_all(dropdown);
// Fetch available locales
try {
fs::path baseLocaleDir = Util::getGettextFilepath(Util::getLocalePath());
for (auto const& d: fs::directory_iterator(baseLocaleDir)) {
if (auto mofile = (d.path() / "LC_MESSAGES" / GETTEXT_PACKAGE) += ".mo"; fs::exists(mofile)) {
availableLocales.push_back(d.path().filename().u8string());
}
}
} catch (const fs::filesystem_error& e) {
g_warning("%s", e.what());
}
std::sort(availableLocales.begin(), availableLocales.end());
// No pot file for English
if (auto enPos = std::lower_bound(availableLocales.begin(), availableLocales.end(), "en");
enPos != availableLocales.end() && !StringUtils::startsWith(*enPos, "en")) {
availableLocales.insert(enPos, "en");
}
// Default
availableLocales.insert(availableLocales.begin(), _("System Default"));
auto gtkAvailableLocales = gtk_list_store_new(1, G_TYPE_STRING);
for (auto const& i: availableLocales) {
GtkTreeIter iter;
gtk_list_store_append(gtkAvailableLocales, &iter);
gtk_list_store_set(gtkAvailableLocales, &iter, 0, i.c_str(), -1);
}
gtk_combo_box_set_model(GTK_COMBO_BOX(dropdown), GTK_TREE_MODEL(gtkAvailableLocales));
// Set the current locale if previously selected
auto prefPos = [&]() {
if (auto preferred = settings->getPreferredLocale(); !preferred.empty()) {
if (auto &&endi = availableLocales.end(), prefPos = std::find(availableLocales.begin(), endi, preferred);
prefPos != endi) {
return prefPos;
}
XojMsgBox::showErrorToUser(nullptr, _("Previously selected language not available anymore!"));
}
// Use system default
return availableLocales.begin();
}();
gtk_combo_box_set_active(GTK_COMBO_BOX(dropdown),
static_cast<gint>(std::distance(availableLocales.begin(), prefPos)));
}
void LanguageConfigGui::saveSettings() {
gint pos = gtk_combo_box_get_active(GTK_COMBO_BOX(get("languageSettingsDropdown")));
auto pref = (pos == 0) ? "" : availableLocales[as_unsigned(pos)];
settings->setPreferredLocale(pref);
settings->customSettingsChanged();
#ifdef _WIN32
_putenv_s("LANGUAGE", this->settings->getPreferredLocale().c_str());
#else
setenv("LANGUAGE", this->settings->getPreferredLocale().c_str(), 1);
#endif
}
| 3,644
|
C++
|
.cpp
| 73
| 43.767123
| 117
| 0.657199
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,572
|
ButtonConfigGui.cpp
|
xournalpp_xournalpp/src/core/gui/dialog/ButtonConfigGui.cpp
|
#include "ButtonConfigGui.h"
#include <memory> // for allocator, allocator_trai...
#include <utility> // for pair
#include <gdk-pixbuf/gdk-pixbuf.h> // for GDK_TYPE_PIXBUF, GdkPixbuf
#include <gdk/gdk.h> // for GdkRGBA
#include <glib-object.h> // for g_value_get_int, GValue
#include "control/DeviceListHelper.h" // for InputDevice, getDeviceList
#include "control/settings/ButtonConfig.h" // for ButtonConfig
#include "control/settings/Settings.h" // for Settings
#include "gui/Builder.h"
#include "util/Color.h" // for GdkRGBA_to_argb, rgb_to_G...
#include "util/gtk4_helper.h"
#include "util/i18n.h" // for _
class GladeSearchpath;
constexpr auto UI_FILE = "settingsButtonConfig.glade";
constexpr auto UI_WIDGET_NAME = "mainBox";
ButtonConfigGui::ToolSizeIndexMap ButtonConfigGui::toolSizeIndexMap = {{0, TOOL_SIZE_NONE}, {1, TOOL_SIZE_VERY_FINE},
{2, TOOL_SIZE_FINE}, {3, TOOL_SIZE_MEDIUM},
{4, TOOL_SIZE_THICK}, {5, TOOL_SIZE_VERY_THICK}};
std::string ButtonConfigGui::toolSizeToLabel(ToolSize size) {
switch (size) {
case TOOL_SIZE_NONE:
return "Thickness - don't change";
case TOOL_SIZE_VERY_FINE:
return "Very thin";
case TOOL_SIZE_FINE:
return "Thin";
case TOOL_SIZE_MEDIUM:
return "Medium";
case TOOL_SIZE_THICK:
return "Thick";
case TOOL_SIZE_VERY_THICK:
return "Very thick";
default:
return "";
}
}
void addToolToList(GtkListStore* typeModel, const char* icon, const char* name, ToolType action) {
GtkTreeIter iter;
gtk_list_store_append(typeModel, &iter);
GdkPixbuf* pixbuf = gtk_icon_theme_load_icon(gtk_icon_theme_get_default(), icon, 24,
static_cast<GtkIconLookupFlags>(0), nullptr);
gtk_list_store_set(typeModel, &iter, 0, pixbuf, -1);
gtk_list_store_set(typeModel, &iter, 1, name, 2, action, -1);
}
ButtonConfigGui::ButtonConfigGui(GladeSearchpath* gladeSearchPath, GtkBox* box, Settings* settings, unsigned int button,
bool withDevice):
settings(settings), button(button), withDevice(withDevice), iconNameHelper(settings) {
Builder builder(gladeSearchPath, UI_FILE);
gtk_box_append(box, builder.get(UI_WIDGET_NAME)); // box takes ownership of it all!
this->cbDevice = builder.get("labelDevice");
this->cbDisableDrawing = builder.get("cbDisableDrawing");
if (withDevice) {
gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(this->cbDevice), _("No device"));
this->deviceList = DeviceListHelper::getDeviceList(this->settings, true);
for (InputDevice const& dev: this->deviceList) {
std::string txt = dev.getName() + " (" + dev.getType() + ")";
gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(this->cbDevice), txt.c_str());
}
} else {
gtk_widget_hide(builder.get("lbDevice"));
gtk_widget_hide(this->cbDevice);
gtk_widget_hide(this->cbDisableDrawing);
}
GtkListStore* typeModel = gtk_list_store_new(3, GDK_TYPE_PIXBUF, G_TYPE_STRING, G_TYPE_INT); // NOLINT
auto addTypeCB = [=](const char* icon, const char* name, ToolType action) {
addToolToList(typeModel, iconNameHelper.iconName(icon).c_str(), name, action);
};
addTypeCB("transparent", _("Tool - don't change"), TOOL_NONE);
addTypeCB("tool-pencil", _("Pen"), TOOL_PEN);
addTypeCB("tool-eraser", _("Eraser"), TOOL_ERASER);
addTypeCB("tool-highlighter", _("Highlighter"), TOOL_HIGHLIGHTER);
addTypeCB("tool-text", _("Text"), TOOL_TEXT);
addTypeCB("tool-image", _("Insert image"), TOOL_IMAGE);
addTypeCB("spacer", _("Vertical space"), TOOL_VERTICAL_SPACE);
addTypeCB("select-lasso", _("Select region"), TOOL_SELECT_REGION);
addTypeCB("select-rect", _("Select rectangle"), TOOL_SELECT_RECT);
addTypeCB("select-multilayer-lasso", _("Select multi layer region"), TOOL_SELECT_MULTILAYER_REGION);
addTypeCB("select-multilayer-rect", _("Select multi layer rect"), TOOL_SELECT_MULTILAYER_RECT);
addTypeCB("hand", _("Hand"), TOOL_HAND);
addTypeCB("floating-toolbox", _("Floating Toolbox (experimental)"), TOOL_FLOATING_TOOLBOX);
addTypeCB("select-pdf-text-head-tail", _("Select Text from pdf"), TOOL_SELECT_PDF_TEXT_LINEAR);
addTypeCB("select-pdf-text-area", _("Select Area Text from pdf"), TOOL_SELECT_PDF_TEXT_RECT);
this->cbTool = builder.get("cbTool");
gtk_combo_box_set_model(GTK_COMBO_BOX(this->cbTool), GTK_TREE_MODEL(typeModel));
g_signal_connect(cbTool, "changed", G_CALLBACK(&cbSelectCallback), this);
GtkCellRenderer* renderer = gtk_cell_renderer_pixbuf_new();
gtk_cell_layout_pack_start(GTK_CELL_LAYOUT(this->cbTool), renderer, false);
gtk_cell_layout_set_attributes(GTK_CELL_LAYOUT(this->cbTool), renderer, "pixbuf", 0, nullptr);
renderer = gtk_cell_renderer_text_new();
gtk_cell_layout_pack_start(GTK_CELL_LAYOUT(this->cbTool), renderer, true);
gtk_cell_layout_set_attributes(GTK_CELL_LAYOUT(this->cbTool), renderer, "text", 1, nullptr);
this->cbThickness = builder.get("cbThickness");
for (auto const& size: toolSizeIndexMap) {
gtk_combo_box_text_insert_text(GTK_COMBO_BOX_TEXT(cbThickness), size.first,
toolSizeToLabel(size.second).c_str());
}
gtk_combo_box_set_active(GTK_COMBO_BOX(cbThickness), 0);
this->colorButton = builder.get("colorButton");
this->cbDrawingType = builder.get("cbDrawingType");
// DRAWING_TYPE_DONT_CHANGE
gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(this->cbDrawingType), _("Drawing Type - don't change"));
// DRAWING_TYPE_DEFAULT
gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(this->cbDrawingType), _("Normal drawing"));
// DRAWING_TYPE_RULER
gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(this->cbDrawingType), _("Draw Line"));
// DRAWING_TYPE_RECTANGLE
gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(this->cbDrawingType), _("Draw Rectangle"));
// DRAWING_TYPE_ELLIPSE
gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(this->cbDrawingType), _("Draw Ellipse"));
// DRAWING_TYPE_ARROW
gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(this->cbDrawingType), _("Draw Arrow"));
// DRAWING_TYPE_DOUBLE_ARROW
gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(this->cbDrawingType), _("Draw Double Arrow"));
// DRAWING_TYPE_COORDINATE_SYSTEM
gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(this->cbDrawingType), _("Draw Coordinate System"));
// DRAWING_TYPE_STROKE_RECOGNIZER
gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(this->cbDrawingType), _("Shape Recognizer"));
// DRAWING_TYPE_SPLINE
gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(this->cbDrawingType), _("Draw Spline"));
// Values in glade GUI!
this->cbEraserType = builder.get("cbEraserType");
// Possible values are defined in the .glade file
this->cbStrokeType = builder.get("cbStrokeType");
loadSettings();
}
void ButtonConfigGui::loadSettings() {
ButtonConfig* cfg = settings->getButtonConfig(button);
GtkTreeModel* model = gtk_combo_box_get_model(GTK_COMBO_BOX(cbTool));
GtkTreeIter iter;
if (!gtk_tree_model_get_iter_first(model, &iter)) {
return;
}
GValue value = {0};
int i = 0;
gtk_combo_box_set_active(GTK_COMBO_BOX(cbTool), 0);
do {
gtk_tree_model_get_value(model, &iter, 2, &value);
int action = g_value_get_int(&value);
if (action == cfg->action) {
gtk_combo_box_set_active(GTK_COMBO_BOX(cbTool), i);
break;
}
i++;
g_value_unset(&value);
} while (gtk_tree_model_iter_next(model, &iter));
// select thickness in combo box
gtk_combo_box_set_active(GTK_COMBO_BOX(cbThickness), 0);
for (auto const& size: toolSizeIndexMap) {
if (size.second == cfg->size) {
gtk_combo_box_set_active(GTK_COMBO_BOX(cbThickness), size.first);
}
}
GdkRGBA color = Util::rgb_to_GdkRGBA(cfg->color);
gtk_color_chooser_set_rgba(GTK_COLOR_CHOOSER(colorButton), &color);
gtk_combo_box_set_active(GTK_COMBO_BOX(this->cbDrawingType), cfg->drawingType);
if (cfg->eraserMode == ERASER_TYPE_DEFAULT) {
gtk_combo_box_set_active(GTK_COMBO_BOX(cbEraserType), 1);
} else if (cfg->eraserMode == ERASER_TYPE_WHITEOUT) {
gtk_combo_box_set_active(GTK_COMBO_BOX(cbEraserType), 2);
} else if (cfg->eraserMode == ERASER_TYPE_DELETE_STROKE) {
gtk_combo_box_set_active(GTK_COMBO_BOX(cbEraserType), 3);
} else {
gtk_combo_box_set_active(GTK_COMBO_BOX(cbEraserType), 0);
}
gtk_combo_box_set_active(GTK_COMBO_BOX(cbStrokeType), cfg->strokeType);
if (withDevice) {
gtk_combo_box_set_active(GTK_COMBO_BOX(cbDevice), 0);
int i = 1;
for (InputDevice const& dev: this->deviceList) {
if (cfg->device == dev.getName()) {
gtk_combo_box_set_active(GTK_COMBO_BOX(cbDevice), i);
break;
}
++i;
}
gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(cbDisableDrawing), cfg->disableDrawing);
}
}
void ButtonConfigGui::saveSettings() {
GtkTreeIter iter;
gtk_combo_box_get_active_iter(GTK_COMBO_BOX(cbTool), &iter);
GValue value = {0};
GtkTreeModel* model = gtk_combo_box_get_model(GTK_COMBO_BOX(cbTool));
gtk_tree_model_get_value(model, &iter, 2, &value);
auto action = static_cast<ToolType>(g_value_get_int(&value));
ButtonConfig* cfg = settings->getButtonConfig(button);
cfg->action = action;
int thickness = gtk_combo_box_get_active(GTK_COMBO_BOX(cbThickness));
if (toolSizeIndexMap.count(thickness) == 0) {
cfg->size = TOOL_SIZE_NONE;
} else {
cfg->size = toolSizeIndexMap[thickness];
}
GdkRGBA color;
gtk_color_chooser_get_rgba(GTK_COLOR_CHOOSER(colorButton), &color);
cfg->color = Util::GdkRGBA_to_argb(color);
cfg->drawingType = static_cast<DrawingType>(gtk_combo_box_get_active(GTK_COMBO_BOX(this->cbDrawingType)));
int eraserMode = gtk_combo_box_get_active(GTK_COMBO_BOX(this->cbEraserType));
if (eraserMode == 1) {
cfg->eraserMode = ERASER_TYPE_DEFAULT;
} else if (eraserMode == 2) {
cfg->eraserMode = ERASER_TYPE_WHITEOUT;
} else if (eraserMode == 3) {
cfg->eraserMode = ERASER_TYPE_DELETE_STROKE;
} else {
cfg->eraserMode = ERASER_TYPE_NONE;
}
cfg->strokeType = static_cast<StrokeType>(gtk_combo_box_get_active(GTK_COMBO_BOX(this->cbStrokeType)));
if (this->withDevice) {
size_t dev = static_cast<size_t>(gtk_combo_box_get_active(GTK_COMBO_BOX(cbDevice)) - 1);
cfg->device = (dev < 0 || this->deviceList.size() <= dev) ? "" : this->deviceList[dev].getName();
cfg->disableDrawing = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(cbDisableDrawing));
}
settings->customSettingsChanged();
}
void ButtonConfigGui::cbSelectCallback(GtkComboBox*, ButtonConfigGui* gui) { gui->enableDisableTools(); }
void ButtonConfigGui::enableDisableTools() {
GtkTreeIter iter;
gtk_combo_box_get_active_iter(GTK_COMBO_BOX(cbTool), &iter);
GtkTreeModel* model = gtk_combo_box_get_model(GTK_COMBO_BOX(cbTool));
GValue value = {0};
gtk_tree_model_get_value(model, &iter, 2, &value);
auto action = static_cast<ToolType>(g_value_get_int(&value));
switch (action) {
case TOOL_PEN:
gtk_widget_set_visible(cbThickness, true);
gtk_widget_set_visible(colorButton, true);
gtk_widget_set_visible(cbDrawingType, true);
gtk_widget_set_visible(cbEraserType, false);
gtk_widget_set_visible(cbStrokeType, true);
break;
case TOOL_HIGHLIGHTER:
case TOOL_SELECT_PDF_TEXT_LINEAR:
case TOOL_SELECT_PDF_TEXT_RECT:
gtk_widget_set_visible(cbThickness, true);
gtk_widget_set_visible(colorButton, true);
gtk_widget_set_visible(cbDrawingType, true);
gtk_widget_set_visible(cbEraserType, false);
gtk_widget_set_visible(cbStrokeType, false);
break;
case TOOL_ERASER:
gtk_widget_set_visible(cbThickness, true);
gtk_widget_set_visible(colorButton, false);
gtk_widget_set_visible(cbDrawingType, false);
gtk_widget_set_visible(cbEraserType, true);
gtk_widget_set_visible(cbStrokeType, false);
break;
case TOOL_TEXT:
gtk_widget_set_visible(cbThickness, false);
gtk_widget_set_visible(colorButton, true);
gtk_widget_set_visible(cbDrawingType, false);
gtk_widget_set_visible(cbEraserType, false);
gtk_widget_set_visible(cbStrokeType, false);
break;
case TOOL_NONE:
case TOOL_IMAGE:
// case TOOL_DRAW_RECT:
// case TOOL_DRAW_ELLIPSE:
case TOOL_SELECT_RECT:
case TOOL_SELECT_REGION:
case TOOL_SELECT_MULTILAYER_RECT:
case TOOL_SELECT_MULTILAYER_REGION:
case TOOL_VERTICAL_SPACE:
case TOOL_HAND:
gtk_widget_set_visible(cbThickness, false);
gtk_widget_set_visible(colorButton, false);
gtk_widget_set_visible(cbDrawingType, false);
gtk_widget_set_visible(cbEraserType, false);
gtk_widget_set_visible(cbStrokeType, false);
break;
default:
break;
}
}
| 13,790
|
C++
|
.cpp
| 275
| 42.127273
| 120
| 0.650312
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,573
|
PageTemplateDialog.cpp
|
xournalpp_xournalpp/src/core/gui/dialog/PageTemplateDialog.cpp
|
#include "PageTemplateDialog.h"
#include <cstdio> // for sprintf
#include <ctime> // for localtime, strftime, time
#include <fstream> // for ofstream, basic_ostream
#include <memory> // for allocator, unique_ptr
#include <optional> // for optional
#include <string> // for string, operator<<
#include <gdk/gdk.h> // for GdkRGBA
#include <glib-object.h> // for G_CALLBACK, g_signal_c...
#include "control/pagetype/PageTypeHandler.h" // for PageTypeInfo, PageType...
#include "control/settings/Settings.h" // for Settings
#include "gui/Builder.h" // for Builder
#include "gui/dialog/XojOpenDlg.h" // for XojOpenDlg
#include "gui/menus/popoverMenus/PageTypeSelectionPopoverGridOnly.h"
#include "gui/toolbarMenubar/ToolMenuHandler.h"
#include "model/FormatDefinitions.h" // for FormatUnits, XOJ_UNITS
#include "model/PageType.h" // for PageType
#include "util/Color.h" // for GdkRGBA_to_argb, rgb_t...
#include "util/PathUtil.h" // for fromGFilename, readString
#include "util/PopupWindowWrapper.h" // for PopupWindowWrapper
#include "util/XojMsgBox.h" // for XojMsgBox
#include "util/i18n.h" // for _
#include "FormatDialog.h" // for FormatDialog
#include "filesystem.h" // for path
class GladeSearchpath;
constexpr auto UI_FILE = "pageTemplate.glade";
constexpr auto UI_DIALOG_NAME = "templateDialog";
using namespace xoj::popup;
PageTemplateDialog::PageTemplateDialog(GladeSearchpath* gladeSearchPath, Settings* settings, ToolMenuHandler* toolmenu,
PageTypeHandler* types):
gladeSearchPath(gladeSearchPath), settings(settings), toolMenuHandler(toolmenu), types(types) {
model.parse(settings->getPageTemplate());
Builder builder(gladeSearchPath, UI_FILE);
window.reset(GTK_WINDOW(builder.get(UI_DIALOG_NAME)));
// Needs to be initialized after this->window
pageTypeSelectionMenu = std::make_unique<PageTypeSelectionPopoverGridOnly>(types, settings, this);
gtk_menu_button_set_popup(GTK_MENU_BUTTON(builder.get("btBackgroundDropdown")),
pageTypeSelectionMenu->getPopover());
pageSizeLabel = GTK_LABEL(builder.get("lbPageSize"));
backgroundTypeLabel = GTK_LABEL(builder.get("lbBackgroundType"));
backgroundColorChooser = GTK_COLOR_CHOOSER(builder.get("cbBackgroundButton"));
copyLastPageButton = GTK_TOGGLE_BUTTON(builder.get("cbCopyLastPage"));
copyLastPageSizeButton = GTK_TOGGLE_BUTTON(builder.get("cbCopyLastPageSize"));
g_signal_connect_swapped(builder.get("btChangePaperSize"), "clicked",
G_CALLBACK(+[](PageTemplateDialog* self) { self->showPageSizeDialog(); }), this);
g_signal_connect_swapped(builder.get("btLoad"), "clicked",
G_CALLBACK(+[](PageTemplateDialog* self) { self->loadFromFile(); }), this);
g_signal_connect_swapped(builder.get("btSave"), "clicked",
G_CALLBACK(+[](PageTemplateDialog* self) { self->saveToFile(); }), this);
g_signal_connect_swapped(builder.get("btCancel"), "clicked", G_CALLBACK(gtk_window_close), this->getWindow());
g_signal_connect_swapped(builder.get("btOk"), "clicked", G_CALLBACK(+[](PageTemplateDialog* self) {
self->saveToModel();
self->settings->setPageTemplate(self->model.toString());
self->toolMenuHandler->setDefaultNewPageType(self->model.getPageInsertType());
gtk_window_close(self->getWindow());
}),
this);
updateDataFromModel();
}
PageTemplateDialog::~PageTemplateDialog() = default;
void PageTemplateDialog::updateDataFromModel() {
GdkRGBA color = Util::rgb_to_GdkRGBA(model.getBackgroundColor());
gtk_color_chooser_set_rgba(backgroundColorChooser, &color);
updatePageSize();
pageTypeSelectionMenu->setSelected(model.getBackgroundType());
changeCurrentPageBackground(types->getInfoOn(model.getBackgroundType()));
gtk_toggle_button_set_active(copyLastPageButton, model.isCopyLastPageSettings());
gtk_toggle_button_set_active(copyLastPageSizeButton, model.isCopyLastPageSize());
}
void PageTemplateDialog::changeCurrentPageBackground(const PageTypeInfo* info) {
model.setBackgroundType(info->page);
gtk_label_set_text(backgroundTypeLabel, info->name.c_str());
}
void PageTemplateDialog::saveToModel() {
model.setCopyLastPageSettings(gtk_toggle_button_get_active(copyLastPageButton));
model.setCopyLastPageSize(gtk_toggle_button_get_active(copyLastPageSizeButton));
GdkRGBA color;
gtk_color_chooser_get_rgba(backgroundColorChooser, &color);
model.setBackgroundColor(Util::GdkRGBA_to_argb(color));
}
void PageTemplateDialog::saveToFile() {
saveToModel();
GtkWidget* dialog =
gtk_file_chooser_dialog_new(_("Save File"), this->getWindow(), GTK_FILE_CHOOSER_ACTION_SAVE, _("_Cancel"),
GTK_RESPONSE_CANCEL, _("_Save"), GTK_RESPONSE_OK, nullptr);
GtkFileFilter* filterXoj = gtk_file_filter_new();
gtk_file_filter_set_name(filterXoj, _("Xournal++ template"));
gtk_file_filter_add_mime_type(filterXoj, "application/x-xopt");
gtk_file_chooser_add_filter(GTK_FILE_CHOOSER(dialog), filterXoj);
if (!settings->getLastSavePath().empty()) {
gtk_file_chooser_set_current_folder(GTK_FILE_CHOOSER(dialog), Util::toGFile(settings->getLastSavePath()).get(),
nullptr);
}
time_t curtime = time(nullptr);
char stime[128];
strftime(stime, sizeof(stime), "%F-Template-%H-%M.xopt", localtime(&curtime));
std::string saveFilename = stime;
gtk_file_chooser_set_current_name(GTK_FILE_CHOOSER(dialog), saveFilename.c_str());
class FileDlg final {
public:
FileDlg(GtkDialog* dialog, PageTemplateDialog* parent): window(GTK_WINDOW(dialog)), parent(parent) {
this->signalId = g_signal_connect(
dialog, "response", G_CALLBACK((+[](GtkDialog* dialog, int response, gpointer data) {
FileDlg* self = static_cast<FileDlg*>(data);
if (response == GTK_RESPONSE_OK) {
auto file = Util::fromGFile(
xoj::util::GObjectSPtr<GFile>(gtk_file_chooser_get_file(GTK_FILE_CHOOSER(dialog)),
xoj::util::adopt)
.get());
auto saveTemplate = [self, dialog](const fs::path& file) {
// Closing the window causes another "response" signal, which we want to ignore
g_signal_handler_disconnect(dialog, self->signalId);
gtk_window_close(GTK_WINDOW(dialog));
self->parent->settings->setLastSavePath(file.parent_path());
std::ofstream out{file};
out << self->parent->model.toString();
};
XojMsgBox::replaceFileQuestion(GTK_WINDOW(dialog), std::move(file),
std::move(saveTemplate));
} else {
// Closing the window causes another "response" signal, which we want to ignore
g_signal_handler_disconnect(dialog, self->signalId);
gtk_window_close(GTK_WINDOW(dialog)); // Deletes self, don't do anything after this
}
})),
this);
}
~FileDlg() = default;
inline GtkWindow* getWindow() const { return window.get(); }
private:
xoj::util::GtkWindowUPtr window;
PageTemplateDialog* parent;
gulong signalId;
};
auto popup = xoj::popup::PopupWindowWrapper<FileDlg>(GTK_DIALOG(dialog), this);
popup.show(GTK_WINDOW(this->getWindow()));
}
void PageTemplateDialog::loadFromFile() {
xoj::OpenDlg::showOpenTemplateDialog(this->getWindow(), settings, [this](fs::path path) {
auto contents = Util::readString(path);
if (!contents.has_value()) {
return;
}
model.parse(*contents);
updateDataFromModel();
});
}
void PageTemplateDialog::updatePageSize() {
const FormatUnits* formatUnit = &XOJ_UNITS[settings->getSizeUnitIndex()];
char buffer[64];
sprintf(buffer, "%0.2lf", model.getPageWidth() / formatUnit->scale);
std::string pageSize = buffer;
pageSize += formatUnit->name;
pageSize += " x ";
sprintf(buffer, "%0.2lf", model.getPageHeight() / formatUnit->scale);
pageSize += buffer;
pageSize += formatUnit->name;
gtk_label_set_text(pageSizeLabel, pageSize.c_str());
}
void PageTemplateDialog::showPageSizeDialog() {
auto popup = xoj::popup::PopupWindowWrapper<xoj::popup::FormatDialog>(gladeSearchPath, settings,
model.getPageWidth(), model.getPageHeight(),
[dlg = this](double width, double height) {
dlg->model.setPageWidth(width);
dlg->model.setPageHeight(height);
dlg->updatePageSize();
});
popup.show(this->getWindow());
}
/**
* The dialog was confirmed / saved
*/
auto PageTemplateDialog::isSaved() const -> bool { return saved; }
| 10,020
|
C++
|
.cpp
| 173
| 44.849711
| 119
| 0.604286
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,574
|
RenameLayerDialog.cpp
|
xournalpp_xournalpp/src/core/gui/dialog/RenameLayerDialog.cpp
|
#include "RenameLayerDialog.h"
#include <memory> // for allocator, make_unique
#include <string> // for string
#include <glib-object.h> // for G_CALLBACK, g_signal_connect
#include "control/layer/LayerController.h" // for LayerController
#include "gui/Builder.h"
#include "undo/LayerRenameUndoAction.h" // for LayerRenameUndoAction
#include "undo/UndoRedoHandler.h" // for UndoRedoHandler
class GladeSearchpath;
class Layer;
constexpr auto UI_FILE = "renameLayerDialog.glade";
constexpr auto UI_DIALOG_NAME = "renameLayerDialog";
RenameLayerDialog::RenameLayerDialog(GladeSearchpath* gladeSearchPath, UndoRedoHandler* undo, LayerController* lc,
Layer* l):
lc(lc), undo(undo), l(l) {
Builder builder(gladeSearchPath, UI_FILE);
window.reset(GTK_WINDOW(builder.get(UI_DIALOG_NAME)));
layerNameEntry = GTK_ENTRY(builder.get("layerNameEntry"));
gtk_entry_set_text(layerNameEntry, lc->getCurrentLayerName().c_str());
g_signal_connect_swapped(builder.get("btCancel"), "clicked", G_CALLBACK(gtk_window_close), this->window.get());
g_signal_connect_swapped(builder.get("btOk"), "clicked", G_CALLBACK(+[](RenameLayerDialog* self) {
std::string newName = gtk_entry_get_text(self->layerNameEntry);
self->undo->addUndoAction(std::make_unique<LayerRenameUndoAction>(
self->lc, self->l, newName, self->lc->getCurrentLayerName()));
self->lc->setCurrentLayerName(newName);
gtk_window_close(self->window.get());
}),
this);
}
| 1,729
|
C++
|
.cpp
| 29
| 47.931034
| 115
| 0.634911
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,575
|
ExportDialog.cpp
|
xournalpp_xournalpp/src/core/gui/dialog/ExportDialog.cpp
|
#include "ExportDialog.h"
#include <algorithm> // for max
#include <stdexcept> // for invalid_argument
#include <string> // for string, to_string, operator+
#include <vector> // for allocator
#include <glib-object.h> // for G_CALLBACK, g_signal_connect
#include "gui/Builder.h"
#include "util/ElementRange.h" // for parse, PageRangeVector
#include "util/gtk4_helper.h"
class GladeSearchpath;
constexpr auto UI_FILE = "exportSettings.glade";
constexpr auto UI_DIALOG_NAME = "exportDialog";
using namespace xoj::popup;
ExportDialog::ExportDialog(GladeSearchpath* gladeSearchPath, ExportGraphicsFormat format, size_t currentPage,
size_t pageCount, std::function<void(const ExportDialog&)> callbackFun):
currentPage(currentPage), pageCount(pageCount), builder(gladeSearchPath, UI_FILE), callbackFun(callbackFun) {
window.reset(GTK_WINDOW(builder.get(UI_DIALOG_NAME)));
gtk_label_set_text(GTK_LABEL(builder.get("lbAllPagesInfo")), ("1 - " + std::to_string(pageCount)).c_str());
gtk_label_set_text(GTK_LABEL(builder.get("lbCurrentPage")), std::to_string(currentPage).c_str());
#if GTK_MAJOR_VERSION == 3
// Widgets are visible by default in gtk4
gtk_widget_show_all(builder.get("dialog-main-box"));
#endif
auto removeQualitySetting = [&builder = this->builder]() {
gtk_widget_hide(builder.get("lbQuality"));
gtk_widget_hide(builder.get("boxQuality"));
gtk_widget_hide(builder.get("cbQuality"));
};
if (format == EXPORT_GRAPHICS_PDF) {
removeQualitySetting();
} else if (format == EXPORT_GRAPHICS_PNG) {
gtk_widget_hide(builder.get("cbProgressiveMode"));
} else { // (format == EXPORT_GRAPHICS_SVG)
removeQualitySetting();
gtk_widget_hide(builder.get("cbProgressiveMode"));
}
// rdRangePages toggled signal handler
//
// Sets and unsets the sensitivity of the text form, OK button and
// displays an error when the text form is selected and contains
// invalid user data. The error goes away when the text form is de-selected.
auto toggledHandler = G_CALLBACK(+[](GtkCheckButton* button, ExportDialog* self) {
auto active = gtk_check_button_get_active(button);
auto btOk = self->builder.get("btOk");
auto txtPages = self->builder.get("txtPages");
gtk_widget_set_sensitive(txtPages, active);
if (active) {
const std::string text_form(gtk_editable_get_chars(GTK_EDITABLE(txtPages), 0, -1));
try {
ElementRange::parse(text_form, self->pageCount);
gtk_widget_remove_css_class(txtPages, "error");
gtk_widget_set_sensitive(btOk, true);
} catch (const std::invalid_argument&) {
gtk_widget_add_css_class(txtPages, "error");
gtk_widget_set_sensitive(btOk, false);
}
} else {
gtk_widget_remove_css_class(txtPages, "error");
gtk_widget_set_sensitive(btOk, true);
}
});
// txtPages changed signal handler
//
// Displays an error when the user inputs invalid page ranges in the text form,
// and sets the sensitivity of the OK button to FALSE. These actions are
// reversed when the text form contains a valid page range.
auto changedHandler = G_CALLBACK(+[](GtkEditable* txtPages, ExportDialog* self) {
const std::string text_form(gtk_editable_get_chars(txtPages, 0, -1));
auto btOk = self->builder.get("btOk");
try {
ElementRange::parse(text_form, self->pageCount);
gtk_widget_remove_css_class(GTK_WIDGET(txtPages), "error");
gtk_widget_set_sensitive(btOk, true);
} catch (const std::invalid_argument& e) {
gtk_widget_add_css_class(GTK_WIDGET(txtPages), "error");
gtk_widget_set_sensitive(btOk, false);
}
});
g_signal_connect(builder.get("rdRangePages"), "toggled", toggledHandler, this);
g_signal_connect(builder.get("cbQuality"), "changed", G_CALLBACK(ExportDialog::selectQualityCriterion), this);
g_signal_connect(builder.get("txtPages"), "changed", changedHandler, this);
g_signal_connect_swapped(builder.get("btCancel"), "clicked", G_CALLBACK(gtk_window_close), this->window.get());
g_signal_connect_swapped(builder.get("btOk"), "clicked", G_CALLBACK(ExportDialog::onSuccessCallback), this);
/**
* By calling this->callbackFun() here, we make sure that `control->unblock()` is run even if the user clicks on
* the close-window button.
*
* The callback returns `false` so that the PopupWindowManager callback deleting `this` gets called as well.
*/
#if GTK_MAJOR_VERSION == 3
g_signal_connect_swapped(window.get(), "delete-event", G_CALLBACK(+[](ExportDialog* self) {
self->callbackFun(*self);
return false;
}),
this);
#else
g_signal_connect_swapped(window.get(), "close-request", G_CALLBACK(+[](ExportDialog* self) {
self->callbackFun(*self);
return false;
}),
this);
#endif
}
ExportDialog::~ExportDialog() = default;
void ExportDialog::selectQualityCriterion(GtkComboBox* comboBox, ExportDialog* self) {
int activeCriterion = gtk_combo_box_get_active(comboBox);
switch (activeCriterion) {
case EXPORT_QUALITY_DPI:
gtk_label_set_text(GTK_LABEL(self->builder.get("lbQualityUnit")), "dpi");
gtk_spin_button_set_adjustment(GTK_SPIN_BUTTON(self->builder.get("sbQualityValue")),
GTK_ADJUSTMENT(self->builder.get<GObject>("adjustmentDpi")));
break;
case EXPORT_QUALITY_WIDTH:
case EXPORT_QUALITY_HEIGHT:
gtk_label_set_text(GTK_LABEL(self->builder.get("lbQualityUnit")), "px");
gtk_spin_button_set_adjustment(GTK_SPIN_BUTTON(self->builder.get("sbQualityValue")),
GTK_ADJUSTMENT(self->builder.get<GObject>("adjustmentHeightWidth")));
break;
}
}
void ExportDialog::onSuccessCallback(ExportDialog* self) {
self->confirmed = true;
self->progressiveMode = gtk_check_button_get_active(GTK_CHECK_BUTTON(self->builder.get("cbProgressiveMode")));
self->backgroundType = static_cast<ExportBackgroundType>(
gtk_combo_box_get_active(GTK_COMBO_BOX(self->builder.get("cbBackgroundType"))));
self->pageRanges = [self]() {
GtkWidget* rdRangeCurrent = self->builder.get("rdRangeCurrent");
GtkWidget* rdRangePages = self->builder.get("rdRangePages");
if (gtk_check_button_get_active(GTK_CHECK_BUTTON(rdRangePages))) {
return ElementRange::parse(gtk_entry_get_text(GTK_ENTRY(self->builder.get("txtPages"))), self->pageCount);
}
if (gtk_check_button_get_active(GTK_CHECK_BUTTON(rdRangeCurrent))) {
PageRangeVector range;
range.emplace_back(self->currentPage - 1, self->currentPage - 1);
return range;
}
PageRangeVector range;
range.emplace_back(0, self->pageCount - 1);
return range;
}();
self->qualityParameter = RasterImageQualityParameter(
static_cast<ExportQualityCriterion>(
gtk_combo_box_get_active(GTK_COMBO_BOX(self->builder.get("cbQuality")))),
gtk_spin_button_get_value_as_int(GTK_SPIN_BUTTON(self->builder.get("sbQualityValue"))));
gtk_window_close(self->window.get());
}
auto ExportDialog::getPngQualityParameter() const -> RasterImageQualityParameter { return qualityParameter; }
auto ExportDialog::isConfirmed() const -> bool { return this->confirmed; }
auto ExportDialog::progressiveModeSelected() const -> bool { return this->progressiveMode; }
auto ExportDialog::getBackgroundType() const -> ExportBackgroundType { return backgroundType; }
auto ExportDialog::getRange() const -> const PageRangeVector& { return pageRanges; }
| 8,143
|
C++
|
.cpp
| 151
| 44.794702
| 118
| 0.651519
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,576
|
LatexDialog.cpp
|
xournalpp_xournalpp/src/core/gui/dialog/LatexDialog.cpp
|
/*
* Xournal++
*
* Latex implementation
*
* @author W Brenna
* http://wbrenna.ca
*
* https://github.com/xournalpp/xournalpp
*
* @license GNU GPLv2 or later
*/
#include "LatexDialog.h"
#include <algorithm> // for max, min
#include <cmath>
#include <sstream> // for operator<<, basic_ostream
#include <utility> // for move
#include <glib.h> // for g_free, gpointer, guint
#include <poppler-document.h> // for poppler_document_get_n_p...
#include <poppler-page.h> // for poppler_page_get_size
#ifdef USE_GTK_SOURCEVIEW
#include <gtksourceview/gtksource.h> // for GTK_SOURCE_VIEW, gtk_sou...
#endif
#include "control/LatexController.h"
#include "control/settings/LatexSettings.h" // for LatexSettings
#include "gui/Builder.h"
#include "model/Font.h" // for XojFont
#include "model/TexImage.h"
#include "util/Range.h"
#include "util/StringUtils.h" // for replace_pair, StringUtils
#include "util/gtk4_helper.h"
#include "util/raii/CStringWrapper.h"
class GladeSearchpath;
// Default background color of the preview.
const Color DEFAULT_PREVIEW_BACKGROUND = Colors::white;
constexpr auto UI_FILE_NAME = "texdialog.glade";
constexpr auto UI_DIALOG_ID = "texDialog";
constexpr auto TEX_BOX_WIDGET_NAME = "texBox";
constexpr auto PREVIEW_WIDGET_ID = "texImage";
LatexDialog::LatexDialog(GladeSearchpath* gladeSearchPath, std::unique_ptr<LatexController> ctrl):
texCtrl(std::move(ctrl)),
cssProvider(gtk_css_provider_new(), xoj::util::adopt),
previewBackgroundColor{DEFAULT_PREVIEW_BACKGROUND} {
texCtrl->dlg = this;
Builder builder(gladeSearchPath, UI_FILE_NAME);
window.reset(GTK_WINDOW(builder.get(UI_DIALOG_ID)));
previewDrawingArea = GTK_DRAWING_AREA(builder.get(PREVIEW_WIDGET_ID));
btOk = GTK_BUTTON(builder.get("btOk"));
texErrorLabel = GTK_LABEL(builder.get("texErrorLabel"));
compilationOutputTextBuffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(builder.get("texCommandOutputText")));
#ifdef USE_GTK_SOURCEVIEW
this->texBox = gtk_source_view_new();
#else
this->texBox = gtk_text_view_new();
#endif
gtk_widget_set_name(this->texBox, TEX_BOX_WIDGET_NAME);
gtk_text_view_set_editable(GTK_TEXT_VIEW(this->texBox), true);
this->textBuffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(this->texBox));
const auto& settings = texCtrl->settings;
if (texCtrl->initialTex.empty()) {
gtk_text_buffer_set_text(this->textBuffer, settings.defaultText.c_str(), -1);
// Preselect the default
GtkTextIter start, end;
gtk_text_buffer_get_bounds(this->textBuffer, &start, &end);
gtk_text_buffer_select_range(this->textBuffer, &start, &end);
} else {
gtk_text_buffer_set_text(this->textBuffer, texCtrl->initialTex.c_str(), -1);
}
#if GTK_MAJOR_VERSION == 3
// Widgets are visible by default in gtk4
gtk_widget_show_all(GTK_WIDGET(texBox));
#endif
gtk_scrolled_window_set_child(GTK_SCROLLED_WINDOW(builder.get("texBoxContainer")), this->texBox);
#ifdef USE_GTK_SOURCEVIEW
// We own neither the languageManager, the styleSchemeManager, nor the sourceLanguage.
// Do not attempt to free them.
GtkSourceStyleSchemeManager* styleSchemeManager = gtk_source_style_scheme_manager_get_default();
GtkSourceLanguageManager* lm = gtk_source_language_manager_get_default();
// Select the TeX highlighting scheme
GtkSourceLanguage* lang = gtk_source_language_manager_guess_language(lm, "file.tex", nullptr);
std::string styleSchemeId = settings.sourceViewThemeId;
GtkSourceStyleScheme* styleScheme =
gtk_source_style_scheme_manager_get_scheme(styleSchemeManager, styleSchemeId.c_str());
if (settings.sourceViewSyntaxHighlight) {
gtk_source_buffer_set_language(GTK_SOURCE_BUFFER(this->textBuffer), lang);
}
gtk_source_view_set_auto_indent(GTK_SOURCE_VIEW(this->texBox), settings.sourceViewAutoIndent);
gtk_source_view_set_indent_on_tab(GTK_SOURCE_VIEW(this->texBox), settings.sourceViewAutoIndent);
gtk_source_view_set_show_line_numbers(GTK_SOURCE_VIEW(this->texBox), settings.sourceViewShowLineNumbers);
if (styleScheme) {
gtk_source_buffer_set_style_scheme(GTK_SOURCE_BUFFER(this->textBuffer), styleScheme);
}
#endif
// Enable/disable word-wrap.
GtkWrapMode texBoxWrapMode = GTK_WRAP_NONE;
if (settings.editorWordWrap) {
texBoxWrapMode = GTK_WRAP_WORD_CHAR;
}
gtk_text_view_set_wrap_mode(GTK_TEXT_VIEW(this->texBox), texBoxWrapMode);
gtk_drawing_area_set_draw_func(this->previewDrawingArea, GtkDrawingAreaDrawFunc(previewDrawFunc), this, nullptr);
std::stringstream texBoxCssBuilder;
if (settings.useCustomEditorFont) {
std::string fontName = settings.editorFont.getName();
// Escape "'" and "\" characters in the fontName
StringUtils::replaceAllChars(fontName, {replace_pair('\\', "\\\\")});
StringUtils::replaceAllChars(fontName, {replace_pair('\'', "\\'")});
texBoxCssBuilder << "#" << TEX_BOX_WIDGET_NAME << " {";
texBoxCssBuilder << " font-size: " << settings.editorFont.getSize() << "pt;";
texBoxCssBuilder << " font-family: '" << fontName << "';";
texBoxCssBuilder << " } ";
gtk_css_provider_load_from_data(this->cssProvider.get(), texBoxCssBuilder.str().c_str(), -1, nullptr);
// Apply the CSS to both the texBox and the drawing area.
gtk_style_context_add_provider(gtk_widget_get_style_context(GTK_WIDGET(this->previewDrawingArea)),
GTK_STYLE_PROVIDER(this->cssProvider.get()),
GTK_STYLE_PROVIDER_PRIORITY_APPLICATION);
gtk_style_context_add_provider(gtk_widget_get_style_context(GTK_WIDGET(this->texBox)),
GTK_STYLE_PROVIDER(this->cssProvider.get()),
GTK_STYLE_PROVIDER_PRIORITY_APPLICATION);
}
g_signal_connect(builder.get("btCancel"), "clicked", G_CALLBACK(+[](GtkButton*, gpointer d) {
auto* self = static_cast<LatexDialog*>(d);
self->texCtrl->cancelEditing();
gtk_window_close(self->window.get());
}),
this);
g_signal_connect(builder.get("btOk"), "clicked", G_CALLBACK(+[](GtkButton*, gpointer d) {
auto* self = static_cast<LatexDialog*>(d);
self->texCtrl->insertTexImage();
gtk_window_close(self->window.get());
}),
this);
if (texCtrl->temporaryRender) {
// Use preexisting pdf
this->setTempRender(texCtrl->temporaryRender->getPdf());
}
/*
* Connect handleTexChanged() to the text buffer containing the latex code, to trigger rebuilds upon code changes.
*/
g_signal_connect(this->getTextBuffer(), "changed", G_CALLBACK(+[](GtkTextBuffer*, gpointer ctrl) {
LatexController::handleTexChanged(static_cast<LatexController*>(ctrl));
}),
texCtrl.get());
g_signal_connect(this->getWindow(), "delete-event", G_CALLBACK(+[](GtkWidget*, GdkEvent*, gpointer d) -> gboolean {
auto self = static_cast<LatexDialog*>(d);
/**
* dlg->getTextBuffer() may survive the dialog. When copying all of its content, the
* clipboard owns a ref to the GtkTextBuffer. We must disconnect the signal to avoid
* dereferencing `self` after its destruction
*/
g_signal_handlers_disconnect_by_data(self->getTextBuffer(), self->texCtrl.get());
return false; // Let the callback from PopupWindowWrapper delete the dialog
}),
this);
g_signal_connect(this->getWindow(), "show", G_CALLBACK(+[](GtkWidget*, gpointer d) {
auto* texCtrl = static_cast<LatexController*>(d);
if (!texCtrl->temporaryRender) {
// Trigger an asynchronous compilation if we are not using a preexisting TexImage
// Keep this after popup.show() so that if an error message is to be displayed (e.g.
// missing Tex executable), it'll appear on top of the LatexDialog.
LatexController::handleTexChanged(texCtrl);
}
}),
texCtrl.get());
}
LatexDialog::~LatexDialog() = default;
void LatexDialog::setCompilationStatus(bool isTexValid, bool isCompilationDone, const std::string& compilationOutput) {
gtk_widget_set_sensitive(GTK_WIDGET(btOk), isTexValid && isCompilationDone);
// Show error warning only if LaTeX is invalid.
gtk_widget_set_opacity(GTK_WIDGET(texErrorLabel), isTexValid ? 0 : 1);
// Update the output pane.
gtk_text_buffer_set_text(compilationOutputTextBuffer, compilationOutput.c_str(), -1);
}
void LatexDialog::setTempRender(PopplerDocument* pdf) {
if (poppler_document_get_n_pages(pdf) < 1) {
return;
}
this->previewPdfPage.reset(poppler_document_get_page(pdf, 0), xoj::util::adopt);
this->previewMask.reset();
// Queue rendering the changed preview.
gtk_widget_queue_draw(GTK_WIDGET(this->previewDrawingArea));
}
void LatexDialog::setPreviewBackgroundColor(Color newColor) { this->previewBackgroundColor = newColor; }
auto LatexDialog::getTextBuffer() -> GtkTextBuffer* { return this->textBuffer; }
auto LatexDialog::getBufferContents() -> std::string {
GtkTextIter start, end;
gtk_text_buffer_get_bounds(this->textBuffer, &start, &end);
auto content =
xoj::util::OwnedCString::assumeOwnership(gtk_text_buffer_get_text(this->textBuffer, &start, &end, false));
return content.get();
}
void LatexDialog::previewDrawFunc(GtkDrawingArea*, cairo_t* cr, int width, int height, LatexDialog* self) {
// If we have nothing to render, do nothing!
if (!self->previewPdfPage) {
return;
}
Range pageRange(0, 0, 0, 0);
poppler_page_get_size(self->previewPdfPage.get(), &pageRange.maxX, &pageRange.maxY);
const double zoom =
std::min(static_cast<double>(width) / pageRange.maxX, static_cast<double>(height) / pageRange.maxY);
if (!self->previewMask.isInitialized() || self->previewMask.getZoom() < zoom) {
// Need to rerender the preview
self->previewMask = xoj::view::Mask(gtk_widget_get_scale_factor(GTK_WIDGET(self->previewDrawingArea)),
pageRange, zoom, CAIRO_CONTENT_COLOR_ALPHA);
poppler_page_render(self->previewPdfPage.get(), self->previewMask.get());
}
Util::cairo_set_source_rgbi(cr, self->previewBackgroundColor);
cairo_paint(cr);
// Center the rendering
const double extraHorizontalSpace = std::max(0.0, width - pageRange.maxX * zoom);
const double extraVerticalSpace = std::max(0.0, height - pageRange.maxY * zoom);
cairo_translate(cr, 0.5 * extraHorizontalSpace, 0.5 * extraVerticalSpace);
cairo_scale(cr, zoom, zoom);
self->previewMask.paintTo(cr);
}
| 11,374
|
C++
|
.cpp
| 214
| 44.350467
| 119
| 0.655079
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,577
|
ToolbarManageDialog.cpp
|
xournalpp_xournalpp/src/core/gui/dialog/ToolbarManageDialog.cpp
|
#include "ToolbarManageDialog.h"
#include <string> // for allocator, string
#include <vector> // for vector
#include <glib-object.h> // for g_signal_connect
#include <pango/pango.h> // for PANGO_WEIGHT_NORMAL
#include "gui/Builder.h"
#include "gui/toolbarMenubar/model/ToolbarData.h" // for ToolbarData
#include "gui/toolbarMenubar/model/ToolbarModel.h" // for ToolbarModel
#include "util/Assert.h" // for xoj_assert
#include "util/i18n.h" // for _
class GladeSearchpath;
constexpr auto UI_FILE = "toolbarManageDialog.glade";
constexpr auto UI_DIALOG_NAME = "manageToolbarsDialog";
enum { COLUMN_STRING, COLUMN_BOLD, COLUMN_POINTER, COLUMN_EDITABLE, N_COLUMNS };
static xoj::util::GObjectSPtr<GtkListStore> createModel(ToolbarModel* tb) {
xoj_assert(tb);
GtkTreeIter iter;
GtkListStore* model = gtk_list_store_new(N_COLUMNS, G_TYPE_STRING, G_TYPE_INT, G_TYPE_POINTER, G_TYPE_BOOLEAN);
gtk_list_store_append(model, &iter);
gtk_list_store_set(model, &iter, COLUMN_STRING, _("Predefined"), COLUMN_BOLD, PANGO_WEIGHT_BOLD, COLUMN_POINTER,
nullptr, COLUMN_EDITABLE, false, -1);
for (const auto& data: tb->getToolbars()) {
if (data->isPredefined()) {
gtk_list_store_append(model, &iter);
gtk_list_store_set(model, &iter, COLUMN_STRING, data->getName().c_str(), COLUMN_BOLD, PANGO_WEIGHT_NORMAL,
COLUMN_POINTER, data.get(), COLUMN_EDITABLE, false, -1);
}
}
gtk_list_store_append(model, &iter);
gtk_list_store_set(model, &iter, COLUMN_STRING, _("Customized"), COLUMN_BOLD, PANGO_WEIGHT_BOLD, COLUMN_POINTER,
nullptr, COLUMN_EDITABLE, false, -1);
for (const auto& data: tb->getToolbars()) {
if (!data->isPredefined()) {
gtk_list_store_append(model, &iter);
gtk_list_store_set(model, &iter, COLUMN_STRING, data->getName().c_str(), COLUMN_BOLD, PANGO_WEIGHT_NORMAL,
COLUMN_POINTER, data.get(), COLUMN_EDITABLE, true, -1);
}
}
return xoj::util::GObjectSPtr<GtkListStore>(model, xoj::util::adopt);
}
ToolbarManageDialog::ToolbarManageDialog(GladeSearchpath* gladeSearchPath, ToolbarModel* tbModel,
std::function<void()> callback):
tbModel(tbModel), model(createModel(tbModel)), callback(callback) {
Builder builder(gladeSearchPath, UI_FILE);
window.reset(GTK_WINDOW(builder.get(UI_DIALOG_NAME)));
tree = GTK_TREE_VIEW(builder.get("toolbarList"));
copyButton = builder.get("btCopy");
deleteButton = builder.get("btDelete");
gtk_tree_view_set_model(tree, GTK_TREE_MODEL(this->model.get()));
GtkCellRenderer* renderer = gtk_cell_renderer_text_new();
GtkTreeViewColumn* column =
gtk_tree_view_column_new_with_attributes(_("Toolbars"), renderer, "text", COLUMN_STRING, "weight",
COLUMN_BOLD, "editable", COLUMN_EDITABLE, nullptr);
gtk_tree_view_append_column(tree, column);
GtkTreeSelection* select = gtk_tree_view_get_selection(tree);
gtk_tree_selection_set_mode(select, GTK_SELECTION_SINGLE);
g_signal_connect(select, "changed", G_CALLBACK(treeSelectionChangedCallback), this);
g_signal_connect(renderer, "edited", G_CALLBACK(treeCellEditedCallback), this);
g_signal_connect(builder.get("btNew"), "clicked", G_CALLBACK(buttonNewCallback), this);
g_signal_connect(deleteButton, "clicked", G_CALLBACK(buttonDeleteCallback), this);
g_signal_connect(copyButton, "clicked", G_CALLBACK(buttonCopyCallback), this);
g_signal_connect_swapped(builder.get("btClose"), "clicked", G_CALLBACK(gtk_window_close), this->window.get());
}
ToolbarManageDialog::~ToolbarManageDialog() { this->callback(); }
void ToolbarManageDialog::buttonNewCallback(GtkButton* button, ToolbarManageDialog* dlg) {
auto data = std::make_unique<ToolbarData>(false);
data->setName(_("New"));
data->setId("custom");
dlg->tbModel->initCopyNameId(data.get());
dlg->addToolbarData(std::move(data));
}
void ToolbarManageDialog::buttonDeleteCallback(GtkButton* button, ToolbarManageDialog* dlg) {
ToolbarData* selected = dlg->getSelectedEntry();
if (selected == nullptr) {
return;
}
GtkTreeModel* model = GTK_TREE_MODEL(dlg->model.get());
GtkTreeIter iter;
if (gtk_tree_model_get_iter_first(model, &iter)) {
do {
ToolbarData* data = nullptr;
gtk_tree_model_get(model, &iter, COLUMN_POINTER, &data, -1);
if (data == selected) {
gtk_list_store_remove(dlg->model.get(), &iter);
break;
}
} while (gtk_tree_model_iter_next(model, &iter));
}
dlg->tbModel->remove(selected);
dlg->updateSelectionData();
}
void ToolbarManageDialog::buttonCopyCallback(GtkButton* button, ToolbarManageDialog* dlg) {
ToolbarData* selected = dlg->getSelectedEntry();
if (selected == nullptr) {
return;
}
auto data = std::make_unique<ToolbarData>(*selected);
dlg->tbModel->initCopyNameId(data.get());
dlg->addToolbarData(std::move(data));
}
void ToolbarManageDialog::addToolbarData(std::unique_ptr<ToolbarData> tbd) {
auto* data = this->tbModel->add(std::move(tbd));
GtkTreeIter iter;
gtk_list_store_append(this->model.get(), &iter);
gtk_list_store_set(this->model.get(), &iter, COLUMN_STRING, data->getName().c_str(), COLUMN_BOLD,
PANGO_WEIGHT_NORMAL, COLUMN_POINTER, data, COLUMN_EDITABLE, true, -1);
GtkTreePath* path = gtk_tree_model_get_path(GTK_TREE_MODEL(this->model.get()), &iter);
GtkTreeViewColumn* column = gtk_tree_view_get_column(tree, 0);
gtk_tree_view_set_cursor(tree, path, column, true);
}
void ToolbarManageDialog::treeCellEditedCallback(GtkCellRendererText* renderer, gchar* pathString, gchar* newText,
ToolbarManageDialog* dlg) {
GtkTreeIter iter;
ToolbarData* data = nullptr;
gtk_tree_model_get_iter_from_string(GTK_TREE_MODEL(dlg->model.get()), &iter, pathString);
gtk_tree_model_get(GTK_TREE_MODEL(dlg->model.get()), &iter, COLUMN_POINTER, &data, -1);
if (data) {
gtk_list_store_set(dlg->model.get(), &iter, COLUMN_STRING, newText, -1);
data->setName(newText);
}
}
void ToolbarManageDialog::entrySelected(ToolbarData* data) {
if (data == nullptr) {
gtk_widget_set_sensitive(copyButton, false);
gtk_widget_set_sensitive(deleteButton, false);
} else {
gtk_widget_set_sensitive(copyButton, true);
gtk_widget_set_sensitive(deleteButton, !data->isPredefined());
}
}
auto ToolbarManageDialog::getSelectedEntry() -> ToolbarData* {
GtkTreeIter iter;
GtkTreeModel* model = nullptr;
ToolbarData* data = nullptr;
GtkTreeSelection* selection = gtk_tree_view_get_selection(tree);
if (selection == nullptr) {
return nullptr;
}
if (gtk_tree_selection_get_selected(selection, &model, &iter)) {
gtk_tree_model_get(model, &iter, COLUMN_POINTER, &data, -1);
return data;
}
return nullptr;
}
void ToolbarManageDialog::updateSelectionData() { entrySelected(getSelectedEntry()); }
void ToolbarManageDialog::treeSelectionChangedCallback(GtkTreeSelection* selection, ToolbarManageDialog* dlg) {
dlg->updateSelectionData();
}
| 7,494
|
C++
|
.cpp
| 148
| 43.574324
| 118
| 0.669084
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,578
|
LatexSettingsPanel.cpp
|
xournalpp_xournalpp/src/core/gui/dialog/LatexSettingsPanel.cpp
|
#include "LatexSettingsPanel.h"
#include <fstream> // for ifstream, basic_istream
#include <iterator> // for istreambuf_iterator, ope...
#include <string> // for allocator, string
#include <variant> // for get_if
#include <gio/gio.h> // for GSubprocess, g_subproces...
#include <glib-object.h> // for g_object_unref, g_object...
#include <glib.h> // for g_error_free, GError
#ifdef USE_GTK_SOURCEVIEW
#include <gtksourceview/gtksource.h> // for gtk_source_style_scheme_...
#endif
#include "control/latex/LatexGenerator.h" // for LatexGenerator::GenError
#include "control/settings/LatexSettings.h" // for LatexSettings
#include "gui/Builder.h"
#include "model/Font.h" // for XojFont
#include "util/Color.h" // for Color
#include "util/PathUtil.h" // for fromGFilename, getTmpDir...
#include "util/PlaceholderString.h" // for PlaceholderString
#include "util/XojMsgBox.h"
#include "util/gtk4_helper.h"
#include "util/i18n.h" // for FS, _F, _
#include "filesystem.h" // for path, is_regular_file
class GladeSearchpath;
constexpr auto UI_FILE = "latexSettings.glade";
constexpr auto UI_PANEL_NAME = "latexSettingsPanel";
LatexSettingsPanel::LatexSettingsPanel(GladeSearchpath* gladeSearchPath):
builder(gladeSearchPath, UI_FILE),
panel(GTK_SCROLLED_WINDOW(builder.get(UI_PANEL_NAME))),
cbAutoDepCheck(GTK_CHECK_BUTTON(builder.get("latexSettingsRunCheck"))),
// Todo(gtk4): replace this GtkFileChooserButton (by what?)
globalTemplateChooser(GTK_FILE_CHOOSER(builder.get("latexSettingsTemplateFile"))),
cbUseSystemFont(GTK_CHECK_BUTTON(builder.get("cbUseSystemFont"))) {
g_signal_connect_swapped(builder.get("latexSettingsTestBtn"), "clicked",
G_CALLBACK(+[](LatexSettingsPanel* self) { self->checkDeps(); }), this);
g_signal_connect_swapped(this->cbUseSystemFont, "toggled",
G_CALLBACK(+[](LatexSettingsPanel* self) { self->updateWidgetSensitivity(); }), this);
#ifdef USE_GTK_SOURCEVIEW
GtkBox* themeSelectionBox = GTK_BOX(builder.get("bxThemeSelectionContainer"));
this->sourceViewThemeSelector = gtk_source_style_scheme_chooser_button_new();
gtk_box_append(themeSelectionBox, sourceViewThemeSelector);
gtk_label_set_text(GTK_LABEL(builder.get("lbSourceviewSettingsDescription")), _("LaTeX editor theme:"));
#if GTK_MAJOR_VERSION == 3
// Widgets are visible by default in gtk4
gtk_widget_show(sourceViewThemeSelector);
#endif
#else
this->sourceViewThemeSelector = nullptr;
gtk_label_set_text(GTK_LABEL(builder.get("lbSourceviewSettingsDescription")),
_("GtkSourceView was disabled when building Xournal++! "
"Some options will not be available."));
#endif
}
void LatexSettingsPanel::load(const LatexSettings& settings) {
gtk_check_button_set_active(this->cbAutoDepCheck, settings.autoCheckDependencies);
gtk_entry_set_text(GTK_ENTRY(builder.get("latexDefaultEntry")), settings.defaultText.c_str());
if (!settings.globalTemplatePath.empty()) {
gtk_file_chooser_set_filename(this->globalTemplateChooser,
Util::toGFilename(settings.globalTemplatePath).c_str());
}
gtk_entry_set_text(GTK_ENTRY(builder.get("latexSettingsGenCmd")), settings.genCmd.c_str());
std::string themeId = settings.sourceViewThemeId;
#ifdef USE_GTK_SOURCEVIEW
GtkSourceStyleSchemeManager* themeManager = gtk_source_style_scheme_manager_get_default();
GtkSourceStyleScheme* theme = gtk_source_style_scheme_manager_get_scheme(themeManager, themeId.c_str());
if (theme) {
gtk_source_style_scheme_chooser_set_style_scheme(GTK_SOURCE_STYLE_SCHEME_CHOOSER(this->sourceViewThemeSelector),
theme);
}
#endif
gtk_check_button_set_active(GTK_CHECK_BUTTON(builder.get("cbShowLineNumbers")), settings.sourceViewShowLineNumbers);
gtk_check_button_set_active(GTK_CHECK_BUTTON(builder.get("cbAutoIndent")), settings.sourceViewAutoIndent);
gtk_check_button_set_active(GTK_CHECK_BUTTON(builder.get("cbSyntaxHighlight")), settings.sourceViewSyntaxHighlight);
// Editor font
std::string editorFontDescription{settings.editorFont.asString()};
gtk_font_chooser_set_font(GTK_FONT_CHOOSER(builder.get("selBtnEditorFont")), editorFontDescription.c_str());
// Should we use the custom editor font?
gtk_check_button_set_active(this->cbUseSystemFont, !settings.useCustomEditorFont);
// Editor word wrap.
gtk_check_button_set_active(GTK_CHECK_BUTTON(builder.get("cbWordWrap")), settings.editorWordWrap);
this->updateWidgetSensitivity();
}
void LatexSettingsPanel::save(LatexSettings& settings) {
settings.autoCheckDependencies = gtk_check_button_get_active(this->cbAutoDepCheck);
settings.defaultText = gtk_entry_get_text(GTK_ENTRY(builder.get("latexDefaultEntry")));
settings.globalTemplatePath = Util::fromGFilename(gtk_file_chooser_get_filename(this->globalTemplateChooser));
settings.genCmd = gtk_entry_get_text(GTK_ENTRY(builder.get("latexSettingsGenCmd")));
#ifdef USE_GTK_SOURCEVIEW
GtkSourceStyleScheme* theme = gtk_source_style_scheme_chooser_get_style_scheme(
GTK_SOURCE_STYLE_SCHEME_CHOOSER(this->sourceViewThemeSelector));
settings.sourceViewThemeId = gtk_source_style_scheme_get_id(theme);
#endif
settings.sourceViewShowLineNumbers =
gtk_check_button_get_active(GTK_CHECK_BUTTON(builder.get("cbShowLineNumbers")));
settings.sourceViewAutoIndent = gtk_check_button_get_active(GTK_CHECK_BUTTON(builder.get("cbAutoIndent")));
settings.sourceViewSyntaxHighlight =
gtk_check_button_get_active(GTK_CHECK_BUTTON(builder.get("cbSyntaxHighlight")));
GtkFontChooser* fontSelector = GTK_FONT_CHOOSER(builder.get("selBtnEditorFont"));
std::string fontDescription{gtk_font_chooser_get_font(fontSelector)};
settings.editorFont = fontDescription;
settings.useCustomEditorFont = !gtk_check_button_get_active(this->cbUseSystemFont);
settings.editorWordWrap = gtk_check_button_get_active(GTK_CHECK_BUTTON(builder.get("cbWordWrap")));
}
void LatexSettingsPanel::checkDeps() {
LatexSettings settings;
this->save(settings);
std::string msg;
bool fail = false;
if (fs::is_regular_file(settings.globalTemplatePath)) {
// Assume the file is encoded as UTF-8 (open in binary mode to avoid surprises)
std::ifstream is(settings.globalTemplatePath, std::ios_base::binary);
if (!is.is_open()) {
msg = FS(_F("Unable to open global template file at {1}. Does it exist?") %
settings.globalTemplatePath.u8string().c_str());
fail = true;
} else {
std::string templ(std::istreambuf_iterator<char>(is), {});
std::string sample = LatexGenerator::templateSub(settings.defaultText, templ, Colors::black);
auto const& tmpDir = Util::getTmpDirSubfolder("tex");
auto result = LatexGenerator(settings).asyncRun(tmpDir, sample);
if (auto* proc = std::get_if<GSubprocess*>(&result)) {
GError* err = nullptr;
if (g_subprocess_wait_check(*proc, nullptr, &err)) {
msg = _("Sample LaTeX file generated successfully.");
} else {
msg = FS(_F("Error: {1}. Please check the contents of {2}") % err->message %
tmpDir.u8string().c_str());
g_error_free(err);
fail = true;
}
g_object_unref(*proc);
} else if (auto* err = std::get_if<LatexGenerator::GenError>(&result)) {
msg = err->message;
fail = true;
}
}
} else {
msg = FS(_F("Error: {1} is not a regular file. Please check your LaTeX template file settings. ") %
settings.globalTemplatePath.u8string().c_str());
fail = true;
}
GtkWindow* win = GTK_WINDOW(gtk_widget_get_toplevel(GTK_WIDGET(panel)));
XojMsgBox::showMessageToUser(win, msg, fail ? GTK_MESSAGE_ERROR : GTK_MESSAGE_INFO);
}
void LatexSettingsPanel::updateWidgetSensitivity() {
bool useSystemFont = gtk_check_button_get_active(this->cbUseSystemFont);
// Only select a custom font if we're not using the system's.
gtk_widget_set_sensitive(builder.get("boxCustomFontOptions"), !useSystemFont);
#ifndef USE_GTK_SOURCEVIEW
gtk_widget_set_sensitive(builder.get("bxGtkSourceviewSettings"), false);
#endif
}
| 8,666
|
C++
|
.cpp
| 151
| 49.84106
| 120
| 0.691936
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,579
|
GotoDialog.cpp
|
xournalpp_xournalpp/src/core/gui/dialog/GotoDialog.cpp
|
#include "GotoDialog.h"
#include <memory> // for allocator
#include "gui/Builder.h"
class GladeSearchpath;
constexpr auto UI_FILE = "goto.glade";
constexpr auto UI_DIALOG_NAME = "gotoDialog";
using namespace xoj::popup;
GotoDialog::GotoDialog(GladeSearchpath* gladeSearchPath, size_t initialPage, size_t maxPage,
std::function<void(size_t)> callback):
callback(callback) {
Builder builder(gladeSearchPath, UI_FILE);
this->window.reset(GTK_WINDOW(builder.get(UI_DIALOG_NAME)));
this->spinButton = GTK_SPIN_BUTTON(builder.get("spinPage"));
gtk_spin_button_set_range(this->spinButton, 1, static_cast<double>(maxPage));
gtk_spin_button_set_value(this->spinButton, static_cast<double>(initialPage + 1));
gtk_editable_select_region(GTK_EDITABLE(this->spinButton), 0, -1); // Select the entire content
auto onSuccessCallback = G_CALLBACK(+[](GotoDialog* self) {
self->callback(static_cast<size_t>(gtk_spin_button_get_value(GTK_SPIN_BUTTON(self->spinButton))));
gtk_window_close(self->window.get());
});
g_signal_connect_swapped(builder.get("btCancel"), "clicked", G_CALLBACK(gtk_window_close), this->window.get());
g_signal_connect_swapped(builder.get("btOk"), "clicked", onSuccessCallback, this);
}
GotoDialog::~GotoDialog() = default;
| 1,329
|
C++
|
.cpp
| 24
| 50.333333
| 115
| 0.715058
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,580
|
BaseElementView.cpp
|
xournalpp_xournalpp/src/core/gui/dialog/backgroundSelect/BaseElementView.cpp
|
#include "BaseElementView.h"
#include <glib-object.h> // for G_CALLBACK, g_signal_connect
#include "control/settings/Settings.h" // for Settings
#include "gui/Shadow.h" // for Shadow
#include "util/Color.h" // for cairo_set_source_rgbi
#include "util/gtk4_helper.h"
#include "BackgroundSelectDialogBase.h" // for BackgroundSelectDialogBase
constexpr int BORDER_WIDTH = 2;
BaseElementView::BaseElementView(size_t id, BackgroundSelectDialogBase* dlg): dlg(dlg), id(id) {
this->widget = gtk_drawing_area_new();
gtk_drawing_area_set_draw_func(GTK_DRAWING_AREA(widget),
GtkDrawingAreaDrawFunc(+[](GtkWidget*, cairo_t* cr, int, int, gpointer element) {
static_cast<BaseElementView*>(element)->paint(cr);
}),
this, nullptr);
#if GTK_MAJOR_VERSION == 3
gtk_widget_show(this->widget);
gtk_widget_add_events(widget, GDK_BUTTON_PRESS_MASK);
g_signal_connect(this->widget, "button-press-event", G_CALLBACK(+[](GtkWidget*, GdkEventButton*, gpointer d) {
auto* element = static_cast<BaseElementView*>(d);
element->dlg->setSelected(element->id);
return true;
}),
this);
#else
auto* ctrl = gtk_gesture_click_new();
gtk_widget_add_controller(widget, GTK_EVENT_CONTROLLER(ctrl));
gtk_gesture_single_set_button(GTK_GESTURE_SINGLE(ctrl), GDK_BUTTON_PRIMARY);
g_signal_connect(ctrl, "pressed",
G_CALLBACK(+[](GtkGestureClick* g, gint n_press, gdouble x, gdouble y, gpointer d) {
if (n_press == 1) {
auto* element = static_cast<BaseElementView*>(d);
element->dlg->setSelected(element->id);
}
}),
this);
#endif
}
BaseElementView::~BaseElementView() {
gtk_widget_destroy(this->widget);
if (this->crBuffer) {
cairo_surface_destroy(this->crBuffer);
this->crBuffer = nullptr;
}
}
void BaseElementView::setSelected(bool selected) {
if (this->selected == selected) {
return;
}
this->selected = selected;
repaint();
}
void BaseElementView::repaint() {
if (this->crBuffer) {
cairo_surface_destroy(this->crBuffer);
this->crBuffer = nullptr;
}
gtk_widget_queue_draw(this->widget);
}
void BaseElementView::paint(cairo_t* cr) {
GtkAllocation alloc;
gtk_widget_get_allocation(this->widget, &alloc);
if (this->crBuffer == nullptr) {
this->crBuffer = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, alloc.width, alloc.height);
int width = getContentWidth();
int height = getContentHeight();
cairo_t* cr2 = cairo_create(this->crBuffer);
cairo_save(cr2);
cairo_translate(cr2, Shadow::getShadowTopLeftSize() + BORDER_WIDTH,
Shadow::getShadowTopLeftSize() + BORDER_WIDTH);
paintContents(cr2);
cairo_restore(cr2);
cairo_set_operator(cr2, CAIRO_OPERATOR_OVER);
if (this->selected) {
// Draw border
Util::cairo_set_source_rgbi(cr2, dlg->getSettings()->getBorderColor());
cairo_set_line_width(cr2, BORDER_WIDTH);
cairo_set_line_cap(cr2, CAIRO_LINE_CAP_BUTT);
cairo_set_line_join(cr2, CAIRO_LINE_JOIN_BEVEL);
cairo_rectangle(cr2, Shadow::getShadowTopLeftSize() + BORDER_WIDTH / 2,
Shadow::getShadowTopLeftSize() + BORDER_WIDTH / 2, width + BORDER_WIDTH,
height + BORDER_WIDTH);
cairo_stroke(cr2);
Shadow::drawShadow(cr2, Shadow::getShadowTopLeftSize(), Shadow::getShadowTopLeftSize(),
width + 2 * BORDER_WIDTH, height + 2 * BORDER_WIDTH);
} else {
Shadow::drawShadow(cr2, Shadow::getShadowTopLeftSize() + BORDER_WIDTH,
Shadow::getShadowTopLeftSize() + BORDER_WIDTH, width, height);
}
cairo_destroy(cr2);
}
cairo_set_operator(cr, CAIRO_OPERATOR_OVER);
cairo_set_source_surface(cr, this->crBuffer, 0, 0);
cairo_paint(cr);
}
auto BaseElementView::getWidget() -> GtkWidget* {
updateSize();
return this->widget;
}
auto BaseElementView::getWidth() -> int {
calcSize();
return getContentWidth() + Shadow::getShadowBottomRightSize() + Shadow::getShadowTopLeftSize() + 2 * BORDER_WIDTH;
}
auto BaseElementView::getHeight() -> int {
calcSize();
return getContentHeight() + Shadow::getShadowBottomRightSize() + Shadow::getShadowTopLeftSize() + 2 * BORDER_WIDTH;
}
void BaseElementView::calcSize() {
// Not implemented in the base class
}
void BaseElementView::updateSize() { gtk_widget_set_size_request(this->widget, this->getWidth(), this->getHeight()); }
| 5,020
|
C++
|
.cpp
| 111
| 35.342342
| 119
| 0.605409
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,581
|
ImageElementView.cpp
|
xournalpp_xournalpp/src/core/gui/dialog/backgroundSelect/ImageElementView.cpp
|
#include "ImageElementView.h"
#include <gdk-pixbuf/gdk-pixbuf.h> // for gdk_pixbuf_...
#include <gdk/gdk.h> // for gdk_cairo_s...
#include "gui/Shadow.h" // for Shadow
#include "gui/dialog/backgroundSelect/BaseElementView.h" // for BaseElement...
#include "util/safe_casts.h" // for ceil_cast
class BackgroundSelectDialogBase;
constexpr int MINIATURE_PIXEL_SIZE = 128;
ImageElementView::ImageElementView(size_t id, BackgroundSelectDialogBase* dlg): BaseElementView(id, dlg) {}
ImageElementView::~ImageElementView() = default;
void ImageElementView::calcSize() {
if (this->width == -1) {
GdkPixbuf* p = backgroundImage.getPixbuf();
this->width = gdk_pixbuf_get_width(p);
this->height = gdk_pixbuf_get_height(p);
if (this->width < this->height) {
zoom = static_cast<double>(MINIATURE_PIXEL_SIZE) / this->height;
this->height = MINIATURE_PIXEL_SIZE;
this->width = floor_cast<int>(this->width * zoom);
} else {
zoom = static_cast<double>(MINIATURE_PIXEL_SIZE) / this->width;
this->width = MINIATURE_PIXEL_SIZE;
this->height = floor_cast<int>(this->height * zoom);
}
}
}
void ImageElementView::paintContents(cairo_t* cr) {
cairo_scale(cr, this->zoom, this->zoom);
GdkPixbuf* p = this->backgroundImage.getPixbuf();
gdk_cairo_set_source_pixbuf(cr, p, 0, 0);
cairo_paint(cr);
}
auto ImageElementView::getContentWidth() -> int { return width; }
auto ImageElementView::getContentHeight() -> int { return height; }
| 1,640
|
C++
|
.cpp
| 34
| 42.647059
| 107
| 0.640527
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,582
|
ImagesDialog.cpp
|
xournalpp_xournalpp/src/core/gui/dialog/backgroundSelect/ImagesDialog.cpp
|
#include "ImagesDialog.h"
#include <cstddef>
#include <memory>
#include <string>
#include <vector>
#include <glib-object.h>
#include "gui/dialog/XojOpenDlg.h" // for showOpenImageDialog
#include "gui/dialog/backgroundSelect/BackgroundSelectDialogBase.h"
#include "gui/dialog/backgroundSelect/BaseElementView.h"
#include "model/BackgroundImage.h"
#include "model/Document.h"
#include "model/PageRef.h"
#include "model/PageType.h"
#include "model/XojPage.h"
#include "util/PathUtil.h"
#include "util/Util.h" // for npos
#include "util/XojMsgBox.h"
#include "util/i18n.h"
#include "ImageElementView.h"
class GladeSearchpath;
class Settings;
ImagesDialog::ImagesDialog(GladeSearchpath* gladeSearchPath, Document* doc, Settings* settings,
std::function<void(BackgroundImage)> callback):
BackgroundSelectDialogBase(gladeSearchPath, doc, settings, _("Select Image")), callback(std::move(callback)) {
loadImagesFromPages();
GtkWidget* lbl = gtk_label_new(_("<b>... or select already used Image:</b>"));
gtk_label_set_use_markup(GTK_LABEL(lbl), true);
gtk_box_prepend(vbox, lbl);
fileChooserButton = GTK_BUTTON(gtk_button_new_with_label(_("Load file")));
gtk_box_prepend(vbox, GTK_WIDGET(fileChooserButton));
#if GTK_MAJOR_VERSION == 3
gtk_widget_show_all(GTK_WIDGET(vbox));
#endif
g_signal_connect(fileChooserButton, "clicked", G_CALLBACK(filechooserButtonCallback), this);
g_signal_connect_swapped(
okButton, "clicked", G_CALLBACK(+[](ImagesDialog* self) {
if (self->selected < self->entries.size()) {
auto img = (static_cast<ImageElementView*>(self->entries[self->selected].get()))->backgroundImage;
if (!img.isEmpty()) {
self->callback(std::move(img));
}
}
gtk_window_close(self->window.get());
}),
this);
populate();
}
ImagesDialog::~ImagesDialog() = default;
void ImagesDialog::loadImagesFromPages() {
doc->lock();
for (size_t i = 0; i < doc->getPageCount(); i++) {
PageRef p = doc->getPage(i);
if (!p->getBackgroundType().isImagePage()) {
continue;
}
if (p->getBackgroundImage().isEmpty()) {
continue;
}
if (isImageAlreadyInTheList(p->getBackgroundImage())) {
// Do not display the same image twice
continue;
}
auto* iv = new ImageElementView(this->entries.size(), this);
iv->backgroundImage = p->getBackgroundImage();
this->entries.emplace_back(iv);
}
doc->unlock();
}
auto ImagesDialog::isImageAlreadyInTheList(BackgroundImage& image) -> bool {
for (const auto& v: this->entries) {
auto* iv = static_cast<ImageElementView*>(v.get());
if (iv->backgroundImage == image) {
return true;
}
}
return false;
}
void ImagesDialog::filechooserButtonCallback(GtkButton*, ImagesDialog* dlg) {
xoj::OpenDlg::showOpenImageDialog(dlg->window.get(), dlg->settings, [dlg](fs::path p, bool attach) {
BackgroundImage img;
GError* err = nullptr;
img.loadFile(p, &err);
img.setAttach(attach);
if (err) {
XojMsgBox::showErrorToUser(dlg->window.get(),
FS(_F("This image could not be loaded. Error message: {1}") % err->message));
g_error_free(err);
return;
}
if (img.isEmpty()) {
XojMsgBox::showErrorToUser(dlg->window.get(), _("This image could not be loaded."));
return;
}
dlg->callback(std::move(img));
gtk_window_close(dlg->window.get());
});
}
| 3,773
|
C++
|
.cpp
| 97
| 31.247423
| 118
| 0.624692
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,583
|
PdfPagesDialog.cpp
|
xournalpp_xournalpp/src/core/gui/dialog/backgroundSelect/PdfPagesDialog.cpp
|
#include "PdfPagesDialog.h"
#include <cstddef>
#include <memory>
#include <string>
#include <vector>
#include <glib-object.h>
#include "gui/dialog/backgroundSelect/BackgroundSelectDialogBase.h"
#include "gui/dialog/backgroundSelect/BaseElementView.h"
#include "model/Document.h"
#include "model/PageRef.h"
#include "model/PageType.h"
#include "model/XojPage.h"
#include "pdf/base/XojPdfPage.h"
#include "util/Assert.h"
#include "util/Util.h" // for npos
#include "util/i18n.h" // for FC
#include "PdfElementView.h"
class GladeSearchpath;
class Settings;
PdfPagesDialog::PdfPagesDialog(GladeSearchpath* gladeSearchPath, Document* doc, Settings* settings,
std::function<void(size_t)> callback):
BackgroundSelectDialogBase(gladeSearchPath, doc, settings, _("Select PDF Page")),
callback(std::move(callback)) {
doc->lock();
for (size_t i = 0; i < doc->getPdfPageCount(); i++) {
XojPdfPageSPtr p = doc->getPdfPage(i);
entries.emplace_back(std::make_unique<PdfElementView>(entries.size(), p, this));
}
size_t used = 0;
for (size_t i = 0; i < doc->getPageCount(); i++) {
PageRef p = doc->getPage(i);
if (p->getBackgroundType().isPdfPage()) {
auto pdfPage = p->getPdfPageNr();
if (pdfPage >= 0 && pdfPage < entries.size()) {
auto* pv = (static_cast<PdfElementView*>(entries[pdfPage].get()));
if (!pv->isUsed()) {
pv->setUsed(true);
used++;
}
}
}
}
xoj_assert(used <= doc->getPdfPageCount());
auto unused = doc->getPdfPageCount() - used;
doc->unlock();
cbUnusedOnly = GTK_CHECK_BUTTON(gtk_check_button_new_with_label(
(unused == 1 ? _("Show only not used pages (one unused page)") :
FC(_F("Show only not used pages ({1} unused pages)") % unused))));
gtk_box_prepend(vbox, GTK_WIDGET(cbUnusedOnly));
#if GTK_MAJOR_VERSION == 3
gtk_widget_show_all(GTK_WIDGET(vbox));
#endif
g_signal_connect(cbUnusedOnly, "toggled", G_CALLBACK(onlyNotUsedCallback), this);
g_signal_connect_swapped(okButton, "clicked", G_CALLBACK(+[](PdfPagesDialog* self) {
if (self->selected < self->entries.size()) {
self->callback(self->selected);
}
gtk_window_close(self->window.get());
}),
this);
populate();
}
PdfPagesDialog::~PdfPagesDialog() = default;
void PdfPagesDialog::updateOkButton() {
bool valid = selected < entries.size() && gtk_widget_get_visible(this->entries[this->selected]->getWidget());
gtk_widget_set_sensitive(okButton, valid);
}
void PdfPagesDialog::onlyNotUsedCallback(GtkToggleButton* tb, PdfPagesDialog* dlg) {
bool hideIfUsed = gtk_toggle_button_get_active(tb);
for (const auto& p: dlg->entries) {
auto* pv = static_cast<PdfElementView*>(p.get());
pv->setHideIfUsed(hideIfUsed);
}
dlg->layout();
dlg->updateOkButton();
}
| 3,176
|
C++
|
.cpp
| 76
| 33.342105
| 113
| 0.60902
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,584
|
BackgroundSelectDialogBase.cpp
|
xournalpp_xournalpp/src/core/gui/dialog/backgroundSelect/BackgroundSelectDialogBase.cpp
|
#include "BackgroundSelectDialogBase.h"
#include <algorithm> // for max
#include <utility> // for move
#include <gdk/gdk.h> // for GDK_EXPOSURE_MASK
#include <glib-object.h> // for G_CALLBACK, g_signal_connect
#include "gui/Builder.h"
#include "util/Util.h" // for paintBackgroundWhite
#include "util/gtk4_helper.h"
#include "util/safe_casts.h" // for round_cast
#include "BaseElementView.h" // for BaseElementView
class GladeSearchpath;
constexpr auto UI_FILE = "backgroundSelection.glade";
constexpr auto UI_DIALOG_NAME = "Dialog";
BackgroundSelectDialogBase::BackgroundSelectDialogBase(GladeSearchpath* gladeSearchPath, Document* doc,
Settings* settings, const char* title):
settings(settings), doc(doc) {
Builder builder(gladeSearchPath, UI_FILE);
this->window.reset(GTK_WINDOW(builder.get(UI_DIALOG_NAME)));
gtk_window_set_title(window.get(), title);
this->container = GTK_FIXED(gtk_fixed_new());
gtk_widget_set_hexpand(GTK_WIDGET(this->container), true);
this->okButton = builder.get("btOk");
this->vbox = GTK_BOX(builder.get("vbox"));
this->scrolledWindow = GTK_SCROLLED_WINDOW(builder.get("scrollContents"));
gtk_scrolled_window_set_child(scrolledWindow, GTK_WIDGET(container));
g_signal_connect(gtk_scrolled_window_get_hadjustment(scrolledWindow), "notify::page-size",
G_CALLBACK(+[](GObject*, GParamSpec*, gpointer d) {
static_cast<BackgroundSelectDialogBase*>(d)->layout();
}),
this);
gtk_window_set_default_size(this->window.get(), 800, 600);
gtk_widget_set_sensitive(this->okButton, false);
g_signal_connect_swapped(builder.get("btCancel"), "clicked", G_CALLBACK(gtk_window_close), this->window.get());
g_signal_connect(this->container, "realize", G_CALLBACK(+[](GtkWidget*, gpointer self) {
static_cast<BackgroundSelectDialogBase*>(self)->layout();
}),
this);
}
BackgroundSelectDialogBase::~BackgroundSelectDialogBase() = default;
auto BackgroundSelectDialogBase::getSettings() -> Settings* { return this->settings; }
void BackgroundSelectDialogBase::layout() {
int x = 0;
int y = 0;
int row_height = 0;
int max_row_width = 0;
auto width = gtk_adjustment_get_page_size(gtk_scrolled_window_get_hadjustment(scrolledWindow));
for (const auto& p: this->entries) {
if (!gtk_widget_get_visible(p->getWidget())) {
continue;
}
if (x + p->getWidth() > width) {
max_row_width = std::max(max_row_width, x);
y += row_height;
x = 0;
row_height = 0;
}
gtk_fixed_move(this->container, p->getWidget(), x, y);
row_height = std::max(row_height, p->getHeight());
x += p->getWidth();
}
max_row_width = std::max(max_row_width, x);
gtk_widget_set_size_request(GTK_WIDGET(this->container), max_row_width, y + row_height);
}
void BackgroundSelectDialogBase::populate() {
for (const auto& e: entries) {
gtk_fixed_put(this->container, e->getWidget(), 0, 0);
}
if (!entries.empty()) {
setSelected(0);
}
layout();
}
void BackgroundSelectDialogBase::setSelected(size_t selected) {
if (this->selected == selected) {
return;
}
size_t lastSelected = this->selected;
if (lastSelected < entries.size()) {
entries[lastSelected]->setSelected(false);
}
if (selected < entries.size()) {
entries[selected]->setSelected(true);
this->selected = selected;
gtk_widget_set_sensitive(okButton, true);
}
}
| 3,745
|
C++
|
.cpp
| 86
| 36.05814
| 115
| 0.639218
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,585
|
PdfElementView.cpp
|
xournalpp_xournalpp/src/core/gui/dialog/backgroundSelect/PdfElementView.cpp
|
#include "PdfElementView.h"
#include <memory> // for __shared_pt...
#include <utility> // for move
#include <gtk/gtk.h> // for gtk_widget_...
#include "gui/dialog/backgroundSelect/BaseElementView.h" // for BaseElement...
#include "pdf/base/XojPdfPage.h" // for XojPdfPageSPtr
#include "util/safe_casts.h" // for ceil_cast
#include "PdfPagesDialog.h" // for PdfPagesDialog
PdfElementView::PdfElementView(size_t id, XojPdfPageSPtr page, PdfPagesDialog* dlg):
BaseElementView(id, dlg), page(std::move(page)) {}
PdfElementView::~PdfElementView() = default;
auto PdfElementView::isUsed() const -> bool { return this->used; }
void PdfElementView::setUsed(bool used) { this->used = used; }
void PdfElementView::setHideIfUsed(bool hideIfUsed) { gtk_widget_set_visible(getWidget(), !(hideIfUsed && isUsed())); }
void PdfElementView::paintContents(cairo_t* cr) {
cairo_scale(cr, PdfPagesDialog::ZOOM_VALUE, PdfPagesDialog::ZOOM_VALUE);
page->render(cr);
}
auto PdfElementView::getContentWidth() -> int { return floor_cast<int>(page->getWidth() * PdfPagesDialog::ZOOM_VALUE); }
auto PdfElementView::getContentHeight() -> int {
return floor_cast<int>(page->getHeight() * PdfPagesDialog::ZOOM_VALUE);
}
| 1,282
|
C++
|
.cpp
| 22
| 55.818182
| 120
| 0.703526
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,586
|
ToolbarDragDropHandler.cpp
|
xournalpp_xournalpp/src/core/gui/dialog/toolbarCustomize/ToolbarDragDropHandler.cpp
|
#include "ToolbarDragDropHandler.h"
#include <string> // for allocator, string
#include <gtk/gtk.h> // for GtkWidget, GTK_TO...
#include "control/Control.h" // for Control
#include "gui/FloatingToolbox.h" // for FloatingToolbox
#include "gui/MainWindow.h" // for MainWindow
#include "gui/toolbarMenubar/model/ToolbarModel.h" // for ToolbarModel
#include "util/PathUtil.h" // for getConfigFile
#include "ToolbarAdapter.h" // for ToolbarAdapter
#include "ToolbarCustomizeDialog.h" // for ToolbarCustomizeD...
#include "config-dev.h" // for TOOLBAR_CONFIG
ToolbarDragDropHandler::ToolbarDragDropHandler(Control* control): control(control) {}
ToolbarDragDropHandler::~ToolbarDragDropHandler() = default;
void ToolbarDragDropHandler::prepareToolbarsForDragAndDrop() {
MainWindow* win = control->getWindow();
this->toolbars.clear();
for (auto w: win->getToolbarWidgets()) {
this->toolbars.emplace_back(std::make_unique<ToolbarAdapter>(w.get(), win->getToolbarName(GTK_TOOLBAR(w.get())),
control->getWindow()->getToolMenuHandler(), win));
}
}
void ToolbarDragDropHandler::clearToolbarsFromDragAndDrop() { this->toolbars.clear(); }
void ToolbarDragDropHandler::toolbarConfigDialogClosed() {
this->customizeDialog.reset();
MainWindow* win = control->getWindow();
this->clearToolbarsFromDragAndDrop();
auto file = Util::getConfigFile(TOOLBAR_CONFIG);
win->getToolbarModel()->save(file);
win->getFloatingToolbox()->hide();
}
void ToolbarDragDropHandler::configure() {
MainWindow* win = control->getWindow();
win->getFloatingToolbox()->showForConfiguration();
this->prepareToolbarsForDragAndDrop();
this->customizeDialog = std::make_unique<ToolbarCustomizeDialog>(control->getGladeSearchPath(), win, this);
this->customizeDialog->show(GTK_WINDOW(win->getWindow()));
}
| 2,030
|
C++
|
.cpp
| 37
| 49.621622
| 120
| 0.686771
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,587
|
ToolbarCustomizeDialog.cpp
|
xournalpp_xournalpp/src/core/gui/dialog/toolbarCustomize/ToolbarCustomizeDialog.cpp
|
#include "ToolbarCustomizeDialog.h"
#include <cstddef> // for size_t
#include <limits> // for numeric_l...
#include <string> // for allocator
#include <vector> // for vector
#include <gdk-pixbuf/gdk-pixbuf.h> // for GdkPixbuf
#include <glib-object.h> // for G_CALLBACK
#include "control/Control.h" // for Control
#include "control/settings/Settings.h" // for Settings
#include "gui/Builder.h"
#include "gui/MainWindow.h" // for MainWindow
#include "gui/ToolitemDragDrop.h" // for ToolItemD...
#include "gui/toolbarMenubar/AbstractToolItem.h" // for AbstractT...
#include "gui/toolbarMenubar/ToolMenuHandler.h" // for ToolMenuH...
#include "gui/toolbarMenubar/icon/ColorIcon.h" // for ColorIcon
#include "gui/toolbarMenubar/icon/ToolbarSeparatorImage.h" // for getNewToo...
#include "gui/toolbarMenubar/model/ColorPalette.h" // for Palette
#include "util/Assert.h" // for xoj_assert
#include "util/Color.h" // for Color
#include "util/EnumIndexedArray.h"
#include "util/GListView.h" // for GListView
#include "util/NamedColor.h" // for NamedColor
#include "util/gtk4_helper.h"
#include "util/i18n.h" // for _
#include "util/raii/GObjectSPtr.h"
#include "ToolItemDragCurrentData.h" // for ToolItemD...
#include "ToolbarDragDropHandler.h" // for ToolbarDr...
#include "ToolbarDragDropHelper.h" // for dragSourc...
class GladeSearchpath;
/*
* struct used for data necessary for dragging
* during toolbar customization
*/
struct ToolbarCustomizeDialog::ToolItemDragData {
ToolbarCustomizeDialog* dlg;
GtkWidget* icon; ///< Currently must be an GtkImage
AbstractToolItem* item;
xoj::util::WidgetSPtr ebox;
};
struct ToolbarCustomizeDialog::ColorToolItemDragData {
ToolbarCustomizeDialog* dlg;
size_t paletteColorIndex;
xoj::util::WidgetSPtr ebox;
};
// Separator and spacer
struct ToolbarCustomizeDialog::SeparatorData {
ToolItemType type;
SeparatorType separator;
const char* label;
};
std::array<ToolbarCustomizeDialog::SeparatorData, 2> ToolbarCustomizeDialog::separators = {
ToolbarCustomizeDialog::SeparatorData{TOOL_ITEM_SEPARATOR, SeparatorType::SEPARATOR, _("Separator")},
ToolbarCustomizeDialog::SeparatorData{TOOL_ITEM_SPACER, SeparatorType::SPACER, _("Spacer")}};
constexpr auto UI_FILE = "toolbarCustomizeDialog.glade";
constexpr auto UI_DIALOG_NAME = "DialogCustomizeToolbar";
ToolbarCustomizeDialog::ToolbarCustomizeDialog(GladeSearchpath* gladeSearchPath, MainWindow* win,
ToolbarDragDropHandler* handler):
itemData(buildToolDataVector(win->getToolMenuHandler()->getToolItems())),
colorItemData(buildColorDataVector(handler->getControl()->getPalette())),
palette(handler->getControl()->getPalette()) {
Builder builder(gladeSearchPath, UI_FILE);
window.reset(GTK_WINDOW(builder.get(UI_DIALOG_NAME)));
notebook = GTK_NOTEBOOK(builder.get("notebook"));
using Cat = AbstractToolItem::Category;
EnumIndexedArray<std::string, Cat> labels;
labels[Cat::AUDIO] = C_("Item category in toolbar customization dialog", "Audio");
labels[Cat::COLORS] = C_("Item category in toolbar customization dialog", "Colors");
labels[Cat::FILES] = C_("Item category in toolbar customization dialog", "Files");
labels[Cat::MISC] = C_("Item category in toolbar customization dialog", "Miscellaneous");
labels[Cat::NAVIGATION] = C_("Item category in toolbar customization dialog", "Navigation");
labels[Cat::SELECTION] = C_("Item category in toolbar customization dialog", "Selection");
labels[Cat::TOOLS] = C_("Item category in toolbar customization dialog", "Tools");
labels[Cat::SEPARATORS] = C_("Item category in toolbar customization dialog", "Separators");
labels[Cat::PLUGINS] = C_("Item category in toolbar customization dialog", "Plugins");
EnumIndexedArray<GtkWidget*, Cat> tabs;
for (std::underlying_type_t<Cat> n = 0; n < xoj::to_underlying(Cat::ENUMERATOR_COUNT); n++) {
Cat c = static_cast<Cat>(n);
tabs[c] = gtk_list_box_new();
GtkWidget* w = gtk_scrolled_window_new();
gtk_scrolled_window_set_child(GTK_SCROLLED_WINDOW(w), tabs[c]);
gtk_notebook_append_page(notebook, w, gtk_label_new(labels[c].c_str()));
}
auto addEntry = [&tabs](GtkWidget* w, Cat c) {
GtkWidget* row = gtk_list_box_row_new();
gtk_list_box_row_set_child(GTK_LIST_BOX_ROW(row), w);
gtk_list_box_row_set_selectable(GTK_LIST_BOX_ROW(row), false);
gtk_list_box_append(GTK_LIST_BOX(tabs[c]), row);
};
for (auto& data: itemData) {
addEntry(data.ebox.get(), data.item->getCategory());
}
for (auto& data: colorItemData) {
addEntry(data.ebox.get(), Cat::COLORS);
}
// init separator and spacer
for (SeparatorData& data: separators) {
GtkBox* box = GTK_BOX(gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 2));
gtk_box_append(box, ToolbarSeparatorImage::newImage(data.separator));
gtk_box_append(box, gtk_label_new(data.label));
GtkWidget* ebox = gtk_event_box_new();
gtk_container_add(GTK_CONTAINER(ebox), GTK_WIDGET(box));
gtk_widget_show_all(ebox);
// make ebox a drag source
gtk_drag_source_set(ebox, GDK_BUTTON1_MASK, &ToolbarDragDropHelper::dropTargetEntry, 1, GDK_ACTION_MOVE);
ToolbarDragDropHelper::dragSourceAddToolbar(ebox);
g_signal_connect(ebox, "drag-begin", G_CALLBACK(toolitemDragBeginSeparator), &data);
g_signal_connect(ebox, "drag-end", G_CALLBACK(toolitemDragEndSeparator), &data);
g_signal_connect(ebox, "drag-data-get", G_CALLBACK(toolitemDragDataGetSeparator), &data);
addEntry(ebox, Cat::SEPARATORS);
}
GtkWidget* target = GTK_WIDGET(notebook); // builder.get("viewport1");
// prepare drag & drop
gtk_drag_dest_set(target, GTK_DEST_DEFAULT_ALL, nullptr, 0, GDK_ACTION_MOVE);
ToolbarDragDropHelper::dragDestAddToolbar(target);
g_signal_connect(target, "drag-data-received", G_CALLBACK(dragDataReceived), this);
g_signal_connect_swapped(builder.get("btClose"), "clicked", G_CALLBACK(gtk_window_close), window.get());
g_signal_connect_swapped(window.get(), "delete-event",
G_CALLBACK(+[](ToolbarDragDropHandler* h) { h->toolbarConfigDialogClosed(); }), handler);
}
ToolbarCustomizeDialog::~ToolbarCustomizeDialog() = default;
void ToolbarCustomizeDialog::toolitemDragBeginSeparator(GtkWidget* widget, GdkDragContext* context, void* data) {
SeparatorData* sepData = static_cast<SeparatorData*>(data);
ToolItemDragCurrentData::setData(sepData->type, -1, nullptr);
GdkPixbuf* pixbuf = ToolbarSeparatorImage::getNewToolPixbuf(sepData->separator);
gtk_drag_set_icon_pixbuf(context, pixbuf, -2, -2);
g_object_unref(pixbuf);
}
void ToolbarCustomizeDialog::toolitemDragEndSeparator(GtkWidget* widget, GdkDragContext* context, void* unused) {
ToolItemDragCurrentData::clearData();
}
void ToolbarCustomizeDialog::toolitemDragDataGetSeparator(GtkWidget* widget, GdkDragContext* context,
GtkSelectionData* selection_data, guint info, guint time,
void* data) {
SeparatorData* sepData = static_cast<SeparatorData*>(data);
auto it = ToolitemDragDrop::ToolItemDragDropData_new(nullptr);
it->type = sepData->type;
gtk_selection_data_set(selection_data, ToolbarDragDropHelper::atomToolItem, 0,
reinterpret_cast<const guchar*>(it.get()), sizeof(ToolItemDragDropData));
}
/**
* Drag a Toolitem from dialog
*/
void ToolbarCustomizeDialog::toolitemDragBegin(GtkWidget* widget, GdkDragContext* context, ToolItemDragData* data) {
ToolItemDragCurrentData::setData(TOOL_ITEM_ITEM, -1, data->item);
if (data->icon) {
ToolbarDragDropHelper::gdk_context_set_icon_from_image(context, data->icon);
}
}
/**
* Drag a Toolitem from dialog STOPPED
*/
void ToolbarCustomizeDialog::toolitemDragEnd(GtkWidget* widget, GdkDragContext* context, ToolItemDragData* data) {
ToolItemDragCurrentData::clearData();
}
void ToolbarCustomizeDialog::toolitemDragDataGet(GtkWidget* widget, GdkDragContext* context,
GtkSelectionData* selection_data, guint info, guint time,
ToolItemDragData* data) {
g_return_if_fail(data != nullptr);
g_return_if_fail(data->item != nullptr);
auto it = ToolitemDragDrop::ToolItemDragDropData_new(data->item);
gtk_selection_data_set(selection_data, ToolbarDragDropHelper::atomToolItem, 0,
reinterpret_cast<const guchar*>(it.get()), sizeof(ToolItemDragDropData));
}
/**
* Drag a ColorToolitem from dialog
*/
void ToolbarCustomizeDialog::toolitemColorDragBegin(GtkWidget* widget, GdkDragContext* context,
ColorToolItemDragData* data) {
ToolItemDragCurrentData::setDataColor(-1, data->paletteColorIndex);
auto namedColor = data->dlg->palette.getColorAt(data->paletteColorIndex);
auto image = ColorIcon::newGdkPixbuf(namedColor.getColor(), 16, true);
gtk_drag_set_icon_pixbuf(context, image.get(), -2, -2);
}
/**
* Drag a ColorToolitem from dialog STOPPED
*/
void ToolbarCustomizeDialog::toolitemColorDragEnd(GtkWidget* widget, GdkDragContext* context,
ColorToolItemDragData* data) {
ToolItemDragCurrentData::clearData();
}
void ToolbarCustomizeDialog::toolitemColorDragDataGet(GtkWidget* widget, GdkDragContext* context,
GtkSelectionData* selection_data, guint info, guint time,
ColorToolItemDragData* data) {
ToolItemDragCurrentData::setDataColor(-1, data->paletteColorIndex);
auto it = ToolitemDragDrop::ToolItemDragDropData_new(nullptr);
it->type = TOOL_ITEM_COLOR;
it->paletteColorIndex = data->paletteColorIndex;
gtk_selection_data_set(selection_data, ToolbarDragDropHelper::atomToolItem, 0,
reinterpret_cast<const guchar*>(it.get()), sizeof(ToolItemDragDropData));
}
/**
* A tool item was dragged to the dialog
*/
void ToolbarCustomizeDialog::dragDataReceived(GtkWidget* widget, GdkDragContext* dragContext, gint x, gint y,
GtkSelectionData* data, guint info, guint time,
ToolbarCustomizeDialog* dlg) {
if (gtk_selection_data_get_data_type(data) != ToolbarDragDropHelper::atomToolItem) {
gtk_drag_finish(dragContext, false, false, time);
return;
}
auto* d = reinterpret_cast<ToolItemDragDropData const*>(gtk_selection_data_get_data(data));
g_return_if_fail(ToolitemDragDrop::checkToolItemDragDropData(d));
gtk_drag_finish(dragContext, true, false, time);
}
/**
* builds up the icon list
*/
auto ToolbarCustomizeDialog::buildToolDataVector(const std::vector<std::unique_ptr<AbstractToolItem>>& tools)
-> std::vector<ToolItemDragData> {
// By reserving, we ensure no reallocation is done, so the pointer `&data` used below is not invalidated
std::vector<ToolItemDragData> database;
database.reserve(tools.size());
for (auto&& item: tools) {
std::string name = item->getToolDisplayName();
GtkWidget* icon = item->getNewToolIcon(); /* floating */
xoj_assert(icon);
GtkBox* box = GTK_BOX(gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 2));
gtk_box_append(box, icon);
gtk_box_append(box, gtk_label_new(name.c_str()));
GtkWidget* ebox = gtk_event_box_new();
gtk_container_add(GTK_CONTAINER(ebox), GTK_WIDGET(box));
gtk_widget_show_all(GTK_WIDGET(ebox));
auto& data = database.emplace_back();
data.dlg = this;
data.icon = icon;
data.item = item.get();
data.ebox.reset(ebox, xoj::util::adopt);
// make ebox a drag source
gtk_drag_source_set(ebox, GDK_BUTTON1_MASK, &ToolbarDragDropHelper::dropTargetEntry, 1, GDK_ACTION_MOVE);
ToolbarDragDropHelper::dragSourceAddToolbar(ebox);
g_signal_connect(ebox, "drag-begin", G_CALLBACK(toolitemDragBegin), &data);
g_signal_connect(ebox, "drag-end", G_CALLBACK(toolitemDragEnd), &data);
g_signal_connect(ebox, "drag-data-get", G_CALLBACK(toolitemDragDataGet), &data);
}
return database;
}
auto ToolbarCustomizeDialog::buildColorDataVector(const Palette& palette) -> std::vector<ColorToolItemDragData> {
// By reserving, we ensure no reallocation is done, so the pointer `&data` used below is not invalidated
std::vector<ColorToolItemDragData> database;
database.reserve(palette.size());
for (size_t paletteColorIndex = 0; paletteColorIndex < palette.size(); paletteColorIndex++) {
// namedColor needs to be a pointer to pass it into a ColorToolItemDragData
const NamedColor& namedColor = palette.getColorAt(paletteColorIndex);
GtkBox* box = GTK_BOX(gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 2));
gtk_box_append(box, ColorIcon::newGtkImage(namedColor.getColor(), 16, true));
gtk_box_append(box, gtk_label_new(namedColor.getName().c_str()));
GtkWidget* ebox = gtk_event_box_new();
gtk_container_add(GTK_CONTAINER(ebox), GTK_WIDGET(box));
gtk_widget_show_all(GTK_WIDGET(ebox));
// make ebox a drag source
gtk_drag_source_set(ebox, GDK_BUTTON1_MASK, &ToolbarDragDropHelper::dropTargetEntry, 1, GDK_ACTION_MOVE);
ToolbarDragDropHelper::dragSourceAddToolbar(ebox);
auto& data = database.emplace_back();
data.dlg = this;
data.paletteColorIndex = paletteColorIndex;
data.ebox.reset(ebox, xoj::util::ref);
g_signal_connect(ebox, "drag-begin", G_CALLBACK(toolitemColorDragBegin), &data);
g_signal_connect(ebox, "drag-end", G_CALLBACK(toolitemColorDragEnd), &data);
g_signal_connect(ebox, "drag-data-get", G_CALLBACK(toolitemColorDragDataGet), &data);
}
return database;
}
void ToolbarCustomizeDialog::show(GtkWindow* parent) {
gtk_window_set_transient_for(this->window.get(), parent);
gtk_window_set_position(this->window.get(), GTK_WIN_POS_CENTER_ON_PARENT);
gtk_widget_show_all(GTK_WIDGET(this->window.get()));
}
| 14,672
|
C++
|
.cpp
| 267
| 47.666667
| 118
| 0.683418
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,588
|
ToolbarDragDropHelper.cpp
|
xournalpp_xournalpp/src/core/gui/dialog/toolbarCustomize/ToolbarDragDropHelper.cpp
|
#include "ToolbarDragDropHelper.h"
#include <cairo.h> // for cairo_surface_set_device_offset, cairo_surf...
#include <gio/gio.h> // for GIcon
#include <glib-object.h> // for g_object_get, G_OBJECT
#include <glib.h> // for g_warning, gchar
namespace ToolbarDragDropHelper {
const GdkAtom atomToolItem = gdk_atom_intern_static_string("application/xournal-ToolbarItem");
const GtkTargetEntry dropTargetEntry = {const_cast<char*>("move-buffer"), GTK_TARGET_SAME_APP, 1};
auto gdk_context_set_icon_from_image(GdkDragContext* ctx, GtkWidget* widget) -> bool {
auto image = GTK_IMAGE(widget);
auto storage = gtk_image_get_storage_type(image);
switch (storage) {
case GTK_IMAGE_PIXBUF: {
gtk_drag_set_icon_pixbuf(ctx, gtk_image_get_pixbuf(image), -2, -2);
return true;
}
case GTK_IMAGE_ICON_NAME: {
gchar const* icon_name{};
gtk_image_get_icon_name(image, &icon_name, nullptr);
gtk_drag_set_icon_name(ctx, icon_name, -2, -2);
return true;
}
case GTK_IMAGE_GICON: {
#ifndef __APPLE__
GIcon* icon{};
gtk_image_get_gicon(image, &icon, nullptr);
gtk_drag_set_icon_gicon(ctx, icon, -2, -2);
return true;
#else
// Todo (fabian): check, if `gtk_drag_set_icon_gicon` is still unimplemented
g_warning("ToolbarDragDropHelper::gdk_context_set_icon_from_image: GTK_IMAGE_GICON is not handled because "
"`gtk_drag_set_icon_gicon` is not implemented. Please create an issue, if this has changed.");
break;
#endif
}
case GTK_IMAGE_SURFACE: {
cairo_surface_t* surface{};
g_object_get(G_OBJECT(image), "surface", &surface, nullptr);
cairo_surface_set_device_offset(surface, -2, -2);
gtk_drag_set_icon_surface(ctx, surface);
return true;
}
case GTK_IMAGE_EMPTY: { ///< Does nothing
g_warning("ToolbarDragDropHelper::gdk_context_set_icon_from_image: Image storage is empty");
break;
}
case GTK_IMAGE_ICON_SET: { ///< Deprecated
g_warning("ToolbarDragDropHelper::gdk_context_set_icon_from_image: Image storage GTK_IMAGE_ICON_SET is "
"deprecated");
break;
}
case GTK_IMAGE_STOCK: { ///< Deprecated
g_warning("ToolbarDragDropHelper::gdk_context_set_icon_from_image: Image storage GTK_IMAGE_STOCK is "
"deprecated");
break;
}
case GTK_IMAGE_ANIMATION: { ///< Can't be handled as we know
g_warning("ToolbarDragDropHelper::gdk_context_set_icon_from_image: Image storage GTK_IMAGE_ANIMATION can't "
"be handled");
break;
}
}
gtk_drag_set_icon_widget(ctx, widget, -2, -2);
return false;
}
void dragDestAddToolbar(GtkWidget* target) {
GtkTargetList* targetList = gtk_drag_dest_get_target_list(target);
if (targetList) {
gtk_target_list_ref(targetList);
} else {
targetList = gtk_target_list_new(nullptr, 0);
}
// If not exist add, else do nothing
if (!gtk_target_list_find(targetList, atomToolItem, nullptr)) {
gtk_target_list_add(targetList, atomToolItem, 0, 0);
}
gtk_drag_dest_set_target_list(target, targetList);
gtk_target_list_unref(targetList);
}
void dragSourceAddToolbar(GtkWidget* widget) {
GtkTargetList* targetList = gtk_drag_source_get_target_list(widget);
if (targetList) {
// List contains already this type
if (gtk_target_list_find(targetList, atomToolItem, nullptr)) {
return;
}
gtk_target_list_ref(targetList);
} else {
targetList = gtk_target_list_new(nullptr, 0);
}
gtk_target_list_add(targetList, atomToolItem, 0, 0);
gtk_drag_source_set_target_list(widget, targetList);
gtk_target_list_unref(targetList);
}
} // namespace ToolbarDragDropHelper
| 4,059
|
C++
|
.cpp
| 95
| 34.336842
| 120
| 0.622408
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,589
|
ToolItemDragCurrentData.cpp
|
xournalpp_xournalpp/src/core/gui/dialog/toolbarCustomize/ToolItemDragCurrentData.cpp
|
#include "ToolItemDragCurrentData.h"
#include <glib.h> // for g_malloc, g_malloc_n, g_free, g_new
#include "util/Stacktrace.h" // for Stacktrace
class AbstractToolItem;
struct NamedColor;
std::unique_ptr<ToolItemDragDropData> ToolItemDragCurrentData::data = nullptr;
void ToolItemDragCurrentData::clearData() { data.reset(); }
void ToolItemDragCurrentData::setData(GtkWidget* widget) {
data = std::make_unique<ToolItemDragDropData>();
ToolItemDragDropData* d = ToolitemDragDrop::metadataGetMetadata(widget);
if (d == nullptr) {
g_warning("ToolItemDragCurrentData::setData(GtkWidget * widget) could not get data!");
Stacktrace::printStacktrace();
return;
}
*data = *d;
}
void ToolItemDragCurrentData::setData(ToolItemType type, int id, AbstractToolItem* item) {
g_return_if_fail(item != nullptr || type != TOOL_ITEM_ITEM);
data = ToolitemDragDrop::ToolItemDragDropData_new(item);
data->type = type;
data->id = id;
}
void ToolItemDragCurrentData::setDataColor(int id, size_t paletteColorIndex) {
data = ToolitemDragDrop::ToolItemDragDropData_new(nullptr);
data->type = TOOL_ITEM_COLOR;
data->id = id;
data->paletteColorIndex = paletteColorIndex;
}
void ToolItemDragCurrentData::setData(ToolItemDragDropData* d) {
data = std::make_unique<ToolItemDragDropData>();
*data = *d;
}
auto ToolItemDragCurrentData::getData() -> const ToolItemDragDropData* { return data.get(); }
| 1,467
|
C++
|
.cpp
| 34
| 39.294118
| 94
| 0.738732
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,590
|
ToolbarAdapter.cpp
|
xournalpp_xournalpp/src/core/gui/dialog/toolbarCustomize/ToolbarAdapter.cpp
|
#include "ToolbarAdapter.h"
#include <utility> // for move
#include <glib-object.h> // for G_CALLBACK
#include "control/Control.h" // for Control
#include "gui/MainWindow.h" // for MainWindow
#include "gui/ToolitemDragDrop.h" // for ToolItemDragDr...
#include "gui/toolbarMenubar/AbstractToolItem.h" // for AbstractToolItem
#include "gui/toolbarMenubar/ColorToolItem.h" // for ColorToolItem
#include "gui/toolbarMenubar/ToolMenuHandler.h" // for ToolMenuHandler
#include "gui/toolbarMenubar/icon/ColorIcon.h" // for ColorIcon
#include "gui/toolbarMenubar/model/ToolbarData.h" // for ToolbarData
#include "util/Assert.h" // for xoj_assert
#include "util/NamedColor.h" // for NamedColor
#include "util/PlaceholderString.h" // for PlaceholderString
#include "util/gtk4_helper.h"
#include "util/i18n.h"
#include "ToolItemDragCurrentData.h" // for ToolItemDragCu...
#include "ToolbarDragDropHelper.h" // for dragDestAddToo...
using std::string;
ToolbarAdapter::ToolbarAdapter(GtkWidget* toolbar, string toolbarName, ToolMenuHandler* toolHandler,
MainWindow* window):
palette(toolHandler->getControl()->getPalette()) {
this->w = toolbar;
g_object_ref(this->w);
this->toolbarName = std::move(toolbarName);
this->window = window;
// prepare drag & drop
gtk_drag_dest_set(toolbar, GTK_DEST_DEFAULT_ALL, nullptr, 0, GDK_ACTION_MOVE);
ToolbarDragDropHelper::dragDestAddToolbar(toolbar);
g_signal_connect(toolbar, "drag_motion", G_CALLBACK(toolbarDragMotionCb), this);
g_signal_connect(toolbar, "drag_leave", G_CALLBACK(toolbarDragLeafeCb), this);
g_signal_connect(toolbar, "drag_data_received", G_CALLBACK(toolbarDragDataReceivedCb), this);
showToolbar();
prepareToolItems();
gtk_widget_add_css_class(w, "editing");
}
ToolbarAdapter::~ToolbarAdapter() {
// remove drag & drop handler
g_signal_handlers_disconnect_by_func(this->w, (gpointer)toolbarDragMotionCb, this);
g_signal_handlers_disconnect_by_func(this->w, (gpointer)toolbarDragLeafeCb, this);
g_signal_handlers_disconnect_by_func(this->w, (gpointer)toolbarDragDataReceivedCb, this);
cleanupToolbars();
gtk_widget_remove_css_class(w, "editing");
g_object_unref(this->w);
}
void ToolbarAdapter::cleanupToolbars() {
GtkToolbar* tb = GTK_TOOLBAR(this->w);
if (gtk_toolbar_get_n_items(tb) == 0) {
gtk_widget_hide(this->w);
} else {
for (int i = 0; i < gtk_toolbar_get_n_items(tb); i++) {
GtkToolItem* it = gtk_toolbar_get_nth_item(tb, i);
cleanToolItem(it);
}
}
}
void ToolbarAdapter::prepareToolItems() {
GtkToolbar* tb = GTK_TOOLBAR(this->w);
for (int i = 0; i < gtk_toolbar_get_n_items(tb); i++) {
GtkToolItem* it = gtk_toolbar_get_nth_item(tb, i);
prepareToolItem(it);
}
}
void ToolbarAdapter::cleanToolItem(GtkToolItem* it) {
GdkWindow* window = gtk_widget_get_window(GTK_WIDGET(it));
if (window) {
gdk_window_set_cursor(window, nullptr);
}
gtk_tool_item_set_use_drag_window(it, false);
gtk_drag_source_unset(GTK_WIDGET(it));
g_signal_handlers_disconnect_by_func(it, (gpointer)toolitemDragBegin, nullptr);
g_signal_handlers_disconnect_by_func(it, (gpointer)toolitemDragEnd, nullptr);
g_signal_handlers_disconnect_by_func(it, (gpointer)toolitemDragDataGet, this);
}
void ToolbarAdapter::prepareToolItem(GtkToolItem* it) {
gtk_tool_item_set_use_drag_window(it, true);
/*
* Set cursor of drag drop to hand. Note: the tool item must be realized for
* this to work!
*/
{
gtk_widget_realize(GTK_WIDGET(it));
GdkDisplay* display = gtk_widget_get_display(GTK_WIDGET(it));
GdkCursor* cursor = gdk_cursor_new_for_display(display, GDK_HAND2);
xoj_assert(cursor);
GdkWindow* window = gtk_widget_get_window(GTK_WIDGET(it));
xoj_assert(window);
gdk_window_set_cursor(window, cursor);
g_object_unref(cursor);
}
gtk_drag_source_set(GTK_WIDGET(it), GDK_BUTTON1_MASK, &ToolbarDragDropHelper::dropTargetEntry, 1, GDK_ACTION_MOVE);
ToolbarDragDropHelper::dragSourceAddToolbar(GTK_WIDGET(it));
g_signal_connect(it, "drag-begin", G_CALLBACK(toolitemDragBegin), nullptr);
g_signal_connect(it, "drag-end", G_CALLBACK(toolitemDragEnd), nullptr);
g_signal_connect(it, "drag-data-get", G_CALLBACK(toolitemDragDataGet), this);
}
void ToolbarAdapter::showToolbar() {
// force the toolbar to be shown even if empty
gtk_widget_show(this->w);
}
/**
* Drag a Toolitem from toolbar
*/
void ToolbarAdapter::toolitemDragBegin(GtkWidget* widget, GdkDragContext* context, void* unused) {
ToolItemDragDropData* data = ToolitemDragDrop::metadataGetMetadata(widget);
g_return_if_fail(data != nullptr);
ToolItemDragCurrentData::setData(data);
auto* icon = ToolitemDragDrop::getIcon(data);
g_object_ref_sink(icon);
ToolbarDragDropHelper::gdk_context_set_icon_from_image(context, icon);
g_object_unref(icon);
gtk_widget_hide(widget);
}
/**
* Drag a Toolitem from toolbar STOPPED
*/
void ToolbarAdapter::toolitemDragEnd(GtkWidget* widget, GdkDragContext* context, void* unused) {
ToolItemDragCurrentData::clearData();
gtk_widget_show(widget);
}
/**
* Remove a toolbar item from the tool where it was
*/
void ToolbarAdapter::removeFromToolbar(AbstractToolItem* item, const string& toolbarName, int id) {
ToolbarData* d = this->window->getSelectedToolbar();
if (d->removeItemByID(toolbarName, id)) {
if (item != nullptr) {
g_message(
"%s",
FS(_F("Removed tool item {1} from Toolbar {2} ID {3}") % item->getId() % toolbarName % id).c_str());
} else {
g_message("%s", FS(_F("Removed tool item from Toolbar {1} ID {2}") % toolbarName % id).c_str());
}
} else {
if (item != nullptr) {
g_message("%s", FS(_F("Could not remove tool item {1} from Toolbar {2} on position {3}") % item->getId() %
toolbarName % id)
.c_str());
} else {
g_message("%s",
FS(_F("Could not remove tool item from Toolbar {1} on position {2}") % toolbarName % id).c_str());
}
}
}
void ToolbarAdapter::toolitemDragDataGet(GtkWidget* widget, GdkDragContext* context, GtkSelectionData* selection_data,
guint info, guint time, ToolbarAdapter* adapter) {
ToolItemDragDropData* data = ToolitemDragDrop::metadataGetMetadata(widget);
g_return_if_fail(data != nullptr);
GtkToolbar* tb = GTK_TOOLBAR(adapter->w);
int position = -1;
for (int i = 0; i < gtk_toolbar_get_n_items(tb); i++) {
GtkToolItem* it = gtk_toolbar_get_nth_item(tb, i);
if (static_cast<void*>(it) == static_cast<void*>(widget)) {
adapter->cleanToolItem(it);
gtk_container_remove(GTK_CONTAINER(tb), GTK_WIDGET(it));
position = i;
break;
}
}
g_return_if_fail(position != -1);
adapter->removeFromToolbar(data->item, adapter->toolbarName, data->id);
gtk_selection_data_set(selection_data, ToolbarDragDropHelper::atomToolItem, 0,
reinterpret_cast<const guchar*>(data), sizeof(ToolItemDragDropData));
}
/**
* A tool item was dragged to the toolbar
*/
auto ToolbarAdapter::toolbarDragMotionCb(GtkToolbar* toolbar, GdkDragContext* context, gint x, gint y, guint time,
ToolbarAdapter* adapter) -> bool {
GdkAtom target = gtk_drag_dest_find_target(GTK_WIDGET(toolbar), context, nullptr);
if (target != ToolbarDragDropHelper::atomToolItem) {
gdk_drag_status(context, static_cast<GdkDragAction>(0), time);
return false;
}
GtkOrientation orientation = gtk_orientable_get_orientation(GTK_ORIENTABLE(toolbar));
bool horizontal = orientation == GTK_ORIENTATION_HORIZONTAL;
gint ipos = toolbarGetDropIndex(toolbar, x, y, horizontal);
gdk_drag_status(context, gdk_drag_context_get_suggested_action(context), time);
const ToolItemDragDropData* d = ToolItemDragCurrentData::getData();
if (d == nullptr) {
g_warning("ToolbarAdapter.cpp, ToolItemDragDropData == nullptr");
return false;
}
if (d->type == TOOL_ITEM_ITEM) {
GtkWidget* iconWidget = d->item->getNewToolIcon();
GtkToolItem* it = gtk_tool_button_new(iconWidget, "");
gtk_toolbar_set_drop_highlight_item(toolbar, it, ipos);
} else if (d->type == TOOL_ITEM_SEPARATOR) {
GtkToolItem* it = gtk_separator_tool_item_new();
gtk_toolbar_set_drop_highlight_item(toolbar, it, ipos);
} else if (d->type == TOOL_ITEM_SPACER) {
GtkToolItem* it = gtk_separator_tool_item_new();
gtk_tool_item_set_expand(it, true);
gtk_toolbar_set_drop_highlight_item(toolbar, it, ipos);
} else if (d->type == TOOL_ITEM_COLOR) {
auto namedColor = adapter->palette.getColorAt(d->paletteColorIndex);
GtkWidget* iconWidget = ColorIcon::newGtkImage(namedColor.getColor(), 16, true);
GtkToolItem* it = gtk_tool_button_new(iconWidget, "");
gtk_toolbar_set_drop_highlight_item(toolbar, it, ipos);
} else {
g_warning("ToolbarAdapter::toolbarDragMotionCb Unhandled type %i", d->type);
}
return true;
}
void ToolbarAdapter::toolbarDragLeafeCb(GtkToolbar* toolbar, GdkDragContext* context, guint time,
ToolbarAdapter* adapter) {
gtk_toolbar_set_drop_highlight_item(toolbar, nullptr, -1);
}
void ToolbarAdapter::toolbarDragDataReceivedCb(GtkToolbar* toolbar, GdkDragContext* context, gint x, gint y,
GtkSelectionData* data, guint info, guint time,
ToolbarAdapter* adapter) {
auto* d = reinterpret_cast<ToolItemDragDropData const*>(gtk_selection_data_get_data(data));
g_return_if_fail(ToolitemDragDrop::checkToolItemDragDropData(d));
bool horizontal = gtk_orientable_get_orientation(GTK_ORIENTABLE(toolbar)) == GTK_ORIENTATION_HORIZONTAL;
gint pos = toolbarGetDropIndex(toolbar, x, y, horizontal);
if (d->type == TOOL_ITEM_ITEM) {
auto it = d->item->createToolItem(horizontal);
gtk_toolbar_insert(toolbar, GTK_TOOL_ITEM(it.get()), pos); // Increases the ref-count of *it
adapter->prepareToolItem(GTK_TOOL_ITEM(it.get()));
ToolbarData* tb = adapter->window->getSelectedToolbar();
const char* name = adapter->window->getToolbarName(toolbar);
string id = d->item->getId();
int newId = tb->insertItem(name, id, pos);
ToolitemDragDrop::attachMetadata(it.get(), newId, d->item);
} else if (d->type == TOOL_ITEM_COLOR) {
auto namedColor = adapter->palette.getColorAt(d->paletteColorIndex);
auto item = std::make_unique<ColorToolItem>(namedColor);
auto it = item->createToolItem(horizontal);
gtk_toolbar_insert(toolbar, GTK_TOOL_ITEM(it.get()), pos);
adapter->prepareToolItem(GTK_TOOL_ITEM(it.get()));
ToolbarData* tb = adapter->window->getSelectedToolbar();
const char* name = adapter->window->getToolbarName(toolbar);
string id = item->getId();
int newId = tb->insertItem(name, id, pos);
ToolitemDragDrop::attachMetadataColor(it.get(), newId, d->paletteColorIndex, item.get());
adapter->window->getToolMenuHandler()->addColorToolItem(std::move(item));
} else if (d->type == TOOL_ITEM_SEPARATOR) {
GtkToolItem* it = gtk_separator_tool_item_new();
gtk_widget_show_all(GTK_WIDGET(it));
gtk_toolbar_insert(toolbar, it, pos);
adapter->prepareToolItem(it);
ToolbarData* tb = adapter->window->getSelectedToolbar();
const char* name = adapter->window->getToolbarName(toolbar);
int newId = tb->insertItem(name, "SEPARATOR", pos);
ToolitemDragDrop::attachMetadata(GTK_WIDGET(it), newId, TOOL_ITEM_SEPARATOR);
} else if (d->type == TOOL_ITEM_SPACER) {
GtkToolItem* it = gtk_separator_tool_item_new();
gtk_separator_tool_item_set_draw(GTK_SEPARATOR_TOOL_ITEM(it), false);
gtk_tool_item_set_expand(it, true);
gtk_widget_show_all(GTK_WIDGET(it));
gtk_toolbar_insert(toolbar, it, pos);
adapter->prepareToolItem(it);
ToolbarData* tb = adapter->window->getSelectedToolbar();
const char* name = adapter->window->getToolbarName(toolbar);
int newId = tb->insertItem(name, "SPACER", pos);
ToolitemDragDrop::attachMetadata(GTK_WIDGET(it), newId, TOOL_ITEM_SPACER);
} else {
g_warning("toolbarDragDataReceivedCb: ToolItemType %i not handled!", d->type);
}
}
auto ToolbarAdapter::toolbarGetDropIndex(GtkToolbar* toolbar, gint x, gint y, bool horizontal) -> gint {
/*
* gtk_toolbar_get_drop_index does not use the correct coordinate system for the y coordinate
* since the y coordinate is only relevant in vertical toolbars the transformation is NOT required for horizontal
* toolbars
*/
if (horizontal) {
return gtk_toolbar_get_drop_index(toolbar, x, y);
} else {
gint wx = 0;
gint wy = 0;
gtk_widget_translate_coordinates(GTK_WIDGET(toolbar), gtk_widget_get_toplevel(GTK_WIDGET(toolbar)), x, y, &wx,
&wy);
return gtk_toolbar_get_drop_index(toolbar, x, wy);
}
}
| 13,791
|
C++
|
.cpp
| 276
| 42.634058
| 120
| 0.657323
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,591
|
ColorSelectorToolItem.cpp
|
xournalpp_xournalpp/src/core/gui/toolbarMenubar/ColorSelectorToolItem.cpp
|
#include "ColorSelectorToolItem.h"
#include <gtk/gtk.h>
#include "control/actions/ActionDatabase.h"
#include "gui/toolbarMenubar/icon/ColorIcon.h" // for ColorIcon
#include "util/GtkUtil.h" // for fixActionableInitialSensitivity
#include "util/gtk4_helper.h" // for gtk_button_set_child
#include "util/i18n.h" // for _
constexpr int ICON_SIZE = 22;
ColorSelectorToolItem::ColorSelectorToolItem(ActionDatabase& db):
AbstractToolItem("COLOR_SELECT", Category::COLORS), gAction(db.getAction(Action::TOOL_COLOR)) {}
auto ColorSelectorToolItem::createItem(bool) -> xoj::util::WidgetSPtr {
GtkWidget* btn = gtk_button_new();
gtk_widget_set_can_focus(btn, false); // todo(gtk4) not necessary anymore
xoj::util::GVariantSPtr v(g_action_get_state(G_ACTION(gAction.get())), xoj::util::adopt);
Color initialColor = getGVariantValue<Color>(v.get());
gtk_button_set_child(GTK_BUTTON(btn), ColorIcon::newGtkImage(initialColor, ICON_SIZE, false));
gtk_widget_set_tooltip_text(btn, this->getToolDisplayName().c_str());
gtk_widget_set_sensitive(btn, g_action_get_enabled(G_ACTION(gAction.get())));
gtk_actionable_set_action_name(GTK_ACTIONABLE(btn),
(std::string("win.") + Action_toString(Action::SELECT_COLOR)).c_str());
// The color follows the value of the GAction state
// NB: we use the notify::state signal because "change-state" is not raised by g_simple_action_set_state()
g_signal_connect_object(gAction.get(), "notify::state", G_CALLBACK(+[](GObject* a, GParamSpec*, gpointer btn) {
xoj::util::GVariantSPtr state(g_action_get_state(G_ACTION(a)), xoj::util::adopt);
auto c = getGVariantValue<Color>(state.get());
gtk_button_set_child(GTK_BUTTON(btn), ColorIcon::newGtkImage(c, ICON_SIZE, false));
}),
btn, GConnectFlags(0));
// Make a proxy for GtkToolbar
GtkToolItem* it = gtk_tool_item_new();
gtk_container_add(GTK_CONTAINER(it), btn);
/// Makes a proxy item for the toolbar's overflow menu
auto createProxy = [&]() {
constexpr int PROXY_ICON_SIZE = 16;
GtkWidget* proxy = gtk_menu_item_new();
auto* box = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 6);
gtk_container_add(GTK_CONTAINER(proxy), box);
gtk_box_append(GTK_BOX(box), ColorIcon::newGtkImage(Colors::gray, PROXY_ICON_SIZE, false));
gtk_box_append(GTK_BOX(box), gtk_label_new(getToolDisplayName().c_str()));
gtk_actionable_set_action_name(GTK_ACTIONABLE(proxy),
(std::string("win.") + Action_toString(Action::SELECT_COLOR)).c_str());
xoj::util::gtk::fixActionableInitialSensitivity(GTK_ACTIONABLE(proxy));
return proxy;
};
gtk_tool_item_set_proxy_menu_item(it, "", createProxy());
return xoj::util::WidgetSPtr(GTK_WIDGET(it), xoj::util::adopt);
}
auto ColorSelectorToolItem::getToolDisplayName() const -> std::string { return _("Select color"); }
auto ColorSelectorToolItem::getNewToolIcon() const -> GtkWidget* {
return ColorIcon::newGtkImage(Colors::gray, ICON_SIZE, false);
}
| 3,291
|
C++
|
.cpp
| 51
| 55.764706
| 115
| 0.649226
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,592
|
PluginToolButton.cpp
|
xournalpp_xournalpp/src/core/gui/toolbarMenubar/PluginToolButton.cpp
|
#include "PluginToolButton.h"
#include "config-features.h" // for ENABLE_PLUGINS
#ifdef ENABLE_PLUGINS
#include <utility> // for move
#include "plugin/Plugin.h" // for ToolbarButtonEntry
#include "util/glib_casts.h"
#include "util/gtk4_helper.h"
PluginToolButton::PluginToolButton(ToolbarButtonEntry* t):
AbstractToolItem(std::move(t->toolbarId), Category::PLUGINS), t(t) {}
PluginToolButton::~PluginToolButton() = default;
auto PluginToolButton::createItem(bool) -> xoj::util::WidgetSPtr {
xoj::util::WidgetSPtr item(gtk_button_new(), xoj::util::adopt);
gtk_widget_set_can_focus(item.get(), false); // todo(gtk4) not necessary anymore
GtkButton* btn = GTK_BUTTON(item.get());
gtk_button_set_relief(btn, GTK_RELIEF_NONE);
gtk_button_set_icon_name(btn, t->iconName.c_str());
gtk_widget_set_tooltip_text(GTK_WIDGET(btn), t->description.c_str());
// Connect signal
g_signal_connect(item.get(), "clicked", G_CALLBACK(+[](GtkWidget*, gpointer d) {
auto* te = static_cast<ToolbarButtonEntry*>(d);
te->plugin->executeToolbarButton(te);
}),
this->t);
return item;
}
auto PluginToolButton::getToolDisplayName() const -> std::string { return this->t->description; }
auto PluginToolButton::getNewToolIcon() const -> GtkWidget* {
return gtk_image_new_from_icon_name(t->iconName.c_str(), GTK_ICON_SIZE_SMALL_TOOLBAR);
}
#endif /* ENABLE_PLUGINS */
| 1,493
|
C++
|
.cpp
| 30
| 43.633333
| 97
| 0.677709
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,593
|
DrawingTypeComboToolButton.cpp
|
xournalpp_xournalpp/src/core/gui/toolbarMenubar/DrawingTypeComboToolButton.cpp
|
#include "DrawingTypeComboToolButton.h"
#include <algorithm> // for find_if
#include <utility> // for move
#include <gtk/gtk.h>
#include "control/actions/ActionDatabase.h"
#include "gui/IconNameHelper.h"
#include "util/glib_casts.h"
#include "util/gtk4_helper.h" // for gtk_popover_new
#include "util/i18n.h"
/// Returns a floating ref
static GtkWidget* createPopoverEntry(const DrawingTypeComboToolButton::Entry& e) {
GtkWidget* entry = gtk_toggle_button_new();
gtk_widget_set_can_focus(entry, false); // todo(gtk4) not necessary anymore
auto actionName = std::string("win.") + g_action_get_name(G_ACTION(e.gAction.get()));
gtk_actionable_set_action_name(GTK_ACTIONABLE(entry), actionName.data());
GtkBox* box = GTK_BOX(gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 6));
gtk_button_set_child(GTK_BUTTON(entry), GTK_WIDGET(box));
gtk_box_append(box, gtk_image_new_from_icon_name(e.icon.c_str(), GTK_ICON_SIZE_SMALL_TOOLBAR));
gtk_box_append(box, gtk_label_new(e.name.c_str()));
gtk_widget_set_tooltip_text(entry, e.name.c_str());
return entry;
}
static auto makeEntries(IconNameHelper& icons, const ActionDatabase& db)
-> std::shared_ptr<EnumIndexedArray<DrawingTypeComboToolButton::Entry, DrawingTypeComboToolButton::Type>> {
using Type = DrawingTypeComboToolButton::Type;
using Entry = DrawingTypeComboToolButton::Entry;
auto res = std::make_shared<EnumIndexedArray<Entry, Type>>();
auto& entries = *res;
entries[Type::RECTANGLE] = Entry(_("Draw Rectangle"), icons.iconName("draw-rect"), db, Action::TOOL_DRAW_RECTANGLE);
entries[Type::ELLIPSE] = Entry(_("Draw Ellipse"), icons.iconName("draw-ellipse"), db, Action::TOOL_DRAW_ELLIPSE);
entries[Type::ARROW] = Entry(_("Draw Arrow"), icons.iconName("draw-arrow"), db, Action::TOOL_DRAW_ARROW);
entries[Type::DOUBLE_ARROW] =
Entry(_("Draw Double Arrow"), icons.iconName("draw-double-arrow"), db, Action::TOOL_DRAW_DOUBLE_ARROW);
entries[Type::LINE] = Entry(_("Draw Line"), icons.iconName("draw-line"), db, Action::TOOL_DRAW_LINE);
entries[Type::COORDINATE_SYSTEM] = Entry(_("Draw coordinate system"), icons.iconName("draw-coordinate-system"), db,
Action::TOOL_DRAW_COORDINATE_SYSTEM);
entries[Type::SPLINE] = Entry(_("Draw Spline"), icons.iconName("draw-spline"), db, Action::TOOL_DRAW_SPLINE);
entries[Type::SHAPE_RECOGNIZER] =
Entry(_("Stroke recognizer"), icons.iconName("shape-recognizer"), db, Action::TOOL_DRAW_SHAPE_RECOGNIZER);
return res;
}
DrawingTypeComboToolButton::Entry::Entry(std::string name, std::string icon, const ActionDatabase& db, Action a):
name(std::move(name)),
icon(std::move(icon)),
gAction(db.getAction(a)),
fullActionName(std::string("win.") + g_action_get_name(G_ACTION(gAction.get()))) {}
DrawingTypeComboToolButton::DrawingTypeComboToolButton(std::string id, IconNameHelper& icons, const ActionDatabase& db):
AbstractToolItem(std::move(id), Category::TOOLS),
entries(makeEntries(icons, db)),
iconName(icons.iconName("combo-drawing-type")),
description(_("Drawing Type Combo")) {}
DrawingTypeComboToolButton::~DrawingTypeComboToolButton() = default;
/// Data structure for callbacks
struct Data {
GtkButton* button;
GtkPopover* popover;
std::shared_ptr<const EnumIndexedArray<DrawingTypeComboToolButton::Entry, DrawingTypeComboToolButton::Type>>
entries;
template <DrawingTypeComboToolButton::Type s>
static void setProminentIconCallback(GObject* action, GParamSpec*, Data* self) {
xoj::util::GVariantSPtr state(g_action_get_state(G_ACTION(action)), xoj::util::adopt);
if (getGVariantValue<bool>(state.get())) {
auto& e = (*self->entries)[s];
gtk_button_set_icon_name(self->button, e.icon.c_str());
gtk_widget_set_tooltip_text(GTK_WIDGET(self->button), e.name.c_str());
gtk_actionable_set_action_name(GTK_ACTIONABLE(self->button), e.fullActionName.c_str());
}
gtk_popover_popdown(self->popover);
}
};
auto DrawingTypeComboToolButton::createItem(bool horizontal) -> xoj::util::WidgetSPtr {
auto data = std::make_unique<Data>();
data->entries = this->entries;
{ // Create popover
data->popover = GTK_POPOVER(gtk_popover_new());
GtkBox* box = GTK_BOX(gtk_box_new(GTK_ORIENTATION_VERTICAL, 0));
gtk_popover_set_child(data->popover, GTK_WIDGET(box));
gtk_widget_add_css_class(GTK_WIDGET(data->popover), "toolbar");
for (const Entry& t: *this->entries) {
gtk_box_append(box, createPopoverEntry(t));
}
gtk_widget_show_all(GTK_WIDGET(box));
}
{ // Create prominent button
GtkWidget* btn = gtk_toggle_button_new();
data->button = GTK_BUTTON(btn);
gtk_widget_set_can_focus(btn, false); // todo(gtk4) not necessary anymore
auto it = std::find_if(entries->begin(), entries->end(), [](auto& e) {
xoj::util::GVariantSPtr state(g_action_get_state(G_ACTION(e.gAction.get())), xoj::util::adopt);
return getGVariantValue<bool>(state.get());
});
const Entry& e = it == entries->end() ? (*entries)[Type::RECTANGLE] : *it; // Select an entry by default
gtk_actionable_set_action_name(GTK_ACTIONABLE(btn), e.fullActionName.data());
gtk_button_set_icon_name(GTK_BUTTON(btn), e.icon.c_str());
gtk_widget_set_tooltip_text(btn, e.name.c_str());
}
// Create item
GtkMenuButton* menubutton = GTK_MENU_BUTTON(gtk_menu_button_new());
gtk_widget_set_can_focus(GTK_WIDGET(menubutton), false); // todo(gtk4) not necessary anymore
gtk_menu_button_set_popover(menubutton, GTK_WIDGET(data->popover));
gtk_menu_button_set_direction(menubutton,
horizontal ? GTK_ARROW_DOWN : GTK_ARROW_RIGHT); // TODO: fix directions
GtkBox* box = GTK_BOX(gtk_box_new(horizontal ? GTK_ORIENTATION_HORIZONTAL : GTK_ORIENTATION_VERTICAL, 0));
gtk_box_append(box, GTK_WIDGET(data->button));
gtk_box_append(box, GTK_WIDGET(menubutton));
auto item = xoj::util::WidgetSPtr(GTK_WIDGET(box), xoj::util::adopt);
/// change the prominent icon when selecting an entry (by any means)
g_signal_connect((*entries)[Type::RECTANGLE].gAction.get(), "notify::state",
xoj::util::wrap_for_g_callback_v<Data::setProminentIconCallback<Type::RECTANGLE>>, data.get());
g_signal_connect((*entries)[Type::ELLIPSE].gAction.get(), "notify::state",
xoj::util::wrap_for_g_callback_v<Data::setProminentIconCallback<Type::ELLIPSE>>, data.get());
g_signal_connect((*entries)[Type::ARROW].gAction.get(), "notify::state",
xoj::util::wrap_for_g_callback_v<Data::setProminentIconCallback<Type::ARROW>>, data.get());
g_signal_connect((*entries)[Type::DOUBLE_ARROW].gAction.get(), "notify::state",
xoj::util::wrap_for_g_callback_v<Data::setProminentIconCallback<Type::DOUBLE_ARROW>>, data.get());
g_signal_connect((*entries)[Type::LINE].gAction.get(), "notify::state",
xoj::util::wrap_for_g_callback_v<Data::setProminentIconCallback<Type::LINE>>, data.get());
g_signal_connect((*entries)[Type::COORDINATE_SYSTEM].gAction.get(), "notify::state",
xoj::util::wrap_for_g_callback_v<Data::setProminentIconCallback<Type::COORDINATE_SYSTEM>>,
data.get());
g_signal_connect((*entries)[Type::SPLINE].gAction.get(), "notify::state",
xoj::util::wrap_for_g_callback_v<Data::setProminentIconCallback<Type::SPLINE>>, data.get());
g_signal_connect((*entries)[Type::SHAPE_RECOGNIZER].gAction.get(), "notify::state",
xoj::util::wrap_for_g_callback_v<Data::setProminentIconCallback<Type::SHAPE_RECOGNIZER>>,
data.get());
// Disconnect the signal and destroy *data if the widget is destroyed
g_object_weak_ref(
G_OBJECT(item.get()),
+[](gpointer d, GObject*) {
Data* data = static_cast<Data*>(d);
g_signal_handlers_disconnect_by_data((*data->entries)[Type::RECTANGLE].gAction.get(), d);
g_signal_handlers_disconnect_by_data((*data->entries)[Type::ELLIPSE].gAction.get(), d);
g_signal_handlers_disconnect_by_data((*data->entries)[Type::ARROW].gAction.get(), d);
g_signal_handlers_disconnect_by_data((*data->entries)[Type::DOUBLE_ARROW].gAction.get(), d);
g_signal_handlers_disconnect_by_data((*data->entries)[Type::LINE].gAction.get(), d);
g_signal_handlers_disconnect_by_data((*data->entries)[Type::COORDINATE_SYSTEM].gAction.get(), d);
g_signal_handlers_disconnect_by_data((*data->entries)[Type::SPLINE].gAction.get(), d);
g_signal_handlers_disconnect_by_data((*data->entries)[Type::SHAPE_RECOGNIZER].gAction.get(), d);
delete data;
},
data.release());
return item;
}
auto DrawingTypeComboToolButton::getToolDisplayName() const -> std::string { return this->description; }
auto DrawingTypeComboToolButton::getNewToolIcon() const -> GtkWidget* {
return gtk_image_new_from_icon_name(iconName.c_str(), GTK_ICON_SIZE_SMALL_TOOLBAR);
}
| 9,407
|
C++
|
.cpp
| 147
| 55.496599
| 120
| 0.662371
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,594
|
ToolSelectCombocontrol.cpp
|
xournalpp_xournalpp/src/core/gui/toolbarMenubar/ToolSelectCombocontrol.cpp
|
#include "ToolSelectCombocontrol.h"
#include <utility> // for move
#include "control/ToolEnums.h"
#include "control/actions/ActionDatabase.h"
#include "gui/IconNameHelper.h"
#include "util/i18n.h"
static std::vector<ComboToolButton::Entry> makeEntries(IconNameHelper& icons, bool hideAudio) {
using Entry = ComboToolButton::Entry;
std::vector<Entry> res = {Entry(_("Select Rectangle"), icons.iconName("select-rect"), TOOL_SELECT_RECT),
Entry(_("Select Region"), icons.iconName("select-lasso"), TOOL_SELECT_REGION),
Entry(_("Select Multi-Layer Rectangle"), icons.iconName("select-multilayer-rect"),
TOOL_SELECT_MULTILAYER_RECT),
Entry(_("Select Multi-Layer Region"), icons.iconName("select-multilayer-lasso"),
TOOL_SELECT_MULTILAYER_REGION),
Entry(_("Select Object"), icons.iconName("object-select"), TOOL_SELECT_OBJECT),
Entry(_("Play Object"), icons.iconName("object-play"), TOOL_PLAY_OBJECT)};
if (hideAudio) {
res.pop_back();
}
return res;
}
ToolSelectCombocontrol::ToolSelectCombocontrol(std::string id, IconNameHelper& icons, const ActionDatabase& db,
bool hideAudio):
ComboToolButton(std::move(id), Category::TOOLS, icons.iconName("combo-selection"), _("Selection dropdown menu"),
makeEntries(icons, hideAudio), db.getAction(Action::SELECT_TOOL)) {}
| 1,590
|
C++
|
.cpp
| 25
| 49.28
| 120
| 0.608584
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,595
|
ColorToolItem.cpp
|
xournalpp_xournalpp/src/core/gui/toolbarMenubar/ColorToolItem.cpp
|
#include "ColorToolItem.h"
#include <utility> // for move
#include "enums/Action.enum.h" // for Action
#include "gui/toolbarMenubar/icon/ColorIcon.h" // for ColorIcon
#include "util/GtkUtil.h" // for setToggleButtonUnreleasable
#include "util/gtk4_helper.h" // for gtk_button_set_child
ColorToolItem::ColorToolItem(NamedColor namedColor):
AbstractToolItem(std::string("COLOR(") + std::to_string(namedColor.getIndex()) + ")", Category::COLORS),
namedColor(std::move(namedColor)),
target(xoj::util::makeGVariantSPtr(namedColor.getColor())) {}
ColorToolItem::~ColorToolItem() = default;
auto ColorToolItem::getColor() const -> Color { return this->namedColor.getColor(); }
auto ColorToolItem::createItem(bool) -> xoj::util::WidgetSPtr {
auto* btn = gtk_toggle_button_new();
gtk_widget_set_can_focus(btn, false); // todo(gtk4) not necessary anymore
auto actionName = std::string("win.") + Action_toString(Action::TOOL_COLOR);
gtk_actionable_set_action_name(GTK_ACTIONABLE(btn), actionName.data());
gtk_actionable_set_action_target_value(GTK_ACTIONABLE(btn), target.get());
xoj::util::gtk::setToggleButtonUnreleasable(GTK_TOGGLE_BUTTON(btn));
gtk_widget_set_tooltip_text(btn, this->namedColor.getName().c_str());
gtk_button_set_child(GTK_BUTTON(btn), getNewToolIcon());
// For the sake of deprecated GtkToolbar, wrap the button in a GtkToolItem
// Todo(gtk4): remove
GtkToolItem* it = gtk_tool_item_new();
gtk_container_add(GTK_CONTAINER(it), btn);
/// Makes a proxy item for the toolbar's overflow menu
auto createProxy = [this]() {
GtkWidget* proxy = gtk_check_menu_item_new();
gtk_check_menu_item_set_draw_as_radio(GTK_CHECK_MENU_ITEM(proxy), true);
auto* box = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 6);
gtk_container_add(GTK_CONTAINER(proxy), box);
gtk_box_append(GTK_BOX(box), getNewToolIcon());
gtk_box_append(GTK_BOX(box), gtk_label_new(getToolDisplayName().c_str()));
gtk_actionable_set_action_name(GTK_ACTIONABLE(proxy),
(std::string("win.") + Action_toString(Action::TOOL_COLOR)).c_str());
if (target) {
gtk_actionable_set_action_target_value(GTK_ACTIONABLE(proxy), target.get());
}
xoj::util::gtk::fixActionableInitialSensitivity(GTK_ACTIONABLE(proxy));
return proxy;
};
gtk_tool_item_set_proxy_menu_item(it, "", createProxy());
return xoj::util::WidgetSPtr(GTK_WIDGET(it), xoj::util::adopt);
}
auto ColorToolItem::getToolDisplayName() const -> std::string { return this->namedColor.getName(); }
auto ColorToolItem::getNewToolIcon() const -> GtkWidget* {
return ColorIcon::newGtkImage(this->namedColor.getColor(), 16, true);
}
void ColorToolItem::updateColor(const Palette& palette) { namedColor = palette.getColorAt(namedColor.getIndex()); }
| 2,960
|
C++
|
.cpp
| 49
| 54.326531
| 115
| 0.68174
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,596
|
ToolZoomSlider.cpp
|
xournalpp_xournalpp/src/core/gui/toolbarMenubar/ToolZoomSlider.cpp
|
#include "ToolZoomSlider.h"
#include <cmath> // for exp, log
#include <sstream> // for stringstream, bas...
#include <utility> // for move
#include <glib.h> // for g_get_monotonic_time
#include "control/actions/ActionDatabase.h"
#include "control/zoom/ZoomControl.h" // for ZoomControl, DEFA...
#include "util/i18n.h" // for _
#include "SliderItemCreationHelper.h"
constexpr double SCALE_LOG_OFFSET = 0.20753;
constexpr int FINE_STEP_COUNT = 100;
constexpr int COARSE_STEP_COUNT = 10;
// TODO(personalizedrefrigerator): Update the range to reflect the min and max zoom settings.
constexpr auto SLIDER_RANGE =
AbstractSliderItem::SliderRange{DEFAULT_ZOOM_MIN, DEFAULT_ZOOM_MAX, FINE_STEP_COUNT, COARSE_STEP_COUNT};
ToolZoomSlider::ToolZoomSlider(std::string id, ZoomControl* zoom, IconNameHelper iconNameHelper, ActionDatabase& db):
AbstractSliderItem{std::move(id), Category::NAVIGATION, SLIDER_RANGE, db.getAction(Action::ZOOM)},
iconName(iconNameHelper.iconName("zoom-slider")),
zoomCtrl(zoom) {}
auto ToolZoomSlider::formatSliderValue(double value) -> std::string {
std::stringstream out;
out << static_cast<int>(std::round(100 * scaleInverseFunction(value)));
out << "%";
return out.str();
}
auto ToolZoomSlider::createItem(bool horizontal) -> xoj::util::WidgetSPtr {
auto item = SliderItemCreationHelper<ToolZoomSlider>::createItem(this, horizontal);
class Listener: public ZoomListener {
public:
Listener(GtkScale* slider, ZoomControl* zoomCtrl): slider(slider), zoomCtrl(zoomCtrl) {
zoomCtrl->addZoomListener(this);
}
~Listener() override { zoomCtrl->removeZoomListener(this); }
void zoomChanged() override {} // No need to do anything here. Handled by the GAction
void zoomRangeValuesChanged() override {
gtk_scale_clear_marks(slider);
auto position = gtk_orientable_get_orientation(GTK_ORIENTABLE(slider)) == GTK_ORIENTATION_HORIZONTAL ?
GTK_POS_BOTTOM :
GTK_POS_RIGHT;
gtk_scale_add_mark(slider, scaleFunction(1.0), position, nullptr);
gtk_scale_add_mark(slider, scaleFunction(zoomCtrl->getZoomFitValue() / zoomCtrl->getZoom100Value()),
position, nullptr);
}
GtkScale* slider; ///< Parent to this data
ZoomControl* zoomCtrl;
};
auto data = std::make_unique<Listener>(GTK_SCALE(item.get()), zoomCtrl);
data->zoomRangeValuesChanged(); // Set up the marks
// Destroy *data if the widget is destroyed
g_object_weak_ref(
G_OBJECT(item.get()), +[](gpointer d, GObject*) { delete static_cast<Listener*>(d); }, data.release());
return item;
}
auto ToolZoomSlider::getToolDisplayName() const -> std::string { return _("Zoom Slider"); }
auto ToolZoomSlider::getNewToolIcon() const -> GtkWidget* {
return gtk_image_new_from_icon_name(iconName.c_str(), GTK_ICON_SIZE_SMALL_TOOLBAR);
}
auto ToolZoomSlider::scaleFunction(double x) -> double { return std::log(x - SCALE_LOG_OFFSET); }
auto ToolZoomSlider::scaleInverseFunction(double x) -> double { return std::exp(x) + SCALE_LOG_OFFSET; }
| 3,258
|
C++
|
.cpp
| 59
| 48.355932
| 117
| 0.683962
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,597
|
FontButton.cpp
|
xournalpp_xournalpp/src/core/gui/toolbarMenubar/FontButton.cpp
|
#include "FontButton.h"
#include <sstream> // for stringstream
#include <utility> // for move
#include <glib-object.h> // for g_object_ref, g_obj...
#include "control/Control.h" // for Control
#include "control/actions/ActionDatabase.h" // for ActionDatabase
#include "gui/toolbarMenubar/AbstractToolItem.h" // for AbstractToolItem
#include "model/Font.h" // for Font
#include "util/GtkUtil.h" // for fixActionableInitialSensitivity
#include "util/gtk4_helper.h" // for gtk_button_set_child
#include "util/i18n.h" // for _
#include "util/raii/GVariantSPtr.h"
#include "util/serdesstream.h"
FontButton::FontButton(std::string id, ActionDatabase& db):
AbstractToolItem(std::move(id), Category::TOOLS), gAction(db.getAction(Action::FONT)) {}
static GtkWidget* makeChild(const char* desc) {
XojFont font(desc);
GtkWidget* box = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 10);
gtk_widget_set_margin_start(box, 4);
gtk_widget_set_margin_end(box, 4);
GtkWidget* label = gtk_label_new(nullptr);
auto markup = "<span font=\"" + font.getName() + "\">" + font.getName() + "</span>";
gtk_label_set_markup(GTK_LABEL(label), markup.c_str());
gtk_box_append(GTK_BOX(box), label);
auto size = serdes_stream<std::stringstream>();
size << font.getSize();
gtk_box_append(GTK_BOX(box), gtk_label_new(size.str().c_str()));
gtk_widget_show_all(box);
return box;
}
auto FontButton::createItem(bool horizontal) -> xoj::util::WidgetSPtr {
GtkWidget* btn = gtk_button_new();
gtk_widget_set_can_focus(btn, false); // todo(gtk4) not necessary anymore
xoj::util::GVariantSPtr font(g_action_get_state(G_ACTION(gAction.get())), xoj::util::adopt);
const char* desc = g_variant_get_string(font.get(), nullptr);
gtk_button_set_child(GTK_BUTTON(btn), makeChild(desc));
gtk_widget_set_tooltip_text(btn, getToolDisplayName().c_str());
gtk_actionable_set_action_name(GTK_ACTIONABLE(btn),
(std::string("win.") + Action_toString(Action::SELECT_FONT)).c_str());
g_signal_connect_object(gAction.get(), "notify::state", G_CALLBACK(+[](GObject* action, GParamSpec*, gpointer btn) {
xoj::util::GVariantSPtr font(g_action_get_state(G_ACTION(action)), xoj::util::adopt);
const char* desc = g_variant_get_string(font.get(), nullptr);
gtk_button_set_child(GTK_BUTTON(btn), makeChild(desc));
}),
btn, GConnectFlags(0));
GtkToolItem* it = gtk_tool_item_new();
gtk_container_add(GTK_CONTAINER(it), btn);
/// Makes a proxy item for the toolbar's overflow menu
auto createProxy = [this]() {
GtkWidget* proxy = gtk_menu_item_new();
auto* box = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 6);
gtk_container_add(GTK_CONTAINER(proxy), box);
gtk_box_append(GTK_BOX(box), getNewToolIcon());
gtk_box_append(GTK_BOX(box), gtk_label_new(getToolDisplayName().c_str()));
gtk_actionable_set_action_name(GTK_ACTIONABLE(proxy),
(std::string("win.") + Action_toString(Action::SELECT_FONT)).c_str());
xoj::util::gtk::fixActionableInitialSensitivity(GTK_ACTIONABLE(proxy));
return proxy;
};
gtk_tool_item_set_proxy_menu_item(it, "", createProxy());
return xoj::util::WidgetSPtr(GTK_WIDGET(it), xoj::util::adopt);
}
auto FontButton::getToolDisplayName() const -> std::string { return _("Font"); }
auto FontButton::getNewToolIcon() const -> GtkWidget* {
return gtk_image_new_from_icon_name("font-x-generic", GTK_ICON_SIZE_LARGE_TOOLBAR);
}
| 3,815
|
C++
|
.cpp
| 66
| 50.348485
| 120
| 0.630987
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,598
|
ToolPdfCombocontrol.cpp
|
xournalpp_xournalpp/src/core/gui/toolbarMenubar/ToolPdfCombocontrol.cpp
|
#include "ToolPdfCombocontrol.h"
#include <utility> // for move
#include "control/ToolEnums.h"
#include "control/actions/ActionDatabase.h"
#include "gui/IconNameHelper.h"
#include "util/i18n.h"
ToolPdfCombocontrol::ToolPdfCombocontrol(std::string id, IconNameHelper& icons, const ActionDatabase& db):
ComboToolButton(
std::move(id), Category::SELECTION, icons.iconName("select-pdf-text-ht"),
_("PDF text selection dropdown menu"),
{Entry(_("Select Linear PDF Text"), icons.iconName("select-pdf-text-ht"), TOOL_SELECT_PDF_TEXT_LINEAR),
Entry(_("Select PDF Text In Rectangle"), icons.iconName("select-pdf-text-area"),
TOOL_SELECT_PDF_TEXT_RECT)},
db.getAction(Action::SELECT_TOOL)) {}
| 799
|
C++
|
.cpp
| 14
| 47.857143
| 119
| 0.661125
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,599
|
TooltipToolButton.cpp
|
xournalpp_xournalpp/src/core/gui/toolbarMenubar/TooltipToolButton.cpp
|
#include "TooltipToolButton.h"
#include <utility> // for move
#include <glib.h>
#include <gtk/gtk.h>
#include "util/glib_casts.h"
#include "util/raii/GObjectSPtr.h" // for WidgetSPtr
TooltipToolButton::TooltipToolButton(std::string id, Category cat, Action action, std::string iconName,
std::string description, std::function<std::string()> fetchTooltip):
ToolButton(std::move(id), cat, action, std::move(iconName), std::move(description), false),
fetchTooltip(std::move(fetchTooltip)) {}
auto TooltipToolButton::createItem(bool horizontal) -> xoj::util::WidgetSPtr {
auto item = ToolButton::createItem(horizontal);
gtk_widget_set_has_tooltip(item.get(), true);
auto* cloneFetchTooltip = new std::function<std::string()>(this->fetchTooltip);
g_signal_connect_data(item.get(), "query-tooltip",
G_CALLBACK(+[](GtkWidget*, gint, gint, gboolean, GtkTooltip* tooltip, gpointer d) {
auto fn = static_cast<std::function<std::string()>*>(d);
gtk_tooltip_set_text(tooltip, (*fn)().c_str());
return true;
}),
cloneFetchTooltip, xoj::util::closure_notify_cb<std::function<std::string()>>,
GConnectFlags(0));
return item;
}
| 1,390
|
C++
|
.cpp
| 24
| 45.416667
| 109
| 0.602063
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,600
|
AbstractToolItem.cpp
|
xournalpp_xournalpp/src/core/gui/toolbarMenubar/AbstractToolItem.cpp
|
#include "AbstractToolItem.h"
#include <utility> // for move
AbstractToolItem::AbstractToolItem(std::string id, Category cat): id(std::move(id)), category(cat) {}
AbstractToolItem::~AbstractToolItem() = default;
auto AbstractToolItem::getId() const -> const std::string& { return id; }
auto AbstractToolItem::getCategory() const -> Category { return category; }
xoj::util::WidgetSPtr AbstractToolItem::createToolItem(bool horizontal) {
xoj::util::WidgetSPtr item = createItem(horizontal);
gtk_widget_set_can_focus(item.get(), false); // todo(gtk4) not necessary anymore
if (GTK_IS_TOOL_ITEM(item.get())) {
gtk_widget_show_all(item.get());
return item;
}
// Wrap in a GtkToolItem
GtkToolItem* wrap = gtk_tool_item_new();
gtk_container_add(GTK_CONTAINER(wrap), item.get());
gtk_widget_show_all(GTK_WIDGET(wrap));
return xoj::util::WidgetSPtr(GTK_WIDGET(wrap), xoj::util::adopt);
}
| 939
|
C++
|
.cpp
| 19
| 45.368421
| 101
| 0.708972
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,601
|
AbstractSliderItem.cpp
|
xournalpp_xournalpp/src/core/gui/toolbarMenubar/AbstractSliderItem.cpp
|
#include "AbstractSliderItem.h"
#include <utility> // for move
AbstractSliderItem::AbstractSliderItem(std::string id, Category cat, SliderRange range, ActionRef gAction):
AbstractToolItem(std::move(id), cat), range(range), gAction(std::move(gAction)) {}
| 265
|
C++
|
.cpp
| 4
| 62.75
| 107
| 0.756757
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,602
|
ComboToolButton.cpp
|
xournalpp_xournalpp/src/core/gui/toolbarMenubar/ComboToolButton.cpp
|
#include "ComboToolButton.h"
#include <algorithm> // for find_if
#include <memory> // for shared_ptr
#include <utility> // for move
#include <gtk/gtk.h>
#include "util/GtkUtil.h" // for setToggleButtonUnreleasable
#include "util/glib_casts.h"
#include "util/gtk4_helper.h" // for gtk_popover_new
/// Returns a floating ref
static GtkWidget* createEmptyButton(GSimpleAction* a, const ComboToolButton::Entry& e) {
GtkWidget* btn = gtk_toggle_button_new();
gtk_actionable_set_action_name(GTK_ACTIONABLE(btn), (std::string("win.") + g_action_get_name(G_ACTION(a))).c_str());
gtk_actionable_set_action_target_value(GTK_ACTIONABLE(btn), e.target.get());
xoj::util::gtk::setToggleButtonUnreleasable(GTK_TOGGLE_BUTTON(btn));
gtk_widget_set_tooltip_text(btn, e.name.c_str());
gtk_widget_set_can_focus(btn, false); // todo(gtk4) not necessary anymore
return btn;
}
/// Returns a floating ref
static GtkWidget* createPopoverEntry(GSimpleAction* a, const ComboToolButton::Entry& e) {
GtkWidget* entry = createEmptyButton(a, e);
GtkBox* box = GTK_BOX(gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 6));
gtk_box_append(box, gtk_image_new_from_icon_name(e.icon.c_str(), GTK_ICON_SIZE_SMALL_TOOLBAR));
gtk_box_append(box, gtk_label_new(e.name.c_str()));
gtk_button_set_child(GTK_BUTTON(entry), GTK_WIDGET(box));
return entry;
}
ComboToolButton::ComboToolButton(std::string id, Category cat, std::string iconName, std::string description,
std::vector<Entry> entries, ActionRef gAction):
AbstractToolItem(std::move(id), cat),
entries(std::move(entries)),
gAction(std::move(gAction)),
iconName(std::move(iconName)),
description(std::move(description)) {}
/// Data structure for callbacks
struct ComboToolInstanceData {
GAction* action;
GtkButton* btn;
GtkPopover* popover;
const std::vector<ComboToolButton::Entry>* entries;
};
/// change the prominent icon depending on G_ACTION(a)'s state
static void setProminentIconCallback(GObject* a, GParamSpec*, ComboToolInstanceData* data) {
xoj::util::GVariantSPtr state(g_action_get_state(G_ACTION(a)), xoj::util::adopt);
auto it = std::find_if(data->entries->begin(), data->entries->end(),
[s = state.get()](const auto& e) { return g_variant_equal(e.target.get(), s); });
if (it != data->entries->end()) {
gtk_button_set_icon_name(data->btn, it->icon.c_str());
gtk_widget_set_tooltip_text(GTK_WIDGET(data->btn), it->name.c_str());
gtk_actionable_set_action_target_value(GTK_ACTIONABLE(data->btn), state.get());
gtk_popover_popdown(data->popover);
}
};
auto ComboToolButton::createItem(bool horizontal) -> xoj::util::WidgetSPtr {
auto data = std::make_unique<ComboToolInstanceData>();
data->entries = &this->entries;
data->action = G_ACTION(this->gAction.get());
{ // Create popover
data->popover = GTK_POPOVER(gtk_popover_new());
gtk_widget_add_css_class(GTK_WIDGET(data->popover), "toolbar");
GtkBox* box = GTK_BOX(gtk_box_new(GTK_ORIENTATION_VERTICAL, 0));
gtk_popover_set_child(data->popover, GTK_WIDGET(box));
for (const Entry& t: this->entries) {
gtk_box_append(box, createPopoverEntry(gAction.get(), t));
}
gtk_widget_show_all(GTK_WIDGET(box));
}
{ // Create prominent button
const Entry& e = entries.front(); // Select the first entry by default
data->btn = GTK_BUTTON(createEmptyButton(gAction.get(), e));
gtk_button_set_icon_name(data->btn, e.icon.c_str());
}
// Create item
GtkMenuButton* menubutton = GTK_MENU_BUTTON(gtk_menu_button_new());
gtk_widget_set_can_focus(GTK_WIDGET(menubutton), false); // todo(gtk4) not necessary anymore
gtk_menu_button_set_popover(menubutton, GTK_WIDGET(data->popover));
gtk_menu_button_set_direction(menubutton,
horizontal ? GTK_ARROW_DOWN : GTK_ARROW_RIGHT); // TODO: fix directions
GtkBox* box = GTK_BOX(gtk_box_new(horizontal ? GTK_ORIENTATION_HORIZONTAL : GTK_ORIENTATION_VERTICAL, 0));
gtk_box_append(box, GTK_WIDGET(data->btn));
gtk_box_append(box, GTK_WIDGET(menubutton));
auto item = xoj::util::WidgetSPtr(GTK_WIDGET(box), xoj::util::adopt);
// Set up the prominent button according to the action state
setProminentIconCallback(G_OBJECT(gAction.get()), nullptr, data.get());
g_signal_connect(gAction.get(), "notify::state", xoj::util::wrap_for_g_callback_v<setProminentIconCallback>,
data.get());
// Disconnect the signal and destroy *data if the widget is destroyed
g_object_weak_ref(
G_OBJECT(item.get()),
+[](gpointer d, GObject* item) {
auto* data = static_cast<ComboToolInstanceData*>(d);
g_signal_handlers_disconnect_by_data(data->action, d);
delete data;
},
data.release());
return item;
}
auto ComboToolButton::getToolDisplayName() const -> std::string { return this->description; }
auto ComboToolButton::getNewToolIcon() const -> GtkWidget* {
return gtk_image_new_from_icon_name(iconName.c_str(), GTK_ICON_SIZE_SMALL_TOOLBAR);
}
| 5,336
|
C++
|
.cpp
| 101
| 46.128713
| 120
| 0.664491
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,603
|
ToolButton.cpp
|
xournalpp_xournalpp/src/core/gui/toolbarMenubar/ToolButton.cpp
|
#include "ToolButton.h"
#include <utility> // for move
#include <glib.h>
#include <gtk/gtk.h>
#include "gui/toolbarMenubar/AbstractToolItem.h" // for AbstractToolItem
#include "util/GVariantTemplate.h"
#include "util/GtkUtil.h"
#include "util/gtk4_helper.h"
#include "util/raii/GObjectSPtr.h" // for WidgetSPtr
ToolButton::ToolButton(std::string id, Category cat, Action action, std::string iconName, std::string description,
bool toggle):
AbstractToolItem(std::move(id), cat),
iconName(std::move(iconName)),
description(std::move(description)),
action(action),
toggle(toggle) {}
ToolButton::ToolButton(std::string id, Category cat, Action action, GVariant* target, std::string iconName,
std::string description):
AbstractToolItem(std::move(id), cat),
iconName(std::move(iconName)),
description(std::move(description)),
action(action),
target(target, xoj::util::refsink),
toggle(true) {}
auto ToolButton::createItem(bool horizontal) -> xoj::util::WidgetSPtr {
GtkWidget* btn = toggle ? gtk_toggle_button_new() : gtk_button_new();
gtk_widget_set_can_focus(btn, false); // todo(gtk4) not necessary anymore
gtk_button_set_child(GTK_BUTTON(btn), getNewToolIcon());
gtk_widget_set_tooltip_text(btn, getToolDisplayName().c_str());
gtk_actionable_set_action_name(GTK_ACTIONABLE(btn), (std::string("win.") + Action_toString(action)).c_str());
if (target) {
gtk_actionable_set_action_target_value(GTK_ACTIONABLE(btn), target.get());
xoj::util::gtk::setToggleButtonUnreleasable(GTK_TOGGLE_BUTTON(btn));
}
// For the sake of deprecated GtkToolbar, wrap the button in a GtkToolItem
// Todo(gtk4): remove
GtkToolItem* it = gtk_tool_item_new();
if (popoverFactory) {
GtkMenuButton* menubutton = GTK_MENU_BUTTON(gtk_menu_button_new());
gtk_widget_set_can_focus(GTK_WIDGET(menubutton), false); // todo(gtk4) not necessary anymore
gtk_menu_button_set_popover(menubutton, popoverFactory->createPopover());
gtk_menu_button_set_direction(menubutton, GTK_ARROW_DOWN);
GtkBox* box = GTK_BOX(gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 0));
gtk_box_append(box, btn);
gtk_box_append(box, GTK_WIDGET(menubutton));
gtk_container_add(GTK_CONTAINER(it), GTK_WIDGET(box));
g_signal_connect_object(it, "toolbar-reconfigured", G_CALLBACK(+[](GtkToolItem* it, gpointer box) {
gtk_orientable_set_orientation(GTK_ORIENTABLE(box),
gtk_tool_item_get_orientation(it));
}),
box, GConnectFlags(0));
g_signal_connect_object(it, "toolbar-reconfigured", G_CALLBACK(+[](GtkToolItem* it, gpointer btn) {
const bool h = gtk_tool_item_get_orientation(it) == GTK_ORIENTATION_HORIZONTAL;
gtk_menu_button_set_direction(GTK_MENU_BUTTON(btn),
h ? GTK_ARROW_DOWN : GTK_ARROW_RIGHT);
if (!gtk_menu_button_get_popover(GTK_MENU_BUTTON(btn))) {
printf("no popover in callback\n");
}
}),
menubutton, GConnectFlags(0));
} else {
gtk_container_add(GTK_CONTAINER(it), GTK_WIDGET(btn));
}
/// Makes a proxy item for the toolbar's overflow menu
auto createProxy = [this]() {
GtkWidget* proxy;
if (toggle) {
proxy = gtk_check_menu_item_new();
if (target) {
gtk_check_menu_item_set_draw_as_radio(GTK_CHECK_MENU_ITEM(proxy), true);
}
} else {
proxy = gtk_menu_item_new();
}
auto* box = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 6);
gtk_container_add(GTK_CONTAINER(proxy), box);
gtk_box_append(GTK_BOX(box), getNewToolIcon());
gtk_box_append(GTK_BOX(box), gtk_label_new(getToolDisplayName().c_str()));
gtk_actionable_set_action_name(GTK_ACTIONABLE(proxy), (std::string("win.") + Action_toString(action)).c_str());
if (target) {
gtk_actionable_set_action_target_value(GTK_ACTIONABLE(proxy), target.get());
}
xoj::util::gtk::fixActionableInitialSensitivity(GTK_ACTIONABLE(proxy));
return proxy;
};
gtk_tool_item_set_proxy_menu_item(it, "", createProxy());
return xoj::util::WidgetSPtr(GTK_WIDGET(it), xoj::util::adopt);
}
auto ToolButton::getToolDisplayName() const -> std::string { return description; }
auto ToolButton::getNewToolIcon() const -> GtkWidget* {
return gtk_image_new_from_icon_name(iconName.c_str(), GTK_ICON_SIZE_LARGE_TOOLBAR);
}
void ToolButton::setPopoverFactory(const PopoverFactory* factory) { popoverFactory = factory; }
| 5,067
|
C++
|
.cpp
| 93
| 42.806452
| 119
| 0.608354
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,604
|
ToolPageLayer.cpp
|
xournalpp_xournalpp/src/core/gui/toolbarMenubar/ToolPageLayer.cpp
|
#include "ToolPageLayer.h"
#include <utility> // for move
#include <glib-object.h> // for G_CALLBACK, g_signa...
#include <glib.h> // for g_warning
#include <pango/pango.h> // for pango_attr_list_insert
#include "control/layer/LayerController.h" // for LayerController
#include "enums/Action.enum.h" // for Action
#include "gui/IconNameHelper.h" // for IconNameHelper
#include "gui/toolbarMenubar/AbstractToolItem.h" // for AbstractToolItem
#include "model/PageRef.h" // for PageRef
#include "model/XojPage.h" // for XojPage
#include "util/GtkUtil.h" // for setRadioButtonActionName
#include "util/glib_casts.h" // for closure_notify_cb
#include "util/gtk4_helper.h" // for gtk_box_append
#include "util/i18n.h" // for _
#include "util/raii/PangoSPtr.h" // for PangoAttrListSPtr
class ShowLayerEntry final {
public:
ShowLayerEntry(LayerController* lc, Layer::Index id) noexcept;
ShowLayerEntry(const ShowLayerEntry&) = delete; // No copies, otherwise we'll get an issue with the signals
ShowLayerEntry& operator=(const ShowLayerEntry&) = delete;
ShowLayerEntry(ShowLayerEntry&& e) noexcept;
ShowLayerEntry& operator=(ShowLayerEntry&&) noexcept;
~ShowLayerEntry() noexcept;
GtkWidget* checkButton;
gulong callbackHandler;
};
ShowLayerEntry::ShowLayerEntry(LayerController* lc, Layer::Index id) noexcept: checkButton(gtk_check_button_new()) {
gtk_widget_set_can_focus(checkButton, false); // todo(gtk4) not necessary anymore
struct Data {
LayerController* lc;
Layer::Index id;
};
this->callbackHandler =
g_signal_connect_data(checkButton, "toggled", G_CALLBACK(+[](GtkToggleButton* btn, gpointer data) {
Data* d = reinterpret_cast<Data*>(data);
d->lc->setLayerVisible(d->id, gtk_toggle_button_get_active(btn));
}),
new Data{lc, id}, xoj::util::closure_notify_cb<Data>, GConnectFlags(0));
gtk_widget_set_margin_end(checkButton, 4);
}
ShowLayerEntry::ShowLayerEntry(ShowLayerEntry&& e) noexcept:
checkButton(std::move(e.checkButton)), callbackHandler(std::exchange(e.callbackHandler, 0U)) {}
auto ShowLayerEntry::operator=(ShowLayerEntry&& e) noexcept -> ShowLayerEntry& {
checkButton = std::move(e.checkButton);
callbackHandler = std::exchange(e.callbackHandler, 0U);
return *this;
}
ShowLayerEntry::~ShowLayerEntry() noexcept = default;
/// @return The GtkWidget* is a floating ref
static std::tuple<GtkWidget*, std::vector<ShowLayerEntry>, std::vector<std::pair<GtkWidget*, gulong>>> createGrid(
LayerController* lc, GtkPopover* popover) {
#if GTK_MAJOR_VERSION == 3
GtkRadioButton* group = nullptr;
auto createLayerRadioButton = [&group, popover](const std::string& layerName,
Layer::Index id) -> std::pair<GtkWidget*, gulong> {
GtkWidget* btn = gtk_radio_button_new_with_label_from_widget(group, layerName.c_str());
gtk_widget_set_can_focus(btn, false);
group = GTK_RADIO_BUTTON(btn);
gtk_actionable_set_action_target_value(GTK_ACTIONABLE(btn), xoj::util::makeGVariantSPtr(id).get());
/**
* RadioButton's and GAction don't work as expected in GTK3
* To circumvent this, we have our own GAction/RadioButton interactions
*/
xoj::util::gtk::setRadioButtonActionName(GTK_RADIO_BUTTON(btn), "win", Action_toString(Action::LAYER_ACTIVE));
// Callback to hide the popover when a new layer is selected
auto sig = g_signal_connect_object(btn, "toggled", G_CALLBACK(+[](GtkToggleButton*, gpointer popover) {
gtk_popover_popdown(GTK_POPOVER(popover));
}),
popover, GConnectFlags(0));
// Block this callback for now, otherwise it is called when the grid is added to the popover
g_signal_handler_block(btn, sig);
return {btn, sig};
};
auto createBackgroundRadioButton = [](LayerController* lc) {
GtkWidget* btn = gtk_radio_button_new_with_label(nullptr, lc->getLayerNameById(0U).c_str());
gtk_widget_set_can_focus(btn, false);
gtk_widget_add_css_class(btn, "invisible");
gtk_widget_set_hexpand(btn, true);
return btn;
};
#else // GTK4
std::string actionName = std::string("win.") + Action_toString(Action::LAYER_ACTIVE); // Todo(cpp20) constexpr
GtkCheckButton* group = nullptr;
auto createLayerRadioButton = [&actionName, &group, popover](const std::string& layerName,
Layer::Index id) -> std::pair<GtkWidget*, gulong> {
GtkWidget* btn = gtk_check_button_new_with_label(layerName.c_str());
// Is grouping necessary here? The GTK4 doc is unclear
gtk_check_button_set_group(GTK_CHECK_BUTTON(btn), std::exchange(group, GTK_CHECK_BUTTON(btn));
gtk_actionable_set_action_name(GTK_ACTIONABLE(btn), actionName.c_str());
gtk_actionable_set_action_target_value(GTK_ACTIONABLE(btn), xoj::util::makeGVariantSPtr(id).get());
// Callback to hide the popover when a new layer is selected
auto sig = g_signal_connect_object(btn, "toggled", G_CALLBACK(+[](GtkToggleButton*, gpointer popover) {
gtk_popover_popdown(GTK_POPOVER(popover)); }), popover, GConnectFlags(0));
// Block this callback for now, otherwise it is called when the grid is added to the popover
g_signal_handler_block(btn, sig);
return {btn, sig};
};
auto createBackgroundRadioButton = [](LayerController* lc) {
GtkWidget* btn = gtk_check_button_new_with_label(lc->getLayerNameById(0U).c_str());
// Todo(gtk4): adapt the css class
gtk_widget_add_css_class(btn, "invisible");
gtk_widget_set_hexpand(btn, true);
return btn;
};
#endif
GtkGrid* grid = GTK_GRID(gtk_grid_new());
auto layerCount = lc->getLayerCount();
std::vector<ShowLayerEntry> entries;
entries.reserve(layerCount + 1);
std::vector<std::pair<GtkWidget*, gulong>> radioButtons;
radioButtons.reserve(layerCount);
// Handle the background separately, as it cannot be selected
gtk_grid_attach(grid, createBackgroundRadioButton(lc), 0, static_cast<int>(layerCount), 1, 1);
gtk_grid_attach(grid, entries.emplace_back(lc, 0).checkButton, 1, static_cast<int>(layerCount), 1, 1);
// Then the other layers
for (Layer::Index id = 1; id <= layerCount; id++) {
int y = static_cast<int>(layerCount - id);
auto [btn, _] = radioButtons.emplace_back(createLayerRadioButton(lc->getLayerNameById(id), id));
gtk_grid_attach(grid, btn, 0, y, 1, 1);
gtk_grid_attach(grid, entries.emplace_back(lc, id).checkButton, 1, y, 1, 1);
}
gtk_widget_show_all(GTK_WIDGET(grid));
return {GTK_WIDGET(grid), std::move(entries), std::move(radioButtons)};
}
/// @return floating ref
static GtkLabel* makeLabel() {
auto* label = GTK_LABEL(gtk_label_new(_("Loading...")));
xoj::util::PangoAttrListSPtr attrs(pango_attr_list_new(), xoj::util::adopt);
pango_attr_list_insert(attrs.get(), pango_attr_weight_new(PANGO_WEIGHT_BOLD));
gtk_label_set_attributes(label, attrs.get());
return label;
}
/// @brief Appends to `box` a button with bold label `name` activating the Action `action`
static void addSpecialButton(GtkBox* box, const std::string& name, Action action) {
GtkWidget* btn = gtk_button_new();
gtk_widget_set_can_focus(btn, false); // todo(gtk4) not necessary anymore
GtkWidget* lb = gtk_label_new(name.c_str());
gtk_widget_set_halign(lb, GTK_ALIGN_START);
xoj::util::PangoAttrListSPtr attrs(pango_attr_list_new(), xoj::util::adopt);
pango_attr_list_insert(attrs.get(), pango_attr_weight_new(PANGO_WEIGHT_BOLD));
gtk_label_set_attributes(GTK_LABEL(lb), attrs.get());
gtk_button_set_child(GTK_BUTTON(btn), lb);
std::string fullActionName = std::string("win.") + Action_toString(action);
gtk_actionable_set_action_name(GTK_ACTIONABLE(btn), fullActionName.c_str());
gtk_box_append(box, btn);
}
/// @return floating ref
static GtkBox* makePopoverContent() {
GtkBox* box = GTK_BOX(gtk_box_new(GTK_ORIENTATION_VERTICAL, 0));
addSpecialButton(box, _("Show all"), Action::LAYER_SHOW_ALL);
addSpecialButton(box, _("Hide all"), Action::LAYER_HIDE_ALL);
gtk_box_append(box, gtk_separator_new(GTK_ORIENTATION_HORIZONTAL));
addSpecialButton(box, _("Create new layer"), Action::LAYER_NEW);
gtk_box_append(box, gtk_separator_new(GTK_ORIENTATION_HORIZONTAL));
gtk_widget_show_all(GTK_WIDGET(box));
return box;
}
/// @return floating ref
static GtkPopover* makePopover(GtkBox* content) {
auto popover = GTK_POPOVER(gtk_popover_new());
gtk_widget_add_css_class(GTK_WIDGET(popover), "toolbar");
gtk_popover_set_child(popover, GTK_WIDGET(content));
return popover;
}
class InstanceData: public LayerCtrlListener {
public:
InstanceData(LayerController* lc):
lc(lc),
label(makeLabel()),
popoverBox(makePopoverContent()),
popover(makePopover(popoverBox)),
grid(nullptr) {}
~InstanceData() = default;
xoj::util::WidgetSPtr makeWidget(bool horizontal) {
xoj::util::WidgetSPtr item(gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 1), xoj::util::adopt);
GtkBox* hbox = GTK_BOX(item.get());
GtkWidget* lbl = gtk_label_new(_("Layer"));
gtk_widget_set_margin_start(lbl, 7);
gtk_widget_set_margin_end(lbl, 7);
gtk_box_append(hbox, lbl);
GtkWidget* menuButton = gtk_menu_button_new();
#if GTK_MAJOR_VERSION == 3
gtk_widget_set_can_focus(menuButton, false);
gtk_box_append(hbox, GTK_WIDGET(this->label));
#else
gtk_menu_button_set_child(GTK_MENU_BUTTON(menuButton), GTK_WIDGET(this->label));
gtk_menu_button_set_always_show_arrow(GTK_MENU_BUTTON(menuButton), true);
#endif
gtk_box_append(hbox, menuButton);
// TODO: fix orientation
gtk_menu_button_set_direction(GTK_MENU_BUTTON(menuButton), horizontal ? GTK_ARROW_DOWN : GTK_ARROW_RIGHT);
gtk_menu_button_set_popover(GTK_MENU_BUTTON(menuButton), GTK_WIDGET(this->popover));
LayerCtrlListener::registerListener(lc);
// *this is destroyed once the widget (hence *popover) has been destroyed. No need to disconnect those signals
g_signal_connect(popover, "show", xoj::util::wrap_for_g_callback_v<popoverShown>, this);
g_signal_connect(popover, "hide", xoj::util::wrap_for_g_callback_v<popoverHidden>, this);
updateSelectedLayer();
return item;
}
static void popoverShown(GtkWidget*, InstanceData* data) {
xoj_assert(!data->grid && data->showLayerItems.empty());
data->setupLayersGrid();
}
static void popoverHidden(GtkWidget*, InstanceData* data) {
if (data->grid) {
data->showLayerItems.clear();
gtk_box_remove(data->popoverBox, data->grid);
data->grid = nullptr;
}
}
private:
void setupLayersGrid() {
auto [grid, entries, radioButtons] = createGrid(lc, popover);
this->grid = grid;
gtk_box_append(this->popoverBox, grid);
this->showLayerItems = std::move(entries);
for (auto [btn, sig]: radioButtons) {
g_signal_handler_unblock(btn, sig);
}
layerVisibilityChanged();
}
void rebuildLayerMenu() override {
if (grid) {
// Only rebuild if the popover is shown
showLayerItems.clear();
gtk_box_remove(popoverBox, grid);
grid = nullptr;
setupLayersGrid();
}
updateSelectedLayer();
}
void layerVisibilityChanged() override {
PageRef page = lc->getCurrentPage();
if (page) {
Layer::Index n = 0;
for (auto& e: showLayerItems) {
g_signal_handler_block(e.checkButton, e.callbackHandler);
gtk_check_button_set_active(GTK_CHECK_BUTTON(e.checkButton), page->isLayerVisible(n++));
g_signal_handler_unblock(e.checkButton, e.callbackHandler);
}
}
}
void updateSelectedLayer() override { gtk_label_set_text(label, lc->getCurrentLayerName().c_str()); }
private:
LayerController* lc;
GtkLabel* label;
GtkBox* popoverBox;
GtkPopover* popover;
GtkWidget* grid;
std::vector<ShowLayerEntry> showLayerItems; ///< Widgets for the layer menu. Index = 0 is for background.
};
ToolPageLayer::ToolPageLayer(std::string id, LayerController* lc, IconNameHelper iconNameHelper):
AbstractToolItem(std::move(id), Category::NAVIGATION),
lc(lc),
iconName(iconNameHelper.iconName("combo-layer")) {}
ToolPageLayer::~ToolPageLayer() = default;
auto ToolPageLayer::getToolDisplayName() const -> std::string { return _("Layer Combo"); }
auto ToolPageLayer::getNewToolIcon() const -> GtkWidget* {
return gtk_image_new_from_icon_name(this->iconName.c_str(), GTK_ICON_SIZE_SMALL_TOOLBAR);
}
auto ToolPageLayer::createItem(bool horizontal) -> xoj::util::WidgetSPtr {
auto data = std::make_unique<InstanceData>(lc);
auto item = data->makeWidget(horizontal);
// Destroy *data if the widget is destroyed
g_object_weak_ref(
G_OBJECT(item.get()), +[](gpointer d, GObject*) { delete static_cast<InstanceData*>(d); }, data.release());
return item;
}
| 13,872
|
C++
|
.cpp
| 269
| 43.947955
| 119
| 0.652084
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,605
|
StylePopoverFactory.cpp
|
xournalpp_xournalpp/src/core/gui/toolbarMenubar/StylePopoverFactory.cpp
|
#include "StylePopoverFactory.h"
#include <utility> // for move
#include <glib.h>
#include <gtk/gtk.h>
#include "util/GtkUtil.h"
#include "util/gtk4_helper.h"
StylePopoverFactory::StylePopoverFactory(Action styleAction, std::vector<Entry> entries):
entries(std::move(entries)), styleAction(styleAction) {}
GtkWidget* StylePopoverFactory::createPopover() const {
GtkWidget* popover = gtk_popover_new();
GtkWidget* box = gtk_box_new(GTK_ORIENTATION_VERTICAL, 0);
gtk_popover_set_child(GTK_POPOVER(popover), box);
#if GTK_MAJOR_VERSION == 3
GtkRadioButton* group = nullptr;
const char* actionName = Action_toString(styleAction);
auto appendItem = [&](const StylePopoverFactory::Entry& e) {
GtkWidget* btn = gtk_radio_button_new_from_widget(group);
group = GTK_RADIO_BUTTON(btn);
xoj::util::gtk::setRadioButtonActionName(GTK_RADIO_BUTTON(btn), "win", actionName);
g_signal_connect_object(btn, "clicked", G_CALLBACK(+[](GtkButton*, gpointer popover) {
gtk_popover_popdown(GTK_POPOVER(popover));
}),
popover, GConnectFlags(0));
#else
GtkCheckButton* group = nullptr;
std::string actionName = std::string("win.") + Action_toString(Action::TOOL_PEN_LINE_STYLE);
auto appendLineStyleItem = [&](const char* label, const char* target, const char* icon) {
GtkWidget* btn = gtk_check_button_new_with_label(layerName.c_str());
// Is grouping necessary here? The GTK4 doc is unclear
gtk_check_button_set_group(GTK_CHECK_BUTTON(btn), std::exchange(group, GTK_CHECK_BUTTON(btn));
gtk_actionable_set_action_name(GTK_ACTIONABLE(btn), actionName.c_str());
g_signal_connect_object(btn, "toggled", G_CALLBACK(+[](GtkCheckButton*, gpointer popover){
gtk_popover_popdown(GTK_POPOVER(popover));}), popover, GConnectFlags(0));
#endif
gtk_actionable_set_action_target_value(GTK_ACTIONABLE(btn), e.target.get());
if (!e.icon.empty()) {
GtkWidget* hbox = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 5);
gtk_box_append(GTK_BOX(hbox), gtk_image_new_from_icon_name(e.icon.c_str(), GTK_ICON_SIZE_LARGE_TOOLBAR));
gtk_box_append(GTK_BOX(hbox), gtk_label_new(e.name.c_str()));
gtk_button_set_child(GTK_BUTTON(btn), hbox);
} else {
gtk_button_set_label(GTK_BUTTON(btn), e.name.c_str());
}
gtk_box_append(GTK_BOX(box), btn);
};
for (const auto& e: entries) {
appendItem(e);
}
gtk_widget_show_all(box);
return popover;
}
| 2,645
|
C++
|
.cpp
| 51
| 43.705882
| 117
| 0.65029
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,606
|
ToolMenuHandler.cpp
|
xournalpp_xournalpp/src/core/gui/toolbarMenubar/ToolMenuHandler.cpp
|
#include "ToolMenuHandler.h"
#include <algorithm> // for max
#include <sstream> // for istringstream
#include "control/Control.h" // for Control
#include "control/ScrollHandler.h" // for ScrollHandler
#include "control/actions/ActionDatabase.h" // for ActionDatabase
#include "control/settings/Settings.h" // for Settings
#include "gui/GladeGui.h" // for GladeGui
#include "gui/GladeSearchpath.h"
#include "gui/ToolitemDragDrop.h" // for ToolitemDragDrop
#include "gui/menus/popoverMenus/PageTypeSelectionPopover.h"
#include "gui/toolbarMenubar/model/ColorPalette.h" // for Palette
#include "gui/toolbarMenubar/model/ToolbarData.h" // for ToolbarData
#include "gui/toolbarMenubar/model/ToolbarEntry.h" // for ToolbarEntry
#include "gui/toolbarMenubar/model/ToolbarItem.h" // for ToolbarItem
#include "gui/toolbarMenubar/model/ToolbarModel.h" // for ToolbarModel
#include "plugin/Plugin.h" // for ToolbarButtonEntr<
#include "util/GVariantTemplate.h" // for gVariantType
#include "util/GtkUtil.h"
#include "util/NamedColor.h" // for NamedColor
#include "util/PathUtil.h"
#include "util/StringUtils.h" // for StringUtils
#include "util/XojMsgBox.h"
#include "util/gtk4_helper.h"
#include "util/i18n.h" // for _
#include "AbstractToolItem.h" // for AbstractToolItem
#include "ColorSelectorToolItem.h" // for ColorSelectorToolItem
#include "ColorToolItem.h" // for ColorToolItem
#include "DrawingTypeComboToolButton.h" // for DrawingTypeComboToolButton
#include "FontButton.h" // for FontButton
#include "PluginToolButton.h" // for PluginToolButton
#include "StylePopoverFactory.h" // for ToolButtonWithStylePopover
#include "ToolButton.h" // for ToolButton
#include "ToolPageLayer.h" // for ToolPageLayer
#include "ToolPageSpinner.h" // for ToolPageSpinner
#include "ToolPdfCombocontrol.h" // for ToolPdfCombocontrol
#include "ToolSelectCombocontrol.h" // for ToolSelectComboc...
#include "ToolZoomSlider.h" // for ToolZoomSlider
#include "TooltipToolButton.h" // for TooltipToolButton
#include "config-dev.h" // for TOOLBAR_CONFIG
#include "config-features.h" // for ENABLE_PLUGINS
#include "filesystem.h" // for exists
using std::string;
ToolMenuHandler::ToolMenuHandler(Control* control, GladeGui* gui):
parent(GTK_WINDOW(gui->getWindow())),
control(control),
zoom(control->getZoomControl()),
gui(gui),
toolHandler(control->getToolHandler()),
tbModel(std::make_unique<ToolbarModel>()),
pageBackgroundChangeController(control->getPageBackgroundChangeController()),
iconNameHelper(control->getSettings()),
pageTypeSelectionPopup(std::make_unique<PageTypeSelectionPopover>(
control->getPageTypes(), control->getPageBackgroundChangeController(), control->getSettings(),
GTK_APPLICATION_WINDOW(parent))) {}
void ToolMenuHandler::populate(const GladeSearchpath* gladeSearchPath) {
initToolItems();
auto file = gladeSearchPath->findFile("", "toolbar.ini");
if (!tbModel->parse(file, true, this->control->getPalette())) {
std::string msg = FS(_F("Could not parse general toolbar.ini file: {1}\n"
"No Toolbars will be available") %
file.u8string());
XojMsgBox::showErrorToUser(control->getGtkWindow(), msg);
}
file = Util::getConfigFile(TOOLBAR_CONFIG);
if (fs::exists(file)) {
if (!tbModel->parse(file, false, this->control->getPalette())) {
string msg = FS(_F("Could not parse custom toolbar.ini file: {1}\n"
"Toolbars will not be available") %
file.u8string());
XojMsgBox::showErrorToUser(control->getGtkWindow(), msg);
}
}
}
ToolMenuHandler::~ToolMenuHandler() = default;
void ToolMenuHandler::freeDynamicToolbarItems() { this->toolbarColorItems.clear(); }
void ToolMenuHandler::unloadToolbar(GtkWidget* toolbar) {
for (int i = gtk_toolbar_get_n_items(GTK_TOOLBAR(toolbar)) - 1; i >= 0; i--) {
GtkToolItem* tbItem = gtk_toolbar_get_nth_item(GTK_TOOLBAR(toolbar), i);
gtk_container_remove(GTK_CONTAINER(toolbar), GTK_WIDGET(tbItem));
}
gtk_widget_hide(toolbar);
}
void ToolMenuHandler::load(const ToolbarData* d, GtkWidget* toolbar, const char* toolbarName, bool horizontal) {
int count = 0;
const auto palette = this->control->getPalette();
for (const ToolbarEntry& e: d->contents) {
if (e.getName() == toolbarName) {
for (const ToolbarItem& dataItem: e.getItems()) {
std::string name = dataItem.getName();
if (!this->control->getAudioController() &&
(name == "AUDIO_RECORDING" || name == "AUDIO_SEEK_BACKWARDS" || name == "AUDIO_PAUSE_PLAYBACK" ||
name == "AUDIO_STOP_PLAYBACK" || name == "AUDIO_SEEK_FORWARDS" || name == "PLAY_OBJECT")) {
continue;
}
if (name == "SEPARATOR") {
GtkToolItem* it = gtk_separator_tool_item_new();
gtk_widget_show(GTK_WIDGET(it));
gtk_toolbar_insert(GTK_TOOLBAR(toolbar), it, -1);
ToolitemDragDrop::attachMetadata(GTK_WIDGET(it), dataItem.getId(), TOOL_ITEM_SEPARATOR);
continue;
}
if (name == "SPACER") {
GtkToolItem* toolItem = gtk_separator_tool_item_new();
gtk_separator_tool_item_set_draw(GTK_SEPARATOR_TOOL_ITEM(toolItem), false);
gtk_tool_item_set_expand(toolItem, true);
gtk_widget_show(GTK_WIDGET(toolItem));
gtk_toolbar_insert(GTK_TOOLBAR(toolbar), toolItem, -1);
ToolitemDragDrop::attachMetadata(GTK_WIDGET(toolItem), dataItem.getId(), TOOL_ITEM_SPACER);
continue;
}
if (StringUtils::startsWith(name, "COLOR(") && StringUtils::endsWith(name, ")")) {
std::string arg = name.substr(6, name.length() - 7);
size_t paletteIndex{};
std::istringstream colorStream(arg);
colorStream >> paletteIndex;
if (!colorStream.eof() || colorStream.fail()) {
g_warning("Toolbar:COLOR(N) has wrong format: %s", arg.c_str());
continue;
}
count++;
const NamedColor& namedColor = palette.getColorAt(paletteIndex);
auto& item = this->toolbarColorItems.emplace_back(std::make_unique<ColorToolItem>(namedColor));
auto it = item->createToolItem(horizontal);
gtk_toolbar_insert(GTK_TOOLBAR(toolbar), GTK_TOOL_ITEM(it.get()), -1);
ToolitemDragDrop::attachMetadataColor(it.get(), dataItem.getId(), paletteIndex, item.get());
continue;
}
bool found = false;
for (auto& item: this->toolItems) {
if (name == item->getId()) {
count++;
auto it = item->createToolItem(horizontal);
gtk_toolbar_insert(GTK_TOOLBAR(toolbar), GTK_TOOL_ITEM(it.get()), -1);
ToolitemDragDrop::attachMetadata(it.get(), dataItem.getId(), item.get());
found = true;
break;
}
}
if (!found) {
g_warning("Toolbar item \"%s\" not found!", name.c_str());
}
}
break;
}
}
if (count == 0) {
gtk_widget_hide(toolbar);
} else {
gtk_widget_show(toolbar);
}
}
void ToolMenuHandler::removeColorToolItem(AbstractToolItem* it) {
g_return_if_fail(it != nullptr);
this->toolbarColorItems.erase(std::find_if(this->toolbarColorItems.begin(), this->toolbarColorItems.end(),
[it](const auto& p) { return p.get() == it; }));
}
void ToolMenuHandler::addColorToolItem(std::unique_ptr<ColorToolItem> it) {
g_return_if_fail(it != nullptr);
this->toolbarColorItems.emplace_back(std::move(it));
}
template <class tool_item, class... Args>
tool_item& ToolMenuHandler::emplaceItem(Args&&... args) {
return static_cast<tool_item&>(*toolItems.emplace_back(std::make_unique<tool_item>(std::forward<Args>(args)...)));
}
#ifdef ENABLE_PLUGINS
void ToolMenuHandler::addPluginItem(ToolbarButtonEntry* t) { emplaceItem<PluginToolButton>(t); }
#endif /* ENABLE_PLUGINS */
void ToolMenuHandler::initToolItems() {
using Cat = AbstractToolItem::Category;
/**
* @brief Simple button, with a GTK stock icon name
* The corresponding action in ActionDatabase[action] should have no state (it can have a parameter)
**/
auto emplaceStockItem = [this](const char* name, Cat c, Action action, const char* icon, std::string description) {
emplaceItem<ToolButton>(name, c, action, icon, description, false);
};
/**
* @brief Simple button, with a custom loaded icon
* The corresponding action in ActionDatabase[action] should have no state (it can have a parameter)
**/
auto emplaceCustomItem = [this](const char* name, Cat c, Action action, const char* icon, std::string description) {
emplaceItem<ToolButton>(name, c, action, iconName(icon), description, false);
};
/**
* @brief Toggle button, with a GTK stock icon name
* The corresponding action in ActionDatabase[action] should have a boolean state and no parameter
**/
auto emplaceStockItemTgl = [this](const char* name, Cat c, Action action, const char* icon,
std::string description) {
emplaceItem<ToolButton>(name, c, action, icon, description, true);
};
/**
* @brief Toggle button, with a custom loaded icon
* The corresponding action in ActionDatabase[action] should have a boolean state and no parameter
**/
auto emplaceCustomItemTgl = [this](const char* name, Cat c, Action action, const char* icon,
std::string description) {
emplaceItem<ToolButton>(name, c, action, iconName(icon), description, true);
};
/**
* @brief Toggle button linked to others sharing the same action (with a custom loaded icon)
* The corresponding action in ActionDatabase[action] should have a state and a parameter. The button is "on"
*when the action state matches `target`.
**/
auto emplaceCustomItemWithTarget = [this](const char* name, Cat c, Action action, auto target, const char* icon,
std::string description) {
emplaceItem<ToolButton>(name, c, action, makeGVariant(target), iconName(icon), description);
};
/**
* @brief Simple button (with a custom loaded icon), with a popover menu to change parameters of the tool
* The corresponding action in ActionDatabase[action] should have no state (it can have a parameter)
**/
auto emplaceCustomItemWithPopover = [this](const char* name, Cat c, Action action, const char* icon,
std::string description, const PopoverFactory* popover) {
auto&& tb = emplaceItem<ToolButton>(name, c, action, iconName(icon), description, false);
tb.setPopoverFactory(popover);
};
auto emplaceCustomItemWithTargetAndMenu = [this](const char* name, Cat c, Action action, auto target,
const char* icon, std::string description,
const PopoverFactory* popover) {
auto&& tb = emplaceItem<ToolButton>(name, c, action, makeGVariant(target), iconName(icon), description);
tb.setPopoverFactory(popover);
};
/*
* Items ordered by menu, if possible.
* There are some entries which are not available in the menu, like the Zoom slider
* All menu items without tool icon are not listed here - they are connected by ActionDatabase
*/
/*
* Menu File
* ------------------------------------------------------------------------
*/
emplaceCustomItem("NEW", Cat::FILES, Action::NEW_FILE, "document-new", _("New Xournal"));
emplaceCustomItem("OPEN", Cat::FILES, Action::OPEN, "document-open", _("Open file"));
emplaceCustomItem("SAVE", Cat::FILES, Action::SAVE, "document-save", _("Save"));
emplaceCustomItem("SAVEPDF", Cat::FILES, Action::EXPORT_AS_PDF, "document-export-pdf", _("Export as PDF"));
emplaceCustomItem("PRINT", Cat::FILES, Action::PRINT, "document-print", _("Print"));
/*
* Menu Edit
* ------------------------------------------------------------------------
*/
// Undo / Redo Texts are updated
emplaceItem<TooltipToolButton>(
"UNDO", Cat::MISC, Action::UNDO, iconName("edit-undo"), _("Undo"),
[undoredo = control->getUndoRedoHandler()]() { return undoredo->undoDescription(); });
emplaceItem<TooltipToolButton>(
"REDO", Cat::MISC, Action::REDO, iconName("edit-redo"), _("Redo"),
[undoredo = control->getUndoRedoHandler()]() { return undoredo->redoDescription(); });
emplaceCustomItem("CUT", Cat::MISC, Action::CUT, "edit-cut", _("Cut"));
emplaceCustomItem("COPY", Cat::MISC, Action::COPY, "edit-copy", _("Copy"));
emplaceCustomItem("PASTE", Cat::MISC, Action::PASTE, "edit-paste", _("Paste"));
emplaceStockItem("SEARCH", Cat::MISC, Action::SEARCH, "edit-find", _("Search"));
emplaceStockItem("DELETE", Cat::MISC, Action::DELETE, "edit-delete", _("Delete"));
emplaceCustomItemTgl("ROTATION_SNAPPING", Cat::MISC, Action::ROTATION_SNAPPING, "snapping-rotation",
_("Rotation Snapping"));
emplaceCustomItemTgl("GRID_SNAPPING", Cat::MISC, Action::GRID_SNAPPING, "snapping-grid", _("Grid Snapping"));
/*
* Menu View
* ------------------------------------------------------------------------
*/
emplaceCustomItemTgl("PAIRED_PAGES", Cat::NAVIGATION, Action::PAIRED_PAGES_MODE, "show-paired-pages",
_("Paired pages"));
emplaceCustomItemTgl("PRESENTATION_MODE", Cat::NAVIGATION, Action::PRESENTATION_MODE, "presentation-mode",
_("Presentation mode"));
emplaceCustomItemTgl("FULLSCREEN", Cat::NAVIGATION, Action::FULLSCREEN, "fullscreen", _("Toggle fullscreen"));
emplaceCustomItem("MANAGE_TOOLBAR", Cat::MISC, Action::MANAGE_TOOLBAR, "toolbars-manage", _("Manage Toolbars"));
emplaceCustomItem("CUSTOMIZE_TOOLBAR", Cat::MISC, Action::CUSTOMIZE_TOOLBAR, "toolbars-customize",
_("Customize Toolbars"));
emplaceStockItem("ZOOM_OUT", Cat::NAVIGATION, Action::ZOOM_OUT, "zoom-out", _("Zoom out"));
emplaceStockItem("ZOOM_IN", Cat::NAVIGATION, Action::ZOOM_IN, "zoom-in", _("Zoom in"));
emplaceStockItemTgl("ZOOM_FIT", Cat::NAVIGATION, Action::ZOOM_FIT, "zoom-fit-best", _("Zoom fit to screen"));
emplaceStockItem("ZOOM_100", Cat::NAVIGATION, Action::ZOOM_100, "zoom-original", _("Zoom to 100%"));
/*
* Menu Navigation
* ------------------------------------------------------------------------
*/
emplaceStockItem("GOTO_FIRST", Cat::NAVIGATION, Action::GOTO_FIRST, "go-first", _("Go to first page"));
emplaceStockItem("GOTO_BACK", Cat::NAVIGATION, Action::GOTO_PREVIOUS, "go-previous", _("Back"));
emplaceCustomItem("GOTO_PAGE", Cat::NAVIGATION, Action::GOTO_PAGE, "go-to", _("Go to page"));
emplaceStockItem("GOTO_NEXT", Cat::NAVIGATION, Action::GOTO_NEXT, "go-next", _("Next"));
emplaceStockItem("GOTO_LAST", Cat::NAVIGATION, Action::GOTO_LAST, "go-last", _("Go to last page"));
emplaceStockItem("GOTO_PREVIOUS_LAYER", Cat::NAVIGATION, Action::LAYER_GOTO_PREVIOUS, "go-previous",
_("Go to previous layer"));
emplaceStockItem("GOTO_NEXT_LAYER", Cat::NAVIGATION, Action::LAYER_GOTO_NEXT, "go-next", _("Go to next layer"));
emplaceStockItem("GOTO_TOP_LAYER", Cat::NAVIGATION, Action::LAYER_GOTO_TOP, "go-top", _("Go to top layer"));
emplaceCustomItem("GOTO_NEXT_ANNOTATED_PAGE", Cat::NAVIGATION, Action::GOTO_NEXT_ANNOTATED_PAGE,
"page-annotated-next", _("Next annotated page"));
/* Menu Journal
* ------------------------------------------------------------------------
*/
emplaceCustomItemWithPopover("INSERT_NEW_PAGE", Cat::TOOLS, Action::NEW_PAGE_AFTER, "page-add", _("Insert page"),
this->pageTypeSelectionPopup.get());
emplaceCustomItem("DELETE_CURRENT_PAGE", Cat::TOOLS, Action::DELETE_PAGE, "page-delete", _("Delete current page"));
/*
* Menu Tool
* ------------------------------------------------------------------------
*/
this->penLineStylePopover = std::make_unique<StylePopoverFactory>(
Action::TOOL_PEN_LINE_STYLE,
std::vector<StylePopoverFactory::Entry>{{_("standard"), iconName("line-style-plain"), "plain"},
{_("dashed"), iconName("line-style-dash"), "dash"},
{_("dash-/ dotted"), iconName("line-style-dash-dot"), "dashdot"},
{_("dotted"), iconName("line-style-dot"), "dot"}});
emplaceCustomItemWithTargetAndMenu("PEN", Cat::TOOLS, Action::SELECT_TOOL, TOOL_PEN, "tool-pencil", _("Pen"),
this->penLineStylePopover.get());
this->eraserTypePopover = std::make_unique<StylePopoverFactory>(
Action::TOOL_ERASER_TYPE,
std::vector<StylePopoverFactory::Entry>{{_("standard"), ERASER_TYPE_DEFAULT},
{_("whiteout"), ERASER_TYPE_WHITEOUT},
{_("delete stroke"), ERASER_TYPE_DELETE_STROKE}});
emplaceCustomItemWithTargetAndMenu("ERASER", Cat::TOOLS, Action::SELECT_TOOL, TOOL_ERASER, "tool-eraser",
_("Eraser"), this->eraserTypePopover.get());
// Add individual line styles as toolbar items
emplaceCustomItemWithTarget("PLAIN", Cat::TOOLS, Action::TOOL_PEN_LINE_STYLE, "plain", "line-style-plain-with-pen",
_("standard"));
emplaceCustomItemWithTarget("DASHED", Cat::TOOLS, Action::TOOL_PEN_LINE_STYLE, "dash", "line-style-dash-with-pen",
_("dashed"));
emplaceCustomItemWithTarget("DASH-/ DOTTED", Cat::TOOLS, Action::TOOL_PEN_LINE_STYLE, "dashdot",
"line-style-dash-dot-with-pen", _("dash-/ dotted"));
emplaceCustomItemWithTarget("DOTTED", Cat::TOOLS, Action::TOOL_PEN_LINE_STYLE, "dot", "line-style-dot-with-pen",
_("dotted"));
emplaceCustomItemWithTarget("HIGHLIGHTER", Cat::TOOLS, Action::SELECT_TOOL, TOOL_HIGHLIGHTER, "tool-highlighter",
_("Highlighter"));
emplaceCustomItemWithTarget("TEXT", Cat::TOOLS, Action::SELECT_TOOL, TOOL_TEXT, "tool-text", _("Text"));
emplaceCustomItem("MATH_TEX", Cat::TOOLS, Action::TEX, "tool-math-tex", _("Add/Edit TeX"));
emplaceCustomItemWithTarget("IMAGE", Cat::TOOLS, Action::SELECT_TOOL, TOOL_IMAGE, "tool-image", _("Image"));
emplaceCustomItem("DEFAULT_TOOL", Cat::TOOLS, Action::SELECT_DEFAULT_TOOL, "default", _("Default Tool"));
emplaceCustomItemWithTarget("SELECT_PDF_TEXT_LINEAR", Cat::SELECTION, Action::SELECT_TOOL,
TOOL_SELECT_PDF_TEXT_LINEAR, "select-pdf-text-ht", _("Select Linear PDF Text"));
emplaceCustomItemWithTarget("SELECT_PDF_TEXT_RECT", Cat::SELECTION, Action::SELECT_TOOL, TOOL_SELECT_PDF_TEXT_RECT,
"select-pdf-text-area", _("Select PDF Text in Rectangle"));
emplaceCustomItemTgl("SETSQUARE", Cat::MISC, Action::SETSQUARE, "setsquare", _("Setsquare"));
emplaceCustomItemTgl("COMPASS", Cat::MISC, Action::COMPASS, "compass", _("Compass"));
emplaceCustomItemTgl("SHAPE_RECOGNIZER", Cat::TOOLS, Action::TOOL_DRAW_SHAPE_RECOGNIZER, "shape-recognizer",
_("Shape Recognizer"));
emplaceCustomItemTgl("DRAW_RECTANGLE", Cat::TOOLS, Action::TOOL_DRAW_RECTANGLE, "draw-rect", _("Draw Rectangle"));
emplaceCustomItemTgl("DRAW_ELLIPSE", Cat::TOOLS, Action::TOOL_DRAW_ELLIPSE, "draw-ellipse", _("Draw Ellipse"));
emplaceCustomItemTgl("DRAW_ARROW", Cat::TOOLS, Action::TOOL_DRAW_ARROW, "draw-arrow", _("Draw Arrow"));
emplaceCustomItemTgl("DRAW_DOUBLE_ARROW", Cat::TOOLS, Action::TOOL_DRAW_DOUBLE_ARROW, "draw-double-arrow",
_("Draw Double Arrow"));
emplaceCustomItemTgl("DRAW_COORDINATE_SYSTEM", Cat::TOOLS, Action::TOOL_DRAW_COORDINATE_SYSTEM,
"draw-coordinate-system", _("Draw Coordinate System"));
emplaceCustomItemTgl("RULER", Cat::TOOLS, Action::TOOL_DRAW_LINE, "draw-line", _("Draw Line"));
emplaceCustomItemTgl("DRAW_SPLINE", Cat::TOOLS, Action::TOOL_DRAW_SPLINE, "draw-spline", _("Draw Spline"));
emplaceCustomItemWithTarget("SELECT_REGION", Cat::SELECTION, Action::SELECT_TOOL, TOOL_SELECT_REGION,
"select-lasso", _("Select Region"));
emplaceCustomItemWithTarget("SELECT_RECTANGLE", Cat::SELECTION, Action::SELECT_TOOL, TOOL_SELECT_RECT,
"select-rect", _("Select Rectangle"));
emplaceCustomItemWithTarget("SELECT_MULTILAYER_REGION", Cat::SELECTION, Action::SELECT_TOOL,
TOOL_SELECT_MULTILAYER_REGION, "select-multilayer-lasso",
_("Select Multi-Layer Region"));
emplaceCustomItemWithTarget("SELECT_MULTILAYER_RECTANGLE", Cat::SELECTION, Action::SELECT_TOOL,
TOOL_SELECT_MULTILAYER_RECT, "select-multilayer-rect",
_("Select Multi-Layer Rectangle"));
emplaceCustomItemWithTarget("SELECT_OBJECT", Cat::SELECTION, Action::SELECT_TOOL, TOOL_SELECT_OBJECT,
"object-select", _("Select Object"));
emplaceCustomItemWithTarget("VERTICAL_SPACE", Cat::SELECTION, Action::SELECT_TOOL, TOOL_VERTICAL_SPACE, "spacer",
_("Vertical Space"));
emplaceCustomItemWithTarget("PLAY_OBJECT", Cat::SELECTION, Action::SELECT_TOOL, TOOL_PLAY_OBJECT, "object-play",
_("Play Object"));
emplaceCustomItemWithTarget("HAND", Cat::SELECTION, Action::SELECT_TOOL, TOOL_HAND, "hand", _("Hand"));
emplaceItem<FontButton>("SELECT_FONT", *control->getActionDatabase());
emplaceCustomItemTgl("AUDIO_RECORDING", Cat::AUDIO, Action::AUDIO_RECORD, "audio-record",
_("Record Audio / Stop Recording"));
emplaceCustomItemTgl("AUDIO_PAUSE_PLAYBACK", Cat::AUDIO, Action::AUDIO_PAUSE_PLAYBACK, "audio-playback-pause",
_("Pause / Play"));
emplaceCustomItem("AUDIO_STOP_PLAYBACK", Cat::AUDIO, Action::AUDIO_STOP_PLAYBACK, "audio-playback-stop", _("Stop"));
emplaceCustomItem("AUDIO_SEEK_FORWARDS", Cat::AUDIO, Action::AUDIO_SEEK_FORWARDS, "audio-seek-forwards",
_("Forward"));
emplaceCustomItem("AUDIO_SEEK_BACKWARDS", Cat::AUDIO, Action::AUDIO_SEEK_BACKWARDS, "audio-seek-backwards",
_("Back"));
///////////////////////////////////////////////////////////////////////////
/*
* Footer tools
* ------------------------------------------------------------------------
*/
toolPageSpinner = &emplaceItem<ToolPageSpinner>("PAGE_SPIN", iconNameHelper, control->getScrollHandler());
emplaceItem<ToolZoomSlider>("ZOOM_SLIDER", zoom, iconNameHelper, *control->getActionDatabase());
emplaceItem<ToolPageLayer>("LAYER", control->getLayerController(), iconNameHelper);
/*
* Non-menu items
* ------------------------------------------------------------------------
*/
/*
* Color item - not in the menu
* aka. COLOR_SELECT
*/
emplaceItem<ColorSelectorToolItem>(*control->getActionDatabase());
bool hideAudio = !this->control->getAudioController();
emplaceItem<ToolSelectCombocontrol>("SELECT", this->iconNameHelper, *this->control->getActionDatabase(), hideAudio);
emplaceItem<DrawingTypeComboToolButton>("DRAW", this->iconNameHelper, *this->control->getActionDatabase());
emplaceItem<ToolPdfCombocontrol>("PDF_TOOL", this->iconNameHelper, *this->control->getActionDatabase());
// General tool configuration - working for every tool which support it
emplaceCustomItemTgl("TOOL_FILL", Cat::TOOLS, Action::TOOL_FILL, "fill", _("Fill"));
emplaceCustomItem("FILL_OPACITY", Cat::TOOLS, Action::TOOL_FILL_OPACITY, "fill-opacity", _("Fill Opacity"));
emplaceCustomItemWithTarget("VERY_FINE", Cat::TOOLS, Action::TOOL_SIZE, TOOL_SIZE_VERY_FINE, "thickness-finer",
_("Very Fine"));
emplaceCustomItemWithTarget("FINE", Cat::TOOLS, Action::TOOL_SIZE, TOOL_SIZE_FINE, "thickness-fine", _("Fine"));
emplaceCustomItemWithTarget("MEDIUM", Cat::TOOLS, Action::TOOL_SIZE, TOOL_SIZE_MEDIUM, "thickness-medium",
_("Medium"));
emplaceCustomItemWithTarget("THICK", Cat::TOOLS, Action::TOOL_SIZE, TOOL_SIZE_THICK, "thickness-thick", _("Thick"));
emplaceCustomItemWithTarget("VERY_THICK", Cat::TOOLS, Action::TOOL_SIZE, TOOL_SIZE_VERY_THICK, "thickness-thicker",
_("Very Thick"));
}
void ToolMenuHandler::setPageInfo(size_t currentPage, size_t pageCount, size_t pdfpage) {
if (this->toolPageSpinner) {
this->toolPageSpinner->setPageInfo(currentPage, pageCount, pdfpage);
}
}
auto ToolMenuHandler::getModel() -> ToolbarModel* { return this->tbModel.get(); }
auto ToolMenuHandler::getControl() -> Control* { return this->control; }
auto ToolMenuHandler::getToolItems() const -> const std::vector<std::unique_ptr<AbstractToolItem>>& {
return this->toolItems;
}
auto ToolMenuHandler::getColorToolItems() const -> const std::vector<std::unique_ptr<ColorToolItem>>& {
return this->toolbarColorItems;
}
auto ToolMenuHandler::iconName(const char* icon) -> std::string { return iconNameHelper.iconName(icon); }
void ToolMenuHandler::updateColorToolItems(const Palette& palette) {
for (const auto& it: this->toolbarColorItems) {
it->updateColor(palette);
}
}
void ToolMenuHandler::setDefaultNewPageType(const std::optional<PageType>& pt) {
this->pageTypeSelectionPopup->setSelected(pt);
}
| 27,198
|
C++
|
.cpp
| 427
| 52.995316
| 120
| 0.612002
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,607
|
ToolPageSpinner.cpp
|
xournalpp_xournalpp/src/core/gui/toolbarMenubar/ToolPageSpinner.cpp
|
#include "ToolPageSpinner.h"
#include <algorithm> // for find
#include <utility> // for move
#include <glib-object.h> // for g_object_ref_sink
#include "gui/toolbarMenubar/AbstractToolItem.h" // for AbstractToolItem
#include "gui/widgets/SpinPageAdapter.h" // for SpinPageAdapter
#include "util/Assert.h" // for xoj_assert
#include "util/Util.h"
#include "util/gtk4_helper.h" // for gtk_box_append
#include "util/i18n.h" // for FS, _, _F, C_F
class ToolPageSpinner::Instance final {
public:
Instance(ToolPageSpinner* handler, GtkOrientation orientation): handler(handler), orientation(orientation) {}
xoj::util::WidgetSPtr makeWidget() {
GtkWidget* spinner = gtk_spin_button_new_with_range(0, 1, 1);
gtk_orientable_set_orientation(GTK_ORIENTABLE(spinner), orientation);
this->spinner.setWidget(spinner); // takes ownership of spinner reference
this->spinner.addListener(handler->getListener());
GtkWidget* numberLabel = gtk_label_new("");
GtkWidget* pageLabel = gtk_label_new(_("Page"));
if (orientation == GTK_ORIENTATION_HORIZONTAL) {
gtk_widget_set_valign(pageLabel, GTK_ALIGN_BASELINE);
gtk_widget_set_margin_start(pageLabel, 7);
gtk_widget_set_margin_end(pageLabel, 7);
gtk_widget_set_valign(spinner, GTK_ALIGN_BASELINE);
gtk_widget_set_valign(numberLabel, GTK_ALIGN_BASELINE);
gtk_widget_set_margin_start(numberLabel, 7);
gtk_widget_set_margin_end(numberLabel, 7);
} else {
gtk_widget_set_halign(pageLabel, GTK_ALIGN_CENTER);
gtk_widget_set_margin_top(pageLabel, 7);
gtk_widget_set_margin_bottom(pageLabel, 7);
gtk_widget_set_halign(spinner, GTK_ALIGN_CENTER);
gtk_widget_set_halign(numberLabel, GTK_ALIGN_CENTER);
gtk_widget_set_valign(spinner, GTK_ALIGN_BASELINE);
gtk_widget_set_valign(numberLabel, GTK_ALIGN_BASELINE);
gtk_label_set_justify(GTK_LABEL(numberLabel), GTK_JUSTIFY_CENTER);
gtk_widget_set_margin_top(numberLabel, 7);
gtk_widget_set_margin_bottom(numberLabel, 7);
}
this->numberLabel = GTK_LABEL(numberLabel);
xoj::util::WidgetSPtr item(gtk_box_new(orientation, 1), xoj::util::adopt);
GtkBox* box = GTK_BOX(item.get());
gtk_box_append(box, pageLabel);
gtk_box_append(box, spinner);
gtk_box_append(box, numberLabel);
return item;
}
void disconnect() { handler = nullptr; }
private:
ToolPageSpinner* handler;
GtkOrientation orientation;
SpinPageAdapter spinner;
GtkLabel* numberLabel;
public:
void setPageInfo(size_t currentPage, size_t pageCount, size_t pdfPage) {
if (pageCount == 0) {
spinner.setMinMaxPage(0, 0);
spinner.setPage(0);
} else {
spinner.setMinMaxPage(1, pageCount);
spinner.setPage(currentPage + 1);
}
updateLabel(pageCount, pdfPage);
}
ToolPageSpinner* getHandler() const { return handler; }
private:
void updateLabel(const size_t pageCount, const size_t pdfPage) {
std::string ofString = FS(C_F("Page {pagenumber} \"of {pagecount}\"", " of {1}") % pageCount);
if (pdfPage != npos) {
if (this->orientation == GTK_ORIENTATION_HORIZONTAL) {
ofString += std::string(", ") + FS(_F("PDF Page {1}") % (pdfPage + 1));
} else {
ofString += std::string("\n") + FS(_F("PDF {1}") % (pdfPage + 1));
}
}
gtk_label_set_text(this->numberLabel, ofString.c_str());
}
};
ToolPageSpinner::ToolPageSpinner(std::string id, IconNameHelper iconNameHelper, SpinPageListener* listener):
AbstractToolItem(std::move(id), Category::NAVIGATION), iconNameHelper(iconNameHelper), listener(listener) {}
ToolPageSpinner::~ToolPageSpinner() {
for (auto* i: instances) {
i->disconnect();
}
}
void ToolPageSpinner::setPageInfo(size_t currentPage, size_t pageCount, size_t pdfPage) {
for (auto* i: instances) {
i->setPageInfo(currentPage, pageCount, pdfPage);
}
}
auto ToolPageSpinner::getToolDisplayName() const -> std::string { return _("Page number"); }
auto ToolPageSpinner::getNewToolIcon() const -> GtkWidget* {
return gtk_image_new_from_icon_name(iconNameHelper.iconName("page-spinner").c_str(), GTK_ICON_SIZE_SMALL_TOOLBAR);
}
auto ToolPageSpinner::createItem(bool horizontal) -> xoj::util::WidgetSPtr {
auto orientation = horizontal ? GTK_ORIENTATION_HORIZONTAL : GTK_ORIENTATION_VERTICAL;
auto data = std::make_unique<Instance>(this, orientation);
auto item = data->makeWidget();
this->instances.emplace_back(data.get()); // Keep a ref for callback propagation
// Destroy *data if the widget is destroyed
g_object_weak_ref(
G_OBJECT(item.get()),
+[](gpointer d, GObject*) {
auto* data = static_cast<Instance*>(d);
if (auto* h = data->getHandler(); h) {
auto& instances = h->instances;
if (auto it = std::find(instances.begin(), instances.end(), data); it != instances.end()) {
instances.erase(it);
}
}
delete data;
},
data.release());
return item;
}
| 5,465
|
C++
|
.cpp
| 116
| 38.75
| 118
| 0.6315
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,608
|
ToolbarItem.cpp
|
xournalpp_xournalpp/src/core/gui/toolbarMenubar/model/ToolbarItem.cpp
|
#include "ToolbarItem.h"
#include <utility>
int ToolbarItem::sid = 0;
ToolbarItem::ToolbarItem(std::string name) {
this->name = std::move(name);
this->id = ToolbarItem::sid++;
if (ToolbarItem::sid < 0) {
ToolbarItem::sid = 0;
}
}
auto ToolbarItem::getName() const -> std::string { return this->name; }
void ToolbarItem::setName(std::string name) { this->name = std::move(name); }
auto ToolbarItem::operator==(ToolbarItem& other) -> bool { return this->name == other.name; }
auto ToolbarItem::getId() const -> int { return this->id; }
| 566
|
C++
|
.cpp
| 14
| 37.142857
| 93
| 0.674632
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,609
|
ToolbarEntry.cpp
|
xournalpp_xournalpp/src/core/gui/toolbarMenubar/model/ToolbarEntry.cpp
|
#include "ToolbarEntry.h"
#include <algorithm>
#include <utility> // for move
#include <glib.h>
#include "gui/toolbarMenubar/model/ToolbarItem.h" // for ToolbarItem
#include "util/Assert.h"
ToolbarEntry::ToolbarEntry() = default;
ToolbarEntry::ToolbarEntry(const ToolbarEntry& e) { *this = e; }
ToolbarEntry::ToolbarEntry(ToolbarEntry&& e) { *this = std::move(e); }
ToolbarEntry& ToolbarEntry::operator=(const ToolbarEntry& e) {
this->name = e.name;
this->entries = e.entries;
return *this;
}
ToolbarEntry& ToolbarEntry::operator=(ToolbarEntry&& e) {
this->name = std::move(e.name);
this->entries = std::move(e.entries);
return *this;
}
ToolbarEntry::~ToolbarEntry() = default;
auto ToolbarEntry::getName() const -> std::string { return this->name; }
void ToolbarEntry::setName(std::string name) { this->name = std::move(name); }
auto ToolbarEntry::addItem(std::string item) -> int { return entries.emplace_back(std::move(item)).getId(); }
auto ToolbarEntry::removeItemById(int id) -> bool {
auto it = std::find_if(entries.begin(), entries.end(), [id](const auto& it) { return it.getId() == id; });
if (it != entries.end()) {
entries.erase(it);
return true;
}
g_warning("ToolbarEntry::removeItemById: Tried to remove inexistant ID");
return false;
}
auto ToolbarEntry::insertItem(std::string item, int position) -> int {
xoj_assert(position >= 0);
if (position >= static_cast<int>(entries.size())) {
return entries.emplace_back(std::move(item)).getId();
}
return entries.emplace(std::next(entries.begin(), position), std::move(item))->getId();
}
auto ToolbarEntry::getItems() const -> const ToolbarItemVector& { return entries; }
| 1,731
|
C++
|
.cpp
| 40
| 39.8
| 110
| 0.693317
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,610
|
ToolbarModel.cpp
|
xournalpp_xournalpp/src/core/gui/toolbarMenubar/model/ToolbarModel.cpp
|
#include "ToolbarModel.h"
#include <algorithm> // for find_if
#include <cstddef> // for size_t
#include "util/XojMsgBox.h" // for XojMsgBox
#include "util/i18n.h" // for _
#include "util/safe_casts.h" // for as_signed
#include "ToolbarData.h" // for ToolbarData
#include "filesystem.h" // for path
ToolbarModel::ToolbarModel() = default;
ToolbarModel::~ToolbarModel() = default;
auto ToolbarModel::getToolbars() const -> const std::vector<std::unique_ptr<ToolbarData>>& { return this->toolbars; }
void ToolbarModel::parseGroup(GKeyFile* config, const char* group, bool predefined, const Palette& colorPalette) {
auto data = std::make_unique<ToolbarData>(predefined);
data->name = (predefined ? "predef_" : "custom_");
data->id = group;
data->load(config, group, colorPalette);
add(std::move(data));
}
void ToolbarModel::remove(ToolbarData* data) {
auto it = std::find_if(toolbars.begin(), toolbars.end(), [data](const auto& tb) { return tb.get() == data; });
if (it != this->toolbars.end()) {
this->toolbars.erase(it);
}
}
auto ToolbarModel::add(std::unique_ptr<ToolbarData> data) -> ToolbarData* {
return this->toolbars.emplace_back(std::move(data)).get();
}
auto ToolbarModel::parse(fs::path const& filepath, bool predefined, const Palette& colorPalette) -> bool {
GKeyFile* config = g_key_file_new();
g_key_file_set_list_separator(config, ',');
if (!g_key_file_load_from_file(config, filepath.u8string().c_str(), G_KEY_FILE_NONE, nullptr)) {
g_key_file_free(config);
return false;
}
gsize length = 0;
gchar** groups = g_key_file_get_groups(config, &length);
for (gsize i = 0; i < length; i++) {
parseGroup(config, groups[i], predefined, colorPalette);
}
g_strfreev(groups);
g_key_file_free(config);
return true;
}
void ToolbarModel::initCopyNameId(ToolbarData* data) {
if (!existsId(data->getId())) {
return;
}
for (int i = 0; i < 100; i++) {
std::string id = data->getId() + " Copy";
if (i > 0) {
id += " ";
id += std::to_string(i);
}
if (!existsId(id)) {
std::string filename = data->getName();
filename += " ";
filename += C_("as a noun: a copy of", "Copy");
if (i > 0) {
filename += " ";
filename += std::to_string(i);
}
data->setName(filename);
data->setId(id);
return;
}
}
}
auto ToolbarModel::existsId(const std::string& id) const -> bool {
return std::any_of(toolbars.begin(), toolbars.end(), [&id](const auto& d) { return d->getId() == id; });
}
const char* TOOLBAR_INI_HEADER =
"# Xournal++ Toolbar configuration\n"
"# Here you can customize the Toolbars\n"
" Delete this file to generate a new config file with default values\n"
"\n"
" Available buttons:\n"
" File: NEW,OPEN,SAVE,SAVEPDF,PRINT\n"
"\n"
" Edit: UNDO,REDO,CUT,COPY,PASTE,SEARCH,DELETE,ROTATION_SNAPPING,GRID_SNAPPING\n"
"\n"
" View: PAIRED_PAGES,PRESENTATION_MODE,FULLSCREEN,MANAGE_TOOLBAR,CUSTOMIZE_TOOLBAR,ZOOM_OUT,ZOOM_IN,ZOOM_FIT,ZOOM_100\n"
"\n"
" Navigation: GOTO_FIRST,GOTO_BACK,GOTO_PAGE,GOTO_NEXT,GOTO_LAST,GOTO_PREVIOUS_LAYER,GOTO_NEXT_LAYER,GOTO_TOP_LAYER,\n"
" GOTO_NEXT_ANNOTATED_PAGE\n"
"\n"
" Journal: INSERT_NEW_PAGE,DELETE_CURRENT_PAGE\n"
"\n"
" Tool: PEN,PLAIN,DASHED,DASH-/ DOTTED,DOTTED,ERASER,HIGHLIGHTER,TEXT,MATH_TEX,IMAGE,DEFAULT_TOOL,SHAPE_RECOGNIZER,SELECT_PDF_TEXT_LINEAR,\n"
" SELECT_PDF_TEXT_RECT,DRAW_RECTANGLE,DRAW_ELLIPSE,DRAW_ARROW,DRAW_DOUBLE_ARROW,DRAW_COORDINATE_SYSTEM,RULER,DRAW_SPLINE,\n"
" SELECT_REGION,SELECT_RECTANGLE,SELECT_MULTILAYER_REGION,SELECT_MULTILAYER_RECTANGLE,SELECT_OBJECT,VERTICAL_SPACE,PLAY_OBJECT,\n"
" HAND,SETSQUARE,COMPASS,SELECT_FONT,AUDIO_RECORDING,AUDIO_PAUSE_PLAYBACK,AUDIO_STOP_PLAYBACK,AUDIO_SEEK_FORWARDS,AUDIO_SEEK_BACKWARDS\n"
" Notice: ERASER and PEN also have drop down menus to select the type, SELECT are all selection tools, with drop down menu\n"
"\n"
" Footer tools: PAGE_SPIN,ZOOM_SLIDER,LAYER,TOOL_FILL,PEN_FILL_OPACITY\n"
" PAGE_SPIN: The page spiner, incl. current page label\n"
" ZOOM_SLIDER: The zoom slider\n"
" LAYER: The layer dropdown menu\n"
"\n"
" Color: "
"COLOR(0),COLOR(1),COLOR(2),COLOR(3),COLOR(4),COLOR(5),COLOR(6),COLOR(7),COLOR(8),COLOR(9),COLOR(10),COLOR_SELECT\n"
" Notice: The colors reference the respective color in the palette.gpl file.\n"
" For backwards compatibility the hex representation, e.g. COLOR(0xff8000), is still permitted. However, the hex value\n"
" will be IGNORED in favour of the \"next\" palette color. They will be automatically migrated when the user customizes\n"
" the respective toolbar configuration.\n"
"\n"
" Non-menu items: SELECT,DRAW,PDF_TOOL\n"
"\n"
" Tool configuration: VERY_FINE,FINE,MEDIUM,THICK,VERY_THICK\n"
"\n"
" Item separation: SEPARATOR,SPACER\n"
"\n";
void ToolbarModel::save(fs::path const& filepath) const {
GKeyFile* config = g_key_file_new();
g_key_file_set_list_separator(config, ',');
g_key_file_set_comment(config, nullptr, nullptr, TOOLBAR_INI_HEADER, nullptr);
for (const auto& data: this->toolbars) {
if (!data->isPredefined()) {
data->saveToKeyFile(config);
}
}
gsize len = 0;
char* data = g_key_file_to_data(config, &len, nullptr);
g_key_file_free(config);
config = nullptr;
GError* error = nullptr;
if (!g_file_set_contents(filepath.u8string().c_str(), data, as_signed(len), &error)) {
XojMsgBox::showErrorToUser(nullptr, error->message);
g_error_free(error);
}
g_free(data);
}
| 6,069
|
C++
|
.cpp
| 131
| 39.389313
| 151
| 0.630501
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,611
|
ToolbarData.cpp
|
xournalpp_xournalpp/src/core/gui/toolbarMenubar/model/ToolbarData.cpp
|
#include "ToolbarData.h"
#include <cstring> // for strcmp, strncmp
#include <utility> // for move
#include "gui/toolbarMenubar/model/ColorPalette.h" // for Palette
#include "gui/toolbarMenubar/model/ToolbarEntry.h" // for ToolbarEntry, Too...
#include "gui/toolbarMenubar/model/ToolbarItem.h" // for ToolbarItem
#include "util/PlaceholderString.h" // for PlaceholderString
#include "util/StringUtils.h" // for StringUtils
#include "util/i18n.h" // for FC, FORMAT_STR, _F
using std::string;
ToolbarData::ToolbarData(bool predefined): predefined(predefined) {}
ToolbarData::ToolbarData(const ToolbarData& data) {
*this = data;
this->predefined = false;
}
void ToolbarData::operator=(const ToolbarData& other) {
this->id = other.id;
this->name = other.name;
this->predefined = other.predefined;
this->contents = other.contents;
}
ToolbarData::~ToolbarData() = default;
auto ToolbarData::getName() const -> const std::string& { return this->name; }
void ToolbarData::setName(string name) { this->name = std::move(name); }
auto ToolbarData::getId() const -> const std::string& { return this->id; }
void ToolbarData::setId(string id) { this->id = std::move(id); }
auto ToolbarData::isPredefined() const -> bool { return this->predefined; }
void ToolbarData::load(GKeyFile* config, const char* group, const Palette& colorPalette) {
size_t unassignedColorIndex = 0U;
auto filterDeprecatedItemNames = [&](std::string name) -> std::string {
// recognize previous name, V1.07 (Jan 2019) and earlier.
if (name == "TWO_PAGES") {
return "PAIRED_PAGES";
}
// recognize previous name, V1.08 (Feb 2019) and earlier.
if (name == "RECSTOP") {
return "AUDIO_RECORDING";
}
// recognize previous name, V1.0.19 (Dec 2020) and earlier
if (name == "HILIGHTER") {
return "HIGHLIGHTER";
}
// recognize previous name, V1.1.0+dev (Jan 2021) and earlier
if (name == "DRAW_CIRCLE") {
return "DRAW_ELLIPSE";
}
// recognize previous name, V1.1.0+dev (Nov 2022) and earlier
if (name == "PEN_FILL_OPACITY") {
return "FILL_OPACITY";
}
if (StringUtils::startsWith(name, "COLOR(") && StringUtils::endsWith(name, ")")) {
std::string arg = name.substr(6, name.length() - 7);
// check for old color format of toolbar.ini
if (StringUtils::startsWith(arg, "0x")) {
auto paletteIndex = colorPalette.getColorAt(unassignedColorIndex++).getIndex();
return "COLOR(" + std::to_string(paletteIndex) + ")";
}
}
return name;
};
gsize length = 0;
gchar** keys = g_key_file_get_keys(config, group, &length, nullptr);
if (keys == nullptr) {
return;
}
gchar* name = g_key_file_get_locale_string(config, group, "name", nullptr, nullptr);
if (name != nullptr) {
this->name = name;
g_free(name);
}
for (gsize i = 0; i < length; i++) {
if (strcmp(keys[i], "name") == 0 || strncmp(keys[i], "name[", 5) == 0) {
continue;
}
auto& e = contents.emplace_back();
e.setName(keys[i]);
gsize keyLen = 0;
gchar** list = g_key_file_get_string_list(config, group, keys[i], &keyLen, nullptr);
for (gsize x = 0; x < keyLen; x++) {
e.addItem(filterDeprecatedItemNames(StringUtils::trim(std::string(list[x]))));
}
g_strfreev(list);
}
g_strfreev(keys);
}
void ToolbarData::saveToKeyFile(GKeyFile* config) const {
string group = getId();
for (const ToolbarEntry& e: this->contents) {
string line{};
for (const auto& it: e.getItems()) {
line += ",";
line += it.getName();
}
if (line.length() > 2) {
g_key_file_set_string(config, group.c_str(), e.getName().c_str(), line.substr(1).c_str());
}
}
g_key_file_set_string(config, group.c_str(), "name", this->name.c_str());
}
auto ToolbarData::insertItem(const std::string& toolbar, const std::string& item, int position) -> int {
g_message("ToolbarData::insertItem(%s, %s, %d);", toolbar.data(), item.data(), position);
g_return_val_if_fail(isPredefined() == false, -1);
for (ToolbarEntry& e: this->contents) {
if (e.getName() == toolbar) {
g_message(" | Toolbar %s found -- Inserting element", toolbar.c_str());
return e.insertItem(item, position);
}
}
// No toolbar named toolbar. Adding a new one
g_message(" | Toolbar %s not found -- Creating a new one", toolbar.c_str());
auto& newEntry = contents.emplace_back();
newEntry.setName(toolbar);
return newEntry.addItem(item);
}
auto ToolbarData::removeItemByID(const string& toolbar, int id) -> bool {
g_return_val_if_fail(isPredefined() == false, false);
for (ToolbarEntry& e: contents) {
if (e.getName() == toolbar) {
return e.removeItemById(id);
}
}
return false;
}
| 5,196
|
C++
|
.cpp
| 123
| 35.292683
| 104
| 0.603815
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,612
|
ColorPalette.cpp
|
xournalpp_xournalpp/src/core/gui/toolbarMenubar/model/ColorPalette.cpp
|
#include "ColorPalette.h"
#include <fstream> // for basic_ifstream, basic_ofstream
#include <sstream> // for operator<<, basic_ostream::operator<<
#include <stdexcept> // for invalid_argument
#include <utility> // for move
#include <glib.h> // for g_warning, g_error
#include "util/StringUtils.h" // for StringUtils
#include "util/Util.h"
#include "util/XojMsgBox.h"
#include "util/i18n.h" // for FORMAT_STR, FS, _
#include "util/serdesstream.h" // for serdes_stream
Palette::Palette(fs::path path): filepath{std::move(path)}, namedColors{}, header{} {}
void Palette::load() {
if (!fs::exists(this->filepath))
throw std::invalid_argument(
FS(FORMAT_STR("The palette file {1} does not exist.") % this->filepath.filename().u8string()));
header.clear();
namedColors.clear();
auto gplFile = serdes_stream<std::ifstream>(filepath);
gplFile.exceptions(std::ifstream::failbit | std::ifstream::badbit);
std::string line;
getline(gplFile, line);
int lineNumber{1};
// parse standard header line
parseFirstGimpPaletteLine(line);
// attempt parsing line by line as either header, color, or fallback
while (!gplFile.eof() && gplFile.peek() != EOF && getline(gplFile, line)) {
lineNumber++;
parseCommentLine(line) || parseHeaderLine(line) || parseColorLine(line) || parseEmptyLine(line) ||
parseLineFallback(lineNumber);
}
if (namedColors.size() < 1) {
throw std::invalid_argument("Your Palettefile has no parsable color. It needs at least one!");
}
}
auto Palette::load_default() -> void {
std::stringstream defaultFile{default_palette()};
std::string line;
getline(defaultFile, line);
if (!parseFirstGimpPaletteLine(line))
g_error("The default file was mallformed. This should never happen!");
while (getline(defaultFile, line)) {
parseHeaderLine(line) || parseColorLine(line);
}
}
auto Palette::getHeader(const std::string& attr) const -> std::string {
if (header.find(attr) == header.end()) {
return std::string{};
}
return header.at(attr);
}
auto Palette::parseFirstGimpPaletteLine(const std::string& line) const -> bool {
if (StringUtils::trim(line) != "GIMP Palette") {
throw std::invalid_argument(".gpl file needs to start with \"GIMP Palette\" in the "
"first line");
}
return true;
}
auto Palette::parseHeaderLine(const std::string& line) -> bool {
Header headerEntry;
std::istringstream iss{line};
if (iss >> headerEntry) {
header[headerEntry.getAttribute()] = headerEntry.getValue();
return true;
}
return false;
}
auto Palette::parseColorLine(const std::string& line) -> bool {
NamedColor color{namedColors.size()};
std::istringstream iss{line};
if (iss >> color) {
namedColors.emplace_back(std::move(color));
return true;
}
return false;
}
auto Palette::parseCommentLine(const std::string& line) const -> bool { return line.front() == '#'; }
auto Palette::parseEmptyLine(const std::string& line) const -> bool { return line.empty(); }
auto Palette::parseLineFallback(int lineNumber) const -> const bool {
throw std::invalid_argument(FS(FORMAT_STR("The line {1} is malformed.") % lineNumber));
}
auto Palette::getColorAt(size_t i) const -> NamedColor const& {
if (i >= namedColors.size()) {
i = i % namedColors.size();
g_warning("There are more Coloritems in the Toolbar than your Palette defines.\n"
"Hence, cycling through palette from the beginning.");
}
return namedColors.at(i);
}
auto Palette::size() const -> size_t { return namedColors.size(); }
auto Palette::default_palette() -> const std::string {
auto d = serdes_stream<std::stringstream>();
d << "GIMP Palette\n"
<< "Name: Xournal Palette\n"
<< "#\n"
<< 0 << " " << 0 << " " << 0 << " " << NC_("Color", "Black") << "\n"
<< 0 << " " << 128 << " " << 0 << " " << NC_("Color", "Green") << "\n"
<< 0 << " " << 192 << " " << 255 << " " << NC_("Color", "Light Blue") << "\n"
<< 0 << " " << 255 << " " << 0 << " " << NC_("Color", "Light Green") << "\n"
<< 51 << " " << 51 << " " << 204 << " " << NC_("Color", "Blue") << "\n"
<< 128 << " " << 128 << " " << 128 << " " << NC_("Color", "Gray") << "\n"
<< 255 << " " << 0 << " " << 0 << " " << NC_("Color", "Red") << "\n"
<< 255 << " " << 0 << " " << 255 << " " << NC_("Color", "Magenta") << "\n"
<< 255 << " " << 128 << " " << 0 << " " << NC_("Color", "Orange") << "\n"
<< 255 << " " << 255 << " " << 0 << " " << NC_("Color", "Yellow") << "\n"
<< 255 << " " << 255 << " " << 255 << " " << NC_("Color", "White") << std::endl;
return d.str();
}
void Palette::create_default(fs::path filepath) {
auto myfile = serdes_stream<std::ofstream>(filepath);
myfile << default_palette();
}
auto Header::getAttribute() const -> std::string { return this->attribute; };
auto Header::getValue() const -> std::string { return this->value; };
auto Palette::getFilePath() const -> fs::path const& { return this->filepath; };
auto operator>>(std::istream& str, Header& header) -> std::istream& {
/*
* inspired by
* https://codereview.stackexchange.com/questions/38879/parsing-text-file-in-c
*/
std::string line;
Header tmp;
if (std::getline(str, line)) {
std::istringstream iss{line};
if (getline(iss, tmp.attribute, ':') && getline(iss, tmp.value, '\n')) {
tmp.attribute = StringUtils::trim(tmp.attribute);
tmp.value = StringUtils::trim(tmp.value);
// parsing was successful hence results can be stored permanently
header = std::move(tmp);
} else {
/*
* One operation failed.
* So set the state on the main stream
* to indicate failure.
*/
str.setstate(std::ios::failbit);
}
}
return str;
}
auto Palette::parseErrorDialog(const std::exception& e) const -> void {
std::stringstream msg_stream{};
msg_stream << "There has been a problem parsing the color palette file at " << filepath.c_str() << "\n\n";
msg_stream << "What happened:\n" << e.what() << std::endl;
msg_stream << "What to do:\n";
msg_stream << "Please fix your palette file, or rename it so xournalpp creates a new default palette file "
"for you. This file can then be used as a template.\n";
msg_stream << "Until this is fixed, the application will use the default color palette.";
// Call later, to make sure the main window has been set up, so the popup is displayed in front of it (and modal)
Util::execInUiThread([msg = msg_stream.str()]() { XojMsgBox::showErrorToUser(nullptr, msg); });
}
| 6,899
|
C++
|
.cpp
| 151
| 39.827815
| 117
| 0.600387
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,613
|
ToolbarSeparatorImage.cpp
|
xournalpp_xournalpp/src/core/gui/toolbarMenubar/icon/ToolbarSeparatorImage.cpp
|
#include "ToolbarSeparatorImage.h"
#include <cairo.h> // for cairo_create, cairo_destroy, cairo_image_su...
#include <gdk/gdk.h> // for gdk_pixbuf_get_from_surface
#include <glib-object.h> // for g_object_unref
#include <util/Color.h> // for Colors::red, Colors::gray
#include <util/Util.h> // for cairo_set_source_rgbi
constexpr double LINE_WIDTH = 5.;
constexpr double MARGIN = 3.;
constexpr double TAIL_SIZE = 5.;
auto ToolbarSeparatorImage::newImage(SeparatorType separator) -> GtkWidget* {
GdkPixbuf* pixbuf = ToolbarSeparatorImage::getNewToolPixbuf(separator);
GtkWidget* w = gtk_image_new_from_pixbuf(pixbuf);
g_object_unref(pixbuf);
return w;
}
auto ToolbarSeparatorImage::getNewToolPixbuf(SeparatorType separator) -> GdkPixbuf* {
constexpr auto width = 30;
constexpr auto height = 30;
cairo_surface_t* crImage = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, width, height);
cairo_t* cr = cairo_create(crImage);
Util::cairo_set_source_rgbi(cr, Colors::red);
cairo_set_line_width(cr, LINE_WIDTH);
cairo_move_to(cr, width / 2, 0);
cairo_line_to(cr, width / 2, height);
cairo_stroke(cr);
if (separator == SeparatorType::SPACER) { // add double arrow tails
Util::cairo_set_source_rgbi(cr, Colors::gray);
cairo_move_to(cr, MARGIN + TAIL_SIZE, height / 2 - TAIL_SIZE);
cairo_line_to(cr, MARGIN, height / 2);
cairo_line_to(cr, MARGIN + TAIL_SIZE, height / 2 + TAIL_SIZE);
cairo_move_to(cr, width - MARGIN - TAIL_SIZE, height / 2 - TAIL_SIZE);
cairo_line_to(cr, width - MARGIN, height / 2);
cairo_line_to(cr, width - MARGIN - TAIL_SIZE, height / 2 + TAIL_SIZE);
cairo_stroke(cr);
}
cairo_destroy(cr);
GdkPixbuf* pixbuf = gdk_pixbuf_get_from_surface(crImage, 0, 0, width, height);
cairo_surface_destroy(crImage);
return pixbuf;
}
| 1,898
|
C++
|
.cpp
| 40
| 42.75
| 94
| 0.679459
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,614
|
ColorIcon.cpp
|
xournalpp_xournalpp/src/core/gui/toolbarMenubar/icon/ColorIcon.cpp
|
#include "ColorIcon.h"
#include <cmath> // for M_PI
#include "util/raii/CairoWrappers.h"
#include "util/raii/GObjectSPtr.h"
namespace ColorIcon {
/**
* Create a new GtkImage with preview color
*/
auto newGtkImage(Color color, int size, bool circle) -> GtkWidget* {
xoj::util::GObjectSPtr<GdkPixbuf> img(newGdkPixbuf(color, size, circle));
GtkWidget* w = gtk_image_new_from_pixbuf(img.get());
gtk_widget_show(w);
return w;
}
/**
* Create a new GdkPixbuf* with preview color
*/
auto newGdkPixbuf(Color color, int size, bool circle) -> xoj::util::GObjectSPtr<GdkPixbuf> {
xoj::util::CairoSurfaceSPtr buf(cairo_image_surface_create(CAIRO_FORMAT_ARGB32, size, size), xoj::util::adopt);
xoj::util::CairoSPtr cr(cairo_create(buf.get()), xoj::util::adopt);
Util::cairo_set_source_rgbi(cr.get(), color, 1);
constexpr double PADDING = 1;
if (circle) {
const double mid = .5 * size;
const double radius = mid - PADDING;
cairo_arc(cr.get(), mid, mid, radius, 0, 2 * M_PI);
} else {
cairo_rectangle(cr.get(), PADDING, PADDING, size - 2 * PADDING, size - 2 * PADDING);
}
cairo_fill_preserve(cr.get());
cairo_set_source_rgba(cr.get(), 0, 0, 0, 1);
cairo_set_line_width(cr.get(), 1);
cairo_stroke(cr.get());
return xoj::util::GObjectSPtr<GdkPixbuf>(gdk_pixbuf_get_from_surface(buf.get(), 0, 0, size, size),
xoj::util::adopt);
}
}; // namespace ColorIcon
| 1,494
|
C++
|
.cpp
| 37
| 35.216216
| 115
| 0.64779
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,615
|
ScrollHandling.cpp
|
xournalpp_xournalpp/src/core/gui/scroll/ScrollHandling.cpp
|
#include "ScrollHandling.h"
#include "gui/Layout.h"
ScrollHandling::ScrollHandling(GtkAdjustment* adjHorizontal, GtkAdjustment* adjVertical):
adjHorizontal(adjHorizontal), adjVertical(adjVertical) {}
ScrollHandling::ScrollHandling(GtkScrollable* scrollable):
ScrollHandling(gtk_scrollable_get_hadjustment(scrollable), gtk_scrollable_get_vadjustment(scrollable)) {}
ScrollHandling::~ScrollHandling() = default;
auto ScrollHandling::getHorizontal() -> GtkAdjustment* { return adjHorizontal; }
auto ScrollHandling::getVertical() -> GtkAdjustment* { return adjVertical; }
void ScrollHandling::init(GtkWidget* xournal, Layout* layout) {
this->xournal = xournal;
this->layout = layout;
}
#define TEMP_FIX true
void ScrollHandling::setLayoutSize(int width, int height) {
// after a page has been inserted the layout size must be updated immediately,
// otherwise it comes down to a race deciding if scrolling happens normally or not
#if TEMP_FIX
// Todo(Fabian): remove that fix, since it is conceptually wrong behavior
// the adjustment is/must be changed implicitly by the layout and the resulting expose event
if (gtk_adjustment_get_upper(getHorizontal()) != width) {
gtk_adjustment_set_upper(getHorizontal(), width);
}
if (gtk_adjustment_get_upper(getVertical()) != height) {
gtk_adjustment_set_upper(getVertical(), height);
}
#endif
}
| 1,432
|
C++
|
.cpp
| 28
| 47.107143
| 113
| 0.749101
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,616
|
MouseInputHandler.cpp
|
xournalpp_xournalpp/src/core/gui/inputdevices/MouseInputHandler.cpp
|
//
// Created by ulrich on 08.04.19.
//
#include "MouseInputHandler.h"
#include "control/ToolHandler.h" // for ToolHandler
#include "control/settings/SettingsEnums.h" // for Button, BUTTON_MOUSE_M...
#include "gui/XournalView.h" // for XournalView
#include "gui/XournalppCursor.h" // for XournalppCursor
#include "gui/inputdevices/InputEvents.h" // for InputEvent, BUTTON_PRE...
#include "gui/inputdevices/PenInputHandler.h" // for PenInputHandler
#include "gui/widgets/XournalWidget.h" // for GtkXournal
#include "InputContext.h" // for InputContext
#include "InputUtils.h" // for InputUtils
class Settings;
class XojPageView;
MouseInputHandler::MouseInputHandler(InputContext* inputContext): PenInputHandler(inputContext) {}
MouseInputHandler::~MouseInputHandler() = default;
auto MouseInputHandler::handleImpl(InputEvent const& event) -> bool {
// Only handle events when there is no active gesture
GtkXournal* xournal = inputContext->getXournal();
// Determine the pressed states of devices and associate them to the current event
setPressedState(event);
/*
* Trigger start action
*/
// Trigger start of action when pen/mouse is pressed
if (event.type == BUTTON_PRESS_EVENT) {
if (pressedButton == BUTTON_NONE || !inputRunning) {
pressedButton = event.button;
this->actionStart(event);
} else if (event.button == pressedButton) {
g_warning("MouseInputHandler: Double BUTTON_PRESS_EVENT on button %u", event.button);
}
return true;
}
if (event.type == BUTTON_2_PRESS_EVENT || event.type == BUTTON_3_PRESS_EVENT) {
this->actionPerform(event);
return true;
}
/*
* Trigger motion actions
*/
// Trigger motion action when pen/mouse is pressed and moved
if (event.type == MOTION_EVENT) // mouse or pen moved
{
this->actionMotion(event);
XournalppCursor* cursor = xournal->view->getCursor();
cursor->setInvisible(false);
cursor->updateCursor();
}
// Notify if mouse enters/leaves widget
if (event.type == ENTER_EVENT) {
this->actionEnterWindow(event);
}
if (event.type == LEAVE_EVENT) {
// this->inputContext->unblockDevice(InputContext::TOUCHSCREEN);
// this->inputContext->getView()->getHandRecognition()->unblock();
this->actionLeaveWindow(event);
}
// Trigger end of action if mouse button is released
if (event.type == BUTTON_RELEASE_EVENT) {
if (event.button == pressedButton) {
pressedButton = BUTTON_NONE;
this->actionEnd(event);
}
return true;
}
// If we loose our Grab on the device end the current action
if (event.type == GRAB_BROKEN_EVENT && this->deviceClassPressed) {
// TODO(fabian): We may need to update pressed state manually here
pressedButton = BUTTON_NONE;
this->actionEnd(event);
return true;
}
return false;
}
void MouseInputHandler::setPressedState(InputEvent const& event) {
XojPageView* currentPage = getPageAtCurrentPosition(event);
this->inputContext->getXournal()->view->getCursor()->setInsidePage(currentPage != nullptr);
if (event.type == BUTTON_PRESS_EVENT) // mouse button pressed or pen touching surface
{
this->deviceClassPressed = true;
switch (event.button) {
case 2:
this->modifier2 = true;
break;
case 3:
this->modifier3 = true;
default:
break;
}
}
if (event.type == BUTTON_RELEASE_EVENT) // mouse button released or pen not touching surface anymore
{
this->deviceClassPressed = false;
switch (event.button) {
case 2:
this->modifier2 = false;
break;
case 3:
this->modifier3 = false;
default:
break;
}
}
}
auto MouseInputHandler::changeTool(InputEvent const& event) -> bool {
Settings* settings = this->inputContext->getSettings();
ToolHandler* toolHandler = this->inputContext->getToolHandler();
bool isClickOnSelection = this->inputContext->getXournal()->selection;
bool toolChanged = false;
if (modifier2 && !isClickOnSelection)
toolChanged = InputUtils::applyButton(toolHandler, settings, Button::BUTTON_MOUSE_MIDDLE);
else if (modifier3 && !isClickOnSelection)
toolChanged = InputUtils::applyButton(toolHandler, settings, Button::BUTTON_MOUSE_RIGHT);
else
toolChanged = toolHandler->pointActiveToolToToolbarTool();
if (toolChanged) {
ToolType toolType = toolHandler->getToolType();
if (toolType == TOOL_TEXT)
toolHandler->selectTool(toolType);
toolHandler->fireToolChanged();
}
return true;
}
void MouseInputHandler::onBlock() {}
| 5,002
|
C++
|
.cpp
| 126
| 32.65873
| 105
| 0.650381
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,617
|
InputContext.cpp
|
xournalpp_xournalpp/src/core/gui/inputdevices/InputContext.cpp
|
//
// Created by ulrich on 06.04.19.
//
#include "InputContext.h"
#include <cstddef> // for NULL
#include <vector> // for vector
#include <glib-object.h> // for g_signal_hand...
#include "control/Control.h" // for Control
#include "control/DeviceListHelper.h" // for InputDevice
#include "control/settings/Settings.h" // for Settings
#include "gui/XournalView.h" // for XournalView
#include "gui/inputdevices/GeometryToolInputHandler.h" // for GeometryToolInputHandler
#include "gui/inputdevices/HandRecognition.h" // for HandRecognition
#include "gui/inputdevices/KeyboardInputHandler.h" // for KeyboardInput...
#include "gui/inputdevices/MouseInputHandler.h" // for MouseInputHan...
#include "gui/inputdevices/StylusInputHandler.h" // for StylusInputHa...
#include "gui/inputdevices/TouchDrawingInputHandler.h" // for TouchDrawingI...
#include "gui/inputdevices/TouchInputHandler.h" // for TouchInputHan...
#include "util/Assert.h" // for xoj_assert
#include "util/gdk4_helper.h"
#include "util/glib_casts.h" // for wrap_for_g_callback
#include "util/gtk4_helper.h"
#include "InputEvents.h" // for InputEvent
#include "config-debug.h" // for DEBUG_INPUT
class ScrollHandling;
class ToolHandler;
InputContext::InputContext(XournalView* view, ScrollHandling* scrollHandling) {
this->view = view;
this->scrollHandling = scrollHandling;
this->stylusHandler = new StylusInputHandler(this);
this->touchHandler = new TouchInputHandler(this);
this->touchDrawingHandler = new TouchDrawingInputHandler(this);
this->mouseHandler = new MouseInputHandler(this);
this->keyboardHandler = new KeyboardInputHandler(this);
for (const InputDevice& savedDevices: this->view->getControl()->getSettings()->getKnownInputDevices()) {
this->knownDevices.insert(savedDevices.getName());
}
}
template <bool (KeyboardInputHandler::*handler)(KeyEvent) const>
static gboolean keyboardCallback(GtkEventControllerKey* self, guint keyval, guint, GdkModifierType state, gpointer d) {
auto* gdkEvent = gtk_event_controller_get_current_event(GTK_EVENT_CONTROLLER(self));
KeyEvent e;
e.keyval = keyval;
e.state = static_cast<GdkModifierType>(state & gtk_accelerator_get_default_mod_mask() &
~gdk_key_event_get_consumed_modifiers(gdkEvent));
e.sourceEvent = gdkEvent;
return (static_cast<KeyboardInputHandler*>(d)->*handler)(e);
}
InputContext::~InputContext() {
// Destructor is called in xournal_widget_dispose, so it can still accept events
g_signal_handler_disconnect(this->widget, signal_id);
delete this->stylusHandler;
this->stylusHandler = nullptr;
delete this->touchHandler;
this->touchHandler = nullptr;
delete this->touchDrawingHandler;
this->touchDrawingHandler = nullptr;
delete this->mouseHandler;
this->mouseHandler = nullptr;
delete this->keyboardHandler;
this->keyboardHandler = nullptr;
}
void InputContext::connect(GtkWidget* pWidget) {
xoj_assert(!this->widget && pWidget);
this->widget = pWidget;
gtk_widget_set_support_multidevice(widget, true);
#if GTK_MAJOR_VERSION == 3
auto* keyCtrl = gtk_event_controller_key_new(widget);
#else
auto* keyCtrl = gtk_event_controller_key_new();
gtk_widget_add_controller(keyCtrl);
#endif
g_signal_connect(keyCtrl, "key-pressed", G_CALLBACK(keyboardCallback<&KeyboardInputHandler::keyPressed>),
keyboardHandler);
g_signal_connect(keyCtrl, "key-released", G_CALLBACK(keyboardCallback<&KeyboardInputHandler::keyReleased>),
keyboardHandler);
int mask =
// Allow scrolling
GDK_SCROLL_MASK |
// Touch / Pen / Mouse
GDK_TOUCH_MASK | GDK_POINTER_MOTION_MASK | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK |
GDK_SMOOTH_SCROLL_MASK | GDK_ENTER_NOTIFY_MASK | GDK_LEAVE_NOTIFY_MASK | GDK_PROXIMITY_IN_MASK |
GDK_PROXIMITY_OUT_MASK;
gtk_widget_add_events(pWidget, mask);
signal_id = g_signal_connect(pWidget, "event", xoj::util::wrap_for_g_callback_v<eventCallback>, this);
}
auto InputContext::eventCallback(GtkWidget* widget, GdkEvent* event, InputContext* self) -> bool {
return self->handle(event);
}
auto InputContext::handle(GdkEvent* sourceEvent) -> bool {
printDebug(sourceEvent);
GdkDevice* sourceDevice = gdk_event_get_source_device(sourceEvent);
if (sourceDevice == NULL) {
return false;
}
InputEvent event = InputEvents::translateEvent(sourceEvent, this->getSettings());
// Add the device to the list of known devices if it is currently unknown
GdkInputSource inputSource = gdk_device_get_source(sourceDevice);
if (inputSource != GDK_SOURCE_KEYBOARD && gdk_device_get_device_type(sourceDevice) != GDK_DEVICE_TYPE_MASTER &&
this->knownDevices.find(std::string(event.deviceName)) == this->knownDevices.end()) {
this->knownDevices.insert(std::string(event.deviceName));
this->getSettings()->transactionStart();
auto deviceClassOption =
this->getSettings()->getDeviceClassForDevice(std::string(event.deviceName), inputSource);
this->getSettings()->setDeviceClassForDevice(sourceDevice, deviceClassOption);
this->getSettings()->transactionEnd();
}
// We do not handle scroll events manually but let GTK do it for us
if (event.type == SCROLL_EVENT) {
// Hand over to standard GTK Scroll / Zoom handling
return false;
}
// Deactivate touchscreen when a pen event occurs
this->getView()->getHandRecognition()->event(event.deviceClass);
// Get the state of all modifiers
this->modifierState = event.state;
// separate events to appropriate handlers
// handle geometry tool
if (geometryToolInputHandler && geometryToolInputHandler->handle(event)) {
return true;
}
// handle tablet stylus
if (event.deviceClass == INPUT_DEVICE_PEN || event.deviceClass == INPUT_DEVICE_ERASER) {
return this->stylusHandler->handle(event);
}
// handle mouse devices
if (event.deviceClass == INPUT_DEVICE_MOUSE || event.deviceClass == INPUT_DEVICE_MOUSE_KEYBOARD_COMBO) {
return this->mouseHandler->handle(event);
}
// handle touchscreens
if (event.deviceClass == INPUT_DEVICE_TOUCHSCREEN) {
bool touchDrawingEnabled = this->getSettings()->getTouchDrawingEnabled();
// trigger touch drawing depending on the setting
if (touchDrawingEnabled) {
return this->touchDrawingHandler->handle(event) || this->touchHandler->handle(event);
}
return this->touchHandler->handle(event);
}
if (event.deviceClass == INPUT_DEVICE_IGNORE) {
return true;
}
#ifdef DEBUG_INPUT
if (event.deviceClass != INPUT_DEVICE_KEYBOARD) { // Keyboard event are handled via the GtkEventControllerKey
g_message("We received an event we do not have a handler for");
}
#endif
return false;
}
auto InputContext::getXournal() -> GtkXournal* { return GTK_XOURNAL(widget); }
auto InputContext::getView() -> XournalView* { return view; }
auto InputContext::getSettings() -> Settings* { return view->getControl()->getSettings(); }
auto InputContext::getToolHandler() -> ToolHandler* { return view->getControl()->getToolHandler(); }
auto InputContext::getScrollHandling() -> ScrollHandling* { return this->scrollHandling; }
void InputContext::setGeometryToolInputHandler(std::unique_ptr<GeometryToolInputHandler> handler) {
this->geometryToolInputHandler = std::move(handler);
}
auto InputContext::getGeometryToolInputHandler() const -> GeometryToolInputHandler* {
return geometryToolInputHandler.get();
}
void InputContext::resetGeometryToolInputHandler() { this->geometryToolInputHandler.reset(); }
auto InputContext::getModifierState() -> GdkModifierType { return this->modifierState; }
/**
* Focus the widget
*/
void InputContext::focusWidget() {
if (!gtk_widget_has_focus(widget)) {
gtk_widget_grab_focus(widget);
}
}
void InputContext::blockDevice(InputContext::DeviceType deviceType) {
if (geometryToolInputHandler) {
geometryToolInputHandler->blockDevice(deviceType);
}
switch (deviceType) {
case MOUSE:
this->mouseHandler->block(true);
break;
case STYLUS:
this->stylusHandler->block(true);
break;
case TOUCHSCREEN:
this->touchDrawingHandler->block(true);
this->touchHandler->block(true);
break;
}
}
void InputContext::unblockDevice(InputContext::DeviceType deviceType) {
if (geometryToolInputHandler) {
geometryToolInputHandler->unblockDevice(deviceType);
}
switch (deviceType) {
case MOUSE:
this->mouseHandler->block(false);
break;
case STYLUS:
this->stylusHandler->block(false);
break;
case TOUCHSCREEN:
this->touchDrawingHandler->block(false);
this->touchHandler->block(false);
break;
}
}
auto InputContext::isBlocked(InputContext::DeviceType deviceType) -> bool {
switch (deviceType) {
case MOUSE:
return this->mouseHandler->isBlocked();
case STYLUS:
return this->stylusHandler->isBlocked();
case TOUCHSCREEN:
return this->touchDrawingHandler->isBlocked();
}
return false;
}
void InputContext::printDebug(GdkEvent* event) {
#ifdef DEBUG_INPUT_GDK_PRINT_EVENTS
gdk_set_show_events(true);
#else
#ifdef DEBUG_INPUT
std::string message = "Event\n";
std::string gdkEventTypes[] = {"GDK_NOTHING",
"GDK_DELETE",
"GDK_DESTROY",
"GDK_EXPOSE",
"GDK_MOTION_NOTIFY",
"GDK_BUTTON_PRESS",
"GDK_DOUBLE_BUTTON_PRESS",
"GDK_TRIPLE_BUTTON_PRESS",
"GDK_BUTTON_RELEASE",
"GDK_KEY_PRESS",
"GDK_KEY_RELEASE",
"GDK_ENTER_NOTIFY",
"GDK_LEAVE_NOTIFY",
"GDK_FOCUS_CHANGE",
"GDK_CONFIGURE",
"GDK_MAP",
"GDK_UNMAP",
"GDK_PROPERTY_NOTIFY",
"GDK_SELECTION_CLEAR",
"GDK_SELECTION_REQUEST",
"GDK_SELECTION_NOTIFY",
"GDK_PROXIMITY_IN",
"GDK_PROXIMITY_OUT",
"GDK_DRAG_ENTER",
"GDK_DRAG_LEAVE",
"GDK_DRAG_MOTION",
"GDK_DRAG_STATUS",
"GDK_DROP_START",
"GDK_DROP_FINISHED",
"GDK_CLIENT_EVENT",
"GDK_VISIBILITY_NOTIFY",
"",
"GDK_SCROLL",
"GDK_WINDOW_STATE",
"GDK_SETTING",
"GDK_OWNER_CHANGE",
"GDK_GRAB_BROKEN",
"GDK_DAMAGE",
"GDK_TOUCH_BEGIN",
"GDK_TOUCH_UPDATE",
"GDK_TOUCH_END",
"GDK_TOUCH_CANCEL",
"GDK_TOUCHPAD_SWIPE",
"GDK_TOUCHPAD_PINCH",
"GDK_PAD_BUTTON_PRESS",
"GDK_PAD_BUTTON_RELEASE",
"GDK_PAD_RING",
"GDK_PAD_STRIP",
"GDK_PAD_GROUP_MODE",
"GDK_EVENT_LAST"};
message += "Event type:\t" + gdkEventTypes[gdk_event_get_event_type(event) + 1] + "\n";
std::string gdkInputSources[] = {"GDK_SOURCE_MOUSE", "GDK_SOURCE_PEN", "GDK_SOURCE_ERASER",
"GDK_SOURCE_CURSOR", "GDK_SOURCE_KEYBOARD", "GDK_SOURCE_TOUCHSCREEN",
"GDK_SOURCE_TOUCHPAD", "GDK_SOURCE_TRACKPOINT", "GDK_SOURCE_TABLET_PAD"};
GdkDevice* device = gdk_event_get_source_device(event);
message += "Source device:\t" + gdkInputSources[gdk_device_get_source(device)] + "\n";
std::string gdkInputClasses[] = {"INPUT_DEVICE_MOUSE", "INPUT_DEVICE_PEN",
"INPUT_DEVICE_ERASER", "INPUT_DEVICE_TOUCHSCREEN",
"INPUT_DEVICE_KEYBOARD", "INPUT_DEVICE_MOUSE_KEYBOARD_COMBO",
"INPUT_DEVICE_IGNORE"};
InputDeviceClass deviceClass = InputEvents::translateDeviceType(device, this->getSettings());
message += "Device Class:\t" + gdkInputClasses[deviceClass] + "\n";
if (gdk_event_get_event_type(event) == GDK_BUTTON_PRESS ||
gdk_event_get_event_type(event) == GDK_DOUBLE_BUTTON_PRESS ||
gdk_event_get_event_type(event) == GDK_TRIPLE_BUTTON_PRESS ||
gdk_event_get_event_type(event) == GDK_BUTTON_RELEASE) {
guint button;
if (gdk_event_get_button(event, &button)) {
message += "Button:\t" + std::to_string(button) + "\n";
}
}
#ifndef DEBUG_INPUT_PRINT_ALL_MOTION_EVENTS
static bool motionEventBlock = false;
if (gdk_event_get_event_type(event) == GDK_MOTION_NOTIFY) {
if (!motionEventBlock) {
motionEventBlock = true;
g_message("%s", message.c_str());
}
} else {
motionEventBlock = false;
g_message("%s", message.c_str());
}
#else
g_message("%s", message.c_str());
#endif // DEBUG_INPUT_PRINT_ALL_MOTION_EVENTS
#endif // DEBUG_INPUT
#endif // DEBUG_INPUT_PRINT_EVENTS
}
| 14,570
|
C++
|
.cpp
| 308
| 36.107143
| 119
| 0.597719
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,618
|
InputUtils.cpp
|
xournalpp_xournalpp/src/core/gui/inputdevices/InputUtils.cpp
|
#include "InputUtils.h"
#include <glib.h> // for g_message
#include "control/ToolEnums.h" // for TOOL_NONE
#include "control/ToolHandler.h" // for ToolHandler
#include "control/settings/ButtonConfig.h" // for ButtonConfig
#include "control/settings/Settings.h" // for Settings
#include "control/settings/SettingsEnums.h" // for Button, BUTTON_TOUCH
bool InputUtils::applyButton(ToolHandler* toolHandler, Settings* settings, Button button) {
bool toolChanged = false;
// if active tool already points to the correct tool nothing needs to be done
if (toolHandler->pointActiveToolToButtonTool(button)) {
toolChanged = true;
ButtonConfig* cfg = settings->getButtonConfig(button);
// if ToolChange is not activated for this button stay with ToolBartool
if (cfg->getAction() == TOOL_NONE)
toolChanged = toolHandler->pointActiveToolToToolbarTool();
else
cfg->applyNoChangeSettings(toolHandler, button);
}
return toolChanged;
}
bool InputUtils::touchDrawingDisallowed(ToolHandler* toolHandler, Settings* settings) {
static bool warningAlreadyShown{false};
ButtonConfig* cfg = settings->getButtonConfig(Button::BUTTON_TOUCH);
if (cfg->getDisableDrawing() && cfg->getAction() == TOOL_NONE && toolHandler->isDrawingTool()) {
if (!warningAlreadyShown)
g_message("Ignoring touchscreen for drawing:\n"
" Please check the settings for Touchscreen.\n"
" The current combination of \"Disable Drawing for this device\"\n"
" together with \"Tool - don't change\"\n"
" prevents any drawing with the selected tool using the TouchScreen.");
warningAlreadyShown = true;
return true;
}
// reset warningAlreadyShown this allows the message to be sent multiple times
// in case the user switches the settings in between multiple times
warningAlreadyShown = false;
return false;
}
| 2,036
|
C++
|
.cpp
| 39
| 44.897436
| 100
| 0.684581
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,619
|
StylusInputHandler.cpp
|
xournalpp_xournalpp/src/core/gui/inputdevices/StylusInputHandler.cpp
|
//
// Created by ulrich on 08.04.19.
//
#include "StylusInputHandler.h"
#include <cmath> // for abs
#include <glib.h> // for g_message
#include "control/ToolHandler.h" // for ToolHandler
#include "control/settings/Settings.h" // for Settings
#include "control/settings/SettingsEnums.h" // for Button, BUTTON_ERASER
#include "gui/PageView.h" // for XojPageView
#include "gui/XournalView.h" // for XournalView
#include "gui/XournalppCursor.h" // for XournalppCursor
#include "gui/inputdevices/HandRecognition.h" // for HandRecognition
#include "gui/inputdevices/InputEvents.h" // for InputEvent, BUTTON_P...
#include "gui/inputdevices/PenInputHandler.h" // for PenInputHandler
#include "gui/inputdevices/PositionInputData.h" // for PositionInputData
#include "gui/widgets/XournalWidget.h" // for GtkXournal
#include "InputContext.h" // for InputContext
#include "InputUtils.h" // for InputUtils
StylusInputHandler::StylusInputHandler(InputContext* inputContext): PenInputHandler(inputContext) {}
StylusInputHandler::~StylusInputHandler() = default;
auto StylusInputHandler::handleImpl(InputEvent const& event) -> bool {
// Only handle events when there is no active gesture
GtkXournal* xournal = inputContext->getXournal();
// Determine the pressed states of devices and associate them to the current event
setPressedState(event);
// Trigger start of action when pen/mouse is pressed
if (event.type == BUTTON_PRESS_EVENT) {
if (event.button == 1 || this->inputContext->getSettings()->getInputSystemTPCButtonEnabled()) {
this->eventsToIgnore = this->inputContext->getSettings()->getIgnoredStylusEvents();
if (this->eventsToIgnore > 0) {
this->eventsToIgnore--; // This is already the first ignored event
} else {
this->eventsToIgnore = -1;
this->actionStart(event);
}
return true;
}
if (this->inputRunning) {
// TPCButton is disabled and modifier button was pressed
this->actionEnd(event);
this->actionStart(event);
} else {
// No input running but modifier key was pressed
// Change the tool depending on the key
changeTool(event);
XojPageView* currentPage = getPageAtCurrentPosition(event);
if (currentPage) {
PositionInputData pos = this->getInputDataRelativeToCurrentPage(currentPage, event);
currentPage->onButtonClickEvent(pos);
}
}
}
// Trigger discrete action on double tap
if (event.type == BUTTON_2_PRESS_EVENT || event.type == BUTTON_3_PRESS_EVENT) {
this->actionPerform(event);
return true;
}
// Trigger motion action when pen/mouse is pressed and moved
if (event.type == MOTION_EVENT) // mouse or pen moved
{
if (this->eventsToIgnore > 0) {
this->eventsToIgnore--;
} else if (this->eventsToIgnore == 0) {
this->eventsToIgnore = -1;
this->actionStart(event);
} else {
this->actionMotion(event);
}
XournalppCursor* cursor = xournal->view->getCursor();
cursor->setInvisible(false);
cursor->updateCursor();
}
// Check if enter/leave events occur in possible locations. This is a bug of the hardware (there are such devices!)
if ((event.type == ENTER_EVENT || event.type == LEAVE_EVENT) && this->deviceClassPressed && this->lastEvent) {
if (std::abs(event.relativeX - lastEvent.relativeX) > 100 ||
std::abs(event.relativeY - lastEvent.relativeY) > 100) {
g_message("Discard impossible event - this is a sign of bugged hardware or drivers");
return true;
}
}
// Notify if pen enters/leaves widget
if (event.type == ENTER_EVENT && !this->inputRunning) {
this->actionEnterWindow(event);
}
if (event.type == LEAVE_EVENT) {
this->inputContext->getView()->getHandRecognition()->unblock();
this->actionLeaveWindow(event);
}
// Trigger end of action if pen tip leaves screen or mouse button is released
if (event.type == BUTTON_RELEASE_EVENT) {
if (event.button == 1 || this->inputContext->getSettings()->getInputSystemTPCButtonEnabled()) {
if (this->eventsToIgnore < 0) {
this->actionEnd(event);
} else {
this->eventsToIgnore = -1;
}
return true;
}
if (this->inputRunning) {
// TPCButton is disabled and modifier button was released
this->actionEnd(event);
this->actionStart(event);
} else {
// No input running but modifier key was pressed
// Change the tool depending on the key
changeTool(event);
}
}
// If we loose our Grab on the device end the current action
if (event.type == GRAB_BROKEN_EVENT && this->deviceClassPressed) {
// TODO(fabian): We may need to update pressed state manually here
this->actionEnd(event);
return true;
}
return false;
}
void StylusInputHandler::setPressedState(InputEvent const& event) {
XojPageView* currentPage = getPageAtCurrentPosition(event);
this->inputContext->getXournal()->view->getCursor()->setInsidePage(currentPage != nullptr);
if (event.type == BUTTON_PRESS_EVENT) // mouse button pressed or pen touching surface
{
switch (event.button) {
case 1:
if (this->inputContext->getSettings()->getIgnoredStylusEvents() <= 0) {
this->deviceClassPressed = true;
}
break;
case 2:
this->modifier2 = true;
break;
case 3:
this->modifier3 = true;
default:
break;
}
} else if (event.type == MOTION_EVENT) {
if (this->eventsToIgnore == 0) {
this->deviceClassPressed = true;
}
} else if (event.type == BUTTON_RELEASE_EVENT) // mouse button released or pen not touching surface anymore
{
switch (event.button) {
case 1:
this->deviceClassPressed = false;
break;
case 2:
this->modifier2 = false;
if (this->inputContext->getSettings()->getInputSystemTPCButtonEnabled()) {
this->deviceClassPressed = false;
}
break;
case 3:
this->modifier3 = false;
if (this->inputContext->getSettings()->getInputSystemTPCButtonEnabled()) {
this->deviceClassPressed = false;
}
default:
break;
}
}
}
auto StylusInputHandler::changeTool(InputEvent const& event) -> bool {
Settings* settings = this->inputContext->getSettings();
ToolHandler* toolHandler = this->inputContext->getToolHandler();
bool toolChanged = false;
if (event.deviceClass == INPUT_DEVICE_PEN && this->modifier2)
toolChanged = InputUtils::applyButton(toolHandler, settings, Button::BUTTON_STYLUS_ONE);
else if (event.deviceClass == INPUT_DEVICE_PEN && this->modifier3)
toolChanged = InputUtils::applyButton(toolHandler, settings, Button::BUTTON_STYLUS_TWO);
else if (event.deviceClass == INPUT_DEVICE_ERASER)
toolChanged = InputUtils::applyButton(toolHandler, settings, Button::BUTTON_ERASER);
else
toolChanged = toolHandler->pointActiveToolToToolbarTool();
if (toolChanged) {
ToolType toolType = toolHandler->getToolType();
if (toolType == TOOL_TEXT)
toolHandler->selectTool(toolType);
toolHandler->fireToolChanged();
}
return true;
}
| 8,002
|
C++
|
.cpp
| 182
| 34.884615
| 119
| 0.617221
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,620
|
GeometryToolInputHandler.cpp
|
xournalpp_xournalpp/src/core/gui/inputdevices/GeometryToolInputHandler.cpp
|
#include "GeometryToolInputHandler.h"
#include <algorithm> // for max
#include <cmath> // for atan2, abs, cos, remainder
#include <memory> // for __shared_ptr_access, shar...
#include <gdk/gdkkeysyms.h> // for GDK_KEY_Down, GDK_KEY_Left
#include <glib.h> // for g_warning
#include "control/Control.h" // for Control
#include "control/GeometryToolController.h" // for GeometryToolController
#include "control/ToolEnums.h" // for TOOL_HAND, TOOL_HIGHLIGHTER
#include "control/ToolHandler.h" // for ToolHandler
#include "control/settings/Settings.h" // for Settings
#include "gui/XournalView.h" // for XournalView
#include "gui/inputdevices/InputContext.h" // for InputContext::DeviceType
#include "gui/inputdevices/InputEvents.h" // for InputEvent, BUTTON_PRESS_...
#include "model/Document.h" // for Document
#include "model/Element.h" // for Element, ELEMENT_STROKE
#include "model/GeometryTool.h" // for HALF_CM
#include "model/Layer.h" // for Layer
#include "model/Snapping.h" // for distanceLine
#include "model/Stroke.h" // for Stroke
#include "model/XojPage.h" // for XojPage
constexpr double MOVE_AMOUNT = HALF_CM / 2.0;
constexpr double MOVE_AMOUNT_SMALL = HALF_CM / 20.0;
constexpr double ROTATE_AMOUNT = M_PI * 5.0 / 180.0;
constexpr double ROTATE_AMOUNT_SMALL = M_PI * 0.2 / 180.0;
constexpr double SCALE_AMOUNT = 1.1;
constexpr double SCALE_AMOUNT_SMALL = 1.01;
constexpr double SNAPPING_DISTANCE_TOLERANCE = 5.0; // pt
constexpr double SNAPPING_ROTATION_TOLERANCE = 3.0 * M_PI / 180.0; // rad
constexpr double ZOOM_DISTANCE_MIN = 0.01;
GeometryToolInputHandler::GeometryToolInputHandler(XournalView* xournal, GeometryToolController* controller, double h,
double tx, double ty):
xournal(xournal), controller(controller), height(h), translationX(tx), translationY(ty) {}
GeometryToolInputHandler::~GeometryToolInputHandler() = default;
auto GeometryToolInputHandler::handle(InputEvent const& event) -> bool {
if (xournal->getSelection() || xournal->getControl()->getTextEditor()) {
return false;
}
const auto device = event.deviceClass;
if ((device == INPUT_DEVICE_MOUSE && isBlocked[InputContext::DeviceType::MOUSE]) ||
(device == INPUT_DEVICE_PEN && isBlocked[InputContext::DeviceType::STYLUS]) ||
(device == INPUT_DEVICE_TOUCHSCREEN && isBlocked[InputContext::DeviceType::TOUCHSCREEN])) {
return false; // don't intervene
}
switch (device) {
case INPUT_DEVICE_KEYBOARD:
return false; // Handled via GtkEventControllerKey in InputContext
case INPUT_DEVICE_TOUCHSCREEN:
return this->handleTouchscreen(event);
case INPUT_DEVICE_PEN:
case INPUT_DEVICE_MOUSE:
case INPUT_DEVICE_MOUSE_KEYBOARD_COMBO:
return this->handlePointer(event);
default:
g_warning("Device class %d not handled by geometry tool", event.deviceClass);
return false;
}
}
void GeometryToolInputHandler::on(UpdateValuesRequest, double h, double rot, double tx, double ty) {
height = h;
rotation = rot;
translationX = tx;
translationY = ty;
}
auto GeometryToolInputHandler::handleTouchscreen(InputEvent const& event) -> bool {
// Don't handle more than 2 inputs
if (this->primarySequence && this->primarySequence != event.sequence && this->secondarySequence &&
this->secondarySequence != event.sequence) {
return false;
}
if (event.type == BUTTON_PRESS_EVENT) {
// Start scrolling when a sequence starts and we currently have none other
if (this->primarySequence == nullptr && this->secondarySequence == nullptr) {
const xoj::util::Point<double> coords = getCoords(event);
if (controller->isInsideGeometryTool(coords.x, coords.y, 0)) {
// Set sequence data
this->primarySequence = event.sequence;
sequenceStart(event);
return true;
} else {
return false;
}
}
// Start zooming as soon as we have two sequences.
else if (this->primarySequence && this->primarySequence != event.sequence &&
this->secondarySequence == nullptr) {
this->secondarySequence = event.sequence;
// Set sequence data
sequenceStart(event);
rotateAndZoomStart();
return true;
}
}
if (event.type == MOTION_EVENT && this->primarySequence) {
if (this->secondarySequence) {
rotateAndZoomMotion(event);
return true;
} else if (event.sequence == this->primarySequence) {
scrollMotion(event);
return true;
}
return false;
}
if (event.type == BUTTON_RELEASE_EVENT) {
if (event.sequence == this->primarySequence) {
// If secondarySequence is nullptr, this sets primarySequence
// to nullptr. If it isn't, then it is now the primary sequence!
this->primarySequence = std::exchange(this->secondarySequence, nullptr);
this->priLastPageRel = this->secLastPageRel;
return true;
} else if (event.sequence == this->secondarySequence) {
this->secondarySequence = nullptr;
return true;
}
}
return false;
}
auto GeometryToolInputHandler::keyPressed(KeyEvent const& event) -> bool {
double xdir = 0;
double ydir = 0;
double angle = 0.0;
double scale = 1.0;
switch (event.keyval) {
case GDK_KEY_Left:
xdir = -1;
break;
case GDK_KEY_Up:
ydir = -1;
break;
case GDK_KEY_Right:
xdir = 1;
break;
case GDK_KEY_Down:
ydir = 1;
break;
case GDK_KEY_r:
angle = (event.state & GDK_MOD1_MASK) ? -ROTATE_AMOUNT_SMALL : -ROTATE_AMOUNT;
break;
case GDK_KEY_R: // r like "rotate"
angle = (event.state & GDK_MOD1_MASK) ? ROTATE_AMOUNT_SMALL : ROTATE_AMOUNT;
break;
case GDK_KEY_s:
scale = (event.state & GDK_MOD1_MASK) ? SCALE_AMOUNT_SMALL : SCALE_AMOUNT;
break;
case GDK_KEY_S:
scale = (event.state & GDK_MOD1_MASK) ? 1. / SCALE_AMOUNT_SMALL : 1. / SCALE_AMOUNT;
break;
case GDK_KEY_m:
controller->markPoint(translationX, translationY);
return true;
}
if (xdir != 0 || ydir != 0) {
const double c = std::cos(rotation);
const double s = std::sin(rotation);
double xshift{0.0};
double yshift{0.0};
const double amount = (event.state & GDK_MOD1_MASK) ? MOVE_AMOUNT_SMALL : MOVE_AMOUNT;
if (event.state & GDK_SHIFT_MASK) {
xshift = amount * (c * xdir - s * ydir);
yshift = amount * (s * xdir + c * ydir);
} else {
xshift = amount * xdir;
yshift = amount * ydir;
}
controller->translate(xshift, yshift);
return true;
}
auto p = xoj::util::Point(translationX, translationY);
if (angle != 0) {
controller->rotate(angle, p.x, p.y);
return true;
}
if (scale != 1.0) {
const double h = height * scale;
if (h <= getMaxHeight() && h >= getMinHeight()) {
controller->scale(scale, p.x, p.y);
return true;
}
}
return false;
}
void GeometryToolInputHandler::sequenceStart(InputEvent const& event) {
if (event.sequence == this->primarySequence) {
this->priLastPageRel = this->getCoords(event);
} else {
this->secLastPageRel = this->getCoords(event);
}
const auto page = controller->getPage();
const Layer* layer = page->getSelectedLayer();
this->lines.clear();
Document* doc = xournal->getDocument();
doc->lock();
// Performance improvement might be obtained by avoiding filtering all elements each
// time a finger has been put onto the screen
for (const auto& e: layer->getElements()) {
if (e->getType() == ELEMENT_STROKE) {
auto* s = dynamic_cast<Stroke*>(e.get());
if (s->getPointCount() == 2) {
lines.push_back(s);
}
}
}
doc->unlock();
}
void GeometryToolInputHandler::scrollMotion(InputEvent const& event) {
// Will only be called if there is a single sequence (rotation/zooming handles two sequences)
auto offset = [&]() {
xoj::util::Point<double> coords = this->getCoords(event);
if (event.sequence == this->primarySequence) {
const xoj::util::Point<double> offset = coords - this->priLastPageRel;
this->priLastPageRel = coords;
return offset;
} else {
const xoj::util::Point<double> offset = coords - this->secLastPageRel;
this->secLastPageRel = coords;
return offset;
}
}();
const auto pos = Point(translationX + offset.x, translationY + offset.y);
double minDist = SNAPPING_DISTANCE_TOLERANCE;
double diffAngle{NAN};
for (const auto& l: lines) {
const Point first = l->getPoint(0);
const Point second = l->getPoint(1);
const double dist = Snapping::distanceLine(pos, first, second);
const double angleLine = std::atan2(second.y - first.y, second.x - first.x);
const double diff = std::remainder(angleLine - rotation, M_PI_2);
if (dist < minDist && std::abs(diff) <= SNAPPING_ROTATION_TOLERANCE) {
minDist = dist;
diffAngle = diff;
}
}
if (!std::isnan(diffAngle)) {
controller->rotate(diffAngle, pos.x, pos.y);
}
controller->translate(offset.x, offset.y);
}
void GeometryToolInputHandler::rotateAndZoomStart() {
this->startZoomDistance = std::max(this->priLastPageRel.distance(this->secLastPageRel), ZOOM_DISTANCE_MIN);
// Whether we can ignore the zoom portion of the gesture (e.g. distance between touch points
// hasn't changed enough or zoom gestures are disabled).
this->canBlockZoom = true;
this->lastZoomScrollCenter = (this->priLastPageRel + this->secLastPageRel) / 2.0;
const xoj::util::Point<double> shift = this->secLastPageRel - this->priLastPageRel;
this->lastAngle = atan2(shift.y, shift.x);
this->lastDist = this->startZoomDistance;
}
void GeometryToolInputHandler::rotateAndZoomMotion(InputEvent const& event) {
if (event.sequence == this->primarySequence) {
this->priLastPageRel = this->getCoords(event);
} else {
this->secLastPageRel = this->getCoords(event);
}
const double dist = std::max(this->priLastPageRel.distance(this->secLastPageRel), ZOOM_DISTANCE_MIN);
const double zoomTriggerThreshold = xournal->getControl()->getSettings()->getTouchZoomStartThreshold();
const double zoomChangePercentage = std::abs(dist - startZoomDistance) / startZoomDistance * 100;
// Has the touch points moved far enough to trigger a zoom and are zoom gestures enabled?
const bool zoomGesturesEnabled = xournal->getControl()->getSettings()->isZoomGesturesEnabled();
if (zoomChangePercentage >= zoomTriggerThreshold && zoomGesturesEnabled) {
this->canBlockZoom = false;
}
const xoj::util::Point<double> center = (this->priLastPageRel + this->secLastPageRel) / 2;
const xoj::util::Point<double> shift = this->secLastPageRel - this->priLastPageRel;
const double angle = atan2(shift.y, shift.x);
const xoj::util::Point<double> offset = center - lastZoomScrollCenter;
controller->translate(offset.x, offset.y);
const double angleIncrease = angle - lastAngle;
const xoj::util::Point<double> centerRel = (this->priLastPageRel + this->secLastPageRel) / 2.0;
if (controller->isInsideGeometryTool(secLastPageRel.x, secLastPageRel.y, 0.0)) {
controller->rotate(angleIncrease, centerRel.x, centerRel.y);
} // allow moving without accidental rotation
const double scaleFactor = dist / lastDist;
const double h = height * scaleFactor;
if (!canBlockZoom && h <= getMaxHeight() && h >= getMinHeight()) {
controller->scale(scaleFactor, centerRel.x, centerRel.y);
}
this->lastZoomScrollCenter = center;
this->lastAngle = angle;
this->lastDist = dist;
}
auto GeometryToolInputHandler::getCoords(InputEvent const& event) -> xoj::util::Point<double> {
const double zoom = xournal->getZoom();
const auto view = controller->getView();
const double posX = event.relativeX - static_cast<double>(view->getX());
const double posY = event.relativeY - static_cast<double>(view->getY());
return xoj::util::Point<double>(posX / zoom, posY / zoom);
}
void GeometryToolInputHandler::blockDevice(InputContext::DeviceType deviceType) { isBlocked[deviceType] = true; }
void GeometryToolInputHandler::unblockDevice(InputContext::DeviceType deviceType) { isBlocked[deviceType] = false; }
| 13,267
|
C++
|
.cpp
| 289
| 38.404844
| 118
| 0.636869
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,621
|
TouchDrawingInputHandler.cpp
|
xournalpp_xournalpp/src/core/gui/inputdevices/TouchDrawingInputHandler.cpp
|
//
// Created by ulrich on 08.04.19.
//
#include "TouchDrawingInputHandler.h"
#include <string> // for operator==, basic_string
#include "control/Control.h" // for Control
#include "control/DeviceListHelper.h" // for getSourceMapping
#include "control/ToolEnums.h" // for TOOL_HAND, ToolType
#include "control/ToolHandler.h" // for ToolHandler
#include "control/settings/ButtonConfig.h" // for ButtonConfig
#include "control/settings/Settings.h" // for Settings
#include "control/settings/SettingsEnums.h" // for BUTTON_TOUCH, Button
#include "gui/MainWindow.h" // for MainWindow
#include "gui/PageView.h" // for XojPageView
#include "gui/XournalView.h" // for XournalView
#include "gui/XournalppCursor.h" // for XournalppCursor
#include "gui/inputdevices/InputEvents.h" // for InputEvent, BUTTON_PRE...
#include "gui/inputdevices/PenInputHandler.h" // for PenInputHandler
#include "gui/widgets/XournalWidget.h" // for GtkXournal
#include "InputContext.h" // for InputContext
#include "InputUtils.h" // for InputUtils
TouchDrawingInputHandler::TouchDrawingInputHandler(InputContext* inputContext): PenInputHandler(inputContext) {
inputContext->getToolHandler()->addToolChangedListener([&](ToolType newToolType) {
InputDeviceClass touchscreenClass =
DeviceListHelper::getSourceMapping(GDK_SOURCE_TOUCHSCREEN, this->inputContext->getSettings());
// If using the touchscreen as a touchscreen...
if (touchscreenClass == INPUT_DEVICE_TOUCHSCREEN) {
updateKineticScrollingEnabled();
}
});
}
TouchDrawingInputHandler::~TouchDrawingInputHandler() = default;
auto TouchDrawingInputHandler::handleImpl(InputEvent const& event) -> bool {
auto* mainWindow = inputContext->getView()->getControl()->getWindow();
ToolHandler* toolHandler = this->inputContext->getToolHandler();
// Do we need to end the touch sequence?
bool mustEnd = event.type == BUTTON_RELEASE_EVENT;
mustEnd = mustEnd || (event.type == GRAB_BROKEN_EVENT && this->deviceClassPressed);
// Notify if finger enters/leaves widget
// Note: Drawing outside window doesn't seem to work
// if this is put later in handleImpl.
if (event.type == ENTER_EVENT) {
this->actionEnterWindow(event);
return false;
}
if (event.type == LEAVE_EVENT) {
this->actionLeaveWindow(event);
return false;
}
// Multitouch
if ((this->primarySequence && this->primarySequence != event.sequence) || this->secondarySequence) {
if (!this->secondarySequence) {
this->secondarySequence = event.sequence;
// Let Gtk's touchscreen-based scrolling do
// momentum-based scrolling!
mainWindow->setGtkTouchscreenScrollingEnabled(true);
XojPageView* currentPage = this->getPageAtCurrentPosition(event);
if (currentPage) {
currentPage->onSequenceCancelEvent(event.deviceId);
}
}
if (mustEnd) {
// Ending two-finger panning/zooming? We should now only have a primary sequence.
if (event.sequence == this->primarySequence) {
this->primarySequence = this->secondarySequence;
this->secondarySequence = nullptr;
// Only scrolling now if using the hand tool.
mainWindow->setGtkTouchscreenScrollingEnabled(toolHandler->getToolType() == TOOL_HAND);
} else if (event.sequence == this->secondarySequence) {
this->secondarySequence = nullptr;
}
}
// false lets another input handler (e.g. TouchInputHandler)
// handle the event.
return false;
}
// Trigger start of action when pen/mouse is pressed
if (event.type == BUTTON_PRESS_EVENT && this->primarySequence == nullptr) {
this->primarySequence = event.sequence;
this->deviceClassPressed = true;
this->actionStart(event);
updateKineticScrollingEnabled();
return false;
}
// Trigger motion action when finger is pressed and moved,
// unless a hand tool, in which case, we return false to
// let an alternate handler (e.g. TouchInputHandler) decide
// what to do...
if (this->deviceClassPressed && event.type == MOTION_EVENT && toolHandler->getToolType() != TOOL_HAND) {
GtkXournal* xournal = inputContext->getXournal();
this->inputContext->getView()->getCursor()->setRotationAngle(event.relativeX);
this->actionMotion(event);
XournalppCursor* cursor = xournal->view->getCursor();
cursor->updateCursor();
return true;
}
if (mustEnd) {
this->primarySequence = nullptr;
this->actionEnd(event);
this->deviceClassPressed = false;
return false; // Any alternates should also end.
}
return false;
}
auto TouchDrawingInputHandler::changeTool(InputEvent const& event) -> bool {
Settings* settings = this->inputContext->getSettings();
ButtonConfig* cfg = settings->getButtonConfig(Button::BUTTON_TOUCH);
ToolHandler* toolHandler = this->inputContext->getToolHandler();
bool toolChanged = false;
if (cfg->device == event.deviceName) {
if (InputUtils::touchDrawingDisallowed(toolHandler, settings))
return false;
toolChanged = InputUtils::applyButton(toolHandler, settings, Button::BUTTON_TOUCH);
} else {
toolChanged = toolHandler->pointActiveToolToToolbarTool();
}
this->updateKineticScrollingEnabled();
if (toolChanged) {
toolHandler->fireToolChanged();
}
return true;
}
void TouchDrawingInputHandler::updateKineticScrollingEnabled() {
auto* control = inputContext->getView()->getControl();
auto* mainWindow = control->getWindow();
auto* toolHandler = this->inputContext->getToolHandler();
// Kinetic scrolling is nice; however, we need to disable it so we can draw (it steals
// single-finger input).
if (mainWindow != nullptr && control->getSettings()->getTouchDrawingEnabled()) {
mainWindow->setGtkTouchscreenScrollingEnabled(toolHandler->getToolType() == TOOL_HAND);
}
}
| 6,355
|
C++
|
.cpp
| 132
| 41.287879
| 111
| 0.671516
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,622
|
InputEvents.cpp
|
xournalpp_xournalpp/src/core/gui/inputdevices/InputEvents.cpp
|
//
// Created by ulrich on 17.05.19.
//
#include "InputEvents.h"
#include "control/settings/Settings.h" // for Settings
#include "control/settings/SettingsEnums.h" // for InputDeviceTypeOption
#include "util/gdk4_helper.h"
auto InputEvents::translateEventType(GdkEventType type) -> InputEventType {
switch (type) {
case GDK_MOTION_NOTIFY:
case GDK_TOUCH_UPDATE:
return MOTION_EVENT;
case GDK_BUTTON_PRESS:
case GDK_TOUCH_BEGIN:
return BUTTON_PRESS_EVENT;
case GDK_2BUTTON_PRESS:
return BUTTON_2_PRESS_EVENT;
case GDK_3BUTTON_PRESS:
return BUTTON_3_PRESS_EVENT;
case GDK_BUTTON_RELEASE:
case GDK_TOUCH_END:
case GDK_TOUCH_CANCEL:
return BUTTON_RELEASE_EVENT;
case GDK_ENTER_NOTIFY:
return ENTER_EVENT;
case GDK_LEAVE_NOTIFY:
return LEAVE_EVENT;
case GDK_PROXIMITY_IN:
return PROXIMITY_IN_EVENT;
case GDK_PROXIMITY_OUT:
return PROXIMITY_OUT_EVENT;
case GDK_SCROLL:
return SCROLL_EVENT;
case GDK_GRAB_BROKEN:
return GRAB_BROKEN_EVENT;
case GDK_KEY_PRESS:
return KEY_PRESS_EVENT;
case GDK_KEY_RELEASE:
return KEY_RELEASE_EVENT;
default:
// Events we do not care about
return UNKNOWN;
}
}
auto InputEvents::translateDeviceType(const std::string& name, GdkInputSource source, Settings* settings)
-> InputDeviceClass {
InputDeviceTypeOption deviceType = settings->getDeviceClassForDevice(name, source);
switch (deviceType) {
case InputDeviceTypeOption::Disabled: {
// Keyboards are not matched in their own class - do this here manually
if (source == GDK_SOURCE_KEYBOARD) {
return INPUT_DEVICE_KEYBOARD;
}
return INPUT_DEVICE_IGNORE;
}
case InputDeviceTypeOption::Mouse:
return INPUT_DEVICE_MOUSE;
case InputDeviceTypeOption::Pen:
return INPUT_DEVICE_PEN;
case InputDeviceTypeOption::Eraser:
return INPUT_DEVICE_ERASER;
case InputDeviceTypeOption::Touchscreen:
return INPUT_DEVICE_TOUCHSCREEN;
case InputDeviceTypeOption::MouseKeyboardCombo:
return INPUT_DEVICE_MOUSE_KEYBOARD_COMBO;
default:
return INPUT_DEVICE_IGNORE;
}
}
auto InputEvents::translateDeviceType(GdkDevice* device, Settings* settings) -> InputDeviceClass {
return translateDeviceType(gdk_device_get_name(device), gdk_device_get_source(device), settings);
}
auto InputEvents::translateEvent(GdkEvent* sourceEvent, Settings* settings) -> InputEvent {
InputEvent targetEvent{};
targetEvent.sourceEvent = sourceEvent;
// Map the event type to our internal ones
GdkEventType sourceEventType = gdk_event_get_event_type(sourceEvent);
targetEvent.type = translateEventType(sourceEventType);
GdkDevice* device = gdk_event_get_source_device(sourceEvent);
targetEvent.deviceClass = translateDeviceType(device, settings);
targetEvent.deviceName = gdk_device_get_name(device);
targetEvent.deviceId = DeviceId(device);
// Copy both coordinates of the event
gdk_event_get_root_coords(sourceEvent, &targetEvent.absoluteX, &targetEvent.absoluteY);
gdk_event_get_coords(sourceEvent, &targetEvent.relativeX, &targetEvent.relativeY);
// Copy the event button if there is any
if (targetEvent.type == BUTTON_PRESS_EVENT || targetEvent.type == BUTTON_RELEASE_EVENT) {
gdk_event_get_button(sourceEvent, &targetEvent.button);
}
if (sourceEventType == GDK_TOUCH_BEGIN || sourceEventType == GDK_TOUCH_END || sourceEventType == GDK_TOUCH_CANCEL) {
// As we only handle single finger events we can set the button statically to 1
targetEvent.button = 1;
}
targetEvent.state = gdk_event_get_modifier_state(sourceEvent);
if (targetEvent.deviceClass == INPUT_DEVICE_KEYBOARD) {
targetEvent.button = gdk_key_event_get_keyval(sourceEvent);
}
// Copy the timestamp
targetEvent.timestamp = gdk_event_get_time(sourceEvent);
// Copy the pressure data
gdk_event_get_axis(sourceEvent, GDK_AXIS_PRESSURE, &targetEvent.pressure);
// Copy the event sequence if there is any, and report no pressure
if (sourceEventType == GDK_TOUCH_BEGIN || sourceEventType == GDK_TOUCH_UPDATE || sourceEventType == GDK_TOUCH_END ||
sourceEventType == GDK_TOUCH_CANCEL) {
targetEvent.sequence = gdk_event_get_event_sequence(sourceEvent);
targetEvent.pressure = Point::NO_PRESSURE;
}
return targetEvent;
}
| 4,751
|
C++
|
.cpp
| 109
| 35.788991
| 120
| 0.682378
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,623
|
SetsquareInputHandler.cpp
|
xournalpp_xournalpp/src/core/gui/inputdevices/SetsquareInputHandler.cpp
|
#include "SetsquareInputHandler.h"
#include <memory> // for __shared_ptr_access, shar...
#include "control/Control.h" // for Control
#include "control/SetsquareController.h" // for SetsquareController, HYPOTENUSE
#include "control/ToolEnums.h" // for TOOL_HAND, TOOL_HIGHLIGHTER
#include "control/ToolHandler.h" // for ToolHandler
#include "gui/XournalView.h" // for XournalView
#include "gui/inputdevices/InputEvents.h" // for InputEvent
#include "model/Setsquare.h" // for Setsquare::INITIAL_HEIGHT,...
constexpr double MIN_HEIGHT = 4.5;
constexpr double MAX_HEIGHT = 15.0;
SetsquareInputHandler::SetsquareInputHandler(XournalView* xournal, GeometryToolController* controller):
GeometryToolInputHandler(xournal, controller, Setsquare::INITIAL_HEIGHT, 0., 0.) {}
SetsquareInputHandler::~SetsquareInputHandler() noexcept { this->unregisterFromPool(); }
auto SetsquareInputHandler::handlePointer(InputEvent const& event) -> bool {
const auto coords = getCoords(event);
SetsquareController* setsquareController = static_cast<SetsquareController*>(controller);
const auto toolHandler = xournal->getControl()->getToolHandler();
switch (toolHandler->getToolType()) {
case TOOL_HIGHLIGHTER:
case TOOL_PEN:
if (event.type == BUTTON_PRESS_EVENT) {
if (controller->isInsideGeometryTool(coords.x, coords.y, 0) &&
setsquareController->posRelToSide(HYPOTENUSE, coords.x, coords.y).y >= -0.5) {
// initialize range
const auto proj = setsquareController->posRelToSide(HYPOTENUSE, coords.x, coords.y).x;
setsquareController->createEdgeStroke(proj);
return true;
} else if (controller->isInsideGeometryTool(coords.x, coords.y, 0) &&
(setsquareController->posRelToSide(LEFT_LEG, coords.x, coords.y).y >= -0.5 ||
setsquareController->posRelToSide(RIGHT_LEG, coords.x, coords.y).y >= -0.5)) {
// initialize point
setsquareController->createRadialStroke(coords.x, coords.y);
return true;
} else {
return false;
}
} else if (event.type == MOTION_EVENT) {
// update range and paint
if (setsquareController->existsEdgeStroke()) {
const auto proj = setsquareController->posRelToSide(HYPOTENUSE, coords.x, coords.y).x;
setsquareController->updateEdgeStroke(proj);
return true;
} else if (setsquareController->existsRadialStroke()) {
setsquareController->updateRadialStroke(coords.x, coords.y);
return true;
}
return false;
} else if (event.type == BUTTON_RELEASE_EVENT) {
// add stroke to layer and reset
if (setsquareController->existsEdgeStroke()) {
setsquareController->finalizeEdgeStroke();
return true;
} else if (setsquareController->existsRadialStroke()) {
setsquareController->finalizeRadialStroke();
return true;
}
}
return false;
case TOOL_HAND:
if (event.type == BUTTON_PRESS_EVENT) {
if (!controller->isInsideGeometryTool(coords.x, coords.y, 0)) {
return false;
} else {
sequenceStart(event);
this->handScrolling = true;
return true;
}
} else if (event.type == MOTION_EVENT && this->handScrolling) {
scrollMotion(event);
return true;
} else if (event.type == BUTTON_RELEASE_EVENT && this->handScrolling) {
this->handScrolling = false;
}
default:
return false;
}
}
auto SetsquareInputHandler::getMinHeight() const -> double { return MIN_HEIGHT; }
auto SetsquareInputHandler::getMaxHeight() const -> double { return MAX_HEIGHT; }
| 4,272
|
C++
|
.cpp
| 80
| 40.0375
| 106
| 0.586801
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,624
|
PositionInputData.cpp
|
xournalpp_xournalpp/src/core/gui/inputdevices/PositionInputData.cpp
|
#include "PositionInputData.h"
auto PositionInputData::isShiftDown() const -> bool { return state & GDK_SHIFT_MASK; }
auto PositionInputData::isControlDown() const -> bool { return state & GDK_CONTROL_MASK; }
auto PositionInputData::isAltDown() const -> bool { return state & GDK_MOD1_MASK; }
| 296
|
C++
|
.cpp
| 4
| 72.25
| 90
| 0.754325
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,625
|
KeyboardInputHandler.cpp
|
xournalpp_xournalpp/src/core/gui/inputdevices/KeyboardInputHandler.cpp
|
#include "KeyboardInputHandler.h"
#include "gui/XournalView.h" // for XournalView
#include "gui/inputdevices/GeometryToolInputHandler.h" // for GeometryToolInputHandler
#include "InputContext.h" // for InputContext
#include "InputEvents.h" // for KeyEvent
KeyboardInputHandler::KeyboardInputHandler(InputContext* inputContext): inputContext(inputContext) {}
KeyboardInputHandler::~KeyboardInputHandler() = default;
bool KeyboardInputHandler::keyPressed(KeyEvent e) const {
auto* geom = inputContext->getGeometryToolInputHandler();
return (geom && geom->keyPressed(e)) || inputContext->getView()->onKeyPressEvent(e);
}
bool KeyboardInputHandler::keyReleased(KeyEvent e) const { return inputContext->getView()->onKeyReleaseEvent(e); }
| 774
|
C++
|
.cpp
| 12
| 62.333333
| 114
| 0.77381
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,626
|
TouchInputHandler.cpp
|
xournalpp_xournalpp/src/core/gui/inputdevices/TouchInputHandler.cpp
|
//
// Created by ulrich on 08.04.19.
//
#include "TouchInputHandler.h"
#include <cmath> // for abs
#include "control/Control.h" // for Control
#include "control/settings/Settings.h" // for Settings
#include "control/zoom/ZoomControl.h" // for ZoomControl
#include "gui/Layout.h" // for Layout
#include "gui/MainWindow.h" // for MainWindow
#include "gui/XournalView.h" // for XournalView
#include "gui/inputdevices/AbstractInputHandler.h" // for AbstractInputHandler
#include "gui/inputdevices/InputEvents.h" // for InputEvent, BUTTO...
#include "InputContext.h" // for InputContext
TouchInputHandler::TouchInputHandler(InputContext* inputContext): AbstractInputHandler(inputContext) {}
auto TouchInputHandler::handleImpl(InputEvent const& event) -> bool {
bool zoomGesturesEnabled = inputContext->getSettings()->isZoomGesturesEnabled();
// Don't handle more then 2 inputs
if (this->primarySequence && this->primarySequence != event.sequence && this->secondarySequence &&
this->secondarySequence != event.sequence) {
return false;
}
if (event.type == BUTTON_PRESS_EVENT) {
// Start scrolling when a sequence starts and we currently have none other
if (this->primarySequence == nullptr && this->secondarySequence == nullptr) {
this->primarySequence = event.sequence;
// Set sequence data
sequenceStart(event);
}
// Start zooming as soon as we have two sequences.
else if (this->primarySequence && this->primarySequence != event.sequence &&
this->secondarySequence == nullptr) {
this->secondarySequence = event.sequence;
// Even if zoom gestures are disabled,
// this is still the start of a sequence.
// Set sequence data
sequenceStart(event);
this->startZoomReady = true;
}
}
if (event.type == MOTION_EVENT && this->primarySequence) {
if (this->primarySequence && this->secondarySequence && zoomGesturesEnabled) {
if (this->startZoomReady) {
if (this->primarySequence == event.sequence) {
sequenceStart(event);
zoomStart();
}
} else {
zoomMotion(event);
}
} else if (event.sequence == this->primarySequence) {
scrollMotion(event);
} else if (this->primarySequence && this->secondarySequence) {
sequenceStart(event);
}
}
if (event.type == BUTTON_RELEASE_EVENT) {
// Only stop zooing if both sequences were active (we were scrolling)
if (this->primarySequence != nullptr && this->secondarySequence != nullptr && zoomGesturesEnabled) {
zoomEnd();
}
if (event.sequence == this->primarySequence) {
// If secondarySequence is nullptr, this sets primarySequence
// to nullptr. If it isn't, then it is now the primary sequence!
this->primarySequence = this->secondarySequence;
this->secondarySequence = nullptr;
this->priLastAbs = this->secLastAbs;
this->priLastRel = this->secLastRel;
} else {
this->secondarySequence = nullptr;
}
}
return false;
}
void TouchInputHandler::sequenceStart(InputEvent const& event) {
if (event.sequence == this->primarySequence) {
this->priLastAbs = {event.absoluteX, event.absoluteY};
this->priLastRel = {event.relativeX, event.relativeY};
} else {
this->secLastAbs = {event.absoluteX, event.absoluteY};
this->secLastRel = {event.relativeX, event.relativeY};
}
}
void TouchInputHandler::scrollMotion(InputEvent const& event) {
// Will only be called if there is a single sequence (zooming handles two sequences)
auto offset = [&]() {
auto absolutePoint = xoj::util::Point{event.absoluteX, event.absoluteY};
if (event.sequence == this->primarySequence) {
auto offset = absolutePoint - this->priLastAbs;
this->priLastAbs = absolutePoint;
return offset;
} else {
auto offset = absolutePoint - this->secLastAbs;
this->secLastAbs = absolutePoint;
return offset;
}
}();
auto* layout = inputContext->getView()->getControl()->getWindow()->getLayout();
layout->scrollRelative(-offset.x, -offset.y);
}
void TouchInputHandler::zoomStart() {
this->startZoomDistance = this->priLastAbs.distance(this->secLastAbs);
if (this->startZoomDistance == 0.0) {
this->startZoomDistance = 0.01;
}
// Whether we can ignore the zoom portion of the gesture (e.g. distance between touch points
// hasn't changed enough).
this->canBlockZoom = true;
ZoomControl* zoomControl = this->inputContext->getView()->getControl()->getZoomControl();
// Disable zoom fit as we are zooming currently
// TODO(fabian): this should happen internally!!!
if (zoomControl->isZoomFitMode()) {
zoomControl->setZoomFitMode(false);
}
// use screen pixel coordinates for the zoom center
// as relative coordinates depend on the changing zoom level
auto center = (this->priLastAbs + this->secLastAbs) / 2.0;
this->lastZoomScrollCenter = center;
// translate absolute window coordinates to the widget-local coordinates
const auto* mainWindow = inputContext->getView()->getControl()->getWindow();
const auto translation = mainWindow->getNegativeXournalWidgetPos();
center += translation;
zoomControl->startZoomSequence(center);
this->startZoomReady = false;
}
void TouchInputHandler::zoomMotion(InputEvent const& event) {
if (event.sequence == this->primarySequence) {
this->priLastAbs = {event.absoluteX, event.absoluteY};
} else {
this->secLastAbs = {event.absoluteX, event.absoluteY};
}
double distance = this->priLastAbs.distance(this->secLastAbs);
double zoom = distance / this->startZoomDistance;
double zoomTriggerThreshold = inputContext->getSettings()->getTouchZoomStartThreshold();
double zoomChangePercentage = std::abs(distance - startZoomDistance) / startZoomDistance * 100;
// Has the touch points moved far enough to trigger a zoom?
if (this->canBlockZoom && zoomChangePercentage < zoomTriggerThreshold) {
zoom = 1.0;
} else {
// Touches have moved far enough from their initial location that we
// no longer prevent touchscreen zooming.
this->canBlockZoom = false;
}
ZoomControl* zoomControl = this->inputContext->getView()->getControl()->getZoomControl();
const auto center = (this->priLastAbs + this->secLastAbs) / 2;
zoomControl->zoomSequenceChange(zoom, true, center - lastZoomScrollCenter);
lastZoomScrollCenter = center;
}
void TouchInputHandler::zoomEnd() {
ZoomControl* zoomControl = this->inputContext->getView()->getControl()->getZoomControl();
zoomControl->endZoomSequence();
}
void TouchInputHandler::onUnblock() {
this->primarySequence = nullptr;
this->secondarySequence = nullptr;
this->startZoomDistance = 0.0;
this->lastZoomScrollCenter = {};
priLastAbs = {-1.0, -1.0};
secLastAbs = {-1.0, -1.0};
priLastRel = {-1.0, -1.0};
secLastRel = {-1.0, -1.0};
}
| 7,502
|
C++
|
.cpp
| 162
| 39.061728
| 108
| 0.654705
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,627
|
CompassInputHandler.cpp
|
xournalpp_xournalpp/src/core/gui/inputdevices/CompassInputHandler.cpp
|
#include "CompassInputHandler.h"
#include <memory> // for __shared_ptr_access, shar...
#include "control/CompassController.h" // for CompassController, HYPOTENUSE
#include "control/Control.h"
#include "control/ToolEnums.h" // for TOOL_HAND, TOOL_HIGHLIGHTER
#include "control/ToolHandler.h" // for ToolHandler
#include "gui/XournalView.h" // for XournalView
#include "gui/inputdevices/InputEvents.h"
#include "model/Compass.h"
constexpr double MIN_HEIGHT = 0.5;
constexpr double MAX_HEIGHT = 10.0;
CompassInputHandler::CompassInputHandler(XournalView* xournal, GeometryToolController* controller):
GeometryToolInputHandler(xournal, controller, Compass::INITIAL_HEIGHT, 0., 0.) {}
CompassInputHandler::~CompassInputHandler() noexcept { this->unregisterFromPool(); }
auto CompassInputHandler::handlePointer(InputEvent const& event) -> bool {
const auto coords = getCoords(event);
CompassController* compassController = static_cast<CompassController*>(controller);
const auto p = compassController->posRelToSide(coords.x, coords.y);
const auto toolHandler = xournal->getControl()->getToolHandler();
switch (toolHandler->getToolType()) {
case TOOL_HIGHLIGHTER:
case TOOL_PEN:
if (event.type == BUTTON_PRESS_EVENT) {
if (controller->isInsideGeometryTool(coords.x, coords.y, 0) &&
!controller->isInsideGeometryTool(coords.x, coords.y, -0.5)) {
// initialize range
lastProj = std::atan2(-p.y, p.x);
compassController->createOutlineStroke(lastProj);
return true;
} else if (controller->isInsideGeometryTool(coords.x, coords.y, 0.) &&
std::abs(compassController->posRelToSide(coords.x, coords.y).y) <= 0.5 &&
std::abs(compassController->posRelToSide(coords.x, coords.y).x - 0.5 * height) <=
0.5 * height) {
compassController->createRadialStroke(std::hypot(p.x, p.y));
return true;
}
return false;
} else if (event.type == MOTION_EVENT) {
// update range and paint
if (compassController->existsOutlineStroke()) {
auto proj = std::atan2(-p.y, p.x);
proj = lastProj + std::remainder(proj - lastProj, 2 * M_PI);
compassController->updateOutlineStroke(proj);
lastProj = proj;
return true;
} else if (compassController->existsRadialStroke()) {
compassController->updateRadialStroke(std::hypot(p.x, p.y));
}
return false;
} else if (event.type == BUTTON_RELEASE_EVENT) {
// add stroke to layer and reset
if (compassController->existsOutlineStroke()) {
compassController->finalizeOutlineStroke();
lastProj = NAN;
return true;
} else if (compassController->existsRadialStroke()) {
compassController->finalizeRadialStroke();
return true;
}
}
return false;
case TOOL_HAND:
if (event.type == BUTTON_PRESS_EVENT) {
if (!controller->isInsideGeometryTool(coords.x, coords.y, 0)) {
return false;
} else {
sequenceStart(event);
this->handScrolling = true;
return true;
}
} else if (event.type == MOTION_EVENT && this->handScrolling) {
scrollMotion(event);
return true;
} else if (event.type == BUTTON_RELEASE_EVENT && this->handScrolling) {
this->handScrolling = false;
}
default:
return false;
}
}
auto CompassInputHandler::getMinHeight() const -> double { return MIN_HEIGHT; }
auto CompassInputHandler::getMaxHeight() const -> double { return MAX_HEIGHT; }
| 4,169
|
C++
|
.cpp
| 82
| 37.341463
| 108
| 0.577347
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,628
|
PenInputHandler.cpp
|
xournalpp_xournalpp/src/core/gui/inputdevices/PenInputHandler.cpp
|
//
// Created by ulrich on 06.04.19.
//
#include "PenInputHandler.h"
#include <algorithm> // for max, min
#include <cmath> // for abs, atan, sqrt
#include <thread> // for thread
#include <utility> // for move
#include <glib.h> // for gdouble, gint, g_message
#include <gtk/gtk.h> // for gtk_adjustment_get_value
#include "control/ToolEnums.h" // for TOOL_HAND, TOOL_IMAGE
#include "control/ToolHandler.h" // for ToolHandler
#include "control/settings/Settings.h" // for Settings
#include "control/tools/CursorSelectionType.h" // for CursorSelectionType
#include "control/tools/EditSelection.h" // for EditSelection
#include "gui/Layout.h" // for Layout
#include "gui/PageView.h" // for XojPageView
#include "gui/XournalView.h" // for XournalView
#include "gui/XournalppCursor.h" // for XournalppCursor
#include "gui/scroll/ScrollHandling.h" // for ScrollHandling
#include "gui/widgets/XournalWidget.h" // for GtkXournal
#include "model/Point.h" // for Point, Point::NO_PRES...
#include "util/Assert.h" // for xoj_assert
#include "util/Point.h" // for Point
#include "util/Util.h" // for execInUiThread
#include "util/safe_casts.h"
#include "AbstractInputHandler.h" // for AbstractInputHandler
#include "InputContext.h" // for InputContext
#include "PositionInputData.h" // for PositionInputData
#include "config-debug.h" // for DEBUG_INPUT
#define WIDGET_SCROLL_BORDER 25
PenInputHandler::PenInputHandler(InputContext* inputContext): AbstractInputHandler(inputContext) {}
PenInputHandler::~PenInputHandler() = default;
void PenInputHandler::updateLastEvent(InputEvent const& event) {
if (!event) {
return;
}
this->lastEvent = event;
if (getPageAtCurrentPosition(event)) {
this->lastHitEvent = event;
}
}
void PenInputHandler::handleScrollEvent(InputEvent const& event) {
// use root coordinates as reference point because
// scrolling changes window relative coordinates
// see github Gnome/evince@1adce5486b10e763bed869
// GTK handles event compression/filtering differently between versions - this may be needed on certain hardware/GTK
// combinations.
if (std::abs((this->scrollStartX - event.absoluteX)) < 0.1 &&
std::abs((this->scrollStartY - event.absoluteY)) < 0.1) {
return;
}
if (this->scrollOffsetX == 0 && this->scrollOffsetY == 0) {
this->scrollOffsetX = this->scrollStartX - event.absoluteX;
this->scrollOffsetY = this->scrollStartY - event.absoluteY;
Util::execInUiThread([&]() {
this->inputContext->getXournal()->layout->scrollRelative(this->scrollOffsetX, this->scrollOffsetY);
// Scrolling done, so reset our counters
this->scrollOffsetX = 0;
this->scrollOffsetY = 0;
});
// Update the reference for the scroll-offset
this->scrollStartX = event.absoluteX;
this->scrollStartY = event.absoluteY;
}
}
auto PenInputHandler::actionStart(InputEvent const& event) -> bool {
this->inputContext->focusWidget();
this->lastActionStartTimeStamp = event.timestamp;
this->sequenceStartPosition = {event.absoluteX, event.absoluteY};
XojPageView* currentPage = this->getPageAtCurrentPosition(event);
// set reference data for handling of entering/leaving page
this->updateLastEvent(event);
// Change the tool depending on the key
if (!changeTool(event))
return false;
// Used for pressure inference
this->lastPressure = 0.0;
// Flag running input
ToolHandler* toolHandler = this->inputContext->getToolHandler();
ToolType toolType = toolHandler->getToolType();
//
if (toolType != TOOL_IMAGE) {
this->inputRunning = true;
} else {
this->deviceClassPressed = false;
}
this->penInWidget = true;
GtkXournal* xournal = this->inputContext->getXournal();
XournalppCursor* cursor = xournal->view->getCursor();
cursor->setMouseDown(true);
// Save the starting offset when hand-tool is selected to get a reference for the scroll-offset
if (toolType == TOOL_HAND) {
this->scrollStartX = event.absoluteX;
this->scrollStartY = event.absoluteY;
}
this->sequenceStartPage = currentPage;
// hand tool don't change the selection, so you can scroll e.g. with your touchscreen without remove the selection
bool changeSelection = xournal->selection && toolHandler->getToolType() != TOOL_HAND;
if ((event.state & GDK_SHIFT_MASK)) {
// When tap single selection is enabled, selections can happen with the Pen tool
if (toolHandler->getToolType() == TOOL_PEN && isCurrentTapSelection(event)) {
changeSelection = false;
}
// Selection tools does not change selection with Shift pressed
if (isSelectToolTypeSingleLayer(toolType)) {
changeSelection = false;
}
}
if (changeSelection) {
EditSelection* selection = xournal->selection;
XojPageView* view = selection->getView();
PositionInputData selectionPos = this->getInputDataRelativeToCurrentPage(view, event);
// Check if event modifies selection instead of page
CursorSelectionType selType =
selection->getSelectionTypeForPos(selectionPos.x, selectionPos.y, xournal->view->getZoom());
if (selType) {
if (selType == CURSOR_SELECTION_MOVE && modifier3) {
selection->copySelection();
}
xournal->selection->mouseDown(selType, selectionPos.x, selectionPos.y);
return true;
}
xournal->view->clearSelection();
changeTool(event);
// stop early to prevent drawing when clicking outside of the selection with the intention of deselecting
if (toolHandler->isDrawingTool())
return true;
}
// Forward event to page
if (currentPage) {
PositionInputData pos = this->getInputDataRelativeToCurrentPage(currentPage, event);
if (pos.pressure != Point::NO_PRESSURE) {
pressureMode = PressureMode::DEVICE_PRESSURE;
} else if (this->inputContext->getSettings()->isPressureGuessingEnabled()) {
pressureMode = PressureMode::INFERRED_PRESSURE;
} else {
pressureMode = PressureMode::NO_PRESSURE;
}
pos.pressure = this->filterPressure(pos, currentPage);
return currentPage->onButtonPressEvent(pos);
}
return true;
}
double PenInputHandler::inferPressureValue(PositionInputData const& pos, XojPageView* page) {
PositionInputData lastPos = getInputDataRelativeToCurrentPage(page, this->lastEvent);
double dt = (pos.timestamp - lastPos.timestamp) / 10.0;
double distance = xoj::util::Point<double>(pos.x, pos.y).distance(xoj::util::Point<double>(lastPos.x, lastPos.y));
double inverseSpeed = dt / (distance + 0.001);
// This doesn't have to be exact. Arctan is used here for its sigmoid-like shape,
// so that lim inverseSpeed->infinity (newPressure) is some finite value.
double newPressure = 3.142 / 2.0 + std::atan(inverseSpeed * 3.14 - 1.3);
// This weighted average both smooths abrupt changes in newPressure caused
// by changes to inverseSpeed and causes an initial increase in pressure.
newPressure = std::min(newPressure, 2.0) / 5.0 + this->lastPressure * 4.0 / 5.0;
// Handle the single-point case.
if (distance == 0) {
newPressure = std::sqrt(dt / 10.0) - 0.1;
}
this->lastPressure = newPressure;
// Final pressure tweaks...
return (newPressure * 1.1 + 0.8) / 2.0;
}
double PenInputHandler::filterPressure(PositionInputData const& pos, XojPageView* page) {
if (pressureMode == PressureMode::NO_PRESSURE) {
return Point::NO_PRESSURE;
}
double filteredPressure;
if (pressureMode == PressureMode::INFERRED_PRESSURE) {
filteredPressure = inferPressureValue(pos, page);
} else {
xoj_assert(pressureMode == PressureMode::DEVICE_PRESSURE);
/**
* On some devices, the pressure value of some events is missing. Use the last recorded pressure value then.
*/
if (pos.pressure == Point::NO_PRESSURE) {
g_debug("Pressure-sensitive device omitted pressure this time");
filteredPressure = lastPressure;
} else {
filteredPressure = pos.pressure;
lastPressure = pos.pressure; // Record in case the pressure value is omitted in the next event
}
}
Settings* settings = this->inputContext->getSettings();
xoj_assert(settings->getMinimumPressure() >= 0.01);
return std::max(settings->getMinimumPressure(), filteredPressure * settings->getPressureMultiplier());
}
bool PenInputHandler::isCurrentTapSelection(InputEvent const& event) const {
ToolHandler* toolHandler = inputContext->getToolHandler();
if (!toolHandler->supportsTapFilter()) {
return false;
}
auto* settings = inputContext->getSettings();
if (!settings->getStrokeFilterEnabled()) {
return false;
}
int tapMaxDuration = 0, filterRepetitionTime = 0;
double tapMaxDistance = NAN; // in mm
settings->getStrokeFilter(&tapMaxDuration, &tapMaxDistance, &filterRepetitionTime);
const double dpmm = settings->getDisplayDpi() / 25.4;
const double dist = std::hypot(this->sequenceStartPosition.x - event.absoluteX,
this->sequenceStartPosition.y - event.absoluteY);
const bool noMovement = dist < tapMaxDistance * dpmm;
const bool fastEnoughTap = event.timestamp - this->lastActionStartTimeStamp < as_unsigned(tapMaxDuration);
const bool notAnAftershock = event.timestamp - this->lastActionEndTimeStamp > as_unsigned(filterRepetitionTime);
if (noMovement && fastEnoughTap && notAnAftershock) {
return true;
}
return false;
}
auto PenInputHandler::actionMotion(InputEvent const& event) -> bool {
/*
* Workaround for misbehaving devices where Enter events are not published every time
* This is required to disable outside scrolling again
*/
gdouble eventX = event.relativeX;
gdouble eventY = event.relativeY;
GtkAdjustment* adjHorizontal = this->inputContext->getScrollHandling()->getHorizontal();
GtkAdjustment* adjVertical = this->inputContext->getScrollHandling()->getVertical();
double h = gtk_adjustment_get_value(adjHorizontal);
double v = gtk_adjustment_get_value(adjVertical);
eventX -= h;
eventY -= v;
GtkWidget* widget = gtk_widget_get_parent(this->inputContext->getView()->getWidget());
gint width = gtk_widget_get_allocated_width(widget);
gint height = gtk_widget_get_allocated_height(widget);
if (!this->penInWidget && eventX > WIDGET_SCROLL_BORDER && eventY > WIDGET_SCROLL_BORDER &&
eventX < width - WIDGET_SCROLL_BORDER && eventY < height - WIDGET_SCROLL_BORDER) {
this->penInWidget = true;
}
GtkXournal* xournal = this->inputContext->getXournal();
ToolHandler* toolHandler = this->inputContext->getToolHandler();
this->changeTool(event);
if (toolHandler->getToolType() == TOOL_HAND) {
if (this->deviceClassPressed) {
this->handleScrollEvent(event);
return true;
}
return false;
}
bool isShiftDown = (event.state & GDK_SHIFT_MASK);
bool handleSelectionMove = xournal->selection != nullptr;
if (xournal->selection && isSelectToolTypeSingleLayer(toolHandler->getToolType()) &&
!xournal->selection->isMoving()) {
if (isShiftDown || this->deviceClassPressed) {
handleSelectionMove = false;
// Cursor mode to match the multiple-selection mode
xournal->view->getCursor()->setMouseSelectionType(CURSOR_SELECTION_NONE);
}
}
if (handleSelectionMove) {
EditSelection* selection = xournal->selection;
XojPageView* view = selection->getView();
PositionInputData pos = this->getInputDataRelativeToCurrentPage(view, event);
if (xournal->selection->isMoving()) {
selection->mouseMove(pos.x, pos.y, pos.isAltDown());
} else if (!isShiftDown) {
CursorSelectionType selType = selection->getSelectionTypeForPos(pos.x, pos.y, xournal->view->getZoom());
xournal->view->getCursor()->setMouseSelectionType(selType);
}
return true;
}
// Check if page was left / entered
XojPageView* lastEventPage = getPageAtCurrentPosition(this->lastEvent);
XojPageView* lastHitEventPage = getPageAtCurrentPosition(this->lastHitEvent);
XojPageView* currentPage = getPageAtCurrentPosition(event);
if (!toolHandler->isSinglePageTool()) {
/*
* Get all events where the input sequence moved from one page to another without stopping the input.
* Only trigger once the new page was entered to ensure that an input device can leave the page temporarily.
* For these events we need to fake an end point in the old page and a start point in the new page.
*/
if (this->deviceClassPressed && currentPage && currentPage != sequenceStartPage && lastHitEventPage) {
#ifdef DEBUG_INPUT
g_message("PenInputHandler: Start new input on switching page...");
#endif
this->actionEnd(this->lastHitEvent);
this->updateLastEvent(event);
bool result = this->actionStart(event);
this->updateLastEvent(event);
return result;
}
/*
* Get all events where the input sequence started outside of a page and moved into one.
* For these events we need to fake a start point in the current page.
*/
if (this->deviceClassPressed && currentPage && !lastEventPage && !lastHitEventPage) {
#ifdef DEBUG_INPUT
g_message("PenInputHandler: Start new input on entering page...");
#endif
bool result = this->actionStart(event);
this->updateLastEvent(event);
return result;
}
}
// Update the cursor
xournal->view->getCursor()->setInsidePage(currentPage != nullptr);
// Selections and single-page elements will always work on one page so we need to handle them differently
if (this->sequenceStartPage && toolHandler->isSinglePageTool()) {
// Relay the event to the page
PositionInputData pos = getInputDataRelativeToCurrentPage(sequenceStartPage, event);
if (!toolHandler->acceptsOutOfPageEvents()) {
// Enforce input to stay within page
pos.x = std::clamp(pos.x, 0.0, static_cast<double>(sequenceStartPage->getDisplayWidth()));
pos.y = std::clamp(pos.y, 0.0, static_cast<double>(sequenceStartPage->getDisplayHeight()));
}
pos.pressure = this->filterPressure(pos, sequenceStartPage);
bool result = sequenceStartPage->onMotionNotifyEvent(pos);
this->updateLastEvent(event); // Update the last position of the input device
return result;
}
if (currentPage && this->penInWidget) {
// Relay the event to the page
PositionInputData pos = getInputDataRelativeToCurrentPage(currentPage, event);
pos.pressure = this->filterPressure(pos, currentPage);
bool result = currentPage->onMotionNotifyEvent(pos);
this->updateLastEvent(event); // Update the last position of the input device
return result;
}
this->updateLastEvent(event); // Update the last position of the input device
return false;
}
auto PenInputHandler::actionEnd(InputEvent const& event) -> bool {
GtkXournal* xournal = inputContext->getXournal();
XournalppCursor* cursor = xournal->view->getCursor();
ToolHandler* toolHandler = inputContext->getToolHandler();
cursor->setMouseDown(false);
bool cancelAction = isCurrentTapSelection(event);
// Holding shift (with selections) also does not imply drawing
if (toolHandler->supportsTapFilter()) {
auto* settings = inputContext->getSettings();
if (settings->getStrokeFilterEnabled()) {
cancelAction |= (event.state & GDK_SHIFT_MASK) && xournal->selection != nullptr;
}
}
if (cancelAction) {
// Cancel the sequence and trigger the necessary action
XojPageView* pageUnderTap = this->sequenceStartPage ? this->sequenceStartPage : getPageAtCurrentPosition(event);
if (pageUnderTap) {
PositionInputData pos = getInputDataRelativeToCurrentPage(pageUnderTap, event);
pageUnderTap->onSequenceCancelEvent(pos.deviceId);
pageUnderTap->onTapEvent(pos);
}
this->sequenceStartPage = nullptr;
this->inputRunning = false;
this->lastActionEndTimeStamp = event.timestamp;
return false;
}
this->lastActionEndTimeStamp = event.timestamp;
EditSelection* sel = xournal->view->getSelection();
if (sel) {
sel->mouseUp();
}
// Selections and single-page elements will always work on one page so we need to handle them differently
if (this->sequenceStartPage && toolHandler->isSinglePageTool()) {
PositionInputData pos = getInputDataRelativeToCurrentPage(this->sequenceStartPage, event);
pos.pressure = this->filterPressure(pos, this->sequenceStartPage);
this->sequenceStartPage->onButtonReleaseEvent(pos);
} else {
// Relay the event to the page
XojPageView* currentPage = getPageAtCurrentPosition(event);
/*
* Use the last active page if you can't find a page under the cursor position.
* This is a workaround for input leaving the page while being active and then stopping outside.
*/
if (!currentPage) {
if (!this->lastHitEvent) {
return false;
}
currentPage = getPageAtCurrentPosition(this->lastHitEvent);
}
if (currentPage) {
PositionInputData pos = getInputDataRelativeToCurrentPage(currentPage, event);
pos.pressure = this->filterPressure(pos, currentPage);
currentPage->onButtonReleaseEvent(pos);
}
}
// Reset the selection
EditSelection* tmpSelection = xournal->selection;
xournal->selection = nullptr;
this->sequenceStartPage = nullptr;
if (toolHandler->pointActiveToolToToolbarTool()) {
toolHandler->fireToolChanged();
}
// we need this workaround so it's possible to select something with the middle button
if (tmpSelection) {
xournal->view->setSelection(tmpSelection);
}
this->inputRunning = false;
return false;
}
void PenInputHandler::actionPerform(InputEvent const& event) {
#ifdef DEBUG_INPUT
g_message("Discrete input action; modifier1=%s, modifier2=%s", this->modifier2 ? "true" : "false",
this->modifier3 ? "true" : "false");
#endif
XojPageView* currentPage = this->getPageAtCurrentPosition(event);
if (currentPage == nullptr) {
return;
}
PositionInputData pos = this->getInputDataRelativeToCurrentPage(currentPage, event);
if (event.type == BUTTON_2_PRESS_EVENT) {
currentPage->onButtonDoublePressEvent(pos);
} else if (event.type == BUTTON_3_PRESS_EVENT) {
currentPage->onButtonTriplePressEvent(pos);
}
}
void PenInputHandler::actionLeaveWindow(InputEvent const& event) {
if (!this->penInWidget) {
return;
}
if (!this->inputContext->getSettings()->getInputSystemDrawOutsideWindowEnabled()) {
this->penInWidget = false;
}
// Stop input sequence if the tool is not a selection tool
ToolHandler* toolHandler = this->inputContext->getToolHandler();
if (this->inputRunning && !toolHandler->isSinglePageTool()) {
if (!this->inputContext->getSettings()->getInputSystemDrawOutsideWindowEnabled()) {
this->actionEnd(this->lastHitEvent);
}
} else if (this->deviceClassPressed) {
// scroll if we have an active selection
gdouble eventX = event.relativeX;
gdouble eventY = event.relativeY;
GtkAdjustment* adjHorizontal = this->inputContext->getScrollHandling()->getHorizontal();
GtkAdjustment* adjVertical = this->inputContext->getScrollHandling()->getVertical();
double h = gtk_adjustment_get_value(adjHorizontal);
double v = gtk_adjustment_get_value(adjVertical);
eventX -= h;
eventY -= v;
GtkWidget* widget = gtk_widget_get_parent(this->inputContext->getView()->getWidget());
gint width = gtk_widget_get_allocated_width(widget);
gint height = gtk_widget_get_allocated_height(widget);
new std::thread([&, eventX, eventY, width, height]() {
int offsetX = 0, offsetY = 0;
// TODO(fabian): make offset dependent on how big the distance between pen and view is
if (eventX < WIDGET_SCROLL_BORDER) {
offsetX = -10;
}
if (eventY < WIDGET_SCROLL_BORDER) {
offsetY = -10;
}
if (eventX > width - WIDGET_SCROLL_BORDER) {
offsetX = 10;
}
if (eventY > height - WIDGET_SCROLL_BORDER) {
offsetY = 10;
}
#ifdef DEBUG_INPUT
g_message("Offset: X:%d\tY:%d", offsetX, offsetY);
#endif
while (!this->penInWidget) {
Util::execInUiThread([&]() {
GtkXournal* xournal = this->inputContext->getXournal();
xournal->layout->scrollRelative(offsetX, offsetY);
});
// sleep for half a second until we scroll again
g_usleep(static_cast<gulong>(0.5 * G_USEC_PER_SEC));
}
});
}
}
void PenInputHandler::actionEnterWindow(InputEvent const& event) {
this->penInWidget = true;
if (!this->inputContext->getSettings()->getInputSystemDrawOutsideWindowEnabled()) {
// Restart input sequence if the tool is pressed and not a single-page tool
ToolHandler* toolHandler = this->inputContext->getToolHandler();
if (this->deviceClassPressed && !toolHandler->isSinglePageTool()) {
this->actionStart(event);
}
}
}
| 22,574
|
C++
|
.cpp
| 472
| 40.322034
| 120
| 0.667773
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,629
|
DeviceId.cpp
|
xournalpp_xournalpp/src/core/gui/inputdevices/DeviceId.cpp
|
#include "DeviceId.h"
#include <gdk/gdk.h>
DeviceId::DeviceId(const GdkDevice* id): id(id) {
if (id) {
auto source = gdk_device_get_source(const_cast<GdkDevice*>(id));
trackpointOrTouchpad = source == GDK_SOURCE_TRACKPOINT || source == GDK_SOURCE_TOUCHPAD;
}
}
void DeviceId::reset(const GdkDevice* id) { *this = DeviceId(id); }
DeviceId::operator bool() const { return id != nullptr; }
bool DeviceId::operator==(const DeviceId& o) const {
// For laptops with both touchpad and trackpoint, allow to use the trackpoint buttons above the touchpad
return (id == o.id) || (trackpointOrTouchpad && o.trackpointOrTouchpad);
}
bool DeviceId::operator!=(const DeviceId& o) const { return !(*this == o); }
| 731
|
C++
|
.cpp
| 15
| 45.466667
| 108
| 0.69888
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,630
|
AbstractInputHandler.cpp
|
xournalpp_xournalpp/src/core/gui/inputdevices/AbstractInputHandler.cpp
|
//
// Created by ulrich on 06.04.19.
//
#include "AbstractInputHandler.h"
#include <string_view>
#include <glib.h> // for gdouble
#include "control/settings/Settings.h" // for Settings
#include "gui/Layout.h" // for Layout
#include "gui/PageView.h" // for XojPageView
#include "gui/XournalView.h" // for XournalView
#include "gui/XournalppCursor.h" // for XournalppCursor
#include "gui/inputdevices/InputEvents.h" // for InputEvent
#include "gui/inputdevices/PositionInputData.h" // for PositionInputData
#include "gui/widgets/XournalWidget.h" // for GtkXournal
#include "model/Point.h" // for Point, Point::NO_PRE...
#include "util/Assert.h" // for xoj_assert
#include "util/safe_casts.h" // for round_cast
#include "InputContext.h" // for InputContext
AbstractInputHandler::AbstractInputHandler(InputContext* inputContext) { this->inputContext = inputContext; }
AbstractInputHandler::~AbstractInputHandler() = default;
void AbstractInputHandler::block(bool block) {
if (block == this->blocked) {
return;
}
this->blocked = block;
if (!this->blocked) {
this->onUnblock();
} else {
this->onBlock();
}
}
auto AbstractInputHandler::isBlocked() const -> bool { return this->blocked; }
auto AbstractInputHandler::handle(InputEvent const& event) -> bool {
if (!this->blocked) {
this->inputContext->getXournal()->view->getCursor()->setInputDeviceClass(event.deviceClass);
return this->handleImpl(event);
}
return true;
}
/**
* Get Page at current position
*
* @return page or nullptr if none
*/
auto AbstractInputHandler::getPageAtCurrentPosition(InputEvent const& event) const -> XojPageView* {
if (!event) {
return nullptr;
}
GtkXournal* xournal = this->inputContext->getXournal();
int x = round_cast<int>(event.relativeX);
int y = round_cast<int>(event.relativeY);
return xournal->layout->getPageViewAt(x, y);
}
/**
* Get input data relative to current input page
*/
auto AbstractInputHandler::getInputDataRelativeToCurrentPage(XojPageView* page, InputEvent const& event) const
-> PositionInputData {
xoj_assert(page != nullptr);
gdouble eventX = event.relativeX;
gdouble eventY = event.relativeY;
PositionInputData pos = {};
pos.x = eventX - static_cast<double>(page->getX());
pos.y = eventY - static_cast<double>(page->getY());
pos.pressure = Point::NO_PRESSURE;
if (this->inputContext->getSettings()->isPressureSensitivity()) {
pos.pressure = event.pressure;
}
pos.state = this->inputContext->getModifierState();
pos.timestamp = event.timestamp;
pos.deviceId = event.deviceId;
return pos;
}
void AbstractInputHandler::onBlock() {}
void AbstractInputHandler::onUnblock() {}
| 2,959
|
C++
|
.cpp
| 75
| 35.72
| 110
| 0.669696
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,631
|
HandRecognition.cpp
|
xournalpp_xournalpp/src/core/gui/inputdevices/HandRecognition.cpp
|
#include "HandRecognition.h"
#include <cstring> // for strcmp
#include <string> // for all...
#include "control/settings/Settings.h" // for SEl...
#include "gtk/gtk.h" // for Gtk...
#include "gui/inputdevices/InputEvents.h" // for INP...
#include "gui/inputdevices/touchdisable/TouchDisableCustom.h" // for Tou...
#include "gui/inputdevices/touchdisable/TouchDisableInterface.h" // for Tou...
#include "gui/inputdevices/touchdisable/TouchDisableX11.h" // for Tou...
#include "util/glib_casts.h" // for wrap_v
#include "util/safe_casts.h" // for as_unsigned
#include "InputContext.h" // for Inp...
using std::string;
HandRecognition::HandRecognition(GtkWidget* widget, InputContext* inputContext, Settings* settings):
inputContext(inputContext), settings(settings) {
#ifdef X11_ENABLED
const char* sessionType = g_getenv("XDG_SESSION_TYPE");
if (sessionType != nullptr && strcmp(sessionType, "x11") == 0) {
x11Session = true;
}
#endif
reload();
}
HandRecognition::~HandRecognition() {
// Enable touchscreen on quit application
if (!touchState && enabled && touchImpl) {
touchImpl->enableTouch();
}
delete touchImpl;
touchImpl = nullptr;
}
/**
* Reload settings
*/
void HandRecognition::reload() {
SElement& touch = settings->getCustomElement("touch");
enabled = false;
touch.getBool("disableTouch", enabled);
if (!enabled) {
delete touchImpl;
touchImpl = nullptr;
return;
}
disableTimeout = 1000;
touch.getInt("timeout", disableTimeout);
if (disableTimeout < 500) {
disableTimeout = 500;
}
delete touchImpl;
touchImpl = nullptr;
string disableMethod;
touch.getString("method", disableMethod);
if (disableMethod == "X11") {
if (!x11Session) {
g_warning("X11 Touch workaround is selected, but no X11 Session running!");
enabled = false;
return;
}
#ifdef X11_ENABLED
touchImpl = new TouchDisableX11();
#endif
} else if (disableMethod == "custom") {
string enableCommand;
touch.getString("cmdEnable", enableCommand);
string disableCommand;
touch.getString("cmdDisable", disableCommand);
touchImpl = new TouchDisableCustom(enableCommand, disableCommand);
} else // Auto detect
{
#ifdef X11_ENABLED
if (x11Session) {
touchImpl = new TouchDisableX11();
}
#endif
}
if (touchImpl) {
touchImpl->init();
}
}
/**
* Called after the timeout
*
* @return true to call again
*/
auto HandRecognition::enableTimeout(HandRecognition* self) -> bool {
gint64 now = g_get_monotonic_time() / 1000;
gint64 lastPenActionTime = now - self->lastPenAction;
if (lastPenActionTime < 20) {
// Pen action within the last 20ms, so simple restart timeout
return true;
}
if (lastPenActionTime > self->disableTimeout) {
// Timeout elapsed, enable touch again
self->enableTouch();
self->touchState = true;
// Do not call again
return false;
}
auto nextTime = static_cast<guint>(now - self->lastPenAction + self->disableTimeout);
g_timeout_add(nextTime, xoj::util::wrap_v<enableTimeout>, self);
// Do not call again, a new time is scheduled
return false;
}
/**
* There was a pen event, restart the timer
*/
void HandRecognition::penEvent() {
lastPenAction = g_get_monotonic_time() / 1000;
if (touchState) {
touchState = false;
if (enabled) {
disableTouch();
}
g_timeout_add(as_unsigned(disableTimeout), xoj::util::wrap_v<enableTimeout>, this);
}
}
/**
* Enable touchscreen
*/
void HandRecognition::enableTouch() {
if (inputContext) {
inputContext->unblockDevice(InputContext::DeviceType::TOUCHSCREEN);
}
if (touchImpl && enabled) {
touchImpl->enableTouch();
}
}
/**
* Disable touchscreen
*/
void HandRecognition::disableTouch() {
if (inputContext) {
inputContext->blockDevice(InputContext::DeviceType::TOUCHSCREEN);
}
if (touchImpl) {
touchImpl->disableTouch();
}
}
/**
* An event from a device occurred
*/
void HandRecognition::event(InputDeviceClass device) {
if (!enabled) {
return;
}
if (device == INPUT_DEVICE_PEN || device == INPUT_DEVICE_ERASER) {
penEvent();
}
}
void HandRecognition::unblock() {
this->enableTouch();
this->touchState = true;
}
| 4,707
|
C++
|
.cpp
| 153
| 25.803922
| 100
| 0.631684
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,632
|
TouchDisableCustom.cpp
|
xournalpp_xournalpp/src/core/gui/inputdevices/touchdisable/TouchDisableCustom.cpp
|
#include "TouchDisableCustom.h"
#include <utility>
#include "util/Util.h"
TouchDisableCustom::TouchDisableCustom(std::string enableCommand, std::string disableCommand):
enableCommand(std::move(enableCommand)), disableCommand(std::move(disableCommand)) {}
TouchDisableCustom::~TouchDisableCustom() = default;
void TouchDisableCustom::enableTouch() { Util::systemWithMessage(enableCommand.c_str()); }
void TouchDisableCustom::disableTouch() { Util::systemWithMessage(disableCommand.c_str()); }
| 507
|
C++
|
.cpp
| 8
| 60.5
| 94
| 0.796748
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.