FlatCAMExcEditor.py 154 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717
  1. from PyQt5 import QtGui, QtCore, QtWidgets
  2. from PyQt5.QtCore import Qt, QSettings
  3. from shapely.geometry import LineString, LinearRing, MultiLineString
  4. from shapely.ops import cascaded_union
  5. import shapely.affinity as affinity
  6. from numpy import arctan2, Inf, array, sqrt, sign, dot
  7. from rtree import index as rtindex
  8. from camlib import *
  9. from flatcamGUI.GUIElements import FCEntry, FCComboBox, FCTable, FCDoubleSpinner, LengthEntry, RadioSet, SpinBoxDelegate
  10. from flatcamEditors.FlatCAMGeoEditor import FCShapeTool, DrawTool, DrawToolShape, DrawToolUtilityShape, FlatCAMGeoEditor
  11. from copy import copy, deepcopy
  12. import gettext
  13. import FlatCAMTranslation as fcTranslate
  14. import builtins
  15. fcTranslate.apply_language('strings')
  16. if '_' not in builtins.__dict__:
  17. _ = gettext.gettext
  18. class FCDrillAdd(FCShapeTool):
  19. """
  20. Resulting type: MultiLineString
  21. """
  22. def __init__(self, draw_app):
  23. DrawTool.__init__(self, draw_app)
  24. self.name = 'drill_add'
  25. self.selected_dia = None
  26. try:
  27. self.draw_app.app.inform.emit(_("Click to place ..."))
  28. self.selected_dia = self.draw_app.tool2tooldia[self.draw_app.last_tool_selected]
  29. # as a visual marker, select again in tooltable the actual tool that we are using
  30. # remember that it was deselected when clicking on canvas
  31. item = self.draw_app.tools_table_exc.item((self.draw_app.last_tool_selected - 1), 1)
  32. self.draw_app.tools_table_exc.setCurrentItem(item)
  33. except KeyError:
  34. self.draw_app.app.inform.emit(_("[WARNING_NOTCL] To add a drill first select a tool"))
  35. self.draw_app.select_tool("drill_select")
  36. return
  37. try:
  38. QtGui.QGuiApplication.restoreOverrideCursor()
  39. except Exception as e:
  40. pass
  41. self.cursor = QtGui.QCursor(QtGui.QPixmap('share/aero_drill.png'))
  42. QtGui.QGuiApplication.setOverrideCursor(self.cursor)
  43. geo = self.utility_geometry(data=(self.draw_app.snap_x, self.draw_app.snap_y))
  44. if isinstance(geo, DrawToolShape) and geo.geo is not None:
  45. self.draw_app.draw_utility_geometry(geo=geo)
  46. self.draw_app.app.inform.emit(_("Click to place ..."))
  47. # Switch notebook to Selected page
  48. self.draw_app.app.ui.notebook.setCurrentWidget(self.draw_app.app.ui.selected_tab)
  49. def click(self, point):
  50. self.make()
  51. return "Done."
  52. def utility_geometry(self, data=None):
  53. self.points = data
  54. return DrawToolUtilityShape(self.util_shape(data))
  55. def util_shape(self, point):
  56. if point[0] is None and point[1] is None:
  57. point_x = self.draw_app.x
  58. point_y = self.draw_app.y
  59. else:
  60. point_x = point[0]
  61. point_y = point[1]
  62. start_hor_line = ((point_x - (self.selected_dia / 2)), point_y)
  63. stop_hor_line = ((point_x + (self.selected_dia / 2)), point_y)
  64. start_vert_line = (point_x, (point_y - (self.selected_dia / 2)))
  65. stop_vert_line = (point_x, (point_y + (self.selected_dia / 2)))
  66. return MultiLineString([(start_hor_line, stop_hor_line), (start_vert_line, stop_vert_line)])
  67. def make(self):
  68. try:
  69. QtGui.QGuiApplication.restoreOverrideCursor()
  70. except Exception as e:
  71. pass
  72. # add the point to drills if the diameter is a key in the dict, if not, create it add the drill location
  73. # to the value, as a list of itself
  74. if self.selected_dia in self.draw_app.points_edit:
  75. self.draw_app.points_edit[self.selected_dia].append(self.points)
  76. else:
  77. self.draw_app.points_edit[self.selected_dia] = [self.points]
  78. self.draw_app.current_storage = self.draw_app.storage_dict[self.selected_dia]
  79. self.geometry = DrawToolShape(self.util_shape(self.points))
  80. self.draw_app.in_action = False
  81. self.complete = True
  82. self.draw_app.app.inform.emit(_("[success] Done. Drill added."))
  83. class FCDrillArray(FCShapeTool):
  84. """
  85. Resulting type: MultiLineString
  86. """
  87. def __init__(self, draw_app):
  88. DrawTool.__init__(self, draw_app)
  89. self.name = 'drill_array'
  90. self.draw_app.array_frame.show()
  91. self.selected_dia = None
  92. self.drill_axis = 'X'
  93. self.drill_array = 'linear'
  94. self.drill_array_size = None
  95. self.drill_pitch = None
  96. self.drill_linear_angle = None
  97. self.drill_angle = None
  98. self.drill_direction = None
  99. self.drill_radius = None
  100. self.origin = None
  101. self.destination = None
  102. self.flag_for_circ_array = None
  103. self.last_dx = 0
  104. self.last_dy = 0
  105. self.pt = []
  106. try:
  107. self.draw_app.app.inform.emit(_("Click to place ..."))
  108. self.selected_dia = self.draw_app.tool2tooldia[self.draw_app.last_tool_selected]
  109. # as a visual marker, select again in tooltable the actual tool that we are using
  110. # remember that it was deselected when clicking on canvas
  111. item = self.draw_app.tools_table_exc.item((self.draw_app.last_tool_selected - 1), 1)
  112. self.draw_app.tools_table_exc.setCurrentItem(item)
  113. except KeyError:
  114. self.draw_app.app.inform.emit(_("[WARNING_NOTCL] To add an Drill Array first select a tool in Tool Table"))
  115. return
  116. try:
  117. QtGui.QGuiApplication.restoreOverrideCursor()
  118. except Exception as e:
  119. pass
  120. self.cursor = QtGui.QCursor(QtGui.QPixmap('share/aero_drill_array.png'))
  121. QtGui.QGuiApplication.setOverrideCursor(self.cursor)
  122. geo = self.utility_geometry(data=(self.draw_app.snap_x, self.draw_app.snap_y), static=True)
  123. if isinstance(geo, DrawToolShape) and geo.geo is not None:
  124. self.draw_app.draw_utility_geometry(geo=geo)
  125. self.draw_app.app.inform.emit(_("Click on target location ..."))
  126. # Switch notebook to Selected page
  127. self.draw_app.app.ui.notebook.setCurrentWidget(self.draw_app.app.ui.selected_tab)
  128. def click(self, point):
  129. if self.drill_array == 'Linear':
  130. self.make()
  131. return
  132. else:
  133. if self.flag_for_circ_array is None:
  134. self.draw_app.in_action = True
  135. self.pt.append(point)
  136. self.flag_for_circ_array = True
  137. self.set_origin(point)
  138. self.draw_app.app.inform.emit(_("Click on the Drill Circular Array Start position"))
  139. else:
  140. self.destination = point
  141. self.make()
  142. self.flag_for_circ_array = None
  143. return
  144. def set_origin(self, origin):
  145. self.origin = origin
  146. def utility_geometry(self, data=None, static=None):
  147. self.drill_axis = self.draw_app.drill_axis_radio.get_value()
  148. self.drill_direction = self.draw_app.drill_direction_radio.get_value()
  149. self.drill_array = self.draw_app.array_type_combo.get_value()
  150. try:
  151. self.drill_array_size = int(self.draw_app.drill_array_size_entry.get_value())
  152. try:
  153. self.drill_pitch = float(self.draw_app.drill_pitch_entry.get_value())
  154. self.drill_linear_angle = float(self.draw_app.linear_angle_spinner.get_value())
  155. self.drill_angle = float(self.draw_app.drill_angle_entry.get_value())
  156. except TypeError:
  157. self.draw_app.app.inform.emit(
  158. _("[ERROR_NOTCL] The value is not Float. Check for comma instead of dot separator."))
  159. return
  160. except Exception as e:
  161. self.draw_app.app.inform.emit(_("[ERROR_NOTCL] The value is mistyped. Check the value. %s") % str(e))
  162. return
  163. if self.drill_array == 'Linear':
  164. if data[0] is None and data[1] is None:
  165. dx = self.draw_app.x
  166. dy = self.draw_app.y
  167. else:
  168. dx = data[0]
  169. dy = data[1]
  170. geo_list = []
  171. geo = None
  172. self.points = [dx, dy]
  173. for item in range(self.drill_array_size):
  174. if self.drill_axis == 'X':
  175. geo = self.util_shape(((dx + (self.drill_pitch * item)), dy))
  176. if self.drill_axis == 'Y':
  177. geo = self.util_shape((dx, (dy + (self.drill_pitch * item))))
  178. if self.drill_axis == 'A':
  179. x_adj = self.drill_pitch * math.cos(math.radians(self.drill_linear_angle))
  180. y_adj = self.drill_pitch * math.sin(math.radians(self.drill_linear_angle))
  181. geo = self.util_shape(
  182. ((dx + (x_adj * item)), (dy + (y_adj * item)))
  183. )
  184. if static is None or static is False:
  185. geo_list.append(affinity.translate(geo, xoff=(dx - self.last_dx), yoff=(dy - self.last_dy)))
  186. else:
  187. geo_list.append(geo)
  188. # self.origin = data
  189. self.last_dx = dx
  190. self.last_dy = dy
  191. return DrawToolUtilityShape(geo_list)
  192. else:
  193. if data[0] is None and data[1] is None:
  194. cdx = self.draw_app.x
  195. cdy = self.draw_app.y
  196. else:
  197. cdx = data[0]
  198. cdy = data[1]
  199. if len(self.pt) > 0:
  200. temp_points = [x for x in self.pt]
  201. temp_points.append([cdx, cdy])
  202. return DrawToolUtilityShape(LineString(temp_points))
  203. def util_shape(self, point):
  204. if point[0] is None and point[1] is None:
  205. point_x = self.draw_app.x
  206. point_y = self.draw_app.y
  207. else:
  208. point_x = point[0]
  209. point_y = point[1]
  210. start_hor_line = ((point_x - (self.selected_dia / 2)), point_y)
  211. stop_hor_line = ((point_x + (self.selected_dia / 2)), point_y)
  212. start_vert_line = (point_x, (point_y - (self.selected_dia / 2)))
  213. stop_vert_line = (point_x, (point_y + (self.selected_dia / 2)))
  214. return MultiLineString([(start_hor_line, stop_hor_line), (start_vert_line, stop_vert_line)])
  215. def make(self):
  216. self.geometry = []
  217. geo = None
  218. try:
  219. QtGui.QGuiApplication.restoreOverrideCursor()
  220. except Exception as e:
  221. pass
  222. # add the point to drills if the diameter is a key in the dict, if not, create it add the drill location
  223. # to the value, as a list of itself
  224. if self.selected_dia not in self.draw_app.points_edit:
  225. self.draw_app.points_edit[self.selected_dia] = []
  226. for i in range(self.drill_array_size):
  227. self.draw_app.points_edit[self.selected_dia].append(self.points)
  228. self.draw_app.current_storage = self.draw_app.storage_dict[self.selected_dia]
  229. if self.drill_array == 'Linear':
  230. for item in range(self.drill_array_size):
  231. if self.drill_axis == 'X':
  232. geo = self.util_shape(((self.points[0] + (self.drill_pitch * item)), self.points[1]))
  233. if self.drill_axis == 'Y':
  234. geo = self.util_shape((self.points[0], (self.points[1] + (self.drill_pitch * item))))
  235. if self.drill_axis == 'A':
  236. x_adj = self.drill_pitch * math.cos(math.radians(self.drill_linear_angle))
  237. y_adj = self.drill_pitch * math.sin(math.radians(self.drill_linear_angle))
  238. geo = self.util_shape(
  239. ((self.points[0] + (x_adj * item)), (self.points[1] + (y_adj * item)))
  240. )
  241. self.geometry.append(DrawToolShape(geo))
  242. else:
  243. if (self.drill_angle * self.drill_array_size) > 360:
  244. self.draw_app.app.inform.emit(_("[WARNING_NOTCL] Too many drills for the selected spacing angle."))
  245. return
  246. radius = distance(self.destination, self.origin)
  247. initial_angle = math.asin((self.destination[1] - self.origin[1]) / radius)
  248. for i in range(self.drill_array_size):
  249. angle_radians = math.radians(self.drill_angle * i)
  250. if self.drill_direction == 'CW':
  251. x = self.origin[0] + radius * math.cos(-angle_radians + initial_angle)
  252. y = self.origin[1] + radius * math.sin(-angle_radians + initial_angle)
  253. else:
  254. x = self.origin[0] + radius * math.cos(angle_radians + initial_angle)
  255. y = self.origin[1] + radius * math.sin(angle_radians + initial_angle)
  256. geo = self.util_shape((x, y))
  257. self.geometry.append(DrawToolShape(geo))
  258. self.complete = True
  259. self.draw_app.app.inform.emit(_("[success] Done. Drill Array added."))
  260. self.draw_app.in_action = False
  261. self.draw_app.array_frame.hide()
  262. return
  263. class FCSlot(FCShapeTool):
  264. """
  265. Resulting type: Polygon
  266. """
  267. def __init__(self, draw_app):
  268. DrawTool.__init__(self, draw_app)
  269. self.name = 'slot_add'
  270. self.draw_app = draw_app
  271. self.draw_app.slot_frame.show()
  272. self.selected_dia = None
  273. try:
  274. self.draw_app.app.inform.emit(_("Click to place ..."))
  275. self.selected_dia = self.draw_app.tool2tooldia[self.draw_app.last_tool_selected]
  276. # as a visual marker, select again in tooltable the actual tool that we are using
  277. # remember that it was deselected when clicking on canvas
  278. item = self.draw_app.tools_table_exc.item((self.draw_app.last_tool_selected - 1), 1)
  279. self.draw_app.tools_table_exc.setCurrentItem(item)
  280. except KeyError:
  281. self.draw_app.app.inform.emit(_("[WARNING_NOTCL] To add a slot first select a tool"))
  282. self.draw_app.select_tool("drill_select")
  283. return
  284. try:
  285. QtGui.QGuiApplication.restoreOverrideCursor()
  286. except Exception as e:
  287. pass
  288. self.cursor = QtGui.QCursor(QtGui.QPixmap('share/aero_slot.png'))
  289. QtGui.QGuiApplication.setOverrideCursor(self.cursor)
  290. self.steps_per_circ = self.draw_app.app.defaults["geometry_circle_steps"]
  291. self.half_height = 0.0
  292. self.half_width = 0.0
  293. self.radius = float(self.selected_dia / 2.0)
  294. geo = self.utility_geometry(data=(self.draw_app.snap_x, self.draw_app.snap_y))
  295. if isinstance(geo, DrawToolShape) and geo.geo is not None:
  296. self.draw_app.draw_utility_geometry(geo=geo)
  297. self.draw_app.app.inform.emit(_("Click on target location ..."))
  298. # Switch notebook to Selected page
  299. self.draw_app.app.ui.notebook.setCurrentWidget(self.draw_app.app.ui.selected_tab)
  300. def click(self, point):
  301. self.make()
  302. return "Done."
  303. def utility_geometry(self, data=None):
  304. self.points = data
  305. geo_data = self.util_shape(data)
  306. if geo_data:
  307. return DrawToolUtilityShape(geo_data)
  308. else:
  309. return None
  310. def util_shape(self, point):
  311. if point is None:
  312. return
  313. # updating values here allows us to change the aperture on the fly, after the Tool has been started
  314. self.selected_dia = self.draw_app.tool2tooldia[self.draw_app.last_tool_selected]
  315. self.radius = float(self.selected_dia / 2.0)
  316. self.steps_per_circ = self.draw_app.app.defaults["geometry_circle_steps"]
  317. try:
  318. slot_length = float(self.draw_app.slot_length_entry.get_value())
  319. except ValueError:
  320. # try to convert comma to decimal point. if it's still not working error message and return
  321. try:
  322. slot_length = float(self.draw_app.slot_length_entry.get_value().replace(',', '.'))
  323. self.draw_app.slot_length_entry.set_value(slot_length)
  324. except ValueError:
  325. self.draw_app.app.inform.emit(_("[WARNING_NOTCL] Value is missing or wrong format. "
  326. "Add it and retry."))
  327. return
  328. try:
  329. slot_angle = float(self.draw_app.slot_angle_spinner.get_value())
  330. except ValueError:
  331. self.draw_app.app.inform.emit(_("[WARNING_NOTCL] Value is missing or wrong format. "
  332. "Add it and retry."))
  333. return
  334. if self.draw_app.slot_axis_radio.get_value() == 'X':
  335. self.half_width = slot_length / 2.0
  336. self.half_height = self.radius
  337. else:
  338. self.half_width = self.radius
  339. self.half_height = slot_length / 2.0
  340. if point[0] is None and point[1] is None:
  341. point_x = self.draw_app.x
  342. point_y = self.draw_app.y
  343. else:
  344. point_x = point[0]
  345. point_y = point[1]
  346. geo = []
  347. if self.half_height > self.half_width:
  348. p1 = (point_x - self.half_width, point_y - self.half_height + self.half_width)
  349. p2 = (point_x + self.half_width, point_y - self.half_height + self.half_width)
  350. p3 = (point_x + self.half_width, point_y + self.half_height - self.half_width)
  351. p4 = (point_x - self.half_width, point_y + self.half_height - self.half_width)
  352. down_center = [point_x, point_y - self.half_height + self.half_width]
  353. d_start_angle = math.pi
  354. d_stop_angle = 0.0
  355. down_arc = arc(down_center, self.half_width, d_start_angle, d_stop_angle, 'ccw', self.steps_per_circ)
  356. up_center = [point_x, point_y + self.half_height - self.half_width]
  357. u_start_angle = 0.0
  358. u_stop_angle = math.pi
  359. up_arc = arc(up_center, self.half_width, u_start_angle, u_stop_angle, 'ccw', self.steps_per_circ)
  360. geo.append(p1)
  361. for pt in down_arc:
  362. geo.append(pt)
  363. geo.append(p2)
  364. geo.append(p3)
  365. for pt in up_arc:
  366. geo.append(pt)
  367. geo.append(p4)
  368. if self.draw_app.slot_axis_radio.get_value() == 'A':
  369. return affinity.rotate(geom=Polygon(geo), angle=-slot_angle)
  370. else:
  371. return Polygon(geo)
  372. else:
  373. p1 = (point_x - self.half_width + self.half_height, point_y - self.half_height)
  374. p2 = (point_x + self.half_width - self.half_height, point_y - self.half_height)
  375. p3 = (point_x + self.half_width - self.half_height, point_y + self.half_height)
  376. p4 = (point_x - self.half_width + self.half_height, point_y + self.half_height)
  377. left_center = [point_x - self.half_width + self.half_height, point_y]
  378. d_start_angle = math.pi / 2
  379. d_stop_angle = 1.5 * math.pi
  380. left_arc = arc(left_center, self.half_height, d_start_angle, d_stop_angle, 'ccw', self.steps_per_circ)
  381. right_center = [point_x + self.half_width - self.half_height, point_y]
  382. u_start_angle = 1.5 * math.pi
  383. u_stop_angle = math.pi / 2
  384. right_arc = arc(right_center, self.half_height, u_start_angle, u_stop_angle, 'ccw', self.steps_per_circ)
  385. geo.append(p1)
  386. geo.append(p2)
  387. for pt in right_arc:
  388. geo.append(pt)
  389. geo.append(p3)
  390. geo.append(p4)
  391. for pt in left_arc:
  392. geo.append(pt)
  393. return Polygon(geo)
  394. def make(self):
  395. try:
  396. QtGui.QGuiApplication.restoreOverrideCursor()
  397. except Exception as e:
  398. pass
  399. try:
  400. self.geometry = DrawToolShape(self.util_shape(self.points))
  401. except Exception as e:
  402. log.debug("FCSlot.make() --> %s" % str(e))
  403. # add the point to drills/slots if the diameter is a key in the dict, if not, create it add the drill location
  404. # to the value, as a list of itself
  405. if self.selected_dia in self.draw_app.slot_points_edit:
  406. self.draw_app.slot_points_edit[self.selected_dia].append(self.points)
  407. else:
  408. self.draw_app.slot_points_edit[self.selected_dia] = [self.points]
  409. self.draw_app.current_storage = self.draw_app.storage_dict[self.selected_dia]
  410. self.draw_app.in_action = False
  411. self.complete = True
  412. self.draw_app.app.inform.emit(_("[success] Done. Adding Slot completed."))
  413. self.draw_app.slot_frame.hide()
  414. class FCSlotArray(FCShapeTool):
  415. """
  416. Resulting type: MultiPolygon
  417. """
  418. def __init__(self, draw_app):
  419. DrawTool.__init__(self, draw_app)
  420. self.name = 'slot_array'
  421. self.draw_app = draw_app
  422. self.draw_app.slot_frame.show()
  423. self.draw_app.slot_array_frame.show()
  424. self.selected_dia = None
  425. try:
  426. self.draw_app.app.inform.emit(_("Click to place ..."))
  427. self.selected_dia = self.draw_app.tool2tooldia[self.draw_app.last_tool_selected]
  428. # as a visual marker, select again in tooltable the actual tool that we are using
  429. # remember that it was deselected when clicking on canvas
  430. item = self.draw_app.tools_table_exc.item((self.draw_app.last_tool_selected - 1), 1)
  431. self.draw_app.tools_table_exc.setCurrentItem(item)
  432. except KeyError:
  433. self.draw_app.app.inform.emit(_("[WARNING_NOTCL] To add an Slot Array first select a tool in Tool Table"))
  434. return
  435. try:
  436. QtGui.QGuiApplication.restoreOverrideCursor()
  437. except Exception as e:
  438. pass
  439. self.cursor = QtGui.QCursor(QtGui.QPixmap('share/aero_array.png'))
  440. QtGui.QGuiApplication.setOverrideCursor(self.cursor)
  441. self.steps_per_circ = self.draw_app.app.defaults["geometry_circle_steps"]
  442. self.half_width = 0.0
  443. self.half_height = 0.0
  444. self.radius = float(self.selected_dia / 2.0)
  445. self.slot_axis = 'X'
  446. self.slot_array = 'linear'
  447. self.slot_array_size = None
  448. self.slot_pitch = None
  449. self.slot_linear_angle = None
  450. self.slot_angle = None
  451. self.slot_direction = None
  452. self.slot_radius = None
  453. self.origin = None
  454. self.destination = None
  455. self.flag_for_circ_array = None
  456. self.last_dx = 0
  457. self.last_dy = 0
  458. self.pt = []
  459. geo = self.utility_geometry(data=(self.draw_app.snap_x, self.draw_app.snap_y), static=True)
  460. if isinstance(geo, DrawToolShape) and geo.geo is not None:
  461. self.draw_app.draw_utility_geometry(geo=geo)
  462. self.draw_app.app.inform.emit(_("Click on target location ..."))
  463. # Switch notebook to Selected page
  464. self.draw_app.app.ui.notebook.setCurrentWidget(self.draw_app.app.ui.selected_tab)
  465. def click(self, point):
  466. if self.slot_array == 'Linear':
  467. self.make()
  468. return
  469. else:
  470. if self.flag_for_circ_array is None:
  471. self.draw_app.in_action = True
  472. self.pt.append(point)
  473. self.flag_for_circ_array = True
  474. self.set_origin(point)
  475. self.draw_app.app.inform.emit(_("Click on the Slot Circular Array Start position"))
  476. else:
  477. self.destination = point
  478. self.make()
  479. self.flag_for_circ_array = None
  480. return
  481. def set_origin(self, origin):
  482. self.origin = origin
  483. def utility_geometry(self, data=None, static=None):
  484. self.slot_axis = self.draw_app.slot_array_axis_radio.get_value()
  485. self.slot_direction = self.draw_app.slot_array_direction_radio.get_value()
  486. self.slot_array = self.draw_app.slot_array_type_combo.get_value()
  487. try:
  488. self.slot_array_size = int(self.draw_app.slot_array_size_entry.get_value())
  489. try:
  490. self.slot_pitch = float(self.draw_app.slot_array_pitch_entry.get_value())
  491. self.slot_linear_angle = float(self.draw_app.slot_array_linear_angle_spinner.get_value())
  492. self.slot_angle = float(self.draw_app.slot_array_angle_entry.get_value())
  493. except TypeError:
  494. self.draw_app.app.inform.emit(
  495. _("[ERROR_NOTCL] The value is not Float. Check for comma instead of dot separator."))
  496. return
  497. except Exception as e:
  498. self.draw_app.app.inform.emit(_("[ERROR_NOTCL] The value is mistyped. Check the value."))
  499. return
  500. if self.slot_array == 'Linear':
  501. if data[0] is None and data[1] is None:
  502. dx = self.draw_app.x
  503. dy = self.draw_app.y
  504. else:
  505. dx = data[0]
  506. dy = data[1]
  507. geo_el_list = []
  508. geo_el = []
  509. self.points = [dx, dy]
  510. for item in range(self.slot_array_size):
  511. if self.slot_axis == 'X':
  512. geo_el = self.util_shape(((dx + (self.slot_pitch * item)), dy))
  513. if self.slot_axis == 'Y':
  514. geo_el = self.util_shape((dx, (dy + (self.slot_pitch * item))))
  515. if self.slot_axis == 'A':
  516. x_adj = self.slot_pitch * math.cos(math.radians(self.slot_linear_angle))
  517. y_adj = self.slot_pitch * math.sin(math.radians(self.slot_linear_angle))
  518. geo_el = self.util_shape(
  519. ((dx + (x_adj * item)), (dy + (y_adj * item)))
  520. )
  521. if static is None or static is False:
  522. geo_el = affinity.translate(geo_el, xoff=(dx - self.last_dx), yoff=(dy - self.last_dy))
  523. geo_el_list.append(geo_el)
  524. self.last_dx = dx
  525. self.last_dy = dy
  526. return DrawToolUtilityShape(geo_el_list)
  527. else:
  528. if data[0] is None and data[1] is None:
  529. cdx = self.draw_app.x
  530. cdy = self.draw_app.y
  531. else:
  532. cdx = data[0]
  533. cdy = data[1]
  534. if len(self.pt) > 0:
  535. temp_points = [x for x in self.pt]
  536. temp_points.append([cdx, cdy])
  537. return DrawToolUtilityShape(LineString(temp_points))
  538. def util_shape(self, point):
  539. # updating values here allows us to change the aperture on the fly, after the Tool has been started
  540. self.selected_dia = self.draw_app.tool2tooldia[self.draw_app.last_tool_selected]
  541. self.radius = float(self.selected_dia / 2.0)
  542. self.steps_per_circ = self.draw_app.app.defaults["geometry_circle_steps"]
  543. try:
  544. slot_length = float(self.draw_app.slot_length_entry.get_value())
  545. except ValueError:
  546. # try to convert comma to decimal point. if it's still not working error message and return
  547. try:
  548. slot_length = float(self.draw_app.slot_length_entry.get_value().replace(',', '.'))
  549. self.draw_app.slot_length_entry.set_value(slot_length)
  550. except ValueError:
  551. self.draw_app.app.inform.emit(_("[WARNING_NOTCL] Value is missing or wrong format. "
  552. "Add it and retry."))
  553. return
  554. try:
  555. slot_angle = float(self.draw_app.slot_angle_spinner.get_value())
  556. except ValueError:
  557. self.draw_app.app.inform.emit(_("[WARNING_NOTCL] Value is missing or wrong format. "
  558. "Add it and retry."))
  559. return
  560. if self.draw_app.slot_axis_radio.get_value() == 'X':
  561. self.half_width = slot_length / 2.0
  562. self.half_height = self.radius
  563. else:
  564. self.half_width = self.radius
  565. self.half_height = slot_length / 2.0
  566. if point[0] is None and point[1] is None:
  567. point_x = self.draw_app.x
  568. point_y = self.draw_app.y
  569. else:
  570. point_x = point[0]
  571. point_y = point[1]
  572. geo = []
  573. if self.half_height > self.half_width:
  574. p1 = (point_x - self.half_width, point_y - self.half_height + self.half_width)
  575. p2 = (point_x + self.half_width, point_y - self.half_height + self.half_width)
  576. p3 = (point_x + self.half_width, point_y + self.half_height - self.half_width)
  577. p4 = (point_x - self.half_width, point_y + self.half_height - self.half_width)
  578. down_center = [point_x, point_y - self.half_height + self.half_width]
  579. d_start_angle = math.pi
  580. d_stop_angle = 0.0
  581. down_arc = arc(down_center, self.half_width, d_start_angle, d_stop_angle, 'ccw', self.steps_per_circ)
  582. up_center = [point_x, point_y + self.half_height - self.half_width]
  583. u_start_angle = 0.0
  584. u_stop_angle = math.pi
  585. up_arc = arc(up_center, self.half_width, u_start_angle, u_stop_angle, 'ccw', self.steps_per_circ)
  586. geo.append(p1)
  587. for pt in down_arc:
  588. geo.append(pt)
  589. geo.append(p2)
  590. geo.append(p3)
  591. for pt in up_arc:
  592. geo.append(pt)
  593. geo.append(p4)
  594. return Polygon(geo)
  595. else:
  596. p1 = (point_x - self.half_width + self.half_height, point_y - self.half_height)
  597. p2 = (point_x + self.half_width - self.half_height, point_y - self.half_height)
  598. p3 = (point_x + self.half_width - self.half_height, point_y + self.half_height)
  599. p4 = (point_x - self.half_width + self.half_height, point_y + self.half_height)
  600. left_center = [point_x - self.half_width + self.half_height, point_y]
  601. d_start_angle = math.pi / 2
  602. d_stop_angle = 1.5 * math.pi
  603. left_arc = arc(left_center, self.half_height, d_start_angle, d_stop_angle, 'ccw', self.steps_per_circ)
  604. right_center = [point_x + self.half_width - self.half_height, point_y]
  605. u_start_angle = 1.5 * math.pi
  606. u_stop_angle = math.pi / 2
  607. right_arc = arc(right_center, self.half_height, u_start_angle, u_stop_angle, 'ccw', self.steps_per_circ)
  608. geo.append(p1)
  609. geo.append(p2)
  610. for pt in right_arc:
  611. geo.append(pt)
  612. geo.append(p3)
  613. geo.append(p4)
  614. for pt in left_arc:
  615. geo.append(pt)
  616. return Polygon(geo)
  617. def make(self):
  618. self.geometry = []
  619. geo = None
  620. try:
  621. QtGui.QGuiApplication.restoreOverrideCursor()
  622. except Exception as e:
  623. pass
  624. # add the point to slots if the diameter is a key in the dict, if not, create it add the drill location
  625. # to the value, as a list of itself
  626. if self.selected_dia not in self.draw_app.slot_points_edit:
  627. self.draw_app.slot_points_edit[self.selected_dia] = []
  628. for i in range(self.slot_array_size):
  629. self.draw_app.slot_points_edit[self.selected_dia].append(self.points)
  630. self.draw_app.current_storage = self.draw_app.storage_dict[self.selected_dia]
  631. if self.slot_array == 'Linear':
  632. for item in range(self.slot_array_size):
  633. if self.slot_axis == 'X':
  634. geo = self.util_shape(((self.points[0] + (self.slot_pitch * item)), self.points[1]))
  635. if self.slot_axis == 'Y':
  636. geo = self.util_shape((self.points[0], (self.points[1] + (self.slot_pitch * item))))
  637. if self.slot_axis == 'A':
  638. x_adj = self.slot_pitch * math.cos(math.radians(self.slot_linear_angle))
  639. y_adj = self.slot_pitch * math.sin(math.radians(self.slot_linear_angle))
  640. geo = self.util_shape(
  641. ((self.points[0] + (x_adj * item)), (self.points[1] + (y_adj * item)))
  642. )
  643. self.geometry.append(DrawToolShape(geo))
  644. else:
  645. if (self.slot_angle * self.slot_array_size) > 360:
  646. self.draw_app.app.inform.emit(_("[WARNING_NOTCL] Too many Slots for the selected spacing angle."))
  647. return
  648. radius = distance(self.destination, self.origin)
  649. initial_angle = math.asin((self.destination[1] - self.origin[1]) / radius)
  650. for i in range(self.slot_array_size):
  651. angle_radians = math.radians(self.slot_angle * i)
  652. if self.slot_direction == 'CW':
  653. x = self.origin[0] + radius * math.cos(-angle_radians + initial_angle)
  654. y = self.origin[1] + radius * math.sin(-angle_radians + initial_angle)
  655. else:
  656. x = self.origin[0] + radius * math.cos(angle_radians + initial_angle)
  657. y = self.origin[1] + radius * math.sin(angle_radians + initial_angle)
  658. geo = self.util_shape((x, y))
  659. if self.slot_direction == 'CW':
  660. geo = affinity.rotate(geo, angle=(math.pi - angle_radians), use_radians=True)
  661. else:
  662. geo = affinity.rotate(geo, angle=(angle_radians - math.pi), use_radians=True)
  663. self.geometry.append(DrawToolShape(geo))
  664. self.complete = True
  665. self.draw_app.app.inform.emit(_("[success] Done. Slot Array added."))
  666. self.draw_app.in_action = False
  667. self.draw_app.slot_frame.hide()
  668. self.draw_app.slot_array_frame.hide()
  669. return
  670. def clean_up(self):
  671. self.draw_app.selected = []
  672. self.draw_app.apertures_table.clearSelection()
  673. self.draw_app.plot_all()
  674. class FCDrillResize(FCShapeTool):
  675. def __init__(self, draw_app):
  676. DrawTool.__init__(self, draw_app)
  677. self.name = 'drill_resize'
  678. self.draw_app.app.inform.emit(_("Click on the Drill(s) to resize ..."))
  679. self.resize_dia = None
  680. self.draw_app.resize_frame.show()
  681. self.points = None
  682. self.selected_dia_list = []
  683. self.current_storage = None
  684. self.geometry = []
  685. self.destination_storage = None
  686. self.draw_app.resize_btn.clicked.connect(self.make)
  687. # Switch notebook to Selected page
  688. self.draw_app.app.ui.notebook.setCurrentWidget(self.draw_app.app.ui.selected_tab)
  689. def make(self):
  690. self.draw_app.is_modified = True
  691. try:
  692. new_dia = self.draw_app.resdrill_entry.get_value()
  693. except:
  694. self.draw_app.app.inform.emit(
  695. _("[ERROR_NOTCL] Resize drill(s) failed. Please enter a diameter for resize.")
  696. )
  697. return
  698. if new_dia not in self.draw_app.olddia_newdia:
  699. self.destination_storage = FlatCAMGeoEditor.make_storage()
  700. self.draw_app.storage_dict[new_dia] = self.destination_storage
  701. # self.olddia_newdia dict keeps the evidence on current tools diameters as keys and gets updated on values
  702. # each time a tool diameter is edited or added
  703. self.draw_app.olddia_newdia[new_dia] = new_dia
  704. else:
  705. self.destination_storage = self.draw_app.storage_dict[new_dia]
  706. for index in self.draw_app.tools_table_exc.selectedIndexes():
  707. row = index.row()
  708. # on column 1 in tool tables we hold the diameters, and we retrieve them as strings
  709. # therefore below we convert to float
  710. dia_on_row = self.draw_app.tools_table_exc.item(row, 1).text()
  711. self.selected_dia_list.append(float(dia_on_row))
  712. # since we add a new tool, we update also the intial state of the tool_table through it's dictionary
  713. # we add a new entry in the tool2tooldia dict
  714. self.draw_app.tool2tooldia[len(self.draw_app.olddia_newdia)] = new_dia
  715. sel_shapes_to_be_deleted = []
  716. if self.selected_dia_list:
  717. for sel_dia in self.selected_dia_list:
  718. self.current_storage = self.draw_app.storage_dict[sel_dia]
  719. for select_shape in self.draw_app.get_selected():
  720. if select_shape in self.current_storage.get_objects():
  721. factor = new_dia / sel_dia
  722. self.geometry.append(
  723. DrawToolShape(affinity.scale(select_shape.geo, xfact=factor, yfact=factor, origin='center'))
  724. )
  725. self.current_storage.remove(select_shape)
  726. # a hack to make the tool_table display less drills per diameter when shape(drill) is deleted
  727. # self.points_edit it's only useful first time when we load the data into the storage
  728. # but is still used as reference when building tool_table in self.build_ui()
  729. # the number of drills displayed in column 2 is just a len(self.points_edit) therefore
  730. # deleting self.points_edit elements (doesn't matter who but just the number)
  731. # solved the display issue.
  732. del self.draw_app.points_edit[sel_dia][0]
  733. sel_shapes_to_be_deleted.append(select_shape)
  734. self.draw_app.on_exc_shape_complete(self.destination_storage)
  735. # a hack to make the tool_table display more drills per diameter when shape(drill) is added
  736. # self.points_edit it's only useful first time when we load the data into the storage
  737. # but is still used as reference when building tool_table in self.build_ui()
  738. # the number of drills displayed in column 2 is just a len(self.points_edit) therefore
  739. # deleting self.points_edit elements (doesn't matter who but just the number)
  740. # solved the display issue.
  741. if new_dia not in self.draw_app.points_edit:
  742. self.draw_app.points_edit[new_dia] = [(0, 0)]
  743. else:
  744. self.draw_app.points_edit[new_dia].append((0, 0))
  745. self.geometry = []
  746. # if following the resize of the drills there will be no more drills for the selected tool then
  747. # delete that tool
  748. if not self.draw_app.points_edit[sel_dia]:
  749. self.draw_app.on_tool_delete(sel_dia)
  750. for shp in sel_shapes_to_be_deleted:
  751. self.draw_app.selected.remove(shp)
  752. self.draw_app.build_ui()
  753. self.draw_app.replot()
  754. self.draw_app.app.inform.emit(_("[success] Done. Drill Resize completed."))
  755. else:
  756. self.draw_app.app.inform.emit(_("[WARNING_NOTCL] Cancelled. No drills selected for resize ..."))
  757. self.draw_app.resize_frame.hide()
  758. self.complete = True
  759. # MS: always return to the Select Tool
  760. self.draw_app.select_tool("drill_select")
  761. class FCDrillMove(FCShapeTool):
  762. def __init__(self, draw_app):
  763. DrawTool.__init__(self, draw_app)
  764. self.name = 'drill_move'
  765. # self.shape_buffer = self.draw_app.shape_buffer
  766. self.origin = None
  767. self.destination = None
  768. self.sel_limit = self.draw_app.app.defaults["excellon_editor_sel_limit"]
  769. self.selection_shape = self.selection_bbox()
  770. self.selected_dia_list = []
  771. if self.draw_app.launched_from_shortcuts is True:
  772. self.draw_app.launched_from_shortcuts = False
  773. self.draw_app.app.inform.emit(_("Click on target location ..."))
  774. else:
  775. self.draw_app.app.inform.emit(_("Click on reference location ..."))
  776. self.current_storage = None
  777. self.geometry = []
  778. for index in self.draw_app.tools_table_exc.selectedIndexes():
  779. row = index.row()
  780. # on column 1 in tool tables we hold the diameters, and we retrieve them as strings
  781. # therefore below we convert to float
  782. dia_on_row = self.draw_app.tools_table_exc.item(row, 1).text()
  783. self.selected_dia_list.append(float(dia_on_row))
  784. # Switch notebook to Selected page
  785. self.draw_app.app.ui.notebook.setCurrentWidget(self.draw_app.app.ui.selected_tab)
  786. def set_origin(self, origin):
  787. self.origin = origin
  788. def click(self, point):
  789. if len(self.draw_app.get_selected()) == 0:
  790. return "Nothing to move."
  791. if self.origin is None:
  792. self.set_origin(point)
  793. self.draw_app.app.inform.emit(_("Click on target location ..."))
  794. return
  795. else:
  796. self.destination = point
  797. self.make()
  798. # MS: always return to the Select Tool
  799. self.draw_app.select_tool("drill_select")
  800. return
  801. def make(self):
  802. # Create new geometry
  803. dx = self.destination[0] - self.origin[0]
  804. dy = self.destination[1] - self.origin[1]
  805. sel_shapes_to_be_deleted = []
  806. for sel_dia in self.selected_dia_list:
  807. self.current_storage = self.draw_app.storage_dict[sel_dia]
  808. for select_shape in self.draw_app.get_selected():
  809. if select_shape in self.current_storage.get_objects():
  810. self.geometry.append(DrawToolShape(affinity.translate(select_shape.geo, xoff=dx, yoff=dy)))
  811. self.current_storage.remove(select_shape)
  812. sel_shapes_to_be_deleted.append(select_shape)
  813. self.draw_app.on_exc_shape_complete(self.current_storage)
  814. self.geometry = []
  815. for shp in sel_shapes_to_be_deleted:
  816. self.draw_app.selected.remove(shp)
  817. sel_shapes_to_be_deleted = []
  818. self.draw_app.build_ui()
  819. self.draw_app.app.inform.emit(_("[success] Done. Drill(s) Move completed."))
  820. def selection_bbox(self):
  821. geo_list = []
  822. for select_shape in self.draw_app.get_selected():
  823. geometric_data = select_shape.geo
  824. try:
  825. for g in geometric_data:
  826. geo_list.append(g)
  827. except TypeError:
  828. geo_list.append(geometric_data)
  829. xmin, ymin, xmax, ymax = get_shapely_list_bounds(geo_list)
  830. pt1 = (xmin, ymin)
  831. pt2 = (xmax, ymin)
  832. pt3 = (xmax, ymax)
  833. pt4 = (xmin, ymax)
  834. return Polygon([pt1, pt2, pt3, pt4])
  835. def utility_geometry(self, data=None):
  836. """
  837. Temporary geometry on screen while using this tool.
  838. :param data:
  839. :return:
  840. """
  841. geo_list = []
  842. if self.origin is None:
  843. return None
  844. if len(self.draw_app.get_selected()) == 0:
  845. return None
  846. dx = data[0] - self.origin[0]
  847. dy = data[1] - self.origin[1]
  848. if len(self.draw_app.get_selected()) <= self.sel_limit:
  849. try:
  850. for geom in self.draw_app.get_selected():
  851. geo_list.append(affinity.translate(geom.geo, xoff=dx, yoff=dy))
  852. except AttributeError:
  853. self.draw_app.select_tool('drill_select')
  854. self.draw_app.selected = []
  855. return
  856. return DrawToolUtilityShape(geo_list)
  857. else:
  858. try:
  859. ss_el = affinity.translate(self.selection_shape, xoff=dx, yoff=dy)
  860. except ValueError:
  861. ss_el = None
  862. return DrawToolUtilityShape(ss_el)
  863. class FCDrillCopy(FCDrillMove):
  864. def __init__(self, draw_app):
  865. FCDrillMove.__init__(self, draw_app)
  866. self.name = 'drill_copy'
  867. def make(self):
  868. # Create new geometry
  869. dx = self.destination[0] - self.origin[0]
  870. dy = self.destination[1] - self.origin[1]
  871. sel_shapes_to_be_deleted = []
  872. for sel_dia in self.selected_dia_list:
  873. self.current_storage = self.draw_app.storage_dict[sel_dia]
  874. for select_shape in self.draw_app.get_selected():
  875. if select_shape in self.current_storage.get_objects():
  876. self.geometry.append(DrawToolShape(affinity.translate(select_shape.geo, xoff=dx, yoff=dy)))
  877. # Add some fake drills into the self.draw_app.points_edit to update the drill count in tool table
  878. # This may fail if we copy slots.
  879. try:
  880. self.draw_app.points_edit[sel_dia].append((0, 0))
  881. except KeyError:
  882. pass
  883. # add some fake slots into the self.draw_app.slots_points_edit
  884. # to update the slot count in tool table
  885. # This may fail if we copy drills.
  886. try:
  887. self.draw_app.slot_points_edit[sel_dia].append((0, 0))
  888. except KeyError:
  889. pass
  890. sel_shapes_to_be_deleted.append(select_shape)
  891. self.draw_app.on_exc_shape_complete(self.current_storage)
  892. self.geometry = []
  893. for shp in sel_shapes_to_be_deleted:
  894. self.draw_app.selected.remove(shp)
  895. sel_shapes_to_be_deleted = []
  896. self.draw_app.build_ui()
  897. self.draw_app.app.inform.emit(_("[success] Done. Drill(s) copied."))
  898. class FCDrillSelect(DrawTool):
  899. def __init__(self, exc_editor_app):
  900. DrawTool.__init__(self, exc_editor_app)
  901. self.name = 'drill_select'
  902. try:
  903. QtGui.QGuiApplication.restoreOverrideCursor()
  904. except Exception as e:
  905. pass
  906. self.exc_editor_app = exc_editor_app
  907. self.storage = self.exc_editor_app.storage_dict
  908. # self.selected = self.exc_editor_app.selected
  909. # here we store all shapes that were selected so we can search for the nearest to our click location
  910. self.sel_storage = FlatCAMExcEditor.make_storage()
  911. self.exc_editor_app.resize_frame.hide()
  912. self.exc_editor_app.array_frame.hide()
  913. self.exc_editor_app.slot_frame.hide()
  914. # self.exc_editor_app.slot_array_frame.hide()
  915. def click(self, point):
  916. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  917. if self.exc_editor_app.app.defaults["global_mselect_key"] == 'Control':
  918. if key_modifier == Qt.ControlModifier:
  919. pass
  920. else:
  921. self.exc_editor_app.selected = []
  922. else:
  923. if key_modifier == Qt.ShiftModifier:
  924. pass
  925. else:
  926. self.exc_editor_app.selected = []
  927. def click_release(self, pos):
  928. self.exc_editor_app.tools_table_exc.clearSelection()
  929. xmin, ymin, xmax, ymax = 0, 0, 0, 0
  930. try:
  931. for storage in self.exc_editor_app.storage_dict:
  932. for sh in self.exc_editor_app.storage_dict[storage].get_objects():
  933. self.sel_storage.insert(sh)
  934. _, closest_shape = self.sel_storage.nearest(pos)
  935. # constrain selection to happen only within a certain bounding box; it works only for MultiLineStrings
  936. if isinstance(closest_shape.geo, MultiLineString):
  937. x_coord, y_coord = closest_shape.geo[0].xy
  938. delta = (x_coord[1] - x_coord[0])
  939. # closest_shape_coords = (((x_coord[0] + delta / 2)), y_coord[0])
  940. xmin = x_coord[0] - (0.7 * delta)
  941. xmax = x_coord[0] + (1.7 * delta)
  942. ymin = y_coord[0] - (0.7 * delta)
  943. ymax = y_coord[0] + (1.7 * delta)
  944. elif isinstance(closest_shape.geo, Polygon):
  945. xmin, ymin, xmax, ymax = closest_shape.geo.bounds
  946. dx = xmax - xmin
  947. dy = ymax - ymin
  948. delta = dx if dx > dy else dy
  949. xmin -= 0.7 * delta
  950. xmax += 0.7 * delta
  951. ymin -= 0.7 * delta
  952. ymax += 0.7 * delta
  953. except StopIteration:
  954. return ""
  955. if pos[0] < xmin or pos[0] > xmax or pos[1] < ymin or pos[1] > ymax:
  956. self.exc_editor_app.selected = []
  957. else:
  958. modifiers = QtWidgets.QApplication.keyboardModifiers()
  959. mod_key = 'Control'
  960. if modifiers == QtCore.Qt.ShiftModifier:
  961. mod_key = 'Shift'
  962. elif modifiers == QtCore.Qt.ControlModifier:
  963. mod_key = 'Control'
  964. if mod_key == self.draw_app.app.defaults["global_mselect_key"]:
  965. if closest_shape in self.exc_editor_app.selected:
  966. self.exc_editor_app.selected.remove(closest_shape)
  967. else:
  968. self.exc_editor_app.selected.append(closest_shape)
  969. else:
  970. self.draw_app.selected = []
  971. self.draw_app.selected.append(closest_shape)
  972. # select the diameter of the selected shape in the tool table
  973. try:
  974. self.draw_app.tools_table_exc.cellPressed.disconnect()
  975. except (TypeError, AttributeError):
  976. pass
  977. sel_tools = set()
  978. self.exc_editor_app.tools_table_exc.setSelectionMode(QtWidgets.QAbstractItemView.MultiSelection)
  979. for shape_s in self.exc_editor_app.selected:
  980. for storage in self.exc_editor_app.storage_dict:
  981. if shape_s in self.exc_editor_app.storage_dict[storage].get_objects():
  982. sel_tools.add(storage)
  983. for storage in sel_tools:
  984. for k, v in self.draw_app.tool2tooldia.items():
  985. if v == storage:
  986. self.exc_editor_app.tools_table_exc.selectRow(int(k) - 1)
  987. self.draw_app.last_tool_selected = int(k)
  988. break
  989. self.exc_editor_app.tools_table_exc.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
  990. self.draw_app.tools_table_exc.cellPressed.connect(self.draw_app.on_row_selected)
  991. # delete whatever is in selection storage, there is no longer need for those shapes
  992. self.sel_storage = FlatCAMExcEditor.make_storage()
  993. return ""
  994. # pos[0] and pos[1] are the mouse click coordinates (x, y)
  995. # for storage in self.exc_editor_app.storage_dict:
  996. # for obj_shape in self.exc_editor_app.storage_dict[storage].get_objects():
  997. # minx, miny, maxx, maxy = obj_shape.geo.bounds
  998. # if (minx <= pos[0] <= maxx) and (miny <= pos[1] <= maxy):
  999. # over_shape_list.append(obj_shape)
  1000. #
  1001. # try:
  1002. # # if there is no shape under our click then deselect all shapes
  1003. # if not over_shape_list:
  1004. # self.exc_editor_app.selected = []
  1005. # FlatCAMExcEditor.draw_shape_idx = -1
  1006. # self.exc_editor_app.tools_table_exc.clearSelection()
  1007. # else:
  1008. # # if there are shapes under our click then advance through the list of them, one at the time in a
  1009. # # circular way
  1010. # FlatCAMExcEditor.draw_shape_idx = (FlatCAMExcEditor.draw_shape_idx + 1) % len(over_shape_list)
  1011. # obj_to_add = over_shape_list[int(FlatCAMExcEditor.draw_shape_idx)]
  1012. #
  1013. # if self.exc_editor_app.app.defaults["global_mselect_key"] == 'Shift':
  1014. # if self.exc_editor_app.modifiers == Qt.ShiftModifier:
  1015. # if obj_to_add in self.exc_editor_app.selected:
  1016. # self.exc_editor_app.selected.remove(obj_to_add)
  1017. # else:
  1018. # self.exc_editor_app.selected.append(obj_to_add)
  1019. # else:
  1020. # self.exc_editor_app.selected = []
  1021. # self.exc_editor_app.selected.append(obj_to_add)
  1022. # else:
  1023. # # if CONTROL key is pressed then we add to the selected list the current shape but if it's already
  1024. # # in the selected list, we removed it. Therefore first click selects, second deselects.
  1025. # if self.exc_editor_app.modifiers == Qt.ControlModifier:
  1026. # if obj_to_add in self.exc_editor_app.selected:
  1027. # self.exc_editor_app.selected.remove(obj_to_add)
  1028. # else:
  1029. # self.exc_editor_app.selected.append(obj_to_add)
  1030. # else:
  1031. # self.exc_editor_app.selected = []
  1032. # self.exc_editor_app.selected.append(obj_to_add)
  1033. #
  1034. # for storage in self.exc_editor_app.storage_dict:
  1035. # for shape in self.exc_editor_app.selected:
  1036. # if shape in self.exc_editor_app.storage_dict[storage].get_objects():
  1037. # for key in self.exc_editor_app.tool2tooldia:
  1038. # if self.exc_editor_app.tool2tooldia[key] == storage:
  1039. # item = self.exc_editor_app.tools_table_exc.item((key - 1), 1)
  1040. # item.setSelected(True)
  1041. # # self.exc_editor_app.tools_table_exc.selectItem(key - 1)
  1042. #
  1043. # except Exception as e:
  1044. # log.error("[ERROR] Something went bad. %s" % str(e))
  1045. # raise
  1046. class FlatCAMExcEditor(QtCore.QObject):
  1047. draw_shape_idx = -1
  1048. def __init__(self, app):
  1049. assert isinstance(app, FlatCAMApp.App), "Expected the app to be a FlatCAMApp.App, got %s" % type(app)
  1050. super(FlatCAMExcEditor, self).__init__()
  1051. self.app = app
  1052. self.canvas = self.app.plotcanvas
  1053. # ## Current application units in Upper Case
  1054. self.units = self.app.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  1055. self.exc_edit_widget = QtWidgets.QWidget()
  1056. # ## Box for custom widgets
  1057. # This gets populated in offspring implementations.
  1058. layout = QtWidgets.QVBoxLayout()
  1059. self.exc_edit_widget.setLayout(layout)
  1060. # add a frame and inside add a vertical box layout. Inside this vbox layout I add all the Drills widgets
  1061. # this way I can hide/show the frame
  1062. self.drills_frame = QtWidgets.QFrame()
  1063. self.drills_frame.setContentsMargins(0, 0, 0, 0)
  1064. layout.addWidget(self.drills_frame)
  1065. self.tools_box = QtWidgets.QVBoxLayout()
  1066. self.tools_box.setContentsMargins(0, 0, 0, 0)
  1067. self.drills_frame.setLayout(self.tools_box)
  1068. # ## Page Title box (spacing between children)
  1069. self.title_box = QtWidgets.QHBoxLayout()
  1070. self.tools_box.addLayout(self.title_box)
  1071. # ## Page Title icon
  1072. pixmap = QtGui.QPixmap('share/flatcam_icon32.png')
  1073. self.icon = QtWidgets.QLabel()
  1074. self.icon.setPixmap(pixmap)
  1075. self.title_box.addWidget(self.icon, stretch=0)
  1076. # ## Title label
  1077. self.title_label = QtWidgets.QLabel("<font size=5><b>%s</b></font>" % _('Excellon Editor'))
  1078. self.title_label.setAlignment(QtCore.Qt.AlignLeft | QtCore.Qt.AlignVCenter)
  1079. self.title_box.addWidget(self.title_label, stretch=1)
  1080. # ## Object name
  1081. self.name_box = QtWidgets.QHBoxLayout()
  1082. self.tools_box.addLayout(self.name_box)
  1083. name_label = QtWidgets.QLabel(_("Name:"))
  1084. self.name_box.addWidget(name_label)
  1085. self.name_entry = FCEntry()
  1086. self.name_box.addWidget(self.name_entry)
  1087. # ### Tools Drills ## ##
  1088. self.tools_table_label = QtWidgets.QLabel("<b>%s</b>" % _('Tools Table'))
  1089. self.tools_table_label.setToolTip(
  1090. _("Tools in this Excellon object\n"
  1091. "when are used for drilling.")
  1092. )
  1093. self.tools_box.addWidget(self.tools_table_label)
  1094. self.tools_table_exc = FCTable()
  1095. # delegate = SpinBoxDelegate(units=self.units)
  1096. # self.tools_table_exc.setItemDelegateForColumn(1, delegate)
  1097. self.tools_box.addWidget(self.tools_table_exc)
  1098. self.tools_table_exc.setColumnCount(4)
  1099. self.tools_table_exc.setHorizontalHeaderLabels(['#', _('Diameter'), 'D', 'S'])
  1100. self.tools_table_exc.setSortingEnabled(False)
  1101. self.tools_table_exc.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectRows)
  1102. self.empty_label = QtWidgets.QLabel('')
  1103. self.tools_box.addWidget(self.empty_label)
  1104. # ### Add a new Tool ## ##
  1105. self.addtool_label = QtWidgets.QLabel('<b>%s</b>' % _('Add/Delete Tool'))
  1106. self.addtool_label.setToolTip(
  1107. _("Add/Delete a tool to the tool list\n"
  1108. "for this Excellon object.")
  1109. )
  1110. self.tools_box.addWidget(self.addtool_label)
  1111. grid1 = QtWidgets.QGridLayout()
  1112. self.tools_box.addLayout(grid1)
  1113. addtool_entry_lbl = QtWidgets.QLabel(_('Tool Dia:'))
  1114. addtool_entry_lbl.setToolTip(
  1115. _("Diameter for the new tool")
  1116. )
  1117. hlay = QtWidgets.QHBoxLayout()
  1118. self.addtool_entry = FCEntry()
  1119. self.addtool_entry.setValidator(QtGui.QDoubleValidator(0.0001, 99.9999, 4))
  1120. hlay.addWidget(self.addtool_entry)
  1121. self.addtool_btn = QtWidgets.QPushButton(_('Add Tool'))
  1122. self.addtool_btn.setToolTip(
  1123. _("Add a new tool to the tool list\n"
  1124. "with the diameter specified above.")
  1125. )
  1126. self.addtool_btn.setFixedWidth(80)
  1127. hlay.addWidget(self.addtool_btn)
  1128. grid1.addWidget(addtool_entry_lbl, 0, 0)
  1129. grid1.addLayout(hlay, 0, 1)
  1130. grid2 = QtWidgets.QGridLayout()
  1131. self.tools_box.addLayout(grid2)
  1132. self.deltool_btn = QtWidgets.QPushButton(_('Delete Tool'))
  1133. self.deltool_btn.setToolTip(
  1134. _("Delete a tool in the tool list\n"
  1135. "by selecting a row in the tool table.")
  1136. )
  1137. grid2.addWidget(self.deltool_btn, 0, 1)
  1138. # add a frame and inside add a vertical box layout. Inside this vbox layout I add all the Drills widgets
  1139. # this way I can hide/show the frame
  1140. self.resize_frame = QtWidgets.QFrame()
  1141. self.resize_frame.setContentsMargins(0, 0, 0, 0)
  1142. self.tools_box.addWidget(self.resize_frame)
  1143. self.resize_box = QtWidgets.QVBoxLayout()
  1144. self.resize_box.setContentsMargins(0, 0, 0, 0)
  1145. self.resize_frame.setLayout(self.resize_box)
  1146. # ### Resize a drill ## ##
  1147. self.emptyresize_label = QtWidgets.QLabel('')
  1148. self.resize_box.addWidget(self.emptyresize_label)
  1149. self.drillresize_label = QtWidgets.QLabel('<b>%s</b>' % _("Resize Drill(s)"))
  1150. self.drillresize_label.setToolTip(
  1151. _("Resize a drill or a selection of drills.")
  1152. )
  1153. self.resize_box.addWidget(self.drillresize_label)
  1154. grid3 = QtWidgets.QGridLayout()
  1155. self.resize_box.addLayout(grid3)
  1156. res_entry_lbl = QtWidgets.QLabel(_('Resize Dia:'))
  1157. res_entry_lbl.setToolTip(
  1158. _("Diameter to resize to.")
  1159. )
  1160. grid3.addWidget(res_entry_lbl, 0, 0)
  1161. hlay2 = QtWidgets.QHBoxLayout()
  1162. self.resdrill_entry = LengthEntry()
  1163. hlay2.addWidget(self.resdrill_entry)
  1164. self.resize_btn = QtWidgets.QPushButton(_('Resize'))
  1165. self.resize_btn.setToolTip(
  1166. _("Resize drill(s)")
  1167. )
  1168. self.resize_btn.setFixedWidth(80)
  1169. hlay2.addWidget(self.resize_btn)
  1170. grid3.addLayout(hlay2, 0, 1)
  1171. self.resize_frame.hide()
  1172. # add a frame and inside add a vertical box layout. Inside this vbox layout I add
  1173. # all the add drill array widgets
  1174. # this way I can hide/show the frame
  1175. self.array_frame = QtWidgets.QFrame()
  1176. self.array_frame.setContentsMargins(0, 0, 0, 0)
  1177. self.tools_box.addWidget(self.array_frame)
  1178. self.array_box = QtWidgets.QVBoxLayout()
  1179. self.array_box.setContentsMargins(0, 0, 0, 0)
  1180. self.array_frame.setLayout(self.array_box)
  1181. # ### Add DRILL Array ## ##
  1182. self.emptyarray_label = QtWidgets.QLabel('')
  1183. self.array_box.addWidget(self.emptyarray_label)
  1184. self.drillarray_label = QtWidgets.QLabel('<b>%s</b>' % _("Add Drill Array"))
  1185. self.drillarray_label.setToolTip(
  1186. _("Add an array of drills (linear or circular array)")
  1187. )
  1188. self.array_box.addWidget(self.drillarray_label)
  1189. self.array_type_combo = FCComboBox()
  1190. self.array_type_combo.setToolTip(
  1191. _("Select the type of drills array to create.\n"
  1192. "It can be Linear X(Y) or Circular")
  1193. )
  1194. self.array_type_combo.addItem(_("Linear"))
  1195. self.array_type_combo.addItem(_("Circular"))
  1196. self.array_box.addWidget(self.array_type_combo)
  1197. self.array_form = QtWidgets.QFormLayout()
  1198. self.array_box.addLayout(self.array_form)
  1199. # Set the number of drill holes in the drill array
  1200. self.drill_array_size_label = QtWidgets.QLabel(_('Nr of drills:'))
  1201. self.drill_array_size_label.setToolTip(_("Specify how many drills to be in the array."))
  1202. self.drill_array_size_label.setMinimumWidth(100)
  1203. self.drill_array_size_entry = LengthEntry()
  1204. self.array_form.addRow(self.drill_array_size_label, self.drill_array_size_entry)
  1205. self.array_linear_frame = QtWidgets.QFrame()
  1206. self.array_linear_frame.setContentsMargins(0, 0, 0, 0)
  1207. self.array_box.addWidget(self.array_linear_frame)
  1208. self.linear_box = QtWidgets.QVBoxLayout()
  1209. self.linear_box.setContentsMargins(0, 0, 0, 0)
  1210. self.array_linear_frame.setLayout(self.linear_box)
  1211. self.linear_form = QtWidgets.QFormLayout()
  1212. self.linear_box.addLayout(self.linear_form)
  1213. # Linear Drill Array direction
  1214. self.drill_axis_label = QtWidgets.QLabel(_('Direction:'))
  1215. self.drill_axis_label.setToolTip(
  1216. _("Direction on which the linear array is oriented:\n"
  1217. "- 'X' - horizontal axis \n"
  1218. "- 'Y' - vertical axis or \n"
  1219. "- 'Angle' - a custom angle for the array inclination")
  1220. )
  1221. self.drill_axis_label.setMinimumWidth(100)
  1222. self.drill_axis_radio = RadioSet([{'label': _('X'), 'value': 'X'},
  1223. {'label': _('Y'), 'value': 'Y'},
  1224. {'label': _('Angle'), 'value': 'A'}])
  1225. self.linear_form.addRow(self.drill_axis_label, self.drill_axis_radio)
  1226. # Linear Drill Array pitch distance
  1227. self.drill_pitch_label = QtWidgets.QLabel(_('Pitch:'))
  1228. self.drill_pitch_label.setToolTip(
  1229. _("Pitch = Distance between elements of the array.")
  1230. )
  1231. self.drill_pitch_label.setMinimumWidth(100)
  1232. self.drill_pitch_entry = LengthEntry()
  1233. self.linear_form.addRow(self.drill_pitch_label, self.drill_pitch_entry)
  1234. # Linear Drill Array angle
  1235. self.linear_angle_label = QtWidgets.QLabel(_('Angle:'))
  1236. self.linear_angle_label.setToolTip(
  1237. _("Angle at which the linear array is placed.\n"
  1238. "The precision is of max 2 decimals.\n"
  1239. "Min value is: -359.99 degrees.\n"
  1240. "Max value is: 360.00 degrees.")
  1241. )
  1242. self.linear_angle_label.setMinimumWidth(100)
  1243. self.linear_angle_spinner = FCDoubleSpinner()
  1244. self.linear_angle_spinner.set_precision(2)
  1245. self.linear_angle_spinner.setSingleStep(1.0)
  1246. self.linear_angle_spinner.setRange(-359.99, 360.00)
  1247. self.linear_form.addRow(self.linear_angle_label, self.linear_angle_spinner)
  1248. self.array_circular_frame = QtWidgets.QFrame()
  1249. self.array_circular_frame.setContentsMargins(0, 0, 0, 0)
  1250. self.array_box.addWidget(self.array_circular_frame)
  1251. self.circular_box = QtWidgets.QVBoxLayout()
  1252. self.circular_box.setContentsMargins(0, 0, 0, 0)
  1253. self.array_circular_frame.setLayout(self.circular_box)
  1254. self.drill_direction_label = QtWidgets.QLabel(_('Direction:'))
  1255. self.drill_direction_label.setToolTip(_("Direction for circular array."
  1256. "Can be CW = clockwise or CCW = counter clockwise."))
  1257. self.drill_direction_label.setMinimumWidth(100)
  1258. self.circular_form = QtWidgets.QFormLayout()
  1259. self.circular_box.addLayout(self.circular_form)
  1260. self.drill_direction_radio = RadioSet([{'label': _('CW'), 'value': 'CW'},
  1261. {'label': _('CCW'), 'value': 'CCW'}])
  1262. self.circular_form.addRow(self.drill_direction_label, self.drill_direction_radio)
  1263. self.drill_angle_label = QtWidgets.QLabel(_('Angle:'))
  1264. self.drill_angle_label.setToolTip(_("Angle at which each element in circular array is placed."))
  1265. self.drill_angle_label.setMinimumWidth(100)
  1266. self.drill_angle_entry = LengthEntry()
  1267. self.circular_form.addRow(self.drill_angle_label, self.drill_angle_entry)
  1268. self.array_circular_frame.hide()
  1269. self.linear_angle_spinner.hide()
  1270. self.linear_angle_label.hide()
  1271. self.array_frame.hide()
  1272. # ######################################################
  1273. # ##### ADDING SLOTS ###################################
  1274. # ######################################################
  1275. # add a frame and inside add a vertical box layout. Inside this vbox layout I add
  1276. # all the add slot widgets
  1277. # this way I can hide/show the frame
  1278. self.slot_frame = QtWidgets.QFrame()
  1279. self.slot_frame.setContentsMargins(0, 0, 0, 0)
  1280. self.tools_box.addWidget(self.slot_frame)
  1281. self.slot_box = QtWidgets.QVBoxLayout()
  1282. self.slot_box.setContentsMargins(0, 0, 0, 0)
  1283. self.slot_frame.setLayout(self.slot_box)
  1284. self.emptyarray_label = QtWidgets.QLabel('')
  1285. self.slot_box.addWidget(self.emptyarray_label)
  1286. self.slot_label = QtWidgets.QLabel('<b>%s</b>' % _("Add Slot"))
  1287. self.slot_label.setToolTip(
  1288. _("Add slot (hole with oval shape)")
  1289. )
  1290. self.slot_box.addWidget(self.slot_label)
  1291. self.slot_form = QtWidgets.QFormLayout()
  1292. self.slot_box.addLayout(self.slot_form)
  1293. # Slot length
  1294. self.slot_length_label = QtWidgets.QLabel(_('Length:'))
  1295. self.slot_length_label.setToolTip(
  1296. _("Length = The length of the slot.")
  1297. )
  1298. self.slot_length_label.setMinimumWidth(100)
  1299. self.slot_length_entry = LengthEntry()
  1300. self.slot_form.addRow(self.slot_length_label, self.slot_length_entry)
  1301. # Slot direction
  1302. self.slot_axis_label = QtWidgets.QLabel(_('Direction:'))
  1303. self.slot_axis_label.setToolTip(
  1304. _("Direction on which the slot is oriented:\n"
  1305. "- 'X' - horizontal axis \n"
  1306. "- 'Y' - vertical axis or \n"
  1307. "- 'Angle' - a custom angle for the slot inclination")
  1308. )
  1309. self.slot_axis_label.setMinimumWidth(100)
  1310. self.slot_axis_radio = RadioSet([{'label': _('X'), 'value': 'X'},
  1311. {'label': _('Y'), 'value': 'Y'},
  1312. {'label': _('Angle'), 'value': 'A'}])
  1313. self.slot_form.addRow(self.slot_axis_label, self.slot_axis_radio)
  1314. # Slot custom angle
  1315. self.slot_angle_label = QtWidgets.QLabel(_('Angle:'))
  1316. self.slot_angle_label.setToolTip(
  1317. _("Angle at which the slot is placed.\n"
  1318. "The precision is of max 2 decimals.\n"
  1319. "Min value is: -359.99 degrees.\n"
  1320. "Max value is: 360.00 degrees.")
  1321. )
  1322. self.slot_angle_label.setMinimumWidth(100)
  1323. self.slot_angle_spinner = FCDoubleSpinner()
  1324. self.slot_angle_spinner.set_precision(2)
  1325. self.slot_angle_spinner.setWrapping(True)
  1326. self.slot_angle_spinner.setRange(-359.99, 360.00)
  1327. self.slot_angle_spinner.setSingleStep(1.0)
  1328. self.slot_form.addRow(self.slot_angle_label, self.slot_angle_spinner)
  1329. self.slot_frame.hide()
  1330. # ######################################################
  1331. # ##### ADDING SLOT ARRAY #############################
  1332. # ######################################################
  1333. # add a frame and inside add a vertical box layout. Inside this vbox layout I add
  1334. # all the add slot widgets
  1335. # this way I can hide/show the frame
  1336. self.slot_array_frame = QtWidgets.QFrame()
  1337. self.slot_array_frame.setContentsMargins(0, 0, 0, 0)
  1338. self.tools_box.addWidget(self.slot_array_frame)
  1339. self.slot_array_box = QtWidgets.QVBoxLayout()
  1340. self.slot_array_box.setContentsMargins(0, 0, 0, 0)
  1341. self.slot_array_frame.setLayout(self.slot_array_box)
  1342. self.emptyarray_label = QtWidgets.QLabel('')
  1343. self.slot_array_box.addWidget(self.emptyarray_label)
  1344. self.slot_array_label = QtWidgets.QLabel('<b>%s</b>' % _("Add SLOT Array"))
  1345. self.slot_array_label.setToolTip(
  1346. _("Add an array of slots (linear or circular array)")
  1347. )
  1348. self.slot_array_box.addWidget(self.slot_array_label)
  1349. self.l_form = QtWidgets.QFormLayout()
  1350. self.slot_array_box.addLayout(self.l_form)
  1351. # Slot length in array
  1352. self.array_slot_length_label = QtWidgets.QLabel(_('Length:'))
  1353. self.array_slot_length_label.setToolTip(
  1354. _("Length = The length of the slot.")
  1355. )
  1356. self.array_slot_length_label.setMinimumWidth(100)
  1357. self.array_slot_length_entry = LengthEntry()
  1358. self.l_form.addRow(self.array_slot_length_label, self.array_slot_length_entry)
  1359. self.slot_array_type_combo = FCComboBox()
  1360. self.slot_array_type_combo.setToolTip(
  1361. _("Select the type of slot array to create.\n"
  1362. "It can be Linear X(Y) or Circular")
  1363. )
  1364. self.slot_array_type_combo.addItem(_("Linear"))
  1365. self.slot_array_type_combo.addItem(_("Circular"))
  1366. self.slot_array_box.addWidget(self.slot_array_type_combo)
  1367. self.slot_array_form = QtWidgets.QFormLayout()
  1368. self.slot_array_box.addLayout(self.slot_array_form)
  1369. # Set the number of slot holes in the slot array
  1370. self.slot_array_size_label = QtWidgets.QLabel(_('Nr of slots:'))
  1371. self.slot_array_size_label.setToolTip(_("Specify how many slots to be in the array."))
  1372. self.slot_array_size_label.setMinimumWidth(100)
  1373. self.slot_array_size_entry = LengthEntry()
  1374. self.slot_array_form.addRow(self.slot_array_size_label, self.slot_array_size_entry)
  1375. self.slot_array_linear_frame = QtWidgets.QFrame()
  1376. self.slot_array_linear_frame.setContentsMargins(0, 0, 0, 0)
  1377. self.slot_array_box.addWidget(self.slot_array_linear_frame)
  1378. self.slot_array_linear_box = QtWidgets.QVBoxLayout()
  1379. self.slot_array_linear_box.setContentsMargins(0, 0, 0, 0)
  1380. self.slot_array_linear_frame.setLayout(self.slot_array_linear_box)
  1381. self.slot_array_linear_form = QtWidgets.QFormLayout()
  1382. self.slot_array_linear_box.addLayout(self.slot_array_linear_form)
  1383. # Linear Slot Array direction
  1384. self.slot_array_axis_label = QtWidgets.QLabel(_('Direction:'))
  1385. self.slot_array_axis_label.setToolTip(
  1386. _("Direction on which the linear array is oriented:\n"
  1387. "- 'X' - horizontal axis \n"
  1388. "- 'Y' - vertical axis or \n"
  1389. "- 'Angle' - a custom angle for the array inclination")
  1390. )
  1391. self.slot_array_axis_label.setMinimumWidth(100)
  1392. self.slot_array_axis_radio = RadioSet([{'label': _('X'), 'value': 'X'},
  1393. {'label': _('Y'), 'value': 'Y'},
  1394. {'label': _('Angle'), 'value': 'A'}])
  1395. self.slot_array_linear_form.addRow(self.slot_array_axis_label, self.slot_array_axis_radio)
  1396. # Linear Slot Array pitch distance
  1397. self.slot_array_pitch_label = QtWidgets.QLabel(_('Pitch:'))
  1398. self.slot_array_pitch_label.setToolTip(
  1399. _("Pitch = Distance between elements of the array.")
  1400. )
  1401. self.slot_array_pitch_label.setMinimumWidth(100)
  1402. self.slot_array_pitch_entry = LengthEntry()
  1403. self.slot_array_linear_form.addRow(self.slot_array_pitch_label, self.slot_array_pitch_entry)
  1404. # Linear Slot Array angle
  1405. self.slot_array_linear_angle_label = QtWidgets.QLabel(_('Angle:'))
  1406. self.slot_array_linear_angle_label.setToolTip(
  1407. _("Angle at which the linear array is placed.\n"
  1408. "The precision is of max 2 decimals.\n"
  1409. "Min value is: -359.99 degrees.\n"
  1410. "Max value is: 360.00 degrees.")
  1411. )
  1412. self.slot_array_linear_angle_label.setMinimumWidth(100)
  1413. self.slot_array_linear_angle_spinner = FCDoubleSpinner()
  1414. self.slot_array_linear_angle_spinner.set_precision(2)
  1415. self.slot_array_linear_angle_spinner.setSingleStep(1.0)
  1416. self.slot_array_linear_angle_spinner.setRange(-359.99, 360.00)
  1417. self.slot_array_linear_form.addRow(self.slot_array_linear_angle_label, self.slot_array_linear_angle_spinner)
  1418. self.slot_array_circular_frame = QtWidgets.QFrame()
  1419. self.slot_array_circular_frame.setContentsMargins(0, 0, 0, 0)
  1420. self.slot_array_box.addWidget(self.slot_array_circular_frame)
  1421. self.slot_array_circular_box = QtWidgets.QVBoxLayout()
  1422. self.slot_array_circular_box.setContentsMargins(0, 0, 0, 0)
  1423. self.slot_array_circular_frame.setLayout(self.slot_array_circular_box)
  1424. self.slot_array_direction_label = QtWidgets.QLabel(_('Direction:'))
  1425. self.slot_array_direction_label.setToolTip(_("Direction for circular array."
  1426. "Can be CW = clockwise or CCW = counter clockwise."))
  1427. self.slot_array_direction_label.setMinimumWidth(100)
  1428. self.slot_array_circular_form = QtWidgets.QFormLayout()
  1429. self.slot_array_circular_box.addLayout(self.slot_array_circular_form)
  1430. self.slot_array_direction_radio = RadioSet([{'label': _('CW'), 'value': 'CW'},
  1431. {'label': _('CCW'), 'value': 'CCW'}])
  1432. self.slot_array_circular_form.addRow(self.slot_array_direction_label, self.slot_array_direction_radio)
  1433. self.slot_array_angle_label = QtWidgets.QLabel(_('Angle:'))
  1434. self.slot_array_angle_label.setToolTip(_("Angle at which each element in circular array is placed."))
  1435. self.slot_array_angle_label.setMinimumWidth(100)
  1436. self.slot_array_angle_entry = LengthEntry()
  1437. self.slot_array_circular_form.addRow(self.slot_array_angle_label, self.slot_array_angle_entry)
  1438. self.slot_array_linear_angle_spinner.hide()
  1439. self.slot_array_linear_angle_label.hide()
  1440. self.slot_array_frame.hide()
  1441. self.tools_box.addStretch()
  1442. # ## Toolbar events and properties
  1443. self.tools_exc = {
  1444. "drill_select": {"button": self.app.ui.select_drill_btn,
  1445. "constructor": FCDrillSelect},
  1446. "drill_add": {"button": self.app.ui.add_drill_btn,
  1447. "constructor": FCDrillAdd},
  1448. "drill_array": {"button": self.app.ui.add_drill_array_btn,
  1449. "constructor": FCDrillArray},
  1450. "slot_add": {"button": self.app.ui.add_slot_btn,
  1451. "constructor": FCSlot},
  1452. "slot_array": {"button": self.app.ui.add_slot_array_btn,
  1453. "constructor": FCSlotArray},
  1454. "drill_resize": {"button": self.app.ui.resize_drill_btn,
  1455. "constructor": FCDrillResize},
  1456. "drill_copy": {"button": self.app.ui.copy_drill_btn,
  1457. "constructor": FCDrillCopy},
  1458. "drill_move": {"button": self.app.ui.move_drill_btn,
  1459. "constructor": FCDrillMove},
  1460. }
  1461. # ## Data
  1462. self.active_tool = None
  1463. self.in_action = False
  1464. self.storage_dict = {}
  1465. self.current_storage = []
  1466. # build the data from the Excellon point into a dictionary
  1467. # {tool_dia: [geometry_in_points]}
  1468. self.points_edit = {}
  1469. self.slot_points_edit = {}
  1470. self.sorted_diameters = []
  1471. self.new_drills = []
  1472. self.new_tools = {}
  1473. self.new_slots = []
  1474. self.new_tool_offset = {}
  1475. # dictionary to store the tool_row and diameters in Tool_table
  1476. # it will be updated everytime self.build_ui() is called
  1477. self.olddia_newdia = {}
  1478. self.tool2tooldia = {}
  1479. # this will store the value for the last selected tool, for use after clicking on canvas when the selection
  1480. # is cleared but as a side effect also the selected tool is cleared
  1481. self.last_tool_selected = None
  1482. self.utility = []
  1483. # this will flag if the Editor "tools" are launched from key shortcuts (True) or from menu toolbar (False)
  1484. self.launched_from_shortcuts = False
  1485. # this var will store the state of the toolbar before starting the editor
  1486. self.toolbar_old_state = False
  1487. self.app.ui.delete_drill_btn.triggered.connect(self.on_delete_btn)
  1488. self.name_entry.returnPressed.connect(self.on_name_activate)
  1489. self.addtool_btn.clicked.connect(self.on_tool_add)
  1490. self.addtool_entry.returnPressed.connect(self.on_tool_add)
  1491. self.deltool_btn.clicked.connect(self.on_tool_delete)
  1492. # self.tools_table_exc.selectionModel().currentChanged.connect(self.on_row_selected)
  1493. self.tools_table_exc.cellPressed.connect(self.on_row_selected)
  1494. self.array_type_combo.currentIndexChanged.connect(self.on_array_type_combo)
  1495. self.slot_array_type_combo.currentIndexChanged.connect(self.on_slot_array_type_combo)
  1496. self.drill_axis_radio.activated_custom.connect(self.on_linear_angle_radio)
  1497. self.slot_axis_radio.activated_custom.connect(self.on_slot_angle_radio)
  1498. self.app.ui.exc_add_array_drill_menuitem.triggered.connect(self.exc_add_drill_array)
  1499. self.app.ui.exc_add_drill_menuitem.triggered.connect(self.exc_add_drill)
  1500. self.app.ui.exc_add_array_slot_menuitem.triggered.connect(self.exc_add_slot_array)
  1501. self.app.ui.exc_add_slot_menuitem.triggered.connect(self.exc_add_slot)
  1502. self.app.ui.exc_resize_drill_menuitem.triggered.connect(self.exc_resize_drills)
  1503. self.app.ui.exc_copy_drill_menuitem.triggered.connect(self.exc_copy_drills)
  1504. self.app.ui.exc_delete_drill_menuitem.triggered.connect(self.on_delete_btn)
  1505. self.app.ui.exc_move_drill_menuitem.triggered.connect(self.exc_move_drills)
  1506. self.exc_obj = None
  1507. # VisPy Visuals
  1508. self.shapes = self.app.plotcanvas.new_shape_collection(layers=1)
  1509. self.tool_shape = self.app.plotcanvas.new_shape_collection(layers=1)
  1510. self.app.pool_recreated.connect(self.pool_recreated)
  1511. # Remove from scene
  1512. self.shapes.enabled = False
  1513. self.tool_shape.enabled = False
  1514. # ## List of selected shapes.
  1515. self.selected = []
  1516. self.move_timer = QtCore.QTimer()
  1517. self.move_timer.setSingleShot(True)
  1518. self.key = None # Currently pressed key
  1519. self.modifiers = None
  1520. self.x = None # Current mouse cursor pos
  1521. self.y = None
  1522. # Current snapped mouse pos
  1523. self.snap_x = None
  1524. self.snap_y = None
  1525. self.pos = None
  1526. self.complete = False
  1527. def make_callback(thetool):
  1528. def f():
  1529. self.on_tool_select(thetool)
  1530. return f
  1531. for tool in self.tools_exc:
  1532. self.tools_exc[tool]["button"].triggered.connect(make_callback(tool)) # Events
  1533. self.tools_exc[tool]["button"].setCheckable(True) # Checkable
  1534. self.options = {
  1535. "global_gridx": 0.1,
  1536. "global_gridy": 0.1,
  1537. "snap_max": 0.05,
  1538. "grid_snap": True,
  1539. "corner_snap": False,
  1540. "grid_gap_link": True
  1541. }
  1542. self.app.options_read_form()
  1543. for option in self.options:
  1544. if option in self.app.options:
  1545. self.options[option] = self.app.options[option]
  1546. self.rtree_exc_index = rtindex.Index()
  1547. # flag to show if the object was modified
  1548. self.is_modified = False
  1549. self.edited_obj_name = ""
  1550. # variable to store the total amount of drills per job
  1551. self.tot_drill_cnt = 0
  1552. self.tool_row = 0
  1553. # variable to store the total amount of slots per job
  1554. self.tot_slot_cnt = 0
  1555. self.tool_row_slots = 0
  1556. self.tool_row = 0
  1557. # store the status of the editor so the Delete at object level will not work until the edit is finished
  1558. self.editor_active = False
  1559. def entry2option(option, entry):
  1560. self.options[option] = float(entry.text())
  1561. # store the status of the editor so the Delete at object level will not work until the edit is finished
  1562. self.editor_active = False
  1563. def pool_recreated(self, pool):
  1564. self.shapes.pool = pool
  1565. self.tool_shape.pool = pool
  1566. @staticmethod
  1567. def make_storage():
  1568. # ## Shape storage.
  1569. storage = FlatCAMRTreeStorage()
  1570. storage.get_points = DrawToolShape.get_pts
  1571. return storage
  1572. def set_ui(self):
  1573. # updated units
  1574. self.units = self.app.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  1575. self.olddia_newdia.clear()
  1576. self.tool2tooldia.clear()
  1577. # build the self.points_edit dict {dimaters: [point_list]}
  1578. for drill in self.exc_obj.drills:
  1579. if drill['tool'] in self.exc_obj.tools:
  1580. if self.units == 'IN':
  1581. tool_dia = float('%.4f' % self.exc_obj.tools[drill['tool']]['C'])
  1582. else:
  1583. tool_dia = float('%.2f' % self.exc_obj.tools[drill['tool']]['C'])
  1584. try:
  1585. self.points_edit[tool_dia].append(drill['point'])
  1586. except KeyError:
  1587. self.points_edit[tool_dia] = [drill['point']]
  1588. # build the self.slot_points_edit dict {dimaters: {"start": Point, "stop": Point}}
  1589. for slot in self.exc_obj.slots:
  1590. if slot['tool'] in self.exc_obj.tools:
  1591. if self.units == 'IN':
  1592. tool_dia = float('%.4f' % self.exc_obj.tools[slot['tool']]['C'])
  1593. else:
  1594. tool_dia = float('%.2f' % self.exc_obj.tools[slot['tool']]['C'])
  1595. try:
  1596. self.slot_points_edit[tool_dia].append({
  1597. "start": slot["start"],
  1598. "stop": slot["stop"]
  1599. })
  1600. except KeyError:
  1601. self.slot_points_edit[tool_dia] = [{
  1602. "start": slot["start"],
  1603. "stop": slot["stop"]
  1604. }]
  1605. # update the olddia_newdia dict to make sure we have an updated state of the tool_table
  1606. for key in self.points_edit:
  1607. self.olddia_newdia[key] = key
  1608. for key in self.slot_points_edit:
  1609. if key not in self.olddia_newdia:
  1610. self.olddia_newdia[key] = key
  1611. sort_temp = []
  1612. for diam in self.olddia_newdia:
  1613. sort_temp.append(float(diam))
  1614. self.sorted_diameters = sorted(sort_temp)
  1615. # populate self.intial_table_rows dict with the tool number as keys and tool diameters as values
  1616. if self.exc_obj.diameterless is False:
  1617. for i in range(len(self.sorted_diameters)):
  1618. tt_dia = self.sorted_diameters[i]
  1619. self.tool2tooldia[i + 1] = tt_dia
  1620. else:
  1621. # the Excellon object has diameters that are bogus information, added by the application because the
  1622. # Excellon file has no tool diameter information. In this case do not order the diameter in the table
  1623. # but use the real order found in the exc_obj.tools
  1624. for k, v in self.exc_obj.tools.items():
  1625. if self.units == 'IN':
  1626. tool_dia = float('%.4f' % v['C'])
  1627. else:
  1628. tool_dia = float('%.2f' % v['C'])
  1629. self.tool2tooldia[int(k)] = tool_dia
  1630. # Init GUI
  1631. self.addtool_entry.set_value(float(self.app.defaults['excellon_editor_newdia']))
  1632. self.drill_array_size_entry.set_value(int(self.app.defaults['excellon_editor_array_size']))
  1633. self.drill_axis_radio.set_value(self.app.defaults['excellon_editor_lin_dir'])
  1634. self.drill_pitch_entry.set_value(float(self.app.defaults['excellon_editor_lin_pitch']))
  1635. self.linear_angle_spinner.set_value(float(self.app.defaults['excellon_editor_lin_angle']))
  1636. self.drill_direction_radio.set_value(self.app.defaults['excellon_editor_circ_dir'])
  1637. self.drill_angle_entry.set_value(float(self.app.defaults['excellon_editor_circ_angle']))
  1638. self.slot_length_entry.set_value(float(self.app.defaults['excellon_editor_slot_length']))
  1639. self.slot_axis_radio.set_value(self.app.defaults['excellon_editor_slot_direction'])
  1640. self.slot_angle_spinner.set_value(float(self.app.defaults['excellon_editor_slot_angle']))
  1641. self.slot_array_size_entry.set_value(int(self.app.defaults['excellon_editor_array_size']))
  1642. self.slot_array_axis_radio.set_value(self.app.defaults['excellon_editor_lin_dir'])
  1643. self.slot_array_pitch_entry.set_value(float(self.app.defaults['excellon_editor_lin_pitch']))
  1644. self.slot_array_linear_angle_spinner.set_value(float(self.app.defaults['excellon_editor_lin_angle']))
  1645. self.slot_array_direction_radio.set_value(self.app.defaults['excellon_editor_circ_dir'])
  1646. self.slot_array_angle_entry.set_value(float(self.app.defaults['excellon_editor_circ_angle']))
  1647. def build_ui(self, first_run=None):
  1648. try:
  1649. # if connected, disconnect the signal from the slot on item_changed as it creates issues
  1650. self.tools_table_exc.itemChanged.disconnect()
  1651. except (TypeError, AttributeError):
  1652. pass
  1653. try:
  1654. self.tools_table_exc.cellPressed.disconnect()
  1655. except (TypeError, AttributeError):
  1656. pass
  1657. # updated units
  1658. self.units = self.app.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  1659. # make a new name for the new Excellon object (the one with edited content)
  1660. self.edited_obj_name = self.exc_obj.options['name']
  1661. self.name_entry.set_value(self.edited_obj_name)
  1662. sort_temp = []
  1663. for diam in self.olddia_newdia:
  1664. sort_temp.append(float(diam))
  1665. self.sorted_diameters = sorted(sort_temp)
  1666. # here, self.sorted_diameters will hold in a oblique way, the number of tools
  1667. n = len(self.sorted_diameters)
  1668. # we have (n+2) rows because there are 'n' tools, each a row, plus the last 2 rows for totals.
  1669. self.tools_table_exc.setRowCount(n + 2)
  1670. self.tot_drill_cnt = 0
  1671. self.tot_slot_cnt = 0
  1672. self.tool_row = 0
  1673. # this variable will serve as the real tool_number
  1674. tool_id = 0
  1675. for tool_no in self.sorted_diameters:
  1676. tool_id += 1
  1677. drill_cnt = 0 # variable to store the nr of drills per tool
  1678. slot_cnt = 0 # variable to store the nr of slots per tool
  1679. # Find no of drills for the current tool
  1680. for tool_dia in self.points_edit:
  1681. if float(tool_dia) == tool_no:
  1682. drill_cnt = len(self.points_edit[tool_dia])
  1683. self.tot_drill_cnt += drill_cnt
  1684. try:
  1685. # Find no of slots for the current tool
  1686. for slot in self.slots:
  1687. if slot['tool'] == tool_no:
  1688. slot_cnt += 1
  1689. self.tot_slot_cnt += slot_cnt
  1690. except AttributeError:
  1691. # log.debug("No slots in the Excellon file")
  1692. # Find no of slots for the current tool
  1693. for tool_dia in self.slot_points_edit:
  1694. if float(tool_dia) == tool_no:
  1695. slot_cnt = len(self.slot_points_edit[tool_dia])
  1696. self.tot_slot_cnt += slot_cnt
  1697. idd = QtWidgets.QTableWidgetItem('%d' % int(tool_id))
  1698. idd.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  1699. self.tools_table_exc.setItem(self.tool_row, 0, idd) # Tool name/id
  1700. # Make sure that the drill diameter when in MM is with no more than 2 decimals
  1701. # There are no drill bits in MM with more than 3 decimals diameter
  1702. # For INCH the decimals should be no more than 3. There are no drills under 10mils
  1703. if self.units == 'MM':
  1704. dia = QtWidgets.QTableWidgetItem('%.2f' % self.olddia_newdia[tool_no])
  1705. else:
  1706. dia = QtWidgets.QTableWidgetItem('%.4f' % self.olddia_newdia[tool_no])
  1707. dia.setFlags(QtCore.Qt.ItemIsEnabled)
  1708. drill_count = QtWidgets.QTableWidgetItem('%d' % drill_cnt)
  1709. drill_count.setFlags(QtCore.Qt.ItemIsEnabled)
  1710. # if the slot number is zero is better to not clutter the GUI with zero's so we print a space
  1711. if slot_cnt > 0:
  1712. slot_count = QtWidgets.QTableWidgetItem('%d' % slot_cnt)
  1713. else:
  1714. slot_count = QtWidgets.QTableWidgetItem('')
  1715. slot_count.setFlags(QtCore.Qt.ItemIsEnabled)
  1716. self.tools_table_exc.setItem(self.tool_row, 1, dia) # Diameter
  1717. self.tools_table_exc.setItem(self.tool_row, 2, drill_count) # Number of drills per tool
  1718. self.tools_table_exc.setItem(self.tool_row, 3, slot_count) # Number of drills per tool
  1719. if first_run is True:
  1720. # set now the last tool selected
  1721. self.last_tool_selected = int(tool_id)
  1722. self.tool_row += 1
  1723. # make the diameter column editable
  1724. for row in range(self.tool_row):
  1725. self.tools_table_exc.item(row, 1).setFlags(
  1726. QtCore.Qt.ItemIsEditable | QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  1727. self.tools_table_exc.item(row, 2).setForeground(QtGui.QColor(0, 0, 0))
  1728. self.tools_table_exc.item(row, 3).setForeground(QtGui.QColor(0, 0, 0))
  1729. # add a last row with the Total number of drills
  1730. # HACK: made the text on this cell '9999' such it will always be the one before last when sorting
  1731. # it will have to have the foreground color (font color) white
  1732. empty = QtWidgets.QTableWidgetItem('9998')
  1733. empty.setForeground(QtGui.QColor(255, 255, 255))
  1734. empty.setFlags(empty.flags() ^ QtCore.Qt.ItemIsEnabled)
  1735. empty_b = QtWidgets.QTableWidgetItem('')
  1736. empty_b.setFlags(empty_b.flags() ^ QtCore.Qt.ItemIsEnabled)
  1737. label_tot_drill_count = QtWidgets.QTableWidgetItem(_('Total Drills'))
  1738. tot_drill_count = QtWidgets.QTableWidgetItem('%d' % self.tot_drill_cnt)
  1739. label_tot_drill_count.setFlags(label_tot_drill_count.flags() ^ QtCore.Qt.ItemIsEnabled)
  1740. tot_drill_count.setFlags(tot_drill_count.flags() ^ QtCore.Qt.ItemIsEnabled)
  1741. self.tools_table_exc.setItem(self.tool_row, 0, empty)
  1742. self.tools_table_exc.setItem(self.tool_row, 1, label_tot_drill_count)
  1743. self.tools_table_exc.setItem(self.tool_row, 2, tot_drill_count) # Total number of drills
  1744. self.tools_table_exc.setItem(self.tool_row, 3, empty_b)
  1745. font = QtGui.QFont()
  1746. font.setBold(True)
  1747. font.setWeight(75)
  1748. for k in [1, 2]:
  1749. self.tools_table_exc.item(self.tool_row, k).setForeground(QtGui.QColor(127, 0, 255))
  1750. self.tools_table_exc.item(self.tool_row, k).setFont(font)
  1751. self.tool_row += 1
  1752. # add a last row with the Total number of slots
  1753. # HACK: made the text on this cell '9999' such it will always be the last when sorting
  1754. # it will have to have the foreground color (font color) white
  1755. empty_2 = QtWidgets.QTableWidgetItem('9999')
  1756. empty_2.setForeground(QtGui.QColor(255, 255, 255))
  1757. empty_2.setFlags(empty_2.flags() ^ QtCore.Qt.ItemIsEnabled)
  1758. empty_3 = QtWidgets.QTableWidgetItem('')
  1759. empty_3.setFlags(empty_3.flags() ^ QtCore.Qt.ItemIsEnabled)
  1760. label_tot_slot_count = QtWidgets.QTableWidgetItem(_('Total Slots'))
  1761. tot_slot_count = QtWidgets.QTableWidgetItem('%d' % self.tot_slot_cnt)
  1762. label_tot_slot_count.setFlags(label_tot_slot_count.flags() ^ QtCore.Qt.ItemIsEnabled)
  1763. tot_slot_count.setFlags(tot_slot_count.flags() ^ QtCore.Qt.ItemIsEnabled)
  1764. self.tools_table_exc.setItem(self.tool_row, 0, empty_2)
  1765. self.tools_table_exc.setItem(self.tool_row, 1, label_tot_slot_count)
  1766. self.tools_table_exc.setItem(self.tool_row, 2, empty_3)
  1767. self.tools_table_exc.setItem(self.tool_row, 3, tot_slot_count) # Total number of slots
  1768. for kl in [1, 2, 3]:
  1769. self.tools_table_exc.item(self.tool_row, kl).setFont(font)
  1770. self.tools_table_exc.item(self.tool_row, kl).setForeground(QtGui.QColor(0, 70, 255))
  1771. # all the tools are selected by default
  1772. self.tools_table_exc.selectColumn(0)
  1773. #
  1774. self.tools_table_exc.resizeColumnsToContents()
  1775. self.tools_table_exc.resizeRowsToContents()
  1776. vertical_header = self.tools_table_exc.verticalHeader()
  1777. # vertical_header.setSectionResizeMode(QtWidgets.QHeaderView.ResizeToContents)
  1778. vertical_header.hide()
  1779. self.tools_table_exc.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  1780. horizontal_header = self.tools_table_exc.horizontalHeader()
  1781. horizontal_header.setSectionResizeMode(0, QtWidgets.QHeaderView.ResizeToContents)
  1782. horizontal_header.setSectionResizeMode(1, QtWidgets.QHeaderView.Stretch)
  1783. horizontal_header.setSectionResizeMode(2, QtWidgets.QHeaderView.ResizeToContents)
  1784. horizontal_header.setSectionResizeMode(3, QtWidgets.QHeaderView.ResizeToContents)
  1785. # horizontal_header.setStretchLastSection(True)
  1786. # self.tools_table_exc.setSortingEnabled(True)
  1787. # sort by tool diameter
  1788. self.tools_table_exc.sortItems(1)
  1789. # After sorting, to display also the number of drills in the right row we need to update self.initial_rows dict
  1790. # with the new order. Of course the last 2 rows in the tool table are just for display therefore we don't
  1791. # use them
  1792. self.tool2tooldia.clear()
  1793. for row in range(self.tools_table_exc.rowCount() - 2):
  1794. tool = int(self.tools_table_exc.item(row, 0).text())
  1795. diameter = float(self.tools_table_exc.item(row, 1).text())
  1796. self.tool2tooldia[tool] = diameter
  1797. self.tools_table_exc.setMinimumHeight(self.tools_table_exc.getHeight())
  1798. self.tools_table_exc.setMaximumHeight(self.tools_table_exc.getHeight())
  1799. # make sure no rows are selected so the user have to click the correct row, meaning selecting the correct tool
  1800. self.tools_table_exc.clearSelection()
  1801. # Remove anything else in the GUI Selected Tab
  1802. self.app.ui.selected_scroll_area.takeWidget()
  1803. # Put ourself in the GUI Selected Tab
  1804. self.app.ui.selected_scroll_area.setWidget(self.exc_edit_widget)
  1805. # Switch notebook to Selected page
  1806. self.app.ui.notebook.setCurrentWidget(self.app.ui.selected_tab)
  1807. # we reactivate the signals after the after the tool adding as we don't need to see the tool been populated
  1808. self.tools_table_exc.itemChanged.connect(self.on_tool_edit)
  1809. self.tools_table_exc.cellPressed.connect(self.on_row_selected)
  1810. def on_tool_add(self, tooldia=None):
  1811. self.is_modified = True
  1812. if tooldia:
  1813. tool_dia = tooldia
  1814. else:
  1815. try:
  1816. tool_dia = float(self.addtool_entry.get_value())
  1817. except ValueError:
  1818. # try to convert comma to decimal point. if it's still not working error message and return
  1819. try:
  1820. tool_dia = float(self.addtool_entry.get_value().replace(',', '.'))
  1821. except ValueError:
  1822. self.app.inform.emit(_("[ERROR_NOTCL] Wrong value format entered, "
  1823. "use a number.")
  1824. )
  1825. return
  1826. if tool_dia not in self.olddia_newdia:
  1827. storage_elem = FlatCAMGeoEditor.make_storage()
  1828. self.storage_dict[tool_dia] = storage_elem
  1829. # self.olddia_newdia dict keeps the evidence on current tools diameters as keys and gets updated on values
  1830. # each time a tool diameter is edited or added
  1831. self.olddia_newdia[tool_dia] = tool_dia
  1832. else:
  1833. self.app.inform.emit(_("[WARNING_NOTCL] Tool already in the original or actual tool list.\n"
  1834. "Save and reedit Excellon if you need to add this tool. ")
  1835. )
  1836. return
  1837. # since we add a new tool, we update also the initial state of the tool_table through it's dictionary
  1838. # we add a new entry in the tool2tooldia dict
  1839. self.tool2tooldia[len(self.olddia_newdia)] = tool_dia
  1840. self.app.inform.emit(_("[success] Added new tool with dia: {dia} {units}").format(dia=str(tool_dia),
  1841. units=str(self.units)))
  1842. self.build_ui()
  1843. # make a quick sort through the tool2tooldia dict so we find which row to select
  1844. row_to_be_selected = None
  1845. for key in sorted(self.tool2tooldia):
  1846. if self.tool2tooldia[key] == tool_dia:
  1847. row_to_be_selected = int(key) - 1
  1848. self.last_tool_selected = int(key)
  1849. break
  1850. self.tools_table_exc.selectRow(row_to_be_selected)
  1851. def on_tool_delete(self, dia=None):
  1852. self.is_modified = True
  1853. deleted_tool_dia_list = []
  1854. try:
  1855. if dia is None or dia is False:
  1856. # deleted_tool_dia = float(self.tools_table_exc.item(self.tools_table_exc.currentRow(), 1).text())
  1857. for index in self.tools_table_exc.selectionModel().selectedRows():
  1858. row = index.row()
  1859. deleted_tool_dia_list.append(float(self.tools_table_exc.item(row, 1).text()))
  1860. else:
  1861. if isinstance(dia, list):
  1862. for dd in dia:
  1863. deleted_tool_dia_list.append(float('%.4f' % dd))
  1864. else:
  1865. deleted_tool_dia_list.append(float('%.4f' % dia))
  1866. except Exception as e:
  1867. self.app.inform.emit(_("[WARNING_NOTCL] Select a tool in Tool Table"))
  1868. return
  1869. for deleted_tool_dia in deleted_tool_dia_list:
  1870. # delete de tool offset
  1871. self.exc_obj.tool_offset.pop(float(deleted_tool_dia), None)
  1872. # delete the storage used for that tool
  1873. storage_elem = FlatCAMGeoEditor.make_storage()
  1874. self.storage_dict[deleted_tool_dia] = storage_elem
  1875. self.storage_dict.pop(deleted_tool_dia, None)
  1876. # I've added this flag_del variable because dictionary don't like
  1877. # having keys deleted while iterating through them
  1878. flag_del = []
  1879. # self.points_edit.pop(deleted_tool_dia, None)
  1880. for deleted_tool in self.tool2tooldia:
  1881. if self.tool2tooldia[deleted_tool] == deleted_tool_dia:
  1882. flag_del.append(deleted_tool)
  1883. if flag_del:
  1884. for tool_to_be_deleted in flag_del:
  1885. # delete the tool
  1886. self.tool2tooldia.pop(tool_to_be_deleted, None)
  1887. # delete also the drills from points_edit dict just in case we add the tool again,
  1888. # we don't want to show the number of drills from before was deleter
  1889. self.points_edit[deleted_tool_dia] = []
  1890. self.olddia_newdia.pop(deleted_tool_dia, None)
  1891. self.app.inform.emit(_("[success] Deleted tool with dia: {del_dia} {units}").format(
  1892. del_dia=str(deleted_tool_dia),
  1893. units=str(self.units)))
  1894. self.replot()
  1895. # self.app.inform.emit("Could not delete selected tool")
  1896. self.build_ui()
  1897. def on_tool_edit(self, item_changed):
  1898. # if connected, disconnect the signal from the slot on item_changed as it creates issues
  1899. self.tools_table_exc.itemChanged.disconnect()
  1900. self.tools_table_exc.cellPressed.disconnect()
  1901. # self.tools_table_exc.selectionModel().currentChanged.disconnect()
  1902. self.is_modified = True
  1903. current_table_dia_edited = None
  1904. if self.tools_table_exc.currentItem() is not None:
  1905. try:
  1906. current_table_dia_edited = float(self.tools_table_exc.currentItem().text())
  1907. except ValueError as e:
  1908. log.debug("FlatCAMExcEditor.on_tool_edit() --> %s" % str(e))
  1909. self.tools_table_exc.setCurrentItem(None)
  1910. return
  1911. row_of_item_changed = self.tools_table_exc.currentRow()
  1912. # rows start with 0, tools start with 1 so we adjust the value by 1
  1913. key_in_tool2tooldia = row_of_item_changed + 1
  1914. dia_changed = self.tool2tooldia[key_in_tool2tooldia]
  1915. # tool diameter is not used so we create a new tool with the desired diameter
  1916. if current_table_dia_edited not in self.olddia_newdia.values():
  1917. # update the dict that holds as keys our initial diameters and as values the edited diameters
  1918. self.olddia_newdia[dia_changed] = current_table_dia_edited
  1919. # update the dict that holds tool_no as key and tool_dia as value
  1920. self.tool2tooldia[key_in_tool2tooldia] = current_table_dia_edited
  1921. # update the tool offset
  1922. modified_offset = self.exc_obj.tool_offset.pop(dia_changed, None)
  1923. if modified_offset is not None:
  1924. self.exc_obj.tool_offset[current_table_dia_edited] = modified_offset
  1925. self.replot()
  1926. else:
  1927. # tool diameter is already in use so we move the drills from the prior tool to the new tool
  1928. factor = current_table_dia_edited / dia_changed
  1929. geometry = []
  1930. for shape_exc in self.storage_dict[dia_changed].get_objects():
  1931. scaled_geo = MultiLineString(
  1932. [affinity.scale(subgeo, xfact=factor, yfact=factor, origin='center') for subgeo in shape_exc.geo]
  1933. )
  1934. geometry.append(DrawToolShape(scaled_geo))
  1935. # add bogus drill points (for total count of drills)
  1936. for k, v in self.olddia_newdia.items():
  1937. if v == current_table_dia_edited:
  1938. self.points_edit[k].append((0, 0))
  1939. break
  1940. # search for the old dia that correspond to the new dia and add the drills in it's storage
  1941. # everything will be sort out later, when the edited Excellon is updated
  1942. for k, v in self.olddia_newdia.items():
  1943. if v == current_table_dia_edited:
  1944. self.add_exc_shape(geometry, self.storage_dict[k])
  1945. break
  1946. # delete the old tool from which we moved the drills
  1947. self.on_tool_delete(dia=dia_changed)
  1948. # delete the tool offset
  1949. self.exc_obj.tool_offset.pop(dia_changed, None)
  1950. # we reactivate the signals after the after the tool editing
  1951. self.tools_table_exc.itemChanged.connect(self.on_tool_edit)
  1952. self.tools_table_exc.cellPressed.connect(self.on_row_selected)
  1953. # self.tools_table_exc.selectionModel().currentChanged.connect(self.on_row_selected)
  1954. def on_name_activate(self):
  1955. self.edited_obj_name = self.name_entry.get_value()
  1956. def activate(self):
  1957. # adjust the status of the menu entries related to the editor
  1958. self.app.ui.menueditedit.setDisabled(True)
  1959. self.app.ui.menueditok.setDisabled(False)
  1960. # adjust the visibility of some of the canvas context menu
  1961. self.app.ui.popmenu_edit.setVisible(False)
  1962. self.app.ui.popmenu_save.setVisible(True)
  1963. self.connect_canvas_event_handlers()
  1964. # initialize working objects
  1965. self.storage_dict = {}
  1966. self.current_storage = []
  1967. self.points_edit = {}
  1968. self.sorted_diameters = []
  1969. self.new_drills = []
  1970. self.new_tools = {}
  1971. self.new_slots = []
  1972. self.new_tool_offset = {}
  1973. self.olddia_newdia = {}
  1974. self.shapes.enabled = True
  1975. self.tool_shape.enabled = True
  1976. # self.app.app_cursor.enabled = True
  1977. self.app.ui.snap_max_dist_entry.setEnabled(True)
  1978. self.app.ui.corner_snap_btn.setEnabled(True)
  1979. self.app.ui.snap_magnet.setVisible(True)
  1980. self.app.ui.corner_snap_btn.setVisible(True)
  1981. self.app.ui.exc_editor_menu.setDisabled(False)
  1982. self.app.ui.exc_editor_menu.menuAction().setVisible(True)
  1983. self.app.ui.update_obj_btn.setEnabled(True)
  1984. self.app.ui.e_editor_cmenu.setEnabled(True)
  1985. self.app.ui.exc_edit_toolbar.setDisabled(False)
  1986. self.app.ui.exc_edit_toolbar.setVisible(True)
  1987. # self.app.ui.snap_toolbar.setDisabled(False)
  1988. # start with GRID toolbar activated
  1989. if self.app.ui.grid_snap_btn.isChecked() is False:
  1990. self.app.ui.grid_snap_btn.trigger()
  1991. self.app.ui.popmenu_disable.setVisible(False)
  1992. self.app.ui.cmenu_newmenu.menuAction().setVisible(False)
  1993. self.app.ui.popmenu_properties.setVisible(False)
  1994. self.app.ui.e_editor_cmenu.menuAction().setVisible(True)
  1995. self.app.ui.g_editor_cmenu.menuAction().setVisible(False)
  1996. self.app.ui.grb_editor_cmenu.menuAction().setVisible(False)
  1997. # Tell the App that the editor is active
  1998. self.editor_active = True
  1999. # show the UI
  2000. self.drills_frame.show()
  2001. def deactivate(self):
  2002. try:
  2003. QtGui.QGuiApplication.restoreOverrideCursor()
  2004. except Exception as e:
  2005. pass
  2006. # adjust the status of the menu entries related to the editor
  2007. self.app.ui.menueditedit.setDisabled(False)
  2008. self.app.ui.menueditok.setDisabled(True)
  2009. # adjust the visibility of some of the canvas context menu
  2010. self.app.ui.popmenu_edit.setVisible(True)
  2011. self.app.ui.popmenu_save.setVisible(False)
  2012. self.disconnect_canvas_event_handlers()
  2013. self.clear()
  2014. self.app.ui.exc_edit_toolbar.setDisabled(True)
  2015. settings = QSettings("Open Source", "FlatCAM")
  2016. if settings.contains("layout"):
  2017. layout = settings.value('layout', type=str)
  2018. if layout == 'standard':
  2019. # self.app.ui.exc_edit_toolbar.setVisible(False)
  2020. self.app.ui.snap_max_dist_entry.setEnabled(False)
  2021. self.app.ui.corner_snap_btn.setEnabled(False)
  2022. self.app.ui.snap_magnet.setVisible(False)
  2023. self.app.ui.corner_snap_btn.setVisible(False)
  2024. elif layout == 'compact':
  2025. # self.app.ui.exc_edit_toolbar.setVisible(True)
  2026. self.app.ui.snap_max_dist_entry.setEnabled(False)
  2027. self.app.ui.corner_snap_btn.setEnabled(False)
  2028. self.app.ui.snap_magnet.setVisible(True)
  2029. self.app.ui.corner_snap_btn.setVisible(True)
  2030. else:
  2031. # self.app.ui.exc_edit_toolbar.setVisible(False)
  2032. self.app.ui.snap_max_dist_entry.setEnabled(False)
  2033. self.app.ui.corner_snap_btn.setEnabled(False)
  2034. self.app.ui.snap_magnet.setVisible(False)
  2035. self.app.ui.corner_snap_btn.setVisible(False)
  2036. # set the Editor Toolbar visibility to what was before entering in the Editor
  2037. self.app.ui.exc_edit_toolbar.setVisible(False) if self.toolbar_old_state is False \
  2038. else self.app.ui.exc_edit_toolbar.setVisible(True)
  2039. # Disable visuals
  2040. self.shapes.enabled = False
  2041. self.tool_shape.enabled = False
  2042. # self.app.app_cursor.enabled = False
  2043. # Tell the app that the editor is no longer active
  2044. self.editor_active = False
  2045. self.app.ui.exc_editor_menu.setDisabled(True)
  2046. self.app.ui.exc_editor_menu.menuAction().setVisible(False)
  2047. self.app.ui.update_obj_btn.setEnabled(False)
  2048. self.app.ui.popmenu_disable.setVisible(True)
  2049. self.app.ui.cmenu_newmenu.menuAction().setVisible(True)
  2050. self.app.ui.popmenu_properties.setVisible(True)
  2051. self.app.ui.g_editor_cmenu.menuAction().setVisible(False)
  2052. self.app.ui.e_editor_cmenu.menuAction().setVisible(False)
  2053. self.app.ui.grb_editor_cmenu.menuAction().setVisible(False)
  2054. # Show original geometry
  2055. if self.exc_obj:
  2056. self.exc_obj.visible = True
  2057. # hide the UI
  2058. self.drills_frame.hide()
  2059. def connect_canvas_event_handlers(self):
  2060. # ## Canvas events
  2061. # first connect to new, then disconnect the old handlers
  2062. # don't ask why but if there is nothing connected I've seen issues
  2063. self.canvas.vis_connect('mouse_press', self.on_canvas_click)
  2064. self.canvas.vis_connect('mouse_move', self.on_canvas_move)
  2065. self.canvas.vis_connect('mouse_release', self.on_exc_click_release)
  2066. # make sure that the shortcuts key and mouse events will no longer be linked to the methods from FlatCAMApp
  2067. # but those from FlatCAMGeoEditor
  2068. self.app.plotcanvas.vis_disconnect('mouse_press', self.app.on_mouse_click_over_plot)
  2069. self.app.plotcanvas.vis_disconnect('mouse_move', self.app.on_mouse_move_over_plot)
  2070. self.app.plotcanvas.vis_disconnect('mouse_release', self.app.on_mouse_click_release_over_plot)
  2071. self.app.plotcanvas.vis_disconnect('mouse_double_click', self.app.on_double_click_over_plot)
  2072. self.app.collection.view.clicked.disconnect()
  2073. self.app.ui.popmenu_copy.triggered.disconnect()
  2074. self.app.ui.popmenu_delete.triggered.disconnect()
  2075. self.app.ui.popmenu_move.triggered.disconnect()
  2076. self.app.ui.popmenu_copy.triggered.connect(self.exc_copy_drills)
  2077. self.app.ui.popmenu_delete.triggered.connect(self.on_delete_btn)
  2078. self.app.ui.popmenu_move.triggered.connect(self.exc_move_drills)
  2079. # Excellon Editor
  2080. self.app.ui.drill.triggered.connect(self.exc_add_drill)
  2081. self.app.ui.drill_array.triggered.connect(self.exc_add_drill_array)
  2082. def disconnect_canvas_event_handlers(self):
  2083. # we restore the key and mouse control to FlatCAMApp method
  2084. # first connect to new, then disconnect the old handlers
  2085. # don't ask why but if there is nothing connected I've seen issues
  2086. self.app.plotcanvas.vis_connect('mouse_press', self.app.on_mouse_click_over_plot)
  2087. self.app.plotcanvas.vis_connect('mouse_move', self.app.on_mouse_move_over_plot)
  2088. self.app.plotcanvas.vis_connect('mouse_release', self.app.on_mouse_click_release_over_plot)
  2089. self.app.plotcanvas.vis_connect('mouse_double_click', self.app.on_double_click_over_plot)
  2090. self.app.collection.view.clicked.connect(self.app.collection.on_mouse_down)
  2091. self.canvas.vis_disconnect('mouse_press', self.on_canvas_click)
  2092. self.canvas.vis_disconnect('mouse_move', self.on_canvas_move)
  2093. self.canvas.vis_disconnect('mouse_release', self.on_exc_click_release)
  2094. try:
  2095. self.app.ui.popmenu_copy.triggered.disconnect(self.exc_copy_drills)
  2096. except (TypeError, AttributeError):
  2097. pass
  2098. try:
  2099. self.app.ui.popmenu_delete.triggered.disconnect(self.on_delete_btn)
  2100. except (TypeError, AttributeError):
  2101. pass
  2102. try:
  2103. self.app.ui.popmenu_move.triggered.disconnect(self.exc_move_drills)
  2104. except (TypeError, AttributeError):
  2105. pass
  2106. self.app.ui.popmenu_copy.triggered.connect(self.app.on_copy_object)
  2107. self.app.ui.popmenu_delete.triggered.connect(self.app.on_delete)
  2108. self.app.ui.popmenu_move.triggered.connect(self.app.obj_move)
  2109. # Excellon Editor
  2110. try:
  2111. self.app.ui.drill.triggered.disconnect(self.exc_add_drill)
  2112. except (TypeError, AttributeError):
  2113. pass
  2114. try:
  2115. self.app.ui.drill_array.triggered.disconnect(self.exc_add_drill_array)
  2116. except (TypeError, AttributeError):
  2117. pass
  2118. def clear(self):
  2119. self.active_tool = None
  2120. # self.shape_buffer = []
  2121. self.selected = []
  2122. self.points_edit = {}
  2123. self.new_tools = {}
  2124. self.new_drills = []
  2125. # self.storage_dict = {}
  2126. self.shapes.clear(update=True)
  2127. self.tool_shape.clear(update=True)
  2128. # self.storage = FlatCAMExcEditor.make_storage()
  2129. self.replot()
  2130. def edit_fcexcellon(self, exc_obj):
  2131. """
  2132. Imports the geometry from the given FlatCAM Excellon object
  2133. into the editor.
  2134. :param exc_obj: FlatCAMExcellon object
  2135. :return: None
  2136. """
  2137. assert isinstance(exc_obj, Excellon), \
  2138. "Expected an Excellon Object, got %s" % type(exc_obj)
  2139. self.deactivate()
  2140. self.activate()
  2141. # Hide original geometry
  2142. self.exc_obj = exc_obj
  2143. exc_obj.visible = False
  2144. self.points_edit = {}
  2145. self.slot_points_edit = {}
  2146. # Set selection tolerance
  2147. # DrawToolShape.tolerance = fc_excellon.drawing_tolerance * 10
  2148. self.select_tool("drill_select")
  2149. self.set_ui()
  2150. # now that we hava data, create the GUI interface and add it to the Tool Tab
  2151. self.build_ui(first_run=True)
  2152. # we activate this after the initial build as we don't need to see the tool been populated
  2153. self.tools_table_exc.itemChanged.connect(self.on_tool_edit)
  2154. # build the geometry for each tool-diameter, each drill will be represented by a '+' symbol
  2155. # and then add it to the storage elements (each storage elements is a member of a list
  2156. for tool_dia in self.points_edit:
  2157. storage_elem = FlatCAMGeoEditor.make_storage()
  2158. for point in self.points_edit[tool_dia]:
  2159. # make a '+' sign, the line length is the tool diameter
  2160. start_hor_line = ((point.x - (tool_dia / 2)), point.y)
  2161. stop_hor_line = ((point.x + (tool_dia / 2)), point.y)
  2162. start_vert_line = (point.x, (point.y - (tool_dia / 2)))
  2163. stop_vert_line = (point.x, (point.y + (tool_dia / 2)))
  2164. shape_geo = MultiLineString([(start_hor_line, stop_hor_line), (start_vert_line, stop_vert_line)])
  2165. if shape_geo is not None:
  2166. self.add_exc_shape(DrawToolShape(shape_geo), storage_elem)
  2167. self.storage_dict[tool_dia] = storage_elem
  2168. # slots
  2169. for tool_dia in self.slot_points_edit:
  2170. buf_value = float(tool_dia) / 2
  2171. for elem_dict in self.slot_points_edit[tool_dia]:
  2172. line_geo = LineString([elem_dict['start'], elem_dict['stop']])
  2173. shape_geo = line_geo.buffer(buf_value)
  2174. if tool_dia not in self.storage_dict:
  2175. storage_elem = FlatCAMGeoEditor.make_storage()
  2176. self.storage_dict[tool_dia] = storage_elem
  2177. if shape_geo is not None:
  2178. self.add_exc_shape(DrawToolShape(shape_geo), self.storage_dict[tool_dia])
  2179. self.replot()
  2180. # add a first tool in the Tool Table but only if the Excellon Object is empty
  2181. if not self.tool2tooldia:
  2182. self.on_tool_add(tooldia=float(self.app.defaults['excellon_editor_newdia']))
  2183. def update_fcexcellon(self, exc_obj):
  2184. """
  2185. Create a new Excellon object that contain the edited content of the source Excellon object
  2186. :param exc_obj: FlatCAMExcellon
  2187. :return: None
  2188. """
  2189. # this dictionary will contain tooldia's as keys and a list of coordinates tuple as values
  2190. # the values of this dict are coordinates of the holes (drills)
  2191. edited_points = {}
  2192. """
  2193. - this dictionary will contain tooldia's as keys and a list of another dicts as values
  2194. - the dict element of the list has the structure
  2195. ================ ====================================
  2196. Key Value
  2197. ================ ====================================
  2198. start (Shapely.Point) Start point of the slot
  2199. stop (Shapely.Point) Stop point of the slot
  2200. ================ ====================================
  2201. """
  2202. edited_slot_points = {}
  2203. for storage_tooldia in self.storage_dict:
  2204. for x in self.storage_dict[storage_tooldia].get_objects():
  2205. if isinstance(x.geo, MultiLineString):
  2206. # all x.geo in self.storage_dict[storage] are MultiLinestring objects for drills
  2207. # each MultiLineString is made out of Linestrings
  2208. # select first Linestring object in the current MultiLineString
  2209. first_linestring = x.geo[0]
  2210. # get it's coordinates
  2211. first_linestring_coords = first_linestring.coords
  2212. x_coord = first_linestring_coords[0][0] + (float(first_linestring.length / 2))
  2213. y_coord = first_linestring_coords[0][1]
  2214. # create a tuple with the coordinates (x, y) and add it to the list that is the value of the
  2215. # edited_points dictionary
  2216. point = (x_coord, y_coord)
  2217. if storage_tooldia not in edited_points:
  2218. edited_points[storage_tooldia] = [point]
  2219. else:
  2220. edited_points[storage_tooldia].append(point)
  2221. elif isinstance(x.geo, Polygon):
  2222. # create a tuple with the points (start, stop) and add it to the list that is the value of the
  2223. # edited_points dictionary
  2224. # first determine the start and stop coordinates for the slot knowing the geometry and the tool
  2225. # diameter
  2226. radius = float(storage_tooldia) / 2
  2227. radius = radius - 0.0000001
  2228. poly = x.geo
  2229. poly = poly.buffer(-radius)
  2230. xmin, ymin, xmax, ymax = poly.bounds
  2231. line_one = LineString([(xmin, ymin), (xmax, ymax)]).intersection(poly).length
  2232. line_two = LineString([(xmin, ymax), (xmax, ymin)]).intersection(poly).length
  2233. if line_one < line_two:
  2234. point_elem = {
  2235. "start": (xmin, ymax),
  2236. "stop": (xmax, ymin)
  2237. }
  2238. else:
  2239. point_elem = {
  2240. "start": (xmin, ymin),
  2241. "stop": (xmax, ymax)
  2242. }
  2243. if storage_tooldia not in edited_slot_points:
  2244. edited_slot_points[storage_tooldia] = [point_elem]
  2245. else:
  2246. edited_slot_points[storage_tooldia].append(point_elem)
  2247. # recreate the drills and tools to be added to the new Excellon edited object
  2248. # first, we look in the tool table if one of the tool diameters was changed then
  2249. # append that a tuple formed by (old_dia, edited_dia) to a list
  2250. changed_key = set()
  2251. for initial_dia in self.olddia_newdia:
  2252. edited_dia = self.olddia_newdia[initial_dia]
  2253. if edited_dia != initial_dia:
  2254. # for drills
  2255. for old_dia in edited_points:
  2256. if old_dia == initial_dia:
  2257. changed_key.add((old_dia, edited_dia))
  2258. # for slots
  2259. for old_dia in edited_slot_points:
  2260. if old_dia == initial_dia:
  2261. changed_key.add((old_dia, edited_dia))
  2262. # if the initial_dia is not in edited_points it means it is a new tool with no drill points
  2263. # (and we have to add it)
  2264. # because in case we have drill points it will have to be already added in edited_points
  2265. # if initial_dia not in edited_points.keys():
  2266. # edited_points[initial_dia] = []
  2267. for el in changed_key:
  2268. edited_points[el[1]] = edited_points.pop(el[0])
  2269. edited_slot_points[el[1]] = edited_slot_points.pop(el[0])
  2270. # Let's sort the edited_points dictionary by keys (diameters) and store the result in a zipped list
  2271. # ordered_edited_points is a ordered list of tuples;
  2272. # element[0] of the tuple is the diameter and
  2273. # element[1] of the tuple is a list of coordinates (a tuple themselves)
  2274. ordered_edited_points = sorted(zip(edited_points.keys(), edited_points.values()))
  2275. current_tool = 0
  2276. for tool_dia in ordered_edited_points:
  2277. current_tool += 1
  2278. # create the self.tools for the new Excellon object (the one with edited content)
  2279. name = str(current_tool)
  2280. spec = {"C": float(tool_dia[0])}
  2281. self.new_tools[name] = spec
  2282. # add in self.tools the 'solid_geometry' key, the value (a list) is populated bellow
  2283. self.new_tools[name]['solid_geometry'] = []
  2284. # create the self.drills for the new Excellon object (the one with edited content)
  2285. for point in tool_dia[1]:
  2286. self.new_drills.append(
  2287. {
  2288. 'point': Point(point),
  2289. 'tool': str(current_tool)
  2290. }
  2291. )
  2292. # repopulate the 'solid_geometry' for each tool
  2293. poly = Point(point).buffer(float(tool_dia[0]) / 2.0, int(int(exc_obj.geo_steps_per_circle) / 4))
  2294. self.new_tools[name]['solid_geometry'].append(poly)
  2295. ordered_edited_slot_points = sorted(zip(edited_slot_points.keys(), edited_slot_points.values()))
  2296. for tool_dia in ordered_edited_slot_points:
  2297. tool_exist_flag = False
  2298. for tool in self.new_tools:
  2299. if tool_dia[0] == self.new_tools[tool]["C"]:
  2300. current_tool = tool
  2301. tool_exist_flag = True
  2302. break
  2303. if tool_exist_flag is False:
  2304. current_tool += 1
  2305. # create the self.tools for the new Excellon object (the one with edited content)
  2306. name = str(current_tool)
  2307. spec = {"C": float(tool_dia[0])}
  2308. self.new_tools[name] = spec
  2309. # add in self.tools the 'solid_geometry' key, the value (a list) is populated bellow
  2310. self.new_tools[name]['solid_geometry'] = []
  2311. # create the self.slots for the new Excellon object (the one with edited content)
  2312. for coord_dict in tool_dia[1]:
  2313. self.new_slots.append(
  2314. {
  2315. 'start': Point(coord_dict['start']),
  2316. 'stop': Point(coord_dict['stop']),
  2317. 'tool': str(current_tool)
  2318. }
  2319. )
  2320. # repopulate the 'solid_geometry' for each tool
  2321. poly = LineString([coord_dict['start'], coord_dict['stop']]).buffer(
  2322. float(tool_dia[0]) / 2.0, int(int(exc_obj.geo_steps_per_circle) / 4)
  2323. )
  2324. self.new_tools[str(current_tool)]['solid_geometry'].append(poly)
  2325. if self.is_modified is True:
  2326. if "_edit" in self.edited_obj_name:
  2327. try:
  2328. idd = int(self.edited_obj_name[-1]) + 1
  2329. self.edited_obj_name = self.edited_obj_name[:-1] + str(idd)
  2330. except ValueError:
  2331. self.edited_obj_name += "_1"
  2332. else:
  2333. self.edited_obj_name += "_edit"
  2334. self.app.worker_task.emit({'fcn': self.new_edited_excellon,
  2335. 'params': [self.edited_obj_name]})
  2336. self.new_tool_offset = self.exc_obj.tool_offset
  2337. # reset the tool table
  2338. self.tools_table_exc.clear()
  2339. self.tools_table_exc.setHorizontalHeaderLabels(['#', _('Diameter'), 'D', 'S'])
  2340. self.last_tool_selected = None
  2341. # delete the edited Excellon object which will be replaced by a new one having the edited content of the first
  2342. self.app.collection.set_active(self.exc_obj.options['name'])
  2343. self.app.collection.delete_active()
  2344. # restore GUI to the Selected TAB
  2345. # Remove anything else in the GUI
  2346. self.app.ui.tool_scroll_area.takeWidget()
  2347. # Switch notebook to Selected page
  2348. self.app.ui.notebook.setCurrentWidget(self.app.ui.selected_tab)
  2349. def update_options(self, obj):
  2350. try:
  2351. if not obj.options:
  2352. obj.options = {}
  2353. obj.options['xmin'] = 0
  2354. obj.options['ymin'] = 0
  2355. obj.options['xmax'] = 0
  2356. obj.options['ymax'] = 0
  2357. return True
  2358. else:
  2359. return False
  2360. except AttributeError:
  2361. obj.options = {}
  2362. return True
  2363. def new_edited_excellon(self, outname):
  2364. """
  2365. Creates a new Excellon object for the edited Excellon. Thread-safe.
  2366. :param outname: Name of the resulting object. None causes the
  2367. name to be that of the file.
  2368. :type outname: str
  2369. :return: None
  2370. """
  2371. self.app.log.debug("Update the Excellon object with edited content. Source is %s" %
  2372. self.exc_obj.options['name'])
  2373. # How the object should be initialized
  2374. def obj_init(excellon_obj, app_obj):
  2375. # self.progress.emit(20)
  2376. excellon_obj.drills = self.new_drills
  2377. excellon_obj.tools = self.new_tools
  2378. excellon_obj.slots = self.new_slots
  2379. excellon_obj.tool_offset = self.new_tool_offset
  2380. excellon_obj.options['name'] = outname
  2381. try:
  2382. excellon_obj.create_geometry()
  2383. except KeyError:
  2384. self.app.inform.emit(
  2385. _("[ERROR_NOTCL] There are no Tools definitions in the file. Aborting Excellon creation.")
  2386. )
  2387. except:
  2388. msg = _("[ERROR] An internal error has ocurred. See shell.\n")
  2389. msg += traceback.format_exc()
  2390. app_obj.inform.emit(msg)
  2391. raise
  2392. # raise
  2393. with self.app.proc_container.new(_("Creating Excellon.")):
  2394. try:
  2395. self.app.new_object("excellon", outname, obj_init)
  2396. except Exception as e:
  2397. log.error("Error on object creation: %s" % str(e))
  2398. self.app.progress.emit(100)
  2399. return
  2400. self.app.inform.emit(_("[success] Excellon editing finished."))
  2401. # self.progress.emit(100)
  2402. def on_tool_select(self, tool):
  2403. """
  2404. Behavior of the toolbar. Tool initialization.
  2405. :rtype : None
  2406. """
  2407. current_tool = tool
  2408. self.app.log.debug("on_tool_select('%s')" % tool)
  2409. if self.last_tool_selected is None and current_tool is not 'drill_select':
  2410. # self.draw_app.select_tool('drill_select')
  2411. self.complete = True
  2412. current_tool = 'drill_select'
  2413. self.app.inform.emit(_("[WARNING_NOTCL] Cancelled. There is no Tool/Drill selected"))
  2414. # This is to make the group behave as radio group
  2415. if current_tool in self.tools_exc:
  2416. if self.tools_exc[current_tool]["button"].isChecked():
  2417. self.app.log.debug("%s is checked." % current_tool)
  2418. for t in self.tools_exc:
  2419. if t != current_tool:
  2420. self.tools_exc[t]["button"].setChecked(False)
  2421. # this is where the Editor toolbar classes (button's) are instantiated
  2422. self.active_tool = self.tools_exc[current_tool]["constructor"](self)
  2423. # self.app.inform.emit(self.active_tool.start_msg)
  2424. else:
  2425. self.app.log.debug("%s is NOT checked." % current_tool)
  2426. for t in self.tools_exc:
  2427. self.tools_exc[t]["button"].setChecked(False)
  2428. self.select_tool('drill_select')
  2429. self.active_tool = FCDrillSelect(self)
  2430. def on_row_selected(self, row, col):
  2431. if col == 0:
  2432. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  2433. if self.app.defaults["global_mselect_key"] == 'Control':
  2434. modifier_to_use = Qt.ControlModifier
  2435. else:
  2436. modifier_to_use = Qt.ShiftModifier
  2437. if key_modifier == modifier_to_use:
  2438. pass
  2439. else:
  2440. self.selected = []
  2441. try:
  2442. selected_dia = self.tool2tooldia[self.tools_table_exc.currentRow() + 1]
  2443. self.last_tool_selected = int(self.tools_table_exc.currentRow()) + 1
  2444. for obj in self.storage_dict[selected_dia].get_objects():
  2445. self.selected.append(obj)
  2446. except Exception as e:
  2447. self.app.log.debug(str(e))
  2448. self.replot()
  2449. def toolbar_tool_toggle(self, key):
  2450. self.options[key] = self.sender().isChecked()
  2451. if self.options[key] is True:
  2452. return 1
  2453. else:
  2454. return 0
  2455. def on_canvas_click(self, event):
  2456. """
  2457. event.x and .y have canvas coordinates
  2458. event.xdata and .ydata have plot coordinates
  2459. :param event: Event object dispatched by VisPy
  2460. :return: None
  2461. """
  2462. self.pos = self.canvas.vispy_canvas.translate_coords(event.pos)
  2463. if self.app.grid_status() == True:
  2464. self.pos = self.app.geo_editor.snap(self.pos[0], self.pos[1])
  2465. self.app.app_cursor.enabled = True
  2466. # Update cursor
  2467. self.app.app_cursor.set_data(np.asarray([(self.pos[0], self.pos[1])]), symbol='++', edge_color='black',
  2468. size=20)
  2469. else:
  2470. self.pos = (self.pos[0], self.pos[1])
  2471. self.app.app_cursor.enabled = False
  2472. if event.button is 1:
  2473. self.app.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  2474. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (0, 0))
  2475. self.pos = self.canvas.vispy_canvas.translate_coords(event.pos)
  2476. # Selection with left mouse button
  2477. if self.active_tool is not None and event.button is 1:
  2478. # Dispatch event to active_tool
  2479. # msg = self.active_tool.click(self.app.geo_editor.snap(event.xdata, event.ydata))
  2480. self.active_tool.click(self.app.geo_editor.snap(self.pos[0], self.pos[1]))
  2481. # If it is a shape generating tool
  2482. if isinstance(self.active_tool, FCShapeTool) and self.active_tool.complete:
  2483. if self.current_storage is not None:
  2484. self.on_exc_shape_complete(self.current_storage)
  2485. self.build_ui()
  2486. # MS: always return to the Select Tool if modifier key is not pressed
  2487. # else return to the current tool
  2488. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  2489. if self.app.defaults["global_mselect_key"] == 'Control':
  2490. modifier_to_use = Qt.ControlModifier
  2491. else:
  2492. modifier_to_use = Qt.ShiftModifier
  2493. # if modifier key is pressed then we add to the selected list the current shape but if it's already
  2494. # in the selected list, we removed it. Therefore first click selects, second deselects.
  2495. if key_modifier == modifier_to_use:
  2496. self.select_tool(self.active_tool.name)
  2497. else:
  2498. # return to Select tool but not for FCDrillAdd or FCSlot
  2499. if isinstance(self.active_tool, FCDrillAdd) or isinstance(self.active_tool, FCSlot):
  2500. self.select_tool(self.active_tool.name)
  2501. else:
  2502. self.select_tool("drill_select")
  2503. return
  2504. if isinstance(self.active_tool, FCDrillSelect):
  2505. # self.app.log.debug("Replotting after click.")
  2506. self.replot()
  2507. else:
  2508. self.app.log.debug("No active tool to respond to click!")
  2509. def on_exc_shape_complete(self, storage):
  2510. self.app.log.debug("on_shape_complete()")
  2511. # Add shape
  2512. if type(storage) is list:
  2513. for item_storage in storage:
  2514. self.add_exc_shape(self.active_tool.geometry, item_storage)
  2515. else:
  2516. self.add_exc_shape(self.active_tool.geometry, storage)
  2517. # Remove any utility shapes
  2518. self.delete_utility_geometry()
  2519. self.tool_shape.clear(update=True)
  2520. # Replot and reset tool.
  2521. self.replot()
  2522. # self.active_tool = type(self.active_tool)(self)
  2523. def add_exc_shape(self, shape, storage):
  2524. """
  2525. Adds a shape to a specified shape storage.
  2526. :param shape: Shape to be added.
  2527. :type shape: DrawToolShape
  2528. :param storage: object where to store the shapes
  2529. :return: None
  2530. """
  2531. # List of DrawToolShape?
  2532. if isinstance(shape, list):
  2533. for subshape in shape:
  2534. self.add_exc_shape(subshape, storage)
  2535. return
  2536. assert isinstance(shape, DrawToolShape), \
  2537. "Expected a DrawToolShape, got %s" % str(type(shape))
  2538. assert shape.geo is not None, \
  2539. "Shape object has empty geometry (None)"
  2540. assert (isinstance(shape.geo, list) and len(shape.geo) > 0) or not isinstance(shape.geo, list), \
  2541. "Shape objects has empty geometry ([])"
  2542. if isinstance(shape, DrawToolUtilityShape):
  2543. self.utility.append(shape)
  2544. else:
  2545. storage.insert(shape) # TODO: Check performance
  2546. def add_shape(self, shape):
  2547. """
  2548. Adds a shape to the shape storage.
  2549. :param shape: Shape to be added.
  2550. :type shape: DrawToolShape
  2551. :return: None
  2552. """
  2553. # List of DrawToolShape?
  2554. if isinstance(shape, list):
  2555. for subshape in shape:
  2556. self.add_shape(subshape)
  2557. return
  2558. assert isinstance(shape, DrawToolShape), \
  2559. "Expected a DrawToolShape, got %s" % type(shape)
  2560. assert shape.geo is not None, \
  2561. "Shape object has empty geometry (None)"
  2562. assert (isinstance(shape.geo, list) and len(shape.geo) > 0) or not isinstance(shape.geo, list), \
  2563. "Shape objects has empty geometry ([])"
  2564. if isinstance(shape, DrawToolUtilityShape):
  2565. self.utility.append(shape)
  2566. else:
  2567. self.storage.insert(shape) # TODO: Check performance
  2568. def on_exc_click_release(self, event):
  2569. """
  2570. Handler of the "mouse_release" event.
  2571. It will pop-up the context menu on right mouse click unless there was a panning move (decided in the
  2572. "mouse_move" event handler) and only if the current tool is the Select tool.
  2573. It will 'close' a Editor tool if it is the case.
  2574. :param event: Event object dispatched by VisPy SceneCavas
  2575. :return: None
  2576. """
  2577. pos_canvas = self.canvas.vispy_canvas.translate_coords(event.pos)
  2578. if self.app.grid_status() == True:
  2579. pos = self.app.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  2580. else:
  2581. pos = (pos_canvas[0], pos_canvas[1])
  2582. # if the released mouse button was RMB then test if it was a panning motion or not, if not it was a context
  2583. # canvas menu
  2584. try:
  2585. if event.button == 2: # right click
  2586. if self.app.ui.popMenu.mouse_is_panning is False:
  2587. try:
  2588. QtGui.QGuiApplication.restoreOverrideCursor()
  2589. except Exception as e:
  2590. pass
  2591. if self.active_tool.complete is False and not isinstance(self.active_tool, FCDrillSelect):
  2592. self.active_tool.complete = True
  2593. self.in_action = False
  2594. self.delete_utility_geometry()
  2595. self.app.inform.emit(_("[success] Done."))
  2596. self.select_tool('drill_select')
  2597. else:
  2598. if isinstance(self.active_tool, FCDrillAdd):
  2599. self.active_tool.complete = True
  2600. self.in_action = False
  2601. self.delete_utility_geometry()
  2602. self.app.inform.emit(_("[success] Done."))
  2603. self.select_tool('drill_select')
  2604. self.app.cursor = QtGui.QCursor()
  2605. self.app.populate_cmenu_grids()
  2606. self.app.ui.popMenu.popup(self.app.cursor.pos())
  2607. except Exception as e:
  2608. log.warning("Error: %s" % str(e))
  2609. raise
  2610. # if the released mouse button was LMB then test if we had a right-to-left selection or a left-to-right
  2611. # selection and then select a type of selection ("enclosing" or "touching")
  2612. try:
  2613. if event.button == 1: # left click
  2614. if self.app.selection_type is not None:
  2615. self.draw_selection_area_handler(self.pos, pos, self.app.selection_type)
  2616. self.app.selection_type = None
  2617. elif isinstance(self.active_tool, FCDrillSelect):
  2618. self.active_tool.click_release((self.pos[0], self.pos[1]))
  2619. # if there are selected objects then plot them
  2620. if self.selected:
  2621. self.replot()
  2622. except Exception as e:
  2623. log.warning("Error: %s" % str(e))
  2624. raise
  2625. def draw_selection_area_handler(self, start, end, sel_type):
  2626. """
  2627. This function is called whenever we have a left mouse click release and only we have a left mouse click drag,
  2628. be it from left to right or from right to left. The direction of the drag is decided in the "mouse_move"
  2629. event handler.
  2630. Pressing a modifier key (eg. Ctrl, Shift or Alt) will change the behavior of the selection.
  2631. Depending on which tool belongs the selected shapes, the corresponding rows in the Tools Table are selected or
  2632. deselected.
  2633. :param start: mouse position when the selection LMB click was done
  2634. :param end: mouse position when the left mouse button is released
  2635. :param sel_type: if True it's a left to right selection (enclosure), if False it's a 'touch' selection
  2636. :return:
  2637. """
  2638. start_pos = (start[0], start[1])
  2639. end_pos = (end[0], end[1])
  2640. poly_selection = Polygon([start_pos, (end_pos[0], start_pos[1]), end_pos, (start_pos[0], end_pos[1])])
  2641. modifiers = None
  2642. # delete the selection shape that was just drawn, we no longer need it
  2643. self.app.delete_selection_shape()
  2644. # detect if a modifier key was pressed while the left mouse button was released
  2645. self.modifiers = QtWidgets.QApplication.keyboardModifiers()
  2646. if self.modifiers == QtCore.Qt.ShiftModifier:
  2647. modifiers = 'Shift'
  2648. elif self.modifiers == QtCore.Qt.ControlModifier:
  2649. modifiers = 'Control'
  2650. if modifiers == self.app.defaults["global_mselect_key"]:
  2651. for storage in self.storage_dict:
  2652. for obj in self.storage_dict[storage].get_objects():
  2653. if (sel_type is True and poly_selection.contains(obj.geo)) or \
  2654. (sel_type is False and poly_selection.intersects(obj.geo)):
  2655. if obj in self.selected:
  2656. # remove the shape object from the selected shapes storage
  2657. self.selected.remove(obj)
  2658. else:
  2659. # add the shape object to the selected shapes storage
  2660. self.selected.append(obj)
  2661. else:
  2662. # clear the selection shapes storage
  2663. self.selected = []
  2664. # then add to the selection shapes storage the shapes that are included (touched) by the selection rectangle
  2665. for storage in self.storage_dict:
  2666. for obj in self.storage_dict[storage].get_objects():
  2667. if (sel_type is True and poly_selection.contains(obj.geo)) or \
  2668. (sel_type is False and poly_selection.intersects(obj.geo)):
  2669. self.selected.append(obj)
  2670. try:
  2671. self.tools_table_exc.cellPressed.disconnect()
  2672. except Exception as e:
  2673. pass
  2674. # first deselect all rows (tools) in the Tools Table
  2675. self.tools_table_exc.clearSelection()
  2676. # and select the rows (tools) in the tool table according to the diameter(s) of the selected shape(s)
  2677. self.tools_table_exc.setSelectionMode(QtWidgets.QAbstractItemView.MultiSelection)
  2678. for storage in self.storage_dict:
  2679. for shape_s in self.selected:
  2680. if shape_s in self.storage_dict[storage].get_objects():
  2681. for key in self.tool2tooldia:
  2682. if self.tool2tooldia[key] == storage:
  2683. item = self.tools_table_exc.item((key - 1), 1)
  2684. self.tools_table_exc.setCurrentItem(item)
  2685. self.last_tool_selected = int(key)
  2686. self.tools_table_exc.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
  2687. self.tools_table_exc.cellPressed.connect(self.on_row_selected)
  2688. self.replot()
  2689. def on_canvas_move(self, event):
  2690. """
  2691. Called on 'mouse_move' event.
  2692. It updates the mouse cursor if the grid snapping is ON.
  2693. It decide if we have a mouse drag and if it is done with the right mouse click. Then it passes this info to a
  2694. class object which is used in the "mouse_release" handler to decide if to pop-up the context menu or not.
  2695. It draws utility_geometry for the Editor tools.
  2696. Update the position labels from status bar.
  2697. Decide if we have a right to left or a left to right mouse drag with left mouse button and call a function
  2698. that will draw a selection shape on canvas.
  2699. event.pos have canvas screen coordinates
  2700. :param event: Event object dispatched by VisPy SceneCavas
  2701. :return: None
  2702. """
  2703. pos = self.canvas.vispy_canvas.translate_coords(event.pos)
  2704. event.xdata, event.ydata = pos[0], pos[1]
  2705. self.x = event.xdata
  2706. self.y = event.ydata
  2707. self.app.ui.popMenu.mouse_is_panning = False
  2708. # if the RMB is clicked and mouse is moving over plot then 'panning_action' is True
  2709. if event.button == 2 and event.is_dragging == 1:
  2710. self.app.ui.popMenu.mouse_is_panning = True
  2711. return
  2712. try:
  2713. x = float(event.xdata)
  2714. y = float(event.ydata)
  2715. except TypeError:
  2716. return
  2717. if self.active_tool is None:
  2718. return
  2719. # ## Snap coordinates
  2720. if self.app.grid_status() == True:
  2721. x, y = self.app.geo_editor.snap(x, y)
  2722. self.app.app_cursor.enabled = True
  2723. # Update cursor
  2724. self.app.app_cursor.set_data(np.asarray([(x, y)]), symbol='++', edge_color='black', size=20)
  2725. else:
  2726. self.app.app_cursor.enabled = False
  2727. self.snap_x = x
  2728. self.snap_y = y
  2729. # update the position label in the infobar since the APP mouse event handlers are disconnected
  2730. self.app.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  2731. "<b>Y</b>: %.4f" % (x, y))
  2732. if self.pos is None:
  2733. self.pos = (0, 0)
  2734. dx = x - self.pos[0]
  2735. dy = y - self.pos[1]
  2736. # update the reference position label in the infobar since the APP mouse event handlers are disconnected
  2737. self.app.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  2738. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  2739. # ## Utility geometry (animated)
  2740. geo = self.active_tool.utility_geometry(data=(x, y))
  2741. if isinstance(geo, DrawToolShape) and geo.geo is not None:
  2742. # Remove any previous utility shape
  2743. self.tool_shape.clear(update=True)
  2744. self.draw_utility_geometry(geo=geo)
  2745. # ## Selection area on canvas section # ##
  2746. if event.is_dragging == 1 and event.button == 1:
  2747. # I make an exception for FCDrillAdd and FCDrillArray because clicking and dragging while making regions
  2748. # can create strange issues. Also for FCSlot and FCSlotArray
  2749. if isinstance(self.active_tool, FCDrillAdd) or isinstance(self.active_tool, FCDrillArray) or \
  2750. isinstance(self.active_tool, FCSlot) or isinstance(self.active_tool, FCSlotArray):
  2751. self.app.selection_type = None
  2752. else:
  2753. dx = pos[0] - self.pos[0]
  2754. self.app.delete_selection_shape()
  2755. if dx < 0:
  2756. self.app.draw_moving_selection_shape((self.pos[0], self.pos[1]), (x, y),
  2757. color=self.app.defaults["global_alt_sel_line"],
  2758. face_color=self.app.defaults['global_alt_sel_fill'])
  2759. self.app.selection_type = False
  2760. else:
  2761. self.app.draw_moving_selection_shape((self.pos[0], self.pos[1]), (x, y))
  2762. self.app.selection_type = True
  2763. else:
  2764. self.app.selection_type = None
  2765. # Update cursor
  2766. self.app.app_cursor.set_data(np.asarray([(x, y)]), symbol='++', edge_color='black', size=20)
  2767. def on_canvas_key_release(self, event):
  2768. self.key = None
  2769. def draw_utility_geometry(self, geo):
  2770. # Add the new utility shape
  2771. try:
  2772. # this case is for the Font Parse
  2773. for el in list(geo.geo):
  2774. if type(el) == MultiPolygon:
  2775. for poly in el:
  2776. self.tool_shape.add(
  2777. shape=poly,
  2778. color=(self.app.defaults["global_draw_color"] + '80'),
  2779. update=False,
  2780. layer=0,
  2781. tolerance=None
  2782. )
  2783. elif type(el) == MultiLineString:
  2784. for linestring in el:
  2785. self.tool_shape.add(
  2786. shape=linestring,
  2787. color=(self.app.defaults["global_draw_color"] + '80'),
  2788. update=False,
  2789. layer=0,
  2790. tolerance=None
  2791. )
  2792. else:
  2793. self.tool_shape.add(
  2794. shape=el,
  2795. color=(self.app.defaults["global_draw_color"] + '80'),
  2796. update=False,
  2797. layer=0,
  2798. tolerance=None
  2799. )
  2800. except TypeError:
  2801. self.tool_shape.add(
  2802. shape=geo.geo, color=(self.app.defaults["global_draw_color"] + '80'),
  2803. update=False, layer=0, tolerance=None)
  2804. self.tool_shape.redraw()
  2805. def replot(self):
  2806. self.plot_all()
  2807. def plot_all(self):
  2808. """
  2809. Plots all shapes in the editor.
  2810. :return: None
  2811. :rtype: None
  2812. """
  2813. # self.app.log.debug("plot_all()")
  2814. self.shapes.clear(update=True)
  2815. for storage in self.storage_dict:
  2816. for shape_plus in self.storage_dict[storage].get_objects():
  2817. if shape_plus.geo is None:
  2818. continue
  2819. if shape_plus in self.selected:
  2820. self.plot_shape(geometry=shape_plus.geo, color=self.app.defaults['global_sel_draw_color'],
  2821. linewidth=2)
  2822. continue
  2823. self.plot_shape(geometry=shape_plus.geo, color=self.app.defaults['global_draw_color'])
  2824. # for shape in self.storage.get_objects():
  2825. # if shape.geo is None: # TODO: This shouldn't have happened
  2826. # continue
  2827. #
  2828. # if shape in self.selected:
  2829. # self.plot_shape(geometry=shape.geo, color=self.app.defaults['global_sel_draw_color'], linewidth=2)
  2830. # continue
  2831. #
  2832. # self.plot_shape(geometry=shape.geo, color=self.app.defaults['global_draw_color'])
  2833. for shape_form in self.utility:
  2834. self.plot_shape(geometry=shape_form.geo, linewidth=1)
  2835. continue
  2836. self.shapes.redraw()
  2837. def plot_shape(self, geometry=None, color='black', linewidth=1):
  2838. """
  2839. Plots a geometric object or list of objects without rendering. Plotted objects
  2840. are returned as a list. This allows for efficient/animated rendering.
  2841. :param geometry: Geometry to be plotted (Any Shapely.geom kind or list of such)
  2842. :param color: Shape color
  2843. :param linewidth: Width of lines in # of pixels.
  2844. :return: List of plotted elements.
  2845. """
  2846. plot_elements = []
  2847. if geometry is None:
  2848. geometry = self.active_tool.geometry
  2849. try:
  2850. for geo in geometry:
  2851. plot_elements += self.plot_shape(geometry=geo, color=color, linewidth=linewidth)
  2852. # ## Non-iterable
  2853. except TypeError:
  2854. # ## DrawToolShape
  2855. if isinstance(geometry, DrawToolShape):
  2856. plot_elements += self.plot_shape(geometry=geometry.geo, color=color, linewidth=linewidth)
  2857. # ## Polygon: Descend into exterior and each interior.
  2858. if type(geometry) == Polygon:
  2859. plot_elements += self.plot_shape(geometry=geometry.exterior, color=color, linewidth=linewidth)
  2860. plot_elements += self.plot_shape(geometry=geometry.interiors, color=color, linewidth=linewidth)
  2861. if type(geometry) == LineString or type(geometry) == LinearRing:
  2862. plot_elements.append(self.shapes.add(shape=geometry, color=color, layer=0))
  2863. if type(geometry) == Point:
  2864. pass
  2865. return plot_elements
  2866. def on_shape_complete(self):
  2867. self.app.log.debug("on_shape_complete()")
  2868. # Add shape
  2869. self.add_shape(self.active_tool.geometry)
  2870. # Remove any utility shapes
  2871. self.delete_utility_geometry()
  2872. self.tool_shape.clear(update=True)
  2873. # Replot and reset tool.
  2874. self.replot()
  2875. # self.active_tool = type(self.active_tool)(self)
  2876. def get_selected(self):
  2877. """
  2878. Returns list of shapes that are selected in the editor.
  2879. :return: List of shapes.
  2880. """
  2881. # return [shape for shape in self.shape_buffer if shape["selected"]]
  2882. return self.selected
  2883. def delete_selected(self):
  2884. temp_ref = [s for s in self.selected]
  2885. for shape_sel in temp_ref:
  2886. self.delete_shape(shape_sel)
  2887. self.selected = []
  2888. self.build_ui()
  2889. self.app.inform.emit(_("[success] Done. Drill(s) deleted."))
  2890. def delete_shape(self, del_shape):
  2891. self.is_modified = True
  2892. if del_shape in self.utility:
  2893. self.utility.remove(del_shape)
  2894. return
  2895. for storage in self.storage_dict:
  2896. # try:
  2897. # self.storage_dict[storage].remove(shape)
  2898. # except:
  2899. # pass
  2900. if del_shape in self.storage_dict[storage].get_objects():
  2901. if isinstance(del_shape.geo, MultiLineString):
  2902. self.storage_dict[storage].remove(del_shape)
  2903. # a hack to make the tool_table display less drills per diameter
  2904. # self.points_edit it's only useful first time when we load the data into the storage
  2905. # but is still used as referecen when building tool_table in self.build_ui()
  2906. # the number of drills displayed in column 2 is just a len(self.points_edit) therefore
  2907. # deleting self.points_edit elements (doesn't matter who but just the number) solved the display issue.
  2908. del self.points_edit[storage][0]
  2909. else:
  2910. self.storage_dict[storage].remove(del_shape)
  2911. del self.slot_points_edit[storage][0]
  2912. if del_shape in self.selected:
  2913. self.selected.remove(del_shape) # TODO: Check performance
  2914. def delete_utility_geometry(self):
  2915. for_deletion = [util_shape for util_shape in self.utility]
  2916. for util_shape in for_deletion:
  2917. self.delete_shape(util_shape)
  2918. self.tool_shape.clear(update=True)
  2919. self.tool_shape.redraw()
  2920. def on_delete_btn(self):
  2921. self.delete_selected()
  2922. self.replot()
  2923. def select_tool(self, toolname):
  2924. """
  2925. Selects a drawing tool. Impacts the object and GUI.
  2926. :param toolname: Name of the tool.
  2927. :return: None
  2928. """
  2929. self.tools_exc[toolname]["button"].setChecked(True)
  2930. self.on_tool_select(toolname)
  2931. def set_selected(self, sel_shape):
  2932. # Remove and add to the end.
  2933. if sel_shape in self.selected:
  2934. self.selected.remove(sel_shape)
  2935. self.selected.append(sel_shape)
  2936. def set_unselected(self, unsel_shape):
  2937. if unsel_shape in self.selected:
  2938. self.selected.remove(unsel_shape)
  2939. def on_array_type_combo(self):
  2940. if self.array_type_combo.currentIndex() == 0:
  2941. self.array_circular_frame.hide()
  2942. self.array_linear_frame.show()
  2943. else:
  2944. self.delete_utility_geometry()
  2945. self.array_circular_frame.show()
  2946. self.array_linear_frame.hide()
  2947. self.app.inform.emit(_("Click on the circular array Center position"))
  2948. def on_slot_array_type_combo(self):
  2949. if self.slot_array_type_combo.currentIndex() == 0:
  2950. self.slot_array_circular_frame.hide()
  2951. self.slot_array_linear_frame.show()
  2952. else:
  2953. self.delete_utility_geometry()
  2954. self.slot_array_circular_frame.show()
  2955. self.slot_array_linear_frame.hide()
  2956. self.app.inform.emit(_("Click on the circular array Center position"))
  2957. def on_linear_angle_radio(self):
  2958. val = self.drill_axis_radio.get_value()
  2959. if val == 'A':
  2960. self.linear_angle_spinner.show()
  2961. self.linear_angle_label.show()
  2962. else:
  2963. self.linear_angle_spinner.hide()
  2964. self.linear_angle_label.hide()
  2965. def on_slot_angle_radio(self):
  2966. val = self.slot_axis_radio.get_value()
  2967. if val == 'A':
  2968. self.slot_angle_spinner.show()
  2969. self.slot_angle_label.show()
  2970. else:
  2971. self.slot_angle_spinner.hide()
  2972. self.slot_angle_label.hide()
  2973. def exc_add_drill(self):
  2974. self.select_tool('drill_add')
  2975. return
  2976. def exc_add_drill_array(self):
  2977. self.select_tool('drill_array')
  2978. return
  2979. def exc_add_slot(self):
  2980. self.select_tool('slot_add')
  2981. return
  2982. def exc_add_slot_array(self):
  2983. self.select_tool('slot_array')
  2984. return
  2985. def exc_resize_drills(self):
  2986. self.select_tool('drill_resize')
  2987. return
  2988. def exc_copy_drills(self):
  2989. self.select_tool('drill_copy')
  2990. return
  2991. def exc_move_drills(self):
  2992. self.select_tool('drill_move')
  2993. return
  2994. def get_shapely_list_bounds(geometry_list):
  2995. xmin = Inf
  2996. ymin = Inf
  2997. xmax = -Inf
  2998. ymax = -Inf
  2999. for gs in geometry_list:
  3000. try:
  3001. gxmin, gymin, gxmax, gymax = gs.bounds
  3002. xmin = min([xmin, gxmin])
  3003. ymin = min([ymin, gymin])
  3004. xmax = max([xmax, gxmax])
  3005. ymax = max([ymax, gymax])
  3006. except Exception as e:
  3007. log.warning("DEVELOPMENT: Tried to get bounds of empty geometry. --> %s" % str(e))
  3008. return [xmin, ymin, xmax, ymax]
  3009. # EOF