FlatCAMObj.py 217 KB

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