Example #1
0
 def render_template(self, template, send=True, content_type='text/html'):
     if isinstance(template, str):
         template = get_resource_path('html', template)
     else:
         template = get_resource_path('html', *template)
     html, url = render(template, model=__browser_session__.model)
     self.delegate.write(html)
     if send:
         self.delegate.send(content_type)
Example #2
0
def get_resource_url(*path):
    """
    Translate path into (url, parent_url, abs_path)
    """

    file_path = get_resource_path('html', *path)
    return file_path.as_uri(), file_path.parent.as_uri(), file_path
Example #3
0
 def getModIcon(self, name, install_path, wbKey, wb):
     icon_path = Path(install_path, 'resources', 'icons', '{0}Workbench.svg'.format(name))
     if icon_path.exists():
         return utils.path_to_url(icon_path)
     else:
         if wb and hasattr(wb, 'Icon'):
             return utils.path_to_url(utils.extract_icon(wb.Icon, 'workbench.svg'))
     return utils.path_to_url(get_resource_path('html', 'img', 'workbench.svg'))
Example #4
0
    def getMacroList(self):

        macros = []
        install_dir = get_macro_path()
        default_icon = utils.path_to_url(
            get_resource_path('html', 'img', 'package_macro.svg'))

        try:
            content = http_get(self.url, timeout=45)
            if content:
                data = json.loads(content)
                wiki = get_page_content_from_json(data)

                for m_link in MACRO_LINK.finditer(wiki):

                    name = m_link.group('name').replace(' ', '_')
                    label = m_link.group('label')
                    description = m_link.group('description')

                    icon = m_link.group('icon')
                    if icon:
                        icon = self.wiki + '/Special:Redirect/file/' + icon.replace(
                            ' ', '_')
                    else:
                        icon = default_icon

                    pkg = PackageInfo(
                        key=name,
                        installDir=install_dir,
                        installFile=Path(install_dir, name + '.FCMacro'),
                        name=name,
                        title=label,
                        description=description,
                        icon=icon,
                        isCore=False,
                        type='Macro',
                        isGit=False,
                        isWiki=True,
                        markedAsSafe=False,
                        categories=[tr('Uncategorized')],
                        date=None,
                        version=None,
                        readmeUrl='{0}/Macro_{1}?origin=*'.format(
                            self.wiki, name),
                        readmeFormat='html')
                    flags.apply_predefined_flags(pkg)
                    macros.append(pkg)

        except:
            traceback.print_exc(file=sys.stderr)

        return macros
Example #5
0
def start_browser():
    global __browser_instance__
    if not __browser_instance__:
        main_window = Gui.getMainWindow().findChild(QtGui.QMdiArea)
        bi = WebView(tr('Extension Manager'), get_cache_path(),
                     request_handler, message_handler, main_window)
        bi.closed.connect(on_web_view_close)
        index = path_to_extman_url(get_resource_path('html', 'index.html'))
        bi.load(index)
        main_window.addSubWindow(bi)
        bi.show()
        __browser_instance__ = bi
    return __browser_instance__
Example #6
0
def getSourcesData():

    # Official sources
    path = get_resource_path('data', 'sources.json')
    data = []
    with open(path, 'r', encoding='utf-8') as f:
        data = json.load(f)

    # Custom sources
    custom = {
        'id': 'Custom',
        'name': 'Custom Extensions Sources',
        'sources': json.loads(ExtManParameters.CustomCloudSources)
    }
    data.append(custom)

    return data
Example #7
0
    def __init__(self, data, channelId):
        super().__init__('Cloud:' + data['protocol'])

        self.channelId = channelId
        self.name = data['name']
        self.title = tr(data['title'])
        self.description = tr(data['description']) or data.get(
            'git', data.get('wiki', ''))
        self.protocolName = data['protocol']
        self.cacheTime = 0
        self.type = data['type']

        icon = data['icon']
        if icon.startswith('html/img/'):
            self.icon = utils.path_to_url(get_resource_path(*icon.split('/')))
        else:
            self.icon = icon

        if data['protocol'] == 'github':
            self.protocol = GithubProtocol(
                data['git'],
                data.get('git_submodules'),
                data.get('index_type'),
                data.get('index_url'),
                data.get('wiki'),
            )
        elif data['protocol'] == 'framagit':
            self.protocol = FramagitProtocol(
                data['git'],
                data.get('git_submodules'),
                data.get('index_type'),
                data.get('index_url'),
                data.get('wiki'),
            )
        elif data['protocol'] == 'fcwiki':
            self.protocol = FCWikiProtocol(data['url'], data['wiki'])
        else:
            raise UnsupportedSourceException(
                "Unsupported protocol: {0}".format(data['protocol']))

        self.updates = {}
Example #8
0
def get_flags_database():
    """
    Reads resources/data/flags.json
    returns dict( "{pkg.type:pkg.name.lower()}" => flags )
    """

    db = {}
    with open(get_resource_path('data', 'flags.json'), 'r',
              encoding='utf-8') as f:
        data = json.load(f)
        for flagId, flag in data.items():
            mods = flag.get('Mod', [])
            macros = flag.get('Macro', [])
            items = itertools.chain(((m, 'Mod') for m in mods),
                                    ((m, 'Macro') for m in macros))
            for name, mtype in items:
                key = "{0}:{1}".format(mtype, name.lower())
                mod = db.get(key, {})
                mod[flagId] = True
                db[key] = mod
    return db
