FlatCAMObj.py 235 KB

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