FlatCAMObj.py 224 KB

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