FlatCAMObj.py 208 KB

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