-
Notifications
You must be signed in to change notification settings - Fork 11
/
FritzingTools.py
executable file
·4860 lines (2599 loc) · 177 KB
/
FritzingTools.py
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
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
# Various support routines for processing Fritzing's fzp and svg files.
# Change this from 'no' to 'yes' to cause 0 length/width terminal definitions
# to be warned about but not modified, to being changed (which will cause them
# to move in the svg and need repositioning) to a length/width of 10 (which
# depending on scaling may or may not be .01in). The default is warn but not
# change, but I use modify as it is much easier converting 0 width parts with
# Inkscape like that.
ModifyTerminal = 'n'
# Set to 'n' (or anything not 'y') to supress Warning 28: (dup id in
# description field) which is all of common, annoying and harmless.
# However by default the warning is issued ...
IssueNameDupWarning = 'n'
Version = '0.0.2' # Version number of this file.
# Import copyfile
from shutil import copyfile
# Import os and sys to get file rename and the argv stuff, re for regex,
# logging to get logging support and PPTools for the parse routine
import os, sys, re, logging, PPTools as PP
# and the lxml library for the xml
from lxml import etree
def InitializeAll():
# Initialize all of the global variables
Errors = []
Warnings = []
Info = []
FzpDict = {}
FzpDict['connectors.fzp.breadboardView'] = []
FzpDict['connectors.fzp.iconView'] = []
FzpDict['connectors.fzp.pcbView'] = []
FzpDict['connectors.fzp.schematicView'] = []
FzpDict['views'] = []
CurView = None
TagStack = [['empty', 0]]
State={'lasttag': 'none', 'nexttag': 'none', 'lastvalue': 'none', 'image': 'none', 'noradius': [], 'KeyErrors': []}
InheritedAttributes=None
return Errors, Warnings, Info, FzpDict, CurView, TagStack, State, InheritedAttributes
# End of def InitializeAll():
def InitializeState():
# Initialize only the state related global variables (not the PrefixDir,
# Errors, Warnings or dictionary) to start processing a different file
# such as an svg linked from a fzp.
TagStack = [['empty', 0]]
State={'lasttag': 'none', 'nexttag': 'none', 'lastvalue': 'none', 'image': 'none', 'noradius': [], 'KeyErrors': []}
InheritedAttributes=None
return TagStack, State, InheritedAttributes
# End of def InitializeState():
def ProcessArgs(Argv, Errors):
# Process the input arguments on the command line.
logging.info (' Entering ProcessArgs\n')
# Regex to match '.svg' to find svg files
SvgExtRegex = re.compile(r'\.svg$', re.IGNORECASE)
# Regex to match .fzp to find fzp files
FzpExtRegex = re.compile(r'\.fzp$', re.IGNORECASE)
# Regex to match 'part. to identify an unzipped fzpz file'
PartRegex = re.compile(r'^part\.', re.IGNORECASE)
# Regex to match 'part.filename' for substitution for both unix and windows.
PartReplaceRegex = re.compile(r'^part\..*$|\/part\..*$|\\part\..*$', re.IGNORECASE)
# Set the return values to the error return (really only FileType needs
# to be done, but do them all for consistancy. Set PrefixDir and Path
# to striing constants (not None) for the dir routines.
FileType = None
DirProcessing = 'N'
PrefixDir = ""
Path = ""
File = None
SrcDir = None
DstDir = None
if len(sys.argv) == 3:
# If we have two directories, one empty, process all the fzp files in
# the first directory in to the empty second directory, creating
# subdirectories as needed (but no backup files!)
DirProcessing, PrefixDir, Path, File, SrcDir, DstDir = ProcessDirArgs(Argv, Errors)
if DirProcessing == 'Y':
# Success, so set FileType to 'dir' from None to indicate no
# error is present and to continue processing.
FileType = 'dir'
# End of if (DirProcessing == 'Y':
logging.info (' Exiting ProcessArgs\n')
return FileType, DirProcessing, PrefixDir, Path, File, SrcDir, DstDir
elif len(sys.argv) != 2:
# No input file or too many arguments so print a usage message and exit.
Errors.append('Usage: {0:s} filename.fzp or filename.svg or srcdir dstdir\n'.format(str(sys.argv[0])))
logging.info (' Exiting ProcessArgs\n')
return FileType, DirProcessing, PrefixDir, Path, File, SrcDir, DstDir
else:
# only a single file is present so arrange to process it.
InFile = sys.argv[1]
logging.debug (' ProcessArgs: input filename %s\n', InFile)
logging.debug (' ProcessArgs: isfile %s\n', os.path.isfile(InFile))
logging.debug (' ProcessArgs: svg %s\n', SvgExtRegex.search(InFile))
logging.debug (' ProcessArgs: fzp %s\n', FzpExtRegex.search(InFile))
if (not os.path.isfile(InFile) or
(SvgExtRegex.search(InFile) == None and
FzpExtRegex.search(InFile) == None)):
# Input file isn't valid, return a usage message.
Errors.append('Usage: {0:s} filename.fzp or filename.svg or srcdir dstdir\n\n\'{1:s}\'\n\neither isn\'t a file or doesn\'t end in .fzp or .svg\n'.format(str(sys.argv[0]), str(InFile)))
logging.info (' Exiting ProcessArgs\n')
return FileType, DirProcessing, PrefixDir, Path, File, SrcDir, DstDir
# End of if not os.path.isfile(InFile) and not SvgExtRegex.search(InFile) and not FzpExtRegex.search(InFile):
Path = ''
# First strip off the current path if any
Path = os.path.dirname(InFile)
if not Path:
# No path present so set that
Path = ''
# End of if not Path:
# and then get the filename
File = os.path.basename(InFile)
if SvgExtRegex.search(File):
# process a single svg file.
FileType = 'SVG'
logging.debug (' ProcessArgs: Found svg input file %s set FileType %s\n', InFile, FileType)
else:
# this is an fzp file of some kind so figure out which kind and
# set the appropriate path.
pat = PartRegex.search(File)
logging.debug (' ProcessArgs: Found svg input file %s Match %s\n', InFile, pat)
if PartRegex.search(File):
# It is a part. type fzp, thus the svgs are in this same
# directory named svg.image_type.filename so set FileType
# to fzpPart to indicate that.
FileType = 'FZPPART'
logging.debug (' ProcessArgs: Set filetype FZPPART\n')
else:
# This is a Fritzing internal type fzp and thus the svgs are in
# svg/PrefixDir/image_type/filename.svg. So make sure we have a
# prefix directory on the input file.
# get the path from the input file.
Path = os.path.dirname(InFile)
# and the file name
File = os.path.basename(InFile)
SplitDir = os.path.split(Path)
if SplitDir[1] == '' or SplitDir[1] == '.' or SplitDir[1] == '..':
Errors.append('Error 10: There must be a directory that is not \'.\' or \'..\' in the input name for\na fzp file in order to find the svg files.\n')
logging.info (' Exiting ProcessArgs no prefix dir error\n')
return FileType, DirProcessing, PrefixDir, Path, File, SrcDir, DstDir
# End of if SplitDir[1] == '' or SplitDir[1] == '.' or SplitDir[1] == '..':
Path = SplitDir[0]
PrefixDir = SplitDir[1]
if PrefixDir == None:
# Make sure PrefixDir has a string value not None for the
# path routines.
PrefixDir = ""
# End of if PrefixDir == None:
# then so set FileType to fzpFritz to indicate that.
FileType = 'FZPFRITZ'
logging.debug (' Found Fritzing type input file %s path %s\n', InFile, Path)
# End of if PartRegex.search(File):
# End of if SvgExtRegex.search(File):
# End of if len(sys.argv) == 3:
logging.debug (' ProcessArgs: End of ProcessArgs return FileType %s PrefixDir %s Path %s File %s\n', FileType, PrefixDir, Path, File)
logging.info (' Exiting ProcessArgs\n')
return FileType, DirProcessing, PrefixDir, Path, File, SrcDir, DstDir
# End of def ProcessArgs(Argv, Errors):
def ProcessDirArgs(argv, Errors):
logging.info (' Entering ProcessDirArgs\n')
# Clear the return variables in case of error.
DirProcessing = 'N'
PrefixDir = ""
Path = ""
File = None
# Get the 2 directories from the input arguments.
SrcDir = argv[1]
DstDir = argv[2]
# Check that the source is a directory
if not os.path.isdir(SrcDir):
Errors.append('Usage: {0:s} src_dir dst_dir\n\nsrc_dir {1:s} isn\'t a directory\n'.format(sys.argv[0], SrcDir))
logging.info (' Exiting ProcessDirArgs src dir error\n')
return DirProcessing, PrefixDir, Path, File, SrcDir, DstDir
# End of if not os.path.isdir(SrcDir):
# then that the dest dir is a directory
if not os.path.isdir(DstDir):
Errors.append('Usage: {0:s} src_dir dst_dir\n\ndst_dir {1:s} Isn\'t a directory\n'.format(sys.argv[0], DstDir))
logging.info (' Exiting ProcessDirArgs dst dir error\n')
return DirProcessing, PrefixDir, Path, File, SrcDir, DstDir
# End of if not os.path.isdir(DstDir):
# Both are directories so make sure the dest is empty
if os.listdir(DstDir) != []:
Errors.append('Error 13: dst dir\n\n{0:s}\n\nmust be empty and it is not\n'.format(str(DstDir)))
logging.info (' Exiting ProcessDirArgs dst dir not empty error\n')
return DirProcessing, PrefixDir, Path, File, SrcDir, DstDir
# End of if os.listdir(DstDir) != []:
# Now get the last element of the src path to create the fzp and svg
# directories under the destination directory.
SplitDir = os.path.split(SrcDir)
logging.debug (' ProcessDirArgs: SplitDir %s\n', SplitDir)
if SplitDir[1] == '' or SplitDir[1] == '.' or SplitDir[1] == '..':
Errors.append('Error 10: There must be a directory that is not \'.\' or \'..\' in the input name for\na fzp file in order to find the svg files.\n')
logging.info (' Exiting ProcessDirArgs no prefix dir error\n')
return DirProcessing, PrefixDir, Path, File, SrcDir, DstDir
else:
Path = SplitDir[0]
PrefixDir = SplitDir[1]
if PrefixDir == None:
# Insure PrefixDir has a string value for the directory routines.
PrefixDir = ""
# End of if PrefixDir == None:
DstFzpDir = os.path.join(DstDir,PrefixDir)
try:
os.makedirs(DstFzpDir)
except os.error as e:
Errors.append('Error 14: Creating dir\n\n{0:s} {1:s} \({2:s}\)\n'.format(DstFzpDir), e.strerror, str(e.errno))
logging.info (' Exiting ProcessDirArgs dir on error %s\n',e.strerror)
return DirProcessing, PrefixDir, Path, File, SrcDir, DstDir
# End of try:
logging.debug (' ProcessDirArgs: mkdir %s\n',DstFzpDir)
# The fzp directory was created so create the base svg directory
DstSvgDir = os.path.join(DstDir, 'svg')
try:
os.makedirs(DstSvgDir)
except os.error as e:
Errors.append('Error 14: Creating dir\n\n{0:s} {1:s} \({2:s}\)\n'.format(DstFzpDir), e.strerror, str(e.errno))
logging.info (' Exiting ProcessDirArgs dir on error %s\n',e.strerror)
return DirProcessing, PrefixDir, Path, File, SrcDir, DstDir
# End of try:
logging.debug (' ProcessDirArgs: mkdir %s\n',DstSvgDir)
DstSvgDir = os.path.join(DstSvgDir, PrefixDir)
try:
os.makedirs(DstSvgDir)
except os.error as e:
Errors.append('Error 14: Creating dir\n\n{0:s} {1:s} \({2:s}\)\n'.format(DstFzpDir), e.strerror, str(e.errno))
logging.info (' Exiting ProcessDirArgs dir on error %s\n',e.strerror)
return DirProcessing, PrefixDir, Path, File, SrcDir, DstDir
# End of try:
logging.debug (' ProcessDirArgs: mkdir %s\n', DstSvgDir)
# then the four svg direcotries
SvgDir = os.path.join(DstSvgDir, 'breadboard')
try:
os.makedirs(SvgDir)
except os.error as e:
Errors.append('Error 14: Creating dir\n\n{0:s} {1:s} \({2:s}\)\n'.format(DstFzpDir), e.strerror, str(e.errno))
logging.info (' Exiting ProcessDirArgs dir on error %s\n',e.strerror)
return DirProcessing, PrefixDir, Path, File, SrcDir, DstDir
# End of try:
logging.debug(' ProcessDirArgs: mkdir %s\n', SvgDir)
SvgDir = os.path.join(DstSvgDir, 'icon')
try:
os.makedirs(SvgDir)
except os.error as e:
Errors.append('Error 14: Creating dir\n\n{0:s} {1:s} \({2:s}\)\n'.format(DstFzpDir), e.strerror, str(e.errno))
logging.info (' Exiting ProcessDirArgs dir on error %s\n',e.strerror)
return DirProcessing, PrefixDir, Path, File, SrcDir, DstDir
# End of try:
logging.debug(' ProcessDirArgs: mkdir %s\n', SvgDir)
SvgDir = os.path.join(DstSvgDir, 'pcb')
try:
os.makedirs(SvgDir)
except os.error as e:
Errors.append('Error 14: Creating dir\n\n{0:s} {1:s} \({2:s}\)\n'.format(DstFzpDir), e.strerror, str(e.errno))
logging.info (' Exiting ProcessDirArgs dir on error %s\n',e.strerror)
return DirProcessing, PrefixDir, Path, File, SrcDir, DstDir
# End of try:
logging.debug(' ProcessDirArgs: mkdir %s\n', SvgDir)
SvgDir = os.path.join(DstSvgDir, 'schematic')
try:
os.makedirs(SvgDir)
except os.error as e:
Errors.append('Error, Creating dir {0:s} {1:s} ({2:s})\n'.format(DstFzpDir), e.strerror, str(e.errno))
logging.info (' Exiting ProcessDirArgs dir on error %s\n',e.strerror)
return DirProcessing, PrefixDir, Path, File, SrcDir, DstDir
# End of try:
logging.debug(' ProcessDirArgs: mkdir %s\n', SvgDir)
# End of if SplitDir[1] == '' or SplitDir[1] == '.' or SplitDir[1] == '..':
# If we get here we have a src and dst directory plus all the required new
# dst directories so return all that to the calling routine. Set
# DirProcessing to 'Y' to indicate success.
DirProcessing, = 'Y'
# Then set FileType to 'dir' from None to not cause a silent error exit
# on return.
FileType = 'dir'
logging.debug (' ProcessDirArgs returning DirProcessing %s PrefixDir %s Path %s File %s SrcDir %s DstDir %s\n', DirProcessing, PrefixDir, Path, File, SrcDir, DstDir)
logging.info (' Exiting ProcessDirArgs\n')
return DirProcessing, PrefixDir, Path, File, SrcDir, DstDir
# End of def ProcessDirArgs(Argv, Errors):
def PopTag(TagStack, Level):
# Determine from the current level if the value on the tag stack is still
# in scope. If it is not, then remove the value from the stack.
logging.info (' Entering PopTag Level %s\n', Level)
logging.debug(' PopTag: entry TagStack %s Level %s\n', TagStack, Level)
Tag, StackLevel = TagStack[len(TagStack) - 1]
# Because we may have exited several recusion levels before calling this
# delete all the tags below the current level.
while Level != 0 and StackLevel >= Level:
# Pop the last item from the stack.
logging.debug(' PopTag: popped Tag %s, StackLevel %s\n', Tag, StackLevel )
TagStack.pop(len(TagStack) - 1)
Tag, StackLevel = TagStack[len(TagStack) - 1]
# End of while Level != 0 and StackLevel >= Level:
logging.debug(' PopTag: exit TagStack %s Level %s\n', TagStack, Level)
logging.info (' Exiting PopTag Level %s\n', Level)
# End of def PopTag(Elem, TagStack, Level):
def BackupFilename(InFile, Errors):
logging.info (' Entering BackupFilename\n')
# First set the appropriate output file name None for an error condition.
OutFile = None
try:
# Then try and rename the input file to InFile.bak
os.rename (InFile, InFile + '.bak')
except os.error as e:
Errors.append('Error 15: Can not rename\n\n\'{0:s}\'\n\nto\n\n\'{1:s}\'\n\n\'{2:s}\'\n\n{3:s} ({4:s})\n'.format(str(InFile), str(InFile + '.bak'), str( e.filename), e.strerror, str(e.errno)))
return InFile, OutFile
# End of try:
# If we get here, then the file was successfully renamed so change the
# filenames and return.
OutFile = InFile
InFile = InFile + '.bak'
return InFile, OutFile
logging.info (' Exiting BackupFilename\n')
# End of def BackupFilename(InFile, Errors):
def DupNameError(InFile, Id, Elem, Errors):
logging.info (' Entering DupNameError:\n')
logging.debug (' DupNameError: Entry InFile %s Id %s Elem %s Errors %s\n', InFile, Id, Elem, Errors)
# Log duplicate name error
Errors.append('Error 16: File\n\'{0:s}\'\nAt line {1:s}\n\nId {2:s} present more than once (and should be unique)\n'.format(str(InFile), str(Elem.sourceline), str(Id)))
logging.info (' Exiting DupNameError\n')
#End of def DupNameError(InFile, Id, Elem, Errors):
def DupNameWarning(InFile, Id, Elem, Warnings):
logging.info (' Entering DupNameWarning:\n')
logging.debug (' DupNameWarning: Entry InFile %s Id %s Elem %s Errors %s\n', InFile, Id, Elem, Warnings)
# Log duplicate name warning
Warnings.append('Warning 28: File\n\'{0:s}\'\nAt line {1:s}\n\nname {2:s} present more than once (and should be unique)\n'.format(str(InFile), str(Elem.sourceline), str(Id)))
logging.info (' Exiting DupNameWarning\n')
#End of def DupNameWarning(InFile, Id, Elem, Warnings):
def ProcessTree(FzpType, FileType, InFile, OutFile, CurView, PrefixDir, Elem, Errors, Warnings, Info, FzpDict, TagStack, State, InheritedAttributes, Debug, Level=0):
# Potentially recursively process the element nodes of an lxml tree to
# aquire the information we need to check file integrity. This routine gets
# called recursively to process child nodes (other routines get called for
# leaf node processing).
logging.info (' Entering ProcessTree FileType %s InFile %s Level %s\n', FileType, InFile, Level)
logging.debug (' **** ProcessTree: Source line %s Elem len %s Level %s\nTag %s\nattributes\n%s\ntext %s\nFzpType %s FileType %s InFile %s OutFile %s CurView %s PrefixDir %s Errors %s Warnings %s Info %s TagStack %s State %s InheritedAttributes %s\n', Elem.sourceline, len(Elem), Level, Elem.tag, Elem.attrib, Elem.text, FzpType, FileType, InFile, OutFile, CurView, PrefixDir, Errors, Warnings, Info, TagStack, State, InheritedAttributes)
# Start by checking for non whitespace charactes in tail (which is likely
# an error) and flag the line if present.
Tail = Elem.tail
logging.debug (' ProcessTree: Tail = \'%s\'\n', Tail)
if Tail != None and not Tail.isspace():
Warnings.append('Warning 2: File\n\'{0:s}\'\nAt line {1:s}\n\nText \'{2:s}\' isn\'t white space and may cause a problem\n'.format(str(InFile), str(Elem.sourceline), str(Tail)))
# End of if not Elem.tail.isspace():
if len(Elem):
logging.debug (' ProcessTree: Procees parent node attributes Source line %s len %s Level %s tag %s\n', Elem.sourceline, len(Elem), Level, Elem.tag)
ProcessLeafNode(FzpType, FileType, InFile, OutFile, CurView, PrefixDir, Elem, Errors, Warnings, Info, FzpDict, TagStack, State, InheritedAttributes, Debug, Level)
logging.debug (' ProcessTree: Child nodes Source line %s len %s Level %s tag %s\n', Elem.sourceline, len(Elem), Level, Elem.tag)
# This node has children so recurse down the tree to deal with them.
for Elem in Elem:
if len(Elem):
# this node has children so process them (the attributes of
# this node will be processed by the recursion call and the
# level will be increased by one.)
ProcessTree(FzpType, FileType, InFile, OutFile, CurView, PrefixDir, Elem, Errors, Warnings, Info, FzpDict, TagStack, State, InheritedAttributes, Debug, Level+1)
else: # This particular element in the for loop is a leaf node.
# As this is a leaf node proecess it again increasing the
# level by 1 before doing the call.
ProcessLeafNode(FzpType, FileType, InFile, OutFile, CurView, PrefixDir, Elem, Errors, Warnings, Info, FzpDict, TagStack, State, InheritedAttributes, Debug, Level+1)
# End of if len(Elem):
# End of for Elem in Elem:
else:
# This is a leaf node and thus the level needs to be increased by 1
# before we process it.
ProcessLeafNode(FzpType, FileType, InFile, OutFile, CurView, PrefixDir, Elem, Errors, Warnings, Info, FzpDict, TagStack, State, InheritedAttributes, Debug, Level+1)
# end of if len(Elem):
logging.info (' Exiting ProcessTree Level %s\n', Level)
# End of def ProcessTree(FzpType, FileType, InFile, OutFile, CurView, PrefixDir, Elem, Errors, Warnings, Info, FzpDict, TagStack, State, InheritedAttributes, Debug, Level=0):
def ProcessLeafNode(FzpType, FileType, InFile, OutFile, CurView, PrefixDir, Elem, Errors, Warnings, Info, FzpDict, TagStack, State, InheritedAttributes, Debug, Level):
logging.info (' Entering ProcessLeafNode FileType %s Level %s\n', FileType, Level)
logging.debug (' ProcessLeafNode: FzpType %s FileType %s InFile %s CurView %s Errors %s\n', FzpType, FileType, InFile,CurView, Errors)
# Start by checking for non whitespace charactes in tail (which is likely
# an error) and flag the line if present.
Tail = Elem.tail
logging.debug (' ProcessLeafNode: Tail = \'%s\'\n', Tail)
if Tail != None and not Tail.isspace():
Warnings.append('Warning 2: File\n\'{0:s}\'\nAt line {1:s}\n\nText \'{2:s}\' isn\'t white space and may cause a problem\n'.format(str(InFile), str(Elem.sourceline), str(Tail)))
# End of if not Elem.tail.isspace():
# Select the appropriate leaf node processing routing based on the FileType
# variable.
if FileType == 'FZPFRITZ' or FileType == 'FZPPART':
# If this is a fzp file do the leaf node processing for that.
ProcessFzpLeafNode(FzpType, FileType, InFile, CurView, PrefixDir, Elem, Errors, Warnings, Info, FzpDict, TagStack, State, Level)
elif FileType == 'SVG':
ProcessSvgLeafNode(FzpType, FileType, InFile, CurView, PrefixDir, Elem, Errors, Warnings, Info, FzpDict, TagStack, State, InheritedAttributes, Level)
else:
if not 'SoftwareError' in State:
# Report the software error once, then set 'SoftwareError' in State
# to supress more messages and just return. It won't work right
# but the problem will at least be reported.
Errors.append('Error 19: File\n\'{0:s}\'\n\nFile type {1:s} is an unknown format (software error)\n'.format(str(InFile), str(FileType)))
State['SoftwareError'] = 'y'
# End of if not 'SoftwareError' in State:
# End of if FileType == 'FZPFRITZ' or FileType == 'FZPPART':
logging.info (' Exiting ProcessLeafNode Level %s\n', Level)
# End of def ProcessLeafNode(FzpType, InFile, OutFile, CurView, PrefixDir, Elem, Errors, Warnings, Info, FzpDict, TagStack, State, InheritedAttributes, Debug, Level):
def ProcessFzp(DirProcessing, FzpType, FileType, InFile, OutFile, CurView, PrefixDir, Errors, Warnings, Info, FzpDict, FilesProcessed, TagStack, State, InheritedAttributes, Debug):
logging.info (' Entering ProcessFzp FzpType %s FileType %s InFile %s\n', FzpType, FileType, InFile)
logging.debug (' ProcessFzp: FzpType %s FileType %s InFile %s OutFile %s CurView %s PrefixDir %s Errors %s Warnings %s Info %s FzpDict %s TagStack %s State %s InheritedAttributes %s Debug %s\n', FzpType, FileType, InFile, OutFile, CurView, PrefixDir, Errors, Warnings, Info, FzpDict, TagStack, State, InheritedAttributes, Debug)
# Parse the input document.
Doc, Root = PP.ParseFile (InFile, Errors)
logging.debug (' ProcessFzp: return from parse Doc %s\n', Doc)
if Doc != None:
# We have successfully parsed the input document so process it. Since
# We don't yet have a CurView, set it to None.
logging.debug (' ProcessFzp: Calling ProceesTree Doc %s\n', Doc)
# Set the local output file to a value in case we don't use it but
# do test it.
FQOutFile = None
if OutFile == None:
if Debug == 0:
# No output file indicates we are processing a single fzp file
# so rename the src file to .bak and use the original src file
# as the output file (assuming the rename is successfull).
# Use FQOutFile as the new file name to preserve the value
# of OutFile for svg processing later.
InFile, FQOutFile = BackupFilename(InFile, Errors)
logging.debug (' ProcessFzp: After BackupFilename(InFile, Errors) InFile %s FQOutFile %s\n', InFile, FQOutFile)
if FQOutFile == None:
# An error occurred, so just return to indicate that without
# writing the file (as there is no where to write it to).
logging.info (' ProcessFzp: Exiting ProcessFzp after rename error\n')
return
# End of if FQOutFile == None:
# End of if Debug == 0:
else:
# OutFile wasn't none, so set FQOutFile
FQOutFile = OutFile
# End of if OutFile == None:
# Now that we have an appropriate input file name, process the tree.
# (we won't get here if there is a file rename error above!)
logging.debug (' ProcessFzp: before ProcessTree FileType %s FQOutFile %s\n', FileType, FQOutFile)
ProcessTree(FzpType, FileType, InFile, FQOutFile, None, PrefixDir, Root, Errors, Warnings, Info, FzpDict, TagStack, State, InheritedAttributes, Debug)
logging.debug (' ProcessFzp: After ProcessTree FileType %s FQOutFile %s\n', FileType, FQOutFile)
# We are at the end of processing the fzp file so check that the
# connector numbers are contiguous.
FzpCheckConnectors(InFile, Root, FzpDict, Errors, Warnings, Info, State)
# We have an output file name so write the fzp file to it (or the
# console if Debug is > 0.)
logging.debug (' ProcessFzp: Prettyprint FQOutFile %s FileType %s\n', FQOutFile, FileType)
PP.OutputTree(Doc, Root, FileType, InFile, FQOutFile, Errors, Warnings, Info, Debug)
# Then process the associatted svg files from the fzp.
logging.debug (' ProcessFzp: Calling ProcessSvgsFromFzp DirProcessing %s FzpType %s FileType %s InFile %s OutFile %s PrefixDir %s Errors %s Warnings %s Info %s FzpDict %s Debug %s\n', DirProcessing, FzpType, FileType, InFile, OutFile, PrefixDir, Errors, Warnings, Info, FzpDict, Debug)
# Use the original value of OutFile to process the svgs.
ProcessSvgsFromFzp(DirProcessing, FzpType, FileType, InFile, OutFile, PrefixDir, Errors, Warnings, Info, FzpDict, FilesProcessed, Debug)
# End of if Doc != None:
logging.info (' Exiting ProcessFzp\n')
# End of def ProcessFzp(DirProcessing, FzpType, FileType, InFile, OutFile, CurView, PrefixDir, Errors, Warnings, Info, FzpDict, FilesProcessed, TagStack, State, InheritedAttributes, Debug):
def ProcessSvgsFromFzp(DirProcessing, FzpType, FileType, InFile, OutFile, PrefixDir, Errors, Warnings, Info, FzpDict, FilesProcessed, Debug):
# Process the svg files referenced in the FzpDict created from a Fritzing
# .fzp file.
logging.info (' Entering ProcessSvgsFromFzp DirProcessing %s FzpType %s FileType %s InFile %s\n', DirProcessing, FzpType, FileType, InFile)
logging.debug (' ProcessSvgsFromFzp: OutFile %s PrefixDir %s FzpDict %s\n', OutFile, PrefixDir, FzpDict)
# First we need to determine the directory structure / filename for the
# svg files as there are several to choose from: uncompressed parts which
# are all in the same directory but with odd prefixes of
# svg.layer.filename or in a Fritzing directory which will be
# ../svg/PrefixDir/layername/filename in 4 different directories. In
# addition we may be processing a single fzp file (in which case the input
# file needs a '.bak' appended to it), or directory of fzp files in which
# case the '.bak' isn't needed. We will form appropriate file names from
# the InFile, OutFile and PrefixDir arguments to feed to the svg
# processing routine.
# Insure FQOutFile has a value
FQOutFile = None
# Get the path from the input and output files (which will be the fzp file
# at this point.)
InPath = os.path.dirname(InFile)
# Record in FilesProcessed that we have processed this file name in case
# this is a directory operation. Get just the file name.
BaseFile = os.path.basename(InFile)
if 'processed.' + InFile in FilesProcessed:
# If we have already processed it, flag an error (should not occur).
logging.debug (' ProcessSvgsFromFzp: InFile %s Error 87 issued\n', InFile)
Errors.append('Error 87: File\n\'{0:s}\'\n\nFile has already been processed (software error)\n'.format(str(InFile)))
logging.info (' Exiting ProcessSvgsFromFzp on already processed error\n')
return
else:
# Mark that we have processed this file.
FilesProcessed['processed.' + InFile] = 'y'
logging.debug (' ProcessSvgsFromFzp: InFile %s marked as processed\n', InFile)
# End of if 'processed.' + InFile in FilesProcessed:
logging.debug (' ProcessSvgsFromFzp: InPath %s InFile %s', InPath, InFile)
if OutFile == None:
OutPath = ''
logging.debug (' ProcessSvgsFromFzp: OutPath %s OutFile %s', OutPath, OutFile)
else:
OutPath = os.path.dirname(OutFile)
logging.debug (' ProcessSvgsFromFzp: OutPath %s OutFile %s', OutPath, OutFile)
# End of if OutFile == None:
for CurView in FzpDict['views']:
logging.debug (' ProcessSvgsFromFzp: Process View %s FileType %s FzpDict[views] %s\n', CurView, FileType, FzpDict['views'])
# Extract just the image name as a string from the list entry.
Image = ''.join(FzpDict[CurView + '.image'])
logging.debug (' ProcessSvgsFromFzp 1: CurView %s Image %s FzpType %s FileType %s OutFile %s\n', CurView, Image, FzpType, FileType, OutFile)
# indicate we haven't seen an output file rename error.
OutFileError = 'n'
if FzpType == 'FZPPART':
# The svg is of the form svg.layer.filename in the directory
# pointed to by Path. So append a svg. to the file name and
# convert the '/' to a '.' to form the file name for processing.
Image = Image.replace(r"/", ".")
if OutFile == None:
# Single file processing so set the output filename and use
# FQOutFile.bak as the input. Again preserve the original
# value of OutFile for processing later svg files.
Image = Image.replace(r"/", ".")
FQOutFile = os.path.join(InPath, 'svg.' + Image)
# Set the input file from the output file in case debug is non
# zero and we don't set a backup file.
FQInFile = FQOutFile
if Debug == 0:
# If Debug isn't set then rename the input file and
# change the input file name. Otherwise leave it alone
# (in this case OutFile is unused and output goes to the
# console for debugging.)
FQInFile, FQOutFile = BackupFilename(FQInFile, Errors)
if FQOutFile == None:
# an error occurred renaming the input file so set an
# an OutFileError so we don't try and process this
# file as we have no valid output file to write it to.
OutFileError = 'n'
# End of if FQOutFile == None:
logging.debug (' ProcessSvgsFromFzp 2: FQInFile %s FQOutFile %s OutFileError %s\n', FQInFile, FQOutFile, OutFileError)
# End of if Debug == 0:
else:
# dir to dir processing so set appropriate file names
# (identical except for path)
FQInFile = os.path.join(InPath, 'svg.' + Image)
FQOutFile = os.path.join(OutPath, 'svg.' + Image)
# End of if OutFile == None:
elif FzpType == 'FZPFRITZ':
# The svg is of the form path../svg/PrefixDir/layername/filename,
# so prepend the appropriate path and use that as the file name.
# First create the new end path as NewFile
# (i.e. '../svg/PrefixDir/Image') once, ready to append as needed.
NewFile = '..'
NewFile = os.path.join(NewFile, 'svg')
logging.debug (' ProcessSvgsFromFzp: after add svg NewFile %s PrefixDir %s\n', NewFile, PrefixDir)
NewFile = os.path.join(NewFile, PrefixDir)
logging.debug (' ProcessSvgsFromFzp: after add PrefixDir NewFile %s\n', NewFile)
NewFile = os.path.join(NewFile, Image)
logging.debug (' ProcessSvgsFromFzp: after add Image NewFile %s\n', NewFile)
# add the new end path to the end of the source path