FlatCAMObj.py 220 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253
  1. ############################################################
  2. # FlatCAM: 2D Post-processing for Manufacturing #
  3. # http://flatcam.org #
  4. # Author: Juan Pablo Caram (c) #
  5. # Date: 2/5/2014 #
  6. # MIT Licence #
  7. ############################################################
  8. from io import StringIO
  9. from PyQt5 import QtCore, QtGui
  10. from PyQt5.QtCore import Qt
  11. import copy
  12. import inspect # TODO: For debugging only.
  13. from shapely.geometry.base import JOIN_STYLE
  14. from datetime import datetime
  15. import FlatCAMApp
  16. from ObjectUI import *
  17. from FlatCAMCommon import LoudDict
  18. from FlatCAMEditor import FlatCAMGeoEditor
  19. from camlib import *
  20. from VisPyVisuals import ShapeCollectionVisual
  21. import itertools
  22. # Interrupts plotting process if FlatCAMObj has been deleted
  23. class ObjectDeleted(Exception):
  24. pass
  25. class ValidationError(Exception):
  26. def __init__(self, message, errors):
  27. super().__init__(message)
  28. self.errors = errors
  29. ########################################
  30. ## FlatCAMObj ##
  31. ########################################
  32. class FlatCAMObj(QtCore.QObject):
  33. """
  34. Base type of objects handled in FlatCAM. These become interactive
  35. in the GUI, can be plotted, and their options can be modified
  36. by the user in their respective forms.
  37. """
  38. # Instance of the application to which these are related.
  39. # The app should set this value.
  40. app = None
  41. def __init__(self, name):
  42. """
  43. Constructor.
  44. :param name: Name of the object given by the user.
  45. :return: FlatCAMObj
  46. """
  47. QtCore.QObject.__init__(self)
  48. # View
  49. self.ui = None
  50. self.options = LoudDict(name=name)
  51. self.options.set_change_callback(self.on_options_change)
  52. self.form_fields = {}
  53. self.kind = None # Override with proper name
  54. # self.shapes = ShapeCollection(parent=self.app.plotcanvas.vispy_canvas.view.scene)
  55. self.shapes = self.app.plotcanvas.new_shape_group()
  56. self.item = None # Link with project view item
  57. self.muted_ui = False
  58. self.deleted = False
  59. self._drawing_tolerance = 0.01
  60. # assert isinstance(self.ui, ObjectUI)
  61. # self.ui.name_entry.returnPressed.connect(self.on_name_activate)
  62. # self.ui.offset_button.clicked.connect(self.on_offset_button_click)
  63. # self.ui.scale_button.clicked.connect(self.on_scale_button_click)
  64. def __del__(self):
  65. pass
  66. def __str__(self):
  67. return "<FlatCAMObj({:12s}): {:20s}>".format(self.kind, self.options["name"])
  68. def from_dict(self, d):
  69. """
  70. This supersedes ``from_dict`` in derived classes. Derived classes
  71. must inherit from FlatCAMObj first, then from derivatives of Geometry.
  72. ``self.options`` is only updated, not overwritten. This ensures that
  73. options set by the app do not vanish when reading the objects
  74. from a project file.
  75. :param d: Dictionary with attributes to set.
  76. :return: None
  77. """
  78. for attr in self.ser_attrs:
  79. if attr == 'options':
  80. self.options.update(d[attr])
  81. else:
  82. try:
  83. setattr(self, attr, d[attr])
  84. except KeyError:
  85. log.debug("FlatCAMObj.from_dict() --> KeyError: %s. Means that we are loading an old project that don't"
  86. "have all attributes in the latest FlatCAM." % str(attr))
  87. pass
  88. def on_options_change(self, key):
  89. # Update form on programmatically options change
  90. self.set_form_item(key)
  91. # Set object visibility
  92. if key == 'plot':
  93. self.visible = self.options['plot']
  94. # self.emit(QtCore.SIGNAL("optionChanged"), key)
  95. self.optionChanged.emit(key)
  96. def set_ui(self, ui):
  97. self.ui = ui
  98. self.form_fields = {"name": self.ui.name_entry}
  99. assert isinstance(self.ui, ObjectUI)
  100. self.ui.name_entry.returnPressed.connect(self.on_name_activate)
  101. self.ui.offset_button.clicked.connect(self.on_offset_button_click)
  102. self.ui.scale_button.clicked.connect(self.on_scale_button_click)
  103. self.ui.offsetvector_entry.returnPressed.connect(self.on_offset_button_click)
  104. self.ui.scale_entry.returnPressed.connect(self.on_scale_button_click)
  105. # self.ui.skew_button.clicked.connect(self.on_skew_button_click)
  106. def build_ui(self):
  107. """
  108. Sets up the UI/form for this object. Show the UI
  109. in the App.
  110. :return: None
  111. :rtype: None
  112. """
  113. self.muted_ui = True
  114. FlatCAMApp.App.log.debug(str(inspect.stack()[1][3]) + "--> FlatCAMObj.build_ui()")
  115. # Remove anything else in the box
  116. # box_children = self.app.ui.notebook.selected_contents.get_children()
  117. # for child in box_children:
  118. # self.app.ui.notebook.selected_contents.remove(child)
  119. # while self.app.ui.selected_layout.count():
  120. # self.app.ui.selected_layout.takeAt(0)
  121. # Put in the UI
  122. # box_selected.pack_start(sw, True, True, 0)
  123. # self.app.ui.notebook.selected_contents.add(self.ui)
  124. # self.app.ui.selected_layout.addWidget(self.ui)
  125. try:
  126. self.app.ui.selected_scroll_area.takeWidget()
  127. except:
  128. self.app.log.debug("Nothing to remove")
  129. self.app.ui.selected_scroll_area.setWidget(self.ui)
  130. self.muted_ui = False
  131. def on_name_activate(self):
  132. old_name = copy.copy(self.options["name"])
  133. new_name = self.ui.name_entry.get_value()
  134. # update the SHELL auto-completer model data
  135. try:
  136. self.app.myKeywords.remove(old_name)
  137. self.app.myKeywords.append(new_name)
  138. self.app.shell._edit.set_model_data(self.app.myKeywords)
  139. except:
  140. log.debug("on_name_activate() --> Could not remove the old object name from auto-completer model list")
  141. self.options["name"] = self.ui.name_entry.get_value()
  142. self.app.inform.emit("[success]Name changed from %s to %s" % (old_name, new_name))
  143. def on_offset_button_click(self):
  144. self.app.report_usage("obj_on_offset_button")
  145. self.read_form()
  146. vect = self.ui.offsetvector_entry.get_value()
  147. self.offset(vect)
  148. self.plot()
  149. self.app.object_changed.emit(self)
  150. def on_scale_button_click(self):
  151. self.app.report_usage("obj_on_scale_button")
  152. self.read_form()
  153. factor = self.ui.scale_entry.get_value()
  154. self.scale(factor)
  155. self.plot()
  156. self.app.object_changed.emit(self)
  157. def on_skew_button_click(self):
  158. self.app.report_usage("obj_on_skew_button")
  159. self.read_form()
  160. xangle = self.ui.xangle_entry.get_value()
  161. yangle = self.ui.yangle_entry.get_value()
  162. self.skew(xangle, yangle)
  163. self.plot()
  164. self.app.object_changed.emit(self)
  165. def to_form(self):
  166. """
  167. Copies options to the UI form.
  168. :return: None
  169. """
  170. FlatCAMApp.App.log.debug(str(inspect.stack()[1][3]) + " --> FlatCAMObj.to_form()")
  171. for option in self.options:
  172. try:
  173. self.set_form_item(option)
  174. except:
  175. self.app.log.warning("Unexpected error:", sys.exc_info())
  176. def read_form(self):
  177. """
  178. Reads form into ``self.options``.
  179. :return: None
  180. :rtype: None
  181. """
  182. FlatCAMApp.App.log.debug(str(inspect.stack()[1][3]) + "--> FlatCAMObj.read_form()")
  183. for option in self.options:
  184. try:
  185. self.read_form_item(option)
  186. except:
  187. self.app.log.warning("Unexpected error:", sys.exc_info())
  188. def set_form_item(self, option):
  189. """
  190. Copies the specified option to the UI form.
  191. :param option: Name of the option (Key in ``self.options``).
  192. :type option: str
  193. :return: None
  194. """
  195. try:
  196. self.form_fields[option].set_value(self.options[option])
  197. except KeyError:
  198. # self.app.log.warn("Tried to set an option or field that does not exist: %s" % option)
  199. pass
  200. def read_form_item(self, option):
  201. """
  202. Reads the specified option from the UI form into ``self.options``.
  203. :param option: Name of the option.
  204. :type option: str
  205. :return: None
  206. """
  207. try:
  208. self.options[option] = self.form_fields[option].get_value()
  209. except KeyError:
  210. self.app.log.warning("Failed to read option from field: %s" % option)
  211. def plot(self):
  212. """
  213. Plot this object (Extend this method to implement the actual plotting).
  214. Call this in descendants before doing the plotting.
  215. :return: Whether to continue plotting or not depending on the "plot" option.
  216. :rtype: bool
  217. """
  218. FlatCAMApp.App.log.debug(str(inspect.stack()[1][3]) + " --> FlatCAMObj.plot()")
  219. if self.deleted:
  220. return False
  221. self.clear()
  222. return True
  223. def serialize(self):
  224. """
  225. Returns a representation of the object as a dictionary so
  226. it can be later exported as JSON. Override this method.
  227. :return: Dictionary representing the object
  228. :rtype: dict
  229. """
  230. return
  231. def deserialize(self, obj_dict):
  232. """
  233. Re-builds an object from its serialized version.
  234. :param obj_dict: Dictionary representing a FlatCAMObj
  235. :type obj_dict: dict
  236. :return: None
  237. """
  238. return
  239. def add_shape(self, **kwargs):
  240. if self.deleted:
  241. raise ObjectDeleted()
  242. else:
  243. key = self.shapes.add(tolerance=self.drawing_tolerance, **kwargs)
  244. return key
  245. @property
  246. def visible(self):
  247. return self.shapes.visible
  248. @visible.setter
  249. def visible(self, value):
  250. self.shapes.visible = value
  251. # Not all object types has annotations
  252. try:
  253. self.annotation.visible = value
  254. except AttributeError:
  255. pass
  256. @property
  257. def drawing_tolerance(self):
  258. return self._drawing_tolerance if self.units == 'MM' or not self.units else self._drawing_tolerance / 25.4
  259. @drawing_tolerance.setter
  260. def drawing_tolerance(self, value):
  261. self._drawing_tolerance = value if self.units == 'MM' or not self.units else value / 25.4
  262. def clear(self, update=False):
  263. self.shapes.clear(update)
  264. # Not all object types has annotations
  265. try:
  266. self.annotation.clear(update)
  267. except AttributeError:
  268. pass
  269. def delete(self):
  270. # Free resources
  271. del self.ui
  272. del self.options
  273. # Set flag
  274. self.deleted = True
  275. class FlatCAMGerber(FlatCAMObj, Gerber):
  276. """
  277. Represents Gerber code.
  278. """
  279. optionChanged = QtCore.pyqtSignal(str)
  280. ui_type = GerberObjectUI
  281. @staticmethod
  282. def merge(grb_list, grb_final):
  283. """
  284. Merges the geometry of objects in geo_list into
  285. the geometry of geo_final.
  286. :param grb_list: List of FlatCAMGerber Objects to join.
  287. :param grb_final: Destination FlatCAMGeometry object.
  288. :return: None
  289. """
  290. if grb_final.solid_geometry is None:
  291. grb_final.solid_geometry = []
  292. if type(grb_final.solid_geometry) is not list:
  293. grb_final.solid_geometry = [grb_final.solid_geometry]
  294. for grb in grb_list:
  295. for option in grb.options:
  296. if option is not 'name':
  297. try:
  298. grb_final.options[option] = grb.options[option]
  299. except:
  300. log.warning("Failed to copy option.", option)
  301. # Expand lists
  302. if type(grb) is list:
  303. FlatCAMGerber.merge(grb, grb_final)
  304. else: # If not list, just append
  305. for geos in grb.solid_geometry:
  306. grb_final.solid_geometry.append(geos)
  307. grb_final.solid_geometry = MultiPolygon(grb_final.solid_geometry)
  308. def __init__(self, name):
  309. Gerber.__init__(self, steps_per_circle=int(self.app.defaults["gerber_circle_steps"]))
  310. FlatCAMObj.__init__(self, name)
  311. self.kind = "gerber"
  312. # The 'name' is already in self.options from FlatCAMObj
  313. # Automatically updates the UI
  314. self.options.update({
  315. "plot": True,
  316. "multicolored": False,
  317. "solid": False,
  318. "isotooldia": 0.016,
  319. "isopasses": 1,
  320. "isooverlap": 0.15,
  321. "milling_type": "cl",
  322. "combine_passes": True,
  323. "noncoppermargin": 0.0,
  324. "noncopperrounded": False,
  325. "bboxmargin": 0.0,
  326. "bboxrounded": False
  327. })
  328. # type of isolation: 0 = exteriors, 1 = interiors, 2 = complete isolation (both interiors and exteriors)
  329. self.iso_type = 2
  330. self.multigeo = False
  331. self.apertures_row = 0
  332. # store the source file here
  333. self.source_file = ""
  334. # assert isinstance(self.ui, GerberObjectUI)
  335. # self.ui.plot_cb.stateChanged.connect(self.on_plot_cb_click)
  336. # self.ui.solid_cb.stateChanged.connect(self.on_solid_cb_click)
  337. # self.ui.multicolored_cb.stateChanged.connect(self.on_multicolored_cb_click)
  338. # self.ui.generate_iso_button.clicked.connect(self.on_iso_button_click)
  339. # self.ui.generate_cutout_button.clicked.connect(self.on_generatecutout_button_click)
  340. # self.ui.generate_bb_button.clicked.connect(self.on_generatebb_button_click)
  341. # self.ui.generate_noncopper_button.clicked.connect(self.on_generatenoncopper_button_click)
  342. # Attributes to be included in serialization
  343. # Always append to it because it carries contents
  344. # from predecessors.
  345. self.ser_attrs += ['options', 'kind']
  346. def set_ui(self, ui):
  347. """
  348. Maps options with GUI inputs.
  349. Connects GUI events to methods.
  350. :param ui: GUI object.
  351. :type ui: GerberObjectUI
  352. :return: None
  353. """
  354. FlatCAMObj.set_ui(self, ui)
  355. FlatCAMApp.App.log.debug("FlatCAMGerber.set_ui()")
  356. self.form_fields.update({
  357. "plot": self.ui.plot_cb,
  358. "multicolored": self.ui.multicolored_cb,
  359. "solid": self.ui.solid_cb,
  360. "isotooldia": self.ui.iso_tool_dia_entry,
  361. "isopasses": self.ui.iso_width_entry,
  362. "isooverlap": self.ui.iso_overlap_entry,
  363. "milling_type": self.ui.milling_type_radio,
  364. "combine_passes": self.ui.combine_passes_cb,
  365. "noncoppermargin": self.ui.noncopper_margin_entry,
  366. "noncopperrounded": self.ui.noncopper_rounded_cb,
  367. "bboxmargin": self.ui.bbmargin_entry,
  368. "bboxrounded": self.ui.bbrounded_cb
  369. })
  370. # Fill form fields only on object create
  371. self.to_form()
  372. assert isinstance(self.ui, GerberObjectUI)
  373. self.ui.plot_cb.stateChanged.connect(self.on_plot_cb_click)
  374. self.ui.solid_cb.stateChanged.connect(self.on_solid_cb_click)
  375. self.ui.multicolored_cb.stateChanged.connect(self.on_multicolored_cb_click)
  376. self.ui.generate_ext_iso_button.clicked.connect(self.on_ext_iso_button_click)
  377. self.ui.generate_int_iso_button.clicked.connect(self.on_int_iso_button_click)
  378. self.ui.generate_iso_button.clicked.connect(self.on_iso_button_click)
  379. self.ui.generate_ncc_button.clicked.connect(self.app.ncclear_tool.run)
  380. self.ui.generate_cutout_button.clicked.connect(self.app.cutout_tool.run)
  381. self.ui.generate_bb_button.clicked.connect(self.on_generatebb_button_click)
  382. self.ui.generate_noncopper_button.clicked.connect(self.on_generatenoncopper_button_click)
  383. self.ui.aperture_table_visibility_cb.stateChanged.connect(self.on_aperture_table_visibility_change)
  384. # Show/Hide Advanced Options
  385. if self.app.defaults["global_advanced"] is False:
  386. self.ui.level.setText('<span style="color:green;"><b>BASIC Mode</b></span>')
  387. self.ui.apertures_table_label.hide()
  388. self.ui.aperture_table_visibility_cb.hide()
  389. self.ui.milling_type_label.hide()
  390. self.ui.milling_type_radio.hide()
  391. self.ui.generate_ext_iso_button.hide()
  392. self.ui.generate_int_iso_button.hide()
  393. else:
  394. self.ui.level.setText('<span style="color:red;"><b>ADVANCED Mode</b></span>')
  395. self.build_ui()
  396. def build_ui(self):
  397. FlatCAMObj.build_ui(self)
  398. try:
  399. # if connected, disconnect the signal from the slot on item_changed as it creates issues
  400. self.ui.apertures_table.itemChanged.disconnect()
  401. except:
  402. pass
  403. n = len(self.apertures) + len(self.aperture_macros)
  404. self.ui.apertures_table.setRowCount(n)
  405. self.apertures_row = 0
  406. aper_no = self.apertures_row + 1
  407. sort = []
  408. for k, v in list(self.apertures.items()):
  409. sort.append(int(k))
  410. sorted_apertures = sorted(sort)
  411. sort = []
  412. for k, v in list(self.aperture_macros.items()):
  413. sort.append(k)
  414. sorted_macros = sorted(sort)
  415. for ap_code in sorted_apertures:
  416. ap_code = str(ap_code)
  417. ap_id_item = QtWidgets.QTableWidgetItem('%d' % int(self.apertures_row + 1))
  418. ap_id_item.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  419. self.ui.apertures_table.setItem(self.apertures_row, 0, ap_id_item) # Tool name/id
  420. ap_code_item = QtWidgets.QTableWidgetItem(ap_code)
  421. ap_code_item.setFlags(QtCore.Qt.ItemIsEnabled)
  422. ap_type_item = QtWidgets.QTableWidgetItem(str(self.apertures[ap_code]['type']))
  423. ap_type_item.setFlags(QtCore.Qt.ItemIsEnabled)
  424. if str(self.apertures[ap_code]['type']) == 'R' or str(self.apertures[ap_code]['type']) == 'O':
  425. ap_dim_item = QtWidgets.QTableWidgetItem(
  426. '%.4f, %.4f' % (self.apertures[ap_code]['width'] * self.file_units_factor,
  427. self.apertures[ap_code]['height'] * self.file_units_factor
  428. )
  429. )
  430. ap_dim_item.setFlags(QtCore.Qt.ItemIsEnabled)
  431. elif str(self.apertures[ap_code]['type']) == 'P':
  432. ap_dim_item = QtWidgets.QTableWidgetItem(
  433. '%.4f, %.4f' % (self.apertures[ap_code]['diam'] * self.file_units_factor,
  434. self.apertures[ap_code]['nVertices'] * self.file_units_factor)
  435. )
  436. ap_dim_item.setFlags(QtCore.Qt.ItemIsEnabled)
  437. else:
  438. ap_dim_item = QtWidgets.QTableWidgetItem('')
  439. ap_dim_item.setFlags(QtCore.Qt.ItemIsEnabled)
  440. try:
  441. if self.apertures[ap_code]['size'] is not None:
  442. ap_size_item = QtWidgets.QTableWidgetItem('%.4f' %
  443. float(self.apertures[ap_code]['size'] *
  444. self.file_units_factor))
  445. else:
  446. ap_size_item = QtWidgets.QTableWidgetItem('')
  447. except KeyError:
  448. ap_size_item = QtWidgets.QTableWidgetItem('')
  449. ap_size_item.setFlags(QtCore.Qt.ItemIsEnabled)
  450. plot_item = FCCheckBox()
  451. plot_item.setLayoutDirection(QtCore.Qt.RightToLeft)
  452. if self.ui.plot_cb.isChecked():
  453. plot_item.setChecked(True)
  454. self.ui.apertures_table.setItem(self.apertures_row, 1, ap_code_item) # Aperture Code
  455. self.ui.apertures_table.setItem(self.apertures_row, 2, ap_type_item) # Aperture Type
  456. self.ui.apertures_table.setItem(self.apertures_row, 3, ap_size_item) # Aperture Dimensions
  457. self.ui.apertures_table.setItem(self.apertures_row, 4, ap_dim_item) # Aperture Dimensions
  458. self.ui.apertures_table.setCellWidget(self.apertures_row, 5, plot_item)
  459. self.apertures_row += 1
  460. for ap_code in sorted_macros:
  461. ap_code = str(ap_code)
  462. ap_id_item = QtWidgets.QTableWidgetItem('%d' % int(self.apertures_row + 1))
  463. ap_id_item.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  464. self.ui.apertures_table.setItem(self.apertures_row, 0, ap_id_item) # Tool name/id
  465. ap_code_item = QtWidgets.QTableWidgetItem(ap_code)
  466. ap_type_item = QtWidgets.QTableWidgetItem('AM')
  467. ap_type_item.setFlags(QtCore.Qt.ItemIsEnabled)
  468. plot_item = FCCheckBox()
  469. plot_item.setLayoutDirection(QtCore.Qt.RightToLeft)
  470. if self.ui.plot_cb.isChecked():
  471. plot_item.setChecked(True)
  472. self.ui.apertures_table.setItem(self.apertures_row, 1, ap_code_item) # Aperture Code
  473. self.ui.apertures_table.setItem(self.apertures_row, 2, ap_type_item) # Aperture Type
  474. self.ui.apertures_table.setCellWidget(self.apertures_row, 5, plot_item)
  475. self.apertures_row += 1
  476. self.ui.apertures_table.selectColumn(0)
  477. #
  478. self.ui.apertures_table.resizeColumnsToContents()
  479. self.ui.apertures_table.resizeRowsToContents()
  480. vertical_header = self.ui.apertures_table.verticalHeader()
  481. # vertical_header.setSectionResizeMode(QtWidgets.QHeaderView.ResizeToContents)
  482. vertical_header.hide()
  483. self.ui.apertures_table.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  484. horizontal_header = self.ui.apertures_table.horizontalHeader()
  485. horizontal_header.setMinimumSectionSize(10)
  486. horizontal_header.setDefaultSectionSize(70)
  487. horizontal_header.setSectionResizeMode(0, QtWidgets.QHeaderView.Fixed)
  488. horizontal_header.resizeSection(0, 20)
  489. horizontal_header.setSectionResizeMode(1, QtWidgets.QHeaderView.ResizeToContents)
  490. horizontal_header.setSectionResizeMode(2, QtWidgets.QHeaderView.ResizeToContents)
  491. horizontal_header.setSectionResizeMode(3, QtWidgets.QHeaderView.ResizeToContents)
  492. horizontal_header.setSectionResizeMode(4, QtWidgets.QHeaderView.Stretch)
  493. horizontal_header.setSectionResizeMode(5, QtWidgets.QHeaderView.Fixed)
  494. horizontal_header.resizeSection(5, 17)
  495. self.ui.apertures_table.setColumnWidth(5, 17)
  496. self.ui.apertures_table.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  497. self.ui.apertures_table.setSortingEnabled(False)
  498. self.ui.apertures_table.setMinimumHeight(self.ui.apertures_table.getHeight())
  499. # self.ui_connect()
  500. def on_generatenoncopper_button_click(self, *args):
  501. self.app.report_usage("gerber_on_generatenoncopper_button")
  502. self.read_form()
  503. name = self.options["name"] + "_noncopper"
  504. def geo_init(geo_obj, app_obj):
  505. assert isinstance(geo_obj, FlatCAMGeometry)
  506. bounding_box = self.solid_geometry.envelope.buffer(float(self.options["noncoppermargin"]))
  507. if not self.options["noncopperrounded"]:
  508. bounding_box = bounding_box.envelope
  509. non_copper = bounding_box.difference(self.solid_geometry)
  510. geo_obj.solid_geometry = non_copper
  511. # TODO: Check for None
  512. self.app.new_object("geometry", name, geo_init)
  513. def on_generatebb_button_click(self, *args):
  514. self.app.report_usage("gerber_on_generatebb_button")
  515. self.read_form()
  516. name = self.options["name"] + "_bbox"
  517. def geo_init(geo_obj, app_obj):
  518. assert isinstance(geo_obj, FlatCAMGeometry)
  519. # Bounding box with rounded corners
  520. bounding_box = self.solid_geometry.envelope.buffer(float(self.options["bboxmargin"]))
  521. if not self.options["bboxrounded"]: # Remove rounded corners
  522. bounding_box = bounding_box.envelope
  523. geo_obj.solid_geometry = bounding_box
  524. self.app.new_object("geometry", name, geo_init)
  525. def on_ext_iso_button_click(self, *args):
  526. if self.ui.follow_cb.get_value() == True:
  527. obj = self.app.collection.get_active()
  528. obj.follow()
  529. # in the end toggle the visibility of the origin object so we can see the generated Geometry
  530. obj.ui.plot_cb.toggle()
  531. else:
  532. self.app.report_usage("gerber_on_iso_button")
  533. self.read_form()
  534. self.isolate(iso_type=0)
  535. def on_int_iso_button_click(self, *args):
  536. if self.ui.follow_cb.get_value() == True:
  537. obj = self.app.collection.get_active()
  538. obj.follow()
  539. # in the end toggle the visibility of the origin object so we can see the generated Geometry
  540. obj.ui.plot_cb.toggle()
  541. else:
  542. self.app.report_usage("gerber_on_iso_button")
  543. self.read_form()
  544. self.isolate(iso_type=1)
  545. def on_iso_button_click(self, *args):
  546. if self.ui.follow_cb.get_value() == True:
  547. obj = self.app.collection.get_active()
  548. obj.follow()
  549. # in the end toggle the visibility of the origin object so we can see the generated Geometry
  550. obj.ui.plot_cb.toggle()
  551. else:
  552. self.app.report_usage("gerber_on_iso_button")
  553. self.read_form()
  554. self.isolate()
  555. def follow(self, outname=None):
  556. """
  557. Creates a geometry object "following" the gerber paths.
  558. :return: None
  559. """
  560. # default_name = self.options["name"] + "_follow"
  561. # follow_name = outname or default_name
  562. if outname is None:
  563. follow_name = self.options["name"] + "_follow"
  564. else:
  565. follow_name = outname
  566. def follow_init(follow_obj, app):
  567. # Propagate options
  568. follow_obj.options["cnctooldia"] = float(self.options["isotooldia"])
  569. follow_obj.solid_geometry = self.solid_geometry
  570. # TODO: Do something if this is None. Offer changing name?
  571. try:
  572. self.app.new_object("geometry", follow_name, follow_init)
  573. except Exception as e:
  574. return "Operation failed: %s" % str(e)
  575. def isolate(self, iso_type=None, dia=None, passes=None, overlap=None,
  576. outname=None, combine=None, milling_type=None):
  577. """
  578. Creates an isolation routing geometry object in the project.
  579. :param iso_type: type of isolation to be done: 0 = exteriors, 1 = interiors and 2 = both
  580. :param dia: Tool diameter
  581. :param passes: Number of tool widths to cut
  582. :param overlap: Overlap between passes in fraction of tool diameter
  583. :param outname: Base name of the output object
  584. :return: None
  585. """
  586. if dia is None:
  587. dia = float(self.options["isotooldia"])
  588. if passes is None:
  589. passes = int(self.options["isopasses"])
  590. if overlap is None:
  591. overlap = float(self.options["isooverlap"])
  592. if combine is None:
  593. combine = self.options["combine_passes"]
  594. else:
  595. combine = bool(combine)
  596. if milling_type is None:
  597. milling_type = self.options["milling_type"]
  598. if iso_type is None:
  599. self.iso_type = 2
  600. else:
  601. self.iso_type = iso_type
  602. base_name = self.options["name"] + "_iso"
  603. base_name = outname or base_name
  604. def generate_envelope(offset, invert, envelope_iso_type=2):
  605. # isolation_geometry produces an envelope that is going on the left of the geometry
  606. # (the copper features). To leave the least amount of burrs on the features
  607. # the tool needs to travel on the right side of the features (this is called conventional milling)
  608. # the first pass is the one cutting all of the features, so it needs to be reversed
  609. # the other passes overlap preceding ones and cut the left over copper. It is better for them
  610. # to cut on the right side of the left over copper i.e on the left side of the features.
  611. try:
  612. geom = self.isolation_geometry(offset, iso_type=envelope_iso_type)
  613. except Exception as e:
  614. log.debug(str(e))
  615. return 'fail'
  616. if invert:
  617. try:
  618. if type(geom) is MultiPolygon:
  619. pl = []
  620. for p in geom:
  621. pl.append(Polygon(p.exterior.coords[::-1], p.interiors))
  622. geom = MultiPolygon(pl)
  623. elif type(geom) is Polygon:
  624. geom = Polygon(geom.exterior.coords[::-1], geom.interiors)
  625. else:
  626. log.debug("FlatCAMGerber.isolate().generate_envelope() Error --> Unexpected Geometry")
  627. except Exception as e:
  628. log.debug("FlatCAMGerber.isolate().generate_envelope() Error --> %s" % str(e))
  629. return geom
  630. if combine:
  631. if self.iso_type == 0:
  632. iso_name = self.options["name"] + "_ext_iso"
  633. elif self.iso_type == 1:
  634. iso_name = self.options["name"] + "_int_iso"
  635. else:
  636. iso_name = base_name
  637. # TODO: This is ugly. Create way to pass data into init function.
  638. def iso_init(geo_obj, app_obj):
  639. # Propagate options
  640. geo_obj.options["cnctooldia"] = float(self.options["isotooldia"])
  641. geo_obj.solid_geometry = []
  642. for i in range(passes):
  643. iso_offset = (((2 * i + 1) / 2.0) * dia) - (i * overlap * dia)
  644. # if milling type is climb then the move is counter-clockwise around features
  645. if milling_type == 'cl':
  646. # geom = generate_envelope (offset, i == 0)
  647. geom = generate_envelope(iso_offset, 1, envelope_iso_type=self.iso_type)
  648. else:
  649. geom = generate_envelope(iso_offset, 0, envelope_iso_type=self.iso_type)
  650. geo_obj.solid_geometry.append(geom)
  651. # detect if solid_geometry is empty and this require list flattening which is "heavy"
  652. # or just looking in the lists (they are one level depth) and if any is not empty
  653. # proceed with object creation, if there are empty and the number of them is the length
  654. # of the list then we have an empty solid_geometry which should raise a Custom Exception
  655. empty_cnt = 0
  656. if not isinstance(geo_obj.solid_geometry, list):
  657. geo_obj.solid_geometry = [geo_obj.solid_geometry]
  658. for g in geo_obj.solid_geometry:
  659. if g:
  660. app_obj.inform.emit("[success]Isolation geometry created: %s" % geo_obj.options["name"])
  661. break
  662. else:
  663. empty_cnt += 1
  664. if empty_cnt == len(geo_obj.solid_geometry):
  665. raise ValidationError("Empty Geometry", None)
  666. geo_obj.multigeo = False
  667. # TODO: Do something if this is None. Offer changing name?
  668. self.app.new_object("geometry", iso_name, iso_init)
  669. else:
  670. for i in range(passes):
  671. offset = (2 * i + 1) / 2.0 * dia - i * overlap * dia
  672. if passes > 1:
  673. if self.iso_type == 0:
  674. iso_name = self.options["name"] + "_ext_iso" + str(i + 1)
  675. elif self.iso_type == 1:
  676. iso_name = self.options["name"] + "_int_iso" + str(i + 1)
  677. else:
  678. iso_name = base_name + str(i + 1)
  679. else:
  680. if self.iso_type == 0:
  681. iso_name = self.options["name"] + "_ext_iso"
  682. elif self.iso_type == 1:
  683. iso_name = self.options["name"] + "_int_iso"
  684. else:
  685. iso_name = base_name
  686. # TODO: This is ugly. Create way to pass data into init function.
  687. def iso_init(geo_obj, app_obj):
  688. # Propagate options
  689. geo_obj.options["cnctooldia"] = float(self.options["isotooldia"])
  690. # if milling type is climb then the move is counter-clockwise around features
  691. if milling_type == 'cl':
  692. # geo_obj.solid_geometry = generate_envelope(offset, i == 0)
  693. geo_obj.solid_geometry = generate_envelope(offset, 1, envelope_iso_type=self.iso_type)
  694. else:
  695. geo_obj.solid_geometry = generate_envelope(offset, 0, envelope_iso_type=self.iso_type)
  696. # detect if solid_geometry is empty and this require list flattening which is "heavy"
  697. # or just looking in the lists (they are one level depth) and if any is not empty
  698. # proceed with object creation, if there are empty and the number of them is the length
  699. # of the list then we have an empty solid_geometry which should raise a Custom Exception
  700. empty_cnt = 0
  701. if not isinstance(geo_obj.solid_geometry, list):
  702. geo_obj.solid_geometry = [geo_obj.solid_geometry]
  703. for g in geo_obj.solid_geometry:
  704. if g:
  705. app_obj.inform.emit("[success]Isolation geometry created: %s" % geo_obj.options["name"])
  706. break
  707. else:
  708. empty_cnt += 1
  709. if empty_cnt == len(geo_obj.solid_geometry):
  710. raise ValidationError("Empty Geometry", None)
  711. geo_obj.multigeo = False
  712. # TODO: Do something if this is None. Offer changing name?
  713. self.app.new_object("geometry", iso_name, iso_init)
  714. def on_plot_cb_click(self, *args):
  715. if self.muted_ui:
  716. return
  717. self.read_form_item('plot')
  718. def on_solid_cb_click(self, *args):
  719. if self.muted_ui:
  720. return
  721. self.read_form_item('solid')
  722. self.plot()
  723. def on_multicolored_cb_click(self, *args):
  724. if self.muted_ui:
  725. return
  726. self.read_form_item('multicolored')
  727. self.plot()
  728. def on_aperture_table_visibility_change(self):
  729. if self.ui.aperture_table_visibility_cb.isChecked():
  730. self.ui.apertures_table.setVisible(True)
  731. else:
  732. self.ui.apertures_table.setVisible(False)
  733. def convert_units(self, units):
  734. """
  735. Converts the units of the object by scaling dimensions in all geometry
  736. and options.
  737. :param units: Units to which to convert the object: "IN" or "MM".
  738. :type units: str
  739. :return: None
  740. :rtype: None
  741. """
  742. factor = Gerber.convert_units(self, units)
  743. self.options['isotooldia'] = float(self.options['isotooldia']) * factor
  744. self.options['bboxmargin'] = float(self.options['bboxmargin']) * factor
  745. def plot(self, **kwargs):
  746. """
  747. :param kwargs: color and face_color
  748. :return:
  749. """
  750. FlatCAMApp.App.log.debug(str(inspect.stack()[1][3]) + " --> FlatCAMGerber.plot()")
  751. # Does all the required setup and returns False
  752. # if the 'ptint' option is set to False.
  753. if not FlatCAMObj.plot(self):
  754. return
  755. if 'color' in kwargs:
  756. color = kwargs['color']
  757. else:
  758. color = self.app.defaults['global_plot_line']
  759. if 'face_color' in kwargs:
  760. face_color = kwargs['face_color']
  761. else:
  762. face_color = self.app.defaults['global_plot_fill']
  763. geometry = self.solid_geometry
  764. # Make sure geometry is iterable.
  765. try:
  766. _ = iter(geometry)
  767. except TypeError:
  768. geometry = [geometry]
  769. def random_color():
  770. color = np.random.rand(4)
  771. color[3] = 1
  772. return color
  773. try:
  774. if self.options["solid"]:
  775. for g in geometry:
  776. if type(g) == Polygon or type(g) == LineString:
  777. self.add_shape(shape=g, color=color,
  778. face_color=random_color() if self.options['multicolored']
  779. else face_color, visible=self.options['plot'])
  780. else:
  781. for el in g:
  782. self.add_shape(shape=el, color=color,
  783. face_color=random_color() if self.options['multicolored']
  784. else face_color, visible=self.options['plot'])
  785. else:
  786. for g in geometry:
  787. if type(g) == Polygon or type(g) == LineString:
  788. self.add_shape(shape=g, color=random_color() if self.options['multicolored'] else 'black',
  789. visible=self.options['plot'])
  790. else:
  791. for el in g:
  792. self.add_shape(shape=el, color=random_color() if self.options['multicolored'] else 'black',
  793. visible=self.options['plot'])
  794. self.shapes.redraw()
  795. except (ObjectDeleted, AttributeError):
  796. self.shapes.clear(update=True)
  797. # experimental plot() when the solid_geometry is stored in the self.apertures
  798. # def plot_apertures(self, **kwargs):
  799. # """
  800. #
  801. # :param kwargs: color and face_color
  802. # :return:
  803. # """
  804. #
  805. # FlatCAMApp.App.log.debug(str(inspect.stack()[1][3]) + " --> FlatCAMGerber.plot()")
  806. #
  807. # # Does all the required setup and returns False
  808. # # if the 'ptint' option is set to False.
  809. # if not FlatCAMObj.plot(self):
  810. # return
  811. #
  812. # if 'color' in kwargs:
  813. # color = kwargs['color']
  814. # else:
  815. # color = self.app.defaults['global_plot_line']
  816. # if 'face_color' in kwargs:
  817. # face_color = kwargs['face_color']
  818. # else:
  819. # face_color = self.app.defaults['global_plot_fill']
  820. #
  821. # geometry = {}
  822. # for ap in self.apertures:
  823. # geometry[ap] = self.apertures[ap]['solid_geometry']
  824. # try:
  825. # _ = iter(geometry[ap])
  826. # except TypeError:
  827. # geometry[ap] = [geometry[ap]]
  828. #
  829. # def random_color():
  830. # color = np.random.rand(4)
  831. # color[3] = 1
  832. # return color
  833. #
  834. # try:
  835. # if self.options["solid"]:
  836. # for geo in geometry:
  837. # for g in geometry[geo]:
  838. # if type(g) == Polygon or type(g) == LineString:
  839. # self.add_shape(shape=g, color=color,
  840. # face_color=random_color() if self.options['multicolored']
  841. # else face_color, visible=self.options['plot'])
  842. # else:
  843. # for el in g:
  844. # self.add_shape(shape=el, color=color,
  845. # face_color=random_color() if self.options['multicolored']
  846. # else face_color, visible=self.options['plot'])
  847. # else:
  848. # for geo in geometry:
  849. # for g in geometry[geo]:
  850. # if type(g) == Polygon or type(g) == LineString:
  851. # self.add_shape(shape=g,
  852. # color=random_color() if self.options['multicolored'] else 'black',
  853. # visible=self.options['plot'])
  854. # else:
  855. # for el in g:
  856. # self.add_shape(shape=el,
  857. # color=random_color() if self.options['multicolored'] else 'black',
  858. # visible=self.options['plot'])
  859. # self.shapes.redraw()
  860. # except (ObjectDeleted, AttributeError):
  861. # self.shapes.clear(update=True)
  862. def serialize(self):
  863. return {
  864. "options": self.options,
  865. "kind": self.kind
  866. }
  867. class FlatCAMExcellon(FlatCAMObj, Excellon):
  868. """
  869. Represents Excellon/Drill code.
  870. """
  871. ui_type = ExcellonObjectUI
  872. optionChanged = QtCore.pyqtSignal(str)
  873. def __init__(self, name):
  874. Excellon.__init__(self, geo_steps_per_circle=int(self.app.defaults["geometry_circle_steps"]))
  875. FlatCAMObj.__init__(self, name)
  876. self.kind = "excellon"
  877. self.options.update({
  878. "plot": True,
  879. "solid": False,
  880. "drillz": -0.1,
  881. "travelz": 0.1,
  882. "feedrate": 5.0,
  883. "feedrate_rapid": 5.0,
  884. "tooldia": 0.1,
  885. "slot_tooldia": 0.1,
  886. "toolchange": False,
  887. "toolchangez": 1.0,
  888. "toolchangexy": "0.0, 0.0",
  889. "endz": 2.0,
  890. "startz": None,
  891. "spindlespeed": None,
  892. "dwell": True,
  893. "dwelltime": 1000,
  894. "ppname_e": 'defaults',
  895. "z_pdepth": -0.02,
  896. "feedrate_probe": 3.0,
  897. "optimization_type": "R",
  898. "gcode_type": "drills"
  899. })
  900. # TODO: Document this.
  901. self.tool_cbs = {}
  902. # dict to hold the tool number as key and tool offset as value
  903. self.tool_offset ={}
  904. # variable to store the total amount of drills per job
  905. self.tot_drill_cnt = 0
  906. self.tool_row = 0
  907. # variable to store the total amount of slots per job
  908. self.tot_slot_cnt = 0
  909. self.tool_row_slots = 0
  910. # variable to store the distance travelled
  911. self.travel_distance = 0.0
  912. # store the source file here
  913. self.source_file = ""
  914. self.multigeo = False
  915. # Attributes to be included in serialization
  916. # Always append to it because it carries contents
  917. # from predecessors.
  918. self.ser_attrs += ['options', 'kind']
  919. @staticmethod
  920. def merge(exc_list, exc_final):
  921. """
  922. Merge Excellon objects found in exc_list parameter into exc_final object.
  923. Options are always copied from source .
  924. Tools are disregarded, what is taken in consideration is the unique drill diameters found as values in the
  925. exc_list tools dict's. In the reconstruction section for each unique tool diameter it will be created a
  926. tool_name to be used in the final Excellon object, exc_final.
  927. If only one object is in exc_list parameter then this function will copy that object in the exc_final
  928. :param exc_list: List or one object of FlatCAMExcellon Objects to join.
  929. :param exc_final: Destination FlatCAMExcellon object.
  930. :return: None
  931. """
  932. # flag to signal that we need to reorder the tools dictionary and drills and slots lists
  933. flag_order = False
  934. try:
  935. flattened_list = list(itertools.chain(*exc_list))
  936. except TypeError:
  937. flattened_list = exc_list
  938. # this dict will hold the unique tool diameters found in the exc_list objects as the dict keys and the dict
  939. # values will be list of Shapely Points; for drills
  940. custom_dict_drills = {}
  941. # this dict will hold the unique tool diameters found in the exc_list objects as the dict keys and the dict
  942. # values will be list of Shapely Points; for slots
  943. custom_dict_slots = {}
  944. for exc in flattened_list:
  945. # copy options of the current excellon obj to the final excellon obj
  946. for option in exc.options:
  947. if option is not 'name':
  948. try:
  949. exc_final.options[option] = exc.options[option]
  950. except:
  951. exc.app.log.warning("Failed to copy option.", option)
  952. for drill in exc.drills:
  953. exc_tool_dia = float('%.3f' % exc.tools[drill['tool']]['C'])
  954. if exc_tool_dia not in custom_dict_drills:
  955. custom_dict_drills[exc_tool_dia] = [drill['point']]
  956. else:
  957. custom_dict_drills[exc_tool_dia].append(drill['point'])
  958. for slot in exc.slots:
  959. exc_tool_dia = float('%.3f' % exc.tools[slot['tool']]['C'])
  960. if exc_tool_dia not in custom_dict_slots:
  961. custom_dict_slots[exc_tool_dia] = [[slot['start'], slot['stop']]]
  962. else:
  963. custom_dict_slots[exc_tool_dia].append([slot['start'], slot['stop']])
  964. # add the zeros and units to the exc_final object
  965. exc_final.zeros = exc.zeros
  966. exc_final.units = exc.units
  967. # variable to make tool_name for the tools
  968. current_tool = 0
  969. # Here we add data to the exc_final object
  970. # the tools diameter are now the keys in the drill_dia dict and the values are the Shapely Points in case of
  971. # drills
  972. for tool_dia in custom_dict_drills:
  973. # we create a tool name for each key in the drill_dia dict (the key is a unique drill diameter)
  974. current_tool += 1
  975. tool_name = str(current_tool)
  976. spec = {"C": float(tool_dia)}
  977. exc_final.tools[tool_name] = spec
  978. # rebuild the drills list of dict's that belong to the exc_final object
  979. for point in custom_dict_drills[tool_dia]:
  980. exc_final.drills.append(
  981. {
  982. "point": point,
  983. "tool": str(current_tool)
  984. }
  985. )
  986. # Here we add data to the exc_final object
  987. # the tools diameter are now the keys in the drill_dia dict and the values are a list ([start, stop])
  988. # of two Shapely Points in case of slots
  989. for tool_dia in custom_dict_slots:
  990. # we create a tool name for each key in the slot_dia dict (the key is a unique slot diameter)
  991. # but only if there are no drills
  992. if not exc_final.tools:
  993. current_tool += 1
  994. tool_name = str(current_tool)
  995. spec = {"C": float(tool_dia)}
  996. exc_final.tools[tool_name] = spec
  997. else:
  998. dia_list = []
  999. for v in exc_final.tools.values():
  1000. dia_list.append(float(v["C"]))
  1001. if tool_dia not in dia_list:
  1002. flag_order = True
  1003. current_tool = len(dia_list) + 1
  1004. tool_name = str(current_tool)
  1005. spec = {"C": float(tool_dia)}
  1006. exc_final.tools[tool_name] = spec
  1007. else:
  1008. for k, v in exc_final.tools.items():
  1009. if v["C"] == tool_dia:
  1010. current_tool = int(k)
  1011. break
  1012. # rebuild the slots list of dict's that belong to the exc_final object
  1013. for point in custom_dict_slots[tool_dia]:
  1014. exc_final.slots.append(
  1015. {
  1016. "start": point[0],
  1017. "stop": point[1],
  1018. "tool": str(current_tool)
  1019. }
  1020. )
  1021. # flag_order == True means that there was an slot diameter not in the tools and we also have drills
  1022. # and the new tool was added to self.tools therefore we need to reorder the tools and drills and slots
  1023. current_tool = 0
  1024. if flag_order is True:
  1025. dia_list = []
  1026. temp_drills = []
  1027. temp_slots = []
  1028. temp_tools = {}
  1029. for v in exc_final.tools.values():
  1030. dia_list.append(float(v["C"]))
  1031. dia_list.sort()
  1032. for ordered_dia in dia_list:
  1033. current_tool += 1
  1034. tool_name_temp = str(current_tool)
  1035. spec_temp = {"C": float(ordered_dia)}
  1036. temp_tools[tool_name_temp] = spec_temp
  1037. for drill in exc_final.drills:
  1038. exc_tool_dia = float('%.3f' % exc_final.tools[drill['tool']]['C'])
  1039. if exc_tool_dia == ordered_dia:
  1040. temp_drills.append(
  1041. {
  1042. "point": drill["point"],
  1043. "tool": str(current_tool)
  1044. }
  1045. )
  1046. for slot in exc_final.slots:
  1047. slot_tool_dia = float('%.3f' % exc_final.tools[slot['tool']]['C'])
  1048. if slot_tool_dia == ordered_dia:
  1049. temp_slots.append(
  1050. {
  1051. "start": slot["start"],
  1052. "stop": slot["stop"],
  1053. "tool": str(current_tool)
  1054. }
  1055. )
  1056. # delete the exc_final tools, drills and slots
  1057. exc_final.tools = dict()
  1058. exc_final.drills[:] = []
  1059. exc_final.slots[:] = []
  1060. # update the exc_final tools, drills and slots with the ordered values
  1061. exc_final.tools = temp_tools
  1062. exc_final.drills[:] = temp_drills
  1063. exc_final.slots[:] = temp_slots
  1064. # create the geometry for the exc_final object
  1065. exc_final.create_geometry()
  1066. def build_ui(self):
  1067. FlatCAMObj.build_ui(self)
  1068. try:
  1069. # if connected, disconnect the signal from the slot on item_changed as it creates issues
  1070. self.ui.tools_table.itemChanged.disconnect()
  1071. except:
  1072. pass
  1073. n = len(self.tools)
  1074. # we have (n+2) rows because there are 'n' tools, each a row, plus the last 2 rows for totals.
  1075. self.ui.tools_table.setRowCount(n + 2)
  1076. self.tot_drill_cnt = 0
  1077. self.tot_slot_cnt = 0
  1078. self.tool_row = 0
  1079. sort = []
  1080. for k, v in list(self.tools.items()):
  1081. sort.append((k, v.get('C')))
  1082. sorted_tools = sorted(sort, key=lambda t1: t1[1])
  1083. tools = [i[0] for i in sorted_tools]
  1084. for tool_no in tools:
  1085. drill_cnt = 0 # variable to store the nr of drills per tool
  1086. slot_cnt = 0 # variable to store the nr of slots per tool
  1087. # Find no of drills for the current tool
  1088. for drill in self.drills:
  1089. if drill['tool'] == tool_no:
  1090. drill_cnt += 1
  1091. self.tot_drill_cnt += drill_cnt
  1092. # Find no of slots for the current tool
  1093. for slot in self.slots:
  1094. if slot['tool'] == tool_no:
  1095. slot_cnt += 1
  1096. self.tot_slot_cnt += slot_cnt
  1097. id = QtWidgets.QTableWidgetItem('%d' % int(tool_no))
  1098. id.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  1099. self.ui.tools_table.setItem(self.tool_row, 0, id) # Tool name/id
  1100. # Make sure that the drill diameter when in MM is with no more than 2 decimals
  1101. # There are no drill bits in MM with more than 3 decimals diameter
  1102. # For INCH the decimals should be no more than 3. There are no drills under 10mils
  1103. if self.units == 'MM':
  1104. dia = QtWidgets.QTableWidgetItem('%.2f' % (self.tools[tool_no]['C']))
  1105. else:
  1106. dia = QtWidgets.QTableWidgetItem('%.3f' % (self.tools[tool_no]['C']))
  1107. dia.setFlags(QtCore.Qt.ItemIsEnabled)
  1108. drill_count = QtWidgets.QTableWidgetItem('%d' % drill_cnt)
  1109. drill_count.setFlags(QtCore.Qt.ItemIsEnabled)
  1110. # if the slot number is zero is better to not clutter the GUI with zero's so we print a space
  1111. if slot_cnt > 0:
  1112. slot_count = QtWidgets.QTableWidgetItem('%d' % slot_cnt)
  1113. else:
  1114. slot_count = QtWidgets.QTableWidgetItem('')
  1115. slot_count.setFlags(QtCore.Qt.ItemIsEnabled)
  1116. try:
  1117. if self.units == 'MM':
  1118. t_offset = self.tool_offset[float('%.2f' % float(self.tools[tool_no]['C']))]
  1119. else:
  1120. t_offset = self.tool_offset[float('%.3f' % float(self.tools[tool_no]['C']))]
  1121. except KeyError:
  1122. t_offset = self.app.defaults['excellon_offset']
  1123. tool_offset_item = QtWidgets.QTableWidgetItem('%s' % str(t_offset))
  1124. plot_item = FCCheckBox()
  1125. plot_item.setLayoutDirection(QtCore.Qt.RightToLeft)
  1126. if self.ui.plot_cb.isChecked():
  1127. plot_item.setChecked(True)
  1128. self.ui.tools_table.setItem(self.tool_row, 1, dia) # Diameter
  1129. self.ui.tools_table.setItem(self.tool_row, 2, drill_count) # Number of drills per tool
  1130. self.ui.tools_table.setItem(self.tool_row, 3, slot_count) # Number of drills per tool
  1131. self.ui.tools_table.setItem(self.tool_row, 4, tool_offset_item) # Tool offset
  1132. self.ui.tools_table.setCellWidget(self.tool_row, 5, plot_item)
  1133. self.tool_row += 1
  1134. # add a last row with the Total number of drills
  1135. empty = QtWidgets.QTableWidgetItem('')
  1136. empty.setFlags(~QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  1137. empty_1 = QtWidgets.QTableWidgetItem('')
  1138. empty_1.setFlags(~QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  1139. label_tot_drill_count = QtWidgets.QTableWidgetItem('Total Drills')
  1140. tot_drill_count = QtWidgets.QTableWidgetItem('%d' % self.tot_drill_cnt)
  1141. label_tot_drill_count.setFlags(QtCore.Qt.ItemIsEnabled)
  1142. tot_drill_count.setFlags(QtCore.Qt.ItemIsEnabled)
  1143. self.ui.tools_table.setItem(self.tool_row, 0, empty)
  1144. self.ui.tools_table.setItem(self.tool_row, 1, label_tot_drill_count)
  1145. self.ui.tools_table.setItem(self.tool_row, 2, tot_drill_count) # Total number of drills
  1146. self.ui.tools_table.setItem(self.tool_row, 3, empty_1) # Total number of drills
  1147. font = QtGui.QFont()
  1148. font.setBold(True)
  1149. font.setWeight(75)
  1150. for k in [1, 2]:
  1151. self.ui.tools_table.item(self.tool_row, k).setForeground(QtGui.QColor(127, 0, 255))
  1152. self.ui.tools_table.item(self.tool_row, k).setFont(font)
  1153. self.tool_row += 1
  1154. # add a last row with the Total number of slots
  1155. empty_2 = QtWidgets.QTableWidgetItem('')
  1156. empty_2.setFlags(~QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  1157. empty_3 = QtWidgets.QTableWidgetItem('')
  1158. empty_3.setFlags(~QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  1159. label_tot_slot_count = QtWidgets.QTableWidgetItem('Total Slots')
  1160. tot_slot_count = QtWidgets.QTableWidgetItem('%d' % self.tot_slot_cnt)
  1161. label_tot_slot_count.setFlags(QtCore.Qt.ItemIsEnabled)
  1162. tot_slot_count.setFlags(QtCore.Qt.ItemIsEnabled)
  1163. self.ui.tools_table.setItem(self.tool_row, 0, empty_2)
  1164. self.ui.tools_table.setItem(self.tool_row, 1, label_tot_slot_count)
  1165. self.ui.tools_table.setItem(self.tool_row, 2, empty_3)
  1166. self.ui.tools_table.setItem(self.tool_row, 3, tot_slot_count) # Total number of slots
  1167. for kl in [1, 2, 3]:
  1168. self.ui.tools_table.item(self.tool_row, kl).setFont(font)
  1169. self.ui.tools_table.item(self.tool_row, kl).setForeground(QtGui.QColor(0, 70, 255))
  1170. # sort the tool diameter column
  1171. # self.ui.tools_table.sortItems(1)
  1172. # all the tools are selected by default
  1173. self.ui.tools_table.selectColumn(0)
  1174. #
  1175. self.ui.tools_table.resizeColumnsToContents()
  1176. self.ui.tools_table.resizeRowsToContents()
  1177. vertical_header = self.ui.tools_table.verticalHeader()
  1178. # vertical_header.setSectionResizeMode(QtWidgets.QHeaderView.ResizeToContents)
  1179. vertical_header.hide()
  1180. self.ui.tools_table.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  1181. horizontal_header = self.ui.tools_table.horizontalHeader()
  1182. horizontal_header.setMinimumSectionSize(10)
  1183. horizontal_header.setDefaultSectionSize(70)
  1184. horizontal_header.setSectionResizeMode(0, QtWidgets.QHeaderView.Fixed)
  1185. horizontal_header.resizeSection(0, 20)
  1186. horizontal_header.setSectionResizeMode(1, QtWidgets.QHeaderView.Stretch)
  1187. horizontal_header.setSectionResizeMode(2, QtWidgets.QHeaderView.ResizeToContents)
  1188. horizontal_header.setSectionResizeMode(3, QtWidgets.QHeaderView.ResizeToContents)
  1189. horizontal_header.setSectionResizeMode(4, QtWidgets.QHeaderView.ResizeToContents)
  1190. horizontal_header.setSectionResizeMode(5, QtWidgets.QHeaderView.Fixed)
  1191. horizontal_header.resizeSection(5, 17)
  1192. self.ui.tools_table.setColumnWidth(5, 17)
  1193. # horizontal_header.setStretchLastSection(True)
  1194. # horizontal_header.setColumnWidth(2, QtWidgets.QHeaderView.ResizeToContents)
  1195. # horizontal_header.setStretchLastSection(True)
  1196. self.ui.tools_table.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  1197. self.ui.tools_table.setSortingEnabled(False)
  1198. self.ui.tools_table.setMinimumHeight(self.ui.tools_table.getHeight())
  1199. self.ui.tools_table.setMaximumHeight(self.ui.tools_table.getHeight())
  1200. if not self.drills:
  1201. self.ui.tdlabel.hide()
  1202. self.ui.tooldia_entry.hide()
  1203. self.ui.generate_milling_button.hide()
  1204. else:
  1205. self.ui.tdlabel.show()
  1206. self.ui.tooldia_entry.show()
  1207. self.ui.generate_milling_button.show()
  1208. if not self.slots:
  1209. self.ui.stdlabel.hide()
  1210. self.ui.slot_tooldia_entry.hide()
  1211. self.ui.generate_milling_slots_button.hide()
  1212. else:
  1213. self.ui.stdlabel.show()
  1214. self.ui.slot_tooldia_entry.show()
  1215. self.ui.generate_milling_slots_button.show()
  1216. # we reactivate the signals after the after the tool adding as we don't need to see the tool been populated
  1217. self.ui.tools_table.itemChanged.connect(self.on_tool_offset_edit)
  1218. self.ui_connect()
  1219. def set_ui(self, ui):
  1220. """
  1221. Configures the user interface for this object.
  1222. Connects options to form fields.
  1223. :param ui: User interface object.
  1224. :type ui: ExcellonObjectUI
  1225. :return: None
  1226. """
  1227. FlatCAMObj.set_ui(self, ui)
  1228. FlatCAMApp.App.log.debug("FlatCAMExcellon.set_ui()")
  1229. self.form_fields.update({
  1230. "plot": self.ui.plot_cb,
  1231. "solid": self.ui.solid_cb,
  1232. "drillz": self.ui.cutz_entry,
  1233. "travelz": self.ui.travelz_entry,
  1234. "feedrate": self.ui.feedrate_entry,
  1235. "feedrate_rapid": self.ui.feedrate_rapid_entry,
  1236. "tooldia": self.ui.tooldia_entry,
  1237. "slot_tooldia": self.ui.slot_tooldia_entry,
  1238. "toolchange": self.ui.toolchange_cb,
  1239. "toolchangez": self.ui.toolchangez_entry,
  1240. "spindlespeed": self.ui.spindlespeed_entry,
  1241. "dwell": self.ui.dwell_cb,
  1242. "dwelltime": self.ui.dwelltime_entry,
  1243. "startz": self.ui.estartz_entry,
  1244. "endz": self.ui.eendz_entry,
  1245. "ppname_e": self.ui.pp_excellon_name_cb,
  1246. "z_pdepth": self.ui.pdepth_entry,
  1247. "feedrate_probe": self.ui.feedrate_probe_entry,
  1248. "gcode_type": self.ui.excellon_gcode_type_radio
  1249. })
  1250. for name in list(self.app.postprocessors.keys()):
  1251. # the HPGL postprocessor is only for Geometry not for Excellon job therefore don't add it
  1252. if name == 'hpgl':
  1253. continue
  1254. self.ui.pp_excellon_name_cb.addItem(name)
  1255. # Fill form fields
  1256. self.to_form()
  1257. # initialize the dict that holds the tools offset
  1258. t_default_offset = self.app.defaults["excellon_offset"]
  1259. if not self.tool_offset:
  1260. for value in self.tools.values():
  1261. if self.units == 'MM':
  1262. dia = float('%.2f' % float(value['C']))
  1263. else:
  1264. dia = float('%.3f' % float(value['C']))
  1265. self.tool_offset[dia] = t_default_offset
  1266. # Show/Hide Advanced Options
  1267. if self.app.defaults["global_advanced"] is False:
  1268. self.ui.level.setText('<span style="color:green;"><b>BASIC Mode</b></span>')
  1269. self.ui.tools_table.setColumnHidden(4, True)
  1270. self.ui.estartz_label.hide()
  1271. self.ui.estartz_entry.hide()
  1272. self.ui.eendz_label.hide()
  1273. self.ui.eendz_entry.hide()
  1274. self.ui.feedrate_rapid_label.hide()
  1275. self.ui.feedrate_rapid_entry.hide()
  1276. self.ui.pdepth_label.hide()
  1277. self.ui.pdepth_entry.hide()
  1278. self.ui.feedrate_probe_label.hide()
  1279. self.ui.feedrate_probe_entry.hide()
  1280. else:
  1281. self.ui.level.setText('<span style="color:red;"><b>ADVANCED Mode</b></span>')
  1282. assert isinstance(self.ui, ExcellonObjectUI), \
  1283. "Expected a ExcellonObjectUI, got %s" % type(self.ui)
  1284. self.ui.plot_cb.stateChanged.connect(self.on_plot_cb_click)
  1285. self.ui.solid_cb.stateChanged.connect(self.on_solid_cb_click)
  1286. self.ui.generate_cnc_button.clicked.connect(self.on_create_cncjob_button_click)
  1287. self.ui.generate_milling_button.clicked.connect(self.on_generate_milling_button_click)
  1288. self.ui.generate_milling_slots_button.clicked.connect(self.on_generate_milling_slots_button_click)
  1289. self.ui.pp_excellon_name_cb.activated.connect(self.on_pp_changed)
  1290. def ui_connect(self):
  1291. for row in range(self.ui.tools_table.rowCount() - 2):
  1292. self.ui.tools_table.cellWidget(row, 5).clicked.connect(self.on_plot_cb_click_table)
  1293. self.ui.plot_cb.stateChanged.connect(self.on_plot_cb_click)
  1294. def ui_disconnect(self):
  1295. for row in range(self.ui.tools_table.rowCount()):
  1296. try:
  1297. self.ui.tools_table.cellWidget(row, 5).clicked.disconnect()
  1298. except:
  1299. pass
  1300. try:
  1301. self.ui.plot_cb.stateChanged.disconnect()
  1302. except:
  1303. pass
  1304. def on_tool_offset_edit(self):
  1305. # if connected, disconnect the signal from the slot on item_changed as it creates issues
  1306. self.ui.tools_table.itemChanged.disconnect()
  1307. # self.tools_table_exc.selectionModel().currentChanged.disconnect()
  1308. self.is_modified = True
  1309. row_of_item_changed = self.ui.tools_table.currentRow()
  1310. if self.units == 'MM':
  1311. dia = float('%.2f' % float(self.ui.tools_table.item(row_of_item_changed, 1).text()))
  1312. else:
  1313. dia = float('%.3f' % float(self.ui.tools_table.item(row_of_item_changed, 1).text()))
  1314. current_table_offset_edited = None
  1315. if self.ui.tools_table.currentItem() is not None:
  1316. try:
  1317. current_table_offset_edited = float(self.ui.tools_table.currentItem().text())
  1318. except ValueError:
  1319. # try to convert comma to decimal point. if it's still not working error message and return
  1320. try:
  1321. current_table_offset_edited = float(self.ui.tools_table.currentItem().text().replace(',', '.'))
  1322. self.ui.tools_table.currentItem().setText(
  1323. self.ui.tools_table.currentItem().text().replace(',', '.'))
  1324. except ValueError:
  1325. self.app.inform.emit("[ERROR_NOTCL]Wrong value format entered, "
  1326. "use a number.")
  1327. self.ui.tools_table.currentItem().setText(str(self.tool_offset[dia]))
  1328. return
  1329. self.tool_offset[dia] = current_table_offset_edited
  1330. # we reactivate the signals after the after the tool editing
  1331. self.ui.tools_table.itemChanged.connect(self.on_tool_offset_edit)
  1332. def get_selected_tools_list(self):
  1333. """
  1334. Returns the keys to the self.tools dictionary corresponding
  1335. to the selections on the tool list in the GUI.
  1336. :return: List of tools.
  1337. :rtype: list
  1338. """
  1339. return [str(x.text()) for x in self.ui.tools_table.selectedItems()]
  1340. def get_selected_tools_table_items(self):
  1341. """
  1342. Returns a list of lists, each list in the list is made out of row elements
  1343. :return: List of table_tools items.
  1344. :rtype: list
  1345. """
  1346. table_tools_items = []
  1347. for x in self.ui.tools_table.selectedItems():
  1348. # from the columnCount we subtract a value of 1 which represent the last column (plot column)
  1349. # which does not have text
  1350. table_tools_items.append([self.ui.tools_table.item(x.row(), column).text()
  1351. for column in range(0, self.ui.tools_table.columnCount() - 1)])
  1352. for item in table_tools_items:
  1353. item[0] = str(item[0])
  1354. return table_tools_items
  1355. def export_excellon(self, whole, fract, e_zeros=None, form='dec', factor=1):
  1356. """
  1357. Returns two values, first is a boolean , if 1 then the file has slots and second contain the Excellon code
  1358. :return: has_slots and Excellon_code
  1359. """
  1360. excellon_code = ''
  1361. # store here if the file has slots, return 1 if any slots, 0 if only drills
  1362. has_slots = 0
  1363. # drills processing
  1364. try:
  1365. if self.drills:
  1366. length = whole + fract
  1367. for tool in self.tools:
  1368. excellon_code += 'T0%s\n' % str(tool) if int(tool) < 10 else 'T%s\n' % str(tool)
  1369. for drill in self.drills:
  1370. if form == 'dec' and tool == drill['tool']:
  1371. drill_x = drill['point'].x * factor
  1372. drill_y = drill['point'].y * factor
  1373. excellon_code += "X{:.{dec}f}Y{:.{dec}f}\n".format(drill_x, drill_y, dec=fract)
  1374. elif e_zeros == 'LZ' and tool == drill['tool']:
  1375. drill_x = drill['point'].x * factor
  1376. drill_y = drill['point'].y * factor
  1377. exc_x_formatted = "{:.{dec}f}".format(drill_x, dec=fract)
  1378. exc_y_formatted = "{:.{dec}f}".format(drill_y, dec=fract)
  1379. # extract whole part and decimal part
  1380. exc_x_formatted = exc_x_formatted.partition('.')
  1381. exc_y_formatted = exc_y_formatted.partition('.')
  1382. # left padd the 'whole' part with zeros
  1383. x_whole = exc_x_formatted[0].rjust(whole, '0')
  1384. y_whole = exc_y_formatted[0].rjust(whole, '0')
  1385. # restore the coordinate padded in the left with 0 and added the decimal part
  1386. # without the decinal dot
  1387. exc_x_formatted = x_whole + exc_x_formatted[2]
  1388. exc_y_formatted = y_whole + exc_y_formatted[2]
  1389. excellon_code += "X{xform}Y{yform}\n".format(xform=exc_x_formatted,
  1390. yform=exc_y_formatted)
  1391. elif tool == drill['tool']:
  1392. drill_x = drill['point'].x * factor
  1393. drill_y = drill['point'].y * factor
  1394. exc_x_formatted = "{:.{dec}f}".format(drill_x, dec=fract).replace('.', '')
  1395. exc_y_formatted = "{:.{dec}f}".format(drill_y, dec=fract).replace('.', '')
  1396. # pad with rear zeros
  1397. exc_x_formatted.ljust(length, '0')
  1398. exc_y_formatted.ljust(length, '0')
  1399. excellon_code += "X{xform}Y{yform}\n".format(xform=exc_x_formatted,
  1400. yform=exc_y_formatted)
  1401. except Exception as e:
  1402. log.debug(str(e))
  1403. # slots processing
  1404. try:
  1405. if self.slots:
  1406. has_slots = 1
  1407. for tool in self.tools:
  1408. if int(tool) < 10:
  1409. excellon_code += 'T0' + str(tool) + '\n'
  1410. else:
  1411. excellon_code += 'T' + str(tool) + '\n'
  1412. for slot in self.slots:
  1413. if form == 'dec' and tool == slot['tool']:
  1414. start_slot_x = slot['start'].x * factor
  1415. start_slot_y = slot['start'].y * factor
  1416. stop_slot_x = slot['stop'].x * factor
  1417. stop_slot_y = slot['stop'].y * factor
  1418. excellon_code += "G00X{:.{dec}f}Y{:.{dec}f}\nM15\n".format(start_slot_x,
  1419. start_slot_y,
  1420. dec=fract)
  1421. excellon_code += "G00X{:.{dec}f}Y{:.{dec}f}\nM16\n".format(stop_slot_x,
  1422. stop_slot_y,
  1423. dec=fract)
  1424. elif e_zeros == 'LZ' and tool == slot['tool']:
  1425. start_slot_x = slot['start'].x * factor
  1426. start_slot_y = slot['start'].y * factor
  1427. stop_slot_x = slot['stop'].x * factor
  1428. stop_slot_y = slot['stop'].y * factor
  1429. start_slot_x_formatted = "{:.{dec}f}".format(start_slot_x, dec=fract).replace('.', '')
  1430. start_slot_y_formatted = "{:.{dec}f}".format(start_slot_y, dec=fract).replace('.', '')
  1431. stop_slot_x_formatted = "{:.{dec}f}".format(stop_slot_x, dec=fract).replace('.', '')
  1432. stop_slot_y_formatted = "{:.{dec}f}".format(stop_slot_y, dec=fract).replace('.', '')
  1433. # extract whole part and decimal part
  1434. start_slot_x_formatted = start_slot_x_formatted.partition('.')
  1435. start_slot_y_formatted = start_slot_y_formatted.partition('.')
  1436. stop_slot_x_formatted = stop_slot_x_formatted.partition('.')
  1437. stop_slot_y_formatted = stop_slot_y_formatted.partition('.')
  1438. # left padd the 'whole' part with zeros
  1439. start_x_whole = start_slot_x_formatted[0].rjust(whole, '0')
  1440. start_y_whole = start_slot_y_formatted[0].rjust(whole, '0')
  1441. stop_x_whole = stop_slot_x_formatted[0].rjust(whole, '0')
  1442. stop_y_whole = stop_slot_y_formatted[0].rjust(whole, '0')
  1443. # restore the coordinate padded in the left with 0 and added the decimal part
  1444. # without the decinal dot
  1445. start_slot_x_formatted = start_x_whole + start_slot_x_formatted[2]
  1446. start_slot_y_formatted = start_y_whole + start_slot_y_formatted[2]
  1447. stop_slot_x_formatted = stop_x_whole + stop_slot_x_formatted[2]
  1448. stop_slot_y_formatted = stop_y_whole + stop_slot_y_formatted[2]
  1449. excellon_code += "G00X{xstart}Y{ystart}\nM15\n".format(xstart=start_slot_x_formatted,
  1450. ystart=start_slot_y_formatted)
  1451. excellon_code += "G00X{xstop}Y{ystop}\nM16\n".format(xstop=stop_slot_x_formatted,
  1452. ystop=stop_slot_y_formatted)
  1453. elif tool == slot['tool']:
  1454. start_slot_x = slot['start'].x * factor
  1455. start_slot_y = slot['start'].y * factor
  1456. stop_slot_x = slot['stop'].x * factor
  1457. stop_slot_y = slot['stop'].y * factor
  1458. length = whole + fract
  1459. start_slot_x_formatted = "{:.{dec}f}".format(start_slot_x, dec=fract).replace('.', '')
  1460. start_slot_y_formatted = "{:.{dec}f}".format(start_slot_y, dec=fract).replace('.', '')
  1461. stop_slot_x_formatted = "{:.{dec}f}".format(stop_slot_x, dec=fract).replace('.', '')
  1462. stop_slot_y_formatted = "{:.{dec}f}".format(stop_slot_y, dec=fract).replace('.', '')
  1463. # pad with rear zeros
  1464. start_slot_x_formatted.ljust(length, '0')
  1465. start_slot_y_formatted.ljust(length, '0')
  1466. stop_slot_x_formatted.ljust(length, '0')
  1467. stop_slot_y_formatted.ljust(length, '0')
  1468. excellon_code += "G00X{xstart}Y{ystart}\nM15\n".format(xstart=start_slot_x_formatted,
  1469. ystart=start_slot_y_formatted)
  1470. excellon_code += "G00X{xstop}Y{ystop}\nM16\n".format(xstop=stop_slot_x_formatted,
  1471. ystop=stop_slot_y_formatted)
  1472. except Exception as e:
  1473. log.debug(str(e))
  1474. if not self.drills and not self.slots:
  1475. log.debug("FlatCAMObj.FlatCAMExcellon.export_excellon() --> Excellon Object is empty: no drills, no slots.")
  1476. return 'fail'
  1477. return has_slots, excellon_code
  1478. def generate_milling_drills(self, tools=None, outname=None, tooldia=None, use_thread=False):
  1479. """
  1480. Note: This method is a good template for generic operations as
  1481. it takes it's options from parameters or otherwise from the
  1482. object's options and returns a (success, msg) tuple as feedback
  1483. for shell operations.
  1484. :return: Success/failure condition tuple (bool, str).
  1485. :rtype: tuple
  1486. """
  1487. # Get the tools from the list. These are keys
  1488. # to self.tools
  1489. if tools is None:
  1490. tools = self.get_selected_tools_list()
  1491. if outname is None:
  1492. outname = self.options["name"] + "_mill"
  1493. if tooldia is None:
  1494. tooldia = float(self.options["tooldia"])
  1495. # Sort tools by diameter. items() -> [('name', diameter), ...]
  1496. # sorted_tools = sorted(list(self.tools.items()), key=lambda tl: tl[1]) # no longer works in Python3
  1497. sort = []
  1498. for k, v in self.tools.items():
  1499. sort.append((k, v.get('C')))
  1500. sorted_tools = sorted(sort, key=lambda t1: t1[1])
  1501. if tools == "all":
  1502. tools = [i[0] for i in sorted_tools] # List if ordered tool names.
  1503. log.debug("Tools 'all' and sorted are: %s" % str(tools))
  1504. if len(tools) == 0:
  1505. self.app.inform.emit("[ERROR_NOTCL]Please select one or more tools from the list and try again.")
  1506. return False, "Error: No tools."
  1507. for tool in tools:
  1508. if tooldia > self.tools[tool]["C"]:
  1509. self.app.inform.emit("[ERROR_NOTCL] Milling tool for DRILLS is larger than hole size. Cancelled.")
  1510. return False, "Error: Milling tool is larger than hole."
  1511. def geo_init(geo_obj, app_obj):
  1512. assert isinstance(geo_obj, FlatCAMGeometry), \
  1513. "Initializer expected a FlatCAMGeometry, got %s" % type(geo_obj)
  1514. app_obj.progress.emit(20)
  1515. ### Add properties to the object
  1516. # get the tool_table items in a list of row items
  1517. tool_table_items = self.get_selected_tools_table_items()
  1518. # insert an information only element in the front
  1519. tool_table_items.insert(0, ["Tool_nr", "Diameter", "Drills_Nr", "Slots_Nr"])
  1520. geo_obj.options['Tools_in_use'] = tool_table_items
  1521. geo_obj.options['type'] = 'Excellon Geometry'
  1522. geo_obj.solid_geometry = []
  1523. # in case that the tool used has the same diameter with the hole, and since the maximum resolution
  1524. # for FlatCAM is 6 decimals,
  1525. # we add a tenth of the minimum value, meaning 0.0000001, which from our point of view is "almost zero"
  1526. for hole in self.drills:
  1527. if hole['tool'] in tools:
  1528. buffer_value = self.tools[hole['tool']]["C"] / 2 - tooldia / 2
  1529. if buffer_value == 0:
  1530. geo_obj.solid_geometry.append(
  1531. Point(hole['point']).buffer(0.0000001).exterior)
  1532. else:
  1533. geo_obj.solid_geometry.append(
  1534. Point(hole['point']).buffer(buffer_value).exterior)
  1535. if use_thread:
  1536. def geo_thread(app_obj):
  1537. app_obj.new_object("geometry", outname, geo_init)
  1538. app_obj.progress.emit(100)
  1539. # Create a promise with the new name
  1540. self.app.collection.promise(outname)
  1541. # Send to worker
  1542. self.app.worker_task.emit({'fcn': geo_thread, 'params': [self.app]})
  1543. else:
  1544. self.app.new_object("geometry", outname, geo_init)
  1545. return True, ""
  1546. def generate_milling_slots(self, tools=None, outname=None, tooldia=None, use_thread=False):
  1547. """
  1548. Note: This method is a good template for generic operations as
  1549. it takes it's options from parameters or otherwise from the
  1550. object's options and returns a (success, msg) tuple as feedback
  1551. for shell operations.
  1552. :return: Success/failure condition tuple (bool, str).
  1553. :rtype: tuple
  1554. """
  1555. # Get the tools from the list. These are keys
  1556. # to self.tools
  1557. if tools is None:
  1558. tools = self.get_selected_tools_list()
  1559. if outname is None:
  1560. outname = self.options["name"] + "_mill"
  1561. if tooldia is None:
  1562. tooldia = float(self.options["slot_tooldia"])
  1563. # Sort tools by diameter. items() -> [('name', diameter), ...]
  1564. # sorted_tools = sorted(list(self.tools.items()), key=lambda tl: tl[1]) # no longer works in Python3
  1565. sort = []
  1566. for k, v in self.tools.items():
  1567. sort.append((k, v.get('C')))
  1568. sorted_tools = sorted(sort, key=lambda t1: t1[1])
  1569. if tools == "all":
  1570. tools = [i[0] for i in sorted_tools] # List if ordered tool names.
  1571. log.debug("Tools 'all' and sorted are: %s" % str(tools))
  1572. if len(tools) == 0:
  1573. self.app.inform.emit("[ERROR_NOTCL]Please select one or more tools from the list and try again.")
  1574. return False, "Error: No tools."
  1575. for tool in tools:
  1576. # I add the 0.0001 value to account for the rounding error in converting from IN to MM and reverse
  1577. adj_toolstable_tooldia = float('%.4f' % float(tooldia))
  1578. adj_file_tooldia = float('%.4f' % float(self.tools[tool]["C"]))
  1579. if adj_toolstable_tooldia > adj_file_tooldia + 0.0001:
  1580. self.app.inform.emit("[ERROR_NOTCL] Milling tool for SLOTS is larger than hole size. Cancelled.")
  1581. return False, "Error: Milling tool is larger than hole."
  1582. def geo_init(geo_obj, app_obj):
  1583. assert isinstance(geo_obj, FlatCAMGeometry), \
  1584. "Initializer expected a FlatCAMGeometry, got %s" % type(geo_obj)
  1585. app_obj.progress.emit(20)
  1586. ### Add properties to the object
  1587. # get the tool_table items in a list of row items
  1588. tool_table_items = self.get_selected_tools_table_items()
  1589. # insert an information only element in the front
  1590. tool_table_items.insert(0, ["Tool_nr", "Diameter", "Drills_Nr", "Slots_Nr"])
  1591. geo_obj.options['Tools_in_use'] = tool_table_items
  1592. geo_obj.options['type'] = 'Excellon Geometry'
  1593. geo_obj.solid_geometry = []
  1594. # in case that the tool used has the same diameter with the hole, and since the maximum resolution
  1595. # for FlatCAM is 6 decimals,
  1596. # we add a tenth of the minimum value, meaning 0.0000001, which from our point of view is "almost zero"
  1597. for slot in self.slots:
  1598. if slot['tool'] in tools:
  1599. toolstable_tool = float('%.4f' % float(tooldia))
  1600. file_tool = float('%.4f' % float(self.tools[tool]["C"]))
  1601. # I add the 0.0001 value to account for the rounding error in converting from IN to MM and reverse
  1602. # for the file_tool (tooldia actually)
  1603. buffer_value = float(file_tool / 2) - float(toolstable_tool / 2) + 0.0001
  1604. if buffer_value == 0:
  1605. start = slot['start']
  1606. stop = slot['stop']
  1607. lines_string = LineString([start, stop])
  1608. poly = lines_string.buffer(0.0000001, int(self.geo_steps_per_circle)).exterior
  1609. geo_obj.solid_geometry.append(poly)
  1610. else:
  1611. start = slot['start']
  1612. stop = slot['stop']
  1613. lines_string = LineString([start, stop])
  1614. poly = lines_string.buffer(buffer_value, int(self.geo_steps_per_circle)).exterior
  1615. geo_obj.solid_geometry.append(poly)
  1616. if use_thread:
  1617. def geo_thread(app_obj):
  1618. app_obj.new_object("geometry", outname + '_slot', geo_init)
  1619. app_obj.progress.emit(100)
  1620. # Create a promise with the new name
  1621. self.app.collection.promise(outname)
  1622. # Send to worker
  1623. self.app.worker_task.emit({'fcn': geo_thread, 'params': [self.app]})
  1624. else:
  1625. self.app.new_object("geometry", outname + '_slot', geo_init)
  1626. return True, ""
  1627. def on_generate_milling_button_click(self, *args):
  1628. self.app.report_usage("excellon_on_create_milling_drills button")
  1629. self.read_form()
  1630. self.generate_milling_drills(use_thread=False)
  1631. def on_generate_milling_slots_button_click(self, *args):
  1632. self.app.report_usage("excellon_on_create_milling_slots_button")
  1633. self.read_form()
  1634. self.generate_milling_slots(use_thread=False)
  1635. def on_pp_changed(self):
  1636. current_pp = self.ui.pp_excellon_name_cb.get_value()
  1637. if "toolchange_probe" in current_pp.lower():
  1638. self.ui.pdepth_entry.setVisible(True)
  1639. self.ui.pdepth_label.show()
  1640. self.ui.feedrate_probe_entry.setVisible(True)
  1641. self.ui.feedrate_probe_label.show()
  1642. else:
  1643. self.ui.pdepth_entry.setVisible(False)
  1644. self.ui.pdepth_label.hide()
  1645. self.ui.feedrate_probe_entry.setVisible(False)
  1646. self.ui.feedrate_probe_label.hide()
  1647. def on_create_cncjob_button_click(self, *args):
  1648. self.app.report_usage("excellon_on_create_cncjob_button")
  1649. self.read_form()
  1650. # Get the tools from the list
  1651. tools = self.get_selected_tools_list()
  1652. if len(tools) == 0:
  1653. # if there is a single tool in the table (remember that the last 2 rows are for totals and do not count in
  1654. # tool number) it means that there are 3 rows (1 tool and 2 totals).
  1655. # in this case regardless of the selection status of that tool, use it.
  1656. if self.ui.tools_table.rowCount() == 3:
  1657. tools.append(self.ui.tools_table.item(0, 0).text())
  1658. else:
  1659. self.app.inform.emit("[ERROR_NOTCL]Please select one or more tools from the list and try again.")
  1660. return
  1661. xmin = self.options['xmin']
  1662. ymin = self.options['ymin']
  1663. xmax = self.options['xmax']
  1664. ymax = self.options['ymax']
  1665. job_name = self.options["name"] + "_cnc"
  1666. pp_excellon_name = self.options["ppname_e"]
  1667. # Object initialization function for app.new_object()
  1668. def job_init(job_obj, app_obj):
  1669. assert isinstance(job_obj, FlatCAMCNCjob), \
  1670. "Initializer expected a FlatCAMCNCjob, got %s" % type(job_obj)
  1671. # get the tool_table items in a list of row items
  1672. tool_table_items = self.get_selected_tools_table_items()
  1673. # insert an information only element in the front
  1674. tool_table_items.insert(0, ["Tool_nr", "Diameter", "Drills_Nr", "Slots_Nr"])
  1675. ### Add properties to the object
  1676. job_obj.options['Tools_in_use'] = tool_table_items
  1677. job_obj.options['type'] = 'Excellon'
  1678. job_obj.options['ppname_e'] = pp_excellon_name
  1679. app_obj.progress.emit(20)
  1680. job_obj.z_cut = float(self.options["drillz"])
  1681. job_obj.tool_offset = self.tool_offset
  1682. job_obj.z_move = float(self.options["travelz"])
  1683. job_obj.feedrate = float(self.options["feedrate"])
  1684. job_obj.feedrate_rapid = float(self.options["feedrate_rapid"])
  1685. job_obj.spindlespeed = float(self.options["spindlespeed"]) if self.options["spindlespeed"] else None
  1686. job_obj.dwell = self.options["dwell"]
  1687. job_obj.dwelltime = float(self.options["dwelltime"])
  1688. job_obj.pp_excellon_name = pp_excellon_name
  1689. job_obj.toolchange_xy_type = "excellon"
  1690. job_obj.coords_decimals = int(self.app.defaults["cncjob_coords_decimals"])
  1691. job_obj.fr_decimals = int(self.app.defaults["cncjob_fr_decimals"])
  1692. job_obj.options['xmin'] = xmin
  1693. job_obj.options['ymin'] = ymin
  1694. job_obj.options['xmax'] = xmax
  1695. job_obj.options['ymax'] = ymax
  1696. try:
  1697. job_obj.z_pdepth = float(self.options["z_pdepth"])
  1698. except ValueError:
  1699. # try to convert comma to decimal point. if it's still not working error message and return
  1700. try:
  1701. job_obj.z_pdepth = float(self.options["z_pdepth"].replace(',', '.'))
  1702. except ValueError:
  1703. self.app.inform.emit(
  1704. '[ERROR_NOTCL]Wrong value format for self.defaults["z_pdepth"] or self.options["z_pdepth"]')
  1705. try:
  1706. job_obj.feedrate_probe = float(self.options["feedrate_probe"])
  1707. except ValueError:
  1708. # try to convert comma to decimal point. if it's still not working error message and return
  1709. try:
  1710. job_obj.feedrate_rapid = float(self.options["feedrate_probe"].replace(',', '.'))
  1711. except ValueError:
  1712. self.app.inform.emit(
  1713. '[ERROR_NOTCL]Wrong value format for self.defaults["feedrate_probe"] '
  1714. 'or self.options["feedrate_probe"]')
  1715. # There could be more than one drill size...
  1716. # job_obj.tooldia = # TODO: duplicate variable!
  1717. # job_obj.options["tooldia"] =
  1718. tools_csv = ','.join(tools)
  1719. ret_val = job_obj.generate_from_excellon_by_tool(self, tools_csv,
  1720. drillz=float(self.options['drillz']),
  1721. toolchange=float(self.options["toolchange"]),
  1722. toolchangexy=self.app.defaults["excellon_toolchangexy"],
  1723. toolchangez=float(self.options["toolchangez"]),
  1724. startz=float(self.options["startz"]) if
  1725. self.options["startz"] else None,
  1726. endz=float(self.options["endz"]),
  1727. excellon_optimization_type=self.app.defaults[
  1728. "excellon_optimization_type"])
  1729. if ret_val == 'fail':
  1730. return 'fail'
  1731. app_obj.progress.emit(50)
  1732. job_obj.gcode_parse()
  1733. app_obj.progress.emit(60)
  1734. job_obj.create_geometry()
  1735. app_obj.progress.emit(80)
  1736. # To be run in separate thread
  1737. def job_thread(app_obj):
  1738. with self.app.proc_container.new("Generating CNC Code"):
  1739. app_obj.new_object("cncjob", job_name, job_init)
  1740. app_obj.progress.emit(100)
  1741. # Create promise for the new name.
  1742. self.app.collection.promise(job_name)
  1743. # Send to worker
  1744. # self.app.worker.add_task(job_thread, [self.app])
  1745. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  1746. def convert_units(self, units):
  1747. factor = Excellon.convert_units(self, units)
  1748. self.options['drillz'] = float(self.options['drillz']) * factor
  1749. self.options['travelz'] = float(self.options['travelz']) * factor
  1750. self.options['feedrate'] = float(self.options['feedrate']) * factor
  1751. self.options['feedrate_rapid'] = float(self.options['feedrate_rapid']) * factor
  1752. self.options['toolchangez'] = float(self.options['toolchangez']) * factor
  1753. if self.app.defaults["excellon_toolchangexy"] == '':
  1754. self.options['toolchangexy'] = "0.0, 0.0"
  1755. else:
  1756. coords_xy = [float(eval(coord)) for coord in self.app.defaults["excellon_toolchangexy"].split(",")]
  1757. if len(coords_xy) < 2:
  1758. self.app.inform.emit("[ERROR]The Toolchange X,Y field in Edit -> Preferences has to be "
  1759. "in the format (x, y) \nbut now there is only one value, not two. ")
  1760. return 'fail'
  1761. coords_xy[0] *= factor
  1762. coords_xy[1] *= factor
  1763. self.options['toolchangexy'] = "%f, %f" % (coords_xy[0], coords_xy[1])
  1764. if self.options['startz'] is not None:
  1765. self.options['startz'] = float(self.options['startz']) * factor
  1766. self.options['endz'] = float(self.options['endz']) * factor
  1767. def on_solid_cb_click(self, *args):
  1768. if self.muted_ui:
  1769. return
  1770. self.read_form_item('solid')
  1771. self.plot()
  1772. def on_plot_cb_click(self, *args):
  1773. if self.muted_ui:
  1774. return
  1775. self.plot()
  1776. self.read_form_item('plot')
  1777. self.ui_disconnect()
  1778. cb_flag = self.ui.plot_cb.isChecked()
  1779. for row in range(self.ui.tools_table.rowCount() - 2):
  1780. table_cb = self.ui.tools_table.cellWidget(row, 5)
  1781. if cb_flag:
  1782. table_cb.setChecked(True)
  1783. else:
  1784. table_cb.setChecked(False)
  1785. self.ui_connect()
  1786. def on_plot_cb_click_table(self):
  1787. # self.ui.cnc_tools_table.cellWidget(row, 2).widget().setCheckState(QtCore.Qt.Unchecked)
  1788. self.ui_disconnect()
  1789. # cw = self.sender()
  1790. # cw_index = self.ui.tools_table.indexAt(cw.pos())
  1791. # cw_row = cw_index.row()
  1792. check_row = 0
  1793. self.shapes.clear(update=True)
  1794. for tool_key in self.tools:
  1795. solid_geometry = self.tools[tool_key]['solid_geometry']
  1796. # find the geo_tool_table row associated with the tool_key
  1797. for row in range(self.ui.tools_table.rowCount()):
  1798. tool_item = int(self.ui.tools_table.item(row, 0).text())
  1799. if tool_item == int(tool_key):
  1800. check_row = row
  1801. break
  1802. if self.ui.tools_table.cellWidget(check_row, 5).isChecked():
  1803. self.options['plot'] = True
  1804. # self.plot_element(element=solid_geometry, visible=True)
  1805. # Plot excellon (All polygons?)
  1806. if self.options["solid"]:
  1807. for geo in solid_geometry:
  1808. self.add_shape(shape=geo, color='#750000BF', face_color='#C40000BF',
  1809. visible=self.options['plot'],
  1810. layer=2)
  1811. else:
  1812. for geo in solid_geometry:
  1813. self.add_shape(shape=geo.exterior, color='red', visible=self.options['plot'])
  1814. for ints in geo.interiors:
  1815. self.add_shape(shape=ints, color='green', visible=self.options['plot'])
  1816. self.shapes.redraw()
  1817. # make sure that the general plot is disabled if one of the row plot's are disabled and
  1818. # if all the row plot's are enabled also enable the general plot checkbox
  1819. cb_cnt = 0
  1820. total_row = self.ui.tools_table.rowCount()
  1821. for row in range(total_row - 2):
  1822. if self.ui.tools_table.cellWidget(row, 5).isChecked():
  1823. cb_cnt += 1
  1824. else:
  1825. cb_cnt -= 1
  1826. if cb_cnt < total_row - 2:
  1827. self.ui.plot_cb.setChecked(False)
  1828. else:
  1829. self.ui.plot_cb.setChecked(True)
  1830. self.ui_connect()
  1831. # def plot_element(self, element, color='red', visible=None, layer=None):
  1832. #
  1833. # visible = visible if visible else self.options['plot']
  1834. #
  1835. # try:
  1836. # for sub_el in element:
  1837. # self.plot_element(sub_el)
  1838. #
  1839. # except TypeError: # Element is not iterable...
  1840. # self.add_shape(shape=element, color=color, visible=visible, layer=0)
  1841. def plot(self):
  1842. # Does all the required setup and returns False
  1843. # if the 'ptint' option is set to False.
  1844. if not FlatCAMObj.plot(self):
  1845. return
  1846. try:
  1847. # Plot excellon (All polygons?)
  1848. if self.options["solid"]:
  1849. for tool in self.tools:
  1850. for geo in self.tools[tool]['solid_geometry']:
  1851. self.add_shape(shape=geo, color='#750000BF', face_color='#C40000BF', visible=self.options['plot'],
  1852. layer=2)
  1853. else:
  1854. for tool in self.tools:
  1855. for geo in self.tools[tool]['solid_geometry']:
  1856. self.add_shape(shape=geo.exterior, color='red', visible=self.options['plot'])
  1857. for ints in geo.interiors:
  1858. self.add_shape(shape=ints, color='green', visible=self.options['plot'])
  1859. self.shapes.redraw()
  1860. return
  1861. except (ObjectDeleted, AttributeError, KeyError):
  1862. self.shapes.clear(update=True)
  1863. # this stays for compatibility reasons, in case we try to open old projects
  1864. try:
  1865. _ = iter(self.solid_geometry)
  1866. except TypeError:
  1867. self.solid_geometry = [self.solid_geometry]
  1868. try:
  1869. # Plot excellon (All polygons?)
  1870. if self.options["solid"]:
  1871. for geo in self.solid_geometry:
  1872. self.add_shape(shape=geo, color='#750000BF', face_color='#C40000BF', visible=self.options['plot'],
  1873. layer=2)
  1874. else:
  1875. for geo in self.solid_geometry:
  1876. self.add_shape(shape=geo.exterior, color='red', visible=self.options['plot'])
  1877. for ints in geo.interiors:
  1878. self.add_shape(shape=ints, color='green', visible=self.options['plot'])
  1879. self.shapes.redraw()
  1880. except (ObjectDeleted, AttributeError):
  1881. self.shapes.clear(update=True)
  1882. # try:
  1883. # # Plot excellon (All polygons?)
  1884. # if self.options["solid"]:
  1885. # for geo_type in self.solid_geometry:
  1886. # if geo_type is not None:
  1887. # if type(geo_type) is dict:
  1888. # for tooldia in geo_type:
  1889. # geo_list = geo_type[tooldia]
  1890. # for geo in geo_list:
  1891. # self.add_shape(shape=geo, color='#750000BF', face_color='#C40000BF',
  1892. # visible=self.options['plot'],
  1893. # layer=2)
  1894. # else:
  1895. # self.add_shape(shape=geo_type, color='#750000BF', face_color='#C40000BF',
  1896. # visible=self.options['plot'],
  1897. # layer=2)
  1898. # else:
  1899. # for geo_type in self.solid_geometry:
  1900. # if geo_type is not None:
  1901. # if type(geo_type) is dict:
  1902. # for tooldia in geo_type:
  1903. # geo_list = geo_type[tooldia]
  1904. # for geo in geo_list:
  1905. # self.add_shape(shape=geo.exterior, color='red', visible=self.options['plot'])
  1906. # for ints in geo.interiors:
  1907. # self.add_shape(shape=ints, color='green', visible=self.options['plot'])
  1908. # else:
  1909. # self.add_shape(shape=geo_type.exterior, color='red', visible=self.options['plot'])
  1910. # for ints in geo_type.interiors:
  1911. # self.add_shape(shape=ints, color='green', visible=self.options['plot'])
  1912. # self.shapes.redraw()
  1913. # except (ObjectDeleted, AttributeError):
  1914. # self.shapes.clear(update=True)
  1915. class FlatCAMGeometry(FlatCAMObj, Geometry):
  1916. """
  1917. Geometric object not associated with a specific
  1918. format.
  1919. """
  1920. optionChanged = QtCore.pyqtSignal(str)
  1921. ui_type = GeometryObjectUI
  1922. @staticmethod
  1923. def merge(geo_list, geo_final, multigeo=None):
  1924. """
  1925. Merges the geometry of objects in grb_list into
  1926. the geometry of geo_final.
  1927. :param geo_list: List of FlatCAMGerber Objects to join.
  1928. :param geo_final: Destination FlatCAMGerber object.
  1929. :return: None
  1930. """
  1931. if geo_final.solid_geometry is None:
  1932. geo_final.solid_geometry = []
  1933. if type(geo_final.solid_geometry) is not list:
  1934. geo_final.solid_geometry = [geo_final.solid_geometry]
  1935. for geo in geo_list:
  1936. for option in geo.options:
  1937. if option is not 'name':
  1938. try:
  1939. geo_final.options[option] = geo.options[option]
  1940. except:
  1941. log.warning("Failed to copy option.", option)
  1942. # Expand lists
  1943. if type(geo) is list:
  1944. FlatCAMGeometry.merge(geo, geo_final)
  1945. # If not list, just append
  1946. else:
  1947. # merge solid_geometry, useful for singletool geometry, for multitool each is empty
  1948. if multigeo is None or multigeo == False:
  1949. geo_final.multigeo = False
  1950. try:
  1951. geo_final.solid_geometry.append(geo.solid_geometry)
  1952. except Exception as e:
  1953. log.debug("FlatCAMGeometry.merge() --> %s" % str(e))
  1954. else:
  1955. geo_final.multigeo = True
  1956. # if multigeo the solid_geometry is empty in the object attributes because it now lives in the
  1957. # tools object attribute, as a key value
  1958. geo_final.solid_geometry = []
  1959. # find the tool_uid maximum value in the geo_final
  1960. geo_final_uid_list = []
  1961. for key in geo_final.tools:
  1962. geo_final_uid_list.append(int(key))
  1963. try:
  1964. max_uid = max(geo_final_uid_list, key=int)
  1965. except ValueError:
  1966. max_uid = 0
  1967. # add and merge tools. If what we try to merge as Geometry is Excellon's and/or Gerber's then don't try
  1968. # to merge the obj.tools as it is likely there is none to merge.
  1969. if not isinstance(geo, FlatCAMGerber) and not isinstance(geo, FlatCAMExcellon):
  1970. for tool_uid in geo.tools:
  1971. max_uid += 1
  1972. geo_final.tools[max_uid] = copy.deepcopy(geo.tools[tool_uid])
  1973. @staticmethod
  1974. def get_pts(o):
  1975. """
  1976. Returns a list of all points in the object, where
  1977. the object can be a MultiPolygon, Polygon, Not a polygon, or a list
  1978. of such. Search is done recursively.
  1979. :param: geometric object
  1980. :return: List of points
  1981. :rtype: list
  1982. """
  1983. pts = []
  1984. ## Iterable: descend into each item.
  1985. try:
  1986. for subo in o:
  1987. pts += FlatCAMGeometry.get_pts(subo)
  1988. ## Non-iterable
  1989. except TypeError:
  1990. if o is not None:
  1991. if type(o) == MultiPolygon:
  1992. for poly in o:
  1993. pts += FlatCAMGeometry.get_pts(poly)
  1994. ## Descend into .exerior and .interiors
  1995. elif type(o) == Polygon:
  1996. pts += FlatCAMGeometry.get_pts(o.exterior)
  1997. for i in o.interiors:
  1998. pts += FlatCAMGeometry.get_pts(i)
  1999. elif type(o) == MultiLineString:
  2000. for line in o:
  2001. pts += FlatCAMGeometry.get_pts(line)
  2002. ## Has .coords: list them.
  2003. else:
  2004. pts += list(o.coords)
  2005. else:
  2006. return
  2007. return pts
  2008. def __init__(self, name):
  2009. FlatCAMObj.__init__(self, name)
  2010. Geometry.__init__(self, geo_steps_per_circle=int(self.app.defaults["geometry_circle_steps"]))
  2011. self.kind = "geometry"
  2012. self.options.update({
  2013. "plot": True,
  2014. "cutz": -0.002,
  2015. "vtipdia": 0.1,
  2016. "vtipangle": 30,
  2017. "travelz": 0.1,
  2018. "feedrate": 5.0,
  2019. "feedrate_z": 5.0,
  2020. "feedrate_rapid": 5.0,
  2021. "spindlespeed": None,
  2022. "dwell": True,
  2023. "dwelltime": 1000,
  2024. "multidepth": False,
  2025. "depthperpass": 0.002,
  2026. "extracut": False,
  2027. "endz": 2.0,
  2028. "toolchange": False,
  2029. "toolchangez": 1.0,
  2030. "toolchangexy": "0.0, 0.0",
  2031. "startz": None,
  2032. "ppname_g": 'default',
  2033. "z_pdepth": -0.02,
  2034. "feedrate_probe": 3.0,
  2035. })
  2036. if "cnctooldia" not in self.options:
  2037. self.options["cnctooldia"] = self.app.defaults["geometry_cnctooldia"]
  2038. self.options["startz"] = self.app.defaults["geometry_startz"]
  2039. # this will hold the tool unique ID that is useful when having multiple tools with same diameter
  2040. self.tooluid = 0
  2041. '''
  2042. self.tools = {}
  2043. This is a dictionary. Each dict key is associated with a tool used in geo_tools_table. The key is the
  2044. tool_id of the tools and the value is another dict that will hold the data under the following form:
  2045. {tooluid: {
  2046. 'tooldia': 1,
  2047. 'offset': 'Path',
  2048. 'offset_value': 0.0
  2049. 'type': 'Rough',
  2050. 'tool_type': 'C1',
  2051. 'data': self.default_tool_data
  2052. 'solid_geometry': []
  2053. }
  2054. }
  2055. '''
  2056. self.tools = {}
  2057. # this dict is to store those elements (tools) of self.tools that are selected in the self.geo_tools_table
  2058. # those elements are the ones used for generating GCode
  2059. self.sel_tools = {}
  2060. self.offset_item_options = ["Path", "In", "Out", "Custom"]
  2061. self.type_item_options = ["Iso", "Rough", "Finish"]
  2062. self.tool_type_item_options = ["C1", "C2", "C3", "C4", "B", "V"]
  2063. # flag to store if the V-Shape tool is selected in self.ui.geo_tools_table
  2064. self.v_tool_type = None
  2065. self.multigeo = False
  2066. # Attributes to be included in serialization
  2067. # Always append to it because it carries contents
  2068. # from predecessors.
  2069. self.ser_attrs += ['options', 'kind', 'tools', 'multigeo']
  2070. def build_ui(self):
  2071. self.ui_disconnect()
  2072. FlatCAMObj.build_ui(self)
  2073. offset = 0
  2074. tool_idx = 0
  2075. n = len(self.tools)
  2076. self.ui.geo_tools_table.setRowCount(n)
  2077. for tooluid_key, tooluid_value in self.tools.items():
  2078. tool_idx += 1
  2079. row_no = tool_idx - 1
  2080. id = QtWidgets.QTableWidgetItem('%d' % int(tool_idx))
  2081. id.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  2082. self.ui.geo_tools_table.setItem(row_no, 0, id) # Tool name/id
  2083. # Make sure that the tool diameter when in MM is with no more than 2 decimals.
  2084. # There are no tool bits in MM with more than 3 decimals diameter.
  2085. # For INCH the decimals should be no more than 3. There are no tools under 10mils.
  2086. if self.units == 'MM':
  2087. dia_item = QtWidgets.QTableWidgetItem('%.2f' % float(tooluid_value['tooldia']))
  2088. else:
  2089. dia_item = QtWidgets.QTableWidgetItem('%.4f' % float(tooluid_value['tooldia']))
  2090. dia_item.setFlags(QtCore.Qt.ItemIsEnabled)
  2091. offset_item = QtWidgets.QComboBox()
  2092. for item in self.offset_item_options:
  2093. offset_item.addItem(item)
  2094. offset_item.setStyleSheet('background-color: rgb(255,255,255)')
  2095. idx = offset_item.findText(tooluid_value['offset'])
  2096. offset_item.setCurrentIndex(idx)
  2097. type_item = QtWidgets.QComboBox()
  2098. for item in self.type_item_options:
  2099. type_item.addItem(item)
  2100. type_item.setStyleSheet('background-color: rgb(255,255,255)')
  2101. idx = type_item.findText(tooluid_value['type'])
  2102. type_item.setCurrentIndex(idx)
  2103. tool_type_item = QtWidgets.QComboBox()
  2104. for item in self.tool_type_item_options:
  2105. tool_type_item.addItem(item)
  2106. tool_type_item.setStyleSheet('background-color: rgb(255,255,255)')
  2107. idx = tool_type_item.findText(tooluid_value['tool_type'])
  2108. tool_type_item.setCurrentIndex(idx)
  2109. tool_uid_item = QtWidgets.QTableWidgetItem(str(tooluid_key))
  2110. plot_item = FCCheckBox()
  2111. plot_item.setLayoutDirection(QtCore.Qt.RightToLeft)
  2112. if self.ui.plot_cb.isChecked():
  2113. plot_item.setChecked(True)
  2114. self.ui.geo_tools_table.setItem(row_no, 1, dia_item) # Diameter
  2115. self.ui.geo_tools_table.setCellWidget(row_no, 2, offset_item)
  2116. self.ui.geo_tools_table.setCellWidget(row_no, 3, type_item)
  2117. self.ui.geo_tools_table.setCellWidget(row_no, 4, tool_type_item)
  2118. ### REMEMBER: THIS COLUMN IS HIDDEN IN OBJECTUI.PY ###
  2119. self.ui.geo_tools_table.setItem(row_no, 5, tool_uid_item) # Tool unique ID
  2120. self.ui.geo_tools_table.setCellWidget(row_no, 6, plot_item)
  2121. try:
  2122. self.ui.tool_offset_entry.set_value(tooluid_value['offset_value'])
  2123. except:
  2124. log.debug("build_ui() --> Could not set the 'offset_value' key in self.tools")
  2125. # make the diameter column editable
  2126. for row in range(tool_idx):
  2127. self.ui.geo_tools_table.item(row, 1).setFlags(QtCore.Qt.ItemIsSelectable |
  2128. QtCore.Qt.ItemIsEditable |
  2129. QtCore.Qt.ItemIsEnabled)
  2130. # sort the tool diameter column
  2131. # self.ui.geo_tools_table.sortItems(1)
  2132. # all the tools are selected by default
  2133. # self.ui.geo_tools_table.selectColumn(0)
  2134. self.ui.geo_tools_table.resizeColumnsToContents()
  2135. self.ui.geo_tools_table.resizeRowsToContents()
  2136. vertical_header = self.ui.geo_tools_table.verticalHeader()
  2137. # vertical_header.setSectionResizeMode(QtWidgets.QHeaderView.ResizeToContents)
  2138. vertical_header.hide()
  2139. self.ui.geo_tools_table.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  2140. horizontal_header = self.ui.geo_tools_table.horizontalHeader()
  2141. horizontal_header.setMinimumSectionSize(10)
  2142. horizontal_header.setDefaultSectionSize(70)
  2143. horizontal_header.setSectionResizeMode(0, QtWidgets.QHeaderView.Fixed)
  2144. horizontal_header.resizeSection(0, 20)
  2145. horizontal_header.setSectionResizeMode(1, QtWidgets.QHeaderView.Stretch)
  2146. # horizontal_header.setColumnWidth(2, QtWidgets.QHeaderView.ResizeToContents)
  2147. horizontal_header.setSectionResizeMode(3, QtWidgets.QHeaderView.ResizeToContents)
  2148. horizontal_header.setSectionResizeMode(4, QtWidgets.QHeaderView.Fixed)
  2149. horizontal_header.resizeSection(4, 40)
  2150. horizontal_header.setSectionResizeMode(6, QtWidgets.QHeaderView.Fixed)
  2151. horizontal_header.resizeSection(4, 17)
  2152. # horizontal_header.setStretchLastSection(True)
  2153. self.ui.geo_tools_table.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  2154. self.ui.geo_tools_table.setColumnWidth(0, 20)
  2155. self.ui.geo_tools_table.setColumnWidth(4, 40)
  2156. self.ui.geo_tools_table.setColumnWidth(6, 17)
  2157. # self.ui.geo_tools_table.setSortingEnabled(True)
  2158. self.ui.geo_tools_table.setMinimumHeight(self.ui.geo_tools_table.getHeight())
  2159. self.ui.geo_tools_table.setMaximumHeight(self.ui.geo_tools_table.getHeight())
  2160. # update UI for all rows - useful after units conversion but only if there is at least one row
  2161. row_cnt = self.ui.geo_tools_table.rowCount()
  2162. if row_cnt > 0:
  2163. for r in range(row_cnt):
  2164. self.update_ui(r)
  2165. # select only the first tool / row
  2166. selected_row = 0
  2167. try:
  2168. self.select_tools_table_row(selected_row, clearsel=True)
  2169. # update the Geometry UI
  2170. self.update_ui()
  2171. except Exception as e:
  2172. # when the tools table is empty there will be this error but once the table is populated it will go away
  2173. log.debug(str(e))
  2174. # disable the Plot column in Tool Table if the geometry is SingleGeo as it is not needed
  2175. # and can create some problems
  2176. if self.multigeo is False:
  2177. self.ui.geo_tools_table.setColumnHidden(6, True)
  2178. else:
  2179. self.ui.geo_tools_table.setColumnHidden(6, False)
  2180. self.set_tool_offset_visibility(selected_row)
  2181. self.ui_connect()
  2182. def set_ui(self, ui):
  2183. FlatCAMObj.set_ui(self, ui)
  2184. log.debug("FlatCAMGeometry.set_ui()")
  2185. assert isinstance(self.ui, GeometryObjectUI), \
  2186. "Expected a GeometryObjectUI, got %s" % type(self.ui)
  2187. # populate postprocessor names in the combobox
  2188. for name in list(self.app.postprocessors.keys()):
  2189. self.ui.pp_geometry_name_cb.addItem(name)
  2190. self.form_fields.update({
  2191. "plot": self.ui.plot_cb,
  2192. "cutz": self.ui.cutz_entry,
  2193. "vtipdia": self.ui.tipdia_entry,
  2194. "vtipangle": self.ui.tipangle_entry,
  2195. "travelz": self.ui.travelz_entry,
  2196. "feedrate": self.ui.cncfeedrate_entry,
  2197. "feedrate_z": self.ui.cncplunge_entry,
  2198. "feedrate_rapid": self.ui.cncfeedrate_rapid_entry,
  2199. "spindlespeed": self.ui.cncspindlespeed_entry,
  2200. "dwell": self.ui.dwell_cb,
  2201. "dwelltime": self.ui.dwelltime_entry,
  2202. "multidepth": self.ui.mpass_cb,
  2203. "ppname_g": self.ui.pp_geometry_name_cb,
  2204. "z_pdepth": self.ui.pdepth_entry,
  2205. "feedrate_probe": self.ui.feedrate_probe_entry,
  2206. "depthperpass": self.ui.maxdepth_entry,
  2207. "extracut": self.ui.extracut_cb,
  2208. "toolchange": self.ui.toolchangeg_cb,
  2209. "toolchangez": self.ui.toolchangez_entry,
  2210. "endz": self.ui.gendz_entry,
  2211. })
  2212. # Fill form fields only on object create
  2213. self.to_form()
  2214. self.ui.tipdialabel.hide()
  2215. self.ui.tipdia_entry.hide()
  2216. self.ui.tipanglelabel.hide()
  2217. self.ui.tipangle_entry.hide()
  2218. self.ui.cutz_entry.setDisabled(False)
  2219. # store here the default data for Geometry Data
  2220. self.default_data = {}
  2221. self.default_data.update({
  2222. "name": None,
  2223. "plot": None,
  2224. "cutz": None,
  2225. "vtipdia": None,
  2226. "vtipangle": None,
  2227. "travelz": None,
  2228. "feedrate": None,
  2229. "feedrate_z": None,
  2230. "feedrate_rapid": None,
  2231. "dwell": None,
  2232. "dwelltime": None,
  2233. "multidepth": None,
  2234. "ppname_g": None,
  2235. "depthperpass": None,
  2236. "extracut": None,
  2237. "toolchange": None,
  2238. "toolchangez": None,
  2239. "endz": None,
  2240. "spindlespeed": None,
  2241. "toolchangexy": None,
  2242. "startz": None
  2243. })
  2244. # fill in self.default_data values from self.options
  2245. for def_key in self.default_data:
  2246. for opt_key, opt_val in self.options.items():
  2247. if def_key == opt_key:
  2248. self.default_data[def_key] = opt_val
  2249. self.tooluid += 1
  2250. if not self.tools:
  2251. self.tools.update({
  2252. self.tooluid: {
  2253. 'tooldia': float(self.options["cnctooldia"]),
  2254. 'offset': 'Path',
  2255. 'offset_value': 0.0,
  2256. 'type': 'Rough',
  2257. 'tool_type': 'C1',
  2258. 'data': self.default_data,
  2259. 'solid_geometry': self.solid_geometry
  2260. }
  2261. })
  2262. else:
  2263. # if self.tools is not empty then it can safely be assumed that it comes from an opened project.
  2264. # Because of the serialization the self.tools list on project save, the dict keys (members of self.tools
  2265. # are each a dict) are turned into strings so we rebuild the self.tools elements so the keys are
  2266. # again float type; dict's don't like having keys changed when iterated through therefore the need for the
  2267. # following convoluted way of changing the keys from string to float type
  2268. temp_tools = {}
  2269. new_key = 0.0
  2270. for tooluid_key in self.tools:
  2271. val = copy.deepcopy(self.tools[tooluid_key])
  2272. new_key = copy.deepcopy(int(tooluid_key))
  2273. temp_tools[new_key] = val
  2274. self.tools.clear()
  2275. self.tools = copy.deepcopy(temp_tools)
  2276. self.ui.tool_offset_entry.hide()
  2277. self.ui.tool_offset_lbl.hide()
  2278. # used to store the state of the mpass_cb if the selected postproc for geometry is hpgl
  2279. self.old_pp_state = self.default_data['multidepth']
  2280. self.old_toolchangeg_state = self.default_data['toolchange']
  2281. if not isinstance(self.ui, GeometryObjectUI):
  2282. log.debug("Expected a GeometryObjectUI, got %s" % type(self.ui))
  2283. return
  2284. self.ui.geo_tools_table.setupContextMenu()
  2285. self.ui.geo_tools_table.addContextMenu(
  2286. "Copy", self.on_tool_copy, icon=QtGui.QIcon("share/copy16.png"))
  2287. self.ui.geo_tools_table.addContextMenu(
  2288. "Delete", lambda: self.on_tool_delete(all=None), icon=QtGui.QIcon("share/delete32.png"))
  2289. # Show/Hide Advanced Options
  2290. if self.app.defaults["global_advanced"] is False:
  2291. self.ui.level.setText('<span style="color:green;"><b>BASIC Mode</b></span>')
  2292. self.ui.geo_tools_table.setColumnHidden(2, True)
  2293. self.ui.geo_tools_table.setColumnHidden(3, True)
  2294. self.ui.geo_tools_table.setColumnHidden(4, True)
  2295. self.ui.addtool_entry_lbl.hide()
  2296. self.ui.addtool_entry.hide()
  2297. self.ui.addtool_btn.hide()
  2298. self.ui.copytool_btn.hide()
  2299. self.ui.deltool_btn.hide()
  2300. self.ui.endzlabel.hide()
  2301. self.ui.gendz_entry.hide()
  2302. self.ui.fr_rapidlabel.hide()
  2303. self.ui.cncfeedrate_rapid_entry.hide()
  2304. self.ui.extracut_cb.hide()
  2305. self.ui.pdepth_label.hide()
  2306. self.ui.pdepth_entry.hide()
  2307. self.ui.feedrate_probe_label.hide()
  2308. self.ui.feedrate_probe_entry.hide()
  2309. else:
  2310. self.ui.level.setText('<span style="color:red;"><b>ADVANCED Mode</b></span>')
  2311. self.ui.plot_cb.stateChanged.connect(self.on_plot_cb_click)
  2312. self.ui.generate_cnc_button.clicked.connect(self.on_generatecnc_button_click)
  2313. self.ui.paint_tool_button.clicked.connect(self.app.paint_tool.run)
  2314. self.ui.pp_geometry_name_cb.activated.connect(self.on_pp_changed)
  2315. def set_tool_offset_visibility(self, current_row):
  2316. if current_row is None:
  2317. return
  2318. try:
  2319. tool_offset = self.ui.geo_tools_table.cellWidget(current_row, 2)
  2320. if tool_offset is not None:
  2321. tool_offset_txt = tool_offset.currentText()
  2322. if tool_offset_txt == 'Custom':
  2323. self.ui.tool_offset_entry.show()
  2324. self.ui.tool_offset_lbl.show()
  2325. else:
  2326. self.ui.tool_offset_entry.hide()
  2327. self.ui.tool_offset_lbl.hide()
  2328. except Exception as e:
  2329. log.debug("set_tool_offset_visibility() --> " + str(e))
  2330. return
  2331. def on_offset_value_edited(self):
  2332. '''
  2333. This will save the offset_value into self.tools storage whenever the oofset value is edited
  2334. :return:
  2335. '''
  2336. for current_row in self.ui.geo_tools_table.selectedItems():
  2337. # sometime the header get selected and it has row number -1
  2338. # we don't want to do anything with the header :)
  2339. if current_row.row() < 0:
  2340. continue
  2341. tool_uid = int(self.ui.geo_tools_table.item(current_row.row(), 5).text())
  2342. self.set_tool_offset_visibility(current_row.row())
  2343. for tooluid_key, tooluid_value in self.tools.items():
  2344. if int(tooluid_key) == tool_uid:
  2345. try:
  2346. tooluid_value['offset_value'] = float(self.ui.tool_offset_entry.get_value())
  2347. except ValueError:
  2348. # try to convert comma to decimal point. if it's still not working error message and return
  2349. try:
  2350. tooluid_value['offset_value'] = float(
  2351. self.ui.tool_offset_entry.get_value().replace(',', '.')
  2352. )
  2353. except ValueError:
  2354. self.app.inform.emit("[ERROR_NOTCL]Wrong value format entered, "
  2355. "use a number.")
  2356. return
  2357. def ui_connect(self):
  2358. # on any change to the widgets that matter it will be called self.gui_form_to_storage which will save the
  2359. # changes in geometry UI
  2360. for i in range(self.ui.grid3.count()):
  2361. try:
  2362. # works for CheckBoxes
  2363. self.ui.grid3.itemAt(i).widget().stateChanged.connect(self.gui_form_to_storage)
  2364. except:
  2365. # works for ComboBoxes
  2366. try:
  2367. self.ui.grid3.itemAt(i).widget().currentIndexChanged.connect(self.gui_form_to_storage)
  2368. except:
  2369. # works for Entry
  2370. try:
  2371. self.ui.grid3.itemAt(i).widget().editingFinished.connect(self.gui_form_to_storage)
  2372. except:
  2373. pass
  2374. for row in range(self.ui.geo_tools_table.rowCount()):
  2375. for col in [2, 3, 4]:
  2376. self.ui.geo_tools_table.cellWidget(row, col).currentIndexChanged.connect(
  2377. self.on_tooltable_cellwidget_change)
  2378. # I use lambda's because the connected functions have parameters that could be used in certain scenarios
  2379. self.ui.addtool_btn.clicked.connect(lambda: self.on_tool_add())
  2380. self.ui.copytool_btn.clicked.connect(lambda: self.on_tool_copy())
  2381. self.ui.deltool_btn.clicked.connect(lambda: self.on_tool_delete())
  2382. self.ui.geo_tools_table.currentItemChanged.connect(self.on_row_selection_change)
  2383. self.ui.geo_tools_table.itemChanged.connect(self.on_tool_edit)
  2384. self.ui.tool_offset_entry.editingFinished.connect(self.on_offset_value_edited)
  2385. for row in range(self.ui.geo_tools_table.rowCount()):
  2386. self.ui.geo_tools_table.cellWidget(row, 6).clicked.connect(self.on_plot_cb_click_table)
  2387. self.ui.plot_cb.stateChanged.connect(self.on_plot_cb_click)
  2388. def ui_disconnect(self):
  2389. try:
  2390. # on any change to the widgets that matter it will be called self.gui_form_to_storage which will save the
  2391. # changes in geometry UI
  2392. for i in range(self.ui.grid3.count()):
  2393. if isinstance(self.ui.grid3.itemAt(i).widget(), FCCheckBox):
  2394. self.ui.grid3.itemAt(i).widget().stateChanged.disconnect()
  2395. if isinstance(self.ui.grid3.itemAt(i).widget(), FCComboBox):
  2396. self.ui.grid3.itemAt(i).widget().currentIndexChanged.disconnect()
  2397. if isinstance(self.ui.grid3.itemAt(i).widget(), LengthEntry) or \
  2398. isinstance(self.ui.grid3.itemAt(i), IntEntry) or \
  2399. isinstance(self.ui.grid3.itemAt(i), FCEntry):
  2400. self.ui.grid3.itemAt(i).widget().editingFinished.disconnect()
  2401. except:
  2402. pass
  2403. try:
  2404. for row in range(self.ui.geo_tools_table.rowCount()):
  2405. for col in [2, 3, 4]:
  2406. self.ui.geo_tools_table.cellWidget(row, col).currentIndexChanged.disconnect()
  2407. except:
  2408. pass
  2409. # I use lambda's because the connected functions have parameters that could be used in certain scenarios
  2410. try:
  2411. self.ui.addtool_btn.clicked.disconnect()
  2412. except:
  2413. pass
  2414. try:
  2415. self.ui.copytool_btn.clicked.disconnect()
  2416. except:
  2417. pass
  2418. try:
  2419. self.ui.deltool_btn.clicked.disconnect()
  2420. except:
  2421. pass
  2422. try:
  2423. self.ui.geo_tools_table.currentItemChanged.disconnect()
  2424. except:
  2425. pass
  2426. try:
  2427. self.ui.geo_tools_table.itemChanged.disconnect()
  2428. except:
  2429. pass
  2430. try:
  2431. self.ui.tool_offset_entry.editingFinished.disconnect()
  2432. except:
  2433. pass
  2434. for row in range(self.ui.geo_tools_table.rowCount()):
  2435. try:
  2436. self.ui.geo_tools_table.cellWidget(row, 6).clicked.disconnect()
  2437. except:
  2438. pass
  2439. try:
  2440. self.ui.plot_cb.stateChanged.disconnect()
  2441. except:
  2442. pass
  2443. def on_tool_add(self, dia=None):
  2444. self.ui_disconnect()
  2445. last_offset = None
  2446. last_offset_value = None
  2447. last_type = None
  2448. last_tool_type = None
  2449. last_data = None
  2450. last_solid_geometry = []
  2451. # if a Tool diameter entered is a char instead a number the final message of Tool adding is changed
  2452. # because the Default value for Tool is used.
  2453. change_message = False
  2454. if dia is not None:
  2455. tooldia = dia
  2456. else:
  2457. try:
  2458. tooldia = float(self.ui.addtool_entry.get_value())
  2459. except ValueError:
  2460. # try to convert comma to decimal point. if it's still not working error message and return
  2461. try:
  2462. tooldia = float(self.ui.addtool_entry.get_value().replace(',', '.'))
  2463. except ValueError:
  2464. change_message = True
  2465. tooldia = float(self.app.defaults["geometry_cnctooldia"])
  2466. if tooldia is None:
  2467. self.build_ui()
  2468. self.app.inform.emit("[ERROR_NOTCL] Please enter the desired tool diameter in Float format.")
  2469. return
  2470. # construct a list of all 'tooluid' in the self.tools
  2471. tool_uid_list = []
  2472. for tooluid_key in self.tools:
  2473. tool_uid_item = int(tooluid_key)
  2474. tool_uid_list.append(tool_uid_item)
  2475. # find maximum from the temp_uid, add 1 and this is the new 'tooluid'
  2476. if not tool_uid_list:
  2477. max_uid = 0
  2478. else:
  2479. max_uid = max(tool_uid_list)
  2480. self.tooluid = max_uid + 1
  2481. if self.units == 'IN':
  2482. tooldia = float('%.4f' % tooldia)
  2483. else:
  2484. tooldia = float('%.2f' % tooldia)
  2485. # here we actually add the new tool; if there is no tool in the tool table we add a tool with default data
  2486. # otherwise we add a tool with data copied from last tool
  2487. if not self.tools:
  2488. self.tools.update({
  2489. self.tooluid: {
  2490. 'tooldia': tooldia,
  2491. 'offset': 'Path',
  2492. 'offset_value': 0.0,
  2493. 'type': 'Rough',
  2494. 'tool_type': 'C1',
  2495. 'data': copy.deepcopy(self.default_data),
  2496. 'solid_geometry': self.solid_geometry
  2497. }
  2498. })
  2499. else:
  2500. # print("LAST", self.tools[maxuid])
  2501. last_data = self.tools[max_uid]['data']
  2502. last_offset = self.tools[max_uid]['offset']
  2503. last_offset_value = self.tools[max_uid]['offset_value']
  2504. last_type = self.tools[max_uid]['type']
  2505. last_tool_type = self.tools[max_uid]['tool_type']
  2506. last_solid_geometry = self.tools[max_uid]['solid_geometry']
  2507. # if previous geometry was empty (it may happen for the first tool added)
  2508. # then copy the object.solid_geometry
  2509. if not last_solid_geometry:
  2510. last_solid_geometry = self.solid_geometry
  2511. self.tools.update({
  2512. self.tooluid: {
  2513. 'tooldia': tooldia,
  2514. 'offset': last_offset,
  2515. 'offset_value': last_offset_value,
  2516. 'type': last_type,
  2517. 'tool_type': last_tool_type,
  2518. 'data': copy.deepcopy(last_data),
  2519. 'solid_geometry': copy.deepcopy(last_solid_geometry)
  2520. }
  2521. })
  2522. # print("CURRENT", self.tools[-1])
  2523. self.ui.tool_offset_entry.hide()
  2524. self.ui.tool_offset_lbl.hide()
  2525. # we do this HACK to make sure the tools attribute to be serialized is updated in the self.ser_attrs list
  2526. try:
  2527. self.ser_attrs.remove('tools')
  2528. except:
  2529. pass
  2530. self.ser_attrs.append('tools')
  2531. if change_message is False:
  2532. self.app.inform.emit("[success] Tool added in Tool Table.")
  2533. else:
  2534. change_message = False
  2535. self.app.inform.emit("[ERROR_NOTCL]Default Tool added. Wrong value format entered.")
  2536. self.build_ui()
  2537. def on_tool_copy(self, all=None):
  2538. self.ui_disconnect()
  2539. # find the tool_uid maximum value in the self.tools
  2540. uid_list = []
  2541. for key in self.tools:
  2542. uid_list.append(int(key))
  2543. try:
  2544. max_uid = max(uid_list, key=int)
  2545. except ValueError:
  2546. max_uid = 0
  2547. if all is None:
  2548. if self.ui.geo_tools_table.selectedItems():
  2549. for current_row in self.ui.geo_tools_table.selectedItems():
  2550. # sometime the header get selected and it has row number -1
  2551. # we don't want to do anything with the header :)
  2552. if current_row.row() < 0:
  2553. continue
  2554. try:
  2555. tooluid_copy = int(self.ui.geo_tools_table.item(current_row.row(), 5).text())
  2556. self.set_tool_offset_visibility(current_row.row())
  2557. max_uid += 1
  2558. self.tools[int(max_uid)] = copy.deepcopy(self.tools[tooluid_copy])
  2559. except AttributeError:
  2560. self.app.inform.emit("[WARNING_NOTCL]Failed. Select a tool to copy.")
  2561. self.build_ui()
  2562. return
  2563. except Exception as e:
  2564. log.debug("on_tool_copy() --> " + str(e))
  2565. # deselect the table
  2566. # self.ui.geo_tools_table.clearSelection()
  2567. else:
  2568. self.app.inform.emit("[WARNING_NOTCL]Failed. Select a tool to copy.")
  2569. self.build_ui()
  2570. return
  2571. else:
  2572. # we copy all tools in geo_tools_table
  2573. try:
  2574. temp_tools = copy.deepcopy(self.tools)
  2575. max_uid += 1
  2576. for tooluid in temp_tools:
  2577. self.tools[int(max_uid)] = copy.deepcopy(temp_tools[tooluid])
  2578. temp_tools.clear()
  2579. except Exception as e:
  2580. log.debug("on_tool_copy() --> " + str(e))
  2581. # if there are no more tools in geo tools table then hide the tool offset
  2582. if not self.tools:
  2583. self.ui.tool_offset_entry.hide()
  2584. self.ui.tool_offset_lbl.hide()
  2585. # we do this HACK to make sure the tools attribute to be serialized is updated in the self.ser_attrs list
  2586. try:
  2587. self.ser_attrs.remove('tools')
  2588. except:
  2589. pass
  2590. self.ser_attrs.append('tools')
  2591. self.build_ui()
  2592. self.app.inform.emit("[success] Tool was copied in Tool Table.")
  2593. def on_tool_edit(self, current_item):
  2594. self.ui_disconnect()
  2595. current_row = current_item.row()
  2596. try:
  2597. d = float(self.ui.geo_tools_table.item(current_row, 1).text())
  2598. except ValueError:
  2599. # try to convert comma to decimal point. if it's still not working error message and return
  2600. try:
  2601. d = float(self.ui.geo_tools_table.item(current_row, 1).text().replace(',', '.'))
  2602. except ValueError:
  2603. self.app.inform.emit("[ERROR_NOTCL]Wrong value format entered, "
  2604. "use a number.")
  2605. return
  2606. tool_dia = float('%.4f' % d)
  2607. tooluid = int(self.ui.geo_tools_table.item(current_row, 5).text())
  2608. self.tools[tooluid]['tooldia'] = tool_dia
  2609. try:
  2610. self.ser_attrs.remove('tools')
  2611. self.ser_attrs.append('tools')
  2612. except:
  2613. pass
  2614. self.app.inform.emit("[success] Tool was edited in Tool Table.")
  2615. self.build_ui()
  2616. def on_tool_delete(self, all=None):
  2617. self.ui_disconnect()
  2618. if all is None:
  2619. if self.ui.geo_tools_table.selectedItems():
  2620. for current_row in self.ui.geo_tools_table.selectedItems():
  2621. # sometime the header get selected and it has row number -1
  2622. # we don't want to do anything with the header :)
  2623. if current_row.row() < 0:
  2624. continue
  2625. try:
  2626. tooluid_del = int(self.ui.geo_tools_table.item(current_row.row(), 5).text())
  2627. self.set_tool_offset_visibility(current_row.row())
  2628. temp_tools = copy.deepcopy(self.tools)
  2629. for tooluid_key in self.tools:
  2630. if int(tooluid_key) == tooluid_del:
  2631. # if the self.tools has only one tool and we delete it then we move the solid_geometry
  2632. # as a property of the object otherwise there will be nothing to hold it
  2633. if len(self.tools) == 1:
  2634. self.solid_geometry = copy.deepcopy(self.tools[tooluid_key]['solid_geometry'])
  2635. temp_tools.pop(tooluid_del, None)
  2636. self.tools = copy.deepcopy(temp_tools)
  2637. temp_tools.clear()
  2638. except AttributeError:
  2639. self.app.inform.emit("[WARNING_NOTCL]Failed. Select a tool to delete.")
  2640. self.build_ui()
  2641. return
  2642. except Exception as e:
  2643. log.debug("on_tool_delete() --> " + str(e))
  2644. # deselect the table
  2645. # self.ui.geo_tools_table.clearSelection()
  2646. else:
  2647. self.app.inform.emit("[WARNING_NOTCL]Failed. Select a tool to delete.")
  2648. self.build_ui()
  2649. return
  2650. else:
  2651. # we delete all tools in geo_tools_table
  2652. self.tools.clear()
  2653. self.app.plot_all()
  2654. # if there are no more tools in geo tools table then hide the tool offset
  2655. if not self.tools:
  2656. self.ui.tool_offset_entry.hide()
  2657. self.ui.tool_offset_lbl.hide()
  2658. # we do this HACK to make sure the tools attribute to be serialized is updated in the self.ser_attrs list
  2659. try:
  2660. self.ser_attrs.remove('tools')
  2661. except:
  2662. pass
  2663. self.ser_attrs.append('tools')
  2664. self.build_ui()
  2665. self.app.inform.emit("[success] Tool was deleted in Tool Table.")
  2666. obj_active = self.app.collection.get_active()
  2667. # if the object was MultiGeo and now it has no tool at all (therefore no geometry)
  2668. # we make it back SingleGeo
  2669. if self.ui.geo_tools_table.rowCount() <= 0:
  2670. obj_active.multigeo = False
  2671. obj_active.options['xmin'] = 0
  2672. obj_active.options['ymin'] = 0
  2673. obj_active.options['xmax'] = 0
  2674. obj_active.options['ymax'] = 0
  2675. if obj_active.multigeo is True:
  2676. try:
  2677. xmin, ymin, xmax, ymax = obj_active.bounds()
  2678. obj_active.options['xmin'] = xmin
  2679. obj_active.options['ymin'] = ymin
  2680. obj_active.options['xmax'] = xmax
  2681. obj_active.options['ymax'] = ymax
  2682. except:
  2683. obj_active.options['xmin'] = 0
  2684. obj_active.options['ymin'] = 0
  2685. obj_active.options['xmax'] = 0
  2686. obj_active.options['ymax'] = 0
  2687. def on_row_selection_change(self):
  2688. self.update_ui()
  2689. def update_ui(self, row=None):
  2690. self.ui_disconnect()
  2691. if row is None:
  2692. try:
  2693. current_row = self.ui.geo_tools_table.currentRow()
  2694. except:
  2695. current_row = 0
  2696. else:
  2697. current_row = row
  2698. if current_row < 0:
  2699. current_row = 0
  2700. self.set_tool_offset_visibility(current_row)
  2701. # populate the form with the data from the tool associated with the row parameter
  2702. try:
  2703. tooluid = int(self.ui.geo_tools_table.item(current_row, 5).text())
  2704. except Exception as e:
  2705. log.debug("Tool missing. Add a tool in Geo Tool Table. %s" % str(e))
  2706. return
  2707. # update the form with the V-Shape fields if V-Shape selected in the geo_tool_table
  2708. # also modify the Cut Z form entry to reflect the calculated Cut Z from values got from V-Shape Fields
  2709. try:
  2710. tool_type_txt = self.ui.geo_tools_table.cellWidget(current_row, 4).currentText()
  2711. self.ui_update_v_shape(tool_type_txt=tool_type_txt)
  2712. except Exception as e:
  2713. log.debug("Tool missing. Add a tool in Geo Tool Table. %s" % str(e))
  2714. return
  2715. try:
  2716. # set the form with data from the newly selected tool
  2717. for tooluid_key, tooluid_value in self.tools.items():
  2718. if int(tooluid_key) == tooluid:
  2719. for key, value in tooluid_value.items():
  2720. if key == 'data':
  2721. form_value_storage = tooluid_value[key]
  2722. self.update_form(form_value_storage)
  2723. if key == 'offset_value':
  2724. # update the offset value in the entry even if the entry is hidden
  2725. self.ui.tool_offset_entry.set_value(tooluid_value[key])
  2726. if key == 'tool_type' and value == 'V':
  2727. self.update_cutz()
  2728. except Exception as e:
  2729. log.debug("FlatCAMObj ---> update_ui() " + str(e))
  2730. self.ui_connect()
  2731. def ui_update_v_shape(self, tool_type_txt):
  2732. if tool_type_txt == 'V':
  2733. self.ui.tipdialabel.show()
  2734. self.ui.tipdia_entry.show()
  2735. self.ui.tipanglelabel.show()
  2736. self.ui.tipangle_entry.show()
  2737. self.ui.cutz_entry.setDisabled(True)
  2738. self.update_cutz()
  2739. else:
  2740. self.ui.tipdialabel.hide()
  2741. self.ui.tipdia_entry.hide()
  2742. self.ui.tipanglelabel.hide()
  2743. self.ui.tipangle_entry.hide()
  2744. self.ui.cutz_entry.setDisabled(False)
  2745. def update_cutz(self):
  2746. try:
  2747. vdia = float(self.ui.tipdia_entry.get_value())
  2748. except ValueError:
  2749. # try to convert comma to decimal point. if it's still not working error message and return
  2750. try:
  2751. vdia = float(self.ui.tipdia_entry.get_value().replace(',', '.'))
  2752. except ValueError:
  2753. self.app.inform.emit("[ERROR_NOTCL]Wrong value format entered, "
  2754. "use a number.")
  2755. return
  2756. try:
  2757. half_vangle = float(self.ui.tipangle_entry.get_value()) / 2
  2758. except ValueError:
  2759. # try to convert comma to decimal point. if it's still not working error message and return
  2760. try:
  2761. half_vangle = float(self.ui.tipangle_entry.get_value().replace(',', '.')) / 2
  2762. except ValueError:
  2763. self.app.inform.emit("[ERROR_NOTCL]Wrong value format entered, "
  2764. "use a number.")
  2765. return
  2766. row = self.ui.geo_tools_table.currentRow()
  2767. tool_uid = int(self.ui.geo_tools_table.item(row, 5).text())
  2768. tooldia = float(self.ui.geo_tools_table.item(row, 1).text())
  2769. new_cutz = (tooldia - vdia) / (2 * math.tan(math.radians(half_vangle)))
  2770. new_cutz = float('%.4f' % -new_cutz)
  2771. self.ui.cutz_entry.set_value(new_cutz)
  2772. # store the new CutZ value into storage (self.tools)
  2773. for tooluid_key, tooluid_value in self.tools.items():
  2774. if int(tooluid_key) == tool_uid:
  2775. tooluid_value['data']['cutz'] = new_cutz
  2776. def on_tooltable_cellwidget_change(self):
  2777. cw = self.sender()
  2778. cw_index = self.ui.geo_tools_table.indexAt(cw.pos())
  2779. cw_row = cw_index.row()
  2780. cw_col = cw_index.column()
  2781. current_uid = int(self.ui.geo_tools_table.item(cw_row, 5).text())
  2782. # store the text of the cellWidget that changed it's index in the self.tools
  2783. for tooluid_key, tooluid_value in self.tools.items():
  2784. if int(tooluid_key) == current_uid:
  2785. cb_txt = cw.currentText()
  2786. if cw_col == 2:
  2787. tooluid_value['offset'] = cb_txt
  2788. if cb_txt == 'Custom':
  2789. self.ui.tool_offset_entry.show()
  2790. self.ui.tool_offset_lbl.show()
  2791. else:
  2792. self.ui.tool_offset_entry.hide()
  2793. self.ui.tool_offset_lbl.hide()
  2794. # reset the offset_value in storage self.tools
  2795. tooluid_value['offset_value'] = 0.0
  2796. elif cw_col == 3:
  2797. # force toolpath type as 'Iso' if the tool type is V-Shape
  2798. if self.ui.geo_tools_table.cellWidget(cw_row, 4).currentText() == 'V':
  2799. tooluid_value['type'] = 'Iso'
  2800. idx = self.ui.geo_tools_table.cellWidget(cw_row, 3).findText('Iso')
  2801. self.ui.geo_tools_table.cellWidget(cw_row, 3).setCurrentIndex(idx)
  2802. else:
  2803. tooluid_value['type'] = cb_txt
  2804. elif cw_col == 4:
  2805. tooluid_value['tool_type'] = cb_txt
  2806. # if the tool_type selected is V-Shape then autoselect the toolpath type as Iso
  2807. if cb_txt == 'V':
  2808. idx = self.ui.geo_tools_table.cellWidget(cw_row, 3).findText('Iso')
  2809. self.ui.geo_tools_table.cellWidget(cw_row, 3).setCurrentIndex(idx)
  2810. self.ui_update_v_shape(tool_type_txt=self.ui.geo_tools_table.cellWidget(cw_row, 4).currentText())
  2811. def update_form(self, dict_storage):
  2812. for form_key in self.form_fields:
  2813. for storage_key in dict_storage:
  2814. if form_key == storage_key:
  2815. try:
  2816. self.form_fields[form_key].set_value(dict_storage[form_key])
  2817. except Exception as e:
  2818. log.debug(str(e))
  2819. # this is done here because those buttons control through OptionalInputSelection if some entry's are Enabled
  2820. # or not. But due of using the ui_disconnect() status is no longer updated and I had to do it here
  2821. self.ui.ois_dwell_geo.on_cb_change()
  2822. self.ui.ois_mpass_geo.on_cb_change()
  2823. self.ui.ois_tcz_geo.on_cb_change()
  2824. def gui_form_to_storage(self):
  2825. self.ui_disconnect()
  2826. widget_changed = self.sender()
  2827. try:
  2828. widget_idx = self.ui.grid3.indexOf(widget_changed)
  2829. except:
  2830. return
  2831. # those are the indexes for the V-Tip Dia and V-Tip Angle, if edited calculate the new Cut Z
  2832. if widget_idx == 1 or widget_idx == 3:
  2833. self.update_cutz()
  2834. # the original connect() function of the OptionalInpuSelection is no longer working because of the
  2835. # ui_diconnect() so I use this 'hack'
  2836. if isinstance(widget_changed, FCCheckBox):
  2837. if widget_changed.text() == 'Multi-Depth:':
  2838. self.ui.ois_mpass_geo.on_cb_change()
  2839. if widget_changed.text() == 'Tool change':
  2840. self.ui.ois_tcz_geo.on_cb_change()
  2841. if widget_changed.text() == 'Dwell:':
  2842. self.ui.ois_dwell_geo.on_cb_change()
  2843. row = self.ui.geo_tools_table.currentRow()
  2844. if row < 0:
  2845. row = 0
  2846. # store all the data associated with the row parameter to the self.tools storage
  2847. tooldia_item = float(self.ui.geo_tools_table.item(row, 1).text())
  2848. offset_item = self.ui.geo_tools_table.cellWidget(row, 2).currentText()
  2849. type_item = self.ui.geo_tools_table.cellWidget(row, 3).currentText()
  2850. tool_type_item = self.ui.geo_tools_table.cellWidget(row, 4).currentText()
  2851. tooluid_item = int(self.ui.geo_tools_table.item(row, 5).text())
  2852. try:
  2853. offset_value_item = float(self.ui.tool_offset_entry.get_value())
  2854. except ValueError:
  2855. # try to convert comma to decimal point. if it's still not working error message and return
  2856. try:
  2857. offset_value_item = float(self.ui.tool_offset_entry.get_value().replace(',', '.')
  2858. )
  2859. except ValueError:
  2860. self.app.inform.emit("[ERROR_NOTCL]Wrong value format entered, "
  2861. "use a number.")
  2862. return
  2863. # this new dict will hold the actual useful data, another dict that is the value of key 'data'
  2864. temp_tools = {}
  2865. temp_dia = {}
  2866. temp_data = {}
  2867. for tooluid_key, tooluid_value in self.tools.items():
  2868. if int(tooluid_key) == tooluid_item:
  2869. for key, value in tooluid_value.items():
  2870. if key == 'tooldia':
  2871. temp_dia[key] = tooldia_item
  2872. # update the 'offset', 'type' and 'tool_type' sections
  2873. if key == 'offset':
  2874. temp_dia[key] = offset_item
  2875. if key == 'type':
  2876. temp_dia[key] = type_item
  2877. if key == 'tool_type':
  2878. temp_dia[key] = tool_type_item
  2879. if key == 'offset_value':
  2880. temp_dia[key] = offset_value_item
  2881. if key == 'data':
  2882. # update the 'data' section
  2883. for data_key in tooluid_value[key].keys():
  2884. for form_key, form_value in self.form_fields.items():
  2885. if form_key == data_key:
  2886. temp_data[data_key] = form_value.get_value()
  2887. # make sure we make a copy of the keys not in the form (we may use 'data' keys that are
  2888. # updated from self.app.defaults
  2889. if data_key not in self.form_fields:
  2890. temp_data[data_key] = value[data_key]
  2891. temp_dia[key] = copy.deepcopy(temp_data)
  2892. temp_data.clear()
  2893. if key == 'solid_geometry':
  2894. temp_dia[key] = copy.deepcopy(self.tools[tooluid_key]['solid_geometry'])
  2895. temp_tools[tooluid_key] = copy.deepcopy(temp_dia)
  2896. else:
  2897. temp_tools[tooluid_key] = copy.deepcopy(tooluid_value)
  2898. self.tools.clear()
  2899. self.tools = copy.deepcopy(temp_tools)
  2900. temp_tools.clear()
  2901. self.ui_connect()
  2902. def select_tools_table_row(self, row, clearsel=None):
  2903. if clearsel:
  2904. self.ui.geo_tools_table.clearSelection()
  2905. if self.ui.geo_tools_table.rowCount() > 0:
  2906. # self.ui.geo_tools_table.item(row, 0).setSelected(True)
  2907. self.ui.geo_tools_table.setCurrentItem(self.ui.geo_tools_table.item(row, 0))
  2908. def export_dxf(self):
  2909. units = self.app.general_options_form.general_app_group.units_radio.get_value().upper()
  2910. dwg = None
  2911. try:
  2912. dwg = ezdxf.new('R2010')
  2913. msp = dwg.modelspace()
  2914. def g2dxf(dxf_space, geo):
  2915. if isinstance(geo, MultiPolygon):
  2916. for poly in geo:
  2917. ext_points = list(poly.exterior.coords)
  2918. dxf_space.add_lwpolyline(ext_points)
  2919. for interior in poly.interiors:
  2920. dxf_space.add_lwpolyline(list(interior.coords))
  2921. if isinstance(geo, Polygon):
  2922. ext_points = list(geo.exterior.coords)
  2923. dxf_space.add_lwpolyline(ext_points)
  2924. for interior in geo.interiors:
  2925. dxf_space.add_lwpolyline(list(interior.coords))
  2926. if isinstance(geo, MultiLineString):
  2927. for line in geo:
  2928. dxf_space.add_lwpolyline(list(line.coords))
  2929. if isinstance(geo, LineString) or isinstance(geo, LinearRing):
  2930. dxf_space.add_lwpolyline(list(geo.coords))
  2931. multigeo_solid_geometry = []
  2932. if self.multigeo:
  2933. for tool in self.tools:
  2934. multigeo_solid_geometry += self.tools[tool]['solid_geometry']
  2935. else:
  2936. multigeo_solid_geometry = self.solid_geometry
  2937. for geo in multigeo_solid_geometry:
  2938. if type(geo) == list:
  2939. for g in geo:
  2940. g2dxf(msp, g)
  2941. else:
  2942. g2dxf(msp, geo)
  2943. # points = FlatCAMGeometry.get_pts(geo)
  2944. # msp.add_lwpolyline(points)
  2945. except Exception as e:
  2946. log.debug(str(e))
  2947. return dwg
  2948. def get_selected_tools_table_items(self):
  2949. """
  2950. Returns a list of lists, each list in the list is made out of row elements
  2951. :return: List of table_tools items.
  2952. :rtype: list
  2953. """
  2954. table_tools_items = []
  2955. if self.multigeo:
  2956. for x in self.ui.geo_tools_table.selectedItems():
  2957. table_tools_items.append([self.ui.geo_tools_table.item(x.row(), column).text()
  2958. for column in range(0, self.ui.geo_tools_table.columnCount())])
  2959. else:
  2960. for x in self.ui.geo_tools_table.selectedItems():
  2961. r = []
  2962. # the last 2 columns for single-geo geometry are irrelevant and create problems reading
  2963. # so we don't read them
  2964. for column in range(0, self.ui.geo_tools_table.columnCount() - 2):
  2965. # the columns have items that have text but also have items that are widgets
  2966. # for which the text they hold has to be read differently
  2967. try:
  2968. txt = self.ui.geo_tools_table.item(x.row(), column).text()
  2969. except AttributeError:
  2970. txt = self.ui.geo_tools_table.cellWidget(x.row(), column).currentText()
  2971. except:
  2972. pass
  2973. r.append(txt)
  2974. table_tools_items.append(r)
  2975. for item in table_tools_items:
  2976. item[0] = str(item[0])
  2977. return table_tools_items
  2978. def on_pp_changed(self):
  2979. current_pp = self.ui.pp_geometry_name_cb.get_value()
  2980. if current_pp == 'hpgl':
  2981. self.old_pp_state = self.ui.mpass_cb.get_value()
  2982. self.old_toolchangeg_state = self.ui.toolchangeg_cb.get_value()
  2983. self.ui.mpass_cb.set_value(False)
  2984. self.ui.mpass_cb.setDisabled(True)
  2985. self.ui.toolchangeg_cb.set_value(True)
  2986. self.ui.toolchangeg_cb.setDisabled(True)
  2987. else:
  2988. self.ui.mpass_cb.set_value(self.old_pp_state)
  2989. self.ui.mpass_cb.setDisabled(False)
  2990. self.ui.toolchangeg_cb.set_value(self.old_toolchangeg_state)
  2991. self.ui.toolchangeg_cb.setDisabled(False)
  2992. if "toolchange_probe" in current_pp.lower():
  2993. self.ui.pdepth_entry.setVisible(True)
  2994. self.ui.pdepth_label.show()
  2995. self.ui.feedrate_probe_entry.setVisible(True)
  2996. self.ui.feedrate_probe_label.show()
  2997. else:
  2998. self.ui.pdepth_entry.setVisible(False)
  2999. self.ui.pdepth_label.hide()
  3000. self.ui.feedrate_probe_entry.setVisible(False)
  3001. self.ui.feedrate_probe_label.hide()
  3002. def on_generatecnc_button_click(self, *args):
  3003. self.app.report_usage("geometry_on_generatecnc_button")
  3004. self.read_form()
  3005. self.sel_tools = {}
  3006. # test to see if we have tools available in the tool table
  3007. if self.ui.geo_tools_table.selectedItems():
  3008. for x in self.ui.geo_tools_table.selectedItems():
  3009. try:
  3010. tooldia = float(self.ui.geo_tools_table.item(x.row(), 1).text())
  3011. except ValueError:
  3012. # try to convert comma to decimal point. if it's still not working error message and return
  3013. try:
  3014. tooldia = float(self.ui.geo_tools_table.item(x.row(), 1).text().replace(',', '.'))
  3015. except ValueError:
  3016. self.app.inform.emit("[ERROR_NOTCL]Wrong Tool Dia value format entered, "
  3017. "use a number.")
  3018. return
  3019. tooluid = int(self.ui.geo_tools_table.item(x.row(), 5).text())
  3020. for tooluid_key, tooluid_value in self.tools.items():
  3021. if int(tooluid_key) == tooluid:
  3022. self.sel_tools.update({
  3023. tooluid: copy.deepcopy(tooluid_value)
  3024. })
  3025. self.mtool_gen_cncjob()
  3026. self.ui.geo_tools_table.clearSelection()
  3027. elif self.ui.geo_tools_table.rowCount() == 1:
  3028. tooluid = int(self.ui.geo_tools_table.item(0, 5).text())
  3029. for tooluid_key, tooluid_value in self.tools.items():
  3030. if int(tooluid_key) == tooluid:
  3031. self.sel_tools.update({
  3032. tooluid: copy.deepcopy(tooluid_value)
  3033. })
  3034. self.mtool_gen_cncjob()
  3035. self.ui.geo_tools_table.clearSelection()
  3036. else:
  3037. self.app.inform.emit("[ERROR_NOTCL] Failed. No tool selected in the tool table ...")
  3038. def mtool_gen_cncjob(self, segx=None, segy=None, use_thread=True):
  3039. """
  3040. Creates a multi-tool CNCJob out of this Geometry object.
  3041. The actual work is done by the target FlatCAMCNCjob object's
  3042. `generate_from_geometry_2()` method.
  3043. :param z_cut: Cut depth (negative)
  3044. :param z_move: Hight of the tool when travelling (not cutting)
  3045. :param feedrate: Feed rate while cutting on X - Y plane
  3046. :param feedrate_z: Feed rate while cutting on Z plane
  3047. :param feedrate_rapid: Feed rate while moving with rapids
  3048. :param tooldia: Tool diameter
  3049. :param outname: Name of the new object
  3050. :param spindlespeed: Spindle speed (RPM)
  3051. :param ppname_g Name of the postprocessor
  3052. :return: None
  3053. """
  3054. offset_str = ''
  3055. multitool_gcode = ''
  3056. # use the name of the first tool selected in self.geo_tools_table which has the diameter passed as tool_dia
  3057. outname = "%s_%s" % (self.options["name"], 'cnc')
  3058. segx = segx if segx is not None else float(self.app.defaults['geometry_segx'])
  3059. segy = segy if segy is not None else float(self.app.defaults['geometry_segy'])
  3060. try:
  3061. xmin = self.options['xmin']
  3062. ymin = self.options['ymin']
  3063. xmax = self.options['xmax']
  3064. ymax = self.options['ymax']
  3065. except Exception as e:
  3066. log.debug("FlatCAMObj.FlatCAMGeometry.mtool_gen_cncjob() --> %s\n" % str(e))
  3067. msg = "[ERROR] An internal error has ocurred. See shell.\n"
  3068. msg += 'FlatCAMObj.FlatCAMGeometry.mtool_gen_cncjob() --> %s' % str(e)
  3069. msg += traceback.format_exc()
  3070. self.app.inform.emit(msg)
  3071. return
  3072. # Object initialization function for app.new_object()
  3073. # RUNNING ON SEPARATE THREAD!
  3074. def job_init_single_geometry(job_obj, app_obj):
  3075. assert isinstance(job_obj, FlatCAMCNCjob), \
  3076. "Initializer expected a FlatCAMCNCjob, got %s" % type(job_obj)
  3077. # count the tools
  3078. tool_cnt = 0
  3079. dia_cnc_dict = {}
  3080. # this turn on the FlatCAMCNCJob plot for multiple tools
  3081. job_obj.multitool = True
  3082. job_obj.multigeo = False
  3083. job_obj.cnc_tools.clear()
  3084. # job_obj.create_geometry()
  3085. job_obj.options['Tools_in_use'] = self.get_selected_tools_table_items()
  3086. job_obj.segx = segx
  3087. job_obj.segy = segy
  3088. try:
  3089. job_obj.z_pdepth = float(self.options["z_pdepth"])
  3090. except ValueError:
  3091. # try to convert comma to decimal point. if it's still not working error message and return
  3092. try:
  3093. job_obj.z_pdepth = float(self.options["z_pdepth"].replace(',', '.'))
  3094. except ValueError:
  3095. self.app.inform.emit(
  3096. '[ERROR_NOTCL]Wrong value format for self.defaults["z_pdepth"] or self.options["z_pdepth"]')
  3097. try:
  3098. job_obj.feedrate_probe = float(self.options["feedrate_probe"])
  3099. except ValueError:
  3100. # try to convert comma to decimal point. if it's still not working error message and return
  3101. try:
  3102. job_obj.feedrate_rapid = float(self.options["feedrate_probe"].replace(',', '.'))
  3103. except ValueError:
  3104. self.app.inform.emit(
  3105. '[ERROR_NOTCL]Wrong value format for self.defaults["feedrate_probe"] '
  3106. 'or self.options["feedrate_probe"]')
  3107. for tooluid_key in self.sel_tools:
  3108. tool_cnt += 1
  3109. app_obj.progress.emit(20)
  3110. for diadict_key, diadict_value in self.sel_tools[tooluid_key].items():
  3111. if diadict_key == 'tooldia':
  3112. tooldia_val = float('%.4f' % float(diadict_value))
  3113. dia_cnc_dict.update({
  3114. diadict_key: tooldia_val
  3115. })
  3116. if diadict_key == 'offset':
  3117. o_val = diadict_value.lower()
  3118. dia_cnc_dict.update({
  3119. diadict_key: o_val
  3120. })
  3121. if diadict_key == 'type':
  3122. t_val = diadict_value
  3123. dia_cnc_dict.update({
  3124. diadict_key: t_val
  3125. })
  3126. if diadict_key == 'tool_type':
  3127. tt_val = diadict_value
  3128. dia_cnc_dict.update({
  3129. diadict_key: tt_val
  3130. })
  3131. if diadict_key == 'data':
  3132. for data_key, data_value in diadict_value.items():
  3133. if data_key == "multidepth":
  3134. multidepth = data_value
  3135. if data_key == "depthperpass":
  3136. depthpercut = data_value
  3137. if data_key == "extracut":
  3138. extracut = data_value
  3139. if data_key == "startz":
  3140. startz = data_value
  3141. if data_key == "endz":
  3142. endz = data_value
  3143. if data_key == "toolchangez":
  3144. toolchangez =data_value
  3145. if data_key == "toolchangexy":
  3146. toolchangexy = data_value
  3147. if data_key == "toolchange":
  3148. toolchange = data_value
  3149. if data_key == "cutz":
  3150. z_cut = data_value
  3151. if data_key == "travelz":
  3152. z_move = data_value
  3153. if data_key == "feedrate":
  3154. feedrate = data_value
  3155. if data_key == "feedrate_z":
  3156. feedrate_z = data_value
  3157. if data_key == "feedrate_rapid":
  3158. feedrate_rapid = data_value
  3159. if data_key == "ppname_g":
  3160. pp_geometry_name = data_value
  3161. if data_key == "spindlespeed":
  3162. spindlespeed = data_value
  3163. if data_key == "dwell":
  3164. dwell = data_value
  3165. if data_key == "dwelltime":
  3166. dwelltime = data_value
  3167. datadict = copy.deepcopy(diadict_value)
  3168. dia_cnc_dict.update({
  3169. diadict_key: datadict
  3170. })
  3171. if dia_cnc_dict['offset'] == 'in':
  3172. tool_offset = -dia_cnc_dict['tooldia'] / 2
  3173. offset_str = 'inside'
  3174. elif dia_cnc_dict['offset'].lower() == 'out':
  3175. tool_offset = dia_cnc_dict['tooldia'] / 2
  3176. offset_str = 'outside'
  3177. elif dia_cnc_dict['offset'].lower() == 'path':
  3178. offset_str = 'onpath'
  3179. tool_offset = 0.0
  3180. else:
  3181. offset_str = 'custom'
  3182. try:
  3183. offset_value = float(self.ui.tool_offset_entry.get_value())
  3184. except ValueError:
  3185. # try to convert comma to decimal point. if it's still not working error message and return
  3186. try:
  3187. offset_value = float(self.ui.tool_offset_entry.get_value().replace(',', '.')
  3188. )
  3189. except ValueError:
  3190. self.app.inform.emit("[ERROR_NOTCL]Wrong value format entered, "
  3191. "use a number.")
  3192. return
  3193. if offset_value:
  3194. tool_offset = float(offset_value)
  3195. else:
  3196. self.app.inform.emit(
  3197. "[WARNING] Tool Offset is selected in Tool Table but no value is provided.\n"
  3198. "Add a Tool Offset or change the Offset Type."
  3199. )
  3200. return
  3201. dia_cnc_dict.update({
  3202. 'offset_value': tool_offset
  3203. })
  3204. job_obj.coords_decimals = self.app.defaults["cncjob_coords_decimals"]
  3205. job_obj.fr_decimals = self.app.defaults["cncjob_fr_decimals"]
  3206. # Propagate options
  3207. job_obj.options["tooldia"] = tooldia_val
  3208. job_obj.options['type'] = 'Geometry'
  3209. job_obj.options['tool_dia'] = tooldia_val
  3210. job_obj.options['xmin'] = xmin
  3211. job_obj.options['ymin'] = ymin
  3212. job_obj.options['xmax'] = xmax
  3213. job_obj.options['ymax'] = ymax
  3214. app_obj.progress.emit(40)
  3215. res = job_obj.generate_from_geometry_2(
  3216. self, tooldia=tooldia_val, offset=tool_offset, tolerance=0.0005,
  3217. z_cut=z_cut, z_move=z_move,
  3218. feedrate=feedrate, feedrate_z=feedrate_z, feedrate_rapid=feedrate_rapid,
  3219. spindlespeed=spindlespeed, dwell=dwell, dwelltime=dwelltime,
  3220. multidepth=multidepth, depthpercut=depthpercut,
  3221. extracut=extracut, startz=startz, endz=endz,
  3222. toolchange=toolchange, toolchangez=toolchangez, toolchangexy=toolchangexy,
  3223. pp_geometry_name=pp_geometry_name,
  3224. tool_no=tool_cnt)
  3225. if res == 'fail':
  3226. log.debug("FlatCAMGeometry.mtool_gen_cncjob() --> generate_from_geometry2() failed")
  3227. return 'fail'
  3228. else:
  3229. dia_cnc_dict['gcode'] = res
  3230. app_obj.progress.emit(50)
  3231. # tell gcode_parse from which point to start drawing the lines depending on what kind of
  3232. # object is the source of gcode
  3233. job_obj.toolchange_xy_type = "geometry"
  3234. dia_cnc_dict['gcode_parsed'] = job_obj.gcode_parse()
  3235. # TODO this serve for bounding box creation only; should be optimized
  3236. dia_cnc_dict['solid_geometry'] = cascaded_union([geo['geom'] for geo in dia_cnc_dict['gcode_parsed']])
  3237. app_obj.progress.emit(80)
  3238. job_obj.cnc_tools.update({
  3239. tooluid_key: copy.deepcopy(dia_cnc_dict)
  3240. })
  3241. dia_cnc_dict.clear()
  3242. # Object initialization function for app.new_object()
  3243. # RUNNING ON SEPARATE THREAD!
  3244. def job_init_multi_geometry(job_obj, app_obj):
  3245. assert isinstance(job_obj, FlatCAMCNCjob), \
  3246. "Initializer expected a FlatCAMCNCjob, got %s" % type(job_obj)
  3247. # count the tools
  3248. tool_cnt = 0
  3249. dia_cnc_dict = {}
  3250. current_uid = int(1)
  3251. # this turn on the FlatCAMCNCJob plot for multiple tools
  3252. job_obj.multitool = True
  3253. job_obj.multigeo = True
  3254. job_obj.cnc_tools.clear()
  3255. job_obj.options['xmin'] = xmin
  3256. job_obj.options['ymin'] = ymin
  3257. job_obj.options['xmax'] = xmax
  3258. job_obj.options['ymax'] = ymax
  3259. try:
  3260. job_obj.z_pdepth = float(self.options["z_pdepth"])
  3261. except ValueError:
  3262. # try to convert comma to decimal point. if it's still not working error message and return
  3263. try:
  3264. job_obj.z_pdepth = float(self.options["z_pdepth"].replace(',', '.'))
  3265. except ValueError:
  3266. self.app.inform.emit(
  3267. '[ERROR_NOTCL]Wrong value format for self.defaults["z_pdepth"] or self.options["z_pdepth"]')
  3268. try:
  3269. job_obj.feedrate_probe = float(self.options["feedrate_probe"])
  3270. except ValueError:
  3271. # try to convert comma to decimal point. if it's still not working error message and return
  3272. try:
  3273. job_obj.feedrate_rapid = float(self.options["feedrate_probe"].replace(',', '.'))
  3274. except ValueError:
  3275. self.app.inform.emit(
  3276. '[ERROR_NOTCL]Wrong value format for self.defaults["feedrate_probe"] '
  3277. 'or self.options["feedrate_probe"]')
  3278. for tooluid_key in self.sel_tools:
  3279. tool_cnt += 1
  3280. app_obj.progress.emit(20)
  3281. # find the tool_dia associated with the tooluid_key
  3282. sel_tool_dia = self.sel_tools[tooluid_key]['tooldia']
  3283. # search in the self.tools for the sel_tool_dia and when found see what tooluid has
  3284. # on the found tooluid in self.tools we also have the solid_geometry that interest us
  3285. for k, v in self.tools.items():
  3286. if float('%.4f' % float(v['tooldia'])) == float('%.4f' % float(sel_tool_dia)):
  3287. current_uid = int(k)
  3288. break
  3289. for diadict_key, diadict_value in self.sel_tools[tooluid_key].items():
  3290. if diadict_key == 'tooldia':
  3291. tooldia_val = float('%.4f' % float(diadict_value))
  3292. dia_cnc_dict.update({
  3293. diadict_key: tooldia_val
  3294. })
  3295. if diadict_key == 'offset':
  3296. o_val = diadict_value.lower()
  3297. dia_cnc_dict.update({
  3298. diadict_key: o_val
  3299. })
  3300. if diadict_key == 'type':
  3301. t_val = diadict_value
  3302. dia_cnc_dict.update({
  3303. diadict_key: t_val
  3304. })
  3305. if diadict_key == 'tool_type':
  3306. tt_val = diadict_value
  3307. dia_cnc_dict.update({
  3308. diadict_key: tt_val
  3309. })
  3310. if diadict_key == 'data':
  3311. for data_key, data_value in diadict_value.items():
  3312. if data_key == "multidepth":
  3313. multidepth = data_value
  3314. if data_key == "depthperpass":
  3315. depthpercut = data_value
  3316. if data_key == "extracut":
  3317. extracut = data_value
  3318. if data_key == "startz":
  3319. startz = data_value
  3320. if data_key == "endz":
  3321. endz = data_value
  3322. if data_key == "toolchangez":
  3323. toolchangez =data_value
  3324. if data_key == "toolchangexy":
  3325. toolchangexy = data_value
  3326. if data_key == "toolchange":
  3327. toolchange = data_value
  3328. if data_key == "cutz":
  3329. z_cut = data_value
  3330. if data_key == "travelz":
  3331. z_move = data_value
  3332. if data_key == "feedrate":
  3333. feedrate = data_value
  3334. if data_key == "feedrate_z":
  3335. feedrate_z = data_value
  3336. if data_key == "feedrate_rapid":
  3337. feedrate_rapid = data_value
  3338. if data_key == "ppname_g":
  3339. pp_geometry_name = data_value
  3340. if data_key == "spindlespeed":
  3341. spindlespeed = data_value
  3342. if data_key == "dwell":
  3343. dwell = data_value
  3344. if data_key == "dwelltime":
  3345. dwelltime = data_value
  3346. datadict = copy.deepcopy(diadict_value)
  3347. dia_cnc_dict.update({
  3348. diadict_key: datadict
  3349. })
  3350. if dia_cnc_dict['offset'] == 'in':
  3351. tool_offset = -dia_cnc_dict['tooldia'] / 2
  3352. offset_str = 'inside'
  3353. elif dia_cnc_dict['offset'].lower() == 'out':
  3354. tool_offset = dia_cnc_dict['tooldia'] / 2
  3355. offset_str = 'outside'
  3356. elif dia_cnc_dict['offset'].lower() == 'path':
  3357. offset_str = 'onpath'
  3358. tool_offset = 0.0
  3359. else:
  3360. offset_str = 'custom'
  3361. try:
  3362. offset_value = float(self.ui.tool_offset_entry.get_value())
  3363. except ValueError:
  3364. # try to convert comma to decimal point. if it's still not working error message and return
  3365. try:
  3366. offset_value = float(self.ui.tool_offset_entry.get_value().replace(',', '.')
  3367. )
  3368. except ValueError:
  3369. self.app.inform.emit("[ERROR_NOTCL]Wrong value format entered, "
  3370. "use a number.")
  3371. return
  3372. if offset_value:
  3373. tool_offset = float(offset_value)
  3374. else:
  3375. self.app.inform.emit(
  3376. "[WARNING] Tool Offset is selected in Tool Table but no value is provided.\n"
  3377. "Add a Tool Offset or change the Offset Type."
  3378. )
  3379. return
  3380. dia_cnc_dict.update({
  3381. 'offset_value': tool_offset
  3382. })
  3383. job_obj.coords_decimals = self.app.defaults["cncjob_coords_decimals"]
  3384. job_obj.fr_decimals = self.app.defaults["cncjob_fr_decimals"]
  3385. # Propagate options
  3386. job_obj.options["tooldia"] = tooldia_val
  3387. job_obj.options['type'] = 'Geometry'
  3388. job_obj.options['tool_dia'] = tooldia_val
  3389. app_obj.progress.emit(40)
  3390. tool_solid_geometry = self.tools[current_uid]['solid_geometry']
  3391. res = job_obj.generate_from_multitool_geometry(
  3392. tool_solid_geometry, tooldia=tooldia_val, offset=tool_offset,
  3393. tolerance=0.0005, z_cut=z_cut, z_move=z_move,
  3394. feedrate=feedrate, feedrate_z=feedrate_z, feedrate_rapid=feedrate_rapid,
  3395. spindlespeed=spindlespeed, dwell=dwell, dwelltime=dwelltime,
  3396. multidepth=multidepth, depthpercut=depthpercut,
  3397. extracut=extracut, startz=startz, endz=endz,
  3398. toolchange=toolchange, toolchangez=toolchangez, toolchangexy=toolchangexy,
  3399. pp_geometry_name=pp_geometry_name,
  3400. tool_no=tool_cnt)
  3401. if res == 'fail':
  3402. log.debug("FlatCAMGeometry.mtool_gen_cncjob() --> generate_from_geometry2() failed")
  3403. return 'fail'
  3404. else:
  3405. dia_cnc_dict['gcode'] = res
  3406. dia_cnc_dict['gcode_parsed'] = job_obj.gcode_parse()
  3407. # TODO this serve for bounding box creation only; should be optimized
  3408. dia_cnc_dict['solid_geometry'] = cascaded_union([geo['geom'] for geo in dia_cnc_dict['gcode_parsed']])
  3409. # tell gcode_parse from which point to start drawing the lines depending on what kind of
  3410. # object is the source of gcode
  3411. job_obj.toolchange_xy_type = "geometry"
  3412. app_obj.progress.emit(80)
  3413. job_obj.cnc_tools.update({
  3414. tooluid_key: copy.deepcopy(dia_cnc_dict)
  3415. })
  3416. dia_cnc_dict.clear()
  3417. if use_thread:
  3418. # To be run in separate thread
  3419. # The idea is that if there is a solid_geometry in the file "root" then most likely thare are no
  3420. # separate solid_geometry in the self.tools dictionary
  3421. def job_thread(app_obj):
  3422. if self.solid_geometry:
  3423. with self.app.proc_container.new("Generating CNC Code"):
  3424. if app_obj.new_object("cncjob", outname, job_init_single_geometry) != 'fail':
  3425. app_obj.inform.emit("[success]CNCjob created: %s" % outname)
  3426. app_obj.progress.emit(100)
  3427. else:
  3428. with self.app.proc_container.new("Generating CNC Code"):
  3429. if app_obj.new_object("cncjob", outname, job_init_multi_geometry) != 'fail':
  3430. app_obj.inform.emit("[success]CNCjob created: %s" % outname)
  3431. app_obj.progress.emit(100)
  3432. # Create a promise with the name
  3433. self.app.collection.promise(outname)
  3434. # Send to worker
  3435. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  3436. else:
  3437. if self.solid_geometry:
  3438. self.app.new_object("cncjob", outname, job_init_single_geometry)
  3439. else:
  3440. self.app.new_object("cncjob", outname, job_init_multi_geometry)
  3441. def generatecncjob(self, outname=None,
  3442. tooldia=None, offset=None,
  3443. z_cut=None, z_move=None,
  3444. feedrate=None, feedrate_z=None, feedrate_rapid=None,
  3445. spindlespeed=None, dwell=None, dwelltime=None,
  3446. multidepth=None, depthperpass=None,
  3447. toolchange=None, toolchangez=None, toolchangexy=None,
  3448. extracut=None, startz=None, endz=None,
  3449. ppname_g=None,
  3450. segx=None,
  3451. segy=None,
  3452. use_thread=True):
  3453. """
  3454. Only used for TCL Command.
  3455. Creates a CNCJob out of this Geometry object. The actual
  3456. work is done by the target FlatCAMCNCjob object's
  3457. `generate_from_geometry_2()` method.
  3458. :param z_cut: Cut depth (negative)
  3459. :param z_move: Hight of the tool when travelling (not cutting)
  3460. :param feedrate: Feed rate while cutting on X - Y plane
  3461. :param feedrate_z: Feed rate while cutting on Z plane
  3462. :param feedrate_rapid: Feed rate while moving with rapids
  3463. :param tooldia: Tool diameter
  3464. :param outname: Name of the new object
  3465. :param spindlespeed: Spindle speed (RPM)
  3466. :param ppname_g Name of the postprocessor
  3467. :return: None
  3468. """
  3469. tooldia = tooldia if tooldia else float(self.options["cnctooldia"])
  3470. outname = outname if outname is not None else self.options["name"]
  3471. z_cut = z_cut if z_cut is not None else float(self.options["cutz"])
  3472. z_move = z_move if z_move is not None else float(self.options["travelz"])
  3473. feedrate = feedrate if feedrate is not None else float(self.options["feedrate"])
  3474. feedrate_z = feedrate_z if feedrate_z is not None else float(self.options["feedrate_z"])
  3475. feedrate_rapid = feedrate_rapid if feedrate_rapid is not None else float(self.options["feedrate_rapid"])
  3476. multidepth = multidepth if multidepth is not None else self.options["multidepth"]
  3477. depthperpass = depthperpass if depthperpass is not None else float(self.options["depthperpass"])
  3478. segx = segx if segx is not None else float(self.app.defaults['geometry_segx'])
  3479. segy = segy if segy is not None else float(self.app.defaults['geometry_segy'])
  3480. extracut = extracut if extracut is not None else float(self.options["extracut"])
  3481. startz = startz if startz is not None else self.options["startz"]
  3482. endz = endz if endz is not None else float(self.options["endz"])
  3483. toolchangez = toolchangez if toolchangez else float(self.options["toolchangez"])
  3484. toolchangexy = toolchangexy if toolchangexy else self.options["toolchangexy"]
  3485. toolchange = toolchange if toolchange else self.options["toolchange"]
  3486. offset = offset if offset else 0.0
  3487. # int or None.
  3488. spindlespeed = spindlespeed if spindlespeed else self.options['spindlespeed']
  3489. dwell = dwell if dwell else self.options["dwell"]
  3490. dwelltime = dwelltime if dwelltime else float(self.options["dwelltime"])
  3491. ppname_g = ppname_g if ppname_g else self.options["ppname_g"]
  3492. # Object initialization function for app.new_object()
  3493. # RUNNING ON SEPARATE THREAD!
  3494. def job_init(job_obj, app_obj):
  3495. assert isinstance(job_obj, FlatCAMCNCjob), "Initializer expected a FlatCAMCNCjob, got %s" % type(job_obj)
  3496. # Propagate options
  3497. job_obj.options["tooldia"] = tooldia
  3498. app_obj.progress.emit(20)
  3499. job_obj.coords_decimals = self.app.defaults["cncjob_coords_decimals"]
  3500. job_obj.fr_decimals = self.app.defaults["cncjob_fr_decimals"]
  3501. app_obj.progress.emit(40)
  3502. job_obj.options['type'] = 'Geometry'
  3503. job_obj.options['tool_dia'] = tooldia
  3504. job_obj.segx = segx
  3505. job_obj.segy = segy
  3506. try:
  3507. job_obj.z_pdepth = float(self.options["z_pdepth"])
  3508. except ValueError:
  3509. # try to convert comma to decimal point. if it's still not working error message and return
  3510. try:
  3511. job_obj.z_pdepth = float(self.options["z_pdepth"].replace(',', '.'))
  3512. except ValueError:
  3513. self.app.inform.emit(
  3514. '[ERROR_NOTCL]Wrong value format for self.defaults["z_pdepth"] or self.options["z_pdepth"]')
  3515. try:
  3516. job_obj.feedrate_probe = float(self.options["feedrate_probe"])
  3517. except ValueError:
  3518. # try to convert comma to decimal point. if it's still not working error message and return
  3519. try:
  3520. job_obj.feedrate_rapid = float(self.options["feedrate_probe"].replace(',', '.'))
  3521. except ValueError:
  3522. self.app.inform.emit(
  3523. '[ERROR_NOTCL]Wrong value format for self.defaults["feedrate_probe"] '
  3524. 'or self.options["feedrate_probe"]')
  3525. # TODO: The tolerance should not be hard coded. Just for testing.
  3526. job_obj.generate_from_geometry_2(self, tooldia=tooldia, offset=offset, tolerance=0.0005,
  3527. z_cut=z_cut, z_move=z_move,
  3528. feedrate=feedrate, feedrate_z=feedrate_z, feedrate_rapid=feedrate_rapid,
  3529. spindlespeed=spindlespeed, dwell=dwell, dwelltime=dwelltime,
  3530. multidepth=multidepth, depthpercut=depthperpass,
  3531. toolchange=toolchange, toolchangez=toolchangez, toolchangexy=toolchangexy,
  3532. extracut=extracut, startz=startz, endz=endz,
  3533. pp_geometry_name=ppname_g
  3534. )
  3535. app_obj.progress.emit(50)
  3536. # tell gcode_parse from which point to start drawing the lines depending on what kind of object is the
  3537. # source of gcode
  3538. job_obj.toolchange_xy_type = "geometry"
  3539. job_obj.gcode_parse()
  3540. app_obj.progress.emit(80)
  3541. if use_thread:
  3542. # To be run in separate thread
  3543. def job_thread(app_obj):
  3544. with self.app.proc_container.new("Generating CNC Code"):
  3545. app_obj.new_object("cncjob", outname, job_init)
  3546. app_obj.inform.emit("[success]CNCjob created: %s" % outname)
  3547. app_obj.progress.emit(100)
  3548. # Create a promise with the name
  3549. self.app.collection.promise(outname)
  3550. # Send to worker
  3551. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  3552. else:
  3553. self.app.new_object("cncjob", outname, job_init)
  3554. # def on_plot_cb_click(self, *args): # TODO: args not needed
  3555. # if self.muted_ui:
  3556. # return
  3557. # self.read_form_item('plot')
  3558. def scale(self, xfactor, yfactor=None, point=None):
  3559. """
  3560. Scales all geometry by a given factor.
  3561. :param xfactor: Factor by which to scale the object's geometry/
  3562. :type xfactor: float
  3563. :param yfactor: Factor by which to scale the object's geometry/
  3564. :type yfactor: float
  3565. :return: None
  3566. :rtype: None
  3567. """
  3568. try:
  3569. xfactor = float(xfactor)
  3570. except:
  3571. self.app.inform.emit("[ERROR_NOTCL] Scale factor has to be a number: integer or float.")
  3572. return
  3573. if yfactor is None:
  3574. yfactor = xfactor
  3575. else:
  3576. try:
  3577. yfactor = float(yfactor)
  3578. except:
  3579. self.app.inform.emit("[ERROR_NOTCL] Scale factor has to be a number: integer or float.")
  3580. return
  3581. if point is None:
  3582. px = 0
  3583. py = 0
  3584. else:
  3585. px, py = point
  3586. # if type(self.solid_geometry) == list:
  3587. # geo_list = self.flatten(self.solid_geometry)
  3588. # self.solid_geometry = []
  3589. # # for g in geo_list:
  3590. # # self.solid_geometry.append(affinity.scale(g, xfactor, yfactor, origin=(px, py)))
  3591. # self.solid_geometry = [affinity.scale(g, xfactor, yfactor, origin=(px, py))
  3592. # for g in geo_list]
  3593. # else:
  3594. # self.solid_geometry = affinity.scale(self.solid_geometry, xfactor, yfactor,
  3595. # origin=(px, py))
  3596. # self.app.inform.emit("[success]Geometry Scale done.")
  3597. def scale_recursion(geom):
  3598. if type(geom) == list:
  3599. geoms=list()
  3600. for local_geom in geom:
  3601. geoms.append(scale_recursion(local_geom))
  3602. return geoms
  3603. else:
  3604. return affinity.scale(geom, xfactor, yfactor, origin=(px, py))
  3605. if self.multigeo is True:
  3606. for tool in self.tools:
  3607. self.tools[tool]['solid_geometry'] = scale_recursion(self.tools[tool]['solid_geometry'])
  3608. else:
  3609. self.solid_geometry=scale_recursion(self.solid_geometry)
  3610. self.app.inform.emit("[success]Geometry Scale done.")
  3611. def offset(self, vect):
  3612. """
  3613. Offsets all geometry by a given vector/
  3614. :param vect: (x, y) vector by which to offset the object's geometry.
  3615. :type vect: tuple
  3616. :return: None
  3617. :rtype: None
  3618. """
  3619. try:
  3620. dx, dy = vect
  3621. except TypeError:
  3622. self.app.inform.emit("[ERROR_NOTCL]An (x,y) pair of values are needed. "
  3623. "Probable you entered only one value in the Offset field.")
  3624. return
  3625. def translate_recursion(geom):
  3626. if type(geom) == list:
  3627. geoms=list()
  3628. for local_geom in geom:
  3629. geoms.append(translate_recursion(local_geom))
  3630. return geoms
  3631. else:
  3632. return affinity.translate(geom, xoff=dx, yoff=dy)
  3633. if self.multigeo is True:
  3634. for tool in self.tools:
  3635. self.tools[tool]['solid_geometry'] = translate_recursion(self.tools[tool]['solid_geometry'])
  3636. else:
  3637. self.solid_geometry=translate_recursion(self.solid_geometry)
  3638. self.app.inform.emit("[success]Geometry Offset done.")
  3639. def convert_units(self, units):
  3640. self.ui_disconnect()
  3641. factor = Geometry.convert_units(self, units)
  3642. self.options['cutz'] = float(self.options['cutz']) * factor
  3643. self.options['depthperpass'] = float(self.options['depthperpass']) * factor
  3644. self.options['travelz'] = float(self.options['travelz']) * factor
  3645. self.options['feedrate'] = float(self.options['feedrate']) * factor
  3646. self.options['feedrate_z'] = float(self.options['feedrate_z']) * factor
  3647. self.options['feedrate_rapid'] = float(self.options['feedrate_rapid']) * factor
  3648. self.options['endz'] = float(self.options['endz']) * factor
  3649. # self.options['cnctooldia'] *= factor
  3650. # self.options['painttooldia'] *= factor
  3651. # self.options['paintmargin'] *= factor
  3652. # self.options['paintoverlap'] *= factor
  3653. self.options["toolchangez"] = float(self.options["toolchangez"]) * factor
  3654. if self.app.defaults["geometry_toolchangexy"] == '':
  3655. self.options['toolchangexy'] = "0.0, 0.0"
  3656. else:
  3657. coords_xy = [float(eval(coord)) for coord in self.app.defaults["geometry_toolchangexy"].split(",")]
  3658. if len(coords_xy) < 2:
  3659. self.app.inform.emit("[ERROR]The Toolchange X,Y field in Edit -> Preferences has to be "
  3660. "in the format (x, y) \nbut now there is only one value, not two. ")
  3661. return 'fail'
  3662. coords_xy[0] *= factor
  3663. coords_xy[1] *= factor
  3664. self.options['toolchangexy'] = "%f, %f" % (coords_xy[0], coords_xy[1])
  3665. if self.options['startz'] is not None:
  3666. self.options['startz'] = float(self.options['startz']) * factor
  3667. param_list = ['cutz', 'depthperpass', 'travelz', 'feedrate', 'feedrate_z', 'feedrate_rapid',
  3668. 'endz', 'toolchangez']
  3669. if isinstance(self, FlatCAMGeometry):
  3670. temp_tools_dict = {}
  3671. tool_dia_copy = {}
  3672. data_copy = {}
  3673. for tooluid_key, tooluid_value in self.tools.items():
  3674. for dia_key, dia_value in tooluid_value.items():
  3675. if dia_key == 'tooldia':
  3676. dia_value *= factor
  3677. dia_value = float('%.4f' % dia_value)
  3678. tool_dia_copy[dia_key] = dia_value
  3679. if dia_key == 'offset':
  3680. tool_dia_copy[dia_key] = dia_value
  3681. if dia_key == 'offset_value':
  3682. dia_value *= factor
  3683. tool_dia_copy[dia_key] = dia_value
  3684. # convert the value in the Custom Tool Offset entry in UI
  3685. custom_offset = None
  3686. try:
  3687. custom_offset = float(self.ui.tool_offset_entry.get_value())
  3688. except ValueError:
  3689. # try to convert comma to decimal point. if it's still not working error message and return
  3690. try:
  3691. custom_offset = float(self.ui.tool_offset_entry.get_value().replace(',', '.')
  3692. )
  3693. except ValueError:
  3694. self.app.inform.emit("[ERROR_NOTCL]Wrong value format entered, "
  3695. "use a number.")
  3696. return
  3697. except TypeError:
  3698. pass
  3699. if custom_offset:
  3700. custom_offset *= factor
  3701. self.ui.tool_offset_entry.set_value(custom_offset)
  3702. if dia_key == 'type':
  3703. tool_dia_copy[dia_key] = dia_value
  3704. if dia_key == 'tool_type':
  3705. tool_dia_copy[dia_key] = dia_value
  3706. if dia_key == 'data':
  3707. for data_key, data_value in dia_value.items():
  3708. # convert the form fields that are convertible
  3709. for param in param_list:
  3710. if data_key == param and data_value is not None:
  3711. data_copy[data_key] = data_value * factor
  3712. # copy the other dict entries that are not convertible
  3713. if data_key not in param_list:
  3714. data_copy[data_key] = data_value
  3715. tool_dia_copy[dia_key] = copy.deepcopy(data_copy)
  3716. data_copy.clear()
  3717. temp_tools_dict.update({
  3718. tooluid_key: copy.deepcopy(tool_dia_copy)
  3719. })
  3720. tool_dia_copy.clear()
  3721. self.tools.clear()
  3722. self.tools = copy.deepcopy(temp_tools_dict)
  3723. # if there is a value in the new tool field then convert that one too
  3724. tooldia = self.ui.addtool_entry.get_value()
  3725. if tooldia:
  3726. tooldia *= factor
  3727. # limit the decimals to 2 for METRIC and 3 for INCH
  3728. if units.lower() == 'in':
  3729. tooldia = float('%.4f' % tooldia)
  3730. else:
  3731. tooldia = float('%.2f' % tooldia)
  3732. self.ui.addtool_entry.set_value(tooldia)
  3733. return factor
  3734. def plot_element(self, element, color='red', visible=None):
  3735. visible = visible if visible else self.options['plot']
  3736. try:
  3737. for sub_el in element:
  3738. self.plot_element(sub_el)
  3739. except TypeError: # Element is not iterable...
  3740. self.add_shape(shape=element, color=color, visible=visible, layer=0)
  3741. def plot(self, visible=None):
  3742. """
  3743. Adds the object into collection.
  3744. :return: None
  3745. """
  3746. # Does all the required setup and returns False
  3747. # if the 'ptint' option is set to False.
  3748. if not FlatCAMObj.plot(self):
  3749. return
  3750. try:
  3751. # plot solid geometries found as members of self.tools attribute dict
  3752. # for MultiGeo
  3753. if self.multigeo == True: # geo multi tool usage
  3754. for tooluid_key in self.tools:
  3755. solid_geometry = self.tools[tooluid_key]['solid_geometry']
  3756. self.plot_element(solid_geometry, visible=visible)
  3757. # plot solid geometry that may be an direct attribute of the geometry object
  3758. # for SingleGeo
  3759. if self.solid_geometry:
  3760. self.plot_element(self.solid_geometry, visible=visible)
  3761. # self.plot_element(self.solid_geometry, visible=self.options['plot'])
  3762. self.shapes.redraw()
  3763. except (ObjectDeleted, AttributeError):
  3764. self.shapes.clear(update=True)
  3765. def on_plot_cb_click(self, *args):
  3766. if self.muted_ui:
  3767. return
  3768. self.plot()
  3769. self.read_form_item('plot')
  3770. self.ui_disconnect()
  3771. cb_flag = self.ui.plot_cb.isChecked()
  3772. for row in range(self.ui.geo_tools_table.rowCount()):
  3773. table_cb = self.ui.geo_tools_table.cellWidget(row, 6)
  3774. if cb_flag:
  3775. table_cb.setChecked(True)
  3776. else:
  3777. table_cb.setChecked(False)
  3778. self.ui_connect()
  3779. def on_plot_cb_click_table(self):
  3780. # self.ui.cnc_tools_table.cellWidget(row, 2).widget().setCheckState(QtCore.Qt.Unchecked)
  3781. self.ui_disconnect()
  3782. cw = self.sender()
  3783. cw_index = self.ui.geo_tools_table.indexAt(cw.pos())
  3784. cw_row = cw_index.row()
  3785. check_row = 0
  3786. self.shapes.clear(update=True)
  3787. for tooluid_key in self.tools:
  3788. solid_geometry = self.tools[tooluid_key]['solid_geometry']
  3789. # find the geo_tool_table row associated with the tooluid_key
  3790. for row in range(self.ui.geo_tools_table.rowCount()):
  3791. tooluid_item = int(self.ui.geo_tools_table.item(row, 5).text())
  3792. if tooluid_item == int(tooluid_key):
  3793. check_row = row
  3794. break
  3795. if self.ui.geo_tools_table.cellWidget(check_row, 6).isChecked():
  3796. self.plot_element(element=solid_geometry, visible=True)
  3797. self.shapes.redraw()
  3798. # make sure that the general plot is disabled if one of the row plot's are disabled and
  3799. # if all the row plot's are enabled also enable the general plot checkbox
  3800. cb_cnt = 0
  3801. total_row = self.ui.geo_tools_table.rowCount()
  3802. for row in range(total_row):
  3803. if self.ui.geo_tools_table.cellWidget(row, 6).isChecked():
  3804. cb_cnt += 1
  3805. else:
  3806. cb_cnt -= 1
  3807. if cb_cnt < total_row:
  3808. self.ui.plot_cb.setChecked(False)
  3809. else:
  3810. self.ui.plot_cb.setChecked(True)
  3811. self.ui_connect()
  3812. class FlatCAMCNCjob(FlatCAMObj, CNCjob):
  3813. """
  3814. Represents G-Code.
  3815. """
  3816. optionChanged = QtCore.pyqtSignal(str)
  3817. ui_type = CNCObjectUI
  3818. def __init__(self, name, units="in", kind="generic", z_move=0.1,
  3819. feedrate=3.0, feedrate_rapid=3.0, z_cut=-0.002, tooldia=0.0,
  3820. spindlespeed=None):
  3821. FlatCAMApp.App.log.debug("Creating CNCJob object...")
  3822. CNCjob.__init__(self, units=units, kind=kind, z_move=z_move,
  3823. feedrate=feedrate, feedrate_rapid=feedrate_rapid, z_cut=z_cut, tooldia=tooldia,
  3824. spindlespeed=spindlespeed, steps_per_circle=int(self.app.defaults["cncjob_steps_per_circle"]))
  3825. FlatCAMObj.__init__(self, name)
  3826. self.kind = "cncjob"
  3827. self.options.update({
  3828. "plot": True,
  3829. "tooldia": 0.03937, # 0.4mm in inches
  3830. "append": "",
  3831. "prepend": "",
  3832. "dwell": False,
  3833. "dwelltime": 1,
  3834. "type": 'Geometry'
  3835. })
  3836. '''
  3837. This is a dict of dictionaries. Each dict is associated with a tool present in the file. The key is the
  3838. diameter of the tools and the value is another dict that will hold the data under the following form:
  3839. {tooldia: {
  3840. 'tooluid': 1,
  3841. 'offset': 'Path',
  3842. 'type_item': 'Rough',
  3843. 'tool_type': 'C1',
  3844. 'data': {} # a dict to hold the parameters
  3845. 'gcode': "" # a string with the actual GCODE
  3846. 'gcode_parsed': {} # dictionary holding the CNCJob geometry and type of geometry (cut or move)
  3847. 'solid_geometry': []
  3848. },
  3849. ...
  3850. }
  3851. It is populated in the FlatCAMGeometry.mtool_gen_cncjob()
  3852. BEWARE: I rely on the ordered nature of the Python 3.7 dictionary. Things might change ...
  3853. '''
  3854. self.cnc_tools = {}
  3855. '''
  3856. This is a dict of dictionaries. Each dict is associated with a tool present in the file. The key is the
  3857. diameter of the tools and the value is another dict that will hold the data under the following form:
  3858. {tooldia: {
  3859. 'tool': int,
  3860. 'nr_drills': int,
  3861. 'nr_slots': int,
  3862. 'offset': float,
  3863. 'data': {} # a dict to hold the parameters
  3864. 'gcode': "" # a string with the actual GCODE
  3865. 'gcode_parsed': {} # dictionary holding the CNCJob geometry and type of geometry (cut or move)
  3866. 'solid_geometry': []
  3867. },
  3868. ...
  3869. }
  3870. It is populated in the FlatCAMExcellon.on_create_cncjob_click() but actually
  3871. it's done in camlib.Excellon.generate_from_excellon_by_tool()
  3872. BEWARE: I rely on the ordered nature of the Python 3.7 dictionary. Things might change ...
  3873. '''
  3874. self.exc_cnc_tools = {}
  3875. # for now it show if the plot will be done for multi-tool CNCJob (True) or for single tool
  3876. # (like the one in the TCL Command), False
  3877. self.multitool = False
  3878. # used for parsing the GCode lines to adjust the GCode when the GCode is offseted or scaled
  3879. gcodex_re_string = r'(?=.*(X[-\+]?\d*\.\d*))'
  3880. self.g_x_re = re.compile(gcodex_re_string)
  3881. gcodey_re_string = r'(?=.*(Y[-\+]?\d*\.\d*))'
  3882. self.g_y_re = re.compile(gcodey_re_string)
  3883. gcodez_re_string = r'(?=.*(Z[-\+]?\d*\.\d*))'
  3884. self.g_z_re = re.compile(gcodez_re_string)
  3885. gcodef_re_string = r'(?=.*(F[-\+]?\d*\.\d*))'
  3886. self.g_f_re = re.compile(gcodef_re_string)
  3887. gcodet_re_string = r'(?=.*(\=\s*[-\+]?\d*\.\d*))'
  3888. self.g_t_re = re.compile(gcodet_re_string)
  3889. gcodenr_re_string = r'([+-]?\d*\.\d+)'
  3890. self.g_nr_re = re.compile(gcodenr_re_string)
  3891. # Attributes to be included in serialization
  3892. # Always append to it because it carries contents
  3893. # from predecessors.
  3894. self.ser_attrs += ['options', 'kind', 'cnc_tools', 'multitool']
  3895. self.annotation = self.app.plotcanvas.new_text_group()
  3896. def build_ui(self):
  3897. self.ui_disconnect()
  3898. FlatCAMObj.build_ui(self)
  3899. # if the FlatCAM object is Excellon don't build the CNC Tools Table but hide it
  3900. if self.cnc_tools:
  3901. self.ui.cnc_tools_table.show()
  3902. else:
  3903. self.ui.cnc_tools_table.hide()
  3904. offset = 0
  3905. tool_idx = 0
  3906. n = len(self.cnc_tools)
  3907. self.ui.cnc_tools_table.setRowCount(n)
  3908. for dia_key, dia_value in self.cnc_tools.items():
  3909. tool_idx += 1
  3910. row_no = tool_idx - 1
  3911. id = QtWidgets.QTableWidgetItem('%d' % int(tool_idx))
  3912. # id.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  3913. self.ui.cnc_tools_table.setItem(row_no, 0, id) # Tool name/id
  3914. # Make sure that the tool diameter when in MM is with no more than 2 decimals.
  3915. # There are no tool bits in MM with more than 2 decimals diameter.
  3916. # For INCH the decimals should be no more than 4. There are no tools under 10mils.
  3917. if self.units == 'MM':
  3918. dia_item = QtWidgets.QTableWidgetItem('%.2f' % float(dia_value['tooldia']))
  3919. else:
  3920. dia_item = QtWidgets.QTableWidgetItem('%.4f' % float(dia_value['tooldia']))
  3921. offset_txt = list(str(dia_value['offset']))
  3922. offset_txt[0] = offset_txt[0].upper()
  3923. offset_item = QtWidgets.QTableWidgetItem(''.join(offset_txt))
  3924. type_item = QtWidgets.QTableWidgetItem(str(dia_value['type']))
  3925. tool_type_item = QtWidgets.QTableWidgetItem(str(dia_value['tool_type']))
  3926. id.setFlags(QtCore.Qt.ItemIsEnabled)
  3927. dia_item.setFlags(QtCore.Qt.ItemIsEnabled)
  3928. offset_item.setFlags(QtCore.Qt.ItemIsEnabled)
  3929. type_item.setFlags(QtCore.Qt.ItemIsEnabled)
  3930. tool_type_item.setFlags(QtCore.Qt.ItemIsEnabled)
  3931. # hack so the checkbox stay centered in the table cell
  3932. # used this:
  3933. # https://stackoverflow.com/questions/32458111/pyqt-allign-checkbox-and-put-it-in-every-row
  3934. # plot_item = QtWidgets.QWidget()
  3935. # checkbox = FCCheckBox()
  3936. # checkbox.setCheckState(QtCore.Qt.Checked)
  3937. # qhboxlayout = QtWidgets.QHBoxLayout(plot_item)
  3938. # qhboxlayout.addWidget(checkbox)
  3939. # qhboxlayout.setAlignment(QtCore.Qt.AlignCenter)
  3940. # qhboxlayout.setContentsMargins(0, 0, 0, 0)
  3941. plot_item = FCCheckBox()
  3942. plot_item.setLayoutDirection(QtCore.Qt.RightToLeft)
  3943. tool_uid_item = QtWidgets.QTableWidgetItem(str(dia_key))
  3944. if self.ui.plot_cb.isChecked():
  3945. plot_item.setChecked(True)
  3946. self.ui.cnc_tools_table.setItem(row_no, 1, dia_item) # Diameter
  3947. self.ui.cnc_tools_table.setItem(row_no, 2, offset_item) # Offset
  3948. self.ui.cnc_tools_table.setItem(row_no, 3, type_item) # Toolpath Type
  3949. self.ui.cnc_tools_table.setItem(row_no, 4, tool_type_item) # Tool Type
  3950. ### REMEMBER: THIS COLUMN IS HIDDEN IN OBJECTUI.PY ###
  3951. self.ui.cnc_tools_table.setItem(row_no, 5, tool_uid_item) # Tool unique ID)
  3952. self.ui.cnc_tools_table.setCellWidget(row_no, 6, plot_item)
  3953. # make the diameter column editable
  3954. # for row in range(tool_idx):
  3955. # self.ui.cnc_tools_table.item(row, 1).setFlags(QtCore.Qt.ItemIsSelectable |
  3956. # QtCore.Qt.ItemIsEnabled)
  3957. for row in range(tool_idx):
  3958. self.ui.cnc_tools_table.item(row, 0).setFlags(
  3959. self.ui.cnc_tools_table.item(row, 0).flags() ^ QtCore.Qt.ItemIsSelectable)
  3960. self.ui.cnc_tools_table.resizeColumnsToContents()
  3961. self.ui.cnc_tools_table.resizeRowsToContents()
  3962. vertical_header = self.ui.cnc_tools_table.verticalHeader()
  3963. # vertical_header.setSectionResizeMode(QtWidgets.QHeaderView.ResizeToContents)
  3964. vertical_header.hide()
  3965. self.ui.cnc_tools_table.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  3966. horizontal_header = self.ui.cnc_tools_table.horizontalHeader()
  3967. horizontal_header.setMinimumSectionSize(10)
  3968. horizontal_header.setDefaultSectionSize(70)
  3969. horizontal_header.setSectionResizeMode(0, QtWidgets.QHeaderView.Fixed)
  3970. horizontal_header.resizeSection(0, 20)
  3971. horizontal_header.setSectionResizeMode(1, QtWidgets.QHeaderView.Stretch)
  3972. horizontal_header.setSectionResizeMode(3, QtWidgets.QHeaderView.ResizeToContents)
  3973. horizontal_header.setSectionResizeMode(4, QtWidgets.QHeaderView.Fixed)
  3974. horizontal_header.resizeSection(4, 40)
  3975. horizontal_header.setSectionResizeMode(6, QtWidgets.QHeaderView.Fixed)
  3976. horizontal_header.resizeSection(4, 17)
  3977. # horizontal_header.setStretchLastSection(True)
  3978. self.ui.cnc_tools_table.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  3979. self.ui.cnc_tools_table.setColumnWidth(0, 20)
  3980. self.ui.cnc_tools_table.setColumnWidth(4, 40)
  3981. self.ui.cnc_tools_table.setColumnWidth(6, 17)
  3982. # self.ui.geo_tools_table.setSortingEnabled(True)
  3983. self.ui.cnc_tools_table.setMinimumHeight(self.ui.cnc_tools_table.getHeight())
  3984. self.ui.cnc_tools_table.setMaximumHeight(self.ui.cnc_tools_table.getHeight())
  3985. self.ui_connect()
  3986. def set_ui(self, ui):
  3987. FlatCAMObj.set_ui(self, ui)
  3988. FlatCAMApp.App.log.debug("FlatCAMCNCJob.set_ui()")
  3989. assert isinstance(self.ui, CNCObjectUI), \
  3990. "Expected a CNCObjectUI, got %s" % type(self.ui)
  3991. self.form_fields.update({
  3992. "plot": self.ui.plot_cb,
  3993. # "tooldia": self.ui.tooldia_entry,
  3994. "append": self.ui.append_text,
  3995. "prepend": self.ui.prepend_text,
  3996. })
  3997. # Fill form fields only on object create
  3998. self.to_form()
  3999. # this means that the object that created this CNCJob was an Excellon
  4000. try:
  4001. if self.travel_distance:
  4002. self.ui.t_distance_label.show()
  4003. self.ui.t_distance_entry.setVisible(True)
  4004. self.ui.t_distance_entry.setDisabled(True)
  4005. self.ui.t_distance_entry.set_value('%.4f' % float(self.travel_distance))
  4006. self.ui.units_label.setText(str(self.units).lower())
  4007. self.ui.units_label.setDisabled(True)
  4008. except AttributeError:
  4009. pass
  4010. # set the kind of geometries are plotted by default with plot2() from camlib.CNCJob
  4011. self.ui.cncplot_method_combo.set_value(self.app.defaults["cncjob_plot_kind"])
  4012. # Show/Hide Advanced Options
  4013. if self.app.defaults["global_advanced"] is False:
  4014. self.ui.level.setText('<span style="color:green;"><b>BASIC Mode</b></span>')
  4015. else:
  4016. self.ui.level.setText('<span style="color:red;"><b>ADVANCED Mode</b></span>')
  4017. self.ui.updateplot_button.clicked.connect(self.on_updateplot_button_click)
  4018. self.ui.export_gcode_button.clicked.connect(self.on_exportgcode_button_click)
  4019. self.ui.modify_gcode_button.clicked.connect(self.on_modifygcode_button_click)
  4020. self.ui.cncplot_method_combo.activated_custom.connect(self.on_plot_kind_change)
  4021. def ui_connect(self):
  4022. for row in range(self.ui.cnc_tools_table.rowCount()):
  4023. self.ui.cnc_tools_table.cellWidget(row, 6).clicked.connect(self.on_plot_cb_click_table)
  4024. self.ui.plot_cb.stateChanged.connect(self.on_plot_cb_click)
  4025. def ui_disconnect(self):
  4026. for row in range(self.ui.cnc_tools_table.rowCount()):
  4027. self.ui.cnc_tools_table.cellWidget(row, 6).clicked.disconnect(self.on_plot_cb_click_table)
  4028. try:
  4029. self.ui.plot_cb.stateChanged.disconnect(self.on_plot_cb_click)
  4030. except:
  4031. pass
  4032. def on_updateplot_button_click(self, *args):
  4033. """
  4034. Callback for the "Updata Plot" button. Reads the form for updates
  4035. and plots the object.
  4036. """
  4037. self.read_form()
  4038. self.plot()
  4039. def on_plot_kind_change(self):
  4040. kind = self.ui.cncplot_method_combo.get_value()
  4041. self.plot(kind=kind)
  4042. def on_exportgcode_button_click(self, *args):
  4043. self.app.report_usage("cncjob_on_exportgcode_button")
  4044. self.read_form()
  4045. name = self.app.collection.get_active().options['name']
  4046. if 'Roland' in self.pp_excellon_name or 'Roland' in self.pp_geometry_name:
  4047. _filter_ = "RML1 Files (*.rol);;" \
  4048. "All Files (*.*)"
  4049. elif 'hpgl' in self.pp_geometry_name:
  4050. _filter_ = "HPGL Files (*.plt);;" \
  4051. "All Files (*.*)"
  4052. else:
  4053. _filter_ = "G-Code Files (*.nc);;G-Code Files (*.txt);;G-Code Files (*.tap);;G-Code Files (*.cnc);;" \
  4054. "G-Code Files (*.g-code);;All Files (*.*)"
  4055. try:
  4056. dir_file_to_save = self.app.get_last_save_folder() + '/' + str(name)
  4057. filename, _ = QtWidgets.QFileDialog.getSaveFileName(
  4058. caption="Export Machine Code ...",
  4059. directory=dir_file_to_save,
  4060. filter=_filter_
  4061. )
  4062. except TypeError:
  4063. filename, _ = QtWidgets.QFileDialog.getSaveFileName(caption="Export Machine Code ...", filter=_filter_)
  4064. filename = str(filename)
  4065. if filename == '':
  4066. self.app.inform.emit("[WARNING_NOTCL]Export Machine Code cancelled ...")
  4067. return
  4068. preamble = str(self.ui.prepend_text.get_value())
  4069. postamble = str(self.ui.append_text.get_value())
  4070. self.export_gcode(filename, preamble=preamble, postamble=postamble)
  4071. self.app.file_saved.emit("gcode", filename)
  4072. self.app.inform.emit("[success] Machine Code file saved to: %s" % filename)
  4073. def on_modifygcode_button_click(self, *args):
  4074. # add the tab if it was closed
  4075. self.app.ui.plot_tab_area.addTab(self.app.ui.cncjob_tab, "Code Editor")
  4076. # delete the absolute and relative position and messages in the infobar
  4077. self.app.ui.position_label.setText("")
  4078. self.app.ui.rel_position_label.setText("")
  4079. # Switch plot_area to CNCJob tab
  4080. self.app.ui.plot_tab_area.setCurrentWidget(self.app.ui.cncjob_tab)
  4081. preamble = str(self.ui.prepend_text.get_value())
  4082. postamble = str(self.ui.append_text.get_value())
  4083. self.app.gcode_edited = self.export_gcode(preamble=preamble, postamble=postamble, to_file=True)
  4084. # first clear previous text in text editor (if any)
  4085. self.app.ui.code_editor.clear()
  4086. # then append the text from GCode to the text editor
  4087. try:
  4088. for line in self.app.gcode_edited:
  4089. proc_line = str(line).strip('\n')
  4090. self.app.ui.code_editor.append(proc_line)
  4091. except Exception as e:
  4092. log.debug('FlatCAMCNNJob.on_modifygcode_button_click() -->%s' % str(e))
  4093. self.app.inform.emit('[ERROR]FlatCAMCNNJob.on_modifygcode_button_click() -->%s' % str(e))
  4094. return
  4095. self.app.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  4096. self.app.handleTextChanged()
  4097. self.app.ui.show()
  4098. def gcode_header(self):
  4099. log.debug("FlatCAMCNCJob.gcode_header()")
  4100. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  4101. marlin = False
  4102. hpgl = False
  4103. probe_pp = False
  4104. try:
  4105. for key in self.cnc_tools:
  4106. if self.cnc_tools[key]['data']['ppname_g'] == 'marlin':
  4107. marlin = True
  4108. break
  4109. if self.cnc_tools[key]['data']['ppname_g'] == 'hpgl':
  4110. hpgl = True
  4111. break
  4112. if "toolchange_probe" in self.cnc_tools[key]['data']['ppname_g'].lower():
  4113. probe_pp = True
  4114. break
  4115. except Exception as e:
  4116. log.debug("FlatCAMCNCJob.gcode_header() error: --> %s" % str(e))
  4117. try:
  4118. if self.options['ppname_e'] == 'marlin':
  4119. marlin = True
  4120. except Exception as e:
  4121. log.debug("FlatCAMCNCJob.gcode_header(): --> There is no such self.option: %s" % str(e))
  4122. try:
  4123. if "toolchange_probe" in self.options['ppname_e'].lower():
  4124. probe_pp = True
  4125. except Exception as e:
  4126. log.debug("FlatCAMCNCJob.gcode_header(): --> There is no such self.option: %s" % str(e))
  4127. if marlin is True:
  4128. gcode = ';Marlin G-CODE GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s\n' % \
  4129. (str(self.app.version), str(self.app.version_date)) + '\n'
  4130. gcode += ';Name: ' + str(self.options['name']) + '\n'
  4131. gcode += ';Type: ' + "G-code from " + str(self.options['type']) + '\n'
  4132. # if str(p['options']['type']) == 'Excellon' or str(p['options']['type']) == 'Excellon Geometry':
  4133. # gcode += '(Tools in use: ' + str(p['options']['Tools_in_use']) + ')\n'
  4134. gcode += ';Units: ' + self.units.upper() + '\n' + "\n"
  4135. gcode += ';Created on ' + time_str + '\n' + '\n'
  4136. elif hpgl is True:
  4137. gcode = 'CO "HPGL CODE GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s' % \
  4138. (str(self.app.version), str(self.app.version_date)) + '";\n'
  4139. gcode += 'CO "Name: ' + str(self.options['name']) + '";\n'
  4140. gcode += 'CO "Type: ' + "HPGL code from " + str(self.options['type']) + '";\n'
  4141. # if str(p['options']['type']) == 'Excellon' or str(p['options']['type']) == 'Excellon Geometry':
  4142. # gcode += '(Tools in use: ' + str(p['options']['Tools_in_use']) + ')\n'
  4143. gcode += 'CO "Units: ' + self.units.upper() + '";\n'
  4144. gcode += 'CO "Created on ' + time_str + '";\n'
  4145. elif probe_pp is True:
  4146. gcode = '(G-CODE GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s)\n' % \
  4147. (str(self.app.version), str(self.app.version_date)) + '\n'
  4148. gcode += '(This GCode tool change is done by using a Probe.)\n' \
  4149. '(Make sure that before you start the job you first do a rough zero for Z axis.)\n' \
  4150. '(This means that you need to zero the CNC axis and then jog to the toolchange X, Y location,)\n' \
  4151. '(mount the probe and adjust the Z so more or less the probe tip touch the plate. ' \
  4152. 'Then zero the Z axis.)\n' + '\n'
  4153. gcode += '(Name: ' + str(self.options['name']) + ')\n'
  4154. gcode += '(Type: ' + "G-code from " + str(self.options['type']) + ')\n'
  4155. # if str(p['options']['type']) == 'Excellon' or str(p['options']['type']) == 'Excellon Geometry':
  4156. # gcode += '(Tools in use: ' + str(p['options']['Tools_in_use']) + ')\n'
  4157. gcode += '(Units: ' + self.units.upper() + ')\n' + "\n"
  4158. gcode += '(Created on ' + time_str + ')\n' + '\n'
  4159. else:
  4160. gcode = '(G-CODE GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s)\n' % \
  4161. (str(self.app.version), str(self.app.version_date)) + '\n'
  4162. gcode += '(Name: ' + str(self.options['name']) + ')\n'
  4163. gcode += '(Type: ' + "G-code from " + str(self.options['type']) + ')\n'
  4164. # if str(p['options']['type']) == 'Excellon' or str(p['options']['type']) == 'Excellon Geometry':
  4165. # gcode += '(Tools in use: ' + str(p['options']['Tools_in_use']) + ')\n'
  4166. gcode += '(Units: ' + self.units.upper() + ')\n' + "\n"
  4167. gcode += '(Created on ' + time_str + ')\n' + '\n'
  4168. return gcode
  4169. def export_gcode(self, filename=None, preamble='', postamble='', to_file=False):
  4170. gcode = ''
  4171. roland = False
  4172. hpgl = False
  4173. # detect if using Roland postprocessor
  4174. try:
  4175. for key in self.cnc_tools:
  4176. if self.cnc_tools[key]['data']['ppname_g'] == 'Roland_MDX_20':
  4177. roland = True
  4178. break
  4179. if self.cnc_tools[key]['data']['ppname_g'] == 'hpgl':
  4180. hpgl = True
  4181. break
  4182. except:
  4183. try:
  4184. for key in self.cnc_tools:
  4185. if self.cnc_tools[key]['data']['ppname_e'] == 'Roland_MDX_20':
  4186. roland = True
  4187. break
  4188. except:
  4189. pass
  4190. # do not add gcode_header when using the Roland postprocessor, add it for every other postprocessor
  4191. if roland is False and hpgl is False:
  4192. gcode = self.gcode_header()
  4193. # detect if using multi-tool and make the Gcode summation correctly for each case
  4194. if self.multitool is True:
  4195. for tooluid_key in self.cnc_tools:
  4196. for key, value in self.cnc_tools[tooluid_key].items():
  4197. if key == 'gcode':
  4198. gcode += value
  4199. break
  4200. else:
  4201. gcode += self.gcode
  4202. if roland is True:
  4203. g = preamble + gcode + postamble
  4204. elif hpgl is True:
  4205. g = self.gcode_header() + preamble + gcode + postamble
  4206. else:
  4207. # fix so the preamble gets inserted in between the comments header and the actual start of GCODE
  4208. g_idx = gcode.rfind('G20')
  4209. # if it did not find 'G20' then search for 'G21'
  4210. if g_idx == -1:
  4211. g_idx = gcode.rfind('G21')
  4212. # if it did not find 'G20' and it did not find 'G21' then there is an error and return
  4213. if g_idx == -1:
  4214. self.app.inform.emit("[ERROR_NOTCL] G-code does not have a units code: either G20 or G21")
  4215. return
  4216. g = gcode[:g_idx] + preamble + '\n' + gcode[g_idx:] + postamble
  4217. # lines = StringIO(self.gcode)
  4218. lines = StringIO(g)
  4219. ## Write
  4220. if filename is not None:
  4221. try:
  4222. with open(filename, 'w') as f:
  4223. for line in lines:
  4224. f.write(line)
  4225. except FileNotFoundError:
  4226. self.app.inform.emit("[WARNING_NOTCL] No such file or directory")
  4227. return
  4228. elif to_file is False:
  4229. # Just for adding it to the recent files list.
  4230. self.app.file_opened.emit("cncjob", filename)
  4231. self.app.file_saved.emit("cncjob", filename)
  4232. self.app.inform.emit("[success] Saved to: " + filename)
  4233. else:
  4234. return lines
  4235. def get_gcode(self, preamble='', postamble=''):
  4236. #we need this to be able get_gcode separatelly for shell command export_gcode
  4237. return preamble + '\n' + self.gcode + "\n" + postamble
  4238. def get_svg(self):
  4239. # we need this to be able get_svg separately for shell command export_svg
  4240. pass
  4241. def on_plot_cb_click(self, *args):
  4242. if self.muted_ui:
  4243. return
  4244. kind = self.ui.cncplot_method_combo.get_value()
  4245. self.plot(kind=kind)
  4246. self.read_form_item('plot')
  4247. self.ui_disconnect()
  4248. cb_flag = self.ui.plot_cb.isChecked()
  4249. for row in range(self.ui.cnc_tools_table.rowCount()):
  4250. table_cb = self.ui.cnc_tools_table.cellWidget(row, 6)
  4251. if cb_flag:
  4252. table_cb.setChecked(True)
  4253. else:
  4254. table_cb.setChecked(False)
  4255. self.ui_connect()
  4256. def on_plot_cb_click_table(self):
  4257. # self.ui.cnc_tools_table.cellWidget(row, 2).widget().setCheckState(QtCore.Qt.Unchecked)
  4258. self.ui_disconnect()
  4259. cw = self.sender()
  4260. cw_index = self.ui.cnc_tools_table.indexAt(cw.pos())
  4261. cw_row = cw_index.row()
  4262. self.shapes.clear(update=True)
  4263. for tooluid_key in self.cnc_tools:
  4264. tooldia = float('%.4f' % float(self.cnc_tools[tooluid_key]['tooldia']))
  4265. gcode_parsed = self.cnc_tools[tooluid_key]['gcode_parsed']
  4266. # tool_uid = int(self.ui.cnc_tools_table.item(cw_row, 3).text())
  4267. for r in range(self.ui.cnc_tools_table.rowCount()):
  4268. if int(self.ui.cnc_tools_table.item(r, 5).text()) == int(tooluid_key):
  4269. if self.ui.cnc_tools_table.cellWidget(r, 6).isChecked():
  4270. self.plot2(tooldia=tooldia, obj=self, visible=True, gcode_parsed=gcode_parsed)
  4271. self.shapes.redraw()
  4272. # make sure that the general plot is disabled if one of the row plot's are disabled and
  4273. # if all the row plot's are enabled also enable the general plot checkbox
  4274. cb_cnt = 0
  4275. total_row = self.ui.cnc_tools_table.rowCount()
  4276. for row in range(total_row):
  4277. if self.ui.cnc_tools_table.cellWidget(row, 6).isChecked():
  4278. cb_cnt += 1
  4279. else:
  4280. cb_cnt -= 1
  4281. if cb_cnt < total_row:
  4282. self.ui.plot_cb.setChecked(False)
  4283. else:
  4284. self.ui.plot_cb.setChecked(True)
  4285. self.ui_connect()
  4286. def plot(self, visible=None, kind='all'):
  4287. # Does all the required setup and returns False
  4288. # if the 'ptint' option is set to False.
  4289. if not FlatCAMObj.plot(self):
  4290. return
  4291. visible = visible if visible else self.options['plot']
  4292. try:
  4293. if self.multitool is False: # single tool usage
  4294. self.plot2(tooldia=float(self.options["tooldia"]), obj=self, visible=visible, kind=kind)
  4295. else:
  4296. # multiple tools usage
  4297. for tooluid_key in self.cnc_tools:
  4298. tooldia = float('%.4f' % float(self.cnc_tools[tooluid_key]['tooldia']))
  4299. gcode_parsed = self.cnc_tools[tooluid_key]['gcode_parsed']
  4300. self.plot2(tooldia=tooldia, obj=self, visible=visible, gcode_parsed=gcode_parsed, kind=kind)
  4301. self.shapes.redraw()
  4302. except (ObjectDeleted, AttributeError):
  4303. self.shapes.clear(update=True)
  4304. self.annotation.clear(update=True)
  4305. def convert_units(self, units):
  4306. factor = CNCjob.convert_units(self, units)
  4307. FlatCAMApp.App.log.debug("FlatCAMCNCjob.convert_units()")
  4308. self.options["tooldia"] = float(self.options["tooldia"]) * factor
  4309. param_list = ['cutz', 'depthperpass', 'travelz', 'feedrate', 'feedrate_z', 'feedrate_rapid',
  4310. 'endz', 'toolchangez']
  4311. temp_tools_dict = {}
  4312. tool_dia_copy = {}
  4313. data_copy = {}
  4314. for tooluid_key, tooluid_value in self.cnc_tools.items():
  4315. for dia_key, dia_value in tooluid_value.items():
  4316. if dia_key == 'tooldia':
  4317. dia_value *= factor
  4318. dia_value = float('%.4f' % dia_value)
  4319. tool_dia_copy[dia_key] = dia_value
  4320. if dia_key == 'offset':
  4321. tool_dia_copy[dia_key] = dia_value
  4322. if dia_key == 'offset_value':
  4323. dia_value *= factor
  4324. tool_dia_copy[dia_key] = dia_value
  4325. if dia_key == 'type':
  4326. tool_dia_copy[dia_key] = dia_value
  4327. if dia_key == 'tool_type':
  4328. tool_dia_copy[dia_key] = dia_value
  4329. if dia_key == 'data':
  4330. for data_key, data_value in dia_value.items():
  4331. # convert the form fields that are convertible
  4332. for param in param_list:
  4333. if data_key == param and data_value is not None:
  4334. data_copy[data_key] = data_value * factor
  4335. # copy the other dict entries that are not convertible
  4336. if data_key not in param_list:
  4337. data_copy[data_key] = data_value
  4338. tool_dia_copy[dia_key] = copy.deepcopy(data_copy)
  4339. data_copy.clear()
  4340. if dia_key == 'gcode':
  4341. tool_dia_copy[dia_key] = dia_value
  4342. if dia_key == 'gcode_parsed':
  4343. tool_dia_copy[dia_key] = dia_value
  4344. if dia_key == 'solid_geometry':
  4345. tool_dia_copy[dia_key] = dia_value
  4346. # if dia_key == 'solid_geometry':
  4347. # tool_dia_copy[dia_key] = affinity.scale(dia_value, xfact=factor, origin=(0, 0))
  4348. # if dia_key == 'gcode_parsed':
  4349. # for g in dia_value:
  4350. # g['geom'] = affinity.scale(g['geom'], factor, factor, origin=(0, 0))
  4351. #
  4352. # tool_dia_copy['gcode_parsed'] = copy.deepcopy(dia_value)
  4353. # tool_dia_copy['solid_geometry'] = cascaded_union([geo['geom'] for geo in dia_value])
  4354. temp_tools_dict.update({
  4355. tooluid_key: copy.deepcopy(tool_dia_copy)
  4356. })
  4357. tool_dia_copy.clear()
  4358. self.cnc_tools.clear()
  4359. self.cnc_tools = copy.deepcopy(temp_tools_dict)
  4360. # end of file