Example #9
0
class ExtManWorkbench(Gui.Workbench):
    """Extension Manager Workbench"""

    Icon = str(get_resource_path('icons', 'ExtManWorkbench.svg'))
    MenuText = tr("Extension Manager")
    ToolTip = tr("Extension Manager")

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

    def GetClassName(self):
        return "Gui::PythonWorkbench"

    def Initialize(self):
        log("ExtMan Initialized")

    def Activated(self):
        install_router(create_router())
        start_browser()

    def Deactivated(self):
        pass
Example #10
0
def extract_icon(src, default='freecad.svg'):

    default_path = get_resource_path('html', 'img', default)
    xpm_path = Path(get_cache_path(), 'xpm')
    if not xpm_path.exists():
        xpm_path.mkdir(parents=True)

    if "XPM" in src:
        try:
            xpm_hash = hashlib.sha256(src.encode()).hexdigest()
            if xpm_hash in XPM_CACHE:
                return XPM_CACHE[xpm_hash]
            xpm = src.replace("\n        ", "\n")
            r = [
                s[:-1].strip('"')
                for s in re.findall(r"(?s)\{(.*?)\};", xpm)[0].split("\n")[1:]
            ]
            p = QtGui.QPixmap(r)
            p = p.scaled(24, 24)
            img = Path(xpm_path, xpm_hash + '.png')
            p.save(img)
            if img.exists():
                XPM_CACHE[xpm_hash] = str(img)
                return str(img)
            else:
                return default_path
        except:
            return default_path
    else:
        try:
            if Path(src).exists():
                return src
            else:
                return default_path
        except:
            return src
Example #11
0
def build_macro_package(path,
                        macro_name,
                        is_core=False,
                        is_git=False,
                        is_wiki=False,
                        install_path=None,
                        base_path=""):

    with open(path, 'r', encoding='utf-8') as f:

        try:
            tags = get_macro_tags(f.read(), path)
        except:  # !TODO: Handle encoding problems in old windows platforms
            tags = {k: None for k in MACRO_TAG_FILTER}
            log_err(tr('Macro {0} contains invalid characters').format(path))

        install_dir = get_macro_path()
        base = dict(key=str(install_path) if install_path else str(path),
                    type='Macro',
                    isCore=is_core,
                    installDir=install_dir,
                    installFile=Path(install_dir, path.name),
                    isGit=is_git,
                    isWiki=is_wiki,
                    basePath=base_path)
        tags.update(base)

        if not tags['title']:
            tags['title'] = tags['name'] or macro_name

        tags['name'] = macro_name  # Always override name with actual file name

        if not tags['icon']:
            tags['icon'] = get_resource_path('html', 'img',
                                             'package_macro.svg')

        try:
            if not Path(tags['icon']).exists():
                tags['icon'] = get_resource_path('html', 'img',
                                                 'package_macro.svg')
        except:
            tags['icon'] = get_resource_path('html', 'img',
                                             'package_macro.svg')

        tags['icon'] = utils.path_to_url(tags['icon'])

        if tags['comment']:
            tags['description'] = tags['comment']

        if not tags['description']:
            tags['description'] = tr('Warning! No description')

        if tags['categories']:
            cats = COMMA_SEP_LIST_PATTERN.split(tags['categories'])
            tags['categories'] = [tr(c) for c in cats]
        else:
            tags['categories'] = [tr('Uncategorized')]

        if tags['files']:
            tags['files'] = COMMA_SEP_LIST_PATTERN.split(tags['files'])

        if tags['readme']:
            tags['readmeUrl'] = tags['readme']
            tags['readmeFormat'] = 'html'
        elif tags['wiki']:
            tags['readmeUrl'] = tags['wiki']
            tags['readmeFormat'] = 'html'
        elif tags['web']:
            tags['readmeUrl'] = tags['web']
            tags['readmeFormat'] = 'html'

        return PackageInfo(**tags)
Example #12
0
# *  You should have received a copy of the GNU General Public License      *
# *  along with this program.  If not, see <https://www.gnu.org/licenses/>. *
# *                                                                         *
# ***************************************************************************

import FreeCADGui as Gui
from PySide import QtGui, QtCore

from freecad.extman.gui.controller import actions, message_handlers
from freecad.extman import tr, get_resource_path, get_cache_path, log, log_err
from freecad.extman.template.html import render
from freecad.extman.gui.webview import WebView

__browser_instance__ = None  # Singleton: WebView
__browser_session__ = {}  # Singleton: State
__browser_base_path__ = get_resource_path(
    'html')  # Constant:  Base dir for templates
__router__ = None  # Singleton: Router configuration


def path_to_extman_url(path):
    return path.as_uri().replace('file:', 'extman:')


class BrowserSession:
    def __init__(self, model, router):
        self.model = model
        self.model['route'] = router

    def set_state(self, **kw):
        self.model.update(kw)
Example #13
0
 def getIcon(self):
     return utils.path_to_url(
         get_resource_path('html', 'img', 'source_installed.svg'))
Example #14
0
 def getProtocolIcon(self):
     return utils.path_to_url(
         get_resource_path('html', 'img', 'source_cloud_{0}.svg'.format(
             self.protocolName)))