FlatCAMObj.py 169 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217
  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. from copy import copy, deepcopy
  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(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=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. "ncctools": "1.0, 0.5",
  319. "nccoverlap": 0.4,
  320. "nccmargin": 1,
  321. "noncoppermargin": 0.0,
  322. "noncopperrounded": False,
  323. "bboxmargin": 0.0,
  324. "bboxrounded": False
  325. })
  326. # type of isolation: 0 = exteriors, 1 = interiors, 2 = complete isolation (both interiors and exteriors)
  327. self.iso_type = 2
  328. # Attributes to be included in serialization
  329. # Always append to it because it carries contents
  330. # from predecessors.
  331. self.ser_attrs += ['options', 'kind']
  332. self.multigeo = False
  333. # assert isinstance(self.ui, GerberObjectUI)
  334. # self.ui.plot_cb.stateChanged.connect(self.on_plot_cb_click)
  335. # self.ui.solid_cb.stateChanged.connect(self.on_solid_cb_click)
  336. # self.ui.multicolored_cb.stateChanged.connect(self.on_multicolored_cb_click)
  337. # self.ui.generate_iso_button.clicked.connect(self.on_iso_button_click)
  338. # self.ui.generate_cutout_button.clicked.connect(self.on_generatecutout_button_click)
  339. # self.ui.generate_bb_button.clicked.connect(self.on_generatebb_button_click)
  340. # self.ui.generate_noncopper_button.clicked.connect(self.on_generatenoncopper_button_click)
  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. def on_generatenoncopper_button_click(self, *args):
  379. self.app.report_usage("gerber_on_generatenoncopper_button")
  380. self.read_form()
  381. name = self.options["name"] + "_noncopper"
  382. def geo_init(geo_obj, app_obj):
  383. assert isinstance(geo_obj, FlatCAMGeometry)
  384. bounding_box = self.solid_geometry.envelope.buffer(self.options["noncoppermargin"])
  385. if not self.options["noncopperrounded"]:
  386. bounding_box = bounding_box.envelope
  387. non_copper = bounding_box.difference(self.solid_geometry)
  388. geo_obj.solid_geometry = non_copper
  389. # TODO: Check for None
  390. self.app.new_object("geometry", name, geo_init)
  391. def on_generatebb_button_click(self, *args):
  392. self.app.report_usage("gerber_on_generatebb_button")
  393. self.read_form()
  394. name = self.options["name"] + "_bbox"
  395. def geo_init(geo_obj, app_obj):
  396. assert isinstance(geo_obj, FlatCAMGeometry)
  397. # Bounding box with rounded corners
  398. bounding_box = self.solid_geometry.envelope.buffer(self.options["bboxmargin"])
  399. if not self.options["bboxrounded"]: # Remove rounded corners
  400. bounding_box = bounding_box.envelope
  401. geo_obj.solid_geometry = bounding_box
  402. self.app.new_object("geometry", name, geo_init)
  403. def on_ext_iso_button_click(self, *args):
  404. if self.ui.follow_cb.get_value() == True:
  405. obj = self.app.collection.get_active()
  406. obj.follow()
  407. # in the end toggle the visibility of the origin object so we can see the generated Geometry
  408. obj.ui.plot_cb.toggle()
  409. else:
  410. self.app.report_usage("gerber_on_iso_button")
  411. self.read_form()
  412. self.isolate(iso_type=0)
  413. def on_int_iso_button_click(self, *args):
  414. if self.ui.follow_cb.get_value() == True:
  415. obj = self.app.collection.get_active()
  416. obj.follow()
  417. # in the end toggle the visibility of the origin object so we can see the generated Geometry
  418. obj.ui.plot_cb.toggle()
  419. else:
  420. self.app.report_usage("gerber_on_iso_button")
  421. self.read_form()
  422. self.isolate(iso_type=1)
  423. def on_iso_button_click(self, *args):
  424. if self.ui.follow_cb.get_value() == True:
  425. obj = self.app.collection.get_active()
  426. obj.follow()
  427. # in the end toggle the visibility of the origin object so we can see the generated Geometry
  428. obj.ui.plot_cb.toggle()
  429. else:
  430. self.app.report_usage("gerber_on_iso_button")
  431. self.read_form()
  432. self.isolate()
  433. def follow(self, outname=None):
  434. """
  435. Creates a geometry object "following" the gerber paths.
  436. :return: None
  437. """
  438. # default_name = self.options["name"] + "_follow"
  439. # follow_name = outname or default_name
  440. if outname is None:
  441. follow_name = self.options["name"] + "_follow"
  442. else:
  443. follow_name = outname
  444. def follow_init(follow_obj, app):
  445. # Propagate options
  446. follow_obj.options["cnctooldia"] = self.options["isotooldia"]
  447. follow_obj.solid_geometry = self.solid_geometry
  448. # TODO: Do something if this is None. Offer changing name?
  449. try:
  450. self.app.new_object("geometry", follow_name, follow_init)
  451. except Exception as e:
  452. return "Operation failed: %s" % str(e)
  453. def isolate(self, iso_type=None, dia=None, passes=None, overlap=None,
  454. outname=None, combine=None, milling_type=None):
  455. """
  456. Creates an isolation routing geometry object in the project.
  457. :param iso_type: type of isolation to be done: 0 = exteriors, 1 = interiors and 2 = both
  458. :param dia: Tool diameter
  459. :param passes: Number of tool widths to cut
  460. :param overlap: Overlap between passes in fraction of tool diameter
  461. :param outname: Base name of the output object
  462. :return: None
  463. """
  464. if dia is None:
  465. dia = self.options["isotooldia"]
  466. if passes is None:
  467. passes = int(self.options["isopasses"])
  468. if overlap is None:
  469. overlap = self.options["isooverlap"]
  470. if combine is None:
  471. combine = self.options["combine_passes"]
  472. else:
  473. combine = bool(combine)
  474. if milling_type is None:
  475. milling_type = self.options["milling_type"]
  476. if iso_type is None:
  477. self.iso_type = 2
  478. else:
  479. self.iso_type = iso_type
  480. base_name = self.options["name"] + "_iso"
  481. base_name = outname or base_name
  482. def generate_envelope(offset, invert, envelope_iso_type=2):
  483. # isolation_geometry produces an envelope that is going on the left of the geometry
  484. # (the copper features). To leave the least amount of burrs on the features
  485. # the tool needs to travel on the right side of the features (this is called conventional milling)
  486. # the first pass is the one cutting all of the features, so it needs to be reversed
  487. # the other passes overlap preceding ones and cut the left over copper. It is better for them
  488. # to cut on the right side of the left over copper i.e on the left side of the features.
  489. try:
  490. geom = self.isolation_geometry(offset, iso_type=envelope_iso_type)
  491. except Exception as e:
  492. log.debug(str(e))
  493. return 'fail'
  494. if invert:
  495. try:
  496. if type(geom) is MultiPolygon:
  497. pl = []
  498. for p in geom:
  499. pl.append(Polygon(p.exterior.coords[::-1], p.interiors))
  500. geom = MultiPolygon(pl)
  501. elif type(geom) is Polygon:
  502. geom = Polygon(geom.exterior.coords[::-1], geom.interiors)
  503. else:
  504. log.debug("FlatCAMGerber.isolate().generate_envelope() Error --> Unexpected Geometry")
  505. except Exception as e:
  506. log.debug("FlatCAMGerber.isolate().generate_envelope() Error --> %s" % str(e))
  507. return geom
  508. if combine:
  509. if self.iso_type == 0:
  510. iso_name = self.options["name"] + "_ext_iso"
  511. elif self.iso_type == 1:
  512. iso_name = self.options["name"] + "_int_iso"
  513. else:
  514. iso_name = base_name
  515. # TODO: This is ugly. Create way to pass data into init function.
  516. def iso_init(geo_obj, app_obj):
  517. # Propagate options
  518. geo_obj.options["cnctooldia"] = self.options["isotooldia"]
  519. geo_obj.solid_geometry = []
  520. for i in range(passes):
  521. iso_offset = (((2 * i + 1) / 2.0) * dia) - (i * overlap * dia)
  522. # if milling type is climb then the move is counter-clockwise around features
  523. if milling_type == 'cl':
  524. # geom = generate_envelope (offset, i == 0)
  525. geom = generate_envelope(iso_offset, 1, envelope_iso_type=self.iso_type)
  526. else:
  527. geom = generate_envelope(iso_offset, 0, envelope_iso_type=self.iso_type)
  528. geo_obj.solid_geometry.append(geom)
  529. # detect if solid_geometry is empty and this require list flattening which is "heavy"
  530. # or just looking in the lists (they are one level depth) and if any is not empty
  531. # proceed with object creation, if there are empty and the number of them is the length
  532. # of the list then we have an empty solid_geometry which should raise a Custom Exception
  533. empty_cnt = 0
  534. if not isinstance(geo_obj.solid_geometry, list):
  535. geo_obj.solid_geometry = [geo_obj.solid_geometry]
  536. for g in geo_obj.solid_geometry:
  537. if g:
  538. app_obj.inform.emit("[success]Isolation geometry created: %s" % geo_obj.options["name"])
  539. break
  540. else:
  541. empty_cnt += 1
  542. if empty_cnt == len(geo_obj.solid_geometry):
  543. raise ValidationError("Empty Geometry", None)
  544. geo_obj.multigeo = False
  545. # TODO: Do something if this is None. Offer changing name?
  546. self.app.new_object("geometry", iso_name, iso_init)
  547. else:
  548. for i in range(passes):
  549. offset = (2 * i + 1) / 2.0 * dia - i * overlap * dia
  550. if passes > 1:
  551. if self.iso_type == 0:
  552. iso_name = self.options["name"] + "_ext_iso" + str(i + 1)
  553. elif self.iso_type == 1:
  554. iso_name = self.options["name"] + "_int_iso" + str(i + 1)
  555. else:
  556. iso_name = base_name + str(i + 1)
  557. else:
  558. if self.iso_type == 0:
  559. iso_name = self.options["name"] + "_ext_iso"
  560. elif self.iso_type == 1:
  561. iso_name = self.options["name"] + "_int_iso"
  562. else:
  563. iso_name = base_name
  564. # TODO: This is ugly. Create way to pass data into init function.
  565. def iso_init(geo_obj, app_obj):
  566. # Propagate options
  567. geo_obj.options["cnctooldia"] = self.options["isotooldia"]
  568. # if milling type is climb then the move is counter-clockwise around features
  569. if milling_type == 'cl':
  570. # geo_obj.solid_geometry = generate_envelope(offset, i == 0)
  571. geo_obj.solid_geometry = generate_envelope(offset, 1, envelope_iso_type=self.iso_type)
  572. else:
  573. geo_obj.solid_geometry = generate_envelope(offset, 0, envelope_iso_type=self.iso_type)
  574. # detect if solid_geometry is empty and this require list flattening which is "heavy"
  575. # or just looking in the lists (they are one level depth) and if any is not empty
  576. # proceed with object creation, if there are empty and the number of them is the length
  577. # of the list then we have an empty solid_geometry which should raise a Custom Exception
  578. empty_cnt = 0
  579. if not isinstance(geo_obj.solid_geometry, list):
  580. geo_obj.solid_geometry = [geo_obj.solid_geometry]
  581. for g in geo_obj.solid_geometry:
  582. if g:
  583. app_obj.inform.emit("[success]Isolation geometry created: %s" % geo_obj.options["name"])
  584. break
  585. else:
  586. empty_cnt += 1
  587. if empty_cnt == len(geo_obj.solid_geometry):
  588. raise ValidationError("Empty Geometry", None)
  589. geo_obj.multigeo = False
  590. # TODO: Do something if this is None. Offer changing name?
  591. self.app.new_object("geometry", iso_name, iso_init)
  592. def on_plot_cb_click(self, *args):
  593. if self.muted_ui:
  594. return
  595. self.read_form_item('plot')
  596. def on_solid_cb_click(self, *args):
  597. if self.muted_ui:
  598. return
  599. self.read_form_item('solid')
  600. self.plot()
  601. def on_multicolored_cb_click(self, *args):
  602. if self.muted_ui:
  603. return
  604. self.read_form_item('multicolored')
  605. self.plot()
  606. def convert_units(self, units):
  607. """
  608. Converts the units of the object by scaling dimensions in all geometry
  609. and options.
  610. :param units: Units to which to convert the object: "IN" or "MM".
  611. :type units: str
  612. :return: None
  613. :rtype: None
  614. """
  615. factor = Gerber.convert_units(self, units)
  616. self.options['isotooldia'] *= factor
  617. self.options['cutoutmargin'] *= factor
  618. self.options['cutoutgapsize'] *= factor
  619. self.options['noncoppermargin'] *= factor
  620. self.options['bboxmargin'] *= factor
  621. def plot(self, **kwargs):
  622. """
  623. :param kwargs: color and face_color
  624. :return:
  625. """
  626. FlatCAMApp.App.log.debug(str(inspect.stack()[1][3]) + " --> FlatCAMGerber.plot()")
  627. # Does all the required setup and returns False
  628. # if the 'ptint' option is set to False.
  629. if not FlatCAMObj.plot(self):
  630. return
  631. if 'color' in kwargs:
  632. color = kwargs['color']
  633. else:
  634. color = self.app.defaults['global_plot_line']
  635. if 'face_color' in kwargs:
  636. face_color = kwargs['face_color']
  637. else:
  638. face_color = self.app.defaults['global_plot_fill']
  639. geometry = self.solid_geometry
  640. # Make sure geometry is iterable.
  641. try:
  642. _ = iter(geometry)
  643. except TypeError:
  644. geometry = [geometry]
  645. def random_color():
  646. color = np.random.rand(4)
  647. color[3] = 1
  648. return color
  649. try:
  650. if self.options["solid"]:
  651. for g in geometry:
  652. if type(g) == Polygon or type(g) == LineString:
  653. self.add_shape(shape=g, color=color,
  654. face_color=random_color() if self.options['multicolored']
  655. else face_color, visible=self.options['plot'])
  656. else:
  657. for el in g:
  658. self.add_shape(shape=el, color=color,
  659. face_color=random_color() if self.options['multicolored']
  660. else face_color, visible=self.options['plot'])
  661. else:
  662. for g in geometry:
  663. if type(g) == Polygon or type(g) == LineString:
  664. self.add_shape(shape=g, color=random_color() if self.options['multicolored'] else 'black',
  665. visible=self.options['plot'])
  666. else:
  667. for el in g:
  668. self.add_shape(shape=el, color=random_color() if self.options['multicolored'] else 'black',
  669. visible=self.options['plot'])
  670. self.shapes.redraw()
  671. except (ObjectDeleted, AttributeError):
  672. self.shapes.clear(update=True)
  673. def serialize(self):
  674. return {
  675. "options": self.options,
  676. "kind": self.kind
  677. }
  678. class FlatCAMExcellon(FlatCAMObj, Excellon):
  679. """
  680. Represents Excellon/Drill code.
  681. """
  682. ui_type = ExcellonObjectUI
  683. optionChanged = QtCore.pyqtSignal(str)
  684. def __init__(self, name):
  685. Excellon.__init__(self, geo_steps_per_circle=self.app.defaults["geometry_circle_steps"])
  686. FlatCAMObj.__init__(self, name)
  687. self.kind = "excellon"
  688. self.options.update({
  689. "plot": True,
  690. "solid": False,
  691. "drillz": -0.1,
  692. "travelz": 0.1,
  693. "feedrate": 5.0,
  694. "feedrate_rapid": 5.0,
  695. "tooldia": 0.1,
  696. "slot_tooldia": 0.1,
  697. "toolchange": False,
  698. "toolchangez": 1.0,
  699. "toolchangexy": "0.0, 0.0",
  700. "endz": 2.0,
  701. "startz": None,
  702. "spindlespeed": None,
  703. "dwell": True,
  704. "dwelltime": 1000,
  705. "ppname_e": 'defaults',
  706. "optimization_type": "R",
  707. "gcode_type": "drills"
  708. })
  709. # TODO: Document this.
  710. self.tool_cbs = {}
  711. # Attributes to be included in serialization
  712. # Always append to it because it carries contents
  713. # from predecessors.
  714. self.ser_attrs += ['options', 'kind']
  715. # variable to store the total amount of drills per job
  716. self.tot_drill_cnt = 0
  717. self.tool_row = 0
  718. # variable to store the total amount of slots per job
  719. self.tot_slot_cnt = 0
  720. self.tool_row_slots = 0
  721. self.multigeo = False
  722. @staticmethod
  723. def merge(exc_list, exc_final):
  724. """
  725. Merge Excellon objects found in exc_list parameter into exc_final object.
  726. Options are always copied from source .
  727. Tools are disregarded, what is taken in consideration is the unique drill diameters found as values in the
  728. exc_list tools dict's. In the reconstruction section for each unique tool diameter it will be created a
  729. tool_name to be used in the final Excellon object, exc_final.
  730. If only one object is in exc_list parameter then this function will copy that object in the exc_final
  731. :param exc_list: List or one object of FlatCAMExcellon Objects to join.
  732. :param exc_final: Destination FlatCAMExcellon object.
  733. :return: None
  734. """
  735. # flag to signal that we need to reorder the tools dictionary and drills and slots lists
  736. flag_order = False
  737. try:
  738. flattened_list = list(itertools.chain(*exc_list))
  739. except TypeError:
  740. flattened_list = exc_list
  741. # this dict will hold the unique tool diameters found in the exc_list objects as the dict keys and the dict
  742. # values will be list of Shapely Points; for drills
  743. custom_dict_drills = {}
  744. # this dict will hold the unique tool diameters found in the exc_list objects as the dict keys and the dict
  745. # values will be list of Shapely Points; for slots
  746. custom_dict_slots = {}
  747. for exc in flattened_list:
  748. # copy options of the current excellon obj to the final excellon obj
  749. for option in exc.options:
  750. if option is not 'name':
  751. try:
  752. exc_final.options[option] = exc.options[option]
  753. except:
  754. exc.app.log.warning("Failed to copy option.", option)
  755. for drill in exc.drills:
  756. exc_tool_dia = float('%.3f' % exc.tools[drill['tool']]['C'])
  757. if exc_tool_dia not in custom_dict_drills:
  758. custom_dict_drills[exc_tool_dia] = [drill['point']]
  759. else:
  760. custom_dict_drills[exc_tool_dia].append(drill['point'])
  761. for slot in exc.slots:
  762. exc_tool_dia = float('%.3f' % exc.tools[slot['tool']]['C'])
  763. if exc_tool_dia not in custom_dict_slots:
  764. custom_dict_slots[exc_tool_dia] = [[slot['start'], slot['stop']]]
  765. else:
  766. custom_dict_slots[exc_tool_dia].append([slot['start'], slot['stop']])
  767. # add the zeros and units to the exc_final object
  768. exc_final.zeros = exc.zeros
  769. exc_final.units = exc.units
  770. # variable to make tool_name for the tools
  771. current_tool = 0
  772. # Here we add data to the exc_final object
  773. # the tools diameter are now the keys in the drill_dia dict and the values are the Shapely Points in case of
  774. # drills
  775. for tool_dia in custom_dict_drills:
  776. # we create a tool name for each key in the drill_dia dict (the key is a unique drill diameter)
  777. current_tool += 1
  778. tool_name = str(current_tool)
  779. spec = {"C": float(tool_dia)}
  780. exc_final.tools[tool_name] = spec
  781. # rebuild the drills list of dict's that belong to the exc_final object
  782. for point in custom_dict_drills[tool_dia]:
  783. exc_final.drills.append(
  784. {
  785. "point": point,
  786. "tool": str(current_tool)
  787. }
  788. )
  789. # Here we add data to the exc_final object
  790. # the tools diameter are now the keys in the drill_dia dict and the values are a list ([start, stop])
  791. # of two Shapely Points in case of slots
  792. for tool_dia in custom_dict_slots:
  793. # we create a tool name for each key in the slot_dia dict (the key is a unique slot diameter)
  794. # but only if there are no drills
  795. if not exc_final.tools:
  796. current_tool += 1
  797. tool_name = str(current_tool)
  798. spec = {"C": float(tool_dia)}
  799. exc_final.tools[tool_name] = spec
  800. else:
  801. dia_list = []
  802. for v in exc_final.tools.values():
  803. dia_list.append(float(v["C"]))
  804. if tool_dia not in dia_list:
  805. flag_order = True
  806. current_tool = len(dia_list) + 1
  807. tool_name = str(current_tool)
  808. spec = {"C": float(tool_dia)}
  809. exc_final.tools[tool_name] = spec
  810. else:
  811. for k, v in exc_final.tools.items():
  812. if v["C"] == tool_dia:
  813. current_tool = int(k)
  814. break
  815. # rebuild the slots list of dict's that belong to the exc_final object
  816. for point in custom_dict_slots[tool_dia]:
  817. exc_final.slots.append(
  818. {
  819. "start": point[0],
  820. "stop": point[1],
  821. "tool": str(current_tool)
  822. }
  823. )
  824. # flag_order == True means that there was an slot diameter not in the tools and we also have drills
  825. # and the new tool was added to self.tools therefore we need to reorder the tools and drills and slots
  826. current_tool = 0
  827. if flag_order is True:
  828. dia_list = []
  829. temp_drills = []
  830. temp_slots = []
  831. temp_tools = {}
  832. for v in exc_final.tools.values():
  833. dia_list.append(float(v["C"]))
  834. dia_list.sort()
  835. for ordered_dia in dia_list:
  836. current_tool += 1
  837. tool_name_temp = str(current_tool)
  838. spec_temp = {"C": float(ordered_dia)}
  839. temp_tools[tool_name_temp] = spec_temp
  840. for drill in exc_final.drills:
  841. exc_tool_dia = float('%.3f' % exc_final.tools[drill['tool']]['C'])
  842. if exc_tool_dia == ordered_dia:
  843. temp_drills.append(
  844. {
  845. "point": drill["point"],
  846. "tool": str(current_tool)
  847. }
  848. )
  849. for slot in exc_final.slots:
  850. slot_tool_dia = float('%.3f' % exc_final.tools[slot['tool']]['C'])
  851. if slot_tool_dia == ordered_dia:
  852. temp_slots.append(
  853. {
  854. "start": slot["start"],
  855. "stop": slot["stop"],
  856. "tool": str(current_tool)
  857. }
  858. )
  859. # delete the exc_final tools, drills and slots
  860. exc_final.tools = dict()
  861. exc_final.drills[:] = []
  862. exc_final.slots[:] = []
  863. # update the exc_final tools, drills and slots with the ordered values
  864. exc_final.tools = temp_tools
  865. exc_final.drills[:] = temp_drills
  866. exc_final.slots[:] = temp_slots
  867. # create the geometry for the exc_final object
  868. exc_final.create_geometry()
  869. def build_ui(self):
  870. FlatCAMObj.build_ui(self)
  871. n = len(self.tools)
  872. # we have (n+2) rows because there are 'n' tools, each a row, plus the last 2 rows for totals.
  873. self.ui.tools_table.setRowCount(n + 2)
  874. self.tot_drill_cnt = 0
  875. self.tot_slot_cnt = 0
  876. self.tool_row = 0
  877. sort = []
  878. for k, v in list(self.tools.items()):
  879. sort.append((k, v.get('C')))
  880. sorted_tools = sorted(sort, key=lambda t1: t1[1])
  881. tools = [i[0] for i in sorted_tools]
  882. for tool_no in tools:
  883. drill_cnt = 0 # variable to store the nr of drills per tool
  884. slot_cnt = 0 # variable to store the nr of slots per tool
  885. # Find no of drills for the current tool
  886. for drill in self.drills:
  887. if drill['tool'] == tool_no:
  888. drill_cnt += 1
  889. self.tot_drill_cnt += drill_cnt
  890. # Find no of slots for the current tool
  891. for slot in self.slots:
  892. if slot['tool'] == tool_no:
  893. slot_cnt += 1
  894. self.tot_slot_cnt += slot_cnt
  895. id = QtWidgets.QTableWidgetItem('%d' % int(tool_no))
  896. id.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  897. self.ui.tools_table.setItem(self.tool_row, 0, id) # Tool name/id
  898. # Make sure that the drill diameter when in MM is with no more than 2 decimals
  899. # There are no drill bits in MM with more than 3 decimals diameter
  900. # For INCH the decimals should be no more than 3. There are no drills under 10mils
  901. if self.units == 'MM':
  902. dia = QtWidgets.QTableWidgetItem('%.2f' % (self.tools[tool_no]['C']))
  903. else:
  904. dia = QtWidgets.QTableWidgetItem('%.3f' % (self.tools[tool_no]['C']))
  905. dia.setFlags(QtCore.Qt.ItemIsEnabled)
  906. drill_count = QtWidgets.QTableWidgetItem('%d' % drill_cnt)
  907. drill_count.setFlags(QtCore.Qt.ItemIsEnabled)
  908. # if the slot number is zero is better to not clutter the GUI with zero's so we print a space
  909. if slot_cnt > 0:
  910. slot_count = QtWidgets.QTableWidgetItem('%d' % slot_cnt)
  911. else:
  912. slot_count = QtWidgets.QTableWidgetItem('')
  913. slot_count.setFlags(QtCore.Qt.ItemIsEnabled)
  914. self.ui.tools_table.setItem(self.tool_row, 1, dia) # Diameter
  915. self.ui.tools_table.setItem(self.tool_row, 2, drill_count) # Number of drills per tool
  916. self.ui.tools_table.setItem(self.tool_row, 3, slot_count) # Number of drills per tool
  917. self.tool_row += 1
  918. # add a last row with the Total number of drills
  919. empty = QtWidgets.QTableWidgetItem('')
  920. empty.setFlags(~QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  921. empty_1 = QtWidgets.QTableWidgetItem('')
  922. empty_1.setFlags(~QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  923. label_tot_drill_count = QtWidgets.QTableWidgetItem('Total Drills')
  924. tot_drill_count = QtWidgets.QTableWidgetItem('%d' % self.tot_drill_cnt)
  925. label_tot_drill_count.setFlags(QtCore.Qt.ItemIsEnabled)
  926. tot_drill_count.setFlags(QtCore.Qt.ItemIsEnabled)
  927. self.ui.tools_table.setItem(self.tool_row, 0, empty)
  928. self.ui.tools_table.setItem(self.tool_row, 1, label_tot_drill_count)
  929. self.ui.tools_table.setItem(self.tool_row, 2, tot_drill_count) # Total number of drills
  930. self.ui.tools_table.setItem(self.tool_row, 3, empty_1) # Total number of drills
  931. font = QtGui.QFont()
  932. font.setBold(True)
  933. font.setWeight(75)
  934. for k in [1, 2]:
  935. self.ui.tools_table.item(self.tool_row, k).setForeground(QtGui.QColor(127, 0, 255))
  936. self.ui.tools_table.item(self.tool_row, k).setFont(font)
  937. self.tool_row += 1
  938. # add a last row with the Total number of slots
  939. empty_2 = QtWidgets.QTableWidgetItem('')
  940. empty_2.setFlags(~QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  941. empty_3 = QtWidgets.QTableWidgetItem('')
  942. empty_3.setFlags(~QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  943. label_tot_slot_count = QtWidgets.QTableWidgetItem('Total Slots')
  944. tot_slot_count = QtWidgets.QTableWidgetItem('%d' % self.tot_slot_cnt)
  945. label_tot_slot_count.setFlags(QtCore.Qt.ItemIsEnabled)
  946. tot_slot_count.setFlags(QtCore.Qt.ItemIsEnabled)
  947. self.ui.tools_table.setItem(self.tool_row, 0, empty_2)
  948. self.ui.tools_table.setItem(self.tool_row, 1, label_tot_slot_count)
  949. self.ui.tools_table.setItem(self.tool_row, 2, empty_3)
  950. self.ui.tools_table.setItem(self.tool_row, 3, tot_slot_count) # Total number of slots
  951. for kl in [1, 2, 3]:
  952. self.ui.tools_table.item(self.tool_row, kl).setFont(font)
  953. self.ui.tools_table.item(self.tool_row, kl).setForeground(QtGui.QColor(0, 70, 255))
  954. # sort the tool diameter column
  955. # self.ui.tools_table.sortItems(1)
  956. # all the tools are selected by default
  957. self.ui.tools_table.selectColumn(0)
  958. #
  959. self.ui.tools_table.resizeColumnsToContents()
  960. self.ui.tools_table.resizeRowsToContents()
  961. vertical_header = self.ui.tools_table.verticalHeader()
  962. # vertical_header.setSectionResizeMode(QtWidgets.QHeaderView.ResizeToContents)
  963. vertical_header.hide()
  964. self.ui.tools_table.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  965. horizontal_header = self.ui.tools_table.horizontalHeader()
  966. horizontal_header.setSectionResizeMode(0, QtWidgets.QHeaderView.ResizeToContents)
  967. horizontal_header.setSectionResizeMode(1, QtWidgets.QHeaderView.Stretch)
  968. horizontal_header.setSectionResizeMode(2, QtWidgets.QHeaderView.ResizeToContents)
  969. horizontal_header.setSectionResizeMode(3, QtWidgets.QHeaderView.ResizeToContents)
  970. # horizontal_header.setStretchLastSection(True)
  971. self.ui.tools_table.setSortingEnabled(False)
  972. self.ui.tools_table.setMinimumHeight(self.ui.tools_table.getHeight())
  973. self.ui.tools_table.setMaximumHeight(self.ui.tools_table.getHeight())
  974. if not self.drills:
  975. self.ui.tdlabel.hide()
  976. self.ui.tooldia_entry.hide()
  977. self.ui.generate_milling_button.hide()
  978. else:
  979. self.ui.tdlabel.show()
  980. self.ui.tooldia_entry.show()
  981. self.ui.generate_milling_button.show()
  982. if not self.slots:
  983. self.ui.stdlabel.hide()
  984. self.ui.slot_tooldia_entry.hide()
  985. self.ui.generate_milling_slots_button.hide()
  986. else:
  987. self.ui.stdlabel.show()
  988. self.ui.slot_tooldia_entry.show()
  989. self.ui.generate_milling_slots_button.show()
  990. def set_ui(self, ui):
  991. """
  992. Configures the user interface for this object.
  993. Connects options to form fields.
  994. :param ui: User interface object.
  995. :type ui: ExcellonObjectUI
  996. :return: None
  997. """
  998. FlatCAMObj.set_ui(self, ui)
  999. FlatCAMApp.App.log.debug("FlatCAMExcellon.set_ui()")
  1000. self.form_fields.update({
  1001. "plot": self.ui.plot_cb,
  1002. "solid": self.ui.solid_cb,
  1003. "drillz": self.ui.cutz_entry,
  1004. "travelz": self.ui.travelz_entry,
  1005. "feedrate": self.ui.feedrate_entry,
  1006. "feedrate_rapid": self.ui.feedrate_rapid_entry,
  1007. "tooldia": self.ui.tooldia_entry,
  1008. "slot_tooldia": self.ui.slot_tooldia_entry,
  1009. "toolchange": self.ui.toolchange_cb,
  1010. "toolchangez": self.ui.toolchangez_entry,
  1011. "spindlespeed": self.ui.spindlespeed_entry,
  1012. "dwell": self.ui.dwell_cb,
  1013. "dwelltime": self.ui.dwelltime_entry,
  1014. "startz": self.ui.estartz_entry,
  1015. "endz": self.ui.eendz_entry,
  1016. "ppname_e": self.ui.pp_excellon_name_cb,
  1017. "gcode_type": self.ui.excellon_gcode_type_radio
  1018. })
  1019. for name in list(self.app.postprocessors.keys()):
  1020. # the HPGL postprocessor is only for Geometry not for Excellon job therefore don't add it
  1021. if name == 'hpgl':
  1022. continue
  1023. self.ui.pp_excellon_name_cb.addItem(name)
  1024. # Fill form fields
  1025. self.to_form()
  1026. assert isinstance(self.ui, ExcellonObjectUI), \
  1027. "Expected a ExcellonObjectUI, got %s" % type(self.ui)
  1028. self.ui.plot_cb.stateChanged.connect(self.on_plot_cb_click)
  1029. self.ui.solid_cb.stateChanged.connect(self.on_solid_cb_click)
  1030. self.ui.generate_cnc_button.clicked.connect(self.on_create_cncjob_button_click)
  1031. self.ui.generate_milling_button.clicked.connect(self.on_generate_milling_button_click)
  1032. self.ui.generate_milling_slots_button.clicked.connect(self.on_generate_milling_slots_button_click)
  1033. def get_selected_tools_list(self):
  1034. """
  1035. Returns the keys to the self.tools dictionary corresponding
  1036. to the selections on the tool list in the GUI.
  1037. :return: List of tools.
  1038. :rtype: list
  1039. """
  1040. return [str(x.text()) for x in self.ui.tools_table.selectedItems()]
  1041. def get_selected_tools_table_items(self):
  1042. """
  1043. Returns a list of lists, each list in the list is made out of row elements
  1044. :return: List of table_tools items.
  1045. :rtype: list
  1046. """
  1047. table_tools_items = []
  1048. for x in self.ui.tools_table.selectedItems():
  1049. table_tools_items.append([self.ui.tools_table.item(x.row(), column).text()
  1050. for column in range(0, self.ui.tools_table.columnCount())])
  1051. for item in table_tools_items:
  1052. item[0] = str(item[0])
  1053. return table_tools_items
  1054. def export_excellon(self):
  1055. """
  1056. Returns two values, first is a boolean , if 1 then the file has slots and second contain the Excellon code
  1057. :return: has_slots and Excellon_code
  1058. """
  1059. excellon_code = ''
  1060. units = self.app.general_options_form.general_app_group.units_radio.get_value().upper()
  1061. # store here if the file has slots, return 1 if any slots, 0 if only drills
  1062. has_slots = 0
  1063. # drills processing
  1064. try:
  1065. for tool in self.tools:
  1066. if int(tool) < 10:
  1067. excellon_code += 'T0' + str(tool) + '\n'
  1068. else:
  1069. excellon_code += 'T' + str(tool) + '\n'
  1070. for drill in self.drills:
  1071. if tool == drill['tool']:
  1072. if units == 'MM':
  1073. excellon_code += 'X' + '%.3f' % drill['point'].x + 'Y' + '%.3f' % drill['point'].y + '\n'
  1074. else:
  1075. excellon_code += 'X' + '%.4f' % drill['point'].x + 'Y' + '%.4f' % drill['point'].y + '\n'
  1076. except Exception as e:
  1077. log.debug(str(e))
  1078. # slots processing
  1079. try:
  1080. if self.slots:
  1081. has_slots = 1
  1082. for tool in self.tools:
  1083. if int(tool) < 10:
  1084. excellon_code += 'T0' + str(tool) + '\n'
  1085. else:
  1086. excellon_code += 'T' + str(tool) + '\n'
  1087. for slot in self.slots:
  1088. if tool == slot['tool']:
  1089. if units == 'MM':
  1090. excellon_code += 'G00' + 'X' + '%.3f' % slot['start'].x + 'Y' + \
  1091. '%.3f' % slot['start'].y + '\n'
  1092. excellon_code += 'M15\n'
  1093. excellon_code += 'G01' + 'X' + '%.3f' % slot['stop'].x + 'Y' + \
  1094. '%.3f' % slot['stop'].y + '\n'
  1095. excellon_code += 'M16\n'
  1096. else:
  1097. excellon_code += 'G00' + 'X' + '%.4f' % slot['start'].x + 'Y' + \
  1098. '%.4f' % slot['start'].y + '\n'
  1099. excellon_code += 'M15\n'
  1100. excellon_code += 'G01' + 'X' + '%.4f' % slot['stop'].x + 'Y' + \
  1101. '%.4f' % slot['stop'].y + '\n'
  1102. excellon_code += 'M16\n'
  1103. except Exception as e:
  1104. log.debug(str(e))
  1105. return has_slots, excellon_code
  1106. def export_excellon_altium(self):
  1107. """
  1108. Returns two values, first is a boolean , if 1 then the file has slots and second contain the Excellon code
  1109. :return: has_slots and Excellon_code
  1110. """
  1111. excellon_code = ''
  1112. units = self.app.general_options_form.general_app_group.units_radio.get_value().upper()
  1113. # store here if the file has slots, return 1 if any slots, 0 if only drills
  1114. has_slots = 0
  1115. # drills processing
  1116. try:
  1117. for tool in self.tools:
  1118. if int(tool) < 10:
  1119. excellon_code += 'T0' + str(tool) + '\n'
  1120. else:
  1121. excellon_code += 'T' + str(tool) + '\n'
  1122. for drill in self.drills:
  1123. if tool == drill['tool']:
  1124. drill_x = drill['point'].x
  1125. drill_y = drill['point'].y
  1126. if units == 'MM':
  1127. drill_x /= 25.4
  1128. drill_y /= 25.4
  1129. exc_x_formatted = ('%.4f' % drill_x).replace('.', '')
  1130. if drill_x < 10:
  1131. exc_x_formatted = '0' + exc_x_formatted
  1132. exc_y_formatted = ('%.4f' % drill_y).replace('.', '')
  1133. if drill_y < 10:
  1134. exc_y_formatted = '0' + exc_y_formatted
  1135. excellon_code += 'X' + exc_x_formatted + 'Y' + exc_y_formatted + '\n'
  1136. except Exception as e:
  1137. log.debug(str(e))
  1138. # slots processing
  1139. try:
  1140. if self.slots:
  1141. has_slots = 1
  1142. for tool in self.tools:
  1143. if int(tool) < 10:
  1144. excellon_code += 'T0' + str(tool) + '\n'
  1145. else:
  1146. excellon_code += 'T' + str(tool) + '\n'
  1147. for slot in self.slots:
  1148. if tool == slot['tool']:
  1149. start_slot_x = slot['start'].x
  1150. start_slot_y = slot['start'].y
  1151. stop_slot_x = slot['stop'].x
  1152. stop_slot_y = slot['stop'].y
  1153. if units == 'MM':
  1154. start_slot_x /= 25.4
  1155. start_slot_y /= 25.4
  1156. stop_slot_x /= 25.4
  1157. stop_slot_y /= 25.4
  1158. start_slot_x_formatted = ('%.4f' % start_slot_x).replace('.', '')
  1159. if start_slot_x < 10:
  1160. start_slot_x_formatted = '0' + start_slot_x_formatted
  1161. start_slot_y_formatted = ('%.4f' % start_slot_y).replace('.', '')
  1162. if start_slot_y < 10:
  1163. start_slot_y_formatted = '0' + start_slot_y_formatted
  1164. stop_slot_x_formatted = ('%.4f' % stop_slot_x).replace('.', '')
  1165. if stop_slot_x < 10:
  1166. stop_slot_x_formatted = '0' + stop_slot_x_formatted
  1167. stop_slot_y_formatted = ('%.4f' % stop_slot_y).replace('.', '')
  1168. if stop_slot_y < 10:
  1169. stop_slot_y_formatted = '0' + stop_slot_y_formatted
  1170. excellon_code += 'G00' + 'X' + start_slot_x_formatted + 'Y' + \
  1171. start_slot_y_formatted + '\n'
  1172. excellon_code += 'M15\n'
  1173. excellon_code += 'G01' + 'X' + stop_slot_x_formatted + 'Y' + \
  1174. stop_slot_y_formatted + '\n'
  1175. excellon_code += 'M16\n'
  1176. except Exception as e:
  1177. log.debug(str(e))
  1178. return has_slots, excellon_code
  1179. def generate_milling_drills(self, tools=None, outname=None, tooldia=None, use_thread=False):
  1180. """
  1181. Note: This method is a good template for generic operations as
  1182. it takes it's options from parameters or otherwise from the
  1183. object's options and returns a (success, msg) tuple as feedback
  1184. for shell operations.
  1185. :return: Success/failure condition tuple (bool, str).
  1186. :rtype: tuple
  1187. """
  1188. # Get the tools from the list. These are keys
  1189. # to self.tools
  1190. if tools is None:
  1191. tools = self.get_selected_tools_list()
  1192. if outname is None:
  1193. outname = self.options["name"] + "_mill"
  1194. if tooldia is None:
  1195. tooldia = self.options["tooldia"]
  1196. # Sort tools by diameter. items() -> [('name', diameter), ...]
  1197. # sorted_tools = sorted(list(self.tools.items()), key=lambda tl: tl[1]) # no longer works in Python3
  1198. sort = []
  1199. for k, v in self.tools.items():
  1200. sort.append((k, v.get('C')))
  1201. sorted_tools = sorted(sort, key=lambda t1: t1[1])
  1202. if tools == "all":
  1203. tools = [i[0] for i in sorted_tools] # List if ordered tool names.
  1204. log.debug("Tools 'all' and sorted are: %s" % str(tools))
  1205. if len(tools) == 0:
  1206. self.app.inform.emit("[error_notcl]Please select one or more tools from the list and try again.")
  1207. return False, "Error: No tools."
  1208. for tool in tools:
  1209. if tooldia > self.tools[tool]["C"]:
  1210. self.app.inform.emit("[error_notcl] Milling tool for DRILLS is larger than hole size. Cancelled.")
  1211. return False, "Error: Milling tool is larger than hole."
  1212. def geo_init(geo_obj, app_obj):
  1213. assert isinstance(geo_obj, FlatCAMGeometry), \
  1214. "Initializer expected a FlatCAMGeometry, got %s" % type(geo_obj)
  1215. app_obj.progress.emit(20)
  1216. ### Add properties to the object
  1217. # get the tool_table items in a list of row items
  1218. tool_table_items = self.get_selected_tools_table_items()
  1219. # insert an information only element in the front
  1220. tool_table_items.insert(0, ["Tool_nr", "Diameter", "Drills_Nr", "Slots_Nr"])
  1221. geo_obj.options['Tools_in_use'] = tool_table_items
  1222. geo_obj.options['type'] = 'Excellon Geometry'
  1223. geo_obj.solid_geometry = []
  1224. # in case that the tool used has the same diameter with the hole, and since the maximum resolution
  1225. # for FlatCAM is 6 decimals,
  1226. # we add a tenth of the minimum value, meaning 0.0000001, which from our point of view is "almost zero"
  1227. for hole in self.drills:
  1228. if hole['tool'] in tools:
  1229. buffer_value = self.tools[hole['tool']]["C"] / 2 - tooldia / 2
  1230. if buffer_value == 0:
  1231. geo_obj.solid_geometry.append(
  1232. Point(hole['point']).buffer(0.0000001).exterior)
  1233. else:
  1234. geo_obj.solid_geometry.append(
  1235. Point(hole['point']).buffer(buffer_value).exterior)
  1236. if use_thread:
  1237. def geo_thread(app_obj):
  1238. app_obj.new_object("geometry", outname, geo_init)
  1239. app_obj.progress.emit(100)
  1240. # Create a promise with the new name
  1241. self.app.collection.promise(outname)
  1242. # Send to worker
  1243. self.app.worker_task.emit({'fcn': geo_thread, 'params': [self.app]})
  1244. else:
  1245. self.app.new_object("geometry", outname, geo_init)
  1246. return True, ""
  1247. def generate_milling_slots(self, tools=None, outname=None, tooldia=None, use_thread=False):
  1248. """
  1249. Note: This method is a good template for generic operations as
  1250. it takes it's options from parameters or otherwise from the
  1251. object's options and returns a (success, msg) tuple as feedback
  1252. for shell operations.
  1253. :return: Success/failure condition tuple (bool, str).
  1254. :rtype: tuple
  1255. """
  1256. # Get the tools from the list. These are keys
  1257. # to self.tools
  1258. if tools is None:
  1259. tools = self.get_selected_tools_list()
  1260. if outname is None:
  1261. outname = self.options["name"] + "_mill"
  1262. if tooldia is None:
  1263. tooldia = self.options["slot_tooldia"]
  1264. # Sort tools by diameter. items() -> [('name', diameter), ...]
  1265. # sorted_tools = sorted(list(self.tools.items()), key=lambda tl: tl[1]) # no longer works in Python3
  1266. sort = []
  1267. for k, v in self.tools.items():
  1268. sort.append((k, v.get('C')))
  1269. sorted_tools = sorted(sort, key=lambda t1: t1[1])
  1270. if tools == "all":
  1271. tools = [i[0] for i in sorted_tools] # List if ordered tool names.
  1272. log.debug("Tools 'all' and sorted are: %s" % str(tools))
  1273. if len(tools) == 0:
  1274. self.app.inform.emit("[error_notcl]Please select one or more tools from the list and try again.")
  1275. return False, "Error: No tools."
  1276. for tool in tools:
  1277. if tooldia > self.tools[tool]["C"]:
  1278. self.app.inform.emit("[error_notcl] Milling tool for SLOTS is larger than hole size. Cancelled.")
  1279. return False, "Error: Milling tool is larger than hole."
  1280. def geo_init(geo_obj, app_obj):
  1281. assert isinstance(geo_obj, FlatCAMGeometry), \
  1282. "Initializer expected a FlatCAMGeometry, got %s" % type(geo_obj)
  1283. app_obj.progress.emit(20)
  1284. ### Add properties to the object
  1285. # get the tool_table items in a list of row items
  1286. tool_table_items = self.get_selected_tools_table_items()
  1287. # insert an information only element in the front
  1288. tool_table_items.insert(0, ["Tool_nr", "Diameter", "Drills_Nr", "Slots_Nr"])
  1289. geo_obj.options['Tools_in_use'] = tool_table_items
  1290. geo_obj.options['type'] = 'Excellon Geometry'
  1291. geo_obj.solid_geometry = []
  1292. # in case that the tool used has the same diameter with the hole, and since the maximum resolution
  1293. # for FlatCAM is 6 decimals,
  1294. # we add a tenth of the minimum value, meaning 0.0000001, which from our point of view is "almost zero"
  1295. for slot in self.slots:
  1296. if slot['tool'] in tools:
  1297. buffer_value = self.tools[slot['tool']]["C"] / 2 - tooldia / 2
  1298. if buffer_value == 0:
  1299. start = slot['start']
  1300. stop = slot['stop']
  1301. lines_string = LineString([start, stop])
  1302. poly = lines_string.buffer(0.0000001, self.geo_steps_per_circle).exterior
  1303. geo_obj.solid_geometry.append(poly)
  1304. else:
  1305. start = slot['start']
  1306. stop = slot['stop']
  1307. lines_string = LineString([start, stop])
  1308. poly = lines_string.buffer(buffer_value, self.geo_steps_per_circle).exterior
  1309. geo_obj.solid_geometry.append(poly)
  1310. if use_thread:
  1311. def geo_thread(app_obj):
  1312. app_obj.new_object("geometry", outname + '_slot', geo_init)
  1313. app_obj.progress.emit(100)
  1314. # Create a promise with the new name
  1315. self.app.collection.promise(outname)
  1316. # Send to worker
  1317. self.app.worker_task.emit({'fcn': geo_thread, 'params': [self.app]})
  1318. else:
  1319. self.app.new_object("geometry", outname + '_slot', geo_init)
  1320. return True, ""
  1321. def on_generate_milling_button_click(self, *args):
  1322. self.app.report_usage("excellon_on_create_milling_drills button")
  1323. self.read_form()
  1324. self.generate_milling_drills(use_thread=False)
  1325. def on_generate_milling_slots_button_click(self, *args):
  1326. self.app.report_usage("excellon_on_create_milling_slots_button")
  1327. self.read_form()
  1328. self.generate_milling_slots(use_thread=False)
  1329. def on_create_cncjob_button_click(self, *args):
  1330. self.app.report_usage("excellon_on_create_cncjob_button")
  1331. self.read_form()
  1332. # Get the tools from the list
  1333. tools = self.get_selected_tools_list()
  1334. if len(tools) == 0:
  1335. self.app.inform.emit("[error_notcl]Please select one or more tools from the list and try again.")
  1336. return
  1337. job_name = self.options["name"] + "_cnc"
  1338. pp_excellon_name = self.options["ppname_e"]
  1339. # Object initialization function for app.new_object()
  1340. def job_init(job_obj, app_obj):
  1341. assert isinstance(job_obj, FlatCAMCNCjob), \
  1342. "Initializer expected a FlatCAMCNCjob, got %s" % type(job_obj)
  1343. # get the tool_table items in a list of row items
  1344. tool_table_items = self.get_selected_tools_table_items()
  1345. # insert an information only element in the front
  1346. tool_table_items.insert(0, ["Tool_nr", "Diameter", "Drills_Nr", "Slots_Nr"])
  1347. ### Add properties to the object
  1348. job_obj.options['Tools_in_use'] = tool_table_items
  1349. job_obj.options['type'] = 'Excellon'
  1350. app_obj.progress.emit(20)
  1351. job_obj.z_cut = self.options["drillz"]
  1352. job_obj.z_move = self.options["travelz"]
  1353. job_obj.feedrate = self.options["feedrate"]
  1354. job_obj.feedrate_rapid = self.options["feedrate_rapid"]
  1355. job_obj.spindlespeed = self.options["spindlespeed"]
  1356. job_obj.dwell = self.options["dwell"]
  1357. job_obj.dwelltime = self.options["dwelltime"]
  1358. job_obj.pp_excellon_name = pp_excellon_name
  1359. job_obj.toolchange_xy = "excellon"
  1360. job_obj.coords_decimals = int(self.app.defaults["cncjob_coords_decimals"])
  1361. job_obj.fr_decimals = int(self.app.defaults["cncjob_fr_decimals"])
  1362. # There could be more than one drill size...
  1363. # job_obj.tooldia = # TODO: duplicate variable!
  1364. # job_obj.options["tooldia"] =
  1365. tools_csv = ','.join(tools)
  1366. job_obj.generate_from_excellon_by_tool(self, tools_csv,
  1367. drillz=self.options['drillz'],
  1368. toolchange=self.options["toolchange"],
  1369. toolchangez=self.options["toolchangez"],
  1370. toolchangexy=self.options["toolchangexy"],
  1371. startz=self.options["startz"],
  1372. endz=self.options["endz"],
  1373. excellon_optimization_type=self.options["optimization_type"])
  1374. app_obj.progress.emit(50)
  1375. job_obj.gcode_parse()
  1376. app_obj.progress.emit(60)
  1377. job_obj.create_geometry()
  1378. app_obj.progress.emit(80)
  1379. # To be run in separate thread
  1380. def job_thread(app_obj):
  1381. with self.app.proc_container.new("Generating CNC Code"):
  1382. app_obj.new_object("cncjob", job_name, job_init)
  1383. app_obj.progress.emit(100)
  1384. # Create promise for the new name.
  1385. self.app.collection.promise(job_name)
  1386. # Send to worker
  1387. # self.app.worker.add_task(job_thread, [self.app])
  1388. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  1389. def on_plot_cb_click(self, *args):
  1390. if self.muted_ui:
  1391. return
  1392. self.read_form_item('plot')
  1393. def on_solid_cb_click(self, *args):
  1394. if self.muted_ui:
  1395. return
  1396. self.read_form_item('solid')
  1397. self.plot()
  1398. def convert_units(self, units):
  1399. factor = Excellon.convert_units(self, units)
  1400. self.options['drillz'] *= factor
  1401. self.options['travelz'] *= factor
  1402. self.options['feedrate'] *= factor
  1403. self.options['feedrate_rapid'] *= factor
  1404. self.options['toolchangez'] *= factor
  1405. coords_xy = [float(eval(coord)) for coord in self.app.defaults["excellon_toolchangexy"].split(",")]
  1406. coords_xy[0] *= factor
  1407. coords_xy[1] *= factor
  1408. self.options['toolchangexy'] = "%f, %f" % (coords_xy[0], coords_xy[1])
  1409. if self.options['startz'] is not None:
  1410. self.options['startz'] *= factor
  1411. self.options['endz'] *= factor
  1412. def plot(self):
  1413. # Does all the required setup and returns False
  1414. # if the 'ptint' option is set to False.
  1415. if not FlatCAMObj.plot(self):
  1416. return
  1417. try:
  1418. _ = iter(self.solid_geometry)
  1419. except TypeError:
  1420. self.solid_geometry = [self.solid_geometry]
  1421. try:
  1422. # Plot excellon (All polygons?)
  1423. if self.options["solid"]:
  1424. for geo in self.solid_geometry:
  1425. self.add_shape(shape=geo, color='#750000BF', face_color='#C40000BF', visible=self.options['plot'],
  1426. layer=2)
  1427. else:
  1428. for geo in self.solid_geometry:
  1429. self.add_shape(shape=geo.exterior, color='red', visible=self.options['plot'])
  1430. for ints in geo.interiors:
  1431. self.add_shape(shape=ints, color='green', visible=self.options['plot'])
  1432. self.shapes.redraw()
  1433. except (ObjectDeleted, AttributeError):
  1434. self.shapes.clear(update=True)
  1435. # try:
  1436. # # Plot excellon (All polygons?)
  1437. # if self.options["solid"]:
  1438. # for geo_type in self.solid_geometry:
  1439. # if geo_type is not None:
  1440. # if type(geo_type) is dict:
  1441. # for tooldia in geo_type:
  1442. # geo_list = geo_type[tooldia]
  1443. # for geo in geo_list:
  1444. # self.add_shape(shape=geo, color='#750000BF', face_color='#C40000BF',
  1445. # visible=self.options['plot'],
  1446. # layer=2)
  1447. # else:
  1448. # self.add_shape(shape=geo_type, color='#750000BF', face_color='#C40000BF',
  1449. # visible=self.options['plot'],
  1450. # layer=2)
  1451. # else:
  1452. # for geo_type in self.solid_geometry:
  1453. # if geo_type is not None:
  1454. # if type(geo_type) is dict:
  1455. # for tooldia in geo_type:
  1456. # geo_list = geo_type[tooldia]
  1457. # for geo in geo_list:
  1458. # self.add_shape(shape=geo.exterior, color='red', visible=self.options['plot'])
  1459. # for ints in geo.interiors:
  1460. # self.add_shape(shape=ints, color='green', visible=self.options['plot'])
  1461. # else:
  1462. # self.add_shape(shape=geo_type.exterior, color='red', visible=self.options['plot'])
  1463. # for ints in geo_type.interiors:
  1464. # self.add_shape(shape=ints, color='green', visible=self.options['plot'])
  1465. # self.shapes.redraw()
  1466. # except (ObjectDeleted, AttributeError):
  1467. # self.shapes.clear(update=True)
  1468. class FlatCAMGeometry(FlatCAMObj, Geometry):
  1469. """
  1470. Geometric object not associated with a specific
  1471. format.
  1472. """
  1473. optionChanged = QtCore.pyqtSignal(str)
  1474. ui_type = GeometryObjectUI
  1475. @staticmethod
  1476. def merge(geo_list, geo_final, multigeo=None):
  1477. """
  1478. Merges the geometry of objects in grb_list into
  1479. the geometry of geo_final.
  1480. :param geo_list: List of FlatCAMGerber Objects to join.
  1481. :param geo_final: Destination FlatCAMGerber object.
  1482. :return: None
  1483. """
  1484. if geo_final.solid_geometry is None:
  1485. geo_final.solid_geometry = []
  1486. if type(geo_final.solid_geometry) is not list:
  1487. geo_final.solid_geometry = [geo_final.solid_geometry]
  1488. for geo in geo_list:
  1489. for option in geo.options:
  1490. if option is not 'name':
  1491. try:
  1492. geo_final.options[option] = geo.options[option]
  1493. except:
  1494. log.warning("Failed to copy option.", option)
  1495. # Expand lists
  1496. if type(geo) is list:
  1497. FlatCAMGeometry.merge(geo, geo_final)
  1498. # If not list, just append
  1499. else:
  1500. # merge solid_geometry, useful for singletool geometry, for multitool each is empty
  1501. if multigeo is None or multigeo == False:
  1502. geo_final.multigeo = False
  1503. try:
  1504. geo_final.solid_geometry.append(geo.solid_geometry)
  1505. except Exception as e:
  1506. log.debug("FlatCAMGeometry.merge() --> %s" % str(e))
  1507. else:
  1508. geo_final.multigeo = True
  1509. # if multigeo the solid_geometry is empty in the object attributes because it now lives in the
  1510. # tools object attribute, as a key value
  1511. geo_final.solid_geometry = []
  1512. # find the tool_uid maximum value in the geo_final
  1513. geo_final_uid_list = []
  1514. for key in geo_final.tools:
  1515. geo_final_uid_list.append(int(key))
  1516. try:
  1517. max_uid = max(geo_final_uid_list, key=int)
  1518. except ValueError:
  1519. max_uid = 0
  1520. # add and merge tools. If what we try to merge as Geometry is Excellon's and/or Gerber's then don't try
  1521. # to merge the obj.tools as it is likely there is none to merge.
  1522. if not isinstance(geo, FlatCAMGerber) and not isinstance(geo, FlatCAMExcellon):
  1523. for tool_uid in geo.tools:
  1524. max_uid += 1
  1525. geo_final.tools[max_uid] = dict(geo.tools[tool_uid])
  1526. @staticmethod
  1527. def get_pts(o):
  1528. """
  1529. Returns a list of all points in the object, where
  1530. the object can be a MultiPolygon, Polygon, Not a polygon, or a list
  1531. of such. Search is done recursively.
  1532. :param: geometric object
  1533. :return: List of points
  1534. :rtype: list
  1535. """
  1536. pts = []
  1537. ## Iterable: descend into each item.
  1538. try:
  1539. for subo in o:
  1540. pts += FlatCAMGeometry.get_pts(subo)
  1541. ## Non-iterable
  1542. except TypeError:
  1543. if o is not None:
  1544. if type(o) == MultiPolygon:
  1545. for poly in o:
  1546. pts += FlatCAMGeometry.get_pts(poly)
  1547. ## Descend into .exerior and .interiors
  1548. elif type(o) == Polygon:
  1549. pts += FlatCAMGeometry.get_pts(o.exterior)
  1550. for i in o.interiors:
  1551. pts += FlatCAMGeometry.get_pts(i)
  1552. elif type(o) == MultiLineString:
  1553. for line in o:
  1554. pts += FlatCAMGeometry.get_pts(line)
  1555. ## Has .coords: list them.
  1556. else:
  1557. pts += list(o.coords)
  1558. else:
  1559. return
  1560. return pts
  1561. def __init__(self, name):
  1562. FlatCAMObj.__init__(self, name)
  1563. Geometry.__init__(self, geo_steps_per_circle=self.app.defaults["geometry_circle_steps"])
  1564. self.kind = "geometry"
  1565. self.options.update({
  1566. "plot": True,
  1567. "cutz": -0.002,
  1568. "vtipdia": 0.1,
  1569. "vtipangle": 30,
  1570. "travelz": 0.1,
  1571. "feedrate": 5.0,
  1572. "feedrate_z": 5.0,
  1573. "feedrate_rapid": 5.0,
  1574. "spindlespeed": None,
  1575. "dwell": True,
  1576. "dwelltime": 1000,
  1577. "multidepth": False,
  1578. "depthperpass": 0.002,
  1579. "extracut": False,
  1580. "endz": 2.0,
  1581. "toolchange": False,
  1582. "toolchangez": 1.0,
  1583. "toolchangexy": "0.0, 0.0",
  1584. "startz": None,
  1585. "ppname_g": 'default',
  1586. })
  1587. if "cnctooldia" not in self.options:
  1588. self.options["cnctooldia"] = self.app.defaults["geometry_cnctooldia"]
  1589. self.options["startz"] = self.app.defaults["geometry_startz"]
  1590. # this will hold the tool unique ID that is useful when having multiple tools with same diameter
  1591. self.tooluid = 0
  1592. '''
  1593. self.tools = {}
  1594. This is a dictionary. Each dict key is associated with a tool used in geo_tools_table. The key is the
  1595. tool_id of the tools and the value is another dict that will hold the data under the following form:
  1596. {tooluid: {
  1597. 'tooldia': 1,
  1598. 'offset': 'Path',
  1599. 'offset_value': 0.0
  1600. 'type': 'Rough',
  1601. 'tool_type': 'C1',
  1602. 'data': self.default_tool_data
  1603. 'solid_geometry': []
  1604. }
  1605. }
  1606. '''
  1607. self.tools = {}
  1608. # this dict is to store those elements (tools) of self.tools that are selected in the self.geo_tools_table
  1609. # those elements are the ones used for generating GCode
  1610. self.sel_tools = {}
  1611. self.offset_item_options = ["Path", "In", "Out", "Custom"]
  1612. self.type_item_options = ["Iso", "Rough", "Finish"]
  1613. self.tool_type_item_options = ["C1", "C2", "C3", "C4", "B", "V"]
  1614. # flag to store if the V-Shape tool is selected in self.ui.geo_tools_table
  1615. self.v_tool_type = None
  1616. self.multigeo = False
  1617. # Attributes to be included in serialization
  1618. # Always append to it because it carries contents
  1619. # from predecessors.
  1620. self.ser_attrs += ['options', 'kind', 'tools', 'multigeo']
  1621. def build_ui(self):
  1622. self.ui_disconnect()
  1623. FlatCAMObj.build_ui(self)
  1624. offset = 0
  1625. tool_idx = 0
  1626. n = len(self.tools)
  1627. self.ui.geo_tools_table.setRowCount(n)
  1628. for tooluid_key, tooluid_value in self.tools.items():
  1629. tool_idx += 1
  1630. row_no = tool_idx - 1
  1631. id = QtWidgets.QTableWidgetItem('%d' % int(tool_idx))
  1632. id.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  1633. self.ui.geo_tools_table.setItem(row_no, 0, id) # Tool name/id
  1634. # Make sure that the tool diameter when in MM is with no more than 2 decimals.
  1635. # There are no tool bits in MM with more than 3 decimals diameter.
  1636. # For INCH the decimals should be no more than 3. There are no tools under 10mils.
  1637. if self.units == 'MM':
  1638. dia_item = QtWidgets.QTableWidgetItem('%.2f' % float(tooluid_value['tooldia']))
  1639. else:
  1640. dia_item = QtWidgets.QTableWidgetItem('%.4f' % float(tooluid_value['tooldia']))
  1641. dia_item.setFlags(QtCore.Qt.ItemIsEnabled)
  1642. offset_item = QtWidgets.QComboBox()
  1643. for item in self.offset_item_options:
  1644. offset_item.addItem(item)
  1645. offset_item.setStyleSheet('background-color: rgb(255,255,255)')
  1646. idx = offset_item.findText(tooluid_value['offset'])
  1647. offset_item.setCurrentIndex(idx)
  1648. type_item = QtWidgets.QComboBox()
  1649. for item in self.type_item_options:
  1650. type_item.addItem(item)
  1651. type_item.setStyleSheet('background-color: rgb(255,255,255)')
  1652. idx = type_item.findText(tooluid_value['type'])
  1653. type_item.setCurrentIndex(idx)
  1654. tool_type_item = QtWidgets.QComboBox()
  1655. for item in self.tool_type_item_options:
  1656. tool_type_item.addItem(item)
  1657. tool_type_item.setStyleSheet('background-color: rgb(255,255,255)')
  1658. idx = tool_type_item.findText(tooluid_value['tool_type'])
  1659. tool_type_item.setCurrentIndex(idx)
  1660. tool_uid_item = QtWidgets.QTableWidgetItem(str(tooluid_key))
  1661. plot_item = FCCheckBox()
  1662. plot_item.setLayoutDirection(QtCore.Qt.RightToLeft)
  1663. if self.ui.plot_cb.isChecked():
  1664. plot_item.setChecked(True)
  1665. self.ui.geo_tools_table.setItem(row_no, 1, dia_item) # Diameter
  1666. self.ui.geo_tools_table.setCellWidget(row_no, 2, offset_item)
  1667. self.ui.geo_tools_table.setCellWidget(row_no, 3, type_item)
  1668. self.ui.geo_tools_table.setCellWidget(row_no, 4, tool_type_item)
  1669. ### REMEMBER: THIS COLUMN IS HIDDEN IN OBJECTUI.PY ###
  1670. self.ui.geo_tools_table.setItem(row_no, 5, tool_uid_item) # Tool unique ID
  1671. self.ui.geo_tools_table.setCellWidget(row_no, 6, plot_item)
  1672. try:
  1673. self.ui.tool_offset_entry.set_value(tooluid_value['offset_value'])
  1674. except:
  1675. log.debug("build_ui() --> Could not set the 'offset_value' key in self.tools")
  1676. # make the diameter column editable
  1677. for row in range(tool_idx):
  1678. self.ui.geo_tools_table.item(row, 1).setFlags(QtCore.Qt.ItemIsSelectable |
  1679. QtCore.Qt.ItemIsEditable |
  1680. QtCore.Qt.ItemIsEnabled)
  1681. # sort the tool diameter column
  1682. # self.ui.geo_tools_table.sortItems(1)
  1683. # all the tools are selected by default
  1684. # self.ui.geo_tools_table.selectColumn(0)
  1685. self.ui.geo_tools_table.resizeColumnsToContents()
  1686. self.ui.geo_tools_table.resizeRowsToContents()
  1687. vertical_header = self.ui.geo_tools_table.verticalHeader()
  1688. # vertical_header.setSectionResizeMode(QtWidgets.QHeaderView.ResizeToContents)
  1689. vertical_header.hide()
  1690. self.ui.geo_tools_table.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  1691. horizontal_header = self.ui.geo_tools_table.horizontalHeader()
  1692. horizontal_header.setMinimumSectionSize(10)
  1693. horizontal_header.setDefaultSectionSize(70)
  1694. horizontal_header.setSectionResizeMode(0, QtWidgets.QHeaderView.Fixed)
  1695. horizontal_header.resizeSection(0, 20)
  1696. horizontal_header.setSectionResizeMode(1, QtWidgets.QHeaderView.Stretch)
  1697. # horizontal_header.setColumnWidth(2, QtWidgets.QHeaderView.ResizeToContents)
  1698. horizontal_header.setSectionResizeMode(3, QtWidgets.QHeaderView.ResizeToContents)
  1699. horizontal_header.setSectionResizeMode(4, QtWidgets.QHeaderView.Fixed)
  1700. horizontal_header.resizeSection(4, 40)
  1701. horizontal_header.setSectionResizeMode(6, QtWidgets.QHeaderView.Fixed)
  1702. horizontal_header.resizeSection(4, 17)
  1703. # horizontal_header.setStretchLastSection(True)
  1704. self.ui.geo_tools_table.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  1705. self.ui.geo_tools_table.setColumnWidth(0, 20)
  1706. self.ui.geo_tools_table.setColumnWidth(4, 40)
  1707. self.ui.geo_tools_table.setColumnWidth(6, 17)
  1708. # self.ui.geo_tools_table.setSortingEnabled(True)
  1709. self.ui.geo_tools_table.setMinimumHeight(self.ui.geo_tools_table.getHeight())
  1710. self.ui.geo_tools_table.setMaximumHeight(self.ui.geo_tools_table.getHeight())
  1711. # update UI for all rows - useful after units conversion but only if there is at least one row
  1712. row_cnt = self.ui.geo_tools_table.rowCount()
  1713. if row_cnt > 0:
  1714. for r in range(row_cnt):
  1715. self.update_ui(r)
  1716. # select only the first tool / row
  1717. selected_row = 0
  1718. try:
  1719. self.select_tools_table_row(selected_row, clearsel=True)
  1720. # update the Geometry UI
  1721. self.update_ui()
  1722. except Exception as e:
  1723. # when the tools table is empty there will be this error but once the table is populated it will go away
  1724. log.debug(str(e))
  1725. # disable the Plot column in Tool Table if the geometry is SingleGeo as it is not needed
  1726. # and can create some problems
  1727. if self.multigeo is False:
  1728. self.ui.geo_tools_table.setColumnHidden(6, True)
  1729. else:
  1730. self.ui.geo_tools_table.setColumnHidden(6, False)
  1731. self.set_tool_offset_visibility(selected_row)
  1732. self.ui_connect()
  1733. def set_ui(self, ui):
  1734. FlatCAMObj.set_ui(self, ui)
  1735. log.debug("FlatCAMGeometry.set_ui()")
  1736. assert isinstance(self.ui, GeometryObjectUI), \
  1737. "Expected a GeometryObjectUI, got %s" % type(self.ui)
  1738. # populate postprocessor names in the combobox
  1739. for name in list(self.app.postprocessors.keys()):
  1740. self.ui.pp_geometry_name_cb.addItem(name)
  1741. self.form_fields.update({
  1742. "plot": self.ui.plot_cb,
  1743. "cutz": self.ui.cutz_entry,
  1744. "vtipdia": self.ui.tipdia_entry,
  1745. "vtipangle": self.ui.tipangle_entry,
  1746. "travelz": self.ui.travelz_entry,
  1747. "feedrate": self.ui.cncfeedrate_entry,
  1748. "feedrate_z": self.ui.cncplunge_entry,
  1749. "feedrate_rapid": self.ui.cncfeedrate_rapid_entry,
  1750. "spindlespeed": self.ui.cncspindlespeed_entry,
  1751. "dwell": self.ui.dwell_cb,
  1752. "dwelltime": self.ui.dwelltime_entry,
  1753. "multidepth": self.ui.mpass_cb,
  1754. "ppname_g": self.ui.pp_geometry_name_cb,
  1755. "depthperpass": self.ui.maxdepth_entry,
  1756. "extracut": self.ui.extracut_cb,
  1757. "toolchange": self.ui.toolchangeg_cb,
  1758. "toolchangez": self.ui.toolchangez_entry,
  1759. "endz": self.ui.gendz_entry,
  1760. })
  1761. # Fill form fields only on object create
  1762. self.to_form()
  1763. self.ui.tipdialabel.hide()
  1764. self.ui.tipdia_entry.hide()
  1765. self.ui.tipanglelabel.hide()
  1766. self.ui.tipangle_entry.hide()
  1767. self.ui.cutz_entry.setDisabled(False)
  1768. # store here the default data for Geometry Data
  1769. self.default_data = {}
  1770. self.default_data.update({
  1771. "name": None,
  1772. "plot": None,
  1773. "cutz": None,
  1774. "vtipdia": None,
  1775. "vtipangle": None,
  1776. "travelz": None,
  1777. "feedrate": None,
  1778. "feedrate_z": None,
  1779. "feedrate_rapid": None,
  1780. "dwell": None,
  1781. "dwelltime": None,
  1782. "multidepth": None,
  1783. "ppname_g": None,
  1784. "depthperpass": None,
  1785. "extracut": None,
  1786. "toolchange": None,
  1787. "toolchangez": None,
  1788. "endz": None,
  1789. "spindlespeed": None,
  1790. "toolchangexy": None,
  1791. "startz": None
  1792. })
  1793. # fill in self.default_data values from self.options
  1794. for def_key in self.default_data:
  1795. for opt_key, opt_val in self.options.items():
  1796. if def_key == opt_key:
  1797. self.default_data[def_key] = opt_val
  1798. self.tooluid += 1
  1799. if not self.tools:
  1800. self.tools.update({
  1801. self.tooluid: {
  1802. 'tooldia': self.options["cnctooldia"],
  1803. 'offset': 'Path',
  1804. 'offset_value': 0.0,
  1805. 'type': 'Rough',
  1806. 'tool_type': 'C1',
  1807. 'data': self.default_data,
  1808. 'solid_geometry': []
  1809. }
  1810. })
  1811. else:
  1812. # if self.tools is not empty then it can safely be assumed that it comes from an opened project.
  1813. # Because of the serialization the self.tools list on project save, the dict keys (members of self.tools
  1814. # are each a dict) are turned into strings so we rebuild the self.tools elements so the keys are
  1815. # again float type; dict's don't like having keys changed when iterated through therefore the need for the
  1816. # following convoluted way of changing the keys from string to float type
  1817. temp_tools = {}
  1818. new_key = 0.0
  1819. for tooluid_key in self.tools:
  1820. val = dict(self.tools[tooluid_key])
  1821. new_key = deepcopy(int(tooluid_key))
  1822. temp_tools[new_key] = val
  1823. self.tools.clear()
  1824. self.tools = dict(temp_tools)
  1825. self.ui.tool_offset_entry.hide()
  1826. self.ui.tool_offset_lbl.hide()
  1827. # used to store the state of the mpass_cb if the selected postproc for geometry is hpgl
  1828. self.old_pp_state = self.default_data['multidepth']
  1829. self.old_toolchangeg_state = self.default_data['toolchange']
  1830. if not isinstance(self.ui, GeometryObjectUI):
  1831. log.debug("Expected a GeometryObjectUI, got %s" % type(self.ui))
  1832. return
  1833. self.ui.geo_tools_table.setupContextMenu()
  1834. self.ui.geo_tools_table.addContextMenu(
  1835. "Copy", self.on_tool_copy, icon=QtGui.QIcon("share/copy16.png"))
  1836. self.ui.geo_tools_table.addContextMenu(
  1837. "Delete", lambda: self.on_tool_delete(all=None), icon=QtGui.QIcon("share/delete32.png"))
  1838. self.ui.plot_cb.stateChanged.connect(self.on_plot_cb_click)
  1839. self.ui.generate_cnc_button.clicked.connect(self.on_generatecnc_button_click)
  1840. self.ui.paint_tool_button.clicked.connect(self.app.paint_tool.run)
  1841. self.ui.pp_geometry_name_cb.activated.connect(self.on_pp_changed)
  1842. def set_tool_offset_visibility(self, current_row):
  1843. if current_row is None:
  1844. return
  1845. try:
  1846. tool_offset = self.ui.geo_tools_table.cellWidget(current_row, 2)
  1847. if tool_offset is not None:
  1848. tool_offset_txt = tool_offset.currentText()
  1849. if tool_offset_txt == 'Custom':
  1850. self.ui.tool_offset_entry.show()
  1851. self.ui.tool_offset_lbl.show()
  1852. else:
  1853. self.ui.tool_offset_entry.hide()
  1854. self.ui.tool_offset_lbl.hide()
  1855. except Exception as e:
  1856. log.debug("set_tool_offset_visibility() --> " + str(e))
  1857. return
  1858. def on_offset_value_edited(self):
  1859. '''
  1860. This will save the offset_value into self.tools storage whenever the oofset value is edited
  1861. :return:
  1862. '''
  1863. for current_row in self.ui.geo_tools_table.selectedItems():
  1864. # sometime the header get selected and it has row number -1
  1865. # we don't want to do anything with the header :)
  1866. if current_row.row() < 0:
  1867. continue
  1868. tool_uid = int(self.ui.geo_tools_table.item(current_row.row(), 5).text())
  1869. self.set_tool_offset_visibility(current_row.row())
  1870. for tooluid_key, tooluid_value in self.tools.items():
  1871. if int(tooluid_key) == tool_uid:
  1872. tooluid_value['offset_value'] = self.ui.tool_offset_entry.get_value()
  1873. def ui_connect(self):
  1874. # on any change to the widgets that matter it will be called self.gui_form_to_storage which will save the
  1875. # changes in geometry UI
  1876. for i in range(self.ui.grid3.count()):
  1877. try:
  1878. # works for CheckBoxes
  1879. self.ui.grid3.itemAt(i).widget().stateChanged.connect(self.gui_form_to_storage)
  1880. except:
  1881. # works for ComboBoxes
  1882. try:
  1883. self.ui.grid3.itemAt(i).widget().currentIndexChanged.connect(self.gui_form_to_storage)
  1884. except:
  1885. # works for Entry
  1886. try:
  1887. self.ui.grid3.itemAt(i).widget().editingFinished.connect(self.gui_form_to_storage)
  1888. except:
  1889. pass
  1890. for row in range(self.ui.geo_tools_table.rowCount()):
  1891. for col in [2, 3, 4]:
  1892. self.ui.geo_tools_table.cellWidget(row, col).currentIndexChanged.connect(
  1893. self.on_tooltable_cellwidget_change)
  1894. # I use lambda's because the connected functions have parameters that could be used in certain scenarios
  1895. self.ui.addtool_btn.clicked.connect(lambda: self.on_tool_add())
  1896. self.ui.copytool_btn.clicked.connect(lambda: self.on_tool_copy())
  1897. self.ui.deltool_btn.clicked.connect(lambda: self.on_tool_delete())
  1898. self.ui.geo_tools_table.currentItemChanged.connect(self.on_row_selection_change)
  1899. self.ui.geo_tools_table.itemChanged.connect(self.on_tool_edit)
  1900. self.ui.tool_offset_entry.editingFinished.connect(self.on_offset_value_edited)
  1901. for row in range(self.ui.geo_tools_table.rowCount()):
  1902. self.ui.geo_tools_table.cellWidget(row, 6).clicked.connect(self.on_plot_cb_click_table)
  1903. self.ui.plot_cb.stateChanged.connect(self.on_plot_cb_click)
  1904. def ui_disconnect(self):
  1905. try:
  1906. # on any change to the widgets that matter it will be called self.gui_form_to_storage which will save the
  1907. # changes in geometry UI
  1908. for i in range(self.ui.grid3.count()):
  1909. if isinstance(self.ui.grid3.itemAt(i).widget(), FCCheckBox):
  1910. self.ui.grid3.itemAt(i).widget().stateChanged.disconnect()
  1911. if isinstance(self.ui.grid3.itemAt(i).widget(), FCComboBox):
  1912. self.ui.grid3.itemAt(i).widget().currentIndexChanged.disconnect()
  1913. if isinstance(self.ui.grid3.itemAt(i).widget(), LengthEntry) or \
  1914. isinstance(self.ui.grid3.itemAt(i), IntEntry) or \
  1915. isinstance(self.ui.grid3.itemAt(i), FCEntry):
  1916. self.ui.grid3.itemAt(i).widget().editingFinished.disconnect()
  1917. except:
  1918. pass
  1919. try:
  1920. for row in range(self.ui.geo_tools_table.rowCount()):
  1921. for col in [2, 3, 4]:
  1922. self.ui.geo_tools_table.cellWidget(row, col).currentIndexChanged.disconnect()
  1923. except:
  1924. pass
  1925. # I use lambda's because the connected functions have parameters that could be used in certain scenarios
  1926. try:
  1927. self.ui.addtool_btn.clicked.disconnect()
  1928. except:
  1929. pass
  1930. try:
  1931. self.ui.copytool_btn.clicked.disconnect()
  1932. except:
  1933. pass
  1934. try:
  1935. self.ui.deltool_btn.clicked.disconnect()
  1936. except:
  1937. pass
  1938. try:
  1939. self.ui.geo_tools_table.currentItemChanged.disconnect()
  1940. except:
  1941. pass
  1942. try:
  1943. self.ui.geo_tools_table.itemChanged.disconnect()
  1944. except:
  1945. pass
  1946. try:
  1947. self.ui.tool_offset_entry.editingFinished.disconnect()
  1948. except:
  1949. pass
  1950. for row in range(self.ui.geo_tools_table.rowCount()):
  1951. try:
  1952. self.ui.geo_tools_table.cellWidget(row, 6).clicked.disconnect()
  1953. except:
  1954. pass
  1955. try:
  1956. self.ui.plot_cb.stateChanged.disconnect()
  1957. except:
  1958. pass
  1959. def on_tool_add(self, dia=None):
  1960. self.ui_disconnect()
  1961. last_offset = None
  1962. last_offset_value = None
  1963. last_type = None
  1964. last_tool_type = None
  1965. last_data = None
  1966. last_solid_geometry = []
  1967. if dia is not None:
  1968. tooldia = dia
  1969. else:
  1970. tooldia = self.ui.addtool_entry.get_value()
  1971. if tooldia is None:
  1972. self.build_ui()
  1973. self.app.inform.emit("[error_notcl] Please enter the desired tool diameter in Float format.")
  1974. return
  1975. # construct a list of all 'tooluid' in the self.tools
  1976. tool_uid_list = []
  1977. for tooluid_key in self.tools:
  1978. tool_uid_item = int(tooluid_key)
  1979. tool_uid_list.append(tool_uid_item)
  1980. # find maximum from the temp_uid, add 1 and this is the new 'tooluid'
  1981. if not tool_uid_list:
  1982. max_uid = 0
  1983. else:
  1984. max_uid = max(tool_uid_list)
  1985. self.tooluid = max_uid + 1
  1986. if self.units == 'IN':
  1987. tooldia = float('%.4f' % tooldia)
  1988. else:
  1989. tooldia = float('%.2f' % tooldia)
  1990. # here we actually add the new tool; if there is no tool in the tool table we add a tool with default data
  1991. # otherwise we add a tool with data copied from last tool
  1992. if not self.tools:
  1993. self.tools.update({
  1994. self.tooluid: {
  1995. 'tooldia': tooldia,
  1996. 'offset': 'Path',
  1997. 'offset_value': 0.0,
  1998. 'type': 'Rough',
  1999. 'tool_type': 'C1',
  2000. 'data': dict(self.default_data),
  2001. 'solid_geometry': []
  2002. }
  2003. })
  2004. else:
  2005. # print("LAST", self.tools[maxuid])
  2006. last_data = self.tools[max_uid]['data']
  2007. last_offset = self.tools[max_uid]['offset']
  2008. last_offset_value = self.tools[max_uid]['offset_value']
  2009. last_type = self.tools[max_uid]['type']
  2010. last_tool_type = self.tools[max_uid]['tool_type']
  2011. last_solid_geometry = self.tools[max_uid]['solid_geometry']
  2012. self.tools.update({
  2013. self.tooluid: {
  2014. 'tooldia': tooldia,
  2015. 'offset': last_offset,
  2016. 'offset_value': last_offset_value,
  2017. 'type': last_type,
  2018. 'tool_type': last_tool_type,
  2019. 'data': dict(last_data),
  2020. 'solid_geometry': deepcopy(last_solid_geometry)
  2021. }
  2022. })
  2023. # print("CURRENT", self.tools[-1])
  2024. self.ui.tool_offset_entry.hide()
  2025. self.ui.tool_offset_lbl.hide()
  2026. # we do this HACK to make sure the tools attribute to be serialized is updated in the self.ser_attrs list
  2027. try:
  2028. self.ser_attrs.remove('tools')
  2029. except:
  2030. pass
  2031. self.ser_attrs.append('tools')
  2032. self.app.inform.emit("[success] Tool added in Tool Table.")
  2033. self.build_ui()
  2034. def on_tool_copy(self, all=None):
  2035. self.ui_disconnect()
  2036. # find the tool_uid maximum value in the self.tools
  2037. uid_list = []
  2038. for key in self.tools:
  2039. uid_list.append(int(key))
  2040. try:
  2041. max_uid = max(uid_list, key=int)
  2042. except ValueError:
  2043. max_uid = 0
  2044. if all is None:
  2045. if self.ui.geo_tools_table.selectedItems():
  2046. for current_row in self.ui.geo_tools_table.selectedItems():
  2047. # sometime the header get selected and it has row number -1
  2048. # we don't want to do anything with the header :)
  2049. if current_row.row() < 0:
  2050. continue
  2051. try:
  2052. tooluid_copy = int(self.ui.geo_tools_table.item(current_row.row(), 5).text())
  2053. self.set_tool_offset_visibility(current_row.row())
  2054. max_uid += 1
  2055. self.tools[int(max_uid)] = dict(self.tools[tooluid_copy])
  2056. except AttributeError:
  2057. self.app.inform.emit("[warning_notcl]Failed. Select a tool to copy.")
  2058. self.build_ui()
  2059. return
  2060. except Exception as e:
  2061. log.debug("on_tool_copy() --> " + str(e))
  2062. # deselect the table
  2063. # self.ui.geo_tools_table.clearSelection()
  2064. else:
  2065. self.app.inform.emit("[warning_notcl]Failed. Select a tool to copy.")
  2066. self.build_ui()
  2067. return
  2068. else:
  2069. # we copy all tools in geo_tools_table
  2070. try:
  2071. temp_tools = dict(self.tools)
  2072. max_uid += 1
  2073. for tooluid in temp_tools:
  2074. self.tools[int(max_uid)] = dict(temp_tools[tooluid])
  2075. temp_tools.clear()
  2076. except Exception as e:
  2077. log.debug("on_tool_copy() --> " + str(e))
  2078. # if there are no more tools in geo tools table then hide the tool offset
  2079. if not self.tools:
  2080. self.ui.tool_offset_entry.hide()
  2081. self.ui.tool_offset_lbl.hide()
  2082. # we do this HACK to make sure the tools attribute to be serialized is updated in the self.ser_attrs list
  2083. try:
  2084. self.ser_attrs.remove('tools')
  2085. except:
  2086. pass
  2087. self.ser_attrs.append('tools')
  2088. self.build_ui()
  2089. self.app.inform.emit("[success] Tool was copied in Tool Table.")
  2090. def on_tool_edit(self, current_item):
  2091. self.ui_disconnect()
  2092. current_row = current_item.row()
  2093. tool_dia = float('%.4f' % float(self.ui.geo_tools_table.item(current_row, 1).text()))
  2094. tooluid = int(self.ui.geo_tools_table.item(current_row, 5).text())
  2095. self.tools[tooluid]['tooldia'] = tool_dia
  2096. try:
  2097. self.ser_attrs.remove('tools')
  2098. self.ser_attrs.append('tools')
  2099. except:
  2100. pass
  2101. self.app.inform.emit("[success] Tool was edited in Tool Table.")
  2102. self.build_ui()
  2103. def on_tool_delete(self, all=None):
  2104. self.ui_disconnect()
  2105. if all is None:
  2106. if self.ui.geo_tools_table.selectedItems():
  2107. for current_row in self.ui.geo_tools_table.selectedItems():
  2108. # sometime the header get selected and it has row number -1
  2109. # we don't want to do anything with the header :)
  2110. if current_row.row() < 0:
  2111. continue
  2112. try:
  2113. tooluid_del = int(self.ui.geo_tools_table.item(current_row.row(), 5).text())
  2114. self.set_tool_offset_visibility(current_row.row())
  2115. temp_tools = dict(self.tools)
  2116. for tooluid_key in self.tools:
  2117. if int(tooluid_key) == tooluid_del:
  2118. temp_tools.pop(tooluid_del, None)
  2119. self.tools = dict(temp_tools)
  2120. temp_tools.clear()
  2121. except AttributeError:
  2122. self.app.inform.emit("[warning_notcl]Failed. Select a tool to delete.")
  2123. self.build_ui()
  2124. return
  2125. except Exception as e:
  2126. log.debug("on_tool_delete() --> " + str(e))
  2127. # deselect the table
  2128. # self.ui.geo_tools_table.clearSelection()
  2129. else:
  2130. self.app.inform.emit("[warning_notcl]Failed. Select a tool to delete.")
  2131. self.build_ui()
  2132. return
  2133. else:
  2134. # we delete all tools in geo_tools_table
  2135. self.tools.clear()
  2136. self.app.plot_all()
  2137. # if there are no more tools in geo tools table then hide the tool offset
  2138. if not self.tools:
  2139. self.ui.tool_offset_entry.hide()
  2140. self.ui.tool_offset_lbl.hide()
  2141. # we do this HACK to make sure the tools attribute to be serialized is updated in the self.ser_attrs list
  2142. try:
  2143. self.ser_attrs.remove('tools')
  2144. except:
  2145. pass
  2146. self.ser_attrs.append('tools')
  2147. self.build_ui()
  2148. self.app.inform.emit("[success] Tool was deleted in Tool Table.")
  2149. obj_active = self.app.collection.get_active()
  2150. # if the object was MultiGeo and now it has no tool at all (therefore no geometry)
  2151. # we make it back SingleGeo
  2152. if self.ui.geo_tools_table.rowCount() <= 0:
  2153. obj_active.multigeo = False
  2154. obj_active.options['xmin'] = 0
  2155. obj_active.options['ymin'] = 0
  2156. obj_active.options['xmax'] = 0
  2157. obj_active.options['ymax'] = 0
  2158. if obj_active.multigeo is True:
  2159. try:
  2160. xmin, ymin, xmax, ymax = obj_active.bounds()
  2161. obj_active.options['xmin'] = xmin
  2162. obj_active.options['ymin'] = ymin
  2163. obj_active.options['xmax'] = xmax
  2164. obj_active.options['ymax'] = ymax
  2165. except:
  2166. obj_active.options['xmin'] = 0
  2167. obj_active.options['ymin'] = 0
  2168. obj_active.options['xmax'] = 0
  2169. obj_active.options['ymax'] = 0
  2170. def on_row_selection_change(self):
  2171. self.update_ui()
  2172. def update_ui(self, row=None):
  2173. self.ui_disconnect()
  2174. if row is None:
  2175. try:
  2176. current_row = self.ui.geo_tools_table.currentRow()
  2177. except:
  2178. current_row = 0
  2179. else:
  2180. current_row = row
  2181. if current_row < 0:
  2182. current_row = 0
  2183. self.set_tool_offset_visibility(current_row)
  2184. # populate the form with the data from the tool associated with the row parameter
  2185. try:
  2186. tooluid = int(self.ui.geo_tools_table.item(current_row, 5).text())
  2187. except Exception as e:
  2188. log.debug("Tool missing. Add a tool in Geo Tool Table. %s" % str(e))
  2189. return
  2190. # update the form with the V-Shape fields if V-Shape selected in the geo_tool_table
  2191. # also modify the Cut Z form entry to reflect the calculated Cut Z from values got from V-Shape Fields
  2192. try:
  2193. tool_type_txt = self.ui.geo_tools_table.cellWidget(current_row, 4).currentText()
  2194. self.ui_update_v_shape(tool_type_txt=tool_type_txt)
  2195. except Exception as e:
  2196. log.debug("Tool missing. Add a tool in Geo Tool Table. %s" % str(e))
  2197. return
  2198. try:
  2199. # set the form with data from the newly selected tool
  2200. for tooluid_key, tooluid_value in self.tools.items():
  2201. if int(tooluid_key) == tooluid:
  2202. for key, value in tooluid_value.items():
  2203. if key == 'data':
  2204. form_value_storage = tooluid_value[key]
  2205. self.update_form(form_value_storage)
  2206. if key == 'offset_value':
  2207. # update the offset value in the entry even if the entry is hidden
  2208. self.ui.tool_offset_entry.set_value(tooluid_value[key])
  2209. if key == 'tool_type' and value == 'V':
  2210. self.update_cutz()
  2211. except Exception as e:
  2212. log.debug("FlatCAMObj ---> update_ui() " + str(e))
  2213. self.ui_connect()
  2214. def ui_update_v_shape(self, tool_type_txt):
  2215. if tool_type_txt == 'V':
  2216. self.ui.tipdialabel.show()
  2217. self.ui.tipdia_entry.show()
  2218. self.ui.tipanglelabel.show()
  2219. self.ui.tipangle_entry.show()
  2220. self.ui.cutz_entry.setDisabled(True)
  2221. self.update_cutz()
  2222. else:
  2223. self.ui.tipdialabel.hide()
  2224. self.ui.tipdia_entry.hide()
  2225. self.ui.tipanglelabel.hide()
  2226. self.ui.tipangle_entry.hide()
  2227. self.ui.cutz_entry.setDisabled(False)
  2228. def update_cutz(self):
  2229. vdia = float(self.ui.tipdia_entry.get_value())
  2230. half_vangle = float(self.ui.tipangle_entry.get_value()) / 2
  2231. row = self.ui.geo_tools_table.currentRow()
  2232. tool_uid = int(self.ui.geo_tools_table.item(row, 5).text())
  2233. tooldia = float(self.ui.geo_tools_table.item(row, 1).text())
  2234. new_cutz = (tooldia - vdia) / (2 * math.tan(math.radians(half_vangle)))
  2235. new_cutz = float('%.4f' % -new_cutz)
  2236. self.ui.cutz_entry.set_value(new_cutz)
  2237. # store the new CutZ value into storage (self.tools)
  2238. for tooluid_key, tooluid_value in self.tools.items():
  2239. if int(tooluid_key) == tool_uid:
  2240. tooluid_value['data']['cutz'] = new_cutz
  2241. def on_tooltable_cellwidget_change(self):
  2242. cw = self.sender()
  2243. cw_index = self.ui.geo_tools_table.indexAt(cw.pos())
  2244. cw_row = cw_index.row()
  2245. cw_col = cw_index.column()
  2246. current_uid = int(self.ui.geo_tools_table.item(cw_row, 5).text())
  2247. # store the text of the cellWidget that changed it's index in the self.tools
  2248. for tooluid_key, tooluid_value in self.tools.items():
  2249. if int(tooluid_key) == current_uid:
  2250. cb_txt = cw.currentText()
  2251. if cw_col == 2:
  2252. tooluid_value['offset'] = cb_txt
  2253. if cb_txt == 'Custom':
  2254. self.ui.tool_offset_entry.show()
  2255. self.ui.tool_offset_lbl.show()
  2256. else:
  2257. self.ui.tool_offset_entry.hide()
  2258. self.ui.tool_offset_lbl.hide()
  2259. # reset the offset_value in storage self.tools
  2260. tooluid_value['offset_value'] = 0.0
  2261. elif cw_col == 3:
  2262. # force toolpath type as 'Iso' if the tool type is V-Shape
  2263. if self.ui.geo_tools_table.cellWidget(cw_row, 4).currentText() == 'V':
  2264. tooluid_value['type'] = 'Iso'
  2265. idx = self.ui.geo_tools_table.cellWidget(cw_row, 3).findText('Iso')
  2266. self.ui.geo_tools_table.cellWidget(cw_row, 3).setCurrentIndex(idx)
  2267. else:
  2268. tooluid_value['type'] = cb_txt
  2269. elif cw_col == 4:
  2270. tooluid_value['tool_type'] = cb_txt
  2271. # if the tool_type selected is V-Shape then autoselect the toolpath type as Iso
  2272. if cb_txt == 'V':
  2273. idx = self.ui.geo_tools_table.cellWidget(cw_row, 3).findText('Iso')
  2274. self.ui.geo_tools_table.cellWidget(cw_row, 3).setCurrentIndex(idx)
  2275. self.ui_update_v_shape(tool_type_txt=self.ui.geo_tools_table.cellWidget(cw_row, 4).currentText())
  2276. def update_form(self, dict_storage):
  2277. for form_key in self.form_fields:
  2278. for storage_key in dict_storage:
  2279. if form_key == storage_key:
  2280. try:
  2281. self.form_fields[form_key].set_value(dict_storage[form_key])
  2282. except Exception as e:
  2283. log.debug(str(e))
  2284. # this is done here because those buttons control through OptionalInputSelection if some entry's are Enabled
  2285. # or not. But due of using the ui_disconnect() status is no longer updated and I had to do it here
  2286. self.ui.ois_dwell_geo.on_cb_change()
  2287. self.ui.ois_mpass_geo.on_cb_change()
  2288. self.ui.ois_tcz_geo.on_cb_change()
  2289. def gui_form_to_storage(self):
  2290. self.ui_disconnect()
  2291. widget_changed = self.sender()
  2292. try:
  2293. widget_idx = self.ui.grid3.indexOf(widget_changed)
  2294. except:
  2295. return
  2296. # those are the indexes for the V-Tip Dia and V-Tip Angle, if edited calculate the new Cut Z
  2297. if widget_idx == 1 or widget_idx == 3:
  2298. self.update_cutz()
  2299. # the original connect() function of the OptionalInpuSelection is no longer working because of the
  2300. # ui_diconnect() so I use this 'hack'
  2301. if isinstance(widget_changed, FCCheckBox):
  2302. if widget_changed.text() == 'Multi-Depth:':
  2303. self.ui.ois_mpass_geo.on_cb_change()
  2304. if widget_changed.text() == 'Tool change':
  2305. self.ui.ois_tcz_geo.on_cb_change()
  2306. if widget_changed.text() == 'Dwell:':
  2307. self.ui.ois_dwell_geo.on_cb_change()
  2308. row = self.ui.geo_tools_table.currentRow()
  2309. if row < 0:
  2310. row = 0
  2311. # store all the data associated with the row parameter to the self.tools storage
  2312. tooldia_item = float(self.ui.geo_tools_table.item(row, 1).text())
  2313. offset_item = self.ui.geo_tools_table.cellWidget(row, 2).currentText()
  2314. type_item = self.ui.geo_tools_table.cellWidget(row, 3).currentText()
  2315. tool_type_item = self.ui.geo_tools_table.cellWidget(row, 4).currentText()
  2316. tooluid_item = int(self.ui.geo_tools_table.item(row, 5).text())
  2317. offset_value_item = self.ui.tool_offset_entry.get_value()
  2318. # this new dict will hold the actual useful data, another dict that is the value of key 'data'
  2319. temp_tools = {}
  2320. temp_dia = {}
  2321. temp_data = {}
  2322. for tooluid_key, tooluid_value in self.tools.items():
  2323. if int(tooluid_key) == tooluid_item:
  2324. for key, value in tooluid_value.items():
  2325. if key == 'tooldia':
  2326. temp_dia[key] = tooldia_item
  2327. # update the 'offset', 'type' and 'tool_type' sections
  2328. if key == 'offset':
  2329. temp_dia[key] = offset_item
  2330. if key == 'type':
  2331. temp_dia[key] = type_item
  2332. if key == 'tool_type':
  2333. temp_dia[key] = tool_type_item
  2334. if key == 'offset_value':
  2335. temp_dia[key] = offset_value_item
  2336. if key == 'data':
  2337. # update the 'data' section
  2338. for data_key in tooluid_value[key].keys():
  2339. for form_key, form_value in self.form_fields.items():
  2340. if form_key == data_key:
  2341. temp_data[data_key] = form_value.get_value()
  2342. # make sure we make a copy of the keys not in the form (we may use 'data' keys that are
  2343. # updated from self.app.defaults
  2344. if data_key not in self.form_fields:
  2345. temp_data[data_key] = value[data_key]
  2346. temp_dia[key] = dict(temp_data)
  2347. temp_data.clear()
  2348. if key == 'solid_geometry':
  2349. temp_dia[key] = deepcopy(self.tools[tooluid_key]['solid_geometry'])
  2350. temp_tools[tooluid_key] = dict(temp_dia)
  2351. else:
  2352. temp_tools[tooluid_key] = dict(tooluid_value)
  2353. self.tools.clear()
  2354. self.tools = dict(temp_tools)
  2355. temp_tools.clear()
  2356. self.ui_connect()
  2357. def select_tools_table_row(self, row, clearsel=None):
  2358. if clearsel:
  2359. self.ui.geo_tools_table.clearSelection()
  2360. if self.ui.geo_tools_table.rowCount() > 0:
  2361. # self.ui.geo_tools_table.item(row, 0).setSelected(True)
  2362. self.ui.geo_tools_table.setCurrentItem(self.ui.geo_tools_table.item(row, 0))
  2363. def export_dxf(self):
  2364. units = self.app.general_options_form.general_app_group.units_radio.get_value().upper()
  2365. dwg = None
  2366. try:
  2367. dwg = ezdxf.new('R2010')
  2368. msp = dwg.modelspace()
  2369. def g2dxf(dxf_space, geo):
  2370. if isinstance(geo, MultiPolygon):
  2371. for poly in geo:
  2372. ext_points = list(poly.exterior.coords)
  2373. dxf_space.add_lwpolyline(ext_points)
  2374. for interior in poly.interiors:
  2375. dxf_space.add_lwpolyline(list(interior.coords))
  2376. if isinstance(geo, Polygon):
  2377. ext_points = list(geo.exterior.coords)
  2378. dxf_space.add_lwpolyline(ext_points)
  2379. for interior in geo.interiors:
  2380. dxf_space.add_lwpolyline(list(interior.coords))
  2381. if isinstance(geo, MultiLineString):
  2382. for line in geo:
  2383. dxf_space.add_lwpolyline(list(line.coords))
  2384. if isinstance(geo, LineString) or isinstance(geo, LinearRing):
  2385. dxf_space.add_lwpolyline(list(geo.coords))
  2386. multigeo_solid_geometry = []
  2387. if self.multigeo:
  2388. for tool in self.tools:
  2389. multigeo_solid_geometry += self.tools[tool]['solid_geometry']
  2390. else:
  2391. multigeo_solid_geometry = self.solid_geometry
  2392. for geo in multigeo_solid_geometry:
  2393. if type(geo) == list:
  2394. for g in geo:
  2395. g2dxf(msp, g)
  2396. else:
  2397. g2dxf(msp, geo)
  2398. # points = FlatCAMGeometry.get_pts(geo)
  2399. # msp.add_lwpolyline(points)
  2400. except Exception as e:
  2401. log.debug(str(e))
  2402. return dwg
  2403. def get_selected_tools_table_items(self):
  2404. """
  2405. Returns a list of lists, each list in the list is made out of row elements
  2406. :return: List of table_tools items.
  2407. :rtype: list
  2408. """
  2409. table_tools_items = []
  2410. for x in self.ui.geo_tools_table.selectedItems():
  2411. table_tools_items.append([self.ui.geo_tools_table.item(x.row(), column).text()
  2412. for column in range(0, self.ui.geo_tools_table.columnCount())])
  2413. for item in table_tools_items:
  2414. item[0] = str(item[0])
  2415. return table_tools_items
  2416. def on_pp_changed(self):
  2417. current_pp = self.ui.pp_geometry_name_cb.get_value()
  2418. if current_pp == 'hpgl':
  2419. self.old_pp_state = self.ui.mpass_cb.get_value()
  2420. self.old_toolchangeg_state = self.ui.toolchangeg_cb.get_value()
  2421. self.ui.mpass_cb.set_value(False)
  2422. self.ui.mpass_cb.setDisabled(True)
  2423. self.ui.toolchangeg_cb.set_value(True)
  2424. self.ui.toolchangeg_cb.setDisabled(True)
  2425. else:
  2426. self.ui.mpass_cb.set_value(self.old_pp_state)
  2427. self.ui.mpass_cb.setDisabled(False)
  2428. self.ui.toolchangeg_cb.set_value(self.old_toolchangeg_state)
  2429. self.ui.toolchangeg_cb.setDisabled(False)
  2430. def on_generatecnc_button_click(self, *args):
  2431. self.app.report_usage("geometry_on_generatecnc_button")
  2432. self.read_form()
  2433. # test to see if we have tools available in the tool table
  2434. if self.ui.geo_tools_table.selectedItems():
  2435. for x in self.ui.geo_tools_table.selectedItems():
  2436. tooldia = float(self.ui.geo_tools_table.item(x.row(), 1).text())
  2437. tooluid = int(self.ui.geo_tools_table.item(x.row(), 5).text())
  2438. for tooluid_key, tooluid_value in self.tools.items():
  2439. if int(tooluid_key) == tooluid:
  2440. self.sel_tools.update({
  2441. tooluid: dict(tooluid_value)
  2442. })
  2443. self.mtool_gen_cncjob()
  2444. self.ui.geo_tools_table.clearSelection()
  2445. else:
  2446. self.app.inform.emit("[error_notcl] Failed. No tool selected in the tool table ...")
  2447. def mtool_gen_cncjob(self, segx=None, segy=None, use_thread=True):
  2448. """
  2449. Creates a multi-tool CNCJob out of this Geometry object.
  2450. The actual work is done by the target FlatCAMCNCjob object's
  2451. `generate_from_geometry_2()` method.
  2452. :param z_cut: Cut depth (negative)
  2453. :param z_move: Hight of the tool when travelling (not cutting)
  2454. :param feedrate: Feed rate while cutting on X - Y plane
  2455. :param feedrate_z: Feed rate while cutting on Z plane
  2456. :param feedrate_rapid: Feed rate while moving with rapids
  2457. :param tooldia: Tool diameter
  2458. :param outname: Name of the new object
  2459. :param spindlespeed: Spindle speed (RPM)
  2460. :param ppname_g Name of the postprocessor
  2461. :return: None
  2462. """
  2463. offset_str = ''
  2464. multitool_gcode = ''
  2465. # use the name of the first tool selected in self.geo_tools_table which has the diameter passed as tool_dia
  2466. outname = "%s_%s" % (self.options["name"], 'cnc')
  2467. segx = segx if segx is not None else float(self.app.defaults['geometry_segx'])
  2468. segy = segy if segy is not None else float(self.app.defaults['geometry_segy'])
  2469. # Object initialization function for app.new_object()
  2470. # RUNNING ON SEPARATE THREAD!
  2471. def job_init_single_geometry(job_obj, app_obj):
  2472. assert isinstance(job_obj, FlatCAMCNCjob), \
  2473. "Initializer expected a FlatCAMCNCjob, got %s" % type(job_obj)
  2474. # count the tools
  2475. tool_cnt = 0
  2476. dia_cnc_dict = {}
  2477. # this turn on the FlatCAMCNCJob plot for multiple tools
  2478. job_obj.multitool = True
  2479. job_obj.multigeo = False
  2480. job_obj.cnc_tools.clear()
  2481. # job_obj.create_geometry()
  2482. job_obj.options['Tools_in_use'] = self.get_selected_tools_table_items()
  2483. job_obj.segx = segx
  2484. job_obj.segy = segy
  2485. for tooluid_key in self.sel_tools:
  2486. tool_cnt += 1
  2487. app_obj.progress.emit(20)
  2488. for diadict_key, diadict_value in self.sel_tools[tooluid_key].items():
  2489. if diadict_key == 'tooldia':
  2490. tooldia_val = float('%.4f' % float(diadict_value))
  2491. dia_cnc_dict.update({
  2492. diadict_key: tooldia_val
  2493. })
  2494. if diadict_key == 'offset':
  2495. o_val = diadict_value.lower()
  2496. dia_cnc_dict.update({
  2497. diadict_key: o_val
  2498. })
  2499. if diadict_key == 'type':
  2500. t_val = diadict_value
  2501. dia_cnc_dict.update({
  2502. diadict_key: t_val
  2503. })
  2504. if diadict_key == 'tool_type':
  2505. tt_val = diadict_value
  2506. dia_cnc_dict.update({
  2507. diadict_key: tt_val
  2508. })
  2509. if diadict_key == 'data':
  2510. for data_key, data_value in diadict_value.items():
  2511. if data_key == "multidepth":
  2512. multidepth = data_value
  2513. if data_key == "depthperpass":
  2514. depthpercut = data_value
  2515. if data_key == "extracut":
  2516. extracut = data_value
  2517. if data_key == "startz":
  2518. startz = data_value
  2519. if data_key == "endz":
  2520. endz = data_value
  2521. if data_key == "toolchangez":
  2522. toolchangez =data_value
  2523. if data_key == "toolchangexy":
  2524. toolchangexy = data_value
  2525. if data_key == "toolchange":
  2526. toolchange = data_value
  2527. if data_key == "cutz":
  2528. z_cut = data_value
  2529. if data_key == "travelz":
  2530. z_move = data_value
  2531. if data_key == "feedrate":
  2532. feedrate = data_value
  2533. if data_key == "feedrate_z":
  2534. feedrate_z = data_value
  2535. if data_key == "feedrate_rapid":
  2536. feedrate_rapid = data_value
  2537. if data_key == "ppname_g":
  2538. pp_geometry_name = data_value
  2539. if data_key == "spindlespeed":
  2540. spindlespeed = data_value
  2541. if data_key == "dwell":
  2542. dwell = data_value
  2543. if data_key == "dwelltime":
  2544. dwelltime = data_value
  2545. datadict = dict(diadict_value)
  2546. dia_cnc_dict.update({
  2547. diadict_key: datadict
  2548. })
  2549. if dia_cnc_dict['offset'] == 'in':
  2550. tool_offset = -dia_cnc_dict['tooldia'] / 2
  2551. offset_str = 'inside'
  2552. elif dia_cnc_dict['offset'].lower() == 'out':
  2553. tool_offset = dia_cnc_dict['tooldia'] / 2
  2554. offset_str = 'outside'
  2555. elif dia_cnc_dict['offset'].lower() == 'path':
  2556. offset_str = 'onpath'
  2557. tool_offset = 0.0
  2558. else:
  2559. offset_str = 'custom'
  2560. offset_value = self.ui.tool_offset_entry.get_value()
  2561. if offset_value:
  2562. tool_offset = float(offset_value)
  2563. else:
  2564. self.app.inform.emit(
  2565. "[warning] Tool Offset is selected in Tool Table but no value is provided.\n"
  2566. "Add a Tool Offset or change the Offset Type."
  2567. )
  2568. return
  2569. dia_cnc_dict.update({
  2570. 'offset_value': tool_offset
  2571. })
  2572. job_obj.coords_decimals = self.app.defaults["cncjob_coords_decimals"]
  2573. job_obj.fr_decimals = self.app.defaults["cncjob_fr_decimals"]
  2574. # Propagate options
  2575. job_obj.options["tooldia"] = tooldia_val
  2576. job_obj.options['type'] = 'Geometry'
  2577. job_obj.options['tool_dia'] = tooldia_val
  2578. app_obj.progress.emit(40)
  2579. dia_cnc_dict['gcode'] = job_obj.generate_from_geometry_2(
  2580. self, tooldia=tooldia_val, offset=tool_offset, tolerance=0.0005,
  2581. z_cut=z_cut, z_move=z_move,
  2582. feedrate=feedrate, feedrate_z=feedrate_z, feedrate_rapid=feedrate_rapid,
  2583. spindlespeed=spindlespeed, dwell=dwell, dwelltime=dwelltime,
  2584. multidepth=multidepth, depthpercut=depthpercut,
  2585. extracut=extracut, startz=startz, endz=endz,
  2586. toolchange=toolchange, toolchangez=toolchangez, toolchangexy=toolchangexy,
  2587. pp_geometry_name=pp_geometry_name,
  2588. tool_no=tool_cnt)
  2589. app_obj.progress.emit(50)
  2590. # tell gcode_parse from which point to start drawing the lines depending on what kind of
  2591. # object is the source of gcode
  2592. job_obj.toolchange_xy = "geometry"
  2593. dia_cnc_dict['gcode_parsed'] = job_obj.gcode_parse()
  2594. # TODO this serve for bounding box creation only; should be optimized
  2595. dia_cnc_dict['solid_geometry'] = cascaded_union([geo['geom'] for geo in dia_cnc_dict['gcode_parsed']])
  2596. app_obj.progress.emit(80)
  2597. job_obj.cnc_tools.update({
  2598. tooluid_key: dict(dia_cnc_dict)
  2599. })
  2600. dia_cnc_dict.clear()
  2601. # Object initialization function for app.new_object()
  2602. # RUNNING ON SEPARATE THREAD!
  2603. def job_init_multi_geometry(job_obj, app_obj):
  2604. assert isinstance(job_obj, FlatCAMCNCjob), \
  2605. "Initializer expected a FlatCAMCNCjob, got %s" % type(job_obj)
  2606. # count the tools
  2607. tool_cnt = 0
  2608. dia_cnc_dict = {}
  2609. current_uid = int(1)
  2610. # this turn on the FlatCAMCNCJob plot for multiple tools
  2611. job_obj.multitool = True
  2612. job_obj.multigeo = True
  2613. job_obj.cnc_tools.clear()
  2614. for tooluid_key in self.sel_tools:
  2615. tool_cnt += 1
  2616. app_obj.progress.emit(20)
  2617. # find the tool_dia associated with the tooluid_key
  2618. sel_tool_dia = self.sel_tools[tooluid_key]['tooldia']
  2619. # search in the self.tools for the sel_tool_dia and when found see what tooluid has
  2620. # on the found tooluid in self.tools we also have the solid_geometry that interest us
  2621. for k, v in self.tools.items():
  2622. if float('%.4f' % float(v['tooldia'])) == float('%.4f' % float(sel_tool_dia)):
  2623. current_uid = int(k)
  2624. break
  2625. for diadict_key, diadict_value in self.sel_tools[tooluid_key].items():
  2626. if diadict_key == 'tooldia':
  2627. tooldia_val = float('%.4f' % float(diadict_value))
  2628. dia_cnc_dict.update({
  2629. diadict_key: tooldia_val
  2630. })
  2631. if diadict_key == 'offset':
  2632. o_val = diadict_value.lower()
  2633. dia_cnc_dict.update({
  2634. diadict_key: o_val
  2635. })
  2636. if diadict_key == 'type':
  2637. t_val = diadict_value
  2638. dia_cnc_dict.update({
  2639. diadict_key: t_val
  2640. })
  2641. if diadict_key == 'tool_type':
  2642. tt_val = diadict_value
  2643. dia_cnc_dict.update({
  2644. diadict_key: tt_val
  2645. })
  2646. if diadict_key == 'data':
  2647. for data_key, data_value in diadict_value.items():
  2648. if data_key == "multidepth":
  2649. multidepth = data_value
  2650. if data_key == "depthperpass":
  2651. depthpercut = data_value
  2652. if data_key == "extracut":
  2653. extracut = data_value
  2654. if data_key == "startz":
  2655. startz = data_value
  2656. if data_key == "endz":
  2657. endz = data_value
  2658. if data_key == "toolchangez":
  2659. toolchangez =data_value
  2660. if data_key == "toolchangexy":
  2661. toolchangexy = data_value
  2662. if data_key == "toolchange":
  2663. toolchange = data_value
  2664. if data_key == "cutz":
  2665. z_cut = data_value
  2666. if data_key == "travelz":
  2667. z_move = data_value
  2668. if data_key == "feedrate":
  2669. feedrate = data_value
  2670. if data_key == "feedrate_z":
  2671. feedrate_z = data_value
  2672. if data_key == "feedrate_rapid":
  2673. feedrate_rapid = data_value
  2674. if data_key == "ppname_g":
  2675. pp_geometry_name = data_value
  2676. if data_key == "spindlespeed":
  2677. spindlespeed = data_value
  2678. if data_key == "dwell":
  2679. dwell = data_value
  2680. if data_key == "dwelltime":
  2681. dwelltime = data_value
  2682. datadict = dict(diadict_value)
  2683. dia_cnc_dict.update({
  2684. diadict_key: datadict
  2685. })
  2686. if dia_cnc_dict['offset'] == 'in':
  2687. tool_offset = -dia_cnc_dict['tooldia'] / 2
  2688. offset_str = 'inside'
  2689. elif dia_cnc_dict['offset'].lower() == 'out':
  2690. tool_offset = dia_cnc_dict['tooldia'] / 2
  2691. offset_str = 'outside'
  2692. elif dia_cnc_dict['offset'].lower() == 'path':
  2693. offset_str = 'onpath'
  2694. tool_offset = 0.0
  2695. else:
  2696. offset_str = 'custom'
  2697. offset_value = self.ui.tool_offset_entry.get_value()
  2698. if offset_value:
  2699. tool_offset = float(offset_value)
  2700. else:
  2701. self.app.inform.emit(
  2702. "[warning] Tool Offset is selected in Tool Table but no value is provided.\n"
  2703. "Add a Tool Offset or change the Offset Type."
  2704. )
  2705. return
  2706. dia_cnc_dict.update({
  2707. 'offset_value': tool_offset
  2708. })
  2709. job_obj.coords_decimals = self.app.defaults["cncjob_coords_decimals"]
  2710. job_obj.fr_decimals = self.app.defaults["cncjob_fr_decimals"]
  2711. # Propagate options
  2712. job_obj.options["tooldia"] = tooldia_val
  2713. job_obj.options['type'] = 'Geometry'
  2714. job_obj.options['tool_dia'] = tooldia_val
  2715. app_obj.progress.emit(40)
  2716. tool_solid_geometry = self.tools[current_uid]['solid_geometry']
  2717. dia_cnc_dict['gcode'] = job_obj.generate_from_multitool_geometry(
  2718. tool_solid_geometry, tooldia=tooldia_val, offset=tool_offset,
  2719. tolerance=0.0005, z_cut=z_cut, z_move=z_move,
  2720. feedrate=feedrate, feedrate_z=feedrate_z, feedrate_rapid=feedrate_rapid,
  2721. spindlespeed=spindlespeed, dwell=dwell, dwelltime=dwelltime,
  2722. multidepth=multidepth, depthpercut=depthpercut,
  2723. extracut=extracut, startz=startz, endz=endz,
  2724. toolchange=toolchange, toolchangez=toolchangez, toolchangexy=toolchangexy,
  2725. pp_geometry_name=pp_geometry_name,
  2726. tool_no=tool_cnt)
  2727. dia_cnc_dict['gcode_parsed'] = job_obj.gcode_parse()
  2728. # TODO this serve for bounding box creation only; should be optimized
  2729. dia_cnc_dict['solid_geometry'] = cascaded_union([geo['geom'] for geo in dia_cnc_dict['gcode_parsed']])
  2730. # tell gcode_parse from which point to start drawing the lines depending on what kind of
  2731. # object is the source of gcode
  2732. job_obj.toolchange_xy = "geometry"
  2733. app_obj.progress.emit(80)
  2734. job_obj.cnc_tools.update({
  2735. tooluid_key: dict(dia_cnc_dict)
  2736. })
  2737. dia_cnc_dict.clear()
  2738. if use_thread:
  2739. # To be run in separate thread
  2740. # The idea is that if there is a solid_geometry in the file "root" then most likely thare are no
  2741. # separate solid_geometry in the self.tools dictionary
  2742. def job_thread(app_obj):
  2743. if self.solid_geometry:
  2744. with self.app.proc_container.new("Generating CNC Code"):
  2745. app_obj.new_object("cncjob", outname, job_init_single_geometry)
  2746. app_obj.inform.emit("[success]CNCjob created: %s" % outname)
  2747. app_obj.progress.emit(100)
  2748. else:
  2749. with self.app.proc_container.new("Generating CNC Code"):
  2750. app_obj.new_object("cncjob", outname, job_init_multi_geometry)
  2751. app_obj.inform.emit("[success]CNCjob created: %s" % outname)
  2752. app_obj.progress.emit(100)
  2753. # Create a promise with the name
  2754. self.app.collection.promise(outname)
  2755. # Send to worker
  2756. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  2757. else:
  2758. if self.solid_geometry:
  2759. self.app.new_object("cncjob", outname, job_init_single_geometry)
  2760. else:
  2761. self.app.new_object("cncjob", outname, job_init_multi_geometry)
  2762. def generatecncjob(self, outname=None,
  2763. tooldia=None, offset=None,
  2764. z_cut=None, z_move=None,
  2765. feedrate=None, feedrate_z=None, feedrate_rapid=None,
  2766. spindlespeed=None, dwell=None, dwelltime=None,
  2767. multidepth=None, depthperpass=None,
  2768. toolchange=None, toolchangez=None, toolchangexy=None,
  2769. extracut=None, startz=None, endz=None,
  2770. ppname_g=None,
  2771. segx=None,
  2772. segy=None,
  2773. use_thread=True):
  2774. """
  2775. Only used for TCL Command.
  2776. Creates a CNCJob out of this Geometry object. The actual
  2777. work is done by the target FlatCAMCNCjob object's
  2778. `generate_from_geometry_2()` method.
  2779. :param z_cut: Cut depth (negative)
  2780. :param z_move: Hight of the tool when travelling (not cutting)
  2781. :param feedrate: Feed rate while cutting on X - Y plane
  2782. :param feedrate_z: Feed rate while cutting on Z plane
  2783. :param feedrate_rapid: Feed rate while moving with rapids
  2784. :param tooldia: Tool diameter
  2785. :param outname: Name of the new object
  2786. :param spindlespeed: Spindle speed (RPM)
  2787. :param ppname_g Name of the postprocessor
  2788. :return: None
  2789. """
  2790. tooldia = tooldia if tooldia else self.options["cnctooldia"]
  2791. outname = outname if outname is not None else self.options["name"]
  2792. z_cut = z_cut if z_cut is not None else self.options["cutz"]
  2793. z_move = z_move if z_move is not None else self.options["travelz"]
  2794. feedrate = feedrate if feedrate is not None else self.options["feedrate"]
  2795. feedrate_z = feedrate_z if feedrate_z is not None else self.options["feedrate_z"]
  2796. feedrate_rapid = feedrate_rapid if feedrate_rapid is not None else self.options["feedrate_rapid"]
  2797. multidepth = multidepth if multidepth is not None else self.options["multidepth"]
  2798. depthperpass = depthperpass if depthperpass is not None else self.options["depthperpass"]
  2799. segx = segx if segx is not None else float(self.app.defaults['geometry_segx'])
  2800. segy = segy if segy is not None else float(self.app.defaults['geometry_segy'])
  2801. extracut = extracut if extracut is not None else self.options["extracut"]
  2802. startz = startz if startz is not None else self.options["startz"]
  2803. endz = endz if endz is not None else self.options["endz"]
  2804. toolchangez = toolchangez if toolchangez else self.options["toolchangez"]
  2805. toolchangexy = toolchangexy if toolchangexy else self.options["toolchangexy"]
  2806. toolchange = toolchange if toolchange else self.options["toolchange"]
  2807. offset = offset if offset else 0.0
  2808. # int or None.
  2809. spindlespeed = spindlespeed if spindlespeed else self.options['spindlespeed']
  2810. dwell = dwell if dwell else self.options["dwell"]
  2811. dwelltime = dwelltime if dwelltime else self.options["dwelltime"]
  2812. ppname_g = ppname_g if ppname_g else self.options["ppname_g"]
  2813. # Object initialization function for app.new_object()
  2814. # RUNNING ON SEPARATE THREAD!
  2815. def job_init(job_obj, app_obj):
  2816. assert isinstance(job_obj, FlatCAMCNCjob), "Initializer expected a FlatCAMCNCjob, got %s" % type(job_obj)
  2817. # Propagate options
  2818. job_obj.options["tooldia"] = tooldia
  2819. app_obj.progress.emit(20)
  2820. job_obj.coords_decimals = self.app.defaults["cncjob_coords_decimals"]
  2821. job_obj.fr_decimals = self.app.defaults["cncjob_fr_decimals"]
  2822. app_obj.progress.emit(40)
  2823. job_obj.options['type'] = 'Geometry'
  2824. job_obj.options['tool_dia'] = tooldia
  2825. job_obj.segx = segx
  2826. job_obj.segy = segy
  2827. # TODO: The tolerance should not be hard coded. Just for testing.
  2828. job_obj.generate_from_geometry_2(self, tooldia=tooldia, offset=offset, tolerance=0.0005,
  2829. z_cut=z_cut, z_move=z_move,
  2830. feedrate=feedrate, feedrate_z=feedrate_z, feedrate_rapid=feedrate_rapid,
  2831. spindlespeed=spindlespeed, dwell=dwell, dwelltime=dwelltime,
  2832. multidepth=multidepth, depthpercut=depthperpass,
  2833. toolchange=toolchange, toolchangez=toolchangez, toolchangexy=toolchangexy,
  2834. extracut=extracut, startz=startz, endz=endz,
  2835. pp_geometry_name=ppname_g
  2836. )
  2837. app_obj.progress.emit(50)
  2838. # tell gcode_parse from which point to start drawing the lines depending on what kind of object is the
  2839. # source of gcode
  2840. job_obj.toolchange_xy = "geometry"
  2841. job_obj.gcode_parse()
  2842. app_obj.progress.emit(80)
  2843. if use_thread:
  2844. # To be run in separate thread
  2845. def job_thread(app_obj):
  2846. with self.app.proc_container.new("Generating CNC Code"):
  2847. app_obj.new_object("cncjob", outname, job_init)
  2848. app_obj.inform.emit("[success]CNCjob created: %s" % outname)
  2849. app_obj.progress.emit(100)
  2850. # Create a promise with the name
  2851. self.app.collection.promise(outname)
  2852. # Send to worker
  2853. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  2854. else:
  2855. self.app.new_object("cncjob", outname, job_init)
  2856. # def on_plot_cb_click(self, *args): # TODO: args not needed
  2857. # if self.muted_ui:
  2858. # return
  2859. # self.read_form_item('plot')
  2860. def scale(self, xfactor, yfactor=None, point=None):
  2861. """
  2862. Scales all geometry by a given factor.
  2863. :param xfactor: Factor by which to scale the object's geometry/
  2864. :type xfactor: float
  2865. :param yfactor: Factor by which to scale the object's geometry/
  2866. :type yfactor: float
  2867. :return: None
  2868. :rtype: None
  2869. """
  2870. if yfactor is None:
  2871. yfactor = xfactor
  2872. if point is None:
  2873. px = 0
  2874. py = 0
  2875. else:
  2876. px, py = point
  2877. if type(self.solid_geometry) == list:
  2878. geo_list = self.flatten(self.solid_geometry)
  2879. self.solid_geometry = []
  2880. # for g in geo_list:
  2881. # self.solid_geometry.append(affinity.scale(g, xfactor, yfactor, origin=(px, py)))
  2882. self.solid_geometry = [affinity.scale(g, xfactor, yfactor, origin=(px, py))
  2883. for g in geo_list]
  2884. else:
  2885. self.solid_geometry = affinity.scale(self.solid_geometry, xfactor, yfactor,
  2886. origin=(px, py))
  2887. def offset(self, vect):
  2888. """
  2889. Offsets all geometry by a given vector/
  2890. :param vect: (x, y) vector by which to offset the object's geometry.
  2891. :type vect: tuple
  2892. :return: None
  2893. :rtype: None
  2894. """
  2895. dx, dy = vect
  2896. def translate_recursion(geom):
  2897. if type(geom) == list:
  2898. geoms=list()
  2899. for local_geom in geom:
  2900. geoms.append(translate_recursion(local_geom))
  2901. return geoms
  2902. else:
  2903. return affinity.translate(geom, xoff=dx, yoff=dy)
  2904. if self.multigeo is True:
  2905. for tool in self.tools:
  2906. self.tools[tool]['solid_geometry'] = translate_recursion(self.tools[tool]['solid_geometry'])
  2907. else:
  2908. self.solid_geometry=translate_recursion(self.solid_geometry)
  2909. def convert_units(self, units):
  2910. self.ui_disconnect()
  2911. factor = Geometry.convert_units(self, units)
  2912. self.options['cutz'] *= factor
  2913. self.options['depthperpass'] *= factor
  2914. self.options['travelz'] *= factor
  2915. self.options['feedrate'] *= factor
  2916. self.options['feedrate_z'] *= factor
  2917. self.options['feedrate_rapid'] *= factor
  2918. self.options['endz'] *= factor
  2919. # self.options['cnctooldia'] *= factor
  2920. self.options['painttooldia'] *= factor
  2921. self.options['paintmargin'] *= factor
  2922. self.options['paintoverlap'] *= factor
  2923. self.options["toolchangez"] *= factor
  2924. coords_xy = [float(eval(coord)) for coord in self.app.defaults["geometry_toolchangexy"].split(",")]
  2925. coords_xy[0] *= factor
  2926. coords_xy[1] *= factor
  2927. self.options['toolchangexy'] = "%f, %f" % (coords_xy[0], coords_xy[1])
  2928. if self.options['startz'] is not None:
  2929. self.options['startz'] *= factor
  2930. param_list = ['cutz', 'depthperpass', 'travelz', 'feedrate', 'feedrate_z', 'feedrate_rapid',
  2931. 'endz', 'toolchangez']
  2932. temp_tools_dict = {}
  2933. tool_dia_copy = {}
  2934. data_copy = {}
  2935. for tooluid_key, tooluid_value in self.tools.items():
  2936. for dia_key, dia_value in tooluid_value.items():
  2937. if dia_key == 'tooldia':
  2938. dia_value *= factor
  2939. dia_value = float('%.4f' % dia_value)
  2940. tool_dia_copy[dia_key] = dia_value
  2941. if dia_key == 'offset':
  2942. tool_dia_copy[dia_key] = dia_value
  2943. if dia_key == 'offset_value':
  2944. dia_value *= factor
  2945. tool_dia_copy[dia_key] = dia_value
  2946. # convert the value in the Custom Tool Offset entry in UI
  2947. custom_offset = self.ui.tool_offset_entry.get_value()
  2948. if custom_offset:
  2949. custom_offset *= factor
  2950. self.ui.tool_offset_entry.set_value(custom_offset)
  2951. if dia_key == 'type':
  2952. tool_dia_copy[dia_key] = dia_value
  2953. if dia_key == 'tool_type':
  2954. tool_dia_copy[dia_key] = dia_value
  2955. if dia_key == 'data':
  2956. for data_key, data_value in dia_value.items():
  2957. # convert the form fields that are convertible
  2958. for param in param_list:
  2959. if data_key == param and data_value is not None:
  2960. data_copy[data_key] = data_value * factor
  2961. # copy the other dict entries that are not convertible
  2962. if data_key not in param_list:
  2963. data_copy[data_key] = data_value
  2964. tool_dia_copy[dia_key] = dict(data_copy)
  2965. data_copy.clear()
  2966. temp_tools_dict.update({
  2967. tooluid_key: dict(tool_dia_copy)
  2968. })
  2969. tool_dia_copy.clear()
  2970. self.tools.clear()
  2971. self.tools = dict(temp_tools_dict)
  2972. # if there is a value in the new tool field then convert that one too
  2973. tooldia = self.ui.addtool_entry.get_value()
  2974. if tooldia:
  2975. tooldia *= factor
  2976. # limit the decimals to 2 for METRIC and 3 for INCH
  2977. if units.lower() == 'in':
  2978. tooldia = float('%.4f' % tooldia)
  2979. else:
  2980. tooldia = float('%.2f' % tooldia)
  2981. self.ui.addtool_entry.set_value(tooldia)
  2982. return factor
  2983. def plot_element(self, element, color='red', visible=None):
  2984. visible = visible if visible else self.options['plot']
  2985. try:
  2986. for sub_el in element:
  2987. self.plot_element(sub_el)
  2988. except TypeError: # Element is not iterable...
  2989. self.add_shape(shape=element, color=color, visible=visible, layer=0)
  2990. def plot(self, visible=None):
  2991. """
  2992. Adds the object into collection.
  2993. :return: None
  2994. """
  2995. # Does all the required setup and returns False
  2996. # if the 'ptint' option is set to False.
  2997. if not FlatCAMObj.plot(self):
  2998. return
  2999. try:
  3000. # plot solid geometries found as members of self.tools attribute dict
  3001. # for MultiGeo
  3002. if self.multigeo == True: # geo multi tool usage
  3003. for tooluid_key in self.tools:
  3004. solid_geometry = self.tools[tooluid_key]['solid_geometry']
  3005. self.plot_element(solid_geometry, visible=visible)
  3006. # plot solid geometry that may be an direct attribute of the geometry object
  3007. # for SingleGeo
  3008. if self.solid_geometry:
  3009. self.plot_element(self.solid_geometry, visible=visible)
  3010. # self.plot_element(self.solid_geometry, visible=self.options['plot'])
  3011. self.shapes.redraw()
  3012. except (ObjectDeleted, AttributeError):
  3013. self.shapes.clear(update=True)
  3014. def on_plot_cb_click(self, *args):
  3015. if self.muted_ui:
  3016. return
  3017. self.plot()
  3018. self.read_form_item('plot')
  3019. self.ui_disconnect()
  3020. cb_flag = self.ui.plot_cb.isChecked()
  3021. for row in range(self.ui.geo_tools_table.rowCount()):
  3022. table_cb = self.ui.geo_tools_table.cellWidget(row, 6)
  3023. if cb_flag:
  3024. table_cb.setChecked(True)
  3025. else:
  3026. table_cb.setChecked(False)
  3027. self.ui_connect()
  3028. def on_plot_cb_click_table(self):
  3029. # self.ui.cnc_tools_table.cellWidget(row, 2).widget().setCheckState(QtCore.Qt.Unchecked)
  3030. self.ui_disconnect()
  3031. cw = self.sender()
  3032. cw_index = self.ui.geo_tools_table.indexAt(cw.pos())
  3033. cw_row = cw_index.row()
  3034. check_row = 0
  3035. self.shapes.clear(update=True)
  3036. for tooluid_key in self.tools:
  3037. solid_geometry = self.tools[tooluid_key]['solid_geometry']
  3038. # find the geo_tool_table row associated with the tooluid_key
  3039. for row in range(self.ui.geo_tools_table.rowCount()):
  3040. tooluid_item = int(self.ui.geo_tools_table.item(row, 5).text())
  3041. if tooluid_item == int(tooluid_key):
  3042. check_row = row
  3043. break
  3044. if self.ui.geo_tools_table.cellWidget(check_row, 6).isChecked():
  3045. self.plot_element(element=solid_geometry, visible=True)
  3046. self.shapes.redraw()
  3047. # make sure that the general plot is disabled if one of the row plot's are disabled and
  3048. # if all the row plot's are enabled also enable the general plot checkbox
  3049. cb_cnt = 0
  3050. total_row = self.ui.geo_tools_table.rowCount()
  3051. for row in range(total_row):
  3052. if self.ui.geo_tools_table.cellWidget(row, 6).isChecked():
  3053. cb_cnt += 1
  3054. else:
  3055. cb_cnt -= 1
  3056. if cb_cnt < total_row:
  3057. self.ui.plot_cb.setChecked(False)
  3058. else:
  3059. self.ui.plot_cb.setChecked(True)
  3060. self.ui_connect()
  3061. class FlatCAMCNCjob(FlatCAMObj, CNCjob):
  3062. """
  3063. Represents G-Code.
  3064. """
  3065. optionChanged = QtCore.pyqtSignal(str)
  3066. ui_type = CNCObjectUI
  3067. def __init__(self, name, units="in", kind="generic", z_move=0.1,
  3068. feedrate=3.0, feedrate_rapid=3.0, z_cut=-0.002, tooldia=0.0,
  3069. spindlespeed=None):
  3070. FlatCAMApp.App.log.debug("Creating CNCJob object...")
  3071. CNCjob.__init__(self, units=units, kind=kind, z_move=z_move,
  3072. feedrate=feedrate, feedrate_rapid=feedrate_rapid, z_cut=z_cut, tooldia=tooldia,
  3073. spindlespeed=spindlespeed, steps_per_circle=self.app.defaults["cncjob_steps_per_circle"])
  3074. FlatCAMObj.__init__(self, name)
  3075. self.kind = "cncjob"
  3076. self.options.update({
  3077. "plot": True,
  3078. "tooldia": 0.03937, # 0.4mm in inches
  3079. "append": "",
  3080. "prepend": "",
  3081. "dwell": False,
  3082. "dwelltime": 1,
  3083. "type": 'Geometry'
  3084. })
  3085. '''
  3086. This is a dict of dictionaries. Each dict is associated with a tool present in the file. The key is the
  3087. diameter of the tools and the value is another dict that will hold the data under the following form:
  3088. {tooldia: {
  3089. 'tooluid': 1,
  3090. 'offset': 'Path',
  3091. 'type_item': 'Rough',
  3092. 'tool_type': 'C1',
  3093. 'data': {} # a dict to hold the parameters
  3094. 'gcode': "" # a string with the actual GCODE
  3095. 'gcode_parsed': {} # dictionary holding the CNCJob geometry and type of geometry (cut or move)
  3096. 'solid_geometry': []
  3097. },
  3098. ...
  3099. }
  3100. It is populated in the FlatCAMGeometry.mtool_gen_cncjob()
  3101. BEWARE: I rely on the ordered nature of the Python 3.7 dictionary. Things might change ...
  3102. '''
  3103. self.cnc_tools = {}
  3104. # for now it show if the plot will be done for multi-tool CNCJob (True) or for single tool
  3105. # (like the one in the TCL Command), False
  3106. self.multitool = False
  3107. # used for parsing the GCode lines to adjust the offset when the GCode was offseted
  3108. offsetx_re_string = r'(?=.*(X[-\+]?\d*\.\d*))'
  3109. self.g_offsetx_re = re.compile(offsetx_re_string)
  3110. offsety_re_string = r'(?=.*(Y[-\+]?\d*\.\d*))'
  3111. self.g_offsety_re = re.compile(offsety_re_string)
  3112. # Attributes to be included in serialization
  3113. # Always append to it because it carries contents
  3114. # from predecessors.
  3115. self.ser_attrs += ['options', 'kind', 'cnc_tools', 'multitool']
  3116. self.annotation = self.app.plotcanvas.new_text_group()
  3117. def build_ui(self):
  3118. self.ui_disconnect()
  3119. FlatCAMObj.build_ui(self)
  3120. # if the FlatCAM object is Excellon don't build the CNC Tools Table but hide it
  3121. if self.cnc_tools:
  3122. self.ui.cnc_tools_table.show()
  3123. self.ui.plot_options_label.show()
  3124. else:
  3125. self.ui.cnc_tools_table.hide()
  3126. self.ui.plot_options_label.hide()
  3127. offset = 0
  3128. tool_idx = 0
  3129. n = len(self.cnc_tools)
  3130. self.ui.cnc_tools_table.setRowCount(n)
  3131. for dia_key, dia_value in self.cnc_tools.items():
  3132. tool_idx += 1
  3133. row_no = tool_idx - 1
  3134. id = QtWidgets.QTableWidgetItem('%d' % int(tool_idx))
  3135. # id.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  3136. self.ui.cnc_tools_table.setItem(row_no, 0, id) # Tool name/id
  3137. # Make sure that the tool diameter when in MM is with no more than 2 decimals.
  3138. # There are no tool bits in MM with more than 2 decimals diameter.
  3139. # For INCH the decimals should be no more than 4. There are no tools under 10mils.
  3140. if self.units == 'MM':
  3141. dia_item = QtWidgets.QTableWidgetItem('%.2f' % float(dia_value['tooldia']))
  3142. else:
  3143. dia_item = QtWidgets.QTableWidgetItem('%.4f' % float(dia_value['tooldia']))
  3144. offset_txt = list(str(dia_value['offset']))
  3145. offset_txt[0] = offset_txt[0].upper()
  3146. offset_item = QtWidgets.QTableWidgetItem(''.join(offset_txt))
  3147. type_item = QtWidgets.QTableWidgetItem(str(dia_value['type']))
  3148. tool_type_item = QtWidgets.QTableWidgetItem(str(dia_value['tool_type']))
  3149. id.setFlags(QtCore.Qt.ItemIsEnabled)
  3150. dia_item.setFlags(QtCore.Qt.ItemIsEnabled)
  3151. offset_item.setFlags(QtCore.Qt.ItemIsEnabled)
  3152. type_item.setFlags(QtCore.Qt.ItemIsEnabled)
  3153. tool_type_item.setFlags(QtCore.Qt.ItemIsEnabled)
  3154. # hack so the checkbox stay centered in the table cell
  3155. # used this:
  3156. # https://stackoverflow.com/questions/32458111/pyqt-allign-checkbox-and-put-it-in-every-row
  3157. # plot_item = QtWidgets.QWidget()
  3158. # checkbox = FCCheckBox()
  3159. # checkbox.setCheckState(QtCore.Qt.Checked)
  3160. # qhboxlayout = QtWidgets.QHBoxLayout(plot_item)
  3161. # qhboxlayout.addWidget(checkbox)
  3162. # qhboxlayout.setAlignment(QtCore.Qt.AlignCenter)
  3163. # qhboxlayout.setContentsMargins(0, 0, 0, 0)
  3164. plot_item = FCCheckBox()
  3165. plot_item.setLayoutDirection(QtCore.Qt.RightToLeft)
  3166. tool_uid_item = QtWidgets.QTableWidgetItem(str(dia_key))
  3167. if self.ui.plot_cb.isChecked():
  3168. plot_item.setChecked(True)
  3169. self.ui.cnc_tools_table.setItem(row_no, 1, dia_item) # Diameter
  3170. self.ui.cnc_tools_table.setItem(row_no, 2, offset_item) # Offset
  3171. self.ui.cnc_tools_table.setItem(row_no, 3, type_item) # Toolpath Type
  3172. self.ui.cnc_tools_table.setItem(row_no, 4, tool_type_item) # Tool Type
  3173. ### REMEMBER: THIS COLUMN IS HIDDEN IN OBJECTUI.PY ###
  3174. self.ui.cnc_tools_table.setItem(row_no, 5, tool_uid_item) # Tool unique ID)
  3175. self.ui.cnc_tools_table.setCellWidget(row_no, 6, plot_item)
  3176. # make the diameter column editable
  3177. # for row in range(tool_idx):
  3178. # self.ui.cnc_tools_table.item(row, 1).setFlags(QtCore.Qt.ItemIsSelectable |
  3179. # QtCore.Qt.ItemIsEnabled)
  3180. for row in range(tool_idx):
  3181. self.ui.cnc_tools_table.item(row, 0).setFlags(
  3182. self.ui.cnc_tools_table.item(row, 0).flags() ^ QtCore.Qt.ItemIsSelectable)
  3183. self.ui.cnc_tools_table.resizeColumnsToContents()
  3184. self.ui.cnc_tools_table.resizeRowsToContents()
  3185. vertical_header = self.ui.cnc_tools_table.verticalHeader()
  3186. # vertical_header.setSectionResizeMode(QtWidgets.QHeaderView.ResizeToContents)
  3187. vertical_header.hide()
  3188. self.ui.cnc_tools_table.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  3189. horizontal_header = self.ui.cnc_tools_table.horizontalHeader()
  3190. horizontal_header.setMinimumSectionSize(10)
  3191. horizontal_header.setDefaultSectionSize(70)
  3192. horizontal_header.setSectionResizeMode(0, QtWidgets.QHeaderView.Fixed)
  3193. horizontal_header.resizeSection(0, 20)
  3194. horizontal_header.setSectionResizeMode(1, QtWidgets.QHeaderView.Stretch)
  3195. horizontal_header.setSectionResizeMode(3, QtWidgets.QHeaderView.ResizeToContents)
  3196. horizontal_header.setSectionResizeMode(4, QtWidgets.QHeaderView.Fixed)
  3197. horizontal_header.resizeSection(4, 40)
  3198. horizontal_header.setSectionResizeMode(6, QtWidgets.QHeaderView.Fixed)
  3199. horizontal_header.resizeSection(4, 17)
  3200. # horizontal_header.setStretchLastSection(True)
  3201. self.ui.cnc_tools_table.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  3202. self.ui.cnc_tools_table.setColumnWidth(0, 20)
  3203. self.ui.cnc_tools_table.setColumnWidth(4, 40)
  3204. self.ui.cnc_tools_table.setColumnWidth(6, 17)
  3205. # self.ui.geo_tools_table.setSortingEnabled(True)
  3206. self.ui.cnc_tools_table.setMinimumHeight(self.ui.cnc_tools_table.getHeight())
  3207. self.ui.cnc_tools_table.setMaximumHeight(self.ui.cnc_tools_table.getHeight())
  3208. self.ui_connect()
  3209. def set_ui(self, ui):
  3210. FlatCAMObj.set_ui(self, ui)
  3211. FlatCAMApp.App.log.debug("FlatCAMCNCJob.set_ui()")
  3212. assert isinstance(self.ui, CNCObjectUI), \
  3213. "Expected a CNCObjectUI, got %s" % type(self.ui)
  3214. self.form_fields.update({
  3215. "plot": self.ui.plot_cb,
  3216. # "tooldia": self.ui.tooldia_entry,
  3217. "append": self.ui.append_text,
  3218. "prepend": self.ui.prepend_text,
  3219. })
  3220. # Fill form fields only on object create
  3221. self.to_form()
  3222. self.ui.updateplot_button.clicked.connect(self.on_updateplot_button_click)
  3223. self.ui.export_gcode_button.clicked.connect(self.on_exportgcode_button_click)
  3224. self.ui.modify_gcode_button.clicked.connect(self.on_modifygcode_button_click)
  3225. def ui_connect(self):
  3226. for row in range(self.ui.cnc_tools_table.rowCount()):
  3227. self.ui.cnc_tools_table.cellWidget(row, 6).clicked.connect(self.on_plot_cb_click_table)
  3228. self.ui.plot_cb.stateChanged.connect(self.on_plot_cb_click)
  3229. def ui_disconnect(self):
  3230. for row in range(self.ui.cnc_tools_table.rowCount()):
  3231. self.ui.cnc_tools_table.cellWidget(row, 6).clicked.disconnect(self.on_plot_cb_click_table)
  3232. try:
  3233. self.ui.plot_cb.stateChanged.disconnect(self.on_plot_cb_click)
  3234. except:
  3235. pass
  3236. def on_updateplot_button_click(self, *args):
  3237. """
  3238. Callback for the "Updata Plot" button. Reads the form for updates
  3239. and plots the object.
  3240. """
  3241. self.read_form()
  3242. self.plot()
  3243. def on_exportgcode_button_click(self, *args):
  3244. self.app.report_usage("cncjob_on_exportgcode_button")
  3245. self.read_form()
  3246. if 'Roland' in self.pp_excellon_name or 'Roland' in self.pp_geometry_name:
  3247. _filter_ = "RML1 Files (*.rol);;" \
  3248. "All Files (*.*)"
  3249. elif 'hpgl' in self.pp_geometry_name:
  3250. _filter_ = "HPGL Files (*.plt);;" \
  3251. "All Files (*.*)"
  3252. else:
  3253. _filter_ = "G-Code Files (*.nc);;G-Code Files (*.txt);;G-Code Files (*.tap);;G-Code Files (*.cnc);;" \
  3254. "G-Code Files (*.g-code);;All Files (*.*)"
  3255. try:
  3256. filename = str(QtWidgets.QFileDialog.getSaveFileName(
  3257. caption="Export Machine Code ...", directory=self.app.get_last_save_folder(), filter=_filter_)[0])
  3258. except TypeError:
  3259. filename = str(QtWidgets.QFileDialog.getSaveFileName(caption="Export Machine Code ...", filter=_filter_)[0])
  3260. preamble = str(self.ui.prepend_text.get_value())
  3261. postamble = str(self.ui.append_text.get_value())
  3262. self.export_gcode(filename, preamble=preamble, postamble=postamble)
  3263. self.app.file_saved.emit("gcode", filename)
  3264. self.app.inform.emit("[success] Machine Code file saved to: %s" % filename)
  3265. def on_modifygcode_button_click(self, *args):
  3266. # add the tab if it was closed
  3267. self.app.ui.plot_tab_area.addTab(self.app.ui.cncjob_tab, "CNC Code Editor")
  3268. # delete the absolute and relative position and messages in the infobar
  3269. self.app.ui.position_label.setText("")
  3270. self.app.ui.rel_position_label.setText("")
  3271. # Switch plot_area to CNCJob tab
  3272. self.app.ui.plot_tab_area.setCurrentWidget(self.app.ui.cncjob_tab)
  3273. preamble = str(self.ui.prepend_text.get_value())
  3274. postamble = str(self.ui.append_text.get_value())
  3275. self.app.gcode_edited = self.export_gcode(preamble=preamble, postamble=postamble, to_file=True)
  3276. # first clear previous text in text editor (if any)
  3277. self.app.ui.code_editor.clear()
  3278. # then append the text from GCode to the text editor
  3279. for line in self.app.gcode_edited:
  3280. proc_line = str(line).strip('\n')
  3281. self.app.ui.code_editor.append(proc_line)
  3282. self.app.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  3283. self.app.handleTextChanged()
  3284. self.app.ui.show()
  3285. def gcode_header(self):
  3286. log.debug("FlatCAMCNCJob.gcode_header()")
  3287. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  3288. marlin = False
  3289. hpgl = False
  3290. try:
  3291. for key in self.cnc_tools:
  3292. if self.cnc_tools[key]['data']['ppname_g'] == 'marlin':
  3293. marlin = True
  3294. break
  3295. if self.cnc_tools[key]['data']['ppname_g'] == 'hpgl':
  3296. hpgl = True
  3297. break
  3298. except Exception as e:
  3299. log.debug("FlatCAMCNCJob.gcode_header() error: --> %s" % str(e))
  3300. try:
  3301. for key in self.cnc_tools:
  3302. if self.cnc_tools[key]['data']['ppname_e'] == 'marlin':
  3303. marlin = True
  3304. break
  3305. except:
  3306. pass
  3307. if marlin is True:
  3308. gcode = ';Marlin G-CODE GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s\n' % \
  3309. (str(self.app.version), str(self.app.version_date)) + '\n'
  3310. gcode += ';Name: ' + str(self.options['name']) + '\n'
  3311. gcode += ';Type: ' + "G-code from " + str(self.options['type']) + '\n'
  3312. # if str(p['options']['type']) == 'Excellon' or str(p['options']['type']) == 'Excellon Geometry':
  3313. # gcode += '(Tools in use: ' + str(p['options']['Tools_in_use']) + ')\n'
  3314. gcode += ';Units: ' + self.units.upper() + '\n' + "\n"
  3315. gcode += ';Created on ' + time_str + '\n' + '\n'
  3316. elif hpgl is True:
  3317. gcode = 'CO "HPGL CODE GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s' % \
  3318. (str(self.app.version), str(self.app.version_date)) + '";\n'
  3319. gcode += 'CO "Name: ' + str(self.options['name']) + '";\n'
  3320. gcode += 'CO "Type: ' + "HPGL code from " + str(self.options['type']) + '";\n'
  3321. # if str(p['options']['type']) == 'Excellon' or str(p['options']['type']) == 'Excellon Geometry':
  3322. # gcode += '(Tools in use: ' + str(p['options']['Tools_in_use']) + ')\n'
  3323. gcode += 'CO "Units: ' + self.units.upper() + '";\n'
  3324. gcode += 'CO "Created on ' + time_str + '";\n'
  3325. else:
  3326. gcode = '(G-CODE GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s)\n' % \
  3327. (str(self.app.version), str(self.app.version_date)) + '\n'
  3328. gcode += '(Name: ' + str(self.options['name']) + ')\n'
  3329. gcode += '(Type: ' + "G-code from " + str(self.options['type']) + ')\n'
  3330. # if str(p['options']['type']) == 'Excellon' or str(p['options']['type']) == 'Excellon Geometry':
  3331. # gcode += '(Tools in use: ' + str(p['options']['Tools_in_use']) + ')\n'
  3332. gcode += '(Units: ' + self.units.upper() + ')\n' + "\n"
  3333. gcode += '(Created on ' + time_str + ')\n' + '\n'
  3334. return gcode
  3335. def export_gcode(self, filename=None, preamble='', postamble='', to_file=False):
  3336. gcode = ''
  3337. roland = False
  3338. hpgl = False
  3339. # detect if using Roland postprocessor
  3340. try:
  3341. for key in self.cnc_tools:
  3342. if self.cnc_tools[key]['data']['ppname_g'] == 'Roland_MDX_20':
  3343. roland = True
  3344. break
  3345. if self.cnc_tools[key]['data']['ppname_g'] == 'hpgl':
  3346. hpgl = True
  3347. break
  3348. except:
  3349. try:
  3350. for key in self.cnc_tools:
  3351. if self.cnc_tools[key]['data']['ppname_e'] == 'Roland_MDX_20':
  3352. roland = True
  3353. break
  3354. except:
  3355. pass
  3356. # do not add gcode_header when using the Roland postprocessor, add it for every other postprocessor
  3357. if roland is False and hpgl is False:
  3358. gcode = self.gcode_header()
  3359. # detect if using multi-tool and make the Gcode summation correctly for each case
  3360. if self.multitool is True:
  3361. for tooluid_key in self.cnc_tools:
  3362. for key, value in self.cnc_tools[tooluid_key].items():
  3363. if key == 'gcode':
  3364. gcode += value
  3365. break
  3366. else:
  3367. gcode += self.gcode
  3368. if roland is True:
  3369. g = preamble + gcode + postamble
  3370. elif hpgl is True:
  3371. g = self.gcode_header() + preamble + gcode + postamble
  3372. else:
  3373. # fix so the preamble gets inserted in between the comments header and the actual start of GCODE
  3374. g_idx = gcode.rfind('G20')
  3375. # if it did not find 'G20' then search for 'G21'
  3376. if g_idx == -1:
  3377. g_idx = gcode.rfind('G21')
  3378. # if it did not find 'G20' and it did not find 'G21' then there is an error and return
  3379. if g_idx == -1:
  3380. self.app.inform.emit("[error_notcl] G-code does not have a units code: either G20 or G21")
  3381. return
  3382. g = gcode[:g_idx] + preamble + '\n' + gcode[g_idx:] + postamble
  3383. # lines = StringIO(self.gcode)
  3384. lines = StringIO(g)
  3385. ## Write
  3386. if filename is not None:
  3387. try:
  3388. with open(filename, 'w') as f:
  3389. for line in lines:
  3390. f.write(line)
  3391. except FileNotFoundError:
  3392. self.app.inform.emit("[warning_notcl] No such file or directory")
  3393. return
  3394. elif to_file is False:
  3395. # Just for adding it to the recent files list.
  3396. self.app.file_opened.emit("cncjob", filename)
  3397. self.app.inform.emit("[success] Saved to: " + filename)
  3398. else:
  3399. return lines
  3400. def get_gcode(self, preamble='', postamble=''):
  3401. #we need this to be able get_gcode separatelly for shell command export_gcode
  3402. return preamble + '\n' + self.gcode + "\n" + postamble
  3403. def get_svg(self):
  3404. # we need this to be able get_svg separately for shell command export_svg
  3405. pass
  3406. def on_plot_cb_click(self, *args):
  3407. if self.muted_ui:
  3408. return
  3409. self.plot()
  3410. self.read_form_item('plot')
  3411. self.ui_disconnect()
  3412. cb_flag = self.ui.plot_cb.isChecked()
  3413. for row in range(self.ui.cnc_tools_table.rowCount()):
  3414. table_cb = self.ui.cnc_tools_table.cellWidget(row, 6)
  3415. if cb_flag:
  3416. table_cb.setChecked(True)
  3417. else:
  3418. table_cb.setChecked(False)
  3419. self.ui_connect()
  3420. def on_plot_cb_click_table(self):
  3421. # self.ui.cnc_tools_table.cellWidget(row, 2).widget().setCheckState(QtCore.Qt.Unchecked)
  3422. self.ui_disconnect()
  3423. cw = self.sender()
  3424. cw_index = self.ui.cnc_tools_table.indexAt(cw.pos())
  3425. cw_row = cw_index.row()
  3426. self.shapes.clear(update=True)
  3427. for tooluid_key in self.cnc_tools:
  3428. tooldia = float('%.4f' % float(self.cnc_tools[tooluid_key]['tooldia']))
  3429. gcode_parsed = self.cnc_tools[tooluid_key]['gcode_parsed']
  3430. # tool_uid = int(self.ui.cnc_tools_table.item(cw_row, 3).text())
  3431. if self.ui.cnc_tools_table.cellWidget((tooluid_key - 1), 6).isChecked():
  3432. self.plot2(tooldia=tooldia, obj=self, visible=True, gcode_parsed=gcode_parsed)
  3433. self.shapes.redraw()
  3434. # make sure that the general plot is disabled if one of the row plot's are disabled and
  3435. # if all the row plot's are enabled also enable the general plot checkbox
  3436. cb_cnt = 0
  3437. total_row = self.ui.cnc_tools_table.rowCount()
  3438. for row in range(total_row):
  3439. if self.ui.cnc_tools_table.cellWidget(row, 6).isChecked():
  3440. cb_cnt += 1
  3441. else:
  3442. cb_cnt -= 1
  3443. if cb_cnt < total_row:
  3444. self.ui.plot_cb.setChecked(False)
  3445. else:
  3446. self.ui.plot_cb.setChecked(True)
  3447. self.ui_connect()
  3448. def plot(self, visible=None):
  3449. # Does all the required setup and returns False
  3450. # if the 'ptint' option is set to False.
  3451. if not FlatCAMObj.plot(self):
  3452. return
  3453. visible = visible if visible else self.options['plot']
  3454. try:
  3455. if self.multitool is False: # single tool usage
  3456. self.plot2(tooldia=self.options["tooldia"], obj=self, visible=visible)
  3457. else:
  3458. # multiple tools usage
  3459. for tooluid_key in self.cnc_tools:
  3460. tooldia = float('%.4f' % float(self.cnc_tools[tooluid_key]['tooldia']))
  3461. gcode_parsed = self.cnc_tools[tooluid_key]['gcode_parsed']
  3462. self.plot2(tooldia=tooldia, obj=self, visible=visible, gcode_parsed=gcode_parsed)
  3463. self.shapes.redraw()
  3464. except (ObjectDeleted, AttributeError):
  3465. self.shapes.clear(update=True)
  3466. self.annotation.clear(update=True)
  3467. def convert_units(self, units):
  3468. factor = CNCjob.convert_units(self, units)
  3469. FlatCAMApp.App.log.debug("FlatCAMCNCjob.convert_units()")
  3470. self.options["tooldia"] *= factor
  3471. # end of file