File indexing completed on 2024-12-15 04:01:20
0001 /* 0002 * SPDX-FileCopyrightText: 2019-2023 Mattia Basaglia <dev@dragon.best> 0003 * 0004 * SPDX-License-Identifier: GPL-3.0-or-later 0005 */ 0006 0007 #pragma once 0008 #include "plugin.hpp" 0009 0010 #include "app/application.hpp" 0011 0012 namespace glaxnimate::plugin { 0013 0014 class Snippet 0015 { 0016 public: 0017 explicit Snippet(const QString& name = {}) 0018 { 0019 set_name(name); 0020 } 0021 0022 const QString& set_name(const QString& name) 0023 { 0024 QString clean_name; 0025 for ( const auto& ch : name ) 0026 { 0027 if ( ch.isLetterOrNumber() || ch == ' ' || ch == '_' || ch == '-' || ch == '.' || ch == '\'' || ch == '"' ) 0028 clean_name.push_back(ch); 0029 } 0030 0031 if ( !clean_name.isEmpty() ) 0032 { 0033 if ( name_.isEmpty() ) 0034 { 0035 name_ = clean_name; 0036 } 0037 else if ( name_ != clean_name && QFileInfo(filename()).exists() ) 0038 { 0039 if ( QFile::rename(filename(), snippet_filename(clean_name)) ) 0040 name_ = clean_name; 0041 } 0042 } 0043 0044 return name_; 0045 } 0046 0047 const QString& name() const 0048 { 0049 return name_; 0050 } 0051 0052 static QString snippet_path() 0053 { 0054 return app::Application::instance()->writable_data_path("snippets"); 0055 } 0056 0057 static QString snippet_filename(const QString& basename) 0058 { 0059 return snippet_path() + "/" + basename + ".py"; 0060 } 0061 0062 QString filename() const 0063 { 0064 return snippet_filename(name_); 0065 } 0066 0067 QString get_source() const 0068 { 0069 QFile file(filename()); 0070 if ( !file.open(QFile::ReadOnly|QIODevice::Text) ) 0071 return {}; 0072 return QString::fromUtf8(file.readAll()); 0073 } 0074 0075 bool ensure_file_exists() const 0076 { 0077 QFileInfo finfo(filename()); 0078 if ( finfo.exists() ) 0079 return true; 0080 0081 QDir parent(snippet_path()); 0082 if ( !parent.exists() ) 0083 { 0084 parent.cdUp(); 0085 if ( !parent.mkpath("snippets") ) 0086 return false; 0087 } 0088 0089 QFile file(filename()); 0090 if ( !file.open(QFile::WriteOnly|QIODevice::Text) ) 0091 return false; 0092 0093 file.write(i18n("# Glaxnimate snippet").toUtf8()); 0094 file.write("\n"); 0095 file.write(i18n("# You have access to the `window` and `document` global variables and the `glaxnimate` module").toUtf8()); 0096 file.write("\n"); 0097 file.write(i18n("# For documentation see https://glaxnimate.mattbas.org/contributing/scripting/").toUtf8()); 0098 file.write("\n"); 0099 file.write("\n"); 0100 return true; 0101 } 0102 0103 private: 0104 QString name_; 0105 }; 0106 0107 } // namespace glaxnimate::plugin