FlatCAMObj.py 234 KB

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