FlatCAMObj.py 251 KB

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