summaryrefslogtreecommitdiff
path: root/scripting/kicadplugins.i
blob: 9a310faa590a1b688fb8ae002cf0d2770926a7c6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
/*
 * This program source code file is part of KiCad, a free EDA CAD application.
 *
 * Copyright (C) 2012 NBEE Embedded Systems, Miguel Angel Ajo <miguelangel@nbee.es>
 * Copyright (C) 1992-2012 KiCad Developers, see AUTHORS.txt for contributors.
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, you may find one here:
 * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
 * or you may search the http://www.gnu.org website for the version 2 license,
 * or you may write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
 */

 /**
  * This file builds the base classes for all kind of python plugins that
  * can be included into kicad.
  * they provide generic code to all the classes:
  *
  * KiCadPlugin
  *  /|\
  *   |
  *   |\-FilePlugin
  *   |\-FootprintWizardPlugin
  *   |\-ActionPlugin
  *
  * It defines the LoadPlugins() function that loads all the plugins
  * available in the system
  *
  */

/*
 * Remark:
 * Avoid using the print function in python wizards
 *
 * Be aware print messages create IO exceptions, because the wizard
 * is run from Pcbnew. And if pcbnew is not run from a console, there is
 * no io channel to read the output of print function.
 * When the io buffer is full, a IO exception is thrown.
 */

%pythoncode
{

KICAD_PLUGINS={}

def ReloadPlugin(name):
    if not KICAD_PLUGINS.has_key(name):
        return False

    KICAD_PLUGINS[name]["object"].deregister()
    mod = reload(KICAD_PLUGINS[name]["module"])
    KICAD_PLUGINS[name]["object"]= mod.register()


def ReloadPlugins():
    import os.path
    for k in KICAD_PLUGINS.keys():
        plugin = KICAD_PLUGINS[k]

        filename = plugin["filename"]
        mtime = plugin["modification_time"]
        now_mtime = os.path.getmtime(filename)

        if mtime!=now_mtime:
            # /* print filename, " is modified, reloading" */
            KICAD_PLUGINS[k]["modification_time"]=now_mtime
            ReloadPlugin(k)


def LoadPlugins(plugpath):
    import os
    import sys

    kicad_path = os.environ.get('KICAD_PATH')
    plugin_directories=[]

    if plugpath:
        plugin_directories.append(plugpath)

    if kicad_path:
        plugin_directories.append(os.path.join(kicad_path, 'scripting', 'plugins'))

    if sys.platform.startswith('linux'):
        plugin_directories.append(os.environ['HOME']+'/.kicad_plugins/')
        plugin_directories.append(os.environ['HOME']+'/.kicad/scripting/plugins/')

    for plugins_dir in plugin_directories:
        if not os.path.isdir(plugins_dir):
            continue

        sys.path.append(plugins_dir)

        for module in os.listdir(plugins_dir):
            if os.path.isdir(plugins_dir+module):
                __import__(module, locals(), globals())

            if module == '__init__.py' or module[-3:] != '.py':
                continue

            mod = __import__(module[:-3], locals(), globals())

            module_filename = plugins_dir+"/"+module
            mtime = os.path.getmtime(module_filename)
            if hasattr(mod,'register'):
                KICAD_PLUGINS[module]={"filename":module_filename,
                                       "modification_time":mtime,
                                       "object":mod.register(),
                                       "module":mod}



class KiCadPlugin:
    def __init__(self):
        pass

    def register(self):
        if isinstance(self,FilePlugin):
            pass # register to file plugins in C++
        if isinstance(self,FootprintWizardPlugin):
            PYTHON_FOOTPRINT_WIZARDS.register_wizard(self)
            return

        if isinstance(self,ActionPlugin):
            pass # register to action plugins in C++

        return

    def deregister(self):
        if isinstance(self,FilePlugin):
            pass # register to file plugins in C++
        if isinstance(self,FootprintWizardPlugin):
            PYTHON_FOOTPRINT_WIZARDS.deregister_wizard(self)
            return

        if isinstance(self,ActionPlugin):
            pass # register to action plugins in C++

        return




class FilePlugin(KiCadPlugin):
    def __init__(self):
        KiCadPlugin.__init__(self)


from math import ceil, floor, sqrt

class FootprintWizardPlugin(KiCadPlugin):
    def __init__(self):
        KiCadPlugin.__init__(self)
        self.defaults()

    def defaults(self):
        self.module = None
        self.parameters = {}
        self.parameter_errors={}
        self.name = "Undefined Footprint Wizard plugin"
        self.description = ""
        self.image = ""
        self.buildmessages = ""

    def GetName(self):
        return self.name

    def GetImage(self):
        return self.image

    def GetDescription(self):
        return self.description


    def GetNumParameterPages(self):
        return len(self.parameters)

    def GetParameterPageName(self,page_n):
        return self.page_order[page_n]

    def GetParameterNames(self,page_n):
        name = self.GetParameterPageName(page_n)
        return self.parameter_order[name]

    def GetParameterValues(self,page_n):
        name = self.GetParameterPageName(page_n)
        names = self.GetParameterNames(page_n)
        values = [self.parameters[name][n] for n in names]
        return map(lambda x: str(x), values)  # list elements as strings

    def GetParameterErrors(self,page_n):
        self.CheckParameters()
        name = self.GetParameterPageName(page_n)
        names = self.GetParameterNames(page_n)
        values = [self.parameter_errors[name][n] for n in names]
        return map(lambda x: str(x), values)  # list elements as strings

    def CheckParameters(self):
        return ""

    def ConvertValue(self,v):
        try:
            v = float(v)
        except:
            pass
        if type(v) is float:
            if ceil(v) == floor(v):
                v = int(v)
        return v


    def SetParameterValues(self,page_n,values):
        name = self.GetParameterPageName(page_n)
        keys = self.GetParameterNames(page_n)
        for n, key in enumerate(keys):
            val = self.ConvertValue(values[n])
            self.parameters[name][key] = val


    def ClearErrors(self):
        errs={}

        for page in self.parameters.keys():
            page_dict = self.parameters[page]
            page_params = {}
            for param in page_dict.keys():
                page_params[param]=""

            errs[page]=page_params

        self.parameter_errors = errs


    def GetFootprint( self ):
        self.BuildFootprint()
        return self.module

    def BuildFootprint(self):
        return

    def GetBuildMessages( self ):
        return self.buildmessages

    def Show(self):
        print "Footprint Wizard Name:        ",self.GetName()
        print "Footprint Wizard Description: ",self.GetDescription()
        n_pages = self.GetNumParameterPages()
        print " setup pages: ",n_pages
        for page in range(0,n_pages):
            name = self.GetParameterPageName(page)
            values = self.GetParameterValues(page)
            names =  self.GetParameterNames(page)
            print "page %d) %s"%(page,name)
            for n in range (0,len(values)):
                print "\t%s\t:\t%s"%(names[n],values[n])

class ActionPlugin(KiCadPlugin):
    def __init__(self):
        KiCadPlugin.__init__(self)

}