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,431
|
ActionBackwardCompatibilityLayer.cpp
|
xournalpp_xournalpp/src/core/plugin/ActionBackwardCompatibilityLayer.cpp
|
#include "ActionBackwardCompatibilityLayer.h"
#ifdef ENABLE_PLUGINS
#include <map>
#include <string_view>
#include "control/Control.h"
#include "control/ToolEnums.h"
#include "control/actions/ActionDatabase.h"
#include "control/settings/Settings.h"
#include "control/tools/EditSelection.h"
using namespace std::literals::string_view_literals;
static const std::map<std::string_view, Action> STATELESS_ACTION_MAP = {
{"ACTION_NEW"sv, Action::NEW_FILE},
{"ACTION_OPEN"sv, Action::OPEN},
{"ACTION_ANNOTATE_PDF"sv, Action::ANNOTATE_PDF},
{"ACTION_SAVE"sv, Action::SAVE},
{"ACTION_SAVE_AS"sv, Action::SAVE_AS},
{"ACTION_EXPORT_AS_PDF"sv, Action::EXPORT_AS_PDF},
{"ACTION_EXPORT_AS"sv, Action::EXPORT_AS},
{"ACTION_PRINT"sv, Action::PRINT},
{"ACTION_QUIT"sv, Action::QUIT},
{"ACTION_UNDO"sv, Action::UNDO},
{"ACTION_REDO"sv, Action::REDO},
{"ACTION_CUT"sv, Action::CUT},
{"ACTION_COPY"sv, Action::COPY},
{"ACTION_PASTE"sv, Action::PASTE},
{"ACTION_SEARCH"sv, Action::SEARCH},
{"ACTION_SELECT_ALL"sv, Action::SELECT_ALL},
{"ACTION_DELETE"sv, Action::DELETE},
{"ACTION_SETTINGS"sv, Action::PREFERENCES},
{"ACTION_GOTO_FIRST"sv, Action::GOTO_FIRST},
{"ACTION_GOTO_BACK"sv, Action::GOTO_PREVIOUS},
{"ACTION_GOTO_PAGE"sv, Action::GOTO_PAGE},
{"ACTION_GOTO_NEXT"sv, Action::GOTO_NEXT},
{"ACTION_GOTO_LAST"sv, Action::GOTO_LAST},
{"ACTION_GOTO_NEXT_ANNOTATED_PAGE"sv, Action::GOTO_NEXT_ANNOTATED_PAGE},
{"ACTION_GOTO_PREVIOUS_ANNOTATED_PAGE"sv, Action::GOTO_PREVIOUS_ANNOTATED_PAGE},
{"ACTION_NEW_PAGE_BEFORE"sv, Action::NEW_PAGE_BEFORE},
{"ACTION_DUPLICATE_PAGE"sv, Action::DUPLICATE_PAGE},
{"ACTION_NEW_PAGE_AFTER"sv, Action::NEW_PAGE_AFTER},
{"ACTION_APPEND_NEW_PDF_PAGES"sv, Action::APPEND_NEW_PDF_PAGES},
{"ACTION_NEW_PAGE_AT_END"sv, Action::NEW_PAGE_AT_END},
{"ACTION_DELETE_PAGE"sv, Action::DELETE_PAGE},
{"ACTION_PAPER_FORMAT"sv, Action::PAPER_FORMAT},
{"ACTION_CONFIGURE_PAGE_TEMPLATE"sv, Action::CONFIGURE_PAGE_TEMPLATE},
{"ACTION_PAPER_BACKGROUND_COLOR"sv, Action::PAPER_BACKGROUND_COLOR},
{"ACTION_MOVE_SELECTION_LAYER_UP"sv, Action::MOVE_SELECTION_LAYER_UP},
{"ACTION_MOVE_SELECTION_LAYER_DOWN"sv, Action::MOVE_SELECTION_LAYER_DOWN},
{"ACTION_TOOL_PEN_FILL_OPACITY"sv, Action::TOOL_PEN_FILL_OPACITY},
{"ACTION_TOOL_DEFAULT"sv, Action::SELECT_DEFAULT_TOOL},
{"ACTION_TOOL_HIGHLIGHTER_FILL_OPACITY"sv, Action::TOOL_HIGHLIGHTER_FILL_OPACITY},
{"ACTION_ZOOM_IN"sv, Action::ZOOM_IN},
{"ACTION_ZOOM_OUT"sv, Action::ZOOM_OUT},
{"ACTION_ZOOM_100"sv, Action::ZOOM_100},
{"ACTION_TEX"sv, Action::TEX},
{"ACTION_MANAGE_TOOLBAR"sv, Action::MANAGE_TOOLBAR},
{"ACTION_CUSTOMIZE_TOOLBAR"sv, Action::CUSTOMIZE_TOOLBAR},
{"ACTION_AUDIO_SEEK_FORWARDS"sv, Action::AUDIO_SEEK_FORWARDS},
{"ACTION_AUDIO_SEEK_BACKWARDS"sv, Action::AUDIO_SEEK_BACKWARDS},
{"ACTION_AUDIO_STOP_PLAYBACK"sv, Action::AUDIO_STOP_PLAYBACK},
{"ACTION_PLUGIN_MANAGER"sv, Action::PLUGIN_MANAGER},
{"ACTION_HELP"sv, Action::HELP},
{"ACTION_ABOUT"sv, Action::ABOUT},
{"ACTION_NEW_LAYER"sv, Action::LAYER_NEW},
{"ACTION_DELETE_LAYER"sv, Action::LAYER_DELETE},
{"ACTION_MERGE_LAYER_DOWN"sv, Action::LAYER_MERGE_DOWN},
{"ACTION_GOTO_NEXT_LAYER"sv, Action::LAYER_GOTO_NEXT},
{"ACTION_GOTO_PREVIOUS_LAYER"sv, Action::LAYER_GOTO_PREVIOUS},
{"ACTION_GOTO_TOP_LAYER"sv, Action::LAYER_GOTO_TOP},
{"ACTION_RENAME_LAYER"sv, Action::LAYER_RENAME},
{"ACTION_SELECT_FONT"sv, Action::SELECT_FONT}};
static const std::map<std::string_view, ToolType> SELECT_TOOL_MAP = {
{"ACTION_TOOL_PEN"sv, TOOL_PEN},
{"ACTION_TOOL_ERASER"sv, TOOL_ERASER},
{"ACTION_TOOL_HIGHLIGHTER"sv, TOOL_HIGHLIGHTER},
{"ACTION_TOOL_TEXT"sv, TOOL_TEXT},
{"ACTION_TOOL_IMAGE"sv, TOOL_IMAGE},
{"ACTION_TOOL_SELECT_RECT"sv, TOOL_SELECT_RECT},
{"ACTION_TOOL_SELECT_REGION"sv, TOOL_SELECT_REGION},
{"ACTION_TOOL_SELECT_MULTILAYER_RECT"sv, TOOL_SELECT_MULTILAYER_RECT},
{"ACTION_TOOL_SELECT_MULTILAYER_REGION"sv, TOOL_SELECT_MULTILAYER_REGION},
{"ACTION_TOOL_SELECT_OBJECT"sv, TOOL_SELECT_OBJECT},
{"ACTION_TOOL_PLAY_OBJECT"sv, TOOL_PLAY_OBJECT},
{"ACTION_TOOL_SELECT_PDF_TEXT_LINEAR"sv, TOOL_SELECT_PDF_TEXT_LINEAR},
{"ACTION_TOOL_SELECT_PDF_TEXT_RECT"sv, TOOL_SELECT_PDF_TEXT_RECT},
{"ACTION_TOOL_VERTICAL_SPACE"sv, TOOL_VERTICAL_SPACE},
{"ACTION_TOOL_HAND"sv, TOOL_HAND},
{"ACTION_TOOL_FLOATING_TOOLBOX"sv, TOOL_FLOATING_TOOLBOX}};
static const std::map<std::string_view, std::pair<Action, ToolSize>> TOOL_SIZE_MAP = {
{"ACTION_SIZE_VERY_FINE"sv, {Action::TOOL_SIZE, TOOL_SIZE_VERY_FINE}},
{"ACTION_SIZE_FINE"sv, {Action::TOOL_SIZE, TOOL_SIZE_FINE}},
{"ACTION_SIZE_MEDIUM"sv, {Action::TOOL_SIZE, TOOL_SIZE_MEDIUM}},
{"ACTION_SIZE_THICK"sv, {Action::TOOL_SIZE, TOOL_SIZE_THICK}},
{"ACTION_SIZE_VERY_THICK"sv, {Action::TOOL_SIZE, TOOL_SIZE_VERY_THICK}},
{"ACTION_TOOL_ERASER_SIZE_VERY_FINE"sv, {Action::TOOL_ERASER_SIZE, TOOL_SIZE_VERY_FINE}},
{"ACTION_TOOL_ERASER_SIZE_FINE"sv, {Action::TOOL_ERASER_SIZE, TOOL_SIZE_FINE}},
{"ACTION_TOOL_ERASER_SIZE_MEDIUM"sv, {Action::TOOL_ERASER_SIZE, TOOL_SIZE_MEDIUM}},
{"ACTION_TOOL_ERASER_SIZE_THICK"sv, {Action::TOOL_ERASER_SIZE, TOOL_SIZE_THICK}},
{"ACTION_TOOL_ERASER_SIZE_VERY_THICK"sv, {Action::TOOL_ERASER_SIZE, TOOL_SIZE_VERY_THICK}},
{"ACTION_TOOL_PEN_SIZE_VERY_FINE"sv, {Action::TOOL_PEN_SIZE, TOOL_SIZE_VERY_FINE}},
{"ACTION_TOOL_PEN_SIZE_FINE"sv, {Action::TOOL_PEN_SIZE, TOOL_SIZE_FINE}},
{"ACTION_TOOL_PEN_SIZE_MEDIUM"sv, {Action::TOOL_PEN_SIZE, TOOL_SIZE_MEDIUM}},
{"ACTION_TOOL_PEN_SIZE_THICK"sv, {Action::TOOL_PEN_SIZE, TOOL_SIZE_THICK}},
{"ACTION_TOOL_PEN_SIZE_VERY_THICK"sv, {Action::TOOL_PEN_SIZE, TOOL_SIZE_VERY_THICK}},
{"ACTION_TOOL_HIGHLIGHTER_SIZE_VERY_FINE"sv, {Action::TOOL_HIGHLIGHTER_SIZE, TOOL_SIZE_VERY_FINE}},
{"ACTION_TOOL_HIGHLIGHTER_SIZE_FINE"sv, {Action::TOOL_HIGHLIGHTER_SIZE, TOOL_SIZE_FINE}},
{"ACTION_TOOL_HIGHLIGHTER_SIZE_MEDIUM"sv, {Action::TOOL_HIGHLIGHTER_SIZE, TOOL_SIZE_MEDIUM}},
{"ACTION_TOOL_HIGHLIGHTER_SIZE_THICK"sv, {Action::TOOL_HIGHLIGHTER_SIZE, TOOL_SIZE_THICK}},
{"ACTION_TOOL_HIGHLIGHTER_SIZE_VERY_THICK"sv, {Action::TOOL_HIGHLIGHTER_SIZE, TOOL_SIZE_VERY_THICK}}};
static const std::map<std::string_view, Action> BOOLEAN_ACTION_MAP = {
{"ACTION_SETSQUARE"sv, Action::SETSQUARE},
{"ACTION_COMPASS"sv, Action::COMPASS},
{"ACTION_TOOL_DRAW_RECT"sv, Action::TOOL_DRAW_RECTANGLE},
{"ACTION_TOOL_DRAW_ELLIPSE"sv, Action::TOOL_DRAW_ELLIPSE},
{"ACTION_TOOL_DRAW_ARROW"sv, Action::TOOL_DRAW_ARROW},
{"ACTION_TOOL_DRAW_DOUBLE_ARROW"sv, Action::TOOL_DRAW_DOUBLE_ARROW},
{"ACTION_TOOL_DRAW_COORDINATE_SYSTEM"sv, Action::TOOL_DRAW_COORDINATE_SYSTEM},
{"ACTION_RULER"sv, Action::TOOL_DRAW_LINE},
{"ACTION_TOOL_DRAW_SPLINE"sv, Action::TOOL_DRAW_SPLINE},
{"ACTION_SHAPE_RECOGNIZER"sv, Action::TOOL_DRAW_SHAPE_RECOGNIZER},
{"ACTION_TOOL_FILL"sv, Action::TOOL_FILL},
{"ACTION_TOOL_PEN_FILL"sv, Action::TOOL_PEN_FILL},
{"ACTION_TOOL_HIGHLIGHTER_FILL"sv, Action::TOOL_HIGHLIGHTER_FILL},
{"ACTION_ZOOM_FIT"sv, Action::ZOOM_FIT},
{"ACTION_VIEW_PAIRED_PAGES"sv, Action::PAIRED_PAGES_MODE},
{"ACTION_VIEW_PRESENTATION_MODE"sv, Action::PRESENTATION_MODE},
{"ACTION_FULLSCREEN"sv, Action::FULLSCREEN},
{"ACTION_AUDIO_PAUSE_PLAYBACK"sv, Action::AUDIO_PAUSE_PLAYBACK},
{"ACTION_AUDIO_RECORD"sv, Action::AUDIO_RECORD},
{"ACTION_GRID_SNAPPING"sv, Action::GRID_SNAPPING},
{"ACTION_ROTATION_SNAPPING"sv, Action::ROTATION_SNAPPING},
{"ACTION_HIGHLIGHT_POSITION"sv, Action::POSITION_HIGHLIGHTING}};
static const std::map<std::string_view, const char*> LINE_STYLE_MAP = {{"ACTION_TOOL_LINE_STYLE_PLAIN"sv, "plain"},
{"ACTION_TOOL_LINE_STYLE_DASH"sv, "dash"},
{"ACTION_TOOL_LINE_STYLE_DASH_DOT"sv, "dashdot"},
{"ACTION_TOOL_LINE_STYLE_DOT"sv, "dot"}};
static const std::map<std::string_view, EraserType> ERASER_TYPE_MAP = {
{"ACTION_TOOL_ERASER_STANDARD"sv, ERASER_TYPE_DEFAULT},
{"ACTION_TOOL_ERASER_DELETE_STROKE"sv, ERASER_TYPE_DELETE_STROKE},
{"ACTION_TOOL_ERASER_WHITEOUT"sv, ERASER_TYPE_WHITEOUT}};
static const std::map<std::string_view, int> COL_ROWS_MAP = {
{"ACTION_SET_COLUMNS_1"sv, 1}, {"ACTION_SET_COLUMNS_2"sv, 2}, {"ACTION_SET_COLUMNS_3"sv, 3},
{"ACTION_SET_COLUMNS_4"sv, 4}, {"ACTION_SET_COLUMNS_5"sv, 5}, {"ACTION_SET_COLUMNS_6"sv, 6},
{"ACTION_SET_COLUMNS_7"sv, 7}, {"ACTION_SET_COLUMNS_8"sv, 8}, {"ACTION_SET_ROWS_1"sv, -1},
{"ACTION_SET_ROWS_2"sv, -2}, {"ACTION_SET_ROWS_3"sv, -3}, {"ACTION_SET_ROWS_4"sv, -4},
{"ACTION_SET_ROWS_5"sv, -5}, {"ACTION_SET_ROWS_6"sv, -6}, {"ACTION_SET_ROWS_7"sv, -7},
{"ACTION_SET_ROWS_8"sv, -8}};
static const std::map<std::string_view, std::pair<Action, bool>> LAYOUT_MAP = {
{"ACTION_SET_LAYOUT_HORIZONTAL"sv, {Action::SET_LAYOUT_VERTICAL, false}},
{"ACTION_SET_LAYOUT_VERTICAL"sv, {Action::SET_LAYOUT_VERTICAL, true}},
{"ACTION_SET_LAYOUT_L2R"sv, {Action::SET_LAYOUT_RIGHT_TO_LEFT, false}},
{"ACTION_SET_LAYOUT_R2L"sv, {Action::SET_LAYOUT_RIGHT_TO_LEFT, true}},
{"ACTION_SET_LAYOUT_T2B"sv, {Action::SET_LAYOUT_BOTTOM_TO_TOP, false}},
{"ACTION_SET_LAYOUT_B2T"sv, {Action::SET_LAYOUT_BOTTOM_TO_TOP, true}}};
static const std::map<std::string_view, EditSelection::OrderChange> SELECTION_ORDER_ACTION_MAP = {
{"ACTION_ARRANGE_BRING_TO_FRONT"sv, EditSelection::OrderChange::BringToFront},
{"ACTION_ARRANGE_BRING_FORWARD"sv, EditSelection::OrderChange::BringForward},
{"ACTION_ARRANGE_SEND_BACKWARD"sv, EditSelection::OrderChange::SendBackward},
{"ACTION_ARRANGE_SEND_TO_BACK"sv, EditSelection::OrderChange::SendToBack}};
void ActionBackwardCompatibilityLayer::actionPerformed(Control* ctrl, std::string_view type, bool enabled) {
auto* actionDB = ctrl->getActionDatabase();
if (auto it = STATELESS_ACTION_MAP.find(type); it != STATELESS_ACTION_MAP.end()) {
actionDB->fireActivateAction(it->second);
} else if (auto it = SELECT_TOOL_MAP.find(type); it != SELECT_TOOL_MAP.end()) {
actionDB->fireChangeActionState(Action::SELECT_TOOL, it->second);
} else if (auto it = TOOL_SIZE_MAP.find(type); it != TOOL_SIZE_MAP.end()) {
actionDB->fireChangeActionState(it->second.first, it->second.second);
} else if (auto it = LINE_STYLE_MAP.find(type); it != LINE_STYLE_MAP.end()) {
actionDB->fireChangeActionState(Action::TOOL_PEN_LINE_STYLE, it->second);
} else if (auto it = ERASER_TYPE_MAP.find(type); it != ERASER_TYPE_MAP.end()) {
actionDB->fireChangeActionState(Action::TOOL_ERASER_TYPE, it->second);
} else if (auto it = BOOLEAN_ACTION_MAP.find(type); it != BOOLEAN_ACTION_MAP.end()) {
actionDB->fireChangeActionState(it->second, enabled);
} else if (auto it = COL_ROWS_MAP.find(type); it != COL_ROWS_MAP.end()) {
actionDB->fireChangeActionState(Action::SET_COLUMNS_OR_ROWS, it->second);
} else if (auto it = LAYOUT_MAP.find(type); it != LAYOUT_MAP.end()) {
actionDB->fireChangeActionState(it->second.first, it->second.second);
} else if (auto it = SELECTION_ORDER_ACTION_MAP.find(type); it != SELECTION_ORDER_ACTION_MAP.end()) {
actionDB->fireActivateAction(Action::ARRANGE_SELECTION_ORDER, it->second);
} else {
// The most specific translations not handled by the above cases
if (type == "ACTION_TOGGLE_PAIRS_PARITY") {
int offset = ctrl->getSettings()->getPairsOffset();
actionDB->fireChangeActionState(Action::PAIRED_PAGES_OFFSET, offset + (offset % 2 == 0 ? 1 : -1));
} else {
g_warning("Plugin: Unhandled action event: %s", type.data());
}
}
}
#endif
| 12,571
|
C++
|
.cpp
| 189
| 57.555556
| 120
| 0.652139
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,432
|
PluginController.cpp
|
xournalpp_xournalpp/src/core/plugin/PluginController.cpp
|
#include "PluginController.h"
#include <memory>
#include "control/Control.h"
#include "gui/MainWindow.h"
#include "util/Assert.h"
#include "config-features.h" // for ENABLE_PLUGINS
#ifdef ENABLE_PLUGINS
#include <algorithm>
#include <tuple>
#include <utility>
#include "control/settings/Settings.h"
#include "gui/GladeSearchpath.h"
#include "gui/dialog/PluginDialog.h"
#include "util/PathUtil.h"
#include "util/PopupWindowWrapper.h"
#include "util/StringUtils.h"
#include "Plugin.h"
namespace {
/**
* @brief This Comparator defines the ordering of Plugins in the Plugin-vector, so that all Plugins are sorted first by
* their name, then by their path. Since the name is determined by the parent directory of the Plugin's path, this
* also ensures that only Plugins with unique paths are kept in the vector.
*/
struct PluginComparator {
using KeyType = std::tuple<std::string const&, fs::path const&>;
static auto get_key(Plugin const& plugin) -> KeyType { return {plugin.getName(), plugin.getPath()}; }
[[maybe_unused]] auto operator()(std::unique_ptr<Plugin> const& lhs, std::unique_ptr<Plugin> const& rhs) const;
[[maybe_unused]] auto operator()(std::unique_ptr<Plugin> const& lhs, KeyType const& rhs) const;
[[maybe_unused]] auto operator()(KeyType const& lhs, std::unique_ptr<Plugin> const& rhs) const;
[[maybe_unused]] auto operator()(Plugin const& lhs, Plugin const& rhs) const { return get_key(lhs) < get_key(rhs); }
[[maybe_unused]] auto operator()(Plugin const& lhs, KeyType const& rhs) const { return get_key(lhs) < rhs; }
[[maybe_unused]] auto operator()(KeyType const& lhs, Plugin const& rhs) const { return lhs < get_key(rhs); }
};
auto PluginComparator::operator()(std::unique_ptr<Plugin> const& lhs, std::unique_ptr<Plugin> const& rhs) const {
return PluginComparator{}(*lhs, *rhs);
}
auto PluginComparator::operator()(std::unique_ptr<Plugin> const& lhs, KeyType const& rhs) const {
return PluginComparator{}(*lhs, rhs);
}
auto PluginComparator::operator()(KeyType const& lhs, std::unique_ptr<Plugin> const& rhs) const {
return PluginComparator{}(lhs, *rhs);
}
auto load_available_plugins_from(fs::path const& path, Control* control) -> std::vector<std::unique_ptr<Plugin>> {
if (!fs::is_directory(path)) {
g_info("Skipping Plugin path, it is not a directory: %s", path.string().c_str());
return {};
}
g_info("Loading plugins from: %s", path.string().c_str());
std::vector<std::unique_ptr<Plugin>> returner;
try {
for (auto const& f: fs::directory_iterator(path)) {
if (!f.is_directory()) {
continue;
}
const auto& pluginPath = f.path();
try {
auto plugin = std::make_unique<Plugin>(control, pluginPath.filename().string(), pluginPath);
if (!plugin || !plugin->isValid()) {
g_warning("Error loading plugin \"%s\"", f.path().string().c_str());
continue;
}
plugin->setEnabled(plugin->isDefaultEnabled());
returner.emplace_back(std::move(plugin));
} catch (const std::exception& e) {
g_warning("Error loading plugin \"%s\": %s", f.path().string().c_str(), e.what());
}
}
} catch (const fs::filesystem_error& e) {
g_warning("Could not open plugin dir: \"%s\": %s", path.string().c_str(), e.what());
}
return returner;
}
auto emplace_sorted_if_not_exists(std::vector<std::unique_ptr<Plugin>>& plugins, std::unique_ptr<Plugin> plugin)
-> void {
xoj_assert(std::is_sorted(begin(plugins), end(plugins), PluginComparator{}));
auto iter = std::equal_range(begin(plugins), std::end(plugins), plugin, PluginComparator{});
if (iter.first != iter.second) {
return;
}
plugins.emplace(iter.first, std::move(plugin));
xoj_assert(std::is_sorted(begin(plugins), end(plugins), PluginComparator{}));
}
} // namespace
#endif
PluginController::PluginController(Control* control): control(control) {
#ifdef ENABLE_PLUGINS
// Todo(fabian) move those search paths into PathUtils
auto searchPath = control->getGladeSearchPath()->getFirstSearchPath();
auto searchPaths = {fs::weakly_canonical(searchPath /= "../plugins"), //
Util::getConfigSubfolder("plugins")};
for (auto&& path: searchPaths) {
auto loaded_plugins = load_available_plugins_from(path, control);
this->plugins.reserve(loaded_plugins.size() + this->plugins.size());
for (auto&& plugin: loaded_plugins) {
emplace_sorted_if_not_exists(this->plugins, std::move(plugin));
}
}
Settings* settings = control->getSettings();
// enable plugins
std::vector<std::string> pluginEnabled = StringUtils::split(settings->getPluginEnabled(), ',');
for (auto&& plugin_path: pluginEnabled) {
auto path = fs::path(plugin_path);
auto name = path.filename().string();
auto iter = std::equal_range(begin(plugins), end(plugins), std::tie(name, path), PluginComparator{});
if (iter.first != iter.second) {
iter.first->get()->setEnabled(true);
}
}
// disable plugins
std::vector<std::string> pluginDisabled = StringUtils::split(settings->getPluginDisabled(), ',');
for (auto&& plugin_path: pluginDisabled) {
auto path = fs::path(plugin_path);
auto name = path.filename().string();
auto iter = std::equal_range(begin(plugins), end(plugins), std::tie(name, path), PluginComparator{});
if (iter.first != iter.second) {
iter.first->get()->setEnabled(false);
}
}
for (auto&& plugin: plugins) {
if (plugin->isEnabled()) {
plugin->loadScript();
}
}
#endif
}
void PluginController::registerToolbar() {
#ifdef ENABLE_PLUGINS
for (auto&& p: this->plugins) {
p->registerToolbar();
}
#endif
}
void PluginController::showPluginManager() const {
#ifdef ENABLE_PLUGINS
xoj::popup::PopupWindowWrapper<PluginDialog> dlg(control->getGladeSearchPath(), control->getSettings(),
this->plugins);
dlg.show(control->getGtkWindow());
#endif
}
auto PluginController::createMenuSections(GtkApplicationWindow* win) -> std::vector<GMenuModel*> {
#ifdef ENABLE_PLUGINS
size_t id = 0;
std::vector<GMenuModel*> sections;
for (auto&& p: this->plugins) {
id = p->populateMenuSection(win, id);
auto* section = p->getMenuSection();
if (section) {
sections.emplace_back(section);
}
}
return sections;
#else
return {};
#endif
}
void PluginController::registerToolButtons(ToolMenuHandler* toolMenuHandler) {
#ifdef ENABLE_PLUGINS
for (auto&& p: this->plugins) {
p->registerToolButton(toolMenuHandler);
}
#endif
}
| 6,938
|
C++
|
.cpp
| 162
| 36.67284
| 120
| 0.649778
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,433
|
ToolBase.cpp
|
xournalpp_xournalpp/src/core/control/ToolBase.cpp
|
#include "ToolBase.h"
#include "control/ToolEnums.h" // for DrawingType, EraserType, ToolSize
ToolBase::ToolBase() = default;
ToolBase::~ToolBase() = default;
/**
* @return Color of the tool for all drawing tools
*/
auto ToolBase::getColor() const -> Color { return this->color; }
/**
* @param color Color of the tool for all drawing tools
*/
void ToolBase::setColor(Color color) { this->color = color; }
/**
* @return Size of a drawing tool
*/
auto ToolBase::getSize() const -> ToolSize { return this->size; }
/**
* @param size Size of a drawing tool
*/
void ToolBase::setSize(ToolSize size) { this->size = size; }
/**
* @return Draw special shape
*/
auto ToolBase::getDrawingType() const -> DrawingType { return this->drawingType; }
/**
* @param drawingType Draw special shape
*/
void ToolBase::setDrawingType(DrawingType drawingType) { this->drawingType = drawingType; }
/**
* @return Eraser Type
*/
auto ToolBase::getEraserType() const -> EraserType { return this->eraserType; }
/**
* @param eraserType type of eraser
*/
void ToolBase::setEraserType(EraserType eraserType) { this->eraserType = eraserType; }
/**
* @return Fill of the shape is enabled
*/
auto ToolBase::getFill() const -> bool { return this->fill; }
/**
* @param fill Fill of the shape is enabled
*/
void ToolBase::setFill(bool fill) { this->fill = fill; }
/**
* @return Alpha for fill
*/
auto ToolBase::getFillAlpha() const -> int { return this->fillAlpha; }
/**
* @param fillAlpha Alpha for fill
*/
void ToolBase::setFillAlpha(int fillAlpha) { this->fillAlpha = fillAlpha; }
/**
* @return Style of the line drawing
*/
auto ToolBase::getLineStyle() const -> const LineStyle& { return this->lineStyle; }
/**
* @param style Style of the line drawing
*/
void ToolBase::setLineStyle(const LineStyle& style) { this->lineStyle = style; }
| 1,849
|
C++
|
.cpp
| 60
| 29.066667
| 91
| 0.714447
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,434
|
ScrollHandler.cpp
|
xournalpp_xournalpp/src/core/control/ScrollHandler.cpp
|
#include "ScrollHandler.h"
#include <memory> // for __shared_ptr_access
#include <glib.h> // for g_error
#include "control/zoom/ZoomControl.h" // for ZoomControl
#include "gui/MainWindow.h" // for MainWindow
#include "gui/XournalView.h" // for XournalView
#include "gui/sidebar/Sidebar.h" // for Sidebar
#include "gui/widgets/SpinPageAdapter.h" // for SpinPageAdapter
#include "model/Document.h" // for Document
#include "model/LinkDestination.h" // for LinkDestination
#include "model/XojPage.h" // for XojPage
#include "util/Util.h" // for npos
#include "Control.h" // for Control
ScrollHandler::ScrollHandler(Control* control): control(control) {}
ScrollHandler::~ScrollHandler() = default;
void ScrollHandler::goToPreviousPage() {
if (this->control->getWindow()) {
scrollToPage(this->control->getWindow()->getXournal()->getCurrentPage() - 1);
}
}
void ScrollHandler::goToNextPage() {
if (this->control->getWindow()) {
scrollToPage(this->control->getWindow()->getXournal()->getCurrentPage() + 1);
}
}
void ScrollHandler::goToLastPage() {
if (this->control->getWindow()) {
scrollToPage(this->control->getDocument()->getPageCount() - 1);
}
}
void ScrollHandler::goToFirstPage() {
if (this->control->getWindow()) {
scrollToPage(0);
}
}
void ScrollHandler::scrollToPage(const PageRef& page, XojPdfRectangle rect) {
Document* doc = this->control->getDocument();
doc->lock();
auto p = doc->indexOf(page);
doc->unlock();
if (p != npos) {
scrollToPage(p, rect);
}
}
void ScrollHandler::scrollToPage(size_t page, XojPdfRectangle rect) {
MainWindow* win = this->control->getWindow();
if (win == nullptr) {
g_error("Window is nullptr!");
return;
}
win->getXournal()->scrollTo(page, rect);
}
void ScrollHandler::scrollToLinkDest(const LinkDestination& dest) {
size_t pdfPage = dest.getPdfPage();
if (pdfPage != npos) {
Document* doc = control->getDocument();
doc->lock();
size_t page = doc->findPdfPage(pdfPage);
doc->unlock();
if (page == npos) {
control->askInsertPdfPage(pdfPage);
} else {
if (dest.shouldChangeTop()) {
control->getScrollHandler()->scrollToPage(page, {dest.getLeft(), dest.getTop(), -1, -1});
} else {
if (control->getCurrentPageNo() != page) {
control->getScrollHandler()->scrollToPage(page);
}
}
}
}
}
void ScrollHandler::scrollToAnnotatedPage(bool next) {
if (!this->control->getWindow()) {
return;
}
size_t step = next ? size_t(1) : size_t(-1); // Don't assume blindly that size_t(-1) == npos
Document* doc = this->control->getDocument();
for (size_t i = this->control->getCurrentPageNo() + step; i < doc->getPageCount() && i != size_t(-1); i += step) {
if (doc->getPage(i)->isAnnotated()) {
scrollToPage(i);
break;
}
}
}
auto ScrollHandler::isPageVisible(size_t page, int* visibleHeight) -> bool {
if (!this->control->getWindow()) {
if (visibleHeight) {
*visibleHeight = 0;
}
return false;
}
return this->control->getWindow()->getXournal()->isPageVisible(page, visibleHeight);
}
void ScrollHandler::pageChanged(size_t page) {
if (page == 0) {
return;
}
scrollToPage(page - 1);
}
| 3,572
|
C++
|
.cpp
| 100
| 29.95
| 118
| 0.612126
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,435
|
Control.cpp
|
xournalpp_xournalpp/src/core/control/Control.cpp
|
#include "Control.h"
#include <algorithm> // for max
#include <cstdlib> // for size_t
#include <exception> // for exce...
#include <functional> // for bind
#include <iterator> // for end
#include <locale>
#include <memory> // for make...
#include <numeric> // for accu...
#include <optional> // for opti...
#include <regex> // for regex
#include <utility> // for move
#include "control/AudioController.h" // for Audi...
#include "control/ClipboardHandler.h" // for Clip...
#include "control/CompassController.h" // for Comp...
#include "control/RecentManager.h" // for Rece...
#include "control/ScrollHandler.h" // for Scro...
#include "control/SetsquareController.h" // for Sets...
#include "control/Tool.h" // for Tool
#include "control/ToolHandler.h" // for Tool...
#include "control/actions/ActionDatabase.h" // for Acti...
#include "control/jobs/AutosaveJob.h" // for Auto...
#include "control/jobs/BaseExportJob.h" // for Base...
#include "control/jobs/CustomExportJob.h" // for Cust...
#include "control/jobs/PdfExportJob.h" // for PdfE...
#include "control/jobs/SaveJob.h" // for SaveJob
#include "control/jobs/Scheduler.h" // for JOB_...
#include "control/jobs/XournalScheduler.h" // for Xour...
#include "control/layer/LayerController.h" // for Laye...
#include "control/pagetype/PageTypeHandler.h" // for Page...
#include "control/settings/ButtonConfig.h" // for Butt...
#include "control/settings/MetadataManager.h" // for Meta...
#include "control/settings/PageTemplateSettings.h" // for Page...
#include "control/settings/Settings.h" // for Sett...
#include "control/settings/SettingsEnums.h" // for Button
#include "control/settings/ViewModes.h" // for ViewM..
#include "control/tools/TextEditor.h" // for Text...
#include "control/xojfile/LoadHandler.h" // for Load...
#include "control/zoom/ZoomControl.h" // for Zoom...
#include "gui/MainWindow.h" // for Main...
#include "gui/PageView.h" // for XojP...
#include "gui/PdfFloatingToolbox.h" // for PdfF...
#include "gui/SearchBar.h" // for Sear...
#include "gui/XournalView.h" // for Xour...
#include "gui/XournalppCursor.h" // for Xour...
#include "gui/dialog/AboutDialog.h" // for Abou...
#include "gui/dialog/FormatDialog.h" // for Form...
#include "gui/dialog/GotoDialog.h" // for Goto...
#include "gui/dialog/PageTemplateDialog.h" // for Page...
#include "gui/dialog/SelectBackgroundColorDialog.h" // for Sele...
#include "gui/dialog/SelectOpacityDialog.h" // for Opac...
#include "gui/dialog/SettingsDialog.h" // for Sett...
#include "gui/dialog/ToolbarManageDialog.h" // for Tool...
#include "gui/dialog/XojOpenDlg.h" // for XojO...
#include "gui/dialog/XojSaveDlg.h" // for XojS...
#include "gui/dialog/toolbarCustomize/ToolbarDragDropHandler.h" // for Tool...
#include "gui/inputdevices/CompassInputHandler.h" // for Comp...
#include "gui/inputdevices/GeometryToolInputHandler.h" // for Geom...
#include "gui/inputdevices/HandRecognition.h" // for Hand...
#include "gui/inputdevices/SetsquareInputHandler.h" // for Sets...
#include "gui/menus/menubar/Menubar.h" // for Menubar
#include "gui/sidebar/Sidebar.h" // for Sidebar
#include "gui/toolbarMenubar/ToolMenuHandler.h" // for Tool...
#include "gui/toolbarMenubar/model/ToolbarData.h" // for Tool...
#include "gui/toolbarMenubar/model/ToolbarModel.h" // for Tool...
#include "model/Compass.h" // for Comp...
#include "model/Document.h" // for Docu...
#include "model/DocumentChangeType.h" // for DOCU...
#include "model/DocumentListener.h" // for Docu...
#include "model/Element.h" // for Element
#include "model/Font.h" // for XojFont
#include "model/Image.h" // for Image
#include "model/Layer.h" // for Layer
#include "model/LineStyle.h" // for Line...
#include "model/PageType.h" // for Page...
#include "model/Setsquare.h" // for Sets...
#include "model/Stroke.h" // for Stroke
#include "model/StrokeStyle.h" // for Stro...
#include "model/TexImage.h" // for TexI...
#include "model/Text.h" // for Text
#include "model/XojPage.h" // for XojPage
#include "pdf/base/XojPdfPage.h" // for XojP...
#include "plugin/PluginController.h" // for Plug...
#include "undo/AddUndoAction.h" // for AddU...
#include "undo/InsertDeletePageUndoAction.h" // for Inse...
#include "undo/InsertUndoAction.h" // for Inse...
#include "undo/MoveSelectionToLayerUndoAction.h" // for Move...
#include "undo/SwapUndoAction.h" // for SwapUndoAction
#include "undo/UndoAction.h" // for Undo...
#include "util/Assert.h" // for xoj_assert
#include "util/Color.h" // for oper...
#include "util/PathUtil.h" // for clea...
#include "util/PlaceholderString.h" // for Plac...
#include "util/PopupWindowWrapper.h" // for PopupWindowWrapper
#include "util/Stacktrace.h" // for Stac...
#include "util/Util.h" // for exec...
#include "util/XojMsgBox.h" // for XojM...
#include "util/glib_casts.h" // for wrap_v
#include "util/i18n.h" // for _, FS
#include "util/safe_casts.h" // for as_unsigned
#include "util/serializing/InputStreamException.h" // for Inpu...
#include "util/serializing/ObjectInputStream.h" // for Obje...
#include "view/CompassView.h" // for Comp...
#include "view/SetsquareView.h" // for Sets...
#include "view/overlays/OverlayView.h" // for Over...
#include "CrashHandler.h" // for emer...
#include "LatexController.h" // for Late...
#include "PageBackgroundChangeController.h" // for Page...
#include "PrintHandler.h" // for print
#include "UndoRedoController.h" // for Undo...
#include "config-dev.h" // for SETT...
#include "config.h" // for PROJ...
using std::string;
Control::Control(GApplication* gtkApp, GladeSearchpath* gladeSearchPath, bool disableAudio): gtkApp(gtkApp) {
this->undoRedo = new UndoRedoHandler(this);
this->undoRedo->addUndoRedoListener(this);
this->isBlocking = false;
this->gladeSearchPath = gladeSearchPath;
this->metadata = new MetadataManager();
this->cursor = new XournalppCursor(this);
auto name = Util::getConfigFile(SETTINGS_XML_FILE);
this->settings = new Settings(std::move(name));
this->settings->load();
this->loadPaletteFromSettings();
this->pageTypes = new PageTypeHandler(gladeSearchPath);
this->audioController =
(disableAudio || this->settings->isAudioDisabled()) ? nullptr : new AudioController(this->settings, this);
this->scrollHandler = new ScrollHandler(this);
this->scheduler = new XournalScheduler();
this->doc = new Document(this);
// for crashhandling
setEmergencyDocument(this->doc);
this->zoom = new ZoomControl();
this->zoom->setZoomStep(this->settings->getZoomStep() / 100.0);
this->zoom->setZoomStepScroll(this->settings->getZoomStepScroll() / 100.0);
this->zoom->setZoom100Value(this->settings->getDisplayDpi() / Util::DPI_NORMALIZATION_FACTOR);
this->toolHandler = new ToolHandler(this, this->actionDB.get(), this->settings);
this->toolHandler->loadSettings();
this->initButtonTool();
/**
* This is needed to update the previews
*/
this->changeTimout = g_timeout_add_seconds(5, xoj::util::wrap_v<checkChangedDocument>, this);
this->pageBackgroundChangeController = std::make_unique<PageBackgroundChangeController>(this);
this->layerController = new LayerController(this);
this->layerController->registerListener(this);
this->pluginController = new PluginController(this);
this->pluginController->registerToolbar();
}
Control::~Control() {
g_source_remove(this->changeTimout);
this->enableAutosave(false);
deleteLastAutosaveFile();
this->scheduler->stop();
this->changedPages.clear(); // can be removed, will be done by implicit destructor
delete this->pluginController;
this->pluginController = nullptr;
delete this->clipboardHandler;
this->clipboardHandler = nullptr;
delete this->undoRedo;
this->undoRedo = nullptr;
delete this->settings;
this->settings = nullptr;
delete this->toolHandler;
this->toolHandler = nullptr;
delete this->sidebar;
this->sidebar = nullptr;
delete this->doc;
this->doc = nullptr;
delete this->searchBar;
this->searchBar = nullptr;
delete this->scrollHandler;
this->scrollHandler = nullptr;
delete this->pageTypes;
this->pageTypes = nullptr;
delete this->metadata;
this->metadata = nullptr;
delete this->cursor;
this->cursor = nullptr;
delete this->zoom;
this->zoom = nullptr;
delete this->scheduler;
this->scheduler = nullptr;
delete this->dragDropHandler;
this->dragDropHandler = nullptr;
delete this->audioController;
this->audioController = nullptr;
delete this->layerController;
this->layerController = nullptr;
}
struct Control::MissingPdfData {
bool wasPdfAttached;
std::string missingFileName;
};
void Control::setLastAutosaveFile(fs::path newAutosaveFile) {
try {
if (!this->lastAutosaveFilename.empty() && !fs::equivalent(newAutosaveFile, this->lastAutosaveFilename) &&
fs::exists(newAutosaveFile)) {
deleteLastAutosaveFile();
}
} catch (const fs::filesystem_error& e) {
auto fmtstr = FS(_F("Filesystem error: {1}") % e.what());
Util::execInUiThread([fmtstr, win = getGtkWindow()]() { XojMsgBox::showErrorToUser(win, fmtstr); });
}
this->lastAutosaveFilename = std::move(newAutosaveFile);
}
void Control::deleteLastAutosaveFile() {
try {
if (fs::exists(this->lastAutosaveFilename)) {
fs::remove(this->lastAutosaveFilename);
}
} catch (const fs::filesystem_error& e) {
auto fmtstr = FS(_F("Could not remove old autosave file \"{1}\": {2}") % this->lastAutosaveFilename.string() %
e.what());
Util::execInUiThread([fmtstr, win = getGtkWindow()]() { XojMsgBox::showErrorToUser(win, fmtstr); });
}
this->lastAutosaveFilename.clear();
}
auto Control::checkChangedDocument(Control* control) -> bool {
if (!control->doc->tryLock()) {
// call again later
return true;
}
for (auto const& page: control->changedPages) {
auto p = control->doc->indexOf(page);
if (p != npos) {
for (DocumentListener* dl: control->changedDocumentListeners) {
dl->pageChanged(p);
}
}
}
control->changedPages.clear();
control->doc->unlock();
// Call again
return true;
}
void Control::saveSettings() {
this->toolHandler->saveSettings();
gint width = 0;
gint height = 0;
gtk_window_get_size(getGtkWindow(), &width, &height);
if (!this->win->isMaximized()) {
this->settings->setMainWndSize(width, height);
}
this->settings->setMainWndMaximized(this->win->isMaximized());
this->sidebar->saveSize();
}
void Control::initWindow(MainWindow* win) {
this->win = win;
this->actionDB = std::make_unique<ActionDatabase>(this);
selectTool(toolHandler->getToolType());
this->sidebar = new Sidebar(win, this);
XojMsgBox::setDefaultWindow(getGtkWindow());
updatePageNumbers(0, npos);
// toolHandler->eraserTypeChanged();
this->searchBar = new SearchBar(this);
if (settings->isPresentationMode()) {
setViewPresentationMode(true);
} else if (settings->isViewFixedRows()) {
setViewRows(settings->getViewRows());
} else {
setViewColumns(settings->getViewColumns());
}
setViewLayoutVert(settings->getViewLayoutVert());
setViewLayoutR2L(settings->getViewLayoutR2L());
setViewLayoutB2T(settings->getViewLayoutB2T());
setViewPairedPages(settings->isShowPairedPages());
toolLineStyleChanged();
this->clipboardHandler = new ClipboardHandler(this, win->getXournal()->getWidget());
this->enableAutosave(settings->isAutosaveEnabled());
}
auto Control::autosaveCallback(Control* control) -> bool {
if (!control->undoRedo->isChangedAutosave()) {
// do nothing, nothing changed
return true;
}
auto* job = new AutosaveJob(control);
control->scheduler->addJob(job, JOB_PRIORITY_NONE);
job->unref();
return true;
}
void Control::enableAutosave(bool enable) {
if (this->autosaveTimeout) {
g_source_remove(this->autosaveTimeout);
this->autosaveTimeout = 0;
}
if (enable) {
auto timeout = guint(settings->getAutosaveTimeout()) * 60U;
this->autosaveTimeout = g_timeout_add_seconds(timeout, xoj::util::wrap_v<autosaveCallback>, this);
}
}
void Control::updatePageNumbers(size_t page, size_t pdfPage) {
if (this->win == nullptr) {
return;
}
this->win->updatePageNumbers(page, this->doc->getPageCount(), pdfPage);
this->sidebar->selectPageNr(page, pdfPage);
this->metadata->storeMetadata(this->doc->getEvMetadataFilename(), static_cast<int>(page),
getZoomControl()->getZoomReal());
if (settings->isPageNumberInTitlebarShown()) {
this->updateWindowTitle();
}
auto current = getCurrentPageNo();
auto count = this->doc->getPageCount();
this->actionDB->enableAction(Action::GOTO_FIRST, current != 0);
this->actionDB->enableAction(Action::GOTO_PREVIOUS, current != 0);
this->actionDB->enableAction(Action::GOTO_PREVIOUS_ANNOTATED_PAGE, current != 0);
this->actionDB->enableAction(Action::GOTO_PAGE, count > 1);
this->actionDB->enableAction(Action::GOTO_NEXT, current < count - 1);
this->actionDB->enableAction(Action::GOTO_LAST, current < count - 1);
this->actionDB->enableAction(Action::GOTO_NEXT_ANNOTATED_PAGE, current < count - 1);
}
bool Control::toggleCompass() {
return toggleGeometryTool<Compass, xoj::view::CompassView, CompassController, CompassInputHandler,
GeometryToolType::COMPASS>();
}
bool Control::toggleSetsquare() {
return toggleGeometryTool<Setsquare, xoj::view::SetsquareView, SetsquareController, SetsquareInputHandler,
GeometryToolType::SETSQUARE>();
}
template <class ToolClass, class ViewClass, class ControllerClass, class InputHandlerClass, GeometryToolType toolType>
bool Control::toggleGeometryTool() {
bool needsNewGeometryTool = !this->geometryToolController || this->geometryToolController->getType() != toolType;
this->resetGeometryTool();
if (!needsNewGeometryTool) {
return false;
}
const auto view = this->win->getXournal()->getViewFor(getCurrentPageNo());
const auto* xournal = GTK_XOURNAL(this->win->getXournal()->getWidget());
auto tool = new ToolClass();
view->addOverlayView(std::make_unique<ViewClass>(tool, view, zoom));
this->geometryTool = std::unique_ptr<GeometryTool>(tool);
this->geometryToolController = std::make_unique<ControllerClass>(view, tool);
std::unique_ptr<InputHandlerClass> geometryToolInputHandler =
std::make_unique<InputHandlerClass>(this->win->getXournal(), geometryToolController.get());
geometryToolInputHandler->registerToPool(tool->getHandlerPool());
Range range = view->getVisiblePart();
if (range.isValid()) {
double originX = (range.minX + range.maxX) * .5;
double originY = (range.minY + range.maxY) * .5;
geometryToolController->translate(originX, originY);
} else {
geometryToolController->translate(view->getWidth() * .5, view->getHeight() * .5);
}
xournal->input->setGeometryToolInputHandler(std::move(geometryToolInputHandler));
geometryTool->notify();
return true;
}
void Control::resetGeometryTool() {
this->geometryToolController.reset();
this->geometryTool.reset();
auto* xournal = GTK_XOURNAL(this->win->getXournal()->getWidget());
xournal->input->resetGeometryToolInputHandler();
}
auto Control::copy() -> bool {
if (this->win && this->win->getXournal()->copy()) {
return true;
}
return this->clipboardHandler->copy();
}
auto Control::cut() -> bool {
if (this->win && this->win->getXournal()->cut()) {
return true;
}
return this->clipboardHandler->cut();
}
auto Control::paste() -> bool {
if (this->win && this->win->getXournal()->paste()) {
return true;
}
return this->clipboardHandler->paste();
}
void Control::selectAlpha(OpacityFeature feature) {
int alpha = 0;
switch (feature) {
case OPACITY_FILL_PEN:
alpha = this->toolHandler->getPenFill();
break;
case OPACITY_FILL_HIGHLIGHTER:
alpha = this->toolHandler->getHighlighterFill();
break;
case OPACITY_SELECT_PDF_TEXT_MARKER:
alpha = this->toolHandler->getSelectPDFTextMarkerOpacity();
break;
default:
g_warning("Unhandled OpacityFeature for selectAlpha event: %s", opacityFeatureToString(feature).c_str());
Stacktrace::printStacktrace();
break;
}
auto dlg = xoj::popup::PopupWindowWrapper<xoj::popup::SelectOpacityDialog>(
gladeSearchPath, alpha, feature, [&th = *toolHandler](int alpha, OpacityFeature feature) {
switch (feature) {
case OPACITY_FILL_PEN:
th.setPenFill(alpha);
break;
case OPACITY_FILL_HIGHLIGHTER:
th.setHighlighterFill(alpha);
break;
case OPACITY_SELECT_PDF_TEXT_MARKER:
th.setSelectPDFTextMarkerOpacity(alpha);
break;
default:
g_warning("Unhandled OpacityFeature for callback of SelectOpacityDialog: %s",
opacityFeatureToString(feature).c_str());
Stacktrace::printStacktrace();
break;
}
});
dlg.show(getGtkWindow());
}
void Control::clearSelectionEndText() {
clearSelection();
if (win) {
win->getXournal()->endTextAllPages();
}
}
void Control::selectAllOnPage() {
auto pageNr = getCurrentPageNo();
if (pageNr == npos) {
return;
}
this->doc->lock();
XojPageView* view = win->getXournal()->getViewFor(pageNr);
if (view == nullptr) {
this->doc->unlock();
return;
}
PageRef page = this->doc->getPage(pageNr);
Layer* layer = page->getSelectedLayer();
win->getXournal()->clearSelection();
auto elements = layer->clearNoFree();
this->doc->unlock();
if (!elements.empty()) {
InsertionOrder insertionOrder;
insertionOrder.reserve(elements.size());
Element::Index n = 0;
for (auto&& e: elements) {
insertionOrder.emplace_back(std::move(e), n++);
}
auto [sel, rg] =
SelectionFactory::createFromFloatingElements(this, page, layer, view, std::move(insertionOrder));
page->fireRangeChanged(rg);
win->getXournal()->setSelection(sel.release());
}
}
void Control::reorderSelection(EditSelection::OrderChange change) {
EditSelection* sel = win->getXournal()->getSelection();
if (!sel) {
return;
}
auto undoAction = sel->rearrangeInsertionOrder(change);
this->undoRedo->addUndoAction(std::move(undoAction));
}
/**
* Fire page selected, but first check if the page Number is valid
*
* @return the page ID or size_t_npos if the page is not found
*/
auto Control::firePageSelected(const PageRef& page) -> size_t {
this->doc->lock();
size_t pageId = this->doc->indexOf(page);
this->doc->unlock();
if (pageId == npos) {
return npos;
}
firePageSelected(pageId);
return pageId;
}
void Control::firePageSelected(size_t page) { DocumentHandler::firePageSelected(page); }
void Control::manageToolbars() {
xoj::popup::PopupWindowWrapper<ToolbarManageDialog> dlg(
this->gladeSearchPath, this->win->getToolbarModel(), [win = this->win]() {
if (const auto& tbs = win->getToolbarModel()->getToolbars();
std::none_of(tbs.begin(), tbs.end(),
[tb = win->getSelectedToolbar()](const auto& t) { return t.get() == tb; })) {
// The active toolbar has been deleted!
xoj_assert(!tbs.empty());
win->toolbarSelected(tbs.front().get());
XojMsgBox::showErrorToUser(
GTK_WINDOW(win->getWindow()),
_("You deleted the active toolbar. Falling back to the default toolbar."));
}
win->updateToolbarMenu();
auto filepath = Util::getConfigFile(TOOLBAR_CONFIG);
win->getToolbarModel()->save(filepath);
});
dlg.show(GTK_WINDOW(this->win->getWindow()));
this->win->updateToolbarMenu();
auto filepath = Util::getConfigFile(TOOLBAR_CONFIG);
this->win->getToolbarModel()->save(filepath);
}
void Control::customizeToolbars() {
xoj_assert(this->win != nullptr);
if (this->win->getSelectedToolbar()->isPredefined()) {
enum { YES = 1, NO };
XojMsgBox::askQuestion(getGtkWindow(),
FC(_F("The Toolbarconfiguration \"{1}\" is predefined, "
"would you create a copy to edit?") %
this->win->getSelectedToolbar()->getName()),
std::string(), {{_("Yes"), YES}, {_("No"), NO}}, [ctrl = this](int response) {
if (response == YES) {
auto data = std::make_unique<ToolbarData>(*ctrl->win->getSelectedToolbar());
ToolbarModel* model = ctrl->win->getToolbarModel();
model->initCopyNameId(data.get());
ctrl->win->toolbarSelected(model->add(std::move(data)));
ctrl->win->updateToolbarMenu();
xoj_assert(!ctrl->win->getSelectedToolbar()->isPredefined());
ctrl->customizeToolbars();
}
});
} else {
if (!this->dragDropHandler) {
this->dragDropHandler = new ToolbarDragDropHandler(this);
}
this->dragDropHandler->configure();
}
}
void Control::setToolDrawingType(DrawingType type) {
if (this->toolHandler->getDrawingType() != type) {
if (this->toolHandler->getDrawingType() == DRAWING_TYPE_SPLINE) {
// Shape changed from spline to something else: finish ongoing splines
if (win) {
win->getXournal()->endSplineAllPages();
}
}
this->toolHandler->setDrawingType(type);
}
}
void Control::setFullscreen(bool enabled) {
win->setFullscreen(enabled);
actionDB->setActionState(Action::FULLSCREEN, enabled);
}
void Control::setShowSidebar(bool enabled) {
win->setSidebarVisible(enabled);
actionDB->setActionState(Action::SHOW_SIDEBAR, enabled);
if (settings->isSidebarVisible() != enabled &&
settings->getActiveViewMode() == PresetViewModeIds::VIEW_MODE_DEFAULT) {
settings->setSidebarVisible(enabled);
ViewMode viewMode = settings->getViewModes()[PresetViewModeIds::VIEW_MODE_DEFAULT];
viewMode.showSidebar = enabled;
settings->setViewMode(PresetViewModeIds::VIEW_MODE_DEFAULT, viewMode);
}
}
void Control::setShowToolbar(bool enabled) {
win->setToolbarVisible(enabled);
actionDB->setActionState(Action::SHOW_TOOLBAR, enabled);
if (settings->isToolbarVisible() != enabled &&
settings->getActiveViewMode() == PresetViewModeIds::VIEW_MODE_DEFAULT) {
settings->setToolbarVisible(enabled);
ViewMode viewMode = settings->getViewModes()[PresetViewModeIds::VIEW_MODE_DEFAULT];
viewMode.showToolbar = enabled;
settings->setViewMode(PresetViewModeIds::VIEW_MODE_DEFAULT, viewMode);
}
}
void Control::setShowMenubar(bool enabled) {
win->setMenubarVisible(enabled);
actionDB->setActionState(Action::SHOW_MENUBAR, enabled);
}
void Control::disableSidebarTmp(bool disabled) { this->sidebar->setTmpDisabled(disabled); }
void Control::addDefaultPage(const std::optional<std::string>& pageTemplate, Document* doc) {
const std::string& templ = pageTemplate.value_or(settings->getPageTemplate());
PageTemplateSettings model;
model.parse(templ);
auto page = std::make_shared<XojPage>(model.getPageWidth(), model.getPageHeight());
page->setBackgroundColor(model.getBackgroundColor());
page->setBackgroundType(model.getBackgroundType());
if (doc == nullptr || doc == this->doc) {
// Apply to the curent document
this->doc->lock();
this->doc->addPage(std::move(page));
this->doc->unlock();
} else {
doc->addPage(std::move(page));
}
}
void Control::updatePageActions() {
auto currentPage = getCurrentPageNo();
auto nbPages = this->doc->getPageCount();
this->actionDB->enableAction(Action::DELETE_PAGE, nbPages > 1);
this->actionDB->enableAction(Action::MOVE_PAGE_TOWARDS_BEGINNING, currentPage != 0);
this->actionDB->enableAction(Action::MOVE_PAGE_TOWARDS_END, currentPage < nbPages - 1);
}
void Control::deletePage() {
clearSelectionEndText();
// if the current page contains the geometry tool, reset it
size_t pNr = getCurrentPageNo();
if (geometryToolController) {
doc->lock();
auto page = doc->indexOf(geometryToolController->getPage());
doc->unlock();
if (page == pNr) {
resetGeometryTool();
}
}
// don't allow delete pages if we have less than 2 pages,
// so we can be (more or less) sure there is at least one page.
if (this->doc->getPageCount() < 2) {
return;
}
if (pNr == npos || pNr > this->doc->getPageCount()) {
// something went wrong...
return;
}
this->doc->lock();
PageRef page = doc->getPage(pNr);
this->doc->unlock();
// first send event, then delete page...
firePageDeleted(pNr);
this->doc->lock();
doc->deletePage(pNr);
this->doc->unlock();
this->undoRedo->addUndoAction(std::make_unique<InsertDeletePageUndoAction>(page, pNr, false));
if (pNr >= this->doc->getPageCount()) {
pNr = this->doc->getPageCount() - 1;
}
scrollHandler->scrollToPage(pNr);
this->win->getXournal()->forceUpdatePagenumbers();
}
void Control::duplicatePage() {
auto page = getCurrentPage();
if (!page) {
return;
}
auto pageCopy = std::make_shared<XojPage>(*page);
insertPage(pageCopy, getCurrentPageNo() + 1);
}
void Control::movePageTowardsBeginning() {
auto currentPageNo = this->getCurrentPageNo();
if (currentPageNo < 1) {
g_warning("Control::movePageTowardsBeginning() called on the first page");
return;
}
if (currentPageNo == npos) {
g_warning("Control::movePageTowardsBeginning() called with current page selected");
return;
}
auto lock = std::unique_lock(*this->doc);
PageRef page = this->doc->getPage(currentPageNo);
PageRef otherPage = doc->getPage(currentPageNo - 1);
if (!page || !otherPage) {
g_warning("Control::movePageTowardsBeginning() called but no page %zu or %zu", currentPageNo,
currentPageNo - 1);
return;
}
doc->deletePage(currentPageNo);
doc->insertPage(page, currentPageNo - 1);
lock.unlock();
UndoRedoHandler* undo = this->getUndoRedoHandler();
undo->addUndoAction(std::make_unique<SwapUndoAction>(currentPageNo - 1, true, page, otherPage));
this->firePageDeleted(currentPageNo);
this->firePageInserted(currentPageNo - 1);
this->firePageSelected(currentPageNo - 1);
this->getScrollHandler()->scrollToPage(currentPageNo - 1);
}
void Control::movePageTowardsEnd() {
auto currentPageNo = this->getCurrentPageNo();
if (currentPageNo == npos) {
g_warning("Control::movePageTowardsEnd() called with current page selected");
return;
}
auto lock = std::unique_lock(*this->doc);
auto nbPage = this->doc->getPageCount();
if (currentPageNo >= nbPage - 1) {
g_warning("Control::movePageTowardsEnd() called on last page");
return;
}
PageRef page = this->doc->getPage(currentPageNo);
PageRef otherPage = doc->getPage(currentPageNo + 1);
if (!page || !otherPage) {
g_warning("Control::movePageTowardsEnd() called but no page %zu or %zu", currentPageNo, currentPageNo + 1);
return;
}
doc->deletePage(currentPageNo);
doc->insertPage(page, currentPageNo + 1);
lock.unlock();
this->undoRedo->addUndoAction(std::make_unique<SwapUndoAction>(currentPageNo, false, page, otherPage));
this->firePageDeleted(currentPageNo);
this->firePageInserted(currentPageNo + 1);
this->firePageSelected(currentPageNo + 1);
this->getScrollHandler()->scrollToPage(currentPageNo + 1);
}
/// Remove mnemonic indicators in menu labels
static std::string removeMnemonics(std::string orig) {
std::regex reg("_(.)");
return std::regex_replace(orig, reg, "$1");
}
void Control::askInsertPdfPage(size_t pdfPage) {
using Responses = enum { CANCEL = 1, AFTER = 2, END = 3 };
std::vector<XojMsgBox::Button> buttons = {{_("Cancel"), Responses::CANCEL},
{_("Insert after current page"), Responses::AFTER},
{_("Insert at end"), Responses::END}};
// Must match the labels in main.glade and PageTypeHandler.cpp
std::string pathToMenuEntry = removeMnemonics(_("_Journal") + std::string(" → ") + _("Paper B_ackground") +
std::string(" → ") + _("With PDF background"));
XojMsgBox::askQuestion(this->getGtkWindow(),
FC(_F("Your current document does not contain PDF Page no {1}\n"
"Would you like to insert this page?\n\n"
"Tip: You can select {2} to insert a PDF page.") %
static_cast<int64_t>(pdfPage + 1) % pathToMenuEntry),
"", buttons, [ctrl = this, pdfPage](int response) {
if (response == Responses::AFTER || response == Responses::END) {
Document* doc = ctrl->getDocument();
doc->lock();
size_t position = response == Responses::AFTER ? ctrl->getCurrentPageNo() + 1 :
doc->getPageCount();
XojPdfPageSPtr pdf = doc->getPdfPage(pdfPage);
doc->unlock();
if (pdf) {
auto page = std::make_shared<XojPage>(pdf->getWidth(), pdf->getHeight());
page->setBackgroundPdfPageNr(pdfPage);
ctrl->insertPage(page, position);
}
}
});
}
void Control::insertNewPage(size_t position, bool shouldScrollToPage) {
pageBackgroundChangeController->insertNewPage(position, shouldScrollToPage);
}
void Control::appendNewPdfPages() {
auto pageCount = this->doc->getPageCount();
// find last page with pdf background and get its pdf page number
auto currentPdfPageCount = [&]() {
for (size_t i = pageCount; i != 0; --i) {
if (auto page = doc->getPage(i - 1); page && page->getBackgroundType().isPdfPage()) {
return page->getPdfPageNr() + 1;
}
}
return size_t{0U};
}();
auto pdfPageCount = this->doc->getPdfPageCount();
auto insertCount = pdfPageCount - currentPdfPageCount;
if (insertCount == 0) {
string msg = FS(_F("No pdf pages available to append. You may need to reopen the document first."));
XojMsgBox::showErrorToUser(getGtkWindow(), msg);
}
for (size_t i = 0; i != insertCount; ++i) {
doc->lock();
XojPdfPageSPtr pdf = doc->getPdfPage(currentPdfPageCount + i);
doc->unlock();
if (pdf) {
auto newPage = std::make_shared<XojPage>(pdf->getWidth(), pdf->getHeight());
newPage->setBackgroundPdfPageNr(currentPdfPageCount + i);
insertPage(newPage, pageCount + i);
} else {
string msg = FS(_F("Unable to retrieve pdf page.")); // should not happen
XojMsgBox::showErrorToUser(getGtkWindow(), msg);
}
}
}
void Control::insertPage(const PageRef& page, size_t position, bool shouldScrollToPage) {
this->doc->lock();
this->doc->insertPage(page, position); // insert the new page to the document and update page numbers
this->doc->unlock();
// notify document listeners about the inserted page; this creates the new XojViewPage, recalculates the layout
// and creates a preview page in the sidebar
firePageInserted(position);
getCursor()->updateCursor();
// make the inserted page fully visible (or at least as much from the top which fits on the screen),
// and make the page appear selected
if (shouldScrollToPage) {
scrollHandler->scrollToPage(position);
firePageSelected(position);
}
updatePageActions();
undoRedo->addUndoAction(std::make_unique<InsertDeletePageUndoAction>(page, position, true));
}
void Control::gotoPage() {
auto popup = xoj::popup::PopupWindowWrapper<xoj::popup::GotoDialog>(
this->gladeSearchPath, this->getCurrentPageNo(), this->doc->getPageCount(),
[scroll = this->scrollHandler](size_t pageNumber) {
xoj_assert(pageNumber != 0);
scroll->scrollToPage(pageNumber - 1);
});
popup.show(GTK_WINDOW(this->win->getWindow()));
}
void Control::updateBackgroundSizeButton() {
if (this->win == nullptr) {
return;
}
// Update paper color button
auto const& p = getCurrentPage();
if (!p || this->win == nullptr) {
return;
}
PageType bg = p->getBackgroundType();
this->actionDB->enableAction(Action::PAPER_BACKGROUND_COLOR, !bg.isSpecial());
// PDF page size is defined, you cannot change it
this->actionDB->enableAction(Action::PAPER_FORMAT, !bg.isPdfPage());
}
void Control::paperTemplate() {
auto popup = xoj::popup::PopupWindowWrapper<xoj::popup::PageTemplateDialog>(this->gladeSearchPath, settings,
win->getToolMenuHandler(), pageTypes);
popup.show(GTK_WINDOW(this->win->getWindow()));
}
void Control::paperFormat() {
auto const& page = getCurrentPage();
if (!page || page->getBackgroundType().isPdfPage()) {
return;
}
clearSelectionEndText();
auto popup = xoj::popup::PopupWindowWrapper<xoj::popup::FormatDialog>(
this->gladeSearchPath, settings, page->getWidth(), page->getHeight(),
[ctrl = this, page](double width, double height) {
ctrl->doc->lock();
Document::setPageSize(page, width, height);
size_t pageNo = ctrl->doc->indexOf(page);
size_t pageCount = ctrl->doc->getPageCount();
ctrl->doc->unlock();
if (pageNo != npos && pageNo < pageCount) {
ctrl->firePageSizeChanged(pageNo);
}
});
popup.show(GTK_WINDOW(this->win->getWindow()));
}
void Control::changePageBackgroundColor() {
auto pNr = getCurrentPageNo();
this->doc->lock();
auto const& p = this->doc->getPage(pNr);
this->doc->unlock();
if (!p) {
return;
}
clearSelectionEndText();
PageType bg = p->getBackgroundType();
if (bg.isSpecial()) {
return;
}
xoj::popup::PopupWindowWrapper<SelectBackgroundColorDialog> dlg(this, [p, pNr, ctrl = this](Color color) {
p->setBackgroundColor(color);
ctrl->firePageChanged(pNr);
});
dlg.show(GTK_WINDOW(this->win->getWindow()));
}
void Control::setViewPairedPages(bool enabled) {
settings->setShowPairedPages(enabled);
win->getXournal()->layoutPages();
scrollHandler->scrollToPage(getCurrentPageNo());
}
void Control::setViewFullscreenMode(bool enabled) {
if (enabled) {
this->loadViewMode(VIEW_MODE_FULLSCREEN);
} else {
this->loadViewMode(VIEW_MODE_DEFAULT);
}
}
void Control::setViewPresentationMode(bool enabled) {
if (enabled) {
this->loadViewMode(VIEW_MODE_PRESENTATION);
bool success = zoom->updateZoomPresentationValue();
if (!success) {
g_warning("Error calculating zoom value");
return;
}
} else {
this->loadViewMode(VIEW_MODE_DEFAULT);
if (settings->isViewFixedRows()) {
setViewRows(settings->getViewRows());
} else {
setViewColumns(settings->getViewColumns());
}
setViewLayoutVert(settings->getViewLayoutVert());
setViewLayoutR2L(settings->getViewLayoutR2L());
setViewLayoutB2T(settings->getViewLayoutB2T());
}
zoom->setZoomPresentationMode(enabled);
settings->setPresentationMode(enabled);
// Disable Zoom
this->actionDB->enableAction(Action::ZOOM_IN, !enabled);
this->actionDB->enableAction(Action::ZOOM_OUT, !enabled);
this->actionDB->enableAction(Action::ZOOM_FIT, !enabled);
this->actionDB->enableAction(Action::ZOOM_100, !enabled);
this->actionDB->enableAction(Action::ZOOM, !enabled);
// TODO Figure out how to replace this
// fireEnableAction(ACTION_FOOTER_ZOOM_SLIDER, !enabled);
this->actionDB->enableAction(Action::SET_LAYOUT_BOTTOM_TO_TOP, !enabled);
this->actionDB->enableAction(Action::SET_LAYOUT_RIGHT_TO_LEFT, !enabled);
this->actionDB->enableAction(Action::SET_LAYOUT_VERTICAL, !enabled);
this->actionDB->enableAction(Action::SET_COLUMNS_OR_ROWS, !enabled);
// disable selection of scroll hand tool
// TODO Figure out how to replace this
// fireEnableAction(ACTION_TOOL_HAND, !enabled);
win->getXournal()->layoutPages();
scrollHandler->scrollToPage(getCurrentPageNo());
}
void Control::setPairsOffset(int numOffset) {
settings->setPairsOffset(numOffset);
win->getXournal()->layoutPages();
scrollHandler->scrollToPage(getCurrentPageNo());
}
void Control::setViewColumns(int numColumns) {
settings->setViewColumns(numColumns);
settings->setViewFixedRows(false);
win->getXournal()->layoutPages();
scrollHandler->scrollToPage(getCurrentPageNo());
}
void Control::setViewRows(int numRows) {
settings->setViewRows(numRows);
settings->setViewFixedRows(true);
win->getXournal()->layoutPages();
scrollHandler->scrollToPage(getCurrentPageNo());
}
void Control::setViewLayoutVert(bool vert) {
settings->setViewLayoutVert(vert);
win->getXournal()->layoutPages();
scrollHandler->scrollToPage(getCurrentPageNo());
}
void Control::setViewLayoutR2L(bool r2l) {
settings->setViewLayoutR2L(r2l);
win->getXournal()->layoutPages();
scrollHandler->scrollToPage(getCurrentPageNo());
}
void Control::setViewLayoutB2T(bool b2t) {
settings->setViewLayoutB2T(b2t);
win->getXournal()->layoutPages();
scrollHandler->scrollToPage(getCurrentPageNo());
}
auto Control::getCurrentPageNo() const -> size_t {
if (this->win) {
return this->win->getXournal()->getCurrentPage();
}
return 0;
}
auto Control::searchTextOnPage(const std::string& text, size_t pageNumber, size_t index, size_t* occurrences,
XojPdfRectangle* matchRect) -> bool {
return getWindow()->getXournal()->searchTextOnPage(text, pageNumber, index, occurrences, matchRect);
}
auto Control::getCurrentPage() -> PageRef {
this->doc->lock();
PageRef p = this->doc->getPage(getCurrentPageNo());
this->doc->unlock();
return p;
}
void Control::undoRedoChanged() {
this->actionDB->enableAction(Action::UNDO, undoRedo->canUndo());
this->actionDB->enableAction(Action::REDO, undoRedo->canRedo());
win->setUndoDescription(undoRedo->undoDescription());
win->setRedoDescription(undoRedo->redoDescription());
updateWindowTitle();
}
void Control::undoRedoPageChanged(PageRef page) {
if (std::find(begin(this->changedPages), end(this->changedPages), page) == end(this->changedPages)) {
this->changedPages.emplace_back(std::move(page));
}
}
void Control::selectTool(ToolType type) {
// keep text-selection when switching from text to seletion tool
auto oldTool = getToolHandler()->getActiveTool();
if (oldTool && win && isSelectToolType(type) && oldTool->getToolType() == ToolType::TOOL_TEXT &&
this->win->getXournal()->getTextEditor() && !(this->win->getXournal()->getTextEditor()->bufferEmpty())) {
auto xournal = this->win->getXournal();
Text* textobj = xournal->getTextEditor()->getTextElement();
clearSelectionEndText();
auto pageNr = getCurrentPageNo();
XojPageView* view = xournal->getViewFor(pageNr);
xoj_assert(view != nullptr);
PageRef page = view->getPage();
auto sel = SelectionFactory::createFromElementOnActiveLayer(this, page, view, textobj);
xournal->setSelection(sel.release());
}
toolHandler->selectTool(type);
toolHandler->fireToolChanged();
}
void Control::selectDefaultTool() {
ButtonConfig* cfg = settings->getButtonConfig(Button::BUTTON_DEFAULT);
cfg->applyConfigToToolbarTool(toolHandler);
if (toolHandler->getToolType() != TOOL_NONE) {
selectTool(toolHandler->getToolType());
}
}
void Control::setFontSelected(const XojFont& font) {
this->actionDB->setActionState(Action::FONT, font.asString().c_str());
}
void Control::toolChanged() {
ToolType type = toolHandler->getToolType();
this->actionDB->setActionState(Action::SELECT_TOOL, type);
this->actionDB->enableAction(Action::TOOL_DRAW_LINE, toolHandler->hasCapability(TOOL_CAP_RULER));
this->actionDB->enableAction(Action::TOOL_DRAW_RECTANGLE, toolHandler->hasCapability(TOOL_CAP_RECTANGLE));
this->actionDB->enableAction(Action::TOOL_DRAW_ELLIPSE, toolHandler->hasCapability(TOOL_CAP_ELLIPSE));
this->actionDB->enableAction(Action::TOOL_DRAW_ARROW, toolHandler->hasCapability(TOOL_CAP_ARROW));
this->actionDB->enableAction(Action::TOOL_DRAW_DOUBLE_ARROW, toolHandler->hasCapability(TOOL_CAP_DOUBLE_ARROW));
this->actionDB->enableAction(Action::TOOL_DRAW_COORDINATE_SYSTEM, toolHandler->hasCapability(TOOL_CAP_ARROW));
this->actionDB->enableAction(Action::TOOL_DRAW_SPLINE, toolHandler->hasCapability(TOOL_CAP_SPLINE));
this->actionDB->enableAction(Action::TOOL_DRAW_SHAPE_RECOGNIZER, toolHandler->hasCapability(TOOL_CAP_RECOGNIZER));
DrawingType dt = toolHandler->getDrawingType();
this->actionDB->setActionState(Action::TOOL_DRAW_LINE, dt == DRAWING_TYPE_LINE);
this->actionDB->setActionState(Action::TOOL_DRAW_RECTANGLE, dt == DRAWING_TYPE_RECTANGLE);
this->actionDB->setActionState(Action::TOOL_DRAW_ELLIPSE, dt == DRAWING_TYPE_ELLIPSE);
this->actionDB->setActionState(Action::TOOL_DRAW_ARROW, dt == DRAWING_TYPE_ARROW);
this->actionDB->setActionState(Action::TOOL_DRAW_DOUBLE_ARROW, dt == DRAWING_TYPE_DOUBLE_ARROW);
this->actionDB->setActionState(Action::TOOL_DRAW_COORDINATE_SYSTEM, dt == DRAWING_TYPE_COORDINATE_SYSTEM);
this->actionDB->setActionState(Action::TOOL_DRAW_SPLINE, dt == DRAWING_TYPE_SPLINE);
this->actionDB->setActionState(Action::TOOL_DRAW_SHAPE_RECOGNIZER, dt == DRAWING_TYPE_SHAPE_RECOGNIZER);
bool enableSize = toolHandler->hasCapability(TOOL_CAP_SIZE);
this->actionDB->enableAction(Action::TOOL_SIZE, enableSize);
if (enableSize) {
toolSizeChanged();
}
// Set or reset the lineStyle
toolLineStyleChanged();
bool enableFill = toolHandler->hasCapability(TOOL_CAP_FILL);
this->actionDB->enableAction(Action::TOOL_FILL, enableFill);
this->actionDB->enableAction(Action::TOOL_FILL_OPACITY, enableFill);
if (enableFill) {
toolFillChanged();
}
bool enableColor = toolHandler->hasCapability(TOOL_CAP_COLOR);
this->actionDB->enableAction(Action::TOOL_COLOR, enableColor);
this->actionDB->enableAction(Action::SELECT_COLOR, enableColor);
if (enableColor) {
toolColorChanged();
}
getCursor()->updateCursor();
if (type != TOOL_TEXT) {
if (win) {
win->getXournal()->endTextAllPages();
}
}
if (toolHandler->getDrawingType() != DRAWING_TYPE_SPLINE) {
if (win) {
win->getXournal()->endSplineAllPages();
}
}
}
void Control::eraserSizeChanged() {
this->actionDB->setActionState(Action::TOOL_ERASER_SIZE, toolHandler->getEraserSize());
}
void Control::penSizeChanged() { this->actionDB->setActionState(Action::TOOL_PEN_SIZE, toolHandler->getPenSize()); }
void Control::highlighterSizeChanged() {
this->actionDB->setActionState(Action::TOOL_HIGHLIGHTER_SIZE, toolHandler->getHighlighterSize());
}
void Control::toolSizeChanged() {
if (toolHandler->getToolType() == TOOL_PEN) {
penSizeChanged();
} else if (toolHandler->getToolType() == TOOL_ERASER) {
eraserSizeChanged();
} else if (toolHandler->getToolType() == TOOL_HIGHLIGHTER) {
highlighterSizeChanged();
}
this->actionDB->setActionState(Action::TOOL_SIZE, toolHandler->getSize());
getCursor()->updateCursor();
}
void Control::toolFillChanged() {
this->actionDB->setActionState(Action::TOOL_FILL, toolHandler->getFill() != -1);
this->actionDB->setActionState(Action::TOOL_PEN_FILL, toolHandler->getPenFillEnabled());
this->actionDB->setActionState(Action::TOOL_HIGHLIGHTER_FILL, toolHandler->getHighlighterFillEnabled());
}
void Control::toolLineStyleChanged() {
std::optional<string> style = getLineStyleToSelect();
this->actionDB->setActionState(Action::TOOL_PEN_LINE_STYLE, style ? style->c_str() : "none");
}
auto Control::getLineStyleToSelect() -> std::optional<string> const {
std::optional<std::string> style;
if (auto* tool = toolHandler->getActiveTool(); tool->getToolType() == TOOL_PEN) {
style = StrokeStyle::formatStyle(tool->getLineStyle());
}
if (!win) {
return style;
}
const EditSelection* sel = win->getXournal()->getSelection();
if (!sel) {
return style;
}
bool isFirstPenStrokeElement = true;
std::optional<std::string> previous_style;
// Todo(cpp20) Replace with std::ranges::filter_view and for_first_then_for_each
for (const Element* e: sel->getElements()) {
if (e->getType() == ELEMENT_STROKE) {
const auto* s = dynamic_cast<const Stroke*>(e);
if (s->getToolType().hasLineStyle()) {
style = StrokeStyle::formatStyle(s->getLineStyle());
if (isFirstPenStrokeElement) {
previous_style = style;
isFirstPenStrokeElement = false;
} else {
if (style != previous_style) {
return std::nullopt;
}
}
}
}
}
return style;
}
void Control::toolColorChanged() {
this->actionDB->setActionState(Action::TOOL_COLOR, getToolHandler()->getColorMaskAlpha());
getCursor()->updateCursor();
}
void Control::changeColorOfSelection() {
if (this->win && toolHandler->hasCapability(TOOL_CAP_COLOR)) {
EditSelection* sel = this->win->getXournal()->getSelection();
if (sel) {
undoRedo->addUndoAction(sel->setColor(toolHandler->getColor()));
}
TextEditor* edit = getTextEditor();
if (this->toolHandler->getToolType() == TOOL_TEXT && edit != nullptr) {
// Todo move into selection
edit->setColor(toolHandler->getColor());
}
}
}
void Control::showSettings() {
// take note of some settings before to compare with after
struct {
Color selectionColor;
bool verticalSpace;
int verticalSpaceAmountAbove;
int verticalSpaceAmountBelow;
bool horizontalSpace;
int horizontalSpaceAmountRight;
int horizontalSpaceAmountLeft;
bool unlimitedScrolling;
StylusCursorType stylusCursorType;
bool highlightPosition;
SidebarNumberingStyle sidebarStyle;
std::optional<std::filesystem::path> colorPaletteSetting;
} settingsBeforeDialog = {
settings->getBorderColor(),
settings->getAddVerticalSpace(),
settings->getAddVerticalSpaceAmountAbove(),
settings->getAddVerticalSpaceAmountBelow(),
settings->getAddHorizontalSpace(),
settings->getAddHorizontalSpaceAmountRight(),
settings->getAddHorizontalSpaceAmountLeft(),
settings->getUnlimitedScrolling(),
settings->getStylusCursorType(),
settings->isHighlightPosition(),
settings->getSidebarNumberingStyle(),
settings->getColorPaletteSetting(),
};
auto dlg = xoj::popup::PopupWindowWrapper<SettingsDialog>(
this->gladeSearchPath, settings, this,
std::vector<fs::path>{Util::getBuiltInPaletteDirectoryPath(), Util::getCustomPaletteDirectoryPath()},
[ctrl = this, settingsBeforeDialog]() {
Settings* settings = ctrl->getSettings();
MainWindow* win = ctrl->win;
XournalView* xournal = win->getXournal();
// note which settings have changed and act accordingly
if (settingsBeforeDialog.selectionColor != settings->getBorderColor()) {
xournal->forceUpdatePagenumbers();
}
if (!settings->getUnlimitedScrolling() &&
(settingsBeforeDialog.verticalSpace != settings->getAddVerticalSpace() ||
settingsBeforeDialog.horizontalSpace != settings->getAddHorizontalSpace() ||
settingsBeforeDialog.verticalSpaceAmountAbove != settings->getAddVerticalSpaceAmountAbove() ||
settingsBeforeDialog.horizontalSpaceAmountRight != settings->getAddHorizontalSpaceAmountRight() ||
settingsBeforeDialog.verticalSpaceAmountBelow != settings->getAddVerticalSpaceAmountBelow() ||
settingsBeforeDialog.horizontalSpaceAmountLeft != settings->getAddHorizontalSpaceAmountLeft())) {
xournal->layoutPages();
double const xChange =
(settings->getAddHorizontalSpace() ? settings->getAddHorizontalSpaceAmountLeft() : 0) -
(settingsBeforeDialog.horizontalSpace ? settingsBeforeDialog.horizontalSpaceAmountLeft : 0);
const double yChange =
(settings->getAddVerticalSpace() ? settings->getAddVerticalSpaceAmountAbove() : 0) -
(settingsBeforeDialog.verticalSpace ? settingsBeforeDialog.verticalSpaceAmountAbove : 0);
win->getLayout()->scrollRelative(xChange, yChange);
}
if (settingsBeforeDialog.unlimitedScrolling != settings->getUnlimitedScrolling()) {
const int xUnlimited = static_cast<int>(win->getLayout()->getVisibleRect().width);
const int yUnlimited = static_cast<int>(win->getLayout()->getVisibleRect().height);
const double xChange =
settingsBeforeDialog.unlimitedScrolling ?
-xUnlimited + (settingsBeforeDialog.horizontalSpace ?
settingsBeforeDialog.horizontalSpaceAmountLeft :
0) :
xUnlimited - (settingsBeforeDialog.horizontalSpace ?
settingsBeforeDialog.horizontalSpaceAmountLeft :
0);
const double yChange =
settingsBeforeDialog.unlimitedScrolling ?
-yUnlimited + (settingsBeforeDialog.verticalSpace ?
settingsBeforeDialog.verticalSpaceAmountAbove :
0) :
yUnlimited - (settingsBeforeDialog.verticalSpace ?
settingsBeforeDialog.verticalSpaceAmountAbove :
0);
xournal->layoutPages();
win->getLayout()->scrollRelative(xChange, yChange);
}
if (settingsBeforeDialog.stylusCursorType != settings->getStylusCursorType() ||
settingsBeforeDialog.highlightPosition != settings->isHighlightPosition()) {
ctrl->getCursor()->updateCursor();
}
if (settingsBeforeDialog.colorPaletteSetting.has_value() &&
settingsBeforeDialog.colorPaletteSetting.value() != settings->getColorPaletteSetting()) {
ctrl->loadPaletteFromSettings();
ctrl->getWindow()->getToolMenuHandler()->updateColorToolItems(ctrl->getPalette());
ctrl->getWindow()->reloadToolbars();
}
ctrl->getSidebar()->saveSize();
ctrl->win->updateScrollbarSidebarPosition();
ctrl->updateWindowTitle();
ctrl->enableAutosave(settings->isAutosaveEnabled());
ctrl->zoom->setZoomStep(settings->getZoomStep() / 100.0);
ctrl->zoom->setZoomStepScroll(settings->getZoomStepScroll() / 100.0);
ctrl->zoom->setZoom100Value(settings->getDisplayDpi() / Util::DPI_NORMALIZATION_FACTOR);
if (settingsBeforeDialog.sidebarStyle != settings->getSidebarNumberingStyle()) {
ctrl->getSidebar()->layout();
}
xournal->getHandRecognition()->reload();
ctrl->win->updateColorscheme();
});
dlg.show(GTK_WINDOW(this->win->getWindow()));
}
static std::unique_ptr<Document> createNewDocument(Control* ctrl, fs::path filepath,
const std::optional<std::string>& pageTemplate) {
auto newDoc = std::make_unique<Document>(ctrl);
if (!filepath.empty()) {
newDoc->setFilepath(std::move(filepath));
}
ctrl->addDefaultPage(pageTemplate, newDoc.get());
return newDoc;
}
void Control::newFile(fs::path filepath) {
this->close(
[ctrl = this, filepath = std::move(filepath)](bool closed) {
if (closed) {
ctrl->replaceDocument(createNewDocument(ctrl, std::move(filepath), std::nullopt), -1);
}
},
true);
}
/**
* Check if this is an autosave file, return false in this case and display a user instruction
*/
static auto shouldFileOpen(fs::path const& filepath, GtkWindow* win) -> bool {
auto basePath = Util::getCacheSubfolder("");
auto isChild = Util::isChildOrEquivalent(filepath, basePath);
if (isChild) {
string msg = FS(_F("Do not open Autosave files. They may will be overwritten!\n"
"Copy the files to another folder.\n"
"Files from Folder {1} cannot be opened.") %
basePath.u8string());
XojMsgBox::showErrorToUser(win, msg);
}
return !isChild;
}
void Control::askToOpenFile() {
/**
* Question: in case the current file has not been saved yet, do we want:
* 1. First ask to save it, save it or discard it and then show the FileChooserDialog to open a new file
* 2. First show the FileChooserDialog, and if a valid file has been selected and successfully opened, ask to
* save or discard the current file
* For now, this implements option 1.
*/
this->close([ctrl = this](bool closed) {
if (closed) {
xoj::OpenDlg::showOpenFileDialog(ctrl->getGtkWindow(), ctrl->settings, [ctrl](fs::path path) {
g_message("%s", (_F("file: {1}") % path.string()).c_str());
ctrl->openFileWithoutSavingTheCurrentDocument(std::move(path), false, -1, [](bool) {});
});
}
});
}
void Control::replaceDocument(std::unique_ptr<Document> doc, int scrollToPage) {
this->closeDocument();
fs::path filepath = doc->getFilepath();
this->doc->lock();
*this->doc = *doc;
this->doc->unlock();
// Set folder as last save path, so the next save will be at the current document location
// This is important because of the new .xopp format, where Xournal .xoj handled as import,
// not as file to load
if (!filepath.empty()) {
settings->setLastSavePath(filepath.parent_path());
}
fireDocumentChanged(DOCUMENT_CHANGE_COMPLETE);
fileLoaded(scrollToPage);
}
void Control::openXoppFile(fs::path filepath, int scrollToPage, std::function<void(bool)> callback) {
LoadHandler loadHandler;
std::unique_ptr<Document> doc(loadHandler.loadDocument(filepath));
if (!doc) {
string msg = FS(_F("Error opening file \"{1}\"") % filepath.u8string()) + "\n" + loadHandler.getLastError();
XojMsgBox::showErrorToUser(this->getGtkWindow(), msg);
callback(false);
return;
}
std::optional<MissingPdfData> missingPdf;
if (!loadHandler.getMissingPdfFilename().empty() || loadHandler.isAttachedPdfMissing()) {
missingPdf = {loadHandler.isAttachedPdfMissing(), loadHandler.getMissingPdfFilename()};
}
auto afterOpen = [ctrl = this, missingPdf = std::move(missingPdf), doc = std::move(doc), filepath,
scrollToPage]() mutable {
ctrl->replaceDocument(std::move(doc), scrollToPage);
if (missingPdf && (missingPdf->wasPdfAttached || !missingPdf->missingFileName.empty())) {
// give the user a second chance to select a new PDF filepath, or to discard the PDF
ctrl->promptMissingPdf(missingPdf.value(), filepath);
}
};
if (loadHandler.getFileVersion() > FILE_FORMAT_VERSION) {
enum { YES = 1, NO };
std::vector<XojMsgBox::Button> buttons = {{_("Yes"), YES}, {_("No"), NO}};
XojMsgBox::askQuestion(
this->getGtkWindow(), _("File version mismatch"),
_("The file being loaded has a file format version newer than the one currently supported by this "
"version of Xournal++, so it may not load properly. Open anyways?"),
buttons, [afterOpen = std::move(afterOpen), callback = std::move(callback)](int response) mutable {
if (response == YES) {
afterOpen();
callback(true);
} else {
callback(false);
}
});
} else {
afterOpen();
callback(true);
}
}
bool Control::openPdfFile(fs::path filepath, bool attachToDocument, int scrollToPage) {
this->getCursor()->setCursorBusy(true);
auto doc = std::make_unique<Document>(this);
bool success = doc->readPdf(filepath, /*initPages=*/true, attachToDocument);
if (success) {
this->replaceDocument(std::move(doc), scrollToPage);
} else {
std::string msg = FS(_F("Error reading PDF file \"{1}\"\n{2}") % filepath.u8string() % doc->getLastErrorMsg());
XojMsgBox::showErrorToUser(this->getGtkWindow(), msg);
}
this->getCursor()->setCursorBusy(false);
return success;
}
bool Control::openXoptFile(fs::path filepath) {
auto pageTemplate = Util::readString(filepath);
if (!pageTemplate) {
// Unable to read the template from the file
return false;
}
this->replaceDocument(createNewDocument(this, std::move(filepath), pageTemplate), -1);
return true;
}
void Control::openFileWithoutSavingTheCurrentDocument(fs::path filepath, bool attachToDocument, int scrollToPage,
std::function<void(bool)> callback) {
if (filepath.empty() || !fs::exists(filepath)) {
this->replaceDocument(createNewDocument(this, std::move(filepath), std::nullopt), -1);
callback(true);
return;
}
if (filepath.extension() == ".xopt") {
this->openXoptFile(std::move(filepath));
callback(true);
return;
}
if (Util::hasPdfFileExt(filepath)) {
if (!attachToDocument && this->settings->isAutoloadPdfXoj()) {
const std::vector<std::string> exts = {".xopp", ".xoj", ".pdf.xopp", ".pdf.xoj"};
fs::path root = filepath;
Util::clearExtensions(root, ".pdf");
for (const std::string& ext: exts) {
fs::path f = root;
f += ext;
if (fs::exists(f)) {
this->openXoppFile(std::move(f), scrollToPage, std::move(callback));
return;
}
}
}
callback(this->openPdfFile(std::move(filepath), attachToDocument, scrollToPage));
return;
}
this->openXoppFile(std::move(filepath), scrollToPage, std::move(callback));
}
void Control::openFile(fs::path filepath, std::function<void(bool)> callback, int scrollToPage, bool forceOpen) {
if (filepath.empty() || (!forceOpen && !shouldFileOpen(filepath, getGtkWindow()))) {
return;
}
this->close([ctrl = this, filepath = std::move(filepath), cb = std::move(callback),
scrollToPage](bool closed) mutable {
if (closed) {
ctrl->openFileWithoutSavingTheCurrentDocument(std::move(filepath), false, scrollToPage, std::move(cb));
}
});
}
void Control::fileLoaded(int scrollToPage) {
this->doc->lock();
auto filepath = this->doc->getEvMetadataFilename();
this->doc->unlock();
if (!filepath.empty()) {
MetadataEntry md = MetadataManager::getForFile(filepath);
if (!md.valid) {
md.zoom = -1;
md.page = 0;
}
if (scrollToPage >= 0) {
md.page = scrollToPage;
}
loadMetadata(md);
RecentManager::addRecentFileFilename(filepath);
} else {
zoom->updateZoomFitValue();
zoom->setZoomFitMode(true);
}
updateWindowTitle();
win->getXournal()->forceUpdatePagenumbers();
getCursor()->updateCursor();
updatePageActions();
}
enum class MissingPdfDialogOptions : gint { USE_PROPOSED, SELECT_OTHER, REMOVE, CANCEL };
void Control::promptMissingPdf(Control::MissingPdfData& missingPdf, const fs::path& filepath) {
const fs::path missingFilePath = fs::path(missingPdf.missingFileName);
// create error message
std::string parentFolderPath;
std::string filename;
#if defined(WIN32)
parentFolderPath = missingFilePath.parent_path().string();
filename = missingFilePath.filename().string();
#else
// since POSIX systems detect the whole Windows path as a filename, this checks whether missingFilePath
// contains a Windows path
std::regex regex(R"([A-Z]:\\(?:.*\\)*(.*))");
std::cmatch matchInfo;
if (std::regex_match(missingFilePath.filename().string().c_str(), matchInfo, regex) && matchInfo[1].matched) {
parentFolderPath = missingFilePath.filename().string();
filename = matchInfo[1].str();
} else {
parentFolderPath = missingFilePath.parent_path().string();
filename = missingFilePath.filename().string();
}
#endif
std::string msg;
if (missingPdf.wasPdfAttached) {
msg = FS(_F("The attached background file could not be found. It might have been moved, "
"renamed or deleted."));
} else {
msg = FS(_F("The background file \"{1}\" could not be found. It might have been moved, renamed or "
"deleted.\nIt was last seen at: \"{2}\"") %
filename % parentFolderPath);
}
// try to find file in current directory
auto proposedPdfFilepath = filepath.parent_path() / filename;
bool proposePdfFile = !missingPdf.wasPdfAttached && !filename.empty() && fs::exists(proposedPdfFilepath) &&
!fs::is_directory(proposedPdfFilepath);
if (proposePdfFile) {
msg += FS(_F("\nProposed replacement file: \"{1}\"") % proposedPdfFilepath.string());
}
// show the dialog
std::vector<XojMsgBox::Button> buttons = {
{_("Select another PDF"), static_cast<int>(MissingPdfDialogOptions::SELECT_OTHER)},
{_("Remove PDF Background"), static_cast<int>(MissingPdfDialogOptions::REMOVE)},
{_("Cancel"), static_cast<int>(MissingPdfDialogOptions::CANCEL)}};
if (proposePdfFile) {
buttons.insert(buttons.begin(),
{_("Use proposed PDF"), static_cast<int>(MissingPdfDialogOptions::USE_PROPOSED)});
}
XojMsgBox::askQuestion(
this->getGtkWindow(), _("Missing PDF background file"), msg, buttons,
std::bind(&Control::missingPdfDialogResponseHandler, this, proposedPdfFilepath, std::placeholders::_1));
}
void Control::missingPdfDialogResponseHandler(fs::path proposedPdfFilepath, int responseId) {
switch (static_cast<MissingPdfDialogOptions>(responseId)) {
case MissingPdfDialogOptions::USE_PROPOSED:
if (!proposedPdfFilepath.empty()) {
this->pageBackgroundChangeController->changePdfPagesBackground(proposedPdfFilepath, false);
}
break;
case MissingPdfDialogOptions::SELECT_OTHER:
Util::execInUiThread([this]() {
xoj::OpenDlg::showAnnotatePdfDialog(getGtkWindow(), settings, [this](fs::path path, bool attachPdf) {
if (!path.empty()) {
this->pageBackgroundChangeController->changePdfPagesBackground(path, attachPdf);
}
});
});
break;
case MissingPdfDialogOptions::REMOVE:
this->pageBackgroundChangeController->applyBackgroundToAllPages(PageType(PageTypeFormat::Plain));
break;
default:
break;
}
}
class MetadataCallbackData {
public:
Control* ctrl{};
MetadataEntry md;
};
/**
* Load the data after processing the document...
*/
auto Control::loadMetadataCallback(MetadataCallbackData* data) -> bool {
if (!data->md.valid) {
return false;
}
ZoomControl* zoom = data->ctrl->zoom;
if (zoom->isZoomPresentationMode()) {
data->ctrl->setViewPresentationMode(true);
} else if (zoom->isZoomFitMode()) {
zoom->updateZoomFitValue();
zoom->setZoomFitMode(true);
} else {
zoom->setZoomFitMode(false);
zoom->setZoom(data->md.zoom * zoom->getZoom100Value());
}
data->ctrl->scrollHandler->scrollToPage(as_unsigned(data->md.page));
// Do not call again!
return false;
}
void Control::loadMetadata(MetadataEntry md) {
auto* data = new MetadataCallbackData();
data->md = std::move(md);
data->ctrl = this;
g_idle_add_full(G_PRIORITY_DEFAULT_IDLE, xoj::util::wrap_v<loadMetadataCallback>, data,
&xoj::util::destroy_cb<MetadataCallbackData>);
}
void Control::askToAnnotatePdf() {
this->close([ctrl = this](bool closed) {
if (closed) {
xoj::OpenDlg::showAnnotatePdfDialog(ctrl->getGtkWindow(), ctrl->settings,
[ctrl](fs::path path, bool attachPdf) {
if (!path.empty()) {
ctrl->openPdfFile(std::move(path), attachPdf, -1);
}
});
}
});
}
void Control::print() {
this->doc->lock();
PrintHandler::print(this->doc, getCurrentPageNo(), this->getGtkWindow());
this->doc->unlock();
}
void Control::block(const string& name) {
if (this->isBlocking) {
return;
}
// Disable all gui Control, to get full control over the application
win->setDynamicallyGeneratedSubmenuDisabled(true);
actionDB->disableAll();
getCursor()->setCursorBusy(true);
disableSidebarTmp(true);
this->statusbar = this->win->get("statusbar");
this->lbState = GTK_LABEL(this->win->get("lbState"));
this->pgState = GTK_PROGRESS_BAR(this->win->get("pgState"));
gtk_label_set_text(this->lbState, name.c_str());
gtk_widget_show(this->statusbar);
this->maxState = 100;
this->isBlocking = true;
}
void Control::unblock() {
if (!this->isBlocking) {
return;
}
this->win->setDynamicallyGeneratedSubmenuDisabled(false);
actionDB->resetEnableStatus();
getCursor()->setCursorBusy(false);
disableSidebarTmp(false);
gtk_widget_hide(this->statusbar);
this->isBlocking = false;
}
void Control::setMaximumState(size_t max) { this->maxState = max; }
void Control::setCurrentState(size_t state) {
Util::execInUiThread([=]() {
gtk_progress_bar_set_fraction(this->pgState,
static_cast<gdouble>(state) / static_cast<gdouble>(this->maxState));
});
}
void Control::showFontDialog() {
this->actionDB->enableAction(Action::SELECT_FONT, false); // Only one dialog
auto* dlg = gtk_font_chooser_dialog_new(_("Select font"), GTK_WINDOW(this->win->getWindow()));
gtk_font_chooser_set_font(GTK_FONT_CHOOSER(dlg), settings->getFont().asString().c_str());
auto popup = xoj::popup::PopupWindowWrapper<XojMsgBox>(
GTK_DIALOG(dlg),
[this, dlg](int response) {
if (response == GTK_RESPONSE_OK) {
auto font =
xoj::util::OwnedCString::assumeOwnership(gtk_font_chooser_get_font(GTK_FONT_CHOOSER(dlg)));
this->actionDB->fireChangeActionState(Action::FONT, font.get());
}
this->actionDB->enableAction(Action::SELECT_FONT, true);
},
XojMsgBox::IMMEDIATE); // We need IMMEDIATE so accessing GTK_FONT_CHOOSER(dlg) is not UB
popup.show(GTK_WINDOW(this->win->getWindow()));
}
void Control::showColorChooserDialog() {
this->actionDB->enableAction(Action::SELECT_COLOR, false); // Only one dialog
auto* dlg = gtk_color_chooser_dialog_new(_("Select color"), GTK_WINDOW(this->win->getWindow()));
GdkRGBA c = Util::argb_to_GdkRGBA(toolHandler->getColor());
gtk_color_chooser_set_rgba(GTK_COLOR_CHOOSER(dlg), &c);
gtk_color_chooser_set_use_alpha(GTK_COLOR_CHOOSER(dlg), false);
auto popup = xoj::popup::PopupWindowWrapper<XojMsgBox>(
GTK_DIALOG(dlg),
[this, dlg](int response) {
if (response == GTK_RESPONSE_OK) {
GdkRGBA c;
gtk_color_chooser_get_rgba(GTK_COLOR_CHOOSER(dlg), &c);
this->actionDB->fireChangeActionState(Action::TOOL_COLOR, Util::GdkRGBA_to_rgb(c));
}
this->actionDB->enableAction(Action::SELECT_COLOR, true);
},
XojMsgBox::IMMEDIATE); // We need IMMEDIATE so accessing GTK_COLOR_CHOOSER(dlg) is not UB
popup.show(GTK_WINDOW(this->win->getWindow()));
}
void Control::updateWindowTitle() {
string title{};
this->doc->lock();
if (doc->getFilepath().empty()) {
if (doc->getPdfFilepath().empty()) {
title = _("Unsaved Document");
} else {
if (settings->isPageNumberInTitlebarShown()) {
title += ("[" + std::to_string(getCurrentPageNo() + 1) + "/" + std::to_string(doc->getPageCount()) +
"] ");
}
if (undoRedo->isChanged()) {
title += "*";
}
if (settings->isFilepathInTitlebarShown()) {
title += ("[" + doc->getPdfFilepath().parent_path().u8string() + "] - " +
doc->getPdfFilepath().filename().u8string());
} else {
title += doc->getPdfFilepath().filename().u8string();
}
}
} else {
if (settings->isPageNumberInTitlebarShown()) {
title += ("[" + std::to_string(getCurrentPageNo() + 1) + "/" + std::to_string(doc->getPageCount()) + "] ");
}
if (undoRedo->isChanged()) {
title += "*";
}
if (settings->isFilepathInTitlebarShown()) {
title += ("[" + doc->getFilepath().parent_path().u8string() + "] - " +
doc->getFilepath().filename().u8string());
} else {
title += doc->getFilepath().filename().u8string();
}
}
this->doc->unlock();
title += " - Xournal++";
gtk_window_set_title(getGtkWindow(), title.c_str());
}
void Control::exportAsPdf() {
this->clearSelectionEndText();
auto* job = new PdfExportJob(this);
job->showFileChooser(
[ctrl = this, job]() {
ctrl->scheduler->addJob(job, JOB_PRIORITY_NONE);
job->unref();
},
[ctrl = this, job]() {
// The job blocked, so we have to unblock, because the job unblocks only after
ctrl->unblock();
job->unref();
});
}
void Control::exportAs() {
this->clearSelectionEndText();
auto* job = new CustomExportJob(this);
job->showDialogAndRun();
}
void Control::save(std::function<void(bool)> callback) { saveImpl(false, std::move(callback)); }
void Control::saveAs(std::function<void(bool)> callback) { saveImpl(true, std::move(callback)); }
void Control::saveImpl(bool saveAs, std::function<void(bool)> callback) {
// clear selection before saving
clearSelectionEndText();
this->doc->lock();
fs::path filepath = this->doc->getFilepath();
this->doc->unlock();
auto doSave = [ctrl = this, cb = std::move(callback)]() {
// clear selection before saving
ctrl->clearSelectionEndText();
auto* job = new SaveJob(ctrl, std::move(cb));
ctrl->scheduler->addJob(job, JOB_PRIORITY_URGENT);
job->unref();
};
if (saveAs || filepath.empty()) {
// No need to backup the old saved file, as there is none
this->doc->lock();
this->doc->setCreateBackupOnSave(false);
auto suggestedPath = this->doc->createSaveFolder(this->settings->getLastSavePath());
suggestedPath /= this->doc->createSaveFilename(Document::XOPP, this->settings->getDefaultSaveName());
this->doc->unlock();
xoj::SaveExportDialog::showSaveFileDialog(getGtkWindow(), settings, std::move(suggestedPath),
[doSave = std::move(doSave), ctrl = this](std::optional<fs::path> p) {
if (p && !p->empty()) {
ctrl->settings->setLastSavePath(p->parent_path());
ctrl->doc->lock();
ctrl->doc->setFilepath(std::move(p.value()));
ctrl->doc->unlock();
doSave();
}
});
} else {
doSave();
}
}
void Control::resetSavedStatus() {
this->doc->lock();
auto filepath = this->doc->getFilepath();
this->doc->unlock();
this->undoRedo->documentSaved();
RecentManager::addRecentFileFilename(filepath);
this->updateWindowTitle();
}
void Control::quit(bool allowCancel) {
auto afterClosed = [this, allowCancel](bool closed) {
if (!closed) {
if (!allowCancel) {
// Cancel is not allowed, and the user close or did not save
// This is probably called from macOS, where the Application
// now will be killed - therefore do an emergency save.
emergencySave();
}
} else {
if (audioController) {
audioController->stopRecording();
}
this->scheduler->lock();
this->scheduler->removeAllJobs();
this->scheduler->unlock();
this->scheduler->stop(); // Finish current task. Must be called to finish pending saves.
this->closeDocument(); // Must be done after all jobs has finished (Segfault on save/export)
settings->save();
g_application_quit(G_APPLICATION(gtkApp));
}
};
this->close(std::move(afterClosed), true, allowCancel);
}
void Control::close(std::function<void(bool)> callback, const bool allowDestroy, const bool allowCancel) {
clearSelectionEndText();
metadata->documentChanged();
resetGeometryTool();
bool safeToClose = !undoRedo->isChanged();
if (!safeToClose) {
fs::path path = doc->getFilepath();
const bool fileRemoved = !path.empty() && !fs::exists(path);
const auto message = fileRemoved ? _("Document file was removed.") : _("This document is not saved yet.");
const bool saveAs = fileRemoved || path.empty();
const auto saveLabel = saveAs ? _("Save As...") : _("Save");
enum { SAVE = 1, DISCARD, CANCEL };
std::vector<XojMsgBox::Button> buttons = {{saveLabel, SAVE}, {_("Discard"), DISCARD}};
if (allowCancel) {
buttons.emplace_back(_("Cancel"), CANCEL);
}
XojMsgBox::askQuestion(getGtkWindow(), message, std::string(), std::move(buttons),
[ctrl = this, saveAs, allowDestroy, callback = std::move(callback)](int response) {
auto execAfter = [allowDestroy, ctrl, cb = std::move(callback)](bool saved) {
if (saved && allowDestroy) {
ctrl->closeDocument();
}
cb(saved);
};
if (response == SAVE) {
ctrl->saveImpl(saveAs, std::move(execAfter));
return;
}
bool safeToClose = response == DISCARD;
execAfter(safeToClose);
});
} else {
if (allowDestroy) {
this->closeDocument();
}
callback(true);
}
}
void Control::closeDocument() {
this->undoRedo->clearContents();
this->doc->lock();
// FIXME: there could potentially be a data race if a job requires the old document but runs after it is closed
this->doc->clearDocument(true);
this->doc->unlock();
this->undoRedoChanged();
}
void Control::initButtonTool() {
std::vector<Button> buttons{Button::BUTTON_ERASER, Button::BUTTON_STYLUS_ONE, Button::BUTTON_STYLUS_TWO,
Button::BUTTON_MOUSE_MIDDLE, Button::BUTTON_MOUSE_RIGHT, Button::BUTTON_TOUCH};
ButtonConfig* cfg;
for (auto b: buttons) {
cfg = settings->getButtonConfig(b);
cfg->initButton(this->toolHandler, b);
}
}
void Control::showAbout() {
auto popup = xoj::popup::PopupWindowWrapper<xoj::popup::AboutDialog>(this->gladeSearchPath);
popup.show(GTK_WINDOW(this->win->getWindow()));
}
auto Control::loadViewMode(ViewModeId mode) -> bool {
if (!settings->loadViewMode(mode)) {
return false;
}
this->win->setMenubarVisible(settings->isMenubarVisible());
this->win->setToolbarVisible(settings->isToolbarVisible());
this->win->setSidebarVisible(settings->isSidebarVisible());
setFullscreen(settings->isFullscreen());
return false;
}
void Control::clipboardCutCopyEnabled(bool enabled) {
this->actionDB->enableAction(Action::CUT, enabled);
this->actionDB->enableAction(Action::COPY, enabled);
}
void Control::clipboardPasteEnabled(bool enabled) { this->actionDB->enableAction(Action::PASTE, enabled); }
void Control::clipboardPasteText(string text) {
auto t = std::make_unique<Text>();
t->setText(text);
t->setFont(settings->getFont());
t->setColor(toolHandler->getTool(TOOL_TEXT).getColor());
clipboardPaste(std::move(t));
}
void Control::clipboardPasteImage(GdkPixbuf* img) {
auto image = std::make_unique<Image>();
image->setImage(img);
auto width =
static_cast<double>(gdk_pixbuf_get_width(img)) / settings->getDisplayDpi() * Util::DPI_NORMALIZATION_FACTOR;
auto height = static_cast<double>(gdk_pixbuf_get_height(img)) / settings->getDisplayDpi() *
Util::DPI_NORMALIZATION_FACTOR;
auto pageNr = getCurrentPageNo();
if (pageNr == npos) {
return;
}
this->doc->lock();
PageRef page = this->doc->getPage(pageNr);
auto pageWidth = page->getWidth();
auto pageHeight = page->getHeight();
this->doc->unlock();
// Size: 3/4 of the page size
pageWidth = pageWidth * 3.0 / 4.0;
pageHeight = pageHeight * 3.0 / 4.0;
auto scaledWidth = width;
auto scaledHeight = height;
if (width > pageWidth) {
scaledWidth = pageWidth;
scaledHeight = (scaledWidth * height) / width;
}
if (scaledHeight > pageHeight) {
scaledHeight = pageHeight;
scaledWidth = (scaledHeight * width) / height;
}
image->setWidth(scaledWidth);
image->setHeight(scaledHeight);
clipboardPaste(std::move(image));
}
void Control::clipboardPaste(ElementPtr e) {
double x = 0;
double y = 0;
auto pageNr = getCurrentPageNo();
if (pageNr == npos) {
return;
}
XojPageView* view = win->getXournal()->getViewFor(pageNr);
if (view == nullptr) {
return;
}
this->doc->lock();
PageRef page = this->doc->getPage(pageNr);
Layer* layer = page->getSelectedLayer();
this->doc->unlock();
win->getXournal()->getPasteTarget(x, y);
double width = e->getElementWidth();
double height = e->getElementHeight();
x = std::max(0.0, x - width / 2);
y = std::max(0.0, y - height / 2);
e->setX(x);
e->setY(y);
undoRedo->addUndoAction(std::make_unique<InsertUndoAction>(page, layer, e.get()));
auto sel = SelectionFactory::createFromFloatingElement(this, page, layer, view, std::move(e));
win->getXournal()->setSelection(sel.release());
}
void Control::registerPluginToolButtons(ToolMenuHandler* toolMenuHandler) {
pluginController->registerToolButtons(toolMenuHandler);
}
void Control::clipboardPasteXournal(ObjectInputStream& in) {
auto pNr = getCurrentPageNo();
if (pNr == npos && win != nullptr) {
return;
}
this->doc->lock();
PageRef page = this->doc->getPage(pNr);
Layer* layer = page->getSelectedLayer();
XojPageView* view = win->getXournal()->getViewFor(pNr);
if (!view || !page) {
this->doc->unlock();
return;
}
auto selection = std::make_unique<EditSelection>(this, page, page->getSelectedLayer(), view);
this->doc->unlock();
try {
ElementPtr element;
std::string version = in.readString();
if (version != PROJECT_STRING) {
g_warning("Paste from Xournal Version %s to Xournal Version %s", version.c_str(), PROJECT_STRING);
}
selection->readSerialized(in);
// document lock not needed anymore, because we don't change the document, we only change the selection
int count = in.readInt();
auto pasteAddUndoAction = std::make_unique<AddUndoAction>(page, false);
// this will undo a group of elements that are inserted
for (int i = 0; i < count; i++) {
std::string name = in.getNextObjectName();
element.reset();
if (name == "Stroke") {
element = std::make_unique<Stroke>();
} else if (name == "Image") {
element = std::make_unique<Image>();
} else if (name == "TexImage") {
element = std::make_unique<TexImage>();
} else if (name == "Text") {
element = std::make_unique<Text>();
} else {
throw InputStreamException(FS(FORMAT_STR("Get unknown object {1}") % name), __FILE__, __LINE__);
}
element->readSerialized(in);
pasteAddUndoAction->addElement(layer, element.get(), layer->indexOf(element.get()));
// Todo: unique_ptr
selection->addElement(std::move(element), std::numeric_limits<Element::Index>::max());
}
undoRedo->addUndoAction(std::move(pasteAddUndoAction));
double x = 0;
double y = 0;
// calculate x/y of paste target, see clipboardPaste(Element* e)
win->getXournal()->getPasteTarget(x, y);
x = std::max(0.0, x - selection->getWidth() / 2);
y = std::max(0.0, y - selection->getHeight() / 2);
// calculate difference between current selection position and destination
auto dx = x - selection->getXOnView();
auto dy = y - selection->getYOnView();
selection->moveSelection(dx, dy);
// update all Elements (same procedure as moving a element selection by hand and releasing the mouse button)
selection->mouseUp();
win->getXournal()->setSelection(selection.release());
} catch (const std::exception& e) {
g_warning("could not paste, Exception occurred: %s", e.what());
Stacktrace::printStacktrace();
if (selection) {
for (Element* el: selection->getElements()) {
delete el;
}
}
}
}
void Control::moveSelectionToLayer(size_t layerNo) {
PageRef currentP = getCurrentPage();
if (layerNo >= currentP->getLayerCount()) {
return;
}
auto selection = getWindow()->getXournal()->getSelection();
if (!selection) {
return;
}
auto* oldLayer = currentP->getSelectedLayer();
auto* newLayer = currentP->getLayers()->at(layerNo);
auto moveSelUndo = std::make_unique<MoveSelectionToLayerUndoAction>(currentP, getLayerController(), oldLayer,
currentP->getSelectedLayerId() - 1, layerNo);
for (auto* e: selection->getElements()) {
moveSelUndo->addElement(newLayer, e, newLayer->indexOf(e));
}
undoRedo->addUndoAction(std::move(moveSelUndo));
getLayerController()->switchToLay(layerNo + 1, /*hideShow=*/false, /*clearSelection=*/false);
}
void Control::deleteSelection() {
if (win) {
win->getXournal()->deleteSelection();
}
}
void Control::clearSelection() {
if (this->win) {
this->win->getXournal()->clearSelection();
this->win->getPdfToolbox()->userCancelSelection();
}
}
void Control::setClipboardHandlerSelection(EditSelection* selection) {
if (this->clipboardHandler) {
this->clipboardHandler->setSelection(selection);
}
}
void Control::addChangedDocumentListener(DocumentListener* dl) { this->changedDocumentListeners.push_back(dl); }
void Control::removeChangedDocumentListener(DocumentListener* dl) { this->changedDocumentListeners.remove(dl); }
void Control::setCopyCutEnabled(bool enabled) { this->clipboardHandler->setCopyCutEnabled(enabled); }
void Control::setFill(bool fill) {
EditSelection* sel = nullptr;
if (this->win) {
sel = this->win->getXournal()->getSelection();
}
if (sel) {
undoRedo->addUndoAction(UndoActionPtr(
sel->setFill(fill ? toolHandler->getPenFill() : -1, fill ? toolHandler->getHighlighterFill() : -1)));
}
toolHandler->setFillEnabled(fill);
}
void Control::setLineStyle(const string& style) {
LineStyle stl = StrokeStyle::parseStyle(style);
if (this->win && this->win->getXournal()->getSelection()) {
undoRedo->addUndoAction(this->win->getXournal()->getSelection()->setLineStyle(stl));
} else if (this->toolHandler->getActiveTool()->getToolType() != TOOL_PEN) {
this->selectTool(TOOL_PEN);
}
this->toolHandler->setLineStyle(stl);
}
void Control::setEraserType(EraserType type) {
if (type != ERASER_TYPE_NONE) {
if (this->toolHandler->getActiveTool()->getToolType() != TOOL_ERASER) {
this->selectTool(TOOL_ERASER);
}
}
this->toolHandler->setEraserType(type);
}
void Control::setToolSize(ToolSize size) {
EditSelection* sel = nullptr;
if (this->win) {
sel = this->win->getXournal()->getSelection();
}
if (sel) {
undoRedo->addUndoAction(UndoActionPtr(sel->setSize(size, toolHandler->getToolThickness(TOOL_PEN),
toolHandler->getToolThickness(TOOL_HIGHLIGHTER),
toolHandler->getToolThickness(TOOL_ERASER))));
}
this->toolHandler->setSize(size);
}
void Control::fontChanged(const XojFont& font) {
settings->setFont(font);
if (this->win) {
if (EditSelection* sel = this->win->getXournal()->getSelection(); sel) {
undoRedo->addUndoAction(UndoActionPtr(sel->setFont(font)));
}
}
if (TextEditor* editor = getTextEditor(); editor) {
editor->setFont(font);
}
}
/**
* The core handler for inserting latex
*/
void Control::runLatex() {
/*
* LatexController::run() will open a non-blocking dialog.
*/
LatexController::run(this);
}
/**
* GETTER / SETTER
*/
auto Control::getUndoRedoHandler() const -> UndoRedoHandler* { return this->undoRedo; }
auto Control::getZoomControl() const -> ZoomControl* { return this->zoom; }
auto Control::getCursor() const -> XournalppCursor* { return this->cursor; }
auto Control::getDocument() const -> Document* { return this->doc; }
auto Control::getToolHandler() const -> ToolHandler* { return this->toolHandler; }
auto Control::getScheduler() const -> XournalScheduler* { return this->scheduler; }
auto Control::getWindow() const -> MainWindow* { return this->win; }
auto Control::getGtkWindow() const -> GtkWindow* { return GTK_WINDOW(this->win->getWindow()); }
void Control::setRotationSnapping(bool enable) {
settings->setSnapRotation(enable);
this->actionDB->setActionState(Action::ROTATION_SNAPPING, enable);
}
void Control::setGridSnapping(bool enable) {
settings->setSnapGrid(enable);
this->actionDB->setActionState(Action::GRID_SNAPPING, enable);
}
auto Control::getTextEditor() -> TextEditor* {
if (this->win) {
return this->win->getXournal()->getTextEditor();
}
return nullptr;
}
auto Control::getGladeSearchPath() const -> GladeSearchpath* { return this->gladeSearchPath; }
auto Control::getSettings() const -> Settings* { return settings; }
auto Control::getScrollHandler() const -> ScrollHandler* { return this->scrollHandler; }
auto Control::getMetadataManager() const -> MetadataManager* { return this->metadata; }
auto Control::getSidebar() const -> Sidebar* { return this->sidebar; }
auto Control::getSearchBar() const -> SearchBar* { return this->searchBar; }
auto Control::getAudioController() const -> AudioController* { return this->audioController; }
auto Control::getPageTypes() const -> PageTypeHandler* { return this->pageTypes; }
auto Control::getPageBackgroundChangeController() const -> PageBackgroundChangeController* {
return this->pageBackgroundChangeController.get();
}
auto Control::getLayerController() const -> LayerController* { return this->layerController; }
auto Control::getPluginController() const -> PluginController* { return this->pluginController; }
auto Control::getPalette() const -> const Palette& { return *(this->palette); }
auto Control::loadPaletteFromSettings() -> void {
const auto palettePath = this->settings->getColorPaletteSetting();
if (palettePath.empty()) {
this->palette->load_default();
return;
}
auto newPalette = std::make_unique<Palette>(palettePath);
this->palette = std::move(newPalette);
// If file does not exist there is no need to attempt parsing it
if (!fs::exists(this->palette->getFilePath())) {
this->palette->load_default();
return;
}
try {
this->palette->load();
} catch (const std::exception& e) {
this->palette->parseErrorDialog(e);
this->palette->load_default();
}
}
| 96,375
|
C++
|
.cpp
| 2,087
| 37.543364
| 120
| 0.610089
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,436
|
ToolEnums.cpp
|
xournalpp_xournalpp/src/core/control/ToolEnums.cpp
|
#include "ToolEnums.h"
#include "model/StrokeStyle.h"
auto toolSizeToString(ToolSize size) -> std::string {
switch (size) {
case TOOL_SIZE_NONE:
return "none";
case TOOL_SIZE_VERY_FINE:
return "veryThin";
case TOOL_SIZE_FINE:
return "thin";
case TOOL_SIZE_MEDIUM:
return "medium";
case TOOL_SIZE_THICK:
return "thick";
case TOOL_SIZE_VERY_THICK:
return "veryThick";
default:
return "";
}
}
auto toolSizeFromString(const std::string& size) -> ToolSize {
if (size == "veryThin") {
return TOOL_SIZE_VERY_FINE;
}
if (size == "thin") {
return TOOL_SIZE_FINE;
}
if (size == "medium") {
return TOOL_SIZE_MEDIUM;
}
if (size == "thick") {
return TOOL_SIZE_THICK;
}
if (size == "veryThick") {
return TOOL_SIZE_VERY_THICK;
}
return TOOL_SIZE_NONE;
}
auto drawingTypeToString(DrawingType type) -> std::string {
switch (type) {
case DRAWING_TYPE_DONT_CHANGE:
return "dontChange";
case DRAWING_TYPE_DEFAULT:
return "default";
case DRAWING_TYPE_LINE:
return "line";
case DRAWING_TYPE_RECTANGLE:
return "rectangle";
case DRAWING_TYPE_ELLIPSE:
return "ellipse";
case DRAWING_TYPE_ARROW:
return "arrow";
case DRAWING_TYPE_DOUBLE_ARROW:
return "doubleArrow";
case DRAWING_TYPE_SHAPE_RECOGNIZER:
return "strokeRecognizer";
case DRAWING_TYPE_COORDINATE_SYSTEM:
return "drawCoordinateSystem";
case DRAWING_TYPE_SPLINE:
return "spline";
default:
return "";
}
}
auto drawingTypeFromString(const std::string& type) -> DrawingType {
if (type == "dontChange") {
return DRAWING_TYPE_DONT_CHANGE;
}
if (type == "line") {
return DRAWING_TYPE_LINE;
}
if (type == "rectangle") {
return DRAWING_TYPE_RECTANGLE;
}
if (type == "ellipse") {
return DRAWING_TYPE_ELLIPSE;
}
if (type == "arrow") {
return DRAWING_TYPE_ARROW;
}
if (type == "doubleArrow") {
return DRAWING_TYPE_DOUBLE_ARROW;
}
if (type == "strokeRecognizer") {
return DRAWING_TYPE_SHAPE_RECOGNIZER;
}
if (type == "drawCoordinateSystem") {
return DRAWING_TYPE_COORDINATE_SYSTEM;
}
if (type == "spline") {
return DRAWING_TYPE_SPLINE;
}
return DRAWING_TYPE_DEFAULT;
}
auto isSelectToolType(ToolType type) -> bool {
return type == TOOL_SELECT_RECT || type == TOOL_SELECT_REGION || type == TOOL_SELECT_MULTILAYER_RECT ||
type == TOOL_SELECT_MULTILAYER_REGION || type == TOOL_SELECT_OBJECT;
}
auto isSelectToolTypeSingleLayer(ToolType type) -> bool {
return type == TOOL_SELECT_RECT || type == TOOL_SELECT_REGION || type == TOOL_SELECT_OBJECT;
}
auto requiresClearedSelection(ToolType type) -> bool {
return type == TOOL_PEN || type == TOOL_HIGHLIGHTER || type == TOOL_ERASER || type == TOOL_TEXT ||
type == TOOL_IMAGE || type == TOOL_SELECT_PDF_TEXT_RECT || type == TOOL_SELECT_PDF_TEXT_RECT ||
type == TOOL_VERTICAL_SPACE;
}
auto toolTypeToString(ToolType type) -> std::string {
switch (type) {
case TOOL_NONE:
return "none";
case TOOL_PEN:
return "pen";
case TOOL_ERASER:
return "eraser";
case TOOL_HIGHLIGHTER:
return "highlighter";
case TOOL_TEXT:
return "text";
case TOOL_IMAGE:
return "image";
case TOOL_SELECT_RECT:
return "selectRect";
case TOOL_SELECT_REGION:
return "selectRegion";
case TOOL_SELECT_MULTILAYER_RECT:
return "selectMultiLayerRect";
case TOOL_SELECT_MULTILAYER_REGION:
return "selectMultiLayerRegion";
case TOOL_SELECT_OBJECT:
return "selectObject";
case TOOL_PLAY_OBJECT:
return "playObject";
case TOOL_VERTICAL_SPACE:
return "verticalSpace";
case TOOL_HAND:
return "hand";
case TOOL_DRAW_RECT:
return "drawRect";
case TOOL_DRAW_ELLIPSE:
return "drawEllipse";
case TOOL_DRAW_ARROW:
return "drawArrow";
case TOOL_DRAW_DOUBLE_ARROW:
return "drawDoubleArrow";
case TOOL_DRAW_COORDINATE_SYSTEM:
return "drawCoordinateSystem";
case TOOL_DRAW_SPLINE:
return "drawSpline";
case TOOL_FLOATING_TOOLBOX:
return "showFloatingToolbox";
case TOOL_SELECT_PDF_TEXT_LINEAR:
return "selectPdfTextLinear";
case TOOL_SELECT_PDF_TEXT_RECT:
return "selectPdfTextRect";
default:
return "";
}
}
auto toolTypeFromString(const std::string& type) -> ToolType {
if (type == "pen") {
return TOOL_PEN;
}
if (type == "eraser") {
return TOOL_ERASER;
}
// recognize previous spelling of Highlighter, V1.0.19 (Dec 2020) and earlier
if (type == "highlighter" || type == "hilighter") {
return TOOL_HIGHLIGHTER;
}
if (type == "text") {
return TOOL_TEXT;
}
if (type == "image") {
return TOOL_IMAGE;
}
if (type == "selectRect") {
return TOOL_SELECT_RECT;
}
if (type == "selectRegion") {
return TOOL_SELECT_REGION;
}
if (type == "selectMultiLayerRect") {
return TOOL_SELECT_MULTILAYER_RECT;
}
if (type == "selectMultiLayerRegion") {
return TOOL_SELECT_MULTILAYER_REGION;
}
if (type == "selectObject") {
return TOOL_SELECT_OBJECT;
}
if (type == "playObject") {
return TOOL_PLAY_OBJECT;
}
if (type == "verticalSpace") {
return TOOL_VERTICAL_SPACE;
}
if (type == "hand") {
return TOOL_HAND;
}
if (type == "drawRect") {
return TOOL_DRAW_RECT;
}
// recognize previous spelling of Ellipse, V1.1.0+dev (Jan 2021) and earlier
if (type == "drawEllipse" || type == "drawCircle") {
return TOOL_DRAW_ELLIPSE;
}
if (type == "drawArrow") {
return TOOL_DRAW_ARROW;
}
if (type == "drawDoubleArrow") {
return TOOL_DRAW_DOUBLE_ARROW;
}
if (type == "drawCoordinateSystem") {
return TOOL_DRAW_COORDINATE_SYSTEM;
}
if (type == "drawSpline") {
return TOOL_DRAW_SPLINE;
}
if (type == "showFloatingToolbox") {
return TOOL_FLOATING_TOOLBOX;
}
if (type == "selectPdfTextLinear") {
return TOOL_SELECT_PDF_TEXT_LINEAR;
}
if (type == "selectPdfTextRect") {
return TOOL_SELECT_PDF_TEXT_RECT;
}
return TOOL_NONE;
}
auto opacityFeatureToString(OpacityFeature feature) -> std::string {
switch (feature) {
case OPACITY_NONE:
return "none";
case OPACITY_FILL_PEN:
return "opacityFillPen";
case OPACITY_FILL_HIGHLIGHTER:
return "opacityFillHighlighter";
case OPACITY_SELECT_PDF_TEXT_MARKER:
return "opacitySelectPdfTextMarker";
default:
return "";
}
}
auto opacityFeatureFromString(const std::string& feature) -> OpacityFeature {
if (feature == "none") {
return OPACITY_NONE;
}
if (feature == "opacityFillPen") {
return OPACITY_FILL_PEN;
}
if (feature == "opacityFillHighlighter") {
return OPACITY_FILL_HIGHLIGHTER;
}
if (feature == "opacitySelectPdfTextMarker") {
return OPACITY_SELECT_PDF_TEXT_MARKER;
}
return OPACITY_NONE;
}
auto eraserTypeToString(EraserType type) -> std::string {
switch (type) {
case ERASER_TYPE_NONE:
return "none";
case ERASER_TYPE_DEFAULT:
return "default";
case ERASER_TYPE_WHITEOUT:
return "whiteout";
case ERASER_TYPE_DELETE_STROKE:
return "deleteStroke";
default:
return "";
}
}
auto eraserTypeFromString(const std::string& type) -> EraserType {
if (type == "default") {
return ERASER_TYPE_DEFAULT;
}
if (type == "whiteout") {
return ERASER_TYPE_WHITEOUT;
}
if (type == "deleteStroke") {
return ERASER_TYPE_DELETE_STROKE;
}
return ERASER_TYPE_NONE;
}
auto strokeTypeToLineStyle(StrokeType type) -> LineStyle {
switch (type) {
case STROKE_TYPE_STANDARD:
return {};
case STROKE_TYPE_DASHED:
return StrokeStyle::parseStyle("dash");
case STROKE_TYPE_DASHDOTTED:
return StrokeStyle::parseStyle("dashdot");
case STROKE_TYPE_DOTTED:
return StrokeStyle::parseStyle("dot");
default:
return {};
}
}
auto strokeTypeToString(StrokeType type) -> std::string {
switch (type) {
case STROKE_TYPE_NONE:
return "none";
case STROKE_TYPE_STANDARD:
return "standard";
case STROKE_TYPE_DASHED:
return "dash";
case STROKE_TYPE_DASHDOTTED:
return "dashdot";
case STROKE_TYPE_DOTTED:
return "dot";
default:
return "";
}
}
auto strokeTypeFromString(const std::string& type) -> StrokeType {
if (type == "standard")
return STROKE_TYPE_STANDARD;
if (type == "dash")
return STROKE_TYPE_DASHED;
if (type == "dashdot")
return STROKE_TYPE_DASHDOTTED;
if (type == "dot")
return STROKE_TYPE_DOTTED;
return STROKE_TYPE_NONE;
}
bool xoj::tool::isPdfSelectionTool(ToolType toolType) {
return toolType == TOOL_SELECT_PDF_TEXT_LINEAR || toolType == TOOL_SELECT_PDF_TEXT_RECT;
}
| 9,891
|
C++
|
.cpp
| 328
| 22.597561
| 107
| 0.589942
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,437
|
GeometryToolController.cpp
|
xournalpp_xournalpp/src/core/control/GeometryToolController.cpp
|
#include "GeometryToolController.h"
#include <memory>
#include "control/Control.h"
#include "control/layer/LayerController.h"
#include "gui/XournalView.h"
#include "gui/XournalppCursor.h"
#include "model/Document.h"
#include "model/GeometryTool.h"
#include "model/Stroke.h"
#include "model/XojPage.h"
#include "undo/InsertUndoAction.h"
using xoj::util::Rectangle;
constexpr double MARK_SIZE = 2.;
GeometryToolController::GeometryToolController(XojPageView* view, GeometryTool* geometryTool):
view(view), geometryTool(geometryTool) {}
GeometryToolController::~GeometryToolController() = default;
void GeometryToolController::translate(double x, double y) {
geometryTool->setTranslationX(geometryTool->getTranslationX() + x);
geometryTool->setTranslationY(geometryTool->getTranslationY() + y);
geometryTool->notify();
}
void GeometryToolController::rotate(double da, double cx, double cy) {
geometryTool->setRotation(geometryTool->getRotation() + da);
const auto offsetX = geometryTool->getTranslationX() - cx;
const auto offsetY = geometryTool->getTranslationY() - cy;
const auto mx = offsetX * cos(da) - offsetY * sin(da);
const auto my = offsetX * sin(da) + offsetY * cos(da);
geometryTool->setTranslationX(cx + mx);
geometryTool->setTranslationY(cy + my);
geometryTool->notify();
}
void GeometryToolController::scale(double f, double cx, double cy) {
geometryTool->setHeight(geometryTool->getHeight() * f);
const auto offsetX = geometryTool->getTranslationX() - cx;
const auto offsetY = geometryTool->getTranslationY() - cy;
const auto mx = offsetX * f;
const auto my = offsetY * f;
geometryTool->setTranslationX(cx + mx);
geometryTool->setTranslationY(cy + my);
geometryTool->notify(true);
}
void GeometryToolController::markPoint(double x, double y) {
const auto control = view->getXournal()->getControl();
const auto h = control->getToolHandler();
auto cross = std::make_unique<Stroke>();
cross->setWidth(h->getToolThickness(TOOL_PEN)[TOOL_SIZE_FINE]);
cross->setColor(h->getTool(TOOL_PEN).getColor());
cross->addPoint(Point(x + MARK_SIZE, y + MARK_SIZE));
cross->addPoint(Point(x - MARK_SIZE, y - MARK_SIZE));
cross->addPoint(Point(x, y));
cross->addPoint(Point(x + MARK_SIZE, y - MARK_SIZE));
cross->addPoint(Point(x - MARK_SIZE, y + MARK_SIZE));
auto* ptr = cross.get();
const auto doc = control->getDocument();
const auto page = view->getPage();
doc->lock();
const auto layer = page->getSelectedLayer();
layer->addElement(std::move(cross));
doc->unlock();
const auto undo = control->getUndoRedoHandler();
undo->addUndoAction(std::make_unique<InsertUndoAction>(page, layer, ptr));
const Rectangle<double> rect{ptr->getX(), ptr->getY(), ptr->getElementWidth(), ptr->getElementHeight()};
view->rerenderRect(rect.x, rect.y, rect.width, rect.height);
}
void GeometryToolController::addStrokeToLayer() {
const auto xournal = view->getXournal();
const auto control = xournal->getControl();
const auto doc = control->getDocument();
const auto page = view->getPage();
auto ptr = stroke.get();
doc->lock();
const auto layer = page->getSelectedLayer();
layer->addElement(std::move(this->stroke));
doc->unlock();
const auto undo = control->getUndoRedoHandler();
undo->addUndoAction(std::make_unique<InsertUndoAction>(page, layer, ptr));
const Rectangle<double> rect{ptr->getX(), ptr->getY(), ptr->getElementWidth(), ptr->getElementHeight()};
view->rerenderRect(rect.x, rect.y, rect.width, rect.height);
geometryTool->setStroke(nullptr);
xournal->getCursor()->updateCursor();
}
void GeometryToolController::initializeStroke() {
const auto h = view->getXournal()->getControl()->getToolHandler();
stroke = std::make_unique<Stroke>();
geometryTool->setStroke(stroke.get());
stroke->setWidth(h->getThickness());
stroke->setColor(h->getColor());
stroke->setFill(h->getFill());
stroke->setLineStyle(h->getLineStyle());
switch (h->getToolType()) {
case TOOL_PEN:
stroke->setToolType(StrokeTool::PEN);
break;
case TOOL_HIGHLIGHTER:
stroke->setToolType(StrokeTool::HIGHLIGHTER);
break;
case TOOL_ERASER:
stroke->setToolType(StrokeTool::ERASER);
break;
default:
g_warning("Unhandled tool when initializing stroke in geometry tool controller");
break;
}
}
auto GeometryToolController::getPage() const -> const PageRef { return view->getPage(); }
auto GeometryToolController::getView() const -> XojPageView* { return view; }
| 4,721
|
C++
|
.cpp
| 106
| 39.650943
| 108
| 0.700762
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,438
|
AudioController.cpp
|
xournalpp_xournalpp/src/core/control/AudioController.cpp
|
#include "AudioController.h"
#include <array> // for array
#include <cstdio> // for snprintf
#include <ctime> // for tm, localtime, time
#include <string> // for string, allocator
#include <glib.h> // for g_get_monotonic_time
#include "audio/AudioPlayer.h" // for AudioPlayer
#include "audio/AudioRecorder.h" // for AudioRecorder
#include "audio/DeviceInfo.h" // for DeviceInfo
#include "control/Control.h" // for Control
#include "control/actions/ActionDatabase.h" // for ActionDatabase
#include "control/settings/Settings.h" // for Settings
#include "gui/MainWindow.h" // for MainWindow
#include "gui/toolbarMenubar/ToolMenuHandler.h" // for ToolMenuHandler
#include "util/XojMsgBox.h" // for XojMsgBox
#include "util/i18n.h" // for _
#include "util/safe_casts.h" // for as_signed
using std::string;
using std::vector;
AudioController::AudioController(Settings* settings, Control* control):
settings(*settings),
control(*control),
audioRecorder(std::make_unique<AudioRecorder>(*settings)),
audioPlayer(std::make_unique<AudioPlayer>(*control, *settings)) {}
AudioController::~AudioController() = default;
auto AudioController::startRecording() -> bool {
if (!this->isRecording()) {
if (getAudioFolder().empty()) {
return false;
}
this->timestamp = static_cast<size_t>(g_get_monotonic_time() / 1000);
std::array<char, 50> buffer{};
time_t secs = time(nullptr);
tm* t = localtime(&secs);
// This prints the date and time in ISO format.
snprintf(buffer.data(), buffer.size(), "%04d-%02d-%02d_%02d-%02d-%02d", t->tm_year + 1900, t->tm_mon + 1,
t->tm_mday, t->tm_hour, t->tm_min, t->tm_sec);
string data(buffer.data());
data += ".ogg";
audioFilename = data;
g_message("Start recording");
bool isRecording = this->audioRecorder->start(getAudioFolder() / data);
if (!isRecording) {
audioFilename = "";
this->timestamp = 0;
}
return isRecording;
}
return false;
}
auto AudioController::stopRecording() -> bool {
if (this->audioRecorder->isRecording()) {
audioFilename = "";
this->timestamp = 0;
g_message("Stop recording");
this->audioRecorder->stop();
}
return true;
}
auto AudioController::isRecording() -> bool { return this->audioRecorder->isRecording(); }
auto AudioController::isPlaying() -> bool { return this->audioPlayer->isPlaying(); }
auto AudioController::startPlayback(fs::path const& file, unsigned int timestamp) -> bool {
this->audioPlayer->stop();
bool status = this->audioPlayer->start(file, timestamp);
if (status) {
auto* actionDB = this->control.getActionDatabase();
actionDB->enableAction(Action::AUDIO_PAUSE_PLAYBACK, true);
actionDB->enableAction(Action::AUDIO_STOP_PLAYBACK, true);
actionDB->enableAction(Action::AUDIO_SEEK_FORWARDS, true);
actionDB->enableAction(Action::AUDIO_SEEK_BACKWARDS, true);
}
return status;
}
void AudioController::pausePlayback() {
this->control.getActionDatabase()->setActionState(Action::AUDIO_PAUSE_PLAYBACK, true);
this->audioPlayer->pause();
}
void AudioController::seekForwards() { this->audioPlayer->seek(as_signed(this->settings.getDefaultSeekTime())); }
void AudioController::seekBackwards() { this->audioPlayer->seek(-1 * as_signed(this->settings.getDefaultSeekTime())); }
void AudioController::continuePlayback() {
this->control.getActionDatabase()->setActionState(Action::AUDIO_PAUSE_PLAYBACK, false);
this->audioPlayer->play();
}
void AudioController::stopPlayback() { this->audioPlayer->stop(); }
auto AudioController::getAudioFilename() const -> fs::path const& { return this->audioFilename; }
auto AudioController::getAudioFolder() const -> fs::path {
auto const& af = this->settings.getAudioFolder();
if (!fs::is_directory(af)) {
string msg = _("Audio folder not set or invalid! Recording won't work!\nPlease set the "
"recording folder under \"Preferences > Audio recording\"");
XojMsgBox::showErrorToUser(this->control.getGtkWindow(), msg);
return fs::path{};
}
return af;
}
auto AudioController::getStartTime() const -> size_t { return this->timestamp; }
auto AudioController::getOutputDevices() const -> vector<DeviceInfo> { return this->audioPlayer->getOutputDevices(); }
auto AudioController::getInputDevices() const -> vector<DeviceInfo> { return this->audioRecorder->getInputDevices(); }
| 4,785
|
C++
|
.cpp
| 98
| 43.316327
| 119
| 0.659145
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,439
|
SearchControl.cpp
|
xournalpp_xournalpp/src/core/control/SearchControl.cpp
|
#include "SearchControl.h"
#include <memory> // for __shared_ptr_access
#include <utility> // for move
#include "model/Element.h" // for Element, ELEMENT_TEXT
#include "model/Layer.h" // for Layer
#include "model/Text.h" // for Text
#include "model/XojPage.h" // for XojPage
#include "view/overlays/SearchResultView.h" // for SEARCH_CHANGED_NOTIFICATION
SearchControl::SearchControl(const PageRef& page, XojPdfPageSPtr pdf):
page(page),
pdf(std::move(pdf)),
viewPool(std::make_shared<xoj::util::DispatchPool<xoj::view::SearchResultView>>()) {}
SearchControl::~SearchControl() = default;
auto SearchControl::search(const std::string& text, size_t index, size_t* occurrences, XojPdfRectangle* matchRect)
-> bool {
this->highlightRect = nullptr;
if (text.empty()) {
if (!this->results.empty()) {
this->results.clear();
this->currentText.clear();
this->viewPool->dispatch(xoj::view::SearchResultView::SEARCH_CHANGED_NOTIFICATION);
}
return true;
}
if (text != this->currentText) {
this->results.clear();
this->currentText = text;
if (this->pdf) {
this->results = this->pdf->findText(text);
}
for (Layer* l: *this->page->getLayers()) {
if (!l->isVisible()) {
continue;
}
for (auto&& e: l->getElements()) {
if (e->getType() == ELEMENT_TEXT) {
Text* t = dynamic_cast<Text*>(e.get());
std::vector<XojPdfRectangle> textResult = t->findText(text);
this->results.insert(this->results.end(), textResult.begin(), textResult.end());
}
}
}
}
this->viewPool->dispatch(xoj::view::SearchResultView::SEARCH_CHANGED_NOTIFICATION);
if (occurrences) {
*occurrences = this->results.size();
}
bool found;
if (index - 1 >= this->results.size()) {
if (matchRect) {
*matchRect = XojPdfRectangle(0, 0, 0, 0);
}
found = false;
} else {
if (matchRect) {
this->highlightRect = &this->results[index - 1];
*matchRect = *this->highlightRect;
}
found = true;
}
return found;
}
| 2,386
|
C++
|
.cpp
| 62
| 30.016129
| 114
| 0.55815
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,440
|
RecentManager.cpp
|
xournalpp_xournalpp/src/core/control/RecentManager.cpp
|
#include "RecentManager.h"
#include <algorithm> // for sort, max
#include <ctime> // for time_t
#include <functional> // for greater, less
#include <string> // for string, allocator, operator+
#include "util/GListView.h" // for GListView, GListView<>::GListVie...
#include "util/PathUtil.h" // for fromUri, toUri, hasPdfFileExt
#include "util/TinyVector.h" // for TinyVector
#include "util/safe_casts.h" // for as_signed
#include "Control.h"
template <template <class> class Comp>
inline auto compareGtkRecentInfo(GtkRecentInfo const& a, GtkRecentInfo const& b) -> bool {
auto deconstify = [](auto&& ref) { return const_cast<GtkRecentInfo*>(&ref); }; // NOLINT
auto a_time = gtk_recent_info_get_modified(deconstify(a)); // actually const
auto b_time = gtk_recent_info_get_modified(deconstify(b));
return Comp<time_t>{}(a_time, b_time);
}
inline auto operator<(GtkRecentInfo const& a, GtkRecentInfo const& b) -> bool {
return compareGtkRecentInfo<std::less>(a, b);
}
inline auto operator>(GtkRecentInfo const& a, GtkRecentInfo const& b) -> bool {
return compareGtkRecentInfo<std::greater>(a, b);
}
namespace {
enum AcceptedFileType { UNSUPPORTED_FILE_TYPE, XOURNAL_FILE_TYPE, PDF_FILE_TYPE };
auto getFileType(GtkRecentInfo& info) -> AcceptedFileType {
const gchar* uri = gtk_recent_info_get_uri(&info);
if (!uri) { // issue #1071
return UNSUPPORTED_FILE_TYPE;
}
auto p = Util::fromUri(uri);
if (!p) { // Skip remote files
return UNSUPPORTED_FILE_TYPE;
}
if (Util::hasXournalFileExt(*p)) {
return XOURNAL_FILE_TYPE;
}
if (Util::hasPdfFileExt(*p)) {
return PDF_FILE_TYPE;
}
return UNSUPPORTED_FILE_TYPE;
}
} // namespace
void RecentManager::clearRecentFiles() {
GtkRecentManager* recentManager = gtk_recent_manager_get_default();
GList* items = gtk_recent_manager_get_items(recentManager);
auto item_view = GListView<GtkRecentInfo>(items);
for (auto& recent: item_view) {
if (getFileType(recent) != UNSUPPORTED_FILE_TYPE) {
gtk_recent_manager_remove_item(recentManager,
gtk_recent_info_get_uri(&recent),
nullptr);
}
}
g_list_free_full(items, GDestroyNotify(gtk_recent_info_unref));
}
void RecentManager::addRecentFileFilename(const fs::path& filepath) {
GtkRecentManager* recentManager = gtk_recent_manager_get_default();
std::string group_name = GROUP;
std::array<gchar*, 2> groups = {group_name.data(), nullptr};
std::string app_name = g_get_application_name();
std::string app_exec = std::string(g_get_prgname()) + " %u";
std::string mime_type = Util::hasPdfFileExt(filepath) ? std::string(MIME_PDF) : std::string(MIME);
GtkRecentData recentData{};
recentData.display_name = nullptr;
recentData.description = nullptr;
recentData.app_name = app_name.data();
recentData.app_exec = app_exec.data();
recentData.groups = groups.data();
recentData.mime_type = mime_type.data();
recentData.is_private = false;
auto uri = Util::toUri(filepath);
if (!uri) {
return;
}
gtk_recent_manager_add_full(recentManager, (*uri).c_str(), &recentData);
}
void RecentManager::removeRecentFileFilename(const fs::path& filename) {
auto uri = Util::toUri(filename);
if (!uri) {
return;
}
GtkRecentManager* recentManager = gtk_recent_manager_get_default();
gtk_recent_manager_remove_item(recentManager, uri->c_str(), nullptr);
}
auto RecentManager::getMostRecent() -> GtkRecentInfoSPtr {
auto recent_items = gtk_recent_manager_get_items(gtk_recent_manager_get_default());
// Todo (cpp20): replace with std::ranges::max_element
if (!recent_items) {
return nullptr;
}
GtkRecentInfo* mostRecent = nullptr;
for (auto& recent: GListView<GtkRecentInfo>(recent_items)) {
auto time = gtk_recent_info_get_modified(&recent);
if (as_signed(time) < 0) {
continue;
}
if (getFileType(recent) != XOURNAL_FILE_TYPE) {
continue;
}
if (mostRecent == nullptr || *mostRecent < recent) {
mostRecent = &recent;
}
}
// Prolong lifetime past the list deletion
GtkRecentInfoSPtr res = mostRecent == nullptr ? nullptr : GtkRecentInfoSPtr(mostRecent, xoj::util::ref);
g_list_free_full(recent_items, GDestroyNotify(gtk_recent_info_unref));
return res;
}
auto RecentManager::getRecentFiles() -> RecentFiles {
GtkRecentManager* recentManager = gtk_recent_manager_get_default();
GList* items = gtk_recent_manager_get_items(recentManager);
RecentFiles res;
for (auto& recent: GListView<GtkRecentInfo>(items)) {
auto fileType = getFileType(recent);
if (fileType == PDF_FILE_TYPE && res.recentPdfFiles.size() < MAX_RECENT) {
res.recentPdfFiles.emplace_back(&recent, xoj::util::ref);
}
if (fileType == XOURNAL_FILE_TYPE && res.recentXoppFiles.size() < MAX_RECENT) {
res.recentXoppFiles.emplace_back(&recent, xoj::util::ref);
}
}
g_list_free_full(items, GDestroyNotify(gtk_recent_info_unref));
auto comp = [](const GtkRecentInfoSPtr& p1, const GtkRecentInfoSPtr& p2) { return *p1.get() > *p2.get(); };
std::sort(res.recentPdfFiles.begin(), res.recentPdfFiles.end(), comp);
std::sort(res.recentXoppFiles.begin(), res.recentXoppFiles.end(), comp);
return res;
}
| 5,589
|
C++
|
.cpp
| 128
| 37.851563
| 111
| 0.661519
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,441
|
PageBackgroundChangeController.cpp
|
xournalpp_xournalpp/src/core/control/PageBackgroundChangeController.cpp
|
#include "PageBackgroundChangeController.h"
#include <memory> // for __shared_ptr...
#include <string> // for allocator
#include <utility> // for move
#include <gdk-pixbuf/gdk-pixbuf.h> // for gdk_pixbuf_g...
#include <gio/gio.h> // for GFile
#include <glib.h> // for g_error_free
#include "control/settings/PageTemplateSettings.h" // for PageTemplate...
#include "control/settings/Settings.h" // for Settings
#include "gui/MainWindow.h" // for MainWindow
#include "gui/XournalView.h" // for XournalView
#include "gui/dialog/backgroundSelect/ImagesDialog.h" // for ImagesDialog
#include "gui/dialog/backgroundSelect/PdfPagesDialog.h" // for PdfPagesDialog
#include "gui/menus/menubar/Menubar.h" // for Menubar
#include "gui/menus/menubar/PageTypeSubmenu.h" // for PageTypeSubmenu
#include "model/BackgroundImage.h" // for BackgroundImage
#include "model/Document.h" // for Document
#include "model/PageType.h" // for PageType
#include "model/XojPage.h" // for XojPage
#include "pdf/base/XojPdfPage.h" // for XojPdfPageSPtr
#include "undo/GroupUndoAction.h" // for GroupUndoAction
#include "undo/MissingPdfUndoAction.h" // for MissingPdfUn...
#include "undo/PageBackgroundChangedUndoAction.h" // for PageBackgrou...
#include "undo/UndoAction.h" // for UndoAction
#include "undo/UndoRedoHandler.h" // for UndoRedoHandler
#include "util/Assert.h" // for xoj_assert
#include "util/PathUtil.h" // for fromGFile
#include "util/PopupWindowWrapper.h"
#include "util/Util.h" // for npos
#include "util/XojMsgBox.h" // for XojMsgBox
#include "util/i18n.h" // for FS, _, _F
#include "Control.h" // for Control
#include "filesystem.h" // for path
PageBackgroundChangeController::PageBackgroundChangeController(Control* control): control(control) {
registerListener(control);
}
void PageBackgroundChangeController::applyBackgroundToAllPages(const PageType& pt) {
control->clearSelectionEndText();
auto apply = [pt, this](CommitParameter param = std::nullopt) {
auto groupUndoAction = std::make_unique<GroupUndoAction>();
Document* doc = control->getDocument();
doc->lock();
auto nbPages = doc->getPageCount();
for (size_t p = 0; p < nbPages; p++) {
auto undoAction = commitPageTypeChange(p, pt, param);
if (undoAction) {
groupUndoAction->addAction(std::move(undoAction));
}
}
doc->unlock();
control->getUndoRedoHandler()->addUndoAction(std::move(groupUndoAction));
// Special background types may alter the page sizes as well
auto fire = pt.isSpecial() ? &Control::firePageSizeChanged : &Control::firePageChanged;
for (size_t n = 0; n < nbPages; n++) {
(control->*fire)(n);
}
control->updateBackgroundSizeButton();
control->getWindow()->getMenubar()->getPageTypeSubmenu().setSelected(std::move(pt));
};
if (pt.isImagePage()) {
askForImageBackground([apply = std::move(apply)](BackgroundImage img) { apply(std::move(img)); });
} else if (pt.isPdfPage()) {
askForPdfBackground([apply = std::move(apply)](size_t pdfPage) { apply(pdfPage); });
} else {
apply();
}
}
void PageBackgroundChangeController::applyCurrentPageBackgroundToAll() {
PageType pt = control->getCurrentPage()->getBackgroundType();
applyBackgroundToAllPages(pt);
}
void PageBackgroundChangeController::changePdfPagesBackground(const fs::path& filepath, bool attachPdf) {
Document* doc = this->control->getDocument();
const fs::path oldFilepath = doc->getPdfFilepath();
const bool oldAttachPdf = doc->isAttachPdf();
if (!doc->readPdf(filepath, false, attachPdf)) {
std::string msg = FS(_F("Error reading PDF: {1}") % doc->getLastErrorMsg());
XojMsgBox::showErrorToUser(this->control->getGtkWindow(), msg);
return;
}
this->control->getWindow()->getXournal()->recreatePdfCache();
this->control->fireDocumentChanged(DOCUMENT_CHANGE_COMPLETE);
auto undoAction = std::make_unique<MissingPdfUndoAction>(oldFilepath, oldAttachPdf);
this->control->getUndoRedoHandler()->addUndoAction(std::move(undoAction));
}
void PageBackgroundChangeController::changeCurrentPageBackground(const PageType& pt) {
control->clearSelectionEndText();
const size_t pageNr = control->getCurrentPageNo();
xoj_assert(pageNr != npos);
auto apply = [this, pt, pageNr](CommitParameter param = std::nullopt) {
Document* doc = control->getDocument();
doc->lock();
auto undoAction = commitPageTypeChange(pageNr, pt, std::move(param));
doc->unlock();
if (undoAction) {
control->getUndoRedoHandler()->addUndoAction(std::move(undoAction));
}
// Special background types may alter the page sizes as well
if (pt.isSpecial()) {
control->firePageSizeChanged(pageNr);
} else {
control->firePageChanged(pageNr);
}
control->updateBackgroundSizeButton();
control->getWindow()->getMenubar()->getPageTypeSubmenu().setSelected(std::move(pt));
};
if (pt.isImagePage()) {
askForImageBackground([apply = std::move(apply)](BackgroundImage img) { apply(std::move(img)); });
} else if (pt.isPdfPage()) {
askForPdfBackground([apply = std::move(apply)](size_t pdfPage) { apply(pdfPage); });
} else {
apply();
}
}
void PageBackgroundChangeController::setPageTypeForNewPages(const std::optional<PageType>& pt) {
this->pageTypeForNewPages = pt;
}
static void setPageImageBackground(const PageRef& page, BackgroundImage img) {
page->setBackgroundImage(std::move(img));
page->setBackgroundType(PageType(PageTypeFormat::Image));
// Apply correct page size
GdkPixbuf* pixbuf = page->getBackgroundImage().getPixbuf();
if (pixbuf) {
page->setSize(gdk_pixbuf_get_width(pixbuf), gdk_pixbuf_get_height(pixbuf));
} else {
g_warning("PageBackgroundChangeController::setPageImageBackground(): Page with image background but nullptr "
"pixbuf");
}
}
static void setPagePdfBackground(const PageRef& page, size_t pdfPageNr, Document* doc) {
if (pdfPageNr < doc->getPdfPageCount()) {
// no need to set a type, if we set the page number the type is also set
page->setBackgroundPdfPageNr(pdfPageNr);
XojPdfPageSPtr p = doc->getPdfPage(pdfPageNr);
page->setSize(p->getWidth(), p->getHeight());
} else {
g_warning("PageBackgroundChangeController::setPagePdfBackground() with past-the-end PDF page number");
}
}
auto PageBackgroundChangeController::commitPageTypeChange(size_t pageNum, const PageType& pageType,
CommitParameter param) -> std::unique_ptr<UndoAction> {
xoj_assert(pageType.isImagePage() == std::holds_alternative<BackgroundImage>(param));
xoj_assert(pageType.isPdfPage() == std::holds_alternative<size_t>(param));
PageRef page = control->getDocument()->getPage(pageNum);
if (!page) {
g_warning("PageBackgroundChangeController::commitPageTypeChange() could not fetch page %zu", pageNum);
return {};
}
Document* doc = control->getDocument();
// Get values for Undo / Redo
const double origW = page->getWidth();
const double origH = page->getHeight();
BackgroundImage origBackgroundImage = page->getBackgroundImage();
const size_t origPdfPage = page->getPdfPageNr();
PageType origType = page->getBackgroundType();
// Apply the new background
if (std::holds_alternative<BackgroundImage>(param)) { // Image background
xoj_assert(!std::get<BackgroundImage>(param).isEmpty());
setPageImageBackground(page, std::move(std::get<BackgroundImage>(param)));
} else if (std::holds_alternative<size_t>(param)) { // PDF background
setPagePdfBackground(page, std::get<size_t>(param), doc);
} else {
page->setBackgroundType(pageType);
}
return std::make_unique<PageBackgroundChangedUndoAction>(page, origType, origPdfPage, origBackgroundImage, origW,
origH);
}
void PageBackgroundChangeController::askForImageBackground(std::function<void(BackgroundImage)> callback) {
Document* doc = control->getDocument();
auto dlg = xoj::popup::PopupWindowWrapper<ImagesDialog>(control->getGladeSearchPath(), doc, control->getSettings(),
std::move(callback));
dlg.show(control->getGtkWindow());
}
void PageBackgroundChangeController::askForPdfBackground(std::function<void(size_t)> callback) {
Document* doc = control->getDocument();
if (doc->getPdfPageCount() == 0) {
std::string msg = _("You don't have any PDF pages to select from. Cancel operation.\n"
"Please select another background type: Menu \"Journal\" → \"Configure Page Template\".");
XojMsgBox::showErrorToUser(control->getGtkWindow(), msg);
return;
}
auto dlg = xoj::popup::PopupWindowWrapper<PdfPagesDialog>(control->getGladeSearchPath(), doc,
control->getSettings(), std::move(callback));
dlg.show(control->getGtkWindow());
}
/**
* Copy the background from source to target
*/
void PageBackgroundChangeController::copyBackgroundFromOtherPage(PageRef target, PageRef source) {
// Copy page size
target->setSize(source->getWidth(), source->getHeight());
// Copy page background type
PageType bg = source->getBackgroundType();
target->setBackgroundType(bg);
if (bg.isPdfPage()) {
// If PDF: Copy PDF Page
target->setBackgroundPdfPageNr(source->getPdfPageNr());
} else if (bg.isImagePage()) {
// If Image: Copy the Image
target->setBackgroundImage(source->getBackgroundImage());
} else {
// Copy the background color
target->setBackgroundColor(source->getBackgroundColor());
}
}
void PageBackgroundChangeController::insertNewPage(size_t position, bool shouldScrollToPage) {
control->clearSelectionEndText();
Document* doc = control->getDocument();
if (position > doc->getPageCount()) {
position = doc->getPageCount();
}
PageTemplateSettings model;
model.parse(control->getSettings()->getPageTemplate());
auto page = std::make_shared<XojPage>(model.getPageWidth(), model.getPageHeight());
auto afterConfigured = [position, shouldScrollToPage, ctrl = this->control](PageRef page) {
ctrl->insertPage(page, position, shouldScrollToPage);
};
if (!pageTypeForNewPages) {
PageRef current = control->getCurrentPage();
xoj_assert(current);
copyBackgroundFromOtherPage(page, current);
afterConfigured(std::move(page));
} else if (pageTypeForNewPages->isImagePage()) {
askForImageBackground([after = std::move(afterConfigured), page = std::move(page)](BackgroundImage img) {
setPageImageBackground(page, std::move(img));
after(std::move(page));
});
} else if (pageTypeForNewPages->isPdfPage()) {
askForPdfBackground([after = std::move(afterConfigured), page = std::move(page), doc](size_t pdfPageNr) {
setPagePdfBackground(page, pdfPageNr, doc);
after(std::move(page));
});
} else {
// Create a new page from template
page->setBackgroundType(pageTypeForNewPages.value());
// Set background Color
page->setBackgroundColor(model.getBackgroundColor());
if (model.isCopyLastPageSize()) {
PageRef current = control->getCurrentPage();
xoj_assert(current);
page->setSize(current->getWidth(), current->getHeight());
}
afterConfigured(std::move(page));
}
}
void PageBackgroundChangeController::documentChanged(DocumentChangeType type) {}
void PageBackgroundChangeController::pageSizeChanged(size_t page) {}
void PageBackgroundChangeController::pageChanged(size_t page) {}
void PageBackgroundChangeController::pageInserted(size_t page) {}
void PageBackgroundChangeController::pageDeleted(size_t page) {}
void PageBackgroundChangeController::pageSelected(size_t page) {
auto const& current = control->getCurrentPage();
if (!current) {
return;
}
control->getWindow()->getMenubar()->getPageTypeSubmenu().setSelected(current->getBackgroundType());
}
| 13,005
|
C++
|
.cpp
| 257
| 43.774319
| 120
| 0.659601
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,442
|
CrashHandler.cpp
|
xournalpp_xournalpp/src/core/control/CrashHandler.cpp
|
#include "CrashHandler.h"
#include <sstream>
#include <string> // for string
#include <glib.h> // for g_warning, g_error
#include "control/xojfile/SaveHandler.h" // for SaveHandler
#include "util/PathUtil.h" // for getConfigFile
#include "util/i18n.h" // for FC, _F, _
#include "filesystem.h" // for path
static Document* document = nullptr;
static std::stringstream logBuffer;
void setEmergencyDocument(Document* doc) { document = doc; }
[[maybe_unused]] static std::stringstream* getCrashHandlerLogBuffer() { return &logBuffer; }
#ifdef _WIN32
#include "CrashHandlerWindows.h"
#else
#include "CrashHandlerUnix.h"
#endif
void emergencySave() {
if (document == nullptr) {
return;
}
g_warning("%s", _("Trying to emergency save the current open document..."));
auto const& filepath = Util::getConfigFile("emergencysave.xopp");
SaveHandler handler;
handler.prepareSave(document);
handler.saveTo(filepath);
if (!handler.getErrorMessage().empty()) {
g_error("%s", FC(_F("Error: {1}") % handler.getErrorMessage()));
} else {
g_warning("%s", FC(_F("Successfully saved document to \"{1}\"") % filepath.string()));
}
}
| 1,224
|
C++
|
.cpp
| 32
| 34.875
| 94
| 0.672881
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,443
|
ClipboardHandler.cpp
|
xournalpp_xournalpp/src/core/control/ClipboardHandler.cpp
|
#include "ClipboardHandler.h"
#include <set> // for multiset, operator!=
#include <utility> // for move
#include <vector> // for vector
#include <cairo-svg.h> // for cairo_svg_surface_c...
#include <cairo.h> // for cairo_create, cairo...
#include <gdk/gdkpixbuf.h> // for gdk_pixbuf_get_from_surface
#include <glib-object.h> // for g_object_unref, g_s...
#include "control/tools/EditSelection.h" // for EditSelection
#include "model/Element.h" // for Element, ELEMENT_TEXT
#include "model/Text.h" // for Text
#include "util/Util.h" // for DPI_NORMALIZATION_F...
#include "util/gtk4_helper.h" // for gtk_widget_get_clipboard
#include "util/safe_casts.h" // for as_unsigned
#include "util/serializing/BinObjectEncoding.h" // for BinObjectEncoding
#include "util/serializing/ObjectInputStream.h" // for ObjectInputStream
#include "util/serializing/ObjectOutputStream.h" // for ObjectOutputStream
#include "view/ElementContainerView.h" // for ElementContainerView
#include "view/View.h" // for Context
#include "config.h" // for PROJECT_STRING
using std::string;
ClipboardListener::~ClipboardListener() = default;
ClipboardHandler::ClipboardHandler(ClipboardListener* listener, GtkWidget* widget) {
this->listener = listener;
this->clipboard = gtk_widget_get_clipboard(widget);
this->handlerId = g_signal_connect(this->clipboard, "owner-change", G_CALLBACK(&ownerChangedCallback), this);
this->listener->clipboardCutCopyEnabled(false);
gtk_clipboard_request_contents(clipboard, gdk_atom_intern_static_string("TARGETS"),
reinterpret_cast<GtkClipboardReceivedFunc>(receivedClipboardContents), this);
}
ClipboardHandler::~ClipboardHandler() { g_signal_handler_disconnect(this->clipboard, this->handlerId); }
static GdkAtom atomXournal = gdk_atom_intern_static_string("application/xournal");
auto ClipboardHandler::paste() -> bool {
/* Request targets again, since the owner-change signal is not emitted on MacOS and under X11 with no XFIXES
* extension. See https://docs.gtk.org/gdk3/struct.EventOwnerChange.html and
* https://gitlab.gnome.org/GNOME/gtk/-/issues/1757 */
gtk_clipboard_request_contents(clipboard, gdk_atom_intern_static_string("TARGETS"),
reinterpret_cast<GtkClipboardReceivedFunc>(receivedClipboardContents), this);
if (this->containsXournal) {
gtk_clipboard_request_contents(this->clipboard, atomXournal,
reinterpret_cast<GtkClipboardReceivedFunc>(pasteClipboardContents), this);
return true;
}
if (this->containsText) {
gtk_clipboard_request_text(this->clipboard, reinterpret_cast<GtkClipboardTextReceivedFunc>(pasteClipboardText),
this);
return true;
}
if (this->containsImage) {
gtk_clipboard_request_image(this->clipboard,
reinterpret_cast<GtkClipboardImageReceivedFunc>(pasteClipboardImage), this);
return true;
}
return false;
}
auto ClipboardHandler::cut() -> bool {
bool result = this->copy();
this->listener->deleteSelection();
return result;
}
auto ElementCompareFunc(Element* a, Element* b) -> bool {
if (a->getY() == b->getY()) {
return (a->getX() - b->getX()) < 0;
}
return (a->getY() - b->getY()) < 0;
}
static GdkAtom atomSvg1 = gdk_atom_intern_static_string("image/svg");
static GdkAtom atomSvg2 = gdk_atom_intern_static_string("image/svg+xml");
// The contents of the clipboard
class ClipboardContents {
public:
ClipboardContents(string text, GdkPixbuf* image, string svg, GString* str) {
this->text = std::move(text);
this->image = image;
this->svg = std::move(svg);
this->str = str;
}
~ClipboardContents() {
g_object_unref(this->image);
g_string_free(this->str, true);
}
static void getFunction(GtkClipboard* clipboard, GtkSelectionData* selection, guint info,
ClipboardContents* contents) {
GdkAtom target = gtk_selection_data_get_target(selection);
if (target == gdk_atom_intern_static_string("UTF8_STRING")) {
gtk_selection_data_set_text(selection, contents->text.c_str(), -1);
} else if (target == gdk_atom_intern_static_string("image/png") ||
target == gdk_atom_intern_static_string("image/jpeg") ||
target == gdk_atom_intern_static_string("image/gif")) {
gtk_selection_data_set_pixbuf(selection, contents->image);
} else if (atomSvg1 == target || atomSvg2 == target) {
gtk_selection_data_set(selection, target, 8, reinterpret_cast<guchar const*>(contents->svg.c_str()),
static_cast<gint>(contents->svg.length()));
} else if (atomXournal == target) {
gtk_selection_data_set(selection, target, 8, reinterpret_cast<guchar*>(contents->str->str),
static_cast<gint>(contents->str->len));
}
}
static void clearFunction(GtkClipboard* clipboard, ClipboardContents* contents) { delete contents; }
private:
string text;
GdkPixbuf* image;
string svg;
GString* str;
};
static auto svgWriteFunction(GString* string, const unsigned char* data, unsigned int length) -> cairo_status_t {
g_string_append_len(string, reinterpret_cast<const gchar*>(data), length);
return CAIRO_STATUS_SUCCESS;
}
auto ClipboardHandler::copy() -> bool {
if (!this->selection) {
return false;
}
/////////////////////////////////////////////////////////////////
// prepare xournal contents
/////////////////////////////////////////////////////////////////
ObjectOutputStream out(new BinObjectEncoding());
out.writeString(PROJECT_STRING);
this->selection->serialize(out);
/////////////////////////////////////////////////////////////////
// prepare text contents
/////////////////////////////////////////////////////////////////
std::multiset<Text*, decltype(&ElementCompareFunc)> textElements(ElementCompareFunc);
for (Element* e: this->selection->getElements()) {
if (e->getType() == ELEMENT_TEXT) {
textElements.insert(dynamic_cast<Text*>(e));
}
}
string text{};
for (Text* t: textElements) {
if (!text.empty()) {
text += "\n";
}
text += t->getText();
}
/////////////////////////////////////////////////////////////////
// prepare image contents: PNG
/////////////////////////////////////////////////////////////////
double dpiFactor = 1.0 / Util::DPI_NORMALIZATION_FACTOR * 300.0;
int width = static_cast<int>(selection->getWidth() * dpiFactor);
int height = static_cast<int>(selection->getHeight() * dpiFactor);
cairo_surface_t* surfacePng = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, width, height);
cairo_t* crPng = cairo_create(surfacePng);
cairo_scale(crPng, dpiFactor, dpiFactor);
cairo_translate(crPng, -selection->getOriginalXOnView(), -selection->getOriginalYOnView());
xoj::view::ElementContainerView view(this->selection);
view.draw(xoj::view::Context::createDefault(crPng));
cairo_destroy(crPng);
GdkPixbuf* image = gdk_pixbuf_get_from_surface(surfacePng, 0, 0, width, height);
cairo_surface_destroy(surfacePng);
/////////////////////////////////////////////////////////////////
// prepare image contents: SVG
/////////////////////////////////////////////////////////////////
GString* svgString = g_string_sized_new(1048576); // 1MB
cairo_surface_t* surfaceSVG =
cairo_svg_surface_create_for_stream(reinterpret_cast<cairo_write_func_t>(svgWriteFunction), svgString,
selection->getWidth(), selection->getHeight());
cairo_t* crSVG = cairo_create(surfaceSVG);
cairo_translate(crSVG, -selection->getOriginalXOnView(), -selection->getOriginalYOnView());
view.draw(xoj::view::Context::createDefault(crSVG));
cairo_surface_destroy(surfaceSVG);
cairo_destroy(crSVG);
/////////////////////////////////////////////////////////////////
// copy to clipboard
/////////////////////////////////////////////////////////////////
GtkTargetList* list = gtk_target_list_new(nullptr, 0);
GtkTargetEntry* targets = nullptr;
int n_targets = 0;
// if we have text elements...
if (!text.empty()) {
gtk_target_list_add_text_targets(list, 0);
}
// we always copy an image to clipboard
gtk_target_list_add_image_targets(list, 0, true);
gtk_target_list_add(list, atomSvg1, 0, 0);
gtk_target_list_add(list, atomSvg2, 0, 0);
gtk_target_list_add(list, atomXournal, 0, 0);
targets = gtk_target_table_new_from_list(list, &n_targets);
auto* contents = new ClipboardContents(text, image, svgString->str, out.getStr());
gtk_clipboard_set_with_data(this->clipboard, targets, static_cast<guint>(n_targets),
reinterpret_cast<GtkClipboardGetFunc>(ClipboardContents::getFunction),
reinterpret_cast<GtkClipboardClearFunc>(ClipboardContents::clearFunction), contents);
gtk_clipboard_set_can_store(this->clipboard, nullptr, 0);
gtk_target_table_free(targets, n_targets);
gtk_target_list_unref(list);
g_string_free(svgString, true);
return true;
}
void ClipboardHandler::setSelection(EditSelection* selection) {
this->selection = selection;
this->listener->clipboardCutCopyEnabled(selection != nullptr);
}
void ClipboardHandler::setCopyCutEnabled(bool enabled) {
if (enabled) {
listener->clipboardCutCopyEnabled(true);
} else if (!selection) {
listener->clipboardCutCopyEnabled(false);
}
}
void ClipboardHandler::ownerChangedCallback(GtkClipboard* clip, GdkEvent* event, ClipboardHandler* handler) {
if (gdk_event_get_event_type(event) == GDK_OWNER_CHANGE) {
handler->clipboardUpdated(event->owner_change.selection);
}
}
void ClipboardHandler::clipboardUpdated(GdkAtom atom) {
gtk_clipboard_request_contents(clipboard, gdk_atom_intern_static_string("TARGETS"),
reinterpret_cast<GtkClipboardReceivedFunc>(receivedClipboardContents), this);
}
void ClipboardHandler::pasteClipboardImage(GtkClipboard* clipboard, GdkPixbuf* pixbuf, ClipboardHandler* handler) {
if (pixbuf) {
handler->listener->clipboardPasteImage(pixbuf);
} else {
g_warning("Trying to paste image, but pixbuf is null");
}
}
void ClipboardHandler::pasteClipboardContents(GtkClipboard* clipboard, GtkSelectionData* selectionData,
ClipboardHandler* handler) {
ObjectInputStream in;
if (in.read(reinterpret_cast<const char*>(gtk_selection_data_get_data(selectionData)),
as_unsigned(gtk_selection_data_get_length(selectionData)))) {
handler->listener->clipboardPasteXournal(in);
}
}
void ClipboardHandler::pasteClipboardText(GtkClipboard* clipboard, const gchar* text, ClipboardHandler* handler) {
if (text) {
handler->listener->clipboardPasteText(text);
}
}
auto gtk_selection_data_targets_include_xournal(GtkSelectionData* selection_data) -> gboolean {
GdkAtom* targets = nullptr;
gint n_targets = 0;
gboolean result = false;
if (gtk_selection_data_get_targets(selection_data, &targets, &n_targets)) {
for (int i = 0; i < n_targets; i++) {
if (targets[i] == atomXournal) {
result = true;
break;
}
}
g_free(targets);
}
return result;
}
void ClipboardHandler::receivedClipboardContents(GtkClipboard* clipboard, GtkSelectionData* selectionData,
ClipboardHandler* handler) {
handler->containsText = gtk_selection_data_targets_include_text(selectionData);
handler->containsXournal = gtk_selection_data_targets_include_xournal(selectionData);
handler->containsImage = gtk_selection_data_targets_include_image(selectionData, false);
handler->listener->clipboardPasteEnabled(handler->containsText || handler->containsXournal ||
handler->containsImage);
}
| 12,596
|
C++
|
.cpp
| 251
| 42.7251
| 119
| 0.627312
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,444
|
SetsquareController.cpp
|
xournalpp_xournalpp/src/core/control/SetsquareController.cpp
|
#include "SetsquareController.h"
#include "control/Control.h"
#include "control/layer/LayerController.h"
#include "gui/XournalView.h"
#include "model/GeometryTool.h"
#include "model/Setsquare.h"
#include "model/Stroke.h"
#include "model/XojPage.h"
using xoj::util::Rectangle;
SetsquareController::SetsquareController(XojPageView* view, Setsquare* setsquare):
GeometryToolController(view, setsquare) {}
SetsquareController::~SetsquareController() = default;
auto SetsquareController::getType() const -> GeometryToolType { return GeometryToolType::SETSQUARE; }
auto SetsquareController::posRelToSide(Leg leg, double x, double y) const -> xoj::util::Point<double> {
cairo_matrix_t matrix = geometryTool->getMatrix();
cairo_matrix_invert(&matrix);
cairo_matrix_transform_point(&matrix, &x, &y);
switch (leg) {
case HYPOTENUSE:
return xoj::util::Point<double>(x, -y);
case LEFT_LEG:
return xoj::util::Point<double>((y + x) / std::sqrt(2.),
(y - x - geometryTool->getHeight()) / std::sqrt(2.));
case RIGHT_LEG:
return xoj::util::Point<double>((y - x) / std::sqrt(2.),
(y + x - geometryTool->getHeight()) / std::sqrt(2.));
default:
g_error("Invalid enum value: %d", leg);
}
}
auto SetsquareController::isInsideGeometryTool(double x, double y, double border) const -> bool {
return posRelToSide(HYPOTENUSE, x, y).y < border && posRelToSide(LEFT_LEG, x, y).y < border &&
posRelToSide(RIGHT_LEG, x, y).y < border;
}
auto SetsquareController::getPointForPos(double xCoord) const -> xoj::util::Point<double> {
double x = xCoord;
double y = 0.0;
cairo_matrix_t matrix = geometryTool->getMatrix();
cairo_matrix_transform_point(&matrix, &x, &y);
return xoj::util::Point<double>(x, y);
}
void SetsquareController::createEdgeStroke(double x) {
if (!std::isnan(x)) {
hypotenuseMax = x;
hypotenuseMin = x;
const auto p = this->getPointForPos(x);
initializeStroke();
stroke->addPoint(Point(p.x, p.y));
stroke->addPoint(Point(p.x, p.y)); // doubled point
geometryTool->notify();
} else {
g_warning("No valid stroke from setsquare!");
}
}
void SetsquareController::createRadialStroke(double x, double y) {
const auto p = posRelToSide(HYPOTENUSE, x, y);
this->strokeAngle = std::atan2(p.y, p.x);
initializeStroke();
updateRadialStroke(x, y);
}
void SetsquareController::updateEdgeStroke(double x) {
hypotenuseMax = std::max(this->hypotenuseMax, x);
hypotenuseMin = std::min(this->hypotenuseMin, x);
stroke->deletePointsFrom(0);
const auto p1 = getPointForPos(hypotenuseMin);
const auto p2 = getPointForPos(hypotenuseMax);
stroke->addPoint(Point(p1.x, p1.y));
stroke->addPoint(Point(p2.x, p2.y));
geometryTool->notify();
}
void SetsquareController::updateRadialStroke(double x, double y) {
stroke->deletePointsFrom(0);
const auto c = getPointForPos(0);
stroke->addPoint(Point(c.x, c.y));
const auto p = posRelToSide(HYPOTENUSE, x, y);
const auto rad = std::hypot(p.x, p.y);
if (rad >= Setsquare::radiusFromHeight(geometryTool->getHeight()) || p.y > 0) {
this->strokeAngle = std::atan2(p.y, p.x);
stroke->addPoint(Point(x, y));
} else {
cairo_matrix_t matrix = geometryTool->getMatrix();
auto qx = rad * std::cos(this->strokeAngle);
auto qy = -rad * std::sin(this->strokeAngle);
cairo_matrix_transform_point(&matrix, &qx, &qy);
stroke->addPoint(Point(qx, qy));
}
geometryTool->notify();
}
void SetsquareController::finalizeEdgeStroke() {
hypotenuseMax = std::numeric_limits<double>::lowest();
hypotenuseMin = std::numeric_limits<double>::max();
addStrokeToLayer();
}
void SetsquareController::finalizeRadialStroke() {
strokeAngle = NAN;
addStrokeToLayer();
}
auto SetsquareController::existsEdgeStroke() -> bool { return hypotenuseMax != std::numeric_limits<double>::lowest(); }
auto SetsquareController::existsRadialStroke() -> bool { return !std::isnan(strokeAngle); }
| 4,235
|
C++
|
.cpp
| 99
| 36.848485
| 119
| 0.664642
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,445
|
Tool.cpp
|
xournalpp_xournalpp/src/core/control/Tool.cpp
|
#include "Tool.h"
#include <optional>
#include <utility>
Tool::Tool(std::string name, ToolType type, Color color, unsigned int capabilities,
std::optional<std::array<double, toolSizes>> thickness):
name{std::move(name)}, type{type}, thickness{std::move(thickness)}, capabilities{capabilities} {
setColor(color);
}
Tool::Tool(const Tool& t): name{t.name}, type{t.type}, thickness{t.thickness}, capabilities{t.capabilities} {
setColor(t.getColor());
}
Tool::~Tool() {}
auto Tool::getName() const -> std::string { return this->name; }
auto Tool::getToolType() const -> ToolType { return this->type; }
void Tool::setCapability(unsigned int capability, bool enabled) {
if (enabled) {
this->capabilities |= capability;
} else {
this->capabilities &= ~capability;
}
}
auto Tool::hasCapability(ToolCapabilities cap) const -> bool { return (this->capabilities & cap) != 0; }
auto Tool::getThickness(ToolSize size) const -> double { return this->thickness.value()[size - TOOL_SIZE_VERY_FINE]; }
auto Tool::isDrawingTool() const -> bool {
return this->type == TOOL_PEN || this->type == TOOL_HIGHLIGHTER || this->type == TOOL_ERASER;
}
| 1,193
|
C++
|
.cpp
| 26
| 42.230769
| 118
| 0.692308
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,446
|
ExportHelper.cpp
|
xournalpp_xournalpp/src/core/control/ExportHelper.cpp
|
#include "ExportHelper.h"
#include <algorithm> // for max
#include <memory> // for unique_ptr, allocator
#include <string> // for string
#include <gio/gio.h> // for g_file_new_for_commandlin...
#include <glib.h> // for g_message, g_error
#include "control/jobs/ImageExport.h" // for ImageExport, EXPORT_GRAPH...
#include "control/jobs/ProgressListener.h" // for DummyProgressListener
#include "model/Document.h" // for Document
#include "pdf/base/XojPdfExport.h" // for XojPdfExport
#include "pdf/base/XojPdfExportFactory.h" // for XojPdfExportFactory
#include "util/ElementRange.h" // for parse, PageRangeVector
#include "util/i18n.h" // for _
#include "util/raii/GObjectSPtr.h" // for GObjectSPtr
#include "filesystem.h" // for operator==, path, u8path
namespace ExportHelper {
/**
* @brief Export the input file as a bunch of image files (one per page)
* @param input Path to the input file
* @param output Path to the output file(s)
* @param range Page range to be parsed. If range=nullptr, exports the whole file
* @param pngDpi Set dpi for Png files. Non positive values are ignored
* @param pngWidth Set the width for Png files. Non positive values are ignored
* @param pngHeight Set the height for Png files. Non positive values are ignored
* @param exportBackground If EXPORT_BACKGROUND_NONE, the exported image file has transparent background
*
* The priority is: pngDpi overwrites pngWidth overwrites pngHeight
*
* @return 0 on success, -3 on export failure
*/
auto exportImg(Document* doc, const char* output, const char* range, const char* layerRange, int pngDpi, int pngWidth,
int pngHeight, ExportBackgroundType exportBackground) -> int {
fs::path const path(output);
ExportGraphicsFormat format = EXPORT_GRAPHICS_PNG;
if (path.extension() == ".svg") {
format = EXPORT_GRAPHICS_SVG;
}
PageRangeVector exportRange;
if (range) {
exportRange = ElementRange::parse(range, doc->getPageCount());
} else {
exportRange.emplace_back(0, doc->getPageCount() - 1);
}
DummyProgressListener progress;
ImageExport imgExport(doc, path, format, exportBackground, exportRange);
if (format == EXPORT_GRAPHICS_PNG) {
if (pngDpi > 0) {
imgExport.setQualityParameter(EXPORT_QUALITY_DPI, pngDpi);
} else if (pngWidth > 0) {
imgExport.setQualityParameter(EXPORT_QUALITY_WIDTH, pngWidth);
} else if (pngHeight > 0) {
imgExport.setQualityParameter(EXPORT_QUALITY_HEIGHT, pngHeight);
}
}
imgExport.setLayerRange(layerRange);
imgExport.exportGraphics(&progress);
std::string errorMsg = imgExport.getLastErrorMsg();
if (!errorMsg.empty()) {
g_message("Error exporting image: %s\n", errorMsg.c_str());
}
g_message("%s", _("Image file successfully created"));
return 0; // no error
}
/**
* @brief Export the input file as pdf
* @param input Path to the input file
* @param output Path to the output file
* @param range Page range to be parsed. If range=nullptr, exports the whole file
* @param exportBackground If EXPORT_BACKGROUND_NONE, the exported pdf file has white background
* @param progressiveMode If true, then for each xournalpp page, instead of rendering one PDF page, the page layers are
* rendered one by one to produce as many pages as there are layers.
*
* @return 0 on success, -3 on export failure
*/
auto exportPdf(Document* doc, const char* output, const char* range, const char* layerRange,
ExportBackgroundType exportBackground, bool progressiveMode) -> int {
xoj::util::GObjectSPtr<GFile> file(g_file_new_for_commandline_arg(output), xoj::util::adopt);
std::unique_ptr<XojPdfExport> pdfe = XojPdfExportFactory::createExport(doc, nullptr);
pdfe->setExportBackground(exportBackground);
auto path = fs::u8path(g_file_peek_path(file.get()));
bool exportSuccess = 0; // Return of the export job
pdfe->setLayerRange(layerRange);
if (range) {
// Parse the range
PageRangeVector exportRange = ElementRange::parse(range, doc->getPageCount());
// Do the export
exportSuccess = pdfe->createPdf(path, exportRange, progressiveMode);
} else {
exportSuccess = pdfe->createPdf(path, progressiveMode);
}
if (!exportSuccess) {
g_error("%s", pdfe->getLastError().c_str());
}
g_message("%s", _("PDF file successfully created"));
return 0; // no error
}
} // namespace ExportHelper
| 4,629
|
C++
|
.cpp
| 97
| 43.041237
| 119
| 0.694494
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,447
|
ToolHandler.cpp
|
xournalpp_xournalpp/src/core/control/ToolHandler.cpp
|
#include "ToolHandler.h"
#include <algorithm> // for clamp
#include <cstdint> // for uint32_t
#include <cstdio> // for size_t
#include <optional> // for nullopt, optional
#include <string> // for operator==, string, basic_string
#include <utility> // for move
#include <glib.h> // for g_warning, g_error
#include "control/Tool.h" // for Tool, Tool::toolSizes
#include "control/actions/ActionDatabase.h"
#include "control/settings/Settings.h" // for SElement, Settings
#include "model/StrokeStyle.h" // for StrokeStyle
#include "util/Color.h"
#include "util/Stacktrace.h" // for Stac...
#include "util/safe_casts.h" // for as_unsigned
class LineStyle;
ToolListener::~ToolListener() = default;
ToolHandler::ToolHandler(ToolListener* stateChangeListener, ActionDatabase* actionDB, Settings* settings):
stateChangeListener(stateChangeListener), actionDB(actionDB), settings(settings) {
initTools();
}
class ToolSelectPDFText: public Tool {
public:
ToolSelectPDFText(std::string name, ToolType type, Color color):
Tool(name, type, color, TOOL_CAP_COLOR | TOOL_CAP_RULER, std::nullopt) {}
~ToolSelectPDFText() override{};
void setColor(Color color) override {
if (color.alpha == 0) {
color.alpha = DEFAULT_SELECT_PDF_TEXT_MARKER_OPACITY;
}
Tool::setColor(color);
}
private:
static const int DEFAULT_SELECT_PDF_TEXT_MARKER_OPACITY = 60;
};
void ToolHandler::initTools() {
std::array<double, Tool::toolSizes> thickness;
// pen thicknesses = 0.15, 0.3, 0.5, 0.8, 2 mm
thickness[TOOL_SIZE_VERY_FINE] = 0.42;
thickness[TOOL_SIZE_FINE] = 0.85;
thickness[TOOL_SIZE_MEDIUM] = 1.41;
thickness[TOOL_SIZE_THICK] = 2.26;
thickness[TOOL_SIZE_VERY_THICK] = 5.67;
tools[TOOL_PEN - TOOL_PEN] = std::make_unique<Tool>(
"pen", TOOL_PEN, Colors::xopp_royalblue,
TOOL_CAP_COLOR | TOOL_CAP_SIZE | TOOL_CAP_RULER | TOOL_CAP_RECTANGLE | TOOL_CAP_ELLIPSE | TOOL_CAP_ARROW |
TOOL_CAP_DOUBLE_ARROW | TOOL_CAP_SPLINE | TOOL_CAP_RECOGNIZER | TOOL_CAP_FILL | TOOL_CAP_DASH_LINE |
TOOL_CAP_LINE_STYLE,
thickness);
thickness[TOOL_SIZE_VERY_FINE] = 1;
thickness[TOOL_SIZE_FINE] = 2.83;
thickness[TOOL_SIZE_MEDIUM] = 8.50;
thickness[TOOL_SIZE_THICK] = 12;
thickness[TOOL_SIZE_VERY_THICK] = 18;
tools[TOOL_ERASER - TOOL_PEN] =
std::make_unique<Tool>("eraser", TOOL_ERASER, Colors::black, TOOL_CAP_SIZE, thickness);
// highlighter thicknesses = 1, 3, 7 mm
thickness[TOOL_SIZE_VERY_FINE] = 1;
thickness[TOOL_SIZE_FINE] = 2.83;
thickness[TOOL_SIZE_MEDIUM] = 8.50;
thickness[TOOL_SIZE_THICK] = 19.84;
thickness[TOOL_SIZE_VERY_THICK] = 30;
tools[TOOL_HIGHLIGHTER - TOOL_PEN] = std::make_unique<Tool>(
"highlighter", TOOL_HIGHLIGHTER, Colors::yellow,
TOOL_CAP_COLOR | TOOL_CAP_SIZE | TOOL_CAP_RULER | TOOL_CAP_RECTANGLE | TOOL_CAP_ELLIPSE | TOOL_CAP_ARROW |
TOOL_CAP_DOUBLE_ARROW | TOOL_CAP_SPLINE | TOOL_CAP_RECOGNIZER | TOOL_CAP_FILL,
thickness);
tools[TOOL_TEXT - TOOL_PEN] =
std::make_unique<Tool>("text", TOOL_TEXT, Colors::black, TOOL_CAP_COLOR, std::nullopt);
tools[TOOL_IMAGE - TOOL_PEN] =
std::make_unique<Tool>("image", TOOL_IMAGE, Colors::black, TOOL_CAP_NONE, std::nullopt);
tools[TOOL_SELECT_RECT - TOOL_PEN] =
std::make_unique<Tool>("selectRect", TOOL_SELECT_RECT, Colors::black, TOOL_CAP_NONE, std::nullopt);
tools[TOOL_SELECT_REGION - TOOL_PEN] =
std::make_unique<Tool>("selectRegion", TOOL_SELECT_REGION, Colors::black, TOOL_CAP_NONE, std::nullopt);
tools[TOOL_SELECT_MULTILAYER_RECT - TOOL_PEN] =
std::make_unique<Tool>("selectMultiLayerRect", TOOL_SELECT_MULTILAYER_RECT, Colors::black, TOOL_CAP_NONE, std::nullopt);
tools[TOOL_SELECT_MULTILAYER_REGION - TOOL_PEN] =
std::make_unique<Tool>("selectMultiLayerRegion", TOOL_SELECT_MULTILAYER_REGION, Colors::black, TOOL_CAP_NONE, std::nullopt);
tools[TOOL_SELECT_OBJECT - TOOL_PEN] =
std::make_unique<Tool>("selectObject", TOOL_SELECT_OBJECT, Colors::black, TOOL_CAP_NONE, std::nullopt);
tools[TOOL_VERTICAL_SPACE - TOOL_PEN] =
std::make_unique<Tool>("verticalSpace", TOOL_VERTICAL_SPACE, Colors::black, TOOL_CAP_NONE, std::nullopt);
tools[TOOL_HAND - TOOL_PEN] =
std::make_unique<Tool>("hand", TOOL_HAND, Colors::black, TOOL_CAP_NONE, std::nullopt);
tools[TOOL_PLAY_OBJECT - TOOL_PEN] =
std::make_unique<Tool>("playObject", TOOL_PLAY_OBJECT, Colors::black, TOOL_CAP_NONE, std::nullopt);
tools[TOOL_DRAW_RECT - TOOL_PEN] =
std::make_unique<Tool>("drawRect", TOOL_DRAW_RECT, Colors::black, TOOL_CAP_NONE, std::nullopt);
tools[TOOL_DRAW_ELLIPSE - TOOL_PEN] =
std::make_unique<Tool>("drawEllipse", TOOL_DRAW_ELLIPSE, Colors::black, TOOL_CAP_NONE, std::nullopt);
tools[TOOL_DRAW_ARROW - TOOL_PEN] =
std::make_unique<Tool>("drawArrow", TOOL_DRAW_ARROW, Colors::black, TOOL_CAP_NONE, std::nullopt);
tools[TOOL_DRAW_DOUBLE_ARROW - TOOL_PEN] = std::make_unique<Tool>("drawDoubleArrow", TOOL_DRAW_DOUBLE_ARROW,
Colors::black, TOOL_CAP_NONE, std::nullopt);
tools[TOOL_DRAW_COORDINATE_SYSTEM - TOOL_PEN] = std::make_unique<Tool>(
"drawCoordinateSystem", TOOL_DRAW_COORDINATE_SYSTEM, Colors::black, TOOL_CAP_NONE, std::nullopt);
tools[TOOL_DRAW_SPLINE - TOOL_PEN] =
std::make_unique<Tool>("drawSpline", TOOL_DRAW_SPLINE, Colors::black, TOOL_CAP_NONE, std::nullopt);
tools[TOOL_FLOATING_TOOLBOX - TOOL_PEN] = std::make_unique<Tool>("showFloatingToolbox", TOOL_FLOATING_TOOLBOX,
Colors::black, TOOL_CAP_NONE, std::nullopt);
tools[TOOL_SELECT_PDF_TEXT_LINEAR - TOOL_PEN] =
std::make_unique<ToolSelectPDFText>("selectPdfTextLinear", TOOL_SELECT_PDF_TEXT_LINEAR, Colors::black);
tools[TOOL_SELECT_PDF_TEXT_RECT - TOOL_PEN] =
std::make_unique<ToolSelectPDFText>("selectPdfTextRect", TOOL_SELECT_PDF_TEXT_RECT, Colors::black);
this->eraserButtonTool = std::make_unique<Tool>(*tools[TOOL_HIGHLIGHTER - TOOL_PEN]);
this->stylusButton1Tool = std::make_unique<Tool>(*tools[TOOL_HIGHLIGHTER - TOOL_PEN]);
this->stylusButton2Tool = std::make_unique<Tool>(*tools[TOOL_HIGHLIGHTER - TOOL_PEN]);
this->mouseMiddleButtonTool = std::make_unique<Tool>(*tools[TOOL_HIGHLIGHTER - TOOL_PEN]);
this->mouseRightButtonTool = std::make_unique<Tool>(*tools[TOOL_HIGHLIGHTER - TOOL_PEN]);
this->touchDrawingButtonTool = std::make_unique<Tool>(*tools[TOOL_HIGHLIGHTER - TOOL_PEN]);
this->toolbarSelectedTool = &getTool(TOOL_PEN);
this->activeTool = &getTool(TOOL_PEN);
}
ToolHandler::~ToolHandler() {
// Do not delete settings!
this->settings = nullptr;
}
void ToolHandler::setEraserType(EraserType eraserType) {
Tool& tool = this->getTool(TOOL_ERASER);
tool.setEraserType(eraserType);
eraserTypeChanged();
}
void ToolHandler::setButtonEraserType(EraserType eraserType, Button button) {
Tool* tool = getButtonTool(button);
tool->setEraserType(eraserType);
}
void ToolHandler::eraserTypeChanged() {
if (this->actionDB == nullptr) {
return;
}
this->actionDB->setActionState(Action::TOOL_ERASER_TYPE, this->getEraserType());
}
auto ToolHandler::getEraserType() const -> EraserType {
// if active tool is eraser get its type
if (this->activeTool->type == TOOL_ERASER)
return this->activeTool->getEraserType();
else // otherwise get EraserType of Toolbar Eraser
return this->getTool(TOOL_ERASER).getEraserType();
}
void ToolHandler::selectTool(ToolType type) {
if (type < 1 || type > TOOL_COUNT) {
g_warning("unknown tool selected: %i\n", type);
return;
}
this->toolbarSelectedTool = &getTool(type);
// set activeTool is necessary for fireToolChanged()
// if called after this method
// to result in the correct Button shown as active
this->activeTool = this->toolbarSelectedTool;
}
void ToolHandler::fireToolChanged() const {
for (auto&& listener: this->toolChangeListeners) { listener(this->activeTool->type); }
stateChangeListener->toolChanged();
}
void ToolHandler::addToolChangedListener(ToolChangedCallback listener) {
toolChangeListeners.emplace_back(std::move(listener));
}
auto ToolHandler::getTool(ToolType type) const -> Tool& { return *(this->tools[type - TOOL_PEN]); }
auto ToolHandler::getActiveTool() const -> Tool* {return this->activeTool; }
auto ToolHandler::getToolType() const -> ToolType {
Tool* tool = this->activeTool;
return tool->type;
}
auto ToolHandler::hasCapability(ToolCapabilities cap, SelectedTool selectedTool) const -> bool {
Tool* tool = getSelectedTool(selectedTool);
return (tool->capabilities & cap) != 0;
}
auto ToolHandler::isDrawingTool() const -> bool {
Tool* tool = this->activeTool;
return tool->isDrawingTool();
}
auto ToolHandler::getSize(SelectedTool selectedTool) const -> ToolSize {
Tool* tool = getSelectedTool(selectedTool);
return tool->getSize();
}
auto ToolHandler::getPenSize() const -> ToolSize { return tools[TOOL_PEN - TOOL_PEN]->getSize(); }
auto ToolHandler::getEraserSize() const -> ToolSize { return tools[TOOL_ERASER - TOOL_PEN]->getSize(); }
auto ToolHandler::getHighlighterSize() const -> ToolSize { return tools[TOOL_HIGHLIGHTER - TOOL_PEN]->getSize(); }
void ToolHandler::setPenSize(ToolSize size) {
this->tools[TOOL_PEN - TOOL_PEN]->setSize(size);
if (this->activeTool->type == TOOL_PEN) {
this->stateChangeListener->toolSizeChanged();
}
}
void ToolHandler::setEraserSize(ToolSize size) {
this->tools[TOOL_ERASER - TOOL_PEN]->setSize(size);
if (this->activeTool->type == TOOL_ERASER) {
this->stateChangeListener->toolSizeChanged();
}
}
void ToolHandler::setHighlighterSize(ToolSize size) {
this->tools[TOOL_HIGHLIGHTER - TOOL_PEN]->setSize(size);
if (this->activeTool->type == TOOL_HIGHLIGHTER) {
this->stateChangeListener->toolSizeChanged();
}
}
void ToolHandler::setPenFillEnabled(bool fill) {
this->tools[TOOL_PEN - TOOL_PEN]->setFill(fill);
if (this->activeTool->type == TOOL_PEN) {
this->stateChangeListener->toolFillChanged();
}
}
auto ToolHandler::getPenFillEnabled() const -> bool { return this->tools[TOOL_PEN - TOOL_PEN]->getFill(); }
void ToolHandler::setPenFill(int alpha) { this->tools[TOOL_PEN - TOOL_PEN]->setFillAlpha(alpha); }
auto ToolHandler::getPenFill() const -> int { return this->tools[TOOL_PEN - TOOL_PEN]->getFillAlpha(); }
void ToolHandler::setHighlighterFillEnabled(bool fill) {
this->tools[TOOL_HIGHLIGHTER - TOOL_PEN]->setFill(fill);
if (this->activeTool->type == TOOL_HIGHLIGHTER) {
this->stateChangeListener->toolFillChanged();
}
}
auto ToolHandler::getHighlighterFillEnabled() const -> bool {
return this->tools[TOOL_HIGHLIGHTER - TOOL_PEN]->getFill();
}
void ToolHandler::setHighlighterFill(int alpha) { this->tools[TOOL_HIGHLIGHTER - TOOL_PEN]->setFillAlpha(alpha); }
auto ToolHandler::getHighlighterFill() const -> int { return this->tools[TOOL_HIGHLIGHTER - TOOL_PEN]->getFillAlpha(); }
static void inline setColorAlpha(Tool& tool, int alpha) {
if (tool.hasCapability(TOOL_CAP_COLOR)) {
Color color = tool.getColor();
color.alpha = static_cast<uint8_t>(alpha);
tool.setColor(color);
} else {
g_warning("setColorAlpha : tool='%s' has no color capability!", tool.getName().c_str());
Stacktrace::printStacktrace();
}
}
void ToolHandler::setSelectPDFTextMarkerOpacity(int alpha) {
// Use same marker opacity for 'select linear pdf text' or 'select pdf text in rectangle'
setColorAlpha(this->getTool(TOOL_SELECT_PDF_TEXT_LINEAR), alpha);
setColorAlpha(this->getTool(TOOL_SELECT_PDF_TEXT_RECT), alpha);
}
auto ToolHandler::getSelectPDFTextMarkerOpacity() const -> int {
// Use same marker opacity for 'select linear pdf text' or 'select pdf text in rectangle'
return this->getTool(TOOL_SELECT_PDF_TEXT_LINEAR).getColor().alpha;
}
auto ToolHandler::getThickness() const -> double {
Tool* tool = this->activeTool;
if (tool->thickness) {
return tool->thickness.value()[tool->getSize()];
}
g_warning("Request size of \"%s\"", tool->getName().c_str());
return 0;
}
void ToolHandler::setSize(ToolSize size) {
ToolSize clippedSize = std::clamp(size, TOOL_SIZE_VERY_FINE, TOOL_SIZE_VERY_THICK);
if (clippedSize != size)
g_warning("ToolHandler::setSize: Invalid size! %i", size);
Tool* tool = this->toolbarSelectedTool;
tool->setSize(clippedSize);
this->stateChangeListener->toolSizeChanged();
}
void ToolHandler::setButtonSize(ToolSize size, Button button) {
ToolSize clippedSize = std::clamp(size, TOOL_SIZE_VERY_FINE, TOOL_SIZE_VERY_THICK);
if (clippedSize != size)
g_warning("ToolHandler::setSize: Invalid size! %i", size);
Tool* tool = getButtonTool(button);
tool->setSize(clippedSize);
}
void ToolHandler::setLineStyle(const LineStyle& style) {
Tool* tool = this->toolbarSelectedTool;
tool->setLineStyle(style);
this->stateChangeListener->toolLineStyleChanged();
}
void ToolHandler::setColor(Color color, bool userSelection) {
if (this->activeTool != this->toolbarSelectedTool && !this->hasCapability(TOOL_CAP_COLOR, SelectedTool::active)) {
this->toolbarSelectedTool->setColor(color);
}
Tool* tool = this->activeTool;
int currentAlpha = tool->getColor().alpha;
tool->setColor(color);
this->stateChangeListener->toolColorChanged();
if (userSelection) {
// ensure that tool color alpha is re-applied on new selected color;
setColorAlpha(*tool, currentAlpha);
this->stateChangeListener->changeColorOfSelection();
}
}
void ToolHandler::setButtonColor(Color color, Button button) {
Tool* tool = this->getButtonTool(button);
tool->setColor(color);
}
auto ToolHandler::getColor() const -> Color { return this->activeTool->getColor(); }
auto ToolHandler::getColorMaskAlpha() const -> Color {
Color c = this->activeTool->getColor();
c.alpha = 0xff;
return c;
}
void ToolHandler::setFillEnabled(bool fill) {
Tool* tool = this->toolbarSelectedTool;
tool->setFill(fill);
this->stateChangeListener->toolFillChanged();
}
auto ToolHandler::getFill() const -> int {
Tool* tool = this->activeTool;
if (!tool->getFill()) {
return -1;
}
return tool->getFillAlpha();
}
auto ToolHandler::getLineStyle() const -> const LineStyle& {
Tool* tool = this->activeTool;
return tool->getLineStyle();
}
auto ToolHandler::getDrawingType(SelectedTool selectedTool) const -> DrawingType {
Tool* tool = getSelectedTool(selectedTool);
return tool->getDrawingType();
}
void ToolHandler::setDrawingType(DrawingType drawingType) {
Tool* tool = this->toolbarSelectedTool;
tool->setDrawingType(drawingType);
}
void ToolHandler::setButtonDrawingType(DrawingType drawingType, Button button) {
Tool* tool = getButtonTool(button);
tool->setDrawingType(drawingType);
}
void ToolHandler::setButtonStrokeType(StrokeType strokeType, Button button) {
this->setButtonStrokeType(strokeTypeToLineStyle(strokeType), button);
}
void ToolHandler::setButtonStrokeType(const LineStyle& lineStyle, Button button) {
Tool* tool = getButtonTool(button);
tool->setLineStyle(lineStyle);
}
auto ToolHandler::getTools() const -> std::array<std::unique_ptr<Tool>, TOOL_COUNT> const& { return tools; }
void ToolHandler::saveSettings() const {
SElement& s = settings->getCustomElement("tools");
s.clear();
s.setString("current", this->activeTool->getName());
for (auto&& tool: tools) {
SElement& st = s.child(tool->getName());
if (tool->hasCapability(TOOL_CAP_COLOR)) {
st.setIntHex("color", int(uint32_t(tool->getColor())));
}
st.setString("drawingType", drawingTypeToString(tool->getDrawingType()));
if (tool->hasCapability(TOOL_CAP_SIZE)) {
std::string value;
switch (tool->getSize()) {
case TOOL_SIZE_VERY_FINE:
value = "VERY_FINE";
break;
case TOOL_SIZE_FINE:
value = "THIN";
break;
case TOOL_SIZE_MEDIUM:
value = "MEDIUM";
break;
case TOOL_SIZE_THICK:
value = "BIG";
break;
case TOOL_SIZE_VERY_THICK:
value = "VERY_BIG";
break;
default:
value = "";
}
st.setString("size", value);
}
if (tool->hasCapability(TOOL_CAP_FILL)) {
st.setInt("fill", tool->getFill());
st.setInt("fillAlpha", tool->getFillAlpha());
}
if (tool->type == TOOL_PEN) {
st.setString("style", StrokeStyle::formatStyle(tool->getLineStyle()));
}
if (tool->type == TOOL_ERASER) {
if (this->getEraserType() == ERASER_TYPE_DELETE_STROKE) {
st.setString("type", "deleteStroke");
} else if (this->getEraserType() == ERASER_TYPE_WHITEOUT) {
st.setString("type", "whiteout");
} else // ERASER_TYPE_DEFAULT
{
st.setString("type", "default");
}
}
}
settings->customSettingsChanged();
}
void ToolHandler::loadSettings() {
SElement& s = settings->getCustomElement("tools");
std::string selectedTool;
if (s.getString("current", selectedTool)) {
for (auto&& tool: tools) {
SElement& st = s.child(tool->getName());
if (selectedTool == tool->getName()) {
this->activeTool = tool.get();
}
int iColor{};
if (tool->hasCapability(TOOL_CAP_COLOR) && st.getInt("color", iColor)) {
tool->setColor(Color(as_unsigned(iColor)));
}
std::string drawingType;
if (st.getString("drawingType", drawingType)) {
tool->setDrawingType(drawingTypeFromString(drawingType));
}
int fill = -1;
if (st.getInt("fill", fill)) {
tool->setFill(fill);
}
int fillAlpha = -1;
if (st.getInt("fillAlpha", fillAlpha)) {
tool->setFillAlpha(fillAlpha);
}
std::string style;
if (st.getString("style", style)) {
tool->setLineStyle(StrokeStyle::parseStyle(style));
}
std::string value;
if (tool->hasCapability(TOOL_CAP_SIZE) && st.getString("size", value)) {
if (value == "VERY_FINE") {
tool->setSize(TOOL_SIZE_VERY_FINE);
} else if (value == "THIN") {
tool->setSize(TOOL_SIZE_FINE);
} else if (value == "MEDIUM") {
tool->setSize(TOOL_SIZE_MEDIUM);
} else if (value == "BIG") {
tool->setSize(TOOL_SIZE_THICK);
} else if (value == "VERY_BIG") {
tool->setSize(TOOL_SIZE_VERY_THICK);
} else {
g_warning("Settings::Unknown tool size: %s\n", value.c_str());
}
}
if (tool->type == TOOL_ERASER) {
std::string type;
if (st.getString("type", type)) {
if (type == "deleteStroke") {
setEraserType(ERASER_TYPE_DELETE_STROKE);
} else if (type == "whiteout") {
setEraserType(ERASER_TYPE_WHITEOUT);
} else {
setEraserType(ERASER_TYPE_DEFAULT);
}
eraserTypeChanged();
}
}
}
}
}
bool ToolHandler::pointActiveToolToButtonTool(Button button) {
Tool* tool = getButtonTool(button);
if (this->activeTool == tool)
return false;
this->activeTool = tool;
return true;
}
bool ToolHandler::pointActiveToolToToolbarTool() {
if (this->activeTool == this->toolbarSelectedTool)
return false;
this->activeTool = this->toolbarSelectedTool;
return true;
}
auto ToolHandler::getToolThickness(ToolType type) const -> const double* {
return this->tools[type - TOOL_PEN]->thickness.value().data();
}
/**
* Change the selection tools capabilities, depending on the selected elements
*/
void ToolHandler::setSelectionEditTools(bool setColor, bool setSize, bool setFill, bool setLineStyle) {
// For all selection tools, apply the features
for (size_t i = TOOL_SELECT_RECT - TOOL_PEN; i <= TOOL_SELECT_OBJECT - TOOL_PEN; i++) {
Tool* t = tools[i].get();
t->setCapability(TOOL_CAP_COLOR, setColor);
t->setCapability(TOOL_CAP_SIZE, setSize);
t->setCapability(TOOL_CAP_FILL, setFill);
t->setCapability(TOOL_CAP_LINE_STYLE, setLineStyle);
t->setSize(TOOL_SIZE_NONE);
t->setColor(Colors::white);
t->setFill(false);
}
if (this->activeTool->type == TOOL_SELECT_RECT || this->activeTool->type == TOOL_SELECT_REGION ||
this->activeTool->type == TOOL_SELECT_MULTILAYER_RECT || this->activeTool->type == TOOL_SELECT_MULTILAYER_REGION ||
this->activeTool->type == TOOL_SELECT_OBJECT || this->activeTool->type == TOOL_PLAY_OBJECT) {
this->stateChangeListener->toolColorChanged();
this->stateChangeListener->toolSizeChanged();
this->stateChangeListener->toolFillChanged();
this->stateChangeListener->toolLineStyleChanged();
this->fireToolChanged();
}
}
auto ToolHandler::isSinglePageTool() const -> bool {
ToolType toolType = this->getToolType();
DrawingType drawingType = this->getDrawingType();
return ((toolType == TOOL_PEN || toolType == TOOL_HIGHLIGHTER) &&
(drawingType == DRAWING_TYPE_ARROW || drawingType == DRAWING_TYPE_DOUBLE_ARROW ||
drawingType == DRAWING_TYPE_ELLIPSE || drawingType == DRAWING_TYPE_COORDINATE_SYSTEM ||
drawingType == DRAWING_TYPE_LINE || drawingType == DRAWING_TYPE_RECTANGLE ||
drawingType == DRAWING_TYPE_SPLINE)) ||
toolType == TOOL_SELECT_RECT || toolType == TOOL_SELECT_REGION || toolType == TOOL_SELECT_MULTILAYER_RECT ||
toolType == TOOL_SELECT_MULTILAYER_REGION || toolType == TOOL_SELECT_OBJECT ||
toolType == TOOL_DRAW_RECT || toolType == TOOL_DRAW_ELLIPSE || toolType == TOOL_DRAW_COORDINATE_SYSTEM ||
toolType == TOOL_DRAW_ARROW || toolType == TOOL_DRAW_DOUBLE_ARROW || toolType == TOOL_FLOATING_TOOLBOX ||
toolType == TOOL_DRAW_SPLINE || toolType == TOOL_SELECT_PDF_TEXT_LINEAR ||
toolType == TOOL_SELECT_PDF_TEXT_RECT;
}
auto ToolHandler::acceptsOutOfPageEvents() const -> bool {
ToolType toolType = this->getToolType();
DrawingType drawingType = this->getDrawingType();
return ((toolType == TOOL_PEN || toolType == TOOL_HIGHLIGHTER) && (drawingType == DRAWING_TYPE_SPLINE)) ||
(toolType == TOOL_DRAW_SPLINE);
}
auto ToolHandler::supportsTapFilter() const -> bool {
ToolType toolType = this->getToolType();
return toolType == TOOL_PEN || toolType == TOOL_HIGHLIGHTER || toolType == TOOL_HAND ||
toolType == TOOL_DRAW_RECT || toolType == TOOL_DRAW_ELLIPSE || toolType == TOOL_DRAW_COORDINATE_SYSTEM ||
toolType == TOOL_DRAW_ARROW || toolType == TOOL_DRAW_DOUBLE_ARROW || toolType == TOOL_DRAW_SPLINE;
}
auto ToolHandler::getSelectedTool(SelectedTool selectedTool) const -> Tool* {
switch (selectedTool) {
case SelectedTool::active:
return this->activeTool;
case SelectedTool::toolbar:
return this->toolbarSelectedTool;
default:
g_error("This button does not exist.");
}
}
auto ToolHandler::getButtonTool(Button button) const -> Tool* {
switch (button) {
case Button::BUTTON_ERASER:
return this->eraserButtonTool.get();
case Button::BUTTON_STYLUS_ONE:
return this->stylusButton1Tool.get();
case Button::BUTTON_STYLUS_TWO:
return this->stylusButton2Tool.get();
case Button::BUTTON_MOUSE_MIDDLE:
return this->mouseMiddleButtonTool.get();
case Button::BUTTON_MOUSE_RIGHT:
return this->mouseRightButtonTool.get();
case Button::BUTTON_TOUCH:
return this->touchDrawingButtonTool.get();
default:
g_error("This button is not defined for ToolHandler.");
}
}
void ToolHandler::resetButtonTool(ToolType type, Button button) {
auto& tool = *(tools[type - TOOL_PEN]);
switch (button) {
case Button::BUTTON_ERASER:
this->eraserButtonTool.reset(new Tool(tool));
break;
case Button::BUTTON_STYLUS_ONE:
this->stylusButton1Tool.reset(new Tool(tool));
break;
case Button::BUTTON_STYLUS_TWO:
this->stylusButton2Tool.reset(new Tool(tool));
break;
case Button::BUTTON_MOUSE_MIDDLE:
this->mouseMiddleButtonTool.reset(new Tool(tool));
break;
case Button::BUTTON_MOUSE_RIGHT:
this->mouseRightButtonTool.reset(new Tool(tool));
break;
case Button::BUTTON_TOUCH:
this->touchDrawingButtonTool.reset(new Tool(tool));
break;
default:
g_error("This button is not defined for ToolHandler.");
}
}
| 26,089
|
C++
|
.cpp
| 559
| 38.890877
| 136
| 0.647207
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,448
|
PrintHandler.cpp
|
xournalpp_xournalpp/src/core/control/PrintHandler.cpp
|
#include "PrintHandler.h"
#include <cmath> // for M_PI_2
#include <memory> // for __shared_ptr_access
#include <string> // for string
#include <cairo.h> // for cairo_rotate, cairo_translate, cairo_t
#include <config-dev.h> // for PRINT_CONFIG_FILE
#include <glib-object.h> // for g_object_unref, G_CALLBACK, g_signa...
#include <glib.h> // for GError, g_error_free, g_warning
#include "model/Document.h" // for Document
#include "model/PageRef.h" // for PageRef
#include "model/PageType.h" // for PageType
#include "model/XojPage.h" // for XojPage
#include "pdf/base/XojPdfPage.h" // for XojPdfPageSPtr, XojPdfPage
#include "util/Assert.h" // for xoj_assert
#include "util/PathUtil.h" // for getConfigFile
#include "util/XojMsgBox.h" // for XojMsgBox
#include "util/i18n.h" // for _
#include "util/safe_casts.h" // for strict_cast
#include "view/DocumentView.h" // for DocumentView
#include "filesystem.h" // for exists, remove, path
namespace {
void drawPage(GtkPrintOperation* /*operation*/, GtkPrintContext* context, int pageNr, Document* doc) {
cairo_t* cr = gtk_print_context_get_cairo_context(context);
PageRef page = doc->getPage(static_cast<size_t>(pageNr));
if (!page) {
return;
}
double width = page->getWidth();
double height = page->getHeight();
if (width > height) {
cairo_rotate(cr, M_PI_2);
cairo_translate(cr, 0, -height);
}
// For better quality printing, we use a dedicated pdf-renderer in this case
if (page->getBackgroundType().isPdfPage()) {
XojPdfPageSPtr popplerPage = doc->getPdfPage(page->getPdfPageNr());
if (popplerPage) {
popplerPage->renderForPrinting(cr);
}
}
xoj::view::BackgroundFlags flags = xoj::view::BACKGROUND_SHOW_ALL;
flags.showPDF = xoj::view::HIDE_PDF_BACKGROUND; // Already printed (if any)
DocumentView view;
view.drawPage(page, cr, true /* dont render eraseable */, flags);
}
void requestPageSetup(GtkPrintOperation* /*op*/, GtkPrintContext* /*ctx*/, int pageNr, GtkPageSetup* setup,
Document* doc) {
PageRef page = doc->getPage(static_cast<size_t>(pageNr)); // Can't be negative
if (!page) {
return;
}
double width = page->getWidth();
double height = page->getHeight();
if (width > height) {
gtk_page_setup_set_orientation(setup, GTK_PAGE_ORIENTATION_LANDSCAPE);
} else {
gtk_page_setup_set_orientation(setup, GTK_PAGE_ORIENTATION_PORTRAIT);
}
GtkPaperSize* size = gtk_paper_size_new_custom("xoj-internal", "xoj-internal", width, height, GTK_UNIT_POINTS);
gtk_page_setup_set_paper_size(setup, size);
gtk_paper_size_free(size);
}
inline void handlePrintError(GError*& error, const char* message) {
if (error) {
g_warning(message, error->message);
g_error_free(error);
error = nullptr;
}
}
} // namespace
// Todo: maybe loop over this twice,
void PrintHandler::print(Document* doc, size_t currentPage, GtkWindow* parent) {
GtkPrintSettings* settings{};
auto filepath = Util::getConfigFile(PRINT_CONFIG_FILE);
if (fs::exists(filepath)) {
GError* error{};
settings = gtk_print_settings_new_from_file(filepath.u8string().c_str(), &error);
handlePrintError(error, "Loading print settings failed with: %s");
fs::remove(filepath);
}
if (settings == nullptr) {
settings = gtk_print_settings_new();
}
GtkPrintOperation* op = gtk_print_operation_new();
gtk_print_operation_set_print_settings(op, settings);
gtk_print_operation_set_n_pages(op, strict_cast<int>(doc->getPageCount()));
gtk_print_operation_set_current_page(op, strict_cast<int>(currentPage));
gtk_print_operation_set_job_name(op, "Xournal++");
gtk_print_operation_set_unit(op, GTK_UNIT_POINTS);
gtk_print_operation_set_use_full_page(op, true);
g_signal_connect(op, "draw_page", G_CALLBACK(drawPage), doc);
g_signal_connect(op, "request-page-setup", G_CALLBACK(requestPageSetup), doc);
GError* error{};
GtkPrintOperationResult res = gtk_print_operation_run(op, GTK_PRINT_OPERATION_ACTION_PRINT_DIALOG, parent, &error);
g_object_unref(settings);
if (GTK_PRINT_OPERATION_RESULT_APPLY == res) {
xoj_assert(!error);
settings = gtk_print_operation_get_print_settings(op);
gtk_print_settings_to_file(settings, filepath.u8string().c_str(), nullptr);
} else if (GTK_PRINT_OPERATION_RESULT_ERROR == res) {
xoj_assert(error);
std::string msg = FS(_F("Running print operation failed with {1}") % error->message);
XojMsgBox::showErrorToUser(nullptr, msg);
g_error_free(error);
}
g_object_unref(op);
}
| 4,825
|
C++
|
.cpp
| 107
| 39.925234
| 119
| 0.665177
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,449
|
XournalMain.cpp
|
xournalpp_xournalpp/src/core/control/XournalMain.cpp
|
#include "XournalMain.h"
#include <algorithm> // for copy, sort, max
#include <array> // for array
#include <chrono> // for time_point, duration, hours...
#include <clocale> // for setlocale, LC_NUMERIC
#include <cstdio> // for printf
#include <cstdlib> // for exit, size_t
#include <exception> // for exception
#include <iostream> // for operator<<, endl, basic_...
#include <locale> // for locale
#include <memory> // for unique_ptr, allocator
#include <optional> // for optional, nullopt
#include <sstream> // for stringstream
#include <stdexcept> // for runtime_error
#include <string> // for string, basic_string
#include <vector> // for vector
#include <gio/gio.h> // for GApplication, G_APPLICATION
#include <glib-object.h> // for G_CALLBACK, g_signal_con...
#include <glib.h> // for GOptionEntry, gchar, G_O...
#include <libintl.h> // for bindtextdomain, textdomain
#include "control/RecentManager.h" // for RecentManager
#include "control/jobs/BaseExportJob.h" // for ExportBackgroundType
#include "control/jobs/XournalScheduler.h" // for XournalScheduler
#include "control/settings/LatexSettings.h" // for LatexSettings
#include "control/settings/Settings.h" // for Settings
#include "control/settings/SettingsEnums.h" // for ICON_THEME_COLOR, ICON_T...
#include "control/xojfile/LoadHandler.h" // for LoadHandler
#include "control/xojfile/SaveHandler.h" // for SaveHandler
#include "gui/GladeSearchpath.h" // for GladeSearchpath
#include "gui/MainWindow.h" // for MainWindow
#include "gui/XournalView.h" // for XournalView
#include "model/Document.h" // for Document
#include "undo/EmergencySaveRestore.h" // for EmergencySaveRestore
#include "undo/UndoRedoHandler.h" // for UndoRedoHandler
#include "util/PathUtil.h" // for getConfigFolder, openFil...
#include "util/PlaceholderString.h" // for PlaceholderString
#include "util/Stacktrace.h" // for Stacktrace
#include "util/Util.h" // for execInUiThread
#include "util/XojMsgBox.h" // for XojMsgBox
#include "util/i18n.h" // for _, FS, _F
#include "Control.h" // for Control
#include "ExportHelper.h" // for exportImg, exportPdf
#include "config-dev.h" // for ERRORLOG_DIR
#include "config-git.h" // for GIT_BRANCH, GIT_ORIGIN_O...
#include "config.h" // for GETTEXT_PACKAGE, ENABLE_NLS
#include "filesystem.h" // for path, operator/, exists
namespace {
constexpr auto APP_FLAGS =
GApplicationFlags(G_APPLICATION_SEND_ENVIRONMENT | G_APPLICATION_NON_UNIQUE | G_APPLICATION_HANDLES_OPEN);
/// Configuration migration status.
enum class MigrateStatus {
NotNeeded, ///< No migration was needed.
Success, ///< Migration was carried out successfully.
Failure, ///< Migration failed. */
};
struct MigrateResult {
MigrateStatus status{};
std::string message; ///< Any additional information about the migration status.
};
auto migrateSettings() -> MigrateResult;
void checkForErrorlog();
void checkForEmergencySave(Control* control);
void initResourcePath(GladeSearchpath* gladePath, const gchar* relativePathAndFile, bool failIfNotFound = true);
void initCAndCoutLocales() {
/**
* Force numbers to be printed out and parsed by C libraries (cairo) in the "classic" locale.
* This avoids issue with tags when exporting to PDF, see #3551
*/
setlocale(LC_NUMERIC, "C");
std::cout.imbue(std::locale());
}
void initLocalisation() {
#ifdef ENABLE_NLS
fs::path localeDir = Util::getGettextFilepath(Util::getLocalePath());
#ifdef _WIN32
wbindtextdomain(GETTEXT_PACKAGE, localeDir.wstring().c_str());
#else
bindtextdomain(GETTEXT_PACKAGE, localeDir.u8string().c_str());
#endif
textdomain(GETTEXT_PACKAGE);
#ifdef _WIN32
bind_textdomain_codeset(GETTEXT_PACKAGE, "UTF-8");
#endif
#endif // ENABLE_NLS
// Not working on GNU g++(mingww) forWindows! Only working on Linux/macOS and with msvc
try {
std::locale::global(std::locale("")); // "" - system default locale
} catch (const std::runtime_error& e) {
g_warning("XournalMain: System default locale could not be set.\n - Caused by: %s\n - Note that it is not "
"supported to set the locale using mingw-w64 on windows.\n - This could be solved by compiling "
"xournalpp with msvc",
e.what());
}
initCAndCoutLocales();
}
auto migrateSettings() -> MigrateResult {
const fs::path newConfigPath = Util::getConfigFolder();
if (!fs::exists(newConfigPath)) {
const std::array oldPaths = {
Util::getConfigFolder().parent_path() /= "com.github.xournalpp.xournalpp",
Util::getConfigFolder().parent_path() /= "com.github.xournalpp.xournalpp.exe",
fs::u8path(g_get_home_dir()) /= ".xournalpp",
};
for (auto const& oldPath: oldPaths) {
if (!fs::is_directory(oldPath)) {
continue;
}
g_message("Migrating configuration from %s to %s", oldPath.string().c_str(),
newConfigPath.string().c_str());
Util::ensureFolderExists(newConfigPath.parent_path());
try {
fs::copy(oldPath, newConfigPath, fs::copy_options::recursive);
constexpr auto msg = "Due to a recent update, Xournal++ has changed where its configuration files are "
"stored.\nThey have been automatically copied from\n\t{1}\nto\n\t{2}";
return {MigrateStatus::Success, FS(_F(msg) % oldPath.u8string() % newConfigPath.u8string())};
} catch (const fs::filesystem_error& e) {
constexpr auto msg =
"Due to a recent update, Xournal++ has changed where its configuration files are "
"stored.\nHowever, when attempting to copy\n\t{1}\nto\n\t{2}\nmigration failed:\n{3}";
g_message("Migration failed: %s", e.what());
return {MigrateStatus::Failure, FS(_F(msg) % oldPath.u8string() % newConfigPath.u8string() % e.what())};
}
}
}
return {MigrateStatus::NotNeeded, ""};
}
static void deleteFile(const fs::path& file) {
std::error_code error;
if (!fs::remove(file, error)) {
std::stringstream msg;
msg << FS(_F("Failed to delete file: {1}") % file.u8string()) << std::endl;
msg << error << std::endl << error.message() << std::endl;
msg << FS(_F("Please delete the file manually"));
XojMsgBox::showErrorToUser(nullptr, msg.str());
}
}
void checkForErrorlog() {
std::vector<fs::path> errorList;
try {
const fs::path errorDir = Util::getCacheSubfolder(ERRORLOG_DIR);
if (!fs::exists(errorDir)) {
return;
}
// Todo(cpp20): replace std::chrono::hours(168) with std::chrono::weeks(1)
const auto oldestModificationDate = fs::file_time_type::clock::now() - std::chrono::hours(168);
for (auto const& f: fs::directory_iterator(errorDir)) {
if (f.is_regular_file() && f.path().filename().string().substr(0, 8) == "errorlog") {
if (f.last_write_time() > oldestModificationDate) {
errorList.emplace_back(f);
}
}
}
} catch (fs::filesystem_error& e) {
g_warning("Filesystem error while looking for crash logs:\n"
" %s\n"
" %s\n",
e.path1().u8string().c_str(), e.what());
return;
}
if (errorList.empty()) {
return;
}
std::sort(errorList.begin(), errorList.end());
std::string msg = errorList.size() == 1 ? _("There is a recent errorlogfile from Xournal++. Please file a "
"Bugreport, so the bug may be fixed.") :
_("There are recent errorlogfiles from Xournal++. Please file a "
"Bugreport, so the bug may be fixed.");
msg += "\n";
msg += FS(_F("The most recent log file name: {1}") % errorList[0].string());
msg += "\n\n";
msg += FS(_F("To prevent this popup from reappearing, simply delete the errorlogfiles."));
enum Responses { FILE_REPORT = 1, OPEN_FILE, OPEN_DIR, DELETE_FILE, CANCEL };
std::vector<XojMsgBox::Button> buttons = {{_("File Bug Report"), FILE_REPORT},
{_("Open Logfile"), OPEN_FILE},
{_("Open Logfile directory"), OPEN_DIR},
{_("Delete Logfile"), DELETE_FILE},
{_("Cancel"), CANCEL}};
XojMsgBox::askQuestion(nullptr, _("Crash log"), msg, buttons,
[errorlogPath = fs::path(errorList.front())](int response) {
if (response == FILE_REPORT) {
Util::openFileWithDefaultApplication(PROJECT_BUGREPORT);
Util::openFileWithDefaultApplication(errorlogPath);
} else if (response == OPEN_FILE) {
Util::openFileWithDefaultApplication(errorlogPath);
} else if (response == OPEN_DIR) {
Util::openFileWithDefaultApplication(errorlogPath.parent_path());
} else if (response == DELETE_FILE) {
deleteFile(errorlogPath);
}
});
}
void checkForEmergencySave(Control* control) {
auto file = Util::getConfigFile("emergencysave.xopp");
if (!fs::exists(file)) {
return;
}
const std::string msg = _("Xournal++ crashed last time. Would you like to restore the last edited file?");
enum { DELETE_FILE = 1, RESTORE_FILE };
XojMsgBox::askQuestion(
nullptr, _("Recovery file detected"), msg,
{{_("Delete file"), DELETE_FILE}, {_("Restore file"), RESTORE_FILE}},
[file = std::move(file), ctrl = control](int response) mutable {
if (response == DELETE_FILE) {
deleteFile(file);
} else if (response == RESTORE_FILE) {
ctrl->openFileWithoutSavingTheCurrentDocument(file, false, -1, [ctrl, file](bool) {
ctrl->getDocument()->setFilepath("");
// Todo Make sure the document is changed + ask for saving
ctrl->getUndoRedoHandler()->addUndoAction(std::make_unique<EmergencySaveRestore>());
deleteFile(file);
});
}
});
}
namespace {
void exitOnMissingPdfFileName(const LoadHandler& loader) {
if (!loader.getMissingPdfFilename().empty()) {
auto msg =
FS(_F("The background file \"{1}\" could not be found. It might have been moved, renamed or deleted.") %
loader.getMissingPdfFilename());
std::cerr << msg << std::endl;
exit(-2);
}
}
} // namespace
/**
* @brief Export the input file as a bunch of image files (one per page)
* @param input Path to the input file
* @param output Path to the output file(s)
* @param range Page range to be parsed. If range=nullptr, exports the whole file
* @param layerRange Layer range to be parsed. Will only export those layers, for every exported page.
* If a number is too high for the number of layers on a given page, it is just ignored.
* If range=nullptr, exports all layers.
* @param pngDpi Set dpi for Png files. Non positive values are ignored
* @param pngWidth Set the width for Png files. Non positive values are ignored
* @param pngHeight Set the height for Png files. Non positive values are ignored
* @param exportBackground If EXPORT_BACKGROUND_NONE, the exported image file has transparent background
*
* The priority is: pngDpi overwrites pngWidth overwrites pngHeight
*
* @return 0 on success, -2 on failure opening the input file, -3 on export failure
*/
auto exportImg(const char* input, const char* output, const char* range, const char* layerRange, int pngDpi,
int pngWidth, int pngHeight, ExportBackgroundType exportBackground) -> int {
LoadHandler loader;
auto doc = loader.loadDocument(input);
if (doc == nullptr) {
g_error("%s", loader.getLastError().c_str());
}
exitOnMissingPdfFileName(loader);
return ExportHelper::exportImg(doc.get(), output, range, layerRange, pngDpi, pngWidth, pngHeight, exportBackground);
}
/**
* @brief Save a xopp-file with given pdf-background
*
* @param input Path to the input .pdf file
* @param output Path to the output .xopp file
* @return int 0 on success
*/
auto saveDoc(const char* input, const char* output) -> int {
// LoadHandler loader;
SaveHandler saver;
char* inputFilename = (char*)input;
const fs::path p = Util::fromGFilename(inputFilename, false);
auto handler = std::make_unique<DocumentHandler>();
auto newDoc = std::make_unique<Document>(handler.get());
const bool res = newDoc->readPdf(p, /*initPages=*/true, false);
if (!res) {
g_error("%s", FC(_F("Error: {1}") % newDoc->getLastErrorMsg().c_str()));
}
saver.prepareSave(newDoc.get());
saver.saveTo(output);
if (!saver.getErrorMessage().empty()) {
g_error("%s", FC(_F("Error: {1}") % saver.getErrorMessage()));
}
return 0;
}
/**
* @brief Export the input file as pdf
* @param input Path to the input file
* @param output Path to the output file
* @param layerRange Layer range to be parsed. Will only export those layers, for every exported page.
* If a number is too high for the number of layers on a given page, it is just ignored.
* If range=nullptr, exports all layers.
* @param range Page range to be parsed. If range=nullptr, exports the whole file
* @param exportBackground If EXPORT_BACKGROUND_NONE, the exported pdf file has white background
* @param progressiveMode If true, then for each xournalpp page, instead of rendering one PDF page, the page layers are
* rendered one by one to produce as many pages as there are layers.
*
* @return 0 on success, -2 on failure opening the input file, -3 on export failure
*/
auto exportPdf(const char* input, const char* output, const char* range, const char* layerRange,
ExportBackgroundType exportBackground, bool progressiveMode) -> int {
LoadHandler loader;
auto doc = loader.loadDocument(input);
if (doc == nullptr) {
g_error("%s", loader.getLastError().c_str());
}
exitOnMissingPdfFileName(loader);
return ExportHelper::exportPdf(doc.get(), output, range, layerRange, exportBackground, progressiveMode);
}
struct XournalMainPrivate {
XournalMainPrivate() = default;
XournalMainPrivate(XournalMainPrivate&&) = delete;
XournalMainPrivate(XournalMainPrivate const&) = delete;
auto operator=(XournalMainPrivate&&) -> XournalMainPrivate = delete;
auto operator=(XournalMainPrivate const&) -> XournalMainPrivate = delete;
~XournalMainPrivate() {
g_strfreev(optFilename);
g_free(pdfFilename);
g_free(imgFilename);
g_free(docFilename);
}
gchar** optFilename{};
gchar* pdfFilename{};
gchar* imgFilename{};
gchar* docFilename{};
gboolean showVersion = false;
int openAtPageNumber = 0; // when no --page is used, the document opens at the page specified in the metadata file
gchar* exportRange{};
gchar* exportLayerRange{};
int exportPngDpi = -1;
int exportPngWidth = -1;
int exportPngHeight = -1;
gboolean exportNoBackground = false;
gboolean exportNoRuling = false;
gboolean progressiveMode = false;
gboolean disableAudio = false;
gboolean attachMode = false;
std::unique_ptr<GladeSearchpath> gladePath;
std::unique_ptr<Control> control;
std::unique_ptr<MainWindow> win;
};
using XMPtr = XournalMainPrivate*;
/// Checks for input method compatibility and ensures it
void ensure_input_model_compatibility() {
const char* imModule = g_getenv("GTK_IM_MODULE");
if (imModule != nullptr) {
const std::string imModuleString{imModule};
if (imModuleString == "xim") {
g_warning("Unsupported input method: %s", imModule);
}
}
}
/**
* Find a file in a resource folder, and return the resource folder path
* Return an empty string, if the folder was not found
*/
auto findResourcePath(const fs::path& searchFile) -> fs::path {
auto search_for = [&searchFile](fs::path start) -> std::optional<fs::path> {
constexpr auto* postfix = "share/xournalpp";
/// 1. relative install
/// 2. windows install
/// 3. build dir
for (int i = 0; i < 3; ++i, start = start.parent_path()) {
if (auto target = start / searchFile; fs::exists(target)) {
return target.parent_path();
}
if (auto folder = start / postfix / searchFile; fs::exists(folder)) {
return folder.parent_path();
}
}
return std::nullopt;
};
/* /// relative execution path
if (auto path = search_for(fs::path{}); path) {
return *path;
}*/
/// real execution path
if (auto path = search_for(Stacktrace::getExePath().parent_path()); path) {
return *path;
}
// Not found
return {};
}
void initResourcePath(GladeSearchpath* gladePath, const gchar* relativePathAndFile, bool failIfNotFound) {
auto uiPath = findResourcePath(relativePathAndFile); // i.e. relativePathAndFile = "ui/about.glade"
if (!uiPath.empty()) {
gladePath->addSearchDirectory(uiPath);
return;
}
// -----------------------------------------------------------------------
fs::path p = Util::getDataPath();
p /= relativePathAndFile;
if (fs::exists(p)) {
gladePath->addSearchDirectory(p.parent_path());
return;
}
std::string msg =
FS(_F("<span foreground='red' size='x-large'>Missing the needed UI file:\n<b>{1}</b></span>\nCould "
"not find them at any location.\n Not relative\n Not in the Working Path\n Not in {2}") %
relativePathAndFile % Util::getDataPath().string());
if (!failIfNotFound) {
msg += _("\n\nWill now attempt to run without this file.");
XojMsgBox::showErrorToUser(nullptr, msg);
} else {
XojMsgBox::showErrorAndQuit(msg, 12);
}
}
void on_activate(GApplication*, XMPtr) {}
void on_command_line(GApplication*, GApplicationCommandLine*, XMPtr) {
g_message("XournalMain::on_command_line: This should never happen, please file a bugreport with a detailed "
"description how to reproduce this message");
// Todo: implement this, if someone files the bug report
}
void on_open_files(GApplication* application, GFile** files, gint numFiles, gchar* hint, XMPtr app_data) {
if (numFiles != 1) {
const std::string msg = _("Sorry, Xournal++ can only open one file at once.\n"
"Others are ignored.");
XojMsgBox::showErrorToUser(GTK_WINDOW(app_data->win->getWindow()), msg);
}
const fs::path p = Util::fromGFilename(g_file_get_path(files[0]), false);
try {
if (fs::exists(p)) {
app_data->control->openFile(p);
} else {
const std::string msg = FS(_F("File {1} does not exist.") % p.u8string());
XojMsgBox::showErrorToUser(GTK_WINDOW(app_data->win->getWindow()), msg);
}
} catch (const fs::filesystem_error& e) {
const std::string msg = FS(_F("Filesystem error: {1}\n"
"Sorry, Xournal++ cannot open the file: {2}\n"
"Consider copying the file to a local directory.") %
e.what() % p.u8string());
XojMsgBox::showErrorToUser(GTK_WINDOW(app_data->win->getWindow()), msg);
}
gtk_window_present(GTK_WINDOW(app_data->win->getWindow()));
}
void on_startup(GApplication* application, XMPtr app_data) {
initLocalisation();
ensure_input_model_compatibility();
const MigrateResult migrateResult = migrateSettings();
app_data->gladePath = std::make_unique<GladeSearchpath>();
initResourcePath(app_data->gladePath.get(), "ui/about.glade");
initResourcePath(app_data->gladePath.get(), "ui/xournalpp.css", false);
app_data->control = std::make_unique<Control>(application, app_data->gladePath.get(), app_data->disableAudio);
auto& globalLatexTemplatePath = app_data->control->getSettings()->latexSettings.globalTemplatePath;
if (globalLatexTemplatePath.empty()) {
globalLatexTemplatePath = findResourcePath("resources/") / "default_template.tex";
g_message("Using default latex template in %s", globalLatexTemplatePath.string().c_str());
app_data->control->getSettings()->save();
}
app_data->win = std::make_unique<MainWindow>(app_data->gladePath.get(), app_data->control.get(),
GTK_APPLICATION(application));
app_data->control->initWindow(app_data->win.get());
app_data->win->populate(app_data->gladePath.get());
if (migrateResult.status != MigrateStatus::NotNeeded) {
Util::execInUiThread(
[=]() { XojMsgBox::showErrorToUser(app_data->control->getGtkWindow(), migrateResult.message); });
}
gtk_application_set_menubar(GTK_APPLICATION(application), app_data->win->getMenuModel());
// Do we want stuff in gtk_application_set_app_menu?
app_data->win->show(nullptr);
fs::path p;
if (app_data->optFilename) {
if (g_strv_length(app_data->optFilename) != 1) {
const std::string msg = _("Sorry, Xournal++ can only open one file at once.\n"
"Others are ignored.");
XojMsgBox::showErrorToUser(GTK_WINDOW(app_data->win->getWindow()), msg);
}
p = Util::fromGFilename(app_data->optFilename[0], false);
} else if (app_data->control->getSettings()->isAutoloadMostRecent()) {
auto most_recent = RecentManager::getMostRecent();
if (most_recent) {
if (auto opt = Util::fromUri(gtk_recent_info_get_uri(most_recent.get()))) {
p = opt.value();
}
}
}
app_data->control->openFileWithoutSavingTheCurrentDocument(
std::move(p), app_data->attachMode, app_data->openAtPageNumber - 1,
[ctrl = app_data->control.get(), app = GTK_APPLICATION(application)](bool) {
ctrl->getScheduler()->start();
checkForErrorlog();
checkForEmergencySave(ctrl);
// There is a timing issue with the layout
// This fixes it, see #405
Util::execInUiThread([=]() { ctrl->getWindow()->getXournal()->layoutPages(); });
gtk_application_add_window(app, ctrl->getGtkWindow());
});
}
auto on_handle_local_options(GApplication*, GVariantDict*, XMPtr app_data) -> gint {
initCAndCoutLocales();
auto print_version = [&] {
if (!std::string(GIT_COMMIT_ID).empty()) {
std::cout << PROJECT_NAME << " " << PROJECT_VERSION << " (" << GIT_COMMIT_ID << ")" << std::endl;
} else {
std::cout << PROJECT_NAME << " " << PROJECT_VERSION << std::endl;
}
std::cout << "└──libgtk: " << gtk_get_major_version() << "." //
<< gtk_get_minor_version() << "." //
<< gtk_get_micro_version() << std::endl; //
};
auto exec_guarded = [&](auto&& fun, auto&& s) {
try {
return fun();
} catch (const std::exception& e) {
std::cerr << "Error: " << e.what() << std::endl;
std::cerr << "In: " << s << std::endl;
print_version();
return (1);
} catch (...) {
std::cerr << "Error: Unknown exception" << std::endl;
std::cerr << "In: " << s << std::endl;
print_version();
return (1);
}
};
if (app_data->showVersion) {
print_version();
return (0);
}
if (app_data->pdfFilename && app_data->optFilename && *app_data->optFilename) {
return exec_guarded(
[&] {
return exportPdf(*app_data->optFilename, app_data->pdfFilename, app_data->exportRange,
app_data->exportLayerRange,
app_data->exportNoBackground ? EXPORT_BACKGROUND_NONE :
app_data->exportNoRuling ? EXPORT_BACKGROUND_UNRULED :
EXPORT_BACKGROUND_ALL,
app_data->progressiveMode);
},
"exportPdf");
}
if (app_data->imgFilename && app_data->optFilename && *app_data->optFilename) {
return exec_guarded(
[&] {
return exportImg(*app_data->optFilename, app_data->imgFilename, app_data->exportRange,
app_data->exportLayerRange, app_data->exportPngDpi, app_data->exportPngWidth,
app_data->exportPngHeight,
app_data->exportNoBackground ? EXPORT_BACKGROUND_NONE :
app_data->exportNoRuling ? EXPORT_BACKGROUND_UNRULED :
EXPORT_BACKGROUND_ALL);
},
"exportImg");
}
if (app_data->docFilename && app_data->optFilename && *app_data->optFilename) {
return exec_guarded([&] { return saveDoc(*app_data->optFilename, app_data->docFilename); }, "saveDocument");
}
return -1;
}
void on_shutdown(GApplication*, XMPtr app_data) {
app_data->control->saveSettings();
app_data->win->getXournal()->clearSelection();
app_data->control->getScheduler()->stop();
}
} // namespace
auto XournalMain::run(int argc, char** argv) -> int {
XournalMainPrivate app_data;
GtkApplication* app = gtk_application_new("com.github.xournalpp.xournalpp", APP_FLAGS);
g_object_set(G_OBJECT(app), "register-session", true, nullptr); // Needed for opening files on MacOS from Finder
g_set_prgname("com.github.xournalpp.xournalpp");
g_signal_connect(app, "activate", G_CALLBACK(&on_activate), &app_data);
g_signal_connect(app, "command-line", G_CALLBACK(&on_command_line), &app_data);
g_signal_connect(app, "open", G_CALLBACK(&on_open_files), &app_data);
g_signal_connect(app, "startup", G_CALLBACK(&on_startup), &app_data);
g_signal_connect(app, "shutdown", G_CALLBACK(&on_shutdown), &app_data);
g_signal_connect(app, "handle-local-options", G_CALLBACK(&on_handle_local_options), &app_data);
std::array options = {GOptionEntry{"page", 'n', 0, G_OPTION_ARG_INT, &app_data.openAtPageNumber,
_("Jump to Page (first Page: 1)"), "N"},
GOptionEntry{G_OPTION_REMAINING, 0, 0, G_OPTION_ARG_FILENAME_ARRAY, &app_data.optFilename,
"<input>", nullptr},
GOptionEntry{"version", 0, 0, G_OPTION_ARG_NONE, &app_data.showVersion,
_("Get version of xournalpp"), nullptr},
GOptionEntry{"disable-audio", 0, 0, G_OPTION_ARG_NONE, &app_data.disableAudio,
_("Disable audio for this session"), nullptr},
GOptionEntry{"attach-mode", 0, 0, G_OPTION_ARG_NONE, &app_data.attachMode,
_("Open PDF in attach mode\n"
" Ignored if no PDF file is specified."),
nullptr},
GOptionEntry{"save", 's', 0, G_OPTION_ARG_FILENAME, &app_data.docFilename,
_("Save xopp-file with the background PDF specified as FILE"), "XOPPFILE"},
GOptionEntry{nullptr}}; // Must be terminated by a nullptr. See gtk doc
g_application_add_main_option_entries(G_APPLICATION(app), options.data());
/**
* Export related options
*/
std::array exportOptions = {
GOptionEntry{"create-pdf", 'p', G_OPTION_FLAG_IN_MAIN, G_OPTION_ARG_FILENAME, &app_data.pdfFilename,
_("Export FILE as PDF"), "PDFFILE"},
GOptionEntry{"create-img", 'i', G_OPTION_FLAG_IN_MAIN, G_OPTION_ARG_FILENAME, &app_data.imgFilename,
_("Export FILE as image files (one per page)\n"
" Guess the output format from the extension of IMGFILE\n"
" Supported formats: .png, .svg"),
"IMGFILE"},
GOptionEntry{"export-no-background", 0, 0, G_OPTION_ARG_NONE, &app_data.exportNoBackground,
_("Export without background\n"
" The exported file has transparent or white background,\n"
" depending on what its format supports\n"),
0},
GOptionEntry{"export-no-ruling", 0, 0, G_OPTION_ARG_NONE, &app_data.exportNoRuling,
_("Export without ruling\n"
" The exported file has no paper ruling\n"),
0},
GOptionEntry{"export-layers-progressively", 0, 0, G_OPTION_ARG_NONE, &app_data.progressiveMode,
_("Export layers progressively\n"
" In PDF export, Render layers progressively one by one.\n"
" This results in N export pages per page with N layers,\n"
" building up the layer stack progressively.\n"
" The resulting PDF file can be used for a presentation.\n"),
0},
GOptionEntry{"export-range", 0, 0, G_OPTION_ARG_STRING, &app_data.exportRange,
_("Only export the pages specified by RANGE (e.g. \"2-3,5,7-\")\n"
" No effect without -p/--create-pdf or -i/--create-img"),
"RANGE"},
GOptionEntry{"export-layer-range", 0, 0, G_OPTION_ARG_STRING, &app_data.exportLayerRange,
_("Only export the layers specified by RANGE (e.g. \"2-3,5,7-\")\n"
" No effect without -p/--create-pdf or -i/--create-img"),
"RANGE"},
GOptionEntry{"export-png-dpi", 0, 0, G_OPTION_ARG_INT, &app_data.exportPngDpi,
_("Set DPI for PNG exports. Default is 300\n"
" No effect without -i/--create-img=foo.png"),
"N"},
GOptionEntry{"export-png-width", 0, 0, G_OPTION_ARG_INT, &app_data.exportPngWidth,
_("Set page width for PNG exports\n"
" No effect without -i/--create-img=foo.png\n"
" Ignored if --export-png-dpi is used"),
"N"},
GOptionEntry{
"export-png-height", 0, 0, G_OPTION_ARG_INT, &app_data.exportPngHeight,
_("Set page height for PNG exports\n"
" No effect without -i/--create-img=foo.png\n"
" Ignored if --export-png-dpi or --export-png-width is used"),
"N"},
GOptionEntry{nullptr}}; // Must be terminated by a nullptr. See gtk doc
GOptionGroup* exportGroup = g_option_group_new("export", _("Advanced export options"),
_("Display advanced export options"), nullptr, nullptr);
g_option_group_add_entries(exportGroup, exportOptions.data());
g_application_add_option_group(G_APPLICATION(app), exportGroup);
auto rv = g_application_run(G_APPLICATION(app), argc, argv);
g_object_unref(app);
return rv;
}
| 33,354
|
C++
|
.cpp
| 633
| 42.017378
| 120
| 0.577584
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,450
|
DeviceListHelper.cpp
|
xournalpp_xournalpp/src/core/control/DeviceListHelper.cpp
|
#include "control/DeviceListHelper.h"
#include <algorithm> // for find, remove_if
#include <utility> // for move
#include <vector> // for vector
#include <glib.h> // for g_list_free, g_warning
#include "control/settings/Settings.h" // for Settings
#include "util/GListView.h" // for GListView, GListView<>::GList...
#include "util/i18n.h" // for _
void storeNewUnlistedDevice(std::vector<InputDevice>& deviceList, GdkDevice* device) {
// This could potentially be problematic with systems having a multitude of input devices as it searches linearily
auto it = std::find(deviceList.begin(), deviceList.end(), InputDevice(device));
if (it != deviceList.end()) {
// Device is already known but source may be unknown
it->updateType(gdk_device_get_source(device));
return;
}
deviceList.emplace_back(device);
}
void addDevicesToList(std::vector<InputDevice>& deviceList, GListView<GdkDevice> devView, bool ignoreTouchDevices) {
for (GdkDevice& dev: devView) {
if (GDK_SOURCE_KEYBOARD == gdk_device_get_source(&dev)) {
continue;
}
if (gdk_device_get_vendor_id(&dev) == nullptr && gdk_device_get_product_id(&dev) == nullptr) {
continue;
}
if (ignoreTouchDevices && GDK_SOURCE_TOUCHSCREEN == gdk_device_get_source(&dev)) {
continue;
}
storeNewUnlistedDevice(deviceList, &dev);
}
}
auto DeviceListHelper::getDeviceList(Settings* settings, bool ignoreTouchDevices) -> std::vector<InputDevice> {
std::vector<InputDevice> deviceList = settings->getKnownInputDevices();
if (ignoreTouchDevices) {
deviceList.erase(
std::remove_if(deviceList.begin(), deviceList.end(),
[](const InputDevice& device) { return device.getSource() == GDK_SOURCE_TOUCHSCREEN; }),
deviceList.end());
}
GdkDisplay* display = gdk_display_get_default();
GdkSeat* defaultSeat = gdk_display_get_default_seat(display);
GdkDevice* pointer = gdk_seat_get_pointer(defaultSeat);
GdkSeat* pointerSeat = gdk_device_get_seat(pointer);
auto* pointerSlaves = gdk_seat_get_slaves(pointerSeat, GDK_SEAT_CAPABILITY_ALL_POINTING);
addDevicesToList(deviceList, pointerSlaves, ignoreTouchDevices);
g_list_free(pointerSlaves);
if (deviceList.empty()) {
g_warning("No device found. Is Xournal++ running in debugger / Eclipse...?\n"
"Probably this is the reason for not finding devices!\n");
}
return deviceList;
}
InputDeviceClass DeviceListHelper::getSourceMapping(GdkInputSource source, Settings* settings) {
auto deviceList = DeviceListHelper::getDeviceList(settings);
for (InputDevice const& inputDevice: deviceList) {
InputDeviceClass deviceClass =
InputEvents::translateDeviceType(inputDevice.getName(), inputDevice.getSource(), settings);
if (inputDevice.getSource() == source) {
return deviceClass;
}
}
return InputDeviceClass::INPUT_DEVICE_IGNORE;
}
InputDevice::InputDevice(GdkDevice* device): name(gdk_device_get_name(device)), source(gdk_device_get_source(device)) {}
InputDevice::InputDevice(std::string name, GdkInputSource source): name(std::move(name)), source(source) {}
auto InputDevice::getName() const -> std::string { return this->name; }
auto InputDevice::getSource() const -> GdkInputSource { return this->source; }
void InputDevice::updateType(GdkInputSource newSource) { this->source = newSource; }
auto InputDevice::getType() const -> std::string {
switch (source) {
case GDK_SOURCE_MOUSE:
return _("mouse");
case GDK_SOURCE_PEN:
return _("pen");
case GDK_SOURCE_ERASER:
return _("eraser");
case GDK_SOURCE_CURSOR:
return _("cursor");
case GDK_SOURCE_KEYBOARD:
// not used: filtered above
return _("keyboard");
case GDK_SOURCE_TOUCHSCREEN:
return _("touchscreen");
case GDK_SOURCE_TOUCHPAD:
return _("touchpad");
#if (GDK_MAJOR_VERSION >= 3 && GDK_MINOR_VERSION >= 22)
case GDK_SOURCE_TRACKPOINT:
return _("trackpoint");
case GDK_SOURCE_TABLET_PAD:
return _("tablet pad");
#endif
}
return "";
}
auto InputDevice::operator==(const InputDevice& inputDevice) const -> bool {
return this->getName() == inputDevice.getName();
}
| 4,519
|
C++
|
.cpp
| 98
| 39.061224
| 120
| 0.662952
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,451
|
LatexController.cpp
|
xournalpp_xournalpp/src/core/control/LatexController.cpp
|
#include "LatexController.h"
#include <cstdlib> // for free
#include <fstream> // for ifstream, basic_istream
#include <iterator> // for istreambuf_iterator, ope...
#include <limits> // for numeric_limits
#include <memory> // for unique_ptr, allocator
#include <optional> // for optional
#include <utility> // for move
#include <variant> // for get_if
#include <glib.h> // for g_error_free, g_error_ma...
#include "control/Tool.h" // for Tool
#include "control/ToolEnums.h" // for TOOL_TEXT
#include "control/ToolHandler.h" // for ToolHandler
#include "control/latex/LatexGenerator.h" // for LatexGenerator::GenError
#include "control/settings/LatexSettings.h" // for LatexSettings
#include "control/settings/Settings.h" // for Settings
#include "control/tools/EditSelection.h" // for EditSelection
#include "gui/Layout.h" // for Layout
#include "gui/MainWindow.h" // for MainWindow
#include "gui/PageView.h" // for XojPageView
#include "gui/XournalView.h" // for XournalView
#include "gui/dialog/LatexDialog.h" // for LatexDialog
#include "model/Document.h" // for Document
#include "model/Element.h" // for Element
#include "model/Layer.h" // for Layer
#include "model/TexImage.h" // for TexImage
#include "model/Text.h" // for Text
#include "model/XojPage.h" // for XojPage
#include "undo/InsertUndoAction.h" // for InsertUndoAction
#include "undo/UndoRedoHandler.h" // for UndoRedoHandler
#include "util/Assert.h" // for xoj_assert
#include "util/Color.h" // for Color, get_color_contrast
#include "util/PathUtil.h" // for ensureFolderExists, getT...
#include "util/PlaceholderString.h" // for PlaceholderString
#include "util/PopupWindowWrapper.h" // for PopupWindowWrapper
#include "util/Rectangle.h" // for Rectangle
#include "util/Util.h" // for npos
#include "util/XojMsgBox.h" // for XojMsgBox
#include "util/i18n.h" // for FS, _, _F, N_
#include "util/safe_casts.h" // for round_cast
#include "Control.h" // for Control
using std::string;
constexpr Color LIGHT_PREVIEW_BACKGROUND = Colors::white;
constexpr Color DARK_PREVIEW_BACKGROUND = Colors::black;
LatexController::LatexController(Control* control):
control(control),
settings(control->getSettings()->latexSettings),
doc(control->getDocument()),
texTmpDir(Util::getTmpDirSubfolder("tex")),
generator(settings) {
Util::ensureFolderExists(this->texTmpDir);
}
LatexController::~LatexController() {
if (updating_cancellable) {
g_cancellable_cancel(updating_cancellable);
g_object_unref(updating_cancellable);
}
this->control = nullptr;
}
/**
* Find the tex executable, return false if not found
*/
auto LatexController::findTexDependencies() -> LatexController::FindDependencyStatus {
auto templatePath = this->settings.globalTemplatePath;
if (fs::is_regular_file(templatePath)) {
std::ifstream is(templatePath, std::ios_base::binary);
if (!is.is_open()) {
g_message("%s", templatePath.string().c_str());
string msg = _("Global template file does not exist. Please check your settings.");
return LatexController::FindDependencyStatus(false, msg);
}
this->latexTemplate = std::string(std::istreambuf_iterator<char>(is), {});
if (!is.good()) {
string msg = _("Failed to read global template file. Please check your settings.");
return LatexController::FindDependencyStatus(false, msg);
}
return LatexController::FindDependencyStatus(true, "");
} else {
string msg = _("Global template file is not a regular file. Please check your settings. ");
return LatexController::FindDependencyStatus(false, msg);
}
}
/**
* Find a selected tex element, and load it
*/
void LatexController::findSelectedTexElement() {
this->doc->lock();
auto pageNr = this->control->getCurrentPageNo();
if (pageNr == npos) {
this->doc->unlock();
return;
}
this->view = this->control->getWindow()->getXournal()->getViewFor(pageNr);
if (view == nullptr) {
this->doc->unlock();
return;
}
// we get the selection
this->page = this->doc->getPage(pageNr);
this->layer = page->getSelectedLayer();
this->selectedElem = view->getSelectedTex() != nullptr ? static_cast<Element*>(view->getSelectedTex()) :
static_cast<Element*>(view->getSelectedText());
if (this->selectedElem) {
// this will get the position of the Latex properly
EditSelection* theSelection = control->getWindow()->getXournal()->getSelection();
xoj::util::Rectangle<double> rect = theSelection->getSnappedBounds();
this->posx = rect.x;
this->posy = rect.y;
if (auto* img = dynamic_cast<TexImage*>(this->selectedElem)) {
this->initialTex = img->getText();
this->temporaryRender = img->cloneTexImage();
this->isValidTex = true;
} else if (auto* txt = dynamic_cast<Text*>(this->selectedElem)) {
this->initialTex = "\\text{" + txt->getText() + "}";
}
this->imgwidth = this->selectedElem->getElementWidth();
this->imgheight = this->selectedElem->getElementHeight();
} else {
// This is a new latex object, so here we pick a convenient initial location
const double zoom = this->control->getWindow()->getXournal()->getZoom();
Layout* const layout = this->control->getWindow()->getLayout();
// Calculate coordinates (screen) of the center of the visible area
const auto visibleBounds = layout->getVisibleRect();
const double centerX = visibleBounds.x + 0.5 * visibleBounds.width;
const double centerY = visibleBounds.y + 0.5 * visibleBounds.height;
if (layout->getPageViewAt(round_cast<int>(centerX), round_cast<int>(centerY)) == this->view) {
// Pick the center of the visible area (converting from screen to page coordinates)
this->posx = (centerX - this->view->getX()) / zoom;
this->posy = (centerY - this->view->getY()) / zoom;
} else {
// No better location, so just center it on the page (possibly out of viewport)
this->posx = this->page->getWidth() / 2;
this->posy = this->page->getHeight() / 2;
}
}
this->doc->unlock();
}
void LatexController::showTexEditDialog(std::unique_ptr<LatexController> ctrl) {
LatexController* texCtrl = ctrl.get();
xoj::popup::PopupWindowWrapper<LatexDialog> popup(texCtrl->control->getGladeSearchPath(), std::move(ctrl));
popup.show(GTK_WINDOW(texCtrl->control->getWindow()->getWindow()));
}
void LatexController::triggerImageUpdate(const string& texString) {
xoj_assert(this->dlg);
if (this->isUpdating()) {
return;
}
Color textColor = this->control->getToolHandler()->getTool(TOOL_TEXT).getColor();
// Determine a background color that has enough contrast with the text color:
if (Util::get_color_contrast(textColor, LIGHT_PREVIEW_BACKGROUND) > 0.5) {
this->dlg->setPreviewBackgroundColor(LIGHT_PREVIEW_BACKGROUND);
} else {
this->dlg->setPreviewBackgroundColor(DARK_PREVIEW_BACKGROUND);
}
this->lastPreviewedTex = texString;
const std::string texContents = LatexGenerator::templateSub(texString, this->latexTemplate, textColor);
auto result = generator.asyncRun(this->texTmpDir, texContents);
if (auto* err = std::get_if<LatexGenerator::GenError>(&result)) {
XojMsgBox::showErrorToUser(this->control->getGtkWindow(), err->message);
} else if (auto** proc = std::get_if<GSubprocess*>(&result)) {
// Render the TeX and capture the process' output.
updating_cancellable = g_cancellable_new();
char* stdinBuff = nullptr; // No stdin
g_subprocess_communicate_utf8_async(*proc, stdinBuff, updating_cancellable,
reinterpret_cast<GAsyncReadyCallback>(onPdfRenderComplete), this);
}
updateStatus();
}
/**
* Text-changed handler: when the Buffer in the dialog changes, this handler
* removes the previous existing render and creates a new one. We need to do it
* through 'self' because signal handlers cannot directly access non-static
* methods and non-static fields such as 'dlg' so we need to wrap all the dlg
* method inside small methods in 'self'. To improve performance, we render the
* text asynchronously.
*/
void LatexController::handleTexChanged(LatexController* self) {
self->triggerImageUpdate(self->dlg->getBufferContents());
}
void LatexController::onPdfRenderComplete(GObject* procObj, GAsyncResult* res, LatexController* self) {
GError* err = nullptr;
bool procExited = false;
GSubprocess* proc = G_SUBPROCESS(procObj);
// Extract the process' output and store it.
{
char* procStdout_ptr = nullptr;
// Stdout and stderr should be merged.
procExited = g_subprocess_communicate_utf8_finish(proc, res, &procStdout_ptr, nullptr, &err);
// If we have stdout, store it.
if (procStdout_ptr != nullptr) {
self->texProcessOutput = procStdout_ptr;
free(procStdout_ptr);
} else {
g_warning("latex command: no stdout stream");
}
}
if (err != nullptr) {
if (g_error_matches(err, G_IO_ERROR, G_IO_ERROR_CANCELLED)) {
// the render was canceled
g_error_free(err);
return;
} else if (!g_error_matches(err, G_SPAWN_EXIT_ERROR, 1)) {
// The error was not caused by invalid LaTeX.
string message =
FS(_F("Latex generation encountered an error: {1} (exit code: {2})") % err->message % err->code);
XojMsgBox::showErrorToUser(self->control->getGtkWindow(), message);
}
self->isValidTex = false;
g_error_free(err);
} else if (procExited && g_subprocess_get_exit_status(proc) != 0) {
// Command exited with non-zero exit status.
self->isValidTex = false;
} else {
self->isValidTex = true;
}
// Delete the PDF if the TeX is invalid.
if (!self->isValidTex) {
fs::path pdfPath = self->texTmpDir / "tex.pdf";
fs::remove(pdfPath);
}
const string currentTex = self->dlg->getBufferContents();
bool shouldUpdate = self->lastPreviewedTex != currentTex;
if (self->isValidTex) {
self->temporaryRender = self->loadRendered(currentTex);
if (self->temporaryRender != nullptr) {
self->dlg->setTempRender(self->temporaryRender->getPdf());
}
}
g_clear_object(&self->updating_cancellable);
g_clear_object(&proc);
self->updateStatus();
if (shouldUpdate) {
self->triggerImageUpdate(currentTex);
}
}
bool LatexController::isUpdating() { return updating_cancellable; }
void LatexController::updateStatus() { this->dlg->setCompilationStatus(isValidTex, !isUpdating(), texProcessOutput); }
void LatexController::deleteOldImage() {
if (this->selectedElem) {
auto sel = SelectionFactory::createFromElementOnActiveLayer(control, page, view, selectedElem);
this->view->getXournal()->deleteSelection(sel.release());
this->selectedElem = nullptr;
}
}
auto LatexController::loadRendered(string renderedTex) -> std::unique_ptr<TexImage> {
if (!this->isValidTex) {
return nullptr;
}
fs::path pdfPath = texTmpDir / "tex.pdf";
auto contents = Util::readString(pdfPath, true, std::ios::binary);
if (!contents) {
return nullptr;
}
auto img = std::make_unique<TexImage>();
GError* err{};
bool loaded = img->loadData(std::move(*contents), &err);
if (err != nullptr) {
string message = FS(_F("Could not load LaTeX PDF file: {1}") % err->message);
XojMsgBox::showErrorToUser(control->getGtkWindow(), message);
g_error_free(err);
return nullptr;
} else if (!loaded || !img->getPdf()) {
XojMsgBox::showErrorToUser(control->getGtkWindow(), FS(_F("Could not load LaTeX PDF file")));
return nullptr;
}
img->setX(posx);
img->setY(posy);
img->setText(std::move(renderedTex));
if (std::abs(imgheight) > 1024 * std::numeric_limits<double>::epsilon()) {
double ratio = img->getElementWidth() / img->getElementHeight();
if (ratio == 0) {
img->setWidth(imgwidth == 0 ? 10 : imgwidth);
} else {
img->setWidth(imgheight * ratio);
}
img->setHeight(imgheight);
}
return img;
}
void LatexController::insertTexImage() {
xoj_assert(this->isValidTex);
xoj_assert(this->temporaryRender != nullptr);
this->control->clearSelectionEndText();
this->deleteOldImage();
control->getUndoRedoHandler()->addUndoAction(
std::make_unique<InsertUndoAction>(page, layer, this->temporaryRender.get()));
// Select element
auto selection =
SelectionFactory::createFromFloatingElement(control, page, layer, view, std::move(this->temporaryRender));
view->getXournal()->setSelection(selection.release());
}
void LatexController::cancelEditing() {
// The original element is currently selected. This drops it back onto the page
this->control->clearSelectionEndText();
}
void LatexController::run(Control* ctrl) {
auto self = std::make_unique<LatexController>(ctrl);
auto depStatus = self->findTexDependencies();
if (!depStatus.success) {
XojMsgBox::showErrorToUser(ctrl->getGtkWindow(), depStatus.errorMsg);
return;
}
self->findSelectedTexElement();
showTexEditDialog(std::move(self));
}
| 14,206
|
C++
|
.cpp
| 305
| 40.222951
| 118
| 0.644931
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,452
|
UndoRedoController.cpp
|
xournalpp_xournalpp/src/core/control/UndoRedoController.cpp
|
#include "UndoRedoController.h"
#include <algorithm> // for copy, max
#include <cstddef> // for size_t
#include <iterator> // for back_insert_iterator, back_...
#include "control/tools/EditSelection.h" // for EditSelection
#include "gui/MainWindow.h" // for MainWindow
#include "gui/XournalView.h" // for XournalView
#include "model/Document.h" // for Document
#include "model/ElementInsertionPosition.h"
#include "model/Layer.h" // for Layer
#include "model/PageRef.h" // for PageRef
#include "model/XojPage.h" // for XojPage
#include "undo/UndoRedoHandler.h" // for UndoRedoHandler
#include "Control.h" // for Control
class XojPageView;
UndoRedoController::UndoRedoController(Control* control): control(control) {}
UndoRedoController::~UndoRedoController() = default;
void UndoRedoController::before() {
EditSelection* selection = control->getWindow()->getXournal()->getSelection();
if (selection != nullptr) {
layer = selection->getSourceLayer();
elements = selection->getElements();
}
control->clearSelectionEndText();
}
void UndoRedoController::after() {
// Restore selection, if any
if (layer == nullptr) {
// No layer - no selection
return;
}
Document* doc = control->getDocument();
PageRef page = control->getCurrentPage();
std::unique_lock lock(*doc);
size_t pageNo = doc->indexOf(page);
XojPageView* view = control->getWindow()->getXournal()->getViewFor(pageNo);
if (!view || !page) {
// The page may have been undone
return;
}
InsertionOrderRef remainingElements;
for (Element* e: elements) {
// Test, if the element has been removed since
if (auto pos = layer->indexOf(e); pos != -1) {
remainingElements.emplace_back(e, pos);
}
}
if (!remainingElements.empty()) {
auto removedElements = layer->removeElementsAt(remainingElements);
lock.unlock(); // Not needed anymore. For all other paths, the lock is released via ~unique_lock()
auto [sel, bounds] =
SelectionFactory::createFromFloatingElements(control, page, layer, view, std::move(removedElements));
control->getWindow()->getXournal()->setSelection(sel.release());
page->fireRangeChanged(bounds);
}
}
void UndoRedoController::undo(Control* control) {
UndoRedoController handler(control);
handler.before();
control->getUndoRedoHandler()->undo();
handler.after();
}
void UndoRedoController::redo(Control* control) {
UndoRedoController handler(control);
handler.before();
control->getUndoRedoHandler()->redo();
handler.after();
}
| 2,765
|
C++
|
.cpp
| 68
| 35.720588
| 117
| 0.665671
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,453
|
PdfCache.cpp
|
xournalpp_xournalpp/src/core/control/PdfCache.cpp
|
#include "PdfCache.h"
#include <algorithm> // for max
#include <cmath> // for ceil, abs
#include <cstdio> // for size_t
#include <memory> // for shared_ptr, __shared_ptr_access
#include <string> // for string
#include <utility> // for move
#include <glib.h> // for g_warning
#include "control/settings/Settings.h" // for Settings
#include "pdf/base/XojPdfDocument.h" // for XojPdfDocument
#include "util/Range.h" // for Range
#include "util/i18n.h" // for _
#include "util/safe_casts.h" // for as_unsigned
#include "view/Mask.h" // for Mask
class PdfCacheEntry {
public:
/**
* Cache [img], the result of rendering [popplerPage] with
* the given [zoom].
* A change in the document's zoom causes a change in the
* quality of the PDF backgrounds (zoomed in => need a higher
* quality rendering).
*
* @param popplerPage
* @param buffer is the result of rendering popplerPage
*/
PdfCacheEntry(XojPdfPageSPtr popplerPage, xoj::view::Mask&& buffer):
popplerPage(std::move(popplerPage)), buffer(std::forward<xoj::view::Mask>(buffer)) {}
~PdfCacheEntry() = default;
XojPdfPageSPtr popplerPage;
xoj::view::Mask buffer;
};
PdfCache::PdfCache(const XojPdfDocument& doc, Settings* settings): pdfDocument(doc) { updateSettings(settings); }
PdfCache::~PdfCache() = default;
void PdfCache::setRefreshThreshold(double threshold) { this->zoomRefreshThreshold = threshold; }
void PdfCache::setMaxSize(size_t newSize) {
this->maxSize = newSize;
if (this->data.size() > this->maxSize) {
this->data.resize(this->maxSize);
}
}
void PdfCache::updateSettings(Settings* settings) {
if (settings) {
setMaxSize(as_unsigned(settings->getPdfPageCacheSize()));
setRefreshThreshold(settings->getPDFPageRerenderThreshold());
}
}
auto PdfCache::lookup(size_t pdfPageNo) const -> const PdfCacheEntry* {
for (auto& e: this->data) {
if (static_cast<size_t>(e->popplerPage->getPageId()) == pdfPageNo) {
return e.get();
}
}
return nullptr;
}
auto PdfCache::cache(XojPdfPageSPtr popplerPage, xoj::view::Mask&& buffer) -> const PdfCacheEntry* {
if (this->data.size() > this->maxSize) {
this->data.resize(this->maxSize);
}
this->data.emplace_front(
std::make_unique<PdfCacheEntry>(std::move(popplerPage), std::forward<xoj::view::Mask>(buffer)));
return this->data.front().get();
}
void PdfCache::render(cairo_t* cr, size_t pdfPageNo, double zoom, double pageWidth, double pageHeight) {
std::lock_guard<std::mutex> lock(this->renderMutex);
const PdfCacheEntry* cacheResult = lookup(pdfPageNo);
bool needsRefresh = cacheResult == nullptr;
if (!needsRefresh) {
double averagedZoom = (zoom + cacheResult->buffer.getZoom()) / 2.0;
double percentZoomChange = std::abs(cacheResult->buffer.getZoom() - zoom) * 100.0 / averagedZoom;
// If we do have a cached result, is its rendering quality
// acceptable for our current zoom?
needsRefresh = (zoom > 1.0 && percentZoomChange > this->zoomRefreshThreshold);
}
if (needsRefresh) {
double renderZoom = std::max(zoom, 1.0);
auto popplerPage = cacheResult ? cacheResult->popplerPage : pdfDocument.getPage(pdfPageNo);
if (!popplerPage) {
g_warning("PdfCache::render Could not get the pdf page %zu from the document", pdfPageNo);
renderMissingPdfPage(cr, pageWidth, pageHeight);
return;
}
xoj::view::Mask buffer(cairo_get_target(cr), Range(0, 0, popplerPage->getWidth(), popplerPage->getHeight()),
renderZoom, CAIRO_CONTENT_COLOR_ALPHA);
popplerPage->render(buffer.get());
cacheResult = cache(popplerPage, std::move(buffer));
}
cacheResult->buffer.paintTo(cr);
}
void PdfCache::renderMissingPdfPage(cairo_t* cr, double pageWidth, double pageHeight) {
cairo_select_font_face(cr, "Sans", CAIRO_FONT_SLANT_NORMAL, CAIRO_FONT_WEIGHT_BOLD);
cairo_set_font_size(cr, 26);
cairo_set_source_rgb(cr, 0.8, 0.8, 0.8);
cairo_text_extents_t extents = {0};
std::string strMissing = _("PDF background missing");
cairo_text_extents(cr, strMissing.c_str(), &extents);
cairo_move_to(cr, pageWidth / 2 - extents.width / 2, pageHeight / 2 - extents.height / 2);
cairo_show_text(cr, strMissing.c_str());
}
| 4,520
|
C++
|
.cpp
| 99
| 40.070707
| 116
| 0.662947
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,454
|
CompassController.cpp
|
xournalpp_xournalpp/src/core/control/CompassController.cpp
|
#include "CompassController.h"
#include "control/Control.h"
#include "control/layer/LayerController.h"
#include "gui/XournalView.h"
#include "model/Compass.h"
#include "model/GeometryTool.h"
#include "model/Stroke.h"
#include "model/XojPage.h"
CompassController::CompassController(XojPageView* view, Compass* compass): GeometryToolController(view, compass) {}
CompassController::~CompassController() = default;
auto CompassController::getType() const -> GeometryToolType { return GeometryToolType::COMPASS; }
auto CompassController::posRelToSide(double x, double y) const -> xoj::util::Point<double> {
cairo_matrix_t inv = geometryTool->getMatrix();
cairo_matrix_invert(&inv);
cairo_matrix_transform_point(&inv, &x, &y);
return xoj::util::Point<double>(x, -y);
}
auto CompassController::isInsideGeometryTool(double x, double y, double border) const -> bool {
const xoj::util::Point<double> p = posRelToSide(x, y);
return std::hypot(p.x, p.y) <= geometryTool->getHeight() + border;
}
auto CompassController::getPointForAngle(double a) const -> xoj::util::Point<double> {
cairo_matrix_t matrix = geometryTool->getMatrix();
double x = geometryTool->getHeight() * std::cos(a);
double y = geometryTool->getHeight() * std::sin(a);
cairo_matrix_transform_point(&matrix, &x, &y);
return xoj::util::Point<double>(x, y);
}
auto CompassController::getPointForRadius(double r) const -> xoj::util::Point<double> {
cairo_matrix_t matrix = geometryTool->getMatrix();
double x = r;
double y = 0.;
cairo_matrix_transform_point(&matrix, &x, &y);
return xoj::util::Point<double>(x, y);
}
void CompassController::createOutlineStroke(double a) {
if (!std::isnan(a)) {
angleMax = a;
angleMin = a;
const xoj::util::Point<double> p = this->getPointForAngle(a);
initializeStroke();
stroke->addPoint(Point(p.x, p.y));
stroke->addPoint(Point(p.x, p.y)); // doubled point
geometryTool->notify();
} else {
g_warning("No valid stroke from compass!");
}
}
void CompassController::createRadialStroke(double x) {
if (!std::isnan(x)) {
radiusMax = x;
radiusMin = x;
const xoj::util::Point<double> p = posRelToSide(x, 0.);
initializeStroke();
stroke->addPoint(Point(p.x, p.y));
stroke->addPoint(Point(p.x, p.y)); // doubled point
geometryTool->notify();
} else {
g_warning("No valid radius from compass!");
}
}
void CompassController::updateOutlineStroke(double x) {
angleMax = std::max(this->angleMax, x);
angleMin = std::min(this->angleMin, x);
stroke->deletePointsFrom(0);
const auto h = view->getXournal()->getControl()->getToolHandler();
const bool filled = (h->getFill() != -1);
const xoj::util::Point<double> c =
xoj::util::Point<double>{geometryTool->getTranslationX(), geometryTool->getTranslationY()};
if (filled && angleMax < angleMin + 2 * M_PI) {
stroke->addPoint(Point(c.x, c.y));
}
for (auto i = 0; i <= 100; i++) {
const xoj::util::Point<double> p =
getPointForAngle(angleMin + static_cast<double>(i) / 100.0 * (angleMax - angleMin));
stroke->addPoint(Point(p.x, p.y));
}
if (filled && angleMax < angleMin + 2 * M_PI) {
stroke->addPoint(Point(c.x, c.y));
}
geometryTool->notify();
}
void CompassController::updateRadialStroke(double x) {
radiusMax = std::max(this->radiusMax, x);
radiusMin = std::min(this->radiusMin, x);
stroke->deletePointsFrom(0);
const xoj::util::Point<double> p1 = getPointForRadius(radiusMin);
const xoj::util::Point<double> p2 = getPointForRadius(radiusMax);
stroke->addPoint(Point(p1.x, p1.y));
stroke->addPoint(Point(p2.x, p2.y));
geometryTool->notify();
}
void CompassController::finalizeOutlineStroke() {
angleMax = std::numeric_limits<double>::lowest();
angleMin = std::numeric_limits<double>::max();
addStrokeToLayer();
}
void CompassController::finalizeRadialStroke() {
radiusMax = std::numeric_limits<double>::lowest();
radiusMin = std::numeric_limits<double>::max();
addStrokeToLayer();
}
auto CompassController::existsOutlineStroke() -> bool { return angleMax != std::numeric_limits<double>::lowest(); }
auto CompassController::existsRadialStroke() -> bool { return radiusMax != std::numeric_limits<double>::lowest(); }
| 4,443
|
C++
|
.cpp
| 104
| 37.817308
| 115
| 0.674311
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,455
|
TextAttribute.cpp
|
xournalpp_xournalpp/src/core/control/xml/TextAttribute.cpp
|
#include "TextAttribute.h"
#include <utility> // for move
#include "control/xml/Attribute.h" // for XMLAttribute
#include "util/OutputStream.h" // for OutputStream
#include "util/StringUtils.h" // for replace_pair, StringUtils
TextAttribute::TextAttribute(std::string name, std::string value):
XMLAttribute(std::move(name)), value(std::move(value)) {}
TextAttribute::~TextAttribute() = default;
void TextAttribute::writeOut(OutputStream* out) {
std::string v = this->value;
StringUtils::replaceAllChars(v, {
replace_pair('&', "&"),
replace_pair('\"', """),
replace_pair('<', "<"),
replace_pair('>', ">"),
replace_pair('\n', " "),
});
out->write(v);
}
| 964
|
C++
|
.cpp
| 19
| 34.947368
| 73
| 0.490426
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,456
|
SizeTAttribute.cpp
|
xournalpp_xournalpp/src/core/control/xml/SizeTAttribute.cpp
|
#include "SizeTAttribute.h"
#include <string> // for allocator, string
#include <glib.h> // for g_free, g_strdup_printf
#include "control/xml/Attribute.h" // for XMLAttribute
#include "util/OutputStream.h" // for OutputStream
SizeTAttribute::SizeTAttribute(const char* name, size_t value): XMLAttribute(name) { this->value = value; }
SizeTAttribute::~SizeTAttribute() = default;
void SizeTAttribute::writeOut(OutputStream* out) {
char* str = g_strdup_printf("%zu", value);
out->write(str);
g_free(str);
}
| 531
|
C++
|
.cpp
| 12
| 41.75
| 107
| 0.721248
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,457
|
XmlPointNode.cpp
|
xournalpp_xournalpp/src/core/control/xml/XmlPointNode.cpp
|
#include "XmlPointNode.h"
#include <algorithm> // for max
#include <utility> // for move
#include "control/xml/XmlAudioNode.h" // for XmlAudioNode
#include "util/OutputStream.h" // for OutputStream
#include "util/Util.h" // for writeCoordinateString
XmlPointNode::XmlPointNode(const char* tag): XmlAudioNode(tag) {}
void XmlPointNode::setPoints(std::vector<Point> pts) { this->points = std::move(pts); }
void XmlPointNode::writeOut(OutputStream* out) {
/** Write stroke and its attributes */
out->write("<");
out->write(tag);
writeAttributes(out);
out->write(">");
auto pointIter = points.begin();
Util::writeCoordinateString(out, pointIter->x, pointIter->y);
++pointIter;
for (; pointIter != points.end(); ++pointIter) {
out->write(" ");
Util::writeCoordinateString(out, pointIter->x, pointIter->y);
}
out->write("</");
out->write(tag);
out->write(">\n");
}
| 965
|
C++
|
.cpp
| 25
| 34.52
| 87
| 0.650913
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,458
|
DoubleAttribute.cpp
|
xournalpp_xournalpp/src/core/control/xml/DoubleAttribute.cpp
|
#include "DoubleAttribute.h"
#include <string> // for allocator, string
#include <glib.h> // for g_ascii_formatd, G_ASCII_DTOSTR_B...
#include "control/xml/Attribute.h" // for XMLAttribute
#include "util/OutputStream.h" // for OutputStream
#include "util/Util.h" // for PRECISION_FORMAT_STRING
DoubleAttribute::DoubleAttribute(const char* name, double value): XMLAttribute(name) { this->value = value; }
DoubleAttribute::~DoubleAttribute() = default;
void DoubleAttribute::writeOut(OutputStream* out) {
char str[G_ASCII_DTOSTR_BUF_SIZE];
// g_ascii_ version uses C locale always.
g_ascii_formatd(str, G_ASCII_DTOSTR_BUF_SIZE, Util::PRECISION_FORMAT_STRING, value);
out->write(str);
}
| 727
|
C++
|
.cpp
| 14
| 49.357143
| 109
| 0.722772
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,459
|
XmlNode.cpp
|
xournalpp_xournalpp/src/core/control/xml/XmlNode.cpp
|
#include "XmlNode.h"
#include <utility> // for move
#include <glib.h> // for g_free
#include "control/jobs/ProgressListener.h" // for ProgressListener
#include "control/xml/Attribute.h" // for XMLAttribute
#include "util/OutputStream.h" // for OutputStream
#include "DoubleArrayAttribute.h" // for DoubleArrayAttribute
#include "DoubleAttribute.h" // for DoubleAttribute
#include "IntAttribute.h" // for IntAttribute
#include "SizeTAttribute.h" // for SizeTAttribute
#include "TextAttribute.h" // for TextAttribute
XmlNode::XmlNode(const char* tag): tag(tag) {}
void XmlNode::setAttrib(const char* attrib, const char* value) {
if (value == nullptr) {
value = "";
}
putAttrib(new TextAttribute(attrib, value));
}
void XmlNode::setAttrib(const char* attrib, std::string value) {
putAttrib(new TextAttribute(attrib, std::move(value)));
}
void XmlNode::setAttrib(const char* attrib, double value) { putAttrib(new DoubleAttribute(attrib, value)); }
void XmlNode::setAttrib(const char* attrib, int value) { putAttrib(new IntAttribute(attrib, value)); }
void XmlNode::setAttrib(const char* attrib, size_t value) { putAttrib(new SizeTAttribute(attrib, value)); }
/**
* The double array is now owned by XmlNode and automatically deleted!
*/
void XmlNode::setAttrib(const char* attrib, std::vector<double> values) {
putAttrib(new DoubleArrayAttribute(attrib, std::move(values)));
}
void XmlNode::writeOut(OutputStream* out, ProgressListener* listener) {
out->write("<");
out->write(tag);
writeAttributes(out);
if (children.empty()) {
out->write("/>\n");
} else {
out->write(">\n");
if (listener) {
listener->setMaximumState(children.size());
}
size_t i = 1;
for (auto& node: children) {
node->writeOut(out);
if (listener) {
listener->setCurrentState(i);
}
i++;
}
out->write("</");
out->write(tag);
out->write(">\n");
}
}
void XmlNode::addChild(XmlNode* node) { children.emplace_back(node); }
void XmlNode::putAttrib(XMLAttribute* a) {
for (auto& attrib: attributes) {
if (attrib->getName() == a->getName()) {
attrib.reset(a);
return;
}
}
attributes.emplace_back(a);
}
void XmlNode::writeAttributes(OutputStream* out) {
for (auto& attrib: attributes) {
out->write(" ");
out->write(attrib->getName());
out->write("=\"");
attrib->writeOut(out);
out->write("\"");
}
}
| 2,642
|
C++
|
.cpp
| 73
| 30.643836
| 108
| 0.631331
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,460
|
XmlTexNode.cpp
|
xournalpp_xournalpp/src/core/control/xml/XmlTexNode.cpp
|
#include "XmlTexNode.h"
#include <glib.h> // for g_base64_encode, g_free, gchar, guchar
#include "control/xml/XmlNode.h" // for XmlNode
#include "util/OutputStream.h" // for OutputStream
XmlTexNode::XmlTexNode(const char* tag, std::string&& binaryData): XmlNode(tag), binaryData(binaryData) {}
XmlTexNode::~XmlTexNode() = default;
void XmlTexNode::writeOut(OutputStream* out) {
out->write("<");
out->write(tag);
writeAttributes(out);
out->write(">");
gchar* base64_str =
g_base64_encode(reinterpret_cast<const guchar*>(this->binaryData.c_str()), this->binaryData.length());
out->write(base64_str);
g_free(base64_str);
out->write("</");
out->write(tag);
out->write(">\n");
}
| 739
|
C++
|
.cpp
| 19
| 34.736842
| 114
| 0.668539
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,461
|
XmlTextNode.cpp
|
xournalpp_xournalpp/src/core/control/xml/XmlTextNode.cpp
|
#include "XmlTextNode.h"
#include <utility> // for move
#include "control/xml/XmlAudioNode.h" // for XmlAudioNode
#include "util/OutputStream.h" // for OutputStream
#include "util/StringUtils.h" // for replace_pair, StringUtils
XmlTextNode::XmlTextNode(const char* tag, std::string text): XmlAudioNode(tag), text(std::move(text)) {}
XmlTextNode::XmlTextNode(const char* tag): XmlAudioNode(tag) {}
void XmlTextNode::setText(std::string text) { this->text = std::move(text); }
void XmlTextNode::writeOut(OutputStream* out) {
out->write("<");
out->write(tag);
writeAttributes(out);
out->write(">");
std::string tmp(this->text);
StringUtils::replaceAllChars(tmp,
{replace_pair('&', "&"), replace_pair('<', "<"), replace_pair('>', ">")});
out->write(tmp);
out->write("</");
out->write(tag);
out->write(">\n");
}
| 918
|
C++
|
.cpp
| 21
| 38.809524
| 117
| 0.634009
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,462
|
XmlImageNode.cpp
|
xournalpp_xournalpp/src/core/control/xml/XmlImageNode.cpp
|
#include "XmlImageNode.h"
#include <glib.h> // for g_base64_encode, g_free, gchar, g_e...
#include "control/xml/XmlNode.h" // for XmlNode
#include "util/OutputStream.h" // for OutputStream
XmlImageNode::XmlImageNode(const char* tag): XmlNode(tag) {
this->img = nullptr;
this->out = nullptr;
this->pos = 0;
}
XmlImageNode::~XmlImageNode() {
if (this->img) {
cairo_surface_destroy(this->img);
}
}
void XmlImageNode::setImage(cairo_surface_t* img) {
if (this->img) {
cairo_surface_destroy(this->img);
}
this->img = cairo_surface_reference(img);
}
auto XmlImageNode::pngWriteFunction(XmlImageNode* image, const unsigned char* data, unsigned int length)
-> cairo_status_t {
for (unsigned int i = 0; i < length; i++, image->pos++) {
if (image->pos == 30) {
gchar* base64_str = g_base64_encode(image->buffer, image->pos);
image->out->write(base64_str);
g_free(base64_str);
image->pos = 0;
}
image->buffer[image->pos] = data[i];
}
return CAIRO_STATUS_SUCCESS;
}
void XmlImageNode::writeOut(OutputStream* out) {
out->write("<");
out->write(tag);
writeAttributes(out);
out->write(">");
if (this->img == nullptr) {
g_error("XmlImageNode::writeOut(); this->img == nullptr");
} else {
this->out = out;
this->pos = 0;
cairo_surface_write_to_png_stream(this->img, reinterpret_cast<cairo_write_func_t>(&pngWriteFunction), this);
gchar* base64_str = g_base64_encode(this->buffer, this->pos);
out->write(base64_str);
g_free(base64_str);
this->out = nullptr;
}
out->write("</");
out->write(tag);
out->write(">\n");
}
| 1,759
|
C++
|
.cpp
| 53
| 27.358491
| 116
| 0.606257
|
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,463
|
XmlAudioNode.cpp
|
xournalpp_xournalpp/src/core/control/xml/XmlAudioNode.cpp
|
#include "XmlAudioNode.h"
#include <utility> // for move
#include "control/xml/XmlNode.h" // for XmlNode
XmlAudioNode::XmlAudioNode(const char* tag): XmlNode(tag), audioFilepath{} {}
XmlAudioNode::~XmlAudioNode() = default;
auto XmlAudioNode::getAudioFilepath() -> fs::path { return this->audioFilepath; }
void XmlAudioNode::setAudioFilepath(fs::path filepath) { this->audioFilepath = std::move(filepath); }
| 416
|
C++
|
.cpp
| 7
| 57.571429
| 101
| 0.756824
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,464
|
DoubleArrayAttribute.cpp
|
xournalpp_xournalpp/src/core/control/xml/DoubleArrayAttribute.cpp
|
#include "DoubleArrayAttribute.h"
#include <algorithm> // for for_each
#include <iterator> // for begin, end
#include <string> // for allocator, string
#include <utility> // for move
#include <glib.h> // for g_ascii_formatd, G_ASCII_DTOSTR_B...
#include "control/xml/Attribute.h" // for XMLAttribute
#include "util/OutputStream.h" // for OutputStream
#include "util/Util.h" // for PRECISION_FORMAT_STRING
DoubleArrayAttribute::DoubleArrayAttribute(const char* name, std::vector<double>&& values):
XMLAttribute(name), values(std::move(values)) {}
DoubleArrayAttribute::~DoubleArrayAttribute() = default;
void DoubleArrayAttribute::writeOut(OutputStream* out) {
if (!this->values.empty()) {
char str[G_ASCII_DTOSTR_BUF_SIZE];
// g_ascii_ version uses C locale always.
g_ascii_formatd(str, G_ASCII_DTOSTR_BUF_SIZE, Util::PRECISION_FORMAT_STRING, this->values[0]);
out->write(str);
std::for_each(std::begin(this->values) + 1, std::end(this->values), [&](auto& x) {
g_ascii_formatd(str, G_ASCII_DTOSTR_BUF_SIZE, Util::PRECISION_FORMAT_STRING, x);
out->write(" ");
out->write(str);
});
}
}
| 1,221
|
C++
|
.cpp
| 25
| 43.56
| 102
| 0.657696
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,465
|
IntAttribute.cpp
|
xournalpp_xournalpp/src/core/control/xml/IntAttribute.cpp
|
#include "IntAttribute.h"
#include <string> // for allocator, string
#include <glib.h> // for g_free, g_strdup_printf
#include "control/xml/Attribute.h" // for XMLAttribute
#include "util/OutputStream.h" // for OutputStream
IntAttribute::IntAttribute(const char* name, int value): XMLAttribute(name) { this->value = value; }
IntAttribute::~IntAttribute() = default;
void IntAttribute::writeOut(OutputStream* out) {
char* str = g_strdup_printf("%i", value);
out->write(str);
g_free(str);
}
| 515
|
C++
|
.cpp
| 12
| 40.416667
| 100
| 0.714286
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,466
|
Attribute.cpp
|
xournalpp_xournalpp/src/core/control/xml/Attribute.cpp
|
#include "Attribute.h"
#include <utility>
XMLAttribute::XMLAttribute(std::string name): name(std::move(name)) {}
XMLAttribute::~XMLAttribute() = default;
auto XMLAttribute::getName() -> std::string { return name; }
| 219
|
C++
|
.cpp
| 5
| 42
| 70
| 0.742857
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,467
|
LatexGenerator.cpp
|
xournalpp_xournalpp/src/core/control/latex/LatexGenerator.cpp
|
#include "LatexGenerator.h"
#include <regex> // for smatch, sregex_iterator
#include <sstream> // for ostringstream
#include <string_view> // for string_view
#include <glib.h> // for GError, gchar, g_error_free
#include <poppler.h> // for g_object_unref
#include "control/settings/LatexSettings.h" // for LatexSettings
#include "util/PathUtil.h" // for getLongPath
#include "util/PlaceholderString.h" // for PlaceholderString
#include "util/Util.h" // for Util
#include "util/i18n.h" // for FS, _F
#include "util/raii/GLibGuards.h" // for GErrorGuard, GStrvGuard
#include "util/raii/GObjectSPtr.h" // for GObjectSptr
#include "util/safe_casts.h" // for as_signed
using namespace xoj::util;
LatexGenerator::LatexGenerator(const LatexSettings& settings): settings(settings) {}
auto LatexGenerator::templateSub(const std::string& input, const std::string& templ, const Color textColor)
-> std::string {
const static std::regex substRe("%%XPP_((TOOL_INPUT)|(TEXT_COLOR))%%");
std::string output;
output.reserve(templ.length());
size_t templatePos = 0;
for (std::sregex_iterator it(templ.begin(), templ.end(), substRe); it != std::sregex_iterator{}; it++) {
std::smatch match = *it;
std::string matchStr = match[1];
std::string repl;
// Performance can be optimized here by precomputing hashes
if (matchStr == "TOOL_INPUT") {
repl = input;
} else if (matchStr == "TEXT_COLOR") {
repl = Util::rgb_to_hex_string(textColor).substr(1);
}
output.append(templ, templatePos, as_unsigned(match.position()) - templatePos);
output.append(repl);
templatePos = as_unsigned(match.position() + match.length());
}
output.append(templ, templatePos);
return output;
}
auto LatexGenerator::asyncRun(const fs::path& texDir, const std::string& texFileContents) -> Result {
std::string cmd = this->settings.genCmd;
GErrorGuard err{};
std::string texFilePathOSEncoding;
try {
texFilePathOSEncoding = (Util::getLongPath(texDir) / "tex.tex").string();
} catch (const fs::filesystem_error& e) {
GenError res{FS(_F("Failed to parse LaTeX generator path: {1}") % e.what())};
}
for (auto i = cmd.find(u8"{}"); i != std::string::npos; i = cmd.find(u8"{}", i + texFilePathOSEncoding.length())) {
cmd.replace(i, 2, texFilePathOSEncoding);
}
// Todo (rolandlo): is this a todo?
// Windows note: g_shell_parse_argv assumes POSIX paths, so Windows paths need to be escaped.
GStrvGuard argv{};
if (!g_shell_parse_argv(cmd.c_str(), nullptr, out_ptr(argv), out_ptr(err))) {
return GenError{FS(_F("Failed to parse LaTeX generator command: {1}") % err->message)};
}
gchar* prog = argv.get()[0];
if (!prog || !(prog = g_find_program_in_path(prog))) {
if (Util::isFlatpakInstallation()) {
return GenError{
FS(_F("Failed to find LaTeX generator program in PATH: {1}\n\nSince installation is detected "
"within Flatpak, you need to install the Flatpak freedesktop Tex Live extension. For "
"example, by running:\n\n$ flatpak install flathub org.freedesktop.Sdk.Extension.texlive") %
argv.get()[0])};
} else {
return GenError{FS(_F("Failed to find LaTeX generator program in PATH: {1}") % argv.get()[0])};
}
}
g_free(argv.get()[0]);
argv.get()[0] = prog;
if (!g_file_set_contents(texFilePathOSEncoding.c_str(), texFileContents.c_str(), as_signed(texFileContents.size()),
out_ptr(err))) {
return GenError({FS(_F("Could not save .tex file: {1}") % err->message)});
}
auto flags = static_cast<GSubprocessFlags>(G_SUBPROCESS_FLAGS_STDOUT_PIPE | G_SUBPROCESS_FLAGS_STDERR_MERGE);
xoj::util::GObjectSPtr<GSubprocessLauncher> launcher(g_subprocess_launcher_new(flags), xoj::util::adopt);
g_subprocess_launcher_set_cwd(launcher.get(), texDir.u8string().c_str());
auto* proc = g_subprocess_launcher_spawnv(launcher.get(), argv.get(), out_ptr(err));
if (proc) {
return {proc};
}
std::ostringstream ss;
for (char** iter = argv.get(); iter != nullptr && *iter != nullptr; ++iter) {
ss << std::string_view(*iter) << ", ";
}
return GenError({FS(_F("Could not start {1}: {2} (exit code: {3})") % ss.str() % err->message % err->code)});
}
| 4,605
|
C++
|
.cpp
| 88
| 45.602273
| 119
| 0.622198
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,468
|
ArrowHandler.cpp
|
xournalpp_xournalpp/src/core/control/tools/ArrowHandler.cpp
|
#include "ArrowHandler.h"
#include <algorithm> // for minmax_element
#include <cmath> // for cos, sin, atan2, M_PI
#include "control/Control.h" // for Control
#include "control/ToolHandler.h" // for ToolHandler
#include "control/tools/BaseShapeHandler.h" // for BaseShapeHandler
#include "control/tools/SnapToGridInputHandler.h" // for SnapToGridInputHan...
#include "gui/inputdevices/PositionInputData.h" // for PositionInputData
#include "model/Point.h" // for Point
#include "util/Range.h" // for Range
ArrowHandler::ArrowHandler(Control* control, const PageRef& page, bool doubleEnded):
BaseShapeHandler(control, page), doubleEnded(doubleEnded) {}
ArrowHandler::~ArrowHandler() = default;
auto ArrowHandler::createShape(bool isAltDown, bool isShiftDown, bool isControlDown)
-> std::pair<std::vector<Point>, Range> {
Point c = snappingHandler.snap(this->currPoint, this->startPoint, isAltDown);
const double lineLength = std::hypot(c.x - this->startPoint.x, c.y - this->startPoint.y);
const double thickness = control->getToolHandler()->getThickness();
const double slimness = lineLength / thickness;
// We've now computed the line points for the arrow
// so we just have to build the head:
// arrowDist is the distance between the line's and the arrow's tips
// delta is the angle between each arrow leg and the line
// an appropriate opening angle 2*delta is Pi/3 radians for an arrow shape
double delta = M_PI / 6.0;
// We use different slimness regimes for proper sizing:
const double THICK1 = 7, THICK3 = 1.6;
const double LENGTH2 = 0.4, LENGTH4 = (doubleEnded ? 0.5 : 0.8);
// set up the size of the arrow head to be THICK1 x the thickness of the line
double arrowDist = thickness * THICK1;
// but not too large compared to the line length
if (slimness >= THICK1 / LENGTH2) {
// arrow head is not too long compared to the line length (regime 1)
} else if (slimness >= THICK3 / LENGTH2) {
// arrow head is not too short compared to the thickness (regime 2)
arrowDist = lineLength * LENGTH2;
} else if (slimness >= THICK3 / LENGTH4) {
// arrow head is not too thick compared to the line length (regime 3)
arrowDist = thickness * THICK3;
// help visibility by widening the angle
delta = (1 + (slimness - THICK3 / LENGTH2) / (THICK3 / LENGTH4 - THICK3 / LENGTH2)) * M_PI / 6.0;
// which allows to shorten the tips and keep the horizonzal distance
arrowDist *= sin(M_PI / 6.0) / sin(delta);
} else {
// shrinking down gracefully (regime 4)
arrowDist = lineLength * LENGTH4;
delta = M_PI / 3.0;
arrowDist *= sin(M_PI / 6.0) / sin(M_PI / 3.0);
}
const double angle = atan2(c.y - this->startPoint.y, c.x - this->startPoint.x);
std::pair<std::vector<Point>, Range> res; // members initialised below
std::vector<Point>& shape = res.first;
shape.reserve(doubleEnded ? 10 : 6);
shape.emplace_back(this->startPoint);
if (doubleEnded) {
shape.emplace_back(startPoint.x + arrowDist * cos(angle + delta),
startPoint.y + arrowDist * sin(angle + delta));
shape.emplace_back(startPoint);
shape.emplace_back(startPoint.x + arrowDist * cos(angle - delta),
startPoint.y + arrowDist * sin(angle - delta));
shape.emplace_back(startPoint);
}
shape.emplace_back(c);
shape.emplace_back(c.x - arrowDist * cos(angle + delta), c.y - arrowDist * sin(angle + delta));
shape.emplace_back(c);
shape.emplace_back(c.x - arrowDist * cos(angle - delta), c.y - arrowDist * sin(angle - delta));
shape.emplace_back(c);
auto [minX, maxX] = std::minmax_element(shape.begin(), shape.end(), [](auto& p, auto& q) { return p.x < q.x; });
auto [minY, maxY] = std::minmax_element(shape.begin(), shape.end(), [](auto& p, auto& q) { return p.y < q.y; });
res.second = Range(minX->x, minY->y, maxX->x, maxY->y);
return res;
}
| 4,163
|
C++
|
.cpp
| 72
| 51.694444
| 116
| 0.646712
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,469
|
EllipseHandler.cpp
|
xournalpp_xournalpp/src/core/control/tools/EllipseHandler.cpp
|
#include "EllipseHandler.h"
#include <algorithm> // for max
#include <cmath> // for abs, pow, M_PI, cos
#include "control/Control.h" // for Control
#include "control/settings/Settings.h" // for Settings
#include "control/tools/BaseShapeHandler.h" // for BaseShapeHandler
#include "control/tools/SnapToGridInputHandler.h" // for SnapToGridInputHan...
#include "model/Point.h" // for Point
#include "util/Assert.h"
EllipseHandler::EllipseHandler(Control* control, const PageRef& page, bool flipShift, bool flipControl):
BaseShapeHandler(control, page, flipShift, flipControl) {}
EllipseHandler::~EllipseHandler() = default;
auto EllipseHandler::createShape(bool isAltDown, bool isShiftDown, bool isControlDown)
-> std::pair<std::vector<Point>, Range> {
/**
* Snap point to grid (if enabled - Alt key pressed will toggle)
*/
Point c = snappingHandler.snapToGrid(this->currPoint, isAltDown);
double width = c.x - this->startPoint.x;
double height = c.y - this->startPoint.y;
this->modShift = isShiftDown;
this->modControl = isControlDown;
Settings* settings = control->getSettings();
if (settings->getDrawDirModsEnabled()) {
// change modifiers based on draw dir
this->modifyModifiersByDrawDir(width, height, true);
}
if (this->modShift) {
// make circle
width = (this->modControl) ? std::hypot(width, height) :
std::copysign(std::max(std::abs(width), std::abs(height)), width);
height = std::copysign(width, height);
}
double radiusX = 0;
double radiusY = 0;
double center_x = 0;
double center_y = 0;
if (!this->modControl) {
radiusX = 0.5 * width;
radiusY = 0.5 * height;
center_x = this->startPoint.x + radiusX;
center_y = this->startPoint.y + radiusY;
} else {
// control key down, draw centered at cursor
radiusX = width;
radiusY = height;
center_x = this->startPoint.x;
center_y = this->startPoint.y;
}
/*
* Set resolution depending on the radius (heuristic)
*/
auto nbPtsPerQuadrant =
static_cast<unsigned int>(std::ceil(5 + 0.3 * (std::abs(radiusX) + std::abs(radiusY))));
const double stepAngle = M_PI_2 / nbPtsPerQuadrant;
std::pair<std::vector<Point>, Range> res;
std::vector<Point>& shape = res.first;
/*
* This call to reserve() makes the calls to std::transform() below safe.
* DO NOT REMOVE
* NB: the +1 is necessary to add a copy of the first point and close the ellipse.
*/
shape.reserve(4 * nbPtsPerQuadrant + 1);
shape.emplace_back(center_x + radiusX, center_y);
for (unsigned int j = 1U; j < nbPtsPerQuadrant; j++) {
const double tgtAngle = stepAngle * j;
const double centerAngle = 0.25 * (std::atan2(std::abs(radiusY) * std::sin(tgtAngle), std::abs(radiusX) * std::cos(tgtAngle))) + 0.75 * tgtAngle;
double xp = center_x + radiusX * std::cos(centerAngle);
double yp = center_y + radiusY * std::sin(centerAngle);
shape.emplace_back(xp, yp);
}
shape.emplace_back(center_x, center_y + radiusY);
// The following std::transform() are only safe because no reallocations will happen (see reserve() above).
// Symmetry for second quadrant
xoj_assert(shape.capacity() >= 2 * shape.size() - 1);
std::transform(std::next(shape.rbegin()), shape.rend(), std::back_inserter(shape),
[&](const Point& p) { return Point(2 * center_x - p.x, p.y); });
// Symmetry for the second half
xoj_assert(shape.capacity() >= 2 * shape.size() - 1);
std::transform(std::next(shape.rbegin()), shape.rend(), std::back_inserter(shape),
[&](const Point& p) { return Point(p.x, 2 * center_y - p.y); });
Range rg(center_x + radiusX, center_y + radiusY);
rg.addPoint(center_x - radiusX, center_y - radiusY);
res.second = rg;
return res;
}
| 4,069
|
C++
|
.cpp
| 86
| 40.790698
| 153
| 0.630583
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,470
|
PdfElemSelection.cpp
|
xournalpp_xournalpp/src/core/control/tools/PdfElemSelection.cpp
|
#include "PdfElemSelection.h"
#include <algorithm> // for max, min
#include <limits> // for numeric_limits
#include <memory> // for __shared_ptr_access
#include <utility> // for move
#include <cairo.h> // for cairo_line_to, cairo_region_destroy
#include <gdk/gdk.h> // for GdkRGBA, gdk_cairo_set_source_rgba
#include "control/Control.h" // for Control
#include "control/ToolHandler.h" // for ToolHandler
#include "gui/PageView.h" // for XojPageView
#include "gui/XournalView.h" // for XournalView
#include "model/Document.h" // for Document
#include "model/PageRef.h" // for PageRef
#include "model/XojPage.h" // for XojPage
#include "pdf/base/XojPdfPage.h" // for XojPdfRectangle, XojPdfPageSelectio...
#include "util/Assert.h" // for xoj_assert
#include "util/safe_casts.h" // for strict_cast, as_signed, as_si...
#include "view/overlays/PdfElementSelectionView.h"
PdfElemSelection::PdfElemSelection(double x, double y, Control* control):
pdf(nullptr),
bounds({x, y, x, y}),
finalized(false),
viewPool(std::make_shared<xoj::util::DispatchPool<xoj::view::PdfElementSelectionView>>()) {
if (auto pNr = control->getCurrentPage()->getPdfPageNr(); pNr != npos) {
Document* doc = control->getDocument();
doc->lock();
this->pdf = doc->getPdfPage(pNr);
doc->unlock();
this->selectionPageNr = pNr;
}
this->toolType = control->getToolHandler()->getToolType();
}
PdfElemSelection::~PdfElemSelection() {
Range rg = getRegionBbox();
this->viewPool->dispatchAndClear(xoj::view::PdfElementSelectionView::CANCEL_SELECTION_REQUEST, rg);
}
auto PdfElemSelection::finalizeSelectionAndRepaint(XojPdfPageSelectionStyle style) -> bool {
Range rg = getRegionBbox();
bool result = this->finalizeSelection(style);
rg = rg.unite(getRegionBbox());
if (!rg.empty()) {
this->viewPool->dispatch(xoj::view::PdfElementSelectionView::FLAG_DIRTY_REGION_REQUEST, rg);
}
return result;
}
bool PdfElemSelection::finalizeSelection(XojPdfPageSelectionStyle style) {
this->finalized = true;
XojPdfPage::TextSelection selection = this->pdf->selectTextLines(this->bounds, style);
this->selectedTextRegion = std::move(selection.region);
this->selectedTextRects = std::move(selection.rects);
this->selectedText = this->pdf->selectText(this->bounds, style);
return !this->selectedTextRects.empty();
}
XojPdfPageSelectionStyle PdfElemSelection::selectionStyleForToolType(ToolType type) {
switch (type) {
case ToolType::TOOL_SELECT_PDF_TEXT_RECT:
return XojPdfPageSelectionStyle::Area;
default:
return XojPdfPageSelectionStyle::Linear;
}
}
Range PdfElemSelection::getRegionBbox() const {
if (this->selectedTextRegion && cairo_region_num_rectangles(this->selectedTextRegion.get()) > 0) {
cairo_rectangle_int_t bbox{};
cairo_region_get_extents(this->selectedTextRegion.get(), &bbox);
return Range(bbox.x, bbox.y, bbox.x + bbox.width, bbox.y + bbox.height);
}
return Range(); // empty range
}
void PdfElemSelection::currentPos(double x, double y, XojPdfPageSelectionStyle style) {
if (!this->pdf) {
return;
}
// Update the end position
this->bounds.x2 = x;
this->bounds.y2 = y;
Range rg = getRegionBbox();
// Repaint the selected text area
switch (style) {
case XojPdfPageSelectionStyle::Linear:
case XojPdfPageSelectionStyle::Word:
case XojPdfPageSelectionStyle::Line:
this->selectedTextRegion.reset(this->pdf->selectTextRegion(this->bounds, style), xoj::util::adopt);
break;
case XojPdfPageSelectionStyle::Area: {
cairo_rectangle_int_t rect;
rect.x = floor_cast<int>(std::min(bounds.x1, bounds.x2));
rect.width = ceil_cast<int>(std::max(bounds.x1, bounds.x2)) - rect.x;
rect.y = floor_cast<int>(std::min(bounds.y1, bounds.y2));
rect.height = ceil_cast<int>(std::max(bounds.y1, bounds.y2)) - rect.y;
this->selectedTextRegion.reset(cairo_region_create_rectangle(&rect), xoj::util::adopt);
} break;
default:
xoj_assert_message(false, "Unreachable");
}
xoj_assert(this->selectedTextRegion);
rg = rg.unite(getRegionBbox());
if (!rg.empty()) {
this->viewPool->dispatch(xoj::view::PdfElementSelectionView::FLAG_DIRTY_REGION_REQUEST, rg);
}
}
auto PdfElemSelection::contains(double x, double y) -> bool {
if (!this->selectedTextRegion) {
return false;
}
return cairo_region_contains_point(this->selectedTextRegion.get(), static_cast<int>(x), static_cast<int>(y));
}
auto PdfElemSelection::getSelectedTextRects() const -> const std::vector<XojPdfRectangle>& { return selectedTextRects; }
auto PdfElemSelection::getSelectedText() const -> const std::string& { return this->selectedText; }
auto PdfElemSelection::getSelectionPageNr() const -> size_t { return selectionPageNr; }
auto PdfElemSelection::isFinalized() const -> bool { return this->finalized; }
void PdfElemSelection::setToolType(ToolType tType) { this->toolType = tType; }
| 5,244
|
C++
|
.cpp
| 112
| 41.357143
| 120
| 0.687353
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,471
|
InputHandler.cpp
|
xournalpp_xournalpp/src/core/control/tools/InputHandler.cpp
|
#include "InputHandler.h"
#include <cmath> // for hypot
#include <cstddef> // for size_t
#include <glib.h> // for g_get_monotonic_time
#include "control/AudioController.h" // for AudioController
#include "control/Control.h" // for Control
#include "control/ToolEnums.h" // for TOOL_ERASER, TOOL_HIGHLIGHTER
#include "control/ToolHandler.h" // for ToolHandler
#include "model/Point.h" // for Point, Point::NO_PRESSURE
#include "model/Stroke.h" // for Stroke, StrokeTool::ERASER, STR...
#include "util/Color.h" // for Color
#include "util/safe_casts.h" // for as_unsigned
#include "filesystem.h" // for path
InputHandler::InputHandler(Control* control, const PageRef& page): control(control), page(page) {}
InputHandler::~InputHandler() = default;
auto InputHandler::getStroke() const -> Stroke* { return stroke.get(); }
auto InputHandler::createStroke(Control* control) -> std::unique_ptr<Stroke> {
ToolHandler* h = control->getToolHandler();
auto s = std::make_unique<Stroke>();
s->setWidth(h->getThickness());
s->setColor(h->getColor());
s->setFill(h->getFill());
s->setLineStyle(h->getLineStyle());
if (h->getToolType() == TOOL_PEN) {
s->setToolType(StrokeTool::PEN);
if (auto* audioController = control->getAudioController(); audioController && audioController->isRecording()) {
fs::path audioFilename = audioController->getAudioFilename();
size_t sttime = audioController->getStartTime();
size_t milliseconds = (as_unsigned(g_get_monotonic_time() / 1000) - sttime);
s->setTimestamp(milliseconds);
s->setAudioFilename(audioFilename);
}
} else if (h->getToolType() == TOOL_HIGHLIGHTER) {
s->setToolType(StrokeTool::HIGHLIGHTER);
} else if (h->getToolType() == TOOL_ERASER) {
s->setToolType(StrokeTool::ERASER);
s->setColor(Colors::white);
}
return s;
}
auto InputHandler::validMotion(Point p, Point q) -> bool {
return std::hypot(p.x - q.x, p.y - q.y) >= PIXEL_MOTION_THRESHOLD;
}
| 2,128
|
C++
|
.cpp
| 43
| 44.55814
| 119
| 0.655888
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,472
|
Selection.cpp
|
xournalpp_xournalpp/src/core/control/tools/Selection.cpp
|
#include "Selection.h"
#include <algorithm> // for max, min
#include <cmath> // for abs, NAN
#include <memory> // for __shared_ptr_access
#include <gdk/gdk.h> // for GdkRGBA, gdk_cairo_set_source_rgba
#include "gui/LegacyRedrawable.h" // for Redrawable
#include "model/Document.h" // for Document
#include "model/Layer.h" // for Layer
#include "model/XojPage.h" // for XojPage
#include "util/safe_casts.h" // for as_unsigned
Selection::Selection(bool multiLayer): multiLayer(multiLayer), viewPool(std::make_shared<xoj::util::DispatchPool<xoj::view::SelectionView>>()) {
}
Selection::~Selection() = default;
auto Selection::finalize(PageRef page, bool disableMultilayer, Document* doc) -> size_t {
this->page = page;
size_t layerId = 0;
if (multiLayer && !disableMultilayer) {
std::lock_guard lock(*doc);
for (auto it = page->getLayers()->rbegin(); it != page->getLayers()->rend(); it++) {
Layer* l = *it;
if (!l->isVisible()) {
continue;
}
bool selectionOnLayer = false;
Element::Index pos = 0;
for (auto&& e: l->getElements()) {
if (e->isInSelection(this)) {
this->selectedElements.emplace_back(e.get(), pos);
selectionOnLayer = true;
}
pos++;
}
if (selectionOnLayer) {
layerId = page->getLayers()->size() - as_unsigned(std::distance(page->getLayers()->rbegin(), it));
break;
}
}
} else {
std::lock_guard lock(*doc);
Layer* l = page->getSelectedLayer();
Element::Index pos = 0;
for (auto&& e: l->getElements()) {
if (e->isInSelection(this)) {
this->selectedElements.emplace_back(e.get(), pos);
layerId = page->getSelectedLayerId();
}
pos++;
}
}
this->viewPool->dispatchAndClear(xoj::view::SelectionView::DELETE_VIEWS_REQUEST, this->bbox);
return layerId;
}
auto Selection::isMultiLayerSelection() -> bool {
return this->multiLayer;
}
auto Selection::releaseElements() -> InsertionOrderRef { return std::move(this->selectedElements); }
//////////////////////////////////////////////////////////
RectSelection::RectSelection(double x, double y, bool multiLayer): Selection(multiLayer), sx(x), sy(y), ex(x), ey(y) {
bbox.addPoint(x, y);
}
RectSelection::~RectSelection() = default;
auto RectSelection::contains(double x, double y) const -> bool { return bbox.contains(x, y); }
void RectSelection::currentPos(double x, double y) {
bbox = Range(sx, sy);
bbox.addPoint(x, y);
Range rg = bbox;
rg.addPoint(ex, ey); // in case the selection is shrinking
this->ex = x;
this->ey = y;
boundaryPoints = {{sx, sy}, {sx, ey}, {ex, ey}, {ex, sy}};
this->viewPool->dispatch(xoj::view::SelectionView::FLAG_DIRTY_REGION, rg);
this->maxDist = std::max({this->maxDist, x - this->sx, this->sx - x, y - this->sy, this->sy - y});
}
auto RectSelection::userTapped(double zoom) const -> bool { return this->maxDist < 10 / zoom; }
auto RectSelection::getBoundary() const -> const std::vector<BoundaryPoint>& { return boundaryPoints; }
//////////////////////////////////////////////////////////
RegionSelect::RegionSelect(double x, double y, bool multiLayer): Selection(multiLayer) {
currentPos(x, y);
}
void RegionSelect::currentPos(double x, double y) {
boundaryPoints.emplace_back(x, y);
bbox.addPoint(x, y);
// at least three points needed
if (boundaryPoints.size() >= 3) {
Range rg(x, y);
const BoundaryPoint& penultimatePoint = boundaryPoints[boundaryPoints.size() - 2];
rg.addPoint(penultimatePoint.x, penultimatePoint.y);
// rg contains the added segment
// add the first point to make sure the filling is painted correctly
rg.addPoint(boundaryPoints.front().x, boundaryPoints.front().y);
this->viewPool->dispatch(xoj::view::SelectionView::FLAG_DIRTY_REGION, rg);
}
}
auto RegionSelect::contains(double x, double y) const -> bool {
if (boundaryPoints.size() <= 2 || !this->bbox.contains(x, y)) {
return false;
}
int hits = 0;
const BoundaryPoint& last = boundaryPoints.back();
double lastx = last.x;
double lasty = last.y;
double curx = NAN, cury = NAN;
// Walk the edges of the polygon
for (auto pointIterator = boundaryPoints.begin(); pointIterator != boundaryPoints.end();
lastx = curx, lasty = cury, ++pointIterator) {
curx = pointIterator->x;
cury = pointIterator->y;
if (cury == lasty) {
continue;
}
int leftx = 0;
if (curx < lastx) {
if (x >= lastx) {
continue;
}
leftx = static_cast<int>(curx);
} else {
if (x >= curx) {
continue;
}
leftx = static_cast<int>(lastx);
}
double test1 = NAN, test2 = NAN;
if (cury < lasty) {
if (y < cury || y >= lasty) {
continue;
}
if (x < leftx) {
hits++;
continue;
}
test1 = x - curx;
test2 = y - cury;
} else {
if (y < lasty || y >= cury) {
continue;
}
if (x < leftx) {
hits++;
continue;
}
test1 = x - lastx;
test2 = y - lasty;
}
if (test1 < (test2 / (lasty - cury) * (lastx - curx))) {
hits++;
}
}
return (hits & 1) != 0;
}
auto RegionSelect::userTapped(double zoom) const -> bool {
double maxDist = 10 / zoom;
const BoundaryPoint& r0 = boundaryPoints.front();
for (const BoundaryPoint& p: boundaryPoints) {
if (std::abs(r0.x - p.x) > maxDist || std::abs(r0.y - p.y) > maxDist) {
return false;
}
}
return true;
}
auto RegionSelect::getBoundary() const -> const std::vector<BoundaryPoint>& { return boundaryPoints; }
| 6,242
|
C++
|
.cpp
| 161
| 30.583851
| 144
| 0.561
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,473
|
SnapToGridInputHandler.cpp
|
xournalpp_xournalpp/src/core/control/tools/SnapToGridInputHandler.cpp
|
#include "SnapToGridInputHandler.h"
#include "control/settings/Settings.h"
#include "model/Snapping.h"
SnapToGridInputHandler::SnapToGridInputHandler(Settings* settings): settings(settings) {}
double SnapToGridInputHandler::snapVertically(double y, bool alt) {
if (alt != settings->isSnapGrid()) {
return Snapping::snapVertically(y, settings->getSnapGridSize(), settings->getSnapGridTolerance());
}
return y;
}
double SnapToGridInputHandler::snapHorizontally(double x, bool alt) {
if (alt != settings->isSnapGrid()) {
return Snapping::snapHorizontally(x, settings->getSnapGridSize(), settings->getSnapGridTolerance());
}
return x;
}
Point SnapToGridInputHandler::snapToGrid(Point const& pos, bool alt) {
if (alt != settings->isSnapGrid()) {
return Snapping::snapToGrid(pos, settings->getSnapGridSize(), settings->getSnapGridTolerance());
}
return pos;
}
double SnapToGridInputHandler::snapAngle(double radian, bool alt) {
if (alt != settings->isSnapRotation()) {
return Snapping::snapAngle(radian, settings->getSnapRotationTolerance());
}
return radian;
}
Point SnapToGridInputHandler::snapRotation(Point const& pos, Point const& center, bool alt) {
if (alt != settings->isSnapRotation()) {
return Snapping::snapRotation(pos, center, settings->getSnapRotationTolerance());
}
return pos;
}
Point SnapToGridInputHandler::snap(Point const& pos, Point const& center, bool alt) {
Point rotationSnappedPoint{snapRotation(pos, center, alt)};
return snapToGrid(rotationSnappedPoint, alt);
}
| 1,599
|
C++
|
.cpp
| 38
| 38.026316
| 108
| 0.740502
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,474
|
StrokeHandler.cpp
|
xournalpp_xournalpp/src/core/control/tools/StrokeHandler.cpp
|
#include "StrokeHandler.h"
#include <algorithm> // for max, min
#include <cmath> // for ceil, pow, abs
#include <limits> // for numeric_limits
#include <memory> // for unique_ptr, mak...
#include <utility> // for move
#include <vector> // for vector
#include <gdk/gdk.h> // for GdkEventKey
#include "control/Control.h" // for Control
#include "control/ToolEnums.h" // for DRAWING_TYPE_ST...
#include "control/ToolHandler.h" // for ToolHandler
#include "control/layer/LayerController.h" // for LayerController
#include "control/settings/Settings.h" // for Settings
#include "control/settings/SettingsEnums.h" // for EmptyLastPageAppendType
#include "control/shaperecognizer/ShapeRecognizer.h" // for ShapeRecognizer
#include "control/tools/InputHandler.h" // for InputHandler::P...
#include "control/tools/SnapToGridInputHandler.h" // for SnapToGridInput...
#include "gui/inputdevices/PositionInputData.h" // for PositionInputData
#include "model/Document.h" // for Document
#include "model/Element.h"
#include "model/Layer.h" // for Layer
#include "model/LineStyle.h" // for LineStyle
#include "model/Stroke.h" // for Stroke, STROKE_...
#include "model/XojPage.h" // for XojPage
#include "undo/InsertUndoAction.h" // for InsertUndoAction
#include "undo/RecognizerUndoAction.h" // for RecognizerUndoA...
#include "undo/UndoRedoHandler.h" // for UndoRedoHandler
#include "util/Assert.h" // for xoj_assert
#include "util/DispatchPool.h" // for DispatchPool
#include "util/Range.h" // for Range
#include "util/Rectangle.h" // for Rectangle, util
#include "view/overlays/StrokeToolFilledHighlighterView.h" // for StrokeToolFilledHighlighterView
#include "view/overlays/StrokeToolFilledView.h" // for StrokeToolFilledView
#include "view/overlays/StrokeToolView.h" // for StrokeToolView
#include "StrokeStabilizer.h" // for Base, get
using xoj::util::Rectangle;
StrokeHandler::StrokeHandler(Control* control, const PageRef& page):
InputHandler(control, page),
snappingHandler(control->getSettings()),
stabilizer(StrokeStabilizer::get(control->getSettings())),
viewPool(std::make_shared<xoj::util::DispatchPool<xoj::view::StrokeToolView>>()) {}
StrokeHandler::~StrokeHandler() = default;
auto StrokeHandler::onKeyPressEvent(const KeyEvent&) -> bool { return false; }
auto StrokeHandler::onKeyReleaseEvent(const KeyEvent&) -> bool { return false; }
auto StrokeHandler::onMotionNotifyEvent(const PositionInputData& pos, double zoom) -> bool {
if (!stroke) {
return false;
}
if (pos.pressure == 0) {
/**
* Some devices emit a move event with pressure 0 when lifting the stylus tip
* Ignore those events
*/
return true;
}
stabilizer->processEvent(pos);
return true;
}
void StrokeHandler::paintTo(Point point) {
if (this->hasPressure && point.z > 0.0) {
point.z *= this->stroke->getWidth();
}
size_t pointCount = stroke->getPointCount();
if (pointCount > 0) {
Point endPoint = stroke->getPoint(pointCount - 1);
double distance = point.lineLengthTo(endPoint);
if (distance < PIXEL_MOTION_THRESHOLD) { //(!validMotion(point, endPoint)) {
if (pointCount == 1 && this->hasPressure && endPoint.z < point.z) {
// Record the possible increase in pressure for the first point
this->stroke->setLastPressure(point.z);
this->viewPool->dispatch(xoj::view::StrokeToolView::THICKEN_FIRST_POINT_REQUEST, point.z);
}
return;
}
if (this->hasPressure) {
/**
* Both device and tool are pressure sensitive
*/
if (const double widthDelta = point.z - endPoint.z;
- widthDelta > MAX_WIDTH_VARIATION || widthDelta > MAX_WIDTH_VARIATION) {
/**
* If the width variation is to big, decompose into shorter segments.
* Those segments can not be shorter than PIXEL_MOTION_THRESHOLD
*/
double nbSteps = std::min(std::ceil(std::abs(widthDelta) / MAX_WIDTH_VARIATION),
std::floor(distance / PIXEL_MOTION_THRESHOLD));
double stepLength = 1.0 / nbSteps;
Point increment((point.x - endPoint.x) * stepLength, (point.y - endPoint.y) * stepLength,
widthDelta * stepLength);
endPoint.z += increment.z;
for (int i = 1; i < static_cast<int>(nbSteps); i++) { // The last step is done below
endPoint.x += increment.x;
endPoint.y += increment.y;
endPoint.z += increment.z;
drawSegmentTo(endPoint);
}
}
}
}
drawSegmentTo(point);
}
void StrokeHandler::drawSegmentTo(const Point& point) {
this->stroke->addPoint(this->hasPressure ? point : Point(point.x, point.y));
this->viewPool->dispatch(xoj::view::StrokeToolView::ADD_POINT_REQUEST, this->stroke->getPointVector().back());
return;
}
void StrokeHandler::onSequenceCancelEvent() {
if (this->stroke) {
this->viewPool->dispatchAndClear(xoj::view::StrokeToolView::CANCELLATION_REQUEST,
Range(this->stroke->boundingRect()));
stroke.reset();
}
}
void StrokeHandler::onButtonReleaseEvent(const PositionInputData& pos, double zoom) {
if (!stroke) {
return;
}
/**
* The stabilizer may have added a gap between the end of the stroke and the input device
* Fill this gap.
*/
stabilizer->finalizeStroke();
// Backward compatibility and also easier to handle for me;-)
// I cannot draw a line with one point, to draw a visible line I need two points,
// twice the same Point is also OK
if (auto const& pv = stroke->getPointVector(); pv.size() == 1) {
const Point pt = pv.front(); // Make a copy, otherwise stroke->addPoint(pt); in UB
if (this->hasPressure) {
// Pressure inference provides a pressure value to the last event. Most devices set this value to 0.
const double newPressure = std::max(pt.z, pos.pressure * this->stroke->getWidth());
this->stroke->setLastPressure(newPressure);
this->viewPool->dispatch(xoj::view::StrokeToolView::THICKEN_FIRST_POINT_REQUEST, newPressure);
}
stroke->addPoint(pt);
}
stroke->freeUnusedPointItems();
Layer* layer = page->getSelectedLayer();
UndoRedoHandler* undo = control->getUndoRedoHandler();
undo->addUndoAction(std::make_unique<InsertUndoAction>(page, layer, stroke.get()));
Settings* settings = control->getSettings();
if (settings->getEmptyLastPageAppend() == EmptyLastPageAppendType::OnDrawOfLastPage) {
auto* doc = control->getDocument();
doc->lock();
auto pdfPageCount = doc->getPdfPageCount();
doc->unlock();
if (pdfPageCount == 0) {
auto currentPage = control->getCurrentPageNo();
doc->lock();
auto lastPage = doc->getPageCount() - 1;
doc->unlock();
if (currentPage == lastPage) {
control->insertNewPage(currentPage + 1, false);
}
}
}
ToolHandler* h = control->getToolHandler();
if (h->getDrawingType() == DRAWING_TYPE_SHAPE_RECOGNIZER) {
ShapeRecognizer reco;
auto recognized = reco.recognizePatterns(stroke.get(), control->getSettings()->getStrokeRecognizerMinSize());
if (recognized) {
// strokeRecognizerDetected handles the repainting and the deletion of the views.
strokeRecognizerDetected(std::move(recognized), layer);
return;
}
}
auto ptr = stroke.get();
Document* doc = control->getDocument();
doc->lock();
layer->addElement(std::move(stroke));
doc->unlock();
// Blitt the stroke to the page's buffer and delete all views.
// Passing the empty Range() as no actual redrawing is necessary at this point
this->viewPool->dispatchAndClear(xoj::view::StrokeToolView::FINALIZATION_REQUEST, Range());
page->fireElementChanged(ptr);
}
void StrokeHandler::strokeRecognizerDetected(std::unique_ptr<Stroke> recognized, Layer* layer) {
recognized->setWidth(stroke->hasPressure() ? stroke->getAvgPressure() : stroke->getWidth());
// snapping
if (control->getSettings()->getSnapRecognizedShapesEnabled()) {
Rectangle<double> oldSnappedBounds = recognized->getSnappedBounds();
Point topLeft = Point(oldSnappedBounds.x, oldSnappedBounds.y);
Point topLeftSnapped = snappingHandler.snapToGrid(topLeft, false);
recognized->move(topLeftSnapped.x - topLeft.x, topLeftSnapped.y - topLeft.y);
Rectangle<double> snappedBounds = recognized->getSnappedBounds();
Point belowRight = Point(snappedBounds.x + snappedBounds.width, snappedBounds.y + snappedBounds.height);
Point belowRightSnapped = snappingHandler.snapToGrid(belowRight, false);
double fx = (std::abs(snappedBounds.width) > std::numeric_limits<double>::epsilon()) ?
(belowRightSnapped.x - topLeftSnapped.x) / snappedBounds.width :
1;
double fy = (std::abs(snappedBounds.height) > std::numeric_limits<double>::epsilon()) ?
(belowRightSnapped.y - topLeftSnapped.y) / snappedBounds.height :
1;
recognized->scale(topLeftSnapped.x, topLeftSnapped.y, fx, fy, 0, false);
}
UndoRedoHandler* undo = control->getUndoRedoHandler();
auto recognizedPtr = recognized.get();
auto strokePtr = stroke.get();
undo->addUndoAction(std::make_unique<RecognizerUndoAction>(page, layer, std::move(stroke), recognizedPtr));
Document* doc = control->getDocument();
doc->lock();
layer->addElement(std::move(recognized));
doc->unlock();
Range range(recognizedPtr->getX(), recognizedPtr->getY());
range.addPoint(recognizedPtr->getX() + recognizedPtr->getElementWidth(),
recognizedPtr->getY() + recognizedPtr->getElementHeight());
range.addPoint(strokePtr->getX(), strokePtr->getY());
range.addPoint(strokePtr->getX() + strokePtr->getElementWidth(), strokePtr->getY() + strokePtr->getElementHeight());
this->viewPool->dispatch(xoj::view::StrokeToolView::STROKE_REPLACEMENT_REQUEST, *recognizedPtr);
// Blitt the new stroke to the page's buffer, delete all the views and refresh the area (so the recognized stroke
// gets displayed instead of the old one).
this->viewPool->dispatchAndClear(xoj::view::StrokeToolView::FINALIZATION_REQUEST, range);
page->fireElementChanged(recognizedPtr);
}
void StrokeHandler::onButtonPressEvent(const PositionInputData& pos, double zoom) {
xoj_assert(!stroke);
this->buttonDownPoint.x = pos.x / zoom;
this->buttonDownPoint.y = pos.y / zoom;
stroke = createStroke(this->control);
this->hasPressure = this->stroke->getToolType().isPressureSensitive() && pos.pressure != Point::NO_PRESSURE;
const double width = this->hasPressure ? pos.pressure * stroke->getWidth() : Point::NO_PRESSURE;
stroke->addPoint(Point(this->buttonDownPoint.x, this->buttonDownPoint.y, width));
stabilizer->initialize(this, zoom, pos);
}
void StrokeHandler::onButtonDoublePressEvent(const PositionInputData&, double) {
// nothing to do
}
auto StrokeHandler::createView(xoj::view::Repaintable* parent) const -> std::unique_ptr<xoj::view::OverlayView> {
xoj_assert(this->stroke);
const Stroke& s = *this->stroke;
if (s.getFill() != -1) {
if (s.getToolType() == StrokeTool::HIGHLIGHTER) {
// Filled highlighter requires to wipe the mask entirely at every iteration
// It has a dedicated view class.
return std::make_unique<xoj::view::StrokeToolFilledHighlighterView>(this, s, parent);
} else {
return std::make_unique<xoj::view::StrokeToolFilledView>(this, s, parent);
}
} else {
return std::make_unique<xoj::view::StrokeToolView>(this, s, parent);
}
}
auto StrokeHandler::getViewPool() const -> const std::shared_ptr<xoj::util::DispatchPool<xoj::view::StrokeToolView>>& {
return viewPool;
}
| 13,004
|
C++
|
.cpp
| 244
| 45.545082
| 120
| 0.633281
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,475
|
BaseShapeHandler.cpp
|
xournalpp_xournalpp/src/core/control/tools/BaseShapeHandler.cpp
|
#include "BaseShapeHandler.h"
#include <cmath> // for pow, NAN
#include <memory> // for make_unique, __share...
#include <gdk/gdkkeysyms.h> // for GDK_KEY_Alt_L, GDK_K...
#include "control/Control.h" // for Control
#include "control/layer/LayerController.h" // for LayerController
#include "control/settings/Settings.h" // for Settings
#include "control/tools/InputHandler.h" // for InputHandler
#include "control/tools/SnapToGridInputHandler.h" // for SnapToGridInputHandler
#include "gui/XournalppCursor.h" // for XournalppCursor
#include "gui/inputdevices/PositionInputData.h" // for PositionInputData
#include "model/Document.h" // for Document
#include "model/Layer.h" // for Layer
#include "model/Stroke.h" // for Stroke
#include "model/XojPage.h" // for XojPage
#include "undo/InsertUndoAction.h" // for InsertUndoAction
#include "undo/UndoRedoHandler.h" // for UndoRedoHandler
#include "util/Assert.h" // for xoj_assert
#include "util/DispatchPool.h" // for DispatchPool
#include "view/overlays/ShapeToolView.h" // for ShapeToolView
BaseShapeHandler::BaseShapeHandler(Control* control, const PageRef& page, bool flipShift, bool flipControl):
InputHandler(control, page),
flipShift(flipShift),
flipControl(flipControl),
snappingHandler(control->getSettings()),
viewPool(std::make_shared<xoj::util::DispatchPool<xoj::view::ShapeToolView>>()) {}
BaseShapeHandler::~BaseShapeHandler() = default;
void BaseShapeHandler::updateShape(bool isAltDown, bool isShiftDown, bool isControlDown) {
auto [shape, rg] = this->createShape(isAltDown, isShiftDown, isControlDown);
std::swap(shape, this->shape);
Range repaintRange = rg.unite(lastSnappingRange);
lastSnappingRange = rg;
repaintRange.addPadding(0.5 * this->stroke->getWidth());
viewPool->dispatch(xoj::view::ShapeToolView::FLAG_DIRTY_REGION, repaintRange);
}
void BaseShapeHandler::cancelStroke() {
this->shape.clear();
Range repaintRange = this->lastSnappingRange;
repaintRange.addPadding(0.5 * this->stroke->getWidth());
this->viewPool->dispatchAndClear(xoj::view::ShapeToolView::FINALIZATION_REQUEST, repaintRange);
this->lastSnappingRange = Range();
}
auto BaseShapeHandler::onKeyEvent(const KeyEvent& event, bool pressed) -> bool {
bool isAltDown = event.state & GDK_MOD1_MASK;
bool isShiftDown = event.state & GDK_SHIFT_MASK;
bool isControlDown = event.state & GDK_CONTROL_MASK;
// event->state contains the modifiers' states BEFORE the current event
if (event.keyval == GDK_KEY_Shift_L || event.keyval == GDK_KEY_Shift_R) {
isShiftDown = pressed;
} else if (event.keyval == GDK_KEY_Control_L || event.keyval == GDK_KEY_Control_R) {
isControlDown = pressed;
} else if (event.keyval == GDK_KEY_Alt_L || event.keyval == GDK_KEY_Alt_R) {
isAltDown = pressed;
} else {
return false;
}
this->updateShape(isAltDown, isShiftDown, isControlDown);
return true;
}
auto BaseShapeHandler::onKeyPressEvent(const KeyEvent& event) -> bool { return onKeyEvent(event, true); }
auto BaseShapeHandler::onKeyReleaseEvent(const KeyEvent& event) -> bool { return onKeyEvent(event, false); }
auto BaseShapeHandler::onMotionNotifyEvent(const PositionInputData& pos, double zoom) -> bool {
Point newPoint(pos.x / zoom, pos.y / zoom);
if (!validMotion(newPoint, this->currPoint)) {
return true;
}
this->currPoint = newPoint;
this->updateShape(pos.isAltDown(), pos.isShiftDown(), pos.isControlDown());
return true;
}
void BaseShapeHandler::onSequenceCancelEvent() { this->cancelStroke(); }
void BaseShapeHandler::onButtonReleaseEvent(const PositionInputData& pos, double zoom) {
control->getCursor()->activateDrawDirCursor(false); // in case released within fixate_Dir_Mods_Dist
if (this->shape.size() <= 1) {
// We need at least two points to make a stroke (it can be twice the same)
this->cancelStroke();
return;
}
Layer* layer = page->getSelectedLayer();
UndoRedoHandler* undo = control->getUndoRedoHandler();
stroke->setPointVector(this->shape, &lastSnappingRange);
Range repaintRange = lastSnappingRange;
repaintRange.addPadding(0.5 * this->stroke->getWidth());
this->viewPool->dispatchAndClear(xoj::view::ShapeToolView::FINALIZATION_REQUEST, repaintRange);
undo->addUndoAction(std::make_unique<InsertUndoAction>(page, layer, stroke.get()));
auto ptr = stroke.get();
Document* doc = control->getDocument();
doc->lock();
layer->addElement(std::move(stroke));
doc->unlock();
page->fireElementChanged(ptr);
control->getCursor()->updateCursor();
}
void BaseShapeHandler::onButtonPressEvent(const PositionInputData& pos, double zoom) {
xoj_assert(this->viewPool->empty());
this->buttonDownPoint.x = pos.x / zoom;
this->buttonDownPoint.y = pos.y / zoom;
this->startPoint = snappingHandler.snapToGrid(this->buttonDownPoint, pos.isAltDown());
this->currPoint = this->startPoint;
this->stroke = createStroke(this->control);
}
void BaseShapeHandler::onButtonDoublePressEvent(const PositionInputData&, double) {
// nothing to do
}
void BaseShapeHandler::modifyModifiersByDrawDir(double width, double height, double zoom, bool changeCursor) {
bool gestureShift = this->flipShift;
bool gestureControl = this->flipControl;
if (this->drawModifierFixed == NONE) {
// User hasn't dragged out past DrawDirModsRadius i.e. modifier not yet locked.
gestureShift = (width < 0) != gestureShift;
gestureControl = (height < 0) != gestureControl;
this->modShift = this->modShift == !gestureShift;
this->modControl = this->modControl == !gestureControl;
double fixate_Dir_Mods_Dist = control->getSettings()->getDrawDirModsRadius() / zoom;
xoj_assert(fixate_Dir_Mods_Dist > 0.0);
if (std::abs(width) > fixate_Dir_Mods_Dist || std::abs(height) > fixate_Dir_Mods_Dist) {
this->drawModifierFixed = static_cast<DIRSET_MODIFIERS>(SET | (gestureShift ? SHIFT : NONE) |
(gestureControl ? CONTROL : NONE));
if (changeCursor) {
control->getCursor()->activateDrawDirCursor(false);
}
} else {
if (changeCursor) {
control->getCursor()->activateDrawDirCursor(true, this->modShift, this->modControl);
}
}
} else {
gestureShift = gestureShift == !(this->drawModifierFixed & SHIFT);
gestureControl = gestureControl == !(this->drawModifierFixed & CONTROL);
this->modShift = this->modShift == !gestureShift;
this->modControl = this->modControl == !gestureControl;
}
}
auto BaseShapeHandler::getShape() const -> const std::vector<Point>& { return this->shape; }
auto BaseShapeHandler::createView(xoj::view::Repaintable* parent) const -> std::unique_ptr<xoj::view::OverlayView> {
return std::make_unique<xoj::view::ShapeToolView>(this, parent);
}
auto BaseShapeHandler::getViewPool() const
-> const std::shared_ptr<xoj::util::DispatchPool<xoj::view::ShapeToolView>>& {
return viewPool;
}
| 7,502
|
C++
|
.cpp
| 141
| 47.546099
| 116
| 0.677908
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,476
|
SplineHandler.cpp
|
xournalpp_xournalpp/src/core/control/tools/SplineHandler.cpp
|
#include "SplineHandler.h"
#include <algorithm> // for max, max_element
#include <cmath> // for pow, M_PI, cos, sin
#include <cstddef> // for size_t
#include <list> // for list, operator!=
#include <memory> // for allocator_traits<>...
#include <optional> // for optional
#include <utility> // for move
#include <gdk/gdkkeysyms.h> // for GDK_KEY_Escape
#include "control/Control.h" // for Control
#include "control/layer/LayerController.h" // for LayerController
#include "control/tools/InputHandler.h" // for InputHandler
#include "control/tools/SnapToGridInputHandler.h" // for SnapToGridInputHan...
#include "control/zoom/ZoomControl.h"
#include "gui/XournalppCursor.h" // for XournalppCursor
#include "gui/inputdevices/InputEvents.h" // for KeyEvent
#include "gui/inputdevices/PositionInputData.h" // for PositionInputData
#include "model/Document.h" // for Document
#include "model/Layer.h" // for Layer
#include "model/SplineSegment.h" // for SplineSegment
#include "model/Stroke.h" // for Stroke
#include "model/XojPage.h" // for XojPage
#include "undo/InsertUndoAction.h" // for InsertUndoAction
#include "undo/UndoRedoHandler.h" // for UndoRedoHandler
#include "util/Assert.h" // for xoj_assert
#include "util/DispatchPool.h"
#include "view/overlays/SplineToolView.h"
SplineHandler::SplineHandler(Control* control, const PageRef& page):
InputHandler(control, page),
snappingHandler(control->getSettings()),
viewPool(std::make_shared<xoj::util::DispatchPool<xoj::view::SplineToolView>>()) {
this->control->getZoomControl()->addZoomListener(this);
this->knotsAttractionRadius = KNOTS_ATTRACTION_RADIUS_IN_PIXELS / this->control->getZoomControl()->getZoom();
}
SplineHandler::~SplineHandler() { this->control->getZoomControl()->removeZoomListener(this); }
std::unique_ptr<xoj::view::OverlayView> SplineHandler::createView(xoj::view::Repaintable* parent) const {
return std::make_unique<xoj::view::SplineToolView>(this, parent);
}
constexpr double SHIFT_AMOUNT = 1.0;
constexpr double ROTATE_AMOUNT = 5.0;
constexpr double SCALE_AMOUNT = 1.05;
constexpr double MAX_TANGENT_LENGTH = 2000.0;
constexpr double MIN_TANGENT_LENGTH = 1.0;
auto SplineHandler::onKeyPressEvent(const KeyEvent& event) -> bool {
if (!stroke) {
return false;
}
xoj_assert(!this->knots.empty() && this->knots.size() == this->tangents.size());
Range rg = this->computeLastSegmentRepaintRange();
switch (event.keyval) {
case GDK_KEY_BackSpace: {
if (this->knots.size() == 1) {
return true;
}
this->deleteLastKnotWithTangent();
xoj_assert(!this->knots.empty() && this->knots.size() == this->tangents.size());
const Point& p = this->knots.back();
const Point& t = this->tangents.back();
rg.addPoint(p.x - t.x, p.y - t.y); // Ensure the tangent vector gets its color updated
break;
}
case GDK_KEY_Right: {
this->movePoint(SHIFT_AMOUNT, 0);
rg = rg.unite(this->computeLastSegmentRepaintRange());
break;
}
case GDK_KEY_Left: {
this->movePoint(-SHIFT_AMOUNT, 0);
rg = rg.unite(this->computeLastSegmentRepaintRange());
break;
}
case GDK_KEY_Up: {
this->movePoint(0, -SHIFT_AMOUNT);
rg = rg.unite(this->computeLastSegmentRepaintRange());
break;
}
case GDK_KEY_Down: {
this->movePoint(0, SHIFT_AMOUNT);
rg = rg.unite(this->computeLastSegmentRepaintRange());
break;
}
case GDK_KEY_r:
case GDK_KEY_R: { // r like "rotate"
double angle = (event.keyval == GDK_KEY_R) ? -ROTATE_AMOUNT : ROTATE_AMOUNT;
double xOld = this->tangents.back().x;
double yOld = this->tangents.back().y;
double xNew = cos(angle * M_PI / 180) * xOld + sin(angle * M_PI / 180) * yOld;
double yNew = -sin(angle * M_PI / 180) * xOld + cos(angle * M_PI / 180) * yOld;
this->modifyLastTangent(Point(xNew, yNew));
rg = rg.unite(this->computeLastSegmentRepaintRange());
break;
}
case GDK_KEY_s:
case GDK_KEY_S: { // s like "scale"
double xOld = this->tangents.back().x;
double yOld = this->tangents.back().y;
double length = 2 * sqrt(pow(xOld, 2) + pow(yOld, 2));
double factor = 1;
if (event.keyval == GDK_KEY_S) {
if (length >= MIN_TANGENT_LENGTH) {
factor = 1 / SCALE_AMOUNT;
}
} else if (length <= MAX_TANGENT_LENGTH) {
factor = SCALE_AMOUNT;
}
double xNew = xOld * factor;
double yNew = yOld * factor;
this->modifyLastTangent(Point(xNew, yNew));
rg = rg.unite(this->computeLastSegmentRepaintRange());
break;
}
default:
return false;
}
this->viewPool->dispatch(xoj::view::SplineToolView::FLAG_DIRTY_REGION, rg);
return true;
}
bool SplineHandler::onKeyReleaseEvent(const KeyEvent& event) {
if (event.keyval == GDK_KEY_Escape) {
this->finalizeSpline();
return true;
}
return false;
}
auto SplineHandler::onMotionNotifyEvent(const PositionInputData& pos, double zoom) -> bool {
if (!stroke) {
return false;
}
xoj_assert(!this->knots.empty() && this->knots.size() == this->tangents.size());
Range rg = this->computeLastSegmentRepaintRange();
if (this->isButtonPressed) {
if (this->inFirstKnotAttractionZone) {
// The button was pressed within the attraction zone. Wait for unpress to confirm/deny spline finalization
return true;
}
Point newTangent = Point(pos.x / zoom - this->currPoint.x, pos.y / zoom - this->currPoint.y);
if (validMotion(newTangent, this->tangents.back())) {
this->modifyLastTangent(newTangent);
}
} else {
this->buttonDownPoint = Point(pos.x / zoom, pos.y / zoom);
bool nowInAttractionZone =
this->buttonDownPoint.lineLengthTo(this->knots.front()) < this->knotsAttractionRadius;
if (nowInAttractionZone) {
if (this->inFirstKnotAttractionZone) {
// No need to update anything while staying in the attraction zone
return true;
}
} else {
this->currPoint = snappingHandler.snap(this->buttonDownPoint, knots.back(), pos.isAltDown());
}
this->inFirstKnotAttractionZone = nowInAttractionZone;
}
rg = rg.unite(this->computeLastSegmentRepaintRange());
this->viewPool->dispatch(xoj::view::SplineToolView::FLAG_DIRTY_REGION, rg);
return true;
}
void SplineHandler::onSequenceCancelEvent() {
// Touch screen sequence changed from normal to swipe/zoom/scroll sequence
isButtonPressed = false;
if (!stroke) {
return;
}
if (this->knots.size() <= 1) {
this->clearTinySpline();
} else {
auto rg = this->computeLastSegmentRepaintRange();
this->deleteLastKnotWithTangent();
this->viewPool->dispatch(xoj::view::SplineToolView::FLAG_DIRTY_REGION, rg);
}
}
void SplineHandler::onButtonReleaseEvent(const PositionInputData& pos, double zoom) {
this->isButtonPressed = false;
if (this->inFirstKnotAttractionZone) {
// The click began in the first knot's attraction zone
// Finalize the spline if we still are in this zone, cancel the sequence otherwise
const Point p(pos.x / zoom, pos.y / zoom);
double dist = p.lineLengthTo(this->knots.front());
if (dist < this->knotsAttractionRadius) {
finalizeSpline();
} else {
this->inFirstKnotAttractionZone = false;
onSequenceCancelEvent();
}
}
}
void SplineHandler::onButtonPressEvent(const PositionInputData& pos, double zoom) {
this->isButtonPressed = true;
if (!stroke) {
// This should only happen right after the SplineHandler's creation, before any views got attached
xoj_assert(this->viewPool->empty());
stroke = createStroke(this->control);
xoj_assert(this->knots.empty() && this->tangents.empty());
this->buttonDownPoint = Point(pos.x / zoom, pos.y / zoom);
this->currPoint = snappingHandler.snapToGrid(this->buttonDownPoint, pos.isAltDown());
this->addKnot(this->currPoint);
} else {
xoj_assert(!this->knots.empty());
this->buttonDownPoint = Point(pos.x / zoom, pos.y / zoom);
this->currPoint = snappingHandler.snap(this->buttonDownPoint, knots.back(), pos.isAltDown());
double dist = this->buttonDownPoint.lineLengthTo(this->knots.front());
if (dist < this->knotsAttractionRadius) { // now the spline is closed and finalized
this->addKnotWithTangent(this->knots.front(), this->tangents.front());
this->inFirstKnotAttractionZone = true;
auto rg = this->computeLastSegmentRepaintRange();
this->viewPool->dispatch(xoj::view::SplineToolView::FLAG_DIRTY_REGION, rg);
} else if (validMotion(currPoint, this->knots.back())) {
this->addKnot(this->currPoint);
auto rg = this->computeLastSegmentRepaintRange();
this->viewPool->dispatch(xoj::view::SplineToolView::FLAG_DIRTY_REGION, rg);
}
}
}
void SplineHandler::onButtonDoublePressEvent(const PositionInputData&, double) { finalizeSpline(); }
void SplineHandler::movePoint(double dx, double dy) {
// move last non dynamically changing point
if (!this->knots.empty()) {
this->knots.back().x += dx;
this->knots.back().y += dy;
}
}
void SplineHandler::clearTinySpline() {
auto rg = this->computeLastSegmentRepaintRange();
// Clearing the knots ensures the view will not draw anything (thus the repainting will erase everything)
this->knots.clear();
this->tangents.clear();
this->stroke.reset();
// Repaints and deletes the views
this->viewPool->dispatchAndClear(xoj::view::SplineToolView::FINALIZATION_REQUEST, rg);
}
void SplineHandler::finalizeSpline() {
xoj_assert(this->stroke);
auto optData = getData();
xoj_assert(optData);
auto& data = optData.value();
if (data.knots.size() < 2) { // This is not a valid spline
clearTinySpline();
return;
}
stroke->setPointVector(linearizeSpline(data));
stroke->freeUnusedPointItems();
Layer* layer = page->getSelectedLayer();
UndoRedoHandler* undo = control->getUndoRedoHandler();
undo->addUndoAction(std::make_unique<InsertUndoAction>(page, layer, stroke.get()));
auto ptr = stroke.get();
Document* doc = control->getDocument();
doc->lock();
layer->addElement(std::move(stroke));
doc->unlock();
auto rg = this->computeTotalRepaintRange(data, ptr->getWidth());
this->viewPool->dispatchAndClear(xoj::view::SplineToolView::FINALIZATION_REQUEST, rg);
// Wait until this finishes before releasing `stroke`, so that PageView::elementChanged does not needlessly rerender
// the stroke
this->page->fireElementChanged(ptr);
control->getCursor()->updateCursor();
}
void SplineHandler::zoomChanged() {
this->knotsAttractionRadius = KNOTS_ATTRACTION_RADIUS_IN_PIXELS / this->control->getZoomControl()->getZoom();
}
void SplineHandler::addKnot(const Point& p) { addKnotWithTangent(p, Point(0, 0)); }
void SplineHandler::addKnotWithTangent(const Point& p, const Point& t) {
this->knots.push_back(p);
this->tangents.push_back(t);
}
void SplineHandler::modifyLastTangent(const Point& t) {
xoj_assert(!this->tangents.empty());
this->tangents.back() = t;
}
void SplineHandler::deleteLastKnotWithTangent() {
xoj_assert(this->knots.size() > 1 && this->knots.size() == this->tangents.size());
this->knots.pop_back();
this->tangents.pop_back();
}
auto SplineHandler::computeTotalRepaintRange(const Data& data, double strokeWidth) const -> Range {
std::vector<double> xCoords = {};
std::vector<double> yCoords = {};
for (auto p: data.knots) {
xCoords.push_back(p.x);
yCoords.push_back(p.y);
}
for (size_t i = 0; i < data.knots.size(); i++) {
xCoords.push_back(data.knots[i].x + data.tangents[i].x);
xCoords.push_back(data.knots[i].x - data.tangents[i].x);
yCoords.push_back(data.knots[i].y + data.tangents[i].y);
yCoords.push_back(data.knots[i].y - data.tangents[i].y);
}
xCoords.push_back(data.currPoint.x);
yCoords.push_back(data.currPoint.y);
double minX = *std::min_element(xCoords.begin(), xCoords.end());
double maxX = *std::max_element(xCoords.begin(), xCoords.end());
double minY = *std::min_element(yCoords.begin(), yCoords.end());
double maxY = *std::max_element(yCoords.begin(), yCoords.end());
Range rg(minX, minY, maxX, maxY);
rg.addPadding(std::max(data.knotsAttractionRadius, strokeWidth)); // Circles around the knots and the spline width
return rg;
}
Range SplineHandler::computeLastSegmentRepaintRange() const {
xoj_assert(!this->knots.empty() && this->knots.size() == this->tangents.size());
Range rg(this->currPoint.x, this->currPoint.y);
const Point& p = this->knots.back();
const Point& t = this->tangents.back();
rg.addPoint(p.x + t.x, p.y + t.y);
rg.addPoint(p.x - t.x, p.y - t.y);
if (auto n = this->knots.size(); n > 1) {
const Point& q = this->knots[n - 2];
const Point& s = this->tangents[n - 2];
rg.addPoint(q.x + s.x, q.y + s.y);
rg.addPoint(q.x, q.y); // Enough for the last segment.
}
// Ensure the range contains the spline (with its width) and the knots' circles
rg.addPadding(std::max(this->knotsAttractionRadius, this->stroke->getWidth()));
if (const Point& q = this->knots.front(); this->inFirstKnotAttractionZone) {
// Make sure the range contains the last spline segment in case the spline is closed.
// The last segment has a width fixed in pixels. The appropriate padding to account for this width will be added
// on the View side.
const double r = this->knotsAttractionRadius;
rg = rg.unite(Range(q.x - r, q.y - r, q.x + r, q.y + r));
const Point& s = this->tangents.front();
rg.addPoint(q.x - s.x, q.y - s.y);
} else if (this->stroke->getFill() != -1) {
// If the stroke is filled, we need to update the filling as well. Changes in the filling happen in the convex
// hull of the last segment and the first knot, so adding the first knot to the range is enough at this point.
rg.addPoint(q.x, q.y);
}
return rg;
}
auto SplineHandler::getViewPool() const -> const std::shared_ptr<xoj::util::DispatchPool<xoj::view::SplineToolView>>& {
return viewPool;
}
auto SplineHandler::getData() const -> std::optional<Data> {
if (this->knots.empty()) {
return std::nullopt;
}
return Data{this->knots, this->tangents, this->currPoint, this->knotsAttractionRadius,
this->inFirstKnotAttractionZone};
}
auto SplineHandler::linearizeSpline(const SplineHandler::Data& data) -> std::vector<Point> {
xoj_assert(!data.knots.empty() && data.knots.size() == data.tangents.size());
std::vector<Point> result;
auto itKnot1 = data.knots.begin();
auto itKnot2 = std::next(itKnot1);
auto itTgt1 = data.tangents.begin();
auto itTgt2 = std::next(itTgt1);
auto end = data.knots.end();
for (; itKnot2 != end; ++itKnot1, ++itKnot2, ++itTgt1, ++itTgt2) {
SplineSegment seg(*itKnot1, Point(itKnot1->x + itTgt1->x, itKnot1->y + itTgt1->y),
Point(itKnot2->x - itTgt2->x, itKnot2->y - itTgt2->y), *itKnot2);
auto pts = seg.toPointSequence();
std::move(pts.begin(), pts.end(), std::back_inserter(result));
}
result.emplace_back(data.knots.back());
return result;
}
| 16,377
|
C++
|
.cpp
| 353
| 39.416431
| 120
| 0.638367
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,477
|
TextEditor.cpp
|
xournalpp_xournalpp/src/core/control/tools/TextEditor.cpp
|
#include "TextEditor.h"
#include <cstring> // for strcmp, size_t
#include <memory> // for allocator, make_unique, __shared_p...
#include <string> // for std::string()
#include <utility> // for move
#include <gdk/gdkkeysyms.h> // for GDK_KEY_B, GDK_KEY_ISO_Enter, GDK_...
#include <glib-object.h> // for g_object_get, g_object_unref, G_CA...
#include "control/AudioController.h"
#include "control/Control.h" // for Control
#include "control/settings/Settings.h"
#include "gui/XournalppCursor.h" // for XournalppCursor
#include "model/Font.h" // for XojFont
#include "model/Text.h" // for Text
#include "model/XojPage.h" // for XojPage
#include "undo/DeleteUndoAction.h"
#include "undo/InsertUndoAction.h"
#include "undo/TextBoxUndoAction.h"
#include "undo/UndoRedoHandler.h" // for UndoRedoHandler
#include "util/Assert.h"
#include "util/DispatchPool.h"
#include "util/Range.h"
#include "util/glib_casts.h" // for wrap_for_once_v
#include "util/gtk4_helper.h"
#include "util/raii/CStringWrapper.h"
#include "util/safe_casts.h" // for round_cast, as_unsigned
#include "view/overlays/TextEditionView.h"
#include "TextEditorKeyBindings.h"
class UndoAction;
/** GtkTextBuffer helper functions **/
static auto getIteratorAtCursor(GtkTextBuffer* buffer) -> GtkTextIter {
GtkTextIter cursorIter = {nullptr};
gtk_text_buffer_get_iter_at_mark(buffer, &cursorIter, gtk_text_buffer_get_insert(buffer));
return cursorIter;
}
/**
* @brief Compute the byte offset of an iterator in the GtkTextBuffer
*
* NB: This is much faster than relying on g_utf8_offset_to_pointer
*/
static auto getByteOffsetOfIterator(GtkTextIter it) -> int {
// Bytes from beginning of line to iterator
int pos = gtk_text_iter_get_line_index(&it);
gtk_text_iter_set_line_index(&it, 0);
// Count bytes of previous lines
while (gtk_text_iter_backward_line(&it)) {
pos += gtk_text_iter_get_bytes_in_line(&it);
}
return pos;
}
static auto getByteOffsetOfCursor(GtkTextBuffer* buffer) -> int {
return getByteOffsetOfIterator(getIteratorAtCursor(buffer));
}
/**
* @brief Get an iterator at the prescribed byte index.
*
* NB: This is much faster than relying on g_utf8_pointer_to_offset for long texts
*/
static auto getIteratorAtByteOffset(GtkTextBuffer* buf, int byteIndex) {
xoj_assert(byteIndex >= 0);
GtkTextIter it = {nullptr};
gtk_text_buffer_get_start_iter(buf, &it);
// Fast forward to the beginning of the line containing our target destination
for (int linelength = gtk_text_iter_get_bytes_in_line(&it);
linelength <= byteIndex && gtk_text_iter_forward_line(&it);
byteIndex -= std::exchange(linelength, gtk_text_iter_get_bytes_in_line(&it))) {}
if (!gtk_text_iter_is_end(&it)) {
gtk_text_iter_set_line_index(&it, byteIndex);
}
// else { // byteIndex was either past-the-end or pointed to the end }
return it;
}
static auto cloneToCString(GtkTextBuffer* buf) {
GtkTextIter start, end;
gtk_text_buffer_get_bounds(buf, &start, &end);
return xoj::util::OwnedCString::assumeOwnership(gtk_text_iter_get_text(&start, &end));
}
/**
* @brief Clone the buffer's content
*
* This is pretty inefficient: the text gets copied twice
*/
static auto cloneToStdString(GtkTextBuffer* buf) -> std::string { return cloneToCString(buf).get(); }
/**
* @brief Clone the buffer's content and insert a string into the clone
* This makes one less copy operation over using cloneToStdString followed by insert()
* (The text is copied "only" twice, and not three times)
*/
static auto cloneWithInsertToStdString(GtkTextBuffer* buf, std::string_view insertedStr) -> std::string {
GtkTextIter start, end;
gtk_text_buffer_get_bounds(buf, &start, &end);
GtkTextIter insertionPoint = getIteratorAtCursor(buf);
auto firstHalf = xoj::util::OwnedCString::assumeOwnership(gtk_text_iter_get_text(&start, &insertionPoint));
auto secondHalf = xoj::util::OwnedCString::assumeOwnership(gtk_text_iter_get_text(&insertionPoint, &end));
std::string_view str1(firstHalf);
std::string_view str2(secondHalf);
std::string res;
res.reserve(str1.length() + str2.length() + insertedStr.length());
res += str1;
res += insertedStr;
res += str2;
return res;
}
TextEditor::TextEditor(Control* control, const PageRef& page, GtkWidget* xournalWidget, double x, double y):
control(control),
page(page),
xournalWidget(xournalWidget),
imContext(gtk_im_multicontext_new(), xoj::util::adopt),
buffer(gtk_text_buffer_new(nullptr), xoj::util::adopt),
viewPool(std::make_shared<xoj::util::DispatchPool<xoj::view::TextEditionView>>()) {
this->initializeEditionAt(x, y);
g_signal_connect(this->buffer.get(), "paste-done", G_CALLBACK(bufferPasteDoneCallback), this);
{ // Get cursor blinking settings
GtkSettings* settings = gtk_widget_get_settings(this->xournalWidget);
g_object_get(settings, "gtk-cursor-blink", &this->cursorBlink, nullptr);
if (this->cursorBlink) {
int tmp = 0;
g_object_get(settings, "gtk-cursor-blink-time", &tmp, nullptr);
xoj_assert(tmp >= 0);
auto cursorBlinkingPeriod = static_cast<unsigned int>(tmp);
this->cursorBlinkingTimeOn = cursorBlinkingPeriod * CURSOR_ON_MULTIPLIER / CURSOR_DIVIDER;
this->cursorBlinkingTimeOff = cursorBlinkingPeriod - this->cursorBlinkingTimeOn;
}
}
gtk_im_context_set_client_widget(this->imContext.get(), this->xournalWidget);
gtk_im_context_focus_in(this->imContext.get());
g_signal_connect(this->imContext.get(), "commit", G_CALLBACK(iMCommitCallback), this);
g_signal_connect(this->imContext.get(), "preedit-changed", G_CALLBACK(iMPreeditChangedCallback), this);
g_signal_connect(this->imContext.get(), "retrieve-surrounding", G_CALLBACK(iMRetrieveSurroundingCallback), this);
g_signal_connect(this->imContext.get(), "delete-surrounding", G_CALLBACK(imDeleteSurroundingCallback), this);
if (this->originalTextElement) {
// If editing a preexisting text, put the cursor at the right location
this->mousePressed(x - textElement->getX(), y - textElement->getY());
} else if (this->cursorBlink) {
BlinkTimer::callback(this);
} else {
this->cursorVisible = true;
}
}
TextEditor::~TextEditor() {
gtk_im_context_focus_out(this->imContext.get());
this->xournalWidget = nullptr;
control->setCopyCutEnabled(false);
this->contentsChanged(true);
finalizeEdition();
}
auto TextEditor::getViewPool() const -> const std::shared_ptr<xoj::util::DispatchPool<xoj::view::TextEditionView>>& {
return viewPool;
}
auto TextEditor::getTextElement() const -> Text* { return this->textElement.get(); }
bool TextEditor::bufferEmpty() const { return gtk_text_buffer_get_char_count(this->buffer.get()) == 0; }
void TextEditor::replaceBufferContent(const std::string& text) {
gtk_text_buffer_set_text(this->buffer.get(), text.c_str(), -1);
GtkTextIter first = {nullptr};
gtk_text_buffer_get_iter_at_offset(this->buffer.get(), &first, 0);
gtk_text_buffer_place_cursor(this->buffer.get(), &first);
this->layoutStatus = LayoutStatus::NEEDS_COMPLETE_UPDATE;
this->cursorBox = computeCursorBox();
}
void TextEditor::setColor(Color color) {
this->textElement->setColor(color);
repaintEditor(false);
}
void TextEditor::setFont(XojFont font) {
this->textElement->setFont(font);
afterFontChange();
}
void TextEditor::afterFontChange() {
this->textElement->updatePangoFont(this->layout.get());
this->computeVirtualCursorPosition();
this->repaintEditor();
}
void TextEditor::iMCommitCallback(GtkIMContext* context, const gchar* str, TextEditor* te) {
gtk_text_buffer_begin_user_action(te->buffer.get());
bool hadSelection = gtk_text_buffer_get_has_selection(te->buffer.get());
gtk_text_buffer_delete_selection(te->buffer.get(), true, true);
if (!strcmp(str, "\n")) {
if (!gtk_text_buffer_insert_interactive_at_cursor(te->buffer.get(), "\n", 1, true)) {
gtk_widget_error_bell(te->xournalWidget);
} else {
te->contentsChanged(true);
}
} else {
if (!hadSelection && te->cursorOverwrite) {
auto insert = getIteratorAtCursor(te->buffer.get());
if (!gtk_text_iter_ends_line(&insert)) {
te->deleteFromCursor(GTK_DELETE_CHARS, 1);
}
}
if (!gtk_text_buffer_insert_interactive_at_cursor(te->buffer.get(), str, -1, true)) {
gtk_widget_error_bell(te->xournalWidget);
}
}
gtk_text_buffer_end_user_action(te->buffer.get());
te->contentsChanged();
te->repaintEditor();
}
void TextEditor::iMPreeditChangedCallback(GtkIMContext* context, TextEditor* te) {
xoj::util::OwnedCString str;
gint cursor_pos = 0;
GtkTextIter iter = getIteratorAtCursor(te->buffer.get());
{
PangoAttrList* attrs = nullptr;
gtk_im_context_get_preedit_string(context, str.contentReplacer(), &attrs, &cursor_pos);
if (attrs == nullptr) {
attrs = pango_attr_list_new();
}
te->preeditAttrList.reset(attrs, xoj::util::adopt);
}
if (str && str[0] && !gtk_text_iter_can_insert(&iter, true)) {
/*
* Keypress events are passed to input method even if cursor position is
* not editable; so beep here if it's multi-key input sequence, input
* method will be reset in key-press-event handler.
*/
gtk_widget_error_bell(te->xournalWidget);
return;
}
te->preeditString = std::move(str);
te->preeditCursor = cursor_pos;
te->contentsChanged();
te->repaintEditor();
}
auto TextEditor::iMRetrieveSurroundingCallback(GtkIMContext* context, TextEditor* te) -> bool {
GtkTextIter start = getIteratorAtCursor(te->buffer.get());
GtkTextIter end = start;
gint pos = gtk_text_iter_get_line_index(&start);
gtk_text_iter_set_line_offset(&start, 0);
gtk_text_iter_forward_to_line_end(&end);
auto text = xoj::util::OwnedCString::assumeOwnership(gtk_text_iter_get_slice(&start, &end));
gtk_im_context_set_surrounding(context, text.get(), -1, pos);
return true;
}
auto TextEditor::imDeleteSurroundingCallback(GtkIMContext* context, gint offset, gint n_chars, TextEditor* te) -> bool {
GtkTextIter start = getIteratorAtCursor(te->buffer.get());
GtkTextIter end = start;
gtk_text_iter_forward_chars(&start, offset);
gtk_text_iter_forward_chars(&end, offset + n_chars);
gtk_text_buffer_delete_interactive(te->buffer.get(), &start, &end, true);
te->contentsChanged();
te->repaintEditor();
return true;
}
auto TextEditor::onKeyPressEvent(const KeyEvent& event) -> bool {
// IME needs to handle the input first so the candidate window works correctly
auto* e = (GdkEventKey*)(static_cast<GdkEvent*>(event.sourceEvent));
if (gtk_im_context_filter_keypress(this->imContext.get(), e)) {
this->needImReset = true;
GtkTextIter iter = getIteratorAtCursor(this->buffer.get());
bool canInsert = gtk_text_iter_can_insert(&iter, true);
if (canInsert) {
control->getCursor()->setInvisible(true);
} else {
this->resetImContext();
}
return true;
}
return keyBindings.processEvent(this, event);
}
auto TextEditor::onKeyReleaseEvent(const KeyEvent& event) -> bool {
GtkTextIter iter = getIteratorAtCursor(this->buffer.get());
auto* e = (GdkEventKey*)(static_cast<GdkEvent*>(event.sourceEvent));
if (gtk_text_iter_can_insert(&iter, true) && gtk_im_context_filter_keypress(this->imContext.get(), e)) {
this->needImReset = true;
return true;
}
return false;
}
void TextEditor::toggleOverwrite() {
this->cursorOverwrite = !this->cursorOverwrite;
repaintCursorAfterChange();
}
/**
* I know it's a bit rough and duplicated
* Improve that later on...
*/
void TextEditor::decreaseFontSize() {
XojFont& font = textElement->getFont();
if (double size = font.getSize(); size > 1) {
font.setSize(font.getSize() - 1);
afterFontChange();
}
}
void TextEditor::increaseFontSize() {
XojFont& font = textElement->getFont();
font.setSize(font.getSize() + 1);
afterFontChange();
}
void TextEditor::toggleBoldFace() {
// get the current/used font
XojFont& font = textElement->getFont();
std::string fontName = font.getName();
std::size_t found = fontName.find(" Bold");
// toggle bold
if (found == std::string::npos) {
fontName = fontName + " Bold";
} else {
fontName = fontName.erase(found, 5);
}
font.setName(fontName);
afterFontChange();
}
void TextEditor::selectAtCursor(TextEditor::SelectType ty) {
GtkTextIter startPos;
GtkTextIter endPos;
gtk_text_buffer_get_selection_bounds(this->buffer.get(), &startPos, &endPos);
const auto searchFlag = GTK_TEXT_SEARCH_TEXT_ONLY; // To be used to find double newlines
switch (ty) {
case TextEditor::SelectType::WORD: {
auto currentPos = getIteratorAtCursor(this->buffer.get());
if (!gtk_text_iter_inside_word(¤tPos)) {
// Do nothing if cursor is over whitespace
return;
}
if (!gtk_text_iter_starts_word(¤tPos)) {
gtk_text_iter_backward_word_start(&startPos);
}
if (!gtk_text_iter_ends_word(¤tPos)) {
gtk_text_iter_forward_word_end(&endPos);
}
break;
}
case TextEditor::SelectType::PARAGRAPH:
// Note that a GTK "paragraph" is a line, so there's no nice one-liner.
// We define a paragraph as text separated by double newlines.
while (!gtk_text_iter_is_start(&startPos)) {
// There's no GTK function to go to line start, so do it manually.
while (!gtk_text_iter_starts_line(&startPos)) {
if (!gtk_text_iter_backward_word_start(&startPos)) {
break;
}
}
// Check for paragraph start
GtkTextIter searchPos = startPos;
gtk_text_iter_backward_chars(&searchPos, 2);
if (gtk_text_iter_backward_search(&startPos, "\n\n", searchFlag, nullptr, nullptr, &searchPos)) {
break;
}
gtk_text_iter_backward_line(&startPos);
}
while (!gtk_text_iter_ends_line(&endPos)) {
gtk_text_iter_forward_to_line_end(&endPos);
// Check for paragraph end
GtkTextIter searchPos = endPos;
gtk_text_iter_forward_chars(&searchPos, 2);
if (gtk_text_iter_forward_search(&endPos, "\n\n", searchFlag, nullptr, nullptr, &searchPos)) {
break;
}
gtk_text_iter_forward_line(&endPos);
}
break;
case TextEditor::SelectType::ALL:
gtk_text_buffer_get_bounds(this->buffer.get(), &startPos, &endPos);
break;
}
gtk_text_buffer_select_range(this->buffer.get(), &startPos, &endPos);
// Selection highlighting is handled through Pango attributes
this->layoutStatus = LayoutStatus::NEEDS_ATTRIBUTES_UPDATE;
this->repaintEditor(false);
}
void TextEditor::moveCursor(GtkMovementStep step, int count, bool extendSelection) {
resetImContext();
// Not possible, but we have to handle the events, else the page gets scrolled
// if (step == GTK_MOVEMENT_PAGES) {
// if (!gtk_text_view_scroll_pages(text_view, count, extend_selection))
// gtk_widget_error_bell(GTK_WIDGET (text_view));
//
// gtk_text_view_check_cursor_blink(text_view);
// gtk_text_view_pend_cursor_blink(text_view);
// return;
// } else if (step == GTK_MOVEMENT_HORIZONTAL_PAGES) {
// if (!gtk_text_view_scroll_hpages(text_view, count, extend_selection))
// gtk_widget_error_bell(GTK_WIDGET (text_view));
//
// gtk_text_view_check_cursor_blink(text_view);
// gtk_text_view_pend_cursor_blink(text_view);
// return;
// }
GtkTextIter insert = getIteratorAtCursor(this->buffer.get());
GtkTextIter newplace = insert;
bool updateVirtualCursor = true;
switch (step) {
case GTK_MOVEMENT_LOGICAL_POSITIONS: // not used!?
gtk_text_iter_forward_visible_cursor_positions(&newplace, count);
break;
case GTK_MOVEMENT_VISUAL_POSITIONS:
if (count < 0) {
gtk_text_iter_backward_cursor_position(&newplace);
} else {
gtk_text_iter_forward_cursor_position(&newplace);
}
break;
case GTK_MOVEMENT_WORDS:
if (count < 0) {
gtk_text_iter_backward_visible_word_starts(&newplace, -count);
} else if (count > 0) {
if (!gtk_text_iter_forward_visible_word_ends(&newplace, count)) {
gtk_text_iter_forward_to_line_end(&newplace);
}
}
break;
case GTK_MOVEMENT_DISPLAY_LINES:
updateVirtualCursor = false;
jumpALine(&newplace, count);
break;
case GTK_MOVEMENT_PARAGRAPHS:
if (count > 0) {
if (!gtk_text_iter_ends_line(&newplace)) {
gtk_text_iter_forward_to_line_end(&newplace);
--count;
}
gtk_text_iter_forward_visible_lines(&newplace, count);
gtk_text_iter_forward_to_line_end(&newplace);
} else if (count < 0) {
if (gtk_text_iter_get_line_offset(&newplace) > 0) {
gtk_text_iter_set_line_offset(&newplace, 0);
}
gtk_text_iter_forward_visible_lines(&newplace, count);
gtk_text_iter_set_line_offset(&newplace, 0);
}
break;
case GTK_MOVEMENT_DISPLAY_LINE_ENDS:
case GTK_MOVEMENT_PARAGRAPH_ENDS:
if (count > 0) {
if (!gtk_text_iter_ends_line(&newplace)) {
gtk_text_iter_forward_to_line_end(&newplace);
}
} else if (count < 0) {
gtk_text_iter_set_line_offset(&newplace, 0);
}
break;
case GTK_MOVEMENT_BUFFER_ENDS:
if (count > 0) {
gtk_text_buffer_get_end_iter(this->buffer.get(), &newplace);
} else if (count < 0) {
gtk_text_buffer_get_iter_at_offset(this->buffer.get(), &newplace, 0);
}
break;
default:
break;
}
// call moveCursorIterator() even if the cursor hasn't moved, since it cancels the selection
moveCursorIterator(&newplace, extendSelection);
if (updateVirtualCursor) {
computeVirtualCursorPosition();
}
if (gtk_text_iter_equal(&insert, &newplace)) {
gtk_widget_error_bell(this->xournalWidget);
}
}
void TextEditor::findPos(GtkTextIter* iter, double xPos, double yPos) const {
int index = 0;
int trailing = 0;
pango_layout_xy_to_index(this->getUpToDateLayout(), round_cast<int>(xPos * PANGO_SCALE),
round_cast<int>(yPos * PANGO_SCALE), &index, &trailing);
/*
* trailing is non-zero iff the abscissa is past the middle of the grapheme.
* In this case, it contains the length of the grapheme in utf8 char count.
* This way, we put the cursor after the grapheme when clicking past the middle of the grapheme.
*/
*iter = getIteratorAtByteOffset(this->buffer.get(), index);
gtk_text_iter_forward_chars(iter, trailing);
}
void TextEditor::updateTextElementContent() { this->textElement->setText(cloneToStdString(this->buffer.get())); }
void TextEditor::contentsChanged(bool forceCreateUndoAction) {
// Todo: Reinstate text edition undo stack
this->layoutStatus = LayoutStatus::NEEDS_COMPLETE_UPDATE;
this->computeVirtualCursorPosition();
}
void TextEditor::markPos(double x, double y, bool extendSelection) {
GtkTextIter newplace = getIteratorAtCursor(this->buffer.get());
findPos(&newplace, x, y);
// call moveCursorIterator() even if the cursor hasn't moved, since it cancels the selection
moveCursorIterator(&newplace, extendSelection);
computeVirtualCursorPosition();
}
void TextEditor::mousePressed(double x, double y) {
this->mouseDown = true;
// Todo select if SHIFT is pressed
markPos(x, y, false);
}
void TextEditor::mouseMoved(double x, double y) {
if (this->mouseDown) {
markPos(x, y, true);
}
}
void TextEditor::mouseReleased() { this->mouseDown = false; }
void TextEditor::jumpALine(GtkTextIter* textIter, int count) {
int cursorLine = gtk_text_iter_get_line(textIter);
if (cursorLine + count < 0) {
return;
}
PangoLayoutLine* line = pango_layout_get_line_readonly(this->layout.get(), cursorLine + count);
if (line == nullptr) {
return;
}
int index = 0;
int trailing = 0;
pango_layout_line_x_to_index(line, this->virtualCursorAbscissa, &index, &trailing);
/*
* trailing is non-zero iff the abscissa is past the middle of the grapheme.
* In this case, it contains the length of the grapheme in utf8 char count.
*/
*textIter = getIteratorAtByteOffset(this->buffer.get(), index);
gtk_text_iter_forward_chars(textIter, trailing);
}
void TextEditor::computeVirtualCursorPosition() {
int offset = getByteOffsetOfCursor(this->buffer.get());
PangoRectangle rect = {0};
pango_layout_index_to_pos(this->getUpToDateLayout(), offset, &rect);
this->virtualCursorAbscissa = rect.x;
}
void TextEditor::moveCursorIterator(const GtkTextIter* newLocation, gboolean extendSelection) {
bool selectionChanged = true;
if (extendSelection) {
if (auto oldLoc = getIteratorAtCursor(this->buffer.get()); gtk_text_iter_equal(newLocation, &oldLoc)) {
// Nothing changed
return;
}
gtk_text_buffer_move_mark_by_name(this->buffer.get(), "insert", newLocation);
control->setCopyCutEnabled(true);
} else {
// if !extendSelection, we clear the selection even if the cursor does not move
selectionChanged = gtk_text_buffer_get_has_selection(this->buffer.get());
gtk_text_buffer_place_cursor(this->buffer.get(), newLocation);
control->setCopyCutEnabled(false);
}
if (this->cursorBlink) {
// Whenever the cursor moves, the blinking cycle restarts from the start (i.e. the cursor is first shown).
this->cursorVisible = false; // Will be toggled to true by BlinkTimer::callback before the repaint
BlinkTimer::callback(this);
}
if (selectionChanged) {
// The selection background color is set through Pango attributes
this->layoutStatus = LayoutStatus::NEEDS_ATTRIBUTES_UPDATE;
// Repaint the entire box. Computing the exact area that was (un)selected would be better but complicated
this->repaintEditor(false);
} else {
repaintCursorAfterChange();
}
}
void TextEditor::updateCursorBox() {
this->cursorBox = computeCursorBox();
if (!viewPool->empty()) {
// Inform the IM of the cursor location (for word selection popup's location)
// We use the first view as the main view, as far as the IM is concerned
auto box = viewPool->front().toWindowCoordinates(xoj::util::Rectangle<double>(this->cursorBox));
GdkRectangle cursorRect; // cursor position in window coordinates
cursorRect.x = static_cast<int>(box.x);
cursorRect.y = static_cast<int>(box.y);
cursorRect.height = static_cast<int>(box.height);
cursorRect.width = static_cast<int>(box.width);
gtk_im_context_set_cursor_location(this->imContext.get(), &cursorRect);
}
}
static auto whitespace(gunichar ch, gpointer user_data) -> gboolean { return (ch == ' ' || ch == '\t'); }
static auto not_whitespace(gunichar ch, gpointer user_data) -> gboolean { return !whitespace(ch, user_data); }
static auto find_whitepace_region(const GtkTextIter* center, GtkTextIter* start, GtkTextIter* end) -> gboolean {
*start = *center;
*end = *center;
if (gtk_text_iter_backward_find_char(start, not_whitespace, nullptr, nullptr)) {
gtk_text_iter_forward_char(start); /* we want the first whitespace... */
}
if (whitespace(gtk_text_iter_get_char(end), nullptr)) {
gtk_text_iter_forward_find_char(end, not_whitespace, nullptr, nullptr);
}
return !gtk_text_iter_equal(start, end);
}
void TextEditor::deleteFromCursor(GtkDeleteType type, int count) {
this->resetImContext();
if (type == GTK_DELETE_CHARS) {
// Char delete deletes the selection, if one exists
if (gtk_text_buffer_delete_selection(this->buffer.get(), true, true)) {
this->contentsChanged(true);
this->repaintEditor();
return;
}
}
GtkTextIter insert = getIteratorAtCursor(this->buffer.get());
GtkTextIter start = insert;
GtkTextIter end = insert;
switch (type) {
case GTK_DELETE_CHARS:
gtk_text_iter_forward_cursor_positions(&end, count);
break;
case GTK_DELETE_WORD_ENDS:
if (count > 0) {
gtk_text_iter_forward_word_ends(&end, count);
} else if (count < 0) {
gtk_text_iter_backward_word_starts(&start, 0 - count);
}
break;
case GTK_DELETE_WORDS:
break;
case GTK_DELETE_DISPLAY_LINE_ENDS:
break;
case GTK_DELETE_DISPLAY_LINES:
break;
case GTK_DELETE_PARAGRAPH_ENDS:
if (count > 0) {
/* If we're already at a newline, we need to
* simply delete that newline, instead of
* moving to the next one.
*/
if (gtk_text_iter_ends_line(&end)) {
gtk_text_iter_forward_line(&end);
--count;
}
while (count > 0) {
if (!gtk_text_iter_forward_to_line_end(&end)) {
break;
}
--count;
}
} else if (count < 0) {
if (gtk_text_iter_starts_line(&start)) {
gtk_text_iter_backward_line(&start);
if (!gtk_text_iter_ends_line(&end)) {
gtk_text_iter_forward_to_line_end(&start);
}
} else {
gtk_text_iter_set_line_offset(&start, 0);
}
++count;
gtk_text_iter_backward_lines(&start, -count);
}
break;
case GTK_DELETE_PARAGRAPHS:
if (count > 0) {
gtk_text_iter_set_line_offset(&start, 0);
gtk_text_iter_forward_to_line_end(&end);
/* Do the lines beyond the first. */
while (count > 1) {
gtk_text_iter_forward_to_line_end(&end);
--count;
}
}
break;
case GTK_DELETE_WHITESPACE: {
find_whitepace_region(&insert, &start, &end);
} break;
default:
break;
}
if (!gtk_text_iter_equal(&start, &end)) {
gtk_text_buffer_begin_user_action(this->buffer.get());
if (!gtk_text_buffer_delete_interactive(this->buffer.get(), &start, &end, true)) {
gtk_widget_error_bell(this->xournalWidget);
}
gtk_text_buffer_end_user_action(this->buffer.get());
} else {
gtk_widget_error_bell(this->xournalWidget);
}
this->contentsChanged();
this->repaintEditor();
}
void TextEditor::backspace() {
resetImContext();
// Backspace deletes the selection, if one exists
if (gtk_text_buffer_delete_selection(this->buffer.get(), true, true)) {
this->contentsChanged();
this->repaintEditor();
return;
}
GtkTextIter insert = getIteratorAtCursor(this->buffer.get());
if (gtk_text_buffer_backspace(this->buffer.get(), &insert, true, true)) {
this->contentsChanged();
this->repaintEditor();
} else {
gtk_widget_error_bell(this->xournalWidget);
}
}
void TextEditor::linebreak() {
this->resetImContext();
iMCommitCallback(nullptr, "\n", this);
control->getCursor()->setInvisible(true);
}
void TextEditor::tabulation() {
resetImContext();
Settings* settings = control->getSettings();
if (!settings->getUseSpacesAsTab()) {
iMCommitCallback(nullptr, "\t", this);
} else {
std::string indent(static_cast<size_t>(settings->getNumberOfSpacesForTab()), ' ');
iMCommitCallback(nullptr, indent.c_str(), this);
}
control->getCursor()->setInvisible(true);
}
void TextEditor::copyToClipboard() const {
GtkClipboard* clipboard = gtk_widget_get_clipboard(this->xournalWidget);
gtk_text_buffer_copy_clipboard(this->buffer.get(), clipboard);
}
void TextEditor::cutToClipboard() {
GtkClipboard* clipboard = gtk_widget_get_clipboard(this->xournalWidget);
gtk_text_buffer_cut_clipboard(this->buffer.get(), clipboard, true);
this->contentsChanged(true);
this->repaintEditor();
}
void TextEditor::pasteFromClipboard() {
GtkClipboard* clipboard = gtk_widget_get_clipboard(this->xournalWidget);
gtk_text_buffer_paste_clipboard(this->buffer.get(), clipboard, nullptr, true);
}
void TextEditor::bufferPasteDoneCallback(GtkTextBuffer* buffer, GtkClipboard* clipboard, TextEditor* te) {
te->contentsChanged(true);
te->repaintEditor();
}
void TextEditor::resetImContext() {
if (this->needImReset) {
this->needImReset = false;
gtk_im_context_reset(this->imContext.get());
}
}
/*
* Blink!
*/
auto TextEditor::BlinkTimer::callback(TextEditor* te) -> bool {
te->cursorVisible = !te->cursorVisible;
auto time = te->cursorVisible ? te->cursorBlinkingTimeOn : te->cursorBlinkingTimeOff;
te->blinkTimer = gdk_threads_add_timeout(time, xoj::util::wrap_for_once_v<callback>, te);
Range dirtyRange = te->cursorBox;
dirtyRange.translate(te->textElement->getX(), te->textElement->getY());
te->viewPool->dispatch(xoj::view::TextEditionView::FLAG_DIRTY_REGION, dirtyRange);
// Remove ourselves
return false;
}
void TextEditor::setTextToPangoLayout(PangoLayout* pl) const {
std::string_view preed(preeditString);
if (!preed.empty()) {
// When using an Input Method, we need to insert the preeditString into the text at the cursor location
std::string txt = cloneWithInsertToStdString(this->buffer.get(), preed);
int pos = getByteOffsetOfCursor(this->buffer.get());
xoj::util::PangoAttrListSPtr attrlist(pango_attr_list_new(), xoj::util::adopt);
pango_attr_list_splice(attrlist.get(), this->preeditAttrList.get(), pos, static_cast<int>(preed.length()));
pango_layout_set_attributes(pl, attrlist.get());
pango_layout_set_text(pl, txt.c_str(), static_cast<int>(txt.length()));
} else {
setSelectionAttributesToPangoLayout(pl);
pango_layout_set_text(pl, cloneToCString(this->buffer.get()).get(), -1);
}
}
Color TextEditor::getSelectionColor() const { return this->control->getSettings()->getSelectionColor(); }
void TextEditor::setSelectionAttributesToPangoLayout(PangoLayout* pl) const {
xoj::util::PangoAttrListSPtr attrlist(pango_attr_list_new(), xoj::util::adopt);
GtkTextIter start;
GtkTextIter end;
bool hasSelection = gtk_text_buffer_get_selection_bounds(this->buffer.get(), &start, &end);
if (hasSelection) {
auto selectionColorU16 = Util::argb_to_ColorU16(this->getSelectionColor());
PangoAttribute* attrib =
pango_attr_background_new(selectionColorU16.red, selectionColorU16.green, selectionColorU16.blue);
attrib->start_index = static_cast<unsigned int>(getByteOffsetOfIterator(start));
attrib->end_index = static_cast<unsigned int>(getByteOffsetOfIterator(end));
pango_attr_list_insert(attrlist.get(), attrib); // attrlist takes ownership of attrib
}
pango_layout_set_attributes(pl, attrlist.get());
}
auto TextEditor::computeBoundingBox() const -> Range {
/*
* NB: we cannot rely on Text::calcSize directly, since it would not take the size changes due to the IM
* preeditString into account.
*/
int w = 0;
int h = 0;
pango_layout_get_size(getUpToDateLayout(), &w, &h);
double width = (static_cast<double>(w)) / PANGO_SCALE;
double height = (static_cast<double>(h)) / PANGO_SCALE;
double x = textElement->getX();
double y = textElement->getY();
// Warning: width can be negative (e.g. for languages written from right to left)
Range res(x, y);
res.addPoint(x + width, y + height);
return res;
}
auto TextEditor::getUpToDateLayout() const -> PangoLayout* {
switch (layoutStatus) {
case LayoutStatus::NEEDS_COMPLETE_UPDATE:
setTextToPangoLayout(this->layout.get());
break;
case LayoutStatus::NEEDS_ATTRIBUTES_UPDATE:
setSelectionAttributesToPangoLayout(this->layout.get());
break;
case LayoutStatus::UP_TO_DATE:
break;
}
layoutStatus = LayoutStatus::UP_TO_DATE;
return this->layout.get();
}
auto TextEditor::getCursorBox() const -> const Range& { return this->cursorBox; }
auto TextEditor::getContentBoundingBox() const -> const Range& { return this->previousBoundingBox; }
bool TextEditor::isCursorVisible() const { return cursorVisible; }
auto TextEditor::computeCursorBox() const -> Range {
// Compute the bounding box of the active grapheme (i.e. the one just after the cursor)
int offset = getByteOffsetOfCursor(this->buffer.get());
if (this->preeditString && this->preeditCursor != 0) {
const gchar* preeditText = this->preeditString.get();
offset += static_cast<int>(g_utf8_offset_to_pointer(preeditText, preeditCursor) - preeditText);
}
PangoRectangle rect = {0};
pango_layout_index_to_pos(getUpToDateLayout(), offset, &rect);
const double ratio = 1.0 / PANGO_SCALE;
// Warning: rect.width could be negative (e.g. for languages written from right to left).
Range res(rect.x * ratio, rect.y * ratio);
res.addPoint((rect.x + (cursorOverwrite ? rect.width : 0.0)) * ratio, (rect.y + rect.height) * ratio);
return res;
}
void TextEditor::repaintEditor(bool sizeChanged) {
Range dirtyRange(this->previousBoundingBox);
if (sizeChanged) {
this->previousBoundingBox = this->computeBoundingBox();
dirtyRange = dirtyRange.unite(this->previousBoundingBox);
}
this->updateCursorBox();
this->viewPool->dispatch(xoj::view::TextEditionView::FLAG_DIRTY_REGION, dirtyRange);
}
void TextEditor::repaintCursorAfterChange() {
Range dirtyRange = this->cursorBox;
this->updateCursorBox();
dirtyRange = dirtyRange.unite(this->cursorBox);
dirtyRange.translate(this->textElement->getX(), this->textElement->getY());
this->viewPool->dispatch(xoj::view::TextEditionView::FLAG_DIRTY_REGION, dirtyRange);
}
void TextEditor::finalizeEdition() {
Layer* layer = this->page->getSelectedLayer();
UndoRedoHandler* undo = this->control->getUndoRedoHandler();
this->control->setFontSelected(this->control->getSettings()->getFont());
if (this->bufferEmpty()) {
// Delete the edited element from layer
if (originalTextElement) {
auto eraseDeleteUndoAction = std::make_unique<DeleteUndoAction>(page, true);
auto [orig, elementIndex] = layer->removeElement(originalTextElement);
xoj_assert(elementIndex != Element::InvalidIndex);
eraseDeleteUndoAction->addElement(layer, std::move(orig), elementIndex);
undo->addUndoAction(std::move(eraseDeleteUndoAction));
originalTextElement = nullptr;
}
this->viewPool->dispatchAndClear(xoj::view::TextEditionView::FINALIZATION_REQUEST, this->previousBoundingBox);
return;
}
this->updateTextElementContent();
if (originalTextElement) {
// Modifying a preexisting element
this->viewPool->dispatchAndClear(xoj::view::TextEditionView::FINALIZATION_REQUEST, this->previousBoundingBox);
this->originalTextElement->setInEditing(false);
auto [orig, _] = layer->removeElement(this->originalTextElement);
auto ptr = this->textElement.get();
layer->addElement(std::move(this->textElement));
this->page->fireElementChanged(ptr);
undo->addUndoAction(std::make_unique<TextBoxUndoAction>(this->page, layer, ptr, std::move(orig)));
} else {
// Creating a new element
auto ptr = this->textElement.get();
layer->addElement(std::move(this->textElement));
this->viewPool->dispatchAndClear(xoj::view::TextEditionView::FINALIZATION_REQUEST, this->previousBoundingBox);
this->page->fireElementChanged(ptr);
undo->addUndoAction(std::make_unique<InsertUndoAction>(page, layer, ptr));
}
}
void TextEditor::initializeEditionAt(double x, double y) {
// Is there already a textfield?
Text* text = nullptr;
// Should we reverse this loop to select the most recent text rather than the oldest?
for (auto&& e: this->page->getSelectedLayer()->getElements()) {
if (e->getType() == ELEMENT_TEXT) {
GdkRectangle matchRect = {gint(x), gint(y), 1, 1};
if (e->intersectsArea(&matchRect)) {
text = dynamic_cast<Text*>(e.get());
break;
}
}
}
if (text == nullptr) {
ToolHandler* h = this->control->getToolHandler();
this->textElement = std::make_unique<Text>();
this->textElement->setColor(h->getColor());
this->textElement->setFont(control->getSettings()->getFont());
this->textElement->setX(x);
this->textElement->setY(y - this->textElement->getElementHeight() / 2);
if (auto audioController = control->getAudioController(); audioController && audioController->isRecording()) {
fs::path audioFilename = audioController->getAudioFilename();
size_t sttime = audioController->getStartTime();
size_t milliseconds = (as_unsigned(g_get_monotonic_time() / 1000) - sttime);
this->textElement->setTimestamp(milliseconds);
this->textElement->setAudioFilename(audioFilename);
}
this->originalTextElement = nullptr;
} else {
this->control->setFontSelected(text->getFont());
this->originalTextElement = text;
this->textElement = text->cloneText();
text->setInEditing(true);
this->page->fireElementChanged(text);
}
this->layout = this->textElement->createPangoLayout();
this->previousBoundingBox = Range(this->textElement->boundingRect());
this->replaceBufferContent(this->textElement->getText());
}
| 39,584
|
C++
|
.cpp
| 895
| 36.759777
| 120
| 0.650466
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,478
|
EditSelectionContents.cpp
|
xournalpp_xournalpp/src/core/control/tools/EditSelectionContents.cpp
|
#include "EditSelectionContents.h"
#include <algorithm> // for min, max, transform
#include <cmath> // for abs, isnan
#include <iterator> // for back_insert_iterator
#include <limits> // for numeric_limits
#include <memory> // for make_unique, __shar...
#include <utility>
#include <glib.h> // for g_idle_add, g_sourc...
#include "control/Control.h" // for Control
#include "control/settings/Settings.h" // for Settings
#include "control/tools/CursorSelectionType.h" // for CURSOR_SELECTION_TO...
#include "gui/PageView.h" // for XojPageView
#include "gui/XournalView.h" // for XournalView
#include "model/Element.h" // for Element, Element::I...
#include "model/Layer.h" // for Layer
#include "model/LineStyle.h" // for LineStyle
#include "model/Stroke.h" // for Stroke, StrokeTool...
#include "model/Text.h" // for Text
#include "model/XojPage.h" // for XojPage
#include "undo/ColorUndoAction.h" // for ColorUndoAction
#include "undo/DeleteUndoAction.h" // for DeleteUndoAction
#include "undo/FillUndoAction.h" // for FillUndoAction
#include "undo/FontUndoAction.h" // for FontUndoAction
#include "undo/InsertUndoAction.h" // for InsertsUndoAction
#include "undo/LineStyleUndoAction.h" // for LineStyleUndoAction
#include "undo/MoveUndoAction.h" // for MoveUndoAction
#include "undo/RotateUndoAction.h" // for RotateUndoAction
#include "undo/ScaleUndoAction.h" // for ScaleUndoAction
#include "undo/SizeUndoAction.h" // for SizeUndoAction
#include "undo/UndoRedoHandler.h" // for UndoRedoHandler
#include "util/Assert.h" // for xoj_assert
#include "util/glib_casts.h" // for wrap_v
#include "util/safe_casts.h" // for as_signed
#include "util/serializing/ObjectInputStream.h" // for ObjectInputStream
#include "util/serializing/ObjectOutputStream.h" // for ObjectOutputStream
#include "view/ElementContainerView.h" // for ElementContainerView
#include "view/View.h" // for Context
class XojFont;
using std::vector;
using xoj::util::Rectangle;
EditSelectionContents::EditSelectionContents(Rectangle<double> bounds, Rectangle<double> snappedBounds,
const PageRef& sourcePage, Layer* sourceLayer, XojPageView* sourceView):
originalBounds(bounds),
lastBounds(bounds),
lastSnappedBounds(snappedBounds),
sourcePage(sourcePage),
sourceLayer(sourceLayer),
sourceView(sourceView) {
this->restoreLineWidth =
this->getSourceView()->getXournal()->getControl()->getSettings()->getRestoreLineWidthEnabled();
}
EditSelectionContents::~EditSelectionContents() {
if (this->rescaleId) {
g_source_remove(this->rescaleId);
this->rescaleId = 0;
}
deleteViewBuffer();
}
/**
* Add an element to the this selection
*/
void EditSelectionContents::addElement(ElementPtr e, Element::Index order) {
xoj_assert(this->selected.size() == this->insertionOrder.size());
this->selected.emplace_back(e.get());
this->insertionOrder.emplace(std::upper_bound(this->insertionOrder.begin(), this->insertionOrder.end(), order), //
std::move(e), order);
}
void EditSelectionContents::replaceInsertionOrder(InsertionOrder newInsertionOrder) {
this->selected.clear();
this->selected.reserve(newInsertionOrder.size());
std::transform(begin(newInsertionOrder), end(newInsertionOrder), std::back_inserter(this->selected),
[](auto const& e) { return e.e.get(); });
this->insertionOrder = std::move(newInsertionOrder);
}
auto EditSelectionContents::stealInsertionOrder() -> InsertionOrder { return std::move(this->insertionOrder); }
/**
* Returns all containing elements of this selection
*/
auto EditSelectionContents::getElements() const -> std::vector<Element*> const& { return this->selected; }
void EditSelectionContents::forEachElement(std::function<void(Element*)> f) const {
for (auto const& e: this->selected) {
f(e);
}
}
/**
* Returns the insert order of this selection
*/
auto EditSelectionContents::getInsertionOrder() const -> const InsertionOrder& { return this->insertionOrder; }
/**
* Sets the tool size for pen or eraser, returs an undo action
* (or nullptr if nothing is done)
*/
auto EditSelectionContents::setSize(ToolSize size, const double* thicknessPen, const double* thicknessHighlighter,
const double* thicknessEraser) -> UndoActionPtr {
auto undo = std::make_unique<SizeUndoAction>(this->sourcePage, this->sourceLayer);
bool found = false;
for (Element* e: this->selected) {
if (e->getType() == ELEMENT_STROKE) {
auto* s = dynamic_cast<Stroke*>(e);
StrokeTool tool = s->getToolType();
double originalWidth = s->getWidth();
size_t pointCount = s->getPointCount();
vector<double> originalPressure = SizeUndoAction::getPressure(s);
if (tool == StrokeTool::PEN) {
s->setWidth(thicknessPen[size]);
} else if (tool == StrokeTool::HIGHLIGHTER) {
s->setWidth(thicknessHighlighter[size]);
} else if (tool == StrokeTool::ERASER) {
s->setWidth(thicknessEraser[size]);
}
// scale the stroke
double factor = s->getWidth() / originalWidth;
s->scalePressure(factor);
// save the new pressure
vector<double> newPressure = SizeUndoAction::getPressure(s);
undo->addStroke(s, originalWidth, s->getWidth(), originalPressure, newPressure, pointCount);
found = true;
}
}
if (found) {
this->deleteViewBuffer();
this->sourceView->getXournal()->repaintSelection();
return undo;
}
return nullptr;
}
/**
* Fills the stroke, return an undo action
* (Or nullptr if nothing done, e.g. because there is only an image)
*/
auto EditSelectionContents::setFill(int alphaPen, int alphaHighligther) -> UndoActionPtr {
auto undo = std::make_unique<FillUndoAction>(this->sourcePage, this->sourceLayer);
bool found = false;
for (Element* e: this->selected) {
if (e->getType() == ELEMENT_STROKE) {
auto* s = dynamic_cast<Stroke*>(e);
StrokeTool tool = s->getToolType();
int newFill = 128;
if (tool == StrokeTool::PEN) {
newFill = alphaPen;
} else if (tool == StrokeTool::HIGHLIGHTER) {
newFill = alphaHighligther;
} else {
continue;
}
if (newFill == s->getFill()) {
continue;
}
bool originalFill = s->getFill();
s->setFill(newFill);
undo->addStroke(s, originalFill, newFill);
found = true;
}
}
if (found) {
this->deleteViewBuffer();
this->sourceView->getXournal()->repaintSelection();
return undo;
}
return nullptr;
}
/**
* Sets the font of all containing text elements, return an undo action
* (or nullptr if there are no Text elements)
*/
auto EditSelectionContents::setFont(const XojFont& font) -> UndoActionPtr {
double x1 = std::numeric_limits<double>::quiet_NaN();
double x2 = std::numeric_limits<double>::quiet_NaN();
double y1 = std::numeric_limits<double>::quiet_NaN();
double y2 = std::numeric_limits<double>::quiet_NaN();
auto undo = std::make_unique<FontUndoAction>(this->sourcePage, this->sourceLayer);
for (Element* e: this->selected) {
if (e->getType() == ELEMENT_TEXT) {
Text* t = dynamic_cast<Text*>(e);
undo->addStroke(t, t->getFont(), font);
if (std::isnan(x1)) {
x1 = t->getX();
y1 = t->getY();
x2 = t->getX() + t->getElementWidth();
y2 = t->getY() + t->getElementHeight();
} else {
// size with old font
x1 = std::min(x1, t->getX());
y1 = std::min(y1, t->getY());
x2 = std::max(x2, t->getX() + t->getElementWidth());
y2 = std::max(y2, t->getY() + t->getElementHeight());
}
t->setFont(font);
// size with new font
x1 = std::min(x1, t->getX());
y1 = std::min(y1, t->getY());
x2 = std::max(x2, t->getX() + t->getElementWidth());
y2 = std::max(y2, t->getY() + t->getElementHeight());
}
}
if (!std::isnan(x1)) {
this->deleteViewBuffer();
this->sourceView->getXournal()->repaintSelection();
return undo;
}
return nullptr;
}
/**
* Set the line style of all strokes, return an undo action
* (Or nullptr if nothing done)
*/
auto EditSelectionContents::setLineStyle(LineStyle style) -> UndoActionPtr {
auto undo = std::make_unique<LineStyleUndoAction>(this->sourcePage, this->sourceLayer);
bool found = false;
for (Element* e: this->selected) {
if (e->getType() == ELEMENT_STROKE) {
auto s = static_cast<Stroke*>(e);
auto lastLineStyle = s->getLineStyle();
s->setLineStyle(style);
undo->addStroke(s, lastLineStyle, s->getLineStyle());
found = true;
}
}
if (found) {
this->deleteViewBuffer();
this->sourceView->getXournal()->repaintSelection();
return undo;
}
return nullptr;
}
/**
* Set the color of all elements, return an undo action
* (Or nullptr if nothing done, e.g. because there is only an image)
*/
auto EditSelectionContents::setColor(Color color) -> UndoActionPtr {
auto undo = std::make_unique<ColorUndoAction>(this->sourcePage, this->sourceLayer);
bool found = false;
for (Element* e: this->selected) {
if (e->getType() == ELEMENT_TEXT || e->getType() == ELEMENT_STROKE) {
auto lastColor = e->getColor();
e->setColor(color);
undo->addStroke(e, lastColor, e->getColor());
found = true;
}
}
if (found) {
this->deleteViewBuffer();
this->sourceView->getXournal()->repaintSelection();
return undo;
}
return nullptr;
}
/**
* Fills the undo item if the selection is deleted
* the selection is cleared after
*/
void EditSelectionContents::fillUndoItem(DeleteUndoAction* undo) {
Layer* layer = this->sourceLayer;
for (auto& [e, pos]: this->insertionOrder) {
undo->addElement(layer, std::move(e), pos);
}
this->selected.clear();
this->insertionOrder.clear();
}
/**
* Callback to redrawing the buffer asynchron
*/
auto EditSelectionContents::repaintSelection(EditSelectionContents* selection) -> bool {
// delete the selection buffer, force a redraw
selection->deleteViewBuffer();
selection->sourceView->getXournal()->repaintSelection();
selection->rescaleId = 0;
return false;
}
/**
* Delete our internal View buffer,
* it will be recreated when the selection is painted next time
*/
void EditSelectionContents::deleteViewBuffer() {
if (this->crBuffer) {
cairo_surface_destroy(this->crBuffer);
this->crBuffer = nullptr;
}
}
InsertionOrder EditSelectionContents::makeMoveEffective(const xoj::util::Rectangle<double>& bounds,
const xoj::util::Rectangle<double>& snappedBounds,
bool preserveAspectRatio) {
double fx = bounds.width / this->originalBounds.width;
double fy = bounds.height / this->originalBounds.height;
if (preserveAspectRatio) {
double f = (fx + fy) / 2;
fx = f;
fy = f;
}
bool scale = (bounds.width != this->originalBounds.width || bounds.height != this->originalBounds.height);
bool rotate = (std::abs(this->rotation) > std::numeric_limits<double>::epsilon());
double mx = bounds.x - this->originalBounds.x;
double my = bounds.y - this->originalBounds.y;
bool move = mx != 0 || my != 0;
for (auto&& [e, _]: this->insertionOrder) {
if (move) {
e->move(mx, my);
}
if (scale) {
e->scale(bounds.x, bounds.y, fx, fy, 0, this->restoreLineWidth);
}
if (rotate) {
e->rotate(snappedBounds.x + this->lastSnappedBounds.width / 2,
snappedBounds.y + this->lastSnappedBounds.height / 2, this->rotation);
}
}
this->selected.clear();
return std::move(this->insertionOrder);
}
/**
* The contents of the selection
*/
void EditSelectionContents::finalizeSelection(Rectangle<double> bounds, Rectangle<double> snappedBounds,
bool aspectRatio, Layer* destinationLayer) {
xoj_assert(this->selected.size() == this->insertionOrder.size());
for (auto&& [e, index]: this->makeMoveEffective(bounds, snappedBounds, aspectRatio)) {
if (index == Element::InvalidIndex) {
// if the element didn't have a source layer (e.g, clipboard)
g_warning("Invalid index");
destinationLayer->addElement(std::move(e));
} else {
destinationLayer->insertElement(std::move(e), index);
}
}
}
auto EditSelectionContents::getOriginalX() const -> double { return this->originalBounds.x; }
auto EditSelectionContents::getOriginalY() const -> double { return this->originalBounds.y; }
auto EditSelectionContents::getOriginalBounds() const -> Rectangle<double> {
return Rectangle<double>{this->originalBounds};
}
auto EditSelectionContents::getSourceView() -> XojPageView* { return this->sourceView; }
void EditSelectionContents::updateContent(Rectangle<double> bounds, Rectangle<double> snappedBounds, double rotation,
bool aspectRatio, Layer* layer, const PageRef& targetPage,
UndoRedoHandler* undo, CursorSelectionType type) {
double mx = snappedBounds.x - this->lastSnappedBounds.x;
double my = snappedBounds.y - this->lastSnappedBounds.y;
bool move = mx != 0 || my != 0;
this->rotation = rotation;
double fx = snappedBounds.width / this->lastSnappedBounds.width;
double fy = snappedBounds.height / this->lastSnappedBounds.height;
if (aspectRatio) {
double f = (fx + fy) / 2;
fx = f;
fy = f;
}
bool rotate = (std::abs(this->rotation - this->lastRotation) > std::numeric_limits<double>::epsilon());
bool scale = (snappedBounds.width != this->lastSnappedBounds.width ||
snappedBounds.height != this->lastSnappedBounds.height);
if (type == CURSOR_SELECTION_MOVE && move) {
undo->addUndoAction(std::make_unique<MoveUndoAction>(this->sourceLayer, this->sourcePage, this->selected, mx,
my, layer, targetPage));
} else if (type == CURSOR_SELECTION_ROTATE && rotate) {
undo->addUndoAction(std::make_unique<RotateUndoAction>(
this->sourcePage, &this->selected, snappedBounds.x + snappedBounds.width / 2,
snappedBounds.y + snappedBounds.height / 2, rotation - this->lastRotation));
this->rotation = 0; // reset rotation for next usage
this->lastRotation = rotation; // undo one rotation at a time.
}
if (scale) {
// The coordinates of the center of the scaling operation. They depend on the scaling operation performed
double px = this->lastSnappedBounds.x;
double py = this->lastSnappedBounds.y;
switch (type) {
case CURSOR_SELECTION_TOP_LEFT:
[[fallthrough]];
case CURSOR_SELECTION_BOTTOM_LEFT:
[[fallthrough]];
case CURSOR_SELECTION_LEFT:
px += this->lastSnappedBounds.width;
break;
default:
break;
}
switch (type) {
case CURSOR_SELECTION_TOP_LEFT:
[[fallthrough]];
case CURSOR_SELECTION_TOP_RIGHT:
[[fallthrough]];
case CURSOR_SELECTION_TOP:
py += this->lastSnappedBounds.height;
break;
default:
break;
}
// now px and py are the center of the scaling in the rotated coordinate system. We need to rotate them
double cx = this->lastSnappedBounds.x + this->lastSnappedBounds.width / 2;
double cy = this->lastSnappedBounds.y + this->lastSnappedBounds.height / 2;
cairo_matrix_t rotMatrix;
cairo_matrix_init_identity(&rotMatrix);
cairo_matrix_translate(&rotMatrix, cx, cy);
cairo_matrix_rotate(&rotMatrix, this->lastRotation);
cairo_matrix_translate(&rotMatrix, -cx, -cy);
cairo_matrix_transform_point(&rotMatrix, &px, &py);
undo->addUndoAction(std::make_unique<ScaleUndoAction>(this->sourcePage, &this->selected, px, py, fx, fy,
this->lastRotation, restoreLineWidth));
}
this->lastBounds = bounds;
this->lastSnappedBounds = snappedBounds;
this->sourceLayer = layer;
this->sourcePage = targetPage;
}
/**
* paints the selection
*/
void EditSelectionContents::paint(cairo_t* cr, double x, double y, double rotation, double width, double height,
double zoom) {
double fx = width / this->originalBounds.width;
double fy = height / this->originalBounds.height;
if (this->relativeX == -9999999999) {
this->relativeX = x;
this->relativeY = y;
}
if (std::abs(rotation) > std::numeric_limits<double>::epsilon()) {
this->rotation = rotation;
}
if (this->crBuffer == nullptr) {
this->crBuffer = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, static_cast<int>(std::abs(width) * zoom),
static_cast<int>(std::abs(height) * zoom));
cairo_t* cr2 = cairo_create(this->crBuffer);
int dx = static_cast<int>(this->relativeX * zoom);
int dy = static_cast<int>(this->relativeY * zoom);
cairo_translate(cr2, fx < 0 ? -width * zoom : 0, fy < 0 ? -height * zoom : 0);
cairo_scale(cr2, fx, fy);
cairo_translate(cr2, -dx, -dy);
cairo_scale(cr2, zoom, zoom);
xoj::view::ElementContainerView view(this);
view.draw(xoj::view::Context::createDefault(cr2));
cairo_destroy(cr2);
}
cairo_save(cr);
int wImg = cairo_image_surface_get_width(this->crBuffer);
int hImg = cairo_image_surface_get_height(this->crBuffer);
int wTarget = static_cast<int>(std::abs(width) * zoom);
int hTarget = static_cast<int>(std::abs(height) * zoom);
double sx = static_cast<double>(wTarget) / wImg;
double sy = static_cast<double>(hTarget) / hImg;
if (wTarget != wImg || hTarget != hImg || std::abs(rotation) > std::numeric_limits<double>::epsilon()) {
if (!this->rescaleId) {
this->rescaleId = g_idle_add(xoj::util::wrap_v<repaintSelection>, this);
}
cairo_scale(cr, sx, sy);
}
double dx = static_cast<int>(std::min(x, x + width) * zoom / sx);
double dy = static_cast<int>(std::min(y, y + height) * zoom / sy);
cairo_set_source_surface(cr, this->crBuffer, dx, dy);
cairo_paint(cr);
cairo_restore(cr);
}
void EditSelectionContents::serialize(ObjectOutputStream& out) const {
out.writeObject("EditSelectionContents");
out.writeDouble(this->originalBounds.x);
out.writeDouble(this->originalBounds.y);
out.writeDouble(this->originalBounds.width);
out.writeDouble(this->originalBounds.height);
out.writeDouble(this->lastSnappedBounds.x);
out.writeDouble(this->lastSnappedBounds.y);
out.writeDouble(this->lastSnappedBounds.width);
out.writeDouble(this->lastSnappedBounds.height);
out.writeDouble(this->rotation);
out.writeDouble(this->relativeX);
out.writeDouble(this->relativeY);
out.endObject();
}
void EditSelectionContents::readSerialized(ObjectInputStream& in) {
in.readObject("EditSelectionContents");
double originalX = in.readDouble();
double originalY = in.readDouble();
double originalW = in.readDouble();
double originalH = in.readDouble();
this->originalBounds = Rectangle<double>{originalX, originalY, originalW, originalH};
double snappedX = in.readDouble();
double snappedY = in.readDouble();
double snappedW = in.readDouble();
double snappedH = in.readDouble();
this->lastSnappedBounds = Rectangle<double>{snappedX, snappedY, snappedW, snappedH};
this->rotation = in.readDouble();
this->relativeX = in.readDouble();
this->relativeY = in.readDouble();
in.endObject();
}
| 21,394
|
C++
|
.cpp
| 480
| 36.633333
| 119
| 0.618118
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,479
|
VerticalToolHandler.cpp
|
xournalpp_xournalpp/src/core/control/tools/VerticalToolHandler.cpp
|
#include "VerticalToolHandler.h"
#include <algorithm> // for max, min, minmax
#include <memory> // for __shared_ptr_access
#include <cairo.h> // for cairo_fill, cairo_...
#include <gdk/gdkkeysyms.h> // for GDK_KEY_Control_L
#include "control/tools/SnapToGridInputHandler.h" // for SnapToGridInputHan...
#include "gui/LegacyRedrawable.h" // for Redrawable
#include "gui/inputdevices/InputEvents.h" // for KeyEvent
#include "model/Element.h" // for Element
#include "model/Layer.h" // for Layer
#include "model/XojPage.h" // for XojPage
#include "undo/MoveUndoAction.h" // for MoveUndoAction
#include "util/DispatchPool.h"
#include "view/overlays/VerticalToolView.h"
class Settings;
VerticalToolHandler::VerticalToolHandler(const PageRef& page, Settings* settings, double y, bool initiallyReverse):
page(page),
layer(this->page->getSelectedLayer()),
spacingSide(initiallyReverse ? Side::Above : Side::Below),
snappingHandler(settings),
viewPool(std::make_shared<xoj::util::DispatchPool<xoj::view::VerticalToolView>>()) {
double ySnapped = snappingHandler.snapVertically(y, false);
this->startY = ySnapped;
this->endY = ySnapped;
this->adoptElements(this->spacingSide);
}
VerticalToolHandler::~VerticalToolHandler() = default;
void VerticalToolHandler::adoptElements(const Side side) {
this->spacingSide = side;
// Return current elements back to page
for (auto&& e: this->elements) {
this->layer->addElement(std::move(e));
}
this->elements.clear();
// Add new elements based on position
for (Element* e: xoj::refElementContainer(this->layer->getElements())) {
if ((side == Side::Below && e->getY() >= this->startY) ||
(side == Side::Above && e->getY() + e->getElementHeight() <= this->startY)) {
this->elements.push_back(this->layer->removeElement(e).e);
}
}
Range rg = this->ownedElementsOriginalBoundingBox;
this->ownedElementsOriginalBoundingBox = this->computeElementsBoundingBox();
rg = rg.unite(this->ownedElementsOriginalBoundingBox);
if (!rg.empty()) {
this->page->fireRangeChanged(rg);
}
}
void VerticalToolHandler::currentPos(double x, double y) {
double ySnapped = snappingHandler.snapVertically(y, false);
if (this->endY == ySnapped) {
return;
}
this->endY = ySnapped;
this->viewPool->dispatch(xoj::view::VerticalToolView::SET_VERTICAL_SHIFT_REQUEST, ySnapped);
}
bool VerticalToolHandler::onKeyPressEvent(const KeyEvent& event) {
if ((event.keyval == GDK_KEY_Control_L || event.keyval == GDK_KEY_Control_R) && this->spacingSide == Side::Below) {
this->adoptElements(Side::Above);
this->viewPool->dispatch(xoj::view::VerticalToolView::SWITCH_DIRECTION_REQUEST);
return true;
}
return false;
}
bool VerticalToolHandler::onKeyReleaseEvent(const KeyEvent& event) {
if ((event.keyval == GDK_KEY_Control_L || event.keyval == GDK_KEY_Control_R) && this->spacingSide == Side::Above) {
this->adoptElements(Side::Below);
this->viewPool->dispatch(xoj::view::VerticalToolView::SWITCH_DIRECTION_REQUEST);
return true;
}
return false;
}
auto VerticalToolHandler::refElements() const -> std::vector<Element*> {
auto result = std::vector<Element*>(this->elements.size());
std::transform(this->elements.begin(), this->elements.end(), result.begin(), [](auto const& e) { return e.get(); });
return result;
}
void VerticalToolHandler::forEachElement(std::function<void(Element*)> f) const {
for (auto const& e: this->elements) {
f(e.get());
}
}
auto VerticalToolHandler::computeElementsBoundingBox() const -> Range {
Range rg;
for (auto const& e: this->elements) {
rg = rg.unite(Range(e->boundingRect()));
}
return rg;
}
auto VerticalToolHandler::finalize() -> std::unique_ptr<MoveUndoAction> {
// Erase the blue area indicating the shift
this->viewPool->dispatchAndClear(xoj::view::VerticalToolView::FINALIZATION_REQUEST);
if (this->elements.empty()) {
return nullptr;
}
const double dY = this->endY - this->startY;
auto undo = std::make_unique<MoveUndoAction>(this->layer, this->page, this->refElements(), 0, dY, this->layer,
this->page);
for (auto&& e: this->elements) {
e->move(0, dY);
this->layer->addElement(std::move(e));
}
this->elements.clear();
this->ownedElementsOriginalBoundingBox.translate(0, dY);
page->fireRangeChanged(this->ownedElementsOriginalBoundingBox);
return undo;
}
double VerticalToolHandler::getPageWidth() const { return page->getWidth(); }
auto VerticalToolHandler::createView(xoj::view::Repaintable* parent, ZoomControl* zoomControl,
const Settings* settings) const -> std::unique_ptr<xoj::view::OverlayView> {
return std::make_unique<xoj::view::VerticalToolView>(this, parent, zoomControl, settings);
}
| 5,165
|
C++
|
.cpp
| 112
| 40.616071
| 120
| 0.666998
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,480
|
ImageSizeSelection.cpp
|
xournalpp_xournalpp/src/core/control/tools/ImageSizeSelection.cpp
|
#include "ImageSizeSelection.h"
#include "util/Rectangle.h" // for Rectangle
using namespace xoj::view;
ImageSizeSelection::ImageSizeSelection(double x, double y):
startX(x),
startY(y),
endX(x),
endY(y),
viewPool(std::make_shared<xoj::util::DispatchPool<ImageSizeSelectionView>>()) {}
void ImageSizeSelection::updatePosition(double x, double y) {
Range old(startX, startY);
old.addPoint(endX, endY);
old.addPoint(x, y);
this->endX = x;
this->endY = y;
this->viewPool->dispatch(xoj::view::ImageSizeSelectionView::FLAG_DIRTY_REGION, old);
}
auto ImageSizeSelection::getSelectedSpace() const -> xoj::util::Rectangle<double> {
const double width = this->startX < this->endX ? this->endX - this->startX : this->startX - this->endX;
const double height = this->startY < this->endY ? this->endY - this->startY : this->startY - this->endY;
const double x = this->startX < this->endX ? this->startX : this->endX;
const double y = this->startY < this->endY ? this->startY : this->endY;
return {x, y, width, height};
}
void ImageSizeSelection::finalize() {
Range box(startX, startY);
box.addPoint(endX, endY);
this->viewPool->dispatchAndClear(xoj::view::ImageSizeSelectionView::FINALIZATION_REQUEST, box);
}
| 1,301
|
C++
|
.cpp
| 29
| 40.310345
| 108
| 0.689328
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,481
|
RectangleHandler.cpp
|
xournalpp_xournalpp/src/core/control/tools/RectangleHandler.cpp
|
#include "RectangleHandler.h"
#include <algorithm> // for max
#include "control/Control.h" // for Control
#include "control/settings/Settings.h" // for Settings
#include "control/tools/BaseShapeHandler.h" // for BaseShapeHandler
#include "control/tools/SnapToGridInputHandler.h" // for SnapToGridInputHan...
#include "model/Point.h" // for Point
RectangleHandler::RectangleHandler(Control* control, const PageRef& page, bool flipShift, bool flipControl):
BaseShapeHandler(control, page, flipShift, flipControl) {}
RectangleHandler::~RectangleHandler() = default;
auto RectangleHandler::createShape(bool isAltDown, bool isShiftDown, bool isControlDown)
-> std::pair<std::vector<Point>, Range> {
/**
* Snap point to grid (if enabled)
*/
Point c = snappingHandler.snapToGrid(this->currPoint, isAltDown);
double width = c.x - this->startPoint.x;
double height = c.y - this->startPoint.y;
this->modShift = isShiftDown;
this->modControl = isControlDown;
Settings* settings = control->getSettings();
if (settings->getDrawDirModsEnabled()) {
// change modifiers based on draw dir
this->modifyModifiersByDrawDir(width, height, true);
}
if (this->modShift) {
// make square
int signW = width > 0 ? 1 : -1;
int signH = height > 0 ? 1 : -1;
width = std::max(width * signW, height * signH) * signW;
height = (width * signW) * signH;
}
Point p1;
if (!this->modControl) {
p1 = this->startPoint;
} else {
// Control is down - drawing from center
p1 = Point(this->startPoint.x - width, this->startPoint.y - height);
}
Point p2 = Point(this->startPoint.x + width, this->startPoint.y + height);
Range rg(p1.x, p1.y);
rg.addPoint(p2.x, p2.y);
return {{p1, {p1.x, p2.y}, p2, {p2.x, p1.y}, p1}, rg};
}
| 1,946
|
C++
|
.cpp
| 44
| 38.75
| 108
| 0.63964
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,482
|
EraseHandler.cpp
|
xournalpp_xournalpp/src/core/control/tools/EraseHandler.cpp
|
#include "EraseHandler.h"
#include <memory> // for make_unique, unique_ptr
#include <utility> // for move
#include <vector> // for vector
#include <gdk/gdk.h> // for GdkRectangle
#include <glib.h> // for gint
#include "control/ToolEnums.h" // for ERASER_TYPE_DELETE_STROKE
#include "control/ToolHandler.h" // for ToolHandler
#include "gui/LegacyRedrawable.h" // for Redrawable
#include "model/Document.h" // for Document
#include "model/Element.h" // for Element, ELEMENT_STROKE
#include "model/Layer.h" // for Layer
#include "model/Stroke.h" // for Stroke
#include "model/XojPage.h" // for XojPage
#include "model/eraser/ErasableStroke.h" // for ErasableStroke
#include "model/eraser/PaddedBox.h" // for PaddedBox
#include "undo/DeleteUndoAction.h" // for DeleteUndoAction
#include "undo/EraseUndoAction.h" // for EraseUndoAction
#include "undo/UndoRedoHandler.h" // for UndoRedoHandler
#include "util/Range.h" // for Range
#include "util/SmallVector.h" // for SmallVector
EraseHandler::EraseHandler(UndoRedoHandler* undo, Document* doc, const PageRef& page, ToolHandler* handler,
LegacyRedrawable* view):
page(page),
handler(handler),
view(view),
doc(doc),
undo(undo),
eraseDeleteUndoAction(nullptr),
eraseUndoAction(nullptr),
halfEraserSize(0) {}
EraseHandler::~EraseHandler() {
if (this->eraseDeleteUndoAction) {
this->finalize();
}
}
/**
* Handle eraser event: "Delete Stroke" and "Standard", Whiteout is not handled here
*/
void EraseHandler::erase(double x, double y) {
this->halfEraserSize = this->handler->getThickness();
GdkRectangle eraserRect = {gint(x - halfEraserSize), gint(y - halfEraserSize), gint(halfEraserSize * 2),
gint(halfEraserSize * 2)};
Range range(x, y);
Layer* l = page->getSelectedLayer();
for (Element* e: xoj::refElementContainer(l->getElements())) {
if (e->getType() == ELEMENT_STROKE && e->intersectsArea(&eraserRect)) {
eraseStroke(l, dynamic_cast<Stroke*>(e), x, y, range);
}
}
this->view->rerenderRange(range);
}
void EraseHandler::eraseStroke(Layer* l, Stroke* s, double x, double y, Range& range) {
ErasableStroke* erasable = s->getErasable();
if (!erasable) {
if (this->handler->getEraserType() == ERASER_TYPE_DELETE_STROKE) {
if (!s->intersects(x, y, halfEraserSize)) {
// The stroke does not intersect the eraser square
return;
}
// delete the entire stroke
this->doc->lock();
auto [stroke, pos] = l->removeElement(s);
this->doc->unlock();
if (pos == -1) {
return;
}
range.addPoint(s->getX(), s->getY());
range.addPoint(s->getX() + s->getElementWidth(), s->getY() + s->getElementHeight());
// removed the if statement - this prevents us from putting multiple elements into a
// stroke erase operation, but it also prevents the crashing and layer issues!
if (!this->eraseDeleteUndoAction) {
auto eraseDel = std::make_unique<DeleteUndoAction>(this->page, true);
// Todo check dangerous: this->eraseDeleteUndoAction could be a dangling reference
this->eraseDeleteUndoAction = eraseDel.get();
this->undo->addUndoAction(std::move(eraseDel));
}
this->eraseDeleteUndoAction->addElement(l, std::move(stroke), pos);
} else { // Default eraser
auto pos = l->indexOf(s);
if (pos == -1) {
return;
}
const double paddingCoeff = PADDING_COEFFICIENT_CAP[s->getStrokeCapStyle()];
const PaddedBox paddedEraserBox{{x, y}, halfEraserSize, halfEraserSize + paddingCoeff * s->getWidth()};
auto intersectionParameters = s->intersectWithPaddedBox(paddedEraserBox);
if (intersectionParameters.empty()) {
// The stroke does not intersect the eraser square
return;
}
if (this->eraseUndoAction == nullptr) {
auto eraseUndo = std::make_unique<EraseUndoAction>(this->page);
// Todo check dangerous: this->eraseDeleteUndoAction could be a dangling reference
this->eraseUndoAction = eraseUndo.get();
this->undo->addUndoAction(std::move(eraseUndo));
}
doc->lock();
erasable = new ErasableStroke(*s);
s->setErasable(erasable);
doc->unlock();
this->eraseUndoAction->addOriginal(l, s, pos);
erasable->beginErasure(intersectionParameters, range);
}
} else {
/**
* This stroke has already been touched by the eraser
* (Necessarily the default eraser)
*/
auto pos = l->indexOf(s);
if (pos == -1) {
return;
}
const double paddingCoeff = PADDING_COEFFICIENT_CAP[s->getStrokeCapStyle()];
const PaddedBox paddedEraserBox{{x, y}, halfEraserSize, halfEraserSize + paddingCoeff * s->getWidth()};
erasable->erase(paddedEraserBox, range);
}
}
void EraseHandler::finalize() {
if (this->eraseUndoAction) {
this->eraseUndoAction->finalize();
this->eraseUndoAction = nullptr;
} else if (this->eraseDeleteUndoAction) {
this->eraseDeleteUndoAction = nullptr;
}
}
| 5,710
|
C++
|
.cpp
| 125
| 36.816
| 115
| 0.602156
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,483
|
ImageHandler.cpp
|
xournalpp_xournalpp/src/core/control/tools/ImageHandler.cpp
|
#include "ImageHandler.h"
#include <algorithm> // for min
#include <fstream>
#include <memory> // for __shared_ptr_access, make...
#include <sstream>
#include <string> // for string
#include <utility> // for operator==, pair
#include <glib-object.h> // for g_object_unref
#include <glib.h> // for g_error_free, g_free, GError
#include "control/Control.h" // for Control
#include "control/tools/EditSelection.h" // for EditSelection
#include "gui/MainWindow.h" // for MainWindow
#include "gui/PageView.h" // for XojPageView
#include "gui/XournalView.h" // for XournalView
#include "gui/dialog/XojOpenDlg.h" // for showOpenImageDialog
#include "model/Image.h"
#include "model/Layer.h" // for Layer
#include "model/PageRef.h" // for PageRef
#include "model/XojPage.h" // for XojPage
#include "undo/InsertUndoAction.h" // for InsertUndoAction
#include "undo/UndoRedoHandler.h" // for UndoRedoHandler
#include "util/XojMsgBox.h" // for XojMsgBox
#include "util/i18n.h" // for _
#include "util/raii/GObjectSPtr.h" // for GObjectSPtr.h
ImageHandler::ImageHandler(Control* control): control(control) {}
ImageHandler::~ImageHandler() = default;
void ImageHandler::chooseAndCreateImage(std::function<void(std::unique_ptr<Image>)> callback) {
xoj::OpenDlg::showOpenImageDialog(control->getGtkWindow(), control->getSettings(),
[cb = std::move(callback), ctrl = control](fs::path p, bool) {
auto img = ImageHandler::createImageFromFile(p);
if (!img || img->getImageSize() == Image::NOSIZE) {
XojMsgBox::showErrorToUser(ctrl->getGtkWindow(),
_("Failed to load image"));
return;
}
cb(std::move(img));
});
}
auto ImageHandler::createImageFromFile(const fs::path& p) -> std::unique_ptr<Image> {
auto fileToString = [](const fs::path& p) {
// This is the faster file dump I could come up with. Faster by 20% than g_file_load_contents (with -O3)
std::ifstream stream(p);
auto pos = stream.tellg();
stream.seekg(0, std::ios_base::end); // Go to the end
auto size = stream.tellg() - pos; // Get the size
stream.seekg(pos); // Go back
std::string s(as_unsigned(size), 0); // Allocate
stream.read(&s[0], size); // Dump
return s;
};
auto img = std::make_unique<Image>();
try {
img->setImage(fileToString(p));
} catch (const std::ios_base::failure& e) {
std::stringstream msg;
msg << _("Error while opening image file: ") << p.string() << '\n'
<< "Error code: " << e.code() << '\n'
<< "Explanatory string: " << e.what();
XojMsgBox::showErrorToUser(nullptr, msg.str());
return nullptr;
}
// Render the image.
// FIXME: this is horrible. We need an ImageView class...
(void)img->getImage();
return img;
}
bool ImageHandler::addImageToDocument(std::unique_ptr<Image> img, PageRef page, Control* control, bool addUndoAction) {
Layer* layer = page->getSelectedLayer();
if (addUndoAction) {
control->getUndoRedoHandler()->addUndoAction(std::make_unique<InsertUndoAction>(page, layer, img.get()));
}
XournalView* xournal = control->getWindow()->getXournal();
auto pageNr = xournal->getCurrentPage();
auto* view = xournal->getViewFor(pageNr);
if (view->getPage() != page) {
g_warning("Active page changed while you selected the image. Aborting.");
return false;
}
auto sel = SelectionFactory::createFromFloatingElement(control, page, layer, view, std::move(img));
control->getWindow()->getXournal()->setSelection(sel.release());
return true;
}
void ImageHandler::automaticScaling(Image& img, PageRef page) {
double zoom = 1;
double x = img.getX();
double y = img.getY();
auto [width, height] = img.getImageSize();
if (x + width > page->getWidth() || y + height > page->getHeight()) {
double const maxZoomX = (page->getWidth() - x) / width;
double const maxZoomY = (page->getHeight() - y) / height;
zoom = std::min(maxZoomX, maxZoomY);
}
img.setWidth(width * zoom);
img.setHeight(height * zoom);
}
void ImageHandler::insertImageWithSize(PageRef page, const xoj::util::Rectangle<double>& space) {
chooseAndCreateImage([space, page, ctrl = control](std::unique_ptr<Image> img) {
xoj_assert(img);
img->setX(space.x);
img->setY(space.y);
auto [width, height] = img->getImageSize();
if (static_cast<int>(space.width) != 0 && static_cast<int>(space.height) != 0) {
// scale down
const double scaling = std::min(space.height / height, space.width / width);
img->setWidth(scaling * width);
img->setHeight(scaling * height);
// center
if (img->getElementHeight() < space.height) {
img->setY(img->getY() + ((space.height - img->getElementHeight()) * 0.5));
}
if (img->getElementWidth() < space.width) {
img->setX(img->getX() + ((space.width - img->getElementWidth()) * 0.5));
}
} else {
// zero space is selected, scale original image size down to fit on the page
automaticScaling(*img, page);
}
addImageToDocument(std::move(img), page, ctrl, true);
});
}
| 5,855
|
C++
|
.cpp
| 120
| 39.675
| 119
| 0.580911
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,484
|
CoordinateSystemHandler.cpp
|
xournalpp_xournalpp/src/core/control/tools/CoordinateSystemHandler.cpp
|
#include "CoordinateSystemHandler.h"
#include <algorithm> // for max
#include "control/Control.h" // for Control
#include "control/settings/Settings.h" // for Settings
#include "control/tools/BaseShapeHandler.h" // for BaseShapeHandler
#include "control/tools/SnapToGridInputHandler.h" // for SnapToGridInputHan...
#include "gui/XournalView.h" // for XournalView
#include "gui/inputdevices/PositionInputData.h" // for PositionInputData
#include "model/Point.h" // for Point
CoordinateSystemHandler::CoordinateSystemHandler(Control* control, const PageRef& page, bool flipShift,
bool flipControl):
BaseShapeHandler(control, page, flipShift, flipControl) {}
CoordinateSystemHandler::~CoordinateSystemHandler() = default;
/**
* Draw a Cartesian coordinate system.
*
* @param currentPoint The current point the mouse cursor is pointing to.
* @param shiftDown Boolean to indicate if "shift" is currently pressed.
* It is currently not used.
*/
auto CoordinateSystemHandler::createShape(bool isAltDown, bool isShiftDown, bool isControlDown)
-> std::pair<std::vector<Point>, Range> {
/**
* Snap point to grid (if enabled)
*/
Point c = snappingHandler.snapToGrid(this->currPoint, isAltDown);
double width = c.x - this->startPoint.x;
double height = c.y - this->startPoint.y;
this->modShift = isShiftDown;
this->modControl = isControlDown;
Settings* settings = control->getSettings();
if (settings->getDrawDirModsEnabled()) {
// change modifiers based on draw dir
this->modifyModifiersByDrawDir(width, height, true);
}
if (this->modShift) {
// make square
int signW = width > 0 ? 1 : -1;
int signH = height > 0 ? 1 : -1;
width = std::max(width * signW, height * signH) * signW;
height = (width * signW) * signH;
}
const Point& p1 = this->startPoint;
Range rg(p1.x, p1.y);
rg.addPoint(p1.x + width, p1.y + height);
if (!this->modControl) {
// draw out from starting point
return {{p1, Point(p1.x, p1.y + height), Point(p1.x + width, p1.y + height)}, rg};
} else {
// Control is down
return {{Point(p1.x, p1.y + height), p1, Point(p1.x + width, p1.y)}, rg};
}
}
| 2,411
|
C++
|
.cpp
| 53
| 39.792453
| 103
| 0.637255
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,485
|
RulerHandler.cpp
|
xournalpp_xournalpp/src/core/control/tools/RulerHandler.cpp
|
#include "RulerHandler.h"
#include "control/tools/BaseShapeHandler.h" // for BaseShapeHandler
#include "control/tools/SnapToGridInputHandler.h" // for SnapToGridInputHan...
#include "model/Point.h" // for Point
class XournalView;
RulerHandler::RulerHandler(Control* control, const PageRef& page): BaseShapeHandler(control, page) {}
RulerHandler::~RulerHandler() = default;
auto RulerHandler::createShape(bool isAltDown, bool isShiftDown, bool isControlDown)
-> std::pair<std::vector<Point>, Range> {
Point secondPoint = snappingHandler.snap(this->currPoint, this->startPoint, isAltDown);
Range rg(this->startPoint.x, this->startPoint.y);
rg.addPoint(secondPoint.x, secondPoint.y);
return {{this->startPoint, secondPoint}, rg};
}
| 792
|
C++
|
.cpp
| 14
| 53.5
| 101
| 0.730918
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,486
|
StrokeStabilizer.cpp
|
xournalpp_xournalpp/src/core/control/tools/StrokeStabilizer.cpp
|
#include "StrokeStabilizer.h"
#include <algorithm> // for min
#include <iterator> // for begin, end
#include <limits> // for numeric_limits
#include <list> // for list, operator!=
#include <numeric> // for accumulate
#include <vector> // for vector
#include "control/settings/Settings.h" // for Settings
#include "control/tools/StrokeStabilizerEnum.h" // for Preprocessor, Averag...
#include "model/SplineSegment.h" // for SplineSegment
#include "model/Stroke.h" // for Stroke
/**
* StrokeStabilizer::get
*/
auto StrokeStabilizer::get(Settings* settings) -> std::unique_ptr<StrokeStabilizer::Base> {
AveragingMethod averagingMethod = settings->getStabilizerAveragingMethod();
Preprocessor preprocessor = settings->getStabilizerPreprocessor();
if (averagingMethod == AveragingMethod::ARITHMETIC) {
if (preprocessor == Preprocessor::DEADZONE) {
return std::make_unique<StrokeStabilizer::ArithmeticDeadzone>(
settings->getStabilizerFinalizeStroke(), settings->getStabilizerBuffersize(),
settings->getStabilizerDeadzoneRadius(), settings->getStabilizerCuspDetection());
}
if (preprocessor == Preprocessor::INERTIA) {
return std::make_unique<StrokeStabilizer::ArithmeticInertia>(
settings->getStabilizerFinalizeStroke(), settings->getStabilizerBuffersize(),
settings->getStabilizerDrag(), settings->getStabilizerMass());
}
return std::make_unique<StrokeStabilizer::Arithmetic>(settings->getStabilizerFinalizeStroke(),
settings->getStabilizerBuffersize());
}
if (averagingMethod == AveragingMethod::VELOCITY_GAUSSIAN) {
if (preprocessor == Preprocessor::DEADZONE) {
return std::make_unique<StrokeStabilizer::VelocityGaussianDeadzone>(
settings->getStabilizerFinalizeStroke(), settings->getStabilizerSigma(),
settings->getStabilizerDeadzoneRadius(), settings->getStabilizerCuspDetection());
}
if (preprocessor == Preprocessor::INERTIA) {
return std::make_unique<StrokeStabilizer::VelocityGaussianInertia>(
settings->getStabilizerFinalizeStroke(), settings->getStabilizerSigma(),
settings->getStabilizerDrag(), settings->getStabilizerMass());
}
return std::make_unique<StrokeStabilizer::VelocityGaussian>(settings->getStabilizerFinalizeStroke(),
settings->getStabilizerSigma());
}
if (preprocessor == Preprocessor::DEADZONE) {
return std::make_unique<StrokeStabilizer::Deadzone>(settings->getStabilizerFinalizeStroke(),
settings->getStabilizerDeadzoneRadius(),
settings->getStabilizerCuspDetection());
}
if (preprocessor == Preprocessor::INERTIA) {
return std::make_unique<StrokeStabilizer::Inertia>(
settings->getStabilizerFinalizeStroke(), settings->getStabilizerDrag(), settings->getStabilizerMass());
}
/**
* Defaults to no stabilization
*/
return std::make_unique<StrokeStabilizer::Base>();
}
/**
* StrokeStabilizer::Active
*/
void StrokeStabilizer::Active::finalizeStroke() {
if (finalize) {
rebalanceStrokePressures();
Event ev = getLastEvent();
quadraticSplineTo(ev);
}
}
void StrokeStabilizer::Active::quadraticSplineTo(const Event& ev) {
/**
* Using the last two points of the stroke, draw a spline quadratic segment to the coordinates of ev.
*/
Stroke* stroke = strokeHandler->getStroke();
size_t pointCount = stroke->getPointCount();
if (pointCount <= 0) {
return;
}
if (pointCount == 1) {
/**
* Draw a line segment
*/
drawEvent(ev);
return;
}
/**
* Draw a quadratic spline segment, with first tangent vector parallel to AB
*/
Point B = stroke->getPoint(pointCount - 1);
const Point A = stroke->getPoint(pointCount - 2);
const bool usePressure = ev.pressure != Point::NO_PRESSURE && stroke->getToolType().isPressureSensitive();
const Point C(ev.x / zoom, ev.y / zoom, usePressure ? ev.pressure * stroke->getWidth() : Point::NO_PRESSURE);
MathVect vAB = {B.x - A.x, B.y - A.y};
MathVect vBC = {C.x - B.x, C.y - B.y};
const double squaredNormBC = vBC.dx * vBC.dx + vBC.dy * vBC.dy;
const double normBC = std::sqrt(squaredNormBC);
const double normAB = vAB.norm();
if (normBC < std::numeric_limits<double>::epsilon()) {
return;
}
if (normAB < std::numeric_limits<double>::epsilon()) {
g_warning("Last two points of stroke coincide. ");
drawEvent(ev);
return;
}
/**
* The first argument of std::min would give a symmetric quadratic spline segment.
* The std::min and its second argument ensure the spline segment stays reasonably close to its nodes
*/
double distance = std::min(std::abs(squaredNormBC * normAB / (2 * MathVect::scalarProduct(vAB, vBC))), normBC);
/**
* Rebalance the pressure values.
*/
if (usePressure) {
double coeff = normBC / 2 + distance; // Very rough estimation of the spline's length
B.z = (coeff * A.z + normAB * C.z) / (normAB + coeff);
stroke->setLastPressure(B.z);
}
// Quadratic control point
Point Q = B.lineTo(A, -distance);
/**
* The quadratic control point is converted into two cubic control points
*/
Point fp = B.relativeLineTo(Q, 2.0 / 3.0);
Point sp = C.relativeLineTo(Q, 2.0 / 3.0);
SplineSegment spline(B, fp, sp, C);
/**
* TODO Add support for spline segments in Stroke and replace this point sequence by a single spline segment
*/
std::list<Point> pointsToPaint = spline.toPointSequence(usePressure);
pointsToPaint.pop_front(); // Point B has already been painted
for (auto&& point: pointsToPaint) {
strokeHandler->drawSegmentTo(point);
}
strokeHandler->drawSegmentTo(C);
}
/**
* StrokeStabilizer::Deadzone
*/
void StrokeStabilizer::Deadzone::recordFirstEvent(const PositionInputData& pos) {
lastEvent = Event(pos);
lastPaintedEvent = lastEvent;
}
void StrokeStabilizer::Deadzone::processEvent(const PositionInputData& pos) {
/**
* Record the event for the stroke finisher
*/
lastEvent = Event(pos);
MathVect movement = {lastEvent.x - lastPaintedEvent.x, lastEvent.y - lastPaintedEvent.y};
double ratio = deadzoneRadius / movement.norm();
if (ratio >= 1) {
/**
* The event occurred inside the deadzone. Invalidate it.
* Flush the contingent buffer for sharper change of directions
*/
resetBuffer(lastPaintedEvent, pos.timestamp);
return;
}
if (cuspDetection && (MathVect::scalarProduct(movement, lastLiveDirection) < 0)) {
/**
* lastLiveDirection != 0 and the angle between movement and lastLiveDirection is greater than 90°
* We have a clear change of direction. This is a cusp. Draw the entire cusp
*/
/**
* Paint a segment from the stroke's last point to the tip of the cusp.
*/
// drawEvent(lastLiveEvent);
quadraticSplineTo(lastLiveEvent);
/**
* Paint the way back from the tip of the cusp
* To do so, we create an artificial point between lastEvent and lastLiveEvent
*/
MathVect diff = {lastEvent.x - lastLiveEvent.x, lastEvent.y - lastLiveEvent.y};
double diffNorm = diff.norm();
double coeff = deadzoneRadius / diffNorm;
lastLiveDirection.dx = coeff * diff.dx;
lastLiveDirection.dy = coeff * diff.dy;
lastPaintedEvent.x = lastEvent.x - lastLiveDirection.dx;
lastPaintedEvent.y = lastEvent.y - lastLiveDirection.dy;
lastPaintedEvent.pressure = coeff * lastLiveEvent.pressure + (1 - coeff) * lastEvent.pressure;
drawEvent(lastPaintedEvent);
lastLiveEvent = lastEvent;
resetBuffer(lastPaintedEvent, pos.timestamp);
return;
}
/**
* Normal behaviour. Adjust the event's coordinates according to the deadzoneRadius
*/
lastLiveEvent = lastEvent;
lastLiveDirection = movement;
Event ev(lastEvent.x - ratio * movement.dx, lastEvent.y - ratio * movement.dy, lastEvent.pressure);
averageAndPaint(ev, pos.timestamp);
}
void StrokeStabilizer::Deadzone::rebalanceStrokePressures() {
Stroke* stroke = strokeHandler->getStroke();
size_t pointCount = stroke->getPointCount();
if (pointCount >= 3) {
/**
* Smoothen a little bit the pressure variations
*/
stroke->setSecondToLastPressure((stroke->getPoint(pointCount - 2).z + stroke->getPoint(pointCount - 3).z) / 2);
}
}
/**
* StrokeStabilizer::Inertia
*/
void StrokeStabilizer::Inertia::recordFirstEvent(const PositionInputData& pos) {
lastEvent = Event(pos);
lastPaintedEvent = lastEvent;
}
void StrokeStabilizer::Inertia::processEvent(const PositionInputData& pos) {
/**
* Record the event for the stroke finisher
*/
lastEvent = Event(pos);
/**
* Compute the acceleration due to the spring action
*/
MathVect springAcceleration = {(lastEvent.x - lastPaintedEvent.x) / mass,
(lastEvent.y - lastPaintedEvent.y) / mass};
speed.dx = speed.dx * oneMinusDrag + springAcceleration.dx;
speed.dy = speed.dy * oneMinusDrag + springAcceleration.dy;
Event ev(lastPaintedEvent.x + speed.dx, lastPaintedEvent.y + speed.dy, lastEvent.pressure);
averageAndPaint(ev, pos.timestamp);
}
void StrokeStabilizer::Inertia::rebalanceStrokePressures() {
Stroke* stroke = strokeHandler->getStroke();
size_t pointCount = stroke->getPointCount();
if (pointCount >= 3) {
/**
* Smoothen a little bit the pressure variations
*/
stroke->setSecondToLastPressure((stroke->getPoint(pointCount - 2).z + stroke->getPoint(pointCount - 3).z) / 2);
}
}
/**
* StrokeStabilizer::Arithmetic
*/
void StrokeStabilizer::Arithmetic::recordFirstEvent(const PositionInputData& pos) {
eventBuffer.assign(Event(pos)); // Fill the buffer with copies of Event(pos)
}
void StrokeStabilizer::Arithmetic::averageAndPaint(const Event& ev, guint32 timestamp) {
/**
* Push the event and overwrite the oldest event in the buffer
*/
eventBuffer.push_front(ev);
/**
* Average the coordinates using an arithmetic mean
*/
Event sum = std::accumulate(begin(eventBuffer), end(eventBuffer), Event(0, 0, 0), [](auto&& lhs, auto&& rhs) {
return Event(lhs.x + rhs.x, lhs.y + rhs.y, lhs.pressure + rhs.pressure);
});
/**
* Rescale the averaged coordinates and draw
*/
double d = static_cast<double>(eventBuffer.size());
sum.pressure /= d;
sum.x /= d;
sum.y /= d;
setLastPaintedEvent(sum);
drawEvent(sum);
}
auto StrokeStabilizer::Arithmetic::getLastEvent() -> Event { return eventBuffer.front(); }
void StrokeStabilizer::Arithmetic::resetBuffer(Event& ev, guint32 timestamp) {
if (eventBuffer.back() != ev) {
eventBuffer.assign(ev); // Replace the entire content of the buffer with copies of ev
}
}
/**
* StrokeStabilizer::VelocityGaussian
*/
void StrokeStabilizer::VelocityGaussian::recordFirstEvent(const PositionInputData& pos) {
eventBuffer.emplace_front(pos);
lastEventTimestamp = pos.timestamp;
}
void StrokeStabilizer::VelocityGaussian::averageAndPaint(const Event& ev, guint32 timestamp) {
/**
* Compute the velocity (if possible) and push the event to eventBuffer
*/
if (eventBuffer.empty()) {
eventBuffer.emplace_front(ev);
} else {
/**
* Issue: timestamps are in ms. They are not precise enough. Different events can have the same timestamp.
*/
VelocityEvent& last = eventBuffer.front();
guint32 timelaps = timestamp - lastEventTimestamp;
if (timelaps == 0) {
timelaps = 1;
}
eventBuffer.emplace_front(ev, std::hypot(ev.x - last.x, ev.y - last.y) / static_cast<double>(timelaps));
}
lastEventTimestamp = timestamp;
/**
* Average the coordinates using the gimp-like weights
*/
Event weightedSum = {0, 0, 0};
double weight;
double sumOfWeights = 0;
double sumOfVelocities = 0;
auto it = eventBuffer.cbegin();
for (; it != eventBuffer.cend(); ++it) {
/**
* The first weight is always 1
*/
weight = exp(-sumOfVelocities * sumOfVelocities / twoSigmaSquared);
if (weight < 0.01) {
break;
}
sumOfVelocities += (*it).velocity;
weightedSum.x += weight * (*it).x;
weightedSum.y += weight * (*it).y;
weightedSum.pressure += weight * (*it).pressure;
sumOfWeights += weight;
}
eventBuffer.erase(it, eventBuffer.cend());
weightedSum.x /= sumOfWeights;
weightedSum.y /= sumOfWeights;
weightedSum.pressure /= sumOfWeights;
setLastPaintedEvent(weightedSum);
drawEvent(weightedSum);
}
auto StrokeStabilizer::VelocityGaussian::getLastEvent() -> Event {
if (eventBuffer.empty()) {
g_warning("StrokeStabilizer::VelocityGaussian buffer empty. This should never be!");
return Event(0, 0, 0);
}
return eventBuffer.front();
}
void StrokeStabilizer::VelocityGaussian::resetBuffer(Event& ev, guint32 timestamp) {
if (eventBuffer.size() != 1 || lastEventTimestamp != timestamp || eventBuffer.front() != ev) {
eventBuffer.clear();
lastEventTimestamp = timestamp;
eventBuffer.emplace_front(ev);
}
}
| 14,043
|
C++
|
.cpp
| 336
| 34.64881
| 119
| 0.653589
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,487
|
EditSelection.cpp
|
xournalpp_xournalpp/src/core/control/tools/EditSelection.cpp
|
#include "EditSelection.h"
#include <algorithm> // for min, max, stable_sort
#include <cmath> // for abs, cos, sin, cop...
#include <cstddef> // for size_t
#include <limits> // for numeric_limits
#include <memory> // for make_unique, __sha...
#include <numeric> // for reduce
#include <string> // for string
#include <utility>
#include <gdk/gdk.h> // for gdk_cairo_set_sour...
#include "control/Control.h" // for Control
#include "control/settings/Settings.h" // for Settings
#include "control/tools/CursorSelectionType.h" // for CURSOR_SELECTION_NONE
#include "control/tools/SnapToGridInputHandler.h" // for SnapToGridInputHan...
#include "control/zoom/ZoomControl.h" // for ZoomControl
#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/widgets/XournalWidget.h" // for gtk_xournal_get_la...
#include "model/Document.h" // for Document
#include "model/Element.h" // for Element::Index
#include "model/ElementInsertionPosition.h"
#include "model/Layer.h" // for Layer
#include "model/LineStyle.h" // for LineStyle
#include "model/Point.h" // for Point
#include "model/XojPage.h" // for XojPage
#include "undo/ArrangeUndoAction.h" // for ArrangeUndoAction
#include "undo/InsertUndoAction.h" // for InsertsUndoAction
#include "undo/UndoRedoHandler.h" // for UndoRedoHandler
#include "util/Range.h" // for Range
#include "util/Util.h" // for cairo_set_dash_from_vector
#include "util/glib_casts.h" // for wrap_v
#include "util/i18n.h" // for _
#include "util/serializing/ObjectInputStream.h" // for ObjectInputStream
#include "util/serializing/ObjectOutputStream.h" // for ObjectOutputStream
#include "EditSelectionContents.h" // for EditSelectionConte...
#include "Selection.h" // for Selection
class XojFont;
using std::vector;
using xoj::util::Rectangle;
/// Smallest can scale down to, in pixels.
constexpr size_t MINPIXSIZE = 5;
/// Padding for ui buttons
constexpr int DELETE_PADDING = 20;
constexpr int ROTATE_PADDING = 8;
/// Number of times to trigger edge pan timer per second
constexpr unsigned int PAN_TIMER_RATE = 30;
namespace SelectionFactory {
/// @return Bounds and SnappingBounds
static auto computeBoxes(const InsertionOrder& elts) -> std::pair<Range, Range> {
return std::transform_reduce(
elts.begin(), elts.end(), std::pair<Range, Range>(),
[](auto&& p, auto&& q) {
return std::pair<Range, Range>(p.first.unite(q.first), p.second.unite(q.second));
},
[](auto&& e) { return std::make_pair(Range(e.e->boundingRect()), Range(e.e->getSnappedBounds())); });
}
auto createFromFloatingElement(Control* ctrl, const PageRef& page, Layer* layer, XojPageView* view, ElementPtr eOwn)
-> std::unique_ptr<EditSelection> {
auto* e = eOwn.get(); // Order of parameter evaluation is unspecified, eOwn.get() must be evaluated before moving
InsertionOrder i{1};
i[0] = InsertionPosition{std::move(eOwn)};
return std::make_unique<EditSelection>(ctrl, std::move(i), page, layer, view, Range(e->boundingRect()),
Range(e->getSnappedBounds()));
}
auto createFromFloatingElements(Control* ctrl, const PageRef& page, Layer* layer, XojPageView* view,
InsertionOrder elts) -> std::pair<std::unique_ptr<EditSelection>, Range> {
xoj_assert(std::is_sorted(elts.begin(), elts.end()));
auto [bounds, snappingBounds] = computeBoxes(elts);
return std::make_pair(
std::make_unique<EditSelection>(ctrl, std::move(elts), page, layer, view, bounds, snappingBounds), bounds);
}
auto createFromElementOnActiveLayer(Control* ctrl, const PageRef& page, XojPageView* view, Element* e,
Element::Index pos) -> std::unique_ptr<EditSelection> {
Document* doc = ctrl->getDocument();
Layer* layer = nullptr;
InsertionOrder i(1);
i[0] = [&] {
std::lock_guard lock(*doc); // lock scope
layer = page->getSelectedLayer();
return layer->removeElementAt(e, pos);
}();
page->fireElementChanged(e);
return std::make_unique<EditSelection>(ctrl, std::move(i), page, layer, view, Range(e->boundingRect()),
Range(e->getSnappedBounds()));
}
auto createFromElementsOnActiveLayer(Control* ctrl, const PageRef& page, XojPageView* view, InsertionOrderRef elts)
-> std::unique_ptr<EditSelection> {
xoj_assert(std::is_sorted(elts.begin(), elts.end()));
Document* doc = ctrl->getDocument();
Layer* layer = nullptr;
auto ownedElts = [&] {
std::lock_guard lock(*doc); // lock scope
layer = page->getSelectedLayer();
return layer->removeElementsAt(elts);
}();
auto [bounds, snappingBounds] = computeBoxes(ownedElts);
page->fireRangeChanged(bounds);
return std::make_unique<EditSelection>(ctrl, std::move(ownedElts), page, layer, view, bounds, snappingBounds);
}
auto addElementFromActiveLayer(Control* ctrl, EditSelection* base, Element* e, Element::Index pos)
-> std::unique_ptr<EditSelection> {
Document* doc = ctrl->getDocument();
Layer* layer = base->getSourceLayer();
auto ownedElem = [&] {
std::lock_guard lock(*doc); // lock scope
return layer->removeElementAt(e, pos);
}();
pos = ownedElem.pos;
const PageRef& page = base->getSourcePage();
page->fireElementChanged(e);
InsertionOrder elts = base->makeMoveEffective();
xoj_assert(!elts.empty());
xoj_assert(std::is_sorted(elts.begin(), elts.end()));
/**
* To sort out the proper Element::Index of the added element *e, we need to imagine elts were added to the layer,
* so that the index may need to be increased.
* Explicitly, we need to insert (e, pos + n) at position n so that the resulting vector is still sorted. Figuring
* out the value of n requires our own binary search (std::lower_bound won't work).
*/
auto begin = elts.begin(), first = begin, last = elts.end();
while (first != last) {
auto it = std::next(first, std::distance(first, last) / 2);
if (it->pos <= pos + std::distance(begin, it)) {
first = std::next(it);
} else {
last = it;
}
}
ownedElem.pos += std::distance(begin, first);
elts.insert(first, std::move(ownedElem));
xoj_assert(std::is_sorted(elts.begin(), elts.end()));
auto [bounds, snappingBounds] = computeBoxes(elts);
return std::make_unique<EditSelection>(ctrl, std::move(elts), page, layer, base->getView(), bounds, snappingBounds);
}
auto addElementsFromActiveLayer(Control* ctrl, EditSelection* base, const InsertionOrderRef& newElts)
-> std::unique_ptr<EditSelection> {
xoj_assert(std::is_sorted(newElts.begin(), newElts.end()));
Document* doc = ctrl->getDocument();
Layer* layer = base->getSourceLayer();
auto ownedElts = [&] { // lock scope
std::lock_guard lock(*doc);
return layer->removeElementsAt(newElts);
}();
auto [bounds, snappingBounds] = computeBoxes(ownedElts);
const PageRef& page = base->getSourcePage();
page->fireRangeChanged(bounds);
InsertionOrder oldElts = base->makeMoveEffective();
xoj_assert(std::is_sorted(oldElts.begin(), oldElts.end()));
auto [oldBounds, oldSnappingBounds] = computeBoxes(oldElts);
InsertionOrder newSelection;
newSelection.reserve(oldElts.size() + newElts.size());
/**
* To sort out the proper Element::Indices, we need to imagine oldElts were added back to the layer, so that some of
* newElts' would see their indices increase. A simple std::merge won't do. See comment in addElementFromActiveLayer
*/
auto oldIt = oldElts.begin(), oldEnd = oldElts.end();
std::ptrdiff_t shift = 0; // number of elements from oldElts that have been added to newSelection
for (auto newIt = ownedElts.begin(), newEnd = ownedElts.end(); newIt != newEnd;) {
if (oldIt == oldEnd) {
xoj_assert(shift == static_cast<std::ptrdiff_t>(oldElts.size()));
for (; newIt != newEnd; ++newIt) {
newSelection.emplace_back(std::move(newIt->e), newIt->pos + shift);
}
break;
}
if (oldIt->pos < newIt->pos + shift) {
newSelection.emplace_back(std::move(*oldIt));
++oldIt;
++shift;
} else {
newSelection.emplace_back(std::move(newIt->e), newIt->pos + shift);
++newIt;
}
}
std::move(oldIt, oldEnd, std::back_inserter(newSelection));
xoj_assert(newSelection.size() == oldElts.size() + newElts.size());
xoj_assert(std::is_sorted(newSelection.begin(), newSelection.end()));
return std::make_unique<EditSelection>(ctrl, std::move(newSelection), page, layer, base->getView(),
bounds.unite(oldBounds), snappingBounds.unite(oldSnappingBounds));
}
}; // namespace SelectionFactory
EditSelection::EditSelection(Control* ctrl, InsertionOrder elts, const PageRef& page, Layer* layer, XojPageView* view,
const Range& bounds, const Range& snappingBounds):
snappedBounds(snappingBounds),
btnWidth(std::max(10, ctrl->getSettings()->getDisplayDpi() / 8)),
sourcePage(page),
sourceLayer(layer),
view(view),
undo(ctrl->getUndoRedoHandler()),
snappingHandler(ctrl->getSettings()) {
// make the visible bounding box large enough so that anchors do not collapse even for horizontal/vertical strokes
const double PADDING = 12.;
x = bounds.minX - PADDING;
y = bounds.minY - PADDING;
width = bounds.getWidth() + 2 * PADDING;
height = bounds.getHeight() + 2 * PADDING;
this->contents = std::make_unique<EditSelectionContents>(this->getRect(), this->snappedBounds, this->sourcePage,
this->sourceLayer, this->view);
this->contents->replaceInsertionOrder(std::move(elts));
cairo_matrix_init_identity(&this->cmatrix);
this->view->getXournal()->getCursor()->setRotationAngle(0);
this->view->getXournal()->getCursor()->setMirror(false);
for (auto&& e: contents->getElements()) {
this->preserveAspectRatio = this->preserveAspectRatio || e->rescaleOnlyAspectRatio();
this->supportMirroring = this->supportMirroring && e->rescaleWithMirror();
this->supportRotation = this->supportRotation && e->getType() == ELEMENT_STROKE;
}
}
EditSelection::EditSelection(Control* ctrl, const PageRef& page, Layer* layer, XojPageView* view):
snappedBounds(Rectangle<double>{}),
btnWidth(std::max(10, ctrl->getSettings()->getDisplayDpi() / 8)),
sourcePage(page),
sourceLayer(layer),
view(view),
undo(ctrl->getUndoRedoHandler()),
snappingHandler(ctrl->getSettings()) {}
EditSelection::~EditSelection() {
finalizeSelection();
if (this->edgePanHandler) {
g_source_destroy(this->edgePanHandler);
g_source_unref(this->edgePanHandler);
}
}
/**
* Finishes all pending changes, move the elements, scale the elements and add
* them to new layer if any or to the old if no new layer
*/
void EditSelection::finalizeSelection() {
XojPageView* v = getPageViewUnderCursor();
if (v == nullptr) { // Not on any page - move back to original page and position
double ox = this->snappedBounds.x - this->x;
double oy = this->snappedBounds.y - this->y;
this->x = this->contents->getOriginalX();
this->y = this->contents->getOriginalY();
this->snappedBounds.x = this->x + ox;
this->snappedBounds.y = this->y + oy;
v = this->contents->getSourceView();
PageRef page = v->getPage();
Layer* layer = page->getSelectedLayer();
// Create an Undo action to compensate - avoids Segfault/Freeze if the user presses undo after this happened
this->contents->updateContent(this->getRect(), this->snappedBounds, this->rotation, this->preserveAspectRatio,
layer, page, this->undo, CURSOR_SELECTION_MOVE);
}
this->view = v;
PageRef page = this->view->getPage();
Layer* layer = page->getSelectedLayer();
this->contents->finalizeSelection(this->getRect(), this->snappedBounds, this->preserveAspectRatio, layer);
// Calculate new clip region delta due to rotation:
double addW =
std::abs(this->width * cos(this->rotation)) + std::abs(this->height * sin(this->rotation)) - this->width;
double addH =
std::abs(this->width * sin(this->rotation)) + std::abs(this->height * cos(this->rotation)) - this->height;
this->view->rerenderRect(this->x - addW / 2.0, this->y - addH / 2.0, this->width + addW, this->height + addH);
// This is needed if the selection not was 100% on a page
this->view->getXournal()->repaintSelection(true);
}
auto EditSelection::makeMoveEffective() -> InsertionOrder {
return contents->makeMoveEffective(this->getRect(), this->snappedBounds, this->preserveAspectRatio);
}
/**
* get the X coordinate relative to the provided view (getView())
* in document coordinates
*/
auto EditSelection::getXOnView() const -> double { return this->x; }
/**
* get the Y coordinate relative to the provided view (getView())
* in document coordinates
*/
auto EditSelection::getYOnView() const -> double { return this->y; }
auto EditSelection::getOriginalXOnView() -> double { return this->contents->getOriginalX(); }
auto EditSelection::getOriginalYOnView() -> double { return this->contents->getOriginalY(); }
/**
* get the width in document coordinates (multiple with zoom)
*/
auto EditSelection::getWidth() const -> double { return this->width; }
/**
* get the height in document coordinates (multiple with zoom)
*/
auto EditSelection::getHeight() const -> double { return this->height; }
/**
* get the bounding rectangle in document coordinates (multiple with zoom)
*/
auto EditSelection::getRect() const -> Rectangle<double> {
return Rectangle<double>{this->x, this->y, this->width, this->height};
}
/**
* gets the minimal bounding box containing all elements of the selection used for e.g. grid snapping
*/
auto EditSelection::getSnappedBounds() const -> Rectangle<double> { return Rectangle<double>{this->snappedBounds}; }
/**
* get the original bounding rectangle in document coordinates
*/
auto EditSelection::getOriginalBounds() const -> Rectangle<double> {
return Rectangle<double>{this->contents->getOriginalBounds()};
}
/**
* Get the rotation angle of the selection
*/
auto EditSelection::getRotation() const -> double { return this->rotation; }
/**
* Get if the selection supports being rotated
*/
auto EditSelection::isRotationSupported() const -> bool { return this->supportRotation; }
/**
* Get the source page (where the selection was done)
*/
auto EditSelection::getSourcePage() const -> PageRef { return this->sourcePage; }
/**
* Get the source layer (form where the Elements come)
*/
auto EditSelection::getSourceLayer() const -> Layer* { return this->sourceLayer; }
/**
* Get the X coordinate in View coordinates (absolute)
*/
auto EditSelection::getXOnViewAbsolute() const -> int {
double zoom = view->getXournal()->getZoom();
return this->view->getX() + static_cast<int>(this->getXOnView() * zoom);
}
/**
* Get the Y coordinate in View coordinates (absolute)
*/
auto EditSelection::getYOnViewAbsolute() const -> int {
double zoom = view->getXournal()->getZoom();
return this->view->getY() + static_cast<int>(this->getYOnView() * zoom);
}
/**
* Sets the tool size for pen or eraser, returs an undo action
* (or nullptr if nothing is done)
*/
auto EditSelection::setSize(ToolSize size, const double* thicknessPen, const double* thicknessHighlighter,
const double* thicknessEraser) -> UndoActionPtr {
return this->contents->setSize(size, thicknessPen, thicknessHighlighter, thicknessEraser);
}
/**
* Fills the stroke, return an undo action
* (Or nullptr if nothing done, e.g. because there is only an image)
*/
auto EditSelection::setFill(int alphaPen, int alphaHighligther) -> UndoActionPtr {
return this->contents->setFill(alphaPen, alphaHighligther);
}
/**
* Set the line style of all elements, return an undo action
* (Or nullptr if nothing done)
*/
auto EditSelection::setLineStyle(LineStyle style) -> UndoActionPtr { return this->contents->setLineStyle(style); }
/**
* Set the color of all elements, return an undo action
* (Or nullptr if nothing done, e.g. because there is only an image)
*/
auto EditSelection::setColor(Color color) -> UndoActionPtr { return this->contents->setColor(color); }
/**
* Sets the font of all containing text elements, return an undo action
* (or nullptr if there are no Text elements)
*/
auto EditSelection::setFont(const XojFont& font) -> UndoActionPtr { return this->contents->setFont(font); }
/**
* Fills de undo item if the selection is deleted
* the selection is cleared after
*/
void EditSelection::fillUndoItem(DeleteUndoAction* undo) { this->contents->fillUndoItem(undo); }
/**
* Add an element to this selection
*
*/
void EditSelection::addElement(ElementPtr eOwned, Element::Index order) {
auto e = eOwned.get();
this->contents->addElement(std::move(eOwned), order);
this->preserveAspectRatio = this->preserveAspectRatio || e->rescaleOnlyAspectRatio();
this->supportMirroring = this->supportMirroring && e->rescaleWithMirror();
this->supportRotation = this->supportRotation && e->getType() == ELEMENT_STROKE;
}
/**
* Returns all containing elements of this selection
*/
auto EditSelection::getElements() const -> std::vector<Element*> const& { return this->contents->getElements(); }
void EditSelection::forEachElement(std::function<void(Element*)> f) const {
this->contents->forEachElement(std::move(f));
}
/**
* Returns the insert order of this selection
*/
auto EditSelection::getInsertionOrder() const -> const InsertionOrder& { return this->contents->getInsertionOrder(); }
auto EditSelection::rearrangeInsertionOrder(const OrderChange change) -> UndoActionPtr {
InsertionOrder orderOwned = this->contents->stealInsertionOrder();
auto oldOrd = refInsertionOrder(orderOwned);
std::string desc = _("Arrange");
switch (change) {
case OrderChange::BringToFront:
for (auto& [_, i]: orderOwned) {
i = std::numeric_limits<Element::Index>::max();
}
break;
case OrderChange::BringForward:
// Set indices of elements to range from [max(indices) + 1, max(indices) + 1 + num elements)
if (!orderOwned.empty()) {
Element::Index i = orderOwned.back().pos + 1;
for (auto& [_, pos]: orderOwned) {
pos = i++;
}
}
desc = _("Bring forward");
break;
case OrderChange::SendBackward:
// Set indices of elements to range from [min(indices) - 1, min(indices) + num elements - 1)
if (!orderOwned.empty()) {
Element::Index i = orderOwned.front().pos;
i = i > 0 ? i - 1 : 0;
for (auto& [_, pos]: orderOwned) {
pos = i++;
}
}
desc = _("Send backward");
break;
case OrderChange::SendToBack:
Element::Index i = 0;
for (auto& [_, pos]: orderOwned) {
pos = i++;
}
desc = _("Send to back");
break;
}
auto newOrd = refInsertionOrder(orderOwned);
this->contents->replaceInsertionOrder(std::move(orderOwned));
PageRef page = this->view->getPage();
return std::make_unique<ArrangeUndoAction>(page, page->getSelectedLayer(), desc, std::move(oldOrd),
std::move(newOrd));
}
/**
* Finish the current movement
* (should be called in the mouse-button-released event handler)
*/
void EditSelection::mouseUp() {
if (this->mouseDownType == CURSOR_SELECTION_DELETE) {
this->view->getXournal()->deleteSelection();
return;
}
PageRef page = this->view->getPage();
Layer* layer = page->getSelectedLayer();
this->rotation = snappingHandler.snapAngle(this->rotation, false);
this->sourcePage = page;
this->sourceLayer = layer;
this->contents->updateContent(this->getRect(), this->snappedBounds, this->rotation, this->preserveAspectRatio,
layer, page, this->undo, this->mouseDownType);
this->mouseDownType = CURSOR_SELECTION_NONE;
const bool wasEdgePanning = this->isEdgePanning();
this->setEdgePan(false);
updateMatrix();
if (wasEdgePanning) {
this->ensureWithinVisibleArea();
}
}
/**
* Handles mouse input for moving and resizing, coordinates are relative to "view"
*/
void EditSelection::mouseDown(CursorSelectionType type, double x, double y) {
double zoom = this->view->getXournal()->getZoom();
this->mouseDownType = type;
// coordinates relative to top left corner of snapped bounds in coordinate system which is not modified
this->relMousePosX = x / zoom - this->snappedBounds.x;
this->relMousePosY = y / zoom - this->snappedBounds.y;
// coordinates relative to top left corner of snapped bounds in coordinate system which is rotated to make bounding
// box edges horizontal/vertical
cairo_matrix_transform_point(&this->cmatrix, &x, &y);
this->relMousePosRotX = x / zoom - this->snappedBounds.x;
this->relMousePosRotY = y / zoom - this->snappedBounds.y;
}
/**
* Handles mouse input for moving and resizing, coordinates are relative to "view"
*/
void EditSelection::mouseMove(double mouseX, double mouseY, bool alt) {
double zoom = this->view->getXournal()->getZoom();
if (this->mouseDownType == CURSOR_SELECTION_MOVE) {
// compute translation (without snapping)
double dx = mouseX / zoom - this->snappedBounds.x - this->relMousePosX;
double dy = mouseY / zoom - this->snappedBounds.y - this->relMousePosY;
// find corner of reduced bounding box in rotated coordinate system closest to grabbing position
double cx = this->snappedBounds.x;
double cy = this->snappedBounds.y;
if ((this->relMousePosRotX > this->snappedBounds.width / 2) ==
(this->snappedBounds.width > 0)) { // closer to the right side
cx += this->snappedBounds.width;
}
if ((this->relMousePosRotY > this->snappedBounds.height / 2) ==
(this->snappedBounds.height > 0)) { // closer to the lower side
cy += this->snappedBounds.height;
}
// compute corner of reduced bounding box in unmodified coordinate system closest to grabbing position
cairo_matrix_t inv = this->cmatrix;
cairo_matrix_invert(&inv);
cx *= zoom;
cy *= zoom;
cairo_matrix_transform_point(&inv, &cx, &cy);
cx /= zoom;
cy /= zoom;
// compute position where unsnapped corner would move
Point p = Point(cx + dx, cy + dy);
// snap this corner
p = snappingHandler.snapToGrid(p, alt);
// move
if (!this->edgePanInhibitNext) {
moveSelection(p.x - cx, p.y - cy);
this->setEdgePan(true);
} else {
this->edgePanInhibitNext = false;
}
} else if (this->mouseDownType == CURSOR_SELECTION_ROTATE && supportRotation) { // catch rotation here
double rdx = mouseX / zoom - this->snappedBounds.x - this->snappedBounds.width / 2;
double rdy = mouseY / zoom - this->snappedBounds.y - this->snappedBounds.height / 2;
double angle = atan2(rdy, rdx);
this->rotation = angle;
this->view->getXournal()->getCursor()->setRotationAngle(180 / M_PI * angle);
} else {
// Translate mouse position into rotated coordinate system:
double rx = mouseX;
double ry = mouseY;
cairo_matrix_transform_point(&this->cmatrix, &rx, &ry);
rx /= zoom;
ry /= zoom;
double minSize = MINPIXSIZE / zoom;
// store pull direction value
int xSide = 0;
int ySide = 0;
if (this->mouseDownType == CURSOR_SELECTION_TOP_LEFT) {
xSide = -1;
ySide = -1;
} else if (this->mouseDownType == CURSOR_SELECTION_TOP_RIGHT) {
xSide = 1;
ySide = -1;
} else if (this->mouseDownType == CURSOR_SELECTION_BOTTOM_LEFT) {
xSide = -1;
ySide = 1;
} else if (this->mouseDownType == CURSOR_SELECTION_BOTTOM_RIGHT) {
xSide = 1;
ySide = 1;
} else if (this->mouseDownType == CURSOR_SELECTION_TOP) {
ySide = -1;
} else if (this->mouseDownType == CURSOR_SELECTION_BOTTOM) {
ySide = 1;
} else if (this->mouseDownType == CURSOR_SELECTION_LEFT) {
xSide = -1;
} else if (this->mouseDownType == CURSOR_SELECTION_RIGHT) {
xSide = 1;
}
// sanity check
if (xSide || ySide) {
// get normalized direction vector for input interpretation (dependent on aspect ratio)
double diag = hypot(xSide * this->width, ySide * this->height);
double nx = xSide * this->width / diag;
double ny = ySide * this->height / diag;
int xMul = (xSide + 1) / 2;
int yMul = (ySide + 1) / 2;
double xOffset =
(rx - this->x) - this->width * xMul; // x-offset from corner/side that is used for resizing
double yOffset =
(ry - this->y) - this->height * yMul; // y-offset from corner/side that is used for resizing
// calculate scale factor using dot product
double f = (xOffset * nx + yOffset * ny + diag) / diag;
f = std::copysign(std::max(std::abs(f), minSize / std::min(std::abs(this->width), std::abs(this->height))),
f);
if (supportMirroring || f > 0) {
scaleShift(xSide ? f : 1, ySide ? f : 1, xSide == -1, ySide == -1);
// in each case first scale without snapping consideration then snap
// take care that wSnap and hSnap are not too small
double snappedX =
snappingHandler.snapHorizontally(this->snappedBounds.x + this->snappedBounds.width * xMul, alt);
double snappedY =
snappingHandler.snapVertically(this->snappedBounds.y + this->snappedBounds.height * yMul, alt);
double dx = snappedX - this->snappedBounds.x - this->snappedBounds.width * xMul;
double dy = snappedY - this->snappedBounds.y - this->snappedBounds.height * yMul;
double fx = (std::abs(this->snappedBounds.width) > minSize) ?
(this->snappedBounds.width + dx * xSide) / this->snappedBounds.width :
1;
double fy = (std::abs(this->snappedBounds.height) > minSize) ?
(this->snappedBounds.height + dy * ySide) / this->snappedBounds.height :
1;
f = (((std::abs(dx) < std::abs(dy)) && (fx != 1)) || fy == 1) ? fx : fy;
f = (std::abs(this->width) * std::abs(f) < minSize || std::abs(this->height) * std::abs(f) < minSize) ?
1 :
f;
scaleShift(xSide ? f : 1, ySide ? f : 1, xSide == -1, ySide == -1);
this->view->getXournal()->getCursor()->setMirror(this->width * this->height < 0);
}
}
}
this->view->getXournal()->repaintSelection();
if (this->mouseDownType == CURSOR_SELECTION_MOVE) {
XojPageView* v = getPageViewUnderCursor();
if (v && v != this->view) {
XournalView* xournal = this->view->getXournal();
const auto pageNr = xournal->getControl()->getDocument()->indexOf(v->getPage());
xournal->pageSelected(pageNr);
translateToView(v);
}
}
}
// scales with scale factors fx and fy fixing the corner of the reduced bounding box defined by changeLeft and
// changeTop
void EditSelection::scaleShift(double fx, double fy, bool changeLeft, bool changeTop) {
double dx = (changeLeft) ? this->snappedBounds.width * (1 - fx) : 0;
double dy = (changeTop) ? this->snappedBounds.height * (1 - fy) : 0;
this->width *= fx;
this->height *= fy;
this->snappedBounds.width *= fx;
this->snappedBounds.height *= fy;
this->x += dx + (this->x - this->snappedBounds.x) * (fx - 1);
this->y += dy + (this->y - this->snappedBounds.y) * (fy - 1);
this->snappedBounds.x += dx;
this->snappedBounds.y += dy;
// compute new rotation center
double cx = this->snappedBounds.x + this->snappedBounds.width / 2;
double cy = this->snappedBounds.y + this->snappedBounds.height / 2;
// transform it back with old rotation center
double zoom = this->view->getXournal()->getZoom();
double cxRot = cx * zoom;
double cyRot = cy * zoom;
cairo_matrix_t inv = this->cmatrix;
cairo_matrix_invert(&inv);
cairo_matrix_transform_point(&inv, &cxRot, &cyRot);
cxRot /= zoom;
cyRot /= zoom;
// move to compensate for changed rotation centers
moveSelection(cxRot - cx, cyRot - cy);
}
auto EditSelection::getPageViewUnderCursor() -> XojPageView* {
double zoom = view->getXournal()->getZoom();
// get grabbing hand position
double hx = this->view->getX() + (this->snappedBounds.x + this->relMousePosX) * zoom;
double hy = this->view->getY() + (this->snappedBounds.y + this->relMousePosY) * zoom;
Layout* layout = gtk_xournal_get_layout(this->view->getXournal()->getWidget());
XojPageView* v = layout->getPageViewAt(static_cast<int>(hx), static_cast<int>(hy));
return v;
}
/**
* Translate all coordinates which are relative to the current view to the new view,
* and set the attribute view to the new view
*/
void EditSelection::translateToView(XojPageView* v) {
double zoom = view->getXournal()->getZoom();
double ox = this->snappedBounds.x - this->x;
double oy = this->snappedBounds.y - this->y;
int aX1 = getXOnViewAbsolute();
int aY1 = getYOnViewAbsolute();
this->x = (aX1 - v->getX()) / zoom;
this->y = (aY1 - v->getY()) / zoom;
this->snappedBounds.x = this->x + ox;
this->snappedBounds.y = this->y + oy;
this->view = v;
// int aX2 = getXOnViewAbsolute();
// int aY2 = getYOnViewAbsolute();
//
// if (aX1 != aX2)
// {
// g_message("aX1 != aX2!! %i / %i", aX1, aX2);
// }
// if (aY1 != aY2)
// {
// g_message("aY1 != aY2!! %i / %i", aY1, aY2);
// }
}
void EditSelection::copySelection() {
// clone elements in the insert order
auto const& orig = getInsertionOrder();
InsertionOrder clonedInsertionOrder;
clonedInsertionOrder.reserve(orig.size());
for (const auto& [e, index]: orig) {
clonedInsertionOrder.emplace_back(e->clone(), index);
}
// apply transformations and add to layer
finalizeSelection();
// restore insert order
contents->replaceInsertionOrder(std::move(clonedInsertionOrder));
// add undo action
PageRef page = this->view->getPage();
Layer* layer = page->getSelectedLayer();
undo->addUndoAction(std::make_unique<InsertsUndoAction>(page, layer, getElements()));
}
/**
* If the selection should moved (or rescaled)
*/
auto EditSelection::isMoving() -> bool { return this->mouseDownType != CURSOR_SELECTION_NONE; }
/**
* Move the selection
*/
void EditSelection::updateMatrix() {
double zoom = this->view->getXournal()->getZoom();
// store rotation matrix for pointer use; the center of the rotation is the center of the bounding box
double rx = (this->snappedBounds.x + this->snappedBounds.width / 2) * zoom;
double ry = (this->snappedBounds.y + this->snappedBounds.height / 2) * zoom;
cairo_matrix_init_identity(&this->cmatrix);
cairo_matrix_translate(&this->cmatrix, rx, ry);
cairo_matrix_rotate(&this->cmatrix, -this->rotation);
cairo_matrix_translate(&this->cmatrix, -rx, -ry);
}
void EditSelection::moveSelection(double dx, double dy, bool addMoveUndo) {
this->x += dx;
this->y += dy;
this->snappedBounds.x += dx;
this->snappedBounds.y += dy;
updateMatrix();
if (addMoveUndo) {
XojPageView* v = getPageViewUnderCursor();
if (v && v != this->view) {
XournalView* xournal = this->view->getXournal();
const auto pageNr = xournal->getControl()->getDocument()->indexOf(v->getPage());
xournal->pageSelected(pageNr);
translateToView(v);
}
this->contents->updateContent(this->getRect(), this->snappedBounds, this->rotation, this->preserveAspectRatio,
this->view->getPage()->getSelectedLayer(), this->view->getPage(), this->undo,
CURSOR_SELECTION_MOVE);
}
this->view->getXournal()->repaintSelection();
}
void EditSelection::setEdgePan(bool pan) {
if (pan && !this->edgePanHandler) {
this->edgePanHandler = g_timeout_source_new(1000 / PAN_TIMER_RATE);
g_source_set_callback(this->edgePanHandler, xoj::util::wrap_v<EditSelection::handleEdgePan>, this, nullptr);
g_source_attach(this->edgePanHandler, nullptr);
} else if (!pan && this->edgePanHandler) {
g_source_destroy(this->edgePanHandler);
g_source_unref(this->edgePanHandler);
this->edgePanHandler = nullptr;
this->edgePanInhibitNext = false;
}
}
bool EditSelection::isEdgePanning() const { return this->edgePanHandler; }
bool EditSelection::handleEdgePan(EditSelection* self) {
if (self->view->getXournal()->getControl()->getZoomControl()->isZoomPresentationMode()) {
self->setEdgePan(false);
return false;
}
Layout* layout = gtk_xournal_get_layout(self->view->getXournal()->getWidget());
const Settings* const settings = self->getView()->getXournal()->getControl()->getSettings();
const double zoom = self->view->getXournal()->getZoom();
// Helper function to compute scroll amount for a single dimension, based on visible region and selection bbox
const auto computeScrollAmt = [&](double visMin, double visLen, double bboxMin, double bboxLen, double layoutSize,
double relMousePos) -> double {
const bool belowMin = bboxMin < visMin;
const bool aboveMax = bboxMin + bboxLen > visMin + visLen;
const double visMax = visMin + visLen;
const double bboxMax = bboxMin + bboxLen;
const bool isLargeSelection = bboxLen > visLen;
const auto centerVis = (visMin + visLen / 2);
const auto mouseDiff = (bboxMin + relMousePos * zoom - centerVis);
// Scroll amount multiplier
double mult = 0.0;
const double maxMult = settings->getEdgePanMaxMult();
int panDir = 0;
// If the selection is larger than the view, scroll based on mouse position relative to the center of the
// visible view Otherwise calculate bonus scroll amount due to proportion of selection out of view.
if (isLargeSelection) {
mult = maxMult * std::abs(mouseDiff) / (visLen);
if (mouseDiff > 0.1 * visLen / 2.0) {
panDir = 1;
} else if (mouseDiff < -0.1 * visLen / 2.0) {
panDir = -1;
}
} else {
if (aboveMax) {
panDir = 1;
mult = maxMult * std::min(bboxLen, bboxMax - visMax) / bboxLen;
} else if (belowMin) {
panDir = -1;
mult = maxMult * std::min(bboxLen, visMin - bboxMin) / bboxLen;
}
}
// Base amount to translate selection (in document coordinates) per timer tick
const double panSpeed = settings->getEdgePanSpeed();
const double translateAmt = visLen * panSpeed / (100.0 * PAN_TIMER_RATE);
// Amount to scroll the visible area by (in layout coordinates), accounting for multiplier
double layoutScroll = zoom * panDir * (translateAmt * mult);
// If scrolling past layout boundaries, clamp scroll amount to boundary
if (visMin + layoutScroll < 0) {
layoutScroll = -visMin;
} else if (visMax + layoutScroll > layoutSize) {
layoutScroll = std::max(0.0, layoutSize - visMax);
}
return layoutScroll;
};
// Compute scroll (for layout) and translation (for selection) for x and y
const int layoutWidth = layout->getMinimalWidth();
const int layoutHeight = layout->getMinimalHeight();
const auto visRect = layout->getVisibleRect();
const auto bbox = self->getBoundingBoxInView();
const auto layoutScrollX =
computeScrollAmt(visRect.x, visRect.width, bbox.x, bbox.width, layoutWidth, self->relMousePosX);
const auto layoutScrollY =
computeScrollAmt(visRect.y, visRect.height, bbox.y, bbox.height, layoutHeight, self->relMousePosY);
const auto translateX = layoutScrollX / zoom;
const auto translateY = layoutScrollY / zoom;
// Perform the scrolling
bool edgePanned = false;
if (self->isMoving() && (layoutScrollX != 0.0 || layoutScrollY != 0.0)) {
layout->scrollRelative(layoutScrollX, layoutScrollY);
self->moveSelection(translateX, translateY);
edgePanned = true;
// To prevent the selection from jumping and to reduce jitter, block the selection movement triggered by user
// input
self->edgePanInhibitNext = true;
} else {
// No panning, so disable the timer.
self->setEdgePan(false);
}
return edgePanned;
}
auto EditSelection::getBoundingBoxInView() const -> Rectangle<double> {
int viewx = this->view->getX();
int viewy = this->view->getY();
double zoom = this->view->getXournal()->getZoom();
double sin = std::sin(this->rotation);
double cos = std::cos(this->rotation);
double w = std::abs(this->width * cos) + std::abs(this->height * sin);
double h = std::abs(this->width * sin) + std::abs(this->height * cos);
double cx = this->x + this->width / 2.0;
double cy = this->y + this->height / 2.0;
double minx = cx - w / 2.0;
double miny = cy - h / 2.0;
return {viewx + minx * zoom, viewy + miny * zoom, w * zoom, h * zoom};
}
void EditSelection::ensureWithinVisibleArea() {
const Rectangle<double> viewRect = this->getBoundingBoxInView();
// need to modify this to take into account the position
// of the object, plus typecast because XojPageView takes ints
this->view->getXournal()->ensureRectIsVisible(static_cast<int>(viewRect.x), static_cast<int>(viewRect.y),
static_cast<int>(viewRect.width), static_cast<int>(viewRect.height));
}
/**
* Get the cursor type for the current position (if 0 then the default cursor should be used)
*/
auto EditSelection::getSelectionTypeForPos(double x, double y, double zoom) -> CursorSelectionType {
double x1 = getXOnView() * zoom;
double x2 = x1 + this->width * zoom;
double y1 = getYOnView() * zoom;
double y2 = y1 + this->height * zoom;
double xmin = std::min(x1, x2);
double xmax = std::max(x1, x2);
double ymin = std::min(y1, y2);
double ymax = std::max(y1, y2);
cairo_matrix_transform_point(&this->cmatrix, &x, &y);
const int EDGE_PADDING = (this->btnWidth / 2) + 2;
const int BORDER_PADDING = (this->btnWidth / 2);
if (x1 - EDGE_PADDING <= x && x <= x1 + EDGE_PADDING && y1 - EDGE_PADDING <= y && y <= y1 + EDGE_PADDING) {
return CURSOR_SELECTION_TOP_LEFT;
}
if (x2 - EDGE_PADDING <= x && x <= x2 + EDGE_PADDING && y1 - EDGE_PADDING <= y && y <= y1 + EDGE_PADDING) {
return CURSOR_SELECTION_TOP_RIGHT;
}
if (x1 - EDGE_PADDING <= x && x <= x1 + EDGE_PADDING && y2 - EDGE_PADDING <= y && y <= y2 + EDGE_PADDING) {
return CURSOR_SELECTION_BOTTOM_LEFT;
}
if (x2 - EDGE_PADDING <= x && x <= x2 + EDGE_PADDING && y2 - EDGE_PADDING <= y && y <= y2 + EDGE_PADDING) {
return CURSOR_SELECTION_BOTTOM_RIGHT;
}
if (xmin - (DELETE_PADDING + this->btnWidth) - BORDER_PADDING <= x &&
x <= xmin - (DELETE_PADDING + this->btnWidth) + BORDER_PADDING && y1 - BORDER_PADDING <= y &&
y <= y1 + BORDER_PADDING) {
return CURSOR_SELECTION_DELETE;
}
if (supportRotation && xmax - BORDER_PADDING + ROTATE_PADDING + this->btnWidth <= x &&
x <= xmax + BORDER_PADDING + ROTATE_PADDING + this->btnWidth && (y2 + y1) / 2 - 4 - BORDER_PADDING <= y &&
(y2 + y1) / 2 + 4 + BORDER_PADDING >= y) {
return CURSOR_SELECTION_ROTATE;
}
if (!this->preserveAspectRatio) {
if (xmin <= x && x <= xmax) {
if (y1 - BORDER_PADDING <= y && y <= y1 + BORDER_PADDING) {
return CURSOR_SELECTION_TOP;
}
if (y2 - BORDER_PADDING <= y && y <= y2 + BORDER_PADDING) {
return CURSOR_SELECTION_BOTTOM;
}
}
if (ymin <= y && y <= ymax) {
if (x1 - BORDER_PADDING <= x && x <= x1 + BORDER_PADDING) {
return CURSOR_SELECTION_LEFT;
}
if (x2 - BORDER_PADDING <= x && x <= x2 + BORDER_PADDING) {
return CURSOR_SELECTION_RIGHT;
}
}
}
if (xmin <= x && x <= xmax && ymin <= y && y <= ymax) {
return CURSOR_SELECTION_MOVE;
}
return CURSOR_SELECTION_NONE;
}
/**
* Paints the selection to cr, with the given zoom factor. The coordinates of cr
* should be relative to the provided view by getView() (use translateEvent())
*/
void EditSelection::paint(cairo_t* cr, double zoom) {
double x = this->x;
double y = this->y;
if (std::abs(this->rotation) > std::numeric_limits<double>::epsilon()) {
this->rotation = snappingHandler.snapAngle(this->rotation, false);
double rx = (snappedBounds.x + snappedBounds.width / 2) * zoom;
double ry = (snappedBounds.y + snappedBounds.height / 2) * zoom;
cairo_translate(cr, rx, ry);
cairo_rotate(cr, this->rotation);
// Draw the rotation point for debugging
// cairo_set_source_rgb(cr, 0, 1, 0);
// cairo_rectangle(cr, 0, 0, 10, 10);
// cairo_stroke(cr);
cairo_translate(cr, -rx, -ry);
}
this->contents->paint(cr, x, y, this->rotation, this->width, this->height, zoom);
cairo_set_operator(cr, CAIRO_OPERATOR_OVER);
GdkRGBA selectionColor = view->getSelectionColor();
// set the line always the same size on display
cairo_set_line_width(cr, 1);
const std::vector<double> dashes = {10.0, 10.0};
Util::cairo_set_dash_from_vector(cr, dashes, 0);
gdk_cairo_set_source_rgba(cr, &selectionColor);
cairo_rectangle(cr, std::min(x, x + width) * zoom, std::min(y, y + height) * zoom, std::abs(width) * zoom,
std::abs(height) * zoom);
// for debugging
// cairo_rectangle(cr, snappedBounds.x * zoom, snappedBounds.y * zoom, snappedBounds.width * zoom,
// snappedBounds.height * zoom);
cairo_stroke_preserve(cr);
auto applied = GdkRGBA{selectionColor.red, selectionColor.green, selectionColor.blue, 0.3};
gdk_cairo_set_source_rgba(cr, &applied);
cairo_fill(cr);
ToolHandler* toolHandler = view->getXournal()->getControl()->getToolHandler();
if (toolHandler->getToolType() != TOOL_HAND) {
cairo_set_dash(cr, nullptr, 0, 0);
if (!this->preserveAspectRatio) {
// top
drawAnchorRect(cr, x + width / 2, y, zoom);
// bottom
drawAnchorRect(cr, x + width / 2, y + height, zoom);
// left
drawAnchorRect(cr, x, y + height / 2, zoom);
// right
drawAnchorRect(cr, x + width, y + height / 2, zoom);
if (supportRotation) {
// rotation handle
drawAnchorRotation(cr,
std::min(x, x + width) + std::abs(width) + (ROTATE_PADDING + this->btnWidth) / zoom,
y + height / 2, zoom);
}
}
// top left
drawAnchorRect(cr, x, y, zoom);
// top right
drawAnchorRect(cr, x + width, y, zoom);
// bottom left
drawAnchorRect(cr, x, y + height, zoom);
// bottom right
drawAnchorRect(cr, x + width, y + height, zoom);
drawDeleteRect(cr, std::min(x, x + width) - (DELETE_PADDING + this->btnWidth) / zoom, y, zoom);
}
}
void EditSelection::drawAnchorRotation(cairo_t* cr, double x, double y, double zoom) {
GdkRGBA selectionColor = view->getSelectionColor();
gdk_cairo_set_source_rgba(cr, &selectionColor);
cairo_rectangle(cr, x * zoom - (this->btnWidth / 2), y * zoom - (this->btnWidth / 2), this->btnWidth,
this->btnWidth);
cairo_stroke_preserve(cr);
cairo_set_source_rgb(cr, 1, 0, 0);
cairo_fill(cr);
}
/**
* draws an idicator where you can scale the selection
*/
void EditSelection::drawAnchorRect(cairo_t* cr, double x, double y, double zoom) {
GdkRGBA selectionColor = view->getSelectionColor();
gdk_cairo_set_source_rgba(cr, &selectionColor);
cairo_rectangle(cr, x * zoom - (this->btnWidth / 2), y * zoom - (this->btnWidth / 2), this->btnWidth,
this->btnWidth);
cairo_stroke_preserve(cr);
cairo_set_source_rgb(cr, 1, 1, 1);
cairo_fill(cr);
}
/**
* draws an idicator where you can delete the selection
*/
void EditSelection::drawDeleteRect(cairo_t* cr, double x, double y, double zoom) const {
cairo_set_source_rgb(cr, 0, 0, 0);
cairo_rectangle(cr, x * zoom - (this->btnWidth / 2), y * zoom - (this->btnWidth / 2), this->btnWidth,
this->btnWidth);
cairo_stroke(cr);
cairo_set_source_rgb(cr, 1, 0, 0);
cairo_move_to(cr, x * zoom - (this->btnWidth / 2), y * zoom - (this->btnWidth / 2));
cairo_rel_move_to(cr, this->btnWidth, 0);
cairo_rel_line_to(cr, -this->btnWidth, this->btnWidth);
cairo_rel_move_to(cr, this->btnWidth, 0);
cairo_rel_line_to(cr, -this->btnWidth, -this->btnWidth);
cairo_stroke(cr);
}
auto EditSelection::getView() -> XojPageView* { return this->view; }
void EditSelection::serialize(ObjectOutputStream& out) const {
out.writeObject("EditSelection");
out.writeDouble(this->x);
out.writeDouble(this->y);
out.writeDouble(this->width);
out.writeDouble(this->height);
out.writeDouble(this->snappedBounds.x);
out.writeDouble(this->snappedBounds.y);
out.writeDouble(this->snappedBounds.width);
out.writeDouble(this->snappedBounds.height);
out.writeDouble(this->rotation);
this->contents->serialize(out);
out.endObject();
out.writeInt(static_cast<int>(this->getElements().size()));
for (Element* e: this->getElements()) {
e->serialize(out);
}
}
void EditSelection::readSerialized(ObjectInputStream& in) {
in.readObject("EditSelection");
this->x = in.readDouble();
this->y = in.readDouble();
this->width = in.readDouble();
this->height = in.readDouble();
double xSnap = in.readDouble();
double ySnap = in.readDouble();
double wSnap = in.readDouble();
double hSnap = in.readDouble();
this->snappedBounds = Rectangle<double>{xSnap, ySnap, wSnap, hSnap};
this->rotation = in.readDouble();
this->contents =
std::make_unique<EditSelectionContents>(xoj::util::Rectangle<double>(), xoj::util::Rectangle<double>(),
this->sourcePage, this->sourceLayer, this->view);
this->contents->readSerialized(in);
in.endObject();
}
| 48,907
|
C++
|
.cpp
| 1,028
| 40.301556
| 120
| 0.630257
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,488
|
LayerCtrlListener.cpp
|
xournalpp_xournalpp/src/core/control/layer/LayerCtrlListener.cpp
|
#include "LayerCtrlListener.h"
#include "LayerController.h"
LayerCtrlListener::LayerCtrlListener(): handler(nullptr) {}
LayerCtrlListener::~LayerCtrlListener() { unregisterListener(); }
void LayerCtrlListener::registerListener(LayerController* handler) {
this->handler = handler;
handler->addListener(this);
}
void LayerCtrlListener::unregisterListener() {
if (this->handler) {
this->handler->removeListener(this);
this->handler = nullptr;
}
}
| 481
|
C++
|
.cpp
| 14
| 30.714286
| 68
| 0.748918
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,489
|
LayerController.cpp
|
xournalpp_xournalpp/src/core/control/layer/LayerController.cpp
|
#include "LayerController.h"
#include <memory> // for __shared_ptr_access, make...
#include <utility> // for move
#include <vector> // for vector
#include "control/Control.h" // for Control
#include "control/actions/ActionDatabase.h" // for ActionDatabase
#include "gui/MainWindow.h" // for MainWindow
#include "gui/XournalView.h" // for XournalView
#include "model/Document.h" // for Document
#include "model/XojPage.h" // for XojPage
#include "undo/InsertLayerUndoAction.h" // for InsertLayerUndoAction
#include "undo/MergeLayerDownUndoAction.h" // for MergeLayerDownUndoAction
#include "undo/MoveLayerUndoAction.h" // for MoveLayerUndoAction
#include "undo/RemoveLayerUndoAction.h" // for RemoveLayerUndoAction
#include "undo/UndoAction.h" // for UndoActionPtr, UndoAction
#include "undo/UndoRedoHandler.h" // for UndoRedoHandler
#include "util/Util.h" // for npos
#include "util/i18n.h" // for FS, _F
#include "LayerCtrlListener.h" // for LayerCtrlListener
LayerController::LayerController(Control* control): control(control), selectedPage(npos) {}
void LayerController::documentChanged(DocumentChangeType type) {
if (type == DOCUMENT_CHANGE_CLEARED || type == DOCUMENT_CHANGE_COMPLETE) {
fireRebuildLayerMenu();
}
}
void LayerController::pageSelected(size_t page) {
if (selectedPage == page) {
return;
}
selectedPage = page;
fireRebuildLayerMenu();
}
void LayerController::insertLayer(PageRef page, Layer* layer, Layer::Index layerPos) {
page->insertLayer(layer, layerPos);
fireRebuildLayerMenu();
}
void LayerController::removeLayer(PageRef page, Layer* layer) {
page->removeLayer(layer);
fireRebuildLayerMenu();
}
void LayerController::addListener(LayerCtrlListener* listener) { this->listener.push_back(listener); }
void LayerController::removeListener(LayerCtrlListener* listener) { this->listener.remove(listener); }
void LayerController::updateActions() {
auto layer = getCurrentLayerId();
auto maxLayer = getLayerCount();
auto* actionDB = control->getActionDatabase();
actionDB->enableAction(Action::LAYER_DELETE, layer > 0);
actionDB->enableAction(Action::LAYER_MERGE_DOWN, layer > 1);
actionDB->enableAction(Action::MOVE_SELECTION_LAYER_UP, layer < maxLayer);
actionDB->enableAction(Action::MOVE_SELECTION_LAYER_DOWN, layer > 1);
actionDB->enableAction(Action::LAYER_GOTO_NEXT, layer < maxLayer);
actionDB->enableAction(Action::LAYER_GOTO_PREVIOUS, layer > 0);
actionDB->enableAction(Action::LAYER_GOTO_TOP, layer < maxLayer);
actionDB->setActionState(Action::LAYER_ACTIVE, layer);
}
void LayerController::fireRebuildLayerMenu() {
for (LayerCtrlListener* l: this->listener) { l->rebuildLayerMenu(); }
updateActions();
}
void LayerController::fireLayerVisibilityChanged() {
for (LayerCtrlListener* l: this->listener) { l->layerVisibilityChanged(); }
// Rerenders the page - Todo: make this another listener
control->getWindow()->getXournal()->layerChanged(selectedPage);
}
void LayerController::fireSelectedLayerChanged() {
for (LayerCtrlListener* l: this->listener) {
l->updateSelectedLayer();
}
updateActions();
}
/**
* Show all layer on the current page
*/
void LayerController::showAllLayer() { showOrHideAllLayer(true); }
/**
* Hide all layer on the current page
*/
void LayerController::hideAllLayer() { showOrHideAllLayer(false); }
/**
* Show / Hide all layer on the current page
*/
void LayerController::showOrHideAllLayer(bool show) {
PageRef page = getCurrentPage();
for (Layer::Index i = 1; i <= page->getLayerCount(); i++) { page->setLayerVisible(i, show); }
fireLayerVisibilityChanged();
}
void LayerController::addNewLayer() {
control->clearSelectionEndText();
PageRef p = getCurrentPage();
if (!p) {
return;
}
auto* l = new Layer();
auto layerPos = p->getSelectedLayerId();
p->insertLayer(l, layerPos);
control->getUndoRedoHandler()->addUndoAction(std::make_unique<InsertLayerUndoAction>(this, p, l, layerPos));
fireRebuildLayerMenu();
// Repaint is not needed here - the new layer is empty
}
void LayerController::deleteCurrentLayer() {
control->clearSelectionEndText();
PageRef p = getCurrentPage();
auto pId = selectedPage;
if (!p) {
return;
}
auto lId = p->getSelectedLayerId();
if (lId == 0) {
return;
}
Layer* l = p->getSelectedLayer();
p->removeLayer(l);
MainWindow* win = control->getWindow();
if (win) {
win->getXournal()->layerChanged(pId);
}
control->getUndoRedoHandler()->addUndoAction(std::make_unique<RemoveLayerUndoAction>(this, p, l, lId - 1));
fireRebuildLayerMenu();
}
void LayerController::moveCurrentLayer(bool up) {
control->clearSelectionEndText();
PageRef p = getCurrentPage();
auto pId = selectedPage;
if (!p) {
return;
}
auto lId = p->getSelectedLayerId();
Layer* currentLayer = p->getSelectedLayer();
if (lId == 0) {
// Background cannot be moved
return;
}
if (lId == 1 && !up) {
// bottom layer cannot be moved down
return;
}
if (lId == p->getLayerCount() && up) {
// top layer cannot be moved up
return;
}
p->removeLayer(currentLayer);
// Layer IDs are a bit strange, because background is 0
// so the first layer is 1, technical the first layer is still
// index 0 in the vector... confusing...
auto newIndex = up ? lId : lId - 2;
p->insertLayer(currentLayer, newIndex);
MainWindow* win = control->getWindow();
if (win) {
win->getXournal()->layerChanged(pId);
}
control->getUndoRedoHandler()->addUndoAction(
std::make_unique<MoveLayerUndoAction>(this, p, currentLayer, lId - 1, newIndex));
fireRebuildLayerMenu();
}
void LayerController::mergeCurrentLayerDown() {
control->clearSelectionEndText();
PageRef page = getCurrentPage();
auto pageID = selectedPage;
if (page == nullptr) {
return;
}
/*
* layerID value:
* ...
* 2: layer 2
* 1: layer 1
* 0: background
*/
const auto layerID = page->getSelectedLayerId();
Layer* currentLayer = page->getSelectedLayer();
if (layerID < 2) {
/*
* lowest (non-background) layer cannot be merged into background
* and the background itself obviously also cannot be merged down
*/
return;
}
/*
* We know this cannot be the background (or even an underflow) because
* we checked for !(layerID < 2) before.
*/
const auto layerBelowID = layerID - 1;
/*
* Layer indices in the vector are off by one from the layer IDs because
* the background is not in the vector, so layer 1 has index 0 and so on.
*/
const Layer::Index layerBelowIndex = layerBelowID - 1;
Layer* layerBelow = (*page->getLayers())[layerBelowIndex];
UndoActionPtr undo_redo_action =
std::make_unique<MergeLayerDownUndoAction>(this, page, currentLayer, layerID - 1, layerBelow, pageID);
undo_redo_action->redo(this->control);
control->getUndoRedoHandler()->addUndoAction(std::move(undo_redo_action));
fireRebuildLayerMenu();
}
void LayerController::copyCurrentLayer() {
control->clearSelectionEndText();
PageRef p = getCurrentPage();
auto pId = selectedPage;
if (!p) {
return;
}
auto lId = p->getSelectedLayerId();
if (lId == 0) {
return;
}
Layer* l = p->getSelectedLayer();
Layer* cloned = l->clone();
p->insertLayer(cloned, lId);
MainWindow* win = control->getWindow();
if (win) {
win->getXournal()->layerChanged(pId);
}
control->getUndoRedoHandler()->addUndoAction(std::make_unique<InsertLayerUndoAction>(this, p, cloned, lId));
fireRebuildLayerMenu();
}
auto LayerController::getCurrentPage() const -> PageRef { return control->getDocument()->getPage(selectedPage); }
auto LayerController::getCurrentPageId() const -> size_t { return selectedPage; }
void LayerController::setLayerVisible(Layer::Index layerId, bool visible) {
getCurrentPage()->setLayerVisible(layerId, visible);
fireLayerVisibilityChanged();
}
/**
* Switch to a layer
*
* @param hideShow Auto hide / show other layers,
* as it was before the advance layer menu
* @param clearSelection Clear / keep current selection before switching layers.
*/
void LayerController::switchToLay(Layer::Index layerId, bool hideShow, bool clearSelection) {
if (clearSelection) {
control->clearSelectionEndText();
}
PageRef p = getCurrentPage();
if (!p) {
return;
}
p->setSelectedLayerId(layerId);
fireSelectedLayerChanged();
if (hideShow) {
for (Layer::Index i = 1; i <= p->getLayerCount(); i++) { p->setLayerVisible(i, i <= layerId); }
fireLayerVisibilityChanged();
}
}
/**
* @return Layer count of the current page
*/
auto LayerController::getLayerCount() const -> Layer::Index {
PageRef page = getCurrentPage();
if (!page) {
return 0;
}
return page->getLayerCount();
}
/**
* @return Current layer ID
*/
auto LayerController::getCurrentLayerId() const -> Layer::Index {
PageRef page = getCurrentPage();
if (!page) {
return 0;
}
return page->getSelectedLayerId();
}
auto LayerController::getCurrentLayerName() const -> std::string {
PageRef page = getCurrentPage();
if (page == nullptr) {
return "Unknown layer name";
}
auto currentID = getCurrentLayerId();
if (currentID == 0) { // If is background
return page->getBackgroundName();
} else if (auto layer = page->getSelectedLayer(); layer->hasName()) {
return layer->getName();
} else {
return FS(_F("Layer {1}") % static_cast<long>(currentID));
}
}
void LayerController::setCurrentLayerName(const std::string& newName) {
PageRef page = getCurrentPage();
if (page == nullptr) {
return;
}
if (getCurrentLayerId() == 0) { // Background
page->setBackgroundName(newName);
} else { // Any other layer
page->getSelectedLayer()->setName(newName);
}
fireRebuildLayerMenu();
}
std::string LayerController::getLayerNameById(Layer::Index id) const {
PageRef page = getCurrentPage();
if (page == nullptr) {
return "Unknown layer name";
}
if (id == 0) {
return page->getBackgroundName();
}
auto previousId = page->getSelectedLayerId();
if (previousId == id) {
return getCurrentLayerName();
}
page->setSelectedLayerId(id);
std::string name = getCurrentLayerName();
page->setSelectedLayerId(previousId);
return name;
}
| 11,004
|
C++
|
.cpp
| 306
| 31.19281
| 114
| 0.672193
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,490
|
LoadHandlerHelper.cpp
|
xournalpp_xournalpp/src/core/control/xojfile/LoadHandlerHelper.cpp
|
/*
* Xournal++
*
* helper methods to load a .xoj / .xopp document
*
* @author Xournal Team
* http://xournal.sf.net
*
* @license GPL
*/
#include "LoadHandlerHelper.h"
#include <cstdint> // for uint32_t
#include <cstdlib> // for strtol, strtoull
#include <cstring> // for strcmp, size_t, strlen
#include <string> // for allocator, string
#include <glib.h> // for g_error_new, G_MARKUP_ERROR, G_M...
#include "util/Color.h"
#include "util/PlaceholderString.h" // for PlaceholderString
#include "util/i18n.h" // for FC, _F, _
#include "LoadHandler.h" // for LoadHandler, getAttribInt, getAt...
#define error(...) \
if (loadHandler->error == nullptr) { \
loadHandler->error = g_error_new(G_MARKUP_ERROR, G_MARKUP_ERROR_INVALID_CONTENT, __VA_ARGS__); \
}
struct PredefinedColor {
const char* name;
const Color rgb;
};
constexpr PredefinedColor PREDEFINED_COLORS[] = {
{"black", Colors::black},
{"blue", Colors::xopp_royalblue},
{"red", Colors::red},
{"green", Colors::green},
{"gray", Colors::gray},
{"lightblue", Colors::xopp_deepskyblue},
{"lightgreen", Colors::lime},
{"magenta", Colors::magenta},
{"orange", Colors::xopp_darkorange},
{"yellow", Colors::yellow},
{"white", Colors::white}};
auto LoadHandlerHelper::parseBackgroundColor(LoadHandler* loadHandler) -> Color {
const char* sColor = LoadHandlerHelper::getAttrib("color", false, loadHandler);
Color color = Colors::white;
if (strcmp("blue", sColor) == 0) {
color = Colors::xopp_paleturqoise;
} else if (strcmp("pink", sColor) == 0) {
color = Colors::xopp_pink;
} else if (strcmp("green", sColor) == 0) {
color = Colors::xopp_aquamarine;
} else if (strcmp("orange", sColor) == 0) {
color = Colors::xopp_lightsalmon;
} else if (strcmp("yellow", sColor) == 0) {
color = Colors::xopp_khaki;
} else {
LoadHandlerHelper::parseColor(sColor, color, loadHandler);
}
return color;
}
auto LoadHandlerHelper::parseColor(const char* text, Color& color, LoadHandler* loadHandler) -> bool {
if (text == nullptr) {
error("%s", _("Attribute color not set!"));
return false;
}
if (text[0] == '#') {
gchar* ptr = nullptr;
auto c = uint32_t(g_ascii_strtoull(&text[1], &ptr, 16));
if (ptr != text + strlen(text)) {
error("%s", FC(_F("Unknown color value \"{1}\"") % text));
return false;
}
color = c >> 8U;
return true;
}
for (auto& i: PREDEFINED_COLORS) {
if (!strcmp(text, i.name)) {
color = i.rgb;
return true;
}
}
error("%s", FC(_F("Color \"{1}\" unknown (not defined in default color list)!") % text));
return false;
}
auto LoadHandlerHelper::getAttrib(const char* name, bool optional, LoadHandler* loadHandler) -> const char* {
const char** aName = loadHandler->attributeNames;
const char** aValue = loadHandler->attributeValues;
while (*aName != nullptr) {
if (!strcmp(*aName, name)) {
return *aValue;
}
aName++;
aValue++;
}
if (!optional) {
g_warning("Parser: attribute %s not found!", name);
}
return nullptr;
}
auto LoadHandlerHelper::getAttribDouble(const char* name, LoadHandler* loadHandler) -> double {
const char* attrib = getAttrib(name, false, loadHandler);
if (attrib == nullptr) {
error("%s", FC(_F("Attribute \"{1}\" could not be parsed as double, the value is nullptr") % name));
return 0;
}
char* ptr = nullptr;
double val = g_ascii_strtod(attrib, &ptr);
if (ptr == attrib) {
error("%s", FC(_F("Attribute \"{1}\" could not be parsed as double, the value is \"{2}\"") % name % attrib));
}
return val;
}
auto LoadHandlerHelper::getAttribInt(const char* name, LoadHandler* loadHandler) -> int {
const char* attrib = getAttrib(name, false, loadHandler);
if (attrib == nullptr) {
error("%s", FC(_F("Attribute \"{1}\" could not be parsed as int, the value is nullptr") % name));
return 0;
}
char* ptr = nullptr;
int val = static_cast<int>(strtol(attrib, &ptr, 10));
if (ptr == attrib) {
error("%s", FC(_F("Attribute \"{1}\" could not be parsed as int, the value is \"{2}\"") % name % attrib));
}
return val;
}
auto LoadHandlerHelper::getAttribInt(const char* name, bool optional, LoadHandler* loadHandler, int& rValue) -> bool {
const char* attrib = getAttrib(name, optional, loadHandler);
if (attrib == nullptr) {
if (!optional) {
g_warning("Parser: attribute %s not found!", name);
}
return false;
}
char* ptr = nullptr;
int val = static_cast<int>(strtol(attrib, &ptr, 10));
if (ptr == attrib) {
error("%s", FC(_F("Attribute \"{1}\" could not be parsed as int, the value is \"{2}\"") % name % attrib));
}
rValue = val;
return true;
}
auto LoadHandlerHelper::getAttribSizeT(const char* name, LoadHandler* loadHandler) -> size_t {
const char* attrib = getAttrib(name, false, loadHandler);
if (attrib == nullptr) {
error("%s", FC(_F("Attribute \"{1}\" could not be parsed as size_t, the value is nullptr") % name));
return 0;
}
char* ptr = nullptr;
size_t val = g_ascii_strtoull(attrib, &ptr, 10);
if (ptr == attrib) {
error("%s", FC(_F("Attribute \"{1}\" could not be parsed as size_t, the value is \"{2}\"") % name % attrib));
}
return val;
}
auto LoadHandlerHelper::getAttribSizeT(const char* name, bool optional, LoadHandler* loadHandler, size_t& rValue)
-> bool {
const char* attrib = getAttrib(name, optional, loadHandler);
if (attrib == nullptr) {
if (!optional) {
g_warning("Parser: attribute %s not found!", name);
}
return false;
}
char* ptr = nullptr;
size_t val = strtoull(attrib, &ptr, 10);
if (ptr == attrib) {
error("%s", FC(_F("Attribute \"{1}\" could not be parsed as size_t, the value is \"{2}\"") % name % attrib));
}
rValue = val;
return true;
}
| 6,419
|
C++
|
.cpp
| 169
| 32.088757
| 118
| 0.585052
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,491
|
LoadHandler.cpp
|
xournalpp_xournalpp/src/core/control/xojfile/LoadHandler.cpp
|
#include "LoadHandler.h"
#include <algorithm> // for copy
#include <cmath> // for isnan
#include <cstdlib> // for atoi, size_t
#include <cstring> // for strcmp, strlen
#include <iterator> // for back_inserter
#include <memory> // for __shared_ptr_access
#include <regex> // for regex_search, smatch
#include <type_traits> // for remove_reference<>::type
#include <utility> // for move
#include <gio/gio.h> // for g_file_get_path, g_fil...
#include <glib-object.h> // for g_object_unref
#include "control/pagetype/PageTypeHandler.h" // for PageTypeHandler
#include "model/BackgroundImage.h" // for BackgroundImage
#include "model/Font.h" // for XojFont
#include "model/Image.h" // for Image
#include "model/Layer.h" // for Layer
#include "model/PageType.h" // for PageType, PageTypeFormat
#include "model/Point.h" // for Point
#include "model/Stroke.h" // for Stroke, StrokeCapStyle
#include "model/StrokeStyle.h" // for StrokeStyle
#include "model/TexImage.h" // for TexImage
#include "model/Text.h" // for Text
#include "model/XojPage.h" // for XojPage
#include "util/Assert.h" // for xoj_assert
#include "util/GzUtil.h" // for GzUtil
#include "util/LoopUtil.h"
#include "util/PlaceholderString.h" // for PlaceholderString
#include "util/i18n.h" // for _F, FC, FS, _
#include "util/raii/GObjectSPtr.h"
#include "util/safe_casts.h" // for as_signed, as_unsigned
#include "LoadHandlerHelper.h" // for getAttrib, getAttribDo...
using std::string;
#define error2(var, ...) \
if (var == nullptr) { \
var = g_error_new(G_MARKUP_ERROR, G_MARKUP_ERROR_INVALID_CONTENT, __VA_ARGS__); \
}
#define error(...) \
if (error == nullptr) { \
error = g_error_new(G_MARKUP_ERROR, G_MARKUP_ERROR_INVALID_CONTENT, __VA_ARGS__); \
}
namespace {
constexpr size_t MAX_VERSION_LENGTH = 50;
constexpr size_t MAX_MIMETYPE_LENGTH = 25;
} // namespace
LoadHandler::LoadHandler():
attachedPdfMissing(false),
pdfFilenameParsed(false),
pos(PARSER_POS_NOT_STARTED),
fileVersion(0),
minimalFileVersion(0),
zipFp(nullptr),
zipContentFile(nullptr),
gzFp(nullptr),
layer(nullptr),
stroke(nullptr),
text(nullptr),
image(nullptr),
teximage(nullptr),
attributeNames(nullptr),
attributeValues(nullptr),
elementName(nullptr),
loadedTimeStamp(0) {
this->error = nullptr;
initAttributes();
}
LoadHandler::~LoadHandler() {
if (this->audioFiles) {
g_hash_table_unref(this->audioFiles);
}
}
void LoadHandler::initAttributes() {
this->zipFp = nullptr;
this->zipContentFile = nullptr;
this->gzFp = nullptr;
this->isGzFile = false;
this->error = nullptr;
this->attributeNames = nullptr;
this->attributeValues = nullptr;
this->elementName = nullptr;
this->pdfFilenameParsed = false;
this->attachedPdfMissing = false;
this->page = nullptr;
this->layer = nullptr;
this->stroke = nullptr;
this->image = nullptr;
this->teximage = nullptr;
this->text = nullptr;
this->pages.clear();
if (this->audioFiles) {
g_hash_table_unref(this->audioFiles);
}
this->audioFiles = g_hash_table_new(g_str_hash, g_str_equal);
}
auto LoadHandler::getLastError() -> string { return this->lastError; }
auto LoadHandler::isAttachedPdfMissing() const -> bool { return this->attachedPdfMissing; }
auto LoadHandler::getMissingPdfFilename() const -> string { return this->pdfMissing; }
auto LoadHandler::openFile(fs::path const& filepath) -> bool {
this->filepath = filepath;
int zipError = 0;
this->zipFp = zip_open(filepath.u8string().c_str(), ZIP_RDONLY, &zipError);
// Check if the file is actually an old XOPP-File and open it
if (!this->zipFp && zipError == ZIP_ER_NOZIP) {
this->gzFp = GzUtil::openPath(filepath, "r");
this->isGzFile = true;
}
if (this->zipFp && !this->isGzFile) {
// Check the mimetype
zip_file_t* mimetypeFp = zip_fopen(this->zipFp, "mimetype", 0);
if (!mimetypeFp) {
this->lastError = zip_error_strerror(zip_get_error(zipFp));
this->lastError =
FS(_F("The file is no valid .xopp file (Mimetype missing): \"{1}\"") % filepath.u8string());
return false;
}
char mimetype[MAX_MIMETYPE_LENGTH + 1] = {};
// read the mimetype and a few more bytes to make sure we do not only read a subset
zip_fread(mimetypeFp, mimetype, MAX_MIMETYPE_LENGTH);
if (!strcmp(mimetype, "application/xournal++")) {
zip_fclose(mimetypeFp);
this->lastError = FS(_F("The file is no valid .xopp file (Mimetype wrong): \"{1}\"") % filepath.u8string());
return false;
}
zip_fclose(mimetypeFp);
// Get the file version
zip_file_t* versionFp = zip_fopen(this->zipFp, "META-INF/version", 0);
if (!versionFp) {
this->lastError =
FS(_F("The file is no valid .xopp file (Version missing): \"{1}\"") % filepath.u8string());
return false;
}
char versionString[MAX_VERSION_LENGTH + 1] = {};
zip_fread(versionFp, versionString, MAX_VERSION_LENGTH);
std::string versions(versionString);
std::regex versionRegex("current=(\\d+?)(?:\n|\r\n)min=(\\d+?)");
std::smatch match;
if (std::regex_search(versions, match, versionRegex)) {
this->fileVersion = std::stoi(match.str(1));
this->minimalFileVersion = std::stoi(match.str(2));
} else {
zip_fclose(versionFp);
this->lastError = FS(_F("The file is not a valid .xopp file (Version string corrupted): \"{1}\"") %
filepath.u8string());
return false;
}
zip_fclose(versionFp);
// open the main content file
this->zipContentFile = zip_fopen(this->zipFp, "content.xml", 0);
if (!this->zipContentFile) {
this->lastError = FS(_F("Failed to open content.xml in zip archive: \"{1}\"") %
zip_error_strerror(zip_get_error(zipFp)));
return false;
}
}
// Fail if neither utility could open the file
if (!this->zipFp && !this->gzFp) {
this->lastError = FS(_F("Could not open file: \"{1}\"") % filepath.u8string());
return false;
}
return true;
}
auto LoadHandler::closeFile() -> bool {
if (this->isGzFile) {
return static_cast<bool>(gzclose(this->gzFp));
}
xoj_assert(this->zipContentFile != nullptr);
zip_fclose(this->zipContentFile);
int zipError = zip_close(this->zipFp);
return zipError == 0;
}
auto LoadHandler::readContentFile(char* buffer, zip_uint64_t len) -> zip_int64_t {
if (this->isGzFile) {
if (gzeof(this->gzFp)) {
return -1;
}
return gzread(this->gzFp, buffer, static_cast<unsigned int>(len));
}
xoj_assert(this->zipContentFile != nullptr);
zip_int64_t lengthRead = zip_fread(this->zipContentFile, buffer, len);
if (lengthRead > 0) {
return lengthRead;
}
return -1;
}
auto LoadHandler::parseXml() -> bool {
xoj_assert(this->doc);
const GMarkupParser parser = {LoadHandler::parserStartElement, LoadHandler::parserEndElement,
LoadHandler::parserText, nullptr, nullptr};
this->error = nullptr;
gboolean valid = true;
this->pos = PARSER_POS_NOT_STARTED;
this->creator = "Unknown";
this->fileVersion = 1;
GMarkupParseContext* context =
g_markup_parse_context_new(&parser, static_cast<GMarkupParseFlags>(0), this, nullptr);
zip_int64_t len = 0;
do {
char buffer[1024];
len = readContentFile(buffer, sizeof(buffer));
if (len > 0) {
valid = g_markup_parse_context_parse(context, buffer, len, &error);
}
if (error) {
g_warning("LoadHandler::parseXml: %s\n", error->message);
valid = false;
break;
}
} while (len >= 0 && valid && !error);
if (valid) {
valid = g_markup_parse_context_end_parse(context, &error);
} else {
if (error != nullptr && error->message != nullptr) {
this->lastError = FS(_F("XML Parser error: {1}") % error->message);
g_error_free(error);
} else {
this->lastError = _("Unknown parser error");
}
g_warning("LoadHandler::parseXml: %s\n", this->lastError.c_str());
}
g_markup_parse_context_free(context);
// Add all parsed pages to the document
this->doc->addPages(pages.begin(), pages.end());
if (this->pos != PASER_POS_FINISHED && this->lastError.empty()) {
lastError = _("Document is not complete (maybe the end is cut off?)");
return false;
}
if (this->pos == PASER_POS_FINISHED && this->doc->getPageCount() == 0) {
lastError = _("Document is corrupted (no pages found in file)");
return false;
}
doc->setCreateBackupOnSave(true);
return valid;
}
void LoadHandler::parseStart() {
if (strcmp(elementName, "xournal") == 0) {
endRootTag = "xournal";
// Read the document version
const char* version = LoadHandlerHelper::getAttrib("version", true, this);
if (version) {
this->creator = "Xournal ";
this->creator += version;
}
const char* fileversion = LoadHandlerHelper::getAttrib("fileversion", true, this);
if (fileversion) {
this->fileVersion = atoi(fileversion);
}
const char* creator = LoadHandlerHelper::getAttrib("creator", true, this);
if (creator) {
this->creator = creator;
}
this->pos = PARSER_POS_STARTED;
} else if (strcmp(elementName, "MrWriter") == 0) {
endRootTag = "MrWriter";
// Read the document version
const char* version = LoadHandlerHelper::getAttrib("version", true, this);
if (version) {
this->creator = "MrWriter ";
this->creator += version;
}
// Document version 1:
// Handle it the same as a Xournal document, and don't allow to overwrite
this->fileVersion = 1;
this->pos = PARSER_POS_STARTED;
} else {
error("%s", FC(_F("Unexpected root tag: {1}") % elementName));
}
}
void LoadHandler::parseContents() {
if (strcmp(elementName, "page") == 0) {
this->pos = PARSER_POS_IN_PAGE;
double width = LoadHandlerHelper::getAttribDouble("width", this);
double height = LoadHandlerHelper::getAttribDouble("height", this);
this->page = std::make_unique<XojPage>(width, height, /*suppressLayer*/ true);
pages.push_back(this->page);
} else if (strcmp(elementName, "audio") == 0) {
this->parseAudio();
} else if (strcmp(elementName, "title") == 0) {
// Ignore this tag, it says nothing...
} else if (strcmp(elementName, "preview") == 0) {
// Ignore this tag, we don't need a preview
} else {
g_warning("%s", FC(_F("Unexpected tag in document: \"{1}\"") % elementName));
}
}
void LoadHandler::parseBgSolid() {
PageType bg;
const char* style = LoadHandlerHelper::getAttrib("style", false, this);
if (style != nullptr) {
bg.format = PageTypeHandler::getPageTypeFormatForString(style);
}
const char* config = LoadHandlerHelper::getAttrib("config", true, this);
if (config != nullptr) {
bg.config = config;
}
this->page->setBackgroundType(bg);
Color color = LoadHandlerHelper::parseBackgroundColor(this);
this->page->setBackgroundColor(color);
const char* name = LoadHandlerHelper::getAttrib("name", true, this);
if (name != nullptr) {
this->page->setBackgroundName(name);
}
}
void LoadHandler::parseBgPixmap() {
const char* domain = LoadHandlerHelper::getAttrib("domain", false, this);
const fs::path filepath = fs::u8path(LoadHandlerHelper::getAttrib("filename", false, this));
// in case of a cloned background image, filename is a string representation of the page number from which the image
// is cloned
if (!strcmp(domain, "absolute") || (!strcmp(domain, "attach") && this->isGzFile)) {
fs::path fileToLoad;
if (!strcmp(domain, "attach")) {
fileToLoad = this->filepath;
fileToLoad += ".";
fileToLoad += filepath;
} else {
fileToLoad = filepath;
}
GError* error = nullptr;
BackgroundImage img;
img.loadFile(fileToLoad, &error);
if (error) {
error("%s",
FC(_F("Could not read image: {1}. Error message: {2}") % fileToLoad.u8string() % error->message));
g_error_free(error);
}
this->page->setBackgroundImage(img);
} else if (!strcmp(domain, "attach")) {
// This is the new zip file attach domain
const auto readResult = readZipAttachment(filepath); ///< Do not remove the const qualifier - see below
if (!readResult) {
return;
}
const std::string& imgData = *readResult; ///< Do not remove the const qualifier - see below
/**
* To avoid an unecessary copy, the data is still managed by the std::unique_ptr<std::string> instance. The
* input stream assumes the data will not be modified: do not remove the const qualifier on readResult or
* imgData
*/
xoj::util::GObjectSPtr<GInputStream> inputStream(
g_memory_input_stream_new_from_data(imgData.data(), static_cast<gssize>(imgData.size()), nullptr),
xoj::util::adopt);
GError* error = nullptr;
BackgroundImage img;
img.loadFile(inputStream.get(), filepath, &error);
g_input_stream_close(inputStream.get(), nullptr, nullptr);
if (error) {
error("%s", FC(_F("Could not read image: {1}. Error message: {2}") % filepath.string() % error->message));
g_error_free(error);
}
this->page->setBackgroundImage(img);
} else if (!strcmp(domain, "clone")) {
gchar* endptr = nullptr;
auto const& filename = filepath.u8string();
auto nr = static_cast<size_t>(g_ascii_strtoull(filename.c_str(), &endptr, 10));
if (endptr == filename.c_str()) {
error("%s", FC(_F("Could not read page number for cloned background image: {1}.") % filepath.string()));
}
PageRef p = pages[nr];
if (p) {
this->page->setBackgroundImage(p->getBackgroundImage());
}
} else {
error("%s", FC(_F("Unknown pixmap::domain type: {1}") % domain));
}
this->page->setBackgroundType(PageType(PageTypeFormat::Image));
}
void LoadHandler::parseBgPdf() {
xoj_assert(this->doc);
int pageno = LoadHandlerHelper::getAttribInt("pageno", this);
bool attachToDocument = false;
fs::path pdfFilename;
this->page->setBackgroundPdfPageNr(as_unsigned(pageno) - 1);
if (!this->pdfFilenameParsed) {
const char* domain = LoadHandlerHelper::getAttrib("domain", false, this);
{
const char* sFilename = LoadHandlerHelper::getAttrib("filename", false, this);
if (sFilename == nullptr) {
error("PDF Filename missing!");
return;
}
pdfFilename = fs::u8path(sFilename);
}
if (!strcmp("absolute", domain)) // Absolute OR relative path
{
if (pdfFilename.is_relative()) {
pdfFilename = xournalFilepath.remove_filename() / pdfFilename;
}
} else if (!strcmp("attach", domain)) {
attachToDocument = true;
// Handle old format separately
if (this->isGzFile) {
pdfFilename = (fs::path{xournalFilepath} += ".") += pdfFilename;
} else {
auto pdfBytes = readZipAttachment(pdfFilename);
if (!pdfBytes) {
return;
}
doc->readPdf(pdfFilename, false, attachToDocument, std::move(pdfBytes));
if (!doc->getLastErrorMsg().empty()) {
error("%s", FC(_F("Error reading PDF: {1}") % doc->getLastErrorMsg()));
}
this->pdfFilenameParsed = true;
return;
}
} else {
error("%s", FC(_F("Unknown domain type: {1}") % domain));
return;
}
this->pdfFilenameParsed = true;
if (fs::is_regular_file(pdfFilename)) {
doc->readPdf(pdfFilename, false, attachToDocument);
if (!doc->getLastErrorMsg().empty()) {
error("%s", FC(_F("Error reading PDF: {1}") % doc->getLastErrorMsg()));
}
} else {
doc->setPdfAttributes(pdfFilename, attachToDocument);
if (attachToDocument) {
this->attachedPdfMissing = true;
} else {
this->pdfMissing = pdfFilename.u8string();
}
}
}
}
void LoadHandler::parsePage() {
if (!strcmp(elementName, "background")) {
const char* name = LoadHandlerHelper::getAttrib("name", true, this);
if (name != nullptr) {
this->page->setBackgroundName(name);
}
const char* type = LoadHandlerHelper::getAttrib("type", false, this);
if (strcmp("solid", type) == 0) {
parseBgSolid();
} else if (strcmp("pixmap", type) == 0) {
parseBgPixmap();
} else if (strcmp("pdf", type) == 0) {
parseBgPdf();
} else {
error("%s", FC(_F("Unknown background type: {1}") % type));
}
} else if (!strcmp(elementName, "layer")) {
this->pos = PARSER_POS_IN_LAYER;
this->layer = new Layer();
const char* name = LoadHandlerHelper::getAttrib("name", true, this);
if (name != nullptr) {
this->layer->setName(name);
}
this->page->addLayer(this->layer);
}
}
void LoadHandler::parseStroke() {
auto strokeOwn = std::make_unique<Stroke>();
this->stroke = strokeOwn.get();
this->layer->addElement(std::move(strokeOwn));
const char* width = LoadHandlerHelper::getAttrib("width", false, this);
char* endPtr = nullptr;
stroke->setWidth(g_ascii_strtod(width, &endPtr));
if (endPtr == width) {
error("%s", FC(_F("Error reading width of a stroke: {1}") % width));
return;
}
// MrWriter writes pressures as separate field
const char* pressure = LoadHandlerHelper::getAttrib("pressures", true, this);
if (pressure == nullptr) {
// Xournal / Xournal++ uses the width field
pressure = endPtr;
}
while (*pressure != 0) {
char* tmpptr = nullptr;
double val = g_ascii_strtod(pressure, &tmpptr);
if (tmpptr == pressure) {
break;
}
pressure = tmpptr;
this->pressureBuffer.push_back(val);
}
Color color{0U};
const char* sColor = LoadHandlerHelper::getAttrib("color", false, this);
if (!LoadHandlerHelper::parseColor(sColor, color, this)) {
return;
}
stroke->setColor(color);
/** read stroke timestamps (xopp fileformat) */
const char* fn = LoadHandlerHelper::getAttrib("fn", true, this);
if (fn != nullptr && strlen(fn) > 0) {
if (this->isGzFile) {
stroke->setAudioFilename(fs::u8path(fn));
} else {
auto tempFile = getTempFileForPath(fn);
if (!tempFile.empty()) {
stroke->setAudioFilename(tempFile);
}
}
}
if (this->fileVersion < 4) {
int ts = 0;
if (LoadHandlerHelper::getAttribInt("ts", true, this, ts)) {
stroke->setTimestamp(as_unsigned(ts) * 1000);
}
} else {
size_t ts = 0;
if (LoadHandlerHelper::getAttribSizeT("ts", true, this, ts)) {
stroke->setTimestamp(ts);
}
}
int fill = -1;
if (LoadHandlerHelper::getAttribInt("fill", true, this, fill)) {
stroke->setFill(fill);
}
const char* capStyleStr = LoadHandlerHelper::getAttrib("capStyle", true, this);
if (capStyleStr != nullptr) {
if (strcmp("butt", capStyleStr) == 0) {
stroke->setStrokeCapStyle(StrokeCapStyle::BUTT);
} else if (strcmp("round", capStyleStr) == 0) {
stroke->setStrokeCapStyle(StrokeCapStyle::ROUND);
} else if (strcmp("square", capStyleStr) == 0) {
stroke->setStrokeCapStyle(StrokeCapStyle::SQUARE);
} else {
g_warning("%s", FC(_F("Unknown stroke cap type: \"{1}\", assuming round") % capStyleStr));
}
}
const char* style = LoadHandlerHelper::getAttrib("style", true, this);
if (style != nullptr) {
stroke->setLineStyle(StrokeStyle::parseStyle(style));
}
const char* tool = LoadHandlerHelper::getAttrib("tool", false, this);
if (strcmp("eraser", tool) == 0) {
stroke->setToolType(StrokeTool::ERASER);
} else if (strcmp("pen", tool) == 0) {
stroke->setToolType(StrokeTool::PEN);
} else if (strcmp("highlighter", tool) == 0) {
stroke->setToolType(StrokeTool::HIGHLIGHTER);
} else {
g_warning("%s", FC(_F("Unknown stroke type: \"{1}\", assuming pen") % tool));
}
/**
* For each stroke being read, set the timestamp value
* we've read just before.
* Afterwards, clean the read timestamp data.
*/
if (loadedFilename.length() != 0) {
this->stroke->setTimestamp(as_unsigned(loadedTimeStamp));
this->stroke->setAudioFilename(loadedFilename);
loadedFilename = "";
loadedTimeStamp = 0;
}
}
void LoadHandler::parseText() {
auto textOwn = std::make_unique<Text>();
this->text = textOwn.get();
this->layer->addElement(std::move(textOwn));
const char* sFont = LoadHandlerHelper::getAttrib("font", false, this);
double fontSize = LoadHandlerHelper::getAttribDouble("size", this);
double x = LoadHandlerHelper::getAttribDouble("x", this);
double y = LoadHandlerHelper::getAttribDouble("y", this);
this->text->setX(x);
this->text->setY(y);
XojFont& f = text->getFont();
f.setName(sFont);
f.setSize(fontSize);
const char* sColor = LoadHandlerHelper::getAttrib("color", false, this);
Color color{0U};
LoadHandlerHelper::parseColor(sColor, color, this);
text->setColor(color);
const char* fn = LoadHandlerHelper::getAttrib("fn", true, this);
if (fn != nullptr && strlen(fn) > 0) {
if (this->isGzFile) {
text->setAudioFilename(fs::u8path(fn));
} else {
auto tempFile = getTempFileForPath(fn);
if (!tempFile.empty()) {
text->setAudioFilename(tempFile);
}
}
}
size_t ts = 0;
if (LoadHandlerHelper::getAttribSizeT("ts", true, this, ts)) {
text->setTimestamp(ts);
}
}
void LoadHandler::parseImage() {
double left = LoadHandlerHelper::getAttribDouble("left", this);
double top = LoadHandlerHelper::getAttribDouble("top", this);
double right = LoadHandlerHelper::getAttribDouble("right", this);
double bottom = LoadHandlerHelper::getAttribDouble("bottom", this);
xoj_assert(this->image == nullptr);
auto imageOwn = std::make_unique<Image>();
this->image = imageOwn.get();
this->layer->addElement(std::move(imageOwn));
this->image->setX(left);
this->image->setY(top);
this->image->setWidth(right - left);
this->image->setHeight(bottom - top);
}
void LoadHandler::parseTexImage() {
double left = LoadHandlerHelper::getAttribDouble("left", this);
double top = LoadHandlerHelper::getAttribDouble("top", this);
double right = LoadHandlerHelper::getAttribDouble("right", this);
double bottom = LoadHandlerHelper::getAttribDouble("bottom", this);
const char* imText = LoadHandlerHelper::getAttrib("text", false, this);
const char* compatibilityTest = LoadHandlerHelper::getAttrib("texlength", true, this);
auto imTextLen = strlen(imText);
if (compatibilityTest != nullptr) {
imTextLen = LoadHandlerHelper::getAttribSizeT("texlength", this);
}
auto teximageOwn = std::make_unique<TexImage>();
this->teximage = teximageOwn.get();
this->layer->addElement(std::move(teximageOwn));
this->teximage->setX(left);
this->teximage->setY(top);
this->teximage->setWidth(right - left);
this->teximage->setHeight(bottom - top);
this->teximage->setText(string(imText, imTextLen));
}
void LoadHandler::parseAttachment() {
if (this->pos != PARSER_POS_IN_IMAGE && this->pos != PARSER_POS_IN_TEXIMAGE) {
g_warning("Found attachment tag as child of a tag that should not have such a child (ignoring this tag)");
return;
}
const char* path = LoadHandlerHelper::getAttrib("path", false, this);
auto readResult = readZipAttachment(path);
if (!readResult) {
return;
}
std::string& imgData = *readResult;
switch (this->pos) {
case PARSER_POS_IN_IMAGE: {
this->image->setImage(std::move(imgData));
break;
}
case PARSER_POS_IN_TEXIMAGE: {
this->teximage->loadData(std::move(imgData), nullptr);
break;
}
default:
break;
}
}
void LoadHandler::parseLayer() {
/**
* read the timestamp before each stroke.
* Used for backwards compatibility
* against xoj files with timestamps)
**/
if (!strcmp(elementName, "timestamp")) {
loadedTimeStamp = LoadHandlerHelper::getAttribInt("ts", this);
loadedFilename = LoadHandlerHelper::getAttrib("fn", false, this);
}
if (!strcmp(elementName, "stroke")) // start of a stroke
{
this->pos = PARSER_POS_IN_STROKE;
parseStroke();
} else if (!strcmp(elementName, "text")) // start of a text item
{
this->pos = PARSER_POS_IN_TEXT;
parseText();
} else if (!strcmp(elementName, "image")) // start of a image item
{
this->pos = PARSER_POS_IN_IMAGE;
parseImage();
} else if (!strcmp(elementName, "teximage")) // start of a image item
{
this->pos = PARSER_POS_IN_TEXIMAGE;
parseTexImage();
}
}
/**
* Create a temporary file for the attached audio file.
* The OS should take care of removing the file.
*/
void LoadHandler::parseAudio() {
const char* filename = LoadHandlerHelper::getAttrib("fn", false, this);
GFileIOStream* fileStream = nullptr;
xoj::util::GObjectSPtr<GFile> tmpFile(g_file_new_tmp("xournal_audio_XXXXXX.tmp", &fileStream, nullptr),
xoj::util::adopt);
if (!tmpFile) {
g_warning("Unable to create temporary file for audio attachment.");
return;
}
GOutputStream* outputStream = g_io_stream_get_output_stream(G_IO_STREAM(fileStream));
zip_stat_t attachmentFileStat;
int statStatus = zip_stat(this->zipFp, filename, 0, &attachmentFileStat);
if (statStatus != 0) {
error("%s", FC(_F("Could not open attachment: {1}. Error message: {2}") % filename %
zip_error_strerror(zip_get_error(this->zipFp))));
return;
}
gsize length = 0;
if (attachmentFileStat.valid & ZIP_STAT_SIZE) {
length = attachmentFileStat.size;
} else {
error("%s", FC(_F("Could not open attachment: {1}. Error message: No valid file size provided") % filename));
return;
}
zip_file_t* attachmentFile = zip_fopen(this->zipFp, filename, 0);
if (!attachmentFile) {
error("%s", FC(_F("Could not open attachment: {1}. Error message: {2}") % filename %
zip_error_strerror(zip_get_error(this->zipFp))));
return;
}
gpointer data = g_malloc(1024);
zip_uint64_t readBytes = 0;
while (readBytes < length) {
zip_int64_t read = zip_fread(attachmentFile, data, 1024);
if (read == -1) {
g_free(data);
zip_fclose(attachmentFile);
error("%s", FC(_F("Could not open attachment: {1}. Error message: Could not read file") % filename));
return;
}
gboolean writeSuccessful =
g_output_stream_write_all(outputStream, data, static_cast<gsize>(read), nullptr, nullptr, nullptr);
if (!writeSuccessful) {
g_free(data);
zip_fclose(attachmentFile);
error("%s", FC(_F("Could not open attachment: {1}. Error message: Could not write file") % filename));
return;
}
readBytes += static_cast<zip_uint64_t>(read);
}
g_free(data);
zip_fclose(attachmentFile);
g_hash_table_insert(this->audioFiles, g_strdup(filename), g_file_get_path(tmpFile.get()));
}
void LoadHandler::parserStartElement(GMarkupParseContext* context, const gchar* elementName,
const gchar** attributeNames, const gchar** attributeValues, gpointer userdata,
GError** error) {
auto* handler = static_cast<LoadHandler*>(userdata);
// Return on error
if (*error) {
return;
}
handler->attributeNames = attributeNames;
handler->attributeValues = attributeValues;
handler->elementName = elementName;
if (handler->pos == PARSER_POS_NOT_STARTED) {
handler->parseStart();
} else if (handler->pos == PARSER_POS_STARTED) {
handler->parseContents();
} else if (handler->pos == PARSER_POS_IN_PAGE) {
handler->parsePage();
} else if (handler->pos == PARSER_POS_IN_LAYER) {
handler->parseLayer();
} else if (handler->pos == PARSER_POS_IN_IMAGE || handler->pos == PARSER_POS_IN_TEXIMAGE) {
// Handle the attachment node within the appropriate nodes
if (!strcmp(elementName, "attachment")) {
handler->parseAttachment();
}
}
handler->attributeNames = nullptr;
handler->attributeValues = nullptr;
handler->elementName = nullptr;
}
void LoadHandler::parserEndElement(GMarkupParseContext* context, const gchar* elementName, gpointer userdata,
GError** error) {
// Return on error
if (*error) {
return;
}
auto* handler = static_cast<LoadHandler*>(userdata);
if (handler->pos == PARSER_POS_STARTED && strcmp(elementName, handler->endRootTag) == 0) {
handler->pos = PASER_POS_FINISHED;
} else if (handler->pos == PARSER_POS_IN_PAGE && strcmp(elementName, "page") == 0) {
// handle unnecessary layer insertion in case of existing layers in file
if (handler->page->getLayerCount() == 0) {
handler->page->addLayer(new Layer());
}
handler->pos = PARSER_POS_STARTED;
handler->page = nullptr;
} else if (handler->pos == PARSER_POS_IN_LAYER && strcmp(elementName, "layer") == 0) {
handler->pos = PARSER_POS_IN_PAGE;
handler->layer = nullptr;
} else if (handler->pos == PARSER_POS_IN_LAYER && strcmp(elementName, "timestamp") == 0) {
/** Used for backwards compatibility against xoj files with timestamps) */
handler->pos = PARSER_POS_IN_LAYER;
handler->stroke = nullptr;
} else if (handler->pos == PARSER_POS_IN_STROKE && strcmp(elementName, "stroke") == 0) {
handler->pos = PARSER_POS_IN_LAYER;
handler->stroke = nullptr;
} else if (handler->pos == PARSER_POS_IN_TEXT && strcmp(elementName, "text") == 0) {
handler->pos = PARSER_POS_IN_LAYER;
handler->text = nullptr;
} else if (handler->pos == PARSER_POS_IN_IMAGE && strcmp(elementName, "image") == 0) {
xoj_assert_message(handler->image->getImage() != nullptr, "image can't be rendered");
handler->pos = PARSER_POS_IN_LAYER;
handler->image = nullptr;
} else if (handler->pos == PARSER_POS_IN_TEXIMAGE && strcmp(elementName, "teximage") == 0) {
handler->pos = PARSER_POS_IN_LAYER;
handler->teximage = nullptr;
}
}
void LoadHandler::fixNullPressureValues() {
/*
* Due to various bugs (see e.g. https://github.com/xournalpp/xournalpp/issues/3643), old files may contain strokes
* with non-positive pressure values.
*
* Those strokes thus fails the somewhat reasonable assumption that pressure values should be positive.
* The portions of stroke with non-positive pressure values are in any case invisible.
*
* This function fixes corrupted strokes by
* 1- removing every point with a non-positive pressure value.
* 2- if required, splitting the affected stroke into several strokes.
* 3- entirely deleting strokes without any valid pressure value
*/
auto& pts = stroke->getPointVector();
if (pressureBuffer.size() >= pts.size()) {
// Too many pressure values. Drop the last ones
xoj_assert(pts.size() >= 2); // An error has already been returned otherwise
pressureBuffer.resize(pts.size() - 1);
}
auto nextPositive = std::find_if(pressureBuffer.begin(), pressureBuffer.end(), [](double v) { return v > 0; });
std::vector<std::vector<Point>> strokePortions;
while (nextPositive != pressureBuffer.end()) {
auto nextNonPositive =
std::find_if(nextPositive, pressureBuffer.end(), [](double v) { return v <= 0 || std::isnan(v); });
size_t nValidPressureValues = static_cast<size_t>(std::distance(nextPositive, nextNonPositive));
std::vector<Point> ps;
ps.reserve(nValidPressureValues + 1);
std::transform(nextPositive, nextNonPositive,
std::next(pts.begin(), std::distance(pressureBuffer.begin(), nextPositive)),
std::back_inserter(ps), [](double v, const Point& p) { return Point(p.x, p.y, v); });
// pts.size() == pressureBuffer.size() + 1 so the following iterator is always dereferencable, even if
// nextNonPositive == pressureBuffer.end()
ps.emplace_back(*std::next(pts.begin(), std::distance(pressureBuffer.begin(), nextNonPositive)));
xoj_assert(ps.size() == nValidPressureValues + 1);
strokePortions.emplace_back(std::move(ps));
if (nextNonPositive == pressureBuffer.end()) {
break;
}
nextPositive = std::find_if(nextNonPositive, pressureBuffer.end(), [](double v) { return v > 0; });
}
if (strokePortions.empty()) {
// There was no valid pressure values! Delete the stroke entirely
g_warning("Found a stroke with only non-positive pressure values! Removing this invisible stroke.");
std::ignore = layer->removeElement(stroke);
stroke = nullptr;
return;
}
g_warning("Found a stroke with some non-positive pressure values. Removing the affected points.");
for_first_then_each(
strokePortions, [&](std::vector<Point>& points) { stroke->setPointVector(std::move(points)); },
[&](std::vector<Point>& points) {
auto strokeOwn = std::make_unique<Stroke>();
strokeOwn->applyStyleFrom(stroke);
strokeOwn->setPointVector(std::move(points));
stroke = strokeOwn.get();
layer->addElement(std::move(strokeOwn));
});
}
void LoadHandler::parserText(GMarkupParseContext* context, const gchar* text, gsize textLen, gpointer userdata,
GError** error) {
// Return on error
if (*error) {
return;
}
auto* handler = static_cast<LoadHandler*>(userdata);
if (handler->pos == PARSER_POS_IN_STROKE) {
const char* ptr = text;
int n = 0;
bool xRead = false;
double x = 0;
while (textLen > 0) {
double tmp = g_ascii_strtod(text, const_cast<char**>(&ptr));
if (ptr == text) {
break;
}
textLen -= as_unsigned(ptr - text);
text = ptr;
n++;
if (!xRead) {
xRead = true;
x = tmp;
} else {
xRead = false;
handler->stroke->addPoint(Point(x, tmp));
}
}
handler->stroke->freeUnusedPointItems();
if (n < 4 || (n & 1)) {
error2(*error, "%s", FC(_F("Wrong count of points ({1})") % n));
return;
}
if (!handler->pressureBuffer.empty()) {
if (handler->pressureBuffer.size() + 1 >= handler->stroke->getPointCount()) {
auto firstNonPositive = std::find_if(handler->pressureBuffer.begin(), handler->pressureBuffer.end(),
[](double v) { return v <= 0 || std::isnan(v); });
if (firstNonPositive != handler->pressureBuffer.end()) {
// Warning: this may delete handler->stroke if no positive pressure values are provided
// Do not dereference handler->stroke after that
handler->fixNullPressureValues();
} else {
handler->stroke->setPressure(handler->pressureBuffer);
}
} else {
g_warning("%s", FC(_F("xoj-File: {1}") % handler->filepath.u8string()));
g_warning("%s", FC(_F("Wrong number of pressure values, got {1}, expected {2}") %
handler->pressureBuffer.size() % (handler->stroke->getPointCount() - 1)));
}
handler->pressureBuffer.clear();
}
} else if (handler->pos == PARSER_POS_IN_TEXT) {
gchar* txt = g_strndup(text, textLen);
handler->text->setText(txt);
g_free(txt);
} else if (handler->pos == PARSER_POS_IN_IMAGE) {
handler->readImage(text, textLen);
} else if (handler->pos == PARSER_POS_IN_TEXIMAGE) {
handler->readTexImage(text, textLen);
}
}
auto LoadHandler::parseBase64(const gchar* base64, gsize length) -> string {
// We have to copy the string in order to null terminate it, sigh.
auto* base64data = static_cast<gchar*>(g_memdup(base64, static_cast<guint>(length) + 1));
base64data[length] = '\0';
gsize binaryBufferLen = 0;
guchar* binaryBuffer = g_base64_decode(base64data, &binaryBufferLen);
g_free(base64data);
string str = string(reinterpret_cast<char*>(binaryBuffer), binaryBufferLen);
g_free(binaryBuffer);
return str;
}
void LoadHandler::readImage(const gchar* base64string, gsize base64stringLen) {
xoj_assert(this->image != nullptr);
if (base64stringLen == 0 || (base64stringLen == 1 && base64string[0] == '\n') || this->image->hasData()) {
return;
}
this->image->setImage(parseBase64(const_cast<char*>(base64string), base64stringLen));
}
void LoadHandler::readTexImage(const gchar* base64string, gsize base64stringLen) {
if (base64stringLen == 1 && !strcmp(base64string, "\n")) {
return;
}
this->teximage->loadData(parseBase64(const_cast<char*>(base64string), base64stringLen));
}
auto LoadHandler::loadDocument(fs::path const& filepath) -> std::unique_ptr<Document> {
initAttributes();
this->doc = std::make_unique<Document>(&dHanlder);
if (!openFile(filepath)) {
this->doc.reset();
return nullptr;
}
xournalFilepath = filepath;
this->pdfFilenameParsed = false;
if (!parseXml()) {
closeFile();
this->doc.reset();
return nullptr;
}
if (fileVersion == 1) {
// This is a Xournal document, not a Xournal++
// Even if the new fileextension is .xopp, allow to
// overwrite .xoj files which are created by Xournal++
// Force the user to save is a bad idea, this will annoy the user
// Rename files is also not that user friendly.
doc->setFilepath("");
} else {
doc->setFilepath(filepath);
}
closeFile();
return std::move(this->doc);
}
auto LoadHandler::readZipAttachment(fs::path const& filename) -> std::unique_ptr<std::string> {
zip_stat_t attachmentFileStat;
const int statStatus = zip_stat(this->zipFp, filename.u8string().c_str(), 0, &attachmentFileStat);
if (statStatus != 0) {
error("%s", FC(_F("Could not open attachment: {1}. Error message: {2}") % filename.string() %
zip_error_strerror(zip_get_error(this->zipFp))));
return {};
}
if (!(attachmentFileStat.valid & ZIP_STAT_SIZE)) {
error("%s",
FC(_F("Could not open attachment: {1}. Error message: No valid file size provided") % filename.string()));
return {};
}
const zip_uint64_t length = attachmentFileStat.size;
zip_file_t* attachmentFile = zip_fopen(this->zipFp, filename.u8string().c_str(), 0);
if (!attachmentFile) {
error("%s", FC(_F("Could not open attachment: {1}. Error message: {2}") % filename.string() %
zip_error_strerror(zip_get_error(this->zipFp))));
return {};
}
auto data = std::make_unique<std::string>(length, 0);
zip_uint64_t readBytes = 0;
while (readBytes < length) {
const zip_int64_t read = zip_fread(attachmentFile, data->data() + readBytes, length - readBytes);
if (read == -1) {
zip_fclose(attachmentFile);
error("%s", FC(_F("Could not open attachment: {1}. Error message: No valid file size provided") %
filename.u8string()));
return {};
}
readBytes += static_cast<zip_uint64_t>(read);
}
zip_fclose(attachmentFile);
return data;
}
auto LoadHandler::getTempFileForPath(fs::path const& filename) -> fs::path {
gpointer tmpFilename = g_hash_table_lookup(this->audioFiles, filename.u8string().c_str());
if (tmpFilename) {
return string(static_cast<char*>(tmpFilename));
}
error("%s", FC(_F("Requested temporary file was not found for attachment {1}") % filename.u8string()));
return "";
}
auto LoadHandler::getFileVersion() const -> int { return this->fileVersion; }
| 42,998
|
C++
|
.cpp
| 1,004
| 34.713147
| 120
| 0.598522
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,492
|
SaveHandler.cpp
|
xournalpp_xournalpp/src/core/control/xojfile/SaveHandler.cpp
|
#include "SaveHandler.h"
#include <cinttypes> // for PRIx32
#include <cstdint> // for uint32_t
#include <cstdio> // for sprintf, size_t
#include <filesystem> // for exists
#include <cairo.h> // for cairo_surface_t
#include <gdk-pixbuf/gdk-pixbuf.h> // for gdk_pixbuf_save
#include <glib.h> // for g_free, g_strdup_printf
#include "control/pagetype/PageTypeHandler.h" // for PageTypeHandler
#include "control/xml/XmlAudioNode.h" // for XmlAudioNode
#include "control/xml/XmlImageNode.h" // for XmlImageNode
#include "control/xml/XmlNode.h" // for XmlNode
#include "control/xml/XmlPointNode.h" // for XmlPointNode
#include "control/xml/XmlTexNode.h" // for XmlTexNode
#include "control/xml/XmlTextNode.h" // for XmlTextNode
#include "model/AudioElement.h" // for AudioElement
#include "model/BackgroundImage.h" // for BackgroundImage
#include "model/Document.h" // for Document
#include "model/Element.h" // for Element, ELEMENT_IMAGE
#include "model/Font.h" // for XojFont
#include "model/Image.h" // for Image
#include "model/Layer.h" // for Layer
#include "model/LineStyle.h" // for LineStyle
#include "model/PageType.h" // for PageType
#include "model/Point.h" // for Point
#include "model/Stroke.h" // for Stroke, StrokeCapStyle
#include "model/StrokeStyle.h" // for StrokeStyle
#include "model/TexImage.h" // for TexImage
#include "model/Text.h" // for Text
#include "model/XojPage.h" // for XojPage
#include "pdf/base/XojPdfDocument.h" // for XojPdfDocument
#include "util/OutputStream.h" // for GzOutputStream, Output...
#include "util/PathUtil.h" // for clearExtensions
#include "util/PlaceholderString.h" // for PlaceholderString
#include "util/i18n.h" // for FS, _F
#include "config.h" // for FILE_FORMAT_VERSION
SaveHandler::SaveHandler() {
this->firstPdfPageVisited = false;
this->attachBgId = 1;
}
void SaveHandler::prepareSave(Document* doc) {
if (this->root) {
// cleanup old data
backgroundImages.clear();
}
this->firstPdfPageVisited = false;
this->attachBgId = 1;
root.reset(new XmlNode("xournal"));
writeHeader();
cairo_surface_t* preview = doc->getPreview();
if (preview) {
auto* image = new XmlImageNode("preview");
image->setImage(preview);
this->root->addChild(image);
}
for (size_t i = 0; i < doc->getPageCount(); i++) {
PageRef p = doc->getPage(i);
p->getBackgroundImage().clearSaveState();
}
for (size_t i = 0; i < doc->getPageCount(); i++) {
PageRef p = doc->getPage(i);
visitPage(root.get(), p, doc, static_cast<int>(i));
}
}
void SaveHandler::writeHeader() {
this->root->setAttrib("creator", PROJECT_STRING);
this->root->setAttrib("fileversion", FILE_FORMAT_VERSION);
this->root->addChild(new XmlTextNode("title", std::string{"Xournal++ document - see "} + PROJECT_HOMEPAGE_URL));
}
auto SaveHandler::getColorStr(Color c, unsigned char alpha) -> std::string {
char str[10];
sprintf(str, "#%08" PRIx32, uint32_t(c) << 8U | alpha);
std::string color(str);
return color;
}
void SaveHandler::writeTimestamp(AudioElement* audioElement, XmlAudioNode* xmlAudioNode) {
if (!audioElement->getAudioFilename().empty()) {
/** set stroke timestamp value to the XmlPointNode */
xmlAudioNode->setAttrib("ts", audioElement->getTimestamp());
xmlAudioNode->setAttrib("fn", audioElement->getAudioFilename().u8string());
}
}
void SaveHandler::visitStroke(XmlPointNode* stroke, Stroke* s) {
StrokeTool t = s->getToolType();
unsigned char alpha = 0xff;
if (t == StrokeTool::PEN) {
stroke->setAttrib("tool", "pen");
writeTimestamp(s, stroke);
} else if (t == StrokeTool::ERASER) {
stroke->setAttrib("tool", "eraser");
} else if (t == StrokeTool::HIGHLIGHTER) {
stroke->setAttrib("tool", "highlighter");
alpha = 0x7f;
} else {
g_warning("Unknown StrokeTool::Value");
stroke->setAttrib("tool", "pen");
}
stroke->setAttrib("color", getColorStr(s->getColor(), alpha).c_str());
const auto& pts = s->getPointVector();
stroke->setPoints(pts);
if (s->hasPressure()) {
std::vector<double> values;
values.reserve(pts.size() + 1);
values.emplace_back(s->getWidth());
std::transform(pts.begin(), pts.end() - 1, std::back_inserter(values), [](const Point& p) { return p.z; });
stroke->setAttrib("width", std::move(values));
} else {
stroke->setAttrib("width", s->getWidth());
}
visitStrokeExtended(stroke, s);
}
/**
* Export the fill attributes
*/
void SaveHandler::visitStrokeExtended(XmlPointNode* stroke, Stroke* s) {
if (s->getFill() != -1) {
stroke->setAttrib("fill", s->getFill());
}
const StrokeCapStyle capStyle = s->getStrokeCapStyle();
if (capStyle == StrokeCapStyle::BUTT) {
stroke->setAttrib("capStyle", "butt");
} else if (capStyle == StrokeCapStyle::ROUND) {
stroke->setAttrib("capStyle", "round");
} else if (capStyle == StrokeCapStyle::SQUARE) {
stroke->setAttrib("capStyle", "square");
} else {
g_warning("Unknown stroke cap type: %i", capStyle);
stroke->setAttrib("capStyle", "round");
}
if (s->getLineStyle().hasDashes()) {
stroke->setAttrib("style", StrokeStyle::formatStyle(s->getLineStyle()));
}
}
void SaveHandler::visitLayer(XmlNode* page, Layer* l) {
auto* layer = new XmlNode("layer");
page->addChild(layer);
if (l->hasName()) {
layer->setAttrib("name", l->getName().c_str());
}
for (auto&& e: l->getElements()) {
if (e->getType() == ELEMENT_STROKE) {
auto* s = dynamic_cast<Stroke*>(e.get());
auto* stroke = new XmlPointNode("stroke");
layer->addChild(stroke);
visitStroke(stroke, s);
} else if (e->getType() == ELEMENT_TEXT) {
Text* t = dynamic_cast<Text*>(e.get());
auto* text = new XmlTextNode("text", t->getText());
layer->addChild(text);
XojFont& f = t->getFont();
text->setAttrib("font", f.getName().c_str());
text->setAttrib("size", f.getSize());
text->setAttrib("x", t->getX());
text->setAttrib("y", t->getY());
text->setAttrib("color", getColorStr(t->getColor()).c_str());
writeTimestamp(t, text);
} else if (e->getType() == ELEMENT_IMAGE) {
auto* i = dynamic_cast<Image*>(e.get());
auto* image = new XmlImageNode("image");
layer->addChild(image);
image->setImage(i->getImage());
image->setAttrib("left", i->getX());
image->setAttrib("top", i->getY());
image->setAttrib("right", i->getX() + i->getElementWidth());
image->setAttrib("bottom", i->getY() + i->getElementHeight());
} else if (e->getType() == ELEMENT_TEXIMAGE) {
auto* i = dynamic_cast<TexImage*>(e.get());
auto* image = new XmlTexNode("teximage", std::string(i->getBinaryData()));
layer->addChild(image);
image->setAttrib("text", i->getText().c_str());
image->setAttrib("left", i->getX());
image->setAttrib("top", i->getY());
image->setAttrib("right", i->getX() + i->getElementWidth());
image->setAttrib("bottom", i->getY() + i->getElementHeight());
}
}
}
void SaveHandler::visitPage(XmlNode* root, PageRef p, Document* doc, int id) {
auto* page = new XmlNode("page");
root->addChild(page);
page->setAttrib("width", p->getWidth());
page->setAttrib("height", p->getHeight());
auto* background = new XmlNode("background");
page->addChild(background);
writeBackgroundName(background, p);
if (p->getBackgroundType().isPdfPage()) {
/**
* ATTENTION! The original xournal can only read the XML if the attributes are in the right order!
* DO NOT CHANGE THE ORDER OF THE ATTRIBUTES!
*/
background->setAttrib("type", "pdf");
if (!firstPdfPageVisited) {
firstPdfPageVisited = true;
if (doc->isAttachPdf()) {
background->setAttrib("domain", "attach");
auto filepath = doc->getFilepath();
Util::clearExtensions(filepath);
filepath += ".xopp.bg.pdf";
background->setAttrib("filename", "bg.pdf");
GError* error = nullptr;
if (!exists(filepath)) {
doc->getPdfDocument().save(filepath, &error);
}
if (error) {
if (!this->errorMessage.empty()) {
this->errorMessage += "\n";
}
this->errorMessage +=
FS(_F("Could not write background \"{1}\", {2}") % filepath.u8string() % error->message);
g_error_free(error);
}
} else {
background->setAttrib("domain", "absolute");
background->setAttrib("filename", doc->getPdfFilepath().u8string());
}
}
background->setAttrib("pageno", p->getPdfPageNr() + 1);
} else if (p->getBackgroundType().isImagePage()) {
background->setAttrib("type", "pixmap");
int cloneId = p->getBackgroundImage().getCloneId();
if (cloneId != -1) {
background->setAttrib("domain", "clone");
char* filename = g_strdup_printf("%i", cloneId);
background->setAttrib("filename", filename);
g_free(filename);
} else if (p->getBackgroundImage().isAttached() && p->getBackgroundImage().getPixbuf()) {
char* filename = g_strdup_printf("bg_%d.png", this->attachBgId++);
background->setAttrib("domain", "attach");
background->setAttrib("filename", filename);
p->getBackgroundImage().setFilepath(filename);
backgroundImages.emplace_back(p->getBackgroundImage());
g_free(filename);
p->getBackgroundImage().setCloneId(id);
} else {
background->setAttrib("domain", "absolute");
background->setAttrib("filename", p->getBackgroundImage().getFilepath().u8string());
p->getBackgroundImage().setCloneId(id);
}
} else {
writeSolidBackground(background, p);
}
// no layer, but we need to write one layer, else the old Xournal cannot read the file
if (p->getLayers()->empty()) {
auto* layer = new XmlNode("layer");
page->addChild(layer);
}
for (Layer* l: *p->getLayers()) {
visitLayer(page, l);
}
}
void SaveHandler::writeSolidBackground(XmlNode* background, PageRef p) {
background->setAttrib("type", "solid");
background->setAttrib("color", getColorStr(p->getBackgroundColor()));
background->setAttrib("style", PageTypeHandler::getStringForPageTypeFormat(p->getBackgroundType().format));
// Not compatible with Xournal, so the background needs
// to be changed to a basic one!
if (!p->getBackgroundType().config.empty()) {
background->setAttrib("config", p->getBackgroundType().config);
}
}
void SaveHandler::writeBackgroundName(XmlNode* background, PageRef p) {
if (p->backgroundHasName()) {
background->setAttrib("name", p->getBackgroundName());
}
}
void SaveHandler::saveTo(const fs::path& filepath, ProgressListener* listener) {
GzOutputStream out(filepath);
if (!out.getLastError().empty()) {
this->errorMessage = out.getLastError();
return;
}
saveTo(&out, filepath, listener);
out.close();
if (this->errorMessage.empty()) {
this->errorMessage = out.getLastError();
}
}
void SaveHandler::saveTo(OutputStream* out, const fs::path& filepath, ProgressListener* listener) {
// XMLNode should be locale-safe ( store doubles using Locale 'C' format
out->write("<?xml version=\"1.0\" standalone=\"no\"?>\n");
root->writeOut(out, listener);
for (BackgroundImage const& img: backgroundImages) {
auto tmpfn = (fs::path(filepath) += ".") += img.getFilepath();
if (!gdk_pixbuf_save(img.getPixbuf(), tmpfn.u8string().c_str(), "png", nullptr, nullptr)) {
if (!this->errorMessage.empty()) {
this->errorMessage += "\n";
}
this->errorMessage += FS(_F("Could not write background \"{1}\". Continuing anyway.") % tmpfn.u8string());
}
}
}
auto SaveHandler::getErrorMessage() -> std::string { return this->errorMessage; }
| 13,164
|
C++
|
.cpp
| 292
| 37.527397
| 118
| 0.590898
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,493
|
XojExportHandler.cpp
|
xournalpp_xournalpp/src/core/control/xojfile/XojExportHandler.cpp
|
#include "XojExportHandler.h"
#include <memory> // for unique_ptr, __shared_p...
#include <string> // for string, allocator, ope...
#include "control/pagetype/PageTypeHandler.h" // for PageTypeHandler
#include "control/xml/XmlNode.h" // for XmlNode
#include "control/xml/XmlTextNode.h" // for XmlTextNode
#include "model/PageType.h" // for PageTypeFormat, PageType
#include "model/XojPage.h" // for XojPage
#include "config.h" // for PROJECT_STRING, PROJEC...
class AudioElement;
class Stroke;
class XmlAudioNode;
class XmlPointNode;
XojExportHandler::XojExportHandler() = default;
XojExportHandler::~XojExportHandler() = default;
/**
* Export the fill attributes
*/
void XojExportHandler::visitStrokeExtended(XmlPointNode* stroke, Stroke* s) {
// Fill is not exported in .xoj
// Line style is also not supported
}
void XojExportHandler::writeHeader() {
this->root->setAttrib("creator", PROJECT_STRING);
// Keep this version on 2, as this is anyway not read by Xournal
this->root->setAttrib("fileversion", "2");
this->root->addChild(
new XmlTextNode("title", std::string{"Xournal document (Compatibility) - see "} + PROJECT_HOMEPAGE_URL));
}
void XojExportHandler::writeSolidBackground(XmlNode* background, PageRef p) {
background->setAttrib("type", "solid");
background->setAttrib("color", getColorStr(p->getBackgroundColor()));
PageTypeFormat bgFormat = p->getBackgroundType().format;
std::string format;
format = PageTypeHandler::getStringForPageTypeFormat(bgFormat);
if (bgFormat != PageTypeFormat::Plain && bgFormat != PageTypeFormat::Ruled && bgFormat != PageTypeFormat::Lined &&
bgFormat != PageTypeFormat::Graph) {
format = "plain";
}
background->setAttrib("style", format);
}
void XojExportHandler::writeTimestamp(AudioElement* audioElement, XmlAudioNode* xmlAudioNode) {
// Do nothing since timestamp are not supported by Xournal
}
void XojExportHandler::writeBackgroundName(XmlNode* background, PageRef p) {
// Do nothing since background name is not supported by Xournal
}
| 2,160
|
C++
|
.cpp
| 47
| 42.659574
| 118
| 0.718437
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,494
|
MetadataManager.cpp
|
xournalpp_xournalpp/src/core/control/settings/MetadataManager.cpp
|
#include "MetadataManager.h"
#include <algorithm> // for sort
#include <cstdlib> // for strtoll, strtod
#include <fstream> // for operator<<, basic_ostream, basic_stringb...
#include <memory> // for allocator_traits<>::value_type
#include <sstream> // for istringstream
#include <string> // for char_traits, string, getline, operator!=
#include <glib.h> // for g_get_real_time, g_message, g_warning, gint64
#include "util/PathUtil.h" // for getConfigSubfolder, getStateSubfolder
#include "util/XojMsgBox.h" // for XojMsgBox
using namespace std;
/**
* Get directory to store metadata files to
*/
static fs::path getMetadataDirectory() { return Util::getStateSubfolder("metadata"); }
/**
* Migrate metadata directory from legacy location
*/
static void migrateMetadataDirectory() {
// do not pass "metadata" to getConfigSubfolder() to avoid creating directory if it doesn't exist
auto legacyDir = Util::getConfigSubfolder() / "metadata";
if (!fs::is_directory(legacyDir)) {
// nothing to do
return;
}
// move all files to the new directory
auto newDir = getMetadataDirectory();
for (auto const& e: fs::directory_iterator(legacyDir)) {
auto newPath = newDir / e.path().filename();
Util::safeRenameFile(e, newPath);
}
// remove legacy directory
try {
fs::remove(legacyDir);
} catch (const fs::filesystem_error&) {
g_warning("Could not delete legacy metadata directory %s", legacyDir.c_str());
}
g_message("Migrated metadata directory from %s to %s", legacyDir.c_str(), newDir.c_str());
}
MetadataEntry::MetadataEntry(): valid(false), zoom(1), page(0), time(0) {}
MetadataManager::~MetadataManager() { documentChanged(); }
/**
* Delete an old metadata file
*/
void MetadataManager::deleteMetadataFile(fs::path const& path) {
// be careful, delete the Metadata file, NOT the Document!
if (path.extension() != ".metadata") {
g_warning("Try to delete non-metadata file: %s", path.string().c_str());
return;
}
try {
fs::remove(path);
} catch (const fs::filesystem_error&) {
g_warning("Could not delete metadata file %s", path.string().c_str());
}
}
/**
* Document was closed, a new document was opened etc.
*/
void MetadataManager::documentChanged() {
// take ownership of metadata
this->mutex.lock();
auto m = std::move(this->metadata);
this->mutex.unlock();
if (m == nullptr) {
return;
}
storeMetadata(*m);
}
auto sortMetadata(MetadataEntry& a, MetadataEntry& b) -> bool { return a.time > b.time; }
/**
* Load the metadata list (sorted)
*/
auto MetadataManager::loadList() -> vector<MetadataEntry> {
migrateMetadataDirectory();
auto folder = getMetadataDirectory();
vector<MetadataEntry> data;
try {
for (auto const& f: fs::directory_iterator(folder)) {
auto path = folder / f;
MetadataEntry entry = loadMetadataFile(path, f.path());
if (entry.valid) {
data.push_back(entry);
}
}
} catch (const fs::filesystem_error& e) {
XojMsgBox::showErrorToUser(nullptr, e.what());
return data;
}
std::sort(data.begin(), data.end(), sortMetadata);
return data;
}
/**
* Parse a single metadata file
*/
auto MetadataManager::loadMetadataFile(fs::path const& path, fs::path const& file) -> MetadataEntry {
MetadataEntry entry;
entry.metadataFile = path;
string line;
ifstream infile(path);
auto time = file.stem().string();
entry.time = strtoll(time.c_str(), nullptr, 10);
if (!getline(infile, line) || line != "XOJ-METADATA/1.0") {
deleteMetadataFile(path);
// Not valid
return entry;
}
if (!getline(infile, line)) {
deleteMetadataFile(path);
// Not valid
return entry;
}
istringstream iss(line);
iss >> entry.path;
if (!getline(infile, line) || line.length() < 6 || line.substr(0, 5) != "page=") {
deleteMetadataFile(path);
// Not valid
return entry;
}
entry.page = static_cast<int>(strtoll(line.substr(5).c_str(), nullptr, 10));
if (!getline(infile, line) || line.length() < 6 || line.substr(0, 5) != "zoom=") {
deleteMetadataFile(path);
// Not valid
return entry;
}
entry.zoom = strtod(line.substr(5).c_str(), nullptr);
entry.valid = true;
return entry;
}
/**
* Get the metadata for a file
*/
auto MetadataManager::getForFile(fs::path const& file) -> MetadataEntry {
vector<MetadataEntry> files = loadList();
MetadataEntry entry;
for (const MetadataEntry& e: files) {
if (e.path == file) {
entry = e;
break;
}
}
for (size_t i = 20; i < files.size(); i++) {
auto path = files[i].metadataFile;
deleteMetadataFile(path);
}
return entry;
}
/**
* Store metadata to file
*/
void MetadataManager::storeMetadata(const MetadataEntry& m) {
vector<MetadataEntry> files = loadList();
for (const MetadataEntry& e: files) {
if (e.path == m.path) {
// This is an old entry with the same path
deleteMetadataFile(e.metadataFile);
}
}
auto path = getMetadataDirectory();
gint64 time = g_get_real_time();
path /= std::to_string(time);
path += ".metadata";
ofstream out(path);
out << "XOJ-METADATA/1.0\n";
out << m.path << "\n";
out << "page=" << m.page << "\n";
out << "zoom=" << m.zoom << "\n";
out.close();
}
/**
* Store the current data into metadata
*/
void MetadataManager::storeMetadata(fs::path const& file, int page, double zoom) {
if (file.empty()) {
return;
}
this->mutex.lock();
if (metadata == nullptr) {
metadata = std::make_unique<MetadataEntry>();
}
metadata->valid = true;
metadata->path = file;
metadata->zoom = zoom;
metadata->page = page;
metadata->time = g_get_real_time();
this->mutex.unlock();
}
| 6,094
|
C++
|
.cpp
| 187
| 27.352941
| 101
| 0.628474
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,495
|
ButtonConfig.cpp
|
xournalpp_xournalpp/src/core/control/settings/ButtonConfig.cpp
|
#include "ButtonConfig.h"
#include "control/Tool.h" // for Tool
#include "control/ToolHandler.h" // for ToolHandler
ButtonConfig::ButtonConfig(ToolType action, Color color, ToolSize size, DrawingType drawingType, EraserType eraserMode,
StrokeType strokeType):
action(action),
color(color),
size(size),
eraserMode(eraserMode),
drawingType(drawingType),
strokeType(strokeType),
disableDrawing(false) {}
ButtonConfig::~ButtonConfig() = default;
auto ButtonConfig::getDisableDrawing() const -> bool { return this->disableDrawing; }
auto ButtonConfig::getDrawingType() -> DrawingType { return this->drawingType; }
auto ButtonConfig::getAction() -> ToolType { return this->action; }
void ButtonConfig::initButton(ToolHandler* toolHandler, Button button) {
if (this->action == TOOL_NONE) {
return;
}
toolHandler->resetButtonTool(this->action, button);
if (this->action == TOOL_PEN || this->action == TOOL_HIGHLIGHTER || this->action == TOOL_ERASER) {
if (this->size != TOOL_SIZE_NONE) {
toolHandler->setButtonSize(this->size, button);
}
if (this->action == TOOL_PEN)
if (this->strokeType != STROKE_TYPE_NONE)
toolHandler->setButtonStrokeType(this->strokeType, button);
if (this->action == TOOL_PEN || this->action == TOOL_HIGHLIGHTER) {
toolHandler->setButtonColor(this->color, button);
if (this->drawingType != DRAWING_TYPE_DONT_CHANGE)
toolHandler->setButtonDrawingType(this->drawingType, button);
}
if (this->action == TOOL_ERASER) {
if (this->eraserMode != ERASER_TYPE_NONE)
toolHandler->setButtonEraserType(this->eraserMode, button);
}
}
}
void ButtonConfig::applyConfigToToolbarTool(ToolHandler* toolHandler) {
if (this->action == TOOL_NONE) {
return;
}
toolHandler->selectTool(this->action);
if (this->action == TOOL_PEN || this->action == TOOL_HIGHLIGHTER || this->action == TOOL_ERASER) {
if (this->size != TOOL_SIZE_NONE) {
toolHandler->setSize(this->size);
}
if (this->action == TOOL_PEN || this->action == TOOL_HIGHLIGHTER) {
toolHandler->setColor(this->color, false);
if (this->drawingType != DRAWING_TYPE_DONT_CHANGE)
toolHandler->setDrawingType(this->drawingType);
}
if (this->action == TOOL_ERASER) {
if (this->eraserMode != ERASER_TYPE_NONE)
toolHandler->setEraserType(this->eraserMode);
}
if (this->action == TOOL_PEN && this->strokeType != STROKE_TYPE_NONE) {
toolHandler->setLineStyle(strokeTypeToLineStyle(this->strokeType));
}
}
}
auto ButtonConfig::applyNoChangeSettings(ToolHandler* toolHandler, Button button) -> bool {
if (this->action == TOOL_NONE) {
return false;
}
if (this->action == TOOL_PEN || this->action == TOOL_HIGHLIGHTER || this->action == TOOL_ERASER) {
Tool const& correspondingTool = toolHandler->getTool(this->action);
if (this->size == TOOL_SIZE_NONE) {
toolHandler->setButtonSize(correspondingTool.getSize(), button);
}
if (this->action == TOOL_PEN || this->action == TOOL_HIGHLIGHTER) {
if (this->drawingType == DRAWING_TYPE_DONT_CHANGE)
toolHandler->setButtonDrawingType(correspondingTool.getDrawingType(), button);
}
if (this->action == TOOL_ERASER) {
if (this->eraserMode == ERASER_TYPE_NONE)
toolHandler->setButtonEraserType(correspondingTool.getEraserType(), button);
}
if (this->action == TOOL_PEN && this->strokeType == STROKE_TYPE_NONE)
toolHandler->setButtonStrokeType(correspondingTool.getLineStyle(), button);
}
return true;
}
| 3,930
|
C++
|
.cpp
| 84
| 38.107143
| 119
| 0.632829
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,496
|
ViewModes.cpp
|
xournalpp_xournalpp/src/core/control/settings/ViewModes.cpp
|
#include "ViewModes.h"
#include "util/StringUtils.h"
#include <iostream>
auto ViewMode::operator==(const ViewMode& other) const -> bool {
return (this->goFullscreen == other.goFullscreen) && (this->showMenubar == other.showMenubar) &&
(this->showToolbar == other.showToolbar) && (this->showSidebar == other.showSidebar);
}
struct ViewMode settingsStringToViewMode(std::string viewModeString) {
struct ViewMode viewMode;
for (const std::string& attr : StringUtils::split(viewModeString, ',')) {
if (attr.compare(ATTR_GO_FULLSCREEN) == 0) {
viewMode.goFullscreen = true;
} else if (attr.compare(ATTR_SHOW_MENUBAR) == 0) {
viewMode.showMenubar = true;
} else if (attr.compare(ATTR_SHOW_TOOLBAR) == 0) {
viewMode.showToolbar = true;
} else if (attr.compare(ATTR_SHOW_SIDEBAR) == 0) {
viewMode.showSidebar = true;
}
}
return viewMode;
}
const std::string viewModeToSettingsString(struct ViewMode viewMode) {
if (!(viewMode.goFullscreen || viewMode.showMenubar || viewMode.showToolbar || viewMode.showSidebar)) {
return "";
}
return ((viewMode.goFullscreen ? "," + static_cast<std::string>(ATTR_GO_FULLSCREEN) : "")
+ (viewMode.showMenubar ? "," + static_cast<std::string>(ATTR_SHOW_MENUBAR) : "")
+ (viewMode.showToolbar ? "," + static_cast<std::string>(ATTR_SHOW_TOOLBAR) : "")
+ (viewMode.showSidebar ? "," + static_cast<std::string>(ATTR_SHOW_SIDEBAR) : "")).erase(0,1);
}
| 1,538
|
C++
|
.cpp
| 31
| 43.225806
| 107
| 0.649368
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,497
|
PageTemplateSettings.cpp
|
xournalpp_xournalpp/src/core/control/settings/PageTemplateSettings.cpp
|
#include "PageTemplateSettings.h"
#include <sstream> // for basic_istream, strings...
#include "control/pagetype/PageTypeHandler.h" // for PageTypeHandler
using std::string;
using std::stringstream;
PageTemplateSettings::PageTemplateSettings():
copyLastPageSettings(true),
copyLastPageSize(false),
pageWidth(595.275591),
pageHeight(841.889764),
backgroundColor(Colors::white) {
backgroundType.format = PageTypeFormat::Lined;
}
PageTemplateSettings::~PageTemplateSettings() = default;
auto PageTemplateSettings::isCopyLastPageSettings() const -> bool { return this->copyLastPageSettings; }
void PageTemplateSettings::setCopyLastPageSettings(bool copyLastPageSettings) {
this->copyLastPageSettings = copyLastPageSettings;
}
auto PageTemplateSettings::isCopyLastPageSize() const -> bool { return this->copyLastPageSize; }
void PageTemplateSettings::setCopyLastPageSize(bool copyLastPageSize) { this->copyLastPageSize = copyLastPageSize; }
auto PageTemplateSettings::getPageWidth() const -> double { return this->pageWidth; }
void PageTemplateSettings::setPageWidth(double pageWidth) { this->pageWidth = pageWidth; }
auto PageTemplateSettings::getPageHeight() const -> double { return this->pageHeight; }
void PageTemplateSettings::setPageHeight(double pageHeight) { this->pageHeight = pageHeight; }
auto PageTemplateSettings::getBackgroundColor() const -> Color { return this->backgroundColor; }
void PageTemplateSettings::setBackgroundColor(Color backgroundColor) { this->backgroundColor = backgroundColor; }
auto PageTemplateSettings::getBackgroundType() -> PageType { return backgroundType; }
auto PageTemplateSettings::getPageInsertType() -> std::optional<PageType> {
if (copyLastPageSettings) {
return std::nullopt;
}
return backgroundType;
}
void PageTemplateSettings::setBackgroundType(const PageType& backgroundType) { this->backgroundType = backgroundType; }
/**
* Parse a template string
*
* @return true if valid
*/
auto PageTemplateSettings::parse(const std::string& tpl) -> bool {
stringstream ss(tpl);
string line;
if (!std::getline(ss, line, '\n')) {
return false;
}
if (line != "xoj/template") {
return false;
}
while (std::getline(ss, line, '\n')) {
size_t pos = line.find('=');
if (pos == string::npos) {
continue;
}
string key = line.substr(0, pos);
string value = line.substr(pos + 1);
if (key == "copyLastPageSettings") {
copyLastPageSettings = value == "true";
} else if (key == "copyLastPageSize") {
copyLastPageSize = value == "true";
} else if (key == "size") {
pos = value.find('x');
pageWidth = std::stod(value.substr(0, pos));
pageHeight = std::stod(value.substr(pos + 1));
} else if (key == "backgroundColor") {
backgroundColor = Color(static_cast<uint32_t>(std::stoul(value.substr(1), nullptr, 16)));
} else if (key == "backgroundType") {
this->backgroundType.format = PageTypeHandler::getPageTypeFormatForString(value);
} else if (key == "backgroundTypeConfig") {
this->backgroundType.config = value;
}
}
return true;
}
/**
* Convert to a parsable string
*/
auto PageTemplateSettings::toString() const -> string {
string str = "xoj/template\n";
str += string("copyLastPageSize=") + (copyLastPageSize ? "true" : "false") + "\n";
str += string("copyLastPageSettings=") + (copyLastPageSettings ? "true" : "false") + "\n";
str += string("size=") + std::to_string(pageWidth) + "x" + std::to_string(pageHeight) + "\n";
str += string("backgroundType=") + PageTypeHandler::getStringForPageTypeFormat(backgroundType.format) + "\n";
if (!backgroundType.config.empty()) {
str += string("backgroundTypeConfig=") + backgroundType.config + "\n";
}
str += string("backgroundColor=") + Util::rgb_to_hex_string(this->backgroundColor) + "\n";
return str;
}
| 4,074
|
C++
|
.cpp
| 88
| 40.693182
| 119
| 0.687737
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,498
|
SettingsEnums.cpp
|
xournalpp_xournalpp/src/core/control/settings/SettingsEnums.cpp
|
#include "SettingsEnums.h"
#include <glib.h> // for g_warning
auto stylusCursorTypeFromString(const std::string& stylusCursorTypeStr) -> StylusCursorType {
if (stylusCursorTypeStr == "none") {
return STYLUS_CURSOR_NONE;
}
if (stylusCursorTypeStr == "dot") {
return STYLUS_CURSOR_DOT;
}
if (stylusCursorTypeStr == "big") {
return STYLUS_CURSOR_BIG;
}
if (stylusCursorTypeStr == "arrow") {
return STYLUS_CURSOR_ARROW;
}
g_warning("Settings::Unknown stylus cursor type: %s\n", stylusCursorTypeStr.c_str());
return STYLUS_CURSOR_DOT;
}
auto eraserVisibilityFromString(const std::string& eraserVisibility) -> EraserVisibility {
if (eraserVisibility == "never") {
return ERASER_VISIBILITY_NEVER;
}
if (eraserVisibility == "always") {
return ERASER_VISIBILITY_ALWAYS;
}
if (eraserVisibility == "hover") {
return ERASER_VISIBILITY_HOVER;
}
if (eraserVisibility == "touch") {
return ERASER_VISIBILITY_TOUCH;
}
g_warning("Settings::Unknown eraser visibility: %s\n", eraserVisibility.c_str());
return ERASER_VISIBILITY_ALWAYS;
}
auto iconThemeFromString(const std::string& iconThemeStr) -> IconTheme {
if (iconThemeStr == "iconsColor") {
return ICON_THEME_COLOR;
}
if (iconThemeStr == "iconsLucide") {
return ICON_THEME_LUCIDE;
}
g_warning("Settings::Unknown icon theme: %s\n", iconThemeStr.c_str());
return ICON_THEME_COLOR;
}
auto themeVariantFromString(const std::string& themeVariantStr) -> ThemeVariant {
if (themeVariantStr == "useSystem") {
return THEME_VARIANT_USE_SYSTEM;
}
if (themeVariantStr == "forceLight") {
return THEME_VARIANT_FORCE_LIGHT;
}
if (themeVariantStr == "forceDark") {
return THEME_VARIANT_FORCE_DARK;
}
g_warning("Settings::Unknown theme variant: %s\n", themeVariantStr.c_str());
return THEME_VARIANT_USE_SYSTEM;
}
auto emptyLastPageAppendFromString(const std::string& str) -> EmptyLastPageAppendType {
if (str == "disabled") {
return EmptyLastPageAppendType::Disabled;
}
if (str == "onDrawOfLastPage") {
return EmptyLastPageAppendType::OnDrawOfLastPage;
}
if (str == "onScrollOfLastPage") {
return EmptyLastPageAppendType::OnScrollToEndOfLastPage;
}
g_warning("Settings::Unknown empty last page append type: %s\n", str.c_str());
return EmptyLastPageAppendType::Disabled;
}
| 2,495
|
C++
|
.cpp
| 70
| 30.314286
| 93
| 0.680728
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,499
|
Settings.cpp
|
xournalpp_xournalpp/src/core/control/settings/Settings.cpp
|
#include "Settings.h"
#include <algorithm> // for max
#include <cstdint> // for uint32_t, int32_t
#include <cstdio> // for sscanf, size_t
#include <cstdlib> // for atoi
#include <cstring> // for strcmp
#include <exception> // for exception
#include <type_traits> // for add_const<>::type
#include <utility> // for pair, move, make_...
#include <libxml/globals.h> // for xmlFree, xmlInden...
#include <libxml/parser.h> // for xmlKeepBlanksDefault
#include <libxml/xmlstring.h> // for xmlStrcmp, xmlChar
#include "control/DeviceListHelper.h" // for InputDevice
#include "control/ToolEnums.h" // for ERASER_TYPE_NONE
#include "control/settings/LatexSettings.h" // for LatexSettings
#include "control/settings/SettingsEnums.h" // for InputDeviceTypeOp...
#include "gui/toolbarMenubar/model/ColorPalette.h" // for Palette
#include "model/FormatDefinitions.h" // for FormatUnits, XOJ_...
#include "util/Color.h"
#include "util/PathUtil.h" // for getConfigFile
#include "util/Util.h" // for PRECISION_FORMAT_...
#include "util/i18n.h" // for _#include "util/safe_casts.h" // for as_unsigned
#include "ButtonConfig.h" // for ButtonConfig
#include "config-dev.h" // for PALETTE_FILE
#include "config-dev.h"
#include "filesystem.h" // for path, u8path, exists
using std::string;
constexpr auto const* DEFAULT_FONT = "Sans";
constexpr auto DEFAULT_FONT_SIZE = 12;
constexpr auto DEFAULT_TOOLBAR = "Portrait";
#define SAVE_BOOL_PROP(var) xmlNode = saveProperty((const char*)#var, (var) ? "true" : "false", root)
#define SAVE_STRING_PROP(var) xmlNode = saveProperty((const char*)#var, (var).empty() ? "" : (var).c_str(), root)
#define SAVE_FONT_PROP(var) xmlNode = saveProperty((const char*)#var, var.asString().c_str(), root)
#define SAVE_INT_PROP(var) xmlNode = saveProperty((const char*)#var, var, root)
#define SAVE_UINT_PROP(var) xmlNode = savePropertyUnsigned((const char*)#var, var, root)
#define SAVE_DOUBLE_PROP(var) xmlNode = savePropertyDouble((const char*)#var, var, root)
#define ATTACH_COMMENT(var) \
com = xmlNewComment((const xmlChar*)(var)); \
xmlAddPrevSibling(xmlNode, com);
Settings::Settings(fs::path filepath): filepath(std::move(filepath)) { loadDefault(); }
Settings::~Settings() = default;
void Settings::loadDefault() {
this->pressureSensitivity = true;
this->minimumPressure = 0.05;
this->pressureMultiplier = 1.0;
this->pressureGuessing = false;
this->zoomGesturesEnabled = true;
this->maximized = false;
this->showPairedPages = false;
this->presentationMode = false;
this->numColumns = 1; // only one of these applies at a time
this->numRows = 1;
this->viewFixedRows = false;
this->layoutVertical = false;
this->layoutRightToLeft = false;
this->layoutBottomToTop = false;
this->numPairsOffset = 1;
this->emptyLastPageAppend = EmptyLastPageAppendType::Disabled;
this->edgePanSpeed = 20.0;
this->edgePanMaxMult = 5.0;
this->zoomStep = 10.0;
this->zoomStepScroll = 2.0;
this->displayDpi = 72;
this->font.setName(DEFAULT_FONT);
this->font.setSize(DEFAULT_FONT_SIZE);
this->mainWndWidth = 800;
this->mainWndHeight = 600;
this->fullscreenActive = false;
this->showSidebar = true;
this->sidebarWidth = 150;
this->sidebarNumberingStyle = SidebarNumberingStyle::DEFAULT;
this->showToolbar = true;
this->selectedToolbar = DEFAULT_TOOLBAR;
this->sidebarOnRight = false;
this->scrollbarOnLeft = false;
this->menubarVisible = true;
this->autoloadMostRecent = false;
this->autoloadPdfXoj = true;
this->stylusCursorType = STYLUS_CURSOR_DOT;
this->eraserVisibility = ERASER_VISIBILITY_ALWAYS;
this->iconTheme = ICON_THEME_COLOR;
this->themeVariant = THEME_VARIANT_USE_SYSTEM;
this->highlightPosition = false;
this->cursorHighlightColor = 0x80FFFF00; // Yellow with 50% opacity
this->cursorHighlightRadius = 30.0;
this->cursorHighlightBorderColor = 0x800000FF; // Blue with 50% opacity
this->cursorHighlightBorderWidth = 0.0;
this->useStockIcons = false;
this->scrollbarHideType = SCROLLBAR_HIDE_NONE;
this->disableScrollbarFadeout = false;
this->disableAudio = false;
// Set this for autosave frequency in minutes.
this->autosaveTimeout = 3;
this->autosaveEnabled = true;
this->addHorizontalSpace = false;
this->addHorizontalSpaceAmountRight = 150;
this->addHorizontalSpaceAmountLeft = 150;
this->addVerticalSpace = false;
this->addVerticalSpaceAmountAbove = 150;
this->addVerticalSpaceAmountBelow = 150;
this->unlimitedScrolling = false;
// Drawing direction emulates modifier keys
this->drawDirModsRadius = 50;
this->drawDirModsEnabled = false;
this->snapRotation = true;
this->snapRotationTolerance = 0.30;
this->snapGrid = true;
this->snapGridTolerance = 0.50;
this->snapGridSize = DEFAULT_GRID_SIZE;
this->strokeRecognizerMinSize = 40;
this->touchDrawing = false;
this->gtkTouchInertialScrolling = true;
this->defaultSaveName = _("%F-Note-%H-%M");
this->defaultPdfExportName = _("%{name}_annotated");
// Eraser
this->buttonConfig[BUTTON_ERASER] = std::make_unique<ButtonConfig>(TOOL_ERASER, Colors::black, TOOL_SIZE_NONE,
DRAWING_TYPE_DEFAULT, ERASER_TYPE_NONE);
// Middle button
this->buttonConfig[BUTTON_MOUSE_MIDDLE] = std::make_unique<ButtonConfig>(TOOL_HAND, Colors::black, TOOL_SIZE_NONE,
DRAWING_TYPE_DEFAULT, ERASER_TYPE_NONE);
// Right button
this->buttonConfig[BUTTON_MOUSE_RIGHT] = std::make_unique<ButtonConfig>(TOOL_NONE, Colors::black, TOOL_SIZE_NONE,
DRAWING_TYPE_DEFAULT, ERASER_TYPE_NONE);
// Touch
this->buttonConfig[BUTTON_TOUCH] = std::make_unique<ButtonConfig>(TOOL_NONE, Colors::black, TOOL_SIZE_NONE,
DRAWING_TYPE_DEFAULT, ERASER_TYPE_NONE);
// Default config
this->buttonConfig[BUTTON_DEFAULT] = std::make_unique<ButtonConfig>(TOOL_PEN, Colors::black, TOOL_SIZE_FINE,
DRAWING_TYPE_DEFAULT, ERASER_TYPE_NONE);
// Pen button 1
this->buttonConfig[BUTTON_STYLUS_ONE] = std::make_unique<ButtonConfig>(TOOL_NONE, Colors::black, TOOL_SIZE_NONE,
DRAWING_TYPE_DEFAULT, ERASER_TYPE_NONE);
// Pen button 2
this->buttonConfig[BUTTON_STYLUS_TWO] = std::make_unique<ButtonConfig>(TOOL_NONE, Colors::black, TOOL_SIZE_NONE,
DRAWING_TYPE_DEFAULT, ERASER_TYPE_NONE);
// default view modes
this->activeViewMode = PresetViewModeIds::VIEW_MODE_DEFAULT;
this->viewModes =
std::vector<ViewMode>{VIEW_MODE_STRUCT_DEFAULT, VIEW_MODE_STRUCT_FULLSCREEN, VIEW_MODE_STRUCT_PRESENTATION};
this->touchZoomStartThreshold = 0.0;
this->pageRerenderThreshold = 5.0;
this->pdfPageCacheSize = 10;
this->preloadPagesBefore = 3U;
this->preloadPagesAfter = 5U;
this->eagerPageCleanup = true;
this->selectionBorderColor = Colors::red;
this->selectionMarkerColor = Colors::xopp_cornflowerblue;
this->activeSelectionColor = Colors::lawngreen;
this->backgroundColor = Colors::xopp_gainsboro02;
// clang-format off
this->pageTemplate = "xoj/template\ncopyLastPageSettings=true\nsize=595.275591x841.889764\nbackgroundType=lined\nbackgroundColor=#ffffff\n";
// clang-format on
this->audioSampleRate = 44100.0;
this->audioInputDevice = AUDIO_INPUT_SYSTEM_DEFAULT;
this->audioOutputDevice = AUDIO_OUTPUT_SYSTEM_DEFAULT;
this->audioGain = 1.0;
this->defaultSeekTime = 5;
this->pluginEnabled = "";
this->pluginDisabled = "";
this->numIgnoredStylusEvents = 0;
this->inputSystemTPCButton = false;
this->inputSystemDrawOutsideWindow = true;
this->strokeFilterIgnoreTime = 150;
this->strokeFilterIgnoreLength = 1;
this->strokeFilterSuccessiveTime = 500;
this->strokeFilterEnabled = false;
this->doActionOnStrokeFiltered = false;
this->trySelectOnStrokeFiltered = false;
this->snapRecognizedShapesEnabled = false;
this->restoreLineWidthEnabled = false;
this->inTransaction = false;
/**
* Stabilizer related settings
*/
this->stabilizerAveragingMethod = StrokeStabilizer::AveragingMethod::NONE;
this->stabilizerPreprocessor = StrokeStabilizer::Preprocessor::NONE;
this->stabilizerBuffersize = 20;
this->stabilizerSigma = 0.5;
this->stabilizerDeadzoneRadius = 1.3;
this->stabilizerCuspDetection = true;
this->stabilizerDrag = 0.4;
this->stabilizerMass = 5.0;
this->stabilizerFinalizeStroke = true;
/**/
this->useSpacesForTab = false;
this->numberOfSpacesForTab = 4;
this->colorPaletteSetting = Util::getBuiltInPaletteDirectoryPath() / DEFAULT_PALETTE_FILE;
}
auto Settings::loadViewMode(ViewModeId mode) -> bool {
if (mode < 0 || mode >= viewModes.size()) {
return false;
}
auto viewMode = viewModes.at(mode);
fullscreenActive = viewMode.goFullscreen;
menubarVisible = viewMode.showMenubar;
showToolbar = viewMode.showToolbar;
showSidebar = viewMode.showSidebar;
this->activeViewMode = mode;
return true;
}
auto Settings::getViewModes() const -> const std::vector<ViewMode>& { return this->viewModes; }
auto Settings::getActiveViewMode() const -> ViewModeId { return this->activeViewMode; }
/**
* tempg_ascii_strtod
* Transition to using g_ascii_strtod to minimize disruption. May, 2019.
* Delete this and replace calls to this function with calls to g_ascii_strtod() in 2020.
* See: https://developer.gnome.org/glib/stable/glib-String-Utility-Functions.html#g-strtod
*/
auto tempg_ascii_strtod(const gchar* txt, gchar** endptr) -> double {
return g_strtod(txt,
endptr); // makes best guess between locale formatted and C formatted numbers. See link above.
}
void Settings::parseData(xmlNodePtr cur, SElement& elem) {
for (xmlNodePtr x = cur->children; x != nullptr; x = x->next) {
if (!xmlStrcmp(x->name, reinterpret_cast<const xmlChar*>("data"))) {
xmlChar* name = xmlGetProp(x, reinterpret_cast<const xmlChar*>("name"));
parseData(x, elem.child(reinterpret_cast<const char*>(name)));
xmlFree(name);
} else if (!xmlStrcmp(x->name, reinterpret_cast<const xmlChar*>("attribute"))) {
xmlChar* name = xmlGetProp(x, reinterpret_cast<const xmlChar*>("name"));
xmlChar* value = xmlGetProp(x, reinterpret_cast<const xmlChar*>("value"));
xmlChar* type = xmlGetProp(x, reinterpret_cast<const xmlChar*>("type"));
string sType = reinterpret_cast<const char*>(type);
if (sType == "int") {
int i = atoi(reinterpret_cast<const char*>(value));
elem.setInt(reinterpret_cast<const char*>(name), i);
} else if (sType == "double") {
double d = tempg_ascii_strtod(reinterpret_cast<const char*>(value),
nullptr); // g_ascii_strtod ignores locale setting.
elem.setDouble(reinterpret_cast<const char*>(name), d);
} else if (sType == "hex") {
int i = 0;
if (sscanf(reinterpret_cast<const char*>(value), "%x", &i)) {
elem.setIntHex(reinterpret_cast<const char*>(name), i);
} else {
g_warning("Settings::Unknown hex value: %s:%s\n", name, value);
}
} else if (sType == "string") {
elem.setString(reinterpret_cast<const char*>(name), reinterpret_cast<const char*>(value));
} else if (sType == "boolean") {
elem.setBool(reinterpret_cast<const char*>(name),
strcmp(reinterpret_cast<const char*>(value), "true") == 0);
} else {
g_warning("Settings::Unknown datatype: %s\n", sType.c_str());
}
xmlFree(name);
xmlFree(type);
xmlFree(value);
} else {
g_warning("Settings::parseData: Unknown XML node: %s\n", x->name);
continue;
}
}
}
void Settings::parseItem(xmlDocPtr doc, xmlNodePtr cur) {
// Parse data map
if (!xmlStrcmp(cur->name, reinterpret_cast<const xmlChar*>("data"))) {
xmlChar* name = xmlGetProp(cur, reinterpret_cast<const xmlChar*>("name"));
if (name == nullptr) {
g_warning("Settings::%s:No name property!\n", cur->name);
return;
}
parseData(cur, data[reinterpret_cast<const char*>(name)]);
xmlFree(name);
return;
}
if (cur->type == XML_COMMENT_NODE) {
return;
}
if (xmlStrcmp(cur->name, reinterpret_cast<const xmlChar*>("property"))) {
g_warning("Settings::Unknown XML node: %s\n", cur->name);
return;
}
xmlChar* name = xmlGetProp(cur, reinterpret_cast<const xmlChar*>("name"));
if (name == nullptr) {
g_warning("Settings::%s:No name property!\n", cur->name);
return;
}
if (xmlStrcmp(name, reinterpret_cast<const xmlChar*>("font")) == 0) {
xmlFree(name);
xmlChar* font = nullptr;
xmlChar* size = nullptr;
font = xmlGetProp(cur, reinterpret_cast<const xmlChar*>("font"));
if (font) {
this->font.setName(reinterpret_cast<const char*>(font));
xmlFree(font);
}
size = xmlGetProp(cur, reinterpret_cast<const xmlChar*>("size"));
if (size) {
double dSize = DEFAULT_FONT_SIZE;
if (sscanf(reinterpret_cast<const char*>(size), "%lf", &dSize) == 1) {
this->font.setSize(dSize);
}
xmlFree(size);
}
return;
}
xmlChar* value = xmlGetProp(cur, reinterpret_cast<const xmlChar*>("value"));
if (value == nullptr) {
xmlFree(name);
g_warning("Settings::No value property!\n");
return;
}
// TODO(fabian): remove this typo fix in 2-3 release cycles
if (xmlStrcmp(name, reinterpret_cast<const xmlChar*>("presureSensitivity")) == 0) {
this->pressureSensitivity = xmlStrcmp(value, reinterpret_cast<const xmlChar*>("true")) == 0;
}
if (xmlStrcmp(name, reinterpret_cast<const xmlChar*>("pressureSensitivity")) == 0) {
this->pressureSensitivity = xmlStrcmp(value, reinterpret_cast<const xmlChar*>("true")) == 0;
} else if (xmlStrcmp(name, reinterpret_cast<const xmlChar*>("minimumPressure")) == 0) {
// std::max is for backwards compatibility for users who might have set this value too small
this->minimumPressure = std::max(0.01, g_ascii_strtod(reinterpret_cast<const char*>(value), nullptr));
} else if (xmlStrcmp(name, reinterpret_cast<const xmlChar*>("pressureMultiplier")) == 0) {
this->pressureMultiplier = g_ascii_strtod(reinterpret_cast<const char*>(value), nullptr);
} else if (xmlStrcmp(name, reinterpret_cast<const xmlChar*>("zoomGesturesEnabled")) == 0) {
this->zoomGesturesEnabled = xmlStrcmp(value, reinterpret_cast<const xmlChar*>("true")) == 0;
} else if (xmlStrcmp(name, reinterpret_cast<const xmlChar*>("selectedToolbar")) == 0) {
this->selectedToolbar = reinterpret_cast<const char*>(value);
} else if (xmlStrcmp(name, reinterpret_cast<const xmlChar*>("lastSavePath")) == 0) {
this->lastSavePath = fs::u8path(reinterpret_cast<const char*>(value));
} else if (xmlStrcmp(name, reinterpret_cast<const xmlChar*>("lastOpenPath")) == 0) {
this->lastOpenPath = fs::u8path(reinterpret_cast<const char*>(value));
} else if (xmlStrcmp(name, reinterpret_cast<const xmlChar*>("lastImagePath")) == 0) {
this->lastImagePath = fs::u8path(reinterpret_cast<const char*>(value));
} else if (xmlStrcmp(name, reinterpret_cast<const xmlChar*>("edgePanSpeed")) == 0) {
this->edgePanSpeed = tempg_ascii_strtod(reinterpret_cast<const char*>(value), nullptr);
} else if (xmlStrcmp(name, reinterpret_cast<const xmlChar*>("edgePanMaxMult")) == 0) {
this->edgePanMaxMult = tempg_ascii_strtod(reinterpret_cast<const char*>(value), nullptr);
} else if (xmlStrcmp(name, reinterpret_cast<const xmlChar*>("zoomStep")) == 0) {
this->zoomStep = tempg_ascii_strtod(reinterpret_cast<const char*>(value), nullptr);
} else if (xmlStrcmp(name, reinterpret_cast<const xmlChar*>("zoomStepScroll")) == 0) {
this->zoomStepScroll = tempg_ascii_strtod(reinterpret_cast<const char*>(value), nullptr);
} else if (xmlStrcmp(name, reinterpret_cast<const xmlChar*>("displayDpi")) == 0) {
this->displayDpi = g_ascii_strtoll(reinterpret_cast<const char*>(value), nullptr, 10);
} else if (xmlStrcmp(name, reinterpret_cast<const xmlChar*>("mainWndWidth")) == 0) {
this->mainWndWidth = g_ascii_strtoll(reinterpret_cast<const char*>(value), nullptr, 10);
} else if (xmlStrcmp(name, reinterpret_cast<const xmlChar*>("mainWndHeight")) == 0) {
this->mainWndHeight = g_ascii_strtoll(reinterpret_cast<const char*>(value), nullptr, 10);
} else if (xmlStrcmp(name, reinterpret_cast<const xmlChar*>("maximized")) == 0) {
this->maximized = xmlStrcmp(value, reinterpret_cast<const xmlChar*>("true")) == 0;
} else if (xmlStrcmp(name, reinterpret_cast<const xmlChar*>("showToolbar")) == 0) {
this->showToolbar = xmlStrcmp(value, reinterpret_cast<const xmlChar*>("true")) == 0;
} else if (xmlStrcmp(name, reinterpret_cast<const xmlChar*>("filepathShownInTitlebar")) == 0) {
this->filepathShownInTitlebar = xmlStrcmp(value, reinterpret_cast<const xmlChar*>("true")) == 0;
} else if (xmlStrcmp(name, reinterpret_cast<const xmlChar*>("pageNumberShownInTitlebar")) == 0) {
this->pageNumberShownInTitlebar = xmlStrcmp(value, reinterpret_cast<const xmlChar*>("true")) == 0;
} else if (xmlStrcmp(name, reinterpret_cast<const xmlChar*>("showSidebar")) == 0) {
this->showSidebar = xmlStrcmp(value, reinterpret_cast<const xmlChar*>("true")) == 0;
} else if (xmlStrcmp(name, reinterpret_cast<const xmlChar*>("sidebarNumberingStyle")) == 0) {
int num = std::stoi(reinterpret_cast<char*>(value));
if (num < static_cast<int>(SidebarNumberingStyle::MIN) || static_cast<int>(SidebarNumberingStyle::MAX) < num) {
num = static_cast<int>(SidebarNumberingStyle::DEFAULT);
g_warning("Settings::Invalid sidebarNumberingStyle value. Reset to default.");
}
this->sidebarNumberingStyle = static_cast<SidebarNumberingStyle>(num);
} else if (xmlStrcmp(name, reinterpret_cast<const xmlChar*>("sidebarWidth")) == 0) {
this->sidebarWidth = std::max<int>(g_ascii_strtoll(reinterpret_cast<const char*>(value), nullptr, 10), 50);
} else if (xmlStrcmp(name, reinterpret_cast<const xmlChar*>("sidebarOnRight")) == 0) {
this->sidebarOnRight = xmlStrcmp(value, reinterpret_cast<const xmlChar*>("true")) == 0;
} else if (xmlStrcmp(name, reinterpret_cast<const xmlChar*>("scrollbarOnLeft")) == 0) {
this->scrollbarOnLeft = xmlStrcmp(value, reinterpret_cast<const xmlChar*>("true")) == 0;
} else if (xmlStrcmp(name, reinterpret_cast<const xmlChar*>("menubarVisible")) == 0) {
this->menubarVisible = xmlStrcmp(value, reinterpret_cast<const xmlChar*>("true")) == 0;
} else if (xmlStrcmp(name, reinterpret_cast<const xmlChar*>("numColumns")) == 0) {
this->numColumns = g_ascii_strtoll(reinterpret_cast<const char*>(value), nullptr, 10);
} else if (xmlStrcmp(name, reinterpret_cast<const xmlChar*>("numRows")) == 0) {
this->numRows = g_ascii_strtoll(reinterpret_cast<const char*>(value), nullptr, 10);
} else if (xmlStrcmp(name, reinterpret_cast<const xmlChar*>("viewFixedRows")) == 0) {
this->viewFixedRows = xmlStrcmp(value, reinterpret_cast<const xmlChar*>("true")) == 0;
} else if (xmlStrcmp(name, reinterpret_cast<const xmlChar*>("layoutVertical")) == 0) {
this->layoutVertical = xmlStrcmp(value, reinterpret_cast<const xmlChar*>("true")) == 0;
} else if (xmlStrcmp(name, reinterpret_cast<const xmlChar*>("layoutRightToLeft")) == 0) {
this->layoutRightToLeft = xmlStrcmp(value, reinterpret_cast<const xmlChar*>("true")) == 0;
} else if (xmlStrcmp(name, reinterpret_cast<const xmlChar*>("layoutBottomToTop")) == 0) {
this->layoutBottomToTop = xmlStrcmp(value, reinterpret_cast<const xmlChar*>("true")) == 0;
} else if (xmlStrcmp(name, reinterpret_cast<const xmlChar*>("showPairedPages")) == 0) {
this->showPairedPages = xmlStrcmp(value, reinterpret_cast<const xmlChar*>("true")) == 0;
} else if (xmlStrcmp(name, reinterpret_cast<const xmlChar*>("numPairsOffset")) == 0) {
this->numPairsOffset = g_ascii_strtoll(reinterpret_cast<const char*>(value), nullptr, 10);
} else if (xmlStrcmp(name, reinterpret_cast<const xmlChar*>("presentationMode")) == 0) {
this->presentationMode = xmlStrcmp(value, reinterpret_cast<const xmlChar*>("true")) == 0;
} else if (xmlStrcmp(name, reinterpret_cast<const xmlChar*>("autoloadMostRecent")) == 0) {
this->autoloadMostRecent = xmlStrcmp(value, reinterpret_cast<const xmlChar*>("true")) == 0;
} else if (xmlStrcmp(name, reinterpret_cast<const xmlChar*>("autoloadPdfXoj")) == 0) {
this->autoloadPdfXoj = xmlStrcmp(value, reinterpret_cast<const xmlChar*>("true")) == 0;
} else if (xmlStrcmp(name, reinterpret_cast<const xmlChar*>("stylusCursorType")) == 0) {
this->stylusCursorType = stylusCursorTypeFromString(reinterpret_cast<const char*>(value));
} else if (xmlStrcmp(name, reinterpret_cast<const xmlChar*>("eraserVisibility")) == 0) {
this->eraserVisibility = eraserVisibilityFromString(reinterpret_cast<const char*>(value));
} else if (xmlStrcmp(name, reinterpret_cast<const xmlChar*>("iconTheme")) == 0) {
this->iconTheme = iconThemeFromString(reinterpret_cast<const char*>(value));
} else if (xmlStrcmp(name, reinterpret_cast<const xmlChar*>("themeVariant")) == 0) {
this->themeVariant = themeVariantFromString(reinterpret_cast<const char*>(value));
} else if (xmlStrcmp(name, reinterpret_cast<const xmlChar*>("highlightPosition")) == 0) {
this->highlightPosition = xmlStrcmp(value, reinterpret_cast<const xmlChar*>("true")) == 0;
} else if (xmlStrcmp(name, reinterpret_cast<const xmlChar*>("cursorHighlightColor")) == 0) {
this->cursorHighlightColor = g_ascii_strtoull(reinterpret_cast<const char*>(value), nullptr, 10);
} else if (xmlStrcmp(name, reinterpret_cast<const xmlChar*>("cursorHighlightRadius")) == 0) {
this->cursorHighlightRadius = g_ascii_strtod(reinterpret_cast<const char*>(value), nullptr);
} else if (xmlStrcmp(name, reinterpret_cast<const xmlChar*>("cursorHighlightBorderColor")) == 0) {
this->cursorHighlightBorderColor = g_ascii_strtoull(reinterpret_cast<const char*>(value), nullptr, 10);
} else if (xmlStrcmp(name, reinterpret_cast<const xmlChar*>("cursorHighlightBorderWidth")) == 0) {
this->cursorHighlightBorderWidth = g_ascii_strtod(reinterpret_cast<const char*>(value), nullptr);
} else if (xmlStrcmp(name, reinterpret_cast<const xmlChar*>("useStockIcons")) == 0) {
this->useStockIcons = xmlStrcmp(value, reinterpret_cast<const xmlChar*>("true")) == 0;
} else if (xmlStrcmp(name, reinterpret_cast<const xmlChar*>("defaultSaveName")) == 0) {
this->defaultSaveName = reinterpret_cast<const char*>(value);
} else if (xmlStrcmp(name, reinterpret_cast<const xmlChar*>("defaultPdfExportName")) == 0) {
this->defaultPdfExportName = reinterpret_cast<const char*>(value);
} else if (xmlStrcmp(name, reinterpret_cast<const xmlChar*>("pluginEnabled")) == 0) {
this->pluginEnabled = reinterpret_cast<const char*>(value);
} else if (xmlStrcmp(name, reinterpret_cast<const xmlChar*>("pluginDisabled")) == 0) {
this->pluginDisabled = reinterpret_cast<const char*>(value);
} else if (xmlStrcmp(name, reinterpret_cast<const xmlChar*>("pageTemplate")) == 0) {
this->pageTemplate = reinterpret_cast<const char*>(value);
} else if (xmlStrcmp(name, reinterpret_cast<const xmlChar*>("sizeUnit")) == 0) {
this->sizeUnit = reinterpret_cast<const char*>(value);
} else if (xmlStrcmp(name, reinterpret_cast<const xmlChar*>("audioFolder")) == 0) {
this->audioFolder = fs::u8path(reinterpret_cast<const char*>(value));
} else if (xmlStrcmp(name, reinterpret_cast<const xmlChar*>("autosaveEnabled")) == 0) {
this->autosaveEnabled = xmlStrcmp(value, reinterpret_cast<const xmlChar*>("true")) == 0;
} else if (xmlStrcmp(name, reinterpret_cast<const xmlChar*>("autosaveTimeout")) == 0) {
this->autosaveTimeout = g_ascii_strtoll(reinterpret_cast<const char*>(value), nullptr, 10);
} else if (xmlStrcmp(name, reinterpret_cast<const xmlChar*>("defaultViewModeAttributes")) == 0) {
this->viewModes.at(PresetViewModeIds::VIEW_MODE_DEFAULT) =
settingsStringToViewMode(reinterpret_cast<const char*>(value));
} else if (xmlStrcmp(name, reinterpret_cast<const xmlChar*>("fullscreenViewModeAttributes")) == 0) {
this->viewModes.at(PresetViewModeIds::VIEW_MODE_FULLSCREEN) =
settingsStringToViewMode(reinterpret_cast<const char*>(value));
} else if (xmlStrcmp(name, reinterpret_cast<const xmlChar*>("presentationViewModeAttributes")) == 0) {
this->viewModes.at(PresetViewModeIds::VIEW_MODE_PRESENTATION) =
settingsStringToViewMode(reinterpret_cast<const char*>(value));
} else if (xmlStrcmp(name, reinterpret_cast<const xmlChar*>("touchZoomStartThreshold")) == 0) {
this->touchZoomStartThreshold = g_ascii_strtod(reinterpret_cast<const char*>(value), nullptr);
} else if (xmlStrcmp(name, reinterpret_cast<const xmlChar*>("pageRerenderThreshold")) == 0) {
this->pageRerenderThreshold = g_ascii_strtod(reinterpret_cast<const char*>(value), nullptr);
} else if (xmlStrcmp(name, reinterpret_cast<const xmlChar*>("pdfPageCacheSize")) == 0) {
this->pdfPageCacheSize = g_ascii_strtoll(reinterpret_cast<const char*>(value), nullptr, 10);
} else if (xmlStrcmp(name, reinterpret_cast<const xmlChar*>("preloadPagesBefore")) == 0) {
this->preloadPagesBefore = g_ascii_strtoull(reinterpret_cast<const char*>(value), nullptr, 10);
} else if (xmlStrcmp(name, reinterpret_cast<const xmlChar*>("preloadPagesAfter")) == 0) {
this->preloadPagesAfter = g_ascii_strtoull(reinterpret_cast<const char*>(value), nullptr, 10);
} else if (xmlStrcmp(name, reinterpret_cast<const xmlChar*>("eagerPageCleanup")) == 0) {
this->eagerPageCleanup = xmlStrcmp(value, reinterpret_cast<const xmlChar*>("true")) == 0;
} else if (xmlStrcmp(name, reinterpret_cast<const xmlChar*>("selectionBorderColor")) == 0) {
this->selectionBorderColor = Color(g_ascii_strtoull(reinterpret_cast<const char*>(value), nullptr, 10));
} else if (xmlStrcmp(name, reinterpret_cast<const xmlChar*>("selectionMarkerColor")) == 0) {
this->selectionMarkerColor = Color(g_ascii_strtoull(reinterpret_cast<const char*>(value), nullptr, 10));
} else if (xmlStrcmp(name, reinterpret_cast<const xmlChar*>("activeSelectionColor")) == 0) {
this->activeSelectionColor = Color(g_ascii_strtoull(reinterpret_cast<const char*>(value), nullptr, 10));
} else if (xmlStrcmp(name, reinterpret_cast<const xmlChar*>("backgroundColor")) == 0) {
this->backgroundColor = Color(g_ascii_strtoull(reinterpret_cast<const char*>(value), nullptr, 10));
} else if (xmlStrcmp(name, reinterpret_cast<const xmlChar*>("addHorizontalSpace")) == 0) {
this->addHorizontalSpace = xmlStrcmp(value, reinterpret_cast<const xmlChar*>("true")) == 0;
} else if (xmlStrcmp(name, reinterpret_cast<const xmlChar*>("addHorizontalSpaceAmount")) == 0) {
const int oldHorizontalAmount =
static_cast<int>(g_ascii_strtoll(reinterpret_cast<const char*>(value), nullptr, 10));
this->addHorizontalSpaceAmountLeft = oldHorizontalAmount;
this->addHorizontalSpaceAmountRight = oldHorizontalAmount;
} else if (xmlStrcmp(name, reinterpret_cast<const xmlChar*>("addHorizontalSpaceAmountRight")) == 0) {
this->addHorizontalSpaceAmountRight =
static_cast<int>(g_ascii_strtoll(reinterpret_cast<const char*>(value), nullptr, 10));
} else if (xmlStrcmp(name, reinterpret_cast<const xmlChar*>("addVerticalSpace")) == 0) {
this->addVerticalSpace = xmlStrcmp(value, reinterpret_cast<const xmlChar*>("true")) == 0;
} else if (xmlStrcmp(name, reinterpret_cast<const xmlChar*>("addVerticalSpaceAmount")) == 0) {
const int oldVerticalAmount =
static_cast<int>(g_ascii_strtoll(reinterpret_cast<const char*>(value), nullptr, 10));
this->addHorizontalSpaceAmountLeft = oldVerticalAmount;
this->addHorizontalSpaceAmountRight = oldVerticalAmount;
} else if (xmlStrcmp(name, reinterpret_cast<const xmlChar*>("addVerticalSpaceAmountAbove")) == 0) {
this->addVerticalSpaceAmountAbove =
static_cast<int>(g_ascii_strtoll(reinterpret_cast<const char*>(value), nullptr, 10));
} else if (xmlStrcmp(name, reinterpret_cast<const xmlChar*>("addHorizontalSpaceAmountLeft")) == 0) {
this->addHorizontalSpaceAmountLeft =
static_cast<int>(g_ascii_strtoll(reinterpret_cast<const char*>(value), nullptr, 10));
} else if (xmlStrcmp(name, reinterpret_cast<const xmlChar*>("addVerticalSpaceAmountBelow")) == 0) {
this->addVerticalSpaceAmountBelow =
static_cast<int>(g_ascii_strtoll(reinterpret_cast<const char*>(value), nullptr, 10));
} else if (xmlStrcmp(name, reinterpret_cast<const xmlChar*>("unlimitedScrolling")) == 0) {
this->unlimitedScrolling = xmlStrcmp(value, reinterpret_cast<const xmlChar*>("true")) == 0;
} else if (xmlStrcmp(name, reinterpret_cast<const xmlChar*>("drawDirModsEnabled")) == 0) {
this->drawDirModsEnabled = xmlStrcmp(value, reinterpret_cast<const xmlChar*>("true")) == 0;
} else if (xmlStrcmp(name, reinterpret_cast<const xmlChar*>("drawDirModsRadius")) == 0) {
this->drawDirModsRadius = g_ascii_strtoll(reinterpret_cast<const char*>(value), nullptr, 10);
} else if (xmlStrcmp(name, reinterpret_cast<const xmlChar*>("snapRotation")) == 0) {
this->snapRotation = xmlStrcmp(value, reinterpret_cast<const xmlChar*>("true")) == 0;
} else if (xmlStrcmp(name, reinterpret_cast<const xmlChar*>("snapRotationTolerance")) == 0) {
this->snapRotationTolerance = tempg_ascii_strtod(reinterpret_cast<const char*>(value), nullptr);
} else if (xmlStrcmp(name, reinterpret_cast<const xmlChar*>("snapGrid")) == 0) {
this->snapGrid = xmlStrcmp(value, reinterpret_cast<const xmlChar*>("true")) == 0;
} else if (xmlStrcmp(name, reinterpret_cast<const xmlChar*>("snapGridSize")) == 0) {
this->snapGridSize = tempg_ascii_strtod(reinterpret_cast<const char*>(value), nullptr);
} else if (xmlStrcmp(name, reinterpret_cast<const xmlChar*>("snapGridTolerance")) == 0) {
this->snapGridTolerance = tempg_ascii_strtod(reinterpret_cast<const char*>(value), nullptr);
} else if (xmlStrcmp(name, reinterpret_cast<const xmlChar*>("strokeRecognizerMinSize")) == 0) {
this->strokeRecognizerMinSize = tempg_ascii_strtod(reinterpret_cast<const char*>(value), nullptr);
} else if (xmlStrcmp(name, reinterpret_cast<const xmlChar*>("touchDrawing")) == 0) {
this->touchDrawing = xmlStrcmp(value, reinterpret_cast<const xmlChar*>("true")) == 0;
} else if (xmlStrcmp(name, reinterpret_cast<const xmlChar*>("gtkTouchInertialScrolling")) == 0) {
this->gtkTouchInertialScrolling = xmlStrcmp(value, reinterpret_cast<const xmlChar*>("true")) == 0;
} else if (xmlStrcmp(name, reinterpret_cast<const xmlChar*>("pressureGuessing")) == 0) {
this->pressureGuessing = xmlStrcmp(value, reinterpret_cast<const xmlChar*>("true")) == 0;
} else if (xmlStrcmp(name, reinterpret_cast<const xmlChar*>("scrollbarHideType")) == 0) {
if (xmlStrcmp(value, reinterpret_cast<const xmlChar*>("both")) == 0) {
this->scrollbarHideType = SCROLLBAR_HIDE_BOTH;
} else if (xmlStrcmp(value, reinterpret_cast<const xmlChar*>("horizontal")) == 0) {
this->scrollbarHideType = SCROLLBAR_HIDE_HORIZONTAL;
} else if (xmlStrcmp(value, reinterpret_cast<const xmlChar*>("vertical")) == 0) {
this->scrollbarHideType = SCROLLBAR_HIDE_VERTICAL;
} else {
this->scrollbarHideType = SCROLLBAR_HIDE_NONE;
}
} else if (xmlStrcmp(name, reinterpret_cast<const xmlChar*>("disableScrollbarFadeout")) == 0) {
this->disableScrollbarFadeout = xmlStrcmp(value, reinterpret_cast<const xmlChar*>("true")) == 0;
} else if (xmlStrcmp(name, reinterpret_cast<const xmlChar*>("disableAudio")) == 0) {
this->disableAudio = xmlStrcmp(value, reinterpret_cast<const xmlChar*>("true")) == 0;
} else if (xmlStrcmp(name, reinterpret_cast<const xmlChar*>("audioSampleRate")) == 0) {
this->audioSampleRate = tempg_ascii_strtod(reinterpret_cast<const char*>(value), nullptr);
} else if (xmlStrcmp(name, reinterpret_cast<const xmlChar*>("audioGain")) == 0) {
this->audioGain = tempg_ascii_strtod(reinterpret_cast<const char*>(value), nullptr);
} else if (xmlStrcmp(name, reinterpret_cast<const xmlChar*>("defaultSeekTime")) == 0) {
this->defaultSeekTime = tempg_ascii_strtod(reinterpret_cast<const char*>(value), nullptr);
} else if (xmlStrcmp(name, reinterpret_cast<const xmlChar*>("audioInputDevice")) == 0) {
this->audioInputDevice = g_ascii_strtoll(reinterpret_cast<const char*>(value), nullptr, 10);
} else if (xmlStrcmp(name, reinterpret_cast<const xmlChar*>("audioOutputDevice")) == 0) {
this->audioOutputDevice = g_ascii_strtoll(reinterpret_cast<const char*>(value), nullptr, 10);
} else if (xmlStrcmp(name, reinterpret_cast<const xmlChar*>("numIgnoredStylusEvents")) == 0) {
this->numIgnoredStylusEvents =
std::max<int>(g_ascii_strtoll(reinterpret_cast<const char*>(value), nullptr, 10), 0);
} else if (xmlStrcmp(name, reinterpret_cast<const xmlChar*>("inputSystemTPCButton")) == 0) {
this->inputSystemTPCButton = xmlStrcmp(value, reinterpret_cast<const xmlChar*>("true")) == 0;
} else if (xmlStrcmp(name, reinterpret_cast<const xmlChar*>("inputSystemDrawOutsideWindow")) == 0) {
this->inputSystemDrawOutsideWindow = xmlStrcmp(value, reinterpret_cast<const xmlChar*>("true")) == 0;
} else if (xmlStrcmp(name, reinterpret_cast<const xmlChar*>("emptyLastPageAppend")) == 0) {
this->emptyLastPageAppend = emptyLastPageAppendFromString(reinterpret_cast<char*>(value));
} else if (xmlStrcmp(name, reinterpret_cast<const xmlChar*>("strokeFilterIgnoreTime")) == 0) {
this->strokeFilterIgnoreTime = g_ascii_strtoll(reinterpret_cast<const char*>(value), nullptr, 10);
} else if (xmlStrcmp(name, reinterpret_cast<const xmlChar*>("strokeFilterIgnoreLength")) == 0) {
this->strokeFilterIgnoreLength = tempg_ascii_strtod(reinterpret_cast<const char*>(value), nullptr);
} else if (xmlStrcmp(name, reinterpret_cast<const xmlChar*>("strokeFilterSuccessiveTime")) == 0) {
this->strokeFilterSuccessiveTime = g_ascii_strtoll(reinterpret_cast<const char*>(value), nullptr, 10);
} else if (xmlStrcmp(name, reinterpret_cast<const xmlChar*>("strokeFilterEnabled")) == 0) {
this->strokeFilterEnabled = xmlStrcmp(value, reinterpret_cast<const xmlChar*>("true")) == 0;
} else if (xmlStrcmp(name, reinterpret_cast<const xmlChar*>("doActionOnStrokeFiltered")) == 0) {
this->doActionOnStrokeFiltered = xmlStrcmp(value, reinterpret_cast<const xmlChar*>("true")) == 0;
} else if (xmlStrcmp(name, reinterpret_cast<const xmlChar*>("trySelectOnStrokeFiltered")) == 0) {
this->trySelectOnStrokeFiltered = xmlStrcmp(value, reinterpret_cast<const xmlChar*>("true")) == 0;
} else if (xmlStrcmp(name, reinterpret_cast<const xmlChar*>("latexSettings.autoCheckDependencies")) == 0) {
this->latexSettings.autoCheckDependencies = xmlStrcmp(value, reinterpret_cast<const xmlChar*>("true")) == 0;
} else if (xmlStrcmp(name, reinterpret_cast<const xmlChar*>("latexSettings.defaultText")) == 0) {
this->latexSettings.defaultText = reinterpret_cast<char*>(value);
} else if (xmlStrcmp(name, reinterpret_cast<const xmlChar*>("latexSettings.globalTemplatePath")) == 0) {
std::string v(reinterpret_cast<char*>(value));
this->latexSettings.globalTemplatePath = fs::u8path(v);
} else if (xmlStrcmp(name, reinterpret_cast<const xmlChar*>("latexSettings.genCmd")) == 0) {
this->latexSettings.genCmd = reinterpret_cast<char*>(value);
} else if (xmlStrcmp(name, reinterpret_cast<const xmlChar*>("latexSettings.sourceViewThemeId")) == 0) {
this->latexSettings.sourceViewThemeId = reinterpret_cast<char*>(value);
} else if (xmlStrcmp(name, reinterpret_cast<const xmlChar*>("latexSettings.editorFont")) == 0) {
this->latexSettings.editorFont = std::string{reinterpret_cast<char*>(value)};
} else if (xmlStrcmp(name, reinterpret_cast<const xmlChar*>("latexSettings.useCustomEditorFont")) == 0) {
this->latexSettings.useCustomEditorFont = xmlStrcmp(value, reinterpret_cast<const xmlChar*>("true")) == 0;
} else if (xmlStrcmp(name, reinterpret_cast<const xmlChar*>("latexSettings.editorWordWrap")) == 0) {
this->latexSettings.editorWordWrap = xmlStrcmp(value, reinterpret_cast<const xmlChar*>("true")) == 0;
} else if (xmlStrcmp(name, reinterpret_cast<const xmlChar*>("latexSettings.sourceViewAutoIndent")) == 0) {
this->latexSettings.sourceViewAutoIndent = xmlStrcmp(value, reinterpret_cast<const xmlChar*>("true")) == 0;
} else if (xmlStrcmp(name, reinterpret_cast<const xmlChar*>("latexSettings.sourceViewSyntaxHighlight")) == 0) {
this->latexSettings.sourceViewSyntaxHighlight = xmlStrcmp(value, reinterpret_cast<const xmlChar*>("true")) == 0;
} else if (xmlStrcmp(name, reinterpret_cast<const xmlChar*>("latexSettings.sourceViewShowLineNumbers")) == 0) {
this->latexSettings.sourceViewShowLineNumbers = xmlStrcmp(value, reinterpret_cast<const xmlChar*>("true")) == 0;
} else if (xmlStrcmp(name, reinterpret_cast<const xmlChar*>("snapRecognizedShapesEnabled")) == 0) {
this->snapRecognizedShapesEnabled = xmlStrcmp(value, reinterpret_cast<const xmlChar*>("true")) == 0;
} else if (xmlStrcmp(name, reinterpret_cast<const xmlChar*>("restoreLineWidthEnabled")) == 0) {
this->restoreLineWidthEnabled = xmlStrcmp(value, reinterpret_cast<const xmlChar*>("true")) == 0;
} else if (xmlStrcmp(name, reinterpret_cast<const xmlChar*>("preferredLocale")) == 0) {
this->preferredLocale = reinterpret_cast<char*>(value);
} else if (xmlStrcmp(name, reinterpret_cast<const xmlChar*>("useSpacesForTab")) == 0) {
this->setUseSpacesAsTab(xmlStrcmp(value, reinterpret_cast<const xmlChar*>("true")) == 0);
} else if (xmlStrcmp(name, reinterpret_cast<const xmlChar*>("numberOfSpacesForTab")) == 0) {
this->setNumberOfSpacesForTab(g_ascii_strtoull(reinterpret_cast<const char*>(value), nullptr, 10));
/**
* Stabilizer related settings
*/
} else if (xmlStrcmp(name, reinterpret_cast<const xmlChar*>("stabilizerAveragingMethod")) == 0) {
this->stabilizerAveragingMethod =
(StrokeStabilizer::AveragingMethod)g_ascii_strtoll(reinterpret_cast<const char*>(value), nullptr, 10);
} else if (xmlStrcmp(name, reinterpret_cast<const xmlChar*>("stabilizerPreprocessor")) == 0) {
this->stabilizerPreprocessor =
(StrokeStabilizer::Preprocessor)g_ascii_strtoll(reinterpret_cast<const char*>(value), nullptr, 10);
} else if (xmlStrcmp(name, reinterpret_cast<const xmlChar*>("stabilizerBuffersize")) == 0) {
this->stabilizerBuffersize = g_ascii_strtoull(reinterpret_cast<const char*>(value), nullptr, 10);
} else if (xmlStrcmp(name, reinterpret_cast<const xmlChar*>("stabilizerSigma")) == 0) {
this->stabilizerSigma = tempg_ascii_strtod(reinterpret_cast<const char*>(value), nullptr);
} else if (xmlStrcmp(name, reinterpret_cast<const xmlChar*>("stabilizerDeadzoneRadius")) == 0) {
this->stabilizerDeadzoneRadius = tempg_ascii_strtod(reinterpret_cast<const char*>(value), nullptr);
} else if (xmlStrcmp(name, reinterpret_cast<const xmlChar*>("stabilizerDrag")) == 0) {
this->stabilizerDrag = tempg_ascii_strtod(reinterpret_cast<const char*>(value), nullptr);
} else if (xmlStrcmp(name, reinterpret_cast<const xmlChar*>("stabilizerMass")) == 0) {
this->stabilizerMass = tempg_ascii_strtod(reinterpret_cast<const char*>(value), nullptr);
} else if (xmlStrcmp(name, reinterpret_cast<const xmlChar*>("stabilizerCuspDetection")) == 0) {
this->stabilizerCuspDetection = xmlStrcmp(value, reinterpret_cast<const xmlChar*>("true")) == 0;
} else if (xmlStrcmp(name, reinterpret_cast<const xmlChar*>("stabilizerFinalizeStroke")) == 0) {
this->stabilizerFinalizeStroke = xmlStrcmp(value, reinterpret_cast<const xmlChar*>("true")) == 0;
} else if (xmlStrcmp(name, reinterpret_cast<const xmlChar*>("colorPalette")) == 0) {
std::string paletteConfig = std::string{reinterpret_cast<const char*>(value)};
if (!paletteConfig.empty()) {
this->colorPaletteSetting = paletteConfig;
}
}
/**/
xmlFree(name);
xmlFree(value);
}
void Settings::loadDeviceClasses() {
SElement& s = getCustomElement("deviceClasses");
for (auto device: s.children()) {
SElement& deviceNode = device.second;
int deviceClass = 0;
int deviceSource = 0;
deviceNode.getInt("deviceClass", deviceClass);
deviceNode.getInt("deviceSource", deviceSource);
inputDeviceClasses.emplace(device.first, std::make_pair(static_cast<InputDeviceTypeOption>(deviceClass),
static_cast<GdkInputSource>(deviceSource)));
}
}
void Settings::loadButtonConfig() {
SElement& s = getCustomElement("buttonConfig");
for (int i = 0; i < BUTTON_COUNT; i++) {
SElement& e = s.child(buttonToString(static_cast<Button>(i)));
const auto& cfg = buttonConfig[i];
string sType;
if (e.getString("tool", sType)) {
ToolType type = toolTypeFromString(sType);
cfg->action = type;
if (type == TOOL_PEN) {
string strokeType;
cfg->strokeType =
e.getString("strokeType", strokeType) ? strokeTypeFromString(strokeType) : STROKE_TYPE_NONE;
}
if (type == TOOL_PEN || type == TOOL_HIGHLIGHTER) {
string drawingType;
if (e.getString("drawingType", drawingType)) {
cfg->drawingType = drawingTypeFromString(drawingType);
}
string sSize;
if (e.getString("size", sSize)) {
cfg->size = toolSizeFromString(sSize);
} else {
// If not specified: do not change
cfg->size = TOOL_SIZE_NONE;
}
}
if (type == TOOL_PEN || type == TOOL_HIGHLIGHTER || type == TOOL_TEXT) {
if (int iColor; e.getInt("color", iColor)) {
cfg->color = Color(as_unsigned(iColor));
}
}
if (type == TOOL_ERASER) {
string sEraserMode;
if (e.getString("eraserMode", sEraserMode)) {
cfg->eraserMode = eraserTypeFromString(sEraserMode);
} else {
// If not specified: do not change
cfg->eraserMode = ERASER_TYPE_NONE;
}
string sSize;
if (e.getString("size", sSize)) {
cfg->size = toolSizeFromString(sSize);
} else {
// If not specified: do not change
cfg->size = TOOL_SIZE_NONE;
}
}
// Touch device
if (i == BUTTON_TOUCH) {
if (!e.getString("device", cfg->device)) {
cfg->device = "";
}
e.getBool("disableDrawing", cfg->disableDrawing);
}
} else {
continue;
}
}
}
auto Settings::load() -> bool {
xmlKeepBlanksDefault(0);
if (!fs::exists(filepath)) {
g_warning("Settings file %s does not exist. Regenerating. ", filepath.string().c_str());
save();
}
xmlDocPtr doc = xmlParseFile(filepath.u8string().c_str());
if (doc == nullptr) {
g_warning("Settings::load:: doc == null, could not load Settings!\n");
return false;
}
xmlNodePtr cur = xmlDocGetRootElement(doc);
if (cur == nullptr) {
g_message("The settings file \"%s\" is empty", filepath.string().c_str());
xmlFreeDoc(doc);
return false;
}
if (xmlStrcmp(cur->name, reinterpret_cast<const xmlChar*>("settings"))) {
g_message("File \"%s\" is of the wrong type", filepath.string().c_str());
xmlFreeDoc(doc);
return false;
}
cur = xmlDocGetRootElement(doc);
cur = cur->xmlChildrenNode;
while (cur != nullptr) {
parseItem(doc, cur);
cur = cur->next;
}
xmlFreeDoc(doc);
loadButtonConfig();
loadDeviceClasses();
// This must be done before the color palette to ensure the color names are translated properly
#ifdef _WIN32
_putenv_s("LANGUAGE", this->preferredLocale.c_str());
#else
setenv("LANGUAGE", this->preferredLocale.c_str(), 1);
#endif
return true;
}
auto Settings::savePropertyDouble(const gchar* key, double value, xmlNodePtr parent) -> xmlNodePtr {
char text[G_ASCII_DTOSTR_BUF_SIZE];
// g_ascii_ version uses C locale always.
g_ascii_formatd(text, G_ASCII_DTOSTR_BUF_SIZE, Util::PRECISION_FORMAT_STRING, value);
xmlNodePtr xmlNode = saveProperty(key, text, parent);
return xmlNode;
}
auto Settings::saveProperty(const gchar* key, int value, xmlNodePtr parent) -> xmlNodePtr {
char* text = g_strdup_printf("%i", value);
xmlNodePtr xmlNode = saveProperty(key, text, parent);
g_free(text);
return xmlNode;
}
auto Settings::savePropertyUnsigned(const gchar* key, unsigned int value, xmlNodePtr parent) -> xmlNodePtr {
char* text = g_strdup_printf("%u", value);
xmlNodePtr xmlNode = saveProperty(key, text, parent);
g_free(text);
return xmlNode;
}
auto Settings::saveProperty(const gchar* key, const gchar* value, xmlNodePtr parent) -> xmlNodePtr {
xmlNodePtr xmlNode = xmlNewChild(parent, nullptr, reinterpret_cast<const xmlChar*>("property"), nullptr);
xmlSetProp(xmlNode, reinterpret_cast<const xmlChar*>("name"), reinterpret_cast<const xmlChar*>(key));
xmlSetProp(xmlNode, reinterpret_cast<const xmlChar*>("value"), reinterpret_cast<const xmlChar*>(value));
return xmlNode;
}
void Settings::saveDeviceClasses() {
SElement& s = getCustomElement("deviceClasses");
for (auto& device: inputDeviceClasses) {
const std::string& name = device.first;
InputDeviceTypeOption& deviceClass = device.second.first;
GdkInputSource& source = device.second.second;
SElement& e = s.child(name);
e.setInt("deviceClass", static_cast<int>(deviceClass));
e.setInt("deviceSource", source);
}
}
void Settings::saveButtonConfig() {
SElement& s = getCustomElement("buttonConfig");
s.clear();
for (int i = 0; i < BUTTON_COUNT; i++) {
SElement& e = s.child(buttonToString(static_cast<Button>(i)));
const auto& cfg = buttonConfig[i];
ToolType const type = cfg->action;
e.setString("tool", toolTypeToString(type));
if (type == TOOL_PEN) {
e.setString("strokeType", strokeTypeToString(cfg->strokeType));
}
if (type == TOOL_PEN || type == TOOL_HIGHLIGHTER) {
e.setString("drawingType", drawingTypeToString(cfg->drawingType));
e.setString("size", toolSizeToString(cfg->size));
}
if (type == TOOL_PEN || type == TOOL_HIGHLIGHTER || type == TOOL_TEXT) {
e.setIntHex("color", int32_t(uint32_t(cfg->color)));
}
if (type == TOOL_ERASER) {
e.setString("eraserMode", eraserTypeToString(cfg->eraserMode));
e.setString("size", toolSizeToString(cfg->size));
}
// Touch device
if (i == BUTTON_TOUCH) {
e.setString("device", cfg->device);
e.setBool("disableDrawing", cfg->disableDrawing);
}
}
}
/**
* Do not save settings until transactionEnd() is called
*/
void Settings::transactionStart() { inTransaction = true; }
/**
* Stop transaction and save settings
*/
void Settings::transactionEnd() {
inTransaction = false;
save();
}
void Settings::save() {
if (inTransaction) {
return;
}
xmlDocPtr doc = nullptr;
xmlNodePtr root = nullptr;
xmlNodePtr xmlNode = nullptr;
xmlIndentTreeOutput = true;
doc = xmlNewDoc(reinterpret_cast<const xmlChar*>("1.0"));
if (doc == nullptr) {
return;
}
saveButtonConfig();
saveDeviceClasses();
/* Create metadata root */
root = xmlNewDocNode(doc, nullptr, reinterpret_cast<const xmlChar*>("settings"), nullptr);
xmlDocSetRootElement(doc, root);
xmlNodePtr com = xmlNewComment(
reinterpret_cast<const xmlChar*>("The Xournal++ settings file. Do not edit this file! "
"Most settings are available in the Settings dialog, "
"the others are commented in this file, but handle with care!"));
xmlAddPrevSibling(root, com);
SAVE_BOOL_PROP(pressureSensitivity);
SAVE_DOUBLE_PROP(minimumPressure);
SAVE_DOUBLE_PROP(pressureMultiplier);
SAVE_BOOL_PROP(zoomGesturesEnabled);
SAVE_STRING_PROP(selectedToolbar);
auto lastSavePath = this->lastSavePath.u8string();
auto lastOpenPath = this->lastOpenPath.u8string();
auto lastImagePath = this->lastImagePath.u8string();
SAVE_STRING_PROP(lastSavePath);
SAVE_STRING_PROP(lastOpenPath);
SAVE_STRING_PROP(lastImagePath);
SAVE_DOUBLE_PROP(edgePanSpeed);
SAVE_DOUBLE_PROP(edgePanMaxMult);
SAVE_DOUBLE_PROP(zoomStep);
SAVE_DOUBLE_PROP(zoomStepScroll);
SAVE_INT_PROP(displayDpi);
SAVE_INT_PROP(mainWndWidth);
SAVE_INT_PROP(mainWndHeight);
SAVE_BOOL_PROP(maximized);
SAVE_BOOL_PROP(showToolbar);
SAVE_BOOL_PROP(showSidebar);
SAVE_INT_PROP(sidebarWidth);
xmlNode = saveProperty("sidebarNumberingStyle", static_cast<int>(sidebarNumberingStyle), root);
SAVE_BOOL_PROP(sidebarOnRight);
SAVE_BOOL_PROP(scrollbarOnLeft);
SAVE_BOOL_PROP(menubarVisible);
SAVE_BOOL_PROP(filepathShownInTitlebar);
SAVE_BOOL_PROP(pageNumberShownInTitlebar);
SAVE_INT_PROP(numColumns);
SAVE_INT_PROP(numRows);
SAVE_BOOL_PROP(viewFixedRows);
SAVE_BOOL_PROP(showPairedPages);
SAVE_BOOL_PROP(layoutVertical);
SAVE_BOOL_PROP(layoutRightToLeft);
SAVE_BOOL_PROP(layoutBottomToTop);
SAVE_INT_PROP(numPairsOffset);
xmlNode = saveProperty("emptyLastPageAppend", emptyLastPageAppendToString(this->emptyLastPageAppend), root);
ATTACH_COMMENT("The icon theme, allowed values are \"disabled\", \"onDrawOfLastPage\", and \"onScrollOfLastPage\"");
SAVE_BOOL_PROP(presentationMode);
auto defaultViewModeAttributes = viewModeToSettingsString(viewModes.at(PresetViewModeIds::VIEW_MODE_DEFAULT));
auto fullscreenViewModeAttributes = viewModeToSettingsString(viewModes.at(PresetViewModeIds::VIEW_MODE_FULLSCREEN));
auto presentationViewModeAttributes =
viewModeToSettingsString(viewModes.at(PresetViewModeIds::VIEW_MODE_PRESENTATION));
SAVE_STRING_PROP(defaultViewModeAttributes);
ATTACH_COMMENT("Which GUI elements are shown in default view mode, separated by a colon (,)");
SAVE_STRING_PROP(fullscreenViewModeAttributes);
ATTACH_COMMENT("Which GUI elements are shown in fullscreen view mode, separated by a colon (,)");
SAVE_STRING_PROP(presentationViewModeAttributes);
ATTACH_COMMENT("Which GUI elements are shown in presentation view mode, separated by a colon (,)");
xmlNode = saveProperty("stylusCursorType", stylusCursorTypeToString(this->stylusCursorType), root);
ATTACH_COMMENT("The cursor icon used with a stylus, allowed values are \"none\", \"dot\", \"big\", \"arrow\"");
xmlNode = saveProperty("eraserVisibility", eraserVisibilityToString(this->eraserVisibility), root);
ATTACH_COMMENT("The eraser cursor visibility used with a stylus, allowed values are \"never\", \"always\", "
"\"hover\", \"touch\"");
xmlNode = saveProperty("iconTheme", iconThemeToString(this->iconTheme), root);
ATTACH_COMMENT("The icon theme, allowed values are \"iconsColor\", \"iconsLucide\"");
xmlNode = saveProperty("themeVariant", themeVariantToString(this->themeVariant), root);
ATTACH_COMMENT("Dark/light mode, allowed values are \"useSystem\", \"forceLight\", \"forceDark\"");
SAVE_BOOL_PROP(highlightPosition);
xmlNode = savePropertyUnsigned("cursorHighlightColor", uint32_t(cursorHighlightColor), root);
xmlNode = savePropertyUnsigned("cursorHighlightBorderColor", uint32_t(cursorHighlightBorderColor), root);
SAVE_DOUBLE_PROP(cursorHighlightRadius);
SAVE_DOUBLE_PROP(cursorHighlightBorderWidth);
SAVE_BOOL_PROP(useStockIcons);
SAVE_BOOL_PROP(disableScrollbarFadeout);
SAVE_BOOL_PROP(disableAudio);
if (this->scrollbarHideType == SCROLLBAR_HIDE_BOTH) {
xmlNode = saveProperty("scrollbarHideType", "both", root);
} else if (this->scrollbarHideType == SCROLLBAR_HIDE_HORIZONTAL) {
xmlNode = saveProperty("scrollbarHideType", "horizontal", root);
} else if (this->scrollbarHideType == SCROLLBAR_HIDE_VERTICAL) {
xmlNode = saveProperty("scrollbarHideType", "vertical", root);
} else {
xmlNode = saveProperty("scrollbarHideType", "none", root);
}
ATTACH_COMMENT("Hides scroolbars in the main window, allowed values: \"none\", \"horizontal\", \"vertical\", "
"\"both\"");
SAVE_BOOL_PROP(autoloadMostRecent);
SAVE_BOOL_PROP(autoloadPdfXoj);
SAVE_STRING_PROP(defaultSaveName);
SAVE_STRING_PROP(defaultPdfExportName);
SAVE_BOOL_PROP(autosaveEnabled);
SAVE_INT_PROP(autosaveTimeout);
SAVE_BOOL_PROP(addHorizontalSpace);
SAVE_INT_PROP(addHorizontalSpaceAmountRight);
SAVE_INT_PROP(addHorizontalSpaceAmountLeft);
SAVE_BOOL_PROP(addVerticalSpace);
SAVE_INT_PROP(addVerticalSpaceAmountAbove);
SAVE_INT_PROP(addVerticalSpaceAmountBelow);
SAVE_BOOL_PROP(unlimitedScrolling);
SAVE_BOOL_PROP(drawDirModsEnabled);
SAVE_INT_PROP(drawDirModsRadius);
SAVE_BOOL_PROP(snapRotation);
SAVE_DOUBLE_PROP(snapRotationTolerance);
SAVE_BOOL_PROP(snapGrid);
SAVE_DOUBLE_PROP(snapGridTolerance);
SAVE_DOUBLE_PROP(snapGridSize);
SAVE_DOUBLE_PROP(strokeRecognizerMinSize);
SAVE_BOOL_PROP(touchDrawing);
SAVE_BOOL_PROP(gtkTouchInertialScrolling);
SAVE_BOOL_PROP(pressureGuessing);
xmlNode = savePropertyUnsigned("selectionBorderColor", uint32_t(selectionBorderColor), root);
xmlNode = savePropertyUnsigned("backgroundColor", uint32_t(backgroundColor), root);
xmlNode = savePropertyUnsigned("selectionMarkerColor", uint32_t(selectionMarkerColor), root);
xmlNode = savePropertyUnsigned("activeSelectionColor", uint32_t(activeSelectionColor), root);
SAVE_DOUBLE_PROP(touchZoomStartThreshold);
SAVE_DOUBLE_PROP(pageRerenderThreshold);
SAVE_INT_PROP(pdfPageCacheSize);
ATTACH_COMMENT("The count of rendered PDF pages which will be cached.");
SAVE_UINT_PROP(preloadPagesBefore);
SAVE_UINT_PROP(preloadPagesAfter);
SAVE_BOOL_PROP(eagerPageCleanup);
SAVE_STRING_PROP(pageTemplate);
ATTACH_COMMENT("Config for new pages");
SAVE_STRING_PROP(sizeUnit);
{
auto audioFolder = this->audioFolder.u8string();
SAVE_STRING_PROP(audioFolder);
}
SAVE_INT_PROP(audioInputDevice);
SAVE_INT_PROP(audioOutputDevice);
SAVE_DOUBLE_PROP(audioSampleRate);
SAVE_DOUBLE_PROP(audioGain);
SAVE_INT_PROP(defaultSeekTime);
SAVE_STRING_PROP(pluginEnabled);
SAVE_STRING_PROP(pluginDisabled);
SAVE_INT_PROP(strokeFilterIgnoreTime);
SAVE_DOUBLE_PROP(strokeFilterIgnoreLength);
SAVE_INT_PROP(strokeFilterSuccessiveTime);
SAVE_BOOL_PROP(strokeFilterEnabled);
SAVE_BOOL_PROP(doActionOnStrokeFiltered);
SAVE_BOOL_PROP(trySelectOnStrokeFiltered);
SAVE_BOOL_PROP(snapRecognizedShapesEnabled);
SAVE_BOOL_PROP(restoreLineWidthEnabled);
SAVE_INT_PROP(numIgnoredStylusEvents);
SAVE_BOOL_PROP(inputSystemTPCButton);
SAVE_BOOL_PROP(inputSystemDrawOutsideWindow);
SAVE_STRING_PROP(preferredLocale);
SAVE_BOOL_PROP(useSpacesForTab);
SAVE_UINT_PROP(numberOfSpacesForTab);
/**
* Stabilizer related settings
*/
saveProperty("stabilizerAveragingMethod", static_cast<int>(stabilizerAveragingMethod), root);
saveProperty("stabilizerPreprocessor", static_cast<int>(stabilizerPreprocessor), root);
SAVE_UINT_PROP(stabilizerBuffersize);
SAVE_DOUBLE_PROP(stabilizerSigma);
SAVE_DOUBLE_PROP(stabilizerDeadzoneRadius);
SAVE_DOUBLE_PROP(stabilizerDrag);
SAVE_DOUBLE_PROP(stabilizerMass);
SAVE_BOOL_PROP(stabilizerCuspDetection);
SAVE_BOOL_PROP(stabilizerFinalizeStroke);
if (!this->colorPaletteSetting.empty()) {
saveProperty("colorPalette", this->colorPaletteSetting.u8string().c_str(), root);
}
/**/
SAVE_BOOL_PROP(latexSettings.autoCheckDependencies);
SAVE_STRING_PROP(latexSettings.defaultText);
// Inline SAVE_STRING_PROP(latexSettings.globalTemplatePath) since it
// breaks on Windows due to the native character representation being
// wchar_t instead of char
fs::path& p = latexSettings.globalTemplatePath;
xmlNode = saveProperty("latexSettings.globalTemplatePath", p.empty() ? "" : p.u8string().c_str(), root);
SAVE_STRING_PROP(latexSettings.genCmd);
SAVE_STRING_PROP(latexSettings.sourceViewThemeId);
SAVE_FONT_PROP(latexSettings.editorFont);
SAVE_BOOL_PROP(latexSettings.useCustomEditorFont);
SAVE_BOOL_PROP(latexSettings.editorWordWrap);
SAVE_BOOL_PROP(latexSettings.sourceViewAutoIndent);
SAVE_BOOL_PROP(latexSettings.sourceViewSyntaxHighlight);
SAVE_BOOL_PROP(latexSettings.sourceViewShowLineNumbers);
xmlNodePtr xmlFont = nullptr;
xmlFont = xmlNewChild(root, nullptr, reinterpret_cast<const xmlChar*>("property"), nullptr);
xmlSetProp(xmlFont, reinterpret_cast<const xmlChar*>("name"), reinterpret_cast<const xmlChar*>("font"));
xmlSetProp(xmlFont, reinterpret_cast<const xmlChar*>("font"),
reinterpret_cast<const xmlChar*>(this->font.getName().c_str()));
char sSize[G_ASCII_DTOSTR_BUF_SIZE];
g_ascii_formatd(sSize, G_ASCII_DTOSTR_BUF_SIZE, Util::PRECISION_FORMAT_STRING,
this->font.getSize()); // no locale
xmlSetProp(xmlFont, reinterpret_cast<const xmlChar*>("size"), reinterpret_cast<const xmlChar*>(sSize));
for (std::map<string, SElement>::value_type p: data) {
saveData(root, p.first, p.second);
}
xmlSaveFormatFileEnc(filepath.u8string().c_str(), doc, "UTF-8", 1);
xmlFreeDoc(doc);
}
void Settings::saveData(xmlNodePtr root, const string& name, SElement& elem) {
xmlNodePtr xmlNode = xmlNewChild(root, nullptr, reinterpret_cast<const xmlChar*>("data"), nullptr);
xmlSetProp(xmlNode, reinterpret_cast<const xmlChar*>("name"), reinterpret_cast<const xmlChar*>(name.c_str()));
for (auto const& [aname, attrib]: elem.attributes()) {
string type;
string value;
if (attrib.type == ATTRIBUTE_TYPE_BOOLEAN) {
type = "boolean";
if (attrib.iValue) {
value = "true";
} else {
value = "false";
}
} else if (attrib.type == ATTRIBUTE_TYPE_INT) {
type = "int";
char* tmp = g_strdup_printf("%i", attrib.iValue);
value = tmp;
g_free(tmp);
} else if (attrib.type == ATTRIBUTE_TYPE_DOUBLE) {
type = "double";
char tmp[G_ASCII_DTOSTR_BUF_SIZE];
g_ascii_formatd(tmp, G_ASCII_DTOSTR_BUF_SIZE, Util::PRECISION_FORMAT_STRING, attrib.dValue);
value = tmp;
} else if (attrib.type == ATTRIBUTE_TYPE_INT_HEX) {
type = "hex";
char* tmp = g_strdup_printf("%06x", attrib.iValue);
value = tmp;
g_free(tmp);
} else if (attrib.type == ATTRIBUTE_TYPE_STRING) {
type = "string";
value = attrib.sValue;
} else {
// Unknown type or empty attribute
continue;
}
xmlNodePtr at = nullptr;
at = xmlNewChild(xmlNode, nullptr, reinterpret_cast<const xmlChar*>("attribute"), nullptr);
xmlSetProp(at, reinterpret_cast<const xmlChar*>("name"), reinterpret_cast<const xmlChar*>(aname.c_str()));
xmlSetProp(at, reinterpret_cast<const xmlChar*>("type"), reinterpret_cast<const xmlChar*>(type.c_str()));
xmlSetProp(at, reinterpret_cast<const xmlChar*>("value"), reinterpret_cast<const xmlChar*>(value.c_str()));
if (!attrib.comment.empty()) {
xmlNodePtr com = xmlNewComment(reinterpret_cast<const xmlChar*>(attrib.comment.c_str()));
xmlAddPrevSibling(xmlNode, com);
}
}
for (std::map<string, SElement>::value_type p: elem.children()) {
saveData(xmlNode, p.first, p.second);
}
}
// Getter- / Setter
auto Settings::isPressureSensitivity() const -> bool { return this->pressureSensitivity; }
auto Settings::isZoomGesturesEnabled() const -> bool { return this->zoomGesturesEnabled; }
void Settings::setZoomGesturesEnabled(bool enable) {
if (this->zoomGesturesEnabled == enable) {
return;
}
this->zoomGesturesEnabled = enable;
save();
}
auto Settings::isSidebarOnRight() const -> bool { return this->sidebarOnRight; }
void Settings::setSidebarOnRight(bool right) {
if (this->sidebarOnRight == right) {
return;
}
this->sidebarOnRight = right;
save();
}
auto Settings::isScrollbarOnLeft() const -> bool { return this->scrollbarOnLeft; }
void Settings::setScrollbarOnLeft(bool right) {
if (this->scrollbarOnLeft == right) {
return;
}
this->scrollbarOnLeft = right;
save();
}
auto Settings::isMenubarVisible() const -> bool { return this->menubarVisible; }
void Settings::setMenubarVisible(bool visible) {
if (this->menubarVisible == visible) {
return;
}
this->menubarVisible = visible;
save();
}
const bool Settings::isFilepathInTitlebarShown() const { return this->filepathShownInTitlebar; }
void Settings::setFilepathInTitlebarShown(const bool shown) {
if (this->filepathShownInTitlebar == shown) {
return;
}
this->filepathShownInTitlebar = shown;
save();
}
const bool Settings::isPageNumberInTitlebarShown() const { return this->pageNumberShownInTitlebar; }
void Settings::setPageNumberInTitlebarShown(const bool shown) {
if (this->pageNumberShownInTitlebar == shown) {
return;
}
this->pageNumberShownInTitlebar = shown;
save();
}
auto Settings::getAutosaveTimeout() const -> int { return this->autosaveTimeout; }
void Settings::setAutosaveTimeout(int autosave) {
if (this->autosaveTimeout == autosave) {
return;
}
this->autosaveTimeout = autosave;
save();
}
auto Settings::isAutosaveEnabled() const -> bool { return this->autosaveEnabled; }
void Settings::setAutosaveEnabled(bool autosave) {
if (this->autosaveEnabled == autosave) {
return;
}
this->autosaveEnabled = autosave;
save();
}
auto Settings::getAddVerticalSpace() const -> bool { return this->addVerticalSpace; }
void Settings::setAddVerticalSpace(bool space) { this->addVerticalSpace = space; }
auto Settings::getAddVerticalSpaceAmountAbove() const -> int { return this->addVerticalSpaceAmountAbove; }
void Settings::setAddVerticalSpaceAmountAbove(int pixels) {
if (this->addVerticalSpaceAmountAbove == pixels) {
return;
}
this->addVerticalSpaceAmountAbove = pixels;
}
auto Settings::getAddVerticalSpaceAmountBelow() const -> int { return this->addVerticalSpaceAmountBelow; }
void Settings::setAddVerticalSpaceAmountBelow(int pixels) {
if (this->addVerticalSpaceAmountBelow == pixels) {
return;
}
this->addVerticalSpaceAmountBelow = pixels;
}
auto Settings::getAddHorizontalSpace() const -> bool { return this->addHorizontalSpace; }
void Settings::setAddHorizontalSpace(bool space) { this->addHorizontalSpace = space; }
auto Settings::getAddHorizontalSpaceAmountRight() const -> int { return this->addHorizontalSpaceAmountRight; }
void Settings::setAddHorizontalSpaceAmountRight(int pixels) {
if (this->addHorizontalSpaceAmountRight == pixels) {
return;
}
this->addHorizontalSpaceAmountRight = pixels;
}
auto Settings::getAddHorizontalSpaceAmountLeft() const -> int { return this->addHorizontalSpaceAmountLeft; }
void Settings::setAddHorizontalSpaceAmountLeft(int pixels) {
if (this->addHorizontalSpaceAmountLeft == pixels) {
return;
}
this->addHorizontalSpaceAmountLeft = pixels;
}
auto Settings::getUnlimitedScrolling() const -> bool { return this->unlimitedScrolling; }
void Settings::setUnlimitedScrolling(bool enable) {
if (enable == this->unlimitedScrolling) {
return;
}
this->unlimitedScrolling = enable;
}
auto Settings::getDrawDirModsEnabled() const -> bool { return this->drawDirModsEnabled; }
void Settings::setDrawDirModsEnabled(bool enable) { this->drawDirModsEnabled = enable; }
auto Settings::getDrawDirModsRadius() const -> int { return this->drawDirModsRadius; }
void Settings::setDrawDirModsRadius(int pixels) {
if (this->drawDirModsRadius == pixels) {
return;
}
this->drawDirModsRadius = pixels;
save();
}
auto Settings::getStylusCursorType() const -> StylusCursorType { return this->stylusCursorType; }
void Settings::setStylusCursorType(StylusCursorType type) {
if (this->stylusCursorType == type) {
return;
}
this->stylusCursorType = type;
save();
}
auto Settings::getEraserVisibility() const -> EraserVisibility { return this->eraserVisibility; }
void Settings::setEraserVisibility(EraserVisibility eraserVisibility) {
if (this->eraserVisibility == eraserVisibility) {
return;
}
this->eraserVisibility = eraserVisibility;
save();
}
auto Settings::getIconTheme() const -> IconTheme { return this->iconTheme; }
void Settings::setIconTheme(IconTheme iconTheme) {
if (this->iconTheme == iconTheme) {
return;
}
this->iconTheme = iconTheme;
save();
}
auto Settings::getThemeVariant() const -> ThemeVariant { return this->themeVariant; }
void Settings::setThemeVariant(ThemeVariant theme) {
if (this->themeVariant == theme) {
return;
}
this->themeVariant = theme;
save();
}
auto Settings::getSidebarNumberingStyle() const -> SidebarNumberingStyle { return this->sidebarNumberingStyle; };
void Settings::setSidebarNumberingStyle(SidebarNumberingStyle numberingStyle) {
if (this->sidebarNumberingStyle == numberingStyle) {
return;
}
this->sidebarNumberingStyle = numberingStyle;
save();
}
auto Settings::isHighlightPosition() const -> bool { return this->highlightPosition; }
void Settings::setHighlightPosition(bool highlight) {
if (this->highlightPosition == highlight) {
return;
}
this->highlightPosition = highlight;
save();
}
auto Settings::getCursorHighlightColor() const -> Color { return this->cursorHighlightColor; }
void Settings::setCursorHighlightColor(Color color) {
if (this->cursorHighlightColor != color) {
this->cursorHighlightColor = color;
save();
}
}
auto Settings::getCursorHighlightRadius() const -> double { return this->cursorHighlightRadius; }
void Settings::setCursorHighlightRadius(double radius) {
if (this->cursorHighlightRadius != radius) {
this->cursorHighlightRadius = radius;
save();
}
}
auto Settings::getCursorHighlightBorderColor() const -> Color { return this->cursorHighlightBorderColor; }
void Settings::setCursorHighlightBorderColor(Color color) {
if (this->cursorHighlightBorderColor != color) {
this->cursorHighlightBorderColor = color;
save();
}
}
auto Settings::getCursorHighlightBorderWidth() const -> double { return this->cursorHighlightBorderWidth; }
void Settings::setCursorHighlightBorderWidth(double radius) {
if (this->cursorHighlightBorderWidth != radius) {
this->cursorHighlightBorderWidth = radius;
save();
}
}
auto Settings::isSnapRotation() const -> bool { return this->snapRotation; }
void Settings::setSnapRotation(bool b) {
if (this->snapRotation == b) {
return;
}
this->snapRotation = b;
save();
}
auto Settings::getSnapRotationTolerance() const -> double { return this->snapRotationTolerance; }
void Settings::setSnapRotationTolerance(double tolerance) {
this->snapRotationTolerance = tolerance;
save();
}
auto Settings::isSnapGrid() const -> bool { return this->snapGrid; }
void Settings::setSnapGrid(bool b) {
if (this->snapGrid == b) {
return;
}
this->snapGrid = b;
save();
}
void Settings::setSnapGridTolerance(double tolerance) {
this->snapGridTolerance = tolerance;
save();
}
auto Settings::getSnapGridTolerance() const -> double { return this->snapGridTolerance; }
auto Settings::getSnapGridSize() const -> double { return this->snapGridSize; };
void Settings::setSnapGridSize(double gridSize) {
if (this->snapGridSize == gridSize) {
return;
}
this->snapGridSize = gridSize;
save();
}
auto Settings::getStrokeRecognizerMinSize() const -> double { return this->strokeRecognizerMinSize; };
void Settings::setStrokeRecognizerMinSize(double value) {
if (this->strokeRecognizerMinSize == value) {
return;
}
this->strokeRecognizerMinSize = value;
save();
};
auto Settings::getTouchDrawingEnabled() const -> bool { return this->touchDrawing; }
void Settings::setTouchDrawingEnabled(bool b) {
if (this->touchDrawing == b) {
return;
}
this->touchDrawing = b;
save();
}
auto Settings::getGtkTouchInertialScrollingEnabled() const -> bool { return this->gtkTouchInertialScrolling; };
void Settings::setGtkTouchInertialScrollingEnabled(bool b) {
if (this->gtkTouchInertialScrolling == b) {
return;
}
this->gtkTouchInertialScrolling = b;
save();
}
auto Settings::isPressureGuessingEnabled() const -> bool { return this->pressureGuessing; }
void Settings::setPressureGuessingEnabled(bool b) {
if (this->pressureGuessing == b) {
return;
}
this->pressureGuessing = b;
save();
}
double Settings::getMinimumPressure() const { return this->minimumPressure; }
void Settings::setMinimumPressure(double minimumPressure) {
if (this->minimumPressure == minimumPressure) {
return;
}
this->minimumPressure = minimumPressure;
save();
}
double Settings::getPressureMultiplier() const { return this->pressureMultiplier; }
void Settings::setPressureMultiplier(double multiplier) {
if (this->pressureMultiplier == multiplier) {
return;
}
this->pressureMultiplier = multiplier;
save();
}
auto Settings::getScrollbarHideType() const -> ScrollbarHideType { return this->scrollbarHideType; }
void Settings::setScrollbarHideType(ScrollbarHideType type) {
if (this->scrollbarHideType == type) {
return;
}
this->scrollbarHideType = type;
save();
}
auto Settings::isAutoloadMostRecent() const -> bool { return this->autoloadMostRecent; }
void Settings::setAutoloadMostRecent(bool load) {
if (this->autoloadMostRecent == load) {
return;
}
this->autoloadMostRecent = load;
save();
}
auto Settings::isAutoloadPdfXoj() const -> bool { return this->autoloadPdfXoj; }
void Settings::setAutoloadPdfXoj(bool load) {
if (this->autoloadPdfXoj == load) {
return;
}
this->autoloadPdfXoj = load;
save();
}
auto Settings::getDefaultSaveName() const -> string const& { return this->defaultSaveName; }
void Settings::setDefaultSaveName(const string& name) {
if (this->defaultSaveName == name) {
return;
}
this->defaultSaveName = name;
save();
}
auto Settings::getDefaultPdfExportName() const -> string const& { return this->defaultPdfExportName; }
void Settings::setDefaultPdfExportName(const string& name) {
if (this->defaultPdfExportName == name) {
return;
}
this->defaultPdfExportName = name;
save();
}
auto Settings::getPageTemplate() const -> string const& { return this->pageTemplate; }
void Settings::setPageTemplate(const string& pageTemplate) {
if (this->pageTemplate == pageTemplate) {
return;
}
this->pageTemplate = pageTemplate;
save();
}
auto Settings::getAudioFolder() const -> fs::path const& { return this->audioFolder; }
void Settings::setAudioFolder(fs::path audioFolder) {
if (this->audioFolder == audioFolder) {
return;
}
this->audioFolder = std::move(audioFolder);
save();
}
auto Settings::getSizeUnit() const -> string const& { return sizeUnit; }
void Settings::setSizeUnit(const string& sizeUnit) {
if (this->sizeUnit == sizeUnit) {
return;
}
this->sizeUnit = sizeUnit;
save();
}
/**
* Get size index in XOJ_UNITS
*/
auto Settings::getSizeUnitIndex() const -> int {
string unit = getSizeUnit();
for (int i = 0; i < XOJ_UNIT_COUNT; i++) {
if (unit == XOJ_UNITS[i].name) {
return i;
}
}
return 0;
}
/**
* Set size index in XOJ_UNITS
*/
void Settings::setSizeUnitIndex(int sizeUnitId) {
if (sizeUnitId < 0 || sizeUnitId >= XOJ_UNIT_COUNT) {
sizeUnitId = 0;
}
setSizeUnit(XOJ_UNITS[sizeUnitId].name);
}
void Settings::setShowPairedPages(bool showPairedPages) {
if (this->showPairedPages == showPairedPages) {
return;
}
this->showPairedPages = showPairedPages;
save();
}
auto Settings::isShowPairedPages() const -> bool { return this->showPairedPages; }
void Settings::setPresentationMode(bool presentationMode) {
if (this->presentationMode == presentationMode) {
return;
}
if (presentationMode) {
this->activeViewMode = PresetViewModeIds::VIEW_MODE_PRESENTATION;
}
this->presentationMode = presentationMode;
save();
}
auto Settings::isPresentationMode() const -> bool {
return this->activeViewMode == PresetViewModeIds::VIEW_MODE_PRESENTATION;
}
void Settings::setPressureSensitivity(gboolean presureSensitivity) {
if (this->pressureSensitivity == presureSensitivity) {
return;
}
this->pressureSensitivity = presureSensitivity;
save();
}
void Settings::setPairsOffset(int numOffset) {
if (this->numPairsOffset == numOffset) {
return;
}
this->numPairsOffset = numOffset;
save();
}
auto Settings::getPairsOffset() const -> int { return this->numPairsOffset; }
void Settings::setEmptyLastPageAppend(EmptyLastPageAppendType emptyLastPageAppend) {
if (this->emptyLastPageAppend == emptyLastPageAppend) {
return;
}
this->emptyLastPageAppend = emptyLastPageAppend;
save();
}
auto Settings::getEmptyLastPageAppend() const -> EmptyLastPageAppendType { return this->emptyLastPageAppend; }
void Settings::setViewColumns(int numColumns) {
if (this->numColumns == numColumns) {
return;
}
this->numColumns = numColumns;
save();
}
auto Settings::getViewColumns() const -> int { return this->numColumns; }
void Settings::setViewRows(int numRows) {
if (this->numRows == numRows) {
return;
}
this->numRows = numRows;
save();
}
auto Settings::getViewRows() const -> int { return this->numRows; }
void Settings::setViewFixedRows(bool viewFixedRows) {
if (this->viewFixedRows == viewFixedRows) {
return;
}
this->viewFixedRows = viewFixedRows;
save();
}
auto Settings::isViewFixedRows() const -> bool { return this->viewFixedRows; }
void Settings::setViewLayoutVert(bool vert) {
if (this->layoutVertical == vert) {
return;
}
this->layoutVertical = vert;
save();
}
auto Settings::getViewLayoutVert() const -> bool { return this->layoutVertical; }
void Settings::setViewLayoutR2L(bool r2l) {
if (this->layoutRightToLeft == r2l) {
return;
}
this->layoutRightToLeft = r2l;
save();
}
auto Settings::getViewLayoutR2L() const -> bool { return this->layoutRightToLeft; }
void Settings::setViewLayoutB2T(bool b2t) {
if (this->layoutBottomToTop == b2t) {
return;
}
this->layoutBottomToTop = b2t;
save();
}
auto Settings::getViewLayoutB2T() const -> bool { return this->layoutBottomToTop; }
void Settings::setLastSavePath(fs::path p) {
this->lastSavePath = std::move(p);
save();
}
auto Settings::getLastSavePath() const -> fs::path const& { return this->lastSavePath; }
void Settings::setLastOpenPath(fs::path p) {
this->lastOpenPath = std::move(p);
save();
}
auto Settings::getLastOpenPath() const -> fs::path const& { return this->lastOpenPath; }
void Settings::setLastImagePath(const fs::path& path) {
if (this->lastImagePath == path) {
return;
}
this->lastImagePath = path;
save();
}
auto Settings::getLastImagePath() const -> fs::path const& { return this->lastImagePath; }
void Settings::setZoomStep(double zoomStep) {
if (this->zoomStep == zoomStep) {
return;
}
this->zoomStep = zoomStep;
save();
}
auto Settings::getZoomStep() const -> double { return this->zoomStep; }
void Settings::setZoomStepScroll(double zoomStepScroll) {
if (this->zoomStepScroll == zoomStepScroll) {
return;
}
this->zoomStepScroll = zoomStepScroll;
save();
}
auto Settings::getZoomStepScroll() const -> double { return this->zoomStepScroll; }
void Settings::setEdgePanSpeed(double speed) {
if (this->edgePanSpeed == speed) {
return;
}
this->edgePanSpeed = speed;
save();
}
auto Settings::getEdgePanSpeed() const -> double { return this->edgePanSpeed; }
void Settings::setEdgePanMaxMult(double maxMult) {
if (this->edgePanMaxMult == maxMult) {
return;
}
this->edgePanMaxMult = maxMult;
save();
}
auto Settings::getEdgePanMaxMult() const -> double { return this->edgePanMaxMult; }
void Settings::setDisplayDpi(int dpi) {
if (this->displayDpi == dpi) {
return;
}
this->displayDpi = dpi;
save();
}
auto Settings::getDisplayDpi() const -> int { return this->displayDpi; }
void Settings::setAreStockIconsUsed(bool use) {
if (this->useStockIcons == use) {
return;
}
this->useStockIcons = use;
save();
}
auto Settings::areStockIconsUsed() const -> bool { return this->useStockIcons; }
auto Settings::isFullscreen() const -> bool { return this->fullscreenActive; }
auto Settings::isSidebarVisible() const -> bool { return this->showSidebar; }
void Settings::setSidebarVisible(bool visible) {
if (this->showSidebar == visible) {
return;
}
this->showSidebar = visible;
save();
}
auto Settings::isToolbarVisible() const -> bool { return this->showToolbar; }
void Settings::setToolbarVisible(bool visible) {
if (this->showToolbar == visible) {
return;
}
this->showToolbar = visible;
save();
}
auto Settings::getSidebarWidth() const -> int { return this->sidebarWidth; }
void Settings::setSidebarWidth(int width) {
width = std::max(width, 50);
if (this->sidebarWidth == width) {
return;
}
this->sidebarWidth = width;
save();
}
void Settings::setMainWndSize(int width, int height) {
this->mainWndWidth = width;
this->mainWndHeight = height;
save();
}
auto Settings::getMainWndWidth() const -> int { return this->mainWndWidth; }
auto Settings::getMainWndHeight() const -> int { return this->mainWndHeight; }
auto Settings::isMainWndMaximized() const -> bool { return this->maximized; }
void Settings::setMainWndMaximized(bool max) {
if (this->maximized == max) {
return;
}
this->maximized = max;
save();
}
void Settings::setSelectedToolbar(const string& name) {
if (this->selectedToolbar == name) {
return;
}
this->selectedToolbar = name;
save();
}
auto Settings::getSelectedToolbar() const -> string const& { return this->selectedToolbar; }
auto Settings::getCustomElement(const string& name) -> SElement& { return this->data[name]; }
void Settings::customSettingsChanged() { save(); }
auto Settings::getButtonConfig(unsigned int id) -> ButtonConfig* {
if (id >= this->buttonConfig.size()) {
g_error("Settings::getButtonConfig try to get id=%i out of range!", id);
return nullptr;
}
return this->buttonConfig[id].get();
}
void Settings::setViewMode(ViewModeId mode, ViewMode viewMode) {
if (this->viewModes[mode] == viewMode) {
return;
}
this->viewModes.at(mode) = viewMode;
save();
}
auto Settings::getTouchZoomStartThreshold() const -> double { return this->touchZoomStartThreshold; }
void Settings::setTouchZoomStartThreshold(double threshold) {
if (this->touchZoomStartThreshold == threshold) {
return;
}
this->touchZoomStartThreshold = threshold;
save();
}
auto Settings::getPDFPageRerenderThreshold() const -> double { return this->pageRerenderThreshold; }
void Settings::setPDFPageRerenderThreshold(double threshold) {
if (this->pageRerenderThreshold == threshold) {
return;
}
this->pageRerenderThreshold = threshold;
save();
}
auto Settings::getPdfPageCacheSize() const -> int { return this->pdfPageCacheSize; }
void Settings::setPdfPageCacheSize(int size) {
if (this->pdfPageCacheSize == size) {
return;
}
this->pdfPageCacheSize = size;
save();
}
auto Settings::getPreloadPagesBefore() const -> unsigned int { return this->preloadPagesBefore; }
void Settings::setPreloadPagesBefore(unsigned int n) {
if (this->preloadPagesBefore == n) {
return;
}
this->preloadPagesBefore = n;
save();
}
auto Settings::getPreloadPagesAfter() const -> unsigned int { return this->preloadPagesAfter; }
void Settings::setPreloadPagesAfter(unsigned int n) {
if (this->preloadPagesAfter == n) {
return;
}
this->preloadPagesAfter = n;
save();
}
auto Settings::isEagerPageCleanup() const -> bool { return this->eagerPageCleanup; }
void Settings::setEagerPageCleanup(bool b) {
if (this->eagerPageCleanup == b) {
return;
}
this->eagerPageCleanup = b;
save();
}
auto Settings::getBorderColor() const -> Color { return this->selectionBorderColor; }
void Settings::setBorderColor(Color color) {
if (this->selectionBorderColor == color) {
return;
}
this->selectionBorderColor = color;
save();
}
auto Settings::getSelectionColor() const -> Color { return this->selectionMarkerColor; }
void Settings::setSelectionColor(Color color) {
if (this->selectionMarkerColor == color) {
return;
}
this->selectionMarkerColor = color;
save();
}
auto Settings::getActiveSelectionColor() const -> Color { return this->activeSelectionColor; }
void Settings::setActiveSelectionColor(Color color) {
if (this->activeSelectionColor == color) {
return;
}
this->activeSelectionColor = color;
save();
}
auto Settings::getBackgroundColor() const -> Color { return this->backgroundColor; }
void Settings::setBackgroundColor(Color color) {
if (this->backgroundColor == color) {
return;
}
this->backgroundColor = color;
save();
}
auto Settings::getFont() -> XojFont& { return this->font; }
void Settings::setFont(const XojFont& font) {
this->font = font;
save();
}
auto Settings::getAudioInputDevice() const -> PaDeviceIndex { return this->audioInputDevice; }
void Settings::setAudioInputDevice(PaDeviceIndex deviceIndex) {
if (this->audioInputDevice == deviceIndex) {
return;
}
this->audioInputDevice = deviceIndex;
save();
}
auto Settings::getAudioOutputDevice() const -> PaDeviceIndex { return this->audioOutputDevice; }
void Settings::setAudioOutputDevice(PaDeviceIndex deviceIndex) {
if (this->audioOutputDevice == deviceIndex) {
return;
}
this->audioOutputDevice = deviceIndex;
save();
}
auto Settings::getAudioSampleRate() const -> double { return this->audioSampleRate; }
void Settings::setAudioSampleRate(double sampleRate) {
if (this->audioSampleRate == sampleRate) {
return;
}
this->audioSampleRate = sampleRate;
save();
}
auto Settings::getAudioGain() const -> double { return this->audioGain; }
void Settings::setAudioGain(double gain) {
if (this->audioGain == gain) {
return;
}
this->audioGain = gain;
save();
}
auto Settings::getDefaultSeekTime() const -> unsigned int { return this->defaultSeekTime; }
void Settings::setDefaultSeekTime(unsigned int t) {
if (this->defaultSeekTime == t) {
return;
}
this->defaultSeekTime = t;
save();
}
auto Settings::getPluginEnabled() const -> string const& { return this->pluginEnabled; }
void Settings::setPluginEnabled(const string& pluginEnabled) {
if (this->pluginEnabled == pluginEnabled) {
return;
}
this->pluginEnabled = pluginEnabled;
save();
}
auto Settings::getPluginDisabled() const -> string const& { return this->pluginDisabled; }
void Settings::setPluginDisabled(const string& pluginDisabled) {
if (this->pluginDisabled == pluginDisabled) {
return;
}
this->pluginDisabled = pluginDisabled;
save();
}
void Settings::getStrokeFilter(int* ignoreTime, double* ignoreLength, int* successiveTime) const {
*ignoreTime = this->strokeFilterIgnoreTime;
*ignoreLength = this->strokeFilterIgnoreLength;
*successiveTime = this->strokeFilterSuccessiveTime;
}
void Settings::setStrokeFilter(int ignoreTime, double ignoreLength, int successiveTime) {
this->strokeFilterIgnoreTime = ignoreTime;
this->strokeFilterIgnoreLength = ignoreLength;
this->strokeFilterSuccessiveTime = successiveTime;
}
void Settings::setStrokeFilterEnabled(bool enabled) { this->strokeFilterEnabled = enabled; }
auto Settings::getStrokeFilterEnabled() const -> bool { return this->strokeFilterEnabled; }
void Settings::setDoActionOnStrokeFiltered(bool enabled) { this->doActionOnStrokeFiltered = enabled; }
auto Settings::getDoActionOnStrokeFiltered() const -> bool { return this->doActionOnStrokeFiltered; }
void Settings::setTrySelectOnStrokeFiltered(bool enabled) { this->trySelectOnStrokeFiltered = enabled; }
auto Settings::getTrySelectOnStrokeFiltered() const -> bool { return this->trySelectOnStrokeFiltered; }
void Settings::setSnapRecognizedShapesEnabled(bool enabled) { this->snapRecognizedShapesEnabled = enabled; }
auto Settings::getSnapRecognizedShapesEnabled() const -> bool { return this->snapRecognizedShapesEnabled; }
void Settings::setRestoreLineWidthEnabled(bool enabled) { this->restoreLineWidthEnabled = enabled; }
auto Settings::getRestoreLineWidthEnabled() const -> bool { return this->restoreLineWidthEnabled; }
auto Settings::setPreferredLocale(std::string const& locale) -> void { this->preferredLocale = locale; }
auto Settings::getPreferredLocale() const -> std::string { return this->preferredLocale; }
void Settings::setIgnoredStylusEvents(int numEvents) {
if (this->numIgnoredStylusEvents == numEvents) {
return;
}
this->numIgnoredStylusEvents = std::max<int>(numEvents, 0);
save();
}
auto Settings::getIgnoredStylusEvents() const -> int { return this->numIgnoredStylusEvents; }
void Settings::setInputSystemTPCButtonEnabled(bool tpcButtonEnabled) {
if (this->inputSystemTPCButton == tpcButtonEnabled) {
return;
}
this->inputSystemTPCButton = tpcButtonEnabled;
save();
}
auto Settings::getInputSystemTPCButtonEnabled() const -> bool { return this->inputSystemTPCButton; }
void Settings::setInputSystemDrawOutsideWindowEnabled(bool drawOutsideWindowEnabled) {
if (this->inputSystemDrawOutsideWindow == drawOutsideWindowEnabled) {
return;
}
this->inputSystemDrawOutsideWindow = drawOutsideWindowEnabled;
save();
}
auto Settings::getInputSystemDrawOutsideWindowEnabled() const -> bool { return this->inputSystemDrawOutsideWindow; }
void Settings::setDeviceClassForDevice(GdkDevice* device, InputDeviceTypeOption deviceClass) {
this->setDeviceClassForDevice(gdk_device_get_name(device), gdk_device_get_source(device), deviceClass);
}
void Settings::setDeviceClassForDevice(const string& deviceName, GdkInputSource deviceSource,
InputDeviceTypeOption deviceClass) {
auto it = inputDeviceClasses.find(deviceName);
if (it != inputDeviceClasses.end()) {
it->second.first = deviceClass;
it->second.second = deviceSource;
} else {
inputDeviceClasses.emplace(deviceName, std::make_pair(deviceClass, deviceSource));
}
}
auto Settings::getKnownInputDevices() const -> std::vector<InputDevice> {
std::vector<InputDevice> inputDevices;
for (auto pair: inputDeviceClasses) {
const std::string& name = pair.first;
GdkInputSource& source = pair.second.second;
inputDevices.emplace_back(name, source);
}
return inputDevices;
}
auto Settings::getDeviceClassForDevice(GdkDevice* device) const -> InputDeviceTypeOption {
return this->getDeviceClassForDevice(gdk_device_get_name(device), gdk_device_get_source(device));
}
auto Settings::getDeviceClassForDevice(const string& deviceName, GdkInputSource deviceSource) const
-> InputDeviceTypeOption {
auto search = inputDeviceClasses.find(deviceName);
if (search != inputDeviceClasses.end()) {
return search->second.first;
}
InputDeviceTypeOption deviceType = InputDeviceTypeOption::Disabled;
switch (deviceSource) {
case GDK_SOURCE_CURSOR:
#if (GDK_MAJOR_VERSION >= 3 && GDK_MINOR_VERSION >= 22)
case GDK_SOURCE_TABLET_PAD:
#endif
case GDK_SOURCE_KEYBOARD:
deviceType = InputDeviceTypeOption::Disabled;
break;
case GDK_SOURCE_MOUSE:
case GDK_SOURCE_TOUCHPAD:
#if (GDK_MAJOR_VERSION >= 3 && GDK_MINOR_VERSION >= 22)
case GDK_SOURCE_TRACKPOINT:
#endif
deviceType = InputDeviceTypeOption::Mouse;
break;
case GDK_SOURCE_PEN:
deviceType = InputDeviceTypeOption::Pen;
break;
case GDK_SOURCE_ERASER:
deviceType = InputDeviceTypeOption::Eraser;
break;
case GDK_SOURCE_TOUCHSCREEN:
deviceType = InputDeviceTypeOption::Touchscreen;
break;
default:
deviceType = InputDeviceTypeOption::Disabled;
}
return deviceType;
}
auto Settings::isScrollbarFadeoutDisabled() const -> bool { return disableScrollbarFadeout; }
void Settings::setScrollbarFadeoutDisabled(bool disable) {
if (disableScrollbarFadeout == disable) {
return;
}
disableScrollbarFadeout = disable;
save();
}
auto Settings::isAudioDisabled() const -> bool { return disableAudio; }
void Settings::setAudioDisabled(bool disable) {
if (disableAudio == disable) {
return;
}
disableAudio = disable;
save();
}
//////////////////////////////////////////////////
SAttribute::SAttribute() {
this->dValue = 0;
this->iValue = 0;
this->type = ATTRIBUTE_TYPE_NONE;
}
SAttribute::SAttribute(const SAttribute& attrib) { *this = attrib; }
SAttribute::~SAttribute() {
this->iValue = 0;
this->type = ATTRIBUTE_TYPE_NONE;
}
//////////////////////////////////////////////////
auto SElement::attributes() -> std::map<string, SAttribute>& { return this->element->attributes; }
auto SElement::children() -> std::map<string, SElement>& { return this->element->children; }
void SElement::clear() {
this->element->attributes.clear();
this->element->children.clear();
}
auto SElement::child(const string& name) -> SElement& { return this->element->children[name]; }
void SElement::setComment(const string& name, const string& comment) {
SAttribute& attrib = this->element->attributes[name];
attrib.comment = comment;
}
void SElement::setIntHex(const string& name, const int value) {
SAttribute& attrib = this->element->attributes[name];
attrib.iValue = value;
attrib.type = ATTRIBUTE_TYPE_INT_HEX;
}
void SElement::setInt(const string& name, const int value) {
SAttribute& attrib = this->element->attributes[name];
attrib.iValue = value;
attrib.type = ATTRIBUTE_TYPE_INT;
}
void SElement::setBool(const string& name, const bool value) {
SAttribute& attrib = this->element->attributes[name];
attrib.iValue = value;
attrib.type = ATTRIBUTE_TYPE_BOOLEAN;
}
void SElement::setString(const string& name, const string& value) {
SAttribute& attrib = this->element->attributes[name];
attrib.sValue = value;
attrib.type = ATTRIBUTE_TYPE_STRING;
}
void SElement::setDouble(const string& name, const double value) {
SAttribute& attrib = this->element->attributes[name];
attrib.dValue = value;
attrib.type = ATTRIBUTE_TYPE_DOUBLE;
}
auto SElement::getDouble(const string& name, double& value) -> bool {
SAttribute& attrib = this->element->attributes[name];
if (attrib.type == ATTRIBUTE_TYPE_NONE) {
this->element->attributes.erase(name);
return false;
}
if (attrib.type != ATTRIBUTE_TYPE_DOUBLE) {
return false;
}
value = attrib.dValue;
return true;
}
auto SElement::getInt(const string& name, int& value) -> bool {
SAttribute& attrib = this->element->attributes[name];
if (attrib.type == ATTRIBUTE_TYPE_NONE) {
this->element->attributes.erase(name);
return false;
}
if (attrib.type != ATTRIBUTE_TYPE_INT && attrib.type != ATTRIBUTE_TYPE_INT_HEX) {
return false;
}
value = attrib.iValue;
return true;
}
auto SElement::getBool(const string& name, bool& value) -> bool {
SAttribute& attrib = this->element->attributes[name];
if (attrib.type == ATTRIBUTE_TYPE_NONE) {
this->element->attributes.erase(name);
return false;
}
if (attrib.type != ATTRIBUTE_TYPE_BOOLEAN) {
return false;
}
value = attrib.iValue;
return true;
}
auto SElement::getString(const string& name, string& value) -> bool {
SAttribute& attrib = this->element->attributes[name];
if (attrib.type == ATTRIBUTE_TYPE_NONE) {
this->element->attributes.erase(name);
return false;
}
if (attrib.type != ATTRIBUTE_TYPE_STRING) {
return false;
}
value = attrib.sValue;
return true;
}
/**
* Stabilizer related getters and setters
*/
auto Settings::getStabilizerCuspDetection() const -> bool { return stabilizerCuspDetection; }
auto Settings::getStabilizerFinalizeStroke() const -> bool { return stabilizerFinalizeStroke; }
auto Settings::getStabilizerBuffersize() const -> size_t { return stabilizerBuffersize; }
auto Settings::getStabilizerDeadzoneRadius() const -> double { return stabilizerDeadzoneRadius; }
auto Settings::getStabilizerDrag() const -> double { return stabilizerDrag; }
auto Settings::getStabilizerMass() const -> double { return stabilizerMass; }
auto Settings::getStabilizerSigma() const -> double { return stabilizerSigma; }
auto Settings::getStabilizerAveragingMethod() const -> StrokeStabilizer::AveragingMethod {
return stabilizerAveragingMethod;
}
auto Settings::getStabilizerPreprocessor() const -> StrokeStabilizer::Preprocessor { return stabilizerPreprocessor; }
void Settings::setStabilizerCuspDetection(bool cuspDetection) {
if (stabilizerCuspDetection == cuspDetection) {
return;
}
stabilizerCuspDetection = cuspDetection;
save();
}
void Settings::setStabilizerFinalizeStroke(bool finalizeStroke) {
if (stabilizerFinalizeStroke == finalizeStroke) {
return;
}
stabilizerFinalizeStroke = finalizeStroke;
save();
}
void Settings::setStabilizerBuffersize(size_t buffersize) {
if (stabilizerBuffersize == buffersize) {
return;
}
stabilizerBuffersize = buffersize;
save();
}
void Settings::setStabilizerDeadzoneRadius(double deadzoneRadius) {
if (stabilizerDeadzoneRadius == deadzoneRadius) {
return;
}
stabilizerDeadzoneRadius = deadzoneRadius;
save();
}
void Settings::setStabilizerDrag(double drag) {
if (stabilizerDrag == drag) {
return;
}
stabilizerDrag = drag;
save();
}
void Settings::setStabilizerMass(double mass) {
if (stabilizerMass == mass) {
return;
}
stabilizerMass = mass;
save();
}
void Settings::setStabilizerSigma(double sigma) {
if (stabilizerSigma == sigma) {
return;
}
stabilizerSigma = sigma;
save();
}
void Settings::setStabilizerAveragingMethod(StrokeStabilizer::AveragingMethod averagingMethod) {
const StrokeStabilizer::AveragingMethod method =
StrokeStabilizer::isValid(averagingMethod) ? averagingMethod : StrokeStabilizer::AveragingMethod::NONE;
if (stabilizerAveragingMethod == method) {
return;
}
stabilizerAveragingMethod = method;
save();
}
void Settings::setStabilizerPreprocessor(StrokeStabilizer::Preprocessor preprocessor) {
const StrokeStabilizer::Preprocessor p =
StrokeStabilizer::isValid(preprocessor) ? preprocessor : StrokeStabilizer::Preprocessor::NONE;
if (stabilizerPreprocessor == p) {
return;
}
stabilizerPreprocessor = p;
save();
}
auto Settings::getColorPaletteSetting() -> fs::path const& { return this->colorPaletteSetting; }
void Settings::setColorPaletteSetting(fs::path palettePath) { this->colorPaletteSetting = palettePath; }
void Settings::setUseSpacesAsTab(bool useSpaces) { this->useSpacesForTab = useSpaces; }
bool Settings::getUseSpacesAsTab() const { return this->useSpacesForTab; }
void Settings::setNumberOfSpacesForTab(unsigned int numberOfSpaces) {
if (this->numberOfSpacesForTab == numberOfSpaces) {
return;
}
// For performance reasons the number of spaces for a tab should be limited
// if this limit is exceeded use a default value
if (numberOfSpaces < 0 || numberOfSpaces > MAX_SPACES_FOR_TAB) {
g_warning("Settings::Invalid number of spaces for tab. Reset to default!");
numberOfSpaces = 4;
}
this->numberOfSpacesForTab = numberOfSpaces;
save();
}
unsigned int Settings::getNumberOfSpacesForTab() const { return this->numberOfSpacesForTab; }
| 100,380
|
C++
|
.cpp
| 2,097
| 41.671912
| 141
| 0.687191
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,500
|
ActionDatabase.cpp
|
xournalpp_xournalpp/src/core/control/actions/ActionDatabase.cpp
|
#include "ActionDatabase.h"
#include <type_traits>
#include <utility>
#include <gobject/gsignal.h>
#include "control/Control.h"
#include "gui/MainWindow.h"
#include "util/GVariantTemplate.h"
#include "util/safe_casts.h" // for to_underlying Todo(cpp20) remove
#include "ActionProperties.h"
#ifdef DEBUG_ACTION_DB
#define START_ROW " * " << std::left << std::setw(30) << std::boolalpha << Action_toString(a)
#endif
template <Action a, class U = void>
struct InitiallyEnabled {
static inline void setup(ActionDatabase* db, Control*) { db->enableAction(a, true); }
};
template <Action a>
struct InitiallyEnabled<a, std::void_t<decltype(&ActionProperties<a>::initiallyEnabled)>> {
static inline void setup(ActionDatabase* db, Control* ctrl) {
db->enableAction(a, ActionProperties<a>::initiallyEnabled(ctrl));
}
};
class ActionDatabase::Populator {
/// Choose the right action namespace
template <Action a, class U = void>
struct ActionNamespace {
static constexpr auto ACTION_NAMESPACE = "win.";
static void addToActionMap(ActionDatabase* db) {
g_action_map_add_action(G_ACTION_MAP(db->win), G_ACTION(db->gActions[a].get()));
}
};
template <Action a>
struct ActionNamespace<
a, std::enable_if_t<std::is_same_v<typename ActionProperties<a>::app_namespace, std::true_type>, void>> {
static constexpr auto ACTION_NAMESPACE = "app.";
static void addToActionMap(ActionDatabase* db) {
g_action_map_add_action(G_ACTION_MAP(gtk_window_get_application(GTK_WINDOW(db->win))),
G_ACTION(db->gActions[a].get()));
}
};
/**
* Accelerators<a>::setup(ctrl); will setup the accelerators listed in ActionProperties<a>::accelerators (if any)
*/
template <Action a, class U = void>
struct Accelerators {
static inline void setup(Control*) {}
};
template <Action a>
struct Accelerators<a, std::void_t<decltype(&ActionProperties<a>::accelerators)>> {
static_assert(std::is_array_v<decltype(ActionProperties<a>::accelerators)>);
static_assert(
std::is_same_v<std::remove_extent_t<decltype(ActionProperties<a>::accelerators)>, const char* const>);
static_assert(
ActionProperties<a>::accelerators[std::extent_v<decltype(ActionProperties<a>::accelerators)> - 1] ==
nullptr,
"ActionProperties<a>::accelerators must be null terminated");
static inline void setup(Control* ctrl) {
// Todo(cpp20) constexpr this concatenation
std::string fullActionName = ActionNamespace<a>::ACTION_NAMESPACE;
fullActionName += Action_toString(a);
gtk_application_set_accels_for_action(GTK_APPLICATION(gtk_window_get_application(ctrl->getGtkWindow())),
fullActionName.c_str(), ActionProperties<a>::accelerators);
}
};
template <Action a>
static inline void finishSetup(ActionDatabase* db, const char* signal) {
db->signalIds[a] = g_signal_connect(G_OBJECT(db->gActions[a].get()), signal,
G_CALLBACK(ActionProperties<a>::callback), db->control);
ActionNamespace<a>::addToActionMap(db);
// g_action_map_add_action(G_ACTION_MAP(db->win), G_ACTION(db->gActions[a].get()));
Accelerators<a>::setup(db->control);
InitiallyEnabled<a>::setup(db, db->control);
}
// Actions without state or parameter
template <Action a, std::enable_if_t<!has_param<a>() && !has_state<a>(), bool> = true>
static void assign(ActionDatabase* db) {
ACTIONDB_PRINT_DEBUG(START_ROW << " | | |");
db->gActions[a].reset(g_simple_action_new(Action_toString(a), nullptr), xoj::util::adopt);
finishSetup<a>(db, "activate");
}
// Actions with parameter but no state
template <Action a, std::enable_if_t<has_param<a>() && !has_state<a>(), bool> = true>
static void assign(ActionDatabase* db) {
ACTIONDB_PRINT_DEBUG(START_ROW << " | | type = \""
<< (const char*)gVariantType<typename ActionProperties<a>::parameter_type>()
<< "\" |");
db->gActions[a].reset(
g_simple_action_new(Action_toString(a), gVariantType<typename ActionProperties<a>::parameter_type>()),
xoj::util::adopt);
finishSetup<a>(db, "activate");
}
// Actions with a state but no parameter
template <Action a, std::enable_if_t<!has_param<a>() && has_state<a>(), bool> = true>
static void assign(ActionDatabase* db) {
ACTIONDB_PRINT_DEBUG(START_ROW << " | \""
<< (const char*)gVariantType<typename ActionProperties<a>::state_type>()
<< "\" = " << std::setw(7) << ActionProperties<a>::initialState(db->control)
<< " | |");
db->gActions[a].reset(g_simple_action_new_stateful(Action_toString(a), nullptr,
makeGVariant<typename ActionProperties<a>::state_type>(
ActionProperties<a>::initialState(db->control))),
xoj::util::adopt);
finishSetup<a>(db, "change-state");
}
// Actions with both state and parameter (with matching type)
template <Action a, std::enable_if_t<has_param<a>() && has_state<a>(), bool> = true>
static void assign(ActionDatabase* db) {
static_assert(
std::is_same_v<typename ActionProperties<a>::state_type, typename ActionProperties<a>::parameter_type>);
ACTIONDB_PRINT_DEBUG(
START_ROW << " | \"" << (const char*)gVariantType<typename ActionProperties<a>::state_type>()
<< "\" = " << std::setw(7) << ActionProperties<a>::initialState(db->control) << " | type = \""
<< (const char*)gVariantType<typename ActionProperties<a>::state_type>() << "\" |");
db->gActions[a].reset(g_simple_action_new_stateful(Action_toString(a),
gVariantType<typename ActionProperties<a>::state_type>(),
makeGVariant<typename ActionProperties<a>::state_type>(
ActionProperties<a>::initialState(db->control))),
xoj::util::adopt);
finishSetup<a>(db, "change-state");
}
template <size_t... As>
static void populateImpl(std::index_sequence<As...>, ActionDatabase* db) {
((assign<static_cast<Action>(As)>(db)), ...);
}
public:
static void populate(ActionDatabase* db);
};
void ActionDatabase::Populator::populate(ActionDatabase* db) {
ACTIONDB_PRINT_DEBUG("Populating ActionDatabase:");
ACTIONDB_PRINT_DEBUG(" ACTION NAME: | STATE INIT | PARAM TYPE |");
populateImpl(std::make_index_sequence<xoj::to_underlying(Action::ENUMERATOR_COUNT)>(), db);
}
ActionDatabase::ActionDatabase(Control* control):
control(control), win(GTK_APPLICATION_WINDOW(control->getWindow()->getWindow())) {
Populator::populate(this);
}
ActionDatabase::~ActionDatabase() {
auto sig = signalIds.begin();
for (auto& a: gActions) {
/**
* The GAction's might still be referenced elsewhere (e.g. by the GtkApplicationWindow), so we need to
* disconnect the signals in case a callback is called and the Control instance has been destroyed
*/
g_signal_handler_disconnect(a.get(), *sig++);
}
}
void ActionDatabase::enableAction(Action action, bool enable) {
xoj_assert(gActions[action]);
g_simple_action_set_enabled(gActions[action].get(), enable);
ACTIONDB_PRINT_DEBUG((enable ? "Enabling Action \"" : "Disabling Action\"") << Action_toString(action) << "\"");
}
auto ActionDatabase::getAction(Action a) const -> ActionRef { return gActions[a]; }
bool ActionDatabase::isActionEnabled(Action a) const {
xoj_assert(gActions[a]);
return g_action_get_enabled(G_ACTION(gActions[a].get()));
}
void ActionDatabase::disableAll() {
for (auto&& a: gActions) {
g_simple_action_set_enabled(a.get(), false);
}
}
template <size_t... As>
static void resetEnableStatusImpl(std::index_sequence<As...>, ActionDatabase* db, Control* ctrl) {
((InitiallyEnabled<static_cast<Action>(As)>::setup(db, ctrl)), ...);
}
void ActionDatabase::resetEnableStatus() {
resetEnableStatusImpl(std::make_index_sequence<xoj::to_underlying(Action::ENUMERATOR_COUNT)>(), this, control);
}
| 8,914
|
C++
|
.cpp
| 168
| 42.785714
| 120
| 0.607237
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,503
|
RecoSegment.cpp
|
xournalpp_xournalpp/src/core/control/shaperecognizer/RecoSegment.cpp
|
#include "RecoSegment.h"
#include <cmath>
#include "Inertia.h"
auto RecoSegment::calcEdgeIsect(RecoSegment* r2) const -> Point {
double t = (r2->xcenter - this->xcenter) * sin(r2->angle) - (r2->ycenter - this->ycenter) * cos(r2->angle);
t /= sin(r2->angle - this->angle);
double x = this->xcenter + t * cos(this->angle);
double y = this->ycenter + t * sin(this->angle);
return Point(x, y);
}
/**
* Find the geometry of a recognized segment
*/
void RecoSegment::calcSegmentGeometry(const Point* pt, int start, int end, Inertia* s) {
this->xcenter = s->centerX();
this->ycenter = s->centerY();
double a = s->xx();
double b = s->xy();
double c = s->yy();
// max angle for inertia quadratic form solves: tan(2t) = 2b/(a-c)
this->angle = atan2(2 * b, a - c) / 2;
this->radius = sqrt(3 * (a + c));
double lmin = 0;
double lmax = 0;
for (int i = start; i <= end; i++) {
double l = (pt[i].x - this->xcenter) * cos(this->angle) + (pt[i].y - this->ycenter) * sin(this->angle);
if (l < lmin) {
lmin = l;
}
if (l > lmax) {
lmax = l;
}
}
this->x1 = this->xcenter + lmin * cos(this->angle);
this->y1 = this->ycenter + lmin * sin(this->angle);
this->x2 = this->xcenter + lmax * cos(this->angle);
this->y2 = this->ycenter + lmax * sin(this->angle);
}
| 1,395
|
C++
|
.cpp
| 38
| 31.5
| 111
| 0.570156
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,504
|
ShapeRecognizer.cpp
|
xournalpp_xournalpp/src/core/control/shaperecognizer/ShapeRecognizer.cpp
|
#include "ShapeRecognizer.h"
#include <cmath> // for fabs, M_PI
#include <iterator> // for begin, next
#include <memory> // for allocator...
#include <utility> // for move
#include <vector> // for vector
#include <glib.h> // for g_message
#include "control/shaperecognizer/RecoSegment.h" // for RecoSegment
#include "control/shaperecognizer/ShapeRecognizerConfig.h" // for RDEBUG
#include "model/Point.h" // for Point
#include "model/Stroke.h" // for Stroke
#include "util/safe_casts.h" // for as_unsigned
#include "CircleRecognizer.h" // for CircleRec...
#include "Inertia.h" // for Inertia
#include "config-debug.h" // for DEBUG_REC...
ShapeRecognizer::ShapeRecognizer() {
resetRecognizer();
this->stroke = nullptr;
this->queueLength = 0;
}
ShapeRecognizer::~ShapeRecognizer() { resetRecognizer(); }
void ShapeRecognizer::resetRecognizer() {
RDEBUG("reset");
this->queue = {};
this->queueLength = 0;
}
/**
* Test if segments form standard shapes
*/
auto ShapeRecognizer::tryRectangle() -> std::unique_ptr<Stroke> {
// first, we need whole strokes to combine to 4 segments...
if (this->queueLength < 4) {
return nullptr;
}
RecoSegment* rs = &this->queue[as_unsigned(this->queueLength - 4)];
if (rs->startpt != 0) {
return nullptr;
}
// check edges make angles ~= Pi/2 and vertices roughly match
double avgAngle = 0.;
for (int i = 0; i <= 3; i++) {
RecoSegment* r1 = &rs[i];
RecoSegment* r2 = &rs[(i + 1) % 4];
if (fabs(fabs(r1->angle - r2->angle) - M_PI / 2) > RECTANGLE_ANGLE_TOLERANCE) {
return nullptr;
}
avgAngle += r1->angle;
if (r2->angle > r1->angle) {
avgAngle += (i + 1) * M_PI / 2;
} else {
avgAngle -= (i + 1) * M_PI / 2;
}
// test if r1 points away from r2 rather than towards it
r1->reversed =
((r1->x2 - r1->x1) * (r2->xcenter - r1->xcenter) + (r1->y2 - r1->y1) * (r2->ycenter - r1->ycenter)) < 0;
}
for (int i = 0; i <= 3; i++) {
RecoSegment* r1 = &rs[i];
RecoSegment* r2 = &rs[(i + 1) % 4];
double dist = hypot((r1->reversed ? r1->x1 : r1->x2) - (r2->reversed ? r2->x2 : r2->x1),
(r1->reversed ? r1->y1 : r1->y2) - (r2->reversed ? r2->y2 : r2->y1));
if (dist > RECTANGLE_LINEAR_TOLERANCE * (r1->radius + r2->radius)) {
return nullptr;
}
}
// make a rectangle of the correct size and slope
avgAngle = avgAngle / 4;
if (fabs(avgAngle) < SLANT_TOLERANCE) {
avgAngle = 0.;
}
if (fabs(avgAngle) > M_PI / 2 - SLANT_TOLERANCE) {
avgAngle = M_PI / 2;
}
auto s = std::make_unique<Stroke>();
s->applyStyleFrom(this->stroke);
for (int i = 0; i <= 3; i++) {
rs[i].angle = avgAngle + i * M_PI / 2;
}
for (int i = 0; i <= 3; i++) {
Point p = rs[i].calcEdgeIsect(&rs[(i + 1) % 4]);
s->addPoint(p);
}
s->addPoint(s->getPoint(0));
return s;
}
/*
* check if something is a polygonal line with at most nsides sides
*/
auto ShapeRecognizer::findPolygonal(const Point* pt, int start, int end, int nsides, int* breaks, Inertia* ss) -> int {
Inertia s;
int i1 = 0, i2 = 0, n1 = 0, n2 = 0;
if (end == start) {
return 0; // no way
}
if (nsides <= 0) {
return 0;
}
if (end - start < 5) {
nsides = 1; // too small for a polygon
}
// look for a linear piece that's big enough
int k = 0;
for (; k < nsides; k++) {
i1 = start + (k * (end - start)) / nsides;
i2 = start + ((k + 1) * (end - start)) / nsides;
s.calc(pt, i1, i2);
if (s.det() < SEGMENT_MAX_DET) {
break;
}
}
if (k == nsides) {
return 0; // failed!
}
double det1{};
double det2{};
Inertia s1;
Inertia s2;
// grow the linear piece we found
while (true) {
if (i1 > start) {
s1 = s;
s1.increase(pt[i1 - 1], pt[i1], 1);
det1 = s1.det();
} else {
det1 = 1.0;
}
if (i2 < end) {
s2 = s;
s2.increase(pt[i2], pt[i2 + 1], 1);
det2 = s2.det();
} else {
det2 = 1.0;
}
if (det1 < det2 && det1 < SEGMENT_MAX_DET) {
i1--;
s = s1;
} else if (det2 < det1 && det2 < SEGMENT_MAX_DET) {
i2++;
s = s2;
} else {
break;
}
}
if (i1 > start) {
n1 = findPolygonal(pt, start, i1, (i2 == end) ? (nsides - 1) : (nsides - 2), breaks, ss);
if (n1 == 0) {
return 0; // it doesn't work
}
} else {
n1 = 0;
}
breaks[n1] = i1;
breaks[n1 + 1] = i2;
ss[n1] = s;
if (i2 < end) {
n2 = findPolygonal(pt, i2, end, nsides - n1 - 1, breaks + n1 + 1, ss + n1 + 1);
if (n2 == 0) {
return 0;
}
} else {
n2 = 0;
}
return n1 + n2 + 1;
}
/**
* Improve on the polygon found by find_polygonal()
*/
void ShapeRecognizer::optimizePolygonal(const Point* pt, int nsides, int* breaks, Inertia* ss) {
for (int i = 1; i < nsides; i++) {
// optimize break between sides i and i+1
double cost = ss[i - 1].det() * ss[i - 1].det() + ss[i].det() * ss[i].det();
Inertia s1 = ss[i - 1];
Inertia s2 = ss[i];
bool improved = false;
while (breaks[i] > breaks[i - 1] + 1) {
// try moving the break to the left
s1.increase(pt[breaks[i] - 1], pt[breaks[i] - 2], -1);
s2.increase(pt[breaks[i] - 1], pt[breaks[i] - 2], 1);
double newcost = s1.det() * s1.det() + s2.det() * s2.det();
if (newcost >= cost) {
break;
}
improved = true;
cost = newcost;
breaks[i]--;
ss[i - 1] = s1;
ss[i] = s2;
}
if (improved) {
continue;
}
s1 = ss[i - 1];
s2 = ss[i];
while (breaks[i] < breaks[i + 1] - 1) {
// try moving the break to the right
s1.increase(pt[breaks[i]], pt[breaks[i] + 1], 1);
s2.increase(pt[breaks[i]], pt[breaks[i] + 1], -1);
double newcost = s1.det() * s1.det() + s2.det() * s2.det();
if (newcost >= cost) {
break;
}
cost = newcost;
breaks[i]++;
ss[i - 1] = s1;
ss[i] = s2;
}
}
}
/**
* Determine if a particular stroke is large enough as to make a shape out of it
*/
auto ShapeRecognizer::isStrokeLargeEnough(Stroke* stroke, double strokeMinSize) -> bool {
if (stroke->getPointCount() < 3) {
return false;
}
auto rect = stroke->getSnappedBounds();
return std::hypot(rect.width, rect.height) >= strokeMinSize;
}
/**
* The main pattern recognition function
*/
auto ShapeRecognizer::recognizePatterns(Stroke* stroke, double strokeMinSize) -> std::unique_ptr<Stroke> {
this->stroke = stroke;
if (!isStrokeLargeEnough(stroke, strokeMinSize)) {
return nullptr;
}
Inertia ss[4];
int brk[5] = {0};
// first see if it's a polygon
int n = findPolygonal(stroke->getPoints(), 0, static_cast<int>(stroke->getPointCount()) - 1, MAX_POLYGON_SIDES, brk,
ss);
if (n > 0) {
optimizePolygonal(stroke->getPoints(), n, brk, ss);
#ifdef DEBUG_RECOGNIZER
g_message("--");
g_message("ShapeReco:: Polygon, %d edges:", n);
for (int i = 0; i < n; i++) {
g_message("ShapeReco:: %d-%d (M=%.0f, det=%.4f)", brk[i], brk[i + 1], ss[i].getMass(), ss[i].det());
}
g_message("--");
#endif
// update recognizer segment queue (most recent at end)
while (n + queueLength > MAX_POLYGON_SIDES) {
// remove oldest polygonal stroke
int i = 1;
while (i < queueLength && queue[as_unsigned(i)].startpt != 0) {
i++;
}
queueLength -= i;
std::move(std::next(begin(queue), i), std::next(begin(queue), i + queueLength), begin(queue));
}
RDEBUG("Queue now has %i + %i edges", this->queueLength, n);
RecoSegment* rs = &this->queue[as_unsigned(this->queueLength)];
this->queueLength += n;
for (int i = 0; i < n; i++) {
rs[i].startpt = brk[i];
rs[i].endpt = brk[i + 1];
rs[i].calcSegmentGeometry(stroke->getPoints(), brk[i], brk[i + 1], ss + i);
}
if (auto result = tryRectangle(); result != nullptr) {
RDEBUG("return rectangle");
return result;
}
// Removed complicated recognition in commit 5494bd002050182cde3af70bd1924f4062579be5
if (n == 1 && ss->det() < LINE_MAX_DET) // current stroke is a line
{
bool aligned = true;
if (fabs(rs->angle) < SLANT_TOLERANCE) // nearly horizontal
{
rs->angle = 0.0;
rs->y1 = rs->y2 = rs->ycenter;
} else if (fabs(rs->angle) > M_PI / 2 - SLANT_TOLERANCE) { // nearly vertical
rs->angle = (rs->angle > 0) ? (M_PI / 2) : (-M_PI / 2);
rs->x1 = rs->x2 = rs->xcenter;
} else {
aligned = false;
}
auto s = std::make_unique<Stroke>();
s->applyStyleFrom(this->stroke);
if (aligned) {
s->addPoint(Point(rs->x1, rs->y1));
s->addPoint(Point(rs->x2, rs->y2));
} else {
auto points = stroke->getPointVector();
s->addPoint(Point(points.front().x, points.front().y));
s->addPoint(Point(points.back().x, points.back().y));
}
RDEBUG("return line");
return s;
}
}
// not a polygon: maybe a circle ?
auto s = CircleRecognizer::recognize(stroke);
if (s) {
RDEBUG("return circle");
return s;
}
return nullptr;
}
| 10,371
|
C++
|
.cpp
| 299
| 26.438127
| 120
| 0.504143
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,505
|
PageTypeHandler.cpp
|
xournalpp_xournalpp/src/core/control/pagetype/PageTypeHandler.cpp
|
#include "PageTypeHandler.h"
#include <algorithm>
#include <utility>
#include "gui/GladeSearchpath.h"
#include "util/XojMsgBox.h"
#include "util/i18n.h"
static void addPageTypeInfo(const std::string& name, PageTypeFormat format, const std::string& config,
std::vector<std::unique_ptr<PageTypeInfo>>& types) {
auto pt = std::make_unique<PageTypeInfo>();
pt->name = std::move(name);
pt->page.format = format;
pt->page.config = std::move(config);
types.emplace_back(std::move(pt));
}
PageTypeHandler::PageTypeHandler(GladeSearchpath* gladeSearchPath) {
auto file = gladeSearchPath->findFile("", "pagetemplates.ini");
if (!parseIni(file) || this->types.size() < 5) {
std::string msg = FS(_F("Could not load pagetemplates.ini file"));
XojMsgBox::showErrorToUser(nullptr, msg);
// On failure load the hardcoded and predefined values
addPageTypeInfo(_("Plain"), PageTypeFormat::Plain, "", types);
addPageTypeInfo(_("Ruled"), PageTypeFormat::Ruled, "", types);
addPageTypeInfo(_("Ruled with vertical line"), PageTypeFormat::Lined, "", types);
addPageTypeInfo(_("Staves"), PageTypeFormat::Staves, "", types);
addPageTypeInfo(_("Graph"), PageTypeFormat::Graph, "", types);
addPageTypeInfo(_("Dotted"), PageTypeFormat::Dotted, "", types);
addPageTypeInfo(_("Isometric Dotted"), PageTypeFormat::IsoDotted, "", types);
addPageTypeInfo(_("Isometric Graph"), PageTypeFormat::IsoGraph, "", types);
}
// Special types
addPageTypeInfo(_("With PDF background"), PageTypeFormat::Pdf, "", specialTypes);
addPageTypeInfo(_("Image"), PageTypeFormat::Image, "", specialTypes);
}
PageTypeHandler::~PageTypeHandler() = default;
auto PageTypeHandler::parseIni(fs::path const& filepath) -> 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++) { loadFormat(config, groups[i]); }
g_strfreev(groups);
g_key_file_free(config);
return true;
}
void PageTypeHandler::loadFormat(GKeyFile* config, const char* group) {
std::string strName;
gchar* name = g_key_file_get_locale_string(config, group, "name", nullptr, nullptr);
if (name != nullptr) {
strName = name;
g_free(name);
}
std::string strFormat;
gchar* format = g_key_file_get_string(config, group, "format", nullptr);
if (format != nullptr) {
strFormat = format;
g_free(format);
}
std::string strConfig;
gchar* cconfig = g_key_file_get_string(config, group, "config", nullptr);
if (cconfig != nullptr) {
strConfig = cconfig;
g_free(cconfig);
}
addPageTypeInfo(strName, getPageTypeFormatForString(strFormat), strConfig, types);
}
auto PageTypeHandler::getPageTypes() -> const std::vector<std::unique_ptr<PageTypeInfo>>& { return this->types; }
auto PageTypeHandler::getSpecialPageTypes() -> const std::vector<std::unique_ptr<PageTypeInfo>>& {
return this->specialTypes;
}
auto PageTypeHandler::getInfoOn(const PageType& pt) const -> const PageTypeInfo* {
const auto& vector = pt.isSpecial() ? specialTypes : types;
auto it = std::find_if(vector.begin(), vector.end(), [&](const auto& info) { return info->page == pt; });
return it == vector.end() ? nullptr : it->get();
}
auto PageTypeHandler::getPageTypeFormatForString(const std::string& format) -> PageTypeFormat {
if (format == "plain") {
return PageTypeFormat::Plain;
}
if (format == "ruled") {
return PageTypeFormat::Ruled;
}
if (format == "lined") {
return PageTypeFormat::Lined;
}
if (format == "staves") {
return PageTypeFormat::Staves;
}
if (format == "graph") {
return PageTypeFormat::Graph;
}
if (format == "dotted") {
return PageTypeFormat::Dotted;
}
if (format == "isodotted") {
return PageTypeFormat::IsoDotted;
}
if (format == "isograph") {
return PageTypeFormat::IsoGraph;
}
if (format == ":pdf") {
return PageTypeFormat::Pdf;
}
if (format == ":image") {
return PageTypeFormat::Image;
}
g_warning("PageTypeHandler::getPageTypeFormatForString: unknown PageType: \"%s\". Replacing with "
"PageTypeFormat::Plain",
format.c_str());
return PageTypeFormat::Plain;
}
auto PageTypeHandler::getStringForPageTypeFormat(const PageTypeFormat& format) -> std::string {
switch (format) {
case PageTypeFormat::Plain:
return "plain";
case PageTypeFormat::Ruled:
return "ruled";
case PageTypeFormat::Lined:
return "lined";
case PageTypeFormat::Staves:
return "staves";
case PageTypeFormat::Graph:
return "graph";
case PageTypeFormat::Dotted:
return "dotted";
case PageTypeFormat::IsoDotted:
return "isodotted";
case PageTypeFormat::IsoGraph:
return "isograph";
case PageTypeFormat::Pdf:
return ":pdf";
case PageTypeFormat::Image:
return ":image";
}
g_warning("PageTypeHandler::getStringForPageTypeFormat: unknown PageType: %d. Replacing with "
"PageTypeFormat::Ruled",
static_cast<int>(format));
return "ruled";
}
| 5,661
|
C++
|
.cpp
| 142
| 33.274648
| 113
| 0.642714
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,506
|
ZoomControl.cpp
|
xournalpp_xournalpp/src/core/control/zoom/ZoomControl.cpp
|
#include "ZoomControl.h"
#include <algorithm> // for find, max
#include <glib-object.h> // for G_CALLBACK, g_signal_connect
#include <glib.h> // for g_warning, guint
#include "control/Control.h" // for Control
#include "control/actions/ActionDatabase.h"
#include "control/settings/Settings.h" // for Settings
#include "control/zoom/ZoomListener.h" // for ZoomListener
#include "gui/Layout.h" // for Layout
#include "gui/PageView.h" // for XojPageView
#include "gui/XournalView.h" // for XournalView
#include "gui/widgets/XournalWidget.h" // for gtk_xournal_get_layout
#include "util/Assert.h" // for xoj_assert
#include "util/Util.h" // for execInUiThread
#include "util/gdk4_helper.h" // for gdk_event_get_modifier_state
#include "util/glib_casts.h" // for wrap_for_g_callback
using xoj::util::Rectangle;
auto onScrolledwindowMainScrollEvent(GtkWidget* widget, GdkEventScroll* event, ZoomControl* zoom) -> bool {
auto state =
gdk_event_get_modifier_state(reinterpret_cast<GdkEvent*>(event)) & gtk_accelerator_get_default_mod_mask();
// do not handle e.g. ALT + Scroll (e.g. Compiz use this shortcut for setting transparency...)
if (state & ~(GDK_CONTROL_MASK | GDK_SHIFT_MASK)) {
return true;
}
if (state & GDK_CONTROL_MASK) {
auto direction =
(event->direction == GDK_SCROLL_UP || (event->direction == GDK_SCROLL_SMOOTH && event->delta_y < 0)) ?
ZOOM_IN :
ZOOM_OUT;
// translate absolute window coordinates to the widget-local coordinates and start zooming
zoom->zoomScroll(direction, Util::toWidgetCoords(widget, xoj::util::Point{event->x_root, event->y_root}));
return true;
}
// TODO(unknown): Disabling scroll here is maybe a bit hacky find a better way
return zoom->isZoomPresentationMode();
}
auto onTouchpadPinchEvent(GtkWidget* widget, GdkEventTouchpadPinch* event, ZoomControl* zoom) -> bool {
if (event->type == GDK_TOUCHPAD_PINCH && event->n_fingers == 2) {
switch (event->phase) {
case GDK_TOUCHPAD_GESTURE_PHASE_BEGIN:
if (zoom->isZoomFitMode()) {
zoom->setZoomFitMode(false);
}
// translate absolute window coordinates to the widget-local coordinates and start zooming
zoom->startZoomSequence(Util::toWidgetCoords(widget, xoj::util::Point{event->x_root, event->y_root}));
break;
case GDK_TOUCHPAD_GESTURE_PHASE_UPDATE:
zoom->zoomSequenceChange(event->scale, true);
break;
case GDK_TOUCHPAD_GESTURE_PHASE_END:
zoom->endZoomSequence();
break;
case GDK_TOUCHPAD_GESTURE_PHASE_CANCEL:
zoom->cancelZoomSequence();
break;
}
return true;
}
return false;
}
// Todo: try to connect this function with the "expose_event", it would be way cleaner and we dont need to align/layout
// the pages manually, but it only works with the top Widget (GtkWindow) for now this works "fine"
// see https://stackoverflow.com/questions/1060039/gtk-detecting-window-resize-from-the-user
auto onWindowSizeChangedEvent(GtkWidget* widget, GdkEvent* event, ZoomControl* zoom) -> bool {
xoj_assert(widget != zoom->view->getWidget());
auto layout = gtk_xournal_get_layout(zoom->view->getWidget());
// Todo (fabian): The following code is a hack.
// Problem size-allocate:
// when using the size-allocate signal, we cant use layout->recalculate() directly.
// But using the xournal-widgets allocation is wrong, since the calculation is skipped already.
// using size-allocate's allocation is wrong, since it is the alloc of the toplevel.
// Problem expose-event:
// when using the expose-event signal, the new Allocation is not known yet; calculation must be deferred.
// (minimize / maximize wont work)
Util::execInUiThread([layout, zoom]() {
zoom->updateZoomPresentationValue();
zoom->updateZoomFitValue();
layout->recalculate();
});
return false;
}
auto ZoomControl::withZoomStep(ZoomDirection direction, double zoomStep) const -> double {
double multiplier = 1.0 + zoomStep;
double newZoom;
if (direction == ZOOM_IN) {
newZoom = this->zoom * multiplier;
} else {
newZoom = this->zoom / multiplier;
}
return newZoom;
}
void ZoomControl::zoomOneStep(ZoomDirection direction, xoj::util::Point<double> zoomCenter) {
if (this->zoomPresentationMode) {
return;
}
this->setZoomFitMode(false);
double newZoom = this->withZoomStep(direction, this->zoomStep);
startZoomSequence(zoomCenter);
this->zoomSequenceChange(newZoom, false);
endZoomSequence();
}
void ZoomControl::zoomOneStep(ZoomDirection direction) {
Rectangle rect = getVisibleRect();
zoomOneStep(direction, {rect.width / 2.0, rect.height / 2.0});
}
void ZoomControl::zoomScroll(ZoomDirection direction, xoj::util::Point<double> zoomCenter) {
if (this->zoomPresentationMode) {
return;
}
if (this->isZoomFitMode()) {
this->setZoomFitMode(false);
}
double newZoom = this->withZoomStep(direction, this->zoomStepScroll);
startZoomSequence(zoomCenter);
this->zoomSequenceChange(newZoom, false);
endZoomSequence();
}
void ZoomControl::startZoomSequence() {
Rectangle rect = getVisibleRect();
startZoomSequence({rect.width / 2.0, rect.height / 2.0});
}
void ZoomControl::startZoomSequence(xoj::util::Point<double> zoomCenter) {
// * set zoom center and zoom startlevel
this->zoomWidgetPos = zoomCenter; // widget space coordinates of the zoomCenter!
this->zoomSequenceStart = this->zoom;
// * set unscaledPixels padding value
size_t currentPageIdx = this->view->getCurrentPage();
// To get the layout, we need to call view->getWidget(), which isn't const.
// As such, we get the view and determine `unscaledPixels` here, rather than
// in `getScrollPositionAfterZoom`.
GtkWidget* widget = view->getWidget();
Layout* layout = gtk_xournal_get_layout(widget);
// Not everything changes size as we zoom in/out. The padding, for example,
// remains constant! (changed when page changes, but the error stays small enough)
this->unscaledPixels = {static_cast<double>(layout->getPaddingLeftOfPage(currentPageIdx)),
static_cast<double>(layout->getPaddingAbovePage(currentPageIdx))};
// * set initial scrollPosition value
auto const& rect = getVisibleRect();
auto const& view_pos = xoj::util::Point{rect.x, rect.y};
// Use this->zoomWidgetPos to zoom into a location other than the top-left (e.g. where
// the user pinched).
this->scrollPosition = (view_pos + this->zoomWidgetPos - this->unscaledPixels) / this->zoom;
}
void ZoomControl::zoomSequenceChange(double zoom, bool relative) {
if (relative) {
if (isZoomSequenceActive()) {
zoom *= zoomSequenceStart;
} else {
zoom *= this->zoom;
}
}
setZoom(zoom);
}
void ZoomControl::zoomSequenceChange(double zoom, bool relative, xoj::util::Point<double> scrollVector) {
if (relative) {
if (isZoomSequenceActive()) {
zoom *= zoomSequenceStart;
} else {
zoom *= this->zoom;
}
}
// scroll update
this->zoomWidgetPos += scrollVector;
setZoom(zoom);
}
void ZoomControl::endZoomSequence() {
scrollPosition = {-1, -1};
zoomSequenceStart = -1;
}
void ZoomControl::cancelZoomSequence() {
if (isZoomSequenceActive()) {
setZoom(zoomSequenceStart);
endZoomSequence();
}
}
auto ZoomControl::isZoomSequenceActive() const -> bool { return zoomSequenceStart != -1; }
auto ZoomControl::getVisibleRect() -> Rectangle<double> {
GtkWidget* widget = view->getWidget();
Layout* layout = gtk_xournal_get_layout(widget);
return layout->getVisibleRect();
}
auto ZoomControl::getScrollPositionAfterZoom() const -> xoj::util::Point<double> {
// If we aren't in a zoomSequence, `unscaledPixels`, `scrollPosition`, and `zoomWidgetPos
// can't be used to determine the scroll position! Return now.
// NOTE: this case should never happen currently.
// getScrollPositionAfterZoom is called from XournalView after setZoom() fired the ZoomListeners
if (!this->isZoomSequenceActive()) {
xoj_assert_message(false, "ZoomControl::getScrollPositionAfterZoom() was called outside of a zoom sequence.");
return {0, 0};
}
return this->scrollPosition * this->zoom - this->zoomWidgetPos + this->unscaledPixels;
}
void ZoomControl::addZoomListener(ZoomListener* l) { this->listener.emplace_back(l); }
void ZoomControl::removeZoomListener(ZoomListener* l) {
if (auto it = std::find(this->listener.begin(), this->listener.end(), l); it != this->listener.end()) {
this->listener.erase(it);
}
}
void ZoomControl::initZoomHandler(GtkWidget* window, GtkWidget* widget, XournalView* v, Control* c) {
this->control = c;
this->view = v;
gtk_widget_add_events(widget, GDK_TOUCHPAD_GESTURE_MASK);
g_signal_connect(widget, "scroll-event", xoj::util::wrap_for_g_callback_v<onScrolledwindowMainScrollEvent>, this);
g_signal_connect(widget, "event", xoj::util::wrap_for_g_callback_v<onTouchpadPinchEvent>, this);
g_signal_connect(window, "configure-event", xoj::util::wrap_for_g_callback_v<onWindowSizeChangedEvent>, this);
registerListener(this->control);
}
void ZoomControl::fireZoomChanged() {
for (ZoomListener* z: this->listener) {
z->zoomChanged();
}
}
void ZoomControl::fireZoomRangeValueChanged() {
for (ZoomListener* z: this->listener) {
z->zoomRangeValuesChanged();
}
}
auto ZoomControl::getZoom() const -> double { return this->zoom; }
auto ZoomControl::getZoomReal() const -> double { return this->zoom / this->zoom100Value; }
void ZoomControl::setZoom(double zoomI) {
zoomI = std::clamp(zoomI, this->zoomMin, this->zoomMax);
if (this->zoom == zoomI) {
return;
}
this->zoom = zoomI;
this->control->getActionDatabase()->setActionState(Action::ZOOM, getZoomReal());
fireZoomChanged();
}
void ZoomControl::setZoom100Value(double zoom100Val) {
auto setWithRelZoom = [zoomOld = this->zoom100Value, zoom100Val](double& val) { val = val / zoomOld * zoom100Val; };
setWithRelZoom(this->zoomMax);
setWithRelZoom(this->zoomMin);
this->zoom100Value = zoom100Val;
fireZoomRangeValueChanged();
}
auto ZoomControl::updateZoomFitValue(size_t pageNo) -> bool {
if (pageNo == 0) {
pageNo = view->getCurrentPage();
}
XojPageView* page = view->getViewFor(pageNo);
if (!page) { // no page
return false;
}
Rectangle widget_rect = getVisibleRect();
double zoom_fit_width = widget_rect.width / (page->getWidth() + 20.0);
this->zoomFitValue = std::clamp(zoom_fit_width, this->zoomMin, this->zoomMax);
fireZoomRangeValueChanged();
if (this->isZoomFitMode() && !this->zoomPresentationMode) {
this->zoomFit();
}
return true;
}
auto ZoomControl::getZoomFitValue() const -> double { return this->zoomFitValue; }
auto ZoomControl::updateZoomPresentationValue(size_t pageNo) -> bool {
XojPageView* page = view->getViewFor(view->getCurrentPage());
if (!page) {
g_warning("Cannot update zoomPresentationValue yet. This should only happen on startup! ");
return true;
}
Rectangle widget_rect = getVisibleRect();
double zoom_fit_width = widget_rect.width / (page->getWidth() + 14.0);
double zoom_fit_height = widget_rect.height / (page->getHeight() + 14.0);
double zoom_presentation = zoom_fit_width < zoom_fit_height ? zoom_fit_width : zoom_fit_height;
this->zoomPresentationValue = std::clamp(zoom_presentation, this->zoomMin, this->zoomMax);
if (this->zoomPresentationMode) {
this->zoomPresentation();
}
return true;
}
auto ZoomControl::getZoom100Value() const -> double { return this->zoom100Value; }
void ZoomControl::zoom100() {
if (this->zoomPresentationMode) {
return;
}
if (this->zoomFitMode) {
this->setZoomFitMode(false);
}
startZoomSequence();
this->zoomSequenceChange(this->zoom100Value, false);
endZoomSequence();
}
void ZoomControl::zoomFit() {
// TODO: properly fix the zoom fit infinite recursion
if (this->isZoomFittingNow) {
return;
}
this->isZoomFittingNow = true;
if (this->isZoomFitMode() && !this->zoomPresentationMode && this->zoom != this->zoomFitValue) {
startZoomSequence();
this->zoomSequenceChange(this->zoomFitValue, false);
endZoomSequence();
}
this->isZoomFittingNow = false;
}
void ZoomControl::zoomPresentation() {
if (this->zoomPresentationMode && this->zoom != this->zoomPresentationValue) {
startZoomSequence();
this->zoomSequenceChange(this->zoomPresentationValue, false);
endZoomSequence();
}
}
void ZoomControl::setZoomFitMode(bool isZoomFitMode) {
if (this->zoomFitMode != isZoomFitMode) {
this->zoomFitMode = isZoomFitMode;
this->control->getActionDatabase()->setActionState(Action::ZOOM_FIT, this->zoomFitMode);
}
if (this->isZoomFitMode()) {
zoomFit();
}
}
auto ZoomControl::isZoomFitMode() const -> bool {
// Todo(fabian): Remove this fix and make both modes possible in parallel, after fixing the infinite loop.
// Explanation: First of all, zoomFit never worked with paired pages. Also, using both resulted in a stackoverflow
// when different page sizes are used. This is caused by a logical loop.
// We decided to deactivate it in PR#2821 & I#2770. instead of fixing it, to get release 1.1.0 ready.
// Zoom presentation mode is also excluded, because it was never intended to work together.
// It is also excluded everywhere else (duplicate code).
auto infiniteLoopFixup = !this->zoomPresentationMode && !this->control->getSettings()->isShowPairedPages();
return this->zoomFitMode && infiniteLoopFixup;
}
void ZoomControl::setZoomPresentationMode(bool isZoomPresentationMode) {
this->zoomPresentationMode = isZoomPresentationMode;
if (isZoomPresentationMode) {
zoomPresentation();
}
}
auto ZoomControl::isZoomPresentationMode() const -> bool { return this->zoomPresentationMode; }
void ZoomControl::setZoomStep(double zoomStep) { this->zoomStep = zoomStep; }
void ZoomControl::setZoomStepScroll(double zoomStep) { this->zoomStepScroll = zoomStep; }
void ZoomControl::pageSizeChanged(size_t page) {
updateZoomPresentationValue(page);
updateZoomFitValue(page);
}
void ZoomControl::pageSelected(size_t page) {
// Todo (fabian): page selected should do nothing here, since Zoom Controls, which page is selected.
// This results in a logical loop. See PR#2821 & I#2770
if (current_page != page) {
this->last_page = this->current_page;
this->current_page = page;
}
updateZoomPresentationValue(this->current_page);
if (view->isPageVisible(this->last_page, nullptr)) {
return;
}
updateZoomFitValue(this->current_page);
}
| 15,565
|
C++
|
.cpp
| 346
| 39.367052
| 120
| 0.681809
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,507
|
AutosaveJob.cpp
|
xournalpp_xournalpp/src/core/control/jobs/AutosaveJob.cpp
|
#include "AutosaveJob.h"
#include <glib.h> // for g_message, g_warning
#include "control/Control.h" // for Control
#include "control/jobs/Job.h" // for JOB_TYPE_AUTOSAVE, JobType
#include "control/xojfile/SaveHandler.h" // for SaveHandler
#include "model/Document.h" // for Document
#include "undo/UndoRedoHandler.h" // for UndoRedoHandler
#include "util/PathUtil.h" // for clearExtensions, getAutosav...
#include "util/XojMsgBox.h" // for XojMsgBox
#include "util/i18n.h" // for FS, _F
#include "filesystem.h" // for path, u8path
AutosaveJob::AutosaveJob(Control* control): control(control) {}
AutosaveJob::~AutosaveJob() = default;
void AutosaveJob::afterRun() {
std::string msg = FS(_F("Error while autosaving: {1}") % this->error);
XojMsgBox::showErrorToUser(control->getGtkWindow(), msg);
}
void AutosaveJob::run() {
SaveHandler handler;
control->getUndoRedoHandler()->documentAutosaved();
Document* doc = control->getDocument();
doc->lock();
handler.prepareSave(doc);
auto filepath = doc->getFilepath();
doc->unlock();
if (filepath.empty()) {
filepath = Util::getAutosaveFilepath();
} else {
filepath.replace_filename(fs::u8path(u8"." + filepath.filename().u8string()));
}
Util::clearExtensions(filepath);
filepath += ".autosave.xopp";
g_message("%s", FS(_F("Autosaving to {1}") % filepath.string()).c_str());
fs::path tempfile = filepath;
tempfile += u8"~";
handler.saveTo(tempfile);
this->error = handler.getErrorMessage();
if (!this->error.empty()) {
callAfterRun();
} else {
try {
if (fs::exists(filepath)) {
fs::path swaptmpfile = filepath;
swaptmpfile += u8".swap";
Util::safeRenameFile(filepath, swaptmpfile);
Util::safeRenameFile(tempfile, filepath);
// All went well, we can delete the old autosave file
fs::remove(swaptmpfile);
} else {
Util::safeRenameFile(tempfile, filepath);
}
control->setLastAutosaveFile(filepath);
} catch (const fs::filesystem_error& e) {
auto fmtstr = _F("Could not rename autosave file from \"{1}\" to \"{2}\": {3}");
this->error = FS(fmtstr % tempfile.u8string() % filepath.u8string() % e.what());
}
}
}
auto AutosaveJob::getType() -> JobType { return JOB_TYPE_AUTOSAVE; }
| 2,549
|
C++
|
.cpp
| 59
| 36.525424
| 92
| 0.608485
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,508
|
SaveJob.cpp
|
xournalpp_xournalpp/src/core/control/jobs/SaveJob.cpp
|
#include "SaveJob.h"
#include <memory> // for __shared_ptr_access
#include <cairo.h> // for cairo_create, cairo_destroy
#include <glib.h> // for g_warning, g_error
#include "control/Control.h" // for Control
#include "control/jobs/BlockingJob.h" // for BlockingJob
#include "control/xojfile/SaveHandler.h" // for SaveHandler
#include "model/Document.h" // for Document
#include "model/PageRef.h" // for PageRef
#include "model/PageType.h" // for PageType
#include "model/XojPage.h" // for XojPage
#include "pdf/base/XojPdfPage.h" // for XojPdfPageSPtr, XojPdfPage
#include "util/PathUtil.h" // for clearExtensions, safeRename...
#include "util/XojMsgBox.h" // for XojMsgBox
#include "util/i18n.h" // for FS, _, _F
#include "view/DocumentView.h" // for DocumentView
#include "filesystem.h" // for path, filesystem_error, remove
SaveJob::SaveJob(Control* control, std::function<void(bool)> callback):
BlockingJob(control, _("Save")), callback(std::move(callback)) {}
SaveJob::~SaveJob() = default;
void SaveJob::run() {
save();
if (this->control->getWindow()) {
callAfterRun();
}
}
void SaveJob::afterRun() {
if (!this->lastError.empty()) {
XojMsgBox::showErrorToUser(control->getGtkWindow(), this->lastError);
callback(false);
} else {
this->control->resetSavedStatus();
callback(true);
}
}
void SaveJob::updatePreview(Control* control) {
const int previewSize = 128;
Document* doc = control->getDocument();
doc->lock();
if (doc->getPageCount() > 0) {
PageRef page = doc->getPage(0);
double width = page->getWidth();
double height = page->getHeight();
double zoom = 1;
if (width < height) {
zoom = previewSize / height;
} else {
zoom = previewSize / width;
}
width *= zoom;
height *= zoom;
cairo_surface_t* crBuffer =
cairo_image_surface_create(CAIRO_FORMAT_ARGB32, ceil_cast<int>(width), ceil_cast<int>(height));
cairo_t* cr = cairo_create(crBuffer);
cairo_scale(cr, zoom, zoom);
xoj::view::BackgroundFlags flags = xoj::view::BACKGROUND_SHOW_ALL;
// We don't have access to a PdfCache on which DocumentView relies for PDF backgrounds.
// We thus print the PDF background by hand.
if (page->getBackgroundType().isPdfPage()) {
auto pgNo = page->getPdfPageNr();
XojPdfPageSPtr popplerPage = doc->getPdfPage(pgNo);
if (popplerPage) {
popplerPage->render(cr);
}
flags.showPDF = xoj::view::HIDE_PDF_BACKGROUND; // Already printed (if any)
} else {
flags.forceBackgroundColor = xoj::view::FORCE_AT_LEAST_BACKGROUND_COLOR;
}
DocumentView view;
view.drawPage(page, cr, true /* don't render erasable */, flags);
cairo_destroy(cr);
doc->setPreview(crBuffer);
cairo_surface_destroy(crBuffer);
} else {
doc->setPreview(nullptr);
}
doc->unlock();
}
auto SaveJob::save() -> bool {
updatePreview(control);
Document* doc = this->control->getDocument();
SaveHandler h;
doc->lock();
h.prepareSave(doc);
fs::path filepath = doc->getFilepath();
doc->unlock();
Util::clearExtensions(filepath, ".pdf");
auto const target = fs::path{filepath}.concat(".xopp");
auto const createBackup = doc->shouldCreateBackupOnSave();
if (createBackup) {
try {
// Note: The backup must be created for the target as this is the filepath
// which will be written to. Do not use the `filepath` variable!
Util::safeRenameFile(target, fs::path{target} += "~");
} catch (const fs::filesystem_error& fe) {
g_warning("Could not create backup! Failed with %s", fe.what());
this->lastError = FS(_F("Save file error, can't backup: {1}") % std::string(fe.what()));
if (!control->getWindow()) {
g_error("%s", this->lastError.c_str());
}
return false;
}
}
doc->lock();
h.saveTo(target, this->control);
doc->setFilepath(target);
doc->unlock();
if (!h.getErrorMessage().empty()) {
this->lastError = FS(_F("Save file error: {1}") % h.getErrorMessage());
if (!control->getWindow()) {
g_error("%s", this->lastError.c_str());
}
return false;
} else if (createBackup) {
try {
// If a backup was created it can be removed now since no error occured during the save
fs::remove(fs::path{target} += "~");
} catch (const fs::filesystem_error& fe) {
g_warning("Could not delete backup! Failed with %s", fe.what());
}
} else {
doc->setCreateBackupOnSave(true);
}
return true;
}
| 5,042
|
C++
|
.cpp
| 125
| 33.08
| 111
| 0.593616
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,509
|
Job.cpp
|
xournalpp_xournalpp/src/core/control/jobs/Job.cpp
|
#include "Job.h"
#include <gdk/gdk.h> // for gdk_threads_add_idle
#include <glib.h> // for g_source_remove
#include "util/glib_casts.h" // for wrap_for_once_v
Job::Job(): refCount(1) {}
Job::~Job() = default;
void Job::unref() {
if (refCount.fetch_sub(1, std::memory_order_acq_rel) == 1) {
delete this;
}
}
void Job::ref() {
refCount.fetch_add(1, std::memory_order_relaxed);
}
void Job::deleteJob() {
this->onDelete();
if (this->afterRunId) {
g_source_remove(this->afterRunId);
this->unref();
}
}
void Job::onDelete() {}
void Job::execute() { this->run(); }
auto Job::getSource() -> void* { return nullptr; }
auto Job::callAfterCallback(Job* job) -> bool {
job->afterRun();
job->afterRunId = 0;
job->unref();
return false; // do not call again
}
void Job::callAfterRun() {
if (this->afterRunId) {
return;
}
this->ref();
this->afterRunId = gdk_threads_add_idle(xoj::util::wrap_for_once_v<Job::callAfterCallback>, this);
}
void Job::afterRun() {}
| 1,057
|
C++
|
.cpp
| 38
| 24.052632
| 102
| 0.623752
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,510
|
CustomExportJob.cpp
|
xournalpp_xournalpp/src/core/control/jobs/CustomExportJob.cpp
|
#include "CustomExportJob.h"
#include <memory> // for unique_ptr
#include <utility> // for move, pair
#include <gtk/gtk.h> // for GTK_WINDOW
#include "control/Control.h" // for Control
#include "control/jobs/BaseExportJob.h" // for BaseExportJob::ExportType
#include "control/xojfile/XojExportHandler.h" // for XojExportHandler
#include "gui/MainWindow.h" // for MainWindow
#include "gui/dialog/ExportDialog.h" // for ExportDialog
#include "model/Document.h" // for Document
#include "pdf/base/XojPdfExport.h" // for XojPdfExport
#include "pdf/base/XojPdfExportFactory.h" // for XojPdfExportFactory
#include "util/PathUtil.h" // for clearExtensions
#include "util/PopupWindowWrapper.h" // for PopupWindowWrapper
#include "util/Util.h" // for execInUiThread
#include "util/XojMsgBox.h" // for XojMsgBox
#include "util/i18n.h" // for _, FS, _F
#include "ImageExport.h" // for ImageExport, EXPORT_GR...
#include "SaveJob.h" // for SaveJob
#include "XournalScheduler.h"
CustomExportJob::CustomExportJob(Control* control): BaseExportJob(control, _("Custom Export")) {
// Supported filters
filters.insert({_("PDF files"), ExportType(".pdf", "application/pdf")});
filters.insert({_("PNG graphics"), ExportType(".png", "image/png")});
filters.insert({_("SVG graphics"), ExportType(".svg", "image/svg+xml")});
filters.insert({_("Xournal (Compatibility)"), ExportType(".xoj", "application/x-xojpp")});
}
CustomExportJob::~CustomExportJob() = default;
void CustomExportJob::addFilterToDialog(GtkFileChooser* dialog) {
// Runs on every filter inside the filters map
for (auto& filter: filters) {
addFileFilterToDialog(dialog, filter.first, filter.second.mimeType);
}
}
auto CustomExportJob::testAndSetFilepath(const fs::path& file, const char* filterName) -> bool {
if (!BaseExportJob::testAndSetFilepath(std::move(file))) {
return false;
}
// Extract the file filter selected
const auto& chosenFilter = filters.at(filterName);
// Remove any pre-existing extension and adds the chosen one
Util::clearExtensions(filepath, chosenFilter.extension);
filepath += chosenFilter.extension;
return checkOverwriteBackgroundPDF(filepath);
}
void CustomExportJob::showDialogAndRun() {
auto onFileSelected = [job = this]() {
if (job->filepath.extension() == ".xoj") {
job->exportTypeXoj = true;
job->control->getScheduler()->addJob(job, JOB_PRIORITY_NONE);
return;
}
if (auto ext = job->filepath.extension(); ext == ".pdf") {
job->format = EXPORT_GRAPHICS_PDF;
} else if (ext == ".svg") {
job->format = EXPORT_GRAPHICS_SVG;
} else if (ext == ".png") {
job->format = EXPORT_GRAPHICS_PNG;
} else {
g_warning("Unknown extension");
}
xoj::popup::PopupWindowWrapper<xoj::popup::ExportDialog> popup(
job->control->getGladeSearchPath(), job->format, job->control->getCurrentPageNo() + 1,
job->control->getDocument()->getPageCount(), [job](const xoj::popup::ExportDialog& dialog) {
if (dialog.isConfirmed()) {
job->exportRange = dialog.getRange();
job->progressiveMode = dialog.progressiveModeSelected();
job->exportBackground = dialog.getBackgroundType();
if (job->format == EXPORT_GRAPHICS_PNG) {
job->pngQualityParameter = dialog.getPngQualityParameter();
}
job->control->getScheduler()->addJob(job, JOB_PRIORITY_NONE);
} else {
// The job blocked, so we have to unblock, because the job
// unblocks only after run
job->control->unblock();
}
job->unref();
});
popup.show(GTK_WINDOW(job->control->getWindow()->getWindow()));
};
auto onCancel = [job = this]() {
job->control->unblock();
job->unref();
};
BaseExportJob::showFileChooser(std::move(onFileSelected), std::move(onCancel));
}
/**
* Create one Graphics file per page
*/
void CustomExportJob::exportGraphics() {
ImageExport imgExport(control->getDocument(), filepath, format, exportBackground, exportRange);
if (format == EXPORT_GRAPHICS_PNG) {
imgExport.setQualityParameter(pngQualityParameter);
}
imgExport.exportGraphics(control);
errorMsg = imgExport.getLastErrorMsg();
}
void CustomExportJob::run() {
if (exportTypeXoj) {
SaveJob::updatePreview(control);
Document* doc = this->control->getDocument();
XojExportHandler h;
doc->lock();
h.prepareSave(doc);
h.saveTo(filepath, this->control);
doc->unlock();
if (!h.getErrorMessage().empty()) {
this->lastError = FS(_F("Save file error: {1}") % h.getErrorMessage());
callAfterRun();
}
} else if (format == EXPORT_GRAPHICS_PDF) {
// don't lock the page here for the whole flow, else we get a dead lock...
// the ui is blocked, so there should be no changes...
Document* doc = control->getDocument();
std::unique_ptr<XojPdfExport> pdfe = XojPdfExportFactory::createExport(doc, control);
pdfe->setExportBackground(exportBackground);
if (!pdfe->createPdf(this->filepath, exportRange, progressiveMode)) {
this->errorMsg = pdfe->getLastError();
}
} else {
exportGraphics();
}
}
void CustomExportJob::afterRun() {
if (!this->lastError.empty()) {
XojMsgBox::showErrorToUser(control->getGtkWindow(), this->lastError);
}
}
| 5,995
|
C++
|
.cpp
| 129
| 38.434109
| 108
| 0.613777
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,511
|
Scheduler.cpp
|
xournalpp_xournalpp/src/core/control/jobs/Scheduler.cpp
|
#include "Scheduler.h"
#include <cinttypes> // for PRId64
#include <cstdint> // for uint64_t
#include "control/jobs/Job.h" // for Job, JOB_TYPE_RENDER
#include "util/Assert.h" // for xoj_assert
#include "util/glib_casts.h" // for wrap_for_once_v
#include "config-debug.h" // for DEBUG_SHEDULER
#ifdef DEBUG_SHEDULER
#define SDEBUG g_message
#else
#define SDEBUG(msg, ...)
#endif
Scheduler::Scheduler() {
this->name = "Scheduler";
// Queue
this->jobQueue[JOB_PRIORITY_URGENT] = &this->queueUrgent;
this->jobQueue[JOB_PRIORITY_HIGH] = &this->queueHigh;
this->jobQueue[JOB_PRIORITY_LOW] = &this->queueLow;
this->jobQueue[JOB_PRIORITY_NONE] = &this->queueNone;
}
Scheduler::~Scheduler() {
SDEBUG("Destroy scheduler");
if (this->jobRenderThreadTimerId) {
g_source_remove(this->jobRenderThreadTimerId);
this->jobRenderThreadTimerId = 0;
}
stop();
Job* job = nullptr;
while ((job = getNextJobUnlocked()) != nullptr) { job->unref(); }
if (this->blockRenderZoomTime) {
g_free(this->blockRenderZoomTime);
}
}
void Scheduler::start() {
SDEBUG("Starting scheduler");
g_return_if_fail(this->thread == nullptr);
this->thread = g_thread_new(name.c_str(), reinterpret_cast<GThreadFunc>(jobThreadCallback), this);
}
void Scheduler::stop() {
SDEBUG("Stopping scheduler");
if (!this->threadRunning) {
return;
}
this->threadRunning = false;
this->jobQueueCond.notify_all();
if (this->thread) {
g_thread_join(this->thread);
}
}
void Scheduler::addJob(Job* job, JobPriority priority) {
SDEBUG("Adding job...");
{
std::lock_guard lock{this->jobQueueMutex};
job->ref();
this->jobQueue[priority]->push_back(job);
}
SDEBUG("add job: %" PRId64 "; type: %" PRId64, (uint64_t)job, (uint64_t)job->getType());
this->jobQueueCond.notify_all();
}
auto Scheduler::getNextJobUnlocked(bool onlyNotRender, bool* hasRenderJobs) -> Job* {
Job* job = nullptr;
for (size_t i = JOB_PRIORITY_URGENT; i < JOB_N_PRIORITIES; i++) {
std::deque<Job*>& queue = *this->jobQueue[i];
if (onlyNotRender) {
for (auto it = queue.begin(); it != queue.end(); ++it) {
job = *it;
if (job->getType() != JOB_TYPE_RENDER) {
queue.erase(it);
return job;
}
if (hasRenderJobs != nullptr) {
*hasRenderJobs = true;
}
}
} else if (!queue.empty()) {
job = queue.front();
queue.pop_front();
xoj_assert(job != nullptr);
return job;
}
}
return nullptr;
}
/**
* Locks the complete scheduler
*/
void Scheduler::lock() { this->schedulerMutex.lock(); }
/**
* Unlocks the complete scheduler
*/
void Scheduler::unlock() { this->schedulerMutex.unlock(); }
#define ZOOM_WAIT_US_TIMEOUT 300000 // 0.3s
void Scheduler::blockRerenderZoom() {
std::lock_guard lock{this->blockRenderMutex};
if (this->blockRenderZoomTime == nullptr) {
this->blockRenderZoomTime = g_new(GTimeVal, 1);
}
g_get_current_time(this->blockRenderZoomTime);
g_time_val_add(this->blockRenderZoomTime, ZOOM_WAIT_US_TIMEOUT);
}
void Scheduler::unblockRerenderZoom() {
{
std::lock_guard lock{this->blockRenderMutex};
g_free(this->blockRenderZoomTime);
this->blockRenderZoomTime = nullptr;
if (this->jobRenderThreadTimerId) {
g_source_remove(this->jobRenderThreadTimerId);
this->jobRenderThreadTimerId = 0;
}
}
this->jobQueueCond.notify_all();
}
/**
* g_time_val_diff:
* @t1: time value t1
* @t2: time value t2
*
* Calculates the time difference between t1 and t2 in milliseconds.
* The result is positive if t1 is later than t2.
*
* Returns:
* Time difference in microseconds
*/
auto g_time_val_diff(GTimeVal* t1, GTimeVal* t2) -> glong {
xoj_assert(t1);
xoj_assert(t2);
return ((t1->tv_sec - t2->tv_sec) * G_USEC_PER_SEC + (t1->tv_usec - t2->tv_usec)) / 1000;
}
/**
* If the Scheduler is blocking because we are zooming and there are only render jobs
* we need to wakeup it later
*/
auto Scheduler::jobRenderThreadTimer(Scheduler* scheduler) -> bool {
scheduler->jobRenderThreadTimerId = 0;
{
std::lock_guard lock{scheduler->blockRenderMutex};
g_free(scheduler->blockRenderZoomTime);
scheduler->blockRenderZoomTime = nullptr;
}
scheduler->jobQueueCond.notify_all();
return false;
}
auto Scheduler::jobThreadCallback(Scheduler* scheduler) -> gpointer {
while (scheduler->threadRunning) {
// lock the whole scheduler
std::unique_lock schedulerLock{scheduler->schedulerMutex};
SDEBUG("Job Thread: Blocked scheduler.");
bool onlyNonRenderJobs = false;
glong diff = 1000;
if (scheduler->blockRenderZoomTime) {
std::lock_guard lock{scheduler->blockRenderMutex};
SDEBUG("Zoom re-render blocking.");
GTimeVal time;
g_get_current_time(&time);
diff = g_time_val_diff(scheduler->blockRenderZoomTime, &time);
if (diff <= 0) {
g_free(scheduler->blockRenderZoomTime);
scheduler->blockRenderZoomTime = nullptr;
SDEBUG("Ended zoom re-render blocking.");
} else {
onlyNonRenderJobs = true;
SDEBUG("Rendering blocked: Only running non-rendering jobs.");
}
}
Job* job;
{
std::unique_lock jobLock{scheduler->jobQueueMutex};
SDEBUG("Job Thread: Locked job queue.");
bool hasOnlyRenderJobs = false;
job = scheduler->getNextJobUnlocked(onlyNonRenderJobs, &hasOnlyRenderJobs);
if (job != nullptr) {
hasOnlyRenderJobs = false;
}
SDEBUG("get job: %" PRId64, (uint64_t)job);
if (job == nullptr) {
// unlock the whole scheduler
schedulerLock.unlock();
if (hasOnlyRenderJobs) {
if (scheduler->jobRenderThreadTimerId) {
g_source_remove(scheduler->jobRenderThreadTimerId);
}
scheduler->jobRenderThreadTimerId = g_timeout_add(
static_cast<guint>(diff), xoj::util::wrap_for_once_v<jobRenderThreadTimer>, scheduler);
}
scheduler->jobQueueCond.wait(jobLock);
continue;
}
}
// Run the job.
{
std::lock_guard lock{scheduler->jobRunningMutex};
SDEBUG("do job: %" PRId64, (uint64_t)job);
job->execute();
job->unref();
}
SDEBUG("next");
}
SDEBUG("finished");
return nullptr;
}
| 6,995
|
C++
|
.cpp
| 200
| 27.185
| 115
| 0.603146
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,512
|
BlockingJob.cpp
|
xournalpp_xournalpp/src/core/control/jobs/BlockingJob.cpp
|
#include "BlockingJob.h"
#include <glib.h> // for g_idle_add
#include <gtk/gtk.h> // for gtk_widget_grab_focus
#include "control/Control.h" // for Control
#include "control/jobs/Job.h" // for JOB_TYPE_BLOCKING, JobType
#include "gui/MainWindow.h" // for MainWindow
#include "gui/XournalView.h" // for XournalView
#include "util/Util.h" // for execInUiThread
#include "util/glib_casts.h" // for wrap_for_once_v
BlockingJob::BlockingJob(Control* control, const std::string& name): control(control) { control->block(name); }
BlockingJob::~BlockingJob() { this->control = nullptr; }
void BlockingJob::execute() {
this->run();
g_idle_add(xoj::util::wrap_for_once_v<finished>, this->control);
}
auto BlockingJob::finished(Control* control) -> bool {
// "this" is not needed, "control" is in
// the closure, therefore no sync needed
Util::execInUiThread([=]() {
control->unblock();
XournalView* xournal = control->getWindow()->getXournal();
gtk_widget_grab_focus(xournal->getWidget());
});
// do not call again
return false;
}
auto BlockingJob::getType() -> JobType { return JOB_TYPE_BLOCKING; }
| 1,177
|
C++
|
.cpp
| 27
| 40.185185
| 111
| 0.680982
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,513
|
PdfExportJob.cpp
|
xournalpp_xournalpp/src/core/control/jobs/PdfExportJob.cpp
|
#include "PdfExportJob.h"
#include <memory> // for unique_ptr, allocator
#include <string> // for string
#include <utility> // for move
#include "control/Control.h" // for Control
#include "control/jobs/BaseExportJob.h" // for BaseExportJob
#include "model/Document.h" // for Document
#include "pdf/base/XojPdfExport.h" // for XojPdfExport
#include "pdf/base/XojPdfExportFactory.h" // for XojPdfExportFactory
#include "util/PathUtil.h" // for clearExtensions
#include "util/i18n.h" // for _
PdfExportJob::PdfExportJob(Control* control): BaseExportJob(control, _("PDF Export")) {}
PdfExportJob::~PdfExportJob() = default;
void PdfExportJob::addFilterToDialog(GtkFileChooser* dialog) {
addFileFilterToDialog(dialog, _("PDF files"), "application/pdf");
}
auto PdfExportJob::testAndSetFilepath(const fs::path& file, const char* /*filterName*/) -> bool {
if (!BaseExportJob::testAndSetFilepath(file)) {
return false;
}
// Remove any pre-existing extension and adds .pdf
Util::clearExtensions(filepath, ".pdf");
filepath += ".pdf";
return checkOverwriteBackgroundPDF(filepath);
}
void PdfExportJob::run() {
Document* doc = control->getDocument();
doc->lock();
std::unique_ptr<XojPdfExport> pdfe = XojPdfExportFactory::createExport(doc, control);
doc->unlock();
if (!pdfe->createPdf(this->filepath, false)) {
this->errorMsg = pdfe->getLastError();
if (control->getWindow()) {
callAfterRun();
}
}
}
| 1,581
|
C++
|
.cpp
| 37
| 38.810811
| 97
| 0.671018
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,514
|
ImageExport.cpp
|
xournalpp_xournalpp/src/core/control/jobs/ImageExport.cpp
|
#include "ImageExport.h"
#include <cmath> // for round
#include <cstddef> // for size_t
#include <memory> // for __shared_ptr_access, allocat...
#include <utility> // for move
#include <vector> // for vector
#include <cairo-svg.h> // for cairo_svg_surface_create
#include "control/jobs/BaseExportJob.h" // for EXPORT_BACKGROUND_NONE, EXPO...
#include "model/Document.h" // for Document
#include "model/PageRef.h" // for PageRef
#include "model/PageType.h" // for PageType
#include "model/XojPage.h" // for XojPage
#include "pdf/base/XojPdfPage.h" // for XojPdfPageSPtr, XojPdfPage
#include "util/Util.h" // for DPI_NORMALIZATION_FACTOR
#include "util/i18n.h" // for _
#include "view/DocumentView.h" // for DocumentView
#include "view/LayerView.h"
#include "view/View.h"
#include "view/background/BackgroundView.h"
#include "ProgressListener.h" // for ProgressListener
using std::string;
ImageExport::ImageExport(Document* doc, fs::path file, ExportGraphicsFormat format,
ExportBackgroundType exportBackground, const PageRangeVector& exportRange):
doc(doc), file(std::move(file)), format(format), exportBackground(exportBackground), exportRange(exportRange) {}
ImageExport::~ImageExport() = default;
/**
* @brief Set a quality level for PNG exports
* @param qParam A quality parameter for the export
*/
void ImageExport::setQualityParameter(RasterImageQualityParameter qParam) { this->qualityParameter = qParam; }
/**
* @brief Set a quality level for PNG exports
* @param criterion A quality criterion for the export
* @param value The target value of this criterion
*/
void ImageExport::setQualityParameter(ExportQualityCriterion criterion, int value) {
this->qualityParameter = RasterImageQualityParameter(criterion, value);
}
/**
* @brief Select layers to export by parsing str
* @param rangeStr A string parsed to get a list of layers
*/
void ImageExport::setLayerRange(const char* rangeStr) {
if (rangeStr) {
// Use no upper bound for layer indices, as the maximal value can vary between pages
layerRange =
std::make_unique<LayerRangeVector>(ElementRange::parse(rangeStr, std::numeric_limits<size_t>::max()));
}
}
/**
* @brief Get the last error message
* @return The last error message to show to the user
*/
auto ImageExport::getLastErrorMsg() const -> string { return lastError; }
/**
* @brief Create Cairo surface for a given page
* @param width the width of the page being exported
* @param height the height of the page being exported
* @param id the id of the page being exported
* @param zoomRatio the zoom ratio for PNG exports with fixed DPI
*
* @return the zoom ratio of the current page if the export type is PNG, 0.0 otherwise
* The return value may differ from that of the parameter zoomRatio if the export has fixed page width or
* height (in pixels). In this case, the zoomRatio (and the DPI) is page-dependent as soon as the document has pages of
* different sizes.
*/
auto ImageExport::createSurface(double width, double height, size_t id, double zoomRatio) -> double {
switch (this->format) {
case EXPORT_GRAPHICS_PNG:
switch (this->qualityParameter.getQualityCriterion()) {
case EXPORT_QUALITY_WIDTH:
zoomRatio = ((double)this->qualityParameter.getValue()) / width;
this->surface = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, this->qualityParameter.getValue(),
(int)std::round(height * zoomRatio));
break;
case EXPORT_QUALITY_HEIGHT:
zoomRatio = ((double)this->qualityParameter.getValue()) / height;
this->surface = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, (int)std::round(width * zoomRatio),
this->qualityParameter.getValue());
break;
case EXPORT_QUALITY_DPI: // Use the zoomRatio given as argument
this->surface = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, (int)std::round(width * zoomRatio),
(int)std::round(height * zoomRatio));
break;
}
this->cr = cairo_create(this->surface);
cairo_scale(this->cr, zoomRatio, zoomRatio);
return zoomRatio;
case EXPORT_GRAPHICS_SVG:
this->surface = cairo_svg_surface_create(getFilenameWithNumber(id).u8string().c_str(), width, height);
cairo_svg_surface_restrict_to_version(this->surface, CAIRO_SVG_VERSION_1_2);
this->cr = cairo_create(this->surface);
break;
default:
this->lastError = _("Unsupported graphics format: ") + std::to_string(this->format);
}
return 0.0;
}
/**
* Free / store the surface
*/
auto ImageExport::freeSurface(size_t id) -> bool {
cairo_destroy(this->cr);
cairo_status_t status = CAIRO_STATUS_SUCCESS;
if (format == EXPORT_GRAPHICS_PNG) {
auto filepath = getFilenameWithNumber(id);
status = cairo_surface_write_to_png(surface, filepath.u8string().c_str());
}
cairo_surface_destroy(surface);
// we ignore this problem
return status == CAIRO_STATUS_SUCCESS;
}
/**
* @brief Get a filename with a (page) number appended
* @param no The appended number. If no==-1, does not append anything.
* e.g. .../export-2.png, if the no is -1, return .../export.png
*
* @return The filename
*/
auto ImageExport::getFilenameWithNumber(size_t no) const -> fs::path {
if (no == SINGLE_PAGE) {
// No number to add
return file;
}
auto ext = file.extension();
auto path(file);
path.replace_extension();
(path += (std::string("-") + std::to_string(no))) += ext;
return path;
}
/**
* @brief Export a single PNG/SVG page
* @param pageId The index of the page being exported
* @param id The number of the page being exported
* @param zoomRatio The zoom ratio for PNG exports with fixed DPI
* @param format The format of the exported image
* @param view A DocumentView for drawing the page
*/
void ImageExport::exportImagePage(size_t pageId, size_t id, double zoomRatio, ExportGraphicsFormat format,
DocumentView& view) {
doc->lock();
PageRef page = doc->getPage(pageId);
doc->unlock();
zoomRatio = createSurface(page->getWidth(), page->getHeight(), id, zoomRatio);
cairo_status_t state = cairo_surface_status(this->surface);
if (state != CAIRO_STATUS_SUCCESS) {
this->lastError = _("Error save image #1");
return;
}
if (page->getBackgroundType().isPdfPage() && (exportBackground != EXPORT_BACKGROUND_NONE)) {
// Handle the pdf page separately, to call renderForPrinting for better quality.
auto pgNo = page->getPdfPageNr();
XojPdfPageSPtr popplerPage = doc->getPdfPage(pgNo);
if (!popplerPage) {
this->lastError = _("Error while exporting the pdf background: I cannot find the pdf page number ");
this->lastError += std::to_string(pgNo);
} else if (format == EXPORT_GRAPHICS_PNG) {
popplerPage->render(cr);
} else {
popplerPage->renderForPrinting(cr);
}
}
xoj::view::BackgroundFlags flags;
flags.showPDF = xoj::view::HIDE_PDF_BACKGROUND; // Already exported (if any)
flags.showImage = exportBackground == EXPORT_BACKGROUND_NONE ? xoj::view::HIDE_IMAGE_BACKGROUND :
xoj::view::SHOW_IMAGE_BACKGROUND;
flags.showRuling = exportBackground <= EXPORT_BACKGROUND_UNRULED ? xoj::view::HIDE_RULING_BACKGROUND :
xoj::view::SHOW_RULING_BACKGROUND;
if (layerRange) {
view.drawLayersOfPage(*layerRange, page, this->cr, true /* dont render eraseable */, flags);
} else {
view.drawPage(page, this->cr, true /* dont render eraseable */, flags);
}
if (!freeSurface(id)) {
// could not create this file...
this->lastError = _("Error save image #2");
return;
}
}
/**
* @brief Create one Graphics file per page
* @param stateListener A listener to track the export progress
*/
void ImageExport::exportGraphics(ProgressListener* stateListener) {
// don't lock the page here for the whole flow, else we get a dead lock...
// the ui is blocked, so there should be no changes...
auto count = doc->getPageCount();
bool onePage = ((this->exportRange.size() == 1) && (this->exportRange[0].first == this->exportRange[0].last));
std::vector<char> selectedPages(count, 0);
size_t selectedCount = 0;
for (PageRangeEntry const& e: this->exportRange) {
for (size_t x = e.first; x <= e.last; x++) {
selectedPages[x] = true;
selectedCount++;
}
}
stateListener->setMaximumState(selectedCount);
/*
* Compute the zoomRatio only once if using DPI as a PNG quality criterion
*/
double zoomRatio = 1.0;
if ((this->format == EXPORT_GRAPHICS_PNG) && (this->qualityParameter.getQualityCriterion() == EXPORT_QUALITY_DPI)) {
zoomRatio = ((double)this->qualityParameter.getValue()) / Util::DPI_NORMALIZATION_FACTOR;
}
DocumentView view;
size_t current = 0;
for (size_t i = 0; i < count; i++) {
auto id = i + 1;
if (onePage) {
id = SINGLE_PAGE;
}
if (selectedPages[i]) {
exportImagePage(i, id, zoomRatio, format, view);
stateListener->setCurrentState(++current);
}
}
}
RasterImageQualityParameter::RasterImageQualityParameter() = default;
RasterImageQualityParameter::RasterImageQualityParameter(ExportQualityCriterion criterion, int value):
qualityCriterion(criterion), value(value) {}
RasterImageQualityParameter::~RasterImageQualityParameter() = default;
auto RasterImageQualityParameter::getQualityCriterion() -> ExportQualityCriterion { return qualityCriterion; }
auto RasterImageQualityParameter::getValue() -> int { return value; }
| 10,408
|
C++
|
.cpp
| 223
| 39.349776
| 120
| 0.647551
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,515
|
XournalScheduler.cpp
|
xournalpp_xournalpp/src/core/control/jobs/XournalScheduler.cpp
|
#include "XournalScheduler.h"
#include <array> // for array
#include <deque> // for _Deque_iterator, deque, operator!=
#include <mutex> // for lock_guard
#include <string> // for string
#include "control/jobs/Scheduler.h" // for JOB_PRIORITY_URGENT, JOB_PRIORIT...
#include "PreviewJob.h" // for PreviewJob
#include "RenderJob.h" // for RenderJob
class SidebarPreviewBaseEntry;
class XojPageView;
XournalScheduler::XournalScheduler() { this->name = "XournalScheduler"; }
XournalScheduler::~XournalScheduler() = default;
void XournalScheduler::removeSidebar(SidebarPreviewBaseEntry* preview) {
// Wait for running jobs to finish: Currently running jobs may still be
// using `preview`, and, as such, it is not completely removed.
bool waitForTaskCompletion = true;
removeSource(preview, JOB_TYPE_PREVIEW, JOB_PRIORITY_HIGH, waitForTaskCompletion);
}
void XournalScheduler::removePage(XojPageView* view) { removeSource(view, JOB_TYPE_RENDER, JOB_PRIORITY_URGENT); }
void XournalScheduler::removeAllJobs() {
std::lock_guard lock{this->jobQueueMutex};
for (size_t priority = JOB_PRIORITY_URGENT; priority < JOB_N_PRIORITIES; priority++) {
std::deque<Job*>& queue = *this->jobQueue[priority];
auto it = queue.begin();
while (it != queue.end()) {
Job* job = *it;
// Only remove PREVIEW and RENDER jobs; we aren't
// responsible for other types of jobs.
JobType type = job->getType();
if (type == JOB_TYPE_PREVIEW || type == JOB_TYPE_RENDER) {
job->deleteJob();
it = queue.erase(it);
job->unref();
job = nullptr;
} else {
++it;
}
}
}
}
void XournalScheduler::finishTask() { std::lock_guard lock{this->jobRunningMutex}; }
void XournalScheduler::removeSource(void* source, JobType type, JobPriority priority, bool awaitFinishTask) {
{
std::lock_guard lock{this->jobQueueMutex};
std::deque<Job*>& queue = *this->jobQueue[priority];
auto it = queue.begin();
while (it != queue.end()) {
Job* job = *it;
if (job->getType() == type && job->getSource() == source) {
it = queue.erase(it);
job->deleteJob();
job->unref();
job = nullptr;
} else {
++it;
}
}
}
// wait until the last job is done
// we can be sure we don't access "source"
if (awaitFinishTask) {
finishTask();
}
}
auto XournalScheduler::existsSource(void* source, JobType type, JobPriority priority) -> bool {
bool exists = false;
std::lock_guard lock{this->jobQueueMutex};
for (Job* job: *this->jobQueue[priority]) {
if (job->getType() == type && job->getSource() == source) {
exists = true;
break;
}
}
return exists;
}
void XournalScheduler::addRepaintSidebar(SidebarPreviewBaseEntry* preview) {
if (existsSource(preview, JOB_TYPE_PREVIEW, JOB_PRIORITY_HIGH)) {
return;
}
auto* job = new PreviewJob(preview);
addJob(job, JOB_PRIORITY_HIGH);
job->unref();
}
void XournalScheduler::addRerenderPage(XojPageView* view) {
if (existsSource(view, JOB_TYPE_RENDER, JOB_PRIORITY_URGENT)) {
return;
}
auto* job = new RenderJob(view);
addJob(job, JOB_PRIORITY_URGENT);
job->unref();
}
| 3,502
|
C++
|
.cpp
| 91
| 31.241758
| 114
| 0.622524
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,516
|
BaseExportJob.cpp
|
xournalpp_xournalpp/src/core/control/jobs/BaseExportJob.cpp
|
#include "BaseExportJob.h"
#include <utility> // for move
#include <glib.h> // for g_warning
#include "control/Control.h" // for Control
#include "control/jobs/BlockingJob.h" // for BlockingJob
#include "control/settings/Settings.h" // for Settings
#include "gui/MainWindow.h" // for MainWindow
#include "gui/dialog/XojSaveDlg.h"
#include "model/Document.h" // for Document, Document::PDF
#include "util/PathUtil.h" // for toGFilename, clearExtensions
#include "util/PopupWindowWrapper.h" // for PopupWindowWrapper
#include "util/XojMsgBox.h" // for XojMsgBox
#include "util/glib_casts.h" // for wrap_for_g_callback_v
#include "util/i18n.h" // for _, FS, _F
BaseExportJob::BaseExportJob(Control* control, const std::string& name): BlockingJob(control, name) {}
BaseExportJob::~BaseExportJob() = default;
void BaseExportJob::addFileFilterToDialog(GtkFileChooser* dialog, const std::string& name, const std::string& mime) {
GtkFileFilter* filter = gtk_file_filter_new();
gtk_file_filter_set_name(filter, name.c_str());
gtk_file_filter_add_mime_type(filter, mime.c_str());
gtk_file_chooser_add_filter(dialog, filter);
}
auto BaseExportJob::checkOverwriteBackgroundPDF(fs::path const& file) const -> bool {
auto backgroundPDF = control->getDocument()->getPdfFilepath();
try {
if (backgroundPDF.empty() || !fs::exists(backgroundPDF)) {
// If there is no background, we can return
return true;
}
if (fs::weakly_canonical(file) == fs::weakly_canonical(backgroundPDF)) {
// If the new file name (with the selected extension) is the previously selected pdf, warn the user
std::string msg = _("Do not overwrite the background PDF! This will cause errors!");
XojMsgBox::showErrorToUser(control->getGtkWindow(), msg);
return false;
}
} catch (const fs::filesystem_error& fe) {
g_warning("%s", fe.what());
auto msg = std::string(_("The check for overwriting the background failed with:\n")) + fe.what();
XojMsgBox::showErrorToUser(control->getGtkWindow(), msg);
return false;
}
return true;
}
void BaseExportJob::showFileChooser(std::function<void()> onFileSelected, std::function<void()> onCancel) {
Settings* settings = control->getSettings();
Document* doc = control->getDocument();
doc->lock();
fs::path suggestedPath = doc->createSaveFolder(settings->getLastSavePath());
suggestedPath /=
doc->createSaveFilename(Document::PDF, settings->getDefaultSaveName(), settings->getDefaultPdfExportName());
doc->unlock();
auto pathValidation = [job = this](fs::path& p, const char* filterName) {
return job->testAndSetFilepath(p, filterName);
};
auto callback = [settings, onFileSelected = std::move(onFileSelected),
onCancel = std::move(onCancel)](std::optional<fs::path> p) {
if (p && !p->empty()) {
settings->setLastSavePath(p->parent_path());
onFileSelected();
} else {
onCancel();
}
};
auto popup = xoj::popup::PopupWindowWrapper<xoj::SaveExportDialog>(control->getSettings(), std::move(suggestedPath),
_("Export File"), _("Export"),
std::move(pathValidation), std::move(callback));
auto* fc = GTK_FILE_CHOOSER(popup.getPopup()->getWindow());
addFilterToDialog(fc);
popup.show(GTK_WINDOW(this->control->getWindow()->getWindow()));
}
auto BaseExportJob::testAndSetFilepath(const fs::path& file, const char* /*filterName*/) -> bool {
try {
if (!file.empty() && fs::is_directory(file.parent_path())) {
this->filepath = file;
return true;
}
} catch (const fs::filesystem_error& e) {
std::string msg = FS(_F("Failed to resolve path with the following error:\n{1}") % e.what());
XojMsgBox::showErrorToUser(control->getGtkWindow(), msg);
}
return false;
}
void BaseExportJob::afterRun() {
if (!this->errorMsg.empty()) {
XojMsgBox::showErrorToUser(control->getGtkWindow(), this->errorMsg);
}
}
| 4,344
|
C++
|
.cpp
| 87
| 42.321839
| 120
| 0.631926
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,517
|
PreviewJob.cpp
|
xournalpp_xournalpp/src/core/control/jobs/PreviewJob.cpp
|
#include "PreviewJob.h"
#include <memory> // for __s...
#include <mutex> // for mutex
#include <vector> // for vector
#include <glib-object.h> // for g_o...
#include <gtk/gtk.h> // for Gtk...
#include "control/Control.h" // for Con...
#include "control/jobs/Job.h" // for JOB...
#include "gui/Shadow.h" // for Shadow
#include "gui/sidebar/previews/base/SidebarPreviewBase.h" // for Sid...
#include "gui/sidebar/previews/base/SidebarPreviewBaseEntry.h" // for Sid...
#include "gui/sidebar/previews/layer/SidebarPreviewLayerEntry.h" // for Sid...
#include "model/Document.h" // for Doc...
#include "model/Layer.h" // for Layer
#include "model/PageRef.h" // for Pag...
#include "model/XojPage.h" // for Xoj...
#include "util/Util.h" // for exe...
#include "view/DocumentView.h" // for Doc...
#include "view/LayerView.h" // for Lay...
#include "view/View.h" // for Con...
#include "view/background/BackgroundFlags.h" // for BAC...
PreviewJob::PreviewJob(SidebarPreviewBaseEntry* sidebar): sidebarPreview(sidebar) {}
PreviewJob::~PreviewJob() { this->sidebarPreview = nullptr; }
void PreviewJob::onDelete() { this->sidebarPreview = nullptr; }
auto PreviewJob::getSource() -> void* { return this->sidebarPreview; }
auto PreviewJob::getType() -> JobType { return JOB_TYPE_PREVIEW; }
void PreviewJob::initGraphics() {
auto w = this->sidebarPreview->imageWidth;
auto h = this->sidebarPreview->imageHeight;
auto DPIscaling = this->sidebarPreview->DPIscaling;
buffer.reset(cairo_image_surface_create(CAIRO_FORMAT_ARGB32, w * DPIscaling, h * DPIscaling), xoj::util::adopt);
cairo_surface_set_device_scale(buffer.get(), DPIscaling, DPIscaling);
cr.reset(cairo_create(buffer.get()), xoj::util::adopt);
double zoom = this->sidebarPreview->sidebar->getZoom();
cairo_translate(cr.get(), Shadow::getShadowTopLeftSize() + 2, Shadow::getShadowTopLeftSize() + 2);
cairo_scale(cr.get(), zoom, zoom);
}
void PreviewJob::finishPaint() {
auto lock = std::lock_guard(this->sidebarPreview->drawingMutex);
this->sidebarPreview->buffer = std::move(this->buffer);
Util::execInUiThread([btn = this->sidebarPreview->button]() { gtk_widget_queue_draw(btn.get()); });
}
void PreviewJob::drawPage() {
PageRef page = this->sidebarPreview->page;
Document* doc = this->sidebarPreview->sidebar->getControl()->getDocument();
DocumentView view;
view.setPdfCache(this->sidebarPreview->sidebar->getCache());
PreviewRenderType type = this->sidebarPreview->getRenderType();
Layer::Index layer = 0;
doc->lock();
// getLayer is not defined for page preview
if (type != RENDER_TYPE_PAGE_PREVIEW) {
layer = (dynamic_cast<SidebarPreviewLayerEntry*>(this->sidebarPreview))->getLayer();
}
auto context = xoj::view::Context::createDefault(cr.get());
switch (type) {
case RENDER_TYPE_PAGE_PREVIEW:
// render all layers
view.drawPage(page, cr.get(), true);
break;
case RENDER_TYPE_PAGE_LAYER:
// render single layer
view.initDrawing(page, cr.get(), true);
if (layer == 0) {
auto flags = xoj::view::BACKGROUND_SHOW_ALL;
flags.forceVisible = xoj::view::FORCE_VISIBLE;
view.drawBackground(flags);
} else {
view.drawBackground(xoj::view::BACKGROUND_FORCE_PAINT_BACKGROUND_COLOR_ONLY);
Layer* drawLayer = (*page->getLayers())[layer - 1];
xoj::view::LayerView layerView(drawLayer);
layerView.draw(context);
}
view.finializeDrawing();
break;
case RENDER_TYPE_PAGE_LAYERSTACK: {
// render all layers up to layer
view.initDrawing(page, cr.get(), true);
auto flags = xoj::view::BACKGROUND_SHOW_ALL;
flags.forceVisible = xoj::view::FORCE_VISIBLE;
view.drawBackground(flags);
for (Layer::Index i = 0; i < layer; i++) {
Layer* drawLayer = (*page->getLayers())[i];
xoj::view::LayerView layerView(drawLayer);
layerView.draw(context);
}
view.finializeDrawing();
break;
}
default:
// unknown type
break;
}
doc->unlock();
}
void PreviewJob::clipToPage() {
// Only render within the preview page. Without this, the when preview jobs attempt
// to clear the display, we fill a region larger than the inside of the preview page!
cairo_rectangle(cr.get(), 0, 0, this->sidebarPreview->page->getWidth(), this->sidebarPreview->page->getHeight());
cairo_clip(cr.get());
}
void PreviewJob::run() {
if (this->sidebarPreview == nullptr) {
return;
}
initGraphics();
clipToPage();
drawPage();
finishPaint();
}
| 5,331
|
C++
|
.cpp
| 110
| 41.709091
| 117
| 0.586154
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,518
|
RenderJob.cpp
|
xournalpp_xournalpp/src/core/control/jobs/RenderJob.cpp
|
#include "RenderJob.h"
#include <mutex> // for mutex
#include <utility> // for move
#include <vector> // for vector
#include <cairo.h> // for cairo_create, cairo_destroy, cairo_...
#include "control/Control.h" // for Control
#include "control/ToolEnums.h" // for TOOL_PLAY_OBJECT
#include "control/ToolHandler.h" // for ToolHandler
#include "control/jobs/Job.h" // for JOB_TYPE_RENDER, JobType
#include "gui/PageView.h" // for XojPageView
#include "gui/XournalView.h" // for XournalView
#include "gui/widgets/XournalWidget.h" // for gtk_xournal_repaint_area
#include "model/Document.h" // for Document
#include "model/XojPage.h" // for Page
#include "util/Assert.h" // for xoj_assert
#include "util/Rectangle.h" // for Rectangle
#include "util/Util.h" // for execInUiThread
#include "util/raii/CairoWrappers.h" // for CairoSurfaceSPtr, CairoSPtr
#include "util/safe_casts.h" // for strict_cast, as_signed, as_si...
#include "view/DocumentView.h" // for DocumentView
#include "view/Mask.h" // for Mask
#if defined(__has_cpp_attribute) && __has_cpp_attribute(likely)
#define XOJ_CPP20_UNLIKELY [[unlikely]]
#else
#define XOJ_CPP20_UNLIKELY
#endif
using xoj::util::Rectangle;
RenderJob::RenderJob(XojPageView* view): view(view) {}
auto RenderJob::getSource() -> void* { return this->view; }
void RenderJob::rerenderRectangle(Rectangle<double> const& rect) {
/**
* Padding seems to be necessary to prevent artefacts of most strokes.
* These artefacts are most pronounced when using the stroke deletion
* tool on ellipses, but also occur occasionally when removing regular
* strokes.
**/
constexpr int RENDER_PADDING = 1;
Range maskRange(rect);
maskRange.addPadding(RENDER_PADDING);
xoj::view::Mask newMask(view->xournal->getDpiScaleFactor(), maskRange, view->xournal->getZoom(),
CAIRO_CONTENT_COLOR_ALPHA);
renderToBuffer(newMask.get());
std::lock_guard lock(this->view->drawingMutex);
if (!view->buffer.isInitialized()) {
// Todo: the buffer must not be uninitializable here, either by moving it into the job or by locking it at job
// creation a shared prt may also be suffice.
XOJ_CPP20_UNLIKELY return;
}
newMask.paintTo(view->buffer.get());
}
void RenderJob::run() {
this->view->repaintRectMutex.lock();
bool rerenderComplete = this->view->rerenderComplete;
auto rerenderRects = std::move(this->view->rerenderRects);
this->view->rerenderComplete = false;
this->view->repaintRectMutex.unlock();
if (rerenderComplete) {
xoj::view::Mask newMask(view->xournal->getDpiScaleFactor(),
Range(0, 0, view->page->getWidth(), view->page->getHeight()), view->xournal->getZoom(),
CAIRO_CONTENT_COLOR_ALPHA);
renderToBuffer(newMask.get());
{
std::lock_guard lock(this->view->drawingMutex);
std::swap(this->view->buffer, newMask);
}
repaintPage();
} else {
for (Rectangle<double> const& rect: rerenderRects) {
rerenderRectangle(rect);
repaintPageArea(rect.x, rect.y, rect.x + rect.width, rect.y + rect.height);
}
}
}
static void repaintWidgetArea(GtkWidget* widget, int x1, int y1, int x2, int y2) {
Util::execInUiThread([=]() { gtk_xournal_repaint_area(widget, x1, y1, x2, y2); });
}
void RenderJob::repaintPage() const { repaintPageArea(0, 0, view->getWidth(), view->getHeight()); }
void RenderJob::repaintPageArea(double x1, double y1, double x2, double y2) const {
double zoom = view->xournal->getZoom();
int x = view->getX();
int y = view->getY();
repaintWidgetArea(view->xournal->getWidget(), x + floor_cast<int>(zoom * x1), y + floor_cast<int>(zoom * y1),
x + ceil_cast<int>(zoom * x2), y + ceil_cast<int>(zoom * y2));
}
void RenderJob::renderToBuffer(cairo_t* cr) const {
DocumentView localView;
localView.setMarkAudioStroke(this->view->getXournal()->getControl()->getToolHandler()->getToolType() ==
TOOL_PLAY_OBJECT);
localView.setPdfCache(this->view->xournal->getCache());
std::lock_guard<Document> lock(*this->view->xournal->getDocument());
localView.drawPage(this->view->page, cr, false);
}
auto RenderJob::getType() -> JobType { return JOB_TYPE_RENDER; }
| 4,567
|
C++
|
.cpp
| 93
| 43.430108
| 119
| 0.648618
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,519
|
FloatingToolbox.cpp
|
xournalpp_xournalpp/src/core/gui/FloatingToolbox.cpp
|
#include "FloatingToolbox.h"
#include <algorithm> // for max
#include <memory> // for allocator
#include <gdk/gdk.h> // for GdkRectangle, GDK_LEAVE_...
#include <glib-object.h> // for G_CALLBACK, g_signal_con...
#include "control/Control.h" // for Control
#include "control/ToolEnums.h" // for TOOL_FLOATING_TOOLBOX
#include "control/settings/ButtonConfig.h" // for ButtonConfig
#include "control/settings/Settings.h" // for Settings
#include "control/settings/SettingsEnums.h" // for BUTTON_COUNT
#include "MainWindow.h" // for MainWindow
#include "ToolbarDefinitions.h" // for ToolbarEntryDefintion
FloatingToolbox::FloatingToolbox(MainWindow* theMainWindow, GtkOverlay* overlay) {
this->mainWindow = theMainWindow;
this->floatingToolbox = theMainWindow->get("floatingToolbox");
this->floatingToolboxX = 200;
this->floatingToolboxY = 200;
this->floatingToolboxState = recalcSize;
gtk_overlay_add_overlay(overlay, this->floatingToolbox);
gtk_overlay_set_overlay_pass_through(overlay, this->floatingToolbox, true);
gtk_widget_add_events(this->floatingToolbox, GDK_LEAVE_NOTIFY_MASK);
g_signal_connect(this->floatingToolbox, "leave-notify-event", G_CALLBACK(handleLeaveFloatingToolbox), this);
// position overlay widgets
g_signal_connect(overlay, "get-child-position", G_CALLBACK(this->getOverlayPosition), this);
}
FloatingToolbox::~FloatingToolbox() = default;
void FloatingToolbox::show(int x, int y) {
this->floatingToolboxX = x;
this->floatingToolboxY = y;
this->show();
}
/****
* floatingToolboxActivated
* True if the user has:
* assigned a mouse or stylus button to bring up the floatingToolbox;
* or enabled tapAction and Show FloatingToolbox( prefs->DrawingArea->ActionOnToolTap );
* or put tools in the FloatingToolbox.
*
*/
auto FloatingToolbox::floatingToolboxActivated() -> bool {
Settings* settings = this->mainWindow->getControl()->getSettings();
ButtonConfig* cfg = nullptr;
// check if any buttons assigned to bring up toolbox
for (unsigned int id = 0; id < BUTTON_COUNT; id++) {
cfg = settings->getButtonConfig(id);
if (cfg->getAction() == TOOL_FLOATING_TOOLBOX) {
return true; // return true
}
}
// check if user can show Floating Menu with tap.
if (settings->getDoActionOnStrokeFiltered() && settings->getStrokeFilterEnabled()) {
return true; // return true
}
if (this->countWidgets() > 0) // FloatingToolbox contains something
{
return true; // return true
}
return false;
}
auto FloatingToolbox::countWidgets() -> int {
int count = 0;
for (int index = TBFloatFirst; index <= TBFloatLast; index++) {
const char* guiName = TOOLBAR_DEFINITIONS[index].guiName;
GtkToolbar* toolbar1 = GTK_TOOLBAR(this->mainWindow->get(guiName));
count += gtk_toolbar_get_n_items(toolbar1);
}
return count;
}
void FloatingToolbox::showForConfiguration() {
if (this->floatingToolboxActivated()) // Do not show if not being used - at least while experimental.
{
GtkWidget* boxContents = this->mainWindow->get("boxContents");
gint wx = 0, wy = 0;
gtk_widget_translate_coordinates(boxContents, gtk_widget_get_toplevel(boxContents), 0, 0, &wx, &wy);
this->floatingToolboxX = wx + 40; // when configuration state these are
this->floatingToolboxY = wy + 40; // topleft coordinates( otherwise center).
this->floatingToolboxState = configuration;
this->show();
}
}
void FloatingToolbox::show() {
gtk_widget_hide(this->floatingToolbox); // force showing in new position
gtk_widget_show_all(this->floatingToolbox);
if (this->floatingToolboxState != configuration) {
gtk_widget_hide(this->mainWindow->get("labelFloatingToolbox"));
}
if (this->floatingToolboxState == configuration || countWidgets() > 0) {
gtk_widget_hide(this->mainWindow->get("showIfEmpty"));
}
}
void FloatingToolbox::hide() {
if (this->floatingToolboxState == configuration) {
this->floatingToolboxState = recalcSize;
}
gtk_widget_hide(this->floatingToolbox);
}
void FloatingToolbox::flagRecalculateSizeRequired() { this->floatingToolboxState = recalcSize; }
/**
* getOverlayPosition - this is how we position the widget in the overlay under the mouse
*
* The requested location is communicated via the FloatingToolbox member variables:
* ->floatingToolbox, so we can operate on the right widget
* ->floatingToolboxState, are we configuring, resizing or just moving
* ->floatingToolboxX, where to display
* ->floatingToolboxY.
*
*/
auto FloatingToolbox::getOverlayPosition(GtkOverlay* overlay, GtkWidget* widget, GdkRectangle* allocation,
FloatingToolbox* self) -> gboolean {
if (widget == self->floatingToolbox) {
gtk_widget_get_allocation(widget, allocation); // get existing width and height
if (self->floatingToolboxState != noChange ||
allocation->height < 2) // if recalcSize or configuration or initiation.
{
GtkRequisition natural;
gtk_widget_get_preferred_size(widget, nullptr, &natural);
allocation->width = natural.width;
allocation->height = natural.height;
}
switch (self->floatingToolboxState) {
case recalcSize: // fallthrough note: recalc done above
case noChange:
// show centered on x,y
allocation->x = self->floatingToolboxX - allocation->width / 2;
allocation->y = self->floatingToolboxY - allocation->height / 2;
self->floatingToolboxState = noChange;
break;
case configuration:
allocation->x = self->floatingToolboxX;
allocation->y = self->floatingToolboxY;
allocation->width = std::max(allocation->width + 32, 50); // always room for one more...
allocation->height = std::max(allocation->height, 50);
break;
}
return true;
}
return false;
}
void FloatingToolbox::handleLeaveFloatingToolbox(GtkWidget* floatingToolbox, GdkEvent* event, FloatingToolbox* self) {
if (floatingToolbox == self->floatingToolbox) {
if (self->floatingToolboxState != configuration) {
self->hide();
}
}
}
| 6,531
|
C++
|
.cpp
| 145
| 38.641379
| 118
| 0.675284
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,520
|
PagePreviewDecoration.cpp
|
xournalpp_xournalpp/src/core/gui/PagePreviewDecoration.cpp
|
#include "PagePreviewDecoration.h"
#include <math.h>
#include "control/Control.h"
#include "control/settings/Settings.h"
#include "gui/MainWindow.h"
#include "util/raii/CairoWrappers.h"
void PagePreviewDecoration::drawDecoration(cairo_t* cr, SidebarPreviewPageEntry* pageEntry, Control* control) {
switch (control->getSettings()->getSidebarNumberingStyle()) {
case SidebarNumberingStyle::NUMBER_BELOW_PREVIEW:
PagePreviewDecoration::drawPageNumberBelowPreview(cr, pageEntry, control);
break;
case SidebarNumberingStyle::NUMBER_WITH_CIRCULAR_BACKGROUND:
PagePreviewDecoration::drawPageNumberWithCircleBackground(cr, pageEntry, control);
break;
case SidebarNumberingStyle::NUMBER_WITH_SQUARE_BACKGROUND:
PagePreviewDecoration::drawPageNumberWithSquareBackground(cr, pageEntry, control);
break;
default:
break;
}
}
void PagePreviewDecoration::drawPageNumberBelowPreview(cairo_t* cr, SidebarPreviewPageEntry* pageEntry,
Control* control) {
xoj::util::CairoSaveGuard saveGuard(cr);
cairo_text_extents_t extents;
std::string pageNumber = std::to_string(pageEntry->getIndex() + 1);
Color color = control->getWindow()->isDarkTheme() ? Colors::white : Colors::xopp_darkslategray;
if (pageEntry->isSelected()) {
color = control->getSettings()->getBorderColor();
}
Util::cairo_set_source_rgbi(cr, color);
cairo_select_font_face(cr, FONT_NAME, CAIRO_FONT_SLANT_NORMAL, CAIRO_FONT_WEIGHT_NORMAL);
cairo_set_font_size(cr, FONT_SIZE);
cairo_text_extents(cr, pageNumber.c_str(), &extents);
double x = pageEntry->getWidth() / 2 - (extents.width / 2 + extents.x_bearing);
double y = pageEntry->getHeight() - MARGIN_BOTTOM - (extents.height / 2 + extents.y_bearing);
cairo_move_to(cr, x, y);
cairo_show_text(cr, pageNumber.c_str());
}
void PagePreviewDecoration::drawPageNumberWithCircleBackground(cairo_t* cr, SidebarPreviewPageEntry* pageEntry,
Control* control) {
xoj::util::CairoSaveGuard saveGuard(cr);
cairo_text_extents_t extents;
std::string pageNumber = std::to_string(pageEntry->getIndex() + 1);
cairo_select_font_face(cr, FONT_NAME, CAIRO_FONT_SLANT_NORMAL, CAIRO_FONT_WEIGHT_NORMAL);
cairo_set_font_size(cr, FONT_SIZE);
cairo_text_extents(cr, pageNumber.c_str(), &extents);
// Set the color for drawing the circle. This circle is required to provide good contrast for the page number.
if (pageEntry->isSelected()) {
Color color = control->getSettings()->getBorderColor();
Util::cairo_set_source_rgbi(cr, color, CIRCLE_LABEL_OPACITY);
} else {
Util::cairo_set_source_rgbi(cr, Colors::xopp_darkslategray, CIRCLE_LABEL_OPACITY);
}
// How many pixels to indent the circle center from the widget border
double indentRight = pageEntry->getWidth() * CIRCLE_INDENT_RIGHT;
double indentBottom = pageEntry->getHeight() * CIRCLE_INDENT_BOTTOM;
// Pixel position of circle center
double x = pageEntry->getWidth() - indentRight;
double y = pageEntry->getHeight() - indentBottom;
// Inner circle width depends on the actual text width
double addititionalWidth = std::max((extents.width - 2 * CIRCLE_RADIUS) + CIRCLE_TEXT_PADDING, 0.0);
// Draw an slightly transparent circle in the lower right corner of the preview
cairo_set_line_width(cr, LINE_WIDTH);
cairo_arc(cr, x - addititionalWidth, y, CIRCLE_RADIUS, M_PI * 0.5, M_PI * 1.5);
cairo_arc(cr, x, y, CIRCLE_RADIUS, M_PI * 1.5, M_PI * 0.5);
cairo_close_path(cr);
cairo_stroke_preserve(cr);
cairo_fill(cr);
// Draw the page number in the center of the previously drawn circle
cairo_move_to(cr, x - addititionalWidth / 2 - (extents.width / 2 + extents.x_bearing), y + CIRCLE_TEXT_Y);
Util::cairo_set_source_argb(cr, Colors::white);
cairo_show_text(cr, pageNumber.c_str());
}
void PagePreviewDecoration::drawPageNumberWithSquareBackground(cairo_t* cr, SidebarPreviewPageEntry* pageEntry,
Control* control) {
xoj::util::CairoSaveGuard saveGuard(cr);
cairo_text_extents_t extents;
std::string pageNumber = std::to_string(pageEntry->getIndex() + 1);
cairo_select_font_face(cr, FONT_NAME, CAIRO_FONT_SLANT_NORMAL, CAIRO_FONT_WEIGHT_NORMAL);
cairo_set_font_size(cr, FONT_SIZE);
cairo_text_extents(cr, pageNumber.c_str(), &extents);
// Select the color for painting the square background
if (pageEntry->isSelected()) {
Util::cairo_set_source_rgbi(cr, control->getSettings()->getBorderColor());
} else {
Util::cairo_set_source_rgbi(cr, Colors::xopp_darkslategray);
// In case the page is not selected draw a border around the preview to match the selected
// See discussion: <https://github.com/xournalpp/xournalpp/issues/4624#issue-1557719574>
cairo_set_line_width(cr, PREVIEW_BORDER_LINE_WIDTH);
cairo_set_line_cap(cr, CAIRO_LINE_CAP_BUTT);
cairo_set_line_join(cr, CAIRO_LINE_JOIN_BEVEL);
cairo_rectangle(cr, PREVIEW_UPPER_LEFT, PREVIEW_UPPER_LEFT, pageEntry->getWidth() - PREVIEW_WIDTH_INDENT,
pageEntry->getHeight() - PREVIEW_HEIGHT_INDENT);
cairo_stroke(cr);
}
// Calculate the rectangle width depending on the page index number of digits
double recWidth = std::max(extents.width + 8, SQUARE_SIZE);
// Calculate the position of the upper left corner of the square
double x = pageEntry->getWidth() - SQUARE_INDENT_RIGHT - recWidth;
double y = pageEntry->getHeight() - SQUARE_INDENT_BOTTOM - SQUARE_SIZE;
// Draw an square in the lower right corner
cairo_set_line_width(cr, LINE_WIDTH);
cairo_rectangle(cr, x, y, recWidth, SQUARE_SIZE);
cairo_stroke_preserve(cr);
cairo_fill(cr);
// Draw the page number in the center of the square
cairo_move_to(cr, x + recWidth / 2 - (extents.width / 2 + extents.x_bearing), y + SQUARE_TEXT_Y);
Util::cairo_set_source_argb(cr, Colors::white);
cairo_show_text(cr, pageNumber.c_str());
}
| 6,265
|
C++
|
.cpp
| 111
| 48.963964
| 114
| 0.6853
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,521
|
PdfFloatingToolbox.cpp
|
xournalpp_xournalpp/src/core/gui/PdfFloatingToolbox.cpp
|
#include "PdfFloatingToolbox.h"
#include <algorithm> // for max, min
#include <cmath> // for abs
#include <cstddef> // for size_t
#include <memory>
#include <string> // for string
#include <utility> // for move
#include <vector> // for vector
#include <glib-object.h> // for G_CALLBACK, g_signal_connect
#include <gtk/gtk.h>
#include "control/Control.h" // for Control
#include "control/ToolEnums.h" // for ToolType, TOOL_SELECT_PDF_TEXT_LI...
#include "control/ToolHandler.h" // for ToolHandler
#include "control/tools/PdfElemSelection.h"
#include "gui/PageView.h" // for XojPageView
#include "gui/XournalView.h" // for XournalView
#include "model/Document.h" // for Document
#include "model/Layer.h" // for Layer
#include "model/PageRef.h" // for PageRef
#include "model/Point.h" // for Point
#include "model/Stroke.h" // for Stroke, BUTT, StrokeTool::HIGHLIG...
#include "model/XojPage.h" // for XojPage
#include "undo/GroupUndoAction.h" // for GroupUndoAction
#include "undo/InsertUndoAction.h" // for InsertUndoAction
#include "undo/UndoAction.h" // for UndoAction
#include "undo/UndoRedoHandler.h" // for UndoRedoHandler
#include "util/Assert.h" // for xoj_assert
#include "util/gtk4_helper.h" // for gtk_widget_get_clipboard
#include "MainWindow.h" // for MainWindow
PdfFloatingToolbox::PdfFloatingToolbox(MainWindow* theMainWindow, GtkOverlay* overlay):
theMainWindow(theMainWindow), overlay(overlay, xoj::util::ref), position({0, 0}) {
this->floatingToolbox = theMainWindow->get("pdfFloatingToolbox");
gtk_overlay_add_overlay(overlay, this->floatingToolbox);
gtk_overlay_set_overlay_pass_through(overlay, this->floatingToolbox, true);
g_signal_connect(overlay, "get-child-position", G_CALLBACK(this->getOverlayPosition), this);
g_signal_connect(theMainWindow->get("pdfTbHighlight"), "clicked", G_CALLBACK(this->highlightCb), this);
g_signal_connect(theMainWindow->get("pdfTbCopyText"), "clicked", G_CALLBACK(this->copyTextCb), this);
g_signal_connect(theMainWindow->get("pdfTbUnderline"), "clicked", G_CALLBACK(this->underlineCb), this);
g_signal_connect(theMainWindow->get("pdfTbStrikethrough"), "clicked", G_CALLBACK(this->strikethroughCb), this);
g_signal_connect(theMainWindow->get("pdfTbChangeType"), "clicked", G_CALLBACK(this->switchSelectTypeCb), this);
this->clearSelection();
this->hide();
}
PdfFloatingToolbox::~PdfFloatingToolbox() = default;
PdfElemSelection* PdfFloatingToolbox::getSelection() const { return this->pdfElemSelection.get(); }
bool PdfFloatingToolbox::hasSelection() const { return this->getSelection() != nullptr; }
void PdfFloatingToolbox::clearSelection() { this->pdfElemSelection.reset(); }
auto PdfFloatingToolbox::newSelection(double x, double y) -> const PdfElemSelection* {
this->pdfElemSelection = std::make_unique<PdfElemSelection>(x, y, this->theMainWindow->getControl());
return this->pdfElemSelection.get();
}
void PdfFloatingToolbox::show(int x, int y) {
xoj_assert(this->getSelection());
// (x, y) are in the gtk window's coordinates.
// However, we actually show the toolbox in the overlay's coordinate system.
gtk_widget_translate_coordinates(gtk_widget_get_toplevel(this->floatingToolbox), GTK_WIDGET(overlay.get()), x, y,
&this->position.x, &this->position.y);
this->show();
}
void PdfFloatingToolbox::hide() {
if (isHidden())
return;
gtk_widget_hide(this->floatingToolbox);
}
auto PdfFloatingToolbox::getOverlayPosition(GtkOverlay* overlay, GtkWidget* widget, GdkRectangle* allocation,
PdfFloatingToolbox* self) -> gboolean {
if (widget == self->floatingToolbox) {
// Get existing width and height
GtkRequisition natural;
gtk_widget_get_preferred_size(widget, nullptr, &natural);
allocation->width = natural.width;
allocation->height = natural.height;
// Make sure the "pdfFloatingToolbox" is fully displayed.
const int gap = 5;
// By default, we show the toolbox below and to the right of the selected text.
// If the toolbox will go out of the window, then we'll flip the corresponding directions.
GtkAllocation windowAlloc{};
gtk_widget_get_allocation(GTK_WIDGET(overlay), &windowAlloc);
bool rightOK = self->position.x + allocation->width + gap <= windowAlloc.width;
bool bottomOK = self->position.y + allocation->height + gap <= windowAlloc.height;
allocation->x = rightOK ? self->position.x + gap : self->position.x - allocation->width - gap;
allocation->y = bottomOK ? self->position.y + gap : self->position.y - allocation->height - gap;
return true;
}
return false;
}
void PdfFloatingToolbox::userCancelSelection() {
this->pdfElemSelection.reset();
this->hide();
}
void PdfFloatingToolbox::highlightCb(GtkButton* button, PdfFloatingToolbox* pft) {
int markerOpacity = pft->theMainWindow->getControl()->getToolHandler()->getSelectPDFTextMarkerOpacity();
pft->createStrokes(PdfMarkerStyle::POS_TEXT_MIDDLE, PdfMarkerStyle::WIDTH_TEXT_HEIGHT, markerOpacity);
pft->userCancelSelection();
}
void PdfFloatingToolbox::copyTextCb(GtkButton* button, PdfFloatingToolbox* pft) {
pft->copyTextToClipboard();
pft->userCancelSelection();
}
void PdfFloatingToolbox::underlineCb(GtkButton* button, PdfFloatingToolbox* pft) {
pft->createStrokes(PdfMarkerStyle::POS_TEXT_BOTTOM, PdfMarkerStyle::WIDTH_TEXT_LINE, 230);
pft->userCancelSelection();
}
void PdfFloatingToolbox::strikethroughCb(GtkButton* button, PdfFloatingToolbox* pft) {
pft->createStrokes(PdfMarkerStyle::POS_TEXT_MIDDLE, PdfMarkerStyle::WIDTH_TEXT_LINE, 230);
pft->userCancelSelection();
}
void PdfFloatingToolbox::show() {
gtk_widget_hide(this->floatingToolbox); // force showing in new position
gtk_widget_show_all(this->floatingToolbox);
}
void PdfFloatingToolbox::copyTextToClipboard() {
GtkClipboard* clipboard = gtk_widget_get_clipboard(this->theMainWindow->getWindow());
if (std::string text = this->pdfElemSelection->getSelectedText(); !text.empty()) {
gtk_clipboard_set_text(clipboard, text.c_str(), -1);
}
}
void PdfFloatingToolbox::createStrokes(PdfMarkerStyle position, PdfMarkerStyle width, int markerOpacity) {
const size_t pdfPageNo = this->pdfElemSelection->getSelectionPageNr();
const size_t currentPage = theMainWindow->getXournal()->getCurrentPage();
// Get the PDF page that the current page corresponds to.
// It should be the same as the PDF page of the selection.
auto doc = this->theMainWindow->getControl()->getDocument();
doc->lock();
const size_t pdfPageOfCurrentPage = doc->getPage(currentPage)->getPdfPageNr();
doc->unlock();
if (pdfPageOfCurrentPage != pdfPageNo) {
// There's probably a bug that violates our assumptions, so no-op.
g_warning("The current page's PDF page is not the same as the PDF page of the selection!");
return;
}
const auto textRects = this->pdfElemSelection->getSelectedTextRects();
if (textRects.empty()) {
return;
}
auto* control = this->theMainWindow->getControl();
PageRef page = control->getCurrentPage();
Layer* layer = page->getSelectedLayer();
auto color = theMainWindow->getXournal()->getControl()->getToolHandler()->getColor();
Range dirtyRange;
std::vector<ElementPtr> strokes;
for (XojPdfRectangle rect: textRects) {
const double topOfLine = std::min(rect.y1, rect.y2);
const double middleOfLine = (rect.y1 + rect.y2) / 2;
const double bottomOfLine = std::max(rect.y1, rect.y2);
const double rectWidth = std::abs(rect.y2 - rect.y1);
// the center line position of stroke
const double h = position == PdfMarkerStyle::POS_TEXT_BOTTOM ? bottomOfLine :
position == PdfMarkerStyle::POS_TEXT_MIDDLE ? middleOfLine :
topOfLine;
// the width of stroke
const double w = width == PdfMarkerStyle::WIDTH_TEXT_LINE ? 1 : rectWidth;
auto stroke = std::make_unique<Stroke>();
stroke->setColor(color);
stroke->setFill(markerOpacity);
stroke->setToolType(StrokeTool::HIGHLIGHTER);
stroke->setWidth(w);
stroke->addPoint(Point(rect.x1, h, -1));
stroke->addPoint(Point(rect.x2, h, -1));
stroke->setStrokeCapStyle(StrokeCapStyle::BUTT);
dirtyRange.addPoint(rect.x1, h - 0.5 * w);
dirtyRange.addPoint(rect.x2, h + 0.5 * w);
strokes.push_back(std::move(stroke));
}
std::vector<Element*> strokePtrs(strokes.size());
std::transform(strokes.begin(), strokes.end(), strokePtrs.begin(), [](auto& e) { return e.get(); });
doc->lock();
for (auto&& s: strokes) {
layer->addElement(std::move(s));
}
doc->unlock();
page->fireElementsChanged(strokePtrs, dirtyRange);
auto undoAct = std::make_unique<GroupUndoAction>();
for (auto* stroke: strokePtrs) {
undoAct->addAction(std::make_unique<InsertUndoAction>(page, layer, stroke));
}
control->getUndoRedoHandler()->addUndoAction(std::move(undoAct));
}
void PdfFloatingToolbox::switchSelectTypeCb(GtkButton* button, PdfFloatingToolbox* pft) {
ToolType type = pft->theMainWindow->getControl()->getToolHandler()->getToolType();
type = type == ToolType::TOOL_SELECT_PDF_TEXT_LINEAR ? ToolType::TOOL_SELECT_PDF_TEXT_RECT :
ToolType::TOOL_SELECT_PDF_TEXT_LINEAR;
pft->theMainWindow->getControl()->selectTool(type);
pft->pdfElemSelection->setToolType(type);
pft->pdfElemSelection->finalizeSelection(PdfElemSelection::selectionStyleForToolType(type));
}
bool PdfFloatingToolbox::isHidden() const { return !gtk_widget_is_visible(this->floatingToolbox); }
| 10,111
|
C++
|
.cpp
| 187
| 48.026738
| 117
| 0.693305
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,522
|
IconNameHelper.cpp
|
xournalpp_xournalpp/src/core/gui/IconNameHelper.cpp
|
#include "IconNameHelper.h"
#include <gtk/gtk.h> // for gtk_icon_theme_get_default
#include "control/settings/Settings.h" // for Settings
IconNameHelper::IconNameHelper(Settings* settings): settings(settings) {}
auto IconNameHelper::iconName(const char* icon) const -> std::string {
std::string xoppName = std::string("xopp-") + icon;
auto iconName = this->settings->areStockIconsUsed() && gtk_icon_theme_has_icon(gtk_icon_theme_get_default(), icon) ?
std::string(icon) :
xoppName;
return iconName;
}
| 575
|
C++
|
.cpp
| 11
| 44.727273
| 120
| 0.6625
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,523
|
RepaintHandler.cpp
|
xournalpp_xournalpp/src/core/gui/RepaintHandler.cpp
|
#include "RepaintHandler.h"
#include <gtk/gtk.h> // for gtk_widget_queue_draw
#include "gui/widgets/XournalWidget.h" // for gtk_xournal_repaint_area
#include "PageView.h" // for XojPageView
#include "XournalView.h" // for XournalView
RepaintHandler::RepaintHandler(XournalView* xournal): xournal(xournal) {}
RepaintHandler::~RepaintHandler() { this->xournal = nullptr; }
void RepaintHandler::repaintPage(const XojPageView* view) {
int x1 = view->getX();
int y1 = view->getY();
int x2 = x1 + view->getDisplayWidth();
int y2 = y1 + view->getDisplayHeight();
gtk_xournal_repaint_area(this->xournal->getWidget(), x1, y1, x2, y2);
}
void RepaintHandler::repaintPageArea(const XojPageView* view, int x1, int y1, int x2, int y2) {
int x = view->getX();
int y = view->getY();
gtk_xournal_repaint_area(this->xournal->getWidget(), x + x1, y + y1, x + x2, y + y2);
}
void RepaintHandler::repaintPageBorder(const XojPageView* view) { gtk_widget_queue_draw(this->xournal->getWidget()); }
| 1,023
|
C++
|
.cpp
| 20
| 48.1
| 118
| 0.705231
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,524
|
Layout.cpp
|
xournalpp_xournalpp/src/core/gui/Layout.cpp
|
#include "Layout.h"
#include <algorithm> // for max, lower_bound, transform
#include <cmath> // for abs
#include <iterator> // for begin, end, distance
#include <numeric> // for accumulate
#include <optional> // for optional
#include <type_traits> // for make_signed_t, remove_referen...
#include <glib-object.h> // for G_CALLBACK, g_signal_connect
#include "control/Control.h" // for Control
#include "control/settings/Settings.h" // for Settings
#include "gui/LayoutMapper.h" // for LayoutMapper, GridPosition
#include "gui/PageView.h" // for XojPageView
#include "gui/scroll/ScrollHandling.h" // for ScrollHandling
#include "model/Document.h" // for Document
#include "util/Rectangle.h" // for Rectangle
#include "util/safe_casts.h" // for strict_cast, as_signed, as_si...
#include "XournalView.h" // for XournalView
using xoj::util::Rectangle;
/**
* Padding outside the pages, including shadow
*/
constexpr auto const XOURNAL_PADDING = 10;
/**
* Allowance for shadow between page pairs in paired page mode
*/
constexpr auto const XOURNAL_ROOM_FOR_SHADOW = 3;
/**
* Padding between the pages
*/
constexpr auto const XOURNAL_PADDING_BETWEEN = 15;
Layout::Layout(XournalView* view, ScrollHandling* scrollHandling): view(view), scrollHandling(scrollHandling) {
g_signal_connect(scrollHandling->getHorizontal(), "value-changed", G_CALLBACK(horizontalScrollChanged), this);
g_signal_connect(scrollHandling->getVertical(), "value-changed", G_CALLBACK(verticalScrollChanged), this);
lastScrollHorizontal = gtk_adjustment_get_value(scrollHandling->getHorizontal());
lastScrollVertical = gtk_adjustment_get_value(scrollHandling->getVertical());
}
void Layout::horizontalScrollChanged(GtkAdjustment* adjustment, Layout* layout) {
Layout::checkScroll(adjustment, layout->lastScrollHorizontal);
layout->updateVisibility();
}
void Layout::verticalScrollChanged(GtkAdjustment* adjustment, Layout* layout) {
Layout::checkScroll(adjustment, layout->lastScrollVertical);
layout->updateVisibility();
layout->maybeAddLastPage(layout);
}
void Layout::maybeAddLastPage(Layout* layout) {
auto* control = this->view->getControl();
auto* settings = control->getSettings();
if (settings->getEmptyLastPageAppend() == EmptyLastPageAppendType::OnScrollToEndOfLastPage) {
// If the layout is 5px away from the end of the last page
if (std::abs((layout->getMinimalHeight() - layout->getVisibleRect().y) - layout->getVisibleRect().height) < 5) {
auto* doc = control->getDocument();
doc->lock();
auto pdfPageCount = doc->getPdfPageCount();
doc->unlock();
if (pdfPageCount == 0) {
auto currentPage = control->getCurrentPageNo();
doc->lock();
auto lastPage = doc->getPageCount() - 1;
doc->unlock();
if (currentPage == lastPage) {
control->insertNewPage(currentPage + 1, false);
}
}
}
}
}
void Layout::checkScroll(GtkAdjustment* adjustment, double& lastScroll) {
lastScroll = gtk_adjustment_get_value(adjustment);
}
void Layout::updateVisibility() {
Rectangle visRect = getVisibleRect();
// step through every possible page position and update using p->setIsVisible()
// Using initial grid aprox speeds things up by a factor of 5. See previous git check-in for specifics.
int x1 = 0;
int y1 = 0;
// Data to select page based on visibility
std::optional<size_t> mostPageNr;
double mostPagePercent = 0;
for (size_t row = 0; row < this->rowYStart.size(); ++row) {
auto y2 = as_signed_strict(this->rowYStart[row]);
for (size_t col = 0; col < this->colXStart.size(); ++col) {
auto x2 = as_signed_strict(this->colXStart[col]);
auto optionalPage = this->mapper.at({col, row});
if (optionalPage) // a page exists at this grid location
{
auto& pageView = this->view->viewPages[*optionalPage];
// check if grid location is visible as an aprox for page visiblity:
if (!(visRect.x > x2 || visRect.x + visRect.width < x1) // visrect not outside current row/col
&& !(visRect.y > y2 || visRect.y + visRect.height < y1)) {
// now use exact check of page itself:
// visrect not outside current page dimensions:
auto const& pageRect = pageView->getRect();
if (auto intersection = pageRect.intersects(visRect); intersection) {
pageView->setIsVisible(true);
// Set the selected page
double percent = intersection->area() / pageRect.area();
if (percent > mostPagePercent) {
mostPageNr = *optionalPage;
mostPagePercent = percent;
}
}
} else {
pageView->setIsVisible(false);
}
}
x1 = x2;
}
y1 = y2;
x1 = 0;
}
if (mostPageNr) {
this->view->getControl()->firePageSelected(*mostPageNr);
}
}
auto Layout::getVisibleRect() -> Rectangle<double> {
return Rectangle(gtk_adjustment_get_value(scrollHandling->getHorizontal()),
gtk_adjustment_get_value(scrollHandling->getVertical()),
gtk_adjustment_get_page_size(scrollHandling->getHorizontal()),
gtk_adjustment_get_page_size(scrollHandling->getVertical()));
}
/**
* adds the addend to base if the predicate is true
*/
[[maybe_unused]] constexpr auto sumIf = [](auto base, auto addend, bool predicate) {
if constexpr (std::is_signed_v<decltype(base)> || std::is_signed_v<decltype(addend)>) {
using RT = std::make_signed_t<decltype(base + addend)>;
if (predicate) {
return RT(base) + RT(addend);
}
return RT(base);
} else if constexpr (!(std::is_signed_v<decltype(base)> || std::is_signed_v<decltype(addend)>)) {
using RT = decltype(base + addend);
if (predicate) {
return RT(base) + RT(addend);
}
return RT(base);
}
};
void Layout::recalculate_int() const {
auto* settings = view->getControl()->getSettings();
auto len = view->viewPages.size();
mapper.configureFromSettings(len, settings);
auto colCount = mapper.getColumns();
auto rowCount = mapper.getRows();
pc.widthCols.assign(colCount, 0);
pc.heightRows.assign(rowCount, 0);
for (size_t pageIdx{}; pageIdx < len; ++pageIdx) {
auto const& raster_p = mapper.at(pageIdx); // auto [c, r] raster = mapper.at();
auto const& c = raster_p.col;
auto const& r = raster_p.row;
auto& v = view->viewPages[pageIdx];
pc.widthCols[c] = std::max(pc.widthCols[c], v->getDisplayWidthDouble());
pc.heightRows[r] = std::max(pc.heightRows[r], v->getDisplayHeightDouble());
}
// add space around the entire page area to accommodate older Wacom tablets with limited sense area.
auto vPadding = 2 * XOURNAL_PADDING;
if (settings->getUnlimitedScrolling()) {
vPadding += 2 * static_cast<int>(gtk_adjustment_get_page_size(scrollHandling->getVertical()));
} else if (settings->getAddVerticalSpace()) {
vPadding += settings->getAddVerticalSpaceAmountAbove();
vPadding += settings->getAddVerticalSpaceAmountBelow();
}
auto hPadding = 2 * XOURNAL_PADDING;
if (settings->getUnlimitedScrolling()) {
hPadding += 2 * static_cast<int>(gtk_adjustment_get_page_size(scrollHandling->getHorizontal()));
} else if (settings->getAddHorizontalSpace()) {
hPadding += settings->getAddHorizontalSpaceAmountLeft();
hPadding += settings->getAddHorizontalSpaceAmountRight();
}
pc.minWidth = as_unsigned(hPadding + as_signed_strict((pc.widthCols.size() - 1) * XOURNAL_PADDING_BETWEEN));
pc.minHeight = as_unsigned(vPadding + as_signed_strict((pc.heightRows.size() - 1) * XOURNAL_PADDING_BETWEEN));
pc.minWidth = floor_cast<size_t>(std::accumulate(begin(pc.widthCols), end(pc.widthCols), double(pc.minWidth)));
pc.minHeight = floor_cast<size_t>(std::accumulate(begin(pc.heightRows), end(pc.heightRows), double(pc.minHeight)));
pc.valid = true;
}
void Layout::recalculate() {
pc.valid = false;
gtk_widget_queue_resize(view->getWidget());
}
void Layout::layoutPages(int width, int height) {
std::lock_guard g{pc.m};
if (!pc.valid) {
recalculate_int();
}
// Todo: remove, just a hack-hotfix
scrollHandling->setLayoutSize(std::max(width, strict_cast<int>(this->pc.minWidth)),
std::max(height, strict_cast<int>(this->pc.minHeight)));
size_t const len = this->view->viewPages.size();
Settings* settings = this->view->getControl()->getSettings();
// get from mapper (some may have changed to accommodate paired setting etc.)
bool const isPairedPages = this->mapper.isPairedPages();
auto const rows = this->pc.heightRows.size();
auto const columns = this->pc.widthCols.size();
// add space around the entire page area to accommodate older Wacom tablets with limited sense area.
auto v_padding = XOURNAL_PADDING;
if (settings->getUnlimitedScrolling()) {
v_padding += static_cast<int>(gtk_adjustment_get_page_size(scrollHandling->getVertical()));
} else if (settings->getAddVerticalSpace()) {
v_padding += settings->getAddVerticalSpaceAmountAbove();
}
auto h_padding = XOURNAL_PADDING;
if (settings->getUnlimitedScrolling()) {
h_padding += static_cast<int>(gtk_adjustment_get_page_size(scrollHandling->getHorizontal()));
} else if (settings->getAddHorizontalSpace()) {
h_padding += settings->getAddHorizontalSpaceAmountLeft();
}
auto const centeringXBorder = (width - as_signed(pc.minWidth)) / 2;
auto const centeringYBorder = (height - as_signed(pc.minHeight)) / 2;
using SBig = decltype(as_signed(h_padding * centeringXBorder));
auto const borderX = static_cast<double>(std::max<SBig>(h_padding, centeringXBorder));
auto const borderY = static_cast<double>(std::max<SBig>(v_padding, centeringYBorder));
// initialize here and x again in loop below.
auto x = borderX;
auto y = borderY;
// Iterate over ALL possible rows and columns.
// We don't know which page, if any, is to be displayed in each row, column - ask the mapper object!
// Then assign that page coordinates with center, left or right justify within row,column grid cell as required.
for (size_t r = 0; r < rows; r++) {
for (size_t c = 0; c < columns; c++) {
auto optionalPage = this->mapper.at({c, r});
if (optionalPage) {
auto& v = this->view->viewPages[*optionalPage];
v->setMappedRowCol(strict_cast<int>(r),
strict_cast<int>(c)); // store row and column for e.g. proper arrow key navigation
auto vDisplayWidth = v->getDisplayWidthDouble();
{
auto paddingLeft = 0.0;
auto paddingRight = 0.0;
auto columnPadding = this->pc.widthCols[c] - vDisplayWidth;
if (isPairedPages && len > 1) {
// pair pages mode
if (c % 2 == 0) {
// align right
paddingLeft = XOURNAL_PADDING_BETWEEN - XOURNAL_ROOM_FOR_SHADOW + columnPadding;
paddingRight = XOURNAL_ROOM_FOR_SHADOW;
} else { // align left
paddingLeft = XOURNAL_ROOM_FOR_SHADOW;
paddingRight = XOURNAL_PADDING_BETWEEN - XOURNAL_ROOM_FOR_SHADOW + columnPadding;
}
} else { // not paired page mode - center
paddingLeft = XOURNAL_PADDING_BETWEEN / 2.0 + columnPadding / 2.0; // center justify
paddingRight = XOURNAL_PADDING_BETWEEN - paddingLeft + columnPadding / 2.0;
}
x += paddingLeft;
v->setX(floor_cast<int>(x)); // set the page position
v->setY(floor_cast<int>(y));
x += vDisplayWidth + paddingRight;
}
} else {
x += this->pc.widthCols[c] + XOURNAL_PADDING_BETWEEN;
}
}
x = borderX;
y += this->pc.heightRows[r] + XOURNAL_PADDING_BETWEEN;
}
this->colXStart.resize(this->pc.widthCols.size());
this->rowYStart.resize(this->pc.heightRows.size());
// accumulated - absolute pixel location for use by getViewAt() and updateVisibility()
auto totalWidth = borderX;
std::transform(
begin(this->pc.widthCols), end(this->pc.widthCols), begin(this->colXStart), [&totalWidth](auto&& widthCol) {
return strict_cast<std::remove_reference_t<decltype(widthCol)>>(totalWidth +=
widthCol + XOURNAL_PADDING_BETWEEN);
});
auto totalHeight = borderY;
std::transform(begin(this->pc.heightRows), end(this->pc.heightRows), begin(this->rowYStart),
[&totalHeight](auto&& heightRow) {
return strict_cast<std::remove_reference_t<decltype(heightRow)>>(
(totalHeight += heightRow + XOURNAL_PADDING_BETWEEN));
});
}
auto Layout::getPaddingAbovePage(size_t pageIndex) const -> int {
const Settings* settings = this->view->getControl()->getSettings();
// User-configured padding above all pages.
auto paddingAbove = XOURNAL_PADDING;
if (settings->getUnlimitedScrolling()) {
paddingAbove += static_cast<int>(gtk_adjustment_get_page_size(scrollHandling->getVertical()));
} else if (settings->getAddVerticalSpace()) {
paddingAbove += settings->getAddVerticalSpaceAmountAbove();
}
// (x, y) coordinate pair gives grid indicies. This handles paired pages
// and different page layouts for us.
auto pageYLocation = this->mapper.at(pageIndex).row;
return strict_cast<int>(as_signed(pageYLocation) * XOURNAL_PADDING_BETWEEN + as_signed(paddingAbove));
}
auto Layout::getPaddingLeftOfPage(size_t pageIndex) const -> int {
bool isPairedPages = this->mapper.isPairedPages();
const Settings* settings = this->view->getControl()->getSettings();
auto paddingBefore = XOURNAL_PADDING;
if (settings->getUnlimitedScrolling()) {
paddingBefore += static_cast<int>(gtk_adjustment_get_page_size(scrollHandling->getHorizontal()));
} else if (settings->getAddHorizontalSpace()) {
paddingBefore += settings->getAddHorizontalSpaceAmountLeft();
}
auto const pageXLocation = as_signed(this->mapper.at(pageIndex).col);
// No page pairing or we haven't rendered enough pages in the row for
// page pairing to have an effect,
if (!isPairedPages) {
return strict_cast<int>(pageXLocation * XOURNAL_PADDING_BETWEEN + XOURNAL_PADDING_BETWEEN / 2 +
as_signed(paddingBefore));
} else {
auto columnPadding =
XOURNAL_PADDING_BETWEEN + strict_cast<int>(pageXLocation / 2) * (XOURNAL_PADDING_BETWEEN * 2);
if (pageXLocation % 2 == 0) {
return strict_cast<int>(columnPadding - XOURNAL_ROOM_FOR_SHADOW + paddingBefore);
} else {
return strict_cast<int>(columnPadding + XOURNAL_ROOM_FOR_SHADOW + paddingBefore);
}
}
}
void Layout::setLayoutSize(int width, int height) { this->scrollHandling->setLayoutSize(width, height); }
void Layout::scrollRelative(double x, double y) {
if (this->view->getControl()->getSettings()->isPresentationMode()) {
return;
}
gtk_adjustment_set_value(scrollHandling->getHorizontal(),
gtk_adjustment_get_value(scrollHandling->getHorizontal()) + x);
gtk_adjustment_set_value(scrollHandling->getVertical(),
gtk_adjustment_get_value(scrollHandling->getVertical()) + y);
}
void Layout::scrollAbs(double x, double y) {
if (this->view->getControl()->getSettings()->isPresentationMode()) {
return;
}
gtk_adjustment_set_value(scrollHandling->getHorizontal(), x);
gtk_adjustment_set_value(scrollHandling->getVertical(), y);
}
void Layout::ensureRectIsVisible(int x, int y, int width, int height) {
gtk_adjustment_clamp_page(scrollHandling->getHorizontal(), x - 5, x + width + 10);
gtk_adjustment_clamp_page(scrollHandling->getVertical(), y - 5, y + height + 10);
}
auto Layout::getPageViewAt(int x, int y) -> XojPageView* {
// Binary Search:
auto rit = std::lower_bound(this->rowYStart.begin(), this->rowYStart.end(), y);
auto const foundRow = size_t(std::distance(this->rowYStart.begin(), rit));
auto cit = std::lower_bound(this->colXStart.begin(), this->colXStart.end(), x);
auto const foundCol = size_t(std::distance(this->colXStart.begin(), cit));
auto optionalPage = this->mapper.at({foundCol, foundRow});
if (optionalPage && this->view->viewPages[*optionalPage]->containsPoint(x, y, false)) {
return this->view->viewPages[*optionalPage].get();
}
return nullptr;
}
auto Layout::getPageIndexAtGridMap(size_t row, size_t col) -> std::optional<size_t> {
return this->mapper.at({col, row}); // watch out.. x,y --> c,r
}
auto Layout::getMinimalHeight() const -> int {
std::lock_guard g{pc.m};
if (!pc.valid) {
recalculate_int();
}
return strict_cast<int>(this->pc.minHeight);
}
auto Layout::getMinimalWidth() const -> int {
std::lock_guard g{pc.m};
if (!pc.valid) {
recalculate_int();
}
return strict_cast<int>(this->pc.minWidth);
}
| 18,236
|
C++
|
.cpp
| 361
| 41.578947
| 120
| 0.630423
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,525
|
PageView.cpp
|
xournalpp_xournalpp/src/core/gui/PageView.cpp
|
#include "PageView.h"
#include <algorithm> // for max, find_if
#include <cinttypes> // for int64_t
#include <cstdint> // for int64_t
#include <cstdlib> // for size_t
#include <iomanip> // for operator<<, quoted
#include <memory> // for unique_ptr, make_...
#include <optional> // for optional
#include <sstream> // for operator<<, basic...
#include <tuple> // for tuple, tie
#include <utility> // for move
#include <gdk/gdk.h> // for GdkRectangle, Gdk...
#include <gdk/gdkkeysyms.h> // for GDK_KEY_Escape
#include <glib-object.h> // for G_CALLBACK, g_sig...
#include <glib.h> // for gint, g_free, g_g...
#include <gtk/gtk.h> // for GtkWidget, gtk_co...
#include "control/AudioController.h" // for AudioController
#include "control/Control.h" // for Control
#include "control/ScrollHandler.h" // for ScrollHandler
#include "control/SearchControl.h" // for SearchControl
#include "control/Tool.h" // for Tool
#include "control/ToolEnums.h" // for DRAWING_TYPE_SPLINE
#include "control/ToolHandler.h" // for ToolHandler
#include "control/jobs/XournalScheduler.h" // for XournalScheduler
#include "control/layer/LayerController.h" // for LayerControl
#include "control/settings/Settings.h" // for Settings
#include "control/tools/ArrowHandler.h" // for ArrowHandler
#include "control/tools/CoordinateSystemHandler.h" // for CoordinateSystemH...
#include "control/tools/EditSelection.h" // for EditSelection
#include "control/tools/EllipseHandler.h" // for EllipseHandler
#include "control/tools/EraseHandler.h" // for EraseHandler
#include "control/tools/ImageHandler.h" // for ImageHandler
#include "control/tools/ImageSizeSelection.h" // for ImageSizeSelection
#include "control/tools/InputHandler.h" // for InputHandler
#include "control/tools/PdfElemSelection.h" // for PdfElemSelection
#include "control/tools/RectangleHandler.h" // for RectangleHandler
#include "control/tools/RulerHandler.h" // for RulerHandler
#include "control/tools/Selection.h" // for RectSelection
#include "control/tools/SplineHandler.h" // for SplineHandler
#include "control/tools/StrokeHandler.h" // for StrokeHandler
#include "control/tools/TextEditor.h" // for TextEditor, TextE...
#include "control/tools/VerticalToolHandler.h" // for VerticalToolHandler
#include "gui/FloatingToolbox.h" // for FloatingToolbox
#include "gui/MainWindow.h" // for MainWindow
#include "gui/PdfFloatingToolbox.h" // for PdfFloatingToolbox
#include "gui/SearchBar.h" // for SearchBar
#include "gui/inputdevices/PositionInputData.h" // for PositionInputData
#include "model/Document.h" // for Document
#include "model/Element.h" // for Element, ELEMENT_...
#include "model/Layer.h" // for Layer, Layer::Index
#include "model/LinkDestination.h" // for LinkDestination
#include "model/PageRef.h" // for PageRef
#include "model/Stroke.h" // for Stroke
#include "model/TexImage.h" // for TexImage
#include "model/Text.h" // for Text
#include "model/XojPage.h" // for XojPage
#include "pdf/base/XojPdfAction.h" // for XojPdfAction
#include "pdf/base/XojPdfDocument.h" // for XojPdfDocument
#include "pdf/base/XojPdfPage.h" // for XojPdfRectangle
#include "undo/DeleteUndoAction.h" // for DeleteUndoAction
#include "undo/InsertUndoAction.h" // for InsertUndoAction
#include "undo/MoveUndoAction.h" // for MoveUndoAction
#include "undo/TextBoxUndoAction.h" // for TextBoxUndoAction
#include "undo/UndoRedoHandler.h" // for UndoRedoHandler
#include "util/Assert.h" // for xoj_assert
#include "util/Color.h" // for rgb_to_GdkRGBA
#include "util/Range.h" // for Range
#include "util/Rectangle.h" // for Rectangle
#include "util/Util.h" // for npos
#include "util/XojMsgBox.h" // for XojMsgBox
#include "util/gtk4_helper.h" // for gtk_box_append
#include "util/i18n.h" // for _F, FC, FS, _
#include "util/raii/CLibrariesSPtr.h" // for adopt
#include "util/safe_casts.h" // for ceil_cast, floor_cast, round_cast
#include "util/serdesstream.h" // for serdes_stream
#include "view/DebugShowRepaintBounds.h" // for IF_DEBUG_REPAINT
#include "view/overlays/OverlayView.h" // for OverlayView, Tool...
#include "view/overlays/PdfElementSelectionView.h" // for PdfElementSelecti...
#include "view/overlays/SearchResultView.h" // for SearchResultView
#include "view/overlays/SelectionView.h" // for SelectionView
#include "view/overlays/TextEditionView.h" // for TextEditionView
#include "PageViewFindObjectHelper.h" // for SelectObject, Pla...
#include "RepaintHandler.h" // for RepaintHandler
#include "XournalView.h" // for XournalView
#include "XournalppCursor.h" // for XournalppCursor
#include "filesystem.h" // for path
class OverlayBase;
using std::string;
using xoj::util::Rectangle;
XojPageView::XojPageView(XournalView* xournal, const PageRef& page):
page(page),
xournal(xournal),
settings(xournal->getControl()->getSettings()),
eraser(std::make_unique<EraseHandler>(xournal->getControl()->getUndoRedoHandler(),
xournal->getControl()->getDocument(), this->page,
xournal->getControl()->getToolHandler(), this)),
oldtext(nullptr) {
this->registerToHandler(this->page);
}
XojPageView::~XojPageView() {
this->unregisterFromHandler();
this->xournal->getControl()->getScheduler()->removePage(this);
this->overlayViews.clear();
endText();
deleteViewBuffer(); // Ensures the mutex is locked during the buffer's destruction
}
void XojPageView::addOverlayView(std::unique_ptr<xoj::view::OverlayView> overlay) {
this->overlayViews.emplace_back(std::move(overlay));
}
void XojPageView::setIsVisible(bool visible) { this->visible = visible; }
void XojPageView::deleteViewBuffer() {
std::lock_guard lock(this->drawingMutex);
this->buffer.reset();
}
auto XojPageView::containsPoint(int x, int y, bool local) const -> bool {
if (!local) {
bool leftOk = this->getX() <= x;
bool rightOk = x <= this->getX() + this->getDisplayWidth();
bool topOk = this->getY() <= y;
bool bottomOk = y <= this->getY() + this->getDisplayHeight();
return leftOk && rightOk && topOk && bottomOk;
}
return x >= 0 && y >= 0 && x <= this->getWidth() && y <= this->getHeight();
}
auto XojPageView::searchTextOnPage(const std::string& text, size_t index, size_t* occurrences,
XojPdfRectangle* matchRect) -> bool {
if (!this->search) {
if (text.empty()) {
return true;
}
auto pNr = this->page->getPdfPageNr();
XojPdfPageSPtr pdf = nullptr;
if (pNr != npos) {
Document* doc = xournal->getControl()->getDocument();
doc->lock();
pdf = doc->getPdfPage(pNr);
doc->unlock();
}
this->search = std::make_unique<SearchControl>(page, pdf);
this->overlayViews.emplace_back(std::make_unique<xoj::view::SearchResultView>(
this->search.get(), this, settings->getSelectionColor(), settings->getActiveSelectionColor()));
}
bool found = this->search->search(text, index, occurrences, matchRect);
repaintPage();
return found;
}
void XojPageView::endText() { this->textEditor.reset(); }
void XojPageView::startText(double x, double y) {
this->xournal->endTextAllPages(this);
this->xournal->getControl()->getSearchBar()->showSearchBar(false);
if (this->textEditor != nullptr) {
const Text* text = this->textEditor->getTextElement();
GdkRectangle matchRect = {gint(x), gint(y), 1, 1};
if (!text->intersectsArea(&matchRect)) {
endText();
} else {
this->textEditor->mousePressed(x - text->getX(), y - text->getY());
}
}
if (this->textEditor == nullptr) {
this->textEditor = std::make_unique<TextEditor>(xournal->getControl(), page, xournal->getWidget(), x, y);
this->overlayViews.emplace_back(std::make_unique<xoj::view::TextEditionView>(this->textEditor.get(), this));
}
}
#ifndef NDEBUG
// used in xoj_assert()
[[maybe_unused]] static bool hasNoViewOf(const std::vector<std::unique_ptr<xoj::view::OverlayView>>& views,
const OverlayBase* o) {
return std::find_if(views.begin(), views.end(), [o](auto& v) { return v->isViewOf(o); }) == views.end();
}
#endif
static void eraseViewsOf(std::vector<std::unique_ptr<xoj::view::OverlayView>>& views, const OverlayBase* o) {
views.erase(std::remove_if(views.begin(), views.end(), [o](auto& v) { return v->isViewOf(o); }), views.end());
xoj_assert(hasNoViewOf(views, o));
}
void XojPageView::endSpline() {
if (SplineHandler* h = dynamic_cast<SplineHandler*>(this->inputHandler.get()); h) {
h->finalizeSpline();
xoj_assert(hasNoViewOf(overlayViews, inputHandler.get()));
this->inputHandler.reset();
}
}
auto XojPageView::onButtonPressEvent(const PositionInputData& pos) -> bool {
if (currentSequenceDeviceId) {
// An input sequence is already under way from another device
return false;
}
currentSequenceDeviceId = pos.deviceId;
Control* control = xournal->getControl();
if (!this->selected) {
control->firePageSelected(this->page);
}
ToolHandler* h = control->getToolHandler();
double x = pos.x;
double y = pos.y;
if (x < 0 || y < 0) {
return false;
}
double zoom = xournal->getZoom();
x /= zoom;
y /= zoom;
XournalppCursor* cursor = xournal->getCursor();
cursor->setMouseDown(true);
if (((h->getToolType() == TOOL_PEN || h->getToolType() == TOOL_HIGHLIGHTER) &&
h->getDrawingType() != DRAWING_TYPE_SPLINE) ||
(h->getToolType() == TOOL_ERASER && h->getEraserType() == ERASER_TYPE_WHITEOUT)) {
if (this->inputHandler) {
/**
* Due to https://github.com/xournalpp/xournalpp/issues/4377
* some devices under some configurations can start an action while another one has already started
* This is a workaround to avoid mem leaks and segfaults
* This `if` statement can probably be replaced by an `assert` once #4377 is fixed
*/
g_warning("InputHandler already exists upon XojPageView::onButtonPressEvent. Deleting it (and its views)");
eraseViewsOf(this->overlayViews, this->inputHandler.get());
this->inputHandler.reset();
}
Control* control = this->xournal->getControl();
switch (h->getDrawingType()) {
case DRAWING_TYPE_LINE:
this->inputHandler = std::make_unique<RulerHandler>(control, getPage());
break;
case DRAWING_TYPE_RECTANGLE:
this->inputHandler = std::make_unique<RectangleHandler>(control, getPage());
break;
case DRAWING_TYPE_ELLIPSE:
this->inputHandler = std::make_unique<EllipseHandler>(control, getPage());
break;
case DRAWING_TYPE_ARROW:
this->inputHandler = std::make_unique<ArrowHandler>(control, getPage(), false);
break;
case DRAWING_TYPE_DOUBLE_ARROW:
this->inputHandler = std::make_unique<ArrowHandler>(control, getPage(), true);
break;
case DRAWING_TYPE_COORDINATE_SYSTEM:
this->inputHandler = std::make_unique<CoordinateSystemHandler>(control, getPage());
break;
default:
this->inputHandler = std::make_unique<StrokeHandler>(control, getPage());
}
this->inputHandler->onButtonPressEvent(pos, zoom);
this->overlayViews.emplace_back(this->inputHandler->createView(this));
} else if ((h->getToolType() == TOOL_PEN || h->getToolType() == TOOL_HIGHLIGHTER) &&
h->getDrawingType() == DRAWING_TYPE_SPLINE) {
if (!this->inputHandler) {
this->inputHandler = std::make_unique<SplineHandler>(this->xournal->getControl(), getPage());
this->inputHandler->onButtonPressEvent(pos, zoom);
this->overlayViews.emplace_back(this->inputHandler->createView(this));
} else {
this->inputHandler->onButtonPressEvent(pos, zoom);
}
} else if (h->getToolType() == TOOL_ERASER) {
this->eraser->erase(x, y);
this->inEraser = true;
} else if (h->getToolType() == TOOL_VERTICAL_SPACE) {
if (this->verticalSpace) {
control->getUndoRedoHandler()->addUndoAction(this->verticalSpace->finalize());
this->verticalSpace.reset();
}
auto* zoomControl = this->getXournal()->getControl()->getZoomControl();
this->verticalSpace = std::make_unique<VerticalToolHandler>(this->page, this->settings, y, pos.isControlDown());
this->overlayViews.emplace_back(this->verticalSpace->createView(this, zoomControl, this->settings));
} else if (h->getToolType() == TOOL_SELECT_RECT || h->getToolType() == TOOL_SELECT_REGION ||
h->getToolType() == TOOL_SELECT_MULTILAYER_RECT || h->getToolType() == TOOL_SELECT_MULTILAYER_REGION ||
h->getToolType() == TOOL_PLAY_OBJECT || h->getToolType() == TOOL_SELECT_OBJECT ||
h->getToolType() == TOOL_SELECT_PDF_TEXT_LINEAR || h->getToolType() == TOOL_SELECT_PDF_TEXT_RECT) {
if (h->getToolType() == TOOL_SELECT_RECT) {
if (!selection) {
this->selection = std::make_unique<RectSelection>(x, y);
this->overlayViews.emplace_back(std::make_unique<xoj::view::SelectionView>(
this->selection.get(), this, this->settings->getSelectionColor()));
} else {
xoj_assert_message(
settings->getInputSystemTPCButtonEnabled(),
"the selection has already been created by a stylus button press while the stylus was "
"hovering!");
}
} else if (h->getToolType() == TOOL_SELECT_REGION) {
if (!selection) {
this->selection = std::make_unique<RegionSelect>(x, y);
this->overlayViews.emplace_back(std::make_unique<xoj::view::SelectionView>(
this->selection.get(), this, this->settings->getSelectionColor()));
} else {
xoj_assert_message(
settings->getInputSystemTPCButtonEnabled(),
"the selection has already been created by a stylus button press while the stylus was "
"hovering!");
}
} else if (h->getToolType() == TOOL_SELECT_MULTILAYER_RECT) {
if (!selection) {
this->selection = std::make_unique<RectSelection>(x, y, /*multiLayer*/ true);
this->overlayViews.emplace_back(std::make_unique<xoj::view::SelectionView>(
this->selection.get(), this, this->settings->getSelectionColor()));
} else {
xoj_assert_message(
settings->getInputSystemTPCButtonEnabled(),
"the selection has already been created by a stylus button press while the stylus was "
"hovering!");
}
} else if (h->getToolType() == TOOL_SELECT_MULTILAYER_REGION) {
if (!selection) {
this->selection = std::make_unique<RegionSelect>(x, y, /*multiLayer*/ true);
this->overlayViews.emplace_back(std::make_unique<xoj::view::SelectionView>(
this->selection.get(), this, this->settings->getSelectionColor()));
} else {
xoj_assert_message(
settings->getInputSystemTPCButtonEnabled(),
"the selection has already been created by a stylus button press while the stylus was "
"hovering!");
}
} else if (h->getToolType() == TOOL_SELECT_PDF_TEXT_LINEAR || h->getToolType() == TOOL_SELECT_PDF_TEXT_RECT) {
// so if we selected something && the pdf selection toolbox is hidden && we hit within the selection
// we could call the pdf floating toolbox again
auto* pdfToolbox = control->getWindow()->getPdfToolbox();
if (pdfToolbox->hasSelection()) {
bool isPdfToolboxHidden = pdfToolbox->isHidden();
bool keepOldSelection = isPdfToolboxHidden && pdfToolbox->getSelection()->contains(x, y);
if (!keepOldSelection) {
pdfToolbox->userCancelSelection();
repaintPage();
} else {
showPdfToolbox(pos);
}
}
if (this->page->getPdfPageNr() != npos && !pdfToolbox->hasSelection()) {
pdfToolbox->selectionStyle = PdfElemSelection::selectionStyleForToolType(h->getToolType());
auto sel = pdfToolbox->newSelection(x, y);
this->overlayViews.emplace_back(
std::make_unique<xoj::view::PdfElementSelectionView>(sel, this, settings->getSelectionColor()));
}
} else if (h->getToolType() == TOOL_SELECT_OBJECT) {
SelectObject select(this);
if (pos.isShiftDown() && xournal->getSelection()) {
select.atAggregate(x, y);
} else {
select.at(x, y);
}
} else if (h->getToolType() == TOOL_PLAY_OBJECT) {
PlayObject play(this);
play.at(x, y);
if (play.playbackStatus) {
auto& status = *play.playbackStatus;
if (!status.success) {
string message = FS(_F("Unable to play audio recording {1}") % status.filename.u8string());
XojMsgBox::showErrorToUser(this->xournal->getControl()->getGtkWindow(), message);
}
}
}
} else if (h->getToolType() == TOOL_TEXT) {
startText(x, y);
} else if (h->getToolType() == TOOL_IMAGE) {
// start selecting the size for the image
this->imageSizeSelection = std::make_unique<ImageSizeSelection>(x, y);
this->overlayViews.emplace_back(std::make_unique<xoj::view::ImageSizeSelectionView>(
this->imageSizeSelection.get(), this, settings->getSelectionColor()));
}
this->onButtonClickEvent(pos);
return true;
}
auto XojPageView::onButtonClickEvent(const PositionInputData& pos) -> bool {
Control* control = xournal->getControl();
double x = pos.x;
double y = pos.y;
if (x < 0 || y < 0) {
return false;
}
ToolHandler* h = control->getToolHandler();
if (h->getToolType() == TOOL_FLOATING_TOOLBOX) {
this->showFloatingToolbox(pos);
}
return true;
}
auto XojPageView::onButtonDoublePressEvent(const PositionInputData& pos) -> bool {
// This method assumes that it is called after onButtonPressEvent but before
// onButtonReleaseEvent
double zoom = this->xournal->getZoom();
double x = pos.x / zoom;
double y = pos.y / zoom;
if (x < 0 || y < 0) {
return false;
}
ToolHandler* toolHandler = this->xournal->getControl()->getToolHandler();
ToolType toolType = toolHandler->getToolType();
DrawingType drawingType = toolHandler->getDrawingType();
EditSelection* selection = xournal->getSelection();
bool hasNoModifiers = !pos.isShiftDown() && !pos.isControlDown();
if (hasNoModifiers && selection != nullptr) {
// Find a selected object under the cursor, if possible. The selection doesn't change the
// element coordinates until it is finalized, so we need to use position relative to the
// original coordinates of the selection.
double origx = x - (selection->getXOnView() - selection->getOriginalXOnView());
double origy = y - (selection->getYOnView() - selection->getOriginalYOnView());
const std::vector<Element*>& elems = selection->getElements();
auto it = std::find_if(elems.begin(), elems.end(),
[&](Element* elem) { return elem->intersectsArea(origx - 5, origy - 5, 5, 5); });
if (it != elems.end()) {
// Enter editing mode on the selected object
Element* object = *it;
ElementType elemType = object->getType();
if (elemType == ELEMENT_TEXT) {
this->xournal->clearSelection();
toolHandler->selectTool(TOOL_TEXT);
toolHandler->fireToolChanged();
// Simulate a button press; there's too many things that we
// could forget to do if we manually call startText
this->onButtonPressEvent(pos);
} else if (elemType == ELEMENT_TEXIMAGE) {
Control* control = this->xournal->getControl();
if (elems.size() > 1) {
// Deselect the other elements
this->xournal->clearSelection();
auto sel = SelectionFactory::createFromElementOnActiveLayer(control, getPage(), this, object);
this->xournal->setSelection(sel.release());
}
control->runLatex();
}
}
} else if (toolType == TOOL_TEXT) {
this->startText(x, y);
this->textEditor->selectAtCursor(TextEditor::SelectType::WORD);
} else if (toolType == TOOL_SELECT_PDF_TEXT_LINEAR || toolType == TOOL_SELECT_PDF_TEXT_RECT) {
auto* pdfToolbox = this->xournal->getControl()->getWindow()->getPdfToolbox();
if (auto* selection = pdfToolbox->getSelection()) {
pdfToolbox->selectionStyle = XojPdfPageSelectionStyle::Word;
selection->currentPos(x, y, pdfToolbox->selectionStyle);
}
} else if (drawingType == DRAWING_TYPE_SPLINE) {
if (this->inputHandler) {
this->inputHandler->onButtonDoublePressEvent(pos, zoom);
xoj_assert(hasNoViewOf(overlayViews, inputHandler.get()));
this->inputHandler.reset();
}
}
return true;
}
auto XojPageView::onButtonTriplePressEvent(const PositionInputData& pos) -> bool {
// This method assumes that it is called after onButtonDoubleEvent but before
// onButtonReleaseEvent
double zoom = this->xournal->getZoom();
double x = pos.x / zoom;
double y = pos.y / zoom;
if (x < 0 || y < 0) {
return false;
}
ToolHandler* toolHandler = this->xournal->getControl()->getToolHandler();
ToolType toolType = toolHandler->getToolType();
if (toolType == TOOL_TEXT) {
this->startText(x, y);
this->textEditor->selectAtCursor(TextEditor::SelectType::PARAGRAPH);
} else if (toolType == TOOL_SELECT_PDF_TEXT_LINEAR || toolType == TOOL_SELECT_PDF_TEXT_RECT) {
auto* pdfToolbox = this->xournal->getControl()->getWindow()->getPdfToolbox();
if (auto* selection = pdfToolbox->getSelection()) {
pdfToolbox->selectionStyle = XojPdfPageSelectionStyle::Line;
selection->currentPos(x, y, pdfToolbox->selectionStyle);
}
}
return true;
}
auto XojPageView::onMotionNotifyEvent(const PositionInputData& pos) -> bool {
if (currentSequenceDeviceId && currentSequenceDeviceId != pos.deviceId) {
// This motion event is not from the device which started the sequence: reject it
return false;
}
double zoom = xournal->getZoom();
double x = pos.x / zoom;
double y = pos.y / zoom;
ToolHandler* h = xournal->getControl()->getToolHandler();
auto* pdfToolbox = this->xournal->getControl()->getWindow()->getPdfToolbox();
if (this->inputHandler && this->inputHandler->onMotionNotifyEvent(pos, zoom)) {
// input handler used this event
} else if (this->imageSizeSelection) {
this->imageSizeSelection->updatePosition(x, y);
} else if (this->selection) {
this->selection->currentPos(x, y);
} else if (auto* selection = pdfToolbox->getSelection(); selection && !selection->isFinalized()) {
selection->currentPos(x, y, pdfToolbox->selectionStyle);
} else if (this->verticalSpace) {
this->verticalSpace->currentPos(x, y);
} else if (this->textEditor) {
XournalppCursor* cursor = getXournal()->getCursor();
cursor->setInvisible(false);
const Text* text = this->textEditor->getTextElement();
this->textEditor->mouseMoved(x - text->getX(), y - text->getY());
} else if (h->getToolType() == TOOL_ERASER && h->getEraserType() != ERASER_TYPE_WHITEOUT && this->inEraser) {
this->eraser->erase(x, y);
}
return false;
}
void XojPageView::onSequenceCancelEvent(DeviceId deviceId) {
if (currentSequenceDeviceId != deviceId) {
// This motion event is not from the device which started the sequence: reject it
return;
}
currentSequenceDeviceId.reset();
if (this->inputHandler) {
this->inputHandler->onSequenceCancelEvent();
if (auto* h = dynamic_cast<SplineHandler*>(this->inputHandler.get()); h) {
// SplineHandler can survive a sequence cancellation
if (!h->getStroke()) {
xoj_assert(hasNoViewOf(overlayViews, inputHandler.get()));
this->inputHandler.reset();
}
} else {
xoj_assert(hasNoViewOf(overlayViews, inputHandler.get()));
this->inputHandler.reset();
}
}
}
void XojPageView::onTapEvent(const PositionInputData& pos) {
if (this->inputHandler) {
/*
* We only want tap events to trigger special actions if no tool is currently under use
* (e.g. a spline is currently under edition)
* Feed the event to the InputHandler as a click
*/
const double zoom = getZoom();
this->inputHandler->onButtonPressEvent(pos, zoom);
this->inputHandler->onButtonReleaseEvent(pos, zoom);
if (!this->inputHandler->getStroke()) {
// The InputHandler finalized its edition
xoj_assert(hasNoViewOf(overlayViews, inputHandler.get()));
this->inputHandler.reset();
}
return;
}
auto* settings = xournal->getControl()->getSettings();
bool doAction = settings->getDoActionOnStrokeFiltered();
if (settings->getTrySelectOnStrokeFiltered()) {
double zoom = xournal->getZoom();
SelectObject select(this);
if (pos.isShiftDown()) {
if (select.atAggregate(pos.x / zoom, pos.y / zoom)) {
doAction = false; // selection made.. no action.
}
} else {
if (select.at(pos.x / zoom, pos.y / zoom)) {
doAction = false; // selection made.. no action.
}
}
}
if (doAction) // pop up a menu
{
this->showFloatingToolbox(pos);
}
}
auto XojPageView::showPdfToolbox(const PositionInputData& pos) -> void {
// Compute coords of the canvas relative to the application window origin.
gint wx = 0, wy = 0;
GtkWidget* widget = xournal->getWidget();
gtk_widget_translate_coordinates(widget, gtk_widget_get_toplevel(widget), 0, 0, &wx, &wy);
// Add the position of the current page view widget (relative to canvas origin)
// and add the input position (relative to the current page view widget).
wx += this->getX() + round_cast<gint>(pos.x);
wy += this->getY() + round_cast<gint>(pos.y);
auto* pdfToolbox = this->xournal->getControl()->getWindow()->getPdfToolbox();
pdfToolbox->show(wx, wy);
}
void XojPageView::deleteView(xoj::view::OverlayView* view) {
auto it = std::find_if(this->overlayViews.begin(), this->overlayViews.end(),
[view](const auto& v) { return view == v.get(); });
if (it != this->overlayViews.end()) {
this->overlayViews.erase(it);
}
}
auto XojPageView::onButtonReleaseEvent(const PositionInputData& pos) -> bool {
if (currentSequenceDeviceId != pos.deviceId) {
// This event is not from the device which started the sequence: reject it
return false;
}
currentSequenceDeviceId.reset();
Control* control = xournal->getControl();
if (this->inputHandler) {
double zoom = xournal->getZoom();
this->inputHandler->onButtonReleaseEvent(pos, zoom);
ToolHandler* h = control->getToolHandler();
bool isDrawingTypeSpline = h->getDrawingType() == DRAWING_TYPE_SPLINE;
if (!isDrawingTypeSpline || !this->inputHandler->getStroke()) { // The Spline Tool finalizes drawing manually
xoj_assert(hasNoViewOf(overlayViews, inputHandler.get()));
this->inputHandler.reset();
}
}
if (this->inEraser) {
this->inEraser = false;
Document* doc = this->xournal->getControl()->getDocument();
doc->lock();
this->eraser->finalize();
doc->unlock();
}
if (this->verticalSpace) {
control->getUndoRedoHandler()->addUndoAction(this->verticalSpace->finalize());
this->verticalSpace.reset();
}
auto* pdfToolbox = control->getWindow()->getPdfToolbox();
if (auto* selection = pdfToolbox->getSelection()) {
if (!selection->isFinalized() && selection->finalizeSelectionAndRepaint(pdfToolbox->selectionStyle)) {
// Selection was created, so reposition the toolbox and display.
showPdfToolbox(pos);
}
}
ToolType toolType = control->getToolHandler()->getActiveTool()->getToolType();
if (xoj::tool::isPdfSelectionTool(toolType)) {
const double zoom = xournal->getZoom();
// Attempt PDF selection
auto& pdfDoc = this->xournal->getDocument()->getPdfDocument();
if (this->getPage()->getPdfPageNr() != npos) {
auto page = pdfDoc.getPage(this->getPage()->getPdfPageNr());
const double pageX = pos.x / zoom;
const double pageY = pos.y / zoom;
displayLinkPopover(page, pageX, pageY);
}
}
if (this->selection) {
const bool aggregate = pos.isShiftDown() && xournal->getSelection();
size_t layerOfFinalizedSel = this->selection->finalize(this->page, aggregate, control->getDocument());
if (layerOfFinalizedSel) {
xournal->setSelection([&]() {
if (aggregate) {
// Aggregate selection
auto sel = selection->releaseElements();
return SelectionFactory::addElementsFromActiveLayer(control, xournal->getSelection(), sel);
} else {
// if selection->multiLayer == true, the selected objects might be on another layer
xournal->getControl()->getLayerController()->switchToLay(layerOfFinalizedSel);
return SelectionFactory::createFromElementsOnActiveLayer(control, page, this,
selection->releaseElements());
}
}()
.release());
} else if (const double zoom = xournal->getZoom(); selection->userTapped(zoom)) {
if (aggregate) {
SelectObject(this).atAggregate(pos.x / zoom, pos.y / zoom);
} else {
SelectObject(this).at(pos.x / zoom, pos.y / zoom, this->selection->isMultiLayerSelection());
}
}
this->selection.reset();
} else if (this->textEditor) {
this->textEditor->mouseReleased();
}
if (this->imageSizeSelection) {
// size for image has been selected, now the image can be added
auto spaceForImage = this->imageSizeSelection->getSelectedSpace();
ImageHandler imgHandler(control);
imgHandler.insertImageWithSize(this->page, spaceForImage);
imageSizeSelection->finalize();
this->imageSizeSelection.reset();
}
return false;
}
auto XojPageView::onKeyPressEvent(const KeyEvent& event) -> bool {
if (this->textEditor) {
if (this->textEditor->onKeyPressEvent(event)) {
return true;
}
} else if (this->inputHandler) {
if (this->inputHandler->onKeyPressEvent(event)) {
return true;
}
} else if (this->verticalSpace) {
if (this->verticalSpace->onKeyPressEvent(event)) {
return true;
}
}
// Esc leaves text edition
if (event.keyval == GDK_KEY_Escape) {
if (this->textEditor) {
endText();
return true;
}
return false;
}
return false;
}
auto XojPageView::onKeyReleaseEvent(const KeyEvent& event) -> bool {
if (this->textEditor && this->textEditor->onKeyReleaseEvent(event)) {
return true;
}
if (this->inputHandler && this->inputHandler->onKeyReleaseEvent(event)) {
DrawingType drawingType = this->xournal->getControl()->getToolHandler()->getDrawingType();
if (drawingType == DRAWING_TYPE_SPLINE) { // Spline drawing has been finalized
if (this->inputHandler) {
xoj_assert(hasNoViewOf(overlayViews, inputHandler.get()));
this->inputHandler.reset();
}
}
return true;
}
if (this->verticalSpace && this->verticalSpace->onKeyReleaseEvent(event)) {
return true;
}
return false;
}
void XojPageView::rerenderPage() {
this->rerenderComplete = true;
this->xournal->getControl()->getScheduler()->addRerenderPage(this);
}
void XojPageView::repaintPage() const { xournal->getRepaintHandler()->repaintPage(this); }
void XojPageView::repaintArea(double x1, double y1, double x2, double y2) const {
double zoom = xournal->getZoom();
xournal->getRepaintHandler()->repaintPageArea(this, floor_cast<int>(x1 * zoom), floor_cast<int>(y1 * zoom),
ceil_cast<int>(x2 * zoom), ceil_cast<int>(y2 * zoom));
}
void XojPageView::flagDirtyRegion(const Range& rg) const { repaintArea(rg.minX, rg.minY, rg.maxX, rg.maxY); }
void XojPageView::drawAndDeleteToolView(xoj::view::ToolView* v, const Range& rg) {
if (v->isViewOf(this->inputHandler.get()) || v->isViewOf(this->verticalSpace.get()) ||
v->isViewOf(this->textEditor.get())) {
// Draw the inputHandler's view onto the page buffer.
std::lock_guard lock(this->drawingMutex);
if (auto cr = buffer.get(); cr) {
v->drawWithoutDrawingAids(cr);
} else {
rerenderPage();
}
}
this->deleteOverlayView(v, rg);
}
void XojPageView::deleteOverlayView(xoj::view::OverlayView* v, const Range& rg) {
this->deleteView(v);
if (!rg.empty()) {
xoj_assert(rg.isValid());
this->flagDirtyRegion(rg);
}
}
double XojPageView::getZoom() const { return xournal->getZoom(); }
ZoomControl* XojPageView::getZoomControl() const { return this->getXournal()->getControl()->getZoomControl(); }
Range XojPageView::getVisiblePart() const {
std::unique_ptr<xoj::util::Rectangle<double>> rect(xournal->getVisibleRect(this));
if (rect) {
return Range(*rect);
}
return Range(); // empty range
}
double XojPageView::getWidth() const { return page->getWidth(); }
double XojPageView::getHeight() const { return page->getHeight(); }
auto XojPageView::toWindowCoordinates(const xoj::util::Rectangle<double>& r) const -> xoj::util::Rectangle<double> {
double zoom = this->getZoom();
return {r.x * zoom + this->getX(), r.y * zoom + this->getY(), r.width * zoom, r.height * zoom};
}
void XojPageView::rerenderRect(double x, double y, double width, double height) {
if (this->rerenderComplete) {
return;
}
auto rect = Rectangle<double>{x, y, width, height};
this->repaintRectMutex.lock();
for (auto&& r: this->rerenderRects) {
// its faster to redraw only one rect than repaint twice the same area
// so loop through the rectangles to be redrawn, if new rectangle
// intersects any of them, replace it by the union with the new one
if (r.intersects(rect)) {
r.unite(rect);
this->repaintRectMutex.unlock();
return;
}
}
this->rerenderRects.push_back(rect);
this->repaintRectMutex.unlock();
this->xournal->getControl()->getScheduler()->addRerenderPage(this);
}
void XojPageView::setSelected(bool selected) {
this->selected = selected;
if (selected) {
this->xournal->requestFocus();
this->xournal->getRepaintHandler()->repaintPageBorder(this);
} else {
this->endSpline();
}
}
auto XojPageView::cut() -> bool {
if (this->textEditor) {
this->textEditor->cutToClipboard();
return true;
}
return false;
}
auto XojPageView::copy() -> bool {
if (this->textEditor) {
this->textEditor->copyToClipboard();
return true;
}
return false;
}
auto XojPageView::paste() -> bool {
if (this->textEditor) {
this->textEditor->pasteFromClipboard();
return true;
}
return false;
}
auto XojPageView::actionDelete() -> bool {
if (this->textEditor) {
this->textEditor->deleteFromCursor(GTK_DELETE_CHARS, 1);
return true;
}
return false;
}
void XojPageView::drawLoadingPage(cairo_t* cr) {
static const string txtLoading = _("Loading...");
cairo_set_source_rgb(cr, 1, 1, 1);
cairo_rectangle(cr, 0, 0, page->getWidth(), page->getHeight());
cairo_fill(cr);
cairo_set_source_rgb(cr, 0.5, 0.5, 0.5);
cairo_select_font_face(cr, "Sans", CAIRO_FONT_SLANT_NORMAL, CAIRO_FONT_WEIGHT_BOLD);
cairo_set_font_size(cr, 32.0);
cairo_text_extents_t ex;
cairo_text_extents(cr, txtLoading.c_str(), &ex);
cairo_move_to(cr, (page->getWidth() - ex.width) / 2 - ex.x_bearing,
(page->getHeight() - ex.height) / 2 - ex.y_bearing);
cairo_show_text(cr, txtLoading.c_str());
rerenderPage();
}
bool XojPageView::displayLinkPopover(std::shared_ptr<XojPdfPage> page, double pageX, double pageY) {
// Search for selected link
const auto links = page->getLinks();
for (auto&& [rect, action]: links) {
std::shared_ptr<const LinkDestination> dest = action->getDestination();
if (!(rect.x1 <= pageX && pageX <= rect.x2 && rect.y1 <= pageY && pageY <= rect.y2)) {
continue;
}
GtkWidget* box = gtk_box_new(GTK_ORIENTATION_VERTICAL, 5);
GtkWidget* popover = makePopover(rect, box);
if (auto uriOpt = dest->getURI()) {
const std::string& uri = uriOpt.value();
char* uriLabel = g_markup_escape_text(uri.c_str(), -1);
auto labelMarkup = serdes_stream<std::stringstream>();
labelMarkup << "<a href=" << std::quoted(uri) << ">" << uriLabel << "</a>";
std::string linkMarkup = labelMarkup.str();
g_free(uriLabel);
GtkWidget* label = gtk_label_new(nullptr);
gtk_label_set_markup(GTK_LABEL(label), linkMarkup.c_str());
gtk_box_append(GTK_BOX(box), label);
} else {
size_t pdfPage = dest->getPdfPage();
Document* doc = xournal->getControl()->getDocument();
doc->lock();
const size_t pageId = doc->findPdfPage(pdfPage);
doc->unlock();
GtkWidget* button{};
if (pageId != npos) {
const auto pageNo = static_cast<int64_t>(pageId + 1);
button = gtk_button_new_with_label(FC(_F("Scroll to page {1}") % pageNo));
} else {
button = gtk_button_new_with_label(FC(_F("Add missing page")));
}
gtk_box_append(GTK_BOX(box), button);
g_signal_connect(
button, "clicked",
G_CALLBACK(+[](GtkButton* bt,
std::tuple<XojPageView*, std::shared_ptr<LinkDestination>, GtkWidget*>* state) {
XojPageView* self;
std::shared_ptr<LinkDestination> dest;
GtkWidget* popover;
std::tie(self, dest, popover) = *state;
self->getXournal()->getControl()->getScrollHandler()->scrollToLinkDest(*dest);
gtk_popover_popdown(GTK_POPOVER(popover));
delete state;
}),
new std::tuple(std::make_tuple(this, dest, popover)));
}
gtk_widget_show_all(popover);
gtk_popover_popup(GTK_POPOVER(popover));
return true;
}
return false;
}
GtkWidget* XojPageView::makePopover(const XojPdfRectangle& rect, GtkWidget* child) {
double zoom = xournal->getZoom();
GtkWidget* popover = gtk_popover_new(this->getXournal()->getWidget());
gtk_popover_set_child(GTK_POPOVER(popover), child);
auto x = floor_cast<int>(this->getX() + rect.x1 * zoom);
auto y = floor_cast<int>(this->getY() + rect.y1 * zoom);
auto w = ceil_cast<int>((rect.x2 - rect.x1) * zoom);
auto h = ceil_cast<int>((rect.y2 - rect.y1) * zoom);
GdkRectangle canvasRect{x, y, w, h};
gtk_popover_set_pointing_to(GTK_POPOVER(popover), &canvasRect);
gtk_popover_set_constrain_to(GTK_POPOVER(popover), GTK_POPOVER_CONSTRAINT_WINDOW);
return popover;
}
auto XojPageView::paintPage(cairo_t* cr, GdkRectangle* rect) -> bool {
double zoom = xournal->getZoom();
xoj::util::CairoSaveGuard saveGuard(cr);
cairo_scale(cr, zoom, zoom);
{
std::lock_guard lock(this->drawingMutex); // Lock the mutex first
xoj::util::CairoSaveGuard saveGuard(cr); // see comment at the end of the scope
if (!this->hasBuffer()) {
drawLoadingPage(cr);
return true;
}
if (this->buffer.getZoom() != zoom) {
rerenderPage();
cairo_pattern_set_filter(cairo_get_source(cr), CAIRO_FILTER_FAST);
}
this->buffer.paintTo(cr);
} // Restore the state of cr and then release the mutex
// restoring the state of cr ensures this->buffer.surface is not longer referenced as the source in cr.
/**
* All the overlay painters below follow the assumption:
* * The given cairo context is in page coordinates: no further scaling/offset is ever required.
*
* To anyone adding another painter here: please keep this assumption true
*/
for (const auto& v: this->overlayViews) {
v->draw(cr);
}
return true;
}
/**
* GETTER / SETTER
*/
auto XojPageView::isSelected() const -> bool { return selected; }
auto XojPageView::hasBuffer() const -> bool { return this->buffer.isInitialized(); }
auto XojPageView::getSelectionColor() -> GdkRGBA { return Util::rgb_to_GdkRGBA(settings->getSelectionColor()); }
auto XojPageView::getTextEditor() -> TextEditor* { return textEditor.get(); }
auto XojPageView::getX() const -> int { return this->dispX; }
void XojPageView::setX(int x) { this->dispX = x; }
auto XojPageView::getY() const -> int { return this->dispY; }
void XojPageView::setY(int y) { this->dispY = y; }
void XojPageView::setMappedRowCol(int row, int col) {
this->mappedRow = row;
this->mappedCol = col;
}
auto XojPageView::getMappedRow() const -> int { return this->mappedRow; }
auto XojPageView::getMappedCol() const -> int { return this->mappedCol; }
auto XojPageView::getPage() const -> const PageRef { return page; }
auto XojPageView::getXournal() const -> XournalView* { return this->xournal; }
auto XojPageView::getDisplayWidth() const -> int {
return round_cast<int>(this->page->getWidth() * this->xournal->getZoom());
}
auto XojPageView::getDisplayHeight() const -> int {
return round_cast<int>(this->page->getHeight() * this->xournal->getZoom());
}
auto XojPageView::getDisplayWidthDouble() const -> double { return this->page->getWidth() * this->xournal->getZoom(); }
auto XojPageView::getDisplayHeightDouble() const -> double {
return this->page->getHeight() * this->xournal->getZoom();
}
auto XojPageView::getSelectedTex() -> TexImage* {
EditSelection* theSelection = this->xournal->getSelection();
if (!theSelection) {
return nullptr;
}
for (Element* e: theSelection->getElements()) {
if (e->getType() == ELEMENT_TEXIMAGE) {
return dynamic_cast<TexImage*>(e);
}
}
return nullptr;
}
auto XojPageView::getSelectedText() -> Text* {
EditSelection* theSelection = this->xournal->getSelection();
if (!theSelection) {
return nullptr;
}
for (Element* e: theSelection->getElements()) {
if (e->getType() == ELEMENT_TEXT) {
return dynamic_cast<Text*>(e);
}
}
return nullptr;
}
auto XojPageView::getRect() const -> Rectangle<double> {
return Rectangle<double>(getX(), getY(), getDisplayWidth(), getDisplayHeight());
}
void XojPageView::rectChanged(Rectangle<double>& rect) { rerenderRect(rect.x, rect.y, rect.width, rect.height); }
void XojPageView::rangeChanged(Range& range) { rerenderRange(range); }
void XojPageView::pageChanged() { rerenderPage(); }
void XojPageView::elementChanged(Element* elem) {
/*
* The input handlers issue an elementChanged event when creating an element.
* There is however no need to redraw the element in this case: the element was already painted to the buffer via a
* call to drawAndDeleteToolView
* There are a couple of exceptions:
* * if the added element is not on the top-most layer, a rerendering is required to draw it under the upper layers
* * if the added element overflows out of the visible part of the page, the ToolView may not have drawn to the
* page buffer the part outside the visible area. Rerendering as well
*/
const bool noRerender = inputHandler && elem == inputHandler->getStroke() &&
page->getSelectedLayerId() == page->getLayerCount() &&
getVisiblePart().contains(elem->boundingRect());
if (!noRerender) {
rerenderElement(elem);
}
}
void XojPageView::elementsChanged(const std::vector<Element*>& elements, const Range& range) {
if (!range.empty()) {
rerenderRange(range);
}
}
void XojPageView::showFloatingToolbox(const PositionInputData& pos) {
Control* control = xournal->getControl();
gint wx = 0, wy = 0;
GtkWidget* widget = xournal->getWidget();
gtk_widget_translate_coordinates(widget, gtk_widget_get_toplevel(widget), 0, 0, &wx, &wy);
wx += round_cast<int>(pos.x) + this->getX();
wy += round_cast<int>(pos.y) + this->getY();
control->getWindow()->getFloatingToolbox()->show(wx, wy);
}
| 48,095
|
C++
|
.cpp
| 996
| 39.89759
| 120
| 0.614069
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,526
|
XournalppCursor.cpp
|
xournalpp_xournalpp/src/core/gui/XournalppCursor.cpp
|
#include "XournalppCursor.h"
#include <cmath> // for cos, sin, M_PI, NAN, fmod
#include <cstdint> // for uint32_t
#include <initializer_list> // for initializer_list
#include <cairo.h> // for cairo_move_to, cairo_lin...
#include <gdk-pixbuf/gdk-pixbuf.h> // for GdkPixbuf
#include <glib-object.h> // for g_object_unref
#include <gtk/gtk.h> // for gtk_widget_get_window
#include "control/Control.h" // for Control
#include "control/ToolEnums.h" // for TOOL_HAND, TOOL_PEN, TOO...
#include "control/ToolHandler.h" // for ToolHandler
#include "control/settings/Settings.h" // for Settings
#include "control/settings/SettingsEnums.h" // for STYLUS_CURSOR_BIG, STYLU...
#include "control/zoom/ZoomControl.h" // for ZoomControl
#include "gui/MainWindow.h" // for MainWindow
#include "util/Color.h" // for argb_to_GdkRGBA, rgb_to_...
#include "util/safe_casts.h" // for ceil_cast
#include "XournalView.h" // for XournalView
// NOTE: Every cursor change must result in the setting of this->currentCursor to the new cursor type even for custom
// cursors.
// Custom cursors can also compare then set this->currentCursorFlavour to notice changes in colour or size etc. The
// flavour calculation is specific to each cursor type and is calculated differently within each type.
// All the cursors we want to use. WARNING Make sure to set their css names in cssCursors[] below WARNING
enum AVAILABLECURSORS {
CRSR_nullptr = 0, // <--- Do Not Modify
CRSR_BUSY,
CRSR_MOVE,
CRSR_MOVING,
CRSR_GRAB,
CRSR_GRABBING,
CRSR_TOP_LEFT_CORNER,
CRSR_TOP_RIGHT_CORNER,
CRSR_BOTTOM_LEFT_CORNER,
CRSR_BOTTOM_RIGHT_CORNER,
CRSR_SB_H_DOUBLE_ARROW,
CRSR_EXCHANGE,
CRSR_PIRATE,
CRSR_SB_V_DOUBLE_ARROW,
CRSR_ARROW,
CRSR_BLANK_CURSOR,
CRSR_XTERM,
CRSR_DEFAULT,
CRSR_HAND2,
CRSR_TCROSS,
CRSR_PENORHIGHLIGHTER,
CRSR_ERASER,
CRSR_DRAWDIRNONE, // drawdir* keep these consecutive and in order: none,shift,ctrl,shiftctrl
CRSR_DRAWDIRSHIFT, // "
CRSR_DRAWDIRCTRL, // "
CRSR_DRAWDIRSHIFTCTRL, // "
CRSR_RESIZE,
CRSR_END_OF_CURSORS
};
struct cursorStruct {
const gchar* cssName;
const gchar* cssBackupName;
};
// our enum mapped to css name and a place to store the cursor pointer.
// Note: including enum as error check (for now?)
cursorStruct cssCursors[CRSR_END_OF_CURSORS];
XournalppCursor::XournalppCursor(Control* control): control(control) {
// clang-format off
// NOTE: Go ahead and use a fancy css cursor... but specify a common backup cursor.
cssCursors[CRSR_nullptr ] = {"",""};
cssCursors[CRSR_BUSY ] = {"wait", "" };
cssCursors[CRSR_MOVE ] = {"all-scroll", "" };
cssCursors[CRSR_MOVING ] = {"grabbing", "" };
cssCursors[CRSR_GRAB ] = {"grab", "" };
cssCursors[CRSR_GRABBING ] = {"grabbing", "" };
cssCursors[CRSR_TOP_LEFT_CORNER ] = {"nw-resize", "" };
cssCursors[CRSR_TOP_RIGHT_CORNER ] = {"ne-resize", "" };
cssCursors[CRSR_BOTTOM_LEFT_CORNER ] = {"sw-resize", "" };
cssCursors[CRSR_BOTTOM_RIGHT_CORNER ] = {"se-resize", "" };
cssCursors[CRSR_SB_H_DOUBLE_ARROW ] = {"ew-resize", "" };
cssCursors[CRSR_EXCHANGE ] = {"exchange", "arrow" };
cssCursors[CRSR_PIRATE ] = {"pirate", "arrow" };
cssCursors[CRSR_SB_V_DOUBLE_ARROW ] = {"ns-resize", "" };
cssCursors[CRSR_ARROW ] = {"default", "" };
cssCursors[CRSR_BLANK_CURSOR ] = {"none", "" };
cssCursors[CRSR_XTERM ] = {"text", "" };
cssCursors[CRSR_DEFAULT ] = {"default", "" };
cssCursors[CRSR_HAND2 ] = {"hand2", "" };
cssCursors[CRSR_TCROSS ] = {"crosshair", "" };
cssCursors[CRSR_PENORHIGHLIGHTER ] = {"",""}; // custom cursors - enum used only for check
cssCursors[CRSR_ERASER ] = {"",""}; // "
cssCursors[CRSR_DRAWDIRNONE ] = {"",""}; // "
cssCursors[CRSR_DRAWDIRSHIFT ] = {"",""}; // "
cssCursors[CRSR_DRAWDIRCTRL ] = {"",""}; // "
cssCursors[CRSR_DRAWDIRSHIFTCTRL ] = {"",""}; // "
cssCursors[CRSR_RESIZE ] = {"",""}; // "
};
// clang-format on
constexpr auto RESIZE_CURSOR_SIZE = 16;
constexpr auto DELTA_ANGLE_ARROW_HEAD = M_PI / 6.0;
constexpr auto LENGTH_ARROW_HEAD = 0.7;
constexpr auto RESIZE_CURSOR_HASH_PRECISION = 1000;
XournalppCursor::~XournalppCursor() = default;
void XournalppCursor::setInputDeviceClass(InputDeviceClass device) { this->inputDevice = device; }
// pen or hi-light cursor will be a DrawDir cursor instead
void XournalppCursor::activateDrawDirCursor(bool enable, bool shift, bool ctrl) {
this->drawDirActive = enable;
this->drawDirShift = shift;
this->drawDirCtrl = ctrl;
}
void XournalppCursor::setMouseDown(bool mouseDown) {
if (this->mouseDown == mouseDown) {
return;
}
this->mouseDown = mouseDown;
ToolHandler* handler = control->getToolHandler();
ToolType type = handler->getToolType();
// Not always an update is needed
if (type == TOOL_HAND || type == TOOL_VERTICAL_SPACE || type == TOOL_ERASER) {
updateCursor();
}
}
void XournalppCursor::setMouseSelectionType(CursorSelectionType selectionType) {
if (this->selectionType == selectionType) {
return;
}
this->selectionType = selectionType;
updateCursor();
}
void XournalppCursor::setRotationAngle(double angle) { this->angle = angle; }
void XournalppCursor::setMirror(bool mirror) { this->mirror = mirror; }
/*This handles setting the busy cursor for the main window and calls
* updateCursor to set the busy cursor for the XournalWidget region.
*/
void XournalppCursor::setCursorBusy(bool busy) {
MainWindow* win = control->getWindow();
if (!win) {
return;
}
if (this->busy == busy) {
return;
}
this->busy = busy;
if (busy) {
GdkWindow* window = gtk_widget_get_window(win->getWindow());
xoj::util::GObjectSPtr<GdkCursor> cursor(
gdk_cursor_new_from_name(gdk_window_get_display(window), cssCursors[CRSR_BUSY].cssName),
xoj::util::adopt);
gdk_window_set_cursor(window, cursor.get());
} else {
if (gtk_widget_get_window(win->getWindow())) {
gdk_window_set_cursor(gtk_widget_get_window(win->getWindow()), nullptr);
}
}
updateCursor();
}
void XournalppCursor::setInsidePage(bool insidePage) {
if (this->insidePage == insidePage) {
return;
}
this->insidePage = insidePage;
updateCursor();
}
void XournalppCursor::setInvisible(bool invisible) {
if (this->invisible == invisible) {
return;
}
this->invisible = invisible;
updateCursor();
}
void XournalppCursor::updateCursor() {
MainWindow* win = control->getWindow();
if (!win) {
return;
}
XournalView* xournal = win->getXournal();
if (!xournal) {
return;
}
GdkCursor* cursor = nullptr;
if (this->busy) {
setCursor(CRSR_BUSY);
} else {
ToolHandler* handler = control->getToolHandler();
ToolType type = handler->getToolType();
if (type == TOOL_HAND) {
if (this->mouseDown) {
setCursor(CRSR_GRABBING);
} else {
setCursor(CRSR_GRAB);
}
} else if (!this->insidePage) {
setCursor(CRSR_DEFAULT);
} else if (this->selectionType) {
switch (this->selectionType) {
case CURSOR_SELECTION_MOVE:
if (this->mouseDown) {
setCursor(CRSR_MOVING);
} else {
setCursor(CRSR_MOVE);
}
break;
case CURSOR_SELECTION_TOP_LEFT:
[[fallthrough]];
case CURSOR_SELECTION_BOTTOM_RIGHT:
cursor = getResizeCursor(45);
break;
case CURSOR_SELECTION_TOP_RIGHT:
[[fallthrough]];
case CURSOR_SELECTION_BOTTOM_LEFT:
cursor = getResizeCursor(135);
break;
case CURSOR_SELECTION_LEFT:
[[fallthrough]];
case CURSOR_SELECTION_RIGHT:
cursor = getResizeCursor(180);
break;
case CURSOR_SELECTION_TOP:
[[fallthrough]];
case CURSOR_SELECTION_BOTTOM:
cursor = getResizeCursor(90);
break;
case CURSOR_SELECTION_ROTATE:
setCursor(CRSR_EXCHANGE);
break;
case CURSOR_SELECTION_DELETE:
setCursor(CRSR_PIRATE);
break;
default:
break;
}
} else if (type == TOOL_PEN || type == TOOL_HIGHLIGHTER) {
if (this->inputDevice == INPUT_DEVICE_MOUSE && !this->mouseDown) // mouse and not pressed
{
setCursor(CRSR_ARROW);
} else {
if (type == TOOL_PEN) {
cursor = getPenCursor();
} else // must be: if (type == TOOL_HIGHLIGHTER)
{
cursor = getHighlighterCursor();
}
}
} else if (type == TOOL_ERASER) {
EraserVisibility visibility = control->getSettings()->getEraserVisibility();
if ((this->inputDevice == INPUT_DEVICE_PEN || this->inputDevice == INPUT_DEVICE_ERASER) &&
(visibility == ERASER_VISIBILITY_NEVER || (visibility == ERASER_VISIBILITY_HOVER && this->mouseDown) ||
(visibility == ERASER_VISIBILITY_TOUCH && !this->mouseDown))) {
setCursor(CRSR_BLANK_CURSOR);
} else {
cursor = getEraserCursor();
}
}
else if (type == TOOL_TEXT) {
if (this->invisible) {
setCursor(CRSR_BLANK_CURSOR);
} else {
setCursor(CRSR_XTERM);
}
} else if (type == TOOL_IMAGE) {
setCursor(CRSR_TCROSS);
} else if (type == TOOL_FLOATING_TOOLBOX) {
setCursor(CRSR_DEFAULT);
} else if (type == TOOL_VERTICAL_SPACE) {
setCursor(CRSR_SB_V_DOUBLE_ARROW);
} else if (type == TOOL_SELECT_OBJECT) {
setCursor(CRSR_DEFAULT);
} else if (type == TOOL_PLAY_OBJECT) {
setCursor(CRSR_HAND2);
} else if (type == TOOL_SELECT_PDF_TEXT_LINEAR) {
setCursor(CRSR_XTERM);
} else // other selections are handled before anyway, because you can move a selection with every tool
{
setCursor(CRSR_TCROSS);
}
}
GdkWindow* window = gtk_widget_get_window(xournal->getWidget());
if (window) {
if (cursor != nullptr) {
gdk_window_set_cursor(window, cursor);
}
gtk_widget_set_sensitive(xournal->getWidget(), !this->busy);
}
// Performance removal!
// If this line is ever required, make sure this function is never called, when the cursor is not set.
// gdk_display_sync(gdk_display_get_default());
if (cursor != nullptr) {
g_object_unref(cursor);
}
}
auto XournalppCursor::getResizeCursor(double deltaAngle) -> GdkCursor* {
if (this->mirror) {
deltaAngle = -deltaAngle;
}
gulong flavour = static_cast<gulong>(RESIZE_CURSOR_HASH_PRECISION * fmod(angle + deltaAngle, 180.0));
if (CRSR_RESIZE == this->currentCursor && flavour == this->currentCursorFlavour) {
return nullptr;
}
this->currentCursor = CRSR_RESIZE;
this->currentCursorFlavour = flavour;
double a = (this->angle + deltaAngle) * M_PI / 180;
cairo_surface_t* crCursor = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, RESIZE_CURSOR_SIZE, RESIZE_CURSOR_SIZE);
cairo_t* cr = cairo_create(crCursor);
cairo_set_source_rgba(cr, 0.1, 0.1, 0.1, 1);
cairo_translate(cr, RESIZE_CURSOR_SIZE / 2, RESIZE_CURSOR_SIZE / 2);
cairo_scale(cr, RESIZE_CURSOR_SIZE / 2, RESIZE_CURSOR_SIZE / 2);
cairo_set_line_width(cr, 0.2);
// draw double headed arrow rotated accordingly
cairo_move_to(cr, cos(a), sin(a));
cairo_line_to(cr, -cos(a), -sin(a));
cairo_stroke(cr);
// head and tail
for (auto s: {-1, 1}) {
cairo_move_to(cr, s * cos(a), s * sin(a));
cairo_rel_line_to(cr, s * cos(a + M_PI + DELTA_ANGLE_ARROW_HEAD) * LENGTH_ARROW_HEAD,
s * sin(a + M_PI + DELTA_ANGLE_ARROW_HEAD) * LENGTH_ARROW_HEAD);
cairo_move_to(cr, s * cos(a), s * sin(a));
cairo_rel_line_to(cr, s * cos(a + M_PI - DELTA_ANGLE_ARROW_HEAD) * LENGTH_ARROW_HEAD,
s * sin(a + M_PI - DELTA_ANGLE_ARROW_HEAD) * LENGTH_ARROW_HEAD);
cairo_stroke(cr);
}
cairo_destroy(cr);
GdkPixbuf* pixbuf = gdk_pixbuf_get_from_surface(crCursor, 0, 0, RESIZE_CURSOR_SIZE, RESIZE_CURSOR_SIZE);
cairo_surface_destroy(crCursor);
GdkCursor* cursor =
gdk_cursor_new_from_pixbuf(gtk_widget_get_display(control->getWindow()->getXournal()->getWidget()), pixbuf,
RESIZE_CURSOR_SIZE / 2, RESIZE_CURSOR_SIZE / 2);
g_object_unref(pixbuf);
return cursor;
}
auto XournalppCursor::getEraserCursor() -> GdkCursor* {
// Eraser's size follow a quadratic increment, so the cursor will do the same
double cursorSize = control->getToolHandler()->getThickness() * 2.0 * control->getZoomControl()->getZoom();
gulong flavour = static_cast<gulong>(64 * cursorSize);
if (CRSR_ERASER == this->currentCursor && flavour == this->currentCursorFlavour) {
return nullptr; // cursor already set
}
this->currentCursor = CRSR_ERASER;
this->currentCursorFlavour = flavour;
cairo_surface_t* surface =
cairo_image_surface_create(CAIRO_FORMAT_ARGB32, ceil_cast<int>(cursorSize), ceil_cast<int>(cursorSize));
cairo_t* cr = cairo_create(surface);
cairo_rectangle(cr, 0, 0, cursorSize, cursorSize);
cairo_set_source_rgb(cr, 1, 1, 1);
cairo_fill(cr);
cairo_rectangle(cr, 0, 0, cursorSize, cursorSize);
cairo_set_source_rgb(cr, 0, 0, 0);
cairo_stroke(cr);
cairo_destroy(cr);
GdkCursor* cursor =
gdk_cursor_new_from_surface(gdk_display_get_default(), surface, cursorSize / 2.0, cursorSize / 2.0);
cairo_surface_destroy(surface);
return cursor;
}
auto XournalppCursor::getHighlighterCursor() -> GdkCursor* {
if (this->drawDirActive) {
return createCustomDrawDirCursor(48, this->drawDirShift, this->drawDirCtrl);
}
return createHighlighterOrPenCursor(120 / 255.0);
}
auto XournalppCursor::getPenCursor() -> GdkCursor* {
if ((control->getSettings()->getStylusCursorType() == STYLUS_CURSOR_NONE) &&
!control->getSettings()->isHighlightPosition()) {
setCursor(CRSR_BLANK_CURSOR);
return nullptr;
}
if (control->getSettings()->getStylusCursorType() == STYLUS_CURSOR_ARROW) {
setCursor(CRSR_ARROW);
return nullptr;
}
if ((control->getSettings()->getStylusCursorType() != STYLUS_CURSOR_NONE) && this->drawDirActive) {
return createCustomDrawDirCursor(48, this->drawDirShift, this->drawDirCtrl);
}
return createHighlighterOrPenCursor(1.0);
}
auto XournalppCursor::createHighlighterOrPenCursor(double alpha) -> GdkCursor* {
auto irgb = control->getToolHandler()->getColor();
auto drgb = Util::rgb_to_GdkRGBA(irgb);
auto cursorType = control->getSettings()->getStylusCursorType();
auto cursor = (cursorType == STYLUS_CURSOR_NONE) ? CRSR_BLANK_CURSOR : CRSR_PENORHIGHLIGHTER;
bool bright = control->getSettings()->isHighlightPosition();
double cursorSize = std::min(90., control->getToolHandler()->getThickness() * control->getZoomControl()->getZoom());
int height = ceil_cast<int>(cursorSize);
int width = height;
// create a hash of variables so we notice if one changes despite being the same cursor type:
gulong flavour = (cursorType == STYLUS_CURSOR_DOT ? 1U : 0U) | (cursorType == STYLUS_CURSOR_BIG ? 2U : 0U) |
(bright ? 4U : 0U) | static_cast<gulong>(64 * alpha) << 3U |
static_cast<gulong>(cursorSize) << 10U | static_cast<gulong>(uint32_t(irgb)) << 15U;
if ((cursor == this->currentCursor) && (flavour == this->currentCursorFlavour)) {
return nullptr;
}
this->currentCursor = cursor;
this->currentCursorFlavour = flavour;
if ((cursorType == STYLUS_CURSOR_BIG) || bright) {
height = width = 90;
}
// We change the drawing method, now the center with the colored dot of the pen
// is at the center of the cairo surface, and when we load the cursor, we load it
// with the relative offset
int centerX = width / 2;
int centerY = height / 2;
cairo_surface_t* crCursor = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, width, height);
cairo_t* cr = cairo_create(crCursor);
if (cursorType == STYLUS_CURSOR_BIG) {
// When using highlighter, paint the icon with the current color
if (alpha != 1.0) {
gdk_cairo_set_source_rgba(cr, &drgb);
} else {
cairo_set_source_rgb(cr, 1, 1, 1);
}
cairo_set_line_width(cr, 1.2);
// Starting point
cairo_move_to(cr, centerX + 2, centerY);
// Pencil cursor
cairo_line_to(cr, centerX + 2, centerY - 4);
cairo_line_to(cr, centerX + 15, centerY - 17.5);
cairo_line_to(cr, centerX + 19, centerY - 14);
cairo_line_to(cr, centerX + 6, centerY);
cairo_close_path(cr);
cairo_fill_preserve(cr);
cairo_set_source_rgb(cr, 0, 0, 0);
cairo_stroke(cr);
cairo_fill_preserve(cr);
}
if (bright) {
// Highlight cursor with a circle
auto&& color = Util::argb_to_GdkRGBA(control->getSettings()->getCursorHighlightColor());
gdk_cairo_set_source_rgba(cr, &color);
cairo_arc(cr, centerX, centerY, control->getSettings()->getCursorHighlightRadius(), 0, 2 * M_PI);
cairo_fill_preserve(cr);
auto&& borderColor = Util::argb_to_GdkRGBA(control->getSettings()->getCursorHighlightBorderColor());
gdk_cairo_set_source_rgba(cr, &borderColor);
cairo_set_line_width(cr, control->getSettings()->getCursorHighlightBorderWidth());
cairo_stroke(cr);
}
if (cursorType != STYLUS_CURSOR_NONE) {
auto drgbCopy = drgb;
drgbCopy.alpha = alpha;
gdk_cairo_set_source_rgba(cr, &drgbCopy);
cairo_arc(cr, centerX, centerY, cursorSize / 2., 0, 2. * M_PI);
cairo_fill(cr);
}
cairo_destroy(cr);
GdkPixbuf* pixbuf = gdk_pixbuf_get_from_surface(crCursor, 0, 0, width, height);
cairo_surface_destroy(crCursor);
GdkCursor* gdkCursor = gdk_cursor_new_from_pixbuf(
gtk_widget_get_display(control->getWindow()->getXournal()->getWidget()), pixbuf, centerX, centerY);
g_object_unref(pixbuf);
return gdkCursor;
}
void XournalppCursor::setCursor(guint cursorID) {
if (cursorID == this->currentCursor) {
return;
}
MainWindow* win = control->getWindow();
if (!win) {
return;
}
XournalView* xournal = win->getXournal();
if (!xournal) {
return;
}
GdkWindow* window = gtk_widget_get_window(xournal->getWidget());
if (!window) {
return;
}
GdkCursor* cursor = gdk_cursor_new_from_name(gdk_window_get_display(window), cssCursors[cursorID].cssName);
if (cursor == nullptr) // failed to get a cursor, try backup cursor.
{
if (cursorID != CRSR_nullptr) {
cursor = gdk_cursor_new_from_name(gdk_window_get_display(window), cssCursors[cursorID].cssBackupName);
// Null cursor is ok but not wanted ... warn user
if (cursor == nullptr) {
if (CRSR_nullptr == this->currentCursor) {
return; // We've already been here
}
g_warning("CSS Cursor and backup not valid '%s', '%s'", cssCursors[cursorID].cssName,
cssCursors[cursorID].cssBackupName);
}
}
cursorID = cursor == nullptr ? CRSR_nullptr : cursorID;
}
this->currentCursor = cursorID;
gdk_window_set_cursor(gtk_widget_get_window(xournal->getWidget()), cursor);
gdk_window_set_cursor(window, cursor);
if (cursor) {
g_object_unref(cursor);
}
}
auto XournalppCursor::createCustomDrawDirCursor(int size, bool shift, bool ctrl) -> GdkCursor* {
bool big = control->getSettings()->getStylusCursorType() == STYLUS_CURSOR_BIG;
bool bright = control->getSettings()->isHighlightPosition();
guint newCursorID = CRSR_DRAWDIRNONE + (shift ? 1 : 0) + (ctrl ? 2 : 0);
gulong flavour =
(big ? 1 : 0) | (bright ? 2 : 0) | static_cast<gulong>(size) << 2; // hash of variables for comparison only
if (newCursorID == this->currentCursor && flavour == this->currentCursorFlavour) {
return nullptr;
}
this->currentCursor = newCursorID;
this->currentCursorFlavour = flavour;
int height = size;
int width = size;
int fontSize = 8;
if (big || bright) {
height = width = 60;
fontSize = 12;
}
int centerX = width - width / 4;
int centerY = height - height / 4;
cairo_surface_t* crCursor = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, width, height);
cairo_t* cr = cairo_create(crCursor);
cairo_set_line_width(cr, 1.2);
// Starting point
cairo_move_to(cr, centerX, height / 2);
cairo_line_to(cr, centerX, height);
cairo_stroke(cr);
cairo_move_to(cr, width / 2, centerY);
cairo_line_to(cr, width, centerY);
cairo_stroke(cr);
if (ctrl) {
cairo_text_extents_t extents;
const char* utf8 = "CONTROL";
double x = NAN, y = NAN;
cairo_select_font_face(cr, "Sans", CAIRO_FONT_SLANT_NORMAL, CAIRO_FONT_WEIGHT_NORMAL);
cairo_set_font_size(cr, fontSize);
cairo_text_extents(cr, utf8, &extents);
x = 0;
y = extents.height;
cairo_move_to(cr, x, y);
cairo_show_text(cr, utf8);
}
if (shift) {
cairo_text_extents_t extents;
const char* utf8 = "SHIFT";
double x = NAN, y = NAN;
cairo_select_font_face(cr, "Sans", CAIRO_FONT_SLANT_NORMAL, CAIRO_FONT_WEIGHT_NORMAL);
cairo_set_font_size(cr, fontSize);
cairo_text_extents(cr, utf8, &extents);
x = 0;
y = extents.height * 2.5;
cairo_move_to(cr, x, y);
cairo_show_text(cr, utf8);
}
cairo_destroy(cr);
GdkPixbuf* pixbuf = gdk_pixbuf_get_from_surface(crCursor, 0, 0, width, height);
cairo_surface_destroy(crCursor);
GdkCursor* cursor = gdk_cursor_new_from_pixbuf(
gtk_widget_get_display(control->getWindow()->getXournal()->getWidget()), pixbuf, centerX, centerY);
g_object_unref(pixbuf);
return cursor;
}
| 23,572
|
C++
|
.cpp
| 545
| 35.653211
| 120
| 0.606028
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,527
|
MainWindow.cpp
|
xournalpp_xournalpp/src/core/gui/MainWindow.cpp
|
#include "MainWindow.h"
#include <regex>
#include <gdk-pixbuf/gdk-pixbuf.h> // for gdk_pixbuf_new_fr...
#include <gdk/gdk.h> // for gdk_screen_get_de...
#include <gio/gio.h> // for g_cancellable_is_...
#include <gtk/gtkcssprovider.h> // for gtk_css_provider_...
#include "control/AudioController.h" // for AudioController
#include "control/Control.h" // for Control
#include "control/DeviceListHelper.h" // for getSourceMapping
#include "control/ScrollHandler.h" // for ScrollHandler
#include "control/actions/ActionDatabase.h" // for ActionDatabase
#include "control/jobs/XournalScheduler.h" // for XournalScheduler
#include "control/layer/LayerController.h" // for LayerController
#include "control/settings/Settings.h" // for Settings
#include "control/settings/SettingsEnums.h" // for SCROLLBAR_HIDE_HO...
#include "control/zoom/ZoomControl.h" // for ZoomControl
#include "gui/FloatingToolbox.h" // for FloatingToolbox
#include "gui/GladeGui.h" // for GladeGui
#include "gui/PdfFloatingToolbox.h" // for PdfFloatingToolbox
#include "gui/SearchBar.h" // for SearchBar
#include "gui/inputdevices/InputEvents.h" // for INPUT_DEVICE_TOUC...
#include "gui/menus/menubar/Menubar.h" // for Menubar
#include "gui/menus/menubar/ToolbarSelectionSubmenu.h" // for ToolbarSelectionSubmenu
#include "gui/scroll/ScrollHandling.h" // for ScrollHandling
#include "gui/sidebar/Sidebar.h" // for Sidebar
#include "gui/toolbarMenubar/ToolMenuHandler.h" // for ToolMenuHandler
#include "gui/toolbarMenubar/model/ToolbarData.h" // for ToolbarData
#include "gui/toolbarMenubar/model/ToolbarModel.h" // for ToolbarModel
#include "gui/widgets/SpinPageAdapter.h" // for SpinPageAdapter
#include "gui/widgets/XournalWidget.h" // for gtk_xournal_get_l...
#include "util/GListView.h" // for GListView, GListV...
#include "util/PathUtil.h" // for getConfigFile
#include "util/Util.h" // for execInUiThread, npos
#include "util/XojMsgBox.h" // for XojMsgBox
#include "util/glib_casts.h" // for wrap_for_once_v
#include "util/gtk4_helper.h" // for gtk_widget_get_width
#include "util/i18n.h" // for FS, _F
#include "util/raii/CStringWrapper.h" // for OwnedCString
#include "GladeSearchpath.h" // for GladeSearchpath
#include "ToolbarDefinitions.h" // for TOOLBAR_DEFINITIO...
#include "XournalView.h" // for XournalView
#include "config-dev.h" // for TOOLBAR_CONFIG
#include "filesystem.h" // for path, exists
#ifdef __APPLE__
// the following header file contains a definition of struct Point that conflicts with model/Point.h
#define Point Point_CF
#include <CoreFoundation/CoreFoundation.h>
#undef Point
#endif
using std::string;
static void themeCallback(GObject*, GParamSpec*, gpointer data) { static_cast<MainWindow*>(data)->updateColorscheme(); }
MainWindow::MainWindow(GladeSearchpath* gladeSearchPath, Control* control, GtkApplication* parent):
GladeGui(gladeSearchPath, "main.glade", "mainWindow"),
control(control),
toolbar(std::make_unique<ToolMenuHandler>(control, this)),
menubar(std::make_unique<Menubar>()) {
gtk_window_set_application(GTK_WINDOW(getWindow()), parent);
panedContainerWidget.reset(get("panelMainContents"), xoj::util::ref);
boxContainerWidget.reset(get("mainContentContainer"), xoj::util::ref);
mainContentWidget.reset(get("boxContents"), xoj::util::ref);
sidebarWidget.reset(get("sidebar"), xoj::util::ref);
loadMainCSS(gladeSearchPath, "xournalpp.css");
GtkOverlay* overlay = GTK_OVERLAY(get("mainOverlay"));
this->pdfFloatingToolBox = std::make_unique<PdfFloatingToolbox>(this, overlay);
this->floatingToolbox = std::make_unique<FloatingToolbox>(this, overlay);
for (size_t i = 0; i < TOOLBAR_DEFINITIONS_LEN; i++) {
this->toolbarWidgets[i].reset(get(TOOLBAR_DEFINITIONS[i].guiName), xoj::util::ref);
}
initXournalWidget();
setSidebarVisible(control->getSettings()->isSidebarVisible());
// Window handler
g_signal_connect(this->window, "delete-event", xoj::util::wrap_for_g_callback_v<deleteEventCallback>,
this->control);
#if GTK_MAJOR_VERSION == 3
g_signal_connect(this->window, "notify::is-maximized", xoj::util::wrap_for_g_callback_v<windowMaximizedCallback>,
this);
#else
g_signal_connect(this->window, "notify::maximized", xoj::util::wrap_for_g_callback_v<windowMaximizedCallback>,
this);
#endif
// "watch over" all key events
auto keyPropagate = +[](GtkWidget* w, GdkEvent* e, gpointer) {
return gtk_window_propagate_key_event(GTK_WINDOW(w), (GdkEventKey*)(e));
};
g_signal_connect(this->window, "key-press-event", G_CALLBACK(keyPropagate), nullptr);
g_signal_connect(this->window, "key-release-event", G_CALLBACK(keyPropagate), nullptr);
updateScrollbarSidebarPosition();
gtk_window_set_default_size(GTK_WINDOW(this->window), control->getSettings()->getMainWndWidth(),
control->getSettings()->getMainWndHeight());
if (control->getSettings()->isMainWndMaximized()) {
gtk_window_maximize(GTK_WINDOW(this->window));
} else {
gtk_window_unmaximize(GTK_WINDOW(this->window));
}
Util::execInUiThread([=]() {
// Execute after the window is visible, else the check won't work
control->setShowMenubar(control->getSettings()->isMenubarVisible());
});
// Drag and Drop
g_signal_connect(this->window, "drag-data-received", G_CALLBACK(dragDataRecived), this);
gtk_drag_dest_set(this->window, GTK_DEST_DEFAULT_ALL, nullptr, 0, GDK_ACTION_COPY);
gtk_drag_dest_add_uri_targets(this->window);
gtk_drag_dest_add_image_targets(this->window);
gtk_drag_dest_add_text_targets(this->window);
g_signal_connect(gtk_widget_get_settings(this->window), "notify::gtk-theme-name", G_CALLBACK(themeCallback), this);
g_signal_connect(gtk_widget_get_settings(this->window), "notify::gtk-application-prefer-dark-theme",
G_CALLBACK(themeCallback), this);
updateColorscheme();
}
void MainWindow::populate(GladeSearchpath* gladeSearchPath) {
toolbar->populate(gladeSearchPath);
menubar->populate(gladeSearchPath, this);
// need to create tool buttons registered in plugins, so they can be added to toolbars
control->registerPluginToolButtons(this->toolbar.get());
createToolbar();
setToolbarVisible(control->getSettings()->isToolbarVisible());
}
GMenuModel* MainWindow::getMenuModel() const { return menubar->getModel(); }
MainWindow::~MainWindow() = default;
struct ThemeProperties {
bool dark;
bool darkSuffix;
std::string rootname; ///< Name without any putative -dark suffix
};
static ThemeProperties getThemeProperties(GtkWidget* w) {
xoj::util::OwnedCString name;
[[maybe_unused]] bool useEnv = false;
// Gtk prioritizes GTK_THEME over GtkSettings content
// cf https://gitlab.gnome.org/GNOME/gtk/blob/90d84a2af8b367bd5a5312b3fa3b67563462c0ef/gtk/gtksettings.c#L1567-L1622
if (auto* p = g_getenv("GTK_THEME")) {
*(name.contentReplacer()) = g_strdup(p);
useEnv = true;
} else {
g_object_get(gtk_widget_get_settings(w), "gtk-theme-name", name.contentReplacer(), nullptr);
}
// Try to figure out if the theme is dark or light
// Some themes handle their dark variant via "gtk-application-prefer-dark-theme" while other just append "-dark"
const std::regex nameparser("([a-zA-Z-]+?)([:-][dD]ark)?");
std::cmatch sm;
std::regex_match(name.get(), sm, nameparser);
ThemeProperties props;
if (sm.size() < 3) {
g_warning("Fails to extract theme root name from: \"%s\"", name.get());
props.rootname = name.get();
props.darkSuffix = false;
} else {
props.rootname = sm[1];
props.darkSuffix = sm[2].length() > 0;
}
gboolean dark = false;
#ifdef __APPLE__
if (!useEnv) {
CFStringRef interfaceStyle =
(CFStringRef)CFPreferencesCopyAppValue(CFSTR("AppleInterfaceStyle"), kCFPreferencesCurrentApplication);
if (interfaceStyle) {
char buffer[128];
if (CFStringGetCString(interfaceStyle, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
std::string style = buffer;
if (auto pos = style.find("Dark"); pos != std::string::npos) {
dark = true;
}
}
}
}
#else
g_object_get(gtk_widget_get_settings(w), "gtk-application-prefer-dark-theme", &dark, nullptr);
#endif
g_debug("Extracted theme info: Name = %s, rootname = %s, dark = %s", name.get(), props.rootname.c_str(),
dark ? "true" : "false");
props.dark = props.darkSuffix || dark; // Some themes handle their dark variant via this setting
return props;
}
void MainWindow::updateColorscheme() {
g_signal_handlers_block_by_func(gtk_widget_get_settings(this->window),
reinterpret_cast<gpointer>(G_CALLBACK(themeCallback)), this);
auto variant = control->getSettings()->getThemeVariant();
if (variant == THEME_VARIANT_USE_SYSTEM) {
gtk_settings_reset_property(gtk_widget_get_settings(this->window), "gtk-application-prefer-dark-theme");
if (modifiedGtkSettingsTheme) {
// Some bug in Gtk makes an infinite loop despite us blocking the signals
gtk_settings_reset_property(gtk_widget_get_settings(this->window), "gtk-theme-name");
modifiedGtkSettingsTheme = false;
}
}
auto props = getThemeProperties(this->window);
this->darkMode = (props.dark && variant != THEME_VARIANT_FORCE_LIGHT) || variant == THEME_VARIANT_FORCE_DARK;
// Set up icons
{
const auto uiPath = this->getGladeSearchPath()->getFirstSearchPath();
const auto lightColorIcons = (uiPath / "iconsColor-light").u8string();
const auto darkColorIcons = (uiPath / "iconsColor-dark").u8string();
const auto lightLucideIcons = (uiPath / "iconsLucide-light").u8string();
const auto darkLucideIcons = (uiPath / "iconsLucide-dark").u8string();
// icon load order from lowest priority to highest priority
std::vector<std::string> iconLoadOrder = {};
const auto chosenTheme = control->getSettings()->getIconTheme();
switch (chosenTheme) {
case ICON_THEME_COLOR:
iconLoadOrder = {darkLucideIcons, lightLucideIcons, darkColorIcons, lightColorIcons};
break;
case ICON_THEME_LUCIDE:
iconLoadOrder = {darkColorIcons, lightColorIcons, darkLucideIcons, lightLucideIcons};
break;
default:
g_message("Unknown icon theme!");
}
if (this->darkMode) {
for (size_t i = 0; 2 * i + 1 < iconLoadOrder.size(); ++i) {
std::swap(iconLoadOrder[2 * i], iconLoadOrder[2 * i + 1]);
}
}
for (auto& p: iconLoadOrder) {
gtk_icon_theme_prepend_search_path(gtk_icon_theme_get_default(), p.c_str());
}
}
GtkStyleContext* context = gtk_widget_get_style_context(GTK_WIDGET(this->window));
if (this->darkMode) {
gtk_style_context_add_class(context, "darkMode");
g_object_set(gtk_widget_get_settings(this->window), "gtk-application-prefer-dark-theme", true, nullptr);
} else {
gtk_style_context_remove_class(context, "darkMode");
g_object_set(gtk_widget_get_settings(this->window), "gtk-application-prefer-dark-theme", false, nullptr);
if (props.darkSuffix) { // The active theme is all dark. Remove the trailing "-dark"
g_object_set(gtk_widget_get_settings(this->window), "gtk-theme-name", props.rootname.c_str(), nullptr);
modifiedGtkSettingsTheme = true;
}
}
{
gchar* name = nullptr;
g_object_get(gtk_widget_get_settings(this->window), "gtk-theme-name", &name, nullptr);
g_debug("Theme name: %s", name);
g_debug("Modified in GtkSettings: %s", modifiedGtkSettingsTheme ? "true" : "false");
g_free(name);
gboolean gtkdark = true;
g_object_get(gtk_widget_get_settings(this->window), "gtk-application-prefer-dark-theme", >kdark, nullptr);
g_debug("Theme variant: %s", gtkdark ? "dark" : "light");
g_debug("Icon theme: %s", iconThemeToString(control->getSettings()->getIconTheme()));
}
g_signal_handlers_unblock_by_func(gtk_widget_get_settings(this->window), reinterpret_cast<gpointer>(themeCallback),
this);
}
void MainWindow::initXournalWidget() {
winXournal = gtk_scrolled_window_new();
setGtkTouchscreenScrollingForDeviceMapping();
gtk_box_append(GTK_BOX(get("boxContents")), winXournal);
GtkWidget* vpXournal = gtk_viewport_new(nullptr, nullptr);
gtk_scrolled_window_set_child(GTK_SCROLLED_WINDOW(winXournal), vpXournal);
scrollHandling = std::make_unique<ScrollHandling>(GTK_SCROLLABLE(vpXournal));
this->xournal = std::make_unique<XournalView>(vpXournal, control, scrollHandling.get());
control->getZoomControl()->initZoomHandler(this->window, winXournal, xournal.get(), control);
gtk_widget_show_all(winXournal);
Layout* layout = gtk_xournal_get_layout(this->xournal->getWidget());
scrollHandling->init(this->xournal->getWidget(), layout);
}
void MainWindow::setGtkTouchscreenScrollingForDeviceMapping() {
InputDeviceClass touchscreenClass =
DeviceListHelper::getSourceMapping(GDK_SOURCE_TOUCHSCREEN, this->getControl()->getSettings());
setGtkTouchscreenScrollingEnabled(touchscreenClass == INPUT_DEVICE_TOUCHSCREEN &&
!control->getSettings()->getTouchDrawingEnabled());
}
void MainWindow::setGtkTouchscreenScrollingEnabled(bool enabled) {
if (!control->getSettings()->getGtkTouchInertialScrollingEnabled()) {
enabled = false;
}
if (enabled == gtkTouchscreenScrollingEnabled.load() || winXournal == nullptr) {
return;
}
gtkTouchscreenScrollingEnabled.store(enabled);
Util::execInUiThread(
[=]() {
const bool touchScrollEnabled = gtkTouchscreenScrollingEnabled.load();
gtk_scrolled_window_set_kinetic_scrolling(GTK_SCROLLED_WINDOW(winXournal), touchScrollEnabled);
},
G_PRIORITY_HIGH);
}
auto MainWindow::getLayout() const -> Layout* { return gtk_xournal_get_layout(this->xournal->getWidget()); }
auto MainWindow::getNegativeXournalWidgetPos() const -> xoj::util::Point<double> {
return Util::toWidgetCoords(this->winXournal, xoj::util::Point{0.0, 0.0});
}
auto cancellable_cancel(GCancellable* cancel) -> bool {
g_cancellable_cancel(cancel);
g_warning("Timeout... Cancel loading URL");
return false;
}
void MainWindow::dragDataRecived(GtkWidget* widget, GdkDragContext* dragContext, gint x, gint y, GtkSelectionData* data,
guint info, guint time, MainWindow* win) {
GtkWidget* source = gtk_drag_get_source_widget(dragContext);
if (source && widget == gtk_widget_get_toplevel(source)) {
gtk_drag_finish(dragContext, false, false, time);
return;
}
guchar* text = gtk_selection_data_get_text(data);
if (text) {
win->control->clipboardPasteText(reinterpret_cast<const char*>(text));
g_free(text);
gtk_drag_finish(dragContext, true, false, time);
return;
}
xoj::util::GObjectSPtr<GdkPixbuf> image(gtk_selection_data_get_pixbuf(data), xoj::util::adopt);
if (image) {
win->control->clipboardPasteImage(image.get());
gtk_drag_finish(dragContext, true, false, time);
return;
}
gchar** uris = gtk_selection_data_get_uris(data);
if (uris) {
for (int i = 0; uris[i] != nullptr && i < 3; i++) {
const char* uri = uris[i];
GCancellable* cancel = g_cancellable_new();
auto cancelTimeout = g_timeout_add(3000, xoj::util::wrap_for_once_v<cancellable_cancel>, cancel);
xoj::util::GObjectSPtr<GFile> file(g_file_new_for_uri(uri), xoj::util::adopt);
GError* err = nullptr;
GFileInputStream* in = g_file_read(file.get(), cancel, &err);
if (g_cancellable_is_cancelled(cancel)) {
continue;
}
if (err == nullptr) {
xoj::util::GObjectSPtr<GdkPixbuf> pixbuf(
gdk_pixbuf_new_from_stream(G_INPUT_STREAM(in), cancel, nullptr), xoj::util::adopt);
if (g_cancellable_is_cancelled(cancel)) {
continue;
}
g_input_stream_close(G_INPUT_STREAM(in), cancel, nullptr);
if (g_cancellable_is_cancelled(cancel)) {
continue;
}
if (pixbuf) {
win->control->clipboardPasteImage(pixbuf.get());
}
} else {
g_error_free(err);
}
if (!g_cancellable_is_cancelled(cancel)) {
g_source_remove(cancelTimeout);
}
g_object_unref(cancel);
}
gtk_drag_finish(dragContext, true, false, time);
g_strfreev(uris);
}
gtk_drag_finish(dragContext, false, false, time);
}
auto MainWindow::getControl() const -> Control* { return control; }
void MainWindow::updateScrollbarSidebarPosition() {
// Part 1: update scrollbar position
if (winXournal != nullptr) {
GtkScrolledWindow* scrolledWindow = GTK_SCROLLED_WINDOW(winXournal);
ScrollbarHideType type = this->getControl()->getSettings()->getScrollbarHideType();
bool scrollbarOnLeft = control->getSettings()->isScrollbarOnLeft();
if (scrollbarOnLeft) {
gtk_scrolled_window_set_placement(scrolledWindow, GTK_CORNER_TOP_RIGHT);
} else {
gtk_scrolled_window_set_placement(scrolledWindow, GTK_CORNER_TOP_LEFT);
}
gtk_widget_set_visible(gtk_scrolled_window_get_hscrollbar(scrolledWindow), !(type & SCROLLBAR_HIDE_HORIZONTAL));
gtk_widget_set_visible(gtk_scrolled_window_get_vscrollbar(scrolledWindow), !(type & SCROLLBAR_HIDE_VERTICAL));
gtk_scrolled_window_set_overlay_scrolling(scrolledWindow,
!control->getSettings()->isScrollbarFadeoutDisabled());
}
// Part 2: update sidebar position
GtkPaned* paned = GTK_PANED(this->panedContainerWidget.get());
// Allocation is reset when we switch up the contained elements. Fetch the
// width here in case we need it afterwards.
int contentWidth = gtk_widget_get_width(this->boxContainerWidget.get());
bool sidebarRight = control->getSettings()->isSidebarOnRight();
if (sidebarRight != (gtk_paned_get_child2(paned) == this->sidebarWidget.get())) {
// switch sidebar and main content
GtkWidget* sidebar = this->sidebarWidget.get();
GtkWidget* mainContent = this->sidebarVisible ? this->mainContentWidget.get() : nullptr;
#if GTK_MAJOR_VERSION == 3
if (this->sidebarVisible) {
gtk_container_remove(GTK_CONTAINER(paned), sidebar);
gtk_container_remove(GTK_CONTAINER(paned), mainContent);
if (sidebarRight) {
gtk_paned_pack1(paned, mainContent, true, false);
gtk_paned_pack2(paned, sidebar, false, false);
} else {
gtk_paned_pack1(paned, sidebar, false, false);
gtk_paned_pack2(paned, mainContent, true, false);
}
} else {
// The sidebar is hidden. That means the paned widget only contains the
// sidebar while the main contents are shown alone in the box container.
gtk_container_remove(GTK_CONTAINER(paned), sidebar);
if (sidebarRight) {
gtk_paned_pack2(paned, sidebar, false, false);
} else {
gtk_paned_pack1(paned, sidebar, false, false);
}
}
#else
gtk_paned_set_start_child(paned, nullptr);
gtk_paned_set_end_child(paned, nullptr);
if (sidebarRight) {
gtk_paned_set_start_child(paned, mainContent);
gtk_paned_set_start_resize(paned, true);
gtk_paned_set_start_shrink(paned, false);
gtk_paned_set_end_child(paned, sidebar);
gtk_paned_set_end_resize(paned, false);
gtk_paned_set_end_shrink(paned, false);
} else {
gtk_paned_set_end_child(paned, mainContent);
gtk_paned_set_end_resize(paned, true);
gtk_paned_set_end_shrink(paned, false);
gtk_paned_set_start_child(paned, sidebar);
gtk_paned_set_start_resize(paned, false);
gtk_paned_set_start_shrink(paned, false);
}
#endif
}
if (this->sidebarVisible) {
updatePanedPosition(contentWidth);
}
}
auto MainWindow::deleteEventCallback(GtkWidget* widget, GdkEvent* event, Control* control) -> bool {
control->quit();
return true;
}
void MainWindow::setSidebarVisible(bool visible) {
if (!visible && (this->control->getSidebar() != nullptr)) {
this->control->getSidebar()->saveSize();
}
if (visible != this->sidebarVisible) {
// Due to a GTK bug, we can't just hide the sidebar widget in the GtkPaned.
// If we do this, we create a dead region where the pane separator was previously.
// In this region, we can't use the touchscreen to start horizontal strokes.
// As such:
if (!visible) {
// hide sidebar
#if GTK_MAJOR_VERSION == 3
gtk_container_remove(GTK_CONTAINER(panedContainerWidget.get()), mainContentWidget.get());
#else
if (control->getSettings()->isSidebarOnRight()) {
gtk_paned_set_start_child(GTK_PANED(panedContainerWidget.get()), nullptr);
} else {
gtk_paned_set_end_child(GTK_PANED(panedContainerWidget.get()), nullptr);
}
#endif
gtk_box_remove(GTK_BOX(boxContainerWidget.get()), panedContainerWidget.get());
gtk_box_append(GTK_BOX(boxContainerWidget.get()), mainContentWidget.get());
this->sidebarVisible = false;
} else {
// show sidebar
// Allocation is reset when we switch up the contained elements. Fetch the
// width here in case we need it afterwards.
int contentWidth = gtk_widget_get_width(boxContainerWidget.get());
gtk_box_remove(GTK_BOX(boxContainerWidget.get()), mainContentWidget.get());
#if GTK_MAJOR_VERSION == 3
if (control->getSettings()->isSidebarOnRight()) {
gtk_paned_pack1(GTK_PANED(panedContainerWidget.get()), mainContentWidget.get(), true, false);
} else {
gtk_paned_pack2(GTK_PANED(panedContainerWidget.get()), mainContentWidget.get(), true, false);
}
#else
if (control->getSettings()->isSidebarOnRight()) {
gtk_paned_set_start_child(GTK_PANED(panedContainerWidget.get()), mainContentWidget.get());
} else {
gtk_paned_set_end_child(GTK_PANED(panedContainerWidget.get()), mainContentWidget.get());
}
#endif
gtk_box_append(GTK_BOX(boxContainerWidget.get()), panedContainerWidget.get());
this->sidebarVisible = true;
updatePanedPosition(contentWidth);
}
}
gtk_widget_set_visible(sidebarWidget.get(), visible);
}
/**
* Invert the position of the paned widget and disconnect from the signal.
* @param handlerId should be the ID of the signal handler that should be disconnected.
*/
static void invertPanedPosition(GtkWidget* widget, GtkAllocation* allocation, gulong* handlerId) {
int newDividerPos = allocation->width - gtk_paned_get_position(GTK_PANED(widget));
gtk_paned_set_position(GTK_PANED(widget), newDividerPos);
// We only need to switch the position once, so disconnect the signal right away.
g_signal_handler_disconnect(widget, *handlerId);
}
void MainWindow::updatePanedPosition(int contentWidth) {
if (!this->control->getSettings()->isSidebarOnRight()) {
// Sidebar is on the left side.
gtk_paned_set_position(GTK_PANED(this->panedContainerWidget.get()),
this->control->getSettings()->getSidebarWidth());
} else {
// Sidebar is on the right side.
if (contentWidth > 0) {
int dividerPos = contentWidth - this->control->getSettings()->getSidebarWidth();
gtk_paned_set_position(GTK_PANED(this->panedContainerWidget.get()), dividerPos);
} else {
// Allocation is unkown (window hasn't been shown yet). We have to wait for the signal.
// Set position as if the sidebar was on the left side, and let the signal handler
// simply invert the position when the allocation is known.
gtk_paned_set_position(GTK_PANED(this->panedContainerWidget.get()),
this->control->getSettings()->getSidebarWidth());
gulong* signal_id = new gulong{};
*signal_id = g_signal_connect_data(
this->panedContainerWidget.get(), "size-allocate",
xoj::util::wrap_for_g_callback_v<invertPanedPosition>, signal_id,
[](gpointer d, GClosure*) { delete reinterpret_cast<gulong*>(d); }, GConnectFlags(0));
}
}
}
void MainWindow::setToolbarVisible(bool visible) {
Settings* settings = control->getSettings();
settings->setToolbarVisible(visible);
for (auto& w: this->toolbarWidgets) {
if (!visible || (gtk_toolbar_get_n_items(GTK_TOOLBAR(w.get())) != 0)) {
gtk_widget_set_visible(w.get(), visible);
}
}
}
void MainWindow::setMenubarVisible(bool visible) {
gtk_application_window_set_show_menubar(GTK_APPLICATION_WINDOW(this->getWindow()), visible);
}
void MainWindow::setMaximized(bool maximized) { this->maximized = maximized; }
auto MainWindow::isMaximized() const -> bool { return this->maximized; }
auto MainWindow::setFullscreen(bool enabled) const -> void {
if (enabled) {
gtk_window_fullscreen(GTK_WINDOW(this->getWindow()));
} else {
gtk_window_unfullscreen(GTK_WINDOW(this->getWindow()));
}
}
auto MainWindow::isDarkTheme() const -> bool { return this->darkMode; }
auto MainWindow::getXournal() const -> XournalView* { return xournal.get(); }
auto MainWindow::windowMaximizedCallback(GObject* window, GParamSpec*, MainWindow* win) -> void {
win->setMaximized(gtk_window_is_maximized(GTK_WINDOW(window)));
}
void MainWindow::toolbarSelected(const std::string& id) {
const auto& toolbars = toolbar->getModel()->getToolbars();
auto it = std::find_if(toolbars.begin(), toolbars.end(), [&](const auto& d) { return d->getId() == id; });
toolbarSelected(it == toolbars.end() ? nullptr : it->get());
}
void MainWindow::toolbarSelected(ToolbarData* d) {
if (!d || this->selectedToolbar == d) {
return;
}
Settings* settings = control->getSettings();
settings->setSelectedToolbar(d->getId());
this->clearToolbar();
this->loadToolbar(d);
}
auto MainWindow::clearToolbar() -> const ToolbarData* {
if (this->selectedToolbar != nullptr) {
for (size_t i = 0; i < TOOLBAR_DEFINITIONS_LEN; i++) {
ToolMenuHandler::unloadToolbar(this->toolbarWidgets[i].get());
}
this->toolbar->freeDynamicToolbarItems();
}
return std::exchange(this->selectedToolbar, nullptr);
}
void MainWindow::loadToolbar(ToolbarData* d) {
this->selectedToolbar = d;
for (size_t i = 0; i < TOOLBAR_DEFINITIONS_LEN; i++) {
this->toolbar->load(d, this->toolbarWidgets[i].get(), TOOLBAR_DEFINITIONS[i].propName,
TOOLBAR_DEFINITIONS[i].horizontal);
}
this->floatingToolbox->flagRecalculateSizeRequired();
}
void MainWindow::reloadToolbars() {
ToolbarData* d = getSelectedToolbar();
this->clearToolbar();
this->toolbarSelected(d);
}
auto MainWindow::getSelectedToolbar() const -> ToolbarData* { return this->selectedToolbar; }
auto MainWindow::getToolbarWidgets() const -> const ToolbarWidgetArray& { return toolbarWidgets; }
auto MainWindow::getToolbarName(GtkToolbar* toolbar) const -> const char* {
for (size_t i = 0; i < TOOLBAR_DEFINITIONS_LEN; i++) {
if (static_cast<void*>(this->toolbarWidgets[i].get()) == static_cast<void*>(toolbar)) {
return TOOLBAR_DEFINITIONS[i].propName;
}
}
return "";
}
void MainWindow::setDynamicallyGeneratedSubmenuDisabled(bool disabled) { menubar->setDisabled(disabled); }
void MainWindow::updateToolbarMenu() {
menubar->getToolbarSelectionSubmenu().update(toolbar.get(), this->selectedToolbar);
}
void MainWindow::createToolbar() {
toolbarSelected(control->getSettings()->getSelectedToolbar());
this->control->getScheduler()->unblockRerenderZoom();
}
void MainWindow::updatePageNumbers(size_t page, size_t pagecount, size_t pdfpage) {
toolbar->setPageInfo(page, pagecount, pdfpage);
}
auto MainWindow::getMenubar() const -> Menubar* { return menubar.get(); }
void MainWindow::show(GtkWindow* parent) { gtk_widget_show(this->window); }
void MainWindow::setUndoDescription(const string& description) { menubar->setUndoDescription(description); }
void MainWindow::setRedoDescription(const string& description) { menubar->setRedoDescription(description); }
auto MainWindow::getToolbarModel() const -> ToolbarModel* { return this->toolbar->getModel(); }
auto MainWindow::getToolMenuHandler() const -> ToolMenuHandler* { return this->toolbar.get(); }
void MainWindow::loadMainCSS(GladeSearchpath* gladeSearchPath, const gchar* cssFilename) {
auto filepath = gladeSearchPath->findFile("", cssFilename);
xoj::util::GObjectSPtr<GtkCssProvider> provider(gtk_css_provider_new(), xoj::util::adopt);
gtk_css_provider_load_from_path(provider.get(), filepath.u8string().c_str(), nullptr);
gtk_style_context_add_provider_for_screen(gdk_screen_get_default(), GTK_STYLE_PROVIDER(provider.get()),
GTK_STYLE_PROVIDER_PRIORITY_APPLICATION);
}
PdfFloatingToolbox* MainWindow::getPdfToolbox() const { return this->pdfFloatingToolBox.get(); }
FloatingToolbox* MainWindow::getFloatingToolbox() const { return this->floatingToolbox.get(); }
| 31,276
|
C++
|
.cpp
| 599
| 44.404007
| 120
| 0.65148
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,528
|
LegacyRedrawable.cpp
|
xournalpp_xournalpp/src/core/gui/LegacyRedrawable.cpp
|
#include "LegacyRedrawable.h"
#include "model/Element.h" // for Element
#include "util/Range.h" // for Range
void LegacyRedrawable::repaintElement(Element* e) const {
repaintArea(e->getX(), e->getY(), e->getElementWidth() + e->getX(), e->getElementHeight() + e->getY());
}
void LegacyRedrawable::repaintRect(double x, double y, double width, double height) const {
repaintArea(x, y, x + width, y + height);
}
void LegacyRedrawable::rerenderRange(const Range& r) { rerenderRect(r.getX(), r.getY(), r.getWidth(), r.getHeight()); }
void LegacyRedrawable::rerenderElement(Element* e) {
rerenderRect(e->getX(), e->getY(), e->getElementWidth(), e->getElementHeight());
}
| 687
|
C++
|
.cpp
| 13
| 50.538462
| 119
| 0.705531
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,529
|
Builder.cpp
|
xournalpp_xournalpp/src/core/gui/Builder.cpp
|
#include "Builder.h"
#include "GladeSearchpath.h" // for GladeSearchpath
#include "filesystem.h" // for path
Builder::Builder(GladeSearchpath* gladeSearchPath, const std::string& uiFile):
builder(gtk_builder_new_from_file(gladeSearchPath->findFile("", uiFile).u8string().c_str()), xoj::util::adopt) {
}
| 320
|
C++
|
.cpp
| 6
| 50.666667
| 120
| 0.724359
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,530
|
GladeGui.cpp
|
xournalpp_xournalpp/src/core/gui/GladeGui.cpp
|
#include "GladeGui.h"
#include <cstdlib> // for exit
#include <glib-object.h> // for g_object_unref
#include <glib.h> // for g_error_free, GError, g_warning
#include "util/PlaceholderString.h" // for PlaceholderString
#include "util/XojMsgBox.h" // for XojMsgBox
#include "util/i18n.h" // for FS, _F
#include "GladeSearchpath.h" // for GladeSearchpath
#include "filesystem.h" // for path
GladeGui::GladeGui(GladeSearchpath* gladeSearchPath, const std::string& glade, const std::string& mainWnd) {
this->gladeSearchPath = gladeSearchPath;
auto filepath = this->gladeSearchPath->findFile("", glade);
GError* error = nullptr;
builder.reset(gtk_builder_new(), xoj::util::adopt);
if (!gtk_builder_add_from_file(builder.get(), filepath.u8string().c_str(), &error)) {
std::string msg =
FS(_F("Error loading glade file \"{1}\" (try to load \"{2}\")") % glade % filepath.u8string());
if (error != nullptr) {
msg += "\n";
msg += error->message;
g_error_free(error);
}
XojMsgBox::showErrorAndQuit(msg, -1);
}
this->window = get(mainWnd);
}
GladeGui::~GladeGui() {
if (!gtk_widget_get_parent(window)) {
gtk_widget_destroy(window);
}
}
auto GladeGui::get(const std::string& name) -> GtkWidget* {
GtkWidget* w = GTK_WIDGET(gtk_builder_get_object(builder.get(), name.c_str()));
if (w == nullptr) {
g_warning("GladeGui::get: Could not find glade Widget: \"%s\"", name.c_str());
}
return w;
}
auto GladeGui::getWindow() const -> GtkWidget* { return this->window; }
auto GladeGui::getGladeSearchPath() const -> GladeSearchpath* { return this->gladeSearchPath; }
auto GladeGui::getBuilder() const -> GtkBuilder* { return this->builder.get(); }
| 1,833
|
C++
|
.cpp
| 41
| 39.634146
| 111
| 0.638154
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,531
|
XournalView.cpp
|
xournalpp_xournalpp/src/core/gui/XournalView.cpp
|
#include "XournalView.h"
#include <algorithm> // for max, min
#include <iterator> // for begin
#include <memory> // for unique_ptr, make_unique
#include <optional> // for optional
#include <gdk/gdk.h> // for GdkEventKey, GDK_SHIF...
#include <gdk/gdkkeysyms.h> // for GDK_KEY_Page_Down
#include <glib-object.h> // for g_object_ref_sink
#include "control/Control.h" // for Control
#include "control/PdfCache.h" // for PdfCache
#include "control/ScrollHandler.h" // for ScrollHandler
#include "control/ToolHandler.h" // for ToolHandler
#include "control/actions/ActionDatabase.h" // for ActionDatabase
#include "control/jobs/XournalScheduler.h" // for XournalScheduler
#include "control/settings/MetadataManager.h" // for MetadataManager
#include "control/settings/Settings.h" // for Settings
#include "control/tools/CursorSelectionType.h" // for CURSOR_SELECTION_NONE
#include "control/tools/EditSelection.h" // for EditSelection
#include "control/zoom/ZoomControl.h" // for ZoomControl
#include "gui/MainWindow.h" // for MainWindow
#include "gui/PdfFloatingToolbox.h" // for PdfFloatingToolbox
#include "gui/inputdevices/HandRecognition.h" // for HandRecognition
#include "gui/inputdevices/InputContext.h" // for InputContext
#include "gui/toolbarMenubar/ColorToolItem.h" // for ColorToolItem
#include "gui/toolbarMenubar/ToolMenuHandler.h" // for ToolMenuHandler
#include "gui/widgets/XournalWidget.h" // for gtk_xournal_get_layout
#include "model/Document.h" // for Document
#include "model/Element.h" // for Element, ELEMENT_STROKE
#include "model/PageRef.h" // for PageRef
#include "model/Stroke.h" // for Stroke, StrokeTool::E...
#include "model/XojPage.h" // for XojPage
#include "undo/DeleteUndoAction.h" // for DeleteUndoAction
#include "undo/UndoRedoHandler.h" // for UndoRedoHandler
#include "util/Assert.h" // for xoj_assert
#include "util/Point.h" // for Point
#include "util/Rectangle.h" // for Rectangle
#include "util/Util.h" // for npos
#include "util/glib_casts.h" // for wrap_v
#include "util/safe_casts.h" // for round_cast
#include "Layout.h" // for Layout
#include "PageView.h" // for XojPageView
#include "RepaintHandler.h" // for RepaintHandler
#include "XournalppCursor.h" // for XournalppCursor
using xoj::util::Rectangle;
constexpr int REGULAR_MOVE_AMOUNT = 3;
constexpr int SMALL_MOVE_AMOUNT = 1;
constexpr int LARGE_MOVE_AMOUNT = 10;
std::pair<size_t, size_t> XournalView::preloadPageBounds(size_t page, size_t maxPage) {
const size_t preloadBefore = this->control->getSettings()->getPreloadPagesBefore();
const size_t preloadAfter = this->control->getSettings()->getPreloadPagesAfter();
const size_t lower = page > preloadBefore ? page - preloadBefore : 0;
const size_t upper = std::min(maxPage, page + preloadAfter);
return {lower, upper};
}
XournalView::XournalView(GtkWidget* parent, Control* control, ScrollHandling* scrollHandling):
scrollHandling(scrollHandling), control(control) {
Document* doc = control->getDocument();
doc->lock();
if (doc->getPdfPageCount() != 0) {
this->cache = std::make_unique<PdfCache>(doc->getPdfDocument(), control->getSettings());
}
doc->unlock();
registerListener(control);
InputContext* inputContext = new InputContext(this, scrollHandling);
this->widget = gtk_xournal_new(this, inputContext);
g_object_ref_sink(this->widget); // take ownership without increasing the ref count
gtk_container_add(GTK_CONTAINER(parent), this->widget);
gtk_widget_show(this->widget);
g_signal_connect(getWidget(), "realize", G_CALLBACK(onRealized), this);
this->repaintHandler = std::make_unique<RepaintHandler>(this);
this->handRecognition = std::make_unique<HandRecognition>(this->widget, inputContext, control->getSettings());
control->getZoomControl()->addZoomListener(this);
gtk_widget_set_can_default(this->widget, true);
gtk_widget_grab_default(this->widget);
gtk_widget_grab_focus(this->widget);
this->cleanupTimeout = g_timeout_add_seconds(5, xoj::util::wrap_v<clearMemoryTimer>, this);
}
XournalView::~XournalView() {
g_source_remove(this->cleanupTimeout);
gtk_widget_destroy(this->widget);
this->widget = nullptr;
}
auto XournalView::clearMemoryTimer(XournalView* widget) -> gboolean {
widget->cleanupBufferCache();
return true;
}
auto XournalView::cleanupBufferCache() -> void {
const auto& [pagesLower, pagesUpper] = this->preloadPageBounds(this->currentPage, this->viewPages.size());
xoj_assert(pagesLower <= pagesUpper);
for (size_t i = 0; i < this->viewPages.size(); i++) {
auto&& page = this->viewPages[i];
const size_t pageNum = i + 1;
const bool isPreload = pagesLower <= pageNum && pageNum <= pagesUpper;
if (!isPreload && !page->isVisible() && page->hasBuffer()) {
page->deleteViewBuffer();
}
}
}
auto XournalView::getCurrentPage() const -> size_t { return currentPage; }
const int scrollKeySize = 30;
auto XournalView::onKeyPressEvent(const KeyEvent& event) -> bool {
size_t p = getCurrentPage();
if (p != npos && p < this->viewPages.size()) {
auto& v = this->viewPages[p];
if (v->onKeyPressEvent(event)) {
return true;
}
}
auto keyval = event.keyval;
auto state = event.state;
if (auto* tool = getControl()->getWindow()->getPdfToolbox(); tool->hasSelection()) {
if (keyval == GDK_KEY_c && state == GDK_CONTROL_MASK) {
// Shortcut to get selected PDF text.
tool->copyTextToClipboard();
return true;
}
}
if (auto* selection = getSelection(); selection) {
if (keyval == GDK_KEY_Escape) {
clearSelection();
return true;
}
int d = REGULAR_MOVE_AMOUNT;
if (state == GDK_MOD1_MASK) {
d = SMALL_MOVE_AMOUNT;
} else if (state == GDK_SHIFT_MASK) {
d = LARGE_MOVE_AMOUNT;
}
int xdir = 0;
int ydir = 0;
if (keyval == GDK_KEY_Left) {
xdir = -1;
} else if (keyval == GDK_KEY_Up) {
ydir = -1;
} else if (keyval == GDK_KEY_Right) {
xdir = 1;
} else if (keyval == GDK_KEY_Down) {
ydir = 1;
}
if (xdir != 0 || ydir != 0) {
selection->moveSelection(d * xdir, d * ydir, /*addMoveUndo=*/true);
selection->ensureWithinVisibleArea();
return true;
}
}
Layout* layout = gtk_xournal_get_layout(this->widget);
if (!state) {
if (keyval == GDK_KEY_Page_Down || keyval == GDK_KEY_KP_Page_Down) {
control->getScrollHandler()->goToNextPage();
return true;
}
if (keyval == GDK_KEY_Page_Up || keyval == GDK_KEY_KP_Page_Up) {
control->getScrollHandler()->goToPreviousPage();
return true;
}
}
if (keyval == GDK_KEY_space) {
GtkAllocation alloc = {0};
gtk_widget_get_allocation(gtk_widget_get_parent(this->widget), &alloc);
int windowHeight = alloc.height - scrollKeySize;
if (!state) {
layout->scrollRelative(0, windowHeight);
return true;
}
if (state == GDK_SHIFT_MASK) {
layout->scrollRelative(0, -windowHeight);
return true;
}
}
// Numeric keypad always navigates by page
if (keyval == GDK_KEY_KP_Up) {
this->pageRelativeXY(0, -1);
return true;
}
if (keyval == GDK_KEY_KP_Down) {
this->pageRelativeXY(0, 1);
return true;
}
if (keyval == GDK_KEY_KP_Left) {
this->pageRelativeXY(-1, 0);
return true;
}
if (keyval == GDK_KEY_KP_Right) {
this->pageRelativeXY(1, 0);
return true;
}
if (keyval == GDK_KEY_Up || keyval == GDK_KEY_k || keyval == GDK_KEY_K) {
if (control->getSettings()->isPresentationMode()) {
control->getScrollHandler()->goToPreviousPage();
return true;
}
if (state == GDK_SHIFT_MASK) {
this->pageRelativeXY(0, -1);
return true;
}
if (!state) {
layout->scrollRelative(0, -scrollKeySize);
return true;
}
}
if (keyval == GDK_KEY_Down || keyval == GDK_KEY_j || keyval == GDK_KEY_J) {
if (control->getSettings()->isPresentationMode()) {
control->getScrollHandler()->goToNextPage();
return true;
}
if (state == GDK_SHIFT_MASK) {
this->pageRelativeXY(0, 1);
return true;
}
if (!state) {
layout->scrollRelative(0, scrollKeySize);
return true;
}
}
if (keyval == GDK_KEY_Left || keyval == GDK_KEY_h) {
if (state == GDK_SHIFT_MASK) {
this->pageRelativeXY(-1, 0);
return true;
}
if (!state) {
if (control->getSettings()->isPresentationMode()) {
control->getScrollHandler()->goToPreviousPage();
} else {
layout->scrollRelative(-scrollKeySize, 0);
}
return true;
}
}
if (keyval == GDK_KEY_Right || keyval == GDK_KEY_l) {
if (state == GDK_SHIFT_MASK) {
this->pageRelativeXY(1, 0);
return true;
}
if (!state) {
if (control->getSettings()->isPresentationMode()) {
control->getScrollHandler()->goToNextPage();
} else {
layout->scrollRelative(scrollKeySize, 0);
}
return true;
}
}
if (keyval == GDK_KEY_End || keyval == GDK_KEY_KP_End) {
control->getScrollHandler()->goToLastPage();
return true;
}
if (keyval == GDK_KEY_Home || keyval == GDK_KEY_KP_Home) {
control->getScrollHandler()->goToFirstPage();
return true;
}
// Switch color on number key
auto& colors = control->getWindow()->getToolMenuHandler()->getColorToolItems();
if (!state && (keyval >= GDK_KEY_0) && (keyval < GDK_KEY_0 + std::min((std::size_t)10, colors.size()))) {
std::size_t index = std::min(colors.size() - 1, (std::size_t)(9 + (keyval - GDK_KEY_0)) % 10);
const auto& colorToolItem = colors.at(index);
if (auto* db = control->getActionDatabase(); db->isActionEnabled(Action::TOOL_COLOR)) {
control->getActionDatabase()->fireChangeActionState(Action::TOOL_COLOR, colorToolItem->getColor());
}
return true;
}
return false;
}
auto XournalView::getRepaintHandler() const -> RepaintHandler* { return this->repaintHandler.get(); }
auto XournalView::onKeyReleaseEvent(const KeyEvent& event) -> bool {
size_t p = getCurrentPage();
if (p != npos && p < this->viewPages.size()) {
auto& v = this->viewPages[p];
if (v->onKeyReleaseEvent(event)) {
return true;
}
}
return false;
}
void XournalView::onRealized(GtkWidget* widget, XournalView* view) {
// Disable event compression
if (gtk_widget_get_realized(view->getWidget())) {
gdk_window_set_event_compression(gtk_widget_get_window(view->getWidget()), false);
} else {
g_warning("could not disable event compression");
}
}
void XournalView::onSettingsChanged() {
if (this->cache) {
this->cache->updateSettings(control->getSettings());
}
}
// send the focus back to the appropriate widget
void XournalView::requestFocus() { gtk_widget_grab_focus(this->widget); }
auto XournalView::searchTextOnPage(const std::string& text, size_t pageNumber, size_t index, size_t* occurrences,
XojPdfRectangle* matchRect) -> bool {
if (pageNumber == npos || pageNumber >= this->viewPages.size()) {
return false;
}
auto& v = this->viewPages[pageNumber];
return v->searchTextOnPage(text, index, occurrences, matchRect);
}
void XournalView::forceUpdatePagenumbers() {
size_t p = this->currentPage;
this->currentPage = npos;
control->firePageSelected(p);
}
auto XournalView::getViewFor(size_t pageNr) const -> XojPageView* {
if (pageNr == npos || pageNr >= this->viewPages.size()) {
return nullptr;
}
return this->viewPages[pageNr].get();
}
void XournalView::pageSelected(size_t page) {
if (this->currentPage == page && this->lastSelectedPage == page) {
return;
}
Document* doc = control->getDocument();
doc->lock();
auto const& file = doc->getEvMetadataFilename();
doc->unlock();
control->getMetadataManager()->storeMetadata(file, static_cast<int>(page), getZoom());
control->getWindow()->getPdfToolbox()->userCancelSelection();
if (this->lastSelectedPage != npos && this->lastSelectedPage < this->viewPages.size()) {
this->viewPages[this->lastSelectedPage]->setSelected(false);
}
endTextAllPages();
this->currentPage = page;
size_t pdfPage = npos;
if (page != npos && page < viewPages.size()) {
auto& vp = viewPages[page];
vp->setSelected(true);
lastSelectedPage = page;
pdfPage = vp->getPage()->getPdfPageNr();
}
control->updatePageNumbers(currentPage, pdfPage);
control->updateBackgroundSizeButton();
control->updatePageActions();
if (control->getSettings()->isEagerPageCleanup()) {
this->cleanupBufferCache();
}
// Load surrounding pages if they are not
const auto& [pagesLower, pagesUpper] = preloadPageBounds(page, this->viewPages.size());
xoj_assert(pagesLower <= pagesUpper);
for (size_t i = pagesLower; i < pagesUpper; i++) {
if (!this->viewPages[i]->hasBuffer()) {
this->viewPages[i]->rerenderPage();
}
}
}
auto XournalView::getControl() const -> Control* { return control; }
void XournalView::scrollTo(size_t pageNo, XojPdfRectangle rect) {
double zoom = getZoom();
if (pageNo >= this->viewPages.size()) {
return;
}
auto& v = this->viewPages[pageNo];
// Make sure it is visible
Layout* layout = gtk_xournal_get_layout(this->widget);
int x = v->getX() + round_cast<int>(rect.x1 * zoom);
int y = v->getY() + round_cast<int>(rect.y1 * zoom);
int width;
int height;
if (rect.x2 == -1 || rect.y2 == -1) {
width = v->getDisplayWidth();
height = v->getDisplayHeight();
} else {
width = round_cast<int>((rect.x2 - rect.x1) * zoom);
height = round_cast<int>((rect.y2 - rect.y1) * zoom);
}
layout->ensureRectIsVisible(x, y, width, height);
// Select the page
control->firePageSelected(pageNo);
}
void XournalView::pageRelativeXY(int offCol, int offRow) {
size_t currPage = getCurrentPage();
XojPageView* view = getViewFor(currPage);
int row = view->getMappedRow();
int col = view->getMappedCol();
Layout* layout = gtk_xournal_get_layout(this->widget);
auto optionalPageIndex = layout->getPageIndexAtGridMap(as_unsigned(row + offRow), as_unsigned(col + offCol));
if (optionalPageIndex) {
this->scrollTo(*optionalPageIndex);
}
}
void XournalView::endTextAllPages(XojPageView* except) const {
for (auto& v: this->viewPages) {
if (except != v.get()) {
v->endText();
}
}
}
void XournalView::endSplineAllPages() const {
for (auto& v: this->viewPages) {
v->endSpline();
}
}
void XournalView::layerChanged(size_t page) {
if (page != npos && page < this->viewPages.size()) {
this->viewPages[page]->rerenderPage();
}
}
void XournalView::getPasteTarget(double& x, double& y) const {
size_t pageNo = getCurrentPage();
if (pageNo == npos) {
return;
}
Rectangle<double>* rect = getVisibleRect(pageNo);
if (rect) {
x = rect->x + rect->width / 2;
y = rect->y + rect->height / 2;
delete rect;
}
}
/**
* Return the rectangle which is visible on screen, in document cooordinates
*
* Or nullptr if the page is not visible
*/
auto XournalView::getVisibleRect(size_t page) const -> Rectangle<double>* {
if (page == npos || page >= this->viewPages.size()) {
return nullptr;
}
auto& p = this->viewPages[page];
return getVisibleRect(p.get());
}
auto XournalView::getVisibleRect(const XojPageView* redrawable) const -> Rectangle<double>* {
return gtk_xournal_get_visible_area(this->widget, redrawable);
}
void XournalView::recreatePdfCache() {
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();
}
/**
* @return Helper class for Touch specific fixes
*/
auto XournalView::getHandRecognition() const -> HandRecognition* { return handRecognition.get(); }
/**
* @return Scrollbars
*/
auto XournalView::getScrollHandling() const -> ScrollHandling* { return scrollHandling; }
auto XournalView::getWidget() const -> GtkWidget* { return widget; }
void XournalView::ensureRectIsVisible(int x, int y, int width, int height) {
Layout* layout = gtk_xournal_get_layout(this->widget);
layout->ensureRectIsVisible(x, y, width, height);
}
void XournalView::zoomChanged() {
size_t currentPage = this->getCurrentPage();
XojPageView* view = getViewFor(currentPage);
ZoomControl* zoom = control->getZoomControl();
if (!view) {
return;
}
layoutPages();
if (zoom->isZoomPresentationMode() || zoom->isZoomFitMode()) {
scrollTo(currentPage);
} else if (zoom->isZoomSequenceActive()) {
auto pos = zoom->getScrollPositionAfterZoom();
Layout* layout = gtk_xournal_get_layout(this->widget);
layout->scrollAbs(pos.x, pos.y);
}
Document* doc = control->getDocument();
doc->lock();
auto const& file = doc->getEvMetadataFilename();
doc->unlock();
control->getMetadataManager()->storeMetadata(file, static_cast<int>(getCurrentPage()), zoom->getZoomReal());
// Updates the Eraser's cursor icon in order to make it as big as the erasing area
control->getCursor()->updateCursor();
// if we changed the zoom of the page, we should hide the pdf floating toolbox
// and if user clicked the selection again, the floating toolbox shows again
control->getWindow()->getPdfToolbox()->hide();
this->control->getScheduler()->blockRerenderZoom();
}
void XournalView::pageSizeChanged(size_t page) {
layoutPages();
if (page != npos && page < this->viewPages.size()) {
this->viewPages[page]->rerenderPage();
}
}
void XournalView::pageChanged(size_t page) {
if (page != npos && page < this->viewPages.size()) {
this->viewPages[page]->rerenderPage();
}
}
void XournalView::pageDeleted(size_t page) {
const size_t currentPageNo = control->getCurrentPageNo();
viewPages.erase(begin(viewPages) + static_cast<long>(page));
layoutPages();
if (currentPageNo > page) {
control->getScrollHandler()->scrollToPage(currentPageNo - 1);
} else {
control->getScrollHandler()->scrollToPage(currentPageNo);
}
}
auto XournalView::getTextEditor() const -> TextEditor* {
for (auto&& page: viewPages) {
if (page->getTextEditor()) {
return page->getTextEditor();
}
}
return nullptr;
}
auto XournalView::getCache() const -> PdfCache* { return this->cache.get(); }
void XournalView::pageInserted(size_t page) {
Document* doc = control->getDocument();
doc->lock();
auto pageView = std::make_unique<XojPageView>(this, doc->getPage(page));
doc->unlock();
viewPages.insert(begin(viewPages) + as_signed(page), std::move(pageView));
layoutPages();
// check which pages are visible and select the most visible page
Layout* layout = gtk_xournal_get_layout(this->widget);
layout->updateVisibility();
}
auto XournalView::getZoom() const -> double { return control->getZoomControl()->getZoom(); }
auto XournalView::getDpiScaleFactor() const -> int { return gtk_widget_get_scale_factor(widget); }
void XournalView::clearSelection() {
EditSelection* sel = GTK_XOURNAL(widget)->selection;
GTK_XOURNAL(widget)->selection = nullptr;
delete sel;
control->setClipboardHandlerSelection(getSelection());
getCursor()->setMouseSelectionType(CURSOR_SELECTION_NONE);
control->getToolHandler()->setSelectionEditTools(false, false, false, false);
}
void XournalView::deleteSelection(EditSelection* sel) {
if (sel == nullptr) {
sel = getSelection();
}
if (sel) {
auto undo = std::make_unique<DeleteUndoAction>(sel->getSourcePage(), false);
sel->fillUndoItem(undo.get());
control->getUndoRedoHandler()->addUndoAction(std::move(undo));
clearSelection();
repaintSelection(true);
}
}
void XournalView::setSelection(EditSelection* selection) {
clearSelection();
GTK_XOURNAL(this->widget)->selection = selection;
control->setClipboardHandlerSelection(getSelection());
bool canChangeSize = false;
bool canChangeColor = false;
bool canChangeFill = false;
bool canChangeLineStyle = false;
for (const Element* e: selection->getElements()) {
switch (e->getType()) {
case ELEMENT_TEXT:
canChangeColor = true;
continue;
case ELEMENT_STROKE: {
canChangeSize = true;
const auto* s = dynamic_cast<const Stroke*>(e);
if (s->getToolType() == StrokeTool::PEN) {
// can change everything, leave loop with break
canChangeColor = true;
canChangeFill = true;
canChangeLineStyle = true;
break;
}
if (s->getToolType() == StrokeTool::HIGHLIGHTER) {
canChangeColor = true;
canChangeFill = true;
}
continue;
}
default:
continue;
}
// leave loop
break;
}
control->getToolHandler()->setSelectionEditTools(canChangeColor, canChangeSize, canChangeFill, canChangeLineStyle);
repaintSelection();
}
void XournalView::repaintSelection(bool evenWithoutSelection) {
if (evenWithoutSelection) {
gtk_widget_queue_draw(this->widget);
return;
}
EditSelection* selection = getSelection();
if (selection == nullptr) {
return;
}
// repaint always the whole widget
gtk_widget_queue_draw(this->widget);
}
void XournalView::layoutPages() {
Layout* layout = gtk_xournal_get_layout(this->widget);
layout->recalculate();
// Todo (fabian): the following lines are conceptually wrong, the Layout::layoutPages function is meant to be
// called by an expose event, but removing it, will break "add page".
auto rectangle = layout->getVisibleRect();
layout->layoutPages(std::max<int>(layout->getMinimalWidth(), round_cast<int>(rectangle.width)),
std::max<int>(layout->getMinimalHeight(), round_cast<int>(rectangle.height)));
}
auto XournalView::getDisplayHeight() const -> int {
GtkAllocation allocation = {0};
gtk_widget_get_allocation(this->widget, &allocation);
return allocation.height;
}
auto XournalView::getDisplayWidth() const -> int {
GtkAllocation allocation = {0};
gtk_widget_get_allocation(this->widget, &allocation);
return allocation.width;
}
auto XournalView::isPageVisible(size_t page, int* visibleHeight) const -> bool {
Rectangle<double>* rect = getVisibleRect(page);
if (rect) {
if (visibleHeight) {
*visibleHeight = round_cast<int>(rect->height);
}
delete rect;
return true;
}
if (visibleHeight) {
*visibleHeight = 0;
}
return false;
}
void XournalView::documentChanged(DocumentChangeType type) {
if (type != DOCUMENT_CHANGE_CLEARED && type != DOCUMENT_CHANGE_COMPLETE) {
return;
}
XournalScheduler* scheduler = this->control->getScheduler();
scheduler->lock();
scheduler->removeAllJobs();
clearSelection();
viewPages.clear();
recreatePdfCache();
Document* doc = control->getDocument();
doc->lock();
size_t pagecount = doc->getPageCount();
viewPages.reserve(pagecount);
for (size_t i = 0; i < pagecount; i++) {
viewPages.emplace_back(std::make_unique<XojPageView>(this, doc->getPage(i)));
}
doc->unlock();
layoutPages();
scrollTo(0);
scheduler->unlock();
}
auto XournalView::cut() -> bool {
size_t p = getCurrentPage();
if (p == npos || p >= viewPages.size()) {
return false;
}
auto& page = viewPages[p];
return page->cut();
}
auto XournalView::copy() -> bool {
size_t p = getCurrentPage();
if (p == npos || p >= viewPages.size()) {
return false;
}
auto& page = viewPages[p];
return page->copy();
}
auto XournalView::paste() -> bool {
size_t p = getCurrentPage();
if (p == npos || p >= viewPages.size()) {
return false;
}
auto& page = viewPages[p];
return page->paste();
}
auto XournalView::actionDelete() -> bool {
size_t p = getCurrentPage();
if (p == npos || p >= viewPages.size()) {
return false;
}
auto& page = viewPages[p];
return page->actionDelete();
}
auto XournalView::getDocument() const -> Document* { return control->getDocument(); }
auto XournalView::getViewPages() const -> std::vector<std::unique_ptr<XojPageView>> const& { return viewPages; }
auto XournalView::getCursor() const -> XournalppCursor* { return control->getCursor(); }
auto XournalView::getSelection() const -> EditSelection* {
g_return_val_if_fail(this->widget != nullptr, nullptr);
g_return_val_if_fail(GTK_IS_XOURNAL(this->widget), nullptr);
return GTK_XOURNAL(this->widget)->selection;
}
| 26,614
|
C++
|
.cpp
| 680
| 32.797059
| 119
| 0.629323
|
xournalpp/xournalpp
| 10,962
| 791
| 1,098
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
12,532
|
SearchBar.cpp
|
xournalpp_xournalpp/src/core/gui/SearchBar.cpp
|
#include "SearchBar.h"
#include <string> // for allocator, string
#include <gdk/gdk.h> // for GdkEventKey, GDK_SHIFT_MASK
#include <gdk/gdkkeysyms.h> // for GDK_KEY_Return
#include <glib-object.h> // for G_CALLBACK, g_signal_connect
#include <glib.h> // for g_free, g_strdup_printf
#include "control/Control.h" // for Control
#include "control/ScrollHandler.h" // for ScrollHandler
#include "control/zoom/ZoomControl.h" // for ZoomControl
#include "gui/MainWindow.h" // for MainWindow
#include "model/Document.h" // for Document
#include "util/PlaceholderString.h" // for PlaceholderString
#include "util/i18n.h" // for _, FC, _F
SearchBar::SearchBar(Control* control): control(control) {
MainWindow* win = control->getWindow();
GtkWidget* close = win->get("buttonCloseSearch");
g_signal_connect(close, "clicked", G_CALLBACK(buttonCloseSearchClicked), this);
GtkWidget* next = win->get("btSearchForward");
GtkWidget* previous = win->get("btSearchBack");
g_signal_connect(next, "clicked", G_CALLBACK(+[](GtkButton* button, SearchBar* self) { self->searchNext(); }),
this);
g_signal_connect(previous, "clicked",
G_CALLBACK(+[](GtkButton* button, SearchBar* self) { self->searchPrevious(); }), this);
// TODO(fabian): When keybindings are implemented, handle previous search keybinding properly
GtkWidget* searchTextField = win->get("searchTextField");
g_signal_connect(searchTextField, "search-changed", G_CALLBACK(searchTextChangedCallback), this);
// Enable next/previous search when pressing Enter / Shift+Enter
g_signal_connect(searchTextField, "key-press-event",
G_CALLBACK(+[](GtkWidget* entry, GdkEventKey* event, SearchBar* self) {
if (event->keyval == GDK_KEY_Return) {
if (event->state & GDK_SHIFT_MASK) {
self->searchPrevious();
} else {
self->searchNext();
}
// Grab focus again since searching will take away focus
gtk_widget_grab_focus(entry);
return true;
} else if (event->keyval == GDK_KEY_Escape) {
self->showSearchBar(false);
return true;
}
return false;
}),
this);
cssTextFild = gtk_css_provider_new();
gtk_style_context_add_provider(gtk_widget_get_style_context(win->get("searchTextField")),
GTK_STYLE_PROVIDER(cssTextFild), GTK_STYLE_PROVIDER_PRIORITY_APPLICATION);
}
SearchBar::~SearchBar() { this->control = nullptr; }
auto SearchBar::searchTextonCurrentPage(const char* text, size_t index, size_t* occurrences, XojPdfRectangle* matchRect)
-> bool {
size_t p = control->getCurrentPageNo();
this->page = p;
return control->searchTextOnPage(text, p, index, occurrences, matchRect);
}
void SearchBar::search(const char* text) {
MainWindow* win = control->getWindow();
GtkWidget* lbSearchState = win->get("lbSearchState");
bool found = true;
this->indexInPage = 0;
if (*text != 0) {
found = searchTextonCurrentPage(text, 1, &this->occurrences, nullptr);
if (found) {
if (occurrences == 1) {
gtk_label_set_text(GTK_LABEL(lbSearchState), _("Text found once on this page"));
} else {
char* msg = g_strdup_printf(_("Text found %zu times on this page"), occurrences);
gtk_label_set_text(GTK_LABEL(lbSearchState), msg);
g_free(msg);
}
} else {
gtk_label_set_text(GTK_LABEL(lbSearchState), _("Text not found"));
}
} else {
searchTextonCurrentPage("", 1, nullptr, nullptr);
gtk_label_set_text(GTK_LABEL(lbSearchState), "");
}
if (found) {
gtk_css_provider_load_from_data(cssTextFild, "GtkSearchEntry {}", -1, nullptr);
} else {
gtk_css_provider_load_from_data(cssTextFild, "GtkSearchEntry { color: #ff0000; }", -1, nullptr);
}
}
void SearchBar::searchTextChangedCallback(GtkEntry* entry, SearchBar* searchBar) {
const char* text = gtk_entry_get_text(entry);
searchBar->search(text);
}
void SearchBar::buttonCloseSearchClicked(GtkButton* button, SearchBar* searchBar) { searchBar->showSearchBar(false); }
template <class Fun>
void SearchBar::search(Fun next) {
MainWindow* win = control->getWindow();
GtkWidget* searchTextField = win->get("searchTextField");
const char* text = gtk_entry_get_text(GTK_ENTRY(searchTextField));
GtkWidget* lbSearchState = win->get("lbSearchState");
if (*text == 0) {
return;
}
const size_t originalPage = page;
XojPdfRectangle matchRect = XojPdfRectangle();
// Search backwards through the pages, wrapping around if needed.
for (;;) {
next(text);
const bool found = control->searchTextOnPage(text, page, indexInPage, &occurrences, &matchRect);
if (found) {
control->getScrollHandler()->scrollToPage(page, matchRect);
control->getScrollHandler();
gtk_label_set_text(GTK_LABEL(lbSearchState),
(occurrences == 1 ? FC(_F("Text found once on page {1}") % (page + 1)) :
FC(_F("Text found {1} times on page {2} ({3} of {1})") %
occurrences % (page + 1) % indexInPage)));
return;
}
if (page == originalPage) {
gtk_label_set_text(GTK_LABEL(lbSearchState), _("Text not found, searched on all pages"));
return;
}
}
}
void SearchBar::searchNext() {
size_t pageCount = control->getDocument()->getPageCount();
search([&](const char* text) {
indexInPage++;
if (indexInPage > occurrences) {
control->searchTextOnPage(text, page, 1, &occurrences, nullptr); // clear the active marker
page++;
if (page >= pageCount) {
page = 0;
}
indexInPage = 1;
}
});
}
void SearchBar::searchPrevious() {
size_t pageCount = control->getDocument()->getPageCount();
search([&](const char* text) {
indexInPage--;
if (indexInPage == 0 || indexInPage >= occurrences) {
control->searchTextOnPage(text, page, 1, &occurrences, nullptr); // clear the active marker
page--;
if (page > pageCount) {
page = pageCount - 1;
}
control->searchTextOnPage(text, page, 1, &occurrences, nullptr);
indexInPage = occurrences;
}
});
}
void SearchBar::showSearchBar(bool show) {
MainWindow* win = control->getWindow();
GtkWidget* searchBar = win->get("searchBar");
if (show) {
GtkWidget* searchTextField = win->get("searchTextField");
gtk_widget_show_all(searchBar);
gtk_widget_grab_focus(searchTextField);
this->indexInPage = 0;
} else {
gtk_widget_hide(searchBar);
const size_t pageCount = control->getDocument()->getPageCount();
for (size_t i = pageCount - 1; i < pageCount; i--) {
control->searchTextOnPage("", i, 0, nullptr, nullptr);
}
}
}
| 7,615
|
C++
|
.cpp
| 164
| 36.268293
| 120
| 0.586722
|
xournalpp/xournalpp
| 10,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.