FlatCAMObj.py 250 KB

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