gns3-server/gns3server/controller/symbols.py

145 lines
5.3 KiB
Python
Raw Normal View History

#!/usr/bin/env python
#
# Copyright (C) 2016 GNS3 Technologies Inc.
#
# 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 3 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/>.
import os
2019-03-12 13:13:33 +02:00
import aiohttp
2018-11-23 13:26:04 +02:00
import posixpath
2018-11-23 12:27:10 +02:00
from .symbol_themes import BUILTIN_SYMBOL_THEMES
from ..utils.get_resource import get_resource
2016-08-17 12:58:19 +03:00
from ..utils.picture import get_size
2016-06-28 20:58:57 +03:00
from ..config import Config
import logging
log = logging.getLogger(__name__)
class Symbols:
"""
Manage GNS3 symbols
"""
def __init__(self):
2018-11-23 12:27:10 +02:00
try:
self.list()
2018-11-23 12:27:10 +02:00
except OSError: # The error will be raised and forwarded later
pass
2018-11-23 12:27:10 +02:00
2016-08-17 12:58:19 +03:00
# Keep a cache of symbols size
self._symbol_size_cache = {}
self._current_theme = "Classic"
2018-11-23 12:27:10 +02:00
self._themes = BUILTIN_SYMBOL_THEMES
@property
def theme(self):
return self._current_theme
@theme.setter
def theme(self, theme):
if not self._themes.get(theme):
2019-03-12 13:13:33 +02:00
raise aiohttp.web.HTTPNotFound(text="Could not find symbol theme '{}'".format(theme))
2018-11-23 12:27:10 +02:00
self._current_theme = theme
2019-03-12 13:13:33 +02:00
def default_symbols(self):
return BUILTIN_SYMBOL_THEMES
def get_default_symbol(self, symbol, symbol_theme):
theme = self._themes.get(symbol_theme, None)
if not theme:
raise aiohttp.web.HTTPNotFound(text="Could not find symbol theme '{}'".format(symbol_theme))
symbol_path = theme.get(symbol)
if symbol_path not in self._symbols_path:
log.warning("Default symbol {} was not found".format(symbol_path))
return None
return symbol_path
def list(self):
2018-11-23 12:27:10 +02:00
self._symbols_path = {}
symbols = []
if get_resource("symbols"):
for root, _, files in os.walk(get_resource("symbols")):
for filename in files:
if filename.startswith('.'):
continue
2018-11-23 13:47:42 +02:00
symbol_file = posixpath.normpath(os.path.relpath(os.path.join(root, filename), get_resource("symbols"))).replace('\\', '/')
theme = posixpath.dirname(symbol_file).replace('/', '-').capitalize()
if not theme:
continue
symbol_id = ':/symbols/' + symbol_file
2018-11-23 12:27:10 +02:00
symbols.append({'symbol_id': symbol_id,
'filename': filename,
'theme': theme,
2018-11-23 12:27:10 +02:00
'builtin': True})
self._symbols_path[symbol_id] = os.path.join(root, filename)
2016-06-28 22:15:22 +03:00
directory = self.symbols_path()
2016-06-28 20:58:57 +03:00
if directory:
for root, _, files in os.walk(directory):
for filename in files:
if filename.startswith('.'):
continue
2018-11-23 13:47:42 +02:00
symbol_file = posixpath.normpath(os.path.relpath(os.path.join(root, filename), directory)).replace('\\', '/')
2018-11-23 12:27:10 +02:00
symbols.append({'symbol_id': symbol_file,
'filename': filename,
'builtin': False,
'theme': "Custom symbols"})
self._symbols_path[symbol_file] = os.path.join(root, filename)
symbols.sort(key=lambda x: x["theme"])
return symbols
2016-06-28 22:15:22 +03:00
def symbols_path(self):
2016-06-28 20:58:57 +03:00
directory = os.path.expanduser(Config.instance().get_section_config("Server").get("symbols_path", "~/GNS3/symbols"))
if directory:
try:
os.makedirs(directory, exist_ok=True)
except OSError as e:
log.error("Could not create symbol directory '{}': {}".format(directory, e))
return None
2016-06-28 20:58:57 +03:00
return directory
def get_path(self, symbol_id):
2016-09-15 19:21:39 +03:00
try:
return self._symbols_path[symbol_id]
2016-09-15 19:21:39 +03:00
except KeyError:
try:
self.list()
return self._symbols_path[symbol_id]
except (OSError, KeyError):
# try to return a symbol with the same name from the classic theme
symbol = self._symbols_path.get(":/symbols/classic/{}".format(os.path.basename(symbol_id)))
if symbol:
return symbol
else:
# return the default computer symbol
2020-10-07 04:18:11 +03:00
log.warning("Could not retrieve symbol '{}', returning default symbol...".format(symbol_id))
return self._symbols_path[":/symbols/classic/computer.svg"]
2016-08-17 12:58:19 +03:00
def get_size(self, symbol_id):
try:
return self._symbol_size_cache[symbol_id]
except KeyError:
with open(self.get_path(symbol_id), "rb") as f:
res = get_size(f.read())
self._symbol_size_cache[symbol_id] = res
return res