FlatCAMApp.py 172 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482
  1. ############################################################
  2. # FlatCAM: 2D Post-processing for Manufacturing #
  3. # http://flatcam.org #
  4. # Author: Juan Pablo Caram (c) #
  5. # Date: 2/5/2014 #
  6. # MIT Licence #
  7. ############################################################
  8. import sys
  9. import traceback
  10. import urllib.request, urllib.parse, urllib.error
  11. import getopt
  12. import random
  13. import logging
  14. import simplejson as json
  15. import re
  16. import webbrowser
  17. import os
  18. import tkinter
  19. from PyQt4 import Qt, QtCore, QtGui
  20. import time # Just used for debugging. Double check before removing.
  21. from xml.dom.minidom import parseString as parse_xml_string
  22. from contextlib import contextmanager
  23. ########################################
  24. ## Imports part of FlatCAM ##
  25. ########################################
  26. import FlatCAMVersion
  27. from FlatCAMWorker import Worker
  28. import ObjectCollection
  29. from FlatCAMObj import FlatCAMCNCjob, FlatCAMExcellon, FlatCAMGerber, FlatCAMGeometry, FlatCAMObj
  30. from PlotCanvas import PlotCanvas
  31. from FlatCAMGUI import FlatCAMGUI, GlobalOptionsUI, FlatCAMActivityView, FlatCAMInfoBar
  32. from FlatCAMCommon import LoudDict
  33. from FlatCAMShell import FCShell
  34. from FlatCAMDraw import FlatCAMDraw
  35. from FlatCAMProcess import *
  36. from MeasurementTool import Measurement
  37. from DblSidedTool import DblSidedTool
  38. import tclCommands
  39. from camlib import *
  40. ########################################
  41. ## App ##
  42. ########################################
  43. class App(QtCore.QObject):
  44. """
  45. The main application class. The constructor starts the GUI.
  46. """
  47. ## Get Cmd Line Options
  48. cmd_line_shellfile = ''
  49. cmd_line_help = "FlatCam.py --shellfile=<cmd_line_shellfile>"
  50. try:
  51. cmd_line_options, args = getopt.getopt(sys.argv[1:], "h:", "shellfile=")
  52. except getopt.GetoptError:
  53. print(cmd_line_help)
  54. sys.exit(2)
  55. for opt, arg in cmd_line_options:
  56. if opt == '-h':
  57. print(cmd_line_help)
  58. sys.exit()
  59. elif opt == '--shellfile':
  60. cmd_line_shellfile = arg
  61. ## Logging ##
  62. log = logging.getLogger('base')
  63. log.setLevel(logging.DEBUG)
  64. # log.setLevel(logging.WARNING)
  65. formatter = logging.Formatter('[%(levelname)s][%(threadName)s] %(message)s')
  66. handler = logging.StreamHandler()
  67. handler.setFormatter(formatter)
  68. log.addHandler(handler)
  69. ## Version
  70. version = 8.5
  71. #version_date_str = "2016/7"
  72. version_date = (0, 0, 0)
  73. version_name = None
  74. ## URL for update checks and statistics
  75. version_url = "http://flatcam.org/version"
  76. ## App URL
  77. app_url = "http://flatcam.org"
  78. ## Manual URL
  79. manual_url = "http://flatcam.org/manual/index.html"
  80. ##################
  81. ## Signals ##
  82. ##################
  83. # Inform the user
  84. # Handled by:
  85. # * App.info() --> Print on the status bar
  86. inform = QtCore.pyqtSignal(str)
  87. # General purpose background task
  88. worker_task = QtCore.pyqtSignal(dict)
  89. # File opened
  90. # Handled by:
  91. # * register_folder()
  92. # * register_recent()
  93. # Note: Setting the parameters to unicode does not seem
  94. # to have an effect. Then are received as Qstring
  95. # anyway.
  96. file_opened = QtCore.pyqtSignal(str, str) # File type and filename
  97. progress = QtCore.pyqtSignal(int) # Percentage of progress
  98. plots_updated = QtCore.pyqtSignal()
  99. # Emitted by new_object() and passes the new object as argument and a plot flag
  100. # on_object_created() adds the object to the collection, plot the object if plot flag is True
  101. # and emits new_object_available.
  102. object_created = QtCore.pyqtSignal(object, bool)
  103. # Emitted when a new object has been added to the collection
  104. # and is ready to be used.
  105. new_object_available = QtCore.pyqtSignal(object)
  106. message = QtCore.pyqtSignal(str, str, str)
  107. # Emmited when shell command is finished(one command only)
  108. shell_command_finished = QtCore.pyqtSignal(object)
  109. # Emitted when an unhandled exception happens
  110. # in the worker task.
  111. thread_exception = QtCore.pyqtSignal(object)
  112. @property
  113. def version_date_str(self):
  114. return "{:4d}/{:02d}".format(
  115. self.version_date[0],
  116. self.version_date[1]
  117. )
  118. def __init__(self, user_defaults=True, post_gui=None):
  119. """
  120. Starts the application.
  121. :return: app
  122. :rtype: App
  123. """
  124. FlatCAMVersion.setup(self)
  125. App.log.info("FlatCAM Starting...")
  126. ###################
  127. ### OS-specific ###
  128. ###################
  129. # Folder for user settings.
  130. if sys.platform == 'win32':
  131. from win32com.shell import shell, shellcon
  132. App.log.debug("Win32!")
  133. self.data_path = shell.SHGetFolderPath(0, shellcon.CSIDL_APPDATA, None, 0) + \
  134. '/FlatCAM'
  135. self.os = 'windows'
  136. else: # Linux/Unix/MacOS
  137. self.data_path = os.path.expanduser('~') + \
  138. '/.FlatCAM'
  139. self.os = 'unix'
  140. ###############################
  141. ### Setup folders and files ###
  142. ###############################
  143. if not os.path.exists(self.data_path):
  144. os.makedirs(self.data_path)
  145. App.log.debug('Created data folder: ' + self.data_path)
  146. try:
  147. f = open(self.data_path + '/defaults.json')
  148. f.close()
  149. except IOError:
  150. App.log.debug('Creating empty defaults.json')
  151. f = open(self.data_path + '/defaults.json', 'w')
  152. json.dump({}, f)
  153. f.close()
  154. try:
  155. f = open(self.data_path + '/recent.json')
  156. f.close()
  157. except IOError:
  158. App.log.debug('Creating empty recent.json')
  159. f = open(self.data_path + '/recent.json', 'w')
  160. json.dump([], f)
  161. f.close()
  162. # Application directory. Chdir to it. Otherwise, trying to load
  163. # GUI icons will fail as thir path is relative.
  164. if hasattr(sys, "frozen"):
  165. # For cx_freeze and sililar.
  166. self.app_home = os.path.dirname(sys.executable)
  167. else:
  168. self.app_home = os.path.dirname(os.path.realpath(__file__))
  169. App.log.debug("Application path is " + self.app_home)
  170. App.log.debug("Started in " + os.getcwd())
  171. os.chdir(self.app_home)
  172. ####################
  173. ## Initialize GUI ##
  174. ####################
  175. QtCore.QObject.__init__(self)
  176. self.ui = FlatCAMGUI(self.version, name=self.version_name)
  177. self.connect(self.ui,
  178. QtCore.SIGNAL("geomUpdate(int, int, int, int)"),
  179. self.save_geometry)
  180. #### Plot Area ####
  181. # self.plotcanvas = PlotCanvas(self.ui.splitter)
  182. self.plotcanvas = PlotCanvas(self.ui.right_layout, self)
  183. self.plotcanvas.mpl_connect('button_press_event', self.on_click_over_plot)
  184. self.plotcanvas.mpl_connect('motion_notify_event', self.on_mouse_move_over_plot)
  185. self.plotcanvas.mpl_connect('key_press_event', self.on_key_over_plot)
  186. self.ui.splitter.setStretchFactor(1, 2)
  187. ##############
  188. #### Data ####
  189. ##############
  190. self.recent = []
  191. self.clipboard = QtGui.QApplication.clipboard()
  192. self.proc_container = FCVisibleProcessContainer(self.ui.activity_view)
  193. self.project_filename = None
  194. self.toggle_units_ignore = False
  195. self.defaults_form = GlobalOptionsUI()
  196. self.defaults_form_fields = {
  197. "units": self.defaults_form.units_radio,
  198. "gerber_plot": self.defaults_form.gerber_group.plot_cb,
  199. "gerber_solid": self.defaults_form.gerber_group.solid_cb,
  200. "gerber_multicolored": self.defaults_form.gerber_group.multicolored_cb,
  201. "gerber_isotooldia": self.defaults_form.gerber_group.iso_tool_dia_entry,
  202. "gerber_isopasses": self.defaults_form.gerber_group.iso_width_entry,
  203. "gerber_isooverlap": self.defaults_form.gerber_group.iso_overlap_entry,
  204. "gerber_combine_passes": self.defaults_form.gerber_group.combine_passes_cb,
  205. "gerber_cutouttooldia": self.defaults_form.gerber_group.cutout_tooldia_entry,
  206. "gerber_cutoutmargin": self.defaults_form.gerber_group.cutout_margin_entry,
  207. "gerber_cutoutgapsize": self.defaults_form.gerber_group.cutout_gap_entry,
  208. "gerber_gaps": self.defaults_form.gerber_group.gaps_radio,
  209. "gerber_noncoppermargin": self.defaults_form.gerber_group.noncopper_margin_entry,
  210. "gerber_noncopperrounded": self.defaults_form.gerber_group.noncopper_rounded_cb,
  211. "gerber_bboxmargin": self.defaults_form.gerber_group.bbmargin_entry,
  212. "gerber_bboxrounded": self.defaults_form.gerber_group.bbrounded_cb,
  213. "excellon_plot": self.defaults_form.excellon_group.plot_cb,
  214. "excellon_solid": self.defaults_form.excellon_group.solid_cb,
  215. "excellon_drillz": self.defaults_form.excellon_group.cutz_entry,
  216. "excellon_travelz": self.defaults_form.excellon_group.travelz_entry,
  217. "excellon_feedrate": self.defaults_form.excellon_group.feedrate_entry,
  218. "excellon_spindlespeed": self.defaults_form.excellon_group.spindlespeed_entry,
  219. "excellon_toolchangez": self.defaults_form.excellon_group.toolchangez_entry,
  220. "excellon_tooldia": self.defaults_form.excellon_group.tooldia_entry,
  221. "geometry_plot": self.defaults_form.geometry_group.plot_cb,
  222. "geometry_cutz": self.defaults_form.geometry_group.cutz_entry,
  223. "geometry_travelz": self.defaults_form.geometry_group.travelz_entry,
  224. "geometry_feedrate": self.defaults_form.geometry_group.cncfeedrate_entry,
  225. "geometry_cnctooldia": self.defaults_form.geometry_group.cnctooldia_entry,
  226. "geometry_painttooldia": self.defaults_form.geometry_group.painttooldia_entry,
  227. "geometry_spindlespeed": self.defaults_form.geometry_group.cncspindlespeed_entry,
  228. "geometry_paintoverlap": self.defaults_form.geometry_group.paintoverlap_entry,
  229. "geometry_paintmargin": self.defaults_form.geometry_group.paintmargin_entry,
  230. "geometry_selectmethod": self.defaults_form.geometry_group.selectmethod_combo,
  231. "geometry_pathconnect": self.defaults_form.geometry_group.pathconnect_cb,
  232. "geometry_paintcontour": self.defaults_form.geometry_group.contour_cb,
  233. "cncjob_plot": self.defaults_form.cncjob_group.plot_cb,
  234. "cncjob_tooldia": self.defaults_form.cncjob_group.tooldia_entry,
  235. "cncjob_prepend": self.defaults_form.cncjob_group.prepend_text,
  236. "cncjob_append": self.defaults_form.cncjob_group.append_text,
  237. "cncjob_dwell": self.defaults_form.cncjob_group.dwell_cb,
  238. "cncjob_dwelltime": self.defaults_form.cncjob_group.dwelltime_cb
  239. }
  240. self.defaults = LoudDict()
  241. self.defaults.set_change_callback(self.on_defaults_dict_change) # When the dictionary changes.
  242. self.defaults.update({
  243. "global_mouse_pan_button": 2,
  244. "serial": 0,
  245. "stats": {},
  246. "units": "IN",
  247. "gerber_plot": True,
  248. "gerber_solid": True,
  249. "gerber_multicolored": False,
  250. "gerber_isotooldia": 0.016,
  251. "gerber_isopasses": 1,
  252. "gerber_isooverlap": 0.15,
  253. "gerber_cutouttooldia": 0.07,
  254. "gerber_cutoutmargin": 0.1,
  255. "gerber_cutoutgapsize": 0.15,
  256. "gerber_gaps": "4",
  257. "gerber_noncoppermargin": 0.0,
  258. "gerber_noncopperrounded": False,
  259. "gerber_bboxmargin": 0.0,
  260. "gerber_bboxrounded": False,
  261. "excellon_plot": True,
  262. "excellon_solid": False,
  263. "excellon_drillz": -0.1,
  264. "excellon_travelz": 0.1,
  265. "excellon_feedrate": 3.0,
  266. "excellon_spindlespeed": None,
  267. "excellon_toolchangez": 1.0,
  268. "excellon_tooldia": 0.016,
  269. "geometry_plot": True,
  270. "geometry_cutz": -0.002,
  271. "geometry_travelz": 0.1,
  272. "geometry_feedrate": 3.0,
  273. "geometry_cnctooldia": 0.016,
  274. "geometry_spindlespeed": None,
  275. "geometry_painttooldia": 0.07,
  276. "geometry_paintoverlap": 0.15,
  277. "geometry_paintmargin": 0.0,
  278. "geometry_selectmethod": "single",
  279. "geometry_pathconnect": True,
  280. "geometry_paintcontour": True,
  281. "cncjob_plot": True,
  282. "cncjob_tooldia": 0.016,
  283. "cncjob_prepend": "",
  284. "cncjob_append": "",
  285. "cncjob_dwell": True,
  286. "cncjob_dwelltime": 1,
  287. "background_timeout": 300000, # Default value is 5 minutes
  288. "verbose_error_level": 0, # Shell verbosity 0 = default
  289. # (python trace only for unknown errors),
  290. # 1 = show trace(show trace allways),
  291. # 2 = (For the future).
  292. # Persistence
  293. "last_folder": None,
  294. # Default window geometry
  295. "def_win_x": 100,
  296. "def_win_y": 100,
  297. "def_win_w": 1024,
  298. "def_win_h": 650,
  299. # Constants...
  300. "defaults_save_period_ms": 20000, # Time between default saves.
  301. "shell_shape": [500, 300], # Shape of the shell in pixels.
  302. "shell_at_startup": False, # Show the shell at startup.
  303. "recent_limit": 10, # Max. items in recent list.
  304. "fit_key": '1',
  305. "zoom_out_key": '2',
  306. "zoom_in_key": '3',
  307. "zoom_ratio": 1.5,
  308. "point_clipboard_format": "(%.4f, %.4f)",
  309. "zdownrate": None,
  310. "excellon_zeros": "L",
  311. "gerber_use_buffer_for_union": True,
  312. "cncjob_coordinate_format": "X%.4fY%.4f"
  313. })
  314. ###############################
  315. ### Load defaults from file ###
  316. if user_defaults:
  317. self.load_defaults()
  318. chars = 'abcdefghijklmnopqrstuvwxyz0123456789'
  319. if self.defaults['serial'] == 0 or len(str(self.defaults['serial'])) < 10:
  320. self.defaults['serial'] = ''.join([random.choice(chars) for i in range(20)])
  321. self.save_defaults(silent=True)
  322. self.propagate_defaults()
  323. self.restore_main_win_geom()
  324. def auto_save_defaults():
  325. try:
  326. self.save_defaults(silent=True)
  327. finally:
  328. QtCore.QTimer.singleShot(self.defaults["defaults_save_period_ms"], auto_save_defaults)
  329. if user_defaults:
  330. QtCore.QTimer.singleShot(self.defaults["defaults_save_period_ms"], auto_save_defaults)
  331. self.options_form = GlobalOptionsUI()
  332. self.options_form_fields = {
  333. "units": self.options_form.units_radio,
  334. "gerber_plot": self.options_form.gerber_group.plot_cb,
  335. "gerber_solid": self.options_form.gerber_group.solid_cb,
  336. "gerber_multicolored": self.options_form.gerber_group.multicolored_cb,
  337. "gerber_isotooldia": self.options_form.gerber_group.iso_tool_dia_entry,
  338. "gerber_isopasses": self.options_form.gerber_group.iso_width_entry,
  339. "gerber_isooverlap": self.options_form.gerber_group.iso_overlap_entry,
  340. "gerber_combine_passes": self.options_form.gerber_group.combine_passes_cb,
  341. "gerber_cutouttooldia": self.options_form.gerber_group.cutout_tooldia_entry,
  342. "gerber_cutoutmargin": self.options_form.gerber_group.cutout_margin_entry,
  343. "gerber_cutoutgapsize": self.options_form.gerber_group.cutout_gap_entry,
  344. "gerber_gaps": self.options_form.gerber_group.gaps_radio,
  345. "gerber_noncoppermargin": self.options_form.gerber_group.noncopper_margin_entry,
  346. "gerber_noncopperrounded": self.options_form.gerber_group.noncopper_rounded_cb,
  347. "gerber_bboxmargin": self.options_form.gerber_group.bbmargin_entry,
  348. "gerber_bboxrounded": self.options_form.gerber_group.bbrounded_cb,
  349. "excellon_plot": self.options_form.excellon_group.plot_cb,
  350. "excellon_solid": self.options_form.excellon_group.solid_cb,
  351. "excellon_drillz": self.options_form.excellon_group.cutz_entry,
  352. "excellon_travelz": self.options_form.excellon_group.travelz_entry,
  353. "excellon_feedrate": self.options_form.excellon_group.feedrate_entry,
  354. "excellon_spindlespeed": self.options_form.excellon_group.spindlespeed_entry,
  355. "excellon_toolchangez": self.options_form.excellon_group.toolchangez_entry,
  356. "excellon_tooldia": self.options_form.excellon_group.tooldia_entry,
  357. "geometry_plot": self.options_form.geometry_group.plot_cb,
  358. "geometry_cutz": self.options_form.geometry_group.cutz_entry,
  359. "geometry_travelz": self.options_form.geometry_group.travelz_entry,
  360. "geometry_feedrate": self.options_form.geometry_group.cncfeedrate_entry,
  361. "geometry_spindlespeed": self.options_form.geometry_group.cncspindlespeed_entry,
  362. "geometry_cnctooldia": self.options_form.geometry_group.cnctooldia_entry,
  363. "geometry_painttooldia": self.options_form.geometry_group.painttooldia_entry,
  364. "geometry_paintoverlap": self.options_form.geometry_group.paintoverlap_entry,
  365. "geometry_paintmargin": self.options_form.geometry_group.paintmargin_entry,
  366. "geometry_selectmethod": self.options_form.geometry_group.selectmethod_combo,
  367. "cncjob_plot": self.options_form.cncjob_group.plot_cb,
  368. "cncjob_tooldia": self.options_form.cncjob_group.tooldia_entry,
  369. "cncjob_prepend": self.options_form.cncjob_group.prepend_text,
  370. "cncjob_append": self.options_form.cncjob_group.append_text
  371. }
  372. self.options = LoudDict()
  373. self.options.set_change_callback(self.on_options_dict_change)
  374. self.options.update({
  375. "units": "IN",
  376. "gerber_plot": True,
  377. "gerber_solid": True,
  378. "gerber_multicolored": False,
  379. "gerber_isotooldia": 0.016,
  380. "gerber_isopasses": 1,
  381. "gerber_isooverlap": 0.15,
  382. "gerber_combine_passes": True,
  383. "gerber_cutouttooldia": 0.07,
  384. "gerber_cutoutmargin": 0.1,
  385. "gerber_cutoutgapsize": 0.15,
  386. "gerber_gaps": "4",
  387. "gerber_noncoppermargin": 0.0,
  388. "gerber_noncopperrounded": False,
  389. "gerber_bboxmargin": 0.0,
  390. "gerber_bboxrounded": False,
  391. "excellon_plot": True,
  392. "excellon_solid": False,
  393. "excellon_drillz": -0.1,
  394. "excellon_travelz": 0.1,
  395. "excellon_feedrate": 3.0,
  396. "excellon_spindlespeed": None,
  397. "excellon_toolchangez": 1.0,
  398. "excellon_tooldia": 0.016,
  399. "geometry_plot": True,
  400. "geometry_cutz": -0.002,
  401. "geometry_travelz": 0.1,
  402. "geometry_feedrate": 3.0,
  403. "geometry_spindlespeed": None,
  404. "geometry_cnctooldia": 0.016,
  405. "geometry_painttooldia": 0.07,
  406. "geometry_paintoverlap": 0.15,
  407. "geometry_paintmargin": 0.0,
  408. "geometry_selectmethod": "single",
  409. "cncjob_plot": True,
  410. "cncjob_tooldia": 0.016,
  411. "cncjob_prepend": "",
  412. "cncjob_append": "",
  413. "background_timeout": 300000, # Default value is 5 minutes
  414. "verbose_error_level": 0, # Shell verbosity:
  415. # 0 = default(python trace only for unknown errors),
  416. # 1 = show trace(show trace allways), 2 = (For the future).
  417. })
  418. self.options.update(self.defaults) # Copy app defaults to project options
  419. #self.options_write_form()
  420. self.on_options_combo_change(0) # Will show the initial form
  421. self.collection = ObjectCollection.ObjectCollection()
  422. self.ui.project_tab_layout.addWidget(self.collection.view)
  423. self.mouse_pan_button = int(self.defaults['global_mouse_pan_button'])
  424. #### End of Data ####
  425. #### Worker ####
  426. App.log.info("Starting Worker...")
  427. self.worker = Worker(self)
  428. self.thr1 = QtCore.QThread()
  429. self.worker.moveToThread(self.thr1)
  430. self.connect(self.thr1, QtCore.SIGNAL("started()"), self.worker.run)
  431. self.thr1.start()
  432. #### Check for updates ####
  433. # Separate thread (Not worker)
  434. App.log.info("Checking for updates in backgroud (this is version %s)." % str(self.version))
  435. self.worker2 = Worker(self, name="worker2")
  436. self.thr2 = QtCore.QThread()
  437. self.worker2.moveToThread(self.thr2)
  438. self.connect(self.thr2, QtCore.SIGNAL("started()"), self.worker2.run)
  439. self.connect(self.thr2, QtCore.SIGNAL("started()"),
  440. lambda: self.worker_task.emit({'fcn': self.version_check,
  441. 'params': [],
  442. 'worker_name': "worker2"}))
  443. self.thr2.start()
  444. ### Signal handling ###
  445. ## Custom signals
  446. self.inform.connect(self.info)
  447. self.message.connect(self.message_dialog)
  448. self.progress.connect(self.set_progress_bar)
  449. self.object_created.connect(self.on_object_created)
  450. self.plots_updated.connect(self.on_plots_updated)
  451. self.file_opened.connect(self.register_recent)
  452. self.file_opened.connect(lambda kind, filename: self.register_folder(filename))
  453. ## Standard signals
  454. # Menu
  455. self.ui.menufilenew.triggered.connect(self.on_file_new)
  456. self.ui.menufileopengerber.triggered.connect(self.on_fileopengerber)
  457. self.ui.menufileopenexcellon.triggered.connect(self.on_fileopenexcellon)
  458. self.ui.menufileopengcode.triggered.connect(self.on_fileopengcode)
  459. self.ui.menufileopenproject.triggered.connect(self.on_file_openproject)
  460. self.ui.menufileimportsvg.triggered.connect(self.on_file_importsvg)
  461. self.ui.menufileexportsvg.triggered.connect(self.on_file_exportsvg)
  462. self.ui.menufilesaveproject.triggered.connect(self.on_file_saveproject)
  463. self.ui.menufilesaveprojectas.triggered.connect(self.on_file_saveprojectas)
  464. self.ui.menufilesaveprojectcopy.triggered.connect(lambda: self.on_file_saveprojectas(make_copy=True))
  465. self.ui.menufilesavedefaults.triggered.connect(self.on_file_savedefaults)
  466. self.ui.exit_action.triggered.connect(self.on_file_exit)
  467. self.ui.menueditnew.triggered.connect(lambda: self.new_object('geometry', 'New Geometry', lambda x, y: None))
  468. self.ui.menueditedit.triggered.connect(self.edit_geometry)
  469. self.ui.menueditok.triggered.connect(self.editor2geometry)
  470. self.ui.menueditjoin.triggered.connect(self.on_edit_join)
  471. self.ui.menueditdelete.triggered.connect(self.on_delete)
  472. self.ui.menuoptions_transfer_a2o.triggered.connect(self.on_options_app2object)
  473. self.ui.menuoptions_transfer_a2p.triggered.connect(self.on_options_app2project)
  474. self.ui.menuoptions_transfer_o2a.triggered.connect(self.on_options_object2app)
  475. self.ui.menuoptions_transfer_p2a.triggered.connect(self.on_options_project2app)
  476. self.ui.menuoptions_transfer_o2p.triggered.connect(self.on_options_object2project)
  477. self.ui.menuoptions_transfer_p2o.triggered.connect(self.on_options_project2object)
  478. self.ui.menuoptions_transform_flipx.triggered.connect(self.on_flipx)
  479. self.ui.menuoptions_transform_flipy.triggered.connect(self.on_flipy)
  480. self.ui.menuviewdisableall.triggered.connect(self.disable_plots)
  481. self.ui.menuviewdisableother.triggered.connect(lambda: self.disable_plots(except_current=True))
  482. self.ui.menuviewenable.triggered.connect(self.enable_all_plots)
  483. self.ui.menutoolshell.triggered.connect(self.on_toggle_shell)
  484. self.ui.menuhelp_about.triggered.connect(self.on_about)
  485. self.ui.menuhelp_home.triggered.connect(lambda: webbrowser.open(self.app_url))
  486. self.ui.menuhelp_manual.triggered.connect(lambda: webbrowser.open(self.manual_url))
  487. # Toolbar
  488. self.ui.open_gerber_btn.triggered.connect(self.on_fileopengerber)
  489. self.ui.open_exc_btn.triggered.connect(self.on_fileopenexcellon)
  490. self.ui.open_gcode_btn.triggered.connect(self.on_fileopengcode)
  491. self.ui.save_btn.triggered.connect(self.on_file_saveprojectas)
  492. self.ui.zoom_fit_btn.triggered.connect(self.on_zoom_fit)
  493. self.ui.zoom_in_btn.triggered.connect(lambda: self.plotcanvas.zoom(1.5))
  494. self.ui.zoom_out_btn.triggered.connect(lambda: self.plotcanvas.zoom(1 / 1.5))
  495. self.ui.clear_plot_btn.triggered.connect(self.plotcanvas.clear)
  496. self.ui.replot_btn.triggered.connect(self.on_toolbar_replot)
  497. self.ui.newgeo_btn.triggered.connect(lambda: self.new_object('geometry', 'New Geometry', lambda x, y: None))
  498. self.ui.editgeo_btn.triggered.connect(self.edit_geometry)
  499. self.ui.updategeo_btn.triggered.connect(self.editor2geometry)
  500. self.ui.delete_btn.triggered.connect(self.on_delete)
  501. self.ui.shell_btn.triggered.connect(self.on_toggle_shell)
  502. # Object list
  503. self.collection.view.activated.connect(self.on_row_activated)
  504. # Options
  505. self.ui.options_combo.activated.connect(self.on_options_combo_change)
  506. self.options_form.units_radio.group_toggle_fn = self.on_toggle_units
  507. #Notebook tabs
  508. ####################
  509. ### Other setups ###
  510. ####################
  511. # Sets up FlatCAMObj, FCProcess and FCProcessContainer.
  512. self.setup_obj_classes()
  513. self.setup_recent_items()
  514. self.setup_component_editor()
  515. #########################
  516. ### Tools and Plugins ###
  517. #########################
  518. self.dblsidedtool = DblSidedTool(self)
  519. self.dblsidedtool.install(icon=QtGui.QIcon('share/doubleside16.png'), separator=True)
  520. self.measeurement_tool = Measurement(self)
  521. self.measeurement_tool.install(icon=QtGui.QIcon('share/measure16.png'))
  522. self.ui.measure_btn.triggered.connect(self.measeurement_tool.run)
  523. self.draw = FlatCAMDraw(self, disabled=True)
  524. #############
  525. ### Shell ###
  526. #############
  527. # TODO: Move this to its own class
  528. self.shell = FCShell(self)
  529. self.shell.setWindowIcon(self.ui.app_icon)
  530. self.shell.setWindowTitle("FlatCAM Shell")
  531. self.shell.resize(*self.defaults["shell_shape"])
  532. self.shell.append_output("FlatCAM {}".format(self.version))
  533. if self.version_name:
  534. self.shell.append_output(" - {}".format(self.version_name))
  535. self.shell.append_output("\n(c) 2014-{} Juan Pablo Caram\n\n".format(
  536. self.version_date[0]))
  537. self.shell.append_output("Type help to get started.\n\n")
  538. self.init_tcl()
  539. self.ui.shell_dock = QtGui.QDockWidget("FlatCAM TCL Shell")
  540. self.ui.shell_dock.setWidget(self.shell)
  541. self.ui.shell_dock.setAllowedAreas(QtCore.Qt.AllDockWidgetAreas)
  542. self.ui.shell_dock.setFeatures(QtGui.QDockWidget.DockWidgetMovable |
  543. QtGui.QDockWidget.DockWidgetFloatable | QtGui.QDockWidget.DockWidgetClosable)
  544. self.ui.addDockWidget(QtCore.Qt.BottomDockWidgetArea, self.ui.shell_dock)
  545. if self.defaults["shell_at_startup"]:
  546. self.ui.shell_dock.show()
  547. else:
  548. self.ui.shell_dock.hide()
  549. if self.cmd_line_shellfile:
  550. try:
  551. with open(self.cmd_line_shellfile, "r") as myfile:
  552. cmd_line_shellfile_text = myfile.read()
  553. self.shell._sysShell.exec_command(cmd_line_shellfile_text)
  554. except Exception as ext:
  555. print(("ERROR: ", ext))
  556. sys.exit(2)
  557. # Post-GUI initialization: Experimental attempt
  558. # to perform unit tests on the GUI.
  559. if post_gui is not None:
  560. post_gui(self)
  561. App.log.debug("END of constructor. Releasing control.")
  562. def init_tcl(self):
  563. if hasattr(self, 'tcl'):
  564. # self.tcl = None
  565. # TODO we need to clean non default variables and procedures here
  566. # new object cannot be used here as it will not remember values created for next passes,
  567. # because tcl was execudted in old instance of TCL
  568. pass
  569. else:
  570. self.tcl = tkinter.Tcl()
  571. self.setup_shell()
  572. def defaults_read_form(self):
  573. for option in self.defaults_form_fields:
  574. self.defaults[option] = self.defaults_form_fields[option].get_value()
  575. def defaults_write_form(self):
  576. for option in self.defaults:
  577. self.defaults_write_form_field(option)
  578. # try:
  579. # self.defaults_form_fields[option].set_value(self.defaults[option])
  580. # except KeyError:
  581. # #self.log.debug("defaults_write_form(): No field for: %s" % option)
  582. # # TODO: Rethink this?
  583. # pass
  584. def defaults_write_form_field(self, field):
  585. try:
  586. self.defaults_form_fields[field].set_value(self.defaults[field])
  587. except KeyError:
  588. #self.log.debug("defaults_write_form(): No field for: %s" % option)
  589. # TODO: Rethink this?
  590. pass
  591. def disable_plots(self, except_current=False):
  592. """
  593. Disables all plots with exception of the current object if specified.
  594. :param except_current: Wether to skip the current object.
  595. :rtype except_current: boolean
  596. :return: None
  597. """
  598. # TODO: This method is very similar to replot_all. Try to merge.
  599. self.progress.emit(10)
  600. def worker_task(app_obj):
  601. percentage = 0.1
  602. try:
  603. delta = 0.9 / len(self.collection.get_list())
  604. except ZeroDivisionError:
  605. self.progress.emit(0)
  606. return
  607. for obj in self.collection.get_list():
  608. if obj != self.collection.get_active() or not except_current:
  609. obj.options['plot'] = False
  610. obj.plot()
  611. percentage += delta
  612. self.progress.emit(int(percentage*100))
  613. self.progress.emit(0)
  614. self.plots_updated.emit()
  615. # Send to worker
  616. self.worker_task.emit({'fcn': worker_task, 'params': [self]})
  617. def edit_geometry(self):
  618. """
  619. Send the current geometry object (if any) into the editor.
  620. :return: None
  621. """
  622. if not isinstance(self.collection.get_active(), FlatCAMGeometry):
  623. self.inform.emit("Select a Geometry Object to edit.")
  624. return
  625. self.ui.updategeo_btn.setEnabled(True)
  626. self.draw.edit_fcgeometry(self.collection.get_active())
  627. def editor2geometry(self):
  628. """
  629. Transfers the geometry in the editor to the current geometry object.
  630. :return: None
  631. """
  632. geo = self.collection.get_active()
  633. if not isinstance(geo, FlatCAMGeometry):
  634. self.inform.emit("Select a Geometry Object to update.")
  635. return
  636. self.draw.update_fcgeometry(geo)
  637. self.draw.deactivate()
  638. self.ui.updategeo_btn.setEnabled(False)
  639. geo.plot()
  640. def get_last_folder(self):
  641. return self.defaults["last_folder"]
  642. def report_usage(self, resource):
  643. """
  644. Increments usage counter for the given resource
  645. in self.defaults['stats'].
  646. :param resource: Name of the resource.
  647. :return: None
  648. """
  649. if resource in self.defaults['stats']:
  650. self.defaults['stats'][resource] += 1
  651. else:
  652. self.defaults['stats'][resource] = 1
  653. # TODO: This shouldn't be here.
  654. class TclErrorException(Exception):
  655. """
  656. this exception is deffined here, to be able catch it if we sucessfully handle all errors from shell command
  657. """
  658. pass
  659. def shell_message(self, msg, show=False, error=False):
  660. """
  661. Shows a message on the FlatCAM Shell
  662. :param msg: Message to display.
  663. :param show: Opens the shell.
  664. :param error: Shows the message as an error.
  665. :return: None
  666. """
  667. if show:
  668. self.ui.shell_dock.show()
  669. if error:
  670. self.shell.append_error(msg + "\n")
  671. else:
  672. self.shell.append_output(msg + "\n")
  673. def raise_tcl_unknown_error(self, unknownException):
  674. """
  675. Raise exception if is different type than TclErrorException
  676. this is here mainly to show unknown errors inside TCL shell console.
  677. :param unknownException:
  678. :return:
  679. """
  680. if not isinstance(unknownException, self.TclErrorException):
  681. self.raise_tcl_error("Unknown error: %s" % str(unknownException))
  682. else:
  683. raise unknownException
  684. def display_tcl_error(self, error, error_info=None):
  685. """
  686. escape bracket [ with \ otherwise there is error
  687. "ERROR: missing close-bracket" instead of real error
  688. :param error: it may be text or exception
  689. :return: None
  690. """
  691. if isinstance(error, Exception):
  692. exc_type, exc_value, exc_traceback = error_info
  693. if not isinstance(error, self.TclErrorException):
  694. show_trace = 1
  695. else:
  696. show_trace = int(self.defaults['verbose_error_level'])
  697. if show_trace > 0:
  698. trc = traceback.format_list(traceback.extract_tb(exc_traceback))
  699. trc_formated = []
  700. for a in reversed(trc):
  701. trc_formated.append(a.replace(" ", " > ").replace("\n", ""))
  702. text = "%s\nPython traceback: %s\n%s" % (exc_value,
  703. exc_type,
  704. "\n".join(trc_formated))
  705. else:
  706. text = "%s" % error
  707. else:
  708. text = error
  709. text = text.replace('[', '\\[').replace('"', '\\"')
  710. self.tcl.eval('return -code error "%s"' % text)
  711. def raise_tcl_error(self, text):
  712. """
  713. this method pass exception from python into TCL as error, so we get stacktrace and reason
  714. :param text: text of error
  715. :return: raise exception
  716. """
  717. self.display_tcl_error(text)
  718. raise self.TclErrorException(text)
  719. def exec_command(self, text):
  720. """
  721. Handles input from the shell. See FlatCAMApp.setup_shell for shell commands.
  722. Also handles execution in separated threads
  723. :param text:
  724. :return: output if there was any
  725. """
  726. self.report_usage('exec_command')
  727. result = self.exec_command_test(text, False)
  728. return result
  729. def exec_command_test(self, text, reraise=True):
  730. """
  731. Same as exec_command(...) with additional control over exceptions.
  732. Handles input from the shell. See FlatCAMApp.setup_shell for shell commands.
  733. :param text: Input command
  734. :param reraise: Re-raise TclError exceptions in Python (mostly for unitttests).
  735. :return: Output from the command
  736. """
  737. text = str(text)
  738. try:
  739. self.shell.open_proccessing() # Disables input box.
  740. result = self.tcl.eval(str(text))
  741. if result != 'None':
  742. self.shell.append_output(result + '\n')
  743. except tkinter.TclError as e:
  744. # This will display more precise answer if something in TCL shell fails
  745. result = self.tcl.eval("set errorInfo")
  746. self.log.error("Exec command Exception: %s" % (result + '\n'))
  747. self.shell.append_error('ERROR: ' + result + '\n')
  748. # Show error in console and just return or in test raise exception
  749. if reraise:
  750. raise e
  751. finally:
  752. self.shell.close_proccessing()
  753. pass
  754. return result
  755. """
  756. Code below is unsused. Saved for later.
  757. """
  758. parts = re.findall(r'([\w\\:\.]+|".*?")+', text)
  759. parts = [p.replace('\n', '').replace('"', '') for p in parts]
  760. self.log.debug(parts)
  761. try:
  762. if parts[0] not in commands:
  763. self.shell.append_error("Unknown command\n")
  764. return
  765. #import inspect
  766. #inspect.getargspec(someMethod)
  767. if (type(commands[parts[0]]["params"]) is not list and len(parts)-1 != commands[parts[0]]["params"]) or \
  768. (type(commands[parts[0]]["params"]) is list and len(parts)-1 not in commands[parts[0]]["params"]):
  769. self.shell.append_error(
  770. "Command %s takes %d arguments. %d given.\n" %
  771. (parts[0], commands[parts[0]]["params"], len(parts)-1)
  772. )
  773. return
  774. cmdfcn = commands[parts[0]]["fcn"]
  775. cmdconv = commands[parts[0]]["converters"]
  776. if len(parts) - 1 > 0:
  777. retval = cmdfcn(*[cmdconv[i](parts[i + 1]) for i in range(len(parts)-1)])
  778. else:
  779. retval = cmdfcn()
  780. retfcn = commands[parts[0]]["retfcn"]
  781. if retval and retfcn(retval):
  782. self.shell.append_output(retfcn(retval) + "\n")
  783. except Exception as e:
  784. #self.shell.append_error(''.join(traceback.format_exc()))
  785. #self.shell.append_error("?\n")
  786. self.shell.append_error(str(e) + "\n")
  787. def info(self, msg, toshell=True):
  788. """
  789. Informs the user. Normally on the status bar, optionally
  790. also on the shell.
  791. :param msg: Text to write.
  792. :param toshell: Forward the meesage to the shell.
  793. :return: None
  794. """
  795. # Type of message in brackets at the begining of the message.
  796. match = re.search("\[([^\]]+)\](.*)", msg)
  797. if match:
  798. level = match.group(1)
  799. msg_ = match.group(2)
  800. self.ui.fcinfo.set_status(str(msg_), level=level)
  801. if toshell:
  802. error = level == "error" or level == "warning"
  803. self.shell_message(msg, error=error, show=True)
  804. else:
  805. self.ui.fcinfo.set_status(str(msg), level="info")
  806. if toshell:
  807. self.shell_message(msg)
  808. def load_defaults(self):
  809. """
  810. Loads the aplication's default settings from defaults.json into
  811. ``self.defaults``.
  812. :return: None
  813. """
  814. try:
  815. f = open(self.data_path + "/defaults.json")
  816. options = f.read()
  817. f.close()
  818. except IOError:
  819. self.log.error("Could not load defaults file.")
  820. self.inform.emit("ERROR: Could not load defaults file.")
  821. return
  822. try:
  823. defaults = json.loads(options)
  824. except:
  825. e = sys.exc_info()[0]
  826. App.log.error(str(e))
  827. self.inform.emit("ERROR: Failed to parse defaults file.")
  828. return
  829. self.defaults.update(defaults)
  830. def save_geometry(self, x, y, width, height):
  831. self.defaults["def_win_x"] = x
  832. self.defaults["def_win_y"] = y
  833. self.defaults["def_win_w"] = width
  834. self.defaults["def_win_h"] = height
  835. self.save_defaults()
  836. def message_dialog(self, title, message, kind="info"):
  837. icon = {"info": QtGui.QMessageBox.Information,
  838. "warning": QtGui.QMessageBox.Warning,
  839. "error": QtGui.QMessageBox.Critical}[str(kind)]
  840. dlg = QtGui.QMessageBox(icon, title, message, parent=self.ui)
  841. dlg.setText(message)
  842. dlg.exec_()
  843. def register_recent(self, kind, filename):
  844. self.log.debug("register_recent()")
  845. self.log.debug(" %s" % kind)
  846. self.log.debug(" %s" % filename)
  847. record = {'kind': str(kind), 'filename': str(filename)}
  848. if record in self.recent:
  849. return
  850. self.recent.insert(0, record)
  851. if len(self.recent) > self.defaults['recent_limit']: # Limit reached
  852. self.recent.pop()
  853. try:
  854. f = open(self.data_path + '/recent.json', 'w')
  855. except IOError:
  856. App.log.error("Failed to open recent items file for writing.")
  857. self.inform.emit('Failed to open recent files file for writing.')
  858. return
  859. #try:
  860. json.dump(self.recent, f)
  861. # except:
  862. # App.log.error("Failed to write to recent items file.")
  863. # self.inform.emit('ERROR: Failed to write to recent items file.')
  864. # f.close()
  865. f.close()
  866. # Re-buid the recent items menu
  867. self.setup_recent_items()
  868. def new_object(self, kind, name, initialize, active=True, fit=True, plot=True):
  869. """
  870. Creates a new specalized FlatCAMObj and attaches it to the application,
  871. this is, updates the GUI accordingly, any other records and plots it.
  872. This method is thread-safe.
  873. Notes:
  874. * If the name is in use, the self.collection will modify it
  875. when appending it to the collection. There is no need to handle
  876. name conflicts here.
  877. :param kind: The kind of object to create. One of 'gerber',
  878. 'excellon', 'cncjob' and 'geometry'.
  879. :type kind: str
  880. :param name: Name for the object.
  881. :type name: str
  882. :param initialize: Function to run after creation of the object
  883. but before it is attached to the application. The function is
  884. called with 2 parameters: the new object and the App instance.
  885. :type initialize: function
  886. :param plot: Whether to plot the object or not
  887. :type plot: Bool
  888. :return: None
  889. :rtype: None
  890. """
  891. self.plot = plot
  892. App.log.debug("new_object()")
  893. t0 = time.time() # Debug
  894. ## Create object
  895. classdict = {
  896. "gerber": FlatCAMGerber,
  897. "excellon": FlatCAMExcellon,
  898. "cncjob": FlatCAMCNCjob,
  899. "geometry": FlatCAMGeometry
  900. }
  901. App.log.debug("Calling object constructor...")
  902. obj = classdict[kind](name)
  903. obj.units = self.options["units"] # TODO: The constructor should look at defaults.
  904. # Set default options from self.options
  905. for option in self.options:
  906. if option.find(kind + "_") == 0:
  907. oname = option[len(kind) + 1:]
  908. obj.options[oname] = self.options[option]
  909. # make sure that the plot option of the new object is reflecting the current status and not the general option
  910. # solve issues with the modelview currently used (checkbox on the Project Tab)
  911. obj.options['plot'] = self.plot
  912. # Initialize as per user request
  913. # User must take care to implement initialize
  914. # in a thread-safe way as is is likely that we
  915. # have been invoked in a separate thread.
  916. t1 = time.time()
  917. self.log.debug("%f seconds before initialize()." % (t1 - t0))
  918. initialize(obj, self)
  919. t2 = time.time()
  920. self.log.debug("%f seconds executing initialize()." % (t2 - t1))
  921. # Check units and convert if necessary
  922. # This condition CAN be true because initialize() can change obj.units
  923. if self.options["units"].upper() != obj.units.upper():
  924. self.inform.emit("Converting units to " + self.options["units"] + ".")
  925. obj.convert_units(self.options["units"])
  926. t3 = time.time()
  927. self.log.debug("%f seconds converting units." % (t3 - t2))
  928. self.log.debug("Moving new object back to main thread.")
  929. # Move the object to the main thread and let the app know that it is available.
  930. obj.moveToThread(QtGui.QApplication.instance().thread())
  931. self.object_created.emit(obj, self.plot)
  932. return obj
  933. def options_read_form(self):
  934. for option in self.options_form_fields:
  935. self.options[option] = self.options_form_fields[option].get_value()
  936. def options_write_form(self):
  937. for option in self.options:
  938. self.options_write_form_field(option)
  939. def options_write_form_field(self, field):
  940. try:
  941. self.options_form_fields[field].set_value(self.options[field])
  942. except KeyError:
  943. # Changed from error to debug. This allows to have data stored
  944. # which is not user-editable.
  945. self.log.debug("options_write_form_field(): No field for: %s" % field)
  946. def on_about(self):
  947. """
  948. Displays the "about" dialog.
  949. :return: None
  950. """
  951. self.report_usage("on_about")
  952. version = self.version
  953. version_date_str = self.version_date_str
  954. version_year = self.version_date[0]
  955. class AboutDialog(QtGui.QDialog):
  956. def __init__(self, parent=None):
  957. QtGui.QDialog.__init__(self, parent)
  958. # Icon and title
  959. self.setWindowIcon(parent.app_icon)
  960. self.setWindowTitle("FlatCAM")
  961. layout1 = QtGui.QVBoxLayout()
  962. self.setLayout(layout1)
  963. layout2 = QtGui.QHBoxLayout()
  964. layout1.addLayout(layout2)
  965. logo = QtGui.QLabel()
  966. logo.setPixmap(QtGui.QPixmap('share/flatcam_icon256.png'))
  967. layout2.addWidget(logo, stretch=0)
  968. title = QtGui.QLabel(
  969. "<font size=8><B>FlatCAM</B></font><BR>"
  970. "Version {} ({})<BR>"
  971. "<BR>"
  972. "2D Computer-Aided Printed Circuit Board<BR>"
  973. "Manufacturing.<BR>"
  974. "<BR>"
  975. "(c) 2014-{} Juan Pablo Caram".format(
  976. version,
  977. version_date_str,
  978. version_year
  979. )
  980. )
  981. layout2.addWidget(title, stretch=1)
  982. layout3 = QtGui.QHBoxLayout()
  983. layout1.addLayout(layout3)
  984. layout3.addStretch()
  985. okbtn = QtGui.QPushButton("Close")
  986. layout3.addWidget(okbtn)
  987. okbtn.clicked.connect(self.accept)
  988. AboutDialog(self.ui).exec_()
  989. def on_file_savedefaults(self):
  990. """
  991. Callback for menu item File->Save Defaults. Saves application default options
  992. ``self.defaults`` to defaults.json.
  993. :return: None
  994. """
  995. self.save_defaults()
  996. def on_file_exit(self):
  997. QtGui.qApp.quit()
  998. def save_defaults(self, silent=False):
  999. """
  1000. Saves application default options
  1001. ``self.defaults`` to defaults.json.
  1002. :return: None
  1003. """
  1004. self.report_usage("save_defaults")
  1005. ## Read options from file ##
  1006. try:
  1007. f = open(self.data_path + "/defaults.json")
  1008. options = f.read()
  1009. f.close()
  1010. except:
  1011. e = sys.exc_info()[0]
  1012. App.log.error("Could not load defaults file.")
  1013. App.log.error(str(e))
  1014. self.inform.emit("[error] Could not load defaults file.")
  1015. return
  1016. try:
  1017. defaults = json.loads(options)
  1018. except:
  1019. e = sys.exc_info()[0]
  1020. App.log.error("Failed to parse defaults file.")
  1021. App.log.error(str(e))
  1022. self.inform.emit("[error] Failed to parse defaults file.")
  1023. return
  1024. # Update options
  1025. self.defaults_read_form()
  1026. defaults.update(self.defaults)
  1027. # Save update options
  1028. try:
  1029. f = open(self.data_path + "/defaults.json", "w")
  1030. json.dump(defaults, f)
  1031. f.close()
  1032. except:
  1033. self.inform.emit("[error] Failed to write defaults to file.")
  1034. return
  1035. if not silent:
  1036. self.inform.emit("Defaults saved.")
  1037. def on_toggle_shell(self):
  1038. """
  1039. toggle shell if is visible close it if closed open it
  1040. :return:
  1041. """
  1042. if self.ui.shell_dock.isVisible():
  1043. self.ui.shell_dock.hide()
  1044. else:
  1045. self.ui.shell_dock.show()
  1046. def on_edit_join(self):
  1047. """
  1048. Callback for Edit->Join. Joins the selected geometry objects into
  1049. a new one.
  1050. :return: None
  1051. """
  1052. objs = self.collection.get_selected()
  1053. def initialize(obj, app):
  1054. FlatCAMGeometry.merge(objs, obj)
  1055. self.new_object("geometry", "Combo", initialize)
  1056. def on_options_app2project(self):
  1057. """
  1058. Callback for Options->Transfer Options->App=>Project. Copies options
  1059. from application defaults to project defaults.
  1060. :return: None
  1061. """
  1062. self.report_usage("on_options_app2project")
  1063. self.defaults_read_form()
  1064. self.options.update(self.defaults)
  1065. self.options_write_form()
  1066. def on_options_project2app(self):
  1067. """
  1068. Callback for Options->Transfer Options->Project=>App. Copies options
  1069. from project defaults to application defaults.
  1070. :return: None
  1071. """
  1072. self.report_usage("on_options_project2app")
  1073. self.options_read_form()
  1074. self.defaults.update(self.options)
  1075. self.defaults_write_form()
  1076. def on_options_project2object(self):
  1077. """
  1078. Callback for Options->Transfer Options->Project=>Object. Copies options
  1079. from project defaults to the currently selected object.
  1080. :return: None
  1081. """
  1082. self.report_usage("on_options_project2object")
  1083. self.options_read_form()
  1084. obj = self.collection.get_active()
  1085. if obj is None:
  1086. self.inform.emit("WARNING: No object selected.")
  1087. return
  1088. for option in self.options:
  1089. if option.find(obj.kind + "_") == 0:
  1090. oname = option[len(obj.kind)+1:]
  1091. obj.options[oname] = self.options[option]
  1092. obj.to_form() # Update UI
  1093. def on_options_object2project(self):
  1094. """
  1095. Callback for Options->Transfer Options->Object=>Project. Copies options
  1096. from the currently selected object to project defaults.
  1097. :return: None
  1098. """
  1099. self.report_usage("on_options_object2project")
  1100. obj = self.collection.get_active()
  1101. if obj is None:
  1102. self.inform.emit("WARNING: No object selected.")
  1103. return
  1104. obj.read_form()
  1105. for option in obj.options:
  1106. if option in ['name']: # TODO: Handle this better...
  1107. continue
  1108. self.options[obj.kind + "_" + option] = obj.options[option]
  1109. self.options_write_form()
  1110. def on_options_object2app(self):
  1111. """
  1112. Callback for Options->Transfer Options->Object=>App. Copies options
  1113. from the currently selected object to application defaults.
  1114. :return: None
  1115. """
  1116. self.report_usage("on_options_object2app")
  1117. obj = self.collection.get_active()
  1118. if obj is None:
  1119. self.inform.emit("WARNING: No object selected.")
  1120. return
  1121. obj.read_form()
  1122. for option in obj.options:
  1123. if option in ['name']: # TODO: Handle this better...
  1124. continue
  1125. self.defaults[obj.kind + "_" + option] = obj.options[option]
  1126. self.defaults_write_form()
  1127. def on_options_app2object(self):
  1128. """
  1129. Callback for Options->Transfer Options->App=>Object. Copies options
  1130. from application defaults to the currently selected object.
  1131. :return: None
  1132. """
  1133. self.report_usage("on_options_app2object")
  1134. self.defaults_read_form()
  1135. obj = self.collection.get_active()
  1136. if obj is None:
  1137. self.inform.emit("WARNING: No object selected.")
  1138. return
  1139. for option in self.defaults:
  1140. if option.find(obj.kind + "_") == 0:
  1141. oname = option[len(obj.kind)+1:]
  1142. obj.options[oname] = self.defaults[option]
  1143. obj.to_form() # Update UI
  1144. def on_options_dict_change(self, field):
  1145. self.options_write_form_field(field)
  1146. if field == "units":
  1147. self.set_screen_units(self.options['units'])
  1148. def on_defaults_dict_change(self, field):
  1149. self.defaults_write_form_field(field)
  1150. def set_screen_units(self, units):
  1151. self.ui.units_label.setText("[" + self.options["units"].lower() + "]")
  1152. def on_toggle_units(self):
  1153. """
  1154. Callback for the Units radio-button change in the Options tab.
  1155. Changes the application's default units or the current project's units.
  1156. If changing the project's units, the change propagates to all of
  1157. the objects in the project.
  1158. :return: None
  1159. """
  1160. self.report_usage("on_toggle_units")
  1161. if self.toggle_units_ignore:
  1162. return
  1163. # If option is the same, then ignore
  1164. if self.options_form.units_radio.get_value().upper() == self.options['units'].upper():
  1165. self.log.debug("on_toggle_units(): Same as options, so ignoring.")
  1166. return
  1167. # Options to scale
  1168. dimensions = ['gerber_isotooldia', 'gerber_cutoutmargin', 'gerber_cutoutgapsize',
  1169. 'gerber_noncoppermargin', 'gerber_bboxmargin', 'excellon_drillz',
  1170. 'excellon_travelz', 'excellon_feedrate', 'excellon_toolchangez', 'excellon_tooldia', 'cncjob_tooldia',
  1171. 'geometry_cutz', 'geometry_travelz', 'geometry_feedrate',
  1172. 'geometry_cnctooldia', 'geometry_painttooldia', 'geometry_paintoverlap',
  1173. 'geometry_paintmargin']
  1174. def scale_options(sfactor):
  1175. for dim in dimensions:
  1176. self.options[dim] *= sfactor
  1177. # The scaling factor depending on choice of units.
  1178. factor = 1/25.4
  1179. if self.options_form.units_radio.get_value().upper() == 'MM':
  1180. factor = 25.4
  1181. # Changing project units. Warn user.
  1182. msgbox = QtGui.QMessageBox()
  1183. msgbox.setText("<B>Change project units ...</B>")
  1184. msgbox.setInformativeText("Changing the units of the project causes all geometrical "
  1185. "properties of all objects to be scaled accordingly. Continue?")
  1186. msgbox.setStandardButtons(QtGui.QMessageBox.Cancel | QtGui.QMessageBox.Ok)
  1187. msgbox.setDefaultButton(QtGui.QMessageBox.Ok)
  1188. response = msgbox.exec_()
  1189. if response == QtGui.QMessageBox.Ok:
  1190. self.options_read_form()
  1191. scale_options(factor)
  1192. self.options_write_form()
  1193. for obj in self.collection.get_list():
  1194. units = self.options_form.units_radio.get_value().upper()
  1195. obj.convert_units(units)
  1196. current = self.collection.get_active()
  1197. if current is not None:
  1198. current.to_form()
  1199. self.plot_all()
  1200. else:
  1201. # Undo toggling
  1202. self.toggle_units_ignore = True
  1203. if self.options_form.units_radio.get_value().upper() == 'MM':
  1204. self.options_form.units_radio.set_value('IN')
  1205. else:
  1206. self.options_form.units_radio.set_value('MM')
  1207. self.toggle_units_ignore = False
  1208. self.options_read_form()
  1209. self.inform.emit("Converted units to %s" % self.options["units"])
  1210. #self.ui.units_label.setText("[" + self.options["units"] + "]")
  1211. self.set_screen_units(self.options["units"])
  1212. def on_options_combo_change(self, sel):
  1213. """
  1214. Called when the combo box to choose between application defaults and
  1215. project option changes value. The corresponding variables are
  1216. copied to the UI.
  1217. :param sel: The option index that was chosen.
  1218. :return: None
  1219. """
  1220. # combo_sel = self.ui.notebook.combo_options.get_active()
  1221. App.log.debug("Options --> %s" % sel)
  1222. # Remove anything else in the box
  1223. # box_children = self.options_box.get_children()
  1224. # box_children = self.ui.notebook.options_contents.get_children()
  1225. # for child in box_children:
  1226. # self.ui.notebook.options_contents.remove(child)
  1227. # try:
  1228. # self.ui.options_area.removeWidget(self.defaults_form)
  1229. # except:
  1230. # pass
  1231. #
  1232. # try:
  1233. # self.ui.options_area.removeWidget(self.options_form)
  1234. # except:
  1235. # pass
  1236. form = [self.defaults_form, self.options_form][sel]
  1237. # self.ui.notebook.options_contents.pack_start(form, False, False, 1)
  1238. try:
  1239. self.ui.options_scroll_area.takeWidget()
  1240. except:
  1241. self.log.debug("Nothing to remove")
  1242. self.ui.options_scroll_area.setWidget(form)
  1243. form.show()
  1244. # self.options2form()
  1245. def on_flipx(self):
  1246. obj_list = self.collection.get_selected()
  1247. xminlist = []
  1248. yminlist = []
  1249. xmaxlist = []
  1250. ymaxlist = []
  1251. if not obj_list:
  1252. self.inform.emit("WARNING: No object selected.")
  1253. msg = "Please Select an object to flip!"
  1254. warningbox = QtGui.QMessageBox()
  1255. warningbox.setText(msg)
  1256. warningbox.setWindowTitle("Warning ...")
  1257. warningbox.setWindowIcon(QtGui.QIcon('share/warning.png'))
  1258. warningbox.setStandardButtons(QtGUi.QMessageBox.Ok)
  1259. warningbox.setDefaultButton(QtGui.QMessageBox.Ok)
  1260. warningbox.exec_()
  1261. else:
  1262. # first get a bounding box to fit all
  1263. for obj in obj_list:
  1264. xmin, ymin, xmax, ymax = obj.bounds()
  1265. xminlist.append(xmin)
  1266. yminlist.append(ymin)
  1267. xmaxlist.append(xmax)
  1268. ymaxlist.append(ymax)
  1269. # get the minimum x,y and maximum x,y for all objects selected
  1270. xminimal = min(xminlist)
  1271. yminimal = min(yminlist)
  1272. xmaximal = max(xmaxlist)
  1273. ymaximal = max(ymaxlist)
  1274. px = 0.5 * (xminimal + xmaximal)
  1275. py = 0.5 * (yminimal + ymaximal)
  1276. # execute mirroring
  1277. for obj in obj_list:
  1278. obj.mirror('X', [px, py])
  1279. obj.plot()
  1280. self.info('Flipped on the X axis ...')
  1281. def on_flipy(self):
  1282. obj_list = self.collection.get_selected()
  1283. xminlist = []
  1284. yminlist = []
  1285. xmaxlist = []
  1286. ymaxlist = []
  1287. if not obj_list:
  1288. self.inform.emit("WARNING: No object selected.")
  1289. msg = "Please Select an object to flip!"
  1290. warningbox = QtGui.QMessageBox()
  1291. warningbox.setText(msg)
  1292. warningbox.setWindowTitle("Warning ...")
  1293. warningbox.setWindowIcon(QtGui.QIcon('share/warning.png'))
  1294. warningbox.setStandardButtons(QtGui.QMessageBox.Ok)
  1295. warningbox.setDefaultButton(QtGui.QMessageBox.Ok)
  1296. warningbox.exec_()
  1297. else:
  1298. # first get a bounding box to fit all
  1299. for obj in obj_list:
  1300. xmin, ymin, xmax, ymax = obj.bounds()
  1301. xminlist.append(xmin)
  1302. yminlist.append(ymin)
  1303. xmaxlist.append(xmax)
  1304. ymaxlist.append(ymax)
  1305. # get the minimum x,y and maximum x,y for all objects selected
  1306. xminimal = min(xminlist)
  1307. yminimal = min(yminlist)
  1308. xmaximal = max(xmaxlist)
  1309. ymaximal = max(ymaxlist)
  1310. px = 0.5 * (xminimal + xmaximal)
  1311. py = 0.5 * (yminimal + ymaximal)
  1312. # execute mirroring
  1313. for obj in obj_list:
  1314. obj.mirror('Y', [px, py])
  1315. obj.plot()
  1316. self.info('Flipped on the Y axis ...')
  1317. def on_delete(self):
  1318. """
  1319. Delete the currently selected FlatCAMObjs.
  1320. :return: None
  1321. """
  1322. self.log.debug("on_delete()")
  1323. self.report_usage("on_delete")
  1324. while (self.collection.get_active()):
  1325. self.delete_first_selected()
  1326. def delete_first_selected(self):
  1327. # Keep this for later
  1328. try:
  1329. name = self.collection.get_active().options["name"]
  1330. isPlotted = self.collection.get_active().options["plot"]
  1331. except AttributeError:
  1332. self.log.debug("Nothing selected for deletion")
  1333. return
  1334. # Remove plot only if the object was plotted otherwise delaxes will fail
  1335. if isPlotted:
  1336. self.plotcanvas.figure.delaxes(self.collection.get_active().axes)
  1337. self.plotcanvas.auto_adjust_axes()
  1338. # Clear form
  1339. self.setup_component_editor()
  1340. # Remove from dictionary
  1341. self.collection.delete_active()
  1342. self.inform.emit("Object deleted: %s" % name)
  1343. def on_plots_updated(self):
  1344. """
  1345. Callback used to report when the plots have changed.
  1346. Adjust axes and zooms to fit.
  1347. :return: None
  1348. """
  1349. self.plotcanvas.auto_adjust_axes()
  1350. self.on_zoom_fit(None)
  1351. def on_toolbar_replot(self):
  1352. """
  1353. Callback for toolbar button. Re-plots all objects.
  1354. :return: None
  1355. """
  1356. self.report_usage("on_toolbar_replot")
  1357. self.log.debug("on_toolbar_replot()")
  1358. try:
  1359. self.collection.get_active().read_form()
  1360. except AttributeError:
  1361. self.log.debug("on_toolbar_replot(): AttributeError")
  1362. pass
  1363. self.plot_all()
  1364. def on_row_activated(self, index):
  1365. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  1366. def on_object_created(self, obj, plot):
  1367. """
  1368. Event callback for object creation.
  1369. :param obj: The newly created FlatCAM object.
  1370. :param plot: If to plot the new object, bool
  1371. :return: None
  1372. """
  1373. t0 = time.time() # DEBUG
  1374. self.log.debug("on_object_created()")
  1375. # The Collection might change the name if there is a collision
  1376. self.collection.append(obj)
  1377. self.inform.emit("Object (%s) created: %s" % (obj.kind, obj.options['name']))
  1378. self.new_object_available.emit(obj)
  1379. if plot:
  1380. obj.plot()
  1381. # deselect all previously selected objects and select the new one
  1382. self.collection.set_all_inactive()
  1383. name = obj.options['name']
  1384. self.collection.set_active(name)
  1385. self.on_zoom_fit(None)
  1386. t1 = time.time() # DEBUG
  1387. self.log.debug("%f seconds adding object and plotting." % (t1 - t0))
  1388. def on_zoom_fit(self, event):
  1389. """
  1390. Callback for zoom-out request. This can be either from the corresponding
  1391. toolbar button or the '1' key when the canvas is focused. Calls ``self.adjust_axes()``
  1392. with axes limits from the geometry bounds of all objects.
  1393. :param event: Ignored.
  1394. :return: None
  1395. """
  1396. xmin, ymin, xmax, ymax = self.collection.get_bounds()
  1397. width = xmax - xmin
  1398. height = ymax - ymin
  1399. xmin -= 0.05 * width
  1400. xmax += 0.05 * width
  1401. ymin -= 0.05 * height
  1402. ymax += 0.05 * height
  1403. self.plotcanvas.adjust_axes(xmin, ymin, xmax, ymax)
  1404. def on_key_over_plot(self, event):
  1405. """
  1406. Callback for the key pressed event when the canvas is focused. Keyboard
  1407. shortcuts are handled here. So far, these are the shortcuts:
  1408. ========== ============================================
  1409. Key Action
  1410. ========== ============================================
  1411. '1' Zoom-fit. Fits the axes limits to the data.
  1412. '2' Zoom-out.
  1413. '3' Zoom-in.
  1414. 'm' Toggle on-off the measuring tool.
  1415. ========== ============================================
  1416. :param event: Ignored.
  1417. :return: None
  1418. """
  1419. if event.key == self.defaults['fit_key']: # 1
  1420. self.on_zoom_fit(None)
  1421. return
  1422. if event.key == self.defaults['zoom_out_key']: # 2
  1423. self.plotcanvas.zoom(1 / self.defaults['zoom_ratio'], self.mouse)
  1424. return
  1425. if event.key == self.defaults['zoom_in_key']: # 3
  1426. self.plotcanvas.zoom(self.defaults['zoom_ratio'], self.mouse)
  1427. return
  1428. # if event.key == 'm':
  1429. # if self.measure.toggle_active():
  1430. # self.inform.emit("Measuring tool ON")
  1431. # else:
  1432. # self.inform.emit("Measuring tool OFF")
  1433. # return
  1434. def on_click_over_plot(self, event):
  1435. """
  1436. Callback for the mouse click event over the plot. This event is generated
  1437. by the Matplotlib backend and has been registered in ``self.__init__()``.
  1438. For details, see: http://matplotlib.org/users/event_handling.html
  1439. Default actions are:
  1440. * Copy coordinates to clipboard. Ex.: (65.5473, -13.2679)
  1441. :param event: Contains information about the event, like which button
  1442. was clicked, the pixel coordinates and the axes coordinates.
  1443. :return: None
  1444. """
  1445. # So it can receive key presses
  1446. self.plotcanvas.canvas.setFocus()
  1447. try:
  1448. App.log.debug('button=%d, x=%d, y=%d, xdata=%f, ydata=%f' % (
  1449. event.button, event.x, event.y, event.xdata, event.ydata))
  1450. modifiers = QtGui.QApplication.keyboardModifiers()
  1451. if modifiers == QtCore.Qt.ControlModifier:
  1452. self.clipboard.setText(self.defaults["point_clipboard_format"] % (event.xdata, event.ydata))
  1453. except Exception as e:
  1454. App.log.debug("Outside plot?")
  1455. App.log.debug(str(e))
  1456. def on_mouse_move_over_plot(self, event):
  1457. """
  1458. Callback for the mouse motion event over the plot. This event is generated
  1459. by the Matplotlib backend and has been registered in ``self.__init__()``.
  1460. For details, see: http://matplotlib.org/users/event_handling.html
  1461. :param event: Contains information about the event.
  1462. :return: None
  1463. """
  1464. try: # May fail in case mouse not within axes
  1465. self.ui.position_label.setText("X: %.4f Y: %.4f" % (
  1466. event.xdata, event.ydata))
  1467. self.mouse = [event.xdata, event.ydata]
  1468. except:
  1469. self.ui.position_label.setText("")
  1470. self.mouse = None
  1471. def on_file_new(self):
  1472. """
  1473. Callback for menu item File->New. Returns the application to its
  1474. startup state. This method is thread-safe.
  1475. :return: None
  1476. """
  1477. self.report_usage("on_file_new")
  1478. # Remove everything from memory
  1479. App.log.debug("on_file_new()")
  1480. self.plotcanvas.clear()
  1481. # tcl needs to be reinitialized, otherwise old shell variables etc remains
  1482. self.init_tcl()
  1483. self.collection.delete_all()
  1484. self.setup_component_editor()
  1485. # Clear project filename
  1486. self.project_filename = None
  1487. # Re-fresh project options
  1488. self.on_options_app2project()
  1489. def on_fileopengerber(self):
  1490. """
  1491. File menu callback for opening a Gerber.
  1492. :return: None
  1493. """
  1494. self.report_usage("on_fileopengerber")
  1495. App.log.debug("on_fileopengerber()")
  1496. try:
  1497. filename = QtGui.QFileDialog.getOpenFileName(caption="Open Gerber",
  1498. directory=self.get_last_folder())
  1499. except TypeError:
  1500. filename = QtGui.QFileDialog.getOpenFileName(caption="Open Gerber")
  1501. # The Qt methods above will return a QString which can cause problems later.
  1502. # So far json.dump() will fail to serialize it.
  1503. # TODO: Improve the serialization methods and remove this fix.
  1504. filename = str(filename)
  1505. if filename == "":
  1506. self.inform.emit("Open cancelled.")
  1507. else:
  1508. self.worker_task.emit({'fcn': self.open_gerber,
  1509. 'params': [filename]})
  1510. def on_fileopenexcellon(self):
  1511. """
  1512. File menu callback for opening an Excellon file.
  1513. :return: None
  1514. """
  1515. self.report_usage("on_fileopenexcellon")
  1516. App.log.debug("on_fileopenexcellon()")
  1517. try:
  1518. filename = QtGui.QFileDialog.getOpenFileName(caption="Open Excellon",
  1519. directory=self.get_last_folder())
  1520. except TypeError:
  1521. filename = QtGui.QFileDialog.getOpenFileName(caption="Open Excellon")
  1522. # The Qt methods above will return a QString which can cause problems later.
  1523. # So far json.dump() will fail to serialize it.
  1524. # TODO: Improve the serialization methods and remove this fix.
  1525. filename = str(filename)
  1526. if filename == "":
  1527. self.inform.emit("Open cancelled.")
  1528. else:
  1529. self.worker_task.emit({'fcn': self.open_excellon,
  1530. 'params': [filename]})
  1531. def on_fileopengcode(self):
  1532. """
  1533. File menu call back for opening gcode.
  1534. :return: None
  1535. """
  1536. self.report_usage("on_fileopengcode")
  1537. App.log.debug("on_fileopengcode()")
  1538. try:
  1539. filename = QtGui.QFileDialog.getOpenFileName(caption="Open G-Code",
  1540. directory=self.get_last_folder())
  1541. except TypeError:
  1542. filename = QtGui.QFileDialog.getOpenFileName(caption="Open G-Code")
  1543. # The Qt methods above will return a QString which can cause problems later.
  1544. # So far json.dump() will fail to serialize it.
  1545. # TODO: Improve the serialization methods and remove this fix.
  1546. filename = str(filename)
  1547. if filename == "":
  1548. self.inform.emit("Open cancelled.")
  1549. else:
  1550. self.worker_task.emit({'fcn': self.open_gcode,
  1551. 'params': [filename]})
  1552. def on_file_openproject(self):
  1553. """
  1554. File menu callback for opening a project.
  1555. :return: None
  1556. """
  1557. self.report_usage("on_file_openproject")
  1558. App.log.debug("on_file_openproject()")
  1559. try:
  1560. filename = QtGui.QFileDialog.getOpenFileName(caption="Open Project",
  1561. directory=self.get_last_folder())
  1562. except TypeError:
  1563. filename = QtGui.QFileDialog.getOpenFileName(caption="Open Project")
  1564. # The Qt methods above will return a QString which can cause problems later.
  1565. # So far json.dump() will fail to serialize it.
  1566. # TODO: Improve the serialization methods and remove this fix.
  1567. filename = str(filename)
  1568. if filename == "":
  1569. self.inform.emit("Open cancelled.")
  1570. else:
  1571. # self.worker_task.emit({'fcn': self.open_project,
  1572. # 'params': [filename]})
  1573. # The above was failing because open_project() is not
  1574. # thread safe. The new_project()
  1575. self.open_project(filename)
  1576. def on_file_exportsvg(self):
  1577. """
  1578. Callback for menu item File->Export SVG.
  1579. :return: None
  1580. """
  1581. self.report_usage("on_file_exportsvg")
  1582. App.log.debug("on_file_exportsvg()")
  1583. obj = self.collection.get_active()
  1584. if obj is None:
  1585. self.inform.emit("WARNING: No object selected.")
  1586. msg = "Please Select a Geometry object to export"
  1587. msgbox = QtGui.QMessageBox()
  1588. msgbox.setInformativeText(msg)
  1589. msgbox.setStandardButtons(QtGui.QMessageBox.Ok)
  1590. msgbox.setDefaultButton(QtGui.QMessageBox.Ok)
  1591. msgbox.exec_()
  1592. return
  1593. # Check for more compatible types and add as required
  1594. if (not isinstance(obj, FlatCAMGeometry) and not isinstance(obj, FlatCAMGerber) and not isinstance(obj, FlatCAMCNCjob)
  1595. and not isinstance(obj, FlatCAMExcellon)):
  1596. msg = "ERROR: Only Geometry, Gerber and CNCJob objects can be used."
  1597. msgbox = QtGui.QMessageBox()
  1598. msgbox.setInformativeText(msg)
  1599. msgbox.setStandardButtons(QtGui.QMessageBox.Ok)
  1600. msgbox.setDefaultButton(QtGui.QMessageBox.Ok)
  1601. msgbox.exec_()
  1602. return
  1603. name = self.collection.get_active().options["name"]
  1604. try:
  1605. filename = QtGui.QFileDialog.getSaveFileName(caption="Export SVG",
  1606. directory=self.get_last_folder(), filter="*.svg")
  1607. except TypeError:
  1608. filename = QtGui.QFileDialog.getSaveFileName(caption="Export SVG")
  1609. filename = str(filename)
  1610. if filename == "":
  1611. self.inform.emit("Export SVG cancelled.")
  1612. return
  1613. else:
  1614. self.export_svg(name, filename)
  1615. def on_file_importsvg(self):
  1616. """
  1617. Callback for menu item File->Import SVG.
  1618. :return: None
  1619. """
  1620. self.report_usage("on_file_importsvg")
  1621. App.log.debug("on_file_importsvg()")
  1622. try:
  1623. filename = QtGui.QFileDialog.getOpenFileName(caption="Import SVG",
  1624. directory=self.get_last_folder())
  1625. except TypeError:
  1626. filename = QtGui.QFileDialog.getOpenFileName(caption="Import SVG")
  1627. filename = str(filename)
  1628. if filename == "":
  1629. self.inform.emit("Open cancelled.")
  1630. else:
  1631. self.worker_task.emit({'fcn': self.import_svg,
  1632. 'params': [filename]})
  1633. def on_file_saveproject(self):
  1634. """
  1635. Callback for menu item File->Save Project. Saves the project to
  1636. ``self.project_filename`` or calls ``self.on_file_saveprojectas()``
  1637. if set to None. The project is saved by calling ``self.save_project()``.
  1638. :return: None
  1639. """
  1640. self.report_usage("on_file_saveproject")
  1641. if self.project_filename is None:
  1642. self.on_file_saveprojectas()
  1643. else:
  1644. self.save_project(self.project_filename)
  1645. self.file_opened.emit("project", self.project_filename)
  1646. self.inform.emit("Project saved to: " + self.project_filename)
  1647. def on_file_saveprojectas(self, make_copy=False):
  1648. """
  1649. Callback for menu item File->Save Project As... Opens a file
  1650. chooser and saves the project to the given file via
  1651. ``self.save_project()``.
  1652. :return: None
  1653. """
  1654. self.report_usage("on_file_saveprojectas")
  1655. try:
  1656. filename = QtGui.QFileDialog.getSaveFileName(caption="Save Project As ...",
  1657. directory=self.get_last_folder())
  1658. except TypeError:
  1659. filename = QtGui.QFileDialog.getSaveFileName(caption="Save Project As ...")
  1660. filename = str(filename)
  1661. try:
  1662. f = open(filename, 'r')
  1663. f.close()
  1664. exists = True
  1665. except IOError:
  1666. exists = False
  1667. msg = "File exists. Overwrite?"
  1668. if exists:
  1669. msgbox = QtGui.QMessageBox()
  1670. msgbox.setInformativeText(msg)
  1671. msgbox.setStandardButtons(QtGui.QMessageBox.Cancel | QtGui.QMessageBox.Ok)
  1672. msgbox.setDefaultButton(QtGui.QMessageBox.Cancel)
  1673. result = msgbox.exec_()
  1674. if result == QtGui.QMessageBox.Cancel:
  1675. return
  1676. self.save_project(filename)
  1677. self.file_opened.emit("project", filename)
  1678. if not make_copy:
  1679. self.project_filename = filename
  1680. self.inform.emit("Project saved to: " + self.project_filename)
  1681. else:
  1682. self.inform.emit("Project copy saved to: " + self.project_filename)
  1683. def export_svg(self, obj_name, filename, scale_factor=0.00):
  1684. """
  1685. Exports a Geometry Object to an SVG file.
  1686. :param filename: Path to the SVG file to save to.
  1687. :return:
  1688. """
  1689. self.log.debug("export_svg()")
  1690. try:
  1691. obj = self.collection.get_by_name(str(obj_name))
  1692. except:
  1693. # TODO: The return behavior has not been established... should raise exception?
  1694. return "Could not retrieve object: %s" % obj_name
  1695. with self.proc_container.new("Exporting SVG") as proc:
  1696. exported_svg = obj.export_svg(scale_factor=scale_factor)
  1697. # Determine bounding area for svg export
  1698. bounds = obj.bounds()
  1699. size = obj.size()
  1700. # Convert everything to strings for use in the xml doc
  1701. svgwidth = str(size[0])
  1702. svgheight = str(size[1])
  1703. minx = str(bounds[0])
  1704. miny = str(bounds[1] - size[1])
  1705. uom = obj.units.lower()
  1706. # Add a SVG Header and footer to the svg output from shapely
  1707. # The transform flips the Y Axis so that everything renders
  1708. # properly within svg apps such as inkscape
  1709. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  1710. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  1711. svg_header += 'width="' + svgwidth + uom + '" '
  1712. svg_header += 'height="' + svgheight + uom + '" '
  1713. svg_header += 'viewBox="' + minx + ' ' + miny + ' ' + svgwidth + ' ' + svgheight + '">'
  1714. svg_header += '<g transform="scale(1,-1)">'
  1715. svg_footer = '</g> </svg>'
  1716. svg_elem = svg_header + exported_svg + svg_footer
  1717. # Parse the xml through a xml parser just to add line feeds
  1718. # and to make it look more pretty for the output
  1719. doc = parse_xml_string(svg_elem)
  1720. with open(filename, 'w') as fp:
  1721. fp.write(doc.toprettyxml())
  1722. def import_svg(self, filename, outname=None):
  1723. """
  1724. Adds a new Geometry Object to the projects and populates
  1725. it with shapes extracted from the SVG file.
  1726. :param filename: Path to the SVG file.
  1727. :param outname:
  1728. :return:
  1729. """
  1730. def obj_init(geo_obj, app_obj):
  1731. geo_obj.import_svg(filename)
  1732. with self.proc_container.new("Importing SVG") as proc:
  1733. # Object name
  1734. name = outname or filename.split('/')[-1].split('\\')[-1]
  1735. self.new_object("geometry", name, obj_init)
  1736. # Register recent file
  1737. self.file_opened.emit("svg", filename)
  1738. # GUI feedback
  1739. self.inform.emit("Opened: " + filename)
  1740. def open_gerber(self, filename, follow=False, outname=None):
  1741. """
  1742. Opens a Gerber file, parses it and creates a new object for
  1743. it in the program. Thread-safe.
  1744. :param outname: Name of the resulting object. None causes the
  1745. name to be that of the file.
  1746. :param filename: Gerber file filename
  1747. :type filename: str
  1748. :param follow: If true, the parser will not create polygons, just lines
  1749. following the gerber path.
  1750. :type follow: bool
  1751. :return: None
  1752. """
  1753. # How the object should be initialized
  1754. def obj_init(gerber_obj, app_obj):
  1755. assert isinstance(gerber_obj, FlatCAMGerber), \
  1756. "Expected to initialize a FlatCAMGerber but got %s" % type(gerber_obj)
  1757. # Opening the file happens here
  1758. self.progress.emit(30)
  1759. try:
  1760. gerber_obj.parse_file(filename, follow=follow)
  1761. except IOError:
  1762. app_obj.inform.emit("[error] Failed to open file: " + filename)
  1763. app_obj.progress.emit(0)
  1764. raise IOError('Failed to open file: ' + filename)
  1765. except ParseError as e:
  1766. app_obj.inform.emit("[error] Failed to parse file: " + filename + ". " + e[0])
  1767. app_obj.progress.emit(0)
  1768. self.log.error(str(e))
  1769. raise
  1770. except:
  1771. msg = "[error] An internal error has ocurred. See shell.\n"
  1772. msg += traceback.format_exc()
  1773. app_obj.inform.emit(msg)
  1774. raise
  1775. if gerber_obj.is_empty():
  1776. app_obj.inform.emit("[error] No geometry found in file: " + filename)
  1777. self.collection.set_active(gerber_obj.options["name"])
  1778. self.collection.delete_active()
  1779. # Further parsing
  1780. self.progress.emit(70) # TODO: Note the mixture of self and app_obj used here
  1781. App.log.debug("open_gerber()")
  1782. with self.proc_container.new("Opening Gerber") as proc:
  1783. self.progress.emit(10)
  1784. # Object name
  1785. name = outname or filename.split('/')[-1].split('\\')[-1]
  1786. ### Object creation ###
  1787. self.new_object("gerber", name, obj_init)
  1788. # Register recent file
  1789. self.file_opened.emit("gerber", filename)
  1790. self.progress.emit(100)
  1791. #proc.done()
  1792. # GUI feedback
  1793. self.inform.emit("Opened: " + filename)
  1794. def open_excellon(self, filename, outname=None):
  1795. """
  1796. Opens an Excellon file, parses it and creates a new object for
  1797. it in the program. Thread-safe.
  1798. :param outname: Name of the resulting object. None causes the
  1799. name to be that of the file.
  1800. :param filename: Excellon file filename
  1801. :type filename: str
  1802. :return: None
  1803. """
  1804. App.log.debug("open_excellon()")
  1805. #self.progress.emit(10)
  1806. # How the object should be initialized
  1807. def obj_init(excellon_obj, app_obj):
  1808. #self.progress.emit(20)
  1809. try:
  1810. excellon_obj.parse_file(filename)
  1811. except IOError:
  1812. app_obj.inform.emit("[error] Cannot open file: " + filename)
  1813. self.progress.emit(0) # TODO: self and app_bjj mixed
  1814. raise IOError("Cannot open file: " + filename)
  1815. except:
  1816. msg = "[error] An internal error has ocurred. See shell.\n"
  1817. msg += traceback.format_exc()
  1818. app_obj.inform.emit(msg)
  1819. raise
  1820. try:
  1821. excellon_obj.create_geometry()
  1822. except:
  1823. msg = "[error] An internal error has ocurred. See shell.\n"
  1824. msg += traceback.format_exc()
  1825. app_obj.inform.emit(msg)
  1826. raise
  1827. if excellon_obj.is_empty():
  1828. app_obj.inform.emit("[error] No geometry found in file: " + filename)
  1829. self.collection.set_active(excellon_obj.options["name"])
  1830. self.collection.delete_active()
  1831. #self.progress.emit(70)
  1832. with self.proc_container.new("Opening Excellon."):
  1833. # Object name
  1834. name = outname or filename.split('/')[-1].split('\\')[-1]
  1835. self.new_object("excellon", name, obj_init)
  1836. # Register recent file
  1837. self.file_opened.emit("excellon", filename)
  1838. # GUI feedback
  1839. self.inform.emit("Opened: " + filename)
  1840. #self.progress.emit(100)
  1841. def open_gcode(self, filename, outname=None):
  1842. """
  1843. Opens a G-gcode file, parses it and creates a new object for
  1844. it in the program. Thread-safe.
  1845. :param outname: Name of the resulting object. None causes the
  1846. name to be that of the file.
  1847. :param filename: G-code file filename
  1848. :type filename: str
  1849. :return: None
  1850. """
  1851. App.log.debug("open_gcode()")
  1852. # How the object should be initialized
  1853. def obj_init(job_obj, app_obj_):
  1854. """
  1855. :type app_obj_: App
  1856. """
  1857. assert isinstance(app_obj_, App), \
  1858. "Initializer expected App, got %s" % type(app_obj_)
  1859. self.progress.emit(10)
  1860. try:
  1861. f = open(filename)
  1862. gcode = f.read()
  1863. f.close()
  1864. except IOError:
  1865. app_obj_.inform.emit("[error] Failed to open " + filename)
  1866. self.progress.emit(0)
  1867. raise IOError("Failed to open " + filename)
  1868. job_obj.gcode = gcode
  1869. self.progress.emit(20)
  1870. job_obj.gcode_parse()
  1871. self.progress.emit(60)
  1872. job_obj.create_geometry()
  1873. with self.proc_container.new("Opening G-Code."):
  1874. # Object name
  1875. name = outname or filename.split('/')[-1].split('\\')[-1]
  1876. # New object creation and file processing
  1877. try:
  1878. self.new_object("cncjob", name, obj_init)
  1879. except Exception as e:
  1880. # e = sys.exc_info()
  1881. App.log.error(str(e))
  1882. self.message_dialog("Failed to create CNCJob Object",
  1883. "Attempting to create a FlatCAM CNCJob Object from " +
  1884. "G-Code file failed during processing:\n" +
  1885. str(e[0]) + " " + str(e[1]), kind="error")
  1886. self.progress.emit(0)
  1887. self.collection.delete_active()
  1888. raise e
  1889. # Register recent file
  1890. self.file_opened.emit("cncjob", filename)
  1891. # GUI feedback
  1892. self.inform.emit("Opened: " + filename)
  1893. self.progress.emit(100)
  1894. def open_project(self, filename):
  1895. """
  1896. Loads a project from the specified file.
  1897. 1) Loads and parses file
  1898. 2) Registers the file as recently opened.
  1899. 3) Calls on_file_new()
  1900. 4) Updates options
  1901. 5) Calls new_object() with the object's from_dict() as init method.
  1902. 6) Calls plot_all()
  1903. :param filename: Name of the file from which to load.
  1904. :type filename: str
  1905. :return: None
  1906. """
  1907. App.log.debug("Opening project: " + filename)
  1908. ## Open and parse
  1909. try:
  1910. f = open(filename, 'r')
  1911. except IOError:
  1912. App.log.error("Failed to open project file: %s" % filename)
  1913. self.inform.emit("[error] Failed to open project file: %s" % filename)
  1914. return
  1915. try:
  1916. d = json.load(f, object_hook=dict2obj)
  1917. except:
  1918. App.log.error("Failed to parse project file: %s" % filename)
  1919. self.inform.emit("[error] Failed to parse project file: %s" % filename)
  1920. f.close()
  1921. return
  1922. self.file_opened.emit("project", filename)
  1923. ## Clear the current project
  1924. ## NOT THREAD SAFE ##
  1925. self.on_file_new()
  1926. ##Project options
  1927. self.options.update(d['options'])
  1928. self.project_filename = filename
  1929. #self.ui.units_label.setText("[" + self.options["units"] + "]")
  1930. self.set_screen_units(self.options["units"])
  1931. ## Re create objects
  1932. App.log.debug("Re-creating objects...")
  1933. for obj in d['objs']:
  1934. def obj_init(obj_inst, app_inst):
  1935. obj_inst.from_dict(obj)
  1936. App.log.debug(obj['kind'] + ": " + obj['options']['name'])
  1937. self.new_object(obj['kind'], obj['options']['name'], obj_init, active=False, fit=False, plot=False)
  1938. self.plot_all()
  1939. self.inform.emit("Project loaded from: " + filename)
  1940. App.log.debug("Project loaded")
  1941. def propagate_defaults(self):
  1942. """
  1943. This method is used to set default values in classes. It's
  1944. an alternative to project options but allows the use
  1945. of values invisible to the user.
  1946. :return: None
  1947. """
  1948. self.log.debug("propagate_defaults()")
  1949. # Which objects to update the given parameters.
  1950. routes = {
  1951. "zdownrate": CNCjob,
  1952. "excellon_zeros": Excellon,
  1953. "gerber_use_buffer_for_union": Gerber,
  1954. "cncjob_coordinate_format": CNCjob
  1955. # "spindlespeed": CNCjob
  1956. }
  1957. for param in routes:
  1958. if param in routes[param].defaults:
  1959. try:
  1960. routes[param].defaults[param] = self.defaults[param]
  1961. self.log.debug(" " + param + " OK")
  1962. except KeyError:
  1963. self.log.debug(" ERROR: " + param + " not in defaults.")
  1964. else:
  1965. # Try extracting the name:
  1966. # classname_param here is param in the object
  1967. if param.find(routes[param].__name__.lower() + "_") == 0:
  1968. p = param[len(routes[param].__name__) + 1:]
  1969. if p in routes[param].defaults:
  1970. routes[param].defaults[p] = self.defaults[param]
  1971. self.log.debug(" " + param + " OK!")
  1972. def restore_main_win_geom(self):
  1973. self.ui.setGeometry(self.defaults["def_win_x"],
  1974. self.defaults["def_win_y"],
  1975. self.defaults["def_win_w"],
  1976. self.defaults["def_win_h"])
  1977. def plot_all(self):
  1978. """
  1979. Re-generates all plots from all objects.
  1980. :return: None
  1981. """
  1982. self.log.debug("plot_all()")
  1983. self.plotcanvas.clear()
  1984. self.progress.emit(10)
  1985. def worker_task(app_obj):
  1986. percentage = 0.1
  1987. try:
  1988. delta = 0.9 / len(self.collection.get_list())
  1989. except ZeroDivisionError:
  1990. self.progress.emit(0)
  1991. return
  1992. for obj in self.collection.get_list():
  1993. obj.plot()
  1994. percentage += delta
  1995. self.progress.emit(int(percentage*100))
  1996. self.progress.emit(0)
  1997. self.plots_updated.emit()
  1998. # Send to worker
  1999. #self.worker.add_task(worker_task, [self])
  2000. self.worker_task.emit({'fcn': worker_task, 'params': [self]})
  2001. def register_folder(self, filename):
  2002. self.defaults["last_folder"] = os.path.split(str(filename))[0]
  2003. def set_progress_bar(self, percentage, text=""):
  2004. self.ui.progress_bar.setValue(int(percentage))
  2005. def setup_shell(self):
  2006. """
  2007. Creates shell functions. Runs once at startup.
  2008. :return: None
  2009. """
  2010. self.log.debug("setup_shell()")
  2011. def shelp(p=None):
  2012. if not p:
  2013. return "Available commands:\n" + \
  2014. '\n'.join([' ' + cmd for cmd in sorted(commands)]) + \
  2015. "\n\nType help <command_name> for usage.\n Example: help open_gerber"
  2016. if p not in commands:
  2017. return "Unknown command: %s" % p
  2018. return commands[p]["help"]
  2019. # --- Migrated to new architecture ---
  2020. # def options(name):
  2021. # ops = self.collection.get_by_name(str(name)).options
  2022. # return '\n'.join(["%s: %s" % (o, ops[o]) for o in ops])
  2023. def h(*args):
  2024. """
  2025. Pre-processes arguments to detect '-keyword value' pairs into dictionary
  2026. and standalone parameters into list.
  2027. """
  2028. kwa = {}
  2029. a = []
  2030. n = len(args)
  2031. name = None
  2032. for i in range(n):
  2033. match = re.search(r'^-([a-zA-Z].*)', args[i])
  2034. if match:
  2035. assert name is None
  2036. name = match.group(1)
  2037. continue
  2038. if name is None:
  2039. a.append(args[i])
  2040. else:
  2041. kwa[name] = args[i]
  2042. name = None
  2043. return a, kwa
  2044. @contextmanager
  2045. def wait_signal(signal, timeout=10000):
  2046. """
  2047. Block loop until signal emitted, timeout (ms) elapses
  2048. or unhandled exception happens in a thread.
  2049. :param signal: Signal to wait for.
  2050. """
  2051. loop = QtCore.QEventLoop()
  2052. # Normal termination
  2053. signal.connect(loop.quit)
  2054. # Termination by exception in thread
  2055. self.thread_exception.connect(loop.quit)
  2056. status = {'timed_out': False}
  2057. def report_quit():
  2058. status['timed_out'] = True
  2059. loop.quit()
  2060. yield
  2061. # Temporarily change how exceptions are managed.
  2062. oeh = sys.excepthook
  2063. ex = []
  2064. def except_hook(type_, value, traceback_):
  2065. ex.append(value)
  2066. oeh(type_, value, traceback_)
  2067. sys.excepthook = except_hook
  2068. # Terminate on timeout
  2069. if timeout is not None:
  2070. QtCore.QTimer.singleShot(timeout, report_quit)
  2071. #### Block ####
  2072. loop.exec_()
  2073. # Restore exception management
  2074. sys.excepthook = oeh
  2075. if ex:
  2076. self.raiseTclError(str(ex[0]))
  2077. if status['timed_out']:
  2078. raise Exception('Timed out!')
  2079. # def wait_signal2(signal, timeout=10000):
  2080. # """Block loop until signal emitted, or timeout (ms) elapses."""
  2081. # loop = QtCore.QEventLoop()
  2082. # signal.connect(loop.quit)
  2083. # status = {'timed_out': False}
  2084. #
  2085. # def report_quit():
  2086. # status['timed_out'] = True
  2087. # loop.quit()
  2088. #
  2089. # if timeout is not None:
  2090. # QtCore.QTimer.singleShot(timeout, report_quit)
  2091. # loop.exec_()
  2092. #
  2093. # if status['timed_out']:
  2094. # raise Exception('Timed out!')
  2095. # def mytest(*args):
  2096. # to = int(args[0])
  2097. #
  2098. # try:
  2099. # for rec in self.recent:
  2100. # if rec['kind'] == 'gerber':
  2101. # self.open_gerber(str(rec['filename']))
  2102. # break
  2103. #
  2104. # basename = self.collection.get_names()[0]
  2105. # isolate(basename, '-passes', '10', '-combine', '1')
  2106. # iso = self.collection.get_by_name(basename + "_iso")
  2107. #
  2108. # with wait_signal(self.new_object_available, to):
  2109. # iso.generatecncjob()
  2110. # # iso.generatecncjob()
  2111. # # wait_signal2(self.new_object_available, to)
  2112. #
  2113. # return str(self.collection.get_names())
  2114. #
  2115. # except Exception as e:
  2116. # return str(e)
  2117. #
  2118. # def mytest2(*args):
  2119. # to = int(args[0])
  2120. #
  2121. # for rec in self.recent:
  2122. # if rec['kind'] == 'gerber':
  2123. # self.open_gerber(str(rec['filename']))
  2124. # break
  2125. #
  2126. # basename = self.collection.get_names()[0]
  2127. # isolate(basename, '-passes', '10', '-combine', '1')
  2128. # iso = self.collection.get_by_name(basename + "_iso")
  2129. #
  2130. # with wait_signal(self.new_object_available, to):
  2131. # 1/0 # Force exception
  2132. # iso.generatecncjob()
  2133. #
  2134. # return str(self.collection.get_names())
  2135. #
  2136. # def mytest3(*args):
  2137. # to = int(args[0])
  2138. #
  2139. # def sometask(*args):
  2140. # time.sleep(2)
  2141. # self.inform.emit("mytest3")
  2142. #
  2143. # with wait_signal(self.inform, to):
  2144. # self.worker_task.emit({'fcn': sometask, 'params': []})
  2145. #
  2146. # return "mytest3 done"
  2147. #
  2148. # def mytest4(*args):
  2149. # to = int(args[0])
  2150. #
  2151. # def sometask(*args):
  2152. # time.sleep(2)
  2153. # 1/0 # Force exception
  2154. # self.inform.emit("mytest4")
  2155. #
  2156. # with wait_signal(self.inform, to):
  2157. # self.worker_task.emit({'fcn': sometask, 'params': []})
  2158. #
  2159. # return "mytest3 done"
  2160. # --- Migrated to new architecture ---
  2161. # def export_svg(name, filename, *args):
  2162. # a, kwa = h(*args)
  2163. # types = {'scale_factor': float}
  2164. #
  2165. # for key in kwa:
  2166. # if key not in types:
  2167. # return 'Unknown parameter: %s' % key
  2168. # kwa[key] = types[key](kwa[key])
  2169. #
  2170. # self.export_svg(str(name), str(filename), **kwa)
  2171. # --- Migrated to new architecture ---
  2172. # def import_svg(filename, *args):
  2173. # a, kwa = h(*args)
  2174. # types = {'outname': str}
  2175. #
  2176. # for key in kwa:
  2177. # if key not in types:
  2178. # return 'Unknown parameter: %s' % key
  2179. # kwa[key] = types[key](kwa[key])
  2180. #
  2181. # self.import_svg(str(filename), **kwa)
  2182. # --- Migrated to new architecture
  2183. # def open_gerber(filename, *args):
  2184. # a, kwa = h(*args)
  2185. # types = {'follow': bool,
  2186. # 'outname': str}
  2187. #
  2188. # for key in kwa:
  2189. # if key not in types:
  2190. # return 'Unknown parameter: %s' % key
  2191. # kwa[key] = types[key](kwa[key])
  2192. #
  2193. # self.open_gerber(str(filename), **kwa)
  2194. # --- Migrated to new architecture ---
  2195. # def open_excellon(filename, *args):
  2196. # a, kwa = h(*args)
  2197. # types = {'outname': str}
  2198. #
  2199. # for key in kwa:
  2200. # if key not in types:
  2201. # return 'Unknown parameter: %s' % key
  2202. # kwa[key] = types[key](kwa[key])
  2203. #
  2204. # self.open_excellon(str(filename), **kwa)
  2205. # --- Migrated to new architecture ---
  2206. # def open_gcode(filename, *args):
  2207. # a, kwa = h(*args)
  2208. # types = {'outname': str}
  2209. #
  2210. # for key in kwa:
  2211. # if key not in types:
  2212. # return 'Unknown parameter: %s' % key
  2213. # kwa[key] = types[key](kwa[key])
  2214. #
  2215. # self.open_gcode(str(filename), **kwa)
  2216. # def cutout(name, *args):
  2217. # a, kwa = h(*args)
  2218. # types = {'dia': float,
  2219. # 'margin': float,
  2220. # 'gapsize': float,
  2221. # 'gaps': str}
  2222. #
  2223. # for key in kwa:
  2224. # if key not in types:
  2225. # return 'Unknown parameter: %s' % key
  2226. # kwa[key] = types[key](kwa[key])
  2227. #
  2228. # try:
  2229. # obj = self.collection.get_by_name(str(name))
  2230. # except:
  2231. # return "Could not retrieve object: %s" % name
  2232. #
  2233. # def geo_init_me(geo_obj, app_obj):
  2234. # margin = kwa['margin'] + kwa['dia'] / 2
  2235. # gap_size = kwa['dia'] + kwa['gapsize']
  2236. # minx, miny, maxx, maxy = obj.bounds()
  2237. # minx -= margin
  2238. # maxx += margin
  2239. # miny -= margin
  2240. # maxy += margin
  2241. # midx = 0.5 * (minx + maxx)
  2242. # midy = 0.5 * (miny + maxy)
  2243. # hgap = 0.5 * gap_size
  2244. # pts = [[midx - hgap, maxy],
  2245. # [minx, maxy],
  2246. # [minx, midy + hgap],
  2247. # [minx, midy - hgap],
  2248. # [minx, miny],
  2249. # [midx - hgap, miny],
  2250. # [midx + hgap, miny],
  2251. # [maxx, miny],
  2252. # [maxx, midy - hgap],
  2253. # [maxx, midy + hgap],
  2254. # [maxx, maxy],
  2255. # [midx + hgap, maxy]]
  2256. # cases = {"tb": [[pts[0], pts[1], pts[4], pts[5]],
  2257. # [pts[6], pts[7], pts[10], pts[11]]],
  2258. # "lr": [[pts[9], pts[10], pts[1], pts[2]],
  2259. # [pts[3], pts[4], pts[7], pts[8]]],
  2260. # "4": [[pts[0], pts[1], pts[2]],
  2261. # [pts[3], pts[4], pts[5]],
  2262. # [pts[6], pts[7], pts[8]],
  2263. # [pts[9], pts[10], pts[11]]]}
  2264. # cuts = cases[kwa['gaps']]
  2265. # geo_obj.solid_geometry = cascaded_union([LineString(segment) for segment in cuts])
  2266. #
  2267. # try:
  2268. # obj.app.new_object("geometry", name + "_cutout", geo_init_me)
  2269. # except Exception, e:
  2270. # return "Operation failed: %s" % str(e)
  2271. #
  2272. # return 'Ok'
  2273. # --- Migrated to new architecture ---
  2274. # def geocutout(name=None, *args):
  2275. # """
  2276. # TCL shell command - see help section
  2277. #
  2278. # Subtract gaps from geometry, this will not create new object
  2279. #
  2280. # :param name: name of object
  2281. # :param args: array of arguments
  2282. # :return: "Ok" if completed without errors
  2283. # """
  2284. #
  2285. # try:
  2286. # a, kwa = h(*args)
  2287. # types = {'dia': float,
  2288. # 'gapsize': float,
  2289. # 'gaps': str}
  2290. #
  2291. # # How gaps wil be rendered:
  2292. # # lr - left + right
  2293. # # tb - top + bottom
  2294. # # 4 - left + right +top + bottom
  2295. # # 2lr - 2*left + 2*right
  2296. # # 2tb - 2*top + 2*bottom
  2297. # # 8 - 2*left + 2*right +2*top + 2*bottom
  2298. #
  2299. # if name is None:
  2300. # self.raise_tcl_error('Argument name is missing.')
  2301. #
  2302. # for key in kwa:
  2303. # if key not in types:
  2304. # self.raise_tcl_error('Unknown parameter: %s' % key)
  2305. # try:
  2306. # kwa[key] = types[key](kwa[key])
  2307. # except Exception, e:
  2308. # self.raise_tcl_error("Cannot cast argument '%s' to type %s." % (key, str(types[key])))
  2309. #
  2310. # try:
  2311. # obj = self.collection.get_by_name(str(name))
  2312. # except:
  2313. # self.raise_tcl_error("Could not retrieve object: %s" % name)
  2314. #
  2315. # # Get min and max data for each object as we just cut rectangles across X or Y
  2316. # xmin, ymin, xmax, ymax = obj.bounds()
  2317. # px = 0.5 * (xmin + xmax)
  2318. # py = 0.5 * (ymin + ymax)
  2319. # lenghtx = (xmax - xmin)
  2320. # lenghty = (ymax - ymin)
  2321. # gapsize = kwa['gapsize'] + kwa['dia'] / 2
  2322. #
  2323. # if kwa['gaps'] == '8' or kwa['gaps'] == '2lr':
  2324. #
  2325. # subtract_rectangle(name,
  2326. # xmin - gapsize,
  2327. # py - gapsize + lenghty / 4,
  2328. # xmax + gapsize,
  2329. # py + gapsize + lenghty / 4)
  2330. # subtract_rectangle(name,
  2331. # xmin - gapsize,
  2332. # py - gapsize - lenghty / 4,
  2333. # xmax + gapsize,
  2334. # py + gapsize - lenghty / 4)
  2335. #
  2336. # if kwa['gaps'] == '8' or kwa['gaps'] == '2tb':
  2337. # subtract_rectangle(name,
  2338. # px - gapsize + lenghtx / 4,
  2339. # ymin - gapsize,
  2340. # px + gapsize + lenghtx / 4,
  2341. # ymax + gapsize)
  2342. # subtract_rectangle(name,
  2343. # px - gapsize - lenghtx / 4,
  2344. # ymin - gapsize,
  2345. # px + gapsize - lenghtx / 4,
  2346. # ymax + gapsize)
  2347. #
  2348. # if kwa['gaps'] == '4' or kwa['gaps'] == 'lr':
  2349. # subtract_rectangle(name,
  2350. # xmin - gapsize,
  2351. # py - gapsize,
  2352. # xmax + gapsize,
  2353. # py + gapsize)
  2354. #
  2355. # if kwa['gaps'] == '4' or kwa['gaps'] == 'tb':
  2356. # subtract_rectangle(name,
  2357. # px - gapsize,
  2358. # ymin - gapsize,
  2359. # px + gapsize,
  2360. # ymax + gapsize)
  2361. #
  2362. # except Exception as unknown:
  2363. # self.raise_tcl_unknown_error(unknown)
  2364. # --- Migrated to new architecture ---
  2365. # def mirror(name, *args):
  2366. # a, kwa = h(*args)
  2367. # types = {'box': str,
  2368. # 'axis': str,
  2369. # 'dist': float}
  2370. #
  2371. # for key in kwa:
  2372. # if key not in types:
  2373. # return 'Unknown parameter: %s' % key
  2374. # kwa[key] = types[key](kwa[key])
  2375. #
  2376. # # Get source object.
  2377. # try:
  2378. # obj = self.collection.get_by_name(str(name))
  2379. # except:
  2380. # return "Could not retrieve object: %s" % name
  2381. #
  2382. # if obj is None:
  2383. # return "Object not found: %s" % name
  2384. #
  2385. # if not isinstance(obj, FlatCAMGerber) and \
  2386. # not isinstance(obj, FlatCAMExcellon) and \
  2387. # not isinstance(obj, FlatCAMGeometry):
  2388. # return "ERROR: Only Gerber, Excellon and Geometry objects can be mirrored."
  2389. #
  2390. # # Axis
  2391. # try:
  2392. # axis = kwa['axis'].upper()
  2393. # except KeyError:
  2394. # return "ERROR: Specify -axis X or -axis Y"
  2395. #
  2396. # # Box
  2397. # if 'box' in kwa:
  2398. # try:
  2399. # box = self.collection.get_by_name(kwa['box'])
  2400. # except:
  2401. # return "Could not retrieve object box: %s" % kwa['box']
  2402. #
  2403. # if box is None:
  2404. # return "Object box not found: %s" % kwa['box']
  2405. #
  2406. # try:
  2407. # xmin, ymin, xmax, ymax = box.bounds()
  2408. # px = 0.5 * (xmin + xmax)
  2409. # py = 0.5 * (ymin + ymax)
  2410. #
  2411. # obj.mirror(axis, [px, py])
  2412. # obj.plot()
  2413. #
  2414. # except Exception, e:
  2415. # return "Operation failed: %s" % str(e)
  2416. #
  2417. # else:
  2418. # try:
  2419. # dist = float(kwa['dist'])
  2420. # except KeyError:
  2421. # dist = 0.0
  2422. # except ValueError:
  2423. # return "Invalid distance: %s" % kwa['dist']
  2424. #
  2425. # try:
  2426. # obj.mirror(axis, [dist, dist])
  2427. # obj.plot()
  2428. # except Exception, e:
  2429. # return "Operation failed: %s" % str(e)
  2430. #
  2431. # return 'Ok'
  2432. # --- Migrated to new architecture ---
  2433. # def aligndrillgrid(outname, *args):
  2434. # a, kwa = h(*args)
  2435. # types = {'gridx': float,
  2436. # 'gridy': float,
  2437. # 'gridoffsetx': float,
  2438. # 'gridoffsety': float,
  2439. # 'columns':int,
  2440. # 'rows':int,
  2441. # 'dia': float
  2442. # }
  2443. # for key in kwa:
  2444. # if key not in types:
  2445. # return 'Unknown parameter: %s' % key
  2446. # kwa[key] = types[key](kwa[key])
  2447. #
  2448. # if 'columns' not in kwa or 'rows' not in kwa:
  2449. # return "ERROR: Specify -columns and -rows"
  2450. #
  2451. # if 'gridx' not in kwa or 'gridy' not in kwa:
  2452. # return "ERROR: Specify -gridx and -gridy"
  2453. #
  2454. # if 'dia' not in kwa:
  2455. # return "ERROR: Specify -dia"
  2456. #
  2457. # if 'gridoffsetx' not in kwa:
  2458. # gridoffsetx = 0
  2459. # else:
  2460. # gridoffsetx = kwa['gridoffsetx']
  2461. #
  2462. # if 'gridoffsety' not in kwa:
  2463. # gridoffsety = 0
  2464. # else:
  2465. # gridoffsety = kwa['gridoffsety']
  2466. #
  2467. # # Tools
  2468. # tools = {"1": {"C": kwa['dia']}}
  2469. #
  2470. # def aligndrillgrid_init_me(init_obj, app_obj):
  2471. # drills = []
  2472. # currenty = 0
  2473. #
  2474. # for row in range(kwa['rows']):
  2475. # currentx = 0
  2476. #
  2477. # for col in range(kwa['columns']):
  2478. # point = Point(currentx + gridoffsetx, currenty + gridoffsety)
  2479. # drills.append({"point": point, "tool": "1"})
  2480. # currentx = currentx + kwa['gridx']
  2481. #
  2482. # currenty = currenty + kwa['gridy']
  2483. #
  2484. # init_obj.tools = tools
  2485. # init_obj.drills = drills
  2486. # init_obj.create_geometry()
  2487. #
  2488. # self.new_object("excellon", outname, aligndrillgrid_init_me)
  2489. # --- Migrated to new architecture ---
  2490. # def aligndrill(name, *args):
  2491. # a, kwa = h(*args)
  2492. # types = {'box': str,
  2493. # 'axis': str,
  2494. # 'holes': str,
  2495. # 'grid': float,
  2496. # 'minoffset': float,
  2497. # 'gridoffset': float,
  2498. # 'axisoffset': float,
  2499. # 'dia': float,
  2500. # 'dist': float}
  2501. #
  2502. # for key in kwa:
  2503. # if key not in types:
  2504. # return 'Unknown parameter: %s' % key
  2505. # kwa[key] = types[key](kwa[key])
  2506. #
  2507. # # Get source object.
  2508. # try:
  2509. # obj = self.collection.get_by_name(str(name))
  2510. # except:
  2511. # return "Could not retrieve object: %s" % name
  2512. #
  2513. # if obj is None:
  2514. # return "Object not found: %s" % name
  2515. #
  2516. # if not isinstance(obj, FlatCAMGeometry) and not isinstance(obj, FlatCAMGerber) and not isinstance(obj, FlatCAMExcellon):
  2517. # return "ERROR: Only Gerber, Geometry and Excellon objects can be used."
  2518. #
  2519. # # Axis
  2520. # try:
  2521. # axis = kwa['axis'].upper()
  2522. # except KeyError:
  2523. # return "ERROR: Specify -axis X or -axis Y"
  2524. #
  2525. # if not ('holes' in kwa or ('grid' in kwa and 'gridoffset' in kwa)):
  2526. # return "ERROR: Specify -holes or -grid with -gridoffset "
  2527. #
  2528. # if 'holes' in kwa:
  2529. # try:
  2530. # holes = eval("[" + kwa['holes'] + "]")
  2531. # except KeyError:
  2532. # return "ERROR: Wrong -holes format (X1,Y1),(X2,Y2)"
  2533. #
  2534. # xscale, yscale = {"X": (1.0, -1.0), "Y": (-1.0, 1.0)}[axis]
  2535. #
  2536. # # Tools
  2537. # tools = {"1": {"C": kwa['dia']}}
  2538. #
  2539. # def alligndrill_init_me(init_obj, app_obj):
  2540. #
  2541. # drills = []
  2542. # if 'holes' in kwa:
  2543. # for hole in holes:
  2544. # point = Point(hole)
  2545. # point_mirror = affinity.scale(point, xscale, yscale, origin=(px, py))
  2546. # drills.append({"point": point, "tool": "1"})
  2547. # drills.append({"point": point_mirror, "tool": "1"})
  2548. # else:
  2549. # if 'box' not in kwa:
  2550. # return "ERROR: -grid can be used only for -box"
  2551. #
  2552. # if 'axisoffset' in kwa:
  2553. # axisoffset = kwa['axisoffset']
  2554. # else:
  2555. # axisoffset = 0
  2556. #
  2557. # # This will align hole to given aligngridoffset and minimal offset from pcb, based on selected axis
  2558. # if axis == "X":
  2559. # firstpoint = kwa['gridoffset']
  2560. #
  2561. # while (xmin - kwa['minoffset']) < firstpoint:
  2562. # firstpoint = firstpoint - kwa['grid']
  2563. #
  2564. # lastpoint = kwa['gridoffset']
  2565. #
  2566. # while (xmax + kwa['minoffset']) > lastpoint:
  2567. # lastpoint = lastpoint + kwa['grid']
  2568. #
  2569. # localholes = (firstpoint, axisoffset), (lastpoint, axisoffset)
  2570. #
  2571. # else:
  2572. # firstpoint = kwa['gridoffset']
  2573. #
  2574. # while (ymin - kwa['minoffset']) < firstpoint:
  2575. # firstpoint = firstpoint - kwa['grid']
  2576. #
  2577. # lastpoint = kwa['gridoffset']
  2578. #
  2579. # while (ymax + kwa['minoffset']) > lastpoint:
  2580. # lastpoint = lastpoint + kwa['grid']
  2581. #
  2582. # localholes = (axisoffset, firstpoint), (axisoffset, lastpoint)
  2583. #
  2584. # for hole in localholes:
  2585. # point = Point(hole)
  2586. # point_mirror = affinity.scale(point, xscale, yscale, origin=(px, py))
  2587. # drills.append({"point": point, "tool": "1"})
  2588. # drills.append({"point": point_mirror, "tool": "1"})
  2589. #
  2590. # init_obj.tools = tools
  2591. # init_obj.drills = drills
  2592. # init_obj.create_geometry()
  2593. #
  2594. # # Box
  2595. # if 'box' in kwa:
  2596. # try:
  2597. # box = self.collection.get_by_name(kwa['box'])
  2598. # except:
  2599. # return "Could not retrieve object box: %s" % kwa['box']
  2600. #
  2601. # if box is None:
  2602. # return "Object box not found: %s" % kwa['box']
  2603. #
  2604. # try:
  2605. # xmin, ymin, xmax, ymax = box.bounds()
  2606. # px = 0.5 * (xmin + xmax)
  2607. # py = 0.5 * (ymin + ymax)
  2608. #
  2609. # obj.app.new_object("excellon", name + "_aligndrill", alligndrill_init_me)
  2610. #
  2611. # except Exception, e:
  2612. # return "Operation failed: %s" % str(e)
  2613. #
  2614. # else:
  2615. # try:
  2616. # dist = float(kwa['dist'])
  2617. # except KeyError:
  2618. # dist = 0.0
  2619. # except ValueError:
  2620. # return "Invalid distance: %s" % kwa['dist']
  2621. #
  2622. # try:
  2623. # px=dist
  2624. # py=dist
  2625. # obj.app.new_object("excellon", name + "_alligndrill", alligndrill_init_me)
  2626. # except Exception, e:
  2627. # return "Operation failed: %s" % str(e)
  2628. #
  2629. # return 'Ok'
  2630. # Migrated but still used?
  2631. # def drillcncjob(name=None, *args):
  2632. # """
  2633. # TCL shell command - see help section
  2634. #
  2635. # :param name: name of object
  2636. # :param args: array of arguments
  2637. # :return: "Ok" if completed without errors
  2638. # """
  2639. #
  2640. # try:
  2641. # a, kwa = h(*args)
  2642. # types = {'tools': str,
  2643. # 'outname': str,
  2644. # 'drillz': float,
  2645. # 'travelz': float,
  2646. # 'feedrate': float,
  2647. # 'spindlespeed': int,
  2648. # 'toolchange': int
  2649. # }
  2650. #
  2651. # if name is None:
  2652. # self.raise_tcl_error('Argument name is missing.')
  2653. #
  2654. # for key in kwa:
  2655. # if key not in types:
  2656. # self.raise_tcl_error('Unknown parameter: %s' % key)
  2657. # try:
  2658. # kwa[key] = types[key](kwa[key])
  2659. # except Exception as e:
  2660. # self.raise_tcl_error("Cannot cast argument '%s' to type %s." % (key, str(types[key])))
  2661. #
  2662. # try:
  2663. # obj = self.collection.get_by_name(str(name))
  2664. # except:
  2665. # self.raise_tcl_error("Could not retrieve object: %s" % name)
  2666. #
  2667. # if obj is None:
  2668. # self.raise_tcl_error('Object not found: %s' % name)
  2669. #
  2670. # if not isinstance(obj, FlatCAMExcellon):
  2671. # self.raise_tcl_error('Only Excellon objects can be drilled, got %s %s.' % (name, type(obj)))
  2672. #
  2673. # try:
  2674. # # Get the tools from the list
  2675. # job_name = kwa["outname"]
  2676. #
  2677. # # Object initialization function for app.new_object()
  2678. # def job_init(job_obj, app_obj):
  2679. # job_obj.z_cut = kwa["drillz"]
  2680. # job_obj.z_move = kwa["travelz"]
  2681. # job_obj.feedrate = kwa["feedrate"]
  2682. # job_obj.spindlespeed = kwa["spindlespeed"] if "spindlespeed" in kwa else None
  2683. # toolchange = True if "toolchange" in kwa and kwa["toolchange"] == 1 else False
  2684. # job_obj.generate_from_excellon_by_tool(obj, kwa["tools"], toolchange)
  2685. # job_obj.gcode_parse()
  2686. # job_obj.create_geometry()
  2687. #
  2688. # obj.app.new_object("cncjob", job_name, job_init)
  2689. #
  2690. # except Exception, e:
  2691. # self.raise_tcl_error("Operation failed: %s" % str(e))
  2692. #
  2693. # except Exception as unknown:
  2694. # self.raise_tcl_unknown_error(unknown)
  2695. # --- Migrated to new architecture ---
  2696. # def millholes(name=None, *args):
  2697. # """
  2698. # TCL shell command - see help section
  2699. # :param name: name of object
  2700. # :param args: array of arguments
  2701. # :return: "Ok" if completed without errors
  2702. # """
  2703. #
  2704. # try:
  2705. # a, kwa = h(*args)
  2706. # types = {'tooldia': float,
  2707. # 'tools': str,
  2708. # 'outname': str}
  2709. #
  2710. # if name is None:
  2711. # self.raise_tcl_error('Argument name is missing.')
  2712. #
  2713. # for key in kwa:
  2714. # if key not in types:
  2715. # self.raise_tcl_error('Unknown parameter: %s' % key)
  2716. # try:
  2717. # kwa[key] = types[key](kwa[key])
  2718. # except Exception, e:
  2719. # self.raise_tcl_error("Cannot cast argument '%s' to type %s." % (key, types[key]))
  2720. #
  2721. # try:
  2722. # if 'tools' in kwa:
  2723. # kwa['tools'] = [x.strip() for x in kwa['tools'].split(",")]
  2724. # except Exception as e:
  2725. # self.raise_tcl_error("Bad tools: %s" % str(e))
  2726. #
  2727. # try:
  2728. # obj = self.collection.get_by_name(str(name))
  2729. # except:
  2730. # self.raise_tcl_error("Could not retrieve object: %s" % name)
  2731. #
  2732. # if obj is None:
  2733. # self.raise_tcl_error("Object not found: %s" % name)
  2734. #
  2735. # if not isinstance(obj, FlatCAMExcellon):
  2736. # self.raise_tcl_error('Only Excellon objects can be mill-drilled, got %s %s.' % (name, type(obj)))
  2737. #
  2738. # try:
  2739. # # This runs in the background: Block until done.
  2740. # with wait_signal(self.new_object_available):
  2741. # success, msg = obj.generate_milling(**kwa)
  2742. #
  2743. # except Exception as e:
  2744. # self.raise_tcl_error("Operation failed: %s" % str(e))
  2745. #
  2746. # if not success:
  2747. # self.raise_tcl_error(msg)
  2748. #
  2749. # except Exception as unknown:
  2750. # self.raise_tcl_unknown_error(unknown)
  2751. # --- Migrated to new architecture ---
  2752. # def exteriors(name=None, *args):
  2753. # """
  2754. # TCL shell command - see help section
  2755. # :param name: name of object
  2756. # :param args: array of arguments
  2757. # :return: "Ok" if completed without errors
  2758. # """
  2759. #
  2760. # try:
  2761. # a, kwa = h(*args)
  2762. # types = {'outname': str}
  2763. #
  2764. # if name is None:
  2765. # self.raise_tcl_error('Argument name is missing.')
  2766. #
  2767. # for key in kwa:
  2768. # if key not in types:
  2769. # self.raise_tcl_error('Unknown parameter: %s' % key)
  2770. # try:
  2771. # kwa[key] = types[key](kwa[key])
  2772. # except Exception, e:
  2773. # self.raise_tcl_error("Cannot cast argument '%s' to type %s." % (key, types[key]))
  2774. #
  2775. # try:
  2776. # obj = self.collection.get_by_name(str(name))
  2777. # except:
  2778. # self.raise_tcl_error("Could not retrieve object: %s" % name)
  2779. #
  2780. # if obj is None:
  2781. # self.raise_tcl_error("Object not found: %s" % name)
  2782. #
  2783. # if not isinstance(obj, Geometry):
  2784. # self.raise_tcl_error('Expected Geometry, got %s %s.' % (name, type(obj)))
  2785. #
  2786. # def geo_init(geo_obj, app_obj):
  2787. # geo_obj.solid_geometry = obj_exteriors
  2788. #
  2789. # if 'outname' in kwa:
  2790. # outname = kwa['outname']
  2791. # else:
  2792. # outname = name + ".exteriors"
  2793. #
  2794. # try:
  2795. # obj_exteriors = obj.get_exteriors()
  2796. # self.new_object('geometry', outname, geo_init)
  2797. # except Exception as e:
  2798. # self.raise_tcl_error("Failed: %s" % str(e))
  2799. #
  2800. # except Exception as unknown:
  2801. # self.raise_tcl_unknown_error(unknown)
  2802. # --- Migrated to new architecture ---
  2803. # def interiors(name=None, *args):
  2804. # '''
  2805. # TCL shell command - see help section
  2806. # :param name: name of object
  2807. # :param args: array of arguments
  2808. # :return: "Ok" if completed without errors
  2809. # '''
  2810. #
  2811. # try:
  2812. # a, kwa = h(*args)
  2813. # types = {'outname': str}
  2814. #
  2815. # for key in kwa:
  2816. # if key not in types:
  2817. # self.raise_tcl_error('Unknown parameter: %s' % key)
  2818. # try:
  2819. # kwa[key] = types[key](kwa[key])
  2820. # except Exception, e:
  2821. # self.raise_tcl_error("Cannot cast argument '%s' to type %s." % (key, types[key]))
  2822. #
  2823. # if name is None:
  2824. # self.raise_tcl_error('Argument name is missing.')
  2825. #
  2826. # try:
  2827. # obj = self.collection.get_by_name(str(name))
  2828. # except:
  2829. # self.raise_tcl_error("Could not retrieve object: %s" % name)
  2830. #
  2831. # if obj is None:
  2832. # self.raise_tcl_error("Object not found: %s" % name)
  2833. #
  2834. # if not isinstance(obj, Geometry):
  2835. # self.raise_tcl_error('Expected Geometry, got %s %s.' % (name, type(obj)))
  2836. #
  2837. # def geo_init(geo_obj, app_obj):
  2838. # geo_obj.solid_geometry = obj_interiors
  2839. #
  2840. # if 'outname' in kwa:
  2841. # outname = kwa['outname']
  2842. # else:
  2843. # outname = name + ".interiors"
  2844. #
  2845. # try:
  2846. # obj_interiors = obj.get_interiors()
  2847. # self.new_object('geometry', outname, geo_init)
  2848. # except Exception as e:
  2849. # self.raise_tcl_error("Failed: %s" % str(e))
  2850. #
  2851. # except Exception as unknown:
  2852. # self.raise_tcl_unknown_error(unknown)
  2853. # --- Migrated to new architecture ---
  2854. # def isolate(name=None, *args):
  2855. # """
  2856. # TCL shell command - see help section
  2857. # :param name: name of object
  2858. # :param args: array of arguments
  2859. # :return: "Ok" if completed without errors
  2860. # """
  2861. #
  2862. # a, kwa = h(*args)
  2863. # types = {'dia': float,
  2864. # 'passes': int,
  2865. # 'overlap': float,
  2866. # 'outname': str,
  2867. # 'combine': int}
  2868. #
  2869. # for key in kwa:
  2870. # if key not in types:
  2871. # self.raise_tcl_error('Unknown parameter: %s' % key)
  2872. # try:
  2873. # kwa[key] = types[key](kwa[key])
  2874. # except Exception, e:
  2875. # self.raise_tcl_error("Cannot cast argument '%s' to type %s." % (key, types[key]))
  2876. # try:
  2877. # obj = self.collection.get_by_name(str(name))
  2878. # except:
  2879. # self.raise_tcl_error("Could not retrieve object: %s" % name)
  2880. #
  2881. # if obj is None:
  2882. # self.raise_tcl_error("Object not found: %s" % name)
  2883. #
  2884. # assert isinstance(obj, FlatCAMGerber), \
  2885. # "Expected a FlatCAMGerber, got %s" % type(obj)
  2886. #
  2887. # if not isinstance(obj, FlatCAMGerber):
  2888. # self.raise_tcl_error('Expected FlatCAMGerber, got %s %s.' % (name, type(obj)))
  2889. #
  2890. # try:
  2891. # obj.isolate(**kwa)
  2892. # except Exception, e:
  2893. # self.raise_tcl_error("Operation failed: %s" % str(e))
  2894. #
  2895. # return 'Ok'
  2896. # --- Migrated to new architecture ---
  2897. # def cncjob(obj_name, *args):
  2898. # a, kwa = h(*args)
  2899. #
  2900. # types = {'z_cut': float,
  2901. # 'z_move': float,
  2902. # 'feedrate': float,
  2903. # 'tooldia': float,
  2904. # 'outname': str,
  2905. # 'spindlespeed': int,
  2906. # 'multidepth' : bool,
  2907. # 'depthperpass' : float
  2908. # }
  2909. #
  2910. # for key in kwa:
  2911. # if key not in types:
  2912. # return 'Unknown parameter: %s' % key
  2913. # kwa[key] = types[key](kwa[key])
  2914. #
  2915. # try:
  2916. # obj = self.collection.get_by_name(str(obj_name))
  2917. # except:
  2918. # return "Could not retrieve object: %s" % obj_name
  2919. # if obj is None:
  2920. # return "Object not found: %s" % obj_name
  2921. #
  2922. # try:
  2923. # obj.generatecncjob(**kwa)
  2924. # except Exception, e:
  2925. # return "Operation failed: %s" % str(e)
  2926. #
  2927. # return 'Ok'
  2928. # --- Migrated to new architecture ---
  2929. # def write_gcode(obj_name, filename, preamble='', postamble=''):
  2930. # """
  2931. # Requires obj_name to be available. It might still be in the
  2932. # making at the time this function is called, so check for
  2933. # promises and send to background if there are promises.
  2934. # """
  2935. #
  2936. # # If there are promised objects, wait until all promises have been fulfilled.
  2937. # if self.collection.has_promises():
  2938. #
  2939. # def write_gcode_on_object(new_object):
  2940. # self.log.debug("write_gcode_on_object(): Disconnecting %s" % write_gcode_on_object)
  2941. # self.new_object_available.disconnect(write_gcode_on_object)
  2942. # write_gcode(obj_name, filename, preamble, postamble)
  2943. #
  2944. # # Try again when a new object becomes available.
  2945. # self.log.debug("write_gcode(): Collection has promises. Queued for %s." % obj_name)
  2946. # self.log.debug("write_gcode(): Queued function: %s" % write_gcode_on_object)
  2947. # self.new_object_available.connect(write_gcode_on_object)
  2948. #
  2949. # return
  2950. #
  2951. # self.log.debug("write_gcode(): No promises. Continuing for %s." % obj_name)
  2952. #
  2953. # try:
  2954. # obj = self.collection.get_by_name(str(obj_name))
  2955. # except:
  2956. # return "Could not retrieve object: %s" % obj_name
  2957. #
  2958. # try:
  2959. # obj.export_gcode(str(filename), str(preamble), str(postamble))
  2960. # except Exception, e:
  2961. # return "Operation failed: %s" % str(e)
  2962. # --- Migrated to new architecture ---
  2963. # def paint_poly(obj_name, inside_pt_x, inside_pt_y, tooldia, overlap):
  2964. # try:
  2965. # obj = self.collection.get_by_name(str(obj_name))
  2966. # except:
  2967. # return "Could not retrieve object: %s" % obj_name
  2968. # if obj is None:
  2969. # return "Object not found: %s" % obj_name
  2970. # obj.paint_poly([float(inside_pt_x), float(inside_pt_y)], float(tooldia), float(overlap))
  2971. # --- New version in new geometry exists, but required here temporarily. ---
  2972. # def add_poly(obj_name, *args):
  2973. # """
  2974. # Required by: add_rectangle()
  2975. #
  2976. # :param obj_name:
  2977. # :param args:
  2978. # :return:
  2979. # """
  2980. # if len(args) % 2 != 0:
  2981. # return "Incomplete coordinate."
  2982. #
  2983. # points = [[float(args[2*i]), float(args[2*i+1])] for i in range(len(args)/2)]
  2984. #
  2985. # try:
  2986. # obj = self.collection.get_by_name(str(obj_name))
  2987. # except:
  2988. # return "Could not retrieve object: %s" % obj_name
  2989. # if obj is None:
  2990. # return "Object not found: %s" % obj_name
  2991. #
  2992. # obj.add_polygon(points)
  2993. # --- Migrated to new architecture ---
  2994. # def add_rectangle(obj_name, botleft_x, botleft_y, topright_x, topright_y):
  2995. # return add_poly(obj_name, botleft_x, botleft_y, botleft_x, topright_y,
  2996. # topright_x, topright_y, topright_x, botleft_y)
  2997. # --- Migrated to new architecture ---
  2998. # def subtract_poly(obj_name, *args):
  2999. # """
  3000. # Required by: subtract_rectangle()
  3001. #
  3002. # :param obj_name:
  3003. # :param args:
  3004. # :return:
  3005. # """
  3006. # if len(args) % 2 != 0:
  3007. # return "Incomplete coordinate."
  3008. #
  3009. # points = [[float(args[2 * i]), float(args[2 * i +1])] for i in range(len(args)/2)]
  3010. #
  3011. # try:
  3012. # obj = self.collection.get_by_name(str(obj_name))
  3013. # except:
  3014. # return "Could not retrieve object: %s" % obj_name
  3015. # if obj is None:
  3016. # return "Object not found: %s" % obj_name
  3017. #
  3018. # obj.subtract_polygon(points)
  3019. # obj.plot()
  3020. #
  3021. # return "OK."
  3022. # --- Migrated to new architecture ---
  3023. # def subtract_rectangle(obj_name, botleft_x, botleft_y, topright_x, topright_y):
  3024. # return subtract_poly(obj_name, botleft_x, botleft_y, botleft_x, topright_y,
  3025. # topright_x, topright_y, topright_x, botleft_y)
  3026. # --- Migrated to new architecture ---
  3027. # def add_circle(obj_name, center_x, center_y, radius):
  3028. # try:
  3029. # obj = self.collection.get_by_name(str(obj_name))
  3030. # except:
  3031. # return "Could not retrieve object: %s" % obj_name
  3032. # if obj is None:
  3033. # return "Object not found: %s" % obj_name
  3034. #
  3035. # obj.add_circle([float(center_x), float(center_y)], float(radius))
  3036. # --- Migrated to new architecture ---
  3037. # def set_active(obj_name):
  3038. # try:
  3039. # self.collection.set_active(str(obj_name))
  3040. # except Exception, e:
  3041. # return "Command failed: %s" % str(e)
  3042. # --- Migrated to new architecture ---
  3043. # def delete(obj_name):
  3044. # try:
  3045. # #deselect all to avoid delete selected object when run delete from shell
  3046. # self.collection.set_all_inactive()
  3047. # self.collection.set_active(str(obj_name))
  3048. # self.on_delete()
  3049. # except Exception, e:
  3050. # return "Command failed: %s" % str(e)
  3051. # --- Migrated to new architecture ---
  3052. # def geo_union(obj_name):
  3053. #
  3054. # try:
  3055. # obj = self.collection.get_by_name(str(obj_name))
  3056. # except:
  3057. # return "Could not retrieve object: %s" % obj_name
  3058. # if obj is None:
  3059. # return "Object not found: %s" % obj_name
  3060. #
  3061. # obj.union()
  3062. # --- Migrated to new architecture ---
  3063. # def join_geometries(obj_name, *obj_names):
  3064. # objs = []
  3065. # for obj_n in obj_names:
  3066. # obj = self.collection.get_by_name(str(obj_n))
  3067. # if obj is None:
  3068. # return "Object not found: %s" % obj_n
  3069. # else:
  3070. # objs.append(obj)
  3071. #
  3072. # def initialize(obj, app):
  3073. # FlatCAMGeometry.merge(objs, obj)
  3074. #
  3075. # if objs is not None:
  3076. # self.new_object("geometry", obj_name, initialize)
  3077. # --- Migrated to new architecture ---
  3078. # def join_excellons(obj_name, *obj_names):
  3079. # objs = []
  3080. # for obj_n in obj_names:
  3081. # obj = self.collection.get_by_name(str(obj_n))
  3082. # if obj is None:
  3083. # return "Object not found: %s" % obj_n
  3084. # else:
  3085. # objs.append(obj)
  3086. #
  3087. # def initialize(obj, app):
  3088. # FlatCAMExcellon.merge(objs, obj)
  3089. #
  3090. # if objs is not None:
  3091. # self.new_object("excellon", obj_name, initialize)
  3092. # --- Migrated to new architecture ---
  3093. # def panelize(name, *args):
  3094. # a, kwa = h(*args)
  3095. # types = {'box': str,
  3096. # 'spacing_columns': float,
  3097. # 'spacing_rows': float,
  3098. # 'columns': int,
  3099. # 'rows': int,
  3100. # 'outname': str}
  3101. #
  3102. # for key in kwa:
  3103. # if key not in types:
  3104. # return 'Unknown parameter: %s' % key
  3105. # kwa[key] = types[key](kwa[key])
  3106. #
  3107. # # Get source object.
  3108. # try:
  3109. # obj = self.collection.get_by_name(str(name))
  3110. # except:
  3111. # return "Could not retrieve object: %s" % name
  3112. #
  3113. # if obj is None:
  3114. # return "Object not found: %s" % name
  3115. #
  3116. # if 'box' in kwa:
  3117. # boxname = kwa['box']
  3118. # try:
  3119. # box = self.collection.get_by_name(boxname)
  3120. # except:
  3121. # return "Could not retrieve object: %s" % name
  3122. # else:
  3123. # box = obj
  3124. #
  3125. # if 'columns' not in kwa or 'rows' not in kwa:
  3126. # return "ERROR: Specify -columns and -rows"
  3127. #
  3128. # if 'outname' in kwa:
  3129. # outname = kwa['outname']
  3130. # else:
  3131. # outname = name + '_panelized'
  3132. #
  3133. # if 'spacing_columns' in kwa:
  3134. # spacing_columns = kwa['spacing_columns']
  3135. # else:
  3136. # spacing_columns = 5
  3137. #
  3138. # if 'spacing_rows' in kwa:
  3139. # spacing_rows = kwa['spacing_rows']
  3140. # else:
  3141. # spacing_rows = 5
  3142. #
  3143. # xmin, ymin, xmax, ymax = box.bounds()
  3144. # lenghtx = xmax - xmin + spacing_columns
  3145. # lenghty = ymax - ymin + spacing_rows
  3146. #
  3147. # currenty = 0
  3148. #
  3149. # def initialize_local(obj_init, app):
  3150. # obj_init.solid_geometry = obj.solid_geometry
  3151. # obj_init.offset([float(currentx), float(currenty)]),
  3152. #
  3153. # def initialize_local_excellon(obj_init, app):
  3154. # FlatCAMExcellon.merge(obj, obj_init)
  3155. # obj_init.offset([float(currentx), float(currenty)]),
  3156. #
  3157. # def initialize_geometry(obj_init, app):
  3158. # FlatCAMGeometry.merge(objs, obj_init)
  3159. #
  3160. # def initialize_excellon(obj_init, app):
  3161. # FlatCAMExcellon.merge(objs, obj_init)
  3162. #
  3163. # objs = []
  3164. # if obj is not None:
  3165. #
  3166. # for row in range(kwa['rows']):
  3167. # currentx = 0
  3168. # for col in range(kwa['columns']):
  3169. # local_outname = outname + ".tmp." + str(col) + "." + str(row)
  3170. # if isinstance(obj, FlatCAMExcellon):
  3171. # self.new_object("excellon", local_outname, initialize_local_excellon)
  3172. # else:
  3173. # self.new_object("geometry", local_outname, initialize_local)
  3174. #
  3175. # currentx += lenghtx
  3176. # currenty += lenghty
  3177. #
  3178. # if isinstance(obj, FlatCAMExcellon):
  3179. # self.new_object("excellon", outname, initialize_excellon)
  3180. # else:
  3181. # self.new_object("geometry", outname, initialize_geometry)
  3182. #
  3183. # #deselect all to avoid delete selected object when run delete from shell
  3184. # self.collection.set_all_inactive()
  3185. # for delobj in objs:
  3186. # self.collection.set_active(delobj.options['name'])
  3187. # self.on_delete()
  3188. #
  3189. # else:
  3190. # return "ERROR: obj is None"
  3191. #
  3192. # return "Ok"
  3193. def make_docs():
  3194. output = ''
  3195. import collections
  3196. od = collections.OrderedDict(sorted(commands.items()))
  3197. for cmd_, val in list(od.items()):
  3198. #print cmd, '\n', ''.join(['~']*len(cmd))
  3199. output += cmd_ + ' \n' + ''.join(['~'] * len(cmd_)) + '\n'
  3200. t = val['help']
  3201. usage_i = t.find('>')
  3202. if usage_i < 0:
  3203. expl = t
  3204. #print expl + '\n'
  3205. output += expl + '\n\n'
  3206. continue
  3207. expl = t[:usage_i - 1]
  3208. #print expl + '\n'
  3209. output += expl + '\n\n'
  3210. end_usage_i = t[usage_i:].find('\n')
  3211. if end_usage_i < 0:
  3212. end_usage_i = len(t[usage_i:])
  3213. #print ' ' + t[usage_i:]
  3214. #print ' No parameters.\n'
  3215. output += ' ' + t[usage_i:] + '\n No parameters.\n'
  3216. else:
  3217. extras = t[usage_i+end_usage_i+1:]
  3218. parts = [s.strip() for s in extras.split('\n')]
  3219. #print ' ' + t[usage_i:usage_i+end_usage_i]
  3220. output += ' ' + t[usage_i:usage_i+end_usage_i] + '\n'
  3221. for p in parts:
  3222. #print ' ' + p + '\n'
  3223. output += ' ' + p + '\n\n'
  3224. return output
  3225. # def follow(obj_name, *args):
  3226. # a, kwa = h(*args)
  3227. #
  3228. # types = {'outname': str}
  3229. #
  3230. # for key in kwa:
  3231. # if key not in types:
  3232. # return 'Unknown parameter: %s' % key
  3233. # kwa[key] = types[key](kwa[key])
  3234. #
  3235. # try:
  3236. # obj = self.collection.get_by_name(str(obj_name))
  3237. # except:
  3238. # return "Could not retrieve object: %s" % obj_name
  3239. # if obj is None:
  3240. # return "Object not found: %s" % obj_name
  3241. #
  3242. # try:
  3243. # obj.follow(**kwa)
  3244. # except Exception, e:
  3245. # return "ERROR: %s" % str(e)
  3246. # def follow(obj_name, *args):
  3247. # a, kwa = h(*args)
  3248. #
  3249. # types = {'outname': str}
  3250. #
  3251. # for key in kwa:
  3252. # if key not in types:
  3253. # return 'Unknown parameter: %s' % key
  3254. # kwa[key] = types[key](kwa[key])
  3255. #
  3256. # try:
  3257. # obj = self.collection.get_by_name(str(obj_name))
  3258. # except:
  3259. # return "Could not retrieve object: %s" % obj_name
  3260. # if obj is None:
  3261. # return "Object not found: %s" % obj_name
  3262. #
  3263. # try:
  3264. # obj.follow(**kwa)
  3265. # except Exception as e:
  3266. # return "ERROR: %s" % str(e)
  3267. # def get_sys(param):
  3268. # if param in self.defaults:
  3269. # return self.defaults[param]
  3270. #
  3271. # return "ERROR: No such system parameter."
  3272. # def set_sys(param, value):
  3273. # # tcl string to python keywords:
  3274. # tcl2py = {
  3275. # "None": None,
  3276. # "none": None,
  3277. # "false": False,
  3278. # "False": False,
  3279. # "true": True,
  3280. # "True": True
  3281. # }
  3282. #
  3283. # if param in self.defaults:
  3284. #
  3285. # try:
  3286. # value = tcl2py[value]
  3287. # except KeyError:
  3288. # pass
  3289. #
  3290. # self.defaults[param] = value
  3291. #
  3292. # self.propagate_defaults()
  3293. # return "Ok"
  3294. #
  3295. # return "ERROR: No such system parameter."
  3296. '''
  3297. Howto implement TCL shell commands:
  3298. All parameters passed to command should be possible to set as None and test it afterwards.
  3299. This is because we need to see error caused in tcl,
  3300. if None value as default parameter is not allowed TCL will return empty error.
  3301. Use:
  3302. def mycommand(name=None,...):
  3303. Test it like this:
  3304. if name is None:
  3305. self.raise_tcl_error('Argument name is missing.')
  3306. When error ocurre, always use raise_tcl_error, never return "sometext" on error,
  3307. otherwise we will miss it and processing will silently continue.
  3308. Method raise_tcl_error pass error into TCL interpreter, then raise python exception,
  3309. which is catched in exec_command and displayed in TCL shell console with red background.
  3310. Error in console is displayed with TCL trace.
  3311. This behavior works only within main thread,
  3312. errors with promissed tasks can be catched and detected only with log.
  3313. TODO: this problem have to be addressed somehow, maybe rewrite promissing to be blocking somehow for TCL shell.
  3314. Kamil's comment: I will rewrite existing TCL commands from time to time to follow this rules.
  3315. '''
  3316. commands = {
  3317. # 'mytest': {
  3318. # 'fcn': mytest,
  3319. # 'help': "Test function. Only for testing."
  3320. # },
  3321. # 'mytest2': {
  3322. # 'fcn': mytest2,
  3323. # 'help': "Test function. Only for testing."
  3324. # },
  3325. # 'mytest3': {
  3326. # 'fcn': mytest3,
  3327. # 'help': "Test function. Only for testing."
  3328. # },
  3329. # 'mytest4': {
  3330. # 'fcn': mytest4,
  3331. # 'help': "Test function. Only for testing."
  3332. # },
  3333. 'help': {
  3334. 'fcn': shelp,
  3335. 'help': "Shows list of commands."
  3336. },
  3337. # --- Migrated to new architecture ---
  3338. # 'import_svg': {
  3339. # 'fcn': import_svg,
  3340. # 'help': "Import an SVG file as a Geometry Object.\n" +
  3341. # "> import_svg <filename>" +
  3342. # " filename: Path to the file to import."
  3343. # },
  3344. # --- Migrated to new architecture ---
  3345. # 'export_svg': {
  3346. # 'fcn': export_svg,
  3347. # 'help': "Export a Geometry Object as a SVG File\n" +
  3348. # "> export_svg <name> <filename> [-scale_factor <0.0 (float)>]\n" +
  3349. # " name: Name of the geometry object to export.\n" +
  3350. # " filename: Path to the file to export.\n" +
  3351. # " scale_factor: Multiplication factor used for scaling line widths during export."
  3352. # },
  3353. # --- Migrated to new architecture ---
  3354. # 'open_gerber': {
  3355. # 'fcn': open_gerber,
  3356. # 'help': "Opens a Gerber file.\n"
  3357. # "> open_gerber <filename> [-follow <0|1>] [-outname <o>]\n"
  3358. # " filename: Path to file to open.\n" +
  3359. # " follow: If 1, does not create polygons, just follows the gerber path.\n" +
  3360. # " outname: Name of the created gerber object."
  3361. # },
  3362. # --- Migrated to new architecture ---
  3363. # 'open_excellon': {
  3364. # 'fcn': open_excellon,
  3365. # 'help': "Opens an Excellon file.\n" +
  3366. # "> open_excellon <filename> [-outname <o>]\n" +
  3367. # " filename: Path to file to open.\n" +
  3368. # " outname: Name of the created excellon object."
  3369. # },
  3370. # --- Migrated to new architecture ---
  3371. # 'open_gcode': {
  3372. # 'fcn': open_gcode,
  3373. # 'help': "Opens an G-Code file.\n" +
  3374. # "> open_gcode <filename> [-outname <o>]\n" +
  3375. # " filename: Path to file to open.\n" +
  3376. # " outname: Name of the created CNC Job object."
  3377. # },
  3378. # --- Migrated to new architecture ---
  3379. # 'open_project': {
  3380. # 'fcn': self.open_project,
  3381. # "help": "Opens a FlatCAM project.\n" +
  3382. # "> open_project <filename>\n" +
  3383. # " filename: Path to file to open."
  3384. # },
  3385. # --- Migrated to new architecture ---
  3386. # 'save_project': {
  3387. # 'fcn': self.save_project,
  3388. # 'help': "Saves the FlatCAM project to file.\n" +
  3389. # "> save_project <filename>\n" +
  3390. # " filename: Path to file to save."
  3391. # },
  3392. # --- Migrated to new architecture ---
  3393. # 'set_active': {
  3394. # 'fcn': set_active,
  3395. # 'help': "Sets a FlatCAM object as active.\n" +
  3396. # "> set_active <name>\n" +
  3397. # " name: Name of the object."
  3398. # },
  3399. # --- Migrated to new architecture ---
  3400. # 'get_names': {
  3401. # 'fcn': lambda: '\n'.join(self.collection.get_names()),
  3402. # 'help': "Lists the names of objects in the project.\n" +
  3403. # "> get_names"
  3404. # },
  3405. # --- Migrated to new architecture ---
  3406. # 'new': {
  3407. # 'fcn': self.on_file_new,
  3408. # 'help': "Starts a new project. Clears objects from memory.\n" +
  3409. # "> new"
  3410. # },
  3411. # --- Migrated to new architecture ---
  3412. # 'options': {
  3413. # 'fcn': options,
  3414. # 'help': "Shows the settings for an object.\n" +
  3415. # "> options <name>\n" +
  3416. # " name: Object name."
  3417. # },
  3418. # --- Migrated to new architecture ---
  3419. # 'isolate': {
  3420. # 'fcn': isolate,
  3421. # 'help': "Creates isolation routing geometry for the given Gerber.\n" +
  3422. # "> isolate <name> [-dia <d>] [-passes <p>] [-overlap <o>] [-combine 0|1]\n" +
  3423. # " name: Name of the object.\n"
  3424. # " dia: Tool diameter\n passes: # of tool width.\n" +
  3425. # " overlap: Fraction of tool diameter to overlap passes." +
  3426. # " combine: combine all passes into one geometry." +
  3427. # " outname: Name of the resulting Geometry object."
  3428. # },
  3429. # 'cutout': {
  3430. # 'fcn': cutout,
  3431. # 'help': "Creates board cutout.\n" +
  3432. # "> cutout <name> [-dia <3.0 (float)>] [-margin <0.0 (float)>] [-gapsize <0.5 (float)>] [-gaps <lr (4|tb|lr)>]\n" +
  3433. # " name: Name of the object\n" +
  3434. # " dia: Tool diameter\n" +
  3435. # " margin: Margin over bounds\n" +
  3436. # " gapsize: size of gap\n" +
  3437. # " gaps: type of gaps"
  3438. # },
  3439. # --- Migrated to new architecture ---
  3440. # 'geocutout': {
  3441. # 'fcn': geocutout,
  3442. # 'help': "Cut holding gaps from geometry.\n" +
  3443. # "> geocutout <name> [-dia <3.0 (float)>] [-margin <0.0 (float)>] [-gapsize <0.5 (float)>] [-gaps <lr (8|4|tb|lr|2tb|2lr)>]\n" +
  3444. # " name: Name of the geometry object\n" +
  3445. # " dia: Tool diameter\n" +
  3446. # " margin: Margin over bounds\n" +
  3447. # " gapsize: size of gap\n" +
  3448. # " gaps: type of gaps\n" +
  3449. # "\n" +
  3450. # " example:\n" +
  3451. # "\n" +
  3452. # " #isolate margin for example from fritzing arduino shield or any svg etc\n" +
  3453. # " isolate BCu_margin -dia 3 -overlap 1\n" +
  3454. # "\n" +
  3455. # " #create exteriors from isolated object\n" +
  3456. # " exteriors BCu_margin_iso -outname BCu_margin_iso_exterior\n" +
  3457. # "\n" +
  3458. # " #delete isolated object if you dond need id anymore\n" +
  3459. # " delete BCu_margin_iso\n" +
  3460. # "\n" +
  3461. # " #finally cut holding gaps\n" +
  3462. # " geocutout BCu_margin_iso_exterior -dia 3 -gapsize 0.6 -gaps 4\n"
  3463. # },
  3464. # --- Migrated to new architecture ---
  3465. # 'mirror': {
  3466. # 'fcn': mirror,
  3467. # 'help': "Mirror a layer.\n" +
  3468. # "> mirror <name> -axis <X|Y> [-box <nameOfBox> | -dist <number>]\n" +
  3469. # " name: Name of the object (Gerber or Excellon) to mirror.\n" +
  3470. # " box: Name of object which act as box (cutout for example.)\n" +
  3471. # " axis: Mirror axis parallel to the X or Y axis.\n" +
  3472. # " dist: Distance of the mirror axis to the X or Y axis."
  3473. #},
  3474. # --- Migrated to new architecture ---
  3475. # 'aligndrillgrid': {
  3476. # 'fcn': aligndrillgrid,
  3477. # 'help': "Create excellon with drills for aligment grid.\n" +
  3478. # "> aligndrillgrid <outname> [-dia <3.0 (float)>] -gridx <float> [-gridoffsetx <0 (float)>] -gridy <float> [-gridoffsety <0 (float)>] -columns <int> -rows <int>\n" +
  3479. # " outname: Name of the object to create.\n" +
  3480. # " dia: Tool diameter\n" +
  3481. # " gridx: grid size in X axis\n" +
  3482. # " gridoffsetx: move grid from origin\n" +
  3483. # " gridy: grid size in Y axis\n" +
  3484. # " gridoffsety: move grid from origin\n" +
  3485. # " colums: grid holes on X axis\n" +
  3486. # " rows: grid holes on Y axis\n"
  3487. # },
  3488. # --- Migrated to new architecture ---
  3489. # 'aligndrill': {
  3490. # 'fcn': aligndrill,
  3491. # 'help': "Create excellon with drills for aligment.\n" +
  3492. # "> aligndrill <name> [-dia <3.0 (float)>] -axis <X|Y> [-box <nameOfBox> -minoffset <float> [-grid <10 (float)> -gridoffset <5 (float)> [-axisoffset <0 (float)>]] | -dist <number>]\n" +
  3493. # " name: Name of the object (Gerber or Excellon) to mirror.\n" +
  3494. # " dia: Tool diameter\n" +
  3495. # " box: Name of object which act as box (cutout for example.)\n" +
  3496. # " grid: aligning to grid, for thouse, who have aligning pins inside table in grid (-5,0),(5,0),(15,0)..." +
  3497. # " gridoffset: offset of grid from 0 position" +
  3498. # " minoffset: min and max distance between align hole and pcb" +
  3499. # " axisoffset: offset on second axis before aligment holes" +
  3500. # " axis: Mirror axis parallel to the X or Y axis.\n" +
  3501. # " dist: Distance of the mirror axis to the X or Y axis."
  3502. # },
  3503. # --- Migrated to new architecture ---
  3504. # 'exteriors': {
  3505. # 'fcn': exteriors,
  3506. # 'help': "Get exteriors of polygons.\n" +
  3507. # "> exteriors <name> [-outname <outname>]\n" +
  3508. # " name: Name of the source Geometry object.\n" +
  3509. # " outname: Name of the resulting Geometry object."
  3510. # },
  3511. # --- Migrated to new architecture ---
  3512. # 'interiors': {
  3513. # 'fcn': interiors,
  3514. # 'help': "Get interiors of polygons.\n" +
  3515. # "> interiors <name> [-outname <outname>]\n" +
  3516. # " name: Name of the source Geometry object.\n" +
  3517. # " outname: Name of the resulting Geometry object."
  3518. # },
  3519. # --- Migrated to new architecture ---
  3520. # 'drillcncjob': {
  3521. # 'fcn': drillcncjob,
  3522. # 'help': "Drill CNC job.\n" +
  3523. # "> drillcncjob <name> -tools <str> -drillz <float> " +
  3524. # "-travelz <float> -feedrate <float> -outname <str> " +
  3525. # "[-spindlespeed (int)] [-toolchange (int)] \n" +
  3526. # " name: Name of the object\n" +
  3527. # " tools: Comma separated indexes of tools (example: 1,3 or 2)\n" +
  3528. # " drillz: Drill depth into material (example: -2.0)\n" +
  3529. # " travelz: Travel distance above material (example: 2.0)\n" +
  3530. # " feedrate: Drilling feed rate\n" +
  3531. # " outname: Name of object to create\n" +
  3532. # " spindlespeed: Speed of the spindle in rpm (example: 4000)\n" +
  3533. # " toolchange: Enable tool changes (example: 1)\n"
  3534. # },
  3535. # 'millholes': {
  3536. # 'fcn': millholes,
  3537. # 'help': "Create Geometry Object for milling holes from Excellon.\n" +
  3538. # "> millholes <name> -tools <str> -tooldia <float> -outname <str> \n" +
  3539. # " name: Name of the Excellon Object\n" +
  3540. # " tools: Comma separated indexes of tools (example: 1,3 or 2)\n" +
  3541. # " tooldia: Diameter of the milling tool (example: 0.1)\n" +
  3542. # " outname: Name of object to create\n"
  3543. # },
  3544. # --- Migrated to the new architecture ---
  3545. # 'scale': {
  3546. # 'fcn': lambda name, factor: self.collection.get_by_name(str(name)).scale(float(factor)),
  3547. # 'help': "Resizes the object by a factor.\n" +
  3548. # "> scale <name> <factor>\n" +
  3549. # " name: Name of the object\n factor: Fraction by which to scale"
  3550. # },
  3551. # --- Migrated to the new architecture ---
  3552. # 'offset': {
  3553. # 'fcn': lambda name, x, y: self.collection.get_by_name(str(name)).offset([float(x), float(y)]),
  3554. # 'help': "Changes the position of the object.\n" +
  3555. # "> offset <name> <x> <y>\n" +
  3556. # " name: Name of the object\n" +
  3557. # " x: X-axis distance\n" +
  3558. # " y: Y-axis distance"
  3559. # },
  3560. # --- Migrated to new architecture ---
  3561. # 'plot': {
  3562. # 'fcn': self.plot_all,
  3563. # 'help': 'Updates the plot on the user interface'
  3564. # },
  3565. # --- Migrated to new architecture ---
  3566. # 'cncjob': {
  3567. # 'fcn': cncjob,
  3568. # 'help': 'Generates a CNC Job from a Geometry Object.\n' +
  3569. # '> cncjob <name> [-z_cut <c>] [-z_move <float>] [-feedrate <float>] [-tooldia <float>] [-spindlespeed <int>] [-multidepth <bool>] [-depthperpass <float>] [-outname <str>]\n' +
  3570. # ' name: Name of the source object\n' +
  3571. # ' z_cut: Z-axis cutting position\n' +
  3572. # ' z_move: Z-axis moving position\n' +
  3573. # ' feedrate: Moving speed when cutting\n' +
  3574. # ' tooldia: Tool diameter to show on screen\n' +
  3575. # ' spindlespeed: Speed of the spindle in rpm (example: 4000)\n' +
  3576. # ' multidepth: Use or not multidepth cnccut\n'+
  3577. # ' depthperpass: Height of one layer for multidepth\n'+
  3578. # ' outname: Name of the output object'
  3579. # },
  3580. # --- Migrated to new architecture ---
  3581. # 'write_gcode': {
  3582. # 'fcn': write_gcode,
  3583. # 'help': 'Saves G-code of a CNC Job object to file.\n' +
  3584. # '> write_gcode <name> <filename>\n' +
  3585. # ' name: Source CNC Job object\n' +
  3586. # ' filename: Output filename'
  3587. # },
  3588. # --- Migrated to new architecture ---
  3589. # 'paint_poly': {
  3590. # 'fcn': paint_poly,
  3591. # 'help': 'Creates a geometry object with toolpath to cover the inside of a polygon.\n' +
  3592. # '> paint_poly <name> <inside_pt_x> <inside_pt_y> <tooldia> <overlap>\n' +
  3593. # ' name: Name of the sourge geometry object.\n' +
  3594. # ' inside_pt_x, inside_pt_y: Coordinates of a point inside the polygon.\n' +
  3595. # ' tooldia: Diameter of the tool to be used.\n' +
  3596. # ' overlap: Fraction of the tool diameter to overlap cuts.'
  3597. # },
  3598. # --- Migrated to new architecture ---
  3599. # 'new_geometry': {
  3600. # 'fcn': lambda name: self.new_object('geometry', str(name), lambda x, y: None),
  3601. # 'help': 'Creates a new empty geometry object.\n' +
  3602. # '> new_geometry <name>\n' +
  3603. # ' name: New object name'
  3604. # },
  3605. # --- Migrated to new architecture ---
  3606. # 'add_poly': {
  3607. # 'fcn': add_poly,
  3608. # 'help': 'Creates a polygon in the given Geometry object.\n' +
  3609. # '> create_poly <name> <x0> <y0> <x1> <y1> <x2> <y2> [x3 y3 [...]]\n' +
  3610. # ' name: Name of the geometry object to which to append the polygon.\n' +
  3611. # ' xi, yi: Coordinates of points in the polygon.'
  3612. # },
  3613. # --- Migrated to new architecture ---
  3614. # 'subtract_poly': {
  3615. # 'fcn': subtract_poly,
  3616. # 'help': 'Subtract polygon from the given Geometry object.\n' +
  3617. # '> subtract_poly <name> <x0> <y0> <x1> <y1> <x2> <y2> [x3 y3 [...]]\n' +
  3618. # ' name: Name of the geometry object, which will be sutracted.\n' +
  3619. # ' xi, yi: Coordinates of points in the polygon.'
  3620. # },
  3621. # --- Migrated to new architecture ---
  3622. # 'delete': {
  3623. # 'fcn': delete,
  3624. # 'help': 'Deletes the give object.\n' +
  3625. # '> delete <name>\n' +
  3626. # ' name: Name of the object to delete.'
  3627. # },
  3628. # --- Migrated to new architecture ---
  3629. # 'geo_union': {
  3630. # 'fcn': geo_union,
  3631. # 'help': 'Runs a union operation (addition) on the components ' +
  3632. # 'of the geometry object. For example, if it contains ' +
  3633. # '2 intersecting polygons, this opperation adds them into' +
  3634. # 'a single larger polygon.\n' +
  3635. # '> geo_union <name>\n' +
  3636. # ' name: Name of the geometry object.'
  3637. # },
  3638. # --- Migrated to new architecture ---
  3639. # 'join_geometries': {
  3640. # 'fcn': join_geometries,
  3641. # 'help': 'Runs a merge operation (join) on the geometry ' +
  3642. # 'objects.' +
  3643. # '> join_geometries <out_name> <obj_name_0>....\n' +
  3644. # ' out_name: Name of the new geometry object.' +
  3645. # ' obj_name_0... names of the objects to join'
  3646. # },
  3647. # --- Migrated to new architecture ---
  3648. # 'join_excellons': {
  3649. # 'fcn': join_excellons,
  3650. # 'help': 'Runs a merge operation (join) on the excellon ' +
  3651. # 'objects.' +
  3652. # '> join_excellons <out_name> <obj_name_0>....\n' +
  3653. # ' out_name: Name of the new excellon object.' +
  3654. # ' obj_name_0... names of the objects to join'
  3655. # },
  3656. # --- Migrated to new architecture ---
  3657. # 'panelize': {
  3658. # 'fcn': panelize,
  3659. # 'help': "Simple panelize geometries.\n" +
  3660. # "> panelize <name> [-box <nameOfBox>] [-spacing_columns <5 (float)>] [-spacing_rows <5 (float)>] -columns <int> -rows <int> [-outname <n>]\n" +
  3661. # " name: Name of the object to panelize.\n" +
  3662. # " box: Name of object which act as box (cutout for example.) for cutout boundary. Object from name is used if not specified.\n" +
  3663. # " spacing_columns: spacing between columns\n"+
  3664. # " spacing_rows: spacing between rows\n"+
  3665. # " columns: number of columns\n"+
  3666. # " rows: number of rows\n"+
  3667. # " outname: Name of the new geometry object."
  3668. # },
  3669. # 'subtract_rect': {
  3670. # 'fcn': subtract_rectangle,
  3671. # 'help': 'Subtract rectange from the given Geometry object.\n' +
  3672. # '> subtract_rect <name> <botleft_x> <botleft_y> <topright_x> <topright_y>\n' +
  3673. # ' name: Name of the geometry object, which will be subtracted.\n' +
  3674. # ' botleft_x, botleft_y: Coordinates of the bottom left corner.\n' +
  3675. # ' topright_x, topright_y Coordinates of the top right corner.'
  3676. # },
  3677. # --- Migrated to new architecture ---
  3678. # 'add_rect': {
  3679. # 'fcn': add_rectangle,
  3680. # 'help': 'Creates a rectange in the given Geometry object.\n' +
  3681. # '> add_rect <name> <botleft_x> <botleft_y> <topright_x> <topright_y>\n' +
  3682. # ' name: Name of the geometry object to which to append the rectangle.\n' +
  3683. # ' botleft_x, botleft_y: Coordinates of the bottom left corner.\n' +
  3684. # ' topright_x, topright_y Coordinates of the top right corner.'
  3685. # },
  3686. # --- Migrated to new architecture ---
  3687. # 'add_circle': {
  3688. # 'fcn': add_circle,
  3689. # 'help': 'Creates a circle in the given Geometry object.\n' +
  3690. # '> add_circle <name> <center_x> <center_y> <radius>\n' +
  3691. # ' name: Name of the geometry object to which to append the circle.\n' +
  3692. # ' center_x, center_y: Coordinates of the center of the circle.\n' +
  3693. # ' radius: Radius of the circle.'
  3694. # },
  3695. 'make_docs': {
  3696. 'fcn': make_docs,
  3697. 'help': 'Prints command rererence in reStructuredText format.'
  3698. },
  3699. # 'follow': {
  3700. # 'fcn': follow,
  3701. # 'help': 'Creates a geometry object following gerber paths.\n' +
  3702. # '> follow <name> [-outname <oname>]\n' +
  3703. # ' name: Name of the gerber object.\n' +
  3704. # ' outname: Name of the output geometry object.'
  3705. # },
  3706. # 'get_sys': {
  3707. # 'fcn': get_sys,
  3708. # 'help': 'Get the value of a system parameter (FlatCAM constant)\n' +
  3709. # '> get_sys <sysparam>\n' +
  3710. # ' sysparam: Name of the parameter.'
  3711. # },
  3712. # --- Migrated to new architecture ---
  3713. # 'set_sys': {
  3714. # 'fcn': set_sys,
  3715. # 'help': 'Set the value of a system parameter (FlatCAM constant)\n' +
  3716. # '> set_sys <sysparam> <paramvalue>\n' +
  3717. # ' sysparam: Name of the parameter.\n' +
  3718. # ' paramvalue: Value to set.'
  3719. # }
  3720. }
  3721. # Import/overwrite tcl commands as objects of TclCommand descendants
  3722. # This modifies the variable 'commands'.
  3723. tclCommands.register_all_commands(self, commands)
  3724. # Add commands to the tcl interpreter
  3725. for cmd in commands:
  3726. self.tcl.createcommand(cmd, commands[cmd]['fcn'])
  3727. # Make the tcl puts function return instead of print to stdout
  3728. self.tcl.eval('''
  3729. rename puts original_puts
  3730. proc puts {args} {
  3731. if {[llength $args] == 1} {
  3732. return "[lindex $args 0]"
  3733. } else {
  3734. eval original_puts $args
  3735. }
  3736. }
  3737. ''')
  3738. def setup_recent_items(self):
  3739. self.log.debug("setup_recent_items()")
  3740. # TODO: Move this to constructor
  3741. icons = {
  3742. "gerber": "share/flatcam_icon16.png",
  3743. "excellon": "share/drill16.png",
  3744. "cncjob": "share/cnc16.png",
  3745. "project": "share/project16.png",
  3746. "svg": "share/geometry16.png"
  3747. }
  3748. openers = {
  3749. 'gerber': lambda fname: self.worker_task.emit({'fcn': self.open_gerber, 'params': [fname]}),
  3750. 'excellon': lambda fname: self.worker_task.emit({'fcn': self.open_excellon, 'params': [fname]}),
  3751. 'cncjob': lambda fname: self.worker_task.emit({'fcn': self.open_gcode, 'params': [fname]}),
  3752. 'project': self.open_project,
  3753. 'svg': self.import_svg
  3754. }
  3755. # Open file
  3756. try:
  3757. f = open(self.data_path + '/recent.json')
  3758. except IOError:
  3759. App.log.error("Failed to load recent item list.")
  3760. self.inform.emit("[error] Failed to load recent item list.")
  3761. return
  3762. try:
  3763. self.recent = json.load(f)
  3764. except json.scanner.JSONDecodeError:
  3765. App.log.error("Failed to parse recent item list.")
  3766. self.inform.emit("[error] Failed to parse recent item list.")
  3767. f.close()
  3768. return
  3769. f.close()
  3770. # Closure needed to create callbacks in a loop.
  3771. # Otherwise late binding occurs.
  3772. def make_callback(func, fname):
  3773. def opener():
  3774. func(fname)
  3775. return opener
  3776. # Reset menu
  3777. self.ui.recent.clear()
  3778. # Create menu items
  3779. for recent in self.recent:
  3780. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  3781. try:
  3782. action = QtGui.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  3783. # Attach callback
  3784. o = make_callback(openers[recent["kind"]], recent['filename'])
  3785. action.triggered.connect(o)
  3786. self.ui.recent.addAction(action)
  3787. except KeyError:
  3788. App.log.error("Unsupported file type: %s" % recent["kind"])
  3789. # self.builder.get_object('open_recent').set_submenu(recent_menu)
  3790. # self.ui.menufilerecent.set_submenu(recent_menu)
  3791. # recent_menu.show_all()
  3792. # self.ui.recent.show()
  3793. def setup_component_editor(self):
  3794. label = QtGui.QLabel("Choose an item from Project")
  3795. label.setAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
  3796. self.ui.selected_scroll_area.setWidget(label)
  3797. def setup_obj_classes(self):
  3798. """
  3799. Sets up application specifics on the FlatCAMObj class.
  3800. :return: None
  3801. """
  3802. FlatCAMObj.app = self
  3803. FCProcess.app = self
  3804. FCProcessContainer.app = self
  3805. def version_check(self):
  3806. """
  3807. Checks for the latest version of the program. Alerts the
  3808. user if theirs is outdated. This method is meant to be run
  3809. in a separate thread.
  3810. :return: None
  3811. """
  3812. self.log.debug("version_check()")
  3813. full_url = App.version_url + \
  3814. "?s=" + str(self.defaults['serial']) + \
  3815. "&v=" + str(self.version) + \
  3816. "&os=" + str(self.os) + \
  3817. "&" + urllib.parse.urlencode(self.defaults["stats"])
  3818. App.log.debug("Checking for updates @ %s" % full_url)
  3819. ### Get the data
  3820. try:
  3821. f = urllib.request.urlopen(full_url)
  3822. except:
  3823. # App.log.warning("Failed checking for latest version. Could not connect.")
  3824. self.log.warning("Failed checking for latest version. Could not connect.")
  3825. self.inform.emit("[warning] Failed checking for latest version. Could not connect.")
  3826. return
  3827. try:
  3828. data = json.load(f)
  3829. except Exception as e:
  3830. App.log.error("Could not parse information about latest version.")
  3831. self.inform.emit("[error] Could not parse information about latest version.")
  3832. App.log.debug("json.load(): %s" % str(e))
  3833. f.close()
  3834. return
  3835. f.close()
  3836. ### Latest version?
  3837. if self.version >= data["version"]:
  3838. App.log.debug("FlatCAM is up to date!")
  3839. self.inform.emit("[success] FlatCAM is up to date!")
  3840. return
  3841. App.log.debug("Newer version available.")
  3842. self.message.emit(
  3843. "Newer Version Available",
  3844. str("There is a newer version of FlatCAM " +
  3845. "available for download:<br><br>" +
  3846. "<B>" + data["name"] + "</b><br>" +
  3847. data["message"].replace("\n", "<br>")),
  3848. "info"
  3849. )
  3850. def enable_all_plots(self, *args):
  3851. self.plotcanvas.clear()
  3852. def worker_task(app_obj):
  3853. percentage = 0.1
  3854. try:
  3855. delta = 0.9 / len(self.collection.get_list())
  3856. except ZeroDivisionError:
  3857. self.progress.emit(0)
  3858. return
  3859. for obj in self.collection.get_list():
  3860. obj.options['plot'] = True
  3861. obj.plot()
  3862. percentage += delta
  3863. self.progress.emit(int(percentage*100))
  3864. self.progress.emit(0)
  3865. self.plots_updated.emit()
  3866. # Send to worker
  3867. # self.worker.add_task(worker_task, [self])
  3868. self.worker_task.emit({'fcn': worker_task, 'params': [self]})
  3869. def save_project(self, filename):
  3870. """
  3871. Saves the current project to the specified file.
  3872. :param filename: Name of the file in which to save.
  3873. :type filename: str
  3874. :return: None
  3875. """
  3876. self.log.debug("save_project()")
  3877. ## Capture the latest changes
  3878. # Current object
  3879. try:
  3880. self.collection.get_active().read_form()
  3881. except:
  3882. self.log.debug("[warning] There was no active object")
  3883. pass
  3884. # Project options
  3885. self.options_read_form()
  3886. # Serialize the whole project
  3887. d = {"objs": [obj.to_dict() for obj in self.collection.get_list()],
  3888. "options": self.options,
  3889. "version": self.version}
  3890. # Open file
  3891. try:
  3892. f = open(filename, 'w')
  3893. except IOError:
  3894. App.log.error("[error] Failed to open file for saving: %s", filename)
  3895. return
  3896. # Write
  3897. json.dump(d, f, default=to_dict, indent=2, sort_keys=True)
  3898. # try:
  3899. # json.dump(d, f, default=to_dict)
  3900. # except Exception, e:
  3901. # print str(e)
  3902. # App.log.error("[error] File open but failed to write: %s", filename)
  3903. # f.close()
  3904. # return
  3905. f.close()
  3906. self.inform.emit("Project saved to: %s" % filename)
  3907. # def main():
  3908. #
  3909. # app = QtGui.QApplication(sys.argv)
  3910. # fc = App()
  3911. # sys.exit(app.exec_())
  3912. #
  3913. #
  3914. # if __name__ == '__main__':
  3915. # main()