├── .gitattributes ├── plugins ├── config.ini ├── icon.png ├── __main__.py ├── requirements.txt ├── plugin.json ├── ConfigHandler │ └── __init__.py ├── FileHandler │ └── __init__.py ├── KiCadImport │ ├── footprint_model_parser.py │ └── __main__.py ├── __init__.py ├── impart_migration.py ├── impart_gui.py ├── single_instance_manager.py ├── impart_easyeda.py ├── kicad_cli │ └── __init__.py ├── KiCadSettingsPaths │ └── __init__.py └── KiCad_Settings │ └── __init__.py ├── doc ├── demo.gif ├── demo.mp4 ├── Screenshot_GUI.png ├── fallback_setup.png ├── 2024-08-17_setting.png ├── kicad_api_settings.png ├── 2024-08-17_Migration.png ├── 2024-08-17_GUI_migrate.png ├── 2025-08_Example_Import.png └── 2024-08-17_Example_Import.png ├── resources ├── icon.png └── icon.svg ├── .vscode ├── settings.json └── launch.json ├── .gitmodules ├── pyrightconfig.json ├── mypy.ini ├── metadata.json ├── .gitignore ├── generate_zip.sh ├── README.md └── LICENSE.txt /.gitattributes: -------------------------------------------------------------------------------- 1 | * text=auto eol=lf 2 | *.sh text eol=lf -------------------------------------------------------------------------------- /plugins/config.ini: -------------------------------------------------------------------------------- 1 | [config] 2 | src_path = 3 | dest_path = 4 | 5 | -------------------------------------------------------------------------------- /doc/demo.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Steffen-W/Import-LIB-KiCad-Plugin/HEAD/doc/demo.gif -------------------------------------------------------------------------------- /doc/demo.mp4: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Steffen-W/Import-LIB-KiCad-Plugin/HEAD/doc/demo.mp4 -------------------------------------------------------------------------------- /plugins/icon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Steffen-W/Import-LIB-KiCad-Plugin/HEAD/plugins/icon.png -------------------------------------------------------------------------------- /resources/icon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Steffen-W/Import-LIB-KiCad-Plugin/HEAD/resources/icon.png -------------------------------------------------------------------------------- /doc/Screenshot_GUI.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Steffen-W/Import-LIB-KiCad-Plugin/HEAD/doc/Screenshot_GUI.png -------------------------------------------------------------------------------- /doc/fallback_setup.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Steffen-W/Import-LIB-KiCad-Plugin/HEAD/doc/fallback_setup.png -------------------------------------------------------------------------------- /doc/2024-08-17_setting.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Steffen-W/Import-LIB-KiCad-Plugin/HEAD/doc/2024-08-17_setting.png -------------------------------------------------------------------------------- /doc/kicad_api_settings.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Steffen-W/Import-LIB-KiCad-Plugin/HEAD/doc/kicad_api_settings.png -------------------------------------------------------------------------------- /doc/2024-08-17_Migration.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Steffen-W/Import-LIB-KiCad-Plugin/HEAD/doc/2024-08-17_Migration.png -------------------------------------------------------------------------------- /doc/2024-08-17_GUI_migrate.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Steffen-W/Import-LIB-KiCad-Plugin/HEAD/doc/2024-08-17_GUI_migrate.png -------------------------------------------------------------------------------- /doc/2025-08_Example_Import.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Steffen-W/Import-LIB-KiCad-Plugin/HEAD/doc/2025-08_Example_Import.png -------------------------------------------------------------------------------- /doc/2024-08-17_Example_Import.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Steffen-W/Import-LIB-KiCad-Plugin/HEAD/doc/2024-08-17_Example_Import.png -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "files.eol": "\n", 3 | // "files.trimTrailingWhitespace": true, 4 | // "files.insertFinalNewline": true 5 | } 6 | -------------------------------------------------------------------------------- /plugins/__main__.py: -------------------------------------------------------------------------------- 1 | from .impart_action import * 2 | 3 | if __name__ == "__main__": 4 | app = wx.App() 5 | frame = wx.Frame(None, title="KiCad Plugin") 6 | frontend = ImpartFrontend() 7 | frontend.ShowModal() 8 | frontend.Destroy() 9 | -------------------------------------------------------------------------------- /.gitmodules: -------------------------------------------------------------------------------- 1 | [submodule "plugins/kiutils"] 2 | path = plugins/kiutils 3 | url = https://github.com/Steffen-W/kiutils.git 4 | [submodule "plugins/easyeda2kicad"] 5 | path = plugins/easyeda2kicad 6 | url = https://github.com/Steffen-W/easyeda2kicad.py.git 7 | -------------------------------------------------------------------------------- /pyrightconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "include": [ 3 | "plugins" 4 | ], 5 | "exclude": [ 6 | "plugins/kiutils", 7 | "plugins/easyeda2kicad", 8 | "**/node_modules", 9 | "**/__pycache__" 10 | ], 11 | "typeCheckingMode": "basic", 12 | "reportMissingImports": false, 13 | "reportMissingTypeStubs": false 14 | } 15 | -------------------------------------------------------------------------------- /.vscode/launch.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": "0.2.0", 3 | "configurations": [ 4 | { 5 | "name": "Debug KiCad Plugin", 6 | "type": "python", 7 | "request": "launch", 8 | "module": "plugins.impart_action", 9 | "cwd": "${workspaceFolder}", 10 | "console": "integratedTerminal" 11 | } 12 | ] 13 | } -------------------------------------------------------------------------------- /plugins/requirements.txt: -------------------------------------------------------------------------------- 1 | # KiCad Plugin Requirements 2 | # Only external pip dependencies needed 3 | 4 | # kicad-python>=0.3.0 5 | # wxPython # GUI 6 | # easyeda2kicad>=0.9.0 7 | # kiutils>=1.4.8 8 | # git+https://github.com/Steffen-W/kiutils@v1.4.9 9 | 10 | # No external dependencies needed - all functionality now uses Python standard library 11 | 12 | # Optional but recommended 13 | typing-extensions 14 | 15 | # Notes: 16 | # - kiutils: Included via git submodule (plugins/kiutils/src/kiutils/) 17 | # - easyeda2kicad: Included via git submodule (plugins/easyeda2kicad/easyeda2kicad/) 18 | # - kicad-python: Usually provided by KiCad 19 | # - wxPython: Provided by KiCad -------------------------------------------------------------------------------- /mypy.ini: -------------------------------------------------------------------------------- 1 | [mypy] 2 | # Add paths for submodule packages so mypy can find easyeda2kicad and kiutils 3 | mypy_path = plugins/easyeda2kicad:plugins/kiutils/src 4 | 5 | # Exclude submodules from type checking (but they remain importable) 6 | exclude = (?x)( 7 | ^plugins/kiutils/.* 8 | | ^plugins/easyeda2kicad/.* 9 | ) 10 | 11 | # Check untyped function bodies 12 | check_untyped_defs = True 13 | 14 | # Ignore missing imports for external libraries without stubs 15 | [mypy-wx.*] 16 | ignore_missing_imports = True 17 | 18 | [mypy-pcbnew.*] 19 | ignore_missing_imports = True 20 | 21 | # Skip checking submodules entirely (don't follow imports into them) 22 | [mypy-kiutils.*] 23 | follow_imports = skip 24 | ignore_errors = True 25 | 26 | [mypy-easyeda2kicad.*] 27 | follow_imports = skip 28 | ignore_errors = True -------------------------------------------------------------------------------- /plugins/plugin.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "https://go.kicad.org/api/schemas/v1", 3 | "identifier": "com.github.Steffen-W.impartGUI", 4 | "name": "impart GUI for KiCad", 5 | "description": "Import library files from Octopart, Samacsys, Ultralibrarian, Snapeda and EasyEDA", 6 | "runtime": { 7 | "type": "python", 8 | "version": "3" 9 | }, 10 | "actions": [ 11 | { 12 | "identifier": "impart_action-action", 13 | "name": "impartGUI (IPC API)", 14 | "description": "impart_action", 15 | "show-button": true, 16 | "scopes": [ 17 | "schematic", 18 | "pcb" 19 | ], 20 | "entrypoint": "impart_action.py", 21 | "icons-light": [ 22 | "icon.png" 23 | ], 24 | "icons-dark": [ 25 | "icon.png" 26 | ] 27 | } 28 | ] 29 | } -------------------------------------------------------------------------------- /metadata.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "https://go.kicad.org/pcm/schemas/v1", 3 | "name": "impart GUI for KiCad", 4 | "description": "Import library files from Octopart, Samacsys, Ultralibrarian, Snapeda and EasyEDA", 5 | "description_full": "Import library files from Octopart, Samacsys, Ultralibrarian, Snapeda and EasyEDA.\n For usage and correct setup please read the Readme: \n https://github.com/Steffen-W/Import-LIB-KiCad-Plugin#use-of-the-application", 6 | "identifier": "com.github.Steffen-W.impartGUI", 7 | "type": "plugin", 8 | "author": { 9 | "name": "Steffen Wittemeier", 10 | "contact": { 11 | "github": "https://github.com/Steffen-W" 12 | } 13 | }, 14 | "maintainer": { 15 | "name": "Steffen Wittemeier", 16 | "contact": { 17 | "github": "https://github.com/Steffen-W" 18 | } 19 | }, 20 | "license": "GPL-3.0", 21 | "resources": { 22 | "homepage": "https://github.com/Steffen-W/Import-LIB-KiCad-Plugin" 23 | }, 24 | "tags": [ 25 | "import", 26 | "library", 27 | "octopart", 28 | "samacsys", 29 | "ultralibrarian", 30 | "snapeda", 31 | "easyeda" 32 | ], 33 | "keep_on_update": [ 34 | ".*/config.ini" 35 | ], 36 | "versions": [ 37 | { 38 | "version": "2025.00.00", 39 | "status": "stable", 40 | "kicad_version": "8.0.4" 41 | } 42 | ] 43 | } -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | Demo 2 | *.zip 3 | test 4 | Video 5 | 6 | # Byte-compiled / optimized / DLL files 7 | __pycache__/ 8 | *.py[cod] 9 | *$py.class 10 | 11 | # C extensions 12 | *.so 13 | 14 | # Distribution / packaging 15 | .Python 16 | build/ 17 | develop-eggs/ 18 | dist/ 19 | downloads/ 20 | eggs/ 21 | .eggs/ 22 | lib/ 23 | lib64/ 24 | parts/ 25 | sdist/ 26 | var/ 27 | wheels/ 28 | pip-wheel-metadata/ 29 | share/python-wheels/ 30 | *.egg-info/ 31 | .installed.cfg 32 | *.egg 33 | MANIFEST 34 | 35 | # PyInstaller 36 | # Usually these files are written by a python script from a template 37 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 38 | *.manifest 39 | *.spec 40 | 41 | # Installer logs 42 | pip-log.txt 43 | pip-delete-this-directory.txt 44 | 45 | # Unit test / coverage reports 46 | htmlcov/ 47 | .tox/ 48 | .nox/ 49 | .coverage 50 | .coverage.* 51 | .cache 52 | nosetests.xml 53 | coverage.xml 54 | *.cover 55 | *.py,cover 56 | .hypothesis/ 57 | .pytest_cache/ 58 | 59 | # Translations 60 | *.mo 61 | *.pot 62 | 63 | # Django stuff: 64 | *.log 65 | local_settings.py 66 | db.sqlite3 67 | db.sqlite3-journal 68 | 69 | # Flask stuff: 70 | instance/ 71 | .webassets-cache 72 | 73 | # Scrapy stuff: 74 | .scrapy 75 | 76 | # Sphinx documentation 77 | docs/_build/ 78 | 79 | # PyBuilder 80 | target/ 81 | 82 | # Jupyter Notebook 83 | .ipynb_checkpoints 84 | 85 | # IPython 86 | profile_default/ 87 | ipython_config.py 88 | 89 | # pyenv 90 | .python-version 91 | 92 | # pipenv 93 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 94 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 95 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 96 | # install all needed dependencies. 97 | #Pipfile.lock 98 | 99 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 100 | __pypackages__/ 101 | 102 | # Celery stuff 103 | celerybeat-schedule 104 | celerybeat.pid 105 | 106 | # SageMath parsed files 107 | *.sage.py 108 | 109 | # Environments 110 | .env 111 | .venv 112 | env/ 113 | venv/ 114 | ENV/ 115 | env.bak/ 116 | venv.bak/ 117 | 118 | # Spyder project settings 119 | .spyderproject 120 | .spyproject 121 | 122 | # Rope project settings 123 | .ropeproject 124 | 125 | # mkdocs documentation 126 | /site 127 | 128 | # mypy 129 | .mypy_cache/ 130 | .dmypy.json 131 | dmypy.json 132 | 133 | # Pyre type checker 134 | .pyre/ 135 | 136 | # Pycharm 137 | .idea/ 138 | -------------------------------------------------------------------------------- /plugins/ConfigHandler/__init__.py: -------------------------------------------------------------------------------- 1 | import configparser 2 | import logging 3 | from pathlib import Path 4 | 5 | 6 | class ConfigHandler: 7 | def __init__(self, config_path): 8 | self.config = configparser.ConfigParser() 9 | self.config_path = config_path 10 | self.config_is_set = False 11 | 12 | self.defaults = { 13 | "SRC_PATH": str(Path.home() / "Downloads"), 14 | "DEST_PATH": str(Path.home() / "KiCad"), 15 | } 16 | 17 | try: 18 | if self.config.read(self.config_path): 19 | if "config" not in self.config: 20 | self.config.add_section("config") 21 | 22 | for key, default_value in self.defaults.items(): 23 | if ( 24 | key not in self.config["config"] 25 | or not self.config["config"][key] 26 | ): 27 | self.config["config"][key] = default_value 28 | 29 | self.config_is_set = True 30 | else: 31 | self._create_default_config() 32 | except Exception as e: 33 | logging.error(f"Error when reading in the configuration: {e}") 34 | self._create_default_config() 35 | 36 | if not self.config_is_set: 37 | self.save_config() 38 | 39 | def _create_default_config(self): 40 | self.config = configparser.ConfigParser() 41 | self.config.add_section("config") 42 | 43 | for key, value in self.defaults.items(): 44 | self.config["config"][key] = value 45 | 46 | self.config_is_set = False 47 | 48 | def get_SRC_PATH(self): 49 | return self.config["config"]["SRC_PATH"] 50 | 51 | def set_SRC_PATH(self, var): 52 | self.config["config"]["SRC_PATH"] = var 53 | self.save_config() 54 | 55 | def get_DEST_PATH(self): 56 | return self.config["config"]["DEST_PATH"] 57 | 58 | def set_DEST_PATH(self, var): 59 | self.config["config"]["DEST_PATH"] = var 60 | self.save_config() 61 | 62 | def get_value(self, key, section="config"): 63 | try: 64 | return self.config[section][key] 65 | except KeyError: 66 | return None 67 | 68 | def set_value(self, key, value, section="config"): 69 | if section not in self.config: 70 | self.config.add_section(section) 71 | 72 | self.config[section][key] = value 73 | self.save_config() 74 | 75 | def save_config(self): 76 | try: 77 | with open(self.config_path, "w") as configfile: 78 | self.config.write(configfile) 79 | except Exception as e: 80 | logging.error(f"Error saving the configuration: {e}") 81 | -------------------------------------------------------------------------------- /plugins/FileHandler/__init__.py: -------------------------------------------------------------------------------- 1 | import logging 2 | from pathlib import Path 3 | from typing import List, Optional 4 | 5 | 6 | class FileHandler: 7 | """Monitors a directory for new ZIP files within a specific size range.""" 8 | 9 | def __init__( 10 | self, 11 | path: str, 12 | min_size: int = 1_000, # 1 KB 13 | max_size: int = 50_000_000, # 50 MB 14 | file_extension: str = ".zip", 15 | ): 16 | """ 17 | Initializes the FileHandler. 18 | 19 | Args: 20 | path: Path to the directory to monitor 21 | min_size: Minimum file size in bytes 22 | max_size: Maximum file size in bytes 23 | file_extension: File extension to monitor 24 | """ 25 | self.min_size = min_size 26 | self.max_size = max_size 27 | self.file_extension = file_extension 28 | self.path = "" 29 | self.known_files: set[str] = set() # Set is more efficient for membership checks 30 | self.logger = logging.getLogger(__name__) 31 | 32 | self.change_path(path) 33 | 34 | def change_path(self, new_path: str) -> None: 35 | """ 36 | Changes the directory to monitor. 37 | 38 | Args: 39 | new_path: New directory path 40 | """ 41 | path_obj = Path(new_path) 42 | 43 | if not path_obj.is_dir(): 44 | self.logger.warning( 45 | f"Path '{new_path}' is not a directory. Using current directory." 46 | ) 47 | new_path = "." 48 | path_obj = Path(new_path) 49 | 50 | if new_path != self.path: 51 | self.path = new_path 52 | self.known_files = set() # Reset known files 53 | self.logger.info(f"Changed directory to '{new_path}'") 54 | 55 | def get_new_files(self, path: Optional[str] = None) -> List[str]: 56 | """ 57 | Finds new files in the specified directory. 58 | 59 | Args: 60 | path: Optional - directory to monitor, 61 | if different from the current one 62 | 63 | Returns: 64 | List of full paths to new files 65 | """ 66 | if path is not None and path != self.path: 67 | self.change_path(path) 68 | 69 | try: 70 | # Use pathlib for better path handling 71 | directory = Path(self.path) 72 | files = [f for f in directory.iterdir() if f.is_file()] 73 | 74 | new_files = [] 75 | 76 | for file_path in sorted(files): 77 | # Check if it's a new file with the correct extension 78 | if file_path.name not in self.known_files and file_path.name.endswith( 79 | self.file_extension 80 | ): 81 | 82 | # Check if the file size is within the allowed range 83 | file_size = file_path.stat().st_size 84 | if self.min_size <= file_size <= self.max_size: 85 | new_files.append(str(file_path.absolute())) 86 | self.known_files.add(file_path.name) 87 | else: 88 | self.logger.debug( 89 | f"File '{file_path.name}' is outside the size range " 90 | f"({file_size} bytes)" 91 | ) 92 | 93 | return new_files 94 | 95 | except (PermissionError, FileNotFoundError) as e: 96 | self.logger.error(f"Error reading directory: {e}") 97 | return [] 98 | -------------------------------------------------------------------------------- /generate_zip.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | # Clean up old ZIP 4 | rm -f Import-LIB-KiCad-Plugin.zip 5 | 6 | # Update metadata version 7 | mv metadata.json metadata_.json 8 | jq --arg today "$(date +%Y.%m.%d)" '.versions[0].version |= $today' metadata_.json > metadata.json 9 | 10 | # Create temporary directory for clean packaging 11 | temp_dir=$(mktemp -d) 12 | build_dir="$temp_dir/build" 13 | mkdir -p "$build_dir" 14 | 15 | echo "Preparing clean package structure..." 16 | 17 | # Copy metadata and resources 18 | cp metadata.json "$build_dir/" 19 | cp -r resources "$build_dir/" 20 | 21 | # Copy plugins directory structure but exclude submodule bloat 22 | mkdir -p "$build_dir/plugins" 23 | 24 | # Copy main plugin files 25 | find plugins -maxdepth 1 -type f \( -name "*.py" -o -name "*.json" -o -name "*.txt" -o -name "*.ini" -o -name "*.png" \) \ 26 | -exec cp {} "$build_dir/plugins/" \; 27 | 28 | # Copy plugin subdirectories (excluding submodules) 29 | for dir in plugins/*/; do 30 | dirname=$(basename "$dir") 31 | 32 | # Skip submodules - we'll handle them specially 33 | if [[ "$dirname" == "easyeda2kicad" || "$dirname" == "kiutils" ]]; then 34 | continue 35 | fi 36 | 37 | # Copy regular plugin directories 38 | if [[ -d "$dir" ]]; then 39 | cp -r "$dir" "$build_dir/plugins/" 40 | fi 41 | done 42 | 43 | # Copy only needed parts from submodules 44 | echo "Copying essential parts from submodules..." 45 | 46 | # Keep kiutils in its original structure for easier development 47 | if [[ -d "plugins/kiutils/src/kiutils" ]]; then 48 | mkdir -p "$build_dir/plugins/kiutils/src" 49 | cp -r plugins/kiutils/src/kiutils "$build_dir/plugins/kiutils/src/" 50 | echo " ✓ Copied kiutils (keeping src/kiutils structure)" 51 | else 52 | echo " ⚠ kiutils/src/kiutils not found" 53 | fi 54 | 55 | # Keep easyeda2kicad in its original structure for easier development 56 | if [[ -d "plugins/easyeda2kicad/easyeda2kicad" ]]; then 57 | mkdir -p "$build_dir/plugins/easyeda2kicad" 58 | cp -r plugins/easyeda2kicad/easyeda2kicad "$build_dir/plugins/easyeda2kicad/" 59 | echo " ✓ Copied easyeda2kicad (keeping easyeda2kicad structure)" 60 | else 61 | echo " ⚠ easyeda2kicad/easyeda2kicad not found" 62 | fi 63 | 64 | # Copy kicad_advanced if it's a file/script 65 | if [[ -f "plugins/kicad_advanced" ]]; then 66 | cp plugins/kicad_advanced "$build_dir/plugins/" 67 | fi 68 | 69 | # Clean up unwanted files from the build 70 | echo "Cleaning up unwanted files..." 71 | find "$build_dir" -name "__pycache__" -type d -exec rm -rf {} + 2>/dev/null 72 | find "$build_dir" -name "*.pyc" -delete 2>/dev/null 73 | find "$build_dir" -name "*.log" -delete 2>/dev/null 74 | find "$build_dir" -name "*.fbp" -delete 2>/dev/null 75 | find "$build_dir" -name "*.svg" -delete 2>/dev/null 76 | 77 | # Create ZIP from clean build directory 78 | echo "Creating ZIP file..." 79 | zip_target="$(pwd)/Import-LIB-KiCad-Plugin.zip" 80 | cd "$build_dir" 81 | zip -r "$zip_target" . -x "*.pyc" "*/__pycache__/*" 82 | cd - > /dev/null 83 | 84 | # Restore original metadata 85 | mv metadata_.json metadata.json 86 | 87 | # Cleanup temp directory 88 | rm -rf "$temp_dir" 89 | 90 | 91 | # Show what's included 92 | echo "" 93 | echo "Package contents:" 94 | if [[ -f "Import-LIB-KiCad-Plugin.zip" ]]; then 95 | unzip -l Import-LIB-KiCad-Plugin.zip 96 | echo "..." 97 | total_files=$(unzip -l Import-LIB-KiCad-Plugin.zip | tail -1 | awk '{print $2}') 98 | echo "Total files: $total_files" 99 | 100 | # Show ZIP size 101 | zip_size=$(ls -lh Import-LIB-KiCad-Plugin.zip | awk '{print $5}') 102 | echo "ZIP size: $zip_size" 103 | else 104 | echo "Error: ZIP file not found after creation" 105 | echo "Debug: Looking for files in current directory:" 106 | ls -la *.zip 2>/dev/null || echo "No ZIP files found" 107 | fi 108 | 109 | echo "ZIP file created: $(realpath Import-LIB-KiCad-Plugin.zip)" -------------------------------------------------------------------------------- /resources/icon.svg: -------------------------------------------------------------------------------- 1 | 2 | 147 | -------------------------------------------------------------------------------- /plugins/KiCadImport/footprint_model_parser.py: -------------------------------------------------------------------------------- 1 | import re 2 | from pathlib import Path 3 | from typing import Optional 4 | 5 | 6 | class FootprintModelParser: 7 | """Simple and reliable parser for KiCad footprint model paths with validation.""" 8 | 9 | def validate_footprint_content(self, content: str) -> bool: 10 | """Check if content is a valid footprint file.""" 11 | if not content.strip(): 12 | return False 13 | 14 | # Check for both old (module) and new (footprint) format 15 | return re.search(r"\((module|footprint)\s+", content) is not None 16 | 17 | def extract_footprint_name(self, content: str) -> Optional[str]: 18 | """Extract footprint name from content and clean it.""" 19 | if not self.validate_footprint_content(content): 20 | return None 21 | 22 | # Extract module/footprint name - support both formats 23 | match = re.search(r'\((module|footprint)\s+"([^"]*)"', content) 24 | if match: 25 | name = match.group(2) # group(1) is module/footprint, group(2) is the name 26 | if name.strip(): 27 | return self.clean_name(name) 28 | 29 | return None 30 | 31 | def clean_name(self, name: str) -> str: 32 | """Clean footprint name by removing invalid characters.""" 33 | invalid = '<>:"/\\|?* ' 34 | name = name.strip() 35 | for char in invalid: 36 | name = name.replace(char, "_") 37 | return name 38 | 39 | def extract_model_info(self, footprint_content: str) -> Optional[str]: 40 | """Extract model filename from footprint content.""" 41 | match = re.search(r'\(model\s+"([^"]*)"', footprint_content) 42 | if match: 43 | model_path = match.group(1) 44 | return Path(model_path).name 45 | return None 46 | 47 | def has_model(self, footprint_content: str) -> bool: 48 | """Check if footprint has a model defined.""" 49 | return re.search(r'\(model\s+"[^"]*"', footprint_content) is not None 50 | 51 | def update_model_path(self, footprint_content: str, new_model_path: str) -> str: 52 | """Simply replace the model path, leave everything else untouched.""" 53 | pattern = re.compile(r'(\(model\s+)"[^"]*"') 54 | 55 | def replace_path(match): 56 | return f'{match.group(1)}"{new_model_path}"' 57 | 58 | return pattern.sub(replace_path, footprint_content) 59 | 60 | def add_model(self, footprint_content: str, model_path: str) -> str: 61 | """Add model block before the last closing parenthesis.""" 62 | model_block = f'\t(model "{model_path}"\n\t\t(offset\n\t\t\t(xyz 0 0 0)\n\t\t)\n\t\t(scale\n\t\t\t(xyz 1 1 1)\n\t\t)\n\t\t(rotate\n\t\t\t(xyz 0 0 0)\n\t\t)\n\t)' 63 | 64 | # Find last closing parenthesis 65 | content = footprint_content.rstrip() 66 | if content.endswith(")"): 67 | return content[:-1] + f"\n{model_block}\n)" 68 | else: 69 | return footprint_content + f"\n{model_block}" 70 | 71 | def update_or_add_model(self, footprint_content: str, model_path: str) -> str: 72 | """Update existing model path or add new model to footprint.""" 73 | if self.has_model(footprint_content): 74 | return self.update_model_path(footprint_content, model_path) 75 | else: 76 | return self.add_model(footprint_content, model_path) 77 | 78 | 79 | if __name__ == "__main__": 80 | parser = FootprintModelParser() 81 | 82 | # Test validation 83 | valid_content = """(footprint "Test" (layer F.Cu) 84 | (pad 1 smd rect (at 0 0) (size 1 1) (layers F.Cu F.Paste F.Mask)) 85 | )""" 86 | 87 | invalid_content = """This is not a footprint file""" 88 | 89 | print("=== Test: Validation ===") 90 | print(f"Valid content: {parser.validate_footprint_content(valid_content)}") 91 | print(f"Invalid content: {parser.validate_footprint_content(invalid_content)}") 92 | print(f"Extract name: {parser.extract_footprint_name(valid_content)}") 93 | 94 | # Test with existing model 95 | content_with_model = """(footprint "Test" (layer F.Cu) 96 | (pad 1 smd rect (at 0 0) (size 1 1) (layers F.Cu F.Paste F.Mask)) 97 | (model "${KICAD_3RD_PARTY}/old.3dshapes/old_model.step" 98 | (offset 99 | (xyz 0 0 0) 100 | ) 101 | (scale 102 | (xyz 1 1 1) 103 | ) 104 | (rotate 105 | (xyz 0 0 0) 106 | ) 107 | ) 108 | )""" 109 | 110 | print("\n=== Test: Update existing model path ===") 111 | new_path = "${KICAD_3RD_PARTY}/Samacsys.3dshapes/new_model.step" 112 | result = parser.update_or_add_model(content_with_model, new_path) 113 | print(result) 114 | -------------------------------------------------------------------------------- /plugins/KiCadImport/__main__.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # coding: utf-8 3 | 4 | # Assembles local KiCad component libraries from downloaded Octopart, 5 | # Samacsys, Ultralibrarian and Snapeda zipfiles using kiutils. 6 | # Supports KiCad 7.0 and newer. 7 | 8 | import logging 9 | from pathlib import Path 10 | 11 | from .__init__ import * 12 | 13 | logger = logging.getLogger(__name__) 14 | 15 | if __name__ == "__main__": 16 | import argparse 17 | 18 | logging.basicConfig(level=logging.ERROR) 19 | 20 | # Example: python plugins/KiCadImport.py --lib-folder import_test --download-folder Demo/libs 21 | 22 | parser = argparse.ArgumentParser( 23 | description="Import KiCad libraries from a file or folder." 24 | ) 25 | 26 | # Create mutually exclusive arguments for file or folder 27 | group = parser.add_mutually_exclusive_group(required=True) 28 | group.add_argument( 29 | "--download-folder", 30 | help="Path to the folder with the zip files to be imported.", 31 | ) 32 | group.add_argument("--download-file", help="Path to the zip file to import.") 33 | 34 | group.add_argument("--easyeda", help="Import easyeda part. example: C2040") 35 | 36 | parser.add_argument( 37 | "--lib-folder", 38 | required=True, 39 | help="Destination folder for the imported KiCad files.", 40 | ) 41 | 42 | parser.add_argument( 43 | "--overwrite-if-exists", 44 | action="store_true", 45 | help="Overwrite existing files if they already exist", 46 | ) 47 | 48 | parser.add_argument( 49 | "--path-variable", 50 | help="Example: if only project-specific '${KIPRJMOD}' standard is '${KICAD_3RD_PARTY}'", 51 | ) 52 | 53 | args = parser.parse_args() 54 | 55 | lib_folder = Path(args.lib_folder) 56 | 57 | if args.path_variable: 58 | path_variable = str(args.path_variable).strip() 59 | else: 60 | path_variable = "${KICAD_3RD_PARTY}" 61 | 62 | if args.download_file: 63 | main( 64 | lib_file=args.download_file, 65 | lib_folder=args.lib_folder, 66 | overwrite=args.overwrite_if_exists, 67 | KICAD_3RD_PARTY_LINK=path_variable, 68 | ) 69 | elif args.download_folder: 70 | download_folder = Path(args.download_folder) 71 | logger.info(f"Processing folder: {download_folder}") 72 | if not download_folder.is_dir(): 73 | logger.error(f"Source folder {download_folder} does not exist") 74 | print(f"Error Source folder {download_folder} does not exist!") 75 | elif not lib_folder.is_dir(): 76 | logger.error(f"Destination folder {lib_folder} does not exist") 77 | print(f"Error destination folder {lib_folder} does not exist!") 78 | else: 79 | zip_files = list(download_folder.glob("*.zip")) 80 | logger.info(f"Found {len(zip_files)} zip files to process") 81 | for zip_file in zip_files: 82 | if ( 83 | zip_file.is_file() and zip_file.stat().st_size >= 1024 84 | ): # Check if it's a file and at least 1 KB 85 | main( 86 | lib_file=zip_file, 87 | lib_folder=args.lib_folder, 88 | overwrite=args.overwrite_if_exists, 89 | KICAD_3RD_PARTY_LINK=path_variable, 90 | ) 91 | else: 92 | logger.warning(f"Skipping {zip_file}: too small or not a file") 93 | elif args.easyeda: 94 | logger.info(f"Processing EasyEDA component: {args.easyeda}") 95 | if not lib_folder.is_dir(): 96 | logger.error(f"Destination folder {lib_folder} does not exist") 97 | print(f"Error destination folder {lib_folder} does not exist!") 98 | else: 99 | component_id = str(args.easyeda).strip() 100 | print("Try to import EasyEDA / LCSC Part# : ", component_id) 101 | from impart_easyeda import EasyEDAImporter, ImportConfig 102 | 103 | try: 104 | config = ImportConfig( 105 | base_folder=lib_folder, 106 | lib_name="EasyEDA", 107 | overwrite=args.overwrite_if_exists, 108 | lib_var=path_variable, 109 | ) 110 | 111 | logger.debug(f"EasyEDA config: {config}") 112 | paths = EasyEDAImporter(config).import_component(component_id) 113 | logger.info(f"EasyEDA import completed for {component_id}") 114 | 115 | # Print results 116 | if paths.symbol_lib: 117 | print(f"Library path : {paths.symbol_lib}") 118 | if paths.footprint_file: 119 | print(f"Footprint path: {paths.footprint_file}") 120 | if paths.model_wrl: 121 | print(f"3D model path (wrl): {paths.model_wrl}") 122 | if paths.model_step: 123 | print(f"3D model path (step): {paths.model_step}") 124 | 125 | except Exception as e: 126 | logger.error(f"EasyEDA import failed for {component_id}: {e}") 127 | print(f"Error importing component: {e}") 128 | -------------------------------------------------------------------------------- /plugins/__init__.py: -------------------------------------------------------------------------------- 1 | import logging 2 | import platform 3 | import sys 4 | from pathlib import Path 5 | from typing import Optional 6 | 7 | import pcbnew 8 | 9 | try: 10 | import wx 11 | except ImportError: 12 | print("Error: wx not available - plugin cannot run without wxPython") 13 | sys.exit(1) 14 | 15 | plugin_dir = Path(__file__).resolve().parent 16 | log_file = plugin_dir / "plugin_fallback.log" 17 | 18 | # Initialize logger immediately - it will be configured later in setup_logging() 19 | logger = logging.getLogger("impart_plugin") 20 | log_handler: Optional[logging.FileHandler] = None 21 | 22 | 23 | def setup_logging(): 24 | """Setup logging for the plugin""" 25 | global logger, log_handler 26 | 27 | try: 28 | log_file.parent.mkdir(parents=True, exist_ok=True) 29 | 30 | logger = logging.getLogger("impart_plugin") 31 | logger.setLevel(logging.DEBUG) 32 | 33 | for handler in logger.handlers[:]: 34 | handler.close() 35 | logger.removeHandler(handler) 36 | 37 | log_handler = logging.FileHandler( 38 | str(log_file), mode="w", encoding="utf-8", delay=False 39 | ) 40 | 41 | formatter = logging.Formatter( 42 | "%(asctime)s %(levelname)s [%(name)s:%(filename)s:%(lineno)d]: %(message)s" 43 | ) 44 | log_handler.setFormatter(formatter) 45 | logger.addHandler(log_handler) 46 | 47 | logger.info(f"Plugin initialization started on {platform.system()}") 48 | logger.info(f"Python executable: {sys.executable}") 49 | logger.info(f"Python version: {sys.version}") 50 | logger.info(f"Plugin directory: {plugin_dir}") 51 | 52 | return True 53 | 54 | except Exception as e: 55 | print(f"Logging setup failed: {e}") 56 | return False 57 | 58 | 59 | def cleanup_logging(): 60 | """Clean up logging resources""" 61 | try: 62 | if log_handler: 63 | log_handler.close() 64 | if logger: 65 | logger.removeHandler(log_handler) 66 | 67 | import gc 68 | 69 | gc.collect() 70 | 71 | except Exception as e: 72 | print(f"Logging cleanup failed: {e}") 73 | 74 | 75 | def setup_submodule_paths(): 76 | """Set up Python paths for git submodules""" 77 | try: 78 | # Add kiutils submodule path 79 | kiutils_path = plugin_dir / "kiutils" / "src" 80 | if kiutils_path.exists(): 81 | kiutils_str = str(kiutils_path) 82 | if kiutils_str not in sys.path: 83 | sys.path.insert(0, kiutils_str) 84 | logger.info(f"✓ Added kiutils to sys.path: {kiutils_str}") 85 | 86 | # Add easyeda2kicad submodule path 87 | easyeda2kicad_path = plugin_dir / "easyeda2kicad" 88 | if easyeda2kicad_path.exists(): 89 | easyeda2kicad_str = str(easyeda2kicad_path) 90 | if easyeda2kicad_str not in sys.path: 91 | sys.path.insert(0, easyeda2kicad_str) 92 | logger.info(f"✓ Added easyeda2kicad to sys.path: {easyeda2kicad_str}") 93 | 94 | # Add plugin directory itself 95 | plugin_dir_str = str(plugin_dir) 96 | if plugin_dir_str not in sys.path: 97 | sys.path.insert(0, plugin_dir_str) 98 | logger.info(f"✓ Added plugin directory to sys.path: {plugin_dir_str}") 99 | 100 | logger.info("✓ All submodule paths configured successfully") 101 | return True 102 | 103 | except Exception as e: 104 | logger.error(f"Failed to setup submodule paths: {e}") 105 | return False 106 | 107 | 108 | def show_error_dialog(title, message): 109 | """Show error dialog with fallback to console""" 110 | try: 111 | app = wx.App() if not wx.GetApp() else None 112 | wx.MessageBox(message, title, wx.OK | wx.ICON_ERROR) 113 | if app: 114 | app.Destroy() 115 | except Exception: 116 | print(f"Error: {title} - {message}") 117 | 118 | 119 | class ActionImpartPlugin(pcbnew.ActionPlugin): 120 | """KiCad Action Plugin for library import using git submodules.""" 121 | 122 | def defaults(self): 123 | self.name = "impartGUI (fallback pcbnew)" 124 | self.category = "Import library files" 125 | self.description = "Import library files from Octopart, Samacsys, Ultralibrarian, Snapeda and EasyEDA" 126 | self.show_toolbar_button = True 127 | 128 | icon_path = plugin_dir / "icon.png" 129 | self.icon_file_name = str(icon_path) 130 | self.dark_icon_file_name = str(icon_path) 131 | 132 | def Run(self): 133 | """Run the plugin with git submodules.""" 134 | try: 135 | setup_logging() 136 | logger.info("Plugin started") 137 | 138 | # Set up paths for git submodules (no venv needed) 139 | if not setup_submodule_paths(): 140 | error_msg = ( 141 | "Failed to set up submodule paths.\n\n" 142 | f"Check log file for details: {log_file}\n\n" 143 | "Ensure git submodules are properly initialized:\n" 144 | "git submodule update --init --recursive" 145 | ) 146 | show_error_dialog("Submodule Setup Error", error_msg) 147 | return 148 | 149 | # Start plugin frontend directly 150 | self._start_plugin_frontend() 151 | 152 | except Exception as e: 153 | logger.exception("Plugin error occurred") 154 | 155 | detailed_msg = ( 156 | f"Plugin Error Details:\n\n" 157 | f"Error: {str(e)}\n" 158 | f"Type: {type(e).__name__}\n\n" 159 | f"Check log file for full details:\n{log_file}\n\n" 160 | ) 161 | 162 | show_error_dialog("Plugin Error", detailed_msg) 163 | 164 | finally: 165 | cleanup_logging() 166 | 167 | def _start_plugin_frontend(self): 168 | """Start the main plugin frontend""" 169 | try: 170 | logger.info("Starting plugin frontend") 171 | 172 | from .impart_action import ImpartFrontend 173 | 174 | frontend = ImpartFrontend(fallback_mode=True) 175 | frontend.ShowModal() 176 | frontend.Destroy() 177 | 178 | logger.info("Plugin stopped") 179 | 180 | except Exception as e: 181 | logger.exception("Frontend error occurred") 182 | 183 | error_msg = ( 184 | f"Frontend Error:\n\n" 185 | f"Error: {str(e)}\n\n" 186 | f"Check log file for details: {log_file}" 187 | ) 188 | 189 | show_error_dialog("Frontend Error", error_msg) 190 | 191 | 192 | ActionImpartPlugin().register() 193 | -------------------------------------------------------------------------------- /plugins/impart_migration.py: -------------------------------------------------------------------------------- 1 | import logging 2 | from pathlib import Path 3 | from typing import Optional, Union 4 | 5 | logger = logging.getLogger(__name__) 6 | 7 | try: 8 | from .kicad_cli import kicad_cli as KicadCli 9 | except ImportError: 10 | from kicad_cli import kicad_cli as KicadCli # type: ignore[import-not-found,no-redef] 11 | 12 | try: 13 | cli: Optional[KicadCli] = KicadCli() 14 | logger.info("✓ kicad_cli initialized successfully") 15 | except Exception as e: 16 | logger.error(f"Failed to initialize kicad_cli: {e}") 17 | cli = None 18 | 19 | 20 | def find_old_lib_files( 21 | folder_path: Union[str, Path], 22 | libs: list[str] = ["Octopart", "Samacsys", "UltraLibrarian", "Snapeda", "EasyEDA"], 23 | ) -> dict[str, dict[str, Path]]: 24 | 25 | folder_path = Path(folder_path).expanduser() 26 | found_files: dict[str, dict[str, Path]] = {} 27 | 28 | if not folder_path.exists(): 29 | return found_files 30 | 31 | for file in folder_path.iterdir(): 32 | if not file.is_file(): 33 | continue 34 | 35 | if not (file.name.endswith(".lib") or file.name.endswith(".kicad_sym")): 36 | continue 37 | 38 | for lib in libs: 39 | if file.name.startswith(lib): 40 | 41 | entry: dict[str, Path] 42 | if lib in found_files: 43 | entry = found_files[lib] 44 | else: 45 | entry = {} 46 | 47 | # Check whether the file ends with ".lib" 48 | if file.name.endswith(".lib"): 49 | entry["old_lib"] = file 50 | 51 | blk_file = file.with_suffix(".lib.blk") 52 | if blk_file.exists() and blk_file.is_file(): 53 | entry["old_lib_blk"] = blk_file # backup file 54 | 55 | dcm_file = file.with_suffix(".dcm") 56 | if dcm_file.exists() and dcm_file.is_file(): 57 | entry["old_lib_dcm"] = dcm_file # description file 58 | 59 | # Check whether the file with the old kicad v6 name exists 60 | elif file.name.endswith("_kicad_sym.kicad_sym"): 61 | entry["oldV6"] = file 62 | 63 | dcm_file = file.with_suffix(".dcm") 64 | if dcm_file.exists() and dcm_file.is_file(): 65 | entry["oldV6_dcm"] = dcm_file # description file 66 | 67 | blk_file = file.with_suffix(".kicad_sym.blk") 68 | if blk_file.exists() and blk_file.is_file(): 69 | entry["oldV6_blk"] = blk_file # backup file 70 | 71 | # Check whether the file with the normal ".kicad_sym" extension exists 72 | elif file.name.endswith(".kicad_sym"): 73 | entry["V6"] = file 74 | 75 | dcm_file = file.with_suffix(".dcm") 76 | if dcm_file.exists() and dcm_file.is_file(): 77 | entry["V6_dcm"] = dcm_file # description file 78 | 79 | blk_file = file.with_suffix(".kicad_sym.blk") 80 | if blk_file.exists() and blk_file.is_file(): 81 | entry["V6_blk"] = blk_file # backup file 82 | 83 | kicad_sym_file = file.with_name(lib + "_old_lib.kicad_sym") 84 | if kicad_sym_file.exists() and kicad_sym_file.is_file(): 85 | # Possible conversion name 86 | entry["old_lib_kicad_sym"] = kicad_sym_file 87 | 88 | if entry: 89 | found_files[lib] = entry 90 | return found_files 91 | 92 | 93 | def convert_lib(SRC: Path, DES: Path, drymode=True): 94 | 95 | BLK_file = SRC.with_suffix(SRC.suffix + ".blk") # Backup 96 | 97 | msg = [] 98 | 99 | if drymode: 100 | msg.append([SRC.name, DES.name]) 101 | msg.append([SRC.name, BLK_file.name]) 102 | 103 | else: 104 | 105 | SRC_dcm = SRC.with_suffix(".dcm") 106 | DES_dcm = DES.with_suffix(".dcm") 107 | if DES_dcm.exists() and DES_dcm.is_file(): 108 | return [] 109 | 110 | if cli is None or not cli.exists(): 111 | logger.error("kicad_cli not available for conversion") 112 | return [] 113 | 114 | result = cli.upgrade_sym_lib(str(SRC), str(DES)) 115 | if not result.success: 116 | logger.error( 117 | f"Converting {SRC.name} to {DES.name} failed: {result.message}" 118 | ) 119 | if result.stderr: 120 | logger.error(f"Conversion error details: {result.stderr}") 121 | return [] 122 | else: 123 | logger.info( 124 | f"Successfully converted {SRC.name} to {DES.name}: {result.message}" 125 | ) 126 | msg.append([SRC.stem, DES.stem]) 127 | 128 | if SRC_dcm.exists() and SRC_dcm.is_file(): 129 | SRC_dcm.rename(DES_dcm) 130 | 131 | SRC.rename(BLK_file) 132 | msg.append([SRC.name, BLK_file.name]) 133 | 134 | return msg 135 | 136 | 137 | def convert_lib_list(libs_dict, drymode=True): 138 | 139 | if cli is None or not cli.exists(): 140 | logger.error("kicad_cli not found! Conversion is not possible.") 141 | drymode = True 142 | 143 | convertlist = [] 144 | for lib, paths in libs_dict.items(): 145 | 146 | # if "V6" in paths: 147 | # print(f"No conversion needed for {lib}.") 148 | 149 | if "old_lib" in paths: 150 | file = paths["old_lib"] 151 | if "V6" in paths or "oldV6" in paths: 152 | if "old_lib_kicad_sym" in paths: 153 | logger.error(f"{lib} old_lib_kicad_sym already exists") 154 | else: 155 | kicad_sym_file = file.with_name(file.stem + "_old_lib.kicad_sym") 156 | res = convert_lib(SRC=file, DES=kicad_sym_file, drymode=drymode) 157 | convertlist.extend(res) 158 | else: 159 | name_V6 = file.with_name(lib + ".kicad_sym") 160 | res = convert_lib(SRC=file, DES=name_V6, drymode=drymode) 161 | convertlist.extend(res) 162 | 163 | if "oldV6" in paths: 164 | file = paths["oldV6"] 165 | if "V6" in paths: 166 | logger.error(f"{lib} V6 already exists") 167 | else: 168 | name_V6 = file.with_name(lib + ".kicad_sym") 169 | res = convert_lib(SRC=file, DES=name_V6, drymode=drymode) 170 | convertlist.extend(res) 171 | return convertlist 172 | 173 | 174 | if __name__ == "__main__": 175 | from pprint import pprint 176 | 177 | logging.basicConfig(level=logging.INFO) 178 | 179 | path = "~/KiCad" 180 | ret = find_old_lib_files(folder_path=path) 181 | if ret: 182 | print("#######################") 183 | pprint(ret) 184 | print("#######################") 185 | 186 | conv = convert_lib_list(ret, drymode=True) 187 | if conv: 188 | print("#######################") 189 | pprint(conv) 190 | print("#######################") 191 | -------------------------------------------------------------------------------- /plugins/impart_gui.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | ########################################################################### 4 | ## Python code generated with wxFormBuilder (version 4.2.1-0-g80c4cb6) 5 | ## http://www.wxformbuilder.org/ 6 | ## 7 | ## PLEASE DO *NOT* EDIT THIS FILE! 8 | ########################################################################### 9 | 10 | import wx 11 | import wx.adv 12 | 13 | ########################################################################### 14 | ## Class impartGUI 15 | ########################################################################### 16 | 17 | 18 | class impartGUI(wx.Dialog): 19 | 20 | def __init__(self, parent): 21 | wx.Dialog.__init__( 22 | self, 23 | parent, 24 | id=wx.ID_ANY, 25 | title="impartGUI", 26 | pos=wx.DefaultPosition, 27 | size=wx.Size(650, 650), 28 | style=wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER | wx.BORDER_DEFAULT, 29 | ) 30 | 31 | self.SetSizeHints(wx.DefaultSize, wx.DefaultSize) 32 | self.SetBackgroundColour(wx.SystemSettings.GetColour(wx.SYS_COLOUR_WINDOW)) 33 | 34 | bSizer = wx.BoxSizer(wx.VERTICAL) 35 | 36 | self.m_button_migrate = wx.Button( 37 | self, 38 | wx.ID_ANY, 39 | "migrate the libraries (highly recommended)", 40 | wx.DefaultPosition, 41 | wx.DefaultSize, 42 | 0, 43 | ) 44 | self.m_button_migrate.SetFont( 45 | wx.Font( 46 | 15, 47 | wx.FONTFAMILY_DEFAULT, 48 | wx.FONTSTYLE_NORMAL, 49 | wx.FONTWEIGHT_NORMAL, 50 | False, 51 | wx.EmptyString, 52 | ) 53 | ) 54 | self.m_button_migrate.Hide() 55 | self.m_button_migrate.SetMaxSize(wx.Size(-1, 150)) 56 | 57 | bSizer.Add(self.m_button_migrate, 1, wx.ALL | wx.EXPAND, 5) 58 | 59 | self.m_button = wx.Button( 60 | self, wx.ID_ANY, "Start", wx.DefaultPosition, wx.DefaultSize, 0 61 | ) 62 | bSizer.Add(self.m_button, 0, wx.ALL | wx.EXPAND, 5) 63 | 64 | self.m_text = wx.TextCtrl( 65 | self, 66 | wx.ID_ANY, 67 | wx.EmptyString, 68 | wx.DefaultPosition, 69 | wx.DefaultSize, 70 | wx.TE_BESTWRAP | wx.TE_MULTILINE, 71 | ) 72 | bSizer.Add(self.m_text, 1, wx.ALL | wx.EXPAND, 5) 73 | 74 | self.m_staticline11 = wx.StaticLine( 75 | self, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize, wx.LI_HORIZONTAL 76 | ) 77 | self.m_staticline11.SetForegroundColour( 78 | wx.SystemSettings.GetColour(wx.SYS_COLOUR_WINDOW) 79 | ) 80 | self.m_staticline11.SetBackgroundColour( 81 | wx.SystemSettings.GetColour(wx.SYS_COLOUR_GRAYTEXT) 82 | ) 83 | self.m_staticline11.Hide() 84 | 85 | bSizer.Add(self.m_staticline11, 0, wx.EXPAND | wx.ALL, 5) 86 | 87 | fgSizer2 = wx.FlexGridSizer(0, 3, 0, 0) 88 | fgSizer2.SetFlexibleDirection(wx.HORIZONTAL) 89 | fgSizer2.SetNonFlexibleGrowMode(wx.FLEX_GROWMODE_ALL) 90 | 91 | self.m_buttonImportManual = wx.Button( 92 | self, wx.ID_ANY, "Manual Import", wx.DefaultPosition, wx.DefaultSize, 0 93 | ) 94 | fgSizer2.Add(self.m_buttonImportManual, 0, wx.ALL, 5) 95 | 96 | m_choice1Choices = ["EeasyEDA / LCSC Part#"] 97 | self.m_choice1 = wx.Choice( 98 | self, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize, m_choice1Choices, 0 99 | ) 100 | self.m_choice1.SetSelection(0) 101 | fgSizer2.Add(self.m_choice1, 0, wx.ALL | wx.EXPAND, 5) 102 | 103 | self.m_textCtrl2 = wx.TextCtrl( 104 | self, 105 | wx.ID_ANY, 106 | wx.EmptyString, 107 | wx.DefaultPosition, 108 | wx.DefaultSize, 109 | wx.TE_PROCESS_ENTER, 110 | ) 111 | self.m_textCtrl2.SetMinSize(wx.Size(220, -1)) 112 | 113 | fgSizer2.Add(self.m_textCtrl2, 0, wx.EXPAND | wx.ALL, 5) 114 | 115 | bSizer.Add(fgSizer2, 0, wx.ALIGN_CENTER_HORIZONTAL, 5) 116 | 117 | self.m_staticline12 = wx.StaticLine( 118 | self, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize, wx.LI_HORIZONTAL 119 | ) 120 | self.m_staticline12.SetForegroundColour( 121 | wx.SystemSettings.GetColour(wx.SYS_COLOUR_WINDOW) 122 | ) 123 | self.m_staticline12.SetBackgroundColour( 124 | wx.SystemSettings.GetColour(wx.SYS_COLOUR_GRAYTEXT) 125 | ) 126 | 127 | bSizer.Add(self.m_staticline12, 0, wx.EXPAND | wx.ALL, 5) 128 | 129 | fgSizer1 = wx.FlexGridSizer(0, 4, 0, 0) 130 | fgSizer1.SetFlexibleDirection(wx.BOTH) 131 | fgSizer1.SetNonFlexibleGrowMode(wx.FLEX_GROWMODE_SPECIFIED) 132 | 133 | fgSizer1.SetMinSize(wx.Size(-1, 0)) 134 | self.m_autoImport = wx.CheckBox( 135 | self, 136 | wx.ID_ANY, 137 | "auto background import", 138 | wx.DefaultPosition, 139 | wx.DefaultSize, 140 | 0, 141 | ) 142 | fgSizer1.Add(self.m_autoImport, 0, wx.ALL | wx.ALIGN_CENTER_VERTICAL, 5) 143 | 144 | self.m_overwrite = wx.CheckBox( 145 | self, 146 | wx.ID_ANY, 147 | "overwrite existing lib", 148 | wx.DefaultPosition, 149 | wx.DefaultSize, 150 | 0, 151 | ) 152 | fgSizer1.Add(self.m_overwrite, 0, wx.ALL | wx.ALIGN_CENTER_VERTICAL, 5) 153 | 154 | self.m_check_import_all = wx.CheckBox( 155 | self, wx.ID_ANY, "import old format", wx.DefaultPosition, wx.DefaultSize, 0 156 | ) 157 | self.m_check_import_all.Enable(False) 158 | self.m_check_import_all.Hide() 159 | 160 | fgSizer1.Add(self.m_check_import_all, 0, wx.ALL, 5) 161 | 162 | self.m_check_autoLib = wx.CheckBox( 163 | self, wx.ID_ANY, "auto KiCad setting", wx.DefaultPosition, wx.DefaultSize, 0 164 | ) 165 | fgSizer1.Add(self.m_check_autoLib, 0, wx.ALL, 5) 166 | 167 | bSizer.Add(fgSizer1, 0, wx.ALIGN_CENTER, 5) 168 | 169 | self.m_staticText_sourcepath = wx.StaticText( 170 | self, 171 | wx.ID_ANY, 172 | "Folder of the library to import:", 173 | wx.DefaultPosition, 174 | wx.DefaultSize, 175 | 0, 176 | ) 177 | self.m_staticText_sourcepath.Wrap(-1) 178 | 179 | bSizer.Add(self.m_staticText_sourcepath, 0, wx.ALL, 5) 180 | 181 | self.m_dirPicker_sourcepath = wx.DirPickerCtrl( 182 | self, 183 | wx.ID_ANY, 184 | ".", 185 | "Select a folder", 186 | wx.DefaultPosition, 187 | wx.DefaultSize, 188 | wx.DIRP_DEFAULT_STYLE, 189 | ) 190 | bSizer.Add(self.m_dirPicker_sourcepath, 0, wx.ALL | wx.EXPAND, 5) 191 | 192 | bSizer2 = wx.BoxSizer(wx.HORIZONTAL) 193 | 194 | self.m_staticText_librarypath = wx.StaticText( 195 | self, 196 | wx.ID_ANY, 197 | "Library save location:", 198 | wx.DefaultPosition, 199 | wx.DefaultSize, 200 | 0, 201 | ) 202 | self.m_staticText_librarypath.Wrap(-1) 203 | 204 | bSizer2.Add(self.m_staticText_librarypath, 0, wx.ALL, 5) 205 | 206 | self.m_checkBoxLocalLib = wx.CheckBox( 207 | self, 208 | wx.ID_ANY, 209 | "Save local, in the project folder", 210 | wx.DefaultPosition, 211 | wx.DefaultSize, 212 | 0, 213 | ) 214 | bSizer2.Add(self.m_checkBoxLocalLib, 0, wx.ALL, 5) 215 | 216 | bSizer.Add(bSizer2, 0, 0, 5) 217 | 218 | self.m_dirPicker_librarypath = wx.DirPickerCtrl( 219 | self, 220 | wx.ID_ANY, 221 | ".", 222 | "Select a folder", 223 | wx.DefaultPosition, 224 | wx.DefaultSize, 225 | wx.DIRP_DEFAULT_STYLE, 226 | ) 227 | bSizer.Add(self.m_dirPicker_librarypath, 0, wx.ALL | wx.EXPAND, 5) 228 | 229 | self.m_staticline1 = wx.StaticLine( 230 | self, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize, wx.LI_HORIZONTAL 231 | ) 232 | self.m_staticline1.SetForegroundColour( 233 | wx.SystemSettings.GetColour(wx.SYS_COLOUR_WINDOW) 234 | ) 235 | self.m_staticline1.SetBackgroundColour( 236 | wx.SystemSettings.GetColour(wx.SYS_COLOUR_GRAYTEXT) 237 | ) 238 | self.m_staticline1.Hide() 239 | 240 | bSizer.Add(self.m_staticline1, 0, wx.EXPAND | wx.ALL, 5) 241 | 242 | self.m_staticText5 = wx.StaticText( 243 | self, 244 | wx.ID_ANY, 245 | "There is no guarantee for faultless function. Use only at your own risk. Should there be any errors please write an issue.\nNecessary settings for the integration of the libraries can be found in the README:", 246 | wx.DefaultPosition, 247 | wx.DefaultSize, 248 | 0, 249 | ) 250 | self.m_staticText5.Wrap(-1) 251 | 252 | self.m_staticText5.Hide() 253 | self.m_staticText5.SetMinSize(wx.Size(-1, 50)) 254 | 255 | bSizer.Add(self.m_staticText5, 0, wx.EXPAND | wx.TOP | wx.RIGHT | wx.LEFT, 5) 256 | 257 | self.m_hyperlink = wx.adv.HyperlinkCtrl( 258 | self, 259 | wx.ID_ANY, 260 | "github.com/Steffen-W/Import-LIB-KiCad-Plugin", 261 | "https://github.com/Steffen-W/Import-LIB-KiCad-Plugin", 262 | wx.DefaultPosition, 263 | wx.DefaultSize, 264 | wx.adv.HL_DEFAULT_STYLE, 265 | ) 266 | bSizer.Add(self.m_hyperlink, 0, wx.BOTTOM | wx.RIGHT | wx.LEFT, 5) 267 | 268 | self.SetSizer(bSizer) 269 | self.Layout() 270 | 271 | self.Centre(wx.BOTH) 272 | 273 | # Connect Events 274 | self.Bind(wx.EVT_CLOSE, self.on_close) 275 | self.m_button_migrate.Bind(wx.EVT_BUTTON, self.migrate_libs) 276 | self.m_button.Bind(wx.EVT_BUTTON, self.BottonClick) 277 | self.m_buttonImportManual.Bind(wx.EVT_BUTTON, self.ButtomManualImport) 278 | self.m_textCtrl2.Bind(wx.EVT_TEXT_ENTER, self.ButtomManualImport) 279 | self.m_dirPicker_sourcepath.Bind(wx.EVT_DIRPICKER_CHANGED, self.DirChange) 280 | self.m_checkBoxLocalLib.Bind(wx.EVT_CHECKBOX, self.m_checkBoxLocalLibOnCheckBox) 281 | self.m_dirPicker_librarypath.Bind(wx.EVT_DIRPICKER_CHANGED, self.DirChange) 282 | 283 | def __del__(self): 284 | pass 285 | 286 | # Virtual event handlers, override them in your derived class 287 | def on_close(self, event): 288 | event.Skip() 289 | 290 | def migrate_libs(self, event): 291 | event.Skip() 292 | 293 | def BottonClick(self, event): 294 | event.Skip() 295 | 296 | def ButtomManualImport(self, event): 297 | event.Skip() 298 | 299 | def DirChange(self, event): 300 | event.Skip() 301 | 302 | def m_checkBoxLocalLibOnCheckBox(self, event): 303 | event.Skip() 304 | -------------------------------------------------------------------------------- /plugins/single_instance_manager.py: -------------------------------------------------------------------------------- 1 | """ 2 | Single Instance Manager with IPC communication for KiCad Plugin. 3 | Handles ensuring only one instance runs and brings existing window to foreground. 4 | """ 5 | 6 | import json 7 | import logging 8 | import socket 9 | import threading 10 | from typing import Any, Optional 11 | 12 | try: 13 | import wx 14 | except ImportError: 15 | wx = None 16 | 17 | 18 | class SingleInstanceManager: 19 | """Manages single instance with IPC communication and window state.""" 20 | 21 | def __init__(self, port: int = 59999): 22 | self.port = port 23 | self.socket: Optional[socket.socket] = None 24 | self.server_thread: Optional[threading.Thread] = None 25 | self.running = False 26 | self.frontend_instance: Optional[Any] = None 27 | self._stopped: bool = False 28 | self._stopping: bool = False 29 | 30 | def is_already_running(self) -> bool: 31 | """Check if another instance is running and send focus command.""" 32 | try: 33 | client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 34 | client_socket.settimeout(2.0) # Longer timeout 35 | client_socket.connect(("127.0.0.1", self.port)) 36 | 37 | message = {"command": "focus"} 38 | data = json.dumps(message).encode("utf-8") 39 | client_socket.send(data) 40 | 41 | # Wait for response to ensure command was processed 42 | try: 43 | client_socket.settimeout(1.0) 44 | response = client_socket.recv(64) 45 | logging.debug( 46 | f"Received response: {response.decode('utf-8', errors='replace')}" 47 | ) 48 | except socket.timeout: 49 | pass # No response is OK 50 | 51 | client_socket.close() 52 | 53 | logging.info("Sent focus command to existing instance") 54 | return True 55 | 56 | except (socket.error, ConnectionRefusedError, OSError) as e: 57 | logging.debug(f"No existing instance found: {e}") 58 | return False 59 | 60 | def start_server(self, frontend_instance: Any) -> bool: 61 | """Start IPC server to listen for commands.""" 62 | self.frontend_instance = frontend_instance 63 | 64 | # Try to find an available port if default is busy 65 | for port_attempt in range(self.port, self.port + 3): 66 | try: 67 | self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 68 | self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) 69 | # Also set SO_REUSEPORT on systems that support it 70 | try: 71 | self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1) 72 | except (AttributeError, OSError): 73 | # SO_REUSEPORT not available on this system (e.g., Windows) 74 | pass 75 | self.socket.bind(("127.0.0.1", port_attempt)) 76 | self.socket.listen(1) 77 | 78 | # Update port if we had to use a different one 79 | if port_attempt != self.port: 80 | logging.info( 81 | f"Port {self.port} was busy, using {port_attempt} instead" 82 | ) 83 | self.port = port_attempt 84 | 85 | self.running = True 86 | break 87 | 88 | except socket.error as e: 89 | if self.socket: 90 | self.socket.close() 91 | self.socket = None 92 | if port_attempt == self.port + 2: # Last attempt 93 | logging.error(f"Failed to start IPC server on any port: {e}") 94 | return False 95 | continue 96 | 97 | self.server_thread = threading.Thread(target=self._server_loop, daemon=True) 98 | self.server_thread.start() 99 | 100 | logging.info(f"IPC server started on port {self.port}") 101 | return True 102 | 103 | def _server_loop(self) -> None: 104 | """Main server loop to handle incoming commands.""" 105 | while self.running: 106 | client_socket = None 107 | try: 108 | if self.socket is None: 109 | break 110 | self.socket.settimeout(1.0) # Add timeout to server socket 111 | client_socket, addr = self.socket.accept() 112 | client_socket.settimeout(5.0) 113 | 114 | data = client_socket.recv(1024).decode("utf-8", errors="ignore") 115 | if data: 116 | try: 117 | message = json.loads(data) 118 | self._handle_command(message) 119 | # Send acknowledgment 120 | client_socket.send(b"OK") 121 | except json.JSONDecodeError: 122 | logging.warning("Received invalid JSON data") 123 | client_socket.send(b"ERROR") 124 | 125 | except socket.timeout: 126 | continue 127 | except socket.error as e: 128 | if self.running: 129 | logging.error(f"Server socket error: {e}") 130 | break 131 | finally: 132 | # Always close client socket 133 | if client_socket: 134 | try: 135 | client_socket.close() 136 | except (socket.error, OSError): 137 | pass 138 | 139 | def _handle_command(self, message: dict) -> None: 140 | """Handle incoming commands.""" 141 | command = message.get("command") 142 | 143 | if command == "focus" and self.frontend_instance: 144 | if wx: 145 | try: 146 | wx.CallAfter(self._bring_to_foreground) 147 | logging.info("Scheduled window focus command") 148 | except RuntimeError as e: 149 | logging.warning(f"wx.CallAfter failed (app may be closing): {e}") 150 | else: 151 | logging.warning("wx not available - cannot bring window to foreground") 152 | 153 | def _bring_to_foreground(self) -> None: 154 | """Bring the window to foreground (must be called from main thread).""" 155 | if not self.frontend_instance: 156 | logging.warning("No frontend instance available") 157 | return 158 | 159 | try: 160 | # Check if window object is still valid 161 | if not hasattr(self.frontend_instance, "IsShown"): 162 | logging.error( 163 | "Frontend instance has no IsShown method - window may be destroyed" 164 | ) 165 | self.frontend_instance = None 166 | return 167 | 168 | # Additional safety check for destroyed window 169 | if ( 170 | hasattr(self.frontend_instance, "IsBeingDeleted") 171 | and self.frontend_instance.IsBeingDeleted() 172 | ): 173 | logging.warning("Frontend instance is being deleted - skipping focus") 174 | return 175 | 176 | # Handle hidden window (running in background) 177 | if not self.frontend_instance.IsShown(): 178 | logging.info("Window is hidden - showing and bringing to foreground") 179 | self.frontend_instance.Show(True) 180 | 181 | # Handle iconized window 182 | if ( 183 | hasattr(self.frontend_instance, "IsIconized") 184 | and self.frontend_instance.IsIconized() 185 | ): 186 | logging.info("Window is iconized - restoring") 187 | self.frontend_instance.Iconize(False) 188 | 189 | # Bring to foreground 190 | self.frontend_instance.Raise() 191 | self.frontend_instance.SetFocus() 192 | 193 | # Request user attention (platform-specific notification) 194 | if hasattr(self.frontend_instance, "RequestUserAttention"): 195 | self.frontend_instance.RequestUserAttention() 196 | 197 | logging.info("Successfully brought window to foreground") 198 | 199 | except Exception as e: 200 | logging.error(f"Failed to bring window to foreground: {e}") 201 | # If window is broken, reset the instance 202 | self.frontend_instance = None 203 | 204 | def register_frontend(self, frontend_instance: Any) -> bool: 205 | """Register a frontend instance. Returns True if this is the first instance.""" 206 | if self.frontend_instance is None: 207 | self.frontend_instance = frontend_instance 208 | logging.info("Registered new frontend instance") 209 | return True 210 | else: 211 | logging.info( 212 | "Frontend instance already exists - new instance should not be created" 213 | ) 214 | return False 215 | 216 | def unregister_frontend(self) -> None: 217 | """Unregister the current frontend instance.""" 218 | self.frontend_instance = None 219 | logging.info("Unregistered frontend instance") 220 | 221 | def is_frontend_hidden(self) -> bool: 222 | """Check if frontend is currently hidden.""" 223 | if self.frontend_instance and hasattr(self.frontend_instance, "IsShown"): 224 | return not self.frontend_instance.IsShown() 225 | return False 226 | 227 | def stop_server(self) -> None: 228 | """Stop the IPC server with robust cleanup.""" 229 | # Prevent multiple stops 230 | if hasattr(self, "_stopped") and self._stopped: 231 | return 232 | 233 | if hasattr(self, "_stopping") and self._stopping: 234 | return 235 | 236 | self._stopping = True 237 | logging.info("Stopping IPC server") 238 | self.running = False 239 | 240 | # Close socket first to stop accepting new connections 241 | if self.socket: 242 | try: 243 | self.socket.shutdown(socket.SHUT_RDWR) 244 | except Exception: 245 | pass # Socket might already be closed 246 | try: 247 | self.socket.close() 248 | except Exception as e: 249 | logging.debug(f"Error closing socket: {e}") 250 | finally: 251 | self.socket = None 252 | 253 | # Force stop server thread with longer timeout 254 | if self.server_thread and self.server_thread.is_alive(): 255 | self.server_thread.join(timeout=5.0) 256 | if self.server_thread.is_alive(): 257 | logging.warning("Server thread did not stop cleanly within 5 seconds") 258 | # Force cleanup thread reference 259 | self.server_thread = None 260 | 261 | self.unregister_frontend() 262 | self._stopping = False 263 | self._stopped = True 264 | logging.info("IPC server stopped") 265 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ![Static Badge](https://img.shields.io/badge/Supports_KiCad-v6%2C_v7%2C_v8%2C_v9-%23314cb0) 2 | ![Static Badge](https://img.shields.io/badge/Supports-Windows%2C_Mac%2C_Linux-Green) 3 | 4 | [![Static Badge](https://img.shields.io/badge/Samacsys-Works_(Component_Search_Engine)-1e8449)](https://componentsearchengine.com/) 5 | [![Static Badge](https://img.shields.io/badge/SnapEDA-Works_(v4%2C_v6)-27ae60)](https://www.snapeda.com/home/) 6 | [![Static Badge](https://img.shields.io/badge/UltraLibrarian-Works-229954)](https://app.ultralibrarian.com/search) 7 | [![Static Badge](https://img.shields.io/badge/Octopart-Works-52be80)](https://octopart.com/) 8 | [![Static Badge](https://img.shields.io/badge/LCSC--EasyEDA-Works-008000)](https://www.lcsc.com/) 9 | 10 | [![GitHub Release](https://img.shields.io/github/release/Steffen-W/Import-LIB-KiCad-Plugin.svg)](https://github.com/Steffen-W/Import-LIB-KiCad-Plugin/releases/latest) 11 | [![GitHub Downloads (all assets, all releases)](https://img.shields.io/github/downloads/Steffen-W/Import-LIB-KiCad-Plugin/total)](https://github.com/Steffen-W/Import-LIB-KiCad-Plugin/releases/latest/download/Import-LIB-KiCad-Plugin.zip) 12 | 13 | # KiCad Import-LIB-KiCad-Plugin ![icon](plugins/icon_small.png) 14 | 15 | This plugin allows importing downloaded libraries from the platforms [Octopart](https://octopart.com/), [Samacsys](https://componentsearchengine.com/), [Ultralibrarian](https://app.ultralibrarian.com/search), [Snapeda](https://www.snapeda.com/home/) and [EasyEDA](https://www.lcsc.com/). It can import symbols, footprints, descriptions, and if available, 3D files. Normally, when you select the imported symbol in KiCad, the appropriate footprint and the 3D file should also be linked. Provided, of course, that the libraries have been included as specified below. 16 | 17 | [![SC2 Video](doc/demo.gif)]([https://youtu.be/cdOKDY-F4ZU](https://youtu.be/VrWPPHtCovQ)) 18 | 19 | [YouTube - Instructions for installation and use](https://youtu.be/BYIKjCs1qKQ) 20 | 21 | ## Installation 22 | 23 | Install the plugin easily through KiCad's **Plugin And Content Manager**. Select ![icon](plugins/icon_small.png) **Import-LIB-KiCad-Plugin** in the Plugins tab, press **Install** and then **Apply Pending Changes**. 24 | 25 | You can also download the latest version [here](https://github.com/Steffen-W/Import-LIB-KiCad-Plugin/releases/latest/download/Import-LIB-KiCad-Plugin.zip) and install it via **KiCad** -> **Plugin And Content Manager** -> **Install from File...** -> select **Import-LIB-KiCad-Plugin.zip** and import. 26 | 27 | ## Use of the application 28 | 29 | The import window is accessible in the **PCB Editor** -> **Tools** -> **External Plugins** -> **impartGUI** 30 | 31 | ![Screenshot_GUI](doc/2025-08_Example_Import.png) 32 | 33 | The libraries to import must be located in the folder specified as **Folder of the library** to import. After pressing Start, the libraries will be imported into the specified folder (**Library save location**). 34 | 35 | **New:** You can also drag and drop ZIP files directly into the text area for instant import without setting up folder monitoring. 36 | 37 | Provided that the paths have been [added correctly in KiCad](#including-the-imported-libraries-in-kicad), the parts can be used immediately in KiCad. If the libraries have not been imported correctly, a warning will indicate this. 38 | 39 | ## Including the imported libraries in KiCad 40 | 41 | To use the imported libraries from the plugin, you will need to add a couple entries to KiCad's path first to see them. You can either let the plugin make the changes automatically (auto KiCad setting) or set the following changes manually in KiCad. 42 | 43 | **Preferences** -> **Configure paths** -> **Environment Variables** -> Add the following entry 44 | 45 | |Name |Path | 46 | |----------------|--------| 47 | |KICAD_3RD_PARTY |**YourLibraryFolder**/KiCad | 48 | 49 | **Preferences** -> **Manage Symbol Libraries** -> **Global Libraries** -> Add the following entries 50 | **(Note: Errors will show up if components weren't imported yet. The errors will disappear after importing as libraries will be created)** 51 | 52 | |Active |Visible |Nickname |Library Path | Library Format | 53 | |------------------|------------------|---------------|---------------------------------------------|----------------| 54 | |:heavy_check_mark:|:heavy_check_mark:|Samacsys |${KICAD_3RD_PARTY}/Samacsys.kicad_sym | KiCad | 55 | |:heavy_check_mark:|:heavy_check_mark:|Snapeda |${KICAD_3RD_PARTY}/Snapeda.kicad_sym | KiCad | 56 | |:heavy_check_mark:|:heavy_check_mark:|UltraLibrarian |${KICAD_3RD_PARTY}/UltraLibrarian.kicad_sym | KiCad | 57 | |:heavy_check_mark:|:heavy_check_mark:|EasyEDA |${KICAD_3RD_PARTY}/EasyEDA.kicad_sym | KiCad | 58 | 59 | **Preferences** -> **Manage Footprint Libraries** -> **Global Libraries** -> Add the following entries 60 | **(Note: It is best to add the library only after the import has been done with the plugin. Afterwards only the created libraries have to be imported. Lower entries are only for example.)** 61 | 62 | |Active |Nickname |Library Path | Library Format| 63 | |-------------------|---------------|-----------------------------------------|---------------| 64 | |:heavy_check_mark: |Samacsys | ${KICAD_3RD_PARTY}/Samacsys.pretty | KiCad | 65 | |:heavy_check_mark: |Snapeda | ${KICAD_3RD_PARTY}/Snapeda.pretty | KiCad | 66 | |:heavy_check_mark: |UltraLibrarian | ${KICAD_3RD_PARTY}/UltraLibrarian.pretty| KiCad | 67 | |:heavy_check_mark: |EasyEDA | ${KICAD_3RD_PARTY}/EasyEDA.pretty | KiCad | 68 | 69 | ## Migrate the libraries 70 | 71 | It is strongly recommended to migrate the libraries. If you see the "migrate the libraries" button, you have been using the plugin for some time. From now on, only the latest library format will be supported. If this does not work, the old format will continue to work. 72 | 73 | ![GUI_migrate](doc/2024-08-17_GUI_migrate.png) 74 | 75 | By pressing "migrate the libraries" the following window appears. Depending on how many libraries you use, fewer libraries may be displayed. Now you can start the conversion process. Important: The conversion only works completely from KiCad 8.0.4. If possible, use the latest stable [![GitHub Release](https://img.shields.io/badge/KiCad-V8-blue.svg)](https://www.kicad.org/download/) version. 76 | 77 | ![Migration](doc/2024-08-17_Migration.png) 78 | 79 | Depending on the setup, further changes may be necessary. You will be notified if this is necessary. Press ok to apply them. A restart of KiCad is mandatory to apply the changes. 80 | 81 | ![update setting](doc/2024-08-17_setting.png) 82 | 83 | ## CLI Support 84 | 85 | The import process can also be done completely without the GUI. ```python -m plugins.KiCadImport -h``` 86 | 87 | ```bash 88 | usage: __main__.py [-h] (--download-folder DOWNLOAD_FOLDER | --download-file DOWNLOAD_FILE | --easyeda EASYEDA) --lib-folder LIB_FOLDER [--overwrite-if-exists] [--path-variable PATH_VARIABLE] 89 | 90 | Import KiCad libraries from a file or folder. 91 | 92 | options: 93 | -h, --help show this help message and exit 94 | --download-folder DOWNLOAD_FOLDER 95 | Path to the folder with the zip files to be imported. 96 | --download-file DOWNLOAD_FILE 97 | Path to the zip file to import. 98 | --easyeda EASYEDA Import easyeda part. example: C2040 99 | --lib-folder LIB_FOLDER 100 | Destination folder for the imported KiCad files. 101 | --overwrite-if-exists 102 | Overwrite existing files if they already exist 103 | --path-variable PATH_VARIABLE 104 | Example: if only project-specific '${KIPRJMOD}' standard is '${KICAD_3RD_PARTY}' 105 | ``` 106 | 107 | ## KiCad IPC API (Recommended) 108 | 109 | The **KiCad IPC API** is the modern and recommended way to run this plugin. It provides automatic dependency management and better performance compared to the fallback solution. 110 | 111 | **To activate the KiCad IPC API:** 112 | 113 | 1. **KiCad** -> **Settings** -> **Plugins** -> **Enable Plugin System** 114 | 2. Check **Enable KiCad API** option 115 | 3. Restart KiCad 116 | 117 | ![KiCad API Settings](doc/kicad_api_settings.png) 118 | 119 | **Benefits of using the KiCad IPC API:** 120 | 121 | - Automatic dependency installation in isolated environment 122 | - Faster startup and execution 123 | - Better integration with KiCad 124 | - No manual setup required 125 | 126 | **Plugin access with IPC API:** 127 | 128 | - **PCB Editor** -> **Tools** -> **External Plugins** -> **impartGUI (IPC API)** 129 | - **Schematic Editor** -> **Tools** -> **External Plugins** -> **impartGUI (IPC API)** 130 | 131 | ## Fallback Solution (pcbnew) 132 | 133 | If the **KiCad IPC API** is not available or activated, the plugin will automatically use a fallback solution. The KiCad API handles dependency installation in its own virtual environment automatically, while the fallback solution requires manual setup. 134 | 135 | **To activate the KiCad IPC API (recommended):** 136 | **KiCad** -> **Settings** -> **Plugins** -> **Activate KiCad API** 137 | 138 | **If using the fallback solution:** 139 | 140 | - A setup dialog will appear on first run 141 | - Click **Start Integration** to manually install required dependencies 142 | - Dependencies (pydantic, requests) will be installed in a separate virtual environment 143 | - Setup only needs to be done once 144 | 145 | ![Fallback Setup](doc/fallback_setup.png) 146 | 147 | The fallback solution provides the same functionality but requires manual dependency setup and may have slower startup times. Using the KiCad IPC API is recommended for optimal performance and automatic dependency management. 148 | 149 | ## Warranty 150 | 151 | **None. Zero. Zilch. Use at your own risk**, and please be sure to use git or some other means of backing up/reverting changes caused by this script. This script will modify existing lib, dcm, footprint or 3D model files. It is your responsibility to back them up or have a way to revert changes should you inadvertently mess something up using this tool. 152 | 153 | Please write an issues if an import does not work as requested. 154 | 155 | ## FAQ 156 | 157 | **Do I have to manually create a library that does not yet exist before using the plugin?** 158 | No, you do not need to create a file manually. Your only task is to download your desired part from the internet and start the import process with the plugin. 159 | 160 | **Where can I save the library?** 161 | It is possible to save the files in any place on your PC where you have read and write permissions. 162 | It is also possible to store the files on network drives or cloud storage to share the library with others. 163 | In the libraries relative paths are used, the absolute path is not considered. 164 | 165 | **Can I change the storage location?** 166 | Yes, this is of course always possible. But you should keep in mind that the existing libraries will not be moved automatically. You would have to do that yourself if necessary. 167 | 168 | **If I import from one source, do I have to stay with that source, or can I import from all sources?** 169 | For each source, a separate library is created for KiCad. Maximum actually three (Samacsys, Ultralibrarian and Snapeda), Octopart components as well as from other suppliers can be found in the Snapeda library. So if you import from a new source, a new library can be created. But maximum three. 170 | 171 | ### General KiCad Questions 172 | 173 | **I have entered a library in the settings in KiCad that does not exist at this time, what happens?** 174 | You get a message that this library does not exist. Nothing more. As soon as it exists, it can be accessed. 175 | 176 | **Can I remove a library from the settings?** 177 | Yes, you can always do that. The libraries are neither deleted nor edited in any way. They are just not included. 178 | 179 | ## Todo List 180 | 181 | - [x] Drag and drop support for ZIP files 182 | - [x] add as local project Lib 183 | - [x] plugin in schematic windows 184 | - [x] Add digikey support 185 | - [x] Reloading the dependency pydantic for [uPesy/easyeda2kicad.py](https://github.com/uPesy/easyeda2kicad.py) 186 | - [x] Updating the library before an import `kicad-cli sym upgrade` 187 | - [x] Updating the footprint library `kicad-cli fp upgrade *.pretty` 188 | - [x] add [jlcpcb parts](https://jlcpcb.com/parts) to import (integrate [uPesy/easyeda2kicad.py](https://github.com/uPesy/easyeda2kicad.py)) 189 | - [x] Automatic background import 190 | - [x] Test on a Mac 191 | - [x] Testing all library formats 192 | - [x] Using the new KiCad format 193 | - [x] Possibility of automatic KiCad settings adjustment 194 | 195 | If you notice an error then please write me an issue. If you want to change the GUI or the functionality, I am also open for ideas. 196 | 197 | [![Create Issue](https://img.shields.io/badge/Create%20Issue-blue.svg)](https://github.com/Steffen-W/Import-LIB-KiCad-Plugin/issues/new) 198 | 199 | Support via Ko-fi 200 | 201 | ## Many thanks to 202 | 203 | [wexi with impart](https://github.com/wexi/impart) and [topherbuckley](https://github.com/topherbuckley/kicad_remote_import) for the code on which the GUI is based. 204 | I would also like to thank [uPesy](https://github.com/uPesy) for enabling the import of [EasyEDA](https://www.lcsc.com/) through his python project [uPesy/easyeda2kicad.py](https://github.com/uPesy/easyeda2kicad.py) (AGPL-3.0 license). 205 | I also thank the people who helped me find the errors in the code. 206 | -------------------------------------------------------------------------------- /plugins/impart_easyeda.py: -------------------------------------------------------------------------------- 1 | # Simplified EasyEDA to KiCad importer 2 | # Based on: https://github.com/uPesy/easyeda2kicad.py/blob/master/easyeda2kicad/__main__.py 3 | import logging 4 | import re 5 | import sys 6 | from dataclasses import dataclass 7 | from pathlib import Path 8 | from typing import Callable, NamedTuple, Optional, Tuple 9 | 10 | # Configure logging 11 | logger = logging.getLogger(__name__) 12 | 13 | try: 14 | from .kicad_cli import kicad_cli as KicadCli 15 | except ImportError: 16 | from kicad_cli import kicad_cli as KicadCli # type: ignore[import-not-found,no-redef] 17 | 18 | try: 19 | cli: Optional[KicadCli] = KicadCli() 20 | logger.info("✓ kicad_cli initialized successfully") 21 | except Exception as e: 22 | logger.error(f"Failed to initialize kicad_cli: {e}") 23 | cli = None 24 | 25 | current_dir = Path(__file__).resolve().parent 26 | easyeda_submodule = current_dir / "easyeda2kicad" 27 | 28 | if easyeda_submodule.exists(): 29 | # Remove any conflicting easyeda2kicad modules from cache first 30 | modules_to_remove = [k for k in sys.modules.keys() if k.startswith("easyeda2kicad")] 31 | for mod in modules_to_remove: 32 | del sys.modules[mod] 33 | 34 | # Add git submodule path at the very beginning 35 | easyeda_str = str(easyeda_submodule) 36 | if easyeda_str not in sys.path: 37 | sys.path.insert(0, easyeda_str) 38 | 39 | logger.info(f"Using easyeda2kicad from: {easyeda_submodule}") 40 | 41 | from easyeda2kicad.easyeda.easyeda_api import EasyedaApi 42 | from easyeda2kicad.easyeda.easyeda_importer import ( 43 | Easyeda3dModelImporter, 44 | EasyedaFootprintImporter, 45 | EasyedaSymbolImporter, 46 | EeSymbol, 47 | ) 48 | from easyeda2kicad.helpers import ( 49 | KicadVersion, 50 | id_already_in_symbol_lib, 51 | update_component_in_symbol_lib_file, 52 | ) 53 | from easyeda2kicad.kicad.export_kicad_3d_model import Exporter3dModelKicad 54 | from easyeda2kicad.kicad.export_kicad_footprint import ExporterFootprintKicad 55 | from easyeda2kicad.kicad.export_kicad_symbol import ExporterSymbolKicad 56 | 57 | logger.info("Successfully imported easyeda2kicad modules") 58 | 59 | 60 | class ImportPaths(NamedTuple): 61 | """Container for all generated file paths""" 62 | 63 | symbol_lib: Optional[Path] = None 64 | footprint_file: Optional[Path] = None 65 | model_wrl: Optional[Path] = None 66 | model_step: Optional[Path] = None 67 | 68 | 69 | @dataclass 70 | class ImportConfig: 71 | """Configuration for import operations""" 72 | 73 | base_folder: Path 74 | lib_name: str = "EasyEDA" 75 | overwrite: bool = False 76 | lib_var: str = "${EASYEDA2KICAD}" 77 | 78 | 79 | class EasyEDAImporter: 80 | """EasyEDA to KiCad component importer - focused on new symbol format only""" 81 | 82 | def __init__( 83 | self, config: ImportConfig, print_func: Optional[Callable[[str], None]] = None 84 | ): 85 | """Initialize importer with configuration""" 86 | self.print_func = print_func or (lambda x: None) 87 | self.config = config 88 | self.config.base_folder = Path(self.config.base_folder).expanduser() 89 | self.api = EasyedaApi() 90 | 91 | # Paths that will be used 92 | self.symbol_lib_path = ( 93 | self.config.base_folder / f"{self.config.lib_name}.kicad_sym" 94 | ) 95 | self.footprint_dir = self.config.base_folder / f"{self.config.lib_name}.pretty" 96 | self.model_dir = self.config.base_folder / f"{self.config.lib_name}.3dshapes" 97 | 98 | def _print(self, message: str) -> None: 99 | """Print message using the provided print function""" 100 | self.print_func(message) 101 | 102 | def _ensure_directories(self) -> None: 103 | """Create necessary directories""" 104 | self.config.base_folder.mkdir(parents=True, exist_ok=True) 105 | self.footprint_dir.mkdir(exist_ok=True) 106 | self.model_dir.mkdir(exist_ok=True) 107 | logger.debug(f"Ensured directories exist in {self.config.base_folder}") 108 | 109 | def _import_symbol(self, cad_data: dict) -> Tuple[bool, Optional[str]]: 110 | """Import symbol and return success status and component name""" 111 | try: 112 | importer = EasyedaSymbolImporter(easyeda_cp_cad_data=cad_data) 113 | easyeda_symbol: EeSymbol = importer.get_symbol() 114 | component_name = easyeda_symbol.info.name 115 | 116 | # Check if symbol library exists first, then check if symbol already exists 117 | if self.symbol_lib_path.exists(): 118 | is_existing = id_already_in_symbol_lib( 119 | lib_path=str(self.symbol_lib_path), 120 | component_name=component_name, 121 | kicad_version=KicadVersion.v6, 122 | ) 123 | else: 124 | is_existing = False 125 | 126 | if is_existing and not self.config.overwrite: 127 | self._print(f"Symbol '{component_name}' already exists.") 128 | return False, component_name 129 | 130 | # Export symbol 131 | exporter = ExporterSymbolKicad( 132 | symbol=easyeda_symbol, kicad_version=KicadVersion.v6 133 | ) 134 | kicad_symbol_content = exporter.export( 135 | footprint_lib_name=self.config.lib_name 136 | ) 137 | 138 | # Check if export was successful 139 | if not kicad_symbol_content: 140 | self._print(f"Failed to export symbol content for: {component_name}") 141 | return False, component_name 142 | 143 | # Add or update symbol in library 144 | if is_existing: 145 | logger.warning( 146 | f"Using unsafe legacy update function for existing symbol: {component_name}" 147 | ) 148 | update_component_in_symbol_lib_file( 149 | lib_path=str(self.symbol_lib_path), 150 | component_name=component_name, 151 | component_content=kicad_symbol_content, 152 | kicad_version=KicadVersion.v6, 153 | ) 154 | self._print(f"Updated symbol: {component_name}") 155 | else: 156 | success = self.add_symbol_to_upgraded_lib(kicad_symbol_content) 157 | if success: 158 | self._print(f"Added symbol: {component_name}") 159 | else: 160 | self._print(f"Failed to add symbol: {component_name}") 161 | return False, component_name 162 | 163 | return True, component_name 164 | 165 | except Exception as e: 166 | self._print(f"Failed to import symbol: {e}") 167 | logger.error(f"Symbol import failed: {e}") 168 | return False, None 169 | 170 | def get_kicad_lib_version(self, content: str) -> int: 171 | """Extract version number from KiCad symbol library. Returns 0 if not found.""" 172 | if not content: 173 | return 0 174 | 175 | match = re.search(r"\(\s*version\s+(\d+)\s*\)", content[:200]) 176 | return int(match.group(1)) if match else 0 177 | 178 | def add_symbol_to_upgraded_lib(self, symbol_content: str) -> bool: 179 | """Add symbol to library with automatic upgrade handling.""" 180 | try: 181 | if not symbol_content: 182 | self._print("Error: Empty symbol content provided") 183 | return False 184 | 185 | complete_symbol_lib = f"""(kicad_symbol_lib 186 | (version 20211014) 187 | (generator https://github.com/uPesy/easyeda2kicad.py) 188 | {symbol_content} 189 | )""" 190 | 191 | if cli is None: 192 | self._print("KiCad CLI not available") 193 | return False 194 | 195 | success, upgraded_symbol_lib, error = cli.upgrade_sym_lib_from_string( 196 | complete_symbol_lib 197 | ) 198 | if not success: 199 | self._print(f"Failed to upgrade new symbol: {error}") 200 | return False 201 | 202 | if self.symbol_lib_path.exists(): 203 | with open(self.symbol_lib_path, "r", encoding="utf-8") as f: 204 | existing_lib = f.read() 205 | 206 | existing_version = self.get_kicad_lib_version(existing_lib) 207 | new_version = self.get_kicad_lib_version(upgraded_symbol_lib) 208 | 209 | if existing_version >= new_version: 210 | upgraded_existing_lib = existing_lib 211 | else: 212 | success, upgraded_existing_lib, error = ( 213 | cli.upgrade_sym_lib_from_string(existing_lib) 214 | ) 215 | if not success: 216 | self._print(f"Failed to upgrade existing library: {error}") 217 | return False 218 | 219 | symbol_start = upgraded_symbol_lib.find("(symbol ") 220 | if symbol_start == -1: 221 | self._print("Could not find symbol content in upgraded library") 222 | return False 223 | 224 | symbol_content_to_add = upgraded_symbol_lib[ 225 | symbol_start : upgraded_symbol_lib.rfind(")") 226 | ].strip() 227 | 228 | last_paren_pos = upgraded_existing_lib.rfind(")") 229 | if last_paren_pos == -1: 230 | self._print("Invalid existing library format") 231 | return False 232 | 233 | final_lib = ( 234 | upgraded_existing_lib[:last_paren_pos].rstrip() 235 | + "\n " 236 | + symbol_content_to_add 237 | + "\n" 238 | + upgraded_existing_lib[last_paren_pos:] 239 | ) 240 | else: 241 | final_lib = upgraded_symbol_lib 242 | 243 | with open(self.symbol_lib_path, "w", encoding="utf-8") as f: 244 | f.write(final_lib) 245 | 246 | return True 247 | 248 | except Exception as e: 249 | self._print(f"Failed to add symbol to library: {e}") 250 | logger.error(f"Symbol library integration failed: {e}") 251 | return False 252 | 253 | def _import_footprint(self, cad_data: dict) -> Optional[Path]: 254 | """Import footprint and return the file path""" 255 | try: 256 | importer = EasyedaFootprintImporter(easyeda_cp_cad_data=cad_data) 257 | easyeda_footprint = importer.get_footprint() 258 | 259 | footprint_file = ( 260 | self.footprint_dir / f"{easyeda_footprint.info.name}.kicad_mod" 261 | ) 262 | 263 | if footprint_file.exists() and not self.config.overwrite: 264 | self._print(f"Footprint already exists: {footprint_file.name}") 265 | return None 266 | 267 | exporter = ExporterFootprintKicad(footprint=easyeda_footprint) 268 | model_3d_path = f"{self.config.lib_var}/{self.config.lib_name}.3dshapes" 269 | 270 | exporter.export( 271 | footprint_full_path=str(footprint_file), 272 | model_3d_path=model_3d_path, 273 | ) 274 | 275 | self._print(f"Created footprint: {footprint_file.name}") 276 | return footprint_file 277 | 278 | except Exception as e: 279 | self._print(f"Failed to import footprint: {e}") 280 | logger.error(f"Footprint import failed: {e}") 281 | return None 282 | 283 | def _import_3d_model(self, cad_data: dict) -> Tuple[Optional[Path], Optional[Path]]: 284 | """Import 3D model and return paths to wrl and step files""" 285 | try: 286 | model_3d = Easyeda3dModelImporter( 287 | easyeda_cp_cad_data=cad_data, download_raw_3d_model=True 288 | ).output 289 | 290 | if not model_3d: 291 | self._print("No 3D model available for this component.") 292 | return None, None 293 | 294 | exporter = Exporter3dModelKicad(model_3d=model_3d) 295 | 296 | if not (exporter.output or exporter.output_step): 297 | self._print("No exportable 3D model found.") 298 | return None, None 299 | 300 | output_name = exporter.output.name if exporter.output else "model" 301 | filepath_wrl = self.model_dir / f"{output_name}.wrl" 302 | filepath_step = self.model_dir / f"{output_name}.step" 303 | 304 | # Check existing files 305 | if not self.config.overwrite: 306 | if filepath_wrl.exists() or filepath_step.exists(): 307 | self._print("3D model files already exist.") 308 | return None, None 309 | 310 | # Export models 311 | exporter.export( 312 | lib_path=str(self.config.base_folder / self.config.lib_name) 313 | ) 314 | 315 | wrl_path = filepath_wrl if filepath_wrl.exists() else None 316 | step_path = filepath_step if filepath_step.exists() else None 317 | 318 | if wrl_path: 319 | self._print(f"Created 3D model (WRL): {wrl_path.name}") 320 | if step_path: 321 | self._print(f"Created 3D model (STEP): {step_path.name}") 322 | 323 | return wrl_path, step_path 324 | 325 | except Exception as e: 326 | self._print(f"Failed to import 3D model: {e}") 327 | logger.error(f"3D model import failed: {e}") 328 | return None, None 329 | 330 | def import_component(self, component_id: str) -> ImportPaths: 331 | """ 332 | Import a component and all its assets. 333 | Returns ImportPaths with all created file paths. 334 | """ 335 | self._print(f"Starting import for EasyEDA/LCSC component: {component_id}") 336 | 337 | # Validate component ID 338 | if not component_id.startswith("C"): 339 | error_msg = f"Invalid component ID: '{component_id}' (must start with 'C', e.g., 'C2040')" 340 | self._print(error_msg) 341 | raise ValueError(error_msg) 342 | 343 | # Ensure directories exist 344 | self._ensure_directories() 345 | 346 | try: 347 | # Fetch CAD data 348 | cad_data = self.api.get_cad_data_of_component(lcsc_id=component_id) 349 | 350 | if not cad_data: 351 | error_msg = f"Failed to fetch CAD data for component {component_id}" 352 | self._print(error_msg) 353 | raise RuntimeError(error_msg) 354 | 355 | # Import all parts 356 | symbol_ok, component_name = self._import_symbol(cad_data) 357 | footprint_path = self._import_footprint(cad_data) 358 | wrl_path, step_path = self._import_3d_model(cad_data) 359 | 360 | # Prepare result 361 | result = ImportPaths( 362 | symbol_lib=self.symbol_lib_path if symbol_ok else None, 363 | footprint_file=footprint_path, 364 | model_wrl=wrl_path, 365 | model_step=step_path, 366 | ) 367 | 368 | # Final status 369 | created_files = sum( 370 | 1 371 | for path in [ 372 | result.symbol_lib, 373 | result.footprint_file, 374 | result.model_wrl, 375 | result.model_step, 376 | ] 377 | if path 378 | ) 379 | 380 | if created_files > 0: 381 | self._print( 382 | f"EasyEDA import completed successfully! ({created_files} files created)" 383 | ) 384 | else: 385 | self._print("EasyEDA import completed, but no new files were created") 386 | 387 | return result 388 | 389 | except Exception as e: 390 | error_msg = f"EasyEDA import failed: {e}" 391 | self._print(error_msg) 392 | logger.error(f"Component import failed for {component_id}: {e}") 393 | raise 394 | 395 | 396 | def import_easyeda_component( 397 | component_id: str, config: ImportConfig, print_func: Callable[[str], None] 398 | ) -> ImportPaths: 399 | importer = EasyEDAImporter(config, print_func) 400 | return importer.import_component(component_id) 401 | 402 | 403 | # Example usage 404 | if __name__ == "__main__": 405 | logging.basicConfig(level=logging.INFO) 406 | 407 | def print_to_console(message): 408 | print(message) 409 | 410 | config = ImportConfig( 411 | base_folder=Path("~/Documents/Kicad/EasyEDA"), 412 | lib_name="EasyEDA", 413 | overwrite=False, 414 | ) 415 | 416 | # Import a component 417 | try: 418 | paths = import_easyeda_component("C2040", config, print_to_console) 419 | 420 | # Access the paths 421 | if paths.symbol_lib: 422 | print(f"Symbol was written to library: {paths.symbol_lib}") 423 | 424 | if paths.footprint_file: 425 | print(f"Footprint was created at: {paths.footprint_file}") 426 | 427 | if paths.model_wrl or paths.model_step: 428 | print("3D models were created:") 429 | if paths.model_wrl: 430 | print(f" WRL: {paths.model_wrl}") 431 | if paths.model_step: 432 | print(f" STEP: {paths.model_step}") 433 | 434 | except Exception as e: 435 | print(f"Import failed: {e}") 436 | -------------------------------------------------------------------------------- /plugins/kicad_cli/__init__.py: -------------------------------------------------------------------------------- 1 | import logging 2 | import os 3 | import shutil 4 | import subprocess 5 | import sys 6 | import tempfile 7 | from dataclasses import dataclass 8 | from typing import List, Optional, Tuple 9 | 10 | 11 | @dataclass 12 | class CommandResult: 13 | """Detailed result information for KiCad CLI commands.""" 14 | 15 | success: bool 16 | stdout: str 17 | stderr: str 18 | return_code: int 19 | message: str = "" 20 | 21 | 22 | class kicad_cli: 23 | def __init__(self) -> None: 24 | """Initialize the KiCad CLI wrapper with logger and command discovery.""" 25 | self.logger: logging.Logger = logging.getLogger(__name__) 26 | self.kicad_cmd: str = self._find_kicad_cli() 27 | 28 | def _find_kicad_cli(self) -> str: 29 | """Find KiCad CLI command across different platforms.""" 30 | # macOS-specific paths - check absolute paths first 31 | if sys.platform == "darwin": # macOS 32 | mac_paths = [ 33 | "/Applications/KiCad/KiCad.app/Contents/MacOS/kicad-cli", 34 | "/Applications/KiCad-10.0/KiCad.app/Contents/MacOS/kicad-cli", 35 | "/Applications/KiCad-9.0/KiCad.app/Contents/MacOS/kicad-cli", 36 | "/Applications/KiCad-8.0/KiCad.app/Contents/MacOS/kicad-cli", 37 | ] 38 | for path in mac_paths: 39 | if os.path.isfile(path) and os.access(path, os.X_OK): 40 | self.logger.info(f"Found KiCad CLI at: {path}") 41 | return path 42 | 43 | # Check system PATH for standard commands 44 | possible_commands: List[str] = ["kicad-cli", "kicad-cli.exe"] 45 | for cmd in possible_commands: 46 | if shutil.which(cmd): 47 | self.logger.info(f"Found KiCad CLI in PATH: {cmd}") 48 | return cmd 49 | 50 | self.logger.warning("KiCad CLI not found, using default 'kicad-cli'") 51 | return "kicad-cli" 52 | 53 | def run_kicad_cli(self, command: List[str]) -> CommandResult: 54 | """Execute a KiCad CLI command with detailed result information.""" 55 | full_command = [self.kicad_cmd] + command 56 | self.logger.info(f"Executing: {' '.join(full_command)}") 57 | 58 | try: 59 | # Windows-specific flag to hide console window 60 | creation_flags = 0 61 | if sys.platform == "win32": 62 | try: 63 | creation_flags = subprocess.CREATE_NO_WINDOW 64 | except AttributeError: 65 | # Fallback for older Python versions on Windows 66 | creation_flags = 0x08000000 # CREATE_NO_WINDOW constant 67 | 68 | # Set LANG to English to ensure consistent output 69 | env = os.environ.copy() 70 | env["LANG"] = "en_US.UTF-8" 71 | env["LC_ALL"] = "en_US.UTF-8" 72 | 73 | result = subprocess.run( 74 | full_command, 75 | stdout=subprocess.PIPE, 76 | stderr=subprocess.PIPE, 77 | text=True, 78 | timeout=30, 79 | creationflags=creation_flags, 80 | env=env, 81 | ) 82 | 83 | success = result.returncode == 0 84 | if success: 85 | self.logger.info("Command completed successfully") 86 | else: 87 | self.logger.error( 88 | f"Command failed with return code {result.returncode}" 89 | ) 90 | 91 | return CommandResult( 92 | success=success, 93 | stdout=result.stdout, 94 | stderr=result.stderr, 95 | return_code=result.returncode, 96 | message=f"Command {'succeeded' if success else 'failed'}", 97 | ) 98 | 99 | except subprocess.TimeoutExpired: 100 | error_msg = f"Timeout: Command took too long: {' '.join(full_command)}" 101 | self.logger.error(error_msg) 102 | return CommandResult(False, "", "Timeout expired", -1, error_msg) 103 | except FileNotFoundError: 104 | error_msg = f"KiCad CLI not found: {self.kicad_cmd}" 105 | self.logger.error(error_msg) 106 | return CommandResult(False, "", "Command not found", -1, error_msg) 107 | except Exception as e: 108 | error_msg = f"Unexpected error running command: {e}" 109 | self.logger.error(error_msg) 110 | return CommandResult(False, "", str(e), -1, error_msg) 111 | 112 | def version_to_tuple(self, version_str: str) -> Tuple[int, int, int]: 113 | """Convert a version string like '8.0.4' or '8.0.4-rc1' to tuple.""" 114 | try: 115 | clean_version: str = version_str.split("-")[0] 116 | parts: List[str] = clean_version.split(".") 117 | while len(parts) < 3: 118 | parts.append("0") 119 | return (int(parts[0]), int(parts[1]), int(parts[2])) 120 | except (ValueError, AttributeError, TypeError, IndexError): 121 | return (0, 0, 0) 122 | 123 | def exists(self) -> bool: 124 | """Check if KiCad CLI exists and meets minimum version requirements.""" 125 | try: 126 | # Windows-specific flag to hide console window 127 | creation_flags = 0 128 | if sys.platform == "win32": 129 | try: 130 | creation_flags = subprocess.CREATE_NO_WINDOW 131 | except AttributeError: 132 | # Fallback for older Python versions on Windows 133 | creation_flags = 0x08000000 # CREATE_NO_WINDOW constant 134 | 135 | # Set LANG to English to ensure consistent output 136 | env = os.environ.copy() 137 | env["LANG"] = "en_US.UTF-8" 138 | env["LC_ALL"] = "en_US.UTF-8" 139 | 140 | result = subprocess.run( 141 | [self.kicad_cmd, "--version"], 142 | check=True, 143 | stdout=subprocess.PIPE, 144 | stderr=subprocess.PIPE, 145 | text=True, 146 | timeout=10, 147 | creationflags=creation_flags, 148 | env=env, 149 | ) 150 | version: str = result.stdout.strip() 151 | min_version: str = "8.0.4" 152 | kicad_vers: Tuple[int, int, int] = self.version_to_tuple(version) 153 | 154 | self.logger.info(f"KiCad Version: {version}") 155 | if not kicad_vers or kicad_vers < self.version_to_tuple(min_version): 156 | self.logger.warning(f"Minimum required KiCad version is: {min_version}") 157 | return False 158 | else: 159 | return True 160 | 161 | except subprocess.TimeoutExpired: 162 | self.logger.error("Timeout checking KiCad version") 163 | return False 164 | except (subprocess.CalledProcessError, FileNotFoundError): 165 | self.logger.error("kicad-cli does not exist or is not accessible") 166 | return False 167 | except Exception as e: 168 | self.logger.error(f"Unexpected error checking KiCad: {e}") 169 | return False 170 | 171 | def _is_valid_symbol_file(self, filepath: str) -> bool: 172 | """Check if file appears to be a valid KiCad symbol file.""" 173 | try: 174 | with open(filepath, "r", encoding="utf-8") as f: 175 | content = f.read(100) 176 | return content.strip().startswith("(kicad_symbol_lib") 177 | except (IOError, UnicodeDecodeError): 178 | return False 179 | 180 | def _validate_upgrade_result( 181 | self, input_file: str, output_file: str, result: CommandResult 182 | ) -> CommandResult: 183 | """Validate that the upgrade operation was successful.""" 184 | target_file = output_file if input_file != output_file else input_file 185 | 186 | if not os.path.exists(target_file): 187 | result.success = False 188 | result.message = f"Output file was not created: {target_file}" 189 | self.logger.error(result.message) 190 | return result 191 | 192 | if not self._is_valid_symbol_file(target_file): 193 | result.success = False 194 | result.message = ( 195 | f"Output file is not a valid KiCad symbol file: {target_file}" 196 | ) 197 | self.logger.error(result.message) 198 | return result 199 | 200 | output_text = (result.stdout + result.stderr).lower() 201 | success_indicators = ["successfully", "completed", "upgraded"] 202 | error_indicators = ["error", "failed", "cannot", "unable"] 203 | 204 | has_success = any(indicator in output_text for indicator in success_indicators) 205 | has_error = any(indicator in output_text for indicator in error_indicators) 206 | 207 | if has_error and not has_success: 208 | result.success = False 209 | result.message = "Error indicators found in command output" 210 | self.logger.warning(result.message) 211 | elif not has_success and result.success: 212 | result.message = "Command completed but no explicit success confirmation" 213 | self.logger.info(result.message) 214 | else: 215 | result.message = "Upgrade completed successfully" 216 | self.logger.info(result.message) 217 | 218 | return result 219 | 220 | def upgrade_sym_lib( 221 | self, input_file: str, output_file: str, force: bool = True 222 | ) -> CommandResult: 223 | """Upgrade a KiCad symbol library file to current format.""" 224 | input_file = str(input_file) 225 | output_file = str(output_file) 226 | if not os.path.exists(input_file): 227 | error_msg = f"Input file does not exist: {input_file}" 228 | self.logger.error(error_msg) 229 | return CommandResult(False, "", error_msg, -1, error_msg) 230 | 231 | # Validate file format 232 | if input_file.endswith(".lib"): 233 | try: 234 | with open(input_file, "r", encoding="utf-8") as f: 235 | if not f.readline().strip().startswith("EESchema-LIBRARY"): 236 | error_msg = ( 237 | f"Input file is not a valid KiCad .lib file: {input_file}" 238 | ) 239 | self.logger.error(error_msg) 240 | return CommandResult(False, "", error_msg, -1, error_msg) 241 | except Exception as e: 242 | error_msg = f"Failed to read file {input_file}: {e}" 243 | self.logger.error(error_msg) 244 | return CommandResult(False, "", error_msg, -1, error_msg) 245 | else: 246 | if not self._is_valid_symbol_file(input_file): 247 | error_msg = f"Input file is not a valid KiCad symbol file: {input_file}" 248 | self.logger.error(error_msg) 249 | return CommandResult(False, "", error_msg, -1, error_msg) 250 | 251 | backup_path = None 252 | if input_file == output_file: 253 | backup_path = f"{input_file}.backup" 254 | try: 255 | shutil.copy2(input_file, backup_path) 256 | self.logger.info(f"Created backup: {backup_path}") 257 | except Exception as e: 258 | error_msg = f"Failed to create backup: {e}" 259 | self.logger.error(error_msg) 260 | return CommandResult(False, "", str(e), -1, error_msg) 261 | 262 | try: 263 | if input_file == output_file: 264 | command = ["sym", "upgrade", input_file] 265 | else: 266 | command = ["sym", "upgrade", input_file, "-o", output_file] 267 | 268 | if force: 269 | command.append("--force") 270 | 271 | result = self.run_kicad_cli(command) 272 | 273 | if result.success: 274 | result = self._validate_upgrade_result(input_file, output_file, result) 275 | 276 | if result.success and backup_path and os.path.exists(backup_path): 277 | os.remove(backup_path) 278 | self.logger.info("Backup removed after successful upgrade") 279 | 280 | if not result.success and backup_path and os.path.exists(backup_path): 281 | try: 282 | shutil.move(backup_path, input_file) 283 | self.logger.info("Restored from backup after upgrade failure") 284 | except Exception as e: 285 | self.logger.error(f"Failed to restore backup: {e}") 286 | 287 | return result 288 | 289 | except Exception as e: 290 | if backup_path and os.path.exists(backup_path): 291 | try: 292 | shutil.move(backup_path, input_file) 293 | self.logger.info("Restored from backup after exception") 294 | except Exception as restore_e: 295 | self.logger.error( 296 | f"Failed to restore backup after exception: {restore_e}" 297 | ) 298 | 299 | error_msg = f"Unexpected error during upgrade: {e}" 300 | self.logger.error(error_msg) 301 | return CommandResult(False, "", str(e), -1, error_msg) 302 | 303 | def upgrade_sym_lib_from_string( 304 | self, symbol_lib_content: str, force: bool = True 305 | ) -> Tuple[bool, str, str]: 306 | """ 307 | Upgrade a KiCad symbol library from string content. 308 | 309 | Args: 310 | symbol_lib_content: String content of the symbol library 311 | force: Whether to force the upgrade operation 312 | 313 | Returns: 314 | Tuple of (success: bool, upgraded_content: str, error_message: str) 315 | - success: True if upgrade was successful 316 | - upgraded_content: The upgraded symbol library content (empty if failed) 317 | - error_message: Error message if upgrade failed (empty if successful) 318 | """ 319 | if not symbol_lib_content.strip(): 320 | error_msg = "Empty symbol library content provided" 321 | self.logger.error(error_msg) 322 | return False, "", error_msg 323 | 324 | content_start = symbol_lib_content.strip() 325 | is_legacy_lib = content_start.startswith("EESchema-LIBRARY") 326 | is_modern_lib = content_start.startswith("(kicad_symbol_lib") 327 | 328 | if not (is_legacy_lib or is_modern_lib): 329 | error_msg = "Content does not appear to be a valid KiCad symbol library" 330 | self.logger.error(error_msg) 331 | return False, "", error_msg 332 | 333 | file_extension = ".lib" if is_legacy_lib else ".kicad_sym" 334 | 335 | try: 336 | input_temp_dir = tempfile.mkdtemp(prefix="kicad_input_") 337 | output_temp_dir = tempfile.mkdtemp(prefix="kicad_output_") 338 | 339 | input_temp_path = os.path.join(input_temp_dir, f"input{file_extension}") 340 | output_temp_path = os.path.join(output_temp_dir, "output.kicad_sym") 341 | 342 | with open(input_temp_path, "w", encoding="utf-8") as f: 343 | f.write(symbol_lib_content) 344 | 345 | try: 346 | self.logger.info( 347 | f"Upgrading symbol library from string (temp files: {input_temp_path} -> {output_temp_path})" 348 | ) 349 | 350 | result = self.upgrade_sym_lib( 351 | input_temp_path, output_temp_path, force=force 352 | ) 353 | 354 | if result.success: 355 | try: 356 | with open(output_temp_path, "r", encoding="utf-8") as f: 357 | upgraded_content = f.read() 358 | 359 | self.logger.info( 360 | "Symbol library successfully upgraded from string" 361 | ) 362 | return True, upgraded_content, "" 363 | 364 | except Exception as e: 365 | error_msg = f"Failed to read upgraded content: {e}" 366 | self.logger.error(error_msg) 367 | return False, "", error_msg 368 | else: 369 | error_msg = f"Upgrade failed: {result.message}" 370 | if result.stderr: 371 | error_msg += f" - {result.stderr}" 372 | self.logger.error(error_msg) 373 | return False, "", error_msg 374 | 375 | finally: 376 | for temp_dir in [input_temp_dir, output_temp_dir]: 377 | try: 378 | if os.path.exists(temp_dir): 379 | shutil.rmtree(temp_dir) 380 | self.logger.debug( 381 | f"Cleaned up temporary directory: {temp_dir}" 382 | ) 383 | except Exception as cleanup_error: 384 | self.logger.warning( 385 | f"Failed to cleanup temporary directory {temp_dir}: {cleanup_error}" 386 | ) 387 | 388 | except Exception as e: 389 | error_msg = f"Failed to create temporary files: {e}" 390 | self.logger.error(error_msg) 391 | return False, "", error_msg 392 | 393 | def upgrade_footprint_lib( 394 | self, 395 | pretty_folder: str, 396 | output_folder: Optional[str] = None, 397 | force: bool = False, 398 | ) -> CommandResult: 399 | """Upgrade a KiCad footprint library folder to current format.""" 400 | pretty_folder = str(pretty_folder) 401 | 402 | if not os.path.exists(pretty_folder): 403 | error_msg = f"Footprint folder does not exist: {pretty_folder}" 404 | self.logger.error(error_msg) 405 | return CommandResult(False, "", error_msg, -1, error_msg) 406 | 407 | if not os.path.isdir(pretty_folder): 408 | error_msg = f"Path is not a directory: {pretty_folder}" 409 | self.logger.error(error_msg) 410 | return CommandResult(False, "", error_msg, -1, error_msg) 411 | 412 | command = ["fp", "upgrade", pretty_folder] 413 | 414 | if output_folder is not None: 415 | output_folder = str(output_folder) 416 | command.extend(["-o", output_folder]) 417 | 418 | if force: 419 | command.append("--force") 420 | 421 | result = self.run_kicad_cli(command) 422 | 423 | target_folder = output_folder if output_folder is not None else pretty_folder 424 | 425 | if result.success and not os.path.exists(target_folder): 426 | result.success = False 427 | result.message = ( 428 | f"Footprint folder disappeared after upgrade: {target_folder}" 429 | ) 430 | self.logger.error(result.message) 431 | elif result.success: 432 | upgrade_mode = ( 433 | "to output folder" if output_folder is not None else "in-place" 434 | ) 435 | result.message = ( 436 | f"Footprint library upgrade completed successfully ({upgrade_mode})" 437 | ) 438 | self.logger.info(result.message) 439 | 440 | return result 441 | 442 | 443 | if __name__ == "__main__": 444 | logging.basicConfig( 445 | level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s" 446 | ) 447 | 448 | cli: kicad_cli = kicad_cli() 449 | 450 | if not cli.exists(): 451 | print("KiCad CLI not found or version too old!") 452 | exit(1) 453 | 454 | input_file: str = "UltraLibrarian_kicad_sym.kicad_sym" 455 | output_file: str = "UltraLibrarian.kicad_sym" 456 | 457 | result = cli.upgrade_sym_lib(input_file, output_file) 458 | 459 | print(f"Symbol library upgrade: {'SUCCESS' if result.success else 'FAILED'}") 460 | print(f"Message: {result.message}") 461 | if not result.success: 462 | print(f"Error details: {result.stderr}") 463 | 464 | result2 = cli.upgrade_footprint_lib("test.pretty", force=True) 465 | 466 | print(f"Footprint library upgrade: {'SUCCESS' if result2.success else 'FAILED'}") 467 | print(f"Message: {result2.message}") 468 | if not result2.success: 469 | print(f"Error details: {result2.stderr}") 470 | -------------------------------------------------------------------------------- /plugins/KiCadSettingsPaths/__init__.py: -------------------------------------------------------------------------------- 1 | """ 2 | KiCad Settings Paths and Application Interface Module 3 | 4 | Provides utilities for detecting KiCad settings paths across different operating systems 5 | and a simplified interface for interacting with KiCad applications. 6 | """ 7 | 8 | import logging 9 | import platform 10 | import sys 11 | from pathlib import Path 12 | from typing import Any, Callable, Dict, List, Optional, Tuple 13 | 14 | 15 | class KiCadSettingsPaths: 16 | """Utility class for detecting KiCad settings paths across different operating systems.""" 17 | 18 | @staticmethod 19 | def get_default_settings_path() -> Path: 20 | """Returns the default settings path for the current operating system.""" 21 | system = platform.system() 22 | home = Path.home() 23 | 24 | if system == "Windows": 25 | return home / "AppData" / "Roaming" / "kicad" 26 | elif system == "Darwin": # macOS 27 | return home / "Library" / "Preferences" / "kicad" 28 | else: # Linux and Unix-like systems 29 | # Check XDG_CONFIG_HOME environment variable 30 | import os 31 | 32 | xdg_config = os.environ.get("XDG_CONFIG_HOME") 33 | if xdg_config: 34 | return Path(xdg_config) / "kicad" 35 | return home / ".config" / "kicad" 36 | 37 | @staticmethod 38 | def find_all_possible_paths() -> List[Path]: 39 | """Discovers all possible KiCad settings paths on the current system.""" 40 | paths: List[Path] = [] 41 | system = platform.system() 42 | home = Path.home() 43 | 44 | try: 45 | if system == "Windows": 46 | base_paths = [ 47 | home / "AppData" / "Roaming" / "kicad", 48 | home / "AppData" / "Local" / "kicad", 49 | Path("C:/ProgramData/kicad"), 50 | ] 51 | paths.extend(base_paths) 52 | 53 | # Version-specific subdirectories 54 | roaming_kicad = home / "AppData" / "Roaming" / "kicad" 55 | if roaming_kicad.exists(): 56 | for major in range(5, 12): 57 | for minor in range(0, 10): 58 | version_path = roaming_kicad / f"{major}.{minor}" 59 | if version_path.exists(): 60 | paths.append(version_path) 61 | 62 | elif system == "Darwin": # macOS 63 | paths.extend( 64 | [ 65 | home / "Library" / "Preferences" / "kicad", 66 | home / "Library" / "Application Support" / "kicad", 67 | ] 68 | ) 69 | 70 | else: # Linux and Unix-like systems 71 | paths.extend( 72 | [ 73 | home / ".config" / "kicad", 74 | home / ".kicad", 75 | Path("/usr/share/kicad"), 76 | Path("/usr/local/share/kicad"), 77 | ] 78 | ) 79 | 80 | # Check XDG_CONFIG_HOME 81 | import os 82 | 83 | xdg_config = os.environ.get("XDG_CONFIG_HOME") 84 | if xdg_config: 85 | xdg_kicad_path = Path(xdg_config) / "kicad" 86 | if xdg_kicad_path not in paths: 87 | paths.append(xdg_kicad_path) 88 | 89 | except (OSError, PermissionError) as e: 90 | print(f"Warning: Error accessing paths during discovery: {e}") 91 | 92 | return [path for path in paths if path.exists()] 93 | 94 | @staticmethod 95 | def find_actual_settings_path() -> Path: 96 | """ 97 | Locates the actual KiCad settings path by searching for configuration files. 98 | Returns the default path if no actual settings are found. 99 | """ 100 | possible_paths = KiCadSettingsPaths.find_all_possible_paths() 101 | config_files = [ 102 | "kicad_common.json", 103 | "eeschema.json", 104 | "pcbnew.json", 105 | "kicad.json", 106 | ] 107 | 108 | for path in possible_paths: 109 | try: 110 | for config_file in config_files: 111 | config_path = path / config_file 112 | if config_path.is_file(): 113 | return path 114 | except (OSError, PermissionError): 115 | continue 116 | 117 | return KiCadSettingsPaths.get_default_settings_path() 118 | 119 | 120 | class KiCadVersionInfo: 121 | """Container for KiCad version information.""" 122 | 123 | def __init__(self, version_tuple: Tuple[int, int, int], full_version: str): 124 | self.major, self.minor, self.patch = version_tuple 125 | self.version_tuple = version_tuple 126 | self.full_version = full_version 127 | 128 | def __str__(self) -> str: 129 | return f"{self.major}.{self.minor}.{self.patch}" 130 | 131 | def __repr__(self) -> str: 132 | return f"KiCadVersionInfo({self.version_tuple}, '{self.full_version}')" 133 | 134 | 135 | class KiCadProjectInfo: 136 | """Container for KiCad project information.""" 137 | 138 | def __init__( 139 | self, 140 | name: Optional[str] = None, 141 | directory: Optional[Path] = None, 142 | board_filename: Optional[Path] = None, 143 | ): 144 | self.name = name 145 | self.directory = directory 146 | self.board_filename = board_filename 147 | 148 | @property 149 | def is_valid(self) -> bool: 150 | """Returns True if project information is available.""" 151 | return any([self.name, self.directory, self.board_filename]) 152 | 153 | @property 154 | def directory_str(self) -> Optional[str]: 155 | """Returns directory as string for backward compatibility.""" 156 | return str(self.directory) if self.directory else None 157 | 158 | @property 159 | def board_filename_str(self) -> Optional[str]: 160 | """Returns board filename as string for backward compatibility.""" 161 | return str(self.board_filename) if self.board_filename else None 162 | 163 | 164 | class KiCadApp: 165 | """ 166 | Simplified KiCad application interface with direct property access. 167 | 168 | All properties are loaded during initialization and can be accessed directly: 169 | - app.connection_type: "IPC", "SWIG", or "FALLBACK" 170 | - app.settings_path: Path to KiCad settings directory 171 | - app.version_info: KiCadVersionInfo object with version details 172 | - app.project_info: KiCadProjectInfo object with project details 173 | - app.is_connected: Boolean indicating if KiCad connection is available 174 | """ 175 | 176 | def __init__(self, prefer_ipc: bool = True, min_version: str = "8.0.0"): 177 | """ 178 | Initializes the KiCad application interface and loads all properties. 179 | 180 | Args: 181 | prefer_ipc: Whether to prefer IPC API over SWIG bindings 182 | min_version: Minimum required KiCad version 183 | """ 184 | self.min_version = min_version 185 | self.connection_type: str = "FALLBACK" 186 | self.pcbnew: Optional[Any] = None 187 | self.kicad_ipc: Optional[Any] = None 188 | self.kipy_errors: Optional[Any] = None 189 | 190 | # Initialize all properties with default values 191 | self.settings_path: Path = KiCadSettingsPaths.find_actual_settings_path() 192 | self.version_info: Optional[KiCadVersionInfo] = None 193 | self.project_info: KiCadProjectInfo = KiCadProjectInfo() 194 | self.is_connected: bool = False 195 | 196 | # Try to establish connection and load properties 197 | if prefer_ipc and self._try_init_ipc(): 198 | self.connection_type = "IPC" 199 | self.is_connected = True 200 | self._load_ipc_properties() 201 | elif self._try_init_swig(): 202 | self.connection_type = "SWIG" 203 | self.is_connected = True 204 | self._load_swig_properties() 205 | else: 206 | print( 207 | "Warning: Neither IPC API nor SWIG bindings available. Limited functionality." 208 | ) 209 | 210 | def _setup_venv_path(self) -> None: 211 | """Sets up virtual environment path for IPC API imports.""" 212 | try: 213 | import os 214 | 215 | venv = os.environ.get("VIRTUAL_ENV") 216 | if venv: 217 | venv_path = Path(venv) 218 | version = f"python{sys.version_info.major}.{sys.version_info.minor}" 219 | venv_site_packages = venv_path / "lib" / version / "site-packages" 220 | 221 | venv_site_packages_str = str(venv_site_packages) 222 | if venv_site_packages_str in sys.path: 223 | sys.path.remove(venv_site_packages_str) 224 | sys.path.insert(0, venv_site_packages_str) 225 | except Exception as e: 226 | logging.exception("Error setting up virtual environment path: %s", e) 227 | 228 | def _try_init_ipc(self) -> bool: 229 | """Attempts to initialize IPC API connection.""" 230 | try: 231 | self._setup_venv_path() 232 | from kipy import KiCad, errors 233 | 234 | self.kipy_errors = errors 235 | self.kicad_ipc = KiCad() 236 | 237 | # Test connection 238 | if self.kicad_ipc is not None: 239 | self.kicad_ipc.get_version() 240 | return True 241 | 242 | except ImportError: 243 | print("KiCad IPC API not available") 244 | return False 245 | except Exception as e: 246 | print(f"KiCad IPC API initialization failed: {e}") 247 | return False 248 | 249 | def _try_init_swig(self) -> bool: 250 | """Attempts to initialize SWIG (pcbnew) connection.""" 251 | try: 252 | import pcbnew 253 | 254 | self.pcbnew = pcbnew 255 | return True 256 | except ImportError: 257 | print("SWIG bindings (pcbnew) not available") 258 | return False 259 | except Exception as e: 260 | print(f"SWIG initialization failed: {e}") 261 | return False 262 | 263 | def _load_ipc_properties(self) -> None: 264 | """Loads all properties using IPC API.""" 265 | if not self.kicad_ipc or not self.kipy_errors: 266 | return 267 | 268 | try: 269 | # Version information 270 | version_info = self.kicad_ipc.get_version() 271 | version_tuple = (version_info.major, version_info.minor, version_info.patch) 272 | self.version_info = KiCadVersionInfo( 273 | version_tuple, version_info.full_version 274 | ) 275 | 276 | # Project and board information 277 | self._load_ipc_project_info() 278 | 279 | except Exception as e: 280 | print(f"Error loading IPC properties: {e}") 281 | 282 | def _load_swig_properties(self) -> None: 283 | """Loads all properties using SWIG (pcbnew).""" 284 | if not self.pcbnew: 285 | return 286 | 287 | try: 288 | # Settings path 289 | settings_manager = self.pcbnew.SETTINGS_MANAGER() 290 | settings_path_str = settings_manager.GetUserSettingsPath() 291 | self.settings_path = Path(settings_path_str) 292 | 293 | # Version information 294 | version_str = self.pcbnew.Version() 295 | version_tuple = self._version_to_tuple(version_str) 296 | full_version = self.pcbnew.FullVersion() 297 | self.version_info = KiCadVersionInfo(version_tuple, full_version) 298 | 299 | # Board and project information 300 | self._load_swig_project_info() 301 | 302 | except Exception as e: 303 | print(f"Error loading SWIG properties: {e}") 304 | 305 | def _version_to_tuple(self, version_str: str) -> Tuple[int, int, int]: 306 | """Converts a version string to a tuple of integers.""" 307 | try: 308 | clean_version = version_str.split("-")[0] 309 | parts = clean_version.split(".") 310 | # Ensure we have at least 3 parts 311 | while len(parts) < 3: 312 | parts.append("0") 313 | return (int(parts[0]), int(parts[1]), int(parts[2])) 314 | except (ValueError, AttributeError, TypeError, IndexError): 315 | return (0, 0, 0) 316 | 317 | def _load_ipc_project_info(self) -> None: 318 | """Loads project info using IPC API.""" 319 | if not self.kicad_ipc or not self.kipy_errors: 320 | return 321 | 322 | try: 323 | board = self.kicad_ipc.get_board() 324 | board_filename = Path(board.name) if board.name else None 325 | 326 | project = board.get_project() 327 | project_name = project.name 328 | project_dir = Path(project.path) if project.path else None 329 | 330 | self.project_info = KiCadProjectInfo( 331 | name=project_name, directory=project_dir, board_filename=board_filename 332 | ) 333 | 334 | except self.kipy_errors.ApiError: 335 | # No PCB open - this is normal 336 | self.project_info = KiCadProjectInfo() 337 | except Exception as e: 338 | print(f"Warning: Could not load project information: {e}") 339 | self.project_info = KiCadProjectInfo() 340 | 341 | def _load_swig_project_info(self) -> None: 342 | """Loads project info using SWIG.""" 343 | if not self.pcbnew: 344 | return 345 | 346 | try: 347 | board = self.pcbnew.GetBoard() 348 | board_filename_str = board.GetFileName() 349 | 350 | project_name = None 351 | project_dir = None 352 | board_filename = None 353 | 354 | if board_filename_str: 355 | board_filename = Path(board_filename_str) 356 | project_dir = board_filename.parent 357 | project_name = board_filename.stem 358 | 359 | self.project_info = KiCadProjectInfo( 360 | name=project_name, directory=project_dir, board_filename=board_filename 361 | ) 362 | 363 | except Exception as e: 364 | print(f"Warning: Could not load board information: {e}") 365 | self.project_info = KiCadProjectInfo() 366 | 367 | @property 368 | def version(self) -> Optional[Tuple[int, int, int]]: 369 | """Returns version tuple.""" 370 | return self.version_info.version_tuple if self.version_info else None 371 | 372 | @property 373 | def full_version(self) -> str: 374 | """Returns full version string.""" 375 | return self.version_info.full_version if self.version_info else "Unknown" 376 | 377 | @property 378 | def project_name(self) -> Optional[str]: 379 | """Returns project name.""" 380 | return self.project_info.name 381 | 382 | @property 383 | def project_dir(self) -> Optional[str]: 384 | """Returns project directory as string.""" 385 | return self.project_info.directory_str 386 | 387 | @property 388 | def board_filename(self) -> Optional[str]: 389 | """Returns board filename as string.""" 390 | return self.project_info.board_filename_str 391 | 392 | def get_board_filename(self) -> Optional[str]: 393 | """Returns the filename of the current board.""" 394 | return self.board_filename 395 | 396 | def get_project_dir(self) -> Optional[str]: 397 | """Returns the directory of the current KiCad project.""" 398 | return self.project_dir 399 | 400 | def path_settings(self) -> str: 401 | """Returns the settings path as string.""" 402 | return str(self.settings_path) 403 | 404 | def check_min_version(self, output_func: Callable[[str], None] = print) -> bool: 405 | """ 406 | Checks if the current KiCad version meets the minimum required version. 407 | 408 | Args: 409 | output_func: Function for outputting messages (default: print) 410 | 411 | Returns: 412 | True if version is sufficient, False otherwise 413 | """ 414 | try: 415 | min_version_tuple = self._version_to_tuple(self.min_version) 416 | 417 | if ( 418 | not self.version_info 419 | or self.version_info.version_tuple < min_version_tuple 420 | ): 421 | output_func(f"KiCad Version: {self.full_version}") 422 | output_func(f"Minimum required KiCad version is {self.min_version}") 423 | output_func("This may limit the functionality of the plugin.") 424 | return False 425 | 426 | return True 427 | 428 | except Exception as e: 429 | print(f"Error during KiCad version check: {e}") 430 | return False 431 | 432 | def refresh_project_info(self) -> None: 433 | """ 434 | Refreshes project and board information. 435 | Useful when project has changed after initialization. 436 | """ 437 | if self.connection_type == "IPC": 438 | self._load_ipc_project_info() 439 | elif self.connection_type == "SWIG": 440 | self._load_swig_project_info() 441 | 442 | def get_info(self) -> Dict[str, Any]: 443 | """Returns all loaded information as a dictionary.""" 444 | return { 445 | "connection_type": self.connection_type, 446 | "is_connected": self.is_connected, 447 | "settings_path": str(self.settings_path), 448 | "version": self.version, 449 | "full_version": self.full_version, 450 | "project_name": self.project_name, 451 | "project_dir": self.project_dir, 452 | "board_filename": self.board_filename, 453 | "min_version": self.min_version, 454 | "version_sufficient": self.check_min_version(lambda x: None), 455 | "project_valid": self.project_info.is_valid, 456 | } 457 | 458 | def print_info(self) -> None: 459 | """Prints a formatted summary of all loaded information.""" 460 | print("=== KiCad Application Information ===") 461 | print(f"Connection Type: {self.connection_type}") 462 | print(f"Connected: {self.is_connected}") 463 | print(f"Settings Path: {self.settings_path}") 464 | print(f"Version: {self.full_version}") 465 | 466 | if self.check_min_version(lambda x: None): 467 | print("✓ Version meets requirements") 468 | else: 469 | print("⚠ Version may be insufficient") 470 | 471 | if self.is_connected: 472 | print("\n=== Project Information ===") 473 | if self.project_info.is_valid: 474 | if self.project_name: 475 | print(f"Project Name: {self.project_name}") 476 | if self.project_dir: 477 | print(f"Project Directory: {self.project_dir}") 478 | if self.board_filename: 479 | print(f"Board Filename: {self.board_filename}") 480 | else: 481 | print("No project currently open or accessible") 482 | 483 | 484 | def connect_kicad() -> Optional[Any]: 485 | """ 486 | Connect to KiCad IPC API 487 | 488 | Returns: 489 | KiCad IPC connection object or None if not available 490 | """ 491 | app = KiCadApp(prefer_ipc=True) 492 | if app.connection_type == "IPC": 493 | return app.kicad_ipc 494 | else: 495 | print("Not connected to KiCad IPC API") 496 | return None 497 | 498 | 499 | def main() -> None: 500 | """Example usage of the simplified KiCad application interface.""" 501 | # Initialize KiCad app - all properties are loaded automatically 502 | app = KiCadApp(prefer_ipc=True, min_version="9.0.0") 503 | 504 | # Direct access to all properties 505 | print(f"Connection: {app.connection_type}") 506 | print(f"Project: {app.project_name}") 507 | print(f"Directory: {app.project_dir}") 508 | 509 | # Or print complete information 510 | app.print_info() 511 | 512 | # Check version requirements 513 | if not app.check_min_version(): 514 | print("Version check failed") 515 | 516 | # Refresh project info if needed 517 | app.refresh_project_info() 518 | 519 | 520 | if __name__ == "__main__": 521 | main() 522 | -------------------------------------------------------------------------------- /plugins/KiCad_Settings/__init__.py: -------------------------------------------------------------------------------- 1 | import json 2 | import logging 3 | import os 4 | from pathlib import Path 5 | from typing import Any, Dict, List, Tuple 6 | 7 | current_dir = Path(__file__).resolve().parent 8 | kiutils_src = current_dir.parent / "kiutils" / "src" 9 | if str(kiutils_src) not in __import__("sys").path: 10 | __import__("sys").path.insert(0, str(kiutils_src)) 11 | 12 | from kiutils.libraries import Library, LibTable 13 | 14 | 15 | class KiCad_Settings: 16 | def __init__( 17 | self, SettingPath: str, path_prefix: str = "${KICAD_3RD_PARTY}" 18 | ) -> None: 19 | self.logger = logging.getLogger(__name__) 20 | self.path_prefix = path_prefix 21 | base_path = Path(SettingPath) 22 | 23 | if ( 24 | not (base_path / "sym-lib-table").exists() 25 | and not (base_path / "fp-lib-table").exists() 26 | ): 27 | version_dirs = [ 28 | d 29 | for d in base_path.iterdir() 30 | if d.is_dir() and d.name.replace(".", "").isdigit() 31 | ] 32 | 33 | if version_dirs: 34 | # Sort by version and take the highest 35 | latest_version = max( 36 | version_dirs, 37 | key=lambda x: tuple( 38 | int(p) for p in x.name.split(".") if p.isdigit() 39 | ), 40 | ) 41 | self.SettingPath = str(latest_version) 42 | self.logger.info( 43 | f"Auto-detected KiCad version directory: {self.SettingPath}" 44 | ) 45 | else: 46 | self.SettingPath = SettingPath 47 | else: 48 | self.SettingPath = SettingPath 49 | 50 | self.logger.info(f"Initializing KiCad_Settings with path: {SettingPath}") 51 | 52 | def get_sym_table(self) -> List[Dict[str, str]]: 53 | path = os.path.join(self.SettingPath, "sym-lib-table") 54 | self.logger.debug(f"Attempting to read symbol library table from: {path}") 55 | 56 | try: 57 | if not os.path.exists(path): 58 | self.logger.info( 59 | f"Symbol library table not found, creating empty table: {path}" 60 | ) 61 | empty_table = LibTable() 62 | empty_table.to_file(path) 63 | 64 | sym_table = LibTable.from_file(path) 65 | self.logger.info( 66 | f"Successfully loaded symbol library table with {len(sym_table.libs)} entries" 67 | ) 68 | 69 | # Convert libraries to dictionaries 70 | result = [ 71 | { 72 | "name": lib.name, 73 | "type": lib.type, 74 | "uri": lib.uri, 75 | "options": lib.options, 76 | "descr": lib.description, 77 | } 78 | for lib in sym_table.libs 79 | ] 80 | return result 81 | 82 | except FileNotFoundError: 83 | self.logger.warning(f"Symbol library table not found: {path}") 84 | return [] 85 | except Exception as e: 86 | self.logger.error(f"Failed to parse symbol library table from {path}: {e}") 87 | return [] 88 | 89 | def set_sym_table(self, libname: str, libpath: str) -> None: 90 | path = os.path.join(self.SettingPath, "sym-lib-table") 91 | self.logger.debug( 92 | f"Adding symbol library '{libname}' with path '{libpath}' to {path}" 93 | ) 94 | 95 | try: 96 | if not os.path.exists(path): 97 | self.logger.info( 98 | f"Symbol library table not found, creating empty table: {path}" 99 | ) 100 | empty_table = LibTable() 101 | empty_table.to_file(path) 102 | 103 | sym_table = LibTable.from_file(path) 104 | 105 | # Check if library already exists 106 | for lib in sym_table.libs: 107 | if lib.name == libname: 108 | self.logger.error( 109 | f"Symbol library '{libname}' already exists in table" 110 | ) 111 | raise ValueError(f"Entry with the name '{libname}' already exists.") 112 | 113 | # Create new library and add it to the table 114 | new_lib = Library( 115 | name=libname, type="KiCad", uri=libpath, options="", description="" 116 | ) 117 | sym_table.libs.append(new_lib) 118 | sym_table.to_file(path) 119 | 120 | self.logger.info(f"Successfully added symbol library '{libname}' to table") 121 | 122 | except Exception as e: 123 | self.logger.error(f"Failed to add symbol library '{libname}': {e}") 124 | raise 125 | 126 | def sym_table_change_entry(self, old_uri: str, new_uri: str) -> None: 127 | path = os.path.join(self.SettingPath, "sym-lib-table") 128 | self.logger.debug( 129 | f"Changing symbol library URI from '{old_uri}' to '{new_uri}'" 130 | ) 131 | 132 | try: 133 | sym_table = LibTable.from_file(path) 134 | 135 | uri_found = False 136 | for lib in sym_table.libs: 137 | if lib.uri == old_uri: 138 | lib.uri = new_uri 139 | uri_found = True 140 | self.logger.info( 141 | f"Changed URI for library '{lib.name}' from '{old_uri}' to '{new_uri}'" 142 | ) 143 | break 144 | 145 | if not uri_found: 146 | self.logger.error(f"URI '{old_uri}' not found in symbol library table") 147 | raise ValueError(f"URI '{old_uri}' not found in the file.") 148 | 149 | sym_table.to_file(path) 150 | self.logger.info("Successfully updated symbol library table") 151 | 152 | except Exception as e: 153 | self.logger.error(f"Failed to change symbol library URI: {e}") 154 | raise 155 | 156 | def get_lib_table(self) -> List[Dict[str, str]]: 157 | path = os.path.join(self.SettingPath, "fp-lib-table") 158 | self.logger.debug(f"Attempting to read footprint library table from: {path}") 159 | 160 | try: 161 | if not os.path.exists(path): 162 | self.logger.info( 163 | f"Footprint library table not found, creating empty table: {path}" 164 | ) 165 | empty_table = LibTable() 166 | empty_table.to_file(path) 167 | 168 | fp_table = LibTable.from_file(path) 169 | self.logger.info( 170 | f"Successfully loaded footprint library table with {len(fp_table.libs)} entries" 171 | ) 172 | 173 | # Convert libraries to dictionaries 174 | result = [ 175 | { 176 | "name": lib.name, 177 | "type": lib.type, 178 | "uri": lib.uri, 179 | "options": lib.options, 180 | "descr": lib.description, 181 | } 182 | for lib in fp_table.libs 183 | ] 184 | return result 185 | 186 | except FileNotFoundError: 187 | self.logger.warning(f"Footprint library table not found: {path}") 188 | return [] 189 | except Exception as e: 190 | self.logger.error( 191 | f"Failed to parse footprint library table from {path}: {e}" 192 | ) 193 | return [] 194 | 195 | def set_lib_table_entry(self, libname: str) -> None: 196 | path = os.path.join(self.SettingPath, "fp-lib-table") 197 | self.logger.debug(f"Adding footprint library '{libname}' to {path}") 198 | 199 | try: 200 | if not os.path.exists(path): 201 | self.logger.info( 202 | f"Footprint library table not found, creating empty table: {path}" 203 | ) 204 | empty_table = LibTable() 205 | empty_table.to_file(path) 206 | 207 | fp_table = LibTable.from_file(path) 208 | 209 | # Check if library already exists 210 | for lib in fp_table.libs: 211 | if lib.name == libname: 212 | self.logger.error( 213 | f"Footprint library '{libname}' already exists in table" 214 | ) 215 | raise ValueError(f"Entry with the name '{libname}' already exists.") 216 | 217 | uri_lib = self.path_prefix + "/" + libname + ".pretty" 218 | new_lib = Library( 219 | name=libname, type="KiCad", uri=uri_lib, options="", description="" 220 | ) 221 | fp_table.libs.append(new_lib) 222 | fp_table.to_file(path) 223 | 224 | self.logger.info( 225 | f"Successfully added footprint library '{libname}' with URI '{uri_lib}'" 226 | ) 227 | 228 | except Exception as e: 229 | self.logger.error(f"Failed to add footprint library '{libname}': {e}") 230 | raise 231 | 232 | def get_kicad_json(self) -> Dict[str, Any]: 233 | path = os.path.join(self.SettingPath, "kicad.json") 234 | self.logger.debug(f"Attempting to read KiCad JSON config from: {path}") 235 | 236 | try: 237 | with open(path) as json_data: 238 | data = json.load(json_data) 239 | self.logger.info("Successfully loaded KiCad JSON config") 240 | return data 241 | 242 | except FileNotFoundError: 243 | self.logger.warning(f"KiCad JSON config not found: {path}") 244 | return {} 245 | except json.JSONDecodeError as e: 246 | self.logger.error(f"Invalid JSON in KiCad config file {path}: {e}") 247 | return {} 248 | except Exception as e: 249 | self.logger.error(f"Failed to read KiCad JSON config from {path}: {e}") 250 | return {} 251 | 252 | def set_kicad_json(self, kicad_json: Dict[str, Any]) -> None: 253 | path = os.path.join(self.SettingPath, "kicad.json") 254 | self.logger.debug(f"Writing KiCad JSON config to: {path}") 255 | 256 | try: 257 | with open(path, "w") as file: 258 | json.dump(kicad_json, file, indent=2) 259 | self.logger.info("Successfully wrote KiCad JSON config") 260 | 261 | except Exception as e: 262 | self.logger.error(f"Failed to write KiCad JSON config to {path}: {e}") 263 | raise 264 | 265 | def get_kicad_common(self) -> Dict[str, Any]: 266 | path = os.path.join(self.SettingPath, "kicad_common.json") 267 | self.logger.debug(f"Attempting to read KiCad common config from: {path}") 268 | 269 | try: 270 | with open(path) as json_data: 271 | data = json.load(json_data) 272 | self.logger.info("Successfully loaded KiCad common config") 273 | return data 274 | 275 | except FileNotFoundError: 276 | self.logger.warning(f"KiCad common config not found: {path}") 277 | return {"environment": {"vars": {}}} 278 | except json.JSONDecodeError as e: 279 | self.logger.error(f"Invalid JSON in KiCad common config file {path}: {e}") 280 | return {"environment": {"vars": {}}} 281 | except Exception as e: 282 | self.logger.error(f"Failed to read KiCad common config from {path}: {e}") 283 | return {"environment": {"vars": {}}} 284 | 285 | def set_kicad_common(self, kicad_common: Dict[str, Any]) -> None: 286 | path = os.path.join(self.SettingPath, "kicad_common.json") 287 | self.logger.debug(f"Writing KiCad common config to: {path}") 288 | 289 | try: 290 | with open(path, "w") as file: 291 | json.dump(kicad_common, file, indent=2) 292 | self.logger.info("Successfully wrote KiCad common config") 293 | 294 | except Exception as e: 295 | self.logger.error(f"Failed to write KiCad common config to {path}: {e}") 296 | raise 297 | 298 | def get_kicad_GlobalVars(self) -> Dict[str, str]: 299 | self.logger.debug("Getting KiCad global variables") 300 | 301 | try: 302 | KiCadjson = self.get_kicad_common() 303 | global_vars = KiCadjson.get("environment", {}).get("vars", {}) 304 | self.logger.info(f"Found {len(global_vars)} global variables") 305 | return global_vars 306 | 307 | except Exception as e: 308 | self.logger.error(f"Failed to get KiCad global variables: {e}") 309 | return {} 310 | 311 | def check_footprintlib(self, SearchLib, add_if_possible=True): 312 | msg = "" 313 | try: 314 | FootprintTable = self.get_lib_table() 315 | FootprintLibs = {lib["name"]: lib for lib in FootprintTable} 316 | 317 | temp_path = self.path_prefix + "/" + SearchLib + ".pretty" 318 | if SearchLib in FootprintLibs: 319 | if not FootprintLibs[SearchLib]["uri"] == temp_path: 320 | msg += "\n" + SearchLib 321 | msg += " in the Footprint Libraries is not imported correctly." 322 | msg += "\nYou have to import the library " + SearchLib 323 | msg += "' with the path '" + temp_path + "' in Footprint Libraries." 324 | if add_if_possible: 325 | msg += ( 326 | "\nThe entry must either be corrected manually or deleted." 327 | ) 328 | # self.set_lib_table_entry(SearchLib) # TODO 329 | else: 330 | msg += "\n" + SearchLib + " is not in the Footprint Libraries." 331 | if add_if_possible: 332 | try: 333 | self.set_lib_table_entry(SearchLib) 334 | msg += "\nThe library " + SearchLib 335 | msg += " has been successfully added." 336 | msg += "\n##### A restart of KiCad is necessary. #####" 337 | except Exception: 338 | msg += "\nFailed to add library automatically." 339 | else: 340 | msg += "\nYou have to import the library " + SearchLib 341 | msg += "' with the path '" + temp_path 342 | msg += ( 343 | "' in the Footprint Libraries or select the automatic option." 344 | ) 345 | except Exception: 346 | msg += f"\nError checking footprint library {SearchLib}." 347 | 348 | return msg 349 | 350 | def check_symbollib(self, SearchLib: str, add_if_possible: bool = True): 351 | msg = "" 352 | try: 353 | SearchLib_name = SearchLib.split(".")[0] 354 | SearchLib_name_short = SearchLib_name.split("_")[0] 355 | 356 | SymbolTable = self.get_sym_table() 357 | SymbolLibs = {lib["name"]: lib for lib in SymbolTable} 358 | SymbolLibsUri = {lib["uri"]: lib for lib in SymbolTable} 359 | 360 | temp_path = self.path_prefix + "/" + SearchLib 361 | 362 | if temp_path not in SymbolLibsUri: 363 | msg += ( 364 | "\n'" + temp_path + "' is not imported into the Symbol Libraries." 365 | ) 366 | if add_if_possible: 367 | try: 368 | if SearchLib_name_short not in SymbolLibs: 369 | self.set_sym_table(SearchLib_name_short, temp_path) 370 | msg += "\nThe library " + SearchLib 371 | msg += " has been successfully added." 372 | msg += "\n##### A restart of KiCad is necessary. #####" 373 | elif SearchLib_name not in SymbolLibs: 374 | self.set_sym_table(SearchLib_name, temp_path) 375 | msg += "\nThe library " + SearchLib 376 | msg += " has been successfully added." 377 | msg += "\n##### A restart of KiCad is necessary. #####" 378 | else: 379 | msg += "\nThe entry must either be corrected manually or deleted." 380 | # self.set_sym_table(SearchLib_name, temp_path) # TODO 381 | except Exception: 382 | msg += "\nFailed to add symbol library automatically." 383 | else: 384 | msg += ( 385 | "\nYou must add them manually or select the automatic option." 386 | ) 387 | except Exception: 388 | msg += f"\nError checking symbol library {SearchLib}." 389 | 390 | return msg 391 | 392 | def check_GlobalVar(self, LocalLibFolder, add_if_possible=True): 393 | msg = "" 394 | GlobalVars = self.get_kicad_GlobalVars() 395 | 396 | def setup_kicad_common(): 397 | kicad_common = self.get_kicad_common() 398 | # Ensure the nested structure exists 399 | if "environment" not in kicad_common: 400 | kicad_common["environment"] = {} 401 | if "vars" not in kicad_common["environment"]: 402 | kicad_common["environment"]["vars"] = {} 403 | 404 | kicad_common["environment"]["vars"]["KICAD_3RD_PARTY"] = LocalLibFolder 405 | self.set_kicad_common(kicad_common) 406 | 407 | if GlobalVars and "KICAD_3RD_PARTY" in GlobalVars: 408 | if not GlobalVars["KICAD_3RD_PARTY"] == LocalLibFolder: 409 | msg += "\nKICAD_3RD_PARTY is defined as '" 410 | msg += GlobalVars["KICAD_3RD_PARTY"] 411 | msg += "' and not '" + LocalLibFolder + "'." 412 | if add_if_possible: 413 | setup_kicad_common() 414 | msg += "\nThe entry was changed automatically." 415 | msg += "\n##### A restart of KiCad is necessary. #####" 416 | else: 417 | msg += "\nChange the entry or select the automatic option." 418 | else: 419 | msg += "\nKICAD_3RD_PARTY" + " is not defined in Environment Variables." 420 | if add_if_possible: 421 | setup_kicad_common() 422 | msg += "\nThe entry has been added successfully." 423 | msg += "\n##### A restart of KiCad is necessary. #####" 424 | else: 425 | msg += "\nYou must add them manually or select the automatic option." 426 | 427 | return msg 428 | 429 | def prepare_library_migration( 430 | self, libs_to_migrate: List[Tuple[str, str]] 431 | ) -> Tuple[str, List[Dict[str, str]]]: 432 | """Prepares library migration by analyzing which symbol libraries need to be updated 433 | 434 | Args: 435 | libs_to_migrate (list): List of tuples with (old_lib, new_lib) format 436 | 437 | Returns: 438 | tuple: (message, libraries_to_rename) 439 | - message: Information about the changes to be made 440 | - libraries_to_rename: List of dictionaries with library renaming information 441 | """ 442 | if not libs_to_migrate or len(libs_to_migrate) <= 0: 443 | return "Error in prepare_library_migration()", [] 444 | 445 | SymbolTable = self.get_sym_table() 446 | SymbolLibsUri = {lib["uri"]: lib for lib in SymbolTable} 447 | libraries_to_rename: List[Dict[str, str]] = [] 448 | 449 | def lib_entry(lib: str) -> str: 450 | return self.path_prefix + "/" + lib 451 | 452 | msg = "" 453 | for old_lib, new_lib in libs_to_migrate: 454 | if new_lib.endswith(".blk"): 455 | msg += f"\n{old_lib} rename to {new_lib}" 456 | else: 457 | msg += f"\n{old_lib} convert to {new_lib}" 458 | 459 | # Check if this library is in the symbol table 460 | if lib_entry(old_lib) in SymbolLibsUri: 461 | entry = SymbolLibsUri[lib_entry(old_lib)] 462 | tmp = { 463 | "oldURI": entry["uri"], 464 | "newURI": lib_entry(new_lib), 465 | "name": entry["name"], 466 | } 467 | libraries_to_rename.append(tmp) 468 | 469 | # Create message about symbol library changes 470 | msg_lib = "" 471 | if len(libraries_to_rename): 472 | msg_lib += "The following changes must be made to the list of imported Symbol libs:\n" 473 | for tmp in libraries_to_rename: 474 | msg_lib += f"\n{tmp['name']} : {tmp['oldURI']} \n-> {tmp['newURI']}" 475 | msg_lib += "\n\n" 476 | msg_lib += "It is necessary to adjust the settings of the imported symbol libraries in KiCad." 477 | 478 | msg += "\n\n" + msg_lib 479 | msg += "\n\nBackup files are also created automatically. " 480 | msg += "These are named '*.blk'.\nShould the changes be applied?" 481 | 482 | return msg, libraries_to_rename 483 | 484 | def execute_library_migration( 485 | self, libraries_to_rename: List[Dict[str, str]] 486 | ) -> str: 487 | """Executes the library migration by changing entries in the symbol table 488 | 489 | Args: 490 | libraries_to_rename (list): List of dictionaries with library renaming information 491 | 492 | Returns: 493 | str: Message about the changes made 494 | """ 495 | if not libraries_to_rename or len(libraries_to_rename) <= 0: 496 | return "No libraries to migrate." 497 | 498 | msg = "" 499 | for lib in libraries_to_rename: 500 | msg += f"\n{lib['name']} : {lib['oldURI']} \n-> {lib['newURI']}" 501 | self.sym_table_change_entry(lib["oldURI"], lib["newURI"]) 502 | 503 | msg += "\n\nA restart of KiCad is necessary to apply all changes." 504 | return msg 505 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------