id
int64
0
877k
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
66
repo_stars
int64
94
47.3k
repo_forks
int64
0
12k
repo_open_issues
int64
0
3.4k
repo_license
stringclasses
11 values
repo_extraction_date
stringclasses
197 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
1,539,757
urid.cpp
ivyl_obs-lv2/urid.cpp
/****************************************************************************** * Copyright (C) 2020 by Arkadiusz Hiler * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. *****************************************************************************/ #include "obs-lv2.hpp" LV2_URID LV2Plugin::urid_map(LV2_URID_Map_Handle handle, const char *uri) { LV2Plugin *lv2 = (LV2Plugin*)handle; LV2_URID urid; std::string key = uri; if (lv2->urid_map_data.find(key) == lv2->urid_map_data.end()) { urid = lv2->current_urid++; lv2->urid_map_data[key] = urid; } else { urid = lv2->urid_map_data[key]; } return urid; } const char *LV2Plugin::urid_unmap(void *handle, LV2_URID urid) { LV2Plugin *lv2 = (LV2Plugin*)handle; const char *value = nullptr; for (auto const& p : lv2->urid_map_data) { if (p.second == urid) { value = p.first.c_str(); } } return value; }
1,498
C++
.cpp
38
37.157895
79
0.633978
ivyl/obs-lv2
34
4
8
GPL-2.0
9/20/2024, 10:45:00 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,539,758
ui.cpp
ivyl_obs-lv2/ui.cpp
/****************************************************************************** * Copyright (C) 2020 by Arkadiusz Hiler * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. *****************************************************************************/ #include "obs-lv2.hpp" /* QT Window Implementation */ WidgetWindow::WidgetWindow(QWidget *parent) : QWidget(parent) { layout.setMargin(0); layout.setSpacing(0); setLayout(&layout); /* BUG: Some controls (e.g. drag and drop points for LSP * Graphic eq) are missplaced until some interaction with the * UI, may be an issue caused by dialog or suil wrapping, needs * debugging - appears with XWayland, need to verify on native X*/ setWindowFlags(Qt::Dialog); } void WidgetWindow::clearWidget(void) { if (this->currentWidget != nullptr) this->layout.removeWidget(this->currentWidget); this->currentWidget = nullptr; } void WidgetWindow::setWidget(QWidget *widget) { this->clearWidget(); this->currentWidget = widget; layout.addWidget(widget); this->resize(widget->size()); } WidgetWindow::~WidgetWindow() {} void WidgetWindow::closeEvent(QCloseEvent *event) { event->ignore(); this->hide(); } /* SUIL CALLBACKS */ void LV2Plugin::suil_write_from_ui(void *controller, uint32_t port_index, uint32_t buffer_size, uint32_t port_protocol, const void *buffer) { LV2Plugin *lv2 = (LV2Plugin*)controller; if (port_protocol != PROTOCOL_FLOAT || buffer_size != sizeof(float)) { printf("gui is trying use protocol %u with buffer_size %u\n", port_protocol, buffer_size); return; /* we MUST gracefully ignore according to the spec */ } lv2->ports[port_index].value = *((float*)buffer); } uint32_t LV2Plugin::suil_port_index(void *controller, const char *symbol) { LV2Plugin *lv2 = (LV2Plugin*)controller; return lv2->port_index(symbol); } /* UI HANDLING */ void LV2Plugin::prepare_ui() { if (this->plugin_instance == nullptr || this->plugin_uri == nullptr) return; if (this->ui_instance != nullptr) return; char* bundle_path = lilv_file_uri_parse(lilv_node_as_uri(lilv_ui_get_bundle_uri(this->ui)), NULL); char* binary_path = lilv_file_uri_parse(lilv_node_as_uri(lilv_ui_get_binary_uri(this->ui)), NULL); this->ui_instance = suil_instance_new(this->ui_host, this, LV2_UI__Qt5UI, this->plugin_uri, lilv_node_as_uri(lilv_ui_get_uri(this->ui)), lilv_node_as_uri(this->ui_type), bundle_path, binary_path, this->features); if (this->ui_instance == nullptr) { printf("failed to find ui!\n"); abort(); } if (this->ui_window == nullptr) this->ui_window = new WidgetWindow(); auto widget = (QWidget*) suil_instance_get_widget(ui_instance); if (widget == nullptr) { printf("filed to create widget!\n"); abort(); } ui_window->setWidget(widget); for (size_t i = 0; i < this->ports_count; ++i) { auto port = this->ports + i; if (port->type != PORT_CONTROL) continue; suil_instance_port_event(this->ui_instance, port->index, sizeof(float), PROTOCOL_FLOAT, &port->value); port->ui_value = port->value; } } void LV2Plugin::show_ui() { if (this->ui_window != nullptr && this->ui_instance != nullptr) this->ui_window->show(); } void LV2Plugin::hide_ui() { if (this->ui_window != nullptr && this->ui_instance != nullptr) this->ui_window->hide(); } bool LV2Plugin::is_ui_visible() { if (this->ui_window == nullptr) return false; return this->ui_window->isVisible(); } void LV2Plugin::cleanup_ui() { if (this->is_ui_visible()) this->hide_ui(); if (this->ui_window != nullptr) this->ui_window->clearWidget(); if (this->ui_instance != nullptr) { suil_instance_free(this->ui_instance); this->ui_instance = nullptr; } } void LV2Plugin::notify_ui_output_control_ports() { if (this->ui_instance == nullptr || this->ui_window == nullptr || !this->is_ui_visible()) return; for (size_t i = 0; i < this->ports_count; ++i) { auto port = this->ports + i; if (port->type != PORT_CONTROL || port->is_input) continue; if (port->ui_value == port->value) continue; suil_instance_port_event(this->ui_instance, port->index, sizeof(float), PROTOCOL_FLOAT, &port->value); port->ui_value = port->value; } }
4,929
C++
.cpp
151
29.450331
99
0.665259
ivyl/obs-lv2
34
4
8
GPL-2.0
9/20/2024, 10:45:00 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,539,759
obs-lv2.cpp
ivyl_obs-lv2/obs-lv2.cpp
/****************************************************************************** * Copyright (C) 2020 by Arkadiusz Hiler * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. *****************************************************************************/ #include <obs/obs-module.h> #include "obs-lv2.hpp" #define PROP_PLUGIN_LIST "lv2_plugin_list" #define PROP_TOGGLE_BUTTON "lv2_toggle_gui_button" class PluginData { public: GuiUpdateTimer *timer; LV2Plugin *lv2; }; OBS_DECLARE_MODULE() MODULE_EXPORT const char *obs_module_description(void) { return "OBS LV2 filters"; } static const char *obs_filter_name(void *unused) { UNUSED_PARAMETER(unused); return "LV2"; } static void obs_filter_update(void *data, obs_data_t *settings); static void *obs_filter_create(obs_data_t *settings, obs_source_t *filter) { auto obs_audio = obs_get_audio(); size_t channels = audio_output_get_channels(obs_audio); PluginData *data = new PluginData(); data->lv2 = new LV2Plugin(channels); const char *state = obs_data_get_string(settings, "lv2_plugin_state"); obs_filter_update(data, settings); data->lv2->set_state(state); data->timer = new GuiUpdateTimer(data->lv2); data->timer->start(); return data; } static void obs_filter_destroy(void *data) { PluginData *d = (PluginData*) data; d->timer->deleteLater(); delete d->lv2; } static bool obs_toggle_gui(obs_properties_t *props, obs_property_t *property, void *data) { LV2Plugin *lv2 = ((PluginData*) data)->lv2; lv2->prepare_ui(); if (lv2->is_ui_visible()) lv2->hide_ui(); else lv2->show_ui(); return true; } static obs_properties_t *obs_filter_properties(void *data) { LV2Plugin *lv2 = ((PluginData*) data)->lv2; obs_properties_t *props = obs_properties_create(); obs_property_t *list = obs_properties_add_list(props, PROP_PLUGIN_LIST, "Plugin", OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_STRING); obs_properties_add_button(props, PROP_TOGGLE_BUTTON, "Toggle LV2 Plugin's GUI", obs_toggle_gui); obs_property_list_add_string(list, "{select a plug-in}", ""); lv2->for_each_supported_plugin([&](const char *name, const char *uri) { obs_property_list_add_string(list, name, uri); }); return props; } static void obs_filter_update(void *data, obs_data_t *settings) { auto obs_audio = obs_get_audio(); LV2Plugin *lv2 = ((PluginData*) data)->lv2; const char *uri = obs_data_get_string(settings, PROP_PLUGIN_LIST); uint32_t sample_rate = audio_output_get_sample_rate(obs_audio); size_t channels = audio_output_get_channels(obs_audio); if (strlen(uri) == 0) lv2->set_uri(nullptr); else lv2->set_uri(uri); lv2->set_sample_rate(sample_rate); lv2->set_channels(channels); lv2->update_plugin_instance(); } static struct obs_audio_data * obs_filter_audio(void *data, struct obs_audio_data *audio) { LV2Plugin *lv2 = ((PluginData*) data)->lv2; float **audio_data = (float **)audio->data; lv2->process_frames(audio_data, audio->frames); return audio; } static void obs_filter_save(void *data, obs_data_t *settings) { LV2Plugin *lv2 = ((PluginData*) data)->lv2; auto state = lv2->get_state(); obs_data_set_string(settings, "lv2_plugin_state", state); free(state); } struct obs_source_info obs_lv2_filter = { .id = "lv2_filter", .type = OBS_SOURCE_TYPE_FILTER, .output_flags = OBS_SOURCE_AUDIO, .get_name = obs_filter_name, .create = obs_filter_create, .destroy = obs_filter_destroy, .get_width = nullptr, .get_height = nullptr, .get_defaults = nullptr, .get_properties = obs_filter_properties, .update = obs_filter_update, .activate = nullptr, .deactivate = nullptr, .show = nullptr, .hide = nullptr, .video_tick = nullptr, .video_render = nullptr, .filter_video = nullptr, .filter_audio = obs_filter_audio, .enum_active_sources = nullptr, .save = obs_filter_save, }; bool obs_module_load(void) { obs_register_source(&obs_lv2_filter); return true; }
4,758
C++
.cpp
140
31.7
89
0.664045
ivyl/obs-lv2
34
4
8
GPL-2.0
9/20/2024, 10:45:00 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,539,760
core.cpp
ivyl_obs-lv2/core.cpp
/****************************************************************************** * Copyright (C) 2020 by Arkadiusz Hiler * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. *****************************************************************************/ #include "obs-lv2.hpp" using namespace std; LV2Plugin::LV2Plugin(size_t channels) { feature_uri_map_data = { this, LV2Plugin::urid_map }; feature_uri_map = { LV2_URID_MAP_URI, &feature_uri_map_data }; feature_uri_unmap_data = { this, LV2Plugin::urid_unmap }; feature_uri_unmap = { LV2_URID_MAP_URI, &feature_uri_unmap_data }; /* data will be set to plugin instance each time we update */ feature_instance_access = { LV2_INSTANCE_ACCESS_URI, nullptr }; feature_data_access = { LV2_DATA_ACCESS_URI, &feature_data_access_data }; features[0] = &feature_uri_map; /* XXX: don't expose it, crashes some plugins */ /* features[1] = &feature_uri_unmap; */ features[1] = &feature_instance_access; features[2] = &feature_data_access; features[3] = nullptr; /* NULL terminated */ this->channels = channels; world = lilv_world_new(); lilv_world_load_all(world); plugins = lilv_world_get_all_plugins(world); plugin = nullptr; ui_host = suil_host_new(LV2Plugin::suil_write_from_ui, LV2Plugin::suil_port_index, NULL, NULL); populate_supported_plugins(); } LV2Plugin::~LV2Plugin() { cleanup_ui(); cleanup_plugin_instance(); suil_host_free(ui_host); lilv_world_free(world); free(plugin_uri); cleanup_ports(); } bool LV2Plugin::is_feature_supported(const LilvNode* node) { bool is_supported = false; if (!lilv_node_is_uri(node)) { printf("tested feature passed is not an URI!\n"); abort(); } auto node_uri = lilv_node_as_uri(node); for (auto feature = this->features; *feature != nullptr; feature++) { if (0 == strcmp((*feature)->URI, node_uri)) is_supported = true; } return is_supported; } void LV2Plugin::populate_supported_plugins(void) { LilvNode* input_port = lilv_new_uri(world, LV2_CORE__InputPort); LilvNode* output_port = lilv_new_uri(world, LV2_CORE__OutputPort); LilvNode* audio_port = lilv_new_uri(world, LV2_CORE__AudioPort); LILV_FOREACH(plugins, i, this->plugins) { auto plugin = lilv_plugins_get(this->plugins, i); bool skip = false; /* filter out plugins which require feature we don't support */ auto req_features = lilv_plugin_get_required_features(plugin); LILV_FOREACH(nodes, j, req_features) { const LilvNode* feature = lilv_nodes_get(req_features, j); if (!this->is_feature_supported(feature)) { skip = true; printf("%s filtered out because we do not support %s\n", lilv_node_as_string(lilv_plugin_get_name(plugin)), lilv_node_as_string(feature)); break; } } lilv_nodes_free(req_features); if (skip) continue; /* filter out plugins without supported UI */ skip = true; auto uis = lilv_plugin_get_uis(plugin); auto qt5_uri = lilv_new_uri(this->world, LV2_UI__Qt5UI); LILV_FOREACH(uis, i, uis) { const LilvNode *ui_type; auto ui = lilv_uis_get(uis, i); if (lilv_ui_is_supported(ui, suil_ui_supported, qt5_uri, &ui_type)) { skip = false; } } lilv_node_free(qt5_uri); if (skip) { printf("%s filtered out - has no usable GUI\n", lilv_node_as_string(lilv_plugin_get_name(plugin))); continue; } auto in_aps = lilv_plugin_get_num_ports_of_class(plugin, audio_port, input_port, NULL); auto out_aps = lilv_plugin_get_num_ports_of_class(plugin, audio_port, output_port, NULL); if (in_aps < this->get_channels() || out_aps < this->get_channels()) { printf("%s filtered out - supports only %u input and %u output channels, while OBS audio uses %lu\n", lilv_node_as_string(lilv_plugin_get_name(plugin)), in_aps, out_aps, this->get_channels()); continue; } this->supported_pluggins.push_back(pair<string,string>( lilv_node_as_string(lilv_plugin_get_name(plugin)), lilv_node_as_string(lilv_plugin_get_uri(plugin)))); } lilv_node_free(audio_port); lilv_node_free(output_port); lilv_node_free(input_port); } void LV2Plugin::for_each_supported_plugin(function<void(const char *, const char *)> f) { for (auto const& p: this->supported_pluggins) f(p.first.c_str(), p.second.c_str()); } void LV2Plugin::set_uri(const char* uri) { bool replace = true; if (this->plugin_uri != nullptr && uri != nullptr) { if (!strcmp(this->plugin_uri, uri)) replace = false; } if (replace) { if (this->plugin_uri != nullptr) free(this->plugin_uri); if (uri != nullptr) this->plugin_uri = strdup(uri); else this->plugin_uri = nullptr; instance_needs_update = true; } } void LV2Plugin::cleanup_plugin_instance(void) { if (this->plugin_instance == nullptr) return; lilv_instance_deactivate(this->plugin_instance); lilv_instance_free(this->plugin_instance); this->feature_instance_access.data = nullptr; this->feature_data_access_data.data_access = nullptr; this->plugin_instance = nullptr; } void LV2Plugin::update_plugin_instance(void) { if (!this->instance_needs_update) return; this->ready = false; this->instance_needs_update = false; cleanup_ui(); cleanup_plugin_instance(); this->plugin = nullptr; this->ui = nullptr; cleanup_ports(); LilvNode *uri = nullptr; if (this->plugin_uri != nullptr) { uri = lilv_new_uri(this->world, this->plugin_uri); this->plugin = lilv_plugins_get_by_uri(plugins, uri); lilv_node_free(uri); } if (this->plugin == nullptr) { WARN("failed to get plugin by uri\n"); return; } auto qt5_uri = lilv_new_uri(this->world, LV2_UI__Qt5UI); auto uis = lilv_plugin_get_uis(this->plugin); LILV_FOREACH(uis, i, uis) { const LilvNode *ui_type; auto ui = lilv_uis_get(uis, i); if (lilv_ui_is_supported(ui, suil_ui_supported, qt5_uri, &ui_type)) { this->ui = ui; this->ui_type = ui_type; break; } } lilv_node_free(qt5_uri); this->plugin_instance = lilv_plugin_instantiate(this->plugin, this->sample_rate, this->features); if (this->plugin_instance == nullptr) { WARN("failed to instantiate plugin\n"); return; } this->feature_instance_access.data = lilv_instance_get_handle(this->plugin_instance); /* XXX: digging in lilv's internals, there may be a better way to do this */ this->feature_data_access_data.data_access = this->plugin_instance->lv2_descriptor->extension_data; this->prepare_ports(); lilv_instance_activate(this->plugin_instance); this->ready = true; } void LV2Plugin::set_sample_rate(uint32_t sample_rate) { if (this->sample_rate != sample_rate) { this->sample_rate = sample_rate; this->instance_needs_update = true; } } void LV2Plugin::set_channels(size_t channels) { if (this->channels != channels) { this->channels = channels; this->instance_needs_update = true; } } size_t LV2Plugin::get_channels(void) { return this->channels; } uint32_t LV2Plugin::port_index(const char *symbol) { LilvNode* lilv_sym = lilv_new_string(this->world, symbol); const LilvPort* port = lilv_plugin_get_port_by_symbol(this->plugin, lilv_sym); lilv_node_free(lilv_sym); if (port == nullptr) return LV2UI_INVALID_PORT_INDEX; auto idx = lilv_port_get_index(this->plugin, port); return idx; }
7,873
C++
.cpp
228
31.557018
104
0.688003
ivyl/obs-lv2
34
4
8
GPL-2.0
9/20/2024, 10:45:00 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,539,761
state.cpp
ivyl_obs-lv2/state.cpp
/****************************************************************************** * Copyright (C) 2020 by Arkadiusz Hiler * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. *****************************************************************************/ #include "obs-lv2.hpp" #define STATE_URI "http://hiler.eu/obs-lv2/plugin-state" const void *LV2Plugin::get_port_value(const char *port_symbol, void *user_data, uint32_t *size, uint32_t *type) { LV2Plugin *lv2 = (LV2Plugin*)user_data; auto idx = LV2Plugin::suil_port_index(lv2, port_symbol); *size = sizeof(float); *type = PROTOCOL_FLOAT; return &lv2->ports[idx].value; } void LV2Plugin::set_port_value(const char *port_symbol, void *user_data, const void *value, uint32_t size, uint32_t type) { LV2Plugin *lv2 = (LV2Plugin*)user_data; auto idx = lv2->port_index(port_symbol); if (idx == LV2UI_INVALID_PORT_INDEX) { printf("trying to set value for unknown port %s\n", port_symbol); return; } if (size != sizeof(float) || type != PROTOCOL_FLOAT) { printf("failed to restore state for %s of type %u - it's not a float\n", port_symbol, type); return; } lv2->ports[idx].value = *((float*) value); } char *LV2Plugin::get_state(void) { if (this->plugin_instance == nullptr) return NULL; auto state = lilv_state_new_from_instance(this->plugin, this->plugin_instance, &this->feature_uri_map_data, NULL, NULL, NULL, NULL, LV2Plugin::get_port_value, this, LV2_STATE_IS_POD, this->features); auto str = lilv_state_to_string(this->world, &this->feature_uri_map_data, &this->feature_uri_unmap_data, state, STATE_URI, NULL); lilv_state_free(state); return str; } void LV2Plugin::set_state(const char *str) { if (str == nullptr || this->plugin_instance == nullptr) return; auto state = lilv_state_new_from_string(this->world, &this->feature_uri_map_data, str); lilv_state_restore(state, this->plugin_instance, LV2Plugin::set_port_value, this, LV2_STATE_IS_POD, this->features); lilv_state_free(state); }
2,756
C++
.cpp
81
30.345679
79
0.648323
ivyl/obs-lv2
34
4
8
GPL-2.0
9/20/2024, 10:45:00 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,539,762
obs-lv2.hpp
ivyl_obs-lv2/obs-lv2.hpp
/****************************************************************************** * Copyright (C) 2020 by Arkadiusz Hiler * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. *****************************************************************************/ #include <lilv-0/lilv/lilv.h> #include <lilv/lilv.h> #include <suil-0/suil/suil.h> #include <suil/suil.h> #include <lv2/ui/ui.h> #include <lv2/atom/atom.h> #include <lv2/urid/urid.h> #include <lv2/state/state.h> #include <lv2/instance-access/instance-access.h> #include <lv2/data-access/data-access.h> #include <iostream> #include <functional> #include <stdio.h> #include <string.h> #include <QWidget> #include <QTimer> #include <QVBoxLayout> #include <QCloseEvent> #include <string> #include <math.h> #include <vector> #include <algorithm> #define WARN printf class LV2Plugin; class GuiUpdateTimer : public QObject { public: GuiUpdateTimer(LV2Plugin *lv2); ~GuiUpdateTimer(); void start(void); protected: void tick(void); QTimer *timer = nullptr; LV2Plugin *lv2 = nullptr; }; class WidgetWindow : public QWidget { public: explicit WidgetWindow(QWidget *parent = nullptr); void clearWidget(void); void setWidget(QWidget *widget); virtual ~WidgetWindow(); protected: QVBoxLayout layout; QWidget *currentWidget = nullptr; void closeEvent(QCloseEvent *event) override; void updatePorts(void); }; #define PROTOCOL_FLOAT 0 enum LV2PortType { PORT_AUDIO, PORT_CONTROL, PORT_ATOM, }; struct LV2Port { uint32_t index; bool is_input; bool is_optional; float value; float ui_value; const LilvPort* lilv_port; enum LV2PortType type; }; class LV2Plugin { public: LV2Plugin(size_t channels); ~LV2Plugin(); void for_each_supported_plugin(std::function<void(const char *, const char *)> f); void set_uri(const char* uri); void set_sample_rate(uint32_t sample_rate); void set_channels(size_t channels); size_t get_channels(void); void update_plugin_instance(void); void cleanup_plugin_instance(void); void prepare_ports(void); void cleanup_ports(void); void prepare_ui(void); void show_ui(void); void hide_ui(void); bool is_ui_visible(void); void cleanup_ui(void); void process_frames(float**, int frames); char *get_state(void); void set_state(const char *str); void notify_ui_output_control_ports(void); uint32_t port_index(const char *symbol); protected: bool ready = false; LilvWorld *world; std::vector<std::pair<std::string,std::string>> supported_pluggins; const LilvPlugins *plugins = nullptr; void populate_supported_plugins(void); const LilvPlugin *plugin = nullptr; LilvInstance *plugin_instance = nullptr; char *plugin_uri = nullptr; uint32_t sample_rate = 0; size_t channels = 0; bool instance_needs_update = true; /* PORT MAPPING */ struct LV2Port *ports = nullptr; size_t ports_count = 0; float **input_buffer = nullptr; float **output_buffer = nullptr; size_t input_channels_count = 0; size_t output_channels_count = 0; /* UI */ const LilvUI *ui = nullptr; const LilvNode *ui_type = nullptr; SuilHost *ui_host = nullptr; SuilInstance* ui_instance = nullptr; WidgetWindow *ui_window = nullptr; bool is_feature_supported(const LilvNode*); static void suil_write_from_ui(void *controller, uint32_t port_index, uint32_t buffer_size, uint32_t format, const void *buffer); static uint32_t suil_port_index(void *controller, const char *symbol); /* URID MAP FEATURE */ std::map<std::string,LV2_URID> urid_map_data; LV2_URID current_urid = 1; /* 0 is reserverd */ LV2_URID_Map feature_uri_map_data; LV2_Feature feature_uri_map; LV2_URID_Unmap feature_uri_unmap_data; LV2_Feature feature_uri_unmap; LV2_Feature feature_instance_access; LV2_Extension_Data_Feature feature_data_access_data; LV2_Feature feature_data_access; static LV2_URID urid_map(void *handle, const char *uri); static const char *urid_unmap(void *handle, LV2_URID urid); const LV2_Feature* features[4]; /* STATE PERSISTENCE */ static const void *get_port_value(const char *port_symbol, void *user_data, uint32_t *size, uint32_t *type); static void set_port_value(const char *port_symbol, void *user_data, const void *value, uint32_t size, uint32_t type); };
4,906
C++
.h
159
28.352201
83
0.71796
ivyl/obs-lv2
34
4
8
GPL-2.0
9/20/2024, 10:45:00 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,539,763
test.cpp
851896022_SuperMacros/test.cpp
#include "test.h" #include <QStringList> #include <QApplication> test::test(QObject *parent) : QObject(parent) { num(); } void test::buff() { QString m_sProjectPath = tr("C:/c");/*文件夹全路径名*/ QDir dir(m_sProjectPath); dir.exists(); /*判断文件夹是否存在*/ dir.setFilter(QDir::Files); /*设置dir的过滤模式,表示只遍历本文件夹内的文件*/ QFileInfoList fileList = dir.entryInfoList(); /*获取本文件夹内所有文件的信息*/ int fileCount = fileList.count(); /*获取本文件夹内的文件个数*/ QList<QVariant> list; QStringList name; QSettings iniFile(qApp->applicationDirPath() +"/test.ini", QSettings::IniFormat); for(int i=0;i<fileCount;i++) /*遍历每个文件*/ { QFileInfo fileInfo = fileList[i]; /*获取每个文件信息*/ //QString suffix = fileInfo.suffix(); /*获取文件后缀名*/ //qDebug()<<suffix; //QString base = QString("%1").arg(fileInfo.baseName().toInt(), 5, 10, QLatin1Char('0')); //qDebug()<<fileInfo.filePath()<<fileInfo.absolutePath() +"/"+ base+"."+suffix; //QFile::rename(fileInfo.filePath(),fileInfo.absolutePath() +"/"+ base+"."+suffix); QImage image= QImage(fileInfo.filePath()); image=image.scaled(8,9,Qt::IgnoreAspectRatio, Qt::SmoothTransformation); //image.save("A:/tmp/"+QString::number(i)+".bmp"); QBitArray hash(64); for(int x=0;x<8;x++) { for(int y=0;y<8;y++) { QColor a=image.pixelColor((x),(y)); QColor b=image.pixelColor((x),((y+1))); //QColor a=image.pixelColor((x*3+4),(y*2+5)); //QColor b=image.pixelColor((x*3+4),((y+1)*2+5)); float GrayA= a.valueF(); float GrayB= b.valueF(); if(GrayA>GrayB) { hash.setBit(x*8+y,true); } else { hash.setBit(x*8+y,false); } } } //qDebug()<<fileInfo.fileName()<<hash; list.append(hash); name.append(fileInfo.baseName()); } iniFile.setValue("buff", list); iniFile.setValue("name", name); } void test::num() { QString m_sProjectPath = tr("C:/num");/*文件夹全路径名*/ QDir dir(m_sProjectPath); dir.exists(); /*判断文件夹是否存在*/ dir.setFilter(QDir::Files); /*设置dir的过滤模式,表示只遍历本文件夹内的文件*/ QFileInfoList fileList = dir.entryInfoList(); /*获取本文件夹内所有文件的信息*/ int fileCount = fileList.count(); /*获取本文件夹内的文件个数*/ QList<QVariant> list; QStringList name; QSettings iniFile(qApp->applicationDirPath() +"/test.ini", QSettings::IniFormat); for(int i=0;i<fileCount;i++) /*遍历每个文件*/ { QFileInfo fileInfo = fileList[i]; /*获取每个文件信息*/ //QString suffix = fileInfo.suffix(); /*获取文件后缀名*/ //qDebug()<<suffix; //QString base = QString("%1").arg(fileInfo.baseName().toInt(), 5, 10, QLatin1Char('0')); //qDebug()<<fileInfo.filePath()<<fileInfo.absolutePath() +"/"+ base+"."+suffix; //QFile::rename(fileInfo.filePath(),fileInfo.absolutePath() +"/"+ base+"."+suffix); QImage image= QImage(fileInfo.filePath()); image=image.scaled(8,9,Qt::IgnoreAspectRatio, Qt::SmoothTransformation); //image.save("A:/tmp/"+QString::number(i)+".bmp"); QBitArray hash(64); for(int x=0;x<8;x++) { for(int y=0;y<8;y++) { QColor a=image.pixelColor((x),(y)); QColor b=image.pixelColor((x),((y+1))); //QColor a=image.pixelColor((x*3+4),(y*2+5)); //QColor b=image.pixelColor((x*3+4),((y+1)*2+5)); float GrayA= a.valueF(); float GrayB= b.valueF(); if(GrayA>GrayB) { hash.setBit(x*8+y,true); } else { hash.setBit(x*8+y,false); } } } //qDebug()<<fileInfo.fileName()<<hash; list.append(hash); name.append(fileInfo.baseName()); } iniFile.setValue("num", list); iniFile.setValue("numname",name); }
4,459
C++
.cpp
107
28.775701
97
0.542979
851896022/SuperMacros
33
12
1
GPL-3.0
9/20/2024, 10:45:00 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,539,765
window.cpp
851896022_SuperMacros/window.cpp
#include "window.h" #include "ui_window.h" #include "QApplication" #include "QPixmap" #include "QImage" #include "QColor" #include "QScreen" #include "QDebug" #include <QMessageBox> window::window(QWidget *parent) : QMainWindow(parent), ui(new Ui::window) { ui->setupUi(this); delayCount.setSingleShot(true); ui->comList->addItems(g->comNameList); ui->textEdit->setText(g->macro); QTimer *timer=new QTimer; connect(timer,SIGNAL(timeout()),this,SLOT(on_test_clicked())); timer->start(1000); for(int i=0;i<12;i++) { hBoxMy.addWidget(&lbMy[i]); hBoxT.addWidget(&lbT[i]); } for(int i=0;i<16;i++) { hBoxKill.addWidget(&lbKill[i]); } ui->groupBox_1->setLayout(&hBoxMy); ui->groupBox_2->setLayout(&hBoxT); ui->groupBox_4->setLayout(&hBoxKill); } window::~window() { delete ui; } void window::on_test_clicked() { QString hp=QString::number(g->nowHP)+"/"+QString::number(g->maxHP) +"("+QString::number(g->perHP())+"%)"; ui->HP->setText(hp); QString mbuff="自身"; QString tbuff="目标"; for(int i=0;i<12;i++) { if(g->myBuffID[i]>0 && g->myBuffID[i]<g->buffName.count()) { mbuff.append(g->buffName.at(g->myBuffID[i])); mbuff.append("|"); } if(g->targetBuffID[i]>0 && g->targetBuffID[i]<g->buffName.count()) { tbuff.append(g->buffName.at(g->targetBuffID[i])); tbuff.append("|"); } } ui->tbuff->setText(tbuff); ui->mbuff->setText(mbuff); //修改图标显示 if(ui->tabWidget->currentIndex()==2) { for(int i=0;i<12;i++) { lbT[i].setPixmap(g->buffImgCacheT[i]); lbMy[i].setPixmap(g->buffImgCacheMy[i]); } } ui->lab_hp->setPixmap(g->hpImgCacheMy); lbKill[0].setPixmap(g->killImgCache); #ifdef sdaa int x ; int y ; // QPixmap pixmap = QPixmap::grabWindow(QApplication::desktop()->winId(), x, y, 1, 1); QList<QScreen *> list_screen = QGuiApplication::screens(); //可能电脑接了多个屏幕 int w=list_screen.at(0)->geometry().width(); int h=list_screen.at(0)->geometry().height(); x=w-392; y=h-460; QPixmap pixmap = list_screen.at(0)->grabWindow(0,x,y,1,1); if (!pixmap.isNull()) //如果像素图不为NULL { QImage image = pixmap.toImage();//将像素图转换为QImage if (!image.isNull()) //如果image不为空 { QColor color1,color2(250,237,189); if (image.valid(0, 0)) //坐标位置有效 { color1 = image.pixel(0, 0); if(colorDiff(color1,color2)<10) { //g->siMingD.start(); //qDebug()<<"开始!!!!!!!!!!!!"; } else { //g->siMingD.stop(); //qDebug()<<"停止!!!!!!!!!!!!"; } } } } #endif } void window::on_startLink_clicked() { if(g->startLink(ui->comList->currentText())) { ui->comList->setEnabled(false); ui->startLink->setEnabled(false); } else { } } #include <QSettings> double window::colorDiff(QColor hsv1,QColor hsv2) { //self-defined static double R = 100; static double angle = 30; static double h = R * cos(angle / 180 * PI); static double r = R * sin(angle / 180 * PI); double x1 = r * hsv1.valueF() * hsv1.hsvSaturationF() * cos(hsv1.hsvHueF() / 180 * PI); double y1 = r * hsv1.valueF() * hsv1.hsvSaturationF() * sin(hsv1.hsvHueF() / 180 * PI); double z1 = h * (1 - hsv1.valueF()); double x2 = r * hsv2.valueF() * hsv2.hsvSaturationF() * cos(hsv2.hsvHueF() / 180 * PI); double y2 = r * hsv2.valueF() * hsv2.hsvSaturationF() * sin(hsv2.hsvHueF() / 180 * PI); double z2 = h * (1 - hsv2.valueF()); double dx = x1 - x2; double dy = y1 - y2; double dz = z1 - z2; return sqrt(dx * dx + dy * dy + dz * dz); } void window::on_btnSave_clicked() { isOk=true; QString allstr=ui->textEdit->toPlainText(); allstr.remove("\r"); QStringList lineList=allstr.split("\n"); boolMap.clear(); for(int line=0;line<lineList.count();line++) { QStringList wordList=lineList.at(line).split(" "); if(wordList.count()<2 || wordList.at(0)==QString("/z"))//如果太短或者为注释 { continue; } else if(wordList.at(0)==QString("/b")) { boolMap.insert(wordList.at(2),stringToBoolLine(wordList.at(1))); } else if(wordList.at(0)==QString("/k")) { if(stringToBoolLine(wordList.at(1))) { if(wordList.at(2).toInt()>150||wordList.at(2).toInt()<4) { QMessageBox::information(this,"错误!","键值错误"); isOk=false; } //g->sendCache.append((char)wordList.at(2).toInt()); } } else { QMessageBox::information(this,"错误!","未知错误1"); isOk=false; } } if(isOk) { QMessageBox::information(this,"通过!","测试通过"); QSettings iniFile(qApp->applicationDirPath() +"/test.ini", QSettings::IniFormat); iniFile.setValue("macro",allstr); ui->btn3->setEnabled(true); } } bool window::stringToBoolLine(QString str) { int c1=str.count("|"); int c2=str.count("&"); if(c1>0&&c2>0) { QMessageBox::information(this,"错误!","不能同时|和&"); isOk=false; return false; } else if(c1>0) { QStringList point=str.split("|"); bool t=stringToBoolLPoint(point.at(0)); for(int i=1;i<point.count();i++) { t = t || stringToBoolLPoint(point.at(i)); } return t; } else if(c2>0) { QStringList point=str.split("&"); bool t=stringToBoolLPoint(point.at(0)); for(int i=1;i<point.count();i++) { t = t && stringToBoolLPoint(point.at(i)); } return t; } else { return stringToBoolLPoint(str); } } bool window::stringToBoolLPoint(QString str) { if(str.count(":")>0) { QStringList t=str.split(":"); if(t.at(0)==QString("nobuff")) { int c=-1; c=g->buffNameMap[t.at(1)]; if(c==0) { QMessageBox::information(this,"错误!","未知图标1"); isOk=false; return false; } else { return g->mNoBuff(c); } } else if(t.at(0)==QString("buff")) { int c=-1; c=g->buffNameMap[t.at(1)]; if(c==0) { QMessageBox::information(this,"错误!","未知图标2"); isOk=false; return false; } else { return g->mBuff(c); } } else if(t.at(0)==QString("tnobuff")) { int c=-1; c=g->buffNameMap[t.at(1)]; if(c==0) { QMessageBox::information(this,"错误!","未知图标3"); isOk=false; return false; } else { return g->tNoBuff(c); } } else if(t.at(0)==QString("tbuff")) { int c=-1; c=g->buffNameMap[t.at(1)]; if(c==0) { QMessageBox::information(this,"错误!","未知图标4"); isOk=false; return false; } else { return g->tBuff(c); } } else { QMessageBox::information(this,"错误!","未知名称"); isOk=false; return false; } } else if(str.count("<")>0) { QStringList t=str.split("<"); if(t.at(0)==QString("HP")) { float f=t.at(1).toFloat(); if(f<1) { return g->perHP()<f; } else { return g->nowHP<f; } } else { QMessageBox::information(this,"错误!","未知变量1"); isOk=false; return false; } } else if(str.count(">")>0) { QStringList t=str.split(">"); if(t.at(0)==QString("HP")) { float f=t.at(1).toFloat(); if(f<1) { return g->perHP()>f; } else { return g->nowHP>f; } } else { QMessageBox::information(this,"错误!","未知变量2"); isOk=false; return false; } } else//如果没符号,认为是之前设定的键值 { if(boolMap.contains(str)) { return boolMap[str]; } else { QMessageBox::information(this,"错误!","没有找到变量"); isOk=false; return false; } } } void window::on_btn3_clicked() { QSettings iniFile(qApp->applicationDirPath() +"/test.ini", QSettings::IniFormat); g->macro=iniFile.value("macro").toString(); ui->btn3->setEnabled(false); } void window::on_textEdit_textChanged() { ui->btn3->setEnabled(false); } void window::on_btnup_1_clicked() { g->mDev.setY(g->mDev.y()+1); QSettings iniFile(qApp->applicationDirPath() +"/test.ini", QSettings::IniFormat); iniFile.setValue("mdev", g->mDev); } void window::on_btndown_1_clicked() { g->mDev.setY(g->mDev.y()-1); QSettings iniFile(qApp->applicationDirPath() +"/test.ini", QSettings::IniFormat); iniFile.setValue("mdev", g->mDev); } void window::on_btnleft_1_clicked() { g->mDev.setX(g->mDev.x()+1); QSettings iniFile(qApp->applicationDirPath() +"/test.ini", QSettings::IniFormat); iniFile.setValue("mdev", g->mDev); } void window::on_btnright_1_clicked() { g->mDev.setX(g->mDev.x()-1); QSettings iniFile(qApp->applicationDirPath() +"/test.ini", QSettings::IniFormat); iniFile.setValue("mdev", g->mDev); } void window::on_btnup_2_clicked() { g->tDev.setY(g->tDev.y()+1); QSettings iniFile(qApp->applicationDirPath() +"/test.ini", QSettings::IniFormat); iniFile.setValue("tdev", g->tDev); } void window::on_btndown_2_clicked() { g->tDev.setY(g->tDev.y()-1); QSettings iniFile(qApp->applicationDirPath() +"/test.ini", QSettings::IniFormat); iniFile.setValue("tdev", g->tDev); } void window::on_btnleft_2_clicked() { g->tDev.setX(g->tDev.x()+1); QSettings iniFile(qApp->applicationDirPath() +"/test.ini", QSettings::IniFormat); iniFile.setValue("tdev", g->tDev); } void window::on_btnright_2_clicked() { g->tDev.setX(g->tDev.x()-1); QSettings iniFile(qApp->applicationDirPath() +"/test.ini", QSettings::IniFormat); iniFile.setValue("tdev", g->tDev); } void window::on_btnup_3_clicked() { g->mHp.setY(g->mHp.y()+1); QSettings iniFile(qApp->applicationDirPath() +"/test.ini", QSettings::IniFormat); iniFile.setValue("mhp", g->mHp); } void window::on_btndown_3_clicked() { g->mHp.setY(g->mHp.y()-1); QSettings iniFile(qApp->applicationDirPath() +"/test.ini", QSettings::IniFormat); iniFile.setValue("mhp", g->mHp); } void window::on_btnleft_3_clicked() { g->mHp.setX(g->mHp.x()+1); QSettings iniFile(qApp->applicationDirPath() +"/test.ini", QSettings::IniFormat); iniFile.setValue("mhp", g->mHp); } void window::on_btnright_3_clicked() { g->mHp.setX(g->mHp.x()-1); QSettings iniFile(qApp->applicationDirPath() +"/test.ini", QSettings::IniFormat); iniFile.setValue("mhp", g->mHp); } void window::on_btnwa_3_clicked() { g->mHp.setWidth(g->mHp.width()+1); QSettings iniFile(qApp->applicationDirPath() +"/test.ini", QSettings::IniFormat); iniFile.setValue("mhp", g->mHp); } void window::on_btnwd_3_clicked() { g->mHp.setWidth(g->mHp.width()-1); QSettings iniFile(qApp->applicationDirPath() +"/test.ini", QSettings::IniFormat); iniFile.setValue("mhp", g->mHp); } void window::on_btnha_3_clicked() { g->mHp.setHeight(g->mHp.height()+1); QSettings iniFile(qApp->applicationDirPath() +"/test.ini", QSettings::IniFormat); iniFile.setValue("mhp", g->mHp); } void window::on_btnhd_3_clicked() { g->mHp.setHeight(g->mHp.height()-1); QSettings iniFile(qApp->applicationDirPath() +"/test.ini", QSettings::IniFormat); iniFile.setValue("mhp", g->mHp); }
13,086
C++
.cpp
449
20.483296
92
0.531519
851896022/SuperMacros
33
12
1
GPL-3.0
9/20/2024, 10:45:00 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,539,766
global.cpp
851896022_SuperMacros/global.cpp
#include "global.h" GLobal *g; #include <QThread> #include "windows.h" #include <QSettings> #include <QVariant> #include <QApplication> GLobal::GLobal(QObject *parent) : QObject(parent) { { QString filename; filename+=(":/KeyList.txt"); //判断文件是否存在 QFile *file = new QFile(filename); if(file->open(QIODevice::ReadOnly)) { for(int i=0;i<10000;i++) { { QString ba(file->readLine()); ba.remove("\r"); ba.remove("\n"); QStringList list=ba.split("|"); keyNameList.append(list.at(1)); keyNoList.append(list.at(0).toInt()); } if(file->atEnd())break; } file->close(); } file->deleteLater(); } { QSettings iniFile(qApp->applicationDirPath() +"/test.ini", QSettings::IniFormat); //qDebug()<<iniFile.value("name").toStringList(); //iniFile.setValue("aaa",222); //qDebug()<<iniFile.value("aaa").toString(); buffDb=iniFile.value("buff").toList(); buffName=iniFile.value("name").toStringList(); numDb=iniFile.value("num").toList(); macro=iniFile.value("macro").toString(); mDev=iniFile.value("mdev").toPoint(); tDev=iniFile.value("tdev").toPoint(); mHp=iniFile.value("mhp").toRect(); for(int i=0;i<buffName.count();i++) { buffNameMap.insert(buffName[i],i); } } foreach(const QSerialPortInfo &info,QSerialPortInfo::availablePorts()) { comNameList << info.portName(); } connect(&sendTimer,SIGNAL(timeout()),this,SLOT(sendData())); if(true) { sendTimer.start(50); } } GLobal::~GLobal() { } bool GLobal::startLink(QString name) { if(!(serialPort==NULL)) { serialPort->deleteLater(); } serialPort=new QSerialPort(name); connect(serialPort,SIGNAL(readyRead()),this,SLOT(onReceived())); serialPort->setBaudRate(QSerialPort::Baud115200,QSerialPort::AllDirections);//设置波特率和读写方向 serialPort->setDataBits(QSerialPort::Data8); //数据位为8位 serialPort->setFlowControl(QSerialPort::NoFlowControl);//无流控制 serialPort->setParity(QSerialPort::NoParity); //无校验位 serialPort->setStopBits(QSerialPort::OneStop); //一位停止位 if(serialPort->open(QIODevice::ReadWrite)) { return true; } else { return false; } } void GLobal::onReceived() { qDebug()<< serialPort->readAll(); return; } void GLobal::sendData() { if(sendCache.count()>0) qDebug()<<sendCache; char data[13]; data[0]=(char)0xE5; data[1]=(char)0x00; data[2]=(char)0xA3; data[3]=(char)0x08; data[4]=(char)0x00; data[5]=(char)0x00; data[6]=(char)0x00; data[7]=(char)0x00; data[8]=(char)0x00; data[9]=(char)0x00; data[10]=(char)0x00; data[11]=(char)0x00; /* data[0]=(char)0x0C; data[1]=(char)0x00; data[2]=(char)0xA1; data[3]=(char)0x01; data[4]=(char)0x00; data[5]=(char)0x00; data[6]=(char)0x00; data[7]=(char)0x00; data[8]=(char)0x00; data[9]=(char)0x00; data[10]=(char)0x00; data[11]=(char)0x00; */ if(!sendCache.isEmpty()) { data[6]=sendCache.first(); sendCache.removeFirst(); } else { } data[12]=data[1]+data[2]+data[3]+data[4]+data[5]+data[6]+data[7]+data[8]+data[9]+data[10]+data[11]; if(!(serialPort==NULL)) { serialPort->write(data,13); } } bool GLobal::tNoBuff(int id) { for(int i=0;i<12;i++) { if(g->targetBuffID[i]==id) { return false; } } return true; } bool GLobal::tBuff(int id) { for(int i=0;i<12;i++) { if(g->targetBuffID[i]==id) { return true; } } return false; } bool GLobal::mNoBuff(int id) { for(int i=0;i<12;i++) { if(g->myBuffID[i]==id) { return false; } } return true; } bool GLobal::mBuff(int id) { for(int i=0;i<12;i++) { if(g->myBuffID[i]==id) { return true; } } return false; } float GLobal::perHP() { return (nowHP*1.0)/(maxHP/1.0); }
4,456
C++
.cpp
181
17.668508
103
0.554811
851896022/SuperMacros
33
12
1
GPL-3.0
9/20/2024, 10:45:00 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,539,767
findgamewindow.cpp
851896022_SuperMacros/findgamewindow.cpp
#include "findgamewindow.h" #include <windows.h> #include "global.h" FindGameWindow::FindGameWindow(QObject *parent) : QObject(parent) { connect(&timer,SIGNAL(timeout()),this,SLOT(onTimerOut())); timer.start(10000); onTimerOut(); } #include <QWidget> #include <QWindow> #include <QScreen> #include <QPixmap> void FindGameWindow::onTimerOut() { HWND hq=FindWindow("KGWin32App",NULL); g->w=QWindow::fromWinId((WId)hq); if(g->w==NULL) { g->isWindowOk=false; } else { g->isWindowOk=true; } }
549
C++
.cpp
26
17.769231
65
0.676245
851896022/SuperMacros
33
12
1
GPL-3.0
9/20/2024, 10:45:00 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,539,768
actuator.cpp
851896022_SuperMacros/macro/actuator.cpp
#include "actuator.h" Actuator::Actuator(QThread *parent) : QThread(parent) { timer=new QTimer; connect(timer,SIGNAL(timeout()),this,SLOT(run())); timer->start(500); } void Actuator::control() { if(timer->isActive()) { timer->stop(); } else { timer->start(500); } } void Actuator::run() { QString allstr=g->macro; allstr.remove("\r"); QStringList lineList=allstr.split("\n"); boolMap.clear(); for(int line=0;line<lineList.count();line++) { QStringList wordList=lineList.at(line).split(" "); if(wordList.count()<2 || wordList.at(0)==QString("/z"))//如果太短或者为注释 { continue; } else if(wordList.at(0)==QString("/b")) { boolMap.insert(wordList.at(2),stringToBoolLine(wordList.at(1))); } else if(wordList.at(0)==QString("/k")) { if(stringToBoolLine(wordList.at(1))) { if(wordList.at(2).toInt()>150||wordList.at(2).toInt()<4) { } else { g->sendCache.append((char)wordList.at(2).toInt()); return; } } } else { } } } bool Actuator::stringToBoolLine(QString str) { int c1=str.count("|"); int c2=str.count("&"); if(c1>0&&c2>0) { return false; } else if(c1>0) { QStringList point=str.split("|"); bool t=stringToBoolLPoint(point.at(0)); for(int i=1;i<point.count();i++) { t = t || stringToBoolLPoint(point.at(i)); } return t; } else if(c2>0) { QStringList point=str.split("&"); bool t=stringToBoolLPoint(point.at(0)); for(int i=1;i<point.count();i++) { t = t && stringToBoolLPoint(point.at(i)); } return t; } else { return stringToBoolLPoint(str); } } bool Actuator::stringToBoolLPoint(QString str) { if(str.count(":")>0) { QStringList t=str.split(":"); if(t.at(0)==QString("nobuff")) { int c=-1; c=g->buffNameMap[t.at(1)]; if(c==0) { return false; } else { return g->mNoBuff(c); } } else if(t.at(0)==QString("buff")) { int c=-1; c=g->buffNameMap[t.at(1)]; if(c==0) { return false; } else { return g->mBuff(c); } } else if(t.at(0)==QString("tnobuff")) { int c=-1; c=g->buffNameMap[t.at(1)]; if(c==0) { return false; } else { return g->tNoBuff(c); } } else if(t.at(0)==QString("tbuff")) { int c=-1; c=g->buffNameMap[t.at(1)]; if(c==0) { return false; } else { return g->tBuff(c); } } else { return false; } } else if(str.count("<")>0) { QStringList t=str.split("<"); if(t.at(0)==QString("HP")) { float f=t.at(1).toFloat(); if(f<1) { return g->perHP()<f; } else { return g->nowHP<f; } } else { return false; } } else if(str.count(">")>0) { QStringList t=str.split(">"); if(t.at(0)==QString("HP")) { float f=t.at(1).toFloat(); if(f<1) { return g->perHP()>f; } else { return g->nowHP>f; } } else { return false; } } else//如果没符号,认为是之前设定的键值 { if(boolMap.contains(str)) { return boolMap[str]; } else { return false; } } }
4,388
C++
.cpp
201
11.935323
76
0.403065
851896022/SuperMacros
33
12
1
GPL-3.0
9/20/2024, 10:45:00 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,539,769
tl.cpp
851896022_SuperMacros/macro/tl.cpp
#include "tl.h" TL::TL(QObject *parent) : QObject(parent) { timer= new QTimer; connect(timer,SIGNAL(timeout()),this,SLOT(onTimeOut())); } void TL::onTimeOut() { } void TL::control() { if(timer->isActive()) { timer->stop(); } else { timer->start(1000); } }
306
C++
.cpp
20
11.8
60
0.584507
851896022/SuperMacros
33
12
1
GPL-3.0
9/20/2024, 10:45:00 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,539,770
findhp.cpp
851896022_SuperMacros/worker/findhp.cpp
#include "findhp.h" #include <QTime> FindHp::FindHp(QThread *parent) : QThread(parent) { } void FindHp::initTHis() { rect=g->hpRect; } void FindHp::run() { //qDebug()<<rect; QPixmap screen = g->nowScreen; QPixmap pixmap=screen.copy(rect); g->hpImgCacheMy=pixmap; pixmap.save("A:/001.bmp"); image = pixmap.toImage();//将像素图转换为QImage for(int x=0;x<image.width();x++) { for(int y=0;y<image.height();y++) { if(image.pixelColor(x,y).red()==image.pixelColor(x,y).green()) { } else { image.setPixelColor(x,y,Qt::black); } if(image.pixelColor(x,y).value()<100) { image.setPixelColor(x,y,Qt::black); } else { image.setPixelColor(x,y,Qt::white); } } } image.save("A:/002.bmp"); int A=0; int B=0; bool state=false; QList<QImage> numberList; for(int x=0;x<image.width();x++) { if(state)//处于记录状态 { if(lineIsHaveColor(x))//有颜色 { B=x;//修改终点 } else//断开了 { //记录图片 QImage tmp=image.copy(A,0,B-A+1,image.height()); numberList.append(tmp); state = false; } } else//处于非记录状态 { if(lineIsHaveColor(x))//有颜色 { A=x;//修改起点 state=true; } else//还是没颜色 { } } } if(true) { for(int i=0;i<numberList.count();i++) { numberList.at(i).save("A:/c"+QString::number(i)+".bmp"); } } //=========================== QList<int> lmaxHP; QList<int> lnowHP; bool finishNowHP=false; for(int i=0;i<numberList.count();i++) { int tmp=imageToNumber(numberList.at(i)); numberList.at(i).save("A:/d"+QString::number(tmp)+".bmp"); if(tmp==10) { finishNowHP = true; } else { if(finishNowHP) { lmaxHP.append(tmp); } else { lnowHP.append(tmp); } } } int MaxHp=0; int nowHp=0; for(int i=0;i<lnowHP.count();i++) { nowHp=nowHp*10+lnowHP.at(i); } for(int i=0;i<lmaxHP.count();i++) { MaxHp=MaxHp*10+lmaxHP.at(i); } g->nowHP=nowHp; g->maxHP=MaxHp; } bool FindHp::lineIsHaveColor(int x) { for(int y=0;y<image.height();y++) { if(image.pixelColor(x,y).value()>100) { return true; } } return false; } int FindHp::imageToNumber(QImage img) { if(image.width()<8 || image.height()<9) { return 9; } img=img.scaled(8,9,Qt::IgnoreAspectRatio, Qt::SmoothTransformation); QBitArray hash(64); for(int x=0;x<8;x++) { for(int y=0;y<8;y++) { QColor a=img.pixelColor((x),(y)); QColor b=img.pixelColor((x),((y+1))); float GrayA= a.valueF(); float GrayB= b.valueF(); if(GrayA>GrayB) { hash.setBit(x*8+y,true); } else { hash.setBit(x*8+y,false); } } } //if(No==2)qDebug()<<hash; for(int i=0;i<g->numDb.count();i++)//对比每个图 { int c=0; for(int j=0;j<64;j++) { if(hash.at(j) == g->numDb.at(i).toBitArray().at(j)) { } else { c++; } } if(c<10) { return i; } } return 9; }
3,946
C++
.cpp
173
13.32948
74
0.434592
851896022/SuperMacros
33
12
1
GPL-3.0
9/20/2024, 10:45:00 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,539,771
discern.cpp
851896022_SuperMacros/worker/discern.cpp
#include "discern.h" #include <QDateTime> Discern::Discern(QObject *parent) : QObject(parent) { timer = new QTimer; connect(timer,SIGNAL(timeout()),this,SLOT(onTimerOut())); for(int i=0;i<24;i++) { findIcon[i]=new FindIcon; findIcon[i]->initThis(i); } findHp = new FindHp; findHp->initTHis(); findKill = new FindKill; findKill->initTHis(); timer->start(480); list_screen = QGuiApplication::screens(); //可能电脑接了多个屏幕 } #include "QPixmap" #include <QApplication> #include <QWindow> void Discern::onTimerOut() { g->nowScreen=g->w->screen()->grabWindow(g->w->winId()); g->nowScreen.save("A:/sss.bmp"); int w=g->nowScreen.width(); int h=g->nowScreen.height(); float stdScale = 4.0/3.0; float nowScale = (w*1.0)/(h*1.0); float scale ; if(nowScale>stdScale)//宽了,以高为准 { scale = (h*1.0)/(1080.0); } else//窄了,以宽为准 { scale = (w*1.0)/(1440.0); } g->hpRect.setRect(100*scale+g->mHp.x(),52*scale+g->mHp.y(),190*scale+g->mHp.width(),12*scale+g->mHp.height()); for(int i=0;i<12;i++) { g->myBuffRect[i].setRect((w/2)-307+g->mDev.x()+(48*i),(h/2)-128+g->mDev.y(),42,42); g->targetBuffRect[i].setRect((w/2)-109+g->tDev.x()+(48*i),(h/2)+53+g->tDev.y(),42,42); } //---------技能------------- int kx; int ky; int kw; int kh; ky=h-(198*scale); kh=44*scale; kw=683*scale; kx=(w/2)-(kw/2)+(24*scale); g->killRect.setRect(kx,ky,kw,kh); #ifdef asdlkjasf int x=(int)rect.left+8; int y=(int)rect.top+32; int w=(int)(rect.right-rect.left)-17; int h=(int)(rect.bottom-rect.top)-41; g->windowRect.setRect(x,y,w,h); //g->myBuffRect[0].setRect(x+653,y+413,42,42); //g->targetBuffRect[0].setRect(x+1079,y+594,42,42); for(int i=0;i<12;i++) { g->myBuffRect[i].setRect(x+653+(48*i),y+413,42,42); g->targetBuffRect[i].setRect(x+1079+(48*i),y+594,42,42); } #endif //刷新坐标 for(int i=0;i<24;i++) { findIcon[i]->initThis(i); } findHp->initTHis(); findKill->initTHis(); if(!g->isWindowOk) { return; } //WId ss = 0; // = list_screen.at(0)->grabWindow(0,0,0,g->targetBuffRect[11].x()+45,g->targetBuffRect[11].y()+45); //g->nowScreen=list_screen.at(0)->grabWindow(qApp->desktop().winId()); findHp->start(); findKill->start(); for(int i=0;i<24;i++) { findIcon[i]->start(); } /* qDebug()<<g->buffDb.count()<<g->numDb.count(); qDebug()<<"m"<<g->myBuffID[0] <<g->myBuffID[1] <<g->myBuffID[2] <<g->myBuffID[3] <<g->myBuffID[4] <<g->myBuffID[5] <<g->myBuffID[6] <<g->myBuffID[7] <<g->myBuffID[8] <<g->myBuffID[9] <<g->myBuffID[10] <<g->myBuffID[11] <<g->nowHP <<g->maxHP; qDebug()<<"t"<<g->targetBuffID[0] <<g->targetBuffID[1] <<g->targetBuffID[2] <<g->targetBuffID[3] <<g->targetBuffID[4] <<g->targetBuffID[5] <<g->targetBuffID[6] <<g->targetBuffID[7] <<g->targetBuffID[8] <<g->targetBuffID[9] <<g->targetBuffID[10] <<g->targetBuffID[11]; */ }
3,807
C++
.cpp
118
21.779661
114
0.477222
851896022/SuperMacros
33
12
1
GPL-3.0
9/20/2024, 10:45:00 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,539,772
findkill.cpp
851896022_SuperMacros/worker/findkill.cpp
#include "findkill.h" FindKill::FindKill(QThread *parent) : QThread(parent) { } void FindKill::initTHis() { rect=g->killRect; } void FindKill::run() { QPixmap screen = g->nowScreen; QPixmap pixmap=screen.copy(rect); g->killImgCache=pixmap; }
260
C++
.cpp
14
16.285714
53
0.717213
851896022/SuperMacros
33
12
1
GPL-3.0
9/20/2024, 10:45:00 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,539,773
findicon.cpp
851896022_SuperMacros/worker/findicon.cpp
#include "findicon.h" FindIcon::FindIcon(QThread *parent) : QThread(parent) { } void FindIcon::initThis(int No) { //this->No=No; if(No>11)//如果是目标 { isMy=false; this->No=No-12; rect=g->targetBuffRect[this->No]; } else { isMy=true; this->No=No; rect=g->myBuffRect[this->No]; } } void FindIcon::run() { //qDebug()<<QThread::currentThread(); //if(No==2)qDebug()<<rect; //QPixmap pixmap = list_screen.at(0)->grabWindow(0,rect.x(),rect.y(),rect.width(),rect.height()); QPixmap screen = g->nowScreen; QPixmap pixmap=screen.copy(rect); if(isMy) { pixmap.save("A:/A"+QString::number(No)+".bmp"); g->buffImgCacheMy[No]=pixmap; } else { pixmap.save("A:/B"+QString::number(No)+".bmp"); g->buffImgCacheT[No]=pixmap; } QImage image = pixmap.toImage();//将像素图转换为QImage if(image.width()<8 || image.height()<9) { if(isMy) { g->myBuffID[No]=-1; } else { g->targetBuffID[No]=-1; } return; } image=image.scaled(8,9,Qt::IgnoreAspectRatio, Qt::SmoothTransformation); QBitArray hash(64); for(int x=0;x<8;x++) { for(int y=0;y<8;y++) { QColor a=image.pixelColor((x),(y)); QColor b=image.pixelColor((x),((y+1))); float GrayA= a.valueF(); float GrayB= b.valueF(); if(GrayA>GrayB) { hash.setBit(x*8+y,true); } else { hash.setBit(x*8+y,false); } } } int ID=-1; //if(No==2)qDebug()<<hash; for(int i=0;i<g->buffDb.count();i++)//对比每个图 { int c=0; for(int j=0;j<64;j++) { if(hash.at(j) == g->buffDb.at(i).toBitArray().at(j)) { } else { c++; } } if(c<10) { ID = i; //qDebug()<<c; } } if(isMy) { g->myBuffID[No]=ID; } else { g->targetBuffID[No]=ID; } }
2,246
C++
.cpp
100
14.16
101
0.463567
851896022/SuperMacros
33
12
1
GPL-3.0
9/20/2024, 10:45:00 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,539,776
test.h
851896022_SuperMacros/test.h
#ifndef TEST_H #define TEST_H #include <QObject> #include <QBitArray> #include <QFile> #include <QFileInfo> #include <QDebug> #include <QImage> #include <QRgb> #include <QBitArray> #include <QDir> #include <QList> #include <QSettings> #include <QVariant> //#include "global.h" class test : public QObject { Q_OBJECT public: explicit test(QObject *parent = nullptr); signals: public slots: void buff(); void num(); }; #endif // TEST_H
454
C++
.h
26
15.692308
45
0.733491
851896022/SuperMacros
33
12
1
GPL-3.0
9/20/2024, 10:45:00 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,539,777
findgamewindow.h
851896022_SuperMacros/findgamewindow.h
#ifndef FINDGAMEWINDOW_H #define FINDGAMEWINDOW_H #include <QObject> #include "global.h" #include "QTimer" class FindGameWindow : public QObject { Q_OBJECT public: explicit FindGameWindow(QObject *parent = nullptr); QTimer timer; signals: public slots: void onTimerOut(); }; #endif // FINDGAMEWINDOW_H
320
C++
.h
16
17.875
55
0.774086
851896022/SuperMacros
33
12
1
GPL-3.0
9/20/2024, 10:45:00 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,539,778
window.h
851896022_SuperMacros/window.h
#ifndef WINDOW_H #define WINDOW_H #include <QMainWindow> #include "global.h" #include "math.h" using namespace std; #define PI 3.1415926535897932384626433832795 #include <QLabel> #include <QHBoxLayout> namespace Ui { class window; } class window : public QMainWindow { Q_OBJECT public: explicit window(QWidget *parent = 0); ~window(); QTimer delayCount; QMap<QString,bool> boolMap; bool isOk; QHBoxLayout hBoxMy; QHBoxLayout hBoxT; QLabel lbMy[12]; QLabel lbT[12]; QHBoxLayout hBoxKill; QLabel lbKill[16]; private slots: void on_test_clicked(); void on_startLink_clicked(); double colorDiff(QColor hsv1,QColor hsv2); void on_btnSave_clicked(); bool stringToBoolLine(QString str); bool stringToBoolLPoint(QString str); void on_btn3_clicked(); void on_textEdit_textChanged(); void on_btnup_1_clicked(); void on_btndown_1_clicked(); void on_btnleft_1_clicked(); void on_btnright_1_clicked(); void on_btnup_2_clicked(); void on_btndown_2_clicked(); void on_btnleft_2_clicked(); void on_btnright_2_clicked(); void on_btnup_3_clicked(); void on_btndown_3_clicked(); void on_btnleft_3_clicked(); void on_btnright_3_clicked(); void on_btnwa_3_clicked(); void on_btnwd_3_clicked(); void on_btnha_3_clicked(); void on_btnhd_3_clicked(); private: Ui::window *ui; }; #endif // WINDOW_H
1,446
C++
.h
56
21.75
46
0.698389
851896022/SuperMacros
33
12
1
GPL-3.0
9/20/2024, 10:45:00 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,539,779
global.h
851896022_SuperMacros/global.h
#ifndef GLOBAL_H #define GLOBAL_H #include <QObject> #include <QString> #include <QDir> #include <QFile> #include <QTimer> #include <QSerialPort> #include <QSerialPortInfo> #include <QDebug> #include <QRect> #include <QVariant> #include <QPixmap> #include <QStringList> #include <QMap> #include <QPoint> class GLobal : public QObject { Q_OBJECT public: explicit GLobal(QObject *parent = nullptr); ~GLobal(); QStringList keyNameList; QList<int> keyNoList; QStringList comNameList; QSerialPort *serialPort=NULL; QList<char> sendCache; QTimer sendTimer; int temp=600; //窗口 bool isWindowOk=false; QWindow *w; QPoint mDev; QPoint tDev; QRect mHp; QPixmap buffImgCacheMy[12]; QPixmap buffImgCacheT[12]; QPixmap hpImgCacheMy; QPixmap killImgCache; //技能 QRect windowRect; QRect myBuffRect[12]; QRect targetBuffRect[12]; int myBuffID[12]; int targetBuffID[12]; QList<QVariant> buffDb; QStringList buffName; QPixmap nowScreen; QMap<QString,int> buffNameMap; //血量 int maxHP; int nowHP; QRect hpRect; QList<QVariant> numDb; //宏 QString macro; //技能 QRect killRect; signals: public slots: bool startLink(QString name); void onReceived(); void sendData(); bool tNoBuff(int id); bool tBuff(int id); bool mNoBuff(int id); bool mBuff(int id); float perHP();//百分比血量 }; extern GLobal *g; #endif // GLOBAL_H
1,507
C++
.h
71
17.126761
47
0.697293
851896022/SuperMacros
33
12
1
GPL-3.0
9/20/2024, 10:45:00 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,539,781
actuator.h
851896022_SuperMacros/macro/actuator.h
#ifndef ACTUATOR_H #define ACTUATOR_H #include <QThread> #include <QObject> #include <QTimer> #include "global.h" class Actuator : public QThread { Q_OBJECT public: explicit Actuator(QThread *parent = nullptr); QTimer *timer; QMap<QString,bool> boolMap; signals: public slots: void run(); bool stringToBoolLine(QString str); bool stringToBoolLPoint(QString str); void control(); }; #endif // ACTUATOR_H
439
C++
.h
21
18.190476
49
0.736715
851896022/SuperMacros
33
12
1
GPL-3.0
9/20/2024, 10:45:00 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,539,782
findicon.h
851896022_SuperMacros/worker/findicon.h
#ifndef FINDICON_H #define FINDICON_H #include <QObject> #include <QThread> #include <QList> #include <QGuiApplication> #include <QRect> #include "global.h" #include <QBitArray> #include <QPixmap> class FindIcon : public QThread { Q_OBJECT public: explicit FindIcon(QThread *parent = nullptr); bool isMy=true; int No=0; QRect rect; signals: public slots: void run(); void initThis(int No); }; #endif // FINDICON_H
447
C++
.h
24
16.25
49
0.732057
851896022/SuperMacros
33
12
1
GPL-3.0
9/20/2024, 10:45:00 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,539,783
discern.h
851896022_SuperMacros/worker/discern.h
#ifndef DISCERN_H #define DISCERN_H #include <QObject> #include "findicon.h" #include "QTimer" #include <QScreen> #include "findhp.h" #include "findkill.h" class Discern : public QObject { Q_OBJECT public: explicit Discern(QObject *parent = nullptr); FindIcon *findIcon[24]; FindHp *findHp; QTimer *timer; FindKill * findKill; QList<QScreen *> list_screen; signals: public slots: void onTimerOut(); }; #endif // DISCERN_H
458
C++
.h
23
17.347826
48
0.723898
851896022/SuperMacros
33
12
1
GPL-3.0
9/20/2024, 10:45:00 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,539,784
findhp.h
851896022_SuperMacros/worker/findhp.h
#ifndef FINDHP_H #define FINDHP_H #include <QObject> #include <QThread> #include <QList> #include <QGuiApplication> #include <QRect> #include "global.h" #include <QBitArray> #include <QPixmap> class FindHp : public QThread { Q_OBJECT public: explicit FindHp(QThread *parent = nullptr); QRect rect; QImage image; signals: public slots: void initTHis(); void run(); bool lineIsHaveColor(int y); int imageToNumber(QImage img); }; #endif // FINDHP_H
483
C++
.h
25
16.84
47
0.732892
851896022/SuperMacros
33
12
1
GPL-3.0
9/20/2024, 10:45:00 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,539,785
findkill.h
851896022_SuperMacros/worker/findkill.h
#ifndef FINDKILL_H #define FINDKILL_H #include <QObject> #include <QThread> #include <QList> #include <QGuiApplication> #include <QRect> #include "global.h" #include <QBitArray> #include <QPixmap> class FindKill : public QThread { Q_OBJECT public: explicit FindKill(QThread *parent = nullptr); QRect rect; QImage image; signals: public slots: void initTHis(); void run(); }; #endif // FINDKILL_H
425
C++
.h
23
16.217391
49
0.740554
851896022/SuperMacros
33
12
1
GPL-3.0
9/20/2024, 10:45:00 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,539,788
main.cpp
BeiChenYx_FramelessWindow/FramelessWindow/main.cpp
#include <QApplication> #include <QTranslator> #include "FrameLessWidget/framelesswidget.h" #include "mainwindow.h" #include "CustomModelView/customheaderview.h" int main(int argc, char *argv[]) { QApplication a(argc, argv); // 处理默认菜单的英文 QTranslator translator; translator.load(QString(":/images/qt_zh_CN.qm")); QApplication::installTranslator(&translator); // 显示最大化和全屏 FramelessWidget w; // 隐藏最大化和全屏 // FramelessWidget w(false, false); // 显示最大化,关闭全屏 // FramelessWidget w(true, false); // 隐藏最大化, 显示全屏, 这种情况应该无法打开全屏 // FramelessWidget w(false, true); auto pMain = new MainWindow(&w); w.setContent(pMain); w.show(); return a.exec(); }
815
C++
.cpp
25
24.72
53
0.700297
BeiChenYx/FramelessWindow
33
21
0
GPL-3.0
9/20/2024, 10:45:00 PM (Europe/Amsterdam)
false
false
false
false
true
false
true
false
1,539,789
mainwindow.cpp
BeiChenYx_FramelessWindow/FramelessWindow/mainwindow.cpp
#include <QHBoxLayout> #include <QFrame> #include <QHBoxLayout> #include "mainwindow.h" #include "ui_mainwindow.h" #include "CustomModelView/customlineeditedelegate.h" MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow), m_pBtnGroupLeftNav(new QButtonGroup(this)), m_pVersionWidget(new VersionInfoWidget("版本号: V1.0.0")), m_pCustomTableView(new CustomTableView()), m_pListView(new QListView()), m_pTreeView(new QTreeView()), m_pBasicWidget(new BasicWidget(this)) { // 框架 --start ui->setupUi(this); this->initUi(); this->initConnetion(); // 框架 --end } MainWindow::~MainWindow() { delete ui; } void MainWindow::initUi() { // 框架 --start // 初始侧边导航为100px, 导航和内容的比例为 1 : 9 QList<int> splitterList{100, this->width() - 108}; ui->splitter->setSizes(splitterList); ui->splitter->setStretchFactor(0, 1); ui->splitter->setStretchFactor(1, 9); ui->statusbar->addPermanentWidget(m_pVersionWidget); for(auto pComboBox: findChildren<QComboBox*>()){ pComboBox->setView(new QListView()); } // 框架 --end // 测试 --start this->addNavStackWidget("", tr("基本组件"), m_pBasicWidget); this->addNavHLine(); auto tableWidget = new QWidget(this); tableWidget->setLayout(new QHBoxLayout); tableWidget->layout()->addWidget(m_pCustomTableView); tableWidget->setObjectName("tableWidget"); this->addNavStackWidget("tableBtn", "tableView", tableWidget); auto listWidget = new QWidget(this); listWidget->setLayout(new QHBoxLayout); listWidget->layout()->addWidget(m_pListView); listWidget->setObjectName("listWidget"); this->addNavStackWidget("listBtn", "listView", listWidget); auto treeWidget = new QWidget(this); treeWidget->setLayout(new QHBoxLayout); treeWidget->layout()->addWidget(m_pTreeView); treeWidget->setObjectName("treeWidget"); this->addNavStackWidget("treeBtn", "treeView", treeWidget); this->addNavHLine(); this->addNavStackWidget("", tr("自绘"), new QWidget(this), QIcon(":/images/filter.png")); m_pListView->setModel(&m_model); m_pTreeView->setModel(&m_model); m_pCustomTableView->setModel(&m_model); m_pCustomTableView->setColumnWidth(1, 150); // 初始化菜单 m_pToListView = new QAction(tr("转到ListView"), this); m_pToTreeView = new QAction(tr("转到TreeView"), this); m_pToTableView = new QAction(tr("转到TableView"), this); m_pViewMenu = new QMenu(this); m_pViewMenu->addAction(m_pToListView); m_pViewMenu->addAction(m_pToTreeView); m_pViewMenu->addAction(m_pToTableView); m_viewBtnMap[m_pToTableView] = "tableBtn"; m_viewBtnMap[m_pToListView] = "listBtn"; m_viewBtnMap[m_pToTreeView] = "treeBtn"; m_pCustomTableView->setContextMenuPolicy(Qt::CustomContextMenu); m_pTreeView->setContextMenuPolicy(Qt::CustomContextMenu); m_pListView->setContextMenuPolicy(Qt::CustomContextMenu); // 测试 --end } void MainWindow::initConnetion() { // 框架 --start connect(m_pBtnGroupLeftNav, SIGNAL(buttonClicked(QAbstractButton *)), this, SLOT(on_buttonClickedLeftNav(QAbstractButton *))); // 框架 --end // 测试 --start connect(m_pCustomTableView, &CustomTableView::customContextMenuRequested, this, [this](const QPoint &){ m_pToTableView->setEnabled(false); m_pToListView->setEnabled(true); m_pToTreeView->setEnabled(true); m_pViewMenu->exec(QCursor::pos()); }); connect(m_pListView, &QListView::customContextMenuRequested, this, [this](const QPoint &){ m_pToTableView->setEnabled(true); m_pToListView->setEnabled(false); m_pToTreeView->setEnabled(true); m_pViewMenu->exec(QCursor::pos()); }); connect(m_pTreeView, &QTreeView::customContextMenuRequested, this, [this](const QPoint &){ m_pToTableView->setEnabled(true); m_pToListView->setEnabled(true); m_pToTreeView->setEnabled(false); m_pViewMenu->exec(QCursor::pos()); }); connect(m_pToListView, &QAction::triggered, this, [this](){ auto view = qApp->focusWidget(); auto who = m_viewBtnMap.value(m_pToListView, ""); auto btn = findChild<QToolButton*>(who); btn->click(); if(view == m_pCustomTableView){ int row = m_pCustomTableView->currentIndex().row(); auto index = m_pListView->model()->index(row, 0); m_pListView->setCurrentIndex(index); }else if(view == m_pTreeView){ int row = m_pTreeView->currentIndex().row(); auto index = m_pListView->model()->index(row, 0); m_pListView->setCurrentIndex(index); } }); connect(m_pToTreeView, &QAction::triggered, this, [this](){ auto view = qApp->focusWidget(); auto who = m_viewBtnMap.value(m_pToTreeView, ""); auto btn = findChild<QToolButton*>(who); btn->click(); if(view == m_pCustomTableView){ int row = m_pCustomTableView->currentIndex().row(); auto index = m_pTreeView->model()->index(row, 0); m_pTreeView->setCurrentIndex(index); }else if(view == m_pListView){ int row = m_pListView->currentIndex().row(); auto index = m_pTreeView->model()->index(row, 0); m_pTreeView->setCurrentIndex(index); } }); connect(m_pToTableView, &QAction::triggered, this, [this](){ auto view = qApp->focusWidget(); auto who = m_viewBtnMap.value(m_pToTableView, ""); auto btn = findChild<QToolButton*>(who); btn->click(); if(view == m_pTreeView){ int row = m_pTreeView->currentIndex().row(); auto index = m_pCustomTableView->model()->index(row, 0); m_pCustomTableView->setCurrentIndex(index); }else if(view == m_pListView){ int row = m_pListView->currentIndex().row(); auto index = m_pCustomTableView->model()->index(row, 0); m_pCustomTableView->setCurrentIndex(index); } }); // 测试 --end } void MainWindow::on_buttonClickedLeftNav(QAbstractButton *btn) { ui->stackedWidget->setCurrentIndex(m_pBtnGroupLeftNav->id(btn)); QToolButton *obj = qobject_cast<QToolButton*>(btn); obj->setChecked(true); } void MainWindow::addNavStackWidget(QString objectName, QString text, QWidget *widget, QIcon ico) { int btnId = m_pTBtnLeftNavVector.length(); auto pTBtn = new QToolButton(this); m_pTBtnLeftNavVector.append(pTBtn); pTBtn->setText(text); pTBtn->setCheckable(true); pTBtn->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); if(!objectName.trimmed().isEmpty()){ pTBtn->setObjectName(objectName); } if(!ico.isNull()){ pTBtn->setIcon(ico); pTBtn->setIconSize(QSize(16, 16)); pTBtn->setToolButtonStyle(Qt::ToolButtonTextUnderIcon); }else{ pTBtn->setToolButtonStyle(Qt::ToolButtonTextOnly); } m_pBtnGroupLeftNav->addButton(pTBtn, btnId); ui->verticalLayout_left_nav->addWidget(pTBtn); ui->stackedWidget->addWidget(widget); } void MainWindow::addNavHLine() { QFrame *line = new QFrame(this); line->setGeometry(QRect(40, 180, 400, 3)); line->setFrameShape(QFrame::HLine); line->setFrameShadow(QFrame::Sunken); line->raise(); line->setObjectName("HLine"); ui->verticalLayout_left_nav->addWidget(line); }
7,559
C++
.cpp
189
33.216931
107
0.662524
BeiChenYx/FramelessWindow
33
21
0
GPL-3.0
9/20/2024, 10:45:00 PM (Europe/Amsterdam)
false
false
false
false
false
false
true
false
1,539,791
customhorizontalheaderview.cpp
BeiChenYx_FramelessWindow/FramelessWindow/CustomModelView/customhorizontalheaderview.cpp
#include <QDebug> #include <QLabel> #include "customhorizontalheaderview.h" const int HEADER_RIGHT_BORDER = 1; CustomHorizontalHeaderView::CustomHorizontalHeaderView(QWidget *parent) : QHeaderView(Qt::Horizontal, parent) { setSectionsMovable(true); setSectionsClickable(true); this->setStretchLastSection(true); this->setObjectName("CustomHorizontalHeaderView"); connect(this, &QHeaderView::sectionResized, this, &CustomHorizontalHeaderView::handleSectionResized); connect(this, &QHeaderView::sectionMoved, this, &CustomHorizontalHeaderView::handleSectionMoved); } CustomHorizontalHeaderView::~CustomHorizontalHeaderView() { for (auto tableFilter : m_pTableFilterList) { delete tableFilter; tableFilter = nullptr; } } void CustomHorizontalHeaderView::setModel(QAbstractItemModel *model) { QHeaderView::setModel(model); for (int i=0; i<count(); ++i) { auto pTableFilter = new CustomHeaderView(i, this); pTableFilter->setTitle(this->model()->headerData(i, Qt::Horizontal).toString()); pTableFilter->show(); m_pTableFilterList.append(pTableFilter); connect(pTableFilter, &CustomHeaderView::sortedUp, this, [this](int index){ emit this->sortedUp(index); for (int i=0; i<m_pTableFilterList.length(); ++i) { if(i == index){continue;} m_pTableFilterList.at(index)->clearStatus(); } }); connect(pTableFilter, &CustomHeaderView::sortedDown, this, [this](int index){ m_pTableFilterList.at(index)->clearStatus(); emit this->sortedDown(index); for (int i=0; i<m_pTableFilterList.length(); ++i) { if(i == index){continue;} m_pTableFilterList.at(index)->clearStatus(); } }); connect(pTableFilter, &CustomHeaderView::filter, this, [this](int index, QString msg){ if(m_pTableFilterList[index]->getFilterMsg().trimmed().isEmpty()){ m_pTableFilterList[index]->clearFilterStatus(); } emit this->filter(index, msg); }); } } void CustomHorizontalHeaderView::headerDataChanged(Qt::Orientation orientation, int logicalFirst, int logicalLast) { if(logicalFirst < 0 || logicalLast > m_pTableFilterList.length()){return;} if(orientation == Qt::Horizontal){ for (int i=logicalFirst; i<=logicalLast; ++i) { m_pTableFilterList.at(i)->setTitle(this->model()->headerData(i, Qt::Horizontal).toString()); } } } void CustomHorizontalHeaderView::paintSection(QPainter *painter, const QRect &rect, int logicalIndex) const { // 屏蔽默认绘制表头,避免修改model, model 可以不更改情况下共享给不同的view // 表头内容都在showEvent中处理,目前没有其他更好方法 Q_UNUSED(rect); painter->save(); QHeaderView::paintSection(painter, QRect(), logicalIndex); painter->restore(); auto pTableFilter = m_pTableFilterList.at(logicalIndex); pTableFilter->setGeometry(sectionViewportPosition(logicalIndex), 0, sectionSize(logicalIndex) - HEADER_RIGHT_BORDER, height()); pTableFilter->show(); // 根据第一个可见视图索引求出逻辑索引, 在这之前的都要隐藏 int startShowIndex = this->visualIndexAt(0); for (int i=0; i<startShowIndex; ++i) { m_pTableFilterList.at(i)->hide(); } } void CustomHorizontalHeaderView::handleSectionResized(int i, int oldSize, int newSize) { Q_UNUSED(i) Q_UNUSED(oldSize); Q_UNUSED(newSize); this->fixSectionPositions(); } void CustomHorizontalHeaderView::handleSectionMoved(int logical, int oldVisualIndex, int newVisualIndex) { Q_UNUSED(logical); Q_UNUSED(oldVisualIndex); Q_UNUSED(newVisualIndex); this->fixSectionPositions(); } void CustomHorizontalHeaderView::resizeEvent(QResizeEvent *event) { QHeaderView::resizeEvent(event); this->fixSectionPositions(); } void CustomHorizontalHeaderView::fixSectionPositions() { for (int i = 0; i<m_pTableFilterList.length();i++){ m_pTableFilterList.at(i)->setGeometry(sectionViewportPosition(i), 0, sectionSize(i) - HEADER_RIGHT_BORDER, height()); } }
4,312
C++
.cpp
105
33.133333
114
0.682614
BeiChenYx/FramelessWindow
33
21
0
GPL-3.0
9/20/2024, 10:45:00 PM (Europe/Amsterdam)
false
false
false
false
true
false
true
false
1,539,792
customtableview.cpp
BeiChenYx_FramelessWindow/FramelessWindow/CustomModelView/customtableview.cpp
#include <QDebug> #include <QItemDelegate> #include "CustomModelView/customtableview.h" CustomTableView::CustomTableView(QWidget *parent) : QTableView(parent), m_pHHeaderView(new CustomHorizontalHeaderView(this)), m_pSortFilterModel(new QSortFilterProxyModel(this)) { this->initConnect(); this->setAlternatingRowColors(true); this->setHorizontalHeader(m_pHHeaderView); this->setObjectName("CustomTableView"); } void CustomTableView::initConnect() { connect(m_pHHeaderView, &CustomHorizontalHeaderView::sortedUp, this, [this](int index){ m_pSortFilterModel->setFilterKeyColumn(index); m_pSortFilterModel->sort(index, Qt::AscendingOrder); }); connect(m_pHHeaderView, &CustomHorizontalHeaderView::sortedDown, this, [this](int index){ m_pSortFilterModel->setFilterKeyColumn(index); m_pSortFilterModel->sort(index, Qt::DescendingOrder); }); connect(m_pHHeaderView, &CustomHorizontalHeaderView::filter, this, [this](int index, QString msg){ m_pSortFilterModel->setFilterKeyColumn(index); m_pSortFilterModel->setFilterFixedString(msg); }); // 设置选中行 this->setSelectionBehavior(QAbstractItemView::SelectRows); // 设置单选 this->setSelectionMode(QAbstractItemView::SingleSelection); // 处理鼠标选择 connect(this, &QTableView::pressed, this, [this](const QModelIndex &index){ qDebug() << "selected: " << index.row() << " data:" << this->model()->data(index).toString(); }); } void CustomTableView::setModel(QAbstractItemModel *model) { m_pSortFilterModel->setSourceModel(model); QTableView::setModel(m_pSortFilterModel); }
1,686
C++
.cpp
41
35.634146
102
0.732132
BeiChenYx/FramelessWindow
33
21
0
GPL-3.0
9/20/2024, 10:45:00 PM (Europe/Amsterdam)
false
false
false
false
true
false
true
false
1,539,793
custommodel.cpp
BeiChenYx_FramelessWindow/FramelessWindow/CustomModelView/custommodel.cpp
#include "custommodel.h" #include <ctime> #include <algorithm> #include <QDebug> CustomModel::CustomModel(QAbstractItemModel *parent) : QAbstractItemModel(parent) { // std::list<int> intList; auto now = QDateTime::currentDateTime(); for (int i=0; i<10; ++i) { // typedef std::tuple<int, int, int, int, QString, QDateTime> ModeLCol; m_stocks.append({i, i*100, qrand() % 100, qrand() % 300, QString("name%1\nname_name").arg(qrand() % 100), now.addSecs(i)}); // auto item = qrand() % 100; // intList.push_back(item); // qDebug() << item; } // auto listMin = std::min_element(intList.begin(), intList.end()); // auto listMax = std::max_element(intList.begin(), intList.end()); // qDebug() << *listMin << " : " << *listMax; } int CustomModel::rowCount(const QModelIndex &parent) const { Q_UNUSED(parent); return m_stocks.length(); } int CustomModel::columnCount(const QModelIndex &parent) const { Q_UNUSED(parent); return m_names.length(); } QVariant CustomModel::data(const QModelIndex &index, int role) const { if(!index.isValid()){ qDebug() << "index is valid: " << index.row() << ":" << index.column(); return QVariant(); } if(index.row() > m_stocks.length() || index.column() > m_names.length()){ qDebug() << "m_stocks len: " << m_stocks.length() << " " << index.row() << ":" << index.column(); return QVariant(); } if(role == Qt::DisplayRole){ auto stock = m_stocks.at(index.row()); return (index.column() > stock.length() || index.column() < 0) ? QVariant() : stock.at(index.column()); } else if(role == Qt::EditRole){ auto stock = m_stocks.at(index.row()); return (index.column() > stock.length() || index.column() < 0) ? QVariant() : stock.at(index.column()); } return QVariant(); } bool CustomModel::setData(const QModelIndex &index, const QVariant &value, int role) { if(!index.isValid()){ qDebug() << "index is valid: " << index.row() << ":" << index.column(); return false; } if(role == Qt::EditRole){ auto stock = m_stocks.at(index.row()); stock[index.column()] = value; emit dataChanged(index, index); return true; } return false; } QVariant CustomModel::headerData(int section, Qt::Orientation orientation, int role) const { if(role != Qt::DisplayRole){ return QVariant(); } if(orientation == Qt::Horizontal){ if(section < 0 || section > m_names.length()){return QVariant();} return QVariant(m_names.at(section)); }else { return QVariant(QString::number(section)); } } bool CustomModel::setHeaderData(int section, Qt::Orientation orientation, const QVariant &value, int role) { if(role != Qt::EditRole){ return false; } if(orientation == Qt::Horizontal){ m_names.replace(section, value.toString()); emit headerDataChanged(Qt::Horizontal, section, section); return true; }else{ return false; } } Qt::ItemFlags CustomModel::flags(const QModelIndex &index) const { if(index.isValid()){ Qt::ItemFlags flags = Qt::ItemIsEnabled | Qt::ItemIsSelectable | Qt::ItemNeverHasChildren | Qt::ItemIsEditable; return flags; } return QAbstractItemModel::flags(index); } QModelIndex CustomModel::index(int row, int column, const QModelIndex &parent) const { if (row < 0 || column < 0 || column >= columnCount(parent) || column > m_names.length()) return QModelIndex(); return createIndex(row,column); } QModelIndex CustomModel::parent(const QModelIndex &child) const { Q_UNUSED(child); return QModelIndex(); } void CustomModel::sort(int column, Qt::SortOrder order) { // 修改之前发生信号 emit layoutAboutToBeChanged(); if(column <= 4 && column >= 0){ if(order == Qt::AscendingOrder){ std::sort(m_stocks.begin(), m_stocks.end(), [](QVector<QVariant> pre, QVector<QVariant> item){ return pre.at(2).toInt() < item.at(2).toInt(); }); } if(order == Qt::DescendingOrder){ std::sort(m_stocks.rbegin(), m_stocks.rend(), [](QVector<QVariant> pre, QVector<QVariant> item){ return pre.at(2).toInt() < item.at(2).toInt(); }); } } // 修改之后要发送的信号 emit layoutChanged(); }
4,433
C++
.cpp
125
30.008
131
0.619338
BeiChenYx/FramelessWindow
33
21
0
GPL-3.0
9/20/2024, 10:45:00 PM (Europe/Amsterdam)
false
false
false
false
true
false
true
false
1,539,794
customheaderview.cpp
BeiChenYx_FramelessWindow/FramelessWindow/CustomModelView/customheaderview.cpp
#include "customheaderview.h" #include "ui_customheaderview.h" #include <QHBoxLayout> #include <QLineEdit> #include <QPushButton> #include <QDebug> FilterDialog::FilterDialog(QWidget *parent) : QWidget(parent) { this->setWindowFlags(Qt::FramelessWindowHint | Qt::WindowSystemMenuHint); auto hLayout = new QHBoxLayout(); m_pLineEdit = new QLineEdit(); m_pBtn = new QPushButton(); m_pBtn->setText(tr("确定")); hLayout->addWidget(m_pLineEdit); hLayout->addWidget(m_pBtn); this->setLayout(hLayout); this->setWindowModality(Qt::ApplicationModal); connect(m_pBtn, &QPushButton::clicked, this, [this](){ emit filter(this->filterMsg()); this->close(); }); } CustomHeaderView::CustomHeaderView(int index, QWidget *parent) : QWidget(parent), ui(new Ui::CustomHeaderView), m_index(index), m_pFilterDialog(new FilterDialog) { ui->setupUi(this); ui->toolButton_filter->setVisible(false); ui->toolButton_sortUp->setVisible(false); ui->toolButton_sortDown->setVisible(false); this->setObjectName("CustomHeaderView"); m_pFilterDialog->hide(); connect(ui->toolButton_sortUp, &QToolButton::clicked, this, [this](){ ui->buttonGroup->setExclusive(true); ui->toolButton_filter->setChecked(false); ui->toolButton_sortUp->setChecked(true); ui->toolButton_sortDown->setChecked(false); this->sortedUp(m_index); }); connect(ui->toolButton_sortDown, &QToolButton::clicked, this, [this](){ ui->buttonGroup->setExclusive(true); ui->toolButton_filter->setChecked(false); ui->toolButton_sortUp->setChecked(false); ui->toolButton_sortDown->setChecked(true); this->sortedDown(m_index); }); connect(ui->toolButton_filter, &QToolButton::clicked, this, [this](){ ui->buttonGroup->setExclusive(true); ui->toolButton_filter->setChecked(true); ui->toolButton_sortUp->setChecked(false); ui->toolButton_sortDown->setChecked(false); auto zero = this->mapToGlobal(QPoint(ui->label_title->pos().x(), ui->label_title->pos().y())); m_pFilterDialog->move(zero.x(), zero.y() + this->height()); m_pFilterDialog->resize(this->size() + QSize(5, 0)); m_pFilterDialog->show(); }); connect(m_pFilterDialog, &FilterDialog::filter, this, [this](QString msg){ this->filter(m_index, msg); }); ui->widget_header->installEventFilter(this); ui->label_title->installEventFilter(this); ui->toolButton_filter->installEventFilter(this); ui->toolButton_sortUp->installEventFilter(this); ui->toolButton_sortDown->installEventFilter(this); } CustomHeaderView::~CustomHeaderView() { delete ui; if(m_pFilterDialog != nullptr){ delete m_pFilterDialog; m_pFilterDialog = nullptr; } } void CustomHeaderView::setTitle(QString text) { ui->label_title->setText(text); } QString CustomHeaderView::title() { return ui->label_title->text(); } void CustomHeaderView::setAlignment(Qt::Alignment align) { ui->label_title->setAlignment(align); } void CustomHeaderView::sortUpVisible(bool status) { ui->toolButton_sortUp->setVisible(status); } void CustomHeaderView::sortDownVisible(bool status) { ui->toolButton_sortDown->setVisible(status); } void CustomHeaderView::filterVisible(bool status) { ui->toolButton_filter->setVisible(status); } void CustomHeaderView::clearStatus() { ui->buttonGroup->setExclusive(false); ui->toolButton_filter->setChecked(false); ui->toolButton_sortUp->setChecked(false); ui->toolButton_sortDown->setChecked(false); } void CustomHeaderView::clearFilterStatus() { ui->buttonGroup->setExclusive(false); ui->toolButton_filter->setChecked(false); } QString CustomHeaderView::getFilterMsg() { return m_pFilterDialog->filterMsg(); } bool CustomHeaderView::eventFilter(QObject *obj, QEvent *event) { if(obj == ui->widget_header || obj == ui->label_title || obj == ui->toolButton_filter || obj == ui->toolButton_sortUp || obj == ui->toolButton_sortDown){ setCursor(Qt::ArrowCursor); } if(event->type() == QEvent::Leave && obj == ui->widget_header){ qDebug() << "Leave, header object name: " << obj->objectName(); ui->toolButton_filter->setVisible(false); ui->toolButton_sortUp->setVisible(false); ui->toolButton_sortDown->setVisible(false); }else if(event->type() == QEvent::Enter && obj == ui->widget_header){ qDebug() << "Enter, header object name: " << obj->objectName(); ui->toolButton_filter->setVisible(true); ui->toolButton_sortUp->setVisible(true); ui->toolButton_sortDown->setVisible(true); } return QWidget::eventFilter(obj, event); }
4,798
C++
.cpp
134
30.955224
102
0.68863
BeiChenYx/FramelessWindow
33
21
0
GPL-3.0
9/20/2024, 10:45:00 PM (Europe/Amsterdam)
false
false
false
false
true
false
true
false
1,539,796
framelesswidget.cpp
BeiChenYx_FramelessWindow/FramelessWindow/FrameLessWidget/framelesswidget.cpp
#include <QDesktopWidget> #include <QTranslator> #include <QGraphicsDropShadowEffect> #include <QScreen> #include "framelesswidget.h" #include "ui_framelesswidget.h" #include <QDebug> FramelessWidget::FramelessWidget(bool isMax, bool isFull, QWidget *parent) : FramelessWidget(parent) { m_isMax = isMax; m_isFull = isMax ? isFull : false; ui->toolButton_max->setVisible(m_isMax); } FramelessWidget::FramelessWidget(QWidget *parent) : QWidget(parent), ui(new Ui::FramelessWidget) { ui->setupUi(this); setWindowFlags(Qt::FramelessWindowHint | Qt::WindowSystemMenuHint); // append minimize button flag in case of windows, // for correct windows native handling of minimize function #if defined(Q_OS_WIN) setWindowFlags(windowFlags() | Qt::WindowMinimizeButtonHint); #endif setAttribute(Qt::WA_NoSystemBackground); setAttribute(Qt::WA_TranslucentBackground); ui->toolButton_restore->setVisible(false); ui->toolButton_full->setVisible(false); ui->toolButton_full_exit->setVisible(false); // shadow under window title text QGraphicsDropShadowEffect *textShadow = new QGraphicsDropShadowEffect; textShadow->setBlurRadius(4.0); textShadow->setColor(QColor(0, 0, 0)); textShadow->setOffset(0.0); ui->label_title->setGraphicsEffect(textShadow); this->styleWindow(true, true); QWidget::setWindowTitle(tr("FrameLessWidget")); QObject::connect(qApp, &QGuiApplication::applicationStateChanged, this, &FramelessWidget::on_applicationStateChanged); setMouseTracking(true); this->setWindowIcon(QIcon(":/images/icon.png")); QApplication::instance()->installEventFilter(this); } FramelessWidget::~FramelessWidget() { delete ui; } void FramelessWidget::setWindowTitle(const QString &text) { ui->label_title->setText(text); QWidget::setWindowTitle(text); } void FramelessWidget::setWindowIcon(const QIcon &ico) { ui->label_icon->setPixmap(ico.pixmap(24, 24)); // 能改变窗口任务栏的图标 // QWidget::setWindowIcon(ico); } void FramelessWidget::setContent(QWidget *w) { QHBoxLayout *pHlayout = new QHBoxLayout; pHlayout->addWidget(w); pHlayout->setMargin(0); ui->windowContent->setLayout(pHlayout); } void FramelessWidget::setLayout(QLayout *layout) { QWidget *pWidget = new QWidget(this); pWidget->setLayout(layout); pWidget->setContentsMargins(0, 0, 0, 0); setContent(pWidget); } void FramelessWidget::on_applicationStateChanged(Qt::ApplicationState state) { if (windowState().testFlag(Qt::WindowNoState)) { styleWindow(state == Qt::ApplicationActive, true); } else if (windowState().testFlag(Qt::WindowFullScreen)) { styleWindow(state == Qt::ApplicationActive, false); } } void FramelessWidget::on_toolButton_close_clicked() { this->close(); } void FramelessWidget::on_toolButton_max_clicked() { ui->toolButton_restore->setVisible(true); ui->toolButton_max->setVisible(false); if(m_isFull){ ui->toolButton_full->setVisible(true); } this->setWindowState(Qt::WindowMaximized); this->showMaximized(); this->styleWindow(true, false); this->update(); } void FramelessWidget::on_toolButton_restore_clicked() { ui->toolButton_restore->setVisible(false); ui->toolButton_max->setVisible(true); ui->toolButton_full->setVisible(false); setWindowState(Qt::WindowNoState); this->styleWindow(true, true); this->update(); } void FramelessWidget::on_toolButton_min_clicked() { this->showMinimized(); this->update(); } void FramelessWidget::on_toolButton_full_clicked() { ui->toolButton_restore->setVisible(false); ui->toolButton_max->setVisible(false); ui->toolButton_full->setVisible(false); ui->toolButton_min->setVisible(false); ui->toolButton_close->setVisible(false); ui->toolButton_full_exit->setVisible(true); // 设置了Qt::WA_TranslucentBackground属性后无法直接调用showFullScreen接口实现全屏 m_fullPoint = QPoint(this->geometry().x(), this->geometry().y()); m_fullSize = QSize(this->geometry().width(), this->geometry().height()); QDesktopWidget *deskdop = QApplication::desktop(); this->move(0, 0); this->resize(deskdop->width(), deskdop->height()); this->setWindowState(Qt::WindowFullScreen); this->update(); } void FramelessWidget::on_toolButton_full_exit_clicked() { ui->toolButton_restore->setVisible(true); ui->toolButton_max->setVisible(false); ui->toolButton_full->setVisible(true); ui->toolButton_min->setVisible(true); ui->toolButton_close->setVisible(true); ui->toolButton_full_exit->setVisible(false); this->move(m_fullPoint); this->resize(m_fullSize); this->setWindowState(Qt::WindowMaximized); this->update(); } void FramelessWidget::styleWindow(bool bActive, bool bNoState) { auto setShadow = [this](QColor color){ #if defined(Q_OS_WIN) this->layout()->setMargin(15); #else this->layout()->setMargin(0); #endif QGraphicsEffect *oldShadow = ui->windowFrame->graphicsEffect(); if (oldShadow){delete oldShadow;} QGraphicsDropShadowEffect *windowShadow = new QGraphicsDropShadowEffect; windowShadow->setBlurRadius(9.0); windowShadow->setColor(color); windowShadow->setOffset(0); ui->windowFrame->setGraphicsEffect(windowShadow); }; auto clearShadow = [this](){ this->layout()->setMargin(0); QGraphicsEffect *oldShadow = ui->windowFrame->graphicsEffect(); if (oldShadow) delete oldShadow; ui->windowFrame->setGraphicsEffect(nullptr); }; auto color = palette().color(bActive ? QPalette::Highlight : QPalette::Shadow); if(bNoState){ setShadow(color); }else{ clearShadow(); } } bool FramelessWidget::eventFilter(QObject *obj, QEvent *event) { // check mouse move event when mouse is moved on any object if (event->type() == QEvent::MouseMove) { if (isMaximized() || isFullScreen()) { return QWidget::eventFilter(obj, event); } QMouseEvent *pMouse = dynamic_cast<QMouseEvent *>(event); if (pMouse) { checkBorderDragging(pMouse); if(obj == ui->windowTitlebar && m_bMousePressedTitle){ move(m_wndPos + (pMouse->globalPos() - m_mousePos)); } } } // press is triggered only on frame window else if (event->type() == QEvent::MouseButtonPress && obj == this) { QMouseEvent *pMouse = dynamic_cast<QMouseEvent *>(event); if (pMouse) { mousePressEvent(pMouse); } } else if(event->type() == QEvent::MouseButtonPress && obj == ui->windowTitlebar){ QMouseEvent *pMouse = dynamic_cast<QMouseEvent *>(event); if (pMouse) { this->m_bMousePressedTitle = true; this->m_mousePos = pMouse->globalPos(); this->m_wndPos = this->pos(); } } else if (event->type() == QEvent::MouseButtonRelease && obj == this) { if (m_bMousePressed) { QMouseEvent *pMouse = dynamic_cast<QMouseEvent *>(event); if (pMouse) { mouseReleaseEvent(pMouse); } } } else if(event->type() == QEvent::MouseButtonRelease && obj == ui->windowTitlebar){ m_bMousePressedTitle = false; } else if(event->type() == QEvent::MouseButtonDblClick && obj == ui->windowTitlebar){ if(windowState().testFlag(Qt::WindowNoState) && m_isMax){ this->on_toolButton_max_clicked(); }else if(windowState().testFlag(Qt::WindowFullScreen)){ this->on_toolButton_full_exit_clicked(); }else if(windowState().testFlag(Qt::WindowMaximized)){ this->on_toolButton_restore_clicked(); } } return QWidget::eventFilter(obj, event); } // pos in global virtual desktop coordinates bool FramelessWidget::leftBorderHit(const QPoint &pos) { const QRect &rect = this->geometry(); if (pos.x() >= rect.x() && pos.x() <= rect.x() + CONST_DRAG_BORDER_SIZE) { return true; } return false; } bool FramelessWidget::rightBorderHit(const QPoint &pos) { const QRect &rect = this->geometry(); int tmp = rect.x() + rect.width(); if (pos.x() <= tmp && pos.x() >= (tmp - CONST_DRAG_BORDER_SIZE)) { return true; } return false; } bool FramelessWidget::topBorderHit(const QPoint &pos) { const QRect &rect = this->geometry(); if (pos.y() >= rect.y() && pos.y() <= rect.y() + CONST_DRAG_BORDER_SIZE) { return true; } return false; } bool FramelessWidget::bottomBorderHit(const QPoint &pos) { const QRect &rect = this->geometry(); int tmp = rect.y() + rect.height(); if (pos.y() <= tmp && pos.y() >= (tmp - CONST_DRAG_BORDER_SIZE)) { return true; } return false; } void FramelessWidget::mousePressEvent(QMouseEvent *event) { if (isMaximized()) { return; } m_bMousePressed = true; m_StartGeometry = this->geometry(); QPoint globalMousePos = mapToGlobal(QPoint(event->x(), event->y())); if (leftBorderHit(globalMousePos) && topBorderHit(globalMousePos)) { m_bDragTop = true; m_bDragLeft = true; setCursor(Qt::SizeFDiagCursor); } else if (rightBorderHit(globalMousePos) && topBorderHit(globalMousePos)) { m_bDragRight = true; m_bDragTop = true; setCursor(Qt::SizeBDiagCursor); } else if (leftBorderHit(globalMousePos) && bottomBorderHit(globalMousePos)) { m_bDragLeft = true; m_bDragBottom = true; setCursor(Qt::SizeBDiagCursor); } else if(rightBorderHit(globalMousePos) && bottomBorderHit(globalMousePos)){ m_bDragBottom = true; m_bDragRight = true; setCursor(Qt::SizeFDiagCursor); } else { if (topBorderHit(globalMousePos)) { m_bDragTop = true; setCursor(Qt::SizeVerCursor); } else if (leftBorderHit(globalMousePos)) { m_bDragLeft = true; setCursor(Qt::SizeHorCursor); } else if (rightBorderHit(globalMousePos)) { m_bDragRight = true; setCursor(Qt::SizeHorCursor); } else if (bottomBorderHit(globalMousePos)) { m_bDragBottom = true; setCursor(Qt::SizeVerCursor); } } } void FramelessWidget::mouseReleaseEvent(QMouseEvent *event) { Q_UNUSED(event); if (isMaximized()) { return; } m_bMousePressed = false; bool bSwitchBackCursorNeeded = m_bDragTop || m_bDragLeft || m_bDragRight || m_bDragBottom; m_bDragTop = false; m_bDragLeft = false; m_bDragRight = false; m_bDragBottom = false; if (bSwitchBackCursorNeeded) { setCursor(Qt::ArrowCursor); } } void FramelessWidget::checkBorderDragging(QMouseEvent *event) { if (isMaximized() || isFullScreen()) { return; } QPoint globalMousePos = event->globalPos(); if (m_bMousePressed) { if (m_bDragTop && m_bDragRight) { int newHeight = m_StartGeometry.height() + m_StartGeometry.y() - globalMousePos.y(); int newWidth = globalMousePos.x() - m_StartGeometry.x(); if (newHeight > this->minimumHeight() && newWidth > this->minimumWidth()) { setGeometry(m_StartGeometry.x(), globalMousePos.y(), newWidth, newHeight); } }else if (m_bDragTop && m_bDragLeft) { int newHeight = m_StartGeometry.height() + m_StartGeometry.y() - globalMousePos.y(); int newWidth = m_StartGeometry.width() + m_StartGeometry.x() - globalMousePos.x(); if (newHeight > this->minimumHeight() && newWidth > this->minimumWidth()) { setGeometry(globalMousePos.x(), globalMousePos.y(), newWidth, newHeight); } }else if (m_bDragBottom && m_bDragLeft) { int newHeight = globalMousePos.y() - m_StartGeometry.y(); int newWidth = m_StartGeometry.width() + m_StartGeometry.x() - globalMousePos.x(); if (newHeight > this->minimumHeight() && newWidth > this->minimumWidth()) { setGeometry(globalMousePos.x(), m_StartGeometry.y(), newWidth, newHeight); } } else if (m_bDragBottom && m_bDragRight) { int newHeight = globalMousePos.y() - m_StartGeometry.y(); int newWidth = globalMousePos.x() - m_StartGeometry.x(); if (newHeight > this->minimumHeight() && newWidth > this->minimumWidth()) { resize(newWidth, newHeight); } } else if (m_bDragTop) { int newHeight = m_StartGeometry.height() + m_StartGeometry.y() - globalMousePos.y(); if (newHeight > this->minimumHeight()) { setGeometry(m_StartGeometry.x(), globalMousePos.y(), m_StartGeometry.width(),newHeight); } } else if (m_bDragLeft) { int newWidth = m_StartGeometry.width() + m_StartGeometry.x() - globalMousePos.x(); if (newWidth > this->minimumWidth()) { setGeometry(globalMousePos.x(), m_StartGeometry.y(), newWidth, m_StartGeometry.height()); } } else if (m_bDragRight) { int newWidth = globalMousePos.x() - m_StartGeometry.x(); if (newWidth > this->minimumWidth()) { resize(newWidth, m_StartGeometry.height()); } } else if (m_bDragBottom) { int newHeight = globalMousePos.y() - m_StartGeometry.y(); if (newHeight > this->minimumHeight()) { resize(m_StartGeometry.width(), newHeight); } } } else { // no mouse pressed if (leftBorderHit(globalMousePos) && topBorderHit(globalMousePos)) { setCursor(Qt::SizeFDiagCursor); } else if (rightBorderHit(globalMousePos) && topBorderHit(globalMousePos)) { setCursor(Qt::SizeBDiagCursor); } else if (leftBorderHit(globalMousePos) && bottomBorderHit(globalMousePos)) { setCursor(Qt::SizeBDiagCursor); } else if(rightBorderHit(globalMousePos) && bottomBorderHit(globalMousePos)){ setCursor(Qt::SizeFDiagCursor); } else { if (topBorderHit(globalMousePos)) { setCursor(Qt::SizeVerCursor); } else if (leftBorderHit(globalMousePos)) { setCursor(Qt::SizeHorCursor); } else if (rightBorderHit(globalMousePos)) { setCursor(Qt::SizeHorCursor); } else if (bottomBorderHit(globalMousePos)) { setCursor(Qt::SizeVerCursor); } else { m_bDragTop = false; m_bDragLeft = false; m_bDragRight = false; m_bDragBottom = false; setCursor(Qt::ArrowCursor); } } } }
14,866
C++
.cpp
371
32.881402
105
0.645891
BeiChenYx/FramelessWindow
33
21
0
GPL-3.0
9/20/2024, 10:45:00 PM (Europe/Amsterdam)
false
false
false
false
false
false
true
false
1,539,798
mainwindow.h
BeiChenYx_FramelessWindow/FramelessWindow/mainwindow.h
#ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QMainWindow> #include <QtWidgets> #include <QStandardItemModel> #include <QMenu> #include <QAction> #include <QListView> #include <QTreeView> #include "CustomModelView/custommodel.h" #include "CustomModelView/customlistview.h" #include "CustomModelView/customtableview.h" #include "CustomModelView/customtreeview.h" #include "basicwidget.h" namespace Ui { class MainWindow; } class VersionInfoWidget : public QWidget { Q_OBJECT public: explicit VersionInfoWidget(QString version="V1.0.0", QWidget *parent = nullptr) : QWidget(parent){ this->setObjectName("customStatusBar"); QHBoxLayout *hLayout = new QHBoxLayout; QLabel *label = new QLabel(version, this); hLayout->addWidget(label); hLayout->setContentsMargins(0, 0, 0, 0); this->setLayout(hLayout); this->setStyleSheet("#customStatusBar QLabel{color: #FFFFFF;}"); } }; class MainWindow : public QMainWindow { Q_OBJECT public: // 框架 --start explicit MainWindow(QWidget *parent = nullptr); ~MainWindow(); void initConnetion(); void initUi(); /* 添加自定义的页面到QStackWidget中,并添加左导航栏按钮 * @name: 左导航按钮需要显示的名字 * @widget: 需要插入的页面 */ void addNavStackWidget(QString objectName, QString text, QWidget *widget, QIcon ico=QIcon()); // 向导航栏中添加水平分割线 void addNavHLine(); // 框架 --end private slots: // 框架 --start void on_buttonClickedLeftNav(QAbstractButton *btn); // 框架 --end private: // 框架 --start Ui::MainWindow *ui; QButtonGroup *m_pBtnGroupLeftNav; QVector<QToolButton*> m_pTBtnLeftNavVector; VersionInfoWidget *m_pVersionWidget; // 框架 --end CustomModel m_model; CustomTableView *m_pCustomTableView; QListView *m_pListView; QTreeView *m_pTreeView; // 菜单跳转 QAction *m_pToListView; QAction *m_pToTreeView; QAction *m_pToTableView; QMenu *m_pViewMenu; QMap<QAction*, QString> m_viewBtnMap; BasicWidget *m_pBasicWidget; }; #endif // MAINWINDOW_H
2,206
C++
.h
73
24.232877
97
0.708669
BeiChenYx/FramelessWindow
33
21
0
GPL-3.0
9/20/2024, 10:45:00 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,539,799
customtableview.h
BeiChenYx_FramelessWindow/FramelessWindow/CustomModelView/customtableview.h
#ifndef CUSTOMTABLE_H #define CUSTOMTABLE_H #include <QObject> #include <QWidget> #include <QTableView> #include <QHeaderView> #include <QModelIndex> #include <QSortFilterProxyModel> #include "CustomModelView/customhorizontalheaderview.h" // 1. 先实现正常的视图/模型显示 // 2. 再实现定制表头 // 3. 处理选择 // 4. 实现右键菜单 // 5. 在不同的View之间交互跳转, QListView/QTreeView/QTableView /* 自定义TableView, 用来在表头进行过滤筛选及排序等操作 */ class CustomTableView : public QTableView { Q_OBJECT public: explicit CustomTableView(QWidget *parent = nullptr); void setModel(QAbstractItemModel *model) override; private: void initConnect(); private: CustomHorizontalHeaderView *m_pHHeaderView; QSortFilterProxyModel *m_pSortFilterModel; }; #endif // CUSTOMTABLE_H
854
C++
.h
28
24.178571
56
0.794579
BeiChenYx/FramelessWindow
33
21
0
GPL-3.0
9/20/2024, 10:45:00 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,539,801
customheaderview.h
BeiChenYx_FramelessWindow/FramelessWindow/CustomModelView/customheaderview.h
#ifndef CUSTOMHEADERVIEW_H #define CUSTOMHEADERVIEW_H #include <QWidget> #include <QPushButton> #include <QLineEdit> namespace Ui { class CustomHeaderView; } class FilterDialog; /* * 自定义横向表头内容框 */ class CustomHeaderView : public QWidget { Q_OBJECT public: explicit CustomHeaderView(int index, QWidget *parent = nullptr); ~CustomHeaderView(); void setTitle(QString text); QString title(); void setAlignment(Qt::Alignment align); void sortUpVisible(bool status); void sortDownVisible(bool status); void filterVisible(bool status); void clearStatus(); void clearFilterStatus(); QString getFilterMsg(); signals: void sortedUp(int index); void sortedDown(int index); void filter(int index, QString msg); protected: virtual bool eventFilter(QObject *obj, QEvent *event); private: Ui::CustomHeaderView *ui; // 索引 int m_index = 0; FilterDialog *m_pFilterDialog; }; class FilterDialog : public QWidget { Q_OBJECT public: FilterDialog(QWidget *parent = nullptr); QString filterMsg(){ return this->m_pLineEdit->text().trimmed(); } signals: void filter(QString msg); private: QPushButton *m_pBtn; QLineEdit *m_pLineEdit; }; #endif // CUSTOMHEADERVIEW_H
1,297
C++
.h
54
20.12963
68
0.73029
BeiChenYx/FramelessWindow
33
21
0
GPL-3.0
9/20/2024, 10:45:00 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,539,802
customhorizontalheaderview.h
BeiChenYx_FramelessWindow/FramelessWindow/CustomModelView/customhorizontalheaderview.h
#ifndef CUSTOMHORIZONTALHEADERVIEW_H #define CUSTOMHORIZONTALHEADERVIEW_H #include <QObject> #include <QHeaderView> #include <QPainter> #include "customheaderview.h" class CustomHorizontalHeaderView : public QHeaderView { Q_OBJECT public: explicit CustomHorizontalHeaderView(QWidget *parent = nullptr); virtual ~CustomHorizontalHeaderView() override; signals: void sortedUp(int index); void sortedDown(int index); void filter(int index, QString msg); public slots: protected: void paintSection(QPainter *painter, const QRect &rect, int logicalIndex) const override; void resizeEvent(QResizeEvent *event) override; void handleSectionMoved(int logical, int oldVisualIndex, int newVisualIndex); void handleSectionResized(int i, int oldSize, int newSize); void setModel(QAbstractItemModel *model) override; void headerDataChanged(Qt::Orientation orientation, int logicalFirst, int logicalLast); void fixSectionPositions(); private: QVector<CustomHeaderView*> m_pTableFilterList; }; #endif // CUSTOMHORIZONTALHEADERVIEW_H
1,081
C++
.h
29
34.068966
93
0.800766
BeiChenYx/FramelessWindow
33
21
0
GPL-3.0
9/20/2024, 10:45:00 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,539,806
framelesswidget.h
BeiChenYx_FramelessWindow/FramelessWindow/FrameLessWidget/framelesswidget.h
#ifndef FRAMELESSWIDGET_H #define FRAMELESSWIDGET_H #include <QWidget> #include <QMouseEvent> #include <QHBoxLayout> #include <QLayout> #include <QProgressBar> #include <QTimer> #include <QLabel> namespace Ui { class FramelessWidget; } // TODO: 完成Demo示例,尽可能多的添加控件的样式 class FramelessWidget : public QWidget { Q_OBJECT public: explicit FramelessWidget(QWidget *parent = nullptr); explicit FramelessWidget(bool isMax, bool isFull=true, QWidget *parent = nullptr); virtual ~FramelessWidget(); // 重载, title, ico, layou三个函数 void setWindowTitle(const QString &text); void setWindowIcon(const QIcon &ico); void setLayout(QLayout *layout); void setContent(QWidget *w); private slots: // 根据窗口状态改变窗口的阴影 void on_applicationStateChanged(Qt::ApplicationState state); void on_toolButton_close_clicked(); void on_toolButton_max_clicked(); void on_toolButton_restore_clicked(); void on_toolButton_min_clicked(); // 全屏进入和退出处理,在最大化才会显示全屏按钮 void on_toolButton_full_clicked(); void on_toolButton_full_exit_clicked(); // 绘制窗口阴影, bActive:窗口是否激活, bNoState: 正常状态 void styleWindow(bool bActive, bool bNoState); bool leftBorderHit(const QPoint &pos); bool rightBorderHit(const QPoint &pos); bool topBorderHit(const QPoint &pos); bool bottomBorderHit(const QPoint &pos); protected: virtual bool eventFilter(QObject *obj, QEvent *event); virtual void mousePressEvent(QMouseEvent *event); virtual void mouseReleaseEvent(QMouseEvent *event); virtual void checkBorderDragging(QMouseEvent *event); private: Ui::FramelessWidget *ui; QRect m_StartGeometry; const quint8 CONST_DRAG_BORDER_SIZE = 15; bool m_bMousePressed = false; bool m_bMousePressedTitle = false; bool m_bDragTop = false; bool m_bDragLeft = false; bool m_bDragRight = false; bool m_bDragBottom = false; QPoint m_mousePos; QPoint m_wndPos; // 全屏之前的窗口位置和尺寸 QPoint m_fullPoint; QSize m_fullSize; // 是否显示全屏按钮和最大化按钮 bool m_isFull = true; bool m_isMax = true; }; class CustomWarningBox : public FramelessWidget{ Q_OBJECT public: explicit CustomWarningBox(QString title, QString info, QWidget *parent=nullptr) : FramelessWidget(parent) { this->setWindowTitle(title); m_pInfo = new QLabel(info); m_pInfo->setStyleSheet("font-size: 24px; color: rgb(255, 170, 0);"); m_pInfo->setAlignment(Qt::AlignCenter); QHBoxLayout *pLayout = new QHBoxLayout(); pLayout->addWidget(m_pInfo); this->setLayout(pLayout); this->setWindowModality(Qt::ApplicationModal); this->resize(300, 100); } virtual ~CustomWarningBox(){} void setInfo(QString info){ m_pInfo->setText(info); } static void customWarningBox(QString title, QString info){ static CustomWarningBox handle(title, info); handle.setInfo(info); handle.setWindowTitle(title); handle.show(); } private: QLabel *m_pInfo; }; class CustomErrorBox : public FramelessWidget{ Q_OBJECT public: explicit CustomErrorBox(QString title, QString info, QWidget *parent=nullptr) : FramelessWidget(parent) { this->setWindowTitle(title); m_pInfo = new QLabel(info); m_pInfo->setStyleSheet("font-size: 24px; color: rgb(240, 0, 0);"); m_pInfo->setAlignment(Qt::AlignCenter); QHBoxLayout *pLayout = new QHBoxLayout(); pLayout->addWidget(m_pInfo); setLayout(pLayout); this->setWindowModality(Qt::ApplicationModal); this->resize(300, 100); } virtual ~CustomErrorBox(){} void setInfo(QString info){ m_pInfo->setText(info); } static void customErrorBox(QString title, QString info){ static CustomErrorBox handle(title, info); handle.setInfo(info); handle.setWindowTitle(title); handle.show(); } private: QLabel *m_pInfo; }; class CustomInfoBox : public FramelessWidget{ Q_OBJECT public: explicit CustomInfoBox(QString title, QString info, QWidget *parent=nullptr) : FramelessWidget(parent) { this->setWindowTitle(title); m_pInfo = new QLabel(info); m_pInfo->setStyleSheet("font-size: 24px; color: rgb(0, 0, 0);"); m_pInfo->setAlignment(Qt::AlignCenter); QHBoxLayout *pLayout = new QHBoxLayout(); pLayout->addWidget(m_pInfo); this->setLayout(pLayout); this->setWindowModality(Qt::ApplicationModal); this->resize(300, 100); } virtual ~CustomInfoBox(){} void setInfo(QString info){ m_pInfo->setText(info); } static void customInfoBox(QString title, QString info){ static CustomInfoBox handle(title, info); handle.setInfo(info); handle.setWindowTitle(title); handle.show(); } private: QLabel *m_pInfo; }; class CustomProgressbar: public FramelessWidget{ Q_OBJECT public: explicit CustomProgressbar(QString title, QString info, QWidget *parent=nullptr) : FramelessWidget(parent) { this->setWindowTitle(title); pPro = new QProgressBar; pInfo = new QLabel(info); QHBoxLayout *pLayout = new QHBoxLayout(); pLayout->addWidget(pInfo); pLayout->addWidget(pPro); this->setLayout(pLayout); this->setWindowModality(Qt::ApplicationModal); this->resize(300, 80); } virtual ~CustomProgressbar(){} public slots: void onSetValue(int value){ this->pPro->setValue(value); if(value == this->pPro->maximum()){ QTimer::singleShot(500, this, &CustomProgressbar::close); } } void onSetError(QString msg) { this->pInfo->setText(msg); } void onSetRange(int min, int max){ this->onSetValue(0); this->pPro->setRange(min, max); } private: QProgressBar *pPro; QLabel *pInfo; }; #endif // FRAMELESSWIDGET_H
6,185
C++
.h
188
26.196809
86
0.680803
BeiChenYx/FramelessWindow
33
21
0
GPL-3.0
9/20/2024, 10:45:00 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,539,807
ideiconprovider.cpp
emartisoft_IDE65XX/ideiconprovider.cpp
#include "ideiconprovider.h" IdeIconProvider::IdeIconProvider() : m_folder(QIcon(":/res/exticon/folder.png")), m_hdd(QIcon(":/res/exticon/hdd.png")), m_asm(QIcon(":/res/exticon/asm.png")), m_prg(QIcon(":/res/exticon/prg.png")), m_lib(QIcon(":/res/exticon/lib.png")), m_txt(QIcon(":/res/exticon/txt.png")), m_bin(QIcon(":/res/exticon/bin.png")), m_sid(QIcon(":/res/exticon/sid.png")), m_dbg(QIcon(":/res/exticon/dbg.png")), m_sym(QIcon(":/res/exticon/sym.png")), m_d64(QIcon(":/res/exticon/d64.png")), m_d71(QIcon(":/res/exticon/d71.png")), m_d81(QIcon(":/res/exticon/d81.png")), m_vs(QIcon(":/res/exticon/vs.png")), m_crt(QIcon(":/res/exticon/crt.png")), m_undefined(QIcon(":/res/exticon/undefined.png")) { } IdeIconProvider::~IdeIconProvider() { } QIcon IdeIconProvider::icon(const QFileInfo &info) const { if(info.isRoot()) { return m_hdd; // hdd } else if(info.isDir()) { return m_folder; // folder } else if(info.isFile()) { if((info.suffix()=="asm")||(info.suffix()=="s")||(info.suffix()=="inc")) return m_asm; // asm, s, inc if(info.suffix()=="prg") return m_prg; // prg if((info.suffix()=="lib")||(info.suffix()=="a")) return m_lib; // lib, a if(info.suffix()=="txt") return m_txt; // txt if(info.suffix()=="bin") return m_bin; // bin if(info.suffix()=="sid") return m_sid; // sid if(info.suffix()=="dbg") return m_dbg; // dbg if(info.suffix()=="sym") return m_sym; // sym if(info.suffix()=="d64") return m_d64; // d64 if(info.suffix()=="d71") return m_d71; // d71 if(info.suffix()=="d81") return m_d81; // d81 if(info.suffix()=="vs") return m_vs; // vs if(info.suffix()=="crt") return m_crt; // crt } return m_undefined; // undefined or others }
1,959
C++
.cpp
51
31.784314
111
0.556435
emartisoft/IDE65XX
33
7
4
GPL-3.0
9/20/2024, 10:45:00 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,539,808
customstyle.cpp
emartisoft_IDE65XX/customstyle.cpp
#include "customstyle.h" #include "common.h" #include <QComboBox> #include <QPainter> #include <QPushButton> #include <QStyleFactory> #include <QDir> CustomStyle::CustomStyle() : QProxyStyle(QStyleFactory::create("fusion")), settings(Common::appConfigDir()+"/settings.ini", QSettings::IniFormat) { setObjectName("CustomStyle"); customPaletteColors[0] = settings.value("CustomBase", QColor(0xc7, 0xc9, 0xcd)).value<QColor>(); customPaletteColors[1] = settings.value("CustomBackground", QColor(0xf0, 0xf0, 0xf0)).value<QColor>(); customPaletteColors[2] = settings.value("CustomHighlights", QColor(0xb1, 0xb1, 0xb1)).value<QColor>(); customPaletteColors[3] = settings.value("CustomBrightText", QColor(255,255,255)).value<QColor>(); customPaletteColors[4] = settings.value("CustomDisable", QColor(64,64,64)).value<QColor>(); customTexturesBackgroundImg = settings.value("CustomBackgroundTexture", ":/res/style/commodore_background.png").toString(); customTexturesButtonImg = settings.value("CustomButtonTexture", ":/res/style/commodore_button.png").toString(); } QPalette CustomStyle::standardPalette() const { if (!m_standardPalette.isBrushSet(QPalette::Disabled, QPalette::Mid)) { QImage buttonImage(customTexturesButtonImg); QImage backgroundImage(customTexturesBackgroundImg); QPalette palette(customPaletteColors[0]); QImage midImage = buttonImage.convertToFormat(QImage::Format_RGB32); QPainter painter; painter.begin(&midImage); painter.setPen(Qt::NoPen); painter.fillRect(midImage.rect(), QColor(0x0, 0x0, 0x0, 0x10)); painter.end(); QPainter painterback; painterback.begin(&backgroundImage); painterback.setPen(Qt::NoPen); painterback.fillRect(backgroundImage.rect(), QColor(0x0, 0x0, 0x0, 0x10)); painterback.end(); setTexture(palette, QPalette::Button, buttonImage); setTexture(palette, QPalette::Mid, midImage); setTexture(palette, QPalette::Window, backgroundImage); palette.setBrush(QPalette::BrightText, customPaletteColors[3]); palette.setBrush(QPalette::Base, customPaletteColors[1]); palette.setBrush(QPalette::Highlight, customPaletteColors[2]); QBrush brush = palette.windowText(); brush.setColor(customPaletteColors[4]); palette.setBrush(QPalette::Disabled, QPalette::WindowText, brush); palette.setBrush(QPalette::Disabled, QPalette::Text, brush); palette.setBrush(QPalette::Disabled, QPalette::ButtonText, brush); palette.setBrush(QPalette::Disabled, QPalette::Base, brush); palette.setBrush(QPalette::Disabled, QPalette::Button, brush); palette.setBrush(QPalette::Disabled, QPalette::Mid, brush); m_standardPalette = palette; } return m_standardPalette; } void CustomStyle::polish(QWidget *widget) { if (qobject_cast<QPushButton *>(widget) || qobject_cast<QComboBox *>(widget) ) widget->setAttribute(Qt::WA_Hover, true); } void CustomStyle::unpolish(QWidget *widget) { if (qobject_cast<QPushButton *>(widget) || qobject_cast<QComboBox *>(widget) ) widget->setAttribute(Qt::WA_Hover, false); } void CustomStyle::drawPrimitive(QStyle::PrimitiveElement element, const QStyleOption *option, QPainter *painter, const QWidget *widget) const { switch (element) { case PE_PanelButtonCommand: { int delta = (option->state & State_MouseOver) ? 64 : 0; QColor slightlyOpaqueBlack(0, 0, 0xf0, 255); QColor semiTransparentWhite(255, 255, 255, 127 + delta); QColor semiTransparentBlack(0, 0, 0, 127 - delta); int x, y, width, height; option->rect.getRect(&x, &y, &width, &height); QPainterPath roundRect = roundRectPath(option->rect); int radius = qMin(width, height) / 2; QBrush brush; bool darker; const QStyleOptionButton *buttonOption = qstyleoption_cast<const QStyleOptionButton *>(option); if (buttonOption && (buttonOption->features & QStyleOptionButton::Flat)) { brush = option->palette.window(); darker = (option->state & (State_Sunken | State_On)); } else { if (option->state & (State_Sunken | State_On)) { brush = option->palette.mid(); darker = !(option->state & State_Sunken); } else { brush = option->palette.button(); darker = false; } } painter->save(); painter->setRenderHint(QPainter::Antialiasing, true); painter->fillPath(roundRect, brush); if (darker) painter->fillPath(roundRect, slightlyOpaqueBlack); int penWidth; if (radius < 10) penWidth = 3; else if (radius < 20) penWidth = 5; else penWidth = 7; QPen topPen(semiTransparentWhite, penWidth); QPen bottomPen(semiTransparentBlack, penWidth); if (option->state & (State_Sunken | State_On)) qSwap(topPen, bottomPen); int x1 = x; int x2 = x + radius; int x3 = x + width - radius; int x4 = x + width; if (option->direction == Qt::RightToLeft) { qSwap(x1, x4); qSwap(x2, x3); } QPolygon topHalf; topHalf << QPoint(x1, y) << QPoint(x4, y) << QPoint(x3, y + radius) << QPoint(x2, y + height - radius) << QPoint(x1, y + height); painter->setClipPath(roundRect); painter->setClipRegion(topHalf, Qt::IntersectClip); painter->setPen(topPen); painter->drawPath(roundRect); QPolygon bottomHalf = topHalf; bottomHalf[0] = QPoint(x4, y + height); painter->setClipPath(roundRect); painter->setClipRegion(bottomHalf, Qt::IntersectClip); painter->setPen(bottomPen); painter->drawPath(roundRect); painter->setPen(option->palette.windowText().color()); painter->setClipping(false); painter->drawPath(roundRect); painter->restore(); } break; default: QProxyStyle::drawPrimitive(element, option, painter, widget); } } void CustomStyle::drawControl(QStyle::ControlElement control, const QStyleOption *option, QPainter *painter, const QWidget *widget) const { switch (control) { case CE_PushButtonLabel: { QStyleOptionButton myButtonOption; const QStyleOptionButton *buttonOption = qstyleoption_cast<const QStyleOptionButton *>(option); if (buttonOption) { myButtonOption = *buttonOption; if (myButtonOption.palette.currentColorGroup() != QPalette::Disabled) { if (myButtonOption.state & (State_Sunken | State_On)) { myButtonOption.palette.setBrush(QPalette::ButtonText, myButtonOption.palette.brightText()); } } } QProxyStyle::drawControl(control, &myButtonOption, painter, widget); } break; default: QProxyStyle::drawControl(control, option, painter, widget); } } void CustomStyle::setTexture(QPalette &palette, QPalette::ColorRole role, const QImage &image) { for (int i = 0; i < QPalette::NColorGroups; ++i) { QBrush brush(image); brush.setColor(palette.brush(QPalette::ColorGroup(i), role).color()); palette.setBrush(QPalette::ColorGroup(i), role, brush); } } QPainterPath CustomStyle::roundRectPath(const QRect &rect) { int x1, y1, x2, y2; rect.getCoords(&x1, &y1, &x2, &y2); QPainterPath path; path.moveTo(x2, y1 ); path.lineTo(x1, y1); path.lineTo(x1, y2); path.lineTo(x2, y2); path.closeSubpath(); return path; }
8,340
C++
.cpp
195
32.738462
141
0.613356
emartisoft/IDE65XX
33
7
4
GPL-3.0
9/20/2024, 10:45:00 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,539,809
highlighter.cpp
emartisoft_IDE65XX/highlighter.cpp
#include "highlighter.h" #include "common.h" Highlighter::Highlighter(QTextDocument *parent) : QSyntaxHighlighter(parent) { QSettings settings(Common::appConfigDir()+"/settings.ini", QSettings::IniFormat); // application style bool styleIsCustom = settings.value("ApplicationStyle").toInt() == 5; HighlightingRule rule; cmdFormat.setForeground((styleIsCustom)? settings.value("CustomOpcode", QColor(0x61, 0x61, 0xd0)).value<QColor>() : QColor(0x61, 0x61, 0xd0)); cmdFormat.setFontWeight(QFont::Bold); const QString cmdPatterns[] = { // standart 6502 mnemonics QStringLiteral("\\badc\\b"), QStringLiteral("\\band\\b"), QStringLiteral("\\basl\\b"), QStringLiteral("\\bbcc\\b"), QStringLiteral("\\bbcs\\b"), QStringLiteral("\\bbeq\\b"), QStringLiteral("\\bbit\\b"), QStringLiteral("\\bbmi\\b"), QStringLiteral("\\bbne\\b"), QStringLiteral("\\bbpl\\b"), QStringLiteral("\\bbrk\\b"), QStringLiteral("\\bbvc\\b"), QStringLiteral("\\bbvs\\b"), QStringLiteral("\\bclc\\b"), QStringLiteral("\\bcld\\b"), QStringLiteral("\\bcli\\b"), QStringLiteral("\\bclv\\b"), QStringLiteral("\\bcmp\\b"), QStringLiteral("\\bcpx\\b"), QStringLiteral("\\bcpy\\b"), QStringLiteral("\\bdec\\b"), QStringLiteral("\\bdex\\b"), QStringLiteral("\\bdey\\b"), QStringLiteral("\\beor\\b"), QStringLiteral("\\binc\\b"), QStringLiteral("\\binx\\b"), QStringLiteral("\\biny\\b"), QStringLiteral("\\bjmp\\b"), QStringLiteral("\\bjsr\\b"), QStringLiteral("\\blda\\b"), QStringLiteral("\\bldx\\b"), QStringLiteral("\\bldy\\b"), QStringLiteral("\\blsr\\b"), QStringLiteral("\\bnop\\b"), QStringLiteral("\\bora\\b"), QStringLiteral("\\bpha\\b"), QStringLiteral("\\bphp\\b"), QStringLiteral("\\bpla\\b"), QStringLiteral("\\bplp\\b"), QStringLiteral("\\brol\\b"), QStringLiteral("\\bror\\b"), QStringLiteral("\\brti\\b"), QStringLiteral("\\brts\\b"), QStringLiteral("\\bsbc\\b"), QStringLiteral("\\bsec\\b"), QStringLiteral("\\bsed\\b"), QStringLiteral("\\bsei\\b"), QStringLiteral("\\bsta\\b"), QStringLiteral("\\bstx\\b"), QStringLiteral("\\bsty\\b"), QStringLiteral("\\btax\\b"), QStringLiteral("\\btay\\b"), QStringLiteral("\\btsx\\b"), QStringLiteral("\\btxa\\b"), QStringLiteral("\\btxs\\b"), QStringLiteral("\\btya\\b"), // illegal 6502 mnemonics QStringLiteral("\\bahx\\b"), QStringLiteral("\\balr\\b"), QStringLiteral("\\banc\\b"), QStringLiteral("\\banc2\\b"), QStringLiteral("\\barr\\b"), QStringLiteral("\\baxs\\b"), QStringLiteral("\\bdcp\\b"), QStringLiteral("\\bisc\\b"), QStringLiteral("\\blas\\b"), QStringLiteral("\\blax\\b"), QStringLiteral("\\brla\\b"), QStringLiteral("\\brra\\b"), QStringLiteral("\\bsax\\b"), QStringLiteral("\\bsbc2\\b"), QStringLiteral("\\bshx\\b"), QStringLiteral("\\bshy\\b"), QStringLiteral("\\bslo\\b"), QStringLiteral("\\bsre\\b"), QStringLiteral("\\btas\\b"), QStringLiteral("\\bxaa\\b"), QStringLiteral("\\bsbx\\b"), QStringLiteral("\\bsha\\b"), // dtv mnemonics QStringLiteral("\\bbra\\b"), QStringLiteral("\\bsac\\b"), QStringLiteral("\\bsir\\b"), // 65c02 mnemonics QStringLiteral("\\bbbr0\\b"), QStringLiteral("\\bbbr1\\b"), QStringLiteral("\\bbbr2\\b"), QStringLiteral("\\bbbr3\\b"), QStringLiteral("\\bbbr4\\b"), QStringLiteral("\\bbbr5\\b"), QStringLiteral("\\bbbr6\\b"), QStringLiteral("\\bbbr7\\b"), QStringLiteral("\\bbbs0\\b"), QStringLiteral("\\bbbs1\\b"), QStringLiteral("\\bbbs2\\b"), QStringLiteral("\\bbbs3\\b"), QStringLiteral("\\bbbs4\\b"), QStringLiteral("\\bbbs5\\b"), QStringLiteral("\\bbbs6\\b"), QStringLiteral("\\bbbs7\\b"), QStringLiteral("\\bphx\\b"), QStringLiteral("\\bphy\\b"), QStringLiteral("\\bplx\\b"), QStringLiteral("\\bply\\b"), QStringLiteral("\\brmb0\\b"), QStringLiteral("\\brmb1\\b"), QStringLiteral("\\brmb2\\b"), QStringLiteral("\\brmb3\\b"), QStringLiteral("\\brmb4\\b"), QStringLiteral("\\brmb5\\b"), QStringLiteral("\\brmb6\\b"), QStringLiteral("\\brmb7\\b"), QStringLiteral("\\bsmb0\\b"), QStringLiteral("\\bsmb1\\b"), QStringLiteral("\\bsmb2\\b"), QStringLiteral("\\bsmb3\\b"), QStringLiteral("\\bsmb4\\b"), QStringLiteral("\\bsmb5\\b"), QStringLiteral("\\bsmb6\\b"), QStringLiteral("\\bsmb7\\b"), QStringLiteral("\\bstp\\b"), QStringLiteral("\\bstz\\b"), QStringLiteral("\\btrb\\b"), QStringLiteral("\\btsb\\b"), QStringLiteral("\\bwai\\b") }; for (const QString &patternCmd : cmdPatterns) { rule.pattern = QRegularExpression(patternCmd, QRegularExpression::CaseInsensitiveOption); rule.format = cmdFormat; highlightingRules.append(rule); } // number numberFormat.setForeground((styleIsCustom)? settings.value("CustomNumber", QColor(0x00, 0x80, 0x80)).value<QColor>() : Qt::darkCyan); rule.pattern = QRegularExpression(QStringLiteral("(?:\\$[0-9a-fA-F]*)|(?:\\#\\$[0-9a-fA-F]*)|(?:\\#\\%[01]*)|(?:\\%[01]*)|(?:\\#[0-9]*)|(?:\\ [0-9]*)|(?:\\([0-9]*\\))")); rule.format = numberFormat; highlightingRules.append(rule); // end of number // function functionFormat.setFontItalic(true); functionFormat.setForeground((styleIsCustom)? settings.value("CustomFunction", QColor(0xaf, 0x64, 0x00)).value<QColor>() : QColor(0xaf, 0x64, 0x00)); functionFormat.setFontWeight(QFont::Bold); rule.pattern = QRegularExpression(QStringLiteral("\\b[A-Za-z0-9_]+(?=\\()")); rule.format = functionFormat; highlightingRules.append(rule); // end of function // label labelFormat.setFontWeight(QFont::ExtraBold); labelFormat.setFontItalic(true); labelFormat.setForeground((styleIsCustom)? settings.value("CustomLabel", QColor(0xc3, 0x34, 0x34)).value<QColor>() : QColor(0xc3, 0x34, 0x34)); rule.pattern = QRegularExpression(QStringLiteral("\\S+:")); rule.format = labelFormat; highlightingRules.append(rule); // end of label // assembler Directives assemblerDirectiveFormat.setForeground((styleIsCustom)? settings.value("CustomAssemblerDir", QColor(0xaf, 0x64, 0x00)).value<QColor>() : QColor(0xaf, 0x64, 0x00)); assemblerDirectiveFormat.setFontItalic(true); assemblerDirectiveFormat.setFontWeight(QFont::Bold); QStringList assemblerDirectivePatterns; assemblerDirectivePatterns <<"\\.function" <<"\\.return" <<"\\.for" <<"\\.print" <<"\\.var" <<"\\.fill" <<"\\.byte" <<"\\.text" <<"\\.label" <<"\\.eval" <<"\\.align" <<"\\.assert" <<"\\.asserterror" <<"\\.break" <<"\\.by" <<"\\.const" <<"\\.cpu" <<"\\.define" <<"\\.disk" <<"\\.dw" <<"\\.dword" <<"\\.encoding" <<"\\.enum" <<"\\.error" <<"\\.errorif" <<"\\.file" <<"\\.filemodify" <<"\\.filenamespace" <<"\\.fillword" <<"\\.if" <<"\\.import binary" <<"\\.import c64" <<"\\.import source" <<"\\.import text" <<"\\.importonce" <<"\\.lohifill" <<"\\.macro" <<"\\.memblock" <<"\\.modify" <<"\\.namespace" <<"\\.pc" <<"\\.plugin" <<"\\.printnow" <<"\\.pseudopc" <<"\\.pseudocommand" <<"\\.segment" <<"\\.segmentdef" <<"\\.segmentout" <<"\\.struct" <<"\\.te" <<"\\.watch" <<"\\.while" <<"\\.wo" <<"\\.word" <<"\\.zp"; for (const QString &patternassemblerDirective : assemblerDirectivePatterns) { rule.pattern = QRegularExpression(patternassemblerDirective); rule.format = assemblerDirectiveFormat; highlightingRules.append(rule); } // end of assembler Directives // preprocessor Directives preprocessorDirectiveFormat.setForeground((styleIsCustom)? settings.value("CustomPreprocessorDir", QColor(0x00, 0x80, 0x00)).value<QColor>() : Qt::darkGreen); preprocessorDirectiveFormat.setFontWeight(QFont::Bold); const QString preprocessorDirectivePatterns[] = { QStringLiteral("#if [^\n]*"), QStringLiteral("#endif"), QStringLiteral("#undef [^\n]*"), QStringLiteral("#else"), QStringLiteral("#elif [^\n]*"), QStringLiteral("#import"), QStringLiteral("#importif [^\n]*"), QStringLiteral("#importonce"), QStringLiteral("#define [^\n]*") }; for (const QString &patternPreprocessorDirectiveFormat : preprocessorDirectivePatterns) { rule.pattern = QRegularExpression(patternPreprocessorDirectiveFormat, QRegularExpression::CaseInsensitiveOption); rule.format = preprocessorDirectiveFormat; highlightingRules.append(rule); } // end of preprocessor Directives // comments singleLineCommentFormat.setForeground((styleIsCustom)? settings.value("CustomComment", QColor(0x80, 0x80, 0x80)).value<QColor>() : Qt::darkGray); rule.pattern = QRegularExpression(QStringLiteral("//[^\n]*")); rule.format = singleLineCommentFormat; highlightingRules.append(rule); multiLineCommentFormat.setForeground((styleIsCustom)? settings.value("CustomComment", QColor(0x80, 0x80, 0x80)).value<QColor>() : Qt::darkGray); commentStartExpression = QRegularExpression(QStringLiteral("/\\*")); commentEndExpression = QRegularExpression(QStringLiteral("\\*/")); // end of comments // quotation quotationFormat.setForeground((styleIsCustom)? settings.value("CustomQuotation", QColor(0x00, 0x80, 0x00)).value<QColor>() : Qt::darkGreen); rule.pattern = QRegularExpression(QStringLiteral("\".*\"")); rule.format = quotationFormat; highlightingRules.append(rule); rule.pattern = QRegularExpression(QStringLiteral("'.*'")); rule.format = quotationFormat; highlightingRules.append(rule); // end of quotation } void Highlighter::highlightBlock(const QString &text) { for (const HighlightingRule &rule : qAsConst(highlightingRules)) { QRegularExpressionMatchIterator matchIterator = rule.pattern.globalMatch(text); while (matchIterator.hasNext()) { QRegularExpressionMatch match = matchIterator.next(); setFormat(match.capturedStart(), match.capturedLength(), rule.format); } } setCurrentBlockState(0); int startIndex = 0; if (previousBlockState() != 1) startIndex = text.indexOf(commentStartExpression); while (startIndex >= 0) { QRegularExpressionMatch match = commentEndExpression.match(text, startIndex); int endIndex = match.capturedStart(); int commentLength = 0; if (endIndex == -1) { setCurrentBlockState(1); commentLength = text.length() - startIndex; } else { commentLength = endIndex - startIndex + match.capturedLength(); } setFormat(startIndex, commentLength, multiLineCommentFormat); startIndex = text.indexOf(commentStartExpression, startIndex + commentLength); } }
11,711
C++
.cpp
220
43.55
175
0.600908
emartisoft/IDE65XX
33
7
4
GPL-3.0
9/20/2024, 10:45:00 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,539,810
choosetopic.cpp
emartisoft_IDE65XX/choosetopic.cpp
#include "choosetopic.h" #include "ui_choosetopic.h" ChooseTopic::ChooseTopic(QWidget *parent) : QDialog(parent), ui(new Ui::ChooseTopic) { setWindowFlags(this->windowFlags() & ~Qt::WindowContextHelpButtonHint); ui->setupUi(this); } ChooseTopic::~ChooseTopic() { delete ui; } void ChooseTopic::setWord(QString word) { ui->lInfo->setText(ui->lInfo->text().replace("<text>", word)); if(word=="define") { ui->lwWords->addItems(QStringList()<<"#define | Preprocessor directive"<<".define | Assembler directive"); } else if (word=="import") { ui->lwWords->addItems(QStringList()<<"#import | Preprocessor directive"<<".import binary | Assembler directive" <<".import c64 | Assembler directive"<<".import source | Assembler directive" <<".import text | Assembler directive"); } else if (word=="if") { ui->lwWords->addItems(QStringList()<<"#if | Preprocessor directive"<<".if | Assembler directive"); } else if (word=="importonce") { ui->lwWords->addItems(QStringList()<<"#importonce | Preprocessor directive"<<".importonce | Assembler directive"); } ui->lwWords->setCurrentRow(0); } QString ChooseTopic::getWord() { QString result = ui->lwWords->currentItem()->text().remove("."); return result.split(" | ")[0]; }
1,417
C++
.cpp
38
30.763158
123
0.624362
emartisoft/IDE65XX
33
7
4
GPL-3.0
9/20/2024, 10:45:00 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,539,811
memoryviewer.cpp
emartisoft_IDE65XX/memoryviewer.cpp
#include "memoryviewer.h" MemoryViewer::MemoryViewer(QWidget *parent) : QWidget(parent), m_lineWidth(0x40), currentAddress(0x0000) { reset(); } void MemoryViewer::poke(int startAddress, int endAddress, QColor color) { for(int i=startAddress;i<endAddress;i++) { memory[i] = true; memoryColor[i] = color; } update(); } void MemoryViewer::reset() { for(int i=0;i<ADRCOUNT;i++) { memory[i] = false; memoryColor[i] = QColor(0xff, 0xff, 0xff); } update(); } void MemoryViewer::setLineWidth(int lineWidth) { m_lineWidth = lineWidth; setFixedHeight(ADRCOUNT/lineWidth + 2); update(); } QString MemoryViewer::getCurrentAddressString() { return QString("$%1").arg(currentAddress,4,16, QLatin1Char('0')); } int MemoryViewer::getCurrentAddress() { return currentAddress; } void MemoryViewer::paintEvent(QPaintEvent *event) { Q_UNUSED(event) QPainter painter(this); // frame painter.setPen(QPen(Qt::darkGray)); painter.drawLine(0,0,m_lineWidth+1,0); painter.drawLine(m_lineWidth+1,0,m_lineWidth+1,ADRCOUNT/m_lineWidth+1); painter.drawLine(m_lineWidth+1,ADRCOUNT/m_lineWidth+1,0,ADRCOUNT/m_lineWidth+1); painter.drawLine(0,ADRCOUNT/m_lineWidth+1,0,0); painter.setFont(QFont(font().family(),8)); for(int y=m_lineWidth*16;y<ADRCOUNT;y+=m_lineWidth*16) { painter.drawLine(m_lineWidth+1,y/m_lineWidth+1,m_lineWidth+8,y/m_lineWidth+1); painter.drawText(m_lineWidth+10,y/m_lineWidth+1+painter.fontMetrics().height()/4,QString("%1-%2").arg(y,4,16, QLatin1Char('0')).arg(y+m_lineWidth-1,4,16, QLatin1Char('0')).toUpper()); } // memory for(int i=0;i<ADRCOUNT;i++) { if(memory[i]) { painter.setPen(QPen(memoryColor[i])); painter.drawPoint(i % m_lineWidth+1, i/m_lineWidth+1); } } } void MemoryViewer::mousePressEvent(QMouseEvent *event) { if(event->button()==Qt::LeftButton) { int mx = event->x(); int my = event->y(); emit currentCoordinateChanged(mx, my); if ((my<1)||(my>ADRCOUNT/m_lineWidth)||(mx<1)||(mx > m_lineWidth)) return; mx--; my--; currentAddress = my*m_lineWidth+mx; emit currentAddressChanged(currentAddress); } }
2,406
C++
.cpp
79
24.379747
192
0.63167
emartisoft/IDE65XX
33
7
4
GPL-3.0
9/20/2024, 10:45:00 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,539,813
main.cpp
emartisoft_IDE65XX/main.cpp
#include "mainwindow.h" #include "singleapplication.h" #include "common.h" #include "darkfusionstyle.h" #include "commodorestyle.h" #include "fabricstyle.h" #include "customstyle.h" #include <QTextStream> int main(int argc, char *argv[]) { QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling); SingleApplication a(argc, argv); if(argc == 0) { if(!a.lock()) return Common::ALREADYRUNNING; } a.setWindowIcon(QIcon(":/res/icon/ide65xx.png")); // add font QFontDatabase::addApplicationFont(":/res/font/UbuntuMono-Bold.ttf"); QFontDatabase::addApplicationFont(":/res/font/UbuntuMono-BoldItalic.ttf"); QFontDatabase::addApplicationFont(":/res/font/UbuntuMono-Italic.ttf"); QFontDatabase::addApplicationFont(":/res/font/UbuntuMono-Regular.ttf"); QSettings settings(Common::appConfigDir()+"/settings.ini", QSettings::IniFormat); // application style int style = settings.value("ApplicationStyle", 3).toInt(); switch (style) { case 0: qApp->setStyle(QStyleFactory::create("fusion")); break; // fusion case 1: qApp->setStyle(new DarkFusionStyle()); break; // darkfusion case 2: qApp->setStyle(QStyleFactory::create("windows")); break; // windows case 3: qApp->setStyle(new CommodoreStyle()); break; // commodore case 4: qApp->setStyle(new FabricStyle()); break; // fabric case 5: qApp->setStyle(new CustomStyle()); break; // custom } qApp->setPalette(QApplication::style()->standardPalette()); // tooltip style qApp->setStyleSheet("QToolTip { color: #000000; background-color: #f8f8f8; border: 1px solid #b0b0b0; }"); // font QString fontFamily = settings.value("ApplicationFontName", "Ubuntu Mono").toString(); int fontSize = settings.value("ApplicationFontSize", 9).toInt(); a.setFont(QFont(fontFamily, fontSize)); MainWindow w; w.show(); return a.exec(); }
2,053
C++
.cpp
44
40.568182
111
0.65812
emartisoft/IDE65XX
33
7
4
GPL-3.0
9/20/2024, 10:45:00 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,539,815
common.cpp
emartisoft_IDE65XX/common.cpp
#include "common.h" QString Common::appLocalDir() { return QCoreApplication::applicationDirPath(); } QString Common::appConfigDir() { return QDir::cleanPath(QStandardPaths::writableLocation(QStandardPaths::GenericConfigLocation) + QDir::separator() + qApp->applicationName()); }
300
C++
.cpp
9
30
147
0.763066
emartisoft/IDE65XX
33
7
4
GPL-3.0
9/20/2024, 10:45:00 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,539,816
darkfusionstyle.cpp
emartisoft_IDE65XX/darkfusionstyle.cpp
#include "darkfusionstyle.h" DarkFusionStyle::DarkFusionStyle(QStyle *style) : QProxyStyle(style) { } void DarkFusionStyle::polish(QPalette &palette) { QColor darkGray(96, 96, 96); QColor blue(0x61, 0x61, 0xd0); QColor whitesmoke(192, 192, 192, 32); palette.setColor(QPalette::Window, darkGray); palette.setColor(QPalette::WindowText, Qt::lightGray); palette.setColor(QPalette::Base, QColor(64, 64, 64)); palette.setColor(QPalette::AlternateBase, darkGray); palette.setColor(QPalette::ToolTipBase, blue); palette.setColor(QPalette::ToolTipText, Qt::lightGray); palette.setColor(QPalette::Text, Qt::gray); palette.setColor(QPalette::Button, darkGray); palette.setColor(QPalette::ButtonText, QColor(20,20,20)); palette.setColor(QPalette::Link, blue.darker()); palette.setColor(QPalette::Highlight, blue); palette.setColor(QPalette::HighlightedText, Qt::black); palette.setColor(QPalette::Active, QPalette::Button, QColor(128, 128, 128)); palette.setColor(QPalette::Disabled, QPalette::ButtonText, whitesmoke.lighter()); palette.setColor(QPalette::Disabled, QPalette::WindowText, whitesmoke.lighter()); palette.setColor(QPalette::Disabled, QPalette::Text, whitesmoke.lighter()); palette.setColor(QPalette::Disabled, QPalette::Light, whitesmoke.lighter()); palette.setColor(QPalette::Light, QColor(192, 192, 192, 32)); palette.setColor(QPalette::Mid, whitesmoke.darker()); palette.setColor(QPalette::Dark, QColor("#303030").lighter()); }
1,576
C++
.cpp
31
45.290323
86
0.726976
emartisoft/IDE65XX
33
7
4
GPL-3.0
9/20/2024, 10:45:00 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,539,817
bookmarkwidget.cpp
emartisoft_IDE65XX/bookmarkwidget.cpp
#include "bookmarkwidget.h" BookmarkWidget::BookmarkWidget(QWidget *parent) : QListView(parent) { delegate = new Delegate(this); delegate->setContentsMargins(4, 2, 4, 2); delegate->setIconSize(24, 24); delegate->setHorizontalSpacing(8); delegate->setVerticalSpacing(2); setModel(new QStandardItemModel(this)); setItemDelegate(delegate); removeAction = new QAction("Remove", this); removeAllAction = new QAction("Remove All", this); editAction = new QAction("Edit", this); setWordWrap(true); } quint64 BookmarkWidget::getLineNumber(int index) { QStringList topTextList = (static_cast<QStandardItemModel *>(model())->item(index)->text()).split(" : "); return topTextList[0].toULongLong(); } QString BookmarkWidget::getFilepath(int index) { QStringList topTextList = (static_cast<QStandardItemModel *>(model())->item(index)->text()).split(" : "); return topTextList[1]; } QString BookmarkWidget::getItemText(int index) { return static_cast<QStandardItemModel *>(model())->item(index)->data(Qt::UserRole).toString(); } QIcon BookmarkWidget::getIcon(int index) { return static_cast<QStandardItemModel *>(model())->item(index)->icon(); } void BookmarkWidget::setTopText(int index, QString topText) { static_cast<QStandardItemModel *>(model())->item(index)->setText(topText); } void BookmarkWidget::addItem(const QPixmap &pixmap, const QString &text, const QString &topText) { auto *item = new QStandardItem(QIcon(pixmap), topText); item->setFlags(Qt::ItemIsEnabled | Qt::ItemIsSelectable); item->setData(text, Qt::UserRole); static_cast<QStandardItemModel *>(model())->appendRow(item); scrollToBottom(); } void BookmarkWidget::removeAll() { static_cast<QStandardItemModel *>(model())->clear(); } void BookmarkWidget::removeItem(int index) { static_cast<QStandardItemModel *>(model())->removeRow(index); } void BookmarkWidget::setItemText(int index, QString text) { static_cast<QStandardItemModel *>(model())->item(index)->setData(text, Qt::UserRole); } void BookmarkWidget::contextMenuEvent(QContextMenuEvent *e) { QMouseEvent leftClick(QEvent::MouseButtonPress, e->pos(), Qt::LeftButton, Qt::NoButton, Qt::NoModifier); mousePressEvent(&leftClick); contextMenu = new QMenu; contextMenu->addAction(editAction); contextMenu->addSeparator(); contextMenu->addAction(removeAction); contextMenu->addSeparator(); contextMenu->addAction(removeAllAction); if(model()->rowCount()>0) { editAction->setEnabled(true); removeAction->setEnabled(true); removeAllAction->setEnabled(true); } else { editAction->setEnabled(false); removeAction->setEnabled(false); removeAllAction->setEnabled(false); } contextMenu->exec(e->globalPos()); if (!contextMenu.isNull()) delete contextMenu; }
3,007
C++
.cpp
84
30.678571
110
0.700935
emartisoft/IDE65XX
33
7
4
GPL-3.0
9/20/2024, 10:45:00 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,539,818
about.cpp
emartisoft_IDE65XX/about.cpp
#include "about.h" #include "ui_about.h" #include <QMessageBox> #include "version.h" About::About(QWidget *parent) : QDialog(parent), ui(new Ui::About) { setWindowFlags(this->windowFlags() & ~Qt::WindowContextHelpButtonHint); ui->setupUi(this); ui->version->setText("IDE 65XX " + QString(VER_FILEVERSION_STR)); } About::~About() { delete ui; } void About::on_bAboutQt_clicked() { QMessageBox::aboutQt(this); }
466
C++
.cpp
20
19.5
76
0.66895
emartisoft/IDE65XX
33
7
4
GPL-3.0
9/20/2024, 10:45:00 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,539,819
mainwindow.cpp
emartisoft_IDE65XX/mainwindow.cpp
#include "mainwindow.h" #include "ui_mainwindow.h" #include <QApplication> #include <QCompleter> #include <QFile> #include <QStringListModel> #define TIMEOUT 5000 #define WINDOW_WIDTH 800 #define WINDOW_HEIGHT 600 MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) , ui(new Ui::MainWindow) , settings(QDir::cleanPath(Common::appConfigDir() + QDir::separator() + "settings.ini"), QSettings::IniFormat) , bookmarkcfgfile(QDir::cleanPath(Common::appConfigDir() + QDir::separator() + "bookmark.ini"), QSettings::IniFormat) { ui->setupUi(this); workspacePath = "?"; pAssemblyFile = asmNotSelected; icProvider = new IdeIconProvider(); ui->dwProjectExplorer->hide(); ui->dwOutput->hide(); ui->dwIssues->hide(); ui->dwOpenDocument->hide(); tabifyDockWidget(ui->dwBookmarks, ui->dwOpenDocument); tabifyDockWidget(ui->dwMemoryViewer, ui->dwHexEditor); statusCurPosInfo = new QLabel("", this); ui->statusbar->addPermanentWidget(statusCurPosInfo); ui->statusbar->showMessage("READY.", TIMEOUT); ui->findDialog->setVisible(false); // find action findAction = new QAction(QIcon(":/res/images/find.png"), tr("Find And Replace"), this); findAction->setShortcut(QKeySequence(Qt::CTRL | Qt::Key_F)); connect(findAction, SIGNAL(triggered()), this, SLOT(showFind())); // show all chars showAllCharsAction = new QAction(QIcon(":/res/images/whitespace.png"), tr("Toggle Show All Characters"), this); connect(showAllCharsAction, SIGNAL(triggered()), this, SLOT(showAllChars())); // action for left toolbar menuCode = new QAction(QIcon(":/res/images/coding.png"), tr("Code"), this); menuCode->setEnabled(false); menuHome = new QAction(QIcon(":/res/images/home.png"), tr("Welcome"), this); connect(menuCode, SIGNAL(triggered()), this, SLOT(OpenCode())); connect(ui->actionHelp, SIGNAL(triggered()), this, SLOT(OpenHelp())); connect(menuHome, SIGNAL(triggered()), this, SLOT(OpenHome())); connect(ui->menuEdit, SIGNAL(aboutToShow()), this, SLOT(showContextMenu())); // After Click Edit menu // toolbar spacerTop = new QLabel(" ", this); spacerBottom = new QLabel(" ", this); spacerMiddle = new QLabel(" ",this); spacerMiddle->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Expanding); spacerTop->setFixedHeight(16); spacerBottom->setFixedHeight(16); setTopToolbar(); leftToolBar = new QToolBar(); leftToolBar->setObjectName("leftSideBar"); leftToolBar->setWindowTitle("Left Sidebar"); addToolBar(Qt::LeftToolBarArea, leftToolBar); leftToolBar->setMinimumSize(64,0); leftToolBar->setMovable(false); leftToolBar->setToolButtonStyle(Qt::ToolButtonTextUnderIcon); leftToolBar->setOrientation(Qt::Vertical); leftToolBar->addWidget(spacerTop); leftToolBar->addAction(menuHome); leftToolBar->addSeparator(); leftToolBar->addAction(ui->actionSelect_Workspace); leftToolBar->addAction(menuCode); leftToolBar->addSeparator(); leftToolBar->addAction(ui->actionSettings); leftToolBar->addAction(ui->actionHelp); leftToolBar->addWidget(spacerMiddle); leftToolBar->addAction(ui->actionBuild_as_binary); leftToolBar->addSeparator(); leftToolBar->addAction(ui->actionDebugger); leftToolBar->addAction(ui->actionBuild_this); leftToolBar->addAction(ui->actionBuild_and_Run); leftToolBar->addWidget(spacerBottom); // file contextmenu ui->tvWorkspaceFiles->setContextMenuPolicy(Qt::CustomContextMenu); fileContextMenu = new QMenu; menuEmulator = new QAction(QIcon(":/res/images/emulator.png"), tr("Run in Emulator"), this); menuExomizer = new QAction(QIcon(":/res/images/crunch.png"), tr("Compress"), this); menuDirmaster = new QAction(QIcon(":/res/images/floppy.png"), tr("Open with Dirmaster"), this); menuSidPlayer = new QAction(QIcon(":/res/images/sid.png"), tr("Play with SID Player"), this); menuC1541 = new QAction(QIcon(":/res/images/floppy.png"), tr("Create D64 image"), this); menuDelete = new QAction(QIcon(":/res/images/delete.png"), tr("Delete"), this); menuRename = new QAction(QIcon(":/res/images/rename.png"), tr("Rename"), this); menuHexEditor = new QAction(QIcon(":/res/images/binary.png"), tr("Open with HexEditor"), this); menuAssemblyFile = new QAction(QIcon(":/res/images/assembly.png"), tr("Set Assembly File"), this); menuCartConv = new QAction(QIcon(":/res/images/cartridge.png"), tr("Convert to CRT"), this); connect(menuEmulator, SIGNAL(triggered()), this, SLOT(RunInEmulator())); connect(menuExomizer, SIGNAL(triggered()), this, SLOT(Compress())); connect(menuDirmaster, SIGNAL(triggered()), this, SLOT(OpenWithDirMaster())); connect(menuSidPlayer, SIGNAL(triggered()), this, SLOT(PlayWithSIDPlayer())); connect(menuC1541, SIGNAL(triggered()), this, SLOT(CreateD64Image())); connect(menuDelete, SIGNAL(triggered()), this, SLOT(RemoveFileOrFolder())); connect(menuRename, SIGNAL(triggered()), this, SLOT(Rename())); connect(menuHexEditor, SIGNAL(triggered()), this, SLOT(OpenWithHexEditor())); connect(menuAssemblyFile, SIGNAL(triggered()), this, SLOT(SetAssemblyFile())); connect(menuCartConv, SIGNAL(triggered()), this, SLOT(ConvertToCrt())); fileContextMenu->addAction(menuEmulator); fileContextMenu->addAction(menuExomizer); fileContextMenu->addAction(menuC1541); #ifdef Q_OS_WIN fileContextMenu->addSeparator(); fileContextMenu->addAction(menuDirmaster); #endif fileContextMenu->addAction(menuSidPlayer); fileContextMenu->addAction(menuHexEditor); fileContextMenu->addAction(menuCartConv); fileContextMenu->addSeparator(); fileContextMenu->addAction(menuAssemblyFile); fileContextMenu->addSeparator(); fileContextMenu->addAction(menuDelete); fileContextMenu->addAction(menuRename); opendocuments.clear(); // init settings window settingsWin = new SettingsWindow(this); settingsWin->ReadCmdLineOption(); readSettings(); // file system watcher watcher = new QFileSystemWatcher(this); connect(watcher, SIGNAL(fileChanged(const QString&)), this, SLOT(fileChanged(const QString&))); // hex file system watcher hexwatcher = new QFileSystemWatcher(this); connect(hexwatcher, SIGNAL(fileChanged(const QString&)), this, SLOT(hexfileChanged(const QString&))); // completer QString strUserCompleterFile = QDir::cleanPath(Common::appConfigDir()+QDir::separator()+"userCompleter.dat"); completer = new QCompleter(this); if(QFile(strUserCompleterFile).exists()) completer->setModel(modelFromFile(strUserCompleterFile)); else completer->setModel(modelFromFile(":/res/completer/kickass.dat")); completer->setModelSorting(QCompleter::CaseSensitivelySortedModel); completer->setCaseSensitivity(Qt::CaseSensitive); completer->setWrapAround(false); // welcome QString styleSheet = QString("background-color: %1;").arg(palette().window().color().name()); ui->brHome->setStyleSheet(styleSheet); // help ui->brHelp->setStyleSheet(styleSheet); ui->brHelp->setSearchPaths(QStringList()<<":/res/help/"); ui->brHelp->setSource(QUrl("help.htm")); // bookmarks auto verticalLayout_13 = new QVBoxLayout(ui->dockBookmarkWidget); verticalLayout_13->setSpacing(0); verticalLayout_13->setObjectName(QString::fromUtf8("verticalLayout_13")); verticalLayout_13->setContentsMargins(0, 0, 0, 0); bookmarks = new BookmarkWidget(ui->dockBookmarkWidget); bookmarks->setObjectName(QString::fromUtf8("boookmarks")); bookmarks->setFrameShape(QFrame::Box); bookmarks->setFrameShadow(QFrame::Sunken); bookmarks->setFont(ui->dwProjectExplorer->font()); connect(bookmarks->removeAction, SIGNAL(triggered()), this, SLOT(removeBookmark())); connect(bookmarks->removeAllAction, SIGNAL(triggered()), this, SLOT(removeAllBookmark())); connect(bookmarks->editAction, SIGNAL(triggered()), this, SLOT(editBookmark())); connect(bookmarks, SIGNAL(clicked(QModelIndex)), this, SLOT(bookmarkClicked(QModelIndex))); verticalLayout_13->addWidget(bookmarks); ui->dwBookmarks->setWidget(ui->dockBookmarkWidget); // hex editor auto toolbar = new QToolBar; toolbar->setIconSize(QSize(16,16)); ui->verticalLayout_hexeditor->insertWidget(0, toolbar); QAction* hNew = new QAction(QIcon(":/res/images/new.png"), "New", this); toolbar->addAction(hNew); connect(hNew, SIGNAL(triggered()), this, SLOT(hexNewFile())); QAction* hOpen = new QAction(QIcon(":/res/images/open.png"), "Open", this); toolbar->addAction(hOpen); connect(hOpen, SIGNAL(triggered()), this, SLOT(hexFileOpen())); hSave = new QAction(QIcon(":/res/images/save.png"), "Save", this); toolbar->addAction(hSave); connect(hSave, SIGNAL(triggered()), this, SLOT(hexFileSave())); QAction* hSaveas = new QAction(QIcon(":/res/images/saveas.png"), "Save As", this); toolbar->addAction(hSaveas); connect(hSaveas, SIGNAL(triggered()), this, SLOT(hexFileSaveas())); hSaveselection = new QAction(QIcon(":/res/images/saveselection.png"), "Save Selection", this); toolbar->addAction(hSaveselection); connect(hSaveselection, SIGNAL(triggered()), this, SLOT(hexFileSaveselection())); toolbar->addSeparator(); hUndo = new QAction(QIcon(":/res/images/undo.png"), "Undo", this); toolbar->addAction(hUndo); connect(hUndo, SIGNAL(triggered()), this, SLOT(hexFileUndo())); hRedo = new QAction(QIcon(":/res/images/redo.png"), "Redo", this); toolbar->addAction(hRedo); connect(hRedo, SIGNAL(triggered()), this, SLOT(hexFileRedo())); toolbar->addSeparator(); QAction* hFindReplace = new QAction(QIcon(":/res/images/find.png"), "Find And Replace", this); toolbar->addAction(hFindReplace); connect(hFindReplace, SIGNAL(triggered()), this, SLOT(hexFileFindReplace())); connect(ui->bytesPerLine, SIGNAL(valueChanged(int)), this, SLOT(bytesperlineValueChanged(int))); connect(ui->hexInsert, SIGNAL(clicked(bool)), this, SLOT(setOverwriteMode(bool))); hexFilename = new QLabel("???", this); ui->verticalLayout_hexeditor->addWidget(hexFilename); hexEdit = new QHexEdit(ui->dockHexEditWidget); hexEdit->setObjectName(QString::fromUtf8("hexEdit")); hexEdit->setFrameShape(QFrame::Box); hexEdit->setFrameShadow(QFrame::Sunken); hexEdit->setFont(QFont(pCodeFontName, pCodeFontSize)); hexEdit->setOverwriteMode(!ui->hexInsert->isChecked()); hexEdit->setReadOnly(false); hexEdit->setAddressArea(true); hexEdit->setAddressAreaColor(palette().window().color()); hexEdit->setAsciiArea(true); hexEdit->setHighlighting(true); hexEdit->setHighlightingColor(QColor(0xff, 0xff, 0x99)); hexEdit->setSelectionColor(palette().highlight().color()); hexEdit->setAddressWidth(4); hexEdit->setBytesPerLine(8); // connects connect(hexEdit, SIGNAL(dataChanged()), this, SLOT(dataChanged())); ui->verticalLayout_hexeditor->addWidget(hexEdit); ui->dwHexEditor->setWidget(ui->dockHexEditWidget); hexActionEnable(); // set recent workspace for home UpdateRecentWorkspaces(); ui->menuEdit->menuAction()->setVisible(false); setActionsEnable(false); // output and issues dockwidgets tabifyDockWidget(ui->dwIssues, ui->dwOutput); // view menu ui->menuView->addAction(ui->topToolBar->toggleViewAction()); ui->menuView->addAction(leftToolBar->toggleViewAction()); ui->menuView->addSeparator(); ui->menuView->addAction(ui->dwProjectExplorer->toggleViewAction()); ui->menuView->addAction(ui->dwOpenDocument->toggleViewAction()); ui->menuView->addSeparator(); ui->menuView->addAction(ui->dwOutput->toggleViewAction()); ui->menuView->addAction(ui->dwIssues->toggleViewAction()); ui->menuView->addSeparator(); ui->menuView->addAction(ui->dwBookmarks->toggleViewAction()); ui->menuView->addAction(ui->dwMemoryViewer->toggleViewAction()); ui->menuView->addAction(ui->dwHexEditor->toggleViewAction()); // home or code if(bWelcome) { OpenHome(); } else { if(pOpenLastUsedFiles) { OpenCode(); } else { OpenHome(); } } QPalette p(palette()); p.setColor(QPalette::Highlight, palette().window().color().darker(96)); p.setColor(QPalette::HighlightedText, Qt::black); ui->listOpenDocuments->setPalette(p); ui->tvWorkspaceFiles->setPalette(p); ui->tOutput->setPalette(p); QPalette pIssue(palette()); pIssue.setColor(QPalette::Highlight, QColor(0xf3, 0x34, 0x34)); pIssue.setColor(QPalette::HighlightedText, Qt::white); ui->tIssues->setPalette(pIssue); // Memory Viewer ui->dwMemoryViewer->installEventFilter(this); ui->sbMemoryViewer->setValue(0x80); ui->mvWarning->setVisible(false); connect(ui->memoryViewer, SIGNAL(currentAddressChanged(int)), this, SLOT(memoryViewerCurrentAddressChanged(int))); connect(ui->memoryViewer, SIGNAL(currentCoordinateChanged(int, int)), this, SLOT(memoryViewerCurrentCoordinateChanged(int, int))); // bookmark.ini int bookmarkCount = bookmarkcfgfile.value("Count",0).toInt(); QString bookmarkWorkspace = bookmarkcfgfile.value("0","").toString(); if((bookmarkCount>0)&&(workspacePath==bookmarkWorkspace)) { for(int i=0;i<bookmarkCount;i++) { QStringList values = bookmarkcfgfile.value(QString::number(i+1),"").toString().split('|'); QPixmap bPixmap = icProvider->icon(QFileInfo(QDir::cleanPath(workspacePath + QDir::separator() + values[1]))).pixmap(24,24); bookmarks->addItem(bPixmap, values[2], values[0] + " : " + values[1]); } } setAcceptDrops(true); // hex search dialog hexSearchDialog = new HexSearchDialog(hexEdit, this); // cartconv cc = new CartConv(this); } MainWindow::~MainWindow() { delete ui; } /*! open file via double click event */ void MainWindow:: on_tvWorkspaceFiles_doubleClicked(const QModelIndex &index) { prepareBeforeOpen(m_ptrModelForTree->filePath(index)); } /*! select file via click event */ void MainWindow::on_tvWorkspaceFiles_clicked(const QModelIndex &index) { filePath = m_ptrModelForTree->filePath(index); selectedIndex = index; tabicon = m_ptrModelForTree->fileIcon(index); } /*! open file from file menu */ void MainWindow::on_actionOpen_triggered() { QString fileName = QFileDialog::getOpenFileName(this, "Open file", workspacePath, tr("Assembler source files (*.asm);;Library files (*.lib);;All files (*.*)")); if(!fileName.isEmpty()) { prepareBeforeOpen(fileName); } } /*! new file */ void MainWindow::on_actionNew_triggered() { if (!selectedIndex.isValid()) { ui->statusbar->showMessage("No workspace", TIMEOUT); return; } Tab *tab = new Tab; ui->tabWidget->addTab(tab, tr("New")); ui->tabWidget->setCurrentWidget(tab); int old = ui->tabWidget->currentIndex(); QString newFile = saveAsFile(old, "New file"); if(!newFile.isEmpty()) { filePath = newFile; openFileFromPath(newFile); ui->statusbar->showMessage("New file", TIMEOUT); } closeFile(old); } /*! text changed for code editor */ void MainWindow::changeCurrentSavedState(bool changed) { QString tabText = ui->tabWidget->tabText(ui->tabWidget->currentIndex()); if (changed) { if (tabText[0] != '*') ui->tabWidget->setTabText(ui->tabWidget->currentIndex(), '*' + tabText); } else { if (tabText[0] == '*') tabText.remove(0, 1); ui->tabWidget->setTabText(ui->tabWidget->currentIndex(), tabText); } } /*! text changed for code editor */ void MainWindow::changeCode() { if(firstOpening){ firstOpening = false; return; } QString tabText = ui->tabWidget->tabText(ui->tabWidget->currentIndex()); if (tabText[0] != '*') ui->tabWidget->setTabText(ui->tabWidget->currentIndex(), '*' + tabText); SetCursorPos(); } /*! tab codeeditor selection changed */ void MainWindow::selectionChangeCode() { emit on_tabWidget_currentChanged(ui->tabWidget->currentIndex()); } /*! Edit menu */ void MainWindow::showContextMenu() { Tab *tab = static_cast<Tab*>( ui->tabWidget->widget(ui->tabWidget->currentIndex())); ui->menuEdit->clear(); ui->menuEdit->addAction(findAction); ui->menuEdit->addAction(showAllCharsAction); ui->menuEdit->addSeparator(); ui->menuEdit->addActions(tab->code->getContextMenu()->actions()); } /*! Cursor pos, selection length, file length info */ void MainWindow::SetCursorPos() { if(ui->tabWidget->count()<1) return; Tab *tab = static_cast<Tab*>( ui->tabWidget->widget(ui->tabWidget->currentIndex())); QString curString = tab->code->textCursor().block().text(); statusCurPosInfo->setText(QString(" Line %1 | Column %2 | Sel %4 | Length %3 | %5 ").arg(tab->code->textCursor().blockNumber()+1).arg(tab->code->textCursor().positionInBlock()+1).arg(tab->code->toPlainText().length()).arg(tab->code->textCursor().selectedText().length()).arg(tab->code->overwriteMode()?"OVR":"INS")); } /*! show find dialog */ void MainWindow::showFind() { Tab *tab = static_cast<Tab*>( ui->tabWidget->currentWidget()); bool fv = ui->findDialog->isVisible(); ui->findDialog->setVisible(!fv); ui->tFind->setText(tab->code->textCursor().selectedText()); (!fv) ? ui->tFind->setFocus() : tab->code->setFocus(); } void MainWindow::showAllChars() { Tab *tab = static_cast<Tab*>( ui->tabWidget->currentWidget()); QTextOption option; tab->code->setShowAllChars(!tab->code->getShowAllChars()); if(tab->code->getShowAllChars()) option.setFlags(QTextOption::ShowLineAndParagraphSeparators | QTextOption::ShowTabsAndSpaces | QTextOption::ShowDocumentTerminator); option.setWrapMode((pWordWrap)? QTextOption::WordWrap : QTextOption::NoWrap); QFontMetrics fm(tab->code->font()); option.setTabStopDistance(fm.horizontalAdvance(' ')*pTabSize); tab->code->document()->setDefaultTextOption(option); } /*! close file */ void MainWindow::closeFile(int index) { Tab *tabForDeleting = static_cast<Tab*>( ui->tabWidget->widget(index)); QString tabText = ui->tabWidget->tabText(ui->tabWidget->currentIndex()); if (tabText[0] == '*') { int ret = QMessageBox::question(this, "Save before closing", "Do you want to save your changes?\n" "Save file [" + tabForDeleting->getCurrentFilePath() + "]?", QMessageBox::Save | QMessageBox::Discard, QMessageBox::Save); switch (ret) { case QMessageBox::Save: // Save was clicked saveFile(index); break; default: // should never be reached break; } } watcher->removePath(tabForDeleting->getCurrentFilePath()); ui->tabWidget->removeTab(index); delete tabForDeleting; ui->statusbar->showMessage("File closed", TIMEOUT); RefreshOpenDocuments(); bool b = ui->tabWidget->count()>0; ui->menuEdit->menuAction()->setVisible(b); setActionsEnableForDoc(b); ui->findDialog->setVisible(false); statusCurPosInfo->setVisible(ui->tabWidget->count()>0); } void MainWindow::on_actionClose_triggered() { if(selectedIndex.isValid()) closeFile(ui->tabWidget->currentIndex()); } void MainWindow::on_tabWidget_tabCloseRequested(int index) { closeFile(index); } /*! save file */ void MainWindow::saveFile(int index) { Tab *tab; if (index == -1) tab = static_cast<Tab*>( ui->tabWidget->currentWidget()); else tab = static_cast<Tab*>( ui->tabWidget->widget(index)); QString filePath = tab->getCurrentFilePath(); if (filePath.isEmpty()) { saveAsFile(index); } else { watcher->removePath(filePath); // REDO/UNDO action works after saving file tab->saveCodeToFile(filePath, false); watcher->addPath(filePath); ui->statusbar->showMessage("File saved", TIMEOUT); } } /*! save file as ... */ QString MainWindow::saveAsFile(int index, QString caption) { QString fileName = QFileDialog::getSaveFileName(this, caption, workspacePath, tr("Assembler source files (*.asm);;Library files (*.lib);;All files (*.*)")); if (!fileName.isEmpty()) { // workspacePath = QFileInfo(fileName).absoluteDir().absolutePath(); Tab *tab; if (index == -1) tab = static_cast<Tab*>( ui->tabWidget->currentWidget()); else tab = static_cast<Tab*>( ui->tabWidget->widget(index)); tab->saveCodeToFile(fileName, false); setCurrentTabName(fileName, index); ui->statusbar->showMessage("File saved", TIMEOUT); return fileName; } else { ui->statusbar->showMessage("File not saved", TIMEOUT); return ""; } } void MainWindow::setCurrentTabName(const QString &filePath, int index) { QString caption; int i; if ((i = filePath.lastIndexOf('/')) == -1) i = filePath.lastIndexOf('\\'); caption = filePath.mid(i + 1); if (index == -1) ui->tabWidget->setTabText(ui->tabWidget->currentIndex(), caption); else ui->tabWidget->setTabText(index, caption); } void MainWindow::openFileFromPath(QString filenamePath) { Tab *tab = new Tab; ui->tabWidget->addTab(tab, tr("New")); ui->tabWidget->setCurrentWidget(tab); firstOpening = true; if(!tab->loadCodeFromFile(filenamePath)) { ui->tabWidget->removeTab(ui->tabWidget->currentIndex()); } else { QString caption; int i; if ((i = filenamePath.lastIndexOf('/')) == -1) i = filenamePath.lastIndexOf('\\'); caption = filenamePath.mid(i + 1); ui->tabWidget->setTabText(ui->tabWidget->currentIndex(), caption); QFileInfo fi(filenamePath); QString ext = fi.completeSuffix(); // highlight extension list if( (ext=="asm")|| (ext=="lib")|| (ext=="inc")|| (ext=="sym")|| (ext=="s")|| (ext=="a") ) tab->highlighter = new Highlighter(tab->code->document()); connect(tab->code, SIGNAL(modificationChanged(bool)), this, SLOT(changeCurrentSavedState(bool))); connect(tab->code, SIGNAL(textChanged()), this, SLOT(changeCode())); connect(tab->code, SIGNAL(selectionChanged()), this, SLOT(selectionChangeCode())); connect(tab->code, SIGNAL(cursorPositionChanged()), this, SLOT(SetCursorPos())); connect(tab->code, SIGNAL(bookmarksChanged(quint64, QString, bool)), this, SLOT(bookmarksChangedSlot(quint64, QString, bool))); connect(tab->code, SIGNAL(updateLineNumber(quint64, int)), this, SLOT(updateLineNumberSlot(quint64, int))); connect(tab->code, SIGNAL(showFindDialog()), this, SLOT(showFind())); connect(tab->code, SIGNAL(overWriteModeChanged()), this, SLOT(SetCursorPos())); connect(tab->code, SIGNAL(AfterEnterSendLine(QString)), this, SLOT(ReceiveLineForCompleter(QString))); tab->code->document()->setModified(false); tab->code->setCompleter(completer); tab->code->setFocus(); tab->code->setFont(QFont(pCodeFontName, pCodeFontSize)); QTextOption option; if(pShowAllChars) option.setFlags(QTextOption::ShowLineAndParagraphSeparators | QTextOption::ShowTabsAndSpaces | QTextOption::ShowDocumentTerminator); option.setWrapMode((pWordWrap)? QTextOption::WordWrap : QTextOption::NoWrap); QFontMetrics fm(tab->code->font()); option.setTabStopDistance(fm.horizontalAdvance(' ')*pTabSize); // tab distance tab->code->document()->setDefaultTextOption(option); tab->code->setShowAllChars(pShowAllChars); tab->code->setAutoCompletion(pAutoCompletion); tab->code->setTabSpace((pTabPolicy==0)?true:false); tab->code->setTabSpaceCount(pTabSize); ui->tabWidget->setTabIcon(ui->tabWidget->currentIndex(), icProvider->icon(fi)); ui->menuEdit->menuAction()->setVisible(true); ui->statusbar->showMessage("File Opened", TIMEOUT); watcher->addPath(filenamePath); setActionsEnable(true); RefreshOpenDocuments(); // set bookmark for (int i=0;i<bookmarks->model()->rowCount();i++) { if(tab->getCurrentFilePath().remove(workspacePath) == bookmarks->getFilepath(i)) { tab->code->bookmarks.append(bookmarks->getLineNumber(i)); } } tab->update(); } statusCurPosInfo->setVisible(ui->tabWidget->count()>0); } /*! open workspace */ void MainWindow::openWorkspace(QString wDir) { QDir wspace(wDir); if(!wspace.exists()) { ui->statusbar->showMessage("Workspace does not exist.", TIMEOUT); RemoveFromRecentWorkspace(wDir); return; } m_ptrModelForTree = new QFileSystemModel(this); m_ptrModelForTree->setRootPath(""); m_ptrModelForTree->setFilter(QDir::Files | QDir::AllDirs | QDir::NoDotAndDotDot); m_ptrModelForTree->setNameFilters(QStringList() << "*.asm" << "*.prg" << "*.sid" << "*.bin" << "*.txt" << "*.s" << "*.lib" << "*.dbg" << "*.sym" << "*.d64" << "*.d71" << "*.d81" << "*.a" << "*.inc" << "*.vs" << "*.crt" ); m_ptrModelForTree->setNameFilterDisables(true); m_ptrModelForTree->setIconProvider(icProvider); ui->tvWorkspaceFiles->setModel(m_ptrModelForTree); const QModelIndex rootIndex = m_ptrModelForTree->index(QDir::cleanPath(wDir)); if(rootIndex.isValid()) ui->tvWorkspaceFiles->setRootIndex(rootIndex); ui->tvWorkspaceFiles->setHeaderHidden(true); ui->tvWorkspaceFiles->setSortingEnabled(true); ui->tvWorkspaceFiles->sortByColumn(0, Qt::AscendingOrder); ui->tvWorkspaceFiles->setIndentation(20); ui->tvWorkspaceFiles->hideColumn(1); ui->tvWorkspaceFiles->hideColumn(2); ui->tvWorkspaceFiles->hideColumn(3); workspacePath = wDir; selectedIndex = rootIndex; ui->statusbar->showMessage("Selected a directory as workspace", TIMEOUT); settings.setValue("Workspace", workspacePath); settings.sync(); ui->dwProjectExplorer->show(); // ui->dwBookmarks->show(); ui->dwOpenDocument->show(); UpdateRecentWorkspaces(); OpenCode(); setWindowTitle(wDir + " - IDE 65XX"); ui->actionNew->setEnabled(true); ui->actionOpen->setEnabled(true); menuCode->setEnabled(true); ui->memoryViewer->reset(); if((lastMemoryViewX!=-1)&&(lastMemoryViewY!=-1)) { sbMemoryViewerValueNotChanged = false; ui->lCurrentAddress->setText("????"); memoryViewerCurrentCoordinateChanged(lastMemoryViewX, lastMemoryViewY); } } void MainWindow::closeAll() { while(ui->tabWidget->count()>0) { closeFile(ui->tabWidget->currentIndex()); } } void MainWindow::on_actionCloseAllButThis_triggered() { while(ui->tabWidget->count()>1) { if(ui->tabWidget->tabText(0) == ui->tabWidget->tabText(ui->tabWidget->currentIndex())) closeFile(1); else closeFile(0); } } void MainWindow::fileChanged(const QString &path) { for(int i=0;i<ui->tabWidget->count();i++) { Tab *tab = static_cast<Tab*>( ui->tabWidget->widget(i)); if(tab->getCurrentFilePath()==path) { QTextCursor cr = tab->code->textCursor(); int p = cr.position(); tab->loadCodeFromFile(path); cr.setPosition(p); tab->code->setTextCursor(cr); } } } void MainWindow::hexfileChanged(const QString &path) { if(curHexFilename==path) { loadHexFile(); } } void MainWindow::setTopToolbar(int index) { ui->topToolBar->clear(); ui->topToolBar->addAction(menuHome); ui->topToolBar->addSeparator(); ui->topToolBar->addAction(ui->actionSelect_Workspace); ui->topToolBar->addAction(menuCode); ui->topToolBar->addSeparator(); ui->topToolBar->addAction(ui->actionNew); ui->topToolBar->addAction(ui->actionOpen); ui->topToolBar->addAction(ui->actionSave); ui->topToolBar->addAction(ui->actionSaveAll); ui->topToolBar->addSeparator(); ui->topToolBar->addAction(ui->actionBuild_as_binary); ui->topToolBar->addAction(ui->actionBuild_this); ui->topToolBar->addAction(ui->actionBuild_and_Run); if (index>-1) { Tab *tab = static_cast<Tab*>( ui->tabWidget->widget(index)); ui->topToolBar->addSeparator(); ui->topToolBar->addAction(findAction); ui->topToolBar->addAction(showAllCharsAction); ui->topToolBar->addActions(tab->code->getContextMenu()->actions()); } } void MainWindow::closeEvent(QCloseEvent *event) { int ret = QMessageBox::question(this, "IDE65xx", "Do you really want to exit?", QMessageBox::Yes | QMessageBox::No, QMessageBox::No); if (ret == QMessageBox::Yes) { OpenCode(); writeSettings(); closeAll(); saveUserCompleter(); event->accept(); } else { event->ignore(); } } void MainWindow::keyReleaseEvent(QKeyEvent *event) { Tab *tab = static_cast<Tab*>( ui->tabWidget->widget(ui->tabWidget->currentIndex())); switch (event->key()) { case (Qt::Key_F1): { QString word = tab->code->getHelpWord(); if( (word=="if")|| (word=="import")|| (word=="define")|| (word=="importonce") ) { ChooseTopic ct(this); ct.setWord(word); if (ct.exec() == QDialog::Accepted) word= ct.getWord(); else word = ""; ct.deleteLater(); } ui->brHelp->setSource(QUrl("help.htm#"+ word.toUpper())); OpenHelp(); break; } case (Qt::Key_F2): { OpenCode(); break; } case (Qt::Key_F3): { OpenHome(); break; } } } bool MainWindow::eventFilter(QObject *obj, QEvent *event) { if (event->type() == QEvent::Resize && obj == ui->dwMemoryViewer) { sbMemoryViewerValueNotChanged = false; ui->lCurrentAddress->setText("????"); memoryViewerCurrentCoordinateChanged(lastMemoryViewX, lastMemoryViewY); } return QWidget::eventFilter(obj, event); } void MainWindow::dragEnterEvent(QDragEnterEvent *event) { if (event->mimeData()->hasUrls()) event->accept(); } void MainWindow::dropEvent(QDropEvent *event) { if (event->mimeData()->hasUrls()) { QList<QUrl> urls = event->mimeData()->urls(); //QString filePath = ; prepareBeforeOpen(urls.at(0).toLocalFile()); event->accept(); } } // save edited file void MainWindow::on_actionSave_triggered() { if(!selectedIndex.isValid()) return; QString tabText = ui->tabWidget->tabText(ui->tabWidget->currentIndex()); if (tabText[0] == '*') { saveFile(ui->tabWidget->currentIndex()); tabText.remove(0,1); ui->tabWidget->setTabText(ui->tabWidget->currentIndex(), tabText); } } // select workspace void MainWindow::on_actionSelect_Workspace_triggered() { QString directory = QFileDialog::getExistingDirectory(this, tr("Select a directory as workspace"), QDir::homePath(), QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks); // workspace if(!directory.isEmpty()) { closeAll(); bookmarks->removeAll(); pAssemblyFile = asmNotSelected; ui->lAssemblyFile->setText(asmNotSelected); openWorkspace(directory); AddRecentWorkspace(directory); } } void MainWindow::UpdateRecentWorkspaces() { QStringList ws = settings.value("recentWorkspaces").toStringList(); int countWs = qMin(ws.size(), pMaxRecentWorkspace); QFile f(":/res/welcome/welcome.htm"); if(f.open(QFile::ReadOnly)) { QString s = f.readAll(); ui->brHome->clear(); if(countWs>0) { for(int i=0; i<countWs; i++) s.append (QString("<a href=\"#?%1\" data-toggle=\"tooltip\" title=\"Remove this from recent workspaces\">&nbsp;&nbsp;<img src=\":/res/images/deletews.png\">&nbsp;&nbsp;</a><a href=\"#*%1\" data-toggle=\"tooltip\" title=\"Open workspace\"><span style=\"font-size:10pt; text-decoration: none; color:#000000;\">%2. </span><span style=\"font-size:12pt; text-decoration: none; color:#6161d0;\">%1</span></a><br><br>").arg(ws[i]).arg(i+1)); } else { s.append("No recent workspace"); } s.append("</body></html>"); ui->brHome->insertHtml(s); f.close(); } } void MainWindow::RemoveFromRecentWorkspace(QString wspc) { QStringList ws = settings.value("recentWorkspaces").toStringList(); ws.removeAll(wspc); settings.setValue("recentWorkspaces", ws); UpdateRecentWorkspaces(); } void MainWindow::AddRecentWorkspace(QString wspc) { // recent workspace QStringList ws = settings.value("recentWorkspaces").toStringList(); ws.removeAll(wspc); ws.prepend(wspc); while(ws.size()>pMaxRecentWorkspace) ws.removeLast(); settings.setValue("recentWorkspaces", ws); } void MainWindow::setActionsEnable(bool value) { ui->actionNew->setEnabled(value); ui->actionOpen->setEnabled(value); setActionsEnableForDoc(value); } void MainWindow::setActionsEnableForDoc(bool value) { ui->actionSave->setEnabled(value); ui->actionSaveAll->setEnabled(value); ui->actionSave_as->setEnabled(value); ui->actionClose->setEnabled(value); ui->actionClose_All->setEnabled(value); ui->actionCloseAllButThis->setEnabled(value); // ui->actionBuild_this->setEnabled(value); // ui->actionBuild_and_Run->setEnabled(value); // ui->actionBuild_as_binary->setEnabled(value); // ui->actionDebugger->setEnabled(value); ui->actionGenerate_Disk_Directive->setEnabled(value); ui->actionGenerate_File_Directive->setEnabled(value); ui->actionInsert_BASIC_SYS_Line->setEnabled(value); ui->actionPuts_A_Breakpoint->setEnabled(value); } void MainWindow::on_brHome_anchorClicked(const QUrl &arg1) { QString ahref = arg1.fragment(); if(ahref=="selectworkspace") { emit on_actionSelect_Workspace_triggered(); return; } // delete workspace ? // open workspace * QString firstChar = arg1.fragment().left(1); QString word = arg1.fragment().remove(firstChar); if(firstChar=="?") { if(QMessageBox::question(this, "Remove?", "Are you sure you want to remove <b>\""+word+"\"</b> from recent workspaces?") == QMessageBox::Yes) { RemoveFromRecentWorkspace(word); } } else if (firstChar == "*") { closeAll(); bookmarks->removeAll(); pAssemblyFile = asmNotSelected; ui->lAssemblyFile->setText(asmNotSelected); openWorkspace(word); AddRecentWorkspace(word); } } // save as... void MainWindow::on_actionSave_as_triggered() { if(!selectedIndex.isValid()) return; QString newFile = saveAsFile(ui->tabWidget->currentIndex()); if(!newFile.isEmpty()) { closeFile(ui->tabWidget->currentIndex()); openFileFromPath(newFile); } } // close all void MainWindow::on_actionClose_All_triggered() { closeAll(); } // save all void MainWindow::on_actionSaveAll_triggered() { int opentabindex = ui->tabWidget->currentIndex(); for (int i=0;i<ui->tabWidget->count();i++) { ui->tabWidget->setCurrentIndex(i); emit on_actionSave_triggered(); } ui->tabWidget->setCurrentIndex(opentabindex); } // exit void MainWindow::on_actionExit_triggered() { close(); } void MainWindow::printOutput(const QString &message, const QColor &color) { QTextCursor cursor = QTextCursor(ui->tOutput->document()); cursor.movePosition(QTextCursor::End); ui->tOutput->setTextCursor(cursor); ui->tOutput->setTextColor(color); ui->tOutput->insertPlainText(message); cursor.movePosition(QTextCursor::End); ui->tOutput->setTextCursor(cursor); } void MainWindow::printOutputWithTime(const QString &message, const QColor &color) { QTime currentTime = QTime::currentTime(); QString timeString = currentTime.toString("[HH:mm:ss.zzz] "); printOutput(timeString + message, color); } bool MainWindow::build(bool afterbuildthenrun, bool binary) { // if(ui->tabWidget->count()==0) return false; writeSettings(); OpenCode(); ui->dwOutput->show(); ui->dwIssues->show(); // If not kickass.jar file exists, app not responding if(!QFile::exists(pKickAssJar)) { printOutputWithTime("Kickass.jar file not exist. Check your settings.\n", QColor(0xf3, 0x34, 0x34)); return false; } //save all emit on_actionSaveAll_triggered(); if(pAssemblyFile.right(4).toLower() != ".asm") { printOutputWithTime("Assembly file not selected\n", QColor(0xf3, 0x34, 0x34)); return false; } // int crIndex = ui->tabWidget->currentIndex(); // Tab *tab = /*(Tab *)*/ static_cast<Tab*>( ui->tabWidget->widget(crIndex)); // QString filePath = tab->getCurrentFilePath(); filePath = QDir::cleanPath(workspacePath + QDir::separator() + pAssemblyFile); QFileInfo fi(filePath); QString ext = fi.completeSuffix(); // filePath = fi.filePath(); if(!((ext=="asm")||(ext=="s"))) { printOutputWithTime("Unable to build this file [" + pAssemblyFile + "]\n", QColor(0xf3, 0x34, 0x34)); return false; } QElapsedTimer timer; timer.start(); if ((filePath.isEmpty()) || (!fi.exists())) { ui->statusbar->showMessage("Build error", TIMEOUT); printOutputWithTime("File not found: " + filePath + "\n", QColor(0xf3, 0x34, 0x34)); } else { printOutputWithTime("Building for " + pAssemblyFile + "\n", Qt::darkGray); QCoreApplication::processEvents(); QProcess asmProcess; QString asmOutput = QDir::cleanPath(Common::appConfigDir() + QDir::separator() + "compileoutput.txt"); asmProcess.setStandardOutputFile(asmOutput); asmProcess.setStandardErrorFile(asmOutput, QIODevice::Append); asmProcess.setWorkingDirectory(fi.absolutePath()); QStringList asmArguments; asmArguments << "-jar" << pKickAssJar << filePath << "-cfgfile" << Common::appConfigDir()+"/ide65xx.cfg"; if(afterbuildthenrun) { QString tempEmulatorParameters = pEmulatorParameters; asmArguments << "-execute" << ((pEmulator.contains(".jar"))? pJRE + " -jar ": "") + pEmulator +" "+ tempEmulatorParameters.remove("<file>"); } if(binary) { asmArguments << "-binfile"; } QString cmd = pJRE; for(int c=0; c<asmArguments.length();c++) cmd+= " " + asmArguments[c]; printOutputWithTime(cmd+"\n", Qt::darkGray); asmProcess.start(pJRE, asmArguments); asmProcess.waitForFinished(); if (asmProcess.error() != QProcess::UnknownError) { printOutputWithTime("Unable to start assembler. Check your settings.\n", QColor(0xf3, 0x34, 0x34)); return false; } QFile logFile; logFile.setFileName(asmOutput); logFile.open(QIODevice::ReadOnly); QTextStream log(&logFile); tabifyDockWidget(ui->dwIssues, ui->dwOutput); clearIssues(); bool showmem = settingsWin->getCheckShowMemCmdLine(); ui->mvWarning->setVisible(!showmem); ui->memoryViewer->reset(); while(!log.atEnd()) { QString currentLine = log.readLine(); printOutput(currentLine+"\n", QColor(0x61, 0x61, 0xd0)); grabIssues(currentLine, log); if(showmem) grabMemoryView(currentLine, log); } logFile.close(); if(asmProcess.exitCode() == 0) { printOutputWithTime("Built successfully.\n", Qt::darkGreen); if(ui->dwMemoryViewer->isVisible()) memoryViewerCurrentCoordinateChanged(0, 0); if(ui->dwHexEditor->isVisible()) { curHexFilename = QDir::cleanPath(fi.absolutePath() + QDir::separator() + settingsWin->getBuildDir() + QDir::separator() + fi.fileName().remove(fi.completeSuffix()) + ((binary) ? "bin":"prg")); loadHexFile(); } } else printOutputWithTime("Error while building '" + filePath + "'\n", QColor(0xf3, 0x34, 0x34)); printOutputWithTime("Elapsed time: " + QString::number(timer.elapsed()) + " ms.\n", Qt::darkCyan); } return true; } void MainWindow::clearIssues() { while(ui->tIssues->rowCount()>0) ui->tIssues->removeRow(0); } void MainWindow::grabIssues(QString currentLine, QTextStream &tStr) { QString sIssue; QString sLine; QString sFilename; // Error: if(currentLine.left(6)=="Error:"){ // issue sIssue = currentLine; sIssue.remove("Error:"); currentLine = tStr.readLine(); printOutput(currentLine+"\n", QColor(0x61, 0x61, 0xd0)); if(currentLine.left(7)=="at line") { // line sLine = currentLine; sLine.remove("at line"); sLine = sLine.split(',')[0].trimmed(); // filename sFilename = currentLine.split(" in ")[1].trimmed(); } addIssue(sIssue, sFilename, sLine); } // Got ?? errors while executing: else if(currentLine.contains("errors while executing:")) { while(true) { currentLine = tStr.readLine(); printOutput(currentLine+"\n", QColor(0x61, 0x61, 0xd0)); if ((currentLine.trimmed()=="")||(currentLine.trimmed()=="...")) break; QStringList s1 = currentLine.split(')'); sIssue = s1[1].trimmed(); s1[0].remove("("); QStringList s2 = (s1[0].trimmed()).split(' '); sLine = (s2[s2.count()-1]).split(':')[0]; s1[0].remove(s2[s2.count()-1]); sFilename = s1[0].trimmed(); addIssue(sIssue, sFilename, sLine); } return; } // goto first issue in editor if(ui->tIssues->rowCount()>0) { ui->tIssues->selectRow(0); emit on_tIssues_cellDoubleClicked(0,0); } } void MainWindow::addIssue(QString issue, QString filename, QString line) { if((filename.contains("\\"))||(filename.contains("/"))) { filename.replace('\\','/'); } else { Tab *tab = static_cast<Tab*>( ui->tabWidget->widget(ui->tabWidget->currentIndex())); QFileInfo fi(tab->getCurrentFilePath()); filename = fi.absolutePath() + "/" + filename; filename.replace('\\','/'); } tabifyDockWidget(ui->dwOutput, ui->dwIssues); int lastRow = ui->tIssues->rowCount(); ui->tIssues->insertRow(lastRow); ui->tIssues->setItem(lastRow, 2, new QTableWidgetItem(line)); ui->tIssues->setItem(lastRow, 1, new QTableWidgetItem(filename + QString(10, ' '))); ui->tIssues->setItem(lastRow, 0, new QTableWidgetItem(issue.trimmed() + QString(10, ' '))); ui->tIssues->resizeColumnsToContents(); } void MainWindow::grabMemoryView(QString currentLine, QTextStream &tStr) { if(currentLine.contains("segment:")) { const QColor colors[4] = { QColor(0x00, 0x80, 0x80), QColor(0x00, 0x80, 0x00), QColor(0x00, 0x00, 0x80), QColor(0x80, 0x00, 0x00) }; int c = 0; while(true) { currentLine = tStr.readLine(); printOutput(currentLine+"\n", QColor(0x61, 0x61, 0xd0)); // $0801-$080c Basic if(currentLine.trimmed().isEmpty()) break; QStringList sl= currentLine.trimmed().split("-$"); bool Ok = false; int startAdr = sl[0].right(4).toInt(&Ok, 16); if(!Ok) break; int endAdr = sl[1].left(4).toInt(&Ok, 16); if(!Ok) break; ui->memoryViewer->poke(startAdr, endAdr, colors[c%4]); c++; } } } void MainWindow::prepareBeforeOpen(QString filename) { // is file opened? for (int i=0;i<ui->tabWidget->count();i++) { Tab *tabForOpened = static_cast<Tab*>(ui->tabWidget->widget(i)); if(tabForOpened->getCurrentFilePath() == filename) { ui->tabWidget->setCurrentIndex(i); return; } } // open file by extension with external app QFileInfo fi(filename); QString ext = fi.completeSuffix(); if( (ext=="asm")|| (ext=="lib")|| (ext=="inc")|| (ext=="txt")|| (ext=="sym")|| (ext=="dbg")|| (ext=="s")|| (ext=="a")|| (ext=="vs") ) { openFileFromPath(filename); SetCursorPos(); } } void MainWindow::saveUserCompleter() { QStringList strModelList = qobject_cast<QStringListModel*>(completer->model())->stringList(); // default + user completer words QFile fOut(QDir::cleanPath(Common::appConfigDir() + QDir::separator() + "userCompleter.dat")); if (fOut.open(QFile::WriteOnly | QFile::Text)) { QTextStream stream(&fOut); for (int i = 0; i < strModelList.size(); ++i) stream << strModelList.at(i) << '\n'; } fOut.close(); } void MainWindow::on_tIssues_cellDoubleClicked(int row, int column) { Q_UNUSED(column) quint64 line = ui->tIssues->item(row, 2)->text().toULongLong(); if(line < 1) return; QString filename = ui->tIssues->item(row, 1)->text().trimmed(); Tab *tab = nullptr; // is file opened? bool isopen = false; for (int i=0;i<ui->tabWidget->count();i++) { tab = static_cast<Tab*>(ui->tabWidget->widget(i)); if(tab->getCurrentFilePath() == filename) { ui->tabWidget->setCurrentIndex(i); isopen = true; break; } } if(!isopen) { openFileFromPath(filename); SetCursorPos(); tab = static_cast<Tab*>(ui->tabWidget->widget(ui->tabWidget->currentIndex())); } tab->code->moveCursor(QTextCursor::Start); for (quint64 i=0;i<line-1;i++) { tab->code->moveCursor(QTextCursor::Down); } tab->code->setFocus(); } void MainWindow::RefreshOpenDocuments() { int tc = ui->tabWidget->count(); ui->listOpenDocuments->clear(); opendocuments.clear(); if(tc<1) return; int selected = ui->tabWidget->currentIndex(); for(int i=0;i<tc;i++) opendocuments.append(ui->tabWidget->tabText(i)); ui->listOpenDocuments->addItems(opendocuments); ui->listOpenDocuments->setCurrentRow(selected); } // changed tab void MainWindow::on_tabWidget_currentChanged(int index) { setTopToolbar(index); ui->listOpenDocuments->setCurrentRow(index); SetCursorPos(); } // close find dialog void MainWindow::on_bFindClose_clicked() { ui->findDialog->setVisible(false); emit find(QString(), Qt::CaseSensitive, true, false); (static_cast<Tab*>( ui->tabWidget->currentWidget()))->code->setFocus(); } // disabled/enabled find/replace buttons void MainWindow::on_tFind_textChanged(const QString &arg1) { ui->bFindNext->setEnabled(!arg1.isEmpty()); ui->bFindAll->setEnabled(!arg1.isEmpty()); ui->bReplace->setEnabled(!arg1.isEmpty()); ui->bReplaceAll->setEnabled(!arg1.isEmpty()); } void MainWindow::find(const QString &pattern, Qt::CaseSensitivity cs, bool all, bool replace, const QString &replaceText) { // Clear all highlights and disable highlighting of current line for (int i = 0; i < ui->tabWidget->count(); i++) { CodeEditor *code = (static_cast<Tab*>( ui->tabWidget->widget(i))->code); disconnect(code, SIGNAL(cursorPositionChanged()), code, SLOT(highlightCurrentLine())); code->setExtraSelections(QList<QTextEdit::ExtraSelection>()); } // Restore highlight if (pattern.isEmpty()) { for (int i = 0; i < ui->tabWidget->count(); i++) { CodeEditor *code = (static_cast<Tab*>( ui->tabWidget->widget(i))->code); connect(code, SIGNAL(cursorPositionChanged()), code, SLOT(highlightCurrentLine())); code->highlightCurrentLine(); } } else { //If true, find all if (all) { for (int i = 0; i < ui->tabWidget->count(); i++) { QTextEdit::ExtraSelection selection; QList<QTextEdit::ExtraSelection> extraSelections; selection.format.setBackground(QBrush(Qt::green)); QTextDocument *document = (static_cast<Tab*>( ui->tabWidget->widget(i)))->getCodeDocument(); QTextCursor newCursor = QTextCursor(document); CodeEditor *code = (static_cast<Tab*>( ui->tabWidget->widget(i))->code); while (!newCursor.isNull() && !newCursor.atEnd()) { if (cs == Qt::CaseSensitive) newCursor = document->find(pattern, newCursor, QTextDocument::FindCaseSensitively); else newCursor = document->find(pattern, newCursor); // Replace mode if (replace && i == ui->tabWidget->currentIndex()) { //newCursor.removeSelectedText(); newCursor.insertText(replaceText); } if (!newCursor.isNull()) { selection.cursor = newCursor; extraSelections.append(selection); } } // Highlight all code->setExtraSelections(extraSelections); } } //Find next only else { QTextEdit::ExtraSelection selection; QList<QTextEdit::ExtraSelection> extraSelections; selection.format.setBackground(QBrush(Qt::green)); QTextDocument *document = (static_cast<Tab*>( ui->tabWidget->currentWidget()))->getCodeDocument(); CodeEditor *code = (static_cast<Tab*>( ui->tabWidget->currentWidget()))->code; static QTextCursor newCursor(document); // if documents differ, cursor is ignored in QTextDocument::find() if (replace) { //newCursor.removeSelectedText(); newCursor.insertText(replaceText); } if (cs == Qt::CaseSensitive) newCursor = document->find(pattern, newCursor, QTextDocument::FindCaseSensitively); else newCursor = document->find(pattern, newCursor); // Continue from start if (newCursor.isNull()) { if (cs == Qt::CaseSensitive) newCursor = document->find(pattern, newCursor, QTextDocument::FindCaseSensitively); else newCursor = document->find(pattern, newCursor); } if (!newCursor.isNull()) { selection.cursor = newCursor; extraSelections.append(selection); QTextCursor cursor = newCursor; cursor.clearSelection(); code->setTextCursor(cursor); } code->setExtraSelections(extraSelections); } } } void MainWindow::ExecuteAppWithFile(QString pApplication, QString additionalArgs) { if(!QFile::exists(pApplication)) { QMessageBox::information(this, "Error?", "Application not found. Check your settings.", QMessageBox::Ok); return; } QCoreApplication::processEvents(); printOutputWithTime(pApplication +" ", Qt::darkGray); if(additionalArgs.isEmpty()) { printOutput(" "+filePath+"\n", Qt::darkGray); p.startDetached(pApplication, QStringList() << filePath); } else { QStringList parameters; QFileInfo fi(filePath); parameters = additionalArgs.split(' '); for(int i=0;i<parameters.length();i++) { // compress if(parameters[i].contains("<infile>")) parameters[i] = parameters[i].replace("<infile>", filePath); if(parameters[i].contains("<outfile>")) { parameters[i] = parameters[i].replace("<outfile>", fi.filePath().remove(fi.fileName())+fi.baseName()+"-compressed.prg"); } // create d64 via c1541 if(parameters[i].contains("<name>")) parameters[i] = parameters[i].replace("<name>", fi.baseName()); if(parameters[i].contains("<pathname>")) { parameters[i] = parameters[i].replace("<pathname>", fi.filePath().remove(fi.fileName())+fi.baseName()); } if(parameters[i].contains("<dbgname>")) { // int crIndex = ui->tabWidget->currentIndex(); // Tab *tab = /*(Tab *)*/ static_cast<Tab*>( ui->tabWidget->widget(crIndex)); // QString filePath = tab->getCurrentFilePath(); QSettings cmdline(Common::appConfigDir()+"/cmdline.ini", QSettings::IniFormat); QFileInfo fid(QDir::cleanPath(workspacePath + QDir::separator() + pAssemblyFile)); QString fOutDir = ""; if(cmdline.value("odir", false).toBool()) fOutDir = cmdline.value("odirtext", "build").toString()+"/"; parameters[i] = parameters[i].replace("<dbgname>", fid.filePath().remove(fid.fileName())+fOutDir+fid.baseName()); } // sid player if(parameters[i].contains("<sidfile>")) { parameters[i] = parameters[i].replace("<sidfile>", filePath); } // emulator parameters if(parameters[i].contains("<file>")) { parameters[i] = parameters[i].replace("<file>", filePath); } printOutput(parameters[i]+" ", Qt::darkGray); } printOutput("\n", Qt::darkGray); // If pApplication is JAR file if(pApplication.contains(".jar")) { parameters.prepend(pApplication); parameters.prepend("-jar"); pApplication = pJRE; } p.startDetached(pApplication, parameters); } } QAbstractItemModel *MainWindow::modelFromFile(const QString &fileName) { QFile file(fileName); if (!file.open(QFile::ReadOnly)) return new QStringListModel(completer); #ifndef QT_NO_CURSOR QGuiApplication::setOverrideCursor(QCursor(Qt::WaitCursor)); #endif QStringList words; while (!file.atEnd()) { QByteArray line = file.readLine(); if (!line.isEmpty()) words << QString::fromUtf8(line.trimmed()); } #ifndef QT_NO_CURSOR QGuiApplication::restoreOverrideCursor(); #endif return new QStringListModel(words, completer); } void MainWindow::HideDocks() { //dockState = saveState(); ui->dwOutput->setVisible(false); ui->dwIssues->setVisible(false); ui->dwProjectExplorer->setVisible(false); ui->dwOpenDocument->setVisible(false); ui->dwBookmarks->setVisible(false); ui->dwHexEditor->setVisible(false); ui->dwMemoryViewer->setVisible(false); ui->menuView->menuAction()->setVisible(false); ui->menuEdit->menuAction()->setVisible(false); setActionsEnable(false); statusCurPosInfo->setVisible(false); } void MainWindow::RestoreDocks() { //restoreState(dockState); const QVariant state = settings.value("DockState"); if (state.isValid()) { restoreState(state.toByteArray()); } ui->menuView->menuAction()->setVisible(true); if(ui->tabWidget->count()>0) { ui->menuEdit->menuAction()->setVisible(true); statusCurPosInfo->setVisible(true); setActionsEnable(true); } } // Run in emulator void MainWindow::RunInEmulator() { ExecuteAppWithFile(pEmulator, pEmulatorParameters); } // Compress prg void MainWindow::Compress() { ExecuteAppWithFile(pCompressionUtility, pCompressionParameters); } // open prg, d64, d71, d81 via dirmaster void MainWindow::OpenWithDirMaster() { ExecuteAppWithFile(pDirMaster); } void MainWindow::PlayWithSIDPlayer() { ExecuteAppWithFile(pSIDPlayer, pSIDPlayerParameters); } // create d64 from prg via c1541 void MainWindow::CreateD64Image() { ExecuteAppWithFile(pC1541, "-format \"<name>,01\" d64 <pathname>.d64 -attach <pathname>.d64 -write <pathname>.prg <name>"); } void MainWindow::RemoveFileOrFolder() { if(!selectedIndex.isValid()) return; QFileInfo fileinfo (filePath); if(fileinfo.isFile()) { int ret = QMessageBox::question(this, "Are you sure?", "Remove file [" + filePath + "]?", QMessageBox::Yes | QMessageBox::No, QMessageBox::No); if (ret == QMessageBox::Yes) { QFile file (filePath); for (int i=0;i<ui->tabWidget->count();i++) { Tab *tabForOpened = static_cast<Tab*>(ui->tabWidget->widget(i)); if(tabForOpened->getCurrentFilePath() == filePath) { closeFile(i); break; } } if(file.remove()) { ui->statusbar->showMessage("File removed", TIMEOUT); } } } else if(fileinfo.isDir()) { int ret = QMessageBox::question(this, "Are you sure?", "Remove Directory [" + filePath + "]?", QMessageBox::Yes | QMessageBox::No, QMessageBox::No); if (ret == QMessageBox::Yes) { QDir(filePath).removeRecursively(); } } } void MainWindow::Rename() { if(!selectedIndex.isValid()) return; QFileInfo fileinfo (filePath); bool ok; QString text; if(fileinfo.isFile()) { text = QInputDialog::getText(this, "Rename File?", "File: "+fileinfo.fileName()+"\nEnter new filename:", QLineEdit::Normal, fileinfo.fileName(), &ok); if (ok && !text.isEmpty()) { QFile file (filePath); for (int i=0;i<ui->tabWidget->count();i++) { Tab *tabForOpened = static_cast<Tab*>(ui->tabWidget->widget(i)); if(tabForOpened->getCurrentFilePath() == filePath) { closeFile(i); break; } } if(file.rename(fileinfo.absolutePath()+"/"+text)) ui->statusbar->showMessage("Filename Changed", TIMEOUT); else ui->statusbar->showMessage("Filename Not Changed", TIMEOUT); } } else if(fileinfo.isDir()) { text = QInputDialog::getText(this, "Rename Folder?", "Folder: "+fileinfo.fileName()+"\nEnter new name of the directory:", QLineEdit::Normal, fileinfo.fileName(), &ok); if (ok && !text.isEmpty()) { if(QDir(filePath).rename(fileinfo.absoluteFilePath(), fileinfo.dir().absolutePath() +"/"+ text)) ui->statusbar->showMessage("Name Of The Directory Changed", TIMEOUT); else ui->statusbar->showMessage("Name Of The Directory Not Changed", TIMEOUT); } } } void MainWindow::OpenWithHexEditor() { curHexFilename = filePath; loadHexFile(); ui->dwHexEditor->show(); ui->statusbar->showMessage("Hex file loaded", TIMEOUT); } void MainWindow::SetAssemblyFile() { pAssemblyFile = filePath.remove(workspacePath); ui->lAssemblyFile->setText(pAssemblyFile); settings.setValue("AssemblyFile", pAssemblyFile); settings.sync(); } void MainWindow::ConvertToCrt() { cc->setPrgFilePath(filePath); QFileInfo fi(filePath); cc->setCartName(fi.fileName().remove("."+fi.completeSuffix())); emit on_actionCartridge_Conversion_Utility_triggered(); } void MainWindow::OpenCode() { RestoreDocks(); ui->stackedWidget->setCurrentWidget(ui->pCode); } void MainWindow::OpenHome() { if(ui->stackedWidget->currentWidget() == ui->pCode) HideDocks(); ui->stackedWidget->setCurrentWidget(ui->pHome); } void MainWindow::OpenHelp() { if(ui->stackedWidget->currentWidget() == ui->pCode) HideDocks(); ui->stackedWidget->setCurrentWidget(ui->pHelp); } void MainWindow::removeBookmark() { // show tab->code int crIndex = ui->tabWidget->currentIndex(); emit bookmarkClicked(bookmarks->selectionModel()->currentIndex()); int selectedindex = bookmarks->currentIndex().row(); quint64 lnum = bookmarks->getLineNumber(selectedindex); Tab *tab = /*(Tab *)*/ static_cast<Tab*>( ui->tabWidget->widget(ui->tabWidget->currentIndex())); if(tab->code->bookmarks.contains(lnum)) { tab->code->bookmarks.removeOne(lnum); tab->code->update(); bookmarks->removeItem(selectedindex); } ui->tabWidget->setCurrentIndex(crIndex); } void MainWindow::removeAllBookmark() { Tab *tab = nullptr;// = /*(Tab *)*/ static_cast<Tab*>( ui->tabWidget->widget(ui->tabWidget->currentIndex())); for (int i=0;i<ui->tabWidget->count();i++) { tab = static_cast<Tab*>( ui->tabWidget->widget(i)); tab->code->bookmarks.clear(); tab->code->update(); } bookmarks->removeAll(); } void MainWindow::editBookmark() { bool ok; int crBookmarkIndex = bookmarks->currentIndex().row(); QString text = QInputDialog::getText(this, tr("Edit Bookmark"), tr("Note text:"), QLineEdit::Normal, bookmarks->getItemText(crBookmarkIndex), &ok); if (ok && !text.isEmpty()) bookmarks->setItemText(crBookmarkIndex, text); } void MainWindow::bookmarkClicked(const QModelIndex &index) { Q_UNUSED(index) //qDebug() << index.data().toString(); //qDebug() << QString::number(bookmarks->getLineNumber(bookmarks->currentIndex().row())); //qDebug() << bookmarks->getFilepath(bookmarks->currentIndex().row()); int bookmarksCurrentIndex = bookmarks->currentIndex().row(); quint64 bLineNumber = bookmarks->getLineNumber(bookmarksCurrentIndex); QString bFilePath = bookmarks->getFilepath(bookmarksCurrentIndex); if(!QFile::exists(workspacePath + bFilePath)) { bookmarks->removeItem(bookmarksCurrentIndex); return; } Tab *tab = nullptr; bool opened = false; // if have opened tab if(ui->tabWidget->count()>0) { for (int i=0;i<ui->tabWidget->count();i++) { tab = static_cast<Tab*>(ui->tabWidget->widget(i)); if(tab->getCurrentFilePath() == workspacePath + bFilePath) { ui->tabWidget->setCurrentIndex(i); opened = true; break; } } } if(!opened){ openFileFromPath(workspacePath + bFilePath); SetCursorPos(); tab = static_cast<Tab*>(ui->tabWidget->widget(ui->tabWidget->currentIndex())); } ui->tabWidget->setTabIcon(ui->tabWidget->currentIndex(), bookmarks->getIcon(bookmarksCurrentIndex)); tab->code->moveCursor(QTextCursor::Start); for (quint64 i=0;i<bLineNumber-1;i++) { tab->code->moveCursor(QTextCursor::Down); } tab->code->setFocus(); } void MainWindow::updateLineNumberSlot(quint64 currentLine, int delta) { int crIndex = ui->tabWidget->currentIndex(); Tab *tab = /*(Tab *)*/ static_cast<Tab*>( ui->tabWidget->widget(crIndex)); QString topTextFilePath = tab->getCurrentFilePath().remove(workspacePath); if(delta<0) { for(int i=0;i<bookmarks->model()->rowCount();i++) { if(bookmarks->getFilepath(i) == topTextFilePath) { quint64 bline = bookmarks->getLineNumber(i); if((bline < (currentLine - delta))&&(bline > currentLine)) { bookmarks->removeItem(i); tab->code->bookmarks.removeOne(bline); i--; } } } } for(int i=0;i<bookmarks->model()->rowCount();i++) { if(bookmarks->getFilepath(i) == topTextFilePath) { quint64 bline = bookmarks->getLineNumber(i); if(bline >= ( (delta>0) ? currentLine-1 : currentLine )) { QString topText = QString::number(bline + delta) + " : " + topTextFilePath; bookmarks->setTopText(i, topText); tab->code->bookmarks.removeOne(bline); tab->code->bookmarks.append(bline + delta); } } } tab->code->update(); } void MainWindow::bookmarksChangedSlot(quint64 lineNumber, QString text, bool isAdded) { int crIndex = ui->tabWidget->currentIndex(); Tab *tab = /*(Tab *)*/ static_cast<Tab*>( ui->tabWidget->widget(crIndex)); QString topTextFilePath = tab->getCurrentFilePath().remove(workspacePath); // add/remove bookmark if(isAdded) { QPixmap icon = ui->tabWidget->tabIcon(crIndex).pixmap(24,24); QString topText = QString::number(lineNumber) + " : " + topTextFilePath; bookmarks->addItem(icon, text, topText); ui->dwBookmarks->show(); // show bookmark dockwidget only } else { for(int i=0;i<bookmarks->model()->rowCount();i++) { if(bookmarks->getFilepath(i) == topTextFilePath) { if(bookmarks->getLineNumber(i)== lineNumber) { bookmarks->removeItem(i); break; } } } } } void MainWindow::memoryViewerCurrentCoordinateChanged(int x, int y) { lastMemoryViewX = x; lastMemoryViewY = y; if((x>ui->sbMemoryViewer->value())||(y>0x10000/ui->sbMemoryViewer->value())) return; int zoom = ui->horizontalSlider->value(); int zww = ui->scaledMemoryViewer->width(); int zwh = ui->scaledMemoryViewer->height(); int zw = zww / zoom; int zh = zwh / zoom; int zx = x - zw / 2; int zy = y - zh / 2; if (zx < 0) zx = 0; if (zy < 0) zy = 0; QPixmap px = ui->memoryViewer->grab(QRect(zx, zy, zw, zh)); if (sbMemoryViewerValueNotChanged) { QPainter painter(&px); painter.setPen(QColor(0xff, 0x00, 0xff)); painter.drawPoint(x-zx,y-zy); painter.end(); } else { sbMemoryViewerValueNotChanged = true; } ui->scaledMemoryViewer->setPixmap(px.scaled(zww, zwh, Qt::KeepAspectRatioByExpanding)); } void MainWindow::ReceiveLineForCompleter(QString line) { QString newLine = line.replace('\t', ' ').replace(':', ' ').replace('#', ' ').replace('$', ' ').replace('.', ' ').replace('/', ' ').replace('*', ' ').replace('"', ' ').trimmed(); QStringList newWords = newLine.split(' '); QStringListModel *strModel = qobject_cast<QStringListModel*>(completer->model()); if(strModel!=NULL) { for(int i=0;i<newWords.length();i++) { bool matched = false; foreach(QString str, strModel->stringList()) { if(str==newWords[i]) { matched = true; break; } } if(!matched) { // adding new word to your completer list strModel->setStringList(strModel->stringList() << newWords[i]); } } } } void MainWindow::memoryViewerCurrentAddressChanged(int) { ui->lCurrentAddress->setText(ui->memoryViewer->getCurrentAddressString().toUpper()); } // Debugger (vice or c64debuggger) void MainWindow::on_actionDebugger_triggered() { QFileInfo debuggerApp(pDebugger); QString dName = debuggerApp.baseName(); QString dArgs = ""; if(dName.left(3)=="C64") dArgs = "-autojmp -layout 10 -symbols <dbgname>.vs -wait 2500 -prg <dbgname>.prg"; // c64 debugger if(dName.left(3)=="x64") dArgs = "-moncommands <dbgname>.vs <dbgname>.prg"; // vice if((debuggerApp.isFile())&&(!dArgs.isEmpty())) { bool preDebugDump = settingsWin->getCmdLineDebugDump(); bool preViceSymbols = settingsWin->getCmdLineViceSymbols(); settingsWin->setCmdLinesEnabledForDebug(); if(build()) { printOutputWithTime("Starting Debugger ... \n", Qt::darkCyan); ExecuteAppWithFile(pDebugger, dArgs); settingsWin->setCmdLinesEnabledForDebug(preDebugDump, preViceSymbols); } } else { printOutputWithTime("Unable to start debugger application. Check your settings.\n", QColor(0xf3, 0x34, 0x34)); } } void MainWindow::on_bFindNext_clicked() { emit find(ui->tFind->text(), ui->cMatchCase->isChecked() ? Qt::CaseSensitive : Qt::CaseInsensitive, false, false); } void MainWindow::on_bFindAll_clicked() { emit find(ui->tFind->text(), ui->cMatchCase->isChecked() ? Qt::CaseSensitive : Qt::CaseInsensitive, true, false); } void MainWindow::on_bReplace_clicked() { emit find(ui->tFind->text(), ui->cMatchCase->isChecked() ? Qt::CaseSensitive : Qt::CaseInsensitive, false, true, ui->tReplace->text()); } void MainWindow::on_bReplaceAll_clicked() { emit find(ui->tFind->text(), ui->cMatchCase->isChecked() ? Qt::CaseSensitive : Qt::CaseInsensitive, true, true, ui->tReplace->text()); } void MainWindow::on_actionSettings_triggered() { readSettingsOptionsOnly(); settingsWin->ReadCmdLineOption(); settingsWin->restartRequired = false; if(settingsWin->exec() == QDialog::Accepted) { writeSettings(); // if tab has opened source for (int i = 0; i < ui->tabWidget->count(); i++) { Tab *tab = static_cast<Tab*>( ui->tabWidget->widget(i)); QTextOption option; if(pShowAllChars) option.setFlags(QTextOption::ShowLineAndParagraphSeparators | QTextOption::ShowTabsAndSpaces | QTextOption::ShowDocumentTerminator); option.setWrapMode((pWordWrap)? QTextOption::WordWrap : QTextOption::NoWrap); QFontMetrics fm(tab->code->font()); option.setTabStopDistance(fm.horizontalAdvance(' ')*pTabSize); tab->code->document()->setDefaultTextOption(option); tab->code->setShowAllChars(pShowAllChars); tab->code->setAutoCompletion(pAutoCompletion); tab->code->setFont(QFont(pCodeFontName, pCodeFontSize)); tab->code->setTabSpace((pTabPolicy==0)?true:false); tab->code->setTabSpaceCount(pTabSize); } // restart required? if(settingsWin->restartRequired) { if(QMessageBox::question(this,"Restart?", "Restart the IDE 65XX application for this change to take effect?")==QMessageBox::Yes) { qApp->quit(); QProcess::startDetached(qApp->arguments()[0], QStringList() << "restart");//application restart } settingsWin->restartRequired = false; } } } void MainWindow::writeSettings() { // Size, Pos settings.setValue("AppSize", this->size()); settings.setValue("AppPos", this->pos()); // Dockstate settings.setValue("DockState", this->saveState()); // Open Files QStringList files; for (int i = 0; i < ui->tabWidget->count(); i++) { Tab *tab = static_cast<Tab*>( ui->tabWidget->widget(i)); files << tab->getCurrentFilePath(); } settings.setValue("OpenFiles", QVariant::fromValue(files)); // workspace settings.setValue("Workspace", workspacePath); settings.setValue("AssemblyFile", pAssemblyFile); // kits pJRE = settingsWin->getJRE(); settings.setValue("JRE", pJRE); pKickAssJar = settingsWin->getKickAssJar(); settings.setValue("KickAssJar", pKickAssJar); // kickass.cfg would be empty QString KickAssJarCopy = pKickAssJar; QFile file(KickAssJarCopy.remove(".jar", Qt::CaseInsensitive) + ".cfg"); if (file.open(QIODevice::WriteOnly | QIODevice::Text)) { QTextStream out(&file); out << "# KickAss.cfg is changed by IDE 65XX\n"; file.close(); } pEmulator = settingsWin->getEmulator(); settings.setValue("Emulator", pEmulator); pEmulatorParameters = settingsWin->getEmulatorParameters(); settings.setValue("EmulatorParameters", pEmulatorParameters); pCompressionUtility = settingsWin->getCompressionUtility(); settings.setValue("CompressionUtility", pCompressionUtility); pDirMaster = settingsWin->getDirMaster(); settings.setValue("DirMaster", pDirMaster); pCompressionParameters = settingsWin->getCompressionParameters(); settings.setValue("CompressionParameters", pCompressionParameters); pSIDPlayerParameters = settingsWin->getSIDPlayerParameters(); settings.setValue("SIDPlayerParameters", pSIDPlayerParameters); pSIDPlayer = settingsWin->getSIDPlayer(); settings.setValue("SIDPlayer", pSIDPlayer); pCartconv = settingsWin->getCartconv(); settings.setValue("CartConv", pCartconv); pC1541 = settingsWin->getC1541(); settings.setValue("C1541", pC1541); pDebugger = settingsWin->getDebugger(); settings.setValue("Debugger", pDebugger); //---- general ---- pOpenLastUsedFiles = settingsWin->getOpenLastUsedFiles(); settings.setValue("OpenLastUsedFiles", pOpenLastUsedFiles); pMaxRecentWorkspace = settingsWin->getMaxRecentWorkspace(); settings.setValue("MaxRecentWorkspace", pMaxRecentWorkspace); pTabSize = settingsWin->getTabSize(); settings.setValue("TabSize", pTabSize); pTabPolicy = settingsWin->getTabPolicy(); settings.setValue("TabPolicy", pTabPolicy); pAutoCompletion = settingsWin->getAutoCompletion(); settings.setValue("AutoCompletion", pAutoCompletion); pCodeFontName = settingsWin->getCodeFontName(); settings.setValue("CodeFontName", pCodeFontName); pCodeFontSize = settingsWin->getCodeFontSize(); settings.setValue("CodeFontSize", pCodeFontSize); pWordWrap = settingsWin->getWordWrap(); settings.setValue("WordWrap", pWordWrap); pShowAllChars = settingsWin->getShowAllCharacters(); settings.setValue("ShowAllChars", pShowAllChars); settings.sync(); //bookmark list saved to ini file int bookmarkCount = bookmarks->model()->rowCount(); bookmarkcfgfile.clear(); bookmarkcfgfile.setValue("Count", bookmarkCount); // Count: bookmark count bookmarkcfgfile.setValue("0", workspacePath); // 0: workspace, 1...oo line|relative-file-path if(bookmarkCount>0) { for (int i=0;i<bookmarkCount;i++) { bookmarkcfgfile.setValue(QString::number(i+1), QString("%1|%2|%3").arg(bookmarks->getLineNumber(i)).arg(bookmarks->getFilepath(i)).arg(bookmarks->getItemText(i))); } } bookmarkcfgfile.sync(); } void MainWindow::readSettings() { // pos, Size resize(settings.value("AppSize", QSize(WINDOW_WIDTH, WINDOW_HEIGHT)).toSize()); move(settings.value("AppPos", QPoint(100,100)).toPoint()); // Dockstate const QVariant state = settings.value("DockState"); if (state.isValid()) { restoreState(state.toByteArray()); } // workspace QString strWorkspace = settings.value("Workspace").toString(); pOpenLastUsedFiles = settings.value("OpenLastUsedFiles", true).toBool(); settingsWin->setOpenLastUsedFiles(pOpenLastUsedFiles); const QStringList files = settings.value("OpenFiles").toStringList(); bWelcome = files.count() < 1; // Open Files if(strWorkspace != "?") { if(pOpenLastUsedFiles) { openWorkspace(strWorkspace); QTimer::singleShot(100, [=] { foreach (const QString &file, files) { if (QFile::exists(file)) { filePath=file; openFileFromPath(file); } } }); setActionsEnable(true); } } else { setActionsEnable(false); } readSettingsOptionsOnly(); } void MainWindow::readSettingsOptionsOnly() { //---- kits ---- pJRE = settings.value("JRE", #ifdef Q_OS_WIN "java.exe" #else "java" #endif ).toString(); settingsWin->setJRE(pJRE); pKickAssJar = settings.value("KickAssJar", "KickAss.jar").toString(); settingsWin->setKickAssJar(pKickAssJar); pEmulator = settings.value("Emulator", #ifdef Q_OS_WIN "x64.exe" #else "x64" #endif ).toString(); settingsWin->setEmulator(pEmulator); pEmulatorParameters = settings.value("EmulatorParameters", "<file>").toString(); settingsWin->setEmulatorParameters(pEmulatorParameters); pCompressionUtility = settings.value("CompressionUtility", #ifdef Q_OS_WIN "exomizer.exe" #else "exomizer" #endif ).toString(); settingsWin->setCompressionUtility(pCompressionUtility); pDirMaster = settings.value("DirMaster", "DirMaster.exe").toString(); settingsWin->setDirMaster(pDirMaster); pCompressionParameters = settings.value("CompressionParameters", "sfx basic -n <infile> -o <outfile>").toString(); settingsWin->setCompressionParameters(pCompressionParameters); pC1541 = settings.value("C1541", #ifdef Q_OS_WIN "c1541.exe" #else "c1541" #endif ).toString(); settingsWin->setC1541(pC1541); pDebugger = settings.value("Debugger", #ifdef Q_OS_WIN "x64.exe" #else "x64" #endif ).toString(); pAssemblyFile = settings.value("AssemblyFile").toString(); ui->lAssemblyFile->setText(pAssemblyFile); settingsWin->setDebugger(pDebugger); pMaxRecentWorkspace = settings.value("MaxRecentWorkspace", 10).toInt(); settingsWin->setMaxRecentWorkspace(pMaxRecentWorkspace); pTabSize = settings.value("TabSize", 4).toInt(); settingsWin->setTabSize(pTabSize); pTabPolicy = settings.value("TabPolicy", 0).toInt(); settingsWin->setTabPolicy(pTabPolicy); pAutoCompletion = settings.value("AutoCompletion", true).toBool(); settingsWin->setAutoCompletion(pAutoCompletion); pCodeFontName = settings.value("CodeFontName", "Ubuntu Mono").toString(); settingsWin->setCodeFontName(pCodeFontName); pCodeFontSize = settings.value("CodeFontSize", 12).toInt(); settingsWin->setCodeFontSize(pCodeFontSize); settingsWin->setApplicationFont(settings.value("ApplicationFontName", "Ubuntu Mono").toString(), settings.value("ApplicationFontSize", 12).toInt()); settingsWin->setApplicationTheme(settings.value("ApplicationStyle", 3).toInt()); pWordWrap = settings.value("WordWrap", false).toBool(); settingsWin->setWordWrap(pWordWrap); pShowAllChars = settings.value("ShowAllChars", false).toBool(); settingsWin->setShowAllCharacters(pShowAllChars); pSIDPlayer = settings.value("SIDPlayer", #ifdef Q_OS_WIN "vsid.exe" #else "vsid" #endif ).toString(); settingsWin->setSIDPlayer(pSIDPlayer); pSIDPlayerParameters = settings.value("SIDPlayerParameters", "<sidfile>").toString(); settingsWin->setSIDPlayerParameters(pSIDPlayerParameters); pCartconv = settings.value("CartConv", #ifdef Q_OS_WIN "cartconv.exe" #else "cartconv" #endif ).toString(); settingsWin->setCartconv(pCartconv); // custom style settingsWin->setCustomBackgroundTexture(settings.value("CustomBackgroundTexture", ":/res/style/commodore_background.png").toString()); settingsWin->setCustomButtonTexture(settings.value("CustomButtonTexture", ":/res/style/commodore_button.png").toString()); settingsWin->setBackground(settings.value("CustomBackground", QColor(0xf0, 0xf0, 0xf0)).value<QColor>()); settingsWin->setBrightText(settings.value("CustomBrightText", QColor(255,255,255)).value<QColor>()); settingsWin->setBase(settings.value("CustomBase", QColor(0xc7, 0xc9, 0xcd)).value<QColor>()); settingsWin->setHighlights(settings.value("CustomHighlights", QColor(0xb1, 0xb1, 0xb1)).value<QColor>()); settingsWin->setDisable(settings.value("CustomDisable", QColor(64,64,64)).value<QColor>()); settingsWin->setOpcode(settings.value("CustomOpcode", QColor(0x61, 0x61, 0xd0)).value<QColor>()); settingsWin->setNumber(settings.value("CustomNumber", QColor(0x00, 0x80, 0x80)).value<QColor>()); settingsWin->setFunction(settings.value("CustomFunction", QColor(0xaf, 0x64, 0x00)).value<QColor>()); settingsWin->setAssemblerDir(settings.value("CustomAssemblerDir", QColor(0xaf, 0x64, 0x00)).value<QColor>()); settingsWin->setPreprocessorDir(settings.value("CustomPreprocessorDir", QColor(0x00, 0x80, 0x00)).value<QColor>()); settingsWin->setComment(settings.value("CustomComment", QColor(0x80, 0x80, 0x80)).value<QColor>()); settingsWin->setQuotation(settings.value("CustomQuotation", QColor(0x00, 0x80, 0x00)).value<QColor>()); settingsWin->setLabel(settings.value("CustomLabel", QColor(0xc3, 0x34, 0x34)).value<QColor>()); } // About void MainWindow::on_actionAbout_triggered() { About ad(this); ad.exec(); } // Build this void MainWindow::on_actionBuild_this_triggered() { build(); } // Build & Run void MainWindow::on_actionBuild_and_Run_triggered() { build(true); } // Build as binary void MainWindow::on_actionBuild_as_binary_triggered() { build(false, true); } // file contextmenu on treeview void MainWindow::on_tvWorkspaceFiles_customContextMenuRequested(const QPoint &pos) { QModelIndex index = ui->tvWorkspaceFiles->indexAt(pos); if (index.isValid()) { filePath = m_ptrModelForTree->filePath(index); selectedIndex = index; tabicon = m_ptrModelForTree->fileIcon(index); menuC1541->setVisible(false); menuEmulator->setVisible(false); menuExomizer->setVisible(false); menuDirmaster->setVisible(false); menuSidPlayer->setVisible(false); menuHexEditor->setVisible(false); menuAssemblyFile->setVisible(false); menuCartConv->setVisible(false); QFileInfo fi(filePath); QString ext = fi.completeSuffix(); if(fi.isFile()) { menuDelete->setText("Delete File"); menuRename->setText("Rename file"); } else { menuDelete->setText("Delete Folder"); menuRename->setText("Rename Directory"); } if((ext=="prg")||(ext=="bin")) { menuC1541->setVisible(true); menuEmulator->setVisible(true); menuExomizer->setVisible(true); menuDirmaster->setVisible(true); menuHexEditor->setVisible(true); } if(ext=="prg") // only prg { menuCartConv->setVisible(true); } if(ext=="sid") { menuSidPlayer->setVisible(true); } if((ext=="d64")||(ext=="d71")||(ext=="d81")) { menuEmulator->setVisible(true); menuDirmaster->setVisible(true); } if(ext=="asm") { menuAssemblyFile->setVisible(true); } if(ext=="crt") { menuEmulator->setVisible(true); menuHexEditor->setVisible(true); } fileContextMenu->exec(ui->tvWorkspaceFiles->viewport()->mapToGlobal(pos)); } } void MainWindow::on_bDescription_clicked() { ui->brHelp->setSource(QUrl("help.htm#description")); } void MainWindow::on_bIllegal_clicked() { ui->brHelp->setSource(QUrl("help.htm#illegal")); } void MainWindow::on_bStandard_clicked() { ui->brHelp->setSource(QUrl("help.htm#standart")); } void MainWindow::on_b65C02opcodes_clicked() { ui->brHelp->setSource(QUrl("help.htm#65c02opcodes")); } void MainWindow::on_bAssemblerDirectives_clicked() { ui->brHelp->setSource(QUrl("help.htm#AssemblerDirectives")); } void MainWindow::on_bPreprocessorDirectives_clicked() { ui->brHelp->setSource(QUrl("help.htm#PreprocessorDirectives")); } void MainWindow::on_bValueTypes_clicked() { ui->brHelp->setSource(QUrl("help.htm#ValueTypes")); } void MainWindow::on_bStandardMacros_clicked() { ui->brHelp->setSource(QUrl("help.htm#StandardMacros")); } void MainWindow::on_actionGenerate_File_Directive_triggered() { TFileDirective fd(this); fd.exec(); QString strFd = fd.getFileDirective(); fd.deleteLater(); if(strFd.isEmpty()) return; insertCode(strFd, QTextCursor::Left); } void MainWindow::on_actionGenerate_Disk_Directive_triggered() { TDiskDirective dd(this); dd.exec(); QString strDd = dd.getDiskDirective(); dd.deleteLater(); if(strDd.isEmpty()) return; insertCode(strDd); } void MainWindow::insertCode(QString code, QTextCursor::MoveOperation operation) { Tab *tab = static_cast<Tab*>( ui->tabWidget->widget(ui->tabWidget->currentIndex())); QTextCursor tmpCursor = tab->code->textCursor(); tmpCursor.movePosition(operation, QTextCursor::MoveAnchor, tmpCursor.columnNumber()); tab->code->setTextCursor(tmpCursor); tab->code->insertPlainText(code); } void MainWindow::on_listOpenDocuments_itemSelectionChanged() { ui->tabWidget->setCurrentIndex(ui->listOpenDocuments->currentRow()); } void MainWindow::on_actionKick_Assembler_Web_Manual_triggered() { QDesktopServices::openUrl(QUrl("http://www.theweb.dk/KickAssembler/webhelp/content/cpt_Introduction.html")); } void MainWindow::on_actionInsert_BASIC_SYS_Line_triggered() { insertCode("BasicUpstart2(start)\nstart:\n", QTextCursor::Left); } void MainWindow::on_actionPuts_A_Breakpoint_triggered() { insertCode(".break\n", QTextCursor::Left); } void MainWindow::on_actionWelcome_triggered() { OpenHome(); } void MainWindow::on_actionCode_triggered() { OpenCode(); } void MainWindow::on_actionClear_Output_triggered() { ui->tOutput->clear(); } void MainWindow::on_tFind_returnPressed() { emit on_bFindAll_clicked(); } void MainWindow::on_sbMemoryViewer_valueChanged(int addressPerLine) { ui->memoryViewer->setLineWidth(addressPerLine); if((lastMemoryViewX!=-1)&&(lastMemoryViewY!=-1)) { sbMemoryViewerValueNotChanged = false; ui->lCurrentAddress->setText("????"); memoryViewerCurrentCoordinateChanged(lastMemoryViewX, lastMemoryViewY); } } void MainWindow::on_horizontalSlider_valueChanged(int value) { ui->lZoomValue->setText(QString("X%1").arg(value)); if((lastMemoryViewX!=-1)&&(lastMemoryViewY!=-1)) { sbMemoryViewerValueNotChanged = false; ui->lCurrentAddress->setText("????"); memoryViewerCurrentCoordinateChanged(lastMemoryViewX, lastMemoryViewY); } } void MainWindow::on_actionReport_An_Issue_triggered() { QDesktopServices::openUrl(QUrl("https://github.com/emartisoft/IDE65XX/issues")); } void MainWindow::dataChanged() { hexActionEnable(); } void MainWindow::setOverwriteMode(bool mode) { hexEdit->setOverwriteMode(!mode); } void MainWindow::bytesperlineValueChanged(int value) { hexEdit->setBytesPerLine(value); } void MainWindow::hexFileFindReplace() { hexSearchDialog->show(); } void MainWindow::hexFileRedo() { hexEdit->redo(); } void MainWindow::hexFileUndo() { hexEdit->undo(); } void MainWindow::hexFileSaveas() { if(hexFilename->text() == "???") return; QString hfileName = QFileDialog::getSaveFileName(this, "Save As...", curHexFilename, "Binary files (*.prg; *.bin)"); if (!hfileName.isEmpty()) { saveHexFile(hfileName); } } void MainWindow::hexFileSave() { saveHexFile(curHexFilename); } void MainWindow::hexFileOpen() { curHexFilename = QFileDialog::getOpenFileName(this, "Open Binary File", workspacePath, "Binary files (*.prg; *.bin)"); if(!curHexFilename.isEmpty()) { loadHexFile(); ui->statusbar->showMessage("Hex file loaded", TIMEOUT); } } void MainWindow::hexNewFile() { QString hnfileName = QFileDialog::getSaveFileName(this, "New Hex File", workspacePath, "Binary files (*.bin; *.prg)"); if (!hnfileName.isEmpty()) { QFileInfo fi(hnfileName); QString ext = fi.completeSuffix(); QByteArray sa; if(ext=="prg") { bool ok; int startAddr = QInputDialog::getInt(this, "Start Address","Start Address:", 0x0000, 0x0000, 0xffff, 1, &ok); if(!ok) return; hexEdit->setAddressOffset(startAddr); quint8 ls = hexEdit->addressOffset() & 0xff; quint8 hs = (hexEdit->addressOffset() & 0xff00) >> 8; sa[0] = ls; sa[1] = hs; sa[2] = 0; } else { sa[0] = 0; } hexEdit->setData(sa); saveHexFile(hnfileName); curHexFilename = hnfileName; loadHexFile(); hexEdit->setOverwriteMode(false); hexEdit->dataAt(0); hexEdit->setFocus(); ui->hexInsert->setChecked(true); } } void MainWindow::hexFileSaveselection() { if(hexEdit->selectedData().isEmpty()) return; QString hfileName = QFileDialog::getSaveFileName(this, "Save Selection", curHexFilename, "Binary file (*.bin)"); if (!hfileName.isEmpty()) { saveHexFile(hfileName, true); } } void MainWindow::hexActionEnable() { bool hModified = hexEdit->isModified(); hSave->setEnabled(hModified); hUndo->setEnabled(hModified); hRedo->setEnabled(hModified); } void MainWindow::saveHexFile(QString &hfilename, bool saveSelection) { QFile file; file.setFileName(hfilename); if(!file.open(QIODevice::WriteOnly)) { QMessageBox::warning(this, "Hex Editor - IDE 65XX", QString("Cannot write file %1.").arg(hfilename)); return; } QFileInfo fi(curHexFilename); QString ext = fi.completeSuffix(); if((ext=="prg")&&(!saveSelection)) { QByteArray sa; quint8 ls = hexEdit->addressOffset() & 0xff; quint8 hs = (hexEdit->addressOffset() & 0xff00) >> 8; sa[0] = ls; sa[1] = hs; file.write(sa); } if(saveSelection) { qint64 ss = hexEdit->getSelectionBegin(); qint64 se = hexEdit->getSelectionEnd(); file.write(hexEdit->dataAt(ss, se-ss)); } else file.write(hexEdit->data()); file.close(); ui->statusbar->showMessage("Hex file saved", TIMEOUT); } void MainWindow::loadHexFile() { quint16 startAddress = 0; QFileInfo fi(curHexFilename); QString ext = fi.completeSuffix(); QFile file; file.setFileName(curHexFilename); if(!file.open(QIODevice::ReadOnly)) return; if(ext=="prg") { auto bytesOfStartAddress = file.read(2); startAddress = (bytesOfStartAddress.at(1) << 8) + bytesOfStartAddress.at(0); } hexEdit->setData(file.readAll()); hexEdit->setAddressOffset(startAddress); file.close(); hexwatcher->removePath(workspacePath + hexFilename->text()); hexFilename->setText(fi.canonicalFilePath().remove(workspacePath)); hexwatcher->addPath(curHexFilename); } void MainWindow::on_actionSet_Assembly_File_For_Current_Tab_triggered() { if(ui->tabWidget->count()==0) return; int crIndex = ui->tabWidget->currentIndex(); Tab *tab = /*(Tab *)*/ static_cast<Tab*>( ui->tabWidget->widget(crIndex)); filePath = tab->getCurrentFilePath(); SetAssemblyFile(); } void MainWindow::on_actionCartridge_Conversion_Utility_triggered() { if(!QFile::exists(pCartconv)) { QMessageBox::information(this, "Error?", "Application (cartconv) not found. Check your settings.", QMessageBox::Ok); return; } cc->setCartConvFilename(pCartconv); cc->exec(); cc->clear(); } void MainWindow::on_actionIDE_65XX_Home_Page_triggered() { QDesktopServices::openUrl(QUrl("https://sites.google.com/view/ide65xx")); }
98,162
C++
.cpp
2,493
30.598476
451
0.612208
emartisoft/IDE65XX
33
7
4
GPL-3.0
9/20/2024, 10:45:00 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,539,820
baseplaintextedit.cpp
emartisoft_IDE65XX/baseplaintextedit.cpp
#include "baseplaintextedit.h" #define ZOOM 4 BasePlainTextEdit::BasePlainTextEdit(QWidget *parent): QPlainTextEdit(parent) { commentAction = new QAction(QIcon(":/res/images/comment.png"), tr("Comment"), this); commentAction->setShortcut(Qt::CTRL|Qt::Key_Slash); connect(commentAction, SIGNAL(triggered()), this, SLOT(commentSelectedCode())); uncommentAction = new QAction(QIcon(":/res/images/removecomment.png"), tr("Remove Comment"), this); uncommentAction->setShortcut(Qt::CTRL|Qt::Key_R); connect(uncommentAction, SIGNAL(triggered()), this, SLOT(uncommentSelectedCode())); undoAction = new QAction(QIcon(":/res/images/undo.png"), tr("Undo"), this); undoAction->setShortcut(QKeySequence::Undo); connect(undoAction, SIGNAL(triggered()), this, SLOT(undo())); redoAction = new QAction(QIcon(":/res/images/redo.png"), tr("Redo"), this); redoAction->setShortcut(QKeySequence::Redo); connect(redoAction, SIGNAL(triggered()), this, SLOT(redo())); cutAction = new QAction(QIcon(":/res/images/cut.png"), tr("Cut"), this); cutAction->setShortcut(QKeySequence::Cut); connect(cutAction, SIGNAL(triggered()), this, SLOT(cut())); copyAction = new QAction(QIcon(":/res/images/copy.png"), tr("Copy"), this); copyAction->setShortcut(QKeySequence::Copy); connect(copyAction, SIGNAL(triggered()), this, SLOT(copy())); pasteAction = new QAction(QIcon(":/res/images/paste.png"), tr("Paste"), this); pasteAction->setShortcut(QKeySequence::Paste); connect(pasteAction, SIGNAL(triggered()), this, SLOT(paste())); deleteAction = new QAction(QIcon(":/res/images/erase.png"), tr("Delete"), this); deleteAction->setShortcut(QKeySequence::Delete); connect(deleteAction, SIGNAL(triggered()), this, SLOT(deleteSelected())); selectAllAction = new QAction(QIcon(":/res/images/selectall.png"), tr("Select All"), this); selectAllAction->setShortcut(QKeySequence::SelectAll); connect(selectAllAction, SIGNAL(triggered()), this, SLOT(selectAll())); lowercaseAction = new QAction(QIcon(":/res/images/lowercase.png"), tr("Lowercase"), this); lowercaseAction->setShortcut(Qt::CTRL|Qt::Key_L); connect(lowercaseAction, SIGNAL(triggered()), this, SLOT(lowercaseSelectedCode())); uppercaseAction = new QAction(QIcon(":/res/images/uppercase.png"), tr("Uppercase"), this); uppercaseAction->setShortcut(Qt::CTRL|Qt::Key_U); connect(uppercaseAction, SIGNAL(triggered()), this, SLOT(uppercaseSelectedCode())); undoAction->setEnabled(false); redoAction->setEnabled(false); connect(this, SIGNAL(undoAvailable(bool)), undoAction, SLOT(setEnabled(bool))); connect(this, SIGNAL(redoAvailable(bool)), redoAction, SLOT(setEnabled(bool))); toogleBookmark = new QAction(QIcon(":/res/images/bookmark.png"), "Toggle Bookmark", this); toogleBookmark->setShortcut(Qt::CTRL|Qt::Key_B); resetZoom(); } BasePlainTextEdit::~BasePlainTextEdit() { delete commentAction; delete uncommentAction; delete undoAction; delete redoAction; delete cutAction; delete copyAction; delete pasteAction; delete deleteAction; delete selectAllAction; delete uppercaseAction; delete lowercaseAction; delete toogleBookmark; } QMenu *BasePlainTextEdit::createMenu() { QMenu *menu = new QMenu; QTextCursor textCursor = this->textCursor(); //! if nothing selected if (textCursor.selectionEnd() - textCursor.selectionStart() <= 0) { uppercaseAction->setEnabled(false); lowercaseAction->setEnabled(false); cutAction->setEnabled(false); copyAction->setEnabled(false); deleteAction->setEnabled(false); } else { uppercaseAction->setEnabled(true); lowercaseAction->setEnabled(true); cutAction->setEnabled(true); copyAction->setEnabled(true); deleteAction->setEnabled(true); } undoAction->setVisible(!isReadOnly()); redoAction->setVisible(!isReadOnly()); cutAction->setVisible(!isReadOnly()); pasteAction->setVisible(!isReadOnly()); deleteAction->setVisible(!isReadOnly()); menu->addAction(commentAction); menu->addAction(uncommentAction); menu->addSeparator(); menu->addAction(undoAction); menu->addAction(redoAction); menu->addSeparator(); menu->addAction(cutAction); menu->addAction(copyAction); menu->addAction(pasteAction); menu->addAction(deleteAction); menu->addSeparator(); menu->addAction(selectAllAction); menu->addSeparator(); menu->addAction(uppercaseAction); menu->addAction(lowercaseAction); menu->addSeparator(); menu->addAction(toogleBookmark); return menu; } int BasePlainTextEdit::getZoom() { return zoom; } void BasePlainTextEdit::resetZoom() { zoom = 0; } void BasePlainTextEdit::contextMenuEvent(QContextMenuEvent *e) { QMouseEvent leftClick(QEvent::MouseButtonPress, e->pos(), Qt::LeftButton, Qt::NoButton, Qt::NoModifier); mousePressEvent(&leftClick); contextMenu = createMenu(); contextMenu->exec(e->globalPos()); if (!contextMenu.isNull()) delete contextMenu; } void BasePlainTextEdit::wheelEvent(QWheelEvent *e) { if( e->modifiers() == Qt::ControlModifier ) { QPoint aDelta = e->angleDelta(); if(aDelta.y() > 0) { if(zoom < ZOOM){ zoomIn(); zoom++; } } else { if(zoom > -ZOOM){ zoomOut(); zoom--; } } } QPlainTextEdit::wheelEvent(e); } void BasePlainTextEdit::commentSelectedCode() { QTextCursor tc = textCursor(); QString selected = tc.selectedText(); if(selected.isEmpty()) { tc.movePosition(QTextCursor::StartOfLine, QTextCursor::MoveAnchor, 0); setTextCursor(tc); insertPlainText("//"); // -------> // text } else { selected.insert(0, QString("/*")); selected.insert(selected.length(), QString("*/")); tc.insertText(selected); // -------> /* text */ } } void BasePlainTextEdit::uncommentSelectedCode() { QTextCursor tc = textCursor(); QString selected = tc.selectedText(); if(selected.isEmpty()) { tc.select(QTextCursor::LineUnderCursor); selected = tc.selectedText(); int p = selected.indexOf("//"); if(p > -1) selected.remove(p,2); tc.insertText(selected); } else { selected.remove("/*"); selected.remove("*/"); tc.insertText(selected); } } void BasePlainTextEdit::deleteSelected() { textCursor().removeSelectedText(); } void BasePlainTextEdit::uppercaseSelectedCode() { textCursor().insertText(textCursor().selectedText().toUpper()); } void BasePlainTextEdit::lowercaseSelectedCode() { textCursor().insertText(textCursor().selectedText().toLower()); }
7,181
C++
.cpp
192
30.765625
109
0.660118
emartisoft/IDE65XX
33
7
4
GPL-3.0
9/20/2024, 10:45:00 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,539,821
hint.cpp
emartisoft_IDE65XX/hint.cpp
#include "hint.h" int Hint::getHint(QString text) { int result = -1; for(int i=0;i<COUNT;i++) { if(text == hints[i][0]) { result = i; break; } } return result; }
246
C++
.cpp
14
10.571429
32
0.430435
emartisoft/IDE65XX
33
7
4
GPL-3.0
9/20/2024, 10:45:00 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,539,822
settingswindow.cpp
emartisoft_IDE65XX/settingswindow.cpp
#include "settingswindow.h" #include "ui_settingswindow.h" SettingsWindow::SettingsWindow(QWidget *parent) : QDialog(parent), ui(new Ui::SettingsWindow), cmdline(Common::appConfigDir()+"/cmdline.ini", QSettings::IniFormat), settings(Common::appConfigDir()+"/settings.ini", QSettings::IniFormat) { setWindowFlags(this->windowFlags() & ~Qt::WindowContextHelpButtonHint); ui->setupUi(this); #ifndef Q_OS_WIN ui->lDirMaster->hide(); ui->tDirMaster->hide(); ui->bDirMaster->hide(); #endif ui->toolBox->setCurrentIndex(0); PopupMenu *pmEmulatorTemplates = new PopupMenu(ui->bEmulatorTemplates, this); QAction *tempVice = new QAction("VICE", this); QAction *tempEmu64 = new QAction("emu64", this); QAction *tempHoxs64 = new QAction("Hoxs64", this); QAction *tempMicro64 = new QAction("micro64", this); QAction *tempZ64K = new QAction("Z64K", this); connect(tempVice, SIGNAL(triggered()), this, SLOT(setVice())); connect(tempEmu64, SIGNAL(triggered()), this, SLOT(setEmu64())); connect(tempHoxs64, SIGNAL(triggered()), this, SLOT(setHoxs64())); connect(tempMicro64, SIGNAL(triggered()), this, SLOT(setMicro64())); connect(tempZ64K, SIGNAL(triggered()), this, SLOT(setZ64K())); pmEmulatorTemplates->addAction(tempVice); pmEmulatorTemplates->addAction(tempEmu64); pmEmulatorTemplates->addAction(tempHoxs64); pmEmulatorTemplates->addAction(tempMicro64); pmEmulatorTemplates->addAction(tempZ64K); ui->bEmulatorTemplates->setMenu(pmEmulatorTemplates); } SettingsWindow::~SettingsWindow() { delete ui; } void SettingsWindow::setJRE(QString &value) { ui->tJRE->setText(value); } void SettingsWindow::setKickAssJar(QString &value) { ui->tKickAssJar->setText(value); } void SettingsWindow::setEmulator(QString &value) { ui->tEmulator->setText(value); } void SettingsWindow::setEmulatorParameters(QString &value) { ui->tEmulatorParameters->setText(value); } void SettingsWindow::setCompressionUtility(QString &value) { ui->tCompressionUtility->setText(value); } void SettingsWindow::setCompressionParameters(QString &value) { ui->tCompressionParameters->setText(value); } void SettingsWindow::setDirMaster(QString &value) { ui->tDirMaster->setText(value); } void SettingsWindow::setC1541(QString &value) { ui->tC1541->setText(value); } void SettingsWindow::setDebugger(QString &value) { ui->tDebugger->setText(value); } void SettingsWindow::setOpenLastUsedFiles(bool open) { ui->cOpenLastUsed->setChecked(open); } void SettingsWindow::setMaxRecentWorkspace(int count) { ui->spMaxRecentWorkspace->setValue(count); } void SettingsWindow::setTabSize(int size) { ui->spTabStopDistance->setValue(size); } void SettingsWindow::setTabPolicy(int index) { ui->cTabPolicy->setCurrentIndex(index); } void SettingsWindow::setCodeFontName(QString &fontName) { ui->lOutput->setFont(QFont(fontName)); } void SettingsWindow::setCodeFontSize(int fontSize) { ui->lOutput->setFont(QFont(getCodeFontName(), fontSize)); } void SettingsWindow::setApplicationFont(QString fontName, int fontSize) { ui->lOutput2->setFont(QFont(fontName, fontSize)); } void SettingsWindow::setApplicationTheme(int select) { ui->cTheme->setCurrentIndex(select); } void SettingsWindow::setWordWrap(bool &value) { ui->cWordWrap->setChecked(value); } void SettingsWindow::setShowAllCharacters(bool &value) { ui->cShowAllCharacters->setChecked(value); } void SettingsWindow::setAutoCompletion(bool &value) { ui->cAutoCompletion->setChecked(value); } void SettingsWindow::setSIDPlayer(QString &value) { ui->tSIDPlayer->setText(value); } void SettingsWindow::setSIDPlayerParameters(QString &value) { ui->tSIDPlayerParameters->setText(value); } void SettingsWindow::setCartconv(QString &value) { ui->tCartconv->setText(value); } void SettingsWindow::setCustomBackgroundTexture(QString value) { ui->fBackgroundTexture->setStyleSheet(QString("background-image: url(%1);").arg(value)); } void SettingsWindow::setCustomButtonTexture(QString value) { ui->fButtonTexture->setStyleSheet(QString("background-image: url(%1);").arg(value)); } void SettingsWindow::setBackground(QColor c) { ui->fBackground->setStyleSheet(QString("background-color: rgb(%1, %2, %3);").arg(c.red()).arg(c.green()).arg(c.blue())); } void SettingsWindow::setBrightText(QColor c) { ui->fBrightText->setStyleSheet(QString("background-color: rgb(%1, %2, %3);").arg(c.red()).arg(c.green()).arg(c.blue())); } void SettingsWindow::setBase(QColor c) { ui->fBase->setStyleSheet(QString("background-color: rgb(%1, %2, %3);").arg(c.red()).arg(c.green()).arg(c.blue())); } void SettingsWindow::setHighlights(QColor c) { ui->fHighlights->setStyleSheet(QString("background-color: rgb(%1, %2, %3);").arg(c.red()).arg(c.green()).arg(c.blue())); } void SettingsWindow::setDisable(QColor c) { ui->fDisable->setStyleSheet(QString("background-color: rgb(%1, %2, %3);").arg(c.red()).arg(c.green()).arg(c.blue())); } void SettingsWindow::setOpcode(QColor c) { ui->fOpcode->setStyleSheet(QString("background-color: rgb(%1, %2, %3);").arg(c.red()).arg(c.green()).arg(c.blue())); } void SettingsWindow::setNumber(QColor c) { ui->fNumber->setStyleSheet(QString("background-color: rgb(%1, %2, %3);").arg(c.red()).arg(c.green()).arg(c.blue())); } void SettingsWindow::setFunction(QColor c) { ui->fFunction->setStyleSheet(QString("background-color: rgb(%1, %2, %3);").arg(c.red()).arg(c.green()).arg(c.blue())); } void SettingsWindow::setAssemblerDir(QColor c) { ui->fAssemblerDir->setStyleSheet(QString("background-color: rgb(%1, %2, %3);").arg(c.red()).arg(c.green()).arg(c.blue())); } void SettingsWindow::setPreprocessorDir(QColor c) { ui->fPreprocessorDir->setStyleSheet(QString("background-color: rgb(%1, %2, %3);").arg(c.red()).arg(c.green()).arg(c.blue())); } void SettingsWindow::setComment(QColor c) { ui->fComment->setStyleSheet(QString("background-color: rgb(%1, %2, %3);").arg(c.red()).arg(c.green()).arg(c.blue())); } void SettingsWindow::setQuotation(QColor c) { ui->fQuotation->setStyleSheet(QString("background-color: rgb(%1, %2, %3);").arg(c.red()).arg(c.green()).arg(c.blue())); } void SettingsWindow::setLabel(QColor c) { ui->fLabel->setStyleSheet(QString("background-color: rgb(%1, %2, %3);").arg(c.red()).arg(c.green()).arg(c.blue())); } void SettingsWindow::setCmdLinesEnabledForDebug(bool debugdump, bool vicesymbols) { ui->coDebugdump->setChecked(debugdump); ui->coVicesymbols->setChecked(vicesymbols); emit on_buttonBox_accepted(); } bool SettingsWindow::getCmdLineDebugDump() { return ui->coDebugdump->isChecked(); } bool SettingsWindow::getCmdLineViceSymbols() { return ui->coVicesymbols->isChecked(); } QString SettingsWindow::getJRE() { return ui->tJRE->text(); } QString SettingsWindow::getKickAssJar() { return ui->tKickAssJar->text(); } QString SettingsWindow::getEmulator() { return ui->tEmulator->text(); } QString SettingsWindow::getEmulatorParameters() { return ui->tEmulatorParameters->text(); } QString SettingsWindow::getCompressionUtility() { return ui->tCompressionUtility->text(); } QString SettingsWindow::getCompressionParameters() { return ui->tCompressionParameters->text(); } QString SettingsWindow::getDirMaster() { return ui->tDirMaster->text(); } QString SettingsWindow::getC1541() { return ui->tC1541->text(); } QString SettingsWindow::getDebugger() { return ui->tDebugger->text(); } QString SettingsWindow::getSIDPlayer() { return ui->tSIDPlayer->text(); } QString SettingsWindow::getSIDPlayerParameters() { return ui->tSIDPlayerParameters->text(); } QString SettingsWindow::getCartconv() { return ui->tCartconv->text(); } QString SettingsWindow::getBuildDir() { if(ui->coOutputDir->isChecked()) return ui->coOutputDirText->text(); else return ""; } bool SettingsWindow::getOpenLastUsedFiles() { return ui->cOpenLastUsed->isChecked(); } int SettingsWindow::getMaxRecentWorkspace() { return ui->spMaxRecentWorkspace->value(); } int SettingsWindow::getTabSize() { return ui->spTabStopDistance->value(); } int SettingsWindow::getTabPolicy() { return ui->cTabPolicy->currentIndex(); } QString SettingsWindow::getCodeFontName() { return ui->lOutput->font().family(); } int SettingsWindow::getCodeFontSize() { return ui->lOutput->font().pointSize(); } bool SettingsWindow::getWordWrap() { return ui->cWordWrap->isChecked(); } bool SettingsWindow::getShowAllCharacters() { return ui->cShowAllCharacters->isChecked(); } bool SettingsWindow::getAutoCompletion() { return ui->cAutoCompletion->isChecked(); } void SettingsWindow::on_bKickAssJar_clicked() { QString strFileName = QFileDialog::getOpenFileName(this, tr("Select KickAss.jar"), Common::appLocalDir(), tr("KickAss.jar (KickAss.jar)")); if (strFileName.isEmpty()) return; ui->tKickAssJar->setText(strFileName); } void SettingsWindow::on_bJRE_clicked() { QString strFileName = QFileDialog::getOpenFileName(this, #ifdef Q_OS_WIN tr("Select JRE java.exe"), #else tr("Select JRE java"), #endif Common::appLocalDir(), #ifdef Q_OS_WIN tr("java.exe (java.exe)" #else tr("java (*)" #endif )); if (strFileName.isEmpty()) return; ui->tJRE->setText(strFileName); } void SettingsWindow::on_bEmulator_clicked() { QString strFileName = QFileDialog::getOpenFileName(this, tr("Select Emulator"), Common::appLocalDir(), #ifdef Q_OS_WIN tr("Emulator Application (*.exe);;Emulator Application (*.jar)" #else tr("Emulator Application (*)" #endif )); if (strFileName.isEmpty()) return; #ifdef Q_OS_MACOS changePathForMacOSAppFile(strFileName); #endif ui->tEmulator->setText(strFileName); } void SettingsWindow::on_bCompressionUtility_clicked() { QString strFileName = QFileDialog::getOpenFileName(this, tr("Select Compression Utility"), Common::appLocalDir(), #ifdef Q_OS_WIN tr("Compression Utility Application (*.exe)" #else tr("Compression Utility Application (*)" #endif )); if (strFileName.isEmpty()) return; #ifdef Q_OS_MACOS changePathForMacOSAppFile(strFileName); #endif ui->tCompressionUtility->setText(strFileName); } void SettingsWindow::on_bChangeFontOutput_clicked() { bool ok; QFontDialog fd(this); fd.setOption(QFontDialog::MonospacedFonts); QFont font = fd.getFont(&ok, ui->lOutput->font(), this); if (ok) { ui->lOutput->setFont(font); } } void SettingsWindow::on_coAsminfo_toggled(bool checked) { ui->coAsminfofile->setEnabled(checked); ui->coAsminfofilename->setEnabled(checked); ui->lcoAsminfofilename->setEnabled(checked); } void SettingsWindow::on_coBytedump_toggled(bool checked) { ui->coBytedumpfile->setEnabled(checked); ui->lcoBytedumpfilename->setEnabled(checked); ui->coBytedumpfilename->setEnabled(checked); } void SettingsWindow::on_coDefine_toggled(bool checked) { ui->lcoDefinepresym->setEnabled(checked); ui->coDefinepresymtext->setEnabled(checked); } //void SettingsWindow::on_coExecute_toggled(bool checked) //{ // ui->coExecutelog->setEnabled(checked); // ui->lcoExecutelog->setEnabled(checked); // ui->coExecutelogfile->setEnabled(checked); //} void SettingsWindow::on_coFillbyte_toggled(bool checked) { ui->lcoFillbyte->setEnabled(checked); ui->coFillbytevalue->setEnabled(checked); } void SettingsWindow::on_coLibdir_toggled(bool checked) { ui->lcolibdirpath->setEnabled(checked); ui->colibdirpathtext->setEnabled(checked); } void SettingsWindow::on_coMaxaddr_toggled(bool checked) { ui->lcoMaxaddr->setEnabled(checked); ui->coMaxaddrValue->setEnabled(checked); } void SettingsWindow::on_coO_toggled(bool checked) { ui->lcoPrgfilename->setEnabled(checked); ui->coPrgfilename->setEnabled(checked); } void SettingsWindow::on_coOutputDir_toggled(bool checked) { ui->lcoOutputDir->setEnabled(checked); ui->coOutputDirText->setEnabled(checked); } void SettingsWindow::on_coReplacefile_toggled(bool checked) { ui->lcoReplacefile->setEnabled(checked); ui->coReplacefilesText->setEnabled(checked); } //void SettingsWindow::on_coSymbolfiledir_toggled(bool checked) //{ // ui->lcoSymbolfiledir->setEnabled(checked); // ui->coSymbolfiledirtext->setEnabled(checked); // ui->coSymbolfiledir->setEnabled(checked); //} void SettingsWindow::on_coLog_toggled(bool checked) { ui->lcoLog->setEnabled(checked); ui->coLogfilename->setEnabled(checked); } void SettingsWindow::on_coExtra_toggled(bool checked) { ui->coOtherCLOArg->setEnabled(checked); } void SettingsWindow::ReadCmdLineOption() { // settings file for command line options ui->coAfo->setChecked(cmdline.value("afo", false).toBool()); ui->coAom->setChecked(cmdline.value("aom", false).toBool()); ui->coAsminfo->setChecked(cmdline.value("asminfo", false).toBool()); ui->coAsminfofile->setChecked(cmdline.value("asminfofile", false).toBool()); ui->coAsminfofilename->setText(cmdline.value("asminfofiletext", "asminfo.txt").toString()); ui->coBytedump->setChecked(cmdline.value("bytedump", false).toBool()); ui->coBytedumpfile->setChecked(cmdline.value("bytedumpfile", false).toBool()); ui->coBytedumpfilename->setText(cmdline.value("bytedumpfiletext", "bytedump.txt").toString()); ui->coDebug->setChecked(cmdline.value("debug", false).toBool()); ui->coDebugdump->setChecked(cmdline.value("debugdump", false).toBool()); ui->coDefine->setChecked(cmdline.value("define", false).toBool()); ui->coDefinepresymtext->setText(cmdline.value("definepresymtext", "DEBUG").toString()); ui->coDtv->setChecked(cmdline.value("dtv", false).toBool()); ui->coExcludeillegal->setChecked(cmdline.value("excludeillegal", false).toBool()); ui->coExecutelog->setChecked(cmdline.value("executelog", false).toBool()); ui->coExecutelogfile->setText(cmdline.value("executelogfiletext", "executelog.txt").toString()); ui->coFillbyte->setChecked(cmdline.value("fillbyte", false).toBool()); ui->coFillbytevalue->setValue(cmdline.value("fillbytevalue", 255).toInt()); ui->coLibdir->setChecked(cmdline.value("libdir", false).toBool()); ui->colibdirpathtext->setText(cmdline.value("libdirpathtext", "../stdlib").toString()); ui->coMaxaddr->setChecked(cmdline.value("maxaddr", false).toBool()); ui->coMaxaddrValue->setValue(cmdline.value("maxaddrvalue", 65535).toInt()); ui->coMbfiles->setChecked(cmdline.value("mbfiles", false).toBool()); ui->coNoeval->setChecked(cmdline.value("noeval", false).toBool()); ui->coO->setChecked(cmdline.value("o", false).toBool()); ui->coPrgfilename->setText(cmdline.value("Prgfilename", "out.prg").toString()); ui->coOutputDir->setChecked(cmdline.value("odir", true).toBool()); ui->coOutputDirText->setText(cmdline.value("odirtext", "build").toString()); ui->coPseudoc3x->setChecked(cmdline.value("pseudoc3x", false).toBool()); ui->coReplacefile->setChecked(cmdline.value("replacefile", false).toBool()); ui->coReplacefilesText->setText(cmdline.value("replacefilesText", "source.asm replace.asm").toString()); ui->coShowmem->setChecked(cmdline.value("showmem", true).toBool()); ui->coTime->setChecked(cmdline.value("time", false).toBool()); ui->coSymbolfile->setChecked(cmdline.value("symbolfile", false).toBool()); ui->coSymbolfiledir->setChecked(cmdline.value("symbolfiledir", false).toBool()); ui->coSymbolfiledirtext->setText(cmdline.value("symbolfiledirtext", "symbol").toString()); ui->coVicesymbols->setChecked(cmdline.value("vicesymbols", true).toBool()); ui->coWarningoff->setChecked(cmdline.value("warningoff", false).toBool()); ui->coLog->setChecked(cmdline.value("log", false).toBool()); ui->coLogfilename->setText(cmdline.value("logfilename", "log.txt").toString()); ui->coExtra->setChecked(cmdline.value("extra", false).toBool()); ui->coOtherCLOArg->setText(cmdline.value("extraarg", ":version=beta2 :x=64").toString()); } bool SettingsWindow::getCheckShowMemCmdLine() { // -showmem is checked? return ui->coShowmem->isChecked(); } void SettingsWindow::on_buttonBox_accepted() { NoEmptyForInputText(); // config file for kickassembler QFile cfgFile(Common::appConfigDir()+"/ide65xx.cfg"); // settings file for command line options if(cfgFile.open(QIODevice::WriteOnly | QIODevice::Text)) { QTextStream stream(&cfgFile); bool b; stream << "# This config file is created by IDE65XX\n"; //-afo b = ui->coAfo->isChecked(); if (b){stream << "-afo\n";} cmdline.setValue("afo", b); //-aom b = ui->coAom->isChecked(); if (b){stream << "-aom\n";} cmdline.setValue("aom", b); //-asminfo all b = ui->coAsminfo->isChecked(); if (b){stream << "-asminfo all\n";} cmdline.setValue("asminfo", b); //-asminfofile if(b) // if <asminfo all> is true { b = ui->coAsminfofile->isChecked(); if(b) {stream << "-asminfofile " << ui->coAsminfofilename->text().trimmed() << "\n";} cmdline.setValue("asminfofile", b); cmdline.setValue("asminfofiletext", ui->coAsminfofilename->text().trimmed()); } //-bytedump b = ui->coBytedump->isChecked(); if (b){stream << "-bytedump\n";} cmdline.setValue("bytedump", b); //-bytedumpfile if(b) // if <bytedump> is true { b = ui->coBytedumpfile->isChecked(); if(b) {stream << "-bytedumpfile " << ui->coBytedumpfilename->text().trimmed() << "\n";} cmdline.setValue("bytedumpfile", b); cmdline.setValue("bytedumpfiletext", ui->coBytedumpfilename->text().trimmed()); } //-debug b = ui->coDebug->isChecked(); if (b){stream << "-debug\n";} cmdline.setValue("debug", b); //-debugdump b = ui->coDebugdump->isChecked(); if (b){stream << "-debugdump\n";} cmdline.setValue("debugdump", b); //-define b = ui->coDefine->isChecked(); if (b){stream << "-define " << ui->coDefinepresymtext->text().trimmed() << "\n";} cmdline.setValue("define", b); cmdline.setValue("definepresymtext", ui->coDefinepresymtext->text().trimmed()); //-dtv b = ui->coDtv->isChecked(); if (b){stream << "-dtv\n";} cmdline.setValue("dtv", b); //-excludeillegal b = ui->coExcludeillegal->isChecked(); if (b){stream << "-excludeillegal\n";} cmdline.setValue("excludeillegal", b); //-executelog b = ui->coExecutelog->isChecked(); if(b) {stream << "-executelog " << ui->coExecutelogfile->text().trimmed() << "\n";} cmdline.setValue("executelog", b); cmdline.setValue("executelogfiletext", ui->coExecutelogfile->text().trimmed()); //-fillbyte b = ui->coFillbyte->isChecked(); if (b){stream << "-fillbyte " << ui->coFillbytevalue->value() << "\n";} cmdline.setValue("fillbyte", b); cmdline.setValue("fillbytevalue", ui->coFillbytevalue->value()); //-libdir b = ui->coLibdir->isChecked(); if (b){stream << "-libdir " << ui->colibdirpathtext->text().trimmed() << "\n";} cmdline.setValue("libdir", b); cmdline.setValue("libdirpathtext", ui->colibdirpathtext->text().trimmed()); //-maxaddr b = ui->coMaxaddr->isChecked(); if (b){stream << "-maxaddr " << ui->coMaxaddrValue->value() << "\n";} cmdline.setValue("maxaddr", b); cmdline.setValue("maxaddrvalue", ui->coMaxaddrValue->value()); //-mbfiles b = ui->coMbfiles->isChecked(); if (b){stream << "-mbfiles\n";} cmdline.setValue("mbfiles", b); //-noeval b = ui->coNoeval->isChecked(); if (b){stream << "-noeval\n";} cmdline.setValue("noeval", b); //-o b = ui->coO->isChecked(); if (b){stream << "-o " << ui->coPrgfilename->text().trimmed() << "\n";} cmdline.setValue("o", b); cmdline.setValue("Prgfilename", ui->coPrgfilename->text().trimmed()); //-odir b = ui->coOutputDir->isChecked(); if (b){stream << "-odir " << ui->coOutputDirText->text().trimmed() << "\n";} cmdline.setValue("odir", b); cmdline.setValue("odirtext", ui->coOutputDirText->text().trimmed()); //-pseudoc3x b = ui->coPseudoc3x->isChecked(); if (b){stream << "-pseudoc3x\n";} cmdline.setValue("pseudoc3x", b); //-replacefile b = ui->coReplacefile->isChecked(); if (b){stream << "-replacefile " << ui->coReplacefilesText->text().trimmed() << "\n";} cmdline.setValue("replacefile", b); cmdline.setValue("replacefilesText", ui->coReplacefilesText->text().trimmed()); //-showmem b = ui->coShowmem->isChecked(); if (b){stream << "-showmem\n";} cmdline.setValue("showmem", b); //-time b = ui->coTime->isChecked(); if (b){stream << "-time\n";} cmdline.setValue("time", b); //-symbolfile b = ui->coSymbolfile->isChecked(); if (b){stream << "-symbolfile\n";} cmdline.setValue("symbolfile", b); //-symbolfiledir if(b) // if <symbolfile> is true { b = ui->coSymbolfiledir->isChecked(); if(b) {stream << "-symbolfiledir " << ui->coSymbolfiledirtext->text().trimmed() << "\n";} cmdline.setValue("symbolfiledir", b); cmdline.setValue("symbolfiledirtext", ui->coSymbolfiledirtext->text().trimmed()); } //-vicesymbols b = ui->coVicesymbols->isChecked(); if (b){stream << "-vicesymbols\n";} cmdline.setValue("vicesymbols", b); //-warningoff b = ui->coWarningoff->isChecked(); if (b){stream << "-warningoff\n";} cmdline.setValue("warningoff", b); //-log b = ui->coLog->isChecked(); if (b){stream << "-log " << ui->coLogfilename->text().trimmed() << "\n";} cmdline.setValue("log", b); cmdline.setValue("logfilename", ui->coLogfilename->text().trimmed()); //additional options b = ui->coExtra->isChecked(); if(b) { QStringList listArguments = ui->coOtherCLOArg->text().trimmed().split(' '); foreach(const QString &argument, listArguments) { stream << argument << "\n"; } } cmdline.setValue("extra", b); cmdline.setValue("extraarg", ui->coOtherCLOArg->text().trimmed()); cfgFile.close(); cmdline.sync(); } } void SettingsWindow::on_coExecutelog_toggled(bool checked) { ui->lcoExecutelog->setEnabled(checked); ui->coExecutelogfile->setEnabled(checked); } void SettingsWindow::on_coSymbolfile_toggled(bool checked) { ui->coSymbolfiledir->setEnabled(checked); ui->lcoSymbolfiledir->setEnabled(checked); ui->coSymbolfiledirtext->setEnabled(checked); } void SettingsWindow::NoEmptyForInputText() { if(ui->coAsminfofilename->text().isEmpty()) ui->coAsminfofilename->setText(cmdline.value("asminfofiletext", "asminfo.txt").toString()); if(ui->coBytedumpfilename->text().isEmpty()) ui->coBytedumpfilename->setText(cmdline.value("bytedumpfiletext", "bytedump.txt").toString()); if(ui->coDefinepresymtext->text().isEmpty()) ui->coDefinepresymtext->setText(cmdline.value("definepresymtext", "DEBUG").toString()); if(ui->coExecutelogfile->text().isEmpty()) ui->coExecutelogfile->setText(cmdline.value("executelogfiletext", "executelog.txt").toString()); if(ui->colibdirpathtext->text().isEmpty()) ui->colibdirpathtext->setText(cmdline.value("libdirpathtext", "../stdlib").toString()); if(ui->coPrgfilename->text().isEmpty()) ui->coPrgfilename->setText(cmdline.value("Prgfilename", "out.prg").toString()); if(ui->coOutputDirText->text().isEmpty()) ui->coOutputDirText->setText(cmdline.value("odirtext", "build").toString()); if(ui->coReplacefilesText->text().isEmpty()) ui->coReplacefilesText->setText(cmdline.value("replacefilesText", "source.asm replace.asm").toString()); if(ui->coSymbolfiledirtext->text().isEmpty()) ui->coSymbolfiledirtext->setText(cmdline.value("symbolfiledirtext", "symbol").toString()); if(ui->coLogfilename->text().isEmpty()) ui->coLogfilename->setText(cmdline.value("logfilename", "log.txt").toString()); if(ui->coOtherCLOArg->text().isEmpty()) ui->coOtherCLOArg->setText(cmdline.value("extraarg", ":version=beta2 :x=64").toString()); } #ifdef Q_OS_MACOS void SettingsWindow::changePathForMacOSAppFile(QString &AppFilePath) { QFileInfo fi(AppFilePath); QString fiFilename = fi.fileName(); if(fiFilename.right(4) == ".app") AppFilePath += "/Contents/MacOS/" + fiFilename.left(fiFilename.length()-4); } #endif void SettingsWindow::on_bDirMaster_clicked() { QString strFileName = QFileDialog::getOpenFileName(this, tr("Select DirMaster.exe"), Common::appLocalDir(), tr("DirMaster.exe (DirMaster.exe)")); if (strFileName.isEmpty()) return; ui->tDirMaster->setText(strFileName); } void SettingsWindow::on_bC1541_clicked() { QString strFileName = QFileDialog::getOpenFileName(this, #ifdef Q_OS_WIN tr("Select c1541.exe"), #else tr("Select c1541"), #endif Common::appLocalDir(), #ifdef Q_OS_WIN tr("c1541.exe (c1541.exe)" #else tr("c1541 (*)" #endif )); if (strFileName.isEmpty()) return; #ifdef Q_OS_MACOS changePathForMacOSAppFile(strFileName); #endif ui->tC1541->setText(strFileName); } void SettingsWindow::on_bDebugger_clicked() { QString strFileName = QFileDialog::getOpenFileName(this, tr("Select Debugger"), Common::appLocalDir(), #ifdef Q_OS_WIN tr("Debugger Application (*.exe)" #else tr("Debugger Application (*)" #endif )); if (strFileName.isEmpty()) return; #ifdef Q_OS_MACOS changePathForMacOSAppFile(strFileName); #endif ui->tDebugger->setText(strFileName); } void SettingsWindow::on_bSIDPlayer_clicked() { QString strFileName = QFileDialog::getOpenFileName(this, tr("Select SID Player"), Common::appLocalDir(), #ifdef Q_OS_WIN tr("SID Player Application (*.*)" #else tr("SID Player Application (*)" #endif )); if (strFileName.isEmpty()) return; #ifdef Q_OS_MACOS changePathForMacOSAppFile(strFileName); #endif ui->tSIDPlayer->setText(strFileName); } void SettingsWindow::on_bChangeFontOutput2_clicked() { bool ok; QFontDialog fd(this); restartRequired = false; QFont font = fd.getFont(&ok, ui->lOutput2->font(), this); if (ok) { ui->lOutput2->setFont(font); settings.setValue("ApplicationFontName", font.family()); settings.setValue("ApplicationFontSize", font.pointSize()); settings.sync(); restartRequired = true; } } void SettingsWindow::on_cTheme_currentIndexChanged(int index) { settings.setValue("ApplicationStyle", index); settings.sync(); restartRequired = true; } void SettingsWindow::setVice() { ui->tEmulatorParameters->setText("<file>"); } void SettingsWindow::setEmu64() { ui->tEmulatorParameters->setText("--nosplash -a <file>"); } void SettingsWindow::setHoxs64() { ui->tEmulatorParameters->setText("-autoload <file>"); } void SettingsWindow::setMicro64() { ui->tEmulatorParameters->setText("<file>"); } void SettingsWindow::setZ64K() { ui->tEmulatorParameters->setText("c64 <file>"); } void SettingsWindow::on_bCartconv_clicked() { QString strFileName = QFileDialog::getOpenFileName(this, tr("Select Cartridge Conversion Utility (cartconv VICE)"), Common::appLocalDir(), #ifdef Q_OS_WIN tr("Cartridge Conversion Utility (cartconv VICE) (cartconv.exe)" #else tr("Cartridge Conversion Utility (cartconv VICE) (*)" #endif )); if (strFileName.isEmpty()) return; #ifdef Q_OS_MACOS changePathForMacOSAppFile(strFileName); #endif ui->tCartconv->setText(strFileName); } void SettingsWindow::on_cTheme_currentTextChanged(const QString &arg1) { ui->gCustomTheme->setEnabled(arg1 == "Custom"); } void SettingsWindow::on_bBackgroundTexture_clicked() { QString strFileName = QFileDialog::getOpenFileName(this, tr("Select Background Texture"), Common::appLocalDir(), tr("Images (*.png; *.jpg)" )); if (strFileName.isEmpty()) return; setCustomBackgroundTexture(strFileName); settings.setValue("CustomBackgroundTexture", strFileName); settings.sync(); restartRequired = true; } void SettingsWindow::on_bButtonTexture_clicked() { QString strFileName = QFileDialog::getOpenFileName(this, tr("Select Button Texture"), Common::appLocalDir(), tr("Images (*.png; *.jpg)" )); if (strFileName.isEmpty()) return; setCustomButtonTexture(strFileName); settings.setValue("CustomButtonTexture", strFileName); settings.sync(); restartRequired = true; } void SettingsWindow::on_bBackgroundColor_clicked() { QColor c = QColorDialog::getColor(settings.value("CustomBackground").value<QColor>(), this, "Background Color"); setBackground(c); settings.setValue("CustomBackground", c); settings.sync(); restartRequired = true; } void SettingsWindow::on_bBrightTextColor_clicked() { QColor c = QColorDialog::getColor(settings.value("CustomBrightText").value<QColor>(), this, "Bright Text Color"); setBrightText(c); settings.setValue("CustomBrightText", c); settings.sync(); restartRequired = true; } void SettingsWindow::on_bBaseColor_clicked() { QColor c = QColorDialog::getColor(settings.value("CustomBase").value<QColor>(), this, "Base Color"); setBase(c); settings.setValue("CustomBase", c); settings.sync(); restartRequired = true; } void SettingsWindow::on_bHighlightsColor_clicked() { QColor c = QColorDialog::getColor(settings.value("CustomHighlights").value<QColor>(), this, "Highlights Color"); setHighlights(c); settings.setValue("CustomHighlights", c); settings.sync(); restartRequired = true; } void SettingsWindow::on_bDisableColor_clicked() { QColor c = QColorDialog::getColor(settings.value("CustomDisable").value<QColor>(), this, "Disable Color"); setDisable(c); settings.setValue("CustomDisable", c); settings.sync(); restartRequired = true; } void SettingsWindow::on_bOpcode_clicked() { QColor c = QColorDialog::getColor(settings.value("CustomOpcode").value<QColor>(), this, "Opcode Color"); setOpcode(c); settings.setValue("CustomOpcode", c); settings.sync(); restartRequired = true; } void SettingsWindow::on_bNumber_clicked() { QColor c = QColorDialog::getColor(settings.value("CustomNumber").value<QColor>(), this, "Number Color"); setNumber(c); settings.setValue("CustomNumber", c); settings.sync(); restartRequired = true; } void SettingsWindow::on_bFunction_clicked() { QColor c = QColorDialog::getColor(settings.value("CustomFunction").value<QColor>(), this, "Function Color"); setFunction(c); settings.setValue("CustomFunction", c); settings.sync(); restartRequired = true; } void SettingsWindow::on_bAssemblerDir_clicked() { QColor c = QColorDialog::getColor(settings.value("CustomAssemblerDir").value<QColor>(), this, "Assembler Directive Color"); setAssemblerDir(c); settings.setValue("CustomAssemblerDir", c); settings.sync(); restartRequired = true; } void SettingsWindow::on_bPreprocessorDir_clicked() { QColor c = QColorDialog::getColor(settings.value("CustomPreprocessorDir").value<QColor>(), this, "Preprocessor Directive Color"); setPreprocessorDir(c); settings.setValue("CustomPreprocessorDir", c); settings.sync(); restartRequired = true; } void SettingsWindow::on_bComment_clicked() { QColor c = QColorDialog::getColor(settings.value("CustomComment").value<QColor>(), this, "Comment Color"); setComment(c); settings.setValue("CustomComment", c); settings.sync(); restartRequired = true; } void SettingsWindow::on_bQuotation_clicked() { QColor c = QColorDialog::getColor(settings.value("CustomQuotation").value<QColor>(), this, "Quotation Color"); setQuotation(c); settings.setValue("CustomQuotation", c); settings.sync(); restartRequired = true; } void SettingsWindow::on_bLabel_clicked() { QColor c = QColorDialog::getColor(settings.value("CustomLabel").value<QColor>(), this, "Label Color"); setLabel(c); settings.setValue("CustomLabel", c); settings.sync(); restartRequired = true; }
37,644
C++
.cpp
935
31.034225
134
0.608285
emartisoft/IDE65XX
33
7
4
GPL-3.0
9/20/2024, 10:45:00 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,539,824
tab.cpp
emartisoft_IDE65XX/tab.cpp
#include "tab.h" Tab::Tab(QWidget *parent) : QMainWindow(parent), code(new CodeEditor()), currentFilePath(""), settings("IDE65xx Project", "IDE65xx") { code->setWordWrapMode(QTextOption::NoWrap); connect(code->document(), SIGNAL(blockCountChanged(int)), this, SLOT(blockCountChanged(int))); setCentralWidget(code); setFonts(); restoreGeometry(settings.value("tabgeometry").toByteArray()); restoreState(settings.value("tabwindowstate").toByteArray()); } void Tab::setFonts() { QFont codeFont; codeFont.setPointSize(settings.value("fontsize", 12).toInt()); codeFont.setFamily(settings.value("fontfamily", QString("Ubuntu Mono")).value<QString>()); codeFont.setStyleHint(QFont::Monospace); code->setFont(codeFont); } void Tab::blockCountChanged(int newBlockCount) { emit code->updateLineNumber(code->textCursor().blockNumber()+1, newBlockCount - oldBlockCount); oldBlockCount = newBlockCount; } QTextDocument * Tab::getCodeDocument() { return code->document(); } QString Tab::getCurrentFilePath() { return currentFilePath; } void Tab::saveCodeToFile(const QString &filePath, bool changeCodeModifiedFlag) { QFile outfile; outfile.setFileName(filePath); outfile.open(QIODevice::WriteOnly | QIODevice::Text); QTextStream out(&outfile); out << code->toPlainText(); if (changeCodeModifiedFlag) { currentFilePath = filePath; getCodeDocument()->setModified(false); } outfile.close(); } bool Tab::loadCodeFromFile(const QString &filePath) { QFile file; file.setFileName(filePath); if(!file.open(QIODevice::ReadOnly)) return false; QTextStream text(&file); QString source = text.readAll(); code->setPlainText(source); currentFilePath = filePath; code->document()->setModified(false); file.close(); return true; } Tab::~Tab() { delete code; }
1,989
C++
.cpp
65
25.615385
100
0.69705
emartisoft/IDE65XX
33
7
4
GPL-3.0
9/20/2024, 10:45:00 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,539,826
tdiskdirective.cpp
emartisoft_IDE65XX/tdiskdirective.cpp
#include "tdiskdirective.h" #include "ui_tdiskdirective.h" TDiskDirective::TDiskDirective(QWidget *parent) : QDialog(parent), ui(new Ui::TDiskDirective) { setWindowFlags(this->windowFlags() & ~Qt::WindowContextHelpButtonHint); ui->setupUi(this); } TDiskDirective::~TDiskDirective() { delete ui; } QString TDiskDirective::getDiskDirective() { return m_diskdirective; } void TDiskDirective::on_tDiskname_textEdited(const QString &arg1) { ui->tDiskname->setText(arg1.toUpper()); } void TDiskDirective::on_tFilename_textEdited(const QString &arg1) { ui->tFilename->setText(arg1.toUpper()); } void TDiskDirective::on_tDiskId_textEdited(const QString &arg1) { ui->tDiskId->setText(arg1.toUpper()); } void TDiskDirective::on_bCancel_clicked() { close(); } void TDiskDirective::on_bOk_clicked() { QString sDiskFilename = ui->tDiskFilename->text(); QString sDiskId = ui->tDiskId->text(); QString sDiskName = ui->tDiskname->text(); QString sDiskFormat = ui->cDiskFormat->currentText(); if(sDiskFilename.isEmpty()){ui->tDiskFilename->setFocus(); return;} if(sDiskId.isEmpty()){ui->tDiskId->setFocus(); return;} if(sDiskName.isEmpty()){ui->tDiskname->setFocus(); return;} m_diskdirective = QString("\n.disk [filename=\"%1\", name=\"%2\", id=\"%3\", format=\"%4\"").arg(sDiskFilename).arg(sDiskName).arg(sDiskId).arg(sDiskFormat); if(ui->cShowInfo->isChecked()) m_diskdirective += ", showInfo"; m_diskdirective += "]\n{\n"; for(int i=0;i<fl.count();i++) { m_diskdirective += "\t" + fl[i]; if(i != (fl.count()-1)) m_diskdirective += ",\n"; } m_diskdirective += "\n}\n\n"; if(ui->cInsertBasicUpstart2->isChecked()) m_diskdirective += "BasicUpstart2(start)\nstart:\n\n"; close(); } void TDiskDirective::on_bAdd_clicked() { QString item; QString sFilename = ui->tFilename->text(); QString sType = ui->cType->currentText(); QString sDefine = ui->tDefine->text(); if(sFilename.isEmpty()){ ui->tFilename->setFocus(); return; } sFilename = sFilename.leftJustified(16, ' '); switch (ui->cDefine->currentIndex()) { case 0: sDefine = ""; break; case 1: sDefine = QString(", segments=\"%1\"").arg(sDefine); break; case 2: if(sType=="sid") { sDefine = QString(", sidFiles=\"%1\"").arg(sDefine); sType = "prg"; } else sDefine = QString(", prgFiles=\"%1\"").arg(sDefine); break; } if(ui->cLocked->isChecked()) sType += "<"; item = QString("[name=\"%1\", type=\"%2\"").arg(sFilename).arg(sType); if(!sDefine.isEmpty()) item += sDefine; if(ui->cHide->isChecked()) item += ", hide"; item += "]"; fl << item; ui->listFiles->clear(); ui->listFiles->addItems(fl); } void TDiskDirective::on_bRemove_clicked() { if(ui->listFiles->selectedItems().empty()) return; fl.removeAt(ui->listFiles->currentRow()); ui->listFiles->clear(); ui->listFiles->addItems(fl); } void TDiskDirective::on_cDefine_currentIndexChanged(int index) { ui->tDefine->setEnabled(index!=0); } void TDiskDirective::on_bClear_clicked() { ui->listFiles->clear(); fl.clear(); } void TDiskDirective::on_bUp_clicked() { if(ui->listFiles->selectedItems().empty()) return; int idx = ui->listFiles->currentRow(); if(idx==0) return; fl.move(idx, idx-1); ui->listFiles->clear(); ui->listFiles->addItems(fl); ui->listFiles->setCurrentRow(idx-1); } void TDiskDirective::on_bDown_clicked() { if(ui->listFiles->selectedItems().empty()) return; int idx = ui->listFiles->currentRow(); if(idx==fl.count()-1) return; fl.move(idx, idx+1); ui->listFiles->clear(); ui->listFiles->addItems(fl); ui->listFiles->setCurrentRow(idx+1); }
4,105
C++
.cpp
125
26.552
162
0.611621
emartisoft/IDE65XX
33
7
4
GPL-3.0
9/20/2024, 10:45:00 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,539,827
codeeditor.cpp
emartisoft_IDE65XX/codeeditor.cpp
#include "codeeditor.h" #include <QPainter> #include <QTextBlock> #include <QCompleter> #include <QKeyEvent> #include <QAbstractItemView> #include <QApplication> #include <QModelIndex> #include <QAbstractItemModel> #include <QScrollBar> #include <QtMath> #include <QToolTip> #include "hint.h" CodeEditor::CodeEditor(QWidget *parent) : BasePlainTextEdit(parent), lineNumberArea(new LineNumberArea(this)), bookmarkImage(":/res/images/bookmark.png"), bookmarkAreaWidth(bookmarkImage.width()) { installEventFilter(this); connect(this, &CodeEditor::blockCountChanged, this, &CodeEditor::updateLineNumberAreaWidth); connect(this, &CodeEditor::updateRequest, this, &CodeEditor::updateLineNumberArea); connect(this, &CodeEditor::cursorPositionChanged, this, &CodeEditor::highlightCurrentLine); updateLineNumberAreaWidth(0); highlightCurrentLine(); setCursorWidth(2); connect(toogleBookmark, SIGNAL(triggered()), this, SLOT(setBookmarkOnCurrentLine())); setMouseTracking(true); } CodeEditor::~CodeEditor() { } int CodeEditor::lineNumberAreaWidth() { int digits = 1; int max = qMax(1, blockCount()); while (max >= 10) { max /= 10; ++digits; } bookmarkAreaWidth = bookmarkImage.width()*fontMetrics().height()/bookmarkImage.height(); int space = 8 + fontMetrics().horizontalAdvance(QLatin1Char('9')) * digits + bookmarkAreaWidth; return space; } QMenu *CodeEditor::getContextMenu() { return createMenu(); } void CodeEditor::setCompleter(QCompleter *completer) { if (c) c->disconnect(this); c = completer; if (!c) return; c->setWidget(this); c->setCompletionMode(QCompleter::PopupCompletion); c->setCaseSensitivity(Qt::CaseInsensitive); c->popup()->setFont(font()); QObject::connect(c, QOverload<const QString &>::of(&QCompleter::activated), this, &CodeEditor::insertCompletion); } QCompleter *CodeEditor::completer() const { return c; } void CodeEditor::repaintLineNumberArea() { //repaint QRect lineNumberAreaRect(lineNumberArea->x(), lineNumberArea->y(), lineNumberArea->width(), lineNumberArea->height()); emit updateRequest(lineNumberAreaRect, 0); } QString CodeEditor::getHelpWord() { // result may be tooltip showing text or under cursor word return (tooltipShowing) ? tooltipWord : textUnderCursor(); } void CodeEditor::updateLineNumberAreaWidth(int) { setViewportMargins(lineNumberAreaWidth(), 0, 0, 0); } void CodeEditor::updateLineNumberArea(const QRect &rect, int dy) { if (dy) lineNumberArea->scroll(0, dy); else lineNumberArea->update(0, rect.y(), lineNumberArea->width(), rect.height()); if (rect.contains(viewport()->rect())) updateLineNumberAreaWidth(0); } QString CodeEditor::textUnderCursor() const { QTextCursor tc = textCursor(); tc.select(QTextCursor::WordUnderCursor); return tc.selectedText(); } void CodeEditor::resizeEvent(QResizeEvent *e) { QPlainTextEdit::resizeEvent(e); QRect cr = contentsRect(); lineNumberArea->setGeometry(QRect(cr.left(), cr.top(), lineNumberAreaWidth(), cr.height())); } void CodeEditor::keyReleaseEvent(QKeyEvent *event) { int initial_position; QTextCursor tc = textCursor(); // Zoom if( (event->modifiers().testFlag(Qt::ControlModifier) && event->key() == Qt::Key_0)) // CTRL + 0 { int d = getZoom(); (d>0)?zoomIn(-d):zoomOut(d); resetZoom(); } // insert or overwrite if(event->key() == Qt::Key_Insert) { setOverwriteMode(!overwriteMode()); if(overwriteMode()) { setCursorWidth(QFontMetrics(font()).horizontalAdvance('9') - 1); // cursor width } else { setCursorWidth(2); } emit overWriteModeChanged(); } if (event->key() == Qt::Key_BraceLeft) { tc.deletePreviousChar(); initial_position = QPlainTextEdit::textCursor().position(); QPlainTextEdit::insertPlainText("{\n\n}"); tc = QPlainTextEdit::textCursor(); tc.setPosition(initial_position+2); QPlainTextEdit::setTextCursor(tc); } if (event->key() == Qt::Key_ParenLeft) { tc.deletePreviousChar(); initial_position = QPlainTextEdit::textCursor().position(); QPlainTextEdit::insertPlainText("()"); tc = QPlainTextEdit::textCursor(); tc.setPosition(initial_position+1); QPlainTextEdit::setTextCursor(tc); } } void CodeEditor::focusInEvent(QFocusEvent *e) { if (c) c->setWidget(this); QPlainTextEdit::focusInEvent(e); } void CodeEditor::keyPressEvent(QKeyEvent *event) { const bool isShortcut = (event->modifiers().testFlag(Qt::ControlModifier) && event->key() == Qt::Key_Space); // CTRL+SPACE if (c && c->popup()->isVisible()) { switch (event->key()) { case Qt::Key_Return: case Qt::Key_Escape: case Qt::Key_Enter: event->ignore(); return; default: break; } } else if (!c || !isShortcut) { switch (event->key()) { case (Qt::Key_Enter) : case (Qt::Key_Return) : { QPlainTextEdit::keyPressEvent(event); QTextCursor cur = textCursor(); cur.movePosition(QTextCursor::PreviousBlock); cur.movePosition(QTextCursor::StartOfBlock); cur.movePosition(QTextCursor::EndOfBlock, QTextCursor::KeepAnchor); QString str = cur.selectedText(); // get text from line emit AfterEnterSendLine(str); // signal int spcCount = 0; int tabCount = 0; int lstr = str.length(); for(int i=0;i<lstr;i++) { if(str[i] == ' ') { spcCount++; } else if(str[i] == '\t') { tabCount++; } else if ((str[i] != ' ')&&(str[i] != '\t')) { break; } } insertPlainText(QString(tabCount, '\t')+QString(spcCount, ' ')); return; break; } } } // bookmark if( (event->modifiers().testFlag(Qt::ControlModifier) && event->key() == Qt::Key_B)) // CTRL + B { setBookmarkOnCurrentLine(); } // show find dialog signal else if( (event->modifiers().testFlag(Qt::ControlModifier) && event->key() == Qt::Key_F)) // CTRL + F { showFindDialog(); } // uppercase else if( (event->modifiers().testFlag(Qt::ControlModifier) && event->key() == Qt::Key_U)) // CTRL + U { uppercaseSelectedCode(); } // lowercase else if( (event->modifiers().testFlag(Qt::ControlModifier) && event->key() == Qt::Key_L)) // CTRL + L { lowercaseSelectedCode(); } // comment else if( (event->modifiers().testFlag(Qt::ControlModifier) && event->key() == Qt::Key_Q)) // CTRL + Q { commentSelectedCode(); } // uncomment else if( (event->modifiers().testFlag(Qt::ControlModifier) && event->key() == Qt::Key_R)) // CTRL + R { uncommentSelectedCode(); } BasePlainTextEdit::keyPressEvent(event); const bool ctrlOrShift = event->modifiers().testFlag(Qt::ControlModifier) || event->modifiers().testFlag(Qt::ShiftModifier); if (!c || (ctrlOrShift && event->text().isEmpty())) return; static QString eow("~!@#$%^&*()_+{}|:\"<>?,./;'[]\\-="); // end of word const bool hasModifier = (event->modifiers() != Qt::NoModifier) && !ctrlOrShift; QString completionPrefix = textUnderCursor(); if (!isShortcut && (hasModifier || event->text().isEmpty()|| completionPrefix.length() < 2 || eow.contains(event->text().right(1)))) { c->popup()->hide(); return; } if (completionPrefix != c->completionPrefix()) { c->setCompletionPrefix(completionPrefix); c->popup()->setCurrentIndex(c->completionModel()->index(0, 0)); } if(cAutoCompletion || isShortcut) { QRect cr = cursorRect(); cr.setWidth(c->popup()->sizeHintForColumn(0) + c->popup()->verticalScrollBar()->sizeHint().width()); c->complete(cr); } } bool CodeEditor::event(QEvent *event) { if (event->type() == QEvent::ToolTip) { QHelpEvent* helpEvent = static_cast<QHelpEvent*>(event); QPoint pos = helpEvent->pos(); pos.setX(pos.x() - viewportMargins().left()); pos.setY(pos.y() - viewportMargins().top()); QTextCursor tcursor = cursorForPosition(pos); tcursor.select(QTextCursor::WordUnderCursor); int hint = Hint::getHint(tcursor.selectedText()); if(hint>-1) { tooltipWord = Hint::hints[hint][0]; QToolTip::showText(helpEvent->globalPos(), QString("" "<table><tbody><tr><td><table style=\"width: 100%;\"><tbody><tr>" "<td style=\"vertical-align: top;\"><h2><strong>%1</strong></h2>" "</td></tr><tr><td><em>%2</em></td></tr>" "<tr><td>%3</td></tr></tbody></table></td>" "<td style=\"width: 48px; text-align: right; vertical-align: top;\">" "<img src=\":/res/images/f1.png\" /></td></tr></tbody></table>" ).arg(tooltipWord).arg(Hint::hints[hint][1]).arg(Hint::hints[hint][2])); tooltipShowing = true; } else { QToolTip::hideText(); tooltipShowing = false; } return true; } return QPlainTextEdit::event(event); } bool CodeEditor::eventFilter(QObject *obj, QEvent *event) { if (event->type() == QEvent::KeyPress) { auto *keyEvent = static_cast<QKeyEvent *>(event); if ((keyEvent->key() == Qt::Key_Tab) || (keyEvent->key() == Qt::Key_Backtab)) { bool shifttab = (keyEvent->key() == Qt::Key_Backtab); QString tabChar = (tabSpace) ? QString(tabSpaceCount, ' ') : QChar('\t'); QTextCursor tc = textCursor(); QString currentLineText = tc.selectedText(); if (!currentLineText.isEmpty()) { const QString newLine = QString::fromUtf8(QByteArray::fromHex(QByteArrayLiteral("e280a9"))); QString newText; if (shifttab) { const int indentSize = tabChar == QStringLiteral("\t") ? tabSpaceCount : tabChar.count(); newText = currentLineText.replace(QRegularExpression(newLine + QStringLiteral("(\\t| {1,") + QString::number(indentSize) + QStringLiteral("})")), QStringLiteral("\n")); newText.remove(QRegularExpression(QStringLiteral("^(\\t| {1,") + QString::number(indentSize) + QStringLiteral("})"))); } else { newText = currentLineText.replace(QRegularExpression(QRegularExpression::escape(newLine) + QStringLiteral("$")), QStringLiteral("\n")); newText.replace(newLine, QStringLiteral("\n") + tabChar).prepend(tabChar); newText.remove(QRegularExpression(QStringLiteral("\\t$"))); } tc.insertText(newText); tc.setPosition(tc.position() - newText.size(), QTextCursor::KeepAnchor); setTextCursor(tc); return true; } else if(!shifttab) { tc.insertText(tabChar); } return true; } } return QPlainTextEdit::eventFilter(obj, event); } void CodeEditor::highlightCurrentLine() { QList<QTextEdit::ExtraSelection> extraSelections; if (!isReadOnly()) { QTextEdit::ExtraSelection selection; QColor lineColor = palette().window().color().darker(128); selection.format.setBackground(lineColor); selection.format.setProperty(QTextFormat::FullWidthSelection, true); selection.cursor = textCursor(); selection.cursor.clearSelection(); extraSelections.append(selection); } setExtraSelections(extraSelections); } void CodeEditor::insertCompletion(const QString &completion) { if (c->widget() != this) return; QTextCursor tc = textCursor(); int extra = completion.length() - c->completionPrefix().length(); tc.movePosition(QTextCursor::Left); tc.movePosition(QTextCursor::EndOfWord); tc.insertText(completion.right(extra)); setTextCursor(tc); } void CodeEditor::setBookmarkOnCurrentLine() { int lineNumber = textCursor().blockNumber() + 1; if (lineNumber <= document()->lineCount()) { lineNumber = document()->findBlockByLineNumber(lineNumber - 1).blockNumber() + 1; if (bookmarks.contains(lineNumber)) { bookmarks.removeOne(lineNumber); emit bookmarksChanged(lineNumber, "", false); } else { bookmarks.append(lineNumber); emit bookmarksChanged(lineNumber, textCursor().block().text().trimmed().append(" "), true); } repaintLineNumberArea(); } } void CodeEditor::lineNumberAreaPaintEvent(QPaintEvent *event) { QPainter painter(lineNumberArea); painter.setRenderHints(QPainter::Antialiasing | QPainter::SmoothPixmapTransform,1); painter.fillRect(event->rect(), palette().window().color()); QTextBlock block = firstVisibleBlock(); int blockNumber = block.blockNumber(); int top = qRound(blockBoundingGeometry(block).translated(contentOffset()).top()); int bottom = top + qRound(blockBoundingRect(block).height()); while (block.isValid() && top <= event->rect().bottom()) { if (block.isVisible() && bottom >= event->rect().top()) { QString number = QString::number(blockNumber + 1); painter.setPen(Qt::darkGray); painter.drawText(0, top - 2, lineNumberArea->width() - bookmarkAreaWidth, fontMetrics().height(), Qt::AlignRight, number); } if (bookmarks.contains(blockNumber + 1)) painter.drawPixmap(lineNumberArea->width() - bookmarkAreaWidth, top, bookmarkImage.width()*fontMetrics().height()/bookmarkImage.height(), fontMetrics().height(), bookmarkImage); block = block.next(); top = bottom; bottom = top + qRound(blockBoundingRect(block).height()); ++blockNumber; } } void CodeEditor::lineNumberAreaMousePressEvent(QMouseEvent *event) { if (event->button() != Qt::LeftButton) return; int lineNumber = 0; int sumHeight = 0; QTextBlock block = firstVisibleBlock(); while (block.isValid() && event->y() > sumHeight) { sumHeight += blockBoundingGeometry(block).height(); block = block.next(); lineNumber++; } int vsbv = verticalScrollBar()->value(); lineNumber += vsbv; if (lineNumber <= document()->lineCount()) { lineNumber = document()->findBlockByLineNumber(lineNumber - 1).blockNumber() + 1; if (bookmarks.contains(lineNumber)) { bookmarks.removeOne(lineNumber); emit bookmarksChanged(lineNumber, "", false); } else { bookmarks.append(lineNumber); moveCursor(QTextCursor::Start); for (int i=0;i<lineNumber-1;i++) { moveCursor(QTextCursor::Down); } setFocus(); emit bookmarksChanged(lineNumber, textCursor().block().text().trimmed().append(" "), true); } repaintLineNumberArea(); } verticalScrollBar()->setValue(vsbv); }
16,927
C++
.cpp
432
28.886574
202
0.569439
emartisoft/IDE65XX
33
7
4
GPL-3.0
9/20/2024, 10:45:00 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,539,828
tfiledirective.cpp
emartisoft_IDE65XX/tfiledirective.cpp
#include "tfiledirective.h" #include "ui_tfiledirective.h" TFileDirective::TFileDirective(QWidget *parent) : QDialog(parent), ui(new Ui::TFileDirective) { setWindowFlags(this->windowFlags() & ~Qt::WindowContextHelpButtonHint); ui->setupUi(this); } TFileDirective::~TFileDirective() { delete ui; } QString TFileDirective::getFileDirective() { return m_filedirective; } void TFileDirective::on_bCancel_clicked() { close(); } void TFileDirective::on_bOk_clicked() { QString sFilename = ui->tFilename->text(); QString sSegment = ui->tSegment->text(); QString sType = ui->cType->currentText(); if(sFilename.isEmpty()) { ui->tFilename->setFocus(); return; } if(sSegment.isEmpty()) { ui->tSegment->setFocus(); return; } QString sBetween = "type=\""+sType+"\""; if (ui->cMbfiles->isChecked()) sBetween = "mbfiles"; m_filedirective = QString("\n.file [name=\"%1.%3\", %4, segments=\"%2\"]\n.segment %2[]\n").arg(sFilename).arg(sSegment).arg(sType).arg(sBetween); if(ui->cInsertBasicUpstart2->isChecked()) m_filedirective += "BasicUpstart2(start)\nstart:\n\n"; close(); }
1,241
C++
.cpp
41
24.902439
151
0.645161
emartisoft/IDE65XX
33
7
4
GPL-3.0
9/20/2024, 10:45:00 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,539,830
hexsearchdialog.cpp
emartisoft_IDE65XX/hexsearchdialog.cpp
#include "hexsearchdialog.h" #include "ui_hexsearchdialog.h" #include <QMessageBox> HexSearchDialog::HexSearchDialog(QHexEdit *hexEdit, QWidget *parent) : QDialog(parent), ui(new Ui::HexSearchDialog) { setWindowFlags(this->windowFlags() & ~Qt::WindowContextHelpButtonHint); ui->setupUi(this); _hexEdit = hexEdit; } HexSearchDialog::~HexSearchDialog() { delete ui; } qint64 HexSearchDialog::findNext() { qint64 from = _hexEdit->cursorPosition() / 2; _findBa = getContent(ui->cbFindFormat->currentIndex(), ui->lFind->text()); qint64 idx = -1; if (_findBa.length() > 0) { if (ui->cbBackwards->isChecked()) idx = _hexEdit->lastIndexOf(_findBa, from*2); else idx = _hexEdit->indexOf(_findBa, from); } return idx; } void HexSearchDialog::on_pbFind_clicked() { findNext(); } void HexSearchDialog::on_pbReplace_clicked() { int idx = findNext(); if (idx >= 0) { QByteArray replaceBa = getContent(ui->cbReplaceFormat->currentIndex(), ui->lReplace->text()); replaceOccurrence(idx, replaceBa); } } void HexSearchDialog::on_pbReplaceAll_clicked() { int replaceCounter = 0; int idx = 0; int goOn = QMessageBox::Yes; while ((idx >= 0) && (goOn == QMessageBox::Yes)) { idx = findNext(); if (idx >= 0) { QByteArray replaceBa = getContent(ui->cbReplaceFormat->currentIndex(), ui->lReplace->text()); int result = replaceOccurrence(idx, replaceBa); if (result == QMessageBox::Yes) replaceCounter += 1; if (result == QMessageBox::Cancel) goOn = result; } } if (replaceCounter > 0) QMessageBox::information(this, tr("Find/Replace - Hex editor - IDE 65XX"), QString(tr("%1 occurrences replaced.")).arg(replaceCounter)); } QByteArray HexSearchDialog::getContent(int comboIndex, const QString &input) { QByteArray findBa; switch (comboIndex) { case 0: // hex findBa = QByteArray::fromHex(input.toLatin1()); break; case 1: // text findBa = input.toUtf8(); break; } return findBa; } qint64 HexSearchDialog::replaceOccurrence(qint64 idx, const QByteArray &replaceBa) { int result = QMessageBox::Yes; if (replaceBa.length() >= 0) { if (ui->cbPrompt->isChecked()) { result = QMessageBox::question(this, tr("Find/Replace - Hex editor - IDE 65XX"), tr("Replace occurrence?"), QMessageBox::Yes | QMessageBox::No | QMessageBox::Cancel); if (result == QMessageBox::Yes) { _hexEdit->replace(idx, replaceBa.length(), replaceBa); _hexEdit->update(); } } else { _hexEdit->replace(idx, _findBa.length(), replaceBa); } } return result; }
2,984
C++
.cpp
100
23.05
144
0.59993
emartisoft/IDE65XX
33
7
4
GPL-3.0
9/20/2024, 10:45:00 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
1,539,831
cartconv.cpp
emartisoft_IDE65XX/cartconv.cpp
#include "cartconv.h" #include "ui_cartconv.h" CartConv::CartConv(QWidget *parent) : QDialog(parent), ui(new Ui::CartConv) { setWindowFlags(this->windowFlags() & ~Qt::WindowContextHelpButtonHint); ui->setupUi(this); QFile fType(":/res/data/types.txt"); if(fType.open(QIODevice::ReadOnly | QIODevice::Text)) { QTextStream stream(&fType); while(!stream.atEnd()) ui->cTypes->addItem(stream.readLine()); fType.close(); ui->cTypes->setCurrentIndex(0); } } CartConv::~CartConv() { delete ui; } void CartConv::setCartConvFilename(QString &value) { cartconvFilename = value; } void CartConv::setPrgFilePath(QString prgFilePath) { ui->lPrgFilePath->setText(prgFilePath); } void CartConv::setCartName(QString name) { ui->lCrtCartName->setText(name); } void CartConv::clear() { ui->lPrgFilePath->clear(); ui->lCrtCartName->clear(); ui->tOutput->clear(); ui->bConvert->setFocus(); } void CartConv::on_bPrgFilePath_clicked() { prgFileNames = QFileDialog::getOpenFileNames(this, tr("Select input file(s)"), Common::appLocalDir(), tr("Input File(s) (*.prg;*.bin;*.crt)" )); int t = prgFileNames.count(); if (t == 0) { ui->lPrgFilePath->clear(); return; } QString strPrgFileNames = ""; for (int i=0;i<t;i++) { strPrgFileNames += prgFileNames[i] + "|"; } strPrgFileNames.remove(strPrgFileNames.length()-1,1); ui->lPrgFilePath->setText(strPrgFileNames); } void CartConv::on_bConvert_clicked() { ui->tOutput->clear(); if(ui->lCrtCartName->text().isEmpty()) { ui->tOutput->appendPlainText("Please enter CRT cart name"); ui->lCrtCartName->setFocus(); return; } if(ui->lPrgFilePath->text().isEmpty()) { ui->tOutput->appendPlainText("Please browse input file(s)"); ui->lPrgFilePath->setFocus(); return; } QStringList inputFilenames; inputFilenames = ui->lPrgFilePath->text().split("|"); QString firstFile; if(ui->lPrgFilePath->text().contains('|')) firstFile = inputFilenames[0]; else firstFile = ui->lPrgFilePath->text(); QFileInfo fi(firstFile); QProcess cartconvProcess; QString cartconvOutput = QDir::cleanPath(Common::appConfigDir() + QDir::separator() + "cartconvoutput.txt"); cartconvProcess.setStandardOutputFile(cartconvOutput); cartconvProcess.setStandardErrorFile(cartconvOutput, QIODevice::Append); cartconvProcess.setWorkingDirectory(fi.absolutePath()); QString opFileWithoutExt = QDir::cleanPath(fi.absolutePath() + QDir::separator() + ui->lCrtCartName->text().trimmed() + "."); // cartconv.exe -t normal -name "cartname" -i input.prg -o output.crt QStringList parameters; parameters << "-t" << ui->cTypes->currentText().split(" - ")[0] << "-name" << ui->lCrtCartName->text().trimmed(); if(ui->lPrgFilePath->text().contains('|')) { for (int i=0; i<prgFileNames.count();i++) { parameters << "-i" << prgFileNames[i]; } } else { parameters << "-i" << firstFile; } parameters << "-o" << opFileWithoutExt + "crt"; cartconvProcess.start(cartconvFilename, parameters); cartconvProcess.waitForFinished(); QFile output(cartconvOutput); if(output.open(QIODevice::ReadOnly | QIODevice::Text)) { QTextStream stream(&output); ui->tOutput->appendPlainText(stream.readAll()); output.close(); } if(cartconvProcess.exitCode()!=0) return; if(ui->cConvertToBinary->isChecked()) { // cartconv -i input.crt -o output.bin cartconvProcess.start(cartconvFilename, QStringList() << "-i" << opFileWithoutExt + "crt" << "-o" << opFileWithoutExt + "bin"); cartconvProcess.waitForFinished(); if(output.open(QIODevice::ReadOnly | QIODevice::Text)) { QTextStream stream(&output); ui->tOutput->appendPlainText(stream.readAll()); output.close(); } if(cartconvProcess.exitCode()!=0) return; } // cartconv -f input.crt cartconvProcess.start(cartconvFilename, QStringList() << "-f" << opFileWithoutExt + "crt"); cartconvProcess.waitForFinished(); if(output.open(QIODevice::ReadOnly | QIODevice::Text)) { QTextStream stream(&output); ui->tOutput->appendPlainText(stream.readAll()); output.close(); } }
4,699
C++
.cpp
140
26.542857
135
0.61827
emartisoft/IDE65XX
33
7
4
GPL-3.0
9/20/2024, 10:45:00 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,539,835
tdiskdirective.h
emartisoft_IDE65XX/tdiskdirective.h
#ifndef TDISKDIRECTIVE_H #define TDISKDIRECTIVE_H #include <QDialog> namespace Ui { class TDiskDirective; } class TDiskDirective : public QDialog { Q_OBJECT public: explicit TDiskDirective(QWidget *parent = nullptr); ~TDiskDirective(); QString getDiskDirective(); private slots: void on_tDiskname_textEdited(const QString &arg1); void on_tFilename_textEdited(const QString &arg1); void on_tDiskId_textEdited(const QString &arg1); void on_bCancel_clicked(); void on_bOk_clicked(); void on_bAdd_clicked(); void on_bRemove_clicked(); void on_cDefine_currentIndexChanged(int index); void on_bClear_clicked(); void on_bUp_clicked(); void on_bDown_clicked(); private: Ui::TDiskDirective *ui; QString m_diskdirective; QStringList fl; }; #endif // TDISKDIRECTIVE_H
896
C++
.h
31
23.419355
56
0.709288
emartisoft/IDE65XX
33
7
4
GPL-3.0
9/20/2024, 10:45:00 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,539,836
version.h
emartisoft_IDE65XX/version.h
#ifndef VERSION_H #define VERSION_H // version #define VER_FILEVERSION 0,1,4 #define VER_FILEVERSION_STR "0.1.4\0" #define VER_PRODUCTVERSION 0,1,4 #define VER_PRODUCTVERSION_STR "0.1.4\0" // ------- #define VER_COMPANYNAME_STR "emarti, Murat Ozdemir" #define VER_FILEDESCRIPTION_STR "IDE 65XX" #define VER_INTERNALNAME_STR "IDE 65XX" #define VER_LEGALCOPYRIGHT_STR "Copyright © 2020 emarti, Murat Ozdemir" #define VER_LEGALTRADEMARKS1_STR "All Rights Reserved" #define VER_LEGALTRADEMARKS2_STR VER_LEGALTRADEMARKS1_STR #define VER_ORIGINALFILENAME_STR "IDE65XX.exe" #define VER_PRODUCTNAME_STR "IDE 65XX" #define VER_COMPANYDOMAIN_STR "https://github.com/emartisoft/IDE65XX" #endif // VERSION_H
802
C++
.h
18
42.222222
78
0.690231
emartisoft/IDE65XX
33
7
4
GPL-3.0
9/20/2024, 10:45:00 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,539,837
cartconv.h
emartisoft_IDE65XX/cartconv.h
#ifndef CARTCONV_H #define CARTCONV_H #include <QDialog> #include <QFile> #include <QTextStream> #include <QFileDialog> #include <QProcess> #include "common.h" namespace Ui { class CartConv; } class CartConv : public QDialog { Q_OBJECT public: explicit CartConv(QWidget *parent = nullptr); ~CartConv(); void setCartConvFilename(QString &value); void setPrgFilePath(QString prgFilePath); void setCartName(QString name); void clear(); private slots: void on_bPrgFilePath_clicked(); void on_bConvert_clicked(); private: Ui::CartConv *ui; QString cartconvFilename; QStringList prgFileNames; }; #endif // CARTCONV_H
667
C++
.h
30
19.366667
49
0.748808
emartisoft/IDE65XX
33
7
4
GPL-3.0
9/20/2024, 10:45:00 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,539,838
hint.h
emartisoft_IDE65XX/hint.h
#ifndef HINT_H #define HINT_H #include <QString> #define COUNT 117 namespace Hint { int getHint(QString text); const QString hints[COUNT][3] = { // 6502 opcodes {"adc", "Add Memory to Accumulator with Carry", "A + M + C -&gt; A, C"}, {"and", "AND Memory with Accumulator", "A AND M -&gt; A"}, {"asl", "Shift Left One Bit (Memory or Accumulator)", "C &lt;- [76543210] &lt;- 0"}, {"bcc", "Branch on Carry Clear", "branch on C = 0"}, {"bcs", "Branch on Carry Set", "branch on C = 1"}, {"beq", "Branch on Result Zero", "branch on Z = 1"}, {"bit", "Test Bits in Memory with Accumulator", "A AND M, M7 -&gt; N, M6 -&gt; V"}, {"bmi", "Branch on Result Minus", "branch on N = 1"}, {"bne", "Branch on Result not Zero", "branch on Z = 0"}, {"bpl", "Branch on Result Plus", "branch on N = 0"}, {"brk", "Force Break", "interrupt, push PC+2, push SR"}, {"bvc", "Branch on Overflow Clear", "branch on V = 0"}, {"bvs", "Branch on Overflow Set", "branch on V = 1"}, {"clc", "Clear Carry Flag", "0 -&gt; C"}, {"cld", "Clear Decimal Mode", "0 -&gt; D"}, {"cli", "Clear Interrupt Disable Bit", "0 -&gt; I"}, {"clv", "Clear Overflow Flag", "0 -&gt; V"}, {"cmp", "Compare Memory with Accumulator", "A - M"}, {"cpx", "Compare Memory and Index X", "X - M"}, {"cpy", "Compare Memory and Index Y", "Y - M"}, {"dec", "Decrement Memory by One", "M - 1 -&gt; M"}, {"dex", "Decrement Index X by One", "X - 1 -&gt; X"}, {"dey", "Decrement Index Y by One", "Y - 1 -&gt; Y"}, {"eor", "Exclusive-OR Memory with Accumulator", "A EOR M -&gt; A"}, {"inc", "Increment Memory by One", "M + 1 -&gt; M"}, {"inx", "Increment Index X by One", "X + 1 -&gt; X"}, {"iny", "Increment Index Y by One", "Y + 1 -&gt; Y"}, {"jmp", "Jump to New Location", "(PC+1) -&gt; PCL, (PC+2) -&gt; PCH"}, {"jsr", "Jump to New Location Saving Return Address", "push (PC+2), (PC+1) -&gt; PCL, (PC+2) -&gt; PCH"}, {"lda", "Load Accumulator with Memory", "M -&gt; A"}, {"ldx", "Load Index X with Memory", "M -&gt; X"}, {"ldy", "Load Index Y with Memory", "M -&gt; Y"}, {"lsr", "Shift One Bit Right (Memory or Accumulator)", "0 -&gt; [76543210] -&gt; C"}, {"nop", "No Operation", "---"}, {"ora", "OR Memory with Accumulator", "A OR M -&gt; A"}, {"pha", "Push Accumulator on Stack", "push A"}, {"php", "Push Processor Status on Stack", "push SR"}, {"pla", "Pull Accumulator from Stack", "pull A"}, {"plp", "Pull Processor Status from Stack", "pull SR"}, {"rol", "Rotate One Bit Left (Memory or Accumulator)", "C &lt;- [76543210] &lt;- C"}, {"ror", "Rotate One Bit Right (Memory or Accumulator)", "C -&gt; [76543210] -&gt; C"}, {"rti", "Return from Interrupt", "pull SR, pull PC"}, {"rts", "Return from Subroutine", "pull PC, PC+1 -&gt; PC"}, {"sbc", "Subtract Memory from Accumulator with Borrow", "A - M - C -&gt; A"}, {"sec", "Set Carry Flag", "1 -&gt; C"}, {"sed", "Set Decimal Flag", "1 -&gt; D"}, {"sei", "Set Interrupt Disable Status", "1 -&gt; I"}, {"sta", "Store Accumulator in Memory", "A -&gt; M"}, {"stx", "Store Index X in Memory", "X -&gt; M"}, {"sty", "Store Index Y in Memory", "Y -&gt; M"}, {"tax", "Transfer Accumulator to Index X", "A -&gt; X"}, {"tay", "Transfer Accumulator to Index Y", "A -&gt; Y"}, {"tsx", "Transfer Stack Pointer to Index X", "SP -&gt; X"}, {"txa", "Transfer Index X to Accumulator", "X -&gt; A"}, {"txs", "Transfer Index X to Stack Register", "X -&gt; SP"}, {"tya", "Transfer Index Y to Accumulator", "Y -&gt; A"}, // illegal opcodes {"slo", "Shift left one bit in memory, then OR accumulator with memory.", "M = M * 2, A = A OR M"}, {"sre", "Shift right one bit in memory, then EOR accumulator with memory.", "M = M / 2, A = A EXOR M"}, {"rla", "Rotate one bit left in memory, then AND accumulator with memory.", "M = M ROL, A = A AND M"}, {"rra", "Rotate one bit right in memory, then add memory to accumulator (with carry).", "M = M ROR, A = A ADC M"}, {"sax", "AND X register with accumulator and store result in memory.", "M = A AND X"}, {"lax", "Load accumulator and X register with memory.", "A = M, X = M"}, {"dcp", "Subtract 1 from memory (without borrow) and then CMPs the result with the A register.", "M = M - 1, A - M"}, {"isc", "Increase memory by one, then subtract memory from accu-mulator (with borrow).", "M = M + 1, A = A - M"}, {"anc", "AND byte with accumulator. If result is negative then carry is set.", "A = A AND M"}, {"alr", "AND byte with accumulator, then shift right one bit in accumulator.", "A = A AND M, A = A / 2"}, {"arr", "AND byte with accumulator, then rotate one bit right in accumulator and check bit 5 and 6:", "A = A AND M, A = A / 2"}, {"xaa", "The contents of the X register to the A register and then ANDs the A register with an immediate value.", "A = X AND M"}, {"shy", "AND Y register with (the high byte of the target address of the OPER) + 1. Store the result in memory.", "M = Y AND (MH + 1)"}, {"shx", "AND X register with (the high byte of the target address of the OPER) + 1. Store the result in memory.", "M = X AND (MH + 1)"}, {"tas", "AND X register with accumulator and store result in stack pointer, then AND stack pointer with the high byte of the target address of the OPER + 1. Store result in memory.", "S = X AND A, M = S AND (MH + 1)"}, {"las", "AND memory with stack pointer, transfer result to accumulator, X register and stack pointer.", "A,X,S = M AND S"}, {"ahx", "Stores the result of A AND X AND the high byte of the target address of the operand +1 in memory.", "M = A AND X AND (MH + 1)"}, // 65c02 opcodes {"bbr0", "Branch on Bit Reset", "branch on bit 0 reset"}, {"bbr1", "Branch on Bit Reset", "branch on bit 1 reset"}, {"bbr2", "Branch on Bit Reset", "branch on bit 2 reset"}, {"bbr3", "Branch on Bit Reset", "branch on bit 3 reset"}, {"bbr4", "Branch on Bit Reset", "branch on bit 4 reset"}, {"bbr5", "Branch on Bit Reset", "branch on bit 5 reset"}, {"bbr6", "Branch on Bit Reset", "branch on bit 6 reset"}, {"bbr7", "Branch on Bit Reset", "branch on bit 7 reset"}, {"bbs0", "Branch on Bit Set", "branch on bit 0 set"}, {"bbs1", "Branch on Bit Set", "branch on bit 1 set"}, {"bbs2", "Branch on Bit Set", "branch on bit 2 set"}, {"bbs3", "Branch on Bit Set", "branch on bit 3 set"}, {"bbs4", "Branch on Bit Set", "branch on bit 4 set"}, {"bbs5", "Branch on Bit Set", "branch on bit 5 set"}, {"bbs6", "Branch on Bit Set", "branch on bit 6 set"}, {"bbs7", "Branch on Bit Set", "branch on bit 7 set"}, {"bra", "Branch always", "branch always"}, {"phx", "Push X Register", "push X"}, {"phy", "Push Y Register", "push Y"}, {"plx", "Pull X Register", "pull X"}, {"ply", "Pull Y Register", "pull Y"}, {"rmb0", "Reset Memory Bit", "M = M NAND 2^0"}, {"rmb1", "Reset Memory Bit", "M = M NAND 2^1"}, {"rmb2", "Reset Memory Bit", "M = M NAND 2^2"}, {"rmb3", "Reset Memory Bit", "M = M NAND 2^3"}, {"rmb4", "Reset Memory Bit", "M = M NAND 2^4"}, {"rmb5", "Reset Memory Bit", "M = M NAND 2^5"}, {"rmb6", "Reset Memory Bit", "M = M NAND 2^6"}, {"rmb7", "Reset Memory Bit", "M = M NAND 2^7"}, {"smb0", "Set Memory Bit", "M = M OR 2^0"}, {"smb1", "Set Memory Bit", "M = M OR 2^1"}, {"smb2", "Set Memory Bit", "M = M OR 2^2"}, {"smb3", "Set Memory Bit", "M = M OR 2^3"}, {"smb4", "Set Memory Bit", "M = M OR 2^4"}, {"smb5", "Set Memory Bit", "M = M OR 2^5"}, {"smb6", "Set Memory Bit", "M = M OR 2^6"}, {"smb7", "Set Memory Bit", "M = M OR 2^7"}, {"stp", "Stop the Processor", "stop"}, {"stz", "Stores a zero byte into Memory", "0 -&gt; M"}, {"trb", "Test and Reset Bits", "M = M NAND A, Z = M AND A"}, {"tsb", "Test and Set Bits", "M = M OR A, Z = M AND A"}, {"wai", "Wait for Interrupt", "wait for interrupt"}, // standart macro {"BasicUpstart", "Add BASIC line that starts your code", "10 SYS XXXX"}, {"BasicUpstart2", "Add BASIC line that starts your code", "10 SYS XXXX"} }; }; #endif // HINT_H
8,858
C++
.h
132
57.606061
227
0.535452
emartisoft/IDE65XX
33
7
4
GPL-3.0
9/20/2024, 10:45:00 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,539,839
memoryviewer.h
emartisoft_IDE65XX/memoryviewer.h
#ifndef MEMORYVIEWER_H #define MEMORYVIEWER_H #include <QPaintEvent> #include <QPainter> #include <QWidget> #include <QPoint> #define ADRCOUNT 0x10000 class MemoryViewer : public QWidget { Q_OBJECT public: explicit MemoryViewer(QWidget *parent = nullptr); void poke(int startAddress, int endAddress, QColor color); void reset(); void setLineWidth(int lineWidth); QString getCurrentAddressString(); int getCurrentAddress(); private: bool memory[ADRCOUNT]; QColor memoryColor[ADRCOUNT]; int m_lineWidth; int currentAddress; protected: void paintEvent(QPaintEvent *event) override; void mousePressEvent(QMouseEvent *event) override; signals: void currentAddressChanged(int address); void currentCoordinateChanged(int x, int y); }; #endif // MEMORYVIEWER_H
860
C++
.h
30
24.2
63
0.737745
emartisoft/IDE65XX
33
7
4
GPL-3.0
9/20/2024, 10:45:00 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,539,841
baseplaintextedit.h
emartisoft_IDE65XX/baseplaintextedit.h
#ifndef BASEPLAINTEXTEDIT_H #define BASEPLAINTEXTEDIT_H #include <QPlainTextEdit> #include <QAction> #include <QMenu> #include <QContextMenuEvent> #include <QTextBlock> #include <QTextStream> #include <QPointer> class BasePlainTextEdit : public QPlainTextEdit { Q_OBJECT public: BasePlainTextEdit(QWidget *parent = nullptr); ~BasePlainTextEdit(); QMenu *createMenu(); int getZoom(); void resetZoom(); QAction *toogleBookmark; protected: void contextMenuEvent(QContextMenuEvent *e) override; void wheelEvent(QWheelEvent *e) override; private: QPointer<QMenu> contextMenu; QAction *commentAction; QAction *uncommentAction; QAction *undoAction; QAction *redoAction; QAction *cutAction; QAction *copyAction; QAction *pasteAction; QAction *deleteAction; QAction *selectAllAction; QAction *uppercaseAction; QAction *lowercaseAction; int zoom; public slots: void commentSelectedCode(); void uncommentSelectedCode(); void deleteSelected(); void uppercaseSelectedCode(); void lowercaseSelectedCode(); }; #endif // BASEPLAINTEXTEDIT_H
1,193
C++
.h
44
22.295455
58
0.729038
emartisoft/IDE65XX
33
7
4
GPL-3.0
9/20/2024, 10:45:00 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,539,842
codeeditor.h
emartisoft_IDE65XX/codeeditor.h
#ifndef CODEEDITOR_H #define CODEEDITOR_H #include "baseplaintextedit.h" QT_BEGIN_NAMESPACE class QPaintEvent; class QResizeEvent; class QSize; class QWidget; class QCompleter; QT_END_NAMESPACE class LineNumberArea; class CodeEditor : public BasePlainTextEdit { Q_OBJECT public: CodeEditor(QWidget *parent = nullptr); ~CodeEditor(); void lineNumberAreaPaintEvent(QPaintEvent *event); void lineNumberAreaMousePressEvent(QMouseEvent *event); int lineNumberAreaWidth(); QMenu *getContextMenu(); void setCompleter(QCompleter *c); QCompleter *completer() const; QString textUnderCursor() const; void repaintLineNumberArea(); QList<int> bookmarks; QString getHelpWord(); bool getShowAllChars(){ return showAllChars; }; void setShowAllChars(bool value){ showAllChars = value; }; void setAutoCompletion(bool value) {cAutoCompletion=value;} void setTabSpaceCount(int value) { tabSpaceCount = value;} void setTabSpace(bool value) { tabSpace = value;} protected: void resizeEvent(QResizeEvent *event) override; void keyReleaseEvent(QKeyEvent *event) override; void focusInEvent(QFocusEvent *e) override; void keyPressEvent(QKeyEvent *event) override; bool event(QEvent *event) override; bool eventFilter(QObject *obj, QEvent *event) override; public slots: void highlightCurrentLine(); void insertCompletion(const QString &completion); void setBookmarkOnCurrentLine(); private slots: void updateLineNumberAreaWidth(int newBlockCount); void updateLineNumberArea(const QRect &rect, int dy); private: QWidget *lineNumberArea; QCompleter *c = nullptr; QPixmap bookmarkImage; int bookmarkAreaWidth; QString tooltipWord; bool tooltipShowing; bool showAllChars; bool cAutoCompletion; int tabSpaceCount; bool tabSpace; signals: void bookmarksChanged(quint64 lineNumber, QString text, bool isAdded); void updateLineNumber(quint64 currentLine, int delta); void showFindDialog(); void overWriteModeChanged(); void AfterEnterSendLine(QString line); }; class LineNumberArea : public QWidget { public: LineNumberArea(CodeEditor *editor) : QWidget(editor), codeEditor(editor) { } QSize sizeHint() const override { return QSize(codeEditor->lineNumberAreaWidth(), 0); } protected: void paintEvent(QPaintEvent *event) override { codeEditor->lineNumberAreaPaintEvent(event); } void mousePressEvent(QMouseEvent *event) override { codeEditor->lineNumberAreaMousePressEvent(event); } private: CodeEditor *codeEditor; }; #endif
2,771
C++
.h
87
26.517241
77
0.732804
emartisoft/IDE65XX
33
7
4
GPL-3.0
9/20/2024, 10:45:00 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,539,844
choosetopic.h
emartisoft_IDE65XX/choosetopic.h
#ifndef CHOOSETOPIC_H #define CHOOSETOPIC_H #include <QDialog> namespace Ui { class ChooseTopic; } class ChooseTopic : public QDialog { Q_OBJECT public: explicit ChooseTopic(QWidget *parent = nullptr); ~ChooseTopic(); void setWord(QString word); QString getWord(); private: Ui::ChooseTopic *ui; }; #endif // CHOOSETOPIC_H
378
C++
.h
18
16.888889
53
0.705202
emartisoft/IDE65XX
33
7
4
GPL-3.0
9/20/2024, 10:45:00 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,539,845
bookmarkwidget.h
emartisoft_IDE65XX/bookmarkwidget.h
#ifndef BOOKMARKWIDGET_H #define BOOKMARKWIDGET_H #include <QListView> #include <QPointer> #include <QAction> #include <QMenu> #include <QContextMenuEvent> #include "delegate.h" #include <QStandardItemModel> #include <QStringList> class BookmarkWidget : public QListView { Q_OBJECT public: explicit BookmarkWidget(QWidget *parent = nullptr); QAction *removeAction; QAction *removeAllAction; QAction *editAction; quint64 getLineNumber(int index); QString getFilepath(int index); QString getItemText(int index); QIcon getIcon(int index); void setTopText(int index, QString text); public slots: void addItem(const QPixmap &pixmap, const QString &text, const QString &topText); void removeAll(); void removeItem(int index); void setItemText(int index, QString text); protected: void contextMenuEvent(QContextMenuEvent *e) override; private: QPointer<QMenu> contextMenu; Delegate *delegate; }; #endif // BOOKMARKWIDGET_H
1,031
C++
.h
35
25.171429
86
0.739837
emartisoft/IDE65XX
33
7
4
GPL-3.0
9/20/2024, 10:45:00 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,539,847
customstyle.h
emartisoft_IDE65XX/customstyle.h
#ifndef CUSTOMSTYLE_H #define CUSTOMSTYLE_H #include <QProxyStyle> #include <QStyleFactory> #include <QPainterPath> #include <QSettings> class CustomStyle : public QProxyStyle { Q_OBJECT public: CustomStyle(); QPalette standardPalette() const override; void polish(QWidget *widget) override; void unpolish(QWidget *widget) override; void drawPrimitive(PrimitiveElement element, const QStyleOption *option, QPainter *painter, const QWidget *widget) const override; void drawControl(ControlElement control, const QStyleOption *option, QPainter *painter, const QWidget *widget) const override; private: static void setTexture(QPalette &palette, QPalette::ColorRole role, const QImage &image); static QPainterPath roundRectPath(const QRect &rect); mutable QPalette m_standardPalette; QColor customPaletteColors[5]; QString customTexturesBackgroundImg; QString customTexturesButtonImg; QSettings settings; }; #endif // CUSTOMSTYLE_H
1,060
C++
.h
29
31
80
0.739766
emartisoft/IDE65XX
33
7
4
GPL-3.0
9/20/2024, 10:45:00 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,539,849
common.h
emartisoft_IDE65XX/common.h
#ifndef COMMON_H #define COMMON_H #include <QString> #include <QCoreApplication> #include <QDir> #include <QStandardPaths> namespace Common { QString appLocalDir(); QString appConfigDir(); static const int ALREADYRUNNING = -0x40; }; #endif // COMMON_H
283
C++
.h
13
18.384615
45
0.723485
emartisoft/IDE65XX
33
7
4
GPL-3.0
9/20/2024, 10:45:00 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,539,850
tab.h
emartisoft_IDE65XX/tab.h
#ifndef TAB_H #define TAB_H #include <QSettings> #include <QTextStream> #include <QFile> #include <QtWidgets/QMainWindow> #include <QDockWidget> #include <QPlainTextEdit> #include "highlighter.h" #include "codeeditor.h" class Tab : public QMainWindow { Q_OBJECT public: explicit Tab(QWidget *parent = nullptr); virtual ~Tab(); QTextDocument *getCodeDocument(); void saveCodeToFile(const QString &filePath, bool changeCodeModifiedFlag = true); bool loadCodeFromFile(const QString &filePath); QString getCurrentFilePath(); void setFonts(); CodeEditor *code; Highlighter *highlighter; private: QString currentFilePath; QSettings settings; int oldBlockCount; private slots: void blockCountChanged(int newBlockCount); }; #endif // TAB_H
841
C++
.h
31
22.612903
86
0.732234
emartisoft/IDE65XX
33
7
4
GPL-3.0
9/20/2024, 10:45:00 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,539,852
ideiconprovider.h
emartisoft_IDE65XX/ideiconprovider.h
#ifndef IDEICONPROVIDER_H #define IDEICONPROVIDER_H #include <QFileIconProvider> class IdeIconProvider : public QFileIconProvider { public: IdeIconProvider(); ~IdeIconProvider(); QIcon icon(const QFileInfo &info) const override; private: QIcon m_folder; QIcon m_hdd; QIcon m_asm; QIcon m_prg; QIcon m_lib; QIcon m_txt; QIcon m_bin; QIcon m_sid; QIcon m_dbg; QIcon m_sym; QIcon m_d64; QIcon m_d71; QIcon m_d81; QIcon m_vs; QIcon m_crt; QIcon m_undefined; }; #endif // IDEICONPROVIDER_H
599
C++
.h
28
16.321429
54
0.654189
emartisoft/IDE65XX
33
7
4
GPL-3.0
9/20/2024, 10:45:00 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,539,853
mainwindow.h
emartisoft_IDE65XX/mainwindow.h
#ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QMainWindow> #include <QFileSystemModel> #include <QFileDialog> #include <QMessageBox> #include <QTime> #include <QProcess> #include <QTextStream> #include <QElapsedTimer> #include <QSettings> #include <QTimer> #include <QFileSystemWatcher> #include <QInputDialog> #include <QDesktopServices> #include <QSpinBox> #include <QDragEnterEvent> #include <QDropEvent> #include <QMimeData> #include "tab.h" #include "highlighter.h" #include "common.h" #include "settingswindow.h" #include "about.h" #include "tfiledirective.h" #include "tdiskdirective.h" #include "ideiconprovider.h" #include "bookmarkwidget.h" #include "choosetopic.h" #include "qhexedit2/qhexedit.h" #include "hexsearchdialog.h" #include "cartconv.h" QT_BEGIN_NAMESPACE namespace Ui { class MainWindow; } class QAbstractItemModel; class QCompleter; class CodeEditor; QT_END_NAMESPACE class MainWindow : public QMainWindow { Q_OBJECT public: MainWindow(QWidget *parent = nullptr); ~MainWindow(); public slots: void changeCurrentSavedState(bool changed); void changeCode(); void selectionChangeCode(); void showContextMenu(); void SetCursorPos(); void showFind(); void showAllChars(); void find(const QString &pattern, Qt::CaseSensitivity cs, bool all, bool replace, const QString &replaceText = nullptr); void RunInEmulator(); void Compress(); void OpenWithDirMaster(); void PlayWithSIDPlayer(); void CreateD64Image(); void RemoveFileOrFolder(); void Rename(); void OpenWithHexEditor(); void SetAssemblyFile(); void ConvertToCrt(); void OpenCode(); void OpenHome(); void OpenHelp(); void removeBookmark(); void removeAllBookmark(); void editBookmark(); void bookmarkClicked(const QModelIndex &index); void bookmarksChangedSlot(quint64 lineNumber, QString text, bool isAdded); void updateLineNumberSlot(quint64 currentLine, int delta); void memoryViewerCurrentAddressChanged(int); void memoryViewerCurrentCoordinateChanged(int x, int y); void ReceiveLineForCompleter(QString line); private slots: void on_tvWorkspaceFiles_doubleClicked(const QModelIndex &index); void on_tvWorkspaceFiles_clicked(const QModelIndex &index); void on_actionOpen_triggered(); void on_actionNew_triggered(); void on_actionClose_triggered(); void on_tabWidget_tabCloseRequested(int index); void on_actionSave_triggered(); void on_actionSelect_Workspace_triggered(); void on_actionSave_as_triggered(); void on_actionClose_All_triggered(); void on_actionSaveAll_triggered(); void on_actionExit_triggered(); void on_actionBuild_this_triggered(); void on_bFindClose_clicked(); void on_tabWidget_currentChanged(int index); void on_tFind_textChanged(const QString &arg1); void on_bFindNext_clicked(); void on_bFindAll_clicked(); void on_bReplace_clicked(); void on_bReplaceAll_clicked(); void on_actionSettings_triggered(); void on_actionAbout_triggered(); void on_actionBuild_and_Run_triggered(); void on_actionBuild_as_binary_triggered(); void on_tvWorkspaceFiles_customContextMenuRequested(const QPoint &pos); void on_actionDebugger_triggered(); void on_actionCloseAllButThis_triggered(); void fileChanged(const QString &path); void hexfileChanged(const QString &path); void on_brHome_anchorClicked(const QUrl &arg1); void on_bDescription_clicked(); void on_bIllegal_clicked(); void on_bStandard_clicked(); void on_actionGenerate_File_Directive_triggered(); void on_actionGenerate_Disk_Directive_triggered(); void on_listOpenDocuments_itemSelectionChanged(); void on_actionKick_Assembler_Web_Manual_triggered(); void on_actionInsert_BASIC_SYS_Line_triggered(); void on_actionPuts_A_Breakpoint_triggered(); void on_b65C02opcodes_clicked(); void on_bAssemblerDirectives_clicked(); void on_bPreprocessorDirectives_clicked(); void on_bValueTypes_clicked(); void on_actionWelcome_triggered(); void on_actionCode_triggered(); void on_actionClear_Output_triggered(); void on_tFind_returnPressed(); void on_tIssues_cellDoubleClicked(int row, int column); void on_bStandardMacros_clicked(); void on_sbMemoryViewer_valueChanged(int addressPerLine); void on_horizontalSlider_valueChanged(int value); void on_actionReport_An_Issue_triggered(); // hex editor slots void dataChanged(); void setOverwriteMode(bool mode); void bytesperlineValueChanged(int value); void hexFileFindReplace(); void hexFileRedo(); void hexFileUndo(); void hexFileSaveas(); void hexFileSave(); void hexFileOpen(); void hexNewFile(); void hexFileSaveselection(); void on_actionSet_Assembly_File_For_Current_Tab_triggered(); void on_actionCartridge_Conversion_Utility_triggered(); void on_actionIDE_65XX_Home_Page_triggered(); private: Ui::MainWindow *ui; QFileSystemModel *m_ptrModelForTree; QAction *findAction; QAction *showAllCharsAction; QToolBar *leftToolBar; QString filePath; // selected file on workspace QModelIndex selectedIndex; QString workspacePath; // settings QSettings settings; void writeSettings(); void readSettings(); void readSettingsOptionsOnly(); SettingsWindow *settingsWin; CartConv *cc; QFileSystemWatcher *watcher; QFileSystemWatcher *hexwatcher; IdeIconProvider *icProvider; bool firstOpening; QIcon tabicon; void closeFile(int index); void saveFile(int index = -1); QString saveAsFile(int index = -1, QString caption = "Save file"); void setCurrentTabName(const QString &filePath, int index); void openFileFromPath(QString filenamePath); void openWorkspace(QString wDir); void closeAll(); void setTopToolbar(int index=-1); void printOutput(const QString & message, const QColor &color); void printOutputWithTime(const QString & message, const QColor &color); bool build(bool afterbuildthenrun = false , bool binary = false); // paths QString pJRE; QString pKickAssJar; QString pEmulator; QString pEmulatorParameters; QString pCompressionUtility; QString pCompressionParameters; QString pSIDPlayer; QString pSIDPlayerParameters; QString pCartconv; QString pDirMaster; QString pC1541; QString pDebugger; QString pAssemblyFile; QString asmNotSelected = "[ Assembly file not selected ]"; bool pOpenLastUsedFiles; int pMaxRecentWorkspace; int pTabSize; int pTabPolicy; QString pCodeFontName; int pCodeFontSize; bool pWordWrap; bool pShowAllChars; bool pAutoCompletion; int pZoom; bool bWelcome; QStringList opendocuments; void RefreshOpenDocuments(); BookmarkWidget *bookmarks; QSettings bookmarkcfgfile; QHexEdit *hexEdit; QLabel *hexFilename; // QSpinBox *bytesPerLine; // QCheckBox *hexInsert; QAction *hRedo; QAction *hUndo; QAction *hSave; QAction *hSaveas; QAction *hSaveselection; void hexActionEnable(); void saveHexFile(QString &hfilename, bool saveSelection=false); void loadHexFile(); QString curHexFilename; HexSearchDialog *hexSearchDialog; QProcess p; void ExecuteAppWithFile(QString pApplication, QString additionalArgs=""); QMenu *fileContextMenu; QAction *menuDirmaster; QAction *menuExomizer; QAction *menuEmulator; QAction *menuC1541; QAction *menuDelete; QAction *menuRename; QAction *menuSidPlayer; QAction *menuHexEditor; QAction *menuAssemblyFile; QAction *menuCartConv; QAbstractItemModel *modelFromFile(const QString& fileName); QCompleter *completer = nullptr; QAction *menuHome; QAction *menuCode; QLabel *spacerTop, *spacerBottom, *spacerMiddle; //vertical spacer for left toolbar QLabel *statusCurPosInfo; //QByteArray dockState; void HideDocks(); void RestoreDocks(); void UpdateRecentWorkspaces(); void RemoveFromRecentWorkspace(QString wspc); void AddRecentWorkspace(QString wspc); void setActionsEnable(bool value); void setActionsEnableForDoc(bool value); void insertCode(QString code, QTextCursor::MoveOperation operation = QTextCursor::Start); // issues void clearIssues(); void grabIssues(QString currentLine, QTextStream &tStr); void addIssue(QString issue, QString filename, QString line); void grabMemoryView(QString currentLine, QTextStream &tStr); int lastMemoryViewX = -1; int lastMemoryViewY = -1; bool sbMemoryViewerValueNotChanged = true; void prepareBeforeOpen(QString filename); void saveUserCompleter(); protected: void closeEvent(QCloseEvent *event) override; void keyReleaseEvent(QKeyEvent *event) override; bool eventFilter(QObject *obj, QEvent *event) override; void dragEnterEvent(QDragEnterEvent *event) override; void dropEvent(QDropEvent *event) override; }; #endif // MAINWINDOW_H
9,474
C++
.h
268
29.660448
94
0.726145
emartisoft/IDE65XX
33
7
4
GPL-3.0
9/20/2024, 10:45:00 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,539,857
darkfusionstyle.h
emartisoft_IDE65XX/darkfusionstyle.h
#ifndef DARKFUSIONSTYLE_H #define DARKFUSIONSTYLE_H #include <QProxyStyle> #include <QStyleFactory> #include <QPainterPath> class DarkFusionStyle : public QProxyStyle { Q_OBJECT public: DarkFusionStyle(QStyle *style = QStyleFactory::create("fusion")); void polish(QPalette &palette) override; }; #endif // DARKFUSIONSTYLE_H
355
C++
.h
13
23.923077
70
0.761905
emartisoft/IDE65XX
33
7
4
GPL-3.0
9/20/2024, 10:45:00 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,539,858
settingswindow.h
emartisoft_IDE65XX/settingswindow.h
#ifndef SETTINGSWINDOW_H #define SETTINGSWINDOW_H #include <QDialog> #include <QFileDialog> #include <QFontDialog> #include <QColorDialog> #include <QTextStream> #include <QSettings> #include <QMessageBox> #include "common.h" #include "popupmenu.h" namespace Ui { class SettingsWindow; } class SettingsWindow : public QDialog { Q_OBJECT public: explicit SettingsWindow(QWidget *parent = nullptr); ~SettingsWindow(); void setJRE(QString &value); void setKickAssJar(QString &value); void setEmulator(QString &value); void setEmulatorParameters(QString &value); void setCompressionUtility(QString &value); void setCompressionParameters(QString &value); void setDirMaster(QString &value); void setC1541(QString &value); void setDebugger(QString &value); void setOpenLastUsedFiles(bool open); void setMaxRecentWorkspace(int count); void setTabSize(int size); void setTabPolicy(int index); void setCodeFontName(QString &fontName); void setCodeFontSize(int fontSize); void setApplicationFont(QString fontName, int fontSize); void setApplicationTheme(int select); void setWordWrap(bool &value); void setShowAllCharacters(bool &value); void setAutoCompletion(bool &value); void setSIDPlayer(QString &value); void setSIDPlayerParameters(QString &value); void setCartconv(QString &value); void setCustomBackgroundTexture(QString value); void setCustomButtonTexture(QString value); void setBackground(QColor c); void setBrightText(QColor c); void setBase(QColor c); void setHighlights(QColor c); void setDisable(QColor c); void setOpcode(QColor c); void setNumber(QColor c); void setFunction(QColor c); void setAssemblerDir(QColor c); void setPreprocessorDir(QColor c); void setComment(QColor c); void setQuotation(QColor c); void setLabel(QColor c); void setCmdLinesEnabledForDebug(bool debugdump = true, bool vicesymbols = true); bool getCmdLineDebugDump(); bool getCmdLineViceSymbols(); QString getJRE(); QString getKickAssJar(); QString getEmulator(); QString getEmulatorParameters(); QString getCompressionUtility(); QString getCompressionParameters(); QString getDirMaster(); QString getC1541(); QString getDebugger(); QString getSIDPlayer(); QString getSIDPlayerParameters(); QString getCartconv(); QString getBuildDir(); bool getOpenLastUsedFiles(); int getMaxRecentWorkspace(); int getTabSize(); int getTabPolicy(); QString getCodeFontName(); int getCodeFontSize(); bool getWordWrap(); bool getShowAllCharacters(); bool getAutoCompletion(); bool restartRequired; void ReadCmdLineOption(); bool getCheckShowMemCmdLine(); private slots: void on_bKickAssJar_clicked(); void on_bJRE_clicked(); void on_bEmulator_clicked(); void on_bCompressionUtility_clicked(); void on_bChangeFontOutput_clicked(); void on_coAsminfo_toggled(bool checked); void on_coBytedump_toggled(bool checked); void on_coDefine_toggled(bool checked); void on_coFillbyte_toggled(bool checked); void on_coLibdir_toggled(bool checked); void on_coMaxaddr_toggled(bool checked); void on_coO_toggled(bool checked); void on_coOutputDir_toggled(bool checked); void on_coReplacefile_toggled(bool checked); void on_coLog_toggled(bool checked); void on_coExtra_toggled(bool checked); void on_buttonBox_accepted(); void on_coExecutelog_toggled(bool checked); void on_coSymbolfile_toggled(bool checked); void on_bDirMaster_clicked(); void on_bC1541_clicked(); void on_bDebugger_clicked(); void on_bSIDPlayer_clicked(); void on_bChangeFontOutput2_clicked(); void on_cTheme_currentIndexChanged(int index); void setVice(); void setEmu64(); void setHoxs64(); void setMicro64(); void setZ64K(); void on_bCartconv_clicked(); void on_cTheme_currentTextChanged(const QString &arg1); void on_bBackgroundTexture_clicked(); void on_bButtonTexture_clicked(); void on_bBackgroundColor_clicked(); void on_bBrightTextColor_clicked(); void on_bBaseColor_clicked(); void on_bHighlightsColor_clicked(); void on_bDisableColor_clicked(); void on_bOpcode_clicked(); void on_bNumber_clicked(); void on_bFunction_clicked(); void on_bAssemblerDir_clicked(); void on_bPreprocessorDir_clicked(); void on_bComment_clicked(); void on_bQuotation_clicked(); void on_bLabel_clicked(); private: Ui::SettingsWindow *ui; QSettings cmdline; QSettings settings; void NoEmptyForInputText(); #ifdef Q_OS_MACOS void changePathForMacOSAppFile(QString &AppFilePath); #endif }; #endif // SETTINGSWINDOW_H
5,056
C++
.h
144
28.958333
85
0.717917
emartisoft/IDE65XX
33
7
4
GPL-3.0
9/20/2024, 10:45:00 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,539,876
mapdownloaddialog.cpp
fafa1899_SinianGIS/SinianGIS/mapdownloaddialog.cpp
#include "mapdownloaddialog.h" #include "ui_mapdownloaddialog.h" #include "Settings.h" #include "GoogleMapTiles.h" #include <QFileDialog> #include <iostream> using namespace std; MapDownloadDialog::MapDownloadDialog(QWidget *parent) : QDialog(parent), ui(new Ui::MapDownloadDialog) { ui->setupUi(this); ui->lELeft->setText(gSettings->value("Left").toString()); ui->lETop->setText(gSettings->value("Top").toString()); ui->lERight->setText(gSettings->value("Right").toString()); ui->lEBottom->setText(gSettings->value("Bottom").toString()); ui->spinBoxDownLoadLevel->setValue(gSettings->value("DownLoadLevel").toInt()); ui->lineEditDownLoadProxy->setText(gSettings->value("DownLoadProxy").toString()); } MapDownloadDialog::~MapDownloadDialog() { delete ui; } void MapDownloadDialog::SaveIniConfig() { gSettings->setValue("Left", ui->lELeft->text()); gSettings->setValue("Top", ui->lETop->text()); gSettings->setValue("Right", ui->lERight->text()); gSettings->setValue("Bottom", ui->lEBottom->text()); gSettings->setValue("DownLoadLevel", ui->spinBoxDownLoadLevel->value()); gSettings->setValue("DownLoadProxy", ui->lineEditDownLoadProxy->text()); } void MapDownloadDialog::on_pBOK_clicked() { SaveIniConfig(); WebTilesClass *webTiles = new GoogleMapTiles(); double l = ui->lELeft->text().toDouble(); double t = ui->lETop->text().toDouble(); double r = ui->lERight->text().toDouble(); double b = ui->lEBottom->text().toDouble(); int z = ui->spinBoxDownLoadLevel->value(); auto proxy = ui->lineEditDownLoadProxy->text().toLocal8Bit(); auto outputDir = ui->lEOutDir->text().toLocal8Bit(); vector<OneTile> tiles; webTiles->GetTiles(l, t, r, b, z, tiles); //size_t i = 0; for (size_t i = 0; i < tiles.size(); i++) { cout << (float)(i + 1) / tiles.size() << endl; string imgName = string(outputDir.data()) + "/" + to_string(tiles[i].y) + "_" + to_string(tiles[i].x); string imgPath = imgName + ".jpg"; DownloadTiles(tiles[i].uri, imgPath, proxy.data()); webTiles->WriteGeoInfo(imgName, tiles[i]); } delete webTiles; QDialog::accept(); } void MapDownloadDialog::on_pBCancel_clicked() { QDialog::reject(); } void MapDownloadDialog::on_pBOutDir_clicked() { QString dir = gSettings->value("DownLoadTilesDir").toString(); QString dirPath = QFileDialog::getExistingDirectory(this,QString::fromLocal8Bit("选择下载文件夹:"), dir); if(dirPath.isNull()) { return; } gSettings->setValue("DownLoadTilesDir", dirPath); ui->lEOutDir->setText(dirPath); }
2,660
C++
.cpp
72
32.680556
110
0.681871
fafa1899/SinianGIS
30
14
2
GPL-3.0
9/20/2024, 10:45:00 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,539,877
sceneprojectbase.cpp
fafa1899_SinianGIS/SinianGIS/sceneprojectbase.cpp
#include "sceneprojectbase.h" #include <iostream> #include <fstream> #include <iomanip> #include <QJsonDocument> #include <QDebug> #include <QFile> #include <QMessageBox> #include "pathref.hpp" using namespace std; static int projIndex = 0; SceneProjectBase::SceneProjectBase() { appDir = PathRef::GetAppDir(); projectFilePath = "新建_"; projectFilePath = projectFilePath + to_string(projIndex++); } SceneProjectBase::~SceneProjectBase() { } void SceneProjectBase::read(std::string path) { QFile file(QString::fromLocal8Bit(path.c_str())); if(!file.open(QIODevice::ReadOnly)) { QMessageBox::critical(nullptr, QString::fromLocal8Bit("错误"), QString::fromLocal8Bit("不能读取工程文件")); return; } QByteArray ba = file.readAll(); QJsonParseError e; QJsonDocument jsonDoc = QJsonDocument::fromJson(ba, &e); if(e.error == QJsonParseError::NoError && !jsonDoc.isNull()) { projectJSON = jsonDoc.object(); } } void SceneProjectBase::write(std::string path) { QJsonDocument document; document.setObject(projectJSON); QByteArray simpbyte_array = document.toJson(QJsonDocument::Indented); QFile file(QString::fromLocal8Bit(path.c_str())); if(!file.open(QIODevice::WriteOnly)) { QMessageBox::critical(nullptr, QString::fromLocal8Bit("错误"), QString::fromLocal8Bit("不能保存工程文件")); return; } file.write(simpbyte_array); file.close(); }
1,469
C++
.cpp
50
25.16
105
0.713564
fafa1899/SinianGIS
30
14
2
GPL-3.0
9/20/2024, 10:45:00 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,539,878
osgshowwidget.cpp
fafa1899_SinianGIS/SinianGIS/osgshowwidget.cpp
#include "osgshowwidget.h" #include "ViewWidget" #include "pathref.hpp" #include <QLayout> #include <QMessageBox> #include <osgEarth/ModelLayer> #include <osgEarth/GLUtils> #include <osgViewer/Viewer> #include <osgViewer/ViewerEventHandlers> #include <osgEarthUtil/ViewFitter> #include <osgEarthUtil/AutoClipPlaneHandler> using namespace std; OSGShowWidget::OSGShowWidget(QWidget *parent) : QWidget(parent) { viewWidget = nullptr; bWork = false; _viewer.setThreadingModel(_viewer.SingleThreaded); // we have to add a starting view, otherwise the CV will automatically // mark itself as done :/ addView(); // timer fires a paint event. // connect(&_timer, SIGNAL(timeout()), this, SLOT(update())); // _timer.start(10); //sceneProject3D = nullptr; } OSGShowWidget::~OSGShowWidget() { if(viewWidget) { delete viewWidget; viewWidget = nullptr; } } //bool OSGShowWidget::load3DProject(std::shared_ptr<SceneProject3D> project) //{ // this->sceneProject3D = project; // view->setSceneData(sceneProject3D->GetRootNode()); // mainManipulator->setViewpoint(*(sceneProject3D->GetHomeViewPoint())); // mainManipulator->setHomeViewpoint(*(sceneProject3D->GetHomeViewPoint())); // view->getCamera()->addCullCallback(new osgEarth::Util::AutoClipPlaneCullCallback(sceneProject3D->GetMapNode())); //加上自动裁剪。否则显示会出现遮挡 // return true; //} //void OSGShowWidget::paintEvent(QPaintEvent* e) //{ // refresh all the views. // if (_viewer.getRunFrameScheme() == osgViewer::ViewerBase::CONTINUOUS || _viewer.checkNeedToDoFrame() ) // { // _viewer.frame(); // } //} //启动定时器绘制 void OSGShowWidget::onStartTimer() { _timerID = startTimer(10); bWork = true; } //关闭定时器绘制 void OSGShowWidget::onStopTimer() { killTimer(_timerID); bWork = false; } //定时器事件 void OSGShowWidget::timerEvent(QTimerEvent* ) { // refresh all the views. if (_viewer.getRunFrameScheme() == osgViewer::ViewerBase::CONTINUOUS || _viewer.checkNeedToDoFrame() ) { _viewer.frame(); } } void OSGShowWidget::addView() { // the new View we want to add: view = new osgViewer::View(); // a widget to hold our view: viewWidget = new osgEarth::QtGui::ViewWidget(view); setLayout(new QHBoxLayout()); layout()->setMargin(1); layout()->addWidget(viewWidget); // set up the view //mainManipulator = new osgEarth::Util::EarthManipulator; //view->setCameraManipulator(mainManipulator); //view->setSceneData( root ); view->getDatabasePager()->setUnrefImageDataAfterApplyPolicy(true,false); view->getCamera()->setSmallFeatureCullingPixelSize(-1.0f); //LabelNode需要 osgEarth::GLUtils::setGlobalDefaults(view->getCamera()->getOrCreateStateSet()); //FeatureNode需要 //view->getCamera()->addCullCallback(new osgEarth::Util::AutoClipPlaneCullCallback(node)); //加上自动裁剪。否则显示会出现遮挡 //osgEarth::Util::MapNodeHelper().configureView(view); // add some stock OSG handlers: view->addEventHandler(new osgViewer::StatsHandler()); view->addEventHandler(new osgViewer::HelpHandler); // add it to the composite viewer. _viewer.addView( view ); } //void OSGShowWidget::SetTerrainLayerViewPoint(std::string name) //{ // auto layer = sceneProject3D->GetMap()->getLayerByName<osgEarth::TerrainLayer>(name); // if (!layer) // { // QMessageBox::critical(this, QString::fromLocal8Bit("警告"), QString::fromLocal8Bit("找不到合适的视点"), QMessageBox::Ok); // return; // } // //获取视点位置 // std::shared_ptr<osgEarth::Viewpoint> vp = std::make_shared<osgEarth::Viewpoint>(); // if (!CalViewPointGeoExtend(layer->getDataExtentsUnion(), vp)) // { // QMessageBox::critical(this, QString::fromLocal8Bit("警告"), QString::fromLocal8Bit("找不到合适的视点"), QMessageBox::Ok); // auto cp = layer->getDataExtentsUnion().getCentroid(); // osgEarth::GeoPoint point(layer->getProfile()->getSRS(), cp.x(), cp.y(), cp.z()); // osgEarth::GeoPoint newPoint = point.transform(sceneProject3D->GetMap()->getSRS()); // vp->focalPoint() = newPoint; // vp->heading() = 0; // vp->pitch() = -90; // vp->range() = 16000; // } // sceneProject3D->insertViewPoint(name, vp); // mainManipulator->setViewpoint(*vp); //} //void OSGShowWidget::SetNodeViewPoint(std::string name) //{ // auto layer = sceneProject3D->GetMap()->getLayerByName<osgEarth::VisibleLayer>(name); // if (!layer) // { // QMessageBox::critical(this, QString::fromLocal8Bit("警告"), QString::fromLocal8Bit("找不到合适的视点"), QMessageBox::Ok); // return; // } // //计算视点 // std::shared_ptr<osgEarth::Viewpoint> vp = std::make_shared<osgEarth::Viewpoint>(); // if(!layer->getNode() || !CalViewPointNode(layer->getNode(), vp)) // { // QMessageBox::critical(this, QString::fromLocal8Bit("警告"), QString::fromLocal8Bit("找不到合适的视点"), QMessageBox::Ok); // // out->focalPoint() = point; // // out->heading() = 0; // // out->pitch() = -90; // // out->range() = 16000; // } // sceneProject3D->insertViewPoint(name, vp); // mainManipulator->setViewpoint(*vp); //}
5,375
C++
.cpp
139
35.330935
147
0.671308
fafa1899/SinianGIS
30
14
2
GPL-3.0
9/20/2024, 10:45:00 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,539,879
main.cpp
fafa1899_SinianGIS/SinianGIS/main.cpp
#include "mainwindow.h" #include "osgshowwidget.h" #include "pathref.hpp" #include "ViewWidget" #include "Settings.h" #include "regedit.h" #include <iostream> #include <gdal_priv.h> #include <QApplication> #include <QStyleFactory> using namespace std; QSettings* gSettings = nullptr; void InitGDALEnvi() { GDALAllRegister(); CPLSetConfigOption("GDAL_FILENAME_IS_UTF8", "NO"); //支持中文路径 CPLSetConfigOption("SHAPE_ENCODING", ""); //解决中文乱码问题 string dir = PathRef::GetAppDir() + "/Resource/gdal_data"; CPLSetConfigOption("GDAL_DATA", dir.c_str()); } void regeditRef() { QString className = QString::fromLocal8Bit("SinianGIS"); // 自定义的类别 QString appPath = QCoreApplication::applicationFilePath(); // 关联的程序目录 QString ext = QString::fromLocal8Bit(".sj"); // 关联的文件类型 QString extDes = QString::fromLocal8Bit("SinianGIS工程文件"); // 该文件类型描述 registerFileRelation(className, appPath, ext, extDes); // ext = QString::fromLocal8Bit(".obj"); // registerFileRelation(className, appPath, ext, extDes); } int main(int argc, char *argv[]) { QApplication::setStyle(QStyleFactory::create("Fusion")); QApplication a(argc, argv); //QSettings能记录一些程序中的信息,下次再打开时可以读取出来 string iniPath = PathRef::GetAppDir() + "/SinianGIS.ini"; QSettings setting(QString::fromLocal8Bit(iniPath.c_str()), QSettings::IniFormat); gSettings = &setting; InitGDALEnvi(); //regeditRef(); string filePath; if(argc>1) { filePath = argv[1]; } MainWindow mainWindow(filePath); mainWindow.show(); return a.exec(); } // 错误调试代码 // for(int i = 10; i>-1; i--) // { // int k =10/i; // cout<<k<<endl; // }
1,872
C++
.cpp
55
29.436364
101
0.647365
fafa1899/SinianGIS
30
14
2
GPL-3.0
9/20/2024, 10:45:00 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,539,880
WebTilesClass.cpp
fafa1899_SinianGIS/SinianGIS/WebTilesClass.cpp
#include "WebTilesClass.h" #include <curl/curl.h> #include <iostream> #include <string> using namespace std; WebTilesClass::WebTilesClass() { } WebTilesClass::~WebTilesClass() { } bool WebTilesClass::GetTiles(double left, double top, double right, double bottom, int level, vector<OneTile> &tiles) { return false; } bool WebTilesClass::WriteGeoInfo(string imgName, OneTile& tile) { return false; } int DownloadTiles(std::string address, std::string outfile, std::string proxy) { //cout << address << endl; curl_global_init(CURL_GLOBAL_ALL); CURL *curl = curl_easy_init(); //设置代理 if (!proxy.empty()) { curl_easy_setopt(curl, CURLOPT_PROXY, proxy.c_str()); } curl_easy_setopt(curl, CURLOPT_URL, address.c_str()); //设置useragent curl_easy_setopt(curl, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36"); FILE *fp = nullptr; if (fopen_s(&fp, outfile.c_str(), "wb") != 0) { curl_easy_cleanup(curl); return CURL_LAST; } //CURLOPT_WRITEFUNCTION 将后继的动作交给write_data函数处理 //std::cout << curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data) << std::endl; curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp); //curl_easy_setopt(curl, CURLOPT_NOPROGRESS, false); //curl_easy_setopt(curl, CURLOPT_PROGRESSFUNCTION, my_progress_func); ////curl_easy_setopt(curl, CURLOPT_PROGRESSDATA, nullptr); CURLcode error = curl_easy_perform(curl); fclose(fp); curl_easy_cleanup(curl); return error; }
1,532
C++
.cpp
49
28.795918
162
0.738079
fafa1899/SinianGIS
30
14
2
GPL-3.0
9/20/2024, 10:45:00 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,539,881
osg3dglobalshowwidget.cpp
fafa1899_SinianGIS/SinianGIS/osg3dglobalshowwidget.cpp
#include "osg3dglobalshowwidget.h" #include <osgEarthUtil/ViewFitter> #include <osgEarthUtil/AutoClipPlaneHandler> #include <iostream> #include <QMessageBox> using namespace std; OSG3DGlobalShowWidget::OSG3DGlobalShowWidget(QWidget *parent):OSGShowWidget(parent) { sceneProject3D = nullptr; mainManipulator = new osgEarth::Util::EarthManipulator; view->setCameraManipulator(mainManipulator); } OSG3DGlobalShowWidget::~OSG3DGlobalShowWidget() { } bool OSG3DGlobalShowWidget::load3DProject(std::shared_ptr<SceneProject3D> project) { sceneProject3D = project; name = sceneProject3D?sceneProject3D->getFileName():""; view->setSceneData(sceneProject3D->GetRootNode()); mainManipulator->setViewpoint(*(sceneProject3D->GetHomeViewPoint())); mainManipulator->setHomeViewpoint(*(sceneProject3D->GetHomeViewPoint())); view->getCamera()->addCullCallback(new osgEarth::Util::AutoClipPlaneCullCallback(sceneProject3D->GetMapNode())); //加上自动裁剪。否则显示会出现遮挡 return true; } void OSG3DGlobalShowWidget::SetTerrainLayerViewPoint(std::string name) { auto layer = sceneProject3D->GetMap()->getLayerByName<osgEarth::TerrainLayer>(name); if (!layer) { QMessageBox::critical(this, QString::fromLocal8Bit("警告"), QString::fromLocal8Bit("找不到合适的视点"), QMessageBox::Ok); return; } //获取视点位置 std::shared_ptr<osgEarth::Viewpoint> vp = std::make_shared<osgEarth::Viewpoint>(); if (!CalViewPointGeoExtend(layer->getDataExtentsUnion(), vp)) { QMessageBox::critical(this, QString::fromLocal8Bit("警告"), QString::fromLocal8Bit("找不到合适的视点"), QMessageBox::Ok); auto cp = layer->getDataExtentsUnion().getCentroid(); osgEarth::GeoPoint point(layer->getProfile()->getSRS(), cp.x(), cp.y(), cp.z()); osgEarth::GeoPoint newPoint = point.transform(sceneProject3D->GetMap()->getSRS()); vp->focalPoint() = newPoint; vp->heading() = 0; vp->pitch() = -90; vp->range() = 16000; } sceneProject3D->insertViewPoint(name, vp); mainManipulator->setViewpoint(*vp); } void OSG3DGlobalShowWidget::SetNodeViewPoint(std::string name) { auto layer = sceneProject3D->GetMap()->getLayerByName<osgEarth::VisibleLayer>(name); if (!layer) { QMessageBox::critical(this, QString::fromLocal8Bit("警告"), QString::fromLocal8Bit("找不到合适的视点"), QMessageBox::Ok); return; } //计算视点 std::shared_ptr<osgEarth::Viewpoint> vp = std::make_shared<osgEarth::Viewpoint>(); if(!layer->getNode() || !CalViewPointNode(layer->getNode(), vp)) { QMessageBox::critical(this, QString::fromLocal8Bit("警告"), QString::fromLocal8Bit("找不到合适的视点"), QMessageBox::Ok); // out->focalPoint() = point; // out->heading() = 0; // out->pitch() = -90; // out->range() = 16000; } sceneProject3D->insertViewPoint(name, vp); mainManipulator->setViewpoint(*vp); } // bool OSG3DGlobalShowWidget::CalViewPointGeoExtend(const osgEarth::GeoExtent& extent, std::shared_ptr<osgEarth::Viewpoint> out) { // double xMin = extent.xMin(); double xMax = extent.xMax(); double yMin = extent.yMin(); double yMax = extent.yMax(); double z = extent.getCentroid().z(); //获取范围的四个点 std::vector<osgEarth::GeoPoint> points = { osgEarth::GeoPoint(extent.getSRS(), xMin, yMin, z), osgEarth::GeoPoint(extent.getSRS(), xMax, yMin, z), osgEarth::GeoPoint(extent.getSRS(), xMax, yMax, z), osgEarth::GeoPoint(extent.getSRS(), xMin, yMax, z) }; //计算视点 osgEarth::Util::ViewFitter vf(sceneProject3D->GetMap()->getSRS(), view->getCamera()); if(!vf.createViewpoint(points, *out)) { return false; } out->heading() = 0; //创建的视点是没有设置heading的,当设置到漫游器的时候,就会用当前的heading return true; } //计算视点 bool OSG3DGlobalShowWidget::CalViewPointNode(osg::ref_ptr<osg::Node> node, std::shared_ptr<osgEarth::Viewpoint> out) { //计算范围 有问题:最大最小z值错误 // osg::ComputeBoundsVisitor boundvisitor; // xform->accept(boundvisitor); // osg::BoundingBox bb = boundvisitor.getBoundingBox(); //计算包围盒 osg::BoundingSphere bs; node->computeBound(); bs = node->getBound(); // double xMin = bs.center().x() - bs.radius(); double xMax = bs.center().x() + bs.radius(); double yMin = bs.center().y() - bs.radius(); double yMax = bs.center().y() + bs.radius(); double zMin = bs.center().z() - bs.radius(); double zMax = bs.center().z() + bs.radius(); //获取范围的四个点 vector<osg::Vec3d> boundPoint= {osg::Vec3d(xMin, yMin, zMin), osg::Vec3d(xMax, yMin, zMin), osg::Vec3d(xMax, yMax, zMin), osg::Vec3d(xMin, yMax, zMin), osg::Vec3d(xMin, yMin, zMax), osg::Vec3d(xMax, yMin, zMax), osg::Vec3d(xMax, yMax, zMax), osg::Vec3d(xMin, yMax, zMax)}; // vector<osg::Vec3d> boundPoint= {osg::Vec3d(xMin, yMin, bs.center().z()), osg::Vec3d(xMax, yMin, bs.center().z()), // osg::Vec3d(xMax, yMax, bs.center().z()), osg::Vec3d(xMin, yMax, bs.center().z())}; std::vector<osgEarth::GeoPoint> points; for(auto &it: boundPoint) { osgEarth::GeoPoint convertPoint; convertPoint.fromWorld(sceneProject3D->GetMap()->getSRS(), it); points.push_back(convertPoint); } //计算视点 osgEarth::Util::ViewFitter vf(sceneProject3D->GetMap()->getSRS(), view->getCamera()); double value_meters = bs.radius()*0.2; vf.setBuffer(value_meters); if(!vf.createViewpoint(points, *out)) { return false; } // qDebug()<<out->focalPoint()->x()<<'\t'<<out->focalPoint()->y()<<'\t'<<out->focalPoint()->z(); // qDebug()<<out->range()->getValue(); out->heading() = 0; //创建的视点是没有设置heading的,当设置到漫游器的时候,就会用当前的heading return true; } void OSG3DGlobalShowWidget::slotViewPoint(std::string name) { auto vp = sceneProject3D->getViewPoint(name); if (!vp) { QMessageBox::critical(this, QString::fromLocal8Bit("警告"), QString::fromLocal8Bit("找不到合适的视点"), QMessageBox::Ok); return; } mainManipulator->setViewpoint(*vp); }
6,464
C++
.cpp
151
35.880795
145
0.65159
fafa1899/SinianGIS
30
14
2
GPL-3.0
9/20/2024, 10:45:00 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,539,883
mainwindow.cpp
fafa1899_SinianGIS/SinianGIS/mainwindow.cpp
#include "mainwindow.h" #include "ui_mainwindow.h" #include "sceneproject3d.h" #include "pathref.hpp" #include "project3dform.h" #include "loadphotogrammetrydialog.h" #include "osgshowwidget.h" #include "Settings.h" #include "mapdownloaddialog.h" #include "osg3dglobalshowwidget.h" #include "osg3dobjectshowwidget.h" #include <QDockWidget> #include <QMenu> #include <QFileDialog> #include <QDebug> #include <QMessageBox> #include <iostream> using namespace std; MainWindow::MainWindow(string filePath, QWidget *parent) : QMainWindow(parent) , ui(new Ui::MainWindow) { initWindow = false; curProj = nullptr; curLeftDock = nullptr; ui->setupUi(this); //设置ribbon ui->ribbonTabWidget->setCurrentIndex(0); ui->toolBar->addWidget(ui->ribbonTabWidget); ui->toolBar->layout()->setMargin(0); ui->toolBar->layout()->setSpacing(0); // QMenu* ArcGISMenu=new QMenu(this); ArcGISMenu->addAction(ui->actionArcGISImage); ArcGISMenu->addAction(ui->actionArcGISTerrain); ui->tBArcGIS->setMenu(ArcGISMenu); ui->tBArcGIS->setPopupMode(QToolButton::InstantPopup); QMenu* BingMenu=new QMenu(this); BingMenu->addAction(ui->actionBingImage); BingMenu->addAction(ui->actionBingTerrain); ui->tBBing->setMenu(BingMenu); ui->tBBing->setPopupMode(QToolButton::InstantPopup); if(filePath.empty()) { std::shared_ptr<SceneProject3D> _3dProject = make_shared<SceneProject3D>(); loadProject(_3dProject); } else { loadData(filePath); } initWindow = true; } MainWindow::~MainWindow() { delete ui; } void MainWindow::show() { QWidget::show(); //ui->showWidget->onStartTimer(); OSGShowWidget *widget = dynamic_cast<OSGShowWidget *>(ui->centralTabWidget->currentWidget()); if(widget && !widget->isWork()) { widget->onStartTimer(); } } void MainWindow::loadData(std::string filePath) { int type = -1; string format = PathRef::GetFormat(filePath); if(format == ".sj") { type = 0; } else if(format == ".osg" || format == ".osgb" || format == ".obj") { type = 1; } loadTypeData(filePath, type); } void MainWindow::on_tBNewProject_clicked() { } void MainWindow::on_tBNewImageLayer_clicked() { QString dir = gSettings->value("ImagePath").toString(); QString filePath = QFileDialog::getOpenFileName(this,QString::fromLocal8Bit("打开本地影像数据"), dir,QString::fromLocal8Bit("本地影像数据(*.tif *.tiff *.img *.jpg *.png);;本地影像数据(*.*)")); if(filePath.isNull()) { return; } gSettings->setValue("ImagePath", filePath); QByteArray path = filePath.toLocal8Bit(); std::shared_ptr<SceneProject3D> proj = std::dynamic_pointer_cast<SceneProject3D>(curProj); if(proj) { proj->AddLocalImage(path.data()); OSG3DGlobalShowWidget *widget = dynamic_cast<OSG3DGlobalShowWidget *>(ui->centralTabWidget->currentWidget()); if(widget) { widget->SetTerrainLayerViewPoint(path.data()); } Project3DForm* dock = dynamic_cast<Project3DForm*>(curLeftDock->widget()); if(dock) { dock->AddImage(path.data()); } } } void MainWindow::on_actionArcGISImage_triggered() { std::shared_ptr<SceneProject3D> proj = std::dynamic_pointer_cast<SceneProject3D>(curProj); if(proj) { proj->AddArcGISImagery(); } } void MainWindow::on_actionArcGISTerrain_triggered() { std::shared_ptr<SceneProject3D> proj = std::dynamic_pointer_cast<SceneProject3D>(curProj); if(proj) { proj->AddArcGISTerrainImagery(); } } void MainWindow::on_actionBingImage_triggered() { std::shared_ptr<SceneProject3D> proj = std::dynamic_pointer_cast<SceneProject3D>(curProj); if(proj) { proj->AddBingImagery(); } } void MainWindow::on_actionBingTerrain_triggered() { std::shared_ptr<SceneProject3D> proj = std::dynamic_pointer_cast<SceneProject3D>(curProj); if(proj) { proj->AddBingTerrain(); } } void MainWindow::on_tBNewTerrainLayer_clicked() { QString dir = gSettings->value("TerrainPath").toString(); QString filePath = QFileDialog::getOpenFileName(this,QString::fromLocal8Bit("打开本地地形数据"), dir,QString::fromLocal8Bit("本地地形数据(*.tif *.img);;本地影像数据(*.*)")); if(filePath.isNull()) { return; } gSettings->setValue("TerrainPath", filePath); QByteArray path = filePath.toLocal8Bit(); std::shared_ptr<SceneProject3D> proj = std::dynamic_pointer_cast<SceneProject3D>(curProj); if(proj) { proj->AddLocalTerrain(path.data()); OSG3DGlobalShowWidget *widget = dynamic_cast<OSG3DGlobalShowWidget *>(ui->centralTabWidget->currentWidget()); if(widget) { widget->SetTerrainLayerViewPoint(path.data()); } Project3DForm* dock = dynamic_cast<Project3DForm*>(curLeftDock->widget()); if(dock) { dock->AddTerrain(path.data()); } } } void MainWindow::on_tBSaveProject_clicked() { QString dir = gSettings->value("SaveFilePath").toString(); QString fileName = QFileDialog::getSaveFileName(this,QString::fromLocal8Bit("保存场景工程文件"),dir, QString::fromLocal8Bit("场景工程文件(*.sj)")); if (fileName.isNull()) { return; } gSettings->setValue("SaveFilePath", fileName); QByteArray path = fileName.toLocal8Bit(); std::shared_ptr<SceneProject3D> proj = std::dynamic_pointer_cast<SceneProject3D>(curProj); if(proj) { proj->write(path.data()); } } void MainWindow::loadProject(std::shared_ptr<SceneProject3D> _3dProject) { string name = PathRef::DirOrPathGetName(_3dProject->getFileName()); OSG3DGlobalShowWidget *tabWidget = new OSG3DGlobalShowWidget(ui->centralTabWidget); if(ui->centralTabWidget->count()==0) { tabWidget->setMinimumSize(QSize(100, 100)); } ui->centralTabWidget->addTab(tabWidget, QString::fromLocal8Bit(name.c_str())); ui->centralTabWidget->setCurrentIndex(ui->centralTabWidget->indexOf(tabWidget)); tabWidget->load3DProject(_3dProject); QDockWidgetEx *projectDock = new QDockWidgetEx(QString::fromLocal8Bit(name.c_str()), this); projectDock->setFeatures(QDockWidget::AllDockWidgetFeatures); Project3DForm *project3DForm = new Project3DForm(projectDock); project3DForm->LoadProject3d(_3dProject); projectDock->setWidget(project3DForm); addDockWidget(Qt::LeftDockWidgetArea, projectDock); if(leftDockMap.size()!=0) { tabifyDockWidget(curLeftDock, projectDock); } connect(project3DForm, &Project3DForm::signalViewPoint, tabWidget, &OSG3DGlobalShowWidget::slotViewPoint); connect(projectDock, &QDockWidgetEx::signalClose, this, &MainWindow::slotCloseDock); curProj = std::dynamic_pointer_cast<SceneProjectBase>(_3dProject); curLeftDock = projectDock; projectMap[_3dProject->getFileName()] = curProj; leftDockMap[_3dProject->getFileName()] = curLeftDock; } void MainWindow::loadObject(std::string filePath) { string name = PathRef::DirOrPathGetName(filePath); OSG3DObjectShowWidget *tabWidget = new OSG3DObjectShowWidget(ui->centralTabWidget); if(ui->centralTabWidget->count()==0) { tabWidget->setMinimumSize(QSize(100, 100)); } ui->centralTabWidget->addTab(tabWidget, QString::fromLocal8Bit(name.c_str())); ui->centralTabWidget->setCurrentIndex(ui->centralTabWidget->indexOf(tabWidget)); tabWidget->load3DObject(filePath); /* string name = PathRef::DirOrPathGetName(_3dProject->getFileName()); OSG3DGlobalShowWidget *tabWidget = new OSG3DGlobalShowWidget(ui->centralTabWidget); if(ui->centralTabWidget->count()==0) { tabWidget->setMinimumSize(QSize(100, 100)); } ui->centralTabWidget->addTab(tabWidget, QString::fromLocal8Bit(name.c_str())); ui->centralTabWidget->setCurrentIndex(ui->centralTabWidget->indexOf(tabWidget)); tabWidget->load3DProject(_3dProject); QDockWidgetEx *projectDock = new QDockWidgetEx(QString::fromLocal8Bit(name.c_str()), this); projectDock->setFeatures(QDockWidget::AllDockWidgetFeatures); Project3DForm *project3DForm = new Project3DForm(projectDock); project3DForm->LoadProject3d(_3dProject); projectDock->setWidget(project3DForm); addDockWidget(Qt::LeftDockWidgetArea, projectDock); if(leftDockMap.size()!=0) { tabifyDockWidget(curLeftDock, projectDock); } connect(project3DForm, &Project3DForm::signalViewPoint, tabWidget, &OSG3DGlobalShowWidget::slotViewPoint); connect(projectDock, &QDockWidgetEx::signalClose, this, &MainWindow::slotCloseDock); curProj = std::dynamic_pointer_cast<SceneProjectBase>(_3dProject); curLeftDock = projectDock; projectMap[_3dProject->getFileName()] = curProj; leftDockMap[_3dProject->getFileName()] = curLeftDock;*/ } void MainWindow::on_tBOpenProject_clicked() { QStringList filterList = {QString::fromLocal8Bit("场景工程文件(*.sj)"), QString::fromLocal8Bit("三维模型数据(*.osg *osgb *.obj)"), QString::fromLocal8Bit("其他数据(*.*)")}; QString filter = filterList.join(QString::fromLocal8Bit(";;")); QString dir = gSettings->value("OpenFilePath").toString(); QString selectedFilter; QString filePath = QFileDialog::getOpenFileName(this,QString::fromLocal8Bit("打开场景工程文件"),dir,filter,&selectedFilter); if(filePath.isNull()) { return; } gSettings->setValue("OpenFilePath", filePath); int type = -1; for(int i = 0; i < filterList.length(); i++) { if(filterList[i] == selectedFilter) { type = i; break; } } QByteArray path = filePath.toLocal8Bit(); loadTypeData(path.data(), type); } void MainWindow::loadTypeData(std::string filePath, int type) { switch (type) { case 0: { std::shared_ptr<SceneProject3D> _3dProject = make_shared<SceneProject3D>(); _3dProject->read(filePath); loadProject(_3dProject); curLeftDock->setVisible(true); //要先设置可见才能显示 curLeftDock->raise(); break; } case 1: { loadObject(filePath); break; } default: break; } } void MainWindow::on_centralTabWidget_currentChanged(int index) { if(!initWindow) { return; } for (int i = 0; i < ui->centralTabWidget->count(); i++) { if( i == index) { OSGShowWidget *widget = dynamic_cast<OSGShowWidget *>(ui->centralTabWidget->widget(i)); if(widget && !widget->isWork()) { widget->onStartTimer(); auto pit = projectMap.find(widget->GetName()); if(pit != projectMap.end()) { curProj = pit->second; } auto dit = leftDockMap.find(widget->GetName()); if(dit != leftDockMap.end()) { if(curLeftDock != dit->second) { curLeftDock = dit->second; curLeftDock->raise(); } } } } else { OSGShowWidget *widget = dynamic_cast<OSGShowWidget *>(ui->centralTabWidget->widget(i)); if(widget && widget->isWork()) { widget->onStopTimer(); } } } } void MainWindow::on_centralTabWidget_tabCloseRequested(int index) { OSGShowWidget *widget = dynamic_cast<OSGShowWidget *>(ui->centralTabWidget->widget(index)); ui->centralTabWidget->removeTab(index); if(widget) { auto pit = projectMap.find(widget->GetName()); if(pit != projectMap.end()) { projectMap.erase(pit); } auto dit = leftDockMap.find(widget->GetName()); if(dit != leftDockMap.end()) { auto dock = dit->second; leftDockMap.erase(dit); removeDockWidget(dock); dock->close(); } if(widget->isWork()) { widget->onStopTimer(); } } } void MainWindow::closeEvent(QCloseEvent *e) { for (int i = ui->centralTabWidget->count()-1; i >= 0; i--) { on_centralTabWidget_tabCloseRequested(i); } } void MainWindow::on_tBNewPhotogrammetry_clicked() { LoadPhotogrammetryDialog loadDialog(this); if(QDialog::Rejected == loadDialog.exec()) { return; } string dir = loadDialog.GetDataDir(); if(dir.empty()) { QMessageBox::critical(this, QString::fromLocal8Bit("提示"), QString::fromLocal8Bit("文件夹不能为空")); return; } std::shared_ptr<SceneProject3D> proj = std::dynamic_pointer_cast<SceneProject3D>(curProj); if(proj) { proj->AddPhotogrammetry(dir); OSG3DGlobalShowWidget *widget = dynamic_cast<OSG3DGlobalShowWidget *>(ui->centralTabWidget->currentWidget()); if(widget) { widget->SetNodeViewPoint(dir.data()); } Project3DForm* dock = dynamic_cast<Project3DForm*>(curLeftDock->widget()); if(dock) { dock->AddTiltingData(dir.data()); } } } int MainWindow::find3DShowWidgetIndex(std::string name) { for(int i = 0; i < ui->centralTabWidget->count(); i++) { OSGShowWidget *widget = dynamic_cast<OSGShowWidget *>(ui->centralTabWidget->widget(i)); if(widget) { if(widget->GetName()==name) { return i; } } } return -1; } void MainWindow::on_MainWindow_tabifiedDockWidgetActivated(QDockWidget *dockWidget) { if(curLeftDock==dockWidget) { return; } Project3DForm* form = dynamic_cast<Project3DForm *>(dockWidget->widget()); if(form) { curLeftDock = dynamic_cast<QDockWidgetEx *>(dockWidget); if(!curLeftDock) { return; } auto pit = projectMap.find(form->GetName()); if(pit != projectMap.end()) { curProj = pit->second; } int index = find3DShowWidgetIndex(form->GetName()); if(index>=0) { ui->centralTabWidget->setCurrentIndex(index); } } } void MainWindow::slotCloseDock(QDockWidgetEx *dockWidget) { Project3DForm* form = dynamic_cast<Project3DForm *>(dockWidget->widget()); if(form) { auto pit = projectMap.find(form->GetName()); if(pit != projectMap.end()) { projectMap.erase(pit); } auto dit = leftDockMap.find(form->GetName()); if(dit != leftDockMap.end()) { leftDockMap.erase(dit); } int index = find3DShowWidgetIndex(form->GetName()); if(index>=0) { OSGShowWidget *widget = dynamic_cast<OSGShowWidget *>(ui->centralTabWidget->widget(index)); if(widget&&widget->isWork()) { widget->onStopTimer(); } ui->centralTabWidget->removeTab(index); } } } void MainWindow::on_tBNewVectorLayer_clicked() { QString dir = gSettings->value("VectorPath").toString(); QString filePath = QFileDialog::getOpenFileName(this,QString::fromLocal8Bit("打开本地矢量数据"), dir,QString::fromLocal8Bit("本地矢量数据(*.shp *.dxf);;本地矢量数据(*.*)")); if(filePath.isNull()) { return; } gSettings->setValue("VectorPath", filePath); QByteArray path = filePath.toLocal8Bit(); std::shared_ptr<SceneProject3D> proj = std::dynamic_pointer_cast<SceneProject3D>(curProj); if(proj) { proj->AddLocalVector(path.data()); OSG3DGlobalShowWidget *widget = dynamic_cast<OSG3DGlobalShowWidget *>(ui->centralTabWidget->currentWidget()); if(widget) { widget->SetNodeViewPoint(path.data()); } Project3DForm* dock = dynamic_cast<Project3DForm*>(curLeftDock->widget()); if(dock) { dock->AddVector(path.data()); } } } void MainWindow::on_tBGoogleImageDownload_clicked() { MapDownloadDialog *mapDownloadDialog = new MapDownloadDialog(this); mapDownloadDialog->exec(); }
16,649
C++
.cpp
502
25.988048
135
0.63837
fafa1899/SinianGIS
30
14
2
GPL-3.0
9/20/2024, 10:45:00 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,539,884
ExceptionDmp.cpp
fafa1899_SinianGIS/SinianGIS/ExceptionDmp.cpp
#include "ExceptionDmp.h" #include <C:\Program Files (x86)\Windows Kits\10\Include\10.0.17763.0\ucrt\tchar.h> #include <Windows.h> #include <DbgHelp.h> #include <QMessageBox> #pragma comment( lib, "Dbghelp.lib" ) static void GetAppDir(TCHAR * dmp_path, size_t num) { TCHAR AppPath[MAX_PATH]; ::GetModuleFileName(nullptr, AppPath, _countof(AppPath)); //_tprintf(_T("%s\n"), AppPath); TCHAR drive[_MAX_DRIVE] = { 0 }; TCHAR dir[_MAX_DIR] = { 0 }; TCHAR fname[_MAX_FNAME] = { 0 }; TCHAR ext[_MAX_EXT] = { 0 }; _tsplitpath_s(AppPath, drive, dir, fname, ext); //_tprintf(_T("drive: %s\n"), drive); //_tprintf(_T("dir: %s\n"), dir); //_tprintf(_T("fname: %s\n"), fname); //_tprintf(_T("ext: %s\n"), ext); _stprintf_s(dmp_path, num, _T("%s%s"), drive, dir); } static LONG WINAPI lpTopLevelExceptionFilter(PEXCEPTION_POINTERS pExInfo) { TCHAR dmp_path[MAX_PATH]; //::GetTempPath(_countof(dmp_path), dmp_path); GetAppDir(dmp_path, MAX_PATH); //_tprintf(_T("%s\n"), dmp_path); SYSTEMTIME tm; GetLocalTime(&tm);//获取时间 TCHAR file_name[128]; _stprintf_s(file_name, L"%spbim%d-%02d-%02d-%02d-%02d-%02d.dmp", dmp_path, tm.wYear, tm.wMonth, tm.wDay, tm.wHour, tm.wMinute, tm.wSecond);//设置dmp文件名称 HANDLE hFile = CreateFile(file_name, GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr); if (hFile != INVALID_HANDLE_VALUE) { MINIDUMP_EXCEPTION_INFORMATION info;//构造dmp异常数据结构 info.ThreadId = GetCurrentThreadId(); info.ClientPointers = FALSE; info.ExceptionPointers = pExInfo; MiniDumpWriteDump(GetCurrentProcess(), GetCurrentProcessId(), hFile, (MINIDUMP_TYPE)MiniDumpNormal, &info, nullptr, nullptr);//写dmp文件 CloseHandle(hFile); const TCHAR *fmt = { L"遇到问题需要关闭,您的数据有可能丢失。\n\n" L"我们对此引起的不便表示抱歉;请将\n\n" L"\"%s\"\n\n" L"发送给我们以便快速查找问题之所在,谢谢。\n\n" L"邮箱:holybell44@126.com\n\n" L"github主页:https://github.com/fafa1899" }; TCHAR msg[400]; _stprintf(msg, fmt, file_name); //MessageBox(NULL, msg, L"程序异常报告", MB_ICONERROR | MB_SYSTEMMODAL); QMessageBox::critical(nullptr, QString::fromLocal8Bit("程序异常报告"), QString::fromWCharArray(msg)); } else { TCHAR info[300] = { L"fail to create dump file:" }; _tcscat_s(info, file_name); //MessageBox(NULL, info, L"dump", MB_ICONERROR | MB_SYSTEMMODAL); QMessageBox::critical(nullptr, QString::fromLocal8Bit("程序异常报告"), QString::fromWCharArray(info)); } return EXCEPTION_EXECUTE_HANDLER; } ExceptionDmp::ExceptionDmp() { SetUnhandledExceptionFilter(lpTopLevelExceptionFilter); } static ExceptionDmp s_ExceptionDmp; ExceptionDmp::~ExceptionDmp() { }
2,804
C++
.cpp
75
32.066667
104
0.677629
fafa1899/SinianGIS
30
14
2
GPL-3.0
9/20/2024, 10:45:00 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,539,885
GoogleMapTiles.cpp
fafa1899_SinianGIS/SinianGIS/GoogleMapTiles.cpp
#include "GoogleMapTiles.h" #include <iostream> #include <string> #include <algorithm> #include <fstream> #include <ogr_spatialref.h> using namespace std; GoogleMapTiles::GoogleMapTiles() { const double radius = 6378137; const double PI = 3.14159265358979323846; double halfSide = radius * PI; geoStartX = -halfSide; geoStartY = -halfSide; geoEndX = halfSide; geoEndY = halfSide; tilePixelSizeX = 256; tilePixelSizeY = 256; levelNum = 22; for (int i = 0; i < levelNum; i++) { OneLevel oneLevel; oneLevel.tilesNumX = (int)pow(2, i); oneLevel.tilesNumY = (int)pow(2, i); oneLevel.pixelSizeX = oneLevel.tilesNumX * tilePixelSizeX; oneLevel.pixelSizeY = oneLevel.tilesNumY * tilePixelSizeY; oneLevel.dX = (geoEndX - geoStartX) / oneLevel.pixelSizeX; oneLevel.dY = (geoEndY - geoStartY) / oneLevel.pixelSizeY; levelList.push_back(oneLevel); } } GoogleMapTiles::~GoogleMapTiles() { } bool GoogleMapTiles::GetTiles(double left, double top, double right, double bottom, int li, vector<OneTile> &tiles) { static int id = 0; if (id > 3) { id = 0; } uri = "http://khms" + to_string(id) + ".google.com/kh/v=865?x=%zu&y=%zu&z=%d"; id++; double xArray[4] = { left, left, right, right }; double yArray[4] = { top, bottom, bottom, top }; OGRSpatialReference webMercator; webMercator.importFromEPSG(3857); OGRSpatialReference wgs84; wgs84.importFromEPSG(4326); OGRCoordinateTransformation* LonLat2XY = OGRCreateCoordinateTransformation(&wgs84, &webMercator); if (!LonLat2XY) { printf("GDAL Error!"); return false; } if (!LonLat2XY->Transform(4, xArray, yArray)) { printf("GDAL Error!"); return false; } OGRCoordinateTransformation::DestroyCT(LonLat2XY); LonLat2XY = nullptr; double minX = geoEndX + 10000; double minY = geoEndY + 10000; double maxX = geoStartX - 10000; double maxY = geoStartY - 10000; for (int i = 0; i < 4; i++) { minX = (std::min)(minX, xArray[i]); minY = (std::min)(minY, yArray[i]); maxX = (std::max)(maxX, xArray[i]); maxY = (std::max)(maxY, yArray[i]); } double pixelStartX = (minX - geoStartX) / levelList[li].dX; double pixelStartY = (minY - geoStartY) / levelList[li].dY; double pixelEndX = (maxX - geoStartX) / levelList[li].dX; double pixelEndY = (maxY - geoStartY) / levelList[li].dY; size_t sx = (int)(pixelStartX / tilePixelSizeX); size_t sy = (int)(pixelStartY / tilePixelSizeY); size_t ex = (int)(pixelEndX / tilePixelSizeX); size_t ey = (int)(pixelEndY / tilePixelSizeY); sy = levelList[li].tilesNumY - 1 - sy; ey = levelList[li].tilesNumY - 1 - ey; std::swap(sy, ey); for (size_t yi = sy; yi <= ey; yi++) { for (size_t xi = sx; xi <= ex; xi++) { char address[512] = ""; sprintf_s(address, 512, uri.c_str(), xi, yi, li); OneTile tile; tile.uri = address; tile.x = xi; tile.y = yi; tile.z = li; tiles.push_back(tile); } } return true; } bool GoogleMapTiles::WriteGeoInfo(string imgName, OneTile& tile) { // string spRefFile = imgName + ".prj"; ofstream outfile(spRefFile); if (!outfile) { printf("Can't Open %s\n", spRefFile.c_str()); return false; } OGRSpatialReference webMercator; webMercator.importFromEPSG(3857); char *pszWKT = nullptr; if (OGRERR_NONE != webMercator.exportToWkt(&pszWKT)) { printf("Get Spatial Reference Error!\n"); return false; } outfile << pszWKT; CPLFree(pszWKT); pszWKT = nullptr; outfile.close(); // int tile_x = tile.x; int tile_y = levelList[tile.z].tilesNumY - 1 - tile.y; int pixel_x = tile_x * tilePixelSizeX; int pixel_y = tile_y * tilePixelSizeY; double dx = levelList[tile.z].dX; double dy = -levelList[tile.z].dY; double tileStartX = geoStartX + pixel_x * levelList[tile.z].dX + 0.5 * levelList[tile.z].dX; double tileStartY = geoStartY + pixel_y * levelList[tile.z].dY + (tilePixelSizeY - 0.5)* levelList[tile.z].dY; string tfwFile = imgName + ".jgw"; FILE *pFile = nullptr; if (fopen_s(&pFile, tfwFile.c_str(), "wt") != 0) { printf("Can't Create JGW:%s", tfwFile.c_str()); return false; } fprintf(pFile, "%.10lf\n", dx); fprintf(pFile, "%.10lf\n", 0.0); fprintf(pFile, "%.10lf\n", 0.0); fprintf(pFile, "%.10lf\n", dy); fprintf(pFile, "%.10lf\n", tileStartX); fprintf(pFile, "%.10lf\n", tileStartY); fclose(pFile); return true; }
4,318
C++
.cpp
147
26.795918
115
0.692775
fafa1899/SinianGIS
30
14
2
GPL-3.0
9/20/2024, 10:45:00 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,539,886
osg3dobjectshowwidget.cpp
fafa1899_SinianGIS/SinianGIS/osg3dobjectshowwidget.cpp
#include "osg3dobjectshowwidget.h" #include <osgGA/TrackballManipulator> osg::ref_ptr<osgGA::TrackballManipulator> mainManipulator; OSG3DObjectShowWidget::OSG3DObjectShowWidget(QWidget *parent) : OSGShowWidget(parent) { root= new osg::Group(); //root->getOrCreateStateSet()->setMode(GL_LIGHTING, osg::StateAttribute::OFF | osg::StateAttribute::OVERRIDE); mainManipulator = new osgGA::TrackballManipulator; view->setCameraManipulator(mainManipulator); view->getCamera()->setClearColor(osg::Vec4(0.678431f, 0.847058f, 0.901961f, 1.0f)); } OSG3DObjectShowWidget::~OSG3DObjectShowWidget() { } void OSG3DObjectShowWidget::load3DObject(std::string filePath) { osg::Node * node = osgDB::readNodeFile(filePath); root->addChild(node); view->setSceneData(root); }
794
C++
.cpp
20
36.7
114
0.775457
fafa1899/SinianGIS
30
14
2
GPL-3.0
9/20/2024, 10:45:00 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,539,887
loadphotogrammetrydialog.cpp
fafa1899_SinianGIS/SinianGIS/loadphotogrammetrydialog.cpp
#include "loadphotogrammetrydialog.h" #include "ui_loadphotogrammetrydialog.h" #include "Settings.h" #include <QMovie> #include <QFileDialog> #include <QMessageBox> #include <QDebug> LoadPhotogrammetryDialog::LoadPhotogrammetryDialog(QWidget *parent) : QDialog(parent), ui(new Ui::LoadPhotogrammetryDialog) { ui->setupUi(this); QMovie * move = new QMovie(this); move->setFileName(":/Res/photogrammetry_data.gif"); ui->labelGIF->setMovie(move); //ui->label_gif->setFixedSize(200,200); //ui->label_gif->setScaledContents(true); move->start(); } LoadPhotogrammetryDialog::~LoadPhotogrammetryDialog() { delete ui; } void LoadPhotogrammetryDialog::on_pushButtonOK_clicked() { QString dirPath = ui->lEDir->text(); if(dirPath.isEmpty() || dirPath.isNull()) { QMessageBox::critical(this, QString::fromLocal8Bit("提示"), QString::fromLocal8Bit("文件夹不能为空")); return; } QByteArray path = dirPath.toLocal8Bit(); dataDir = path.data(); QDialog::accept(); } void LoadPhotogrammetryDialog::on_pushButtonCancel_clicked() { QDialog::reject(); } void LoadPhotogrammetryDialog::on_pBDir_clicked() { QString dir = gSettings->value("ObliquePath").toString(); QString dirPath = QFileDialog::getExistingDirectory(this,QString::fromLocal8Bit("选择倾斜摄影数据文件夹:"), dir); if(dirPath.isNull()) { return; } gSettings->setValue("ObliquePath", dirPath); ui->lEDir->setText(dirPath); }
1,499
C++
.cpp
50
25.94
106
0.720226
fafa1899/SinianGIS
30
14
2
GPL-3.0
9/20/2024, 10:45:00 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,539,888
qdockwidgetex.cpp
fafa1899_SinianGIS/SinianGIS/qdockwidgetex.cpp
#include "qdockwidgetex.h" #include <QDebug> void QDockWidgetEx::closeEvent(QCloseEvent *event) { signalClose(this); }
125
C++
.cpp
6
18.833333
50
0.786325
fafa1899/SinianGIS
30
14
2
GPL-3.0
9/20/2024, 10:45:00 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,539,889
regedit.cpp
fafa1899_SinianGIS/SinianGIS/regedit.cpp
#include "regedit.h" #include <QSettings> void registerFileRelation(const QString& className,const QString& appPath,const QString& ext,const QString& extDes) { QString baseUrl("HKEY_CURRENT_USER\\Software\\Classes"); // 要添加的顶层目录 QSettings settingClasses(baseUrl,QSettings::NativeFormat); // 在...Classes\类别下创建一个新的类别,并设置该类别打开文件时的调用参数 settingClasses.setValue("/" + className + "/Shell/Open/Command/.","\"" + appPath + "\" \"%1\""); // 文件类型描述 settingClasses.setValue("/" + className + "/.",extDes); // 设置该类别的默认图标默认图标 settingClasses.setValue("/" + className + "/DefaultIcon/.",appPath + ",0"); // 关联ext 和 类别 settingClasses.setValue("/" + ext + "/OpenWithProgIds/" + className,""); // 立即保存该修改 settingClasses.sync(); }
839
C++
.cpp
17
41.058824
115
0.683646
fafa1899/SinianGIS
30
14
2
GPL-3.0
9/20/2024, 10:45:00 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,539,890
sceneproject3d.cpp
fafa1899_SinianGIS/SinianGIS/sceneproject3d.cpp
#include "sceneproject3d.h" #include "pathref.hpp" #include "tinyxml/tinyxml.h" #include "StdStringEx.hpp" #include <QDebug> #include <QMessageBox> #include <string> #include <direct.h> #include <osg/Program> #include <osgDB/WriteFile> #include <osgEarth/ImageLayer> #include <osgEarth/ModelLayer> #include <osgEarth/SpatialReference> #include <osgEarth/GeoTransform> #include <osgEarthDrivers/gdal/GDALOptions> #include <osgEarthDrivers/cache_filesystem/FileSystemCache> #include <osgEarthDrivers/bing/BingOptions> #include <osgEarthDrivers/arcgis/ArcGISOptions> #include <osgEarthDrivers/sky_simple/SimpleSkyOptions> #include <osgEarthDrivers/feature_ogr/OGRFeatureOptions> //#include <osgEarthDrivers/model_feature_geom/FeatureGeomModelOptions> //#include <osgEarthDrivers/tms/TMSOptions> //#include <osgEarthDrivers/tilecache/TileCacheOptions> #include <osgEarthFeatures/FeatureSourceLayer> #include <osgEarthFeatures/FeatureModelLayer> #include <osgEarthUtil/EarthManipulator> //#include <osgEarthUtil/AutoClipPlaneHandler> #include <osgEarthUtil/ExampleResources> //#include <osgEarthUtil/RTTPicker> //#include <osgEarthUtil/Shadowing> using namespace std; SceneProject3D::SceneProject3D() { root = new osg::Group(); InitEarthMapNode(); AddSkyBox(); InitViewPoint(); } void SceneProject3D::create() { } void SceneProject3D::read(std::string path) { this->projectFilePath = path; SceneProjectBase::read(path); if (projectJSON.contains("LocalImage")) { QJsonValue key_value = projectJSON.take("LocalImage"); if (key_value.isArray()) { QJsonArray array = key_value.toArray(); for (int i = 0; i < array.size(); i++) { QJsonValue value = array.at(i); if (value.isString()) { QByteArray v = value.toString().toLocal8Bit(); AddLocalImage(v.data()); } } } } if (projectJSON.contains("LocalTerrain")) { QJsonValue key_value = projectJSON.take("LocalTerrain"); if (key_value.isArray()) { QJsonArray array = key_value.toArray(); for (int i = 0; i < array.size(); i++) { QJsonValue value = array.at(i); if (value.isString()) { QByteArray v = value.toString().toLocal8Bit(); AddLocalTerrain(v.data()); } } } } if(projectJSON.contains("ObliquePhotography")) { QJsonValue key_value = projectJSON.take("ObliquePhotography"); if (key_value.isArray()) { QJsonArray array = key_value.toArray(); for (int i = 0; i < array.size(); i++) { QJsonValue value = array.at(i); if (value.isString()) { QByteArray v = value.toString().toLocal8Bit(); AddPhotogrammetry(v.data()); } } } } if(projectJSON.contains("LocalVector")) { QJsonValue key_value = projectJSON.take("LocalVector"); if (key_value.isArray()) { QJsonArray array = key_value.toArray(); for (int i = 0; i < array.size(); i++) { QJsonValue value = array.at(i); if (value.isString()) { QByteArray v = value.toString().toLocal8Bit(); AddLocalVector(v.data()); } } } } if(projectJSON.contains("ViewPoints")) { ReadViewPoint(); } } void SceneProject3D::ReadViewPoint() { QJsonValue viewPointJSON = projectJSON.take("ViewPoints"); if(viewPointJSON.isArray()) { QJsonArray array = viewPointJSON.toArray(); for (int i = 0; i < array.size(); i++) { QJsonValue value = array.at(i); if (value.isObject()) { QJsonObject object = value.toObject(); QJsonValue name = object.value(QString::fromLocal8Bit("name")); if(!name.isString()) { continue; } std::shared_ptr<osgEarth::Viewpoint> oe_VP = std::make_shared<osgEarth::Viewpoint>(); QJsonValue vp = object.value("vp"); if(vp.isObject()) { QJsonObject k_v = vp.toObject(); QJsonValue focalPointX = k_v.value(QString::fromLocal8Bit("focalPointX")); QJsonValue focalPointY = k_v.value(QString::fromLocal8Bit("focalPointY")); QJsonValue focalPointZ = k_v.value(QString::fromLocal8Bit("focalPointZ")); QJsonValue heading = k_v.value(QString::fromLocal8Bit("heading")); QJsonValue pitch = k_v.value(QString::fromLocal8Bit("pitch")); QJsonValue range = k_v.value(QString::fromLocal8Bit("range")); osgEarth::GeoPoint focalPoint(map->getSRS(), focalPointX.toDouble(), focalPointY.toDouble(), focalPointZ.toDouble()); oe_VP->focalPoint() = focalPoint; oe_VP->heading() = heading.toDouble(); oe_VP->pitch() = pitch.toDouble(); oe_VP->range() = range.toDouble(); } QByteArray N = name.toString().toLocal8Bit(); viewPointMap.insert(make_pair(N.data(),oe_VP)); } } } } void SceneProject3D::write(std::string path) { this->projectFilePath = path; projectJSON.insert("LocalImage", localImageArray); projectJSON.insert("LocalTerrain", localTerrainArray); projectJSON.insert("ObliquePhotography", obliquePhotographyArray); projectJSON.insert("LocalVector", localVectorArray); SaveViewPoint(); SceneProjectBase::write(path); } void SceneProject3D::SaveViewPoint() { QJsonArray viewPointJSON; for(auto &it : viewPointMap) { QJsonObject vp; QJsonValue nameValue(QString::fromLocal8Bit(it.first.c_str())); vp.insert("name", nameValue); QJsonObject key_value; key_value.insert("focalPointX", it.second->focalPoint()->x()); key_value.insert("focalPointY", it.second->focalPoint()->y()); key_value.insert("focalPointZ", it.second->focalPoint()->z()); key_value.insert("heading", it.second->heading()->getValue()); key_value.insert("pitch", it.second->pitch()->getValue()); key_value.insert("range", it.second->range()->getValue()); vp.insert("vp", key_value); viewPointJSON.push_back(vp); } projectJSON.insert("ViewPoints", viewPointJSON); } void SceneProject3D::InitEarthMapNode() { osgEarth::ProfileOptions profileOpts; //profileOpts.srsString() = wktString;//"EPSG:4547"; //osgEarth::Bounds bs(535139, 3365107, 545139, 3375107); //osgEarth::Bounds bs(minX, minY, maxX, maxY); //profileOpts.bounds() = bs; //地图配置:设置缓存目录 osgEarth::Drivers::FileSystemCacheOptions cacheOpts; string cacheDir = appDir + "/tmp"; cacheOpts.rootPath() = cacheDir; osgEarth::MapOptions mapOpts; mapOpts.cache() = cacheOpts; //mapOpts.coordSysType() = MapOptions::CSTYPE_PROJECTED; mapOpts.profile() = profileOpts; //创建地图节点 map = new osgEarth::Map(mapOpts); mapNode = new osgEarth::MapNode(map); //root->addChild(mapNode); osgEarth::Drivers::GDALOptions gdal; //gdal.url() = appDir + "/Resource/BlueMarbleNASA.jpg"; //gdal.url() = appDir + "/Resource/World_e-Atlas_Bright-BMNG-200404.tiff"; gdal.url() = appDir + "/Resource/baseMap.jpg"; osg::ref_ptr<osgEarth::ImageLayer> layer = new osgEarth::ImageLayer("BlueMarble", gdal); map->addLayer(layer); } void SceneProject3D::AddSkyBox() { // osgEarth::SimpleSky::SimpleSkyOptions options; options.atmosphereVisible() = true; options.atmosphericLighting() = false; options.sunVisible() = true; options.moonVisible() = true; options.starsVisible() = true; string moonImage = PathRef::GetAppDir() + "/Resource/moon_1024x512.jpg"; options.moonImageURI() = moonImage; //options.ambient() = 0.25f; // osg::ref_ptr<osgEarth::SimpleSky::SkyNode> skyNode = osgEarth::SimpleSky::SkyNode::create(options, mapNode); root->addChild(skyNode); skyNode->addChild(mapNode); osgEarth::DateTime d = skyNode->getDateTime(); skyNode->setDateTime(osgEarth::DateTime(d.year(), d.month(), d.day(), 4.0)); // 格林尼治,时差8小时 } //设置初始视点 void SceneProject3D::InitViewPoint() { double cx = 0; double cy = 0; map->getProfile()->getExtent().getCentroid(cx, cy); if (cx<abs(1e-6) && cy<abs(1e-6)) //中心位置为0说明可能是全地图显示 { cx = 112.637113; cy = 26.939324; } osgEarth::GeoPoint newPoint(map->getSRS(), cx, cy, 0); homeViewPoint.focalPoint() = newPoint; homeViewPoint.heading() = 0; homeViewPoint.pitch() = -90; homeViewPoint.range() = 20000000; } void SceneProject3D::AddLocalImage(string filePath) { osgEarth::Drivers::GDALOptions gdal; gdal.url() = filePath; osg::ref_ptr<osgEarth::ImageLayer> layer = new osgEarth::ImageLayer(filePath, gdal); map->addLayer(layer); QJsonValue value(QString::fromLocal8Bit(filePath.c_str())); localImageArray.push_back(value); } void SceneProject3D::AddLocalTerrain(std::string filePath) { osgEarth::Drivers::GDALOptions gdal; gdal.url() = filePath; osg::ref_ptr<osgEarth::ElevationLayer> layer = new osgEarth::ElevationLayer(filePath, gdal); map->addLayer(layer); QJsonValue value(QString::fromLocal8Bit(filePath.c_str())); localTerrainArray.push_back(value); } //加入矢量数据 bool SceneProject3D::AddLocalVector(std::string filePath) { // osgEarth::Drivers::OGRFeatureOptions featureData; featureData.url() = filePath; // ifstream infile("C:/Data/vector/hs/23.prj"); // string line; // getline(infile, line); // featureData.profile()->srsString() = line; // Make a feature source layer and add it to the Map: osgEarth::Features::FeatureSourceLayerOptions ogrLayer; ogrLayer.name() = filePath + "_source"; ogrLayer.featureSource() = featureData; osgEarth::Features::FeatureSourceLayer* featureSourceLayer = new osgEarth::Features::FeatureSourceLayer(ogrLayer); map->addLayer(featureSourceLayer); osgEarth::Features::FeatureSource *features = featureSourceLayer->getFeatureSource(); if (!features) { QMessageBox::critical(nullptr, QString::fromLocal8Bit("警告"), QString::fromLocal8Bit("无法打开该矢量文件!"), QMessageBox::Ok); return false; } osgEarth::Symbology::Geometry::Type type = features->getGeometryType(); if (osgEarth::Symbology::Geometry::TYPE_UNKNOWN == type) { QMessageBox::critical(nullptr, QString::fromLocal8Bit("警告"), QString::fromLocal8Bit("该矢量文件的类型未知,或者含有多种类型的特征。"), QMessageBox::Ok); return false; } osgEarth::Symbology::Style style; //高度设置 osgEarth::Symbology::AltitudeSymbol* alt = style.getOrCreate<osgEarth::Symbology::AltitudeSymbol>(); int altMode = 1; switch (altMode) { case 2: alt->clamping() = alt->CLAMP_RELATIVE_TO_TERRAIN; break; case 3: alt->clamping() = alt->CLAMP_ABSOLUTE; break; case 1: default: alt->clamping() = alt->CLAMP_TO_TERRAIN; alt->technique() = alt->TECHNIQUE_DRAPE; break; } if(osgEarth::Symbology::Geometry::TYPE_POINTSET == type) { osgEarth::Symbology::PointSymbol *ps = style.getOrCreateSymbol<osgEarth::Symbology::PointSymbol>(); ps->size() = 5; ps->fill()->color() = osgEarth::Symbology::Color("#EE6363"); ps->smooth() = true; } else if(osgEarth::Symbology::Geometry::TYPE_LINESTRING == type || osgEarth::Symbology::Geometry::TYPE_RING == type) { osgEarth::Symbology::LineSymbol* ls = style.getOrCreateSymbol<osgEarth::Symbology::LineSymbol>(); ls->stroke()->color() = osgEarth::Symbology::Color("#436EEE"); ls->stroke()->width() = 1.0; ls->tessellationSize()->set(100, osgEarth::Units::KILOMETERS); } else if(osgEarth::Symbology::Geometry::TYPE_POLYGON == type) { osgEarth::Symbology::LineSymbol* ls = style.getOrCreateSymbol<osgEarth::Symbology::LineSymbol>(); ls->stroke()->color() = osgEarth::Symbology::Color("#9370DB"); ls->stroke()->width() = 1.0; ls->tessellationSize()->set(100, osgEarth::Units::KILOMETERS); osgEarth::Symbology::PolygonSymbol *polygonSymbol = style.getOrCreateSymbol<osgEarth::Symbology::PolygonSymbol>(); polygonSymbol->fill()->color() = osgEarth::Symbology::Color(152.0f/255, 251.0f/255, 152.0f/255, 0.5f); //238 230 133 polygonSymbol->outline() = true; } //可见性 osgEarth::Symbology::RenderSymbol* rs = style.getOrCreate<osgEarth::Symbology::RenderSymbol>(); rs->depthTest() = false; // osgEarth::Features::FeatureModelLayerOptions fmlOpt; fmlOpt.name() = filePath; fmlOpt.featureSourceLayer() = filePath + "_source"; fmlOpt.enableLighting() = false; fmlOpt.styles() = new osgEarth::Symbology::StyleSheet(); fmlOpt.styles()->addStyle(style); osg::ref_ptr<osgEarth::Features::FeatureModelLayer> fml = new osgEarth::Features::FeatureModelLayer(fmlOpt); map->addLayer(fml); /* if (!config.fieldName.empty()) { Style labelStyle; TextSymbol* text = labelStyle.getOrCreateSymbol<TextSymbol>(); //string name = QString::fromLocal8Bit("[座落地址]").toUtf8().data(); //string name = "[宗地代码]"; //string name = "[Name]"; string name = string("[") + QString::fromLocal8Bit(config.fieldName.c_str()).toUtf8().data() + "]"; text->content() = StringExpression(name); //text->priority() = NumericExpression( "[pop_cntry]" ); text->size() = 16.0f; text->alignment() = TextSymbol::ALIGN_CENTER_CENTER; text->fill()->color() = Color::White; text->halo()->color() = Color::Red; text->encoding() = TextSymbol::ENCODING_UTF8; string fontFile = PathRef::GetAppDir() + "/fonts/SourceHanSansCN-Regular.ttf"; text->font() = fontFile; // and configure a model layer: FeatureModelLayerOptions fmlOpt; fmlOpt.name() = config.name + "_labels"; fmlOpt.featureSourceLayer() = config.name + "_source"; fmlOpt.styles() = new StyleSheet(); fmlOpt.styles()->addStyle(labelStyle); ref_ptr<FeatureModelLayer> fml = new FeatureModelLayer(fmlOpt); //fml->setFeatureSource(features); earthMap->addLayer(fml); }*/ /* Style newStyle; newStyle = *style; newStyle.setName("test"); //styleSheet->addStyle(newStyle); LineSymbol* ls = newStyle.getOrCreateSymbol<LineSymbol>(); ls->stroke()->color() = Color::Yellow; ls->stroke()->width() = 1.0f; ls->tessellationSize()->set(100, Units::KILOMETERS); StyleSelector styleSelector; styleSelector.styleName() = "test"; styleSelector.query()->expression() = "fid < 50"; //styleSheet->selectors().push_back(styleSelector); //fmlOpt.styles()->addStyle(newStyle); //fmlOpt.styles()->selectors().push_back(styleSelector); */ QJsonValue value(QString::fromLocal8Bit(filePath.c_str())); localVectorArray.push_back(value); return true; } //读取3d场景的元数据 bool SceneProject3D::readObliqueXML(std::string metaXML, double& x, double& y, double &z) { string strSRS; string strSRSOrigin; //打开XML工程文档 TiXmlDocument myDocument(metaXML); if (!myDocument.LoadFile()) { QString str = QString::fromLocal8Bit("不能打开XML文件:%1\n").arg(metaXML.c_str()); QMessageBox::critical(nullptr, QString::fromLocal8Bit("警告"), str); return false; } //根节点 TiXmlElement *RootElement = myDocument.RootElement(); TiXmlElement *ChildElement = RootElement->FirstChildElement(); while(ChildElement) { if (_stricmp(ChildElement->Value(), "SRS") == 0) { strSRS = ChildElement->GetText(); } if(_stricmp(ChildElement->Value(), "SRSOrigin") == 0) { strSRSOrigin = ChildElement->GetText(); } ChildElement = ChildElement->NextSiblingElement(); } if(strSRS.length()<4) { QMessageBox::critical(nullptr, QString::fromLocal8Bit("警告"), QString::fromLocal8Bit("坐标参考不正确!"), QMessageBox::Ok); return false; } const osgEarth::SpatialReference* srs = osgEarth::SpatialReference::get(strSRS); if(srs) //如果是正确的坐标系 { vector<string> subline; StdStringEx::CutString(strSRSOrigin, subline, ','); if(subline.size() != 3) { QMessageBox::critical(NULL, QString::fromLocal8Bit("警告"), QString::fromLocal8Bit("strSRSOrigin格式不正确!"), QMessageBox::Ok); return false; } x = atof(subline[0].c_str()); y = atof(subline[1].c_str()); z = atof(subline[2].c_str()); //判断是否相等 if(!map->getSRS()->isEquivalentTo(srs)) { osgEarth::GeoPoint point(srs, x, y, z); osgEarth::GeoPoint newPoint; if(!point.transform(map->getSRS(), newPoint)) { QMessageBox::critical(nullptr, QString::fromLocal8Bit("警告"), QString::fromLocal8Bit("不支持的空间参考转换!"), QMessageBox::Ok); return false; } x = newPoint.x(); y = newPoint.y(); z = newPoint.z(); } } else { string tmp = strSRS.substr(0, 4); if(_stricmp(tmp.c_str(), "ENU:") != 0) { QMessageBox::critical(nullptr, QString::fromLocal8Bit("警告"), QString::fromLocal8Bit("坐标参考不一致!"), QMessageBox::Ok); return false; } strSRS = strSRS.substr(4); vector<string> subline; StdStringEx::CutString(strSRS, subline, ','); if(subline.size() != 2) { QMessageBox::critical(nullptr, QString::fromLocal8Bit("警告"), QString::fromLocal8Bit("坐标参考格式不正确!"), QMessageBox::Ok); return false; } y = atof(subline[0].c_str()); x = atof(subline[1].c_str()); } return true; } void SceneProject3D::createObliqueIndexes(std::string fileDir) { string dataDir = fileDir + "/Data"; osg::ref_ptr<osg::Group> group = new osg::Group(); vector<string> subDirs; PathRef::findDir(dataDir, subDirs); for(size_t i = 0; i<subDirs.size(); i++) { string name = PathRef::DirOrPathGetName(subDirs[i]); string path = subDirs[i] + "/" + name + ".osgb"; osg::ref_ptr<osg::Node> node = osgDB::readNodeFile(path); osg::ref_ptr<osg::PagedLOD> lod = new osg::PagedLOD(); auto bs = node->getBound(); auto c = bs.center(); auto r = bs.radius(); lod->setCenter(c); lod->setRadius(r); lod->setRangeMode(osg::LOD::RangeMode::PIXEL_SIZE_ON_SCREEN); osg::ref_ptr<osg::Geode> geode = new osg::Geode; geode->getOrCreateStateSet(); lod->addChild(geode.get()); std::string relativeFilePath = "./Data/" + name + "/" + name + ".osgb"; //相对路径 lod->setFileName(0, ""); lod->setFileName(1, relativeFilePath); lod->setRange(0, 0, 1.0); //第一层不可见 lod->setRange(1, 1.0, FLT_MAX); lod->setDatabasePath(""); group->addChild(lod); } std::string outputLodFile = fileDir + "/Data.osgb"; osgDB::writeNodeFile(*group, outputLodFile); } bool SceneProject3D::AddPhotogrammetry(std::string fileDir) { string obliqueIndexesFile = fileDir + "/Data.osgb"; if (!PathRef::isDirExist(obliqueIndexesFile)) { createObliqueIndexes(fileDir); } osg::ref_ptr<osg::Node> node = osgDB::readNodeFile(obliqueIndexesFile); if(!node) { return false; } // string xmlPath = fileDir + "/metadata.xml"; double cx = 0; double cy = 0; double cz = 0; if(!readObliqueXML(xmlPath, cx, cy, cz)) { return false; } // osg::ref_ptr<osgEarth::GeoTransform> xform = new osgEarth::GeoTransform(); xform->addChild(node); xform->setTerrain(mapNode->getTerrain()); osgEarth::GeoPoint point(map->getSRS(), cx, cy, cz); //使用绝对高,正高 xform->setPosition(point); // osg::ref_ptr<osgEarth::ModelLayer> layer = new osgEarth::ModelLayer(fileDir, xform); map->addLayer(layer); const char * vertexShader = { "void main(void ){\n" " gl_TexCoord[0] = gl_MultiTexCoord0;\n" " gl_Position = gl_ModelViewProjectionMatrix*gl_Vertex;\n" "}\n" }; const char * fragShader = { "uniform sampler2D baseTex;\n" "void main(void){\n" " vec2 coord = gl_TexCoord[0].xy;\n" " vec4 C = texture2D(baseTex, coord)\n;" " gl_FragColor = C;\n" "}\n" }; osg::ref_ptr<osg::Program> program = new osg::Program(); program->addShader(new osg::Shader(osg::Shader::FRAGMENT, fragShader)); program->addShader(new osg::Shader(osg::Shader::VERTEX, vertexShader)); osg::StateSet * ss = node->getOrCreateStateSet(); ss->setAttributeAndModes(program, osg::StateAttribute::ON); //osg::StateAttribute* attr = ss->getAttribute(osg::StateAttribute::PROGRAM); //cout<<program->getType()<<endl; //ss->removeAttribute(attr); QJsonValue value(QString::fromLocal8Bit(fileDir.c_str())); obliquePhotographyArray.push_back(value); return true; } void SceneProject3D::AddArcGISDrivers(std::string name, std::string url) { osgEarth::Drivers::ArcGISOptions imagery; imagery.url() = url; osg::ref_ptr<osgEarth::ImageLayer> layer = new osgEarth::ImageLayer("ArcGISTerrainImagery", imagery); layer->options().cacheId() = name; layer->options().cachePolicy() = osgEarth::CachePolicy::USAGE_READ_WRITE; map->addLayer(layer); } void SceneProject3D::AddArcGISImagery() { AddArcGISDrivers("ArcGISImagery", "http://services.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer"); //AddArcGISDrivers("arcgis-reference-overlay", "http://services.arcgisonline.com/ArcGIS/rest/services/Reference/World_Boundaries_and_Places_Alternate/MapServer"); } void SceneProject3D::AddArcGISTerrainImagery() { AddArcGISDrivers("ArcGISTerrainImagery", "http://services.arcgisonline.com/arcgis/rest/services/World_Terrain_Base/MapServer"); } void SceneProject3D::AddBingImagery() { osgEarth::Drivers::BingOptions bing; bing.apiKey() = "As--nt_Uo7NaGON-IJ0jYcW3LmKsx2BEChizSNA7FRXF8I_Z1GJ37-3CS2qzyiyD"; bing.imagerySet() = "Aerial"; osg::ref_ptr<osgEarth::ImageLayer> layer = new osgEarth::ImageLayer("BingImagery", bing); layer->options().cacheId() = "BingImagery"; layer->options().cachePolicy() = osgEarth::CachePolicy::USAGE_READ_WRITE; map->addLayer(layer); } void SceneProject3D::AddBingTerrain() { osgEarth::Drivers::BingOptions bing; bing.apiKey() = "As--nt_Uo7NaGON-IJ0jYcW3LmKsx2BEChizSNA7FRXF8I_Z1GJ37-3CS2qzyiyD"; osg::ref_ptr<osgEarth::ElevationLayer> layer = new osgEarth::ElevationLayer("BingTerrain", bing); layer->options().cacheId() = "BingTerrain"; layer->options().cachePolicy() = osgEarth::CachePolicy::USAGE_READ_WRITE; map->addLayer(layer); } void SceneProject3D::insertViewPoint(std::string name, std::shared_ptr<osgEarth::Viewpoint> vp) { viewPointMap[name] = vp; } std::shared_ptr<osgEarth::Viewpoint> SceneProject3D::getViewPoint(std::string name) { auto iter = viewPointMap.find(name); if(iter == viewPointMap.end()) { return nullptr; } return iter->second; }
24,249
C++
.cpp
618
31.757282
166
0.635346
fafa1899/SinianGIS
30
14
2
GPL-3.0
9/20/2024, 10:45:00 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,539,891
project3dform.cpp
fafa1899_SinianGIS/SinianGIS/project3dform.cpp
#include "project3dform.h" #include "ui_project3dform.h" #include "pathref.hpp" #include <iostream> #include <QDebug> using namespace std; Q_DECLARE_METATYPE(std::string); Project3DForm::Project3DForm(QWidget *parent) : QWidget(parent), sceneProject3D(nullptr), mainIcon(":/Res/main.png"), terrainIcon(":/Res/terrain.png"), imageIcon(":/Res/image.png"), vectorIcon(":/Res/vector.png"), tiltingDataIcon(":/Res/photogrammetry.png"), ui(new Ui::Project3DForm) { ui->setupUi(this); // QTreeWidgetItem* root = new QTreeWidgetItem(ui->treeWidget); root->setText(0, QString::fromLocal8Bit("三维场景")); ui->treeWidget->addTopLevelItem(root); root->setCheckState(0, Qt::Checked); root->setIcon(0, mainIcon); // terrainItem = new QTreeWidgetItem(root); terrainItem->setText(0, QString::fromLocal8Bit("地形")); root->addChild(terrainItem); terrainItem->setCheckState(0, Qt::Checked); terrainItem->setIcon(0, terrainIcon); // imageItem = new QTreeWidgetItem(root); imageItem->setText(0, QString::fromLocal8Bit("影像")); root->addChild(imageItem); imageItem->setCheckState(0, Qt::Checked); imageItem->setIcon(0, imageIcon); // vectorItem = new QTreeWidgetItem(root); vectorItem->setText(0, QString::fromLocal8Bit("矢量")); root->addChild(vectorItem); vectorItem->setCheckState(0, Qt::Checked); vectorItem->setIcon(0, vectorIcon); // tiltingDataItem = new QTreeWidgetItem(root); tiltingDataItem->setText(0, QString::fromLocal8Bit("倾斜摄影数据")); root->addChild(tiltingDataItem); tiltingDataItem->setCheckState(0, Qt::Checked); tiltingDataItem->setIcon(0, tiltingDataIcon); // // // QTreeWidgetItem* modelDataItem = new QTreeWidgetItem(); // modelDataItem->setText(0, QString::fromLocal8Bit("模型数据")); // root->addChild(modelDataItem); // modelDataItem->setCheckState(0, Qt::Checked); //展开所有的子项目 ui->treeWidget->expandAll(); //要在设置完子项目之后再调用才有效 } Project3DForm::~Project3DForm() { delete ui; } void Project3DForm::LoadProject3d(std::shared_ptr<SceneProject3D> project) { sceneProject3D = project; for (int i = 0; i < sceneProject3D->localImageArray.size(); i++) { QJsonValue value = sceneProject3D->localImageArray.at(i); if (value.isString()) { QByteArray v = value.toString().toLocal8Bit(); AddImage(v.data()); } } for (int i = 0; i < sceneProject3D->localTerrainArray.size(); i++) { QJsonValue value = sceneProject3D->localTerrainArray.at(i); if (value.isString()) { QByteArray v = value.toString().toLocal8Bit(); AddTerrain(v.data()); } } for (int i = 0; i < sceneProject3D->obliquePhotographyArray.size(); i++) { QJsonValue value = sceneProject3D->obliquePhotographyArray.at(i); if (value.isString()) { QByteArray v = value.toString().toLocal8Bit(); AddTiltingData(v.data()); } } for (int i = 0; i < sceneProject3D->localVectorArray.size(); i++) { QJsonValue value = sceneProject3D->localVectorArray.at(i); if (value.isString()) { QByteArray v = value.toString().toLocal8Bit(); AddVector(v.data()); } } } void Project3DForm::AddTerrain(std::string fileName) { QTreeWidgetItem *subItem = new QTreeWidgetItem(terrainItem); string name = PathRef::DirOrPathGetName(fileName); subItem->setText(0, QString::fromLocal8Bit(name.c_str())); terrainItem->addChild(subItem); subItem->setCheckState(0, Qt::Checked); subItem->setIcon(0, terrainIcon); subItem->setData(0, Qt::UserRole, QVariant::fromValue(fileName)); } void Project3DForm::AddImage(std::string fileName) { QTreeWidgetItem *subItem = new QTreeWidgetItem(imageItem); string name = PathRef::DirOrPathGetName(fileName); subItem->setText(0, QString::fromLocal8Bit(name.c_str())); imageItem->addChild(subItem); subItem->setCheckState(0, Qt::Checked); subItem->setIcon(0, imageIcon); subItem->setData(0, Qt::UserRole, QVariant::fromValue(fileName)); } void Project3DForm::AddVector(std::string fileName) { QTreeWidgetItem *subItem = new QTreeWidgetItem(vectorItem); string name = PathRef::DirOrPathGetName(fileName); subItem->setText(0, QString::fromLocal8Bit(name.c_str())); vectorItem->addChild(subItem); subItem->setCheckState(0, Qt::Checked); subItem->setIcon(0, vectorIcon); subItem->setData(0, Qt::UserRole, QVariant::fromValue(fileName)); } void Project3DForm::AddTiltingData(std::string fileName) { QTreeWidgetItem *subItem = new QTreeWidgetItem(tiltingDataItem); string name = PathRef::DirOrPathGetName(fileName); subItem->setText(0, QString::fromLocal8Bit(name.c_str())); tiltingDataItem->addChild(subItem); subItem->setCheckState(0, Qt::Checked); subItem->setIcon(0, tiltingDataIcon); subItem->setData(0, Qt::UserRole, QVariant::fromValue(fileName)); } void Project3DForm::on_treeWidget_itemDoubleClicked(QTreeWidgetItem *item, int column) { QTreeWidgetItem *parent = item->parent(); if(parent == terrainItem || parent == imageItem || parent == vectorItem || parent == tiltingDataItem) { string name = item->data(0, Qt::UserRole).value<std::string>(); signalViewPoint(name); } }
5,474
C++
.cpp
148
31.601351
105
0.687512
fafa1899/SinianGIS
30
14
2
GPL-3.0
9/20/2024, 10:45:00 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,539,892
osg3dglobalshowwidget.h
fafa1899_SinianGIS/SinianGIS/osg3dglobalshowwidget.h
#ifndef OSG3DGLOBALSHOWWIDGET_H #define OSG3DGLOBALSHOWWIDGET_H #include "osgshowwidget.h" #include "sceneproject3d.h" #include <osgViewer/CompositeViewer> #include <osgEarthUtil/EarthManipulator> class OSG3DGlobalShowWidget : public OSGShowWidget { Q_OBJECT public: explicit OSG3DGlobalShowWidget(QWidget *parent = nullptr); virtual ~OSG3DGlobalShowWidget(); bool load3DProject(std::shared_ptr<SceneProject3D> project); void SetTerrainLayerViewPoint(std::string name); void SetNodeViewPoint(std::string name); signals: public slots: void slotViewPoint(std::string name); protected: std::shared_ptr<SceneProject3D> sceneProject3D; osg::ref_ptr<osgEarth::Util::EarthManipulator> mainManipulator; bool CalViewPointGeoExtend(const osgEarth::GeoExtent& extent, std::shared_ptr<osgEarth::Viewpoint> out); bool CalViewPointNode(osg::ref_ptr<osg::Node> node, std::shared_ptr<osgEarth::Viewpoint> out); }; #endif // OSG3DGLOBALSHOWWIDGET_H
988
C++
.h
25
36.28
108
0.796004
fafa1899/SinianGIS
30
14
2
GPL-3.0
9/20/2024, 10:45:00 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,539,893
pathref.hpp
fafa1899_SinianGIS/SinianGIS/pathref.hpp
#ifndef PATHREF_H #define PATHREF_H #include <string> #include <vector> #include <QApplication> #include <QDir> using std::string; using std::vector; class PathRef { public: PathRef() { } //得到文件名 C:\\b\\a(.txt) -> a.txt static string GetNameWithFormat(string filePath) { size_t p = filePath.find_last_of(slash); if (p != string::npos) { filePath = filePath.substr(p+1, filePath.length() - p - 1); } return filePath; } //得到文件路径的格式后缀 C:\\b\\a.txt -> .txt static string GetFormat(string filePath) { size_t p = filePath.find_last_of('.'); if (p == string::npos) { return string(); } return filePath.erase(0, p); } //得到文件路径上层目录 C:\\b\\a(.txt) -> C:\\b static string GetPathLastDir(string filePath) { size_t p = filePath.find_last_of(slash); if (p != string::npos) { filePath.erase(p); } return filePath; } //得到文件路径的文件名 C:\\b\\a(.txt) -> a static std::string DirOrPathGetName(std::string filePath) { size_t m = filePath.find_last_of(slash); if (m == string::npos) { return filePath; } size_t p = filePath.find_last_of('.'); if (p != string::npos && p > m) //没有点号或者 { filePath.erase(p); } std::string dirPath = filePath; dirPath.erase(0, m + 1); return dirPath; } //改变路径名称,便于保存 C:\\b\\a.txt->c--b-c.txt static string GetSaveString(string filePath) { for(size_t i = 0; i<filePath.length(); i++) { if(filePath[i] == '\\' || filePath[i] == '/' || filePath[i] == ':') { filePath[i] = '-'; } } return filePath; } //获取APP目录 static std::string GetAppDir() { QByteArray currentDir = QCoreApplication::applicationDirPath().toLocal8Bit(); return currentDir.data(); } //查找目录下所有的文件夹 static void findDir(string dir, vector<string>& subDirs) { // subDirs.clear(); QDir fromDir(QString::fromLocal8Bit(dir.c_str())); QStringList filters; // QFileInfoList fileInfoList = fromDir.entryInfoList(filters, QDir::AllDirs|QDir::Files); foreach(QFileInfo fileInfo, fileInfoList) { if (fileInfo.fileName() == "." || fileInfo.fileName() == "..") { continue; } if (fileInfo.isDir()) { QByteArray dir = fileInfo.filePath().toLocal8Bit(); subDirs.push_back(dir.data()); } } } static bool isDirExist(std::string filePath)//定义 { QFile mFile(QString::fromLocal8Bit(filePath.c_str())); if(mFile.exists()) { return true; } return false; } const static char slash = '/'; }; #endif // PATHREF_H
3,017
C++
.h
113
19.00885
95
0.543324
fafa1899/SinianGIS
30
14
2
GPL-3.0
9/20/2024, 10:45:00 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,539,894
qdockwidgetex.h
fafa1899_SinianGIS/SinianGIS/qdockwidgetex.h
#ifndef QDOCKWIDGETEX_H #define QDOCKWIDGETEX_H #include <QDockWidget> class QDockWidgetEx : public QDockWidget { Q_OBJECT public: explicit QDockWidgetEx(const QString &title, QWidget *parent = nullptr, Qt::WindowFlags flags = Qt::WindowFlags()) : QDockWidget(title, parent, flags) { } explicit QDockWidgetEx(QWidget *parent = nullptr, Qt::WindowFlags flags = Qt::WindowFlags()) : QDockWidget(parent, flags) { } signals: void signalClose(QDockWidgetEx *dock); protected: void closeEvent(QCloseEvent *event); }; #endif // QDOCKWIDGETEX_H
622
C++
.h
22
23.409091
96
0.695286
fafa1899/SinianGIS
30
14
2
GPL-3.0
9/20/2024, 10:45:00 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,539,895
Settings.h
fafa1899_SinianGIS/SinianGIS/Settings.h
#ifndef COMMON_H #define COMMON_H #include <QSettings> extern QSettings* gSettings; #endif // COMMON_H
106
C++
.h
5
19.6
28
0.795918
fafa1899/SinianGIS
30
14
2
GPL-3.0
9/20/2024, 10:45:00 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,539,896
osg3dobjectshowwidget.h
fafa1899_SinianGIS/SinianGIS/osg3dobjectshowwidget.h
#ifndef OSG3DOBJECTSHOWWIDGET_H #define OSG3DOBJECTSHOWWIDGET_H #include "osgshowwidget.h" class OSG3DObjectShowWidget : public OSGShowWidget { Q_OBJECT public: explicit OSG3DObjectShowWidget(QWidget *parent = nullptr); virtual ~OSG3DObjectShowWidget(); void load3DObject(std::string filePath); signals: protected: osg::ref_ptr<osg::Group> root; public slots: }; #endif // OSG3DOBJECTSHOWWIDGET_H
424
C++
.h
16
23.8125
62
0.798005
fafa1899/SinianGIS
30
14
2
GPL-3.0
9/20/2024, 10:45:00 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,539,897
loadphotogrammetrydialog.h
fafa1899_SinianGIS/SinianGIS/loadphotogrammetrydialog.h
#ifndef LOADPHOTOGRAMMETRYDIALOG_H #define LOADPHOTOGRAMMETRYDIALOG_H #include <QDialog> namespace Ui { class LoadPhotogrammetryDialog; } class LoadPhotogrammetryDialog : public QDialog { Q_OBJECT public: explicit LoadPhotogrammetryDialog(QWidget *parent = nullptr); ~LoadPhotogrammetryDialog(); std::string GetDataDir(){return dataDir;} protected: std::string dataDir; private slots: void on_pushButtonOK_clicked(); void on_pushButtonCancel_clicked(); void on_pBDir_clicked(); private: Ui::LoadPhotogrammetryDialog *ui; }; #endif // LOADPHOTOGRAMMETRYDIALOG_H
608
C++
.h
23
23.391304
65
0.789199
fafa1899/SinianGIS
30
14
2
GPL-3.0
9/20/2024, 10:45:00 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,539,898
WebTilesClass.h
fafa1899_SinianGIS/SinianGIS/WebTilesClass.h
#pragma once #include <vector> struct OneLevel { int tilesNumX; int tilesNumY; int pixelSizeX; int pixelSizeY; double dX; double dY; }; struct OneTile { size_t x; size_t y; int z; std::string uri; }; class WebTilesClass { public: WebTilesClass(); virtual ~WebTilesClass(); virtual bool GetTiles(double left, double top, double right, double bottom, int level, std::vector<OneTile> &tiles); virtual bool WriteGeoInfo(std::string imgName, OneTile& tile); protected: //地图左上角的地理起始位置,位于左上角 double geoStartX; //起始位置X double geoStartY; //起始位置Y double geoEndX; //终点位置X double geoEndY; //终点位置Y int tilePixelSizeX; int tilePixelSizeY; int levelNum; std::vector<OneLevel> levelList; }; int DownloadTiles(std::string address, std::string outfile, std::string proxy = "");
842
C++
.h
37
19.72973
118
0.758893
fafa1899/SinianGIS
30
14
2
GPL-3.0
9/20/2024, 10:45:00 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,539,899
sceneproject3d.h
fafa1899_SinianGIS/SinianGIS/sceneproject3d.h
#ifndef SCENEPROJECT3D_H #define SCENEPROJECT3D_H #include "sceneprojectbase.h" #include <osg/Group> #include <osgEarth/MapNode> #include <osgEarth/Viewpoint> class SceneProject3D : public SceneProjectBase { public: SceneProject3D(); virtual void create() override; virtual void read(std::string path) override; virtual void write(std::string path) override; osg::ref_ptr<osg::Group> GetRootNode(){return root;} osgEarth::Viewpoint *GetHomeViewPoint(){return &homeViewPoint;} osg::ref_ptr<osgEarth::Map> GetMap(){return map;} osg::ref_ptr<osgEarth::MapNode> GetMapNode(){return mapNode;} QJsonArray& GetImageArray(){return localImageArray;} void AddLocalImage(std::string filePath); void AddLocalTerrain(std::string filePath); bool AddLocalVector(std::string filePath); bool AddPhotogrammetry(std::string fileDir); void AddArcGISImagery(); void AddArcGISTerrainImagery(); void AddBingImagery(); void AddBingTerrain(); void insertViewPoint(std::string name, std::shared_ptr<osgEarth::Viewpoint> vp); std::shared_ptr<osgEarth::Viewpoint> getViewPoint(std::string name); void AddSkyBox(); // QJsonArray localImageArray; QJsonArray localTerrainArray; QJsonArray obliquePhotographyArray; QJsonArray localVectorArray; //signals: protected: void InitEarthMapNode(); void InitViewPoint(); void AddArcGISDrivers(std::string name, std::string url); bool CalViewPointGeoExtend(const osgEarth::GeoExtent& extent, std::shared_ptr<osgEarth::Viewpoint> out); void createObliqueIndexes(std::string fileDir); //读取倾斜摄影数据的元数据 bool readObliqueXML(std::string metaXML, double& x, double& y, double &z); //读取倾斜摄影数据的元数据 void ReadViewPoint(); void SaveViewPoint(); osg::ref_ptr<osg::Group> root; osg::ref_ptr<osgEarth::Map> map; osg::ref_ptr<osgEarth::MapNode> mapNode; osgEarth::Viewpoint homeViewPoint; std::map<std::string, std::shared_ptr<osgEarth::Viewpoint>> viewPointMap; }; #endif // SCENEPROJECT3D_H
2,091
C++
.h
51
36.156863
108
0.743988
fafa1899/SinianGIS
30
14
2
GPL-3.0
9/20/2024, 10:45:00 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,539,900
osgshowwidget.h
fafa1899_SinianGIS/SinianGIS/osgshowwidget.h
#ifndef OSGSHOWWIDGET_H #define OSGSHOWWIDGET_H #include "sceneproject3d.h" #include <map> #include <QWidget> #include <QTimer> #include <osgViewer/CompositeViewer> #include <osgEarthUtil/EarthManipulator> class OSGShowWidget : public QWidget { Q_OBJECT public: explicit OSGShowWidget(QWidget *parent = nullptr); virtual ~OSGShowWidget(); virtual std::string GetName(){return name;} //bool load3DProject(std::shared_ptr<SceneProject3D> project); // void SetTerrainLayerViewPoint(std::string name); // void SetNodeViewPoint(std::string name); //启动定时器绘制 void onStartTimer(); //关闭定时器绘制 void onStopTimer(); bool isWork(){return bWork;} //std::string GetName(){return sceneProject3D?sceneProject3D->getFileName():"";} protected: //virtual void paintEvent(QPaintEvent* e); virtual void timerEvent(QTimerEvent* ); void addView(); // bool CalViewPointGeoExtend(const osgEarth::GeoExtent& extent, std::shared_ptr<osgEarth::Viewpoint> out); // bool CalViewPointNode(osg::ref_ptr<osg::Node> node, std::shared_ptr<osgEarth::Viewpoint> out); //QTimer _timer; int _timerID; //定时器ID osgViewer::CompositeViewer _viewer; bool bWork; osg::ref_ptr<osgViewer::View> view; //std::shared_ptr<SceneProject3D> sceneProject3D; //osg::ref_ptr<osgEarth::Util::EarthManipulator> mainManipulator; QWidget* viewWidget; std::string name; signals: }; #endif // OSGSHOWWIDGET_H
1,523
C++
.h
42
32.119048
110
0.718251
fafa1899/SinianGIS
30
14
2
GPL-3.0
9/20/2024, 10:45:00 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,539,901
StdStringEx.hpp
fafa1899_SinianGIS/SinianGIS/StdStringEx.hpp
#pragma once #include <string> #include <vector> #include <sstream> using std::string; using std::vector; //std::string的强化函数类 class StdStringEx { public: //根据字符切分string,兼容最前最后存在字符 static void CutString(string line, vector<string> &subline, char a) { //首字母为a,剔除首字母 if (line.size() < 1) { return; } if (line[0] == a) { line.erase(0, 1); } size_t pos = 0; while (pos < line.length()) { size_t curpos = pos; pos = line.find(a, curpos); if (pos == string::npos) { pos = line.length(); } subline.push_back(line.substr(curpos, pos - curpos)); pos++; } return; } //根据空截断字符串 static void ChopStringLineEx(string line, vector<string> &substring) { std::stringstream linestream(line); string sub; while (linestream >> sub) { substring.push_back(sub); } } };
873
C++
.h
47
14.87234
69
0.661935
fafa1899/SinianGIS
30
14
2
GPL-3.0
9/20/2024, 10:45:00 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,539,902
mainwindow.h
fafa1899_SinianGIS/SinianGIS/mainwindow.h
#ifndef MAINWINDOW_H #define MAINWINDOW_H #include "sceneproject3d.h" #include "qdockwidgetex.h" #include <QMainWindow> #include <memory> QT_BEGIN_NAMESPACE namespace Ui { class MainWindow; } QT_END_NAMESPACE class MainWindow : public QMainWindow { Q_OBJECT public: MainWindow(std::string filePath, QWidget *parent = nullptr); ~MainWindow(); void show(); signals: void signalDockRaise(); protected: void closeEvent(QCloseEvent *e); void loadData(std::string filePath); void loadTypeData(std::string filePath, int type); void loadProject(std::shared_ptr<SceneProject3D> _3dProject); void loadObject(std::string filePath); int find3DShowWidgetIndex(std::string name); std::map<std::string, std::shared_ptr<SceneProjectBase>> projectMap; std::map<std::string, QDockWidgetEx *> leftDockMap; std::shared_ptr<SceneProjectBase> curProj; QDockWidgetEx *curLeftDock; bool initWindow; private slots: void on_tBNewProject_clicked(); //加载影像数据 void on_tBNewImageLayer_clicked(); void on_actionArcGISImage_triggered(); void on_actionArcGISTerrain_triggered(); void on_actionBingImage_triggered(); void on_actionBingTerrain_triggered(); //加载地形数据 void on_tBNewTerrainLayer_clicked(); void on_tBSaveProject_clicked(); //打开数据 void on_tBOpenProject_clicked(); void on_centralTabWidget_currentChanged(int index); void on_centralTabWidget_tabCloseRequested(int index); //加载倾斜摄影数据 void on_tBNewPhotogrammetry_clicked(); //堆叠的停靠窗口被激活 void on_MainWindow_tabifiedDockWidgetActivated(QDockWidget *dockWidget); void slotCloseDock(QDockWidgetEx *dockWidget); //加载矢量 void on_tBNewVectorLayer_clicked(); void on_tBGoogleImageDownload_clicked(); private: Ui::MainWindow *ui; }; #endif // MAINWINDOW_H
1,895
C++
.h
57
28.298246
76
0.750141
fafa1899/SinianGIS
30
14
2
GPL-3.0
9/20/2024, 10:45:00 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,539,903
sceneprojectbase.h
fafa1899_SinianGIS/SinianGIS/sceneprojectbase.h
#ifndef SCENEPROJECTBASE_H #define SCENEPROJECTBASE_H #include <string> #include <QJsonObject> #include <QJsonArray> class SceneProjectBase { public: SceneProjectBase(); virtual ~SceneProjectBase(); virtual void create()=0; virtual void read(std::string path)=0; virtual void write(std::string path)=0; std::string getFileName(){return projectFilePath;} protected: std::string projectFilePath; std::string appDir; QJsonObject projectJSON; }; #endif // SCENEPROJECTBASE_H
514
C++
.h
20
22.55
54
0.759754
fafa1899/SinianGIS
30
14
2
GPL-3.0
9/20/2024, 10:45:00 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false